@ultimat3/cli 10.0.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ // The app's own error page, which only a process with a disk can find: `@ultimat3/http` renders the
2
+ // framework's and declares the seam, this file is the half that reads a file. Rails' `public/404.html`,
3
+ // one directory further in — `apps/web/site/` is already where an app's public files live, which is
4
+ // where `favicon.ico` is overridden too.
5
+
6
+ // why: Bun exposes no path-join primitive, and the source path is app-root-relative — the same
7
+ // necessity `favicon.ts` records for `FAVICON_SOURCE`.
8
+ import { join } from 'node:path';
9
+ import { renderErrorPage } from '@ultimat3/http';
10
+ import { currentLocale } from '@ultimat3/i18n';
11
+
12
+ /**
13
+ * One file per status, named by the status, and NO generic `error.html` beside it: a second rung
14
+ * would need a precedence rule, and a `{{status}}` slot would be a template language the framework
15
+ * does not otherwise have. An app that wants one page for three statuses writes three files.
16
+ */
17
+ export const ERROR_PAGE_DIR = 'apps/web/site/errors';
18
+
19
+ /** What `x verify`, a `fix:` and this reader all name — never spelled twice. */
20
+ export const errorPageSource = (status: number): string =>
21
+ `${ERROR_PAGE_DIR}/${String(status)}.html`;
22
+
23
+ /**
24
+ * What a static host serves for a path that matches no file. `404.html` at the export root is the
25
+ * convention S3, Cloudflare Pages, Netlify and nginx already look for, so the artifact needs no
26
+ * configuration to answer the way the served process does.
27
+ */
28
+ export const STATIC_ERROR_PAGE = '404.html';
29
+
30
+ /** A status a `Response` can carry. A number outside it never becomes a path. */
31
+ const isStatus = (status: number): boolean =>
32
+ Number.isInteger(status) && status >= 100 && status <= 599;
33
+
34
+ /**
35
+ * The app's page for one status, or `undefined`.
36
+ *
37
+ * Read per REQUEST, never cached at boot, for `favicon.ts`'s reason: `x dev` is a running process
38
+ * an author drops a file into, and a reader that captured "there was none" at startup would keep
39
+ * answering the framework's page until the server was restarted.
40
+ */
41
+ export async function errorPageOverride(root: string, status: number): Promise<string | undefined> {
42
+ if (!isStatus(status)) return undefined;
43
+ const file = Bun.file(join(root, errorPageSource(status)));
44
+ return (await file.exists()) ? file.text() : undefined;
45
+ }
46
+
47
+ /**
48
+ * `ServerHooks.errorPage`, bound to one app root. Installed by `startWeb` so `x dev` and the
49
+ * container cannot answer a browser differently — the rule `assetRoutes` already holds for
50
+ * `/favicon.ico`.
51
+ */
52
+ export const errorPageHook =
53
+ (root: string) =>
54
+ (status: number): Promise<string | undefined> =>
55
+ errorPageOverride(root, status);
56
+
57
+ /**
58
+ * The document that goes into a static export: the app's file if it has one, the framework's page
59
+ * otherwise. Its own function because the export has no process to ask, exactly as `faviconBytes`
60
+ * is — a second rule for which page a static build carries would be an artifact that disagrees
61
+ * with the server it was built from.
62
+ *
63
+ * No request id and no pathname: nothing about this file is per-request, and the renderer omits
64
+ * both rather than inventing them.
65
+ */
66
+ export async function errorPageDocument(root: string, status: number): Promise<string> {
67
+ const own = await errorPageOverride(root, status);
68
+ return (
69
+ own ??
70
+ renderErrorPage({
71
+ status,
72
+ // What the served 404 carries, so the artifact and the process name one code.
73
+ code: 'X_ROUTE_NOT_FOUND',
74
+ // The app's default, resolved after `loadApp` registered its catalogs — a build has no
75
+ // request to negotiate against.
76
+ locale: currentLocale(),
77
+ })
78
+ );
79
+ }
package/src/errors.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // that resolves it — the codes themselves, their titles and their registration are `./error-codes`,
3
3
  // so a package importing a class does not pull the table and vice versa.
4
4
  import { UltimateError } from '@ultimat3/core';
5
+ import { quoteArg } from './shell-quote';
5
6
 
6
7
  /** An unknown command or subcommand. Carries a suggestion so the retry is one keystroke away. */
