@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.
@@ -0,0 +1,401 @@
1
+ import { EventContext } from "@wooksjs/event-core";
2
+ import { ODataCallAnswer, ODataCallInit, ODataExtraParams, ODataOperationGrouping, ODataOperationRef, ODataRowsAnswer } from "@atscript/odata";
3
+ import { AtscriptDbReadable, FilterExpr, TCrudPermissions } from "@atscript/db";
4
+ import { ODataSpace } from "@atscript/db-odata";
5
+ import { AsDbController, AsDbReadableController, TDbActionInfo, TDbRequestContext } from "@atscript/moost-db";
6
+ import { TAtscriptAnnotatedType, TAtscriptDataType } from "@atscript/typescript/utils";
7
+
8
+ //#region src/request.d.ts
9
+ /**
10
+ * The incoming HTTP request an OData call is made for: what a credentials strategy of the
11
+ * application reads (a tenant, to pick the token the server obtained for it).
12
+ *
13
+ * Outside an HTTP event (a job, a script, application start) there is no request: `headers` is
14
+ * empty and `event` is `undefined`.
15
+ */
16
+ interface IncomingRequest {
17
+ /** The request headers, names in lower case. */
18
+ readonly headers: Readonly<Record<string, string | string[] | undefined>>;
19
+ /** The event context of the request, for composables that take one. */
20
+ readonly event: EventContext | undefined;
21
+ /** One header as a single string; `name` in any case. */
22
+ header(name: string): string | undefined;
23
+ /**
24
+ * The value of one cookie of the `Cookie` header, as Wooks' `useCookies` reads it: the name in
25
+ * any case, the header split only at `"; "`, percent-decoding undone, a quoted value with its
26
+ * quotes; `undefined` for a missing or empty one.
27
+ */
28
+ cookie(name: string): string | undefined;
29
+ }
30
+ /**
31
+ * The HTTP request of the current event, read with Wooks' `useHeaders` and `useCookies`. Resolved
32
+ * through the event context Wooks keeps in `AsyncLocalStorage`, so every overlapping request sees
33
+ * its own, wherever in its call chain this is asked.
34
+ */
35
+ declare function currentIncomingRequest(): IncomingRequest;
36
+ //#endregion
37
+ //#region src/auth.d.ts
38
+ /**
39
+ * A credentials strategy: what the adapter option `init` of `@atscript/db-odata` takes, called
40
+ * once per table operation, in the HTTP request it is made for. It returns the credentials the
41
+ * server was given for the service (a technical user), and may add a time limit
42
+ * (`callTimeout`). The service never sees the end users of the server: the server authenticates
43
+ * and authorizes them itself.
44
+ */
45
+ type ODataAuth = () => ODataCallInit | undefined | Promise<ODataCallInit | undefined>;
46
+ /**
47
+ * Headers sent with every call: `staticHeaders({ "x-api-key": key })`, a credential the server was
48
+ * given in a header of its own.
49
+ */
50
+ declare function staticHeaders(headers: Record<string, string>): ODataAuth;
51
+ /** HTTP Basic authentication of a technical user. */
52
+ declare function basicAuth(options: {
53
+ user: string;
54
+ password: string;
55
+ }): ODataAuth;
56
+ /**
57
+ * Bearer authentication of a technical user: a token, or a function asked for one at every table
58
+ * operation, which caches and refreshes a token that expires (an OAuth client-credentials token,
59
+ * for example). The function runs in the request it is asked for and receives it.
60
+ */
61
+ declare function bearerAuth(token: string | ((request: IncomingRequest) => string | Promise<string>)): ODataAuth;
62
+ /**
63
+ * Limits every table operation to `ms` milliseconds, all its OData requests together. A call
64
+ * that takes longer fails as a timeout, which the error mapping answers with `504`.
65
+ */
66
+ declare function callTimeout(ms: number): ODataAuth;
67
+ /**
68
+ * One strategy out of several: each is asked for the current request and the answers are merged
69
+ * in the order given. A later header replaces an earlier one of the same name (in any case), a
70
+ * later session replaces an earlier one, read options are merged, and the call is aborted when
71
+ * any of the signals fires.
72
+ *
73
+ * ```ts
74
+ * combineAuth(basicAuth({ user, password }), callTimeout(15_000))
75
+ * ```
76
+ */
77
+ declare function combineAuth(...strategies: ODataAuth[]): ODataAuth;
78
+ //#endregion
79
+ //#region src/controller-checks.d.ts
80
+ /**
81
+ * `crud` without the writes the entity set does not allow: `insert`, `update` and `replace`,
82
+ * `remove`, by `allowedWrites` of the adapter (`crud` as it is for a table of another adapter).
83
+ * What `ODataTableController` does in `buildCrud`; a moost-db controller of another base over an
84
+ * OData table (an ARBAC controller of aooth) does the same:
85
+ *
86
+ * ```ts
87
+ * protected override buildCrud() {
88
+ * return allowedCrud(super.buildCrud(), this.readable);
89
+ * }
90
+ * ```
91
+ */
92
+ declare function allowedCrud(crud: TCrudPermissions, readable: AtscriptDbReadable<any>): TCrudPermissions;
93
+ /**
94
+ * Refuses every endpoint of a table whose entity set the live service no longer has, `/meta`
95
+ * included: moost-db's `404` `NOT_FOUND` (`notFoundError()`), the answer of a missing row. The
96
+ * adapter itself would answer such a table with a plain `Error` (`500`), a fault of the server's
97
+ * build. Nothing for any other table. What the OData bases do in `prepareRequest`, which moost-db
98
+ * runs first on every endpoint; a moost-db controller of another base does the same:
99
+ *
100
+ * ```ts
101
+ * protected override async prepareRequest(ctx: TDbRequestContext) {
102
+ * refuseGoneEntitySet(this.readable);
103
+ * await super.prepareRequest?.(ctx); // the base's own, when it has one (aooth's ARBAC check)
104
+ * }
105
+ * ```
106
+ */
107
+ declare function refuseGoneEntitySet(readable: AtscriptDbReadable<any>): void;
108
+ //#endregion
109
+ //#region src/operations.d.ts
110
+ /** A handle of the model module's `ops`, whatever its parameter, result and row types. */
111
+ type AnyOperationRef = ODataOperationRef<any, unknown, unknown>;
112
+ /** Options of {@link ODataOperation}. */
113
+ interface ODataOperationOptions {
114
+ /**
115
+ * An operation called on rows: how several rows go out in their one `$batch`, each in a
116
+ * changeset of its own (`isolated`, Fiori's default: each row has its own outcome) or all in
117
+ * one (`changeSet`: applied all or none). The generated bases write the build's (the
118
+ * `InvocationGrouping` of the `UI.DataFieldForAction` naming the operation, else `isolated`); an
119
+ * override in a subclass sets another. A live change of it is neither refused nor followed.
120
+ */
121
+ grouping?: ODataOperationGrouping;
122
+ }
123
+ /**
124
+ * Marks a controller method as the route of an OData operation: `operation` is its typed handle
125
+ * of the model module's `ops` (`ops.OrderSet.ReleaseOrder`). The generated bases put it on every
126
+ * method they generate, beside moost-db's own decorators (`@DbAction`, `@InputForm`,
127
+ * `@DbActionRows`); `runOperation()` of the method's controller calls the operation it names, and
128
+ * the OData bases refuse an operation the live service no longer fits before anything else runs.
129
+ *
130
+ * A method of your own calls an operation the same way: a db action of your table controller over
131
+ * an unbound operation (a toolbar or row button) takes `@DbAction`, its route, this marker with
132
+ * the operation's handle, and `this.runOperation({ params })`.
133
+ */
134
+ declare function ODataOperation(operation: AnyOperationRef, options?: ODataOperationOptions): MethodDecorator;
135
+ /** What `runOperation()` of a controller takes. */
136
+ interface ODataOperationInput {
137
+ /**
138
+ * An operation called on rows: the rows of `@DbActionRows()`, each with its key and, where the
139
+ * set has a version token, its `__etag` (sent as `If-Match`).
140
+ */
141
+ rows?: readonly object[];
142
+ /**
143
+ * An operation called on rows, without a row load: the ids of `@DbActionIDs()`. The entity's
144
+ * ETag is read right before the call.
145
+ */
146
+ ids?: readonly object[];
147
+ /** The parameters: the form of `@InputForm`, or the body of an operations route. */
148
+ params?: object;
149
+ /**
150
+ * OData v2 only: parameters the operation does not declare, sent untyped. Set them in code, in
151
+ * an override; never pass on what a request sent.
152
+ */
153
+ extra?: ODataExtraParams;
154
+ }
155
+ /**
156
+ * The base of a service's operations controller: what the generated operations base
157
+ * (`<Service>OperationsBase` of the controllers module) extends. Its routes call the service's
158
+ * unbound operations, one POST each, the parameters as the JSON body; there is no UI. Declare a
159
+ * leaf over the generated base with Moost's `@Controller(path)` and `@Inherit()`, guard it and
160
+ * register it:
161
+ *
162
+ * ```ts
163
+ * ‎@Inherit()
164
+ * ‎@Controller("api/sales/ops")
165
+ * ‎@Authenticate(staff)
166
+ * export class SalesOperations extends SalesOperationsBase {}
167
+ * ```
168
+ *
169
+ * The space is the one registered under the service's name (`provideDbSpace(space, "sales")`,
170
+ * the types' `@db.space`). The body is validated against the live operation type: an invalid one
171
+ * answers moost-db's `400` envelope. An operation the live service no longer has answers `404`;
172
+ * one it changed so that the build no longer fits answers `500` (logged). The service's failures
173
+ * answer as a moost-db controller answers them (`400`, `409`, `502`, `504`, `429`).
174
+ */
175
+ declare class ODataOperationsController {
176
+ /**
177
+ * Calls the operation the current method is marked with (`@ODataOperation`), with `params` (the
178
+ * body; none for a request without one) and, on OData v2, `extra`: parameters the operation does not declare, sent untyped (set
179
+ * them in an override, never from a request). Answers `{ value, message?, messages?, details? }`.
180
+ */
181
+ protected runOperation<R = unknown>(input?: Pick<ODataOperationInput, "params" | "extra">): Promise<ODataCallAnswer<R>>;
182
+ }
183
+ //#endregion
184
+ //#region src/readable-controller.d.ts
185
+ /**
186
+ * Refuses a `$search` that moost-db's `applySearchFallback` returned unapplied (`applied` is the
187
+ * filter it was given) because neither the table nor a `@db.column.searchable` field can take it:
188
+ * `400` `INVALID_QUERY` on `$search`, where moost-db would answer every row unsearched. What the
189
+ * OData bases do; a moost-db controller of another base does the same:
190
+ *
191
+ * ```ts
192
+ * protected override applySearchFallback(filter: FilterExpr | undefined, controls: Record<string, unknown>) {
193
+ * const applied = super.applySearchFallback(filter, controls);
194
+ * refuseUnappliedSearch(this.readable, filter, controls, applied);
195
+ * return applied;
196
+ * }
197
+ * ```
198
+ */
199
+ declare function refuseUnappliedSearch(readable: AtscriptDbReadable<any>, filter: FilterExpr | undefined, controls: Record<string, unknown>, applied: FilterExpr | undefined): void;
200
+ /**
201
+ * The read-only controller of `@atscript/moost-db` (`AsDbReadableController`) for an entity set of
202
+ * an OData service. Declare one per entity set, as with any moost-db controller:
203
+ *
204
+ * ```ts
205
+ * ‎@ReadableController(sales.Customer, "api/sales/CustomerSet")
206
+ * export class CustomerSetController extends ODataReadableController<typeof sales.Customer> {}
207
+ * ```
208
+ *
209
+ * The model token resolves the space the application registered under the types' `@db.space`
210
+ * (`provideDbSpace(space, "sales")`); a table of the space (`space.getTable(sales.Customer)`)
211
+ * binds as well.
212
+ *
213
+ * What it adds to moost-db's controller:
214
+ *
215
+ * - **`$search`** on an entity set the service cannot search is refused with `400`; moost-db would
216
+ * answer with every row unsearched. A type whose fields carry `@db.column.searchable` keeps
217
+ * moost-db's substring search over those fields.
218
+ * - **An entity set the live service no longer has** answers every endpoint, `/meta` included,
219
+ * with moost-db's `404` `NOT_FOUND`, from `prepareRequest`. A subclass that implements
220
+ * `prepareRequest` itself calls `super.prepareRequest(ctx)` first.
221
+ *
222
+ * A failure of the service needs nothing of it: the adapter throws atscript-db's `STORE_FAILED`,
223
+ * `STORE_TIMEOUT` or `STORE_THROTTLED`, which every moost-db controller answers `502`, `504` or
224
+ * `429` (with `Retry-After`) and logs.
225
+ *
226
+ * A class of your own between yours and this one needs Moost's `@Inherit()`, as with any Moost
227
+ * controller base.
228
+ */
229
+ declare class ODataReadableController<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType, DataType = TAtscriptDataType<T>> extends AsDbReadableController<T, DataType> {
230
+ protected applySearchFallback(filter: FilterExpr | undefined, controls: Record<string, unknown>): FilterExpr | undefined;
231
+ private get operationHost();
232
+ /**
233
+ * Refuses a set the live service no longer has (`404` on every endpoint, `/meta` included) and
234
+ * an operation of the build it no longer fits (an action of the controller: `404` when the
235
+ * service no longer has it, `500` when it changed it). A subclass that implements it calls
236
+ * `super.prepareRequest(ctx)` first.
237
+ */
238
+ protected prepareRequest(ctx: TDbRequestContext): void | Promise<void>;
239
+ /**
240
+ * The db actions, without the operations the live service no longer fits: what `/meta`,
241
+ * `$actions` and `/meta/actions` list.
242
+ */
243
+ protected buildActions(): TDbActionInfo[];
244
+ /**
245
+ * Calls the OData operation the current method is marked with (`@ODataOperation`), bound to the
246
+ * controller's entity set: on `rows` (`@DbActionRows()`; each row's `__etag` is sent as
247
+ * `If-Match`) or `ids` (`@DbActionIDs()`) for an operation called on rows, with `params` (the
248
+ * `@InputForm`) and, on OData v2, `extra` (parameters the operation does not declare, set in
249
+ * code). An id the row load did not find answers `404`, before any call.
250
+ *
251
+ * On rows it answers `ODataRowsAnswer`: moost-db's action target summary (`matched`,
252
+ * `processed`, `skipped` by the availability gate, `failed` with each row's `status` and
253
+ * `code`) with one `value` per row that ran and the service's messages. Several rows go out as
254
+ * one `$batch` by the mark's grouping: `isolated` (each row on its own; the rows that ran stay
255
+ * applied when others fail) or `changeSet` (all or none: a refused run answers its one error,
256
+ * nothing applied). Every row failed: the first row's error, with the entries of every row at
257
+ * `[i]`; one row: its own error (a stale `__etag`: moost-db's `409` `VERSION_MISMATCH` with the
258
+ * current token). On the collection it answers `{ value, message?, messages?, details? }`.
259
+ */
260
+ protected runOperation<R = unknown>(input: ODataOperationInput & ({
261
+ rows: readonly object[];
262
+ } | {
263
+ ids: readonly object[];
264
+ })): Promise<ODataRowsAnswer<R>>;
265
+ protected runOperation<R = unknown>(input?: ODataOperationInput): Promise<ODataCallAnswer<R>>;
266
+ }
267
+ //#endregion
268
+ //#region src/table-controller.d.ts
269
+ /**
270
+ * The read and write controller of `@atscript/moost-db` (`AsDbController`: `POST`, `PUT`,
271
+ * `PATCH`, `DELETE` next to the read endpoints) for an entity set the service lets you write to.
272
+ * Declare one per entity set, as with any moost-db controller:
273
+ *
274
+ * ```ts
275
+ * ‎@TableController(sales.Order, "api/sales/OrderSet")
276
+ * export class OrderSetController extends ODataTableController<typeof sales.Order> {}
277
+ * ```
278
+ *
279
+ * The model token resolves the space the application registered under the types' `@db.space`
280
+ * (`provideDbSpace(space, "sales")`); a table of the space (`space.getTable(sales.Order)`) binds
281
+ * as well.
282
+ *
283
+ * Everything `ODataReadableController` adds, and:
284
+ *
285
+ * - **Only the writes the entity set allows** are offered: `/meta` lists in `crud` the writes the
286
+ * live service allows (`allowedWrites` of `@atscript/db-odata`). Another write is refused before
287
+ * any request with moost-db's `400` `NOT_SUPPORTED`, naming why. That holds for a set that takes
288
+ * no write at all, and for one the live service no longer lets you write to: the application
289
+ * starts either way.
290
+ * - **An entity set the live service no longer has** answers every endpoint with `404`
291
+ * `NOT_FOUND`, from `prepareRequest` (a subclass that implements it calls
292
+ * `super.prepareRequest(ctx)` first).
293
+ *
294
+ * Its writes are those of `@atscript/db-odata`: one entity at a time, by key, and last-write-wins,
295
+ * each in the session the space keeps for the credentials it sends.
296
+ */
297
+ declare class ODataTableController<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType, DataType = TAtscriptDataType<T>> extends AsDbController<T, DataType> {
298
+ protected buildCrud(): TCrudPermissions;
299
+ protected applySearchFallback(filter: FilterExpr | undefined, controls: Record<string, unknown>): FilterExpr | undefined;
300
+ private get operationHost();
301
+ /**
302
+ * Refuses a set the live service no longer has (`404` on every endpoint, `/meta` included) and
303
+ * an operation of the build it no longer fits (an action of the controller: `404` when the
304
+ * service no longer has it, `500` when it changed it). A subclass that implements it calls
305
+ * `super.prepareRequest(ctx)` first.
306
+ */
307
+ protected prepareRequest(ctx: TDbRequestContext): void | Promise<void>;
308
+ /**
309
+ * The db actions, without the operations the live service no longer fits: what `/meta`,
310
+ * `$actions` and `/meta/actions` list.
311
+ */
312
+ protected buildActions(): TDbActionInfo[];
313
+ /**
314
+ * Calls the OData operation the current method is marked with (`@ODataOperation`), bound to the
315
+ * controller's entity set: on `rows` (`@DbActionRows()`; each row's `__etag` is sent as
316
+ * `If-Match`) or `ids` (`@DbActionIDs()`) for an operation called on rows, with `params` (the
317
+ * `@InputForm`) and, on OData v2, `extra` (parameters the operation does not declare, set in
318
+ * code). An id the row load did not find answers `404`, before any call.
319
+ *
320
+ * On rows it answers `ODataRowsAnswer`: moost-db's action target summary (`matched`,
321
+ * `processed`, `skipped` by the availability gate, `failed` with each row's `status` and
322
+ * `code`) with one `value` per row that ran and the service's messages. Several rows go out as
323
+ * one `$batch` by the mark's grouping: `isolated` (each row on its own; the rows that ran stay
324
+ * applied when others fail) or `changeSet` (all or none: a refused run answers its one error,
325
+ * nothing applied). Every row failed: the first row's error, with the entries of every row at
326
+ * `[i]`; one row: its own error (a stale `__etag`: moost-db's `409` `VERSION_MISMATCH` with the
327
+ * current token). On the collection it answers `{ value, message?, messages?, details? }`.
328
+ */
329
+ protected runOperation<R = unknown>(input: ODataOperationInput & ({
330
+ rows: readonly object[];
331
+ } | {
332
+ ids: readonly object[];
333
+ })): Promise<ODataRowsAnswer<R>>;
334
+ protected runOperation<R = unknown>(input?: ODataOperationInput): Promise<ODataCallAnswer<R>>;
335
+ }
336
+ //#endregion
337
+ //#region src/value-help-controllers.d.ts
338
+ /** Options of {@link valueHelpControllers}. */
339
+ interface ValueHelpControllerOptions {
340
+ /** The route prefix of every value-help route: `api/vh`. */
341
+ prefix: string;
342
+ /**
343
+ * The class every controller extends: `ODataReadableController` (the default), or a class of
344
+ * the application's own between them, each marked `@Inherit()`. Where the application puts its
345
+ * guards (`@Authenticate`, `@ArbacResource`, interceptors) and hooks for every value-help route.
346
+ */
347
+ base?: typeof ODataReadableController<any>;
348
+ /**
349
+ * The application's own controller classes. With it, the helper serves the `@ui.valueHelp`
350
+ * targets of the types they serve (in the service or in a value-help service) and nothing
351
+ * else, and never a set one of them serves already. Without it, every set of the service's
352
+ * value-help services (`Common.ValueListReferences`).
353
+ */
354
+ own?: readonly Function[];
355
+ }
356
+ /**
357
+ * The read-only controllers of the value-help sets of a live space: call it after
358
+ * `await space.connect()` and before `app.init()`, and register what it returns.
359
+ *
360
+ * ```ts
361
+ * await space.connect();
362
+ * const own = [OrderSetController];
363
+ * app.registerControllers(
364
+ * ...own,
365
+ * ...valueHelpControllers(space, { prefix: "api/vh", base: SalesValueHelp, own }),
366
+ * );
367
+ * await app.init();
368
+ * ```
369
+ *
370
+ * Which sets: without `own`, every set of the service's value-help services; with `own`, every
371
+ * `@ui.valueHelp` target of the types those controllers serve, in the service or in a
372
+ * value-help service, except the sets they serve. Taken from the live types, so a value-help set
373
+ * only the live `$metadata` has is served too.
374
+ *
375
+ * Each controller is `class extends base {}`, named `<EntitySet>ValueHelpController`, bound with
376
+ * moost-db's `@ReadableController` at `<prefix>/<service>/<EntitySet>` (a set of the service) or
377
+ * `<prefix>/<service>/<value-help service>/<EntitySet>` (the reference path without `..`
378
+ * segments). moost-db publishes that path as the target's `db.http.path`, so the `/meta` of the
379
+ * parent carries it and Atscript UI offers the picker. `$with` and relational filters are refused
380
+ * with `400`; there are no write routes.
381
+ *
382
+ * The reads are the space's own (its `init`): the service sees the server's technical user, never
383
+ * the end user. Who may call these routes is the application's to decide, through `base` and its
384
+ * global interceptors, as for every controller it declares.
385
+ *
386
+ * A set with a name that is no plain route segment (`[A-Za-z0-9_.~-]`) gets no route, with a
387
+ * warning on the console.
388
+ *
389
+ * Each route is made once per space: a second call with the same prefix throws, as do two
390
+ * value-help services whose references differ only by `.` or `..` segments. Two spaces with one
391
+ * service name and one prefix would make the same routes, which the helper cannot see: give each
392
+ * space its own name, and let `new MoostHttp({ router: { disableDuplicatePath: true } })` make
393
+ * `app.init()` refuse any path registered twice.
394
+ *
395
+ * @throws Error before the space is connected, for a space over an engine at hand (it has no
396
+ * types), for a `base` that is no `ODataReadableController` or misses `@Inherit()`, and for a
397
+ * route already made for the space.
398
+ */
399
+ declare function valueHelpControllers(space: ODataSpace, options: ValueHelpControllerOptions): Function[];
400
+ //#endregion
401
+ export { type IncomingRequest, type ODataAuth, ODataOperation, type ODataOperationInput, type ODataOperationOptions, ODataOperationsController, ODataReadableController, ODataTableController, type ValueHelpControllerOptions, allowedCrud, basicAuth, bearerAuth, callTimeout, combineAuth, currentIncomingRequest, refuseGoneEntitySet, refuseUnappliedSearch, staticHeaders, valueHelpControllers };