@hamur/i18n 0.0.0-stage → 0.0.2

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 (155) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/bun-index-1ve1hj66.js +744 -0
  4. package/dist/chunks/bun-index-8bw4xpv8.js +93 -0
  5. package/dist/chunks/bun-index-ej6vjnjs.js +297 -0
  6. package/dist/chunks/bun-index-pdepkyy1.js +474 -0
  7. package/dist/src/adapters/angular.js +67 -0
  8. package/dist/src/adapters/html.js +34 -0
  9. package/dist/src/adapters/preact.js +23 -0
  10. package/dist/src/adapters/react.js +23 -0
  11. package/dist/src/adapters/solid.js +48 -0
  12. package/dist/src/adapters/svelte.js +74 -0
  13. package/dist/src/adapters/vue.js +48 -0
  14. package/dist/src/cli.js +1898 -0
  15. package/dist/src/index.js +2755 -0
  16. package/dist/src/load.js +35 -0
  17. package/dist/src/server/index.js +395 -0
  18. package/dist/types/src/adapters/angular.d.ts +20 -0
  19. package/dist/types/src/adapters/bind.d.ts +44 -0
  20. package/dist/types/src/adapters/html.d.ts +5 -0
  21. package/dist/types/src/adapters/preact.d.ts +6 -0
  22. package/dist/types/src/adapters/react.d.ts +6 -0
  23. package/dist/types/src/adapters/solid.d.ts +9 -0
  24. package/dist/types/src/adapters/svelte.d.ts +12 -0
  25. package/dist/types/src/adapters/vue.d.ts +8 -0
  26. package/dist/types/src/build/catalog.d.ts +5 -0
  27. package/dist/types/src/build/drop.d.ts +12 -0
  28. package/dist/types/src/build/extract.d.ts +11 -0
  29. package/dist/types/src/build/head.d.ts +4 -0
  30. package/dist/types/src/build/messages.d.ts +27 -0
  31. package/dist/types/src/build/prerender.d.ts +10 -0
  32. package/dist/types/src/build/routes.d.ts +14 -0
  33. package/dist/types/src/build/split.d.ts +37 -0
  34. package/dist/types/src/build/types.d.ts +15 -0
  35. package/dist/types/src/cli.d.ts +12 -0
  36. package/dist/types/src/compiler/compile.d.ts +17 -0
  37. package/dist/types/src/compiler/mf2-parse.d.ts +62 -0
  38. package/dist/types/src/compiler/mf2.d.ts +3 -0
  39. package/dist/types/src/compiler/parse.d.ts +58 -0
  40. package/dist/types/src/compiler/skeleton.d.ts +7 -0
  41. package/dist/types/src/index.d.ts +2 -0
  42. package/dist/types/src/load.d.ts +7 -0
  43. package/dist/types/src/module.d.ts +15 -0
  44. package/dist/types/src/options.d.ts +7 -0
  45. package/dist/types/src/runtime/catalog-client.d.ts +3 -0
  46. package/dist/types/src/runtime/catalog-loader.d.ts +15 -0
  47. package/dist/types/src/runtime/catalog-server.d.ts +5 -0
  48. package/dist/types/src/runtime/catalog.d.ts +60 -0
  49. package/dist/types/src/runtime/chain.d.ts +3 -0
  50. package/dist/types/src/runtime/format.d.ts +27 -0
  51. package/dist/types/src/runtime/head.d.ts +9 -0
  52. package/dist/types/src/runtime/interpret.d.ts +20 -0
  53. package/dist/types/src/runtime/link.d.ts +8 -0
  54. package/dist/types/src/runtime/locale.d.ts +73 -0
  55. package/dist/types/src/runtime/match.d.ts +54 -0
  56. package/dist/types/src/runtime/messages.d.ts +42 -0
  57. package/dist/types/src/runtime/middleware.d.ts +2 -0
  58. package/dist/types/src/runtime/negotiate.d.ts +9 -0
  59. package/dist/types/src/runtime/plugin.d.ts +4 -0
  60. package/dist/types/src/runtime/redirect.d.ts +32 -0
  61. package/dist/types/src/runtime/rich.d.ts +5 -0
  62. package/dist/types/src/runtime/translate.d.ts +21 -0
  63. package/dist/types/src/server/catalog.d.ts +2 -0
  64. package/dist/types/src/server/context.d.ts +48 -0
  65. package/dist/types/src/server/door-all-catalog.d.ts +3 -0
  66. package/dist/types/src/server/door-all.d.ts +2 -0
  67. package/dist/types/src/server/door-catalog.d.ts +3 -0
  68. package/dist/types/src/server/door-root-catalog.d.ts +3 -0
  69. package/dist/types/src/server/door-root.d.ts +2 -0
  70. package/dist/types/src/server/door.d.ts +2 -0
  71. package/dist/types/src/server/index.d.ts +7 -0
  72. package/dist/types/src/server/preferred.d.ts +6 -0
  73. package/dist/types/src/server/redirect.d.ts +3 -0
  74. package/dist/types/src/server/setup.d.ts +2 -0
  75. package/dist/types/src/types.d.ts +163 -0
  76. package/package.json +155 -4
  77. package/src/adapters/angular.ts +58 -0
  78. package/src/adapters/bind.ts +144 -0
  79. package/src/adapters/html.ts +35 -0
  80. package/src/adapters/preact.ts +18 -0
  81. package/src/adapters/react.ts +18 -0
  82. package/src/adapters/solid.ts +44 -0
  83. package/src/adapters/svelte.ts +75 -0
  84. package/src/adapters/test/SveltePage.svelte +18 -0
  85. package/src/adapters/test/SvelteReporting.svelte +20 -0
  86. package/src/adapters/test/SvelteRich.svelte +11 -0
  87. package/src/adapters/test/SvelteRichPlain.svelte +11 -0
  88. package/src/adapters/test/peer.ts +7 -0
  89. package/src/adapters/test/preact-client.ts +43 -0
  90. package/src/adapters/test/preact-page.ts +34 -0
  91. package/src/adapters/test/preact-rich.ts +9 -0
  92. package/src/adapters/test/react-client.ts +49 -0
  93. package/src/adapters/test/react-page.ts +34 -0
  94. package/src/adapters/test/react-rich.ts +15 -0
  95. package/src/adapters/test/runtime.ts +104 -0
  96. package/src/adapters/test/solid-client.ts +33 -0
  97. package/src/adapters/test/solid-page.ts +30 -0
  98. package/src/adapters/test/solid-rich.ts +5 -0
  99. package/src/adapters/test/svelte-client.ts +51 -0
  100. package/src/adapters/test/svelte-log.ts +2 -0
  101. package/src/adapters/test/svelte-plugin.ts +20 -0
  102. package/src/adapters/test/vue-page.ts +26 -0
  103. package/src/adapters/test/vue-rich.ts +16 -0
  104. package/src/adapters/vue.ts +44 -0
  105. package/src/build/catalog.ts +44 -0
  106. package/src/build/drop.ts +36 -0
  107. package/src/build/extract.ts +207 -0
  108. package/src/build/head.ts +10 -0
  109. package/src/build/messages.ts +347 -0
  110. package/src/build/prerender.ts +48 -0
  111. package/src/build/routes.ts +269 -0
  112. package/src/build/split.ts +240 -0
  113. package/src/build/types.ts +156 -0
  114. package/src/cli.ts +25 -0
  115. package/src/compiler/compile.ts +190 -0
  116. package/src/compiler/mf2-parse.ts +469 -0
  117. package/src/compiler/mf2.ts +393 -0
  118. package/src/compiler/parse.ts +265 -0
  119. package/src/compiler/skeleton.ts +85 -0
  120. package/src/env.d.ts +55 -0
  121. package/src/index.ts +24 -0
  122. package/src/load.ts +41 -0
  123. package/src/module.ts +66 -0
  124. package/src/options.ts +198 -0
  125. package/src/runtime/catalog-client.ts +28 -0
  126. package/src/runtime/catalog-loader.ts +28 -0
  127. package/src/runtime/catalog-server.ts +36 -0
  128. package/src/runtime/catalog.ts +190 -0
  129. package/src/runtime/chain.ts +9 -0
  130. package/src/runtime/format.ts +102 -0
  131. package/src/runtime/head.ts +57 -0
  132. package/src/runtime/interpret.ts +504 -0
  133. package/src/runtime/link.ts +36 -0
  134. package/src/runtime/locale.ts +392 -0
  135. package/src/runtime/match.ts +334 -0
  136. package/src/runtime/messages.ts +129 -0
  137. package/src/runtime/middleware.ts +32 -0
  138. package/src/runtime/negotiate.ts +61 -0
  139. package/src/runtime/plugin.ts +69 -0
  140. package/src/runtime/redirect.ts +191 -0
  141. package/src/runtime/rich.ts +21 -0
  142. package/src/runtime/translate.ts +131 -0
  143. package/src/server/catalog.ts +11 -0
  144. package/src/server/context.ts +191 -0
  145. package/src/server/door-all-catalog.ts +7 -0
  146. package/src/server/door-all.ts +5 -0
  147. package/src/server/door-catalog.ts +6 -0
  148. package/src/server/door-root-catalog.ts +7 -0
  149. package/src/server/door-root.ts +5 -0
  150. package/src/server/door.ts +4 -0
  151. package/src/server/index.ts +11 -0
  152. package/src/server/preferred.ts +12 -0
  153. package/src/server/redirect.ts +26 -0
  154. package/src/server/setup.ts +14 -0
  155. package/src/types.ts +182 -0
