@intlayer/chokidar 8.4.9 → 8.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/initConfig/templates/cjs.txt +9 -1
- package/dist/assets/initConfig/templates/mjs.txt +9 -1
- package/dist/assets/initConfig/templates/ts.txt +9 -1
- package/dist/cjs/build.cjs +2 -0
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +2 -2
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs +3 -4
- package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/utils/readDictionariesFromDisk.cjs +25 -0
- package/dist/cjs/utils/readDictionariesFromDisk.cjs.map +1 -0
- package/dist/cjs/writeConfiguration/generateConfigurationContent.cjs +31 -0
- package/dist/cjs/writeConfiguration/generateConfigurationContent.cjs.map +1 -0
- package/dist/cjs/writeConfiguration/index.cjs +5 -23
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +2 -2
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/esm/build.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs +2 -2
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs.map +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs +3 -4
- package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +1 -1
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
- package/dist/esm/utils/readDictionariesFromDisk.mjs +23 -0
- package/dist/esm/utils/readDictionariesFromDisk.mjs.map +1 -0
- package/dist/esm/writeConfiguration/generateConfigurationContent.mjs +29 -0
- package/dist/esm/writeConfiguration/generateConfigurationContent.mjs.map +1 -0
- package/dist/esm/writeConfiguration/index.mjs +5 -23
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +2 -2
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/types/build.d.ts +2 -1
- package/dist/types/cleanRemovedContentDeclaration.d.ts.map +1 -1
- package/dist/types/utils/readDictionariesFromDisk.d.ts +9 -0
- package/dist/types/utils/readDictionariesFromDisk.d.ts.map +1 -0
- package/dist/types/writeConfiguration/generateConfigurationContent.d.ts +7 -0
- package/dist/types/writeConfiguration/generateConfigurationContent.d.ts.map +1 -0
- package/dist/types/writeConfiguration/index.d.ts.map +1 -1
- package/package.json +10 -10
|
@@ -53,6 +53,11 @@ const config = {
|
|
|
53
53
|
provider: 'openai',
|
|
54
54
|
model: 'gpt-5-mini',
|
|
55
55
|
apiKey: process.env.OPENAI_API_KEY,
|
|
56
|
+
/**
|
|
57
|
+
* Additional context for the translations
|
|
58
|
+
*
|
|
59
|
+
* Can be use in addition of the dictionary `description` field
|
|
60
|
+
*/
|
|
56
61
|
applicationContext: [''].join('\n'),
|
|
57
62
|
},
|
|
58
63
|
compiler: {
|
|
@@ -85,7 +90,10 @@ const config = {
|
|
|
85
90
|
|
|
86
91
|
/**
|
|
87
92
|
* Indicates if the components should be saved after being transformed.
|
|
88
|
-
*
|
|
93
|
+
*
|
|
94
|
+
* - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
|
|
95
|
+
*
|
|
96
|
+
* - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
|
|
89
97
|
*/
|
|
90
98
|
saveComponents: false,
|
|
91
99
|
},
|
|
@@ -53,6 +53,11 @@ const config = {
|
|
|
53
53
|
provider: 'openai',
|
|
54
54
|
model: 'gpt-5-mini',
|
|
55
55
|
apiKey: process.env.OPENAI_API_KEY,
|
|
56
|
+
/**
|
|
57
|
+
* Additional context for the translations
|
|
58
|
+
*
|
|
59
|
+
* Can be use in addition of the dictionary `description` field
|
|
60
|
+
*/
|
|
56
61
|
applicationContext: [''].join('\n'),
|
|
57
62
|
},
|
|
58
63
|
compiler: {
|
|
@@ -85,7 +90,10 @@ const config = {
|
|
|
85
90
|
|
|
86
91
|
/**
|
|
87
92
|
* Indicates if the components should be saved after being transformed.
|
|
88
|
-
*
|
|
93
|
+
*
|
|
94
|
+
* - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
|
|
95
|
+
*
|
|
96
|
+
* - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
|
|
89
97
|
*/
|
|
90
98
|
saveComponents: false,
|
|
91
99
|
},
|
|
@@ -52,6 +52,11 @@ const config: IntlayerConfig = {
|
|
|
52
52
|
provider: 'openai',
|
|
53
53
|
model: 'gpt-5-mini',
|
|
54
54
|
apiKey: process.env.OPENAI_API_KEY,
|
|
55
|
+
/**
|
|
56
|
+
* Additional context for the translations
|
|
57
|
+
*
|
|
58
|
+
* Can be use in addition of the dictionary `description` field
|
|
59
|
+
*/
|
|
55
60
|
applicationContext: [''].join('\n'),
|
|
56
61
|
},
|
|
57
62
|
compiler: {
|
|
@@ -84,7 +89,10 @@ const config: IntlayerConfig = {
|
|
|
84
89
|
|
|
85
90
|
/**
|
|
86
91
|
* Indicates if the components should be saved after being transformed.
|
|
87
|
-
*
|
|
92
|
+
*
|
|
93
|
+
* - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
|
|
94
|
+
*
|
|
95
|
+
* - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
|
|
88
96
|
*/
|
|
89
97
|
saveComponents: false,
|
|
90
98
|
},
|
package/dist/cjs/build.cjs
CHANGED
|
@@ -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 =
|
|
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 {
|
|
1
|
+
{"version":3,"file":"buildIntlayerDictionary.cjs","names":["OUTPUT_FORMAT","IMPORT_MODE","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,YAAY,cAC3BC;CAEF,MAAM,EAAE,yBAAyB,KAAK,YAAY;EAChD,GAAG;EACH,GAAG;EACJ;CAED,MAAM,+BAA6C,CACjD,GAAG,yBACJ;AAED,KAAI,yBAAyB;EAC3B,MAAM,2BACJC,gEAAyB,cAAc,OAAO,wBAAwB;AAGxE,OAAK,MAAM,qBAAqB,0BAA0B;GACxD,MAAM,kCACJ,yBAAyB,kBAAkB;AAE7C,OAAI,iCAAiC,SAAS,GAAG;IAE/C,MAAM,4BACJ,gCAAgC,QAC7B,uBACC,mBAAmB,YAAY,kBAAkB,QACpD;AAEH,iCAA6B,KAAK,GAAG,0BAA0B;;;;CAKrE,MAAM,uBAAuB,MAAMC,kFACjC,8BACA,eACA,IACD;CAED,MAAM,qBAAqB,MAAMC,8EAC/B,sBACA,cACD;CAED,MAAM,6BAAwD,EAAE;CAChE,MAAM,mCAAmB,IAAI,KAAa;AAE1C,MAAK,MAAM,CAAC,KAAK,iBAAiB,OAAO,QAAQ,mBAAmB,EAAE;EAEpE,MAAM,OADa,aAAa,WACR,cAAc;AAEtC,MAAI,SAAS,aAAa,SAAS,QACjC,4BAA2B,OAAO;AAGpC,MAAI,SAAS,QACX,kBAAiB,IAAI,IAAI;;CAI7B,IAAI,sBAAwD;AAE5D,KAAI,OAAO,KAAK,2BAA2B,CAAC,SAAS,EACnD,uBAAsB,MAAMC,8EAC1B,4BACA,eACA,QACD;CAGH,IAAI,oBAAsD;AAE1D,KAAI,uBAAuB,iBAAiB,OAAO,GAAG;EACpD,MAAM,2BAAsD,EAAE;AAE9D,OAAK,MAAM,OAAO,iBAChB,KAAI,oBAAoB,KACtB,0BAAyB,OAAO,oBAAoB;AAIxD,MAAI,OAAO,KAAK,yBAAyB,CAAC,SAAS,EACjD,qBAAoB,MAAMC,0EACxB,0BACA,eACA,QACD;;AAIL,QAAO;EACL;EACA;EACA;EACA;EACD"}
|
|
@@ -1,20 +1,19 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
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 =
|
|
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 =
|
|
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,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6DACC,cAAc,OAAO,UAAU,GAAG,WAAW,IAAI,KAAK,CAC5D;AACD,mBAAc,KAAK,cAAc;KAQjC,MAAM,eAAe,4FAHnB,cAAc,OAAO,wBACrB,GAAG,WAAW,IAAI,IACnB,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,UAAMA,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"}
|
|
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,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AM,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"}
|
|
@@ -46,7 +46,7 @@ const getIntlayerBundle = async (configuration) => {
|
|
|
46
46
|
const rootRequire = (0, _intlayer_config_utils.getProjectRequire)(configuration.system.baseDir);
|
|
47
47
|
const configPackageRequire = _intlayer_config_utils.configESMxCJSRequire;
|
|
48
48
|
const localRequire = _intlayer_config_utils.isESModule ? (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href) : require;
|
|
49
|
-
const configurationPath = (0, node_path.join)(configuration.system.configDir, `configuration.
|
|
49
|
+
const configurationPath = (0, node_path.join)(configuration.system.configDir, `configuration.cjs`);
|
|
50
50
|
const replaceModules = {
|
|
51
51
|
defu: configPackageRequire.resolve("defu"),
|
|
52
52
|
esbuild: configPackageRequire.resolve("esbuild"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIntlayerBundle.cjs","names":["configESMxCJSRequire","isESModule","builtinModules"],"sources":["../../../src/loadDictionaries/getIntlayerBundle.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { builtinModules, createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { bundleFile, type ESBuildPlugin } from '@intlayer/config/file';\nimport {\n configESMxCJSRequire,\n getProjectRequire,\n isESModule,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Rewrites selected bare specifiers (and any of their subpaths) to absolute file paths,\n * using the provided localeRequire (either createRequire(import.meta.url) or require).\n *\n * Example:\n * rewritePathsPlugin([\"@intlayer/config\", \"@intlayer/core\"], localeRequire)\n * …will also rewrite \"@intlayer/core/file\" etc.\n */\nconst rewritePathsPlugin = (\n replaceModules: Record<string, string>,\n excludeModules?: string[]\n): ESBuildPlugin => {\n return {\n name: 'rewrite-paths',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n const exact = replaceModules[args.path];\n\n if (excludeModules?.includes(args.path)) {\n return null;\n }\n\n if (exact) {\n return {\n path: exact,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n\n // Optional: support subpaths like \"@intlayer/core/xyz\"\n for (const key of Object.keys(replaceModules)) {\n if (args.path === key || args.path.startsWith(`${key}/`)) {\n const sub = args.path.slice(key.length); // '' or '/...'\n return {\n path: replaceModules[key] + sub,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n }\n });\n },\n };\n};\n\n/**\n * Get the intlayer bundle to embed @intlayer/core and be able to mock @intlayer/config/built to mock the configuration file.\n */\nexport const getIntlayerBundle = async (configuration: IntlayerConfig) => {\n const rootRequire = getProjectRequire(configuration.system.baseDir);\n const configPackageRequire = configESMxCJSRequire;\n const localRequire = isESModule ? createRequire(import.meta.url) : require;\n\n const configurationPath = join(\n configuration.system.configDir,\n `configuration.
|
|
1
|
+
{"version":3,"file":"getIntlayerBundle.cjs","names":["configESMxCJSRequire","isESModule","builtinModules"],"sources":["../../../src/loadDictionaries/getIntlayerBundle.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { builtinModules, createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { bundleFile, type ESBuildPlugin } from '@intlayer/config/file';\nimport {\n configESMxCJSRequire,\n getProjectRequire,\n isESModule,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Rewrites selected bare specifiers (and any of their subpaths) to absolute file paths,\n * using the provided localeRequire (either createRequire(import.meta.url) or require).\n *\n * Example:\n * rewritePathsPlugin([\"@intlayer/config\", \"@intlayer/core\"], localeRequire)\n * …will also rewrite \"@intlayer/core/file\" etc.\n */\nconst rewritePathsPlugin = (\n replaceModules: Record<string, string>,\n excludeModules?: string[]\n): ESBuildPlugin => {\n return {\n name: 'rewrite-paths',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n const exact = replaceModules[args.path];\n\n if (excludeModules?.includes(args.path)) {\n return null;\n }\n\n if (exact) {\n return {\n path: exact,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n\n // Optional: support subpaths like \"@intlayer/core/xyz\"\n for (const key of Object.keys(replaceModules)) {\n if (args.path === key || args.path.startsWith(`${key}/`)) {\n const sub = args.path.slice(key.length); // '' or '/...'\n return {\n path: replaceModules[key] + sub,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n }\n });\n },\n };\n};\n\n/**\n * Get the intlayer bundle to embed @intlayer/core and be able to mock @intlayer/config/built to mock the configuration file.\n */\nexport const getIntlayerBundle = async (configuration: IntlayerConfig) => {\n const rootRequire = getProjectRequire(configuration.system.baseDir);\n const configPackageRequire = configESMxCJSRequire;\n const localRequire = isESModule ? createRequire(import.meta.url) : require;\n\n const configurationPath = join(\n configuration.system.configDir,\n `configuration.cjs`\n );\n\n const replaceModules = {\n defu: configPackageRequire.resolve('defu'),\n esbuild: configPackageRequire.resolve('esbuild'),\n '@intlayer/config/built': configurationPath,\n '@intlayer/config/utils': localRequire.resolve('@intlayer/config/utils'),\n '@intlayer/config/client': localRequire.resolve('@intlayer/config/client'),\n '@intlayer/config/logger': localRequire.resolve('@intlayer/config/logger'),\n '@intlayer/core/file': localRequire.resolve('@intlayer/core/file'),\n };\n\n const filePath = rootRequire.resolve('intlayer');\n const code = await readFile(filePath, 'utf-8');\n\n const output = await bundleFile(code, filePath, {\n external: [\n ...builtinModules,\n ...builtinModules.map((mod) => `node:${mod}`),\n ],\n minify: true,\n plugins: [rewritePathsPlugin(replaceModules)],\n });\n\n return output ?? '';\n};\n"],"mappings":";;;;;;;;;;;;;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ationFilePath, configuration
|
|
|
50
50
|
try {
|
|
51
51
|
const dictionariesPromises = contentDeclarationFilePath.map(async (path) => {
|
|
52
52
|
return {
|
|
53
|
-
relativePath: (0, node_path.relative)(
|
|
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(
|
|
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,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;IAAE,sCARqB,OAAO,SAAS,KAAK;IAQ5B,YANJ,MAAM,uBACvB,MACA,eACA,eACD;IAEkC;IAEtC;EAaD,MAAM,sBAAoC,yBAXhB,MAAM,QAAQ,IAAI,qBAAqB,EACpB,QAC1C,KAAK,EAAE,cAAc,iBAAiB;AACrC,OAAI,WACF,KAAI,gBAAgB;AAEtB,UAAO;KAET,EAAE,CACH,EAIC,cACD,CAAC,QAAQ,eAAe,WAAW,aAAa,SAAS;EAE1D,MAAM,wBAAwB,oBAAoB,KAAK,iBAAiB;GACtE,eAAe,YAAY;GAC3B,MAAM;GACN,QAAQ;GACT,EAAE;AAEH,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"}
|
|
@@ -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"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
let _intlayer_config_node = require("@intlayer/config/node");
|
|
4
|
+
|
|
5
|
+
//#region src/writeConfiguration/generateConfigurationContent.ts
|
|
6
|
+
const generateConfigurationContent = (configuration, format) => {
|
|
7
|
+
const { internationalization, routing, editor, log, metadata } = (0, _intlayer_config_node.buildBrowserConfiguration)(configuration);
|
|
8
|
+
let content = "";
|
|
9
|
+
content += `const internationalization = ${JSON.stringify(internationalization, null, 2)};\n`;
|
|
10
|
+
content += `const routing = ${JSON.stringify(routing, null, 2)};\n`;
|
|
11
|
+
content += `const editor = ${JSON.stringify(editor, null, 2)};\n`;
|
|
12
|
+
content += `const log = ${JSON.stringify(log, null, 2)};\n`;
|
|
13
|
+
content += `const metadata = ${JSON.stringify(metadata, null, 2)};\n`;
|
|
14
|
+
content += `const configuration = { internationalization, routing, editor, log, metadata };\n`;
|
|
15
|
+
if (format === "esm") {
|
|
16
|
+
content += `\nexport { internationalization, routing, editor, log, metadata, configuration };\n`;
|
|
17
|
+
content += `export default configuration;\n`;
|
|
18
|
+
} else {
|
|
19
|
+
content += `\nmodule.exports.internationalization = internationalization;\n`;
|
|
20
|
+
content += `module.exports.routing = routing;\n`;
|
|
21
|
+
content += `module.exports.editor = editor;\n`;
|
|
22
|
+
content += `module.exports.log = log;\n`;
|
|
23
|
+
content += `module.exports.metadata = metadata;\n`;
|
|
24
|
+
content += `module.exports = configuration;\n`;
|
|
25
|
+
}
|
|
26
|
+
return content;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
exports.generateConfigurationContent = generateConfigurationContent;
|
|
31
|
+
//# sourceMappingURL=generateConfigurationContent.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateConfigurationContent.cjs","names":[],"sources":["../../../src/writeConfiguration/generateConfigurationContent.ts"],"sourcesContent":["import { buildBrowserConfiguration } from '@intlayer/config/node';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const generateConfigurationContent = (\n configuration: IntlayerConfig,\n format: 'cjs' | 'esm'\n): string => {\n const { internationalization, routing, editor, log, metadata } =\n buildBrowserConfiguration(configuration);\n\n let content = '';\n\n content += `const internationalization = ${JSON.stringify(internationalization, null, 2)};\\n`;\n content += `const routing = ${JSON.stringify(routing, null, 2)};\\n`;\n content += `const editor = ${JSON.stringify(editor, null, 2)};\\n`;\n content += `const log = ${JSON.stringify(log, null, 2)};\\n`;\n content += `const metadata = ${JSON.stringify(metadata, null, 2)};\\n`;\n content += `const configuration = { internationalization, routing, editor, log, metadata };\\n`;\n\n if (format === 'esm') {\n content += `\\nexport { internationalization, routing, editor, log, metadata, configuration };\\n`;\n content += `export default configuration;\\n`;\n } else {\n content += `\\nmodule.exports.internationalization = internationalization;\\n`;\n content += `module.exports.routing = routing;\\n`;\n content += `module.exports.editor = editor;\\n`;\n content += `module.exports.log = log;\\n`;\n content += `module.exports.metadata = metadata;\\n`;\n content += `module.exports = configuration;\\n`;\n }\n\n return content;\n};\n"],"mappings":";;;;;AAGA,MAAa,gCACX,eACA,WACW;CACX,MAAM,EAAE,sBAAsB,SAAS,QAAQ,KAAK,kEACxB,cAAc;CAE1C,IAAI,UAAU;AAEd,YAAW,gCAAgC,KAAK,UAAU,sBAAsB,MAAM,EAAE,CAAC;AACzF,YAAW,mBAAmB,KAAK,UAAU,SAAS,MAAM,EAAE,CAAC;AAC/D,YAAW,kBAAkB,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;AAC7D,YAAW,eAAe,KAAK,UAAU,KAAK,MAAM,EAAE,CAAC;AACvD,YAAW,oBAAoB,KAAK,UAAU,UAAU,MAAM,EAAE,CAAC;AACjE,YAAW;AAEX,KAAI,WAAW,OAAO;AACpB,aAAW;AACX,aAAW;QACN;AACL,aAAW;AACX,aAAW;AACX,aAAW;AACX,aAAW;AACX,aAAW;AACX,aAAW;;AAGb,QAAO"}
|
|
@@ -1,40 +1,22 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
|
-
const
|
|
3
|
+
const require_writeFileIfChanged = require('../writeFileIfChanged.cjs');
|
|
4
|
+
const require_writeConfiguration_generateConfigurationContent = require('./generateConfigurationContent.cjs');
|
|
4
5
|
let node_fs_promises = require("node:fs/promises");
|
|
5
6
|
let node_path = require("node:path");
|
|
6
|
-
let node_util = require("node:util");
|
|
7
7
|
|
|
8
8
|
//#region src/writeConfiguration/index.ts
|
|
9
|
-
const getCachedConfiguration = async (configuration) => {
|
|
10
|
-
const configurationContent = await (0, node_fs_promises.readFile)((0, node_path.join)(configuration.system.configDir, "configuration.json"), "utf8");
|
|
11
|
-
return JSON.parse(configurationContent);
|
|
12
|
-
};
|
|
13
9
|
const isCachedConfigurationUpToDate = async (configuration) => {
|
|
14
10
|
try {
|
|
15
|
-
|
|
16
|
-
return (0, node_util.isDeepStrictEqual)(await getCachedConfiguration(configuration), cleanedConfiguration);
|
|
11
|
+
return await (0, node_fs_promises.readFile)((0, node_path.join)(configuration.system.configDir, "configuration.mjs"), "utf8") === require_writeConfiguration_generateConfigurationContent.generateConfigurationContent(configuration, "esm");
|
|
17
12
|
} catch {
|
|
18
13
|
return null;
|
|
19
14
|
}
|
|
20
15
|
};
|
|
21
|
-
const cleanConfiguration = (configuration) => {
|
|
22
|
-
return JSON.parse(JSON.stringify({
|
|
23
|
-
internationalization: {
|
|
24
|
-
locales: configuration.internationalization.locales,
|
|
25
|
-
defaultLocale: configuration.internationalization.defaultLocale
|
|
26
|
-
},
|
|
27
|
-
editor: configuration.editor,
|
|
28
|
-
log: configuration.log,
|
|
29
|
-
routing: configuration.routing,
|
|
30
|
-
metadata: configuration.metadata
|
|
31
|
-
}));
|
|
32
|
-
};
|
|
33
16
|
const writeConfiguration = async (configuration) => {
|
|
34
|
-
const {
|
|
35
|
-
const { configDir } = system;
|
|
17
|
+
const { configDir } = configuration.system;
|
|
36
18
|
await (0, node_fs_promises.mkdir)(configDir, { recursive: true });
|
|
37
|
-
await
|
|
19
|
+
await Promise.all([require_writeFileIfChanged.writeFileIfChanged((0, node_path.join)(configDir, "configuration.mjs"), require_writeConfiguration_generateConfigurationContent.generateConfigurationContent(configuration, "esm")), require_writeFileIfChanged.writeFileIfChanged((0, node_path.join)(configDir, "configuration.cjs"), require_writeConfiguration_generateConfigurationContent.generateConfigurationContent(configuration, "cjs"))]);
|
|
38
20
|
};
|
|
39
21
|
|
|
40
22
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["generateConfigurationContent","writeFileIfChanged"],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { generateConfigurationContent } from './generateConfigurationContent';\n\nexport const isCachedConfigurationUpToDate = async (\n configuration: IntlayerConfig\n): Promise<boolean | null> => {\n try {\n const mjsPath = join(configuration.system.configDir, 'configuration.mjs');\n const existingContent = await readFile(mjsPath, 'utf8');\n const expectedContent = generateConfigurationContent(configuration, 'esm');\n return existingContent === expectedContent;\n } catch {\n return null; // Can crash if file doesn't exist yet or config is not defined\n }\n};\n\nexport const writeConfiguration = async (configuration: IntlayerConfig) => {\n const { configDir } = configuration.system;\n\n await mkdir(configDir, { recursive: true });\n\n await Promise.all([\n writeFileIfChanged(\n join(configDir, 'configuration.mjs'),\n generateConfigurationContent(configuration, 'esm')\n ),\n writeFileIfChanged(\n join(configDir, 'configuration.cjs'),\n generateConfigurationContent(configuration, 'cjs')\n ),\n ]);\n};\n"],"mappings":";;;;;;;;AAMA,MAAa,gCAAgC,OAC3C,kBAC4B;AAC5B,KAAI;AAIF,SAFwB,yDADH,cAAc,OAAO,WAAW,oBAAoB,EACzB,OAAO,KAC/BA,qFAA6B,eAAe,MAAM;SAEpE;AACN,SAAO;;;AAIX,MAAa,qBAAqB,OAAO,kBAAkC;CACzE,MAAM,EAAE,cAAc,cAAc;AAEpC,mCAAY,WAAW,EAAE,WAAW,MAAM,CAAC;AAE3C,OAAM,QAAQ,IAAI,CAChBC,kEACO,WAAW,oBAAoB,EACpCD,qFAA6B,eAAe,MAAM,CACnD,EACDC,kEACO,WAAW,oBAAoB,EACpCD,qFAA6B,eAAe,MAAM,CACnD,CACF,CAAC"}
|
|
@@ -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 =
|
|
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,IAAI,qBAA0B;EAC5B,GAAG;EACH;EACD;;;;AAMD,YAAW,MAA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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;;AAQ3B,KAAI,EAFF,mBAAmB,WAAW,mBAAmB,K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esm/build.mjs
CHANGED
|
@@ -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 =
|
|
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) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildIntlayerDictionary.mjs","names":[],"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 {
|
|
1
|
+
{"version":3,"file":"buildIntlayerDictionary.mjs","names":[],"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 );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BAChB,KAAI,oBAAoB,KACtB,0BAAyB,OAAO,oBAAoB;AAIxD,MAAI,OAAO,KAAK,yBAAyB,CAAC,SAAS,EACjD,qBAAoB,MAAM,qBACxB,0BACA,eACA,QACD;;AAIL,QAAO;EACL;EACA;EACA;EACA;EACD"}
|
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
import { createDictionaryEntryPoint } from "./createDictionaryEntryPoint/createDictionaryEntryPoint.mjs";
|
|
2
|
+
import { readDictionariesFromDisk } from "./utils/readDictionariesFromDisk.mjs";
|
|
2
3
|
import { writeJsonIfChanged } from "./writeJsonIfChanged.mjs";
|
|
3
4
|
import { readFile, rm } from "node:fs/promises";
|
|
4
5
|
import { join, normalize, relative } from "node:path";
|
|
5
6
|
import { normalizePath } from "@intlayer/config/client";
|
|
6
7
|
import { colorizeKey, colorizePath, getAppLogger } from "@intlayer/config/logger";
|
|
7
|
-
import { getDictionaries } from "@intlayer/dictionaries-entry";
|
|
8
|
-
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
9
8
|
import fg from "fast-glob";
|
|
10
9
|
|
|
11
10
|
//#region src/cleanRemovedContentDeclaration.ts
|
|
12
11
|
const cleanRemovedContentDeclaration = async (filePath, keysToKeep, configuration) => {
|
|
13
12
|
const appLogger = getAppLogger(configuration);
|
|
14
|
-
const unmergedDictionaries =
|
|
13
|
+
const unmergedDictionaries = readDictionariesFromDisk(configuration.system.unmergedDictionariesDir);
|
|
15
14
|
const baseDir = configuration.system.baseDir;
|
|
16
15
|
const relativeFilePath = relative(baseDir, filePath);
|
|
17
16
|
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));
|
|
@@ -39,7 +38,7 @@ const cleanRemovedContentDeclaration = async (filePath, keysToKeep, configuratio
|
|
|
39
38
|
}
|
|
40
39
|
}
|
|
41
40
|
}));
|
|
42
|
-
const dictionaries =
|
|
41
|
+
const dictionaries = readDictionariesFromDisk(configuration.system.dictionariesDir);
|
|
43
42
|
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));
|
|
44
43
|
await Promise.all(uniqueMergedDictionaries.map(async (dictionary) => {
|
|
45
44
|
const mergedFilePath = normalize(join(configuration.system.dictionariesDir, `${dictionary.key}.json`));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanRemovedContentDeclaration.mjs","names":[],"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,YAAY,aAAa,cAAc;CAE7C,MAAM,uBAAuB,wBAAwB,cAAc;CAEnE,MAAM,UAAU,cAAc,OAAO;CAErC,MAAM,mBAAmB,SAAS,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,mBAAmB,UACvB,KACE,cAAc,OAAO,yBACrB,GAAG,WAAW,IAAI,OACnB,CACF;AAED,MAAI;GACF,MAAM,cAAc,MAAM,SAAS,kBAAkB,OAAO;GAC5D,MAAM,gBAAgB,KAAK,MAAM,YAAY;AAE7C,OAAI,cAAc,WAAW,GAC3B;QAAI,cAAc,GAAG,aAAa,kBAAkB;AAClD,eACE,gCAAgC,YAAY,WAAW,IAAI,IAC3D,EAAE,WAAW,MAAM,CACpB;AACD,mBAAc,KAAK,iBAAiB;AACpC,iBAAY,KAAK,WAAW,IAAI;;UAE7B;AAIL,UAAM,mBAAmB,kBAHD,cAAc,QACnC,YAAiB,QAAQ,aAAa,iBACxC,CAC0D;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,SAAS,SAAS,YAAY,mBAAmB,CACjE;AAED,UAAM,mBAAmB,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,gBAAgB,UACpB,KAAK,cAAc,OAAO,UAAU,GAAG,WAAW,IAAI,KAAK,CAC5D;AACD,kBAAc,KAAK,cAAc;;;GAGrC,CACH;AAGD,KAAI,cAAc,SAAS,KAAK,YAAY,SAAS,GAAG;AAEtD,QAAM,2BAA2B,eAAe,EAAE,aAAa,CAAC;AAGhE,MAAI,cAAc,SAAS,EACzB,OAAM,QAAQ,IACZ,cAAc,IAAI,OAAO,SAAS;GAChC,MAAM,eAAe,SAAS,SAAS,KAAK;AAC5C,OAAI;AACF,UAAM,GAAG,MAAM,EAAE,OAAO,MAAM,CAAC;AAE/B,cAAU,qBAAqB,aAAa,aAAa,IAAI,EAC3D,WAAW,MACZ,CAAC;WACI;AACN,cACE,6BAA6B,aAAa,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.mjs","names":[],"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,YAAY,aAAa,cAAc;CAE7C,MAAM,uBAAuB,yBAE3B,cAAc,OAAO,wBAAwB;CAE/C,MAAM,UAAU,cAAc,OAAO;CAErC,MAAM,mBAAmB,SAAS,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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Ac,SAAS,KAAK,YAAY,SAAS;EAC9D"}
|
|
@@ -45,7 +45,7 @@ const getIntlayerBundle = async (configuration) => {
|
|
|
45
45
|
const rootRequire = getProjectRequire(configuration.system.baseDir);
|
|
46
46
|
const configPackageRequire = configESMxCJSRequire;
|
|
47
47
|
const localRequire = isESModule ? createRequire(import.meta.url) : __require;
|
|
48
|
-
const configurationPath = join(configuration.system.configDir, `configuration.
|
|
48
|
+
const configurationPath = join(configuration.system.configDir, `configuration.cjs`);
|
|
49
49
|
const replaceModules = {
|
|
50
50
|
defu: configPackageRequire.resolve("defu"),
|
|
51
51
|
esbuild: configPackageRequire.resolve("esbuild"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIntlayerBundle.mjs","names":[],"sources":["../../../src/loadDictionaries/getIntlayerBundle.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { builtinModules, createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { bundleFile, type ESBuildPlugin } from '@intlayer/config/file';\nimport {\n configESMxCJSRequire,\n getProjectRequire,\n isESModule,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Rewrites selected bare specifiers (and any of their subpaths) to absolute file paths,\n * using the provided localeRequire (either createRequire(import.meta.url) or require).\n *\n * Example:\n * rewritePathsPlugin([\"@intlayer/config\", \"@intlayer/core\"], localeRequire)\n * …will also rewrite \"@intlayer/core/file\" etc.\n */\nconst rewritePathsPlugin = (\n replaceModules: Record<string, string>,\n excludeModules?: string[]\n): ESBuildPlugin => {\n return {\n name: 'rewrite-paths',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n const exact = replaceModules[args.path];\n\n if (excludeModules?.includes(args.path)) {\n return null;\n }\n\n if (exact) {\n return {\n path: exact,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n\n // Optional: support subpaths like \"@intlayer/core/xyz\"\n for (const key of Object.keys(replaceModules)) {\n if (args.path === key || args.path.startsWith(`${key}/`)) {\n const sub = args.path.slice(key.length); // '' or '/...'\n return {\n path: replaceModules[key] + sub,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n }\n });\n },\n };\n};\n\n/**\n * Get the intlayer bundle to embed @intlayer/core and be able to mock @intlayer/config/built to mock the configuration file.\n */\nexport const getIntlayerBundle = async (configuration: IntlayerConfig) => {\n const rootRequire = getProjectRequire(configuration.system.baseDir);\n const configPackageRequire = configESMxCJSRequire;\n const localRequire = isESModule ? createRequire(import.meta.url) : require;\n\n const configurationPath = join(\n configuration.system.configDir,\n `configuration.
|
|
1
|
+
{"version":3,"file":"getIntlayerBundle.mjs","names":[],"sources":["../../../src/loadDictionaries/getIntlayerBundle.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { builtinModules, createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { bundleFile, type ESBuildPlugin } from '@intlayer/config/file';\nimport {\n configESMxCJSRequire,\n getProjectRequire,\n isESModule,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Rewrites selected bare specifiers (and any of their subpaths) to absolute file paths,\n * using the provided localeRequire (either createRequire(import.meta.url) or require).\n *\n * Example:\n * rewritePathsPlugin([\"@intlayer/config\", \"@intlayer/core\"], localeRequire)\n * …will also rewrite \"@intlayer/core/file\" etc.\n */\nconst rewritePathsPlugin = (\n replaceModules: Record<string, string>,\n excludeModules?: string[]\n): ESBuildPlugin => {\n return {\n name: 'rewrite-paths',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n const exact = replaceModules[args.path];\n\n if (excludeModules?.includes(args.path)) {\n return null;\n }\n\n if (exact) {\n return {\n path: exact,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n\n // Optional: support subpaths like \"@intlayer/core/xyz\"\n for (const key of Object.keys(replaceModules)) {\n if (args.path === key || args.path.startsWith(`${key}/`)) {\n const sub = args.path.slice(key.length); // '' or '/...'\n return {\n path: replaceModules[key] + sub,\n namespace: 'intlayer-replace-modules',\n external: true, // ← prevents onLoad requirement\n };\n }\n }\n });\n },\n };\n};\n\n/**\n * Get the intlayer bundle to embed @intlayer/core and be able to mock @intlayer/config/built to mock the configuration file.\n */\nexport const getIntlayerBundle = async (configuration: IntlayerConfig) => {\n const rootRequire = getProjectRequire(configuration.system.baseDir);\n const configPackageRequire = configESMxCJSRequire;\n const localRequire = isESModule ? createRequire(import.meta.url) : require;\n\n const configurationPath = join(\n configuration.system.configDir,\n `configuration.cjs`\n );\n\n const replaceModules = {\n defu: configPackageRequire.resolve('defu'),\n esbuild: configPackageRequire.resolve('esbuild'),\n '@intlayer/config/built': configurationPath,\n '@intlayer/config/utils': localRequire.resolve('@intlayer/config/utils'),\n '@intlayer/config/client': localRequire.resolve('@intlayer/config/client'),\n '@intlayer/config/logger': localRequire.resolve('@intlayer/config/logger'),\n '@intlayer/core/file': localRequire.resolve('@intlayer/core/file'),\n };\n\n const filePath = rootRequire.resolve('intlayer');\n const code = await readFile(filePath, 'utf-8');\n\n const output = await bundleFile(code, filePath, {\n external: [\n ...builtinModules,\n ...builtinModules.map((mod) => `node:${mod}`),\n ],\n minify: true,\n plugins: [rewritePathsPlugin(replaceModules)],\n });\n\n return output ?? '';\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAM,sBACJ,gBACA,mBACkB;AAClB,QAAO;EACL,MAAM;EACN,MAAM,OAAO;AACX,SAAM,UAAU,EAAE,QAAQ,MAAM,GAAG,SAAS;IAC1C,MAAM,QAAQ,eAAe,KAAK;AAElC,QAAI,gBAAgB,SAAS,KAAK,KAAK,CACrC,QAAO;AAGT,QAAI,MACF,QAAO;KACL,MAAM;KACN,WAAW;KACX,UAAU;KACX;AAIH,SAAK,MAAM,OAAO,OAAO,KAAK,eAAe,CAC3C,KAAI,KAAK,SAAS,OAAO,KAAK,KAAK,WAAW,GAAG,IAAI,GAAG,EAAE;KACxD,MAAM,MAAM,KAAK,KAAK,MAAM,IAAI,OAAO;AACvC,YAAO;MACL,MAAM,eAAe,OAAO;MAC5B,WAAW;MACX,UAAU;MACX;;KAGL;;EAEL;;;;;AAMH,MAAa,oBAAoB,OAAO,kBAAkC;CACxE,MAAM,cAAc,kBAAkB,cAAc,OAAO,QAAQ;CACnE,MAAM,uBAAuB;CAC7B,MAAM,eAAe,aAAa,cAAc,OAAO,KAAK,IAAI;CAEhE,MAAM,oBAAoB,KACxB,cAAc,OAAO,WACrB,oBACD;CAED,MAAM,iBAAiB;EACrB,MAAM,qBAAqB,QAAQ,OAAO;EAC1C,SAAS,qBAAqB,QAAQ,UAAU;EAChD,0BAA0B;EAC1B,0BAA0B,aAAa,QAAQ,yBAAyB;EACxE,2BAA2B,aAAa,QAAQ,0BAA0B;EAC1E,2BAA2B,aAAa,QAAQ,0BAA0B;EAC1E,uBAAuB,aAAa,QAAQ,sBAAsB;EACnE;CAED,MAAM,WAAW,YAAY,QAAQ,WAAW;AAYhD,QATe,MAAM,WAFR,MAAM,SAAS,UAAU,QAAQ,EAER,UAAU;EAC9C,UAAU,CACR,GAAG,gBACH,GAAG,eAAe,KAAK,QAAQ,QAAQ,MAAM,CAC9C;EACD,QAAQ;EACR,SAAS,CAAC,mBAAmB,eAAe,CAAC;EAC9C,CAAC,IAEe"}
|
|
@@ -48,7 +48,7 @@ const loadContentDeclarations = async (contentDeclarationFilePath, configuration
|
|
|
48
48
|
try {
|
|
49
49
|
const dictionariesPromises = contentDeclarationFilePath.map(async (path) => {
|
|
50
50
|
return {
|
|
51
|
-
relativePath: relative(
|
|
51
|
+
relativePath: relative(system.baseDir, path),
|
|
52
52
|
dictionary: await loadContentDeclaration(path, configuration, bundleFilePath)
|
|
53
53
|
};
|
|
54
54
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadContentDeclaration.mjs","names":[],"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(
|
|
1
|
+
{"version":3,"file":"loadContentDeclaration.mjs","names":[],"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,YAAY,UAAU,eAAe,CAAC,kBAAkB,EAAE,EACrE,OAAO,MAAO,KAAK,KAAK,KAAK,GAC9B,CAAC;CAEF,MAAM,WAAW,KAAK,OAAO,UAAU,sBAAsB;AAG7D,KAAI,CAFsB,MAAM,SAAS,EAEjB;AAEtB,QAAM,U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CuB,MAAM,YAClC,qBACA,OAAO,uBAAwD;AAC7D,OAAI,CAAC,mBACH;AAGF,oBAAiB,CACf;IACE,eAAe,mBAAmB;IAClC,MAAM;IACN,QAAQ;IACT,CACF,CAAC;GAEF,MAAM,8BAA8B,MAAM,0BACxC,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,23 @@
|
|
|
1
|
+
import { basename, extname, join } from "node:path";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/readDictionariesFromDisk.ts
|
|
5
|
+
/**
|
|
6
|
+
* Reads all JSON dictionary files from a directory, keyed by filename.
|
|
7
|
+
* Uses readFileSync instead of require() to avoid require.cache memory leak.
|
|
8
|
+
*/
|
|
9
|
+
const readDictionariesFromDisk = (directory) => {
|
|
10
|
+
const dictionaries = {};
|
|
11
|
+
if (existsSync(directory)) {
|
|
12
|
+
const files = readdirSync(directory).filter((file) => file.endsWith(".json"));
|
|
13
|
+
for (const file of files) {
|
|
14
|
+
const key = basename(file, extname(file));
|
|
15
|
+
dictionaries[key] = JSON.parse(readFileSync(join(directory, file), "utf-8"));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return dictionaries;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
//#endregion
|
|
22
|
+
export { readDictionariesFromDisk };
|
|
23
|
+
//# sourceMappingURL=readDictionariesFromDisk.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readDictionariesFromDisk.mjs","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,KAAI,WAAW,UAAU,EAAE;EACzB,MAAM,QAAQ,YAAY,UAAU,CAAC,QAAQ,SAC3C,KAAK,SAAS,QAAQ,CACvB;AAED,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,MAAM,SAAS,MAAM,QAAQ,KAAK,CAAC;AACzC,gBAAa,OAAO,KAAK,MACvB,aAAa,KAAK,WAAW,KAAK,EAAE,QAAQ,CAC7C;;;AAIL,QAAO"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { buildBrowserConfiguration } from "@intlayer/config/node";
|
|
2
|
+
|
|
3
|
+
//#region src/writeConfiguration/generateConfigurationContent.ts
|
|
4
|
+
const generateConfigurationContent = (configuration, format) => {
|
|
5
|
+
const { internationalization, routing, editor, log, metadata } = buildBrowserConfiguration(configuration);
|
|
6
|
+
let content = "";
|
|
7
|
+
content += `const internationalization = ${JSON.stringify(internationalization, null, 2)};\n`;
|
|
8
|
+
content += `const routing = ${JSON.stringify(routing, null, 2)};\n`;
|
|
9
|
+
content += `const editor = ${JSON.stringify(editor, null, 2)};\n`;
|
|
10
|
+
content += `const log = ${JSON.stringify(log, null, 2)};\n`;
|
|
11
|
+
content += `const metadata = ${JSON.stringify(metadata, null, 2)};\n`;
|
|
12
|
+
content += `const configuration = { internationalization, routing, editor, log, metadata };\n`;
|
|
13
|
+
if (format === "esm") {
|
|
14
|
+
content += `\nexport { internationalization, routing, editor, log, metadata, configuration };\n`;
|
|
15
|
+
content += `export default configuration;\n`;
|
|
16
|
+
} else {
|
|
17
|
+
content += `\nmodule.exports.internationalization = internationalization;\n`;
|
|
18
|
+
content += `module.exports.routing = routing;\n`;
|
|
19
|
+
content += `module.exports.editor = editor;\n`;
|
|
20
|
+
content += `module.exports.log = log;\n`;
|
|
21
|
+
content += `module.exports.metadata = metadata;\n`;
|
|
22
|
+
content += `module.exports = configuration;\n`;
|
|
23
|
+
}
|
|
24
|
+
return content;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { generateConfigurationContent };
|
|
29
|
+
//# sourceMappingURL=generateConfigurationContent.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateConfigurationContent.mjs","names":[],"sources":["../../../src/writeConfiguration/generateConfigurationContent.ts"],"sourcesContent":["import { buildBrowserConfiguration } from '@intlayer/config/node';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const generateConfigurationContent = (\n configuration: IntlayerConfig,\n format: 'cjs' | 'esm'\n): string => {\n const { internationalization, routing, editor, log, metadata } =\n buildBrowserConfiguration(configuration);\n\n let content = '';\n\n content += `const internationalization = ${JSON.stringify(internationalization, null, 2)};\\n`;\n content += `const routing = ${JSON.stringify(routing, null, 2)};\\n`;\n content += `const editor = ${JSON.stringify(editor, null, 2)};\\n`;\n content += `const log = ${JSON.stringify(log, null, 2)};\\n`;\n content += `const metadata = ${JSON.stringify(metadata, null, 2)};\\n`;\n content += `const configuration = { internationalization, routing, editor, log, metadata };\\n`;\n\n if (format === 'esm') {\n content += `\\nexport { internationalization, routing, editor, log, metadata, configuration };\\n`;\n content += `export default configuration;\\n`;\n } else {\n content += `\\nmodule.exports.internationalization = internationalization;\\n`;\n content += `module.exports.routing = routing;\\n`;\n content += `module.exports.editor = editor;\\n`;\n content += `module.exports.log = log;\\n`;\n content += `module.exports.metadata = metadata;\\n`;\n content += `module.exports = configuration;\\n`;\n }\n\n return content;\n};\n"],"mappings":";;;AAGA,MAAa,gCACX,eACA,WACW;CACX,MAAM,EAAE,sBAAsB,SAAS,QAAQ,KAAK,aAClD,0BAA0B,cAAc;CAE1C,IAAI,UAAU;AAEd,YAAW,gCAAgC,KAAK,UAAU,sBAAsB,MAAM,EAAE,CAAC;AACzF,YAAW,mBAAmB,KAAK,UAAU,SAAS,MAAM,EAAE,CAAC;AAC/D,YAAW,kBAAkB,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;AAC7D,YAAW,eAAe,KAAK,UAAU,KAAK,MAAM,EAAE,CAAC;AACvD,YAAW,oBAAoB,KAAK,UAAU,UAAU,MAAM,EAAE,CAAC;AACjE,YAAW;AAEX,KAAI,WAAW,OAAO;AACpB,aAAW;AACX,aAAW;QACN;AACL,aAAW;AACX,aAAW;AACX,aAAW;AACX,aAAW;AACX,aAAW;AACX,aAAW;;AAGb,QAAO"}
|
|
@@ -1,38 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { writeFileIfChanged } from "../writeFileIfChanged.mjs";
|
|
2
|
+
import { generateConfigurationContent } from "./generateConfigurationContent.mjs";
|
|
2
3
|
import { mkdir, readFile } from "node:fs/promises";
|
|
3
4
|
import { join } from "node:path";
|
|
4
|
-
import { isDeepStrictEqual } from "node:util";
|
|
5
5
|
|
|
6
6
|
//#region src/writeConfiguration/index.ts
|
|
7
|
-
const getCachedConfiguration = async (configuration) => {
|
|
8
|
-
const configurationContent = await readFile(join(configuration.system.configDir, "configuration.json"), "utf8");
|
|
9
|
-
return JSON.parse(configurationContent);
|
|
10
|
-
};
|
|
11
7
|
const isCachedConfigurationUpToDate = async (configuration) => {
|
|
12
8
|
try {
|
|
13
|
-
|
|
14
|
-
return isDeepStrictEqual(await getCachedConfiguration(configuration), cleanedConfiguration);
|
|
9
|
+
return await readFile(join(configuration.system.configDir, "configuration.mjs"), "utf8") === generateConfigurationContent(configuration, "esm");
|
|
15
10
|
} catch {
|
|
16
11
|
return null;
|
|
17
12
|
}
|
|
18
13
|
};
|
|
19
|
-
const cleanConfiguration = (configuration) => {
|
|
20
|
-
return JSON.parse(JSON.stringify({
|
|
21
|
-
internationalization: {
|
|
22
|
-
locales: configuration.internationalization.locales,
|
|
23
|
-
defaultLocale: configuration.internationalization.defaultLocale
|
|
24
|
-
},
|
|
25
|
-
editor: configuration.editor,
|
|
26
|
-
log: configuration.log,
|
|
27
|
-
routing: configuration.routing,
|
|
28
|
-
metadata: configuration.metadata
|
|
29
|
-
}));
|
|
30
|
-
};
|
|
31
14
|
const writeConfiguration = async (configuration) => {
|
|
32
|
-
const {
|
|
33
|
-
const { configDir } = system;
|
|
15
|
+
const { configDir } = configuration.system;
|
|
34
16
|
await mkdir(configDir, { recursive: true });
|
|
35
|
-
await
|
|
17
|
+
await Promise.all([writeFileIfChanged(join(configDir, "configuration.mjs"), generateConfigurationContent(configuration, "esm")), writeFileIfChanged(join(configDir, "configuration.cjs"), generateConfigurationContent(configuration, "cjs"))]);
|
|
36
18
|
};
|
|
37
19
|
|
|
38
20
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { generateConfigurationContent } from './generateConfigurationContent';\n\nexport const isCachedConfigurationUpToDate = async (\n configuration: IntlayerConfig\n): Promise<boolean | null> => {\n try {\n const mjsPath = join(configuration.system.configDir, 'configuration.mjs');\n const existingContent = await readFile(mjsPath, 'utf8');\n const expectedContent = generateConfigurationContent(configuration, 'esm');\n return existingContent === expectedContent;\n } catch {\n return null; // Can crash if file doesn't exist yet or config is not defined\n }\n};\n\nexport const writeConfiguration = async (configuration: IntlayerConfig) => {\n const { configDir } = configuration.system;\n\n await mkdir(configDir, { recursive: true });\n\n await Promise.all([\n writeFileIfChanged(\n join(configDir, 'configuration.mjs'),\n generateConfigurationContent(configuration, 'esm')\n ),\n writeFileIfChanged(\n join(configDir, 'configuration.cjs'),\n generateConfigurationContent(configuration, 'cjs')\n ),\n ]);\n};\n"],"mappings":";;;;;;AAMA,MAAa,gCAAgC,OAC3C,kBAC4B;AAC5B,KAAI;AAIF,SAFwB,MAAM,SADd,KAAK,cAAc,OAAO,WAAW,oBAAoB,EACzB,OAAO,KAC/B,6BAA6B,eAAe,MAAM;SAEpE;AACN,SAAO;;;AAIX,MAAa,qBAAqB,OAAO,kBAAkC;CACzE,MAAM,EAAE,cAAc,cAAc;AAEpC,OAAM,MAAM,WAAW,EAAE,WAAW,MAAM,CAAC;AAE3C,OAAM,QAAQ,IAAI,CAChB,mBACE,KAAK,WAAW,oBAAoB,EACpC,6BAA6B,eAAe,MAAM,CACnD,EACD,mBACE,KAAK,WAAW,oBAAoB,EACpC,6BAA6B,eAAe,MAAM,CACnD,CACF,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readDictionariesFromDisk } from "../utils/readDictionariesFromDisk.mjs";
|
|
1
2
|
import { getFormatFromExtension } from "../utils/getFormatFromExtension.mjs";
|
|
2
3
|
import { detectFormatCommand } from "../detectFormatCommand.mjs";
|
|
3
4
|
import { processContentDeclarationContent } from "./processContentDeclarationContent.mjs";
|
|
@@ -5,7 +6,6 @@ import { transformJSONFile } from "./transformJSONFile.mjs";
|
|
|
5
6
|
import { writeJSFile } from "./writeJSFile.mjs";
|
|
6
7
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
7
8
|
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
8
|
-
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
9
9
|
import { existsSync } from "node:fs";
|
|
10
10
|
import { COMPILER_NO_METADATA } from "@intlayer/config/defaultValues";
|
|
11
11
|
import { getFilteredLocalesDictionary, getPerLocaleDictionary } from "@intlayer/core/plugins";
|
|
@@ -69,7 +69,7 @@ const writeContentDeclaration = async (dictionary, configuration, options) => {
|
|
|
69
69
|
...options
|
|
70
70
|
};
|
|
71
71
|
const newDictionaryLocationPath = join(baseDir, newDictionariesPath);
|
|
72
|
-
const existingDictionary =
|
|
72
|
+
const existingDictionary = readDictionariesFromDisk(configuration.system.unmergedDictionariesDir)[dictionary.key]?.find((el) => el.localId === dictionary.localId);
|
|
73
73
|
const formattedContentDeclaration = await formatContentDeclaration(dictionary, configuration, localeList);
|
|
74
74
|
if (existingDictionary?.filePath) {
|
|
75
75
|
const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeContentDeclaration.mjs","names":[],"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,MAAM,iCAAiC,WAAW;CAEpD,IAAI,UAAU,oBAAoB;;;;AAMlC,KAAI,WA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F,UAAM,GAAG,UAAU,EAAE,OAAO,MAAM,CAAC;WAC7B;AAGR,SAAM;;EAGR,MAAM,gBAAgB,oBAAoB,cAAc;AAExD,MAAI,cACF,KAAI;AACF,YAAS,cAAc,QAAQ,YAAY,iBAAiB,EAAE;IAC5D,OAAO;IACP,KAAK,cAAc,OAAO;IAC3B,CAAC;WACK,OAAO;AACd,WAAQ,MAAM,MAAM;;AAIxB;;AAGF,OAAM,YAAY,kBAAkB,YAAY,eAAe,WAAW;AAI1E,KAAI;AAKF,QAAM,GAJe,KACnB,cAAc,OAAO,UACrB,yBACD,EACsB,EAAE,WAAW,MAAM,CAAC;SACrC"}
|
|
1
|
+
{"version":3,"file":"writeContentDeclaration.mjs","names":[],"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,MAAM,iCAAiC,WAAW;CAEpD,IAAI,UAAU,oBAAoB;;;;AAMlC,KAAI,WAAW,OACb,WAAU,uBACR,qBACA,WAAW,OACZ,CAAC;UACO,WACT,WAAU,6BACR,qBACA,WACD,CAAC;CAGJ,IAAI,qBAA0B;EAC5B,GAAG;EACH;EACD;;;;AAMD,YAAW,MAAM,UAAU,cAAc,WAAW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iBAAiB,EAAE;IAC5D,OAAO;IACP,KAAK,cAAc,OAAO;IAC3B,CAAC;WACK,OAAO;AACd,WAAQ,MAAM,MAAM;;AAIxB;;AAGF,OAAM,YAAY,kBAAkB,YAAY,eAAe,WAAW;AAI1E,KAAI;AAKF,QAAM,GAJe,KACnB,cAAc,OAAO,UACrB,yBACD,EACsB,EAAE,WAAW,MAAM,CAAC;SACrC"}
|
package/dist/types/build.d.ts
CHANGED
|
@@ -16,10 +16,11 @@ import { ensureIntlayerBundle, formatLocalDictionaries, loadContentDeclaration,
|
|
|
16
16
|
import { loadLocalDictionaries } from "./loadDictionaries/loadLocalDictionaries.js";
|
|
17
17
|
import { formatDistantDictionaries, loadRemoteDictionaries } from "./loadDictionaries/loadRemoteDictionaries.js";
|
|
18
18
|
import { prepareIntlayer } from "./prepareIntlayer.js";
|
|
19
|
+
import { readDictionariesFromDisk } from "./utils/readDictionariesFromDisk.js";
|
|
19
20
|
import { isCachedConfigurationUpToDate, writeConfiguration } from "./writeConfiguration/index.js";
|
|
20
21
|
import { detectExportedComponentName } from "./writeContentDeclaration/detectExportedComponentName.js";
|
|
21
22
|
import { DictionaryStatus } from "./writeContentDeclaration/dictionaryStatus.js";
|
|
22
23
|
import { transformJSFile } from "./writeContentDeclaration/transformJSFile.js";
|
|
23
24
|
import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.js";
|
|
24
25
|
import { writeJSFile } from "./writeContentDeclaration/writeJSFile.js";
|
|
25
|
-
export { BuildDictionariesOptions, CreateDictionaryEntryPointOptions, DictionariesStatus, DictionaryStatus, 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 { BuildDictionariesOptions, CreateDictionaryEntryPointOptions, DictionariesStatus, DictionaryStatus, 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanRemovedContentDeclaration.d.ts","names":[],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"cleanRemovedContentDeclaration.d.ts","names":[],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"mappings":";;;cAea,8BAAA,GACX,QAAA,UACA,UAAA,YACA,aAAA,EAAe,cAAA,KACd,OAAA;EACD,2BAAA;EACA,WAAA;EACA,UAAA;AAAA"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/utils/readDictionariesFromDisk.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Reads all JSON dictionary files from a directory, keyed by filename.
|
|
4
|
+
* Uses readFileSync instead of require() to avoid require.cache memory leak.
|
|
5
|
+
*/
|
|
6
|
+
declare const readDictionariesFromDisk: <T = Record<string, any>>(directory: string) => T;
|
|
7
|
+
//#endregion
|
|
8
|
+
export { readDictionariesFromDisk };
|
|
9
|
+
//# sourceMappingURL=readDictionariesFromDisk.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readDictionariesFromDisk.d.ts","names":[],"sources":["../../../src/utils/readDictionariesFromDisk.ts"],"mappings":";;AAOA;;;cAAa,wBAAA,OAAgC,MAAA,eAC3C,SAAA,aACC,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { IntlayerConfig } from "@intlayer/types/config";
|
|
2
|
+
|
|
3
|
+
//#region src/writeConfiguration/generateConfigurationContent.d.ts
|
|
4
|
+
declare const generateConfigurationContent: (configuration: IntlayerConfig, format: "cjs" | "esm") => string;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { generateConfigurationContent };
|
|
7
|
+
//# sourceMappingURL=generateConfigurationContent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateConfigurationContent.d.ts","names":[],"sources":["../../../src/writeConfiguration/generateConfigurationContent.ts"],"mappings":";;;cAGa,4BAAA,GACX,aAAA,EAAe,cAAA,EACf,MAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/writeConfiguration/index.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/writeConfiguration/index.ts"],"mappings":";;;cAMa,6BAAA,GACX,aAAA,EAAe,cAAA,KACd,OAAA;AAAA,cAWU,kBAAA,GAA4B,aAAA,EAAe,cAAA,KAAc,OAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/chokidar",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.5.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Uses chokidar to scan and build Intlayer declaration files into dictionaries based on Intlayer configuration.",
|
|
6
6
|
"keywords": [
|
|
@@ -110,13 +110,13 @@
|
|
|
110
110
|
},
|
|
111
111
|
"dependencies": {
|
|
112
112
|
"@babel/parser": "7.29.0",
|
|
113
|
-
"@intlayer/api": "8.
|
|
114
|
-
"@intlayer/config": "8.
|
|
115
|
-
"@intlayer/core": "8.
|
|
116
|
-
"@intlayer/dictionaries-entry": "8.
|
|
117
|
-
"@intlayer/remote-dictionaries-entry": "8.
|
|
118
|
-
"@intlayer/types": "8.
|
|
119
|
-
"@intlayer/unmerged-dictionaries-entry": "8.
|
|
113
|
+
"@intlayer/api": "8.5.0",
|
|
114
|
+
"@intlayer/config": "8.5.0",
|
|
115
|
+
"@intlayer/core": "8.5.0",
|
|
116
|
+
"@intlayer/dictionaries-entry": "8.5.0",
|
|
117
|
+
"@intlayer/remote-dictionaries-entry": "8.5.0",
|
|
118
|
+
"@intlayer/types": "8.5.0",
|
|
119
|
+
"@intlayer/unmerged-dictionaries-entry": "8.5.0",
|
|
120
120
|
"chokidar": "3.6.0",
|
|
121
121
|
"defu": "6.1.4",
|
|
122
122
|
"fast-glob": "3.3.3",
|
|
@@ -131,8 +131,8 @@
|
|
|
131
131
|
"@utils/tsdown-config": "1.0.4",
|
|
132
132
|
"rimraf": "6.1.3",
|
|
133
133
|
"tsdown": "0.21.4",
|
|
134
|
-
"typescript": "
|
|
135
|
-
"vitest": "4.1.
|
|
134
|
+
"typescript": "6.0.2",
|
|
135
|
+
"vitest": "4.1.1",
|
|
136
136
|
"zod": "4.3.6"
|
|
137
137
|
},
|
|
138
138
|
"engines": {
|