@ultimat3/cli 31.51.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 (65) hide show
  1. package/README.md +9 -9
  2. package/package.json +29 -29
  3. package/src/catalog-layout.ts +194 -0
  4. package/src/cmd-i18n-spec.ts +4 -4
  5. package/src/cmd-i18n-split.ts +133 -0
  6. package/src/cmd-i18n.ts +46 -66
  7. package/src/config-redact.ts +20 -4
  8. package/src/db-rollback-pass.ts +4 -1
  9. package/src/dev-child-watch.ts +16 -0
  10. package/src/dev-db-migrate.ts +27 -46
  11. package/src/dev-db-migrator-hold.ts +131 -0
  12. package/src/dev-db-rollback.ts +11 -2
  13. package/src/dev-rebuild-schema.ts +7 -24
  14. package/src/generate-catalog-locales.ts +25 -2
  15. package/src/generate-follow-ups.ts +8 -3
  16. package/src/i18n-audit.ts +17 -33
  17. package/src/i18n-index.ts +108 -31
  18. package/src/i18n-locale-parity.ts +14 -6
  19. package/src/i18n-new-locale.ts +75 -0
  20. package/src/i18n-registration.ts +52 -27
  21. package/src/island-capture.ts +36 -7
  22. package/src/merge-state.ts +3 -2
  23. package/src/messages-floor.ts +2 -0
  24. package/src/messages.ts +2 -0
  25. package/src/serve-boot-telemetry.ts +106 -0
  26. package/src/serve-boot.ts +23 -4
  27. package/src/shot-blank.ts +70 -0
  28. package/src/templates/catalog-barrel.ts +84 -0
  29. package/src/templates/guard-released-forms.ts +2 -1
  30. package/src/templates/guard-untranslated-string.ts +27 -6
  31. package/src/templates/locales.ts +6 -0
  32. package/src/templates/scaffold-gitattributes.ts +9 -2
  33. package/src/templates/scaffold-i18n.ts +10 -6
  34. package/src/templates/shapes/offline.ts +5 -2
  35. package/src/test-ignores.ts +3 -2
  36. package/src/verify-floor.ts +9 -1
  37. package/src/verify-local-only.ts +66 -0
  38. package/src/verify-run.ts +17 -2
  39. package/wiki/Actions.md +1 -1
  40. package/wiki/Auth.md +3 -3
  41. package/wiki/Batching-And-Preloading.md +1 -0
  42. package/wiki/CLI-Reference-Data.md +241 -0
  43. package/wiki/CLI-Reference-Gate.md +572 -0
  44. package/wiki/CLI-Reference-Project.md +414 -0
  45. package/wiki/CLI-Reference-Ship.md +348 -0
  46. package/wiki/CLI-Reference-Tools.md +666 -0
  47. package/wiki/CLI-Reference.md +14 -2225
  48. package/wiki/Compared.md +8 -8
  49. package/wiki/Configuration.md +26 -2
  50. package/wiki/Deployment.md +1 -1
  51. package/wiki/Entities-And-Migrations.md +3 -2
  52. package/wiki/I18n.md +39 -5
  53. package/wiki/Installation.md +1 -1
  54. package/wiki/Jobs-And-Workflows.md +29 -1
  55. package/wiki/Known-Gaps.md +3 -0
  56. package/wiki/Observability.md +15 -1
  57. package/wiki/Outbound-HTTP.md +62 -2
  58. package/wiki/PWA-And-Offline.md +1 -1
  59. package/wiki/Policies-And-Authz.md +10 -0
  60. package/wiki/Realtime.md +29 -2
  61. package/wiki/Static-Assets.md +1 -1
  62. package/wiki/Testing.md +33 -0
  63. package/wiki/Theming.md +31 -8
  64. package/wiki/Troubleshooting.md +1 -1
  65. package/wiki/Upgrading.md +5 -1
@@ -25,6 +25,8 @@ import { APP_CATALOGS_PATH } from '@ultimat3/i18n/app-catalogs';
25
25
  import { mountedAdminKeys } from './admin-catalog-keys';
26
26
  import type { LoadedApp } from './app-load';
27
27
  import { loadApp } from './app-load';
