@ultimat3/cli 31.50.0 → 31.52.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.
Files changed (80) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +9 -9
  3. package/package.json +29 -29
  4. package/src/app-boundaries.ts +2 -0
  5. package/src/app-dev-imports.ts +77 -0
  6. package/src/app-load-import-chain.ts +112 -0
  7. package/src/app-load-unresolved.ts +173 -16
  8. package/src/app-load.ts +22 -5
  9. package/src/catalog-layout.ts +194 -0
  10. package/src/cmd-i18n-spec.ts +4 -4
  11. package/src/cmd-i18n-split.ts +133 -0
  12. package/src/cmd-i18n.ts +46 -66
  13. package/src/config-redact.ts +20 -4
  14. package/src/db-rollback-pass.ts +4 -1
  15. package/src/dev-child-watch.ts +16 -0
  16. package/src/dev-db-migrate.ts +27 -46
  17. package/src/dev-db-migrator-hold.ts +131 -0
  18. package/src/dev-db-rollback.ts +11 -2
  19. package/src/dev-only-imports.ts +59 -0
  20. package/src/dev-rebuild-schema.ts +7 -24
  21. package/src/error-codes-boundary.ts +2 -0
  22. package/src/evaluated-walk.ts +103 -0
  23. package/src/generate-catalog-locales.ts +25 -2
  24. package/src/generate-follow-ups.ts +8 -3
  25. package/src/i18n-audit.ts +17 -33
  26. package/src/i18n-index.ts +108 -31
  27. package/src/i18n-locale-parity.ts +14 -6
  28. package/src/i18n-new-locale.ts +75 -0
  29. package/src/i18n-registration.ts +52 -27
  30. package/src/index.ts +2 -0
  31. package/src/island-capture.ts +36 -7
  32. package/src/mcp-errors.ts +3 -1
  33. package/src/merge-state.ts +3 -2
  34. package/src/messages-floor.ts +2 -0
  35. package/src/messages.ts +2 -0
  36. package/src/module-imports.ts +26 -15
  37. package/src/page-route.ts +75 -0
  38. package/src/scan-ways.ts +145 -0
  39. package/src/serve-boot-telemetry.ts +106 -0
  40. package/src/serve-boot.ts +23 -4
  41. package/src/shot-blank.ts +70 -0
  42. package/src/templates/catalog-barrel.ts +84 -0
  43. package/src/templates/guard-released-forms.ts +2 -1
  44. package/src/templates/guard-untranslated-string.ts +27 -6
  45. package/src/templates/locales.ts +6 -0
  46. package/src/templates/scaffold-gitattributes.ts +9 -2
  47. package/src/templates/scaffold-i18n.ts +10 -6
  48. package/src/templates/shapes/offline.ts +5 -2
  49. package/src/test-ignores.ts +3 -2
  50. package/src/verify-checks.ts +7 -3
  51. package/src/verify-floor.ts +9 -1
  52. package/src/verify-local-only.ts +66 -0
  53. package/src/verify-run.ts +17 -2
  54. package/wiki/Actions.md +1 -1
  55. package/wiki/Auth.md +4 -4
  56. package/wiki/Batching-And-Preloading.md +1 -0
  57. package/wiki/CLI-Reference-Data.md +241 -0
  58. package/wiki/CLI-Reference-Gate.md +572 -0
  59. package/wiki/CLI-Reference-Project.md +414 -0
  60. package/wiki/CLI-Reference-Ship.md +348 -0
  61. package/wiki/CLI-Reference-Tools.md +666 -0
  62. package/wiki/CLI-Reference.md +14 -2225
  63. package/wiki/Compared.md +8 -8
  64. package/wiki/Configuration.md +26 -2
  65. package/wiki/Deployment.md +1 -1
  66. package/wiki/Entities-And-Migrations.md +3 -2
  67. package/wiki/I18n.md +39 -5
  68. package/wiki/Installation.md +1 -1
  69. package/wiki/Jobs-And-Workflows.md +29 -1
  70. package/wiki/Known-Gaps.md +3 -0
  71. package/wiki/Observability.md +15 -1
  72. package/wiki/Outbound-HTTP.md +62 -2
  73. package/wiki/PWA-And-Offline.md +1 -1
  74. package/wiki/Policies-And-Authz.md +10 -0
  75. package/wiki/Realtime.md +29 -2
  76. package/wiki/Static-Assets.md +1 -1
  77. package/wiki/Testing.md +58 -0
  78. package/wiki/Theming.md +31 -8
  79. package/wiki/Troubleshooting.md +2 -2
  80. package/wiki/Upgrading.md +6 -1
@@ -15,17 +15,21 @@ import { IslandRequestUnstubbedError, IslandUnphotographableError } from './isla
15
15
  import type { IslandReadiness, IslandStateShot } from './island-verdict';
16
16
  import { parseReadiness } from './island-verdict';
17
17
  import { quoteArg } from './shell-quote';
18
+ import { blankShotReason } from './shot-blank';
18
19
  import { type ShotCookiePair, shotCookies } from './shot-cookie';
