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

scopedSettings.ts

414 lines15.8 KB

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