@intlayer/chokidar 8.4.8 → 8.4.10

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 (36) hide show
  1. package/dist/cjs/build.cjs +2 -0
  2. package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +2 -2
  3. package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
  4. package/dist/cjs/cleanRemovedContentDeclaration.cjs +3 -4
  5. package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
  6. package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +1 -7
  7. package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
  8. package/dist/cjs/init/index.cjs +24 -18
  9. package/dist/cjs/init/index.cjs.map +1 -1
  10. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +1 -1
  11. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
  12. package/dist/cjs/utils/readDictionariesFromDisk.cjs +25 -0
  13. package/dist/cjs/utils/readDictionariesFromDisk.cjs.map +1 -0
  14. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +2 -2
  15. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  16. package/dist/esm/build.mjs +2 -1
  17. package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs +2 -2
  18. package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs.map +1 -1
  19. package/dist/esm/cleanRemovedContentDeclaration.mjs +3 -4
  20. package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
  21. package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs +1 -7
  22. package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs.map +1 -1
  23. package/dist/esm/init/index.mjs +24 -18
  24. package/dist/esm/init/index.mjs.map +1 -1
  25. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +1 -1
  26. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
  27. package/dist/esm/utils/readDictionariesFromDisk.mjs +23 -0
  28. package/dist/esm/utils/readDictionariesFromDisk.mjs.map +1 -0
  29. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +2 -2
  30. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  31. package/dist/types/build.d.ts +2 -1
  32. package/dist/types/cleanRemovedContentDeclaration.d.ts.map +1 -1
  33. package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts.map +1 -1
  34. package/dist/types/utils/readDictionariesFromDisk.d.ts +9 -0
  35. package/dist/types/utils/readDictionariesFromDisk.d.ts.map +1 -0
  36. package/package.json +10 -10
@@ -6,6 +6,7 @@ const require_createDictionaryEntryPoint_getBuiltFetchDictionariesPath = require
6
6
  const require_createDictionaryEntryPoint_getBuiltRemoteDictionariesPath = require('./createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs');
7
7
  const require_createDictionaryEntryPoint_getBuiltUnmergedDictionariesPath = require('./createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs');
8
8
  const require_createDictionaryEntryPoint_createDictionaryEntryPoint = require('./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs');
9
+ const require_utils_readDictionariesFromDisk = require('./utils/readDictionariesFromDisk.cjs');
9
10
  const require_buildIntlayerDictionary_buildIntlayerDictionary = require('./buildIntlayerDictionary/buildIntlayerDictionary.cjs');
10
11
  const require_createType_createModuleAugmentation = require('./createType/createModuleAugmentation.cjs');
11
12
  const require_createType_createType = require('./createType/createType.cjs');
@@ -52,6 +53,7 @@ exports.loadLocalDictionaries = require_loadDictionaries_loadLocalDictionaries.l
52
53
  exports.loadRemoteDictionaries = require_loadDictionaries_loadRemoteDictionaries.loadRemoteDictionaries;
53
54
  exports.prepareIntlayer = require_prepareIntlayer.prepareIntlayer;
54
55
  exports.processContentDeclaration = require_buildIntlayerDictionary_processContentDeclaration.processContentDeclaration;
56
+ exports.readDictionariesFromDisk = require_utils_readDictionariesFromDisk.readDictionariesFromDisk;
55
57
  exports.transformJSFile = require_writeContentDeclaration_transformJSFile.transformJSFile;
56
58
  exports.writeConfiguration = require_writeConfiguration_index.writeConfiguration;
57
59
  exports.writeContentDeclaration = require_writeContentDeclaration_writeContentDeclaration.writeContentDeclaration;
@@ -1,10 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ const require_utils_readDictionariesFromDisk = require('../utils/readDictionariesFromDisk.cjs');
3
4
  const require_buildIntlayerDictionary_writeDynamicDictionary = require('./writeDynamicDictionary.cjs');
4
5
  const require_buildIntlayerDictionary_writeFetchDictionary = require('./writeFetchDictionary.cjs');
5
6
  const require_buildIntlayerDictionary_writeMergedDictionary = require('./writeMergedDictionary.cjs');
6
7
  const require_buildIntlayerDictionary_writeUnmergedDictionary = require('./writeUnmergedDictionary.cjs');
7
- let _intlayer_unmerged_dictionaries_entry = require("@intlayer/unmerged-dictionaries-entry");
8
8
  let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
9
9
 
10
10
  //#region src/buildIntlayerDictionary/buildIntlayerDictionary.ts
@@ -24,7 +24,7 @@ const buildDictionary = async (localDictionariesEntries, configuration, options)
24
24
  };
25
25
  const unmergedDictionariesToUpdate = [...localDictionariesEntries];
