@venizia/ardor-kernel 0.4.8-5 → 0.4.8-7

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,9 +1,15 @@
1
- import { type AnyType, type IAuthTokenRecord, type IdType } from '../../common/index.js';
1
+ import { type AnyType, type IApplicationInfo, type IAuthTokenRecord, type IdType, type IScopedKeys } from '../../common/index.js';
2
2
  import { BaseService } from './base.js';
3
- /** Keeps the signed-in session (token, identity, roles) in `localStorage`; everything under `LocalStorageKeys.PREFIX_AUTH`. */
3
+ /**
4
+ * Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
5
+ * `keys.authPrefix`: `LocalStorageKeys.PREFIX_AUTH`, or `@app/auth/<id>/` when the application has an `id`.
6
+ */
4
7
  export declare class DefaultAuthService extends BaseService {
5
8
  private readonly listeners;
6
- constructor();
9
+ /** The keys of this application's session and store: the application's `id` scopes them. */
10
+ readonly keys: IScopedKeys;
11
+ /** A subclass with its own constructor passes `info` on to `super(info)`; otherwise its keys are the unscoped ones. */
12
+ constructor(info?: IApplicationInfo);
7
13
  /** `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes. */
8
14
  subscribe(opts: {
9
15
  listener: () => void;
@@ -18,7 +24,11 @@ export declare class DefaultAuthService extends BaseService {
18
24
  private parseStored;
19
25
  /** The stored identity; `{}` when nothing usable is stored, also outside a browser. */
20
26
  getUser(): AnyType;
21
- /** The stored roles; empty when nothing usable is stored, also outside a browser. */
27
+ /**
28
+ * The stored roles; empty when nothing usable is stored, also outside a browser. They are data in
29
+ * the browser, so whoever controls the browser can change them: use them to show or hide interface,
30
+ * never to decide what a user may do. The backend must check every permission on every request.
31
+ */
22
32
  getRoles(): Set<string>;
23
33
  /** The stored token, `null` for every visitor who has not signed in. */
24
34
  getAuth(): IAuthTokenRecord | null;
@@ -44,7 +54,7 @@ export declare class DefaultAuthService extends BaseService {
44
54
  */
45
55
  roles?: ReadonlyArray<string>;
46
56
  }): void;
47
- /** Removes every key under `LocalStorageKeys.PREFIX_AUTH`, then notifies the subscribers; does nothing outside a browser. */
57
+ /** Removes every key under `keys.authPrefix`, then notifies the subscribers; does nothing outside a browser. */
48
58
  cleanUp(): void;
49
59
  }
50
60
  //# sourceMappingURL=auth.d.ts.map
@@ -1,12 +1,30 @@
1
- import { getError } from '@venizia/ignis-inversion';
2
- import { LocalStorageKeys } from '../../common/index.js';
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ 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;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var DefaultAuthService_1;
14
+ import { getError, inject } from '@venizia/ignis-inversion';
15
+ import { CoreBindings, LocalStorageKeys, } from '../../common/index.js';
3
16
  import { AuthTokenStore } from '../../helpers/index.js';
4
17
  import { BaseService } from './base.js';
5
- /** Keeps the signed-in session (token, identity, roles) in `localStorage`; everything under `LocalStorageKeys.PREFIX_AUTH`. */
6
- export class DefaultAuthService extends BaseService {
7
- constructor() {
8
- super({ scope: DefaultAuthService.name });
18
+ /**
19
+ * Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
20
+ * `keys.authPrefix`: `LocalStorageKeys.PREFIX_AUTH`, or `@app/auth/<id>/` when the application has an `id`.
21
+ */
22
+ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends BaseService {
23
+ /** A subclass with its own constructor passes `info` on to `super(info)`; otherwise its keys are the unscoped ones. */
24
+ constructor(info) {
25
+ super({ scope: DefaultAuthService_1.name });
9
26
  this.listeners = new Set();
27
+ this.keys = LocalStorageKeys.scoped({ id: info?.id });
10
28
  }
11
29
  /** `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes. */
12
30
  subscribe(opts) {
@@ -49,16 +67,20 @@ export class DefaultAuthService extends BaseService {
49
67
  /** The stored identity; `{}` when nothing usable is stored, also outside a browser. */
50
68
  getUser() {
51
69
  const identity = this.parseStored({
52
- key: LocalStorageKeys.KEY_AUTH_IDENTITY,
70
+ key: this.keys.identity,
53
71
  method: 'getUser',
54
72
  });
55
73
  const isRecord = typeof identity === 'object' && identity !== null && !Array.isArray(identity);
56
74
  return isRecord ? identity : {};
57
75
  }
58
- /** The stored roles; empty when nothing usable is stored, also outside a browser. */
76
+ /**
77
+ * The stored roles; empty when nothing usable is stored, also outside a browser. They are data in
78
+ * the browser, so whoever controls the browser can change them: use them to show or hide interface,
79
+ * never to decide what a user may do. The backend must check every permission on every request.
80
+ */
59
81
  getRoles() {
60
82
  const stored = this.parseStored({
61
- key: LocalStorageKeys.KEY_AUTH_PERMISSION,
83
+ key: this.keys.permission,
62
84
  method: 'getRoles',
63
85
  });
64
86
  const roles = Array.isArray(stored) ? stored.filter((role) => typeof role === 'string') : [];
@@ -66,7 +88,7 @@ export class DefaultAuthService extends BaseService {
66
88
  }
67
89
  /** The stored token, `null` for every visitor who has not signed in. */
68
90
  getAuth() {
69
- return AuthTokenStore.read() ?? null;
91
+ return AuthTokenStore.read({ key: this.keys.token }) ?? null;
70
92
  }
71
93
  /**
72
94
  * Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
@@ -80,25 +102,30 @@ export class DefaultAuthService extends BaseService {
80
102
  });
81
103
  }
82
104
  const { token, userId, username = '', provider = '', referenceId = '', roles } = opts;
83
- AuthTokenStore.write({ token, provider });
84
- localStorage.setItem(LocalStorageKeys.KEY_AUTH_IDENTITY, JSON.stringify({ userId, username, referenceId, provider }));
105
+ AuthTokenStore.write({ token, provider, key: this.keys.token });
106
+ localStorage.setItem(this.keys.identity, JSON.stringify({ userId, username, referenceId, provider }));
85
107
  if (roles) {
86
- localStorage.setItem(LocalStorageKeys.KEY_AUTH_PERMISSION, JSON.stringify(roles));
108
+ localStorage.setItem(this.keys.permission, JSON.stringify(roles));
87
109
  }
88
110
  this.notify();
89
111
  }
90
- /** Removes every key under `LocalStorageKeys.PREFIX_AUTH`, then notifies the subscribers; does nothing outside a browser. */
112
+ /** Removes every key under `keys.authPrefix`, then notifies the subscribers; does nothing outside a browser. */
91
113
  cleanUp() {
92
114
  if (typeof localStorage === 'undefined') {
93
115
  return;
94
116
  }
95
117
  Object.keys(localStorage).forEach((key) => {
96
- if (!key.startsWith(LocalStorageKeys.PREFIX_AUTH)) {
118
+ if (!key.startsWith(this.keys.authPrefix)) {
97
119
  return;
98
120
  }
99
121
  localStorage.removeItem(key);
100
122
  });
101
123
  this.notify();
102
124
  }
103
- }
125
+ };
126
+ DefaultAuthService = DefaultAuthService_1 = __decorate([
127
+ __param(0, inject({ key: CoreBindings.APPLICATION_INFO, isOptional: true })),
128
+ __metadata("design:paramtypes", [Object])
129
+ ], DefaultAuthService);
130
+ export { DefaultAuthService };
104
131
  //# sourceMappingURL=auth.js.map
@@ -39,10 +39,24 @@ export declare class DefaultNetworkRequestService extends BaseService {
39
39
  authService?: DefaultAuthService;
40
40
  });
41
41
  /**
42
- * The stored token (`AuthTokenStore.read`), `undefined` outside a browser. The default of
43
- * `resolveAuthToken`, and what to hand an `HttpDataSource` as its `authTokenResolver`.
42
+ * The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
43
+ * application with no `id`. With an application `id` the session is under other keys: use
44
+ * `createAuthTokenReader({ id })`, the `HttpDataSource` `getDataSourceAuth()` of the data provider, or `authService.getAuth`.
44
45
  */
45
46
  static readAuthTokenFromStorage(): IAuthTokenRecord | undefined;
47
+ /**
48
+ * A reader of the stored token of the application with this `id` (`IApplicationInfo.id`): the same
49
+ * key `DefaultAuthService.getAuth` reads (`LocalStorageKeys.scoped({ id }).token`). Without an `id` it
50
+ * is `readAuthTokenFromStorage`. Throws for an invalid `id`, when it is created.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * super({ baseUrl: '/api', authTokenResolver: DefaultNetworkRequestService.createAuthTokenReader({ id: 'shop' }) });
55
+ * ```
56
+ */
57
+ static createAuthTokenReader(opts?: {
58
+ id?: string;
59
+ }): () => IAuthTokenRecord | undefined;
46
60
  /**
47
61
  * The token this service sends. The one way to supply a token: override it to read another
48
62
  * store, or to hold the token in memory.
@@ -59,9 +73,12 @@ export declare class DefaultNetworkRequestService extends BaseService {
59
73
  }): boolean;
60
74
  /**
61
75
  * Refreshes the session after a 401. `true`: refreshed, the request is retried; `false`: this
62
- * service has no refresh; a throw: the refresh failed and `onAuthFailure` runs. The default posts
63
- * to `authRecovery.refreshTokenPath` with no body and saves the new token through `authService`,
64
- * keeping the stored identity and roles; with no path or no `authService` it answers `false`.
76
+ * service has no refresh, or the session changed while the request was in flight (another user
77
+ * signed in, the user signed out, or another tab refreshed): the new token is not saved, and the
78
+ * failure of a refresh made for a session that is gone is not reported; a throw: the refresh
79
+ * failed and `onAuthFailure` runs. The default posts to `authRecovery.refreshTokenPath` with no
80
+ * body and saves the new token through `authService`, keeping the stored identity and roles;
81
+ * with no path or no `authService` it answers `false`.
65
82
  */
66
83
  protected refreshToken(): Promise<boolean>;
67
84
  /**
@@ -123,6 +140,12 @@ export declare class DefaultNetworkRequestService extends BaseService {
123
140
  getRequestHeader(opts: {
124
141
  resource: string;
125
142
  }): Record<string, string>;
143
+ /**
144
+ * Whether the request stays where `baseUrl` points: no entry of `paths` carries a tab, a line break,
145
+ * a backslash or a dot segment (also written `%2E`), and the URL built from
146
+ * them, resolved the way a browser does, has the origin of the base and a path under it.
147
+ */
148
+ private static isUnderBase;
126
149
  /** The body as it is sent and the content type to send it under. Override to encode another way. */
127
150
  protected encodeBody(opts: {
128
151
  bodyType?: string;
@@ -2,7 +2,7 @@ import { getError } from '@venizia/ignis-inversion';
2
2
  import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
3
3
  import { UuidV4Generator } from '@venizia/ignis-helpers/uuid';
4
4
  import { HttpExtraRequest } from '@venizia/ignis-kernel/repository';
5
- import { App, HeaderConstants, RequestChannel, RequestCountData, RequestMethods, RequestTypes, } from '../../common/index.js';
5
+ import { App, HeaderConstants, LocalStorageKeys, RequestChannel, RequestCountData, RequestMethods, RequestTypes, } from '../../common/index.js';
6
6
  import { AuthRecovery, AuthTokenStore, NetworkHeaders, RequestBodyEncoder, ResponseReader, } from '../../helpers/index.js';
7
7
  import { BaseService } from './base.js';
8
8
  /**
@@ -33,19 +33,37 @@ export class DefaultNetworkRequestService extends BaseService {
33
33
  });
34
34
  }
35
35
  /**
36
- * The stored token (`AuthTokenStore.read`), `undefined` outside a browser. The default of
37
- * `resolveAuthToken`, and what to hand an `HttpDataSource` as its `authTokenResolver`.
36
+ * The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
37
+ * application with no `id`. With an application `id` the session is under other keys: use
38
+ * `createAuthTokenReader({ id })`, the `HttpDataSource` `getDataSourceAuth()` of the data provider, or `authService.getAuth`.
38
39
  */
39
40
  static readAuthTokenFromStorage() {
40
41
  return AuthTokenStore.read();
41
42
  }
43
+ /**
44
+ * A reader of the stored token of the application with this `id` (`IApplicationInfo.id`): the same
45
+ * key `DefaultAuthService.getAuth` reads (`LocalStorageKeys.scoped({ id }).token`). Without an `id` it
46
+ * is `readAuthTokenFromStorage`. Throws for an invalid `id`, when it is created.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * super({ baseUrl: '/api', authTokenResolver: DefaultNetworkRequestService.createAuthTokenReader({ id: 'shop' }) });
51
+ * ```
52
+ */
53
+ static createAuthTokenReader(opts = {}) {
54
+ const { token: key } = LocalStorageKeys.scoped({ id: opts.id });
55
+ return () => AuthTokenStore.read({ key });
56
+ }
42
57
  // --- Hooks -----------------------------------------------------------------------------------
43
58
  /**
44
59
  * The token this service sends. The one way to supply a token: override it to read another
45
60
  * store, or to hold the token in memory.
46
61
  */
47
62
  resolveAuthToken() {
48
- return DefaultNetworkRequestService.readAuthTokenFromStorage();
63
+ // The auth service knows where this application's session is kept (its `id` scopes the keys).
64
+ return this.authService
65
+ ? (this.authService.getAuth() ?? undefined)
66
+ : DefaultNetworkRequestService.readAuthTokenFromStorage();
49
67
  }
50
68
  /**
51
69
  * Whether a request goes without a token: its `resource` is in `noAuthPaths`, or the resource, or
@@ -73,27 +91,63 @@ export class DefaultNetworkRequestService extends BaseService {
73
91
  }
74
92
  /**
75
93
  * Refreshes the session after a 401. `true`: refreshed, the request is retried; `false`: this
76
- * service has no refresh; a throw: the refresh failed and `onAuthFailure` runs. The default posts
77
- * to `authRecovery.refreshTokenPath` with no body and saves the new token through `authService`,
78
- * keeping the stored identity and roles; with no path or no `authService` it answers `false`.
94
+ * service has no refresh, or the session changed while the request was in flight (another user
95
+ * signed in, the user signed out, or another tab refreshed): the new token is not saved, and the
96
+ * failure of a refresh made for a session that is gone is not reported; a throw: the refresh
97
+ * failed and `onAuthFailure` runs. The default posts to `authRecovery.refreshTokenPath` with no
98
+ * body and saves the new token through `authService`, keeping the stored identity and roles;
99
+ * with no path or no `authService` it answers `false`.
79
100
  */
80
101
  async refreshToken() {
81
102
  const path = this.authRecovery?.refreshTokenPath;
82
- if (!path || !this.authService) {
103
+ const { authService } = this;
104
+ if (!path || !authService) {
83
105
  return false;
84
106
  }
85
- const response = await this.doRequest({
86
- paths: [path],
87
- method: RequestMethods.POST,
88
- type: RequestTypes.SEND,
89
- headers: this.getRequestHeader({ resource: path }),
107
+ // The session this refresh is for: the answer belongs to it and to no other.
108
+ const readSession = () => ({
109
+ userId: `${authService.getUser().userId}`,
110
+ token: authService.getAuth()?.value,
90
111
  });
91
- const user = this.authService.getUser();
112
+ const startedFor = readSession();
113
+ // `false`: another user, or none, is signed in now. `true`: the same user holds another token
114
+ // now (another tab refreshed, or a new sign-in), which the retry uses. `undefined`: unchanged.
115
+ const readChange = () => {
116
+ const now = readSession();
117
+ if (now.userId !== startedFor.userId) {
118
+ return false;
119
+ }
120
+ return now.token === startedFor.token ? undefined : true;
121
+ };
122
+ let response;
123
+ try {
124
+ const result = await this.doRequest({
125
+ paths: [path],
126
+ method: RequestMethods.POST,
127
+ type: RequestTypes.SEND,
128
+ headers: this.getRequestHeader({ resource: path }),
129
+ });
130
+ response = result;
131
+ }
132
+ catch (error) {
133
+ const change = readChange();
134
+ if (change === undefined) {
135
+ throw error;
136
+ }
137
+ return change;
138
+ }
139
+ const user = authService.getUser();
140
+ const change = readChange();
92
141
  // Signed out while the request was in flight: saving the token would start a session with no user.
93
142
  if (user.userId === undefined) {
94
143
  return false;
95
144
  }
96
- this.authService.saveAuth({
145
+ // The session moved on: this answer is for the one that asked, so it is not saved.
146
+ if (change !== undefined) {
147
+ this.logger.warn('[refreshToken] The session changed while the refresh was in flight, its answer is dropped');
148
+ return change;
149
+ }
150
+ authService.saveAuth({
97
151
  userId: user.userId,
98
152
  username: user.username,
99
153
  referenceId: user.referenceId,
@@ -261,6 +315,30 @@ export class DefaultNetworkRequestService extends BaseService {
261
315
  [HeaderConstants.AUTHORIZATION]: authHeader.token,
262
316
  };
263
317
  }
318
+ /**
319
+ * Whether the request stays where `baseUrl` points: no entry of `paths` carries a tab, a line break,
320
+ * a backslash or a dot segment (also written `%2E`), and the URL built from
321
+ * them, resolved the way a browser does, has the origin of the base and a path under it.
322
+ */
323
+ static isUnderBase(opts) {
324
+ const { baseUrl, paths, url } = opts;
325
+ // The joined path, so a dot segment is found whichever entry holds it.
326
+ if (/[\\\t\n\r]|(^|\/)(\.|%2e){1,2}(\/|$)/i.test(paths.join('/'))) {
327
+ return false;
328
+ }
329
+ try {
330
+ const origin = 'http://base.invalid';
331
+ const base = new URL(baseUrl, origin);
332
+ const target = new URL(url, origin);
333
+ const prefix = base.pathname.replace(/\/+$/, '');
334
+ return (target.origin === base.origin &&
335
+ (target.pathname === prefix || target.pathname.startsWith(`${prefix}/`)));
336
+ // eslint-disable-next-line venizia/no-silent-catch -- a URL that does not parse is the answer: the request is refused
337
+ }
338
+ catch {
339
+ return false;
340
+ }
341
+ }
264
342
  /** The body as it is sent and the content type to send it under. Override to encode another way. */
265
343
  encodeBody(opts) {
266
344
  return RequestBodyEncoder.encode(opts);
@@ -308,6 +386,9 @@ export class DefaultNetworkRequestService extends BaseService {
308
386
  });
309
387
  }
310
388
  const url = this.networkRequest.getRequestUrl({ baseUrl, paths });
389
+ if (!DefaultNetworkRequestService.isUnderBase({ baseUrl, paths, url })) {
390
+ throw getError({ message: '[doRequest] Invalid path to send request!' });
391
+ }
311
392
  const sendOnce = (sendHeaders) => {
312
393
  return this.networkRequest.getNetworkService().send({
313
394
  url,
@@ -317,8 +398,12 @@ export class DefaultNetworkRequestService extends BaseService {
317
398
  headers: sendHeaders,
318
399
  }, this.logger);
319
400
  };
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}`;
320
403
  let fetched = await sendOnce(headers);
321
- if (fetched.status === 401 && this.recovery.canRecover({ paths })) {
404
+ if (fetched.status === 401 &&
405
+ `${this.authService?.getUser().userId}` === sentBy &&
406
+ this.recovery.canRecover({ paths })) {
322
407
  const isRefreshed = await this.refresh();
323
408
  if (isRefreshed) {
324
409
  const authHeader = this.getRequestAuthorizationHeader();
@@ -23,11 +23,21 @@ export declare class CoreBindings {
23
23
  /** An `IPermissionProvider`, bound by the application; unbound means every check passes. */
24
24
  static readonly PERMISSION_PROVIDER = "@app/application/permission/provider";
25
25
  }
26
+ /** The session keys and the store prefix of one application, from `LocalStorageKeys.scoped`. */
27
+ export interface IScopedKeys {
28
+ /** Everything under it is this application's session: `DefaultAuthService.cleanUp` removes it all. */
29
+ authPrefix: string;
30
+ /** The data of this application's signed-in user; sign-out removes everything under it. */
31
+ storePrefix: string;
32
+ token: string;
33
+ identity: string;
34
+ permission: string;
35
+ }
26
36
  /** The `localStorage` keys the kernel owns. */
27
37
  export declare class LocalStorageKeys {
28
38
  /** Everything under this prefix is the session: `DefaultAuthService.cleanUp` removes it all. */
29
39
  static readonly PREFIX_AUTH = "@app/auth/";
30
- /** The namespace `BrowserStorage` recommends for the keys of an application. */
40
+ /** The data of the signed-in user: sign-out removes everything under it. Preferences that outlive a sign-out go under `@app/prefs/`. */
31
41
  static readonly PREFIX_STORE = "@app/store/";
32
42
  /** The stored `IAuthTokenRecord`, as JSON. */
33
43
  static readonly KEY_AUTH_TOKEN = "@app/auth/token";
@@ -37,6 +47,16 @@ export declare class LocalStorageKeys {
37
47
  static readonly KEY_AUTH_PERMISSION = "@app/auth/permission";
38
48
  /** The three session keys. */
39
49
  static readonly SCHEME_SET: Set<string>;
50
+ /**
51
+ * The keys of one application. With no `id` they are the constants above, so an application that is
52
+ * 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
54
+ * 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.
56
+ */
57
+ static scoped(opts?: {
58
+ id?: string;
59
+ }): IScopedKeys;
40
60
  /** Whether `value` is a session key in `SCHEME_SET`. */
41
61
  static isValid(value: string): boolean;
42
62
  }
@@ -1,3 +1,4 @@
1
+ import { getError } from '@venizia/ignis-inversion';
1
2
  /** The container keys the kernel binds and reads. */
2
3
  export class CoreBindings {
3
4
  /** The application itself, bound by `preConfigure`. */
@@ -27,7 +28,7 @@ export class CoreBindings {
27
28
  export class LocalStorageKeys {
28
29
  /** Everything under this prefix is the session: `DefaultAuthService.cleanUp` removes it all. */
29
30
  static { this.PREFIX_AUTH = '@app/auth/'; }
30
- /** The namespace `BrowserStorage` recommends for the keys of an application. */
31
+ /** The data of the signed-in user: sign-out removes everything under it. Preferences that outlive a sign-out go under `@app/prefs/`. */
31
32
  static { this.PREFIX_STORE = '@app/store/'; }
32
33
  /** The stored `IAuthTokenRecord`, as JSON. */
33
34
  static { this.KEY_AUTH_TOKEN = '@app/auth/token'; }
@@ -41,6 +42,29 @@ export class LocalStorageKeys {
41
42
  this.KEY_AUTH_IDENTITY,
42
43
  this.KEY_AUTH_PERMISSION,
43
44
  ]); }
45
+ /**
46
+ * The keys of one application. With no `id` they are the constants above, so an application that is
47
+ * 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
49
+ * 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.
51
+ */
52
+ static scoped(opts = {}) {
53
+ const { id } = opts;
54
+ if (id !== undefined && !(typeof id === 'string' && /^(?!\.+$)[A-Za-z0-9._-]+$/.test(id))) {
55
+ throw getError({
56
+ message: "[LocalStorageKeys.scoped] IApplicationInfo.id is letters, digits, '.', '_' and '-', and not dots only",
57
+ });
58
+ }
59
+ const scope = id === undefined ? '' : `${id}/`;
60
+ return {
61
+ authPrefix: `${this.PREFIX_AUTH}${scope}`,
62
+ storePrefix: `${this.PREFIX_STORE}${scope}`,
63
+ token: `${this.PREFIX_AUTH}${scope}token`,
64
+ identity: `${this.PREFIX_AUTH}${scope}identity`,
65
+ permission: `${this.PREFIX_AUTH}${scope}permission`,
66
+ };
67
+ }
44
68
  /** Whether `value` is a session key in `SCHEME_SET`. */
45
69
  static isValid(value) {
46
70
  return this.SCHEME_SET.has(value);
@@ -91,10 +91,11 @@ export interface IAuthProviderOptions {
91
91
  /** Where `checkAuth` validates the stored token. Default: not called; the stored token is enough. */
92
92
  checkAuth?: string;
93
93
  /**
94
- * Where the admin goes once `login` resolves.
94
+ * Where the admin goes once `login` resolves. `false`: nowhere, `login` resolves with
95
+ * `redirectTo: false` and the page stays (a guest or kiosk shell).
95
96
  * @default '/'
96
97
  */
97
- afterLogin?: string;
98
+ afterLogin?: string | false;
98
99
  };
99
100
  }
100
101
  /** How a request recovers from a 401. */
@@ -219,7 +220,11 @@ export interface IArtifactIndex {
219
220
  services?: ReadonlyArray<TClass<unknown>>;
220
221
  controllers?: ReadonlyArray<TClass<unknown>>;
221
222
  }
222
- /** Answers whether the current actor may act on a resource. Bound by the application under `CoreBindings.PERMISSION_PROVIDER`. */
223
+ /**
224
+ * Answers whether the current actor may act on a resource. Bound by the application under
225
+ * `CoreBindings.PERMISSION_PROVIDER`. It decides what the interface shows, not what a user is allowed
226
+ * to do: the backend must check every permission on every request.
227
+ */
223
228
  export interface IPermissionProvider {
224
229
  canAccess(opts: {
225
230
  resource: string;
@@ -274,6 +279,12 @@ export interface IApplicationInfo {
274
279
  name: string;
275
280
  version: string;
276
281
  description: string;
282
+ /**
283
+ * Scopes the session and store keys in browser storage to this application (`LocalStorageKeys.scoped`),
284
+ * so two applications on one origin do not share a session. Give every application of an origin an id.
285
+ * Without one the keys are the unscoped ones.
286
+ */
287
+ id?: string;
277
288
  author?: {
278
289
  name: string;
279
290
  email: string;
@@ -2,15 +2,18 @@ import { type IAuthTokenRecord } from '../common/index.js';
2
2
  /** The one place that reads and writes the stored auth token, with the browser guard. */
3
3
  export declare class AuthTokenStore {
4
4
  private static readonly logger;
5
- /** The stored token, or `undefined` when none is stored, it is unusable, or there is no `localStorage`. */
6
- static read(): IAuthTokenRecord | undefined;
7
- /** Stores the token with its `provider` under `LocalStorageKeys.KEY_AUTH_TOKEN`. Throws when `localStorage` is not available. */
5
+ /** The stored token (under `key`, `LocalStorageKeys.KEY_AUTH_TOKEN` by default), or `undefined` when none is stored, it is unusable, or there is no `localStorage`. */
6
+ static read(opts?: {
7
+ key?: string;
8
+ }): IAuthTokenRecord | undefined;
9
+ /** Stores the token with its `provider` under `key` (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available. */
8
10
  static write(opts: {
9
11
  token: {
10
12
  value: string;
11
13
  type: string;
12
14
  };
13
15
  provider: string;
16
+ key?: string;
14
17
  }): void;
15
18
  }
16
19
  //# sourceMappingURL=auth-token-store.d.ts.map
@@ -4,12 +4,12 @@ import { LocalStorageKeys } from '../common/index.js';
4
4
  /** The one place that reads and writes the stored auth token, with the browser guard. */
5
5
  export class AuthTokenStore {
6
6
  static { this.logger = LoggerFactory.getLogger(['AuthTokenStore']); }
7
- /** The stored token, or `undefined` when none is stored, it is unusable, or there is no `localStorage`. */
8
- static read() {
7
+ /** The stored token (under `key`, `LocalStorageKeys.KEY_AUTH_TOKEN` by default), or `undefined` when none is stored, it is unusable, or there is no `localStorage`. */
8
+ static read(opts = {}) {
9
9
  if (typeof localStorage === 'undefined') {
10
10
  return undefined;
11
11
  }
12
- const stored = localStorage.getItem(LocalStorageKeys.KEY_AUTH_TOKEN);
12
+ const stored = localStorage.getItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN);
13
13
  if (!stored?.length) {
14
14
  return undefined;
15
15
  }
@@ -23,14 +23,14 @@ export class AuthTokenStore {
23
23
  return undefined;
24
24
  }
25
25
  }
26
- /** Stores the token with its `provider` under `LocalStorageKeys.KEY_AUTH_TOKEN`. Throws when `localStorage` is not available. */
26
+ /** Stores the token with its `provider` under `key` (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available. */
27
27
  static write(opts) {
28
28
  // Not a silent skip: a sign-in that is not kept would look like it worked.
29
29
  if (typeof localStorage === 'undefined') {
30
30
  throw getError({ message: '[write] localStorage is not available' });
31
31
  }
32
32
  const { token, provider } = opts;
33
- localStorage.setItem(LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider })));
33
+ localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider })));
34
34
  }
35
35
  }
36
36
  //# sourceMappingURL=auth-token-store.js.map
package/dist/testing.d.ts CHANGED
@@ -28,12 +28,20 @@ export declare class FakeResizeObserver implements ResizeObserver {
28
28
  unobserve(target: Element): void;
29
29
  disconnect(): void;
30
30
  }
31
- /** An `IntersectionObserver` whose `observe()` records the element; `flush` delivers one entry to the observers of an element. */
31
+ /**
32
+ * An `IntersectionObserver` whose `observe()` records the element and reports nothing by itself: `settle`
33
+ * delivers the first report of a browser, `flush` delivers an entry to the observers of an element.
34
+ */
32
35
  export declare class FakeIntersectionObserver implements IntersectionObserver {
36
+ #private;
33
37
  readonly callback: IntersectionObserverCallback;
34
38
  readonly options?: IntersectionObserverInit | undefined;
35
39
  /** The observers created since the last `install`, in creation order. */
36
40
  static all: Array<FakeIntersectionObserver>;
41
+ /** How many observers were created since the last `install`. */
42
+ static get created(): number;
43
+ /** The observers created since the last `install` that are not disconnected. */
44
+ static live(): Array<FakeIntersectionObserver>;
37
45
  readonly root: null;
38
46
  readonly rootMargin = "";
39
47
  readonly scrollMargin = "";
@@ -50,6 +58,15 @@ export declare class FakeIntersectionObserver implements IntersectionObserver {
50
58
  isIntersecting: boolean;
51
59
  ratio?: number;
52
60
  }): void;
61
+ /**
62
+ * The first report of a browser: every live observer is called, once per target it has not reported
63
+ * on yet, with the entry for `isIntersecting` (not intersecting by default). A target already
64
+ * reported on, by `settle` or `flush`, is skipped.
65
+ */
66
+ static settle(opts?: {
67
+ isIntersecting?: boolean;
68
+ ratio?: number;
69
+ }): void;
53
70
  observe(target: Element): void;
54
71
  unobserve(target: Element): void;
55
72
  disconnect(): void;
@@ -57,11 +74,16 @@ export declare class FakeIntersectionObserver implements IntersectionObserver {
57
74
  }
58
75
  /** The `MediaQueryList` that `matchMedia` answers under `FakeMatchMedia.install`: one per query, `false` until `set`. */
59
76
  export declare class FakeMatchMedia extends EventTarget {
77
+ #private;
60
78
  readonly media: string;
61
79
  matches: boolean;
62
80
  /** The queries asked since the last `install`, with the list each one got. */
63
81
  static readonly queries: Map<string, FakeMatchMedia>;
64
82
  constructor(media: string, matches?: boolean);
83
+ /** How many distinct `change` listeners are subscribed now, to assert a subscribe and an unsubscribe. */
84
+ get listenerCount(): number;
85
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void;
86
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;
65
87
  /** Replaces `window.matchMedia` with a function that answers the list of the query. */
66
88
  static install(): () => void;
67
89
  /** The list of `query`, made on the first ask. */
@@ -74,9 +96,9 @@ export declare class FakeMatchMedia extends EventTarget {
74
96
  }
75
97
  /**
76
98
  * A `Storage` that behaves like the real one: stored keys are own properties, so `Object.keys` lists
77
- * them. Set `failReads` for a blocked storage (reads throw `SecurityError`) and `failWrites` for a
78
- * full or blocked one (`setItem` and `clear` throw `QuotaExceededError`, `removeItem` throws
79
- * `SecurityError`); both can change at any time. A key named like a member of the fake (`getItem`,
99
+ * them. Each way to fail has its own switch, and each can change at any time: `failReads` makes
100
+ * `getItem` throw `SecurityError`, `failListing` makes `key` and `length` throw it, `failWrites` makes
101
+ * `setItem` and `clear` throw `QuotaExceededError` and `removeItem` throw `SecurityError`. A key named like a member of the fake (`getItem`,
80
102
  * `length`, `writes`, `failWrites` and the rest) would shadow it, so `setItem` throws a `TypeError`
81
103
  * for it, where the real `Storage` accepts it.
82
104
  */
@@ -85,6 +107,8 @@ export declare class FakeStorage implements Storage {
85
107
  [name: string]: unknown;
86
108
  get failReads(): boolean;
87
109
  set failReads(value: boolean);
110
+ get failListing(): boolean;
111
+ set failListing(value: boolean);
88
112
  get failWrites(): boolean;
89
113
  set failWrites(value: boolean);
90
114
  /** The values passed to `setItem` that the storage accepted, in order. */
package/dist/testing.js CHANGED
@@ -3,17 +3,36 @@
3
3
  * whose own do nothing, such as happy-dom. Each fake puts itself on the global with `install`,
4
4
  * which returns the function that puts the previous value back.
5
5
  */
6
- /** Defines `name` on `target` and answers the function that puts the previous own property back. */
6
+ /**
7
+ * Defines `name` on the global and, where `window` is another object (happy-dom), on `window` too, so
8
+ * code that reads `window.matchMedia` or `window.localStorage` meets the fake. `at` names a member of
9
+ * them instead (`navigator`). Answers the function that puts the previous properties back.
10
+ */
7
11
  const swap = (opts) => {
8
- const { target, name, value } = opts;
9
- const previous = Object.getOwnPropertyDescriptor(target, name);
10
- Object.defineProperty(target, name, { value, configurable: true, writable: true });
11
- return () => {
12
- if (previous) {
13
- Object.defineProperty(target, name, previous);
12
+ const { name, value, at } = opts;
13
+ const roots = [globalThis, Reflect.get(globalThis, 'window')];
14
+ const targets = new Set();
15
+ for (const root of roots) {
16
+ const target = at && root ? Reflect.get(Object(root), at) : root;
17
+ if (typeof target === 'object' && target !== null) {
18
+ targets.add(target);
14
19
  }
15
- else {
16
- Reflect.deleteProperty(target, name);
20
+ }
21
+ const restores = [...targets].map((target) => {
22
+ const previous = Object.getOwnPropertyDescriptor(target, name);
23
+ Object.defineProperty(target, name, { value, configurable: true, writable: true });
24
+ return () => {
25
+ if (previous) {
26
+ Object.defineProperty(target, name, previous);
27
+ }
28
+ else {
29
+ Reflect.deleteProperty(target, name);
30
+ }
31
+ };
32
+ });
33
+ return () => {
34
+ for (const restore of restores) {
35
+ restore();
17
36
  }
18
37
  };
19
38
  };
@@ -46,7 +65,7 @@ export class FakeResizeObserver {
46
65
  /** Replaces `globalThis.ResizeObserver` with the fake and forgets the earlier observers. */
47
66
  static install() {
48
67
  FakeResizeObserver.all = [];
49
- return swap({ target: globalThis, name: 'ResizeObserver', value: FakeResizeObserver });
68
+ return swap({ name: 'ResizeObserver', value: FakeResizeObserver });
50
69
  }
51
70
  /** Calls every observer of `element` with one entry of that size, for the content and the border box alike. */
52
71
  static flush(opts) {
@@ -81,13 +100,41 @@ export class FakeResizeObserver {
81
100
  this.targets.length = 0;
82
101
  }
83
102
  }
84
- /** An `IntersectionObserver` whose `observe()` records the element; `flush` delivers one entry to the observers of an element. */
103
+ const intersectionEntryOf = (opts) => {
104
+ const box = { x: 0, y: 0, width: 10, height: 10, top: 0, left: 0, right: 10, bottom: 10 };
105
+ const rect = { ...box, toJSON: () => box };
106
+ return {
107
+ target: opts.element,
108
+ isIntersecting: opts.isIntersecting,
109
+ intersectionRatio: opts.ratio,
110
+ boundingClientRect: rect,
111
+ intersectionRect: rect,
112
+ rootBounds: null,
113
+ time: 0,
114
+ };
115
+ };
116
+ /**
117
+ * An `IntersectionObserver` whose `observe()` records the element and reports nothing by itself: `settle`
118
+ * delivers the first report of a browser, `flush` delivers an entry to the observers of an element.
119
+ */
85
120
  export class FakeIntersectionObserver {
86
121
  /** The observers created since the last `install`, in creation order. */
87
122
  static { this.all = []; }
123
+ /** How many observers were created since the last `install`. */
124
+ static get created() {
125
+ return FakeIntersectionObserver.all.length;
126
+ }
127
+ /** The observers created since the last `install` that are not disconnected. */
128
+ static live() {
129
+ return FakeIntersectionObserver.all.filter((observer) => !observer.isDisconnected);
130
+ }
131
+ /** The targets this observer has reported on: a browser reports each newly observed target once, at first. */
132
+ #reported;
88
133
  constructor(callback, options) {
89
134
  this.callback = callback;
90
135
  this.options = options;
136
+ /** The targets this observer has reported on: a browser reports each newly observed target once, at first. */
137
+ this.#reported = new Set();
91
138
  this.root = null;
92
139
  this.rootMargin = '';
93
140
  this.scrollMargin = '';
@@ -100,38 +147,45 @@ export class FakeIntersectionObserver {
100
147
  /** Replaces `globalThis.IntersectionObserver` with the fake and forgets the earlier observers. */
101
148
  static install() {
102
149
  FakeIntersectionObserver.all = [];
103
- return swap({
104
- target: globalThis,
105
- name: 'IntersectionObserver',
106
- value: FakeIntersectionObserver,
107
- });
150
+ return swap({ name: 'IntersectionObserver', value: FakeIntersectionObserver });
108
151
  }
109
152
  /** Calls every observer of `element` with one entry. `ratio` is 1 when the element intersects and 0 when not, unless given. */
110
153
  static flush(opts) {
111
154
  const { element, isIntersecting, ratio = isIntersecting ? 1 : 0 } = opts;
112
- const box = { x: 0, y: 0, width: 10, height: 10, top: 0, left: 0, right: 10, bottom: 10 };
113
- const rect = { ...box, toJSON: () => box };
114
- const entry = {
115
- target: element,
116
- isIntersecting,
117
- intersectionRatio: ratio,
118
- boundingClientRect: rect,
119
- intersectionRect: rect,
120
- rootBounds: null,
121
- time: 0,
122
- };
155
+ const entry = intersectionEntryOf({ element, isIntersecting, ratio });
123
156
  for (const observer of FakeIntersectionObserver.all) {
124
157
  if (observer.targets.includes(element)) {
158
+ observer.#reported.add(element);
125
159
  observer.callback([entry], observer);
126
160
  }
127
161
  }
128
162
  }
163
+ /**
164
+ * The first report of a browser: every live observer is called, once per target it has not reported
165
+ * on yet, with the entry for `isIntersecting` (not intersecting by default). A target already
166
+ * reported on, by `settle` or `flush`, is skipped.
167
+ */
168
+ static settle(opts = {}) {
169
+ const { isIntersecting = false, ratio = isIntersecting ? 1 : 0 } = opts;
170
+ for (const observer of FakeIntersectionObserver.live()) {
171
+ const entries = observer.targets
172
+ .filter((element) => !observer.#reported.has(element))
173
+ .map((element) => {
174
+ observer.#reported.add(element);
175
+ return intersectionEntryOf({ element, isIntersecting, ratio });
176
+ });
177
+ if (entries.length > 0) {
178
+ observer.callback(entries, observer);
179
+ }
180
+ }
181
+ }
129
182
  observe(target) {
130
183
  if (!this.targets.includes(target)) {
131
184
  this.targets.push(target);
132
185
  }
133
186
  }
134
187
  unobserve(target) {
188
+ this.#reported.delete(target);
135
189
  drop({ list: this.targets, item: target });
136
190
  }
137
191
  disconnect() {
@@ -146,16 +200,32 @@ export class FakeIntersectionObserver {
146
200
  export class FakeMatchMedia extends EventTarget {
147
201
  /** The queries asked since the last `install`, with the list each one got. */
148
202
  static { this.queries = new Map(); }
203
+ #listeners = new Set();
149
204
  constructor(media, matches = false) {
150
205
  super();
151
206
  this.media = media;
152
207
  this.matches = matches;
153
208
  }
209
+ /** How many distinct `change` listeners are subscribed now, to assert a subscribe and an unsubscribe. */
210
+ get listenerCount() {
211
+ return this.#listeners.size;
212
+ }
213
+ addEventListener(type, listener, options) {
214
+ if (type === 'change' && listener) {
215
+ this.#listeners.add(listener);
216
+ }
217
+ super.addEventListener(type, listener, options);
218
+ }
219
+ removeEventListener(type, listener, options) {
220
+ if (type === 'change' && listener) {
221
+ this.#listeners.delete(listener);
222
+ }
223
+ super.removeEventListener(type, listener, options);
224
+ }
154
225
  /** Replaces `window.matchMedia` with a function that answers the list of the query. */
155
226
  static install() {
156
227
  FakeMatchMedia.queries.clear();
157
228
  return swap({
158
- target: globalThis,
159
229
  name: 'matchMedia',
160
230
  value: (query) => FakeMatchMedia.of(query),
161
231
  });
@@ -175,14 +245,15 @@ export class FakeMatchMedia extends EventTarget {
175
245
  }
176
246
  /**
177
247
  * A `Storage` that behaves like the real one: stored keys are own properties, so `Object.keys` lists
178
- * them. Set `failReads` for a blocked storage (reads throw `SecurityError`) and `failWrites` for a
179
- * full or blocked one (`setItem` and `clear` throw `QuotaExceededError`, `removeItem` throws
180
- * `SecurityError`); both can change at any time. A key named like a member of the fake (`getItem`,
248
+ * them. Each way to fail has its own switch, and each can change at any time: `failReads` makes
249
+ * `getItem` throw `SecurityError`, `failListing` makes `key` and `length` throw it, `failWrites` makes
250
+ * `setItem` and `clear` throw `QuotaExceededError` and `removeItem` throw `SecurityError`. A key named like a member of the fake (`getItem`,
181
251
  * `length`, `writes`, `failWrites` and the rest) would shadow it, so `setItem` throws a `TypeError`
182
252
  * for it, where the real `Storage` accepts it.
183
253
  */
184
254
  export class FakeStorage {
185
255
  #failReads = false;
256
+ #failListing = false;
186
257
  #failWrites = false;
187
258
  #writes = [];
188
259
  get failReads() {
@@ -191,6 +262,12 @@ export class FakeStorage {
191
262
  set failReads(value) {
192
263
  this.#failReads = value;
193
264
  }
265
+ get failListing() {
266
+ return this.#failListing;
267
+ }
268
+ set failListing(value) {
269
+ this.#failListing = value;
270
+ }
194
271
  get failWrites() {
195
272
  return this.#failWrites;
196
273
  }
@@ -202,12 +279,13 @@ export class FakeStorage {
202
279
  return this.#writes;
203
280
  }
204
281
  get length() {
205
- return this.#keys().length;
282
+ this.#assertListable();
283
+ return Object.keys(this).length;
206
284
  }
207
285
  /** Makes this the `localStorage` (the default) or the `sessionStorage` of the global. */
208
286
  install(area = 'local') {
209
287
  const name = area === 'session' ? 'sessionStorage' : 'localStorage';
210
- return swap({ target: globalThis, name, value: this });
288
+ return swap({ name, value: this });
211
289
  }
212
290
  getItem(key) {
213
291
  this.#assertReadable();
@@ -230,22 +308,22 @@ export class FakeStorage {
230
308
  }
231
309
  removeItem(key) {
232
310
  this.#assertWritable('Access is denied', 'SecurityError');
233
- this.#assertReadable();
234
311
  Reflect.deleteProperty(this, key);
235
312
  }
236
313
  clear() {
237
314
  this.#assertWritable('The quota has been exceeded', 'QuotaExceededError');
238
- for (const key of this.#keys()) {
315
+ for (const key of Object.keys(this)) {
239
316
  Reflect.deleteProperty(this, key);
240
317
  }
241
318
  }
242
319
  key(index) {
243
- this.#assertReadable();
244
- return this.#keys()[index] ?? null;
320
+ this.#assertListable();
321
+ return Object.keys(this)[index] ?? null;
245
322
  }
246
- #keys() {
247
- this.#assertReadable();
248
- return Object.keys(this);
323
+ #assertListable() {
324
+ if (this.#failListing) {
325
+ throw new DOMException('Access is denied', 'SecurityError');
326
+ }
249
327
  }
250
328
  #assertReadable() {
251
329
  if (this.#failReads) {
@@ -269,7 +347,7 @@ export class FakeClipboard {
269
347
  }
270
348
  /** Makes this the `navigator.clipboard`. */
271
349
  install() {
272
- return swap({ target: globalThis.navigator, name: 'clipboard', value: this });
350
+ return swap({ at: 'navigator', name: 'clipboard', value: this });
273
351
  }
274
352
  writeText(text) {
275
353
  if (this.isDenied) {
@@ -1,4 +1,9 @@
1
1
  import { type IStorageCodec, type TStorageArea } from '../common/index.js';
2
+ /** What `BrowserStorage.subscribe` tells its listener about a change. */
3
+ export interface IStorageChange {
4
+ /** `true` when another tab or window changed the storage (a `storage` event); `false` for a write or removal through `BrowserStorage` in this one. */
5
+ isExternal: boolean;
6
+ }
2
7
  /**
3
8
  * `localStorage` and `sessionStorage` that never throw: a missing area, a blocked accessor, a quota
4
9
  * error or text the codec cannot read gives the fallback or `false`. Nothing touches `window` at
@@ -48,18 +53,23 @@ export declare class BrowserStorage {
48
53
  }): Array<string>;
49
54
  /**
50
55
  * Removes every key that starts with `prefix` and answers how many it removed. An empty `prefix`
51
- * removes nothing, and a session key is never removed, as in `remove`. A key another tab removed
56
+ * removes nothing, and a session key is never removed, as in `remove`. Every subscriber of a key under the
57
+ * prefix is told, whether or not the key was stored. A key another tab removed
52
58
  * after the listing still counts: `removeItem` of a missing key does not throw.
53
59
  */
54
60
  static removeWhere(opts: {
55
61
  storage?: TStorageArea;
56
62
  prefix: string;
57
63
  }): number;
58
- /** `listener` runs after a write through `BrowserStorage` and after another tab changes the key. */
64
+ /**
65
+ * `listener` runs after a write through `BrowserStorage` and after another tab changes the key, and says which
66
+ * of the two it was in `change.isExternal`: a listener that writes back can skip the change of another tab, and one that
67
+ * shows "changed in another tab" can skip its own. A listener that takes no argument is called the same way.
68
+ */
59
69
  static subscribe(opts: {
60
70
  key: string;
61
71
  storage?: TStorageArea;
62
- listener: () => void;
72
+ listener: (change: IStorageChange) => void;
63
73
  }): () => void;
64
74
  private static listen;
65
75
  private static write;
@@ -74,15 +74,30 @@ export class BrowserStorage {
74
74
  }
75
75
  /**
76
76
  * Removes every key that starts with `prefix` and answers how many it removed. An empty `prefix`
77
- * removes nothing, and a session key is never removed, as in `remove`. A key another tab removed
77
+ * removes nothing, and a session key is never removed, as in `remove`. Every subscriber of a key under the
78
+ * prefix is told, whether or not the key was stored. A key another tab removed
78
79
  * after the listing still counts: `removeItem` of a missing key does not throw.
79
80
  */
80
81
  static removeWhere(opts) {
81
82
  const { storage, prefix } = opts;
82
83
  const keys = prefix ? BrowserStorage.keys({ storage, prefix }) : [];
83
- return keys.filter((key) => BrowserStorage.remove({ key, storage })).length;
84
+ const removed = keys.filter((key) => BrowserStorage.remove({ key, storage })).length;
85
+ // A key not stored yet, with a write waiting for it, is under the prefix too: tell its subscribers.
86
+ if (prefix) {
87
+ BrowserStorage.notify({
88
+ key: undefined,
89
+ area: BrowserStorage.area({ storage }),
90
+ prefix,
91
+ isExternal: false,
92
+ });
93
+ }
94
+ return removed;
84
95
  }
85
- /** `listener` runs after a write through `BrowserStorage` and after another tab changes the key. */
96
+ /**
97
+ * `listener` runs after a write through `BrowserStorage` and after another tab changes the key, and says which
98
+ * of the two it was in `change.isExternal`: a listener that writes back can skip the change of another tab, and one that
99
+ * shows "changed in another tab" can skip its own. A listener that takes no argument is called the same way.
100
+ */
86
101
  static subscribe(opts) {
87
102
  const subscription = { ...opts };
88
103
  if (BrowserStorage.subs.size === 0) {
@@ -109,7 +124,7 @@ export class BrowserStorage {
109
124
  return BrowserStorage.safe({
110
125
  run: () => {
111
126
  opts.run(area);
112
- BrowserStorage.notify({ key: opts.key, area });
127
+ BrowserStorage.notify({ key: opts.key, area, isExternal: false });
113
128
  return true;
114
129
  },
115
130
  fallback: false,
@@ -117,15 +132,18 @@ export class BrowserStorage {
117
132
  }
118
133
  static notify(opts) {
119
134
  for (const { key, storage, listener } of BrowserStorage.subs) {
120
- if ((opts.key === null || opts.key === key) &&
135
+ if ((opts.key === null || opts.key === key || (!!opts.prefix && key.startsWith(opts.prefix))) &&
121
136
  opts.area === BrowserStorage.area({ storage })) {
122
- BrowserStorage.safe({ run: listener, fallback: undefined });
137
+ BrowserStorage.safe({
138
+ run: () => listener({ isExternal: opts.isExternal }),
139
+ fallback: undefined,
140
+ });
123
141
  }
124
142
  }
125
143
  }
126
144
  static { this.onEvent = (event) => {
127
145
  if ('key' in event && 'storageArea' in event) {
128
- BrowserStorage.notify({ key: event.key, area: event.storageArea });
146
+ BrowserStorage.notify({ key: event.key, area: event.storageArea, isExternal: true });
129
147
  }
130
148
  }; }
131
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ardor-kernel",
3
- "version": "0.4.8-5",
3
+ "version": "0.4.8-7",
4
4
  "description": "ARDOR kernel - the isomorphic core of the ARDOR frontend framework: application base on IGNIS inversion, service and provider bases, request/auth constants, binding keys, the network request service, runtime config and the HTTP repository (from IGNIS). No React and no react-admin.",
5
5
  "keywords": [
6
6
  "ardor",
@@ -73,12 +73,12 @@
73
73
  "devDependencies": {
74
74
  "@size-limit/preset-small-lib": "^14.2.0",
75
75
  "@types/bun": "^1.4.3",
76
- "@venizia/dev-configs": "^0.4.8-2",
77
- "@venizia/ignis-connectors": "^0.4.8-4",
78
- "@venizia/ignis-filter": "^0.4.7-2",
79
- "@venizia/ignis-helpers": "^0.4.8-4",
80
- "@venizia/ignis-inversion": "^0.4.7-2",
81
- "@venizia/ignis-kernel": "^0.4.8-4",
76
+ "@venizia/dev-configs": "^0.4.8-3",
77
+ "@venizia/ignis-connectors": "^0.4.8-6",
78
+ "@venizia/ignis-filter": "^0.4.7-4",
79
+ "@venizia/ignis-helpers": "^0.4.8-6",
80
+ "@venizia/ignis-inversion": "^0.4.7-3",
81
+ "@venizia/ignis-kernel": "^0.4.8-6",
82
82
  "eslint": "^10.13.0",
83
83
  "oxlint": "1.89.0",
84
84
  "oxlint-tsgolint": "7.0.2004",
@@ -88,11 +88,11 @@
88
88
  "typescript": "^6.0.3"
89
89
  },
90
90
  "peerDependencies": {
91
- "@venizia/ignis-connectors": "^0.4.8-4",
92
- "@venizia/ignis-filter": "^0.4.7-2",
93
- "@venizia/ignis-helpers": "^0.4.8-4",
94
- "@venizia/ignis-inversion": "^0.4.7-2",
95
- "@venizia/ignis-kernel": "^0.4.8-4",
91
+ "@venizia/ignis-connectors": "^0.4.8-6",
92
+ "@venizia/ignis-filter": "^0.4.7-4",
93
+ "@venizia/ignis-helpers": "^0.4.8-6",
94
+ "@venizia/ignis-inversion": "^0.4.7-3",
95
+ "@venizia/ignis-kernel": "^0.4.8-6",
96
96
  "reflect-metadata": ">=0.2.2"
97
97
  },
98
98
  "peerDependenciesMeta": {
@@ -109,12 +109,12 @@
109
109
  "@venizia/ignis-inversion",
110
110
  "reflect-metadata"
111
111
  ],
112
- "limit": "7660 B"
112
+ "limit": "8440 B"
113
113
  },
114
114
  {
115
115
  "path": "dist/testing.js",
116
116
  "import": "*",
117
- "limit": "1340 B"
117
+ "limit": "1640 B"
118
118
  }
119
119
  ],
120
120
  "engines": {