@ultimat3/core 31.38.1 → 31.40.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.
package/CLAUDE.md CHANGED
@@ -63,11 +63,13 @@ top-level `UltimateError` use in `error-codes.ts`.
63
63
  | `allowHosts` | `host-rules.ts` | a wildcard admits no inward literal, no `localhost`/`*.localhost`; exact rules do |
64
64
  | which surface a route lives on, how it renders, caches offline and hydrates | `route-vocabulary.ts` (`SURFACES`, `RENDER_MODES`, `OFFLINE_STRATEGIES`, `HYDRATE_STRATEGIES`) | every union is `(typeof ARRAY)[number]`, pinned in `type-pins.ts`; `scripts/render-modes.test.ts` refuses a second declaration. Re-export it, never restate it; `@ultimat3/render` re-exports the `Surface` type only, never `SURFACES` (`X_HELPER_COPY`) |
65
65
  | which of two route patterns wins a pathname | `route-rank.ts` (`routeRank`) | the request router's order as one integer: segment by segment, literal 3 > `:param` 2 > `*catch-all` 1, ENDED 4, packed base 5 over 22 segments |
66
+ | which pathnames a literal segment owns | `route-literal.ts` (`literalSegmentPattern`) | the ONE compiler, render's `compilePattern` and pwa's worker rules: raw, or each char `encodeURIComponent` escapes as its escape, either hex case. A subset of the router's (raw or decodes-to), never more. `/a\|b` owns `/a%7Cb` |
66
67
  | an `http.path` template (`/orders/:id`) | `route-path-template.ts` (pure, also on `./page`) + `route-path-merge.ts` (`mergePathParams`, `X_HTTP_PATH_INPUT_CONFLICT`) | `action` and `query` both pin one and share a tier; never a copy in either |
67
68
  | `errors:` | `declared-errors.ts`, `-openapi.ts`, `-scan.ts` | ONE copy for `action` and `query`. The HTTP status is passed in (`ErrorStatusOf`): http is above core. The scan is test-time only |
68
69
  | a session's loss, an island's poll | `session-lost.ts`, `visible-interval.ts` | the ONE poll an island takes; both on `./page` † |
69
70
  | which rungs a cache ladder has | `cache-vocabulary.ts` (`CACHE_TIERS`) | `@ultimat3/cache`'s read order, imported (no `TIER_ORDER` alias). `isr` is a `RenderMode`, never a tier |
70
71
  | which build of the APP this is | `app-version.ts` (`APP_VERSION`) | one reader, `dev` by default |
72
+ | which build this PROCESS serves | `build-id.ts` (`installBuildId`, `./adapter`; `installedBuildId`) | the boot's one resolver installs it; `ctxOf`, health and the exercise route read it; `'dev'` unbooted. Core never reads `BUILD_ID` |
71
73
  | the values | `env.ts` | `checkEnv().values` holds REAL secrets — printing goes through `maskedEnvValues()` |
72
74
  | `.env.example` | `env-example.ts` | a projection of the schema, never hand-maintained |
73
75
  | loading `.env` | **Bun**, not us | `envFileCandidates()` documents the measured order; there is no `.env.staging` |
package/README.md CHANGED
@@ -71,6 +71,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
71
71
  | `isSameOriginPath(value)` — a path on THIS origin as a browser resolves it: refuses `//host`, `/\host`, a C0 control or DEL (`/\t/evil.example` parses to `//evil.example`) and a dot segment leaving a `//` pathname. The one predicate for every URL precached as an offline answer, `@ultimat3/pwa`'s build included | `config-pwa.ts` |
72
72
  | the closed route vocabulary every renderer names | `route-vocabulary.ts` |
73
73
  | which of two route patterns wins a pathname (`routeRank`) | `route-rank.ts` |
74
+ | the regex a route's literal segment matches a pathname with (`literalSegmentPattern`) | `route-literal.ts` |
74
75
  | runtime roles + `ROLE` resolution | `roles.ts` |
75
76
  | an app's role-scoped boot line — `bootWarning({ code, roles, once?, message, fields })`, said only where a booting role can act on it, `once: 'process'` or `'build'` (the boot installs the per-build store with `installBootWarnings`, on `@ultimat3/core/adapter`) | `boot-warning.ts` |
76
77
  | `Clock` — the only source of "now" | `clock.ts` |
