@hamur/i18n 0.0.0-stage → 0.0.1

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 +17 -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 +122 -4
  77. package/src/adapters/angular.ts +65 -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,2755 @@
1
+ // packages/i18n/src/module.ts
2
+ import { DiagnosticError as DiagnosticError8, defineModule } from "hamur/kit";
3
+
4
+ // packages/i18n/src/build/catalog.ts
5
+ import { readFile, stat } from "node:fs/promises";
6
+ import { relative, resolve } from "node:path";
7
+ import { DiagnosticError as DiagnosticError2, addTemplate, createResolver } from "hamur/kit";
8
+
9
+ // packages/i18n/src/options.ts
10
+ import { DiagnosticError } from "hamur/kit";
11
+ var CODE = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/;
12
+ var COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
13
+ var STRATEGIES = new Set(["prefix_except_default", "prefix", "prefix_and_default", "no_prefix"]);
14
+ var catalogMissing = (catalog) => "i18n.catalog " + JSON.stringify(catalog) + " does not exist";
15
+ var BASE_URL_REMOVED = "i18n.baseUrl was removed: set site.url (HAMUR_SITE_URL at run time)";
16
+ function fail(message) {
17
+ throw new DiagnosticError("HAMUR_E5806", message);
18
+ }
19
+ function resolveLocale(entry, index) {
20
+ const input = typeof entry === "string" ? { code: entry } : entry;
21
+ const { code } = input;
22
+ if (typeof code !== "string" || !CODE.test(code)) {
23
+ fail(`i18n.locales[${index}].code ${JSON.stringify(code)} must be lower-case letters, digits and "-" (like "fr" or "pt-br")`);
24
+ }
25
+ const language = input.language ?? code;
26
+ try {
27
+ Intl.getCanonicalLocales(language);
28
+ } catch {
29
+ fail(`i18n.locales[${index}].language ${JSON.stringify(language)} is not a BCP 47 language tag`);
30
+ }
31
+ const dir = input.dir ?? (new Intl.Locale(language).getTextInfo().direction === "rtl" ? "rtl" : "ltr");
32
+ const name = input.name ?? new Intl.DisplayNames([language], { type: "language" }).of(language) ?? language;
33
+ return { code, language, dir, name };
34
+ }
35
+ function originOf(value) {
36
+ if (typeof value !== "string")
37
+ return;
38
+ let url;
39
+ try {
40
+ url = new URL(value);
41
+ } catch {
42
+ return;
43
+ }
44
+ if (url.protocol !== "http:" && url.protocol !== "https:")
45
+ return;
46
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash || /[?#]/.test(value))
47
+ return;
48
+ return url.origin;
49
+ }
50
+ function originExample(value) {
51
+ const host = typeof value === "string" ? value.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/*/, "").replace(/^[^@/?#]*@/, "").split(/[/?#]/)[0] : "";
52
+ try {
53
+ if (host)
54
+ return new URL("https://" + host).origin;
55
+ } catch {
56
+ return "https://example.com";
57
+ }
58
+ return "https://example.com";
59
+ }
60
+ function resolveDomains(entries, locales, strategySet) {
61
+ const given = entries.map((entry) => typeof entry === "string" ? undefined : entry.domain);
62
+ if (given.every((domain) => domain === undefined))
63
+ return;
64
+ const domains = {};
65
+ const byHost = new Map;
66
+ given.forEach((domain, index) => {
67
+ if (domain === undefined)
68
+ return;
69
+ const origin = originOf(domain);
70
+ if (!origin)
71
+ fail(`i18n.locales[${index}].domain ${JSON.stringify(domain)} must be an origin such as ${JSON.stringify(originExample(domain))}`);
72
+ const { code } = locales[index];
73
+ const host = new URL(origin).host;
74
+ const other = byHost.get(host);
75
+ if (other !== undefined)
76
+ fail(`i18n.locales: ${JSON.stringify(other)} and ${JSON.stringify(code)} share the domain ${JSON.stringify(domains[other])}`);
77
+ byHost.set(host, code);
78
+ domains[code] = origin;
79
+ });
80
+ const missing = given.indexOf(undefined);
81
+ if (missing !== -1)
82
+ fail(`i18n.locales[${missing}] has no domain; set domain on every locale or none`);
83
+ if (strategySet)
84
+ fail("i18n.strategy cannot be set with locales[].domain; each domain serves one locale without a prefix");
85
+ return domains;
86
+ }
87
+ function resolveOptions(input) {
88
+ const options = input ?? {};
89
+ if (!Array.isArray(options.locales) || options.locales.length === 0)
90
+ fail("i18n.locales must list at least one locale");
91
+ const locales = options.locales.map(resolveLocale);
92
+ const codes = new Set;
93
+ for (const { code } of locales) {
94
+ if (codes.has(code))
95
+ fail(`i18n.locales: ${JSON.stringify(code)} is listed twice`);
96
+ codes.add(code);
97
+ }
98
+ const defaultLocale = options.defaultLocale;
99
+ if (!codes.has(defaultLocale))
100
+ fail(`i18n.defaultLocale ${JSON.stringify(defaultLocale)} is not in i18n.locales (${[...codes].join(", ")})`);
101
+ const strategy = options.strategy ?? "prefix_except_default";
102
+ if (!STRATEGIES.has(strategy))
103
+ fail(`i18n.strategy ${JSON.stringify(strategy)} is not supported; use "prefix_except_default", "prefix", "prefix_and_default" or "no_prefix"`);
104
+ const redirectToDefaultLocale = options.redirectToDefaultLocale ?? false;
105
+ if (redirectToDefaultLocale && strategy !== "prefix")
106
+ fail('i18n.redirectToDefaultLocale needs strategy "prefix"');
107
+ if (strategy === "no_prefix" && Object.keys(options.pages ?? {}).length > 0)
108
+ fail("i18n.pages needs a prefix strategy; no_prefix keeps one path per page");
109
+ if (Object.hasOwn(options, "baseUrl"))
110
+ fail(BASE_URL_REMOVED);
111
+ const timeZone = options.timeZone ?? "UTC";
112
+ try {
113
+ new Intl.DateTimeFormat("en", { timeZone });
114
+ } catch {
115
+ fail(`i18n.timeZone ${JSON.stringify(timeZone)} is not a time zone this runtime knows`);
116
+ }
117
+ const cookie = options.detect?.cookie ?? "hamur_locale";
118
+ if (cookie !== false && (typeof cookie !== "string" || !COOKIE_NAME.test(cookie)))
119
+ fail(`i18n.detect.cookie ${JSON.stringify(cookie)} is not a valid cookie name`);
120
+ const { redirect } = options.detect ?? {};
121
+ if (redirect !== undefined && redirect !== "root" && redirect !== "all" && redirect !== false)
122
+ fail(`i18n.detect.redirect ${JSON.stringify(redirect)} is not supported; use "root", "all" or false`);
123
+ const fallback = options.fallback ?? "default";
124
+ if (fallback !== "default" && fallback !== false) {
125
+ if (typeof fallback !== "object" || fallback === null || Array.isArray(fallback))
126
+ fail(`i18n.fallback must be "default", false or an object of locale chains (got ${JSON.stringify(fallback)})`);
127
+ for (const [key, chain] of Object.entries(fallback)) {
128
+ if (!codes.has(key))
129
+ fail(`i18n.fallback: ${JSON.stringify(key)} is not in i18n.locales`);
130
+ if (!Array.isArray(chain))
131
+ fail(`i18n.fallback[${JSON.stringify(key)}] must be an array of locale codes`);
132
+ for (const entry of chain) {
133
+ if (!codes.has(entry))
134
+ fail(`i18n.fallback[${JSON.stringify(key)}]: ${JSON.stringify(entry)} is not in i18n.locales`);
135
+ if (entry === key)
136
+ fail(`i18n.fallback[${JSON.stringify(key)}] lists ${JSON.stringify(key)} itself`);
137
+ }
138
+ }
139
+ }
140
+ for (const [name, paths] of Object.entries(options.pages ?? {})) {
141
+ if (paths?.[defaultLocale] === false)
142
+ fail(`i18n.pages.${name}.${defaultLocale}: the default locale always has its page`);
143
+ }
144
+ const missingPage = options.missingPage ?? "404";
145
+ if (missingPage !== "404" && missingPage !== "redirect" && missingPage !== "rewrite")
146
+ fail(`i18n.missingPage must be "404", "redirect" or "rewrite" (got ${JSON.stringify(missingPage)})`);
147
+ const domains = resolveDomains(options.locales, locales, options.strategy !== undefined);
148
+ const localizeLinks = options.localizeLinks ?? true;
149
+ if (typeof localizeLinks !== "boolean")
150
+ fail(`i18n.localizeLinks must be a boolean (got ${JSON.stringify(localizeLinks)})`);
151
+ const split = options.split ?? false;
152
+ if (split !== false && split !== "route")
153
+ fail(`i18n.split ${JSON.stringify(split)} is not supported; use false or "route"`);
154
+ const dropUnusedKeys = options.dropUnusedKeys ?? false;
155
+ if (typeof dropUnusedKeys !== "boolean")
156
+ fail(`i18n.dropUnusedKeys must be a boolean (got ${JSON.stringify(dropUnusedKeys)})`);
157
+ const keepKeys = options.keepKeys ?? [];
158
+ if (!Array.isArray(keepKeys) || keepKeys.some((glob) => typeof glob !== "string" || glob === ""))
159
+ fail('i18n.keepKeys must be an array of key globs such as "status.*"');
160
+ const syntax = options.syntax ?? "mf1";
161
+ if (syntax !== "mf1" && syntax !== "mf2")
162
+ fail(`i18n.syntax must be "mf1" or "mf2" (got ${JSON.stringify(syntax)})`);
163
+ const { catalog } = options;
164
+ if (catalog !== undefined && (typeof catalog !== "string" || catalog === ""))
165
+ fail(catalogMissing(catalog));
166
+ return {
167
+ locales,
168
+ defaultLocale,
169
+ strategy,
170
+ redirectToDefaultLocale,
171
+ detect: { cookie, redirect: options.detect?.redirect ?? (domains ? false : "root") },
172
+ pages: options.pages ?? {},
173
+ timeZone,
174
+ missingPage,
175
+ fallback,
176
+ localizeLinks,
177
+ split,
178
+ dropUnusedKeys,
179
+ keepKeys,
180
+ syntax,
181
+ ...catalog === undefined ? {} : { catalog },
182
+ ...domains ? { domains } : {}
183
+ };
184
+ }
185
+
186
+ // packages/i18n/src/build/catalog.ts
187
+ var DEFAULT_EXPORT = /\bexport\s+default\s+defineCatalog\s*\(/;
188
+ async function readCatalogFile(rootDir, catalog) {
189
+ const path = resolve(rootDir, catalog);
190
+ const found = await stat(path).catch(() => {
191
+ return;
192
+ });
193
+ if (!found?.isFile())
194
+ throw new DiagnosticError2("HAMUR_E5814", catalogMissing(catalog));
195
+ const text = await readFile(path, "utf8");
196
+ if (!DEFAULT_EXPORT.test(text))
197
+ throw new DiagnosticError2("HAMUR_E5815", relative(rootDir, path) + " must export default defineCatalog({ … })");
198
+ return path;
199
+ }
200
+ var setupCatalog = async (options, hamur) => {
201
+ const path = options.catalog === undefined ? undefined : await readCatalogFile(hamur.options.rootDir, options.catalog);
202
+ const r = createResolver(new URL("../../src/build/catalog.ts", import.meta.url).href);
203
+ addTemplate({
204
+ filename: "i18n/catalog",
205
+ getContents: () => path ? "export { loadCatalog as default } from " + JSON.stringify(r.resolve("../runtime/catalog-client.ts")) + `;
206
+ ` : `export default undefined;
207
+ `
208
+ });
209
+ addTemplate({
210
+ filename: "i18n/catalog-server",
211
+ server: true,
212
+ getContents: () => path ? "export { loadCatalog as default } from " + JSON.stringify(r.resolve("../runtime/catalog-server.ts")) + `;
213
+ ` : `export default undefined;
214
+ `
215
+ });
216
+ addTemplate({
217
+ filename: "i18n/catalog-source",
218
+ server: true,
219
+ getContents: () => "export default " + (path ? "() => import(" + JSON.stringify(path) + ")" : "undefined") + `;
220
+ `
221
+ });
222
+ };
223
+
224
+ // packages/i18n/src/build/head.ts
225
+ import { diagnostic, useLogger } from "hamur/kit";
226
+ var SITE_URL_WARNING = "[hamur] site.url is not set; hreflang and canonical links are not written";
227
+ var setupHead = (options, hamur) => {
228
+ if (!options.domains && hamur.options.site.url === undefined && !process.env.HAMUR_SITE_URL)
229
+ useLogger("hamur").warn(diagnostic("HAMUR_W5833", SITE_URL_WARNING.replace(/^\[hamur\] /, "")));
230
+ };
231
+
232
+ // packages/i18n/src/build/messages.ts
233
+ import { createHash } from "node:crypto";
234
+ import { readdir, readFile as readFile4, realpath } from "node:fs/promises";
235
+ import { basename, join as join2, relative as relative3 } from "node:path";
236
+ import { DiagnosticError as DiagnosticError6, addBunPlugin, addTemplate as addTemplate3, diagnostic as diagnostic3, useLogger as useLogger3 } from "hamur/kit";
237
+
238
+ // packages/i18n/src/compiler/skeleton.ts
239
+ var WIDTHS = { short: "short", narrow: "narrow", "full-name": "long" };
240
+ function supportedUnit(unit) {
241
+ try {
242
+ new Intl.NumberFormat("en", { style: "unit", unit });
243
+ return true;
244
+ } catch {
245
+ return false;
246
+ }
247
+ }
248
+ function parseSkeleton(source, offset) {
249
+ const options = {};
250
+ let scale;
251
+ let percent = false;
252
+ let unit;
253
+ let currency;
254
+ let width;
255
+ const fail = (at, reason) => {
256
+ throw new MessageSyntaxError(at, reason);
257
+ };
258
+ for (const match of source.matchAll(/\S+/g)) {
259
+ const token = match[0];
260
+ const at = offset + match.index;
261
+ const stem = () => fail(at, 'number skeleton stem "' + token.split("/")[0] + '" is not supported');
262
+ let found;
263
+ if (token === "percent") {
264
+ options.style = "percent";
265
+ percent = true;
266
+ } else if (token === "compact-short" || token === "compact-long") {
267
+ options.notation = "compact";
268
+ options.compactDisplay = token === "compact-short" ? "short" : "long";
269
+ } else if (token.startsWith("unit/")) {
270
+ unit = token.slice(5);
271
+ if (!unit || !supportedUnit(unit))
272
+ fail(at, 'number skeleton unit "' + unit + '" is not supported');
273
+ } else if (token.startsWith("currency/")) {
274
+ currency = token.slice(9);
275
+ if (!/^[A-Za-z]{3}$/.test(currency))
276
+ fail(at, 'number skeleton currency "' + currency + '" is not a three-letter code');
277
+ currency = currency.toUpperCase();
278
+ } else if (token.startsWith("scale/")) {
279
+ scale = Number(token.slice(6));
280
+ if (token.length === 6 || !Number.isFinite(scale))
281
+ fail(at, 'number skeleton scale "' + token.slice(6) + '" is not a number');
282
+ } else if (token.startsWith("unit-width-")) {
283
+ const value = token.slice(11);
284
+ if (!Object.hasOwn(WIDTHS, value))
285
+ stem();
286
+ width = { token, value, at };
287
+ } else if ((found = /^\.(0*)(#*)$/.exec(token)) && token.length > 1) {
288
+ options.minimumFractionDigits = found[1].length;
289
+ options.maximumFractionDigits = found[1].length + found[2].length;
290
+ } else if (token === "sign-always")
291
+ options.signDisplay = "always";
292
+ else if (token === "group-off")
293
+ options.useGrouping = false;
294
+ else if (token === "integer")
295
+ options.maximumFractionDigits = 0;
296
+ else
297
+ stem();
298
+ }
299
+ if (unit !== undefined && currency !== undefined)
300
+ fail(offset, "number skeleton cannot hold both unit/<unit> and currency/<code>");
301
+ if (unit !== undefined) {
302
+ options.style = "unit";
303
+ options.unit = unit;
304
+ if (width)
305
+ options.unitDisplay = WIDTHS[width.value];
306
+ } else if (currency !== undefined) {
307
+ options.style = "currency";
308
+ options.currency = currency;
309
+ if (width) {
310
+ if (width.value !== "narrow")
311
+ fail(width.at, 'number skeleton stem "' + width.token + '" is not supported');
312
+ options.currencyDisplay = "narrowSymbol";
313
+ }
314
+ } else if (width)
315
+ fail(width.at, 'number skeleton "' + width.token + '" needs a unit/<unit> or currency/<code> stem');
316
+ if (percent && scale === 100)
317
+ scale = undefined;
318
+ return scale === undefined ? { options } : { options, scale };
319
+ }
320
+
321
+ // packages/i18n/src/compiler/parse.ts
322
+ class MessageSyntaxError extends Error {
323
+ offset;
324
+ reason;
325
+ constructor(offset, reason) {
326
+ super(`${reason} (column ${offset + 1})`);
327
+ this.offset = offset;
328
+ this.reason = reason;
329
+ this.name = "MessageSyntaxError";
330
+ }
331
+ }
332
+ var PLURAL_CATEGORIES = ["zero", "one", "two", "few", "many", "other"];
333
+ var DATE_STYLES = ["short", "medium", "long", "full"];
334
+ var EXACT = /^=\d+$/;
335
+ var OPEN_TAG = /<([A-Za-z][A-Za-z0-9_-]*)(\/?)>/y;
336
+ var CLOSE_TAG = /<\/([A-Za-z][A-Za-z0-9_-]*)>/y;
337
+ function parseMessage(source) {
338
+ let i = 0;
339
+ const fail = (offset, reason) => {
340
+ throw new MessageSyntaxError(offset, reason);
341
+ };
342
+ const skipSpace = () => {
343
+ while (i < source.length && /\s/.test(source[i]))
344
+ i++;
345
+ };
346
+ const peek = (pattern) => {
347
+ pattern.lastIndex = i;
348
+ return pattern.exec(source);
349
+ };
350
+ const read = (pattern) => {
351
+ pattern.lastIndex = i;
352
+ const found = pattern.exec(source);
353
+ if (!found)
354
+ return "";
355
+ i += found[0].length;
356
+ return found[0];
357
+ };
358
+ function nodes(closer, openAt, inPlural, tag) {
359
+ const out = [];
360
+ let text = "";
361
+ const flush = () => {
362
+ if (text)
363
+ out.push({ type: "text", value: text });
364
+ text = "";
365
+ };
366
+ while (i < source.length) {
367
+ const c = source[i];
368
+ if (c === "{") {
369
+ flush();
370
+ out.push(argument(inPlural));
371
+ } else if (c === "}") {
372
+ if (tag)
373
+ fail(tag.at, "tag <" + tag.name + "> is not closed");
374
+ if (!closer)
375
+ fail(i, 'unmatched "}"');
376
+ flush();
377
+ return out;
378
+ } else if (c === "<" && peek(OPEN_TAG)) {
379
+ const found = peek(OPEN_TAG);
380
+ flush();
381
+ const at = i;
382
+ i += found[0].length;
383
+ const name = found[1];
384
+ out.push({ type: "tag", name, children: found[2] ? [] : nodes(closer, openAt, inPlural, { name, at }) });
385
+ } else if (c === "<" && peek(CLOSE_TAG)) {
386
+ const found = peek(CLOSE_TAG);
387
+ if (!tag)
388
+ fail(i, "closing tag </" + found[1] + "> has no opening tag");
389
+ if (found[1] !== tag.name)
390
+ fail(tag.at, "tag <" + tag.name + "> is not closed");
391
+ flush();
392
+ i += found[0].length;
393
+ return out;
394
+ } else if (c === "#" && inPlural) {
395
+ flush();
396
+ out.push({ type: "pound" });
397
+ i++;
398
+ } else if (c === "'") {
399
+ const next = source[i + 1];
400
+ if (next === "'") {
401
+ text += "'";
402
+ i += 2;
403
+ } else if (next === "{" || next === "}" || next === "#" && inPlural) {
404
+ i++;
405
+ while (i < source.length) {
406
+ if (source[i] === "'") {
407
+ if (source[i + 1] === "'") {
408
+ text += "'";
409
+ i += 2;
410
+ continue;
411
+ }
412
+ i++;
413
+ break;
414
+ }
415
+ text += source[i++];
416
+ }
417
+ } else {
418
+ text += c;
419
+ i++;
420
+ }
421
+ } else {
422
+ text += c;
423
+ i++;
424
+ }
425
+ }
426
+ if (tag)
427
+ fail(tag.at, "tag <" + tag.name + "> is not closed");
428
+ if (closer)
429
+ fail(openAt, 'unclosed "{"');
430
+ flush();
431
+ return out;
432
+ }
433
+ function argument(inPlural) {
434
+ const openAt = i++;
435
+ skipSpace();
436
+ const name = read(/[^\s,{}]+/y);
437
+ if (!name)
438
+ fail(i, i >= source.length ? 'unclosed "{"' : "expected an argument name");
439
+ skipSpace();
440
+ if (i >= source.length)
441
+ fail(openAt, 'unclosed "{"');
442
+ if (source[i] === "}") {
443
+ i++;
444
+ return { type: "arg", name };
445
+ }
446
+ if (source[i] !== ",")
447
+ fail(i, `expected "," or "}" after "${name}"`);
448
+ i++;
449
+ skipSpace();
450
+ const typeAt = i;
451
+ const type = read(/[A-Za-z]+/y);
452
+ if (!type)
453
+ fail(i, i >= source.length ? 'unclosed "{"' : "expected an argument type");
454
+ skipSpace();
455
+ if (type === "number" || type === "date" || type === "time")
456
+ return simple(name, type, openAt);
457
+ if (type === "plural" || type === "selectordinal" || type === "select") {
458
+ if (i >= source.length)
459
+ fail(openAt, 'unclosed "{"');
460
+ if (source[i] !== ",")
461
+ fail(i, `expected "," after "${type}"`);
462
+ i++;
463
+ return choice(name, type, openAt, inPlural);
464
+ }
465
+ return fail(typeAt, `unknown argument type "${type}"`);
466
+ }
467
+ function simple(name, type, openAt) {
468
+ let style = "";
469
+ let styleAt = i;
470
+ if (source[i] === ",") {
471
+ i++;
472
+ skipSpace();
473
+ styleAt = i;
474
+ style = read(/[^}]*/y).trim();
475
+ }
476
+ if (source[i] !== "}")
477
+ fail(openAt, 'unclosed "{"');
478
+ i++;
479
+ if (type === "number") {
480
+ if (style === "")
481
+ return { type: "number", name, style: "decimal" };
482
+ if (style === "integer" || style === "percent")
483
+ return { type: "number", name, style };
484
+ if (style.startsWith("::")) {
485
+ const currency = /^::currency\/([A-Za-z]{3})$/.exec(style);
486
+ if (currency)
487
+ return { type: "number", name, style: "currency", currency: currency[1].toUpperCase() };
488
+ const { options, scale } = parseSkeleton(style.slice(2), styleAt + 2);
489
+ return scale === undefined ? { type: "number", name, style: "skeleton", options } : { type: "number", name, style: "skeleton", options, scale };
490
+ }
491
+ return fail(styleAt, `unknown number style "${style}"`);
492
+ }
493
+ if (style !== "" && !DATE_STYLES.includes(style))
494
+ fail(styleAt, `unknown ${type} style "${style}"`);
495
+ return { type: "date", name, kind: type, style: style || "medium" };
496
+ }
497
+ function choice(name, type, openAt, inPlural) {
498
+ const cases = [];
499
+ const seen = new Set;
500
+ let offset = 0;
501
+ while (true) {
502
+ skipSpace();
503
+ if (i >= source.length)
504
+ fail(openAt, 'unclosed "{"');
505
+ if (source[i] === "}") {
506
+ i++;
507
+ break;
508
+ }
509
+ const keyAt = i;
510
+ if (source.startsWith("offset:", i)) {
511
+ if (type !== "plural")
512
+ fail(i, '"offset" is only valid in a plural');
513
+ i += 7;
514
+ skipSpace();
515
+ const digits = read(/\d+/y);
516
+ if (!digits)
517
+ fail(i, "offset must be an integer");
518
+ offset = Number(digits);
519
+ continue;
520
+ }
521
+ const key = read(/[^\s{}]+/y);
522
+ if (!key)
523
+ fail(i, "expected a case key");
524
+ if (type !== "select" && !EXACT.test(key) && !PLURAL_CATEGORIES.includes(key)) {
525
+ fail(keyAt, `"${key}" is not a plural case; use =<integer>, zero, one, two, few, many or other`);
526
+ }
527
+ if (seen.has(key))
528
+ fail(keyAt, `duplicate case "${key}"`);
529
+ seen.add(key);
530
+ skipSpace();
531
+ if (source[i] !== "{")
532
+ fail(i, `expected "{" after case "${key}"`);
533
+ const bodyAt = i++;
534
+ const body = nodes(true, bodyAt, type !== "select" || inPlural);
535
+ i++;
536
+ cases.push({ key, body });
537
+ }
538
+ if (!seen.has("other"))
539
+ fail(openAt, `${type} needs an "other" case`);
540
+ return type === "select" ? { type: "select", name, cases } : { type: "plural", name, ordinal: type === "selectordinal", offset, cases };
541
+ }
542
+ return nodes(false, 0, false);
543
+ }
544
+
545
+ // packages/i18n/src/compiler/mf2-parse.ts
546
+ var NUMBER_OPTIONS = [
547
+ "select",
548
+ "signDisplay",
549
+ "useGrouping",
550
+ "minimumIntegerDigits",
551
+ "minimumFractionDigits",
552
+ "maximumFractionDigits",
553
+ "minimumSignificantDigits",
554
+ "maximumSignificantDigits",
555
+ "trailingZeroDisplay",
556
+ "roundingPriority",
557
+ "roundingIncrement",
558
+ "roundingMode"
559
+ ];
560
+ var INTEGER_OPTIONS = ["select", "signDisplay", "useGrouping", "minimumIntegerDigits", "maximumSignificantDigits"];
561
+ var FUNCTIONS = {
562
+ string: [],
563
+ number: NUMBER_OPTIONS,
564
+ integer: INTEGER_OPTIONS,
565
+ datetime: ["dateFields", "dateLength", "timePrecision", "timeZoneStyle", "timeZone", "hour12", "calendar"],
566
+ date: ["fields", "length", "timeZone", "calendar"],
567
+ time: ["precision", "timeZoneStyle", "timeZone", "hour12", "calendar"]
568
+ };
569
+ var isBidi = (c) => c === 1564 || c === 8206 || c === 8207 || c >= 8294 && c <= 8297;
570
+ var isWs = (c) => c === 32 || c === 9 || c === 13 || c === 10 || c === 12288;
571
+ function isNameStart(c) {
572
+ if (c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 43 || c === 95)
573
+ return true;
574
+ if (c < 161 || c > 1114111)
575
+ return false;
576
+ if (c === 1564 || c === 5760 || c === 12288 || c === 8287)
577
+ return false;
578
+ if (c >= 8192 && c <= 8202 || c >= 8206 && c <= 8207 || c >= 8232 && c <= 8239 || c >= 8294 && c <= 8297)
579
+ return false;
580
+ if (c >= 55296 && c <= 57343 || c >= 64976 && c <= 65007)
581
+ return false;
582
+ return (c & 65535) < 65534;
583
+ }
584
+ var isNameChar = (c) => isNameStart(c) || c >= 48 && c <= 57 || c === 45 || c === 46;
585
+
586
+ class Parser {
587
+ src;
588
+ i = 0;
589
+ ws = false;
590
+ constructor(src) {
591
+ this.src = src;
592
+ }
593
+ fail(reason, at = this.i) {
594
+ throw new MessageSyntaxError(at, reason);
595
+ }
596
+ cp(at = this.i) {
597
+ return this.src.codePointAt(at) ?? -1;
598
+ }
599
+ at(text) {
600
+ return this.src.startsWith(text, this.i);
601
+ }
602
+ o() {
603
+ for (;; ) {
604
+ const c = this.cp();
605
+ if (c === -1 || !(isWs(c) || isBidi(c)))
606
+ return;
607
+ this.i++;
608
+ }
609
+ }
610
+ s() {
611
+ let j = this.i;
612
+ while (isBidi(this.cp(j)))
613
+ j++;
614
+ if (!isWs(this.cp(j)))
615
+ return false;
616
+ this.i = j + 1;
617
+ this.o();
618
+ return true;
619
+ }
620
+ sep() {
621
+ this.ws = this.s();
622
+ if (!this.ws)
623
+ this.o();
624
+ }
625
+ textChar(c) {
626
+ if (c === 0)
627
+ this.fail("a NUL character is not allowed");
628
+ if (c >= 55296 && c <= 57343)
629
+ this.fail("an unpaired surrogate is not allowed");
630
+ }
631
+ message() {
632
+ this.o();
633
+ if (!this.at(".") && !this.at("{{")) {
634
+ this.i = 0;
635
+ return { declarations: [], parts: this.pattern(false) };
636
+ }
637
+ const declarations = [];
638
+ for (;; ) {
639
+ const at = this.i;
640
+ if (this.at(".input")) {
641
+ this.i += 6;
642
+ this.o();
643
+ const expression = this.expression();
644
+ const operand = expression.operand;
645
+ if (operand?.kind !== "variable")
646
+ this.fail(".input needs a variable such as {$count :number}", expression.at);
647
+ declarations.push({ input: true, name: operand.name, expression, at });
648
+ } else if (this.at(".local")) {
649
+ this.i += 6;
650
+ if (!this.s())
651
+ this.fail("expected whitespace after .local");
652
+ if (this.src[this.i] !== "$")
653
+ this.fail("expected a variable such as $count");
654
+ const variable = this.variable();
655
+ this.o();
656
+ if (this.src[this.i] !== "=")
657
+ this.fail("expected = after the variable");
658
+ this.i++;
659
+ this.o();
660
+ declarations.push({ input: false, name: variable.name, expression: this.expression(), at });
661
+ } else
662
+ break;
663
+ this.o();
664
+ }
665
+ let parts = [];
666
+ let matcher;
667
+ if (this.at("{{"))
668
+ parts = this.quotedPattern();
669
+ else if (this.at(".match"))
670
+ matcher = this.matcher();
671
+ else if (this.at("."))
672
+ this.fail('unknown keyword "' + (/^\.[^\s{|}]*/.exec(this.src.slice(this.i))?.[0] ?? ".") + '"');
673
+ else
674
+ this.fail("expected a quoted pattern {{…}} or .match");
675
+ this.o();
676
+ if (this.i < this.src.length)
677
+ this.fail("unexpected content after the message");
678
+ return { declarations, parts, ...matcher ? { matcher } : {} };
679
+ }
680
+ quotedPattern() {
681
+ this.i += 2;
682
+ const parts = this.pattern(true);
683
+ this.i += 2;
684
+ return parts;
685
+ }
686
+ matcher() {
687
+ const at = this.i;
688
+ this.i += 6;
689
+ const selectors = [];
690
+ for (;; ) {
691
+ if (!this.s())
692
+ this.fail("expected whitespace");
693
+ if (this.src[this.i] !== "$")
694
+ break;
695
+ const variable = this.variable();
696
+ selectors.push({ name: variable.name, at: variable.at });
697
+ }
698
+ if (selectors.length === 0)
699
+ this.fail("expected a selector such as $count");
700
+ const variants = [];
701
+ for (;; ) {
702
+ const start = this.i;
703
+ const keys = [this.key()];
704
+ for (;; ) {
705
+ const had = this.s();
706
+ if (!had)
707
+ this.o();
708
+ if (this.at("{{"))
709
+ break;
710
+ if (!had)
711
+ this.fail("expected whitespace or {{");
712
+ keys.push(this.key());
713
+ }
714
+ variants.push({ keys, parts: this.quotedPattern(), at: start });
715
+ this.o();
716
+ if (this.i >= this.src.length)
717
+ break;
718
+ }
719
+ return { at, selectors, variants };
720
+ }
721
+ key() {
722
+ if (this.src[this.i] === "*") {
723
+ this.i++;
724
+ return null;
725
+ }
726
+ return this.literal("expected a variant key").value;
727
+ }
728
+ pattern(quoted) {
729
+ const parts = [];
730
+ let text = "";
731
+ const flush = () => {
732
+ if (text)
733
+ parts.push({ type: "text", value: text });
734
+ text = "";
735
+ };
736
+ for (;; ) {
737
+ const c = this.cp();
738
+ if (c === -1) {
739
+ if (quoted)
740
+ this.fail("expected }} to close the pattern");
741
+ break;
742
+ }
743
+ if (c === 123) {
744
+ flush();
745
+ parts.push(this.placeholder());
746
+ } else if (c === 125) {
747
+ if (quoted && this.at("}}"))
748
+ break;
749
+ this.fail("unexpected }; write \\} for a brace in text");
750
+ } else if (c === 92) {
751
+ text += this.escape();
752
+ } else {
753
+ this.textChar(c);
754
+ text += String.fromCodePoint(c);
755
+ this.i += c > 65535 ? 2 : 1;
756
+ }
757
+ }
758
+ flush();
759
+ return parts;
760
+ }
761
+ escape() {
762
+ const next = this.src[this.i + 1];
763
+ if (next !== "\\" && next !== "{" && next !== "|" && next !== "}")
764
+ this.fail("a backslash must be followed by \\, {, | or }");
765
+ this.i += 2;
766
+ return next;
767
+ }
768
+ placeholder() {
769
+ const at = this.i;
770
+ this.i++;
771
+ this.o();
772
+ const c = this.src[this.i];
773
+ if (c === "#" || c === "/")
774
+ return this.markup(c);
775
+ return { type: "expression", expression: this.expressionBody(at) };
776
+ }
777
+ expression() {
778
+ const at = this.i;
779
+ if (this.src[this.i] !== "{")
780
+ this.fail("expected {");
781
+ this.i++;
782
+ this.o();
783
+ return this.expressionBody(at);
784
+ }
785
+ expressionBody(at) {
786
+ const expression = { at };
787
+ const c = this.src[this.i];
788
+ if (c === "$")
789
+ expression.operand = this.variable();
790
+ else if (c === ":")
791
+ expression.call = this.call();
792
+ else
793
+ expression.operand = this.literal("expected a literal, a variable, a function or markup");
794
+ if (expression.operand) {
795
+ this.sep();
796
+ if (this.ws && this.src[this.i] === ":")
797
+ expression.call = this.call();
798
+ }
799
+ while (this.ws && this.src[this.i] === "@")
800
+ this.attribute();
801
+ if (this.src[this.i] !== "}")
802
+ this.fail("expected }");
803
+ this.i++;
804
+ return expression;
805
+ }
806
+ markup(kind) {
807
+ this.i++;
808
+ const name = this.identifier();
809
+ this.options();
810
+ while (this.ws && this.src[this.i] === "@")
811
+ this.attribute();
812
+ let standalone = false;
813
+ if (kind === "#" && this.src[this.i] === "/") {
814
+ standalone = true;
815
+ this.i++;
816
+ this.o();
817
+ }
818
+ if (this.src[this.i] !== "}")
819
+ this.fail("expected }");
820
+ this.i++;
821
+ return { type: "markup", kind: standalone ? "standalone" : kind === "#" ? "open" : "close", name };
822
+ }
823
+ call() {
824
+ const at = this.i;
825
+ this.i++;
826
+ const name = this.identifier();
827
+ return { name, at, options: this.options() };
828
+ }
829
+ options() {
830
+ const options = [];
831
+ for (;; ) {
832
+ this.sep();
833
+ if (!this.ws || !isNameStart(this.cp()))
834
+ return options;
835
+ const at = this.i;
836
+ const name = this.identifier();
837
+ if (options.some((option) => option.name === name))
838
+ this.fail('duplicate option "' + name + '"', at);
839
+ this.o();
840
+ if (this.src[this.i] !== "=")
841
+ this.fail("expected = after the option name");
842
+ this.i++;
843
+ this.o();
844
+ const value = this.src[this.i] === "$" ? this.variable() : this.literal("expected an option value");
845
+ options.push({ name, value, at });
846
+ }
847
+ }
848
+ attribute() {
849
+ this.i++;
850
+ this.identifier();
851
+ const save = this.i;
852
+ this.o();
853
+ if (this.src[this.i] === "=") {
854
+ this.i++;
855
+ this.o();
856
+ this.literal("expected an attribute value");
857
+ } else
858
+ this.i = save;
859
+ this.sep();
860
+ }
861
+ variable() {
862
+ const at = this.i;
863
+ this.i++;
864
+ return { kind: "variable", name: this.name().normalize("NFC"), at };
865
+ }
866
+ identifier() {
867
+ let id = this.name();
868
+ if (this.src[this.i] === ":") {
869
+ this.i++;
870
+ id += ":" + this.name();
871
+ }
872
+ return id;
873
+ }
874
+ name() {
875
+ if (isBidi(this.cp()))
876
+ this.i++;
877
+ if (!isNameStart(this.cp()))
878
+ this.fail("expected a name");
879
+ const start = this.i;
880
+ while (isNameChar(this.cp()))
881
+ this.i += this.cp() > 65535 ? 2 : 1;
882
+ const value = this.src.slice(start, this.i);
883
+ if (isBidi(this.cp()))
884
+ this.i++;
885
+ return value;
886
+ }
887
+ literal(reason) {
888
+ if (this.src[this.i] === "|")
889
+ return this.quoted();
890
+ const start = this.i;
891
+ while (isNameChar(this.cp()))
892
+ this.i += this.cp() > 65535 ? 2 : 1;
893
+ if (this.i === start)
894
+ this.fail(reason);
895
+ return { kind: "literal", value: this.src.slice(start, this.i) };
896
+ }
897
+ quoted() {
898
+ const open = this.i;
899
+ this.i++;
900
+ let value = "";
901
+ for (;; ) {
902
+ const c = this.cp();
903
+ if (c === -1)
904
+ this.fail("unclosed |", open);
905
+ if (c === 124)
906
+ break;
907
+ if (c === 92)
908
+ value += this.escape();
909
+ else {
910
+ this.textChar(c);
911
+ value += String.fromCodePoint(c);
912
+ this.i += c > 65535 ? 2 : 1;
913
+ }
914
+ }
915
+ this.i++;
916
+ return { kind: "literal", value };
917
+ }
918
+ }
919
+ function expressionsOf(parts) {
920
+ return parts.flatMap((part) => part.type === "expression" ? [part.expression] : []);
921
+ }
922
+ function check(message) {
923
+ const declared = new Map;
924
+ const seen = new Set;
925
+ for (const declaration of message.declarations) {
926
+ const { name, expression } = declaration;
927
+ const refs = (expression.call?.options ?? []).flatMap((option) => option.value.kind === "variable" ? [option.value.name] : []);
928
+ if (!declaration.input && expression.operand?.kind === "variable")
929
+ refs.push(expression.operand.name);
930
+ if (declared.has(name) || seen.has(name) || refs.includes(name))
931
+ throw new MessageSyntaxError(declaration.at, "variable $" + name + " is declared twice or used before its declaration");
932
+ for (const ref of refs)
933
+ seen.add(ref);
934
+ declared.set(name, declaration);
935
+ }
936
+ const { matcher } = message;
937
+ if (matcher) {
938
+ const annotated = (name) => {
939
+ const declaration = declared.get(name);
940
+ if (!declaration)
941
+ return false;
942
+ if (declaration.expression.call)
943
+ return true;
944
+ const operand = declaration.expression.operand;
945
+ return !declaration.input && operand?.kind === "variable" && annotated(operand.name);
946
+ };
947
+ for (const selector of matcher.selectors) {
948
+ if (!annotated(selector.name))
949
+ throw new MessageSyntaxError(selector.at, ".match needs an annotated selector such as {$count :number}");
950
+ }
951
+ const ids = new Set;
952
+ for (const variant of matcher.variants) {
953
+ if (variant.keys.length !== matcher.selectors.length) {
954
+ throw new MessageSyntaxError(variant.at, "a variant has " + variant.keys.length + " keys but .match has " + matcher.selectors.length + " selectors");
955
+ }
956
+ const id = JSON.stringify(variant.keys.map((key) => key === null ? null : key.normalize("NFC")));
957
+ if (ids.has(id))
958
+ throw new MessageSyntaxError(variant.at, "two variants have the same keys");
959
+ ids.add(id);
960
+ }
961
+ if (!matcher.variants.some((variant) => variant.keys.every((key) => key === null)))
962
+ throw new MessageSyntaxError(matcher.at, ".match needs a variant whose keys are all *");
963
+ }
964
+ const all = [
965
+ ...message.declarations.map((declaration) => declaration.expression),
966
+ ...expressionsOf(message.parts),
967
+ ...matcher?.variants.flatMap((variant) => expressionsOf(variant.parts)) ?? []
968
+ ];
969
+ for (const { call } of all) {
970
+ if (call && !Object.hasOwn(FUNCTIONS, call.name))
971
+ throw new MessageSyntaxError(call.at, "function :" + call.name + " is not supported");
972
+ }
973
+ }
974
+ function parseMf2(source) {
975
+ const message = new Parser(source).message();
976
+ check(message);
977
+ return message;
978
+ }
979
+
980
+ // packages/i18n/src/compiler/mf2.ts
981
+ import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
982
+ var PRELUDE_CORE = String.raw`const R = (a, k) => {
983
+ let v = Object.hasOwn(a, k) ? a[k] : undefined;
984
+ if (v === undefined) for (const n of Object.keys(a)) if (n.normalize("NFC") === k) v = a[n];
985
+ return v === undefined ? { x: 1, t: "{$" + k + "}" } : { v, t: "{$" + k + "}" };
986
+ };
987
+ const D = (x, n) => ({ ...x, t: "{$" + n + "}" });
988
+ const O = (x) => (x.x ? undefined : x.v);
989
+ const T = (x, f) => {
990
+ if (x.x) return x.t;
991
+ try {
992
+ const v = x.v;
993
+ if (x.k === "number" || x.k === "integer") return f.n(v, x.i);
994
+ if (x.k === "datetime" || x.k === "date" || x.k === "time") return f.d(x.d, x.i);
995
+ if (x.k === "string") return v;
996
+ return typeof v === "number" || typeof v === "bigint" ? f.n(v) : v instanceof Date ? f.d(v) : String(v);
997
+ } catch {
998
+ return x.t;
999
+ }
1000
+ };
1001
+ `;
1002
+ var PRELUDE_OPTIONS = String.raw`const en = (l) => (v) => (l.includes(String(v)) ? String(v) : undefined);
1003
+ const ds = (v, lo, hi) => {
1004
+ v = String(v);
1005
+ if (!/^(0|[1-9][0-9]?)$/.test(v)) return undefined;
1006
+ v = Number(v);
1007
+ return v >= lo && v <= hi ? v : undefined;
1008
+ };
1009
+ `;
1010
+ var PRELUDE_STRING = String.raw`const S = (x, t) => (x === undefined || x.x ? { x: 1, t } : { k: "string", v: String(x.v), t });
1011
+ `;
1012
+ var PRELUDE_NUMBER = String.raw`const NUM = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/;
1013
+ const NO = {
1014
+ select: en(["plural", "ordinal", "exact"]),
1015
+ signDisplay: en(["auto", "always", "exceptZero", "negative", "never"]),
1016
+ useGrouping: en(["auto", "always", "never", "min2"]),
1017
+ minimumIntegerDigits: (v) => ds(v, 1, 21),
1018
+ minimumFractionDigits: (v) => ds(v, 0, 99),
1019
+ maximumFractionDigits: (v) => ds(v, 0, 99),
1020
+ minimumSignificantDigits: (v) => ds(v, 1, 21),
1021
+ maximumSignificantDigits: (v) => ds(v, 1, 21),
1022
+ trailingZeroDisplay: en(["auto", "stripIfInteger"]),
1023
+ roundingPriority: en(["auto", "morePrecision", "lessPrecision"]),
1024
+ roundingIncrement: (v) => ([1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000].includes(Number(v)) ? Number(v) : undefined),
1025
+ roundingMode: en(["ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven"]),
1026
+ };
1027
+ const NK = ["select", "signDisplay", "useGrouping", "minimumIntegerDigits", "maximumSignificantDigits"];
1028
+ const NI = (fn, x, o, t) => {
1029
+ const bad = { x: 1, t };
1030
+ if (x === undefined || x.x || x.k === "datetime" || x.k === "date" || x.k === "time") return bad;
1031
+ let v = x.v;
1032
+ if (typeof v === "string" && NUM.test(v)) v = Number(v);
1033
+ if (typeof v !== "number" && typeof v !== "bigint") return bad;
1034
+ const keys = fn === "integer" ? NK : Object.keys(NO);
1035
+ const r = {};
1036
+ let ns = x.n || 0;
1037
+ if (x.r) {
1038
+ for (const k of keys) if (k !== "select" && x.r[k] !== undefined) r[k] = x.r[k];
1039
+ if (x.r.select !== undefined) ns = 1;
1040
+ }
1041
+ for (const k of keys) {
1042
+ if (!Object.hasOwn(o, k)) continue;
1043
+ const raw = o[k];
1044
+ if (k === "select") {
1045
+ if (Array.isArray(raw)) ns = 1;
1046
+ else if (NO.select(raw) !== undefined) {
1047
+ r.select = NO.select(raw);
1048
+ ns = 0;
1049
+ }
1050
+ continue;
1051
+ }
1052
+ const val = NO[k](Array.isArray(raw) ? raw[0] : raw);
1053
+ if (val !== undefined) r[k] = val;
1054
+ }
1055
+ if (fn === "integer") v = typeof v === "bigint" ? v : Math.trunc(v) || 0;
1056
+ const i = {};
1057
+ for (const k in r) if (k !== "select") i[k] = k === "useGrouping" && r[k] === "never" ? false : r[k];
1058
+ if (fn === "integer") i.maximumFractionDigits = 0;
1059
+ return { k: fn, v, r, i, n: ns, t };
1060
+ };
1061
+ `;
1062
+ var PRELUDE_DATE = String.raw`const DTL = /^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]{1,3})?(Z|[+-]((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)?$/;
1063
+ const dv = (v) => {
1064
+ if (v instanceof Date) return isNaN(v.getTime()) ? undefined : { ms: v.getTime() };
1065
+ if (typeof v === "number") return isFinite(v) ? { ms: v } : undefined;
1066
+ if (typeof v !== "string" || !DTL.test(v)) return undefined;
1067
+ const at = v.indexOf("T");
1068
+ const date = at < 0 ? v : v.slice(0, at);
1069
+ let time = at < 0 ? "00:00:00" : v.slice(at + 1);
1070
+ let om;
1071
+ const z = /(Z|[+-][0-9]{2}:[0-9]{2})$/.exec(time);
1072
+ if (z) {
1073
+ time = time.slice(0, -z[1].length);
1074
+ om = z[1] === "Z" ? 0 : (z[1][0] === "-" ? -1 : 1) * (Number(z[1].slice(1, 3)) * 60 + Number(z[1].slice(4)));
1075
+ }
1076
+ const ms = Date.parse(date + "T" + time + "Z");
1077
+ if (isNaN(ms)) return undefined;
1078
+ return om === undefined ? { ms, fl: 1 } : { ms: ms - om * 60000, om };
1079
+ };
1080
+ const DO = {
1081
+ fields: en(["weekday", "day-weekday", "month-day", "month-day-weekday", "year-month-day", "year-month-day-weekday"]),
1082
+ length: en(["long", "medium", "short"]),
1083
+ precision: en(["hour", "minute", "second"]),
1084
+ timeZoneStyle: en(["long", "short"]),
1085
+ timeZone: (v) => {
1086
+ v = String(v);
1087
+ if (v === "input" || v === "UTC") return v;
1088
+ try {
1089
+ new Intl.DateTimeFormat("en", { timeZone: v });
1090
+ return v;
1091
+ } catch {
1092
+ return undefined;
1093
+ }
1094
+ },
1095
+ hour12: en(["true", "false"]),
1096
+ calendar: (v) => {
1097
+ v = String(v);
1098
+ try {
1099
+ new Intl.DateTimeFormat("en", { calendar: v });
1100
+ return v;
1101
+ } catch {
1102
+ return undefined;
1103
+ }
1104
+ },
1105
+ };
1106
+ const DA = { dateFields: "fields", dateLength: "length", timePrecision: "precision" };
1107
+ const DT = (fn, x, o, t) => {
1108
+ const bad = { x: 1, t };
1109
+ if (x === undefined || x.x || x.k === "number" || x.k === "integer") return bad;
1110
+ const d = x.k === "datetime" || x.k === "date" || x.k === "time" ? { ms: x.v, om: x.om, fl: x.fl } : dv(x.v);
1111
+ if (!d) return bad;
1112
+ const r = {};
1113
+ if (x.r) for (const k of ["timeZone", "hour12", "calendar"]) if (x.r[k] !== undefined) r[k] = x.r[k];
1114
+ for (const n of Object.keys(o)) {
1115
+ const key = DA[n] || n;
1116
+ const raw = o[n];
1117
+ const over = key === "timeZone" || key === "hour12" || key === "calendar";
1118
+ if (Array.isArray(raw) && !over) continue;
1119
+ const val = DO[key](Array.isArray(raw) ? raw[0] : raw);
1120
+ if (val !== undefined) r[key] = val;
1121
+ }
1122
+ const i = {};
1123
+ if (fn !== "time") {
1124
+ const p = (r.fields || "year-month-day").split("-");
1125
+ const l = r.length || "medium";
1126
+ if (p.includes("year")) i.year = l === "short" ? "2-digit" : "numeric";
1127
+ if (p.includes("month")) i.month = l === "long" ? "long" : l === "medium" ? "short" : "numeric";
1128
+ if (p.includes("day")) i.day = "numeric";
1129
+ if (p.includes("weekday")) i.weekday = l === "long" ? "long" : "short";
1130
+ }
1131
+ if (fn !== "date") {
1132
+ const p = r.precision || "minute";
1133
+ i.hour = "numeric";
1134
+ if (p !== "hour") i.minute = "2-digit";
1135
+ if (p === "second") i.second = "2-digit";
1136
+ }
1137
+ if (r.timeZoneStyle) i.timeZoneName = r.timeZoneStyle;
1138
+ if (r.hour12 !== undefined) i.hour12 = r.hour12 === "true";
1139
+ if (r.calendar) i.calendar = r.calendar;
1140
+ let shown = d.ms;
1141
+ if (r.timeZone === "UTC") i.timeZone = "UTC";
1142
+ else if (r.timeZone === "input") {
1143
+ if (d.om !== undefined) {
1144
+ i.timeZone = "UTC";
1145
+ shown += d.om * 60000;
1146
+ } else if (d.fl) i.timeZone = "UTC";
1147
+ } else if (r.timeZone) i.timeZone = r.timeZone;
1148
+ else if (d.fl) i.timeZone = "UTC";
1149
+ return { k: fn, v: d.ms, om: d.om, fl: d.fl, r, i, d: shown, t };
1150
+ };
1151
+ `;
1152
+ var PRELUDE_SELECT = String.raw`const CAT = { zero: "zero", one: "one", two: "two", few: "few", many: "many", other: "other" };
1153
+ const K = (x, f) => {
1154
+ if (x.x) return [];
1155
+ if (x.k === "string") return [x.v.normalize("NFC")];
1156
+ if ((x.k !== "number" && x.k !== "integer") || x.n) return [];
1157
+ const n = typeof x.v === "bigint" ? Number(x.v) : x.v;
1158
+ const s = x.r.select || "plural";
1159
+ const keys = [String(n)];
1160
+ if (s !== "exact") keys.push(f.p(n, 0, CAT, s === "ordinal"));
1161
+ return keys;
1162
+ };
1163
+ const W = (s, vs) => {
1164
+ let best;
1165
+ let rank;
1166
+ for (const [k, b] of vs) {
1167
+ const r = [];
1168
+ for (let i = 0; i < s.length; i++) {
1169
+ const j = k[i] === null ? s[i].length : s[i].indexOf(k[i]);
1170
+ if (j < 0) break;
1171
+ r.push(j);
1172
+ }
1173
+ if (r.length < s.length) continue;
1174
+ let better = rank === undefined;
1175
+ for (let i = 0; !better && i < r.length && r[i] <= rank[i]; i++) better = r[i] < rank[i];
1176
+ if (better) {
1177
+ rank = r;
1178
+ best = b;
1179
+ }
1180
+ }
1181
+ return best();
1182
+ };
1183
+ `;
1184
+ var q = JSON.stringify;
1185
+ var literalFallback = (value) => "{|" + value.replace(/[\\|]/g, "\\$&") + "|}";
1186
+ function argKind(call) {
1187
+ if (call?.name === "number" || call?.name === "integer")
1188
+ return "number";
1189
+ if (call?.name === "datetime" || call?.name === "date" || call?.name === "time")
1190
+ return "date";
1191
+ return "text";
1192
+ }
1193
+ function compileMf2Catalog(messages, language, options = {}) {
1194
+ const entries = [];
1195
+ const args = {};
1196
+ const tags = {};
1197
+ const needs = { rich: false, core: false, opt: false, str: false, num: false, date: false, sel: false };
1198
+ const where = (key) => {
1199
+ const file = typeof options.file === "function" ? options.file(key) : options.file ?? "locales/" + language + ".json";
1200
+ return file + " " + q(key);
1201
+ };
1202
+ for (const [key, source] of Object.entries(messages)) {
1203
+ let message;
1204
+ try {
1205
+ message = parseMf2(source);
1206
+ } catch (error) {
1207
+ if (error instanceof MessageSyntaxError)
1208
+ throw new DiagnosticError3("HAMUR_E5807", error.message, { at: where(key) });
1209
+ throw error;
1210
+ }
1211
+ const kinds = {};
1212
+ const scope = new Map;
1213
+ let next = 0;
1214
+ let dynamic = message.declarations.length > 0 || message.matcher !== undefined;
1215
+ const use = (name, kind) => {
1216
+ const known = kinds[name];
1217
+ if (known === undefined || known === "text")
1218
+ kinds[name] = kind;
1219
+ else if (kind !== "text" && known !== kind)
1220
+ throw new DiagnosticError3("HAMUR_E5808", "argument " + q(name) + " is used as both " + known + " and " + kind, {
1221
+ at: where(key)
1222
+ });
1223
+ };
1224
+ const ref = (name, kind) => {
1225
+ const id = scope.get(name);
1226
+ if (id !== undefined)
1227
+ return id;
1228
+ use(name, kind);
1229
+ needs.core = true;
1230
+ return "R(a, " + q(name) + ")";
1231
+ };
1232
+ const expression = ({ operand, call }) => {
1233
+ let x = "undefined";
1234
+ let t = "{:" + (call?.name ?? "") + "}";
1235
+ if (operand?.kind === "literal") {
1236
+ t = literalFallback(operand.value);
1237
+ x = "{ v: " + q(operand.value) + ", t: " + q(t) + " }";
1238
+ } else if (operand) {
1239
+ t = "{$" + operand.name + "}";
1240
+ x = ref(operand.name, argKind(call));
1241
+ }
1242
+ if (!call)
1243
+ return x;
1244
+ const known = FUNCTIONS[call.name];
1245
+ const given = call.options.filter((option) => known.includes(option.name)).map((option) => q(option.name) + ": " + (option.value.kind === "literal" ? q(option.value.value) : "[O(" + ref(option.value.name, "text") + ")]"));
1246
+ const opts = "{ " + given.join(", ") + " }";
1247
+ needs.core = true;
1248
+ if (call.name === "string") {
1249
+ needs.str = true;
1250
+ return "S(" + x + ", " + q(t) + ")";
1251
+ }
1252
+ if (call.name === "number" || call.name === "integer") {
1253
+ needs.opt = needs.num = true;
1254
+ return "NI(" + q(call.name) + ", " + x + ", " + opts + ", " + q(t) + ")";
1255
+ }
1256
+ needs.opt = needs.date = true;
1257
+ return "DT(" + q(call.name) + ", " + x + ", " + opts + ", " + q(t) + ")";
1258
+ };
1259
+ const names = new Set;
1260
+ const pattern = (parts) => {
1261
+ let pieces = [];
1262
+ let text;
1263
+ const open = [];
1264
+ const flush = () => {
1265
+ if (text !== undefined)
1266
+ pieces.push(q(text));
1267
+ text = undefined;
1268
+ };
1269
+ const closeTop = () => {
1270
+ const frame = open.pop();
1271
+ const children = "J(" + pieces.join(", ") + ")";
1272
+ pieces = frame.pieces;
1273
+ pieces.push("{ tag: " + q(frame.name) + ", children: " + children + " }");
1274
+ };
1275
+ const rich = parts.some((part) => part.type === "markup");
1276
+ if (rich)
1277
+ needs.rich = dynamic = true;
1278
+ for (const part of parts) {
1279
+ if (part.type === "markup") {
1280
+ names.add(part.name);
1281
+ flush();
1282
+ if (part.kind === "open") {
1283
+ open.push({ name: part.name, pieces });
1284
+ pieces = [];
1285
+ } else if (part.kind === "standalone")
1286
+ pieces.push("{ tag: " + q(part.name) + ", children: [] }");
1287
+ else if (open.some((frame) => frame.name === part.name)) {
1288
+ while (open[open.length - 1].name !== part.name)
1289
+ closeTop();
1290
+ closeTop();
1291
+ }
1292
+ } else if (part.type === "text")
1293
+ text = (text ?? "") + part.value;
1294
+ else if (part.type === "expression") {
1295
+ const { operand, call } = part.expression;
1296
+ if (!call && operand?.kind === "literal")
1297
+ text = (text ?? "") + operand.value;
1298
+ else {
1299
+ flush();
1300
+ dynamic = true;
1301
+ needs.core = true;
1302
+ pieces.push("T(" + expression(part.expression) + ", f)");
1303
+ }
1304
+ }
1305
+ }
1306
+ flush();
1307
+ while (open.length)
1308
+ closeTop();
1309
+ if (rich)
1310
+ return "J(" + pieces.join(", ") + ")";
1311
+ return pieces.length ? pieces.join(" + ") : '""';
1312
+ };
1313
+ const lines = [];
1314
+ for (const declaration of message.declarations) {
1315
+ const id = "d" + next++;
1316
+ lines.push("const " + id + " = D(" + expression(declaration.expression) + ", " + q(declaration.name) + ");");
1317
+ scope.set(declaration.name, id);
1318
+ needs.core = true;
1319
+ }
1320
+ let body;
1321
+ const { matcher } = message;
1322
+ if (matcher) {
1323
+ needs.sel = true;
1324
+ const selectors = matcher.selectors.map((selector) => "K(" + scope.get(selector.name) + ", f)");
1325
+ const variants = matcher.variants.map((variant) => "[[" + variant.keys.map((k) => k === null ? "null" : q(k.normalize("NFC"))).join(", ") + "], () => " + pattern(variant.parts) + "]");
1326
+ body = "W([" + selectors.join(", ") + "], [" + variants.join(", ") + "])";
1327
+ } else
1328
+ body = pattern(message.parts);
1329
+ args[key] = kinds;
1330
+ if (names.size)
1331
+ tags[key] = [...names];
1332
+ let value;
1333
+ if (!dynamic)
1334
+ value = body;
1335
+ else if (lines.length === 0)
1336
+ value = "(a, f) => " + body;
1337
+ else
1338
+ value = "(a, f) => { " + lines.join(" ") + " return " + body + "; }";
1339
+ entries.push(" " + q(key) + ": " + value + ",");
1340
+ }
1341
+ const prelude = [
1342
+ needs.rich ? `const J = (...p) => p.flat();
1343
+ ` : "",
1344
+ needs.core ? PRELUDE_CORE : "",
1345
+ needs.opt ? PRELUDE_OPTIONS : "",
1346
+ needs.str ? PRELUDE_STRING : "",
1347
+ needs.num ? PRELUDE_NUMBER : "",
1348
+ needs.date ? PRELUDE_DATE : "",
1349
+ needs.sel ? PRELUDE_SELECT : ""
1350
+ ].join("");
1351
+ const body = entries.length ? `export default {
1352
+ ` + entries.join(`
1353
+ `) + `
1354
+ };` : "export default {};";
1355
+ return { code: prelude + body + `
1356
+ `, args, tags };
1357
+ }
1358
+
1359
+ // packages/i18n/src/compiler/compile.ts
1360
+ import { DiagnosticError as DiagnosticError4 } from "hamur/kit";
1361
+ var q2 = JSON.stringify;
1362
+ function hasTag(nodes) {
1363
+ return nodes.some((node) => node.type === "tag" || (node.type === "plural" || node.type === "select") && node.cases.some(({ body }) => hasTag(body)));
1364
+ }
1365
+ function collectTags(nodes, into) {
1366
+ for (const node of nodes) {
1367
+ if (node.type === "tag") {
1368
+ into.add(node.name);
1369
+ collectTags(node.children, into);
1370
+ } else if (node.type === "plural" || node.type === "select")
1371
+ for (const { body } of node.cases)
1372
+ collectTags(body, into);
1373
+ }
1374
+ }
1375
+ function categoriesOf(language, type) {
1376
+ return new Set(new Intl.PluralRules(language, { type }).resolvedOptions().pluralCategories);
1377
+ }
1378
+ function compileCatalog(messages, language, options = {}) {
1379
+ if (options.syntax === "mf2")
1380
+ return compileMf2Catalog(messages, language, options);
1381
+ const entries = [];
1382
+ const args = {};
1383
+ const tags = {};
1384
+ const helpers = { g: false, v: false, j: false, m: false };
1385
+ const where = (key) => {
1386
+ const file = typeof options.file === "function" ? options.file(key) : options.file ?? `locales/${language}.json`;
1387
+ return `${file} ${q2(key)}`;
1388
+ };
1389
+ const cardinal = categoriesOf(language, "cardinal");
1390
+ const ordinal = categoriesOf(language, "ordinal");
1391
+ for (const [key, source] of Object.entries(messages)) {
1392
+ let nodes;
1393
+ try {
1394
+ nodes = parseMessage(source);
1395
+ } catch (error) {
1396
+ if (error instanceof MessageSyntaxError)
1397
+ throw new DiagnosticError4("HAMUR_E5807", error.message, { at: where(key) });
1398
+ throw error;
1399
+ }
1400
+ const kinds = {};
1401
+ const use = (name, kind) => {
1402
+ const known = kinds[name];
1403
+ if (known === undefined || known === "text")
1404
+ kinds[name] = kind;
1405
+ else if (kind !== "text" && known !== kind)
1406
+ throw new DiagnosticError4("HAMUR_E5808", `argument ${q2(name)} is used as both ${known} and ${kind}`, {
1407
+ at: where(key)
1408
+ });
1409
+ };
1410
+ const ref = (name) => {
1411
+ helpers.g = true;
1412
+ return `g(a, ${q2(name)})`;
1413
+ };
1414
+ const emit = (list, scope) => list.map((node) => {
1415
+ switch (node.type) {
1416
+ case "text":
1417
+ return q2(node.value);
1418
+ case "pound":
1419
+ scope.state.used = true;
1420
+ return scope.pound;
1421
+ case "arg":
1422
+ use(node.name, "text");
1423
+ helpers.v = true;
1424
+ return `v(${ref(node.name)}, f)`;
1425
+ case "number": {
1426
+ use(node.name, "number");
1427
+ const opts = {
1428
+ decimal: "{}",
1429
+ integer: "{ maximumFractionDigits: 0 }",
1430
+ percent: '{ style: "percent" }',
1431
+ currency: `{ style: "currency", currency: ${q2(node.currency)} }`,
1432
+ skeleton: q2(node.options)
1433
+ }[node.style];
1434
+ if (node.scale === undefined)
1435
+ return `f.n(${ref(node.name)}, ${opts})`;
1436
+ helpers.m = true;
1437
+ return `f.n(m(${ref(node.name)}, ${node.scale}), ${opts})`;
1438
+ }
1439
+ case "tag":
1440
+ return `{ tag: ${q2(node.name)}, children: ${join(node.children, scope)} }`;
1441
+ case "date":
1442
+ use(node.name, "date");
1443
+ return `f.d(${ref(node.name)}, { ${node.kind === "date" ? "dateStyle" : "timeStyle"}: ${q2(node.style)} })`;
1444
+ case "select": {
1445
+ use(node.name, "select");
1446
+ const cases = node.cases.map(({ key: label, body }) => `${q2(label)}: ${caseBody(body, { pound: scope.pound, state: scope.state, depth: scope.depth }, false)}`);
1447
+ return `f.s(${ref(node.name)}, { ${cases.join(", ")} })`;
1448
+ }
1449
+ case "plural": {
1450
+ use(node.name, "number");
1451
+ const known = node.ordinal ? ordinal : cardinal;
1452
+ for (const { key: label } of node.cases) {
1453
+ if (label.startsWith("=") || label === "other" || known.has(label))
1454
+ continue;
1455
+ options.warn?.(`${where(key)}: plural case ${q2(label)} never applies to ${language}`);
1456
+ }
1457
+ const cases = node.cases.map(({ key: label, body }) => {
1458
+ const own = { pound: `c${scope.depth}`, state: { used: false }, depth: scope.depth + 1 };
1459
+ return `${q2(label)}: ${caseBody(body, own, true)}`;
1460
+ });
1461
+ return `f.p(${ref(node.name)}, ${node.offset}, { ${cases.join(", ")} }, ${node.ordinal})`;
1462
+ }
1463
+ }
1464
+ });
1465
+ const join = (list, scope) => {
1466
+ helpers.j = true;
1467
+ return `J(${emit(list, scope).join(", ")})`;
1468
+ };
1469
+ const caseBody = (body, scope, takesCount) => {
1470
+ const parts = emit(body, scope);
1471
+ let text = parts.length === 0 ? '""' : parts.join(" + ");
1472
+ if (hasTag(body)) {
1473
+ helpers.j = true;
1474
+ text = `J(${parts.join(", ")})`;
1475
+ }
1476
+ if (body.every((node) => node.type === "text"))
1477
+ return text;
1478
+ return takesCount && scope.state.used ? `(${scope.pound}) => ${text}` : `() => ${text}`;
1479
+ };
1480
+ const top = { pound: undefined, state: { used: false }, depth: 0 };
1481
+ const rich = hasTag(nodes);
1482
+ const parts = emit(nodes, top);
1483
+ args[key] = kinds;
1484
+ if (rich) {
1485
+ const names = new Set;
1486
+ collectTags(nodes, names);
1487
+ tags[key] = [...names];
1488
+ helpers.j = true;
1489
+ }
1490
+ const dynamic = nodes.some((node) => node.type !== "text");
1491
+ const body = rich ? `J(${parts.join(", ")})` : parts.length ? parts.join(" + ") : '""';
1492
+ entries.push(` ${q2(key)}: ${dynamic ? `(a, f) => ${body}` : body},`);
1493
+ }
1494
+ const lines = [];
1495
+ if (helpers.g)
1496
+ lines.push('const g = (a, k) => (k in a && Object.hasOwn(a, k) && a[k] !== undefined ? a[k] : "{" + k + "}");');
1497
+ if (helpers.v)
1498
+ lines.push('const v = (x, f) => (typeof x === "number" || typeof x === "bigint" ? f.n(x) : x instanceof Date ? f.d(x) : String(x));');
1499
+ if (helpers.j)
1500
+ lines.push("const J = (...p) => p.flat();");
1501
+ if (helpers.m)
1502
+ lines.push('const m = (x, s) => (typeof x === "number" || typeof x === "bigint" ? Number(x) * s : x);');
1503
+ lines.push(entries.length ? `export default {
1504
+ ${entries.join(`
1505
+ `)}
1506
+ };` : "export default {};");
1507
+ return { code: `${lines.join(`
1508
+ `)}
1509
+ `, args, tags };
1510
+ }
1511
+
1512
+ // packages/i18n/src/runtime/chain.ts
1513
+ function fallbackChain(fallback, defaultLocale, code) {
1514
+ if (code === defaultLocale || fallback === false)
1515
+ return [];
1516
+ if (fallback === undefined || fallback === "default")
1517
+ return [defaultLocale];
1518
+ const own = (fallback[code] ?? []).filter((entry) => entry !== code && entry !== defaultLocale);
1519
+ return [...new Set(own), defaultLocale];
1520
+ }
1521
+
1522
+ // packages/i18n/src/build/routes.ts
1523
+ import { relative as relative2 } from "node:path";
1524
+ import {
1525
+ DiagnosticError as DiagnosticError5,
1526
+ addAppPlugin,
1527
+ addRouteMiddleware,
1528
+ addTemplate as addTemplate2,
1529
+ createResolver as createResolver2,
1530
+ diagnostic as diagnostic2,
1531
+ extendPages,
1532
+ useLogger as useLogger2
1533
+ } from "hamur/kit";
1534
+
1535
+ // packages/i18n/src/runtime/match.ts
1536
+ var NAME = /^[A-Za-z_][A-Za-z0-9_]*/;
1537
+ function splitPath(path) {
1538
+ const start = path.startsWith("/") ? 1 : 0;
1539
+ const end = path.length > start && path.endsWith("/") ? path.length - 1 : path.length;
1540
+ return end <= start ? [] : path.slice(start, end).split("/");
1541
+ }
1542
+ var SEPARATORS = "-_.~";
1543
+ function optionalRun(parts, index) {
1544
+ const next = parts[index + 1];
1545
+ if (typeof next === "string") {
1546
+ let run = 0;
1547
+ while (run < next.length && SEPARATORS.includes(next[run]))
1548
+ run++;
1549
+ return { side: "after", run: next.slice(0, run) };
1550
+ }
1551
+ const previous = parts[index - 1];
1552
+ let run = previous.length;
1553
+ while (run > 0 && SEPARATORS.includes(previous[run - 1]))
1554
+ run--;
1555
+ return { side: "before", run: previous.slice(run) };
1556
+ }
1557
+ function parseSegment(text) {
1558
+ if (text.startsWith("**:")) {
1559
+ const optional = text.endsWith("?");
1560
+ const name = text.slice(3, optional ? -1 : undefined);
1561
+ if (NAME.exec(name)?.[0] !== name)
1562
+ throw new Error(`bad catch-all name in "${text}"`);
1563
+ return { kind: optional ? "optionalCatchAll" : "catchAll", name };
1564
+ }
1565
+ if (!text.includes(":") && !text.includes("\\"))
1566
+ return { kind: "static", text };
1567
+ const parts = [];
1568
+ let literal = "";
1569
+ let stray = false;
1570
+ let i = 0;
1571
+ while (i < text.length) {
1572
+ if (text[i] === "\\") {
1573
+ if (i === text.length - 1)
1574
+ throw new Error(`trailing "\\" in "${text}"`);
1575
+ literal += text[i + 1];
1576
+ i += 2;
1577
+ continue;
1578
+ }
1579
+ if (text[i] !== ":") {
1580
+ if (text[i] === "?")
1581
+ stray = true;
1582
+ literal += text[i++];
1583
+ continue;
1584
+ }
1585
+ const name = NAME.exec(text.slice(i + 1))?.[0];
1586
+ if (!name)
1587
+ throw new Error(`missing param name in "${text}"`);
1588
+ if (literal)
1589
+ parts.push(literal);
1590
+ else if (parts.length > 0)
1591
+ throw new Error(`params in "${text}" need text between them`);
1592
+ literal = "";
1593
+ i += 1 + name.length;
1594
+ const optional = text[i] === "?";
1595
+ if (optional)
1596
+ i++;
1597
+ if (optional && parts.length === 0 && i === text.length)
1598
+ return { kind: "optional", name };
1599
+ parts.push(optional ? { param: name, optional: true } : { param: name });
1600
+ }
1601
+ if (parts.length === 0)
1602
+ return { kind: "static", text: literal };
1603
+ if (literal)
1604
+ parts.push(literal);
1605
+ if (stray)
1606
+ throw new Error(`unexpected "?" in "${text}"`);
1607
+ const params = parts.filter((part) => typeof part !== "string");
1608
+ if (params.length > 1 && params.some((part) => part.optional))
1609
+ throw new Error(`an optional param in "${text}" cannot share the segment with another param`);
1610
+ const [only] = parts;
1611
+ return parts.length === 1 && typeof only !== "string" ? { kind: "param", name: only.param } : { kind: "mixed", parts };
1612
+ }
1613
+ function parsePattern(pattern) {
1614
+ if (!pattern.startsWith("/"))
1615
+ throw new Error('must start with "/"');
1616
+ const segments = splitPath(pattern).map((text) => {
1617
+ if (text === "")
1618
+ throw new Error("empty segment");
1619
+ return parseSegment(text);
1620
+ });
1621
+ const names = new Set;
1622
+ segments.forEach((segment, index) => {
1623
+ for (const name of paramsOf(segment)) {
1624
+ if (names.has(name))
1625
+ throw new Error(`duplicate param "${name}"`);
1626
+ names.add(name);
1627
+ }
1628
+ if ((segment.kind === "optional" || segment.kind === "catchAll" || segment.kind === "optionalCatchAll") && index !== segments.length - 1) {
1629
+ throw new Error(`"${segment.kind}" segment must be last`);
1630
+ }
1631
+ });
1632
+ return segments;
1633
+ }
1634
+ function paramsOf(segment) {
1635
+ if (segment.kind === "static")
1636
+ return [];
1637
+ if (segment.kind === "mixed")
1638
+ return segment.parts.flatMap((part) => typeof part === "string" ? [] : [part.param]);
1639
+ return [segment.name];
1640
+ }
1641
+ var escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
1642
+ function mixedRegex(parts) {
1643
+ const at = parts.findIndex((part) => typeof part !== "string" && part.optional);
1644
+ const { side, run } = at === -1 ? { side: "after", run: "" } : optionalRun(parts, at);
1645
+ const source = parts.map((part, index) => {
1646
+ if (typeof part === "string") {
1647
+ if (at === -1 || index !== at + (side === "after" ? 1 : -1))
1648
+ return escapeRegex(part);
1649
+ return escapeRegex(side === "after" ? part.slice(run.length) : part.slice(0, part.length - run.length));
1650
+ }
1651
+ if (!part.optional)
1652
+ return "(.+?)";
1653
+ return side === "after" ? `(?:(.+?)${escapeRegex(run)})?` : `(?:${escapeRegex(run)}(.+?))?`;
1654
+ }).join("");
1655
+ return new RegExp(`^${source}$`);
1656
+ }
1657
+ function insert(root, segments, data) {
1658
+ const names = [];
1659
+ let node = root;
1660
+ let slot = "route";
1661
+ let catchAll;
1662
+ for (const segment of segments) {
1663
+ if (segment.kind === "static") {
1664
+ node.statics ??= new Map;
1665
+ let next = node.statics.get(segment.text);
1666
+ if (!next)
1667
+ node.statics.set(segment.text, next = {});
1668
+ node = next;
1669
+ } else if (segment.kind === "mixed") {
1670
+ const key = segment.parts.map((part) => typeof part === "string" ? part : part.optional ? "\x00?\x00" : "\x00").join("");
1671
+ names.push(...paramsOf(segment));
1672
+ node.mixed ??= [];
1673
+ let child = node.mixed.find((entry) => entry.key === key);
1674
+ if (!child) {
1675
+ const regex = mixedRegex(segment.parts);
1676
+ const literal = segment.parts.reduce((sum, part) => sum + (typeof part === "string" ? part.length : 0), 0);
1677
+ node.mixed.push(child = {
1678
+ key,
1679
+ regex,
1680
+ literal,
1681
+ optional: segment.parts.some((part) => typeof part !== "string" && part.optional === true),
1682
+ node: {}
1683
+ });
1684
+ node.mixed.sort((a, b) => Number(a.optional) - Number(b.optional) || b.literal - a.literal);
1685
+ }
1686
+ node = child.node;
1687
+ } else if (segment.kind === "param") {
1688
+ names.push(segment.name);
1689
+ node = node.param ??= {};
1690
+ } else if (segment.kind === "optional") {
1691
+ names.push(segment.name);
1692
+ slot = "optional";
1693
+ } else {
1694
+ catchAll = segment.name;
1695
+ slot = segment.kind;
1696
+ }
1697
+ }
1698
+ node[slot] ??= { data, names, ...catchAll !== undefined ? { catchAll } : {} };
1699
+ }
1700
+ function leafMatch(leaf, captured, rest) {
1701
+ const params = {};
1702
+ leaf.names.forEach((name, index) => {
1703
+ if (captured[index] !== undefined)
1704
+ params[name] = captured[index];
1705
+ });
1706
+ if (leaf.catchAll !== undefined)
1707
+ params[leaf.catchAll] = rest;
1708
+ return { ...leaf.data, params };
1709
+ }
1710
+ function walk(node, segments, index, captured) {
1711
+ if (index === segments.length) {
1712
+ const leaf = node.route ?? node.optional ?? node.optionalCatchAll;
1713
+ return leaf && leafMatch(leaf, captured, []);
1714
+ }
1715
+ const segment = segments[index];
1716
+ const next = node.statics?.get(segment);
1717
+ const viaStatic = next && walk(next, segments, index + 1, captured);
1718
+ if (viaStatic)
1719
+ return viaStatic;
1720
+ if (segment !== "") {
1721
+ for (const child of node.mixed ?? []) {
1722
+ const found = child.regex.exec(segment);
1723
+ if (!found)
1724
+ continue;
1725
+ const depth = captured.length;
1726
+ captured.push(...found.slice(1));
1727
+ const match = walk(child.node, segments, index + 1, captured);
1728
+ if (match)
1729
+ return match;
1730
+ captured.length = depth;
1731
+ }
1732
+ if (node.param) {
1733
+ captured.push(segment);
1734
+ const match = walk(node.param, segments, index + 1, captured);
1735
+ if (match)
1736
+ return match;
1737
+ captured.pop();
1738
+ }
1739
+ if (index === segments.length - 1 && node.optional)
1740
+ return leafMatch(node.optional, [...captured, segment], []);
1741
+ }
1742
+ const all = node.catchAll ?? node.optionalCatchAll;
1743
+ return all && leafMatch(all, captured, segments.slice(index));
1744
+ }
1745
+ function encodeParam(value) {
1746
+ return encodeURIComponent(value);
1747
+ }
1748
+ function createMatcher(table) {
1749
+ const root = {};
1750
+ const parsed = new Map;
1751
+ for (const [name, patterns] of Object.entries(table.routes)) {
1752
+ for (const [code, pattern] of Object.entries(patterns)) {
1753
+ const segments = parsePattern(pattern);
1754
+ parsed.set(`${name}\x00${code}`, segments);
1755
+ insert(root, segments, { name, code });
1756
+ }
1757
+ }
1758
+ for (const [name, patterns] of Object.entries(table.aliases ?? {})) {
1759
+ for (const [code, pattern] of Object.entries(patterns))
1760
+ insert(root, parsePattern(pattern), { name, code });
1761
+ }
1762
+ return {
1763
+ matchPath(path) {
1764
+ const segments = splitPath(path);
1765
+ try {
1766
+ for (let i = 0;i < segments.length; i++)
1767
+ if (segments[i].includes("%"))
1768
+ segments[i] = decodeURIComponent(segments[i]);
1769
+ } catch {
1770
+ return;
1771
+ }
1772
+ return walk(root, segments, 0, []);
1773
+ },
1774
+ buildPath(name, code, params = {}) {
1775
+ const segments = parsed.get(`${name}\x00${code}`);
1776
+ if (!segments) {
1777
+ if (!table.routes[name])
1778
+ throw new Error(`i18n: no route named "${name}"`);
1779
+ throw new Error(`i18n: route "${name}" has no path in "${code}"`);
1780
+ }
1781
+ const value = (param) => params[param];
1782
+ const required = (param) => {
1783
+ const given = value(param);
1784
+ const text = Array.isArray(given) ? given.join("/") : given;
1785
+ if (text === undefined || text === "")
1786
+ throw new Error(`i18n: route "${name}" needs the param "${param}"`);
1787
+ return text;
1788
+ };
1789
+ const out = [];
1790
+ for (const segment of segments) {
1791
+ if (segment.kind === "static")
1792
+ out.push(segment.text);
1793
+ else if (segment.kind === "mixed") {
1794
+ const optional = segment.parts.find((part) => typeof part !== "string" && part.optional);
1795
+ const absent = optional !== undefined && (value(optional.param) === undefined || value(optional.param) === "");
1796
+ const at = segment.parts.findIndex((part) => part === optional);
1797
+ const { side, run } = absent ? optionalRun(segment.parts, at) : { side: "after", run: "" };
1798
+ out.push(segment.parts.flatMap((part, index) => {
1799
+ if (typeof part !== "string")
1800
+ return absent && part === optional ? [] : [encodeParam(required(part.param))];
1801
+ if (!absent || index !== at + (side === "after" ? 1 : -1))
1802
+ return [part];
1803
+ return [side === "after" ? part.slice(run.length) : part.slice(0, part.length - run.length)];
1804
+ }).join(""));
1805
+ } else if (segment.kind === "param")
1806
+ out.push(encodeParam(required(segment.name)));
1807
+ else {
1808
+ const given = value(segment.name);
1809
+ const list = given === undefined ? [] : Array.isArray(given) ? given : [given];
1810
+ if (segment.kind === "catchAll" && list.length === 0)
1811
+ required(segment.name);
1812
+ out.push(...list.filter((part) => part !== "").map(encodeParam));
1813
+ }
1814
+ }
1815
+ return `/${out.join("/")}`;
1816
+ }
1817
+ };
1818
+ }
1819
+
1820
+ // packages/i18n/src/build/routes.ts
1821
+ var SEPARATOR = "___";
1822
+ function paramsOf2(segments) {
1823
+ return segments.flatMap((segment) => {
1824
+ if (segment.kind === "static")
1825
+ return [];
1826
+ if (segment.kind === "mixed")
1827
+ return segment.parts.flatMap((part) => typeof part === "string" ? [] : [{ name: part.param, kind: part.optional ? "optional" : "param" }]);
1828
+ return [{ name: segment.name, kind: segment.kind }];
1829
+ });
1830
+ }
1831
+ var signature = (segments) => paramsOf2(segments).map(({ name, kind }) => `${name}:${kind}`).sort().join(",");
1832
+ function shapeOf(path) {
1833
+ const parts = parsePattern(path).map((segment) => {
1834
+ if (segment.kind === "static")
1835
+ return segment.text;
1836
+ if (segment.kind === "mixed")
1837
+ return segment.parts.map((part) => typeof part === "string" ? part : part.optional ? "\x00?\x00" : "\x00").join("");
1838
+ return { param: ":", optional: ":?", catchAll: "**", optionalCatchAll: "**?" }[segment.kind];
1839
+ });
1840
+ return `/${parts.join("/")}`;
1841
+ }
1842
+ function flatten(records, ancestors = []) {
1843
+ return records.flatMap((record) => [...flatten(record.children, [...ancestors, record.name]), { record, ancestors }]);
1844
+ }
1845
+ function tableOf(records, options, copies) {
1846
+ const table = { copies, routes: {}, aliases: {} };
1847
+ for (const { record } of flatten(records)) {
1848
+ const index = record.name.indexOf(SEPARATOR);
1849
+ const base = index === -1 ? record.name : record.name.slice(0, index);
1850
+ const code = index === -1 ? options.defaultLocale : record.name.slice(index + SEPARATOR.length);
1851
+ const own = index !== -1 && code === options.defaultLocale && options.strategy === "prefix_and_default" ? table.aliases[base] ??= {} : table.routes[base] ??= {};
1852
+ own[code] = record.path;
1853
+ }
1854
+ return table;
1855
+ }
1856
+ function localizeRoutes(routes, options, rootDir = "") {
1857
+ if (options.strategy === "no_prefix")
1858
+ return { routes, table: tableOf(routes, options, []) };
1859
+ const shown = (file) => rootDir ? relative2(rootDir, file) : file;
1860
+ const originals = flatten(routes);
1861
+ for (const { record } of originals) {
1862
+ if (record.name.includes(SEPARATOR))
1863
+ throw new DiagnosticError5("HAMUR_E5816", `i18n: route name "${record.name}" (${shown(record.file)}) contains "___", which route copies use`);
1864
+ }
1865
+ const byName = new Map(originals.map(({ record }) => [record.name, record]));
1866
+ const codes = new Set(options.locales.map((locale) => locale.code));
1867
+ for (const [name, paths] of Object.entries(options.pages)) {
1868
+ const record = byName.get(name);
1869
+ if (!record)
1870
+ throw new DiagnosticError5("HAMUR_E5817", `i18n.pages: no route named "${name}"`);
1871
+ const own = parsePattern(record.path);
1872
+ for (const [code, path] of Object.entries(paths ?? {})) {
1873
+ if (!codes.has(code))
1874
+ throw new DiagnosticError5("HAMUR_E5818", `i18n.pages.${name}: "${code}" is not in i18n.locales`);
1875
+ if (path === false)
1876
+ continue;
1877
+ let segments;
1878
+ try {
1879
+ if (typeof path !== "string")
1880
+ throw new Error("not a string");
1881
+ segments = parsePattern(path);
1882
+ } catch {
1883
+ throw new DiagnosticError5("HAMUR_E5819", `i18n.pages.${name}.${code} ${JSON.stringify(path)} must be a route path starting with "/"`);
1884
+ }
1885
+ if (signature(segments) !== signature(own)) {
1886
+ const names = paramsOf2(own).map((param) => param.name);
1887
+ throw new DiagnosticError5("HAMUR_E5820", `i18n.pages.${name}.${code} ${JSON.stringify(path)} must keep the params of "${record.path}" (${names.length ? names.join(", ") : "none"})`);
1888
+ }
1889
+ }
1890
+ }
1891
+ const localized = (record, code) => {
1892
+ const own = options.pages[record.name]?.[code];
1893
+ return typeof own === "string" ? own : record.path;
1894
+ };
1895
+ const domains = options.domains;
1896
+ const absent = (record, code) => options.pages[record.name]?.[code] === false;
1897
+ const prefixed = (code, path) => domains ? path : `/${code}${path === "/" ? "" : path}`;
1898
+ const copy = (record, code) => ({
1899
+ ...record,
1900
+ name: `${record.name}${SEPARATOR}${code}`,
1901
+ path: prefixed(code, localized(record, code)),
1902
+ children: record.children.filter((child) => !absent(child, code)).map((child) => copy(child, code))
1903
+ });
1904
+ const moved = (record) => {
1905
+ const children = record.children.map(moved);
1906
+ const path = localized(record, options.defaultLocale);
1907
+ return path === record.path && children.every((child, index) => child === record.children[index]) ? record : { ...record, path, children };
1908
+ };
1909
+ const keep = domains !== undefined || options.strategy === "prefix_except_default" || options.strategy === "prefix_and_default";
1910
+ const copies = options.locales.map((locale) => locale.code).filter((code) => options.strategy !== "prefix_except_default" && !domains || code !== options.defaultLocale);
1911
+ const kept = keep ? routes.map(moved) : [];
1912
+ const differs = (record, code) => localized(record, code) !== localized(record, options.defaultLocale) || record.children.some((child) => differs(child, code));
1913
+ const made = new Map;
1914
+ const wanted = (record, code) => {
1915
+ if (absent(record, code))
1916
+ return false;
1917
+ if (!domains)
1918
+ return true;
1919
+ if (!differs(record, code))
1920
+ return false;
1921
+ const paths = flatten([copy(record, code)]).map((entry) => entry.record.path).join(`
1922
+ `);
1923
+ let seen = made.get(record);
1924
+ if (!seen)
1925
+ made.set(record, seen = new Set);
1926
+ if (seen.has(paths))
1927
+ return false;
1928
+ seen.add(paths);
1929
+ return true;
1930
+ };
1931
+ const copied = copies.flatMap((code) => routes.filter((record) => wanted(record, code)).map((record) => copy(record, code)));
1932
+ const result = [...kept, ...copied];
1933
+ const table = tableOf(result, options, domains ? [] : copies);
1934
+ if (domains) {
1935
+ table.domains = domains;
1936
+ for (const { record } of originals) {
1937
+ const own = table.routes[record.name] ??= {};
1938
+ for (const { code } of options.locales)
1939
+ own[code] ??= localized(record, code);
1940
+ }
1941
+ }
1942
+ if (!domains) {
1943
+ for (const { record } of originals) {
1944
+ for (const code of copies) {
1945
+ if (!absent(record, code))
1946
+ continue;
1947
+ (table.routes[record.name] ??= {})[code] = prefixed(code, record.path);
1948
+ (table.missing ??= {})[record.name] = [...table.missing[record.name] ?? [], code];
1949
+ }
1950
+ }
1951
+ }
1952
+ const all = flatten(result);
1953
+ const seen = new Map;
1954
+ for (const entry of [
1955
+ ...all.filter((item) => !item.record.name.includes(SEPARATOR)),
1956
+ ...all.filter((item) => item.record.name.includes(SEPARATOR))
1957
+ ]) {
1958
+ const shape = shapeOf(entry.record.path);
1959
+ const other = seen.get(shape);
1960
+ const related = other && (other.ancestors.includes(entry.record.name) || entry.ancestors.includes(other.record.name));
1961
+ if (other && !related && entry.record.name.includes(SEPARATOR)) {
1962
+ throw new DiagnosticError5("HAMUR_E5821", `i18n: route copy "${entry.record.path}" (${entry.record.name}) clashes with "${other.record.path}" (${other.record.name}, ${shown(other.record.file)})`);
1963
+ }
1964
+ if (!other)
1965
+ seen.set(shape, entry);
1966
+ }
1967
+ return { routes: result, table };
1968
+ }
1969
+ var tables = new WeakMap;
1970
+ var routeTableOf = (hamur) => tables.get(hamur) ?? { copies: [], routes: {} };
1971
+ var rememberRouteTable = (hamur, table) => void tables.set(hamur, table);
1972
+ var PRERENDER_WARNING = 'i18n: "/" is prerendered, so detect.redirect "root" never runs for it';
1973
+ function setupRoutes(options, hamur) {
1974
+ const r = createResolver2(new URL("../../src/build/routes.ts", import.meta.url).href);
1975
+ let table = { copies: [], routes: {} };
1976
+ extendPages((routes) => {
1977
+ const localized = localizeRoutes(routes, options, hamur.options.rootDir);
1978
+ routes.splice(0, routes.length, ...localized.routes);
1979
+ table = localized.table;
1980
+ rememberRouteTable(hamur, table);
1981
+ });
1982
+ const exports = (values) => Object.entries(values).map(([name, value]) => `export const ${name} = ${JSON.stringify(value) ?? "undefined"};
1983
+ `).join("");
1984
+ addTemplate2({
1985
+ filename: "i18n/routes",
1986
+ getContents: () => exports({
1987
+ copies: table.copies,
1988
+ routes: table.routes,
1989
+ aliases: table.aliases ?? {},
1990
+ missing: table.missing ?? {},
1991
+ domains: table.domains,
1992
+ server: [...new Set(hamur.serverRoutes.map((route) => route.path))]
1993
+ })
1994
+ });
1995
+ addTemplate2({
1996
+ filename: "i18n/options",
1997
+ getContents: () => exports({
1998
+ locales: options.locales,
1999
+ defaultLocale: options.defaultLocale,
2000
+ strategy: options.strategy,
2001
+ redirectToDefaultLocale: options.redirectToDefaultLocale,
2002
+ cookie: options.detect.cookie,
2003
+ timeZone: options.timeZone,
2004
+ fallback: options.fallback,
2005
+ missingPage: options.missingPage,
2006
+ localizeLinks: options.localizeLinks,
2007
+ syntax: options.syntax,
2008
+ baseURL: hamur.options.app.baseURL.endsWith("/") ? hamur.options.app.baseURL : `${hamur.options.app.baseURL}/`
2009
+ })
2010
+ });
2011
+ addAppPlugin({ src: r.resolve("../runtime/plugin.ts"), mode: "all" });
2012
+ addRouteMiddleware({ path: r.resolve("../runtime/middleware.ts"), global: true });
2013
+ if (options.detect.redirect !== "root" || options.strategy === "no_prefix")
2014
+ return;
2015
+ const { preset, routeRules, prerender } = hamur.options;
2016
+ const root = routeRules["/"];
2017
+ const prerendered = preset === "static" || !Array.isArray(root) && root?.prerender === true || typeof prerender.routes === "function" || (prerender.routes ?? []).includes("/");
2018
+ if ((options.strategy === "prefix_except_default" || options.strategy === "prefix_and_default") && prerendered)
2019
+ useLogger2("hamur").warn(diagnostic2("HAMUR_W5832", PRERENDER_WARNING));
2020
+ }
2021
+
2022
+ // packages/i18n/src/build/drop.ts
2023
+ import { existsSync as existsSync2 } from "node:fs";
2024
+ import { readFile as readFile3 } from "node:fs/promises";
2025
+ import { resolve as resolve2, sep as sep2 } from "node:path";
2026
+
2027
+ // packages/i18n/src/build/split.ts
2028
+ import { existsSync } from "node:fs";
2029
+ import { readFile as readFile2 } from "node:fs/promises";
2030
+ import { dirname, join, sep } from "node:path";
2031
+ var SCRIPT_LOADERS = {
2032
+ ".ts": "ts",
2033
+ ".mts": "ts",
2034
+ ".cts": "ts",
2035
+ ".tsx": "tsx",
2036
+ ".js": "js",
2037
+ ".mjs": "js",
2038
+ ".cjs": "js",
2039
+ ".jsx": "jsx"
2040
+ };
2041
+ var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|md|mdx|html)$/;
2042
+ var IMPORT_TEXT = /\b(?:import|export)\s+(?:[^'"`;]*?\bfrom\s*)?(["'])([^"'\n]+)\1/g;
2043
+ var INLINE_OBJECT = "useTranslation\\s*\\([^()]*\\)\\s*\\)?\\s*\\.\\s*t\\s*";
2044
+ var BINDING = /\b(?:const|let|var)\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.]*?(?:useI18n|useTranslation|translator)\s*\(/g;
2045
+ var baseOf = (name) => name.split("___")[0];
2046
+ var escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2047
+ var transpilers = new Map;
2048
+ function boundNames(source) {
2049
+ const functions = new Set;
2050
+ const objects = new Set;
2051
+ for (const found of source.matchAll(BINDING)) {
2052
+ const target = found[1];
2053
+ if (!target.startsWith("{")) {
2054
+ objects.add(target);
2055
+ continue;
2056
+ }
2057
+ for (const member of target.slice(1, -1).split(",")) {
2058
+ const named = /^\s*t\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:=.*)?$/s.exec(member);
2059
+ if (named)
2060
+ functions.add(named[1] ?? "t");
2061
+ }
2062
+ }
2063
+ return { functions, objects };
2064
+ }
2065
+ function firstArgument(source, at) {
2066
+ let i = at;
2067
+ while (/\s/.test(source[i] ?? ""))
2068
+ i++;
2069
+ const quote = source[i];
2070
+ if (quote === ")")
2071
+ return;
2072
+ if (quote !== '"' && quote !== "'" && quote !== "`")
2073
+ return null;
2074
+ let end = i + 1;
2075
+ while (end < source.length && source[end] !== quote) {
2076
+ if (source[end] === "\\" || quote === "`" && source[end] === "$" && source[end + 1] === "{")
2077
+ return null;
2078
+ end++;
2079
+ }
2080
+ if (end >= source.length)
2081
+ return null;
2082
+ let after = end + 1;
2083
+ while (/\s/.test(source[after] ?? ""))
2084
+ after++;
2085
+ return source[after] === "," || source[after] === ")" ? source.slice(i + 1, end) : null;
2086
+ }
2087
+ function readKeys(source, withDynamic = true) {
2088
+ const keys = new Set;
2089
+ const positions = new Map;
2090
+ let dynamic = false;
2091
+ let at;
2092
+ const { functions, objects } = boundNames(source);
2093
+ const member = withDynamic ? "(?:\\.\\s*(?:rich|dynamic)\\s*)?\\(" : "(?:\\.\\s*rich\\s*)?\\(";
2094
+ const patterns = [
2095
+ new RegExp(INLINE_OBJECT + member, "g"),
2096
+ ...[...functions].map((name) => new RegExp("(?<![\\w$.])" + escape(name) + "\\s*" + member, "g")),
2097
+ ...[...objects].map((name) => new RegExp("(?<![\\w$.])" + escape(name) + "\\s*\\.\\s*t\\s*" + member, "g"))
2098
+ ];
2099
+ for (const pattern of patterns) {
2100
+ for (const found of source.matchAll(pattern)) {
2101
+ const argument = firstArgument(source, found.index + found[0].length);
2102
+ if (argument === undefined)
2103
+ continue;
2104
+ if (argument === null) {
2105
+ dynamic = true;
2106
+ at = at === undefined ? found.index : Math.min(at, found.index);
2107
+ } else {
2108
+ keys.add(argument);
2109
+ positions.set(argument, Math.min(positions.get(argument) ?? found.index, found.index));
2110
+ }
2111
+ }
2112
+ }
2113
+ return { keys, dynamic, positions, ...at === undefined ? {} : { at } };
2114
+ }
2115
+ function importsOf(source, file) {
2116
+ const loader = SCRIPT_LOADERS[file.slice(file.lastIndexOf("."))];
2117
+ if (loader) {
2118
+ let transpiler = transpilers.get(loader);
2119
+ if (!transpiler)
2120
+ transpilers.set(loader, transpiler = new Bun.Transpiler({ loader }));
2121
+ try {
2122
+ return transpiler.scan(source).imports.filter((entry) => entry.kind === "import-statement").map((entry) => entry.path);
2123
+ } catch {}
2124
+ }
2125
+ return [...source.matchAll(IMPORT_TEXT)].map((found) => found[2]);
2126
+ }
2127
+ function createSplitReader(roots) {
2128
+ const files = new Map;
2129
+ const inside = (file) => !file.includes(sep + "node_modules" + sep) && roots.some((root) => file.startsWith(root + sep)) && SOURCE.test(file);
2130
+ const resolve = (specifier, from) => {
2131
+ if (!/^[./#]/.test(specifier))
2132
+ return;
2133
+ try {
2134
+ return Bun.resolveSync(specifier, dirname(from));
2135
+ } catch {
2136
+ return;
2137
+ }
2138
+ };
2139
+ const load = (file) => {
2140
+ let held = files.get(file);
2141
+ if (!held) {
2142
+ held = readFile2(file, "utf8").then((source) => ({
2143
+ read: readKeys(source),
2144
+ imports: importsOf(source, file).flatMap((specifier) => resolve(specifier, file) ?? [])
2145
+ }), () => {
2146
+ return;
2147
+ });
2148
+ files.set(file, held);
2149
+ }
2150
+ return held;
2151
+ };
2152
+ return {
2153
+ async read(entries) {
2154
+ const keys = new Set;
2155
+ const dynamic = [];
2156
+ const seen = new Set;
2157
+ const queue = [...entries];
2158
+ for (let file = queue.shift();file !== undefined; file = queue.shift()) {
2159
+ if (seen.has(file))
2160
+ continue;
2161
+ seen.add(file);
2162
+ const loaded = await load(file);
2163
+ if (!loaded)
2164
+ continue;
2165
+ for (const key of loaded.read.keys)
2166
+ keys.add(key);
2167
+ if (loaded.read.dynamic)
2168
+ dynamic.push(file);
2169
+ queue.push(...loaded.imports.filter((next) => !seen.has(next) && inside(next)));
2170
+ }
2171
+ return { keys, dynamic };
2172
+ }
2173
+ };
2174
+ }
2175
+ function flatten2(records, ancestors = []) {
2176
+ return records.flatMap((record) => [
2177
+ { record, chain: [...ancestors, record] },
2178
+ ...flatten2(record.children, [...ancestors, record])
2179
+ ]);
2180
+ }
2181
+ var slotFiles = (record) => Object.values(record.slots ?? {}).flatMap((slot) => [
2182
+ ...slot.default ? [slot.default] : [],
2183
+ ...flatten2(slot.routes).map((entry) => entry.record.file)
2184
+ ]);
2185
+ var filesOf = (chain) => chain.flatMap((record) => [
2186
+ record.file,
2187
+ ...[record.error, record.template, record.notFound, record.outletNotFound, record.pending].filter((file) => file !== undefined),
2188
+ ...slotFiles(record)
2189
+ ]);
2190
+ function errorFile(hamur) {
2191
+ for (const { srcDir } of [hamur.options, ...hamur.options.layers]) {
2192
+ for (const extension of hamur.adapter.extensions)
2193
+ if (existsSync(join(srcDir, "error" + extension)))
2194
+ return join(srcDir, "error" + extension);
2195
+ }
2196
+ return;
2197
+ }
2198
+ async function planSplit(hamur) {
2199
+ const { options } = hamur;
2200
+ const roots = [options.rootDir, ...options.layers.map((layer) => layer.rootDir)];
2201
+ const reader = createSplitReader(roots);
2202
+ const error = errorFile(hamur);
2203
+ const sharedFiles = [
2204
+ ...hamur.layouts.map((layout) => layout.file),
2205
+ ...hamur.appRoot ? [hamur.appRoot] : [],
2206
+ ...hamur.notFound ? [hamur.notFound] : [],
2207
+ ...error ? [error] : []
2208
+ ];
2209
+ const shared = await reader.read(sharedFiles);
2210
+ const routes = new Map;
2211
+ for (const { record, chain } of flatten2(hamur.routes)) {
2212
+ const base = baseOf(record.name);
2213
+ if (routes.has(base))
2214
+ continue;
2215
+ const own = await reader.read(filesOf(chain));
2216
+ routes.set(base, { keys: new Set([...own.keys].filter((key) => !shared.keys.has(key))), dynamic: own.dynamic });
2217
+ }
2218
+ return { shared, routes };
2219
+ }
2220
+
2221
+ // packages/i18n/src/build/drop.ts
2222
+ function keepMatcher(glob) {
2223
+ const source = glob.split(/(\*\*|\*)/).map((part) => part === "**" ? ".*" : part === "*" ? "[^.]*" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
2224
+ return new RegExp("^" + source + "$");
2225
+ }
2226
+ async function readClientInputs(inputs, rootDir) {
2227
+ const keys = new Set;
2228
+ let dynamic;
2229
+ for (const input of inputs) {
2230
+ const file = [resolve2(input), resolve2(rootDir, input)].find((path) => existsSync2(path));
2231
+ if (!file || file.includes(sep2 + "node_modules" + sep2) || !SOURCE.test(file))
2232
+ continue;
2233
+ const source = await readFile3(file, "utf8").catch(() => {
2234
+ return;
2235
+ });
2236
+ if (source === undefined)
2237
+ continue;
2238
+ const read = readKeys(source);
2239
+ for (const key of read.keys)
2240
+ keys.add(key);
2241
+ if (read.at !== undefined && !dynamic)
2242
+ dynamic = { file, line: source.slice(0, read.at).split(`
2243
+ `).length };
2244
+ }
2245
+ return { keys, ...dynamic ? { dynamic } : {} };
2246
+ }
2247
+
2248
+ // packages/i18n/src/build/messages.ts
2249
+ async function scanLocaleFiles(roots, codes) {
2250
+ const byCode = new Map;
2251
+ const ignored = [];
2252
+ for (const root of roots) {
2253
+ const dir = join2(root, "locales");
2254
+ const names = await readdir(dir).catch(() => []);
2255
+ for (const name of names.filter((entry) => entry.endsWith(".json")).sort()) {
2256
+ const code = name.slice(0, -".json".length);
2257
+ if (!CODE.test(code))
2258
+ ignored.push(join2(dir, name));
2259
+ else if (codes.includes(code))
2260
+ byCode.set(code, [...byCode.get(code) ?? [], join2(dir, name)]);
2261
+ }
2262
+ }
2263
+ return { byCode, ignored };
2264
+ }
2265
+ function duplicateKey(text) {
2266
+ const stack = [];
2267
+ let pending = "";
2268
+ for (let i = 0;i < text.length; i++) {
2269
+ const c = text[i];
2270
+ const top = stack.at(-1);
2271
+ if (c === '"') {
2272
+ let end = i + 1;
2273
+ while (text[end] !== '"')
2274
+ end += text[end] === "\\" ? 2 : 1;
2275
+ const value = JSON.parse(text.slice(i, end + 1));
2276
+ i = end;
2277
+ if (top?.keys && top.expectKey) {
2278
+ const path = top.path ? `${top.path}.${value}` : value;
2279
+ if (top.keys.has(value))
2280
+ return path;
2281
+ top.keys.add(value);
2282
+ top.expectKey = false;
2283
+ pending = path;
2284
+ }
2285
+ } else if (c === "{") {
2286
+ stack.push({ keys: new Set, path: top?.keys ? pending : top?.path ?? "", expectKey: true });
2287
+ } else if (c === "[") {
2288
+ stack.push({ path: top?.keys ? pending : top?.path ?? "", expectKey: false });
2289
+ } else if (c === "}" || c === "]") {
2290
+ stack.pop();
2291
+ } else if (c === "," && top?.keys) {
2292
+ top.expectKey = true;
2293
+ }
2294
+ }
2295
+ return;
2296
+ }
2297
+ function flattenMessages(value, file) {
2298
+ const out = {};
2299
+ const walk = (node, prefix) => {
2300
+ for (const [name, child] of Object.entries(node)) {
2301
+ const key = prefix + name;
2302
+ if (name === "")
2303
+ throw new DiagnosticError6("HAMUR_E5809", `key ${JSON.stringify(key)} must not be empty or contain "."`, {
2304
+ at: file
2305
+ });
2306
+ if (name.includes("."))
2307
+ throw new DiagnosticError6("HAMUR_E5809", `key ${JSON.stringify(key)} contains "."; "." nests keys ({ "a": { "b": … } } is "a.b"), so use a key without it and put the text in the value: "Type to search": "Type to search..."`, { at: file });
2308
+ if (typeof child === "string")
2309
+ out[key] = child;
2310
+ else if (child !== null && typeof child === "object" && !Array.isArray(child))
2311
+ walk(child, `${key}.`);
2312
+ else
2313
+ throw new DiagnosticError6("HAMUR_E5810", `${JSON.stringify(key)} must be a string or an object`, { at: file });
2314
+ }
2315
+ };
2316
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2317
+ throw new DiagnosticError6("HAMUR_E5811", "must be a JSON object", { at: file });
2318
+ walk(value, "");
2319
+ return out;
2320
+ }
2321
+ async function mergeLocaleFiles(files, rootDir) {
2322
+ const messages = {};
2323
+ const origin = {};
2324
+ for (const path of files) {
2325
+ const file = relative3(rootDir, path);
2326
+ const text = await readFile4(path, "utf8");
2327
+ let json;
2328
+ try {
2329
+ json = JSON.parse(text);
2330
+ } catch (error) {
2331
+ throw new DiagnosticError6("HAMUR_E5812", `invalid JSON (${error.message})`, { at: file });
2332
+ }
2333
+ const twice = duplicateKey(text);
2334
+ if (twice)
2335
+ throw new DiagnosticError6("HAMUR_E5813", `${JSON.stringify(twice)} is defined twice`, { at: file });
2336
+ for (const [key, message] of Object.entries(flattenMessages(json, file))) {
2337
+ if (Object.hasOwn(messages, key))
2338
+ continue;
2339
+ messages[key] = message;
2340
+ origin[key] = file;
2341
+ }
2342
+ }
2343
+ return { messages, origin };
2344
+ }
2345
+ function fillFromChain(own, chain) {
2346
+ const merged = { messages: { ...own.messages }, origin: { ...own.origin } };
2347
+ const filled = [];
2348
+ for (const base of chain) {
2349
+ for (const [key, message] of Object.entries(base.messages)) {
2350
+ if (Object.hasOwn(merged.messages, key))
2351
+ continue;
2352
+ merged.messages[key] = message;
2353
+ merged.origin[key] = base.origin[key];
2354
+ filled.push(key);
2355
+ }
2356
+ }
2357
+ return { merged, filled };
2358
+ }
2359
+ var chunkSpecifier = (appId, id) => `#${appId}-chunk/${createHash("sha256").update(id).digest("hex").slice(0, 8)}`;
2360
+ var setupMessages = async (options, hamur) => {
2361
+ const { rootDir, layers, dev } = hamur.options;
2362
+ const log = useLogger3("hamur");
2363
+ const warned = new Set;
2364
+ const warn = (text) => {
2365
+ if (warned.has(text))
2366
+ return;
2367
+ warned.add(text);
2368
+ log.warn(diagnostic3("HAMUR_W5831", `i18n: ${text}`));
2369
+ };
2370
+ const { byCode, ignored } = await scanLocaleFiles([rootDir, ...layers.map((layer) => layer.rootDir)], options.locales.map((locale) => locale.code));
2371
+ for (const path of ignored)
2372
+ warn(`${relative3(rootDir, path)} is ignored: "${basename(path, ".json")}" is not a locale code`);
2373
+ for (const { code } of options.locales) {
2374
+ if (!byCode.has(code))
2375
+ warn(`no locales/${code}.json in the app or a layer; every key of ${code} falls back`);
2376
+ }
2377
+ const drop = options.dropUnusedKeys && !dev;
2378
+ let keep;
2379
+ const compile = async (code, only, client = false) => {
2380
+ const language = options.locales.find((locale) => locale.code === code).language;
2381
+ let merged = await mergeLocaleFiles(byCode.get(code) ?? [], rootDir);
2382
+ let filled = [];
2383
+ const chain = fallbackChain(options.fallback, options.defaultLocale, code);
2384
+ if (chain.length > 0) {
2385
+ ({ merged, filled } = fillFromChain(merged, await Promise.all(chain.map((member) => mergeLocaleFiles(byCode.get(member) ?? [], rootDir)))));
2386
+ }
2387
+ const { origin } = merged;
2388
+ const wanted = (key) => (!only || only.has(key)) && (!client || !keep || keep(key));
2389
+ const messages = only || client && keep ? Object.fromEntries(Object.entries(merged.messages).filter(([key]) => wanted(key))) : merged.messages;
2390
+ const compiled = compileCatalog(messages, language, {
2391
+ file: (key) => origin[key] ?? `locales/${code}.json`,
2392
+ warn,
2393
+ syntax: options.syntax
2394
+ });
2395
+ return dev ? { ...compiled, code: `${compiled.code}export const fallbacks = ${JSON.stringify(filled)};
2396
+ ` } : compiled;
2397
+ };
2398
+ for (const { code } of options.locales)
2399
+ await compile(code);
2400
+ const anchors = new Map;
2401
+ for (const { code } of options.locales) {
2402
+ const anchor = byCode.get(code)?.[0];
2403
+ if (dev && anchor) {
2404
+ anchors.set(anchor, code);
2405
+ anchors.set(await realpath(anchor), code);
2406
+ }
2407
+ addTemplate3({
2408
+ filename: `i18n/${code}`,
2409
+ getContents: async () => anchor && dev ? `export { default, fallbacks } from ${JSON.stringify(anchor)};
2410
+ ` : `${(await compile(code)).code}export const locale = ${JSON.stringify(code)};
2411
+ `
2412
+ });
2413
+ }
2414
+ if (anchors.size) {
2415
+ const filter = new RegExp(`^(${[...anchors.keys()].map((path) => path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`);
2416
+ addBunPlugin({
2417
+ name: "hamur-i18n-messages",
2418
+ setup(build) {
2419
+ build.onLoad({ filter }, async ({ path }) => ({
2420
+ contents: (await compile(anchors.get(path))).code,
2421
+ loader: "js"
2422
+ }));
2423
+ }
2424
+ });
2425
+ }
2426
+ const split = options.split === "route" && !dev;
2427
+ const chunked = split || drop;
2428
+ const names = () => split ? ["_shared", ...Object.keys(routeTableOf(hamur).routes)] : ["_shared"];
2429
+ const table = (entry) => `{
2430
+ ` + options.locales.map(({ code }) => " " + JSON.stringify(code) + ": " + entry(code) + ",").join(`
2431
+ `) + `
2432
+ }`;
2433
+ const loader = (id) => "() => import(" + JSON.stringify(id) + ")";
2434
+ const full = table((code) => loader("#hamur/i18n/" + code));
2435
+ addTemplate3({
2436
+ filename: "i18n/loaders",
2437
+ getContents: () => {
2438
+ if (!chunked)
2439
+ return "export default " + full + `;
2440
+ export const routes = {};
2441
+ `;
2442
+ const routes = table((code) => "{ " + names().map((name) => JSON.stringify(name) + ": " + loader("#hamur/i18n/" + code + "/" + name)).join(", ") + " }");
2443
+ return "export default import.meta.server ? " + full + ` : {};
2444
+ export const routes = import.meta.server ? {} : ` + routes + `;
2445
+ `;
2446
+ }
2447
+ });
2448
+ addTemplate3({
2449
+ filename: "i18n/chunks",
2450
+ getContents: (context) => {
2451
+ const map = context.manifest.importMap ?? {};
2452
+ const urlOf = (id) => map[chunkSpecifier(hamur.options.appId, "hamur-virtual:" + id)];
2453
+ const chunks = Object.fromEntries(options.locales.flatMap(({ code }) => {
2454
+ if (!chunked) {
2455
+ const url = urlOf("#hamur/i18n/" + code);
2456
+ return url ? [[code, url]] : [];
2457
+ }
2458
+ const urls = names().flatMap((name) => {
2459
+ const url = urlOf("#hamur/i18n/" + code + "/" + name);
2460
+ return url ? [[name, url]] : [];
2461
+ });
2462
+ return [[code, Object.fromEntries(urls)]];
2463
+ }));
2464
+ return "export default " + JSON.stringify(chunks) + `;
2465
+ `;
2466
+ }
2467
+ });
2468
+ if (drop) {
2469
+ const matchers = options.keepKeys.map(keepMatcher);
2470
+ hamur.hooks.hook("build:client:config", async (config) => {
2471
+ if (!config.entrypoints.includes("#hamur/client-entry"))
2472
+ return;
2473
+ keep = () => false;
2474
+ let inputs;
2475
+ try {
2476
+ const probe = {
2477
+ ...config,
2478
+ splitting: false,
2479
+ minify: false,
2480
+ sourcemap: "none",
2481
+ metafile: true,
2482
+ throw: false
2483
+ };
2484
+ delete probe.outdir;
2485
+ const result = await Bun.build(probe);
2486
+ if (!result.success)
2487
+ return;
2488
+ inputs = Object.keys(result.metafile?.inputs ?? {});
2489
+ } finally {
2490
+ keep = undefined;
2491
+ }
2492
+ const read = await readClientInputs(inputs, rootDir);
2493
+ if (read.dynamic) {
2494
+ warn(relative3(rootDir, read.dynamic.file) + ":" + read.dynamic.line + " uses a dynamic message key, so dropUnusedKeys is off for this build");
2495
+ return;
2496
+ }
2497
+ const kept = (key) => read.keys.has(key) || matchers.some((matcher) => matcher.test(key));
2498
+ const all = new Set;
2499
+ for (const { code } of options.locales)
2500
+ for (const key of Object.keys((await mergeLocaleFiles(byCode.get(code) ?? [], rootDir)).messages))
2501
+ all.add(key);
2502
+ keep = kept;
2503
+ log.info("i18n: dropped " + [...all].filter((key) => !kept(key)).length + " of " + all.size + " keys");
2504
+ });
2505
+ }
2506
+ if (!chunked)
2507
+ return;
2508
+ let planned;
2509
+ const plan = () => {
2510
+ planned ??= planSplit(hamur).then((made) => {
2511
+ const files = new Set([...made.shared.dynamic, ...[...made.routes.values()].flatMap((entry) => entry.dynamic)]);
2512
+ for (const file of files)
2513
+ for (const { code } of options.locales)
2514
+ warn(relative3(rootDir, file) + " uses a dynamic message key; its route ships the full " + code + " catalog");
2515
+ return made;
2516
+ });
2517
+ return planned;
2518
+ };
2519
+ hamur.hooks.hook("templates:extend", (templates) => {
2520
+ for (const { code } of options.locales) {
2521
+ for (const name of names()) {
2522
+ templates.push({
2523
+ filename: "i18n/" + code + "/" + name,
2524
+ getContents: async () => {
2525
+ if (!split)
2526
+ return (await compile(code, undefined, true)).code;
2527
+ const { shared, routes } = await plan();
2528
+ const own = name === "_shared" ? shared : routes.get(name);
2529
+ return (await compile(code, own && own.dynamic.length === 0 ? own.keys : undefined, true)).code;
2530
+ }
2531
+ });
2532
+ }
2533
+ }
2534
+ });
2535
+ };
2536
+
2537
+ // packages/i18n/src/build/prerender.ts
2538
+ import { diagnostic as diagnostic4, useLogger as useLogger4 } from "hamur/kit";
2539
+ var noPrefixPrerenderWarning = (defaultLocale) => "[hamur] i18n: no_prefix prerenders only the default locale (" + defaultLocale + "); other locales render at request time";
2540
+ var isStaticPreset = (preset) => preset === "static" || preset.endsWith("-static") || preset === "github-pages" || preset === "gitlab-pages";
2541
+ var setupPrerender = (options, hamur) => {
2542
+ if (options.strategy === "no_prefix" || options.domains) {
2543
+ if (options.domains || !isStaticPreset(hamur.options.preset)) {
2544
+ hamur.options.prerender.ignore.push((path) => createMatcher(routeTableOf(hamur)).matchPath(path) !== undefined);
2545
+ return;
2546
+ }
2547
+ let warned = false;
2548
+ hamur.hooks.hook("prerender:routes", (seeds) => {
2549
+ if (seeds.size === 0 || warned)
2550
+ return;
2551
+ warned = true;
2552
+ useLogger4("hamur").warn(diagnostic4("HAMUR_W5834", noPrefixPrerenderWarning(options.defaultLocale).replace(/^\[hamur\] /, "")));
2553
+ });
2554
+ return;
2555
+ }
2556
+ hamur.hooks.hook("prerender:routes", (seeds) => {
2557
+ const table = routeTableOf(hamur);
2558
+ const { matchPath, buildPath } = createMatcher(table);
2559
+ const hidden = (name, code) => options.missingPage === "404" && table.missing?.[name]?.includes(code);
2560
+ for (const seed of [...seeds]) {
2561
+ const match = matchPath(seed);
2562
+ if (!match || table.missing?.[match.name]?.includes(match.code))
2563
+ continue;
2564
+ for (const { code } of options.locales)
2565
+ if (code !== match.code && !hidden(match.name, code))
2566
+ seeds.add(buildPath(match.name, code, match.params));
2567
+ }
2568
+ });
2569
+ };
2570
+
2571
+ // packages/i18n/src/build/types.ts
2572
+ import { DiagnosticError as DiagnosticError7, addTypeTemplate, diagnostic as diagnostic5, useLogger as useLogger5 } from "hamur/kit";
2573
+ function selectCases(nodes, into) {
2574
+ for (const node of nodes) {
2575
+ if (node.type === "select") {
2576
+ const set = into.get(node.name) ?? new Set;
2577
+ for (const { key } of node.cases)
2578
+ if (key !== "other")
2579
+ set.add(key);
2580
+ into.set(node.name, set);
2581
+ }
2582
+ if (node.type === "select" || node.type === "plural")
2583
+ for (const { body } of node.cases)
2584
+ selectCases(body, into);
2585
+ if (node.type === "tag")
2586
+ selectCases(node.children, into);
2587
+ }
2588
+ }
2589
+ function typeOf(kind, cases) {
2590
+ switch (kind) {
2591
+ case "text":
2592
+ return "string | number";
2593
+ case "number":
2594
+ return "number";
2595
+ case "date":
2596
+ return "Date | number";
2597
+ case "select":
2598
+ return [...[...cases ?? []].map((name) => JSON.stringify(name)), "(string & {})"].join(" | ");
2599
+ }
2600
+ }
2601
+ async function analyzeLocales(options, roots, rootDir) {
2602
+ const { byCode } = await scanLocaleFiles(roots, options.locales.map((locale) => locale.code));
2603
+ const load = async (code) => {
2604
+ const merged = await mergeLocaleFiles(byCode.get(code) ?? [], rootDir);
2605
+ const language = options.locales.find((locale) => locale.code === code).language;
2606
+ const { args, tags } = compileCatalog(merged.messages, language, {
2607
+ file: (key) => merged.origin[key] ?? `locales/${code}.json`,
2608
+ syntax: options.syntax
2609
+ });
2610
+ return { ...merged, args, tags };
2611
+ };
2612
+ const base = await load(options.defaultLocale);
2613
+ const baseKeys = Object.keys(base.messages);
2614
+ const messages = {};
2615
+ for (const key of baseKeys) {
2616
+ const cases = new Map;
2617
+ if (options.syntax === "mf1")
2618
+ selectCases(parseMessage(base.messages[key]), cases);
2619
+ messages[key] = Object.fromEntries(Object.entries(base.args[key]).map(([name, kind]) => [name, typeOf(kind, cases.get(name))]));
2620
+ }
2621
+ const warnings = [];
2622
+ const tags = base.tags;
2623
+ if (baseKeys.length === 0)
2624
+ return { messages, tags, warnings };
2625
+ for (const { code } of options.locales) {
2626
+ if (code === options.defaultLocale || !byCode.has(code))
2627
+ continue;
2628
+ const own = await load(code);
2629
+ const file = `locales/${code}.json`;
2630
+ const missing = baseKeys.filter((key) => !Object.hasOwn(own.messages, key));
2631
+ if (missing.length)
2632
+ warnings.push(`${file} lacks ${missing.length} key${missing.length === 1 ? "" : "s"} of the default locale: ${missing.join(", ")}`);
2633
+ const extra = Object.keys(own.messages).filter((key) => !Object.hasOwn(base.messages, key));
2634
+ if (extra.length)
2635
+ warnings.push(`${file} has ${extra.length} key${extra.length === 1 ? "" : "s"} the default locale lacks: ${extra.join(", ")}`);
2636
+ for (const [key, args] of Object.entries(own.args)) {
2637
+ const expected = base.args[key];
2638
+ if (!expected)
2639
+ continue;
2640
+ const where = own.origin[key] ?? file;
2641
+ for (const tag of own.tags[key] ?? []) {
2642
+ if (!base.tags[key]?.includes(tag))
2643
+ throw new DiagnosticError7("HAMUR_E5827", `${where} ${JSON.stringify(key)}: tag <${tag}> is not in the default locale's message`);
2644
+ }
2645
+ for (const [name, kind] of Object.entries(args)) {
2646
+ if (!Object.hasOwn(expected, name))
2647
+ throw new DiagnosticError7("HAMUR_E5828", `${where} ${JSON.stringify(key)}: argument ${JSON.stringify(name)} is not in the default locale's message`);
2648
+ if (expected[name] !== kind)
2649
+ throw new DiagnosticError7("HAMUR_E5829", `${where} ${JSON.stringify(key)}: argument ${JSON.stringify(name)} is ${kind}, the default locale's message has ${expected[name]}`);
2650
+ }
2651
+ }
2652
+ }
2653
+ return { messages, tags, warnings };
2654
+ }
2655
+ function typesTemplate(options, analysis) {
2656
+ const messages = Object.entries(analysis.messages).map(([key, args]) => {
2657
+ const fields = Object.entries(args).map(([name, type]) => `${JSON.stringify(name)}: ${type}`);
2658
+ return ` ${JSON.stringify(key)}: ${fields.length ? `{ ${fields.join("; ")} }` : "{}"};`;
2659
+ });
2660
+ const locales = options.locales.map(({ code }) => ` ${JSON.stringify(code)}: true;`);
2661
+ const tagged = Object.entries(analysis.tags).map(([key, names]) => ` ${JSON.stringify(key)}: ${names.map((name) => JSON.stringify(name)).join(" | ")};`);
2662
+ const tags = tagged.length ? ` interface HamurI18nTags {
2663
+ ${tagged.join(`
2664
+ `)}
2665
+ }
2666
+ ` : "";
2667
+ return `declare module "@hamur/i18n" {
2668
+ interface HamurI18nMessages {
2669
+ ${messages.join(`
2670
+ `)}
2671
+ }
2672
+ ${tags} interface HamurI18nLocales {
2673
+ ${locales.join(`
2674
+ `)}
2675
+ }
2676
+ }
2677
+ export {};
2678
+ `;
2679
+ }
2680
+ function rootPathTypes(options, hamur) {
2681
+ if (!hamur.options.typescript.typedPaths || options.strategy !== "prefix" || options.detect.redirect === false)
2682
+ return "";
2683
+ return `declare module "hamur/app" {
2684
+ interface HamurRoutePaths {
2685
+ "i18n /": "/";
2686
+ }
2687
+ }
2688
+ `;
2689
+ }
2690
+ var setupTypes = async (options, hamur) => {
2691
+ const { rootDir, layers } = hamur.options;
2692
+ const roots = [rootDir, ...layers.map((layer) => layer.rootDir)];
2693
+ const log = useLogger5("hamur");
2694
+ const analysis = await analyzeLocales(options, roots, rootDir);
2695
+ for (const text of analysis.warnings)
2696
+ log.warn(diagnostic5("HAMUR_W5830", `i18n: ${text}`));
2697
+ addTypeTemplate({
2698
+ filename: "i18n.d.ts",
2699
+ getContents: async () => typesTemplate(options, await analyzeLocales(options, roots, rootDir)) + rootPathTypes(options, hamur)
2700
+ });
2701
+ };
2702
+
2703
+ // packages/i18n/src/server/setup.ts
2704
+ import { addServer, createResolver as createResolver3 } from "hamur/kit";
2705
+ var setupServer = (options) => {
2706
+ const mode = options.domains ? "" : options.detect.redirect === "root" ? "-root" : options.detect.redirect === "all" && options.strategy !== "no_prefix" ? "-all" : "";
2707
+ const door = "./door" + mode + (options.catalog === undefined ? "" : "-catalog") + ".ts";
2708
+ addServer(createResolver3(new URL("../../src/server/setup.ts", import.meta.url).href).resolve(door));
2709
+ };
2710
+
2711
+ // packages/i18n/src/module.ts
2712
+ var resolvedOptions = new WeakMap;
2713
+ var DOMAIN_STATIC = "i18n: locales[].domain needs a server preset (static serves one host)";
2714
+ var CATALOG_STATIC = "i18n.catalog needs a server preset (static has no server to load the catalog)";
2715
+ var DOMAIN_ORIGIN = "i18n: locales[].domain cannot be used with app.origin, which gives every request one host";
2716
+ var PATH_KEYED_ISR = new Set(["vercel", "netlify"]);
2717
+ var domainIsrError = (preset, pattern) => "i18n: locales[].domain cannot be used with an isr route rule on the " + preset + " preset (" + JSON.stringify(pattern) + "); its ISR cache keys on the path, not the host";
2718
+ var isIsr = (rule) => {
2719
+ const isr = rule?.isr;
2720
+ return isr === true || typeof isr === "number" && isr > 0;
2721
+ };
2722
+ function checkDomainHosting(hamur) {
2723
+ const { preset, app, routeRules } = hamur.options;
2724
+ if (isStaticPreset(preset))
2725
+ throw new DiagnosticError8("HAMUR_E5802", DOMAIN_STATIC);
2726
+ if (app.origin !== undefined)
2727
+ throw new DiagnosticError8("HAMUR_E5803", DOMAIN_ORIGIN);
2728
+ if (!PATH_KEYED_ISR.has(preset))
2729
+ return;
2730
+ for (const [pattern, rule] of Object.entries(routeRules)) {
2731
+ if ((Array.isArray(rule) ? rule : [rule]).some(isIsr))
2732
+ throw new DiagnosticError8("HAMUR_E5804", domainIsrError(preset, pattern));
2733
+ }
2734
+ }
2735
+ var module_default = defineModule({
2736
+ meta: { name: "i18n", configKey: "i18n" },
2737
+ async setup(input, hamur) {
2738
+ const options = resolveOptions(input);
2739
+ if (options.domains)
2740
+ checkDomainHosting(hamur);
2741
+ if (options.catalog !== undefined && isStaticPreset(hamur.options.preset))
2742
+ throw new DiagnosticError8("HAMUR_E5805", CATALOG_STATIC);
2743
+ await setupRoutes(options, hamur);
2744
+ await setupMessages(options, hamur);
2745
+ await setupCatalog(options, hamur);
2746
+ await setupServer(options, hamur);
2747
+ await setupHead(options, hamur);
2748
+ await setupPrerender(options, hamur);
2749
+ await setupTypes(options, hamur);
2750
+ resolvedOptions.set(hamur, options);
2751
+ }
2752
+ });
2753
+ export {
2754
+ module_default as default
2755
+ };