@atscript/db-client 0.1.195 → 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.
package/dist/index.d.mts CHANGED
@@ -1,476 +1,5 @@
1
- import { $ as TDbInsertManyResult, A as DecoratedControls, B as OwnOf, C as CalendarBucketLabel, D as DbInsert, E as DataOf, F as InsertOf, G as RowOf, H as PatchOf, I as MetaResponse, J as StageRow, K as SearchIndexInfo, L as NavOf, M as FieldMeta, N as FilterExpr, O as DbPatch, P as IdOf, Q as TDbInsertManyIgnoreResult, R as NestedAggregateQuery, S as BucketUnit, T as ClientResponse, U as RelationInfo, V as PageResult, W as ResponseDataOf, X as TDbDeleteResult, Y as TClientCallOptions, Z as TDbInsertIgnoreResult, _ as AggregateQuery, at as UniqueryControls, b as AtscriptClientShape, c as ActionNotFoundError, ct as WeekStart, d as ActionUnsupportedError, dt as clearMetaStore, et as TDbInsertResult, f as ClientError, ft as defaultMetaStore, g as VersionMismatchErrorBody, h as VersionMismatchError, i as ValidatorMode, it as Uniquery, j as DecoratedQuery, k as DbRow, l as ActionTargetError, lt as MetaStore, m as TransportError, n as ClientValidatorOptions, nt as TDbUpdateResult, o as ActionDisabledError, ot as ValidGroupBy, p as ClientValidationError, q as ServerError, rt as TypedWithRelation, s as ActionDisabledErrorBody, st as ValidNested, t as ClientValidator, tt as TDbQueryTarget, u as ActionTargetErrorBody, ut as MetaStoreOptions, v as AggregateResult, w as ClientOptions, x as BucketExpr, y as AggregateStage, z as NestedAggregateResult } from "./validator-FC3SyLqE.mjs";
2
- import { AggregateQuery as AggregateQuery$1, AggregateResult as AggregateResult$1, BucketSeriesOptions, ComputedExpr, NestedAggregateQuery as NestedAggregateQuery$1, NestedAggregateResult as NestedAggregateResult$1, NextBucketOptions, Uniquery as Uniquery$1, ValidGroupBy as ValidGroupBy$1, ValidNested as ValidNested$1, bucketSeries, bucketStartInstant, nextBucketLabel } from "@uniqu/core";
3
- import { TAtscriptAnnotatedType, TSerializedAnnotatedType } from "@atscript/typescript/utils";
4
- import { TCrudOp, TCrudPermissions, TDbActionInfo, TDbActionInfo as TDbActionInfo$1, TDbActionIntent, TDbActionLevel, TDbActionProcessor, TDbActionTargetSummary, TDbActionTargetSummary as TDbActionTargetSummary$1, TDbAvailableActions, TDbAvailableActions as TDbAvailableActions$1, TDbDeleteResult as TDbDeleteResult$1, TDbInsertIgnoreResult as TDbInsertIgnoreResult$1, TDbInsertManyIgnoreResult as TDbInsertManyIgnoreResult$1, TDbInsertManyResult as TDbInsertManyResult$1, TDbInsertResult as TDbInsertResult$1, TDbUpdateResult as TDbUpdateResult$1 } from "@atscript/db";
5
-
6
- //#region src/client.d.ts
7
- type Own<T> = OwnOf<T>;
8
- type Nav<T> = NavOf<T>;
9
- type Id<T> = IdOf<T>;
10
- type Response<T, Q> = ClientResponse<T, Q>;
11
- /** A read row: the response over the own fields plus the declared decorations `D`, each optional. */
12
- type DecoratedRow<T, Q, D> = Response<T, Q> & Partial<D>;
13
- /**
14
- * A `query()` / `pages()` row: {@link DecoratedRow}, plus `$score` on a vector read
15
- * (`$search` with `$vector`, since 0.1.183): higher = closer, on the scale of `$threshold`.
16
- */
17
- type ReadRow<T, Q, D> = DecoratedRow<T, Q, D> & (Q extends {
18
- controls: {
19
- $search: string;
20
- $vector: string;
21
- };
22
- } ? {
23
- $score: number;
24
- } : unknown);
25
- /**
26
- * One insert row for `returning`: an untyped client's row is any `object`,
27
- * which an array would match too — there it is any non-array object.
28
- */
29
- type SingleInsertOf<T> = [keyof InsertOf<T>] extends [never] ? Record<string, any> & {
30
- readonly [Symbol.iterator]?: never;
31
- } : InsertOf<T>;
32
- /** The stored row `insert(row, { returning: true })` answers: the `one()` row shape. */
33
- type InsertedRow<T, D> = DecoratedRow<T, Record<never, never>, D>;
34
- /** A two-level aggregate query: one with `controls.$from`. */
35
- type NestedShape = {
36
- controls: {
37
- $from: object;
38
- };
39
- };
40
- /** The compile-time check an aggregate query must pass: two-level or flat. */
41
- type AggregateCheck<T, Q> = Q extends NestedShape ? ValidNested$1<T, Q> : ValidGroupBy$1<T, Q>;
42
- /** The rows `aggregate()` answers for query `Q`. */
43
- type AggregateRows<T, Q extends AggregateQuery$1<T> | NestedAggregateQuery$1<T>> = Q extends NestedShape ? NestedAggregateResult$1<T, Q>[] : Q["controls"]["$select"] extends readonly (string | ComputedExpr)[] ? AggregateResult$1<T, Q["controls"]["$select"]>[] : Record<string, unknown>[];
44
- /**
45
- * HTTP client for moost-db REST endpoints.
46
- *
47
- * Each method maps 1:1 to a controller endpoint:
48
- * - `query()` → `GET /query`
49
- * - `count()` → `GET /query` with `$count`
50
- * - `aggregate()` → `GET /query` with `$groupBy`
51
- * - `pages()` → `GET /pages`
52
- * - `one()` → `GET /one/:id` or `GET /one?compositeKeys`
53
- * - `insert()` → `POST /`
54
- * - `update()` → `PATCH /`
55
- * - `replace()` → `PUT /`
56
- * - `remove()` → `DELETE /:id` or `DELETE /?compositeKeys`
57
- * - `meta()` → `GET /meta`
58
- *
59
- * ```typescript
60
- * const users = new Client<typeof User>('/api/users')
61
- * const all = await users.query()
62
- * const page = await users.pages({ filter: { active: true } }, 1, 20)
63
- * ```
64
- *
65
- * `D` (since 0.1.148) types the display-only fields the controller declares
66
- * with `@DbDecorations`: `$select` of the read methods accepts their keys and
67
- * rows carry them as optional properties. Filter and sort stay over `T`'s own
68
- * fields — a decoration is never filterable or sortable.
69
- *
70
- * ```typescript
71
- * const tickets = new Client<typeof Ticket, TicketDecorations>('/api/tickets')
72
- * const rows = await tickets.query({ controls: { $select: ['title', 'ownerName'] } })
73
- * rows[0].ownerName // string | undefined
74
- * ```
75
- */
76
- declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D extends object = Record<never, never>> {
77
- private readonly _path;
78
- private readonly _baseUrl;
79
- private readonly _fetch;
80
- private readonly _headers?;
81
- private readonly _navigate?;
82
- private readonly _lenientWrites?;
83
- private readonly _metaStore;
84
- private readonly _metaKey?;
85
- private readonly _locale?;
86
- /** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
87
- private _metaLocale?;
88
- private _metaPromise?;
89
- /** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
90
- private _metaEtag?;
91
- private _validatorPromise?;
92
- /** Loaded action forms (type + served `$i18n`) keyed by resolved URL. */
93
- private _formCache;
94
- constructor(path: string, opts?: ClientOptions);
95
- /**
96
- * `GET /query` — query records with typed filter, sort, select, and relations.
97
- *
98
- * The response type narrows by the literal `$with` array in `query` —
99
- * relations not listed in `$with` are stripped from the row type. A vector
100
- * read (`controls: { $search, $vector }`) types `$score` on every row.
101
- */
102
- query<const Q extends DecoratedQuery<T, D> = DecoratedQuery<T, D>>(query?: Q, opts?: TClientCallOptions): Promise<ReadRow<T, Q, D>[]>;
103
- /**
104
- * `GET /query` with `$count: true` — returns record count.
105
- */
106
- count(query?: {
107
- filter?: Uniquery$1<Own<T>, Nav<T>>["filter"];
108
- }, opts?: TClientCallOptions): Promise<number>;
109
- /**
110
- * `GET /query` with `$groupBy` — aggregate query with typed dimension/measure fields.
111
- * `$groupBy: []` is the ungrouped aggregate: one row over the filtered set (served
112
- * by moost-db since 0.1.155 — the URL carries the aggregate `$select` and no `$groupBy`).
113
- *
114
- * `$select` may carry calendar buckets (`{ $bucket, $field, $tz?, $weekStart?, $as? }`);
115
- * a `$groupBy` entry must be a dimension or a bucket alias (`ValidGroupBy`), and a
116
- * bucket's value is typed as its `YYYY-MM-DD` (hour: `YYYY-MM-DDTHH:00`) label
117
- * (`| null` for an optional source).
118
- * Gap-fill between labels with `nextBucketLabel` (re-exported here).
119
- *
120
- * Arithmetic (since 0.1.148): `{ $fn: 'sum', $expr, $as }` aggregates a per-row
121
- * expression over numeric fields; `{ $expr, $as }` computes over aliases of other
122
- * numeric entries or numeric `$groupBy` fields (`number | null`). `first` / `last`
123
- * read a representative row ordered by `$rowOrder`. The URL forms are `expr(a/b):x`,
124
- * `sum(a*b):x`, `first(f):x` and `$rowOrder=f,-id`.
125
- *
126
- * Since 0.1.168 (server: `/meta` `distinctFieldLists`, `conditionalAggregates`,
127
- * `nestedAggregates`):
128
- * - `{ $fn: 'countDistinct', $field: ['a', 'b'] }` counts distinct combinations (a row
129
- * with any NULL field is not counted); URL `countDistinct(a,b)`;
130
- * - `{ $fn, $field, $where, $as }` aggregates only the rows matching `$where` (a typed
131
- * filter); URL `sum(amount|status=paid):paid`;
132
- * - a query with `controls.$from` is a two-level aggregate: `$from` groups the filtered
133
- * rows, the root controls aggregate its rows and name its columns (its `$groupBy`
134
- * keys and aliases) — typed by `ValidNested`, rows by `NestedAggregateResult`.
135
- */
136
- aggregate<const Q extends AggregateQuery$1<Own<T>> | NestedAggregateQuery$1<Own<T>>>(query: Q & AggregateCheck<Own<T>, Q>, opts?: TClientCallOptions): Promise<AggregateRows<Own<T>, Q>>;
137
- /**
138
- * `GET /pages` — paginated query with typed filter and relations.
139
- *
140
- * Response rows narrow by the literal `$with` array — same algebra as
141
- * {@link query}, `$score` on a vector read included.
142
- */
143
- pages<const Q extends DecoratedQuery<T, D> = DecoratedQuery<T, D>>(query?: Q, page?: number, size?: number, opts?: TClientCallOptions): Promise<PageResult<ReadRow<T, Q, D>>>;
144
- /**
145
- * `GET /geo` — distance-ranked geospatial search (tables with `@db.index.geo`).
146
- *
147
- * `point` is `[lng, lat]` (GeoJSON order). Rows come back ordered by distance
148
- * ascending, each carrying a computed `$distance` (meters from `point`).
149
- * `$maxDistance` / `$minDistance` (meters) and `$index` (geo index name) ride
150
- * in `query.controls`; filter / `$select` / `$with` / `$skip` / `$limit`
151
- * compose as usual.
152
- */
153
- geoSearch<const Q extends DecoratedQuery<T, D> = DecoratedQuery<T, D>>(point: [number, number], query?: Q, opts?: TClientCallOptions): Promise<Array<DecoratedRow<T, Q, D> & {
154
- $distance: number;
155
- }>>;
156
- /**
157
- * `GET /geo` with `$page` / `$size` — paginated distance-ranked search.
158
- */
159
- geoPages<const Q extends DecoratedQuery<T, D> = DecoratedQuery<T, D>>(point: [number, number], query?: Q, page?: number, size?: number, opts?: TClientCallOptions): Promise<PageResult<DecoratedRow<T, Q, D> & {
160
- $distance: number;
161
- }>>;
162
- /**
163
- * `GET /one/:id` or `GET /one?k1=v1&k2=v2` — single record by primary key.
164
- *
165
- * Returns `null` on 404. Response narrows by the literal `$with` array in
166
- * `query.controls` — same algebra as {@link query}.
167
- */
168
- one<const Q extends {
169
- controls?: DecoratedControls<T, D>;
170
- } = {
171
- controls?: DecoratedControls<T, D>;
172
- }>(id: Id<T>, query?: Q, opts?: TClientCallOptions): Promise<DecoratedRow<T, Q, D> | null>;
173
- /**
174
- * `POST /` — insert many records.
175
- */
176
- insert(data: InsertOf<T>[], opts?: TClientCallOptions): Promise<TDbInsertManyResult$1>;
177
- /**
178
- * `POST /?$onConflict=ignore` — insert many records, skipping the ones that
179
- * collide; the result reports inserted and skipped input indices (since 0.1.148).
180
- */
181
- insert(data: InsertOf<T>[], opts: TClientCallOptions & {
182
- onConflict: "ignore";
183
- }): Promise<TDbInsertManyIgnoreResult$1>;
184
- /**
185
- * `POST /` with `Prefer: return=representation` — insert one record and
186
- * get the stored row back as `row` (since 0.1.168): server defaults and
187
- * stamps included, shaped as `one()` would answer it. `row` is absent when
188
- * the server could not apply the preference (the caller may not read the
189
- * row, or a skipped conflict).
190
- */
191
- insert(data: SingleInsertOf<T>, opts: TClientCallOptions & {
192
- returning: true;
193
- }): Promise<TDbInsertResult$1 & {
194
- row?: InsertedRow<T, D>;
195
- }>;
196
- /**
197
- * `POST /?$onConflict=ignore` with `Prefer: return=representation` — as
198
- * above; a skipped row answers `{ conflict: true }` without `row`.
199
- */
200
- insert(data: SingleInsertOf<T>, opts: TClientCallOptions & {
201
- returning: true;
202
- onConflict: "ignore";
203
- }): Promise<TDbInsertIgnoreResult$1 & {
204
- row?: InsertedRow<T, D>;
205
- }>;
206
- /**
207
- * `POST /` — insert one record. The version column (if any) is optional —
208
- * the server initialises it; `$cas` is rejected (no meaning on insert).
209
- */
210
- insert(data: InsertOf<T>, opts?: TClientCallOptions): Promise<TDbInsertResult$1>;
211
- /**
212
- * `POST /?$onConflict=ignore` — insert one record, skipping it when it
213
- * collides on the primary key or a unique index (since 0.1.148).
214
- */
215
- insert(data: InsertOf<T>, opts: TClientCallOptions & {
216
- onConflict: "ignore";
217
- }): Promise<TDbInsertIgnoreResult$1>;
218
- /**
219
- * `PATCH /` — partial update one or many records by primary key.
220
- *
221
- * Accepts both OCC shapes (since 0.1.128): a bare `version: N` (the wire
222
- * contract) or the SDK `$cas: { version: N }`, which is lifted to `version`
223
- * before preflight and sending. A stale version surfaces as
224
- * {@link VersionMismatchError}; a PK-only body with a version is a real
225
- * write (the server bumps the version).
226
- */
227
- update(data: PatchOf<T> | PatchOf<T>[], opts?: TClientCallOptions): Promise<TDbUpdateResult$1>;
228
- /**
229
- * `PUT /` — full replace one or many records by primary key. Same OCC
230
- * shapes as {@link update}; the version column itself is optional.
231
- */
232
- replace(data: RowOf<T> | RowOf<T>[], opts?: TClientCallOptions): Promise<TDbUpdateResult$1>;
233
- /**
234
- * `DELETE /:id` or `DELETE /?k1=v1&k2=v2` — remove a record by primary key.
235
- */
236
- remove(id: Id<T>, opts?: TClientCallOptions): Promise<TDbDeleteResult$1>;
237
- /**
238
- * `GET /meta` — table/view metadata (cached after first call).
239
- *
240
- * The response is revalidated through the client's meta store
241
- * (`ClientOptions.metaStore`): ETags seen before for this store key go out
242
- * as `If-None-Match`, and a `304 Not Modified` reuses the stored body.
243
- */
244
- meta(): Promise<MetaResponse>;
245
- /**
246
- * The `ETag` of the `/meta` body {@link meta} resolved to — `undefined`
247
- * before it resolves, after {@link invalidateMeta}, or when the server sent
248
- * no readable `ETag` (cross-origin without `Access-Control-Expose-Headers:
249
- * ETag`). Equal ETags mean byte-identical `/meta` bodies, so it can key
250
- * anything derived from them (deserialized types, validators, column
251
- * definitions) across clients and route params.
252
- *
253
- * @since 0.1.153
254
- */
255
- metaEtag(): string | undefined;
256
- /**
257
- * The {@link MetaStore} {@link meta} revalidates through — the shared
258
- * default store, the one passed as `ClientOptions.metaStore`, or
259
- * `undefined` when that option was `false`. Read-only: clear it on an
260
- * identity change (`client.metaStore?.clear()`) together with
261
- * {@link invalidateMeta}.
262
- *
263
- * @since 0.1.155
264
- */
265
- get metaStore(): MetaStore | undefined;
266
- /**
267
- * Drops everything this client cached from the server's metadata — the
268
- * `/meta` response, the validator built from it and the loaded action
269
- * forms — so the next call fetches them again. Call it when the viewer's
270
- * identity changes (login, logout, role change): `/meta` is projected per
271
- * user, and a client reused across identities would otherwise keep serving
272
- * the previous user's columns, actions and write rules.
273
- *
274
- * The next `meta()` still revalidates through the meta store, so an
275
- * unchanged `/meta` costs a `304`, not a download. On an identity change
276
- * also clear the store (`clearMetaStore()` / `metaStore.clear()`).
277
- *
278
- * @since 0.1.151
279
- */
280
- invalidateMeta(): void;
281
- /**
282
- * Invoke a declared action by name. Resolves the action descriptor from the
283
- * cached `/meta` response, then dispatches based on `processor`:
284
- *
285
- * - `'backend'` → POST the identifier as a JSON body to the action's path
286
- * and return the parsed server response. The HTTP method is always POST.
287
- * - `'navigate'` → for `level: 'row'`, substitute `$1` in `value` with the
288
- * identifier values, walking `meta.preferredId` field order (each value
289
- * URL-encoded, compound IDs joined with `/`); for `level: 'rows'` or
290
- * `'table'`, navigate to `value` verbatim. The default navigator (browser
291
- * only) calls `window.location.assign(url)`. Provide
292
- * `ClientOptions.navigate` to integrate with a SPA router.
293
- * - `'custom'` → throw {@link ActionUnsupportedError}; UI-dispatched events
294
- * are the application's responsibility, not the client's.
295
- *
296
- * Throws {@link ActionNotFoundError} when the action is not present in `/meta`.
297
- *
298
- * **Identifier shape (server contract).** `id` is always an object (single)
299
- * or array of objects (multi) — never a scalar. Each object's field set
300
- * must exactly match one legitimate identification on the table (PK or any
301
- * `@db.index.unique` group). Even single-field PK tables send `{ id: 'abc' }`,
302
- * not `'abc'`. `level: 'table'` actions take no identifier (`undefined`).
303
- *
304
- * The TypeScript signature widens to `Partial<Own<T>>` because the server's
305
- * exact-match validation cannot be expressed at the type level. Mismatched
306
- * field sets produce HTTP 400; obvious type errors (scalars, `null`) are
307
- * caught at compile time when `T` is typed.
308
- *
309
- * **Form input.** When the action's `inputForm` field is set, the server
310
- * expects a structured payload in the envelope's `input` field. Pass it as
311
- * the third argument; the schema can be fetched ahead of time via
312
- * {@link getActionForm} to drive a UI form. Body shape on the wire is
313
- * `{ ids?, input? }` — `ids` carries `id` (object or array per level),
314
- * `input` carries the form payload.
315
- *
316
- * **Delegated actions** (since 0.1.147). An action another controller owns
317
- * (`owner`, e.g. a view listing its source table's actions) may carry
318
- * `idMap`: each `id` is then a row (or identifier) of THIS controller and
319
- * is mapped to the owner's identification — `{ [ownerField]:
320
- * row[path] }` — before it is sent to `value` (the owner's route). A
321
- * missing path throws `TypeError`. See {@link actionIdentifier}.
322
- *
323
- * @typeParam R Caller-asserted return shape from the action handler. The
324
- * server returns whatever the handler emits (commonly
325
- * `{ message?: string, ... }`); the client cannot validate.
326
- */
327
- action<R = unknown>(name: string, id?: Partial<Own<T>> | Partial<Own<T>>[], input?: unknown): Promise<R>;
328
- /**
329
- * Runs a `'rows'` action on every row matching a query (since 0.1.147) —
330
- * the action's `/meta` entry must carry `queryTarget`. POSTs
331
- * `{ query: { q, exclude?, expectCount?, maxRows? }, input? }` to
332
- * `queryTarget.url` (a delegated action: the view resolves the rows and
333
- * runs the owner's action in batches) or `value`. `q` is the `/query`
334
- * string of `target.filter` / `search` / `index`.
335
- *
336
- * The server answers what the handler returns — for a delegated action
337
- * (and a handler returning `target.summary()`) a
338
- * {@link TDbActionTargetSummary}. Refusals arrive as
339
- * {@link ActionTargetError}: `TARGET_TOO_LARGE` (`cap`), `TARGET_CHANGED`
340
- * (`matched` differs from `expectCount`), `TARGET_INVALID`. Throws
341
- * {@link ActionUnsupportedError} when the action takes no query target.
342
- *
343
- * @since 0.1.147
344
- */
345
- actionOnQuery<R = TDbActionTargetSummary$1>(name: string, target: TDbQueryTarget<T>, input?: unknown): Promise<R>;
346
- /**
347
- * How many rows {@link actionOnQuery} would target right now (a dry run:
348
- * the handler does not run) — pass the answer as `expectCount` to make the
349
- * real run fail with `TARGET_CHANGED` if the set changed in between.
350
- *
351
- * @since 0.1.147
352
- */
353
- countActionTarget(name: string, target: TDbQueryTarget<T>): Promise<{
354
- matched: number;
355
- }>;
356
- private _queryTargetAction;
357
- private _postQueryTarget;
358
- /**
359
- * `GET /meta/actions/:id` or `GET /meta/actions?k1=v1&k2=v2` — the
360
- * row-level actions the caller may run on one row right now, and the
361
- * reasons of those disabled with one: `{ actions, disabledReasons? }`.
362
- * Works for rows the caller cannot read; an unknown or out-of-scope id
363
- * resolves to `{ actions: [] }`. Id forms as {@link one}.
364
- *
365
- * @since 0.1.145
366
- */
367
- availableActions(id: Id<T>): Promise<TDbAvailableActions$1>;
368
- /**
369
- * Fetches and caches the deserialized form schema for an action's
370
- * `@InputForm()` parameter. Returns `null` when the action has no form
371
- * declared, or doesn't exist on `/meta`. Callers typically pass the
372
- * returned annotated type to a form-renderer (e.g. `@atscript/ui` form
373
- * components) and then submit the collected payload through
374
- * {@link action}'s `input` argument.
375
- *
376
- * The schema comes from this controller's `meta/form/:name`, or — when the
377
- * action carries `formUrl` — from `baseUrl + formUrl`.
378
- * Cached per resolved URL.
379
- */
380
- getActionForm(actionName: string): Promise<TAtscriptAnnotatedType | null>;
381
- /**
382
- * The texts the action's form schema was served with in this client's
383
- * locale (its `$i18n`: registered message templates and the translated
384
- * literals of its expressions), or `undefined` when the server sent none
385
- * or the action has no form. Read from the same cached response as
386
- * {@link getActionForm}; merge them into your UI texts to show the form's
387
- * expression results in the user's language.
388
- *
389
- * @since 0.1.170
390
- */
391
- getActionFormTexts(actionName: string): Promise<Record<string, string> | undefined>;
392
- private _actionForm;
393
- private _loadActionForm;
394
- /**
395
- * Returns a lazily-initialized {@link ClientValidator} backed by the `/meta` type.
396
- * Useful for accessing `flatMap` and `navFields` (e.g. for form generation).
397
- */
398
- getValidator(): Promise<ClientValidator>;
399
- /** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
400
- private _prepareWrite;
401
- private _getValidator;
402
- private _buildActionBody;
403
- private _interpolateNavigateUrl;
404
- private _dispatchNavigate;
405
- private _postAction;
406
- private _idToParams;
407
- /**
408
- * The endpoint addressing one row under `base`: `base/<id>` for a scalar
409
- * id, `base?k1=v1&k2=v2` for an object id; `query` (a query string) is
410
- * appended.
411
- */
412
- private _idUrl;
413
- private _getOrNull;
414
- private _get;
415
- private _resolveHeaders;
416
- /** `ClientOptions.locale` now. */
417
- private _currentLocale;
418
- /** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
419
- private _syncLocale;
420
- /**
421
- * `GET /meta` through the meta store: conditional when the store holds
422
- * bodies for this key, falling back to a plain request whenever the
423
- * conditional one cannot be answered from the store.
424
- */
425
- private _loadMeta;
426
- /** Reads a `/meta` response; a `2xx` carrying a readable `ETag` goes into the store. */
427
- private _storeMeta;
428
- private _request;
429
- /** `baseUrl + path` joined with an endpoint relative to this controller (`""`, `meta`, `?q`…). */
430
- private _endpointUrl;
431
- /** Sends one request to an absolute URL with the client's headers and a JSON body. */
432
- private _requestUrl;
433
- private _send;
434
- /** `fetch` with a network failure surfaced as {@link TransportError}. */
435
- private _fetchUrl;
436
- /** A response's JSON body, or the matching error for a non-2xx status. */
437
- private _readResponse;
438
- }
439
- /**
440
- * The identifier `action` takes for one row (or identifier) of the
441
- * controller whose `/meta` listed it (since 0.1.147):
442
- *
443
- * - a delegated action with `idMap` → the owner's identification,
444
- * `{ [ownerField]: rowOrId[path] }` (dot paths allowed); a missing value
445
- * throws `TypeError` naming the action and the path;
446
- * - any other action → `rowOrId`'s `preferredId` fields when it carries them
447
- * all, else `rowOrId` itself (already an identifier).
448
- *
449
- * UIs build `ids` from loaded rows with it; `Client.action()` applies the
450
- * `idMap` mapping itself.
451
- *
452
- * @since 0.1.147
453
- */
454
- declare function actionIdentifier(action: Pick<TDbActionInfo$1, "name" | "idMap">, rowOrId: Record<string, unknown>, preferredId: readonly string[]): Record<string, unknown>;
455
- /**
456
- * Render a single identifier field for substitution into a navigate-URL
457
- * template or human-readable string. `null` / `undefined` collapse to `""`
458
- * (NOT the literal `"undefined"` / `"null"` that `String()` would produce).
459
- */
460
- declare function formatIdentifierField(v: unknown): string;
461
- /**
462
- * Render a row identifier as a `/`-joined string in `preferredId`
463
- * declaration order — NOT object-key insertion order (which is unstable
464
- * across callers). Raw form, no URL-encoding; for prompt text, error
465
- * messages, log lines, etc.
466
- */
467
- declare function formatIdentifier(id: Record<string, unknown> | undefined, preferredId: readonly string[]): string;
468
- /**
469
- * URL-encoded form of `formatIdentifier` — for `processor: 'navigate'`
470
- * `$1` substitution. Each field is `encodeURIComponent`'d, then joined
471
- * with a literal `/`. Missing fields render as empty segments (e.g.
472
- * `acme//jane`), not the literal `"undefined"`.
473
- */
474
- declare function encodeNavigateId(id: Record<string, unknown>, preferredId: readonly string[]): string;
475
- //#endregion
476
- export { ActionDisabledError, type ActionDisabledErrorBody, ActionNotFoundError, ActionTargetError, type ActionTargetErrorBody, ActionUnsupportedError, type AggregateQuery, type AggregateResult, type AggregateStage, type AtscriptClientShape, type BucketExpr, type BucketSeriesOptions, type BucketUnit, type CalendarBucketLabel, Client, ClientError, type ClientOptions, type ClientResponse, ClientValidationError, type ClientValidator, type ClientValidatorOptions, type DataOf, type DbInsert, type DbPatch, type DbRow, type FieldMeta, type FilterExpr, type IdOf, type InsertOf, type MetaResponse, MetaStore, type MetaStoreOptions, type NavOf, type NestedAggregateQuery, type NestedAggregateResult, type NextBucketOptions, type OwnOf, type PageResult, type PatchOf, type RelationInfo, type ResponseDataOf, type RowOf, type SearchIndexInfo, type ServerError, type StageRow, type TClientCallOptions, type TCrudOp, type TCrudPermissions, type TDbActionInfo, type TDbActionIntent, type TDbActionLevel, type TDbActionProcessor, type TDbActionTargetSummary, type TDbAvailableActions, type TDbDeleteResult, type TDbInsertIgnoreResult, type TDbInsertManyIgnoreResult, type TDbInsertManyResult, type TDbInsertResult, type TDbQueryTarget, type TDbUpdateResult, type TSerializedAnnotatedType, TransportError, type TypedWithRelation, type Uniquery, type UniqueryControls, type ValidGroupBy, type ValidNested, type ValidatorMode, VersionMismatchError, type VersionMismatchErrorBody, type WeekStart, actionIdentifier, bucketSeries, bucketStartInstant, clearMetaStore, defaultMetaStore, encodeNavigateId, formatIdentifier, formatIdentifierField, nextBucketLabel };
1
+ import { $ as RelationInfo, A as AggregateStage, B as DbPatch, C as ClientError, D as VersionMismatchErrorBody, E as VersionMismatchError, F as ClientLike, G as InsertOf, H as FieldMeta, I as ClientOptions, J as NestedAggregateQuery, K as MetaResponse, L as ClientResponse, M as BucketExpr, N as BucketUnit, O as AggregateQuery, P as CalendarBucketLabel, Q as PatchOf, R as DataOf, S as ActionUnsupportedError, St as defaultMetaStore, T as TransportError, U as FilterExpr, V as DbRow, W as IdOf, X as OwnOf, Y as NestedAggregateResult, Z as PageResult, _ as ActionDisabledError, _t as ValidNested, a as InsertedRow, at as TClientCallOptions, b as ActionTargetError, bt as MetaStoreOptions, c as actionIdentifier, ct as TDbInsertManyIgnoreResult, d as formatIdentifierField, dt as TDbQueryTarget, et as ResponseDataOf, f as ClientValidator, ft as TDbUpdateResult, gt as ValidGroupBy, h as ValidatorMode, ht as UniqueryControls, i as DecoratedRow, it as StageRow, j as AtscriptClientShape, k as AggregateResult, l as encodeNavigateId, lt as TDbInsertManyResult, mt as Uniquery, n as AggregateRows, nt as SearchIndexInfo, o as ReadRow, ot as TDbDeleteResult, p as ClientValidatorOptions, pt as TypedWithRelation, q as NavOf, r as Client, rt as ServerError, s as SingleInsertOf, st as TDbInsertIgnoreResult, t as AggregateCheck, tt as RowOf, u as formatIdentifier, ut as TDbInsertResult, v as ActionDisabledErrorBody, vt as WeekStart, w as ClientValidationError, x as ActionTargetErrorBody, xt as clearMetaStore, y as ActionNotFoundError, yt as MetaStore, z as DbInsert } from "./client-DIymxYkx.mjs";
2
+ import { BucketSeriesOptions, NextBucketOptions, bucketSeries, bucketStartInstant, nextBucketLabel } from "@uniqu/core";
3
+ import { TSerializedAnnotatedType } from "@atscript/typescript/utils";
4
+ import { TCrudOp, TCrudPermissions, TDbActionInfo, TDbActionIntent, TDbActionLevel, TDbActionProcessor, TDbActionTargetSummary, TDbAvailableActions } from "@atscript/db";
5
+ export { ActionDisabledError, type ActionDisabledErrorBody, ActionNotFoundError, ActionTargetError, type ActionTargetErrorBody, ActionUnsupportedError, type AggregateCheck, type AggregateQuery, type AggregateResult, type AggregateRows, type AggregateStage, type AtscriptClientShape, type BucketExpr, type BucketSeriesOptions, type BucketUnit, type CalendarBucketLabel, Client, ClientError, type ClientLike, type ClientOptions, type ClientResponse, ClientValidationError, type ClientValidator, type ClientValidatorOptions, type DataOf, type DbInsert, type DbPatch, type DbRow, type DecoratedRow, type FieldMeta, type FilterExpr, type IdOf, type InsertOf, type InsertedRow, type MetaResponse, MetaStore, type MetaStoreOptions, type NavOf, type NestedAggregateQuery, type NestedAggregateResult, type NextBucketOptions, type OwnOf, type PageResult, type PatchOf, type ReadRow, type RelationInfo, type ResponseDataOf, type RowOf, type SearchIndexInfo, type ServerError, type SingleInsertOf, type StageRow, type TClientCallOptions, type TCrudOp, type TCrudPermissions, type TDbActionInfo, type TDbActionIntent, type TDbActionLevel, type TDbActionProcessor, type TDbActionTargetSummary, type TDbAvailableActions, type TDbDeleteResult, type TDbInsertIgnoreResult, type TDbInsertManyIgnoreResult, type TDbInsertManyResult, type TDbInsertResult, type TDbQueryTarget, type TDbUpdateResult, type TSerializedAnnotatedType, TransportError, type TypedWithRelation, type Uniquery, type UniqueryControls, type ValidGroupBy, type ValidNested, type ValidatorMode, VersionMismatchError, type VersionMismatchErrorBody, type WeekStart, actionIdentifier, bucketSeries, bucketStartInstant, clearMetaStore, defaultMetaStore, encodeNavigateId, formatIdentifier, formatIdentifierField, nextBucketLabel };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClientError, c as VersionMismatchError, i as ActionUnsupportedError, n as ActionNotFoundError, o as ClientValidationError, r as ActionTargetError, s as TransportError, t as ActionDisabledError } from "./client-error-Dn4WeNft.mjs";
1
+ import { a as ClientError, c as VersionMismatchError, i as ActionUnsupportedError, n as ActionNotFoundError, o as ClientValidationError, r as ActionTargetError, s as TransportError, t as ActionDisabledError } from "./client-error-Dy1bhtlh.mjs";
2
2
  import { buildUrl } from "@uniqu/url/builder";
