@venizia/ardor-kernel 0.4.8-15 → 0.4.8-17

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.
@@ -1,18 +1,33 @@
1
1
  import { getError } from '@venizia/ignis-inversion';
2
+ import { HTTP } from '@venizia/ignis-helpers/common';
2
3
  import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
3
4
  import { UuidV4Generator } from '@venizia/ignis-helpers/uuid';
4
5
  import { HttpExtraRequest } from '@venizia/ignis-kernel/repository';
5
6
  import { App, HeaderConstants, LocalStorageKeys, RequestChannel, RequestCountData, RequestMethods, RequestTypes, } from '../../common/index.js';
6
7
  import { AuthRecovery, AuthTokenStore, NetworkHeaders, RequestBodyEncoder, ResponseReader, } from '../../helpers/index.js';
7
8
  import { BaseService } from './base.js';
9
+ /** The `normalized.code` of the 401 that answers a request whose session is gone: the user who sent it signed out or another user signed in while it was in flight. */
10
+ export const SESSION_CHANGED_CODE = 'ardor.network.session_changed';
11
+ /** The `normalized.code` of the 504 a request rejects with when it outlives the configured `timeout`. */
12
+ export const NETWORK_TIMEOUT_CODE = 'ardor.network.timeout';
8
13
  /**
14
+ * Sends the requests of the data provider with its own sender. The repositories of
15
+ * `@venizia/ardor/repository` send through IGNIS's `HttpDataSource`, from the optional peer
16
+ * `@venizia/ignis-connectors`, which this service cannot import without making that peer required:
17
+ * until IGNIS's transport core is in a required peer, two clients exist, and `getDataSourceAuth`
18
+ * gives the second the session of the first.
19
+ *
9
20
  * The options hold data (the base URL, headers, the no-auth lists, the refresh path); behaviour is
10
21
  * in the protected hooks, each taking one `opts` object, which a subclass overrides.
11
22
  */
