@venizia/ardor-kernel 0.4.8-8 → 0.4.8

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,4 +1,4 @@
1
- import { type IAuthTokenRecord } from '../common/index.js';
1
+ import { type IAuthTokenRecord, type IdType } 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;
@@ -6,13 +6,17 @@ export declare class AuthTokenStore {
6
6
  static read(opts?: {
7
7
  key?: string;
8
8
  }): IAuthTokenRecord | undefined;
9
- /** Stores the token with its `provider` under `key` (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available. */
9
+ /**
10
+ * Stores the token with its `provider`, and the `userId` it was issued to when given, under `key`
11
+ * (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available.
12
+ */
10
13
  static write(opts: {
11
14
  token: {
12
15
  value: string;
13
16
  type: string;
14
17
  };
15
18
  provider: string;
19
+ userId?: IdType;
16
20
  key?: string;
17
21
  }): void;
18
22
  }
@@ -23,14 +23,17 @@ export class AuthTokenStore {
23
23
  return undefined;
24
24
  }
25
25
  }
26
- /** Stores the token with its `provider` under `key` (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available. */
26
+ /**
27
+ * Stores the token with its `provider`, and the `userId` it was issued to when given, under `key`
28
+ * (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available.
29
+ */
27
30
  static write(opts) {
28
31
  // Not a silent skip: a sign-in that is not kept would look like it worked.
29
32
  if (typeof localStorage === 'undefined') {
30
33
  throw getError({ message: '[write] localStorage is not available' });
31
34
  }
32
- const { token, provider } = opts;
33
- localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider })));
35
+ const { token, provider, userId } = opts;
36
+ localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider }, userId === undefined ? {} : { userId })));
34
37
  }
35
38
  }
36
39
  //# sourceMappingURL=auth-token-store.js.map
@@ -6,7 +6,8 @@ import type { ILogger } from '@venizia/ignis-helpers/core';
6
6
  */