3
3
  import { bucketSeries, bucketStartInstant, nextBucketLabel } from "@uniqu/core";
4
4
  //#region src/meta-store.ts
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_client_error = require("./client-error-C9Q5xCuW.cjs");
2
+ const require_client_error = require("./client-error-YjY_SOaf.cjs");
3
3
  let _atscript_typescript_utils = require("@atscript/typescript/utils");
4
4
  let _atscript_db_validator = require("@atscript/db/validator");
5
5
  //#region src/validator.ts
@@ -20,10 +20,13 @@ var ClientValidator = class {
20
20
  navFields;
21
21
  /** The table's version column when it opts into OCC (from `/meta`). */
22
22
  versionColumn;
23
+ /** The version column is a `@db.column.version.token` in the served type (since 0.1.196). */
24
+ _versionToken;
23
25
  constructor(type, opts) {
24
26
  this._type = type;
25
27
  this._lenientWrites = opts?.lenientWrites === true;
26
28
  this.versionColumn = opts?.versionColumn;
29
+ if ((this.versionColumn === void 0 ? void 0 : type.type.props.get(this.versionColumn))?.metadata.has("db.column.version.token")) this._versionToken = true;
27
30
  if (opts?.messages) this._translate = (0, _atscript_typescript_utils.messagesTranslator)(opts.messages);
28
31
  const ctx = (0, _atscript_db_validator.buildValidationContext)(type);
29
32
  this.flatMap = ctx.flatMap;
@@ -32,7 +35,8 @@ var ClientValidator = class {
32
35
  /**
33
36
  * Normalises the SDK `$cas` shape to the wire shape (since 0.1.128):
34
37
  * `{ id, $cas: { version: 4 } }` → `{ id, version: 4 }` (the server lifts
35
- * `version` back to `$cas`). Returns a shallow clone per item; items
38
+ * `version` back to `$cas`). On a `@db.column.version.token` column (read
39
+ * from the served type, since 0.1.196) the version is a string. Returns a shallow clone per item; items
36
40
  * without `$cas` (a `$cas: undefined` counts as absent) are returned
37
41
  * as-is. Throws `ClientValidationError` when the table is not versioned,
38
42
  * the `$cas` shape is invalid, or `version` and `$cas` disagree — the same
@@ -53,7 +57,7 @@ var ClientValidator = class {
53
57
  }]);
54
58
  const clone = { ...item };
55
59
  try {
56
- (0, _atscript_db_validator.reconcileCas)(clone, this.versionColumn, "version");
60
+ (0, _atscript_db_validator.reconcileCas)(clone, this.versionColumn, "version", this._versionToken);
57
61
  } catch (e) {
58
62
  if (e instanceof _atscript_db_validator.DbError) throw new require_client_error.ClientValidationError(e.errors.map((err) => toEntry(err, `${prefix}${err.path}`)));
59
63
  throw e;
@@ -1,2 +1,2 @@
1
- import { a as createClientValidator, i as ValidatorMode, n as ClientValidatorOptions, p as ClientValidationError, r as DbValidationContext, t as ClientValidator } from "./validator-D9QYeBWO.cjs";
1
+ import { f as ClientValidator, g as createClientValidator, h as ValidatorMode, m as DbValidationContext, p as ClientValidatorOptions, w as ClientValidationError } from "./client-CNTDhOXn.cjs";
2
2
  export { ClientValidationError, ClientValidator, ClientValidatorOptions, type DbValidationContext, type ValidatorMode, createClientValidator };
@@ -1,2 +1,2 @@
1
- import { a as createClientValidator, i as ValidatorMode, n as ClientValidatorOptions, p as ClientValidationError, r as DbValidationContext, t as ClientValidator } from "./validator-FC3SyLqE.mjs";
1
+ import { f as ClientValidator, g as createClientValidator, h as ValidatorMode, m as DbValidationContext, p as ClientValidatorOptions, w as ClientValidationError } from "./client-DIymxYkx.mjs";
2
2
  export { ClientValidationError, ClientValidator, ClientValidatorOptions, type DbValidationContext, type ValidatorMode, createClientValidator };
@@ -1,4 +1,4 @@
1
- import { o as ClientValidationError } from "./client-error-Dn4WeNft.mjs";
1
+ import { o as ClientValidationError } from "./client-error-Dy1bhtlh.mjs";
2
2
  import { deserializeAnnotatedType, localizeErrors, messagesTranslator } from "@atscript/typescript/utils";
3
3
  import { DbError, buildValidationContext, dbValidatorOptions, normalizeWritePayload, reconcileCas } from "@atscript/db/validator";
4
4
  //#region src/validator.ts
@@ -19,10 +19,13 @@ var ClientValidator = class {
19
19
  navFields;
20
20
  /** The table's version column when it opts into OCC (from `/meta`). */
21
21
  versionColumn;
22
+ /** The version column is a `@db.column.version.token` in the served type (since 0.1.196). */
23
+ _versionToken;
22
24
  constructor(type, opts) {
23
25
  this._type = type;
24
26
  this._lenientWrites = opts?.lenientWrites === true;
25
27
  this.versionColumn = opts?.versionColumn;
28
+ if ((this.versionColumn === void 0 ? void 0 : type.type.props.get(this.versionColumn))?.metadata.has("db.column.version.token")) this._versionToken = true;
26
29
  if (opts?.messages) this._translate = messagesTranslator(opts.messages);
27
30
  const ctx = buildValidationContext(type);
28
31
  this.flatMap = ctx.flatMap;
@@ -31,7 +34,8 @@ var ClientValidator = class {
31
34
  /**
32
35
  * Normalises the SDK `$cas` shape to the wire shape (since 0.1.128):
33
36
  * `{ id, $cas: { version: 4 } }` → `{ id, version: 4 }` (the server lifts
34
- * `version` back to `$cas`). Returns a shallow clone per item; items
37
+ * `version` back to `$cas`). On a `@db.column.version.token` column (read
38
+ * from the served type, since 0.1.196) the version is a string. Returns a shallow clone per item; items
35
39
  * without `$cas` (a `$cas: undefined` counts as absent) are returned
36
40
  * as-is. Throws `ClientValidationError` when the table is not versioned,
37
41
  * the `$cas` shape is invalid, or `version` and `$cas` disagree — the same
@@ -52,7 +56,7 @@ var ClientValidator = class {
52
56
  }]);
53
57
  const clone = { ...item };
54
58
  try {
55
- reconcileCas(clone, this.versionColumn, "version");
59
+ reconcileCas(clone, this.versionColumn, "version", this._versionToken);
56
60
  } catch (e) {
57
61
  if (e instanceof DbError) throw new ClientValidationError(e.errors.map((err) => toEntry(err, `${prefix}${err.path}`)));
58
62
  throw e;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-client",
3
- "version": "0.1.195",
3
+ "version": "0.1.196",
4
4
  "description": "Browser-compatible HTTP client for @atscript/moost-db REST endpoints.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -47,14 +47,14 @@
47
47
  "@uniqu/url": "^0.2.2"
48
48
  },
49
49
  "devDependencies": {
50
- "@atscript/core": "^0.2.22",
51
- "@atscript/typescript": "^0.2.22",
52
- "unplugin-atscript": "^0.2.22",
53
- "@atscript/db": "0.1.195"
50
+ "@atscript/core": "^0.2.23",
51
+ "@atscript/typescript": "^0.2.23",
52
+ "unplugin-atscript": "^0.2.23",
53
+ "@atscript/db": "0.1.196"
54
54
  },
55
55
  "peerDependencies": {
56
- "@atscript/typescript": "^0.2.22",
57
- "@atscript/db": "^0.1.195"
56
+ "@atscript/typescript": "^0.2.23",
57
+ "@atscript/db": "^0.1.196"
58
58
  },
59
59
  "scripts": {
60
60
  "build": "vp pack",