@intlayer/chokidar 7.2.3 → 7.3.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/README.md +2 -0
- package/dist/cjs/index.cjs +12 -12
- package/dist/cjs/listDictionariesPath.cjs +9 -0
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +9 -2
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/transformFiles/extractDictionaryKey.cjs +16 -0
- package/dist/cjs/transformFiles/extractDictionaryKey.cjs.map +1 -0
- package/dist/cjs/transformFiles/index.cjs +6 -0
- package/dist/cjs/transformFiles/transformFiles.cjs +218 -0
- package/dist/cjs/transformFiles/transformFiles.cjs.map +1 -0
- package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs +16 -14
- package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +1 -1
- package/dist/esm/index.mjs +10 -9
- package/dist/esm/listDictionariesPath.mjs +9 -1
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs +10 -3
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/transformFiles/extractDictionaryKey.mjs +15 -0
- package/dist/esm/transformFiles/extractDictionaryKey.mjs.map +1 -0
- package/dist/esm/transformFiles/index.mjs +4 -0
- package/dist/esm/transformFiles/transformFiles.mjs +215 -0
- package/dist/esm/transformFiles/transformFiles.mjs.map +1 -0
- package/dist/esm/writeContentDeclaration/detectFormatCommand.mjs +16 -14
- package/dist/esm/writeContentDeclaration/detectFormatCommand.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs +1 -1
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts +2 -2
- package/dist/types/buildIntlayerDictionary/writeRemoteDictionary.d.ts +2 -2
- package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts +2 -2
- package/dist/types/index.d.ts +5 -3
- package/dist/types/listDictionariesPath.d.ts +6 -1
- package/dist/types/listDictionariesPath.d.ts.map +1 -1
- package/dist/types/prepareIntlayer.d.ts.map +1 -1
- package/dist/types/transformFiles/extractDictionaryKey.d.ts +5 -0
- package/dist/types/transformFiles/extractDictionaryKey.d.ts.map +1 -0
- package/dist/types/transformFiles/index.d.ts +3 -0
- package/dist/types/transformFiles/transformFiles.d.ts +16 -0
- package/dist/types/transformFiles/transformFiles.d.ts.map +1 -0
- package/package.json +21 -12
- package/dist/cjs/compiler/extractDictionaryKey.cjs +0 -38
- package/dist/cjs/compiler/extractDictionaryKey.cjs.map +0 -1
- package/dist/cjs/compiler/index.cjs +0 -225
- package/dist/cjs/compiler/index.cjs.map +0 -1
- package/dist/esm/compiler/extractDictionaryKey.mjs +0 -36
- package/dist/esm/compiler/extractDictionaryKey.mjs.map +0 -1
- package/dist/esm/compiler/index.mjs +0 -219
- package/dist/esm/compiler/index.mjs.map +0 -1
- package/dist/types/compiler/extractDictionaryKey.d.ts +0 -13
- package/dist/types/compiler/extractDictionaryKey.d.ts.map +0 -1
- package/dist/types/compiler/index.d.ts +0 -36
- package/dist/types/compiler/index.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
<a href="https://github.com/aymericzip/intlayer/blob/main/LICENSE" target="_blank" rel="noopener noreferrer nofollow"><img src="https://img.shields.io/github/license/aymericzip/intlayer?style=for-the-badge&labelColor=000000&color=FFFFFF&logoColor=000000&cacheSeconds=86400" alt="license"/></a>
|
|
25
25
|
<a href="https://github.com/aymericzip/intlayer/commits/main" target="_blank" rel="noopener noreferrer nofollow"><img src="https://img.shields.io/github/last-commit/aymericzip/intlayer?style=for-the-badge&labelColor=000000&color=FFFFFF&logoColor=000000&cacheSeconds=86400" alt="last commit"/>
|
|
26
26
|
</a>
|
|
27
|
+
<a href="https://bountyhub.dev/bounties?repo=intlayer" target="_blank" rel="noopener noreferrer nofollow"><img src="https://img.shields.io/badge/Bounties-on%20BountyHub-yellow?style=for-the-badge&labelColor=000000&color=FFFFFF&logoColor=000000&cacheSeconds=86400" alt="Bounties on BountyHub"/>
|
|
28
|
+
</a>
|
|
27
29
|
</p>
|
|
28
30
|
|
|
29
31
|