@@ -1036,12 +1037,15 @@ Interfaces (`AuditSink`, `SleepClock`, `ErrorReporter`, `FailureStore`, `SecretS
1036
1037
  built-ins to copy or compose (`systemClock`, `noWaitClock`, `envSecretSource`, `fileSecretSource`,
1037
1038
  `defaultSecretSource`), the error a source raises (`SecretsKeyMissingError`), and the INSTALLERS —
1038
1039
  `installAuditSink` (+ `resetAuditSink`), `installClock`, `installErrorReporter`,
1039
- `installFailureStore`, `installSecretSource` — and `adapterSlot(fallback)`, the one
1040
+ `installFailureStore`, `installSecretSource`, `installBuildId` (+ `installedBuildId`) — and `adapterSlot(fallback)`, the one
1040
1041
  slot every package's installer is built on. Every installer returns its release (`() => void`), which
1041
1042
  removes ITS install alone: installers may stop in any order, and a second release is a no-op.
1042
1043
  `ctxOf()` and the logger read the installed clock at each call, so `runtime.ts`'s `clock` reaches
1043
1044
  every action, query and job; deadlines racing real timers, AWS signing and a bare `uuidV7()` stay
1044
- on the system clock. Their callers are the boot (reading
1045
+ on the system clock. `installBuildId(id)` is the boot's ONE hand-off of the build id it resolved (`BUILD_ID` when
1046
+ stamped and non-empty, else the manifest hash): `ctxOf().buildId`, `/healthz` and `/readyz` read
1047
+ it, never `BUILD_ID` itself, so they name what `x-ultimate-build` names. Unbooted — a bare script,
1048
+ a test — it is `'dev'`. Their callers are the boot (reading
1045
1049
  `apps/<app>/runtime.ts`) and `@ultimat3/testing`; the barrel exports none of them.
1046
1050
 
1047
1051
  ## Supporting exports
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.38.1",
3
+ "version": "31.40.0",
4
4
  "description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -54,6 +54,6 @@
54
54
  "test": "bun test"
55
55
  },
56
56
  "dependencies": {
57
- "@ultimat3/schema": "31.38.1"
57
+ "@ultimat3/schema": "31.40.0"
58
58
  }
59
59
  }
package/src/adapter.ts CHANGED
@@ -9,6 +9,8 @@ export type { AuditRecord, AuditSink } from './audit';
9
9
  export { installAuditSink, resetAuditSink } from './audit';
10
10
  /** The boot's context for `bootWarning`: its roles and per-build store. cli's `startRoles` alone. */
11
11
  export { installBootWarnings } from './boot-warning';
12
+ /** The build id the boot resolved (`BUILD_ID` stamped, else the manifest hash); `'dev'` unbooted. */
13
+ export { installBuildId, installedBuildId } from './build-id';
12
14
  export type { Clock, FrozenClock, SleepClock } from './clock';
13
15
 
14
16
  export type { ErrorReport, ErrorReporter } from './error-reporter';
@@ -0,0 +1,24 @@
1
+ // Single responsibility: the build id this process serves, as the BOOT resolved it — `BUILD_ID`
2
+ // when stamped and non-empty, else the manifest's content hash (cli's `serve-boot.ts`/`dev-boot.ts`).
3
+ // Core never reads `BUILD_ID` itself: its `?? 'dev'` kept the `''` an unstamped image's Dockerfile
4
+ // writes, so `/healthz` and a worker's `ctx.buildId` said `""` while `x-ultimate-build` named the hash.
5
+
6
+ import { adapterSlot } from './adapter-slot';
7
+
8
+ /** Outside any boot — a bare script, a test — there is no build to name. */
9
+ const UNBOOTED_BUILD_ID = 'dev';
10
+
11
+ const builds = /* @__PURE__ */ adapterSlot<string>(() => UNBOOTED_BUILD_ID);
12
+
13
+ /**
14
+ * The boot's one hand-off of the id it resolved — on `@ultimat3/core/adapter` only, as every
15
+ * installer is. Answers the release that removes THIS install and no other, in any order.
16
+ */
17
+ export function installBuildId(id: string): () => void {
18
+ return builds.install(id);
19
+ }
20
+
21
+ /** The id `ctxOf()`, the health report and `x-ultimate-build` agree on; `'dev'` when none installed. */
22
+ export function installedBuildId(): string {
23
+ return builds.current();
24
+ }
package/src/clock.ts CHANGED
@@ -67,10 +67,15 @@ export const liveClock: Clock = /* @__PURE__ */ Object.freeze({
67
67
  monotonic: (): number => (installedClocks.current() ?? systemClock).monotonic(),
68
68
  });
69
69
 
70
+ /**
71
+ * Screened: `new Date('2026-13-01')` is an Invalid Date, not a throw, and a clock stuck at `NaN`
72
+ * hands every reader a comparison that is always false and `uuidV7` an id that is no UUID. Refused
73
+ * where the bad instant enters, at construction and at `set`. A pre-1970 instant is a real one.
74
+ */
70
75
  function toEpochMs(at: Date | number | string): number {
71
- if (at instanceof Date) return at.getTime();
72
- if (typeof at === 'number') return at;
73
- return new Date(at).getTime();
76
+ const ms =
77
+ at instanceof Date ? at.getTime() : typeof at === 'number' ? at : new Date(at).getTime();
78
+ return finiteOption('frozenClock', 'instant', ms);
74
79
  }
75
80
 
76
81
  /**
package/src/context.ts CHANGED
@@ -32,6 +32,7 @@
32
32
 
33
33
  import { type Actor, anonymousActor } from './actor';
34
34
  import { asyncContext } from './async-context';
35
+ import { installedBuildId } from './build-id';
35
36
  import { type Clock, liveClock } from './clock';
36
37
  import { DEFAULT_LOCALE, DEFAULT_TIME_ZONE } from './default-locale';
37
38
  import { isUltimateError, UltimateError } from './errors';
@@ -158,10 +159,6 @@ const requestContext = asyncContext<Ctx>('the request context');
158
159
 
159
160
  const neverAborted = new AbortController().signal;
160
161
 
161
- function buildId(): string {
162
- return process.env['BUILD_ID'] ?? 'dev';
163
- }
164
-
165
162
  export function ctxOf(init: CtxInit = {}): Ctx {
166
163
  const clock = init.clock ?? liveClock;
167
164
  const requestId = init.requestId ?? uuidV7(clock);
@@ -174,7 +171,7 @@ export function ctxOf(init: CtxInit = {}): Ctx {
174
171
  actor: init.actor ?? anonymousActor(),
175
172
  locale: init.locale ?? DEFAULT_LOCALE,
176
173
  tz: init.tz ?? DEFAULT_TIME_ZONE,
177
- buildId: init.buildId ?? buildId(),
174
+ buildId: init.buildId ?? installedBuildId(),
178
175
  role: init.role ?? resolveRole(),
179
176
  clock,
180
177
  now: () => clock.now(),
package/src/ids.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Single responsibility: identifier generation. UUIDv7 is the framework default because
2
2
  // database indexes, cursors and log sorting all want time-ordered keys.
3
3
 
4
+ import { assert } from './assert';
4
5
  import { type Clock, systemClock } from './clock';
5
6
  import { describeValue } from './error-render';
6
7
  import { UltimateError } from './errors';
@@ -20,6 +21,8 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f
20
21
  /** 12-bit counter lives in `rand_a`, seeded low so ~3k ids/ms fit before it overflows. */
21
22
  const COUNTER_SEED_MASK = 0x3ff;
22
23
  const COUNTER_MAX = 0xfff;
24
+ /** `unix_ts_ms` is 48 bits: past it the hex slice wraps, before 0 it has no encoding at all. */
25
+ const MAX_EPOCH_MS = 0xffff_ffff_ffff;
23
26
 
24
27
  let lastEpochMs = -1;
25
28
  let counter = 0;
@@ -105,6 +108,16 @@ function hexOf(byteLength: number): string {
105
108
  */
106
109
  export function uuidV7(clock: Clock = systemClock): string {
107
110
  let epochMs = clock.now().getTime();
111
+ // Before the clamp and before `lastEpochMs` is written: an Invalid Date minted `…-0NaN-7…` and
112
+ // stored `NaN` as the high-water mark, so the next id skipped the clamp and could sort first.
113
+ // `assert` only on the failing branch: its messages would otherwise be built on every id.
114
+ if (!(epochMs >= 0 && epochMs <= MAX_EPOCH_MS)) {
115
+ assert(
116
+ false,
117
+ `uuidV7's clock read ${String(epochMs)} ms: a UUIDv7 holds 0 to 2^48-1 unix ms, so an Invalid Date or a pre-1970 instant has no encoding`,
118
+ "uuidV7(frozenClock('2026-01-01T00:00:00Z')) // a clock at a valid instant on or after 1970",
119
+ );
120
+ }
108
121
  if (epochMs < lastEpochMs) epochMs = lastEpochMs;
