@intlayer/chokidar 8.7.13 → 8.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/cjs/cleanRemovedContentDeclaration.cjs +2 -2
  2. package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
  3. package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +1 -1
  4. package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
  5. package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs +2 -1
  6. package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
  7. package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs +2 -1
  8. package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
  9. package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs +2 -1
  10. package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
  11. package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs +2 -1
  12. package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
  13. package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs +2 -1
  14. package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
  15. package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
  16. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +1 -1
  17. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
  18. package/dist/cjs/prepareIntlayer.cjs +1 -1
  19. package/dist/cjs/prepareIntlayer.cjs.map +1 -1
  20. package/dist/cjs/utils/getPathHash.cjs +15 -4
  21. package/dist/cjs/utils/getPathHash.cjs.map +1 -1
  22. package/dist/cjs/watcher.cjs +11 -0
  23. package/dist/cjs/watcher.cjs.map +1 -1
  24. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +5 -1
  25. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
  26. package/dist/esm/cleanRemovedContentDeclaration.mjs +2 -2
  27. package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
  28. package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +1 -1
  29. package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
  30. package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs +3 -2
  31. package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs.map +1 -1
  32. package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs +3 -2
  33. package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
  34. package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs +3 -2
  35. package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
  36. package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs +3 -2
  37. package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs.map +1 -1
  38. package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs +3 -2
  39. package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs.map +1 -1
  40. package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
  41. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +1 -1
  42. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
  43. package/dist/esm/prepareIntlayer.mjs +1 -1
  44. package/dist/esm/prepareIntlayer.mjs.map +1 -1
  45. package/dist/esm/utils/getPathHash.mjs +15 -3
  46. package/dist/esm/utils/getPathHash.mjs.map +1 -1
  47. package/dist/esm/watcher.mjs +11 -1
  48. package/dist/esm/watcher.mjs.map +1 -1
  49. package/dist/esm/writeContentDeclaration/transformJSFile.mjs +5 -1
  50. package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
  51. package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts +2 -2
  52. package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts.map +1 -1
  53. package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts +2 -2
  54. package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts.map +1 -1
  55. package/dist/types/createDictionaryEntryPoint/getBuiltDictionariesPath.d.ts.map +1 -1
  56. package/dist/types/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.d.ts.map +1 -1
  57. package/dist/types/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.d.ts.map +1 -1
  58. package/dist/types/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.d.ts.map +1 -1
  59. package/dist/types/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.d.ts.map +1 -1
  60. package/dist/types/formatDictionary.d.ts +19 -20
  61. package/dist/types/formatDictionary.d.ts.map +1 -1
  62. package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts +2 -2
  63. package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +1 -1
  64. package/dist/types/utils/getPathHash.d.ts +3 -0
  65. package/dist/types/utils/getPathHash.d.ts.map +1 -1
  66. package/dist/types/watcher.d.ts.map +1 -1
  67. package/dist/types/writeContentDeclaration/transformJSFile.d.ts.map +1 -1
  68. package/package.json +8 -8
@@ -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,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,KAAI,EAAE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;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.PLURAL ||\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 'plural',\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.PLURAL,\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.PLURAL) calleeName = 'plural';\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', 'plural', '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,KAAI,EAAE,iBAAiB,MAAM,aAAa,EACxC;OAAK,MAAM,QAAQ,aAAa,WAC9B,KAAI,EAAE,SAAS,MAAM,KAAK,IAAI,EAAE,eAAe,MAAM,KAAK,EAAE;GAC1D,IAAI,WAAW;AAEf,OAAI,EAAE,WAAW,MAAM,KAAK,IAAI,CAAE,YAAW,KAAK,IAAI;Y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uB,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"}
@@ -72,7 +72,7 @@ const cleanRemovedContentDeclaration = async (filePath, keysToKeep, configuratio
72
72
  }));