26
26
  if (importOtherDictionaries) {
27
- const prevUnmergedDictionaries = (0, _intlayer_unmerged_dictionaries_entry.getUnmergedDictionaries)(configuration);
27
+ const prevUnmergedDictionaries = require_utils_readDictionariesFromDisk.readDictionariesFromDisk(configuration.system.unmergedDictionariesDir);
28
28
  for (const dictionaryToWrite of localDictionariesEntries) {
29
29
  const allPrebuiltUnmergedDictionaries = prevUnmergedDictionaries[dictionaryToWrite.key];
30
30
  if (allPrebuiltUnmergedDictionaries?.length > 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"buildIntlayerDictionary.cjs","names":["OUTPUT_FORMAT","IMPORT_MODE","writeUnmergedDictionaries","writeMergedDictionaries","writeDynamicDictionary","writeFetchDictionary"],"sources":["../../../src/buildIntlayerDictionary/buildIntlayerDictionary.ts"],"sourcesContent":["import { IMPORT_MODE, OUTPUT_FORMAT } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport {\n type LocalizedDictionaryOutput,\n writeDynamicDictionary,\n} from './writeDynamicDictionary';\nimport { writeFetchDictionary } from './writeFetchDictionary';\nimport { writeMergedDictionaries } from './writeMergedDictionary';\nimport { writeUnmergedDictionaries } from './writeUnmergedDictionary';\n\nexport type BuildDictionariesOptions = Partial<{\n formats: typeof OUTPUT_FORMAT;\n importOtherDictionaries: boolean;\n env: 'prod' | 'dev';\n}>;\n\nconst defaultOptions = {\n formats: OUTPUT_FORMAT,\n importOtherDictionaries: true,\n env: 'dev',\n} as const satisfies BuildDictionariesOptions;\n\n/**\n * This function transpile the bundled code to to make dictionaries as JSON files\n */\nexport const buildDictionary = async (\n localDictionariesEntries: Dictionary[],\n configuration: IntlayerConfig,\n options?: BuildDictionariesOptions\n) => {\n const importMode =\n configuration?.build?.importMode ??\n configuration?.dictionary?.importMode ??\n IMPORT_MODE;\n\n const { importOtherDictionaries, env, formats } = {\n ...defaultOptions,\n ...options,\n };\n\n const unmergedDictionariesToUpdate: Dictionary[] = [\n ...localDictionariesEntries,\n ];\n\n if (importOtherDictionaries) {\n const prevUnmergedDictionaries: Record<string, Dictionary[]> =\n getUnmergedDictionaries(configuration);\n\n // Reinsert other dictionaries with the same key to avoid merging errors\n for (const dictionaryToWrite of localDictionariesEntries) {\n const allPrebuiltUnmergedDictionaries =\n prevUnmergedDictionaries[dictionaryToWrite.key];\n\n if (allPrebuiltUnmergedDictionaries?.length > 0) {\n // Do not add the same dictionary again by filtering out the one with the same localId\n const otherUnmergedDictionaries =\n allPrebuiltUnmergedDictionaries.filter(\n (unmergedDictionary) =>\n unmergedDictionary.localId !== dictionaryToWrite.localId\n );\n\n unmergedDictionariesToUpdate.push(...otherUnmergedDictionaries);\n }\n }\n }\n\n const unmergedDictionaries = await writeUnmergedDictionaries(\n unmergedDictionariesToUpdate,\n configuration,\n env\n );\n\n const mergedDictionaries = await writeMergedDictionaries(\n unmergedDictionaries,\n configuration\n );\n\n const dictionariesToBuildDynamic: typeof mergedDictionaries = {};\n const keysToBuildFetch = new Set<string>();\n\n for (const [key, mergedResult] of Object.entries(mergedDictionaries)) {\n const dictionary = mergedResult.dictionary;\n const mode = dictionary.importMode ?? importMode;\n\n if (mode === 'dynamic' || mode === 'fetch') {\n dictionariesToBuildDynamic[key] = mergedResult;\n }\n\n if (mode === 'fetch') {\n keysToBuildFetch.add(key);\n }\n }\n\n let dynamicDictionaries: LocalizedDictionaryOutput | null = null;\n\n if (Object.keys(dictionariesToBuildDynamic).length > 0) {\n dynamicDictionaries = await writeDynamicDictionary(\n dictionariesToBuildDynamic,\n configuration,\n formats\n );\n }\n\n let fetchDictionaries: LocalizedDictionaryOutput | null = null;\n\n if (dynamicDictionaries && keysToBuildFetch.size > 0) {\n const dictionariesToBuildFetch: LocalizedDictionaryOutput = {};\n\n for (const key of keysToBuildFetch) {\n if (dynamicDictionaries[key]) {\n dictionariesToBuildFetch[key] = dynamicDictionaries[key];\n }\n }\n\n if (Object.keys(dictionariesToBuildFetch).length > 0) {\n fetchDictionaries = await writeFetchDictionary(\n dictionariesToBuildFetch,\n configuration,\n formats\n );\n }\n }\n\n return {\n unmergedDictionaries,\n mergedDictionaries,\n dynamicDictionaries,\n fetchDictionaries,\n };\n};\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,iBAAiB;CACrB,SAASA;CACT,yBAAyB;CACzB,KAAK;CACN;;;;AAKD,MAAa,kBAAkB,OAC7B,0BACA,eACA,YACG;CACH,MAAM,aACJ,e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E","readDictionariesFromDisk","writeUnmergedDictionaries","writeMergedDictionaries","writeDynamicDictionary","writeFetchDictionary"],"sources":["../../../src/buildIntlayerDictionary/buildIntlayerDictionary.ts"],"sourcesContent":["import { IMPORT_MODE, OUTPUT_FORMAT } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { readDictionariesFromDisk } from '../utils/readDictionariesFromDisk';\nimport {\n type LocalizedDictionaryOutput,\n writeDynamicDictionary,\n} from './writeDynamicDictionary';\nimport { writeFetchDictionary } from './writeFetchDictionary';\nimport { writeMergedDictionaries } from './writeMergedDictionary';\nimport { writeUnmergedDictionaries } from './writeUnmergedDictionary';\n\nexport type BuildDictionariesOptions = Partial<{\n formats: typeof OUTPUT_FORMAT;\n importOtherDictionaries: boolean;\n env: 'prod' | 'dev';\n}>;\n\nconst defaultOptions = {\n formats: OUTPUT_FORMAT,\n importOtherDictionaries: true,\n env: 'dev',\n} as const satisfies BuildDictionariesOptions;\n\n/**\n * This function transpile the bundled code to to make dictionaries as JSON files\n */\nexport const buildDictionary = async (\n localDictionariesEntries: Dictionary[],\n configuration: IntlayerConfig,\n options?: BuildDictionariesOptions\n) => {\n const importMode =\n configuration?.build?.importMode ??\n configuration?.dictionary?.importMode ??\n IMPORT_MODE;\n\n const { importOtherDictionaries, env, formats } = {\n ...defaultOptions,\n ...options,\n };\n\n const unmergedDictionariesToUpdate: Dictionary[] = [\n ...localDictionariesEntries,\n ];\n\n if (importOtherDictionaries) {\n const prevUnmergedDictionaries: Record<string, Dictionary[]> =\n readDictionariesFromDisk(configuration.system.unmergedDictionariesDir);\n\n // Reinsert other dictionaries with the same key to avoid merging errors\n for (const dictionaryToWrite of localDictionariesEntries) {\n const allPrebuiltUnmergedDictionaries =\n prevUnmergedDictionaries[dictionaryToWrite.key];\n\n if (allPrebuiltUnmergedDictionaries?.length > 0) {\n // Do not add the same dictionary again by filtering out the one with the same localId\n const otherUnmergedDictionaries =\n allPrebuiltUnmergedDictionaries.filter(\n (unmergedDictionary) =>\n unmergedDictionary.localId !== dictionaryToWrite.localId\n );\n\n unmergedDictionariesToUpdate.push(...otherUnmergedDictionaries);\n }\n }\n }\n\n const unmergedDictionaries = await writeUnmergedDictionaries(\n unmergedDictionariesToUpdate,\n configuration,\n env\n );\n\n const mergedDictionaries = await writeMergedDictionaries(\n unmergedDictionaries,\n configuration\n );\n\n const dictionariesToBuildDynamic: typeof mergedDictionaries = {};\n const keysToBuildFetch = new Set<string>();\n\n for (const [key, mergedResult] of Object.entries(mergedDictionaries)) {\n const dictionary = mergedResult.dictionary;\n const mode = dictionary.importMode ?? importMode;\n\n if (mode === 'dynamic' || mode === 'fetch') {\n dictionariesToBuildDynamic[key] = mergedResult;\n }\n\n if (mode === 'fetch') {\n keysToBuildFetch.add(key);\n }\n }\n\n let dynamicDictionaries: LocalizedDictionaryOutput | null = null;\n\n if (Object.keys(dictionariesToBuildDynamic).length > 0) {\n dynamicDictionaries = await writeDynamicDictionary(\n dictionariesToBuildDynamic,\n configuration,\n formats\n );\n }\n\n let fetchDictionaries: LocalizedDictionaryOutput | null = null;\n\n if (dynamicDictionaries && keysToBuildFetch.size > 0) {\n const dictionariesToBuildFetch: LocalizedDictionaryOutput = {};\n\n for (const key of keysToBuildFetch) {\n if (dynamicDictionaries[key]) {\n dictionariesToBuildFetch[key] = dynamicDictionaries[key];\n }\n }\n\n if (Object.keys(dictionariesToBuildFetch).length > 0) {\n fetchDictionaries = await writeFetchDictionary(\n dictionariesToBuildFetch,\n configuration,\n formats\n );\n }\n }\n\n return {\n unmergedDictionaries,\n mergedDictionaries,\n dynamicDictionaries,\n fetchDictionaries,\n };\n};\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,iBAAiB;CACrB,SAASA;CACT,yBAAyB;CACzB,KAAK;CACN;;;;AAKD,MAAa,kBAAkB,OAC7B,0BACA,eACA,YACG;CACH,MAAM,aACJ,eAAe,OAAO,cACtB,eAAe,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2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
3
  const require_createDictionaryEntryPoint_createDictionaryEntryPoint = require('./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs');
4
+ const require_utils_readDictionariesFromDisk = require('./utils/readDictionariesFromDisk.cjs');
4
5
  const require_writeJsonIfChanged = require('./writeJsonIfChanged.cjs');
5
6
  let node_fs_promises = require("node:fs/promises");
6
7
  let node_path = require("node:path");
7
8
  let _intlayer_config_client = require("@intlayer/config/client");
8
9
  let _intlayer_config_logger = require("@intlayer/config/logger");
9
- let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
10
- let _intlayer_unmerged_dictionaries_entry = require("@intlayer/unmerged-dictionaries-entry");
11
10
  let fast_glob = require("fast-glob");
12
11
  fast_glob = require_runtime.__toESM(fast_glob);
13
12
 
14
13
  //#region src/cleanRemovedContentDeclaration.ts
15
14
  const cleanRemovedContentDeclaration = async (filePath, keysToKeep, configuration) => {
16
15
  const appLogger = (0, _intlayer_config_logger.getAppLogger)(configuration);
17
- const unmergedDictionaries = (0, _intlayer_unmerged_dictionaries_entry.getUnmergedDictionaries)(configuration);
16
+ const unmergedDictionaries = require_utils_readDictionariesFromDisk.readDictionariesFromDisk(configuration.system.unmergedDictionariesDir);
18
17
  const baseDir = configuration.system.baseDir;
19
18
  const relativeFilePath = (0, node_path.relative)(baseDir, filePath);
20
19
  const uniqueUnmergedDictionaries = Object.values(unmergedDictionaries).flat().filter((dictionary) => dictionary.filePath === relativeFilePath && !keysToKeep.includes(dictionary.key)).filter((dictionary, index, self) => index === self.findIndex((t) => t.key === dictionary.key));
@@ -42,7 +41,7 @@ const cleanRemovedContentDeclaration = async (filePath, keysToKeep, configuratio
42
41
  }
43
42
  }
44
43
  }));
45
- const dictionaries = (0, _intlayer_dictionaries_entry.getDictionaries)(configuration);
44
+ const dictionaries = require_utils_readDictionariesFromDisk.readDictionariesFromDisk(configuration.system.dictionariesDir);
46
45
  const uniqueMergedDictionaries = (Object.values(dictionaries)?.filter((dictionary) => !keysToKeep.includes(dictionary.key) && dictionary.localIds?.length === 1 && dictionary.localIds[0].endsWith(`::local::${relativeFilePath}`))).filter((dictionary, index, self) => index === self.findIndex((t) => t.key === dictionary.key));
47
46
  await Promise.all(uniqueMergedDictionaries.map(async (dictionary) => {
48
47
  const mergedFilePath = (0, node_path.normalize)((0, node_path.join)(configuration.system.dictionariesDir, `${dictionary.key}.json`));
@@ -1 +1 @@
1
- {"version":3,"file":"cleanRemovedContentDeclaration.cjs","names":["writeJsonIfChanged","createDictionaryEntryPoint"],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"sourcesContent":["import { readFile, rm } from 'node:fs/promises';\nimport { join, normalize, relative } from 'node:path';\nimport { normalizePath } from '@intlayer/config/client';\nimport {\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport fg from 'fast-glob';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint';\nimport { writeJsonIfChanged } from './writeJsonIfChanged';\n\nexport const cleanRemovedContentDeclaration = async (\n filePath: string,\n keysToKeep: string[],\n configuration: IntlayerConfig\n): Promise<{\n changedDictionariesLocalIds: string[];\n excludeKeys: string[];\n hasRebuilt: boolean;\n}> => {\n const appLogger = getAppLogger(configuration);\n\n const unmergedDictionaries = getUnmergedDictionaries(configuration);\n\n const baseDir = configuration.system.baseDir;\n\n const relativeFilePath = relative(baseDir, filePath);\n const flatUnmergedDictionaries = Object.values(unmergedDictionaries).flat();\n\n const filteredUnmergedDictionaries = flatUnmergedDictionaries.filter(\n (dictionary) =>\n dictionary.filePath === relativeFilePath &&\n !keysToKeep.includes(dictionary.key)\n );\n\n // Deduplicate dictionaries by key\n const uniqueUnmergedDictionaries = filteredUnmergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n const changedDictionariesLocalIds: string[] = [];\n const filesToRemove: string[] = [];\n const excludeKeys: string[] = [];\n\n // Identify Unmerged Dictionaries to remove or clean\n await Promise.all(\n uniqueUnmergedDictionaries.map(async (dictionary) => {\n const unmergedFilePath = normalize(\n join(\n configuration.system.unmergedDictionariesDir,\n `${dictionary.key}.json`\n )\n );\n\n try {\n const jsonContent = await readFile(unmergedFilePath, 'utf8');\n const parsedContent = JSON.parse(jsonContent);\n\n if (parsedContent.length === 1) {\n if (parsedContent[0].filePath === relativeFilePath) {\n appLogger(\n `Removing outdated dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n filesToRemove.push(unmergedFilePath);\n excludeKeys.push(dictionary.key);\n }\n } else {\n const filteredContent = parsedContent.filter(\n (content: any) => content.filePath !== relativeFilePath\n );\n await writeJsonIfChanged(unmergedFilePath, filteredContent);\n changedDictionariesLocalIds.push(dictionary.localId!);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n }\n })\n );\n\n const dictionaries = getDictionaries(configuration);\n const flatDictionaries = Object.values(dictionaries) as Dictionary[];\n\n const filteredMergedDictionaries = flatDictionaries?.filter(\n (dictionary) =>\n !keysToKeep.includes(dictionary.key) &&\n dictionary.localIds?.length === 1 &&\n (dictionary.localIds[0] as string).endsWith(\n `::local::${relativeFilePath}`\n )\n );\n\n const uniqueMergedDictionaries = filteredMergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n // Identify Merged Dictionaries, Types, and Dynamic Dictionaries to remove\n await Promise.all(\n uniqueMergedDictionaries.map(async (dictionary) => {\n const mergedFilePath = normalize(\n join(configuration.system.dictionariesDir, `${dictionary.key}.json`)\n );\n\n try {\n const fileContent = await readFile(mergedFilePath, 'utf8');\n const parsedContent = JSON.parse(fileContent) as Dictionary;\n\n if (parsedContent.localIds?.length === 1) {\n if (\n parsedContent.localIds[0].endsWith(`::local::${relativeFilePath}`)\n ) {\n appLogger(\n `Removing outdated unmerged dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n\n // Mark JSON for removal\n filesToRemove.push(mergedFilePath);\n\n // Mark TS Types for removal\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n\n // Mark Dynamic Dictionaries for removal\n // We use glob to catch the loader files (.cjs, .mjs) AND the split locale files (.en.json, etc.)\n const dynamicFilesGlob = join(\n configuration.system.dynamicDictionariesDir,\n `${dictionary.key}.*`\n );\n const dynamicFiles = await fg(normalizePath(dynamicFilesGlob), {\n absolute: true,\n });\n filesToRemove.push(...dynamicFiles);\n\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n } else {\n const localIds = parsedContent.localIds?.filter(\n (localeId) => !localeId.endsWith(`::local::${relativeFilePath}`)\n ) as string[];\n const newContent = { ...parsedContent, localIds };\n await writeJsonIfChanged(mergedFilePath, newContent);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n }\n }\n })\n );\n\n // Execute Cleanup\n if (filesToRemove.length > 0 || excludeKeys.length > 0) {\n // Update entry points (indexes) first so the app doesn't import dead files\n await createDictionaryEntryPoint(configuration, { excludeKeys });\n\n // Remove the files synchronously (awaited) immediately after.\n if (filesToRemove.length > 0) {\n await Promise.all(\n filesToRemove.map(async (path) => {\n const relativePath = relative(baseDir, path);\n try {\n await rm(path, { force: true });\n\n appLogger(`Deleted artifact: ${colorizePath(relativePath)}`, {\n isVerbose: true,\n });\n } catch {\n appLogger(\n `Error while removing file ${colorizePath(relativePath)}`,\n {\n isVerbose: true,\n }\n );\n }\n })\n );\n }\n }\n\n return {\n changedDictionariesLocalIds,\n excludeKeys,\n hasRebuilt: filesToRemove.length > 0 || excludeKeys.length > 0,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;AAgBA,MAAa,iCAAiC,OAC5C,UACA,YACA,kBAKI;CACJ,MAAM,sDAAyB,cAAc;CAE7C,MAAM,0FAA+C,cAAc;CAEnE,MAAM,UAAU,cAAc,OAAO;CAErC,MAAM,2CAA4B,SAAS,SAAS;CAUpD,MAAM,6BAT2B,OAAO,OAAO,qBAAqB,CAAC,MAAM,CAEb,QAC3D,eACC,WAAW,aAAa,oBACxB,CAAC,WAAW,SAAS,WAAW,IAAI,CACvC,CAG+D,QAC7D,YAAY,OAAO,SAClB,UAAU,KAAK,WAAW,MAAM,EAAE,QAAQ,WAAW,IAAI,CAC5D;CAED,MAAM,8BAAwC,EAAE;CAChD,MAAM,gBAA0B,EAAE;CAClC,MAAM,cAAwB,EAAE;AAGhC,OAAM,QAAQ,IACZ,2BAA2B,IAAI,OAAO,eAAe;EACnD,MAAM,gEAEF,cAAc,OAAO,yBACrB,GAAG,WAAW,IAAI,OACnB,CACF;AAED,MAAI;GACF,MAAM,cAAc,qCAAe,kBAAkB,OAAO;GAC5D,MAAM,gBAAgB,KAAK,MAAM,YAAY;AAE7C,OAAI,cAAc,WAAW,GAC3B;QAAI,cAAc,GAAG,aAAa,kBAAkB;AAClD,eACE,yEAA4C,WAAW,IAAI,IAC3D,EAAE,WAAW,MAAM,CACpB;AACD,mBAAc,KAAK,iBAAiB;AACpC,iBAAY,KAAK,WAAW,IAAI;;UAE7B;AAIL,UAAMA,8CAAmB,kBAHD,cAAc,QACnC,YAAiB,QAAQ,aAAa,iBACxC,CAC0D;AAC3D,gCAA4B,KAAK,WAAW,QAAS;;WAEhD,OAAY;AACnB,OAAI,MAAM,SAAS,UACjB;QAAI,CAAC,YAAY,SAAS,WAAW,IAAI,CACvC,aAAY,KAAK,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,WAAW,IAAI;IAElC,MAAM,6DACC,cAAc,OAAO,UAAU,GAAG,WAAW,IAAI,KAAK,CAC5D;AACD,kBAAc,KAAK,cAAc;;;GAGrC,CACH;AAGD,KAAI,cAAc,SAAS,KAAK,YAAY,SAAS,GAAG;AAEtD,QAAMC,yFAA2B,eAAe,EAAE,aAAa,CAAC;AAGhE,MAAI,cAAc,SAAS,EACzB,OAAM,QAAQ,IACZ,cAAc,IAAI,OAAO,SAAS;GAChC,MAAM,uCAAwB,SAAS,KAAK;AAC5C,OAAI;AACF,mCAAS,MAAM,EAAE,OAAO,MAAM,CAAC;AAE/B,cAAU,+DAAkC,aAAa,IAAI,EAC3D,WAAW,MACZ,CAAC;WACI;AACN,cACE,uEAA0C,aAAa,IACvD,EACE,WAAW,MACZ,CACF;;IAEH,CACH;;AAIL,QAAO;EACL;EACA;EACA,YAAY,cAAc,SAAS,KAAK,YAAY,SAAS;EAC9D"}
1
+ {"version":3,"file":"cleanRemovedContentDeclaration.cjs","names":["readDictionariesFromDisk","writeJsonIfChanged","createDictionaryEntryPoint"],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"sourcesContent":["import { readFile, rm } from 'node:fs/promises';\nimport { join, normalize, relative } from 'node:path';\nimport { normalizePath } from '@intlayer/config/client';\nimport {\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport fg from 'fast-glob';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint';\nimport { readDictionariesFromDisk } from './utils/readDictionariesFromDisk';\nimport { writeJsonIfChanged } from './writeJsonIfChanged';\n\nexport const cleanRemovedContentDeclaration = async (\n filePath: string,\n keysToKeep: string[],\n configuration: IntlayerConfig\n): Promise<{\n changedDictionariesLocalIds: string[];\n excludeKeys: string[];\n hasRebuilt: boolean;\n}> => {\n const appLogger = getAppLogger(configuration);\n\n const unmergedDictionaries = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n\n const baseDir = configuration.system.baseDir;\n\n const relativeFilePath = relative(baseDir, filePath);\n const flatUnmergedDictionaries = Object.values(unmergedDictionaries).flat();\n\n const filteredUnmergedDictionaries = flatUnmergedDictionaries.filter(\n (dictionary) =>\n dictionary.filePath === relativeFilePath &&\n !keysToKeep.includes(dictionary.key)\n );\n\n // Deduplicate dictionaries by key\n const uniqueUnmergedDictionaries = filteredUnmergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n const changedDictionariesLocalIds: string[] = [];\n const filesToRemove: string[] = [];\n const excludeKeys: string[] = [];\n\n // Identify Unmerged Dictionaries to remove or clean\n await Promise.all(\n uniqueUnmergedDictionaries.map(async (dictionary) => {\n const unmergedFilePath = normalize(\n join(\n configuration.system.unmergedDictionariesDir,\n `${dictionary.key}.json`\n )\n );\n\n try {\n const jsonContent = await readFile(unmergedFilePath, 'utf8');\n const parsedContent = JSON.parse(jsonContent);\n\n if (parsedContent.length === 1) {\n if (parsedContent[0].filePath === relativeFilePath) {\n appLogger(\n `Removing outdated dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n filesToRemove.push(unmergedFilePath);\n excludeKeys.push(dictionary.key);\n }\n } else {\n const filteredContent = parsedContent.filter(\n (content: any) => content.filePath !== relativeFilePath\n );\n await writeJsonIfChanged(unmergedFilePath, filteredContent);\n changedDictionariesLocalIds.push(dictionary.localId!);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n }\n })\n );\n\n const dictionaries = readDictionariesFromDisk<Record<string, Dictionary>>(\n configuration.system.dictionariesDir\n );\n const flatDictionaries = Object.values(dictionaries) as Dictionary[];\n\n const filteredMergedDictionaries = flatDictionaries?.filter(\n (dictionary) =>\n !keysToKeep.includes(dictionary.key) &&\n dictionary.localIds?.length === 1 &&\n (dictionary.localIds[0] as string).endsWith(\n `::local::${relativeFilePath}`\n )\n );\n\n const uniqueMergedDictionaries = filteredMergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n // Identify Merged Dictionaries, Types, and Dynamic Dictionaries to remove\n await Promise.all(\n uniqueMergedDictionaries.map(async (dictionary) => {\n const mergedFilePath = normalize(\n join(configuration.system.dictionariesDir, `${dictionary.key}.json`)\n );\n\n try {\n const fileContent = await readFile(mergedFilePath, 'utf8');\n const parsedContent = JSON.parse(fileContent) as Dictionary;\n\n if (parsedContent.localIds?.length === 1) {\n if (\n parsedContent.localIds[0].endsWith(`::local::${relativeFilePath}`)\n ) {\n appLogger(\n `Removing outdated unmerged dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n\n // Mark JSON for removal\n filesToRemove.push(mergedFilePath);\n\n // Mark TS Types for removal\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n\n // Mark Dynamic Dictionaries for removal\n // We use glob to catch the loader files (.cjs, .mjs) AND the split locale files (.en.json, etc.)\n const dynamicFilesGlob = join(\n configuration.system.dynamicDictionariesDir,\n `${dictionary.key}.*`\n );\n const dynamicFiles = await fg(normalizePath(dynamicFilesGlob), {\n absolute: true,\n });\n filesToRemove.push(...dynamicFiles);\n\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n } else {\n const localIds = parsedContent.localIds?.filter(\n (localeId) => !localeId.endsWith(`::local::${relativeFilePath}`)\n ) as string[];\n const newContent = { ...parsedContent, localIds };\n await writeJsonIfChanged(mergedFilePath, newContent);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n }\n }\n })\n );\n\n // Execute Cleanup\n if (filesToRemove.length > 0 || excludeKeys.length > 0) {\n // Update entry points (indexes) first so the app doesn't import dead files\n await createDictionaryEntryPoint(configuration, { excludeKeys });\n\n // Remove the files synchronously (awaited) immediately after.\n if (filesToRemove.length > 0) {\n await Promise.all(\n filesToRemove.map(async (path) => {\n const relativePath = relative(baseDir, path);\n try {\n await rm(path, { force: true });\n\n appLogger(`Deleted artifact: ${colorizePath(relativePath)}`, {\n isVerbose: true,\n });\n } catch {\n appLogger(\n `Error while removing file ${colorizePath(relativePath)}`,\n {\n isVerbose: true,\n }\n );\n }\n })\n );\n }\n }\n\n return {\n changedDictionariesLocalIds,\n excludeKeys,\n hasRebuilt: filesToRemove.length > 0 || excludeKeys.length > 0,\n };\n};\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAa,iCAAiC,OAC5C,UACA,YACA,kBAKI;CACJ,MAAM,sDAAyB,cAAc;CAE7C,MAAM,uBAAuBA,gEAE3B,cAAc,OAAO,wBAAwB;CAE/C,MAAM,UAAU,cAAc,OAAO;CAErC,MAAM,2CAA4B,SAAS,SAAS;CAUpD,MAAM,6BAT2B,OAAO,OAAO,qBAAqB,CAAC,MAAM,CAEb,QAC3D,eACC,WAAW,aAAa,oBACxB,CAAC,WAAW,SAAS,WAAW,IAAI,CACvC,CAG+D,QAC7D,YAAY,OAAO,SAClB,UAAU,KAAK,WAAW,MAAM,EAAE,QAAQ,WAAW,IAAI,CAC5D;CAED,MAAM,8BAAwC,EAAE;CAChD,MAAM,gBAA0B,EAAE;CAClC,MAAM,cAAwB,EAAE;AAGhC,OAAM,QAAQ,IACZ,2BAA2B,IAAI,OAAO,eAAe;EACnD,MAAM,gEAEF,cAAc,OAAO,yBACrB,GAAG,WAAW,IAAI,OACnB,CACF;AAED,MAAI;GACF,MAAM,cAAc,qCAAe,kBAAkB,OAAO;GAC5D,MAAM,gBAAgB,KAAK,MAAM,YAAY;AAE7C,OAAI,cAAc,WAAW,GAC3B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CAC4D,EAAE,EAC7D,UAAU,MACX,CAAC;AACF,mBAAc,KAAK,GAAG,aAAa;AAEnC,SAAI,CAAC,YAAY,SAAS,WAAW,IAAI,CACvC,aAAY,KAAK,WAAW,IAAI;;UAG/B;IACL,MAAM,WAAW,cAAc,UAAU,QACtC,aAAa,CAAC,SAAS,SAAS,YAAY,mBAAmB,CACjE;AAED,UAAMC,8CAAmB,gBADN;KAAE,GAAG;KAAe;KAAU,CACG;;WAE/C,OAAY;AACnB,OAAI,MAAM,SAAS,UAAU;AAC3B,QAAI,CAAC,YAAY,SAAS,WAAW,IAAI,CACvC,aAAY,KAAK,WAAW,IAAI;IAElC,MAAM,6DACC,cAAc,OAAO,UAAU,GAAG,WAAW,IAAI,KAAK,CAC5D;AACD,kBAAc,KAAK,cAAc;;;GAGrC,CACH;AAGD,KAAI,cAAc,SAAS,KAAK,YAAY,SAAS,GAAG;AAEtD,QAAMC,yFAA2B,eAAe,EAAE,aAAa,CAAC;AAGhE,MAAI,cAAc,SAAS,EACzB,OAAM,QAAQ,IACZ,cAAc,IAAI,OAAO,SAAS;GAChC,MAAM,uCAAwB,SAAS,KAAK;AAC5C,OAAI;AACF,mCAAS,MAAM,EAAE,OAAO,MAAM,CAAC;AAE/B,cAAU,+DAAkC,aAAa,IAAI,EAC3D,WAAW,MACZ,CAAC;WACI;AACN,cACE,uEAA0C,aAAa,IACvD,EACE,WAAW,MACZ,CACF;;IAEH,CACH;;AAIL,QAAO;EACL;EACA;EACA,YAAY,cAAc,SAAS,KAAK,YAAY,SAAS;EAC9D"}
@@ -17,15 +17,9 @@ const generateDictionaryListContent = (dictionaries, functionName, importType, f
17
17
  id: (0, node_path.basename)(dictionaryPath, (0, node_path.extname)(dictionaryPath)),
18
18
  hash: `_${require_utils_getPathHash.getPathHash(dictionaryPath)}`
19
19
  }));
20
- const useFsReadForJson = format === "cjs" && importType === "json";
21
- if (useFsReadForJson) {
22
- content += `const _fs = require('node:fs');\n`;
23
- content += `const _path = require('node:path');\n`;
24
- }
25
20
  dictionariesRef.forEach((dictionary) => {
26
21
  if (format === "esm") content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === "json" ? " with { type: 'json' }" : ""};\n`;
27
- if (format === "cjs") if (useFsReadForJson) content += `const ${dictionary.hash} = JSON.parse(_fs.readFileSync(_path.join(__dirname, '${dictionary.relativePath}'), 'utf-8'));\n`;
28
- else content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\n`;
22
+ if (format === "cjs") content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\n`;
29
23
  });
30
24
  content += "\n";
31
25
  const formattedDictionaryMap = dictionariesRef.map((dictionary) => ` "${dictionary.id}": ${dictionary.hash}`).join(",\n");
@@ -1 +1 @@
1
- {"version":3,"file":"generateDictionaryListContent.cjs","names":["getPathHash"],"sources":["../../../src/createDictionaryEntryPoint/generateDictionaryListContent.ts"],"sourcesContent":["import { basename, extname, relative } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { getPathHash } from '../utils/getPathHash';\n\n/**\n * This function generates the content of the dictionary list file\n */\nexport const generateDictionaryListContent = (\n dictionaries: string[],\n functionName: string,\n importType: 'json' | 'javascript',\n format: 'cjs' | 'esm' = 'esm',\n configuration = getConfiguration()\n): string => {\n const { mainDir } = configuration.system;\n\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: normalizePath(relative(mainDir, dictionaryPath)),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getPathHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // For CJS JSON imports, use readFileSync to avoid require.cache memory leak\n const useFsReadForJson = format === 'cjs' && importType === 'json';\n\n if (useFsReadForJson) {\n content += `const _fs = require('node:fs');\\n`;\n content += `const _path = require('node:path');\\n`;\n }\n\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === 'json' ? \" with { type: 'json' }\" : ''};\\n`;\n if (format === 'cjs') {\n if (useFsReadForJson) {\n content += `const ${dictionary.hash} = JSON.parse(_fs.readFileSync(_path.join(__dirname, '${dictionary.relativePath}'), 'utf-8'));\\n`;\n } else {\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n }\n }\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n content += `const dictionaries = {\\n${formattedDictionaryMap}\\n};\\n`;\n content += `const ${functionName} = () => dictionaries;\\n`;\n\n if (format === 'esm') {\n content += `\\n`;\n content += `export { ${functionName} };\\n`;\n content += `export default dictionaries;\\n`;\n }\n\n if (format === 'cjs') {\n content += `\\n`;\n content += `module.exports.${functionName} = ${functionName};\\n`;\n content += `module.exports = dictionaries;\\n`;\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,iCACX,cACA,cACA,YACA,SAAwB,OACxB,6DAAkC,KACvB;CACX,MAAM,EAAE,YAAY,cAAc;CAElC,IAAI,UAAU;CAEd,MAAM,kBAAkB,aAAa,KAAK,oBAAoB;EAC5D,gFAAqC,SAAS,eAAe,CAAC;EAC9D,4BAAa,uCAAwB,eAAe,CAAC;EACrD,MAAM,IAAIA,sCAAY,eAAe;EACtC,EAAE;CAGH,MAAM,mBAAmB,WAAW,SAAS,eAAe;AAE5D,KAAI,kBAAkB;AACpB,aAAW;AACX,aAAW;;AAGb,iBAAgB,SAAS,eAAe;AACtC,MAAI,WAAW,MACb,YAAW,UAAU,WAAW,KAAK,SAAS,WAAW,aAAa,GAAG,eAAe,SAAS,2BAA2B,GAAG;AACjI,MAAI,WAAW,MACb,KAAI,iBACF,YAAW,SAAS,WAAW,KAAK,wDAAwD,WAAW,aAAa;MAEpH,YAAW,SAAS,WAAW,KAAK,cAAc,WAAW,aAAa;GAG9E;AAEF,YAAW;CAGX,MAAM,yBAAiC,gBACpC,KAAK,eAAe,MAAM,WAAW,GAAG,KAAK,WAAW,OAAO,CAC/D,KAAK,MAAM;AAEd,YAAW,2BAA2B,uBAAuB;AAC7D,YAAW,SAAS,aAAa;AAEjC,KAAI,WAAW,OAAO;AACpB,aAAW;AACX,aAAW,YAAY,aAAa;AACpC,aAAW;;AAGb,KAAI,WAAW,OAAO;AACpB,aAAW;AACX,aAAW,kBAAkB,aAAa,KAAK,aAAa;AAC5D,aAAW;;AAGb,QAAO"}
1
+ {"version":3,"file":"generateDictionaryListContent.cjs","names":["getPathHash"],"sources":["../../../src/createDictionaryEntryPoint/generateDictionaryListContent.ts"],"sourcesContent":["import { basename, extname, relative } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { getPathHash } from '../utils/getPathHash';\n\n/**\n * This function generates the content of the dictionary list file\n */\nexport const generateDictionaryListContent = (\n dictionaries: string[],\n functionName: string,\n importType: 'json' | 'javascript',\n format: 'cjs' | 'esm' = 'esm',\n configuration = getConfiguration()\n): string => {\n const { mainDir } = configuration.system;\n\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: normalizePath(relative(mainDir, dictionaryPath)),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getPathHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === 'json' ? \" with { type: 'json' }\" : ''};\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n content += `const dictionaries = {\\n${formattedDictionaryMap}\\n};\\n`;\n content += `const ${functionName} = () => dictionaries;\\n`;\n\n if (format === 'esm') {\n content += `\\n`;\n content += `export { ${functionName} };\\n`;\n content += `export default dictionaries;\\n`;\n }\n\n if (format === 'cjs') {\n content += `\\n`;\n content += `module.exports.${functionName} = ${functionName};\\n`;\n content += `module.exports = dictionaries;\\n`;\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,iCACX,cACA,cACA,YACA,SAAwB,OACxB,6DAAkC,KACvB;CACX,MAAM,EAAE,YAAY,cAAc;CAElC,IAAI,UAAU;CAEd,MAAM,kBAAkB,aAAa,KAAK,oBAAoB;EAC5D,gFAAqC,SAAS,eAAe,CAAC;EAC9D,4BAAa,uCAAwB,eAAe,CAAC;EACrD,MAAM,IAAIA,sCAAY,eAAe;EACtC,EAAE;AAEH,iBAAgB,SAAS,eAAe;AACtC,MAAI,WAAW,MACb,YAAW,UAAU,WAAW,KAAK,SAAS,WAAW,aAAa,GAAG,eAAe,SAAS,2BAA2B,GAAG;AACjI,MAAI,WAAW,MACb,YAAW,SAAS,WAAW,KAAK,cAAc,WAAW,aAAa;GAC5E;AAEF,YAAW;CAGX,MAAM,yBAAiC,gBACpC,KAAK,eAAe,MAAM,WAAW,GAAG,KAAK,WAAW,OAAO,CAC/D,KAAK,MAAM;AAEd,YAAW,2BAA2B,uBAAuB;AAC7D,YAAW,SAAS,aAAa;AAEjC,KAAI,WAAW,OAAO;AACpB,aAAW;AACX,aAAW,YAAY,aAAa;AACpC,aAAW;;AAGb,KAAI,WAAW,OAAO;AACpB,aAAW;AACX,aAAW,kBAAkB,aAAa,KAAK,aAAa;AAC5D,aAAW;;AAGb,QAAO"}
@@ -191,23 +191,29 @@ const initIntlayer = async (rootDir) => {
191
191
  }
192
192
  break;
193
193
  }
194
- if (isNextJsProject) {
195
- const nextVersion = packageJson.dependencies?.next || packageJson.devDependencies?.next;
196
- const isVersionGreaterOrEqual = (versionString, major) => {
197
- if (!versionString || typeof versionString !== "string") return false;
198
- const match = versionString.match(/^[^\d]*(\d+)/);
199
- if (!match) return false;
200
- return parseInt(match[1], 10) >= major;
201
- };
202
- if (nextVersion && isVersionGreaterOrEqual(nextVersion, 16)) {
203
- const devScript = packageJson.scripts?.dev;
204
- const expectedScript = "intlayer watch --with 'bun run --bun next dev'";
205
- if (devScript && devScript !== expectedScript && devScript.includes("next dev")) {
206
- packageJson.scripts.dev = expectedScript;
207
- await require_init_utils_fileSystem.writeFileToRoot(rootDir, packageJsonPath, JSON.stringify(packageJson, null, 2));
208
- (0, _intlayer_config_logger.logger)(`${_intlayer_config_logger.v} Updated ${(0, _intlayer_config_logger.colorizePath)("package.json")} dev script for Next.js >= 16`);
209
- }
210
- }
194
+ const allDeps = {
195
+ ...packageJson.dependencies,
196
+ ...packageJson.devDependencies
197
+ };
198
+ const isVersionGreaterOrEqual = (versionString, major) => {
199
+ if (!versionString || typeof versionString !== "string") return false;
200
+ const match = versionString.match(/^[^\d]*(\d+)/);
201
+ if (!match) return false;
202
+ return parseInt(match[1], 10) >= major;
203
+ };
204
+ const backendIntlayerPackages = [
205
+ "express-intlayer",
206
+ "fastify-intlayer",
207
+ "adonis-intlayer",
208
+ "hono-intlayer"
209
+ ];
210
+ const devScript = packageJson.scripts?.dev;
211
+ let newDevScript;
212
+ if ((isNextJsProject && isVersionGreaterOrEqual(allDeps.next, 16) || backendIntlayerPackages.some((pkg) => allDeps[pkg])) && !devScript.includes("intlayer watch")) newDevScript = `intlayer watch --with '${devScript}'`;
213
+ if (newDevScript) {
214
+ packageJson.scripts.dev = newDevScript;
215
+ await require_init_utils_fileSystem.writeFileToRoot(rootDir, packageJsonPath, JSON.stringify(packageJson, null, 2));
216
+ (0, _intlayer_config_logger.logger)(`${_intlayer_config_logger.v} Updated ${(0, _intlayer_config_logger.colorizePath)("package.json")} dev script to run intlayer watch`);
211
217
  }
212
218
  for (const file of [
213
219
  "webpack.config.js",
@@ -222,7 +228,7 @@ const initIntlayer = async (rootDir) => {
222
228
  if (!hasAliasConfiguration) {
223
229
  const aliases = (0, _intlayer_config_utils.getAlias)({ configuration: (0, _intlayer_config_node.getConfiguration)({ baseDir: rootDir }) });
224
230
  if (hasTsConfig && tsConfigFiles.length > 0) {
225
- const tsConfigPath = tsConfigFiles.find((f) => f === "tsconfig.json") || tsConfigFiles[0];
231
+ const tsConfigPath = tsConfigFiles.find((file) => file === "tsconfig.json") || tsConfigFiles[0];
226
232
  const config = require_init_utils_jsonParser.parseJSONWithComments(await require_init_utils_fileSystem.readFileFromRoot(rootDir, tsConfigPath));
227
233
  config.compilerOptions ??= {};
228
234
  config.compilerOptions.paths ??= {};
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["ANSIColors","exists","x","readFileFromRoot","writeFileToRoot","v","parseJSONWithComments","ensureDirectory","findTsConfigFiles","initConfig","updateViteConfig","updateNextConfig"],"sources":["../../../src/init/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\n\nimport { getAlias } from '@intlayer/config/utils';\nimport { initConfig } from '../initConfig';\nimport {\n ensureDirectory,\n exists,\n findTsConfigFiles,\n parseJSONWithComments,\n readFileFromRoot,\n updateNextConfig,\n updateViteConfig,\n writeFileToRoot,\n} from './utils';\n\n/**\n * Documentation URL Constants\n */\nconst DocumentationRouter = {\n NextJS: 'https://intlayer.org/doc/environment/nextjs.md',\n NextJS_15: 'https://intlayer.org/doc/environment/nextjs/15.md',\n NextJS_14: 'https://intlayer.org/doc/environment/nextjs/14.md',\n CRA: 'https://intlayer.org/doc/environment/create-react-app.md',\n Astro: 'https://intlayer.org/doc/environment/astro.md',\n ViteAndReact: 'https://intlayer.org/doc/environment/vite-and-react.md',\n ViteAndReact_ReactRouterV7:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7.md',\n ViteAndReact_ReactRouterV7_FSRoutes:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7-fs-routes.md',\n ViteAndVue: 'https://intlayer.org/doc/environment/vite-and-vue.md',\n ViteAndSolid: 'https://intlayer.org/doc/environment/vite-and-solid.md',\n ViteAndSvelte: 'https://intlayer.org/doc/environment/vite-and-svelte.md',\n ViteAndPreact: 'https://intlayer.org/doc/environment/vite-and-preact.md',\n TanStackRouter: 'https://intlayer.org/doc/environment/tanstack.md',\n NuxtAndVue: 'https://intlayer.org/doc/environment/nuxt-and-vue.md',\n Angular: 'https://intlayer.org/doc/environment/angular.md',\n SvelteKit: 'https://intlayer.org/doc/environment/sveltekit.md',\n ReactNativeAndExpo:\n 'https://intlayer.org/doc/environment/react-native-and-expo.md',\n Lynx: 'https://intlayer.org/doc/environment/lynx-and-react.md',\n Express: 'https://intlayer.org/doc/environment/express.md',\n NestJS: 'https://intlayer.org/doc/environment/nestjs.md',\n Fastify: 'https://intlayer.org/doc/environment/fastify.md',\n Default: 'https://intlayer.org/doc/get-started',\n\n // Check for competitors libs\n NextIntl: 'https://intlayer.org/blog/intlayer-with-next-intl.md',\n ReactI18Next: 'https://intlayer.org/blog/intlayer-with-react-i18next.md',\n ReactIntl: 'https://intlayer.org/blog/intlayer-with-react-intl.md',\n NextI18Next: 'https://intlayer.org/blog/intlayer-with-next-i18next.md',\n VueI18n: 'https://intlayer.org/blog/intlayer-with-vue-i18n.md',\n};\n\n/**\n * Helper: Detects the environment and returns the doc URL\n */\nconst getDocumentationUrl = (packageJson: any): string => {\n const deps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n /**\n * Helper to check if a version string matches a specific major version\n * Matches: \"15\", \"^15.0.0\", \"~15.2\", \"15.0.0-beta\"\n */\n const isVersion = (versionString: string, major: number): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const regex = new RegExp(`^[\\\\^~]?${major}(?:\\\\.|$)`);\n return regex.test(versionString);\n };\n\n // Mobile / Cross-platform\n if (deps['@lynx-js/react'] || deps['@lynx-js/core']) {\n return DocumentationRouter.Lynx;\n }\n if (deps['react-native'] || deps.expo) {\n return DocumentationRouter.ReactNativeAndExpo;\n }\n\n // Meta-frameworks (Next, Nuxt, Astro, SvelteKit)\n if (deps.next) {\n const version = deps.next;\n\n if (isVersion(version, 14)) {\n return DocumentationRouter.NextJS_14;\n }\n\n if (isVersion(version, 15)) {\n return DocumentationRouter.NextJS_15;\n }\n\n return DocumentationRouter.NextJS;\n }\n\n if (deps.nuxt) return DocumentationRouter.NuxtAndVue;\n if (deps.astro) return DocumentationRouter.Astro;\n if (deps['@sveltejs/kit']) return DocumentationRouter.SvelteKit;\n\n // Routers (TanStack & React Router v7)\n if (deps['@tanstack/react-router']) {\n return DocumentationRouter.TanStackRouter;\n }\n\n // Check for React Router v7\n const reactRouterVersion = deps['react-router'];\n if (reactRouterVersion && typeof reactRouterVersion === 'string') {\n // Distinguish between standard v7 and v7 with FS routes\n if (deps['@react-router/fs-routes']) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7_FSRoutes;\n }\n\n // Use Regex to ensure it is v7\n if (isVersion(reactRouterVersion, 7)) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7;\n }\n }\n\n // Vite Ecosystem (General)\n if (deps.vite) {\n if (deps.vue) return DocumentationRouter.ViteAndVue;\n if (deps['solid-js']) return DocumentationRouter.ViteAndSolid;\n if (deps.svelte) return DocumentationRouter.ViteAndSvelte;\n if (deps.preact) return DocumentationRouter.ViteAndPreact;\n\n // Default to React if Vite is present but specific other frameworks aren't found\n return DocumentationRouter.ViteAndReact;\n }\n\n // Other Web Frameworks\n if (deps['react-scripts']) return DocumentationRouter.CRA;\n if (deps['@angular/core']) return DocumentationRouter.Angular;\n\n // Backend\n if (deps['@nestjs/core']) return DocumentationRouter.NestJS;\n if (deps.express) return DocumentationRouter.Express;\n if (deps.fastify) return DocumentationRouter.Fastify;\n\n // Competitor Libs (Migration Guides)\n // We check these last as specific environment setup is usually higher priority,\n // but if no specific framework logic matched (or as a fallback), we guide to migration.\n if (deps['next-intl']) return DocumentationRouter.NextIntl;\n if (deps['react-i18next'] || deps.i18next)\n return DocumentationRouter.ReactI18Next;\n if (deps['react-intl']) return DocumentationRouter.ReactIntl;\n if (deps['next-i18next']) return DocumentationRouter.NextI18Next;\n if (deps['vue-i18n']) return DocumentationRouter.VueI18n;\n\n return DocumentationRouter.Default;\n};\n\n/**\n * MAIN LOGIC\n */\nexport const initIntlayer = async (rootDir: string) => {\n logger(colorize('Checking Intlayer configuration...', ANSIColors.CYAN));\n\n // READ PACKAGE.JSON\n const packageJsonPath = 'package.json';\n if (!(await exists(rootDir, packageJsonPath))) {\n logger(\n `${x} No ${colorizePath('package.json')} found. Please run this script from the project root.`,\n { level: 'error' }\n );\n process.exit(1);\n }\n\n const packageJsonContent = await readFileFromRoot(rootDir, packageJsonPath);\n let packageJson: Record<string, any>;\n try {\n packageJson = JSON.parse(packageJsonContent);\n } catch {\n logger(`${x} Could not parse ${colorizePath('package.json')}.`, {\n level: 'error',\n });\n process.exit(1);\n }\n\n // Determine the correct documentation URL based on dependencies\n const guideUrl = getDocumentationUrl(packageJson);\n\n // CHECK .GITIGNORE\n const gitignorePath = '.gitignore';\n if (await exists(rootDir, gitignorePath)) {\n const gitignoreContent = await readFileFromRoot(rootDir, gitignorePath);\n\n if (!gitignoreContent.includes('intlayer')) {\n const newContent = `${gitignoreContent}\\n# Intlayer\\n.intlayer\\n`;\n await writeFileToRoot(rootDir, gitignorePath, newContent);\n logger(\n `${v} Added ${colorizePath('.intlayer')} to ${colorizePath(gitignorePath)}`\n );\n } else {\n logger(`${v} ${colorizePath(gitignorePath)} already includes .intlayer`);\n }\n }\n\n // CHECK VS CODE EXTENSION RECOMMENDATIONS\n const vscodeDir = '.vscode';\n const extensionsJsonPath = join(vscodeDir, 'extensions.json');\n const extensionId = 'intlayer.intlayer-vs-code-extension';\n\n try {\n let extensionsConfig: { recommendations: string[] } = {\n recommendations: [],\n };\n\n if (await exists(rootDir, extensionsJsonPath)) {\n const content = await readFileFromRoot(rootDir, extensionsJsonPath);\n extensionsConfig = parseJSONWithComments(content);\n } else {\n await ensureDirectory(rootDir, vscodeDir);\n }\n\n if (!extensionsConfig.recommendations) {\n extensionsConfig.recommendations = [];\n }\n\n if (!extensionsConfig.recommendations.includes(extensionId)) {\n extensionsConfig.recommendations.push(extensionId);\n await writeFileToRoot(\n rootDir,\n extensionsJsonPath,\n JSON.stringify(extensionsConfig, null, 2)\n );\n logger(\n `${v} Added ${colorize(extensionId, ANSIColors.MAGENTA)} to ${colorizePath(extensionsJsonPath)}`\n );\n } else {\n logger(\n `${v} ${colorizePath(extensionsJsonPath)} already includes ${colorize(extensionId, ANSIColors.MAGENTA)}`\n );\n }\n } catch {\n logger(\n `${x} Could not update ${colorizePath(extensionsJsonPath)}. You may need to add ${colorize(extensionId, ANSIColors.MAGENTA)} manually.`,\n { level: 'warn' }\n );\n }\n\n // CHECK TSCONFIGS\n const tsConfigFiles = await findTsConfigFiles(rootDir);\n let hasTsConfig = false;\n\n for (const fileName of tsConfigFiles) {\n if (await exists(rootDir, fileName)) {\n hasTsConfig = true;\n try {\n const fileContent = await readFileFromRoot(rootDir, fileName);\n const config = parseJSONWithComments(fileContent);\n const typeDefinition = '.intlayer/**/*.ts';\n\n let updated = false;\n\n if (!config.include) {\n // Skip if no include array (solution-style)\n } else if (\n Array.isArray(config.include) &&\n !(config.include as string[]).some((pattern: string) =>\n pattern.includes('.intlayer')\n )\n ) {\n config.include.push(typeDefinition);\n updated = true;\n } else if (config.include.includes(typeDefinition)) {\n logger(\n `${v} ${colorizePath(fileName)} already includes intlayer types`\n );\n }\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n fileName,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(fileName)} to include intlayer types`\n );\n }\n } catch {\n logger(\n `${x} Could not parse or update ${colorizePath(fileName)}. You may need to add ${colorizePath('.intlayer/types/**/*.ts')} manually.`,\n { level: 'warn' }\n );\n }\n }\n }\n\n // INITIALIZE CONFIG FILE\n const format = hasTsConfig ? 'intlayer.config.ts' : 'intlayer.config.mjs';\n await initConfig(format, rootDir);\n\n let hasAliasConfiguration = false;\n\n // CHECK VITE CONFIG\n const viteConfigs = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];\n\n for (const file of viteConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('vite-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateViteConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // CHECK NEXT CONFIG\n const nextConfigs = ['next.config.js', 'next.config.mjs', 'next.config.ts'];\n let isNextJsProject = false;\n\n for (const file of nextConfigs) {\n if (await exists(rootDir, file)) {\n isNextJsProject = true;\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('next-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateNextConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // UPDATE PACKAGE.JSON DEV SCRIPT FOR NEXT.JS >= 16\n if (isNextJsProject) {\n const nextVersion =\n packageJson.dependencies?.next || packageJson.devDependencies?.next;\n\n const isVersionGreaterOrEqual = (\n versionString: string,\n major: number\n ): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const match = versionString.match(/^[^\\d]*(\\d+)/);\n\n if (!match) return false;\n const majorVersion = parseInt(match[1], 10);\n return majorVersion >= major;\n };\n\n if (nextVersion && isVersionGreaterOrEqual(nextVersion, 16)) {\n const devScript = packageJson.scripts?.dev;\n const expectedScript = \"intlayer watch --with 'bun run --bun next dev'\";\n\n if (\n devScript &&\n devScript !== expectedScript &&\n devScript.includes('next dev')\n ) {\n packageJson.scripts.dev = expectedScript;\n\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath('package.json')} dev script for Next.js >= 16`\n );\n }\n }\n }\n\n // CHECK WEBPACK CONFIG\n const webpackConfigs = [\n 'webpack.config.js',\n 'webpack.config.ts',\n 'webpack.config.mjs',\n 'webpack.config.cjs',\n ];\n\n for (const file of webpackConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n logger(\n `${v} Found ${colorizePath(\n file\n )}. Make sure to configure aliases manually or use the Intlayer Webpack plugin.`\n );\n break;\n }\n }\n\n if (!hasAliasConfiguration) {\n const configuration = getConfiguration({ baseDir: rootDir });\n const aliases = getAlias({ configuration });\n\n if (hasTsConfig && tsConfigFiles.length > 0) {\n const tsConfigPath =\n tsConfigFiles.find((f) => f === 'tsconfig.json') || tsConfigFiles[0];\n const tsConfigContent = await readFileFromRoot(rootDir, tsConfigPath);\n const config = parseJSONWithComments(tsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n tsConfigPath,\n JSON.stringify(config, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath(\n tsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n const jsConfigPath = 'jsconfig.json';\n\n if (await exists(rootDir, jsConfigPath)) {\n const jsConfigContent = await readFileFromRoot(rootDir, jsConfigPath);\n const config = parseJSONWithComments(jsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n jsConfigPath,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n jsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n packageJson.imports ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n const importAlias = alias.replace('@', '#');\n const importPath = path.startsWith('.') ? path : `./${path}`;\n\n if (!packageJson.imports[importAlias]) {\n packageJson.imports[importAlias] = importPath;\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n packageJsonPath\n )} to include Intlayer imports`\n );\n }\n }\n }\n }\n\n // FINAL SUCCESS MESSAGE\n logger(`${v} ${colorize('Intlayer init setup complete.', ANSIColors.GREEN)}`);\n logger([\n colorize('Next →', ANSIColors.MAGENTA),\n colorize(\n `Follow the instructions in the documentation to complete the setup:`,\n ANSIColors.GREY_LIGHT\n ),\n colorizePath(guideUrl),\n ]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAM,sBAAsB;CAC1B,QAAQ;CACR,WAAW;CACX,WAAW;CACX,KAAK;CACL,OAAO;CACP,cAAc;CACd,4BACE;CACF,qCACE;CACF,YAAY;CACZ,cAAc;CACd,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,YAAY;CACZ,SAAS;CACT,WAAW;CACX,oBACE;CACF,MAAM;CACN,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CAGT,UAAU;CACV,cAAc;CACd,WAAW;CACX,aAAa;CACb,SAAS;CACV;;;;AAKD,MAAM,uBAAuB,gBAA6B;CACxD,MAAM,OAAO;EACX,GAAG,YAAY;EACf,GAAG,YAAY;EAChB;;;;;CAMD,MAAM,aAAa,eAAuB,UAA2B;AACnE,MAAI,CAAC,iBAAiB,OAAO,kBAAkB,SAAU,QAAO;AAEhE,SADc,IAAI,OAAO,WAAW,MAAM,WAAW,CACxC,KAAK,cAAc;;A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B,MAAM,QAAQ;AACxC,aAAO,gBAAgB,MAAM,SAAS,CAAC,KAAK;AAC5C,gBAAU;;MAEZ;AAEF,QAAI,SAAS;AACX,WAAMC,8CACJ,SACA,cACA,KAAK,UAAU,QAAQ,MAAM,EAAE,CAChC;AACD,yCACE,GAAGC,0BAAE,qDACH,aACD,CAAC,8BACH;;UAEE;AACL,gBAAY,YAAY,EAAE;IAE1B,IAAI,UAAU;AAEd,WAAO,QAAQ,QAAQ,CAAC,SAAS,CAAC,OAAO,UAAU;KACjD,MAAM,cAAc,MAAM,QAAQ,KAAK,IAAI;KAC3C,MAAM,aAAa,KAAK,WAAW,IAAI,GAAG,OAAO,KAAK;AAEtD,SAAI,CAAC,YAAY,QAAQ,cAAc;AACrC,kBAAY,QAAQ,eAAe;AACnC,gBAAU;;MAEZ;AAEF,QAAI,SAAS;AACX,WAAMD,8CACJ,SACA,iBACA,KAAK,UAAU,aAAa,MAAM,EAAE,CACrC;AACD,yCACE,GAAGC,0BAAE,qDACH,gBACD,CAAC,8BACH;;;;;AAOT,qCAAO,GAAGA,0BAAE,yCAAY,iCAAiCL,wBAAW,MAAM,GAAG;AAC7E,qCAAO;wCACI,UAAUA,wBAAW,QAAQ;wCAEpC,uEACAA,wBAAW,WACZ;4CACY,SAAS;EACvB,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["ANSIColors","exists","x","readFileFromRoot","writeFileToRoot","v","parseJSONWithComments","ensureDirectory","findTsConfigFiles","initConfig","updateViteConfig","updateNextConfig"],"sources":["../../../src/init/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\n\nimport { getAlias } from '@intlayer/config/utils';\nimport { initConfig } from '../initConfig';\nimport {\n ensureDirectory,\n exists,\n findTsConfigFiles,\n parseJSONWithComments,\n readFileFromRoot,\n updateNextConfig,\n updateViteConfig,\n writeFileToRoot,\n} from './utils';\n\n/**\n * Documentation URL Constants\n */\nconst DocumentationRouter = {\n NextJS: 'https://intlayer.org/doc/environment/nextjs.md',\n NextJS_15: 'https://intlayer.org/doc/environment/nextjs/15.md',\n NextJS_14: 'https://intlayer.org/doc/environment/nextjs/14.md',\n CRA: 'https://intlayer.org/doc/environment/create-react-app.md',\n Astro: 'https://intlayer.org/doc/environment/astro.md',\n ViteAndReact: 'https://intlayer.org/doc/environment/vite-and-react.md',\n ViteAndReact_ReactRouterV7:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7.md',\n ViteAndReact_ReactRouterV7_FSRoutes:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7-fs-routes.md',\n ViteAndVue: 'https://intlayer.org/doc/environment/vite-and-vue.md',\n ViteAndSolid: 'https://intlayer.org/doc/environment/vite-and-solid.md',\n ViteAndSvelte: 'https://intlayer.org/doc/environment/vite-and-svelte.md',\n ViteAndPreact: 'https://intlayer.org/doc/environment/vite-and-preact.md',\n TanStackRouter: 'https://intlayer.org/doc/environment/tanstack.md',\n NuxtAndVue: 'https://intlayer.org/doc/environment/nuxt-and-vue.md',\n Angular: 'https://intlayer.org/doc/environment/angular.md',\n SvelteKit: 'https://intlayer.org/doc/environment/sveltekit.md',\n ReactNativeAndExpo:\n 'https://intlayer.org/doc/environment/react-native-and-expo.md',\n Lynx: 'https://intlayer.org/doc/environment/lynx-and-react.md',\n Express: 'https://intlayer.org/doc/environment/express.md',\n NestJS: 'https://intlayer.org/doc/environment/nestjs.md',\n Fastify: 'https://intlayer.org/doc/environment/fastify.md',\n Default: 'https://intlayer.org/doc/get-started',\n\n // Check for competitors libs\n NextIntl: 'https://intlayer.org/blog/intlayer-with-next-intl.md',\n ReactI18Next: 'https://intlayer.org/blog/intlayer-with-react-i18next.md',\n ReactIntl: 'https://intlayer.org/blog/intlayer-with-react-intl.md',\n NextI18Next: 'https://intlayer.org/blog/intlayer-with-next-i18next.md',\n VueI18n: 'https://intlayer.org/blog/intlayer-with-vue-i18n.md',\n};\n\n/**\n * Helper: Detects the environment and returns the doc URL\n */\nconst getDocumentationUrl = (packageJson: any): string => {\n const deps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n /**\n * Helper to check if a version string matches a specific major version\n * Matches: \"15\", \"^15.0.0\", \"~15.2\", \"15.0.0-beta\"\n */\n const isVersion = (versionString: string, major: number): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const regex = new RegExp(`^[\\\\^~]?${major}(?:\\\\.|$)`);\n return regex.test(versionString);\n };\n\n // Mobile / Cross-platform\n if (deps['@lynx-js/react'] || deps['@lynx-js/core']) {\n return DocumentationRouter.Lynx;\n }\n if (deps['react-native'] || deps.expo) {\n return DocumentationRouter.ReactNativeAndExpo;\n }\n\n // Meta-frameworks (Next, Nuxt, Astro, SvelteKit)\n if (deps.next) {\n const version = deps.next;\n\n if (isVersion(version, 14)) {\n return DocumentationRouter.NextJS_14;\n }\n\n if (isVersion(version, 15)) {\n return DocumentationRouter.NextJS_15;\n }\n\n return DocumentationRouter.NextJS;\n }\n\n if (deps.nuxt) return DocumentationRouter.NuxtAndVue;\n if (deps.astro) return DocumentationRouter.Astro;\n if (deps['@sveltejs/kit']) return DocumentationRouter.SvelteKit;\n\n // Routers (TanStack & React Router v7)\n if (deps['@tanstack/react-router']) {\n return DocumentationRouter.TanStackRouter;\n }\n\n // Check for React Router v7\n const reactRouterVersion = deps['react-router'];\n if (reactRouterVersion && typeof reactRouterVersion === 'string') {\n // Distinguish between standard v7 and v7 with FS routes\n if (deps['@react-router/fs-routes']) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7_FSRoutes;\n }\n\n // Use Regex to ensure it is v7\n if (isVersion(reactRouterVersion, 7)) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7;\n }\n }\n\n // Vite Ecosystem (General)\n if (deps.vite) {\n if (deps.vue) return DocumentationRouter.ViteAndVue;\n if (deps['solid-js']) return DocumentationRouter.ViteAndSolid;\n if (deps.svelte) return DocumentationRouter.ViteAndSvelte;\n if (deps.preact) return DocumentationRouter.ViteAndPreact;\n\n // Default to React if Vite is present but specific other frameworks aren't found\n return DocumentationRouter.ViteAndReact;\n }\n\n // Other Web Frameworks\n if (deps['react-scripts']) return DocumentationRouter.CRA;\n if (deps['@angular/core']) return DocumentationRouter.Angular;\n\n // Backend\n if (deps['@nestjs/core']) return DocumentationRouter.NestJS;\n if (deps.express) return DocumentationRouter.Express;\n if (deps.fastify) return DocumentationRouter.Fastify;\n\n // Competitor Libs (Migration Guides)\n // We check these last as specific environment setup is usually higher priority,\n // but if no specific framework logic matched (or as a fallback), we guide to migration.\n if (deps['next-intl']) return DocumentationRouter.NextIntl;\n if (deps['react-i18next'] || deps.i18next)\n return DocumentationRouter.ReactI18Next;\n if (deps['react-intl']) return DocumentationRouter.ReactIntl;\n if (deps['next-i18next']) return DocumentationRouter.NextI18Next;\n if (deps['vue-i18n']) return DocumentationRouter.VueI18n;\n\n return DocumentationRouter.Default;\n};\n\n/**\n * MAIN LOGIC\n */\nexport const initIntlayer = async (rootDir: string) => {\n logger(colorize('Checking Intlayer configuration...', ANSIColors.CYAN));\n\n // READ PACKAGE.JSON\n const packageJsonPath = 'package.json';\n if (!(await exists(rootDir, packageJsonPath))) {\n logger(\n `${x} No ${colorizePath('package.json')} found. Please run this script from the project root.`,\n { level: 'error' }\n );\n process.exit(1);\n }\n\n const packageJsonContent = await readFileFromRoot(rootDir, packageJsonPath);\n let packageJson: Record<string, any>;\n try {\n packageJson = JSON.parse(packageJsonContent);\n } catch {\n logger(`${x} Could not parse ${colorizePath('package.json')}.`, {\n level: 'error',\n });\n process.exit(1);\n }\n\n // Determine the correct documentation URL based on dependencies\n const guideUrl = getDocumentationUrl(packageJson);\n\n // CHECK .GITIGNORE\n const gitignorePath = '.gitignore';\n if (await exists(rootDir, gitignorePath)) {\n const gitignoreContent = await readFileFromRoot(rootDir, gitignorePath);\n\n if (!gitignoreContent.includes('intlayer')) {\n const newContent = `${gitignoreContent}\\n# Intlayer\\n.intlayer\\n`;\n await writeFileToRoot(rootDir, gitignorePath, newContent);\n logger(\n `${v} Added ${colorizePath('.intlayer')} to ${colorizePath(gitignorePath)}`\n );\n } else {\n logger(`${v} ${colorizePath(gitignorePath)} already includes .intlayer`);\n }\n }\n\n // CHECK VS CODE EXTENSION RECOMMENDATIONS\n const vscodeDir = '.vscode';\n const extensionsJsonPath = join(vscodeDir, 'extensions.json');\n const extensionId = 'intlayer.intlayer-vs-code-extension';\n\n try {\n let extensionsConfig: { recommendations: string[] } = {\n recommendations: [],\n };\n\n if (await exists(rootDir, extensionsJsonPath)) {\n const content = await readFileFromRoot(rootDir, extensionsJsonPath);\n extensionsConfig = parseJSONWithComments(content);\n } else {\n await ensureDirectory(rootDir, vscodeDir);\n }\n\n if (!extensionsConfig.recommendations) {\n extensionsConfig.recommendations = [];\n }\n\n if (!extensionsConfig.recommendations.includes(extensionId)) {\n extensionsConfig.recommendations.push(extensionId);\n await writeFileToRoot(\n rootDir,\n extensionsJsonPath,\n JSON.stringify(extensionsConfig, null, 2)\n );\n logger(\n `${v} Added ${colorize(extensionId, ANSIColors.MAGENTA)} to ${colorizePath(extensionsJsonPath)}`\n );\n } else {\n logger(\n `${v} ${colorizePath(extensionsJsonPath)} already includes ${colorize(extensionId, ANSIColors.MAGENTA)}`\n );\n }\n } catch {\n logger(\n `${x} Could not update ${colorizePath(extensionsJsonPath)}. You may need to add ${colorize(extensionId, ANSIColors.MAGENTA)} manually.`,\n { level: 'warn' }\n );\n }\n\n // CHECK TSCONFIGS\n const tsConfigFiles = await findTsConfigFiles(rootDir);\n let hasTsConfig = false;\n\n for (const fileName of tsConfigFiles) {\n if (await exists(rootDir, fileName)) {\n hasTsConfig = true;\n try {\n const fileContent = await readFileFromRoot(rootDir, fileName);\n const config = parseJSONWithComments(fileContent);\n const typeDefinition = '.intlayer/**/*.ts';\n\n let updated = false;\n\n if (!config.include) {\n // Skip if no include array (solution-style)\n } else if (\n Array.isArray(config.include) &&\n !(config.include as string[]).some((pattern: string) =>\n pattern.includes('.intlayer')\n )\n ) {\n config.include.push(typeDefinition);\n updated = true;\n } else if (config.include.includes(typeDefinition)) {\n logger(\n `${v} ${colorizePath(fileName)} already includes intlayer types`\n );\n }\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n fileName,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(fileName)} to include intlayer types`\n );\n }\n } catch {\n logger(\n `${x} Could not parse or update ${colorizePath(fileName)}. You may need to add ${colorizePath('.intlayer/types/**/*.ts')} manually.`,\n { level: 'warn' }\n );\n }\n }\n }\n\n // INITIALIZE CONFIG FILE\n const format = hasTsConfig ? 'intlayer.config.ts' : 'intlayer.config.mjs';\n await initConfig(format, rootDir);\n\n let hasAliasConfiguration = false;\n\n // CHECK VITE CONFIG\n const viteConfigs = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];\n\n for (const file of viteConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('vite-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateViteConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // CHECK NEXT CONFIG\n const nextConfigs = ['next.config.js', 'next.config.mjs', 'next.config.ts'];\n let isNextJsProject = false;\n\n for (const file of nextConfigs) {\n if (await exists(rootDir, file)) {\n isNextJsProject = true;\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('next-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateNextConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // UPDATE PACKAGE.JSON DEV SCRIPT\n // Next.js >= 16 uses a bun-specific wrapper; backend frameworks wrap whatever\n // the existing dev script is. Both use `intlayer watch --with`.\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n const isVersionGreaterOrEqual = (\n versionString: string,\n major: number\n ): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const match = versionString.match(/^[^\\d]*(\\d+)/);\n if (!match) return false;\n return parseInt(match[1], 10) >= major;\n };\n\n const backendIntlayerPackages = [\n 'express-intlayer',\n 'fastify-intlayer',\n 'adonis-intlayer',\n 'hono-intlayer',\n ];\n\n const devScript = packageJson.scripts?.dev;\n\n let newDevScript: string | undefined;\n\n if (\n ((isNextJsProject && isVersionGreaterOrEqual(allDeps.next, 16)) ||\n backendIntlayerPackages.some((pkg) => allDeps[pkg])) &&\n !devScript.includes('intlayer watch')\n ) {\n newDevScript = `intlayer watch --with '${devScript}'`;\n }\n\n if (newDevScript) {\n packageJson.scripts.dev = newDevScript;\n\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath('package.json')} dev script to run intlayer watch`\n );\n }\n\n // CHECK WEBPACK CONFIG\n const webpackConfigs = [\n 'webpack.config.js',\n 'webpack.config.ts',\n 'webpack.config.mjs',\n 'webpack.config.cjs',\n ];\n\n for (const file of webpackConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n logger(\n `${v} Found ${colorizePath(\n file\n )}. Make sure to configure aliases manually or use the Intlayer Webpack plugin.`\n );\n break;\n }\n }\n\n if (!hasAliasConfiguration) {\n const configuration = getConfiguration({ baseDir: rootDir });\n const aliases = getAlias({ configuration });\n\n if (hasTsConfig && tsConfigFiles.length > 0) {\n const tsConfigPath =\n tsConfigFiles.find((file) => file === 'tsconfig.json') ||\n tsConfigFiles[0];\n const tsConfigContent = await readFileFromRoot(rootDir, tsConfigPath);\n const config = parseJSONWithComments(tsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n tsConfigPath,\n JSON.stringify(config, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath(\n tsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n const jsConfigPath = 'jsconfig.json';\n\n if (await exists(rootDir, jsConfigPath)) {\n const jsConfigContent = await readFileFromRoot(rootDir, jsConfigPath);\n const config = parseJSONWithComments(jsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n jsConfigPath,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n jsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n packageJson.imports ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n const importAlias = alias.replace('@', '#');\n const importPath = path.startsWith('.') ? path : `./${path}`;\n\n if (!packageJson.imports[importAlias]) {\n packageJson.imports[importAlias] = importPath;\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n packageJsonPath\n )} to include Intlayer imports`\n );\n }\n }\n }\n }\n\n // FINAL SUCCESS MESSAGE\n logger(`${v} ${colorize('Intlayer init setup complete.', ANSIColors.GREEN)}`);\n logger([\n colorize('Next →', ANSIColors.MAGENTA),\n colorize(\n `Follow the instructions in the documentation to complete the setup:`,\n ANSIColors.GREY_LIGHT\n ),\n colorizePath(guideUrl),\n ]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqB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AM,EAAE,CACrC;AACD,yCACE,GAAGC,0BAAE,qDACH,gBACD,CAAC,8BACH;;;;;AAOT,qCAAO,GAAGA,0BAAE,yCAAY,iCAAiCL,wBAAW,MAAM,GAAG;AAC7E,qCAAO;wCACI,UAAUA,wBAAW,QAAQ;wCAEpC,uEACAA,wBAAW,WACZ;4CACY,SAAS;EACvB,CAAC"}
@@ -50,7 +50,7 @@ const loadContentDeclarations = async (contentDeclarationFilePath, configuration
50
50
  try {
51
51
  const dictionariesPromises = contentDeclarationFilePath.map(async (path) => {
52
52
  return {
53
- relativePath: (0, node_path.relative)(configuration.system.baseDir, path),
53
+ relativePath: (0, node_path.relative)(system.baseDir, path),
54
54
  dictionary: await loadContentDeclaration(path, configuration, bundleFilePath)
55
55
  };
56
56
  });
@@ -1 +1 @@
1
- {"version":3,"file":"loadContentDeclaration.cjs","names":["getIntlayerBundle","filterInvalidDictionaries","parallelize","processContentDeclaration"],"sources":["../../../src/loadDictionaries/loadContentDeclaration.ts"],"sourcesContent":["import { writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { loadExternalFile } from '@intlayer/config/file';\nimport { cacheDisk, getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { processContentDeclaration } from '../buildIntlayerDictionary/processContentDeclaration';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { getIntlayerBundle } from './getIntlayerBundle';\nimport type { DictionariesStatus } from './loadDictionaries';\nimport { logTypeScriptErrors } from './logTypeScriptErrors';\n\nexport const formatLocalDictionaries = (\n dictionariesRecord: Record<string, Dictionary>,\n configuration: IntlayerConfig\n): Dictionary[] =>\n Object.entries(dictionariesRecord).map(([relativePath, dict]) => ({\n ...dict,\n location: dict.location ?? configuration.dictionary?.location ?? 'local',\n localId: `${dict.key}::local::${relativePath}`,\n filePath: relativePath,\n }));\n\nexport const ensureIntlayerBundle = async (\n configuration: IntlayerConfig\n): Promise<string> => {\n const { system } = configuration;\n\n const { set, isValid } = cacheDisk(configuration, ['intlayer-bundle'], {\n ttlMs: 1000 * 60 * 60 * 24 * 5, // 5 days\n });\n\n const filePath = join(system.cacheDir, 'intlayer-bundle.cjs');\n const hasIntlayerBundle = await isValid();\n\n if (!hasIntlayerBundle) {\n const intlayerBundle = await getIntlayerBundle(configuration);\n await writeFile(filePath, intlayerBundle);\n await set('ok');\n }\n\n return filePath;\n};\n\nexport const loadContentDeclaration = async (\n path: string,\n configuration: IntlayerConfig,\n bundleFilePath?: string\n): Promise<Dictionary | undefined> => {\n const { build } = configuration;\n\n const resolvedBundleFilePath =\n bundleFilePath ?? (await ensureIntlayerBundle(configuration));\n\n try {\n const dictionary = await loadExternalFile(path, {\n projectRequire: build.require ?? getProjectRequire(),\n buildOptions: {\n banner: {\n js: [\n `globalThis.INTLAYER_FILE_PATH = '${path}';`,\n `globalThis.INTLAYER_BASE_DIR = '${configuration.system.baseDir}';`,\n ].join('\\n'),\n },\n },\n aliases: {\n intlayer: resolvedBundleFilePath,\n },\n });\n\n return dictionary;\n } catch (error) {\n console.error(`Error loading content declaration at ${path}:`, error);\n return undefined;\n }\n};\n\nexport const loadContentDeclarations = async (\n contentDeclarationFilePath: string[],\n configuration: IntlayerConfig,\n onStatusUpdate?: (status: DictionariesStatus[]) => void\n): Promise<Dictionary[]> => {\n const { build, system } = configuration;\n\n // Check for TypeScript warnings before we build\n if (build.checkTypes) {\n logTypeScriptErrors(contentDeclarationFilePath, configuration).catch(\n (e) => {\n console.error('Error during TypeScript validation:', e);\n }\n );\n }\n\n const bundleFilePath = await ensureIntlayerBundle(configuration);\n\n try {\n const dictionariesPromises = contentDeclarationFilePath.map(\n async (path) => {\n const relativePath = relative(configuration.system.baseDir, path);\n\n const dictionary = await loadContentDeclaration(\n path,\n configuration,\n bundleFilePath\n );\n\n return { relativePath, dictionary };\n }\n );\n\n const dictionariesArray = await Promise.all(dictionariesPromises);\n const dictionariesRecord = dictionariesArray.reduce(\n (acc, { relativePath, dictionary }) => {\n if (dictionary) {\n acc[relativePath] = dictionary;\n }\n return acc;\n },\n {} as Record<string, Dictionary>\n );\n\n const contentDeclarations: Dictionary[] = formatLocalDictionaries(\n dictionariesRecord,\n configuration\n ).filter((dictionary) => dictionary.location !== 'remote');\n\n const listFoundDictionaries = contentDeclarations.map((declaration) => ({\n dictionaryKey: declaration.key,\n type: 'local' as const,\n status: 'found' as const,\n }));\n\n onStatusUpdate?.(listFoundDictionaries);\n\n const processedDictionaries = await parallelize(\n contentDeclarations,\n async (contentDeclaration): Promise<Dictionary | undefined> => {\n if (!contentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: contentDeclaration.key,\n type: 'local',\n status: 'building',\n },\n ]);\n\n const processedContentDeclaration = await processContentDeclaration(\n contentDeclaration as Dictionary,\n configuration\n );\n\n if (!processedContentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: processedContentDeclaration.key,\n type: 'local',\n status: 'built',\n },\n ]);\n\n return processedContentDeclaration;\n }\n );\n\n return filterInvalidDictionaries(processedDictionaries, configuration, {\n checkSchema: false,\n });\n } catch {\n console.error('Error loading content declarations');\n }\n\n return [];\n};\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,2BACX,oBACA,kBAEA,OAAO,QAAQ,mBAAmB,CAAC,KAAK,CAAC,cAAc,WAAW;CAChE,GAAG;CACH,UAAU,KAAK,YAAY,cAAc,YAAY,YAAY;CACjE,SAAS,GAAG,KAAK,IAAI,WAAW;CAChC,UAAU;CACX,EAAE;AAEL,MAAa,uBAAuB,OAClC,kBACoB;CACpB,MAAM,EAAE,WAAW;CAEnB,MAAM,EAAE,KAAK,kDAAsB,eAAe,CAAC,kBAAkB,EAAE,EACrE,OAAO,MAAO,KAAK,KAAK,KAAK,GAC9B,CAAC;CAEF,MAAM,+BAAgB,OAAO,UAAU,sBAAsB;AAG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EH,mBAAiB,sBAAsB;AAsCvC,SAAOC,4DApCuB,MAAMC,sCAClC,qBACA,OAAO,uBAAwD;AAC7D,OAAI,CAAC,mBACH;AAGF,oBAAiB,CACf;IACE,eAAe,mBAAmB;IAClC,MAAM;IACN,QAAQ;IACT,CACF,CAAC;GAEF,MAAM,8BAA8B,MAAMC,oFACxC,oBACA,cACD;AAED,OAAI,CAAC,4BACH;AAGF,oBAAiB,CACf;IACE,eAAe,4BAA4B;IAC3C,MAAM;IACN,QAAQ;IACT,CACF,CAAC;AAEF,UAAO;IAEV,EAEuD,eAAe,EACrE,aAAa,OACd,CAAC;SACI;AACN,UAAQ,MAAM,qCAAqC;;AAGrD,QAAO,EAAE"}
1
+ {"version":3,"file":"loadContentDeclaration.cjs","names":["getIntlayerBundle","filterInvalidDictionaries","parallelize","processContentDeclaration"],"sources":["../../../src/loadDictionaries/loadContentDeclaration.ts"],"sourcesContent":["import { writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { loadExternalFile } from '@intlayer/config/file';\nimport { cacheDisk, getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { processContentDeclaration } from '../buildIntlayerDictionary/processContentDeclaration';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { getIntlayerBundle } from './getIntlayerBundle';\nimport type { DictionariesStatus } from './loadDictionaries';\nimport { logTypeScriptErrors } from './logTypeScriptErrors';\n\nexport const formatLocalDictionaries = (\n dictionariesRecord: Record<string, Dictionary>,\n configuration: IntlayerConfig\n): Dictionary[] =>\n Object.entries(dictionariesRecord).map(([relativePath, dict]) => ({\n ...dict,\n location: dict.location ?? configuration.dictionary?.location ?? 'local',\n localId: `${dict.key}::local::${relativePath}`,\n filePath: relativePath,\n }));\n\nexport const ensureIntlayerBundle = async (\n configuration: IntlayerConfig\n): Promise<string> => {\n const { system } = configuration;\n\n const { set, isValid } = cacheDisk(configuration, ['intlayer-bundle'], {\n ttlMs: 1000 * 60 * 60 * 24 * 5, // 5 days\n });\n\n const filePath = join(system.cacheDir, 'intlayer-bundle.cjs');\n const hasIntlayerBundle = await isValid();\n\n if (!hasIntlayerBundle) {\n const intlayerBundle = await getIntlayerBundle(configuration);\n await writeFile(filePath, intlayerBundle);\n await set('ok');\n }\n\n return filePath;\n};\n\nexport const loadContentDeclaration = async (\n path: string,\n configuration: IntlayerConfig,\n bundleFilePath?: string\n): Promise<Dictionary | undefined> => {\n const { build } = configuration;\n\n const resolvedBundleFilePath =\n bundleFilePath ?? (await ensureIntlayerBundle(configuration));\n\n try {\n const dictionary = await loadExternalFile(path, {\n projectRequire: build.require ?? getProjectRequire(),\n buildOptions: {\n banner: {\n js: [\n `globalThis.INTLAYER_FILE_PATH = '${path}';`,\n `globalThis.INTLAYER_BASE_DIR = '${configuration.system.baseDir}';`,\n ].join('\\n'),\n },\n },\n aliases: {\n intlayer: resolvedBundleFilePath,\n },\n });\n\n return dictionary;\n } catch (error) {\n console.error(`Error loading content declaration at ${path}:`, error);\n return undefined;\n }\n};\n\nexport const loadContentDeclarations = async (\n contentDeclarationFilePath: string[],\n configuration: IntlayerConfig,\n onStatusUpdate?: (status: DictionariesStatus[]) => void\n): Promise<Dictionary[]> => {\n const { build, system } = configuration;\n\n // Check for TypeScript warnings before we build\n if (build.checkTypes) {\n logTypeScriptErrors(contentDeclarationFilePath, configuration).catch(\n (e) => {\n console.error('Error during TypeScript validation:', e);\n }\n );\n }\n\n const bundleFilePath = await ensureIntlayerBundle(configuration);\n\n try {\n const dictionariesPromises = contentDeclarationFilePath.map(\n async (path) => {\n const relativePath = relative(system.baseDir, path);\n\n const dictionary = await loadContentDeclaration(\n path,\n configuration,\n bundleFilePath\n );\n\n return { relativePath, dictionary };\n }\n );\n\n const dictionariesArray = await Promise.all(dictionariesPromises);\n const dictionariesRecord = dictionariesArray.reduce(\n (acc, { relativePath, dictionary }) => {\n if (dictionary) {\n acc[relativePath] = dictionary;\n }\n return acc;\n },\n {} as Record<string, Dictionary>\n );\n\n const contentDeclarations: Dictionary[] = formatLocalDictionaries(\n dictionariesRecord,\n configuration\n ).filter((dictionary) => dictionary.location !== 'remote');\n\n const listFoundDictionaries = contentDeclarations.map((declaration) => ({\n dictionaryKey: declaration.key,\n type: 'local' as const,\n status: 'found' as const,\n }));\n\n onStatusUpdate?.(listFoundDictionaries);\n\n const processedDictionaries = await parallelize(\n contentDeclarations,\n async (contentDeclaration): Promise<Dictionary | undefined> => {\n if (!contentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: contentDeclaration.key,\n type: 'local',\n status: 'building',\n },\n ]);\n\n const processedContentDeclaration = await processContentDeclaration(\n contentDeclaration as Dictionary,\n configuration\n );\n\n if (!processedContentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: processedContentDeclaration.key,\n type: 'local',\n status: 'built',\n },\n ]);\n\n return processedContentDeclaration;\n }\n );\n\n return filterInvalidDictionaries(processedDictionaries, configuration, {\n checkSchema: false,\n });\n } catch {\n console.error('Error loading content declarations');\n }\n\n return [];\n};\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,2BACX,oBACA,kBAEA,OAAO,QAAQ,mBAAmB,CAAC,KAAK,CAAC,cAAc,WAAW;CAChE,GAAG;CACH,UAAU,KAAK,YAAY,cAAc,YAAY,YAAY;CACjE,SAAS,GAAG,KAAK,IAAI,WAAW;CAChC,UAAU;CACX,EAAE;AAEL,MAAa,uBAAuB,OAClC,kBACoB;CACpB,MAAM,EAAE,WAAW;CAEnB,MAAM,EAAE,KAAK,kDAAsB,eAAe,CAAC,kBAAkB,EAAE,EACrE,OAAO,MAAO,KAAK,KAAK,KAAK,GAC9B,CAAC;CAEF,MAAM,+BAAgB,OAAO,UAAU,sBAAsB;AAG7D,KAAI,CAFsB,MAAM,SAAS,EAEjB;AAEtB,wCAAgB,UADO,MAAMA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O,uBAAwD;AAC7D,OAAI,CAAC,mBACH;AAGF,oBAAiB,CACf;IACE,eAAe,mBAAmB;IAClC,MAAM;IACN,QAAQ;IACT,CACF,CAAC;GAEF,MAAM,8BAA8B,MAAMC,oFACxC,oBACA,cACD;AAED,OAAI,CAAC,4BACH;AAGF,oBAAiB,CACf;IACE,eAAe,4BAA4B;IAC3C,MAAM;IACN,QAAQ;IACT,CACF,CAAC;AAEF,UAAO;IAEV,EAEuD,eAAe,EACrE,aAAa,OACd,CAAC;SACI;AACN,UAAQ,MAAM,qCAAqC;;AAGrD,QAAO,EAAE"}
@@ -0,0 +1,25 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let node_path = require("node:path");
4
+ let node_fs = require("node:fs");
5
+
6
+ //#region src/utils/readDictionariesFromDisk.ts
7
+ /**
8
+ * Reads all JSON dictionary files from a directory, keyed by filename.
9
+ * Uses readFileSync instead of require() to avoid require.cache memory leak.
10
+ */
11
+ const readDictionariesFromDisk = (directory) => {
12
+ const dictionaries = {};
13
+ if ((0, node_fs.existsSync)(directory)) {
14
+ const files = (0, node_fs.readdirSync)(directory).filter((file) => file.endsWith(".json"));
15
+ for (const file of files) {
16
+ const key = (0, node_path.basename)(file, (0, node_path.extname)(file));
17
+ dictionaries[key] = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(directory, file), "utf-8"));
18
+ }
19
+ }
20
+ return dictionaries;
21
+ };
22
+
23
+ //#endregion
24
+ exports.readDictionariesFromDisk = readDictionariesFromDisk;
25
+ //# sourceMappingURL=readDictionariesFromDisk.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readDictionariesFromDisk.cjs","names":[],"sources":["../../../src/utils/readDictionariesFromDisk.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { basename, extname, join } from 'node:path';\n\n/**\n * Reads all JSON dictionary files from a directory, keyed by filename.\n * Uses readFileSync instead of require() to avoid require.cache memory leak.\n */\nexport const readDictionariesFromDisk = <T = Record<string, any>>(\n directory: string\n): T => {\n const dictionaries: Record<string, any> = {};\n\n if (existsSync(directory)) {\n const files = readdirSync(directory).filter((file) =>\n file.endsWith('.json')\n );\n\n for (const file of files) {\n const key = basename(file, extname(file));\n dictionaries[key] = JSON.parse(\n readFileSync(join(directory, file), 'utf-8')\n );\n }\n }\n\n return dictionaries as T;\n};\n"],"mappings":";;;;;;;;;;AAOA,MAAa,4BACX,cACM;CACN,MAAM,eAAoC,EAAE;AAE5C,6BAAe,UAAU,EAAE;EACzB,MAAM,iCAAoB,UAAU,CAAC,QAAQ,SAC3C,KAAK,SAAS,QAAQ,CACvB;AAED,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,8BAAe,6BAAc,KAAK,CAAC;AACzC,gBAAa,OAAO,KAAK,oDACL,WAAW,KAAK,EAAE,QAAQ,CAC7C;;;AAIL,QAAO"}
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ const require_utils_readDictionariesFromDisk = require('../utils/readDictionariesFromDisk.cjs');
3
4
  const require_utils_getFormatFromExtension = require('../utils/getFormatFromExtension.cjs');
4
5
  const require_detectFormatCommand = require('../detectFormatCommand.cjs');
5
6
  const require_writeContentDeclaration_processContentDeclarationContent = require('./processContentDeclarationContent.cjs');
@@ -7,7 +8,6 @@ const require_writeContentDeclaration_transformJSONFile = require('./transformJS
7
8
  const require_writeContentDeclaration_writeJSFile = require('./writeJSFile.cjs');
8
9
  let node_fs_promises = require("node:fs/promises");
9
10
  let node_path = require("node:path");
10
- let _intlayer_unmerged_dictionaries_entry = require("@intlayer/unmerged-dictionaries-entry");
11
11
  let node_fs = require("node:fs");
12
12
  let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
13
13
  let _intlayer_core_plugins = require("@intlayer/core/plugins");
@@ -71,7 +71,7 @@ const writeContentDeclaration = async (dictionary, configuration, options) => {
71
71
  ...options
72
72
  };
73
73
  const newDictionaryLocationPath = (0, node_path.join)(baseDir, newDictionariesPath);
74
- const existingDictionary = (0, _intlayer_unmerged_dictionaries_entry.getUnmergedDictionaries)(configuration)[dictionary.key]?.find((el) => el.localId === dictionary.localId);
74
+ const existingDictionary = require_utils_readDictionariesFromDisk.readDictionariesFromDisk(configuration.system.unmergedDictionariesDir)[dictionary.key]?.find((el) => el.localId === dictionary.localId);
75
75
  const formattedContentDeclaration = await formatContentDeclaration(dictionary, configuration, localeList);
76
76
  if (existingDictionary?.filePath) {
77
77
  const isSameContent = (0, node_util.isDeepStrictEqual)(existingDictionary, dictionary);
@@ -1 +1 @@
1
- {"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","COMPILER_NO_METADATA","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAM,2BAA2B,OAC/B,YACA,eACA,eACG;;;;CAIH,MAAM,sBACJ,MAAMA,kGAAiC,WAAW;CAEpD,IAAI,UAAU,oBAAoB;;;;AAMlC,KAAI,WAAW,OACb,8DACE,qBACA,WAAW,OACZ,CAAC;UACO,WACT,oEACE,qBACA,WACD,CAAC;CAGJ,IA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KAAK,cAAc,OAAO;IAC3B,CAAC;WACK,OAAO;AACd,WAAQ,MAAM,MAAM;;AAIxB;;AAGF,OAAMC,wDAAY,kBAAkB,YAAY,eAAe,WAAW;AAI1E,KAAI;AAKF,qDAHE,cAAc,OAAO,UACrB,yBACD,EACsB,EAAE,WAAW,MAAM,CAAC;SACrC"}
1
+ {"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","COMPILER_NO_METADATA","readDictionariesFromDisk","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { readDictionariesFromDisk } from '../utils/readDictionariesFromDisk';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAM,2BAA2B,OAC/B,YACA,eACA,eACG;;;;CAIH,MAAM,sBACJ,MAAMA,kGAAiC,WAAW;CAEpD,IAAI,UAAU,oBAAoB;;;;AAMlC,KAAI,WAAW,OACb,8DACE,qBACA,WAAW,OACZ,CAAC;UACO,WACT,oEACE,qBACA,WACD,CAAC;CAGJ,IAAI,qBAA0B;EAC5B,GAAG;EACH;EACD;;;;AAMD,YAAW,MAAM,UAAU,cAAc,WAAW,EAAE,CACpD,KAAI,OAAO,cAAc;EACvB,MAAM,kBAAkB,MAAM,OAAO,eAAe;GAClD,YAAY;GACZ;GACD,CAAC;AAEF,MAAI,gBACF,sBAAqB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EACsB,EAAE,WAAW,MAAM,CAAC;SACrC"}
@@ -5,6 +5,7 @@ import { getBuiltFetchDictionariesPath } from "./createDictionaryEntryPoint/getB
5
5
  import { getBuiltRemoteDictionariesPath } from "./createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs";
6
6
  import { getBuiltUnmergedDictionariesPath } from "./createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs";
7
7
  import { createDictionaryEntryPoint } from "./createDictionaryEntryPoint/createDictionaryEntryPoint.mjs";
8
+ import { readDictionariesFromDisk } from "./utils/readDictionariesFromDisk.mjs";
8
9
  import { buildDictionary } from "./buildIntlayerDictionary/buildIntlayerDictionary.mjs";
9
10
  import { createModuleAugmentation, getTypeName } from "./createType/createModuleAugmentation.mjs";
10
11
  import { createTypes, generateTypeScriptType } from "./createType/createType.mjs";
@@ -22,4 +23,4 @@ import { transformJSFile } from "./writeContentDeclaration/transformJSFile.mjs";
22
23
  import { writeJSFile } from "./writeContentDeclaration/writeJSFile.mjs";
23
24
  import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.mjs";
24
25
 
25
- export { buildDictionary, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, ensureIntlayerBundle, formatDictionaries, formatDictionariesOutput, formatDictionary, formatDictionaryOutput, formatDistantDictionaries, formatLocalDictionaries, generateDictionaryListContent, generateTypeScriptType, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getTypeName, isCachedConfigurationUpToDate, loadContentDeclaration, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, prepareIntlayer, processContentDeclaration, transformJSFile, writeConfiguration, writeContentDeclaration, writeJSFile };
26
+ export { buildDictionary, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, ensureIntlayerBundle, formatDictionaries, formatDictionariesOutput, formatDictionary, formatDictionaryOutput, formatDistantDictionaries, formatLocalDictionaries, generateDictionaryListContent, generateTypeScriptType, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getTypeName, isCachedConfigurationUpToDate, loadContentDeclaration, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, prepareIntlayer, processContentDeclaration, readDictionariesFromDisk, transformJSFile, writeConfiguration, writeContentDeclaration, writeJSFile };
@@ -1,8 +1,8 @@
1
+ import { readDictionariesFromDisk } from "../utils/readDictionariesFromDisk.mjs";
1
2
  import { writeDynamicDictionary } from "./writeDynamicDictionary.mjs";
2
3
  import { writeFetchDictionary } from "./writeFetchDictionary.mjs";
3
4
  import { writeMergedDictionaries } from "./writeMergedDictionary.mjs";
4
5
  import { writeUnmergedDictionaries } from "./writeUnmergedDictionary.mjs";
5
- import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
6
6
  import { IMPORT_MODE, OUTPUT_FORMAT } from "@intlayer/config/defaultValues";
7
7
 
8
8
  //#region src/buildIntlayerDictionary/buildIntlayerDictionary.ts
@@ -22,7 +22,7 @@ const buildDictionary = async (localDictionariesEntries, configuration, options)
22
22
  };
23
23
  const unmergedDictionariesToUpdate = [...localDictionariesEntries];
24
24
  if (importOtherDictionaries) {
25
- const prevUnmergedDictionaries = getUnmergedDictionaries(configuration);
25
+ const prevUnmergedDictionaries = readDictionariesFromDisk(configuration.system.unmergedDictionariesDir);
26
26
  for (const dictionaryToWrite of localDictionariesEntries) {
27
27
  const allPrebuiltUnmergedDictionaries = prevUnmergedDictionaries[dictionaryToWrite.key];
28
28
  if (allPrebuiltUnmergedDictionaries?.length > 0) {