@vocab/core 1.6.3 → 1.6.5-fix-messageformat-import-20250923004826

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 (68) hide show
  1. package/dist/chunk-nOFOJqeH.js +30 -0
  2. package/dist/icu-handler-9mldObYa.js +29 -0
  3. package/dist/icu-handler-9mldObYa.js.map +1 -0
  4. package/dist/icu-handler-COUleaeZ.mjs +22 -0
  5. package/dist/icu-handler-COUleaeZ.mjs.map +1 -0
  6. package/dist/icu-handler.d.mts +7 -0
  7. package/dist/icu-handler.d.ts +7 -0
  8. package/dist/icu-handler.js +3 -0
  9. package/dist/icu-handler.mjs +3 -0
  10. package/dist/index.d.mts +53 -0
  11. package/dist/index.d.ts +53 -0
  12. package/dist/index.js +679 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/index.mjs +660 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/runtime.d.mts +8 -0
  17. package/dist/runtime.d.ts +8 -0
  18. package/dist/runtime.js +13 -0
  19. package/dist/runtime.js.map +1 -0
  20. package/dist/runtime.mjs +12 -0
  21. package/dist/runtime.mjs.map +1 -0
  22. package/dist/translation-file-BEIJ1-3N.js +34 -0
  23. package/dist/translation-file-BEIJ1-3N.js.map +1 -0
  24. package/dist/translation-file-CAOIsAU9.d.mts +7 -0
  25. package/dist/translation-file-DQOiWtfV.d.ts +7 -0
  26. package/dist/translation-file-Dn19n2oY.mjs +28 -0
  27. package/dist/translation-file-Dn19n2oY.mjs.map +1 -0
  28. package/dist/translation-file.d.mts +3 -0
  29. package/dist/translation-file.d.ts +3 -0
  30. package/dist/translation-file.js +3 -0
  31. package/dist/translation-file.mjs +3 -0
  32. package/dist/types-DFxEF4pq.d.mts +146 -0
  33. package/dist/types-Di9uIscO.d.ts +146 -0
  34. package/package.json +17 -28
  35. package/README.md +0 -724
  36. package/dist/declarations/src/compile.d.ts +0 -6
  37. package/dist/declarations/src/config.d.ts +0 -4
  38. package/dist/declarations/src/icu-handler.d.ts +0 -2
  39. package/dist/declarations/src/index.d.ts +0 -6
  40. package/dist/declarations/src/load-translations.d.ts +0 -32
  41. package/dist/declarations/src/runtime.d.ts +0 -3
  42. package/dist/declarations/src/translation-file.d.ts +0 -2
  43. package/dist/declarations/src/types.d.ts +0 -143
  44. package/dist/declarations/src/utils.d.ts +0 -26
  45. package/dist/declarations/src/validate/index.d.ts +0 -3
  46. package/dist/vocab-core.cjs.d.ts +0 -2
  47. package/dist/vocab-core.cjs.dev.js +0 -893
  48. package/dist/vocab-core.cjs.js +0 -7
  49. package/dist/vocab-core.cjs.prod.js +0 -893
  50. package/dist/vocab-core.esm.js +0 -866
  51. package/icu-handler/dist/vocab-core-icu-handler.cjs.d.ts +0 -2
  52. package/icu-handler/dist/vocab-core-icu-handler.cjs.dev.js +0 -31
  53. package/icu-handler/dist/vocab-core-icu-handler.cjs.js +0 -7
  54. package/icu-handler/dist/vocab-core-icu-handler.cjs.prod.js +0 -31
  55. package/icu-handler/dist/vocab-core-icu-handler.esm.js +0 -23
  56. package/icu-handler/package.json +0 -4
  57. package/runtime/dist/vocab-core-runtime.cjs.d.ts +0 -2
  58. package/runtime/dist/vocab-core-runtime.cjs.dev.js +0 -15
  59. package/runtime/dist/vocab-core-runtime.cjs.js +0 -7
  60. package/runtime/dist/vocab-core-runtime.cjs.prod.js +0 -15
  61. package/runtime/dist/vocab-core-runtime.esm.js +0 -10
  62. package/runtime/package.json +0 -4
  63. package/translation-file/dist/vocab-core-translation-file.cjs.d.ts +0 -2
  64. package/translation-file/dist/vocab-core-translation-file.cjs.dev.js +0 -35
  65. package/translation-file/dist/vocab-core-translation-file.cjs.js +0 -7
  66. package/translation-file/dist/vocab-core-translation-file.cjs.prod.js +0 -35
  67. package/translation-file/dist/vocab-core-translation-file.esm.js +0 -31
  68. package/translation-file/package.json +0 -4