28
+ import type { CatalogLayout } from './catalog-layout';
29
+ import { catalogLocation } from './catalog-layout';
28
30
  import type { DuplicateProbe } from './duplicate-packages';
29
31
  import { duplicateCause, duplicateFinding, findDuplicateInstalls } from './duplicate-packages';
30
32
  import { auditApp } from './i18n-audit';
@@ -33,7 +35,7 @@ import { mailPreviewFindings } from './mail-preview-findings';
33
35
  import type { Finding } from './output';
34
36
  import { findingFrom } from './output';
35
37
  import { quoteArg } from './shell-quote';
36
- import { CATALOG_ROOT, catalogPath } from './templates/locales';
38
+ import { CATALOG_ROOT } from './templates/locales';
37
39
 
38
40
  /** The one package this check probes for a duplicate: its registry is the one it reads. */
39
41
  const I18N_PKG = '@ultimat3/i18n';
@@ -48,8 +50,10 @@ export type AppLoader = (root: string) => Promise<Pick<LoadedApp, 'findings' | '
48
50
 
49
51
  export interface RegistrationInput {
50
52
  readonly root: string;
51
- /** The catalogs on disk, parsed — `packages/i18n/catalogs/*.json`. */
53
+ /** The catalogs on disk, parsed — `packages/i18n/catalogs/*.json` and `catalogs/<locale>/`. */
52
54
  readonly catalogs: Readonly<Record<Locale, Catalog>>;
55
+ /** Each locale's form on disk, so a finding names the file or directory it is about. */
56
+ readonly layout?: CatalogLayout;
53
57
  readonly extraction: Extraction;
54
58
  readonly ignoreUnused: readonly string[];
55
59
  readonly load?: AppLoader;
@@ -105,19 +109,20 @@ export async function checkRegistration(input: RegistrationInput): Promise<Regis
105
109
  const findings: Finding[] =
106
110
  duplicate === undefined ? [] : [duplicateFinding(input.root, duplicate, RECHECK)];
107
111
  for (const gap of gaps) {
108
- const finding = findingFrom(catalogUnregistered(gap));
112
+ const at = catalogLocation(input.layout, gap.locale);
113
+ const finding = findingFrom(catalogUnregistered({ ...gap, file: at }));
109
114
  findings.push(
110
115
  duplicate === undefined
111
- ? { ...finding, ...unregisteredFix(gap.locale, index), at: catalogPath(gap.locale) }
116
+ ? { ...finding, ...unregisteredFix(gap.locale, index), at }
112
117
  : // The registry's own fix names a source edit — move the `defineCatalogs()` call — that an
113
118
  // agent following it performs on a file that is already right (one adopter, 2026-09-05).
114
119
  // With a duplicate on disk the cause IS the install, so the finding says so and the fix
115
120
  // is the one the duplicate carries.
116
121
  {
117
122
  ...finding,
118
- cause: `${duplicateCause(input.root, duplicate)}; ${gap.missing.length} of ${catalogPath(gap.locale)}'s ${gap.shipped} key(s) registered into the copy the CLI does not read`,
123
+ cause: `${duplicateCause(input.root, duplicate)}; ${gap.missing.length} of ${at}'s ${gap.shipped} key(s) registered into the copy the CLI does not read`,
119
124
  fix: findings[0]?.fix ?? finding.fix,
120
- at: catalogPath(gap.locale),
125
+ at,
121
126
  },
122
127
  );
123
128
  }
@@ -142,7 +147,7 @@ export async function checkRegistration(input: RegistrationInput): Promise<Regis
142
147
  .filter((tag) => !unregisteredSet.has(tag))
143
148
  .sort()) {
144
149
  const missing = unanswered(catalogFor(locale), adminKeys);
145
- if (missing.length > 0) findings.push(adminKeysFinding(locale, missing));
150
+ if (missing.length > 0) findings.push(adminKeysFinding(locale, missing, input.layout));
146
151
  }
147
152
 
