@atscript/db-odata 0.0.0-stage → 0.0.2

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.mjs ADDED
@@ -0,0 +1,1395 @@
1
+ import { BaseDbAdapter, DbError, DbSpace, isPlainObject, searchIndexNotFoundMessage } from "@atscript/db";
2
+ import { VERSION_TOKEN, allowedWrites, changeByKey, createODataSource, createSession, dbFailureOf, describeEntitySet, describeField, dialectFor, isODataError, isODataPayloadError, isODataQueryError, isODataServiceError, rowsFailure, runOperation, runParameters, sendEach, sendsRowToken, storeFailure, withLocale, writeFailureOf, writeRefusal } from "@atscript/odata";
3
+ import { resolveAlias } from "@uniqu/core";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/errors.ts
6
+ /**
7
+ * An operation the adapter refuses before any request: one OData cannot express (a write by a
8
+ * filter, a field operator, a grouped read `$apply` has no form for), or one the service model
9
+ * does not allow (a write to an entity set that is not insertable, updatable or deletable, or
10
+ * that is draft-enabled; a grouped read of a set without `$apply`, or of what it does not
11
+ * aggregate).
12
+ *
13
+ * A `DbError` with atscript-db's code `NOT_SUPPORTED` (the adapter cannot perform what was asked),
14
+ * which moost-db answers with `400`: the request can avoid it. Its one entry names no `params`, as
15
+ * moost-db's `NOT_SUPPORTED` does, and is coded `NOT_SUPPORTED`, or as the browser client codes the
16
+ * same refusal (`UNSUPPORTED_FIELD_OPERATOR` for a field operator, `CAS_NOT_SUPPORTED` for a
17
+ * version number); the browser client answers a write the entity set does not allow, and a
18
+ * grouped read it cannot answer, with the same body (`dbFailureOf` of `@atscript/odata`).
19
+ */
20
+ var ODataNotSupportedError = class extends DbError {
21
+ name = "ODataNotSupportedError";
22
+ /** The adapter method that was called (`insertMany`, `updateOne`, `deleteMany`, `aggregate`, …). */
23
+ operation;
24
+ /**
25
+ * @param message why it is refused; by default that the adapter does not support `operation`
26
+ * @param cause the engine's refusal; the entry's `path` is the one an `ODataQueryError` names
27
+ * (the field or control it is about), else empty
28
+ * @param entry the entry's `path` and `code` where the browser client names the same refusal
29
+ * so (a field operator at its field, `UNSUPPORTED_FIELD_OPERATOR`; a version number at `$cas`,
30
+ * `CAS_NOT_SUPPORTED`); by default `NOT_SUPPORTED` at the path above
31
+ */
32
+ constructor(operation, entitySet, message, cause, entry = {}) {
33
+ const text = message ?? `${operation} is not supported by the OData adapter ("${entitySet}")`;
34
+ const path = entry.path ?? (isODataQueryError(cause) ? cause.path ?? "" : "");
35
+ super("NOT_SUPPORTED", [{
36
+ path,
37
+ message: text,
38
+ code: entry.code ?? "NOT_SUPPORTED"
39
+ }], text, cause === void 0 ? void 0 : { cause });
40
+ this.operation = operation;
41
+ }
42
+ };
43
+ /** Also true for an `ODataNotSupportedError` created by another copy of this package. */
44
+ function isODataNotSupportedError(value) {
45
+ return value instanceof ODataNotSupportedError || value instanceof Error && value.name === "ODataNotSupportedError" && typeof value.operation === "string";
46
+ }
47
+ /**
48
+ * What a Moost server answers for a failure of its own call that `dbFailureOf` leaves to the
49
+ * host: the service could not be reached, refused the server's credentials (`401`, `403`) or a
50
+ * write without a session the CSRF token needs, answered another status, a page or a payload that
51
+ * is no OData answer, or a paging link that leads nowhere: `STORE_FAILED`; the call was aborted
52
+ * (`callTimeout`): `STORE_TIMEOUT`. The server calls the service with credentials it is given,
53
+ * never the caller's own, so each is a fault behind the server, not of the request. A
54
+ * precondition the service demands and its metadata does not declare (`428`, or a `412` to a
55
+ * request without `If-Match`: `etag-required`) is `STORE_FAILED` with a message that says so, its
56
+ * entry coded `PRECONDITION_REQUIRED`.
57
+ */
58
+ function serverFailureOf(error, entitySet) {
59
+ if (writeFailureOf(error) === "etag-required") {
60
+ const message = `The data service accepts this request only with a precondition (If-Match) that its metadata does not declare for "${entitySet}": nothing was applied`;
61
+ return {
62
+ ...storeFailure("STORE_FAILED"),
63
+ message,
64
+ entries: [{
65
+ path: "",
66
+ message,
67
+ code: "PRECONDITION_REQUIRED"
68
+ }]
69
+ };
70
+ }
71
+ if (isODataError(error)) return storeFailure(error.kind === "aborted" ? "STORE_TIMEOUT" : "STORE_FAILED");
72
+ if (isODataServiceError(error) || isODataPayloadError(error)) return storeFailure("STORE_FAILED");
73
+ }
74
+ /**
75
+ * Turns what the OData engine throws into the `DbError` the atscript-db stack expects, with the
76
+ * original as `cause`:
77
+ *
78
+ * - every failure `dbFailureOf` of `@atscript/odata` maps (the one mapping both hosts answer
79
+ * with): `NOT_SUPPORTED` for what OData or the entity set cannot do (a write the set does not
80
+ * allow, a grouped read it cannot answer, what OData v2 cannot express); `INVALID_QUERY` for a
81
+ * read or write the engine refused (moost-db's codes on the entries: `UNKNOWN_FIELD`,
82
+ * `FIELD_NOT_PERMITTED`, …; a refused write keeps the engine's code), a value that cannot be
83
+ * written, a read past `maxPages` (on `$limit`) and a `400` of the service (its messages by
84
+ * field); `CONFLICT` for a `409` of the service; `SERIALIZATION_FAILURE` for a write that met a
85
+ * change between reading the entity's ETag and writing on every attempt; `STORE_THROTTLED`
86
+ * (`params.retryAfter`), `STORE_TIMEOUT` and `STORE_FAILED` for the service's `429`, `504` and
87
+ * other `5xx`
88
+ * - every other failure of the service, which `dbFailureOf` leaves to the host: `STORE_FAILED`
89
+ * (it could not be reached, refused the server's credentials or a write without a session,
90
+ * demanded a precondition its metadata does not declare (`PRECONDITION_REQUIRED` on the entry),
91
+ * answered another status or no OData answer; a `404` is one of them: a key read never gets here
92
+ * with it, the engine answers that with "no entity", and the adapter answers a write by key that
93
+ * meets one with "nothing matched"), `STORE_TIMEOUT` (the call was aborted)
94
+ *
95
+ * moost-db answers the `STORE_*` codes `502`, `504` and `429` (with `Retry-After`) and logs every
96
+ * `5xx` with the cause; their messages are generic, what the service said stays in the cause.
97
+ * Anything else (a `DbError`, an error of the `init` hook, a bug) is returned as it is.
98
+ *
99
+ * @param model the service model, which maps the targets of the service's messages to field paths
100
+ * @param parameters of a failed operation call: the parameters of the operation (`runParameters`
101
+ * of `@atscript/odata`), whose messages are then reported at the parameter they name
102
+ */
103
+ function toDbError(error, entitySet, model, parameters) {
104
+ const failure = dbFailureOf(error, {
105
+ model,
106
+ entitySet,
107
+ parameters
108
+ }) ?? serverFailureOf(error, entitySet);
109
+ if (!failure) return error;
110
+ return new DbError(failure.code, failure.entries, failure.message, { cause: error });
111
+ }
112
+ /**
113
+ * What `runOperation` answered, or threw, with each error mapped as a call on its row alone: the
114
+ * one rule of the space's and a table's `callOperation`. A `412` on the caller's own version token
115
+ * (the row carries `token`: the entity changed since the caller read it) is `null`, the row's
116
+ * version mismatch for the caller to answer: one row resolves `null`, a row of several is
117
+ * `{ index, error: null }` in `failed`. A row the service has no entity for (the ETag read finds
118
+ * none, or the call is answered `404` or `410`) is a `DbError` `NOT_FOUND`; every other failure is
119
+ * mapped by {@link toDbError}, as a refused `changeSet` run of several rows is.
120
+ *
121
+ * @param context `token`, the field the rows carry the version token in, where the call sends it
122
+ * as `If-Match` (`sendsRowToken`; none: no `null`); the entity set, the model and the operation's
123
+ * `parameters` (`runParameters`) that map the targets of the service's messages
124
+ */
125
+ async function operationAnswer(running, rows = [], context) {
126
+ const { token, entitySet, model, parameters } = context;
127
+ const mapped = (error, row) => {
128
+ const failure = writeFailureOf(error);
129
+ if (token !== void 0 && typeof row?.[token] === "string" && row[token] !== "" && failure === "changed") return null;
130
+ if (row !== void 0 && failure === "not-found") return new DbError("NOT_FOUND", [{
131
+ path: "",
132
+ message: "Not found"
133
+ }], "Not found", { cause: error });
134
+ return toDbError(error, entitySet, model, parameters);
135
+ };
136
+ let answer;
137
+ try {
138
+ answer = await running;
139
+ } catch (error) {
140
+ const failure = mapped(error, rows.length === 1 ? rows[0] : void 0);
141
+ if (failure === null) return null;
142
+ throw failure;
143
+ }
144
+ if (answer.failed) answer.failed = answer.failed.map(({ index, error }) => ({
145
+ index,
146
+ error: mapped(error, rows[index])
147
+ }));
148
+ return answer;
149
+ }
150
+ //#endregion
151
+ //#region src/refusals.ts
152
+ /** The verdict refusing `operation` among a connection's refusals; `undefined` when it fits. */
153
+ function refusalIn(connection, operation) {
154
+ const verdict = connection?.refusals?.[operation.paramsType];
155
+ return verdict && verdict.operation.operation === operation.operation ? verdict : void 0;
156
+ }
157
+ //#endregion
158
+ //#region src/read-spec.ts
159
+ function isKeyValue(value) {
160
+ const type = typeof value;
161
+ return type === "string" || type === "number" || type === "boolean" || type === "bigint" || value instanceof Date;
162
+ }
163
+ function collectEqualities(filter, found) {
164
+ if (!isPlainObject(filter)) return false;
165
+ for (const [name, value] of Object.entries(filter)) {
166
+ if (value === void 0) continue;
167
+ if (name === "$and") {
168
+ if (!Array.isArray(value)) return false;
169
+ if (!value.every((member) => collectEqualities(member, found))) return false;
170
+ continue;
171
+ }
172
+ if (name.startsWith("$")) return false;
173
+ let operand = value;
174
+ if (isPlainObject(value)) {
175
+ const operators = Object.keys(value);
176
+ if (operators.length !== 1 || operators[0] !== "$eq") return false;
177
+ operand = value.$eq;
178
+ }
179
+ if (!isKeyValue(operand)) return false;
180
+ if (found.has(name) && found.get(name) !== operand) return false;
181
+ found.set(name, operand);
182
+ }
183
+ return true;
184
+ }
185
+ /**
186
+ * The entity key a filter addresses, when the filter is exactly an equality on every key property
187
+ * and nothing else: `{ K: v }`, `{ K: { $eq: v } }`, several keys in one object or spread over a
188
+ * `$and`. This is how an id lookup of the table layer arrives. `undefined` for every other filter.
189
+ */
190
+ function keyOf(filter, keys) {
191
+ if (keys.length === 0) return void 0;
192
+ const found = /* @__PURE__ */ new Map();
193
+ if (!collectEqualities(filter, found) || found.size !== keys.length) return void 0;
194
+ const key = {};
195
+ for (const name of keys) {
196
+ if (!found.has(name)) return void 0;
197
+ key[name] = found.get(name);
198
+ }
199
+ return key;
200
+ }
201
+ const covers = (ancestor, path) => path === ancestor || path.startsWith(`${ancestor}.`);
202
+ /** The paths a `$select` asks for, with no path listed under a selected parent. */
203
+ function selectedPaths(select, leaves) {
204
+ const projection = select.asProjection;
205
+ if (!projection) return void 0;
206
+ const entries = Object.entries(projection);
207
+ if (entries[0][1] === 1) {
208
+ const included = entries.filter(([, flag]) => flag === 1).map(([path]) => path);
209
+ return included.filter((path) => !included.some((other) => other !== path && covers(other, path)));
210
+ }
211
+ const excluded = entries.filter(([, flag]) => flag === 0).map(([path]) => path);
212
+ return leaves.filter((leaf) => !excluded.some((path) => covers(path, leaf)));
213
+ }
214
+ /**
215
+ * `$sort` as `$orderby`. A key property the service cannot sort by is left out: the table layer
216
+ * appends the primary key to every `$sort` as a tie-breaker, after its own capability check, and
217
+ * a tie-breaker the service cannot honour must not fail the read. Any other property is passed
218
+ * on, and the query layer refuses the read when the service cannot sort by it.
219
+ */
220
+ function orderByOf(sort, context) {
221
+ const orderBy = [];
222
+ for (const [path, direction] of Object.entries(sort ?? {})) {
223
+ if (context.unsortableKeys.includes(path)) continue;
224
+ orderBy.push(direction === -1 ? {
225
+ path,
226
+ desc: true
227
+ } : { path });
228
+ }
229
+ return orderBy;
230
+ }
231
+ function count(value) {
232
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
233
+ }
234
+ /**
235
+ * Translates what the table layer hands an adapter into a {@link ReadSpec}:
236
+ *
237
+ * - `filter` is passed on as it is: paths use `.` between segments on both sides
238
+ * - `$select` → `select` (an exclusion projection becomes the remaining leaves), without the
239
+ * version token, which the service does not have: the adapter fills it from the ETag
240
+ * - `$sort` → `orderBy`, without the key properties the service cannot sort by
241
+ * - `$skip` / `$limit` → `skip` / `top`
242
+ *
243
+ * `$with` is left to {@link withRelations}: its entries name the tables of the relations, whose
244
+ * adapters translate their part. The other controls are not reads of an entity set and are
245
+ * ignored here.
246
+ */
247
+ function readShapeOf(query, context) {
248
+ const { controls } = query;
249
+ const spec = { entitySet: context.entitySet };
250
+ if (query.filter && Object.keys(query.filter).length > 0) spec.filter = query.filter;
251
+ const shape = { spec };
252
+ const select = controls.$select ? selectedPaths(controls.$select, context.leaves) : void 0;
253
+ if (select) {
254
+ spec.select = select.filter((path) => path !== context.token);
255
+ shape.projection = select.map((path) => path.split("."));
256
+ }
257
+ const orderBy = orderByOf(controls.$sort, context);
258
+ if (orderBy.length > 0) spec.orderBy = orderBy;
259
+ const skip = count(controls.$skip);
260
+ if (skip) spec.skip = skip;
261
+ const top = count(controls.$limit);
262
+ if (top !== void 0) spec.top = top;
263
+ return shape;
264
+ }
265
+ /**
266
+ * `shape` of a related table's read, whose rows keep the table's key: a selection of the relation
267
+ * is widened with the key properties it leaves out, as atscript-db's relation loader keeps the key
268
+ * of a related row it joins by, and as the service sends it (the browser client hands the rows on
269
+ * as they come).
270
+ */
271
+ function keepingKey(shape, key) {
272
+ const { projection } = shape;
273
+ if (!projection) return shape;
274
+ for (const name of key) if (!projection.some((segments) => segments.length === 1 && segments[0] === name)) projection.push([name]);
275
+ return shape;
276
+ }
277
+ /** The expansion of a relation: the parts of its table's read an expansion takes. */
278
+ function expansionOf({ nav, shape }) {
279
+ const { filter, select, orderBy, expand } = shape.spec;
280
+ const expansion = { navigation: nav };
281
+ if (filter) expansion.filter = filter;
282
+ if (select) expansion.select = select;
283
+ if (orderBy) expansion.orderBy = orderBy;
284
+ if (expand) expansion.expand = expand;
285
+ return expansion;
286
+ }
287
+ /**
288
+ * `shape` with the relations of `$with` as expansions of its request (`$expand`): the filter,
289
+ * selection, sort and nested relations of each go with it. The table layer never pages a
290
+ * relation of this adapter. The navigations join the projection, so a `$select` of the read does
291
+ * not cut them away.
292
+ */
293
+ function withRelations(shape, relations) {
294
+ if (relations.length === 0) return shape;
295
+ shape.relations = relations;
296
+ shape.spec.expand = relations.map(expansionOf);
297
+ if (shape.projection) for (const { nav } of relations) shape.projection.push([nav]);
298
+ return shape;
299
+ }
300
+ function copyPath(from, to, segments, depth) {
301
+ const name = segments[depth];
302
+ if (!Object.hasOwn(from, name)) return;
303
+ const value = from[name];
304
+ if (depth === segments.length - 1 || !isPlainObject(value)) {
305
+ to[name] = value;
306
+ return;
307
+ }
308
+ const target = isPlainObject(to[name]) ? to[name] : {};
309
+ to[name] = target;
310
+ copyPath(value, target, segments, depth + 1);
311
+ }
312
+ /** The rows with only the selected paths; the rows themselves when everything is selected. */
313
+ function projectRows(rows, projection) {
314
+ if (!projection) return rows;
315
+ return rows.map((row) => {
316
+ const projected = {};
317
+ for (const segments of projection) copyPath(row, projected, segments, 0);
318
+ return projected;
319
+ });
320
+ }
321
+ /**
322
+ * The rows of a read cut back to its shape: the selected paths of each row, and the related
323
+ * rows of each relation cut back to the relation's own shape, at every depth. The service
324
+ * returns more than was asked for (the key always, a complex value as a whole on v2).
325
+ */
326
+ function shapeRows(rows, shape) {
327
+ const shaped = projectRows(rows, shape.projection);
328
+ for (const { nav, shape: related } of shape.relations ?? []) for (const row of shaped) {
329
+ const value = row[nav];
330
+ if (Array.isArray(value)) row[nav] = shapeRows(value, related);
331
+ else if (isPlainObject(value)) row[nav] = shapeRows([value], related)[0];
332
+ }
333
+ return shaped;
334
+ }
335
+ //#endregion
336
+ //#region src/write-payload.ts
337
+ /**
338
+ * A value that replaces a complex value as a whole, with every member it leaves out set to
339
+ * `null`: OData merges a complex value sent with `PATCH` / `MERGE` into the stored one, so an
340
+ * omitted member would otherwise keep its stored value.
341
+ */
342
+ function wholeValue(value, path, membersOf) {
343
+ const whole = {};
344
+ for (const [name, member] of Object.entries(value)) whole[name] = isPlainObject(member) ? wholeValue(member, `${path}.${name}`, membersOf) : member;
345
+ for (const name of membersOf(path) ?? []) if (!Object.hasOwn(whole, name)) whole[name] = null;
346
+ return whole;
347
+ }
348
+ /**
349
+ * The payload of an OData partial update (`PATCH` on v4, `MERGE` on v2) for a patch as the table
350
+ * layer hands it to `updateOne`:
351
+ *
352
+ * - a top-level member is set as it is; a complex value (an object) replaces the stored one,
353
+ * which is what the table layer means by it (`@db.patch.strategy "replace"`, the default), so
354
+ * the members it leaves out are sent as `null`
355
+ * - a dot path (`Address.City`, from a `@db.patch.strategy "merge"` object) is written into its
356
+ * complex value, whose other members the service keeps: OData merges complex values in a
357
+ * partial update
358
+ * - an array is a collection, which OData replaces as a whole
359
+ */
360
+ function patchPayload(data, membersOf) {
361
+ const payload = {};
362
+ const paths = [];
363
+ for (const [name, value] of Object.entries(data)) if (name.includes(".")) paths.push([name.split("."), value]);
364
+ else payload[name] = isPlainObject(value) ? wholeValue(value, name, membersOf) : value;
365
+ for (const [segments, value] of paths) {
366
+ let target = payload;
367
+ for (const segment of segments.slice(0, -1)) {
368
+ const next = target[segment];
369
+ target = isPlainObject(next) ? next : target[segment] = {};
370
+ }
371
+ target[segments.at(-1)] = isPlainObject(value) ? wholeValue(value, segments.join("."), membersOf) : value;
372
+ }
373
+ return payload;
374
+ }
375
+ //#endregion
376
+ //#region src/odata-adapter.ts
377
+ /** The name of the one search index an entity set with free-text search has. */
378
+ const ODATA_SEARCH_INDEX = "DEFAULT";
379
+ const STORE_DEFAULT_FNS = new Set(["store"]);
380
+ /** What the table layer reads a primary-key or foreign-key field with. */
381
+ const KEY_FILTER_OPS = ["$eq", "$in"];
382
+ /** A query-layer operator that is a comparison of atscript-db (no relation predicate). */
383
+ function isComparison(op) {
384
+ return op !== "$some" && op !== "$none";
385
+ }
386
+ function under(path, parents) {
387
+ return parents.some((parent) => path.startsWith(`${parent}.`));
388
+ }
389
+ /** The first field a field operator (`$inc`, `$mul`) names; `undefined` when there is none. */
390
+ function fieldOpPath(ops) {
391
+ return [ops?.inc, ops?.mul].flatMap((fields) => Object.keys(fields ?? {}))[0];
392
+ }
393
+ function sendInit(init) {
394
+ const { read: _read, maxPages: _maxPages, ...send } = init;
395
+ return send;
396
+ }
397
+ /**
398
+ * An `@atscript/db` adapter over an entity set of an OData v2 / v4 service, through the
399
+ * `@atscript/odata` engine. One instance serves one table; its entity set is the table's name
400
+ * (`@db.table`, which the generator writes as the entity set's name).
401
+ *
402
+ * Writes go one entity at a time, by key: create, partial update, replace and delete. Writes by a
403
+ * filter and field operators throw {@link ODataNotSupportedError} before any request. On an entity
404
+ * set with optimistic concurrency the table has a version token (the entity's ETag): an update or
405
+ * replace that carries it (`$cas`) is sent with it as `If-Match`, and a change made since the
406
+ * caller's read matches nothing, which moost-db answers as its version mismatch. One that does
407
+ * not carry it, and every delete, is last-write-wins: the adapter reads the current ETag right
408
+ * before the write, which satisfies the service's If-Match requirement but detects no change made
409
+ * since the caller's own read (a change between that read and the write has the write sent again,
410
+ * three attempts at most, then `SERIALIZATION_FAILURE`). A call the service does not serve is a
411
+ * `STORE_FAILED`, `STORE_TIMEOUT` or `STORE_THROTTLED` (see `toDbError`). There
412
+ * are no transactions: a write of several rows that fails midway leaves the rows written before
413
+ * it. The relations of `$with` ride the read as `$expand` (see {@link supportsWithInRead}).
414
+ */
415
+ var ODataAdapter = class extends BaseDbAdapter {
416
+ _set;
417
+ _leaves;
418
+ _members;
419
+ _keyFields;
420
+ _aggregateFns;
421
+ _fields = /* @__PURE__ */ new Map();
422
+ _service;
423
+ provide;
424
+ /** The entity set (the table's name) and the value-help service the adapter was bound to. */
425
+ _bound;
426
+ /** What the entity set was described from: the live model, or the saved one for a gone set. */
427
+ _described;
428
+ _gone = false;
429
+ constructor(service, options = {}) {
430
+ super();
431
+ this.options = options;
432
+ this.provide = typeof service === "function" ? service : () => service;
433
+ }
434
+ /**
435
+ * The service the table is read from: the one the adapter was created with, or, for a type of
436
+ * one of its value-help services (`@odata.valueHelpService`), that service's engine
437
+ * (`service.valueHelpService(…)`).
438
+ *
439
+ * @throws Error before the service is known (a live space not connected yet).
440
+ */
441
+ get service() {
442
+ this.describe();
443
+ return this._service;
444
+ }
445
+ /**
446
+ * Whether the live service no longer has the entity set (a live space only): every call of
447
+ * the table then throws a plain `Error`, a fault of the server's build (moost-db answers it
448
+ * `500`); the OData controller bases of `@atscript/moost-odata` answer such a table `404` first.
449
+ */
450
+ get gone() {
451
+ this.describe();
452
+ return this._gone;
453
+ }
454
+ /** Describes the entity set once the service is known; see {@link entitySet}. */
455
+ describe() {
456
+ if (this._set) return this._set;
457
+ const bound = this._bound;
458
+ if (!bound) throw new Error("The OData adapter is not bound to a table: it has no entity set");
459
+ const base = this.provide();
460
+ if (!base) throw new Error(`Table "${bound.name}": its OData space is not connected. Call \`await space.connect()\` before the tables are used (before \`app.init()\`).`);
461
+ const { saved } = this.options;
462
+ let service = base;
463
+ if (bound.valueHelp !== void 0) {
464
+ service = base.valueHelpService(bound.valueHelp);
465
+ if (!service && !saved) throw new Error(`The OData service has no value-help service "${bound.valueHelp}" (table "${bound.name}"). Create the service from the model module generated with the types, which holds its value-help services.`);
466
+ }
467
+ if (service && Object.hasOwn(service.model.entitySets, bound.name)) {
468
+ this._service = service;
469
+ this._described = {
470
+ model: service.model,
471
+ context: service.context
472
+ };
473
+ } else {
474
+ const model = bound.valueHelp === void 0 ? saved : saved?.valueHelpServices?.[bound.valueHelp]?.model;
475
+ if (!model || !Object.hasOwn(model.entitySets, bound.name)) throw new Error(`The OData service has no entity set "${bound.name}"`);
476
+ this._gone = true;
477
+ this._service = service ?? base;
478
+ this._described = {
479
+ model,
480
+ context: {
481
+ version: model.version,
482
+ dialect: dialectFor(model)
483
+ }
484
+ };
485
+ }
486
+ this._set = describeEntitySet(this._described.model, bound.name, this._described.context);
487
+ return this._set;
488
+ }
489
+ /**
490
+ * Refuses every call of a table whose entity set the live service no longer has: the server's
491
+ * build no longer fits the service, which no request can avoid (a plain `Error`).
492
+ */
493
+ refuseGone() {
494
+ if (!this.gone) return;
495
+ throw new Error(`The OData service no longer has the entity set "${this._bound.name}"`);
496
+ }
497
+ /**
498
+ * Why an operation of the build bound to this entity set is refused: its verdict when the live
499
+ * service no longer has it or no longer fits the build's calls of it (see
500
+ * `ODataSpace.refusalOf`); `undefined` when it fits.
501
+ */
502
+ refusalOf(operation) {
503
+ return refusalIn(this.options.connection?.(), operation);
504
+ }
505
+ /**
506
+ * Calls an operation bound to this entity set (`runOperation` of `@atscript/odata`, the entity
507
+ * set filled in), with the space's credentials and session, as every call of the table: on the
508
+ * collection, or, for an operation called on rows, on `rows` (each with its key and, where the
509
+ * set has a version token, its `__etag`). The handle of an unbound operation (it names no entity
510
+ * set) is called unbound: a db action of the table over it. The parameters are validated against
511
+ * the live operation type (the validator's `ValidatorError`); what the call throws is mapped as
512
+ * the table's calls are (`toDbError`).
513
+ *
514
+ * A call that sends the caller's version token (a call that writes, on a row with its `__etag`;
515
+ * see `sendsRowToken`) that the service refuses with `412` resolves `null`: the entity changed
516
+ * since the caller read it, a version mismatch for the caller to answer (a Moost server answers
517
+ * it as moost-db answers a stale write: `409` with the current token, or `404`). Without the
518
+ * token the ETag is read first, and read again when the entity changed in between
519
+ * (`retryWhileChanged`, then `SERIALIZATION_FAILURE`).
520
+ *
521
+ * A row the service has no entity for (the ETag read before its call finds none, or the call is
522
+ * answered `404` or `410`) is a `DbError` `NOT_FOUND`, which the OData controller bases answer as
523
+ * moost-db answers a missing row (`notFoundError()`, `404`). An operation the live service no
524
+ * longer has never gets here: its verdict refuses it before any call.
525
+ *
526
+ * Several rows go out as one `$batch` by `input.grouping` (see `runOperation`; one call per row
527
+ * on a service created with `batch: false`, as a space's `batch: false` creates it). Each row of
528
+ * an `isolated` run that failed is in `failed`, its error mapped as a call on that row alone: a
529
+ * `DbError` (`toDbError`, `NOT_FOUND` above), or `null` for a `412` on its own `__etag` (its
530
+ * version mismatch, as for one row). A `changeSet` run the service refused throws its one error,
531
+ * mapped so (`SERIALIZATION_FAILURE` for a `412`, `CONFLICT` for a `404`: nothing was applied;
532
+ * the entries of a message that names a row at that row, `[1]`).
533
+ *
534
+ * @throws Error for an entity set the live service no longer has.
535
+ */
536
+ async callOperation(input) {
537
+ this.refuseGone();
538
+ const connection = this.options.connection?.();
539
+ if (!connection) throw new Error(`Table "${this.entitySet.name}": an operation runs on the connection of an OData space (createODataSpace), which it has not`);
540
+ const init = sendInit(await this.options.init?.() ?? {});
541
+ const run = typeof input.operation !== "string" && input.operation.entitySet === void 0 ? { ...input } : {
542
+ ...input,
543
+ entitySet: this.entitySet.name
544
+ };
545
+ return operationAnswer(runOperation(connection, run, init), input.rows, {
546
+ token: sendsRowToken(connection, run) ? this.token : void 0,
547
+ entitySet: this.entitySet.name,
548
+ model: this.service.model,
549
+ parameters: runParameters(connection, run)
550
+ });
551
+ }
552
+ registerReadable(...args) {
553
+ super.registerReadable(...args);
554
+ const [readable] = args;
555
+ const valueHelp = readable.type.metadata.get("odata.valueHelpService");
556
+ this._bound = {
557
+ name: readable.tableName,
558
+ ...typeof valueHelp === "string" ? { valueHelp } : {}
559
+ };
560
+ if (this.provide()) this.describe();
561
+ }
562
+ /**
563
+ * The entity set this adapter reads, as the query layer describes it: from the live model, or,
564
+ * for a set the live service no longer has, from the saved one.
565
+ */
566
+ get entitySet() {
567
+ return this.describe();
568
+ }
569
+ /** A complex type is a nested object; paths arrive as `Address.City`. */
570
+ supportsNestedObjects() {
571
+ return true;
572
+ }
573
+ /** Referential integrity is the service's business. */
574
+ supportsNativeForeignKeys() {
575
+ return true;
576
+ }
577
+ /**
578
+ * The relations of `$with` are read in the request of the rows, as `$expand`: every row comes
579
+ * back with its related rows under the navigation name. Each `$with` entry goes into the
580
+ * expansion as the table layer hands it over, with its filter (a relation's own and any a
581
+ * controller conjoined into the entry), its `$select` and `$sort` and its nested entries, so a
582
+ * scope a server adds to a relation reaches the service. OData v2 has no options in an
583
+ * expansion other than the selection: there a filter or sort of a relation is refused
584
+ * (`NOT_SUPPORTED`), never dropped. The table layer refuses paging a relation itself.
585
+ *
586
+ * A navigation the service declares no foreign key for (`@db.rel.store`) is read the same way.
587
+ */
588
+ supportsWithInRead() {
589
+ return true;
590
+ }
591
+ /** A relation is read through `$expand`: only to a table of the same service. */
592
+ sharesStoreWith(other) {
593
+ return super.sharesStoreWith(other) && other.service === this.service;
594
+ }
595
+ /**
596
+ * The aggregate functions of the entity set's `$apply` (`aggregateFns` of `describeEntitySet`):
597
+ * none on OData v2 and on a set the service declares no `Aggregation.ApplySupported` for; `sum`,
598
+ * `min`, `max`, `avg` on an SAP service; also `count` and `countDistinct` on any other. The
599
+ * table layer refuses any other function before {@link aggregate} is called.
600
+ */
601
+ aggregateFns() {
602
+ this._aggregateFns ??= new Set(this.entitySet.aggregateFns);
603
+ return this._aggregateFns;
604
+ }
605
+ /**
606
+ * `store`: a property the service computes (`@db.default.store`, which the generator emits) is
607
+ * left to the service when an insert leaves it out, and a value given for it is dropped by the
608
+ * engine. The key the service assigns comes back in `insertedId`.
609
+ */
610
+ nativeDefaultFns() {
611
+ return STORE_DEFAULT_FNS;
612
+ }
613
+ /**
614
+ * The row version is the entity's ETag, which the service moves on every write: the generator
615
+ * emits a version token field on every entity set with optimistic concurrency. Reads fill it;
616
+ * an update or replace with `$cas` sends it as `If-Match`.
617
+ */
618
+ supportsVersionTokens() {
619
+ return true;
620
+ }
621
+ /**
622
+ * Whether the service can compare the field with a value. A property whose type has no literal
623
+ * form (a stream, a geo value, `Edm.Untyped`) answers `false` although the query layer takes a
624
+ * null check on it: this method is about value comparison; {@link filterOps} lists the
625
+ * operators. A primary-key or foreign-key field is always filterable, by `$eq` and `$in`.
626
+ */
627
+ canFilterField(fd) {
628
+ if (fd.encrypted) return false;
629
+ return this.fieldOf(fd.path).filterOps.includes("$eq") || this.keyFields.has(fd.path);
630
+ }
631
+ /**
632
+ * The operators the service lets a filter use on the field: `allowedFilterOps` of
633
+ * `describeField` (what the query layer translates for the property's type, narrowed by the
634
+ * service's filter restriction). `[]` for a field the service does not let you filter by, so a
635
+ * lone `$exists` is refused there too. The table layer refuses any other operator before a
636
+ * request, and `/meta` serves the list.
637
+ *
638
+ * A primary-key or foreign-key field always keeps `$eq` and `$in`, which the table layer reads
639
+ * by itself (key reads, relation loads) and requires of such a field: a key the service declares
640
+ * non-filterable, or single-value only, still lists them. An equality on the whole key is a key
641
+ * read (`EntitySet(key)`), which needs no filter; any other filter on it the service judges.
642
+ */
643
+ filterOps(fd) {
644
+ const ops = this.fieldOf(fd.path).allowedFilterOps.filter(isComparison);
645
+ if (!this.keyFields.has(fd.path)) return ops;
646
+ return [...KEY_FILTER_OPS.filter((op) => !ops.includes(op)), ...ops];
647
+ }
648
+ /** The primary-key and foreign-key fields of the table. */
649
+ get keyFields() {
650
+ if (!this._keyFields) {
651
+ const fields = new Set(this._table.primaryKeys);
652
+ for (const fk of this._table.foreignKeys.values()) for (const field of fk.fields) fields.add(field);
653
+ this._keyFields = fields;
654
+ }
655
+ return this._keyFields;
656
+ }
657
+ canSortField(fd) {
658
+ return !fd.encrypted && !fd.isGeoPoint && this.fieldOf(fd.path).sortable;
659
+ }
660
+ isSearchable() {
661
+ return this.entitySet.searchable;
662
+ }
663
+ getSearchIndexes() {
664
+ if (!this.isSearchable()) return [];
665
+ return [{
666
+ name: ODATA_SEARCH_INDEX,
667
+ type: "text",
668
+ description: "Free-text search of the OData service",
669
+ isDefault: true
670
+ }];
671
+ }
672
+ fieldOf(path) {
673
+ let field = this._fields.get(path);
674
+ if (!field) {
675
+ const { name } = this.entitySet;
676
+ const { model, context } = this._described;
677
+ field = describeField(model, name, path, context);
678
+ this._fields.set(path, field);
679
+ }
680
+ return field;
681
+ }
682
+ /**
683
+ * A filter that is exactly an equality on every key property is read by key
684
+ * (`EntitySet(key)`); anything else is the first row of a collection read. A missing entity is
685
+ * `null`.
686
+ */
687
+ findOne(query) {
688
+ return this.call(async (init) => {
689
+ const shape = this.shapeOf(query);
690
+ const key = shape.spec.skip ? void 0 : keyOf(query.filter, this.entitySet.key);
691
+ if (key) {
692
+ const { entitySet, select, expand } = shape.spec;
693
+ const found = await this.service.readOne({
694
+ entitySet,
695
+ key,
696
+ select,
697
+ expand
698
+ }, init);
699
+ if (!found) return null;
700
+ return shapeRows(this.withTokens([found.row], [found.etag]), shape)[0];
701
+ }
702
+ const read = await this.service.read({
703
+ ...shape.spec,
704
+ top: 1
705
+ }, init);
706
+ return read.rows.length > 0 ? this.rowsOf(read, shape)[0] : null;
707
+ });
708
+ }
709
+ /**
710
+ * Reads the matching rows; the engine follows the paging links of the service up to `$limit`.
711
+ * A read without `$limit` that the service cuts into more pages than the engine follows fails
712
+ * (`INVALID_QUERY` on `$limit`) instead of answering with a part of the rows.
713
+ */
714
+ findMany(query) {
715
+ return this.call(async (init) => {
716
+ const shape = this.shapeOf(query);
717
+ return this.rowsOf(await this.service.read(shape.spec, init), shape);
718
+ });
719
+ }
720
+ /**
721
+ * `/$count`; a filter that is exactly an equality on every key property is a key read instead,
722
+ * which also works on a set that cannot count or demands a filter on other properties. The
723
+ * table layer asks this way whether the row of a patch with nothing to write exists.
724
+ */
725
+ count(query) {
726
+ return this.call(async (init) => {
727
+ const key = keyOf(query.filter, this.entitySet.key);
728
+ if (!key) return this.service.count(this.countSpecOf(query), init);
729
+ const { name: entitySet, key: select } = this.entitySet;
730
+ return await this.service.readOne({
731
+ entitySet,
732
+ key,
733
+ select
734
+ }, init) ? 1 : 0;
735
+ });
736
+ }
737
+ /** One request: the rows with the inline count of the service. */
738
+ findManyWithCount(query) {
739
+ return this.call((init) => this.readWithCount(this.shapeOf(query), init));
740
+ }
741
+ search(text, query, indexName) {
742
+ return this.call(async (init) => {
743
+ const shape = this.searchShapeOf(text, query, indexName);
744
+ return this.rowsOf(await this.service.read(shape.spec, init), shape);
745
+ });
746
+ }
747
+ searchWithCount(text, query, indexName) {
748
+ return this.call((init) => this.readWithCount(this.searchShapeOf(text, query, indexName), init));
749
+ }
750
+ /**
751
+ * A grouped read, as one OData v4 `$apply` request (`planAggregate` of `@atscript/odata`): the
752
+ * filter, the grouping with its aggregates, `$having` as a filter of the groups, then `$sort`,
753
+ * `$skip` and `$limit` over the groups; `$count` asks for the number of groups
754
+ * (`$top=0&$count=true`) and answers `[{ count }]`. Rows come back with the grouped fields
755
+ * (nested under a complex property) and every aggregate under its alias, decoded as reads are
756
+ * (a decimal as a string, a count as a number).
757
+ *
758
+ * Refused with {@link ODataNotSupportedError} before any request: a set that cannot aggregate
759
+ * (OData v2, no `Aggregation.ApplySupported`), and what the service model rules out (an amount
760
+ * whose currency is not grouped, `sum` / `avg` of what is no number, `count` of a field,
761
+ * `$search`). What only the service knows it answers itself.
762
+ */
763
+ aggregate(query) {
764
+ return this.call(async (init) => {
765
+ const spec = this.aggregateSpecOf(query);
766
+ try {
767
+ const result = await this.service.aggregate(spec, init);
768
+ return spec.count ? [{ count: result.count }] : result.rows;
769
+ } catch (error) {
770
+ if (isODataQueryError(error) && error.code === "UNSUPPORTED_AGGREGATE") throw new ODataNotSupportedError("aggregate", this.entitySet.name, error.message, error);
771
+ throw error;
772
+ }
773
+ });
774
+ }
775
+ /**
776
+ * Creates the entity: `POST` to the entity set. Resolves with its key: the one the service
777
+ * reports (from the returned entity, else from the `Location` / `OData-EntityId` header), else
778
+ * the one in `data` when it was sent. A key property the service computes is not sent (the
779
+ * engine drops it), so its value in `data` does not count.
780
+ */
781
+ insertOne(data) {
782
+ return this.write("insertOne", "insert", async (init) => ({ insertedId: await this.create(data, init) }));
783
+ }
784
+ /**
785
+ * One `POST` per row. Several rows go out as one `$batch`, each row in a changeset of its own
786
+ * (on OData v4 the service is asked to continue past a failed part): it is not atomic, and the
787
+ * rows after a failed one still run. On a service created with `batch: false` (a space's
788
+ * `batch: false`) or without `$batch`, the rows go one after the other, on past a failed one,
789
+ * answered alike. The table
790
+ * layer inserts a single row this way too: one plain `POST`, its failure its own.
791
+ *
792
+ * Several rows answer `{ insertedCount, insertedIds }` in request order when every row was
793
+ * created. When rows failed it throws the first failed row's error (its code), with every
794
+ * failed row's entries at that row (`[1].City`, `[1]`) and, for each row created, an entry
795
+ * `{ path: "[j]", code: "INSERTED", message, params: { insertedId } }`; its message says how many
796
+ * rows were created and which failed (`rowsFailure` of `@atscript/odata`). Every row failed: the
797
+ * first row's message, no `INSERTED` entry. A `$batch` that failed as a whole: that failure,
798
+ * mapped as a single call's (nothing is known to have run).
799
+ */
800
+ insertMany(data) {
801
+ return this.write("insertMany", "insert", async (init) => {
802
+ if (data.length === 1) return {
803
+ insertedCount: 1,
804
+ insertedIds: [await this.create(data[0], init)]
805
+ };
806
+ const set = this.entitySet.name;
807
+ const rows = data.map((row) => this.withoutToken(row));
808
+ const settled = await sendEach(this.service, rows.length, (index, target) => target.batch ? target.batch.create(set, rows[index]) : this.service.create(set, rows[index], target.init), init);
809
+ const created = [];
810
+ const failed = [];
811
+ settled.forEach((outcome, index) => {
812
+ if (outcome.status === "rejected") failed.push({
813
+ index,
814
+ error: toDbError(outcome.reason, set, this.service.model)
815
+ });
816
+ else created.push({
817
+ index,
818
+ insertedId: this.insertedId(rows[index], outcome.value)
819
+ });
820
+ });
821
+ if (failed.length === 0) return {
822
+ insertedCount: created.length,
823
+ insertedIds: created.map((row) => row.insertedId)
824
+ };
825
+ const [first] = failed;
826
+ if (!failed.every(({ error }) => error instanceof DbError)) throw first.error;
827
+ const { message, entries } = rowsFailure(rows.length, failed.map(({ index, error }) => {
828
+ const { code, message, errors } = error;
829
+ return {
830
+ index,
831
+ code,
832
+ message,
833
+ entries: errors
834
+ };
835
+ }), created);
836
+ const error = first.error;
837
+ throw new DbError(error.code, entries, message, { cause: error.cause });
838
+ });
839
+ }
840
+ /**
841
+ * Replaces the entity (`PUT`) addressed by `filter`, which has to be an equality on every key
842
+ * property. Properties the service maintains are not sent. An entity the service does not
843
+ * have matches nothing.
844
+ */
845
+ replaceOne(filter, data, expectedVersion) {
846
+ return this.write("replaceOne", "update", async (init, operation) => {
847
+ const key = this.keyFor(operation, filter);
848
+ return this.change(operation, key, init, expectedVersion, (etag) => this.service.replace(this.entitySet.name, key, data, {
849
+ ...init,
850
+ etag
851
+ }));
852
+ });
853
+ }
854
+ /**
855
+ * Partially updates the entity (`MERGE` on v2, `PATCH` on v4) addressed by `filter`, which has
856
+ * to be an equality on every key property. A complex value in `data` replaces the stored one
857
+ * (its other members are sent as `null`); a dot path is merged into it. Field operators
858
+ * (`$inc`, `$mul`) are refused. An entity the service does not have matches nothing.
859
+ */
860
+ updateOne(filter, data, ops, expectedVersion) {
861
+ return this.write("updateOne", "update", async (init, operation) => {
862
+ const opPath = fieldOpPath(ops);
863
+ if (opPath !== void 0) throw new ODataNotSupportedError(operation, this.entitySet.name, "Field operators ($inc, $mul) cannot be expressed in an OData write: send the new value", void 0, {
864
+ path: opPath,
865
+ code: "UNSUPPORTED_FIELD_OPERATOR"
866
+ });
867
+ const key = this.keyFor(operation, filter);
868
+ const patch = patchPayload(data, (path) => this.membersOf(path));
869
+ return this.change(operation, key, init, expectedVersion, (etag) => this.service.update(this.entitySet.name, key, patch, {
870
+ ...init,
871
+ etag
872
+ }));
873
+ });
874
+ }
875
+ /**
876
+ * Deletes the entity addressed by `filter`, which has to be an equality on every key property.
877
+ * An entity the service does not have is not deleted (`deletedCount: 0`). Last-write-wins, as
878
+ * an update without a version token: the current ETag is read right before the delete, again
879
+ * when the entity changed in between (`retryWhileChanged`).
880
+ */
881
+ deleteOne(filter) {
882
+ return this.write("deleteOne", "delete", async (init, operation) => {
883
+ const key = this.keyFor(operation, filter);
884
+ const { matched } = await changeByKey((etag) => this.service.remove(this.entitySet.name, key, {
885
+ ...init,
886
+ etag
887
+ }), this.byKey(key, init));
888
+ return { deletedCount: matched ? 1 : 0 };
889
+ });
890
+ }
891
+ updateMany() {
892
+ return this.refuseByFilter("updateMany");
893
+ }
894
+ replaceMany() {
895
+ return this.refuseByFilter("replaceMany");
896
+ }
897
+ deleteMany() {
898
+ return this.refuseByFilter("deleteMany");
899
+ }
900
+ /** The service owns its schema: there is nothing to create. */
901
+ ensureTable() {
902
+ return Promise.resolve();
903
+ }
904
+ refuseByFilter(operation) {
905
+ const name = this._set?.name ?? "";
906
+ return Promise.reject(new ODataNotSupportedError(operation, name, `${operation} writes the rows a filter matches; the OData adapter writes one entity of "${name}" at a time, by its key`));
907
+ }
908
+ /**
909
+ * The writes the service model allows on the entity set, as the adapter applies them
910
+ * (`allowedWrites` of `@atscript/odata`, the rule the browser client follows too): none on a set
911
+ * that is draft-enabled, can only be reached through a navigation, or holds the parameters of a
912
+ * parameterized view. Every other write is refused with {@link ODataNotSupportedError} before any
913
+ * request.
914
+ */
915
+ get allowedWrites() {
916
+ return allowedWrites(this.entitySet);
917
+ }
918
+ /**
919
+ * What the service model says about writing to the entity set, whatever the write sends:
920
+ * `writeRefusal` of `@atscript/odata`.
921
+ */
922
+ refuseUnless(operation, write) {
923
+ const refusal = writeRefusal(this.entitySet, write);
924
+ if (refusal) throw new ODataNotSupportedError(operation, this.entitySet.name, refusal.message, refusal);
925
+ }
926
+ /** The key of a write by key; any other filter is refused (there is no write by query). */
927
+ keyFor(operation, filter) {
928
+ const { name, key: names } = this.entitySet;
929
+ const key = keyOf(filter, names);
930
+ if (key) return key;
931
+ throw new ODataNotSupportedError(operation, name, `${operation} needs a filter that is exactly an equality on every key property of "${name}" (${names.join(", ")}): an OData service writes one entity by its key`);
932
+ }
933
+ /**
934
+ * Runs a write: refuses what the service model does not allow before anything is asked, then
935
+ * calls `init` once and maps what the write throws (see `toDbError`).
936
+ */
937
+ async write(operation, write, run) {
938
+ this.refuseGone();
939
+ this.refuseUnless(operation, write);
940
+ const init = sendInit(await this.options.init?.() ?? {});
941
+ try {
942
+ return await run(init, operation);
943
+ } catch (error) {
944
+ throw toDbError(error, this.entitySet.name, this.service.model);
945
+ }
946
+ }
947
+ async create(data, init) {
948
+ const row = this.withoutToken(data);
949
+ return this.insertedId(row, await this.service.create(this.entitySet.name, row, init));
950
+ }
951
+ /** The row to create: the service issues the ETag, so a token given with it means nothing. */
952
+ withoutToken(data) {
953
+ const { token } = this;
954
+ if (!token || !Object.hasOwn(data, token)) return data;
955
+ const { [token]: _token, ...rest } = data;
956
+ return rest;
957
+ }
958
+ /**
959
+ * The key of a created row: the one the service reports (from the returned entity, else from
960
+ * the `Location` / `OData-EntityId` header), else the one sent.
961
+ */
962
+ insertedId(data, result) {
963
+ const written = { ...data };
964
+ for (const path of result.dropped ?? []) delete written[path];
965
+ if (result.key) Object.assign(written, result.key);
966
+ return this._resolveInsertedId(written, void 0, result.key);
967
+ }
968
+ /**
969
+ * How a write by key reads the entity (`changeByKey` of `@atscript/odata`): its ETag, when the
970
+ * entity set declares optimistic concurrency (with or without naming the properties), read
971
+ * right before a write without the caller's token to be sent as `If-Match`; when the entity
972
+ * answers without one, `*` is sent (the set wants an If-Match). After a write with nothing to
973
+ * send, its existence is read
974
+ * by the key alone.
975
+ *
976
+ * The pre-read only satisfies the service's If-Match requirement (it would answer `428`
977
+ * otherwise). It is not optimistic concurrency: the ETag is read by the adapter, not carried
978
+ * from the caller's own read, so the write is last-write-wins and overwrites whatever changed
979
+ * since the caller read the entity. A change in the moment between this read and the write (a
980
+ * `412`) has the ETag read again and the write sent again (three attempts); conflict detection
981
+ * is the caller's version token (`$cas`, see {@link change}).
982
+ */
983
+ byKey(key, init) {
984
+ const { name: entitySet, key: select, optimisticConcurrency } = this.entitySet;
985
+ return {
986
+ read: async () => {
987
+ const found = await this.service.readOne({
988
+ entitySet,
989
+ key
990
+ }, init);
991
+ return found ? { etag: found.etag } : void 0;
992
+ },
993
+ readEtag: optimisticConcurrency !== void 0,
994
+ exists: async () => !!await this.service.readOne({
995
+ entitySet,
996
+ key,
997
+ select
998
+ }, init)
999
+ };
1000
+ }
1001
+ /**
1002
+ * An update or replace by key (`changeByKey` of `@atscript/odata`). With `expected` (the
1003
+ * caller's version token, from `$cas`) it is sent as `If-Match` and nothing is read first: a
1004
+ * `412` (the entity changed) and a `404` match nothing, which moost-db answers as its version
1005
+ * mismatch (409, the current token) or a missing row. Without it, the ETag the set needs is
1006
+ * read right before the write (last-write-wins), and read again when the entity changed in
1007
+ * between (three attempts, then `SERIALIZATION_FAILURE`).
1008
+ */
1009
+ async change(operation, key, init, expected, send) {
1010
+ if (expected !== void 0 && typeof expected !== "string") throw new ODataNotSupportedError(operation, this.entitySet.name, "A version number ($cas) cannot be checked by an OData service, which compares ETags: send the entity's version token", void 0, {
1011
+ path: "$cas",
1012
+ code: "CAS_NOT_SUPPORTED"
1013
+ });
1014
+ const { matched, modified } = await changeByKey(send, {
1015
+ ...this.byKey(key, init),
1016
+ ...expected === void 0 ? {} : { etag: expected }
1017
+ });
1018
+ return {
1019
+ matchedCount: matched ? 1 : 0,
1020
+ modifiedCount: modified ? 1 : 0
1021
+ };
1022
+ }
1023
+ /**
1024
+ * The members of the complex value at `path`, from the table's stored fields
1025
+ * (`storedDescriptors`: no navigation property or part of one).
1026
+ */
1027
+ membersOf(path) {
1028
+ if (!this._members) {
1029
+ const members = /* @__PURE__ */ new Map();
1030
+ for (const fd of this._table.storedDescriptors) {
1031
+ const dot = fd.path.lastIndexOf(".");
1032
+ if (dot < 0) continue;
1033
+ const parent = fd.path.slice(0, dot);
1034
+ const list = members.get(parent) ?? [];
1035
+ list.push(fd.path.slice(dot + 1));
1036
+ members.set(parent, list);
1037
+ }
1038
+ this._members = members;
1039
+ }
1040
+ return this._members.get(path);
1041
+ }
1042
+ /** Runs an operation with the call options of the current request, and maps what it throws. */
1043
+ async call(run) {
1044
+ this.refuseGone();
1045
+ const init = await this.options.init?.() ?? {};
1046
+ try {
1047
+ return await run({
1048
+ ...init,
1049
+ read: {
1050
+ selectUnits: false,
1051
+ ...init.read
1052
+ }
1053
+ });
1054
+ } catch (error) {
1055
+ throw toDbError(error, this._set?.name ?? "", this.service.model);
1056
+ }
1057
+ }
1058
+ get context() {
1059
+ const { name, key, sortableKey } = this.entitySet;
1060
+ const context = {
1061
+ entitySet: name,
1062
+ unsortableKeys: key.filter((name) => !sortableKey.includes(name)),
1063
+ leaves: this.leaves
1064
+ };
1065
+ if (this.token) context.token = this.token;
1066
+ return context;
1067
+ }
1068
+ /**
1069
+ * The version token field of the table (`@db.column.version.token`, which the generator emits on
1070
+ * an entity set with optimistic concurrency); `undefined` when it has none.
1071
+ */
1072
+ get token() {
1073
+ return this._table.versionToken ? this._table.versionColumn : void 0;
1074
+ }
1075
+ /**
1076
+ * The rows of a read, each with its ETag as the version token, cut back to the selection, and
1077
+ * their related rows to theirs.
1078
+ */
1079
+ rowsOf(result, shape) {
1080
+ return shapeRows(this.withTokens(result.rows, result.etags ?? []), shape);
1081
+ }
1082
+ /** Puts each row's ETag into the version token field, when the table has one. */
1083
+ withTokens(rows, etags) {
1084
+ const { token } = this;
1085
+ if (!token) return rows;
1086
+ for (const [i, row] of rows.entries()) {
1087
+ const etag = etags[i];
1088
+ if (etag !== void 0) row[token] = etag;
1089
+ }
1090
+ return rows;
1091
+ }
1092
+ /**
1093
+ * The paths an exclusion projection is taken from: every stored field (`storedDescriptors`:
1094
+ * navigation properties are none) that holds no other field, a collection counting as one
1095
+ * field.
1096
+ */
1097
+ get leaves() {
1098
+ if (!this._leaves) {
1099
+ const stored = this._table.storedDescriptors;
1100
+ const collections = stored.filter((fd) => fd.designType === "array").map((fd) => fd.path);
1101
+ const paths = stored.map((fd) => fd.path).filter((path) => !under(path, collections));
1102
+ this._leaves = paths.filter((path) => collections.includes(path) || !paths.some((other) => other.startsWith(`${path}.`)));
1103
+ }
1104
+ return this._leaves;
1105
+ }
1106
+ /**
1107
+ * The read of a query, with the `$with` entries as expansions: each translated by the adapter
1108
+ * of its table (one of the same service, see {@link sharesStoreWith}), nested entries included.
1109
+ * Related rows keep their key at every depth, whatever their selection.
1110
+ */
1111
+ shapeOf(query) {
1112
+ return withRelations(readShapeOf(query, this.context), (query.controls.$with ?? []).map(({ nav, isArray, target, query: related }) => {
1113
+ const adapter = target.adapter;
1114
+ return {
1115
+ nav,
1116
+ isArray,
1117
+ shape: keepingKey(adapter.shapeOf(related), adapter.entitySet.key)
1118
+ };
1119
+ }));
1120
+ }
1121
+ /** What the table layer hands {@link aggregate}, as the engine's grouped read. */
1122
+ aggregateSpecOf(query) {
1123
+ const { controls } = query;
1124
+ const spec = {
1125
+ entitySet: this.entitySet.name,
1126
+ groupBy: [...controls.$groupBy ?? []],
1127
+ aggregates: (controls.$select?.aggregates ?? []).map((expr) => ({
1128
+ fn: expr.$fn,
1129
+ field: String(expr.$field),
1130
+ alias: resolveAlias(expr)
1131
+ }))
1132
+ };
1133
+ if (query.filter && Object.keys(query.filter).length > 0) spec.filter = query.filter;
1134
+ const having = controls.$having;
1135
+ if (having && Object.keys(having).length > 0) spec.having = having;
1136
+ const sort = Object.entries(controls.$sort ?? {});
1137
+ if (sort.length > 0) spec.orderBy = sort.map(([path, direction]) => direction === -1 ? {
1138
+ path,
1139
+ desc: true
1140
+ } : { path });
1141
+ if (typeof controls.$search === "string" && controls.$search !== "") spec.search = controls.$search;
1142
+ if (controls.$count) {
1143
+ spec.count = true;
1144
+ spec.top = 0;
1145
+ return spec;
1146
+ }
1147
+ if (typeof controls.$skip === "number" && controls.$skip > 0) spec.skip = controls.$skip;
1148
+ if (typeof controls.$limit === "number") spec.top = controls.$limit;
1149
+ return spec;
1150
+ }
1151
+ countSpecOf(query) {
1152
+ const spec = { entitySet: this.entitySet.name };
1153
+ if (query.filter && Object.keys(query.filter).length > 0) spec.filter = query.filter;
1154
+ return spec;
1155
+ }
1156
+ searchShapeOf(text, query, indexName) {
1157
+ if (indexName !== void 0 && indexName !== "DEFAULT") throw new DbError("INVALID_QUERY", [{
1158
+ path: "$index",
1159
+ message: searchIndexNotFoundMessage(indexName)
1160
+ }]);
1161
+ const shape = this.shapeOf(query);
1162
+ shape.spec.search = text;
1163
+ return shape;
1164
+ }
1165
+ async readWithCount(shape, init) {
1166
+ const result = await this.service.read({
1167
+ ...shape.spec,
1168
+ count: true
1169
+ }, init);
1170
+ return {
1171
+ data: this.rowsOf(result, shape),
1172
+ count: result.count ?? 0
1173
+ };
1174
+ }
1175
+ };
1176
+ //#endregion
1177
+ //#region src/sessions.ts
1178
+ /** How long an unused session is kept unless `ttl` says otherwise: 30 minutes. */
1179
+ const DEFAULT_SESSION_TTL = 30 * 6e4;
1180
+ /** How many sessions a space keeps unless `max` says otherwise. */
1181
+ const DEFAULT_MAX_SESSIONS = 1e3;
1182
+ /** Headers that are no credentials: they do not tell sessions apart. */
1183
+ const NOT_CREDENTIALS = new Set(["accept-language"]);
1184
+ function positive(value, fallback, name) {
1185
+ if (value === void 0) return fallback;
1186
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`createODataSpace: "sessions.${name}" must be a positive number`);
1187
+ return value;
1188
+ }
1189
+ /**
1190
+ * Gives each call the session of the credentials it sends: the cookies the service set for them
1191
+ * and the CSRF token bound to those cookies. The key is the SHA-256 of the call's headers (names
1192
+ * in lower case, sorted, values exact), `Accept-Language` left out; with no header, the one
1193
+ * session of the space's static credentials, or none when it has none either: such calls stay
1194
+ * stateless. A call that brings a session of its own keeps it. Bounded and expiring; a dropped
1195
+ * session is no error, the next call starts a new one.
1196
+ */
1197
+ function sessionKeeper(options, staticCredentials) {
1198
+ const ttl = positive(options.ttl, DEFAULT_SESSION_TTL, "ttl");
1199
+ const max = Math.floor(positive(options.max, 1e3, "max")) || 1;
1200
+ const entries = /* @__PURE__ */ new Map();
1201
+ const get = (key) => {
1202
+ const now = Date.now();
1203
+ for (const [known, entry] of entries) {
1204
+ if (now - entry.usedAt < ttl) break;
1205
+ entries.delete(known);
1206
+ }
1207
+ const entry = entries.get(key) ?? {
1208
+ session: createSession(),
1209
+ usedAt: now
1210
+ };
1211
+ entry.usedAt = now;
1212
+ entries.delete(key);
1213
+ entries.set(key, entry);
1214
+ while (entries.size > max) entries.delete(entries.keys().next().value);
1215
+ return entry.session;
1216
+ };
1217
+ return (init) => {
1218
+ if (init.session) return init;
1219
+ const credentials = Object.entries(init.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => !NOT_CREDENTIALS.has(name)).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1220
+ if (credentials.length === 0 && !staticCredentials) return init;
1221
+ const key = createHash("sha256").update(JSON.stringify(credentials)).digest("hex");
1222
+ return {
1223
+ ...init,
1224
+ session: get(key)
1225
+ };
1226
+ };
1227
+ }
1228
+ //#endregion
1229
+ //#region src/space.ts
1230
+ const notConnected = () => /* @__PURE__ */ new Error("The OData space is not connected: call `await space.connect()` before `app.init()`");
1231
+ /**
1232
+ * A `DbSpace` over an OData service: its entity sets are its tables. A live space reads the
1233
+ * service's `$metadata` with {@link connect}, before the application's controllers are created.
1234
+ */
1235
+ var ODataSpace = class extends DbSpace {
1236
+ /** The live source; absent on a space over an engine at hand. */
1237
+ source;
1238
+ _connection;
1239
+ defaultInit;
1240
+ callInit;
1241
+ constructor(adapterFactory, options, from = {}) {
1242
+ super(adapterFactory, options);
1243
+ if (from.source) this.source = from.source;
1244
+ if (from.fixed) this._connection = {
1245
+ name: "",
1246
+ service: from.fixed,
1247
+ types: {},
1248
+ fast: true
1249
+ };
1250
+ this.defaultInit = from.connect;
1251
+ this.callInit = from.call;
1252
+ }
1253
+ /** The connection, once {@link connect} succeeded (from the start on a fixed space). */
1254
+ get connection() {
1255
+ return this._connection;
1256
+ }
1257
+ /** The engine of the connection. @throws Error before the space is connected. */
1258
+ get service() {
1259
+ if (!this._connection) throw notConnected();
1260
+ return this._connection.service;
1261
+ }
1262
+ /**
1263
+ * Reads the live `$metadata` and value-help documents, in the language the models were saved
1264
+ * in, and makes the generated types live (`createODataSource` of `@atscript/odata`): call it
1265
+ * once before `app.init()`, which creates the controllers and binds them to the tables. The
1266
+ * read is made with `init`, else with the space's own `init` (the credentials the server is
1267
+ * given). Resolves with the same connection ever after. What the live metadata changed against
1268
+ * the saved one is logged once as a warning: entity sets gone or allowing fewer writes,
1269
+ * properties added, removed or changed.
1270
+ *
1271
+ * @throws what reading `$metadata` throws: the `ODataError` of a refused or failed read, the
1272
+ * parser's `Error` for an answer that is no `$metadata` document.
1273
+ */
1274
+ async connect(init) {
1275
+ if (this._connection) return this._connection;
1276
+ const call = await (init ?? this.defaultInit)?.();
1277
+ this._connection = await this.source.connect(call && sendInit(call));
1278
+ return this._connection;
1279
+ }
1280
+ /**
1281
+ * Why an operation of the build is refused: its verdict when the live service no longer has it
1282
+ * (`gone`) or changed it so that the build's calls no longer fit (`incompatible`); `undefined`
1283
+ * when it fits. A live space holds the live service to the build: the verdicts are computed
1284
+ * once, on `connect()`, when the live `$metadata` differs from the saved one.
1285
+ */
1286
+ refusalOf(operation) {
1287
+ return refusalIn(this._connection, operation);
1288
+ }
1289
+ /**
1290
+ * Calls an operation of the service (`runOperation` of `@atscript/odata`), with the space's
1291
+ * credentials, the session it keeps for them and its language, as the tables' calls are made: an
1292
+ * unbound one, or a bound one with `entitySet` (a set's table calls its own with
1293
+ * `ODataAdapter.callOperation`). An operation the live service no longer fits is refused first
1294
+ * (see {@link refusalOf}); the parameters are validated against the live operation type (the
1295
+ * validator's `ValidatorError`). What the call throws, and the error of each row in `failed`, is
1296
+ * mapped as the adapter's `callOperation` maps it: a call that sends the caller's version token
1297
+ * (a call that writes, on a row with its `__etag`) refused with `412` is that row's version
1298
+ * mismatch, for the caller to answer (one row resolves `null`, a row of several is
1299
+ * `{ index, error: null }` in `failed`), a row the service has no entity for a `DbError`
1300
+ * `NOT_FOUND`, the rest as the tables' calls (`toDbError`).
1301
+ *
1302
+ * @throws Error before the space is connected.
1303
+ */
1304
+ async callOperation(input) {
1305
+ const connection = this._connection;
1306
+ if (!connection) throw notConnected();
1307
+ const init = sendInit(await this.callInit?.() ?? {});
1308
+ const { operation } = input;
1309
+ const entitySet = input.entitySet ?? (typeof operation === "string" ? void 0 : operation.entitySet) ?? "";
1310
+ return operationAnswer(runOperation(connection, input, init), input.rows, {
1311
+ token: sendsRowToken(connection, input) ? VERSION_TOKEN : void 0,
1312
+ entitySet,
1313
+ model: connection.service.model,
1314
+ parameters: runParameters(connection, input)
1315
+ });
1316
+ }
1317
+ };
1318
+ /**
1319
+ * Creates a `DbSpace` over an OData service: `space.getTable(Type)` returns a table that reads the
1320
+ * entity set `Type` was generated from (or built from at runtime). A type of one of the service's
1321
+ * value-help services (`@odata.valueHelpService`) is read at that service's root, through
1322
+ * `service.valueHelpService(…)`, with the space's `init`.
1323
+ *
1324
+ * The generated types name the service as their `@db.space`: registered under that name with
1325
+ * moost-db's `provideDbSpace(space, "sales")`, the space serves model-token controllers
1326
+ * (`@TableController(sales.Order, …)`). Never run schema sync over it: the service owns its
1327
+ * schema.
1328
+ *
1329
+ * Live (`baseUrl`, `model`, `types`, …): the tables can be created at import (the controllers'
1330
+ * decorators); `connect()` reads the live `$metadata` before `app.init()`. The space holds the
1331
+ * live service to the build: an operation of the build the live service no longer fits is
1332
+ * refused (`refusalOf`, `callOperation`) and listed in the drift report. An entity set the live
1333
+ * service no longer has keeps its table, and every call of it throws a plain `Error` (the
1334
+ * server's build no longer fits the service: moost-db answers `500`); the OData controller bases
1335
+ * of `@atscript/moost-odata` answer every endpoint of such a table `404` instead.
1336
+ *
1337
+ * Every call of a table is made with the space's `init` (credentials, a time limit), with the
1338
+ * session the space keeps for the credentials it sends, and, when the models name the language
1339
+ * they were saved in, with that language as `Accept-Language` (unless `init` names one), so
1340
+ * labels and data texts come in one language.
1341
+ */
1342
+ function createODataSpace(options) {
1343
+ const { logger, onClose, sessions, init: own } = options;
1344
+ const space = {
1345
+ logger,
1346
+ onClose
1347
+ };
1348
+ if ("service" in options && options.service) {
1349
+ const keep = sessions === false ? void 0 : sessionKeeper(sessions ?? {}, false);
1350
+ const init = keep ? async () => keep(await own?.() ?? {}) : own;
1351
+ const fixed = options.service;
1352
+ let instance;
1353
+ const factory = () => new ODataAdapter(fixed, {
1354
+ ...init ? { init } : {},
1355
+ connection: () => instance?.connection
1356
+ });
1357
+ instance = new ODataSpace(factory, space, {
1358
+ fixed,
1359
+ connect: own,
1360
+ call: init
1361
+ });
1362
+ return instance;
1363
+ }
1364
+ const { logger: _logger, onClose: _onClose, sessions: _sessions, init: _init, onDrift, batch, ...sourceOptions } = options;
1365
+ const warn = (message) => logger ? logger.warn(message) : console.warn(message);
1366
+ const source = createODataSource({
1367
+ ...sourceOptions,
1368
+ batch: batch === false ? false : {
1369
+ ...batch,
1370
+ auto: false
1371
+ },
1372
+ onDrift: onDrift ?? ((_drift, message) => warn(message)),
1373
+ verdicts: true
1374
+ });
1375
+ const { language } = source;
1376
+ const keep = sessions === false ? void 0 : sessionKeeper(sessions ?? {}, !!sourceOptions.headers);
1377
+ const init = async () => {
1378
+ const call = withLocale(await own?.() ?? {}, language);
1379
+ return keep ? keep(call) : call;
1380
+ };
1381
+ let instance;
1382
+ const factory = () => new ODataAdapter(() => instance?.connection?.service, {
1383
+ init,
1384
+ ...sourceOptions.model ? { saved: sourceOptions.model } : {},
1385
+ connection: () => instance?.connection
1386
+ });
1387
+ instance = new ODataSpace(factory, space, {
1388
+ source,
1389
+ connect: own,
1390
+ call: init
1391
+ });
1392
+ return instance;
1393
+ }
1394
+ //#endregion
1395
+ export { DEFAULT_MAX_SESSIONS, DEFAULT_SESSION_TTL, ODATA_SEARCH_INDEX, ODataAdapter, ODataNotSupportedError, ODataSpace, createODataSpace, isODataNotSupportedError, toDbError };