19
20
  import type { ShotServer } from './shot-server';
20
21
  import { allowHostsFrom } from './shot-server';
21
22
  import { SETTLE_POLL_MS, settleReadiness } from './shot-settle';
22
23
 
23
24
  /**
24
- * A backstop and not a quality bar: it catches the answers that are not an image at all — a driver
25
- * that hands back a handshake, an empty buffer, a PNG signature with nothing behind it. A real
26
- * capture of any viewport clears it by an order of magnitude.
25
+ * The smallest complete PNG (signature, IHDR, one IDAT, IEND) — a cheap backstop ahead of the
26
+ * pixel judgement in `shot-blank.ts`, for an answer that cannot be an image at all: a handshake,
27
+ * an empty buffer, a signature with nothing behind it. Never a quality bar: a flat 36 px button is
28
+ * a few hundred honest bytes, and a floor of 512 refused it as blank (2077pc's theme toggle,
29
+ * 372 bytes). Whether the picture shows anything is the PIXELS' question. `0` turns the whole
30
+ * judgement off — the seam a fake driver needs.
27
31
  */
28
- export const MIN_SHOT_BYTES = 512;
32
+ export const MIN_SHOT_BYTES = 67;
29
33
 
30
34
  /**
31
35
  * Page pixels kept on every side of the crop target.
@@ -121,6 +125,31 @@ export function photographFault(
121
125
  return undefined;
122
126
  }
123
127
 
128
+ const browserFix = (target: IslandShotTarget): string =>
129
+ `x shot --island ${quoteArg(target.name)} --browser /usr/bin/chromium --json # macOS: --browser "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; Windows: --browser "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"`;
130
+
131
+ /**
132
+ * The assertion AFTER the shutter: the bytes are an image, and the image shows something. Under
133
+ * the byte floor or undecodable is the browser's fault; one colour or nothing opaque is the crop's.
134
+ * A `floor` of 0 asserts nothing — the seam a fake driver's 8-byte answer needs.
135
+ */
136
+ export async function pictureFault(
137
+ target: IslandShotTarget,
138
+ bytes: Uint8Array,
139
+ floor: number,
140
+ ): Promise<Refusal | undefined> {
141
+ if (floor === 0) return undefined;
142
+ if (bytes.byteLength < floor) {
143
+ return {
144
+ reason: `produced ${bytes.byteLength} bytes, under the ${floor}-byte floor — that is not an image`,
145
+ fix: browserFix(target),
146
+ };
147
+ }
148
+ const blank = await blankShotReason(bytes);
149
+ if (blank === undefined) return undefined;
150
+ return { reason: blank.reason, fix: blank.undecodable ? browserFix(target) : cropFix(target) };
151
+ }
152
+
124
153
  /**
125
154
  * The capture rectangle for a readiness answer, in PAGE coordinates: the crop target's frame (its
126
155
  * own box grown to every open popup),
@@ -260,13 +289,13 @@ export async function captureIslandState(
260
289
  finiteCount('x shot --island', 'cropMarginPx', options.cropMarginPx ?? ISLAND_CROP_MARGIN_PX),
261
290
  );
262
291
  const bytes = await page.screenshot({ clip });
263
- if (bytes.byteLength < floor) {
292
+ const empty = await pictureFault(target, bytes, floor);
293
+ if (empty !== undefined) {
264
294
  throw new IslandUnphotographableError({
265
295
  island: target.island,
266
296
  state: target.state,
267
297
  theme: target.theme,
268
- reason: `produced ${bytes.byteLength} bytes, under the ${floor}-byte floor — that is not an image`,
269
- fix: `x shot --island ${quoteArg(target.name)} --browser /usr/bin/chromium --json # macOS: --browser "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; Windows: --browser "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"`,
298
+ ...empty,
270
299
  });
271
300
  }
272
301
  await Bun.write(join(options.outDir, target.file), bytes);
package/src/mcp-errors.ts CHANGED
@@ -297,7 +297,7 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
297
297
  X_BOUNDARY_PACKAGE_TO_APP:
298
298
  'x verify --only boundaries --json # after moving the shared code into the package, or importing in the opposite direction',
299
299
  X_APP_IMPORT_UNRESOLVED:
300
- 'x doctor --json # names the package to bun add, or the file whose import to edit',
300
+ 'x doctor --json # names the app module, and the install or the edit that clears it',
301
301
  X_STREAM_ALREADY_FLUSHED:
302
302
  'load: async () => { setCookie(name, value); return data; }, // in defineRoute, never inside a Hole',
303
303
  X_QUERY_SLICE_ENTITY:
@@ -393,6 +393,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
393
393
  // raised error's own `fix:` carries the named invocation; `ULTIMATE_TASK_RUN` stays in the cause.
394
394
  X_TASK_RUN_PRODUCTION:
395
395
  'x tasks list --json # then name the task: x tasks run <name> --production --json',
396
+ X_BOUNDARY_DEV_IMPORT:
397
+ 'x verify --only boundaries --json # names the module and its import: move test support to apps/web/test/, which no role loads, or drop the import from a module a role needs',
396
398
  };
397
399
 
398
400
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -55,8 +55,9 @@ export async function catalogFileFindings(root: string): Promise<readonly Findin
55
55
  const findings: Finding[] = [];
56
56
  const directory = `${root}/${CATALOG_ROOT}`;
57
57
  if (!existsSync(directory)) return findings;
58
- for await (const name of new Bun.Glob('*.json').scan(directory)) {
59
- const at = `${CATALOG_ROOT}/${name}`;
58
+ // `**`: a split locale's namespace files (`en/billing.json`) are imported by every page too.
59
+ for await (const name of new Bun.Glob('**/*.json').scan(directory)) {
60
+ const at = `${CATALOG_ROOT}/${name.replaceAll('\\', '/')}`;
60
61
  const text = await Bun.file(`${root}/${at}`).text();
