@intlayer/chokidar 8.7.6-canary.0 → 8.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
  2. package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
  3. package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
  4. package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
  5. package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
  6. package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
  7. package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
  8. package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
  9. package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
  10. package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
  11. package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
  12. package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
  13. package/dist/cjs/createType/createType.cjs.map +1 -1
  14. package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
  15. package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
  16. package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
  17. package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
  18. package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
  19. package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
  20. package/dist/cjs/init/index.cjs.map +1 -1
  21. package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
  22. package/dist/cjs/init/utils/jsonParser.cjs.map +1 -1
  23. package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
  24. package/dist/cjs/initConfig/index.cjs.map +1 -1
  25. package/dist/cjs/installSkills/index.cjs.map +1 -1
  26. package/dist/cjs/listDictionariesPath.cjs.map +1 -1
  27. package/dist/cjs/listGitFiles.cjs.map +1 -1
  28. package/dist/cjs/listProjects.cjs.map +1 -1
  29. package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
  30. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
  31. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  32. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
  33. package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
  34. package/dist/cjs/logConfigDetails.cjs.map +1 -1
  35. package/dist/cjs/prepareIntlayer.cjs.map +1 -1
  36. package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
  37. package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
  38. package/dist/cjs/utils/buildComponentFilesList.cjs.map +1 -1
  39. package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
  40. package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
  41. package/dist/cjs/utils/getContentExtension.cjs.map +1 -1
  42. package/dist/cjs/utils/pLimit.cjs +6 -1
  43. package/dist/cjs/utils/pLimit.cjs.map +1 -1
  44. package/dist/cjs/utils/resolveObjectPromises.cjs.map +1 -1
  45. package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -1
  46. package/dist/cjs/utils/runOnce.cjs.map +1 -1
  47. package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
  48. package/dist/cjs/utils/runParallel/bootstrap.cjs.map +1 -1
  49. package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
  50. package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
  51. package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
  52. package/dist/cjs/watcher.cjs.map +1 -1
  53. package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
  54. package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
  55. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
  56. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  57. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
  58. package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
  59. package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
  60. package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
  61. package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
  62. package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs.map +1 -1
  63. package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
  64. package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
  65. package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs.map +1 -1
  66. package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
  67. package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
  68. package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs.map +1 -1
  69. package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs.map +1 -1
  70. package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
  71. package/dist/esm/createType/createType.mjs.map +1 -1
  72. package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
  73. package/dist/esm/filterInvalidDictionaries.mjs.map +1 -1
  74. package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
  75. package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
  76. package/dist/esm/handleContentDeclarationFileMoved.mjs.map +1 -1
  77. package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
  78. package/dist/esm/init/index.mjs.map +1 -1
  79. package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
  80. package/dist/esm/init/utils/jsonParser.mjs.map +1 -1
  81. package/dist/esm/init/utils/tsConfig.mjs.map +1 -1
  82. package/dist/esm/initConfig/index.mjs.map +1 -1
  83. package/dist/esm/installSkills/index.mjs.map +1 -1
  84. package/dist/esm/listDictionariesPath.mjs.map +1 -1
  85. package/dist/esm/listGitFiles.mjs.map +1 -1
  86. package/dist/esm/listProjects.mjs.map +1 -1
  87. package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
  88. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
  89. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  90. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
  91. package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
  92. package/dist/esm/logConfigDetails.mjs.map +1 -1
  93. package/dist/esm/prepareIntlayer.mjs.map +1 -1
  94. package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
  95. package/dist/esm/utils/autoDecorateContent.mjs.map +1 -1
  96. package/dist/esm/utils/buildComponentFilesList.mjs.map +1 -1
  97. package/dist/esm/utils/buildFilesList.mjs.map +1 -1
  98. package/dist/esm/utils/chunkJSON.mjs.map +1 -1
  99. package/dist/esm/utils/getContentExtension.mjs.map +1 -1
  100. package/dist/esm/utils/pLimit.mjs +6 -1
  101. package/dist/esm/utils/pLimit.mjs.map +1 -1
  102. package/dist/esm/utils/resolveObjectPromises.mjs.map +1 -1
  103. package/dist/esm/utils/resolveRelativePath.mjs.map +1 -1
  104. package/dist/esm/utils/runOnce.mjs.map +1 -1
  105. package/dist/esm/utils/runParallel/bin.mjs.map +1 -1
  106. package/dist/esm/utils/runParallel/bootstrap.mjs.map +1 -1
  107. package/dist/esm/utils/runParallel/index.mjs.map +1 -1
  108. package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
  109. package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
  110. package/dist/esm/watcher.mjs.map +1 -1
  111. package/dist/esm/writeConfiguration/index.mjs.map +1 -1
  112. package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
  113. package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
  114. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  115. package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
  116. package/dist/esm/writeFileIfChanged.mjs.map +1 -1
  117. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"configManipulation.cjs","names":[],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a module is already imported or required.\n */\nconst isModuleImported = (ast: any, moduleName: string): boolean => {\n let found = false;\n recast.visit(ast, {\n visitImportDeclaration(path) {\n if (path.node.source.value === moduleName) {\n found = true;\n }\n return false;\n },\n visitCallExpression(path) {\n const { callee, arguments: args } = path.node;\n\n if (\n n.Identifier.check(callee) &&\n callee.name === 'require' &&\n args[0] &&\n n.StringLiteral.check(args[0]) &&\n args[0].value === moduleName\n ) {\n found = true;\n }\n return false;\n },\n });\n return found;\n};\n\n/**\n * Injects import/require at the top of the file.\n */\nconst injectImport = (\n ast: any,\n isCJS: boolean,\n importName: string,\n source: string\n) => {\n if (isModuleImported(ast, source)) return;\n\n const declaration = isCJS\n ? b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern([\n b.objectProperty.from({\n key: b.identifier(importName),\n value: b.identifier(importName),\n shorthand: true,\n }),\n ]),\n b.callExpression(b.identifier('require'), [b.stringLiteral(source)])\n ),\n ])\n : b.importDeclaration(\n [b.importSpecifier(b.identifier(importName))],\n b.stringLiteral(source)\n );\n\n ast.program.body.unshift(declaration);\n};\n\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile =\n extension === 'cjs' ||\n (content.includes('module.exports') && !content.includes('import '));\n\n injectImport(ast, isCJSFile, 'intlayer', 'vite-intlayer');\n\n const updateConfigObject = (objExpr: any) => {\n if (\n !objExpr ||\n (objExpr.type !== 'ObjectExpression' &&\n !n.ObjectExpression.check(objExpr))\n )\n return;\n\n let pluginsProp = objExpr.properties.find((p: any) => {\n if (!p || !p.key) return false;\n const keyName = p.key.name || p.key.value;\n return keyName === 'plugins';\n }) as any;\n\n if (!pluginsProp) {\n pluginsProp = b.property(\n 'init',\n b.identifier('plugins'),\n b.arrayExpression([])\n );\n objExpr.properties.push(pluginsProp);\n }\n\n const pluginsValue = pluginsProp.value;\n\n if (\n pluginsValue &&\n (pluginsValue.type === 'ArrayExpression' ||\n n.ArrayExpression.check(pluginsValue))\n ) {\n const hasPlugin = pluginsValue.elements.some((el: any) => {\n const callee = el?.callee;\n\n if (!callee) return false;\n const name = callee.name || callee.id?.name;\n return name === 'intlayer' || name === 'il';\n });\n\n if (!hasPlugin) {\n pluginsValue.elements.push(\n b.callExpression(b.identifier('intlayer'), [])\n );\n }\n }\n };\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n\n if (n.ObjectExpression.check(decl)) {\n updateConfigObject(decl);\n } else if (\n n.CallExpression.check(decl) &&\n n.Identifier.check(decl.callee) &&\n decl.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(decl.arguments[0])) {\n updateConfigObject(decl.arguments[0]);\n }\n } else if (n.Identifier.check(decl)) {\n const name = decl.name;\n ast.program.body.forEach((stmt: any) => {\n if (n.VariableDeclaration.check(stmt)) {\n stmt.declarations.forEach((vdecl: any) => {\n if (\n n.VariableDeclarator.check(vdecl) &&\n n.Identifier.check(vdecl.id) &&\n vdecl.id.name === name &&\n n.ObjectExpression.check(vdecl.init)\n ) {\n updateConfigObject(vdecl.init);\n }\n });\n }\n });\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports'\n ) {\n if (n.ObjectExpression.check(right)) {\n updateConfigObject(right);\n } else if (\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(right.arguments[0])) {\n updateConfigObject(right.arguments[0]);\n }\n }\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile = extension === 'cjs' || content.includes('module.exports');\n\n injectImport(ast, isCJSFile, 'withIntlayer', 'next-intlayer/server');\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const declaration = path.node.declaration;\n if (\n n.Expression.check(declaration) &&\n !(\n n.CallExpression.check(declaration) &&\n n.Identifier.check(declaration.callee) &&\n declaration.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('declaration')\n .replace(\n b.callExpression(b.identifier('withIntlayer'), [declaration as any])\n );\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports' &&\n !(\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('right')\n .replace(b.callExpression(b.identifier('withIntlayer'), [right]));\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n"],"mappings":";;;;;;AAEA,MAAM,IAAI,OAAO,MAAM;AACvB,MAAM,IAAI,OAAO,MAAM;;;;AAKvB,MAAM,oBAAoB,KAAU,eAAgC;CAClE,IAAI,QAAQ;AACZ,QAAO,MAAM,KAAK;EAChB,uBAAuB,MAAM;AAC3B,OAAI,KAAK,KAAK,OAAO,UAAU,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AEV,CAAC;AAEF,QAAO,OAAO,MAAM,IAAI,CAAC"}
1
+ {"version":3,"file":"configManipulation.cjs","names":[],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a module is already imported or required.\n */\nconst isModuleImported = (ast: any, moduleName: string): boolean => {\n let found = false;\n recast.visit(ast, {\n visitImportDeclaration(path) {\n if (path.node.source.value === moduleName) {\n found = true;\n }\n return false;\n },\n visitCallExpression(path) {\n const { callee, arguments: args } = path.node;\n\n if (\n n.Identifier.check(callee) &&\n callee.name === 'require' &&\n args[0] &&\n n.StringLiteral.check(args[0]) &&\n args[0].value === moduleName\n ) {\n found = true;\n }\n return false;\n },\n });\n return found;\n};\n\n/**\n * Injects import/require at the top of the file.\n */\nconst injectImport = (\n ast: any,\n isCJS: boolean,\n importName: string,\n source: string\n) => {\n if (isModuleImported(ast, source)) return;\n\n const declaration = isCJS\n ? b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern([\n b.objectProperty.from({\n key: b.identifier(importName),\n value: b.identifier(importName),\n shorthand: true,\n }),\n ]),\n b.callExpression(b.identifier('require'), [b.stringLiteral(source)])\n ),\n ])\n : b.importDeclaration(\n [b.importSpecifier(b.identifier(importName))],\n b.stringLiteral(source)\n );\n\n ast.program.body.unshift(declaration);\n};\n\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile =\n extension === 'cjs' ||\n (content.includes('module.exports') && !content.includes('import '));\n\n injectImport(ast, isCJSFile, 'intlayer', 'vite-intlayer');\n\n const updateConfigObject = (objExpr: any) => {\n if (\n !objExpr ||\n (objExpr.type !== 'ObjectExpression' &&\n !n.ObjectExpression.check(objExpr))\n )\n return;\n\n let pluginsProp = objExpr.properties.find((p: any) => {\n if (!p || !p.key) return false;\n const keyName = p.key.name || p.key.value;\n return keyName === 'plugins';\n }) as any;\n\n if (!pluginsProp) {\n pluginsProp = b.property(\n 'init',\n b.identifier('plugins'),\n b.arrayExpression([])\n );\n objExpr.properties.push(pluginsProp);\n }\n\n const pluginsValue = pluginsProp.value;\n\n if (\n pluginsValue &&\n (pluginsValue.type === 'ArrayExpression' ||\n n.ArrayExpression.check(pluginsValue))\n ) {\n const hasPlugin = pluginsValue.elements.some((el: any) => {\n const callee = el?.callee;\n\n if (!callee) return false;\n const name = callee.name || callee.id?.name;\n return name === 'intlayer' || name === 'il';\n });\n\n if (!hasPlugin) {\n pluginsValue.elements.push(\n b.callExpression(b.identifier('intlayer'), [])\n );\n }\n }\n };\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n\n if (n.ObjectExpression.check(decl)) {\n updateConfigObject(decl);\n } else if (\n n.CallExpression.check(decl) &&\n n.Identifier.check(decl.callee) &&\n decl.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(decl.arguments[0])) {\n updateConfigObject(decl.arguments[0]);\n }\n } else if (n.Identifier.check(decl)) {\n const name = decl.name;\n ast.program.body.forEach((stmt: any) => {\n if (n.VariableDeclaration.check(stmt)) {\n stmt.declarations.forEach((vdecl: any) => {\n if (\n n.VariableDeclarator.check(vdecl) &&\n n.Identifier.check(vdecl.id) &&\n vdecl.id.name === name &&\n n.ObjectExpression.check(vdecl.init)\n ) {\n updateConfigObject(vdecl.init);\n }\n });\n }\n });\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports'\n ) {\n if (n.ObjectExpression.check(right)) {\n updateConfigObject(right);\n } else if (\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(right.arguments[0])) {\n updateConfigObject(right.arguments[0]);\n }\n }\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile = extension === 'cjs' || content.includes('module.exports');\n\n injectImport(ast, isCJSFile, 'withIntlayer', 'next-intlayer/server');\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const declaration = path.node.declaration;\n if (\n n.Expression.check(declaration) &&\n !(\n n.CallExpression.check(declaration) &&\n n.Identifier.check(declaration.callee) &&\n declaration.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('declaration')\n .replace(\n b.callExpression(b.identifier('withIntlayer'), [declaration as any])\n );\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports' &&\n !(\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('right')\n .replace(b.callExpression(b.identifier('withIntlayer'), [right]));\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n"],"mappings":";;;;;;AAEA,MAAM,IAAI,OAAO,MAAM;AACvB,MAAM,IAAI,OAAO,MAAM;;;;AAKvB,MAAM,oBAAoB,KAAU,eAAgC;CAClE,IAAI,QAAQ;AACZ,QAAO,MAAM,KAAK;EAChB,uBAAuB,MAAM;AAC3B,OAAI,KAAK,KAAK,OAAO,UAAU,WAC7B,SAAQ;AAEV,UAAO;;EAET,oBAAoB,MAAM;GACxB,MAAM,EAAE,QAAQ,WAAW,SAAS,KAAK;AAEzC,OACE,EAAE,WAAW,MAAM,OAAO,IAC1B,OAAO,SAAS,aAChB,KAAK,MACL,EAAE,cAAc,MAAM,KAAK,GAAG,IAC9B,KAAK,GAAG,UAAU,WAElB,SAAQ;AAEV,UAAO;;EAEV,CAAC;AACF,QAAO;;;;;AAMT,MAAM,gBACJ,KACA,OACA,YACA,WACG;AACH,KAAI,iBAAiB,KAAK,OAAO,CAAE;CAEnC,MAAM,cA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AAO,MAAM,IAAI,CAAC;;AAG3B,MAAa,oBACX,SACA,cACW;CACX,MAAM,MAAM,OAAO,MAAM,SAAS,EAChC,QAAQ,QAAQ,4BAA4B,EAC7C,CAAC;AAGF,cAAa,KAFK,cAAc,SAAS,QAAQ,SAAS,iBAAiB,EAE9C,gBAAgB,uBAAuB;AAEpE,QAAO,MAAM,KAAK;EAChB,8BAA8B,MAAM;GAClC,MAAM,cAAc,KAAK,KAAK;AAC9B,OACE,EAAE,WAAW,MAAM,YAAY,IAC/B,EACE,EAAE,eAAe,MAAM,YAAY,IACnC,EAAE,WAAW,MAAM,YAAY,OAAO,IACtC,YAAY,OAAO,SAAS,gBAG9B,MACG,IAAI,cAAc,CAClB,QACC,EAAE,eAAe,EAAE,WAAW,eAAe,EAAE,CAAC,YAAmB,CAAC,CACrE;AAEL,UAAO;;EAET,0BAA0B,MAAM;GAC9B,MAAM,EAAE,MAAM,UAAU,KAAK;AAE7B,OACE,EAAE,iBAAiB,MAAM,KAAK,IAC9B,OAAO,MAAM,KAAK,CAAC,SAAS,oBAC5B,EACE,EAAE,eAAe,MAAM,MAAM,IAC7B,EAAE,WAAW,MAAM,MAAM,OAAO,IAChC,MAAM,OAAO,SAAS,gBAGxB,MACG,IAAI,QAAQ,CACZ,QAAQ,EAAE,eAAe,EAAE,WAAW,eAAe,EAAE,CAAC,MAAM,CAAC,CAAC;AAErE,UAAO;;EAEV,CAAC;AAEF,QAAO,OAAO,MAAM,IAAI,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonParser.cjs","names":[],"sources":["../../../../src/init/utils/jsonParser.ts"],"sourcesContent":["/**\n * Helper to parse JSON that may contain comments (tsconfig allows comments)\n */\nexport const parseJSONWithComments = (jsonString: string) => {\n // First, try parsing as-is (most tsconfig files don't have comments)\n try {\n return JSON.parse(jsonString);\n } catch {\n // If that fails, try stripping comments\n // Note: This simple approach removes comments line by line to avoid\n // matching glob patterns like /* and */ that appear in paths\n }\n\n // Process line by line to safely remove comments\n const lines = jsonString.split('\\n');\n const cleanedLines = lines.map((line) => {\n // Track if we're inside a string\n let inString = false;\n let result = '';\n\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n // Handle string boundaries (accounting for escaped quotes)\n if (char === '\"' && (i === 0 || line[i - 1] !== '\\\\')) {\n inString = !inString;\n result += char;\n continue;\n }\n\n // If we're inside a string, keep the character\n if (inString) {\n result += char;\n continue;\n }\n\n // Check for single-line comment outside of strings\n if (char === '/' && nextChar === '/') {\n // Rest of line is a comment, stop here\n break;\n }\n\n // Check for multi-line comment start (/* ... */)\n // For simplicity, we only handle single-line /* */ comments here\n if (char === '/' && nextChar === '*') {\n const endIndex = line.indexOf('*/', i + 2);\n if (endIndex !== -1) {\n // Skip the comment\n i = endIndex + 1;\n continue;\n }\n }\n\n result += char;\n }\n\n return result;\n });\n\n return JSON.parse(cleanedLines.join('\\n'));\n};\n"],"mappings":";;;;;;AAGA,MAAa,yBAAyB,eAAuB;AAE3D,KAAI;AACF,SAAO,KAAK,MAAM,WAAW;SACvB;CAQR,MAAM,eADQ,WAAW,MAAM,KAAK,CACT,KAAK,SAAS;EAEvC,IAAI,WAAW;EACf,IAAI,SAAS;AAEb,OAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,MAAM,OAAO,KAAK;GAClB,MAAM,WAAW,KAAK,IAAI;AAG1B,OAAI,SAAS,SAAQ,MAAM,KAAK,KAAK,IAAI,OAAO,OAAO;AACrD,eAAW,CAAC;AACZ,cAAU;AACV;;AAIF,OAAI,UAAU;AACZ,cAAU;AACV;;AAIF,OAAI,SAAS,OAAO,aAAa,IAE/B;AAKF,OAAI,SAAS,OAAO,aAAa,KAAK;IACpC,MAAM,WAAW,KAAK,QAAQ,MAAM,IAAI,EAAE;AAC1C,QAAI,aAAa,IAAI;AAEnB,SAAI,WAAW;AACf;;;AAIJ,aAAU;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK,MAAM,aAAa,KAAK,KAAK,CAAC"}
1
+ {"version":3,"file":"jsonParser.cjs","names":[],"sources":["../../../../src/init/utils/jsonParser.ts"],"sourcesContent":["/**\n * Helper to parse JSON that may contain comments (tsconfig allows comments)\n */\nexport const parseJSONWithComments = (jsonString: string) => {\n // First, try parsing as-is (most tsconfig files don't have comments)\n try {\n return JSON.parse(jsonString);\n } catch {\n // If that fails, try stripping comments\n // Note: This simple approach removes comments line by line to avoid\n // matching glob patterns like /* and */ that appear in paths\n }\n\n // Process line by line to safely remove comments\n const lines = jsonString.split('\\n');\n const cleanedLines = lines.map((line) => {\n // Track if we're inside a string\n let inString = false;\n let result = '';\n\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n // Handle string boundaries (accounting for escaped quotes)\n if (char === '\"' && (i === 0 || line[i - 1] !== '\\\\')) {\n inString = !inString;\n result += char;\n continue;\n }\n\n // If we're inside a string, keep the character\n if (inString) {\n result += char;\n continue;\n }\n\n // Check for single-line comment outside of strings\n if (char === '/' && nextChar === '/') {\n // Rest of line is a comment, stop here\n break;\n }\n\n // Check for multi-line comment start (/* ... */)\n // For simplicity, we only handle single-line /* */ comments here\n if (char === '/' && nextChar === '*') {\n const endIndex = line.indexOf('*/', i + 2);\n if (endIndex !== -1) {\n // Skip the comment\n i = endIndex + 1;\n continue;\n }\n }\n\n result += char;\n }\n\n return result;\n });\n\n return JSON.parse(cleanedLines.join('\\n'));\n};\n"],"mappings":";;;;;;AAGA,MAAa,yBAAyB,eAAuB;AAE3D,KAAI;AACF,SAAO,KAAK,MAAM,WAAW;SACvB;CAQR,MAAM,eADQ,WAAW,MAAM,KACL,CAAC,KAAK,SAAS;EAEvC,IAAI,WAAW;EACf,IAAI,SAAS;AAEb,OAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,MAAM,OAAO,KAAK;GAClB,MAAM,WAAW,KAAK,IAAI;AAG1B,OAAI,SAAS,SAAQ,MAAM,KAAK,KAAK,IAAI,OAAO,OAAO;AACrD,eAAW,CAAC;AACZ,cAAU;AACV;;AAIF,OAAI,UAAU;AACZ,cAAU;AACV;;AAIF,OAAI,SAAS,OAAO,aAAa,IAE/B;AAKF,OAAI,SAAS,OAAO,aAAa,KAAK;IACpC,MAAM,WAAW,KAAK,QAAQ,MAAM,IAAI,EAAE;AAC1C,QAAI,aAAa,IAAI;AAEnB,SAAI,WAAW;AACf;;;AAIJ,aAAU;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK,MAAM,aAAa,KAAK,KAAK,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"tsConfig.cjs","names":[],"sources":["../../../../src/init/utils/tsConfig.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\n\n/**\n * Helper to find all tsconfig files (tsconfig.json, tsconfig.*.json)\n */\nexport const findTsConfigFiles = async (rootDir: string): Promise<string[]> => {\n try {\n const files = await readdir(rootDir);\n\n return files.filter(\n (file) => file === 'tsconfig.json' || /^tsconfig\\..+\\.json$/.test(file)\n );\n } catch {\n return [];\n }\n};\n"],"mappings":";;;;;;;;AAKA,MAAa,oBAAoB,OAAO,YAAuC;AAC7E,KAAI;AAGF,UAFc,oCAAc,QAAQ,EAEvB,QACV,SAAS,SAAS,mBAAmB,uBAAuB,KAAK,KAAK,CACxE;SACK;AACN,SAAO,EAAE"}
1
+ {"version":3,"file":"tsConfig.cjs","names":[],"sources":["../../../../src/init/utils/tsConfig.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\n\n/**\n * Helper to find all tsconfig files (tsconfig.json, tsconfig.*.json)\n */\nexport const findTsConfigFiles = async (rootDir: string): Promise<string[]> => {\n try {\n const files = await readdir(rootDir);\n\n return files.filter(\n (file) => file === 'tsconfig.json' || /^tsconfig\\..+\\.json$/.test(file)\n );\n } catch {\n return [];\n }\n};\n"],"mappings":";;;;;;;;AAKA,MAAa,oBAAoB,OAAO,YAAuC;AAC7E,KAAI;AAGF,UAAO,oCAFqB,QAAQ,EAEvB,QACV,SAAS,SAAS,mBAAmB,uBAAuB,KAAK,KAAK,CACxE;SACK;AACN,SAAO,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["v","readAsset"],"sources":["../../../src/initConfig/index.ts"],"sourcesContent":["import { writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { colorizePath, logger, v } from '@intlayer/config/logger';\nimport {\n type configurationFilesCandidates,\n searchConfigurationFile,\n} from '@intlayer/config/node';\n\n/**\n * UTILITIES\n */\nconst rootDir = process.cwd();\n\n// Helper to write a file\nconst writeFileToRoot = async (filePath: string, content: string) =>\n await writeFile(join(rootDir, filePath), content, 'utf8');\n\ntype ConfigFormat = 'ts' | 'cjs' | 'mjs' | 'js' | 'json';\n\nconst getTemplatePath = (format: ConfigFormat) => {\n switch (format) {\n case 'ts':\n return './templates/ts.txt';\n case 'cjs':\n return './templates/cjs.txt';\n case 'mjs':\n return './templates/mjs.txt';\n case 'js':\n return './templates/mjs.txt';\n case 'json':\n return './templates/json.txt';\n default:\n return './templates/ts.txt';\n }\n};\n\n/**\n * Initialize the Intlayer configuration file\n */\nexport const initConfig = async (\n format: (typeof configurationFilesCandidates)[number],\n baseDir: string\n) => {\n // Search for configuration file\n const { configurationFilePath } = searchConfigurationFile(baseDir);\n\n // return if the configuration file is found\n if (configurationFilePath) {\n const relativePath = relative(baseDir, configurationFilePath);\n logger(`${v} ${colorizePath(relativePath)} already exists`);\n return;\n }\n\n // Extract the format from the filename (e.g. 'intlayer.config.ts' -> 'ts')\n const extension = format.split('.').pop() as ConfigFormat;\n\n const templatePath = getTemplatePath(extension);\n const configContent = readAsset(templatePath);\n\n await writeFileToRoot(format, configContent);\n logger(`${v} Created ${colorizePath(format)}`);\n};\n"],"mappings":";;;;;;;;;;;;AAYA,MAAM,UAAU,QAAQ,KAAK;AAG7B,MAAM,kBAAkB,OAAO,UAAkB,YAC/C,0DAAqB,SAAS,SAAS,EAAE,SAAS,OAAO;AAI3D,MAAM,mBAAmB,WAAyB;AAChD,SAAQ,QAAR;EACE,KAAK,KACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,KACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;;;;;AAOb,MAAa,aAAa,OACxB,QACA,YACG;CAEH,MAAM,EAAE,6EAAkD,QAAQ;AAGlE,KAAI,uBAAuB;AAEzB,sCAAO,GAAGA,0BAAE,qEADkB,SAAS,sBAAsB,CACpB,CAAC,iBAAiB;AAC3D;;AASF,OAAM,gBAAgB,QAFAC,+BADD,gBAFH,OAAO,MAAM,IAAI,CAAC,KAAK,CAEM,CACF,CAED;AAC5C,qCAAO,GAAGD,0BAAE,qDAAwB,OAAO,GAAG"}
1
+ {"version":3,"file":"index.cjs","names":["v","readAsset"],"sources":["../../../src/initConfig/index.ts"],"sourcesContent":["import { writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { colorizePath, logger, v } from '@intlayer/config/logger';\nimport {\n type configurationFilesCandidates,\n searchConfigurationFile,\n} from '@intlayer/config/node';\n\n/**\n * UTILITIES\n */\nconst rootDir = process.cwd();\n\n// Helper to write a file\nconst writeFileToRoot = async (filePath: string, content: string) =>\n await writeFile(join(rootDir, filePath), content, 'utf8');\n\ntype ConfigFormat = 'ts' | 'cjs' | 'mjs' | 'js' | 'json';\n\nconst getTemplatePath = (format: ConfigFormat) => {\n switch (format) {\n case 'ts':\n return './templates/ts.txt';\n case 'cjs':\n return './templates/cjs.txt';\n case 'mjs':\n return './templates/mjs.txt';\n case 'js':\n return './templates/mjs.txt';\n case 'json':\n return './templates/json.txt';\n default:\n return './templates/ts.txt';\n }\n};\n\n/**\n * Initialize the Intlayer configuration file\n */\nexport const initConfig = async (\n format: (typeof configurationFilesCandidates)[number],\n baseDir: string\n) => {\n // Search for configuration file\n const { configurationFilePath } = searchConfigurationFile(baseDir);\n\n // return if the configuration file is found\n if (configurationFilePath) {\n const relativePath = relative(baseDir, configurationFilePath);\n logger(`${v} ${colorizePath(relativePath)} already exists`);\n return;\n }\n\n // Extract the format from the filename (e.g. 'intlayer.config.ts' -> 'ts')\n const extension = format.split('.').pop() as ConfigFormat;\n\n const templatePath = getTemplatePath(extension);\n const configContent = readAsset(templatePath);\n\n await writeFileToRoot(format, configContent);\n logger(`${v} Created ${colorizePath(format)}`);\n};\n"],"mappings":";;;;;;;;;;;;AAYA,MAAM,UAAU,QAAQ,KAAK;AAG7B,MAAM,kBAAkB,OAAO,UAAkB,YAC/C,0DAAqB,SAAS,SAAS,EAAE,SAAS,OAAO;AAI3D,MAAM,mBAAmB,WAAyB;AAChD,SAAQ,QAAR;EACE,KAAK,KACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,KACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;;;;;AAOb,MAAa,aAAa,OACxB,QACA,YACG;CAEH,MAAM,EAAE,6EAAkD,QAAQ;AAGlE,KAAI,uBAAuB;AAEzB,sCAAO,GAAGA,0BAAE,qEADkB,SAAS,sBACC,CAAC,CAAC,iBAAiB;AAC3D;;AASF,OAAM,gBAAgB,QAFAC,+BADD,gBAFH,OAAO,MAAM,IAAI,CAAC,KAEU,CACF,CAED,CAAC;AAC5C,qCAAO,GAAGD,0BAAE,qDAAwB,OAAO,GAAG"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readAsset","path","fs","v"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Astro: 'Astro-specific usage and getIntlayer',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\nexport const getInitialSkills = (\n deps: Record<string, string>\n): (keyof typeof SKILLS_METADATA)[] => {\n const skills: (keyof typeof SKILLS_METADATA)[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n ];\n\n if (deps.next) skills.push('NextJS');\n if (deps.react || !deps.next) skills.push('React');\n if (deps.preact) skills.push('Preact');\n if (deps['solid-js']) skills.push('Solid');\n if (deps.vue || deps.nuxt) skills.push('Vue');\n if (deps.svelte || deps['@sveltejs/kit']) skills.push('Svelte');\n if (deps.astro) skills.push('Astro');\n\n return skills;\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n return response.text();\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform].dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(\n skillContent.match(/https:\\/\\/intlayer\\.org\\/doc\\/[^\\s)]+\\.md/g) || []\n )\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs.filter((slug) => slug !== 'doc').join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,OAAO;CACP,KAAK;CACL,UACE;CACF,eAAe;CACf,QAAQ;CACR,OAAO;CACP,KAAK;CACL,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OACE;CACF,OAAO;CACR;AAID,MAAa,SAAS,OAAO,KAAK,gBAAgB;AAElD,MAAa,oBACX,SACqC;CACrC,MAAM,SAA2C;EAC/C;EACA;EACA;EACA;EACA;EACD;AAED,KAAI,KAAK,KAAM,QAAO,KAAK,SAAS;AACpC,KAAI,KAAK,SAAS,CAAC,KAAK,KAAM,QAAO,KAAK,QAAQ;AAClD,KAAI,KAAK,OAAQ,QAAO,KAAK,SAAS;AACtC,KAAI,KAAK,YAAa,QAAO,KAAK,QAAQ;AAC1C,KAAI,KAAK,OAAO,KAAK,KAAM,QAAO,KAAK,MAAM;AAC7C,KAAI,KAAK,UAAU,KAAK,iBAAkB,QAAO,KAAK,SAAS;AAC/D,KAAI,KAAK,MAAO,QAAO,KAAK,QAAQ;AAEpC,QAAO;;;;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EhC;EAEF,MAAM,UAAU,MAAM,QAAQ,IAAI,iBAAiB;AAGnD,OAAK,MAAM,OAAO,QAChB,KAAI,IAAI,WAAW,IAAI,YAAY,IAAI,WAAW,IAAI,cAAc;AAElE,SAAMC,iBAAG,UACPD,kBAAK,KAAK,cAAc,IAAI,SAAS,EACrC,IAAI,SACJ,QACD;AAGD,yBAAsB,oBAAoB,WACxC,IAAI,KACJ,IAAI,aACL;;EAKL,MAAM,WAAWA,kBAAK,KAAK,UAAU,WAAW;AAChD,QAAMC,iBAAG,UAAU,UAAU,qBAAqB,QAAQ;AAC1D,gBAAc,KAAK,GAAG,UAAU,WAAW;;AAG7C,KAAI,cAAc,WAAW,EAC3B,QAAO;AAGT,QAAO,GAAGC,0BAAE,WAAW,cAAc,OAAO,aAAa"}
1
+ {"version":3,"file":"index.cjs","names":["readAsset","path","fs","v"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Astro: 'Astro-specific usage and getIntlayer',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\nexport const getInitialSkills = (\n deps: Record<string, string>\n): (keyof typeof SKILLS_METADATA)[] => {\n const skills: (keyof typeof SKILLS_METADATA)[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n ];\n\n if (deps.next) skills.push('NextJS');\n if (deps.react || !deps.next) skills.push('React');\n if (deps.preact) skills.push('Preact');\n if (deps['solid-js']) skills.push('Solid');\n if (deps.vue || deps.nuxt) skills.push('Vue');\n if (deps.svelte || deps['@sveltejs/kit']) skills.push('Svelte');\n if (deps.astro) skills.push('Astro');\n\n return skills;\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n return response.text();\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform].dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(\n skillContent.match(/https:\\/\\/intlayer\\.org\\/doc\\/[^\\s)]+\\.md/g) || []\n )\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs.filter((slug) => slug !== 'doc').join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,OAAO;CACP,KAAK;CACL,UACE;CACF,eAAe;CACf,QAAQ;CACR,OAAO;CACP,KAAK;CACL,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OACE;CACF,OAAO;CACR;AAID,MAAa,SAAS,OAAO,KAAK,gBAAgB;AAElD,MAAa,oBACX,SACqC;CACrC,MAAM,SAA2C;EAC/C;EACA;EACA;EACA;EACA;EACD;AAED,KAAI,KAAK,KAAM,QAAO,KAAK,SAAS;AACpC,KAAI,KAAK,SAAS,CAAC,KAAK,KAAM,QAAO,KAAK,QAAQ;AAClD,KAAI,KAAK,OAAQ,QAAO,KAAK,SAAS;AACtC,KAAI,KAAK,YAAa,QAAO,KAAK,QAAQ;AAC1C,KAAI,KAAK,OAAO,KAAK,KAAM,QAAO,KAAK,MAAM;AAC7C,KAAI,KAAK,UAAU,KAAK,iBAAkB,QAAO,KAAK,SAAS;AAC/D,KAAI,KAAK,MAAO,QAAO,KAAK,QAAQ;AAEpC,QAAO;;;;;AAYT,MAAa,qBAAuD;CAClE,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,WAAW,UAAU,QAAQ,IAAI,iBAAiB;EACjE;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,aAAa,UACzB,QAAQ,IAAI,iBAAiB;EAChC;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,SAAS,UAAU,QAAQ,IAAI,iBAAiB;EAC/D;CACD,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aAAa,QAAQ,IAAI,YAAY;EACtC;CACD,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,WAAW,UAAU,QAAQ,IAAI,iBAAiB;EACjE;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACL,aAAa,QAAQ,IAAI,aAAa;EACvC;CACD,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aAAa,QAAQ,IAAI,WAAW;EACrC;CACD,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,mBAAmB,UAAU,CAAC,CAAC,QAAQ,IAAI;EAC1D;CACD,aAAa;EACX,OAAO;EACP,KAAK;EACN;CACD,SAAS;EACP,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,WAAW;EACT,OAAO;EACP,KAAK;EACN;CACD,aAAa;EACX,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACN;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACN;CACD,QAAQ;EACN,OAAO;EACP,KAAK;EACN;CACD,aAAa;EACX,OAAO;EACP,KAAK;EACN;CACD,KAAK;EACH,OAAO;EACP,KAAK;EACN;CACD,WAAW;EACT,OAAO;EACP,KAAK;EACN;CACD,IAAI;EACF,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACN;CACD,SAAS;EACP,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,SAAS;EACP,OAAO;EACP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Ac,WAAW,EAC3B,QAAO;AAGT,QAAO,GAAGC,0BAAE,WAAW,cAAc,OAAO,aAAa"}
@@ -1 +1 @@
1
- {"version":3,"file":"listDictionariesPath.cjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const { fileExtensions, contentDir, excludedPath } = configuration.content;\n\n const watchedFilesPatternWithPath = fileExtensions.flatMap((ext) =>\n contentDir.map((dir) =>\n `${normalizePath(dir)}/**/*${ext}`.replace('//', '/')\n )\n );\n\n const filePromises = watchedFilesPatternWithPath.map(async (pattern) => {\n // Identify the static part of the path (before any wildcards like *)\n // e.g. \"/Users/.../design-system/dist/esm/**/*.content.ts\" -> \"/Users/.../design-system/dist/esm/\"\n const magicIndex = pattern.search(/[*?{}(]/);\n const basePattern =\n magicIndex > -1 ? pattern.slice(0, magicIndex) : pattern;\n\n // Filter the global ignored list for this specific pattern\n const applicableIgnore = excludedPath.filter((excludePattern) => {\n // Heuristic: Extract the key directory name from the glob\n // e.g. \"**/dist/**\" -> \"dist\", \"**/node_modules/**\" -> \"node_modules\"\n const cleanName = excludePattern.replace(/\\*\\*/g, '').replace(/\\//g, '');\n\n // If the explicit base path contains the excluded directory (e.g. \".../dist/...\"),\n // we assume you explicitly want it, so we REMOVE it from the ignore list.\n // We check for `/${cleanName}/` to ensure we match whole folder names.\n if (cleanName && basePattern.includes(`/${cleanName}/`)) {\n return false; // Drop this exclude rule\n }\n\n return true; // Keep this exclude rule\n });\n\n // Run fast-glob with the customized ignore list\n return fg(pattern, {\n ignore: applicableIgnore,\n absolute: true,\n dot: true,\n });\n });\n\n const filesArrays = await Promise.all(filePromises);\n\n // Flatten and deduplicate\n const uniqueFiles = Array.from(new Set(filesArrays.flat()));\n\n return uniqueFiles;\n};\n\nexport const listDictionariesWithStats = async (\n configuration: IntlayerConfig\n) => {\n const files = await listDictionaries(configuration);\n\n return Promise.all(\n files.map(async (file) => ({ path: file, stats: await stat(file) }))\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAa,mBAAmB,OAC9B,kBACsB;CACtB,MAAM,EAAE,gBAAgB,YAAY,iBAAiB,cAAc;CAQnE,MAAM,eAN8B,eAAe,SAAS,QAC1D,WAAW,KAAK,QACd,6CAAiB,IAAI,CAAC,OAAO,MAAM,QAAQ,MAAM,IAAI,CACtD,CACF,CAEgD,IAAI,OAAO,YAAY;EAGtE,MAAM,aAAa,QAAQ,OAAO,UAAU;EAC5C,MAAM,cACJ,aAAa,KAAK,QAAQ,MAAM,GAAG,WAAW,GAAG;AAmBnD,gCAAU,SAAS;GACjB,QAjBuB,aAAa,QAAQ,mBAAmB;IAG/D,MAAM,YAAY,eAAe,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;AAKxE,QAAI,aAAa,YAAY,SAAS,IAAI,UAAU,GAAG,CACrD,QAAO;AAGT,WAAO;KACP;GAKA,UAAU;GACV,KAAK;GACN,CAAC;GACF;CAEF,MAAM,cAAc,MAAM,QAAQ,IAAI,aAAa;AAKnD,QAFoB,MAAM,KAAK,IAAI,IAAI,YAAY,MAAM,CAAC,CAAC;;AAK7D,MAAa,4BAA4B,OACvC,kBACG;CACH,MAAM,QAAQ,MAAM,iBAAiB,cAAc;AAEnD,QAAO,QAAQ,IACb,MAAM,IAAI,OAAO,UAAU;EAAE,MAAM;EAAM,OAAO,iCAAW,KAAK;EAAE,EAAE,CACrE"}
1
+ {"version":3,"file":"listDictionariesPath.cjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const { fileExtensions, contentDir, excludedPath } = configuration.content;\n\n const watchedFilesPatternWithPath = fileExtensions.flatMap((ext) =>\n contentDir.map((dir) =>\n `${normalizePath(dir)}/**/*${ext}`.replace('//', '/')\n )\n );\n\n const filePromises = watchedFilesPatternWithPath.map(async (pattern) => {\n // Identify the static part of the path (before any wildcards like *)\n // e.g. \"/Users/.../design-system/dist/esm/**/*.content.ts\" -> \"/Users/.../design-system/dist/esm/\"\n const magicIndex = pattern.search(/[*?{}(]/);\n const basePattern =\n magicIndex > -1 ? pattern.slice(0, magicIndex) : pattern;\n\n // Filter the global ignored list for this specific pattern\n const applicableIgnore = excludedPath.filter((excludePattern) => {\n // Heuristic: Extract the key directory name from the glob\n // e.g. \"**/dist/**\" -> \"dist\", \"**/node_modules/**\" -> \"node_modules\"\n const cleanName = excludePattern.replace(/\\*\\*/g, '').replace(/\\//g, '');\n\n // If the explicit base path contains the excluded directory (e.g. \".../dist/...\"),\n // we assume you explicitly want it, so we REMOVE it from the ignore list.\n // We check for `/${cleanName}/` to ensure we match whole folder names.\n if (cleanName && basePattern.includes(`/${cleanName}/`)) {\n return false; // Drop this exclude rule\n }\n\n return true; // Keep this exclude rule\n });\n\n // Run fast-glob with the customized ignore list\n return fg(pattern, {\n ignore: applicableIgnore,\n absolute: true,\n dot: true,\n });\n });\n\n const filesArrays = await Promise.all(filePromises);\n\n // Flatten and deduplicate\n const uniqueFiles = Array.from(new Set(filesArrays.flat()));\n\n return uniqueFiles;\n};\n\nexport const listDictionariesWithStats = async (\n configuration: IntlayerConfig\n) => {\n const files = await listDictionaries(configuration);\n\n return Promise.all(\n files.map(async (file) => ({ path: file, stats: await stat(file) }))\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAa,mBAAmB,OAC9B,kBACsB;CACtB,MAAM,EAAE,gBAAgB,YAAY,iBAAiB,cAAc;CAQnE,MAAM,eAN8B,eAAe,SAAS,QAC1D,WAAW,KAAK,QACd,6CAAiB,IAAI,CAAC,OAAO,MAAM,QAAQ,MAAM,IAAI,CACtD,CAG6C,CAAC,IAAI,OAAO,YAAY;EAGtE,MAAM,aAAa,QAAQ,OAAO,UAAU;EAC5C,MAAM,cACJ,aAAa,KAAK,QAAQ,MAAM,GAAG,WAAW,GAAG;AAmBnD,gCAAU,SAAS;GACjB,QAjBuB,aAAa,QAAQ,mBAAmB;IAG/D,MAAM,YAAY,eAAe,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;AAKxE,QAAI,aAAa,YAAY,SAAS,IAAI,UAAU,GAAG,CACrD,QAAO;AAGT,WAAO;KAKiB;GACxB,UAAU;GACV,KAAK;GACN,CAAC;GACF;CAEF,MAAM,cAAc,MAAM,QAAQ,IAAI,aAAa;AAKnD,QAFoB,MAAM,KAAK,IAAI,IAAI,YAAY,MAAM,CAAC,CAExC;;AAGpB,MAAa,4BAA4B,OACvC,kBACG;CACH,MAAM,QAAQ,MAAM,iBAAiB,cAAc;AAEnD,QAAO,QAAQ,IACb,MAAM,IAAI,OAAO,UAAU;EAAE,MAAM;EAAM,OAAO,iCAAW,KAAK;EAAE,EAAE,CACrE"}
@@ -1 +1 @@
1
- {"version":3,"file":"listGitFiles.cjs","names":[],"sources":["../../src/listGitFiles.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { log } from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport simpleGit from 'simple-git';\n\nexport type DiffMode = 'gitDiff' | 'uncommitted' | 'unpushed' | 'untracked';\n\nconst getGitRootDir = async (): Promise<string | null> => {\n try {\n const git = simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (error) {\n const appLogger = getAppLogger({ log });\n appLogger(`Error getting git root directory: ${error}`, {\n level: 'error',\n });\n return null;\n }\n};\n\nexport type ListGitFilesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n absolute?: boolean;\n};\n\nexport const listGitFiles = async ({\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n absolute = true,\n}: ListGitFilesOptions) => {\n try {\n const git = simpleGit();\n const diff: Set<string> = new Set();\n\n if (mode.includes('untracked')) {\n const status = await git.status();\n status.not_added.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('uncommitted')) {\n // Get uncommitted changes\n const uncommittedDiff = await git.diff(['--name-only', 'HEAD']);\n\n const uncommittedFiles = uncommittedDiff.split('\\n').filter(Boolean);\n\n uncommittedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('unpushed')) {\n // Get unpushed commits\n const unpushedDiff = await git.diff(['--name-only', '@{push}...HEAD']);\n\n const unpushedFiles = unpushedDiff.split('\\n').filter(Boolean);\n\n unpushedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('gitDiff')) {\n // Get the base branch (usually main/master) from CI environment\n\n await git.fetch(baseRef);\n\n const diffBranch = await git.diff([\n '--name-only',\n `${baseRef}...${currentRef}`,\n ]);\n\n const gitDiffFiles = diffBranch.split('\\n').filter(Boolean);\n\n gitDiffFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (absolute) {\n const gitRootDir = await getGitRootDir();\n if (!gitRootDir) {\n return [];\n }\n return Array.from(diff).map((file) => join(gitRootDir, file));\n }\n\n return Array.from(diff);\n } catch (error) {\n console.warn('Failed to get changes list:', error);\n }\n};\n\nexport type ListGitLinesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n};\n\nexport const listGitLines = async (\n filePath: string,\n {\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n }: ListGitLinesOptions\n): Promise<number[]> => {\n const git = simpleGit();\n // We collect **line numbers** (1-based) that were modified/added by the diff.\n // Using a Set ensures uniqueness when the same line is reported by several modes.\n const changedLines: Set<number> = new Set();\n\n /**\n * Extracts line numbers from a diff generated with `--unified=0`.\n * Each hunk header looks like: @@ -<oldStart>,<oldCount> +<newStart>,<newCount> @@\n * We consider both the \"+\" (new) side for additions and the \"-\" (old) side for deletions.\n * For deletions, we add the line before and after the deletion point in the current file.\n */\n const collectLinesFromDiff = (diffOutput: string) => {\n const hunkRegex = /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/g;\n let match: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: Used in while loop condition\n while ((match = hunkRegex.exec(diffOutput)) !== null) {\n const oldCount = match[2] ? Number(match[2]) : 1;\n const newStart = Number(match[3]);\n const newCount = match[4] ? Number(match[4]) : 1;\n\n // Handle additions/modifications (+ side)\n if (newCount > 0) {\n for (let i = 0; i < newCount; i++) {\n changedLines.add(newStart + i);\n }\n }\n\n // Handle deletions (- side)\n if (oldCount > 0 && newCount === 0) {\n // For deletions, add the line before and after the deletion point\n // The deletion point in the new file is at newStart\n if (newStart > 1) {\n changedLines.add(newStart - 1); // Line before deletion\n }\n changedLines.add(newStart); // Line after deletion (if it exists)\n }\n }\n };\n\n // 1. Handle untracked files – when a file is untracked its entire content is new.\n if (mode.includes('untracked')) {\n const status = await git.status();\n const isUntracked = status.not_added.includes(filePath);\n if (isUntracked) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n content.split('\\n').forEach((_, idx) => {\n changedLines.add(idx + 1);\n });\n } catch {\n // ignore read errors – file may have been deleted, etc.\n }\n }\n }\n\n // 2. Uncommitted changes (working tree vs HEAD)\n if (mode.includes('uncommitted')) {\n const diffOutput = await git.diff(['--unified=0', 'HEAD', '--', filePath]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 3. Unpushed commits – compare local branch to its upstream\n if (mode.includes('unpushed')) {\n const diffOutput = await git.diff([\n '--unified=0',\n '@{push}...HEAD',\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 4. Regular git diff between baseRef and currentRef (e.g., CI pull-request diff)\n if (mode.includes('gitDiff')) {\n await git.fetch(baseRef);\n const diffOutput = await git.diff([\n '--unified=0',\n `${baseRef}...${currentRef}`,\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // Return the list sorted for convenience\n return Array.from(changedLines).sort((a, b) => a - b);\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAM,gBAAgB,YAAoC;AACxD,KAAI;AAGF,UADgB,+BADO,CACG,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,OAAO;AAEd,4CAD+B,EAAE,iCAAK,CAAC,CAC7B,qCAAqC,SAAS,EACtD,OAAO,SACR,CAAC;AACF,SAAO;;;AAWX,MAAa,eAAe,OAAO,EACjC,MACA,UAAU,eACV,aAAa,QACb,WAAW,WACc;AACzB,KAAI;EACF,MAAM,+BAAiB;EACvB,MAAM,uBAAoB,IAAI,KAAK;AAEnC,MAAI,KAAK,SAAS,YAAY,CAE5B,EADe,MAAM,IAAI,QAAQ,EAC1B,UAAU,SAAS,SAAS;AACjC,QAAK,IAAI,KAAK;IACd;AAGJ,MAAI,KAAK,SAAS,cAAc,CAM9B,EAJwB,MAAM,IAAI,KAAK,CAAC,eAAe,OAAO,CAAC,EAEtB,MAAM,KAAK,CAAC,OAAO,QAAQ,CAEnD,SAAS,SAAS;AACjC,QAAK,IAAI,KAAK;IACd;AAGJ,MAAI,KAAK,SAAS,WAAW,CAM3B,EAJqB,MAAM,IAAI,KAAK,CAAC,eAAe,iBAAiB,CAAC,EAEnC,MAAM,KAAK,CAAC,OAAO,QAAQ,CAEhD,SAAS,SAAS;AAC9B,QAAK,IAAI,KAAK;IACd;AAGJ,MAAI,KAAK,SAAS,UAAU,EAAE;AAG5B,SAAM,IAAI,MAAM,QAAQ;AASxB,IAPmB,MAAM,IAAI,KAAK,CAChC,eACA,GAAG,QAAQ,KAAK,aAC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,CAC1C;AAIlC,KAAI,KAAK,SAAS,WAAW,CAO3B,sBANmB,MAAM,IAAI,KAAK;EAChC;EACA;EACA;EACA;EACD,CAAC,CAC8B;AAIlC,KAAI,KAAK,SAAS,UAAU,EAAE;AAC5B,QAAM,IAAI,MAAM,QAAQ;AAOxB,uBANmB,MAAM,IAAI,KAAK;GAChC;GACA,GAAG,QAAQ,KAAK;GAChB;GACA;GACD,CAAC,CAC8B;;AAIlC,QAAO,MAAM,KAAK,aAAa,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE"}
1
+ {"version":3,"file":"listGitFiles.cjs","names":[],"sources":["../../src/listGitFiles.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { log } from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport simpleGit from 'simple-git';\n\nexport type DiffMode = 'gitDiff' | 'uncommitted' | 'unpushed' | 'untracked';\n\nconst getGitRootDir = async (): Promise<string | null> => {\n try {\n const git = simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (error) {\n const appLogger = getAppLogger({ log });\n appLogger(`Error getting git root directory: ${error}`, {\n level: 'error',\n });\n return null;\n }\n};\n\nexport type ListGitFilesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n absolute?: boolean;\n};\n\nexport const listGitFiles = async ({\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n absolute = true,\n}: ListGitFilesOptions) => {\n try {\n const git = simpleGit();\n const diff: Set<string> = new Set();\n\n if (mode.includes('untracked')) {\n const status = await git.status();\n status.not_added.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('uncommitted')) {\n // Get uncommitted changes\n const uncommittedDiff = await git.diff(['--name-only', 'HEAD']);\n\n const uncommittedFiles = uncommittedDiff.split('\\n').filter(Boolean);\n\n uncommittedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('unpushed')) {\n // Get unpushed commits\n const unpushedDiff = await git.diff(['--name-only', '@{push}...HEAD']);\n\n const unpushedFiles = unpushedDiff.split('\\n').filter(Boolean);\n\n unpushedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('gitDiff')) {\n // Get the base branch (usually main/master) from CI environment\n\n await git.fetch(baseRef);\n\n const diffBranch = await git.diff([\n '--name-only',\n `${baseRef}...${currentRef}`,\n ]);\n\n const gitDiffFiles = diffBranch.split('\\n').filter(Boolean);\n\n gitDiffFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (absolute) {\n const gitRootDir = await getGitRootDir();\n if (!gitRootDir) {\n return [];\n }\n return Array.from(diff).map((file) => join(gitRootDir, file));\n }\n\n return Array.from(diff);\n } catch (error) {\n console.warn('Failed to get changes list:', error);\n }\n};\n\nexport type ListGitLinesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n};\n\nexport const listGitLines = async (\n filePath: string,\n {\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n }: ListGitLinesOptions\n): Promise<number[]> => {\n const git = simpleGit();\n // We collect **line numbers** (1-based) that were modified/added by the diff.\n // Using a Set ensures uniqueness when the same line is reported by several modes.\n const changedLines: Set<number> = new Set();\n\n /**\n * Extracts line numbers from a diff generated with `--unified=0`.\n * Each hunk header looks like: @@ -<oldStart>,<oldCount> +<newStart>,<newCount> @@\n * We consider both the \"+\" (new) side for additions and the \"-\" (old) side for deletions.\n * For deletions, we add the line before and after the deletion point in the current file.\n */\n const collectLinesFromDiff = (diffOutput: string) => {\n const hunkRegex = /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/g;\n let match: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: Used in while loop condition\n while ((match = hunkRegex.exec(diffOutput)) !== null) {\n const oldCount = match[2] ? Number(match[2]) : 1;\n const newStart = Number(match[3]);\n const newCount = match[4] ? Number(match[4]) : 1;\n\n // Handle additions/modifications (+ side)\n if (newCount > 0) {\n for (let i = 0; i < newCount; i++) {\n changedLines.add(newStart + i);\n }\n }\n\n // Handle deletions (- side)\n if (oldCount > 0 && newCount === 0) {\n // For deletions, add the line before and after the deletion point\n // The deletion point in the new file is at newStart\n if (newStart > 1) {\n changedLines.add(newStart - 1); // Line before deletion\n }\n changedLines.add(newStart); // Line after deletion (if it exists)\n }\n }\n };\n\n // 1. Handle untracked files – when a file is untracked its entire content is new.\n if (mode.includes('untracked')) {\n const status = await git.status();\n const isUntracked = status.not_added.includes(filePath);\n if (isUntracked) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n content.split('\\n').forEach((_, idx) => {\n changedLines.add(idx + 1);\n });\n } catch {\n // ignore read errors – file may have been deleted, etc.\n }\n }\n }\n\n // 2. Uncommitted changes (working tree vs HEAD)\n if (mode.includes('uncommitted')) {\n const diffOutput = await git.diff(['--unified=0', 'HEAD', '--', filePath]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 3. Unpushed commits – compare local branch to its upstream\n if (mode.includes('unpushed')) {\n const diffOutput = await git.diff([\n '--unified=0',\n '@{push}...HEAD',\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 4. Regular git diff between baseRef and currentRef (e.g., CI pull-request diff)\n if (mode.includes('gitDiff')) {\n await git.fetch(baseRef);\n const diffOutput = await git.diff([\n '--unified=0',\n `${baseRef}...${currentRef}`,\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // Return the list sorted for convenience\n return Array.from(changedLines).sort((a, b) => a - b);\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAM,gBAAgB,YAAoC;AACxD,KAAI;AAGF,UAAO,+BADkB,CAAC,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,OAAO;AAEd,4CAD+B,EAAE,iCAAK,CAC7B,CAAC,qCAAqC,SAAS,EACtD,OAAO,SACR,CAAC;AACF,SAAO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AClB,IAAI;AAGJ,UAAQ,QAAQ,UAAU,KAAK,WAAW,MAAM,MAAM;GACpD,MAAM,WAAW,MAAM,KAAK,OAAO,MAAM,GAAG,GAAG;GAC/C,MAAM,WAAW,OAAO,MAAM,GAAG;GACjC,MAAM,WAAW,MAAM,KAAK,OAAO,MAAM,GAAG,GAAG;AAG/C,OAAI,WAAW,EACb,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,IAC5B,cAAa,IAAI,WAAW,EAAE;AAKlC,OAAI,WAAW,KAAK,aAAa,GAAG;AAGlC,QAAI,WAAW,EACb,cAAa,IAAI,WAAW,EAAE;AAEhC,iBAAa,IAAI,SAAS;;;;AAMhC,KAAI,KAAK,SAAS,YAAY,EAG5B;OADoB,MADC,IAAI,QAAQ,EACN,UAAU,SAAS,SAC/B,CACb,KAAI;AAEF,6BAD6B,UAAU,QAChC,CAAC,MAAM,KAAK,CAAC,SAAS,GAAG,QAAQ;AACtC,iBAAa,IAAI,MAAM,EAAE;KACzB;UACI;;AAOZ,KAAI,KAAK,SAAS,cAAc,CAE9B,sBAAqB,MADI,IAAI,KAAK;EAAC;EAAe;EAAQ;EAAM;EAAS,CAAC,CAC1C;AAIlC,KAAI,KAAK,SAAS,WAAW,CAO3B,sBAAqB,MANI,IAAI,KAAK;EAChC;EACA;EACA;EACA;EACD,CAAC,CAC8B;AAIlC,KAAI,KAAK,SAAS,UAAU,EAAE;AAC5B,QAAM,IAAI,MAAM,QAAQ;AAOxB,uBAAqB,MANI,IAAI,KAAK;GAChC;GACA,GAAG,QAAQ,KAAK;GAChB;GACA;GACD,CAAC,CAC8B;;AAIlC,QAAO,MAAM,KAAK,aAAa,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"listProjects.cjs","names":["configurationFilesCandidates"],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport simpleGit from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Get the git root directory\n */\nconst getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;;;;;AAqBA,MAAM,gBAAgB,OAAO,QAAyC;AACpE,KAAI;AAGF,UADgB,OADJ,8BAAgB,IAAI,4BAAc,EACpB,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,QAAQ;AACf,SAAO;;;;;;;;;AAUX,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,KAAK;AAGjD,KAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,UAAU;AACjD,MAAI,WACF,aAAY;;CAUhB,MAAM,cAAc,6BALGA,mDAA6B,KACjD,aAAa,MAAM,WACrB,EAG4C;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,aAAa;EAC5C,KAAK;EACN,CAAC;CAGF,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,gCAAiB,KAAK,CAAC,CAAC,CAAC;AAG1E,QAAO;EAAE;EAAW,cAAc,YAAY,MAAM;EAAE"}
1
+ {"version":3,"file":"listProjects.cjs","names":["configurationFilesCandidates"],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport simpleGit from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Get the git root directory\n */\nconst getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;;;;;AAqBA,MAAM,gBAAgB,OAAO,QAAyC;AACpE,KAAI;AAGF,UAAO,OAFK,8BAAgB,IAAI,4BAAc,EACpB,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,QAAQ;AACf,SAAO;;;;;;;;;AAUX,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,KAAK;AAGjD,KAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,UAAU;AACjD,MAAI,WACF,aAAY;;CAUhB,MAAM,cAAc,6BALGA,mDAA6B,KACjD,aAAa,MAAM,WAIqB,EAAE;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,aAAa;EAC5C,KAAK;EACN,CAAC;CAGF,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,gCAAiB,KAAK,CAAC,CAAC,CAAC;AAG1E,QAAO;EAAE;EAAW,cAAc,YAAY,MAAM;EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"getIntlayerBundle.cjs","names":["builtinModules"],"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,KAAK;MAGjD,UAAU;MACX;YACK;AACN,YAAO;;AAIX,WAAO;KACP;;EAEL;;AAGH,MAAa,oBAAoB,OAAO,kBAAkC;CACxE,MAAM,4DAAgC,cAAc,OAAO,QAAQ;CAOnE,MAAM,UAAU,EACd,8CALA,cAAc,OAAO,WACrB,oBACD,EAIA;CAED,MAAM,WAAW,YAAY,QAAQ,WAAW;AAgBhD,QAbe,4CAFF,qCAAe,UAAU,QAAQ,EAER,UAAU;EAC9C,QAAQ;EACR,UAAU;EACV,UAAU;GACR,GAAGA;GACH,GAAGA,2BAAe,KAAK,QAAQ,QAAQ,MAAM;GAC7C;GACA;GACD;EACD,QAAQ;EACR,SAAS,CAAC,mBAAmB,SAAS,YAAY,CAAC;EACpD,CAAC,IAEe"}
1
+ {"version":3,"file":"getIntlayerBundle.cjs","names":["builtinModules"],"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,4DAAgC,cAAc,OAAO,QAAQ;CAOnE,MAAM,UAAU,EACd,8CALA,cAAc,OAAO,WACrB,oBAI2C,EAC5C;CAED,MAAM,WAAW,YAAY,QAAQ,WAAW;AAgBhD,QAAO,4CAbyB,qCAFJ,UAAU,QAAQ,EAER,UAAU;EAC9C,QAAQ;EACR,UAAU;EACV,UAAU;GACR,GAAGA;GACH,GAAGA,2BAAe,KAAK,QAAQ,QAAQ,MAAM;GAC7C;GACA;GACD;EACD,QAAQ;EACR,SAAS,CAAC,mBAAmB,SAAS,YAAY,CAAC;EACpD,CAAC,IAEe"}
@@ -1 +1 @@
1
- {"version":3,"file":"loadContentDeclaration.cjs","names":["getIntlayerBundle","filterInvalidDictionaries","parallelize","processContentDeclaration"],"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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SACI;AACN,UAAQ,MAAM,qCAAqC;;AAGrD,QAAO,EAAE"}
1
+ {"version":3,"file":"loadContentDeclaration.cjs","names":["getIntlayerBundle","filterInvalidDictionaries","parallelize","processContentDeclaration"],"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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BACH;AAGF,oBAAiB,CACf;IACE,eAAe,mBAAmB;IAClC,MAAM;IACN,QAAQ;IACT,CACF,CAAC;GAEF,MAAM,8BAA8B,MAAMC,oFACxC,oBACA,cACD;AAED,OAAI,CAAC,4BACH;AAGF,oBAAiB,CACf;IACE,eAAe,4BAA4B;IAC3C,MAAM;IACN,QAAQ;IACT,CACF,CAAC;AAEF,UAAO;IAEV,EAEuD,eAAe,EACrE,aAAa,OACd,CAAC;SACI;AACN,UAAQ,MAAM,qCAAqC;;AAGrD,QAAO,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;AA8BA,IAAI,yBAA+C,EAAE;AACrD,MAAM,SAAS,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yBAAyB;GAC9C;EACF"}
1
+ {"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;AA8BA,IAAI,yBAA+C,EAAE;AACrD,MAAM,SAAS,IAAIA,iDAAoB;AAEvC,MAAM,6BAA6B,aAAmC;CACpE,MAAM,UAAgC,CAAC,GAAG,uBAAuB;AAEjE,MAAK,MAAM,YAAY,UAAU;EAC/B,MAAM,QAAQ,QAAQ,WACnB,MACC,EAAE,kBAAkB,SAAS,iBAAiB,EAAE,SAAS,SAAS,KACrE;AACD,MAAI,SAAS,EACX,SAAQ,SAAS;MAEjB,SAAQ,KAAK,SAAS;;AAI1B,0BAAyB;AACzB,QAAO,OAAO,SAAS;AAEvB,QAAO;;AAQT,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mB,OAAO;CAE/C,MAAM,yBAAyB,KAAK,KAAK;CAMzC,MAAM,oBAAkC,MAAMC,wEAJhC,MAAM,QAAQ,yBAAyB,GACjD,2BACA,CAAC,yBAAyB,EAI5B,eACA,0BACD,CACE,MAAM,iBACLF,4DAA0B,cAAc,cAAc,CACvD,CACA,MAAM,iBAAiBC,4CAAmB,aAAa,CAAC;CAE3D,MAAM,wBAAwB,KAAK,KAAK;AAWxC,2BATgC,kBAAkB,KAC/C,gBACE;EACC,eAAe,WAAW;EAC1B,MAAM;EACN,QAAQ;EACT,EAG4C,CAAC;CAElD,MAAM,wBAAwB,QAC5B,cAAc,OAAO,YAAY,cAAc,OAAO,aACvD;AAED,KAAI,sBAEF,QAAO,gBAAgB,KAAK;CAG9B,IAAI,qBAAmC,EAAE;AAEzC,KAAI,sBACF,sBAAqB,MAAME,uEACzB,eACA,2BACA;EACE,0BAA0B,OAAO,kBAAkB;EACnD,yBAAyB,OAAO,iBAAiB;EACjD,UAAU,MAAM,OAAO,eAAe,EAAE;EACzC,CACF,CACE,MAAM,iBACLH,4DAA0B,cAAc,cAAc,CACvD,CACA,MAAM,iBAAiBC,4CAAmB,aAAa,CAAC;CAG7D,MAAM,yBAAyB,KAAK,KAAK;AAGzC,QAAO,QAAQ;AAEf,cAAa,cAAc;AAE3B,QAAO;EACL;EACA;EACA;EACA,MAAM;GACJ,mBAAmB,wBAAwB;GAC3C,oBAAoB,yBAAyB;GAC7C,oBAAoB,yBAAyB;GAC9C;EACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"loadRemoteDictionaries.cjs","names":["sortAlphabetically","fetchDistantDictionaries"],"sources":["../../../src/loadDictionaries/loadRemoteDictionaries.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\n// @ts-ignore @intlayer/backend is not build yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getRemoteDictionaries } from '@intlayer/remote-dictionaries-entry';\nimport type { Dictionary, DictionaryId, DictionaryKey } from '@intlayer/types/dictionary';\nimport { fetchDistantDictionaries } from '../fetchDistantDictionaries';\nimport type { DictionariesStatus } from '../loadDictionaries/loadDictionaries';\nimport { sortAlphabetically } from '../utils/sortAlphabetically';\n\nexport const formatDistantDictionaries = (\n dictionaries: (DictionaryAPI | Dictionary)[]\n): Dictionary[] =>\n dictionaries.map((dict) => ({\n ...dict,\n localId: `${dict.key}::remote::${dict.id}`,\n location: 'remote' as const,\n }));\n\nexport const loadRemoteDictionaries = async (\n configuration = getConfiguration(),\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: {\n onStartRemoteCheck?: () => void;\n onStopRemoteCheck?: () => void;\n onError?: (error: Error) => void;\n }\n): Promise<Dictionary[]> => {\n const { editor } = configuration;\n const remoteDictionariesRecord = getRemoteDictionaries(configuration);\n\n const hasRemoteDictionaries = Boolean(editor.clientId && editor.clientSecret);\n\n if (!hasRemoteDictionaries) return [];\n\n try {\n options?.onStartRemoteCheck?.();\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await intlayerAPI.dictionary.getDictionariesUpdateTimestamp();\n\n const distantDictionaryUpdateTimeStamp: Record<\n DictionaryId,\n { key: DictionaryKey; updatedAt: number }\n > | null = getDictionariesKeysResult.data;\n\n if (!distantDictionaryUpdateTimeStamp) {\n throw new Error('No distant dictionaries found');\n }\n\n const dictionariesIdToFetch = Object.entries(\n distantDictionaryUpdateTimeStamp\n ).filter(([dictionaryId, data]) => {\n // If remote doesn't provide updatedAt, fetch to be safe\n if (!data.updatedAt) return true;\n\n // If no local cache exists, fetch\n const local: Dictionary | undefined = remoteDictionariesRecord[\n data.key\n ]?.find((dictionary) => dictionary.id === dictionaryId);\n if (!local) return true;\n\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // If local timestamp missing or older than remote, fetch\n if (typeof localUpdatedAt !== 'number') return true;\n\n return data.updatedAt > localUpdatedAt;\n });\n\n const flatRemoteDictionariesRecord: DictionaryAPI[] = Object.values(\n remoteDictionariesRecord\n ).flat();\n\n const cachedDictionaries: Dictionary[] =\n flatRemoteDictionariesRecord.filter((dictionary) => {\n const remoteUpdatedAt =\n distantDictionaryUpdateTimeStamp[dictionary.id!].updatedAt;\n\n const localUpdatedAtRaw = dictionary.updatedAt;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // Consider as cached/imported when local exists and is up-to-date or newer\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n });\n\n // Report cached as already imported\n if (cachedDictionaries.length > 0) {\n onStatusUpdate?.(\n cachedDictionaries.map((dictionary) => ({\n dictionaryKey: dictionary.key,\n type: 'remote',\n status: 'imported',\n }))\n );\n }\n\n const orderedDistantDictionaryKeys = dictionariesIdToFetch\n .map(([, data]) => data.key)\n .sort(sortAlphabetically);\n\n // Report pending for keys to be fetched so totals are visible immediately\n if (orderedDistantDictionaryKeys.length > 0) {\n onStatusUpdate?.(\n orderedDistantDictionaryKeys.map((key) => ({\n dictionaryKey: key,\n type: 'remote',\n status: 'pending',\n }))\n );\n }\n\n const distantDictionariesData = await fetchDistantDictionaries(\n {\n dictionaryKeys: orderedDistantDictionaryKeys,\n },\n onStatusUpdate\n );\n\n const distantDictionaries: Dictionary[] = formatDistantDictionaries(\n distantDictionariesData\n );\n\n return [...cachedDictionaries, ...distantDictionaries];\n } catch (error) {\n options?.onError?.(error as Error);\n return [];\n } finally {\n options?.onStopRemoteCheck?.();\n }\n};\n"],"mappings":";;;;;;;;;AAUA,MAAa,6BACX,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AQ;GACT,EAAE,CACJ;EAGH,MAAM,+BAA+B,sBAClC,KAAK,GAAG,UAAU,KAAK,IAAI,CAC3B,KAAKA,oDAAmB;AAG3B,MAAI,6BAA6B,SAAS,EACxC,kBACE,6BAA6B,KAAK,SAAS;GACzC,eAAe;GACf,MAAM;GACN,QAAQ;GACT,EAAE,CACJ;EAUH,MAAM,sBAAoC,0BAPV,MAAMC,0DACpC,EACE,gBAAgB,8BACjB,EACD,eACD,CAIA;AAED,SAAO,CAAC,GAAG,oBAAoB,GAAG,oBAAoB;UAC/C,OAAO;AACd,WAAS,UAAU,MAAe;AAClC,SAAO,EAAE;WACD;AACR,WAAS,qBAAqB"}
1
+ {"version":3,"file":"loadRemoteDictionaries.cjs","names":["sortAlphabetically","fetchDistantDictionaries"],"sources":["../../../src/loadDictionaries/loadRemoteDictionaries.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\n// @ts-ignore @intlayer/backend is not build yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getRemoteDictionaries } from '@intlayer/remote-dictionaries-entry';\nimport type { Dictionary, DictionaryId, DictionaryKey } from '@intlayer/types/dictionary';\nimport { fetchDistantDictionaries } from '../fetchDistantDictionaries';\nimport type { DictionariesStatus } from '../loadDictionaries/loadDictionaries';\nimport { sortAlphabetically } from '../utils/sortAlphabetically';\n\nexport const formatDistantDictionaries = (\n dictionaries: (DictionaryAPI | Dictionary)[]\n): Dictionary[] =>\n dictionaries.map((dict) => ({\n ...dict,\n localId: `${dict.key}::remote::${dict.id}`,\n location: 'remote' as const,\n }));\n\nexport const loadRemoteDictionaries = async (\n configuration = getConfiguration(),\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: {\n onStartRemoteCheck?: () => void;\n onStopRemoteCheck?: () => void;\n onError?: (error: Error) => void;\n }\n): Promise<Dictionary[]> => {\n const { editor } = configuration;\n const remoteDictionariesRecord = getRemoteDictionaries(configuration);\n\n const hasRemoteDictionaries = Boolean(editor.clientId && editor.clientSecret);\n\n if (!hasRemoteDictionaries) return [];\n\n try {\n options?.onStartRemoteCheck?.();\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await intlayerAPI.dictionary.getDictionariesUpdateTimestamp();\n\n const distantDictionaryUpdateTimeStamp: Record<\n DictionaryId,\n { key: DictionaryKey; updatedAt: number }\n > | null = getDictionariesKeysResult.data;\n\n if (!distantDictionaryUpdateTimeStamp) {\n throw new Error('No distant dictionaries found');\n }\n\n const dictionariesIdToFetch = Object.entries(\n distantDictionaryUpdateTimeStamp\n ).filter(([dictionaryId, data]) => {\n // If remote doesn't provide updatedAt, fetch to be safe\n if (!data.updatedAt) return true;\n\n // If no local cache exists, fetch\n const local: Dictionary | undefined = remoteDictionariesRecord[\n data.key\n ]?.find((dictionary) => dictionary.id === dictionaryId);\n if (!local) return true;\n\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // If local timestamp missing or older than remote, fetch\n if (typeof localUpdatedAt !== 'number') return true;\n\n return data.updatedAt > localUpdatedAt;\n });\n\n const flatRemoteDictionariesRecord: DictionaryAPI[] = Object.values(\n remoteDictionariesRecord\n ).flat();\n\n const cachedDictionaries: Dictionary[] =\n flatRemoteDictionariesRecord.filter((dictionary) => {\n const remoteUpdatedAt =\n distantDictionaryUpdateTimeStamp[dictionary.id!].updatedAt;\n\n const localUpdatedAtRaw = dictionary.updatedAt;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // Consider as cached/imported when local exists and is up-to-date or newer\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n });\n\n // Report cached as already imported\n if (cachedDictionaries.length > 0) {\n onStatusUpdate?.(\n cachedDictionaries.map((dictionary) => ({\n dictionaryKey: dictionary.key,\n type: 'remote',\n status: 'imported',\n }))\n );\n }\n\n const orderedDistantDictionaryKeys = dictionariesIdToFetch\n .map(([, data]) => data.key)\n .sort(sortAlphabetically);\n\n // Report pending for keys to be fetched so totals are visible immediately\n if (orderedDistantDictionaryKeys.length > 0) {\n onStatusUpdate?.(\n orderedDistantDictionaryKeys.map((key) => ({\n dictionaryKey: key,\n type: 'remote',\n status: 'pending',\n }))\n );\n }\n\n const distantDictionariesData = await fetchDistantDictionaries(\n {\n dictionaryKeys: orderedDistantDictionaryKeys,\n },\n onStatusUpdate\n );\n\n const distantDictionaries: Dictionary[] = formatDistantDictionaries(\n distantDictionariesData\n );\n\n return [...cachedDictionaries, ...distantDictionaries];\n } catch (error) {\n options?.onError?.(error as Error);\n return [];\n } finally {\n options?.onStopRemoteCheck?.();\n }\n};\n"],"mappings":";;;;;;;;;AAUA,MAAa,6BACX,iBAEA,aAAa,KAAK,UAAU;CAC1B,GAAG;CACH,SAAS,GAAG,KAAK,IAAI,YAAY,KAAK;CACtC,UAAU;CACX,EAAE;AAEL,MAAa,yBAAyB,OACpC,6DAAkC,EAClC,gBACA,YAK0B;CAC1B,MAAM,EAAE,WAAW;CACnB,MAAM,0FAAiD,cAAc;AAIrE,KAAI,CAF0B,QAAQ,OAAO,YAAY,OAAO,aAEtC,CAAE,QAAO,EAAE;AAErC,KAAI;AACF,WAAS,sBAAsB;EAQ/B,MAAM,oCAGK,6CAT6B,QAAW,cAIhC,CAAC,WAAW,gCAAgC,EAK1B;AAErC,MAAI,CAAC,iCACH,OAAM,IAAI,MAAM,gCAAgC;EAGlD,MAAM,wBAAwB,OAAO,QACnC,iCACD,CAAC,QAAQ,CAAC,cAAc,UAAU;AAEjC,OAAI,CAAC,KAAK,UAAW,QAAO;GAG5B,MAAM,QAAgC,yBACpC,KAAK,MACJ,MAAM,eAAe,WAAW,OAAO,aAAa;AACvD,OAAI,CAAC,MAAO,QAAO;GAEnB,MAAM,oBAAqB,OAAe;GAK1C,MAAM,iBACJ,OAAO,sBAAsB,WACzB,oBACA,oBACE,IAAI,KAAK,kBAAkB,CAAC,SAAS,GACrC;AAGR,OAAI,OAAO,mBAAmB,SAAU,QAAO;AAE/C,UAAO,KAAK,YAAY;IACxB;EAMF,MAAM,qBAJgD,OAAO,OAC3D,yBACD,CAAC,MAG4B,CAAC,QAAQ,eAAe;GAClD,MAAM,kBACJ,iCAAiC,WAAW,IAAK;GAEnD,MAAM,oBAAoB,WAAW;GAErC,MAAM,iBACJ,OAAO,sBAAsB,WACzB,oBACA,oBACE,IAAI,KAAK,kBAAkB,CAAC,SAAS,GACrC;AAGR,UACE,OAAO,mBAAmB,YAC1B,OAAO,oBAAoB,YAC3B,kBAAkB;IAEpB;AAGJ,MAAI,mBAAmB,SAAS,EAC9B,kBACE,mBAAmB,KAAK,gBAAgB;GACtC,eAAe,WAAW;GAC1B,MAAM;GACN,QAAQ;GACT,EAAE,CACJ;EAGH,MAAM,+BAA+B,sBAClC,KAAK,GAAG,UAAU,KAAK,IAAI,CAC3B,KAAKA,oDAAmB;AAG3B,MAAI,6BAA6B,SAAS,EACxC,kBACE,6BAA6B,KAAK,SAAS;GACzC,eAAe;GACf,MAAM;GACN,QAAQ;GACT,EAAE,CACJ;EAUH,MAAM,sBAAoC,0BACxC,MARoCC,0DACpC,EACE,gBAAgB,8BACjB,EACD,eACD,CAIA;AAED,SAAO,CAAC,GAAG,oBAAoB,GAAG,oBAAoB;UAC/C,OAAO;AACd,WAAS,UAAU,MAAe;AAClC,SAAO,EAAE;WACD;AACR,WAAS,qBAAqB"}
@@ -1 +1 @@
1
- {"version":3,"file":"logTypeScriptErrors.cjs","names":[],"sources":["../../../src/loadDictionaries/logTypeScriptErrors.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const logTypeScriptErrors = async (\n filePaths: string[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n\n const filesToCheck = filePaths.filter((path) => {\n const ext = extname(path);\n\n return ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.json'].includes(\n ext\n );\n });\n\n if (filesToCheck.length === 0) return;\n\n let ts: typeof import('typescript');\n\n try {\n ts = (await import('typescript')).default || (await import('typescript'));\n } catch {\n // TypeScript not installed, skip type checking\n\n return;\n }\n\n const configFileName = ts.findConfigFile(\n configuration.system?.baseDir ?? process.cwd(),\n ts.sys.fileExists,\n 'tsconfig.json'\n );\n\n let compilerOptions: any = {\n noEmit: true,\n\n allowJs: true,\n\n resolveJsonModule: true,\n };\n\n if (configFileName) {\n const configFileText = ts.sys.readFile(configFileName);\n\n if (configFileText) {\n const configJson = ts.parseConfigFileTextToJson(\n configFileName,\n\n configFileText\n );\n\n if (!configJson.error) {\n const parsedConfig = ts.parseJsonConfigFileContent(\n configJson.config,\n\n ts.sys,\n\n dirname(configFileName)\n );\n\n const { incremental, tsBuildInfoFile, ...restOptions } =\n parsedConfig.options;\n\n compilerOptions = { ...compilerOptions, ...restOptions, noEmit: true };\n }\n }\n }\n\n const program = ts.createProgram(filesToCheck, compilerOptions);\n\n filesToCheck.forEach((filePath) => {\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) return;\n\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n\n diagnostics.forEach((diagnostic) => {\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n\n '\\n'\n );\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } =\n diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n\n appLogger(\n `TS Error in ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`,\n\n { level: 'warn' }\n );\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OAAO,EAAE,GAAG,YAAY,EAAE,KAAK,WAE3E,EAAE,OAAO,QAAQ,CAClB;;IAEH;GACF"}
1
+ {"version":3,"file":"logTypeScriptErrors.cjs","names":[],"sources":["../../../src/loadDictionaries/logTypeScriptErrors.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const logTypeScriptErrors = async (\n filePaths: string[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n\n const filesToCheck = filePaths.filter((path) => {\n const ext = extname(path);\n\n return ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.json'].includes(\n ext\n );\n });\n\n if (filesToCheck.length === 0) return;\n\n let ts: typeof import('typescript');\n\n try {\n ts = (await import('typescript')).default || (await import('typescript'));\n } catch {\n // TypeScript not installed, skip type checking\n\n return;\n }\n\n const configFileName = ts.findConfigFile(\n configuration.system?.baseDir ?? process.cwd(),\n ts.sys.fileExists,\n 'tsconfig.json'\n );\n\n let compilerOptions: any = {\n noEmit: true,\n\n allowJs: true,\n\n resolveJsonModule: true,\n };\n\n if (configFileName) {\n const configFileText = ts.sys.readFile(configFileName);\n\n if (configFileText) {\n const configJson = ts.parseConfigFileTextToJson(\n configFileName,\n\n configFileText\n );\n\n if (!configJson.error) {\n const parsedConfig = ts.parseJsonConfigFileContent(\n configJson.config,\n\n ts.sys,\n\n dirname(configFileName)\n );\n\n const { incremental, tsBuildInfoFile, ...restOptions } =\n parsedConfig.options;\n\n compilerOptions = { ...compilerOptions, ...restOptions, noEmit: true };\n }\n }\n }\n\n const program = ts.createProgram(filesToCheck, compilerOptions);\n\n filesToCheck.forEach((filePath) => {\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) return;\n\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n\n diagnostics.forEach((diagnostic) => {\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n\n '\\n'\n );\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } =\n diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n\n appLogger(\n `TS Error in ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`,\n\n { level: 'warn' }\n );\n }\n });\n });\n};\n"],"mappings":";;;;;;AAIA,MAAa,sBAAsB,OACjC,WACA,kBACG;CACH,MAAM,sDAAyB,cAAc;CAE7C,MAAM,eAAe,UAAU,QAAQ,SAAS;EAC9C,MAAM,6BAAc,KAAK;AAEzB,SAAO;GAAC;GAAO;GAAQ;GAAO;GAAQ;GAAQ;GAAQ;GAAQ,CAAC,SAC7D,IACD;GACD;AAEF,KAAI,aAAa,WAAW,EAAG;CAE/B,IAAI;AAEJ,KAAI;AACF,QAAM,MAAM,OAAO,eAAe,WAAY,MAAM,OAAO;SACrD;AAGN;;CAGF,MAAM,iBAAiB,GAAG,eACxB,cAAc,QAAQ,WAAW,QAAQ,KAAK,EAC9C,GAAG,IAAI,YACP,gBACD;CAED,IAAI,kBAAuB;EACzB,QAAQ;EAER,SAAS;EAET,mBAAmB;EACpB;AAED,KAAI,gBAAgB;EAClB,MAAM,iBAAiB,GAAG,IAAI,SAAS,eAAe;AAEtD,MAAI,gBAAgB;GAClB,MAAM,aAAa,GAAG,0BACpB,gBAEA,eACD;AAED,OAAI,CAAC,WAAW,OAAO;IASrB,MAAM,EAAE,aAAa,iBAAiB,GAAG,gBARpB,GAAG,2BACtB,WAAW,QAEX,GAAG,4BAEK,eAAe,CAIX,CAAC;AAEf,sBAAkB;KAAE,GAAG;KAAiB,GAAG;KAAa,QAAQ;KAAM;;;;CAK5E,MAAM,UAAU,GAAG,cAAc,cAAc,gBAAgB;AAE/D,cAAa,SAAS,aAAa;EACjC,MAAM,aAAa,QAAQ,cAAc,SAAS;AAElD,MAAI,CAAC,WAAY;AAIjB,EAFoB,GAAG,sBAAsB,SAAS,WAE3C,CAAC,SAAS,eAAe;GAClC,MAAM,UAAU,GAAG,6BACjB,WAAW,aAEX,KACD;AAED,OAAI,WAAW,QAAQ,WAAW,UAAU,QAAW;IACrD,MAAM,EAAE,MAAM,cACZ,WAAW,KAAK,8BAA8B,WAAW,MAAM;AAEjE,cACE,eAAe,WAAW,KAAK,SAAS,IAAI,OAAO,EAAE,GAAG,YAAY,EAAE,KAAK,WAE3E,EAAE,OAAO,QAAQ,CAClB;;IAEH;GACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"logConfigDetails.cjs","names":["formatPath","intlayerConfigSchema","x","ANSIColors"],"sources":["../../src/logConfigDetails.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { getEnvFilePath } from '@intlayer/config/env';\nimport {\n colorize,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfigurationAndFilePath,\n intlayerConfigSchema,\n} from '@intlayer/config/node';\nimport { formatPath, runOnce } from './utils';\n\nexport const logConfigDetails = (options?: GetConfigurationOptions) => {\n const {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n } = getConfigurationAndFilePath(options);\n const appLogger = getAppLogger(configuration);\n\n runOnce(\n join(\n configuration.system.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-config-locaded.lock'\n ),\n () => {\n if (numCustomConfiguration === 0) {\n appLogger(\n 'Configuration file not found, using default configuration.',\n {\n isVerbose: true,\n }\n );\n } else {\n const baseDir = configuration.system.baseDir;\n const relativeOutputPath = relative(baseDir, configurationFilePath!);\n\n if (numCustomConfiguration === 1) {\n const dotEnvFilePath = getEnvFilePath(options?.env, options?.envFile);\n\n appLogger(\n `Configuration loaded ${formatPath(relativeOutputPath)}${dotEnvFilePath ? ` - Env: ${formatPath(dotEnvFilePath)}` : ''}`,\n {\n isVerbose: true,\n }\n );\n } else {\n appLogger(\n `Multiple configuration files found, using ${formatPath(relativeOutputPath)}.`,\n {\n isVerbose: true,\n }\n );\n }\n }\n\n if (customConfiguration) {\n const validation = intlayerConfigSchema.safeParse(customConfiguration);\n\n if (!validation.success) {\n const errorMessages = validation.error.issues\n .map((error) => {\n const path = colorizePath(` - ${error.path.join('.')}:`);\n const message = colorize(error.message, ANSIColors.GREY_DARK);\n return `${path} ${message}`;\n })\n .join('\\n');\n const errorMessage = `${x} Invalid configuration:\\n${errorMessages}`;\n\n appLogger(errorMessage);\n }\n\n if (customConfiguration.build?.importMode) {\n appLogger(\n `${colorize('build.importMode', ANSIColors.BLUE)} is deprecated, use ${colorize('dictionary.importMode', ANSIColors.BLUE)} instead`\n );\n }\n if (customConfiguration.compiler?.transformPattern) {\n appLogger(\n `${colorize('compiler.transformPattern', ANSIColors.BLUE)} is deprecated, use ${colorize('build.traversePattern', ANSIColors.BLUE)} instead`\n );\n }\n if (customConfiguration.compiler?.excludePattern) {\n appLogger(\n `${colorize('compiler.excludePattern', ANSIColors.BLUE)} is deprecated, use ${colorize('build.traversePattern', ANSIColors.BLUE)} instead`\n );\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 60, // 1 minute\n }\n );\n};\n"],"mappings":";;;;;;;;;;;;AAgBA,MAAa,oBAAoB,YAAsC;CACrE,MAAM,EACJ,eACA,qBACA,wBACA,iFAC8B,QAAQ;CACxC,MAAM,sDAAyB,cAAc;AAE7C,mDAEI,cAAc,OAAO,SACrB,aACA,SACA,+BACD,QACK;AACJ,MAAI,2BAA2B,EAC7B,WACE,8DACA,EACE,WAAW,MACZ,CACF;OACI;GACL,MAAM,UAAU,cAAc,OAAO;GACrC,MAAM,6CAA8B,SAAS,sBAAuB;AAEpE,OAAI,2BAA2B,GAAG;IAChC,MAAM,0DAAgC,SAAS,KAAK,SAAS,QAAQ;AAErE,cACE,wBAAwBA,mCAAW,mBAAmB,GAAG,iBAAiB,WAAWA,mCAAW,eAAe,KAAK,MACpH,EACE,WAAW,MACZ,CACF;SAED,WACE,6CAA6CA,mCAAW,mBAAmB,CAAC,IAC5E,EACE,WAAW,MACZ,CACF;;AAIL,MAAI,qBAAqB;GACvB,MAAM,aAAaC,2CAAqB,UAAU,oBAAoB;AAEtE,OAAI,CAAC,WAAW,QAUd,WAFqB,GAAGC,0BAAE,2BAPJ,WAAW,MAAM,OACpC,KAAK,UAAU;AAGd,WAAO,6CAFmB,MAAM,MAAM,KAAK,KAAK,IAAI,CAAC,GAAG,CAEzC,yCADU,MAAM,SAASC,wBAAW,UAAU;KAE7D,CACD,KAAK,KAAK,GAGU;AAGzB,OAAI,oBAAoB,OAAO,WAC7B,WACE,yCAAY,oBAAoBA,wBAAW,KAAK,CAAC,4DAA+B,yBAAyBA,wBAAW,KAAK,CAAC,UAC3H;AAEH,OAAI,oBAAoB,UAAU,iBAChC,WACE,yCAAY,6BAA6BA,wBAAW,KAAK,CAAC,4DAA+B,yBAAyBA,wBAAW,KAAK,CAAC,UACpI;AAEH,OAAI,oBAAoB,UAAU,eAChC,WACE,yCAAY,2BAA2BA,wBAAW,KAAK,CAAC,4DAA+B,yBAAyBA,wBAAW,KAAK,CAAC,UAClI;;IAIP,EACE,gBAAgB,MAAO,IACxB,CACF"}
1
+ {"version":3,"file":"logConfigDetails.cjs","names":["formatPath","intlayerConfigSchema","x","ANSIColors"],"sources":["../../src/logConfigDetails.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { getEnvFilePath } from '@intlayer/config/env';\nimport {\n colorize,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfigurationAndFilePath,\n intlayerConfigSchema,\n} from '@intlayer/config/node';\nimport { formatPath, runOnce } from './utils';\n\nexport const logConfigDetails = (options?: GetConfigurationOptions) => {\n const {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n } = getConfigurationAndFilePath(options);\n const appLogger = getAppLogger(configuration);\n\n runOnce(\n join(\n configuration.system.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-config-locaded.lock'\n ),\n () => {\n if (numCustomConfiguration === 0) {\n appLogger(\n 'Configuration file not found, using default configuration.',\n {\n isVerbose: true,\n }\n );\n } else {\n const baseDir = configuration.system.baseDir;\n const relativeOutputPath = relative(baseDir, configurationFilePath!);\n\n if (numCustomConfiguration === 1) {\n const dotEnvFilePath = getEnvFilePath(options?.env, options?.envFile);\n\n appLogger(\n `Configuration loaded ${formatPath(relativeOutputPath)}${dotEnvFilePath ? ` - Env: ${formatPath(dotEnvFilePath)}` : ''}`,\n {\n isVerbose: true,\n }\n );\n } else {\n appLogger(\n `Multiple configuration files found, using ${formatPath(relativeOutputPath)}.`,\n {\n isVerbose: true,\n }\n );\n }\n }\n\n if (customConfiguration) {\n const validation = intlayerConfigSchema.safeParse(customConfiguration);\n\n if (!validation.success) {\n const errorMessages = validation.error.issues\n .map((error) => {\n const path = colorizePath(` - ${error.path.join('.')}:`);\n const message = colorize(error.message, ANSIColors.GREY_DARK);\n return `${path} ${message}`;\n })\n .join('\\n');\n const errorMessage = `${x} Invalid configuration:\\n${errorMessages}`;\n\n appLogger(errorMessage);\n }\n\n if (customConfiguration.build?.importMode) {\n appLogger(\n `${colorize('build.importMode', ANSIColors.BLUE)} is deprecated, use ${colorize('dictionary.importMode', ANSIColors.BLUE)} instead`\n );\n }\n if (customConfiguration.compiler?.transformPattern) {\n appLogger(\n `${colorize('compiler.transformPattern', ANSIColors.BLUE)} is deprecated, use ${colorize('build.traversePattern', ANSIColors.BLUE)} instead`\n );\n }\n if (customConfiguration.compiler?.excludePattern) {\n appLogger(\n `${colorize('compiler.excludePattern', ANSIColors.BLUE)} is deprecated, use ${colorize('build.traversePattern', ANSIColors.BLUE)} instead`\n );\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 60, // 1 minute\n }\n );\n};\n"],"mappings":";;;;;;;;;;;;AAgBA,MAAa,oBAAoB,YAAsC;CACrE,MAAM,EACJ,eACA,qBACA,wBACA,iFAC8B,QAAQ;CACxC,MAAM,sDAAyB,cAAc;AAE7C,mDAEI,cAAc,OAAO,SACrB,aACA,SACA,+BACD,QACK;AACJ,MAAI,2BAA2B,EAC7B,WACE,8DACA,EACE,WAAW,MACZ,CACF;OACI;GACL,MAAM,UAAU,cAAc,OAAO;GACrC,MAAM,6CAA8B,SAAS,sBAAuB;AAEpE,OAAI,2BAA2B,GAAG;IAChC,MAAM,0DAAgC,SAAS,KAAK,SAAS,QAAQ;AAErE,cACE,wBAAwBA,mCAAW,mBAAmB,GAAG,iBAAiB,WAAWA,mCAAW,eAAe,KAAK,MACpH,EACE,WAAW,MACZ,CACF;SAED,WACE,6CAA6CA,mCAAW,mBAAmB,CAAC,IAC5E,EACE,WAAW,MACZ,CACF;;AAIL,MAAI,qBAAqB;GACvB,MAAM,aAAaC,2CAAqB,UAAU,oBAAoB;AAEtE,OAAI,CAAC,WAAW,QAUd,WAAU,GAFcC,0BAAE,2BAPJ,WAAW,MAAM,OACpC,KAAK,UAAU;AAGd,WAAO,6CAFmB,MAAM,MAAM,KAAK,KAAK,IAAI,CAAC,GAEvC,CAAC,yCADU,MAAM,SAASC,wBAAW,UAC1B;KACzB,CACD,KAAK,KAC0D,GAE3C;AAGzB,OAAI,oBAAoB,OAAO,WAC7B,WACE,yCAAY,oBAAoBA,wBAAW,KAAK,CAAC,4DAA+B,yBAAyBA,wBAAW,KAAK,CAAC,UAC3H;AAEH,OAAI,oBAAoB,UAAU,iBAChC,WACE,yCAAY,6BAA6BA,wBAAW,KAAK,CAAC,4DAA+B,yBAAyBA,wBAAW,KAAK,CAAC,UACpI;AAEH,OAAI,oBAAoB,UAAU,eAChC,WACE,yCAAY,2BAA2BA,wBAAW,KAAK,CAAC,4DAA+B,yBAAyBA,wBAAW,KAAK,CAAC,UAClI;;IAIP,EACE,gBAAgB,MAAO,IACxB,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * 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,sDAAyB,cAAc;CAE7C,MAAM,mCACJ,cAAc,OAAO,UACrB,yBACD;CAED,MAAM,qDAAyB,eAAe,CAAC,mBAAmB,CAAC;CACnE,MAAM,uBAAuB,MAAM,aAAa,KAAK;CACrD,MAAM,mBAAmB,QACvB,wBAAwB,yBAAyBA,sCAAY,QAC9D;CAED,MAAM,kBAAkB,MAAMC,+DAA8B,cAAc;CAG1E,MAAM,wBAAwB,MAAMC,uDAA0B,cAAc;CAC5E,IAAI,sBAAsB;AAC1B,KAAI;EAEF,MAAM,gBAAgB,iCAAW,aAAa;AAC9C,wBAAsB,sBAAsB,MACzC,eACC,WAAW,MAAM,MAAM,SAAS,GAAG,cAAc,MAAM,SAAS,CACnE;SACK;CAGR,MAAM,6BADkB,MAAM,QAAQ,IAAI,cAAc,WAAW,EAAE,CAAC,EACpB,MAAM,WACtD,QAAQ,OAAO,iBAAiB,CACjC;CAED,MAAM,EAAE,OAAO,QAAQ,UAAU,YAAY,gBAAgB,QAAQ;EACnE,GAAG;EACH,UACE,CAAC,oBACD,CAAC,mBACD,uBACA;EACF,GAAI,WAAW,EAAE;EAClB;AAGD,OAAMC,8BACJ,cACA,YAAY;AAIV,MAAI,SAAS,CAAC,iBACZ,OAAMC,sCAAe,cAAc;AAGrC,QAAM,aAAa,IAAIJ,sCAAY,QAAQ;EAE3C,MAAM,qBAAqB,KAAK,KAAK;AAErC,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AAI7C,YACE,CACE,mEAEE,IAN8B,KAAK,KAAK,GAMN,sBAAsB,MACxDP,wBAAW,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,8CAAiB,GAFS,KAAK,KAAK,GAAG,mBAEE,KAAKA,wBAAW,MAAM,CAAC,EACjE;GACE,OAAO;GACP,WAAW;GACZ,CACF;IAEH;EACE;EACA;EACA;EACD,CACF"}
1
+ {"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * 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,sDAAyB,cAAc;CAE7C,MAAM,mCACJ,cAAc,OAAO,UACrB,yBACD;CAED,MAAM,qDAAyB,eAAe,CAAC,mBAAmB,CAAC;CACnE,MAAM,uBAAuB,MAAM,aAAa,KAAK;CACrD,MAAM,mBAAmB,QACvB,wBAAwB,yBAAyBA,sCAAY,QAC9D;CAED,MAAM,kBAAkB,MAAMC,+DAA8B,cAAc;CAG1E,MAAM,wBAAwB,MAAMC,uDAA0B,cAAc;CAC5E,IAAI,sBAAsB;AAC1B,KAAI;EAEF,MAAM,gB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C,KAAK,GAAG,EACVF,wBAAW,UACZ,CACF,EACD,EACE,WAAW,MACZ,CACF;EAGD,MAAM,qBAAqB,MAAMG,wEAC/B;GACE,GAAG,aAAa;GAChB,GAAG,aAAa;GAChB,GAAG,aAAa;GACjB,EACD,eACA;GAAE,SAAS;GAAQ,yBAAyB;GAAO;GAAK,CACzD;AAID,QAAMC,4EACJ,aAAa,oBACb,cACD;AAMD,QAAMC,0CAJsB,OAAO,OACjC,oBAAoB,sBAAsB,EAAE,CAC7C,CAAC,KAAK,eAAe,WAAW,WAEI,EAAE,cAAc;AAErD,QAAMC,yFAA2B,cAAc;EAE/C,MAAM,wBAAwB,KAAK,KAAK;AAExC,YAAU,CACR,4DAEE,IAAI,wBAAwB,mBAAmB,MAC/CN,wBAAW,UACZ,CACF,CAAC;AAEF,QAAMO,qEAAyB,cAAc;AAI7C,YACE,CACE,mEAEE,IAN8B,KAAK,KAMJ,GAAG,sBAAsB,MACxDP,wBAAW,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,8CAAiB,GAFS,KAAK,KAAK,GAAG,mBAEE,KAAKA,wBAAW,MAAM,CAAC,EACjE;GACE,OAAO;GACP,WAAW;GACZ,CACF;IAEH;EACE;EACA;EACA;EACD,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"reduceDictionaryContent.cjs","names":["applyMask"],"sources":["../../../src/reduceDictionaryContent/reduceDictionaryContent.ts"],"sourcesContent":["import { getMaskContent } from '@intlayer/core/plugins';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { applyMask } from './applyMask';\n\nexport const reduceDictionaryContent = (\n fullDictionary: Dictionary,\n partialDictionary: Dictionary\n) => {\n const mask = getMaskContent(partialDictionary);\n const result = applyMask(fullDictionary, mask);\n\n return result;\n};\n"],"mappings":";;;;;;AAIA,MAAa,2BACX,gBACA,sBACG;AAIH,QAFeA,oDAAU,2DADG,kBAAkB,CACA"}
1
+ {"version":3,"file":"reduceDictionaryContent.cjs","names":["applyMask"],"sources":["../../../src/reduceDictionaryContent/reduceDictionaryContent.ts"],"sourcesContent":["import { getMaskContent } from '@intlayer/core/plugins';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { applyMask } from './applyMask';\n\nexport const reduceDictionaryContent = (\n fullDictionary: Dictionary,\n partialDictionary: Dictionary\n) => {\n const mask = getMaskContent(partialDictionary);\n const result = applyMask(fullDictionary, mask);\n\n return result;\n};\n"],"mappings":";;;;;;AAIA,MAAa,2BACX,gBACA,sBACG;AAIH,QAFeA,oDAAU,2DADG,kBACiB,CAEhC"}
@@ -1 +1 @@
1
- {"version":3,"file":"autoDecorateContent.cjs","names":["NodeTypes"],"sources":["../../../src/utils/autoDecorateContent.ts"],"sourcesContent":["import { getMarkdownMetadata } from '@intlayer/core/markdown';\nimport {\n getInsertionValues,\n html,\n insert,\n md,\n} from '@intlayer/core/transpiler';\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\n/**\n * Check if a string is a markdown string\n */\nconst isMarkdown = (str: string): boolean => {\n // Check for common markdown indicators\n const patterns = [\n /^\\s*---/m, // Front Matter\n /^\\s*#+\\s/m, // Headers: # Title\n /^\\s*[-*+]\\s/m, // Unordered lists: - Item or * Item\n /^\\s*\\d+\\.\\s/m, // Ordered lists: 1. Item\n /^\\s*>\\s/m, // Blockquotes: > Quote\n /\\[.+\\]\\(.+\\)/, // Links: [text](url)\n /!\\[.+\\]\\(.+\\)/, // Images: ![alt](url)\n /`{1,3}.+`{1,3}/, // Code blocks or inline code: `code` or ```code```\n /\\*\\*.+\\*\\*/, // Bold: **text**\n /__.+__/, // Bold: __text__\n /<(https?:\\/\\/[^\\s>]+)>/, // Autolinks: <http://...>\n ];\n\n return patterns.some((pattern) => pattern.test(str));\n};\n\n/**\n * Check if a string is an insertion string\n */\nconst isInsertion = (str: string): boolean =>\n getInsertionValues(str).length > 0;\n\n/**\n * Check if a string is an HTML/JSX string\n * Matches:\n * - <Tag>\n * - </Tag>\n * - <Tag />\n * - <Tag attribute=\"value\">\n * - <Component.SubComponent>\n */\nconst isHTML = (str: string): boolean => {\n // 1. Matches opening or self-closing tags: <Tag ... > or <Tag ... />\n // - Must start with < followed by a letter (to avoid math comparisons like a < b)\n // - Allows alphanumeric, hyphens, and dots (for Namespaced components) in tag name\n // - Allows attributes until the closing >\n const openTagRegex = /<[a-zA-Z][a-zA-Z0-9\\-.]*(\\s+[^>]*)?\\/?>/;\n\n // 2. Matches closing tags: </Tag>\n const closeTagRegex = /<\\/[a-zA-Z][a-zA-Z0-9\\-.]*\\s*>/;\n\n return openTagRegex.test(str) || closeTagRegex.test(str);\n};\n\nconst leafNodeTypes: string[] = [\n NodeTypes.HTML,\n NodeTypes.MARKDOWN,\n NodeTypes.INSERTION,\n NodeTypes.FILE,\n NodeTypes.REACT_NODE,\n NodeTypes.TEXT,\n NodeTypes.NUMBER,\n NodeTypes.BOOLEAN,\n NodeTypes.NULL,\n NodeTypes.UNKNOWN,\n];\n\ntype AutoTransformationOptions = {\n markdown?: boolean;\n html?: boolean;\n insertion?: boolean;\n};\n\n/**\n * Automatically decorate content strings with md() or insert() if they match\n */\nexport const autoDecorateContent = (\n content: any,\n options: boolean | AutoTransformationOptions = true\n): any => {\n if (options === false) {\n return content;\n }\n\n const {\n markdown = true,\n html: htmlOption = true,\n insertion = true,\n } = typeof options === 'object' ? options : {};\n\n if (typeof content === 'string') {\n if (markdown && isMarkdown(content)) {\n const markdownNode = md(content);\n\n return {\n ...markdownNode,\n metadata: getMarkdownMetadata(content),\n };\n }\n\n if (htmlOption && isHTML(content)) {\n return html(content);\n }\n\n if (insertion && isInsertion(content)) {\n return insert(content);\n }\n\n return content;\n }\n\n if (Array.isArray(content)) {\n return content.map((item) => autoDecorateContent(item, options));\n }\n\n if (content && typeof content === 'object') {\n // If it's already a decorated node (has nodeType)\n if ('nodeType' in content) {\n const nodeType = content.nodeType;\n\n // If it's a leaf node type, don't re-decorate its content\n if (leafNodeTypes.includes(nodeType)) {\n return content;\n }\n\n // If it's a container node type (like translation, enumeration, etc.), recurse into its content field\n if (nodeType in content) {\n return {\n ...content,\n [nodeType]: autoDecorateContent(content[nodeType], options),\n };\n }\n\n return content;\n }\n\n // Plain object, recurse into all keys\n const result: Record<string, any> = {};\n for (const key of Object.keys(content)) {\n result[key] = autoDecorateContent(content[key], options);\n }\n return result;\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,cAAc,QAAyB;AAgB3C,QAdiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAEe,MAAM,YAAY,QAAQ,KAAK,IAAI,CAAC;;;;;AAMtD,MAAM,eAAe,0DACA,IAAI,CAAC,SAAS;;;;;;;;;;AAWnC,MAAM,UAAU,QAAyB;AAUvC,QALqB,0CAKD,KAAK,IAAI,IAFP,iCAEyB,KAAK,IAAI;;AAG1D,MAAM,gBAA0B;CAC9BA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACX;;;;AAWD,MAAa,uBACX,SACA,UAA+C,SACvC;AACR,KAAI,YAAY,MACd,QAAO;CAGT,MAAM,EACJ,WAAW,MACX,MAAM,aAAa,MACnB,YAAY,SACV,OAAO,YAAY,WAAW,UAAU,EAAE;AAE9C,KAAI,OAAO,YAAY,UAAU;AAC/B,MAAI,YAAY,WAAW,QAAQ,CAGjC,QAAO;GACL,qCAHsB,QAAQ;GAI9B,2DAA8B,QAAQ;GACvC;AAGH,MAAI,cAAc,OAAO,QAAQ,CAC/B,4CAAY,QAAQ;AAGtB,MAAI,aAAa,YAAY,QAAQ,CACnC,8CAAc,QAAQ;AAGxB,SAAO;;AAGT,KAAI,MAAM,QAAQ,QAAQ,CACxB,QAAO,QAAQ,KAAK,SAAS,oBAAoB,MAAM,QAAQ,CAAC;AAGlE,KAAI,WAAW,OAAO,YAAY,UAAU;AAE1C,MAAI,cAAc,SAAS;GACzB,MAAM,WAAW,QAAQ;AAGzB,OAAI,cAAc,SAAS,SAAS,CAClC,QAAO;AAIT,OAAI,YAAY,QACd,QAAO;IACL,GAAG;KACF,WAAW,oBAAoB,QAAQ,WAAW,QAAQ;IAC5D;AAGH,UAAO;;EAIT,MAAM,SAA8B,EAAE;AACtC,OAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,CACpC,QAAO,OAAO,oBAAoB,QAAQ,MAAM,QAAQ;AAE1D,SAAO;;AAGT,QAAO"}
1
+ {"version":3,"file":"autoDecorateContent.cjs","names":["NodeTypes"],"sources":["../../../src/utils/autoDecorateContent.ts"],"sourcesContent":["import { getMarkdownMetadata } from '@intlayer/core/markdown';\nimport {\n getInsertionValues,\n html,\n insert,\n md,\n} from '@intlayer/core/transpiler';\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\n/**\n * Check if a string is a markdown string\n */\nconst isMarkdown = (str: string): boolean => {\n // Check for common markdown indicators\n const patterns = [\n /^\\s*---/m, // Front Matter\n /^\\s*#+\\s/m, // Headers: # Title\n /^\\s*[-*+]\\s/m, // Unordered lists: - Item or * Item\n /^\\s*\\d+\\.\\s/m, // Ordered lists: 1. Item\n /^\\s*>\\s/m, // Blockquotes: > Quote\n /\\[.+\\]\\(.+\\)/, // Links: [text](url)\n /!\\[.+\\]\\(.+\\)/, // Images: ![alt](url)\n /`{1,3}.+`{1,3}/, // Code blocks or inline code: `code` or ```code```\n /\\*\\*.+\\*\\*/, // Bold: **text**\n /__.+__/, // Bold: __text__\n /<(https?:\\/\\/[^\\s>]+)>/, // Autolinks: <http://...>\n ];\n\n return patterns.some((pattern) => pattern.test(str));\n};\n\n/**\n * Check if a string is an insertion string\n */\nconst isInsertion = (str: string): boolean =>\n getInsertionValues(str).length > 0;\n\n/**\n * Check if a string is an HTML/JSX string\n * Matches:\n * - <Tag>\n * - </Tag>\n * - <Tag />\n * - <Tag attribute=\"value\">\n * - <Component.SubComponent>\n */\nconst isHTML = (str: string): boolean => {\n // 1. Matches opening or self-closing tags: <Tag ... > or <Tag ... />\n // - Must start with < followed by a letter (to avoid math comparisons like a < b)\n // - Allows alphanumeric, hyphens, and dots (for Namespaced components) in tag name\n // - Allows attributes until the closing >\n const openTagRegex = /<[a-zA-Z][a-zA-Z0-9\\-.]*(\\s+[^>]*)?\\/?>/;\n\n // 2. Matches closing tags: </Tag>\n const closeTagRegex = /<\\/[a-zA-Z][a-zA-Z0-9\\-.]*\\s*>/;\n\n return openTagRegex.test(str) || closeTagRegex.test(str);\n};\n\nconst leafNodeTypes: string[] = [\n NodeTypes.HTML,\n NodeTypes.MARKDOWN,\n NodeTypes.INSERTION,\n NodeTypes.FILE,\n NodeTypes.REACT_NODE,\n NodeTypes.TEXT,\n NodeTypes.NUMBER,\n NodeTypes.BOOLEAN,\n NodeTypes.NULL,\n NodeTypes.UNKNOWN,\n];\n\ntype AutoTransformationOptions = {\n markdown?: boolean;\n html?: boolean;\n insertion?: boolean;\n};\n\n/**\n * Automatically decorate content strings with md() or insert() if they match\n */\nexport const autoDecorateContent = (\n content: any,\n options: boolean | AutoTransformationOptions = true\n): any => {\n if (options === false) {\n return content;\n }\n\n const {\n markdown = true,\n html: htmlOption = true,\n insertion = true,\n } = typeof options === 'object' ? options : {};\n\n if (typeof content === 'string') {\n if (markdown && isMarkdown(content)) {\n const markdownNode = md(content);\n\n return {\n ...markdownNode,\n metadata: getMarkdownMetadata(content),\n };\n }\n\n if (htmlOption && isHTML(content)) {\n return html(content);\n }\n\n if (insertion && isInsertion(content)) {\n return insert(content);\n }\n\n return content;\n }\n\n if (Array.isArray(content)) {\n return content.map((item) => autoDecorateContent(item, options));\n }\n\n if (content && typeof content === 'object') {\n // If it's already a decorated node (has nodeType)\n if ('nodeType' in content) {\n const nodeType = content.nodeType;\n\n // If it's a leaf node type, don't re-decorate its content\n if (leafNodeTypes.includes(nodeType)) {\n return content;\n }\n\n // If it's a container node type (like translation, enumeration, etc.), recurse into its content field\n if (nodeType in content) {\n return {\n ...content,\n [nodeType]: autoDecorateContent(content[nodeType], options),\n };\n }\n\n return content;\n }\n\n // Plain object, recurse into all keys\n const result: Record<string, any> = {};\n for (const key of Object.keys(content)) {\n result[key] = autoDecorateContent(content[key], options);\n }\n return result;\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,cAAc,QAAyB;AAgB3C,QAAO;EAbL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGa,CAAC,MAAM,YAAY,QAAQ,KAAK,IAAI,CAAC;;;;;AAMtD,MAAM,eAAe,0DACA,IAAI,CAAC,SAAS;;;;;;;;;;AAWnC,MAAM,UAAU,QAAyB;AAUvC,QAAO,0CAAa,KAAK,IAAI,IAAI,iCAAc,KAAK,IAAI;;AAG1D,MAAM,gBAA0B;CAC9BA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACVA,yBAAU;CACX;;;;AAWD,MAAa,uBACX,SACA,UAA+C,SACvC;AACR,KAAI,YAAY,MACd,QAAO;CAGT,MAAM,EACJ,WAAW,MACX,MAAM,aAAa,MACnB,YAAY,SACV,OAAO,YAAY,WAAW,UAAU,EAAE;AAE9C,KAAI,OAAO,YAAY,UAAU;AAC/B,MAAI,YAAY,WAAW,QAAQ,CAGjC,QAAO;GACL,qCAHsB,QAGP;GACf,2DAA8B,QAAQ;GACvC;AAGH,MAAI,cAAc,OAAO,QAAQ,CAC/B,4CAAY,QAAQ;AAGtB,MAAI,aAAa,YAAY,QAAQ,CACnC,8CAAc,QAAQ;AAGxB,SAAO;;AAGT,KAAI,MAAM,QAAQ,QAAQ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