@venizia/ardor-kernel 0.5.0-11 → 0.5.0-13

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.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/dist/base/applications/abstract.d.ts +12 -24
  3. package/dist/base/applications/abstract.js +4 -6
  4. package/dist/base/decorators/api.d.ts +0 -3
  5. package/dist/base/decorators/api.js +0 -3
  6. package/dist/base/providers/base.d.ts +0 -3
  7. package/dist/base/providers/base.js +0 -3
  8. package/dist/base/providers/role-permission.d.ts +1 -8
  9. package/dist/base/providers/role-permission.js +0 -3
  10. package/dist/base/services/auth.d.ts +6 -12
  11. package/dist/base/services/auth.js +5 -8
  12. package/dist/base/services/base.d.ts +0 -3
  13. package/dist/base/services/base.js +0 -3
  14. package/dist/base/services/network-request-base.d.ts +133 -0
  15. package/dist/base/services/network-request-base.js +302 -0
  16. package/dist/base/services/network-request.d.ts +28 -131
  17. package/dist/base/services/network-request.js +13 -252
  18. package/dist/common/constants.d.ts +0 -23
  19. package/dist/common/constants.js +0 -23
  20. package/dist/common/keys.d.ts +17 -20
  21. package/dist/common/keys.js +5 -9
  22. package/dist/common/types.d.ts +45 -45
  23. package/dist/helpers/networks/auth-recovery.d.ts +0 -3
  24. package/dist/helpers/networks/auth-recovery.js +0 -3
  25. package/dist/{testing.d.ts → testing/index.d.ts} +2 -17
  26. package/dist/{testing.js → testing/index.js} +1 -16
  27. package/dist/utilities/auth-token-store.d.ts +2 -8
  28. package/dist/utilities/auth-token-store.js +1 -4
  29. package/dist/utilities/browser-clipboard.d.ts +1 -3
  30. package/dist/utilities/browser-clipboard.js +5 -5
  31. package/dist/utilities/browser-storage.d.ts +16 -10
  32. package/dist/utilities/browser-storage.js +36 -20
  33. package/dist/utilities/browser.d.ts +0 -3
  34. package/dist/utilities/browser.js +0 -3
  35. package/dist/utilities/file.d.ts +5 -5
  36. package/dist/utilities/file.js +5 -5
  37. package/dist/utilities/network-response-reader.d.ts +61 -17
  38. package/dist/utilities/network-response-reader.js +157 -22
  39. package/dist/utilities/request-body-encoder.d.ts +35 -15
  40. package/dist/utilities/request-body-encoder.js +67 -10
  41. package/dist/utilities/runtime-config.d.ts +8 -9
  42. package/dist/utilities/runtime-config.js +0 -9
  43. package/dist/utilities/storage-codecs.d.ts +0 -3
  44. package/dist/utilities/storage-codecs.js +0 -3
  45. package/dist/utilities/value.d.ts +0 -3
  46. package/dist/utilities/value.js +0 -3
  47. package/package.json +24 -24
@@ -1,43 +1,86 @@
1
- import { type INetworkResponse, RequestCountData, type TConstValue, type TRequestType } from '../common/index.js';
1
+ import { type INetworkResponse, type IResponseSchema, RequestCountData, type TConstValue, type TRequestType } from '../common/index.js';
2
+ /** What `read` takes besides a schema. */
3
+ interface IReadResponseOptions {
4
+ response: Response;
5
+ type: TRequestType;
6
+ requestCountData?: TConstValue<typeof RequestCountData>;
7
+ }
2
8
  /**
3
9
  * Reads a `Response` into an `INetworkResponse`, and an error response into an error.
4
- *
5
- * @useWhen you read a `Response` into a typed result or a typed error
6
- * @insteadOf `response.json()` with hand-written error handling
7
10
  */