73
73
  if (filesToRemove.length > 0 || excludeKeys.length > 0) {
74
74
  await createDictionaryEntryPoint(configuration, { excludeKeys });
75
- if (filesToRemove.length > 0) await Promise.all(filesToRemove.map(async (path) => {
75
+ if (filesToRemove.length > 0) setTimeout(async () => await Promise.all(filesToRemove.map(async (path) => {
76
76
  const relativePath = relative(baseDir, path);
77
77
  try {
78
78
  await rm(path, { force: true });
@@ -80,7 +80,7 @@ const cleanRemovedContentDeclaration = async (filePath, keysToKeep, configuratio
80
80
  } catch {
81
81
  appLogger(`Error while removing file ${colorizePath(relativePath)}`, { isVerbose: true });
82
82
  }
83
- }));
83
+ })), 3e3);
84
84
  }
85
85
  return {
86
86
  changedDictionariesLocalIds,
@@ -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,6BAT2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EACzB,OAAM,QAAQ,IACZ,cAAc,IAAI,OAAO,SAAS;GAChC,MAAM,eAAe,SAAS,SAAS,KAAK;AAC5C,OAAI;AACF,UAAM,GAAG,MAAM,EAAE,OAAO,MAAM,CAAC;AAE/B,cAAU,qBAAqB,aAAa,aAAa,IAAI,EAC3D,WAAW,MACZ,CAAC;WACI;AACN,cACE,6BAA6B,aAAa,aAAa,IACvD,EACE,WAAW,MACZ,CACF;;IAEH,CACH;;AAIL,QAAO;EACL;EACA;EACA,YAAY,cAAc,SAAS,KAAK,YAAY,SAAS;EAC9D"}
1
+ {"version":3,"file":"cleanRemovedContentDeclaration.mjs","names":[],"sources":["../../src/cleanRemovedContentDeclaration.ts"],"sourcesContent":["import { readFile, rm } from 'node:fs/promises';\nimport { join, normalize, relative } from 'node:path';\nimport { normalizePath } from '@intlayer/config/client';\nimport {\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport fg from 'fast-glob';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint';\nimport { readDictionariesFromDisk } from './utils/readDictionariesFromDisk';\nimport { writeJsonIfChanged } from './writeJsonIfChanged';\n\nexport const cleanRemovedContentDeclaration = async (\n filePath: string,\n keysToKeep: string[],\n configuration: IntlayerConfig\n): Promise<{\n changedDictionariesLocalIds: string[];\n excludeKeys: string[];\n hasRebuilt: boolean;\n}> => {\n const appLogger = getAppLogger(configuration);\n\n const unmergedDictionaries = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n\n const baseDir = configuration.system.baseDir;\n\n const relativeFilePath = relative(baseDir, filePath);\n const flatUnmergedDictionaries = Object.values(unmergedDictionaries).flat();\n\n const filteredUnmergedDictionaries = flatUnmergedDictionaries.filter(\n (dictionary) =>\n dictionary.filePath === relativeFilePath &&\n !keysToKeep.includes(dictionary.key)\n );\n\n // Deduplicate dictionaries by key\n const uniqueUnmergedDictionaries = filteredUnmergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n const changedDictionariesLocalIds: string[] = [];\n const filesToRemove: string[] = [];\n const excludeKeys: string[] = [];\n\n // Identify Unmerged Dictionaries to remove or clean\n await Promise.all(\n uniqueUnmergedDictionaries.map(async (dictionary) => {\n const unmergedFilePath = normalize(\n join(\n configuration.system.unmergedDictionariesDir,\n `${dictionary.key}.json`\n )\n );\n\n try {\n const jsonContent = await readFile(unmergedFilePath, 'utf8');\n const parsedContent = JSON.parse(jsonContent);\n\n if (parsedContent.length === 1) {\n if (parsedContent[0].filePath === relativeFilePath) {\n appLogger(\n `Removing outdated dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n filesToRemove.push(unmergedFilePath);\n excludeKeys.push(dictionary.key);\n }\n } else {\n const filteredContent = parsedContent.filter(\n (content: any) => content.filePath !== relativeFilePath\n );\n await writeJsonIfChanged(unmergedFilePath, filteredContent);\n changedDictionariesLocalIds.push(dictionary.localId!);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n }\n })\n );\n\n const dictionaries = readDictionariesFromDisk<Record<string, Dictionary>>(\n configuration.system.dictionariesDir\n );\n const flatDictionaries = Object.values(dictionaries) as Dictionary[];\n\n const filteredMergedDictionaries = flatDictionaries?.filter(\n (dictionary) =>\n !keysToKeep.includes(dictionary.key) &&\n dictionary.localIds?.length === 1 &&\n (dictionary.localIds[0] as string).endsWith(\n `::local::${relativeFilePath}`\n )\n );\n\n const uniqueMergedDictionaries = filteredMergedDictionaries.filter(\n (dictionary, index, self) =>\n index === self.findIndex((t) => t.key === dictionary.key)\n );\n\n // Identify Merged Dictionaries, Types, and Dynamic Dictionaries to remove\n await Promise.all(\n uniqueMergedDictionaries.map(async (dictionary) => {\n const mergedFilePath = normalize(\n join(configuration.system.dictionariesDir, `${dictionary.key}.json`)\n );\n\n try {\n const fileContent = await readFile(mergedFilePath, 'utf8');\n const parsedContent = JSON.parse(fileContent) as Dictionary;\n\n if (parsedContent.localIds?.length === 1) {\n if (\n parsedContent.localIds[0].endsWith(`::local::${relativeFilePath}`)\n ) {\n appLogger(\n `Removing outdated unmerged dictionary ${colorizeKey(dictionary.key)}`,\n { isVerbose: true }\n );\n\n // Mark JSON for removal\n filesToRemove.push(mergedFilePath);\n\n // Mark TS Types for removal\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n\n // Mark Dynamic Dictionaries for removal\n // We use glob to catch the loader files (.cjs, .mjs) AND the split locale files (.en.json, etc.)\n const dynamicFilesGlob = join(\n configuration.system.dynamicDictionariesDir,\n `${dictionary.key}.*`\n );\n const dynamicFiles = await fg(normalizePath(dynamicFilesGlob), {\n absolute: true,\n });\n filesToRemove.push(...dynamicFiles);\n\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n }\n } else {\n const localIds = parsedContent.localIds?.filter(\n (localeId) => !localeId.endsWith(`::local::${relativeFilePath}`)\n ) as string[];\n const newContent = { ...parsedContent, localIds };\n await writeJsonIfChanged(mergedFilePath, newContent);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n if (!excludeKeys.includes(dictionary.key)) {\n excludeKeys.push(dictionary.key);\n }\n const typesFilePath = normalize(\n join(configuration.system.typesDir, `${dictionary.key}.ts`)\n );\n filesToRemove.push(typesFilePath);\n }\n }\n })\n );\n\n // Execute Cleanup\n if (filesToRemove.length > 0 || excludeKeys.length > 0) {\n // Update entry points (indexes) first so the app doesn't import dead files\n await createDictionaryEntryPoint(configuration, { excludeKeys });\n\n // Remove the files synchronously (awaited) immediately after.\n if (filesToRemove.length > 0) {\n setTimeout(\n async () =>\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 3000\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,MAER,CAAC,QAC3D,eACC,WAAW,aAAa,oBACxB,CAAC,WAAW,SAAS,WAAW,IAAI,CAIuB,CAAC,QAC7D,YAAY,OAAO,SAClB,UAAU,KAAK,WAAW,MAAM,EAAE,QAAQ,WAAW,IAAI,CAC5D;CAED,MAAM,8BAAwC,EAAE;CAChD,MAAM,gBAA0B,EAAE;CAClC,MAAM,cAAwB,EAAE;AAGhC,OAAM,QAAQ,IACZ,2BAA2B,IAAI,OAAO,eAAe;EACnD,MAAM,mBAAmB,UACvB,KACE,cAAc,OAAO,yBACrB,GAAG,WAAW,IAAI,OACnB,CACF;AAED,MAAI;GACF,MAAM,cAAc,MAAM,SAAS,kBAAkB,OAAO;GAC5D,MAAM,gBAAgB,KAAK,MAAM,YAAY;AAE7C,OAAI,cAAc,WAAW,GAC3B;QAAI,cAAc,GAAG,aAAa,kBAAkB;AAClD,eACE,gCAAgC,YAAY,WAAW,IAAI,IAC3D,EAAE,WAAW,MAAM,CACpB;AACD,mBAAc,KAAK,iBAAiB;AACpC,iBAAY,KAAK,WAAW,IAAI;;UAE7B;AAIL,UAAM,mBAAmB,kBAHD,cAAc,QACnC,YAAiB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AAM,WAAW,cAAc,UAAU,QACtC,aAAa,CAAC,SAAS,SAAS,YAAY,mBAAmB,CACjE;AAED,UAAM,mBAAmB,gBAAgB;KADpB,GAAG;KAAe;KACY,CAAC;;WAE/C,OAAY;AACnB,OAAI,MAAM,SAAS,UAAU;AAC3B,QAAI,CAAC,YAAY,SAAS,WAAW,IAAI,CACvC,aAAY,KAAK,WAAW,IAAI;IAElC,MAAM,gBAAgB,UACpB,KAAK,cAAc,OAAO,UAAU,GAAG,WAAW,IAAI,KAAK,CAC5D;AACD,kBAAc,KAAK,cAAc;;;GAGrC,CACH;AAGD,KAAI,cAAc,SAAS,KAAK,YAAY,SAAS,GAAG;AAEtD,QAAM,2BAA2B,eAAe,EAAE,aAAa,CAAC;AAGhE,MAAI,cAAc,SAAS,EACzB,YACE,YACE,MAAM,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,EACH,IACD;;AAIL,QAAO;EACL;EACA;EACA,YAAY,cAAc,SAAS,KAAK,YAAY,SAAS;EAC9D"}
@@ -61,7 +61,7 @@ const createDictionaryEntryPoint = async (configuration = getConfiguration(), op
61
61
  fileName: "remote_dictionaries",
62
62
  format
63
63
  }))
64
- ], async ({ paths, fileName, format, functionName, importType }) => writeDictionaryFiles(paths, fileName, importType, functionName, format, configuration));
64
+ ], async ({ paths, fileName, format, functionName, importType }) => await writeDictionaryFiles(paths, fileName, importType, functionName, format, configuration));
65
65
  };
