@eskais/app-sdk 0.1.0 → 0.2.0

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 (90) hide show
  1. package/README.md +17 -11
  2. package/dist/action/action.d.ts +69 -10
  3. package/dist/action/action.js +147 -29
  4. package/dist/action/bulk.d.ts +24 -0
  5. package/dist/action/bulk.js +24 -0
  6. package/dist/core/constants.d.ts +57 -0
  7. package/dist/core/constants.js +31 -0
  8. package/dist/core/contracts.d.ts +7 -0
  9. package/dist/core/data-labels.d.ts +14 -0
  10. package/dist/core/data-labels.js +40 -0
  11. package/dist/core/errors.d.ts +11 -5
  12. package/dist/core/errors.js +52 -9
  13. package/dist/dialogs/dialogs.d.ts +75 -0
  14. package/dist/dialogs/dialogs.js +66 -0
  15. package/dist/errors/adapters.d.ts +21 -0
  16. package/dist/errors/adapters.js +81 -0
  17. package/dist/errors/define-errors.d.ts +88 -0
  18. package/dist/errors/define-errors.js +168 -0
  19. package/dist/errors/idempotency.d.ts +2 -0
  20. package/dist/errors/idempotency.js +13 -0
  21. package/dist/i18n/adapters.d.ts +53 -0
  22. package/dist/i18n/adapters.js +56 -0
  23. package/dist/i18n/format.d.ts +10 -0
  24. package/dist/i18n/format.js +273 -0
  25. package/dist/i18n/labels.d.ts +10 -0
  26. package/dist/i18n/labels.js +227 -0
  27. package/dist/i18n/locale.d.ts +73 -0
  28. package/dist/i18n/locale.js +74 -0
  29. package/dist/i18n/messages.d.ts +93 -0
  30. package/dist/i18n/messages.js +16 -0
  31. package/dist/import/import.d.ts +4 -2
  32. package/dist/import/import.js +7 -4
  33. package/dist/index.d.ts +18 -3
  34. package/dist/index.js +17 -2
  35. package/dist/navigation/nav.d.ts +14 -5
  36. package/dist/navigation/nav.js +37 -14
  37. package/dist/next/server/index.d.ts +2 -1
  38. package/dist/next/server/index.js +2 -1
  39. package/dist/next/server/page.d.ts +8 -2
  40. package/dist/next/server/page.js +14 -7
  41. package/dist/next/server/session.d.ts +13 -0
  42. package/dist/next/server/session.js +13 -0
  43. package/dist/permissions/permissions.d.ts +134 -0
  44. package/dist/permissions/permissions.js +121 -0
  45. package/dist/react/data-layer.d.ts +42 -5
  46. package/dist/react/data-layer.js +49 -4
  47. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  48. package/dist/react/hooks/use-action-dialog.js +31 -0
  49. package/dist/react/hooks/use-action.d.ts +30 -5
  50. package/dist/react/hooks/use-action.js +85 -27
  51. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  52. package/dist/react/hooks/use-bulk-action.js +24 -0
  53. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  54. package/dist/react/hooks/use-dialogs.js +20 -0
  55. package/dist/react/hooks/use-nav.js +3 -2
  56. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  57. package/dist/react/hooks/use-new-rows.js +24 -0
  58. package/dist/react/hooks/use-permissions.d.ts +13 -0
  59. package/dist/react/hooks/use-permissions.js +19 -0
  60. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  61. package/dist/react/hooks/use-reauthenticate.js +11 -0
  62. package/dist/react/hooks/use-resource.d.ts +28 -5
  63. package/dist/react/hooks/use-resource.js +63 -26
  64. package/dist/react/index.d.ts +11 -4
  65. package/dist/react/index.js +11 -4
  66. package/dist/react/keys.d.ts +9 -0
  67. package/dist/react/keys.js +4 -0
  68. package/dist/react/new-rows.d.ts +22 -0
  69. package/dist/react/new-rows.js +72 -0
  70. package/dist/refresh/new-rows.d.ts +13 -0
  71. package/dist/refresh/new-rows.js +18 -0
  72. package/dist/resource/resource-relations.d.ts +6 -3
  73. package/dist/resource/resource-relations.js +26 -13
  74. package/dist/resource/resource-schema.d.ts +1 -1
  75. package/dist/resource/resource-schema.js +1 -1
  76. package/dist/resource/resource-texts.d.ts +18 -0
  77. package/dist/resource/resource-texts.js +13 -0
  78. package/dist/resource/resource-types.d.ts +169 -30
  79. package/dist/resource/resource-words.d.ts +25 -0
  80. package/dist/resource/resource-words.js +221 -0
  81. package/dist/resource/resource.d.ts +6 -2
  82. package/dist/resource/resource.js +99 -173
  83. package/dist/services/read-only-service.d.ts +18 -0
  84. package/dist/services/read-only-service.js +25 -0
  85. package/dist/services/rest-service.d.ts +4 -1
  86. package/dist/services/rest-service.js +2 -0
  87. package/dist/view/view-types.d.ts +4 -2
  88. package/locales/en.json +193 -0
  89. package/locales/es.json +193 -0
  90. package/package.json +5 -2