8
11
  export declare class NetworkResponseReader {
9
12
  /** The server wraps an error body under this key; both transports unwrap it. */
10
13
  static readonly ERROR_ROOT_KEY = "error";
14
+ private static readonly DIGITS_RE;
11
15
  /** Content types read as text. */
12
16
  private static readonly TEXTUAL_RE;
13
- /** A response as `INetworkResponse`: JSON read by the request type, a file as a `Blob`. */
14
- static read<TResult = unknown>(opts: {
15
- response: Response;
16
- type: TRequestType;
17
- requestCountData?: TConstValue<typeof RequestCountData>;
17
+ /**
18
+ * A response as `INetworkResponse` whose `data` the schema checked and typed. The schema is given
19
+ * the data as it was read: the rows of a list, the `Blob` of a file. What it refuses throws a
20
+ * `FetchSchemaError` (502). A textual body is read as JSON whatever its type says; one that is no
21
+ * JSON, a 204, and an empty body of no content type that is no attachment are refused too (code
22
+ * `invalid_json`, as in the IGNIS fetchers).
23
+ */
24
+ static read<TResult>(opts: IReadResponseOptions & {
25
+ schema: IResponseSchema<TResult>;
18
26
  }): Promise<INetworkResponse<TResult>>;
27
+ /** A response as `INetworkResponse`: JSON read by the request type, a file as a `Blob`. `data` is `unknown`. */
28
+ static read(opts: IReadResponseOptions & {
29
+ schema?: IResponseSchema;
30
+ }): Promise<INetworkResponse>;
31
+ /**
32
+ * A count as a server sends it: a non-negative integer, or a string of digits. Anything else is
33
+ * `undefined`.
34
+ */
35
+ static parseCount(opts: {
36
+ count: unknown;
37
+ }): number | undefined;
38
+ /**
39
+ * The response with its `data` checked and typed by the schema, for a transport that builds an
40
+ * `INetworkResponse` itself. Whatever `parse` throws, a bug inside it included, becomes a
41
+ * `FetchSchemaError` (502) that names paths and rules, never the data.
42
+ */
43
+ static checkData<TResult>(opts: {
44
+ response: INetworkResponse;
45
+ schema: IResponseSchema<TResult>;
46
+ /** The status the data came with. @default 200 */
47
+ status?: number;
48
+ url?: string;
49
+ }): INetworkResponse<TResult>;
50
+ /**
51
+ * The JSON of a textual body, whatever textual type it names, for a schema to check; nothing for a
52
+ * file. Throws `invalid_json` for a 204 and for a textual body that is no JSON.
53
+ */
54
+ private static readSchemaJson;
55
+ /** The refusal of an answer that holds no JSON and no file. */
56
+ private static noBodyRefusal;
57
+ /** What the headers say of the body: its content type, lower-cased, and whether it is an attachment. */
58
+ private static describeBody;
59
+ private static refusal;
60
+ /** `json` is the body already read and parsed, for a textual answer. */
61
+ private static readUnchecked;
19
62
  /**
20
63
  * Shapes a parsed body by request type. `GET_LIST` and `GET_MANY_REFERENCE` give `data` as an
21
64
  * array and `total` from `Content-Range`, else the row count; with `RequestCountData.DATA_WITH_COUNT`
22
- * the body must be `{ data, count }`, or it throws. Any other type gives `data` as is, and `count`
65
+ * the body must be `{ data, count }`, or it throws; its `count` is read by `parseCount` (none gives the row count, any other value 0 and a warning). Any other type gives `data` as is, and `count`
23
66
  * from `x-response-count` when that is a number; with `DATA_WITH_COUNT` it returns the
24
- * `{ data, count }` body unchanged.
67
+ * `data` of a `{ data, count }` body, with its `count` and `total` when they are numbers, and no
68
+ * `data` for a body that is no plain object. Other keys of the body are left out.
25
69
  */
26
- static convert<TData = unknown>(opts: {
70
+ static convert(opts: {
27
71
  response: {
28
- data: TData | {
29
- data: TData;
30
- count?: number;
31
- };
72
+ data: unknown;
32
73
  headers: Pick<Headers, 'get'>;
33
74
  };
34
75
  type: string;
35
76
  requestCountData?: TConstValue<typeof RequestCountData>;
36
77
  }): {
37
- data: TData;
78
+ data: unknown;
38
79
  count?: number;
39
80
  total?: number;
40
81
  };
82
+ /** The count of a list body: the row count when it names none, 0 and a warning for any other non-count. */
83
+ private static toListCount;
41
84
  /** 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. */
42
85
  private static toRows;
43
86
  /** The total from `Content-Range`, or the page's own row count when the header is absent or malformed. */
@@ -51,4 +94,5 @@ export declare class NetworkResponseReader {
51
94
  headers?: Pick<Headers, 'get'>;
52
95
  }): string | undefined;
53
96
  }
97
+ export {};
54
98
  //# sourceMappingURL=network-response-reader.d.ts.map
@@ -1,34 +1,141 @@
1
1
  import { ContentDispositionTypes, HTTP } from '@venizia/ignis-helpers/common';
2
2
  import { getError } from '@venizia/ignis-inversion';
3
- import { HttpResponseReader } from '@venizia/ignis-helpers/core';
3
+ import { FetchSchemaError, HttpResponseReader, LoggerFactory, RecordUtility, } from '@venizia/ignis-helpers/core';
4
4
  import { RequestCountData, RequestTypes, } from '../common/index.js';
5
5
  /** A list body that carries its rows and its total: `{ data, count }`. Null and primitives are not one. */
6
6
  const isCountedBody = (value) => {
7
7
  return typeof value === 'object' && value !== null && 'data' in value && 'count' in value;
8
8
  };
9
+ /** The issue the IGNIS fetchers give for a body that is no JSON, an empty one included. */
10
+ const NO_BODY_ISSUE = { path: [], code: 'invalid_json' };
11
+ /** A path of a schema issue as the IGNIS fetchers report it: a symbol as its text. */
12
+ const toIssuePath = (opts) => {
13
+ const { path } = opts;
14
+ if (!Array.isArray(path)) {
15
+ return [];
16
+ }
17
+ return path.flatMap((part) => {
18
+ if (typeof part === 'symbol') {
19
+ return [String(part)];
20
+ }
21
+ return typeof part === 'string' || typeof part === 'number' ? [part] : [];
22
+ });
23
+ };
24
+ /**
25
+ * Where and by which rule a schema refused: the `issues` of what it threw, as zod shapes them, or one
26
+ * `custom` issue at the root when it threw none. Never the message or a value, which may quote the body.
27
+ */
28
+ const issuesOf = (opts) => {
29
+ const { error } = opts;
30
+ const issues = RecordUtility.isRecord(error) ? error.issues : undefined;
31
+ const named = Array.isArray(issues) ? issues.filter(RecordUtility.isRecord) : [];
32
+ if (named.length === 0) {
33
+ return [{ path: [], code: 'custom' }];
34
+ }
35
+ return named.map(({ path, code }) => ({
36
+ path: toIssuePath({ path }),
37
+ code: typeof code === 'string' ? code : 'custom',
38
+ }));
39
+ };
9
40
  /**
10
41
  * Reads a `Response` into an `INetworkResponse`, and an error response into an error.
11
- *
12
- * @useWhen you read a `Response` into a typed result or a typed error
13
- * @insteadOf `response.json()` with hand-written error handling
14
42
  */
15
43
  export class NetworkResponseReader {
16
44
  /** The server wraps an error body under this key; both transports unwrap it. */
17
45
  static { this.ERROR_ROOT_KEY = 'error'; }
46
+ static { this.DIGITS_RE = /^\d+$/; }
18
47
  /** Content types read as text. */
19
48
  static { this.TEXTUAL_RE = /^(application\/(json|.*\+json|xml|.*\+xml|x-www-form-urlencoded|javascript|graphql)|text\/)/i; }
20
- /** A response as `INetworkResponse`: JSON read by the request type, a file as a `Blob`. */
21
49
  static async read(opts) {
22
- const { response, type, requestCountData } = opts;
50
+ const { schema, response } = opts;
51
+ if (!schema) {
52
+ return NetworkResponseReader.readUnchecked(opts);
53
+ }
54
+ const { status, url } = response;
55
+ const json = await NetworkResponseReader.readSchemaJson({ response });
56
+ const read = await NetworkResponseReader.readUnchecked({ ...opts, json });
57
+ const { contentType, isAttachment } = NetworkResponseReader.describeBody({ response });
58
+ // No content type and no attachment reads as a `Blob`: an empty one is nothing to check.
59
+ const isNoBody = contentType === '' && !isAttachment && read.data instanceof Blob && read.data.size === 0;
60
+ if (isNoBody) {
61
+ throw NetworkResponseReader.noBodyRefusal({ response });
62
+ }
63
+ return NetworkResponseReader.checkData({ response: read, schema, status, url });
64
+ }
65
+ /**
66
+ * A count as a server sends it: a non-negative integer, or a string of digits. Anything else is
67
+ * `undefined`.
68
+ */
69
+ static parseCount(opts) {
70
+ const { count } = opts;
71
+ const isDigits = typeof count === 'string' && NetworkResponseReader.DIGITS_RE.test(count);
72
+ const parsed = typeof count === 'number' || isDigits ? Number(count) : Number.NaN;
73
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined;
74
+ }
75
+ /**
76
+ * The response with its `data` checked and typed by the schema, for a transport that builds an
77
+ * `INetworkResponse` itself. Whatever `parse` throws, a bug inside it included, becomes a
78
+ * `FetchSchemaError` (502) that names paths and rules, never the data.
79
+ */
80
+ static checkData(opts) {
81
+ const { response, schema, status = HTTP.ResultCodes.RS_2.Ok, url = '' } = opts;
82
+ try {
83
+ return { ...response, data: schema.parse(response.data) };
84
+ }
85
+ catch (error) {
86
+ throw NetworkResponseReader.refusal({ status, url, issues: issuesOf({ error }) });
87
+ }
88
+ }
89
+ /**
90
+ * The JSON of a textual body, whatever textual type it names, for a schema to check; nothing for a
91
+ * file. Throws `invalid_json` for a 204 and for a textual body that is no JSON.
92
+ */
93
+ static async readSchemaJson(opts) {
94
+ const { response } = opts;
95
+ if (response.status === HTTP.ResultCodes.RS_2.NoContent) {
96
+ throw NetworkResponseReader.noBodyRefusal({ response });
97
+ }
98
+ const { contentType, isAttachment } = NetworkResponseReader.describeBody({ response });
99
+ if (isAttachment || !NetworkResponseReader.TEXTUAL_RE.test(contentType)) {
100
+ return undefined;
101
+ }
102
+ const text = await response.text();
103
+ try {
104
+ return { body: JSON.parse(text) };
105
+ }
106
+ catch {
107
+ // Without the parse error: its message quotes the body.
108
+ throw NetworkResponseReader.noBodyRefusal({ response });
109
+ }
110
+ }
111
+ /** The refusal of an answer that holds no JSON and no file. */
112
+ static noBodyRefusal(opts) {
113
+ const { status, url } = opts.response;
114
+ return NetworkResponseReader.refusal({ status, url, issues: [NO_BODY_ISSUE] });
115
+ }
116
+ /** What the headers say of the body: its content type, lower-cased, and whether it is an attachment. */
117
+ static describeBody(opts) {
118
+ const { headers } = opts.response;
119
+ const contentType = (headers?.get(HTTP.Headers.CONTENT_TYPE) ?? '').toLowerCase();
120
+ const contentDisposition = headers?.get(HTTP.Headers.CONTENT_DISPOSITION) ?? '';
121
+ const { type } = HttpResponseReader.parseContentDisposition({ header: contentDisposition });
122
+ const isAttachment = type?.toLowerCase() === ContentDispositionTypes.ATTACHMENT;
123
+ return { contentType, contentDisposition, isAttachment };
124
+ }
125
+ static refusal(opts) {
126
+ const { status, url, issues } = opts;
127
+ // Without the query: it may carry a token or user data.
128
+ return new FetchSchemaError({ status, url: url.split('?')[0] ?? '', issues });
129
+ }
130
+ /** `json` is the body already read and parsed, for a textual answer. */
131
+ static async readUnchecked(opts) {
132
+ const { response, type, requestCountData, json } = opts;
23
133
  if (response.status === 204) {
24
134
  return { data: {} };
25
135
  }
26
- const contentType = (response.headers?.get(HTTP.Headers.CONTENT_TYPE) ?? '').toLowerCase();
27
- const contentDisposition = response.headers?.get(HTTP.Headers.CONTENT_DISPOSITION) ?? '';
28
- const { type: dispositionType } = HttpResponseReader.parseContentDisposition({
29
- header: contentDisposition,
136
+ const { contentType, contentDisposition, isAttachment } = NetworkResponseReader.describeBody({
137
+ response,
30
138
  });
31
- const isAttachment = dispositionType?.toLowerCase() === ContentDispositionTypes.ATTACHMENT;
32
139
  const isTextual = contentType !== '' && NetworkResponseReader.TEXTUAL_RE.test(contentType);
33
140
  if (isAttachment || !isTextual) {
34
141
  const { blob, filename } = await HttpResponseReader.readFile({ response });
@@ -38,10 +145,14 @@ export class NetworkResponseReader {
38
145
  ...(contentDisposition ? { contentDisposition } : {}),
39
146
  };
40
147
  }
41
- const parsedBody = await HttpResponseReader.readBody({
42
- response,
43
- context: `[NetworkResponseReader] ${response.status}`,
44
- });
148
+ let parsedBody = json?.body;
149
+ if (!json) {
150
+ const body = await HttpResponseReader.readBody({
151
+ response,
152
+ context: `[NetworkResponseReader] ${response.status}`,
153
+ });
154
+ parsedBody = body;
155
+ }
45
156
  // A route with extras answers `{ data, extra }`; `readExtra` strips only `extra`, so a
46
157
  // count-in-body request still reads `{ count, data }`.
47
158
  const { body, extra } = HttpResponseReader.readExtra({
@@ -58,9 +169,10 @@ export class NetworkResponseReader {
58
169
  /**
59
170
  * Shapes a parsed body by request type. `GET_LIST` and `GET_MANY_REFERENCE` give `data` as an
60
171
  * array and `total` from `Content-Range`, else the row count; with `RequestCountData.DATA_WITH_COUNT`
61
- * the body must be `{ data, count }`, or it throws. Any other type gives `data` as is, and `count`
172
+ * the body must be `{ data, count }`, or it throws; its `count` is read by `parseCount` (none gives the row count, any other value 0 and a warning). Any other type gives `data` as is, and `count`
62
173
  * from `x-response-count` when that is a number; with `DATA_WITH_COUNT` it returns the
63
- * `{ data, count }` body unchanged.
174
+ * `data` of a `{ data, count }` body, with its `count` and `total` when they are numbers, and no
175
+ * `data` for a body that is no plain object. Other keys of the body are left out.
64
176
  */
65
177
  static convert(opts) {
66
178
  const { response: { data, headers }, type, requestCountData, } = opts;
@@ -73,15 +185,17 @@ export class NetworkResponseReader {
73
185
  message: `[convertResponse] Invalid response format for requestCountData=${RequestCountData.DATA_WITH_COUNT} !`,
74
186
  });
75
187
  }
76
- const dataFormatted = data;
77
- const normalizedData = NetworkResponseReader.toRows({ data: dataFormatted.data });
188
+ const normalizedData = NetworkResponseReader.toRows({ data: data.data });
78
189
  const total = NetworkResponseReader.resolveTotal({
79
190
  headers,
80
191
  rowCount: normalizedData.length,
81
192
  });
82
193
  return {
83
194
  data: normalizedData,
84
- count: dataFormatted?.count ?? normalizedData.length,
195
+ count: NetworkResponseReader.toListCount({
196
+ count: data.count,
197
+ rowCount: normalizedData.length,
198
+ }),
85
199
  total,
86
200
  };
87
201
  }
@@ -97,17 +211,38 @@ export class NetworkResponseReader {
97
211
  }
98
212
  default: {
99
213
  if (requestCountData === RequestCountData.DATA_WITH_COUNT) {
100
- return data;
214
+ // Only the keys of the answer, each of its own type: another body key would pass as one.
215
+ if (!RecordUtility.isPlainRecord(data)) {
216
+ return { data: undefined };
217
+ }
218
+ const { count, total } = data;
219
+ return {
220
+ data: data.data,
221
+ count: typeof count === 'number' ? count : undefined,
222
+ total: typeof total === 'number' ? total : undefined,
223
+ };
101
224
  }
102
225
  // A missing or non-numeric header means the server sent no count - never NaN.
103
226
  const count = Number.parseInt(headers?.get(HTTP.Headers.RESPONSE_COUNT_DATA) ?? '', 10);
104
227
  return {
105
- data: data,
228
+ data,
106
229
  count: Number.isNaN(count) ? undefined : count,
107
230
  };
108
231
  }
109
232
  }
110
233
  }
234
+ /** The count of a list body: the row count when it names none, 0 and a warning for any other non-count. */
235
+ static toListCount(opts) {
236
+ const { count, rowCount } = opts;
237
+ if (count === undefined || count === null) {
238
+ return rowCount;
239
+ }
240
+ const parsed = NetworkResponseReader.parseCount({ count });
241
+ if (parsed === undefined) {
242
+ LoggerFactory.getLogger([NetworkResponseReader.name]).warn('[convert] The count is no non-negative integer, count is 0 | count: %o', count);
243
+ }
244
+ return parsed ?? 0;
245
+ }
111
246
  /** 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. */
112
247
  static toRows(opts) {
113
248
  const { data } = opts;
@@ -8,42 +8,62 @@ export interface IEncodedBody {
8
8
  type TPassThroughBodyType = typeof RequestBodyTypes.JSON | typeof RequestBodyTypes.NONE | typeof RequestBodyTypes.BINARY;
9
9
  /**
10
10
  * Turns a request body into what `fetch` sends, by `RequestBodyTypes`.
11
- *
12
- * @useWhen you turn a request body into what `fetch` sends
13
- * @insteadOf `JSON.stringify` and `FormData` built by hand
14
11
  */
15
12
  export declare class RequestBodyEncoder {
13
+ /**
14
+ * Throws for options that carry `body` or `bodyType`, which `payload` replaced, and for a
15
+ * `payload` that is not `{ data, type? }`: either one would send something else than the caller
16
+ * meant. At run time any text `type` passes, for an `encodeBody` override that reads one;
17
+ * `IRequestPayload` types only the `RequestBodyTypes` values.
18
+ */
19
+ static assertPayload(opts: {
20
+ options: object;
21
+ /** The class that was given the options, named in the message. */
22
+ owner: string;
23
+ }): void;
16
24
  /**
17
25
  * The body as it is sent and the content type to send it under. The overloads give the type of what
18
26
  * is built: a `FormData` for `form-data` (no content type: `fetch` adds the multipart one), a
19
- * `URLSearchParams` for `x-www-form-urlencoded`, and the body you passed for `json`, `none`,
20
- * `binary` or no type. A `bodyType` known only as a `string` answers `IEncodedBody`.
27
+ * `URLSearchParams` for `x-www-form-urlencoded`, and the data you passed for `json`, `none`,
28
+ * `binary` or no type. A `payload.type` known only as a `string` answers `IEncodedBody`.
21
29
  */
22
30
  static encode(opts: {
23
- bodyType: typeof RequestBodyTypes.FORM_DATA;
24
- body: unknown;
31
+ payload: {
32
+ data: unknown;
33
+ type: typeof RequestBodyTypes.FORM_DATA;
34
+ };
25
35
  }): {
26
36
  body: FormData;
27
37
  contentType?: undefined;
28
38
  };
29
39
  static encode(opts: {
30
- bodyType: typeof RequestBodyTypes.FORM_URL_ENCODED;
31
- body: unknown;
40
+ payload: {
41
+ data: unknown;
42
+ type: typeof RequestBodyTypes.FORM_URL_ENCODED;
43
+ };
32
44
  }): {
33
45
  body: URLSearchParams;
34
46
  contentType: string;
35
47
  };
36
- static encode<TBody>(opts: {
37
- bodyType?: TPassThroughBodyType;
38
- body: TBody;
48
+ static encode<TData>(opts: {
49
+ payload: {
50
+ data: TData;
51
+ type?: TPassThroughBodyType;
52
+ };
39
53
  }): {
40
- body: TBody;
54
+ body: TData;
41
55
  contentType: string;
42
56
  };
43
57
  static encode(opts: {
44
- bodyType?: string;
45
- body: unknown;
58
+ payload?: {
59
+ data: unknown;
60
+ type?: string;
61
+ };
46
62
  }): IEncodedBody;
63
+ /** What is wrong with a `payload`: its shape or its type; `undefined` when nothing is. */
64
+ private static findInvalidPayload;
65
+ /** The fields of a form body: those of an object, or the indexes of an array or a string. */
66
+ private static entriesOf;
47
67
  private static isFileList;
48
68
  /** A multipart text value: JSON for objects and arrays, ISO-8601 for a `Date`, `String()` otherwise. */
49
69
  private static encodeText;
@@ -1,19 +1,40 @@
1
+ import { RecordUtility } from '@venizia/ignis-helpers/core';
1
2
  import { getError } from '@venizia/ignis-inversion';
2
3
  import { RequestBodyTypes } from '../common/index.js';
3
4
  import { ValueUtility } from './value.js';
4
5
  /**
5
6
  * Turns a request body into what `fetch` sends, by `RequestBodyTypes`.
6
- *
7
- * @useWhen you turn a request body into what `fetch` sends
8
- * @insteadOf `JSON.stringify` and `FormData` built by hand
9
7
  */
10
8
  export class RequestBodyEncoder {
9
+ /**
10
+ * Throws for options that carry `body` or `bodyType`, which `payload` replaced, and for a
11
+ * `payload` that is not `{ data, type? }`: either one would send something else than the caller
12
+ * meant. At run time any text `type` passes, for an `encodeBody` override that reads one;
13
+ * `IRequestPayload` types only the `RequestBodyTypes` values.
14
+ */
15
+ static assertPayload(opts) {
16
+ const { options, owner } = opts;
17
+ const removed = ['body', 'bodyType'].filter((key) => key in options);
18
+ if (removed.length) {
19
+ const verb = removed.length > 1 ? 'were' : 'was';
20
+ throw getError({
21
+ message: `[${owner}] ${removed.join(' and ')} ${verb} replaced by payload: { data, type }`,
22
+ });
23
+ }
24
+ const payload = 'payload' in options ? options.payload : undefined;
25
+ const invalid = RequestBodyEncoder.findInvalidPayload({ payload });
26
+ if (invalid) {
27
+ throw getError({ message: `[${owner}] payload takes { data, type? }: invalid ${invalid}` });
28
+ }
29
+ }
11
30
  static encode(opts) {
12
- const { bodyType, body } = opts;
31
+ RequestBodyEncoder.assertPayload({ options: opts, owner: RequestBodyEncoder.name });
32
+ const body = opts.payload?.data;
33
+ const bodyType = opts.payload?.type;
13
34
  switch (bodyType) {
14
35
  case RequestBodyTypes.FORM_URL_ENCODED: {
15
36
  const encoded = new URLSearchParams();
16
- for (const [key, value] of Object.entries((body ?? {}))) {
37
+ for (const [key, value] of RequestBodyEncoder.entriesOf({ body })) {
17
38
  if (!ValueUtility.isDefined(value)) {
18
39
  continue;
19
40
  }
@@ -27,9 +48,11 @@ export class RequestBodyEncoder {
27
48
  }
28
49
  case RequestBodyTypes.FORM_DATA: {
29
50
  const formData = new FormData();
30
- for (const [key, value] of Object.entries((body ?? {}))) {
31
- const values = Array.isArray(value) || RequestBodyEncoder.isFileList(value);
32
- for (const item of values ? Array.from(value) : [value]) {
51
+ for (const [key, value] of RequestBodyEncoder.entriesOf({ body })) {
52
+ const items = Array.isArray(value) || RequestBodyEncoder.isFileList(value)
53
+ ? Array.from(value)
54
+ : [value];
55
+ for (const item of items) {
33
56
  RequestBodyEncoder.appendFormValue({ formData, key, value: item });
34
57
  }
35
58
  }
@@ -41,6 +64,39 @@ export class RequestBodyEncoder {
41
64
  }
42
65
  }
43
66
  }
67
+ /** What is wrong with a `payload`: its shape or its type; `undefined` when nothing is. */
68
+ static findInvalidPayload(opts) {
69
+ const { payload } = opts;
70
+ if (payload === undefined) {
71
+ return undefined;
72
+ }
73
+ if (Array.isArray(payload)) {
74
+ return 'shape (got an array)';
75
+ }
76
+ if (payload === null) {
77
+ return 'shape (got null)';
78
+ }
79
+ if (typeof payload !== 'object') {
80
+ return `shape (got a ${typeof payload})`;
81
+ }
82
+ if (!('data' in payload)) {
83
+ return 'shape (no data)';
84
+ }
85
+ const { data: _data, type, ...rest } = payload;
86
+ const unknownKeys = Object.keys(rest);
87
+ if (unknownKeys.length) {
88
+ return `shape (unknown key ${unknownKeys.join(', ')})`;
89
+ }
90
+ return type === undefined || typeof type === 'string' ? undefined : 'type';
91
+ }
92
+ /** The fields of a form body: those of an object, or the indexes of an array or a string. */
93
+ static entriesOf(opts) {
94
+ const { body } = opts;
95
+ if (RecordUtility.isRecord(body)) {
96
+ return Object.entries(body);
97
+ }
98
+ return typeof body === 'string' ? Object.entries(body) : [];
99
+ }
44
100
  // `FileList` exists only in a DOM; the bare identifier throws in Workers and on Bun.
45
101
  static isFileList(value) {
46
102
  return typeof FileList !== 'undefined' && value instanceof FileList;
@@ -51,7 +107,7 @@ export class RequestBodyEncoder {
51
107
  // A urlencoded body carries text only; a file here would be sent as `"{}"` with nothing said.
52
108
  if (value instanceof Blob) {
53
109
  throw getError({
54
- message: `[getRequestProps] "${key}" is a file, which a ${bodyType} body cannot carry. Send it with bodyType "${RequestBodyTypes.FORM_DATA}".`,
110
+ message: `[getRequestProps] "${key}" is a file, which a ${bodyType} body cannot carry. Send it with payload.type "${RequestBodyTypes.FORM_DATA}".`,
55
111
  });
56
112
  }
57
113
  if (value instanceof Date) {
@@ -69,7 +125,8 @@ export class RequestBodyEncoder {
69
125
  return;
70
126
  }
71
127
  if (value instanceof Blob) {
72
- formData.append(key, value, value.name);
128
+ const name = 'name' in value && typeof value.name === 'string' ? value.name : undefined;
129
+ formData.append(key, value, name);
73
130
  return;
74
131
  }
75
132
  formData.append(key, RequestBodyEncoder.encodeText({ key, value, bodyType: RequestBodyTypes.FORM_DATA }));
@@ -2,20 +2,14 @@ import type { TNullable } from '@venizia/ignis-helpers/common';
2
2
  /**
3
3
  * The name `config.js` writes the runtime config under: `window.__APP_CONFIG__`, a record of strings.
4
4
  * The preset image writes it at container start, from the environment variables that start with `VITE_`.
5
- *
6
- * @useWhen you need the name of the global the runtime config is written under
7
5
  */
8
6
  export declare const RUNTIME_CONFIG_GLOBAL = "__APP_CONFIG__";
9
7
  /**
10
8
  * The `normalized.code` of the error `RuntimeConfig.getRequired` throws for a value that is not set; the key is in its `extra.key`.
11
- *
12
- * @useWhen you tell the error of a required config value that is not set from any other error
13
9
  */
14
10
  export declare const RUNTIME_CONFIG_REQUIRED_CODE = "ardor.runtime_config.required";
15
11
  /**
16
12
  * 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.
17
- *
18
- * @useWhen you tell the error of a config value that failed its `transform` from any other error
19
13
  */
20
14
  export declare const RUNTIME_CONFIG_INVALID_CODE = "ardor.runtime_config.invalid";
21
15
  interface IRuntimeConfigReadOptions {
@@ -26,9 +20,6 @@ interface IRuntimeConfigReadOptions {
26
20
  }
27
21
  /**
28
22
  * Reads configuration a deployment can change without a rebuild.
29
- *
30
- * @useWhen a value must change per deployment without a rebuild
31
- * @insteadOf `import.meta.env` or `window.__APP_CONFIG__` read by hand
32
23
  */
33
24
  export declare class RuntimeConfig {
34
25
  /**
@@ -49,10 +40,18 @@ export declare class RuntimeConfig {
49
40
  defaultValue?: undefined;
50
41
  transform?: undefined;
51
42
  }): string | undefined;
43
+ /**
44
+ * A `transform` that may answer `undefined` or `null` needs the `defaultValue` that then applies. One
45
+ * that throws raises an `ApplicationError` of `RUNTIME_CONFIG_INVALID_CODE`.
46
+ */
52
47
  static get<TValue>(opts: IRuntimeConfigReadOptions & {
53
48
  transform: (raw: string | undefined) => TNullable<TValue>;
54
49
  defaultValue: TValue;
55
50
  }): TValue;
51
+ /**
52
+ * A `transform` that always answers a value needs no `defaultValue`. One that throws raises an
53
+ * `ApplicationError` of `RUNTIME_CONFIG_INVALID_CODE`.
54
+ */
56
55
  static get<TValue>(opts: IRuntimeConfigReadOptions & {
57
56
  transform: (raw: string | undefined) => TValue;
58
57
  defaultValue?: TValue;
@@ -2,20 +2,14 @@ import { getError } from '@venizia/ignis-inversion';
2
2
  /**
3
3
  * The name `config.js` writes the runtime config under: `window.__APP_CONFIG__`, a record of strings.
4
4
  * The preset image writes it at container start, from the environment variables that start with `VITE_`.
5
- *
6
- * @useWhen you need the name of the global the runtime config is written under
7
5
  */
8
6
  export const RUNTIME_CONFIG_GLOBAL = '__APP_CONFIG__';
9
7
  /**
10
8
  * The `normalized.code` of the error `RuntimeConfig.getRequired` throws for a value that is not set; the key is in its `extra.key`.
11
- *
12
- * @useWhen you tell the error of a required config value that is not set from any other error
13
9
  */
14
10
  export const RUNTIME_CONFIG_REQUIRED_CODE = 'ardor.runtime_config.required';
15
11
  /**
16
12
  * 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.
17
- *
18
- * @useWhen you tell the error of a config value that failed its `transform` from any other error
19
13
  */
20
14
  export const RUNTIME_CONFIG_INVALID_CODE = 'ardor.runtime_config.invalid';
21
15
  const readString = (opts) => {
@@ -50,9 +44,6 @@ const applyTransform = (opts) => {
50
44
  };
51
45
  /**
52
46
  * Reads configuration a deployment can change without a rebuild.
53
- *
54
- * @useWhen a value must change per deployment without a rebuild
55
- * @insteadOf `import.meta.env` or `window.__APP_CONFIG__` read by hand
56
47
  */
57
48
  export class RuntimeConfig {
58
49
  static get(opts) {
@@ -1,9 +1,6 @@
1
1
  import type { IStorageCodec } from '../common/index.js';
2
2
  /**
3
3
  * The codecs `BrowserStorage` takes, in place of its JSON default.
4
- *
5
- * @useWhen `BrowserStorage` or `useStoredState` needs a codec other than JSON
6
- * @insteadOf hand-written parse and stringify around storage
7
4
  */
8
5
  export declare class StorageCodecs {
9
6
  /** A bare string, not JSON. Create once; outside `allowed`, decode and encode throw. */
@@ -1,9 +1,6 @@
1
1
  import { getError } from '@venizia/ignis-inversion';
2
2
  /**
3
3
  * The codecs `BrowserStorage` takes, in place of its JSON default.
4
- *
5
- * @useWhen `BrowserStorage` or `useStoredState` needs a codec other than JSON
6
- * @insteadOf hand-written parse and stringify around storage
7
4
  */
8
5
  export class StorageCodecs {
9
6
  /** A bare string, not JSON. Create once; outside `allowed`, decode and encode throw. */
@@ -1,9 +1,6 @@
1
1
  import type { TNullable } from '@venizia/ignis-helpers/common';
2
2
  /**
3
3
  * Checks of a value's kind.
4
- *
5
- * @useWhen you check what type a value has
6
- * @insteadOf repeated `typeof` chains
7
4
  */
8
5
  export declare class ValueUtility {
9
6
  /** Positional on purpose: a type predicate narrows its own parameter. */