|
package/dist/cjs/index.cjs
CHANGED
|
@@ -22,14 +22,7 @@ const require_handleAdditionalContentDeclarationFile = require('./handleAddition
|
|
|
22
22
|
const require_handleContentDeclarationFileChange = require('./handleContentDeclarationFileChange.cjs');
|
|
23
23
|
const require_listDictionariesPath = require('./listDictionariesPath.cjs');
|
|
24
24
|
const require_handleUnlinkedContentDeclarationFile = require('./handleUnlinkedContentDeclarationFile.cjs');
|
|
25
|
-
const require_writeContentDeclaration_detectExportedComponentName = require('./writeContentDeclaration/detectExportedComponentName.cjs');
|
|
26
|
-
const require_writeContentDeclaration_transformJSFile = require('./writeContentDeclaration/transformJSFile.cjs');
|
|
27
|
-
const require_utils_getFormatFromExtension = require('./utils/getFormatFromExtension.cjs');
|
|
28
25
|
const require_getContentDeclarationFileTemplate_getContentDeclarationFileTemplate = require('./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs');
|
|
29
|
-
const require_writeContentDeclaration_detectFormatCommand = require('./writeContentDeclaration/detectFormatCommand.cjs');
|
|
30
|
-
const require_writeContentDeclaration_writeJSFile = require('./writeContentDeclaration/writeJSFile.cjs');
|
|
31
|
-
const require_writeContentDeclaration_writeContentDeclaration = require('./writeContentDeclaration/writeContentDeclaration.cjs');
|
|
32
|
-
const require_compiler_index = require('./compiler/index.cjs');
|
|
33
26
|
const require_listGitFiles = require('./listGitFiles.cjs');
|
|
34
27
|
const require_utils_sortAlphabetically = require('./utils/sortAlphabetically.cjs');
|
|
35
28
|
const require_loadDictionaries_loadRemoteDictionaries = require('./loadDictionaries/loadRemoteDictionaries.cjs');
|
|
@@ -37,6 +30,14 @@ const require_loadDictionaries_loadDictionaries = require('./loadDictionaries/lo
|
|
|
37
30
|
const require_utils_runOnce = require('./utils/runOnce.cjs');
|
|
38
31
|
const require_prepareIntlayer = require('./prepareIntlayer.cjs');
|
|
39
32
|
const require_reduceDictionaryContent_reduceDictionaryContent = require('./reduceDictionaryContent/reduceDictionaryContent.cjs');
|
|
33
|
+
const require_writeContentDeclaration_detectExportedComponentName = require('./writeContentDeclaration/detectExportedComponentName.cjs');
|
|
34
|
+
const require_transformFiles_extractDictionaryKey = require('./transformFiles/extractDictionaryKey.cjs');
|
|
35
|
+
const require_writeContentDeclaration_transformJSFile = require('./writeContentDeclaration/transformJSFile.cjs');
|
|
36
|
+
const require_utils_getFormatFromExtension = require('./utils/getFormatFromExtension.cjs');
|
|
37
|
+
const require_writeContentDeclaration_detectFormatCommand = require('./writeContentDeclaration/detectFormatCommand.cjs');
|
|
38
|
+
const require_writeContentDeclaration_writeJSFile = require('./writeContentDeclaration/writeJSFile.cjs');
|
|
39
|
+
const require_writeContentDeclaration_writeContentDeclaration = require('./writeContentDeclaration/writeContentDeclaration.cjs');
|
|
40
|
+
const require_transformFiles_transformFiles = require('./transformFiles/transformFiles.cjs');
|
|
40
41
|
const require_utils_splitTextByLine = require('./utils/splitTextByLine.cjs');
|
|
41
42
|
const require_utils_getChunk = require('./utils/getChunk.cjs');
|
|
42
43
|
const require_utils_chunkJSON = require('./utils/chunkJSON.cjs');
|
|
@@ -56,8 +57,8 @@ exports.createModuleAugmentation = require_createType_createModuleAugmentation.c
|
|
|
56
57
|
exports.createTypes = require_createType_createType.createTypes;
|
|
57
58
|
exports.detectExportedComponentName = require_writeContentDeclaration_detectExportedComponentName.detectExportedComponentName;
|
|
58
59
|
exports.detectFormatCommand = require_writeContentDeclaration_detectFormatCommand.detectFormatCommand;
|
|
59
|
-
exports.
|
|
60
|
-
exports.extractIntlayer =
|
|
60
|
+
exports.extractDictionaryKey = require_transformFiles_extractDictionaryKey.extractDictionaryKey;
|
|
61
|
+
exports.extractIntlayer = require_transformFiles_transformFiles.extractIntlayer;
|
|
61
62
|
exports.fetchDistantDictionaries = require_fetchDistantDictionaries.fetchDistantDictionaries;
|
|
62
63
|
exports.formatLocale = require_utils_formatter.formatLocale;
|
|
63
64
|
exports.formatPath = require_utils_formatter.formatPath;
|
|
@@ -79,6 +80,7 @@ exports.handleContentDeclarationFileChange = require_handleContentDeclarationFil
|
|
|
79
80
|
exports.handleUnlinkedContentDeclarationFile = require_handleUnlinkedContentDeclarationFile.handleUnlinkedContentDeclarationFile;
|
|
80
81
|
exports.isInvalidDictionary = require_filterInvalidDictionaries.isInvalidDictionary;
|
|
81
82
|
exports.listDictionaries = require_listDictionariesPath.listDictionaries;
|
|
83
|
+
exports.listDictionariesWithStats = require_listDictionariesPath.listDictionariesWithStats;
|
|
82
84
|
exports.listGitFiles = require_listGitFiles.listGitFiles;
|
|
83
85
|
exports.listGitLines = require_listGitFiles.listGitLines;
|
|
84
86
|
exports.loadContentDeclarations = require_loadDictionaries_loadContentDeclaration.loadContentDeclarations;
|
|
@@ -97,11 +99,9 @@ exports.runOnce = require_utils_runOnce.runOnce;
|
|
|
97
99
|
exports.runParallel = require_utils_runParallel_index.runParallel;
|
|
98
100
|
exports.sortAlphabetically = require_utils_sortAlphabetically.sortAlphabetically;
|
|
99
101
|
exports.splitTextByLines = require_utils_splitTextByLine.splitTextByLines;
|
|
100
|
-
exports.
|
|
101
|
-
exports.transformFiles = require_compiler_index.transformFiles;
|
|
102
|
+
exports.transformFiles = require_transformFiles_transformFiles.transformFiles;
|
|
102
103
|
exports.transformJSFile = require_writeContentDeclaration_transformJSFile.transformJSFile;
|
|
103
104
|
exports.verifyIdenticObjectFormat = require_utils_verifyIdenticObjectFormat.verifyIdenticObjectFormat;
|
|
104
105
|
exports.watch = require_watcher.watch;
|
|
105
|
-
exports.writeContent = require_compiler_index.writeContent;
|
|
106
106
|
exports.writeContentDeclaration = require_writeContentDeclaration_writeContentDeclaration.writeContentDeclaration;
|
|
107
107
|
exports.writeJSFile = require_writeContentDeclaration_writeJSFile.writeJSFile;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_fs_promises = require("node:fs/promises");
|
|
2
3
|
let fast_glob = require("fast-glob");
|
|
3
4
|
fast_glob = require_rolldown_runtime.__toESM(fast_glob);
|
|
4
5
|
|
|
@@ -11,7 +12,15 @@ fast_glob = require_rolldown_runtime.__toESM(fast_glob);
|
|
|
11
12
|
const listDictionaries = async (configuration) => {
|
|
12
13
|
return await (0, fast_glob.default)(configuration.content.watchedFilesPatternWithPath, { ignore: configuration.content.excludedPath });
|
|
13
14
|
};
|
|
15
|
+
const listDictionariesWithStats = async (configuration) => {
|
|
16
|
+
const files = await listDictionaries(configuration);
|
|
17
|
+
return Promise.all(files.map(async (file) => ({
|
|
18
|
+
path: file,
|
|
19
|
+
stats: await (0, node_fs_promises.stat)(file)
|
|
20
|
+
})));
|
|
21
|
+
};
|
|
14
22
|
|
|
15
23
|
//#endregion
|
|
16
24
|
exports.listDictionaries = listDictionaries;
|
|
25
|
+
exports.listDictionariesWithStats = listDictionariesWithStats;
|
|
17
26
|
//# sourceMappingURL=listDictionariesPath.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listDictionariesPath.cjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const files: string[] = await fg(\n configuration.content.watchedFilesPatternWithPath,\n {\n ignore: configuration.content.excludedPath,\n }\n );\n\n return files;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"listDictionariesPath.cjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const files: string[] = await fg(\n configuration.content.watchedFilesPatternWithPath,\n {\n ignore: configuration.content.excludedPath,\n }\n );\n\n return files;\n};\n\nexport const listDictionariesWithStats = async (\n configuration: IntlayerConfig\n) => {\n const files = await listDictionaries(configuration);\n\n return Promise.all(\n files.map(async (file) => ({ path: file, stats: await stat(file) }))\n );\n};\n"],"mappings":";;;;;;;;;;;AASA,MAAa,mBAAmB,OAC9B,kBACsB;AAQtB,QAPwB,6BACtB,cAAc,QAAQ,6BACtB,EACE,QAAQ,cAAc,QAAQ,cAC/B,CACF;;AAKH,MAAa,4BAA4B,OACvC,kBACG;CACH,MAAM,QAAQ,MAAM,iBAAiB,cAAc;AAEnD,QAAO,QAAQ,IACb,MAAM,IAAI,OAAO,UAAU;EAAE,MAAM;EAAM,OAAO,iCAAW,KAAK;EAAE,EAAE,CACrE"}
|
|
@@ -9,6 +9,7 @@ const require_loadDictionaries_loadDictionaries = require('./loadDictionaries/lo
|
|
|
9
9
|
const require_buildIntlayerDictionary_writeRemoteDictionary = require('./buildIntlayerDictionary/writeRemoteDictionary.cjs');
|
|
10
10
|
const require_utils_runOnce = require('./utils/runOnce.cjs');
|
|
11
11
|
const require_writeConfiguration_index = require('./writeConfiguration/index.cjs');
|
|
12
|
+
let node_fs_promises = require("node:fs/promises");
|
|
12
13
|
let __intlayer_config = require("@intlayer/config");
|
|
13
14
|
let node_path = require("node:path");
|
|
14
15
|
let __intlayer_config_package_json = require("@intlayer/config/package.json");
|
|
@@ -27,9 +28,15 @@ const prepareIntlayer = async (configuration, options) => {
|
|
|
27
28
|
const intlayerCacheVersion = await versionCache.get();
|
|
28
29
|
const isCorrectVersion = Boolean(intlayerCacheVersion && intlayerCacheVersion === __intlayer_config_package_json.default.version);
|
|
29
30
|
const isConfigSimilar = await require_writeConfiguration_index.isCachedConfigurationUpToDate(configuration);
|
|
31
|
+
const dictionariesWithStats = await require_listDictionariesPath.listDictionariesWithStats(configuration);
|
|
32
|
+
let isDictionaryChanged = false;
|
|
33
|
+
try {
|
|
34
|
+
const sentinelStats = await (0, node_fs_promises.stat)(sentinelPath);
|
|
35
|
+
isDictionaryChanged = dictionariesWithStats.some((dictionary) => dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime());
|
|
36
|
+
} catch {}
|
|
30
37
|
const { clean, format, forceRun, onIsCached, cacheTimeoutMs } = {
|
|
31
38
|
...DEFAULT_PREPARE_INTLAYER_OPTIONS,
|
|
32
|
-
forceRun: !isCorrectVersion || !isConfigSimilar,
|
|
39
|
+
forceRun: !isCorrectVersion || !isConfigSimilar || isDictionaryChanged,
|
|
33
40
|
...options ?? {}
|
|
34
41
|
};
|
|
35
42
|
await require_utils_runOnce.runOnce(sentinelPath, async () => {
|
|
@@ -40,7 +47,7 @@ const prepareIntlayer = async (configuration, options) => {
|
|
|
40
47
|
await require_writeConfiguration_index.writeConfiguration(configuration);
|
|
41
48
|
const configurationWrittenTime = Date.now();
|
|
42
49
|
appLogger(["Configuration written", (0, __intlayer_config.colorize)(`(${configurationWrittenTime - preparationStartMs}ms)`, __intlayer_config.ANSIColors.GREY_DARK)], { isVerbose: true });
|
|
43
|
-
const dictionaries = await require_loadDictionaries_loadDictionaries.loadDictionaries(
|
|
50
|
+
const dictionaries = await require_loadDictionaries_loadDictionaries.loadDictionaries(dictionariesWithStats.map((dictionary) => dictionary.path), configuration);
|
|
44
51
|
const dictionariesLoadedTime = Date.now();
|
|
45
52
|
appLogger(["Content loaded", (0, __intlayer_config.colorize)([dictionaries.remoteDictionaries.length + dictionaries.pluginDictionaries.length > 0 ? [
|
|
46
53
|
`(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","
|
|
1
|
+
{"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n ANSIColors,\n cacheDisk,\n // checkVersionsConsistency,\n colorize,\n getAppLogger,\n} from '@intlayer/config';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.content.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun: !isCorrectVersion || !isConfigSimilar || isDictionaryChanged,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? `- Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? `- Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? `- Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n format,\n false\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesPaths = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionaryPath);\n\n await createTypes(dictionariesPaths, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`,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ACxB,cAAc;KACZ;KACA;KACD;IACD;IACD,CAAC;;AAIJ,YACE,CAAC,wCAAiB,GAFS,KAAK,KAAK,GAAG,mBAEE,KAAKA,6BAAW,MAAM,CAAC,EACjE;GACE,OAAO;GACP,WAAW;GACZ,CACF;IAEH;EACE;EACA;EACA;EACD,CACF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_writeContentDeclaration_detectExportedComponentName = require('../writeContentDeclaration/detectExportedComponentName.cjs');
|
|
3
|
+
let node_path = require("node:path");
|
|
4
|
+
|
|
5
|
+
//#region src/transformFiles/extractDictionaryKey.ts
|
|
6
|
+
const extractDictionaryKey = (filePath, fileText) => {
|
|
7
|
+
const componentName = require_writeContentDeclaration_detectExportedComponentName.detectExportedComponentName(fileText);
|
|
8
|
+
if (componentName) return componentName;
|
|
9
|
+
let baseName = (0, node_path.basename)(filePath, (0, node_path.extname)(filePath));
|
|
10
|
+
if (baseName === "index") baseName = (0, node_path.basename)((0, node_path.dirname)(filePath));
|
|
11
|
+
return baseName;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
exports.extractDictionaryKey = extractDictionaryKey;
|
|
16
|
+
//# sourceMappingURL=extractDictionaryKey.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extractDictionaryKey.cjs","names":["detectExportedComponentName"],"sources":["../../../src/transformFiles/extractDictionaryKey.ts"],"sourcesContent":["import { basename, dirname, extname } from 'node:path';\nimport { detectExportedComponentName } from '../writeContentDeclaration/detectExportedComponentName';\n\nexport const extractDictionaryKey = (\n filePath: string,\n fileText: string\n): string => {\n const componentName = detectExportedComponentName(fileText);\n if (componentName) {\n return componentName;\n }\n\n const ext = extname(filePath);\n let baseName = basename(filePath, ext);\n\n if (baseName === 'index') {\n baseName = basename(dirname(filePath));\n }\n\n return baseName;\n};\n"],"mappings":";;;;;AAGA,MAAa,wBACX,UACA,aACW;CACX,MAAM,gBAAgBA,wFAA4B,SAAS;AAC3D,KAAI,cACF,QAAO;CAIT,IAAI,mCAAoB,iCADJ,SAAS,CACS;AAEtC,KAAI,aAAa,QACf,2DAA4B,SAAS,CAAC;AAGxC,QAAO"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
const require_transformFiles_extractDictionaryKey = require('./extractDictionaryKey.cjs');
|
|
2
|
+
const require_transformFiles_transformFiles = require('./transformFiles.cjs');
|
|
3
|
+
|
|
4
|
+
exports.extractDictionaryKey = require_transformFiles_extractDictionaryKey.extractDictionaryKey;
|
|
5
|
+
exports.extractIntlayer = require_transformFiles_transformFiles.extractIntlayer;
|
|
6
|
+
exports.transformFiles = require_transformFiles_transformFiles.transformFiles;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_transformFiles_extractDictionaryKey = require('./extractDictionaryKey.cjs');
|
|
3
|
+
const require_writeContentDeclaration_detectFormatCommand = require('../writeContentDeclaration/detectFormatCommand.cjs');
|
|
4
|
+
const require_writeContentDeclaration_writeContentDeclaration = require('../writeContentDeclaration/writeContentDeclaration.cjs');
|
|
5
|
+
let node_fs_promises = require("node:fs/promises");
|
|
6
|
+
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
7
|
+
let __intlayer_config = require("@intlayer/config");
|
|
8
|
+
let node_path = require("node:path");
|
|
9
|
+
let node_child_process = require("node:child_process");
|
|
10
|
+
let ts_morph = require("ts-morph");
|
|
11
|
+
|
|
12
|
+
//#region src/transformFiles/transformFiles.ts
|
|
13
|
+
const ATTRIBUTES_TO_EXTRACT = [
|
|
14
|
+
"title",
|
|
15
|
+
"placeholder",
|
|
16
|
+
"alt",
|
|
17
|
+
"aria-label",
|
|
18
|
+
"label"
|
|
19
|
+
];
|
|
20
|
+
const shouldExtract = (text) => {
|
|
21
|
+
const trimmed = text.trim();
|
|
22
|
+
if (!trimmed) return false;
|
|
23
|
+
if (!trimmed.includes(" ")) return false;
|
|
24
|
+
if (!/^[A-Z]/.test(trimmed)) return false;
|
|
25
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("v-")) return false;
|
|
26
|
+
return true;
|
|
27
|
+
};
|
|
28
|
+
const generateKey = (text, existingKeys) => {
|
|
29
|
+
let key = text.replace(/\s+/g, " ").replace(/_+/g, " ").replace(/-+/g, " ").replace(/[^a-zA-Z0-9 ]/g, "").trim().split(" ").filter(Boolean).slice(0, 5).map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
|
|
30
|
+
if (!key) key = "content";
|
|
31
|
+
if (existingKeys.has(key)) {
|
|
32
|
+
let i = 1;
|
|
33
|
+
while (existingKeys.has(`${key}${i}`)) i++;
|
|
34
|
+
key = `${key}${i}`;
|
|
35
|
+
}
|
|
36
|
+
return key;
|
|
37
|
+
};
|
|
38
|
+
const writeContentHelper = async (extractedContent, componentKey, filePath, configuration, outputDir) => {
|
|
39
|
+
const { defaultLocale } = configuration.internationalization;
|
|
40
|
+
const { baseDir } = configuration.content;
|
|
41
|
+
const dirName = outputDir ? (0, node_path.resolve)(outputDir) : (0, node_path.dirname)(filePath);
|
|
42
|
+
const baseName = (0, node_path.basename)(filePath, (0, node_path.extname)(filePath));
|
|
43
|
+
const contentFilePath = (0, node_path.join)(dirName, `${baseName.charAt(0).toLowerCase() + baseName.slice(1)}.content.ts`);
|
|
44
|
+
await require_writeContentDeclaration_writeContentDeclaration.writeContentDeclaration({
|
|
45
|
+
key: componentKey,
|
|
46
|
+
content: extractedContent,
|
|
47
|
+
locale: defaultLocale,
|
|
48
|
+
filePath: (0, node_path.relative)(baseDir, contentFilePath)
|
|
49
|
+
}, configuration, { newDictionariesPath: (0, node_path.relative)(baseDir, dirName) });
|
|
50
|
+
return contentFilePath;
|
|
51
|
+
};
|
|
52
|
+
const extractTsContent = (sourceFile, existingKeys) => {
|
|
53
|
+
const extractedContent = {};
|
|
54
|
+
const replacements = [];
|
|
55
|
+
sourceFile.forEachDescendant((node) => {
|
|
56
|
+
if (ts_morph.Node.isJsxText(node)) {
|
|
57
|
+
const text = node.getText();
|
|
58
|
+
if (shouldExtract(text)) {
|
|
59
|
+
const key = generateKey(text, existingKeys);
|
|
60
|
+
existingKeys.add(key);
|
|
61
|
+
extractedContent[key] = text.replace(/\s+/g, " ").trim();
|
|
62
|
+
replacements.push({
|
|
63
|
+
node,
|
|
64
|
+
key,
|
|
65
|
+
type: "jsx-text"
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
} else if (ts_morph.Node.isJsxAttribute(node)) {
|
|
69
|
+
const name = node.getNameNode().getText();
|
|
70
|
+
if (ATTRIBUTES_TO_EXTRACT.includes(name)) {
|
|
71
|
+
const initializer = node.getInitializer();
|
|
72
|
+
if (ts_morph.Node.isStringLiteral(initializer)) {
|
|
73
|
+
const text = initializer.getLiteralValue();
|
|
74
|
+
if (shouldExtract(text)) {
|
|
75
|
+
const key = generateKey(text, existingKeys);
|
|
76
|
+
existingKeys.add(key);
|
|
77
|
+
extractedContent[key] = text.trim();
|
|
78
|
+
replacements.push({
|
|
79
|
+
node,
|
|
80
|
+
key,
|
|
81
|
+
type: "jsx-attribute"
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
} else if (ts_morph.Node.isStringLiteral(node)) {
|
|
87
|
+
const text = node.getLiteralValue();
|
|
88
|
+
if (shouldExtract(text)) {
|
|
89
|
+
const parent = node.getParent();
|
|
90
|
+
if (parent?.getKindName() === "ImportDeclaration" || parent?.getKindName() === "ImportSpecifier" || parent?.getKindName() === "ModuleSpecifier") return;
|
|
91
|
+
if (ts_morph.Node.isJsxAttribute(parent)) return;
|
|
92
|
+
if (ts_morph.Node.isCallExpression(parent)) {
|
|
93
|
+
if (parent.getExpression().getText().includes("console.log")) return;
|
|
94
|
+
}
|
|
95
|
+
if (ts_morph.Node.isPropertyAssignment(parent)) {
|
|
96
|
+
if (parent.getNameNode() === node) return;
|
|
97
|
+
}
|
|
98
|
+
const key = generateKey(text, existingKeys);
|
|
99
|
+
existingKeys.add(key);
|
|
100
|
+
extractedContent[key] = text.trim();
|
|
101
|
+
replacements.push({
|
|
102
|
+
node,
|
|
103
|
+
key,
|
|
104
|
+
type: "string-literal"
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
return {
|
|
110
|
+
extractedContent,
|
|
111
|
+
replacements
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
const processReactFile = async (filePath, componentKey, packageName, project, save = true) => {
|
|
115
|
+
let sourceFile;
|
|
116
|
+
try {
|
|
117
|
+
sourceFile = project.addSourceFileAtPath(filePath);
|
|
118
|
+
} catch {
|
|
119
|
+
sourceFile = project.getSourceFileOrThrow(filePath);
|
|
120
|
+
}
|
|
121
|
+
const { extractedContent, replacements } = extractTsContent(sourceFile, /* @__PURE__ */ new Set());
|
|
122
|
+
if (Object.keys(extractedContent).length === 0) return null;
|
|
123
|
+
for (const { node, key, type } of replacements) if (type === "jsx-text" && ts_morph.Node.isJsxText(node)) node.replaceWithText(`{content.${key}}`);
|
|
124
|
+
else if (type === "jsx-attribute" && ts_morph.Node.isJsxAttribute(node)) node.setInitializer(`{content.${key}.value}`);
|
|
125
|
+
else if (type === "string-literal" && ts_morph.Node.isStringLiteral(node)) node.replaceWithText(`content.${key}.value`);
|
|
126
|
+
const importDecl = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === packageName);
|
|
127
|
+
if (!importDecl) sourceFile.addImportDeclaration({
|
|
128
|
+
namedImports: ["useIntlayer"],
|
|
129
|
+
moduleSpecifier: packageName
|
|
130
|
+
});
|
|
131
|
+
else if (!importDecl.getNamedImports().some((n) => n.getName() === "useIntlayer")) importDecl.addNamedImport("useIntlayer");
|
|
132
|
+
sourceFile.getFunctions().forEach((f) => {
|
|
133
|
+
f.getBody()?.asKind(ts_morph.SyntaxKind.Block)?.insertStatements(0, `const content = useIntlayer("${componentKey}");`);
|
|
134
|
+
});
|
|
135
|
+
sourceFile.getVariableDeclarations().forEach((v) => {
|
|
136
|
+
const init = v.getInitializer();
|
|
137
|
+
if (ts_morph.Node.isArrowFunction(init) || ts_morph.Node.isFunctionExpression(init)) {
|
|
138
|
+
const body = init.getBody();
|
|
139
|
+
if (ts_morph.Node.isBlock(body)) {
|
|
140
|
+
if (body.getText().includes("return") || body.getText().includes("use")) body.insertStatements(0, `const content = useIntlayer("${componentKey}");`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
if (save) await sourceFile.save();
|
|
145
|
+
return extractedContent;
|
|
146
|
+
};
|
|
147
|
+
const extractIntlayer = async (filePath, packageName, options, project) => {
|
|
148
|
+
const saveComponent = !options?.declarationOnly;
|
|
149
|
+
const writeContent = !options?.codeOnly;
|
|
150
|
+
const configuration = (0, __intlayer_config.getConfiguration)(options?.configOptions);
|
|
151
|
+
const appLogger = (0, __intlayer_config.getAppLogger)(configuration);
|
|
152
|
+
const { baseDir } = configuration.content;
|
|
153
|
+
const _project = project || new ts_morph.Project({ skipAddingFilesFromTsConfig: true });
|
|
154
|
+
const baseName = require_transformFiles_extractDictionaryKey.extractDictionaryKey(filePath, (await node_fs_promises.default.readFile(filePath)).toString());
|
|
155
|
+
const componentKey = (0, __intlayer_config.camelCaseToKebabCase)(baseName);
|
|
156
|
+
const ext = (0, node_path.extname)(filePath);
|
|
157
|
+
let extractedContent = null;
|
|
158
|
+
if (ext === ".vue") try {
|
|
159
|
+
const { processVueFile } = await import("@intlayer/vue-transformer");
|
|
160
|
+
extractedContent = await processVueFile(filePath, componentKey, packageName, {
|
|
161
|
+
generateKey,
|
|
162
|
+
shouldExtract,
|
|
163
|
+
extractTsContent
|
|
164
|
+
}, saveComponent);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error.code === "ERR_MODULE_NOT_FOUND" || error.message?.includes("Cannot find module")) throw new Error(`Please install ${(0, __intlayer_config.colorizePath)("@intlayer/vue-transformer", __intlayer_config.ANSIColors.YELLOW)} to process Vue files.`);
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
else if (ext === ".svelte") try {
|
|
170
|
+
const { processSvelteFile } = await import("@intlayer/svelte-transformer");
|
|
171
|
+
extractedContent = await processSvelteFile(filePath, componentKey, packageName, {
|
|
172
|
+
generateKey,
|
|
173
|
+
shouldExtract,
|
|
174
|
+
extractTsContent
|
|
175
|
+
}, saveComponent);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (error.code === "ERR_MODULE_NOT_FOUND" || error.message?.includes("Cannot find module")) throw new Error(`Please install ${(0, __intlayer_config.colorizePath)("@intlayer/svelte-transformer", __intlayer_config.ANSIColors.YELLOW)} to process Svelte files.`);
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
else if ([
|
|
181
|
+
".tsx",
|
|
182
|
+
".jsx",
|
|
183
|
+
".ts",
|
|
184
|
+
".js"
|
|
185
|
+
].includes(ext)) extractedContent = await processReactFile(filePath, componentKey, packageName, _project, saveComponent);
|
|
186
|
+
if (!extractedContent) {
|
|
187
|
+
appLogger(`No extractable text found in ${baseName}`);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (writeContent) {
|
|
191
|
+
const contentFilePath = await writeContentHelper(extractedContent, componentKey, filePath, configuration, options?.outputDir);
|
|
192
|
+
appLogger(`Created content file: ${(0, __intlayer_config.colorizePath)((0, node_path.relative)(configuration.content.baseDir, contentFilePath))}`);
|
|
193
|
+
}
|
|
194
|
+
if (saveComponent) {
|
|
195
|
+
try {
|
|
196
|
+
const formatCommand = require_writeContentDeclaration_detectFormatCommand.detectFormatCommand(configuration);
|
|
197
|
+
if (formatCommand) (0, node_child_process.execSync)(formatCommand.replace("{{file}}", filePath), {
|
|
198
|
+
stdio: "ignore",
|
|
199
|
+
cwd: baseDir
|
|
200
|
+
});
|
|
201
|
+
} catch {}
|
|
202
|
+
appLogger(`Updated component: ${(0, __intlayer_config.colorizePath)((0, node_path.relative)(baseDir, filePath))}`);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const transformFiles = async (filePaths, packageName, options) => {
|
|
206
|
+
const appLogger = (0, __intlayer_config.getAppLogger)((0, __intlayer_config.getConfiguration)(options?.configOptions));
|
|
207
|
+
const project = new ts_morph.Project({ skipAddingFilesFromTsConfig: true });
|
|
208
|
+
for (const filePath of filePaths) try {
|
|
209
|
+
await extractIntlayer(filePath, packageName, options, project);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
appLogger(`Failed to transform ${filePath}: ${error.message}`);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
//#endregion
|
|
216
|
+
exports.extractIntlayer = extractIntlayer;
|
|
217
|
+
exports.transformFiles = transformFiles;
|
|
218
|
+
//# sourceMappingURL=transformFiles.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformFiles.cjs","names":["writeContentDeclaration","extractedContent: Record<string, string>","replacements: TsReplacement[]","Node","sourceFile: SourceFile","SyntaxKind","Project","extractDictionaryKey","fs","extractedContent: Record<string, string> | null","error: any","ANSIColors","detectFormatCommand"],"sources":["../../../src/transformFiles/transformFiles.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path';\nimport {\n ANSIColors,\n camelCaseToKebabCase,\n colorizePath,\n type GetConfigurationOptions,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';\nimport { writeContentDeclaration } from '../writeContentDeclaration';\nimport { detectFormatCommand } from '../writeContentDeclaration/detectFormatCommand';\nimport { extractDictionaryKey } from './extractDictionaryKey';\n\n// ==========================================\n// 1. Shared Utilities\n// ==========================================\n\nconst ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\nconst shouldExtract = (text: string): boolean => {\n const trimmed = text.trim();\n if (!trimmed) return false;\n if (!trimmed.includes(' ')) return false;\n // Starts with Capital letter\n if (!/^[A-Z]/.test(trimmed)) return false;\n // Filter out template logic identifiers (simple check)\n if (trimmed.startsWith('{') || trimmed.startsWith('v-')) return false;\n return true;\n};\n\nconst generateKey = (text: string, existingKeys: Set<string>): string => {\n const maxWords = 5;\n let key = text\n .replace(/\\s+/g, ' ')\n .replace(/_+/g, ' ')\n .replace(/-+/g, ' ')\n .replace(/[^a-zA-Z0-9 ]/g, '')\n .trim()\n .split(' ')\n .filter(Boolean)\n .slice(0, maxWords)\n .map((word, index) =>\n index === 0\n ? word.toLowerCase()\n : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n )\n .join('');\n\n if (!key) key = 'content';\n if (existingKeys.has(key)) {\n let i = 1;\n while (existingKeys.has(`${key}${i}`)) i++;\n key = `${key}${i}`;\n }\n return key;\n};\n\nconst writeContentHelper = async (\n extractedContent: Record<string, string>,\n componentKey: string,\n filePath: string,\n configuration: IntlayerConfig,\n outputDir?: string\n) => {\n const { defaultLocale } = configuration.internationalization;\n const { baseDir } = configuration.content;\n\n const dirName = outputDir ? resolve(outputDir) : dirname(filePath);\n const ext = extname(filePath);\n const baseName = basename(filePath, ext);\n const contentBaseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);\n\n const contentFilePath = join(dirName, `${contentBaseName}.content.ts`);\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n\n const dictionary: Dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n\n const relativeDir = relative(baseDir, dirName);\n await writeContentDeclaration(dictionary, configuration, {\n newDictionariesPath: relativeDir,\n });\n\n return contentFilePath;\n};\n\ntype TsReplacement = {\n node: Node;\n key: string;\n type: 'jsx-text' | 'jsx-attribute' | 'string-literal';\n};\n\nconst extractTsContent = (\n sourceFile: SourceFile,\n existingKeys: Set<string>\n): {\n extractedContent: Record<string, string>;\n replacements: TsReplacement[];\n} => {\n const extractedContent: Record<string, string> = {};\n const replacements: TsReplacement[] = [];\n\n sourceFile.forEachDescendant((node) => {\n // 1. JSX Text\n if (Node.isJsxText(node)) {\n const text = node.getText();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.replace(/\\s+/g, ' ').trim();\n replacements.push({ node, key, type: 'jsx-text' });\n }\n }\n\n // 2. JSX Attributes\n else if (Node.isJsxAttribute(node)) {\n const name = node.getNameNode().getText();\n if (ATTRIBUTES_TO_EXTRACT.includes(name)) {\n const initializer = node.getInitializer();\n if (Node.isStringLiteral(initializer)) {\n const text = initializer.getLiteralValue();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'jsx-attribute' });\n }\n }\n }\n }\n\n // 3. String Literals (Variables, Arrays, etc.)\n else if (Node.isStringLiteral(node)) {\n const text = node.getLiteralValue();\n if (shouldExtract(text)) {\n const parent = node.getParent();\n\n // Skip if inside ImportDeclaration\n if (\n parent?.getKindName() === 'ImportDeclaration' ||\n parent?.getKindName() === 'ImportSpecifier' ||\n parent?.getKindName() === 'ModuleSpecifier'\n ) {\n return;\n }\n\n // Skip if it's a JSX Attribute value (handled above)\n if (Node.isJsxAttribute(parent)) return;\n\n // Skip console.log\n if (Node.isCallExpression(parent)) {\n const expression = parent.getExpression();\n if (expression.getText().includes('console.log')) return;\n }\n\n // Skip Object Keys: { key: \"value\" } -> \"key\" is PropertyAssignment name if not computed\n if (Node.isPropertyAssignment(parent)) {\n if (parent.getNameNode() === node) return; // It's the key\n }\n\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'string-literal' });\n }\n }\n });\n\n return { extractedContent, replacements };\n};\n\n// ==========================================\n// 2. React (TS-Morph) Strategy\n// ==========================================\n\nconst processReactFile = async (\n filePath: string,\n componentKey: string,\n packageName: string,\n project: Project,\n save: boolean = true\n) => {\n let sourceFile: SourceFile;\n try {\n sourceFile = project.addSourceFileAtPath(filePath);\n } catch {\n sourceFile = project.getSourceFileOrThrow(filePath);\n }\n\n const existingKeys = new Set<string>();\n const { extractedContent, replacements } = extractTsContent(\n sourceFile,\n existingKeys\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n for (const { node, key, type } of replacements) {\n if (type === 'jsx-text' && Node.isJsxText(node)) {\n node.replaceWithText(`{content.${key}}`);\n } else if (type === 'jsx-attribute' && Node.isJsxAttribute(node)) {\n node.setInitializer(`{content.${key}.value}`);\n } else if (type === 'string-literal' && Node.isStringLiteral(node)) {\n // For React/JS variables, we usually want the value\n node.replaceWithText(`content.${key}.value`);\n }\n }\n\n // Inject hook\n const importDecl = sourceFile.getImportDeclaration(\n (d) => d.getModuleSpecifierValue() === packageName\n );\n if (!importDecl) {\n sourceFile.addImportDeclaration({\n namedImports: ['useIntlayer'],\n moduleSpecifier: packageName,\n });\n } else if (\n !importDecl.getNamedImports().some((n) => n.getName() === 'useIntlayer')\n ) {\n importDecl.addNamedImport('useIntlayer');\n }\n\n // Insert hook at start of component\n sourceFile.getFunctions().forEach((f) => {\n f.getBody()\n ?.asKind(SyntaxKind.Block)\n ?.insertStatements(0, `const content = useIntlayer(\"${componentKey}\");`);\n });\n\n // Also handle const/arrow components\n sourceFile.getVariableDeclarations().forEach((v) => {\n const init = v.getInitializer();\n if (Node.isArrowFunction(init) || Node.isFunctionExpression(init)) {\n const body = init.getBody();\n if (Node.isBlock(body)) {\n // Heuristic: check if it returns JSX or uses hooks\n if (\n body.getText().includes('return') ||\n body.getText().includes('use')\n ) {\n body.insertStatements(\n 0,\n `const content = useIntlayer(\"${componentKey}\");`\n );\n }\n }\n }\n });\n\n if (save) {\n await sourceFile.save();\n }\n return extractedContent;\n};\n\n// ==========================================\n// 5. Main Dispatcher\n// ==========================================\n\nexport type PackageName =\n | 'next-intlayer'\n | 'react-intlayer'\n | 'vue-intlayer'\n | 'svelte-intlayer'\n | 'preact-intlayer'\n | 'solid-intlayer'\n | 'angular-intlayer'\n | 'express-intlayer';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n outputDir?: string;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n};\n\nexport const extractIntlayer = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions,\n project?: Project\n) => {\n const saveComponent = !options?.declarationOnly;\n const writeContent = !options?.codeOnly;\n\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.content;\n\n // Setup Project for TS/React files if needed\n const _project =\n project || new Project({ skipAddingFilesFromTsConfig: true });\n\n const baseName = extractDictionaryKey(\n filePath,\n (await fs.readFile(filePath)).toString()\n );\n const componentKey = camelCaseToKebabCase(baseName);\n const ext = extname(filePath);\n\n let extractedContent: Record<string, string> | null = null;\n\n if (ext === '.vue') {\n try {\n const { processVueFile } = (await import(\n '@intlayer/vue-transformer'\n )) as any;\n extractedContent = await processVueFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-transformer', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n throw error;\n }\n } else if (ext === '.svelte') {\n try {\n const { processSvelteFile } = (await import(\n '@intlayer/svelte-transformer'\n )) as any;\n extractedContent = await processSvelteFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-transformer', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n throw error;\n }\n } else if (['.tsx', '.jsx', '.ts', '.js'].includes(ext)) {\n extractedContent = await processReactFile(\n filePath,\n componentKey,\n packageName,\n _project,\n saveComponent\n );\n }\n\n if (!extractedContent) {\n appLogger(`No extractable text found in ${baseName}`);\n return;\n }\n\n // Shared Write Logic\n if (writeContent) {\n const contentFilePath = await writeContentHelper(\n extractedContent,\n componentKey,\n filePath,\n configuration,\n options?.outputDir\n );\n\n const relativeContentFilePath = relative(\n configuration.content.baseDir,\n contentFilePath\n );\n appLogger(`Created content file: ${colorizePath(relativeContentFilePath)}`);\n }\n\n // Optional: Format\n if (saveComponent) {\n try {\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'ignore', // Silent\n cwd: baseDir,\n });\n }\n } catch {\n // Ignore format errors\n }\n\n appLogger(\n `Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\nexport const transformFiles = async (\n filePaths: string[],\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n });\n\n for (const filePath of filePaths) {\n try {\n await extractIntlayer(filePath, packageName, options, project);\n } catch (error) {\n appLogger(`Failed to transform ${filePath}: ${(error as Error).message}`);\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAqBA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,SAA0B;CAC/C,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,CAAC,QAAQ,SAAS,IAAI,CAAE,QAAO;AAEnC,KAAI,CAAC,SAAS,KAAK,QAAQ,CAAE,QAAO;AAEpC,K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AC,kBAAkB;AACrB,YAAU,gCAAgC,WAAW;AACrD;;AAIF,KAAI,cAAc;EAChB,MAAM,kBAAkB,MAAM,mBAC5B,kBACA,cACA,UACA,eACA,SAAS,UACV;AAMD,YAAU,qFAHR,cAAc,QAAQ,SACtB,gBACD,CACuE,GAAG;;AAI7E,KAAI,eAAe;AACjB,MAAI;GACF,MAAM,gBAAgBC,wEAAoB,cAAc;AACxD,OAAI,cACF,kCAAS,cAAc,QAAQ,YAAY,SAAS,EAAE;IACpD,OAAO;IACP,KAAK;IACN,CAAC;UAEE;AAIR,YACE,kFAA4C,SAAS,SAAS,CAAC,GAChE;;;AAIL,MAAa,iBAAiB,OAC5B,WACA,aACA,YACG;CAEH,MAAM,wFADiC,SAAS,cAAc,CACjB;CAE7C,MAAM,UAAU,IAAIN,iBAAQ,EAC1B,6BAA6B,MAC9B,CAAC;AAEF,MAAK,MAAM,YAAY,UACrB,KAAI;AACF,QAAM,gBAAgB,UAAU,aAAa,SAAS,QAAQ;UACvD,OAAO;AACd,YAAU,uBAAuB,SAAS,IAAK,MAAgB,UAAU"}
|
|
@@ -3,21 +3,23 @@ let __intlayer_config = require("@intlayer/config");
|
|
|
3
3
|
|
|
4
4
|
//#region src/writeContentDeclaration/detectFormatCommand.ts
|
|
5
5
|
const detectFormatCommand = (configuration) => {
|
|
6
|
-
const { formatCommand } = configuration.content;
|
|
7
|
-
const projectRequire = (0, __intlayer_config.getProjectRequire)();
|
|
8
|
-
if (formatCommand) return formatCommand;
|
|
9
6
|
try {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
7
|
+
const { formatCommand, baseDir } = configuration.content;
|
|
8
|
+
const projectRequire = (0, __intlayer_config.getProjectRequire)(baseDir);
|
|
9
|
+
if (formatCommand) return formatCommand;
|
|
10
|
+
try {
|
|
11
|
+
projectRequire.resolve("prettier");
|
|
12
|
+
return "prettier --write \"{{file}}\" --log-level silent";
|
|
13
|
+
} catch (_error) {}
|
|
14
|
+
try {
|
|
15
|
+
projectRequire.resolve("biome");
|
|
16
|
+
return "biome format \"{{file}}\" --write --log-level none";
|
|
17
|
+
} catch (_error) {}
|
|
18
|
+
try {
|
|
19
|
+
projectRequire.resolve("eslint");
|
|
20
|
+
return "eslint --fix \"{{file}}\" --quiet";
|
|
21
|
+
} catch (_error) {}
|
|
22
|
+
} catch {}
|
|
21
23
|
};
|
|
22
24
|
|
|
23
25
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detectFormatCommand.cjs","names":[],"sources":["../../../src/writeContentDeclaration/detectFormatCommand.ts"],"sourcesContent":["import { getProjectRequire } from '@intlayer/config';\nimport type { IntlayerConfig } from '@intlayer/types';\n\nexport const detectFormatCommand = (configuration: IntlayerConfig) => {\n const { formatCommand } = configuration.content;\n
|
|
1
|
+
{"version":3,"file":"detectFormatCommand.cjs","names":[],"sources":["../../../src/writeContentDeclaration/detectFormatCommand.ts"],"sourcesContent":["import { getProjectRequire } from '@intlayer/config';\nimport type { IntlayerConfig } from '@intlayer/types';\n\nexport const detectFormatCommand = (configuration: IntlayerConfig) => {\n try {\n const { formatCommand, baseDir } = configuration.content;\n const projectRequire = getProjectRequire(baseDir);\n\n if (formatCommand) {\n return formatCommand;\n }\n\n // Try Prettier\n try {\n projectRequire.resolve('prettier');\n\n return 'prettier --write \"{{file}}\" --log-level silent';\n } catch (_error) {\n // Prettier not found, continue to next option\n }\n\n // Try Biome\n try {\n projectRequire.resolve('biome');\n\n return 'biome format \"{{file}}\" --write --log-level none';\n } catch (_error) {\n // Biome not found, continue to next option\n }\n\n // Try ESLint\n try {\n projectRequire.resolve('eslint');\n\n return 'eslint --fix \"{{file}}\" --quiet';\n } catch (_error) {\n // ESLint not found, no formatter available\n }\n } catch {}\n\n // No formatter found\n return undefined;\n};\n"],"mappings":";;;;AAGA,MAAa,uBAAuB,kBAAkC;AACpE,KAAI;EACF,MAAM,EAAE,eAAe,YAAY,cAAc;EACjD,MAAM,0DAAmC,QAAQ;AAEjD,MAAI,cACF,QAAO;AAIT,MAAI;AACF,kBAAe,QAAQ,WAAW;AAElC,UAAO;WACA,QAAQ;AAKjB,MAAI;AACF,kBAAe,QAAQ,QAAQ;AAE/B,UAAO;WACA,QAAQ;AAKjB,MAAI;AACF,kBAAe,QAAQ,SAAS;AAEhC,UAAO;WACA,QAAQ;SAGX"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_getContentDeclarationFileTemplate_getContentDeclarationFileTemplate = require('../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs');
|
|
2
3
|
const require_writeContentDeclaration_transformJSFile = require('./transformJSFile.cjs');
|
|
3
4
|
const require_utils_getFormatFromExtension = require('../utils/getFormatFromExtension.cjs');
|
|
4
|
-
const require_getContentDeclarationFileTemplate_getContentDeclarationFileTemplate = require('../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs');
|
|
5
5
|
const require_writeContentDeclaration_detectFormatCommand = require('./detectFormatCommand.cjs');
|
|
6
6
|
let node_fs = require("node:fs");
|
|
7
7
|
let node_fs_promises = require("node:fs/promises");
|
package/dist/esm/index.mjs
CHANGED
|
@@ -20,16 +20,9 @@ import { loadContentDeclarations } from "./loadDictionaries/loadContentDeclarati
|
|
|
20
20
|
import { loadLocalDictionaries } from "./loadDictionaries/loadLocalDictionaries.mjs";
|
|
21
21
|
import { handleAdditionalContentDeclarationFile } from "./handleAdditionalContentDeclarationFile.mjs";
|
|
22
22
|
import { handleContentDeclarationFileChange } from "./handleContentDeclarationFileChange.mjs";
|
|
23
|
-
import { listDictionaries } from "./listDictionariesPath.mjs";
|
|
23
|
+
import { listDictionaries, listDictionariesWithStats } from "./listDictionariesPath.mjs";
|
|
24
24
|
import { handleUnlinkedContentDeclarationFile } from "./handleUnlinkedContentDeclarationFile.mjs";
|
|
25
|
-
import { detectExportedComponentName } from "./writeContentDeclaration/detectExportedComponentName.mjs";
|
|
26
|
-
import { transformJSFile } from "./writeContentDeclaration/transformJSFile.mjs";
|
|
27
|
-
import { getExtensionFromFormat, getFormatFromExtension } from "./utils/getFormatFromExtension.mjs";
|
|
28
25
|
import { getContentDeclarationFileTemplate } from "./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";
|
|
29
|
-
import { detectFormatCommand } from "./writeContentDeclaration/detectFormatCommand.mjs";
|
|
30
|
-
import { writeJSFile } from "./writeContentDeclaration/writeJSFile.mjs";
|
|
31
|
-
import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.mjs";
|
|
32
|
-
import { extractContent, extractIntlayer, transformComponent, transformFiles, writeContent } from "./compiler/index.mjs";
|
|
33
26
|
import { listGitFiles, listGitLines } from "./listGitFiles.mjs";
|
|
34
27
|
import { sortAlphabetically } from "./utils/sortAlphabetically.mjs";
|
|
35
28
|
import { loadRemoteDictionaries } from "./loadDictionaries/loadRemoteDictionaries.mjs";
|
|
@@ -37,6 +30,14 @@ import { loadDictionaries } from "./loadDictionaries/loadDictionaries.mjs";
|
|
|
37
30
|
import { runOnce } from "./utils/runOnce.mjs";
|
|
38
31
|
import { prepareIntlayer } from "./prepareIntlayer.mjs";
|
|
39
32
|
import { reduceDictionaryContent } from "./reduceDictionaryContent/reduceDictionaryContent.mjs";
|
|
33
|
+
import { detectExportedComponentName } from "./writeContentDeclaration/detectExportedComponentName.mjs";
|
|
34
|
+
import { extractDictionaryKey } from "./transformFiles/extractDictionaryKey.mjs";
|
|
35
|
+
import { transformJSFile } from "./writeContentDeclaration/transformJSFile.mjs";
|
|
36
|
+
import { getExtensionFromFormat, getFormatFromExtension } from "./utils/getFormatFromExtension.mjs";
|
|
37
|
+
import { detectFormatCommand } from "./writeContentDeclaration/detectFormatCommand.mjs";
|
|
38
|
+
import { writeJSFile } from "./writeContentDeclaration/writeJSFile.mjs";
|
|
39
|
+
import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.mjs";
|
|
40
|
+
import { extractIntlayer, transformFiles } from "./transformFiles/transformFiles.mjs";
|
|
40
41
|
import { splitTextByLines } from "./utils/splitTextByLine.mjs";
|
|
41
42
|
import { getChunk } from "./utils/getChunk.mjs";
|
|
42
43
|
import { assembleJSON, chunkJSON, reconstructFromSingleChunk } from "./utils/chunkJSON.mjs";
|
|
@@ -46,4 +47,4 @@ import { runParallel } from "./utils/runParallel/index.mjs";
|
|
|
46
47
|
import { verifyIdenticObjectFormat } from "./utils/verifyIdenticObjectFormat.mjs";
|
|
47
48
|
import { buildAndWatchIntlayer, watch } from "./watcher.mjs";
|
|
48
49
|
|
|
49
|
-
export { assembleJSON, buildAndWatchIntlayer, buildDictionary, chunkJSON, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, detectFormatCommand,
|
|
50
|
+
export { assembleJSON, buildAndWatchIntlayer, buildDictionary, chunkJSON, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, detectFormatCommand, extractDictionaryKey, extractIntlayer, fetchDistantDictionaries, formatLocale, formatPath, generateDictionaryListContent, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getChunk, getContentDeclarationFileTemplate, getExtensionFromFormat, getFileHash, getFormatFromExtension, getGlobalLimiter, getTaskLimiter, handleAdditionalContentDeclarationFile, handleContentDeclarationFileChange, handleUnlinkedContentDeclarationFile, isInvalidDictionary, listDictionaries, listDictionariesWithStats, listGitFiles, listGitLines, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, pLimit, parallelize, parallelizeGlobal, prepareIntlayer, reconstructFromSingleChunk, reduceDictionaryContent, reduceObjectFormat, resolveObjectPromises, runOnce, runParallel, sortAlphabetically, splitTextByLines, transformFiles, transformJSFile, verifyIdenticObjectFormat, watch, writeContentDeclaration, writeJSFile };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
1
2
|
import fg from "fast-glob";
|
|
2
3
|
|
|
3
4
|
//#region src/listDictionariesPath.ts
|
|
@@ -9,7 +10,14 @@ import fg from "fast-glob";
|
|
|
9
10
|
const listDictionaries = async (configuration) => {
|
|
10
11
|
return await fg(configuration.content.watchedFilesPatternWithPath, { ignore: configuration.content.excludedPath });
|
|
11
12
|
};
|
|
13
|
+
const listDictionariesWithStats = async (configuration) => {
|
|
14
|
+
const files = await listDictionaries(configuration);
|
|
15
|
+
return Promise.all(files.map(async (file) => ({
|
|
16
|
+
path: file,
|
|
17
|
+
stats: await stat(file)
|
|
18
|
+
})));
|
|
19
|
+
};
|
|
12
20
|
|
|
13
21
|
//#endregion
|
|
14
|
-
export { listDictionaries };
|
|
22
|
+
export { listDictionaries, listDictionariesWithStats };
|
|
15
23
|
//# sourceMappingURL=listDictionariesPath.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listDictionariesPath.mjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const files: string[] = await fg(\n configuration.content.watchedFilesPatternWithPath,\n {\n ignore: configuration.content.excludedPath,\n }\n );\n\n return files;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"listDictionariesPath.mjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const files: string[] = await fg(\n configuration.content.watchedFilesPatternWithPath,\n {\n ignore: configuration.content.excludedPath,\n }\n );\n\n return files;\n};\n\nexport const listDictionariesWithStats = async (\n configuration: IntlayerConfig\n) => {\n const files = await listDictionaries(configuration);\n\n return Promise.all(\n files.map(async (file) => ({ path: file, stats: await stat(file) }))\n );\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,mBAAmB,OAC9B,kBACsB;AAQtB,QAPwB,MAAM,GAC5B,cAAc,QAAQ,6BACtB,EACE,QAAQ,cAAc,QAAQ,cAC/B,CACF;;AAKH,MAAa,4BAA4B,OACvC,kBACG;CACH,MAAM,QAAQ,MAAM,iBAAiB,cAAc;AAEnD,QAAO,QAAQ,IACb,MAAM,IAAI,OAAO,UAAU;EAAE,MAAM;EAAM,OAAO,MAAM,KAAK,KAAK;EAAE,EAAE,CACrE"}
|