7
8
  export class UnknownCommandError extends UltimateError {
@@ -47,6 +48,30 @@ export class MissingPositionalError extends UltimateError {
47
48
  }
48
49
  }
49
50
 
51
+ /**
52
+ * `x new /srv/apps/shop` — a PATH where a NAME goes.
53
+ *
54
+ * `names()` slugifies whatever it is given, so the separators became hyphens and the whole path
55
+ * turned into ONE directory inside the cwd: `x new /tmp/probe/vision` wrote `tmp-probe-vision`
56
+ * into the current directory and `git init`-ed it there. Nothing failed, and the app the caller
57
+ * asked for did not exist.
58
+ *
59
+ * `--dir` is the flag that takes a path, so the two are one flag apart and the fix is the
60
+ * invocation the caller meant — built from what they typed, never a placeholder.
61
+ */
62
+ export class AppNameIsPathError extends UltimateError {
63
+ constructor(input: { name: string; parent: string; base: string; invocation?: string }) {
64
+ // The invocation the caller typed, not the literal `x new`: the same command is the whole of
65
+ // `bunx create-ultimate`, which runs before `x` is installed.
66
+ const invocation = input.invocation ?? 'x new';
67
+ super({
68
+ code: 'X_CLI_BAD_FLAG',
69
+ cause: `"${invocation}" takes a NAME and got the path "${input.name}" — it would be slugified into one directory name`,
70
+ fix: `${invocation} ${quoteArg(input.base)} --dir ${quoteArg(input.parent)}`,
71
+ });
72
+ }
73
+ }
74
+
50
75
  /**
51
76
  * A command that declares subcommands, invoked with none and declaring no `defaultSubcommand`.
52
77
  *
package/src/favicon.ts ADDED
@@ -0,0 +1,113 @@
1
+ // `/favicon.ico`, which every browser requests unprompted and no Ultimate app answered: the
2
+ // scaffold wrote no file and neither served surface mounted a route, so a permanent 404 sat in the
3
+ // console of every app the framework produces. The app's own file wins; the framework answers when
4
+ // there is none, so an app inherits a clean console rather than a file it has to remember to add.
5
+
6
+ // why: Bun exposes no path-join primitive, and `FAVICON_SOURCE` is app-root-relative, so resolving
7
+ // it against the root is string work no `Bun.file` overload does — the same necessity
8
+ // `dev-assets.ts` records for `ICON_SOURCE`.
9
+ import { join } from 'node:path';
10
+ import { createRaster, encodeImage } from '@ultimat3/core';
11
+ import type { CacheHint, Route, UltimateRequest } from '@ultimat3/http';
12
+ import { applyCacheHeaders } from '@ultimat3/http';
13
+
14
+ /** What a browser asks for with no `<link rel="icon">` to tell it otherwise. */
15
+ export const FAVICON_PATH = '/favicon.ico';
16
+
17
+ /**
18
+ * The one file an app overrides it with — beside `ICON_SOURCE`, in the same directory, because
19
+ * `apps/web/site/` is already where an app's public files live. One path, never a search order: a
20
+ * mechanism that accepted `favicon.png` too would be two ways to do one thing, and an app whose
21
+ * icon is not there would have to be told which of them won.
22
+ */
23
+ export const FAVICON_SOURCE = 'apps/web/site/favicon.ico';
24
+
25
+ /** 32px, which is what a browser tab and a bookmark bar both ask for. */
26
+ const DEFAULT_SIZE = 32;
27
+
28
+ /**
29
+ * Not a colour: one mid-grey LEVEL written to all three channels, exactly as
30
+ * `templates/scaffold-icon.ts` argues — `@ultimat3/ui` owns the colour roles and `cli -> ui` is a
31
+ * boundary error, so a placeholder here must claim no brand colour to begin with.
32
+ */
33
+ const MARK_LEVEL = 128;
34
+ const OPAQUE = 255;
35
+
36
+ const FAVICON_CACHE: CacheHint = { mode: 'public', maxAgeSeconds: 3600 };
37
+
38
+ /**
39
+ * The framework's answer when the app declares none: a solid 32x32 PNG, encoded through
40
+ * `@ultimat3/core`'s own pipeline rather than shipped as an opaque blob — the same encoder
41
+ * `x new`'s icon goes through, so there is no second image format in the tree and no base64
42
+ * constant nobody can verify. Served as `image/png` under an `.ico` URL, which every browser reads
43
+ * by content type; a real ICO container would be a fourth format for one placeholder.
44
+ *
45
+ * Deliberately NOT derived from `ICON_SOURCE`: resizing the app's install icon needs
46
+ * `@ultimat3/pwa`'s pipeline and would make the answer depend on a file that may be missing, which
47
+ * is a third rung under a mechanism that has exactly two.
48
+ */
49
+ export function defaultFavicon(): Uint8Array {
50
+ const raster = createRaster(DEFAULT_SIZE, DEFAULT_SIZE, 'favicon');
51
+ const { pixels } = raster;
52
+ for (let i = 0; i < pixels.length; i += 4) {
53
+ pixels[i] = MARK_LEVEL;
54
+ pixels[i + 1] = MARK_LEVEL;
55
+ pixels[i + 2] = MARK_LEVEL;
56
+ pixels[i + 3] = OPAQUE;
57
+ }
58
+ return encodeImage(raster, 'png');
59
+ }
60
+
61
+ /** Encoded once per process: the bytes are a pure function of two constants. */
62
+ let builtin: Uint8Array | undefined;
63
+
64
+ const builtinBytes = (): Uint8Array => {
65
+ builtin ??= defaultFavicon();
66
+ return builtin;
67
+ };
68
+
69
+ const iconResponse = (bytes: Uint8Array, contentType: string): Response =>
70
+ applyCacheHeaders(
71
+ // Copied, not passed through: a `Uint8Array<ArrayBufferLike>` may be backed by a
72
+ // `SharedArrayBuffer`, which `Response` does not accept — `dev-assets.ts`'s rule, verbatim.
73
+ new Response(new Uint8Array(bytes), { headers: { 'content-type': contentType } }),
74
+ FAVICON_CACHE,
75
+ );
76
+
77
+ /** What a surface answers with, and what it says the bytes are. */
78
+ export interface FaviconBytes {
79
+ readonly bytes: Uint8Array;
80
+ readonly contentType: string;
81
+ }
82
+
83
+ /**
84
+ * Read per REQUEST, never once at boot: `x dev` is a running process an author drops a favicon
85
+ * into, and a route that captured "there was no file" at startup would keep answering the
86
+ * placeholder until the server was restarted — the class of dev/prod difference this package's
87
+ * own header forbids.
88
+ *
89
+ * Its own function because the static export has no process to ask: `prerenderSite` writes these
90
+ * same bytes into the artifact, and a second rule for which favicon a static build carries would
91
+ * be a build whose tab icon differs from the server's.
92
+ */
93
+ export async function faviconBytes(root: string): Promise<FaviconBytes> {
94
+ const own = Bun.file(join(root, FAVICON_SOURCE));
95
+ if (await own.exists()) return { bytes: await own.bytes(), contentType: 'image/x-icon' };
96
+ return { bytes: builtinBytes(), contentType: 'image/png' };
97
+ }
98
+
99
+ export async function faviconResponse(root: string): Promise<Response> {
100
+ const favicon = await faviconBytes(root);
101
+ return iconResponse(favicon.bytes, favicon.contentType);
102
+ }
103
+
104
+ /**
105
+ * Mounted through `assetRoutes`, so `x dev`, the container and every test that boots either get it
106
+ * from one place. Public by definition — a browser requests it before anyone has signed in.
107
+ */
108
+ export const faviconRoute = (root: string): Route => ({
109
+ method: 'GET',
110
+ path: FAVICON_PATH,
111
+ meta: { name: 'assets.favicon', auth: 'public', cache: FAVICON_CACHE, tags: ['assets'] },
112
+ handler: async (_request: UltimateRequest): Promise<Response> => faviconResponse(root),
113
+ });
@@ -0,0 +1,104 @@
1
+ // The other half of the citation rule: a `fix:` may name a FILE, and nothing resolved it. Only
2
+ // `x <command>` citations were checked (`fix-command.ts`), so a fix telling its reader to open a
3
+ // path that no longer exists — or never did — satisfied every gate the repo has, while a file token
4
+ // is one of the four things that make a fix an instruction at all (`COMMAND_TOKENS`).
5
+
6
+ // why: Bun exposes no synchronous existence primitive — `Bun.file(p).exists()` is async and answers
7
+ // false for a DIRECTORY, and this rule has to judge both. Delete when Bun ships one.
8
+ import { existsSync } from 'node:fs';
9
+ // why: Bun exposes no path-join or dirname primitive. The same necessity `error-contract.ts`
10
+ // already records for `join`.
11
+ import { dirname, join } from 'node:path';
12
+
13
+ /**
14
+ * The extensions a fix line may cite a file by — the SAME set `COMMAND_TOKENS`' file pattern is
15
+ * built from, exported here so the token that lets a fix count as an instruction and the token this
16
+ * rule resolves can never drift apart. Two lists would mean a citation that satisfies the first
17
+ * rule and is invisible to the second, which is the hole this file exists to close.
18
+ */
19
+ export const CITED_FILE_EXTENSIONS = [
20
+ 'ts',
21
+ 'tsx',
22
+ 'js',
23
+ 'json',
24
+ 'md',
25
+ 'toml',
26
+ 'yaml',
27
+ 'yml',
28
+ 'css',
29
+ 'scss',
30
+ 'sql',
31
+ ] as const;
32
+
33
+ /** `[\w.@-]*\/[\w.@-]+\.(?:ts|…)`, as one source string both rules read. */
34
+ export const FILE_TOKEN_PATTERN = String.raw`[\w.@-]*\/[\w.@-]+\.(?:${CITED_FILE_EXTENSIONS.join('|')})\b`;
35
+
36
+ /**
37
+ * A whole path, not the last two segments `FILE_TOKEN_PATTERN` matches: this rule resolves the
38
+ * citation, so it needs every segment. `*` is in the class because a glob is a citation too.
39
+ */
40
+ const PATH_CITATION = new RegExp(
41
+ String.raw`(?:[\w.@*-]+\/)+[\w.@*-]+\.(?:${CITED_FILE_EXTENSIONS.join('|')})\b`,
42
+ 'g',
43
+ );
44
+
45
+ /** A URL is not a repo path, and `https://ultimate.dev/errors/x.md` is shaped like one. */
46
+ const URL_SPAN = /\b[a-z][\w+.-]*:\/\/\S+/gi;
47
+
48
+ /**
49
+ * Whether this repo can judge the citation at all. THREE exclusions, each one a shape that resolves
50
+ * against something other than the root the gate is running in — reporting any of them would be a
51
+ * finding nobody can act on:
52
+ *
53
+ * - a scoped module specifier (`@ultimat3/ui/global.scss`) resolves through `node_modules`;
54
+ * - a dot-relative path (`./global.scss`) resolves against the reader's own file, which the fix
55
+ * line does not name;
56
+ * - a path whose PARENT DIRECTORY does not exist here is app-facing by construction — `src/errors.ts`
57
+ * means "in the package you are editing", `apps/web/server.ts` and `packages/i18n/catalogs/en.json`
58
+ * name directories a generated app has and this repo does not. What is left is the citation this
59
+ * root really can answer: a directory that exists, named as holding a file it does not hold.
60
+ */
61
+ function isJudgeable(token: string, root: string): boolean {
62
+ if (token.startsWith('@') || token.startsWith('./') || token.startsWith('../')) return false;
63
+ const star = token.indexOf('*');
64
+ // A glob's FIXED prefix is what has to exist; the segments a `*` stands for are the answer. Cut
65
+ // at the separator before the star rather than at the star — `dirname('packages/')` is `.`, and
66
+ // a glob whose first segment is the wildcard has no prefix to check at all.
67
+ const cut = star === -1 ? -1 : token.lastIndexOf('/', star);
68
+ const base = star === -1 ? dirname(token) : token.slice(0, Math.max(cut, 0));
69
+ return base !== '.' && base !== '' && existsSync(join(root, base));
70
+ }
71
+
72
+ /** Every path-shaped citation on a fix line that this root can resolve, in the order written. */
73
+ export function pathCitations(fix: string, root: string): readonly string[] {
74
+ const prose = fix.replaceAll(URL_SPAN, ' ');
75
+ return [...prose.matchAll(PATH_CITATION)]
76
+ .map((match) => match[0])
77
+ .filter((token) => isJudgeable(token, root));
78
+ }
79
+
80
+ /** A glob matches when at least one file answers it; anything else must exist as written. */
81
+ async function resolves(token: string, root: string): Promise<boolean> {
82
+ if (!token.includes('*')) return existsSync(join(root, token));
83
+ for await (const _match of new Bun.Glob(token).scan({ cwd: root, onlyFiles: false })) {
84
+ return true;
85
+ }
86
+ return false;
87
+ }
88
+
89
+ /**
90
+ * The first path a fix cites that this repo does not have, as one sentence for a `cause:`. One
91
+ * finding per fix line, never one per token — the same rule `citedCommandProblem` holds to.
92
+ *
93
+ * Read off the STATIC form of the fix (the caller blanks `${…}` first): a path assembled at run
94
+ * time is not a path this can resolve, and guessing at one reports findings nobody can act on.
95
+ */
96
+ export async function citedPathProblem(fix: string, root: string): Promise<string | undefined> {
97
+ for (const token of pathCitations(fix, root)) {
98
+ if (!(await resolves(token, root))) {
99
+ const kind = token.includes('*') ? 'matches no file' : 'is not a file in this repository';
100
+ return `cites "${token}", which ${kind}`;
101
+ }
102
+ }
103
+ return undefined;
104
+ }
package/src/hold.ts CHANGED
@@ -3,7 +3,23 @@
3
3
  // before the exit code. Ctrl-C then takes core's own three-phase drain (stop accepting, finish
