@ultimat3/core 31.26.0 → 31.28.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/README.md CHANGED
@@ -53,7 +53,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
53
53
  | typed env validated at boot | `env.ts` |
54
54
  | `.env.example` rendered from that schema, and its drift check | `env-example.ts` |
55
55
  | named environments + `ULTIMATE_ENV` resolution | `environment.ts` |
56
- | which store backs a seam — `storeMode(env)`: `memory` under `test`, `database` everywhere else | `store-mode.ts` |
56
+ | which store backs a seam — `storeMode(env)`: `memory` under `test`, `database` everywhere else; `withStoreMode(mode, work)` declares the answer for a process that knows better (`x exercise`: a test process on its scratch database) | `store-mode.ts` |
57
57
  | the boot refusal of a shipped dev signing secret outside development/test — `X_CURSOR_SECRET_DEV` | `dev-secrets.ts` |
58
58
  | a value that cannot be printed by accident | `secret.ts` |
59
59
  | the committed encrypted secrets envelope, AES-256-GCM | `secrets.ts` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.26.0",
3
+ "version": "31.28.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.26.0"
57
+ "@ultimat3/schema": "31.28.0"
58
58
  }
59
59
  }
@@ -111,7 +111,8 @@ export function renderCauseValue(value: unknown): string {
111
111
  * `\u2028` and `\u2029` are included because they terminate a line for a JavaScript parser and
112
112
  * for several log viewers, while `String.prototype.split('\n')` never sees them.
113
113
  *
114
- * The set is every C0 control, DEL, and `\u2028`/`\u2029`. Line breaks are the structural half —
114
+ * The set is every C0 control, DEL, every C1 control (`\u009b` is a one-byte CSI), and
115
+ * `\u2028`/`\u2029`. Line breaks are the structural half —
115
116
  * they add a line to a line-oriented format — and the rest ride along because a terminal reads them
116
117
  * as commands of its own: a raw `\u001b` in a cause is an ANSI escape, so a value could repaint the
117
118
  * screen, hide the line above it or move the cursor over what a reader had already been shown.
@@ -121,7 +122,7 @@ export function renderCauseValue(value: unknown): string {
121
122
  */
122
123
  export function singleLine(text: string): string {
123
124
  // biome-ignore lint/suspicious/noControlCharactersInRegex: escaping them is the point.
124
- return text.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, (char) => {
125
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (char) => {
125
126
  const known = Object.hasOwn(CONTROL_ESCAPES, char) ? CONTROL_ESCAPES[char] : undefined;
126
127
  if (known !== undefined) return known;
127
128
  return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
@@ -98,6 +98,7 @@ export type {
98
98
  RenderPageEvent,
99
99
  StatementAttribution,
100
100
  StorageEvent,
101
+ StorageMultipartEvent,
101
102
  TimedEvent,
102
103
  } from '../instrument-events';
103
104
  export { INSTRUMENT_EVENTS } from '../instrument-events';
@@ -53,12 +53,12 @@ export const FRAMEWORK_ENV: readonly FrameworkEnvName[] = [
53
53
  ...contract('cli', 'APP_URL', 'SITE_ORIGIN', 'SYNC_URL', 'HOST', 'PORT', 'METRICS_PORT'),
54
54
  ...contract('cli', 'NODE_ENV', 'TRUSTED_PROXY_HOPS', 'WORKER_QUEUES', 'SENTRY_DSN'),
55
55
  ...contract('cli', 'S3_ENDPOINT', 'S3_BUCKET', 'S3_REGION', 'S3_FORCE_PATH_STYLE'),
56
- ...contract('cli', 'SCRAPE_CDP_URL'),
56
+ ...contract('cli', 'SCRAPE_CDP_URL', 'TLS_CERT', 'TLS_KEY'),
57
57
  ...toggles('cli', 'OTEL_SDK_DISABLED'),
58
58
  ...internal('cli', 'ULTIMATE_SEED_TIER', 'ULTIMATE_STATE_DIR', 'ULTIMATE_BUILD_CAPTURE'),
59
59
  ...internal('cli', 'ULTIMATE_DEV_CHILD', 'ULTIMATE_DEV_SUPERVISOR_PID', 'X_ENV'),
60
60
  ...internal('cli', 'ULTIMATE_KEEP_GLOBAL_CLI', 'ULTIMATE_VERIFY_STEP', 'CI_RUNNER'),
61
- ...host('cli', 'CI', 'GITHUB_SHA', 'GITHUB_BASE_REF', 'EDITOR', 'VISUAL'),
61
+ ...host('cli', 'CI', 'GITHUB_SHA', 'GITHUB_BASE_REF', 'EDITOR', 'VISUAL', 'USERPROFILE'),
62
62
  ...contract('core', 'ULTIMATE_ENV', 'ROLE', 'BUILD_ID', 'APP_VERSION', 'LOG_LEVEL'),
63
63
  ...contract('core', 'ULTIMATE_CURSOR_SECRET', 'ULTIMATE_SECRETS_KEY'),
64
64
  ...contract('core', 'ULTIMATE_SECRETS_RETIRED_KEYS', 'METRICS_INTERVAL_MS'),
@@ -10,19 +10,45 @@
10
10
  import { asyncContext } from './async-context';
11
11
  import type { FetchLike } from './client-dispatch';
12
12
 
13
- const scope = asyncContext<FetchLike>('the in-process dispatch');
13
+ /** The scope: who answers, and which urls are its to answer (every one, when unsaid). */
14
+ interface InProcess {
15
+ readonly fetchImpl: FetchLike;
16
+ readonly owns?: ((url: string) => boolean) | undefined;
17
+ }
18
+
19
+ const scope = asyncContext<InProcess>('the in-process dispatch');
14
20
 
15
21
  const INSTALLED: unique symbol = Symbol.for('ultimate.in-process-fetch');
16
22
 
23
+ /**
24
+ * A `Request` object as the dispatcher's `(url, init)`: its method, headers and body carried, with
25
+ * `init` laid over it as `fetch` itself would — a bare `init ?? {}` sent a POST as a bodyless GET.
26
+ */
27
+ async function asInit(input: Request, init: RequestInit | undefined): Promise<RequestInit> {
28
+ const request = init === undefined ? input : new Request(input, init);
29
+ const bodyless = request.method === 'GET' || request.method === 'HEAD';
30
+ return {
31
+ method: request.method,
32
+ headers: request.headers,
33
+ redirect: request.redirect,
34
+ signal: request.signal,
35
+ ...(bodyless ? {} : { body: await request.arrayBuffer() }),
36
+ };
37
+ }
38
+
17
39
  /** Wrap `globalThis.fetch` once per process; a re-wrap after someone replaced it wraps theirs. */
18
40
  function install(): void {
19
41
  const current = globalThis.fetch as typeof fetch & { [INSTALLED]?: true };
20
42
  if (current[INSTALLED] === true) return;
21
- const wrapped = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
43
+ const wrapped = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
22
44
  const inProcess = scope.get();
23
45
  if (inProcess === undefined) return current(input, init);
24
46
  const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
25
- return inProcess(url, init ?? {});
47
+ // A url the scope does not own — another host — goes where it would have gone without one.
48
+ if (inProcess.owns !== undefined && !inProcess.owns(url)) return current(input, init);
49
+ if (typeof input === 'string' || input instanceof URL)
50
+ return inProcess.fetchImpl(url, init ?? {});
51
+ return inProcess.fetchImpl(url, await asInit(input, init));
26
52
  };
27
53
  globalThis.fetch = Object.assign(wrapped, current, { [INSTALLED]: true as const });
28
54
  }
@@ -30,10 +56,15 @@ function install(): void {
30
56
  /**
31
57
  * Run `fn` with every `fetch` inside it — so every `clientTransport` call, `queryClient()` and
32
58
  * `rpc()` included — answered by `fetchImpl`: the app's own HTTP pipeline handed a `Request`,
33
- * rather than the network. A caller's explicit `fetchImpl` never reaches `globalThis.fetch` at all,
34
- * so a test's double is never overridden by an ambient scope.
59
+ * rather than the network. `owns` narrows that to the urls it answers true for (the app's own
60
+ * origin); the rest reach the fetch this wrapped. A caller's explicit `fetchImpl` never reaches
61
+ * `globalThis.fetch` at all, so a test's double is never overridden by an ambient scope.
35
62
  */
36
- export function withInProcessFetch<T>(fetchImpl: FetchLike, fn: () => T): T {
63
+ export function withInProcessFetch<T>(
64
+ fetchImpl: FetchLike,
65
+ fn: () => T,
66
+ owns?: (url: string) => boolean,
67
+ ): T {
37
68
  install();
38
- return scope.run(fetchImpl, fn);
69
+ return scope.run({ fetchImpl, owns }, fn);
39
70
  }
package/src/index.ts CHANGED
@@ -536,6 +536,7 @@ export type {
536
536
  StartSpanOptions,
537
537
  StatementAttribution,
538
538
  StorageEvent,
539
+ StorageMultipartEvent,
539
540
  TelemetryOptions,
540
541
  TimedEvent,
541
542
  } from './exports/observability';
@@ -990,7 +991,7 @@ export { singleFlight } from './single-flight';
990
991
  export { ambientClock, noWaitClock } from './sleep-clock';
991
992
  export { endOfLiteral, maskLiterals, QUOTES, stripComments } from './source-mask';
992
993
  export type { StoreMode } from './store-mode';
993
- export { storeMode } from './store-mode';
994
+ export { storeMode, withStoreMode } from './store-mode';
994
995
  export { THEME_STORAGE_KEY } from './theme-storage';
995
996
  export { timingSafeEqual } from './timing-safe-equal';
996
997
  export type { ToolDescriptionSource } from './tool-description';
@@ -144,6 +144,15 @@ export interface StorageEvent extends TimedEvent {
144
144
  readonly bytes?: number | undefined;
145
145
  }
146
146
 
147
+ /**
148
+ * One change to a multipart upload session on a resolved disk: opened, a part stored, assembled
149
+ * into the object at `key`, or dropped with its parts. Signing a part URL or listing parts changes
150
+ * nothing and is no event. `bytes` is the part's, or the assembled object's.
151
+ */
152
+ export interface StorageMultipartEvent extends StorageEvent {
153
+ readonly op: 'create' | 'part' | 'complete' | 'abort';
154
+ }
155
+
147
156
  export interface CacheLookupEvent {
148
157
  readonly tier: string;
149
158
  readonly key: string;
@@ -207,6 +216,7 @@ export interface FrameworkEventMap {
207
216
  'storage.copy': StorageEvent;
208
217
  'storage.delete': StorageEvent;
209
218
  'storage.list': StorageEvent;
219
+ 'storage.multipart': StorageMultipartEvent;
210
220
  'cache.hit': CacheLookupEvent;
211
221
  'cache.miss': CacheLookupEvent;
212
222
  'cache.invalidate': CacheInvalidateEvent;
@@ -259,6 +269,7 @@ export const INSTRUMENT_EVENTS = Object.freeze({
259
269
  'storage.copy': { span: 'client', owner: '@ultimat3/storage' },
260
270
  'storage.delete': { span: 'client', owner: '@ultimat3/storage' },
261
271
  'storage.list': { span: 'client', owner: '@ultimat3/storage' },
272
+ 'storage.multipart': { span: 'client', owner: '@ultimat3/storage' },
262
273
  'cache.hit': { span: 'event', owner: '@ultimat3/cache' },
263
274
  'cache.miss': { span: 'event', owner: '@ultimat3/cache' },
264
275
  'cache.invalidate': { span: 'internal', owner: '@ultimat3/cache' },
@@ -62,7 +62,10 @@ const redactedKeys = new Set<string>([
62
62
  * snake and the header spelling. It names what BEARS a credential and nothing wider, because a
63
63
  * redacted field is one an operator cannot correlate on:
64
64
  *
65
- * - `password` / `passphrase` anywhere — no ordinary field carries the word.
65
+ * - `password` / `passphrase` ANYWHERE — `password1`, `new_password2`, `passwordConfirm` are all
66
+ * plaintext — except the named metadata: a `has`/`is` prefix, and a `policy`, `minLength`,
67
+ * `maxLength`, `length`, `changedAt` or `set` suffix. `pass` / `pwd` as a service's credential
68
+ * (`SMTP_PASS`, `dbPwd`, `pgpass`); the shell's own `PWD` / `OLDPWD` stay readable.
66
69
  * - `secret` as the LAST word (`mfaSecret`, `webhookSecret`, `appSecrets`, `secretAccessKey`), so
67
70
  * `clientSecretEnv` and `secretsPath` — a variable name and a path — stay readable.
68
71
  * - a `token` is a bearer UNLESS its qualifier says it is not: fail closed, with the exceptions
@@ -84,6 +87,7 @@ const redactedKeys = new Set<string>([
84
87
  * `credentialId`, `jwtIssuer`, `cookieName`, `privateKeyId` name a credential, not hold one.
85
88
  * - card verification codes (`cvv`, `cvc2`) as a suffix, and a `pin` only as the WHOLE word
86
89
  * behind an owner qualifier — three letters inside `spinner`, `shipping` or `pinned` are not one.
90
+ * Any other owner (`ADMIN_PIN`, `adminPin`) is `SEGMENT`'s, below; a `passcode` as a suffix.
87
91
  *
88
92
  * Built from constant alternatives with no nested quantifier, so there is no input it backtracks on.
89
93
  */
@@ -96,11 +100,17 @@ const verdicts = new Map<string, boolean>();
96
100
  /** Exported for its own work-count test only (`logger-redact.test.ts`); never on the barrel. */
97
101
  export const CREDENTIAL_NAME = new RegExp(
98
102
  [
99
- 'passw(?:or)?d|passphrase',
100
- 'secrets?$',
101
- '(?:api|private|signing|encryption|master|hmac|secrets?|access|retired)keys?$|accesskeyid$',
103
+ '(?<!^(?:has|is))passw(?:or)?d(?!(?:policy|minlength|maxlength|length|changedat|set)$)|passphrase',
104
+ 'passcodes?(?:hash(?:es)?)?$|(?<!^(?:old)?)pwd$',
105
+ '^(?:db|pg|smtp|mail|redis|mysql|ldap|ftp|sftp|proxy|admin|root|user|api|imap|amqp|mongo)?pass$',
106
+ 'secrets?$|secretkeybase$',
107
+ '(?:api|private|signing|encryption|master|hmac|secrets?|access|retired|tls|ssl|client|license|app|stripe)keys?$|accesskeyid$',
102
108
  '(?:token|key)hash(?:es)?$',
103
- '(?<!idempotency|page|continuation|cursor|sync)token$',
109
+ '(?<!idempotency|page|continuation|cursor|sync|next|resume|start|cancellation)token$',
110
+ 'authorization$|authheader$|^auth$|^npmconfigauth$',
111
+ '^session$|sessid$',
112
+ '(?:totp|mfa|otp)seeds?$',
113
+ 'codeverifier$|clientassertion$|samlresponse$|webhookurls?$',
104
114
  '(?:access|refresh|id|session|reset|bearer|auth|api|csrf|xsrf|captcha|card|verification|invite|magic|magiclink|device|push|workload|oauth)tokens$',
105
115
  'authconfig$|connectionstring$|dsn$',
106
116
  '(?:database|db|redis|replication|nats|smtp|amqp|mongo)ur[li]s?$',
@@ -113,6 +123,41 @@ export const CREDENTIAL_NAME = new RegExp(
113
123
  ].join('|'),
114
124
  );
115
125
 
126
+ /**
127
+ * A short credential word by SEGMENT, which the joined form above cannot see: `ADMIN_PIN` and
128
+ * `adminPin` are `adminpin`, and no list of owners is complete. Asked of the key split at camel
129
+ * humps, `_`, `-` and `.` (`admin_pin`, `connect_sid`), so each word matches only whole and last:
130
+ * a `pin` (or before `code` / `number` / `hash`), a `pass`, a session `sid`, a personal access
131
+ * token `pat` — and `spinner`, `mapping`, `pinned`, `bypass`, `sidebar` and `pattern` stay readable.
132
+ */
133
+ const SEGMENT = /(?:^|_)(?:pin(?:_(?:code|number))?(?:_hash(?:es)?)?|pass(?:_hash)?|sid|pat)$/;
134
+
135
+ /**
136
+ * An env-spelled `*_KEY` (`STRIPE_KEY`, `SENDGRID_KEY`) is key material whatever the provider: a
137
+ * provider list is never complete. Only SCREAMING_SNAKE, because a camel `fooKey` in app data is a
138
+ * lookup far more often than a credential (`cacheKey`, `sortKey`), and those stay on the joined
139
+ * list's qualifiers instead. The lookups an env var does name keep their reading.
140
+ */
141
+ const ENV_KEY = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*_KEYS?$/;
142
+ const LOOKUP_KEY =
143
+ /(?:^|_)(?:CACHE|IDEMPOTENCY|PARTITION|PRIMARY|FOREIGN|SORT|I18N|ROUTING|DEDUPE|SHARD|LOOKUP|OBJECT)_KEYS?$/;
144
+ const isEnvKeyMaterial = (key: string): boolean => ENV_KEY.test(key) && !LOOKUP_KEY.test(key);
145
+
146
+ /** How much of a key's end the segment rules read. */
147
+ const SEGMENT_WINDOW = 64;
148
+
149
+ /** `adminPin` / `ADMIN_PIN` / `PINCode` / `admin-pin` → `admin_pin` / `pin_code`: one word per segment. */
150
+ const segmented = (key: string): string =>
151
+ // The TAIL only: every segment rule ends at `$` and spans under 20 characters, and a key is caller
152
+ // data — the camel-hump pass over 20,000 capitals took 1.2 s. 64 keeps every word whole.
153
+ key
154
+ .slice(-SEGMENT_WINDOW)
155
+ // A lookahead, not `([A-Z]+)([A-Z][a-z])`: the same split, with nothing to backtrack over.
156
+ .replace(/([A-Z])(?=[A-Z][a-z])/g, '$1_')
157
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
158
+ .replace(/[-.]/g, '_')
159
+ .toLowerCase();
160
+
116
161
  /** Mark keys as secret everywhere. `defineEnv()` calls this for every `secret: true` var. */
117
162
  export function redactKeys(keys: Iterable<string>): void {
118
163
  for (const key of keys) redactedKeys.add(key.toLowerCase());
@@ -155,7 +200,11 @@ export function isRedactedKey(key: string): boolean {
155
200
  const known = verdicts.get(key);
156
201
  if (known !== undefined) return known;
157
202
  const lower = key.toLowerCase();
158
- const verdict = redactedKeys.has(lower) || CREDENTIAL_NAME.test(lower.replace(/[_-]/g, ''));
203
+ const verdict =
204
+ redactedKeys.has(lower) ||
205
+ CREDENTIAL_NAME.test(lower.replace(/[_-]/g, '')) ||
206
+ SEGMENT.test(segmented(key)) ||
207
+ isEnvKeyMaterial(key);
159
208
  // Insertion order is age, so the first key is the oldest: FIFO, no bookkeeping per hit. Bounded
160
209
  // because a key is caller data — a request body's own keys reach `redactFields`.
161
210
  if (verdicts.size >= REDACTION_MEMO_SIZE) verdicts.delete(verdicts.keys().next().value ?? '');
@@ -43,6 +43,16 @@ export async function mapBounded<T, R>(
43
43
  fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
44
44
  options: MapBoundedOptions & { readonly settle?: 'first' | undefined },
45
45
  ): Promise<R[]>;
46
+ /**
47
+ * A value typed `MapBoundedOptions` itself — the 31.23 call shape, before `settle` split the
48
+ * overloads. Its `settle` is not known statically, so neither answer is: narrow with
49
+ * `settle: 'first'` or `'all'` at the call for an exact result type.
50
+ */
51
+ export async function mapBounded<T, R>(
52
+ items: readonly T[],
53
+ fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
54
+ options: MapBoundedOptions,
55
+ ): Promise<R[] | PromiseSettledResult<R>[]>;
46
56
  export async function mapBounded<T, R>(
47
57
  items: readonly T[],
48
58
  fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
package/src/store-mode.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  // Which store backs a framework seam in this process — the in-memory one or the database — decided
2
2
  // once. Three apps each wrote the ternary with a different predicate, and under `x dev` one seam
3
- // sat in memory while every repository read the embedded Postgres.
3
+ // sat in memory while every repository read the embedded Postgres. A process that knows better than
4
+ // its environment — `x exercise`, a test process on a migrated scratch database — declares it.
4
5
 
6
+ import { assert } from './assert';
7
+ import { asyncContext } from './async-context';
5
8
  import { resolveEnvironment } from './environment';
6
9
 
7
10
  export const STORE_MODES = ['memory', 'database'] as const;
@@ -9,7 +12,33 @@ export const STORE_MODES = ['memory', 'database'] as const;
9
12
  export type StoreMode = (typeof STORE_MODES)[number];
10
13
 
11
14
  /**
12
- * `memory` under `test`, `database` everywhere else. The environment and never `DATABASE_URL`:
15
+ * The process slot `withStoreMode` writes: the declared mode and the call that declared it. On
16
+ * `globalThis` under a registered symbol rather than a module `let`: an app's modules and the CLI
17
+ * may hold two copies of core, and both must read it.
18
+ */
19
+ const DECLARED: unique symbol = Symbol.for('ultimate.store-mode');
20
+
21
+ interface Declared {
22
+ readonly mode: StoreMode;
23
+ /** The declaring call's identity, in flight in its `work`: what a nested call is inside. */
24
+ readonly owner: object;
25
+ }
26
+
27
+ /** Which declaration the caller's async context is inside — `undefined` outside every one. */
28
+ const inside = asyncContext<object>('the declared store mode');
29
+
30
+ const declared = (): Declared | undefined => {
31
+ const value: unknown = Reflect.get(globalThis, DECLARED);
32
+ if (typeof value !== 'object' || value === null) return undefined;
33
+ const mode: unknown = Reflect.get(value, 'mode');
34
+ const owner: unknown = Reflect.get(value, 'owner');
35
+ if (mode !== 'memory' && mode !== 'database') return undefined;
36
+ return typeof owner === 'object' && owner !== null ? { mode, owner } : undefined;
37
+ };
38
+
39
+ /**
40
+ * The mode `withStoreMode` declared, if any; else `memory` under `test`, `database` everywhere
41
+ * else. The environment and never `DATABASE_URL`:
13
42
  * `x dev` installs the embedded PGlite as the process client and sets no URL, and a container
14
43
  * gets its pool from the URL — both are `database`. `bun test` installs no client at all, so a
15
44
  * statement there would have nothing to reach; that is the one carve-out. An unknown
@@ -19,5 +48,34 @@ export type StoreMode = (typeof STORE_MODES)[number];
19
48
  * process environment, so the caller passes `Bun.env`.
20
49
  */
21
50
  export function storeMode(env: Readonly<Record<string, string | undefined>>): StoreMode {
51
+ const active = declared();
52
+ if (active !== undefined) return active.mode;
22
53
  return resolveEnvironment({ env }) === 'test' ? 'memory' : 'database';
23
54
  }
55
+
56
+ /**
57
+ * `mode` as `storeMode`'s answer for the length of `work`, whatever the environment says — for a
58
+ * process whose stores a module picks at LOAD, so it is process-wide and not async-scoped. Only
59
+ * `x exercise` calls it: a test process (`ULTIMATE_ENV=test`) on a migrated scratch database,
60
+ * where a seam left in memory would make every reach writing it prove nothing. Restored after,
61
+ * thrown or not; nested inside the in-flight one's `work`, the inner one wins until it returns.
62
+ *
63
+ * Any other overlap is refused (`X_INVARIANT`): two declarations side by side restore out of order
64
+ * — A ends and restores nothing, B ends and restores A's — and the process keeps a mode nobody
65
+ * declares any more. One process has one answer, so a second must wait for the first.
66
+ */
67
+ export async function withStoreMode<T>(mode: StoreMode, work: () => Promise<T>): Promise<T> {
68
+ const before = declared();
69
+ assert(
70
+ before === undefined || inside.get() === before.owner,
71
+ `withStoreMode('${mode}') started while withStoreMode('${before?.mode ?? mode}') is in flight and not inside its work: the two would restore out of order`,
72
+ `await withStoreMode('${mode}', work) // after the in-flight one resolves, or from inside its work`,
73
+ );
74
+ const owner = {};
75
+ Reflect.set(globalThis, DECLARED, { mode, owner } satisfies Declared);
76
+ try {
77
+ return await inside.run(owner, work);
78
+ } finally {
79
+ Reflect.set(globalThis, DECLARED, before);
80
+ }
81
+ }