@atscript/db-client 0.1.194 → 0.1.196

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.
@@ -1,627 +0,0 @@
1
- import { AggregateQuery as AggregateQuery$1, AggregateResult as AggregateResult$1, AggregateStage, BucketExpr, BucketUnit, CalendarBucketLabel, FilterExpr, NestedAggregateQuery as NestedAggregateQuery$1, NestedAggregateResult as NestedAggregateResult$1, SelectExpr, StageRow, TypedWithRelation, Uniquery as Uniquery$1, UniqueryControls, ValidGroupBy as ValidGroupBy$1, ValidNested as ValidNested$1, WeekStart } from "@uniqu/core";
2
- import { TAtscriptAnnotatedType, TAtscriptTypeObject } from "@atscript/typescript/utils";
3
- import { DbInsert, DbPatch, DbResponse, DbRow, TDbDeleteResult as TDbDeleteResult$1, TDbInsertIgnoreResult as TDbInsertIgnoreResult$1, TDbInsertManyIgnoreResult as TDbInsertManyIgnoreResult$1, TDbInsertManyResult as TDbInsertManyResult$1, TDbInsertResult as TDbInsertResult$1, TDbUpdateResult as TDbUpdateResult$1, TFieldMeta, TMetaResponse, TRelationInfo, TSearchIndexInfo } from "@atscript/db";
4
- import { DbValidationContext, ValidatorMode, ValidatorMode as ValidatorMode$1 } from "@atscript/db/validator";
5
-
6
- //#region src/meta-store.d.ts
7
- /** Options for {@link MetaStore}. */
8
- interface MetaStoreOptions {
9
- /**
10
- * How many `/meta` bodies the store keeps (least recently used are dropped
11
- * first). Default `50`.
12
- */
13
- maxEntries?: number;
14
- /**
15
- * After a conditional `/meta` request fails at the transport level (e.g. a
16
- * CORS preflight refusing `If-None-Match`) while the plain retry succeeds,
17
- * how long (ms) that store key is loaded without `If-None-Match` before a
18
- * conditional request is tried again. Default `300000` (5 minutes).
19
- */
20
- unconditionalMs?: number;
21
- }
22
- /**
23
- * Content-addressed cache of `GET /meta` responses, keyed by the server's
24
- * `ETag`, used by {@link Client.meta} to revalidate instead of downloading.
25
- *
26
- * For each store key (the meta URL, or `ClientOptions.metaKey`) the store
27
- * remembers the ETags it has seen. `meta()` sends them as `If-None-Match`;
28
- * when the server answers `304 Not Modified` the client reuses the body
29
- * stored under the returned `ETag`. Several keys that serve the same bytes
30
- * — e.g. one parametric controller mounted at `/api/tenant/:id/todos` —
31
- * therefore share one stored body, and the first visit to a new key costs a
32
- * `304` instead of the full `/meta`.
33
- *
34
- * It is a pure cache: the server decides on every request whether the body
35
- * is still valid. Failures are never stored.
36
- *
37
- * @since 0.1.153
38
- */
39
- declare class MetaStore {
40
- private readonly _maxEntries;
41
- private readonly _unconditionalMs;
42
- /** Raw JSON body by opaque ETag (`W/` stripped — `If-None-Match` compares weakly). */
43
- private readonly _bodies;
44
- private readonly _keys;
45
- constructor(options?: MetaStoreOptions);
46
- /** Number of stored `/meta` bodies. */
47
- get size(): number;
48
- /**
49
- * The ETags this store would send as `If-None-Match` for `key` — those seen
50
- * for it whose body is still stored, most recent first.
51
- */
52
- candidates(key: string): string[];
53
- /** Drops every stored body and remembered ETag. */
54
- clear(): void;
55
- /**
56
- * Stored body for `etag` (weak comparison), marking it — and `etag` as the
57
- * latest candidate for `key` — as recently used.
58
- *
59
- * @internal used by `Client`
60
- */
61
- _reuse(key: string, etag: string): string | undefined;
62
- /**
63
- * Stores a `200` body under its ETag and remembers the ETag for `key`.
64
- *
65
- * @internal used by `Client`
66
- */
67
- _put(key: string, etag: string, text: string): void;
68
- /**
69
- * Whether `key` is in its no-`If-None-Match` window; an expired window is
70
- * cleared, so the next request is conditional again.
71
- *
72
- * @internal used by `Client`
73
- */
74
- _isUnconditional(key: string): boolean;
75
- /** @internal used by `Client` */
76
- _markUnconditional(key: string): void;
77
- private _remember;
78
- /** The entry for `key`, created if needed and moved to most recently used. */
79
- private _touchKey;
80
- }
81
- /**
82
- * The store every {@link Client} uses unless `ClientOptions.metaStore` says
83
- * otherwise, so all clients in a page share revalidated `/meta` bodies.
84
- * Exported since 0.1.155: `client.metaStore === defaultMetaStore` tells a
85
- * client on the shared store from one with its own.
86
- */
87
- declare const defaultMetaStore: MetaStore;
88
- /**
89
- * Clears the shared default {@link MetaStore}. Call it on sign-out or any
90
- * identity change (together with `Client.invalidateMeta()` on live clients).
91
- *
92
- * @since 0.1.153
93
- */
94
- declare function clearMetaStore(): void;
95
- //#endregion
96
- //#region src/types.d.ts
97
- /**
98
- * Write payload for `insert()` (since 0.1.168): every key optional, optional
99
- * columns additionally accept `null` (explicit NULL). A value of the model's
100
- * interface type fits; on an untyped client any object does.
101
- */
102
- type InsertOf<T> = DbInsert<ResponseDataOf<T>>;
103
- /**
104
- * Write payload for `update()`: every key optional, optional columns
105
- * additionally accept `null` (explicit NULL). Number fields also take
106
- * `{ $inc | $dec | $mul: n }`, top-level arrays the array operators
107
- * (`$insert`, `$remove`, …) and the payload a `$cas` version check (since
108
- * 0.1.168). A value of the model's interface type fits; on an untyped client
109
- * any object does.
110
- */
111
- type PatchOf<T> = DbPatch<ResponseDataOf<T>>;
112
- /**
113
- * Write payload for `replace()`: full row; optional columns additionally
114
- * accept `null`, `$cas` checks the version. On an untyped client any object fits.
115
- */
116
- type RowOf<T> = DbRow<ResponseDataOf<T>>;
117
- /** Options for creating a Client instance. */
118
- interface ClientOptions {
119
- /**
120
- * Custom fetch implementation. Defaults to `globalThis.fetch`.
121
- * Use this to inject auth headers, interceptors, or a custom HTTP client.
122
- */
123
- fetch?: typeof globalThis.fetch;
124
- /**
125
- * Default headers to include with every request.
126
- * Can be a static object or an async factory (e.g. for refreshing auth tokens).
127
- */
128
- headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
129
- /**
130
- * Base URL prefix. Prepended to the client path for full URL construction.
131
- * @example "https://api.example.com"
132
- */
133
- baseUrl?: string;
134
- /**
135
- * Override for `processor: 'navigate'` action dispatch. When `Client.action()`
136
- * resolves a navigate action, this hook is invoked with the interpolated
137
- * URL. Default behaviour (browser only) calls `window.location.assign(url)`.
138
- *
139
- * Provide a custom navigator to integrate with a SPA router:
140
- * ```typescript
141
- * new Client('/api/users', { navigate: (url) => router.push(url) })
142
- * ```
143
- */
144
- navigate?: (url: string) => void | Promise<void>;
145
- /**
146
- * Tolerate unknown properties in write payloads during client preflight
147
- * validation. Enable when the served `/meta` type is a projection of the
148
- * full server-side type (e.g. an ARBAC read overlay strips write-only
149
- * fields) — the server stays authoritative. Off by default: strict
150
- * preflight catches typos.
151
- */
152
- lenientWrites?: boolean;
153
- /**
154
- * Where `meta()` keeps revalidatable `/meta` bodies (since 0.1.153).
155
- * Defaults to one store shared by every client in the page, so clients for
156
- * the same controller — or for one parametric controller under different
157
- * route params — revalidate with `If-None-Match` and reuse the body on a
158
- * `304`. Pass your own `new MetaStore()` to isolate a group of clients, or
159
- * `false` to always download `/meta`.
160
- */
161
- metaStore?: MetaStore | false;
162
- /**
163
- * Key under which `metaStore` remembers this client's ETags (since
164
- * 0.1.153). Defaults to the `/meta` URL. Give clients of a parametric
165
- * mount one shared key (e.g. the route template
166
- * `"/api/tenant/:tenantId/todos"`) so a new route param revalidates against
167
- * the body already loaded for another one.
168
- */
169
- metaKey?: string;
170
- /**
171
- * The locale to ask the server for (since 0.1.170): sent as
172
- * `Accept-Language` on every request (unless `headers` carries one), so a
173
- * server with a translator answers in that language — `/meta` texts, error
174
- * messages and the templates (`/meta` `type.$i18n`) the preflight
175
- * validator translates its errors with. A function is read per request.
176
- *
177
- * The cached `/meta`, the validator built from it and the loaded action
178
- * forms belong to the locale they were loaded in: after a switch, the next
179
- * call loads them again (revalidated through `metaStore`, which keeps one
180
- * entry per locale — a switch back costs a `304`). Already-held results
181
- * stay as they are: re-read them (in a UI, remount on a locale change).
182
- */
183
- locale?: string | (() => string | undefined);
184
- }
185
- /** Search index metadata from the server. */
186
- type SearchIndexInfo = TSearchIndexInfo;
187
- /** Relation summary in meta response. */
188
- type RelationInfo = TRelationInfo;
189
- /** Per-field capability flags. */
190
- type FieldMeta = TFieldMeta;
191
- /** Enhanced meta response from the server (`GET /meta`). */
192
- type MetaResponse = TMetaResponse;
193
- /** Paginated response shape from `GET /pages`. */
194
- interface PageResult<T> {
195
- data: T[];
196
- page: number;
197
- itemsPerPage: number;
198
- pages: number;
199
- count: number;
200
- }
201
- /**
202
- * Per-call options of the `Client` read / write methods (since 0.1.165).
203
- */
204
- interface TClientCallOptions {
205
- /**
206
- * Cancels the request. An aborted request rejects with a `TransportError`
207
- * whose `aborted` is `true` (the `AbortError` is its `cause`).
208
- */
209
- signal?: AbortSignal;
210
- }
211
- /** One entry of a server error's `errors` list. */
212
- interface ServerErrorEntry {
213
- path: string;
214
- message: string;
215
- /** Machine-readable reason (`UNIQUE`, `FK_MISSING`, `FK_RESTRICT`, …). @since 0.1.165 */
216
- code?: string;
217
- /** Values the message names, for translating it. @since 0.1.165 */
218
- params?: Record<string, unknown>;
219
- details?: unknown[];
220
- }
221
- /**
222
- * Server error response shape (matches moost-db error transform). Open to
223
- * extra fields (since 0.1.165): a handler's own error body (`quota`, `tier`,
224
- * …) reads without a cast — type it with `ClientError<B>`.
225
- */
226
- interface ServerError {
227
- message: string;
228
- statusCode: number;
229
- /**
230
- * The `DbError` code (`CONFLICT`, `FK_VIOLATION`, …), moost-db's own
231
- * (`UNKNOWN_FIELD`, `INVALID_QUERY`, `VERSION_MISMATCH`, … — every 400 /
232
- * 403 / 409 is coded since 0.1.175) or a handler's own. @since 0.1.165
233
- */
234
- code?: string;
235
- /** Values the top-level message names, for translating it. @since 0.1.175 */
236
- params?: Record<string, unknown>;
237
- errors?: ServerErrorEntry[];
238
- [key: string]: unknown;
239
- }
240
- /**
241
- * Minimal brand shape every `Client<T>` generic must satisfy. All fields are
242
- * optional — plain interfaces and `Record<string, unknown>` satisfy this
243
- * constraint, so `new Client('/path')` (no generic) keeps working with
244
- * `unknown` / `Record<string, unknown>` fallbacks. Atscript-generated types
245
- * fill these brand fields and unlock per-method inference.
246
- */
247
- type AtscriptClientShape = {
248
- __pk?: unknown;
249
- __ownProps?: Record<string, unknown>;
250
- __navProps?: Record<string, unknown>;
251
- type?: {
252
- __dataType?: unknown;
253
- };
254
- };
255
- /** Extract the data type from an Atscript annotated type `T`. */
256
- type DataOf<T> = T extends {
257
- type: {
258
- __dataType?: infer D;
259
- };
260
- } ? unknown extends D ? T extends (new (...a: any[]) => infer I) ? I : Record<string, unknown> : D & Record<string, unknown> : Record<string, unknown>;
261
- /**
262
- * The row type a read answers with: {@link DataOf} without its
263
- * `Record<string, unknown>` widening, which would make `DbResponse`'s
264
- * `Omit` collapse every field to `unknown` (since 0.1.165).
265
- */
266
- type ResponseDataOf<T> = T extends {
267
- type: {
268
- __dataType?: infer D;
269
- };
270
- } ? unknown extends D ? T extends (new (...a: any[]) => infer I) ? I : Record<string, unknown> : D : Record<string, unknown>;
271
- /**
272
- * `$select` controls of a read over `T` whose controller declares the display-only
273
- * fields `D` (`@DbDecorations`): `$select` also accepts `keyof D`; filter, sort
274
- * and every other control stay over the own fields. Since 0.1.148.
275
- */
276
- type DecoratedControls<T, D> = Omit<UniqueryControls<OwnOf<T>, NavOf<T>>, "$select"> & {
277
- $select?: SelectExpr<OwnOf<T> & D>;
278
- /**
279
- * `false` — a `$search` read computes no relevance score: rows come in
280
- * `$sort` order, or primary-key order without one. A `$vector` read refuses
281
- * it (400). Default `true`. Since 0.1.175.
282
- */
283
- $rank?: boolean;
284
- };
285
- /** A read query over `T` — {@link DecoratedControls} for the controls. Since 0.1.148. */
286
- type DecoratedQuery<T, D> = Omit<Uniquery$1<OwnOf<T>, NavOf<T>>, "controls"> & {
287
- controls?: DecoratedControls<T, D>;
288
- };
289
- /** Extract own (non-nav) properties from an Atscript annotated type. */
290
- type OwnOf<T> = T extends {
291
- __ownProps: infer O;
292
- } ? O : DataOf<T>;
293
- /** Extract nav properties from an Atscript annotated type. */
294
- type NavOf<T> = T extends {
295
- __navProps: infer N extends Record<string, unknown>;
296
- } ? N : Record<string, never>;
297
- /** Extract primary key type from an Atscript annotated type. */
298
- type IdOf<T> = T extends {
299
- __pk: infer PK;
300
- } ? PK : unknown;
301
- /**
302
- * Narrow a read-method response type by the literal `$with` array in the
303
- * query, mirroring the backend's `DbResponse<Data, Nav, Q>` algebra. Nav
304
- * properties are stripped by default and re-added only for relations the
305
- * caller listed in `$with`. When `T` carries no nav-prop brand, `DbResponse`
306
- * short-circuits to the data type. `$actions` / `$disabledReasons` are always
307
- * optional — the server emits them only when the request set `?$actions=true`.
308
- */
309
- type ClientResponse<T, Q> = DbResponse<ResponseDataOf<T>, NavOf<T>, Q> & {
310
- /**
311
- * Server-evaluated per-row availability for `'row'` and `'rows'`-level
312
- * actions. Each entry is the `name` of an action that is NOT disabled for
313
- * this row.
314
- */
315
- $actions?: string[];
316
- /**
317
- * Action name → human-readable reason, for actions disabled on this row
318
- * whose `disabled` predicate returned a reason string. Present only on
319
- * rows with at least one such reason; keys never appear in `$actions`.
320
- *
321
- * @since 0.1.141
322
- */
323
- $disabledReasons?: Record<string, string>;
324
- };
325
- /**
326
- * "Every row matching this query" — the target of
327
- * `Client.actionOnQuery()` / `countActionTarget()`, for a `'rows'` action
328
- * whose `/meta` entry carries `queryTarget`. The same filter / search /
329
- * index the user's `/query` used; the server resolves it under the caller's
330
- * read scope and the action's own gate.
331
- *
332
- * @since 0.1.147
333
- */
334
- interface TDbQueryTarget<T = AtscriptClientShape> {
335
- filter?: Uniquery$1<OwnOf<T>, NavOf<T>>["filter"];
336
- /** `$search` term. */
337
- search?: string;
338
- /** `$index` — the search index `search` uses. */
339
- index?: string;
340
- /** Identifiers to leave out (any identification of the controller the request goes to). */
341
- exclude?: Record<string, unknown>[];
342
- /** Fail with 409 `TARGET_CHANGED` when the target no longer matches exactly this many rows. */
343
- expectCount?: number;
344
- /** Client-side cap (never above the action's `queryTarget.maxRows`). */
345
- maxRows?: number;
346
- }
347
- //#endregion
348
- //#region src/client-error.d.ts
349
- /**
350
- * Error thrown by `Client` when the server responds with a non-2xx status code.
351
- * Captures the HTTP status and the structured error body from moost-db.
352
- */
353
- declare class ClientError<B extends ServerError = ServerError> extends Error {
354
- /** HTTP status code (e.g. 400, 404, 409, 500). */
355
- readonly status: number;
356
- /**
357
- * Structured error response from the server. `B` (since 0.1.165) types a
358
- * body that carries fields of its own: `new ClientError<QuotaBody>(…)`,
359
- * `(e as ClientError<QuotaBody>).body.quota`.
360
- */
361
- readonly body: B;
362
- name: string;
363
- constructor(/** HTTP status code (e.g. 400, 404, 409, 500). */
364
-
365
- status: number,
366
- /**
367
- * Structured error response from the server. `B` (since 0.1.165) types a
368
- * body that carries fields of its own: `new ClientError<QuotaBody>(…)`,
369
- * `(e as ClientError<QuotaBody>).body.quota`.
370
- */
371
-
372
- body: B);
373
- /** Shortcut to structured validation/DB errors from the server. */
374
- get errors(): ServerErrorEntry[];
375
- }
376
- /**
377
- * Thrown before the request is sent when the client-side preflight
378
- * (`validator` option, `ClientValidator`) rejects a write. A
379
- * {@link ClientError} since 0.1.165 — status `400`, `body` shaped like the
380
- * server's validation envelope (`{ message, statusCode: 400, errors }`) — so
381
- * one `instanceof ClientError` branch handles a preflight failure and the
382
- * server's 400 alike; `preflight` (`true`) tells them apart. The same class
383
- * is exported from `@atscript/db-client` and `@atscript/db-client/validator`.
384
- */
385
- declare class ClientValidationError extends ClientError {
386
- name: string;
387
- /** `true`: the request never left the client. */
388
- readonly preflight: true;
389
- constructor(errors: ServerErrorEntry[]);
390
- }
391
- /**
392
- * Wire-body shape for `ActionDisabledError` responses (HTTP 409). Extends
393
- * the base `ServerError` envelope with a `name` discriminator, the action
394
- * name, and the offending identifier(s). The bridge between `@atscript/moost-db`'s
395
- * server-side error and this typed client-side subclass is the wire JSON
396
- * body — neither package depends on the other.
397
- */
398
- interface ActionDisabledErrorBody extends ServerError {
399
- name: "ActionDisabledError";
400
- action: string;
401
- id?: Record<string, unknown>;
402
- ids?: Record<string, unknown>[];
403
- /** Reason shared by every rejected row, when the server's predicate gave one. @since 0.1.141 */
404
- reason?: string;
405
- /** `'rows'` level: index-aligned with `ids`, `null` = no reason for that row. @since 0.1.141 */
406
- reasons?: (string | null)[];
407
- }
408
- /**
409
- * Typed marker thrown by `Client._send` when the server response body's
410
- * `name === 'ActionDisabledError'`. The transport / status / base body are
411
- * identical to a generic `ClientError`; this subclass adds typed accessors
412
- * so consumers can write `catch (e) { if (e instanceof ActionDisabledError) … }`
413
- * to access `action` / `id` / `ids` / `reason` / `reasons` without indexing
414
- * into `body`.
415
- */
416
- declare class ActionDisabledError extends ClientError {
417
- name: string;
418
- /** The `@DbAction` name that rejected the request. */
419
- get action(): string;
420
- /** Present only for `'row'`-level rejections. */
421
- get id(): Record<string, unknown> | undefined;
422
- /** Present only for `'rows'`-level rejections (full list of failing IDs). */
423
- get ids(): Record<string, unknown>[] | undefined;
424
- /**
425
- * Human-readable reason shared by every rejected row — present only when
426
- * the server's `disabled` predicate returned one. `message` already
427
- * carries it.
428
- *
429
- * @since 0.1.141
430
- */
431
- get reason(): string | undefined;
432
- /**
433
- * `'rows'`-level only: per-row reasons index-aligned with {@link ids}
434
- * (`null` where that row has none). Present only when at least one
435
- * rejected row carries a reason.
436
- *
437
- * @since 0.1.141
438
- */
439
- get reasons(): (string | null)[] | undefined;
440
- }
441
- /**
442
- * Wire-body shape for `ActionTargetError` responses (since 0.1.147): a
443
- * query target the server refused — `code` says why.
444
- */
445
- interface ActionTargetErrorBody extends ServerError {
446
- name: "ActionTargetError";
447
- code: "TARGET_INVALID" | "TARGET_TOO_LARGE" | "TARGET_CHANGED";
448
- action: string;
449
- /** `TARGET_CHANGED`: the current match count. */
450
- matched?: number;
451
- /** `TARGET_TOO_LARGE`: the most rows one request may target. */
452
- cap?: number;
453
- }
454
- /**
455
- * Typed marker thrown by `Client` when a query-targeted action request is
456
- * refused (body `name === 'ActionTargetError'`): `TARGET_INVALID` (400),
457
- * `TARGET_TOO_LARGE` (400, `cap`) or `TARGET_CHANGED` (409, `matched` — the
458
- * rows the query matches now; re-confirm and retry with that count).
459
- *
460
- * @since 0.1.147
461
- */
462
- declare class ActionTargetError extends ClientError {
463
- name: string;
464
- get code(): ActionTargetErrorBody["code"];
465
- get action(): string;
466
- get matched(): number | undefined;
467
- get cap(): number | undefined;
468
- }
469
- /**
470
- * Wire-body shape for 409 OCC `version_mismatch` responses. Extends the base
471
- * `ServerError` envelope with a `kind` discriminator and the row's current
472
- * server-side version. The bridge between `@atscript/moost-db`'s server-side
473
- * `_disambiguateMismatch` and this typed client-side subclass is the wire
474
- * JSON body — neither package depends on the other.
475
- */
476
- interface VersionMismatchErrorBody extends ServerError {
477
- kind: "version_mismatch";
478
- currentVersion: number;
479
- }
480
- /**
481
- * Typed marker thrown by `Client._send` when the server response body's
482
- * `kind === 'version_mismatch'`. The transport / status / base body are
483
- * identical to a generic `ClientError`; this subclass adds a typed
484
- * `currentVersion` accessor so consumers can write
485
- * `catch (e) { if (e instanceof VersionMismatchError) … }` without casting.
486
- */
487
- declare class VersionMismatchError extends ClientError {
488
- name: string;
489
- /** Row's current server-side version — clients refresh + retry against it. */
490
- get currentVersion(): number;
491
- }
492
- /**
493
- * Thrown by `Client` when NO server verdict was obtained: `fetch` itself
494
- * rejected (network down, DNS, CORS, `AbortError`, …) or a 2xx response
495
- * carried a body that is not JSON. Unlike {@link ClientError} — where the
496
- * server answered and rejected — the request's outcome is unknown: a write
497
- * may have committed. Reload before retrying a non-idempotent write.
498
- * The underlying error is the standard `cause`.
499
- */
500
- declare class TransportError extends Error {
501
- /** HTTP method of the failed request. */
502
- readonly method: string;
503
- /** Full request URL. */
504
- readonly url: string;
505
- name: string;
506
- constructor(/** HTTP method of the failed request. */
507
-
508
- method: string, /** Full request URL. */
509
-
510
- url: string, /** What went wrong; the message is `<method> <url>: <detail>`. */
511
-
512
- detail: string, cause?: unknown);
513
- /**
514
- * `true` when the request was cancelled — its `cause` is an `AbortError`
515
- * (an aborted `signal`) or a `TimeoutError` (`AbortSignal.timeout`) —
516
- * rather than a network failure. @since 0.1.165
517
- */
518
- get aborted(): boolean;
519
- }
520
- /** Thrown by `Client.action()` when the action name is not present in `/meta`. */
521
- declare class ActionNotFoundError extends Error {
522
- readonly action: string;
523
- name: string;
524
- constructor(action: string);
525
- }
526
- /**
527
- * Thrown by `Client.action()` for actions that cannot be invoked through
528
- * the client — currently `processor: 'custom'` (UI-dispatched events,
529
- * which the application is responsible for handling) and `processor: 'navigate'`
530
- * when no browser environment and no `navigate` option are configured.
531
- */
532
- declare class ActionUnsupportedError extends Error {
533
- readonly action: string;
534
- readonly processor: string;
535
- name: string;
536
- constructor(action: string, processor: string, message: string);
537
- }
538
- //#endregion
539
- //#region src/validator.d.ts
540
- /** Options for {@link ClientValidator} / {@link createClientValidator}. */
541
- interface ClientValidatorOptions {
542
- /**
543
- * The table's `@db.column.version` column (from `/meta`'s `versionColumn`).
544
- * Enables the `$cas` lift in {@link ClientValidator.liftCas}; without it a
545
- * `$cas` payload is rejected (the table is not versioned).
546
- */
547
- versionColumn?: string;
548
- /**
549
- * Tolerate unknown properties in write payloads. Enable when the served
550
- * `/meta` type is a PROJECTION of the full server-side type (e.g. an ARBAC
551
- * read overlay that strips write-only fields such as sealed credentials) —
552
- * otherwise a legitimate write carrying such a field is rejected client-side
553
- * while the server would accept it. The server stays authoritative; this
554
- * only relaxes the client preflight, so leave it off unless you need it
555
- * (strict preflight catches typos).
556
- */
557
- lenientWrites?: boolean;
558
- /**
559
- * Message templates and texts to translate the preflight's errors with
560
- * (since 0.1.170) — the served type's `$i18n` (`/meta` `type.$i18n`), which
561
- * {@link createClientValidator} passes by default. Errors keep their
562
- * `code` / `params`; ids missing from it keep the English message.
563
- */
564
- messages?: Readonly<Record<string, string>>;
565
- }
566
- /**
567
- * Client-side validator backed by an Atscript type from the `/meta` endpoint.
568
- *
569
- * Caches validators per mode. Lazily initializes from a meta response promise.
570
- */
571
- declare class ClientValidator {
572
- private _type;
573
- private _validators;
574
- private _options;
575
- private _lenientWrites;
576
- private _translate?;
577
- /** Flat map of dotted field paths to their annotated types. */
578
- readonly flatMap: Map<string, TAtscriptAnnotatedType>;
579
- /** Set of field paths that are navigation relations (TO/FROM/VIA). */
580
- readonly navFields: ReadonlySet<string>;
581
- /** The table's version column when it opts into OCC (from `/meta`). */
582
- readonly versionColumn?: string;
583
- constructor(type: TAtscriptAnnotatedType<TAtscriptTypeObject>, opts?: ClientValidatorOptions);
584
- /**
585
- * Normalises the SDK `$cas` shape to the wire shape (since 0.1.128):
586
- * `{ id, $cas: { version: 4 } }` → `{ id, version: 4 }` (the server lifts
587
- * `version` back to `$cas`). Returns a shallow clone per item; items
588
- * without `$cas` (a `$cas: undefined` counts as absent) are returned
589
- * as-is. Throws `ClientValidationError` when the table is not versioned,
590
- * the `$cas` shape is invalid, or `version` and `$cas` disagree — the same
591
- * messages the server produces, from the shared `reconcileCas` — or when
592
- * `$cas` appears on an insert.
593
- */
594
- liftCas(data: unknown, mode: ValidatorMode): unknown;
595
- private _liftCasItem;
596
- /**
597
- * Applies the type's `@normalize.*` to write data (one item or an array)
598
- * the way the server's write in `mode` does — patch operators and nested
599
- * relation data included. Run it before {@link validate} and send its
600
- * result. Pure and copy-on-change; never validates.
601
- *
602
- * @since 0.1.170
603
- */
604
- normalize(data: unknown, mode: ValidatorMode): unknown;
605
- /**
606
- * Validate data for a given write mode.
607
- * Throws `ClientValidationError` if validation fails. Validates `data` as
608
- * given — run {@link normalize} first.
609
- */
610
- validate(data: unknown, mode: ValidatorMode): void;
611
- private _getValidator;
612
- /** The options of `mode`'s validator — one object per mode (normalization judges with it too). */
613
- private _getOptions;
614
- }
615
- /**
616
- * Create a {@link ClientValidator} from a meta response (or promise).
617
- *
618
- * @example
619
- * ```typescript
620
- * const client = new Client<typeof User>('/db/tables/users')
621
- * const validator = createClientValidator(await client.meta())
622
- * validator.validate({ name: 'foo' }, 'insert')
623
- * ```
624
- */
625
- declare function createClientValidator(meta: MetaResponse, opts?: ClientValidatorOptions): ClientValidator;
626
- //#endregion
627
- export { TDbInsertManyResult$1 as $, DecoratedControls as A, OwnOf as B, CalendarBucketLabel as C, DbInsert as D, DataOf as E, InsertOf as F, RowOf as G, PatchOf as H, MetaResponse as I, StageRow as J, SearchIndexInfo as K, NavOf as L, FieldMeta as M, FilterExpr as N, DbPatch as O, IdOf as P, TDbInsertManyIgnoreResult$1 as Q, NestedAggregateQuery$1 as R, BucketUnit as S, ClientResponse as T, RelationInfo as U, PageResult as V, ResponseDataOf as W, TDbDeleteResult$1 as X, TClientCallOptions as Y, TDbInsertIgnoreResult$1 as Z, AggregateQuery$1 as _, createClientValidator as a, UniqueryControls as at, AtscriptClientShape as b, ActionNotFoundError as c, WeekStart as ct, ActionUnsupportedError as d, clearMetaStore as dt, TDbInsertResult$1 as et, ClientError as f, defaultMetaStore as ft, VersionMismatchErrorBody as g, VersionMismatchError as h, ValidatorMode$1 as i, Uniquery$1 as it, DecoratedQuery as j, DbRow as k, ActionTargetError as l, MetaStore as lt, TransportError as m, ClientValidatorOptions as n, TDbUpdateResult$1 as nt, ActionDisabledError as o, ValidGroupBy$1 as ot, ClientValidationError as p, ServerError as q, DbValidationContext as r, TypedWithRelation as rt, ActionDisabledErrorBody as s, ValidNested$1 as st, ClientValidator as t, TDbQueryTarget as tt, ActionTargetErrorBody as u, MetaStoreOptions as ut, AggregateResult$1 as v, ClientOptions as w, BucketExpr as x, AggregateStage as y, NestedAggregateResult$1 as z };