@intlayer/chokidar 8.7.6-canary.0 → 8.7.7
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/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs.map +1 -1
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
- package/dist/cjs/init/utils/jsonParser.cjs.map +1 -1
- package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
- package/dist/cjs/initConfig/index.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
- package/dist/cjs/logConfigDetails.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
- package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
- package/dist/cjs/utils/buildComponentFilesList.cjs.map +1 -1
- package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
- package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
- package/dist/cjs/utils/getContentExtension.cjs.map +1 -1
- package/dist/cjs/utils/pLimit.cjs +6 -1
- package/dist/cjs/utils/pLimit.cjs.map +1 -1
- package/dist/cjs/utils/resolveObjectPromises.cjs.map +1 -1
- package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -1
- package/dist/cjs/utils/runOnce.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bootstrap.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
- package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs.map +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs.map +1 -1
- package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
- package/dist/esm/createType/createType.mjs.map +1 -1
- package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
- package/dist/esm/filterInvalidDictionaries.mjs.map +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileMoved.mjs.map +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
- package/dist/esm/init/utils/jsonParser.mjs.map +1 -1
- package/dist/esm/init/utils/tsConfig.mjs.map +1 -1
- package/dist/esm/initConfig/index.mjs.map +1 -1
- package/dist/esm/installSkills/index.mjs.map +1 -1
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/listGitFiles.mjs.map +1 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
- package/dist/esm/logConfigDetails.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
- package/dist/esm/utils/autoDecorateContent.mjs.map +1 -1
- package/dist/esm/utils/buildComponentFilesList.mjs.map +1 -1
- package/dist/esm/utils/buildFilesList.mjs.map +1 -1
- package/dist/esm/utils/chunkJSON.mjs.map +1 -1
- package/dist/esm/utils/getContentExtension.mjs.map +1 -1
- package/dist/esm/utils/pLimit.mjs +6 -1
- package/dist/esm/utils/pLimit.mjs.map +1 -1
- package/dist/esm/utils/resolveObjectPromises.mjs.map +1 -1
- package/dist/esm/utils/resolveRelativePath.mjs.map +1 -1
- package/dist/esm/utils/runOnce.mjs.map +1 -1
- package/dist/esm/utils/runParallel/bin.mjs.map +1 -1
- package/dist/esm/utils/runParallel/bootstrap.mjs.map +1 -1
- package/dist/esm/utils/runParallel/index.mjs.map +1 -1
- package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
- package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
- package/dist/esm/writeFileIfChanged.mjs.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSFile.cjs","names":["NodeTypes","babelTsParser"],"sources":["../../../src/writeContentDeclaration/transformJSFile.ts"],"sourcesContent":["import { getNodeType } from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport * as recast from 'recast';\nimport * as babelTsParser from 'recast/parsers/babel-ts.js';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Unwraps TypeScript/Babel expression wrappers (satisfies, as, !, <Type>).\n * Uses string fallbacks to bypass outdated ast-types definitions.\n */\nconst unwrap = (node: any) => {\n while (\n node &&\n (n.TSSatisfiesExpression?.check(node) ||\n n.TSAsExpression?.check(node) ||\n n.TSTypeAssertion?.check(node) ||\n n.TSNonNullExpression?.check(node) ||\n [\n 'TSSatisfiesExpression',\n 'TSAsExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n ].includes(node.type))\n ) {\n node = node.expression;\n }\n return node;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n\n return false;\n });\n};\n\n/**\n * Synchronizes numeric suffixes across locales.\n * E.g. \"Hello 1\" -> \"Hello 3\" updates \"Bonjour 1\" to \"Bonjour 3\".\n */\nconst syncNumericSuffixAcrossLocales = (\n existingNode: any,\n fallbackLocaleCode: string,\n newFallbackValue: string\n) => {\n const trailingNumberMatch = newFallbackValue.match(/\\d+(?!.*\\d)/);\n if (!trailingNumberMatch) return;\n const newTrailingNumber = trailingNumberMatch[0];\n\n if (n.ObjectExpression.check(existingNode)) {\n for (const prop of existingNode.properties) {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (\n n.Literal.check(prop.key) &&\n typeof prop.key.value === 'string'\n )\n propName = prop.key.value;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n\n if (propName && propName !== fallbackLocaleCode) {\n if (\n n.Literal.check(prop.value) &&\n typeof prop.value.value === 'string'\n ) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.literal(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n } else if (n.StringLiteral.check(prop.value)) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.stringLiteral(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n }\n }\n }\n }\n }\n};\n\n/**\n * Checks if a value represents a multilingual Intlayer node.\n * A node is multilingual if it is a Translation node, or if it is a specialized node\n * (Markdown, HTML, etc.) that contains a Translation node.\n */\nconst isMultilingualNode = (val: any): boolean => {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) {\n return false;\n }\n\n const nodeType = getNodeType(val as ContentNode);\n\n if (nodeType === NodeTypes.TRANSLATION) {\n return true;\n }\n\n if (\n nodeType === NodeTypes.MARKDOWN ||\n nodeType === NodeTypes.HTML ||\n nodeType === NodeTypes.INSERTION\n ) {\n return isMultilingualNode((val as any)[nodeType]);\n }\n\n if (\n nodeType === NodeTypes.ENUMERATION ||\n nodeType === NodeTypes.CONDITION ||\n nodeType === NodeTypes.GENDER\n ) {\n const data = (val as any)[nodeType];\n\n if (data && typeof data === 'object') {\n return Object.values(data).some((v) => isMultilingualNode(v));\n }\n }\n\n return false;\n};\n\n/**\n * Recursively builds or updates an AST node for a given dictionary value.\n */\nconst buildNodeForValue = (\n val: any,\n existingNode: any,\n fallbackLocale: string | undefined, // In per-locale mode, this is the locale of the file\n requiredImports: Set<string>\n): any => {\n const unwrappedExisting = unwrap(existingNode);\n\n // --- CRITICAL GUARD: STRICT AST PRESERVATION ---\n // If the existing node is code (JSX, Variables, standard functions), leave it alone.\n // Only allow updates to literals, plain objects, arrays, and Intlayer helpers.\n if (unwrappedExisting) {\n const isUpdatableNode =\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting) ||\n n.NumericLiteral.check(unwrappedExisting) ||\n n.BooleanLiteral.check(unwrappedExisting) ||\n n.TemplateLiteral.check(unwrappedExisting) ||\n n.ObjectExpression.check(unwrappedExisting) ||\n n.ArrayExpression.check(unwrappedExisting) ||\n (n.CallExpression.check(unwrappedExisting) &&\n n.Identifier.check(unwrappedExisting.callee) &&\n [\n 't',\n 'enu',\n 'cond',\n 'gender',\n 'insert',\n 'md',\n 'html',\n 'file',\n 'nest',\n ].includes(unwrappedExisting.callee.name));\n\n if (!isUpdatableNode) {\n return existingNode;\n }\n }\n\n // If we are in per-locale mode (fallbackLocale is set)\n // and the value is not already a complex translation node,\n // we want to store it as a simple literal, NOT wrapped in t().\n if (fallbackLocale && !existingNode && !isMultilingualNode(val)) {\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n }\n\n if (fallbackLocale && existingNode && !isMultilingualNode(val)) {\n if (\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 't'\n ) {\n const arg = unwrap(existingNode.arguments[0]);\n\n if (n.ObjectExpression.check(arg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(arg, fallbackLocale, val);\n }\n updateObjectLiteral(\n arg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n\n if (!fallbackLocale) {\n requiredImports.add('t');\n }\n\n return existingNode;\n }\n }\n\n if (\n (!val || typeof val !== 'object') &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 'md'\n ) {\n const innerArg = existingNode.arguments[0];\n\n if (\n n.CallExpression.check(innerArg) &&\n n.Identifier.check(innerArg.callee) &&\n innerArg.callee.name === 't'\n ) {\n const tArg = unwrap(innerArg.arguments[0]);\n\n if (n.ObjectExpression.check(tArg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(tArg, fallbackLocale, val);\n }\n updateObjectLiteral(\n tArg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add('md');\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n }\n }\n\n // 1. Primitives\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (unwrappedExisting) {\n // Preserve existing template literals (backticks)\n if (\n n.TemplateLiteral.check(unwrappedExisting) &&\n unwrappedExisting.expressions.length === 0\n ) {\n unwrappedExisting.quasis[0].value.raw = String(val);\n unwrappedExisting.quasis[0].value.cooked = String(val);\n return existingNode;\n }\n // Preserve existing standard literals (keeps quote styling)\n if (\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting)\n ) {\n unwrappedExisting.value = val;\n return existingNode;\n }\n }\n\n // Force multiline strings to use Template Literals\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n\n // 2. Arrays\n if (Array.isArray(val)) {\n if (unwrappedExisting && n.ArrayExpression.check(unwrappedExisting)) {\n const elements = [...unwrappedExisting.elements];\n val.forEach((item, i) => {\n elements[i] = buildNodeForValue(\n item,\n elements[i],\n fallbackLocale,\n requiredImports\n );\n });\n\n if (elements.length > val.length) elements.length = val.length;\n unwrappedExisting.elements = elements as any;\n\n return existingNode;\n } else {\n return b.arrayExpression(\n val.map((item) =>\n buildNodeForValue(item, null, fallbackLocale, requiredImports)\n )\n );\n }\n }\n\n // 3. Intlayer Specialized Nodes\n const nodeType =\n val && typeof val === 'object' && !Array.isArray(val)\n ? getNodeType(val as ContentNode)\n : null;\n\n if (\n nodeType &&\n [\n NodeTypes.TRANSLATION,\n NodeTypes.ENUMERATION,\n NodeTypes.CONDITION,\n NodeTypes.GENDER,\n NodeTypes.INSERTION,\n NodeTypes.MARKDOWN,\n NodeTypes.HTML,\n NodeTypes.FILE,\n NodeTypes.NESTED,\n NodeTypes.ARRAY,\n NodeTypes.OBJECT,\n NodeTypes.REACT_NODE,\n NodeTypes.NUMBER,\n NodeTypes.BOOLEAN,\n NodeTypes.NULL,\n NodeTypes.UNKNOWN,\n ].includes(nodeType as any) &&\n nodeType !== NodeTypes.TEXT\n ) {\n const nodeData = (val as any)[nodeType];\n let calleeName = '';\n\n if (nodeType === NodeTypes.TRANSLATION) calleeName = 't';\n else if (nodeType === NodeTypes.ENUMERATION) calleeName = 'enu';\n else if (nodeType === NodeTypes.CONDITION) calleeName = 'cond';\n else if (nodeType === NodeTypes.GENDER) calleeName = 'gender';\n else if (nodeType === NodeTypes.INSERTION) calleeName = 'insert';\n else if (nodeType === NodeTypes.MARKDOWN) calleeName = 'md';\n else if (nodeType === NodeTypes.HTML) calleeName = 'html';\n else if (nodeType === NodeTypes.FILE) calleeName = 'file';\n else if (nodeType === NodeTypes.NESTED) calleeName = 'nest';\n\n if (calleeName) requiredImports.add(calleeName);\n\n const isMatchingCall =\n existingNode &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === calleeName;\n\n if (['t', 'enu', 'cond', 'gender'].includes(calleeName)) {\n let objArg: any = null;\n\n if (\n isMatchingCall &&\n existingNode.arguments.length > 0 &&\n n.ObjectExpression.check(existingNode.arguments[0])\n ) {\n objArg = existingNode.arguments[0];\n } else {\n objArg = b.objectExpression([]);\n }\n updateObjectLiteral(objArg, nodeData, fallbackLocale, requiredImports);\n\n return isMatchingCall\n ? existingNode\n : b.callExpression(b.identifier(calleeName), [objArg]);\n }\n\n if (['md', 'html', 'insert', 'file'].includes(calleeName)) {\n const argNode = buildNodeForValue(\n nodeData,\n isMatchingCall && existingNode.arguments.length > 0\n ? existingNode.arguments[0]\n : null,\n fallbackLocale,\n requiredImports\n );\n\n if (isMatchingCall) {\n existingNode.arguments[0] = argNode;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(calleeName), [argNode]);\n }\n\n if (calleeName === 'nest') {\n const args = [b.literal(nodeData.dictionaryKey)];\n\n if (nodeData.path) args.push(b.literal(nodeData.path));\n\n if (isMatchingCall) {\n existingNode.arguments = args;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier('nest'), args);\n }\n }\n\n // 4. Plain Object\n const objNode =\n unwrappedExisting && n.ObjectExpression.check(unwrappedExisting)\n ? unwrappedExisting\n : b.objectExpression([]);\n\n updateObjectLiteral(objNode, val, fallbackLocale, requiredImports);\n\n return existingNode && unwrappedExisting === existingNode\n ? objNode\n : existingNode || objNode;\n};\n\n/**\n * Recursively updates the AST object literal properties.\n */\nconst updateObjectLiteral = (\n node: recast.types.namedTypes.ObjectExpression,\n data: Record<string, any>,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp) {\n existingProp.value = buildNodeForValue(\n val,\n existingProp.value,\n fallbackLocale,\n requiredImports\n );\n } else {\n const isValidId = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n const keyNode = isValidId ? b.identifier(key) : b.literal(key);\n const valueNode = buildNodeForValue(\n val,\n null,\n fallbackLocale,\n requiredImports\n );\n node.properties.push(b.property('init', keyNode, valueNode));\n }\n }\n};\n\n/**\n * Modifies the AST's top-level imports to inject dynamically needed helper utilities seamlessly.\n */\nconst addImports = (ast: any, requiredImports: Set<string>, isESM: boolean) => {\n if (requiredImports.size === 0) return;\n\n const existingCoreImports = new Set<string>();\n let coreImportPath: any = null;\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n const source = path.node.source.value;\n\n if (source === 'intlayer') {\n coreImportPath = path;\n path.node.specifiers?.forEach((spec) => {\n if (\n n.ImportSpecifier.check(spec) &&\n typeof spec.imported.name === 'string'\n ) {\n existingCoreImports.add(spec.imported.name);\n }\n });\n }\n\n return false;\n },\n visitVariableDeclaration(path) {\n path.node.declarations.forEach((decl) => {\n if (\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require'\n ) {\n const arg = decl.init.arguments[0];\n\n if (n.Literal.check(arg)) {\n if (arg.value === 'intlayer') {\n if (n.ObjectPattern.check(decl.id)) {\n decl.id.properties.forEach((prop) => {\n if (\n n.Property.check(prop) &&\n (n.Identifier.check(prop.key) ||\n n.Identifier.check(prop.value))\n ) {\n const name = n.Identifier.check(prop.key)\n ? prop.key.name\n : (prop.value as any).name;\n existingCoreImports.add(name);\n }\n });\n } else if (n.Identifier.check(decl.id)) {\n // Handle const intlayer = require('intlayer')\n existingCoreImports.add(decl.id.name);\n }\n }\n }\n }\n });\n\n return false;\n },\n });\n\n const missingCore = Array.from(requiredImports).filter(\n (imp) => !existingCoreImports.has(imp)\n );\n\n if (missingCore.length === 0) return;\n\n if (isESM) {\n if (coreImportPath) {\n missingCore.forEach((imp) => {\n coreImportPath.node.specifiers.push(\n b.importSpecifier(b.identifier(imp))\n );\n });\n coreImportPath.node.specifiers.sort((a: any, b: any) =>\n a.imported.name.localeCompare(b.imported.name)\n );\n } else {\n const specifiers = missingCore\n .sort()\n .map((imp) => b.importSpecifier(b.identifier(imp)));\n const newImport = b.importDeclaration(specifiers, b.literal('intlayer'));\n ast.program.body.unshift(newImport);\n }\n } else {\n let insertIndex = 0;\n\n if (\n ast.program.body.length > 0 &&\n n.ExpressionStatement.check(ast.program.body[0]) &&\n n.Literal.check(ast.program.body[0].expression)\n ) {\n insertIndex = 1; // Insert after 'use strict'\n }\n const cjsLines: any[] = [];\n\n const properties = missingCore.sort().map((imp) => {\n const prop = b.property('init', b.identifier(imp), b.identifier(imp));\n prop.shorthand = true;\n\n return prop;\n });\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern(properties),\n b.callExpression(b.identifier('require'), [b.literal('intlayer')])\n ),\n ])\n );\n\n ast.program.body.splice(insertIndex, 0, ...cjsLines);\n }\n};\n\n/**\n * Updates a JS/TS file seamlessly to map new localization keys, arrays, complex nodes and nested dictionaries gracefully using AST updates via Recast parser.\n */\nexport const transformJSFile = async (\n fileContent: string,\n dictionary: Dictionary,\n fallbackLocale?: Locale,\n noMetadata?: boolean\n): Promise<string> => {\n if (!dictionary || typeof dictionary !== 'object') return fileContent;\n\n let ast: any;\n try {\n ast = recast.parse(fileContent, {\n parser: babelTsParser,\n });\n } catch (error) {\n console.error({ error });\n return fileContent;\n }\n\n let rootObject: any = null;\n let isESM = false;\n\n recast.visit(ast, {\n visitExportDefaultDeclaration() {\n isESM = true;\n\n return false;\n },\n visitImportDeclaration() {\n isESM = true;\n\n return false;\n },\n });\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n const unwrappedDecl = unwrap(decl);\n\n if (n.ObjectExpression.check(unwrappedDecl)) {\n rootObject = unwrappedDecl;\n } else if (n.Identifier.check(unwrappedDecl)) {\n const varName = unwrappedDecl.name;\n recast.visit(ast, {\n visitVariableDeclarator(vp) {\n const unwrappedInit = unwrap(vp.node.init);\n\n if (\n n.Identifier.check(vp.node.id) &&\n vp.node.id.name === varName &&\n n.ObjectExpression.check(unwrappedInit)\n ) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n return false;\n },\n visitAssignmentExpression(path) {\n const left = path.node.left;\n\n if (n.MemberExpression.check(left)) {\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'module' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'exports'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'exports' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'default'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n }\n this.traverse(path);\n },\n });\n\n if (!rootObject) {\n recast.visit(ast, {\n visitVariableDeclarator(path) {\n const unwrappedInit = unwrap(path.node.init);\n\n if (!rootObject && n.ObjectExpression.check(unwrappedInit)) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n if (!rootObject) return fileContent;\n\n const requiredImports = new Set<string>();\n const effectiveFallbackLocale = (fallbackLocale as string) ?? 'en';\n\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n ];\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n rootObject.properties = rootObject.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n\n // Update satisfies type if exists\n recast.visit(ast, {\n visitNode(path) {\n const node = path.node;\n if (\n (n.TSSatisfiesExpression?.check(node) ||\n node.type === 'TSSatisfiesExpression') &&\n (node as any).typeAnnotation &&\n n.TSTypeReference.check((node as any).typeAnnotation) &&\n n.Identifier.check((node as any).typeAnnotation.typeName) &&\n (node as any).typeAnnotation.typeName.name === 'Dictionary'\n ) {\n (node as any).typeAnnotation = b.tsIndexedAccessType(\n b.tsTypeReference(b.identifier('Dictionary')),\n b.tsLiteralType(b.stringLiteral('content'))\n );\n }\n this.traverse(path);\n },\n });\n } else {\n for (const prop of metadataProperties) {\n if ((dictionary as any)[prop] !== undefined) {\n updateObjectLiteral(\n rootObject,\n { [prop]: (dictionary as any)[prop] },\n undefined,\n requiredImports\n );\n }\n }\n }\n\n if (dictionary.content !== undefined) {\n updateObjectLiteral(\n rootObject,\n noMetadata\n ? (dictionary.content as Record<string, any>)\n : { content: dictionary.content },\n effectiveFallbackLocale,\n requiredImports\n );\n }\n\n addImports(ast, requiredImports, isESM);\n\n return recast.print(ast).code;\n};\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,IAAI,OAAO,MAAM;AACvB,MAAM,IAAI,OAAO,MAAM;;;;;AAMvB,MAAM,UAAU,SAAc;AAC5B,QACE,SACC,EAAE,uBAAuB,MAAM,KAAK,IACnC,EAAE,gBAAgB,MAAM,KAAK,IAC7B,EAAE,iBAAiB,MAAM,KAAK,IAC9B,EAAE,qBAAqB,MAAM,KAAK,IAClC;EACE;EACA;EACA;EACA;EACD,CAAC,SAAS,KAAK,KAAK,EAEvB,QAAO,KAAK;AAEd,QAAO;;;;;;AAOT,MAAM,uBAAuB,MAAW,QAAgB;AACtD,QAAO,KAAK,WAAW,MAAM,SAAc;AACzC,MAAI,EAAE,SAAS,MAAM,KAAK,IAAI,EAAE,eAAe,MAAM,KAAK,EAAE;AAC1D,OAAI,EAAE,WAAW,MAAM,KAAK,IAAI,IAAI,KAAK,IAAI,SAAS,IAAK,QAAO;AAElE,OAAI,EAAE,cAA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SAAS,MAAM,KAAK,IAAI,EAAE,eAAe,MAAM,KAAK,EAAE;IAC1D,IAAI,WAAW;AACf,QAAI,EAAE,WAAW,MAAM,KAAK,IAAI,CAAE,YAAW,KAAK,IAAI;aAC7C,EAAE,cAAc,MAAM,KAAK,IAAI,CAAE,YAAW,KAAK,IAAI;aACrD,EAAE,QAAQ,MAAM,KAAK,IAAI,CAAE,YAAW,OAAO,KAAK,IAAI,MAAM;AAErE,WAAO,CAAC;KAAC;KAAO;KAAW,GAAG;KAAmB,CAAC,SAAS,SAAS;;AAEtE,UAAO;IACP;AAGF,SAAO,MAAM,KAAK,EAChB,UAAU,MAAM;GACd,MAAM,OAAO,KAAK;AAClB,QACG,EAAE,uBAAuB,MAAM,KAAK,IACnC,KAAK,SAAS,4BACf,KAAa,kBACd,EAAE,gBAAgB,MAAO,KAAa,eAAe,IACrD,EAAE,WAAW,MAAO,KAAa,eAAe,SAAS,IACxD,KAAa,eAAe,SAAS,SAAS,aAE/C,CAAC,KAAa,iBAAiB,EAAE,oBAC/B,EAAE,gBAAgB,EAAE,WAAW,aAAa,CAAC,EAC7C,EAAE,cAAc,EAAE,cAAc,UAAU,CAAC,CAC5C;AAEH,QAAK,SAAS,KAAK;KAEtB,CAAC;OAEF,MAAK,MAAM,QAAQ,mBACjB,KAAK,WAAmB,UAAU,OAChC,qBACE,YACA,GAAG,OAAQ,WAAmB,OAAO,EACrC,QACA,gBACD;AAKP,KAAI,WAAW,YAAY,OACzB,qBACE,YACA,aACK,WAAW,UACZ,EAAE,SAAS,WAAW,SAAS,EACnC,yBACA,gBACD;AAGH,YAAW,KAAK,iBAAiB,MAAM;AAEvC,QAAO,OAAO,MAAM,IAAI,CAAC"}
|
|
1
|
+
{"version":3,"file":"transformJSFile.cjs","names":["NodeTypes","babelTsParser"],"sources":["../../../src/writeContentDeclaration/transformJSFile.ts"],"sourcesContent":["import { getNodeType } from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport * as recast from 'recast';\nimport * as babelTsParser from 'recast/parsers/babel-ts.js';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Unwraps TypeScript/Babel expression wrappers (satisfies, as, !, <Type>).\n * Uses string fallbacks to bypass outdated ast-types definitions.\n */\nconst unwrap = (node: any) => {\n while (\n node &&\n (n.TSSatisfiesExpression?.check(node) ||\n n.TSAsExpression?.check(node) ||\n n.TSTypeAssertion?.check(node) ||\n n.TSNonNullExpression?.check(node) ||\n [\n 'TSSatisfiesExpression',\n 'TSAsExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n ].includes(node.type))\n ) {\n node = node.expression;\n }\n return node;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n\n return false;\n });\n};\n\n/**\n * Synchronizes numeric suffixes across locales.\n * E.g. \"Hello 1\" -> \"Hello 3\" updates \"Bonjour 1\" to \"Bonjour 3\".\n */\nconst syncNumericSuffixAcrossLocales = (\n existingNode: any,\n fallbackLocaleCode: string,\n newFallbackValue: string\n) => {\n const trailingNumberMatch = newFallbackValue.match(/\\d+(?!.*\\d)/);\n if (!trailingNumberMatch) return;\n const newTrailingNumber = trailingNumberMatch[0];\n\n if (n.ObjectExpression.check(existingNode)) {\n for (const prop of existingNode.properties) {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (\n n.Literal.check(prop.key) &&\n typeof prop.key.value === 'string'\n )\n propName = prop.key.value;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n\n if (propName && propName !== fallbackLocaleCode) {\n if (\n n.Literal.check(prop.value) &&\n typeof prop.value.value === 'string'\n ) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.literal(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n } else if (n.StringLiteral.check(prop.value)) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.stringLiteral(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n }\n }\n }\n }\n }\n};\n\n/**\n * Checks if a value represents a multilingual Intlayer node.\n * A node is multilingual if it is a Translation node, or if it is a specialized node\n * (Markdown, HTML, etc.) that contains a Translation node.\n */\nconst isMultilingualNode = (val: any): boolean => {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) {\n return false;\n }\n\n const nodeType = getNodeType(val as ContentNode);\n\n if (nodeType === NodeTypes.TRANSLATION) {\n return true;\n }\n\n if (\n nodeType === NodeTypes.MARKDOWN ||\n nodeType === NodeTypes.HTML ||\n nodeType === NodeTypes.INSERTION\n ) {\n return isMultilingualNode((val as any)[nodeType]);\n }\n\n if (\n nodeType === NodeTypes.ENUMERATION ||\n nodeType === NodeTypes.CONDITION ||\n nodeType === NodeTypes.GENDER\n ) {\n const data = (val as any)[nodeType];\n\n if (data && typeof data === 'object') {\n return Object.values(data).some((v) => isMultilingualNode(v));\n }\n }\n\n return false;\n};\n\n/**\n * Recursively builds or updates an AST node for a given dictionary value.\n */\nconst buildNodeForValue = (\n val: any,\n existingNode: any,\n fallbackLocale: string | undefined, // In per-locale mode, this is the locale of the file\n requiredImports: Set<string>\n): any => {\n const unwrappedExisting = unwrap(existingNode);\n\n // --- CRITICAL GUARD: STRICT AST PRESERVATION ---\n // If the existing node is code (JSX, Variables, standard functions), leave it alone.\n // Only allow updates to literals, plain objects, arrays, and Intlayer helpers.\n if (unwrappedExisting) {\n const isUpdatableNode =\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting) ||\n n.NumericLiteral.check(unwrappedExisting) ||\n n.BooleanLiteral.check(unwrappedExisting) ||\n n.TemplateLiteral.check(unwrappedExisting) ||\n n.ObjectExpression.check(unwrappedExisting) ||\n n.ArrayExpression.check(unwrappedExisting) ||\n (n.CallExpression.check(unwrappedExisting) &&\n n.Identifier.check(unwrappedExisting.callee) &&\n [\n 't',\n 'enu',\n 'cond',\n 'gender',\n 'insert',\n 'md',\n 'html',\n 'file',\n 'nest',\n ].includes(unwrappedExisting.callee.name));\n\n if (!isUpdatableNode) {\n return existingNode;\n }\n }\n\n // If we are in per-locale mode (fallbackLocale is set)\n // and the value is not already a complex translation node,\n // we want to store it as a simple literal, NOT wrapped in t().\n if (fallbackLocale && !existingNode && !isMultilingualNode(val)) {\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n }\n\n if (fallbackLocale && existingNode && !isMultilingualNode(val)) {\n if (\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 't'\n ) {\n const arg = unwrap(existingNode.arguments[0]);\n\n if (n.ObjectExpression.check(arg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(arg, fallbackLocale, val);\n }\n updateObjectLiteral(\n arg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n\n if (!fallbackLocale) {\n requiredImports.add('t');\n }\n\n return existingNode;\n }\n }\n\n if (\n (!val || typeof val !== 'object') &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 'md'\n ) {\n const innerArg = existingNode.arguments[0];\n\n if (\n n.CallExpression.check(innerArg) &&\n n.Identifier.check(innerArg.callee) &&\n innerArg.callee.name === 't'\n ) {\n const tArg = unwrap(innerArg.arguments[0]);\n\n if (n.ObjectExpression.check(tArg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(tArg, fallbackLocale, val);\n }\n updateObjectLiteral(\n tArg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add('md');\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n }\n }\n\n // 1. Primitives\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (unwrappedExisting) {\n // Preserve existing template literals (backticks)\n if (\n n.TemplateLiteral.check(unwrappedExisting) &&\n unwrappedExisting.expressions.length === 0\n ) {\n unwrappedExisting.quasis[0].value.raw = String(val);\n unwrappedExisting.quasis[0].value.cooked = String(val);\n return existingNode;\n }\n // Preserve existing standard literals (keeps quote styling)\n if (\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting)\n ) {\n unwrappedExisting.value = val;\n return existingNode;\n }\n }\n\n // Force multiline strings to use Template Literals\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n\n // 2. Arrays\n if (Array.isArray(val)) {\n if (unwrappedExisting && n.ArrayExpression.check(unwrappedExisting)) {\n const elements = [...unwrappedExisting.elements];\n val.forEach((item, i) => {\n elements[i] = buildNodeForValue(\n item,\n elements[i],\n fallbackLocale,\n requiredImports\n );\n });\n\n if (elements.length > val.length) elements.length = val.length;\n unwrappedExisting.elements = elements as any;\n\n return existingNode;\n } else {\n return b.arrayExpression(\n val.map((item) =>\n buildNodeForValue(item, null, fallbackLocale, requiredImports)\n )\n );\n }\n }\n\n // 3. Intlayer Specialized Nodes\n const nodeType =\n val && typeof val === 'object' && !Array.isArray(val)\n ? getNodeType(val as ContentNode)\n : null;\n\n if (\n nodeType &&\n [\n NodeTypes.TRANSLATION,\n NodeTypes.ENUMERATION,\n NodeTypes.CONDITION,\n NodeTypes.GENDER,\n NodeTypes.INSERTION,\n NodeTypes.MARKDOWN,\n NodeTypes.HTML,\n NodeTypes.FILE,\n NodeTypes.NESTED,\n NodeTypes.ARRAY,\n NodeTypes.OBJECT,\n NodeTypes.REACT_NODE,\n NodeTypes.NUMBER,\n NodeTypes.BOOLEAN,\n NodeTypes.NULL,\n NodeTypes.UNKNOWN,\n ].includes(nodeType as any) &&\n nodeType !== NodeTypes.TEXT\n ) {\n const nodeData = (val as any)[nodeType];\n let calleeName = '';\n\n if (nodeType === NodeTypes.TRANSLATION) calleeName = 't';\n else if (nodeType === NodeTypes.ENUMERATION) calleeName = 'enu';\n else if (nodeType === NodeTypes.CONDITION) calleeName = 'cond';\n else if (nodeType === NodeTypes.GENDER) calleeName = 'gender';\n else if (nodeType === NodeTypes.INSERTION) calleeName = 'insert';\n else if (nodeType === NodeTypes.MARKDOWN) calleeName = 'md';\n else if (nodeType === NodeTypes.HTML) calleeName = 'html';\n else if (nodeType === NodeTypes.FILE) calleeName = 'file';\n else if (nodeType === NodeTypes.NESTED) calleeName = 'nest';\n\n if (calleeName) requiredImports.add(calleeName);\n\n const isMatchingCall =\n existingNode &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === calleeName;\n\n if (['t', 'enu', 'cond', 'gender'].includes(calleeName)) {\n let objArg: any = null;\n\n if (\n isMatchingCall &&\n existingNode.arguments.length > 0 &&\n n.ObjectExpression.check(existingNode.arguments[0])\n ) {\n objArg = existingNode.arguments[0];\n } else {\n objArg = b.objectExpression([]);\n }\n updateObjectLiteral(objArg, nodeData, fallbackLocale, requiredImports);\n\n return isMatchingCall\n ? existingNode\n : b.callExpression(b.identifier(calleeName), [objArg]);\n }\n\n if (['md', 'html', 'insert', 'file'].includes(calleeName)) {\n const argNode = buildNodeForValue(\n nodeData,\n isMatchingCall && existingNode.arguments.length > 0\n ? existingNode.arguments[0]\n : null,\n fallbackLocale,\n requiredImports\n );\n\n if (isMatchingCall) {\n existingNode.arguments[0] = argNode;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(calleeName), [argNode]);\n }\n\n if (calleeName === 'nest') {\n const args = [b.literal(nodeData.dictionaryKey)];\n\n if (nodeData.path) args.push(b.literal(nodeData.path));\n\n if (isMatchingCall) {\n existingNode.arguments = args;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier('nest'), args);\n }\n }\n\n // 4. Plain Object\n const objNode =\n unwrappedExisting && n.ObjectExpression.check(unwrappedExisting)\n ? unwrappedExisting\n : b.objectExpression([]);\n\n updateObjectLiteral(objNode, val, fallbackLocale, requiredImports);\n\n return existingNode && unwrappedExisting === existingNode\n ? objNode\n : existingNode || objNode;\n};\n\n/**\n * Recursively updates the AST object literal properties.\n */\nconst updateObjectLiteral = (\n node: recast.types.namedTypes.ObjectExpression,\n data: Record<string, any>,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp) {\n existingProp.value = buildNodeForValue(\n val,\n existingProp.value,\n fallbackLocale,\n requiredImports\n );\n } else {\n const isValidId = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n const keyNode = isValidId ? b.identifier(key) : b.literal(key);\n const valueNode = buildNodeForValue(\n val,\n null,\n fallbackLocale,\n requiredImports\n );\n node.properties.push(b.property('init', keyNode, valueNode));\n }\n }\n};\n\n/**\n * Modifies the AST's top-level imports to inject dynamically needed helper utilities seamlessly.\n */\nconst addImports = (ast: any, requiredImports: Set<string>, isESM: boolean) => {\n if (requiredImports.size === 0) return;\n\n const existingCoreImports = new Set<string>();\n let coreImportPath: any = null;\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n const source = path.node.source.value;\n\n if (source === 'intlayer') {\n coreImportPath = path;\n path.node.specifiers?.forEach((spec) => {\n if (\n n.ImportSpecifier.check(spec) &&\n typeof spec.imported.name === 'string'\n ) {\n existingCoreImports.add(spec.imported.name);\n }\n });\n }\n\n return false;\n },\n visitVariableDeclaration(path) {\n path.node.declarations.forEach((decl) => {\n if (\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require'\n ) {\n const arg = decl.init.arguments[0];\n\n if (n.Literal.check(arg)) {\n if (arg.value === 'intlayer') {\n if (n.ObjectPattern.check(decl.id)) {\n decl.id.properties.forEach((prop) => {\n if (\n n.Property.check(prop) &&\n (n.Identifier.check(prop.key) ||\n n.Identifier.check(prop.value))\n ) {\n const name = n.Identifier.check(prop.key)\n ? prop.key.name\n : (prop.value as any).name;\n existingCoreImports.add(name);\n }\n });\n } else if (n.Identifier.check(decl.id)) {\n // Handle const intlayer = require('intlayer')\n existingCoreImports.add(decl.id.name);\n }\n }\n }\n }\n });\n\n return false;\n },\n });\n\n const missingCore = Array.from(requiredImports).filter(\n (imp) => !existingCoreImports.has(imp)\n );\n\n if (missingCore.length === 0) return;\n\n if (isESM) {\n if (coreImportPath) {\n missingCore.forEach((imp) => {\n coreImportPath.node.specifiers.push(\n b.importSpecifier(b.identifier(imp))\n );\n });\n coreImportPath.node.specifiers.sort((a: any, b: any) =>\n a.imported.name.localeCompare(b.imported.name)\n );\n } else {\n const specifiers = missingCore\n .sort()\n .map((imp) => b.importSpecifier(b.identifier(imp)));\n const newImport = b.importDeclaration(specifiers, b.literal('intlayer'));\n ast.program.body.unshift(newImport);\n }\n } else {\n let insertIndex = 0;\n\n if (\n ast.program.body.length > 0 &&\n n.ExpressionStatement.check(ast.program.body[0]) &&\n n.Literal.check(ast.program.body[0].expression)\n ) {\n insertIndex = 1; // Insert after 'use strict'\n }\n const cjsLines: any[] = [];\n\n const properties = missingCore.sort().map((imp) => {\n const prop = b.property('init', b.identifier(imp), b.identifier(imp));\n prop.shorthand = true;\n\n return prop;\n });\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern(properties),\n b.callExpression(b.identifier('require'), [b.literal('intlayer')])\n ),\n ])\n );\n\n ast.program.body.splice(insertIndex, 0, ...cjsLines);\n }\n};\n\n/**\n * Updates a JS/TS file seamlessly to map new localization keys, arrays, complex nodes and nested dictionaries gracefully using AST updates via Recast parser.\n */\nexport const transformJSFile = async (\n fileContent: string,\n dictionary: Dictionary,\n fallbackLocale?: Locale,\n noMetadata?: boolean\n): Promise<string> => {\n if (!dictionary || typeof dictionary !== 'object') return fileContent;\n\n let ast: any;\n try {\n ast = recast.parse(fileContent, {\n parser: babelTsParser,\n });\n } catch (error) {\n console.error({ error });\n return fileContent;\n }\n\n let rootObject: any = null;\n let isESM = false;\n\n recast.visit(ast, {\n visitExportDefaultDeclaration() {\n isESM = true;\n\n return false;\n },\n visitImportDeclaration() {\n isESM = true;\n\n return false;\n },\n });\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n const unwrappedDecl = unwrap(decl);\n\n if (n.ObjectExpression.check(unwrappedDecl)) {\n rootObject = unwrappedDecl;\n } else if (n.Identifier.check(unwrappedDecl)) {\n const varName = unwrappedDecl.name;\n recast.visit(ast, {\n visitVariableDeclarator(vp) {\n const unwrappedInit = unwrap(vp.node.init);\n\n if (\n n.Identifier.check(vp.node.id) &&\n vp.node.id.name === varName &&\n n.ObjectExpression.check(unwrappedInit)\n ) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n return false;\n },\n visitAssignmentExpression(path) {\n const left = path.node.left;\n\n if (n.MemberExpression.check(left)) {\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'module' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'exports'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'exports' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'default'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n }\n this.traverse(path);\n },\n });\n\n if (!rootObject) {\n recast.visit(ast, {\n visitVariableDeclarator(path) {\n const unwrappedInit = unwrap(path.node.init);\n\n if (!rootObject && n.ObjectExpression.check(unwrappedInit)) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n if (!rootObject) return fileContent;\n\n const requiredImports = new Set<string>();\n const effectiveFallbackLocale = (fallbackLocale as string) ?? 'en';\n\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n ];\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n rootObject.properties = rootObject.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n\n // Update satisfies type if exists\n recast.visit(ast, {\n visitNode(path) {\n const node = path.node;\n if (\n (n.TSSatisfiesExpression?.check(node) ||\n node.type === 'TSSatisfiesExpression') &&\n (node as any).typeAnnotation &&\n n.TSTypeReference.check((node as any).typeAnnotation) &&\n n.Identifier.check((node as any).typeAnnotation.typeName) &&\n (node as any).typeAnnotation.typeName.name === 'Dictionary'\n ) {\n (node as any).typeAnnotation = b.tsIndexedAccessType(\n b.tsTypeReference(b.identifier('Dictionary')),\n b.tsLiteralType(b.stringLiteral('content'))\n );\n }\n this.traverse(path);\n },\n });\n } else {\n for (const prop of metadataProperties) {\n if ((dictionary as any)[prop] !== undefined) {\n updateObjectLiteral(\n rootObject,\n { [prop]: (dictionary as any)[prop] },\n undefined,\n requiredImports\n );\n }\n }\n }\n\n if (dictionary.content !== undefined) {\n updateObjectLiteral(\n rootObject,\n noMetadata\n ? (dictionary.content as Record<string, any>)\n : { content: dictionary.content },\n effectiveFallbackLocale,\n requiredImports\n );\n }\n\n addImports(ast, requiredImports, isESM);\n\n return recast.print(ast).code;\n};\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,IAAI,OAAO,MAAM;AACvB,MAAM,IAAI,OAAO,MAAM;;;;;AAMvB,MAAM,UAAU,SAAc;AAC5B,QACE,SACC,EAAE,uBAAuB,MAAM,KAAK,IACnC,EAAE,gBAAgB,MAAM,KAAK,IAC7B,EAAE,iBAAiB,MAAM,KAAK,IAC9B,EAAE,qBAAqB,MAAM,KAAK,IAClC;EACE;EACA;EACA;EACA;EACD,CAAC,SAAS,KAAK,KAAK,EAEvB,QAAO,KAAK;AAEd,QAAO;;;;;;AAOT,MAAM,uBAAuB,MAAW,QAAgB;AACtD,QAAO,KAAK,WAAW,MAAM,SAAc;AACzC,MAAI,EAAE,SAAS,MAAM,KAAK,IAAI,EAAE,eAAe,MAAM,KAAK,EAAE;AAC1D,OAAI,EAAE,WAAW,MAAM,KAAK,IAAI,IAAI,KAAK,IAAI,SAAS,IAAK,QAAO;AAElE,OAAI,EAAE,cAAc,MAAM,KAAK,IAAI,IAAI,KAAK,IAAI,UAAU,IACxD,QAAO;AAET,OAAI,EAAE,QAAQ,MAAM,KAAK,IAAI,IAAI,KAAK,IAAI,UAAU,IAAK,QAAO;;AAGlE,SAAO;GACP;;;;;;AAOJ,MAAM,kCACJ,cACA,oBACA,qBACG;CACH,MAAM,sBAAsB,iBAAiB,MAAM,cAAc;AACjE,KAAI,CAAC,oBAAqB;CAC1B,MAAM,oBAAoB,oBAAoB;AAE9C,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KAAW,GAAG;KAAmB,CAAC,SAAS,SAAS;;AAEtE,UAAO;IACP;AAGF,SAAO,MAAM,KAAK,EAChB,UAAU,MAAM;GACd,MAAM,OAAO,KAAK;AAClB,QACG,EAAE,uBAAuB,MAAM,KAAK,IACnC,KAAK,SAAS,4BACf,KAAa,kBACd,EAAE,gBAAgB,MAAO,KAAa,eAAe,IACrD,EAAE,WAAW,MAAO,KAAa,eAAe,SAAS,IACxD,KAAa,eAAe,SAAS,SAAS,aAE/C,CAAC,KAAa,iBAAiB,EAAE,oBAC/B,EAAE,gBAAgB,EAAE,WAAW,aAAa,CAAC,EAC7C,EAAE,cAAc,EAAE,cAAc,UAAU,CAAC,CAC5C;AAEH,QAAK,SAAS,KAAK;KAEtB,CAAC;OAEF,MAAK,MAAM,QAAQ,mBACjB,KAAK,WAAmB,UAAU,OAChC,qBACE,YACA,GAAG,OAAQ,WAAmB,OAAO,EACrC,QACA,gBACD;AAKP,KAAI,WAAW,YAAY,OACzB,qBACE,YACA,aACK,WAAW,UACZ,EAAE,SAAS,WAAW,SAAS,EACnC,yBACA,gBACD;AAGH,YAAW,KAAK,iBAAiB,MAAM;AAEvC,QAAO,OAAO,MAAM,IAAI,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","COMPILER_NO_METADATA","readDictionariesFromDisk","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { readDictionariesFromDisk } from '../utils/readDictionariesFromDisk';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAM,2BAA2B,OAC/B,YACA,eACA,eACG;;;;CAIH,MAAM,sBACJ,MAAMA,kGAAiC,WAAW;CAEpD,IAAI,UAAU,oBAAoB;;;;AAMlC,KAAI,WAAW,OACb,8DACE,qBACA,WAAW,OACZ,CAAC;UACO,WACT,oEACE,qBACA,WACD,CAAC;CAGJ,IAAI,qBAA0B;EAC5B,GAAG;EACH;EACD;;;;AAMD,YAAW,MAAM,UAAU,cAAc,WAAW,EAAE,CACpD,KAAI,OAAO,cAAc;EACvB,MAAM,kBAAkB,MAAM,OAAO,eAAe;GAClD,YAAY;GACZ;GACD,CAAC;AAEF,MAAI,gBACF,sBAAqB;;AAQ3B,KAAI,EAFF,mBAAmB,WAAW,mBAAmB,KAE1B,QAAO;CAEhC,IAAI,SAAqB;EACvB,KAAK,WAAW;EAChB,IAAI,WAAW;EACf,OAAO,WAAW;EAClB,aAAa,WAAW;EACxB,MAAM,WAAW;EACjB,QAAQ,WAAW;EACnB,MAAM,WAAW;EACjB,QAAQ,WAAW;EACnB,UAAU,WAAW;EACrB,YAAY,WAAW;EACvB,SAAS,WAAW;EACpB;EACD;AAUD,KAFeC,4DAFb,WAAW,kCAAmB,WAAW,SAAS,GAAG,QAEP,KAGnC,UACX,mBAAmB,WACnB,mBAAmB,IAEnB,UAAS;EACP,SAAS;EACT,GAAG;EACJ;AAGH,QAAO;;AAST,MAAM,iBAAiB,EACrB,qBAAqB,yBACtB;AAED,MAAa,0BAA0B,OACrC,YACA,eACA,YACwD;CACxD,MAAM,EAAE,QAAQ,aAAa;CAC7B,MAAM,EAAE,YAAY;CAEpB,MAAM,aAAa,UAAU,cAAcC;CAC3C,MAAM,EAAE,qBAAqB,eAAe;EAC1C,GAAG;EACH,GA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AAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC;EACxG,MAAM,WAAW,8BACR,SAAS,aAAa,GAC3B,GAAG,iBAAiB,GAAG;AAC3B,MAAI;AACF,yCAAgB,UAAU,oBAAoB,QAAQ;AACtD,sCAAa,UAAU,iBAAiB;WACjC,OAAO;AACd,OAAI;AACF,mCAAS,UAAU,EAAE,OAAO,MAAM,CAAC;WAC7B;AAGR,SAAM;;EAGR,MAAM,gBAAgBC,gDAAoB,cAAc;AAExD,MAAI,cACF,KAAI;AACF,oCAAS,cAAc,QAAQ,YAAY,iBAAiB,EAAE;IAC5D,OAAO;IACP,KAAK,cAAc,OAAO;IAC3B,CAAC;WACK,OAAO;AACd,WAAQ,MAAM,MAAM;;AAIxB;;AAGF,OAAMC,wDAAY,kBAAkB,YAAY,eAAe,WAAW;AAI1E,KAAI;AAKF,qDAHE,cAAc,OAAO,UACrB,yBACD,EACsB,EAAE,WAAW,MAAM,CAAC;SACrC"}
|
|
1
|
+
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","COMPILER_NO_METADATA","readDictionariesFromDisk","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { readDictionariesFromDisk } from '../utils/readDictionariesFromDisk';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MA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a,UAAU,iBAAiB;WACjC,OAAO;AACd,OAAI;AACF,mCAAS,UAAU,EAAE,OAAO,MAAM,CAAC;WAC7B;AAGR,SAAM;;EAGR,MAAM,gBAAgBC,gDAAoB,cAAc;AAExD,MAAI,cACF,KAAI;AACF,oCAAS,cAAc,QAAQ,YAAY,iBAAiB,EAAE;IAC5D,OAAO;IACP,KAAK,cAAc,OAAO;IAC3B,CAAC;WACK,OAAO;AACd,WAAQ,MAAM,MAAM;;AAIxB;;AAGF,OAAMC,wDAAY,kBAAkB,YAAY,eAAe,WAAW;AAI1E,KAAI;AAKF,qDAHE,cAAc,OAAO,UACrB,yBAEmB,EAAE,EAAE,WAAW,MAAM,CAAC;SACrC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeJSFile.cjs","names":["getFormatFromExtension","getContentDeclarationFileTemplate","transformJSFile","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n const mergedDictionary = {\n ...configuration.dictionary,\n ...dictionary,\n };\n\n const appLogger = getAppLogger(configuration);\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath) as Extension;\n\n const format = getFormatFromExtension(fileExtension);\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n // Filter out undefined values\n Object.fromEntries(\n Object.entries({\n id: noMetadata ? undefined : mergedDictionary.id,\n locale: noMetadata ? undefined : mergedDictionary.locale,\n filled: noMetadata ? undefined : mergedDictionary.filled,\n fill: noMetadata ? undefined : mergedDictionary.fill,\n description: noMetadata ? undefined : mergedDictionary.description,\n title: noMetadata ? undefined : mergedDictionary.title,\n tags: noMetadata ? undefined : mergedDictionary.tags,\n version: noMetadata ? undefined : mergedDictionary.version,\n priority: noMetadata ? undefined : mergedDictionary.priority,\n importMode: noMetadata ? undefined : mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n ),\n noMetadata\n );\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, template, 'utf-8');\n await rename(tempPath, filePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n }\n\n let fileContent = await readFile(filePath, 'utf-8');\n\n if (fileContent === '') {\n const format = getFormatFromExtension(extname(filePath) as Extension);\n\n fileContent = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n {},\n noMetadata\n );\n }\n\n const finalCode = await transformJSFile(\n fileContent,\n dictionary,\n dictionary.locale as any,\n noMetadata\n );\n\n // Write the modified code back to the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, finalCode, 'utf-8');\n await rename(tempPath, filePath);\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc,OACzB,UACA,YACA,eACA,eACkB;CAClB,MAAM,mBAAmB;EACvB,GAAG,cAAc;EACjB,GAAG;EACJ;CAED,MAAM,sDAAyB,cAAc;AAG7C,KAAI,yBAAY,SAAS,EAAE;EAGzB,MAAM,SAASA,mFAFe,
|
|
1
|
+
{"version":3,"file":"writeJSFile.cjs","names":["getFormatFromExtension","getContentDeclarationFileTemplate","transformJSFile","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n const mergedDictionary = {\n ...configuration.dictionary,\n ...dictionary,\n };\n\n const appLogger = getAppLogger(configuration);\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath) as Extension;\n\n const format = getFormatFromExtension(fileExtension);\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n // Filter out undefined values\n Object.fromEntries(\n Object.entries({\n id: noMetadata ? undefined : mergedDictionary.id,\n locale: noMetadata ? undefined : mergedDictionary.locale,\n filled: noMetadata ? undefined : mergedDictionary.filled,\n fill: noMetadata ? undefined : mergedDictionary.fill,\n description: noMetadata ? undefined : mergedDictionary.description,\n title: noMetadata ? undefined : mergedDictionary.title,\n tags: noMetadata ? undefined : mergedDictionary.tags,\n version: noMetadata ? undefined : mergedDictionary.version,\n priority: noMetadata ? undefined : mergedDictionary.priority,\n importMode: noMetadata ? undefined : mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n ),\n noMetadata\n );\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, template, 'utf-8');\n await rename(tempPath, filePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n }\n\n let fileContent = await readFile(filePath, 'utf-8');\n\n if (fileContent === '') {\n const format = getFormatFromExtension(extname(filePath) as Extension);\n\n fileContent = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n {},\n noMetadata\n );\n }\n\n const finalCode = await transformJSFile(\n fileContent,\n dictionary,\n dictionary.locale as any,\n noMetadata\n );\n\n // Write the modified code back to the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, finalCode, 'utf-8');\n await rename(tempPath, filePath);\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc,OACzB,UACA,YACA,eACA,eACkB;CAClB,MAAM,mBAAmB;EACvB,GAAG,cAAc;EACjB,GAAG;EACJ;CAED,MAAM,sDAAyB,cAAc;AAG7C,KAAI,yBAAY,SAAS,EAAE;EAGzB,MAAM,SAASA,mFAFe,SAEqB,CAAC;AAEpD,YAAU,oCAAoC,EAC5C,WAAW,MACZ,CAAC;EACF,MAAM,WAAW,MAAMC,8GACrB,iBAAiB,KACjB,QAEA,OAAO,YACL,OAAO,QAAQ;GACb,IAAI,aAAa,SAAY,iBAAiB;GAC9C,QAAQ,aAAa,SAAY,iBAAiB;GAClD,QAAQ,aAAa,SAAY,iBAAiB;GAClD,MAAM,aA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U,WAAW,QAAQ;AAC7C,qCAAa,UAAU,SAAS;AAChC,sCAAO,wBAAwB,YAAY;GACzC,OAAO;GACP,WAAW;GACZ,CAAC;UACK,OAAO;AACd,MAAI;AACF,kCAAS,UAAU,EAAE,OAAO,MAAM,CAAC;UAC7B;EAGR,MAAM,MAAM;AACZ,sCAAO,iCAAiC,YAAY,EAClD,OAAO,SACR,CAAC;AACF,QAAM,IAAI,MAAM,gCAAgC,SAAS,IAAI,IAAI,UAAU;;CAG7E,MAAM,gBAAgBC,gDAAoB,cAAc;AAExD,KAAI,cACF,KAAI;AACF,mCAAS,cAAc,QAAQ,YAAY,SAAS,EAAE;GACpD,OAAO;GACP,KAAK,cAAc,OAAO;GAC3B,CAAC;UACK,OAAO;AACd,UAAQ,MAAM,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport { createReadStream, rmSync } from 'node:fs';\nimport { chmod, mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n// Helper to hash existing file via stream\nconst getFileHash = (path: string): Promise<string | null> => {\n return new Promise((resolve) => {\n const hash = createHash('sha256');\n const stream = createReadStream(path);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', () => resolve(null));\n });\n};\n\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n {\n encoding = 'utf8',\n tempDir,\n }: { encoding?: BufferEncoding; tempDir?: string } = {}\n): Promise<boolean> => {\n const newDataHash = createHash('sha256').update(data, encoding).digest('hex');\n const existingHash = await getFileHash(path);\n\n if (newDataHash === existingHash) {\n return false;\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n let mode: number | undefined;\n try {\n mode = (await stat(path)).mode;\n } catch {}\n\n await writeFile(tempPath, data, { encoding });\n\n if (mode !== undefined) {\n await chmod(tempPath, mode);\n }\n\n await rename(tempPath, path);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":";;;;;;;;AAKA,MAAM,kCAAkB,IAAI,KAAa;AAGzC,QAAQ,GAAG,cAAc;AACvB,MAAK,MAAM,QAAQ,gBACjB,KAAI;AACF,sBAAO,MAAM,EAAE,OAAO,MAAM,CAAC;SACvB;EAEV;AAGF,MAAM,eAAe,SAAyC;AAC5D,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,mCAAkB,SAAS;EACjC,MAAM,uCAA0B,KAAK;AACrC,SAAO,GAAG,SAAS,UAAU,KAAK,OAAO,MAAM,CAAC;AAChD,SAAO,GAAG,aAAa,QAAQ,KAAK,OAAO,MAAM,CAAC,CAAC;AACnD,SAAO,GAAG,eAAe,QAAQ,KAAK,CAAC;GACvC;;AAGJ,MAAa,qBAAqB,OAChC,MACA,MACA,EACE,WAAW,QACX,YACmD,EAAE,KAClC;AAIrB,iCAH+B,SAAS,CAAC,OAAO,MAAM,SAAS,CAAC,OAAO,
|
|
1
|
+
{"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport { createReadStream, rmSync } from 'node:fs';\nimport { chmod, mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n// Helper to hash existing file via stream\nconst getFileHash = (path: string): Promise<string | null> => {\n return new Promise((resolve) => {\n const hash = createHash('sha256');\n const stream = createReadStream(path);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', () => resolve(null));\n });\n};\n\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n {\n encoding = 'utf8',\n tempDir,\n }: { encoding?: BufferEncoding; tempDir?: string } = {}\n): Promise<boolean> => {\n const newDataHash = createHash('sha256').update(data, encoding).digest('hex');\n const existingHash = await getFileHash(path);\n\n if (newDataHash === existingHash) {\n return false;\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n let mode: number | undefined;\n try {\n mode = (await stat(path)).mode;\n } catch {}\n\n await writeFile(tempPath, data, { encoding });\n\n if (mode !== undefined) {\n await chmod(tempPath, mode);\n }\n\n await rename(tempPath, path);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":";;;;;;;;AAKA,MAAM,kCAAkB,IAAI,KAAa;AAGzC,QAAQ,GAAG,cAAc;AACvB,MAAK,MAAM,QAAQ,gBACjB,KAAI;AACF,sBAAO,MAAM,EAAE,OAAO,MAAM,CAAC;SACvB;EAEV;AAGF,MAAM,eAAe,SAAyC;AAC5D,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,mCAAkB,SAAS;EACjC,MAAM,uCAA0B,KAAK;AACrC,SAAO,GAAG,SAAS,UAAU,KAAK,OAAO,MAAM,CAAC;AAChD,SAAO,GAAG,aAAa,QAAQ,KAAK,OAAO,MAAM,CAAC,CAAC;AACnD,SAAO,GAAG,eAAe,QAAQ,KAAK,CAAC;GACvC;;AAGJ,MAAa,qBAAqB,OAChC,MACA,MACA,EACE,WAAW,QACX,YACmD,EAAE,KAClC;AAIrB,iCAH+B,SAAS,CAAC,OAAO,MAAM,SAAS,CAAC,OAAO,MAGxD,KAAK,MAFO,YAAY,KAAK,CAG1C,QAAO;AAGT,KAAI,QACF,mCAAY,SAAS,EAAE,WAAW,MAAM,CAAC;CAG3C,MAAM,eAAe,2BAAY,KAAK,CAAC,GAAG,KAAK,KAAK,CAAC,gCAAe,EAAE,CAAC,SAAS,MAAM,CAAC;CACvF,MAAM,WAAW,8BACR,SAAS,aAAa,GAC3B,GAAG,KAAK,GAAG;AACf,iBAAgB,IAAI,SAAS;AAE7B,KAAI;EACF,IAAI;AACJ,MAAI;AACF,WAAQ,iCAAW,KAAK,EAAE;UACpB;AAER,wCAAgB,UAAU,MAAM,EAAE,UAAU,CAAC;AAE7C,MAAI,SAAS,OACX,mCAAY,UAAU,KAAK;AAG7B,qCAAa,UAAU,KAAK;UACrB,OAAO;AACd,MAAI;AACF,kCAAS,UAAU,EAAE,OAAO,MAAM,CAAC;UAC7B;AACR,QAAM;WACE;AACR,kBAAgB,OAAO,SAAS;;AAGlC,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeDynamicDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeDynamicDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { OUTPUT_FORMAT } from '@intlayer/config/defaultValues';\nimport { colorizePath } from '@intlayer/config/logger';\nimport { getPerLocaleDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { parallelize } from '../utils/parallelize';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport type { MergedDictionaryOutput } from './writeMergedDictionary';\n\nexport type DictionaryResult = {\n dictionaryPath: string;\n dictionary: Dictionary;\n};\n\nexport type LocalizedDictionaryResult = Partial<\n Record<Locale, DictionaryResult>\n>;\n\nexport type LocalizedDictionaryOutput = Record<\n string,\n LocalizedDictionaryResult\n>;\n\nconst DICTIONARIES_SUBDIR = 'json'; // Necessary to add a static first dir for Turbopack\n\n/**\n * Generates the content of a dictionary entry point file.\n */\nexport const generateDictionaryEntryPoint = (\n key: string,\n locales: string[],\n format: 'cjs' | 'esm' = 'esm'\n): string => {\n const sortedLocales = [...locales].sort((a, b) =>\n String(a).localeCompare(String(b))\n );\n\n const localeEntries = sortedLocales\n .map((locale) =>\n format === 'esm'\n ? ` '${locale}': () => import('./${DICTIONARIES_SUBDIR}/${key}/${locale}.json').then(m => m.default)`\n : ` '${locale}': () => Promise.resolve(require('./${DICTIONARIES_SUBDIR}/${key}/${locale}.json'))`\n )\n .join(',\\n');\n\n if (format === 'esm') {\n return (\n `const content = {\\n${localeEntries}\\n};\\n\\n` +\n `export default content;\\n`\n );\n }\n return `module.exports = {\\n${localeEntries}\\n};\\n`;\n};\n\n/**\n * Write the localized dictionaries to the dictionariesDir\n * @param mergedDictionaries - The merged dictionaries\n * @param configuration - The configuration\n * @returns The final dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/dynamic_dictionary/dictionaries/en_home.json\n * // .intlayer/dynamic_dictionary/dictionaries/fr_home.json\n * ```\n */\nexport const writeDynamicDictionary = async (\n mergedDictionaries: MergedDictionaryOutput,\n configuration: IntlayerConfig,\n formats: ('cjs' | 'esm')[] = OUTPUT_FORMAT\n): Promise<LocalizedDictionaryOutput> => {\n const { locales, defaultLocale } = configuration.internationalization;\n const { dynamicDictionariesDir } = configuration.system;\n\n const dictDir = resolve(dynamicDictionariesDir, DICTIONARIES_SUBDIR);\n await mkdir(dictDir, { recursive: true });\n\n const resultDictionariesPaths: LocalizedDictionaryOutput = {};\n\n // Merge dictionaries with the same key and write to dictionariesDir\n await parallelize(\n Object.entries(mergedDictionaries).sort(([a], [b]) =>\n String(a).localeCompare(String(b))\n ),\n async ([key, dictionaryEntry]) => {\n if (key === 'undefined') return;\n\n const localizedDictionariesPathsRecord: LocalizedDictionaryResult = {};\n\n const keyDir = resolve(dictDir, key);\n await mkdir(keyDir, { recursive: true });\n\n await parallelize(locales, async (locale) => {\n const localizedDictionary = getPerLocaleDictionary(\n dictionaryEntry.dictionary,\n locale,\n defaultLocale\n );\n\n // Directory structure: json/key/locale.json\n const resultFilePath = resolve(keyDir, `${locale}.json`);\n\n await writeJsonIfChanged(resultFilePath, localizedDictionary).catch(\n (err) => {\n console.error(\n `Error creating localized ${key}/${locale}.json:`,\n err\n );\n }\n );\n\n localizedDictionariesPathsRecord[locale] = {\n dictionaryPath: resultFilePath,\n dictionary: localizedDictionary,\n };\n });\n\n resultDictionariesPaths[key] = localizedDictionariesPathsRecord;\n\n await parallelize(formats, async (format) => {\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n const content = generateDictionaryEntryPoint(key, locales, format);\n\n await writeFileIfChanged(\n resolve(dynamicDictionariesDir, `${key}.${extension}`),\n content\n ).catch((err) => {\n console.error(\n `Error creating dynamic ${colorizePath(resolve(dynamicDictionariesDir, `${key}.${extension}`))}:`,\n err\n );\n });\n });\n }\n );\n\n return resultDictionariesPaths;\n};\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,sBAAsB;;;;AAK5B,MAAa,gCACX,KACA,SACA,SAAwB,UACb;CAKX,MAAM,gBAJgB,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,MAC1C,OAAO,EAAE,CAAC,cAAc,OAAO,EAAE,CAAC,
|
|
1
|
+
{"version":3,"file":"writeDynamicDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeDynamicDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { OUTPUT_FORMAT } from '@intlayer/config/defaultValues';\nimport { colorizePath } from '@intlayer/config/logger';\nimport { getPerLocaleDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { parallelize } from '../utils/parallelize';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport type { MergedDictionaryOutput } from './writeMergedDictionary';\n\nexport type DictionaryResult = {\n dictionaryPath: string;\n dictionary: Dictionary;\n};\n\nexport type LocalizedDictionaryResult = Partial<\n Record<Locale, DictionaryResult>\n>;\n\nexport type LocalizedDictionaryOutput = Record<\n string,\n LocalizedDictionaryResult\n>;\n\nconst DICTIONARIES_SUBDIR = 'json'; // Necessary to add a static first dir for Turbopack\n\n/**\n * Generates the content of a dictionary entry point file.\n */\nexport const generateDictionaryEntryPoint = (\n key: string,\n locales: string[],\n format: 'cjs' | 'esm' = 'esm'\n): string => {\n const sortedLocales = [...locales].sort((a, b) =>\n String(a).localeCompare(String(b))\n );\n\n const localeEntries = sortedLocales\n .map((locale) =>\n format === 'esm'\n ? ` '${locale}': () => import('./${DICTIONARIES_SUBDIR}/${key}/${locale}.json').then(m => m.default)`\n : ` '${locale}': () => Promise.resolve(require('./${DICTIONARIES_SUBDIR}/${key}/${locale}.json'))`\n )\n .join(',\\n');\n\n if (format === 'esm') {\n return (\n `const content = {\\n${localeEntries}\\n};\\n\\n` +\n `export default content;\\n`\n );\n }\n return `module.exports = {\\n${localeEntries}\\n};\\n`;\n};\n\n/**\n * Write the localized dictionaries to the dictionariesDir\n * @param mergedDictionaries - The merged dictionaries\n * @param configuration - The configuration\n * @returns The final dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/dynamic_dictionary/dictionaries/en_home.json\n * // .intlayer/dynamic_dictionary/dictionaries/fr_home.json\n * ```\n */\nexport const writeDynamicDictionary = async (\n mergedDictionaries: MergedDictionaryOutput,\n configuration: IntlayerConfig,\n formats: ('cjs' | 'esm')[] = OUTPUT_FORMAT\n): Promise<LocalizedDictionaryOutput> => {\n const { locales, defaultLocale } = configuration.internationalization;\n const { dynamicDictionariesDir } = configuration.system;\n\n const dictDir = resolve(dynamicDictionariesDir, DICTIONARIES_SUBDIR);\n await mkdir(dictDir, { recursive: true });\n\n const resultDictionariesPaths: LocalizedDictionaryOutput = {};\n\n // Merge dictionaries with the same key and write to dictionariesDir\n await parallelize(\n Object.entries(mergedDictionaries).sort(([a], [b]) =>\n String(a).localeCompare(String(b))\n ),\n async ([key, dictionaryEntry]) => {\n if (key === 'undefined') return;\n\n const localizedDictionariesPathsRecord: LocalizedDictionaryResult = {};\n\n const keyDir = resolve(dictDir, key);\n await mkdir(keyDir, { recursive: true });\n\n await parallelize(locales, async (locale) => {\n const localizedDictionary = getPerLocaleDictionary(\n dictionaryEntry.dictionary,\n locale,\n defaultLocale\n );\n\n // Directory structure: json/key/locale.json\n const resultFilePath = resolve(keyDir, `${locale}.json`);\n\n await writeJsonIfChanged(resultFilePath, localizedDictionary).catch(\n (err) => {\n console.error(\n `Error creating localized ${key}/${locale}.json:`,\n err\n );\n }\n );\n\n localizedDictionariesPathsRecord[locale] = {\n dictionaryPath: resultFilePath,\n dictionary: localizedDictionary,\n };\n });\n\n resultDictionariesPaths[key] = localizedDictionariesPathsRecord;\n\n await parallelize(formats, async (format) => {\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n const content = generateDictionaryEntryPoint(key, locales, format);\n\n await writeFileIfChanged(\n resolve(dynamicDictionariesDir, `${key}.${extension}`),\n content\n ).catch((err) => {\n console.error(\n `Error creating dynamic ${colorizePath(resolve(dynamicDictionariesDir, `${key}.${extension}`))}:`,\n err\n );\n });\n });\n }\n );\n\n return resultDictionariesPaths;\n};\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,sBAAsB;;;;AAK5B,MAAa,gCACX,KACA,SACA,SAAwB,UACb;CAKX,MAAM,gBAJgB,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,MAC1C,OAAO,EAAE,CAAC,cAAc,OAAO,EAAE,CAAC,CAGD,CAChC,KAAK,WACJ,WAAW,QACP,MAAM,OAAO,qBAAqB,oBAAoB,GAAG,IAAI,GAAG,OAAO,gCACvE,MAAM,OAAO,sCAAsC,oBAAoB,GAAG,IAAI,GAAG,OAAO,UAC7F,CACA,KAAK,MAAM;AAEd,KAAI,WAAW,MACb,QACE,sBAAsB,cAAc;AAIxC,QAAO,uBAAuB,cAAc;;;;;;;;;;;;;;;;;;AAmB9C,MAAa,yBAAyB,OACpC,oBACA,eACA,UAA6B,kBACU;CACvC,MAAM,EAAE,SAAS,kBAAkB,cAAc;CACjD,MAAM,EAAE,2BAA2B,cAAc;CAEjD,MAAM,UAAU,QAAQ,wBAAwB,oBAAoB;AACpE,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;CAEzC,MAAM,0BAAqD,EAAE;AAG7D,OAAM,YACJ,OAAO,QAAQ,mBAAmB,CAAC,MAAM,CAAC,IAAI,CAAC,OAC7C,OAAO,EAAE,CAAC,cAAc,OAAO,EAAE,CAAC,CACnC,EACD,OAAO,CAAC,KAAK,qBAAqB;AAChC,MAAI,QAAQ,YAAa;EAEzB,MAAM,mCAA8D,EAAE;EAEtE,MAAM,SAAS,QAAQ,SAAS,IAAI;AACpC,QAAM,MAAM,QAAQ,EAAE,WAAW,MAAM,CAAC;AAExC,QAAM,YAAY,SAAS,OAAO,WAAW;GAC3C,MAAM,sBAAsB,uBAC1B,gBAAgB,YAChB,QACA,cACD;GAGD,MAAM,iBAAiB,QAAQ,QAAQ,GAAG,OAAO,OAAO;AAExD,SAAM,mBAAmB,gBAAgB,oBAAoB,CAAC,OAC3D,QAAQ;AACP,YAAQ,MACN,4BAA4B,IAAI,GAAG,OAAO,SAC1C,IACD;KAEJ;AAED,oCAAiC,UAAU;IACzC,gBAAgB;IAChB,YAAY;IACb;IACD;AAEF,0BAAwB,OAAO;AAE/B,QAAM,YAAY,SAAS,OAAO,WAAW;GAC3C,MAAM,YAAY,WAAW,QAAQ,QAAQ;GAC7C,MAAM,UAAU,6BAA6B,KAAK,SAAS,OAAO;AAElE,SAAM,mBACJ,QAAQ,wBAAwB,GAAG,IAAI,GAAG,YAAY,EACtD,QACD,CAAC,OAAO,QAAQ;AACf,YAAQ,MACN,0BAA0B,aAAa,QAAQ,wBAAwB,GAAG,IAAI,GAAG,YAAY,CAAC,CAAC,IAC/F,IACD;KACD;IACF;GAEL;AAED,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeMergedDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeMergedDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { colorizePath } from '@intlayer/config/logger';\nimport {\n mergeDictionaries,\n normalizeDictionaries,\n} from '@intlayer/core/dictionaryManipulator';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { parallelize } from '../utils/parallelize';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport type { UnmergedDictionaryOutput } from './writeUnmergedDictionary';\n\nexport type MergedDictionaryResult = {\n dictionaryPath: string;\n dictionary: Dictionary;\n};\n\nexport type MergedDictionaryOutput = Record<string, MergedDictionaryResult>;\n\n/**\n * Write the merged dictionaries to the dictionariesDir\n * @param groupedDictionaries - The grouped dictionaries\n * @param configuration - The configuration\n * @returns The merged dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/dictionary/home.json\n * // { key: 'home', content: { ... } },\n * ```\n */\nexport const writeMergedDictionaries = async (\n groupedDictionaries: UnmergedDictionaryOutput,\n configuration: IntlayerConfig\n): Promise<MergedDictionaryOutput> => {\n const { dictionariesDir } = configuration.system;\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(dictionariesDir), { recursive: true });\n\n const results = await parallelize(\n Object.entries(groupedDictionaries),\n async ([key, dictionariesEntry]) => {\n if (key === 'undefined') {\n return undefined as unknown as readonly [\n string,\n MergedDictionaryResult,\n ];\n }\n\n const normalizedDictionaries = normalizeDictionaries(\n dictionariesEntry.dictionaries,\n configuration\n );\n\n const mergedDictionary = mergeDictionaries(normalizedDictionaries);\n\n const outputFileName = `${key}.json`;\n const resultFilePath = resolve(dictionariesDir, outputFileName);\n\n // Write the merged dictionary\n await writeJsonIfChanged(resultFilePath, mergedDictionary).catch(\n (err) => {\n console.error(\n `Error creating merged ${colorizePath(resultFilePath)}:`,\n err\n );\n }\n );\n\n return [\n key,\n {\n dictionaryPath: resultFilePath,\n dictionary: mergedDictionary,\n } as MergedDictionaryResult,\n ] as const;\n }\n );\n\n return Object.fromEntries(\n results.filter(Boolean) as Array<readonly [string, MergedDictionaryResult]>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,0BAA0B,OACrC,qBACA,kBACoC;CACpC,MAAM,EAAE,oBAAoB,cAAc;AAG1C,OAAM,MAAM,QAAQ,gBAAgB,EAAE,EAAE,WAAW,MAAM,CAAC;CAE1D,MAAM,UAAU,MAAM,YACpB,OAAO,QAAQ,oBAAoB,EACnC,OAAO,CAAC,KAAK,uBAAuB;AAClC,MAAI,QAAQ,YACV;EAWF,MAAM,mBAAmB,kBALM,sBAC7B,kBAAkB,cAClB,
|
|
1
|
+
{"version":3,"file":"writeMergedDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeMergedDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { colorizePath } from '@intlayer/config/logger';\nimport {\n mergeDictionaries,\n normalizeDictionaries,\n} from '@intlayer/core/dictionaryManipulator';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { parallelize } from '../utils/parallelize';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport type { UnmergedDictionaryOutput } from './writeUnmergedDictionary';\n\nexport type MergedDictionaryResult = {\n dictionaryPath: string;\n dictionary: Dictionary;\n};\n\nexport type MergedDictionaryOutput = Record<string, MergedDictionaryResult>;\n\n/**\n * Write the merged dictionaries to the dictionariesDir\n * @param groupedDictionaries - The grouped dictionaries\n * @param configuration - The configuration\n * @returns The merged dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/dictionary/home.json\n * // { key: 'home', content: { ... } },\n * ```\n */\nexport const writeMergedDictionaries = async (\n groupedDictionaries: UnmergedDictionaryOutput,\n configuration: IntlayerConfig\n): Promise<MergedDictionaryOutput> => {\n const { dictionariesDir } = configuration.system;\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(dictionariesDir), { recursive: true });\n\n const results = await parallelize(\n Object.entries(groupedDictionaries),\n async ([key, dictionariesEntry]) => {\n if (key === 'undefined') {\n return undefined as unknown as readonly [\n string,\n MergedDictionaryResult,\n ];\n }\n\n const normalizedDictionaries = normalizeDictionaries(\n dictionariesEntry.dictionaries,\n configuration\n );\n\n const mergedDictionary = mergeDictionaries(normalizedDictionaries);\n\n const outputFileName = `${key}.json`;\n const resultFilePath = resolve(dictionariesDir, outputFileName);\n\n // Write the merged dictionary\n await writeJsonIfChanged(resultFilePath, mergedDictionary).catch(\n (err) => {\n console.error(\n `Error creating merged ${colorizePath(resultFilePath)}:`,\n err\n );\n }\n );\n\n return [\n key,\n {\n dictionaryPath: resultFilePath,\n dictionary: mergedDictionary,\n } as MergedDictionaryResult,\n ] as const;\n }\n );\n\n return Object.fromEntries(\n results.filter(Boolean) as Array<readonly [string, MergedDictionaryResult]>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,0BAA0B,OACrC,qBACA,kBACoC;CACpC,MAAM,EAAE,oBAAoB,cAAc;AAG1C,OAAM,MAAM,QAAQ,gBAAgB,EAAE,EAAE,WAAW,MAAM,CAAC;CAE1D,MAAM,UAAU,MAAM,YACpB,OAAO,QAAQ,oBAAoB,EACnC,OAAO,CAAC,KAAK,uBAAuB;AAClC,MAAI,QAAQ,YACV;EAWF,MAAM,mBAAmB,kBALM,sBAC7B,kBAAkB,cAClB,cAG+D,CAAC;EAGlE,MAAM,iBAAiB,QAAQ,iBAAiB,GADtB,IAAI,OACiC;AAG/D,QAAM,mBAAmB,gBAAgB,iBAAiB,CAAC,OACxD,QAAQ;AACP,WAAQ,MACN,yBAAyB,aAAa,eAAe,CAAC,IACtD,IACD;IAEJ;AAED,SAAO,CACL,KACA;GACE,gBAAgB;GAChB,YAAY;GACb,CACF;GAEJ;AAED,QAAO,OAAO,YACZ,QAAQ,OAAO,QAAQ,CACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeRemoteDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeRemoteDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config/logger';\nimport { orderDictionaries } from '@intlayer/core/dictionaryManipulator';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDistantDictionaries } from '../loadDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport {\n groupDictionariesByKey,\n type UnmergedDictionaryResult,\n} from './writeUnmergedDictionary';\n\nexport type RemoteDictionaryResult = {\n dictionaryPath: string;\n dictionaries: Dictionary[];\n};\n\nexport type RemoteDictionaryOutput = Record<string, RemoteDictionaryResult>;\n\n/**\n * Write the localized dictionaries to the dictionariesDir\n * @param mergedDictionaries - The merged dictionaries\n * @param configuration - The configuration\n * @returns The final dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/fetch_dictionaries/home.json\n * // { key: 'home', content: { ... } },\n * ```\n */\nexport const writeRemoteDictionary = async (\n remoteDictionaries: Dictionary[],\n configuration: IntlayerConfig\n): Promise<RemoteDictionaryOutput> => {\n const { remoteDictionariesDir } = configuration.system;\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(remoteDictionariesDir), { recursive: true });\n\n const filteredDictionaries = filterInvalidDictionaries(\n remoteDictionaries,\n configuration\n );\n\n // Group dictionaries by key and write to unmergedDictionariesDir\n const groupedDictionaries = groupDictionariesByKey(filteredDictionaries);\n\n // Merge dictionaries with the same key and write to dictionariesDir\n const results = await parallelize(\n Object.entries(groupedDictionaries),\n async ([key, dictionaries]) => {\n if (key === 'undefined') {\n return undefined as unknown as readonly [\n string,\n UnmergedDictionaryResult,\n ];\n }\n\n const formattedDictionaries = formatDistantDictionaries(dictionaries);\n\n const orderedDictionaries = orderDictionaries(formattedDictionaries);\n\n const outputFileName = `${key}.json`;\n const unmergedFilePath = resolve(remoteDictionariesDir, outputFileName);\n\n // Write the grouped dictionaries\n await writeJsonIfChanged(unmergedFilePath, orderedDictionaries).catch(\n (err) => {\n console.error(\n `${x} Error creating unmerged ${colorizePath(unmergedFilePath)}:`,\n err\n );\n }\n );\n\n return [\n key,\n {\n dictionaryPath: unmergedFilePath,\n dictionaries,\n } as UnmergedDictionaryResult,\n ] as const;\n }\n );\n\n return Object.fromEntries(\n results.filter(Boolean) as Array<\n readonly [string, UnmergedDictionaryResult]\n >\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,wBAAwB,OACnC,oBACA,kBACoC;CACpC,MAAM,EAAE,0BAA0B,cAAc;AAGhD,OAAM,MAAM,QAAQ,sBAAsB,EAAE,EAAE,WAAW,MAAM,CAAC;CAQhE,MAAM,sBAAsB,uBANC,0BAC3B,oBACA,
|
|
1
|
+
{"version":3,"file":"writeRemoteDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeRemoteDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config/logger';\nimport { orderDictionaries } from '@intlayer/core/dictionaryManipulator';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDistantDictionaries } from '../loadDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport {\n groupDictionariesByKey,\n type UnmergedDictionaryResult,\n} from './writeUnmergedDictionary';\n\nexport type RemoteDictionaryResult = {\n dictionaryPath: string;\n dictionaries: Dictionary[];\n};\n\nexport type RemoteDictionaryOutput = Record<string, RemoteDictionaryResult>;\n\n/**\n * Write the localized dictionaries to the dictionariesDir\n * @param mergedDictionaries - The merged dictionaries\n * @param configuration - The configuration\n * @returns The final dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/fetch_dictionaries/home.json\n * // { key: 'home', content: { ... } },\n * ```\n */\nexport const writeRemoteDictionary = async (\n remoteDictionaries: Dictionary[],\n configuration: IntlayerConfig\n): Promise<RemoteDictionaryOutput> => {\n const { remoteDictionariesDir } = configuration.system;\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(remoteDictionariesDir), { recursive: true });\n\n const filteredDictionaries = filterInvalidDictionaries(\n remoteDictionaries,\n configuration\n );\n\n // Group dictionaries by key and write to unmergedDictionariesDir\n const groupedDictionaries = groupDictionariesByKey(filteredDictionaries);\n\n // Merge dictionaries with the same key and write to dictionariesDir\n const results = await parallelize(\n Object.entries(groupedDictionaries),\n async ([key, dictionaries]) => {\n if (key === 'undefined') {\n return undefined as unknown as readonly [\n string,\n UnmergedDictionaryResult,\n ];\n }\n\n const formattedDictionaries = formatDistantDictionaries(dictionaries);\n\n const orderedDictionaries = orderDictionaries(formattedDictionaries);\n\n const outputFileName = `${key}.json`;\n const unmergedFilePath = resolve(remoteDictionariesDir, outputFileName);\n\n // Write the grouped dictionaries\n await writeJsonIfChanged(unmergedFilePath, orderedDictionaries).catch(\n (err) => {\n console.error(\n `${x} Error creating unmerged ${colorizePath(unmergedFilePath)}:`,\n err\n );\n }\n );\n\n return [\n key,\n {\n dictionaryPath: unmergedFilePath,\n dictionaries,\n } as UnmergedDictionaryResult,\n ] as const;\n }\n );\n\n return Object.fromEntries(\n results.filter(Boolean) as Array<\n readonly [string, UnmergedDictionaryResult]\n >\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,wBAAwB,OACnC,oBACA,kBACoC;CACpC,MAAM,EAAE,0BAA0B,cAAc;AAGhD,OAAM,MAAM,QAAQ,sBAAsB,EAAE,EAAE,WAAW,MAAM,CAAC;CAQhE,MAAM,sBAAsB,uBANC,0BAC3B,oBACA,cAIqE,CAAC;CAGxE,MAAM,UAAU,MAAM,YACpB,OAAO,QAAQ,oBAAoB,EACnC,OAAO,CAAC,KAAK,kBAAkB;AAC7B,MAAI,QAAQ,YACV;EAQF,MAAM,sBAAsB,kBAFE,0BAA0B,aAEW,CAAC;EAGpE,MAAM,mBAAmB,QAAQ,uBAAuB,GAD9B,IAAI,OACyC;AAGvE,QAAM,mBAAmB,kBAAkB,oBAAoB,CAAC,OAC7D,QAAQ;AACP,WAAQ,MACN,GAAG,EAAE,2BAA2B,aAAa,iBAAiB,CAAC,IAC/D,IACD;IAEJ;AAED,SAAO,CACL,KACA;GACE,gBAAgB;GAChB;GACD,CACF;GAEJ;AAED,QAAO,OAAO,YACZ,QAAQ,OAAO,QAAQ,CAGxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeUnmergedDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeUnmergedDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config/logger';\nimport { orderDictionaries } from '@intlayer/core/dictionaryManipulator';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, DictionaryKey } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\n\nexport const groupDictionariesByKey = (\n dictionaries: Dictionary[]\n): Record<string, Dictionary[]> =>\n dictionaries.reduce(\n (acc, dictionary) => {\n const key = dictionary.key;\n if (!acc[key]) {\n acc[key] = [];\n }\n acc[key].push(dictionary);\n return acc;\n },\n {} as Record<string, Dictionary[]>\n );\n\nexport type UnmergedDictionaryResult = {\n dictionaryPath: string;\n dictionaries: Dictionary[];\n};\n\nexport type UnmergedDictionaryOutput = Record<\n DictionaryKey,\n UnmergedDictionaryResult\n>;\n\n/**\n * Write the unmerged dictionaries to the unmergedDictionariesDir\n * @param dictionaries - The dictionaries to write\n * @param configuration - The configuration\n * @returns The grouped dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * console.log(unmergedDictionaries);\n *\n * // .intlayer/unmerged_dictionaries/home.json\n * // {\n * // [\n * // { key: 'home', content: { ... } },\n * // { key: 'home', content: { ... } },\n * // ],\n * // }\n * ```\n */\nexport const writeUnmergedDictionaries = async (\n dictionaries: Dictionary[],\n configuration: IntlayerConfig,\n env: 'prod' | 'dev'\n): Promise<UnmergedDictionaryOutput> => {\n const { unmergedDictionariesDir } = configuration.system;\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(unmergedDictionariesDir), { recursive: true });\n\n const filteredDictionaries = filterInvalidDictionaries(\n dictionaries,\n configuration,\n { checkSchema: true }\n );\n\n // Group dictionaries by key and write to unmergedDictionariesDir\n const groupedDictionaries = groupDictionariesByKey(filteredDictionaries);\n\n const results = await parallelize(\n Object.entries(groupedDictionaries),\n async ([key, dictionaries]) => {\n if (key === 'undefined') {\n return undefined as unknown as readonly [\n string,\n UnmergedDictionaryResult,\n ];\n }\n\n const orderedDictionaries = orderDictionaries(dictionaries);\n\n const outputFileName = `${key}.json`;\n const unmergedFilePath = resolve(unmergedDictionariesDir, outputFileName);\n\n // Write the grouped dictionaries in disk if the editor is enabled\n // To make work the visual editor on the server\n // No need them if the editor is disabled\n // But in local env (env: 'dev') we write them for the vscode extension\n if (configuration.editor.enabled || env === 'dev') {\n await writeJsonIfChanged(unmergedFilePath, orderedDictionaries).catch(\n (err) => {\n console.error(\n `${x} Error creating unmerged ${colorizePath(unmergedFilePath)}:`,\n err\n );\n }\n );\n }\n\n return [\n key,\n {\n dictionaryPath: unmergedFilePath,\n dictionaries: dictionaries,\n } as UnmergedDictionaryResult,\n ] as const;\n }\n );\n\n return Object.fromEntries(\n results.filter(Boolean) as Array<\n readonly [string, UnmergedDictionaryResult]\n >\n );\n};\n"],"mappings":";;;;;;;;;AAUA,MAAa,0BACX,iBAEA,aAAa,QACV,KAAK,eAAe;CACnB,MAAM,MAAM,WAAW;AACvB,KAAI,CAAC,IAAI,KACP,KAAI,OAAO,EAAE;AAEf,KAAI,KAAK,KAAK,WAAW;AACzB,QAAO;GAET,EAAE,CACH;;;;;;;;;;;;;;;;;;;;;AAgCH,MAAa,4BAA4B,OACvC,cACA,eACA,QACsC;CACtC,MAAM,EAAE,4BAA4B,cAAc;AAGlD,OAAM,MAAM,QAAQ,wBAAwB,EAAE,EAAE,WAAW,MAAM,CAAC;CASlE,MAAM,sBAAsB,uBAPC,0BAC3B,cACA,eACA,EAAE,aAAa,MAAM,
|
|
1
|
+
{"version":3,"file":"writeUnmergedDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeUnmergedDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config/logger';\nimport { orderDictionaries } from '@intlayer/core/dictionaryManipulator';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, DictionaryKey } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\n\nexport const groupDictionariesByKey = (\n dictionaries: Dictionary[]\n): Record<string, Dictionary[]> =>\n dictionaries.reduce(\n (acc, dictionary) => {\n const key = dictionary.key;\n if (!acc[key]) {\n acc[key] = [];\n }\n acc[key].push(dictionary);\n return acc;\n },\n {} as Record<string, Dictionary[]>\n );\n\nexport type UnmergedDictionaryResult = {\n dictionaryPath: string;\n dictionaries: Dictionary[];\n};\n\nexport type UnmergedDictionaryOutput = Record<\n DictionaryKey,\n UnmergedDictionaryResult\n>;\n\n/**\n * Write the unmerged dictionaries to the unmergedDictionariesDir\n * @param dictionaries - The dictionaries to write\n * @param configuration - The configuration\n * @returns The grouped dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * console.log(unmergedDictionaries);\n *\n * // .intlayer/unmerged_dictionaries/home.json\n * // {\n * // [\n * // { key: 'home', content: { ... } },\n * // { key: 'home', content: { ... } },\n * // ],\n * // }\n * ```\n */\nexport const writeUnmergedDictionaries = async (\n dictionaries: Dictionary[],\n configuration: IntlayerConfig,\n env: 'prod' | 'dev'\n): Promise<UnmergedDictionaryOutput> => {\n const { unmergedDictionariesDir } = configuration.system;\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(unmergedDictionariesDir), { recursive: true });\n\n const filteredDictionaries = filterInvalidDictionaries(\n dictionaries,\n configuration,\n { checkSchema: true }\n );\n\n // Group dictionaries by key and write to unmergedDictionariesDir\n const groupedDictionaries = groupDictionariesByKey(filteredDictionaries);\n\n const results = await parallelize(\n Object.entries(groupedDictionaries),\n async ([key, dictionaries]) => {\n if (key === 'undefined') {\n return undefined as unknown as readonly [\n string,\n UnmergedDictionaryResult,\n ];\n }\n\n const orderedDictionaries = orderDictionaries(dictionaries);\n\n const outputFileName = `${key}.json`;\n const unmergedFilePath = resolve(unmergedDictionariesDir, outputFileName);\n\n // Write the grouped dictionaries in disk if the editor is enabled\n // To make work the visual editor on the server\n // No need them if the editor is disabled\n // But in local env (env: 'dev') we write them for the vscode extension\n if (configuration.editor.enabled || env === 'dev') {\n await writeJsonIfChanged(unmergedFilePath, orderedDictionaries).catch(\n (err) => {\n console.error(\n `${x} Error creating unmerged ${colorizePath(unmergedFilePath)}:`,\n err\n );\n }\n );\n }\n\n return [\n key,\n {\n dictionaryPath: unmergedFilePath,\n dictionaries: dictionaries,\n } as UnmergedDictionaryResult,\n ] as const;\n }\n );\n\n return Object.fromEntries(\n results.filter(Boolean) as Array<\n readonly [string, UnmergedDictionaryResult]\n >\n );\n};\n"],"mappings":";;;;;;;;;AAUA,MAAa,0BACX,iBAEA,aAAa,QACV,KAAK,eAAe;CACnB,MAAM,MAAM,WAAW;AACvB,KAAI,CAAC,IAAI,KACP,KAAI,OAAO,EAAE;AAEf,KAAI,KAAK,KAAK,WAAW;AACzB,QAAO;GAET,EAAE,CACH;;;;;;;;;;;;;;;;;;;;;AAgCH,MAAa,4BAA4B,OACvC,cACA,eACA,QACsC;CACtC,MAAM,EAAE,4BAA4B,cAAc;AAGlD,OAAM,MAAM,QAAQ,wBAAwB,EAAE,EAAE,WAAW,MAAM,CAAC;CASlE,MAAM,sBAAsB,uBAPC,0BAC3B,cACA,eACA,EAAE,aAAa,MAAM,CAIgD,CAAC;CAExE,MAAM,UAAU,MAAM,YACpB,OAAO,QAAQ,oBAAoB,EACnC,OAAO,CAAC,KAAK,kBAAkB;AAC7B,MAAI,QAAQ,YACV;EAMF,MAAM,sBAAsB,kBAAkB,aAAa;EAG3D,MAAM,mBAAmB,QAAQ,yBAAyB,GADhC,IAAI,OAC2C;AAMzE,MAAI,cAAc,OAAO,WAAW,QAAQ,MAC1C,OAAM,mBAAmB,kBAAkB,oBAAoB,CAAC,OAC7D,QAAQ;AACP,WAAQ,MACN,GAAG,EAAE,2BAA2B,aAAa,iBAAiB,CAAC,IAC/D,IACD;IAEJ;AAGH,SAAO,CACL,KACA;GACE,gBAAgB;GACF;GACf,CACF;GAEJ;AAED,QAAO,OAAO,YACZ,QAAQ,OAAO,QAAQ,CAGxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanRemovedContentDeclaration.mjs","names":[],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"sourcesContent":["import { readFile, rm } from 'node:fs/promises';\nimport { join, normalize, relative } from 'node:path';\nimport { normalizePath } from '@intlayer/config/client';\nimport {\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport fg from 'fast-glob';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint';\nimport { readDictionariesFromDisk } from './utils/readDictionariesFromDisk';\nimport { writeJsonIfChanged } from './writeJsonIfChanged';\n\nexport const cleanRemovedContentDeclaration = async (\n filePath: string,\n keysToKeep: string[],\n configuration: IntlayerConfig\n): Promise<{\n changedDictionariesLocalIds: string[];\n excludeKeys: string[];\n hasRebuilt: boolean;\n}> => {\n const appLogger = getAppLogger(configuration);\n\n const unmergedDictionaries = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n\n const baseDir = configuration.system.baseDir;\n\n const relativeFilePath = relative(baseDir, filePath);\n const flatUnmergedDictionaries = Object.values(unmergedDictionaries).flat();\n\n const filteredUnmergedDictionaries = flatUnmergedDictionaries.filter(\n (dictionary) =>\n dictionary.filePath === relativeFilePath &&\n !keysToKeep.includes(dictionary.key)\n );\n\n // Deduplicate dictionaries by key\n const uniqueUnmergedDictionaries = filteredUnmergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n const changedDictionariesLocalIds: string[] = [];\n const filesToRemove: string[] = [];\n const excludeKeys: string[] = [];\n\n // Identify Unmerged Dictionaries to remove or clean\n await Promise.all(\n uniqueUnmergedDictionaries.map(async (dictionary) => {\n const unmergedFilePath = normalize(\n join(\n configuration.system.unmergedDictionariesDir,\n `${dictionary.key}.json`\n )\n );\n\n try {\n const jsonContent = await readFile(unmergedFilePath, 'utf8');\n const parsedContent = JSON.parse(jsonContent);\n\n if (parsedContent.length === 1) {\n if (parsedContent[0].filePath === relativeFilePath) {\n appLogger(\n `Removing outdated dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n filesToRemove.push(unmergedFilePath);\n excludeKeys.push(dictionary.key);\n }\n } else {\n const filteredContent = parsedContent.filter(\n (content: any) => content.filePath !== relativeFilePath\n );\n await writeJsonIfChanged(unmergedFilePath, filteredContent);\n changedDictionariesLocalIds.push(dictionary.localId!);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n }\n })\n );\n\n const dictionaries = readDictionariesFromDisk<Record<string, Dictionary>>(\n configuration.system.dictionariesDir\n );\n const flatDictionaries = Object.values(dictionaries) as Dictionary[];\n\n const filteredMergedDictionaries = flatDictionaries?.filter(\n (dictionary) =>\n !keysToKeep.includes(dictionary.key) &&\n dictionary.localIds?.length === 1 &&\n (dictionary.localIds[0] as string).endsWith(\n `::local::${relativeFilePath}`\n )\n );\n\n const uniqueMergedDictionaries = filteredMergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n // Identify Merged Dictionaries, Types, and Dynamic Dictionaries to remove\n await Promise.all(\n uniqueMergedDictionaries.map(async (dictionary) => {\n const mergedFilePath = normalize(\n join(configuration.system.dictionariesDir, `${dictionary.key}.json`)\n );\n\n try {\n const fileContent = await readFile(mergedFilePath, 'utf8');\n const parsedContent = JSON.parse(fileContent) as Dictionary;\n\n if (parsedContent.localIds?.length === 1) {\n if (\n parsedContent.localIds[0].endsWith(`::local::${relativeFilePath}`)\n ) {\n appLogger(\n `Removing outdated unmerged dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n\n // Mark JSON for removal\n filesToRemove.push(mergedFilePath);\n\n // Mark TS Types for removal\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n\n // Mark Dynamic Dictionaries for removal\n // We use glob to catch the loader files (.cjs, .mjs) AND the split locale files (.en.json, etc.)\n const dynamicFilesGlob = join(\n configuration.system.dynamicDictionariesDir,\n `${dictionary.key}.*`\n );\n const dynamicFiles = await fg(normalizePath(dynamicFilesGlob), {\n absolute: true,\n });\n filesToRemove.push(...dynamicFiles);\n\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n } else {\n const localIds = parsedContent.localIds?.filter(\n (localeId) => !localeId.endsWith(`::local::${relativeFilePath}`)\n ) as string[];\n const newContent = { ...parsedContent, localIds };\n await writeJsonIfChanged(mergedFilePath, newContent);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n }\n }\n })\n );\n\n // Execute Cleanup\n if (filesToRemove.length > 0 || excludeKeys.length > 0) {\n // Update entry points (indexes) first so the app doesn't import dead files\n await createDictionaryEntryPoint(configuration, { excludeKeys });\n\n // Remove the files synchronously (awaited) immediately after.\n if (filesToRemove.length > 0) {\n await Promise.all(\n filesToRemove.map(async (path) => {\n const relativePath = relative(baseDir, path);\n try {\n await rm(path, { force: true });\n\n appLogger(`Deleted artifact: ${colorizePath(relativePath)}`, {\n isVerbose: true,\n });\n } catch {\n appLogger(\n `Error while removing file ${colorizePath(relativePath)}`,\n {\n isVerbose: true,\n }\n );\n }\n })\n );\n }\n }\n\n return {\n changedDictionariesLocalIds,\n excludeKeys,\n hasRebuilt: filesToRemove.length > 0 || excludeKeys.length > 0,\n };\n};\n"],"mappings":";;;;;;;;;;AAeA,MAAa,iCAAiC,OAC5C,UACA,YACA,kBAKI;CACJ,MAAM,YAAY,aAAa,cAAc;CAE7C,MAAM,uBAAuB,yBAE3B,cAAc,OAAO,wBAAwB;CAE/C,MAAM,UAAU,cAAc,OAAO;CAErC,MAAM,mBAAmB,SAAS,SAAS,SAAS;CAUpD,MAAM,6BAT2B,OAAO,OAAO,qBAAqB,CAAC,MAAM,CAEb,QAC3D,eACC,WAAW,aAAa,oBACxB,CAAC,WAAW,SAAS,WAAW,IAAI,CACvC,CAG+D,QAC7D,YAAY,OAAO,SAClB,UAAU,KAAK,WAAW,MAAM,EAAE,QAAQ,WAAW,IAAI,CAC5D;CAED,MAAM,8BAAwC,EAAE;CAChD,MAAM,gBAA0B,EAAE;CAClC,MAAM,cAAwB,EAAE;AAGhC,OAAM,QAAQ,IACZ,2BAA2B,IAAI,OAAO,eAAe;EACnD,MAAM,mBAAmB,UACvB,KACE,cAAc,OAAO,yBACrB,GAAG,WAAW,IAAI,OACnB,CACF;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[],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"sourcesContent":["import { readFile, rm } from 'node:fs/promises';\nimport { join, normalize, relative } from 'node:path';\nimport { normalizePath } from '@intlayer/config/client';\nimport {\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport fg from 'fast-glob';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint';\nimport { readDictionariesFromDisk } from './utils/readDictionariesFromDisk';\nimport { writeJsonIfChanged } from './writeJsonIfChanged';\n\nexport const cleanRemovedContentDeclaration = async (\n filePath: string,\n keysToKeep: string[],\n configuration: IntlayerConfig\n): Promise<{\n changedDictionariesLocalIds: string[];\n excludeKeys: string[];\n hasRebuilt: boolean;\n}> => {\n const appLogger = getAppLogger(configuration);\n\n const unmergedDictionaries = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n\n const baseDir = configuration.system.baseDir;\n\n const relativeFilePath = relative(baseDir, filePath);\n const flatUnmergedDictionaries = Object.values(unmergedDictionaries).flat();\n\n const filteredUnmergedDictionaries = flatUnmergedDictionaries.filter(\n (dictionary) =>\n dictionary.filePath === relativeFilePath &&\n !keysToKeep.includes(dictionary.key)\n );\n\n // Deduplicate dictionaries by key\n const uniqueUnmergedDictionaries = filteredUnmergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n const changedDictionariesLocalIds: string[] = [];\n const filesToRemove: string[] = [];\n const excludeKeys: string[] = [];\n\n // Identify Unmerged Dictionaries to remove or clean\n await Promise.all(\n uniqueUnmergedDictionaries.map(async (dictionary) => {\n const unmergedFilePath = normalize(\n join(\n configuration.system.unmergedDictionariesDir,\n `${dictionary.key}.json`\n )\n );\n\n try {\n const jsonContent = await readFile(unmergedFilePath, 'utf8');\n const parsedContent = JSON.parse(jsonContent);\n\n if (parsedContent.length === 1) {\n if (parsedContent[0].filePath === relativeFilePath) {\n appLogger(\n `Removing outdated dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n filesToRemove.push(unmergedFilePath);\n excludeKeys.push(dictionary.key);\n }\n } else {\n const filteredContent = parsedContent.filter(\n (content: any) => content.filePath !== relativeFilePath\n );\n await writeJsonIfChanged(unmergedFilePath, filteredContent);\n changedDictionariesLocalIds.push(dictionary.localId!);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n }\n })\n );\n\n const dictionaries = readDictionariesFromDisk<Record<string, Dictionary>>(\n configuration.system.dictionariesDir\n );\n const flatDictionaries = Object.values(dictionaries) as Dictionary[];\n\n const filteredMergedDictionaries = flatDictionaries?.filter(\n (dictionary) =>\n !keysToKeep.includes(dictionary.key) &&\n dictionary.localIds?.length === 1 &&\n (dictionary.localIds[0] as string).endsWith(\n `::local::${relativeFilePath}`\n )\n );\n\n const uniqueMergedDictionaries = filteredMergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n // Identify Merged Dictionaries, Types, and Dynamic Dictionaries to remove\n await Promise.all(\n uniqueMergedDictionaries.map(async (dictionary) => {\n const mergedFilePath = normalize(\n join(configuration.system.dictionariesDir, `${dictionary.key}.json`)\n );\n\n try {\n const fileContent = await readFile(mergedFilePath, 'utf8');\n const parsedContent = JSON.parse(fileContent) as Dictionary;\n\n if (parsedContent.localIds?.length === 1) {\n if (\n parsedContent.localIds[0].endsWith(`::local::${relativeFilePath}`)\n ) {\n appLogger(\n `Removing outdated unmerged dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n\n // Mark JSON for removal\n filesToRemove.push(mergedFilePath);\n\n // Mark TS Types for removal\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n\n // Mark Dynamic Dictionaries for removal\n // We use glob to catch the loader files (.cjs, .mjs) AND the split locale files (.en.json, etc.)\n const dynamicFilesGlob = join(\n configuration.system.dynamicDictionariesDir,\n `${dictionary.key}.*`\n );\n const dynamicFiles = await fg(normalizePath(dynamicFilesGlob), {\n absolute: true,\n });\n filesToRemove.push(...dynamicFiles);\n\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n } else {\n const localIds = parsedContent.localIds?.filter(\n (localeId) => !localeId.endsWith(`::local::${relativeFilePath}`)\n ) as string[];\n const newContent = { ...parsedContent, localIds };\n await writeJsonIfChanged(mergedFilePath, newContent);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n }\n }\n })\n );\n\n // Execute Cleanup\n if (filesToRemove.length > 0 || excludeKeys.length > 0) {\n // Update entry points (indexes) first so the app doesn't import dead files\n await createDictionaryEntryPoint(configuration, { excludeKeys });\n\n // Remove the files synchronously (awaited) immediately after.\n if (filesToRemove.length > 0) {\n await Promise.all(\n filesToRemove.map(async (path) => {\n const relativePath = relative(baseDir, path);\n try {\n await rm(path, { force: true });\n\n appLogger(`Deleted artifact: ${colorizePath(relativePath)}`, {\n isVerbose: true,\n });\n } catch {\n appLogger(\n `Error while removing file ${colorizePath(relativePath)}`,\n {\n isVerbose: true,\n }\n );\n }\n })\n );\n }\n }\n\n return {\n changedDictionariesLocalIds,\n excludeKeys,\n hasRebuilt: filesToRemove.length > 0 || excludeKeys.length > 0,\n };\n};\n"],"mappings":";;;;;;;;;;AAeA,MAAa,iCAAiC,OAC5C,UACA,YACA,kBAKI;CACJ,MAAM,YAAY,aAAa,cAAc;CAE7C,MAAM,uBAAuB,yBAE3B,cAAc,OAAO,wBAAwB;CAE/C,MAAM,UAAU,cAAc,OAAO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,2BAA2B,eAAe,EAAE,aAAa,CAAC;AAGhE,MAAI,cAAc,SAAS,EACzB,OAAM,QAAQ,IACZ,cAAc,IAAI,OAAO,SAAS;GAChC,MAAM,eAAe,SAAS,SAAS,KAAK;AAC5C,OAAI;AACF,UAAM,GAAG,MAAM,EAAE,OAAO,MAAM,CAAC;AAE/B,cAAU,qBAAqB,aAAa,aAAa,IAAI,EAC3D,WAAW,MACZ,CAAC;WACI;AACN,cACE,6BAA6B,aAAa,aAAa,IACvD,EACE,WAAW,MACZ,CACF;;IAEH,CACH;;AAIL,QAAO;EACL;EACA;EACA,YAAY,cAAc,SAAS,KAAK,YAAY,SAAS;EAC9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createDictionaryEntryPoint.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/createDictionaryEntryPoint.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { parallelize } from '../utils/parallelize';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { generateDictionaryListContent } from './generateDictionaryListContent';\nimport { getBuiltDictionariesPath } from './getBuiltDictionariesPath';\nimport { getBuiltDynamicDictionariesPath } from './getBuiltDynamicDictionariesPath';\nimport { getBuiltFetchDictionariesPath } from './getBuiltFetchDictionariesPath';\nimport { getBuiltRemoteDictionariesPath } from './getBuiltRemoteDictionariesPath';\nimport { getBuiltUnmergedDictionariesPath } from './getBuiltUnmergedDictionariesPath';\n\nconst writeDictionaryFiles = async (\n paths: Promise<string[]>,\n fileName: string,\n importType: 'json' | 'javascript',\n functionName: string,\n format: 'cjs' | 'esm',\n configuration = getConfiguration()\n) => {\n const content = generateDictionaryListContent(\n await paths,\n functionName,\n importType,\n format,\n configuration\n );\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n\n const { mainDir } = configuration.system;\n\n await writeFileIfChanged(\n resolve(mainDir, `${fileName}.${extension}`),\n content\n );\n};\n\nexport type CreateDictionaryEntryPointOptions = {\n formats?: ('cjs' | 'esm')[];\n excludeKeys?: string[];\n};\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const createDictionaryEntryPoint = async (\n configuration = getConfiguration(),\n options: CreateDictionaryEntryPointOptions = {}\n) => {\n const { formats, excludeKeys = [] } = options;\n const outputFormats = formats ?? configuration.build.outputFormat;\n const { mainDir } = configuration.system;\n\n await mkdir(mainDir, { recursive: true });\n\n const writeOperations = [\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltDictionariesPath(configuration, excludeKeys),\n importType: 'json',\n functionName: 'getDictionaries',\n fileName: 'dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltUnmergedDictionariesPath(configuration, excludeKeys),\n importType: 'json',\n functionName: 'getUnmergedDictionaries',\n fileName: 'unmerged_dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltDynamicDictionariesPath(\n configuration,\n format,\n excludeKeys\n ),\n importType: 'javascript',\n functionName: 'getDynamicDictionaries',\n fileName: 'dynamic_dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltFetchDictionariesPath(\n configuration,\n format,\n excludeKeys\n ),\n importType: 'javascript',\n functionName: 'getFetchDictionaries',\n fileName: 'fetch_dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltRemoteDictionariesPath(configuration, excludeKeys),\n importType: 'json',\n functionName: 'getRemoteDictionaries',\n fileName: 'remote_dictionaries' as const,\n format,\n }) as const\n ),\n ];\n\n await parallelize(\n writeOperations,\n async ({ paths, fileName, format, functionName, importType }) =>\n writeDictionaryFiles(\n paths,\n fileName,\n importType,\n functionName,\n format,\n configuration\n )\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,uBAAuB,OAC3B,OACA,UACA,YACA,cACA,QACA,gBAAgB,kBAAkB,KAC/B;CACH,MAAM,UAAU,8BACd,MAAM,OACN,cACA,YACA,QACA,cACD;CACD,MAAM,YAAY,WAAW,QAAQ,QAAQ;CAE7C,MAAM,EAAE,YAAY,cAAc;AAElC,OAAM,mBACJ,QAAQ,SAAS,GAAG,SAAS,GAAG,YAAY,EAC5C,QACD;;;;;AAWH,MAAa,6BAA6B,OACxC,gBAAgB,kBAAkB,EAClC,UAA6C,EAAE,KAC5C;CACH,MAAM,EAAE,SAAS,cAAc,EAAE,KAAK;CACtC,MAAM,gBAAgB,WAAW,cAAc,MAAM;CACrD,MAAM,EAAE,YAAY,cAAc;AAElC,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;AA+DzC,OAAM,
|
|
1
|
+
{"version":3,"file":"createDictionaryEntryPoint.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/createDictionaryEntryPoint.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { parallelize } from '../utils/parallelize';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { generateDictionaryListContent } from './generateDictionaryListContent';\nimport { getBuiltDictionariesPath } from './getBuiltDictionariesPath';\nimport { getBuiltDynamicDictionariesPath } from './getBuiltDynamicDictionariesPath';\nimport { getBuiltFetchDictionariesPath } from './getBuiltFetchDictionariesPath';\nimport { getBuiltRemoteDictionariesPath } from './getBuiltRemoteDictionariesPath';\nimport { getBuiltUnmergedDictionariesPath } from './getBuiltUnmergedDictionariesPath';\n\nconst writeDictionaryFiles = async (\n paths: Promise<string[]>,\n fileName: string,\n importType: 'json' | 'javascript',\n functionName: string,\n format: 'cjs' | 'esm',\n configuration = getConfiguration()\n) => {\n const content = generateDictionaryListContent(\n await paths,\n functionName,\n importType,\n format,\n configuration\n );\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n\n const { mainDir } = configuration.system;\n\n await writeFileIfChanged(\n resolve(mainDir, `${fileName}.${extension}`),\n content\n );\n};\n\nexport type CreateDictionaryEntryPointOptions = {\n formats?: ('cjs' | 'esm')[];\n excludeKeys?: string[];\n};\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const createDictionaryEntryPoint = async (\n configuration = getConfiguration(),\n options: CreateDictionaryEntryPointOptions = {}\n) => {\n const { formats, excludeKeys = [] } = options;\n const outputFormats = formats ?? configuration.build.outputFormat;\n const { mainDir } = configuration.system;\n\n await mkdir(mainDir, { recursive: true });\n\n const writeOperations = [\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltDictionariesPath(configuration, excludeKeys),\n importType: 'json',\n functionName: 'getDictionaries',\n fileName: 'dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltUnmergedDictionariesPath(configuration, excludeKeys),\n importType: 'json',\n functionName: 'getUnmergedDictionaries',\n fileName: 'unmerged_dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltDynamicDictionariesPath(\n configuration,\n format,\n excludeKeys\n ),\n importType: 'javascript',\n functionName: 'getDynamicDictionaries',\n fileName: 'dynamic_dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltFetchDictionariesPath(\n configuration,\n format,\n excludeKeys\n ),\n importType: 'javascript',\n functionName: 'getFetchDictionaries',\n fileName: 'fetch_dictionaries' as const,\n format,\n }) as const\n ),\n ...outputFormats.map(\n (format) =>\n ({\n paths: getBuiltRemoteDictionariesPath(configuration, excludeKeys),\n importType: 'json',\n functionName: 'getRemoteDictionaries',\n fileName: 'remote_dictionaries' as const,\n format,\n }) as const\n ),\n ];\n\n await parallelize(\n writeOperations,\n async ({ paths, fileName, format, functionName, importType }) =>\n writeDictionaryFiles(\n paths,\n fileName,\n importType,\n functionName,\n format,\n configuration\n )\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,uBAAuB,OAC3B,OACA,UACA,YACA,cACA,QACA,gBAAgB,kBAAkB,KAC/B;CACH,MAAM,UAAU,8BACd,MAAM,OACN,cACA,YACA,QACA,cACD;CACD,MAAM,YAAY,WAAW,QAAQ,QAAQ;CAE7C,MAAM,EAAE,YAAY,cAAc;AAElC,OAAM,mBACJ,QAAQ,SAAS,GAAG,SAAS,GAAG,YAAY,EAC5C,QACD;;;;;AAWH,MAAa,6BAA6B,OACxC,gBAAgB,kBAAkB,EAClC,UAA6C,EAAE,KAC5C;CACH,MAAM,EAAE,SAAS,cAAc,EAAE,KAAK;CACtC,MAAM,gBAAgB,WAAW,cAAc,MAAM;CACrD,MAAM,EAAE,YAAY,cAAc;AAElC,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;AA+DzC,OAAM,YACJ;EA7DA,GAAG,cAAc,KACd,YACE;GACC,OAAO,yBAAyB,eAAe,YAAY;GAC3D,YAAY;GACZ,cAAc;GACd,UAAU;GACV;GACD,EACJ;EACD,GAAG,cAAc,KACd,YACE;GACC,OAAO,iCAAiC,eAAe,YAAY;GACnE,YAAY;GACZ,cAAc;GACd,UAAU;GACV;GACD,EACJ;EACD,GAAG,cAAc,KACd,YACE;GACC,OAAO,gCACL,eACA,QACA,YACD;GACD,YAAY;GACZ,cAAc;GACd,UAAU;GACV;GACD,EACJ;EACD,GAAG,cAAc,KACd,YACE;GACC,OAAO,8BACL,eACA,QACA,YACD;GACD,YAAY;GACZ,cAAc;GACd,UAAU;GACV;GACD,EACJ;EACD,GAAG,cAAc,KACd,YACE;GACC,OAAO,+BAA+B,eAAe,YAAY;GACjE,YAAY;GACZ,cAAc;GACd,UAAU;GACV;GACD,EACJ;EAIc,EACf,OAAO,EAAE,OAAO,UAAU,QAAQ,cAAc,iBAC9C,qBACE,OACA,UACA,YACA,cACA,QACA,cACD,CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBuiltDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltDictionariesPath = async (\n configuration: IntlayerConfig,\n excludeKeys: string[] = []\n) => {\n const { dictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(dictionariesDir)}/**/*.json`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, '.json');\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,2BAA2B,OACtC,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,iBAAiB,YAAY,cAAc;AAGnD,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAOzC,
|
|
1
|
+
{"version":3,"file":"getBuiltDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltDictionariesPath = async (\n configuration: IntlayerConfig,\n excludeKeys: string[] = []\n) => {\n const { dictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(dictionariesDir)}/**/*.json`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, '.json');\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,2BAA2B,OACtC,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,iBAAiB,YAAY,cAAc;AAGnD,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAOzC,SAAO,MAJkC,GACvC,GAAG,cAAc,gBAAgB,CAAC,YACnC,EAEuB,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,QAAQ;AACnC,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBuiltDynamicDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltDynamicDictionariesPath = async (\n configuration: IntlayerConfig,\n format: 'cjs' | 'esm' = 'esm',\n excludeKeys: string[] = []\n) => {\n const { dynamicDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(dynamicDictionariesDir)}/*.${extension}`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, `.${extension}`);\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,kCAAkC,OAC7C,eACA,SAAwB,OACxB,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,wBAAwB,YAAY,cAAc;AAG1D,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;CAGzC,MAAM,YAAY,WAAW,QAAQ,QAAQ;AAM7C,
|
|
1
|
+
{"version":3,"file":"getBuiltDynamicDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltDynamicDictionariesPath = async (\n configuration: IntlayerConfig,\n format: 'cjs' | 'esm' = 'esm',\n excludeKeys: string[] = []\n) => {\n const { dynamicDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(dynamicDictionariesDir)}/*.${extension}`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, `.${extension}`);\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,kCAAkC,OAC7C,eACA,SAAwB,OACxB,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,wBAAwB,YAAY,cAAc;AAG1D,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;CAGzC,MAAM,YAAY,WAAW,QAAQ,QAAQ;AAM7C,SAAO,MAJkC,GACvC,GAAG,cAAc,uBAAuB,CAAC,KAAK,YAC/C,EAEuB,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,IAAI,YAAY;AAC3C,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBuiltFetchDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltFetchDictionariesPath = async (\n configuration: IntlayerConfig,\n format: 'cjs' | 'esm' = 'esm',\n excludeKeys: string[] = []\n) => {\n const { fetchDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(fetchDictionariesDir)}/*.${extension}`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, `.${extension}`);\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,gCAAgC,OAC3C,eACA,SAAwB,OACxB,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,sBAAsB,YAAY,cAAc;AAGxD,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;CAGzC,MAAM,YAAY,WAAW,QAAQ,QAAQ;AAM7C,
|
|
1
|
+
{"version":3,"file":"getBuiltFetchDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltFetchDictionariesPath = async (\n configuration: IntlayerConfig,\n format: 'cjs' | 'esm' = 'esm',\n excludeKeys: string[] = []\n) => {\n const { fetchDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(fetchDictionariesDir)}/*.${extension}`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, `.${extension}`);\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,gCAAgC,OAC3C,eACA,SAAwB,OACxB,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,sBAAsB,YAAY,cAAc;AAGxD,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;CAGzC,MAAM,YAAY,WAAW,QAAQ,QAAQ;AAM7C,SAAO,MAJkC,GACvC,GAAG,cAAc,qBAAqB,CAAC,KAAK,YAC7C,EAEuB,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,IAAI,YAAY;AAC3C,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBuiltRemoteDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltRemoteDictionariesPath = async (\n configuration: IntlayerConfig,\n excludeKeys: string[] = []\n) => {\n const { remoteDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = fg.sync(\n `${normalizePath(remoteDictionariesDir)}/**/*.json`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, '.json');\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,iCAAiC,OAC5C,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,uBAAuB,YAAY,cAAc;AAGzD,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAOzC,QAJmC,GAAG,KACpC,GAAG,cAAc,sBAAsB,CAAC,
|
|
1
|
+
{"version":3,"file":"getBuiltRemoteDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltRemoteDictionariesPath = async (\n configuration: IntlayerConfig,\n excludeKeys: string[] = []\n) => {\n const { remoteDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = fg.sync(\n `${normalizePath(remoteDictionariesDir)}/**/*.json`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, '.json');\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,iCAAiC,OAC5C,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,uBAAuB,YAAY,cAAc;AAGzD,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAOzC,QAJmC,GAAG,KACpC,GAAG,cAAc,sBAAsB,CAAC,YAGnB,CAAC,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,QAAQ;AACnC,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBuiltUnmergedDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltUnmergedDictionariesPath = async (\n configuration: IntlayerConfig,\n excludeKeys: string[] = []\n) => {\n const { unmergedDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(unmergedDictionariesDir)}/**/*.json`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, '.json');\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,mCAAmC,OAC9C,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,yBAAyB,YAAY,cAAc;AAG3D,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAOzC,
|
|
1
|
+
{"version":3,"file":"getBuiltUnmergedDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getBuiltUnmergedDictionariesPath = async (\n configuration: IntlayerConfig,\n excludeKeys: string[] = []\n) => {\n const { unmergedDictionariesDir, mainDir } = configuration.system;\n\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = await fg(\n `${normalizePath(unmergedDictionariesDir)}/**/*.json`\n );\n\n return dictionariesPath.filter((path) => {\n const key = basename(path, '.json');\n return !excludeKeys.includes(key);\n });\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,mCAAmC,OAC9C,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,yBAAyB,YAAY,cAAc;AAG3D,KAAI,CAAC,WAAW,QAAQ,CACtB,WAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAOzC,SAAO,MAJkC,GACvC,GAAG,cAAc,wBAAwB,CAAC,YAC3C,EAEuB,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,QAAQ;AACnC,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
|