@@ -0,0 +1,744 @@
1
+ // @bun
2
+ // packages/i18n/src/compiler/skeleton.ts
3
+ var WIDTHS = { short: "short", narrow: "narrow", "full-name": "long" };
4
+ function supportedUnit(unit) {
5
+ try {
6
+ new Intl.NumberFormat("en", { style: "unit", unit });
7
+ return true;
8
+ } catch {
9
+ return false;
10
+ }
11
+ }
12
+ function parseSkeleton(source, offset) {
13
+ const options = {};
14
+ let scale;
15
+ let percent = false;
16
+ let unit;
17
+ let currency;
18
+ let width;
19
+ const fail = (at, reason) => {
20
+ throw new MessageSyntaxError(at, reason);
21
+ };
22
+ for (const match of source.matchAll(/\S+/g)) {
23
+ const token = match[0];
24
+ const at = offset + match.index;
25
+ const stem = () => fail(at, 'number skeleton stem "' + token.split("/")[0] + '" is not supported');
26
+ let found;
27
+ if (token === "percent") {
28
+ options.style = "percent";
29
+ percent = true;
30
+ } else if (token === "compact-short" || token === "compact-long") {
31
+ options.notation = "compact";
32
+ options.compactDisplay = token === "compact-short" ? "short" : "long";
33
+ } else if (token.startsWith("unit/")) {
34
+ unit = token.slice(5);
35
+ if (!unit || !supportedUnit(unit))
36
+ fail(at, 'number skeleton unit "' + unit + '" is not supported');
37
+ } else if (token.startsWith("currency/")) {
38
+ currency = token.slice(9);
39
+ if (!/^[A-Za-z]{3}$/.test(currency))
40
+ fail(at, 'number skeleton currency "' + currency + '" is not a three-letter code');
41
+ currency = currency.toUpperCase();
42
+ } else if (token.startsWith("scale/")) {
43
+ scale = Number(token.slice(6));
44
+ if (token.length === 6 || !Number.isFinite(scale))
45
+ fail(at, 'number skeleton scale "' + token.slice(6) + '" is not a number');
46
+ } else if (token.startsWith("unit-width-")) {
47
+ const value = token.slice(11);
48
+ if (!Object.hasOwn(WIDTHS, value))
49
+ stem();
50
+ width = { token, value, at };
51
+ } else if ((found = /^\.(0*)(#*)$/.exec(token)) && token.length > 1) {
52
+ options.minimumFractionDigits = found[1].length;
53
+ options.maximumFractionDigits = found[1].length + found[2].length;
54
+ } else if (token === "sign-always")
55
+ options.signDisplay = "always";
56
+ else if (token === "group-off")
57
+ options.useGrouping = false;
58
+ else if (token === "integer")
59
+ options.maximumFractionDigits = 0;
60
+ else
61
+ stem();
62
+ }
63
+ if (unit !== undefined && currency !== undefined)
64
+ fail(offset, "number skeleton cannot hold both unit/<unit> and currency/<code>");
65
+ if (unit !== undefined) {
66
+ options.style = "unit";
67
+ options.unit = unit;
68
+ if (width)
69
+ options.unitDisplay = WIDTHS[width.value];
70
+ } else if (currency !== undefined) {
71
+ options.style = "currency";
72
+ options.currency = currency;
73
+ if (width) {
74
+ if (width.value !== "narrow")
75
+ fail(width.at, 'number skeleton stem "' + width.token + '" is not supported');
76
+ options.currencyDisplay = "narrowSymbol";
77
+ }
78
+ } else if (width)
79
+ fail(width.at, 'number skeleton "' + width.token + '" needs a unit/<unit> or currency/<code> stem');
80
+ if (percent && scale === 100)
81
+ scale = undefined;
82
+ return scale === undefined ? { options } : { options, scale };
83
+ }
84
+
85
+ // packages/i18n/src/compiler/parse.ts
86
+ class MessageSyntaxError extends Error {
87
+ offset;
88
+ reason;
89
+ constructor(offset, reason) {
90
+ super(`${reason} (column ${offset + 1})`);
91
+ this.offset = offset;
92
+ this.reason = reason;
93
+ this.name = "MessageSyntaxError";
94
+ }
95
+ }
96
+ var PLURAL_CATEGORIES = ["zero", "one", "two", "few", "many", "other"];
97
+ var DATE_STYLES = ["short", "medium", "long", "full"];
98
+ var EXACT = /^=\d+$/;
99
+ var OPEN_TAG = /<([A-Za-z][A-Za-z0-9_-]*)(\/?)>/y;
100
+ var CLOSE_TAG = /<\/([A-Za-z][A-Za-z0-9_-]*)>/y;
101
+ function parseMessage(source) {
102
+ let i = 0;
103
+ const fail = (offset, reason) => {
104
+ throw new MessageSyntaxError(offset, reason);
105
+ };
106
+ const skipSpace = () => {
107
+ while (i < source.length && /\s/.test(source[i]))
108
+ i++;
109
+ };
110
+ const peek = (pattern) => {
111
+ pattern.lastIndex = i;
112
+ return pattern.exec(source);
113
+ };
114
+ const read = (pattern) => {
115
+ pattern.lastIndex = i;
116
+ const found = pattern.exec(source);
117
+ if (!found)
118
+ return "";
119
+ i += found[0].length;
120
+ return found[0];
121
+ };
122
+ function nodes(closer, openAt, inPlural, tag) {
123
+ const out = [];
124
+ let text = "";
125
+ const flush = () => {
126
+ if (text)
127
+ out.push({ type: "text", value: text });
128
+ text = "";
129
+ };
130
+ while (i < source.length) {
131
+ const c = source[i];
132
+ if (c === "{") {
133
+ flush();
134
+ out.push(argument(inPlural));
135
+ } else if (c === "}") {
136
+ if (tag)
137
+ fail(tag.at, "tag <" + tag.name + "> is not closed");
138
+ if (!closer)
139
+ fail(i, 'unmatched "}"');
140
+ flush();
141
+ return out;
142
+ } else if (c === "<" && peek(OPEN_TAG)) {
143
+ const found = peek(OPEN_TAG);
144
+ flush();
145
+ const at = i;
146
+ i += found[0].length;
147
+ const name = found[1];
148
+ out.push({ type: "tag", name, children: found[2] ? [] : nodes(closer, openAt, inPlural, { name, at }) });
149
+ } else if (c === "<" && peek(CLOSE_TAG)) {
150
+ const found = peek(CLOSE_TAG);
151
+ if (!tag)
152
+ fail(i, "closing tag </" + found[1] + "> has no opening tag");
153
+ if (found[1] !== tag.name)
154
+ fail(tag.at, "tag <" + tag.name + "> is not closed");
155
+ flush();
156
+ i += found[0].length;
157
+ return out;
158
+ } else if (c === "#" && inPlural) {
159
+ flush();
160
+ out.push({ type: "pound" });
161
+ i++;
162
+ } else if (c === "'") {
163
+ const next = source[i + 1];
164
+ if (next === "'") {
165
+ text += "'";
166
+ i += 2;
167
+ } else if (next === "{" || next === "}" || next === "#" && inPlural) {
168
+ i++;
169
+ while (i < source.length) {
170
+ if (source[i] === "'") {
171
+ if (source[i + 1] === "'") {
172
+ text += "'";
173
+ i += 2;
174
+ continue;
175
+ }
176
+ i++;
177
+ break;
178
+ }
179
+ text += source[i++];
180
+ }
181
+ } else {
182
+ text += c;
183
+ i++;
184
+ }
185
+ } else {
186
+ text += c;
187
+ i++;
188
+ }
189
+ }
190
+ if (tag)
191
+ fail(tag.at, "tag <" + tag.name + "> is not closed");
192
+ if (closer)
193
+ fail(openAt, 'unclosed "{"');
194
+ flush();
195
+ return out;
196
+ }
197
+ function argument(inPlural) {
198
+ const openAt = i++;
199
+ skipSpace();
200
+ const name = read(/[^\s,{}]+/y);
201
+ if (!name)
202
+ fail(i, i >= source.length ? 'unclosed "{"' : "expected an argument name");
203
+ skipSpace();
204
+ if (i >= source.length)
205
+ fail(openAt, 'unclosed "{"');
206
+ if (source[i] === "}") {
207
+ i++;
208
+ return { type: "arg", name };
209
+ }
210
+ if (source[i] !== ",")
211
+ fail(i, `expected "," or "}" after "${name}"`);
212
+ i++;
213
+ skipSpace();
214
+ const typeAt = i;
215
+ const type = read(/[A-Za-z]+/y);
216
+ if (!type)
217
+ fail(i, i >= source.length ? 'unclosed "{"' : "expected an argument type");
218
+ skipSpace();
219
+ if (type === "number" || type === "date" || type === "time")
220
+ return simple(name, type, openAt);
221
+ if (type === "plural" || type === "selectordinal" || type === "select") {
222
+ if (i >= source.length)
223
+ fail(openAt, 'unclosed "{"');
224
+ if (source[i] !== ",")
225
+ fail(i, `expected "," after "${type}"`);
226
+ i++;
227
+ return choice(name, type, openAt, inPlural);
228
+ }
229
+ return fail(typeAt, `unknown argument type "${type}"`);
230
+ }
231
+ function simple(name, type, openAt) {
232
+ let style = "";
233
+ let styleAt = i;
234
+ if (source[i] === ",") {
235
+ i++;
236
+ skipSpace();
237
+ styleAt = i;
238
+ style = read(/[^}]*/y).trim();
239
+ }
240
+ if (source[i] !== "}")
241
+ fail(openAt, 'unclosed "{"');
242
+ i++;
243
+ if (type === "number") {
244
+ if (style === "")
245
+ return { type: "number", name, style: "decimal" };
246
+ if (style === "integer" || style === "percent")
247
+ return { type: "number", name, style };
248
+ if (style.startsWith("::")) {
249
+ const currency = /^::currency\/([A-Za-z]{3})$/.exec(style);
250
+ if (currency)
251
+ return { type: "number", name, style: "currency", currency: currency[1].toUpperCase() };
252
+ const { options, scale } = parseSkeleton(style.slice(2), styleAt + 2);
253
+ return scale === undefined ? { type: "number", name, style: "skeleton", options } : { type: "number", name, style: "skeleton", options, scale };
254
+ }
255
+ return fail(styleAt, `unknown number style "${style}"`);
256
+ }
257
+ if (style !== "" && !DATE_STYLES.includes(style))
258
+ fail(styleAt, `unknown ${type} style "${style}"`);
259
+ return { type: "date", name, kind: type, style: style || "medium" };
260
+ }
261
+ function choice(name, type, openAt, inPlural) {
262
+ const cases = [];
263
+ const seen = new Set;
264
+ let offset = 0;
265
+ while (true) {
266
+ skipSpace();
267
+ if (i >= source.length)
268
+ fail(openAt, 'unclosed "{"');
269
+ if (source[i] === "}") {
270
+ i++;
271
+ break;
272
+ }
273
+ const keyAt = i;
274
+ if (source.startsWith("offset:", i)) {
275
+ if (type !== "plural")
276
+ fail(i, '"offset" is only valid in a plural');
277
+ i += 7;
278
+ skipSpace();
279
+ const digits = read(/\d+/y);
280
+ if (!digits)
281
+ fail(i, "offset must be an integer");
282
+ offset = Number(digits);
283
+ continue;
284
+ }
285
+ const key = read(/[^\s{}]+/y);
286
+ if (!key)
287
+ fail(i, "expected a case key");
288
+ if (type !== "select" && !EXACT.test(key) && !PLURAL_CATEGORIES.includes(key)) {
289
+ fail(keyAt, `"${key}" is not a plural case; use =<integer>, zero, one, two, few, many or other`);
290
+ }
291
+ if (seen.has(key))
292
+ fail(keyAt, `duplicate case "${key}"`);
293
+ seen.add(key);
294
+ skipSpace();
295
+ if (source[i] !== "{")
296
+ fail(i, `expected "{" after case "${key}"`);
297
+ const bodyAt = i++;
298
+ const body = nodes(true, bodyAt, type !== "select" || inPlural);
299
+ i++;
300
+ cases.push({ key, body });
301
+ }
302
+ if (!seen.has("other"))
303
+ fail(openAt, `${type} needs an "other" case`);
304
+ return type === "select" ? { type: "select", name, cases } : { type: "plural", name, ordinal: type === "selectordinal", offset, cases };
305
+ }
306
+ return nodes(false, 0, false);
307
+ }
308
+
309
+ // packages/i18n/src/compiler/mf2-parse.ts
310
+ var NUMBER_OPTIONS = [
311
+ "select",
312
+ "signDisplay",
313
+ "useGrouping",
314
+ "minimumIntegerDigits",
315
+ "minimumFractionDigits",
316
+ "maximumFractionDigits",
317
+ "minimumSignificantDigits",
318
+ "maximumSignificantDigits",
319
+ "trailingZeroDisplay",
320
+ "roundingPriority",
321
+ "roundingIncrement",
322
+ "roundingMode"
323
+ ];
324
+ var INTEGER_OPTIONS = ["select", "signDisplay", "useGrouping", "minimumIntegerDigits", "maximumSignificantDigits"];
325
+ var FUNCTIONS = {
326
+ string: [],
327
+ number: NUMBER_OPTIONS,
328
+ integer: INTEGER_OPTIONS,
329
+ datetime: ["dateFields", "dateLength", "timePrecision", "timeZoneStyle", "timeZone", "hour12", "calendar"],
330
+ date: ["fields", "length", "timeZone", "calendar"],
331
+ time: ["precision", "timeZoneStyle", "timeZone", "hour12", "calendar"]
332
+ };
333
+ var isBidi = (c) => c === 1564 || c === 8206 || c === 8207 || c >= 8294 && c <= 8297;
334
+ var isWs = (c) => c === 32 || c === 9 || c === 13 || c === 10 || c === 12288;
335
+ function isNameStart(c) {
336
+ if (c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 43 || c === 95)
337
+ return true;
338
+ if (c < 161 || c > 1114111)
339
+ return false;
340
+ if (c === 1564 || c === 5760 || c === 12288 || c === 8287)
341
+ return false;
342
+ if (c >= 8192 && c <= 8202 || c >= 8206 && c <= 8207 || c >= 8232 && c <= 8239 || c >= 8294 && c <= 8297)
343
+ return false;
344
+ if (c >= 55296 && c <= 57343 || c >= 64976 && c <= 65007)
345
+ return false;
346
+ return (c & 65535) < 65534;
347
+ }
348
+ var isNameChar = (c) => isNameStart(c) || c >= 48 && c <= 57 || c === 45 || c === 46;
349
+
350
+ class Parser {
351
+ src;
352
+ i = 0;
353
+ ws = false;
354
+ constructor(src) {
355
+ this.src = src;
356
+ }
357
+ fail(reason, at = this.i) {
358
+ throw new MessageSyntaxError(at, reason);
359
+ }
360
+ cp(at = this.i) {
361
+ return this.src.codePointAt(at) ?? -1;
362
+ }
363
+ at(text) {
364
+ return this.src.startsWith(text, this.i);
365
+ }
366
+ o() {
367
+ for (;; ) {
368
+ const c = this.cp();
369
+ if (c === -1 || !(isWs(c) || isBidi(c)))
370
+ return;
371
+ this.i++;
372
+ }
373
+ }
374
+ s() {
375
+ let j = this.i;
376
+ while (isBidi(this.cp(j)))
377
+ j++;
378
+ if (!isWs(this.cp(j)))
379
+ return false;
380
+ this.i = j + 1;
381
+ this.o();
382
+ return true;
383
+ }
384
+ sep() {
385
+ this.ws = this.s();
386
+ if (!this.ws)
387
+ this.o();
388
+ }
389
+ textChar(c) {
390
+ if (c === 0)
391
+ this.fail("a NUL character is not allowed");
392
+ if (c >= 55296 && c <= 57343)
393
+ this.fail("an unpaired surrogate is not allowed");
394
+ }
395
+ message() {
396
+ this.o();
397
+ if (!this.at(".") && !this.at("{{")) {
398
+ this.i = 0;
399
+ return { declarations: [], parts: this.pattern(false) };
400
+ }
401
+ const declarations = [];
402
+ for (;; ) {
403
+ const at = this.i;
404
+ if (this.at(".input")) {
405
+ this.i += 6;
406
+ this.o();
407
+ const expression = this.expression();
408
+ const operand = expression.operand;
409
+ if (operand?.kind !== "variable")
410
+ this.fail(".input needs a variable such as {$count :number}", expression.at);
411
+ declarations.push({ input: true, name: operand.name, expression, at });
412
+ } else if (this.at(".local")) {
413
+ this.i += 6;
414
+ if (!this.s())
415
+ this.fail("expected whitespace after .local");
416
+ if (this.src[this.i] !== "$")
417
+ this.fail("expected a variable such as $count");
418
+ const variable = this.variable();
419
+ this.o();
420
+ if (this.src[this.i] !== "=")
421
+ this.fail("expected = after the variable");
422
+ this.i++;
423
+ this.o();
424
+ declarations.push({ input: false, name: variable.name, expression: this.expression(), at });
425
+ } else
426
+ break;
427
+ this.o();
428
+ }
429
+ let parts = [];
430
+ let matcher;
431
+ if (this.at("{{"))
432
+ parts = this.quotedPattern();
433
+ else if (this.at(".match"))
434
+ matcher = this.matcher();
435
+ else if (this.at("."))
436
+ this.fail('unknown keyword "' + (/^\.[^\s{|}]*/.exec(this.src.slice(this.i))?.[0] ?? ".") + '"');
437
+ else
438
+ this.fail("expected a quoted pattern {{\u2026}} or .match");
439
+ this.o();
440
+ if (this.i < this.src.length)
441
+ this.fail("unexpected content after the message");
442
+ return { declarations, parts, ...matcher ? { matcher } : {} };
443
+ }
444
+ quotedPattern() {
445
+ this.i += 2;
446
+ const parts = this.pattern(true);
447
+ this.i += 2;
448
+ return parts;
449
+ }
450
+ matcher() {
451
+ const at = this.i;
452
+ this.i += 6;
453
+ const selectors = [];
454
+ for (;; ) {
455
+ if (!this.s())
456
+ this.fail("expected whitespace");
457
+ if (this.src[this.i] !== "$")
458
+ break;
459
+ const variable = this.variable();
460
+ selectors.push({ name: variable.name, at: variable.at });
461
+ }
462
+ if (selectors.length === 0)
463
+ this.fail("expected a selector such as $count");
464
+ const variants = [];
465
+ for (;; ) {
466
+ const start = this.i;
467
+ const keys = [this.key()];
468
+ for (;; ) {
469
+ const had = this.s();
470
+ if (!had)
471
+ this.o();
472
+ if (this.at("{{"))
473
+ break;
474
+ if (!had)
475
+ this.fail("expected whitespace or {{");
476
+ keys.push(this.key());
477
+ }
478
+ variants.push({ keys, parts: this.quotedPattern(), at: start });
479
+ this.o();
480
+ if (this.i >= this.src.length)
481
+ break;
482
+ }
483
+ return { at, selectors, variants };
484
+ }
485
+ key() {
486
+ if (this.src[this.i] === "*") {
487
+ this.i++;
488
+ return null;
489
+ }
490
+ return this.literal("expected a variant key").value;
491
+ }
492
+ pattern(quoted) {
493
+ const parts = [];
494
+ let text = "";
495
+ const flush = () => {
496
+ if (text)
497
+ parts.push({ type: "text", value: text });
498
+ text = "";
499
+ };
500
+ for (;; ) {
501
+ const c = this.cp();
502
+ if (c === -1) {
503
+ if (quoted)
504
+ this.fail("expected }} to close the pattern");
505
+ break;
506
+ }
507
+ if (c === 123) {
508
+ flush();
509
+ parts.push(this.placeholder());
510
+ } else if (c === 125) {
511
+ if (quoted && this.at("}}"))
512
+ break;
513
+ this.fail("unexpected }; write \\} for a brace in text");
514
+ } else if (c === 92) {
515
+ text += this.escape();
516
+ } else {
517
+ this.textChar(c);
518
+ text += String.fromCodePoint(c);
519
+ this.i += c > 65535 ? 2 : 1;
520
+ }
521
+ }
522
+ flush();
523
+ return parts;
524
+ }
525
+ escape() {
526
+ const next = this.src[this.i + 1];
527
+ if (next !== "\\" && next !== "{" && next !== "|" && next !== "}")
528
+ this.fail("a backslash must be followed by \\, {, | or }");
529
+ this.i += 2;
530
+ return next;
531
+ }
532
+ placeholder() {
533
+ const at = this.i;
534
+ this.i++;
535
+ this.o();
536
+ const c = this.src[this.i];
537
+ if (c === "#" || c === "/")
538
+ return this.markup(c);
539
+ return { type: "expression", expression: this.expressionBody(at) };
540
+ }
541
+ expression() {
542
+ const at = this.i;
543
+ if (this.src[this.i] !== "{")
544
+ this.fail("expected {");
545
+ this.i++;
546
+ this.o();
547
+ return this.expressionBody(at);
548
+ }
549
+ expressionBody(at) {
550
+ const expression = { at };
551
+ const c = this.src[this.i];
552
+ if (c === "$")
553
+ expression.operand = this.variable();
554
+ else if (c === ":")
555
+ expression.call = this.call();
556
+ else
557
+ expression.operand = this.literal("expected a literal, a variable, a function or markup");
558
+ if (expression.operand) {
559
+ this.sep();
560
+ if (this.ws && this.src[this.i] === ":")
561
+ expression.call = this.call();
562
+ }
563
+ while (this.ws && this.src[this.i] === "@")
564
+ this.attribute();
565
+ if (this.src[this.i] !== "}")
566
+ this.fail("expected }");
567
+ this.i++;
568
+ return expression;
569
+ }
570
+ markup(kind) {
571
+ this.i++;
572
+ const name = this.identifier();
573
+ this.options();
574
+ while (this.ws && this.src[this.i] === "@")
575
+ this.attribute();
576
+ let standalone = false;
577
+ if (kind === "#" && this.src[this.i] === "/") {
578
+ standalone = true;
579
+ this.i++;
580
+ this.o();
581
+ }
582
+ if (this.src[this.i] !== "}")
583
+ this.fail("expected }");
584
+ this.i++;
585
+ return { type: "markup", kind: standalone ? "standalone" : kind === "#" ? "open" : "close", name };
586
+ }
587
+ call() {
588
+ const at = this.i;
589
+ this.i++;
590
+ const name = this.identifier();
591
+ return { name, at, options: this.options() };
592
+ }
593
+ options() {
594
+ const options = [];
595
+ for (;; ) {
596
+ this.sep();
597
+ if (!this.ws || !isNameStart(this.cp()))
598
+ return options;
599
+ const at = this.i;
600
+ const name = this.identifier();
601
+ if (options.some((option) => option.name === name))
602
+ this.fail('duplicate option "' + name + '"', at);
603
+ this.o();
604
+ if (this.src[this.i] !== "=")
605
+ this.fail("expected = after the option name");
606
+ this.i++;
607
+ this.o();
608
+ const value = this.src[this.i] === "$" ? this.variable() : this.literal("expected an option value");
609
+ options.push({ name, value, at });
610
+ }
611
+ }
612
+ attribute() {
613
+ this.i++;
614
+ this.identifier();
615
+ const save = this.i;
616
+ this.o();
617
+ if (this.src[this.i] === "=") {
618
+ this.i++;
619
+ this.o();
620
+ this.literal("expected an attribute value");
621
+ } else
622
+ this.i = save;
623
+ this.sep();
624
+ }
625
+ variable() {
626
+ const at = this.i;
627
+ this.i++;
628
+ return { kind: "variable", name: this.name().normalize("NFC"), at };
629
+ }
630
+ identifier() {
631
+ let id = this.name();
632
+ if (this.src[this.i] === ":") {
633
+ this.i++;
634
+ id += ":" + this.name();
635
+ }
636
+ return id;
637
+ }
638
+ name() {
639
+ if (isBidi(this.cp()))
640
+ this.i++;
641
+ if (!isNameStart(this.cp()))
642
+ this.fail("expected a name");
643
+ const start = this.i;
644
+ while (isNameChar(this.cp()))
645
+ this.i += this.cp() > 65535 ? 2 : 1;
646
+ const value = this.src.slice(start, this.i);
647
+ if (isBidi(this.cp()))
648
+ this.i++;
649
+ return value;
650
+ }
651
+ literal(reason) {
652
+ if (this.src[this.i] === "|")
653
+ return this.quoted();
654
+ const start = this.i;
655
+ while (isNameChar(this.cp()))
656
+ this.i += this.cp() > 65535 ? 2 : 1;
657
+ if (this.i === start)
658
+ this.fail(reason);
659
+ return { kind: "literal", value: this.src.slice(start, this.i) };
660
+ }
661
+ quoted() {
662
+ const open = this.i;
663
+ this.i++;
664
+ let value = "";
665
+ for (;; ) {
666
+ const c = this.cp();
667
+ if (c === -1)
668
+ this.fail("unclosed |", open);
669
+ if (c === 124)
670
+ break;
671
+ if (c === 92)
672
+ value += this.escape();
673
+ else {
674
+ this.textChar(c);
675
+ value += String.fromCodePoint(c);
676
+ this.i += c > 65535 ? 2 : 1;
677
+ }
678
+ }
679
+ this.i++;
680
+ return { kind: "literal", value };
681
+ }
682
+ }
683
+ function expressionsOf(parts) {
684
+ return parts.flatMap((part) => part.type === "expression" ? [part.expression] : []);
685
+ }
686
+ function check(message) {
687
+ const declared = new Map;
688
+ const seen = new Set;
689
+ for (const declaration of message.declarations) {
690
+ const { name, expression } = declaration;
691
+ const refs = (expression.call?.options ?? []).flatMap((option) => option.value.kind === "variable" ? [option.value.name] : []);
692
+ if (!declaration.input && expression.operand?.kind === "variable")
693
+ refs.push(expression.operand.name);
694
+ if (declared.has(name) || seen.has(name) || refs.includes(name))
695
+ throw new MessageSyntaxError(declaration.at, "variable $" + name + " is declared twice or used before its declaration");
696
+ for (const ref of refs)
697
+ seen.add(ref);
698
+ declared.set(name, declaration);
699
+ }
700
+ const { matcher } = message;
701
+ if (matcher) {
702
+ const annotated = (name) => {
703
+ const declaration = declared.get(name);
704
+ if (!declaration)
705
+ return false;
706
+ if (declaration.expression.call)
707
+ return true;
708
+ const operand = declaration.expression.operand;
709
+ return !declaration.input && operand?.kind === "variable" && annotated(operand.name);
710
+ };
711
+ for (const selector of matcher.selectors) {
712
+ if (!annotated(selector.name))
713
+ throw new MessageSyntaxError(selector.at, ".match needs an annotated selector such as {$count :number}");
714
+ }
715
+ const ids = new Set;
716
+ for (const variant of matcher.variants) {
717
+ if (variant.keys.length !== matcher.selectors.length) {
718
+ throw new MessageSyntaxError(variant.at, "a variant has " + variant.keys.length + " keys but .match has " + matcher.selectors.length + " selectors");
719
+ }
720
+ const id = JSON.stringify(variant.keys.map((key) => key === null ? null : key.normalize("NFC")));
721
+ if (ids.has(id))
722
+ throw new MessageSyntaxError(variant.at, "two variants have the same keys");
723
+ ids.add(id);
724
+ }
725
+ if (!matcher.variants.some((variant) => variant.keys.every((key) => key === null)))
726
+ throw new MessageSyntaxError(matcher.at, ".match needs a variant whose keys are all *");
727
+ }
728
+ const all = [
729
+ ...message.declarations.map((declaration) => declaration.expression),
730
+ ...expressionsOf(message.parts),
731
+ ...matcher?.variants.flatMap((variant) => expressionsOf(variant.parts)) ?? []
732
+ ];
733
+ for (const { call } of all) {
734
+ if (call && !Object.hasOwn(FUNCTIONS, call.name))
735
+ throw new MessageSyntaxError(call.at, "function :" + call.name + " is not supported");
736
+ }
737
+ }
738
+ function parseMf2(source) {
739
+ const message = new Parser(source).message();
740
+ check(message);
741
+ return message;
742
+ }
743
+
744
+ export { MessageSyntaxError, parseMessage, FUNCTIONS, parseMf2 };