7
7
  export declare class AuthRecovery {
8
8
  private readonly opts;
9
- private refreshing;
9
+ /** The refresh in flight for each session (`key`): a request of another session never joins it. */
10
+ private readonly refreshing;
10
11
  constructor(opts: {
11
12
  logger: ILogger;
12
13
  /** Read per request: the service lets its `authRecovery` be set after construction. */
@@ -18,8 +19,14 @@ export declare class AuthRecovery {
18
19
  /** Whether the request, given by its paths, goes without a token; such a request never recovers. */
19
20
  isNoAuthPath: (paths: string[]) => boolean;
20
21
  });
21
- /** Once for every 401 in flight: the callers share one `refresh`. `true` when the token was refreshed. */
22
- refresh(): Promise<boolean>;
22
+ /**
23
+ * Once for every 401 in flight of one session (`key`): those callers share one `refresh`. A 401 of
24
+ * another session starts its own, so it never waits for an answer that belongs to someone else.
25
+ * `true` when the token was refreshed.
26
+ */
27
+ refresh(opts?: {
28
+ key?: string;
29
+ }): Promise<boolean>;
23
30
  /** Not for a no-auth path, nor for the refresh path itself, which would wait on itself. */
24
31
  canRecover(opts: {
25
32
  paths: string[];
@@ -6,13 +6,23 @@
6
6
  export class AuthRecovery {
7
7
  constructor(opts) {
8
8
  this.opts = opts;
9
- this.refreshing = null;
9
+ /** The refresh in flight for each session (`key`): a request of another session never joins it. */
10
+ this.refreshing = new Map();
10
11
  }
11
- /** Once for every 401 in flight: the callers share one `refresh`. `true` when the token was refreshed. */
12
- refresh() {
12
+ /**
13
+ * Once for every 401 in flight of one session (`key`): those callers share one `refresh`. A 401 of
14
+ * another session starts its own, so it never waits for an answer that belongs to someone else.
15
+ * `true` when the token was refreshed.
16
+ */
17
+ refresh(opts = {}) {
13
18
  const { logger, refresh, onFailure } = this.opts;
19
+ const { key = '' } = opts;
20
+ const inFlight = this.refreshing.get(key);
21
+ if (inFlight) {
22
+ return inFlight;
23
+ }
14
24
  // A refresh that throws synchronously is still a failed refresh, not a stray exception.
15
- this.refreshing ??= Promise.resolve()
25
+ const started = Promise.resolve()
16
26
  .then(() => refresh())
17
27
  .catch(async (error) => {
18
28
  logger.error('[refresh] refreshToken failed | error: %o', error);
@@ -25,9 +35,10 @@ export class AuthRecovery {
25
35
  return false;
26
36
  })
27
37
  .finally(() => {
28
- this.refreshing = null;
38
+ this.refreshing.delete(key);
29
39
  });
30
- return this.refreshing;
40
+ this.refreshing.set(key, started);
41
+ return started;
31
42
  }
32
43
  /** Not for a no-auth path, nor for the refresh path itself, which would wait on itself. */
33
44
  canRecover(opts) {
@@ -31,6 +31,8 @@ export declare class ResponseReader {
31
31
  count?: number;
32
32
  total?: number;
33
33
  };
34
+ /** The rows of a list answer: an array as it is, no body at all (an empty answer) as no row, any other value as the one row. */
35
+ private static toRows;
34
36
  /**
35
37
  * A failed response as an `ApplicationError`, mapped like IGNIS `HttpDataSource`: the HTTP status,
36
38
  * the server's code and args, its `extra` with the `requestId` added, and `details.cause`.
@@ -28,7 +28,10 @@ export class ResponseReader {
28
28
  ...(contentDisposition ? { contentDisposition } : {}),
29
29
  };
30
30
  }
31
- const parsedBody = await response.json();
31
+ const parsedBody = await HttpResponseReader.readBody({
32
+ response,
33
+ context: `[ResponseReader] ${response.status}`,
34
+ });
32
35
  // A route with extras answers `{ data, extra }`; `readExtra` strips only `extra`, so a
33
36
  // count-in-body request still reads `{ count, data }`.
34
37
  const { body, extra } = HttpResponseReader.readExtra({
@@ -61,9 +64,7 @@ export class ResponseReader {
61
64
  });
62
65
  }
63
66
  const dataFormatted = data;
64
- const normalizedData = !Array.isArray(dataFormatted.data)
65
- ? [dataFormatted.data]
66
- : dataFormatted.data;
67
+ const normalizedData = ResponseReader.toRows({ data: dataFormatted.data });
67
68
  const total = ResponseReader.resolveTotal({ headers, rowCount: normalizedData.length });
68
69
  return {
69
70
  data: normalizedData,
@@ -71,7 +72,7 @@ export class ResponseReader {
71
72
  total,
72
73
  };
73
74
  }
74
- const normalizedData = !Array.isArray(data) ? [data] : data;
75
+ const normalizedData = ResponseReader.toRows({ data });
75
76
  const total = ResponseReader.resolveTotal({ headers, rowCount: normalizedData.length });
76
77
  return {
77
78
  data: normalizedData,
@@ -91,6 +92,14 @@ export class ResponseReader {
91
92
  }
92
93
  }
93
94
  }
95
+ /** The rows of a list answer: an array as it is, no body at all (an empty answer) as no row, any other value as the one row. */
96
+ static toRows(opts) {
97
+ const { data } = opts;
98
+ if (Array.isArray(data)) {
99
+ return data;
100
+ }
101
+ return data === null || data === undefined ? [] : [data];
102
+ }
94
103
  /**
95
104
  * A failed response as an `ApplicationError`, mapped like IGNIS `HttpDataSource`: the HTTP status,
96
105
  * the server's code and args, its `extra` with the `requestId` added, and `details.cause`.
@@ -3,34 +3,60 @@
3
3
  * The preset image writes it at container start, from the environment variables that start with `VITE_`.
4
4
  */
5
5
  export declare const RUNTIME_CONFIG_GLOBAL = "__APP_CONFIG__";
6
- /** The `normalized.code` of the error `RuntimeConfig.get` throws for a required value that is not set; the key is in its `extra.key`. */
6
+ /** The `normalized.code` of the error `RuntimeConfig.getRequired` throws for a value that is not set; the key is in its `extra.key`. */
7
7
  export declare const RUNTIME_CONFIG_REQUIRED_CODE = "ardor.runtime_config.required";
8
- interface IRuntimeConfigOptions {
8
+ /** The `normalized.code` of the error a `transform` of `RuntimeConfig` causes by throwing, or by answering `undefined` or `null` to `getRequired`; the key is in its `extra.key`, the value is never in the error. */
9
+ export declare const RUNTIME_CONFIG_INVALID_CODE = "ardor.runtime_config.invalid";
10
+ interface IRuntimeConfigReadOptions {
9
11
  /** The name looked up in `window.__APP_CONFIG__` and in `buildTimeEnv`. */
10
12
  key: string;
11
13
  /** The build-time source, normally `import.meta.env`. */
12
14
  buildTimeEnv?: Record<string, unknown>;
13
- /** Used when neither source has a non-empty string for `key`. */
14
- defaultValue?: string;
15
15
  }
16
16
  /** Reads configuration a deployment can change without a rebuild. */
17
17
  export declare class RuntimeConfig {
18
18
  /**
19
19
  * One config value: the runtime one (`window.__APP_CONFIG__`), else the build-time one
20
- * (`buildTimeEnv`, passed by the app as `import.meta.env`), else `defaultValue`. Only a non-empty
21
- * string counts, and a missing global is not an error.
20
+ * (`buildTimeEnv`, passed by the app as `import.meta.env`), else `defaultValue`. A value that is
21
+ * empty or only spaces counts as unset, in both sources, and a missing global is not an error.
22
22
  *
23
- * With `required: true` the result is a `string`: when all three are absent it throws, naming the
24
- * key and never a value. The error is an `ApplicationError` with `normalized.code` equal to
25
- * `RUNTIME_CONFIG_REQUIRED_CODE` and the key in `extra.key`, so a caller tells it from another error
26
- * without reading the message. Without `required`, the result is `string | undefined`.
23
+ * With `transform` the result is what it makes of the value (a number, a boolean). It is handed
24
+ * `undefined` when the value is unset, and `defaultValue` applies when it answers `undefined` or
25
+ * `null`. A `transform` that throws raises an `ApplicationError` with `normalized.code` equal to
26
+ * `RUNTIME_CONFIG_INVALID_CODE` and the key in `extra.key`, never the value.
27
27
  */
28
- static get(opts: IRuntimeConfigOptions & {
29
- required: true;
28
+ static get(opts: IRuntimeConfigReadOptions & {
29
+ defaultValue: string;
30
+ transform?: undefined;
30
31
  }): string;
31
- static get(opts: IRuntimeConfigOptions & {
32
- required?: boolean;
32
+ static get(opts: IRuntimeConfigReadOptions & {
33
+ defaultValue?: undefined;
34
+ transform?: undefined;
33
35
  }): string | undefined;
36
+ static get<TValue>(opts: IRuntimeConfigReadOptions & {
37
+ transform: (raw: string | undefined) => TValue | null | undefined;
38
+ defaultValue: TValue;
39
+ }): TValue;
40
+ static get<TValue>(opts: IRuntimeConfigReadOptions & {
41
+ transform: (raw: string | undefined) => TValue;
42
+ defaultValue?: TValue;
43
+ }): TValue;
44
+ /**
45
+ * One config value the app cannot run without, read as `get` reads it. When it is unset it throws,
46
+ * naming the key and never a value: an `ApplicationError` with `normalized.code` equal to
47
+ * `RUNTIME_CONFIG_REQUIRED_CODE` and the key in `extra.key`, so a caller tells it from another
48
+ * error without reading the message. It has no `defaultValue`.
49
+ *
50
+ * With `transform` the result is what it makes of the value, which it is handed as a `string`. A
51
+ * `transform` that throws, or answers `undefined` or `null`, raises the error of
52
+ * `RUNTIME_CONFIG_INVALID_CODE`, with the key in `extra.key` and never the value.
53
+ */
54
+ static getRequired(opts: IRuntimeConfigReadOptions & {
55
+ transform?: undefined;
56
+ }): string;
57
+ static getRequired<TValue>(opts: IRuntimeConfigReadOptions & {
58
+ transform: (raw: string) => TValue | null | undefined;
59
+ }): TValue;
34
60
  }
35
61
  export {};
36
62
  //# sourceMappingURL=runtime-config.d.ts.map
@@ -4,8 +4,10 @@ import { getError } from '@venizia/ignis-inversion';
4
4
  * The preset image writes it at container start, from the environment variables that start with `VITE_`.
5
5
  */
6
6
  export const RUNTIME_CONFIG_GLOBAL = '__APP_CONFIG__';
7
- /** The `normalized.code` of the error `RuntimeConfig.get` throws for a required value that is not set; the key is in its `extra.key`. */
7
+ /** The `normalized.code` of the error `RuntimeConfig.getRequired` throws for a value that is not set; the key is in its `extra.key`. */
8
8
  export const RUNTIME_CONFIG_REQUIRED_CODE = 'ardor.runtime_config.required';
9
+ /** The `normalized.code` of the error a `transform` of `RuntimeConfig` causes by throwing, or by answering `undefined` or `null` to `getRequired`; the key is in its `extra.key`, the value is never in the error. */
10
+ export const RUNTIME_CONFIG_INVALID_CODE = 'ardor.runtime_config.invalid';
9
11
  const readString = (opts) => {
10
12
  const { source, key } = opts;
11
13
  if (typeof source !== 'object' || source === null || Array.isArray(source)) {
@@ -16,20 +18,55 @@ const readString = (opts) => {
16
18
  return undefined;
17
19
  }
18
20
  const value = Reflect.get(source, key);
19
- return typeof value === 'string' && value !== '' ? value : undefined;
21
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
22
+ };
23
+ const readValue = (opts) => {
24
+ const { key, buildTimeEnv } = opts;
25
+ return (readString({ source: Reflect.get(globalThis, RUNTIME_CONFIG_GLOBAL), key }) ??
26
+ readString({ source: buildTimeEnv, key }));
27
+ };
28
+ const applyTransform = (opts) => {
29
+ const { key, raw, transform } = opts;
30
+ try {
31
+ return transform(raw);
32
+ }
33
+ catch {
34
+ throw getError({
35
+ messageCode: RUNTIME_CONFIG_INVALID_CODE,
36
+ extra: { key },
37
+ message: `[RuntimeConfig] '${key}' is not valid | The transform threw on the value; fix the value in config.js or in the build-time env`,
38
+ });
39
+ }
20
40
  };
21
41
  /** Reads configuration a deployment can change without a rebuild. */
22
42
  export class RuntimeConfig {
23
43
  static get(opts) {
24
- const { key, buildTimeEnv, defaultValue, required } = opts;
25
- const value = readString({ source: Reflect.get(globalThis, RUNTIME_CONFIG_GLOBAL), key }) ??
26
- readString({ source: buildTimeEnv, key }) ??
27
- defaultValue;
28
- if (required && value === undefined) {
44
+ const { key, defaultValue, transform } = opts;
45
+ const raw = readValue(opts);
46
+ if (transform === undefined) {
47
+ return raw ?? defaultValue;
48
+ }
49
+ return applyTransform({ key, raw, transform }) ?? defaultValue;
50
+ }
51
+ static getRequired(opts) {
52
+ const { key, transform } = opts;
53
+ const raw = readValue(opts);
54
+ if (raw === undefined) {
29
55
  throw getError({
30
56
  messageCode: RUNTIME_CONFIG_REQUIRED_CODE,
31
57
  extra: { key },
32
- message: `[RuntimeConfig.get] '${key}' is required and not set | Write it to config.js (a VITE_ variable of the container, listed in APP_REQUIRED_ENV), or pass it in buildTimeEnv or defaultValue`,
58
+ message: `[RuntimeConfig.getRequired] '${key}' is required and not set | Write it to config.js (a VITE_ variable of the container, listed in APP_REQUIRED_ENV), or pass it in buildTimeEnv`,
59
+ });
60
+ }
61
+ if (transform === undefined) {
62
+ return raw;
63
+ }
64
+ const value = applyTransform({ key, raw, transform });
65
+ if (value === undefined || value === null) {
66
+ throw getError({
67
+ messageCode: RUNTIME_CONFIG_INVALID_CODE,
68
+ extra: { key },
69
+ message: `[RuntimeConfig.getRequired] '${key}' is not valid | The transform answered nothing for the value; fix the value in config.js or in the build-time env`,
33
70
  });
34
71
  }
35
72
  return value;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ardor-kernel",
3
- "version": "0.4.8-8",
3
+ "version": "0.4.8",
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",
@@ -67,18 +67,17 @@
67
67
  "access": "public"
68
68
  },
69
69
  "scripts": {
70
- "force-update": "sh ../../scripts/build/force-update.sh",
71
70
  "prepublishOnly": "make rebuild"
72
71
  },
73
72
  "devDependencies": {
74
73
  "@size-limit/preset-small-lib": "^14.2.0",
75
74
  "@types/bun": "^1.4.3",
76
- "@venizia/dev-configs": "^0.4.8-4",
77
- "@venizia/ignis-connectors": "^0.4.8-7",
78
- "@venizia/ignis-filter": "^0.4.7-4",
79
- "@venizia/ignis-helpers": "^0.4.8-7",
80
- "@venizia/ignis-inversion": "^0.4.7-3",
81
- "@venizia/ignis-kernel": "^0.4.8-7",
75
+ "@venizia/dev-configs": "^0.4.8",
76
+ "@venizia/ignis-connectors": "^0.4.8",
77
+ "@venizia/ignis-filter": "^0.4.7",
78
+ "@venizia/ignis-helpers": "^0.4.8",
79
+ "@venizia/ignis-inversion": "^0.4.7",
80
+ "@venizia/ignis-kernel": "^0.4.8",
82
81
  "eslint": "^10.13.0",
83
82
  "oxlint": "1.89.0",
84
83
  "oxlint-tsgolint": "7.0.2004",
@@ -88,11 +87,11 @@
88
87
  "typescript": "^6.0.3"
89
88
  },
90
89
  "peerDependencies": {
91
- "@venizia/ignis-connectors": "^0.4.8-7",
92
- "@venizia/ignis-filter": "^0.4.7-4",
93
- "@venizia/ignis-helpers": "^0.4.8-7",
94
- "@venizia/ignis-inversion": "^0.4.7-3",
95
- "@venizia/ignis-kernel": "^0.4.8-7",
90
+ "@venizia/ignis-connectors": "^0.4.8",
91
+ "@venizia/ignis-filter": "^0.4.7",
92
+ "@venizia/ignis-helpers": "^0.4.8",
93
+ "@venizia/ignis-inversion": "^0.4.7",
94
+ "@venizia/ignis-kernel": "^0.4.8",
96
95
  "reflect-metadata": ">=0.2.2"
97
96
  },
98
97
  "peerDependenciesMeta": {
@@ -109,7 +108,7 @@
109
108
  "@venizia/ignis-inversion",
110
109
  "reflect-metadata"
111
110
  ],
112
- "limit": "8440 B"
111
+ "limit": "11070 B"
113
112
  },
114
113
  {
115
114
  "path": "dist/testing.js",