4
4
  // in-flight, close) instead of killing a query mid-round-trip.
5
5
 
6
- import { drain, installSignalHandlers, onShutdown } from '@ultimat3/core';
6
+ import { drain, installSignalHandlers, logger, onShutdown, systemClock } from '@ultimat3/core';
7
+
8
+ export interface HoldOptions {
9
+ /**
10
+ * What to call once the release is done, with `0`. Omit and nothing is called.
11
+ *
12
+ * There is exactly one caller: `runRole` in `serve.ts`, which is what `apps/web/server.ts`
13
+ * awaits — the one entry point with nothing above it to end the process. `bin.ts` ends in
14
+ * `process.exit(code)`, so `x dev` and `x mcp` need none of this; a container has no such line,
15
+ * and one non-unref'd interval anywhere in the app then holds an event loop with nothing left to
16
+ * do until `terminationGracePeriodSeconds` runs out and the kubelet SIGKILLs it.
17
+ *
18
+ * A function rather than a boolean because `process.exit` in a library is untestable: this is
19
+ * the seam the test passes a spy through, and the caller is the one that knows.
20
+ */
21
+ readonly exit?: (code: number) => void;
22
+ }
7
23
 
8
24
  /**
9
25
  * Wait for a shutdown, then release what core's lifecycle does not own.
@@ -16,15 +32,29 @@ import { drain, installSignalHandlers, onShutdown } from '@ultimat3/core';
16
32
  * `release` runs after the drain completes, so in-flight requests still see the database the
17
33
  * handler opened them against. It is the resources core never learned about: the embedded
18
34
  * Postgres, the worker, the file watcher.
35
+ *
36
+ * It runs INSIDE the drain's own deadline, and that is not a detail. `drain()` ABANDONS a hook
37
+ * that overruns `ShutdownReason.deadlineAt` — the process is meant to exit without it — and
38
+ * `release` here re-enters the very same teardown one call later: `app.stop()` ->
39
+ * `startRoles().stop()` -> `worker.stop()`, memoised in the package that owns it, so awaiting it
40
+ * is awaiting the promise the drain just walked away from. Unbounded, that hangs forever and the
41
+ * deadline buys nothing.
19
42
  */