61
62
  if (MARKER.test(text)) {
62
63
  findings.push(
@@ -11,6 +11,8 @@ export const FLOOR_MESSAGES = {
11
11
  'cli.verify.skip.noManifest': 'no {file} committed, so there is no contract to diff',
12
12
  'cli.verify.skip.noRoadmap': 'no {file} here',
13
13
  'cli.verify.skip.nothing': 'the step found nothing to check here',
14
+ // One line per step `localOnly` left out of a CI run (`verify-local-only.ts`): coverage it omits.
15
+ 'cli.verify.localOnly.line': 'left out in CI: {step} — {reason}',
14
16
  // Without `strict`, a warning and never red: an existing app meets it on `main` (X_BREAKING_ON_MAIN).
15
17
  'cli.verify.unwaived':
16
18
  'not strict: {names} ran no check here — give each a suite, or a "skip" why in x.verify.json, then set "strict": true',
package/src/messages.ts CHANGED
@@ -172,6 +172,8 @@ const CATALOG = {
172
172
  // say "this locale's slots drifted and this string was never translated".
173
173
  'cli.i18n.parity':
174
174
  '{count} locale-parity finding(s) across {locales} locale(s) — a slot or an untranslated copy against {reference}',
175
+ 'cli.i18n.split':
176
+ 'split {locales} locale(s) into {files} namespace file(s) — {moved} moved from a flat file',
175
177
  'cli.i18n.synced': 'synced {locale} from {from} — {added} key(s) added, {total} total',
176
178
  'cli.i18n.unused': '{count} key(s) defined in {locale} and never used:',
177
179
  'cli.mail.preview.missing':
@@ -20,28 +20,39 @@ const transpilers = {
20
20
  tsx: new Bun.Transpiler({ loader: 'tsx' }),
21
21
  };
22
22
 
23
- /**
24
- * Absolute paths, in source order. A file that will not parse imports nothing yet, and a
25
- * specifier that will not resolve contributes no edge: the module's own import reports both.
26
- */
27
- export function resolvedImports(path: string, source: string, edges: ImportEdges): string[] {
23
+ /** Every specifier `source` names, as written and in source order. Unparseable: it names none yet. */
24
+ export function importedSpecifiers(
25
+ path: string,
26
+ source: string,
27
+ edges: ImportEdges,
28
+ ): readonly string[] {
28
29
  const transpiler = path.endsWith('x') ? transpilers.tsx : transpilers.ts;
29
- let specifiers: readonly { readonly path: string; readonly kind: string }[];
30
30
  try {
31
- specifiers =
31
+ const imports =
32
32
  edges === 'referenced'
33
33
  ? transpiler.scanImports(source)
34
34
  : transpiler.scan(source).imports.filter((one) => one.kind !== 'dynamic-import');
35
+ return imports.map((one) => one.path);
35
36
  } catch {
36
37
  return [];
37
38
  }
38
- const found: string[] = [];
39
- for (const { path: specifier } of specifiers) {
40
- try {
41
- found.push(Bun.resolveSync(specifier, dirname(path)));
42
- } catch {
43
- // Unresolvable: no edge.
44
- }
39
+ }
40
+
41
+ /** The file `specifier` is from `path`, as Bun resolves it — `undefined` when it resolves to none. */
42
+ export function resolveImport(specifier: string, path: string): string | undefined {
43
+ try {
44
+ return Bun.resolveSync(specifier, dirname(path));
45
+ } catch {
46
+ return undefined;
45
47
  }
46
- return found;
48
+ }
49
+
50
+ /**
51
+ * Absolute paths, in source order. A file that will not parse imports nothing yet, and a
52
+ * specifier that will not resolve contributes no edge: the module's own import reports both.
53
+ */
54
+ export function resolvedImports(path: string, source: string, edges: ImportEdges): string[] {
55
+ return importedSpecifiers(path, source, edges).flatMap(
56
+ (specifier) => resolveImport(specifier, path) ?? [],
57
+ );
47
58
  }
@@ -0,0 +1,75 @@
1
+ // Single responsibility: a registered page's GET through the real `httpPipeline`, for a unit test —
2
+ // what a visitor RECEIVES (status, headers, cookies set, redirect, document), where `renderRoute`
3
+ // answers what the page renders. It lives in cli because the page handler (`appRoutes`) does.
4
+
5
+ import { assert } from '@ultimat3/core';
6
+ import { defineHttpConfig, httpPipeline, httpRouter } from '@ultimat3/http';
7
+ import { attachedIsr } from './runtime-isr';
8
+ import { appRoutes } from './runtime-render';
9
+
10
+ export interface PageRouteOptions {
11
+ /** Request headers, as a browser sends them (`accept-language`, `if-none-match` …). */
12
+ readonly headers?: Readonly<Record<string, string>>;
13
+ /**
14
+ * Cookies the request carries, by name; each value is percent-encoded as `useRequestCookie`
15
+ * decodes it. Pass either this or a `cookie` header, never both.
16
+ */
17
+ readonly cookies?: Readonly<Record<string, string>>;
18
+ /** The build the document names. Default `'page-route'`. */
19
+ readonly buildId?: string;
20
+ }
21
+
22
+ const ORIGIN = 'http://localhost';
23
+
24
+ const cookieHeader = (cookies: Readonly<Record<string, string>>): string =>
25
+ Object.entries(cookies)
26
+ .map(([name, value]) => `${name}=${encodeURIComponent(value)}`)
27
+ .join('; ');
28
+
29
+ /**
30
+ * `GET <path>` against the pages registered in this process (`registerRoute`, or `loadApp`), as the
31
+ * response a visitor gets. `path` is the URL path and query (`/es/precios?page=2`), starting with
32
+ * `/`. A path no page claims answers the pipeline's own 404.
33
+ *
34
+ * ```ts
35
+ * const response = await pageRoute('/dashboard', { cookies: { sid: 's-1' } });
36
+ * expect(response.status).toBe(200);
37
+ * expect(response.headers.getSetCookie()).toEqual([]);
38
+ * ```
39
+ */
40
+ export async function pageRoute(path: string, options: PageRouteOptions = {}): Promise<Response> {
41
+ assert(
42
+ path.startsWith('/'),
43
+ 'pageRoute requires a URL path starting with a slash',
44
+ "pageRoute('/dashboard?tab=2')",
45
+ );
46
+ const headers = new Headers(options.headers);
47
+ if (options.cookies !== undefined) {
48
+ assert(
49
+ !headers.has('cookie'),
50
+ 'pageRoute was handed both `cookies` and a `cookie` header',
51
+ "pageRoute('/dashboard', { cookies: { sid: 's-1' } })",
52
+ );
53
+ if (Object.keys(options.cookies).length > 0) {
54
+ headers.set('cookie', cookieHeader(options.cookies));
55
+ }
56
+ }
57
+ const buildId = options.buildId ?? 'page-route';
58
+ // One ISR controller per call, released after it: `appRoutes` would otherwise attach one it
59
+ // never detaches, and every call of a suite would leave a revalidator behind.
60
+ const { isr, release } = attachedIsr({ buildId });
61
+ try {
62
+ const pipeline = httpPipeline({
63
+ table: httpRouter(appRoutes({ buildId, isr })),
64
+ config: defineHttpConfig({
65
+ dev: false,
66
+ buildId,
67
+ hostname: '127.0.0.1',
68
+ rateLimit: { scope: 'process' },
69
+ }),
70
+ });
71
+ return await pipeline.handle(new Request(`${ORIGIN}${path}`, { headers }), { role: 'web' });
72
+ } finally {
73
+ release();
74
+ }
75
+ }
@@ -0,0 +1,145 @@
1
+ // Every way the boot scan has into each module holding a development import: the holder itself when
2
+ // it is scanned, else one chain per scanned edge towards it through modules outside the scan. One
3
+ // pass backwards from all the holders at once, each module read once per distance it is reached at
4
+ // and not once per holder: helpers that reconverge carry every holder below them together.
5
+
6
+ import type { ChainStep, EvaluatedImport } from './evaluated-walk';
7
+
8
+ /** A set of holders, one bit each: what reached a module together is moved and compared at once. */
9
+ type Holders = bigint;
10
+
11
+ /** The holders below a module, by how many imports below it they are. */
12
+ type Below = ReadonlyMap<number, Holders>;
13
+
14
+ /** One import of a module's, and the holders it is the first step of the shortest way to. */
15
+ interface Hop {
16
+ readonly edge: EvaluatedImport;
17
+ readonly target: string;
18
+ readonly holders: Holders;
19
+ }
20
+
21
+ /** `edges` by `key`, in the order given: a module's own stay in the order it writes them. */
22
+ function indexed(
23
+ edges: readonly EvaluatedImport[],
24
+ key: (edge: EvaluatedImport) => string | undefined,
25
+ ): ReadonlyMap<string | undefined, readonly EvaluatedImport[]> {
26
+ const index = new Map<string | undefined, EvaluatedImport[]>();
27
+ for (const edge of edges) {
28
+ const known = index.get(key(edge)) ?? [];
29
+ known.push(edge);
30
+ index.set(key(edge), known);
31
+ }
32
+ return index;
33
+ }
34
+
35
+ const together = (below: Below | undefined): Holders =>
36
+ [...(below?.values() ?? [])].reduce((all, holders) => all | holders, 0n);
37
+
38
+ /** Which bits are set, read off the digits: the clear ones between them cost no step each. */
39
+ function bitsOf(holders: Holders): readonly number[] {
40
+ const digits = holders.toString(2);
41
+ const found: number[] = [];
42
+ for (let at = digits.indexOf('1'); at !== -1; at = digits.indexOf('1', at + 1)) {
43
+ found.push(digits.length - 1 - at);
44
+ }
45
+ return found;
46
+ }
47
+
48
+ /** How far below each module outside the scan every holder is, shortest way. */
49
+ function distances(
50
+ bits: ReadonlyMap<string, Holders>,
51
+ scanned: ReadonlySet<string>,
52
+ into: ReadonlyMap<string | undefined, readonly EvaluatedImport[]>,
53
+ ): ReadonlyMap<string, Below> {
54
+ const below = new Map<string, Map<number, Holders>>();
55
+ const reached = new Map(bits);
56
+ let frontier: ReadonlyMap<string, Holders> = bits;
57
+ for (let distance = 0; frontier.size > 0; distance += 1) {
58
+ const next = new Map<string, Holders>();
59
+ for (const [path, holders] of frontier) {
60
+ const known = below.get(path) ?? new Map<number, Holders>();
61
+ below.set(path, known.set(distance, holders));
62
+ for (const { from } of into.get(path) ?? []) {
63
+ if (scanned.has(from)) continue;
64
+ const had = reached.get(from) ?? 0n;
65
+ const fresh = holders & ~had;
66
+ if (fresh === 0n) continue;
67
+ reached.set(from, had | fresh);
68
+ next.set(from, (next.get(from) ?? 0n) | fresh);
69
+ }
70
+ }
71
+ frontier = next;
72
+ }
73
+ return below;
74
+ }
75
+
76
+ /**
77
+ * The ways into each of `holders` over the app's followed `edges`. Shortest, and of two as short the
78
+ * one the module higher up imports first. Never through a scanned module: its own edge is the cut.
79
+ */
80
+ export function scanWays(
81
+ holders: readonly string[],
82
+ scanned: ReadonlySet<string>,
83
+ edges: readonly EvaluatedImport[],
84
+ ): (holder: string) => readonly (readonly ChainStep[])[] {
85
+ const outside = [...new Set(holders)].filter((holder) => !scanned.has(holder));
86
+ const bits = new Map(
87
+ outside.map((holder, index): [string, Holders] => [holder, 1n << BigInt(index)]),
88
+ );
89
+ const into = indexed(edges, (edge) => edge.target());
90
+ const below = distances(bits, scanned, into);
91
+ const onward = indexed(edges, (edge) => edge.from);
92
+ const hops = new Map<string, readonly Hop[]>();
93
+
94
+ /** Told once per module, whichever chains pass through it. */
95
+ function hopsOf(path: string): readonly Hop[] {
96
+ const known = hops.get(path);
97
+ if (known !== undefined) return known;
98
+ const here = below.get(path);
99
+ let left = together(here);
100
+ const found: Hop[] = [];
101
+ for (const edge of onward.get(path) ?? []) {
102
+ if (left === 0n) break;
103
+ const target = edge.target();
104
+ if (target === undefined) continue;
105
+ const closer = below.get(target);
106
+ let nearer = 0n;
107
+ for (const [distance, at] of here ?? []) nearer |= at & (closer?.get(distance - 1) ?? 0n);
108
+ // A holder an earlier import already leads to is that one's.
109
+ if ((nearer & left) === 0n) continue;
110
+ left &= ~nearer;
111
+ found.push({ edge, target, holders: nearer });
112
+ }
113
+ hops.set(path, found);
114
+ return found;
115
+ }
116
+
117
+ /** From a module the holder is below, down to it: the steps after the module itself. */
118
+ function down(from: string, bit: Holders): readonly ChainStep[] {
119
+ const steps: ChainStep[] = [];
120
+ const hopAt = (path: string): Hop | undefined =>
121
+ hopsOf(path).find((hop) => (hop.holders & bit) !== 0n);
122
+ for (let hop = hopAt(from); hop !== undefined; hop = hopAt(hop.target)) {
123
+ steps.push({ path: hop.target, specifier: hop.edge.specifier });
124
+ }
125
+ return steps;
126
+ }
127
+
128
+ /** The scanned edges into the modules each holder is below, in the order given. */
129
+ const cuts = new Map(outside.map((holder): [string, Hop[]] => [holder, []]));
130
+ for (const edge of edges) {
131
+ const target = (scanned.has(edge.from) ? edge.target() : undefined) ?? '';
132
+ const holders = together(below.get(target));
133
+ for (const bit of bitsOf(holders))
134
+ cuts.get(outside[bit] ?? '')?.push({ edge, target, holders });
135
+ }
136
+
137
+ return (holder) =>
138
+ scanned.has(holder)
139
+ ? [[{ path: holder }]]
140
+ : (cuts.get(holder) ?? []).map(({ edge, target }) => [
141
+ { path: edge.from },
142
+ { path: target, specifier: edge.specifier },
143
+ ...down(target, bits.get(holder) ?? 0n),
144
+ ]);
145
+ }
@@ -0,0 +1,106 @@
1
+ // Which service a served role's signals name, and which build (#1361). The OTel env first —
2
+ // `OTEL_SERVICE_NAME`, then `service.name` in `OTEL_RESOURCE_ATTRIBUTES` — set before the app's
3
+ // config loads so the spans its load opens carry it; then the app's `name` only where the env was
4
+ // silent. Version: `service.version` in the attributes, else the build id, else `APP_VERSION`.
5
+
6
+ import { appVersion, logger } from '@ultimat3/core';
7
+ import { installTelemetry } from '@ultimat3/core/adapter';
8
+
9
+ type Env = Readonly<Record<string, string | undefined>>;
10
+
11
+ const ATTRIBUTES_KEY = 'OTEL_RESOURCE_ATTRIBUTES';
12
+
13
+ /** Empty is unset: a platform that exports a key bare has named nothing. */
14
+ const said = (value: string | undefined): string | undefined =>
15
+ value === undefined || value.trim() === '' ? undefined : value.trim();
16
+
17
+ /** One `key=value` pair, or `undefined` when it is malformed (no key, no `=`, a bad escape). */
18
+ function pairOf(entry: string): readonly [string, string] | undefined {
19
+ const at = entry.indexOf('=');
20
+ const key = at === -1 ? '' : entry.slice(0, at).trim();
21
+ if (key === '') return undefined;
22
+ try {
23
+ return [key, decodeURIComponent(entry.slice(at + 1).trim())];
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * `OTEL_RESOURCE_ATTRIBUTES` as the OTel SDK spec reads it: comma-separated `key=value`, values
31
+ * percent-decoded. One malformed pair discards the WHOLE value with one warning — the spec's rule,
32
+ * and the safe one: a half-read list could name the service from the wrong pair.
33
+ */
34
+ export function resourceAttributes(env: Env): ReadonlyMap<string, string> {
35
+ const raw = said(env[ATTRIBUTES_KEY]);
36
+ const out = new Map<string, string>();
37
+ if (raw === undefined) return out;
38
+ for (const entry of raw.split(',')) {
39
+ if (entry.trim() === '') continue;
40
+ const pair = pairOf(entry);
41
+ if (pair === undefined) {
42
+ // The value is never echoed: a deploy may carry anything in a resource attribute.
43
+ logger.warn('ultimate otel resource attributes ignored', {
44
+ cause: `${ATTRIBUTES_KEY} holds a pair that is not key=value with a percent-encoded value, so the whole variable is ignored`,
45
+ fix: `${ATTRIBUTES_KEY}=service.name=<name>,service.version=<version> # comma-separated, values percent-encoded`,
46
+ });
47
+ return new Map();
48
+ }
49
+ out.set(pair[0], pair[1]);
50
+ }
51
+ return out;
52
+ }
53
+
54
+ export interface ServiceIdentity {
55
+ /** Absent when the env names no service: the app's `name` fills it after the config loads. */
56
+ readonly serviceName?: string;
57
+ readonly serviceVersion: string;
58
+ }
59
+
60
+ /**
61
+ * What the env alone can say, before the config or the build id is resolved. A stamped
62
+ * `BUILD_ID` is read here already, so a span opened while the app loads carries the build.
63
+ */
64
+ export function serviceIdentityFromEnv(env: Env): ServiceIdentity {
65
+ return identityOf(env, resourceAttributes(env));
66
+ }
67
+
68
+ /** Parsed once per boot by its caller: a malformed value warns once, not once per reader. */
69
+ function identityOf(env: Env, attributes: ReadonlyMap<string, string>): ServiceIdentity {
70
+ const name = said(env['OTEL_SERVICE_NAME']) ?? said(attributes.get('service.name'));
71
+ const serviceVersion =
72
+ said(attributes.get('service.version')) ?? said(env['BUILD_ID']) ?? appVersion(env);
73
+ return name === undefined ? { serviceVersion } : { serviceName: name, serviceVersion };
74
+ }
75
+
76
+ export interface ServiceIdentityBoot {
77
+ readonly named: (appName: string | undefined) => void;
78
+ readonly built: (buildId: string) => void;
79
+ readonly release: () => void;
80
+ }
81
+
82
+ /**
83
+ * Names the service from the env, before anything else in the boot runs, and answers the two
84
+ * later steps and the release. `named(app)` is the config's turn; `built(id)` the resolved build
85
+ * id's — both lose to what the env said.
86
+ */
87
+ export function configureServiceIdentity(env: Env): ServiceIdentityBoot {
88
+ const attributes = resourceAttributes(env);
89
+ const early = identityOf(env, attributes);
90
+ const releases = [installTelemetry(early)];
91
+ const versionSaid = said(attributes.get('service.version')) !== undefined;
92
+ return {
93
+ named(appName) {
94
+ if (early.serviceName !== undefined || appName === undefined) return;
95
+ releases.push(installTelemetry({ serviceName: appName }));
96
+ },
97
+ built(buildId) {
98
+ if (versionSaid || buildId === '') return;
99
+ releases.push(installTelemetry({ serviceVersion: buildId }));
100
+ },
101
+ release() {
102
+ // Newest first: each release restores what its own call found.
103
+ for (const release of releases.splice(0).reverse()) release();
104
+ },
105
+ };
106
+ }
package/src/serve-boot.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  import type { DrainConfig, LifecycleOptions, Role } from '@ultimat3/core';
11
11
  import { configureLifecycle, logger, UltimateError } from '@ultimat3/core';
12
12
  import { installBuildId } from '@ultimat3/core/adapter';
13
+ import { configureOutboundProxy } from '@ultimat3/core/outbound';
13
14
  import { loadAppConfig } from './app-config-load';
14
15
  import { armFailureCapture } from './failure-capture-boot';
15
16
  import type { MetricsEndpoint } from './metrics-endpoint';
@@ -28,6 +29,7 @@ import { releaseOrThrow, startServices } from './runtime-services';
28
29
  import type { BootTimeline } from './serve-boot-phases';
29
30
  import { bootTimeline } from './serve-boot-phases';
30
31
  import { type BootProbe, openBootProbe } from './serve-boot-probe';
32
+ import { configureServiceIdentity, type ServiceIdentityBoot } from './serve-boot-telemetry';
31
33
  import { bootWarningConcerns, warnAtBoot } from './serve-boot-warnings';
32
34
  import { loadDrainConfig, loadHealthConfig } from './serve-drain';
33
35
  import {
@@ -103,9 +105,19 @@ export async function bootServing(boot: {
103
105
  readonly metrics: MetricsEndpoint;
104
106
  }): Promise<ServedApp> {
105
107
  const { options } = boot;
108
+ // Before the config loads, from the env alone (#1361): a span the app's config opens already
109
+ // names the service the deploy named. The app's `name` and the build id fill in below.
110
+ // FIRST in the unwind list, so it is released last: the exporter's final flush still names it.
111
+ const identity = configureServiceIdentity(options.env);
112
+ boot.acquired.unshift(identity.release);
106
113
  // Before anything is started or created: a role `app.config.ts` does not list is refused while
107
114
  // there is nothing to unwind but the scrape listener.
108
- assertRoleDeclared(boot.role, await loadAppConfig(options.root));
115
+ const appConfig = await loadAppConfig(options.root);
116
+ identity.named(appConfig?.name);
117
+ assertRoleDeclared(boot.role, appConfig);
118
+ // `outbound.proxy`, before any service or app module can send: every `outbound()` call that
119
+ // names no proxy of its own — APNs, FCM, OAuth, a webhook — goes through it from here on.
120
+ boot.acquired.push(configureOutboundProxy(appConfig?.outbound));
109
121
  // The role's own grace FIRST, before the services: the schema wait runs inside them, and a worker
110
122
  // SIGTERMed mid-wait sat through web's readiness grace. `app.config.ts`'s `drain` section is
111
123
  // applied over this once the app is loaded (`bootRoles`).
@@ -136,6 +148,7 @@ export async function bootServing(boot: {
136
148
  timeline.phase('services');
137
149
  return bootRoles({
138
150
  ...boot,
151
+ identity,
139
152
  runtime,
140
153
  timeline,
141
154
  ...(tls === undefined ? {} : { tls }),
@@ -170,6 +183,8 @@ export function refuseHalfLoadedApp(role: Role, findings: readonly Finding[]): v
170
183
  async function bootRoles(boot: {
171
184
  readonly options: ServeOptions;
172
185
  readonly role: Role;
186
+ /** The service identity `bootServing` named from the env and the config; the build id is ours. */
187
+ readonly identity: ServiceIdentityBoot;
173
188
  readonly runtime: RunningServices;
174
189
  readonly acquired: (() => void | Promise<void>)[];
175
190
  /** The scrape listener `serveApp` opened before any of this work; `startRoles` adopts it. */
@@ -187,11 +202,14 @@ async function bootRoles(boot: {
187
202
  // shipped chart and nothing read it, so every deployment that configured a collector got an empty
188
203
  // dashboard. `x dev` keeps its own recorder — the `/_x` timeline is a different sink with a
189
204
  // different lifetime — so this is the production boot's alone (axiom 6).
190
- // At the FRONT of the unwind list, so the stop and a failed boot's rollback alike release it
191
- // last: the drain's own spans and the final counter snapshot still have somewhere to go.
205
+ // At the FRONT of the unwind list (behind only the service identity), so the stop and a failed
206
+ // boot's rollback alike release it last but one: the drain's own spans and the final counter
207
+ // snapshot still have somewhere to go, under the service's own name.
192
208
  // The config first, for `database.slowStatementMs`: `app.config.ts` declares, it registers no hook.
193
209
  const appConfig = await loadAppConfig(options.root);
194
- acquired.unshift(
210
+ acquired.splice(
211
+ acquired.indexOf(boot.identity.release) + 1,
212
+ 0,
195
213
  startOtlpExport(options.env, { slowStatementMs: appConfig?.database.slowStatementMs }),
196
214
  );
197
215
  // The image's compiled stylesheets, before the first page is imported — importing one IS
@@ -223,6 +241,7 @@ async function bootRoles(boot: {
223
241
  // Core's one copy: `ctx.buildId` (a job's audit row), `/healthz` and `/readyz` read this, never
224
242
  // `BUILD_ID` — an unstamped image's `''` would otherwise disagree with `x-ultimate-build`.
225
243
  acquired.push(installBuildId(buildId));
244
+ boot.identity.built(buildId);
226
245
  timeline.phase('build-id');
227
246
  // Before the first socket opens: everything above this line fails loudly into the container's
228
247
  // own logs, everything below it is a served request, a claimed job or a routed frame.
@@ -0,0 +1,70 @@
1
+ // Is a captured picture a picture of anything? Judged by its PIXELS, never its byte count: a flat
2
+ // 36 px button is a few hundred honest bytes, and a blank 1280x800 crop compresses to about as few.
3
+ // One pure verdict over the decoded raster, so a test can hand it both and see them told apart.
4
+
5
+ import type { Raster } from '@ultimat3/core';
6
+ import { decodeImage, transformImageBytes } from '@ultimat3/core';
7
+
8
+ /**
9
+ * The widest spread, per channel, a crop may have and still be ONE colour. Not 0: a GPU
10
+ * compositor dithers a flat fill by a level or two, and that noise is not content. A hairline
11
+ * border, a glyph or a focus ring against the page is tens of levels — an order of magnitude past it.
12
+ */
13
+ export const BLANK_CHANNEL_SPREAD = 2;
14
+
15
+ /** The bytes as 8-bit RGBA: whatever PNG flavour the browser wrote, Bun re-encodes it to one. */
16
+ async function rasterOf(bytes: Uint8Array): Promise<Raster | null> {
17
+ try {
18
+ return decodeImage(await transformImageBytes(bytes, { format: 'png' }));
19
+ } catch {
20
+ // The caller's refusal is the report: bytes no decoder reads are "not an image", whichever
21
+ // `X_IMAGE_*` code the decoder named.
22
+ return null;
23
+ }
24
+ }
25
+
26
+ export interface BlankShot {
27
+ readonly reason: string;
28
+ /** No decoder read the bytes: the browser's fault, not the crop's. */
29
+ readonly undecodable: boolean;
30
+ }
31
+
32
+ /**
33
+ * Why the picture shows nothing, or `undefined` when it shows something. Three refusals: bytes no
34
+ * decoder reads, a crop with no opaque pixel, and a crop every pixel of which is one colour (within
35
+ * `BLANK_CHANNEL_SPREAD`). Anything with two colours in it — a border on a background, a glyph —
36
+ * passes, however few bytes it took.
37
+ */
38
+ export async function blankShotReason(bytes: Uint8Array): Promise<BlankShot | undefined> {
39
+ const raster = await rasterOf(bytes);
40
+ if (raster === null) {
41
+ return {
42
+ reason: `produced ${bytes.byteLength} bytes no image decoder reads — that is not an image`,
43
+ undecodable: true,
44
+ };
45
+ }
46
+ const { pixels, width, height } = raster;
47
+ const low = [255, 255, 255, 255];
48
+ const high = [0, 0, 0, 0];
49
+ for (let i = 0; i < pixels.length; i += 4) {
50
+ for (let c = 0; c < 4; c += 1) {
51
+ const value = pixels[i + c] ?? 0;
52
+ if (value < (low[c] ?? 0)) low[c] = value;
53
+ if (value > (high[c] ?? 0)) high[c] = value;
54
+ }
55
+ }
56
+ if ((high[3] ?? 0) === 0) {
57
+ return {
58
+ reason: `produced a ${width}x${height} picture every pixel of which is fully transparent`,
59
+ undecodable: false,
60
+ };
61
+ }
62
+ const spread = Math.max(...high.map((value, c) => value - (low[c] ?? 0)));
63
+ if (spread <= BLANK_CHANNEL_SPREAD) {
64
+ return {
65
+ reason: `produced a ${width}x${height} picture every pixel of which is one colour (rgba ${low.join(',')}) — nothing was painted in the crop`,
66
+ undecodable: false,
67
+ };
68
+ }
69
+ return undefined;
70
+ }