@intlayer/chokidar 8.1.11 → 8.2.1

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 (104) hide show
  1. package/dist/assets/installSkills/skills/astro.md +1 -1
  2. package/dist/assets/installSkills/skills/cli.md +2 -2
  3. package/dist/cjs/cli.cjs +1 -1
  4. package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +1 -1
  5. package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
  6. package/dist/cjs/createType/createModuleAugmentation.cjs +3 -3
  7. package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
  8. package/dist/cjs/init/utils/configManipulation.cjs +1 -1
  9. package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
  10. package/dist/cjs/installMCP/installMCP.cjs +2 -0
  11. package/dist/cjs/installMCP/installMCP.cjs.map +1 -0
  12. package/dist/cjs/installSkills/index.cjs +1 -1
  13. package/dist/cjs/installSkills/index.cjs.map +1 -1
  14. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +1 -1
  15. package/dist/cjs/loadDictionaries/log.cjs +1 -1
  16. package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
  17. package/dist/cjs/prepareIntlayer.cjs +1 -1
  18. package/dist/cjs/utils/getPathHash.cjs +2 -0
  19. package/dist/cjs/utils/getPathHash.cjs.map +1 -0
  20. package/dist/cjs/utils/index.cjs +1 -1
  21. package/dist/cjs/watcher.cjs +1 -1
  22. package/dist/cjs/watcher.cjs.map +1 -1
  23. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +1 -2
  24. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
  25. package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +1 -1
  26. package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
  27. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +1 -1
  28. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  29. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +1 -1
  30. package/dist/esm/cli.mjs +1 -1
  31. package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs +1 -1
  32. package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs.map +1 -1
  33. package/dist/esm/createType/createModuleAugmentation.mjs +9 -9
  34. package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
  35. package/dist/esm/init/utils/configManipulation.mjs +1 -1
  36. package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
  37. package/dist/esm/installMCP/installMCP.mjs +2 -0
  38. package/dist/esm/installMCP/installMCP.mjs.map +1 -0
  39. package/dist/esm/installSkills/index.mjs +1 -1
  40. package/dist/esm/installSkills/index.mjs.map +1 -1
  41. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs +1 -1
  42. package/dist/esm/loadDictionaries/log.mjs +2 -2
  43. package/dist/esm/loadDictionaries/log.mjs.map +1 -1
  44. package/dist/esm/prepareIntlayer.mjs +1 -1
  45. package/dist/esm/utils/getPathHash.mjs +2 -0
  46. package/dist/esm/utils/getPathHash.mjs.map +1 -0
  47. package/dist/esm/utils/index.mjs +1 -1
  48. package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
  49. package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
  50. package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
  51. package/dist/esm/watcher.mjs +1 -1
  52. package/dist/esm/watcher.mjs.map +1 -1
  53. package/dist/esm/writeContentDeclaration/transformJSFile.mjs +1 -2
  54. package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
  55. package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +1 -1
  56. package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
  57. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +1 -1
  58. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  59. package/dist/esm/writeContentDeclaration/writeJSFile.mjs +1 -1
  60. package/dist/types/build.d.ts +0 -5
  61. package/dist/types/cli.d.ts +8 -5
  62. package/dist/types/createType/createModuleAugmentation.d.ts.map +1 -1
  63. package/dist/types/fetchDistantDictionaries.d.ts +0 -1
  64. package/dist/types/fetchDistantDictionaries.d.ts.map +1 -1
  65. package/dist/types/init/utils/configManipulation.d.ts +0 -12
  66. package/dist/types/init/utils/configManipulation.d.ts.map +1 -1
  67. package/dist/types/installMCP/installMCP.d.ts +11 -0
  68. package/dist/types/installMCP/installMCP.d.ts.map +1 -0
  69. package/dist/types/installSkills/index.d.ts +23 -49
  70. package/dist/types/installSkills/index.d.ts.map +1 -1
  71. package/dist/types/loadDictionaries/log.d.ts.map +1 -1
  72. package/dist/types/utils/getPathHash.d.ts +5 -0
  73. package/dist/types/utils/getPathHash.d.ts.map +1 -0
  74. package/dist/types/utils/index.d.ts +2 -2
  75. package/dist/types/watcher.d.ts.map +1 -1
  76. package/dist/types/writeContentDeclaration/transformJSFile.d.ts +1 -26
  77. package/dist/types/writeContentDeclaration/transformJSFile.d.ts.map +1 -1
  78. package/dist/types/writeContentDeclaration/transformJSONFile.d.ts.map +1 -1
  79. package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +1 -1
  80. package/package.json +9 -23
  81. package/dist/cjs/index.cjs +0 -1
  82. package/dist/cjs/transformFiles/extractDictionaryKey.cjs +0 -2
  83. package/dist/cjs/transformFiles/extractDictionaryKey.cjs.map +0 -1
  84. package/dist/cjs/transformFiles/index.cjs +0 -1
  85. package/dist/cjs/transformFiles/transformFiles.cjs +0 -2
  86. package/dist/cjs/transformFiles/transformFiles.cjs.map +0 -1
  87. package/dist/cjs/utils/getFileHash.cjs +0 -2
  88. package/dist/cjs/utils/getFileHash.cjs.map +0 -1
  89. package/dist/esm/index.mjs +0 -1
  90. package/dist/esm/transformFiles/extractDictionaryKey.mjs +0 -2
  91. package/dist/esm/transformFiles/extractDictionaryKey.mjs.map +0 -1
  92. package/dist/esm/transformFiles/index.mjs +0 -1
  93. package/dist/esm/transformFiles/transformFiles.mjs +0 -2
  94. package/dist/esm/transformFiles/transformFiles.mjs.map +0 -1
  95. package/dist/esm/utils/getFileHash.mjs +0 -2
  96. package/dist/esm/utils/getFileHash.mjs.map +0 -1
  97. package/dist/types/index.d.ts +0 -57
  98. package/dist/types/transformFiles/extractDictionaryKey.d.ts +0 -5
  99. package/dist/types/transformFiles/extractDictionaryKey.d.ts.map +0 -1
  100. package/dist/types/transformFiles/index.d.ts +0 -3
  101. package/dist/types/transformFiles/transformFiles.d.ts +0 -24
  102. package/dist/types/transformFiles/transformFiles.d.ts.map +0 -1
  103. package/dist/types/utils/getFileHash.d.ts +0 -5
  104. package/dist/types/utils/getFileHash.d.ts.map +0 -1
@@ -33,7 +33,7 @@ const content = await getIntlayer("my-dictionary-key");
33
33
  ## References
34
34
 
