@atscript/moost-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/LICENSE +21 -0
- package/README.md +562 -2
- package/dist/index.cjs +700 -0
- package/dist/index.d.cts +401 -0
- package/dist/index.d.mts +402 -0
- package/dist/index.mjs +681 -0
- package/package.json +71 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _wooksjs_event_core = require("@wooksjs/event-core");
|
|
3
|
+
let _wooksjs_event_http = require("@wooksjs/event-http");
|
|
4
|
+
let _atscript_db_odata = require("@atscript/db-odata");
|
|
5
|
+
let _atscript_moost_db = require("@atscript/moost-db");
|
|
6
|
+
let _atscript_db = require("@atscript/db");
|
|
7
|
+
let _atscript_odata = require("@atscript/odata");
|
|
8
|
+
let _moostjs_event_http = require("@moostjs/event-http");
|
|
9
|
+
let moost = require("moost");
|
|
10
|
+
let _atscript_typescript_utils = require("@atscript/typescript/utils");
|
|
11
|
+
//#region src/request.ts
|
|
12
|
+
const NO_HEADERS = Object.freeze({});
|
|
13
|
+
/**
|
|
14
|
+
* The HTTP request of the current event, read with Wooks' `useHeaders` and `useCookies`. Resolved
|
|
15
|
+
* through the event context Wooks keeps in `AsyncLocalStorage`, so every overlapping request sees
|
|
16
|
+
* its own, wherever in its call chain this is asked.
|
|
17
|
+
*/
|
|
18
|
+
function currentIncomingRequest() {
|
|
19
|
+
const current = (0, _wooksjs_event_core.tryGetCurrent)();
|
|
20
|
+
const event = current?.has(_wooksjs_event_http.httpKind.keys.req) ? current : void 0;
|
|
21
|
+
const headers = event ? (0, _wooksjs_event_http.useHeaders)(event) : NO_HEADERS;
|
|
22
|
+
const header = (name) => {
|
|
23
|
+
const value = headers[name.toLowerCase()];
|
|
24
|
+
return Array.isArray(value) ? value.join(", ") : value;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
headers,
|
|
28
|
+
event,
|
|
29
|
+
header,
|
|
30
|
+
cookie: (name) => event ? (0, _wooksjs_event_http.useCookies)(event).getCookie(name) ?? void 0 : void 0
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/auth.ts
|
|
35
|
+
/**
|
|
36
|
+
* Headers sent with every call: `staticHeaders({ "x-api-key": key })`, a credential the server was
|
|
37
|
+
* given in a header of its own.
|
|
38
|
+
*/
|
|
39
|
+
function staticHeaders(headers) {
|
|
40
|
+
const fixed = { ...headers };
|
|
41
|
+
return () => ({ headers: { ...fixed } });
|
|
42
|
+
}
|
|
43
|
+
/** HTTP Basic authentication of a technical user. */
|
|
44
|
+
function basicAuth(options) {
|
|
45
|
+
const { user, password } = options;
|
|
46
|
+
if (user === "" || user.includes(":")) throw new Error("basicAuth: the user name must not be empty and cannot contain \":\"");
|
|
47
|
+
const value = `Basic ${Buffer.from(`${user}:${password}`, "utf8").toString("base64")}`;
|
|
48
|
+
return () => ({ headers: { Authorization: value } });
|
|
49
|
+
}
|
|
50
|
+
function bearerHeader(token) {
|
|
51
|
+
if (typeof token !== "string" || token === "") throw new Error("bearerAuth: there is no token to authenticate with");
|
|
52
|
+
return { headers: { Authorization: `Bearer ${token}` } };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Bearer authentication of a technical user: a token, or a function asked for one at every table
|
|
56
|
+
* operation, which caches and refreshes a token that expires (an OAuth client-credentials token,
|
|
57
|
+
* for example). The function runs in the request it is asked for and receives it.
|
|
58
|
+
*/
|
|
59
|
+
function bearerAuth(token) {
|
|
60
|
+
if (typeof token === "string") {
|
|
61
|
+
bearerHeader(token);
|
|
62
|
+
return () => bearerHeader(token);
|
|
63
|
+
}
|
|
64
|
+
return () => {
|
|
65
|
+
const value = token(currentIncomingRequest());
|
|
66
|
+
return typeof value === "string" ? bearerHeader(value) : value.then(bearerHeader);
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Limits every table operation to `ms` milliseconds, all its OData requests together. A call
|
|
71
|
+
* that takes longer fails as a timeout, which the error mapping answers with `504`.
|
|
72
|
+
*/
|
|
73
|
+
function callTimeout(ms) {
|
|
74
|
+
if (!Number.isFinite(ms) || ms <= 0) throw new Error("callTimeout: the limit must be a positive number of milliseconds");
|
|
75
|
+
return () => ({ signal: AbortSignal.timeout(ms) });
|
|
76
|
+
}
|
|
77
|
+
function mergeInits(parts) {
|
|
78
|
+
const merged = {};
|
|
79
|
+
const headers = /* @__PURE__ */ new Map();
|
|
80
|
+
const signals = [];
|
|
81
|
+
let read;
|
|
82
|
+
for (const part of parts) {
|
|
83
|
+
if (!part) continue;
|
|
84
|
+
for (const [key, value] of Object.entries(part)) if (value !== void 0) merged[key] = value;
|
|
85
|
+
for (const [name, value] of Object.entries(part.headers ?? {})) headers.set(name.toLowerCase(), [name, value]);
|
|
86
|
+
if (part.signal) signals.push(part.signal);
|
|
87
|
+
if (part.read) read = Object.assign(read ?? {}, part.read);
|
|
88
|
+
}
|
|
89
|
+
if (Object.keys(merged).length === 0) return void 0;
|
|
90
|
+
if (headers.size > 0) merged.headers = Object.fromEntries(headers.values());
|
|
91
|
+
if (read) merged.read = read;
|
|
92
|
+
if (signals.length > 1) merged.signal = AbortSignal.any(signals);
|
|
93
|
+
return merged;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* One strategy out of several: each is asked for the current request and the answers are merged
|
|
97
|
+
* in the order given. A later header replaces an earlier one of the same name (in any case), a
|
|
98
|
+
* later session replaces an earlier one, read options are merged, and the call is aborted when
|
|
99
|
+
* any of the signals fires.
|
|
100
|
+
*
|
|
101
|
+
* ```ts
|
|
102
|
+
* combineAuth(basicAuth({ user, password }), callTimeout(15_000))
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
function combineAuth(...strategies) {
|
|
106
|
+
return async () => mergeInits(await Promise.all(strategies.map(async (init) => init())));
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/controller-checks.ts
|
|
110
|
+
/** The adapter of a readable when it is one of `@atscript/db-odata`. */
|
|
111
|
+
function odataAdapterOf(readable) {
|
|
112
|
+
const adapter = readable?.getAdapter();
|
|
113
|
+
return adapter instanceof _atscript_db_odata.ODataAdapter ? adapter : void 0;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* `crud` without the writes the entity set does not allow: `insert`, `update` and `replace`,
|
|
117
|
+
* `remove`, by `allowedWrites` of the adapter (`crud` as it is for a table of another adapter).
|
|
118
|
+
* What `ODataTableController` does in `buildCrud`; a moost-db controller of another base over an
|
|
119
|
+
* OData table (an ARBAC controller of aooth) does the same:
|
|
120
|
+
*
|
|
121
|
+
* ```ts
|
|
122
|
+
* protected override buildCrud() {
|
|
123
|
+
* return allowedCrud(super.buildCrud(), this.readable);
|
|
124
|
+
* }
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
function allowedCrud(crud, readable) {
|
|
128
|
+
const adapter = odataAdapterOf(readable);
|
|
129
|
+
if (!adapter) return crud;
|
|
130
|
+
const allowed = adapter.allowedWrites;
|
|
131
|
+
const pruned = { ...crud };
|
|
132
|
+
if (!allowed.insert) delete pruned.insert;
|
|
133
|
+
if (!allowed.update) {
|
|
134
|
+
delete pruned.update;
|
|
135
|
+
delete pruned.replace;
|
|
136
|
+
}
|
|
137
|
+
if (!allowed.delete) delete pruned.remove;
|
|
138
|
+
return pruned;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Refuses every endpoint of a table whose entity set the live service no longer has, `/meta`
|
|
142
|
+
* included: moost-db's `404` `NOT_FOUND` (`notFoundError()`), the answer of a missing row. The
|
|
143
|
+
* adapter itself would answer such a table with a plain `Error` (`500`), a fault of the server's
|
|
144
|
+
* build. Nothing for any other table. What the OData bases do in `prepareRequest`, which moost-db
|
|
145
|
+
* runs first on every endpoint; a moost-db controller of another base does the same:
|
|
146
|
+
*
|
|
147
|
+
* ```ts
|
|
148
|
+
* protected override async prepareRequest(ctx: TDbRequestContext) {
|
|
149
|
+
* refuseGoneEntitySet(this.readable);
|
|
150
|
+
* await super.prepareRequest?.(ctx); // the base's own, when it has one (aooth's ARBAC check)
|
|
151
|
+
* }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
function refuseGoneEntitySet(readable) {
|
|
155
|
+
if (odataAdapterOf(readable)?.gone) throw (0, _atscript_moost_db.notFoundError)();
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region \0@oxc-project+runtime@0.121.0/helpers/decorate.js
|
|
159
|
+
function __decorate(decorators, target, key, desc) {
|
|
160
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
161
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
162
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
163
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
//#region src/operations.ts
|
|
167
|
+
const mate = () => (0, moost.getMoostMate)();
|
|
168
|
+
/**
|
|
169
|
+
* Marks a controller method as the route of an OData operation: `operation` is its typed handle
|
|
170
|
+
* of the model module's `ops` (`ops.OrderSet.ReleaseOrder`). The generated bases put it on every
|
|
171
|
+
* method they generate, beside moost-db's own decorators (`@DbAction`, `@InputForm`,
|
|
172
|
+
* `@DbActionRows`); `runOperation()` of the method's controller calls the operation it names, and
|
|
173
|
+
* the OData bases refuse an operation the live service no longer fits before anything else runs.
|
|
174
|
+
*
|
|
175
|
+
* A method of your own calls an operation the same way: a db action of your table controller over
|
|
176
|
+
* an unbound operation (a toolbar or row button) takes `@DbAction`, its route, this marker with
|
|
177
|
+
* the operation's handle, and `this.runOperation({ params })`.
|
|
178
|
+
*/
|
|
179
|
+
function ODataOperation(operation, options = {}) {
|
|
180
|
+
const mark = {
|
|
181
|
+
operation,
|
|
182
|
+
...options.grouping ? options : {}
|
|
183
|
+
};
|
|
184
|
+
return mate().decorate("odata_operation", mark);
|
|
185
|
+
}
|
|
186
|
+
/** The mark of the method handling the current event. */
|
|
187
|
+
function currentMark() {
|
|
188
|
+
const context = (0, moost.useControllerContext)();
|
|
189
|
+
const mark = context.getMethodMeta()?.odata_operation;
|
|
190
|
+
if (!mark) throw new Error(`runOperation() was called from ${context.getMethod() ?? "a method"}, which has no @ODataOperation(handle): mark the method with the operation's handle`);
|
|
191
|
+
return mark;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Refuses an operation of the build the live service no longer fits: one it no longer has with
|
|
195
|
+
* moost-db's `404` (`notFoundError()`), one it changed with the core's plain `Error` (a fault of
|
|
196
|
+
* the server's build: moost-db answers `500` and logs it).
|
|
197
|
+
*/
|
|
198
|
+
function refuse(verdict) {
|
|
199
|
+
if (!verdict) return;
|
|
200
|
+
if (verdict.verdict === "gone") throw (0, _atscript_moost_db.notFoundError)();
|
|
201
|
+
throw (0, _atscript_odata.incompatibleOperationError)(verdict);
|
|
202
|
+
}
|
|
203
|
+
/** The operations among a controller's db actions, by action name: what its `@ODataOperation` names. */
|
|
204
|
+
const byController = /* @__PURE__ */ new WeakMap();
|
|
205
|
+
function operationsOf(ctor, app) {
|
|
206
|
+
let found = byController.get(ctor);
|
|
207
|
+
if (found) return found;
|
|
208
|
+
found = /* @__PURE__ */ new Map();
|
|
209
|
+
const overview = app.getControllersOverview().find((o) => o.type === ctor);
|
|
210
|
+
for (const handler of overview?.handlers ?? []) {
|
|
211
|
+
const meta = handler.meta;
|
|
212
|
+
const name = meta.atscript_db_action?.name;
|
|
213
|
+
if (name !== void 0 && meta.odata_operation) found.set(name, meta.odata_operation);
|
|
214
|
+
}
|
|
215
|
+
byController.set(ctor, found);
|
|
216
|
+
return found;
|
|
217
|
+
}
|
|
218
|
+
/** The verdict refusing the action `name` of a controller, when it is one of its operations. */
|
|
219
|
+
function refusalOfAction(host, name) {
|
|
220
|
+
const mark = operationsOf(host.ctor, host.app).get(name);
|
|
221
|
+
return mark && odataAdapterOf(host.readable)?.refusalOf(mark.operation);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* `prepareRequest` of the bases: an action (`action`, and a view's `delegatedAction`) naming one
|
|
225
|
+
* of the controller's operations the live service no longer fits is refused, after the guards
|
|
226
|
+
* and before the ids are read, the rows loaded or the handler runs.
|
|
227
|
+
*/
|
|
228
|
+
function refuseRefusedOperation(host, ctx) {
|
|
229
|
+
if (ctx.endpoint !== "action" && ctx.endpoint !== "delegatedAction" || !ctx.action) return;
|
|
230
|
+
refuse(refusalOfAction(host, ctx.action));
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* `buildActions` of the bases: the actions without the operations the live service refuses. Every
|
|
234
|
+
* list of actions follows it: `/meta`, `$actions`, `/meta/actions` and a view's delegated entries.
|
|
235
|
+
*/
|
|
236
|
+
function withoutRefusedActions(host, actions) {
|
|
237
|
+
return actions.filter((action) => !refusalOfAction(host, action.name));
|
|
238
|
+
}
|
|
239
|
+
/** The key of a row: what moost-db's action target names it by, and what it is read again by. */
|
|
240
|
+
function keyOf(readable, row) {
|
|
241
|
+
return Object.fromEntries(readable.primaryKeys.map((key) => [key, row[key]]));
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* A row the service has no entity for (the adapter's `DbError` `NOT_FOUND`: the ETag read before
|
|
245
|
+
* its call found none, or the call was answered `404`): moost-db's answer to a missing row,
|
|
246
|
+
* `notFoundError()`. Any other error as it is.
|
|
247
|
+
*/
|
|
248
|
+
function missingRow(error) {
|
|
249
|
+
return error instanceof _atscript_db.DbError && error.code === "NOT_FOUND" ? (0, _atscript_moost_db.notFoundError)() : error;
|
|
250
|
+
}
|
|
251
|
+
/** The answer moost-db gives an error of a row's call; `undefined` for one it does not map. */
|
|
252
|
+
function bodyOf(error) {
|
|
253
|
+
if (error instanceof _atscript_db.DbError) return (0, _atscript_moost_db.dbErrorToHttp)(error).body;
|
|
254
|
+
if (error instanceof _moostjs_event_http.HttpError) return error.body;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The error of a run on several rows where every row failed: the first row's answer (its status,
|
|
258
|
+
* code and message, as that call alone would have been answered), with the entries of every row
|
|
259
|
+
* at that row (`[i]`, `[i].Note`; `rowsFailure` of `@atscript/odata`).
|
|
260
|
+
*/
|
|
261
|
+
function everyRowFailed(errors) {
|
|
262
|
+
const bodies = errors.map(bodyOf);
|
|
263
|
+
if (!bodies.every((body) => body !== void 0)) return errors[0];
|
|
264
|
+
const { entries } = (0, _atscript_odata.rowsFailure)(errors.length, bodies.map(({ message, code, params, errors }, index) => ({
|
|
265
|
+
index,
|
|
266
|
+
message,
|
|
267
|
+
entries: errors ?? [],
|
|
268
|
+
code,
|
|
269
|
+
params
|
|
270
|
+
})));
|
|
271
|
+
const [first] = errors;
|
|
272
|
+
if (first instanceof _atscript_db.DbError) return new _atscript_db.DbError(first.code, entries, first.message, { cause: first.cause });
|
|
273
|
+
const body = bodies[0];
|
|
274
|
+
return new _moostjs_event_http.HttpError(body.statusCode, {
|
|
275
|
+
...body,
|
|
276
|
+
errors: entries
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The answer of an operation on rows: moost-db's action target summary (the gate's skipped
|
|
281
|
+
* rows, the rows the run failed on reported with `fail(id, error)`, its counts), each failed row
|
|
282
|
+
* with the status, code and message its call alone would have been answered with, and the
|
|
283
|
+
* operation's values and messages. Every row of the request's ids failed: the error of
|
|
284
|
+
* {@link everyRowFailed}. Where the gate skipped rows, or on a query target, the rows handed to
|
|
285
|
+
* the run are not the request's ids, and a run whose every row failed answers the summary, as
|
|
286
|
+
* moost-db's own targets do (`processed: 0`, `failed` by id, `skipped` kept). (One row never gets
|
|
287
|
+
* here: the runner sends it as a plain call, whose failure is its own error.)
|
|
288
|
+
*/
|
|
289
|
+
async function rowsAnswer(readable, rows, answer, stale) {
|
|
290
|
+
const failed = await Promise.all((answer.failed ?? []).map(async ({ index, error }) => ({
|
|
291
|
+
index,
|
|
292
|
+
error: error === null ? await stale(keyOf(readable, rows[index])) : missingRow(error)
|
|
293
|
+
})));
|
|
294
|
+
const target = (0, _atscript_moost_db.useDbActionTarget)();
|
|
295
|
+
if (failed.length > 0 && failed.length === rows.length && target.kind === "ids" && target.summary().skipped.length === 0) throw everyRowFailed(failed.map((f) => f.error));
|
|
296
|
+
for (const { index, error } of failed) target.fail(keyOf(readable, rows[index]), error);
|
|
297
|
+
const summary = target.summary();
|
|
298
|
+
const { failed: _failed, ...ran } = answer;
|
|
299
|
+
return {
|
|
300
|
+
...summary,
|
|
301
|
+
failed: summary.failed,
|
|
302
|
+
...ran
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
/** Whether an id names the row of `key`: the same value for each key property. */
|
|
306
|
+
function sameRow(readable, id, key) {
|
|
307
|
+
if (id === null || typeof id !== "object") return false;
|
|
308
|
+
const values = id;
|
|
309
|
+
return readable.primaryKeys.every((name) => String(values[name]) === String(key[name]));
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* The error of a refused changeset of several rows, its entries that name a row (`[k]`, with the
|
|
313
|
+
* row's key as `params.id`) at that row's index in the request's ids (`[j]`), the rows handed to
|
|
314
|
+
* the run being those the gate left; on a query target, which lists no ids, at `""` with
|
|
315
|
+
* `params.id`. Any other error as it is.
|
|
316
|
+
*/
|
|
317
|
+
async function atRequestRows(readable, error) {
|
|
318
|
+
if (!(error instanceof _atscript_db.DbError) || !error.errors.some((entry) => entry.params?.id)) return error;
|
|
319
|
+
const { ids } = await (0, _wooksjs_event_core.current)().get(_atscript_moost_db.dbActionBodySlot);
|
|
320
|
+
const requested = (0, _atscript_moost_db.useDbActionTarget)().kind === "ids" && Array.isArray(ids) ? ids : [];
|
|
321
|
+
const entries = error.errors.map((entry) => {
|
|
322
|
+
const id = entry.params?.id;
|
|
323
|
+
const at = id ? /^\[\d+\]\.?/.exec(entry.path) : null;
|
|
324
|
+
if (!id || !at) return entry;
|
|
325
|
+
const index = requested.findIndex((requestedId) => sameRow(readable, requestedId, id));
|
|
326
|
+
const rest = entry.path.slice(at[0].length);
|
|
327
|
+
return {
|
|
328
|
+
...entry,
|
|
329
|
+
path: index < 0 ? "" : rest ? `[${index}].${rest}` : `[${index}]`
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
return new _atscript_db.DbError(error.code, entries, error.message, { cause: error.cause });
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* `runOperation()` of the set bases: the marked operation, bound to the controller's entity set,
|
|
336
|
+
* by the grouping of its mark. On rows it answers {@link ODataRowsAnswer}.
|
|
337
|
+
*/
|
|
338
|
+
async function runSetOperation(readable, input, stale) {
|
|
339
|
+
const { operation, grouping } = currentMark();
|
|
340
|
+
const adapter = odataAdapterOf(readable);
|
|
341
|
+
if (!adapter) throw new Error(`runOperation(): the table "${readable.tableName}" is no table of an OData space`);
|
|
342
|
+
refuse(adapter.refusalOf(operation));
|
|
343
|
+
const rows = input.rows ?? input.ids;
|
|
344
|
+
if (rows?.some((row) => row === null || row === void 0)) throw (0, _atscript_moost_db.notFoundError)();
|
|
345
|
+
let answer;
|
|
346
|
+
try {
|
|
347
|
+
answer = await adapter.callOperation({
|
|
348
|
+
operation,
|
|
349
|
+
...rows ? { rows } : {},
|
|
350
|
+
...input.params ? { params: input.params } : {},
|
|
351
|
+
...input.extra ? { extra: input.extra } : {},
|
|
352
|
+
...grouping ? { grouping } : {}
|
|
353
|
+
});
|
|
354
|
+
} catch (error) {
|
|
355
|
+
throw rows ? missingRow(await atRequestRows(readable, error)) : missingRow(error);
|
|
356
|
+
}
|
|
357
|
+
if (answer === null) throw await stale(keyOf(readable, rows[0]));
|
|
358
|
+
return rows ? rowsAnswer(readable, rows, answer, stale) : answer;
|
|
359
|
+
}
|
|
360
|
+
let ODataOperationsController = class ODataOperationsController {
|
|
361
|
+
/**
|
|
362
|
+
* Calls the operation the current method is marked with (`@ODataOperation`), with `params` (the
|
|
363
|
+
* body; none for a request without one) and, on OData v2, `extra`: parameters the operation does not declare, sent untyped (set
|
|
364
|
+
* them in an override, never from a request). Answers `{ value, message?, messages?, details? }`.
|
|
365
|
+
*/
|
|
366
|
+
async runOperation(input = {}) {
|
|
367
|
+
const { operation } = currentMark();
|
|
368
|
+
const space = (0, _atscript_moost_db.resolveDbSpace)(operation.service);
|
|
369
|
+
if (!(space instanceof _atscript_db_odata.ODataSpace)) throw new Error(`runOperation(): the space registered as "${operation.service}" is no OData space (createODataSpace)`);
|
|
370
|
+
refuse(space.refusalOf(operation));
|
|
371
|
+
const { params } = input;
|
|
372
|
+
return space.callOperation({
|
|
373
|
+
operation,
|
|
374
|
+
params: params === void 0 || params === null || params === "" ? {} : params,
|
|
375
|
+
...input.extra ? { extra: input.extra } : {}
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
ODataOperationsController = __decorate([(0, _atscript_moost_db.UseValidationErrorTransform)()], ODataOperationsController);
|
|
380
|
+
//#endregion
|
|
381
|
+
//#region src/readable-controller.ts
|
|
382
|
+
/**
|
|
383
|
+
* Refuses a `$search` that moost-db's `applySearchFallback` returned unapplied (`applied` is the
|
|
384
|
+
* filter it was given) because neither the table nor a `@db.column.searchable` field can take it:
|
|
385
|
+
* `400` `INVALID_QUERY` on `$search`, where moost-db would answer every row unsearched. What the
|
|
386
|
+
* OData bases do; a moost-db controller of another base does the same:
|
|
387
|
+
*
|
|
388
|
+
* ```ts
|
|
389
|
+
* protected override applySearchFallback(filter: FilterExpr | undefined, controls: Record<string, unknown>) {
|
|
390
|
+
* const applied = super.applySearchFallback(filter, controls);
|
|
391
|
+
* refuseUnappliedSearch(this.readable, filter, controls, applied);
|
|
392
|
+
* return applied;
|
|
393
|
+
* }
|
|
394
|
+
* ```
|
|
395
|
+
*/
|
|
396
|
+
function refuseUnappliedSearch(readable, filter, controls, applied) {
|
|
397
|
+
if (applied === filter && controls.$search && controls.$vector === void 0 && !readable.isSearchable()) throw (0, _atscript_moost_db.badRequest)("$search", `"${readable.tableName}" has no free-text search`, "INVALID_QUERY");
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* The read-only controller of `@atscript/moost-db` (`AsDbReadableController`) for an entity set of
|
|
401
|
+
* an OData service. Declare one per entity set, as with any moost-db controller:
|
|
402
|
+
*
|
|
403
|
+
* ```ts
|
|
404
|
+
* @ReadableController(sales.Customer, "api/sales/CustomerSet")
|
|
405
|
+
* export class CustomerSetController extends ODataReadableController<typeof sales.Customer> {}
|
|
406
|
+
* ```
|
|
407
|
+
*
|
|
408
|
+
* The model token resolves the space the application registered under the types' `@db.space`
|
|
409
|
+
* (`provideDbSpace(space, "sales")`); a table of the space (`space.getTable(sales.Customer)`)
|
|
410
|
+
* binds as well.
|
|
411
|
+
*
|
|
412
|
+
* What it adds to moost-db's controller:
|
|
413
|
+
*
|
|
414
|
+
* - **`$search`** on an entity set the service cannot search is refused with `400`; moost-db would
|
|
415
|
+
* answer with every row unsearched. A type whose fields carry `@db.column.searchable` keeps
|
|
416
|
+
* moost-db's substring search over those fields.
|
|
417
|
+
* - **An entity set the live service no longer has** answers every endpoint, `/meta` included,
|
|
418
|
+
* with moost-db's `404` `NOT_FOUND`, from `prepareRequest`. A subclass that implements
|
|
419
|
+
* `prepareRequest` itself calls `super.prepareRequest(ctx)` first.
|
|
420
|
+
*
|
|
421
|
+
* A failure of the service needs nothing of it: the adapter throws atscript-db's `STORE_FAILED`,
|
|
422
|
+
* `STORE_TIMEOUT` or `STORE_THROTTLED`, which every moost-db controller answers `502`, `504` or
|
|
423
|
+
* `429` (with `Retry-After`) and logs.
|
|
424
|
+
*
|
|
425
|
+
* A class of your own between yours and this one needs Moost's `@Inherit()`, as with any Moost
|
|
426
|
+
* controller base.
|
|
427
|
+
*/
|
|
428
|
+
var ODataReadableController = class extends _atscript_moost_db.AsDbReadableController {
|
|
429
|
+
applySearchFallback(filter, controls) {
|
|
430
|
+
const applied = super.applySearchFallback(filter, controls);
|
|
431
|
+
refuseUnappliedSearch(this.readable, filter, controls, applied);
|
|
432
|
+
return applied;
|
|
433
|
+
}
|
|
434
|
+
get operationHost() {
|
|
435
|
+
return {
|
|
436
|
+
readable: this.readable,
|
|
437
|
+
ctor: this.constructor,
|
|
438
|
+
app: this.app
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Refuses a set the live service no longer has (`404` on every endpoint, `/meta` included) and
|
|
443
|
+
* an operation of the build it no longer fits (an action of the controller: `404` when the
|
|
444
|
+
* service no longer has it, `500` when it changed it). A subclass that implements it calls
|
|
445
|
+
* `super.prepareRequest(ctx)` first.
|
|
446
|
+
*/
|
|
447
|
+
prepareRequest(ctx) {
|
|
448
|
+
refuseGoneEntitySet(this.readable);
|
|
449
|
+
refuseRefusedOperation(this.operationHost, ctx);
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* The db actions, without the operations the live service no longer fits: what `/meta`,
|
|
453
|
+
* `$actions` and `/meta/actions` list.
|
|
454
|
+
*/
|
|
455
|
+
buildActions() {
|
|
456
|
+
return withoutRefusedActions(this.operationHost, super.buildActions());
|
|
457
|
+
}
|
|
458
|
+
runOperation(input = {}) {
|
|
459
|
+
return runSetOperation(this.readable, input, (id) => this._disambiguateMismatch(id, this.readable.versionColumn));
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
(0, moost.Inherit)()(ODataReadableController);
|
|
463
|
+
//#endregion
|
|
464
|
+
//#region src/table-controller.ts
|
|
465
|
+
/**
|
|
466
|
+
* The read and write controller of `@atscript/moost-db` (`AsDbController`: `POST`, `PUT`,
|
|
467
|
+
* `PATCH`, `DELETE` next to the read endpoints) for an entity set the service lets you write to.
|
|
468
|
+
* Declare one per entity set, as with any moost-db controller:
|
|
469
|
+
*
|
|
470
|
+
* ```ts
|
|
471
|
+
* @TableController(sales.Order, "api/sales/OrderSet")
|
|
472
|
+
* export class OrderSetController extends ODataTableController<typeof sales.Order> {}
|
|
473
|
+
* ```
|
|
474
|
+
*
|
|
475
|
+
* The model token resolves the space the application registered under the types' `@db.space`
|
|
476
|
+
* (`provideDbSpace(space, "sales")`); a table of the space (`space.getTable(sales.Order)`) binds
|
|
477
|
+
* as well.
|
|
478
|
+
*
|
|
479
|
+
* Everything `ODataReadableController` adds, and:
|
|
480
|
+
*
|
|
481
|
+
* - **Only the writes the entity set allows** are offered: `/meta` lists in `crud` the writes the
|
|
482
|
+
* live service allows (`allowedWrites` of `@atscript/db-odata`). Another write is refused before
|
|
483
|
+
* any request with moost-db's `400` `NOT_SUPPORTED`, naming why. That holds for a set that takes
|
|
484
|
+
* no write at all, and for one the live service no longer lets you write to: the application
|
|
485
|
+
* starts either way.
|
|
486
|
+
* - **An entity set the live service no longer has** answers every endpoint with `404`
|
|
487
|
+
* `NOT_FOUND`, from `prepareRequest` (a subclass that implements it calls
|
|
488
|
+
* `super.prepareRequest(ctx)` first).
|
|
489
|
+
*
|
|
490
|
+
* Its writes are those of `@atscript/db-odata`: one entity at a time, by key, and last-write-wins,
|
|
491
|
+
* each in the session the space keeps for the credentials it sends.
|
|
492
|
+
*/
|
|
493
|
+
var ODataTableController = class extends _atscript_moost_db.AsDbController {
|
|
494
|
+
buildCrud() {
|
|
495
|
+
return allowedCrud(super.buildCrud(), this.readable);
|
|
496
|
+
}
|
|
497
|
+
applySearchFallback(filter, controls) {
|
|
498
|
+
const applied = super.applySearchFallback(filter, controls);
|
|
499
|
+
refuseUnappliedSearch(this.readable, filter, controls, applied);
|
|
500
|
+
return applied;
|
|
501
|
+
}
|
|
502
|
+
get operationHost() {
|
|
503
|
+
return {
|
|
504
|
+
readable: this.readable,
|
|
505
|
+
ctor: this.constructor,
|
|
506
|
+
app: this.app
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Refuses a set the live service no longer has (`404` on every endpoint, `/meta` included) and
|
|
511
|
+
* an operation of the build it no longer fits (an action of the controller: `404` when the
|
|
512
|
+
* service no longer has it, `500` when it changed it). A subclass that implements it calls
|
|
513
|
+
* `super.prepareRequest(ctx)` first.
|
|
514
|
+
*/
|
|
515
|
+
prepareRequest(ctx) {
|
|
516
|
+
refuseGoneEntitySet(this.readable);
|
|
517
|
+
refuseRefusedOperation(this.operationHost, ctx);
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* The db actions, without the operations the live service no longer fits: what `/meta`,
|
|
521
|
+
* `$actions` and `/meta/actions` list.
|
|
522
|
+
*/
|
|
523
|
+
buildActions() {
|
|
524
|
+
return withoutRefusedActions(this.operationHost, super.buildActions());
|
|
525
|
+
}
|
|
526
|
+
runOperation(input = {}) {
|
|
527
|
+
return runSetOperation(this.readable, input, (id) => this._disambiguateMismatch(id, this.readable.versionColumn));
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
(0, moost.Inherit)()(ODataTableController);
|
|
531
|
+
//#endregion
|
|
532
|
+
//#region src/value-help-controllers.ts
|
|
533
|
+
/** A route segment that is plain text: no parameter (`:`), wildcard (`*`) or escape. */
|
|
534
|
+
const SEGMENT = /^[A-Za-z0-9_.~-]+$/;
|
|
535
|
+
const metaOf = (type) => type.metadata;
|
|
536
|
+
/**
|
|
537
|
+
* The routes made for each space. Moost takes a second handler on one path without a word, and
|
|
538
|
+
* runs it when the first one throws: a request its guard refuses would be answered by the twin.
|
|
539
|
+
*/
|
|
540
|
+
const routesMade = /* @__PURE__ */ new WeakMap();
|
|
541
|
+
/** What tells an entity set apart: its service (`@db.space`), its value-help service, its name. */
|
|
542
|
+
function setKey(type) {
|
|
543
|
+
const metadata = metaOf(type);
|
|
544
|
+
const entitySet = metadata.get("db.table");
|
|
545
|
+
if (typeof entitySet !== "string") return void 0;
|
|
546
|
+
const valueHelpService = metadata.get("odata.valueHelpService");
|
|
547
|
+
return JSON.stringify([
|
|
548
|
+
metadata.get("db.space"),
|
|
549
|
+
typeof valueHelpService === "string" ? valueHelpService : "",
|
|
550
|
+
entitySet
|
|
551
|
+
]);
|
|
552
|
+
}
|
|
553
|
+
/** The type a controller class serves, by moost-db's binding; `undefined` for another class. */
|
|
554
|
+
function servedType(ctor) {
|
|
555
|
+
const binding = (0, _atscript_moost_db.findReadableBinding)(ctor);
|
|
556
|
+
if (!binding) return void 0;
|
|
557
|
+
return binding.model ?? binding.resolve().type;
|
|
558
|
+
}
|
|
559
|
+
/** The `@ui.valueHelp` targets on the properties of a type, nested objects and arrays included. */
|
|
560
|
+
function valueHelpTargets(type, into, seen = /* @__PURE__ */ new Set()) {
|
|
561
|
+
const def = type.type;
|
|
562
|
+
if (seen.has(def)) return;
|
|
563
|
+
seen.add(def);
|
|
564
|
+
if (def.kind === "array") return valueHelpTargets(def.of, into, seen);
|
|
565
|
+
if (def.kind !== "object") return;
|
|
566
|
+
for (const prop of def.props.values()) {
|
|
567
|
+
if ((0, _atscript_db.isNavRelation)(prop)) continue;
|
|
568
|
+
const help = metaOf(prop).get("ui.valueHelp");
|
|
569
|
+
const target = typeof help?.target === "function" ? help.target() : void 0;
|
|
570
|
+
if ((0, _atscript_typescript_utils.isAnnotatedType)(target)) into.add(target);
|
|
571
|
+
valueHelpTargets(prop, into, seen);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/** Refuses a base whose controllers would serve writes, or would get no routes. */
|
|
575
|
+
function checkBase(base) {
|
|
576
|
+
if (base !== ODataReadableController && !(base.prototype instanceof ODataReadableController)) throw new Error(`valueHelpControllers: \`base\` ${base.name} is no ODataReadableController: value-help routes are read-only, so the base extends ODataReadableController`);
|
|
577
|
+
const mate = (0, moost.getMoostMate)();
|
|
578
|
+
for (let c = base; c !== ODataReadableController; c = Object.getPrototypeOf(c)) if (!mate.read(c)?.inherit) throw new Error(`valueHelpControllers: ${c.name} carries no @Inherit(): Moost passes the routes of ODataReadableController down only through classes marked @Inherit(). Add @Inherit() to ${c.name}.`);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* The read-only controllers of the value-help sets of a live space: call it after
|
|
582
|
+
* `await space.connect()` and before `app.init()`, and register what it returns.
|
|
583
|
+
*
|
|
584
|
+
* ```ts
|
|
585
|
+
* await space.connect();
|
|
586
|
+
* const own = [OrderSetController];
|
|
587
|
+
* app.registerControllers(
|
|
588
|
+
* ...own,
|
|
589
|
+
* ...valueHelpControllers(space, { prefix: "api/vh", base: SalesValueHelp, own }),
|
|
590
|
+
* );
|
|
591
|
+
* await app.init();
|
|
592
|
+
* ```
|
|
593
|
+
*
|
|
594
|
+
* Which sets: without `own`, every set of the service's value-help services; with `own`, every
|
|
595
|
+
* `@ui.valueHelp` target of the types those controllers serve, in the service or in a
|
|
596
|
+
* value-help service, except the sets they serve. Taken from the live types, so a value-help set
|
|
597
|
+
* only the live `$metadata` has is served too.
|
|
598
|
+
*
|
|
599
|
+
* Each controller is `class extends base {}`, named `<EntitySet>ValueHelpController`, bound with
|
|
600
|
+
* moost-db's `@ReadableController` at `<prefix>/<service>/<EntitySet>` (a set of the service) or
|
|
601
|
+
* `<prefix>/<service>/<value-help service>/<EntitySet>` (the reference path without `..`
|
|
602
|
+
* segments). moost-db publishes that path as the target's `db.http.path`, so the `/meta` of the
|
|
603
|
+
* parent carries it and Atscript UI offers the picker. `$with` and relational filters are refused
|
|
604
|
+
* with `400`; there are no write routes.
|
|
605
|
+
*
|
|
606
|
+
* The reads are the space's own (its `init`): the service sees the server's technical user, never
|
|
607
|
+
* the end user. Who may call these routes is the application's to decide, through `base` and its
|
|
608
|
+
* global interceptors, as for every controller it declares.
|
|
609
|
+
*
|
|
610
|
+
* A set with a name that is no plain route segment (`[A-Za-z0-9_.~-]`) gets no route, with a
|
|
611
|
+
* warning on the console.
|
|
612
|
+
*
|
|
613
|
+
* Each route is made once per space: a second call with the same prefix throws, as do two
|
|
614
|
+
* value-help services whose references differ only by `.` or `..` segments. Two spaces with one
|
|
615
|
+
* service name and one prefix would make the same routes, which the helper cannot see: give each
|
|
616
|
+
* space its own name, and let `new MoostHttp({ router: { disableDuplicatePath: true } })` make
|
|
617
|
+
* `app.init()` refuse any path registered twice.
|
|
618
|
+
*
|
|
619
|
+
* @throws Error before the space is connected, for a space over an engine at hand (it has no
|
|
620
|
+
* types), for a `base` that is no `ODataReadableController` or misses `@Inherit()`, and for a
|
|
621
|
+
* route already made for the space.
|
|
622
|
+
*/
|
|
623
|
+
function valueHelpControllers(space, options) {
|
|
624
|
+
const { prefix, base = ODataReadableController, own } = options;
|
|
625
|
+
if (!space.source) throw new Error("valueHelpControllers: the space is over an engine at hand, which has no types; create a live space (`createODataSpace({ baseUrl, model, types })`)");
|
|
626
|
+
const connection = space.connection;
|
|
627
|
+
if (!connection) throw new Error("valueHelpControllers: the OData space is not connected: call `await space.connect()` first");
|
|
628
|
+
checkBase(base);
|
|
629
|
+
const live = new Set(Object.values(connection.types));
|
|
630
|
+
let targets;
|
|
631
|
+
if (own) {
|
|
632
|
+
const served = own.map(servedType).filter((type) => type !== void 0);
|
|
633
|
+
const skip = new Set(served.map(setKey));
|
|
634
|
+
const found = /* @__PURE__ */ new Set();
|
|
635
|
+
for (const type of served) valueHelpTargets(type, found);
|
|
636
|
+
targets = [...found].filter((type) => {
|
|
637
|
+
const key = setKey(type);
|
|
638
|
+
return live.has(type) && key !== void 0 && !skip.has(key);
|
|
639
|
+
});
|
|
640
|
+
} else targets = [...live].filter((type) => typeof metaOf(type).get("odata.valueHelpService") === "string" && setKey(type) !== void 0);
|
|
641
|
+
const root = prefix.replace(/^\/+|\/+$/g, "");
|
|
642
|
+
const planned = targets.flatMap((type) => {
|
|
643
|
+
const metadata = metaOf(type);
|
|
644
|
+
const entitySet = metadata.get("db.table");
|
|
645
|
+
const valueHelpService = metadata.get("odata.valueHelpService");
|
|
646
|
+
const segments = [
|
|
647
|
+
connection.name,
|
|
648
|
+
...typeof valueHelpService === "string" ? valueHelpService.split("/").filter((s) => s !== "" && s !== "." && s !== "..") : [],
|
|
649
|
+
entitySet
|
|
650
|
+
];
|
|
651
|
+
const odd = segments.find((segment) => !SEGMENT.test(segment));
|
|
652
|
+
if (odd !== void 0) {
|
|
653
|
+
console.warn(`valueHelpControllers: no route for the entity set "${entitySet}": "${odd}" is no plain route segment`);
|
|
654
|
+
return [];
|
|
655
|
+
}
|
|
656
|
+
return [{
|
|
657
|
+
type,
|
|
658
|
+
entitySet,
|
|
659
|
+
route: [root, ...segments].filter(Boolean).join("/")
|
|
660
|
+
}];
|
|
661
|
+
});
|
|
662
|
+
const made = new Set(routesMade.get(space));
|
|
663
|
+
for (const { route } of planned) {
|
|
664
|
+
if (made.has(route)) throw new Error(`valueHelpControllers: the route "${route}" is made twice for this space (a second call with the same prefix, or value-help services whose references differ only by "." or ".." segments): a request one handler's guard refuses would be answered by the other`);
|
|
665
|
+
made.add(route);
|
|
666
|
+
}
|
|
667
|
+
routesMade.set(space, made);
|
|
668
|
+
return planned.map(({ type, entitySet, route }) => {
|
|
669
|
+
const Controller = class extends base {
|
|
670
|
+
async prepareRequest(ctx) {
|
|
671
|
+
if (ctx.controls?.$with !== void 0) throw (0, _atscript_moost_db.badRequest)("$with", "A value-help route reads no relations", "INVALID_QUERY");
|
|
672
|
+
if (ctx.hasRelationFilters) throw (0, _atscript_moost_db.badRequest)("", "A value-help route takes no relational filter", "INVALID_QUERY");
|
|
673
|
+
await super.prepareRequest(ctx);
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
Object.defineProperty(Controller, "name", { value: `${entitySet}ValueHelpController` });
|
|
677
|
+
(0, _atscript_moost_db.ReadableController)(space.getTable(type), route)(Controller);
|
|
678
|
+
return Controller;
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
//#endregion
|
|
682
|
+
exports.ODataOperation = ODataOperation;
|
|
683
|
+
Object.defineProperty(exports, "ODataOperationsController", {
|
|
684
|
+
enumerable: true,
|
|
685
|
+
get: function() {
|
|
686
|
+
return ODataOperationsController;
|
|
687
|
+
}
|
|
688
|
+
});
|
|
689
|
+
exports.ODataReadableController = ODataReadableController;
|
|
690
|
+
exports.ODataTableController = ODataTableController;
|
|
691
|
+
exports.allowedCrud = allowedCrud;
|
|
692
|
+
exports.basicAuth = basicAuth;
|
|
693
|
+
exports.bearerAuth = bearerAuth;
|
|
694
|
+
exports.callTimeout = callTimeout;
|
|
695
|
+
exports.combineAuth = combineAuth;
|
|
696
|
+
exports.currentIncomingRequest = currentIncomingRequest;
|
|
697
|
+
exports.refuseGoneEntitySet = refuseGoneEntitySet;
|
|
698
|
+
exports.refuseUnappliedSearch = refuseUnappliedSearch;
|
|
699
|
+
exports.staticHeaders = staticHeaders;
|
|
700
|
+
exports.valueHelpControllers = valueHelpControllers;
|