@objectstack/types 16.1.0 → 17.0.0-rc.1
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/CHANGELOG.md +2656 -0
- package/dist/index.d.mts +420 -5
- package/dist/index.d.ts +420 -5
- package/dist/index.js +156 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +147 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -4
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
+
import { TenancyPosture } from '@objectstack/spec/security';
|
|
2
|
+
import { ErrorCode, ApiError } from '@objectstack/spec/api';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Degraded-boot reporting, shared by every subsystem that can be told to boot
|
|
6
|
+
* without a datasource it needs.
|
|
7
|
+
*
|
|
8
|
+
* Two of them exist today and they opt in through the *same* operator flag
|
|
9
|
+
* (`OS_ALLOW_DRIVER_CONNECT_FAILURE`, see {@link resolveAllowDriverConnectFailure}):
|
|
10
|
+
*
|
|
11
|
+
* - `ObjectQLEngine.init()` — a boot-registered driver whose `connect()`
|
|
12
|
+
* rejected (framework#3741).
|
|
13
|
+
* - `DatasourceConnectionService` — a declared datasource that objects bind to
|
|
14
|
+
* explicitly, or an `external` one with `validation.onMismatch:'fail'`,
|
|
15
|
+
* that could not be connected (framework#3758).
|
|
16
|
+
*
|
|
17
|
+
* They live in different packages but owe the operator the same thing: the
|
|
18
|
+
* degraded state must be impossible to miss.
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* Emit the degraded-boot banner on a channel the host cannot accidentally
|
|
22
|
+
* silence.
|
|
23
|
+
*
|
|
24
|
+
* `OS_ALLOW_DRIVER_CONNECT_FAILURE` only justifies itself if the state it opts
|
|
25
|
+
* into is impossible to miss — and a logger-only banner is missable, because
|
|
26
|
+
* the logger answers to a level the operator sets. `Logger.write()` returns
|
|
27
|
+
* before emitting anything when the record is below `config.level`, so at
|
|
28
|
+
* `--log-level error`, `fatal`, or `silent` this `warn` never reaches ANY
|
|
29
|
+
* stream. A production host running at `error` is exactly the deployment this
|
|
30
|
+
* flag exists for, and is exactly where the banner would vanish. Writing to
|
|
31
|
+
* stderr as well is the same belt-and-braces the kernel already uses for
|
|
32
|
+
* plugin startup failures.
|
|
33
|
+
*
|
|
34
|
+
* A second reason used to be load-bearing and no longer is: `os serve` blanked
|
|
35
|
+
* ALL of stdout while the kernel booted, and `Logger` routes `warn` to stdout,
|
|
36
|
+
* so a boot-phase banner was swallowed at every level. That was framework#4012
|
|
37
|
+
* and is fixed — the boot window buffers and replays `warn`-and-above instead
|
|
38
|
+
* of discarding it. Do not re-derive this helper's necessity from the
|
|
39
|
+
* boot-quiet capture; the level filter is what keeps it alive.
|
|
40
|
+
*
|
|
41
|
+
* Best-effort and never throws: falls back to `console.error`, then to silence
|
|
42
|
+
* on runtimes that have neither (the logger still carries the structured
|
|
43
|
+
* record either way).
|
|
44
|
+
*/
|
|
45
|
+
declare function emitDegradedBootBanner(message: string): void;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Environment-variable helpers shared across `@objectstack/*` packages.
|
|
49
|
+
*
|
|
50
|
+
* The framework standardises on `OS_*` prefixed env vars (see AGENTS.md
|
|
51
|
+
* "Environment Variables" section). Some historical names predate this
|
|
52
|
+
* convention — `AUTH_SECRET`, `ROOT_DOMAIN`, `OBJECTSTACK_*`, …
|
|
53
|
+
*
|
|
54
|
+
* To migrate without breaking user `.env` files mid-release, call
|
|
55
|
+
* {@link readEnvWithDeprecation} at every legacy read site:
|
|
56
|
+
*
|
|
57
|
+
* const v = readEnvWithDeprecation('OS_AUTH_SECRET', 'AUTH_SECRET');
|
|
58
|
+
*
|
|
59
|
+
* If only the legacy name is set, the value is still returned but a
|
|
60
|
+
* one-shot `console.warn` fires (per-process per-variable) telling
|
|
61
|
+
* operators to rename it.
|
|
62
|
+
*/
|
|
63
|
+
|
|
1
64
|
/**
|
|
2
65
|
* Read an env var, preferring the canonical `OS_*` name and falling
|
|
3
66
|
* back to one or more legacy aliases.
|
|
@@ -45,6 +108,28 @@ declare function readEnvWithDeprecation(preferred: string, legacy: string | read
|
|
|
45
108
|
* result must be stable for the process lifetime.
|
|
46
109
|
*/
|
|
47
110
|
declare function resolveMultiOrgEnabled(): boolean;
|
|
111
|
+
/**
|
|
112
|
+
* [ADR-0105 D1] Resolve the deployment's REQUESTED tenancy posture —
|
|
113
|
+
* `single` | `group` | `isolated`.
|
|
114
|
+
*
|
|
115
|
+
* `OS_TENANCY_POSTURE` is the canonical knob and generalizes the boolean
|
|
116
|
+
* `OS_MULTI_ORG_ENABLED` it supersedes:
|
|
117
|
+
*
|
|
118
|
+
* - set → that posture (the legacy spelling `multi` normalizes to `isolated`)
|
|
119
|
+
* - unset → derived from `OS_MULTI_ORG_ENABLED`: `true` ⇒ `isolated`, else `single`
|
|
120
|
+
*
|
|
121
|
+
* so every existing deployment keeps its current posture with no config change.
|
|
122
|
+
*
|
|
123
|
+
* An unrecognized value THROWS rather than falling back. A typo'd posture that
|
|
124
|
+
* quietly resolved to `single` would silently remove the organization wall —
|
|
125
|
+
* the deployment-layer form of the "declared but unenforced" defect ADR-0049
|
|
126
|
+
* forbids, and the same reasoning behind ADR-0093 D5's refusal to boot into
|
|
127
|
+
* undeclared degradation.
|
|
128
|
+
*
|
|
129
|
+
* This resolves what the operator ASKED FOR. Whether the posture is actually
|
|
130
|
+
* enforced is the `tenancy` service's answer (`isolationActive` / `degraded`).
|
|
131
|
+
*/
|
|
132
|
+
declare function resolveTenancyPosture(): TenancyPosture;
|
|
48
133
|
/**
|
|
49
134
|
* Escape hatch for the degraded-tenancy boot guard (ADR-0093 D5).
|
|
50
135
|
*
|
|
@@ -57,6 +142,43 @@ declare function resolveMultiOrgEnabled(): boolean;
|
|
|
57
142
|
* an unset flag means "fail fast".
|
|
58
143
|
*/
|
|
59
144
|
declare function resolveAllowDegradedTenancy(): boolean;
|
|
145
|
+
/**
|
|
146
|
+
* Escape hatch for the driver-connect boot guard (framework#3741).
|
|
147
|
+
*
|
|
148
|
+
* `ObjectQLEngine.init()` connects every boot-registered driver and, by
|
|
149
|
+
* default, refuses to boot when any of them fails — a server whose database is
|
|
150
|
+
* unreachable must not report itself started and then 500 every request with an
|
|
151
|
+
* error that reads nothing like "the database is down". Failing there is also
|
|
152
|
+
* what gives a driver the ability to REFUSE STARTUP at all: any fatal startup
|
|
153
|
+
* check a driver wants to run (licence, server version, incompatible
|
|
154
|
+
* configuration, missing capability) can simply throw from `connect()`.
|
|
155
|
+
*
|
|
156
|
+
* Setting this to a truthy value (`true`/`1`/`on`/`yes`, case-insensitive)
|
|
157
|
+
* boots anyway, in an explicitly degraded state that is logged loudly at
|
|
158
|
+
* startup. Every query routed to a failed driver fails until the datasource
|
|
159
|
+
* becomes reachable — the underlying clients do re-establish connections on
|
|
160
|
+
* their own (framework#3759) — but the boot-time schema sync those drivers
|
|
161
|
+
* missed is never re-run, so their tables may simply not exist afterwards.
|
|
162
|
+
* Defaults OFF — an unset flag means "fail fast".
|
|
163
|
+
*/
|
|
164
|
+
declare function resolveAllowDriverConnectFailure(): boolean;
|
|
165
|
+
/**
|
|
166
|
+
* Escape hatch for plugin-dev's production boot guard (ADR-0115 D6, #3900).
|
|
167
|
+
*
|
|
168
|
+
* `DevPlugin.init()` refuses to run under `NODE_ENV=production`: the stack it
|
|
169
|
+
* assembles is built around an auth secret published inside the npm package and
|
|
170
|
+
* an in-memory driver with persistence off, neither of which a production
|
|
171
|
+
* deployment should acquire by accident. Setting this to a truthy value
|
|
172
|
+
* (`true`/`1`/`on`/`yes`, case-insensitive) boots anyway, in an explicitly
|
|
173
|
+
* degraded state that is branded in the boot log and on the ready banner.
|
|
174
|
+
* Defaults OFF — an unset flag means "fail fast".
|
|
175
|
+
*
|
|
176
|
+
* Lives here rather than as a bare `process.env[…] === '1'` inside plugin-dev so
|
|
177
|
+
* that the whole `OS_ALLOW_*` family answers to one truthy vocabulary: the
|
|
178
|
+
* strict `=== '1'` it replaced fails CLOSED on `OS_ALLOW_DEV_PLUGIN=true`, which
|
|
179
|
+
* is safe but reads to an operator as the flag being broken.
|
|
180
|
+
*/
|
|
181
|
+
declare function resolveAllowDevPlugin(): boolean;
|
|
60
182
|
/**
|
|
61
183
|
* SINGLE decision point for "is the MCP HTTP surface (`/api/v1/mcp`) on?".
|
|
62
184
|
*
|
|
@@ -140,14 +262,46 @@ declare function resolveOrgLimit(): number | undefined;
|
|
|
140
262
|
* 3. No env var and no `zh-*` locale → off. OSS / non-Chinese deployments
|
|
141
263
|
* never load `pinyin-pro` and pay zero compute cost.
|
|
142
264
|
*
|
|
143
|
-
* Hosts that know the stack's i18n config
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
265
|
+
* Hosts that know the stack's i18n config — the CLI `serve` boot path AND the
|
|
266
|
+
* standalone artifact boot (`createStandaloneStack`, which `os migrate`
|
|
267
|
+
* plan/apply and embedders go through) — resolve once with locales and stamp
|
|
268
|
+
* the decision back into the env via {@link stampSearchPinyinEnabled}, so
|
|
269
|
+
* downstream consumers constructed without config access (per-engine
|
|
270
|
+
* SchemaRegistry) read the same answer via the no-arg form (#3955).
|
|
147
271
|
*/
|
|
148
272
|
declare function resolveSearchPinyinEnabled(opts?: {
|
|
149
273
|
locales?: readonly string[];
|
|
150
274
|
}): boolean;
|
|
275
|
+
/**
|
|
276
|
+
* The locales a stack's `i18n` config declares — `defaultLocale`,
|
|
277
|
+
* `fallbackLocale`, then `supportedLocales`. Accepts the config loosely typed
|
|
278
|
+
* (`unknown`) so any boot path can pass whatever its stack config or compiled
|
|
279
|
+
* artifact carries without importing spec schemas; non-string entries and a
|
|
280
|
+
* non-object config collapse to `[]`.
|
|
281
|
+
*/
|
|
282
|
+
declare function collectConfiguredLocales(i18n: unknown): string[];
|
|
283
|
+
/**
|
|
284
|
+
* Resolve the pinyin-search decision from a stack's `i18n` config and stamp a
|
|
285
|
+
* positive result back into `OS_SEARCH_PINYIN_ENABLED` (#2486, #3955).
|
|
286
|
+
*
|
|
287
|
+
* Every boot path that SEES the stack config must stamp, because consumers
|
|
288
|
+
* constructed later without config access (each engine's `SchemaRegistry`
|
|
289
|
+
* provisioning the `__search` companion column, the `plugin-pinyin-search`
|
|
290
|
+
* gate) read the decision through the no-arg
|
|
291
|
+
* {@link resolveSearchPinyinEnabled}. A boot path that skips the stamp
|
|
292
|
+
* computes a schema view WITHOUT the companion columns — which is how
|
|
293
|
+
* `os migrate` came to flag the dev runtime's live `__search` columns as
|
|
294
|
+
* destructive orphans (#3955). Call sites: the CLI `serve`/`dev` boot
|
|
295
|
+
* (`objectstack.config.ts`) and `createStandaloneStack` (compiled artifact —
|
|
296
|
+
* `os migrate plan`/`apply`, embedders).
|
|
297
|
+
*
|
|
298
|
+
* An explicit `OS_SEARCH_PINYIN_ENABLED` always wins — the resolver reads it
|
|
299
|
+
* before consulting locales, so the stamp only materializes the
|
|
300
|
+
* locale-derived default. Only a positive decision is written: "unset" and
|
|
301
|
+
* "off" read identically through the no-arg resolver, and leaving the var
|
|
302
|
+
* untouched keeps a later boot free to re-derive from ITS config.
|
|
303
|
+
*/
|
|
304
|
+
declare function stampSearchPinyinEnabled(i18n: unknown): boolean;
|
|
151
305
|
/**
|
|
152
306
|
* SINGLE decision point for a sandbox script-runner DEFAULT (ms), resolved from
|
|
153
307
|
* the environment (framework#3259 / ADR-0102).
|
|
@@ -184,6 +338,144 @@ declare function resolveSandboxTimeoutMs(kind: 'hook' | 'action' | 'wallCeiling'
|
|
|
184
338
|
*/
|
|
185
339
|
declare function _resetEnvDeprecationWarnings(): void;
|
|
186
340
|
|
|
341
|
+
/**
|
|
342
|
+
* Shared "does this error message leak server internals?" heuristic (#3867).
|
|
343
|
+
*
|
|
344
|
+
* ObjectStack has more than one HTTP boundary. `@objectstack/rest` guards the
|
|
345
|
+
* REST data routes inside `mapDataError`; the dispatcher-plugin routes
|
|
346
|
+
* (`/analytics`, `/packages`, `/i18n`, `/automation`, …) exit
|
|
347
|
+
* through `errorResponseBase`. Before #3867 only the first of those sanitised
|
|
348
|
+
* anything, so a driver error raised under `/analytics/query` reached the
|
|
349
|
+
* client verbatim — a real SQL statement in the response body:
|
|
350
|
+
*
|
|
351
|
+
* ```
|
|
352
|
+
* {"success":false,"error":{"message":"SELECT FROM \"sqlite_sequence\" - near \"FROM\": syntax error","code":500}}
|
|
353
|
+
* ```
|
|
354
|
+
*
|
|
355
|
+
* "Do not ship driver internals to clients" is a property of the HTTP
|
|
356
|
+
* boundary, not of one router, so the predicate lives here — the package both
|
|
357
|
+
* `@objectstack/rest` and `@objectstack/runtime` already depend on — and each
|
|
358
|
+
* boundary applies it in its own envelope. One heuristic, one place to widen
|
|
359
|
+
* when a new dialect's phrasing shows up.
|
|
360
|
+
*
|
|
361
|
+
* Deliberately a *heuristic over the message*, not a driver taxonomy: these
|
|
362
|
+
* errors arrive as plain `Error`s from a half-dozen dialects with no shared
|
|
363
|
+
* shape. It is applied only where the outcome is already a 5xx, so a false
|
|
364
|
+
* positive costs a caller nothing but detail on a response that was a server
|
|
365
|
+
* fault anyway — while the full text still reaches server logs and the
|
|
366
|
+
* error reporter.
|
|
367
|
+
*/
|
|
368
|
+
/** Generic replacement text for a message that trips {@link looksLikeInternalErrorLeak}. */
|
|
369
|
+
declare const INTERNAL_ERROR_MESSAGE = "Internal server error";
|
|
370
|
+
/**
|
|
371
|
+
* Whether `message` looks like a raw SQL statement or driver/engine dump that
|
|
372
|
+
* must not be returned to an API client.
|
|
373
|
+
*
|
|
374
|
+
* Matches: dialect error codes (`SQLSTATE`, `sqlite_*`), bare statements
|
|
375
|
+
* (a message that *starts* as `SELECT`/`INSERT INTO`/`UPDATE`/`DELETE FROM` —
|
|
376
|
+
* drivers prefix the offending SQL to their message), and constraint-violation
|
|
377
|
+
* dumps, which name physical tables and columns.
|
|
378
|
+
*
|
|
379
|
+
* Does NOT match ordinary business or validation messages, which is why the
|
|
380
|
+
* statement forms are anchored with `startsWith`: a legitimate message may
|
|
381
|
+
* *mention* "update" without being one.
|
|
382
|
+
*/
|
|
383
|
+
declare function looksLikeInternalErrorLeak(message: string | undefined | null): boolean;
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Seek-based (keyset) pagination for the batch walks that read a whole object.
|
|
387
|
+
*
|
|
388
|
+
* # Why this exists rather than `limit`/`offset`
|
|
389
|
+
*
|
|
390
|
+
* A background walk that pages with a growing `offset` — rebuild an index,
|
|
391
|
+
* verify file references, backfill a projection — is wrong in two ways that a
|
|
392
|
+
* seek fixes at once.
|
|
393
|
+
*
|
|
394
|
+
* **It can skip rows.** `LIMIT n OFFSET k` is a slice of an arrangement, and
|
|
395
|
+
* the arrangement has to be the *same* one on every page for the slices to
|
|
396
|
+
* partition the set. Drivers now guarantee that for a single read
|
|
397
|
+
* (objectstack#4363), but not across a walk that *mutates as it goes*: a
|
|
398
|
+
* backfill that updates each page, or a rebuild that deletes, changes the very
|
|
399
|
+
* set the next offset counts into. Rows shift past the cursor and are never
|
|
400
|
+
* visited. For a verifier that decides which files are still referenced, or an
|
|
401
|
+
* index rebuild that deletes what it did not see, a skipped row is not a slow
|
|
402
|
+
* page — it is a wrong answer that looks like a clean run. A seek predicate
|
|
403
|
+
* carries the position *in the data* instead of counting from the start, so an
|
|
404
|
+
* update cannot move a row past it and a delete cannot shift one under it.
|
|
405
|
+
*
|
|
406
|
+
* **It is quadratic.** The database must produce and discard every skipped row
|
|
407
|
+
* to honor an offset, so walking n rows in pages of p costs O(n²/p). On a
|
|
408
|
+
* 2M-row table the last pages were measured at ~1.1 s each against ~0.09 s for
|
|
409
|
+
* the first. A seek starts each page at the cursor, so every page costs the
|
|
410
|
+
* same: O(n) for the walk, and index-served throughout.
|
|
411
|
+
*
|
|
412
|
+
* # What it requires
|
|
413
|
+
*
|
|
414
|
+
* A column that is **unique and orderable** — `id` by default, which every
|
|
415
|
+
* object this driver-managed platform creates carries. An object without one
|
|
416
|
+
* (a federated table, ADR-0015) cannot be walked this way; callers that scan
|
|
417
|
+
* arbitrary registry objects already skip what they cannot read, and that is
|
|
418
|
+
* the correct outcome here too rather than a silent partial scan.
|
|
419
|
+
*
|
|
420
|
+
* # Shape
|
|
421
|
+
*
|
|
422
|
+
* `read` is the caller's own query — this owns the loop, the cursor and the
|
|
423
|
+
* `where` merge, and nothing else. Deliberately one implementation rather than
|
|
424
|
+
* the six hand-rolled copies it replaces: the cursor merge is the part that is
|
|
425
|
+
* easy to get subtly wrong (an object whose own `where` already constrains the
|
|
426
|
+
* key), and six copies of it drift silently.
|
|
427
|
+
*
|
|
428
|
+
* @example
|
|
429
|
+
* const walk = keysetWalk<Row>(
|
|
430
|
+
* (q) => engine.find('sys_approval_request', { ...q, fields: ['id'], context: SYSTEM_CTX }),
|
|
431
|
+
* { where: { status: 'pending' }, pageSize: 500 },
|
|
432
|
+
* );
|
|
433
|
+
* for await (const page of walk.pages()) { … }
|
|
434
|
+
* if (walk.truncated) { … }
|
|
435
|
+
*/
|
|
436
|
+
/** The query a {@link keysetWalk} hands its reader: the caller's `where`, narrowed by the cursor. */
|
|
437
|
+
interface KeysetPageQuery {
|
|
438
|
+
/** The caller's `where`, AND-ed with the seek predicate once the walk has a cursor. */
|
|
439
|
+
where?: unknown;
|
|
440
|
+
/** Always ascending on the key column — the walk's order IS the seek order. */
|
|
441
|
+
orderBy: Array<{
|
|
442
|
+
field: string;
|
|
443
|
+
order: 'asc';
|
|
444
|
+
}>;
|
|
445
|
+
/** Page size. */
|
|
446
|
+
limit: number;
|
|
447
|
+
}
|
|
448
|
+
interface KeysetWalkOptions {
|
|
449
|
+
/** The caller's filter, applied to every page. */
|
|
450
|
+
where?: unknown;
|
|
451
|
+
/** Rows per page. */
|
|
452
|
+
pageSize: number;
|
|
453
|
+
/**
|
|
454
|
+
* Stop after this many rows and set {@link KeysetWalk.truncated}. Omit for an
|
|
455
|
+
* unbounded walk. A cap is not a failure — it is how a scan bounds its own
|
|
456
|
+
* cost — but it must be reported, or a partial scan reads as a complete one.
|
|
457
|
+
*/
|
|
458
|
+
max?: number;
|
|
459
|
+
/** Unique, orderable column to seek on. Defaults to `id`. */
|
|
460
|
+
key?: string;
|
|
461
|
+
}
|
|
462
|
+
interface KeysetWalk<T> {
|
|
463
|
+
/** Pages, in key order, until the source is exhausted or `max` is reached. */
|
|
464
|
+
pages(): AsyncGenerator<T[]>;
|
|
465
|
+
/** Rows yielded so far. */
|
|
466
|
+
readonly scanned: number;
|
|
467
|
+
/** True when `max` stopped the walk before the source was exhausted. */
|
|
468
|
+
readonly truncated: boolean;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Walk an object by seeking past the last key rather than counting from the
|
|
472
|
+
* start. See the module comment for why every batch scan should.
|
|
473
|
+
*
|
|
474
|
+
* `read` receives a {@link KeysetPageQuery} and returns the page; the caller
|
|
475
|
+
* owns everything else about the query (projection, context, object name).
|
|
476
|
+
*/
|
|
477
|
+
declare function keysetWalk<T extends Record<string, unknown>>(read: (query: KeysetPageQuery) => Promise<T[]>, options: KeysetWalkOptions): KeysetWalk<T>;
|
|
478
|
+
|
|
187
479
|
/**
|
|
188
480
|
* True when a dynamic `import()` / `require.resolve()` failed because the
|
|
189
481
|
* module is simply NOT INSTALLED — as opposed to the module being present but
|
|
@@ -200,6 +492,129 @@ declare function _resetEnvDeprecationWarnings(): void;
|
|
|
200
492
|
*/
|
|
201
493
|
declare function isModuleNotFoundError(err: unknown): boolean;
|
|
202
494
|
|
|
495
|
+
/**
|
|
496
|
+
* The ONE writer for the declared REST response envelope (#3973).
|
|
497
|
+
*
|
|
498
|
+
* `BaseResponseSchema` (`packages/spec/src/api/contract.zod.ts`) declares one
|
|
499
|
+
* envelope for every REST body the platform emits:
|
|
500
|
+
*
|
|
501
|
+
* { success: true, data }
|
|
502
|
+
* { success: false, error: { code, message } }
|
|
503
|
+
*
|
|
504
|
+
* The schema declares it once. Until this file, the code that *wrote* it was
|
|
505
|
+
* copied per route module — seven `sendOk` / `sendError` pairs after #3843 and
|
|
506
|
+
* #3983 converted the last drifting one, so the envelope's shape lived in
|
|
507
|
+
* fourteen places rather than one.
|
|
508
|
+
*
|
|
509
|
+
* ## Why a shared builder rather than seven agreeing copies
|
|
510
|
+
*
|
|
511
|
+
* `scripts/check-route-envelope.mjs` proves the copies agree today, and that is
|
|
512
|
+
* exactly why this is a cleanup and not a bug fix. But a guard proves agreement;
|
|
513
|
+
* it does not create it. An eighth module starts by copying the pair again —
|
|
514
|
+
* which is not hypothetical, it is the observed history: `share-link-routes.ts`
|
|
515
|
+
* was found by the repo-wide scan already drifting, and its drift had broken
|
|
516
|
+
* `client.shareLinks.create()` / `.list()` through `unwrapResponse` (#3983).
|
|
517
|
+
*
|
|
518
|
+
* ## Why here
|
|
519
|
+
*
|
|
520
|
+
* Placement was the open question in #3973, not design. `packages/spec` is
|
|
521
|
+
* schemas-only (Prime Directive #2), and the callers span `packages/rest`, four
|
|
522
|
+
* `services/*` and one `plugins/*`, which rules out anything that depends on
|
|
523
|
+
* them. `@objectstack/types` depends on nothing but `@objectstack/spec`, so
|
|
524
|
+
* every caller can reach it, and it is where the repo already puts a helper the
|
|
525
|
+
* HTTP boundaries share: {@link looksLikeInternalErrorLeak} lives one file over
|
|
526
|
+
* for the same reason, and made the same argument first — "do not ship driver
|
|
527
|
+
* internals to clients" is a property of the boundary, not of one router.
|
|
528
|
+
*
|
|
529
|
+
* Writing the declared envelope is the same kind of property.
|
|
530
|
+
*
|
|
531
|
+
* ## What this does NOT change
|
|
532
|
+
*
|
|
533
|
+
* Every byte on the wire. The seven pairs were already identical modulo the
|
|
534
|
+
* optional `status` and `extra` parameters unioned below; this file is their
|
|
535
|
+
* union, and each module's driven conformance suite still parses its real
|
|
536
|
+
* bodies against the real spec schemas.
|
|
537
|
+
*
|
|
538
|
+
* The dispatcher surface (`packages/runtime/src/domains/*`) is deliberately not
|
|
539
|
+
* a caller: those handlers RETURN `{ status, body }` for a central sender rather
|
|
540
|
+
* than writing to a response, so they are already consolidated behind their own
|
|
541
|
+
* `deps.success` / `deps.error` helpers and audited by the other half of
|
|
542
|
+
* `check-route-envelope.mjs`.
|
|
543
|
+
*/
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* The only thing an envelope builder needs from a response object.
|
|
547
|
+
*
|
|
548
|
+
* Structural on purpose, so this file depends on no HTTP contract at all:
|
|
549
|
+
* `IHttpResponse` (`@objectstack/spec/contracts`) satisfies it, and so does the
|
|
550
|
+
* `any`-typed `res` the three older route modules still carry. That is what lets
|
|
551
|
+
* a package import the builders without also importing a server abstraction.
|
|
552
|
+
*/
|
|
553
|
+
interface EnvelopeResponse {
|
|
554
|
+
status(code: number): EnvelopeResponse;
|
|
555
|
+
json(body: unknown): unknown;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Emit a success body in the DECLARED envelope — `{ success: true, data }`.
|
|
559
|
+
*
|
|
560
|
+
* `data` carries the route's payload; it is not spread. A payload duplicated
|
|
561
|
+
* into a stray top-level key (`{ success: true, data: link, link }`) parses
|
|
562
|
+
* clean against `BaseResponseSchema` and is still drift — that shipped on
|
|
563
|
+
* `/share-links` for as long as nobody looked (#4038), which is why
|
|
564
|
+
* `envelopeViolations` exists beside the schema and why there is one `data`
|
|
565
|
+
* slot here rather than a spread.
|
|
566
|
+
*
|
|
567
|
+
* `status` defaults to 200 and is set explicitly even then. Five of the seven
|
|
568
|
+
* modules already did that; the two that called `res.json(...)` bare are
|
|
569
|
+
* unaffected, because the default they were relying on is the value now passed.
|
|
570
|
+
*/
|
|
571
|
+
declare function sendOk(res: EnvelopeResponse, data: unknown, status?: number): void;
|
|
572
|
+
/**
|
|
573
|
+
* Emit an error in the DECLARED envelope — `{ success: false, error: { code,
|
|
574
|
+
* message } }`, with `code` a semantic STRING and `message` a field OF `error`
|
|
575
|
+
* rather than a sibling of it.
|
|
576
|
+
*
|
|
577
|
+
* Both halves of that sentence were once wrong somewhere: `error` was a bare
|
|
578
|
+
* string in `service-storage` and `admin-routes` (so `body.error.message` read
|
|
579
|
+
* `undefined`), and `code` was the human message in `package-routes` (#3675 →
|
|
580
|
+
* #3689 → #3843).
|
|
581
|
+
*
|
|
582
|
+
* ## `code` is the closed ADR-0112 vocabulary, not `string`
|
|
583
|
+
*
|
|
584
|
+
* All seven copies typed this parameter `string`, so an invented code was caught
|
|
585
|
+
* only at runtime, by a conformance suite parsing a driven body against
|
|
586
|
+
* `ApiErrorSchema` — i.e. only on the routes a test happened to drive. `ErrorCode`
|
|
587
|
+
* is `StandardErrorCode ∪ ERROR_CODE_LEDGER` (`error-code-ledger.zod.ts`), the
|
|
588
|
+
* same union that schema validates against, so consolidating here moves the check
|
|
589
|
+
* to compile time for every call site at once. It cost no call-site churn: every
|
|
590
|
+
* code the seven modules emit was already registered.
|
|
591
|
+
*
|
|
592
|
+
* A new code is registered in `ERROR_CODE_LEDGER` under its owning package —
|
|
593
|
+
* and if the condition is generic (not found / permission / validation), the
|
|
594
|
+
* standard catalog is used instead of registering a synonym for it.
|
|
595
|
+
*
|
|
596
|
+
* ## `extra` is `ApiError`'s own optional fields, not a `Record`
|
|
597
|
+
*
|
|
598
|
+
* Merged into `error`, and typed as exactly what `ApiErrorSchema` declares
|
|
599
|
+
* beside `code` and `message` — `details`, `category`, `requestId`, `httpStatus`.
|
|
600
|
+
* `details` is the slot for structured context: `package-routes` puts a partial
|
|
601
|
+
* delete's per-item failures there, `settings-routes` the whole
|
|
602
|
+
* `SettingsActionResult`.
|
|
603
|
+
*
|
|
604
|
+
* This started as `Record<string, unknown>`, because `settings-routes` also hung
|
|
605
|
+
* `namespace` / `key` / `reason` / `fields` beside `code`, which the schema does
|
|
606
|
+
* not declare. Those bodies passed every gate anyway — `ApiErrorSchema` is a
|
|
607
|
+
* plain `z.object`, so unknown keys were STRIPPED rather than rejected, and
|
|
608
|
+
* `envelopeViolations` inspects only the body's top level — making them
|
|
609
|
+
* conformant *by stripping* rather than by declaration. #4224 moved that module's
|
|
610
|
+
* four branches onto `details`, which is what lets the parameter close here.
|
|
611
|
+
*
|
|
612
|
+
* Closing it at the shared builder is the part that lasts: an undeclared sibling
|
|
613
|
+
* is now a compile error in every module at once, rather than a key that quietly
|
|
614
|
+
* evaporates at the schema boundary in whichever module reintroduces it.
|
|
615
|
+
*/
|
|
616
|
+
declare function sendError(res: EnvelopeResponse, status: number, code: ErrorCode, message: string, extra?: Pick<ApiError, 'category' | 'httpStatus' | 'details' | 'requestId'>): void;
|
|
617
|
+
|
|
203
618
|
interface IKernel {
|
|
204
619
|
ql?: any;
|
|
205
620
|
start(): Promise<void>;
|
|
@@ -214,4 +629,4 @@ interface RuntimePlugin {
|
|
|
214
629
|
onStart?: (ctx: RuntimeContext) => void | Promise<void>;
|
|
215
630
|
}
|
|
216
631
|
|
|
217
|
-
export { type IKernel, type RuntimeContext, type RuntimePlugin, _resetEnvDeprecationWarnings, isMcpServerEnabled, isModuleNotFoundError, readEnvWithDeprecation, resolveAllowDegradedTenancy, resolveMcpStdioAutoStart, resolveMultiOrgEnabled, resolveOrgLimit, resolveSandboxTimeoutMs, resolveSearchPinyinEnabled };
|
|
632
|
+
export { type EnvelopeResponse, type IKernel, INTERNAL_ERROR_MESSAGE, type KeysetPageQuery, type KeysetWalk, type KeysetWalkOptions, type RuntimeContext, type RuntimePlugin, _resetEnvDeprecationWarnings, collectConfiguredLocales, emitDegradedBootBanner, isMcpServerEnabled, isModuleNotFoundError, keysetWalk, looksLikeInternalErrorLeak, readEnvWithDeprecation, resolveAllowDegradedTenancy, resolveAllowDevPlugin, resolveAllowDriverConnectFailure, resolveMcpStdioAutoStart, resolveMultiOrgEnabled, resolveOrgLimit, resolveSandboxTimeoutMs, resolveSearchPinyinEnabled, resolveTenancyPosture, sendError, sendOk, stampSearchPinyinEnabled };
|