109
122
 
110
123
  if (epochMs === lastEpochMs) {
package/src/index.ts CHANGED
@@ -946,6 +946,7 @@ export { retryMemo } from './retry-memo';
946
946
  export { isRetryableStatus, RETRYABLE_STATUSES } from './retryable-status';
947
947
  export type { ResolveRoleOptions, Role, RoleInfo, ScalingSignal } from './roles';
948
948
  export { isRole, ROLE_INFO, ROLES, resolveRole } from './roles';
949
+ export { literalSegmentPattern } from './route-literal';
949
950
  export { HttpPathInputConflictError, mergePathParams } from './route-path-merge';
950
951
  export type { FilledTemplate, TemplateKeyNode } from './route-path-template';
951
952
  export {
package/src/lifecycle.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // phases on SIGTERM — stop accepting, finish in-flight, close resources — under one deadline,
3
3
  // and reports the same /healthz + /readyz state.
4
4
 
5
+ import { installedBuildId } from './build-id';
5
6
  import { type Clock, systemClock } from './clock';
6
7
  import type { ReadinessMode } from './config-health';
7
8
  import { assertReadinessMode } from './config-health';
@@ -404,7 +405,7 @@ export function healthReport(
404
405
  ready: state === 'ready' && (mode === 'process' || dependencies),
405
406
  uptimeMs: Math.round(clock.monotonic() - startedAtMono),
406
407
  inflight,
407
- buildId: process.env['BUILD_ID'] ?? 'dev',
408
+ buildId: installedBuildId(),
408
409
  checks,
409
410
  registered: readinessCheckCount(),
410
411
  };
@@ -0,0 +1,41 @@
1
+ // Single responsibility: a route's LITERAL segment as the one regex source every matcher tests a
2
+ // pathname with — `@ultimat3/render`'s `compilePattern` and `@ultimat3/pwa`'s worker rules. Tier 0
3
+ // beside `routeRank` because both readers are tier 4 and may not import each other. Pure, no I/O.
4
+
5
+ /** What `encodeURIComponent` leaves as written; the WHATWG path serializer escapes a subset of the rest. */
6
+ const UNRESERVED = /^[A-Za-z0-9\-_.!~*'()]$/;
7
+
8
+ const escapeRegex = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
+
10
+ const hexDigit = (digit: string): string =>
11
+ /[A-F]/.test(digit) ? `[${digit}${digit.toLowerCase()}]` : digit;
12
+
13
+ /** `é` as `%[Cc]3%[Aa]9`: its UTF-8 bytes, each escape in either hex case. */
14
+ const escaped = (char: string): string =>
15
+ [...new TextEncoder().encode(char)]
16
+ .map((byte) => {
17
+ const hex = byte.toString(16).toUpperCase().padStart(2, '0');
18
+ return `%${hexDigit(hex.charAt(0))}${hexDigit(hex.charAt(1))}`;
19
+ })
20
+ .join('');
21
+
22
+ /**
23
+ * The regex source (no anchors) for every spelling of a literal segment that the request router
24
+ * (`@ultimat3/http`'s trie: the raw segment, or its percent-decoding) routes to it AND that a writer
25
+ * produces: `canonicalPath` writes `|` as `%7C`, `URL.pathname` writes `é` as `%C3%A9` and `%` as
26
+ * itself, a hand-typed link may use lower-case hex. Each character a writer escapes is matched raw
27
+ * or escaped; one no writer escapes (`p`, `.`) only raw. A `%` matches raw only in the literal's
28
+ * own spelling, because a raw `%` beside an escape does not decode — the router 404s `50%x%7C`.
29
+ */
30
+ export function literalSegmentPattern(segment: string): string {
31
+ const chars = [...segment];
32
+ if (chars.every((char) => UNRESERVED.test(char))) return escapeRegex(segment);
33
+ const decoded = chars
34
+ .map((char) => {
35
+ if (UNRESERVED.test(char)) return escapeRegex(char);
36
+ if (char === '%') return escaped(char);
37
+ return `(?:${escapeRegex(char)}|${escaped(char)})`;
38
+ })
39
+ .join('');
40
+ return segment.includes('%') ? `(?:${escapeRegex(segment)}|${decoded})` : decoded;
41
+ }