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

theme.ts

587 lines23.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - publish commits and rollbacks
2// move exact directory entries with rename, which the FileSystem service does
3// not expose atomically.
4/**
5 * `t3 theme` - inspect and set the environment's theme. Connected web and
6 * desktop clients switch when it is set; mobile keeps its own appearance
7 * settings. Each client applies one set once, so a theme the user picks in
8 * Settings afterwards sticks until the next `t3 theme set`.
9 *
10 * Writes `defaultTheme` (and `defaultThemeSetAt`, so a re-set of the same
11 * value still acts) into the environment's `settings.json`. A running server
12 * watches that file and pushes the change, so this works before the first
13 * launch and on a live server alike.
14 *
15 * The edit is deliberately a minimal one on the parsed JSON object rather than
16 * a schema round-trip. Settings files outlive the build that reads them, and a
17 * provisioning command must not drop keys this version does not recognise.
18 */
19import * as NodeFS from "node:fs";
20​
21import {
22 EnvironmentThemeFile,
23 EnvironmentThemeId,
24 environmentThemeFileHasColors,
25} from "@t3tools/contracts";
26import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
27import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
28import * as Config from "effect/Config";
29import * as Console from "effect/Console";
30import * as DateTime from "effect/DateTime";
31import * as Effect from "effect/Effect";
32import * as FileSystem from "effect/FileSystem";
33import * as Option from "effect/Option";
34import * as Path from "effect/Path";
35import * as Schema from "effect/Schema";
36import { Argument, Command, Flag } from "effect/unstable/cli";
37​
38import { writeFileStringAtomically } from "../atomicWrite.ts";
39import * as ServerConfig from "../config.ts";
40import {
41 MAX_THEME_FILE_BYTES,
42 readPublishedThemes,
43 readThemeFileGuarded,
44} from "../environmentTheme.ts";
45import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
46import { baseDirFlag } from "./config.ts";
47​
48/** Settings files outlive the build that reads them, so the object is carried
49 * as-is and only the theme keys are touched. */
50const SparseSettings = Schema.Record(Schema.String, Schema.Unknown);
51const decodeSettingsJson = Schema.decodeUnknownEffect(fromLenientJson(SparseSettings));
52const encodeSettingsJson = Schema.encodeEffect(fromJsonStringPretty(SparseSettings));
53const decodeThemeFileJsonExit = Schema.decodeUnknownExit(
54 Schema.fromJsonString(EnvironmentThemeFile),
55);
56const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
57​
58export class ThemeSettingsUnreadableError extends Schema.TaggedError<ThemeSettingsUnreadableError>()(
59 "ThemeSettingsUnreadableError",
60 { settingsPath: Schema.String, cause: Schema.Defect() },
61) {
62 override get message(): string {
63 return `Could not read ${this.settingsPath}. Fix its permissions, then run this again.`;
64 }
66​
67export class ThemeSettingsMalformedError extends Schema.TaggedError<ThemeSettingsMalformedError>()(
68 "ThemeSettingsMalformedError",
69 { settingsPath: Schema.String, cause: Schema.Defect() },
70) {
71 override get message(): string {
72 return `${this.settingsPath} is not a JSON object. Fix or remove it, then run this again.`;
73 }
75​
76export class ThemeSettingsBusyError extends Schema.TaggedError<ThemeSettingsBusyError>()(
77 "ThemeSettingsBusyError",
78 { settingsPath: Schema.String, attempts: Schema.Number },
79) {
80 override get message(): string {
81 return `${this.settingsPath} kept changing while writing (gave up after ${this.attempts} attempts). Try again.`;
82 }
84​
85export class ThemeSettingsWriteError extends Schema.TaggedError<ThemeSettingsWriteError>()(
86 "ThemeSettingsWriteError",
87 { settingsPath: Schema.String, cause: Schema.Defect() },
88) {
89 override get message(): string {
90 return `Could not write ${this.settingsPath}.`;
91 }
93​
94export class ThemeFileUnreadableError extends Schema.TaggedError<ThemeFileUnreadableError>()(
95 "ThemeFileUnreadableError",
96 // Optional: a path that never existed has no underlying failure to carry,
97 // and a manufactured string there would only look like a real one.
98 { filePath: Schema.String, cause: Schema.optional(Schema.Defect()) },
99) {
100 override get message(): string {
101 return `Could not read ${this.filePath}.`;
102 }
104​
105export class ThemeFileInvalidError extends Schema.TaggedError<ThemeFileInvalidError>()(
106 "ThemeFileInvalidError",
107 { filePath: Schema.String, cause: Schema.Defect() },
108) {
109 override get message(): string {
110 return `${this.filePath} is not a valid theme file. Use a theme exported from T3 Code, or a seeded file with name, appearance, canvas, and accent.`;
111 }
113​
114export class ThemeFileTooLargeError extends Schema.TaggedError<ThemeFileTooLargeError>()(
115 "ThemeFileTooLargeError",
116 { filePath: Schema.String, limit: Schema.Number },
117) {
118 override get message(): string {
119 return `${this.filePath} is larger than ${this.limit} bytes, which is more than a theme can publish.`;
120 }
122​
123export class ThemeFileColorlessError extends Schema.TaggedError<ThemeFileColorlessError>()(
124 "ThemeFileColorlessError",
125 { filePath: Schema.String },
126) {
127 override get message(): string {
128 return `${this.filePath} has no colors to publish.`;
129 }
131​
132export class ThemePublishError extends Schema.TaggedError<ThemePublishError>()(
133 "ThemePublishError",
134 { themesDir: Schema.String, cause: Schema.Defect() },
135) {
136 override get message(): string {
137 return `Could not publish the theme into ${this.themesDir}.`;
138 }
140​
141const INVALID_THEME_ID_REASON =
142 "is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
143​
144export class ThemeIdUnknownError extends Schema.TaggedError<ThemeIdUnknownError>()(
145 "ThemeIdUnknownError",
146 { themeId: Schema.String, known: Schema.Array(Schema.String) },
147) {
148 override get message(): string {
149 return `No theme named "${this.themeId}". Available: ${this.known.join(", ")}. Publish one by passing a theme file instead of an id.`;
150 }
152​
153export class ThemeIdInvalidError extends Schema.TaggedError<ThemeIdInvalidError>()(
154 "ThemeIdInvalidError",
155 { themeId: Schema.String },
156) {
157 override get message(): string {
158 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}.`;
159 }
161​
162/** A filename that cannot be a theme id, where --id is the way out. */
163export class ThemeFileIdInvalidError extends Schema.TaggedError<ThemeFileIdInvalidError>()(
164 "ThemeFileIdInvalidError",
165 { themeId: Schema.String, filePath: Schema.String },
166) {
167 override get message(): string {
168 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}. Pass one with --id.`;
169 }
171​
172export class ThemeTargetMissingError extends Schema.TaggedError<ThemeTargetMissingError>()(
173 "ThemeTargetMissingError",
174 {},
175) {
176 override get message(): string {
177 return "Provide a theme id or file, or run `t3 theme clear` to remove the theme.";
178 }
180​
181const envT3Home = Config.string("T3CODE_HOME").pipe(Config.option);
182​
183const resolveThemePaths = Effect.fn(function* (explicitBaseDir: Option.Option<string>) {
184 // Same precedence as the rest of the CLI: --base-dir, then T3CODE_HOME,
185 // then the default home. A provisioning script exporting T3CODE_HOME must
186 // not have this one command silently target the default install.
187 const envHome = Option.filter(yield* envT3Home, (value) => value.trim().length > 0);
188 const configuredBaseDir = Option.orElse(explicitBaseDir, () => envHome);
189 const baseDir = yield* resolveBaseDir(Option.getOrUndefined(configuredBaseDir));
190 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {
191 baseDirIsExplicit: Option.isSome(configuredBaseDir),
192 });
193 return {
194 settingsPath: derivedPaths.settingsPath,
195 themesDir: derivedPaths.environmentThemesDir,
196 };
197});
198​
199/**
200 * Reads the sparse settings object, treating only a genuinely absent file as
201 * empty. A permission or I/O error must propagate: reading it as "no settings"
202 * would have the caller write a fresh sparse file over settings it never saw.
203 */
204const readSettingsObject = Effect.fn(function* (settingsPath: string) {
205 const fs = yield* FileSystem.FileSystem;
206 const exists = yield* fs
207 .exists(settingsPath)
208 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
209 if (!exists) return { raw: "", settings: {} };
210​
211 const raw = yield* fs
212 .readFileString(settingsPath)
213 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
214 if (raw.trim().length === 0) return { raw, settings: {} };
215​
216 const settings = yield* decodeSettingsJson(raw).pipe(
217 Effect.mapError((cause) => new ThemeSettingsMalformedError({ settingsPath, cause })),
218 );
219 return { raw, settings };
220});
221​
222/**
223 * A running server owns this file too, and its write path is an in-process
224 * semaphore that cannot serialize against another process. So the document is
225 * re-read immediately before the rename and the whole edit is retried when it
226 * moved underneath us, which is what turns "last writer wins" into "last
227 * writer merges", and an edit that keeps losing the race fails loudly rather
228 * than overwriting. A write landing inside the remaining rename window is
229 * still possible; the server's own watcher reconciles the file either way.
230 */
231const CONCURRENT_WRITE_ATTEMPTS = 5;
232​
233const writeDefaultTheme = Effect.fn(function* (input: {
234 readonly settingsPath: string;
235 readonly themeId: string;
236}) {
237 const fs = yield* FileSystem.FileSystem;
238​
239 for (let attempt = 1; ; attempt++) {
240 const { raw, settings } = yield* readSettingsObject(input.settingsPath);
241 const setAt = DateTime.formatIso(yield* DateTime.now);
242 const next =
243 input.themeId.length > 0
244 ? // The timestamp is the set-generation: it lets clients apply a re-set
245 // of the same value they already applied once.
246 { ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }
247 : // Clearing removes the keys rather than storing empty strings, so the
248 // file reads the same as one that never set a theme.
249 Object.fromEntries(
250 Object.entries(settings).filter(
251 ([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",
252 ),
253 );
254​
255 const contents = yield* encodeSettingsJson(next);
256 const current = yield* fs
257 .readFileString(input.settingsPath)
258 .pipe(Effect.orElseSucceed(() => ""));
259 if (current !== raw) {
260 // Falling through here would overwrite whatever landed in between, which
261 // is exactly the loss this loop exists to prevent.
262 if (attempt >= CONCURRENT_WRITE_ATTEMPTS) {
263 return yield* Effect.fail(
264 new ThemeSettingsBusyError({
265 settingsPath: input.settingsPath,
266 attempts: CONCURRENT_WRITE_ATTEMPTS,
267 }),
268 );
269 }
270 continue;
271 }
272​
273 yield* writeFileStringAtomically({
274 filePath: input.settingsPath,
275 contents: `${contents}\n`,
276 }).pipe(
277 Effect.mapError(
278 (cause) => new ThemeSettingsWriteError({ settingsPath: input.settingsPath, cause }),
279 ),
280 );
281 return;
282 }
283});
284​
285/** Publishes a theme file into the environment's themes directory and returns
286 * the id it published under. */
287const publishThemeFile = Effect.fn(function* (input: {
288 readonly themesDir: string;
289 readonly filePath: string;
290 readonly explicitId: Option.Option<string>;
291}) {
292 const fs = yield* FileSystem.FileSystem;
293 const path = yield* Path.Path;
294 // A preflight for error quality only: it tells a FIFO from an oversized
295 // file. Enforcement happens at the guarded read below.
296 const info = yield* fs
297 .stat(input.filePath)
298 .pipe(
299 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
300 );
301 if (info.type !== "File") {
302 return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));
303 }
304 if (Number(info.size) > MAX_THEME_FILE_BYTES) {
305 return yield* Effect.fail(
306 new ThemeFileTooLargeError({ filePath: input.filePath, limit: MAX_THEME_FILE_BYTES }),
307 );
308 }
309​
310 // An explicit source path is the user's own input, and a symlink there is a
311 // normal way to point at a theme (desktop hooks symlink the current
312 // palette), so it is resolved before the guarded read. The read still goes
313 // through one opened handle whose type and size checks bind to the file
314 // actually read, so a FIFO cannot hang the command and an oversized target
315 // is refused.
316 const resolvedSource = yield* fs
317 .realPath(input.filePath)
318 .pipe(
319 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
320 );
321 const raw = readThemeFileGuarded(resolvedSource, MAX_THEME_FILE_BYTES);
322 if (raw === null) {
323 return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));
324 }
325​
326 const decoded = decodeThemeFileJsonExit(raw);
327 if (decoded._tag === "Failure") {
328 return yield* Effect.fail(
329 new ThemeFileInvalidError({ filePath: input.filePath, cause: decoded.cause }),
330 );
331 }
332 if (!environmentThemeFileHasColors(decoded.value)) {
333 return yield* Effect.fail(new ThemeFileColorlessError({ filePath: input.filePath }));
334 }
335​
336 const fileBasename = path.basename(input.filePath, ".json");
337 const themeId = Option.getOrElse(input.explicitId, () => fileBasename);
338 // The same rules the watcher applies when it reads the directory back, so a
339 // publish cannot report success for a file that will then be skipped.
340 if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {
341 return yield* Effect.fail(new ThemeFileIdInvalidError({ themeId, filePath: input.filePath }));
342 }
343​
344 const destinationPath = path.join(input.themesDir, `${themeId}.json`);
345 // Neither ends in `.json`, so the watcher never mistakes them for themes.
346 // Both names carry the pid, so concurrent publishers of one id cannot
347 // unlink or restore over each other's staging and rollback copies.
348 const backupPath = `${destinationPath}.rollback-${process.pid}`;
349 const stagingPath = `${destinationPath}.staging-${process.pid}`;
350 yield* fs
351 .makeDirectory(input.themesDir, { recursive: true })
352 .pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));
353​
354 const publishFailure = (cause: unknown) =>
355 new ThemePublishError({ themesDir: input.themesDir, cause });
356​
357 // Staged in full before anything moves, so the commit below is two adjacent
358 // renames with no I/O between them. The staging entry is created O_EXCL
359 // after clearing any stale leftover, so a symlink or file already at that
360 // predictable name is never followed or written through. Written verbatim:
361 // appending so much as a newline could push a file at the size limit past
362 // it and have the watcher skip what was just accepted.
363 const stagedIno = yield* Effect.try({
364 try: () => {
365 try {
366 NodeFS.unlinkSync(stagingPath);
367 } catch {
368 // Nothing stale to clear.
369 }
370 const fd = NodeFS.openSync(
371 stagingPath,
372 NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
373 0o644,
374 );
375 try {
376 NodeFS.writeFileSync(fd, raw);
377 // Rename preserves the inode, so this identifies our published file
378 // at the destination for as long as it is actually ours.
379 return NodeFS.fstatSync(fd).ino;
380 } finally {
381 NodeFS.closeSync(fd);
382 }
383 },
384 catch: publishFailure,
385 });
386​
387 // Whatever occupies the destination -- a theme, a symlink, anything -- is
388 // moved aside in one atomic step rather than inspected and then replaced:
389 // there is no window between a check and the commit, and rollback restores
390 // that exact directory entry instead of a re-read of it. Only "nothing
391 // there" continues; any other rename failure aborts before the destination
392 // is touched.
393 const hadPrevious = yield* Effect.try({
394 try: () => {
395 try {
396 NodeFS.renameSync(destinationPath, backupPath);
397 return true;
398 } catch (error) {
399 if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
400 throw error;
401 }
402 },
403 catch: publishFailure,
404 });
405​
406 const revert = Effect.sync(() => {
407 try {
408 NodeFS.unlinkSync(stagingPath);
409 } catch {
410 // Usually already renamed away; a stray staging file is watcher-inert.
411 }
412 try {
413 // The destination is touched only while it is empty or still holds
414 // the exact file this process put there; a concurrent publisher's
415 // newer file wins, and this process's obsolete copy is discarded.
416 const destinationIno = (() => {
417 try {
418 return NodeFS.lstatSync(destinationPath).ino;
419 } catch {
420 return null;
421 }
422 })();
423 if (hadPrevious) {
424 if (destinationIno === null || destinationIno === stagedIno) {
425 NodeFS.renameSync(backupPath, destinationPath);
426 } else {
427 NodeFS.unlinkSync(backupPath);
428 }
429 } else if (destinationIno === stagedIno) {
430 NodeFS.unlinkSync(destinationPath);
431 }
432 } catch {
433 // Best effort; the failure that triggered the revert still surfaces.
434 }
435 });
436 const cleanup = Effect.sync(() => {
437 try {
438 if (hadPrevious) NodeFS.unlinkSync(backupPath);
439 } catch {
440 // A stray backup is inert: it is not `.json`, so nothing serves it.
441 }
442 });
443​
444 yield* Effect.try({
445 try: () => NodeFS.renameSync(stagingPath, destinationPath),
446 catch: publishFailure,
447 }).pipe(Effect.onError(() => revert));
448​
449 return { themeId, revert, cleanup };
450});
451​
452/**
453 * Ids a client can actually resolve: this build's built-ins plus what the
454 * machine publishes, read through the same function the watcher uses so a file
455 * it would skip can never be accepted here. The mobile default is absent on
456 * purpose -- web and desktop cannot resolve it and mobile does not follow this
457 * setting, so naming it would be the silent no-op this check exists to stop.
458 */
459const resolvableThemeIds = Effect.fn(function* (themesDir: string) {
460 const published = yield* readPublishedThemes(themesDir);
461 return [...BUILT_IN_THEME_IDS, ...published.map((theme) => theme.id)].toSorted();
462});
463​
464const themeSetCommand = Command.make("set", {
465 baseDir: baseDirFlag,
466 id: Flag.string("id").pipe(
467 Flag.withDescription("Theme id to publish a file under, instead of its filename."),
468 Flag.optional,
469 ),
470 theme: Argument.string("theme").pipe(
471 Argument.withDescription(
472 'A theme id (a built-in, or one this machine publishes — themes/nightfall.json is "nightfall"), or a path to a theme JSON file to publish and set in one step.',
473 ),
474 ),
475}).pipe(
476 Command.withDescription("Set the environment's theme; connected clients switch to it."),
477 Command.withHandler((flags) =>
478 Effect.gen(function* () {
479 const fs = yield* FileSystem.FileSystem;
480 const target = yield* expandHomePath(flags.theme.trim());
481 if (target.length === 0) {
482 return yield* Effect.fail(new ThemeTargetMissingError());
483 }
484 const paths = yield* resolveThemePaths(flags.baseDir);
485​
486 // An existing file publishes; anything path-shaped that does not exist
487 // is a mistake to surface, not an id to store; everything else must be
488 // a well-formed id, so a typo cannot be written as a theme no client
489 // will ever resolve.
490 // Path-shaped first, existence second. Deciding on existence alone would
491 // make `t3 theme set ocean` publish ./ocean whenever the cwd happens to
492 // hold a file by that name, instead of selecting the built-in.
493 const looksLikePath =
494 target.endsWith(".json") ||
495 target.includes("/") ||
496 target.includes("\\") ||
497 target.startsWith("~");
498 const targetIsFile =
499 looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));
500 let themeId: string;
501 let revertPublish: Effect.Effect<void> = Effect.void;
502 let cleanupPublish: Effect.Effect<void> = Effect.void;
503 if (targetIsFile) {
504 // Settings are preflighted before publishing, so a settings file the
505 // set step cannot read or parse fails the command before it mutates
506 // the themes directory.
507 yield* readSettingsObject(paths.settingsPath);
508 const published = yield* publishThemeFile({
509 themesDir: paths.themesDir,
510 filePath: target,
511 explicitId: flags.id,
512 });
513 themeId = published.themeId;
514 revertPublish = published.revert;
515 cleanupPublish = published.cleanup;
516 } else if (looksLikePath) {
517 return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: target }));
518 } else if (isEnvironmentThemeId(target)) {
519 const known = yield* resolvableThemeIds(paths.themesDir);
520 if (!known.includes(target)) {
521 return yield* Effect.fail(new ThemeIdUnknownError({ themeId: target, known }));
522 }
523 themeId = target;
524 } else {
525 return yield* Effect.fail(new ThemeIdInvalidError({ themeId: target }));
526 }
527​
528 // set means set: if the default cannot be written, the publish that
529 // rode along with it is undone rather than left as a side effect of a
530 // command that reported failure.
531 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId }).pipe(
532 Effect.onError(() => revertPublish),
533 );
534 yield* cleanupPublish;
535 yield* Console.log(
536 targetIsFile
537 ? `Published ${target} as "${themeId}" and set it as the environment theme.\n`
538 : `Environment theme set to "${themeId}" in ${paths.settingsPath}.\n`,
539 );
540 }),
541 ),
542);
543​
544const themeClearCommand = Command.make("clear", { baseDir: baseDirFlag }).pipe(
545 Command.withDescription("Remove the environment's theme; clients keep what they have."),
546 Command.withHandler((flags) =>
547 Effect.gen(function* () {
548 const paths = yield* resolveThemePaths(flags.baseDir);
549 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId: "" });
550 yield* Console.log(`Environment theme cleared in ${paths.settingsPath}.\n`);
551 }),
552 ),
553);
554​
555const themeShowCommand = Command.make("show", { baseDir: baseDirFlag }).pipe(
556 Command.withDescription("Show the environment's theme and its published themes."),
557 Command.withHandler((flags) =>
558 Effect.gen(function* () {
559 const paths = yield* resolveThemePaths(flags.baseDir);
560 const { settings } = yield* readSettingsObject(paths.settingsPath);
561 const defaultTheme =
562 typeof settings.defaultTheme === "string" && settings.defaultTheme.length > 0
563 ? settings.defaultTheme
564 : null;
565​
566 const published = (yield* readPublishedThemes(paths.themesDir))
567 .map((theme) => theme.id)
568 .toSorted();
569​
570 yield* Console.log(
571 defaultTheme === null
572 ? "Environment theme: not set.\n"
573 : `Environment theme: "${defaultTheme}".\n`,
574 );
575 yield* Console.log(
576 published.length === 0
577 ? `Published themes: none (publish into ${paths.themesDir}).\n`
578 : `Published themes: ${published.join(", ")}.\n`,
579 );
580 }),
581 ),
582);
583​
584export const themeCommand = Command.make("theme").pipe(
585 Command.withDescription("Inspect and set environment-wide theme defaults."),
586 Command.withSubcommands([themeSetCommand, themeClearCommand, themeShowCommand]),
587);