20
- export function holdUntilShutdown(name: string, release: () => Promise<void>): () => Promise<void> {
43
+ export function holdUntilShutdown(
44
+ name: string,
45
+ release: () => Promise<void>,
46
+ options: HoldOptions = {},
47
+ ): () => Promise<void> {
21
48
  const uninstall = installSignalHandlers({ exit: false });
22
49
  let unregister = (): void => {};
23
- const shuttingDown = new Promise<void>((resolve) => {
50
+ // The hook's own `reason`, not a stopwatch of ours: `deadlineAt` is the instant core computed
51
+ // when the drain began, on the same real monotonic clock, so this budget IS the drain's budget
52
+ // rather than a second one that happens to be the same length.
53
+ const shuttingDown = new Promise<number>((resolve) => {
24
54
  unregister = onShutdown(
25
55
  `cli:${name}:hold`,
26
- () => {
27
- resolve();
56
+ (reason) => {
57
+ resolve(reason.deadlineAt);
28
58
  },
29
59
  { phase: 'accept' },
30
60
  );
@@ -35,14 +65,50 @@ export function holdUntilShutdown(name: string, release: () => Promise<void>): (
35
65
  // Memoised: awaiting a hold twice must not release twice, and `dispatch` is not the only
36
66
  // caller a test can be.
37
67
  held ??= (async () => {
38
- await shuttingDown;
68
+ const deadlineAt = await shuttingDown;
39
69
  // Idempotent in core: this joins the drain already in flight and resolves when its last
40
70
  // phase is done. Calling it is what makes `release` the step after the drain, not beside it.
41
71
  await drain();
42
72
  unregister();
43
73
  uninstall();
44
- await release();
74
+ await releaseWithin(name, release, deadlineAt - systemClock.monotonic());
75
+ options.exit?.(0);
45
76
  })();
46
77
  return held;
47
78
  };
48
79
  }
80
+
81
+ /**
82
+ * `release()` raced against what is left of the drain's budget.
83
+ *
84
+ * A local race and not core's `settleWithin`, which is internal to `lifecycle-deadline.ts` and not
85
+ * on core's barrel. The semantics are deliberately the same, including the one that matters: a
86
+ * REJECTION still rejects — `dispatch` awaits the hold inside its own `try`, and an embedded
87
+ * database that would not close is a finding on the way out, never a clean exit over it.
88
+ *
89
+ * A budget already spent is `0`, and that abandons immediately by design: past `deadlineAt` the
90
+ * orchestrator is already counting down to SIGKILL, so the honest move is to say so and exit
91
+ * rather than to start a second grace period nobody granted.
92
+ */
93
+ async function releaseWithin(
94
+ name: string,
95
+ release: () => Promise<void>,
96
+ budgetMs: number,
97
+ ): Promise<void> {
98
+ const budget = Math.max(0, budgetMs);
99
+ let timer: ReturnType<typeof setTimeout> | undefined;
100
+ const abandoned = new Promise<'abandoned'>((resolve) => {
101
+ timer = setTimeout(() => resolve('abandoned'), budget);
102
+ });
103
+ try {
104
+ const outcome = await Promise.race([release().then(() => 'released' as const), abandoned]);
105
+ if (outcome === 'released') return;
106
+ logger.warn('X_SHUTDOWN_TIMEOUT', {
107
+ code: 'X_SHUTDOWN_TIMEOUT',
108
+ cause: `the "${name}" release was still running ${budget}ms after the drain finished and has been ABANDONED — the process exits without it, so anything it held may not be closed`,
109
+ fix: 'raise the budget past the slowest teardown — configureLifecycle({ deadlineMs: 600_000 }) for a 10-minute one — and set terminationGracePeriodSeconds to at least as many seconds',
110
+ });
111
+ } finally {
112
+ if (timer !== undefined) clearTimeout(timer);
113
+ }
114
+ }
package/src/index.ts CHANGED
@@ -116,6 +116,7 @@ export {
116
116
  export type { ErrorCatalog } from './error-catalog';
117
117
  export {
118
118
  buildErrorCatalog,
119
+ CATALOG_OPTIONAL_HOSTS,
119
120
  CATALOG_PACKAGES,
120
121
  loadErrorCatalog,
121
122
  registeredErrorCodes,
@@ -167,6 +168,13 @@ export {
167
168
  } from './errors';
168
169
  export type { ExecOptions, ExecResult, Runner } from './exec';
169
170
  export { exec, execOutput } from './exec';
171
+ export {
172
+ defaultFavicon,
173
+ FAVICON_PATH,
174
+ FAVICON_SOURCE,
175
+ faviconResponse,
176
+ faviconRoute,
177
+ } from './favicon';
170
178
  export type { CitationFault, CitationRules, CommandCatalog, FixCitation } from './fix-command';
171
179
  export {
172
180
  citationFault,
@@ -177,6 +185,12 @@ export {
177
185
  } from './fix-command';
178
186
  export type { HelperResolver } from './fix-imports';
179
187
  export { candidatePaths, createHelperResolver, scanImports } from './fix-imports';
188
+ export {
189
+ CITED_FILE_EXTENSIONS,
190
+ citedPathProblem,
191
+ FILE_TOKEN_PATTERN,
192
+ pathCitations,
193
+ } from './fix-path';
180
194
  export type { FixHelper, FixScan } from './fix-scan';
181
195
  export { scanFixes, scanFixHelpers, scanFixSites } from './fix-scan';
182
196
  export type { DeclaredFlag } from './flag-reads';
@@ -0,0 +1,181 @@
1
+ // One question only this package can ask: a route SUBSCRIBES to live rows, and does anything on
2
+ // that route ever run in a browser to receive them? `@ultimat3/realtime` cannot see a route and
3
+ // `@ultimat3/render` may not import realtime, so the two halves meet here — beside the island
4
+ // build, which is the other place the route table and the client graph are both in scope.
5
+ //
6
+ // The failure it closes is silent by construction (#271): with no island the page server-renders
7
+ // its `loading` branch, answers 200, and stays that way forever — nothing throws, nothing logs,
8
+ // and every suite passes.
9
+
10
+ // why: Bun exposes no path API, and a route file's imports are resolved against its own directory.
11
+ import { join, posix } from 'node:path';
12
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
13
+ import type { RouteEntry } from '@ultimat3/render';
14
+ import { ISLAND_EXTENSION, routeEntries } from '@ultimat3/render';
15
+ import type { Finding } from './output';
16
+
17
+ /**
18
+ * The exports that only work with a registered `LiveClient`. Each one either subscribes, mutates
19
+ * or reads the connection, so a module naming one is a module that needs a browser to have booted
20
+ * it — `hasLiveClient` and `LiveClient` itself are deliberately absent: the first IS the guard, and
21
+ * the second is what an island's `mount()` constructs.
22
+ */
23
+ export const LIVE_HOOKS = [
24
+ 'useLive',
25
+ 'liveHookFor',
26
+ 'useConnection',
27
+ 'useMutation',
28
+ 'useMutationQueue',
29
+ ] as const;
30
+
31
+ /**
32
+ * The one escape hatch, and it is a call an author writes on purpose: a module that ASKS whether
33
+ * there is a client has already written what happens when there is none. `app/update-banner.tsx`
34
+ * in the reference app is the shape — imported by the layout, so by every page, and correct on all
35
+ * of them.
36
+ */
37
+ const GUARD = 'hasLiveClient';
38
+
39
+ /** Value imports only: `import type` is erased, so it boots nothing and needs nothing. */
40
+ const REALTIME_IMPORT = /import\s+([^;]*?)from\s*['"]@ultimat3\/realtime(?:\/[\w-]+)?['"]/g;
41
+
42
+ const bindingsOf = (clause: string): readonly string[] =>
43
+ (/\{([^}]*)\}/.exec(clause)?.[1] ?? '')
44
+ .split(',')
45
+ .map((entry) => entry.split(/\bas\b/)[0]?.trim() ?? '')
46
+ .filter((name) => name.length > 0 && !name.startsWith('type '));
47
+
48
+ /**
49
+ * Which live hooks one module imports, or `[]` — including for a module that guards, which is a
50
+ * per-FILE verdict on purpose: the guard is written next to the read it protects.
51
+ */
52
+ export function liveHooksIn(source: string): readonly string[] {
53
+ const hooks: string[] = [];
54
+ for (const match of source.matchAll(REALTIME_IMPORT)) {
55
+ const clause = match[1] ?? '';
56
+ if (clause.trimStart().startsWith('type ')) continue;
57
+ const names = bindingsOf(clause);
58
+ if (names.includes(GUARD)) return [];
59
+ for (const hook of LIVE_HOOKS) if (names.includes(hook)) hooks.push(hook);
60
+ }
61
+ return hooks;
62
+ }
63
+
64
+ /** What a relative specifier can be on disk. The list `fix-imports.ts` already resolves against. */
65
+ const candidates = (base: string): readonly string[] => [
66
+ `${base}.ts`,
67
+ `${base}.tsx`,
68
+ `${base}/index.ts`,
69
+ `${base}/index.tsx`,
70
+ ];
71
+
72
+ async function readModule(
73
+ root: string,
74
+ file: string,
75
+ ): Promise<{ path: string; source: string } | undefined> {
76
+ for (const path of file.endsWith('.ts') || file.endsWith('.tsx') ? [file] : candidates(file)) {
77
+ const handle = Bun.file(join(root, path));
78
+ if (await handle.exists()) return { path, source: await handle.text() };
79
+ }
80
+ return undefined;
81
+ }
82
+
83
+ /** Where a route's graph first reaches a live hook. */
84
+ export interface LiveReach {
85
+ /** App-root-relative module that imports it. */
86
+ readonly at: string;
87
+ readonly hook: string;
88
+ }
89
+
90
+ /**
91
+ * Walk the route module's own import graph and answer the first live hook in it.
92
+ *
93
+ * Relative specifiers only. A bare one resolves through `node_modules` or a workspace name, and
94
+ * following either would mean guessing which package a name came from — the limit `fix-imports.ts`
95
+ * records for the same walk. So this UNDER-reports rather than over-reports: a finding here is
96
+ * always a real one, which is what lets the rule ship with no pin table.
97
+ */
98
+ export async function liveReachOf(root: string, file: string): Promise<LiveReach | undefined> {
99
+ const seen = new Set<string>();
100
+ const queue = [file];
101
+ while (queue.length > 0) {
102
+ const next = queue.shift();
103
+ if (next === undefined || seen.has(next)) continue;
104
+ seen.add(next);
105
+ const module = await readModule(root, next);
106
+ if (module === undefined) continue;
107
+ const hook = liveHooksIn(module.source)[0];
108
+ if (hook !== undefined) return { at: module.path, hook };
109
+ const loader = module.path.endsWith('x') ? 'tsx' : 'ts';
110
+ // Bun's transpiler is the parser, exactly as in `scripts/boundaries.ts`: it erases type-only
111
+ // imports and finds the dynamic ones, which no regex over this source could do.
112
+ for (const scanned of new Bun.Transpiler({ loader }).scanImports(module.source)) {
113
+ if (!scanned.path.startsWith('.')) continue;
114
+ queue.push(posix.normalize(posix.join(posix.dirname(module.path), scanned.path)));
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ export interface LiveRouteGap extends LiveReach {
121
+ readonly route: string;
122
+ readonly file: string;
123
+ /** What the route declares. `'never'` is the second way nothing boots. */
124
+ readonly hydrate: string;
125
+ readonly islands: readonly string[];
126
+ }
127
+
128
+ /** The `x g island` invocation that fixes it, built from this route's own file — never a placeholder. */
129
+ const generatorFor = (file: string): string => {
130
+ const dir = posix.dirname(file);
131
+ return `x g island ${posix.basename(dir)} --at ${dir}`;
132
+ };
133
+
134
+ /**
135
+ * Every route that reads live rows with nothing to receive them. Two shapes, one condition — no
136
+ * island at all, and an island the route declares `hydrate: 'never'` for. `X_ISLAND_NOT_HYDRATED`
137
+ * covers the second only at render time, and only for a render that reaches the island, so a route
138
+ * can hold the contradiction and never be asked.
139
+ */
140
+ export async function liveRouteGaps(
141
+ root: string,
142
+ entries: readonly RouteEntry[],
143
+ ): Promise<readonly LiveRouteGap[]> {
144
+ const gaps: LiveRouteGap[] = [];
145
+ for (const entry of entries) {
146
+ if (entry.surface === 'api') continue;
147
+ if (entry.islands.length > 0 && entry.config.hydrate !== 'never') continue;
148
+ const reach = await liveReachOf(root, entry.file);
149
+ if (reach === undefined) continue;
150
+ gaps.push({
151
+ ...reach,
152
+ route: entry.path,
153
+ file: entry.file,
154
+ hydrate: entry.config.hydrate,
155
+ islands: entry.islands,
156
+ });
157
+ }
158
+ return gaps;
159
+ }
160
+
161
+ export const liveRouteFindingFor = (gap: LiveRouteGap): Finding => ({
162
+ code: 'X_LIVE_ROUTE_NO_ISLAND',
163
+ cause:
164
+ `${gap.route} reads ${gap.hook}() (${gap.at}) and ` +
165
+ (gap.islands.length === 0
166
+ ? 'declares no island'
167
+ : `declares hydrate: 'never' beside ${gap.islands.join(', ')}`) +
168
+ ', so no module of this route ever runs in a browser: its rows have nowhere to arrive and the page renders its loading branch forever, at 200',
169
+ fix:
170
+ `${generatorFor(gap.file)}, declare it with island({ src: './${posix.basename(posix.dirname(gap.file))}${ISLAND_EXTENSION}' }) above defineRoute in ${gap.file}, ` +
171
+ `and move the ${gap.hook}() read into its mount() — which is where setLiveClient() can be called`,
172
+ docs: ERROR_DOCS_URL,
173
+ at: gap.at,
174
+ });
175
+
176
+ /**
177
+ * What this rule contributes to `x verify`'s `budgets` step — the step that already loaded the app
178
+ * and already asks what JavaScript a route's document boots.
179
+ */
180
+ export const liveRouteFindings = async (root: string): Promise<readonly Finding[]> =>
181
+ (await liveRouteGaps(root, routeEntries())).map(liveRouteFindingFor);