@intlayer/sync-json-plugin 7.5.10 → 7.5.11
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.
package/dist/cjs/syncJSON.cjs
CHANGED
|
@@ -17,12 +17,9 @@ const extractKeyAndLocaleFromPath = (filePath, maskPattern, locales, defaultLoca
|
|
|
17
17
|
regexStr = regexStr.replace(escapeRegex(localePlaceholder), `(?<locale>${localesAlternation})`);
|
|
18
18
|
if (maskPattern.includes(keyPlaceholder)) regexStr = regexStr.replace(escapeRegex(keyPlaceholder), "(?<key>[^/]+)");
|
|
19
19
|
const match = new RegExp(regexStr).exec(filePath);
|
|
20
|
-
|
|
21
|
-
let
|
|
22
|
-
|
|
23
|
-
locale = match.groups.locale;
|
|
24
|
-
key = match.groups.key ?? "index";
|
|
25
|
-
}
|
|
20
|
+
if (!match || !match.groups) return null;
|
|
21
|
+
let locale = match.groups.locale;
|
|
22
|
+
let key = match.groups.key ?? "index";
|
|
26
23
|
if (typeof key === "undefined") key = "index";
|
|
27
24
|
if (typeof locale === "undefined") locale = defaultLocale;
|
|
28
25
|
return {
|
|
@@ -46,10 +43,17 @@ const listMessages = (builder, configuration) => {
|
|
|
46
43
|
const files = fast_glob.default.sync(globPattern, { cwd: baseDir });
|
|
47
44
|
const result = {};
|
|
48
45
|
for (const file of files) {
|
|
49
|
-
const
|
|
50
|
-
|
|
46
|
+
const extraction = extractKeyAndLocaleFromPath(file, maskPattern, locales, defaultLocale);
|
|
47
|
+
if (!extraction) continue;
|
|
48
|
+
const { key, locale } = extraction;
|
|
49
|
+
const expectedPath = builder({
|
|
50
|
+
key,
|
|
51
|
+
locale
|
|
52
|
+
});
|
|
53
|
+
const absoluteFoundPath = (0, node_path.isAbsolute)(file) ? file : (0, node_path.resolve)(baseDir, file);
|
|
54
|
+
if (absoluteFoundPath !== ((0, node_path.isAbsolute)(expectedPath) ? expectedPath : (0, node_path.resolve)(baseDir, expectedPath))) continue;
|
|
51
55
|
if (!result[locale]) result[locale] = {};
|
|
52
|
-
result[locale][key] =
|
|
56
|
+
result[locale][key] = absoluteFoundPath;
|
|
53
57
|
}
|
|
54
58
|
const hasKeyInMask = maskPattern.includes("{{__KEY__}}");
|
|
55
59
|
const discoveredKeys = /* @__PURE__ */ new Set();
|
|
@@ -81,7 +85,10 @@ const loadMessagePathMap = (source, configuration) => {
|
|
|
81
85
|
};
|
|
82
86
|
const syncJSON = (options) => {
|
|
83
87
|
const { location, priority, format } = {
|
|
84
|
-
location:
|
|
88
|
+
location: `sync-json::${options.source({
|
|
89
|
+
key: "{{key}}",
|
|
90
|
+
locale: "{{locale}}"
|
|
91
|
+
})}`,
|
|
85
92
|
priority: 0,
|
|
86
93
|
...options
|
|
87
94
|
};
|
|
@@ -126,7 +133,10 @@ const syncJSON = (options) => {
|
|
|
126
133
|
key: dictionary.key,
|
|
127
134
|
locale: dictionary.locale
|
|
128
135
|
})) !== (0, node_path.resolve)(dictionary.filePath)) return dictionary;
|
|
129
|
-
return
|
|
136
|
+
return (0, _intlayer_chokidar.formatDictionaryOutput)({
|
|
137
|
+
...dictionary,
|
|
138
|
+
format
|
|
139
|
+
}).content;
|
|
130
140
|
},
|
|
131
141
|
afterBuild: async ({ dictionaries, configuration }) => {
|
|
132
142
|
const { getPerLocaleDictionary } = await import("@intlayer/core");
|
|
@@ -137,6 +147,7 @@ const syncJSON = (options) => {
|
|
|
137
147
|
dictionary: dictionary.dictionary,
|
|
138
148
|
locale
|
|
139
149
|
}))), async ({ key, dictionary, locale }) => {
|
|
150
|
+
if (dictionary.location !== location) return;
|
|
140
151
|
const builderPath = options.source({
|
|
141
152
|
key,
|
|
142
153
|
locale
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncJSON.cjs","names":["locale: Locale | undefined","key: string | undefined","fg","result: MessagesRecord","messages: MessagesRecord","dictionariesMap: DictionariesMap","fill: string","dictionaries: Dictionary[]","json: JSONContent","dictionary: Dictionary"],"sources":["../../src/syncJSON.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { formatDictionaryOutput } from '@intlayer/chokidar';\nimport { getProjectRequire } from '@intlayer/config';\nimport type {\n Dictionary,\n DictionaryFormat,\n IntlayerConfig,\n LocalDictionaryId,\n Locale,\n LocalesValues,\n Plugin,\n} from '@intlayer/types';\nimport fg from 'fast-glob';\n\ntype JSONContent = Record<string, any>;\n\ntype Builder = ({\n key,\n locale,\n}: {\n key: string;\n locale: LocalesValues | (string & {});\n}) => string;\n\ntype MessagesRecord = Record<Locale, Record<Dictionary['key'], FilePath>>;\n\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const extractKeyAndLocaleFromPath = (\n filePath: string,\n maskPattern: string,\n locales: Locale[],\n defaultLocale: Locale\n) => {\n const keyPlaceholder = '{{__KEY__}}';\n const localePlaceholder = '{{__LOCALE__}}';\n\n const escapedMask = escapeRegex(maskPattern);\n const localesAlternation = locales.join('|');\n\n // Build a regex from the mask to capture locale (and key if present)\n let regexStr = `^${escapedMask}$`;\n\n regexStr = regexStr.replace(\n escapeRegex(localePlaceholder),\n `(?<locale>${localesAlternation})`\n );\n\n if (maskPattern.includes(keyPlaceholder)) {\n regexStr = regexStr.replace(escapeRegex(keyPlaceholder), '(?<key>[^/]+)');\n }\n\n const maskRegex = new RegExp(regexStr);\n\n const match = maskRegex.exec(filePath);\n\n let locale: Locale | undefined;\n let key: string | undefined;\n\n if (match?.groups) {\n locale = match.groups.locale as Locale | undefined;\n key = (match.groups.key as string | undefined) ?? 'index';\n }\n\n if (typeof key === 'undefined') {\n key = 'index';\n }\n\n if (typeof locale === 'undefined') {\n locale = defaultLocale;\n }\n\n return {\n key,\n locale,\n };\n};\n\nconst listMessages = (\n builder: Builder,\n configuration: IntlayerConfig\n): MessagesRecord => {\n const { content, internationalization } = configuration;\n\n const baseDir = content.baseDir;\n const locales = internationalization.locales;\n const defaultLocale = internationalization.defaultLocale;\n\n const localePattern = `{${locales.map((locale) => locale).join(',')}}`;\n\n const globPattern = builder({ key: '*', locale: localePattern });\n const maskPattern = builder({ key: '{{__KEY__}}', locale: '{{__LOCALE__}}' });\n\n const files = fg.sync(globPattern, {\n cwd: baseDir,\n });\n\n const result: MessagesRecord = {} as MessagesRecord;\n\n for (const file of files) {\n const { key, locale } = extractKeyAndLocaleFromPath(\n file,\n maskPattern,\n locales,\n defaultLocale\n );\n\n const absolutePath = isAbsolute(file) ? file : resolve(baseDir, file);\n\n if (!result[locale as Locale]) {\n result[locale as Locale] = {};\n }\n\n result[locale as Locale][key as Dictionary['key']] = absolutePath;\n }\n\n // Ensure all declared locales are present even if the file doesn't exist yet\n // Derive the list of keys from discovered files; if no key placeholder in mask, default to 'index'\n const hasKeyInMask = maskPattern.includes('{{__KEY__}}');\n const discoveredKeys = new Set<string>();\n\n for (const locale of Object.keys(result)) {\n for (const key of Object.keys(result[locale as Locale] ?? {})) {\n discoveredKeys.add(key);\n }\n }\n\n if (!hasKeyInMask) {\n discoveredKeys.add('index');\n }\n\n // If no keys were discovered and mask expects a key, we cannot infer keys.\n // In that case, do not fabricate unknown keys.\n const keysToEnsure =\n discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];\n\n for (const locale of locales) {\n if (!result[locale]) {\n result[locale] = {} as Record<Dictionary['key'], FilePath>;\n }\n\n for (const key of keysToEnsure) {\n if (!result[locale][key as Dictionary['key']]) {\n const builtPath = builder({ key, locale });\n const absoluteBuiltPath = isAbsolute(builtPath)\n ? builtPath\n : resolve(baseDir, builtPath);\n\n result[locale][key as Dictionary['key']] = absoluteBuiltPath;\n }\n }\n }\n\n return result;\n};\n\ntype FilePath = string;\n\ntype DictionariesMap = { path: string; locale: Locale; key: string }[];\n\nconst loadMessagePathMap = (\n source: MessagesRecord | Builder,\n configuration: IntlayerConfig\n) => {\n const messages: MessagesRecord = listMessages(\n source as Builder,\n configuration\n );\n\n const dictionariesPathMap: DictionariesMap = Object.entries(messages).flatMap(\n ([locale, keysRecord]) =>\n Object.entries(keysRecord).map(([key, path]) => {\n const absolutePath = isAbsolute(path)\n ? path\n : resolve(configuration.content.baseDir, path);\n\n return {\n path: absolutePath,\n locale,\n key,\n } as DictionariesMap[number];\n })\n );\n\n return dictionariesPathMap;\n};\n\ntype SyncJSONPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * ```ts\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * })\n * ```\n */\n source: Builder;\n\n /**\n * Because Intlayer transform the JSON files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * ```ts\n * const config ={\n * plugins: [\n * syncJSON({\n * source: ({ key, locale }) => `./resources/${locale}/${key}.json`\n * location: 'plugin-i18next',\n * }),\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * location: 'plugin-next-intl',\n * }),\n * ]\n * }\n * ```\n */\n location?: string;\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is -1. (.content file priority is 0)\n *\n */\n priority?: number;\n\n /**\n * The format of the dictionaries created by the plugin.\n *\n * Default: 'intlayer'\n *\n * The format of the dictionaries created by the plugin.\n */\n format?: DictionaryFormat;\n};\n\nexport const syncJSON = (options: SyncJSONPluginOptions): Plugin => {\n const { location, priority, format } = {\n location: 'plugin',\n priority: 0,\n ...options,\n };\n\n return {\n name: 'sync-json',\n\n loadDictionaries: async ({ configuration }) => {\n const dictionariesMap: DictionariesMap = loadMessagePathMap(\n options.source,\n configuration\n );\n\n let fill: string = options.source({\n key: '{{key}}',\n locale: '{{locale}}',\n });\n\n if (fill && !isAbsolute(fill)) {\n fill = join(configuration.content.baseDir, fill);\n }\n\n const dictionaries: Dictionary[] = [];\n\n for (const { locale, path, key } of dictionariesMap) {\n const requireFunction =\n configuration.build?.require ?? getProjectRequire();\n let json: JSONContent = {};\n try {\n json = requireFunction(path as string);\n } catch {\n // File does not exist yet; default to empty content so it can be filled later\n json = {};\n }\n\n const filePath = relative(configuration.content.baseDir, path);\n\n const dictionary: Dictionary = {\n key,\n locale,\n fill,\n format,\n localId: `${key}::${location}::${filePath}` as LocalDictionaryId,\n location: location as Dictionary['location'],\n filled:\n locale !== configuration.internationalization.defaultLocale\n ? true\n : undefined,\n content: json,\n filePath,\n priority,\n };\n\n dictionaries.push(dictionary);\n }\n\n return dictionaries;\n },\n\n formatOutput: ({ dictionary }) => {\n if (!dictionary.filePath || !dictionary.locale) return dictionary;\n\n const builderPath = options.source({\n key: dictionary.key,\n locale: dictionary.locale,\n });\n\n // It's not one of the JSON that we synchronize, don't modify it\n if (resolve(builderPath) !== resolve(dictionary.filePath)) {\n return dictionary;\n }\n\n return dictionary.content;\n },\n afterBuild: async ({ dictionaries, configuration }) => {\n // Dynamic import to avoid circular dependency as core package import config, that load esbuild, that load the config file, that load the plugin\n const { getPerLocaleDictionary } = await import('@intlayer/core');\n const { parallelize } = await import('@intlayer/chokidar');\n\n const locales = configuration.internationalization.locales;\n\n type RecordList = {\n key: string;\n dictionary: Dictionary;\n locale: Locale;\n };\n\n const recordList: RecordList[] = Object.entries(\n dictionaries.mergedDictionaries\n ).flatMap(([key, dictionary]) =>\n locales.map((locale) => ({\n key,\n dictionary: dictionary.dictionary as Dictionary,\n locale,\n }))\n );\n\n await parallelize(recordList, async ({ key, dictionary, locale }) => {\n const builderPath = options.source({\n key,\n locale,\n });\n\n const localizedDictionary = getPerLocaleDictionary(dictionary, locale);\n\n // Restore the original format from plugin options for output formatting\n const dictionaryWithFormat = {\n ...localizedDictionary,\n format,\n };\n\n const formattedOutput = formatDictionaryOutput(dictionaryWithFormat);\n\n // Remove function, Symbol, etc. as it can be written as JSON\n const content = JSON.parse(JSON.stringify(formattedOutput.content));\n\n if (\n typeof content === 'undefined' ||\n (typeof content === 'object' &&\n Object.keys(content as Record<string, unknown>).length === 0)\n ) {\n return;\n }\n\n // Ensure directory exists before writing the file\n await mkdir(dirname(builderPath), { recursive: true });\n\n const stringContent = JSON.stringify(content, null, 2);\n\n await writeFile(\n builderPath,\n `${stringContent}\\n`, // Add a new line at the end of the file to avoid formatting issues with VSCode\n 'utf-8'\n );\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;AA2BA,MAAM,eAAe,QAAgB,IAAI,QAAQ,uBAAuB,OAAO;AAE/E,MAAa,+BACX,UACA,aACA,SACA,kBACG;CACH,MAAM,iBAAiB;CACvB,MAAM,oBAAoB;CAE1B,MAAM,cAAc,YAAY,YAAY;CAC5C,MAAM,qBAAqB,QAAQ,KAAK,IAAI;CAG5C,IAAI,WAAW,IAAI,YAAY;AAE/B,YAAW,SAAS,QAClB,YAAY,kBAAkB,EAC9B,aAAa,mBAAmB,GACjC;AAED,KAAI,YAAY,SAAS,eAAe,CACtC,YAAW,SAAS,QAAQ,YAAY,eAAe,EAAE,gBAAgB;CAK3E,MAAM,QAFY,IAAI,OAAO,SAAS,CAEd,KAAK,SAAS;CAEtC,IAAIA;CACJ,IAAIC;AAEJ,KAAI,OAAO,QAAQ;AACjB,WAAS,MAAM,OAAO;AACtB,QAAO,MAAM,OAAO,OAA8B;;AAGpD,KAAI,OAAO,QAAQ,YACjB,OAAM;AAGR,KAAI,OAAO,WAAW,YACpB,UAAS;AAGX,QAAO;EACL;EACA;EACD;;AAGH,MAAM,gBACJ,SACA,kBACmB;CACnB,MAAM,EAAE,SAAS,yBAAyB;CAE1C,MAAM,UAAU,QAAQ;CACxB,MAAM,UAAU,qBAAqB;CACrC,MAAM,gBAAgB,qBAAqB;CAI3C,MAAM,cAAc,QAAQ;EAAE,KAAK;EAAK,QAFlB,IAAI,QAAQ,KAAK,WAAW,OAAO,CAAC,KAAK,IAAI,CAAC;EAEL,CAAC;CAChE,MAAM,cAAc,QAAQ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BACf,QAAQ,KAAK,YAAY;IACvB;IACA,YAAY,WAAW;IACvB;IACD,EAAE,CACJ,EAE6B,OAAO,EAAE,KAAK,YAAY,aAAa;IACnE,MAAM,cAAc,QAAQ,OAAO;KACjC;KACA;KACD,CAAC;IAUF,MAAM,iEALuB;KAC3B,GAJ0B,uBAAuB,YAAY,OAAO;KAKpE;KACD,CAEmE;IAGpE,MAAM,UAAU,KAAK,MAAM,KAAK,UAAU,gBAAgB,QAAQ,CAAC;AAEnE,QACE,OAAO,YAAY,eAClB,OAAO,YAAY,YAClB,OAAO,KAAK,QAAmC,CAAC,WAAW,EAE7D;AAIF,6DAAoB,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAItD,0CACE,aACA,GAJoB,KAAK,UAAU,SAAS,MAAM,EAAE,CAInC,KACjB,QACD;KACD;;EAEL"}
|
|
1
|
+
{"version":3,"file":"syncJSON.cjs","names":["fg","result: MessagesRecord","messages: MessagesRecord","dictionariesMap: DictionariesMap","fill: string","dictionaries: Dictionary[]","json: JSONContent","dictionary: Dictionary"],"sources":["../../src/syncJSON.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { formatDictionaryOutput } from '@intlayer/chokidar';\nimport { getProjectRequire } from '@intlayer/config';\nimport type {\n Dictionary,\n DictionaryFormat,\n IntlayerConfig,\n LocalDictionaryId,\n Locale,\n LocalesValues,\n Plugin,\n} from '@intlayer/types';\nimport fg from 'fast-glob';\n\ntype JSONContent = Record<string, any>;\n\ntype Builder = ({\n key,\n locale,\n}: {\n key: string;\n locale: LocalesValues | (string & {});\n}) => string;\n\ntype MessagesRecord = Record<Locale, Record<Dictionary['key'], FilePath>>;\n\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const extractKeyAndLocaleFromPath = (\n filePath: string,\n maskPattern: string,\n locales: Locale[],\n defaultLocale: Locale\n): { key: string; locale: Locale } | null => {\n const keyPlaceholder = '{{__KEY__}}';\n const localePlaceholder = '{{__LOCALE__}}';\n\n const escapedMask = escapeRegex(maskPattern);\n const localesAlternation = locales.join('|');\n\n // Build a regex from the mask to capture locale (and key if present)\n let regexStr = `^${escapedMask}$`;\n\n regexStr = regexStr.replace(\n escapeRegex(localePlaceholder),\n `(?<locale>${localesAlternation})`\n );\n\n if (maskPattern.includes(keyPlaceholder)) {\n // Ensure key does not contain slashes to prevent matching across directories\n regexStr = regexStr.replace(escapeRegex(keyPlaceholder), '(?<key>[^/]+)');\n }\n\n const maskRegex = new RegExp(regexStr);\n const match = maskRegex.exec(filePath);\n\n // FIX: If the path doesn't strictly match the pattern, return null\n // Do not fall back to 'index' or defaultLocale for unmatched files.\n if (!match || !match.groups) {\n return null;\n }\n\n let locale = match.groups.locale as Locale | undefined;\n let key = (match.groups.key as string | undefined) ?? 'index';\n\n if (typeof key === 'undefined') {\n key = 'index';\n }\n\n if (typeof locale === 'undefined') {\n locale = defaultLocale;\n }\n\n return {\n key,\n locale,\n };\n};\n\nconst listMessages = (\n builder: Builder,\n configuration: IntlayerConfig\n): MessagesRecord => {\n const { content, internationalization } = configuration;\n\n const baseDir = content.baseDir;\n const locales = internationalization.locales;\n const defaultLocale = internationalization.defaultLocale;\n\n const localePattern = `{${locales.map((locale) => locale).join(',')}}`;\n\n const globPattern = builder({ key: '*', locale: localePattern });\n const maskPattern = builder({ key: '{{__KEY__}}', locale: '{{__LOCALE__}}' });\n\n const files = fg.sync(globPattern, {\n cwd: baseDir,\n });\n\n const result: MessagesRecord = {} as MessagesRecord;\n\n for (const file of files) {\n const extraction = extractKeyAndLocaleFromPath(\n file,\n maskPattern,\n locales,\n defaultLocale\n );\n\n // FIX: If extraction failed (regex mismatch), skip this file\n if (!extraction) {\n continue;\n }\n\n const { key, locale } = extraction;\n\n // FIX: Round Trip Check\n // 1. Generate what the path SHOULD be for this key/locale using the current builder\n const expectedPath = builder({ key, locale });\n\n // 2. Resolve both to absolute paths to ensure safe comparison\n const absoluteFoundPath = isAbsolute(file) ? file : resolve(baseDir, file);\n const absoluteExpectedPath = isAbsolute(expectedPath)\n ? expectedPath\n : resolve(baseDir, expectedPath);\n\n // 3. If the file found doesn't exactly match the file expected, it belongs to another plugin/structure\n if (absoluteFoundPath !== absoluteExpectedPath) {\n continue;\n }\n\n if (!result[locale as Locale]) {\n result[locale as Locale] = {};\n }\n\n result[locale as Locale][key as Dictionary['key']] = absoluteFoundPath;\n }\n\n // Ensure all declared locales are present even if the file doesn't exist yet\n const hasKeyInMask = maskPattern.includes('{{__KEY__}}');\n const discoveredKeys = new Set<string>();\n\n for (const locale of Object.keys(result)) {\n for (const key of Object.keys(result[locale as Locale] ?? {})) {\n discoveredKeys.add(key);\n }\n }\n\n if (!hasKeyInMask) {\n discoveredKeys.add('index');\n }\n\n const keysToEnsure =\n discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];\n\n for (const locale of locales) {\n if (!result[locale]) {\n result[locale] = {} as Record<Dictionary['key'], FilePath>;\n }\n\n for (const key of keysToEnsure) {\n if (!result[locale][key as Dictionary['key']]) {\n const builtPath = builder({ key, locale });\n const absoluteBuiltPath = isAbsolute(builtPath)\n ? builtPath\n : resolve(baseDir, builtPath);\n\n result[locale][key as Dictionary['key']] = absoluteBuiltPath;\n }\n }\n }\n\n return result;\n};\n\ntype FilePath = string;\n\ntype DictionariesMap = { path: string; locale: Locale; key: string }[];\n\nconst loadMessagePathMap = (\n source: MessagesRecord | Builder,\n configuration: IntlayerConfig\n) => {\n const messages: MessagesRecord = listMessages(\n source as Builder,\n configuration\n );\n\n const dictionariesPathMap: DictionariesMap = Object.entries(messages).flatMap(\n ([locale, keysRecord]) =>\n Object.entries(keysRecord).map(([key, path]) => {\n const absolutePath = isAbsolute(path)\n ? path\n : resolve(configuration.content.baseDir, path);\n\n return {\n path: absolutePath,\n locale,\n key,\n } as DictionariesMap[number];\n })\n );\n\n return dictionariesPathMap;\n};\n\ntype SyncJSONPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * ```ts\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * })\n * ```\n */\n source: Builder;\n\n /**\n * Because Intlayer transform the JSON files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * ```ts\n * const config ={\n * plugins: [\n * syncJSON({\n * source: ({ key, locale }) => `./resources/${locale}/${key}.json`\n * location: 'plugin-i18next',\n * }),\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * location: 'plugin-next-intl',\n * }),\n * ]\n * }\n * ```\n */\n location?: string;\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is -1. (.content file priority is 0)\n *\n */\n priority?: number;\n\n /**\n * The format of the dictionaries created by the plugin.\n *\n * Default: 'intlayer'\n *\n * The format of the dictionaries created by the plugin.\n */\n format?: DictionaryFormat;\n};\n\nexport const syncJSON = (options: SyncJSONPluginOptions): Plugin => {\n // Generate a unique default location based on the source pattern.\n // This ensures that if you have multiple plugins, they don't share the same 'plugin' ID.\n const patternMarker = options.source({\n key: '{{key}}',\n locale: '{{locale}}',\n });\n const defaultLocation = `sync-json::${patternMarker}`;\n\n const { location, priority, format } = {\n location: defaultLocation,\n priority: 0,\n ...options,\n };\n\n return {\n name: 'sync-json',\n\n loadDictionaries: async ({ configuration }) => {\n const dictionariesMap: DictionariesMap = loadMessagePathMap(\n options.source,\n configuration\n );\n\n let fill: string = options.source({\n key: '{{key}}',\n locale: '{{locale}}',\n });\n\n if (fill && !isAbsolute(fill)) {\n fill = join(configuration.content.baseDir, fill);\n }\n\n const dictionaries: Dictionary[] = [];\n\n for (const { locale, path, key } of dictionariesMap) {\n const requireFunction =\n configuration.build?.require ?? getProjectRequire();\n let json: JSONContent = {};\n try {\n json = requireFunction(path as string);\n } catch {\n json = {};\n }\n\n const filePath = relative(configuration.content.baseDir, path);\n\n const dictionary: Dictionary = {\n key,\n locale,\n fill,\n format,\n localId: `${key}::${location}::${filePath}` as LocalDictionaryId,\n location: location as Dictionary['location'],\n filled:\n locale !== configuration.internationalization.defaultLocale\n ? true\n : undefined,\n content: json,\n filePath,\n priority,\n };\n\n dictionaries.push(dictionary);\n }\n\n return dictionaries;\n },\n\n formatOutput: ({ dictionary }) => {\n if (!dictionary.filePath || !dictionary.locale) return dictionary;\n\n const builderPath = options.source({\n key: dictionary.key,\n locale: dictionary.locale,\n });\n\n // Verification to ensure we are formatting the correct file\n if (resolve(builderPath) !== resolve(dictionary.filePath)) {\n return dictionary;\n }\n\n const dictionaryWithFormat = {\n ...dictionary,\n format,\n };\n\n const formattedOutput = formatDictionaryOutput(\n dictionaryWithFormat as Dictionary\n );\n\n return formattedOutput.content;\n },\n\n afterBuild: async ({ dictionaries, configuration }) => {\n const { getPerLocaleDictionary } = await import('@intlayer/core');\n const { parallelize } = await import('@intlayer/chokidar');\n\n const locales = configuration.internationalization.locales;\n\n type RecordList = {\n key: string;\n dictionary: Dictionary;\n locale: Locale;\n };\n\n // We get all dictionaries, but we need to filter them\n const recordList: RecordList[] = Object.entries(\n dictionaries.mergedDictionaries\n ).flatMap(([key, dictionary]) =>\n locales.map((locale) => ({\n key,\n dictionary: dictionary.dictionary as Dictionary,\n locale,\n }))\n );\n\n await parallelize(recordList, async ({ key, dictionary, locale }) => {\n // Only process dictionaries that belong to THIS plugin instance.\n if (dictionary.location !== location) {\n return;\n }\n\n const builderPath = options.source({\n key,\n locale,\n });\n\n const localizedDictionary = getPerLocaleDictionary(dictionary, locale);\n\n const dictionaryWithFormat = {\n ...localizedDictionary,\n format,\n };\n\n const formattedOutput = formatDictionaryOutput(dictionaryWithFormat);\n\n const content = JSON.parse(JSON.stringify(formattedOutput.content));\n\n if (\n typeof content === 'undefined' ||\n (typeof content === 'object' &&\n Object.keys(content as Record<string, unknown>).length === 0)\n ) {\n return;\n }\n\n await mkdir(dirname(builderPath), { recursive: true });\n\n const stringContent = JSON.stringify(content, null, 2);\n\n await writeFile(builderPath, `${stringContent}\\n`, 'utf-8');\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;AA2BA,MAAM,eAAe,QAAgB,IAAI,QAAQ,uBAAuB,OAAO;AAE/E,MAAa,+BACX,UACA,aACA,SACA,kBAC2C;CAC3C,MAAM,iBAAiB;CACvB,MAAM,oBAAoB;CAE1B,MAAM,cAAc,YAAY,YAAY;CAC5C,MAAM,qBAAqB,QAAQ,KAAK,IAAI;CAG5C,IAAI,WAAW,IAAI,YAAY;AAE/B,YAAW,SAAS,QAClB,YAAY,kBAAkB,EAC9B,aAAa,mBAAmB,GACjC;AAED,KAAI,YAAY,SAAS,eAAe,CAEtC,YAAW,SAAS,QAAQ,YAAY,eAAe,EAAE,gBAAgB;CAI3E,MAAM,QADY,IAAI,OAAO,SAAS,CACd,KAAK,SAAS;AAItC,KAAI,CAAC,SAAS,CAAC,MAAM,OACnB,QAAO;CAGT,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAI,MAAO,MAAM,OAAO,OAA8B;AAEtD,KAAI,OAAO,QAAQ,YACjB,OAAM;AAGR,KAAI,OAAO,WAAW,YACpB,UAAS;AAGX,QAAO;EACL;EACA;EACD;;AAGH,MAAM,gBACJ,SACA,kBACmB;CACnB,MAAM,EAAE,SAAS,yBAAyB;CAE1C,MAAM,UAAU,QAAQ;CACxB,MAAM,UAAU,qBAAqB;CACrC,MAAM,gBAAgB,qBAAqB;CAI3C,MAAM,cAAc,QAAQ;EAAE,KAAK;EAAK,QAFlB,IAAI,QAAQ,KAAK,WAAW,OAAO,CAAC,KAAK,IAAI,CAAC;EAEL,CAAC;CAChE,MAAM,cAAc,QAAQ;EAAE,KAAK;EAAe,QAAQ;EAAkB,CAAC;CAE7E,MAAM,QAAQA,kBAAG,KAAK,aAAa,EACjC,KAAK,SACN,CA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;GAChD,MAAM,EAAE,gBAAgB,MAAM,OAAO;GAErC,MAAM,UAAU,cAAc,qBAAqB;AAmBnD,SAAM,YAV2B,OAAO,QACtC,aAAa,mBACd,CAAC,SAAS,CAAC,KAAK,gBACf,QAAQ,KAAK,YAAY;IACvB;IACA,YAAY,WAAW;IACvB;IACD,EAAE,CACJ,EAE6B,OAAO,EAAE,KAAK,YAAY,aAAa;AAEnE,QAAI,WAAW,aAAa,SAC1B;IAGF,MAAM,cAAc,QAAQ,OAAO;KACjC;KACA;KACD,CAAC;IASF,MAAM,iEALuB;KAC3B,GAH0B,uBAAuB,YAAY,OAAO;KAIpE;KACD,CAEmE;IAEpE,MAAM,UAAU,KAAK,MAAM,KAAK,UAAU,gBAAgB,QAAQ,CAAC;AAEnE,QACE,OAAO,YAAY,eAClB,OAAO,YAAY,YAClB,OAAO,KAAK,QAAmC,CAAC,WAAW,EAE7D;AAGF,6DAAoB,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAItD,0CAAgB,aAAa,GAFP,KAAK,UAAU,SAAS,MAAM,EAAE,CAER,KAAK,QAAQ;KAC3D;;EAEL"}
|
package/dist/esm/syncJSON.mjs
CHANGED
|
@@ -15,12 +15,9 @@ const extractKeyAndLocaleFromPath = (filePath, maskPattern, locales, defaultLoca
|
|
|
15
15
|
regexStr = regexStr.replace(escapeRegex(localePlaceholder), `(?<locale>${localesAlternation})`);
|
|
16
16
|
if (maskPattern.includes(keyPlaceholder)) regexStr = regexStr.replace(escapeRegex(keyPlaceholder), "(?<key>[^/]+)");
|
|
17
17
|
const match = new RegExp(regexStr).exec(filePath);
|
|
18
|
-
|
|
19
|
-
let
|
|
20
|
-
|
|
21
|
-
locale = match.groups.locale;
|
|
22
|
-
key = match.groups.key ?? "index";
|
|
23
|
-
}
|
|
18
|
+
if (!match || !match.groups) return null;
|
|
19
|
+
let locale = match.groups.locale;
|
|
20
|
+
let key = match.groups.key ?? "index";
|
|
24
21
|
if (typeof key === "undefined") key = "index";
|
|
25
22
|
if (typeof locale === "undefined") locale = defaultLocale;
|
|
26
23
|
return {
|
|
@@ -44,10 +41,17 @@ const listMessages = (builder, configuration) => {
|
|
|
44
41
|
const files = fg.sync(globPattern, { cwd: baseDir });
|
|
45
42
|
const result = {};
|
|
46
43
|
for (const file of files) {
|
|
47
|
-
const
|
|
48
|
-
|
|
44
|
+
const extraction = extractKeyAndLocaleFromPath(file, maskPattern, locales, defaultLocale);
|
|
45
|
+
if (!extraction) continue;
|
|
46
|
+
const { key, locale } = extraction;
|
|
47
|
+
const expectedPath = builder({
|
|
48
|
+
key,
|
|
49
|
+
locale
|
|
50
|
+
});
|
|
51
|
+
const absoluteFoundPath = isAbsolute(file) ? file : resolve(baseDir, file);
|
|
52
|
+
if (absoluteFoundPath !== (isAbsolute(expectedPath) ? expectedPath : resolve(baseDir, expectedPath))) continue;
|
|
49
53
|
if (!result[locale]) result[locale] = {};
|
|
50
|
-
result[locale][key] =
|
|
54
|
+
result[locale][key] = absoluteFoundPath;
|
|
51
55
|
}
|
|
52
56
|
const hasKeyInMask = maskPattern.includes("{{__KEY__}}");
|
|
53
57
|
const discoveredKeys = /* @__PURE__ */ new Set();
|
|
@@ -79,7 +83,10 @@ const loadMessagePathMap = (source, configuration) => {
|
|
|
79
83
|
};
|
|
80
84
|
const syncJSON = (options) => {
|
|
81
85
|
const { location, priority, format } = {
|
|
82
|
-
location:
|
|
86
|
+
location: `sync-json::${options.source({
|
|
87
|
+
key: "{{key}}",
|
|
88
|
+
locale: "{{locale}}"
|
|
89
|
+
})}`,
|
|
83
90
|
priority: 0,
|
|
84
91
|
...options
|
|
85
92
|
};
|
|
@@ -124,7 +131,10 @@ const syncJSON = (options) => {
|
|
|
124
131
|
key: dictionary.key,
|
|
125
132
|
locale: dictionary.locale
|
|
126
133
|
})) !== resolve(dictionary.filePath)) return dictionary;
|
|
127
|
-
return
|
|
134
|
+
return formatDictionaryOutput({
|
|
135
|
+
...dictionary,
|
|
136
|
+
format
|
|
137
|
+
}).content;
|
|
128
138
|
},
|
|
129
139
|
afterBuild: async ({ dictionaries, configuration }) => {
|
|
130
140
|
const { getPerLocaleDictionary } = await import("@intlayer/core");
|
|
@@ -135,6 +145,7 @@ const syncJSON = (options) => {
|
|
|
135
145
|
dictionary: dictionary.dictionary,
|
|
136
146
|
locale
|
|
137
147
|
}))), async ({ key, dictionary, locale }) => {
|
|
148
|
+
if (dictionary.location !== location) return;
|
|
138
149
|
const builderPath = options.source({
|
|
139
150
|
key,
|
|
140
151
|
locale
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncJSON.mjs","names":["locale: Locale | undefined","key: string | undefined","result: MessagesRecord","messages: MessagesRecord","dictionariesMap: DictionariesMap","fill: string","dictionaries: Dictionary[]","json: JSONContent","dictionary: Dictionary"],"sources":["../../src/syncJSON.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { formatDictionaryOutput } from '@intlayer/chokidar';\nimport { getProjectRequire } from '@intlayer/config';\nimport type {\n Dictionary,\n DictionaryFormat,\n IntlayerConfig,\n LocalDictionaryId,\n Locale,\n LocalesValues,\n Plugin,\n} from '@intlayer/types';\nimport fg from 'fast-glob';\n\ntype JSONContent = Record<string, any>;\n\ntype Builder = ({\n key,\n locale,\n}: {\n key: string;\n locale: LocalesValues | (string & {});\n}) => string;\n\ntype MessagesRecord = Record<Locale, Record<Dictionary['key'], FilePath>>;\n\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const extractKeyAndLocaleFromPath = (\n filePath: string,\n maskPattern: string,\n locales: Locale[],\n defaultLocale: Locale\n) => {\n const keyPlaceholder = '{{__KEY__}}';\n const localePlaceholder = '{{__LOCALE__}}';\n\n const escapedMask = escapeRegex(maskPattern);\n const localesAlternation = locales.join('|');\n\n // Build a regex from the mask to capture locale (and key if present)\n let regexStr = `^${escapedMask}$`;\n\n regexStr = regexStr.replace(\n escapeRegex(localePlaceholder),\n `(?<locale>${localesAlternation})`\n );\n\n if (maskPattern.includes(keyPlaceholder)) {\n regexStr = regexStr.replace(escapeRegex(keyPlaceholder), '(?<key>[^/]+)');\n }\n\n const maskRegex = new RegExp(regexStr);\n\n const match = maskRegex.exec(filePath);\n\n let locale: Locale | undefined;\n let key: string | undefined;\n\n if (match?.groups) {\n locale = match.groups.locale as Locale | undefined;\n key = (match.groups.key as string | undefined) ?? 'index';\n }\n\n if (typeof key === 'undefined') {\n key = 'index';\n }\n\n if (typeof locale === 'undefined') {\n locale = defaultLocale;\n }\n\n return {\n key,\n locale,\n };\n};\n\nconst listMessages = (\n builder: Builder,\n configuration: IntlayerConfig\n): MessagesRecord => {\n const { content, internationalization } = configuration;\n\n const baseDir = content.baseDir;\n const locales = internationalization.locales;\n const defaultLocale = internationalization.defaultLocale;\n\n const localePattern = `{${locales.map((locale) => locale).join(',')}}`;\n\n const globPattern = builder({ key: '*', locale: localePattern });\n const maskPattern = builder({ key: '{{__KEY__}}', locale: '{{__LOCALE__}}' });\n\n const files = fg.sync(globPattern, {\n cwd: baseDir,\n });\n\n const result: MessagesRecord = {} as MessagesRecord;\n\n for (const file of files) {\n const { key, locale } = extractKeyAndLocaleFromPath(\n file,\n maskPattern,\n locales,\n defaultLocale\n );\n\n const absolutePath = isAbsolute(file) ? file : resolve(baseDir, file);\n\n if (!result[locale as Locale]) {\n result[locale as Locale] = {};\n }\n\n result[locale as Locale][key as Dictionary['key']] = absolutePath;\n }\n\n // Ensure all declared locales are present even if the file doesn't exist yet\n // Derive the list of keys from discovered files; if no key placeholder in mask, default to 'index'\n const hasKeyInMask = maskPattern.includes('{{__KEY__}}');\n const discoveredKeys = new Set<string>();\n\n for (const locale of Object.keys(result)) {\n for (const key of Object.keys(result[locale as Locale] ?? {})) {\n discoveredKeys.add(key);\n }\n }\n\n if (!hasKeyInMask) {\n discoveredKeys.add('index');\n }\n\n // If no keys were discovered and mask expects a key, we cannot infer keys.\n // In that case, do not fabricate unknown keys.\n const keysToEnsure =\n discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];\n\n for (const locale of locales) {\n if (!result[locale]) {\n result[locale] = {} as Record<Dictionary['key'], FilePath>;\n }\n\n for (const key of keysToEnsure) {\n if (!result[locale][key as Dictionary['key']]) {\n const builtPath = builder({ key, locale });\n const absoluteBuiltPath = isAbsolute(builtPath)\n ? builtPath\n : resolve(baseDir, builtPath);\n\n result[locale][key as Dictionary['key']] = absoluteBuiltPath;\n }\n }\n }\n\n return result;\n};\n\ntype FilePath = string;\n\ntype DictionariesMap = { path: string; locale: Locale; key: string }[];\n\nconst loadMessagePathMap = (\n source: MessagesRecord | Builder,\n configuration: IntlayerConfig\n) => {\n const messages: MessagesRecord = listMessages(\n source as Builder,\n configuration\n );\n\n const dictionariesPathMap: DictionariesMap = Object.entries(messages).flatMap(\n ([locale, keysRecord]) =>\n Object.entries(keysRecord).map(([key, path]) => {\n const absolutePath = isAbsolute(path)\n ? path\n : resolve(configuration.content.baseDir, path);\n\n return {\n path: absolutePath,\n locale,\n key,\n } as DictionariesMap[number];\n })\n );\n\n return dictionariesPathMap;\n};\n\ntype SyncJSONPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * ```ts\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * })\n * ```\n */\n source: Builder;\n\n /**\n * Because Intlayer transform the JSON files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * ```ts\n * const config ={\n * plugins: [\n * syncJSON({\n * source: ({ key, locale }) => `./resources/${locale}/${key}.json`\n * location: 'plugin-i18next',\n * }),\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * location: 'plugin-next-intl',\n * }),\n * ]\n * }\n * ```\n */\n location?: string;\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is -1. (.content file priority is 0)\n *\n */\n priority?: number;\n\n /**\n * The format of the dictionaries created by the plugin.\n *\n * Default: 'intlayer'\n *\n * The format of the dictionaries created by the plugin.\n */\n format?: DictionaryFormat;\n};\n\nexport const syncJSON = (options: SyncJSONPluginOptions): Plugin => {\n const { location, priority, format } = {\n location: 'plugin',\n priority: 0,\n ...options,\n };\n\n return {\n name: 'sync-json',\n\n loadDictionaries: async ({ configuration }) => {\n const dictionariesMap: DictionariesMap = loadMessagePathMap(\n options.source,\n configuration\n );\n\n let fill: string = options.source({\n key: '{{key}}',\n locale: '{{locale}}',\n });\n\n if (fill && !isAbsolute(fill)) {\n fill = join(configuration.content.baseDir, fill);\n }\n\n const dictionaries: Dictionary[] = [];\n\n for (const { locale, path, key } of dictionariesMap) {\n const requireFunction =\n configuration.build?.require ?? getProjectRequire();\n let json: JSONContent = {};\n try {\n json = requireFunction(path as string);\n } catch {\n // File does not exist yet; default to empty content so it can be filled later\n json = {};\n }\n\n const filePath = relative(configuration.content.baseDir, path);\n\n const dictionary: Dictionary = {\n key,\n locale,\n fill,\n format,\n localId: `${key}::${location}::${filePath}` as LocalDictionaryId,\n location: location as Dictionary['location'],\n filled:\n locale !== configuration.internationalization.defaultLocale\n ? true\n : undefined,\n content: json,\n filePath,\n priority,\n };\n\n dictionaries.push(dictionary);\n }\n\n return dictionaries;\n },\n\n formatOutput: ({ dictionary }) => {\n if (!dictionary.filePath || !dictionary.locale) return dictionary;\n\n const builderPath = options.source({\n key: dictionary.key,\n locale: dictionary.locale,\n });\n\n // It's not one of the JSON that we synchronize, don't modify it\n if (resolve(builderPath) !== resolve(dictionary.filePath)) {\n return dictionary;\n }\n\n return dictionary.content;\n },\n afterBuild: async ({ dictionaries, configuration }) => {\n // Dynamic import to avoid circular dependency as core package import config, that load esbuild, that load the config file, that load the plugin\n const { getPerLocaleDictionary } = await import('@intlayer/core');\n const { parallelize } = await import('@intlayer/chokidar');\n\n const locales = configuration.internationalization.locales;\n\n type RecordList = {\n key: string;\n dictionary: Dictionary;\n locale: Locale;\n };\n\n const recordList: RecordList[] = Object.entries(\n dictionaries.mergedDictionaries\n ).flatMap(([key, dictionary]) =>\n locales.map((locale) => ({\n key,\n dictionary: dictionary.dictionary as Dictionary,\n locale,\n }))\n );\n\n await parallelize(recordList, async ({ key, dictionary, locale }) => {\n const builderPath = options.source({\n key,\n locale,\n });\n\n const localizedDictionary = getPerLocaleDictionary(dictionary, locale);\n\n // Restore the original format from plugin options for output formatting\n const dictionaryWithFormat = {\n ...localizedDictionary,\n format,\n };\n\n const formattedOutput = formatDictionaryOutput(dictionaryWithFormat);\n\n // Remove function, Symbol, etc. as it can be written as JSON\n const content = JSON.parse(JSON.stringify(formattedOutput.content));\n\n if (\n typeof content === 'undefined' ||\n (typeof content === 'object' &&\n Object.keys(content as Record<string, unknown>).length === 0)\n ) {\n return;\n }\n\n // Ensure directory exists before writing the file\n await mkdir(dirname(builderPath), { recursive: true });\n\n const stringContent = JSON.stringify(content, null, 2);\n\n await writeFile(\n builderPath,\n `${stringContent}\\n`, // Add a new line at the end of the file to avoid formatting issues with VSCode\n 'utf-8'\n );\n });\n },\n };\n};\n"],"mappings":";;;;;;;AA2BA,MAAM,eAAe,QAAgB,IAAI,QAAQ,uBAAuB,OAAO;AAE/E,MAAa,+BACX,UACA,aACA,SACA,kBACG;CACH,MAAM,iBAAiB;CACvB,MAAM,oBAAoB;CAE1B,MAAM,cAAc,YAAY,YAAY;CAC5C,MAAM,qBAAqB,QAAQ,KAAK,IAAI;CAG5C,IAAI,WAAW,IAAI,YAAY;AAE/B,YAAW,SAAS,QAClB,YAAY,kBAAkB,EAC9B,aAAa,mBAAmB,GACjC;AAED,KAAI,YAAY,SAAS,eAAe,CACtC,YAAW,SAAS,QAAQ,YAAY,eAAe,EAAE,gBAAgB;CAK3E,MAAM,QAFY,IAAI,OAAO,SAAS,CAEd,KAAK,S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I;KACvB;KACV,QACE,WAAW,cAAc,qBAAqB,gBAC1C,OACA;KACN,SAAS;KACT;KACA;KACD;AAED,iBAAa,KAAK,WAAW;;AAG/B,UAAO;;EAGT,eAAe,EAAE,iBAAiB;AAChC,OAAI,CAAC,WAAW,YAAY,CAAC,WAAW,OAAQ,QAAO;AAQvD,OAAI,QANgB,QAAQ,OAAO;IACjC,KAAK,WAAW;IAChB,QAAQ,WAAW;IACpB,CAAC,CAGsB,KAAK,QAAQ,WAAW,SAAS,CACvD,QAAO;AAGT,UAAO,WAAW;;EAEpB,YAAY,OAAO,EAAE,cAAc,oBAAoB;GAErD,MAAM,EAAE,2BAA2B,MAAM,OAAO;GAChD,MAAM,EAAE,gBAAgB,MAAM,OAAO;GAErC,MAAM,UAAU,cAAc,qBAAqB;AAkBnD,SAAM,YAV2B,OAAO,QACtC,aAAa,mBACd,CAAC,SAAS,CAAC,KAAK,gBACf,QAAQ,KAAK,YAAY;IACvB;IACA,YAAY,WAAW;IACvB;IACD,EAAE,CACJ,EAE6B,OAAO,EAAE,KAAK,YAAY,aAAa;IACnE,MAAM,cAAc,QAAQ,OAAO;KACjC;KACA;KACD,CAAC;IAUF,MAAM,kBAAkB,uBALK;KAC3B,GAJ0B,uBAAuB,YAAY,OAAO;KAKpE;KACD,CAEmE;IAGpE,MAAM,UAAU,KAAK,MAAM,KAAK,UAAU,gBAAgB,QAAQ,CAAC;AAEnE,QACE,OAAO,YAAY,eAClB,OAAO,YAAY,YAClB,OAAO,KAAK,QAAmC,CAAC,WAAW,EAE7D;AAIF,UAAM,MAAM,QAAQ,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAItD,UAAM,UACJ,aACA,GAJoB,KAAK,UAAU,SAAS,MAAM,EAAE,CAInC,KACjB,QACD;KACD;;EAEL"}
|
|
1
|
+
{"version":3,"file":"syncJSON.mjs","names":["result: MessagesRecord","messages: MessagesRecord","dictionariesMap: DictionariesMap","fill: string","dictionaries: Dictionary[]","json: JSONContent","dictionary: Dictionary"],"sources":["../../src/syncJSON.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { formatDictionaryOutput } from '@intlayer/chokidar';\nimport { getProjectRequire } from '@intlayer/config';\nimport type {\n Dictionary,\n DictionaryFormat,\n IntlayerConfig,\n LocalDictionaryId,\n Locale,\n LocalesValues,\n Plugin,\n} from '@intlayer/types';\nimport fg from 'fast-glob';\n\ntype JSONContent = Record<string, any>;\n\ntype Builder = ({\n key,\n locale,\n}: {\n key: string;\n locale: LocalesValues | (string & {});\n}) => string;\n\ntype MessagesRecord = Record<Locale, Record<Dictionary['key'], FilePath>>;\n\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const extractKeyAndLocaleFromPath = (\n filePath: string,\n maskPattern: string,\n locales: Locale[],\n defaultLocale: Locale\n): { key: string; locale: Locale } | null => {\n const keyPlaceholder = '{{__KEY__}}';\n const localePlaceholder = '{{__LOCALE__}}';\n\n const escapedMask = escapeRegex(maskPattern);\n const localesAlternation = locales.join('|');\n\n // Build a regex from the mask to capture locale (and key if present)\n let regexStr = `^${escapedMask}$`;\n\n regexStr = regexStr.replace(\n escapeRegex(localePlaceholder),\n `(?<locale>${localesAlternation})`\n );\n\n if (maskPattern.includes(keyPlaceholder)) {\n // Ensure key does not contain slashes to prevent matching across directories\n regexStr = regexStr.replace(escapeRegex(keyPlaceholder), '(?<key>[^/]+)');\n }\n\n const maskRegex = new RegExp(regexStr);\n const match = maskRegex.exec(filePath);\n\n // FIX: If the path doesn't strictly match the pattern, return null\n // Do not fall back to 'index' or defaultLocale for unmatched files.\n if (!match || !match.groups) {\n return null;\n }\n\n let locale = match.groups.locale as Locale | undefined;\n let key = (match.groups.key as string | undefined) ?? 'index';\n\n if (typeof key === 'undefined') {\n key = 'index';\n }\n\n if (typeof locale === 'undefined') {\n locale = defaultLocale;\n }\n\n return {\n key,\n locale,\n };\n};\n\nconst listMessages = (\n builder: Builder,\n configuration: IntlayerConfig\n): MessagesRecord => {\n const { content, internationalization } = configuration;\n\n const baseDir = content.baseDir;\n const locales = internationalization.locales;\n const defaultLocale = internationalization.defaultLocale;\n\n const localePattern = `{${locales.map((locale) => locale).join(',')}}`;\n\n const globPattern = builder({ key: '*', locale: localePattern });\n const maskPattern = builder({ key: '{{__KEY__}}', locale: '{{__LOCALE__}}' });\n\n const files = fg.sync(globPattern, {\n cwd: baseDir,\n });\n\n const result: MessagesRecord = {} as MessagesRecord;\n\n for (const file of files) {\n const extraction = extractKeyAndLocaleFromPath(\n file,\n maskPattern,\n locales,\n defaultLocale\n );\n\n // FIX: If extraction failed (regex mismatch), skip this file\n if (!extraction) {\n continue;\n }\n\n const { key, locale } = extraction;\n\n // FIX: Round Trip Check\n // 1. Generate what the path SHOULD be for this key/locale using the current builder\n const expectedPath = builder({ key, locale });\n\n // 2. Resolve both to absolute paths to ensure safe comparison\n const absoluteFoundPath = isAbsolute(file) ? file : resolve(baseDir, file);\n const absoluteExpectedPath = isAbsolute(expectedPath)\n ? expectedPath\n : resolve(baseDir, expectedPath);\n\n // 3. If the file found doesn't exactly match the file expected, it belongs to another plugin/structure\n if (absoluteFoundPath !== absoluteExpectedPath) {\n continue;\n }\n\n if (!result[locale as Locale]) {\n result[locale as Locale] = {};\n }\n\n result[locale as Locale][key as Dictionary['key']] = absoluteFoundPath;\n }\n\n // Ensure all declared locales are present even if the file doesn't exist yet\n const hasKeyInMask = maskPattern.includes('{{__KEY__}}');\n const discoveredKeys = new Set<string>();\n\n for (const locale of Object.keys(result)) {\n for (const key of Object.keys(result[locale as Locale] ?? {})) {\n discoveredKeys.add(key);\n }\n }\n\n if (!hasKeyInMask) {\n discoveredKeys.add('index');\n }\n\n const keysToEnsure =\n discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];\n\n for (const locale of locales) {\n if (!result[locale]) {\n result[locale] = {} as Record<Dictionary['key'], FilePath>;\n }\n\n for (const key of keysToEnsure) {\n if (!result[locale][key as Dictionary['key']]) {\n const builtPath = builder({ key, locale });\n const absoluteBuiltPath = isAbsolute(builtPath)\n ? builtPath\n : resolve(baseDir, builtPath);\n\n result[locale][key as Dictionary['key']] = absoluteBuiltPath;\n }\n }\n }\n\n return result;\n};\n\ntype FilePath = string;\n\ntype DictionariesMap = { path: string; locale: Locale; key: string }[];\n\nconst loadMessagePathMap = (\n source: MessagesRecord | Builder,\n configuration: IntlayerConfig\n) => {\n const messages: MessagesRecord = listMessages(\n source as Builder,\n configuration\n );\n\n const dictionariesPathMap: DictionariesMap = Object.entries(messages).flatMap(\n ([locale, keysRecord]) =>\n Object.entries(keysRecord).map(([key, path]) => {\n const absolutePath = isAbsolute(path)\n ? path\n : resolve(configuration.content.baseDir, path);\n\n return {\n path: absolutePath,\n locale,\n key,\n } as DictionariesMap[number];\n })\n );\n\n return dictionariesPathMap;\n};\n\ntype SyncJSONPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * ```ts\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * })\n * ```\n */\n source: Builder;\n\n /**\n * Because Intlayer transform the JSON files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * ```ts\n * const config ={\n * plugins: [\n * syncJSON({\n * source: ({ key, locale }) => `./resources/${locale}/${key}.json`\n * location: 'plugin-i18next',\n * }),\n * syncJSON({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.json`\n * location: 'plugin-next-intl',\n * }),\n * ]\n * }\n * ```\n */\n location?: string;\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is -1. (.content file priority is 0)\n *\n */\n priority?: number;\n\n /**\n * The format of the dictionaries created by the plugin.\n *\n * Default: 'intlayer'\n *\n * The format of the dictionaries created by the plugin.\n */\n format?: DictionaryFormat;\n};\n\nexport const syncJSON = (options: SyncJSONPluginOptions): Plugin => {\n // Generate a unique default location based on the source pattern.\n // This ensures that if you have multiple plugins, they don't share the same 'plugin' ID.\n const patternMarker = options.source({\n key: '{{key}}',\n locale: '{{locale}}',\n });\n const defaultLocation = `sync-json::${patternMarker}`;\n\n const { location, priority, format } = {\n location: defaultLocation,\n priority: 0,\n ...options,\n };\n\n return {\n name: 'sync-json',\n\n loadDictionaries: async ({ configuration }) => {\n const dictionariesMap: DictionariesMap = loadMessagePathMap(\n options.source,\n configuration\n );\n\n let fill: string = options.source({\n key: '{{key}}',\n locale: '{{locale}}',\n });\n\n if (fill && !isAbsolute(fill)) {\n fill = join(configuration.content.baseDir, fill);\n }\n\n const dictionaries: Dictionary[] = [];\n\n for (const { locale, path, key } of dictionariesMap) {\n const requireFunction =\n configuration.build?.require ?? getProjectRequire();\n let json: JSONContent = {};\n try {\n json = requireFunction(path as string);\n } catch {\n json = {};\n }\n\n const filePath = relative(configuration.content.baseDir, path);\n\n const dictionary: Dictionary = {\n key,\n locale,\n fill,\n format,\n localId: `${key}::${location}::${filePath}` as LocalDictionaryId,\n location: location as Dictionary['location'],\n filled:\n locale !== configuration.internationalization.defaultLocale\n ? true\n : undefined,\n content: json,\n filePath,\n priority,\n };\n\n dictionaries.push(dictionary);\n }\n\n return dictionaries;\n },\n\n formatOutput: ({ dictionary }) => {\n if (!dictionary.filePath || !dictionary.locale) return dictionary;\n\n const builderPath = options.source({\n key: dictionary.key,\n locale: dictionary.locale,\n });\n\n // Verification to ensure we are formatting the correct file\n if (resolve(builderPath) !== resolve(dictionary.filePath)) {\n return dictionary;\n }\n\n const dictionaryWithFormat = {\n ...dictionary,\n format,\n };\n\n const formattedOutput = formatDictionaryOutput(\n dictionaryWithFormat as Dictionary\n );\n\n return formattedOutput.content;\n },\n\n afterBuild: async ({ dictionaries, configuration }) => {\n const { getPerLocaleDictionary } = await import('@intlayer/core');\n const { parallelize } = await import('@intlayer/chokidar');\n\n const locales = configuration.internationalization.locales;\n\n type RecordList = {\n key: string;\n dictionary: Dictionary;\n locale: Locale;\n };\n\n // We get all dictionaries, but we need to filter them\n const recordList: RecordList[] = Object.entries(\n dictionaries.mergedDictionaries\n ).flatMap(([key, dictionary]) =>\n locales.map((locale) => ({\n key,\n dictionary: dictionary.dictionary as Dictionary,\n locale,\n }))\n );\n\n await parallelize(recordList, async ({ key, dictionary, locale }) => {\n // Only process dictionaries that belong to THIS plugin instance.\n if (dictionary.location !== location) {\n return;\n }\n\n const builderPath = options.source({\n key,\n locale,\n });\n\n const localizedDictionary = getPerLocaleDictionary(dictionary, locale);\n\n const dictionaryWithFormat = {\n ...localizedDictionary,\n format,\n };\n\n const formattedOutput = formatDictionaryOutput(dictionaryWithFormat);\n\n const content = JSON.parse(JSON.stringify(formattedOutput.content));\n\n if (\n typeof content === 'undefined' ||\n (typeof content === 'object' &&\n Object.keys(content as Record<string, unknown>).length === 0)\n ) {\n return;\n }\n\n await mkdir(dirname(builderPath), { recursive: true });\n\n const stringContent = JSON.stringify(content, null, 2);\n\n await writeFile(builderPath, `${stringContent}\\n`, 'utf-8');\n });\n },\n };\n};\n"],"mappings":";;;;;;;AA2BA,MAAM,eAAe,QAAgB,IAAI,QAAQ,uBAAuB,OAAO;AAE/E,MAAa,+BACX,UACA,aACA,SACA,kBAC2C;CAC3C,MAAM,iBAAiB;CACvB,MAAM,oBAAoB;CAE1B,MAAM,cAAc,YAAY,YAAY;CAC5C,MAAM,qBAAqB,QAAQ,KAAK,IAAI;CAG5C,IAAI,WAAW,IAAI,YAAY;AAE/B,YAAW,SAAS,QAClB,YAAY,kBAAkB,EAC9B,aAAa,mBAAmB,GACjC;AAED,KAAI,YAAY,SAAS,eAAe,CAEtC,YAAW,SAAS,QAAQ,YAAY,eAAe,EAAE,gBAAgB;CAI3E,MAAM,QADY,IAAI,OAAO,SAAS,CACd,KAAK,SAAS;AAItC,KAAI,CAAC,SAAS,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AAM,MAAM,QAAQ,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAItD,UAAM,UAAU,aAAa,GAFP,KAAK,UAAU,SAAS,MAAM,EAAE,CAER,KAAK,QAAQ;KAC3D;;EAEL"}
|
package/dist/types/syncJSON.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ type Builder = ({
|
|
|
11
11
|
declare const extractKeyAndLocaleFromPath: (filePath: string, maskPattern: string, locales: Locale[], defaultLocale: Locale) => {
|
|
12
12
|
key: string;
|
|
13
13
|
locale: Locale;
|
|
14
|
-
};
|
|
14
|
+
} | null;
|
|
15
15
|
type SyncJSONPluginOptions = {
|
|
16
16
|
/**
|
|
17
17
|
* The source of the plugin.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncJSON.d.ts","names":[],"sources":["../../src/syncJSON.ts"],"sourcesContent":[],"mappings":";;;KAiBK,OAAA;;;;;EAAA,MAAA,EAKK,aALE,GAAA,CAAA,MAAA,GAAA,CAAA,CAAA,CAAA;CACV,EAAA,GAAA,MAAA;AACA,cAUW,2BAVX,EAAA,CAAA,QAAA,EAAA,MAAA,EAAA,WAAA,EAAA,MAAA,EAAA,OAAA,EAaS,MAbT,EAAA,EAAA,aAAA,EAce,MAdf,EAAA,GAAA;EAGQ,GAAA,EAAA,MAAA;EAAa,MAAA,
|
|
1
|
+
{"version":3,"file":"syncJSON.d.ts","names":[],"sources":["../../src/syncJSON.ts"],"sourcesContent":[],"mappings":";;;KAiBK,OAAA;;;;;EAAA,MAAA,EAKK,aALE,GAAA,CAAA,MAAA,GAAA,CAAA,CAAA,CAAA;CACV,EAAA,GAAA,MAAA;AACA,cAUW,2BAVX,EAAA,CAAA,QAAA,EAAA,MAAA,EAAA,WAAA,EAAA,MAAA,EAAA,OAAA,EAaS,MAbT,EAAA,EAAA,aAAA,EAce,MAdf,EAAA,GAAA;EAGQ,GAAA,EAAA,MAAA;EAAa,MAAA,EAYG,MAZH;AAOvB,CAAA,GAAa,IAAA;KAiLR,qBAAA,GA9KM;EACM;;;AA6Cf;AAwLF;;;;;;UA7CU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WA0CC;;cAGE,oBAAqB,0BAAwB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/sync-json-plugin",
|
|
3
|
-
"version": "7.5.
|
|
3
|
+
"version": "7.5.11",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A plugin for Intlayer that syncs JSON files to dictionaries.",
|
|
6
6
|
"keywords": [
|
|
@@ -72,10 +72,10 @@
|
|
|
72
72
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@intlayer/chokidar": "7.5.
|
|
76
|
-
"@intlayer/config": "7.5.
|
|
77
|
-
"@intlayer/core": "7.5.
|
|
78
|
-
"@intlayer/types": "7.5.
|
|
75
|
+
"@intlayer/chokidar": "7.5.11",
|
|
76
|
+
"@intlayer/config": "7.5.11",
|
|
77
|
+
"@intlayer/core": "7.5.11",
|
|
78
|
+
"@intlayer/types": "7.5.11",
|
|
79
79
|
"fast-glob": "3.3.3"
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|