package/dist/index.mjs ADDED
@@ -0,0 +1,660 @@
1
+ import { createRequire } from "node:module";
2
+ import IntlMessageFormat from "intl-messageformat";
3
+ import { existsSync, promises } from "fs";
4
+ import path from "path";
5
+ import { TYPE, isArgumentElement, isDateElement, isNumberElement, isPluralElement, isSelectElement, isTagElement, isTimeElement, parse } from "@formatjs/icu-messageformat-parser";
6
+ import prettier from "prettier";
7
+ import chokidar from "chokidar";
8
+ import pc from "picocolors";
9
+ import debug from "debug";
10
+ import glob from "fast-glob";
11
+ import { printAST } from "@formatjs/icu-messageformat-parser/printer.js";
12
+ import findUp from "find-up";
13
+ import Validator from "fastest-validator";
14
+
15
+ //#region rolldown:runtime
16
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
17
+
18
+ //#endregion
19
+ //#region src/logger.ts
20
+ const trace = debug(`vocab:core`);
21
+
22
+ //#endregion
23
+ //#region src/utils.ts
24
+ const defaultTranslationDirSuffix = ".vocab";
25
+ const devTranslationFileName = "translations.json";
26
+ const globAnyPathWithOptionalPrefix = "**/?(*)";
27
+ function isDevLanguageFile(filePath) {
28
+ return filePath.endsWith(`/${devTranslationFileName}`) || filePath === devTranslationFileName;
29
+ }
30
+ function isAltLanguageFile(filePath) {
31
+ return filePath.endsWith(".translations.json");
32
+ }
33
+ function isTranslationDirectory(filePath, { translationsDirectorySuffix = defaultTranslationDirSuffix }) {
34
+ return filePath.endsWith(translationsDirectorySuffix);
35
+ }
36
+ function getTranslationFolderGlob({ translationsDirectorySuffix = defaultTranslationDirSuffix }) {
37
+ const result = `${globAnyPathWithOptionalPrefix}${translationsDirectorySuffix}`;
38
+ trace("getTranslationFolderGlob", result);
39
+ return result;
40
+ }
41
+ function getDevTranslationFileGlob({ translationsDirectorySuffix = defaultTranslationDirSuffix }) {
42
+ const result = `${globAnyPathWithOptionalPrefix}${translationsDirectorySuffix}/${devTranslationFileName}`;
43
+ trace("getDevTranslationFileGlob", result);
44
+ return result;
45
+ }
46
+ function getAltTranslationFileGlob(config) {
47
+ const altLanguages = getAltLanguages(config);
48
+ const langMatch = altLanguages.length === 1 ? altLanguages[0] : `{${altLanguages.join(",")}}`;
49
+ const { translationsDirectorySuffix = defaultTranslationDirSuffix } = config;
50
+ const result = `**/*${translationsDirectorySuffix}/${langMatch}.translations.json`;
51
+ trace("getAltTranslationFileGlob", result);
52
+ return result;
53
+ }
54
+ function getAltLanguages({ devLanguage, languages }) {
55
+ return languages.map((v) => v.name).filter((lang) => lang !== devLanguage);
56
+ }
57
+ function getDevLanguageFileFromTsFile(tsFilePath) {
58
+ const directory = path.dirname(tsFilePath);
59
+ const result = path.normalize(path.join(directory, devTranslationFileName));
60
+ trace(`Returning dev language path ${result} for path ${tsFilePath}`);
61
+ return result;
62
+ }
63
+ function getDevLanguageFileFromAltLanguageFile(altLanguageFilePath) {
64
+ const directory = path.dirname(altLanguageFilePath);
65
+ const result = path.normalize(path.join(directory, devTranslationFileName));
66
+ trace(`Returning dev language path ${result} for path ${altLanguageFilePath}`);
67
+ return result;
68
+ }
69
+ function getTSFileFromDevLanguageFile(devLanguageFilePath) {
70
+ const directory = path.dirname(devLanguageFilePath);
71
+ const result = path.normalize(path.join(directory, "index.ts"));
72
+ trace(`Returning TS path ${result} for path ${devLanguageFilePath}`);
73
+ return result;
74
+ }
75
+ function getAltLanguageFilePath(devLanguageFilePath, language) {
76
+ const directory = path.dirname(devLanguageFilePath);
77
+ const result = path.normalize(path.join(directory, `${language}.translations.json`));
78
+ trace(`Returning alt language path ${result} for path ${devLanguageFilePath}`);
79
+ return path.normalize(result);
80
+ }
81
+ function mapValues(obj, func) {
82
+ const newObj = {};
83
+ const keys = Object.keys(obj);
84
+ for (const key of keys) newObj[key] = func(obj[key]);
85
+ return newObj;
86
+ }
87
+ function getTranslationMessages(translations) {
88
+ return mapValues(translations, (v) => v.message);
89
+ }
90
+
91
+ //#endregion
92
+ //#region src/generate-language.ts
93
+ function generateLanguageFromTranslations({ baseTranslations, generator }) {
94
+ if (!generator.transformElement && !generator.transformMessage) return baseTranslations;
95
+ const translationKeys = Object.keys(baseTranslations);
96
+ const generatedTranslations = {};
97
+ for (const translationKey of translationKeys) {
98
+ const translation = baseTranslations[translationKey];
99
+ let transformedMessage = translation.message;
100
+ if (generator.transformElement) {
101
+ const transformedAst = new IntlMessageFormat(translation.message).getAst().map(transformMessageFormatElement(generator.transformElement));
102
+ transformedMessage = printAST(transformedAst);
103
+ }
104
+ if (generator.transformMessage) transformedMessage = generator.transformMessage(transformedMessage);
105
+ generatedTranslations[translationKey] = { message: transformedMessage };
106
+ }
107
+ return generatedTranslations;
108
+ }
109
+ function transformMessageFormatElement(transformElement) {
110
+ return (messageFormatElement) => {
111
+ const transformedMessageFormatElement = { ...messageFormatElement };
112
+ switch (transformedMessageFormatElement.type) {
113
+ case TYPE.literal:
114
+ transformedMessageFormatElement.value = transformElement(transformedMessageFormatElement.value);
115
+ break;
116
+ case TYPE.select:
117
+ case TYPE.plural:
118
+ const transformedOptions = { ...transformedMessageFormatElement.options };
119
+ for (const key of Object.keys(transformedOptions)) transformedOptions[key].value = transformedOptions[key].value.map(transformMessageFormatElement(transformElement));
120
+ break;
121
+ case TYPE.tag:
122
+ transformedMessageFormatElement.children = transformedMessageFormatElement.children.map(transformMessageFormatElement(transformElement));
123
+ break;
124
+ default: break;
125
+ }
126
+ return transformedMessageFormatElement;
127
+ };
128
+ }
129
+
130
+ //#endregion
131
+ //#region src/load-translations.ts
132
+ function getUniqueKey(key, namespace) {
133
+ return `${key}.${namespace}`;
134
+ }
135
+ function mergeWithDevLanguageTranslation({ translation, devTranslation }) {
136
+ const keys = Object.keys(devTranslation);
137
+ const newLanguage = {};
138
+ for (const key of keys) if (translation[key]) newLanguage[key] = {
139
+ message: translation[key].message,
140
+ description: devTranslation[key].description
141
+ };
142
+ return newLanguage;
143
+ }
144
+ function getLanguageFallbacks({ languages }) {
145
+ const languageFallbackMap = /* @__PURE__ */ new Map();
146
+ for (const lang of languages) if (lang.extends) languageFallbackMap.set(lang.name, lang.extends);
147
+ return languageFallbackMap;
148
+ }
149
+ function getLanguageHierarchy({ languages }) {
150
+ const hierarchyMap = /* @__PURE__ */ new Map();
151
+ const fallbacks = getLanguageFallbacks({ languages });
152
+ for (const lang of languages) {
153
+ const langHierarchy = [];
154
+ let currLang = lang.extends;
155
+ while (currLang) {
156
+ langHierarchy.push(currLang);
157
+ currLang = fallbacks.get(currLang);
158
+ }
159
+ hierarchyMap.set(lang.name, langHierarchy);
160
+ }
161
+ return hierarchyMap;
162
+ }
163
+ function getFallbackLanguageOrder({ languages, languageName, devLanguage, fallbacks }) {
164
+ const languageHierarchy = getLanguageHierarchy({ languages }).get(languageName);
165
+ if (!languageHierarchy) throw new Error(`Missing language hierarchy for ${languageName}`);
166
+ const fallbackLanguageOrder = [languageName];
167
+ if (fallbacks !== "none") {
168
+ fallbackLanguageOrder.unshift(...languageHierarchy.reverse());
169
+ if (fallbacks === "all" && fallbackLanguageOrder[0] !== devLanguage) fallbackLanguageOrder.unshift(devLanguage);
170
+ }
171
+ return fallbackLanguageOrder;
172
+ }
173
+ function getNamespaceByFilePath(relativePath, { translationsDirectorySuffix = defaultTranslationDirSuffix }) {
174
+ let namespace = path.dirname(relativePath).replace(/^src\//, "").replace(/\//g, "_");
175
+ if (namespace.endsWith(translationsDirectorySuffix)) namespace = namespace.slice(0, -translationsDirectorySuffix.length);
176
+ return namespace;
177
+ }
178
+ function printValidationError(...params) {
179
+ console.error(pc.red("Error loading translation:"), ...params);
180
+ }
181
+ function getTranslationsFromFile(translationFileContents, { isAltLanguage, filePath, withTags }) {
182
+ if (!translationFileContents || typeof translationFileContents !== "object") throw new Error(`Unable to read translation file ${filePath}. Translations must be an object.`);
183
+ const { $namespace, _meta,...keys } = translationFileContents;
184
+ if (isAltLanguage && $namespace) printValidationError(`Found $namespace in alt language file in ${filePath}. $namespace is only used in the dev language and will be ignored.`);
185
+ if (!isAltLanguage && $namespace && typeof $namespace !== "string") printValidationError(`Found non-string $namespace in language file in ${filePath}. $namespace must be a string.`);
186
+ if (isAltLanguage && _meta?.tags) printValidationError(`Found _meta.tags in alt language file in ${filePath}. _meta.tags is only used in the dev language and will be ignored.`);
187
+ const includeTags = !isAltLanguage && withTags;
188
+ const validKeys = {};
189
+ for (const [translationKey, { tags,...translation }] of Object.entries(keys)) {
190
+ if (typeof translation === "string") {
191
+ printValidationError(`Found string for a translation "${translationKey}" in ${filePath}. Translation must be an object of the format {message: string}.`);
192
+ continue;
193
+ }
194
+ if (!translation) {
195
+ printValidationError(`Found empty translation "${translationKey}" in ${filePath}. Translation must be an object of the format {message: string}.`);
196
+ continue;
197
+ }
198
+ if (!translation.message || typeof translation.message !== "string") {
199
+ printValidationError(`No message found for translation "${translationKey}" in ${filePath}. Translation must be an object of the format {message: string}.`);
200
+ continue;
201
+ }
202
+ validKeys[translationKey] = {
203
+ ...translation,
204
+ tags: includeTags ? tags : void 0
205
+ };
206
+ }
207
+ const metadata = { tags: includeTags ? _meta?.tags : void 0 };
208
+ return {
209
+ $namespace,
210
+ keys: validKeys,
211
+ metadata
212
+ };
213
+ }
214
+ function loadAltLanguageFile({ filePath, languageName, devTranslation, fallbacks }, { devLanguage, languages }) {
215
+ const altLanguageTranslation = {};
216
+ const fallbackLanguageOrder = getFallbackLanguageOrder({
217
+ languages,
218
+ languageName,
219
+ devLanguage,
220
+ fallbacks
221
+ });
222
+ trace(`Loading alt language file with precedence: ${fallbackLanguageOrder.slice().reverse().join(" -> ")}`);
223
+ for (const fallbackLanguage of fallbackLanguageOrder) if (fallbackLanguage !== devLanguage) try {
224
+ const altFilePath = getAltLanguageFilePath(filePath, fallbackLanguage);
225
+ delete __require.cache[altFilePath];
226
+ const translationFile = __require(altFilePath);
227
+ const { keys: fallbackLanguageTranslation } = getTranslationsFromFile(translationFile, {
228
+ filePath: altFilePath,
229
+ isAltLanguage: true
230
+ });
231
+ Object.assign(altLanguageTranslation, mergeWithDevLanguageTranslation({
232
+ translation: fallbackLanguageTranslation,
233
+ devTranslation
234
+ }));
235
+ } catch {
236
+ trace(`Missing alt language file ${getAltLanguageFilePath(filePath, fallbackLanguage)}
237
+ `);
238
+ }
239
+ else Object.assign(altLanguageTranslation, devTranslation);
240
+ return altLanguageTranslation;
241
+ }
242
+ function stripTagsFromTranslations(translations) {
243
+ return Object.fromEntries(Object.entries(translations).map(([key, { tags,...rest }]) => [key, rest]));
244
+ }
245
+ function loadTranslation({ filePath, fallbacks, withTags }, userConfig) {
246
+ trace(`Loading translation file in "${fallbacks}" fallback mode: "${filePath}"`);
247
+ const languageSet = {};
248
+ delete __require.cache[filePath];
249
+ const translationContent = __require(filePath);
250
+ const relativePath = path.relative(userConfig.projectRoot || process.cwd(), filePath);
251
+ const { $namespace, keys: devTranslation, metadata } = getTranslationsFromFile(translationContent, {
252
+ filePath,
253
+ isAltLanguage: false,
254
+ withTags
255
+ });
256
+ const namespace = typeof $namespace === "string" ? $namespace : getNamespaceByFilePath(relativePath, userConfig);
257
+ trace(`Found file ${filePath}. Using namespace ${namespace}`);
258
+ languageSet[userConfig.devLanguage] = devTranslation;
259
+ const devTranslationNoTags = withTags ? stripTagsFromTranslations(devTranslation) : devTranslation;
260
+ const altLanguages = getAltLanguages(userConfig);
261
+ for (const languageName of altLanguages) languageSet[languageName] = loadAltLanguageFile({
262
+ filePath,
263
+ languageName,
264
+ devTranslation: devTranslationNoTags,
265
+ fallbacks
266
+ }, userConfig);
267
+ for (const generatedLanguage of userConfig.generatedLanguages || []) {
268
+ const { name: generatedLanguageName, generator } = generatedLanguage;
269
+ const baseLanguage = generatedLanguage.extends || userConfig.devLanguage;
270
+ const baseTranslations = languageSet[baseLanguage];
271
+ languageSet[generatedLanguageName] = generateLanguageFromTranslations({
272
+ baseTranslations,
273
+ generator
274
+ });
275
+ }
276
+ return {
277
+ filePath,
278
+ keys: Object.keys(devTranslation),
279
+ namespace,
280
+ relativePath,
281
+ languages: languageSet,
282
+ metadata
283
+ };
284
+ }
285
+ async function loadAllTranslations({ fallbacks, includeNodeModules, withTags }, config) {
286
+ const { projectRoot, ignore = [] } = config;
287
+ const translationFiles = await glob(getDevTranslationFileGlob(config), {
288
+ ignore: includeNodeModules ? ignore : [...ignore, "**/node_modules/**"],
289
+ absolute: true,
290
+ cwd: projectRoot
291
+ });
292
+ trace(`Found ${translationFiles.length} translation files`);
293
+ const loadedTranslations = [];
294
+ const keys = /* @__PURE__ */ new Set();
295
+ for (const translationFile of translationFiles) {
296
+ const loadedTranslation = loadTranslation({
297
+ filePath: translationFile,
298
+ fallbacks,
299
+ withTags
300
+ }, config);
301
+ loadedTranslations.push(loadedTranslation);
302
+ for (const key of loadedTranslation.keys) {
303
+ const uniqueKey = getUniqueKey(key, loadedTranslation.namespace);
304
+ if (keys.has(uniqueKey)) {
305
+ trace(`Duplicate keys found`);
306
+ throw new Error(`Duplicate keys found. Key with namespace ${loadedTranslation.namespace} and key ${key} was found multiple times.`);
307
+ }
308
+ keys.add(uniqueKey);
309
+ const globalKey = loadedTranslation.languages[config.devLanguage][key].globalKey;
310
+ if (globalKey) {
311
+ if (keys.has(globalKey)) throw new Error(`Duplicate keys found. Key with global key ${globalKey} and key ${key} was found multiple times`);
312
+ keys.add(globalKey);
313
+ }
314
+ }
315
+ }
316
+ return loadedTranslations;
317
+ }
318
+
319
+ //#endregion
320
+ //#region src/compile.ts
321
+ function extractHasTags(ast) {
322
+ return ast.some((element) => {
323
+ if (isSelectElement(element) || isPluralElement(element)) return Object.values(element.options).map((o) => o.value).some((child) => extractHasTags(child));
324
+ return isTagElement(element);
325
+ });
326
+ }
327
+ function extractParamTypes(ast, currentParams) {
328
+ let params = { ...currentParams };
329
+ let vocabTypesImports = /* @__PURE__ */ new Set();
330
+ for (const element of ast) if (isArgumentElement(element)) {
331
+ if (!(element.value in params)) params[element.value] = "string";
332
+ } else if (isNumberElement(element)) params[element.value] = "number";
333
+ else if (isPluralElement(element)) {
334
+ params[element.value] = "number";
335
+ const children = Object.values(element.options).map((o) => o.value);
336
+ for (const child of children) {
337
+ const [newParams, subImports] = extractParamTypes(child, params);
338
+ vocabTypesImports = new Set([...vocabTypesImports, ...subImports]);
339
+ params = newParams;
340
+ }
341
+ } else if (isDateElement(element) || isTimeElement(element)) params[element.value] = "Date | number";
342
+ else if (isTagElement(element)) {
343
+ params[element.value] = "FormatXMLElementFn<T>";
344
+ vocabTypesImports.add("FormatXMLElementFn");
345
+ const [newParams, subImports] = extractParamTypes(element.children, params);
346
+ vocabTypesImports = new Set([...vocabTypesImports, ...subImports]);
347
+ params = newParams;
348
+ } else if (isSelectElement(element)) {
349
+ const nonOtherOptionsUnion = Object.keys(element.options).filter((o) => o !== "other").map((o) => `'${o}'`).join(" | ");
350
+ params[element.value] = `StringWithSuggestions<${nonOtherOptionsUnion}>`;
351
+ vocabTypesImports.add("StringWithSuggestions");
352
+ const children = Object.values(element.options).map((o) => o.value);
353
+ for (const child of children) {
354
+ const [newParams, subImports] = extractParamTypes(child, params);
355
+ vocabTypesImports = new Set([...vocabTypesImports, ...subImports]);
356
+ params = newParams;
357
+ }
358
+ }
359
+ return [params, vocabTypesImports];
360
+ }
361
+ function serialiseObjectToType(v) {
362
+ let result = "";
363
+ for (const [key, value] of Object.entries(v)) result += `${JSON.stringify(key)}: ${value && typeof value === "object" ? serialiseObjectToType(value) : value},`;
364
+ return `{ ${result} }`;
365
+ }
366
+ const serializeTypeImports = (imports, moduleName) => {
367
+ if (imports.size === 0) return "";
368
+ return `import type { ${Array.from(imports).join(", ")} } from '${moduleName}';`;
369
+ };
370
+ function serialiseTranslationRuntime(value, imports, loadedTranslation) {
371
+ trace("Serialising translations:", loadedTranslation);
372
+ const translationsType = {};
373
+ for (const [key, { params, message, hasTags }] of value.entries()) {
374
+ let translationFunctionString = `() => ${message}`;
375
+ if (Object.keys(params).length > 0) {
376
+ const formatGeneric = hasTags ? "<T = string>" : "";
377
+ const formatReturn = hasTags && imports.has("FormatXMLElementFn") ? "ReturnType<FormatXMLElementFn<T>>" : "string";
378
+ translationFunctionString = `${formatGeneric}(values: ${serialiseObjectToType(params)}) => ${formatReturn}`;
379
+ }
380
+ translationsType[key] = translationFunctionString;
381
+ }
382
+ const languagesUnionAsString = Object.keys(loadedTranslation.languages).map((l) => `'${l}'`).join(" | ");
383
+ const languageEntries = Object.entries(loadedTranslation.languages).map(([languageName, translations]) => `${JSON.stringify(languageName)}: createLanguage(${JSON.stringify(getTranslationMessages(translations))})`).join(",");
384
+ return `
385
+ // This file is automatically generated by Vocab.
386
+ // To make changes update translation.json files directly.
387
+
388
+ ${serializeTypeImports(imports, "@vocab/core")}
389
+ import { createLanguage, createTranslationFile } from '@vocab/core/runtime';
390
+
391
+ const translations = createTranslationFile<
392
+ ${languagesUnionAsString},
393
+ ${serialiseObjectToType(translationsType)}
394
+ >({
395
+ ${languageEntries}
396
+ });
397
+
398
+ export default translations;
399
+ `;
400
+ }
401
+ async function generateRuntime(loadedTranslation) {
402
+ const { languages: loadedLanguages, filePath } = loadedTranslation;
403
+ trace("Generating types for", filePath);
404
+ const translationTypes = /* @__PURE__ */ new Map();
405
+ let imports = /* @__PURE__ */ new Set();
406
+ for (const key of loadedTranslation.keys) {
407
+ let params = {};
408
+ const messages = /* @__PURE__ */ new Set();
409
+ let hasTags = false;
410
+ for (const translatedLanguage of Object.values(loadedLanguages)) if (translatedLanguage[key]) {
411
+ const ast = parse(translatedLanguage[key].message);
412
+ hasTags = hasTags || extractHasTags(ast);
413
+ const [parsedParams, vocabTypesImports] = extractParamTypes(ast, params);
414
+ imports = new Set([...imports, ...vocabTypesImports]);
415
+ params = parsedParams;
416
+ messages.add(JSON.stringify(translatedLanguage[key].message));
417
+ }
418
+ translationTypes.set(key, {
419
+ params,
420
+ hasTags,
421
+ message: Array.from(messages).join(" | ")
422
+ });
423
+ }
424
+ const prettierConfig = await prettier.resolveConfig(filePath);
425
+ const serializedTranslationType = serialiseTranslationRuntime(translationTypes, imports, loadedTranslation);
426
+ const declaration = await prettier.format(serializedTranslationType, {
427
+ ...prettierConfig,
428
+ parser: "typescript"
429
+ });
430
+ const outputFilePath = getTSFileFromDevLanguageFile(filePath);
431
+ trace(`Writing translation types to ${outputFilePath}`);
432
+ await writeIfChanged(outputFilePath, declaration);
433
+ }
434
+ function watch(config) {
435
+ const cwd = config.projectRoot || process.cwd();
436
+ const watcher = chokidar.watch([
437
+ getDevTranslationFileGlob(config),
438
+ getAltTranslationFileGlob(config),
439
+ getTranslationFolderGlob(config)
440
+ ], {
441
+ cwd,
442
+ ignored: config.ignore ? [...config.ignore, "**/node_modules/**"] : ["**/node_modules/**"],
443
+ ignoreInitial: true
444
+ });
445
+ const onTranslationChange = async (relativePath) => {
446
+ trace(`Detected change for file ${relativePath}`);
447
+ let targetFile;
448
+ if (isDevLanguageFile(relativePath)) targetFile = path.resolve(cwd, relativePath);
449
+ else if (isAltLanguageFile(relativePath)) targetFile = getDevLanguageFileFromAltLanguageFile(path.resolve(cwd, relativePath));
450
+ if (targetFile) try {
451
+ const loadedTranslation = loadTranslation({
452
+ filePath: targetFile,
453
+ fallbacks: "all"
454
+ }, config);
455
+ await generateRuntime(loadedTranslation);
456
+ } catch (e) {
457
+ console.log("Failed to generate types for", relativePath);
458
+ console.error(e);
459
+ }
460
+ };
461
+ const onNewDirectory = async (relativePath) => {
462
+ trace("Detected new directory", relativePath);
463
+ if (!isTranslationDirectory(relativePath, config)) {
464
+ trace("Ignoring non-translation directory:", relativePath);
465
+ return;
466
+ }
467
+ const newFilePath = path.join(relativePath, devTranslationFileName);
468
+ if (!existsSync(newFilePath)) {
469
+ await promises.writeFile(newFilePath, JSON.stringify({}, null, 2));
470
+ trace("Created new empty translation file:", newFilePath);
471
+ } else trace(`New directory already contains translation file. Skipping creation. Existing file ${newFilePath}`);
472
+ };
473
+ watcher.on("addDir", onNewDirectory);
474
+ watcher.on("add", onTranslationChange).on("change", onTranslationChange);
475
+ return () => watcher.close();
476
+ }
477
+ async function compile({ watch: shouldWatch = false } = {}, config) {
478
+ const translations = await loadAllTranslations({
479
+ fallbacks: "all",
480
+ includeNodeModules: false
481
+ }, config);
482
+ for (const loadedTranslation of translations) await generateRuntime(loadedTranslation);
483
+ if (shouldWatch) {
484
+ trace("Listening for changes to files...");
485
+ return watch(config);
486
+ }
487
+ }
488
+ async function writeIfChanged(filepath, contents) {
489
+ let hasChanged = true;
490
+ try {
491
+ hasChanged = await promises.readFile(filepath, { encoding: "utf-8" }) !== contents;
492
+ } catch {}
493
+ if (hasChanged) await promises.writeFile(filepath, contents, { encoding: "utf-8" });
494
+ }
495
+
496
+ //#endregion
497
+ //#region src/validate/index.ts
498
+ function findMissingKeys(loadedTranslation, devLanguageName, altLanguages) {
499
+ const devLanguage = loadedTranslation.languages[devLanguageName];
500
+ if (!devLanguage) throw new Error(`Failed to load dev language: ${loadedTranslation.filePath}`);
501
+ const result = {};
502
+ let valid = true;
503
+ const requiredKeys = Object.keys(devLanguage);
504
+ if (requiredKeys.length > 0) for (const altLanguageName of altLanguages) {
505
+ const altLanguage = loadedTranslation.languages[altLanguageName] ?? {};
506
+ for (const key of requiredKeys) if (typeof altLanguage[key]?.message !== "string") {
507
+ if (!result[altLanguageName]) result[altLanguageName] = [];
508
+ result[altLanguageName].push(key);
509
+ valid = false;
510
+ }
511
+ }
512
+ return [valid, result];
513
+ }
514
+ async function validate(config) {
515
+ const allTranslations = await loadAllTranslations({
516
+ fallbacks: "valid",
517
+ includeNodeModules: true
518
+ }, config);
519
+ let valid = true;
520
+ for (const loadedTranslation of allTranslations) {
521
+ const [translationValid, result] = findMissingKeys(loadedTranslation, config.devLanguage, getAltLanguages(config));
522
+ if (!translationValid) {
523
+ valid = false;
524
+ console.log(pc.red(`Incomplete translations: "${pc.bold(loadedTranslation.relativePath)}"`));
525
+ for (const lang of Object.keys(result)) {
526
+ const missingKeys = result[lang];
527
+ console.log(pc.yellow(lang), "->", missingKeys.map((v) => `"${v}"`).join(", "));
528
+ }
529
+ }
530
+ }
531
+ return valid;
532
+ }
533
+
534
+ //#endregion
535
+ //#region src/ValidationError.ts
536
+ var ValidationError = class extends Error {
537
+ code;
538
+ rawMessage;
539
+ constructor(code, message) {
540
+ super(`Invalid vocab.config.js: ${code} - ${message}`);
541
+ this.code = code;
542
+ this.rawMessage = message;
543
+ }
544
+ };
545
+
546
+ //#endregion
547
+ //#region src/config.ts
548
+ const boldCyan = (s) => pc.bold(pc.cyan(s));
549
+ const checkConfigFile = new Validator().compile({
550
+ $$strict: true,
551
+ devLanguage: { type: "string" },
552
+ languages: {
553
+ type: "array",
554
+ items: {
555
+ type: "object",
556
+ props: {
557
+ name: { type: "string" },
558
+ extends: {
559
+ type: "string",
560
+ optional: true
561
+ }
562
+ }
563
+ }
564
+ },
565
+ generatedLanguages: {
566
+ type: "array",
567
+ items: {
568
+ type: "object",
569
+ props: {
570
+ name: { type: "string" },
571
+ extends: {
572
+ type: "string",
573
+ optional: true
574
+ },
575
+ generator: {
576
+ type: "object",
577
+ props: {
578
+ transformElement: {
579
+ type: "function",
580
+ optional: true
581
+ },
582
+ transformMessage: {
583
+ type: "function",
584
+ optional: true
585
+ }
586
+ }
587
+ }
588
+ }
589
+ },
590
+ optional: true
591
+ },
592
+ translationsDirectorySuffix: {
593
+ type: "string",
594
+ optional: true
595
+ },
596
+ projectRoot: {
597
+ type: "string",
598
+ optional: true
599
+ },
600
+ ignore: {
601
+ type: "array",
602
+ items: "string",
603
+ optional: true
604
+ }
605
+ });
606
+ const splitMap = (message, callback) => message.split(" ,").map((v) => callback(v)).join(" ,");
607
+ function validateConfig(c) {
608
+ trace("Validating configuration file");
609
+ const isValid = checkConfigFile(c);
610
+ if (isValid !== true) throw new ValidationError("InvalidStructure", (Array.isArray(isValid) ? isValid : []).map((v) => {
611
+ if (v.type === "objectStrict") return `Invalid key(s) ${splitMap(v.actual, (m) => `"${pc.cyan(m)}"`)}. Expected one of ${splitMap(v.expected, pc.green)}`;
612
+ if (v.field) return v.message?.replace(v.field, pc.cyan(v.field));
613
+ return v.message;
614
+ }).join(" \n"));
615
+ const languageStrings = c.languages.map((v) => v.name);
616
+ if (!languageStrings.includes(c.devLanguage)) throw new ValidationError("InvalidDevLanguage", `The dev language "${boldCyan(c.devLanguage)}" was not found in languages ${languageStrings.join(", ")}.`);
617
+ const foundLanguages = [];
618
+ for (const lang of c.languages) {
619
+ if (foundLanguages.includes(lang.name)) throw new ValidationError("DuplicateLanguage", `The language "${boldCyan(lang.name)}" was defined multiple times.`);
620
+ foundLanguages.push(lang.name);
621
+ if (lang.extends && !languageStrings.includes(lang.extends)) throw new ValidationError("InvalidExtends", `The language "${boldCyan(lang.name)}"'s extends of ${boldCyan(lang.extends)} was not found in languages ${languageStrings.join(", ")}.`);
622
+ }
623
+ const foundGeneratedLanguages = [];
624
+ for (const generatedLang of c.generatedLanguages || []) {
625
+ if (foundGeneratedLanguages.includes(generatedLang.name)) throw new ValidationError("DuplicateGeneratedLanguage", `The generated language "${boldCyan(generatedLang.name)}" was defined multiple times.`);
626
+ foundGeneratedLanguages.push(generatedLang.name);
627
+ if (languageStrings.includes(generatedLang.name)) throw new ValidationError("InvalidGeneratedLanguage", `The generated language "${boldCyan(generatedLang.name)}" is already defined as a language.`);
628
+ if (generatedLang.extends && !languageStrings.includes(generatedLang.extends)) throw new ValidationError("InvalidExtends", `The generated language "${boldCyan(generatedLang.name)}"'s extends of ${boldCyan(generatedLang.extends)} was not found in languages ${languageStrings.join(", ")}.`);
629
+ }
630
+ trace("Configuration file is valid");
631
+ return true;
632
+ }
633
+ function createConfig(configFilePath) {
634
+ return {
635
+ projectRoot: path.dirname(configFilePath),
636
+ ...__require(configFilePath)
637
+ };
638
+ }
639
+ async function resolveConfig(customConfigFilePath) {
640
+ const configFilePath = customConfigFilePath ? path.resolve(customConfigFilePath) : await findUp(["vocab.config.js", "vocab.config.cjs"]);
641
+ if (configFilePath) {
642
+ trace(`Resolved configuration file to ${configFilePath}`);
643
+ return createConfig(configFilePath);
644
+ }
645
+ trace("No configuration file found");
646
+ return null;
647
+ }
648
+ function resolveConfigSync(customConfigFilePath) {
649
+ const configFilePath = customConfigFilePath ? path.resolve(customConfigFilePath) : findUp.sync(["vocab.config.js", "vocab.config.cjs"]);
650
+ if (configFilePath) {
651
+ trace(`Resolved configuration file to ${configFilePath}`);
652
+ return createConfig(configFilePath);
653
+ }
654
+ trace("No configuration file found");
655
+ return null;
656
+ }
657
+
658
+ //#endregion
659
+ export { compile, getAltLanguageFilePath, getAltLanguages, getDevLanguageFileFromTsFile, getUniqueKey, loadAllTranslations, loadTranslation, resolveConfig, resolveConfigSync, validate, validateConfig, watch };
660
+ //# sourceMappingURL=index.mjs.map