12
23
  export class DefaultNetworkRequestService extends BaseService {
13
24
  constructor(opts) {
14
25
  super({ scope: DefaultNetworkRequestService.name });
15
- const { name, baseUrl = '', headers = {}, noAuthPaths, noAuthPathRegex, authRecovery, authService, } = opts;
26
+ /** The session each data source request was sent under, keyed by the context object IGNIS hands to both hooks. */
27
+ this.sentSessions = new WeakMap();
28
+ const { name, baseUrl = '', headers = {}, noAuthPaths, noAuthPathRegex, authRecovery, authService, timeout = { use: false }, } = opts;
29
+ DefaultNetworkRequestService.assertTimeout({ timeout });
30
+ this.timeout = timeout;
16
31
  this.headers = NetworkHeaders.toRecord({ headers });
17
32
  this.noAuthPaths = noAuthPaths;
18
33
  this.noAuthPathRegexes = this.compileNoAuthPathRegex({ input: noAuthPathRegex });
@@ -54,6 +69,19 @@ export class DefaultNetworkRequestService extends BaseService {
54
69
  const { token: key } = LocalStorageKeys.scoped({ id: opts.id });
55
70
  return () => AuthTokenStore.read({ key });
56
71
  }
72
+ /** Throws unless a timeout that is on has a positive integer `milliseconds`. */
73
+ static assertTimeout(opts) {
74
+ const { timeout } = opts;
75
+ if (!timeout?.use) {
76
+ return;
77
+ }
78
+ const { milliseconds } = timeout;
79
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {
80
+ throw getError({
81
+ message: `[DefaultNetworkRequestService] timeout.milliseconds must be a positive integer, got ${milliseconds}`,
82
+ });
83
+ }
84
+ }
57
85
  // --- Hooks -----------------------------------------------------------------------------------
58
86
  /**
59
87
  * The token this service sends. The one way to supply a token: override it to read another
@@ -217,7 +245,79 @@ export class DefaultNetworkRequestService extends BaseService {
217
245
  * Also what `DefaultAuthProvider.refreshToken` calls, so a refresh is made in one place.
218
246
  */
219
247
  refresh() {
220
- return this.recovery.refresh();
248
+ const { userId, token } = this.readSession();
249
+ return this.recovery.refresh({ key: `${userId}|${token}` });
250
+ }
251
+ /** The session signed in now: who, and with which token. */
252
+ readSession() {
253
+ const userId = this.authService?.getUser().userId;
254
+ return {
255
+ userId: userId === undefined ? undefined : `${userId}`,
256
+ token: this.resolveAuthToken()?.value,
257
+ };
258
+ }
259
+ /** The 401 that answers a request whose session is gone: `DefaultAuthProvider.checkError` leaves the signed-in session alone for it. */
260
+ sessionChangedError() {
261
+ return getError({
262
+ statusCode: 401,
263
+ messageCode: SESSION_CHANGED_CODE,
264
+ message: '[doRequest] The session that sent this request ended while it was in flight',
265
+ });
266
+ }
267
+ /**
268
+ * How the session changed since `sent`: `undefined` when it did not, `true` when the same user holds
269
+ * another token now (the request can be sent again with it), `false` when the user who sent is gone. When
270
+ * nobody can tell who sent, another token is a switch: it is never read as the same user's.
271
+ */
272
+ readSessionChange(opts) {
273
+ const { sent } = opts;
274
+ const now = this.readSession();
275
+ if (now.userId === sent.userId && now.token === sent.token) {
276
+ return undefined;
277
+ }
278
+ return sent.userId !== undefined && now.userId === sent.userId && !!now.token;
279
+ }
280
+ /** `task` settles as it does, or the wait rejects with the reason of `signal` once it aborts; the task itself is not cancelled. */
281
+ static async untilAborted(opts) {
282
+ const { task, signal } = opts;
283
+ if (!signal) {
284
+ return task;
285
+ }
286
+ let onAbort;
287
+ const aborted = new Promise((_resolve, reject) => {
288
+ onAbort = () => reject(signal.reason);
289
+ if (signal.aborted) {
290
+ onAbort();
291
+ return;
292
+ }
293
+ signal.addEventListener('abort', onAbort, { once: true });
294
+ });
295
+ try {
296
+ const settled = await Promise.race([task, aborted]);
297
+ return settled;
298
+ }
299
+ finally {
300
+ if (onAbort) {
301
+ signal.removeEventListener('abort', onAbort);
302
+ }
303
+ }
304
+ }
305
+ /**
306
+ * Whether the 401 of a request that `sent` is a session change for the caller: the user who sent is gone and
307
+ * either the request was sent again since (`isRetried`) or another session is signed in now. A refresh that
308
+ * failed and ended the session itself leaves nobody to protect, and its 401 stands.
309
+ */
310
+ isSessionTaken(opts) {
311
+ // With no user to compare, the token that follows a refresh this service ran is that refresh's.
312
+ if (opts.sent.userId === undefined && opts.isRetried) {
313
+ return false;
314
+ }
315
+ // A user switch in progress (a token stored for another user than the identity) is someone signing in: it
316
+ // reads no token, but it is not a sign-out.
317
+ return (this.readSessionChange({ sent: opts.sent }) === false &&
318
+ (opts.isRetried ||
319
+ this.readSession().token !== undefined ||
320
+ this.authService?.isSwitching() === true));
221
321
  }
222
322
  // --- Requests --------------------------------------------------------------------------------
223
323
  /**
@@ -227,18 +327,46 @@ export class DefaultNetworkRequestService extends BaseService {
227
327
  */
228
328
  getDataSourceAuth(opts) {
229
329
  return {
230
- authTokenResolver: ({ paths }) => {
231
- return this.isNoAuthPath({ resource: paths[0], paths })
330
+ authTokenResolver: (context) => {
331
+ const { paths } = context;
332
+ const sent = this.sentSessions.get(context);
333
+ // The retry of a request whose user has gone must not carry the token of whoever signed in since.
334
+ if (sent && this.readSessionChange({ sent }) === false) {
335
+ return undefined;
336
+ }
337
+ const token = this.isNoAuthPath({ resource: paths[0], paths })
232
338
  ? undefined
233
339
  : this.resolveAuthToken();
340
+ // Both hooks receive this very object, and a retry sends again under the session of that moment.
341
+ this.sentSessions.set(context, { userId: this.readSession().userId, token: token?.value });
342
+ return token;
234
343
  },
235
344
  headersResolver: () => {
236
345
  return NetworkHeaders.merge({
237
346
  sources: [this.getSessionHeaders(), opts ? this.getTracingHeaders(opts) : {}],
238
347
  });
239
348
  },
240
- onUnauthorized: ({ paths }) => {
241
- return this.recovery.canRecover({ paths }) ? this.refresh() : Promise.resolve(false);
349
+ onUnauthorized: (context) => {
350
+ if (!this.recovery.canRecover({ paths: context.paths })) {
351
+ return Promise.resolve(false);
352
+ }
353
+ const sent = this.sentSessions.get(context);
354
+ const change = sent ? this.readSessionChange({ sent }) : undefined;
355
+ if (change === false) {
356
+ return Promise.reject(this.sessionChangedError());
357
+ }
358
+ if (change === true) {
359
+ return Promise.resolve(true);
360
+ }
361
+ return this.refresh().then((isRefreshed) => {
362
+ // The retry sends again under the session of this refresh.
363
+ if (sent && sent.userId === undefined && isRefreshed) {
364
+ this.sentSessions.set(context, this.readSession());
365
+ }
366
+ return sent && this.isSessionTaken({ sent, isRetried: isRefreshed })
367
+ ? Promise.reject(this.sessionChangedError())
368
+ : isRefreshed;
369
+ });
242
370
  },
243
371
  errorRootKey: ResponseReader.ERROR_ROOT_KEY,
244
372
  };
@@ -376,10 +504,11 @@ export class DefaultNetworkRequestService extends BaseService {
376
504
  * Sends the request and reads the response by `type`. Throws when `baseUrl` (the option, else the
377
505
  * service's) is empty. A 401 on a path that can recover triggers `refresh` and, if it refreshed,
378
506
  * one retry with the new token. Any other non-2xx response, or a retry that still fails, throws
379
- * the error read from the response.
507
+ * the error read from the response. An aborted `signal` rejects with its reason, and a request
508
+ * that outlives the service's `timeout` rejects with a 504 coded `NETWORK_TIMEOUT_CODE`.
380
509
  */
381
510
  async doRequest(opts) {
382
- const { baseUrl = this.baseUrl, type, method, paths, body, headers, query, requestCountData, } = opts;
511
+ const { baseUrl = this.baseUrl, paths, signal } = opts;
383
512
  if (!baseUrl) {
384
513
  throw getError({
385
514
  message: '[doRequest] Invalid baseUrl to send request!',
@@ -389,6 +518,33 @@ export class DefaultNetworkRequestService extends BaseService {
389
518
  if (!DefaultNetworkRequestService.isUnderBase({ baseUrl, paths, url })) {
390
519
  throw getError({ message: '[doRequest] Invalid path to send request!' });
391
520
  }
521
+ const timeoutSignal = this.timeout.use
522
+ ? AbortSignal.timeout(this.timeout.milliseconds)
523
+ : undefined;
524
+ const sendSignal = timeoutSignal && signal
525
+ ? AbortSignal.any([signal, timeoutSignal])
526
+ : (timeoutSignal ?? signal);
527
+ try {
528
+ const response = await this.sendAndRead({ ...opts, url, signal: sendSignal });
529
+ return response;
530
+ }
531
+ catch (error) {
532
+ // The combined signal keeps the reason of whichever source aborted first.
533
+ if (this.timeout.use &&
534
+ timeoutSignal?.aborted &&
535
+ sendSignal?.reason === timeoutSignal.reason) {
536
+ throw getError({
537
+ statusCode: HTTP.ResultCodes.RS_5.GatewayTimeout,
538
+ messageCode: NETWORK_TIMEOUT_CODE,
539
+ message: `[doRequest] The request to ${paths.join('/')} did not answer within ${this.timeout.milliseconds} ms`,
540
+ });
541
+ }
542
+ throw error;
543
+ }
544
+ }
545
+ /** `doRequest` once the URL is checked: the send, the refresh and retry after a 401, then the read. */
546
+ async sendAndRead(opts) {
547
+ const { url, type, method, paths, body, headers, query, requestCountData, signal } = opts;
392
548
  const sendOnce = (sendHeaders) => {
393
549
  return this.networkRequest.getNetworkService().send({
394
550
  url,
@@ -396,15 +552,33 @@ export class DefaultNetworkRequestService extends BaseService {
396
552
  params: query,
397
553
  body: method === RequestMethods.GET ? undefined : body,
398
554
  headers: sendHeaders,
555
+ signal,
399
556
  }, this.logger);
400
557
  };
401
- // Who sends: a 401 that arrives after another user signed in is not this user's to refresh.
402
- const sentBy = `${this.authService?.getUser().userId}`;
558
+ const sent = this.readSession();
559
+ let isRetried = false;
403
560
  let fetched = await sendOnce(headers);
404
- if (fetched.status === 401 &&
405
- `${this.authService?.getUser().userId}` === sentBy &&
406
- this.recovery.canRecover({ paths })) {
407
- const isRefreshed = await this.refresh();
561
+ if (fetched.status === 401 && this.recovery.canRecover({ paths })) {
562
+ // A 401 that arrives after the session changed is not the new session's to refresh or to end.
563
+ const change = this.readSessionChange({ sent });
564
+ if (change === false) {
565
+ throw this.sessionChangedError();
566
+ }
567
+ let isRefreshed = change === true;
568
+ if (change === undefined) {
569
+ // The wait ends with this request's abort; the refresh itself keeps running for the others.
570
+ const refreshed = await DefaultNetworkRequestService.untilAborted({
571
+ task: this.refresh(),
572
+ signal,
573
+ });
574
+ isRefreshed = refreshed;
575
+ }
576
+ // The session may have moved on while the refresh was in flight, or inside a `refreshToken` override.
577
+ if (this.isSessionTaken({ sent, isRetried: isRefreshed })) {
578
+ throw this.sessionChangedError();
579
+ }
580
+ // The shared refresh is never aborted for one request: this request stops when it returns.
581
+ signal?.throwIfAborted();
408
582
  if (isRefreshed) {
409
583
  const authHeader = this.getRequestAuthorizationHeader();
410
584
  const retryHeaders = NetworkHeaders.merge({
@@ -418,14 +592,26 @@ export class DefaultNetworkRequestService extends BaseService {
418
592
  });
419
593
  const result = await sendOnce(retryHeaders);
420
594
  fetched = result;
595
+ isRetried = true;
421
596
  }
422
597
  }
423
598
  const status = fetched.status;
599
+ // The retry may have been answered 401 after the user who sent it had gone too.
600
+ if (status === 401 &&
601
+ this.recovery.canRecover({ paths }) &&
602
+ this.isSessionTaken({ sent, isRetried })) {
603
+ throw this.sessionChangedError();
604
+ }
424
605
  if (status < 200 || status >= 300) {
425
606
  const result2 = await ResponseReader.toError({ response: fetched });
426
607
  throw result2;
427
608
  }
428
- return ResponseReader.read({ response: fetched, type, requestCountData });
609
+ const response = await ResponseReader.read({
610
+ response: fetched,
611
+ type,
612
+ requestCountData,
613
+ });
614
+ return response;
429
615
  }
430
616
  }
431
617
  //# sourceMappingURL=network-request.js.map
@@ -1,3 +1,4 @@
1
+ import type { IRestDataProviderOptions, IRolePermissionProviderOptions, TAuthProviderOptions } from './types.js';
1
2
  /** The container keys the kernel binds and reads. */
2
3
  export declare class CoreBindings {
3
4
  /** The application itself, bound by `preConfigure`. */
@@ -10,35 +11,69 @@ export declare class CoreBindings {
10
11
  static readonly DEFAULT_I18N_PROVIDER = "@app/application/i18n/default";
11
12
  /** The REST data provider. */
12
13
  static readonly DEFAULT_REST_DATA_PROVIDER = "@app/application/data/rest/default";
13
- /** The `IAuthProviderOptions`. */
14
+ /** The `TAuthProviderOptions`: `{ use: true }` turns sign-in on; unbound means `{ use: false }`. */
14
15
  static readonly AUTH_PROVIDER_OPTIONS = "@app/application/options/auth";
15
16
  /** The `DefaultAuthService`. */
16
17
  static readonly DEFAULT_AUTH_SERVICE = "@app/application/service/auth/default";
17
18
  /** The `IRestDataProviderOptions`. */
18
19
  static readonly REST_DATA_PROVIDER_OPTIONS = "@app/application/options/rest/data";
19
- /** The options of the i18n provider. */
20
+ /** The options of the i18n provider; unbound means English only. */
20
21
  static readonly I18N_PROVIDER_OPTIONS = "@app/application/options/i18n";
21
22
  /** The `features()` an application mounts, bound by `preConfigure()`. */
22
23
  static readonly FEATURES = "@app/application/features";
23
24
  /** An `IPermissionProvider`, bound by the application; unbound means every check passes. */
24
25
  static readonly PERMISSION_PROVIDER = "@app/application/permission/provider";
26
+ /** The `IRolePermissionProviderOptions` that `RolePermissionProvider` reads. */
27
+ static readonly PERMISSION_PROVIDER_OPTIONS = "@app/application/options/permission";
28
+ }
29
+ /**
30
+ * The options type of each options key of `CoreBindings`, which `provideOption` checks a method
31
+ * against. A package that owns an options type declares it with `declare module '@venizia/ardor-kernel'`:
32
+ * `@venizia/ardor-admin` adds `CoreBindings.I18N_PROVIDER_OPTIONS`.
33
+ */
34
+ export interface ICoreOptionTypes {
35
+ [CoreBindings.AUTH_PROVIDER_OPTIONS]: TAuthProviderOptions;
36
+ [CoreBindings.REST_DATA_PROVIDER_OPTIONS]: IRestDataProviderOptions;
37
+ [CoreBindings.PERMISSION_PROVIDER_OPTIONS]: IRolePermissionProviderOptions;
25
38
  }
26
39
  /** The session keys and the store prefix of one application, from `LocalStorageKeys.scoped`. */
27
40
  export interface IScopedKeys {
28
- /** Everything under it is this application's session: `DefaultAuthService.cleanUp` removes it all. */
41
+ /**
42
+ * The prefix of this application's session keys: `DefaultAuthService.cleanUp` removes them. Without
43
+ * an application `id` it is also the start of every scoped session, and `cleanUp` skips those.
44
+ */
29
45
  authPrefix: string;
30
- /** The data of this application's signed-in user; sign-out removes everything under it. */
46
+ /**
47
+ * The data of this application's signed-in user; sign-out removes every key that starts with it.
48
+ * Without an application `id` it is `@app/store/`, the start of every scoped store prefix, so an
49
+ * application without an `id` removes the data of the applications with one: every application on
50
+ * an origin sets an `id`.
51
+ */
31
52
  storePrefix: string;
53
+ /** The preferences of this application's user: they outlive a sign-out. */
54
+ prefsPrefix: string;
55
+ /** The stored locale of the i18n provider. */
56
+ locale: string;
32
57
  token: string;
33
58
  identity: string;
34
59
  permission: string;
35
60
  }
36
61
  /** The `localStorage` keys the kernel owns. */
37
62
  export declare class LocalStorageKeys {
38
- /** Everything under this prefix is the session: `DefaultAuthService.cleanUp` removes it all. */
63
+ /**
64
+ * The session keys of an application with no `id`: `DefaultAuthService.cleanUp` removes them, and
65
+ * skips the keys of applications with an `id`, which are `@app/auth/<id>/...`.
66
+ */
39
67
  static readonly PREFIX_AUTH = "@app/auth/";
40
- /** The data of the signed-in user: sign-out removes everything under it. Preferences that outlive a sign-out go under `@app/prefs/`. */
68
+ /**
69
+ * The data of the signed-in user: sign-out removes every key that starts with the store prefix of
70
+ * the application. This one is the start of every scoped store prefix (`@app/store/<id>/`), so
71
+ * applications that share an origin must all set an `id`. Preferences that outlive a sign-out go
72
+ * under `@app/prefs/`.
73
+ */
41
74
  static readonly PREFIX_STORE = "@app/store/";
75
+ /** Preferences that outlive a sign-out, such as the chosen language: nothing sweeps them. */
76
+ static readonly PREFIX_PREFS = "@app/prefs/";
42
77
  /** The stored `IAuthTokenRecord`, as JSON. */
43
78
  static readonly KEY_AUTH_TOKEN = "@app/auth/token";
44
79
  /** The stored identity (`userId`, `username`, `referenceId`, `provider`), as JSON. */
@@ -50,9 +85,10 @@ export declare class LocalStorageKeys {
50
85
  /**
51
86
  * The keys of one application. With no `id` they are the constants above, so an application that is
52
87
  * alone on its origin changes nothing. With an `id` (`IApplicationInfo.id`) the session sits under
53
- * `@app/auth/<id>/` and the store under `@app/store/<id>/`, so two applications on one origin share
88
+ * `@app/auth/<id>/`, the store under `@app/store/<id>/` and the preferences under `@app/prefs/<id>/`, so two applications on one origin share
54
89
  * no session and no sign-out sweeps the other's data. The `id` is letters, digits, `.`, `_` and `-`,
55
- * and is not made of dots only.
90
+ * and is not made of dots only. Applications on one origin must ALL set an `id`: the store prefix
91
+ * without one is a prefix of every scoped store prefix, so its sign-out removes their data too.
56
92
  */
57
93
  static scoped(opts?: {
58
94
  id?: string;
@@ -11,25 +11,37 @@ export class CoreBindings {
11
11
  static { this.DEFAULT_I18N_PROVIDER = '@app/application/i18n/default'; }
12
12
  /** The REST data provider. */
13
13
  static { this.DEFAULT_REST_DATA_PROVIDER = '@app/application/data/rest/default'; }
14
- /** The `IAuthProviderOptions`. */
14
+ /** The `TAuthProviderOptions`: `{ use: true }` turns sign-in on; unbound means `{ use: false }`. */
15
15
  static { this.AUTH_PROVIDER_OPTIONS = '@app/application/options/auth'; }
16
16
  /** The `DefaultAuthService`. */
17
17
  static { this.DEFAULT_AUTH_SERVICE = '@app/application/service/auth/default'; }
18
18
  /** The `IRestDataProviderOptions`. */
19
19
  static { this.REST_DATA_PROVIDER_OPTIONS = '@app/application/options/rest/data'; }
20
- /** The options of the i18n provider. */
20
+ /** The options of the i18n provider; unbound means English only. */
21
21
  static { this.I18N_PROVIDER_OPTIONS = '@app/application/options/i18n'; }
22
22
  /** The `features()` an application mounts, bound by `preConfigure()`. */
23
23
  static { this.FEATURES = '@app/application/features'; }
24
24
  /** An `IPermissionProvider`, bound by the application; unbound means every check passes. */
25
25
  static { this.PERMISSION_PROVIDER = '@app/application/permission/provider'; }
26
+ /** The `IRolePermissionProviderOptions` that `RolePermissionProvider` reads. */
27
+ static { this.PERMISSION_PROVIDER_OPTIONS = '@app/application/options/permission'; }
26
28
  }
27
29
  /** The `localStorage` keys the kernel owns. */
28
30
  export class LocalStorageKeys {
29
- /** Everything under this prefix is the session: `DefaultAuthService.cleanUp` removes it all. */
31
+ /**
32
+ * The session keys of an application with no `id`: `DefaultAuthService.cleanUp` removes them, and
33
+ * skips the keys of applications with an `id`, which are `@app/auth/<id>/...`.
34
+ */
30
35
  static { this.PREFIX_AUTH = '@app/auth/'; }
31
- /** The data of the signed-in user: sign-out removes everything under it. Preferences that outlive a sign-out go under `@app/prefs/`. */
36
+ /**
37
+ * The data of the signed-in user: sign-out removes every key that starts with the store prefix of
38
+ * the application. This one is the start of every scoped store prefix (`@app/store/<id>/`), so
39
+ * applications that share an origin must all set an `id`. Preferences that outlive a sign-out go
40
+ * under `@app/prefs/`.
41
+ */
32
42
  static { this.PREFIX_STORE = '@app/store/'; }
43
+ /** Preferences that outlive a sign-out, such as the chosen language: nothing sweeps them. */
44
+ static { this.PREFIX_PREFS = '@app/prefs/'; }
33
45
  /** The stored `IAuthTokenRecord`, as JSON. */
34
46
  static { this.KEY_AUTH_TOKEN = '@app/auth/token'; }
35
47
  /** The stored identity (`userId`, `username`, `referenceId`, `provider`), as JSON. */
@@ -45,9 +57,10 @@ export class LocalStorageKeys {
45
57
  /**
46
58
  * The keys of one application. With no `id` they are the constants above, so an application that is
47
59
  * alone on its origin changes nothing. With an `id` (`IApplicationInfo.id`) the session sits under
48
- * `@app/auth/<id>/` and the store under `@app/store/<id>/`, so two applications on one origin share
60
+ * `@app/auth/<id>/`, the store under `@app/store/<id>/` and the preferences under `@app/prefs/<id>/`, so two applications on one origin share
49
61
  * no session and no sign-out sweeps the other's data. The `id` is letters, digits, `.`, `_` and `-`,
50
- * and is not made of dots only.
62
+ * and is not made of dots only. Applications on one origin must ALL set an `id`: the store prefix
63
+ * without one is a prefix of every scoped store prefix, so its sign-out removes their data too.
51
64
  */
52
65
  static scoped(opts = {}) {
53
66
  const { id } = opts;
@@ -60,6 +73,8 @@ export class LocalStorageKeys {
60
73
  return {
61
74
  authPrefix: `${this.PREFIX_AUTH}${scope}`,
62
75
  storePrefix: `${this.PREFIX_STORE}${scope}`,
76
+ prefsPrefix: `${this.PREFIX_PREFS}${scope}`,
77
+ locale: `${this.PREFIX_PREFS}${scope}locale`,
63
78
  token: `${this.PREFIX_AUTH}${scope}token`,
64
79
  identity: `${this.PREFIX_AUTH}${scope}identity`,
65
80
  permission: `${this.PREFIX_AUTH}${scope}permission`,
@@ -1,11 +1,12 @@
1
- import type { AnyObject, AnyType, TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise } from '@venizia/ignis-helpers/common';
1
+ import type { TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise } from '@venizia/ignis-helpers/common';
2
2
  import type { TBuildInfoRecord } from '@venizia/ignis-helpers/core';
3
3
  import type { TClass } from '@venizia/ignis-inversion';
4
4
  import type { TExtraRequest } from '@venizia/ignis-kernel/repository';
5
+ import type { AbstractArdorApplication } from '../base/applications/abstract.js';
5
6
  import type { Environments, RequestBodyTypes, RequestCountData, RequestMethods, RequestTypes, StorageAreas } from './constants.js';
6
7
  /** A record id: a string or a number. */
7
8
  export type IdType = string | number;
8
- export type { AnyObject, AnyType, TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise, };
9
+ export type { TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise, };
9
10
  /** One of the `RequestMethods` values. */
10
11
  export type TRequestMethod = TStringConstValue<typeof RequestMethods>;
11
12
  /** One of the `Environments` values. */
@@ -30,7 +31,19 @@ export interface ISendParams {
30
31
  requestCountData?: TConstValue<typeof RequestCountData>;
31
32
  /** The list extras to ask the route for, sent in `x-request-extra`. */
32
33
  extra?: TExtraRequest;
34
+ /** Aborts the request; it then rejects with the signal's reason. */
35
+ signal?: AbortSignal;
33
36
  }
37
+ /**
38
+ * How long a request may take before it is aborted and rejects with `NETWORK_TIMEOUT_CODE`.
39
+ * `milliseconds` is a positive integer.
40
+ */
41
+ export type TRequestTimeoutOptions = {
42
+ use: false;
43
+ } | {
44
+ use: true;
45
+ milliseconds: number;
46
+ };
34
47
  /** One of the `RequestBodyTypes` values. */
35
48
  export type TRequestBodyType = TStringConstValue<typeof RequestBodyTypes>;
36
49
  /** One of the `StorageAreas` values. */
@@ -66,10 +79,23 @@ export interface IGetRequestPropsResult {
66
79
  headers?: HeadersInit;
67
80
  body?: unknown;
68
81
  }
69
- /** Keys react-admin does not know ride on its params and become filter keys; `any`, so ra-core's param interfaces stay assignable. */
82
+ /**
83
+ * Keys react-admin does not know ride on its params and become filter keys. A react-admin param type
84
+ * is an interface, which has no index signature: spread it (`{ ...params }`) where this is expected.
85
+ */
70
86
  export interface ICustomParams {
71
- params?: Record<string, AnyType>;
72
- [key: string]: AnyType;
87
+ params?: Record<string, unknown>;
88
+ [key: string]: unknown;
89
+ }
90
+ /**
91
+ * The identity `saveAuth` stores and `getUser` reads back: every field is absent when nothing is
92
+ * stored. It has no index signature, so an interface of your own that has these fields fits it.
93
+ */
94
+ export interface IAuthUser {
95
+ userId?: IdType;
96
+ username?: string;
97
+ referenceId?: IdType;
98
+ provider?: string;
73
99
  }
74
100
  /** What `login` read from the sign-in response. `roles` are names. */
75
101
  export interface ISignInSession {
@@ -80,7 +106,10 @@ export interface ISignInSession {
80
106
  };
81
107
  roles: Array<string>;
82
108
  }
83
- /** Data only: where the auth provider talks to. Behaviour is in `DefaultAuthProvider`'s protected hooks. */
109
+ /**
110
+ * Data only: where the auth provider talks to, the `use: true` half of `TAuthProviderOptions`.
111
+ * Behaviour is in `DefaultAuthProvider`'s protected hooks.
112
+ */
84
113
  export interface IAuthProviderOptions {
85
114
  paths?: {
86
115
  /**
@@ -98,6 +127,16 @@ export interface IAuthProviderOptions {
98
127
  afterLogin?: string | false;
99
128
  };
100
129
  }
130
+ /**
131
+ * What `CoreBindings.AUTH_PROVIDER_OPTIONS` holds: sign-in on with its `paths`, or off. Unbound means
132
+ * `{ use: false }`: `ApplicationProviders.resolve` then hands react-admin no auth provider, and
133
+ * every page is public.
134
+ */
135
+ export type TAuthProviderOptions = {
136
+ use: false;
137
+ } | ({
138
+ use: true;
139
+ } & IAuthProviderOptions);
101
140
  /** How a request recovers from a 401. */
102
141
  export interface IAuthRecoveryOptions {
103
142
  /**
@@ -154,6 +193,12 @@ export interface IRestDataProviderOptions extends INoAuthOptions {
154
193
  headers?: HeadersInit;
155
194
  /** Enables the refresh-and-retry after a 401. */
156
195
  authRecovery?: IAuthRecoveryOptions;
196
+ /**
197
+ * Aborts a request that has not answered within `milliseconds`; it rejects with a 504 whose
198
+ * `normalized.code` is `NETWORK_TIMEOUT_CODE`. An invalid `milliseconds` throws when the provider is built.
199
+ * @default { use: false }
200
+ */
201
+ timeout?: TRequestTimeoutOptions;
157
202
  }
158
203
  /** The token an application is signed in with. */
159
204
  export interface IAuthTokenRecord {
@@ -161,6 +206,8 @@ export interface IAuthTokenRecord {
161
206
  type?: string;
162
207
  value: string;
163
208
  provider?: string;
209
+ /** The user the token was issued to, stored by `saveAuth`; absent on a token stored without it. */
210
+ userId?: IdType;
164
211
  }
165
212
  /** What an `HttpDataSource` hook reads from the request it is asked about. */
166
213
  export interface IDataSourceRequestContext {
@@ -204,7 +251,18 @@ export interface IFeatureBase {
204
251
  * @default []
205
252
  */
206
253
  configurations?: Array<TClass<unknown>>;
207
- /** What the feature checks, in the application's vocabulary. Declared for a role editor; ARDOR enforces nothing. */
254
+ /**
255
+ * The feature's own stereotyped classes, by value, in the shape of the application's
256
+ * `artifacts()` index. Importing the feature module imports them, so discovery binds them, and
257
+ * `start()` checks each was discovered.
258
+ * @default {}
259
+ */
260
+ artifacts?: IArtifactIndex;
261
+ /**
262
+ * The permission names the feature's pages use, in the application's vocabulary: metadata for a
263
+ * role editor to list. Descriptive only, it enforces nothing; `access` on a route or a menu entry
264
+ * is what asks `canAccess`.
265
+ */
208
266
  permissions?: Array<string>;
209
267
  }
210
268
  /**
@@ -232,47 +290,35 @@ export interface IPermissionProvider {
232
290
  record?: unknown;
233
291
  }): Promise<boolean>;
234
292
  }
235
- /** The contract of an application: lifecycle hooks, registration of artifacts, and `start`. */
236
- export interface IArdorApplication {
237
- /** Binds the application instance and info, then the discovered, feature and listed classes. */
238
- preConfigure(): ValueOrPromise<void>;
239
- /** Runs after `preConfigure` in `start`. */
240
- postConfigure(): ValueOrPromise<void>;
241
- /** The application's own bindings, bound last in `preConfigure`. */
242
- bindContext(): ValueOrPromise<void>;
243
- /** Classes bound by key as singletons. */
244
- bindingList(): Record<string, TClass<unknown>>;
245
- /** The features this application mounts. */
246
- features(): Array<IFeatureBase>;
247
- /** The artifact indexes `start` checks every stereotyped class against. */
248
- artifacts(): Array<IArtifactIndex>;
249
- /** Binds `value` under `<scope>.<ClassName>` as a singleton. */
250
- injectable<T>(scope: string, value: TClass<T>, tags?: Array<string>): void;
251
- /** Binds `value` in the service namespace. */
252
- service<T>(value: TClass<T>): unknown;
253
- /** Binds `value` in the repository namespace. */
254
- repository<T>(value: TClass<T>): unknown;
255
- /** Binds `value` in the data source namespace. */
256
- dataSource<T>(value: TClass<T>): unknown;
257
- /** Binds `value` in the component namespace. */
258
- component<T>(value: TClass<T>): unknown;
259
- /** Runs the whole startup: resolves the indexes, then `preConfigure`, then `postConfigure`. */
260
- start(): ValueOrPromise<void>;
293
+ /** The options of `RolePermissionProvider`, bound under `CoreBindings.PERMISSION_PROVIDER_OPTIONS`. */
294
+ export interface IRolePermissionProviderOptions {
295
+ /**
296
+ * Role name to grant patterns. A pattern is `'<resource>.<action>'`, `'<resource>.*'`, `'*.<action>'`
297
+ * or `'*'`; anything else throws when the provider is built. A pattern has one `.`, so a resource whose
298
+ * name contains a `.` cannot be named exactly: grant it with `'*.<action>'` or `'*'`, or give it a name without one.
299
+ */
300
+ grants: Record<string, ReadonlyArray<string>>;
301
+ }
302
+ /**
303
+ * The contract of an application: lifecycle hooks, registration of artifacts, and `start`. Picked
304
+ * from `AbstractArdorApplication`, so its signatures are the class's own.
305
+ */
306
+ export interface IArdorApplication extends Pick<AbstractArdorApplication, 'preConfigure' | 'postConfigure' | 'bindContext' | 'bindingList' | 'features' | 'artifacts' | 'service' | 'repository' | 'dataSource' | 'component' | 'start'> {
261
307
  }
262
308
  type TDeepPath = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
263
309
  /** Values a path stops at: their members are not state. */
264
- type TPathLeaf = Date | RegExp | ReadonlySet<AnyType> | ReadonlyMap<AnyType, AnyType> | Promise<AnyType> | ((...args: Array<AnyType>) => AnyType);
310
+ type TPathLeaf = Date | RegExp | ReadonlySet<unknown> | ReadonlyMap<unknown, unknown> | Promise<unknown> | ((...args: never[]) => unknown);
265
311
  type TIsAny<TValue> = 0 extends 1 & TValue ? true : false;
266
312
  /**
267
313
  * The dotted paths of an object type, to `DeepLevel` levels (10 by default). An array, a `Date`, a
268
314
  * `Set`, a `Map`, a `Promise`, a function and an `any` field are leaves: the path stops at them.
269
315
  */
270
- export type TPaths<T, DeepLevel extends number = 10> = DeepLevel extends 0 ? never : T extends Array<AnyType> | TPathLeaf ? never : T extends object ? {
271
- [K in keyof T]-?: K extends string | number ? TIsAny<T[K]> extends true ? `${K}` : NonNullable<T[K]> extends Array<AnyType> | TPathLeaf ? `${K}` : NonNullable<T[K]> extends object ? `${K}` | `${K}.${TPaths<NonNullable<T[K]>, TDeepPath[DeepLevel]>}` : `${K}` : never;
316
+ export type TPaths<T, DeepLevel extends number = 10> = DeepLevel extends 0 ? never : T extends Array<unknown> | TPathLeaf ? never : T extends object ? {
317
+ [K in keyof T]-?: K extends string | number ? TIsAny<T[K]> extends true ? `${K}` : NonNullable<T[K]> extends Array<unknown> | TPathLeaf ? `${K}` : NonNullable<T[K]> extends object ? `${K}` | `${K}.${TPaths<NonNullable<T[K]>, TDeepPath[DeepLevel]>}` : `${K}` : never;
272
318
  }[keyof T] : never;
273
319
  /** The dotted paths of an object type, to `DeepLevel` levels (10 by default); unlike `TPaths`, only the paths down to a leaf value. */
274
320
  export type TFullPaths<T, DeepLevel extends number = 10> = DeepLevel extends never ? never : T extends Array<infer U> ? TFullPaths<U> : T extends object ? {
275
- [K in keyof T]-?: K extends string | number ? T[K] extends Array<any> | object ? `${K}.${TFullPaths<T[K], TDeepPath[DeepLevel]>}` : `${K}` : never;
321
+ [K in keyof T]-?: K extends string | number ? T[K] extends object ? `${K}.${TFullPaths<T[K], TDeepPath[DeepLevel]>}` : `${K}` : never;
276
322
  }[keyof T] : never;
277
323
  /** What an application is: bound under `CoreBindings.APPLICATION_INFO`, and the name a tracing id starts with. */
278
324
  export interface IApplicationInfo {