148
153
  return {
@@ -180,8 +185,13 @@ const ADMIN_KEYS_WRITTEN =
180
185
  'writes each key above: in the default locale the label x g resource --admin generates, a real string to keep or reword; in any other locale that label inside ⟦…⟧, to translate';
181
186
 
182
187
  /** The finding with the code's own COMMAND and a comment that is true of what it writes. */
183
- function missingKeysFinding(locale: Locale, missing: readonly string[], written: string): Finding {
184
- const finding = findingFrom(catalogMissingKeys(locale, missing));
188
+ function missingKeysFinding(
189
+ locale: Locale,
190
+ missing: readonly string[],
191
+ written: string,
192
+ layout: CatalogLayout | undefined,
193
+ ): Finding {
194
+ const finding = findingFrom(catalogMissingKeys(locale, missing, catalogLocation(layout, locale)));
185
195
  const [command = finding.fix] = finding.fix.split(' #');
186
196
  return { ...finding, fix: `${command} # ${written}` };
187
197
  }
@@ -192,12 +202,16 @@ function missingKeysFinding(locale: Locale, missing: readonly string[], written:
192
202
  * too (`cmd-i18n.ts`), nested. The hand edit this used to name was a dotted key, which
193
203
  * `loadCatalog` refuses as `X_CATALOG_INVALID`.
194
204
  */
195
- function adminKeysFinding(locale: Locale, missing: readonly string[]): Finding {
196
- const path = catalogPath(locale);
205
+ function adminKeysFinding(
206
+ locale: Locale,
207
+ missing: readonly string[],
208
+ layout: CatalogLayout | undefined,
209
+ ): Finding {
210
+ const path = catalogLocation(layout, locale);
197
211
  const shown = missing.slice(0, 12).map((key) => `"${key}"`);
198
212
  const more = missing.length > shown.length ? `, +${missing.length - shown.length} more` : '';
199
213
  return {
200
- ...missingKeysFinding(locale, missing, ADMIN_KEYS_WRITTEN),
214
+ ...missingKeysFinding(locale, missing, ADMIN_KEYS_WRITTEN, layout),
201
215
  cause: `${path} is missing ${missing.length} key(s) the mounted admin renders (defineAdmin derives them, so no source file names one): ${shown.join(', ')}${more}`,
202
216
  at: path,
203
217
  };
@@ -230,10 +244,12 @@ export function unregisteredFix(
230
244
  index: string | undefined,
231
245
  ): { readonly fix?: string } {
232
246
  if (index === undefined) return {};
233
- // The index is GENERATED (`i18nIndex`), so the one spelling that matters is the import it writes
234
- // — `catalogs/<tag>.json`. Matching a bare tag instead would read `en` out of the word `key` and
235
- // report a registered locale as unregistered, which is the direction that costs trust.
236
- if (index.includes(`${CATALOG_ROOT.split('/').pop() ?? 'catalogs'}/${locale}.json`)) return {};
247
+ // The index is GENERATED (`i18nIndex`), so the spellings that matter are the imports it writes
248
+ // — `catalogs/<tag>.json`, or `catalogs/<tag>'` for a split locale's barrel. Matching a bare tag
249
+ // instead would read `en` out of the word `key` and report a registered locale as unregistered,
250
+ // which is the direction that costs trust.
251
+ const dir = CATALOG_ROOT.split('/').pop() ?? 'catalogs';
252
+ if (index.includes(`${dir}/${locale}.json`) || index.includes(`${dir}/${locale}'`)) return {};
237
253
  return {
238
254
  fix: `x i18n sync ${quoteArg(locale)} # re-derives ${APP_CATALOGS_PATH} from the catalogs on disk`,
239
255
  };
@@ -305,21 +321,24 @@ export function withPlaceholdersMissing(
305
321
  * placeholder. Built here rather than in `cmd-i18n.ts` because `x verify`'s `i18n` step reports
306
322
  * the same finding, and a second construction of it is two renderers of one fact waiting to drift.
307
323
  */
308
- export function missingKeyFindings(report: ExtractReport): readonly Finding[] {
324
+ export function missingKeyFindings(
325
+ report: ExtractReport,
326
+ layout?: CatalogLayout,
327
+ ): readonly Finding[] {
309
328
  const missing = report.locales
310
329
  .filter((audit) => audit.missing.length > 0)
311
330
  .map((audit) => ({
312
- ...missingKeysFinding(audit.locale, audit.missing, SOURCE_KEYS_WRITTEN),
313
- at: catalogPath(audit.locale),
331
+ ...missingKeysFinding(audit.locale, audit.missing, SOURCE_KEYS_WRITTEN, layout),
332
+ at: catalogLocation(layout, audit.locale),
314
333
  }));
315
334
  // A select or ordinal family with no `_other` renders `⟦key⟧` for every value it does not name:
316
335
  // the same loud miss, one family wide, so the same gate refuses it.
317
336
  const incomplete = report.locales
318
337
  .filter((audit) => audit.incomplete.length > 0)
319
- .map((audit) => ({
320
- ...findingFrom(familyIncomplete(audit.locale, audit.incomplete)),
321
- at: catalogPath(audit.locale),
322
- }));
338
+ .map((audit) => {
339
+ const at = catalogLocation(layout, audit.locale);
340
+ return { ...findingFrom(familyIncomplete(audit.locale, audit.incomplete, at)), at };
341
+ });
323
342
  return [...missing, ...incomplete];
324
343
  }
325
344
 
@@ -333,12 +352,18 @@ export function missingKeyFindings(report: ExtractReport): readonly Finding[] {
333
352
  * have, and a string nobody translated.
334
353
  */
335
354
  export async function catalogFindings(root: string): Promise<readonly Finding[]> {
336
- const { report, catalogs, extraction, ignoreUnused } = await auditApp(root);
337
- const registration = await checkRegistration({ root, catalogs, extraction, ignoreUnused });
355
+ const { report, catalogs, extraction, ignoreUnused, layout } = await auditApp(root);
356
+ const registration = await checkRegistration({
357
+ root,
358
+ catalogs,
359
+ extraction,
360
+ ignoreUnused,
361
+ layout,
362
+ });
338
363
  return [
339
- ...missingKeyFindings(withPlaceholdersMissing(report, catalogs)),
364
+ ...missingKeyFindings(withPlaceholdersMissing(report, catalogs), layout),
340
365
  ...registration.findings,
341
- ...localeParityFindings(catalogs),
366
+ ...localeParityFindings(catalogs, layout),
342
367
  // The app is loaded by the audit above, so every `defineMail({ preview })` is registered.
343
368
  ...mailPreviewFindings(Object.keys(catalogs)),
344
369
  ];
@@ -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);
@@ -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':
@@ -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
+ }
@@ -0,0 +1,84 @@
1
+ // The module a split locale's directory holds beside its namespace files: each file imported and
2
+ // set at the key path its name stands for, so `packages/i18n/src/index.ts` imports one locale as
3
+ // one object and `typeof` it is still the typed key space. Derived from the file list alone, so
4
+ // every writer re-derives it and none can drift from another.
5
+
6
+ import { catalogFilePrefix } from '@ultimat3/i18n';
7
+ import { pascal } from './naming';
8
+
9
+ /** The export every barrel declares — `import { catalog as en } from '../catalogs/en'`. */
10
+ export const BARREL_EXPORT = 'catalog';
11
+
12
+ interface Node {
13
+ binding?: string;
14
+ readonly children: Map<string, Node>;
15
+ }
16
+
17
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
18
+
19
+ /** `'my-ns'` where a segment is not an identifier; bare where it is, as Biome formats it. */
20
+ const property = (segment: string): string => (IDENTIFIER.test(segment) ? segment : `'${segment}'`);
21
+
22
+ /**
23
+ * One binding per file, `ns` + its prefix in PascalCase: `site/home.json` → `nsSiteHome`. The
24
+ * prefix keeps every binding clear of a reserved word (`default.json`, `new.json`) and of a leading
25
+ * digit (`404.json`); a second file reshaped to the same name takes a counter.
26
+ */
27
+ function bindingsOf(prefixes: readonly string[]): ReadonlyMap<string, string> {
28
+ const taken = new Set<string>();
29
+ const bindings = new Map<string, string>();
30
+ for (const prefix of prefixes) {
31
+ const base = `ns${pascal(prefix.replaceAll('.', '-'))}`;
32
+ let binding = base;
33
+ for (let n = 2; taken.has(binding); n += 1) binding = `${base}${n}`;
34
+ taken.add(binding);
35
+ bindings.set(prefix, binding);
36
+ }
37
+ return bindings;
38
+ }
39
+
40
+ /** A node as an expression: a file alone is its binding; children make an expanded object. */
41
+ function render(node: Node, indent: string): string {
42
+ if (node.children.size === 0) return node.binding ?? '{}';
43
+ const inner = `${indent} `;
44
+ const lines = node.binding === undefined ? [] : [`${inner}...${node.binding},`];
45
+ for (const [segment, child] of node.children) {
46
+ lines.push(`${inner}${property(segment)}: ${render(child, inner)},`);
47
+ }
48
+ return `{\n${lines.join('\n')}\n${indent}}`;
49
+ }
50
+
51
+ /**
52
+ * The barrel for a locale directory holding `files` (names relative to it: `billing.json`,
53
+ * `site/home.json`). Imports in file-name order — Biome's import sort is told to leave them, as
54
+ * it puts `site/home.json` before `site.json` by a rule no writer here restates — and every object
55
+ * expanded one entry per line: the shape Biome's formatter keeps, and the one `x merge-driver`
56
+ * merges when two branches each add a namespace.
57
+ */
58
+ export function catalogBarrel(files: readonly string[]): string {
59
+ const names = [...new Set(files)].sort();
60
+ const prefixes = names.map(catalogFilePrefix);
61
+ const bindings = bindingsOf(prefixes);
62
+ const root: Node = { children: new Map() };
63
+ for (const prefix of [...prefixes].sort()) {
64
+ let node = root;
65
+ for (const segment of prefix.split('.')) {
66
+ const child = node.children.get(segment) ?? { children: new Map() };
67
+ node.children.set(segment, child);
68
+ node = child;
69
+ }
70
+ const binding = bindings.get(prefix);
71
+ if (binding !== undefined) node.binding = binding;
72
+ }
73
+ const imports = names.map((name, index) => {
74
+ const prefix = prefixes[index] ?? '';
75
+ return `import ${bindings.get(prefix) ?? ''} from './${name}';`;
76
+ });
77
+ const block = imports.length === 0 ? '' : `${imports.join('\n')}\n\n`;
78
+ return `// Generated from the namespace files beside it — never hand-edited: \`bunx x i18n split\` and
79
+ // every x i18n command re-derive it. Each file sits at the key path its name stands for.
80
+ // biome-ignore-all assist/source/organizeImports: in file-name order, the order every writer derives
81
+
82
+ ${block}export const ${BARREL_EXPORT} = ${render(root, '')};
83
+ `;
84
+ }
@@ -147,6 +147,7 @@ export const RELEASED_GUARD_FORMS: Readonly<
147
147
  ['w7as1ib1ido8', 'error'],
148
148
  ],
149
149
  'untranslated-string': [
150
+ ['14xfnj5h9tq91', 'error'],
150
151
  ['211cleyx8cmgn', 'error'],
151
152
  ['2tmea7cmz7rvr', 'error'],
152
153
  ['2x85ib5eqdxzi', 'error'],
@@ -191,6 +192,6 @@ export const RELEASED_GUARD_TEST_FORMS: Readonly<Record<string, readonly string[
191
192
  'undeclared-custom-property': ['30bi2v92swukf', 'svuf8sm14fm8'],
192
193
  'undeclared-env': ['38run3rew6y0c', '8xdp7gp7hol7'],
193
194
  'undefined-style-class': ['1uy88gpk5k8p8', '2sy8me3i3bmzw'],
194
- 'untranslated-string': ['30q3u45cey2eq', 'cgvfv231gnvg', 'kdo3fxwgix3j'],
195
+ 'untranslated-string': ['30q3u45cey2eq', '3bocce437rxn7', 'cgvfv231gnvg', 'kdo3fxwgix3j'],
195
196
  'unzoned-date': ['1m46q3h8t4v7v', '1siep3fqscks4', '20x6l238r09jk', '3jzdaqcytkgil'],
196
197
  };