66
66
 
67
67
  //#endregion
@@ -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,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
+ {"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 resolvedPath = await paths;\n\n const content = generateDictionaryListContent(\n resolvedPath,\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 await 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;CAGH,MAAM,UAAU,8BACd,MAHyB,OAIzB,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,MAAM,qBACJ,OACA,UACA,YACA,cACA,QACA,cACD,CACJ"}
@@ -1,6 +1,7 @@
1
+ import { mkdir } from "node:fs/promises";
1
2
  import { basename } from "node:path";
2
3
  import fg from "fast-glob";
3
- import { existsSync, mkdirSync } from "node:fs";
4
+ import { existsSync } from "node:fs";
4
5
  import { normalizePath } from "@intlayer/config/utils";
5
6
 
6
7
  //#region src/createDictionaryEntryPoint/getBuiltDictionariesPath.ts
@@ -9,7 +10,7 @@ import { normalizePath } from "@intlayer/config/utils";
9
10
  */
10
11
  const getBuiltDictionariesPath = async (configuration, excludeKeys = []) => {
11
12
  const { dictionariesDir, mainDir } = configuration.system;
12
- if (!existsSync(mainDir)) mkdirSync(mainDir, { recursive: true });
13
+ if (!existsSync(mainDir)) await mkdir(mainDir, { recursive: true });
13
14
  return (await fg(`${normalizePath(dictionariesDir)}/**/*.json`)).filter((path) => {
14
15
  const key = basename(path, ".json");
15
16
  return !excludeKeys.includes(key);
@@ -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,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
+ {"version":3,"file":"getBuiltDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltDictionariesPath.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\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 await mkdir(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":";;;;;;;;;;AAUA,MAAa,2BAA2B,OACtC,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,iBAAiB,YAAY,cAAc;AAGnD,KAAI,CAAC,WAAW,QAAQ,CACtB,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;AAO3C,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,6 +1,7 @@
1
+ import { mkdir } from "node:fs/promises";
1
2
  import { basename } from "node:path";
2
3
  import fg from "fast-glob";
3
- import { existsSync, mkdirSync } from "node:fs";
4
+ import { existsSync } from "node:fs";
4
5
  import { normalizePath } from "@intlayer/config/utils";
5
6
 
6
7
  //#region src/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.ts
@@ -9,7 +10,7 @@ import { normalizePath } from "@intlayer/config/utils";
9
10
  */
10
11
  const getBuiltDynamicDictionariesPath = async (configuration, format = "esm", excludeKeys = []) => {
11
12
  const { dynamicDictionariesDir, mainDir } = configuration.system;
12
- if (!existsSync(mainDir)) mkdirSync(mainDir, { recursive: true });
13
+ if (!existsSync(mainDir)) await mkdir(mainDir, { recursive: true });
13
14
  const extension = format === "cjs" ? "cjs" : "mjs";
14
15
  return (await fg(`${normalizePath(dynamicDictionariesDir)}/*.${extension}`)).filter((path) => {
15
16
  const key = basename(path, `.${extension}`);
@@ -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,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
+ {"version":3,"file":"getBuiltDynamicDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\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 await mkdir(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":";;;;;;;;;;AAUA,MAAa,kCAAkC,OAC7C,eACA,SAAwB,OACxB,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,wBAAwB,YAAY,cAAc;AAG1D,KAAI,CAAC,WAAW,QAAQ,CACtB,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;CAG3C,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,6 +1,7 @@
1
+ import { mkdir } from "node:fs/promises";
1
2
  import { basename } from "node:path";
2
3
  import fg from "fast-glob";
3
- import { existsSync, mkdirSync } from "node:fs";
4
+ import { existsSync } from "node:fs";
4
5
  import { normalizePath } from "@intlayer/config/utils";
5
6
 
6
7
  //#region src/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.ts
@@ -9,7 +10,7 @@ import { normalizePath } from "@intlayer/config/utils";
9
10
  */
10
11
  const getBuiltFetchDictionariesPath = async (configuration, format = "esm", excludeKeys = []) => {
11
12
  const { fetchDictionariesDir, mainDir } = configuration.system;
12
- if (!existsSync(mainDir)) mkdirSync(mainDir, { recursive: true });
13
+ if (!existsSync(mainDir)) await mkdir(mainDir, { recursive: true });
13
14
  const extension = format === "cjs" ? "cjs" : "mjs";
14
15
  return (await fg(`${normalizePath(fetchDictionariesDir)}/*.${extension}`)).filter((path) => {
15
16
  const key = basename(path, `.${extension}`);
@@ -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,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
+ {"version":3,"file":"getBuiltFetchDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\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 await mkdir(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":";;;;;;;;;;AAUA,MAAa,gCAAgC,OAC3C,eACA,SAAwB,OACxB,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,sBAAsB,YAAY,cAAc;AAGxD,KAAI,CAAC,WAAW,QAAQ,CACtB,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;CAG3C,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,6 +1,7 @@
1
+ import { mkdir } from "node:fs/promises";
1
2
  import { basename } from "node:path";
2
3
  import fg from "fast-glob";
3
- import { existsSync, mkdirSync } from "node:fs";
4
+ import { existsSync } from "node:fs";
4
5
  import { normalizePath } from "@intlayer/config/utils";
5
6
 
6
7
  //#region src/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.ts
@@ -9,7 +10,7 @@ import { normalizePath } from "@intlayer/config/utils";
9
10
  */
10
11
  const getBuiltRemoteDictionariesPath = async (configuration, excludeKeys = []) => {
11
12
  const { remoteDictionariesDir, mainDir } = configuration.system;
12
- if (!existsSync(mainDir)) mkdirSync(mainDir, { recursive: true });
13
+ if (!existsSync(mainDir)) await mkdir(mainDir, { recursive: true });
13
14
  return fg.sync(`${normalizePath(remoteDictionariesDir)}/**/*.json`).filter((path) => {
14
15
  const key = basename(path, ".json");
15
16
  return !excludeKeys.includes(key);
@@ -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,YAGnB,CAAC,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,QAAQ;AACnC,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
1
+ {"version":3,"file":"getBuiltRemoteDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\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 await mkdir(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":";;;;;;;;;;AAUA,MAAa,iCAAiC,OAC5C,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,uBAAuB,YAAY,cAAc;AAGzD,KAAI,CAAC,WAAW,QAAQ,CACtB,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;AAO3C,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,6 +1,7 @@
1
+ import { mkdir } from "node:fs/promises";
1
2
  import { basename } from "node:path";
2
3
  import fg from "fast-glob";
3
- import { existsSync, mkdirSync } from "node:fs";
4
+ import { existsSync } from "node:fs";
4
5
  import { normalizePath } from "@intlayer/config/utils";
5
6
 
6
7
  //#region src/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.ts
@@ -9,7 +10,7 @@ import { normalizePath } from "@intlayer/config/utils";
9
10
  */
10
11
  const getBuiltUnmergedDictionariesPath = async (configuration, excludeKeys = []) => {
11
12
  const { unmergedDictionariesDir, mainDir } = configuration.system;
12
- if (!existsSync(mainDir)) mkdirSync(mainDir, { recursive: true });
13
+ if (!existsSync(mainDir)) await mkdir(mainDir, { recursive: true });
13
14
  return (await fg(`${normalizePath(unmergedDictionariesDir)}/**/*.json`)).filter((path) => {
14
15
  const key = basename(path, ".json");
15
16
  return !excludeKeys.includes(key);
@@ -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,SAAO,MAJkC,GACvC,GAAG,cAAc,wBAAwB,CAAC,YAC3C,EAEuB,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,QAAQ;AACnC,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
1
+ {"version":3,"file":"getBuiltUnmergedDictionariesPath.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\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 await mkdir(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":";;;;;;;;;;AAUA,MAAa,mCAAmC,OAC9C,eACA,cAAwB,EAAE,KACvB;CACH,MAAM,EAAE,yBAAyB,YAAY,cAAc;AAG3D,KAAI,CAAC,WAAW,QAAQ,CACtB,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;AAO3C,SAAO,MAJkC,GACvC,GAAG,cAAc,wBAAwB,CAAC,YAC3C,EAEuB,QAAQ,SAAS;EACvC,MAAM,MAAM,SAAS,MAAM,QAAQ;AACnC,SAAO,CAAC,YAAY,SAAS,IAAI;GACjC"}
@@ -1 +1 @@
1
- {"version":3,"file":"getIntlayerBundle.mjs","names":[],"sources":["../../../src/loadDictionaries/getIntlayerBundle.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { builtinModules } from 'node:module';\nimport { join } from 'node:path';\nimport { bundleFile, type ESBuildPlugin } from '@intlayer/config/file';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Rewrites bare specifiers to absolute paths on the user's disk and externalizes them\n * to preserve directory context (__dirname/import.meta.url).\n */\nconst localResolvePlugin = (\n aliases: Record<string, string>,\n rootRequire: NodeJS.Require\n): ESBuildPlugin => {\n return {\n name: 'local-resolve',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n // 1. Direct alias match\n if (aliases[args.path]) {\n return {\n path: aliases[args.path],\n external: true, // Prevents inlining and context loss\n };\n }\n\n // 2. Dynamic resolution via user workspace\n if (args.path === 'defu' || args.path.startsWith('@intlayer/')) {\n try {\n const absolutePath = rootRequire.resolve(args.path);\n return {\n path: absolutePath,\n external: true, // Injects `require('/absolute/path')`\n };\n } catch {\n return null;\n }\n }\n\n return null;\n });\n },\n };\n};\n\nexport const getIntlayerBundle = async (configuration: IntlayerConfig) => {\n const rootRequire = getProjectRequire(configuration.system.baseDir);\n\n const configurationPath = join(\n configuration.system.configDir,\n `configuration.cjs`\n );\n\n const aliases = {\n '@intlayer/config/built': configurationPath,\n };\n\n const filePath = rootRequire.resolve('intlayer');\n const code = await readFile(filePath, 'utf-8');\n\n const output = await bundleFile(code, filePath, {\n bundle: true,\n platform: 'node',\n external: [\n ...builtinModules,\n ...builtinModules.map((mod) => `node:${mod}`),\n 'vscode',\n 'esbuild',\n ],\n minify: true,\n plugins: [localResolvePlugin(aliases, rootRequire)],\n });\n\n return output ?? '';\n};\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,sBACJ,SACA,gBACkB;AAClB,QAAO;EACL,MAAM;EACN,MAAM,OAAO;AACX,SAAM,UAAU,EAAE,QAAQ,MAAM,GAAG,SAAS;AAE1C,QAAI,QAAQ,KAAK,MACf,QAAO;KACL,MAAM,QAAQ,KAAK;KACnB,UAAU;KACX;AAIH,QAAI,KAAK,SAAS,UAAU,KAAK,KAAK,WAAW,aAAa,CAC5D,KAAI;AAEF,YAAO;MACL,MAFmB,YAAY,QAAQ,KAAK,KAE1B;MAClB,UAAU;MACX;YACK;AACN,YAAO;;AAIX,WAAO;KACP;;EAEL;;AAGH,MAAa,oBAAoB,OAAO,kBAAkC;CACxE,MAAM,cAAc,kBAAkB,cAAc,OAAO,QAAQ;CAOnE,MAAM,UAAU,EACd,0BANwB,KACxB,cAAc,OAAO,WACrB,oBAI2C,EAC5C;CAED,MAAM,WAAW,YAAY,QAAQ,WAAW;AAgBhD,QAAO,MAbc,WAAW,MAFb,SAAS,UAAU,QAAQ,EAER,UAAU;EAC9C,QAAQ;EACR,UAAU;EACV,UAAU;GACR,GAAG;GACH,GAAG,eAAe,KAAK,QAAQ,QAAQ,MAAM;GAC7C;GACA;GACD;EACD,QAAQ;EACR,SAAS,CAAC,mBAAmB,SAAS,YAAY,CAAC;EACpD,CAAC,IAEe"}
1
+ {"version":3,"file":"getIntlayerBundle.mjs","names":[],"sources":["../../../src/loadDictionaries/getIntlayerBundle.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { builtinModules } from 'node:module';\nimport { join } from 'node:path';\nimport { bundleFile, type ESBuildPlugin } from '@intlayer/config/file';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Rewrites bare specifiers to absolute paths on the user's disk and externalizes them\n * to preserve directory context (__dirname/import.meta.url).\n */\nconst localResolvePlugin = (\n aliases: Record<string, string>,\n rootRequire: NodeJS.Require\n): ESBuildPlugin => {\n return {\n name: 'local-resolve',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n // Direct alias match\n if (aliases[args.path]) {\n return {\n path: aliases[args.path],\n external: true, // Prevents inlining and context loss\n };\n }\n\n // Dynamic resolution via user workspace\n if (args.path === 'defu' || args.path.startsWith('@intlayer/')) {\n try {\n const absolutePath = rootRequire.resolve(args.path);\n return {\n path: absolutePath,\n external: true, // Injects `require('/absolute/path')`\n };\n } catch {\n return null;\n }\n }\n\n return null;\n });\n },\n };\n};\n\nexport const getIntlayerBundle = async (configuration: IntlayerConfig) => {\n const rootRequire = getProjectRequire(configuration.system.baseDir);\n\n const configurationPath = join(\n configuration.system.configDir,\n `configuration.cjs`\n );\n\n const aliases = {\n '@intlayer/config/built': configurationPath,\n };\n\n const filePath = rootRequire.resolve('intlayer');\n const code = await readFile(filePath, 'utf-8');\n\n const output = await bundleFile(code, filePath, {\n bundle: true,\n platform: 'node',\n external: [\n ...builtinModules,\n ...builtinModules.map((mod) => `node:${mod}`),\n 'vscode',\n 'esbuild',\n ],\n minify: true,\n plugins: [localResolvePlugin(aliases, rootRequire)],\n });\n\n return output ?? '';\n};\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,sBACJ,SACA,gBACkB;AAClB,QAAO;EACL,MAAM;EACN,MAAM,OAAO;AACX,SAAM,UAAU,EAAE,QAAQ,MAAM,GAAG,SAAS;AAE1C,QAAI,QAAQ,KAAK,MACf,QAAO;KACL,MAAM,QAAQ,KAAK;KACnB,UAAU;KACX;AAIH,QAAI,KAAK,SAAS,UAAU,KAAK,KAAK,WAAW,aAAa,CAC5D,KAAI;AAEF,YAAO;MACL,MAFmB,YAAY,QAAQ,KAAK,KAE1B;MAClB,UAAU;MACX;YACK;AACN,YAAO;;AAIX,WAAO;KACP;;EAEL;;AAGH,MAAa,oBAAoB,OAAO,kBAAkC;CACxE,MAAM,cAAc,kBAAkB,cAAc,OAAO,QAAQ;CAOnE,MAAM,UAAU,EACd,0BANwB,KACxB,cAAc,OAAO,WACrB,oBAI2C,EAC5C;CAED,MAAM,WAAW,YAAY,QAAQ,WAAW;AAgBhD,QAAO,MAbc,WAAW,MAFb,SAAS,UAAU,QAAQ,EAER,UAAU;EAC9C,QAAQ;EACR,UAAU;EACV,UAAU;GACR,GAAG;GACH,GAAG,eAAe,KAAK,QAAQ,QAAQ,MAAM;GAC7C;GACA;GACD;EACD,QAAQ;EACR,SAAS,CAAC,mBAAmB,SAAS,YAAY,CAAC;EACpD,CAAC,IAEe"}
@@ -35,7 +35,7 @@ const getExternalDeps = async (baseDir) => {
35
35
  ...parsedPackages.dependencies,
36
36
  ...parsedPackages.devDependencies
37
37
  });
38
- const esmPackagesToBundle = ["your-esm-package-name"];
38
+ const esmPackagesToBundle = [];
39
39
  const externalDeps = allDependencies.filter((dep) => !esmPackagesToBundle.includes(dep));
40
40
  externalDeps.push("esbuild");
41
41
  cachedExternalDeps = externalDeps;
@@ -1 +1 @@
1
- {"version":3,"file":"loadContentDeclaration.mjs","names":[],"sources":["../../../src/loadDictionaries/loadContentDeclaration.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { loadExternalFile } from '@intlayer/config/file';\nimport {\n cacheDisk,\n getPackageJsonPath,\n getProjectRequire,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { processContentDeclaration } from '../buildIntlayerDictionary/processContentDeclaration';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { getIntlayerBundle } from './getIntlayerBundle';\nimport type { DictionariesStatus } from './loadDictionaries';\nimport { logTypeScriptErrors } from './logTypeScriptErrors';\n\nexport const formatLocalDictionaries = (\n dictionariesRecord: Record<string, Dictionary>,\n configuration: IntlayerConfig\n): Dictionary[] =>\n Object.entries(dictionariesRecord).map(([relativePath, dict]) => ({\n ...dict,\n location: dict.location ?? configuration.dictionary?.location ?? 'local',\n localId: `${dict.key}::local::${relativePath}`,\n filePath: relativePath,\n }));\n\nexport const ensureIntlayerBundle = async (\n configuration: IntlayerConfig\n): Promise<string> => {\n const { system } = configuration;\n\n const { set, isValid } = cacheDisk(configuration, ['intlayer-bundle'], {\n ttlMs: 1000 * 60 * 60 * 24 * 5, // 5 days\n });\n\n const filePath = join(system.cacheDir, 'intlayer-bundle.cjs');\n const hasIntlayerBundle = await isValid();\n\n if (!hasIntlayerBundle) {\n const intlayerBundle = await getIntlayerBundle(configuration);\n await writeFile(filePath, intlayerBundle);\n await set('ok');\n }\n\n return filePath;\n};\n\ntype LoadContentDeclarationOptions = {\n logError?: boolean;\n};\n\n// Initialize a module-level cache\nlet cachedExternalDeps: string[] | null = null;\n\n// Helper to fetch and cache the dependencies\nconst getExternalDeps = async (baseDir: string): Promise<string[]> => {\n if (cachedExternalDeps) {\n return cachedExternalDeps; // Return instantly on subsequent calls\n }\n\n try {\n const packageJsonPath = getPackageJsonPath(baseDir);\n\n const packageJSON = await readFile(\n packageJsonPath.packageJsonPath,\n 'utf-8'\n );\n const parsedPackages = JSON.parse(packageJSON);\n const allDependencies = Object.keys({\n ...parsedPackages.dependencies,\n ...parsedPackages.devDependencies,\n });\n\n // Specify the ESM packages to bundle\n const esmPackagesToBundle = ['your-esm-package-name'];\n\n const externalDeps = allDependencies.filter(\n (dep) => !esmPackagesToBundle.includes(dep)\n );\n\n externalDeps.push('esbuild');\n\n // Save to cache\n cachedExternalDeps = externalDeps;\n } catch (error) {\n console.warn(\n 'Could not read package.json for externalizing dependencies, fallback to empty array',\n error\n );\n cachedExternalDeps = ['esbuild'];\n }\n\n return cachedExternalDeps;\n};\n\nexport const loadContentDeclaration = async (\n path: string,\n configuration: IntlayerConfig,\n bundleFilePath?: string,\n options?: LoadContentDeclarationOptions\n): Promise<Dictionary | undefined> => {\n const { build, system } = configuration;\n\n // Call the cached helper\n const externalDeps = await getExternalDeps(system.baseDir);\n\n const resolvedBundleFilePath =\n bundleFilePath ?? (await ensureIntlayerBundle(configuration));\n\n try {\n const dictionary = await loadExternalFile(path, {\n logError: options?.logError,\n projectRequire: build.require ?? getProjectRequire(),\n buildOptions: {\n packages: undefined, // It fixes the import of ESM packages in the content declaration\n external: externalDeps,\n banner: {\n js: [\n `var __filename = ${JSON.stringify(path)};`,\n `var __dirname = ${JSON.stringify(dirname(path))};`,\n `globalThis.INTLAYER_FILE_PATH = '${path}';`,\n `globalThis.INTLAYER_BASE_DIR = '${configuration.system.baseDir}';`,\n ].join('\\n'),\n },\n },\n aliases: {\n intlayer: resolvedBundleFilePath,\n },\n });\n\n return dictionary;\n } catch (error) {\n console.error(`Error loading content declaration at ${path}:`, error);\n return undefined;\n }\n};\n\nexport const loadContentDeclarations = async (\n contentDeclarationFilePath: string[],\n configuration: IntlayerConfig,\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: LoadContentDeclarationOptions\n): Promise<Dictionary[]> => {\n const { build, system } = configuration;\n\n // Check for TypeScript warnings before we build\n if (build.checkTypes) {\n logTypeScriptErrors(contentDeclarationFilePath, configuration).catch(\n (e) => {\n console.error('Error during TypeScript validation:', e);\n }\n );\n }\n\n const bundleFilePath = await ensureIntlayerBundle(configuration);\n\n try {\n const dictionariesPromises = contentDeclarationFilePath.map(\n async (path) => {\n const relativePath = relative(system.baseDir, path);\n\n const dictionary = await loadContentDeclaration(\n path,\n configuration,\n bundleFilePath,\n options\n );\n\n return { relativePath, dictionary };\n }\n );\n\n const dictionariesArray = await Promise.all(dictionariesPromises);\n const dictionariesRecord = dictionariesArray.reduce(\n (acc, { relativePath, dictionary }) => {\n if (dictionary) {\n acc[relativePath] = dictionary;\n }\n return acc;\n },\n {} as Record<string, Dictionary>\n );\n\n const contentDeclarations: Dictionary[] = formatLocalDictionaries(\n dictionariesRecord,\n configuration\n ).filter((dictionary) => dictionary.location !== 'remote');\n\n const listFoundDictionaries = contentDeclarations.map((declaration) => ({\n dictionaryKey: declaration.key,\n type: 'local' as const,\n status: 'found' as const,\n }));\n\n onStatusUpdate?.(listFoundDictionaries);\n\n const processedDictionaries = await parallelize(\n contentDeclarations,\n async (contentDeclaration): Promise<Dictionary | undefined> => {\n if (!contentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: contentDeclaration.key,\n type: 'local',\n status: 'building',\n },\n ]);\n\n const processedContentDeclaration = await processContentDeclaration(\n contentDeclaration as Dictionary,\n configuration\n );\n\n if (!processedContentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: processedContentDeclaration.key,\n type: 'local',\n status: 'built',\n },\n ]);\n\n return processedContentDeclaration;\n }\n );\n\n return filterInvalidDictionaries(processedDictionaries, configuration, {\n checkSchema: false,\n });\n } catch {\n console.error('Error loading content declarations');\n }\n\n return [];\n};\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,2BACX,oBACA,kBAEA,OAAO,QAAQ,mBAAmB,CAAC,KAAK,CAAC,cAAc,WAAW;CAChE,GAAG;CACH,UAAU,KAAK,YAAY,cAAc,YAAY,YAAY;CACjE,SAAS,GAAG,KAAK,IAAI,WAAW;CAChC,UAAU;CACX,EAAE;AAEL,MAAa,uBAAuB,OAClC,kBACoB;CACpB,MAAM,EAAE,WAAW;CAEnB,MAAM,EAAE,KAAK,YAAY,UAAU,eAAe,CAAC,kBAAkB,EAAE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AAE"}
1
+ {"version":3,"file":"loadContentDeclaration.mjs","names":[],"sources":["../../../src/loadDictionaries/loadContentDeclaration.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { loadExternalFile } from '@intlayer/config/file';\nimport {\n cacheDisk,\n getPackageJsonPath,\n getProjectRequire,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { processContentDeclaration } from '../buildIntlayerDictionary/processContentDeclaration';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { parallelize } from '../utils/parallelize';\nimport { getIntlayerBundle } from './getIntlayerBundle';\nimport type { DictionariesStatus } from './loadDictionaries';\nimport { logTypeScriptErrors } from './logTypeScriptErrors';\n\nexport const formatLocalDictionaries = (\n dictionariesRecord: Record<string, Dictionary>,\n configuration: IntlayerConfig\n): Dictionary[] =>\n Object.entries(dictionariesRecord).map(([relativePath, dict]) => ({\n ...dict,\n location: dict.location ?? configuration.dictionary?.location ?? 'local',\n localId: `${dict.key}::local::${relativePath}`,\n filePath: relativePath,\n }));\n\nexport const ensureIntlayerBundle = async (\n configuration: IntlayerConfig\n): Promise<string> => {\n const { system } = configuration;\n\n const { set, isValid } = cacheDisk(configuration, ['intlayer-bundle'], {\n ttlMs: 1000 * 60 * 60 * 24 * 5, // 5 days\n });\n\n const filePath = join(system.cacheDir, 'intlayer-bundle.cjs');\n const hasIntlayerBundle = await isValid();\n\n if (!hasIntlayerBundle) {\n const intlayerBundle = await getIntlayerBundle(configuration);\n await writeFile(filePath, intlayerBundle);\n await set('ok');\n }\n\n return filePath;\n};\n\ntype LoadContentDeclarationOptions = {\n logError?: boolean;\n};\n\n// Initialize a module-level cache\nlet cachedExternalDeps: string[] | null = null;\n\n// Helper to fetch and cache the dependencies\nconst getExternalDeps = async (baseDir: string): Promise<string[]> => {\n if (cachedExternalDeps) {\n return cachedExternalDeps; // Return instantly on subsequent calls\n }\n\n try {\n const packageJsonPath = getPackageJsonPath(baseDir);\n\n const packageJSON = await readFile(\n packageJsonPath.packageJsonPath,\n 'utf-8'\n );\n const parsedPackages = JSON.parse(packageJSON);\n const allDependencies = Object.keys({\n ...parsedPackages.dependencies,\n ...parsedPackages.devDependencies,\n });\n\n // Specify the ESM packages to bundle\n const esmPackagesToBundle: string[] = [];\n\n const externalDeps = allDependencies.filter(\n (dep) => !esmPackagesToBundle.includes(dep)\n );\n\n externalDeps.push('esbuild');\n\n // Save to cache\n cachedExternalDeps = externalDeps;\n } catch (error) {\n console.warn(\n 'Could not read package.json for externalizing dependencies, fallback to empty array',\n error\n );\n cachedExternalDeps = ['esbuild'];\n }\n\n return cachedExternalDeps;\n};\n\nexport const loadContentDeclaration = async (\n path: string,\n configuration: IntlayerConfig,\n bundleFilePath?: string,\n options?: LoadContentDeclarationOptions\n): Promise<Dictionary | undefined> => {\n const { build, system } = configuration;\n\n // Call the cached helper\n const externalDeps = await getExternalDeps(system.baseDir);\n\n const resolvedBundleFilePath =\n bundleFilePath ?? (await ensureIntlayerBundle(configuration));\n\n try {\n const dictionary = await loadExternalFile(path, {\n logError: options?.logError,\n projectRequire: build.require ?? getProjectRequire(),\n buildOptions: {\n packages: undefined, // It fixes the import of ESM packages in the content declaration\n external: externalDeps,\n banner: {\n js: [\n `var __filename = ${JSON.stringify(path)};`,\n `var __dirname = ${JSON.stringify(dirname(path))};`,\n `globalThis.INTLAYER_FILE_PATH = '${path}';`,\n `globalThis.INTLAYER_BASE_DIR = '${configuration.system.baseDir}';`,\n ].join('\\n'),\n },\n },\n aliases: {\n intlayer: resolvedBundleFilePath,\n },\n });\n\n return dictionary;\n } catch (error) {\n console.error(`Error loading content declaration at ${path}:`, error);\n return undefined;\n }\n};\n\nexport const loadContentDeclarations = async (\n contentDeclarationFilePath: string[],\n configuration: IntlayerConfig,\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: LoadContentDeclarationOptions\n): Promise<Dictionary[]> => {\n const { build, system } = configuration;\n\n // Check for TypeScript warnings before we build\n if (build.checkTypes) {\n logTypeScriptErrors(contentDeclarationFilePath, configuration).catch(\n (e) => {\n console.error('Error during TypeScript validation:', e);\n }\n );\n }\n\n const bundleFilePath = await ensureIntlayerBundle(configuration);\n\n try {\n const dictionariesPromises = contentDeclarationFilePath.map(\n async (path) => {\n const relativePath = relative(system.baseDir, path);\n\n const dictionary = await loadContentDeclaration(\n path,\n configuration,\n bundleFilePath,\n options\n );\n\n return { relativePath, dictionary };\n }\n );\n\n const dictionariesArray = await Promise.all(dictionariesPromises);\n const dictionariesRecord = dictionariesArray.reduce(\n (acc, { relativePath, dictionary }) => {\n if (dictionary) {\n acc[relativePath] = dictionary;\n }\n return acc;\n },\n {} as Record<string, Dictionary>\n );\n\n const contentDeclarations: Dictionary[] = formatLocalDictionaries(\n dictionariesRecord,\n configuration\n ).filter((dictionary) => dictionary.location !== 'remote');\n\n const listFoundDictionaries = contentDeclarations.map((declaration) => ({\n dictionaryKey: declaration.key,\n type: 'local' as const,\n status: 'found' as const,\n }));\n\n onStatusUpdate?.(listFoundDictionaries);\n\n const processedDictionaries = await parallelize(\n contentDeclarations,\n async (contentDeclaration): Promise<Dictionary | undefined> => {\n if (!contentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: contentDeclaration.key,\n type: 'local',\n status: 'building',\n },\n ]);\n\n const processedContentDeclaration = await processContentDeclaration(\n contentDeclaration as Dictionary,\n configuration\n );\n\n if (!processedContentDeclaration) {\n return undefined;\n }\n\n onStatusUpdate?.([\n {\n dictionaryKey: processedContentDeclaration.key,\n type: 'local',\n status: 'built',\n },\n ]);\n\n return processedContentDeclaration;\n }\n );\n\n return filterInvalidDictionaries(processedDictionaries, configuration, {\n checkSchema: false,\n });\n } catch {\n console.error('Error loading content declarations');\n }\n\n return [];\n};\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,2BACX,oBACA,kBAEA,OAAO,QAAQ,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ACT,CACF,CAAC;GAEF,MAAM,8BAA8B,MAAM,0BACxC,oBACA,cACD;AAED,OAAI,CAAC,4BACH;AAGF,oBAAiB,CACf;IACE,eAAe,4BAA4B;IAC3C,MAAM;IACN,QAAQ;IACT,CACF,CAAC;AAEF,UAAO;IAEV,EAEuD,eAAe,EACrE,aAAa,OACd,CAAC;SACI;AACN,UAAQ,MAAM,qCAAqC;;AAGrD,QAAO,EAAE"}
@@ -69,7 +69,7 @@ const prepareIntlayer = async (configuration, options) => {
69
69
  });
70
70
  await writeRemoteDictionary(dictionaries.remoteDictionaries, configuration);
71
71
  await createTypes(Object.values(dictionariesOutput?.mergedDictionaries ?? {}).map((dictionary) => dictionary.dictionary), configuration);
72
- await createDictionaryEntryPoint(configuration);
72
+ await createDictionaryEntryPoint(configuration, { formats: options?.format });
73
73
  const dictionariesBuiltTime = Date.now();
74
74
  appLogger(["Dictionaries built", colorize(`(${dictionariesBuiltTime - preparationStartMs}ms)`, ANSIColors.GREY_DARK)]);
75
75
  await createModuleAugmentation(configuration);
@@ -1 +1 @@
1
- {"version":3,"file":"prepareIntlayer.mjs","names":[],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n env?: 'prod' | 'dev';\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n env: 'dev',\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const resolvedPlugins = await Promise.all(configuration.plugins ?? []);\n const hasPluginLoadDictionaries = resolvedPlugins.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs, env } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n { formats: format, importOtherDictionaries: false, env }\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,MAAM,mCAAmC;CACvC,OAAO;CACP,KAAK;CACL,QAAQ,CAAC,OAAO,MAAM;CACtB,gBAAgB,MAAO,KAAK;CAC7B;AAED,MAAa,kBAAkB,OAC7B,eACA,YACG;CACH,MAAM,YAAY,aAAa,cAAc;CAE7C,MAAM,eAAe,KACnB,cAAc,OAAO,UACrB,yBACD;CAED,MAAM,eAAe,UAAU,eAAe,CAAC,mBAAmB,CAAC;CACnE,MAAM,uBAAuB,MAAM,aAAa,KAAK;CACrD,MAAM,mBAAmB,QACvB,wBAAwB,yBAAyB,YAAY,QAC9D;CAED,MAAM,kBAAkB,MAA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AS,IACrC,cAAc,aAAa,KAAK,mBAAmB,MACnD;GACJ;GACD,CAAC,KAAK,GAAG,GACV,IAAI,yBAAyB,yBAAyB,KAC3D,CAAC,KAAK,GAAG,EACV,WAAW,UACZ,CACF,EACD,EACE,WAAW,MACZ,CACF;EAGD,MAAM,qBAAqB,MAAM,gBAC/B;GACE,GAAG,aAAa;GAChB,GAAG,aAAa;GAChB,GAAG,aAAa;GACjB,EACD,eACA;GAAE,SAAS;GAAQ,yBAAyB;GAAO;GAAK,CACzD;AAID,QAAM,sBACJ,aAAa,oBACb,cACD;AAMD,QAAM,YAJsB,OAAO,OACjC,oBAAoB,sBAAsB,EAAE,CAC7C,CAAC,KAAK,eAAe,WAAW,WAEI,EAAE,cAAc;AAErD,QAAM,2BAA2B,cAAc;EAE/C,MAAM,wBAAwB,KAAK,KAAK;AAExC,YAAU,CACR,sBACA,SACE,IAAI,wBAAwB,mBAAmB,MAC/C,WAAW,UACZ,CACF,CAAC;AAEF,QAAM,yBAAyB,cAAc;AAI7C,YACE,CACE,6BACA,SACE,IAN8B,KAAK,KAMJ,GAAG,sBAAsB,MACxD,WAAW,UACZ,CACF,EACD,EACE,WAAW,MACZ,CACF;AAID,aAAW,MAAM,UAAU,cAAc,WAAW,EAAE,EAAE;GACtD,MAAM,EAAE,sBAAsB,uBAAuB;AAErD,SAAM,OAAO,aAAa;IACxB,cAAc;KACZ;KACA;KACD;IACD;IACD,CAAC;;AAIJ,YACE,CAAC,QAAQ,SAAS,GAFS,KAAK,KAAK,GAAG,mBAEE,KAAK,WAAW,MAAM,CAAC,EACjE;GACE,OAAO;GACP,WAAW;GACZ,CACF;IAEH;EACE;EACA;EACA;EACD,CACF"}
1
+ {"version":3,"file":"prepareIntlayer.mjs","names":[],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n env?: 'prod' | 'dev';\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n env: 'dev',\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const resolvedPlugins = await Promise.all(configuration.plugins ?? []);\n const hasPluginLoadDictionaries = resolvedPlugins.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs, env } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n { formats: format, importOtherDictionaries: false, env }\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration, {\n formats: options?.format,\n });\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":";;;;;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