Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

scopedSettings.ts

390 lines14.8 KB

1import {
2 ClientSettingsSchema,
3 type ClientSettingsPatch,
4 type EnvironmentId,
5 PROJECT_SCOPED_SERVER_SETTING_KEYS,
6 type ProjectId,
7 type ProjectScopedServerSettingKey,
8 type ProjectSettingsOverrides,
9 ServerSettings,
10 type ServerSettingsPatch,
11} from "@t3tools/contracts";
12import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
13import {
14 clearProjectSettingsOverrides,
15 resolveProjectSettings,
16 resolveWorktreeCleanup,
17 type ProjectSettingSource,
18} from "@t3tools/shared/projectSettings";
19import * as Equal from "effect/Equal";
20​
21import type { ResolvedSettingsScope } from "./settingsScope";
22​
23export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
24​
25interface ScopedSettingsEnvironment {
26 readonly environmentId: EnvironmentId;
27 readonly label: string;
28 readonly connection: { readonly phase: EnvironmentConnectionPhase };
29 readonly serverConfig: {
30 readonly settings: ServerSettings;
31 readonly environment?: {
32 readonly capabilities: { readonly projectSettingsOverrides?: boolean | undefined };
33 };
34 } | null;
36​
37const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
38const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
39const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
40​
41export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
42 return PROJECT_SCOPED_KEYS.has(key);
44​
45function isPlainObject(value: unknown): value is Record<string, unknown> {
46 return typeof value === "object" && value !== null && !Array.isArray(value);
48​
49/** The representative supplies display values, never the set of write targets. */
50export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
51 scope: ResolvedSettingsScope,
52 available: readonly T[],
53 primaryEnvironmentId: EnvironmentId | null,
54) {
55 const selectedIds = new Set(scope.environmentIds);
56 const environments = available.filter((environment) =>
57 selectedIds.has(environment.environmentId),
58 );
59 const connectedEnvironments = environments.filter(
60 (environment) =>
61 environment.connection.phase === "connected" && environment.serverConfig !== null,
62 );
63 const environment =
64 connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
65 connectedEnvironments[0] ??
66 null;
67 return { environments, connectedEnvironments, environment };
69​
70/**
71 * One (environment, project) pair the scope writes to, with that project's
72 * effective settings. Environment scopes have no member and read the
73 * environment settings directly.
74 */
75export interface ScopedSettingsTarget {
76 readonly environmentId: EnvironmentId;
77 /** The environment's label; a project is the same project on every environment. */
78 readonly label: string;
79 readonly projectId: ProjectId | null;
80 readonly settings: ServerSettings;
81 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
83​
84/** Effective settings per connected target: members at project scope, environments otherwise. */
85export function resolveScopedSettingsTargets(
86 scope: ResolvedSettingsScope,
87 connectedEnvironments: readonly ScopedSettingsEnvironment[],
88): readonly ScopedSettingsTarget[] {
89 const byId = new Map(
90 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
91 );
92 if (scope.kind === "project" || scope.kind === "checkout") {
93 return scope.members.flatMap((member) => {
94 const environment = byId.get(member.environmentId);
95 if (!environment?.serverConfig) return [];
96 const resolved = resolveProjectSettings(environment.serverConfig.settings, member.id);
97 return [
98 {
99 environmentId: member.environmentId,
100 label: environment.label,
101 projectId: member.id,
102 settings: resolved.settings,
103 sources: resolved.sources,
104 },
105 ];
106 });
107 }
108 return connectedEnvironments.flatMap((environment) =>
109 environment.serverConfig
110 ? [
111 {
112 environmentId: environment.environmentId,
113 label: environment.label,
114 projectId: null,
115 settings: environment.serverConfig.settings,
116 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
117 },
118 ]
119 : [],
120 );
122​
123export function scopedSettingsAreMixed(
124 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
125 keys: readonly (keyof ServerSettings)[],
126): boolean {
127 const first = targets[0];
128 return (
129 first !== undefined &&
130 targets.some((candidate) =>
131 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
132 )
133 );
135​
136export type ScopedSettingSource = ProjectSettingSource | "mixed";
137​
138/** Whether the keys are overridden on every target, inherited on every target, or split. */
139export function scopedSettingsSource(
140 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
141 keys: readonly (keyof ServerSettings)[],
142): ScopedSettingSource {
143 const scoped = keys.filter(isProjectScopedSettingKey);
144 if (scoped.length === 0 || targets.length === 0) return "environment";
145 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
146 return sources.size > 1 ? "mixed" : sources.has("project") ? "project" : "environment";
148​
149interface ScopedServerWrite {
150 readonly environmentId: EnvironmentId;
151 readonly label: string;
152 readonly patch: ServerSettingsPatch;
154​
155function projectOverrideWrites(
156 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
157 environments: readonly ScopedSettingsEnvironment[],
158 update: (
159 current: ProjectSettingsOverrides,
160 settings: ServerSettings,
161 projectId: ProjectId,
162 ) => ProjectSettingsOverrides | null,
163): ScopedServerWrite[] {
164 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
165 const writes = new Map<EnvironmentId, ScopedServerWrite>();
166 for (const member of scope.members) {
167 const environment = byId.get(member.environmentId);
168 if (
169 !environment?.serverConfig ||
170 environment.connection.phase !== "connected" ||
171 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
172 ) {
173 continue;
174 }
175 const settings = environment.serverConfig.settings;
176 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
177 const existing = writes.get(member.environmentId);
178 writes.set(member.environmentId, {
179 environmentId: member.environmentId,
180 label: environment.label,
181 patch: {
182 projectSettingsOverrides: {
183 ...existing?.patch.projectSettingsOverrides,
184 [member.id]: entry,
185 },
186 },
187 });
188 }
189 return [...writes.values()];
191​
192/**
193 * Environment scopes write the patch to every connected environment; project
194 * and checkout scopes write the scopable keys into each member's override
195 * entry on its environment. Client keys always persist locally.
196 */
197export function planScopedSettingsPatch(
198 scope: ResolvedSettingsScope,
199 environments: readonly ScopedSettingsEnvironment[],
200 patch: ScopedSettingsPatch,
201) {
202 const clientPatch = Object.fromEntries(
203 Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key)),
204 ) as ClientSettingsPatch;
205 const serverPatch = Object.fromEntries(
206 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
207 ) as ServerSettingsPatch;
208 const serverKeys = Object.keys(serverPatch);
209 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
210 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
211 const unscopableKeys = isProjectScope
212 ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
213 : [];
214 const serverWrites: ScopedServerWrite[] =
215 serverKeys.length === 0
216 ? []
217 : isProjectScope
218 ? unscopableKeys.length > 0
219 ? []
220 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
221 // Object-valued keys arrive as partial patches (the writing style
222 // rows send one field); an override entry stores the whole value,
223 // so complete the patch from the target's effective value.
224 const effective = resolveProjectSettings(settings, projectId).settings;
225 const next: Record<string, unknown> = { ...current };
226 for (const [key, value] of Object.entries(serverPatch)) {
227 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
228 next[key] = {
229 mode: "custom",
230 rules: {
231 ...resolveWorktreeCleanup(settings, projectId),
232 ...serverPatch.worktreeCleanup.rules,
233 },
234 };
235 continue;
236 }
237 const base = effective[key as keyof ServerSettings];
238 next[key] =
239 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
240 }
241 return next as ProjectSettingsOverrides;
242 })
243 : scope.kind === "all" || scope.kind === "environment"
244 ? connectedEnvironments.map((environment) => ({
245 environmentId: environment.environmentId,
246 label: environment.label,
247 patch:
248 environment.serverConfig?.settings.worktreeCleanup != null &&
249 serverPatch.storageCleanup &&
250 Object.keys(serverPatch.storageCleanup).some((key) => key.startsWith("worktree"))
251 ? {
252 ...serverPatch,
253 worktreeCleanup: {
254 mode: "custom",
255 rules: {
256 ...resolveWorktreeCleanup(environment.serverConfig.settings, null),
257 ...Object.fromEntries(
258 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
259 key.startsWith("worktree"),
260 ),
261 ),
262 },
263 },
264 }
265 : serverPatch,
266 }))
267 : [];
268 const hasClientWrite = Object.keys(clientPatch).length > 0;
269 const hasWrite = hasClientWrite || serverWrites.length > 0;
270 const unavailableReason =
271 hasWrite || Object.keys(patch).length === 0
272 ? null
273 : scope.kind === "unavailable"
274 ? scope.message
275 : unscopableKeys.length > 0
276 ? "This setting is environment-wide and cannot be overridden by a project."
277 : isProjectScope
278 ? "Connect the selected checkouts, or update their environments, to save a project override."
279 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
280 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
282​
283/** Remove the keys' project overrides so each member inherits its environment value again. */
284export function planScopedSettingsClear(
285 scope: ResolvedSettingsScope,
286 environments: readonly ScopedSettingsEnvironment[],
287 keys: readonly ProjectScopedServerSettingKey[],
288) {
289 const serverWrites =
290 scope.kind === "project" || scope.kind === "checkout"
291 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
292 clearProjectSettingsOverrides(settings, projectId, keys),
293 )
294 : [];
295 return {
296 clientPatch: {} as ClientSettingsPatch,
297 hasClientWrite: false,
298 serverWrites,
299 unavailableReason:
300 serverWrites.length > 0
301 ? null
302 : "Connect the selected checkouts, or update their environments, to reset this override.",
303 };
305​
306export interface ProjectOverrideEntry {
307 readonly environmentId: EnvironmentId;
308 readonly projectId: ProjectId;
310​
311/**
312 * The projects on the selected environments that override `keys`. An
313 * environment edit leaves these untouched, so the row can name them and
314 * offer to clear them.
315 */
316export function listProjectOverrides(
317 environments: readonly ScopedSettingsEnvironment[],
318 keys: readonly (keyof ServerSettings)[],
319): readonly ProjectOverrideEntry[] {
320 const scoped = keys.filter(isProjectScopedSettingKey);
321 if (scoped.length === 0) return [];
322 return environments.flatMap((environment) => {
323 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
324 if (!overrides) return [];
325 return Object.entries(overrides).flatMap(([projectId, entry]) =>
326 scoped.some((key) => Object.hasOwn(entry, key))
327 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
328 : [],
329 );
330 });
332​
333/** Drop `keys` from the named project entries so they follow the environment again. */
334export function planProjectOverridesClear(
335 environments: readonly ScopedSettingsEnvironment[],
336 entries: readonly ProjectOverrideEntry[],
337 keys: readonly ProjectScopedServerSettingKey[],
338) {
339 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
340 const writes = new Map<EnvironmentId, ScopedServerWrite>();
341 for (const { environmentId, projectId } of entries) {
342 const environment = byId.get(environmentId);
343 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
344 const settings = environment.serverConfig.settings;
345 const existing = writes.get(environmentId);
346 writes.set(environmentId, {
347 environmentId,
348 label: environment.label,
349 patch: {
350 projectSettingsOverrides: {
351 ...existing?.patch.projectSettingsOverrides,
352 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
353 },
354 },
355 });
356 }
357 const serverWrites = [...writes.values()];
358 return {
359 clientPatch: {} as ClientSettingsPatch,
360 hasClientWrite: false,
361 serverWrites,
362 unavailableReason:
363 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
364 };
366​
367/** Wait for every target so a failed environment does not hide successful or later writes. */
368export async function persistScopedSettingsPatch(
369 plan: ReturnType<typeof planScopedSettingsPatch>,
370 persistServer: (input: {
371 environmentId: EnvironmentId;
372 input: { patch: ServerSettingsPatch };
373 }) => Promise<{ readonly _tag: "Success" | "Failure" }>,
374 persistClient: (patch: ClientSettingsPatch) => void,
375) {
376 if (plan.hasClientWrite) persistClient(plan.clientPatch);
377 const results = await Promise.allSettled(
378 plan.serverWrites.map(({ environmentId, patch }) =>
379 persistServer({ environmentId, input: { patch } }),
380 ),
381 );
382 const failedEnvironments = plan.serverWrites.filter((_, index) => {
383 const result = results[index];
384 return result?.status !== "fulfilled" || result.value._tag === "Failure";
385 });
386 return {
387 failedEnvironments,
388 savedEnvironmentCount: plan.serverWrites.length - failedEnvironments.length,
389 };