35
35
  - [Website](https://intlayer.org)
36
- - [Doc](https://intlayer.org/doc/concept/cli.md)
36
+ - [Doc](https://intlayer.org/doc/concept/cli/index.md)
37
37
 
38
38
  - [Astro](https://intlayer.org/doc/environment/astro.md)
39
39
  - [Intlayer Exports](https://intlayer.org/doc/packages/intlayer/exports.md)
@@ -40,7 +40,7 @@ npm install intlayer-cli
40
40
 
41
41
  - [Build](https://intlayer.org/doc/concept/cli/build.md)
42
42
  - [CI](https://intlayer.org/doc/concept/cli/ci.md)
43
- - [CLI Overview](https://intlayer.org/doc/concept/cli.md)
43
+ - [CLI Overview](https://intlayer.org/doc/concept/cli/index.md)
44
44
  - [Configuration](https://intlayer.org/doc/concept/cli/configuration.md)
45
45
  - [Debug](https://intlayer.org/doc/concept/cli/debug.md)
46
46
  - [Doc Review](https://intlayer.org/doc/concept/cli/doc-review.md)
@@ -63,7 +63,7 @@ npm install intlayer-cli
63
63
  ### Packages
64
64
 
65
65
  - [Website](https://intlayer.org)
66
- - [Doc](https://intlayer.org/doc/concept/cli.md)
66
+ - [Doc](https://intlayer.org/doc/concept/cli/index.md)
67
67
 
68
68
  - [Intlayer CLI](https://intlayer.org/doc/packages/intlayer-cli/exports.md)
69
69
  - [Intlayer CLI Exports](https://intlayer.org/doc/packages/intlayer-cli/exports.md)
package/dist/cjs/cli.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./listDictionariesPath.cjs`),t=require(`./detectFormatCommand.cjs`),n=require(`./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs`),r=require(`./init/index.cjs`),i=require(`./installSkills/index.cjs`),a=require(`./listGitFiles.cjs`),o=require(`./listProjects.cjs`),s=require(`./transformFiles/extractDictionaryKey.cjs`),c=require(`./transformFiles/transformFiles.cjs`);exports.ATTRIBUTES_TO_EXTRACT=c.ATTRIBUTES_TO_EXTRACT,exports.SKILLS=i.SKILLS,exports.SKILLS_METADATA=i.SKILLS_METADATA,exports.detectFormatCommand=t.detectFormatCommand,exports.extractDictionaryKey=s.extractDictionaryKey,exports.extractIntlayer=c.extractIntlayer,exports.getContentDeclarationFileTemplate=n.getContentDeclarationFileTemplate,exports.initIntlayer=r.initIntlayer,exports.installSkills=i.installSkills,exports.listDictionaries=e.listDictionaries,exports.listDictionariesWithStats=e.listDictionariesWithStats,exports.listGitFiles=a.listGitFiles,exports.listGitLines=a.listGitLines,exports.listProjects=o.listProjects,exports.shouldExtract=c.shouldExtract,exports.transformFiles=c.transformFiles;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./listDictionariesPath.cjs`),t=require(`./writeContentDeclaration/detectExportedComponentName.cjs`),n=require(`./writeContentDeclaration/transformJSFile.cjs`),r=require(`./detectFormatCommand.cjs`),i=require(`./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs`),a=require(`./writeContentDeclaration/writeJSFile.cjs`),o=require(`./writeContentDeclaration/writeContentDeclaration.cjs`),s=require(`./init/index.cjs`),c=require(`./installSkills/index.cjs`),l=require(`./installMCP/installMCP.cjs`),u=require(`./listGitFiles.cjs`),d=require(`./listProjects.cjs`);exports.PLATFORMS=c.PLATFORMS,exports.PLATFORMS_METADATA=c.PLATFORMS_METADATA,exports.SKILLS=c.SKILLS,exports.SKILLS_METADATA=c.SKILLS_METADATA,exports.detectExportedComponentName=t.detectExportedComponentName,exports.detectFormatCommand=r.detectFormatCommand,exports.getContentDeclarationFileTemplate=i.getContentDeclarationFileTemplate,exports.getInitialSkills=c.getInitialSkills,exports.initIntlayer=s.initIntlayer,exports.installMCP=l.installMCP,exports.installSkills=c.installSkills,exports.listDictionaries=e.listDictionaries,exports.listDictionariesWithStats=e.listDictionariesWithStats,exports.listGitFiles=u.listGitFiles,exports.listGitLines=u.listGitLines,exports.listProjects=d.listProjects,exports.transformJSFile=n.transformJSFile,exports.writeContentDeclaration=o.writeContentDeclaration,exports.writeJSFile=a.writeJSFile;
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getFileHash.cjs`);let t=require(`@intlayer/config/node`),n=require(`node:path`),r=require(`@intlayer/config/utils`);const i=(i,a,o,s=`esm`,c=(0,t.getConfiguration)())=>{let{mainDir:l}=c.system,u=``,d=i.map(t=>({relativePath:(0,r.normalizePath)((0,n.relative)(l,t)),id:(0,n.basename)(t,(0,n.extname)(t)),hash:`_${e.getFileHash(t)}`}));d.forEach(e=>{s===`esm`&&(u+=`import ${e.hash} from '${e.relativePath}'${o===`json`?` with { type: 'json' }`:``};\n`),s===`cjs`&&(u+=`const ${e.hash} = require('${e.relativePath}');\n`)}),u+=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getPathHash.cjs`);let t=require(`@intlayer/config/node`),n=require(`node:path`),r=require(`@intlayer/config/utils`);const i=(i,a,o,s=`esm`,c=(0,t.getConfiguration)())=>{let{mainDir:l}=c.system,u=``,d=i.map(t=>({relativePath:(0,r.normalizePath)((0,n.relative)(l,t)),id:(0,n.basename)(t,(0,n.extname)(t)),hash:`_${e.getPathHash(t)}`}));d.forEach(e=>{s===`esm`&&(u+=`import ${e.hash} from '${e.relativePath}'${o===`json`?` with { type: 'json' }`:``};\n`),s===`cjs`&&(u+=`const ${e.hash} = require('${e.relativePath}');\n`)}),u+=`
2
2
  `;let f=d.map(e=>` "${e.id}": ${e.hash}`).join(`,
3
3
  `);return u+=`const dictionaries = {\n${f}\n};\n`,u+=`const ${a} = () => dictionaries;\n`,s===`esm`&&(u+=`
4
4
  `,u+=`export { ${a} };\n`,u+=`export default dictionaries;
@@ -1 +1 @@
1
- {"version":3,"file":"generateDictionaryListContent.cjs","names":["getFileHash"],"sources":["../../../src/createDictionaryEntryPoint/generateDictionaryListContent.ts"],"sourcesContent":["import { basename, extname, relative } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { getFileHash } from '../utils/getFileHash';\n\n/**\n * This function generates the content of the dictionary list file\n */\nexport const generateDictionaryListContent = (\n dictionaries: string[],\n functionName: string,\n importType: 'json' | 'javascript',\n format: 'cjs' | 'esm' = 'esm',\n configuration = getConfiguration()\n): string => {\n const { mainDir } = configuration.system;\n\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: normalizePath(relative(mainDir, dictionaryPath)),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getFileHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === 'json' ? \" with { type: 'json' }\" : ''};\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n content += `const dictionaries = {\\n${formattedDictionaryMap}\\n};\\n`;\n content += `const ${functionName} = () => dictionaries;\\n`;\n\n if (format === 'esm') {\n content += `\\n`;\n content += `export { ${functionName} };\\n`;\n content += `export default dictionaries;\\n`;\n }\n\n if (format === 'cjs') {\n content += `\\n`;\n content += `module.exports.${functionName} = ${functionName};\\n`;\n content += `module.exports = dictionaries;\\n`;\n }\n\n return content;\n};\n"],"mappings":"8PAQA,MAAa,GACX,EACA,EACA,EACA,EAAwB,MACxB,GAAA,EAAA,EAAA,mBAAkC,GACvB,CACX,GAAM,CAAE,WAAY,EAAc,OAE9B,EAAU,GAER,EAAkB,EAAa,IAAK,IAAoB,CAC5D,cAAA,EAAA,EAAA,gBAAA,EAAA,EAAA,UAAqC,EAAS,EAAe,CAAC,CAC9D,IAAA,EAAA,EAAA,UAAa,GAAA,EAAA,EAAA,SAAwB,EAAe,CAAC,CACrD,KAAM,IAAIA,EAAAA,YAAY,EAAe,GACtC,EAAE,CAGH,EAAgB,QAAS,GAAe,CAClC,IAAW,QACb,GAAW,UAAU,EAAW,KAAK,SAAS,EAAW,aAAa,GAAG,IAAe,OAAS,yBAA2B,GAAG,MAC7H,IAAW,QACb,GAAW,SAAS,EAAW,KAAK,cAAc,EAAW,aAAa,SAC5E,CAEF,GAAW;EAGX,IAAM,EAAiC,EACpC,IAAK,GAAe,MAAM,EAAW,GAAG,KAAK,EAAW,OAAO,CAC/D,KAAK;EAAM,CAiBd,MAfA,IAAW,2BAA2B,EAAuB,QAC7D,GAAW,SAAS,EAAa,0BAE7B,IAAW,QACb,GAAW;EACX,GAAW,YAAY,EAAa,OACpC,GAAW;GAGT,IAAW,QACb,GAAW;EACX,GAAW,kBAAkB,EAAa,KAAK,EAAa,KAC5D,GAAW;GAGN"}
1
+ {"version":3,"file":"generateDictionaryListContent.cjs","names":["getPathHash"],"sources":["../../../src/createDictionaryEntryPoint/generateDictionaryListContent.ts"],"sourcesContent":["import { basename, extname, relative } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { getPathHash } from '../utils/getPathHash';\n\n/**\n * This function generates the content of the dictionary list file\n */\nexport const generateDictionaryListContent = (\n dictionaries: string[],\n functionName: string,\n importType: 'json' | 'javascript',\n format: 'cjs' | 'esm' = 'esm',\n configuration = getConfiguration()\n): string => {\n const { mainDir } = configuration.system;\n\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: normalizePath(relative(mainDir, dictionaryPath)),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getPathHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === 'json' ? \" with { type: 'json' }\" : ''};\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n content += `const dictionaries = {\\n${formattedDictionaryMap}\\n};\\n`;\n content += `const ${functionName} = () => dictionaries;\\n`;\n\n if (format === 'esm') {\n content += `\\n`;\n content += `export { ${functionName} };\\n`;\n content += `export default dictionaries;\\n`;\n }\n\n if (format === 'cjs') {\n content += `\\n`;\n content += `module.exports.${functionName} = ${functionName};\\n`;\n content += `module.exports = dictionaries;\\n`;\n }\n\n return content;\n};\n"],"mappings":"8PAQA,MAAa,GACX,EACA,EACA,EACA,EAAwB,MACxB,GAAA,EAAA,EAAA,mBAAkC,GACvB,CACX,GAAM,CAAE,WAAY,EAAc,OAE9B,EAAU,GAER,EAAkB,EAAa,IAAK,IAAoB,CAC5D,cAAA,EAAA,EAAA,gBAAA,EAAA,EAAA,UAAqC,EAAS,EAAe,CAAC,CAC9D,IAAA,EAAA,EAAA,UAAa,GAAA,EAAA,EAAA,SAAwB,EAAe,CAAC,CACrD,KAAM,IAAIA,EAAAA,YAAY,EAAe,GACtC,EAAE,CAGH,EAAgB,QAAS,GAAe,CAClC,IAAW,QACb,GAAW,UAAU,EAAW,KAAK,SAAS,EAAW,aAAa,GAAG,IAAe,OAAS,yBAA2B,GAAG,MAC7H,IAAW,QACb,GAAW,SAAS,EAAW,KAAK,cAAc,EAAW,aAAa,SAC5E,CAEF,GAAW;EAGX,IAAM,EAAiC,EACpC,IAAK,GAAe,MAAM,EAAW,GAAG,KAAK,EAAW,OAAO,CAC/D,KAAK;EAAM,CAiBd,MAfA,IAAW,2BAA2B,EAAuB,QAC7D,GAAW,SAAS,EAAa,0BAE7B,IAAW,QACb,GAAW;EACX,GAAW,YAAY,EAAa,OACpC,GAAW;GAGT,IAAW,QACb,GAAW;EACX,GAAW,kBAAkB,EAAa,KAAK,EAAa,KAC5D,GAAW;GAGN"}
@@ -1,9 +1,9 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../writeFileIfChanged.cjs`),n=require(`../utils/getFileHash.cjs`);let r=require(`node:fs/promises`),i=require(`node:path`),a=require(`@intlayer/config/utils`),o=require(`fast-glob`);o=e.__toESM(o);let s=require(`zod-to-ts`);const c=e=>`${(0,a.kebabCaseToCamelCase)(e)}Content`,l=e=>e.map(e=>` "${e}": 1;`).join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../writeFileIfChanged.cjs`),n=require(`../utils/getPathHash.cjs`);let r=require(`node:fs/promises`),i=require(`node:path`),a=require(`@intlayer/config/utils`),o=require(`fast-glob`);o=e.__toESM(o);let s=require(`zod-to-ts`);const c=e=>`${(0,a.kebabCaseToCamelCase)(e)}Content`,l=e=>e.map(e=>` "${e}": 1;`).join(`
2
2
  `),u=e=>{if(!e)return`any`;let t=e._def??e.def??e;switch(t.typeName??t.type){case`ZodString`:case`string`:return`string`;case`ZodNumber`:case`number`:return`number`;case`ZodBoolean`:case`boolean`:return`boolean`;case`ZodNull`:case`null`:return`null`;case`ZodUndefined`:case`undefined`:return`undefined`;case`ZodArray`:case`array`:return`${u(t.type??t.element)}[]`;case`ZodObject`:case`object`:{let e=typeof t.shape==`function`?t.shape():t.shape;return e?`{\n${Object.entries(e).map(([e,t])=>` "${e}": ${u(t)};`).join(`
3
3
  `)}\n }`:`Record<string, any>`}case`ZodOptional`:case`optional`:return`${u(t.innerType??t.wrapped)} | undefined`;case`ZodNullable`:case`nullable`:return`${u(t.innerType??t.wrapped)} | null`;case`ZodUnion`:case`union`:return(t.options??[]).map(u).join(` | `);case`ZodIntersection`:case`intersection`:return`${u(t.left)} & ${u(t.right)}`;case`ZodEnum`:case`enum`:return(t.values??[]).map(e=>`"${e}"`).join(` | `);case`ZodLiteral`:case`literal`:{let e=t.value;return typeof e==`string`?`"${e}"`:String(e)}default:return`any`}},d=(e,t)=>{let{internationalization:r,system:a}=t,{moduleAugmentationDir:o}=a,{locales:c,requiredLocales:d,strictMode:f}=r,p=`import "intlayer";
4
- `,m=e.map(e=>({relativePath:`./${(0,i.relative)(o,e)}`,id:(0,i.basename)(e,(0,i.extname)(e)),hash:`_${n.getFileHash(e)}`}));for(let e of m)p+=`import ${e.hash} from '${e.relativePath}';\n`;p+=`
4
+ `,m=e.map(e=>({relativePath:`./${(0,i.relative)(o,e)}`,id:(0,i.basename)(e,(0,i.extname)(e)),hash:`_${n.getPathHash(e)}`}));for(let e of m)p+=`import ${e.hash} from '${e.relativePath}';\n`;p+=`
5
5
  `;let h=m.map(e=>` "${e.id}": typeof ${e.hash};`).join(`
6
- `),g=c,_=d?.length?d.filter(e=>g.includes(e)):g,v=l(g),y=l(_),b=t.schemas??{},x=Object.entries(b).map(([e,t])=>{let n=`any`;if(t)try{let{node:r}=(0,s.zodToTs)(t,e);n=r.kind===133?u(t):(0,s.printNode)(r)}catch{n=u(t)}return` "${e}": ${n};`}).join(`
6
+ `),g=c,_=d?.length?d.filter(e=>g.includes(e)):g,v=l(g),y=l(_),b=t.schemas??{},x=Object.entries(b).map(([e,t])=>{let n=`any`;if(t)try{let{node:e}=(0,s.zodToTs)(t,{auxiliaryTypeStore:(0,s.createAuxiliaryTypeStore)()});n=e.kind===133?u(t):(0,s.printNode)(e)}catch{n=u(t)}return` "${e}": ${n};`}).join(`
7
7
  `),S=f===`strict`?`strict`:f===`inclusive`?`inclusive`:`loose`;return p+=`declare module 'intlayer' {
8
8
  `,p+=` interface __DictionaryRegistry {\n${h}\n }\n\n`,p+=` interface __DeclaredLocalesRegistry {\n${v}\n }\n\n`,p+=` interface __RequiredLocalesRegistry {\n${y}\n }\n\n`,p+=` interface __SchemaRegistry {\n${x}\n }\n\n`,p+=` interface __StrictModeRegistry { mode: '${S}' }\n`,p+=`}
9
9
  `,p},f=async e=>{let{moduleAugmentationDir:n,typesDir:s}=e.system;await(0,r.mkdir)(n,{recursive:!0});let c=d(await(0,o.default)((0,a.normalizePath)(`${s}/*.ts`),{ignore:[`**/*.d.ts`]}),e);await t.writeFileIfChanged((0,i.join)(n,`intlayer.d.ts`),c)};exports.createModuleAugmentation=f,exports.getTypeName=c;
@@ -1 +1 @@
1
- {"version":3,"file":"createModuleAugmentation.cjs","names":["getFileHash","writeFileIfChanged"],"sources":["../../../src/createType/createModuleAugmentation.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { basename, extname, join, relative } from 'node:path';\nimport { kebabCaseToCamelCase, normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig, Locale } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport { printNode, zodToTs } from 'zod-to-ts';\nimport { getFileHash } from '../utils/getFileHash';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\n\nexport const getTypeName = (key: string): string =>\n `${kebabCaseToCamelCase(key)}Content`;\n\n/** Returns lines like: [Locales.FRENCH]: 1; */\nconst formatLocales = (locales: Locale[]) =>\n locales.map((locale) => ` \"${locale}\": 1;`).join('\\n');\n\nconst zodToTsString = (schema: any): string => {\n if (!schema) return 'any';\n\n // Support both real Zod objects (_def) and serialized versions (def or nested)\n const def = schema._def ?? schema.def ?? schema;\n\n // Handle serialized type names (sometimes 'type' instead of 'typeName')\n const typeName = def.typeName ?? def.type;\n\n switch (typeName) {\n case 'ZodString':\n case 'string':\n return 'string';\n case 'ZodNumber':\n case 'number':\n return 'number';\n case 'ZodBoolean':\n case 'boolean':\n return 'boolean';\n case 'ZodNull':\n case 'null':\n return 'null';\n case 'ZodUndefined':\n case 'undefined':\n return 'undefined';\n case 'ZodArray':\n case 'array':\n return `${zodToTsString(def.type ?? def.element)}[]`;\n case 'ZodObject':\n case 'object': {\n const shape = typeof def.shape === 'function' ? def.shape() : def.shape;\n if (!shape) return 'Record<string, any>';\n\n const entries = Object.entries(shape)\n .map(([k, v]) => ` \"${k}\": ${zodToTsString(v)};`)\n .join('\\n');\n return `{\\n${entries}\\n }`;\n }\n case 'ZodOptional':\n case 'optional':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | undefined`;\n case 'ZodNullable':\n case 'nullable':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | null`;\n case 'ZodUnion':\n case 'union': {\n const options = def.options ?? [];\n return options.map(zodToTsString).join(' | ');\n }\n case 'ZodIntersection':\n case 'intersection':\n return `${zodToTsString(def.left)} & ${zodToTsString(def.right)}`;\n case 'ZodEnum':\n case 'enum': {\n const values = def.values ?? [];\n return values.map((v: string) => `\"${v}\"`).join(' | ');\n }\n case 'ZodLiteral':\n case 'literal': {\n const value = def.value;\n return typeof value === 'string' ? `\"${value}\"` : String(value);\n }\n default:\n return 'any';\n }\n};\n\n/** Generate the content of the module augmentation file */\nconst generateTypeIndexContent = (\n typeFiles: string[],\n configuration: IntlayerConfig\n): string => {\n const { internationalization, system } = configuration;\n const { moduleAugmentationDir } = system;\n const { locales, requiredLocales, strictMode } = internationalization;\n\n let fileContent = 'import \"intlayer\";\\n';\n\n // Build dictionary refs\n const dictionariesRef = typeFiles.map((dictionaryPath) => ({\n relativePath: `./${relative(moduleAugmentationDir, dictionaryPath)}`,\n id: basename(dictionaryPath, extname(dictionaryPath)),\n hash: `_${getFileHash(dictionaryPath)}`,\n }));\n\n // Import all dictionaries\n for (const dictionary of dictionariesRef) {\n fileContent += `import ${dictionary.hash} from '${dictionary.relativePath}';\\n`;\n }\n fileContent += '\\n';\n\n // Dictionary map entries (id: typeof <hash>)\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": typeof ${dictionary.hash};`)\n .join('\\n');\n\n // Ensure required ⊆ declared; if empty, default required = declared\n const declared = locales;\n const requiredSanitized = requiredLocales?.length\n ? requiredLocales.filter((requiredLocales) =>\n declared.includes(requiredLocales)\n )\n : declared;\n\n const formattedDeclaredLocales = formatLocales(declared);\n const formattedRequiredLocales = formatLocales(requiredSanitized);\n\n // Build schema registry\n const schemas = configuration.schemas ?? {};\n const formattedSchemas = Object.entries(schemas)\n .map(([key, schema]) => {\n let typeStr = 'any';\n\n if (schema) {\n try {\n const { node } = zodToTs(schema as any, key);\n // 133 is the kind for AnyKeyword in TypeScript\n if ((node as any).kind !== 133) {\n typeStr = printNode(node);\n } else {\n // Fallback to custom string generator if zodToTs returns any\n typeStr = zodToTsString(schema);\n }\n } catch (_e) {\n // Fallback to custom string generator\n typeStr = zodToTsString(schema);\n }\n }\n return ` \"${key}\": ${typeStr};`;\n })\n .join('\\n');\n\n // Choose strict mode registry key\n const strictKey =\n strictMode === 'strict'\n ? 'strict'\n : strictMode === 'inclusive'\n ? 'inclusive'\n : 'loose';\n\n /**\n * Module augmentation that ONLY adds keys to registries.\n * No types/aliases redefined here—avoids merge conflicts.\n */\n fileContent += `declare module 'intlayer' {\\n`;\n // Dictionaries registry\n fileContent += ` interface __DictionaryRegistry {\\n${formattedDictionaryMap}\\n }\\n\\n`;\n // Locales registries\n fileContent += ` interface __DeclaredLocalesRegistry {\\n${formattedDeclaredLocales}\\n }\\n\\n`;\n fileContent += ` interface __RequiredLocalesRegistry {\\n${formattedRequiredLocales}\\n }\\n\\n`;\n // Schema registry\n fileContent += ` interface __SchemaRegistry {\\n${formattedSchemas}\\n }\\n\\n`;\n // Resolved strict mode (narrow the literal at build time)\n fileContent += ` interface __StrictModeRegistry { mode: '${strictKey}' }\\n`;\n fileContent += `}\\n`;\n\n return fileContent;\n};\n\n/** Generate the index file merging all the types */\nexport const createModuleAugmentation = async (\n configuration: IntlayerConfig\n) => {\n const { moduleAugmentationDir, typesDir } = configuration.system;\n\n await mkdir(moduleAugmentationDir, { recursive: true });\n\n const dictionariesTypesDefinitions: string[] = await fg(\n normalizePath(`${typesDir}/*.ts`),\n { ignore: ['**/*.d.ts'] }\n );\n\n const tsContent = generateTypeIndexContent(\n dictionariesTypesDefinitions,\n configuration\n );\n\n const tsFilePath = join(moduleAugmentationDir, 'intlayer.d.ts');\n await writeFileIfChanged(tsFilePath, tsContent);\n};\n"],"mappings":"mWASA,MAAa,EAAe,GAC1B,IAAA,EAAA,EAAA,sBAAwB,EAAI,CAAC,SAGzB,EAAiB,GACrB,EAAQ,IAAK,GAAW,QAAQ,EAAO,OAAO,CAAC,KAAK;EAAK,CAErD,EAAiB,GAAwB,CAC7C,GAAI,CAAC,EAAQ,MAAO,MAGpB,IAAM,EAAM,EAAO,MAAQ,EAAO,KAAO,EAKzC,OAFiB,EAAI,UAAY,EAAI,KAErC,CACE,IAAK,YACL,IAAK,SACH,MAAO,SACT,IAAK,YACL,IAAK,SACH,MAAO,SACT,IAAK,aACL,IAAK,UACH,MAAO,UACT,IAAK,UACL,IAAK,OACH,MAAO,OACT,IAAK,eACL,IAAK,YACH,MAAO,YACT,IAAK,WACL,IAAK,QACH,MAAO,GAAG,EAAc,EAAI,MAAQ,EAAI,QAAQ,CAAC,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AAiC,EACpC,IAAK,GAAe,QAAQ,EAAW,GAAG,YAAY,EAAW,KAAK,GAAG,CACzE,KAAK;EAAK,CAGP,EAAW,EACX,EAAoB,GAAiB,OACvC,EAAgB,OAAQ,GACtB,EAAS,SAAS,EAAgB,CACnC,CACD,EAEE,EAA2B,EAAc,EAAS,CAClD,EAA2B,EAAc,EAAkB,CAG3D,EAAU,EAAc,SAAW,EAAE,CACrC,EAAmB,OAAO,QAAQ,EAAQ,CAC7C,KAAK,CAAC,EAAK,KAAY,CACtB,IAAI,EAAU,MAEd,GAAI,EACF,GAAI,CACF,GAAM,CAAE,SAAA,EAAA,EAAA,SAAiB,EAAe,EAAI,CAE5C,AACE,EADG,EAAa,OAAS,IAIf,EAAc,EAAO,EAH/B,EAAA,EAAA,WAAoB,EAAK,MAKhB,CAEX,EAAU,EAAc,EAAO,CAGnC,MAAO,QAAQ,EAAI,KAAK,EAAQ,IAChC,CACD,KAAK;EAAK,CAGP,EACJ,IAAe,SACX,SACA,IAAe,YACb,YACA,QAkBR,MAZA,IAAe;EAEf,GAAe,uCAAuC,EAAuB,WAE7E,GAAe,4CAA4C,EAAyB,WACpF,GAAe,4CAA4C,EAAyB,WAEpF,GAAe,mCAAmC,EAAiB,WAEnE,GAAe,6CAA6C,EAAU,OACtE,GAAe;EAER,GAII,EAA2B,KACtC,IACG,CACH,GAAM,CAAE,wBAAuB,YAAa,EAAc,OAE1D,MAAA,EAAA,EAAA,OAAY,EAAuB,CAAE,UAAW,GAAM,CAAC,CAOvD,IAAM,EAAY,EAL6B,MAAA,EAAA,EAAA,UAAA,EAAA,EAAA,eAC/B,GAAG,EAAS,OAAO,CACjC,CAAE,OAAQ,CAAC,YAAY,CAAE,CAC1B,CAIC,EACD,CAGD,MAAMC,EAAAA,oBAAAA,EAAAA,EAAAA,MADkB,EAAuB,gBAAgB,CAC1B,EAAU"}
1
+ {"version":3,"file":"createModuleAugmentation.cjs","names":["getPathHash","writeFileIfChanged"],"sources":["../../../src/createType/createModuleAugmentation.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { basename, extname, join, relative } from 'node:path';\nimport { kebabCaseToCamelCase, normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig, Locale } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport { createAuxiliaryTypeStore, printNode, zodToTs } from 'zod-to-ts';\nimport { getPathHash } from '../utils';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\n\nexport const getTypeName = (key: string): string =>\n `${kebabCaseToCamelCase(key)}Content`;\n\n/** Returns lines like: [Locales.FRENCH]: 1; */\nconst formatLocales = (locales: Locale[]) =>\n locales.map((locale) => ` \"${locale}\": 1;`).join('\\n');\n\nconst zodToTsString = (schema: any): string => {\n if (!schema) return 'any';\n\n // Support both real Zod objects (_def) and serialized versions (def or nested)\n const def = schema._def ?? schema.def ?? schema;\n\n // Handle serialized type names (sometimes 'type' instead of 'typeName')\n const typeName = def.typeName ?? def.type;\n\n switch (typeName) {\n case 'ZodString':\n case 'string':\n return 'string';\n case 'ZodNumber':\n case 'number':\n return 'number';\n case 'ZodBoolean':\n case 'boolean':\n return 'boolean';\n case 'ZodNull':\n case 'null':\n return 'null';\n case 'ZodUndefined':\n case 'undefined':\n return 'undefined';\n case 'ZodArray':\n case 'array':\n return `${zodToTsString(def.type ?? def.element)}[]`;\n case 'ZodObject':\n case 'object': {\n const shape = typeof def.shape === 'function' ? def.shape() : def.shape;\n if (!shape) return 'Record<string, any>';\n\n const entries = Object.entries(shape)\n .map(([k, v]) => ` \"${k}\": ${zodToTsString(v)};`)\n .join('\\n');\n return `{\\n${entries}\\n }`;\n }\n case 'ZodOptional':\n case 'optional':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | undefined`;\n case 'ZodNullable':\n case 'nullable':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | null`;\n case 'ZodUnion':\n case 'union': {\n const options = def.options ?? [];\n return options.map(zodToTsString).join(' | ');\n }\n case 'ZodIntersection':\n case 'intersection':\n return `${zodToTsString(def.left)} & ${zodToTsString(def.right)}`;\n case 'ZodEnum':\n case 'enum': {\n const values = def.values ?? [];\n return values.map((v: string) => `\"${v}\"`).join(' | ');\n }\n case 'ZodLiteral':\n case 'literal': {\n const value = def.value;\n return typeof value === 'string' ? `\"${value}\"` : String(value);\n }\n default:\n return 'any';\n }\n};\n\n/** Generate the content of the module augmentation file */\nconst generateTypeIndexContent = (\n typeFiles: string[],\n configuration: IntlayerConfig\n): string => {\n const { internationalization, system } = configuration;\n const { moduleAugmentationDir } = system;\n const { locales, requiredLocales, strictMode } = internationalization;\n\n let fileContent = 'import \"intlayer\";\\n';\n\n // Build dictionary refs\n const dictionariesRef = typeFiles.map((dictionaryPath) => ({\n relativePath: `./${relative(moduleAugmentationDir, dictionaryPath)}`,\n id: basename(dictionaryPath, extname(dictionaryPath)),\n hash: `_${getPathHash(dictionaryPath)}`,\n }));\n\n // Import all dictionaries\n for (const dictionary of dictionariesRef) {\n fileContent += `import ${dictionary.hash} from '${dictionary.relativePath}';\\n`;\n }\n fileContent += '\\n';\n\n // Dictionary map entries (id: typeof <hash>)\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": typeof ${dictionary.hash};`)\n .join('\\n');\n\n // Ensure required ⊆ declared; if empty, default required = declared\n const declared = locales;\n const requiredSanitized = requiredLocales?.length\n ? requiredLocales.filter((requiredLocales) =>\n declared.includes(requiredLocales)\n )\n : declared;\n\n const formattedDeclaredLocales = formatLocales(declared);\n const formattedRequiredLocales = formatLocales(requiredSanitized);\n\n // Build schema registry\n const schemas = configuration.schemas ?? {};\n const formattedSchemas = Object.entries(schemas)\n .map(([key, schema]) => {\n let typeStr = 'any';\n\n if (schema) {\n try {\n const { node } = zodToTs(schema, {\n auxiliaryTypeStore: createAuxiliaryTypeStore(),\n });\n // 133 is the kind for AnyKeyword in TypeScript\n if ((node as any).kind !== 133) {\n typeStr = printNode(node);\n } else {\n // Fallback to custom string generator if zodToTs returns any\n typeStr = zodToTsString(schema);\n }\n } catch (_e) {\n // Fallback to custom string generator\n typeStr = zodToTsString(schema);\n }\n }\n return ` \"${key}\": ${typeStr};`;\n })\n .join('\\n');\n\n // Choose strict mode registry key\n const strictKey =\n strictMode === 'strict'\n ? 'strict'\n : strictMode === 'inclusive'\n ? 'inclusive'\n : 'loose';\n\n /**\n * Module augmentation that ONLY adds keys to registries.\n * No types/aliases redefined here—avoids merge conflicts.\n */\n fileContent += `declare module 'intlayer' {\\n`;\n // Dictionaries registry\n fileContent += ` interface __DictionaryRegistry {\\n${formattedDictionaryMap}\\n }\\n\\n`;\n // Locales registries\n fileContent += ` interface __DeclaredLocalesRegistry {\\n${formattedDeclaredLocales}\\n }\\n\\n`;\n fileContent += ` interface __RequiredLocalesRegistry {\\n${formattedRequiredLocales}\\n }\\n\\n`;\n // Schema registry\n fileContent += ` interface __SchemaRegistry {\\n${formattedSchemas}\\n }\\n\\n`;\n // Resolved strict mode (narrow the literal at build time)\n fileContent += ` interface __StrictModeRegistry { mode: '${strictKey}' }\\n`;\n fileContent += `}\\n`;\n\n return fileContent;\n};\n\n/** Generate the index file merging all the types */\nexport const createModuleAugmentation = async (\n configuration: IntlayerConfig\n) => {\n const { moduleAugmentationDir, typesDir } = configuration.system;\n\n await mkdir(moduleAugmentationDir, { recursive: true });\n\n const dictionariesTypesDefinitions: string[] = await fg(\n normalizePath(`${typesDir}/*.ts`),\n { ignore: ['**/*.d.ts'] }\n );\n\n const tsContent = generateTypeIndexContent(\n dictionariesTypesDefinitions,\n configuration\n );\n\n const tsFilePath = join(moduleAugmentationDir, 'intlayer.d.ts');\n await writeFileIfChanged(tsFilePath, tsContent);\n};\n"],"mappings":"mWASA,MAAa,EAAe,GAC1B,IAAA,EAAA,EAAA,sBAAwB,EAAI,CAAC,SAGzB,EAAiB,GACrB,EAAQ,IAAK,GAAW,QAAQ,EAAO,OAAO,CAAC,KAAK;EAAK,CAErD,EAAiB,GAAwB,CAC7C,GAAI,CAAC,EAAQ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Aa,EAAc,OAE1D,MAAA,EAAA,EAAA,OAAY,EAAuB,CAAE,UAAW,GAAM,CAAC,CAOvD,IAAM,EAAY,EAL6B,MAAA,EAAA,EAAA,UAAA,EAAA,EAAA,eAC/B,GAAG,EAAS,OAAO,CACjC,CAAE,OAAQ,CAAC,YAAY,CAAE,CAC1B,CAIC,EACD,CAGD,MAAMC,EAAAA,oBAAAA,EAAAA,EAAAA,MADkB,EAAuB,gBAAgB,CAC1B,EAAU"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../../_virtual/_rolldown/runtime.cjs`);let e=require(`ts-morph`);const t=(t,n)=>{let r=t.getImportDeclarations().some(e=>e.getModuleSpecifierValue()===n),i=t.getDescendantsOfKind(e.SyntaxKind.CallExpression).some(t=>t.getExpression().getText()===`require`&&t.getArguments()[0]?.asKind(e.SyntaxKind.StringLiteral)?.getLiteralValue()===n);return r||i},n=(e,t)=>t===`cjs`?!0:[`mjs`,`ts`].includes(t)?!1:e.includes(`module.exports`)&&!e.includes(`import `)&&!e.includes(`export `),r=(r,i)=>{let a=new e.Project({useInMemoryFileSystem:!0}).createSourceFile(`vite.config.${i}`,r),o=n(r,i);t(a,`vite-intlayer`)||(o?a.insertVariableStatement(0,{declarationKind:`const`,declarations:[{name:`{ intlayer }`,initializer:`require("vite-intlayer")`}]}):a.addImportDeclaration({moduleSpecifier:`vite-intlayer`,namedImports:[`intlayer`]}));let s,c=a.getExportAssignment(e=>!e.isExportEquals());if(c){let t=c.getExpression();if(t.getKind()===e.SyntaxKind.CallExpression){let n=t.asKind(e.SyntaxKind.CallExpression);if(n?.getExpression().getText()===`defineConfig`){let t=n.getArguments()[0];t?.getKind()===e.SyntaxKind.ObjectLiteralExpression&&(s=t.asKind(e.SyntaxKind.ObjectLiteralExpression))}}else if(t.getKind()===e.SyntaxKind.ObjectLiteralExpression)s=t.asKind(e.SyntaxKind.ObjectLiteralExpression);else if(t.getKind()===e.SyntaxKind.Identifier){let n=t.asKind(e.SyntaxKind.Identifier)?.getDefinitions();if(n&&n.length>0){let t=n[0].getDeclarationNode();if(t?.getKind()===e.SyntaxKind.VariableDeclaration){let n=t.asKind(e.SyntaxKind.VariableDeclaration)?.getInitializer();n?.getKind()===e.SyntaxKind.ObjectLiteralExpression&&(s=n.asKind(e.SyntaxKind.ObjectLiteralExpression))}}}}if(!s){let t=a.getStatements();for(let n of t)if(n.getKind()===e.SyntaxKind.ExpressionStatement){let t=n.asKind(e.SyntaxKind.ExpressionStatement)?.getExpression();if(t?.getKind()===e.SyntaxKind.BinaryExpression){let n=t.asKind(e.SyntaxKind.BinaryExpression);if(n?.getLeft().getText()===`module.exports`&&n.getOperatorToken().getKind()===e.SyntaxKind.EqualsToken){let t=n.getRight();if(t.getKind()===e.SyntaxKind.ObjectLiteralExpression)s=t.asKind(e.SyntaxKind.ObjectLiteralExpression);else if(t.getKind()===e.SyntaxKind.CallExpression){let n=t.asKind(e.SyntaxKind.CallExpression);if(n?.getExpression().getText()===`defineConfig`){let t=n.getArguments()[0];t?.getKind()===e.SyntaxKind.ObjectLiteralExpression&&(s=t.asKind(e.SyntaxKind.ObjectLiteralExpression))}}else if(t.getKind()===e.SyntaxKind.Identifier){let n=t.asKind(e.SyntaxKind.Identifier)?.getDefinitions();if(n&&n.length>0){let t=n[0].getDeclarationNode();if(t?.getKind()===e.SyntaxKind.VariableDeclaration){let n=t.asKind(e.SyntaxKind.VariableDeclaration)?.getInitializer();n?.getKind()===e.SyntaxKind.ObjectLiteralExpression&&(s=n.asKind(e.SyntaxKind.ObjectLiteralExpression))}}}}}}}if(s){let t=s.getProperty(`plugins`);if(t||=(s.addPropertyAssignment({name:`plugins`,initializer:`[]`}),s.getProperty(`plugins`)),t?.getKind()===e.SyntaxKind.PropertyAssignment){let n=t.asKind(e.SyntaxKind.PropertyAssignment)?.getInitializer();if(n?.getKind()===e.SyntaxKind.ArrayLiteralExpression){let t=n.asKind(e.SyntaxKind.ArrayLiteralExpression);t?.getElements().some(e=>e.getText().includes(`intlayer(`))||t?.addElement(`intlayer()`)}}}return a.getFullText()},i=(r,i)=>{let a=new e.Project({useInMemoryFileSystem:!0}).createSourceFile(`next.config.${i}`,r),o=n(r,i);t(a,`next-intlayer/server`)||(o?a.insertVariableStatement(0,{declarationKind:`const`,declarations:[{name:`{ withIntlayer }`,initializer:`require("next-intlayer/server")`}]}):a.addImportDeclaration({moduleSpecifier:`next-intlayer/server`,namedImports:[`withIntlayer`]}));let s=!1,c=a.getExportAssignment(e=>!e.isExportEquals());if(c){let e=c.getExpression();e.getText().includes(`withIntlayer`)||(c.setExpression(`withIntlayer(${e.getText()})`),s=!0)}if(!s){let t=a.getStatements();for(let n of t)if(n.getKind()===e.SyntaxKind.ExpressionStatement){let t=n.asKind(e.SyntaxKind.ExpressionStatement)?.getExpression();if(t?.getKind()===e.SyntaxKind.BinaryExpression){let n=t.asKind(e.SyntaxKind.BinaryExpression);if(n?.getLeft().getText()===`module.exports`&&n.getOperatorToken().getKind()===e.SyntaxKind.EqualsToken){let e=n.getRight();e.getText().includes(`withIntlayer`)||(e.replaceWithText(`withIntlayer(${e.getText()})`),s=!0)}}}}return a.getFullText()};exports.updateNextConfig=i,exports.updateViteConfig=r;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../../_virtual/_rolldown/runtime.cjs`);let t=require(`recast`);t=e.__toESM(t);const n=t.types.builders,r=t.types.namedTypes,i=(e,n)=>{let i=!1;return t.visit(e,{visitImportDeclaration(e){return e.node.source.value===n&&(i=!0),!1},visitCallExpression(e){let{callee:t,arguments:a}=e.node;return r.Identifier.check(t)&&t.name===`require`&&a[0]&&r.StringLiteral.check(a[0])&&a[0].value===n&&(i=!0),!1}}),i},a=(e,t,r,a)=>{if(i(e,a))return;let o=t?n.variableDeclaration(`const`,[n.variableDeclarator(n.objectPattern([n.objectProperty.from({key:n.identifier(r),value:n.identifier(r),shorthand:!0})]),n.callExpression(n.identifier(`require`),[n.stringLiteral(a)]))]):n.importDeclaration([n.importSpecifier(n.identifier(r))],n.stringLiteral(a));e.program.body.unshift(o)},o=(e,i)=>{let o=t.parse(e,{parser:require(`recast/parsers/typescript`)});a(o,i===`cjs`||e.includes(`module.exports`)&&!e.includes(`import `),`intlayer`,`vite-intlayer`);let s=e=>{if(!e||e.type!==`ObjectExpression`&&!r.ObjectExpression.check(e))return;let t=e.properties.find(e=>!e||!e.key?!1:(e.key.name||e.key.value)===`plugins`);t||(t=n.property(`init`,n.identifier(`plugins`),n.arrayExpression([])),e.properties.push(t));let i=t.value;i&&(i.type===`ArrayExpression`||r.ArrayExpression.check(i))&&(i.elements.some(e=>{let t=e?.callee;if(!t)return!1;let n=t.name||t.id?.name;return n===`intlayer`||n===`il`})||i.elements.push(n.callExpression(n.identifier(`intlayer`),[])))};return t.visit(o,{visitExportDefaultDeclaration(e){let t=e.node.declaration;if(r.ObjectExpression.check(t))s(t);else if(r.CallExpression.check(t)&&r.Identifier.check(t.callee)&&t.callee.name===`defineConfig`)r.ObjectExpression.check(t.arguments[0])&&s(t.arguments[0]);else if(r.Identifier.check(t)){let e=t.name;o.program.body.forEach(t=>{r.VariableDeclaration.check(t)&&t.declarations.forEach(t=>{r.VariableDeclarator.check(t)&&r.Identifier.check(t.id)&&t.id.name===e&&r.ObjectExpression.check(t.init)&&s(t.init)})})}return!1},visitAssignmentExpression(e){let{left:n,right:i}=e.node;return r.MemberExpression.check(n)&&t.print(n).code===`module.exports`&&(r.ObjectExpression.check(i)?s(i):r.CallExpression.check(i)&&r.Identifier.check(i.callee)&&i.callee.name===`defineConfig`&&r.ObjectExpression.check(i.arguments[0])&&s(i.arguments[0])),!1}}),t.print(o).code},s=(e,i)=>{let o=t.parse(e,{parser:require(`recast/parsers/typescript`)});return a(o,i===`cjs`||e.includes(`module.exports`),`withIntlayer`,`next-intlayer/server`),t.visit(o,{visitExportDefaultDeclaration(e){let t=e.node.declaration;return r.Expression.check(t)&&!(r.CallExpression.check(t)&&r.Identifier.check(t.callee)&&t.callee.name===`withIntlayer`)&&e.get(`declaration`).replace(n.callExpression(n.identifier(`withIntlayer`),[t])),!1},visitAssignmentExpression(e){let{left:i,right:a}=e.node;return r.MemberExpression.check(i)&&t.print(i).code===`module.exports`&&!(r.CallExpression.check(a)&&r.Identifier.check(a.callee)&&a.callee.name===`withIntlayer`)&&e.get(`right`).replace(n.callExpression(n.identifier(`withIntlayer`),[a])),!1}}),t.print(o).code};exports.updateNextConfig=s,exports.updateViteConfig=o;
2
2
  //# sourceMappingURL=configManipulation.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"configManipulation.cjs","names":["SyntaxKind","Project"],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import {\n type ObjectLiteralExpression,\n Project,\n type SourceFile,\n SyntaxKind,\n} from 'ts-morph';\n\n/**\n * Checks if a module is already imported or required in the source file.\n */\nconst isModuleImported = (\n sourceFile: SourceFile,\n moduleName: string\n): boolean => {\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((i) => i.getModuleSpecifierValue() === moduleName);\n\n const hasRequire = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((c) => {\n const expression = c.getExpression();\n return (\n expression.getText() === 'require' &&\n c\n .getArguments()[0]\n ?.asKind(SyntaxKind.StringLiteral)\n ?.getLiteralValue() === moduleName\n );\n });\n\n return hasImport || hasRequire;\n};\n\n/**\n * Checks if the file should be treated as CommonJS.\n */\nconst isCJS = (content: string, extension: string): boolean => {\n if (extension === 'cjs') return true;\n if (['mjs', 'ts'].includes(extension)) return false;\n\n return (\n content.includes('module.exports') &&\n !content.includes('import ') &&\n !content.includes('export ')\n );\n};\n\n/**\n * Updates a Vite configuration file to include the Intlayer plugin.\n * @param content The content of the vite.config file\n * @param extension The file extension (ts, js, mjs, cjs)\n * @returns The updated content\n */\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\n `vite.config.${extension}`,\n content\n );\n\n const isCJSFile = isCJS(content, extension);\n\n // Add import if missing\n const hasIntlayerImport = isModuleImported(sourceFile, 'vite-intlayer');\n\n if (!hasIntlayerImport) {\n if (isCJSFile) {\n sourceFile.insertVariableStatement(0, {\n declarationKind: 'const' as any,\n declarations: [\n {\n name: '{ intlayer }',\n initializer: 'require(\"vite-intlayer\")',\n },\n ],\n });\n } else {\n sourceFile.addImportDeclaration({\n moduleSpecifier: 'vite-intlayer',\n namedImports: ['intlayer'],\n });\n }\n }\n\n // Find the configuration object\n let configObject: ObjectLiteralExpression | undefined;\n\n // Case: export default defineConfig({...})\n const exportDefault = sourceFile.getExportAssignment(\n (e) => !e.isExportEquals()\n );\n if (exportDefault) {\n const expression = exportDefault.getExpression();\n\n if (expression.getKind() === SyntaxKind.CallExpression) {\n const call = expression.asKind(SyntaxKind.CallExpression);\n\n if (call?.getExpression().getText() === 'defineConfig') {\n const arg = call.getArguments()[0];\n\n if (arg?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = arg.asKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n } else if (expression.getKind() === SyntaxKind.ObjectLiteralExpression) {\n // Case: export default {...}\n configObject = expression.asKind(SyntaxKind.ObjectLiteralExpression);\n } else if (expression.getKind() === SyntaxKind.Identifier) {\n // Case: const config = {...}; export default config;\n const identifier = expression.asKind(SyntaxKind.Identifier);\n const definitions = identifier?.getDefinitions();\n\n if (definitions && definitions.length > 0) {\n const node = definitions[0].getDeclarationNode();\n\n if (node?.getKind() === SyntaxKind.VariableDeclaration) {\n const init = node\n .asKind(SyntaxKind.VariableDeclaration)\n ?.getInitializer();\n\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = init.asKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n }\n }\n }\n\n // Case: module.exports = {...}\n if (!configObject) {\n const expressionStatements = sourceFile.getStatements();\n for (const statement of expressionStatements) {\n if (statement.getKind() === SyntaxKind.ExpressionStatement) {\n const expr = statement\n .asKind(SyntaxKind.ExpressionStatement)\n ?.getExpression();\n\n if (expr?.getKind() === SyntaxKind.BinaryExpression) {\n const binary = expr.asKind(SyntaxKind.BinaryExpression);\n\n if (\n binary?.getLeft().getText() === 'module.exports' &&\n binary.getOperatorToken().getKind() === SyntaxKind.EqualsToken\n ) {\n const right = binary.getRight();\n\n if (right.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = right.asKind(SyntaxKind.ObjectLiteralExpression);\n } else if (right.getKind() === SyntaxKind.CallExpression) {\n // Case: module.exports = defineConfig({...})\n const call = right.asKind(SyntaxKind.CallExpression);\n\n if (call?.getExpression().getText() === 'defineConfig') {\n const arg = call.getArguments()[0];\n\n if (arg?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = arg.asKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n } else if (right.getKind() === SyntaxKind.Identifier) {\n // Case: const config = {...}; module.exports = config;\n const identifier = right.asKind(SyntaxKind.Identifier);\n const definitions = identifier?.getDefinitions();\n\n if (definitions && definitions.length > 0) {\n const node = definitions[0].getDeclarationNode();\n\n if (node?.getKind() === SyntaxKind.VariableDeclaration) {\n const init = node\n .asKind(SyntaxKind.VariableDeclaration)\n ?.getInitializer();\n\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = init.asKind(\n SyntaxKind.ObjectLiteralExpression\n );\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n // 3. Update plugins array\n if (configObject) {\n let pluginsProp = configObject.getProperty('plugins');\n\n if (!pluginsProp) {\n configObject.addPropertyAssignment({\n name: 'plugins',\n initializer: '[]',\n });\n pluginsProp = configObject.getProperty('plugins');\n }\n\n if (pluginsProp?.getKind() === SyntaxKind.PropertyAssignment) {\n const initializer = pluginsProp\n .asKind(SyntaxKind.PropertyAssignment)\n ?.getInitializer();\n\n if (initializer?.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const array = initializer.asKind(SyntaxKind.ArrayLiteralExpression);\n const hasIntlayer = array\n ?.getElements()\n .some((el) => el.getText().includes('intlayer('));\n\n if (!hasIntlayer) {\n array?.addElement('intlayer()');\n }\n }\n }\n }\n\n return sourceFile.getFullText();\n};\n\n/**\n * Updates a Next.js configuration file to wrap the export with withIntlayer.\n * @param content The content of the next.config file\n * @param extension The file extension (ts, js, mjs, cjs)\n * @returns The updated content\n */\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\n `next.config.${extension}`,\n content\n );\n\n const isCJSFile = isCJS(content, extension);\n\n // 1. Add import if missing\n const hasIntlayerImport = isModuleImported(\n sourceFile,\n 'next-intlayer/server'\n );\n\n if (!hasIntlayerImport) {\n if (isCJSFile) {\n sourceFile.insertVariableStatement(0, {\n declarationKind: 'const' as any,\n declarations: [\n {\n name: '{ withIntlayer }',\n initializer: 'require(\"next-intlayer/server\")',\n },\n ],\n });\n } else {\n sourceFile.addImportDeclaration({\n moduleSpecifier: 'next-intlayer/server',\n namedImports: ['withIntlayer'],\n });\n }\n }\n\n // 2. Wrap export\n let updated = false;\n\n // Case: export default ...\n const exportDefault = sourceFile.getExportAssignment(\n (e) => !e.isExportEquals()\n );\n if (exportDefault) {\n const expression = exportDefault.getExpression();\n\n if (!expression.getText().includes('withIntlayer')) {\n exportDefault.setExpression(`withIntlayer(${expression.getText()})`);\n updated = true;\n }\n }\n\n // Case: module.exports = ...\n if (!updated) {\n const expressionStatements = sourceFile.getStatements();\n for (const statement of expressionStatements) {\n if (statement.getKind() === SyntaxKind.ExpressionStatement) {\n const expr = statement\n .asKind(SyntaxKind.ExpressionStatement)\n ?.getExpression();\n\n if (expr?.getKind() === SyntaxKind.BinaryExpression) {\n const binary = expr.asKind(SyntaxKind.BinaryExpression);\n\n if (\n binary?.getLeft().getText() === 'module.exports' &&\n binary.getOperatorToken().getKind() === SyntaxKind.EqualsToken\n ) {\n const right = binary.getRight();\n\n if (!right.getText().includes('withIntlayer')) {\n right.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AW,wBAAwB,EAAG,CACpC,gBAAiB,QACjB,aAAc,CACZ,CACE,KAAM,mBACN,YAAa,kCACd,CACF,CACF,CAAC,CAEF,EAAW,qBAAqB,CAC9B,gBAAiB,uBACjB,aAAc,CAAC,eAAe,CAC/B,CAAC,EAKN,IAAI,EAAU,GAGR,EAAgB,EAAW,oBAC9B,GAAM,CAAC,EAAE,gBAAgB,CAC3B,CACD,GAAI,EAAe,CACjB,IAAM,EAAa,EAAc,eAAe,CAE3C,EAAW,SAAS,CAAC,SAAS,eAAe,GAChD,EAAc,cAAc,gBAAgB,EAAW,SAAS,CAAC,GAAG,CACpE,EAAU,IAKd,GAAI,CAAC,EAAS,CACZ,IAAM,EAAuB,EAAW,eAAe,CACvD,IAAK,IAAM,KAAa,EACtB,GAAI,EAAU,SAAS,GAAKD,EAAAA,WAAW,oBAAqB,CAC1D,IAAM,EAAO,EACV,OAAOA,EAAAA,WAAW,oBAAoB,EACrC,eAAe,CAEnB,GAAI,GAAM,SAAS,GAAKA,EAAAA,WAAW,iBAAkB,CACnD,IAAM,EAAS,EAAK,OAAOA,EAAAA,WAAW,iBAAiB,CAEvD,GACE,GAAQ,SAAS,CAAC,SAAS,GAAK,kBAChC,EAAO,kBAAkB,CAAC,SAAS,GAAKA,EAAAA,WAAW,YACnD,CACA,IAAM,EAAQ,EAAO,UAAU,CAE1B,EAAM,SAAS,CAAC,SAAS,eAAe,GAC3C,EAAM,gBAAgB,gBAAgB,EAAM,SAAS,CAAC,GAAG,CACzD,EAAU,OAQtB,OAAO,EAAW,aAAa"}
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":"kKAEA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,GAAoB,EAAU,IAAgC,CAClE,IAAI,EAAQ,GAuBZ,OAtBA,EAAO,MAAM,EAAK,CAChB,uBAAuB,EAAM,CAI3B,OAHI,EAAK,KAAK,OAAO,QAAU,IAC7B,EAAQ,IAEH,IAET,oBAAoB,EAAM,CACxB,GAAM,CAAE,SAAQ,UAAW,GAAS,EAAK,KAWzC,OARE,EAAE,WAAW,MAAM,EAAO,EAC1B,EAAO,OAAS,WAChB,EAAK,IACL,EAAE,cAAc,MAAM,EAAK,GAAG,EAC9B,EAAK,GAAG,QAAU,IAElB,EAAQ,IAEH,IAEV,CAAC,CACK,GAMH,GACJ,EACA,EACA,EACA,IACG,CACH,GAAI,EAAiB,EAAK,EAAO,CAAE,OAEnC,IAAM,EAAc,EAChB,EAAE,oBAAoB,QAAS,CAC7B,EAAE,mBACA,EAAE,cAAc,CACd,EAAE,eAAe,KAAK,CACpB,IAAK,EAAE,WAAW,EAAW,CAC7B,MAAO,EAAE,WAAW,EAAW,CAC/B,UAAW,GACZ,CAAC,CACH,CAAC,CACF,EAAE,eAAe,EAAE,WAAW,UAAU,CAAE,CAAC,EAAE,cAAc,EAAO,CAAC,CAAC,CACrE,CACF,CAAC,CACF,EAAE,kBACA,CAAC,EAAE,gBAAgB,EAAE,WAAW,EAAW,CAAC,CAAC,CAC7C,EAAE,cAAc,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CAAC,EAAmB,CAAC,CACrE,CAEE,IAET,0BAA0B,EAAM,CAC9B,GAAM,CAAE,OAAM,SAAU,EAAK,KAe7B,OAZE,EAAE,iBAAiB,MAAM,EAAK,EAC9B,EAAO,MAAM,EAAK,CAAC,OAAS,kBAC5B,EACE,EAAE,eAAe,MAAM,EAAM,EAC7B,EAAE,WAAW,MAAM,EAAM,OAAO,EAChC,EAAM,OAAO,OAAS,iBAGxB,EACG,IAAI,QAAQ,CACZ,QAAQ,EAAE,eAAe,EAAE,WAAW,eAAe,CAAE,CAAC,EAAM,CAAC,CAAC,CAE9D,IAEV,CAAC,CAEK,EAAO,MAAM,EAAI,CAAC"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../installSkills/index.cjs`);let n=require(`node:path`);n=e.__toESM(n);let r=require(`node:fs`),i=require(`node:os`);i=e.__toESM(i);const a=process.platform===`win32`?n.default.join(process.env.APPDATA||``,`Claude`,`claude_desktop_config.json`):n.default.join(i.default.homedir(),`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`),o=async(e,i,o)=>{let s,c=`mcpServers`;if(i===`Claude`)s=a;else{let r=n.default.dirname(t.PLATFORMS_METADATA[i].dir);s=n.default.join(e,r,`mcp.json`),i===`VSCode`&&(c=`servers`)}await r.promises.mkdir(n.default.dirname(s),{recursive:!0});let l={};try{let e=await r.promises.readFile(s,`utf-8`);l=JSON.parse(e)}catch{}if(l[c]||(l[c]={}),o===`stdio`){let e={command:`npx`,args:[`-y`,`@intlayer/mcp`]};i===`VSCode`&&(e.type=`stdio`),l[c].intlayer=e}else{let e={url:`https://mcp.intlayer.org`};i===`VSCode`?e.type=`sse`:e.transport=`sse`,l[c].intlayer=e}return await r.promises.writeFile(s,JSON.stringify(l,null,2),`utf-8`),`MCP server configuration updated in ${s}`};exports.installMCP=o;
2
+ //# sourceMappingURL=installMCP.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installMCP.cjs","names":["path","os","PLATFORMS_METADATA","fs"],"sources":["../../../src/installMCP/installMCP.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { PLATFORMS_METADATA, type Platform } from '../installSkills';\n\nexport type MCPTransport = 'stdio' | 'sse';\n\nconst MCP_CONFIG_FILENAME = 'mcp.json';\n\nconst CLAUDE_DESKTOP_CONFIG_PATH =\n process.platform === 'win32'\n ? path.join(\n process.env.APPDATA || '',\n 'Claude',\n 'claude_desktop_config.json'\n )\n : path.join(\n os.homedir(),\n 'Library',\n 'Application Support',\n 'Claude',\n 'claude_desktop_config.json'\n );\n\n/**\n * Installs the Intlayer MCP server configuration for a specific platform.\n */\nexport const installMCP = async (\n projectRoot: string,\n platform: Platform,\n transport: MCPTransport\n): Promise<string> => {\n let configPath: string;\n let configKey = 'mcpServers';\n\n if (platform === 'Claude') {\n configPath = CLAUDE_DESKTOP_CONFIG_PATH;\n } else {\n const relativeDir = path.dirname(PLATFORMS_METADATA[platform].dir); // e.g. .cursor or .vscode\n configPath = path.join(projectRoot, relativeDir, MCP_CONFIG_FILENAME);\n\n if (platform === 'VSCode') {\n configKey = 'servers';\n }\n }\n\n // Ensure the configuration directory exists\n await fs.mkdir(path.dirname(configPath), { recursive: true });\n\n let config: any = {};\n try {\n const content = await fs.readFile(configPath, 'utf-8');\n config = JSON.parse(content);\n } catch {\n // File doesn't exist or is invalid JSON, start fresh\n }\n\n if (!config[configKey]) {\n config[configKey] = {};\n }\n\n if (transport === 'stdio') {\n const mcpConfig: any = {\n command: 'npx',\n args: ['-y', '@intlayer/mcp'],\n };\n\n if (platform === 'VSCode') {\n mcpConfig.type = 'stdio';\n }\n\n config[configKey].intlayer = mcpConfig;\n } else {\n const mcpConfig: any = {\n url: 'https://mcp.intlayer.org',\n };\n\n if (platform === 'VSCode') {\n mcpConfig.type = 'sse';\n } else {\n mcpConfig.transport = 'sse';\n }\n\n config[configKey].intlayer = mcpConfig;\n }\n\n await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8');\n\n return `MCP server configuration updated in ${configPath}`;\n};\n"],"mappings":"uQAOA,MAEM,EACJ,QAAQ,WAAa,QACjBA,EAAAA,QAAK,KACH,QAAQ,IAAI,SAAW,GACvB,SACA,6BACD,CACDA,EAAAA,QAAK,KACHC,EAAAA,QAAG,SAAS,CACZ,UACA,sBACA,SACA,6BACD,CAKM,EAAa,MACxB,EACA,EACA,IACoB,CACpB,IAAI,EACA,EAAY,aAEhB,GAAI,IAAa,SACf,EAAa,MACR,CACL,IAAM,EAAcD,EAAAA,QAAK,QAAQE,EAAAA,mBAAmB,GAAU,IAAI,CAClE,EAAaF,EAAAA,QAAK,KAAK,EAAa,EAAa,WAAoB,CAEjE,IAAa,WACf,EAAY,WAKhB,MAAMG,EAAAA,SAAG,MAAMH,EAAAA,QAAK,QAAQ,EAAW,CAAE,CAAE,UAAW,GAAM,CAAC,CAE7D,IAAI,EAAc,EAAE,CACpB,GAAI,CACF,IAAM,EAAU,MAAMG,EAAAA,SAAG,SAAS,EAAY,QAAQ,CACtD,EAAS,KAAK,MAAM,EAAQ,MACtB,EAQR,GAJK,EAAO,KACV,EAAO,GAAa,EAAE,EAGpB,IAAc,QAAS,CACzB,IAAM,EAAiB,CACrB,QAAS,MACT,KAAM,CAAC,KAAM,gBAAgB,CAC9B,CAEG,IAAa,WACf,EAAU,KAAO,SAGnB,EAAO,GAAW,SAAW,MACxB,CACL,IAAM,EAAiB,CACrB,IAAK,2BACN,CAEG,IAAa,SACf,EAAU,KAAO,MAEjB,EAAU,UAAY,MAGxB,EAAO,GAAW,SAAW,EAK/B,OAFA,MAAMA,EAAAA,SAAG,UAAU,EAAY,KAAK,UAAU,EAAQ,KAAM,EAAE,CAAE,QAAQ,CAEjE,uCAAuC"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../_virtual/_utils_asset.cjs`);let n=require(`node:path`);n=e.__toESM(n);let r=require(`node:fs`),i=require(`@intlayer/core/markdown`);const a={Usage:`How to use Intlayer in your project`,RemoteContent:`How to use Intlayer with Remote/CMS/Server-side content`,Config:`Intlayer configuration documentation`,Content:`Reference for all Intlayer content node types (t, enu, etc.)`,React:`React-specific syntax and hooks usage`,Angular:`Angular-specific syntax and Injectable Function usage`,NextJS:`Next.js-specific usage (Server & Client components)`,Vue:`Vue-specific composables and syntax`,Preact:`Preact-specific syntax and hooks usage`,Solid:`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.`,Svelte:`Svelte-specific stores and syntax`,Astro:`Astro-specific usage and getIntlayer`,CLI:`Intlayer CLI commands and usage`,Compiler:`Intlayer Compiler setup and usage for automatic content extraction without .content files`},o=Object.keys(a),s={},c={Cursor:`.cursor/skills`,Windsurf:`.windsurf/skills`,Trae:`.trae/skills`,OpenCode:`.opencode/skills`,GitHub:`.github/skills`,Claude:`.claude/skills`,VSCode:`.vscode/skills`,Antigravity:`.agent/skills`,Augment:`.augment/skills`,OpenClaw:`skills`,Cline:`.cline/skills`,CodeBuddy:`.codebuddy/skills`,CommandCode:`.commandcode/skills`,Continue:`.continue/skills`,Crush:`.crush/skills`,Droid:`.factory/skills`,Goose:`.goose/skills`,Junie:`.junie/skills`,IFlow:`.iflow/skills`,KiloCode:`.kilocode/skills`,Kiro:`.kiro/skills`,Kode:`.kode/skills`,MCPJam:`.mcpjam/skills`,MistralVibe:`.vibe/skills`,Mux:`.mux/skills`,OpenHands:`.openhands/skills`,Pi:`.pi/skills`,Qoder:`.qoder/skills`,Qwen:`.qwen/skills`,RooCode:`.roo/skills`,TraeCN:`.trae/skills`,Zencoder:`.zencoder/skills`,Neovate:`.neovate/skills`,Pochi:`.pochi/skills`,Other:`skills`},l=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),u=e=>{let n=`./skills/${s[e]??l(e)}.md`;try{return t.readAsset(n)}catch{return console.warn(`Warning: Could not read asset for skill: ${e} at ${n}`),``}},d=()=>{try{return t.readAsset(`./LICENCE.md`)}catch{return console.warn(`Warning: Could not read LICENCE.md asset`),``}},f=async e=>{let t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.statusText}`);return t.text()},p=async(e,t,a)=>{let o=c[t]??`skills`,p=n.default.join(e,o),m=t!==`VSCode`;await r.promises.mkdir(p,{recursive:!0});let h=[],g=d();for(let e of a){let t=`intlayer-${s[e]??l(e)}`,a=u(e);if(!a)continue;let o=Array.from(new Set(a.match(/https:\/\/intlayer\.org\/doc\/[^\s)]+\.md/g)||[]));if(m){let s=n.default.join(p,t),c=n.default.join(s,`references`);await r.promises.mkdir(c,{recursive:!0}),g&&await r.promises.writeFile(n.default.join(s,`LICENCE.md`),g,`utf-8`);let l=a,u=o.map(async t=>{try{let e=await f(t),n=(0,i.getMarkdownMetadata)(e),r=``;return r=Array.isArray(n.slugs)?n.slugs.filter(e=>e!==`doc`).join(`_`):new URL(t).pathname.split(`/`).filter(e=>e&&e!==`doc`).map(e=>e.replace(`.md`,``)).join(`_`),r=r?`${r}.md`:`index.md`,{url:t,localRefPath:`references/${r}`,fileName:r,content:e,success:!0}}catch(n){return console.warn(`Warning: Failed to download ref ${t} for skill ${e}`,n),{url:t,success:!1}}}),d=await Promise.all(u);for(let e of d)e.success&&e.fileName&&e.content&&e.localRefPath&&(await r.promises.writeFile(n.default.join(c,e.fileName),e.content,`utf-8`),l=l.replaceAll(e.url,e.localRefPath));let m=n.default.join(s,`SKILL.md`);await r.promises.writeFile(m,l,`utf-8`),h.push(`${t}/SKILL.md`)}else{let e=`${t}.md`,i=n.default.join(p,e);await r.promises.writeFile(i,a,`utf-8`),h.push(e)}}return h.length===0?`No skill files were created. Check your asset paths.`:`Created ${h.length} skills in ${p}`};exports.SKILLS=o,exports.SKILLS_METADATA=a,exports.installSkills=p;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../_virtual/_utils_asset.cjs`);let n=require(`node:path`);n=e.__toESM(n);let r=require(`node:fs`),i=require(`@intlayer/core/markdown`);const a={Config:`Intlayer configuration documentation`,Content:`Reference for all Intlayer content node types (t, enu, etc.)`,Usage:`How to use Intlayer in your project`,CLI:`Intlayer CLI commands and usage`,Compiler:`Intlayer Compiler setup and usage for automatic content extraction without .content files`,RemoteContent:`How to use Intlayer with Remote/CMS/Server-side content`,NextJS:`Next.js-specific usage (Server & Client components)`,React:`React-specific syntax and hooks usage`,Vue:`Vue-specific composables and syntax`,Svelte:`Svelte-specific stores and syntax`,Angular:`Angular-specific syntax and Injectable Function usage`,Preact:`Preact-specific syntax and hooks usage`,Solid:`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.`,Astro:`Astro-specific usage and getIntlayer`},o=Object.keys(a),s=e=>{let t=[`Usage`,`Content`,`Config`,`CLI`,`Compiler`];return e.next&&t.push(`NextJS`),(e.react||!e.next)&&t.push(`React`),e.preact&&t.push(`Preact`),e[`solid-js`]&&t.push(`Solid`),(e.vue||e.nuxt)&&t.push(`Vue`),(e.svelte||e[`@sveltejs/kit`])&&t.push(`Svelte`),e.astro&&t.push(`Astro`),t},c={Cursor:{label:`Cursor`,dir:`.cursor/skills`,check:()=>process.env.CURSOR===`true`||process.env.TERM_PROGRAM===`cursor`},Windsurf:{label:`Windsurf`,dir:`.windsurf/skills`,check:()=>process.env.WINDSURF===`true`||process.env.TERM_PROGRAM===`windsurf`},Trae:{label:`Trae`,dir:`.trae/skills`,check:()=>process.env.TRAE===`true`||process.env.TERM_PROGRAM===`trae`},TraeCN:{label:`Trae CN`,dir:`.trae/skills`,check:()=>process.env.TRAE_CN===`true`},VSCode:{label:`VS Code`,dir:`.vscode/skills`,check:()=>process.env.VSCODE===`true`||process.env.TERM_PROGRAM===`vscode`},OpenCode:{label:`OpenCode`,dir:`.opencode/skills`,check:()=>process.env.OPENCODE===`true`},Claude:{label:`Claude Code`,dir:`.claude/skills`,check:()=>process.env.CLAUDE===`true`},GitHub:{label:`GitHub Copilot Workspace`,dir:`.github/skills`,check:()=>process.env.GITHUB_ACTIONS===`true`||!!process.env.GITHUB_WORKSPACE},Antigravity:{label:`Antigravity`,dir:`.agent/skills`},Augment:{label:`Augment`,dir:`.augment/skills`},OpenClaw:{label:`OpenClaw`,dir:`skills`},Cline:{label:`Cline`,dir:`.cline/skills`},CodeBuddy:{label:`CodeBuddy`,dir:`.codebuddy/skills`},CommandCode:{label:`Command Code`,dir:`.commandcode/skills`},Continue:{label:`Continue`,dir:`.continue/skills`},Crush:{label:`Crush`,dir:`.crush/skills`},Droid:{label:`Droid`,dir:`.factory/skills`},Goose:{label:`Goose`,dir:`.goose/skills`},IFlow:{label:`iFlow CLI`,dir:`.iflow/skills`},Junie:{label:`Junie`,dir:`.junie/skills`},KiloCode:{label:`Kilo Code`,dir:`.kilocode/skills`},Kiro:{label:`Kiro CLI`,dir:`.kiro/skills`},Kode:{label:`Kode`,dir:`.kode/skills`},MCPJam:{label:`MCPJam`,dir:`.mcpjam/skills`},MistralVibe:{label:`Mistral Vibe`,dir:`.vibe/skills`},Mux:{label:`Mux`,dir:`.mux/skills`},OpenHands:{label:`OpenHands`,dir:`.openhands/skills`},Pi:{label:`Pi`,dir:`.pi/skills`},Qoder:{label:`Qoder`,dir:`.qoder/skills`},Qwen:{label:`Qwen Code`,dir:`.qwen/skills`},RooCode:{label:`Roo Code`,dir:`.roo/skills`},Zencoder:{label:`Zencoder`,dir:`.zencoder/skills`},Neovate:{label:`Neovate`,dir:`.neovate/skills`},Pochi:{label:`Pochi`,dir:`.pochi/skills`},Other:{label:`Other`,dir:`skills`}},l=Object.keys(c),u={},d=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),f=e=>{let n=`./skills/${u[e]??d(e)}.md`;try{return t.readAsset(n)}catch{return console.warn(`Warning: Could not read asset for skill: ${e} at ${n}`),``}},p=()=>{try{return t.readAsset(`./LICENCE.md`)}catch{return console.warn(`Warning: Could not read LICENCE.md asset`),``}},m=async e=>{let t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.statusText}`);return t.text()},h=async(e,t,a)=>{let o=c[t].dir??`skills`,s=n.default.join(e,o);await r.promises.mkdir(s,{recursive:!0});let l=[],h=p();for(let e of a){let t=`intlayer-${u[e]??d(e)}`,a=f(e);if(!a)continue;let o=Array.from(new Set(a.match(/https:\/\/intlayer\.org\/doc\/[^\s)]+\.md/g)||[])),c=n.default.join(s,t),p=n.default.join(c,`references`);await r.promises.mkdir(p,{recursive:!0}),h&&await r.promises.writeFile(n.default.join(c,`LICENCE.md`),h,`utf-8`);let g=a,_=o.map(async t=>{try{let e=await m(t),n=(0,i.getMarkdownMetadata)(e),r=``;return r=Array.isArray(n.slugs)?n.slugs.filter(e=>e!==`doc`).join(`_`):new URL(t).pathname.split(`/`).filter(e=>e&&e!==`doc`).map(e=>e.replace(`.md`,``)).join(`_`),r=r?`${r}.md`:`index.md`,{url:t,localRefPath:`references/${r}`,fileName:r,content:e,success:!0}}catch(n){return console.warn(`Warning: Failed to download ref ${t} for skill ${e}`,n),{url:t,success:!1}}}),v=await Promise.all(_);for(let e of v)e.success&&e.fileName&&e.content&&e.localRefPath&&(await r.promises.writeFile(n.default.join(p,e.fileName),e.content,`utf-8`),g=g.replaceAll(e.url,e.localRefPath));let y=n.default.join(c,`SKILL.md`);await r.promises.writeFile(y,g,`utf-8`),l.push(`${t}/SKILL.md`)}return l.length===0?`No skill files were created. Check your asset paths.`:`Created ${l.length} skills in ${s}`};exports.PLATFORMS=l,exports.PLATFORMS_METADATA=c,exports.SKILLS=o,exports.SKILLS_METADATA=a,exports.getInitialSkills=s,exports.installSkills=h;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readAsset","path","fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\nexport const SKILLS_METADATA = {\n Usage: 'How to use Intlayer in your project',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n React: 'React-specific syntax and hooks usage',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n Vue: 'Vue-specific composables and syntax',\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 Svelte: 'Svelte-specific stores and syntax',\n Astro: 'Astro-specific usage and getIntlayer',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n} as const;\n\nexport const SKILLS = Object.keys(\n SKILLS_METADATA\n) as (keyof typeof SKILLS_METADATA)[];\n\nexport type Skill = (typeof SKILLS)[number];\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 * Configuration for Platform paths to keep code clean.\n */\nconst PLATFORM_DIRS = {\n Cursor: '.cursor/skills',\n Windsurf: '.windsurf/skills',\n Trae: '.trae/skills',\n OpenCode: '.opencode/skills',\n GitHub: '.github/skills',\n Claude: '.claude/skills',\n VSCode: '.vscode/skills', // Fixed: VSCode usually uses .vscode, not .github\n Antigravity: '.agent/skills',\n Augment: '.augment/skills',\n OpenClaw: 'skills',\n Cline: '.cline/skills',\n CodeBuddy: '.codebuddy/skills',\n CommandCode: '.commandcode/skills',\n Continue: '.continue/skills',\n Crush: '.crush/skills',\n Droid: '.factory/skills',\n Goose: '.goose/skills',\n Junie: '.junie/skills',\n IFlow: '.iflow/skills',\n KiloCode: '.kilocode/skills',\n Kiro: '.kiro/skills',\n Kode: '.kode/skills',\n MCPJam: '.mcpjam/skills',\n MistralVibe: '.vibe/skills',\n Mux: '.mux/skills',\n OpenHands: '.openhands/skills',\n Pi: '.pi/skills',\n Qoder: '.qoder/skills',\n Qwen: '.qwen/skills',\n RooCode: '.roo/skills',\n TraeCN: '.trae/skills',\n Zencoder: '.zencoder/skills',\n Neovate: '.neovate/skills',\n Pochi: '.pochi/skills',\n Other: 'skills',\n};\n\nexport type Platform = keyof typeof PLATFORM_DIRS;\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 // 1. Determine destination directory\n const relativeDir = PLATFORM_DIRS[platform] ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n const useAgentStructure = platform !== 'VSCode';\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 if (useAgentStructure) {\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\n .filter((slug) => slug !== 'doc')\n .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 } else {\n // Flat Structure (Generic/VSCode): .../skills/<skill-name>.md\n const fileName = `${skillName}.md`;\n const filePath = path.join(skillsBaseDir, fileName);\n\n await fs.writeFile(filePath, skillContent, 'utf-8');\n createdSkills.push(fileName);\n }\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":"0QAKA,MAAa,EAAkB,CAC7B,MAAO,sCACP,cAAe,0DACf,OAAQ,uCACR,QAAS,+DACT,MAAO,wCACP,QAAS,wDACT,OAAQ,sDACR,IAAK,sCACL,OAAQ,yCACR,MACE,qMACF,OAAQ,oCACR,MAAO,uCACP,IAAK,kCACL,SACE,4FACH,CAEY,EAAS,OAAO,KAC3B,EACD,CAOK,EAAqD,EAAE,CAKvD,EAAgB,CACpB,OAAQ,iBACR,SAAU,mBACV,KAAM,eACN,SAAU,mBACV,OAAQ,iBACR,OAAQ,iBACR,OAAQ,iBACR,YAAa,gBACb,QAAS,kBACT,SAAU,SACV,MAAO,gBACP,UAAW,oBACX,YAAa,sBACb,SAAU,mBACV,MAAO,gBACP,MAAO,kBACP,MAAO,gBACP,MAAO,gBACP,MAAO,gBACP,SAAU,mBACV,KAAM,eACN,KAAM,eACN,OAAQ,iBACR,YAAa,eACb,IAAK,cACL,UAAW,oBACX,GAAI,aACJ,MAAO,gBACP,KAAM,eACN,QAAS,cACT,OAAQ,eACR,SA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,OAJI,EAAc,SAAW,EACpB,uDAGF,WAAW,EAAc,OAAO,aAAa"}
1
+ {"version":3,"file":"index.cjs","names":["readAsset","path","fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\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 `Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":"0QAQA,MAAa,EAAkB,CAC7B,OAAQ,uCACR,QAAS,+DACT,MAAO,sCACP,IAAK,kCACL,SACE,4FACF,cAAe,0DACf,OAAQ,sDACR,MAAO,wCACP,IAAK,sCACL,OAAQ,oCACR,QAAS,wDACT,OAAQ,yCACR,MACE,qMACF,MAAO,uCACR,CAIY,EAAS,OAAO,KAAK,EAAgB,CAErC,EACX,GACqC,CACrC,IAAM,EAA2C,CAC/C,QACA,UACA,SACA,MACA,WACD,CAUD,OARI,EAAK,M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Q,MAAO,GAAG,CAAC,CACtC,KAAK,IAAI,CAId,EAAW,EAAW,GAAG,EAAS,KAAO,WAGlC,CACL,MACA,aAJmB,cAAc,IAKjC,WACA,UACA,QAAS,GACV,OACM,EAAO,CAKd,OAJA,QAAQ,KACN,mCAAmC,EAAI,aAAa,IACpD,EACD,CACM,CAAE,MAAK,QAAS,GAAO,GAEhC,CAEI,EAAU,MAAM,QAAQ,IAAI,EAAiB,CAGnD,IAAK,IAAM,KAAO,EACZ,EAAI,SAAW,EAAI,UAAY,EAAI,SAAW,EAAI,eAEpD,MAAMC,EAAAA,SAAG,UACPD,EAAAA,QAAK,KAAK,EAAc,EAAI,SAAS,CACrC,EAAI,QACJ,QACD,CAGD,EAAsB,EAAoB,WACxC,EAAI,IACJ,EAAI,aACL,EAKL,IAAM,EAAWA,EAAAA,QAAK,KAAK,EAAU,WAAW,CAChD,MAAMC,EAAAA,SAAG,UAAU,EAAU,EAAqB,QAAQ,CAC1D,EAAc,KAAK,GAAG,EAAU,WAAW,CAO7C,OAJI,EAAc,SAAW,EACpB,uDAGF,WAAW,EAAc,OAAO,aAAa"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../fetchDistantDictionaries.cjs`),t=require(`../utils/sortAlphabetically.cjs`);let n=require(`@intlayer/config/node`),r=require(`@intlayer/api`),i=require(`@intlayer/remote-dictionaries-entry`);const a=e=>e.map(e=>({...e,localId:`${e.key}::remote::${e.id}`,location:`remote`})),o=async(o=(0,n.getConfiguration)(),s,c)=>{let{editor:l}=o,u=(0,i.getRemoteDictionaries)(o);if(!(l.clientId&&l.clientSecret))return[];try{c?.onStartRemoteCheck?.();let n=(await(0,r.getIntlayerAPIProxy)(void 0,o).dictionary.getDictionariesUpdateTimestamp()).data;if(!n)throw Error(`No distant dictionaries found`);let i=Object.entries(n).filter(([e,t])=>{if(!t.updatedAt)return!0;let n=u[t.key]?.find(t=>t.id===e);if(!n)return!0;let r=n?.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`?t.updatedAt>i:!0}),l=Object.values(u).flat().filter(e=>{let t=n[e.id].updatedAt,r=e.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`&&typeof t==`number`&&i>=t});l.length>0&&s?.(l.map(e=>({dictionaryKey:e.key,type:`remote`,status:`imported`})));let d=i.map(([,e])=>e.key).sort(t.sortAlphabetically);d.length>0&&s?.(d.map(e=>({dictionaryKey:e,type:`remote`,status:`pending`})));let f=a(await e.fetchDistantDictionaries({dictionaryKeys:d},s));return[...l,...f]}catch(e){return c?.onError?.(e),[]}finally{c?.onStopRemoteCheck?.()}};exports.formatDistantDictionaries=a,exports.loadRemoteDictionaries=o;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/sortAlphabetically.cjs`),t=require(`../fetchDistantDictionaries.cjs`);let n=require(`@intlayer/config/node`),r=require(`@intlayer/api`),i=require(`@intlayer/remote-dictionaries-entry`);const a=e=>e.map(e=>({...e,localId:`${e.key}::remote::${e.id}`,location:`remote`})),o=async(o=(0,n.getConfiguration)(),s,c)=>{let{editor:l}=o,u=(0,i.getRemoteDictionaries)(o);if(!(l.clientId&&l.clientSecret))return[];try{c?.onStartRemoteCheck?.();let n=(await(0,r.getIntlayerAPIProxy)(void 0,o).dictionary.getDictionariesUpdateTimestamp()).data;if(!n)throw Error(`No distant dictionaries found`);let i=Object.entries(n).filter(([e,t])=>{if(!t.updatedAt)return!0;let n=u[t.key]?.find(t=>t.id===e);if(!n)return!0;let r=n?.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`?t.updatedAt>i:!0}),l=Object.values(u).flat().filter(e=>{let t=n[e.id].updatedAt,r=e.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`&&typeof t==`number`&&i>=t});l.length>0&&s?.(l.map(e=>({dictionaryKey:e.key,type:`remote`,status:`imported`})));let d=i.map(([,e])=>e.key).sort(e.sortAlphabetically);d.length>0&&s?.(d.map(e=>({dictionaryKey:e,type:`remote`,status:`pending`})));let f=a(await t.fetchDistantDictionaries({dictionaryKeys:d},s));return[...l,...f]}catch(e){return c?.onError?.(e),[]}finally{c?.onStopRemoteCheck?.()}};exports.formatDistantDictionaries=a,exports.loadRemoteDictionaries=o;
2
2
  //# sourceMappingURL=loadRemoteDictionaries.cjs.map
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/config/client`),n=require(`@intlayer/config/built`);n=e.__toESM(n);var r=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=t.spinnerFrames;isFinished=!1;prefix;lastRenderedState=``;remoteCheckInProgress=!1;expectRemote=!1;remoteError;pluginTotal=0;pluginDone=0;pluginError;constructor(){this.prefix=n.default?.log?.prefix??``}setExpectRemote(e){this.expectRemote=e}startRemoteCheck(){this.isFinished||(this.remoteCheckInProgress=!0,this.startSpinner(),this.render())}stopRemoteCheck(){this.remoteCheckInProgress=!1}update(e){if(this.isFinished)return;for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey&&e.type===t.type);e>=0?this.statuses[e]=t:this.statuses.push(t)}let{remoteTotal:t}=this.computeProgress();this.expectRemote&&!this.remoteCheckInProgress&&t===0||(this.startSpinner(),this.render())}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}setRemoteError=e=>{this.remoteError=(0,t.extractErrorMessage)(e),this.stopRemoteCheck(),this.render()};setPluginTotal(e){this.isFinished||(this.pluginTotal=e,e>0&&this.startSpinner(),this.render())}setPluginDone(e){this.isFinished||(this.pluginDone=e,this.render())}setPluginError(e){this.isFinished||(this.pluginError=(0,t.extractErrorMessage)(e),this.render())}render(){let{localTotal:e,localDone:n,remoteTotal:r,remoteDone:i,pluginTotal:a,pluginDone:o}=this.computeProgress(),s=this.spinnerFrames[this.spinnerIndex],c=(0,t.colorize)(s,t.ANSIColors.BLUE),l=[],u=n===e,d=i===r,f=o===a;this.expectRemote&&this.remoteCheckInProgress&&r===0||(u?l.push(`${this.prefix} ${t.v} Local content: ${(0,t.colorize)(`${n}`,t.ANSIColors.GREEN)}${(0,t.colorize)(`/${e}`,t.ANSIColors.GREY)}`):l.push(`${this.prefix} ${c} Local content: ${(0,t.colorize)(`${n}`,t.ANSIColors.BLUE)}${(0,t.colorize)(`/${e}`,t.ANSIColors.GREY)}`)),(r>0||this.remoteCheckInProgress||this.remoteError)&&(this.remoteError?l.push(`${this.prefix} ${t.x} Remote content: ${(0,t.colorize)(this.remoteError,t.ANSIColors.RED)}`):r===0?l.push(`${this.prefix} ${c} Remote content: ${(0,t.colorize)(`Check server`,t.ANSIColors.BLUE)}`):d?l.push(`${this.prefix} ${t.v} Remote content: ${(0,t.colorize)(`${i}`,t.ANSIColors.GREEN)}${(0,t.colorize)(`/${r}`,t.ANSIColors.GREY)}`):l.push(`${this.prefix} ${c} Remote content: ${(0,t.colorize)(`${i}`,t.ANSIColors.BLUE)}${(0,t.colorize)(`/${r}`,t.ANSIColors.GREY)}`)),(a>0||this.pluginError)&&(this.pluginError?l.push(`${this.prefix} ${t.x} Plugin content: ${(0,t.colorize)(this.pluginError,t.ANSIColors.RED)}`):f?l.push(`${this.prefix} ${t.v} Plugin content: ${(0,t.colorize)(`${o}`,t.ANSIColors.GREEN)}${(0,t.colorize)(`/${a}`,t.ANSIColors.GREY)}`):l.push(`${this.prefix} ${c} Plugin content: ${(0,t.colorize)(`${o}`,t.ANSIColors.BLUE)}${(0,t.colorize)(`/${a}`,t.ANSIColors.GREY)}`));let p=l.join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/config/client`),n=require(`@intlayer/config/built`);n=e.__toESM(n);var r=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=t.spinnerFrames;isFinished=!1;prefix;lastRenderedState=``;remoteCheckInProgress=!1;expectRemote=!1;remoteError;pluginTotal=0;pluginDone=0;pluginError;constructor(){this.prefix=(0,t.getPrefix)(n.default?.log?.prefix)??``}setExpectRemote(e){this.expectRemote=e}startRemoteCheck(){this.isFinished||(this.remoteCheckInProgress=!0,this.startSpinner(),this.render())}stopRemoteCheck(){this.remoteCheckInProgress=!1}update(e){if(this.isFinished)return;for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey&&e.type===t.type);e>=0?this.statuses[e]=t:this.statuses.push(t)}let{remoteTotal:t}=this.computeProgress();this.expectRemote&&!this.remoteCheckInProgress&&t===0||(this.startSpinner(),this.render())}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}setRemoteError=e=>{this.remoteError=(0,t.extractErrorMessage)(e),this.stopRemoteCheck(),this.render()};setPluginTotal(e){this.isFinished||(this.pluginTotal=e,e>0&&this.startSpinner(),this.render())}setPluginDone(e){this.isFinished||(this.pluginDone=e,this.render())}setPluginError(e){this.isFinished||(this.pluginError=(0,t.extractErrorMessage)(e),this.render())}render(){let{localTotal:e,localDone:n,remoteTotal:r,remoteDone:i,pluginTotal:a,pluginDone:o}=this.computeProgress(),s=this.spinnerFrames[this.spinnerIndex],c=(0,t.colorize)(s,t.ANSIColors.BLUE),l=[],u=n===e,d=i===r,f=o===a;this.expectRemote&&this.remoteCheckInProgress&&r===0||(u?l.push(`${this.prefix} ${t.v} Local content: ${(0,t.colorize)(`${n}`,t.ANSIColors.GREEN)}${(0,t.colorize)(`/${e}`,t.ANSIColors.GREY)}`):l.push(`${this.prefix} ${c} Local content: ${(0,t.colorize)(`${n}`,t.ANSIColors.BLUE)}${(0,t.colorize)(`/${e}`,t.ANSIColors.GREY)}`)),(r>0||this.remoteCheckInProgress||this.remoteError)&&(this.remoteError?l.push(`${this.prefix} ${t.x} Remote content: ${(0,t.colorize)(this.remoteError,t.ANSIColors.RED)}`):r===0?l.push(`${this.prefix} ${c} Remote content: ${(0,t.colorize)(`Check server`,t.ANSIColors.BLUE)}`):d?l.push(`${this.prefix} ${t.v} Remote content: ${(0,t.colorize)(`${i}`,t.ANSIColors.GREEN)}${(0,t.colorize)(`/${r}`,t.ANSIColors.GREY)}`):l.push(`${this.prefix} ${c} Remote content: ${(0,t.colorize)(`${i}`,t.ANSIColors.BLUE)}${(0,t.colorize)(`/${r}`,t.ANSIColors.GREY)}`)),(a>0||this.pluginError)&&(this.pluginError?l.push(`${this.prefix} ${t.x} Plugin content: ${(0,t.colorize)(this.pluginError,t.ANSIColors.RED)}`):f?l.push(`${this.prefix} ${t.v} Plugin content: ${(0,t.colorize)(`${o}`,t.ANSIColors.GREEN)}${(0,t.colorize)(`/${a}`,t.ANSIColors.GREY)}`):l.push(`${this.prefix} ${c} Plugin content: ${(0,t.colorize)(`${o}`,t.ANSIColors.BLUE)}${(0,t.colorize)(`/${a}`,t.ANSIColors.GREY)}`));let p=l.join(`
2
2
  `);if(p===this.lastRenderedState)return;this.lastRenderedState=p,this.renderedLines>0&&process.stdout.write(`\x1b[${this.renderedLines}F`);let m=Math.max(this.renderedLines,l.length);for(let e=0;e<m;e++){process.stdout.write(`\x1B[2K`);let t=l[e];t!==void 0&&process.stdout.write(t),process.stdout.write(`
3
3
  `)}this.renderedLines=l.length}computeProgress(){let e=new Set(this.statuses.filter(e=>e.type===`local`).map(e=>e.dictionaryKey)),t=new Set(this.statuses.filter(e=>e.type===`local`&&(e.status===`built`||e.status===`error`)).map(e=>e.dictionaryKey)),n=new Set(this.statuses.filter(e=>e.type===`remote`).map(e=>e.dictionaryKey)),r=new Set(this.statuses.filter(e=>e.type===`remote`&&(e.status===`fetched`||e.status===`imported`||e.status===`error`)).map(e=>e.dictionaryKey));return{localTotal:e.size,localDone:t.size,remoteTotal:n.size,remoteDone:r.size,pluginTotal:this.pluginTotal,pluginDone:this.pluginDone}}};exports.DictionariesLogger=r;
4
4
  //# sourceMappingURL=log.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"log.cjs","names":["spinnerFrames","configuration","ANSIColors","v","x"],"sources":["../../../src/loadDictionaries/log.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport {\n ANSIColors,\n colorize,\n extractErrorMessage,\n spinnerFrames,\n v,\n x,\n} from '@intlayer/config/client';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport class DictionariesLogger {\n private statuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n private remoteCheckInProgress = false;\n private expectRemote = false;\n private remoteError: string | undefined;\n private pluginTotal = 0;\n private pluginDone = 0;\n private pluginError: string | undefined;\n\n constructor() {\n this.prefix = configuration?.log?.prefix ?? '';\n }\n\n setExpectRemote(expect: boolean) {\n this.expectRemote = expect;\n }\n\n startRemoteCheck() {\n if (this.isFinished) return;\n this.remoteCheckInProgress = true;\n this.startSpinner();\n this.render();\n }\n\n stopRemoteCheck() {\n this.remoteCheckInProgress = false;\n }\n\n update(newStatuses: DictionariesStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) =>\n s.dictionaryKey === status.dictionaryKey && s.type === status.type\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n // If we expect remote fetch later, avoid rendering a local-only line first\n const { remoteTotal } = this.computeProgress();\n if (this.expectRemote && !this.remoteCheckInProgress && remoteTotal === 0) {\n // Do not start spinner or render yet; wait until remote check starts\n return;\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n // Render final state and keep it visible\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n public setRemoteError = (error?: Error) => {\n this.remoteError = extractErrorMessage(error);\n // Avoid rendering a transient remote-only line while the remote check flag is still true\n // Ensure local + remote are rendered together after a failure\n this.stopRemoteCheck();\n this.render();\n };\n\n setPluginTotal(total: number) {\n if (this.isFinished) return;\n this.pluginTotal = total;\n if (total > 0) {\n this.startSpinner();\n }\n this.render();\n }\n\n setPluginDone(done: number) {\n if (this.isFinished) return;\n this.pluginDone = done;\n this.render();\n }\n\n setPluginError(error?: Error) {\n if (this.isFinished) return;\n this.pluginError = extractErrorMessage(error);\n this.render();\n }\n\n private render() {\n const {\n localTotal,\n localDone,\n remoteTotal,\n remoteDone,\n pluginTotal,\n pluginDone,\n } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const clock = colorize(frame, ANSIColors.BLUE);\n const lines: string[] = [];\n\n const isLocalDone = localDone === localTotal;\n const isRemoteDone = remoteDone === remoteTotal;\n const isPluginDone = pluginDone === pluginTotal;\n\n const suppressLocalWhileCheckingRemote =\n this.expectRemote && this.remoteCheckInProgress && remoteTotal === 0;\n\n if (!suppressLocalWhileCheckingRemote) {\n if (isLocalDone) {\n lines.push(\n `${this.prefix} ${v} Local content: ${colorize(`${localDone}`, ANSIColors.GREEN)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Local content: ${colorize(`${localDone}`, ANSIColors.BLUE)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Single remote line: show error, check, or progress counts\n if (remoteTotal > 0 || this.remoteCheckInProgress || this.remoteError) {\n if (this.remoteError) {\n lines.push(\n `${this.prefix} ${x} Remote content: ${colorize(\n this.remoteError,\n ANSIColors.RED\n )}`\n );\n } else if (remoteTotal === 0) {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize('Check server', ANSIColors.BLUE)}`\n );\n } else if (isRemoteDone) {\n lines.push(\n `${this.prefix} ${v} Remote content: ${colorize(`${remoteDone}`, ANSIColors.GREEN)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize(`${remoteDone}`, ANSIColors.BLUE)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Plugin line: show error or progress counts\n if (pluginTotal > 0 || this.pluginError) {\n if (this.pluginError) {\n lines.push(\n `${this.prefix} ${x} Plugin content: ${colorize(\n this.pluginError,\n ANSIColors.RED\n )}`\n );\n } else if (isPluginDone) {\n lines.push(\n `${this.prefix} ${v} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.GREEN)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.BLUE)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Check if the state has changed to avoid duplicate rendering\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const localKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'local')\n .map((s) => s.dictionaryKey)\n );\n\n const localDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'local' && (s.status === 'built' || s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n const remoteKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'remote')\n .map((s) => s.dictionaryKey)\n );\n\n const remoteDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'remote' &&\n (s.status === 'fetched' ||\n s.status === 'imported' ||\n s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n return {\n localTotal: localKeys.size,\n localDone: localDoneKeys.size,\n remoteTotal: remoteKeys.size,\n remoteDone: remoteDoneKeys.size,\n pluginTotal: this.pluginTotal,\n pluginDone: this.pluginDone,\n } as const;\n }\n}\n"],"mappings":"oNAWA,IAAa,EAAb,KAAgC,CAC9B,SAAyC,EAAE,CAC3C,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,OACA,kBAAoC,GACpC,sBAAgC,GAChC,aAAuB,GACvB,YACA,YAAsB,EACtB,WAAqB,EACrB,YAEA,aAAc,CACZ,KAAK,OAASC,EAAAA,SAAe,KAAK,QAAU,GAG9C,gBAAgB,EAAiB,CAC/B,KAAK,aAAe,EAGtB,kBAAmB,CACb,KAAK,aACT,KAAK,sBAAwB,GAC7B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,iBAAkB,CAChB,KAAK,sBAAwB,GAG/B,OAAO,EAAmC,CACxC,GAAI,KAAK,WAAY,OACrB,IAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,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AY,EAAe,KAC3B,YAAa,KAAK,YAClB,WAAY,KAAK,WAClB"}
1
+ {"version":3,"file":"log.cjs","names":["spinnerFrames","configuration","ANSIColors","v","x"],"sources":["../../../src/loadDictionaries/log.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport {\n ANSIColors,\n colorize,\n extractErrorMessage,\n getPrefix,\n spinnerFrames,\n v,\n x,\n} from '@intlayer/config/client';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport class DictionariesLogger {\n private statuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n private remoteCheckInProgress = false;\n private expectRemote = false;\n private remoteError: string | undefined;\n private pluginTotal = 0;\n private pluginDone = 0;\n private pluginError: string | undefined;\n\n constructor() {\n this.prefix = getPrefix(configuration?.log?.prefix) ?? '';\n }\n\n setExpectRemote(expect: boolean) {\n this.expectRemote = expect;\n }\n\n startRemoteCheck() {\n if (this.isFinished) return;\n this.remoteCheckInProgress = true;\n this.startSpinner();\n this.render();\n }\n\n stopRemoteCheck() {\n this.remoteCheckInProgress = false;\n }\n\n update(newStatuses: DictionariesStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) =>\n s.dictionaryKey === status.dictionaryKey && s.type === status.type\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n // If we expect remote fetch later, avoid rendering a local-only line first\n const { remoteTotal } = this.computeProgress();\n if (this.expectRemote && !this.remoteCheckInProgress && remoteTotal === 0) {\n // Do not start spinner or render yet; wait until remote check starts\n return;\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n // Render final state and keep it visible\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n public setRemoteError = (error?: Error) => {\n this.remoteError = extractErrorMessage(error);\n // Avoid rendering a transient remote-only line while the remote check flag is still true\n // Ensure local + remote are rendered together after a failure\n this.stopRemoteCheck();\n this.render();\n };\n\n setPluginTotal(total: number) {\n if (this.isFinished) return;\n this.pluginTotal = total;\n if (total > 0) {\n this.startSpinner();\n }\n this.render();\n }\n\n setPluginDone(done: number) {\n if (this.isFinished) return;\n this.pluginDone = done;\n this.render();\n }\n\n setPluginError(error?: Error) {\n if (this.isFinished) return;\n this.pluginError = extractErrorMessage(error);\n this.render();\n }\n\n private render() {\n const {\n localTotal,\n localDone,\n remoteTotal,\n remoteDone,\n pluginTotal,\n pluginDone,\n } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const clock = colorize(frame, ANSIColors.BLUE);\n const lines: string[] = [];\n\n const isLocalDone = localDone === localTotal;\n const isRemoteDone = remoteDone === remoteTotal;\n const isPluginDone = pluginDone === pluginTotal;\n\n const suppressLocalWhileCheckingRemote =\n this.expectRemote && this.remoteCheckInProgress && remoteTotal === 0;\n\n if (!suppressLocalWhileCheckingRemote) {\n if (isLocalDone) {\n lines.push(\n `${this.prefix} ${v} Local content: ${colorize(`${localDone}`, ANSIColors.GREEN)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Local content: ${colorize(`${localDone}`, ANSIColors.BLUE)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Single remote line: show error, check, or progress counts\n if (remoteTotal > 0 || this.remoteCheckInProgress || this.remoteError) {\n if (this.remoteError) {\n lines.push(\n `${this.prefix} ${x} Remote content: ${colorize(\n this.remoteError,\n ANSIColors.RED\n )}`\n );\n } else if (remoteTotal === 0) {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize('Check server', ANSIColors.BLUE)}`\n );\n } else if (isRemoteDone) {\n lines.push(\n `${this.prefix} ${v} Remote content: ${colorize(`${remoteDone}`, ANSIColors.GREEN)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize(`${remoteDone}`, ANSIColors.BLUE)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Plugin line: show error or progress counts\n if (pluginTotal > 0 || this.pluginError) {\n if (this.pluginError) {\n lines.push(\n `${this.prefix} ${x} Plugin content: ${colorize(\n this.pluginError,\n ANSIColors.RED\n )}`\n );\n } else if (isPluginDone) {\n lines.push(\n `${this.prefix} ${v} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.GREEN)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.BLUE)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Check if the state has changed to avoid duplicate rendering\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const localKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'local')\n .map((s) => s.dictionaryKey)\n );\n\n const localDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'local' && (s.status === 'built' || s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n const remoteKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'remote')\n .map((s) => s.dictionaryKey)\n );\n\n const remoteDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'remote' &&\n (s.status === 'fetched' ||\n s.status === 'imported' ||\n s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n return {\n localTotal: localKeys.size,\n localDone: localDoneKeys.size,\n remoteTotal: remoteKeys.size,\n remoteDone: remoteDoneKeys.size,\n pluginTotal: this.pluginTotal,\n pluginDone: this.pluginDone,\n } as const;\n }\n}\n"],"mappings":"oNAYA,IAAa,EAAb,KAAgC,CAC9B,SAAyC,EAAE,CAC3C,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,OACA,kBAAoC,GACpC,sBAAgC,GAChC,aAAuB,GACvB,YACA,YAAsB,EACtB,WAAqB,EACrB,YAEA,aAAc,CACZ,KAAK,QAAA,EAAA,EAAA,WAAmBC,EAAAA,SAAe,KAAK,OAAO,EAAI,GAGzD,gBAAgB,EAAiB,CAC/B,KAAK,aAAe,EAGtB,kBAAmB,CACb,KAAK,aACT,KAAK,sBAAwB,GAC7B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,iBAAkB,CAChB,KAAK,sBAAwB,GAG/B,OAAO,EAAmC,CACxC,GAAI,KAAK,WAAY,OACrB,IAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,SAAS,UACzB,GACC,EAAE,gBAAkB,EAAO,eAAiB,EAAE,OAAS,EAAO,KACjE,CACG,GAAS,EACX,KAAK,SAAS,GAAS,EAEvB,KAAK,SAAS,KAAK,EAAO,CAK9B,GAAM,CAAE,eAAgB,KAAK,iBAAiB,CAC1C,KAAK,cAAgB,CAAC,KAAK,uBAAyB,IAAgB,IAKxE,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,QAAS,CACP,KAAK,WAAa,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AK,kBAAoB,EAErB,KAAK,cAAgB,GACvB,QAAQ,OAAO,MAAM,QAAQ,KAAK,cAAc,GAAG,CAGrD,IAAM,EAAoB,KAAK,IAAI,KAAK,cAAe,EAAM,OAAO,CACpE,IAAK,IAAI,EAAI,EAAG,EAAI,EAAmB,IAAK,CAC1C,QAAQ,OAAO,MAAM,UAAU,CAC/B,IAAM,EAAO,EAAM,GACf,IAAS,IAAA,IACX,QAAQ,OAAO,MAAM,EAAK,CAE5B,QAAQ,OAAO,MAAM;EAAK,CAG5B,KAAK,cAAgB,EAAM,OAG7B,iBAA0B,CACxB,IAAM,EAAY,IAAI,IACpB,KAAK,SACF,OAAQ,GAAM,EAAE,OAAS,QAAQ,CACjC,IAAK,GAAM,EAAE,cAAc,CAC/B,CAEK,EAAgB,IAAI,IACxB,KAAK,SACF,OACE,GACC,EAAE,OAAS,UAAY,EAAE,SAAW,SAAW,EAAE,SAAW,SAC/D,CACA,IAAK,GAAM,EAAE,cAAc,CAC/B,CAEK,EAAa,IAAI,IACrB,KAAK,SACF,OAAQ,GAAM,EAAE,OAAS,SAAS,CAClC,IAAK,GAAM,EAAE,cAAc,CAC/B,CAEK,EAAiB,IAAI,IACzB,KAAK,SACF,OACE,GACC,EAAE,OAAS,WACV,EAAE,SAAW,WACZ,EAAE,SAAW,YACb,EAAE,SAAW,SAClB,CACA,IAAK,GAAM,EAAE,cAAc,CAC/B,CAED,MAAO,CACL,WAAY,EAAU,KACtB,UAAW,EAAc,KACzB,YAAa,EAAW,KACxB,WAAY,EAAe,KAC3B,YAAa,KAAK,YAClB,WAAY,KAAK,WAClB"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./_virtual/_rolldown/runtime.cjs`),t=require(`./buildIntlayerDictionary/buildIntlayerDictionary.cjs`),n=require(`./cleanOutputDir.cjs`),r=require(`./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs`),i=require(`./createType/createModuleAugmentation.cjs`),a=require(`./createType/createType.cjs`),o=require(`./loadDictionaries/loadDictionaries.cjs`),s=require(`./buildIntlayerDictionary/writeRemoteDictionary.cjs`),c=require(`./listDictionariesPath.cjs`),l=require(`./utils/runOnce.cjs`),u=require(`./writeConfiguration/index.cjs`);let d=require(`node:fs/promises`),f=require(`node:path`),p=require(`@intlayer/config/logger`),m=require(`@intlayer/config/utils`),h=require(`@intlayer/config/package.json`);h=e.__toESM(h);const g={clean:!1,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},_=async(e,_)=>{let v=(0,p.getAppLogger)(e),y=(0,f.join)(e.system.cacheDir,`intlayer-prepared.lock`),b=(0,m.cacheDisk)(e,[`intlayer-version`]),x=await b.get(),S=!!(x&&x===h.default.version),C=await u.isCachedConfigurationUpToDate(e),w=await c.listDictionariesWithStats(e),T=!1;try{let e=await(0,d.stat)(y);T=w.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let E=e.plugins?.some(e=>!!e.loadDictionaries),{clean:D,format:O,forceRun:k,onIsCached:A,cacheTimeoutMs:j}={...g,forceRun:!S||!C||T||E,..._??{}};await l.runOnce(y,async()=>{(D||!S)&&await n.cleanOutputDir(e),await b.set(h.default.version);let c=Date.now();v([`Preparing Intlayer`,(0,p.colorize)(`(v${h.default.version})`,p.ANSIColors.GREY_DARK)]),await u.writeConfiguration(e);let l=Date.now();v([`Configuration written`,(0,p.colorize)(`(${l-c}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});let d=await o.loadDictionaries(w.map(e=>e.path),e),f=Date.now();v([`Content loaded`,(0,p.colorize)([d.remoteDictionaries.length+d.pluginDictionaries.length>0?[`(Total: ${f-l}ms`,d.localDictionaries.length>0?` - Local: ${d.time.localDictionaries}ms`:``,d.remoteDictionaries.length>0?` - Remote: ${d.time.remoteDictionaries}ms`:``,d.pluginDictionaries.length>0?` - Plugin: ${d.time.pluginDictionaries}ms`:``,`)`].join(``):`(${f-l}ms)`].join(``),p.ANSIColors.GREY_DARK)],{isVerbose:!0});let m=await t.buildDictionary([...d.localDictionaries,...d.remoteDictionaries,...d.pluginDictionaries],e,O,!1);await s.writeRemoteDictionary(d.remoteDictionaries,e),await a.createTypes(Object.values(m?.mergedDictionaries??{}).map(e=>e.dictionary),e),await r.createDictionaryEntryPoint(e);let g=Date.now();v([`Dictionaries built`,(0,p.colorize)(`(${g-c}ms)`,p.ANSIColors.GREY_DARK)]),await i.createModuleAugmentation(e),v([`Module augmentation built`,(0,p.colorize)(`(${Date.now()-g}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});for await(let t of e.plugins??[]){let{unmergedDictionaries:n,mergedDictionaries:r}=m;await t.afterBuild?.({dictionaries:{unmergedDictionaries:n,mergedDictionaries:r},configuration:e})}v([`Done`,(0,p.colorize)(`${Date.now()-c}ms`,p.ANSIColors.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:k,onIsCached:A,cacheTimeoutMs:j})};exports.prepareIntlayer=_;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./_virtual/_rolldown/runtime.cjs`),t=require(`./buildIntlayerDictionary/buildIntlayerDictionary.cjs`),n=require(`./cleanOutputDir.cjs`),r=require(`./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs`),i=require(`./utils/runOnce.cjs`),a=require(`./createType/createModuleAugmentation.cjs`),o=require(`./createType/createType.cjs`),s=require(`./loadDictionaries/loadDictionaries.cjs`),c=require(`./buildIntlayerDictionary/writeRemoteDictionary.cjs`),l=require(`./listDictionariesPath.cjs`),u=require(`./writeConfiguration/index.cjs`);let d=require(`node:fs/promises`),f=require(`node:path`),p=require(`@intlayer/config/logger`),m=require(`@intlayer/config/utils`),h=require(`@intlayer/config/package.json`);h=e.__toESM(h);const g={clean:!1,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},_=async(e,_)=>{let v=(0,p.getAppLogger)(e),y=(0,f.join)(e.system.cacheDir,`intlayer-prepared.lock`),b=(0,m.cacheDisk)(e,[`intlayer-version`]),x=await b.get(),S=!!(x&&x===h.default.version),C=await u.isCachedConfigurationUpToDate(e),w=await l.listDictionariesWithStats(e),T=!1;try{let e=await(0,d.stat)(y);T=w.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let E=e.plugins?.some(e=>!!e.loadDictionaries),{clean:D,format:O,forceRun:k,onIsCached:A,cacheTimeoutMs:j}={...g,forceRun:!S||!C||T||E,..._??{}};await i.runOnce(y,async()=>{(D||!S)&&await n.cleanOutputDir(e),await b.set(h.default.version);let i=Date.now();v([`Preparing Intlayer`,(0,p.colorize)(`(v${h.default.version})`,p.ANSIColors.GREY_DARK)]),await u.writeConfiguration(e);let l=Date.now();v([`Configuration written`,(0,p.colorize)(`(${l-i}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});let d=await s.loadDictionaries(w.map(e=>e.path),e),f=Date.now();v([`Content loaded`,(0,p.colorize)([d.remoteDictionaries.length+d.pluginDictionaries.length>0?[`(Total: ${f-l}ms`,d.localDictionaries.length>0?` - Local: ${d.time.localDictionaries}ms`:``,d.remoteDictionaries.length>0?` - Remote: ${d.time.remoteDictionaries}ms`:``,d.pluginDictionaries.length>0?` - Plugin: ${d.time.pluginDictionaries}ms`:``,`)`].join(``):`(${f-l}ms)`].join(``),p.ANSIColors.GREY_DARK)],{isVerbose:!0});let m=await t.buildDictionary([...d.localDictionaries,...d.remoteDictionaries,...d.pluginDictionaries],e,O,!1);await c.writeRemoteDictionary(d.remoteDictionaries,e),await o.createTypes(Object.values(m?.mergedDictionaries??{}).map(e=>e.dictionary),e),await r.createDictionaryEntryPoint(e);let g=Date.now();v([`Dictionaries built`,(0,p.colorize)(`(${g-i}ms)`,p.ANSIColors.GREY_DARK)]),await a.createModuleAugmentation(e),v([`Module augmentation built`,(0,p.colorize)(`(${Date.now()-g}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});for await(let t of e.plugins??[]){let{unmergedDictionaries:n,mergedDictionaries:r}=m;await t.afterBuild?.({dictionaries:{unmergedDictionaries:n,mergedDictionaries:r},configuration:e})}v([`Done`,(0,p.colorize)(`${Date.now()-i}ms`,p.ANSIColors.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:k,onIsCached:A,cacheTimeoutMs:j})};exports.prepareIntlayer=_;
2
2
  //# sourceMappingURL=prepareIntlayer.cjs.map
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`node:crypto`);t=e.__toESM(t);const n=e=>t.default.createHash(`sha3-256`).update(e).digest(`base64`).replace(/[^A-Z\d]/gi,``).substring(0,20);exports.getPathHash=n;
2
+ //# sourceMappingURL=getPathHash.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPathHash.cjs","names":["crypto"],"sources":["../../../src/utils/getPathHash.ts"],"sourcesContent":["import crypto from 'node:crypto';\n\nexport const getPathHash = (filePath: string) =>\n crypto\n .createHash('sha3-256')\n .update(filePath)\n .digest('base64')\n .replace(/[^A-Z\\d]/gi, '')\n .substring(0, 20);\n"],"mappings":"oKAEA,MAAa,EAAe,GAC1BA,EAAAA,QACG,WAAW,WAAW,CACtB,OAAO,EAAS,CAChB,OAAO,SAAS,CAChB,QAAQ,aAAc,GAAG,CACzB,UAAU,EAAG,GAAG"}
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./pLimit.cjs`),t=require(`./parallelize.cjs`),n=require(`./formatter.cjs`),r=require(`./autoDecorateContent.cjs`),i=require(`./resolveObjectPromises.cjs`),a=require(`./getFileHash.cjs`),o=require(`./sortAlphabetically.cjs`),s=require(`./runOnce.cjs`),c=require(`./getFormatFromExtension.cjs`),l=require(`./buildFilesList.cjs`),u=require(`./splitTextByLine.cjs`),d=require(`./getChunk.cjs`),f=require(`./chunkJSON.cjs`),p=require(`./getComponentTransformPattern.cjs`),m=require(`./mergeChunks.cjs`),h=require(`./parallelizeGlobal.cjs`),g=require(`./reduceObjectFormat.cjs`),_=require(`./runParallel/index.cjs`),v=require(`./verifyIdenticObjectFormat.cjs`);exports.Queue=e.Queue,exports.assembleJSON=f.assembleJSON,exports.autoDecorateContent=r.autoDecorateContent,exports.buildFilesList=l.buildFilesList,exports.chunkJSON=f.chunkJSON,exports.formatLocale=n.formatLocale,exports.formatPath=n.formatPath,exports.getChunk=d.getChunk,exports.getComponentTransformPattern=p.getComponentTransformPattern,exports.getComponentTransformPatternSync=p.getComponentTransformPatternSync,exports.getExtensionFromFormat=c.getExtensionFromFormat,exports.getFileHash=a.getFileHash,exports.getFormatFromExtension=c.getFormatFromExtension,exports.getGlobalLimiter=h.getGlobalLimiter,exports.getTaskLimiter=h.getTaskLimiter,exports.mergeChunks=m.mergeChunks,exports.pLimit=e.pLimit,exports.parallelize=t.parallelize,exports.parallelizeGlobal=h.parallelizeGlobal,exports.reconstructFromSingleChunk=f.reconstructFromSingleChunk,exports.reduceObjectFormat=g.reduceObjectFormat,exports.resolveObjectPromises=i.resolveObjectPromises,exports.runOnce=s.runOnce,exports.runParallel=_.runParallel,exports.sortAlphabetically=o.sortAlphabetically,exports.splitTextByLines=u.splitTextByLines,exports.verifyIdenticObjectFormat=v.verifyIdenticObjectFormat;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./pLimit.cjs`),t=require(`./parallelize.cjs`),n=require(`./formatter.cjs`),r=require(`./autoDecorateContent.cjs`),i=require(`./resolveObjectPromises.cjs`),a=require(`./getPathHash.cjs`),o=require(`./buildFilesList.cjs`),s=require(`./splitTextByLine.cjs`),c=require(`./getChunk.cjs`),l=require(`./chunkJSON.cjs`),u=require(`./getComponentTransformPattern.cjs`),d=require(`./getFormatFromExtension.cjs`),f=require(`./mergeChunks.cjs`),p=require(`./parallelizeGlobal.cjs`),m=require(`./reduceObjectFormat.cjs`),h=require(`./runOnce.cjs`),g=require(`./runParallel/index.cjs`),_=require(`./sortAlphabetically.cjs`),v=require(`./verifyIdenticObjectFormat.cjs`);exports.Queue=e.Queue,exports.assembleJSON=l.assembleJSON,exports.autoDecorateContent=r.autoDecorateContent,exports.buildFilesList=o.buildFilesList,exports.chunkJSON=l.chunkJSON,exports.formatLocale=n.formatLocale,exports.formatPath=n.formatPath,exports.getChunk=c.getChunk,exports.getComponentTransformPattern=u.getComponentTransformPattern,exports.getComponentTransformPatternSync=u.getComponentTransformPatternSync,exports.getExtensionFromFormat=d.getExtensionFromFormat,exports.getFormatFromExtension=d.getFormatFromExtension,exports.getGlobalLimiter=p.getGlobalLimiter,exports.getPathHash=a.getPathHash,exports.getTaskLimiter=p.getTaskLimiter,exports.mergeChunks=f.mergeChunks,exports.pLimit=e.pLimit,exports.parallelize=t.parallelize,exports.parallelizeGlobal=p.parallelizeGlobal,exports.reconstructFromSingleChunk=l.reconstructFromSingleChunk,exports.reduceObjectFormat=m.reduceObjectFormat,exports.resolveObjectPromises=i.resolveObjectPromises,exports.runOnce=h.runOnce,exports.runParallel=g.runParallel,exports.sortAlphabetically=_.sortAlphabetically,exports.splitTextByLines=s.splitTextByLines,exports.verifyIdenticObjectFormat=v.verifyIdenticObjectFormat;
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./prepareIntlayer.cjs`),t=require(`./writeContentDeclaration/writeContentDeclaration.cjs`),n=require(`./handleAdditionalContentDeclarationFile.cjs`),r=require(`./handleContentDeclarationFileChange.cjs`),i=require(`./handleContentDeclarationFileMoved.cjs`),a=require(`./handleUnlinkedContentDeclarationFile.cjs`);let o=require(`@intlayer/config/node`),s=require(`node:fs/promises`),c=require(`node:path`),l=require(`@intlayer/config/logger`),u=require(`@intlayer/config/utils`),d=require(`chokidar`);const f=new Map;let p=Promise.resolve();const m=e=>{p=p.then(async()=>{try{await e()}catch(e){console.error(e)}})},h=p=>{let h=(0,o.getConfigurationAndFilePath)(p?.configOptions),g=h.configurationFilePath,_=p?.configuration??h.configuration,v=(0,l.getAppLogger)(_),{watch:y,watchedFilesPatternWithPath:b,fileExtensions:x}=_.content;return(0,d.watch)([...Array.isArray(b)?b:[b],...g?[g]:[]],{persistent:y,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:1e3,pollInterval:100},ignored:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.intlayer/**`],...p}).on(`add`,async e=>{let r=(0,c.basename)(e),a=!1,o;for(let[e]of f)if((0,c.basename)(e)===r){o=e;break}if(!o&&f.size===1&&(o=f.keys().next().value),o){let t=f.get(o);t&&(clearTimeout(t.timer),f.delete(o)),a=!0,v(`File moved from ${o} to ${e}`)}m(async()=>{if(a&&o)await i.handleContentDeclarationFileMoved(o,e,_);else{if(await(0,s.readFile)(e,`utf-8`)===``){let n=x.map(e=>e.replace(/\./g,`\\.`)).join(`|`);await t.writeContentDeclaration({key:r.replace(RegExp(`(${n})$`),``),content:{},filePath:e},_)}await n.handleAdditionalContentDeclarationFile(e,_)}})}).on(`change`,async t=>m(async()=>{if(g&&t===g){v(`Configuration file changed, repreparing Intlayer`),(0,u.clearModuleCache)(g),(0,u.clearAllCache)();let{configuration:t}=(0,o.getConfigurationAndFilePath)(p?.configOptions);_=p?.configuration??t,await e.prepareIntlayer(_,{clean:!1})}else await r.handleContentDeclarationFileChange(t,_)})).on(`unlink`,async e=>{let t=setTimeout(async()=>{f.delete(e),m(async()=>a.handleUnlinkedContentDeclarationFile(e,_))},200);f.set(e,{timer:t,oldPath:e})}).on(`error`,async t=>{v(`Watcher error: ${t}`,{level:`error`}),v(`Restarting watcher`),await e.prepareIntlayer(_)})},g=async t=>{let{skipPrepare:n,...r}=t??{},i=t?.configuration??(0,o.getConfiguration)(t?.configOptions);n||await e.prepareIntlayer(i,{forceRun:!0}),(i.content.watch||t?.persistent)&&((0,l.getAppLogger)(i)(`Watching Intlayer content declarations`),h({...r,configuration:i}))};exports.buildAndWatchIntlayer=g,exports.watch=h;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./prepareIntlayer.cjs`),t=require(`./writeContentDeclaration/writeContentDeclaration.cjs`),n=require(`./handleAdditionalContentDeclarationFile.cjs`),r=require(`./handleContentDeclarationFileChange.cjs`),i=require(`./handleContentDeclarationFileMoved.cjs`),a=require(`./handleUnlinkedContentDeclarationFile.cjs`);let o=require(`@intlayer/config/node`),s=require(`node:fs/promises`),c=require(`node:path`),l=require(`@intlayer/config/logger`),u=require(`@intlayer/config/utils`),d=require(`chokidar`);const f=new Map;let p=Promise.resolve();const m=e=>{p=p.then(async()=>{try{await e()}catch(e){console.error(e)}})},h=p=>{let h=(0,o.getConfigurationAndFilePath)(p?.configOptions),g=h.configurationFilePath,_=p?.configuration??h.configuration,v=(0,l.getAppLogger)(_),{watch:y,watchedFilesPatternWithPath:b,fileExtensions:x}=_.content,S=[...Array.isArray(b)?b:[b],...g?[g]:[]];if(_.content.watch)return v(`Watching Intlayer content declarations`),(0,d.watch)(S,{persistent:y,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:1e3,pollInterval:100},ignored:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.intlayer/**`],...p}).on(`add`,async e=>{let r=(0,c.basename)(e),a=!1,o;for(let[e]of f)if((0,c.basename)(e)===r){o=e;break}if(!o&&f.size===1&&(o=f.keys().next().value),o){let t=f.get(o);t&&(clearTimeout(t.timer),f.delete(o)),a=!0,v(`File moved from ${o} to ${e}`)}m(async()=>{if(a&&o)await i.handleContentDeclarationFileMoved(o,e,_);else{if(await(0,s.readFile)(e,`utf-8`)===``){let n=x.map(e=>e.replace(/\./g,`\\.`)).join(`|`);await t.writeContentDeclaration({key:r.replace(RegExp(`(${n})$`),``),content:{},filePath:e},_)}await n.handleAdditionalContentDeclarationFile(e,_)}})}).on(`change`,async t=>m(async()=>{if(g&&t===g){v(`Configuration file changed, repreparing Intlayer`),(0,u.clearModuleCache)(g),(0,u.clearAllCache)();let{configuration:t}=(0,o.getConfigurationAndFilePath)(p?.configOptions);_=p?.configuration??t,await e.prepareIntlayer(_,{clean:!1})}else await r.handleContentDeclarationFileChange(t,_)})).on(`unlink`,async e=>{let t=setTimeout(async()=>{f.delete(e),m(async()=>a.handleUnlinkedContentDeclarationFile(e,_))},200);f.set(e,{timer:t,oldPath:e})}).on(`error`,async t=>{v(`Watcher error: ${t}`,{level:`error`}),v(`Restarting watcher`),await e.prepareIntlayer(_)})},g=async t=>{let{skipPrepare:n,...r}=t??{},i=t?.configuration??(0,o.getConfiguration)(t?.configOptions);n||await e.prepareIntlayer(i,{forceRun:!0}),(i.content.watch||t?.persistent)&&h({...r,configuration:i})};exports.buildAndWatchIntlayer=g,exports.watch=h;
2
2
  //# sourceMappingURL=watcher.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"watcher.cjs","names":["handleContentDeclarationFileMoved","writeContentDeclaration","handleAdditionalContentDeclarationFile","prepareIntlayer","handleContentDeclarationFileChange","handleUnlinkedContentDeclarationFile"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n getConfigurationAndFilePath,\n} from '@intlayer/config/node';\nimport { clearAllCache, clearModuleCache } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleContentDeclarationFileMoved } from './handleContentDeclarationFileMoved';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport { writeContentDeclaration } from './writeContentDeclaration';\n\n// Map to track files that were recently unlinked: oldPath -> { timer, timestamp }\nconst pendingUnlinks = new Map<\n string,\n { timer: NodeJS.Timeout; oldPath: string }\n>();\n\n// Task queue to ensure sequential processing of file events\nlet processingQueue = Promise.resolve();\nconst processEvent = (task: () => Promise<void>) => {\n processingQueue = processingQueue.then(async () => {\n try {\n await task();\n } catch (error) {\n console.error(error);\n }\n });\n};\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configResult = getConfigurationAndFilePath(options?.configOptions);\n const configurationFilePath = configResult.configurationFilePath;\n let configuration: IntlayerConfig =\n options?.configuration ?? configResult.configuration;\n const appLogger = getAppLogger(configuration);\n\n const {\n watch: isWatchMode,\n watchedFilesPatternWithPath,\n fileExtensions,\n } = configuration.content;\n\n const pathsToWatch = [\n ...(Array.isArray(watchedFilesPatternWithPath)\n ? watchedFilesPatternWithPath\n : [watchedFilesPatternWithPath]),\n ...(configurationFilePath ? [configurationFilePath] : []),\n ];\n\n return chokidarWatch(pathsToWatch, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n ignored: [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n ],\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n let isMove = false;\n\n // Check if this Add corresponds to a pending Unlink (Move/Rename detection)\n // Heuristic:\n // - Priority A: Exact basename match (Moved to different folder)\n // - Priority B: Single entry in pendingUnlinks (Renamed file)\n let matchedOldPath: string | undefined;\n\n // Search for basename match\n for (const [oldPath] of pendingUnlinks) {\n if (basename(oldPath) === fileName) {\n matchedOldPath = oldPath;\n break;\n }\n }\n\n // If no basename match, but exactly one file was recently unlinked, assume it's a rename\n if (!matchedOldPath && pendingUnlinks.size === 1) {\n matchedOldPath = pendingUnlinks.keys().next().value;\n }\n\n if (matchedOldPath) {\n // It is a move! Cancel the unlink handler\n const pending = pendingUnlinks.get(matchedOldPath);\n if (pending) {\n clearTimeout(pending.timer);\n pendingUnlinks.delete(matchedOldPath);\n }\n\n isMove = true;\n appLogger(`File moved from ${matchedOldPath} to ${filePath}`);\n }\n\n processEvent(async () => {\n if (isMove && matchedOldPath) {\n await handleContentDeclarationFileMoved(\n matchedOldPath,\n filePath,\n configuration\n );\n } else {\n const fileContent = await readFile(filePath, 'utf-8');\n const isEmpty = fileContent === '';\n\n // Fill template content declaration file if it is empty\n if (isEmpty) {\n const extensionPattern = fileExtensions\n .map((ext) => ext.replace(/\\./g, '\\\\.'))\n .join('|');\n const name = fileName.replace(\n new RegExp(`(${extensionPattern})$`),\n ''\n );\n\n await writeContentDeclaration(\n {\n key: name,\n content: {},\n filePath,\n },\n configuration\n );\n }\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n }\n });\n })\n .on('change', async (filePath) =>\n processEvent(async () => {\n if (configurationFilePath && filePath === configurationFilePath) {\n appLogger('Configuration file changed, repreparing Intlayer');\n\n clearModuleCache(configurationFilePath);\n clearAllCache();\n\n const { configuration: newConfiguration } =\n getConfigurationAndFilePath(options?.configOptions);\n\n configuration = options?.configuration ?? newConfiguration;\n\n await prepareIntlayer(configuration, { clean: false });\n } else {\n await handleContentDeclarationFileChange(filePath, configuration);\n }\n })\n )\n .on('unlink', async (filePath) => {\n // Delay unlink processing to see if an 'add' event occurs (indicating a move)\n const timer = setTimeout(async () => {\n // If timer fires, the file was genuinely removed\n pendingUnlinks.delete(filePath);\n processEvent(async () =>\n handleUnlinkedContentDeclarationFile(filePath, configuration)\n );\n }, 200); // 200ms window to catch the 'add' event\n\n pendingUnlinks.set(filePath, { timer, oldPath: filePath });\n })\n .on('error', async (error) => {\n appLogger(`Watcher error: ${error}`, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n if (configuration.content.watch || options?.persistent) {\n const appLogger = getAppLogger(configuration);\n\n appLogger('Watching Intlayer content declarations');\n watch({ ...rest, configuration });\n }\n};\n"],"mappings":"mnBAoBA,MAAM,EAAiB,IAAI,IAM3B,IAAI,EAAkB,QAAQ,SAAS,CACvC,MAAM,EAAgB,GAA8B,CAClD,EAAkB,EAAgB,KAAK,SAAY,CACjD,GAAI,CACF,MAAM,GAAM,OACL,EAAO,CACd,QAAQ,MAAM,EAAM,GAEtB,EAUS,EAAS,GAA2B,CAC/C,IAAM,GAAA,EAAA,EAAA,6BAA2C,GAAS,cAAc,CAClE,EAAwB,EAAa,sBACvC,EACF,GAAS,eAAiB,EAAa,cACnC,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,CACJ,MAAO,EACP,8BACA,kBACE,EAAc,QASlB,OAAA,EAAA,EAAA,OAPqB,CACnB,GAAI,MAAM,QAAQ,EAA4B,CAC1C,EACA,CAAC,EAA4B,CACjC,GAAI,EAAwB,CAAC,EAAsB,CAAG,EAAE,CACzD,CAEkC,CACjC,WAAY,EACZ,cAAe,GACf,iBAAkB,CAChB,mBAAoB,IACpB,aAAc,IACf,CACD,QAAS,CACP,qBACA,aACA,cACA,kBACD,CACD,GAAG,EACJ,CAAC,CACC,GAAG,MAAO,KAAO,IAAa,CAC7B,IAAM,GAAA,EAAA,EAAA,UAAoB,EAAS,CAC/B,EAAS,GAMT,EAGJ,IAAK,GAAM,CAAC,KAAY,EACtB,IAAA,EAAA,EAAA,UAAa,EAAQ,GAAK,EAAU,CAClC,EAAiB,EACjB,MASJ,GAJI,CAAC,GAAkB,EAAe,OAAS,IAC7C,EAAiB,EAAe,MAAM,CAAC,MAAM,CAAC,OAG5C,EAAgB,CAEl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MF,EAAAA,gBAAgB,EAAc,EACpC,EAGO,EAAwB,KAAO,IAA2B,CACrE,GAAM,CAAE,cAAa,GAAG,GAAS,GAAW,EAAE,CACxC,EACJ,GAAS,gBAAA,EAAA,EAAA,kBAAkC,GAAS,cAAc,CAE/D,GACH,MAAMA,EAAAA,gBAAgB,EAAe,CAAE,SAAU,GAAM,CAAC,EAGtD,EAAc,QAAQ,OAAS,GAAS,eAG1C,EAAA,EAAA,cAF+B,EAAc,CAEnC,yCAAyC,CACnD,EAAM,CAAE,GAAG,EAAM,gBAAe,CAAC"}
1
+ {"version":3,"file":"watcher.cjs","names":["handleContentDeclarationFileMoved","writeContentDeclaration","handleAdditionalContentDeclarationFile","prepareIntlayer","handleContentDeclarationFileChange","handleUnlinkedContentDeclarationFile"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n getConfigurationAndFilePath,\n} from '@intlayer/config/node';\nimport { clearAllCache, clearModuleCache } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleContentDeclarationFileMoved } from './handleContentDeclarationFileMoved';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport { writeContentDeclaration } from './writeContentDeclaration';\n\n// Map to track files that were recently unlinked: oldPath -> { timer, timestamp }\nconst pendingUnlinks = new Map<\n string,\n { timer: NodeJS.Timeout; oldPath: string }\n>();\n\n// Task queue to ensure sequential processing of file events\nlet processingQueue = Promise.resolve();\nconst processEvent = (task: () => Promise<void>) => {\n processingQueue = processingQueue.then(async () => {\n try {\n await task();\n } catch (error) {\n console.error(error);\n }\n });\n};\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configResult = getConfigurationAndFilePath(options?.configOptions);\n const configurationFilePath = configResult.configurationFilePath;\n let configuration: IntlayerConfig =\n options?.configuration ?? configResult.configuration;\n const appLogger = getAppLogger(configuration);\n\n const {\n watch: isWatchMode,\n watchedFilesPatternWithPath,\n fileExtensions,\n } = configuration.content;\n\n const pathsToWatch = [\n ...(Array.isArray(watchedFilesPatternWithPath)\n ? watchedFilesPatternWithPath\n : [watchedFilesPatternWithPath]),\n ...(configurationFilePath ? [configurationFilePath] : []),\n ];\n\n if (!configuration.content.watch) return;\n\n appLogger('Watching Intlayer content declarations');\n\n return chokidarWatch(pathsToWatch, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n ignored: [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n ],\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n let isMove = false;\n\n // Check if this Add corresponds to a pending Unlink (Move/Rename detection)\n // Heuristic:\n // - Priority A: Exact basename match (Moved to different folder)\n // - Priority B: Single entry in pendingUnlinks (Renamed file)\n let matchedOldPath: string | undefined;\n\n // Search for basename match\n for (const [oldPath] of pendingUnlinks) {\n if (basename(oldPath) === fileName) {\n matchedOldPath = oldPath;\n break;\n }\n }\n\n // If no basename match, but exactly one file was recently unlinked, assume it's a rename\n if (!matchedOldPath && pendingUnlinks.size === 1) {\n matchedOldPath = pendingUnlinks.keys().next().value;\n }\n\n if (matchedOldPath) {\n // It is a move! Cancel the unlink handler\n const pending = pendingUnlinks.get(matchedOldPath);\n if (pending) {\n clearTimeout(pending.timer);\n pendingUnlinks.delete(matchedOldPath);\n }\n\n isMove = true;\n appLogger(`File moved from ${matchedOldPath} to ${filePath}`);\n }\n\n processEvent(async () => {\n if (isMove && matchedOldPath) {\n await handleContentDeclarationFileMoved(\n matchedOldPath,\n filePath,\n configuration\n );\n } else {\n const fileContent = await readFile(filePath, 'utf-8');\n const isEmpty = fileContent === '';\n\n // Fill template content declaration file if it is empty\n if (isEmpty) {\n const extensionPattern = fileExtensions\n .map((ext) => ext.replace(/\\./g, '\\\\.'))\n .join('|');\n const name = fileName.replace(\n new RegExp(`(${extensionPattern})$`),\n ''\n );\n\n await writeContentDeclaration(\n {\n key: name,\n content: {},\n filePath,\n },\n configuration\n );\n }\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n }\n });\n })\n .on('change', async (filePath) =>\n processEvent(async () => {\n if (configurationFilePath && filePath === configurationFilePath) {\n appLogger('Configuration file changed, repreparing Intlayer');\n\n clearModuleCache(configurationFilePath);\n clearAllCache();\n\n const { configuration: newConfiguration } =\n getConfigurationAndFilePath(options?.configOptions);\n\n configuration = options?.configuration ?? newConfiguration;\n\n await prepareIntlayer(configuration, { clean: false });\n } else {\n await handleContentDeclarationFileChange(filePath, configuration);\n }\n })\n )\n .on('unlink', async (filePath) => {\n // Delay unlink processing to see if an 'add' event occurs (indicating a move)\n const timer = setTimeout(async () => {\n // If timer fires, the file was genuinely removed\n pendingUnlinks.delete(filePath);\n processEvent(async () =>\n handleUnlinkedContentDeclarationFile(filePath, configuration)\n );\n }, 200); // 200ms window to catch the 'add' event\n\n pendingUnlinks.set(filePath, { timer, oldPath: filePath });\n })\n .on('error', async (error) => {\n appLogger(`Watcher error: ${error}`, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n if (configuration.content.watch || options?.persistent) {\n watch({ ...rest, configuration });\n }\n};\n"],"mappings":"mnBAoBA,MAAM,EAAiB,IAAI,IAM3B,IAAI,EAAkB,QAAQ,SAAS,CACvC,MAAM,EAAgB,GAA8B,CAClD,EAAkB,EAAgB,KAAK,SAAY,CACjD,GAAI,CACF,MAAM,GAAM,OACL,EAAO,CACd,QAAQ,MAAM,EAAM,GAEtB,EAUS,EAAS,GAA2B,CAC/C,IAAM,GAAA,EAAA,EAAA,6BAA2C,GAAS,cAAc,CAClE,EAAwB,EAAa,sBACvC,EACF,GAAS,eAAiB,EAAa,cACnC,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,CACJ,MAAO,EACP,8BACA,kBACE,EAAc,QAEZ,EAAe,CACnB,GAAI,MAAM,QAAQ,EAA4B,CAC1C,EACA,CAAC,EAA4B,CACjC,GAAI,EAAwB,CAAC,EAAsB,CAAG,EAAE,CACzD,CAEI,KAAc,QAAQ,MAI3B,OAFA,EAAU,yCAAyC,EAEnD,EAAA,EAAA,OAAqB,EAAc,CACjC,WAAY,EACZ,cAAe,GACf,iBAAkB,CAChB,mBAAoB,IACpB,aAAc,IACf,CACD,QAAS,CACP,qBACA,aACA,cACA,kBACD,CACD,GAAG,EACJ,CAAC,CACC,GAAG,MAAO,KAAO,IAAa,CAC7B,IAAM,GAAA,EAAA,EAAA,UAAoB,EAAS,CAC/B,EAAS,GAMT,EAGJ,IAAK,GAAM,CAAC,KAAY,EACtB,IAAA,EAAA,EAAA,UAAa,EAAQ,GAAK,EAAU,CAClC,EAAiB,EACjB,MASJ,GAJI,CAAC,GAAkB,EAAe,OAAS,IAC7C,EAAiB,EAAe,MAAM,CAAC,MAAM,CAAC,OAG5C,EAAgB,CAElB,IAAM,EAAU,EAAe,IAAI,EAAe,CAC9C,IACF,aAAa,EAAQ,MAAM,CAC3B,EAAe,OAAO,EAAe,EA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