@@ -0,0 +1,168 @@
1
+ import { ErrorReason, Feedback, Idempotency, Operation } from "../core/constants.js";
2
+ import { isServiceError, reasonOf, ServiceFailure, toServiceError } from "../core/errors.js";
3
+ import { lookup, resolveText } from "../i18n/locale.js";
4
+ import { idempotencyKey } from "./idempotency.js";
5
+ const defaultFeedback = {
6
+ [ErrorReason.network]: Feedback.toast,
7
+ [ErrorReason.timeout]: Feedback.toast,
8
+ [ErrorReason.unauthorized]: Feedback.toast,
9
+ [ErrorReason.sessionExpired]: Feedback.toast,
10
+ [ErrorReason.forbidden]: Feedback.toast,
11
+ [ErrorReason.notFound]: Feedback.toast,
12
+ [ErrorReason.conflict]: Feedback.inline,
13
+ [ErrorReason.validation]: Feedback.inline,
14
+ [ErrorReason.rateLimited]: Feedback.toast,
15
+ [ErrorReason.server]: Feedback.toast,
16
+ [ErrorReason.unknown]: Feedback.toast,
17
+ [ErrorReason.aborted]: Feedback.silent,
18
+ };
19
+ const retriedByDefault = new Set([ErrorReason.network, ErrorReason.timeout, ErrorReason.rateLimited]);
20
+ const reauthReasons = new Set([ErrorReason.unauthorized, ErrorReason.sessionExpired]);
21
+ const needsReauth = (error) => reauthReasons.has(error.reason);
22
+ function backoff(attempt) {
23
+ const base = Math.min(300 * 2 ** attempt, 5000);
24
+ return base / 2 + Math.random() * (base / 2);
25
+ }
26
+ const neverAborts = new AbortController().signal;
27
+ function abortFailure(signal) {
28
+ return new ServiceFailure(toServiceError(signal.reason ?? new DOMException("Aborted", "AbortError")));
29
+ }
30
+ function untilAborted(promise, signal) {
31
+ if (signal === neverAborts)
32
+ return promise;
33
+ return new Promise((resolve, reject) => {
34
+ if (signal.aborted) {
35
+ reject(abortFailure(signal));
36
+ return;
37
+ }
38
+ const stop = () => reject(abortFailure(signal));
39
+ signal.addEventListener("abort", stop, { once: true });
40
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
41
+ });
42
+ }
43
+ function wait(ms, signal) {
44
+ return untilAborted(new Promise((resolve) => {
45
+ const timer = setTimeout(resolve, ms);
46
+ signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
47
+ }), signal);
48
+ }
49
+ /**
50
+ * The app's error policy: how transport errors classify into reasons, how each reason is worded and shown, when calls
51
+ * retry and how an expired session signs in again. Give it to `DataLayer` (`errors`) and every resource call and
52
+ * action goes through it.
53
+ */
54
+ export function defineErrors(options = {}) {
55
+ const handlers = [];
56
+ const attempts = options.retry?.attempts ?? 2;
57
+ const delay = options.retry?.delay ?? backoff;
58
+ let generation = 0;
59
+ let reauthenticating;
60
+ function classify(raw) {
61
+ const adapted = isServiceError(raw) || raw instanceof ServiceFailure ? undefined : adapt(raw);
62
+ const error = adapted ?? toServiceError(raw);
63
+ const coded = error.code === undefined ? undefined : options.codes?.[error.code];
64
+ return { ...error, reason: coded?.reason ?? reasonOf(error) };
65
+ }
66
+ function adapt(raw) {
67
+ for (const adapter of options.adapters ?? []) {
68
+ const error = adapter(raw);
69
+ if (error)
70
+ return error;
71
+ }
72
+ return undefined;
73
+ }
74
+ const codeOf = (error) => (error.code === undefined ? undefined : options.codes?.[error.code]);
75
+ function retries(error, operation, idempotent) {
76
+ if (operation === Operation.mutation && !idempotent)
77
+ return false;
78
+ const said = options.reasons?.[error.reason]?.retry;
79
+ if (said !== undefined)
80
+ return said;
81
+ if (error.reason === ErrorReason.server)
82
+ return error.retryable;
83
+ return retriedByDefault.has(error.reason);
84
+ }
85
+ function reauthenticate(error, startedAt, signal) {
86
+ if (generation !== startedAt)
87
+ return Promise.resolve(true);
88
+ const handler = handlers.at(-1) ?? options.reauthenticate;
89
+ if (!handler)
90
+ return Promise.resolve(false);
91
+ reauthenticating ??= Promise.resolve()
92
+ .then(() => handler(error))
93
+ .then((done) => {
94
+ if (done)
95
+ generation += 1;
96
+ return done;
97
+ }, () => false)
98
+ .finally(() => {
99
+ reauthenticating = undefined;
100
+ });
101
+ return untilAborted(reauthenticating, signal);
102
+ }
103
+ async function run(call, given) {
104
+ const signal = given.signal ?? neverAborts;
105
+ const keyed = given.idempotencyKey ?? (given.idempotency === Idempotency.key ? idempotencyKey() : undefined);
106
+ const idempotent = keyed !== undefined || given.idempotency === Idempotency.idempotent;
107
+ const context = {
108
+ signal,
109
+ ...(given.session === undefined ? {} : { session: given.session }),
110
+ ...(keyed === undefined ? {} : { idempotencyKey: keyed }),
111
+ };
112
+ const attempt = async (tries, reauthed) => {
113
+ if (signal.aborted)
114
+ throw abortFailure(signal);
115
+ const startedAt = generation;
116
+ try {
117
+ return await call(context);
118
+ }
119
+ catch (raw) {
120
+ if (signal.aborted)
121
+ throw abortFailure(signal);
122
+ const error = classify(raw);
123
+ if (error.reason === ErrorReason.aborted)
124
+ throw new ServiceFailure(error);
125
+ if (needsReauth(error) && !reauthed) {
126
+ if (await reauthenticate(error, startedAt, signal))
127
+ return attempt(tries, true);
128
+ }
129
+ else if (tries < attempts && retries(error, given.operation, idempotent)) {
130
+ await wait(delay(tries, error), signal);
131
+ return attempt(tries + 1, reauthed);
132
+ }
133
+ throw new ServiceFailure(error);
134
+ }
135
+ };
136
+ return attempt(0, false);
137
+ }
138
+ return {
139
+ classify,
140
+ text(error, locale, fallback) {
141
+ const own = codeOf(error)?.message ?? options.reasons?.[error.reason]?.message;
142
+ if (own !== undefined)
143
+ return resolveText(own, locale);
144
+ const key = `errors.${error.reason}`;
145
+ return fallback?.[error.reason] ?? lookup(locale, key) ?? key;
146
+ },
147
+ feedback(error, { operation = Operation.query, feedback } = {}) {
148
+ return (feedback ??
149
+ codeOf(error)?.feedback ??
150
+ options.reasons?.[error.reason]?.feedback ??
151
+ (operation === Operation.mutation && error.reason !== ErrorReason.aborted
152
+ ? options.mutations?.error
153
+ : undefined) ??
154
+ defaultFeedback[error.reason]);
155
+ },
156
+ successFeedback: (feedback) => feedback ?? options.mutations?.success ?? Feedback.toast,
157
+ needsReauth,
158
+ onReauthenticate(handler) {
159
+ handlers.push(handler);
160
+ return () => {
161
+ const index = handlers.lastIndexOf(handler);
162
+ if (index !== -1)
163
+ handlers.splice(index, 1);
164
+ };
165
+ },
166
+ run,
167
+ };
168
+ }
@@ -0,0 +1,2 @@
1
+ /** A random idempotency key (a UUID v4), from `crypto.randomUUID` where the page is a secure context. */
2
+ export declare function idempotencyKey(): string;
@@ -0,0 +1,13 @@
1
+ import { ValueType } from "../core/constants.js";
2
+ const hex = (byte) => byte.toString(16).padStart(2, "0");
3
+ /** A random idempotency key (a UUID v4), from `crypto.randomUUID` where the page is a secure context. */
4
+ export function idempotencyKey() {
5
+ if (typeof crypto.randomUUID === ValueType.function)
6
+ return crypto.randomUUID();
7
+ // Spec: RFC 9562 UUID version 4, for an insecure context where `randomUUID` is missing.
8
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
9
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
10
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
11
+ const text = [...bytes].map(hex).join("");
12
+ return `${text.slice(0, 8)}-${text.slice(8, 12)}-${text.slice(12, 16)}-${text.slice(16, 20)}-${text.slice(20)}`;
13
+ }
@@ -0,0 +1,53 @@
1
+ import type { Locale } from "./locale.js";
2
+ export type AdapterOptions = {
3
+ /** The BCP 47 code `Intl` formats numbers and dates with; give it, so the server and the browser agree. */
4
+ locale: string;
5
+ /** Where a key the library lacks comes from: `defineLocale("es", { messages: es })`. */
6
+ base?: Locale;
7
+ };
8
+ /** A value next-intl formats: what `t`'s second argument takes. */
9
+ export type NextIntlValue = string | number | boolean | Date | null | undefined;
10
+ type Bivariant<Call extends (...args: never[]) => unknown> = {
11
+ call(...args: Parameters<Call>): ReturnType<Call>;
12
+ }["call"];
13
+ /** next-intl's `t`, from `useTranslations("eskais")` or `await getTranslations("eskais")`. */
14
+ export type NextIntlTranslator = Bivariant<(key: string, values?: Record<string, NextIntlValue>) => string> & {
15
+ has?: Bivariant<(key: string) => boolean>;
16
+ raw?: Bivariant<(key: string) => unknown>;
17
+ };
18
+ /**
19
+ * next-intl's translator as the App SDK's locale, in a client component (`useTranslations("eskais")`) or on the
20
+ * server (`await getTranslations("eskais")` for `navPage` and `generateMetadata`). next-intl formats the ICU messages
21
+ * itself. Merge the shipped catalog under your namespace in `i18n/request.ts` so every key is there:
22
+ * `messages.eskais = { ...es, ...mine.eskais }`.
23
+ */
24
+ export declare function fromNextIntl(t: NextIntlTranslator, options: AdapterOptions): Locale;
25
+ /** An i18next instance, with `i18next-icu` so it reads ICU MessageFormat. */
26
+ export type I18nextLike = {
27
+ readonly language: string;
28
+ t(key: string, options?: Record<string, unknown>): unknown;
29
+ exists(key: string, options?: Record<string, unknown>): boolean;
30
+ };
31
+ /**
32
+ * An i18next instance as the App SDK's locale. The catalogs are ICU MessageFormat, so add `i18next-icu`. `namespace`
33
+ * is where the App SDK's keys live (`eskais` by default); the locale's code is `i18n.language` unless given.
34
+ */
35
+ export declare function fromI18next(i18n: I18nextLike, options?: Partial<AdapterOptions> & {
36
+ namespace?: string;
37
+ }): Locale;
38
+ /** FormatJS's `IntlShape`, from `createIntl` or react-intl's `useIntl()`. */
39
+ export type IntlShapeLike = {
40
+ readonly locale: string;
41
+ readonly messages: Readonly<Record<string, unknown>>;
42
+ formatMessage(descriptor: {
43
+ id: string;
44
+ }, values?: Record<string, unknown>): string;
45
+ };
46
+ /**
47
+ * FormatJS (react-intl) as the App SDK's locale. FormatJS keys are flat, so the App SDK's are prefixed:
48
+ * `eskais.create`, `eskais.resources.orders.one` (`prefix` changes it; `""` for none).
49
+ */
50
+ export declare function fromIntl(intl: IntlShapeLike, options?: Partial<AdapterOptions> & {
51
+ prefix?: string;
52
+ }): Locale;
53
+ export {};
@@ -0,0 +1,56 @@
1
+ import { isBoolean, isNumber, isRecord, isString } from "../core/guards.js";
2
+ function adapt(code, own, ownHas, base) {
3
+ const has = (key) => ownHas(key) || base?.has(key) === true;
4
+ const t = (key, values) => {
5
+ if (ownHas(key))
6
+ return own(key, values);
7
+ return base ? base.t(key, values) : key;
8
+ };
9
+ return Object.freeze({ code, t, has });
10
+ }
11
+ function nextIntlValues(values) {
12
+ return Object.fromEntries(Object.entries(values).map(([name, value]) => [
13
+ name,
14
+ value === null ||
15
+ value === undefined ||
16
+ value instanceof Date ||
17
+ isString(value) ||
18
+ isNumber(value) ||
19
+ isBoolean(value)
20
+ ? value
21
+ : String(value),
22
+ ]));
23
+ }
24
+ /**
25
+ * next-intl's translator as the App SDK's locale, in a client component (`useTranslations("eskais")`) or on the
26
+ * server (`await getTranslations("eskais")` for `navPage` and `generateMetadata`). next-intl formats the ICU messages
27
+ * itself. Merge the shipped catalog under your namespace in `i18n/request.ts` so every key is there:
28
+ * `messages.eskais = { ...es, ...mine.eskais }`.
29
+ */
30
+ export function fromNextIntl(t, options) {
31
+ const has = (key) => (t.has ? t.has(key) && (t.raw ? isString(t.raw(key)) : true) : true);
32
+ return adapt(options.locale, (key, values) => t(key, values === undefined ? undefined : nextIntlValues(values)), has, options.base);
33
+ }
34
+ /**
35
+ * An i18next instance as the App SDK's locale. The catalogs are ICU MessageFormat, so add `i18next-icu`. `namespace`
36
+ * is where the App SDK's keys live (`eskais` by default); the locale's code is `i18n.language` unless given.
37
+ */
38
+ export function fromI18next(i18n, options = {}) {
39
+ const ns = options.namespace ?? "eskais";
40
+ const own = (key, values) => {
41
+ const text = i18n.t(key, { ...values, ns });
42
+ return isString(text) ? text : key;
43
+ };
44
+ const has = (key) => i18n.exists(key, { ns }) && isString(i18n.t(key, { ns, returnObjects: true }));
45
+ return adapt(options.locale ?? i18n.language, own, has, options.base);
46
+ }
47
+ /**
48
+ * FormatJS (react-intl) as the App SDK's locale. FormatJS keys are flat, so the App SDK's are prefixed:
49
+ * `eskais.create`, `eskais.resources.orders.one` (`prefix` changes it; `""` for none).
50
+ */
51
+ export function fromIntl(intl, options = {}) {
52
+ const prefix = options.prefix ?? "eskais";
53
+ const id = (key) => (prefix === "" ? key : `${prefix}.${key}`);
54
+ const has = (key) => isRecord(intl.messages) && id(key) in intl.messages;
55
+ return adapt(options.locale ?? intl.locale, (key, values) => intl.formatMessage({ id: id(key) }, values === undefined ? undefined : { ...values }), has, options.base);
56
+ }
@@ -0,0 +1,10 @@
1
+ /** The values a message's arguments read: `{ one: "pedido", gender: "m", count: 3 }`. */
2
+ export type MessageValues = Readonly<Record<string, unknown>>;
3
+ /**
4
+ * Formats an ICU MessageFormat message in `code`'s language: `{name}`, `{n, number}` (`integer`, `percent`),
5
+ * `{d, date, short}` and `{d, time, short}`, `{n, plural, =0 {…} one {# item} other {# items}}` (with `offset:`),
6
+ * `{n, selectordinal, …}` and `{gender, select, f {…} other {…}}`. Quotes escape as in ICU: `''` and `'{literal}'`.
7
+ */
8
+ export declare function formatMessage(message: string, values?: MessageValues, code?: string): string;
9
+ /** Throws a `SyntaxError` that says where, when `message` isn't valid ICU MessageFormat. */
10
+ export declare function checkMessage(message: string): void;
@@ -0,0 +1,273 @@
1
+ import { isNumber, isOneOf, isRecord, isString, valuesOf } from "../core/guards.js";
2
+ const PartKind = {
3
+ argument: "argument",
4
+ number: "number",
5
+ date: "date",
6
+ time: "time",
7
+ plural: "plural",
8
+ selectordinal: "selectordinal",
9
+ select: "select",
10
+ pound: "pound",
11
+ };
12
+ const Other = "other";
13
+ const Offset = "offset:";
14
+ const Exact = "=";
15
+ const formatKinds = new Map([
16
+ [PartKind.number, PartKind.number],
17
+ [PartKind.date, PartKind.date],
18
+ [PartKind.time, PartKind.time],
19
+ [PartKind.plural, PartKind.plural],
20
+ [PartKind.selectordinal, PartKind.selectordinal],
21
+ [PartKind.select, PartKind.select],
22
+ ]);
23
+ const Brace = { open: "{", close: "}" };
24
+ const Quote = "'";
25
+ const Pound = "#";
26
+ const Comma = ",";
27
+ class Parser {
28
+ source;
29
+ at = 0;
30
+ constructor(source) {
31
+ this.source = source;
32
+ }
33
+ fail(what) {
34
+ throw new SyntaxError(`${what} at ${String(this.at)} in the message "${this.source}".`);
35
+ }
36
+ spaces() {
37
+ while (/\s/u.test(this.source[this.at] ?? ""))
38
+ this.at += 1;
39
+ }
40
+ word() {
41
+ this.spaces();
42
+ const start = this.at;
43
+ while (this.at < this.source.length && !/[\s{},]/u.test(this.source[this.at]))
44
+ this.at += 1;
45
+ if (start === this.at)
46
+ this.fail("Expected a name");
47
+ return this.source.slice(start, this.at);
48
+ }
49
+ expect(char) {
50
+ this.spaces();
51
+ if (this.source[this.at] !== char)
52
+ this.fail(`Expected "${char}"`);
53
+ this.at += 1;
54
+ }
55
+ quoted(inPlural) {
56
+ const next = this.source[this.at + 1];
57
+ if (next === Quote) {
58
+ this.at += 2;
59
+ return Quote;
60
+ }
61
+ const special = next === Brace.open || next === Brace.close || (inPlural && next === Pound);
62
+ if (!special)
63
+ return undefined;
64
+ const close = this.source.indexOf(Quote, this.at + 1);
65
+ const end = close === -1 ? this.source.length : close;
66
+ const text = this.source.slice(this.at + 1, end);
67
+ this.at = end + 1;
68
+ return text;
69
+ }
70
+ message(inPlural, nested) {
71
+ const parts = [];
72
+ let text = "";
73
+ const flush = () => {
74
+ if (text !== "")
75
+ parts.push(text);
76
+ text = "";
77
+ };
78
+ while (this.at < this.source.length) {
79
+ const char = this.source[this.at];
80
+ if (char === Brace.close) {
81
+ if (nested)
82
+ break;
83
+ this.fail("Unexpected }");
84
+ }
85
+ if (char === Brace.open) {
86
+ flush();
87
+ parts.push(this.argument(inPlural));
88
+ continue;
89
+ }
90
+ if (char === Pound && inPlural) {
91
+ flush();
92
+ parts.push({ kind: PartKind.pound });
93
+ this.at += 1;
94
+ continue;
95
+ }
96
+ if (char === Quote) {
97
+ const literal = this.quoted(inPlural);
98
+ if (literal !== undefined) {
99
+ text += literal;
100
+ continue;
101
+ }
102
+ }
103
+ text += char;
104
+ this.at += 1;
105
+ }
106
+ flush();
107
+ return parts;
108
+ }
109
+ branches(inPlural) {
110
+ const found = {};
111
+ this.spaces();
112
+ while (this.source[this.at] !== Brace.close) {
113
+ const key = this.word();
114
+ this.expect(Brace.open);
115
+ found[key] = this.message(inPlural, true);
116
+ this.expect(Brace.close);
117
+ this.spaces();
118
+ if (this.at >= this.source.length)
119
+ this.fail("Expected }");
120
+ }
121
+ if (!(Other in found))
122
+ this.fail("Expected an other branch");
123
+ return found;
124
+ }
125
+ argument(inPlural) {
126
+ this.expect(Brace.open);
127
+ const name = this.word();
128
+ this.spaces();
129
+ if (this.source[this.at] === Brace.close) {
130
+ this.at += 1;
131
+ return { kind: PartKind.argument, name };
132
+ }
133
+ this.expect(Comma);
134
+ const type = this.word();
135
+ const kind = formatKinds.get(type) ?? this.fail(`Unknown format "${type}"`);
136
+ this.spaces();
137
+ if (kind === PartKind.select || kind === PartKind.plural || kind === PartKind.selectordinal) {
138
+ this.expect(Comma);
139
+ this.spaces();
140
+ let offset = 0;
141
+ if (this.source.startsWith(Offset, this.at)) {
142
+ this.at += Offset.length;
143
+ offset = Number(this.word());
144
+ }
145
+ const branches = this.branches(kind === PartKind.select ? inPlural : true);
146
+ this.expect(Brace.close);
147
+ return kind === PartKind.select ? { kind, name, branches } : { kind, name, offset, branches };
148
+ }
149
+ if (kind !== PartKind.number && kind !== PartKind.date && kind !== PartKind.time)
150
+ this.fail("Unexpected format");
151
+ let style = "";
152
+ if (this.source[this.at] === Comma) {
153
+ this.at += 1;
154
+ style = this.word();
155
+ }
156
+ this.expect(Brace.close);
157
+ return { kind, name, style };
158
+ }
159
+ }
160
+ const parsed = new Map();
161
+ function parse(source) {
162
+ const known = parsed.get(source);
163
+ if (known)
164
+ return known;
165
+ const parts = source.includes(Brace.open) || source.includes(Quote) ? new Parser(source).message(false, false) : [source];
166
+ parsed.set(source, parts);
167
+ return parts;
168
+ }
169
+ const intl = new Map();
170
+ function cached(key, make, is) {
171
+ const known = intl.get(key);
172
+ if (is(known))
173
+ return known;
174
+ const made = make();
175
+ intl.set(key, made);
176
+ return made;
177
+ }
178
+ const isNumberFormat = (value) => value instanceof Intl.NumberFormat;
179
+ const isDateFormat = (value) => value instanceof Intl.DateTimeFormat;
180
+ const isPluralRules = (value) => value instanceof Intl.PluralRules;
181
+ const NumberStyle = { integer: "integer", percent: "percent" };
182
+ const DateStyle = { short: "short", medium: "medium", long: "long", full: "full" };
183
+ const dateStyles = valuesOf(DateStyle);
184
+ const PluralType = { cardinal: "cardinal", ordinal: "ordinal" };
185
+ function numberFormat(code, style) {
186
+ const options = style === NumberStyle.integer
187
+ ? { maximumFractionDigits: 0 }
188
+ : style === NumberStyle.percent
189
+ ? { style: NumberStyle.percent }
190
+ : {};
191
+ return cached(`n|${code}|${style}`, () => new Intl.NumberFormat(code, options), isNumberFormat);
192
+ }
193
+ function dateFormat(code, kind, style) {
194
+ const chosen = isOneOf(dateStyles, style) ? style : DateStyle.medium;
195
+ const options = kind === PartKind.date ? { dateStyle: chosen } : { timeStyle: chosen };
196
+ return cached(`${kind}|${code}|${chosen}`, () => new Intl.DateTimeFormat(code, options), isDateFormat);
197
+ }
198
+ function plurals(code, ordinal) {
199
+ const type = ordinal ? PluralType.ordinal : PluralType.cardinal;
200
+ return cached(`p|${code}|${type}`, () => new Intl.PluralRules(code, { type }), isPluralRules);
201
+ }
202
+ function toDate(value) {
203
+ if (value instanceof Date)
204
+ return value;
205
+ if (isNumber(value) || isString(value)) {
206
+ const date = new Date(value);
207
+ return Number.isNaN(date.getTime()) ? undefined : date;
208
+ }
209
+ return undefined;
210
+ }
211
+ function plain(value, code) {
212
+ if (isNumber(value))
213
+ return numberFormat(code, "").format(value);
214
+ if (value instanceof Date)
215
+ return dateFormat(code, PartKind.date, DateStyle.medium).format(value);
216
+ if (value === undefined || value === null)
217
+ return "";
218
+ if (isString(value))
219
+ return value;
220
+ if (isRecord(value) || Array.isArray(value))
221
+ return JSON.stringify(value);
222
+ return String(value);
223
+ }
224
+ function render(parts, values, code, pound) {
225
+ let out = "";
226
+ for (const part of parts) {
227
+ if (isString(part)) {
228
+ out += part;
229
+ continue;
230
+ }
231
+ if (part.kind === PartKind.pound) {
232
+ out += pound === undefined ? Pound : numberFormat(code, "").format(pound);
233
+ continue;
234
+ }
235
+ const value = values[part.name];
236
+ if (part.kind === PartKind.argument)
237
+ out += plain(value, code);
238
+ else if (part.kind === PartKind.number || part.kind === PartKind.date || part.kind === PartKind.time) {
239
+ const date = part.kind === PartKind.number ? undefined : toDate(value);
240
+ if (part.kind === PartKind.number)
241
+ out += isNumber(value) ? numberFormat(code, part.style).format(value) : plain(value, code);
242
+ else
243
+ out += date ? dateFormat(code, part.kind, part.style).format(date) : plain(value, code);
244
+ }
245
+ else if (part.kind === PartKind.select) {
246
+ const branch = part.branches[plain(value, code)] ?? part.branches[Other] ?? [];
247
+ out += render(branch, values, code, pound);
248
+ }
249
+ else {
250
+ const count = Number(value);
251
+ const exact = part.branches[`${Exact}${String(count)}`];
252
+ const shifted = count - part.offset;
253
+ const branch = exact ??
254
+ part.branches[plurals(code, part.kind === PartKind.selectordinal).select(shifted)] ??
255
+ part.branches[Other] ??
256
+ [];
257
+ out += render(branch, values, code, shifted);
258
+ }
259
+ }
260
+ return out;
261
+ }
262
+ /**
263
+ * Formats an ICU MessageFormat message in `code`'s language: `{name}`, `{n, number}` (`integer`, `percent`),
264
+ * `{d, date, short}` and `{d, time, short}`, `{n, plural, =0 {…} one {# item} other {# items}}` (with `offset:`),
265
+ * `{n, selectordinal, …}` and `{gender, select, f {…} other {…}}`. Quotes escape as in ICU: `''` and `'{literal}'`.
266
+ */
267
+ export function formatMessage(message, values = {}, code = "en") {
268
+ return render(parse(message), values, code, undefined);
269
+ }
270
+ /** Throws a `SyntaxError` that says where, when `message` isn't valid ICU MessageFormat. */
271
+ export function checkMessage(message) {
272
+ parse(message);
273
+ }
@@ -0,0 +1,10 @@
1
+ import type { DataLabels } from "../core/data-labels.js";
2
+ import { Gender } from "./messages.js";
3
+ import { type Locale } from "./locale.js";
4
+ /**
5
+ * The `DataLabels` the blocks read, from a locale's messages. Messages about a resource get its `gender` too
6
+ * (`Gender.feminine`, `"f"`), for a `select`; `{one}` and `{other}` are its name in lower case, `{One}` and `{Other}`
7
+ * as written.
8
+ */
9
+ export declare function dataLabelsOf(locale: Locale, gender?: string): DataLabels;
10
+ export { Gender };