@atscript/moost-odata 0.0.0-stage → 0.0.1

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