@intlayer/chokidar 7.5.0-canary.0 → 7.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/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +4 -4
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/processContentDeclaration.cjs +2 -2
- package/dist/cjs/buildIntlayerDictionary/processContentDeclaration.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +7 -7
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs +5 -5
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +5 -5
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +5 -5
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs +4 -4
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/cleanOutputDir.cjs +2 -2
- package/dist/cjs/cleanOutputDir.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +16 -11
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +4 -4
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs +2 -2
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs +2 -2
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs +2 -2
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs +2 -2
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs +2 -2
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs +3 -3
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs +3 -3
- package/dist/cjs/createType/createType.cjs.map +1 -1
- package/dist/cjs/fetchDistantDictionaries.cjs +6 -6
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs +3 -3
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/formatDictionary.cjs +7 -7
- package/dist/cjs/formatDictionary.cjs.map +1 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs +2 -2
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs +2 -2
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs +2 -2
- package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs +2 -2
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs +4 -4
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +5 -5
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +4 -4
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +11 -11
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +6 -6
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +17 -17
- package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +14 -14
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs +2 -2
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
- package/dist/cjs/transformFiles/transformFiles.cjs +9 -9
- package/dist/cjs/transformFiles/transformFiles.cjs.map +1 -1
- package/dist/cjs/utils/formatter.cjs +7 -7
- package/dist/cjs/utils/formatter.cjs.map +1 -1
- package/dist/cjs/utils/runOnce.cjs +4 -4
- package/dist/cjs/utils/runOnce.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/index.cjs +1 -1
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/watcher.cjs +5 -5
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs +2 -2
- package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs +14 -14
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +86 -86
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +5 -5
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +4 -4
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +14 -9
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs +2 -2
- package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs.map +1 -1
- package/dist/esm/utils/runParallel/index.mjs +1 -1
- package/dist/esm/utils/runParallel/index.mjs.map +1 -1
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts +2 -2
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts +3 -3
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts +3 -3
- 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/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts.map +1 -1
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts +2 -2
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts.map +1 -1
- package/dist/types/listDictionariesPath.d.ts +2 -2
- package/dist/types/listDictionariesPath.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts +2 -2
- package/package.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reduceDictionaryContent.cjs","names":["applyMask"],"sources":["../../../src/reduceDictionaryContent/reduceDictionaryContent.ts"],"sourcesContent":["import { getMaskContent } from '@intlayer/core';\nimport type { Dictionary } from '@intlayer/types';\nimport { applyMask } from './applyMask';\n\nexport const reduceDictionaryContent = (\n fullDictionary: Dictionary,\n partialDictionary: Dictionary\n) => {\n const mask = getMaskContent(partialDictionary);\n const result = applyMask(fullDictionary, mask);\n\n return result;\n};\n"],"mappings":";;;;;AAIA,MAAa,2BACX,gBACA,sBACG;AAIH,QAFeA,oDAAU,
|
|
1
|
+
{"version":3,"file":"reduceDictionaryContent.cjs","names":["applyMask"],"sources":["../../../src/reduceDictionaryContent/reduceDictionaryContent.ts"],"sourcesContent":["import { getMaskContent } from '@intlayer/core';\nimport type { Dictionary } from '@intlayer/types';\nimport { applyMask } from './applyMask';\n\nexport const reduceDictionaryContent = (\n fullDictionary: Dictionary,\n partialDictionary: Dictionary\n) => {\n const mask = getMaskContent(partialDictionary);\n const result = applyMask(fullDictionary, mask);\n\n return result;\n};\n"],"mappings":";;;;;AAIA,MAAa,2BACX,gBACA,sBACG;AAIH,QAFeA,oDAAU,mDADG,kBAAkB,CACA"}
|
|
@@ -4,7 +4,7 @@ const require_writeContentDeclaration_detectFormatCommand = require('../writeCon
|
|
|
4
4
|
const require_writeContentDeclaration_writeContentDeclaration = require('../writeContentDeclaration/writeContentDeclaration.cjs');
|
|
5
5
|
let node_fs_promises = require("node:fs/promises");
|
|
6
6
|
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
7
|
-
let
|
|
7
|
+
let _intlayer_config = require("@intlayer/config");
|
|
8
8
|
let node_path = require("node:path");
|
|
9
9
|
let node_child_process = require("node:child_process");
|
|
10
10
|
let ts_morph = require("ts-morph");
|
|
@@ -173,12 +173,12 @@ const processReactFile = async (filePath, componentKey, packageName, project, sa
|
|
|
173
173
|
const extractIntlayer = async (filePath, packageName, options, project) => {
|
|
174
174
|
const saveComponent = !options?.declarationOnly;
|
|
175
175
|
const writeContent = !options?.codeOnly;
|
|
176
|
-
const configuration = (0,
|
|
177
|
-
const appLogger = (0,
|
|
176
|
+
const configuration = (0, _intlayer_config.getConfiguration)(options?.configOptions);
|
|
177
|
+
const appLogger = (0, _intlayer_config.getAppLogger)(configuration);
|
|
178
178
|
const { baseDir } = configuration.content;
|
|
179
179
|
const _project = project || new ts_morph.Project({ skipAddingFilesFromTsConfig: true });
|
|
180
180
|
const baseName = require_transformFiles_extractDictionaryKey.extractDictionaryKey(filePath, (await node_fs_promises.default.readFile(filePath)).toString());
|
|
181
|
-
const componentKey = (0,
|
|
181
|
+
const componentKey = (0, _intlayer_config.camelCaseToKebabCase)(baseName);
|
|
182
182
|
const ext = (0, node_path.extname)(filePath);
|
|
183
183
|
let extractedContent = null;
|
|
184
184
|
if (ext === ".vue") try {
|
|
@@ -189,7 +189,7 @@ const extractIntlayer = async (filePath, packageName, options, project) => {
|
|
|
189
189
|
extractTsContent
|
|
190
190
|
}, saveComponent);
|
|
191
191
|
} catch (error) {
|
|
192
|
-
if (error.code === "ERR_MODULE_NOT_FOUND" || error.message?.includes("Cannot find module")) throw new Error(`Please install ${(0,
|
|
192
|
+
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.`);
|
|
193
193
|
throw error;
|
|
194
194
|
}
|
|
195
195
|
else if (ext === ".svelte") try {
|
|
@@ -200,7 +200,7 @@ const extractIntlayer = async (filePath, packageName, options, project) => {
|
|
|
200
200
|
extractTsContent
|
|
201
201
|
}, saveComponent);
|
|
202
202
|
} catch (error) {
|
|
203
|
-
if (error.code === "ERR_MODULE_NOT_FOUND" || error.message?.includes("Cannot find module")) throw new Error(`Please install ${(0,
|
|
203
|
+
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.`);
|
|
204
204
|
throw error;
|
|
205
205
|
}
|
|
206
206
|
else if ([
|
|
@@ -215,7 +215,7 @@ const extractIntlayer = async (filePath, packageName, options, project) => {
|
|
|
215
215
|
}
|
|
216
216
|
if (writeContent) {
|
|
217
217
|
const contentFilePath = await writeContentHelper(extractedContent, componentKey, filePath, configuration, options?.outputDir);
|
|
218
|
-
appLogger(`Created content file: ${(0,
|
|
218
|
+
appLogger(`Created content file: ${(0, _intlayer_config.colorizePath)((0, node_path.relative)(configuration.content.baseDir, contentFilePath))}`);
|
|
219
219
|
}
|
|
220
220
|
if (saveComponent) {
|
|
221
221
|
try {
|
|
@@ -225,11 +225,11 @@ const extractIntlayer = async (filePath, packageName, options, project) => {
|
|
|
225
225
|
cwd: baseDir
|
|
226
226
|
});
|
|
227
227
|
} catch {}
|
|
228
|
-
appLogger(`Updated component: ${(0,
|
|
228
|
+
appLogger(`Updated component: ${(0, _intlayer_config.colorizePath)((0, node_path.relative)(baseDir, filePath))}`);
|
|
229
229
|
}
|
|
230
230
|
};
|
|
231
231
|
const transformFiles = async (filePaths, packageName, options) => {
|
|
232
|
-
const appLogger = (0,
|
|
232
|
+
const appLogger = (0, _intlayer_config.getAppLogger)((0, _intlayer_config.getConfiguration)(options?.configOptions));
|
|
233
233
|
const project = new ts_morph.Project({ skipAddingFilesFromTsConfig: true });
|
|
234
234
|
for (const filePath of filePaths) try {
|
|
235
235
|
await extractIntlayer(filePath, packageName, options, project);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformFiles.cjs","names":["dictionary: Dictionary","multilingualContent: Record<string, TranslationNode>","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 (exported for reuse in babel plugin)\n// ==========================================\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/**\n * Default function to determine if a string should be extracted for localization\n */\nexport const 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\n/**\n * Generate a unique key from text for use as a dictionary key\n */\nexport const generateKey = (\n text: string,\n existingKeys: Set<string>\n): 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\n/**\n * Translation node structure used in multilingual dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\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 isPerLocaleFile = configuration?.dictionary?.locale;\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 let dictionary: Dictionary;\n\n if (isPerLocaleFile) {\n // Per-locale format: simple string content with locale property\n dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes, no locale property\n const multilingualContent: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(extractedContent)) {\n multilingualContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n\n dictionary = {\n key: componentKey,\n content: multilingualContent,\n filePath: relativeContentFilePath,\n };\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":";;;;;;;;;;;;;;;AAwBA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACD;;;;AAKD,MAAa,iBAAiB,SAA0B;CACtD,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,KAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,WAAW,KAAK,CAAE,QAAO;AAChE,QAAO;;;;;AAMT,MAAa,eACX,MACA,iBACW;CAEX,IAAI,MAAM,KACP,QAAQ,QAAQ,IAAI,CACpB,QAAQ,OAAO,IAAI,CACnB,QAAQ,OAAO,IAAI,CACnB,QAAQ,kBAAkB,GAAG,CAC7B,MAAM,CACN,MAAM,IAAI,CACV,OAAO,QAAQ,CACf,MAAM,GATQ,EASI,CAClB,KAAK,MAAM,UACV,UAAU,IACN,KAAK,aAAa,GAClB,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,KAAK,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BAAkB,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"}
|
|
1
|
+
{"version":3,"file":"transformFiles.cjs","names":["dictionary: Dictionary","multilingualContent: Record<string, TranslationNode>","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 (exported for reuse in babel plugin)\n// ==========================================\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/**\n * Default function to determine if a string should be extracted for localization\n */\nexport const 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\n/**\n * Generate a unique key from text for use as a dictionary key\n */\nexport const generateKey = (\n text: string,\n existingKeys: Set<string>\n): 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\n/**\n * Translation node structure used in multilingual dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\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 isPerLocaleFile = configuration?.dictionary?.locale;\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 let dictionary: Dictionary;\n\n if (isPerLocaleFile) {\n // Per-locale format: simple string content with locale property\n dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes, no locale property\n const multilingualContent: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(extractedContent)) {\n multilingualContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n\n dictionary = {\n key: componentKey,\n content: multilingualContent,\n filePath: relativeContentFilePath,\n };\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":";;;;;;;;;;;;;;;AAwBA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACD;;;;AAKD,MAAa,iBAAiB,SAA0B;CACtD,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,KAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,WAAW,KAAK,CAAE,QAAO;AAChE,QAAO;;;;;AAMT,MAAa,eACX,MACA,iBACW;CAEX,IAAI,MAAM,KACP,QAAQ,QAAQ,IAAI,CACpB,QAAQ,OAAO,IAAI,CACnB,QAAQ,OAAO,IAAI,CACnB,QAAQ,kBAAkB,GAAG,CAC7B,MAAM,CACN,MAAM,IAAI,CACV,OAAO,QAAQ,CACf,MAAM,GATQ,EASI,CAClB,KAAK,MAAM,UACV,UAAU,IACN,KAAK,aAAa,GAClB,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,KAAK,MAAM,EAAE,CAAC,aAAa,CAC/D,CACA,KAAK,GAAG;AAEX,KAAI,CAAC,IAAK,OAAM;AAChB,KAAI,aAAa,IAAI,IAAI,EAAE;EACzB,IAAI,IAAI;AACR,SAAO,aAAa,IAAI,GAAG,MAAM,IAAI,CAAE;AACvC,QAAM,GAAG,MAAM;;AAEjB,QAAO;;AAWT,MAAM,qBAAqB,OACzB,kBACA,cACA,UACA,eACA,cACG;CACH,MAAM,EAAE,kBAAkB,cAAc;CACxC,M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GAChE;;;AAIL,MAAa,iBAAiB,OAC5B,WACA,aACA,YACG;CAEH,MAAM,sFADiC,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"}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let
|
|
2
|
+
let _intlayer_config = require("@intlayer/config");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
|
-
let
|
|
5
|
-
|
|
6
|
-
let
|
|
7
|
-
let
|
|
4
|
+
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
|
+
_intlayer_config_built = require_rolldown_runtime.__toESM(_intlayer_config_built);
|
|
6
|
+
let _intlayer_core = require("@intlayer/core");
|
|
7
|
+
let _intlayer_types = require("@intlayer/types");
|
|
8
8
|
|
|
9
9
|
//#region src/utils/formatter.ts
|
|
10
|
-
const formatPath = (path, color) => [path].flat().map((path$1) => path$1.startsWith("/") ? (0, node_path.relative)(
|
|
11
|
-
const formatLocale = (locale, color =
|
|
10
|
+
const formatPath = (path, color) => [path].flat().map((path$1) => path$1.startsWith("/") ? (0, node_path.relative)(_intlayer_config_built.default.content.baseDir, path$1) : path$1).map((relativePath) => color === false ? relativePath : (0, _intlayer_config.colorizePath)(relativePath, color)).join(`, `);
|
|
11
|
+
const formatLocale = (locale, color = _intlayer_config.ANSIColors.GREEN) => [locale].flat().map((locale$1) => `${(0, _intlayer_core.getLocaleName)(locale$1, _intlayer_types.Locales.ENGLISH)} (${locale$1})`).map((text) => color === false ? text : (0, _intlayer_config.colorize)(text, color)).join(`, `);
|
|
12
12
|
|
|
13
13
|
//#endregion
|
|
14
14
|
exports.formatLocale = formatLocale;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatter.cjs","names":["path","configuration","ANSIColors","locale","Locales"],"sources":["../../../src/utils/formatter.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { ANSIColors, colorize, colorizePath } from '@intlayer/config';\nimport configuration from '@intlayer/config/built';\nimport { getLocaleName } from '@intlayer/core';\nimport { Locales, type LocalesValues } from '@intlayer/types';\n\nexport const formatPath = (\n path: string | string[],\n color?: ANSIColors | false\n) =>\n [path]\n .flat()\n .map((path) =>\n path.startsWith('/')\n ? relative(configuration.content.baseDir, path)\n : path\n )\n .map((relativePath) =>\n color === false ? relativePath : colorizePath(relativePath, color)\n )\n .join(`, `);\n\nexport const formatLocale = (\n locale: LocalesValues | LocalesValues[],\n color: ANSIColors | false = ANSIColors.GREEN\n) =>\n [locale]\n .flat()\n .map((locale) => `${getLocaleName(locale, Locales.ENGLISH)} (${locale})`)\n .map((text) => (color === false ? text : colorize(text, color)))\n .join(`, `);\n"],"mappings":";;;;;;;;;AAMA,MAAa,cACX,MACA,UAEA,CAAC,KAAK,CACH,MAAM,CACN,KAAK,WACJA,OAAK,WAAW,IAAI,2BACPC,
|
|
1
|
+
{"version":3,"file":"formatter.cjs","names":["path","configuration","ANSIColors","locale","Locales"],"sources":["../../../src/utils/formatter.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { ANSIColors, colorize, colorizePath } from '@intlayer/config';\nimport configuration from '@intlayer/config/built';\nimport { getLocaleName } from '@intlayer/core';\nimport { Locales, type LocalesValues } from '@intlayer/types';\n\nexport const formatPath = (\n path: string | string[],\n color?: ANSIColors | false\n) =>\n [path]\n .flat()\n .map((path) =>\n path.startsWith('/')\n ? relative(configuration.content.baseDir, path)\n : path\n )\n .map((relativePath) =>\n color === false ? relativePath : colorizePath(relativePath, color)\n )\n .join(`, `);\n\nexport const formatLocale = (\n locale: LocalesValues | LocalesValues[],\n color: ANSIColors | false = ANSIColors.GREEN\n) =>\n [locale]\n .flat()\n .map((locale) => `${getLocaleName(locale, Locales.ENGLISH)} (${locale})`)\n .map((text) => (color === false ? text : colorize(text, color)))\n .join(`, `);\n"],"mappings":";;;;;;;;;AAMA,MAAa,cACX,MACA,UAEA,CAAC,KAAK,CACH,MAAM,CACN,KAAK,WACJA,OAAK,WAAW,IAAI,2BACPC,+BAAc,QAAQ,SAASD,OAAK,GAC7CA,OACL,CACA,KAAK,iBACJ,UAAU,QAAQ,kDAA4B,cAAc,MAAM,CACnE,CACA,KAAK,KAAK;AAEf,MAAa,gBACX,QACA,QAA4BE,4BAAW,UAEvC,CAAC,OAAO,CACL,MAAM,CACN,KAAK,aAAW,qCAAiBC,UAAQC,wBAAQ,QAAQ,CAAC,IAAID,SAAO,GAAG,CACxE,KAAK,SAAU,UAAU,QAAQ,sCAAgB,MAAM,MAAM,CAAE,CAC/D,KAAK,KAAK"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
let node_fs_promises = require("node:fs/promises");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
|
-
let
|
|
5
|
-
|
|
4
|
+
let _intlayer_core_package_json = require("@intlayer/core/package.json");
|
|
5
|
+
_intlayer_core_package_json = require_rolldown_runtime.__toESM(_intlayer_core_package_json);
|
|
6
6
|
|
|
7
7
|
//#region src/utils/runOnce.ts
|
|
8
8
|
const DEFAULT_RUN_ONCE_OPTIONS = { cacheTimeoutMs: 60 * 1e3 };
|
|
@@ -10,7 +10,7 @@ const writeSentinelFile = async (sentinelFilePath, currentTimestamp) => {
|
|
|
10
10
|
try {
|
|
11
11
|
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(sentinelFilePath), { recursive: true });
|
|
12
12
|
const data = {
|
|
13
|
-
version:
|
|
13
|
+
version: _intlayer_core_package_json.default.version,
|
|
14
14
|
timestamp: currentTimestamp
|
|
15
15
|
};
|
|
16
16
|
await (0, node_fs_promises.writeFile)(sentinelFilePath, JSON.stringify(data), { flag: "wx" });
|
|
@@ -58,7 +58,7 @@ const runOnce = async (sentinelFilePath, callback, options) => {
|
|
|
58
58
|
} catch {
|
|
59
59
|
cachedVersion = void 0;
|
|
60
60
|
}
|
|
61
|
-
if (!cachedVersion || cachedVersion !==
|
|
61
|
+
if (!cachedVersion || cachedVersion !== _intlayer_core_package_json.default.version) shouldRebuild = true;
|
|
62
62
|
} catch {
|
|
63
63
|
shouldRebuild = true;
|
|
64
64
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runOnce.cjs","names":["data: SentinelData","packageJson","err: any","cachedVersion: string | undefined"],"sources":["../../../src/utils/runOnce.ts"],"sourcesContent":["import { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport packageJson from '@intlayer/core/package.json' with { type: 'json' };\n\ntype RunOnceOptions = {\n /**\n * The function to execute when the sentinel is not found or is older than the cache timeout.\n */\n onIsCached?: () => void | Promise<void>;\n /**\n * The time window in milliseconds during which the sentinel is considered valid.\n *\n * @default 60000 = 1 minute\n */\n cacheTimeoutMs?: number;\n /**\n * If true, the callback will always run. If undefined, the callback will run only if the sentinel is older than the cache timeout.\n *\n * @default false\n */\n forceRun?: boolean;\n};\n\nconst DEFAULT_RUN_ONCE_OPTIONS = {\n cacheTimeoutMs: 60 * 1000, // 1 minute in milliseconds,\n} satisfies RunOnceOptions;\n\ntype SentinelData = {\n version: string;\n timestamp: number;\n};\n\nconst writeSentinelFile = async (\n sentinelFilePath: string,\n currentTimestamp: number\n) => {\n try {\n // Ensure the directory exists before writing the file\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n\n // O_EXCL ensures only the *first* process can create the file\n const data: SentinelData = {\n version: packageJson.version,\n timestamp: currentTimestamp,\n };\n await writeFile(sentinelFilePath, JSON.stringify(data), { flag: 'wx' });\n } catch (err: any) {\n if (err.code === 'EEXIST') {\n // Another process already created it → we're done\n return;\n }\n throw err; // unexpected FS error\n }\n};\n\n/**\n * Ensures a callback function runs only once within a specified time window across multiple processes.\n * Uses a sentinel file to coordinate execution and prevent duplicate work.\n *\n * @param sentinelFilePath - Path to the sentinel file used for coordination\n * @param callback - The function to execute (should be async)\n * @param options - The options for the runOnce function\n *\n * @example\n * ```typescript\n * await runPrepareIntlayerOnce(\n * '/tmp/intlayer-sentinel',\n * async () => {\n * // Your initialization logic here\n * await prepareIntlayer();\n * },\n * 30 * 1000 // 30 seconds cache\n * );\n * ```\n *\n * @throws {Error} When there are unexpected filesystem errors\n */\nexport const runOnce = async (\n sentinelFilePath: string,\n callback: () => void | Promise<void>,\n options?: RunOnceOptions\n) => {\n const { onIsCached, cacheTimeoutMs, forceRun } = {\n ...DEFAULT_RUN_ONCE_OPTIONS,\n ...(options ?? {}),\n };\n const currentTimestamp = Date.now();\n\n try {\n // Check if sentinel file exists and get its stats\n const sentinelStats = await stat(sentinelFilePath);\n const sentinelAge = currentTimestamp - sentinelStats.mtime.getTime();\n\n // Determine if we should rebuild based on cache age, force flag, or version mismatch\n let shouldRebuild = Boolean(forceRun) || sentinelAge > cacheTimeoutMs!;\n\n if (!shouldRebuild) {\n try {\n const raw = await readFile(sentinelFilePath, 'utf8');\n let cachedVersion: string | undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<SentinelData>;\n cachedVersion = parsed.version;\n } catch {\n // Legacy format (timestamp only). Force a rebuild once to write versioned sentinel.\n cachedVersion = undefined;\n }\n\n if (!cachedVersion || cachedVersion !== packageJson.version) {\n shouldRebuild = true;\n }\n } catch {\n // If we cannot read the file, err on the safe side and rebuild\n shouldRebuild = true;\n }\n }\n\n if (shouldRebuild) {\n try {\n await unlink(sentinelFilePath);\n } catch {}\n // Fall through to create new sentinel and rebuild\n } else {\n await onIsCached?.();\n // Sentinel is recent and versions match, no need to rebuild\n return;\n }\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n // File doesn't exist, continue to create it\n } else {\n throw err; // unexpected FS error\n }\n }\n\n // Write sentinel file before to block parallel processes\n writeSentinelFile(sentinelFilePath, currentTimestamp);\n\n try {\n await callback();\n\n // Write sentinel file after to ensure the first one has not been removed with cleanOutputDir\n writeSentinelFile(sentinelFilePath, currentTimestamp);\n } catch {\n try {\n await unlink(sentinelFilePath); // Remove sentinel file if an error occurs\n } catch {}\n }\n};\n"],"mappings":";;;;;;;AAuBA,MAAM,2BAA2B,EAC/B,gBAAgB,KAAK,KACtB;AAOD,MAAM,oBAAoB,OACxB,kBACA,qBACG;AACH,KAAI;AAEF,2DAAoB,iBAAiB,EAAE,EAAE,WAAW,MAAM,CAAC;EAG3D,MAAMA,OAAqB;GACzB,SAASC,
|
|
1
|
+
{"version":3,"file":"runOnce.cjs","names":["data: SentinelData","packageJson","err: any","cachedVersion: string | undefined"],"sources":["../../../src/utils/runOnce.ts"],"sourcesContent":["import { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport packageJson from '@intlayer/core/package.json' with { type: 'json' };\n\ntype RunOnceOptions = {\n /**\n * The function to execute when the sentinel is not found or is older than the cache timeout.\n */\n onIsCached?: () => void | Promise<void>;\n /**\n * The time window in milliseconds during which the sentinel is considered valid.\n *\n * @default 60000 = 1 minute\n */\n cacheTimeoutMs?: number;\n /**\n * If true, the callback will always run. If undefined, the callback will run only if the sentinel is older than the cache timeout.\n *\n * @default false\n */\n forceRun?: boolean;\n};\n\nconst DEFAULT_RUN_ONCE_OPTIONS = {\n cacheTimeoutMs: 60 * 1000, // 1 minute in milliseconds,\n} satisfies RunOnceOptions;\n\ntype SentinelData = {\n version: string;\n timestamp: number;\n};\n\nconst writeSentinelFile = async (\n sentinelFilePath: string,\n currentTimestamp: number\n) => {\n try {\n // Ensure the directory exists before writing the file\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n\n // O_EXCL ensures only the *first* process can create the file\n const data: SentinelData = {\n version: packageJson.version,\n timestamp: currentTimestamp,\n };\n await writeFile(sentinelFilePath, JSON.stringify(data), { flag: 'wx' });\n } catch (err: any) {\n if (err.code === 'EEXIST') {\n // Another process already created it → we're done\n return;\n }\n throw err; // unexpected FS error\n }\n};\n\n/**\n * Ensures a callback function runs only once within a specified time window across multiple processes.\n * Uses a sentinel file to coordinate execution and prevent duplicate work.\n *\n * @param sentinelFilePath - Path to the sentinel file used for coordination\n * @param callback - The function to execute (should be async)\n * @param options - The options for the runOnce function\n *\n * @example\n * ```typescript\n * await runPrepareIntlayerOnce(\n * '/tmp/intlayer-sentinel',\n * async () => {\n * // Your initialization logic here\n * await prepareIntlayer();\n * },\n * 30 * 1000 // 30 seconds cache\n * );\n * ```\n *\n * @throws {Error} When there are unexpected filesystem errors\n */\nexport const runOnce = async (\n sentinelFilePath: string,\n callback: () => void | Promise<void>,\n options?: RunOnceOptions\n) => {\n const { onIsCached, cacheTimeoutMs, forceRun } = {\n ...DEFAULT_RUN_ONCE_OPTIONS,\n ...(options ?? {}),\n };\n const currentTimestamp = Date.now();\n\n try {\n // Check if sentinel file exists and get its stats\n const sentinelStats = await stat(sentinelFilePath);\n const sentinelAge = currentTimestamp - sentinelStats.mtime.getTime();\n\n // Determine if we should rebuild based on cache age, force flag, or version mismatch\n let shouldRebuild = Boolean(forceRun) || sentinelAge > cacheTimeoutMs!;\n\n if (!shouldRebuild) {\n try {\n const raw = await readFile(sentinelFilePath, 'utf8');\n let cachedVersion: string | undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<SentinelData>;\n cachedVersion = parsed.version;\n } catch {\n // Legacy format (timestamp only). Force a rebuild once to write versioned sentinel.\n cachedVersion = undefined;\n }\n\n if (!cachedVersion || cachedVersion !== packageJson.version) {\n shouldRebuild = true;\n }\n } catch {\n // If we cannot read the file, err on the safe side and rebuild\n shouldRebuild = true;\n }\n }\n\n if (shouldRebuild) {\n try {\n await unlink(sentinelFilePath);\n } catch {}\n // Fall through to create new sentinel and rebuild\n } else {\n await onIsCached?.();\n // Sentinel is recent and versions match, no need to rebuild\n return;\n }\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n // File doesn't exist, continue to create it\n } else {\n throw err; // unexpected FS error\n }\n }\n\n // Write sentinel file before to block parallel processes\n writeSentinelFile(sentinelFilePath, currentTimestamp);\n\n try {\n await callback();\n\n // Write sentinel file after to ensure the first one has not been removed with cleanOutputDir\n writeSentinelFile(sentinelFilePath, currentTimestamp);\n } catch {\n try {\n await unlink(sentinelFilePath); // Remove sentinel file if an error occurs\n } catch {}\n }\n};\n"],"mappings":";;;;;;;AAuBA,MAAM,2BAA2B,EAC/B,gBAAgB,KAAK,KACtB;AAOD,MAAM,oBAAoB,OACxB,kBACA,qBACG;AACH,KAAI;AAEF,2DAAoB,iBAAiB,EAAE,EAAE,WAAW,MAAM,CAAC;EAG3D,MAAMA,OAAqB;GACzB,SAASC,oCAAY;GACrB,WAAW;GACZ;AACD,wCAAgB,kBAAkB,KAAK,UAAU,KAAK,EAAE,EAAE,MAAM,MAAM,CAAC;UAChEC,KAAU;AACjB,MAAI,IAAI,SAAS,SAEf;AAEF,QAAM;;;;;;;;;;;;;;;;;;;;;;;;;AA0BV,MAAa,UAAU,OACrB,kBACA,UACA,YACG;CACH,MAAM,EAAE,YAAY,gBAAgB,aAAa;EAC/C,GAAG;EACH,GAAI,WAAW,EAAE;EAClB;CACD,MAAM,mBAAmB,KAAK,KAAK;AAEnC,KAAI;EAGF,MAAM,cAAc,oBADE,iCAAW,iBAAiB,EACG,MAAM,SAAS;EAGpE,IAAI,gBAAgB,QAAQ,SAAS,IAAI,cAAc;AAEvD,MAAI,CAAC,cACH,KAAI;GACF,MAAM,MAAM,qCAAe,kBAAkB,OAAO;GACpD,IAAIC;AACJ,OAAI;AAEF,oBADe,KAAK,MAAM,IAAI,CACP;WACjB;AAEN,oBAAgB;;AAGlB,OAAI,CAAC,iBAAiB,kBAAkBF,oCAAY,QAClD,iBAAgB;UAEZ;AAEN,mBAAgB;;AAIpB,MAAI,cACF,KAAI;AACF,sCAAa,iBAAiB;UACxB;OAEH;AACL,SAAM,cAAc;AAEpB;;UAEKC,KAAU;AACjB,MAAI,IAAI,SAAS,UAAU,OAGzB,OAAM;;AAKV,mBAAkB,kBAAkB,iBAAiB;AAErD,KAAI;AACF,QAAM,UAAU;AAGhB,oBAAkB,kBAAkB,iBAAiB;SAC/C;AACN,MAAI;AACF,sCAAa,iBAAiB;UACxB"}
|
|
@@ -27,7 +27,7 @@ const runParallel = (proc) => {
|
|
|
27
27
|
cwd: process.cwd(),
|
|
28
28
|
stdio: "inherit",
|
|
29
29
|
env: childEnv,
|
|
30
|
-
shell:
|
|
30
|
+
shell: isWin
|
|
31
31
|
};
|
|
32
32
|
const child = isArray ? args.length === 0 && /\s/.test(command) ? isWin ? spawnFunc(process.env.ComSpec ?? "cmd.exe", [
|
|
33
33
|
"/d",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["delimiter","spawnWin32","spawnPosix","signalHandlers: { event: string; handler: (...args: any[]) => void }[]"],"sources":["../../../../src/utils/runParallel/index.ts"],"sourcesContent":["import { delimiter, join } from 'node:path';\nimport { spawnPosix } from './spawnPosix';\nimport { spawnWin32 } from './spawnWin32';\n\nexport type ParallelHandle = {\n kill: () => void;\n result: Promise<any>;\n commandText: string;\n};\n\n/**\n * Start a cross-platform parallel process using npm-run-all approach.\n * Accepts either a single string (e.g., 'next start') or an array of tokens (e.g., ['next', 'start']).\n */\nexport const runParallel = (proc?: string | string[]): ParallelHandle => {\n if (!proc || (Array.isArray(proc) && proc.length === 0))\n throw new Error('Invalid command');\n\n const commandText = Array.isArray(proc) ? proc.join(' ') : proc;\n\n const isArray = Array.isArray(proc);\n const command = isArray ? (proc as string[])[0] : commandText;\n const args = isArray ? (proc as string[]).slice(1) : [];\n\n // Ensure local binaries (node_modules/.bin) are resolvable\n const cwdBin = join(process.cwd(), 'node_modules', '.bin');\n const PATH_KEY =\n Object.keys(process.env).find((key) => key.toLowerCase() === 'path') ??\n 'PATH';\n\n const extendedPath = [cwdBin, process.env[PATH_KEY] ?? '']\n .filter(Boolean)\n .join(delimiter);\n\n const childEnv = {\n ...process.env,\n [PATH_KEY]: extendedPath,\n } as NodeJS.ProcessEnv;\n\n const isWin = process.platform === 'win32';\n const spawnFunc = isWin ? spawnWin32 : spawnPosix;\n\n // Spawn options\n const spawnOptions = {\n cwd: process.cwd(),\n stdio: 'inherit' as const,\n env: childEnv,\n shell:
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["delimiter","spawnWin32","spawnPosix","signalHandlers: { event: string; handler: (...args: any[]) => void }[]"],"sources":["../../../../src/utils/runParallel/index.ts"],"sourcesContent":["import { delimiter, join } from 'node:path';\nimport { spawnPosix } from './spawnPosix';\nimport { spawnWin32 } from './spawnWin32';\n\nexport type ParallelHandle = {\n kill: () => void;\n result: Promise<any>;\n commandText: string;\n};\n\n/**\n * Start a cross-platform parallel process using npm-run-all approach.\n * Accepts either a single string (e.g., 'next start') or an array of tokens (e.g., ['next', 'start']).\n */\nexport const runParallel = (proc?: string | string[]): ParallelHandle => {\n if (!proc || (Array.isArray(proc) && proc.length === 0))\n throw new Error('Invalid command');\n\n const commandText = Array.isArray(proc) ? proc.join(' ') : proc;\n\n const isArray = Array.isArray(proc);\n const command = isArray ? (proc as string[])[0] : commandText;\n const args = isArray ? (proc as string[]).slice(1) : [];\n\n // Ensure local binaries (node_modules/.bin) are resolvable\n const cwdBin = join(process.cwd(), 'node_modules', '.bin');\n const PATH_KEY =\n Object.keys(process.env).find((key) => key.toLowerCase() === 'path') ??\n 'PATH';\n\n const extendedPath = [cwdBin, process.env[PATH_KEY] ?? '']\n .filter(Boolean)\n .join(delimiter);\n\n const childEnv = {\n ...process.env,\n [PATH_KEY]: extendedPath,\n } as NodeJS.ProcessEnv;\n\n const isWin = process.platform === 'win32';\n const spawnFunc = isWin ? spawnWin32 : spawnPosix;\n\n // Spawn options\n const spawnOptions = {\n cwd: process.cwd(),\n stdio: 'inherit' as const,\n env: childEnv,\n shell: isWin,\n };\n\n // Spawn the child process\n const child = isArray\n ? // If provided as a single string element that includes spaces, treat it like a shell command\n args.length === 0 && /\\s/.test(command)\n ? isWin\n ? spawnFunc(\n process.env.ComSpec ?? 'cmd.exe',\n ['/d', '/s', '/c', command],\n spawnOptions\n )\n : spawnFunc(\n process.env.SHELL ?? '/bin/sh',\n ['-c', command],\n spawnOptions\n )\n : spawnFunc(command, args, spawnOptions)\n : isWin\n ? spawnFunc(\n process.env.ComSpec ?? 'cmd.exe',\n ['/d', '/s', '/c', commandText],\n spawnOptions\n )\n : spawnFunc(\n process.env.SHELL ?? '/bin/sh',\n ['-c', commandText],\n spawnOptions\n );\n\n const result = new Promise<void>((resolve, reject) => {\n child.on('error', (err) => {\n try {\n console.error(\n `[runParallel] Failed to start: ${err?.message ?? String(err)}`\n );\n } catch {}\n cleanupHandlers();\n reject(err);\n });\n\n child.on('exit', (code, signal) => {\n cleanupHandlers();\n\n // Treat common termination signals as graceful exits, not failures\n const gracefulSignals = ['SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGHUP'];\n if (code === 0 || (signal && gracefulSignals.includes(signal))) {\n resolve();\n } else {\n reject(\n Object.assign(new Error('Parallel process failed'), { code, signal })\n );\n }\n });\n });\n\n const cleanup = () => {\n try {\n child.kill('SIGTERM');\n } catch {\n // Best effort\n }\n };\n\n const signalHandlers: { event: string; handler: (...args: any[]) => void }[] =\n [\n { event: 'SIGINT', handler: cleanup },\n { event: 'SIGTERM', handler: cleanup },\n { event: 'SIGQUIT', handler: cleanup },\n { event: 'SIGHUP', handler: cleanup },\n ];\n\n // Register signal handlers\n signalHandlers.forEach(({ event, handler }) => {\n process.on(event as any, handler as any);\n });\n\n const cleanupHandlers = () => {\n signalHandlers.forEach(({ event, handler }) => {\n process.off(event as any, handler as any);\n });\n };\n\n const kill = () => {\n try {\n child.kill('SIGTERM');\n } catch {\n // Best effort\n }\n };\n\n return { kill, result, commandText };\n};\n"],"mappings":";;;;;;;;;;AAcA,MAAa,eAAe,SAA6C;AACvE,KAAI,CAAC,QAAS,MAAM,QAAQ,KAAK,I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AAiB;AACjB,UAAO,IAAI;IACX;AAEF,QAAM,GAAG,SAAS,MAAM,WAAW;AACjC,oBAAiB;AAIjB,OAAI,SAAS,KAAM,UADK;IAAC;IAAU;IAAW;IAAW;IAAS,CACrB,SAAS,OAAO,CAC3D,UAAS;OAET,QACE,OAAO,uBAAO,IAAI,MAAM,0BAA0B,EAAE;IAAE;IAAM;IAAQ,CAAC,CACtE;IAEH;GACF;CAEF,MAAM,gBAAgB;AACpB,MAAI;AACF,SAAM,KAAK,UAAU;UACf;;CAKV,MAAMC,iBACJ;EACE;GAAE,OAAO;GAAU,SAAS;GAAS;EACrC;GAAE,OAAO;GAAW,SAAS;GAAS;EACtC;GAAE,OAAO;GAAW,SAAS;GAAS;EACtC;GAAE,OAAO;GAAU,SAAS;GAAS;EACtC;AAGH,gBAAe,SAAS,EAAE,OAAO,cAAc;AAC7C,UAAQ,GAAG,OAAc,QAAe;GACxC;CAEF,MAAM,wBAAwB;AAC5B,iBAAe,SAAS,EAAE,OAAO,cAAc;AAC7C,WAAQ,IAAI,OAAc,QAAe;IACzC;;CAGJ,MAAM,aAAa;AACjB,MAAI;AACF,SAAM,KAAK,UAAU;UACf;;AAKV,QAAO;EAAE;EAAM;EAAQ;EAAa"}
|
package/dist/cjs/watcher.cjs
CHANGED
|
@@ -3,7 +3,7 @@ const require_handleAdditionalContentDeclarationFile = require('./handleAddition
|
|
|
3
3
|
const require_handleContentDeclarationFileChange = require('./handleContentDeclarationFileChange.cjs');
|
|
4
4
|
const require_handleUnlinkedContentDeclarationFile = require('./handleUnlinkedContentDeclarationFile.cjs');
|
|
5
5
|
const require_prepareIntlayer = require('./prepareIntlayer.cjs');
|
|
6
|
-
let
|
|
6
|
+
let _intlayer_config = require("@intlayer/config");
|
|
7
7
|
let node_path = require("node:path");
|
|
8
8
|
let chokidar = require("chokidar");
|
|
9
9
|
|
|
@@ -11,8 +11,8 @@ let chokidar = require("chokidar");
|
|
|
11
11
|
/** @ts-ignore remove error Module '"chokidar"' has no exported member 'ChokidarOptions'. */
|
|
12
12
|
const recentlyAddedFiles = /* @__PURE__ */ new Set();
|
|
13
13
|
const watch = (options) => {
|
|
14
|
-
const configuration = options?.configuration ?? (0,
|
|
15
|
-
const appLogger = (0,
|
|
14
|
+
const configuration = options?.configuration ?? (0, _intlayer_config.getConfiguration)(options?.configOptions);
|
|
15
|
+
const appLogger = (0, _intlayer_config.getAppLogger)(configuration);
|
|
16
16
|
const { watch: isWatchMode, watchedFilesPatternWithPath } = configuration.content;
|
|
17
17
|
/** @ts-ignore remove error Expected 0-1 arguments, but got 2. */
|
|
18
18
|
return (0, chokidar.watch)(watchedFilesPatternWithPath, {
|
|
@@ -48,10 +48,10 @@ const watch = (options) => {
|
|
|
48
48
|
};
|
|
49
49
|
const buildAndWatchIntlayer = async (options) => {
|
|
50
50
|
const { skipPrepare, ...rest } = options ?? {};
|
|
51
|
-
const configuration = options?.configuration ?? (0,
|
|
51
|
+
const configuration = options?.configuration ?? (0, _intlayer_config.getConfiguration)(options?.configOptions);
|
|
52
52
|
if (!options?.skipPrepare) await require_prepareIntlayer.prepareIntlayer(configuration, { forceRun: true });
|
|
53
53
|
if (configuration.content.watch || options?.persistent) {
|
|
54
|
-
(0,
|
|
54
|
+
(0, _intlayer_config.getAppLogger)(configuration)("Watching Intlayer content declarations");
|
|
55
55
|
watch({
|
|
56
56
|
...rest,
|
|
57
57
|
configuration
|
package/dist/cjs/watcher.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watcher.cjs","names":["handleAdditionalContentDeclarationFile","handleContentDeclarationFileChange","handleUnlinkedContentDeclarationFile","prepareIntlayer"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport {\n type GetConfigurationOptions,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { IntlayerConfig } from '@intlayer/types';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions'. */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\n\nconst recentlyAddedFiles = new Set<string>();\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { watch: isWatchMode, watchedFilesPatternWithPath } =\n configuration.content;\n\n /** @ts-ignore remove error Expected 0-1 arguments, but got 2. */\n return chokidarWatch(watchedFilesPatternWithPath, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n ignored: [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n ],\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n recentlyAddedFiles.add(fileName);\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n\n setTimeout(() => recentlyAddedFiles.delete(fileName), 1000); // Allow time for unlink to trigger if it's a move\n })\n .on(\n 'change',\n async (filePath) =>\n await handleContentDeclarationFileChange(filePath, configuration)\n )\n .on('unlink', async (filePath) => {\n setTimeout(async () => {\n const fileName = basename(filePath);\n\n if (recentlyAddedFiles.has(fileName)) {\n // The file was moved, so ignore unlink\n return;\n }\n\n await handleUnlinkedContentDeclarationFile(filePath, configuration);\n }, 300); // Allow time for unlink to trigger if it's a move\n })\n .on('error', async (error) => {\n appLogger(`Watcher error: ${error}`, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!options?.skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n if (configuration.content.watch || options?.persistent) {\n const appLogger = getAppLogger(configuration);\n\n appLogger('Watching Intlayer content declarations');\n // Start watching (assuming watch is also async)\n watch({ ...rest, configuration });\n }\n};\n"],"mappings":";;;;;;;;;;;AAcA,MAAM,qCAAqB,IAAI,KAAa;AAS5C,MAAa,SAAS,YAA2B;CAC/C,MAAM,gBACJ,SAAS,
|
|
1
|
+
{"version":3,"file":"watcher.cjs","names":["handleAdditionalContentDeclarationFile","handleContentDeclarationFileChange","handleUnlinkedContentDeclarationFile","prepareIntlayer"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport {\n type GetConfigurationOptions,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { IntlayerConfig } from '@intlayer/types';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions'. */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\n\nconst recentlyAddedFiles = new Set<string>();\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { watch: isWatchMode, watchedFilesPatternWithPath } =\n configuration.content;\n\n /** @ts-ignore remove error Expected 0-1 arguments, but got 2. */\n return chokidarWatch(watchedFilesPatternWithPath, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n ignored: [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n ],\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n recentlyAddedFiles.add(fileName);\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n\n setTimeout(() => recentlyAddedFiles.delete(fileName), 1000); // Allow time for unlink to trigger if it's a move\n })\n .on(\n 'change',\n async (filePath) =>\n await handleContentDeclarationFileChange(filePath, configuration)\n )\n .on('unlink', async (filePath) => {\n setTimeout(async () => {\n const fileName = basename(filePath);\n\n if (recentlyAddedFiles.has(fileName)) {\n // The file was moved, so ignore unlink\n return;\n }\n\n await handleUnlinkedContentDeclarationFile(filePath, configuration);\n }, 300); // Allow time for unlink to trigger if it's a move\n })\n .on('error', async (error) => {\n appLogger(`Watcher error: ${error}`, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!options?.skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n if (configuration.content.watch || options?.persistent) {\n const appLogger = getAppLogger(configuration);\n\n appLogger('Watching Intlayer content declarations');\n // Start watching (assuming watch is also async)\n watch({ ...rest, configuration });\n }\n};\n"],"mappings":";;;;;;;;;;;AAcA,MAAM,qCAAqB,IAAI,KAAa;AAS5C,MAAa,SAAS,YAA2B;CAC/C,MAAM,gBACJ,SAAS,wDAAkC,SAAS,cAAc;CACpE,MAAM,+CAAyB,cAAc;CAE7C,MAAM,EAAE,OAAO,aAAa,gCAC1B,cAAc;;AAGhB,4BAAqB,6BAA6B;EAChD,YAAY;EACZ,eAAe;EACf,kBAAkB;GAChB,oBAAoB;GACpB,cAAc;GACf;EACD,SAAS;GACP;GACA;GACA;GACA;GACD;EACD,GAAG;EACJ,CAAC,CACC,GAAG,OAAO,OAAO,aAAa;EAC7B,MAAM,mCAAoB,SAAS;AACnC,qBAAmB,IAAI,SAAS;AAEhC,QAAMA,sFAAuC,UAAU,cAAc;AAErE,mBAAiB,mBAAmB,OAAO,SAAS,EAAE,IAAK;GAC3D,CACD,GACC,UACA,OAAO,aACL,MAAMC,8EAAmC,UAAU,cAAc,CACpE,CACA,GAAG,UAAU,OAAO,aAAa;AAChC,aAAW,YAAY;GACrB,MAAM,mCAAoB,SAAS;AAEnC,OAAI,mBAAmB,IAAI,SAAS,CAElC;AAGF,SAAMC,kFAAqC,UAAU,cAAc;KAClE,IAAI;GACP,CACD,GAAG,SAAS,OAAO,UAAU;AAC5B,YAAU,kBAAkB,SAAS,EACnC,OAAO,SACR,CAAC;AAEF,YAAU,qBAAqB;AAE/B,QAAMC,wCAAgB,cAAc;GACpC;;AAGN,MAAa,wBAAwB,OAAO,YAA2B;CACrE,MAAM,EAAE,aAAa,GAAG,SAAS,WAAW,EAAE;CAC9C,MAAM,gBACJ,SAAS,wDAAkC,SAAS,cAAc;AAEpE,KAAI,CAAC,SAAS,YACZ,OAAMA,wCAAgB,eAAe,EAAE,UAAU,MAAM,CAAC;AAG1D,KAAI,cAAc,QAAQ,SAAS,SAAS,YAAY;AAGtD,qCAF+B,cAAc,CAEnC,yCAAyC;AAEnD,QAAM;GAAE,GAAG;GAAM;GAAe,CAAC"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let
|
|
2
|
+
let _intlayer_config = require("@intlayer/config");
|
|
3
3
|
|
|
4
4
|
//#region src/writeContentDeclaration/detectFormatCommand.ts
|
|
5
5
|
const detectFormatCommand = (configuration) => {
|
|
6
6
|
try {
|
|
7
7
|
const { formatCommand, baseDir } = configuration.content;
|
|
8
|
-
const projectRequire = (0,
|
|
8
|
+
const projectRequire = (0, _intlayer_config.getProjectRequire)(baseDir);
|
|
9
9
|
if (formatCommand) return formatCommand;
|
|
10
10
|
try {
|
|
11
11
|
projectRequire.resolve("prettier");
|
|
@@ -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 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,
|
|
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,yDAAmC,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,9 +1,9 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
let node_fs = require("node:fs");
|
|
3
|
-
let
|
|
3
|
+
let _intlayer_config = require("@intlayer/config");
|
|
4
4
|
let node_path = require("node:path");
|
|
5
|
-
let
|
|
6
|
-
let
|
|
5
|
+
let _intlayer_core = require("@intlayer/core");
|
|
6
|
+
let _intlayer_types = require("@intlayer/types");
|
|
7
7
|
|
|
8
8
|
//#region src/writeContentDeclaration/processContentDeclarationContent.ts
|
|
9
9
|
/**
|
|
@@ -11,7 +11,7 @@ let __intlayer_types = require("@intlayer/types");
|
|
|
11
11
|
*/
|
|
12
12
|
const writeFilePlugin = {
|
|
13
13
|
id: "write-file-plugin",
|
|
14
|
-
canHandle: (node) => typeof node === "object" && node?.nodeType ===
|
|
14
|
+
canHandle: (node) => typeof node === "object" && node?.nodeType === _intlayer_types.NodeType.File,
|
|
15
15
|
transform: (node) => {
|
|
16
16
|
const fileContent = node.content;
|
|
17
17
|
const filePath = node.fixedPath;
|
|
@@ -23,11 +23,11 @@ const writeFilePlugin = {
|
|
|
23
23
|
if (!(0, node_fs.existsSync)(fileDirectory)) (0, node_fs.mkdirSync)(fileDirectory, { recursive: true });
|
|
24
24
|
(0, node_fs.writeFileSync)(absoluteFilePath, fileContent);
|
|
25
25
|
} catch (error) {
|
|
26
|
-
throw new Error(`${
|
|
26
|
+
throw new Error(`${_intlayer_config.x} Error writing file to ${(0, _intlayer_config.colorizePath)(filePath)}: ${error}`);
|
|
27
27
|
}
|
|
28
28
|
return {
|
|
29
|
-
nodeType:
|
|
30
|
-
[
|
|
29
|
+
nodeType: _intlayer_types.NodeType.File,
|
|
30
|
+
[_intlayer_types.NodeType.File]: node.file
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
33
|
};
|
|
@@ -36,11 +36,11 @@ const writeFilePlugin = {
|
|
|
36
36
|
*/
|
|
37
37
|
const markdownFilePlugin = {
|
|
38
38
|
id: "markdown-file-plugin",
|
|
39
|
-
canHandle: (node) => typeof node === "object" && node?.nodeType ===
|
|
39
|
+
canHandle: (node) => typeof node === "object" && node?.nodeType === _intlayer_types.NodeType.Markdown,
|
|
40
40
|
transform: (node, props, deepTransformNode$1) => {
|
|
41
41
|
return {
|
|
42
|
-
nodeType:
|
|
43
|
-
[
|
|
42
|
+
nodeType: _intlayer_types.NodeType.Markdown,
|
|
43
|
+
[_intlayer_types.NodeType.Markdown]: deepTransformNode$1(node.markdown, props)
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
46
|
};
|
|
@@ -49,15 +49,15 @@ const markdownFilePlugin = {
|
|
|
49
49
|
*/
|
|
50
50
|
const insertionFilePlugin = {
|
|
51
51
|
id: "insertion-file-plugin",
|
|
52
|
-
canHandle: (node) => typeof node === "object" && node?.nodeType ===
|
|
52
|
+
canHandle: (node) => typeof node === "object" && node?.nodeType === _intlayer_types.NodeType.Insertion,
|
|
53
53
|
transform: (node, props, deepTransformNode$1) => {
|
|
54
54
|
return {
|
|
55
|
-
nodeType:
|
|
56
|
-
[
|
|
55
|
+
nodeType: _intlayer_types.NodeType.Insertion,
|
|
56
|
+
[_intlayer_types.NodeType.Insertion]: deepTransformNode$1(node.insertion, props)
|
|
57
57
|
};
|
|
58
58
|
}
|
|
59
59
|
};
|
|
60
|
-
const processContentDeclarationContent = async (dictionary) => (0,
|
|
60
|
+
const processContentDeclarationContent = async (dictionary) => (0, _intlayer_core.deepTransformNode)(dictionary, {
|
|
61
61
|
dictionaryKey: dictionary.key,
|
|
62
62
|
keyPath: [],
|
|
63
63
|
plugins: [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processContentDeclarationContent.cjs","names":["writeFilePlugin: Plugins","NodeType","x","markdownFilePlugin: Plugins","deepTransformNode","insertionFilePlugin: Plugins"],"sources":["../../../src/writeContentDeclaration/processContentDeclarationContent.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config';\nimport {\n deepTransformNode,\n type FileContent,\n type FileContentConstructor,\n type InsertionContent,\n type InsertionContentConstructor,\n type MarkdownContent,\n type MarkdownContentConstructor,\n type Plugins,\n} from '@intlayer/core';\nimport { type Dictionary, NodeType } from '@intlayer/types';\n\n/**\n * Write file plugin\n */\n\nconst writeFilePlugin: Plugins = {\n id: 'write-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.File,\n transform: (node: FileContent) => {\n const fileContent = node.content;\n const filePath = node.fixedPath;\n\n if (typeof fileContent !== 'string') {\n throw new Error('File content must be a string');\n }\n\n if (typeof filePath !== 'string') {\n throw new Error('File path must be a string');\n }\n\n // Write the file to the file system\n try {\n const absoluteFilePath = join(process.cwd(), filePath);\n\n // Create the file directory if it doesn't exist\n const fileDirectory = dirname(absoluteFilePath);\n\n if (!existsSync(fileDirectory)) {\n mkdirSync(fileDirectory, { recursive: true });\n }\n\n // Write the file\n writeFileSync(absoluteFilePath, fileContent);\n } catch (error) {\n throw new Error(\n `${x} Error writing file to ${colorizePath(filePath)}: ${error}`\n );\n }\n\n const transformedFileContent: FileContentConstructor = {\n nodeType: NodeType.File,\n [NodeType.File]: node.file,\n };\n\n return transformedFileContent;\n },\n};\n\n/**\n * Markdown file plugin\n */\n\nconst markdownFilePlugin: Plugins = {\n id: 'markdown-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Markdown,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const simplifiedMarkdownNode: MarkdownContentConstructor = {\n nodeType: NodeType.Markdown,\n [NodeType.Markdown]: deepTransformNode(node.markdown, props),\n };\n\n return simplifiedMarkdownNode;\n },\n};\n\n/**\n * Insertion file plugin\n */\n\nconst insertionFilePlugin: Plugins = {\n id: 'insertion-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Insertion,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const simplifiedInsertionNode: InsertionContentConstructor = {\n nodeType: NodeType.Insertion,\n [NodeType.Insertion]: deepTransformNode(node.insertion, props),\n };\n\n return simplifiedInsertionNode;\n },\n};\n\nexport const processContentDeclarationContent = async (\n dictionary: Dictionary\n) =>\n deepTransformNode(dictionary, {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [writeFilePlugin, markdownFilePlugin, insertionFilePlugin],\n });\n"],"mappings":";;;;;;;;;;;AAmBA,MAAMA,kBAA2B;CAC/B,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAaC,
|
|
1
|
+
{"version":3,"file":"processContentDeclarationContent.cjs","names":["writeFilePlugin: Plugins","NodeType","x","markdownFilePlugin: Plugins","deepTransformNode","insertionFilePlugin: Plugins"],"sources":["../../../src/writeContentDeclaration/processContentDeclarationContent.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config';\nimport {\n deepTransformNode,\n type FileContent,\n type FileContentConstructor,\n type InsertionContent,\n type InsertionContentConstructor,\n type MarkdownContent,\n type MarkdownContentConstructor,\n type Plugins,\n} from '@intlayer/core';\nimport { type Dictionary, NodeType } from '@intlayer/types';\n\n/**\n * Write file plugin\n */\n\nconst writeFilePlugin: Plugins = {\n id: 'write-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.File,\n transform: (node: FileContent) => {\n const fileContent = node.content;\n const filePath = node.fixedPath;\n\n if (typeof fileContent !== 'string') {\n throw new Error('File content must be a string');\n }\n\n if (typeof filePath !== 'string') {\n throw new Error('File path must be a string');\n }\n\n // Write the file to the file system\n try {\n const absoluteFilePath = join(process.cwd(), filePath);\n\n // Create the file directory if it doesn't exist\n const fileDirectory = dirname(absoluteFilePath);\n\n if (!existsSync(fileDirectory)) {\n mkdirSync(fileDirectory, { recursive: true });\n }\n\n // Write the file\n writeFileSync(absoluteFilePath, fileContent);\n } catch (error) {\n throw new Error(\n `${x} Error writing file to ${colorizePath(filePath)}: ${error}`\n );\n }\n\n const transformedFileContent: FileContentConstructor = {\n nodeType: NodeType.File,\n [NodeType.File]: node.file,\n };\n\n return transformedFileContent;\n },\n};\n\n/**\n * Markdown file plugin\n */\n\nconst markdownFilePlugin: Plugins = {\n id: 'markdown-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Markdown,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const simplifiedMarkdownNode: MarkdownContentConstructor = {\n nodeType: NodeType.Markdown,\n [NodeType.Markdown]: deepTransformNode(node.markdown, props),\n };\n\n return simplifiedMarkdownNode;\n },\n};\n\n/**\n * Insertion file plugin\n */\n\nconst insertionFilePlugin: Plugins = {\n id: 'insertion-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Insertion,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const simplifiedInsertionNode: InsertionContentConstructor = {\n nodeType: NodeType.Insertion,\n [NodeType.Insertion]: deepTransformNode(node.insertion, props),\n };\n\n return simplifiedInsertionNode;\n },\n};\n\nexport const processContentDeclarationContent = async (\n dictionary: Dictionary\n) =>\n deepTransformNode(dictionary, {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [writeFilePlugin, markdownFilePlugin, insertionFilePlugin],\n });\n"],"mappings":";;;;;;;;;;;AAmBA,MAAMA,kBAA2B;CAC/B,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAaC,yBAAS;CAC1D,YAAY,SAAsB;EAChC,MAAM,cAAc,KAAK;EACzB,MAAM,WAAW,KAAK;AAEtB,MAAI,OAAO,gBAAgB,SACzB,OAAM,IAAI,MAAM,gCAAgC;AAGlD,MAAI,OAAO,aAAa,SACtB,OAAM,IAAI,MAAM,6BAA6B;AAI/C,MAAI;GACF,MAAM,uCAAwB,QAAQ,KAAK,EAAE,SAAS;GAGtD,MAAM,uCAAwB,iBAAiB;AAE/C,OAAI,yBAAY,cAAc,CAC5B,wBAAU,eAAe,EAAE,WAAW,MAAM,CAAC;AAI/C,8BAAc,kBAAkB,YAAY;WACrC,OAAO;AACd,SAAM,IAAI,MACR,GAAGC,mBAAE,4DAAsC,SAAS,CAAC,IAAI,QAC1D;;AAQH,SALuD;GACrD,UAAUD,yBAAS;IAClBA,yBAAS,OAAO,KAAK;GACvB;;CAIJ;;;;AAMD,MAAME,qBAA8B;CAClC,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAaF,yBAAS;CAC1D,YAAY,MAAuB,OAAO,wBAAsB;AAM9D,SAL2D;GACzD,UAAUA,yBAAS;IAClBA,yBAAS,WAAWG,oBAAkB,KAAK,UAAU,MAAM;GAC7D;;CAIJ;;;;AAMD,MAAMC,sBAA+B;CACnC,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAaJ,yBAAS;CA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