@intlayer/config 9.0.0-canary.8 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/dist/cjs/built.cjs +2 -0
  2. package/dist/cjs/built.cjs.map +1 -1
  3. package/dist/cjs/bundle/index.cjs +1 -1
  4. package/dist/cjs/bundle/index.cjs.map +1 -1
  5. package/dist/cjs/bundle/logBundle.cjs.map +1 -1
  6. package/dist/cjs/callers/base.cjs +42 -0
  7. package/dist/cjs/callers/base.cjs.map +1 -0
  8. package/dist/cjs/callers/compat/i18next.cjs +27 -0
  9. package/dist/cjs/callers/compat/i18next.cjs.map +1 -0
  10. package/dist/cjs/callers/compat/lingui.cjs +82 -0
  11. package/dist/cjs/callers/compat/lingui.cjs.map +1 -0
  12. package/dist/cjs/callers/compat/nextIntl.cjs +44 -0
  13. package/dist/cjs/callers/compat/nextIntl.cjs.map +1 -0
  14. package/dist/cjs/callers/compat/reactI18next.cjs +50 -0
  15. package/dist/cjs/callers/compat/reactI18next.cjs.map +1 -0
  16. package/dist/cjs/callers/compat/reactIntl.cjs +31 -0
  17. package/dist/cjs/callers/compat/reactIntl.cjs.map +1 -0
  18. package/dist/cjs/callers/compat/useIntl.cjs +46 -0
  19. package/dist/cjs/callers/compat/useIntl.cjs.map +1 -0
  20. package/dist/cjs/callers/compat/vueI18n.cjs +26 -0
  21. package/dist/cjs/callers/compat/vueI18n.cjs.map +1 -0
  22. package/dist/cjs/callers/index.cjs +87 -0
  23. package/dist/cjs/callers/index.cjs.map +1 -0
  24. package/dist/cjs/callers/transform.cjs +46 -0
  25. package/dist/cjs/callers/transform.cjs.map +1 -0
  26. package/dist/cjs/callers/types.cjs +0 -0
  27. package/dist/cjs/client.cjs +1 -0
  28. package/dist/cjs/configFile/buildBrowserConfiguration.cjs +47 -3
  29. package/dist/cjs/configFile/buildBrowserConfiguration.cjs.map +1 -1
  30. package/dist/cjs/configFile/buildConfigurationFields.cjs +9 -3
  31. package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
  32. package/dist/cjs/configFile/configurationSchema.cjs +7 -0
  33. package/dist/cjs/configFile/configurationSchema.cjs.map +1 -1
  34. package/dist/cjs/configFile/getConfiguration.cjs +10 -3
  35. package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
  36. package/dist/cjs/configFile/index.cjs +2 -0
  37. package/dist/cjs/configFile/loadConfigurationFile.cjs.map +1 -1
  38. package/dist/cjs/configFile/searchConfigurationFile.cjs +0 -1
  39. package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
  40. package/dist/cjs/defaultValues/analytics.cjs +16 -0
  41. package/dist/cjs/defaultValues/analytics.cjs.map +1 -0
  42. package/dist/cjs/defaultValues/build.cjs.map +1 -1
  43. package/dist/cjs/defaultValues/content.cjs.map +1 -1
  44. package/dist/cjs/defaultValues/index.cjs +4 -0
  45. package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
  46. package/dist/cjs/defaultValues/routing.cjs.map +1 -1
  47. package/dist/cjs/envVars/envVars.cjs +2 -1
  48. package/dist/cjs/envVars/envVars.cjs.map +1 -1
  49. package/dist/cjs/loadEnvFile.cjs +44 -7
  50. package/dist/cjs/loadEnvFile.cjs.map +1 -1
  51. package/dist/cjs/loadExternalFile/bundleFile.cjs +4 -3
  52. package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
  53. package/dist/cjs/loadExternalFile/bundleJSFile.cjs +0 -1
  54. package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -1
  55. package/dist/cjs/loadExternalFile/index.cjs +1 -0
  56. package/dist/cjs/loadExternalFile/loadExternalFile.cjs +11 -6
  57. package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
  58. package/dist/cjs/loadExternalFile/parseFileContent.cjs +52 -17
  59. package/dist/cjs/loadExternalFile/parseFileContent.cjs.map +1 -1
  60. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +99 -10
  61. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
  62. package/dist/cjs/logger.cjs +2 -1
  63. package/dist/cjs/logger.cjs.map +1 -1
  64. package/dist/cjs/node.cjs +2 -0
  65. package/dist/cjs/utils/ESMxCJSHelpers.cjs +0 -1
  66. package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
  67. package/dist/cjs/utils/alias.cjs +0 -1
  68. package/dist/cjs/utils/alias.cjs.map +1 -1
  69. package/dist/cjs/utils/builtConfigKeys.cjs +38 -0
  70. package/dist/cjs/utils/builtConfigKeys.cjs.map +1 -0
  71. package/dist/cjs/utils/cacheDisk.cjs +2 -1
  72. package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
  73. package/dist/cjs/utils/cacheMemory.cjs +0 -1
  74. package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
  75. package/dist/cjs/utils/clearModuleCache.cjs.map +1 -1
  76. package/dist/cjs/utils/compareVersions.cjs.map +1 -1
  77. package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
  78. package/dist/cjs/utils/getDictionarySelectorUsage.cjs.map +1 -1
  79. package/dist/cjs/utils/getExtension.cjs.map +1 -1
  80. package/dist/cjs/utils/getPackageJsonPath.cjs +0 -1
  81. package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
  82. package/dist/cjs/utils/getStorageAttributes.cjs +2 -1
  83. package/dist/cjs/utils/getStorageAttributes.cjs.map +1 -1
  84. package/dist/cjs/utils/getUsedNodeTypes.cjs +0 -1
  85. package/dist/cjs/utils/getUsedNodeTypes.cjs.map +1 -1
  86. package/dist/cjs/utils/index.cjs +2 -0
  87. package/dist/cjs/utils/logStack.cjs.map +1 -1
  88. package/dist/cjs/utils/normalizePath.cjs.map +1 -1
  89. package/dist/cjs/utils/parseFilePathPattern.cjs.map +1 -1
  90. package/dist/cjs/utils/pathSecurity.cjs +0 -1
  91. package/dist/cjs/utils/pathSecurity.cjs.map +1 -1
  92. package/dist/cjs/utils/retryManager.cjs.map +1 -1
  93. package/dist/cjs/utils/setIntlayerIdentifier.cjs.map +1 -1
  94. package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
  95. package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
  96. package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
  97. package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
  98. package/dist/esm/built.mjs +2 -1
  99. package/dist/esm/built.mjs.map +1 -1
  100. package/dist/esm/bundle/index.mjs +2 -2
  101. package/dist/esm/bundle/index.mjs.map +1 -1
  102. package/dist/esm/bundle/logBundle.mjs.map +1 -1
  103. package/dist/esm/callers/base.mjs +40 -0
  104. package/dist/esm/callers/base.mjs.map +1 -0
  105. package/dist/esm/callers/compat/i18next.mjs +25 -0
  106. package/dist/esm/callers/compat/i18next.mjs.map +1 -0
  107. package/dist/esm/callers/compat/lingui.mjs +80 -0
  108. package/dist/esm/callers/compat/lingui.mjs.map +1 -0
  109. package/dist/esm/callers/compat/nextIntl.mjs +42 -0
  110. package/dist/esm/callers/compat/nextIntl.mjs.map +1 -0
  111. package/dist/esm/callers/compat/reactI18next.mjs +48 -0
  112. package/dist/esm/callers/compat/reactI18next.mjs.map +1 -0
  113. package/dist/esm/callers/compat/reactIntl.mjs +29 -0
  114. package/dist/esm/callers/compat/reactIntl.mjs.map +1 -0
  115. package/dist/esm/callers/compat/useIntl.mjs +44 -0
  116. package/dist/esm/callers/compat/useIntl.mjs.map +1 -0
  117. package/dist/esm/callers/compat/vueI18n.mjs +24 -0
  118. package/dist/esm/callers/compat/vueI18n.mjs.map +1 -0
  119. package/dist/esm/callers/index.mjs +72 -0
  120. package/dist/esm/callers/index.mjs.map +1 -0
  121. package/dist/esm/callers/transform.mjs +43 -0
  122. package/dist/esm/callers/transform.mjs.map +1 -0
  123. package/dist/esm/callers/types.mjs +0 -0
  124. package/dist/esm/client.mjs +2 -2
  125. package/dist/esm/configFile/buildBrowserConfiguration.mjs +47 -4
  126. package/dist/esm/configFile/buildBrowserConfiguration.mjs.map +1 -1
  127. package/dist/esm/configFile/buildConfigurationFields.mjs +10 -4
  128. package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
  129. package/dist/esm/configFile/configurationSchema.mjs +7 -1
  130. package/dist/esm/configFile/configurationSchema.mjs.map +1 -1
  131. package/dist/esm/configFile/getConfiguration.mjs +10 -2
  132. package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
  133. package/dist/esm/configFile/index.mjs +3 -3
  134. package/dist/esm/configFile/loadConfigurationFile.mjs.map +1 -1
  135. package/dist/esm/configFile/searchConfigurationFile.mjs.map +1 -1
  136. package/dist/esm/defaultValues/analytics.mjs +12 -0
  137. package/dist/esm/defaultValues/analytics.mjs.map +1 -0
  138. package/dist/esm/defaultValues/build.mjs.map +1 -1
  139. package/dist/esm/defaultValues/content.mjs.map +1 -1
  140. package/dist/esm/defaultValues/index.mjs +2 -1
  141. package/dist/esm/defaultValues/internationalization.mjs.map +1 -1
  142. package/dist/esm/defaultValues/routing.mjs.map +1 -1
  143. package/dist/esm/envVars/envVars.mjs +2 -1
  144. package/dist/esm/envVars/envVars.mjs.map +1 -1
  145. package/dist/esm/loadEnvFile.mjs +45 -8
  146. package/dist/esm/loadEnvFile.mjs.map +1 -1
  147. package/dist/esm/loadExternalFile/bundleFile.mjs +4 -2
  148. package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
  149. package/dist/esm/loadExternalFile/bundleJSFile.mjs.map +1 -1
  150. package/dist/esm/loadExternalFile/index.mjs +2 -2
  151. package/dist/esm/loadExternalFile/loadExternalFile.mjs +11 -6
  152. package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
  153. package/dist/esm/loadExternalFile/parseFileContent.mjs +52 -17
  154. package/dist/esm/loadExternalFile/parseFileContent.mjs.map +1 -1
  155. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +102 -13
  156. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
  157. package/dist/esm/logger.mjs +2 -1
  158. package/dist/esm/logger.mjs.map +1 -1
  159. package/dist/esm/node.mjs +3 -3
  160. package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
  161. package/dist/esm/utils/alias.mjs.map +1 -1
  162. package/dist/esm/utils/builtConfigKeys.mjs +36 -0
  163. package/dist/esm/utils/builtConfigKeys.mjs.map +1 -0
  164. package/dist/esm/utils/cacheDisk.mjs +6 -5
  165. package/dist/esm/utils/cacheDisk.mjs.map +1 -1
  166. package/dist/esm/utils/cacheMemory.mjs.map +1 -1
  167. package/dist/esm/utils/clearModuleCache.mjs.map +1 -1
  168. package/dist/esm/utils/compareVersions.mjs.map +1 -1
  169. package/dist/esm/utils/extractErrorMessage.mjs.map +1 -1
  170. package/dist/esm/utils/getDictionarySelectorUsage.mjs.map +1 -1
  171. package/dist/esm/utils/getExtension.mjs.map +1 -1
  172. package/dist/esm/utils/getPackageJsonPath.mjs.map +1 -1
  173. package/dist/esm/utils/getStorageAttributes.mjs +2 -1
  174. package/dist/esm/utils/getStorageAttributes.mjs.map +1 -1
  175. package/dist/esm/utils/getUsedNodeTypes.mjs.map +1 -1
  176. package/dist/esm/utils/index.mjs +2 -1
  177. package/dist/esm/utils/logStack.mjs.map +1 -1
  178. package/dist/esm/utils/normalizePath.mjs.map +1 -1
  179. package/dist/esm/utils/parseFilePathPattern.mjs.map +1 -1
  180. package/dist/esm/utils/pathSecurity.mjs.map +1 -1
  181. package/dist/esm/utils/retryManager.mjs.map +1 -1
  182. package/dist/esm/utils/setIntlayerIdentifier.mjs.map +1 -1
  183. package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs.map +1 -1
  184. package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs.map +1 -1
  185. package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs.map +1 -1
  186. package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs.map +1 -1
  187. package/dist/types/built.d.ts +2 -1
  188. package/dist/types/built.d.ts.map +1 -1
  189. package/dist/types/bundle/index.d.ts +2 -4
  190. package/dist/types/bundle/index.d.ts.map +1 -1
  191. package/dist/types/bundle/logBundle.d.ts +0 -1
  192. package/dist/types/bundle/logBundle.d.ts.map +1 -1
  193. package/dist/types/callers/base.d.ts +13 -0
  194. package/dist/types/callers/base.d.ts.map +1 -0
  195. package/dist/types/callers/compat/i18next.d.ts +11 -0
  196. package/dist/types/callers/compat/i18next.d.ts.map +1 -0
  197. package/dist/types/callers/compat/lingui.d.ts +6 -0
  198. package/dist/types/callers/compat/lingui.d.ts.map +1 -0
  199. package/dist/types/callers/compat/nextIntl.d.ts +12 -0
  200. package/dist/types/callers/compat/nextIntl.d.ts.map +1 -0
  201. package/dist/types/callers/compat/reactI18next.d.ts +14 -0
  202. package/dist/types/callers/compat/reactI18next.d.ts.map +1 -0
  203. package/dist/types/callers/compat/reactIntl.d.ts +15 -0
  204. package/dist/types/callers/compat/reactIntl.d.ts.map +1 -0
  205. package/dist/types/callers/compat/useIntl.d.ts +11 -0
  206. package/dist/types/callers/compat/useIntl.d.ts.map +1 -0
  207. package/dist/types/callers/compat/vueI18n.d.ts +11 -0
  208. package/dist/types/callers/compat/vueI18n.d.ts.map +1 -0
  209. package/dist/types/callers/index.d.ts +48 -0
  210. package/dist/types/callers/index.d.ts.map +1 -0
  211. package/dist/types/callers/transform.d.ts +60 -0
  212. package/dist/types/callers/transform.d.ts.map +1 -0
  213. package/dist/types/callers/types.d.ts +160 -0
  214. package/dist/types/callers/types.d.ts.map +1 -0
  215. package/dist/types/client.d.ts +2 -2
  216. package/dist/types/colors.d.ts +14 -14
  217. package/dist/types/colors.d.ts.map +1 -1
  218. package/dist/types/configFile/buildBrowserConfiguration.d.ts +24 -4
  219. package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
  220. package/dist/types/configFile/buildConfigurationFields.d.ts +8 -4
  221. package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
  222. package/dist/types/configFile/configurationSchema.d.ts +43 -34
  223. package/dist/types/configFile/configurationSchema.d.ts.map +1 -1
  224. package/dist/types/configFile/getConfiguration.d.ts +0 -1
  225. package/dist/types/configFile/getConfiguration.d.ts.map +1 -1
  226. package/dist/types/configFile/index.d.ts +3 -3
  227. package/dist/types/configFile/loadConfigurationFile.d.ts +1 -2
  228. package/dist/types/configFile/loadConfigurationFile.d.ts.map +1 -1
  229. package/dist/types/configFile/searchConfigurationFile.d.ts +1 -1
  230. package/dist/types/configFile/searchConfigurationFile.d.ts.map +1 -1
  231. package/dist/types/defaultValues/analytics.d.ts +11 -0
  232. package/dist/types/defaultValues/analytics.d.ts.map +1 -0
  233. package/dist/types/defaultValues/build.d.ts.map +1 -1
  234. package/dist/types/defaultValues/compiler.d.ts.map +1 -1
  235. package/dist/types/defaultValues/content.d.ts.map +1 -1
  236. package/dist/types/defaultValues/dictionary.d.ts +0 -1
  237. package/dist/types/defaultValues/dictionary.d.ts.map +1 -1
  238. package/dist/types/defaultValues/editor.d.ts.map +1 -1
  239. package/dist/types/defaultValues/index.d.ts +2 -1
  240. package/dist/types/defaultValues/internationalization.d.ts +0 -1
  241. package/dist/types/defaultValues/internationalization.d.ts.map +1 -1
  242. package/dist/types/defaultValues/log.d.ts.map +1 -1
  243. package/dist/types/defaultValues/routing.d.ts +0 -1
  244. package/dist/types/defaultValues/routing.d.ts.map +1 -1
  245. package/dist/types/defaultValues/system.d.ts.map +1 -1
  246. package/dist/types/envVars/envVars.d.ts +0 -1
  247. package/dist/types/envVars/envVars.d.ts.map +1 -1
  248. package/dist/types/loadEnvFile.d.ts +1 -1
  249. package/dist/types/loadEnvFile.d.ts.map +1 -1
  250. package/dist/types/loadExternalFile/bundleFile.d.ts +0 -1
  251. package/dist/types/loadExternalFile/bundleFile.d.ts.map +1 -1
  252. package/dist/types/loadExternalFile/bundleJSFile.d.ts +57 -59
  253. package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -1
  254. package/dist/types/loadExternalFile/index.d.ts +2 -2
  255. package/dist/types/loadExternalFile/loadExternalFile.d.ts +0 -1
  256. package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
  257. package/dist/types/loadExternalFile/parseFileContent.d.ts +9 -1
  258. package/dist/types/loadExternalFile/parseFileContent.d.ts.map +1 -1
  259. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +4 -4
  260. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
  261. package/dist/types/logger.d.ts +2 -3
  262. package/dist/types/logger.d.ts.map +1 -1
  263. package/dist/types/node.d.ts +3 -3
  264. package/dist/types/utils/ESMxCJSHelpers.d.ts.map +1 -1
  265. package/dist/types/utils/alias.d.ts +1 -6
  266. package/dist/types/utils/alias.d.ts.map +1 -1
  267. package/dist/types/utils/builtConfigKeys.d.ts +25 -0
  268. package/dist/types/utils/builtConfigKeys.d.ts.map +1 -0
  269. package/dist/types/utils/cacheDisk.d.ts +22 -11
  270. package/dist/types/utils/cacheDisk.d.ts.map +1 -1
  271. package/dist/types/utils/cacheMemory.d.ts +3 -3
  272. package/dist/types/utils/cacheMemory.d.ts.map +1 -1
  273. package/dist/types/utils/clearModuleCache.d.ts.map +1 -1
  274. package/dist/types/utils/compareVersions.d.ts +1 -1
  275. package/dist/types/utils/compareVersions.d.ts.map +1 -1
  276. package/dist/types/utils/extractErrorMessage.d.ts.map +1 -1
  277. package/dist/types/utils/getDictionarySelectorUsage.d.ts +0 -1
  278. package/dist/types/utils/getDictionarySelectorUsage.d.ts.map +1 -1
  279. package/dist/types/utils/getExtension.d.ts +1 -2
  280. package/dist/types/utils/getExtension.d.ts.map +1 -1
  281. package/dist/types/utils/getPackageJsonPath.d.ts.map +1 -1
  282. package/dist/types/utils/getStorageAttributes.d.ts +0 -1
  283. package/dist/types/utils/getStorageAttributes.d.ts.map +1 -1
  284. package/dist/types/utils/getUsedNodeTypes.d.ts +0 -1
  285. package/dist/types/utils/getUsedNodeTypes.d.ts.map +1 -1
  286. package/dist/types/utils/index.d.ts +2 -1
  287. package/dist/types/utils/logStack.d.ts.map +1 -1
  288. package/dist/types/utils/normalizePath.d.ts.map +1 -1
  289. package/dist/types/utils/parseFilePathPattern.d.ts +0 -1
  290. package/dist/types/utils/parseFilePathPattern.d.ts.map +1 -1
  291. package/dist/types/utils/pathSecurity.d.ts.map +1 -1
  292. package/dist/types/utils/retryManager.d.ts +8 -9
  293. package/dist/types/utils/retryManager.d.ts.map +1 -1
  294. package/dist/types/utils/setIntlayerIdentifier.d.ts.map +1 -1
  295. package/dist/types/utils/stringFormatter/camelCaseToKebabCase.d.ts.map +1 -1
  296. package/dist/types/utils/stringFormatter/camelCaseToSentence.d.ts.map +1 -1
  297. package/dist/types/utils/stringFormatter/kebabCaseToCamelCase.d.ts.map +1 -1
  298. package/dist/types/utils/stringFormatter/toLowerCamelCase.d.ts.map +1 -1
  299. package/package.json +11 -7
  300. package/dist/cjs/built.browser.cjs +0 -46
  301. package/dist/cjs/built.browser.cjs.map +0 -1
  302. package/dist/esm/built.browser.mjs +0 -32
  303. package/dist/esm/built.browser.mjs.map +0 -1
  304. package/dist/types/built.browser.d.ts +0 -27
  305. package/dist/types/built.browser.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"parseFileContent.cjs","names":["getProjectRequire","loadEnvFile"],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n envVarOptions?: LoadEnvFileOptions;\n projectRequire?: NodeJS.Require;\n additionalEnvVars?: Record<string, string>;\n /**\n * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n * Example:\n * mocks: {\n * '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n * }\n */\n mocks?: Record<string, any>;\n /**\n * Optional alias map if you want to redirect specifiers.\n * Useful when user code imports a subpath you want to collapse.\n * Example:\n * aliases: { '@intlayer/config/built': '@intlayer/config' }\n */\n aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n 'Buffer',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'queueMicrotask',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'AbortController',\n 'AbortSignal',\n 'performance',\n 'fetch',\n 'crypto',\n 'structuredClone',\n] as const;\n\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n options ?? {};\n\n let additionalGlobalVar = {};\n\n const baseRequire: NodeJS.Require =\n typeof projectRequire === 'function' ? projectRequire : getProjectRequire();\n\n // Wrap require to honor mocks and aliases inside the VM\n const mockedRequire: NodeJS.Require = (() => {\n const mockTable = Object.assign(\n {\n esbuild,\n },\n mocks\n );\n const aliasTable = Object.assign({}, aliases);\n\n const wrappedRequire = function mockableRequire(id: string) {\n const target = aliasTable?.[id] ? aliasTable[id] : id;\n\n if (mockTable && Object.hasOwn(mockTable, target)) {\n return mockTable[target];\n }\n\n // If the original id was aliased, allow mocks to be defined on either key.\n if (target !== id && mockTable && Object.hasOwn(mockTable, id)) {\n return mockTable[id];\n }\n\n return baseRequire(target);\n } as NodeJS.Require;\n\n // Mirror NodeJS.Require properties\n wrappedRequire.resolve = baseRequire.resolve.bind(baseRequire);\n wrappedRequire.main = baseRequire.main;\n wrappedRequire.extensions = baseRequire.extensions;\n wrappedRequire.cache = baseRequire.cache;\n\n return wrappedRequire;\n })();\n\n try {\n // Dynamically try to require React if it's installed in the project\n additionalGlobalVar = {\n React: baseRequire('react'),\n };\n } catch (_err) {\n // React is not installed, so we inject a dummy React object to capture JSX elements\n // This allows using JSX in content declarations even if React is not installed (e.g. in Solid.js or Vue projects)\n // because esbuild's tsx loader defaults to React.createElement.\n additionalGlobalVar = {\n React: {\n createElement: (type: any, props: any, ...children: any[]) => ({\n type,\n props: {\n ...props,\n children: children.length <= 1 ? children[0] : children,\n },\n }),\n Fragment: Symbol.for('react.fragment'),\n },\n };\n }\n\n const sandboxContext: Context = {\n exports: {\n default: {},\n },\n module: {\n exports: {},\n },\n process: {\n ...process,\n env: {\n ...process.env,\n ...loadEnvFile(envVarOptions),\n ...additionalEnvVars,\n },\n },\n console,\n require: mockedRequire,\n ...additionalGlobalVar,\n };\n\n for (const key of NODE_GLOBALS) {\n if (!(key in sandboxContext) && key in globalThis) {\n (sandboxContext as Record<string, unknown>)[key] =\n globalThis[key as keyof typeof globalThis];\n }\n }\n\n return sandboxContext;\n};\n\nexport const parseFileContent = <T>(\n fileContentString: string,\n options?: SandBoxContextOptions\n): T | undefined => {\n const sandboxContext = getSandBoxContext(options);\n\n // Force strict mode so illegal writes throw instead of silently failing.\n runInNewContext(`\"use strict\";\\n${fileContentString}`, sandboxContext);\n\n const candidates: unknown[] = [\n sandboxContext.exports?.default,\n sandboxContext.module?.exports?.defaults,\n sandboxContext.module?.exports?.default,\n sandboxContext.module?.exports,\n ];\n\n let result: T | undefined;\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof candidate === 'object' &&\n Object.keys(candidate as object).length > 0\n ) {\n result = candidate as T;\n break;\n }\n }\n\n // Drop heavy references so the V8 context created by runInNewContext can be\n // garbage-collected promptly. The extracted `result` is a plain data object\n // and does not retain the sandbox.\n (sandboxContext as Record<string, unknown>).require = undefined;\n (sandboxContext as Record<string, unknown>).process = undefined;\n (sandboxContext as Record<string, unknown>).React = undefined;\n (sandboxContext as Record<string, unknown>).module = undefined;\n (sandbox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ACH,KAAK;IACH,GAAG,QAAQ;IACX,GAAGC,gCAAY,cAAc;IAC7B,GAAG;IACJ;GACF;EACD;EACA,SAAS;EACT,GAAG;EACJ;AAED,MAAK,MAAM,OAAO,aAChB,KAAI,EAAE,OAAO,mBAAmB,OAAO,WACrC,CAAC,eAA2C,OAC1C,WAAW;AAIjB,QAAO;;AAGT,MAAa,oBACX,mBACA,YACkB;CAClB,MAAM,iBAAiB,kBAAkB,QAAQ;AAGjD,8BAAgB,kBAAkB,qBAAqB,eAAe;CAEtE,MAAM,aAAwB;EAC5B,eAAe,SAAS;EACxB,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ;EACxB;CAED,IAAI;AACJ,MAAK,MAAM,aAAa,WACtB,KACE,aACA,OAAO,cAAc,YACrB,OAAO,KAAK,UAAoB,CAAC,SAAS,GAC1C;AACA,WAAS;AACT;;AAOJ,CAAC,eAA2C,UAAU;AACtD,CAAC,eAA2C,UAAU;AACtD,CAAC,eAA2C,QAAQ;AACpD,CAAC,eAA2C,SAAS;AACrD,CAAC,eAA2C,UAAU;AAEtD,QAAO"}
1
+ {"version":3,"file":"parseFileContent.cjs","names":["getProjectRequire","loadEnvFile"],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n envVarOptions?: LoadEnvFileOptions;\n projectRequire?: NodeJS.Require;\n additionalEnvVars?: Record<string, string>;\n /**\n * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n * Example:\n * mocks: {\n * '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n * }\n */\n mocks?: Record<string, any>;\n /**\n * Optional alias map if you want to redirect specifiers.\n * Useful when user code imports a subpath you want to collapse.\n * Example:\n * aliases: { '@intlayer/config/built': '@intlayer/config' }\n */\n aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n 'Buffer',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'queueMicrotask',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'AbortController',\n 'AbortSignal',\n 'performance',\n 'fetch',\n 'crypto',\n 'structuredClone',\n] as const;\n\n/**\n * Cache of the project's React module (or the JSX-capturing fallback) keyed by\n * the require's resolution paths. Node does not cache *failed* resolutions, so\n * without this every sandbox creation in a non-React project (Vue, Svelte,\n * Angular…) pays a full node_modules walk that ends in a throw.\n */\nconst reactModuleCache = new Map<string, { React: unknown }>();\n\n/**\n * Fallback React implementation used when React is not installed in the\n * project. It captures JSX elements as plain objects so JSX can be used in\n * content declarations (esbuild's tsx loader defaults to React.createElement).\n */\nconst createFallbackReact = () => ({\n createElement: (type: any, props: any, ...children: any[]) => ({\n type,\n props: {\n ...props,\n children: children.length <= 1 ? children[0] : children,\n },\n }),\n Fragment: Symbol.for('react.fragment'),\n});\n\nconst getReactGlobal = (baseRequire: NodeJS.Require): { React: unknown } => {\n // resolve.paths() is computed in-memory (no fs access) and identifies the\n // node_modules chain this require instance resolves against.\n const resolutionKey =\n baseRequire.resolve.paths?.('react')?.join('|') ?? '<default>';\n\n const cachedReactModule = reactModuleCache.get(resolutionKey);\n if (cachedReactModule) return cachedReactModule;\n\n let reactGlobal: { React: unknown };\n try {\n // Dynamically try to require React if it's installed in the project\n reactGlobal = { React: baseRequire('react') };\n } catch (_err) {\n reactGlobal = { React: createFallbackReact() };\n }\n\n reactModuleCache.set(resolutionKey, reactGlobal);\n\n return reactGlobal;\n};\n\n/**\n * Snapshot of the non-env `process` properties, taken once at module load.\n * Spreading `process` enumerates ~100 properties (some behind getters); doing\n * it per sandbox is wasteful since everything except `env` is static.\n */\nconst processSnapshot = { ...process };\n\n/**\n * Builds the global context handed to `runInNewContext`.\n *\n * SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh\n * module/exports, controlled env), NOT for containment. It exposes the real\n * project `require`, a copy of `process`, and `fetch` — code executed here has\n * full host privileges. Only ever run trusted, build-time project files\n * (same trust model as `vite.config.ts`).\n */\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n options ?? {};\n\n const baseRequire: NodeJS.Require =\n typeof projectRequire === 'function' ? projectRequire : getProjectRequire();\n\n // Wrap require to honor mocks and aliases inside the VM\n const mockedRequire: NodeJS.Require = (() => {\n const mockTable = Object.assign(\n {\n esbuild,\n },\n mocks\n );\n const aliasTable = Object.assign({}, aliases);\n\n const wrappedRequire = function mockableRequire(id: string) {\n const target = aliasTable?.[id] ? aliasTable[id] : id;\n\n if (mockTable && Object.hasOwn(mockTable, target)) {\n return mockTable[target];\n }\n\n // If the original id was aliased, allow mocks to be defined on either key.\n if (target !== id && mockTable && Object.hasOwn(mockTable, id)) {\n return mockTable[id];\n }\n\n return baseRequire(target);\n } as NodeJS.Require;\n\n // Mirror NodeJS.Require properties\n wrappedRequire.resolve = baseRequire.resolve.bind(baseRequire);\n wrappedRequire.main = baseRequire.main;\n wrappedRequire.extensions = baseRequire.extensions;\n wrappedRequire.cache = baseRequire.cache;\n\n return wrappedRequire;\n })();\n\n const sandboxContext: Context = {\n exports: {\n default: {},\n },\n module: {\n exports: {},\n },\n process: {\n ...processSnapshot,\n env: {\n ...process.env,\n ...loadEnvFile(envVarOptions),\n ...additionalEnvVars,\n },\n },\n console,\n require: mockedRequire,\n ...getReactGlobal(baseRequire),\n };\n\n for (const key of NODE_GLOBALS) {\n if (!(key in sandboxContext) && key in globalThis) {\n (sandboxContext as Record<string, unknown>)[key] =\n globalThis[key as keyof typeof globalThis];\n }\n }\n\n return sandboxContext;\n};\n\nexport const parseFileContent = <T>(\n fileContentString: string,\n options?: SandBoxContextOptions\n): T | undefined => {\n const sandboxContext = getSandBoxContext(options);\n\n // Force strict mode so illegal writes throw instead of silently failing.\n runInNewContext(`\"use strict\";\\n${fileContentString}`, sandboxContext);\n\n const candidates: unknown[] = [\n sandboxContext.exports?.default,\n sandboxContext.module?.exports?.defaults,\n sandboxContext.module?.exports?.default,\n sandboxContext.module?.exports,\n ];\n\n let result: T | undefined;\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof candidate === 'object' &&\n Object.keys(candidate as object).length > 0\n ) {\n result = candidate as T;\n break;\n }\n }\n\n // Drop heavy references so the V8 context created by runInNewContext can be\n // garbage-collected promptly. The extracted `result` is a plain data object\n // and does not retain the sandbox.\n (sandboxContext as Record<string, unknown>).require = undefined;\n (sandboxContext as Record<string, unknown>).process = undefined;\n (sandboxContext as Record<string, unknown>).React = undefined;\n (sandboxContext as Record<string, unknown>).module = undefined;\n (sandboxContext as Record<string, unknown>).exports = undefined;\n\n return result;\n};\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,mCAAmB,IAAI,IAAgC;;;;;;AAO7D,MAAM,6BAA6B;CACjC,gBAAgB,MAAW,OAAY,GAAG,cAAqB;EAC7D;EACA,OAAO;GACL,GAAG;GACH,UAAU,SAAS,UAAU,IAAI,SAAS,KAAK;EACjD;CACF;CACA,UAAU,OAAO,IAAI,gBAAgB;AACvC;AAEA,MAAM,kBAAkB,gBAAoD;CAG1E,MAAM,gBACJ,YAAY,QAAQ,QAAQ,OAAO,CAAC,EAAE,KAAK,GAAG,KAAK;CAErD,MAAM,oBAAoB,iBAAiB,I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O,mBAAmB,OAAO,YACrC,AAAC,eAA2C,OAC1C,WAAW;CAIjB,OAAO;AACT;AAEA,MAAa,oBACX,mBACA,YACkB;CAClB,MAAM,iBAAiB,kBAAkB,OAAO;CAGhD,6BAAgB,kBAAkB,qBAAqB,cAAc;CAErE,MAAM,aAAwB;EAC5B,eAAe,SAAS;EACxB,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ;CACzB;CAEA,IAAI;CACJ,KAAK,MAAM,aAAa,YACtB,IACE,aACA,OAAO,cAAc,YACrB,OAAO,KAAK,SAAmB,CAAC,CAAC,SAAS,GAC1C;EACA,SAAS;EACT;CACF;CAMF,AAAC,eAA2C,UAAU;CACtD,AAAC,eAA2C,UAAU;CACtD,AAAC,eAA2C,QAAQ;CACpD,AAAC,eAA2C,SAAS;CACrD,AAAC,eAA2C,UAAU;CAEtD,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
+ const require_utils_cacheMemory = require('../utils/cacheMemory.cjs');
3
3
  const require_utils_getPackageJsonPath = require('../utils/getPackageJsonPath.cjs');
4
4
  const require_loadExternalFile_bundleFile = require('./bundleFile.cjs');
5
5
  let node_fs = require("node:fs");
@@ -9,9 +9,23 @@ let esbuild = require("esbuild");
9
9
  let node_url = require("node:url");
10
10
 
11
11
  //#region src/loadExternalFile/transpileTSToCJS.ts
12
+ /**
13
+ * Cache of resolved tsconfig paths keyed by the file's directory.
14
+ * Avoids re-walking to package.json + existsSync on every transpilation.
15
+ */
16
+ const tsConfigPathCache = /* @__PURE__ */ new Map();
12
17
  const getTsConfigPath = (filePath) => {
13
- const tsconfigPath = (0, node_path.join)(require_utils_getPackageJsonPath.getPackageJsonPath((0, node_path.dirname)(filePath)).baseDir, "tsconfig.json");
14
- return (0, node_fs.existsSync)(tsconfigPath) ? tsconfigPath : void 0;
18
+ const fileDirectory = (0, node_path.dirname)(filePath);
19
+ if (tsConfigPathCache.has(fileDirectory)) return tsConfigPathCache.get(fileDirectory);
20
+ let resolvedPath;
21
+ try {
22
+ const tsconfigPath = (0, node_path.join)(require_utils_getPackageJsonPath.getPackageJsonPath(fileDirectory).baseDir, "tsconfig.json");
23
+ resolvedPath = (0, node_fs.existsSync)(tsconfigPath) ? tsconfigPath : void 0;
24
+ } catch {
25
+ resolvedPath = void 0;
26
+ }
27
+ tsConfigPathCache.set(fileDirectory, resolvedPath);
28
+ return resolvedPath;
15
29
  };
16
30
  const getTransformationOptions = (filePath) => ({
17
31
  loader: {
@@ -31,15 +45,85 @@ const getTransformationOptions = (filePath) => ({
31
45
  write: false,
32
46
  packages: "external",
33
47
  bundle: true,
48
+ metafile: true,
34
49
  tsconfig: getTsConfigPath(filePath),
35
50
  define: {
36
51
  "import.meta.url": JSON.stringify((0, node_url.pathToFileURL)(filePath).href),
37
52
  "import.meta.env": "process.env"
38
53
  }
39
54
  });
55
+ /**
56
+ * In-memory cache of transpiled outputs keyed by entry file path (one entry
57
+ * per file, so re-transpilations replace rather than accumulate).
58
+ * The entry file is validated by content hash; bundled relative imports are
59
+ * validated by mtime + size so an edited dependency invalidates the cache.
60
+ */
61
+ const transpileCache = /* @__PURE__ */ new Map();
62
+ const isInputUnchanged = (input) => {
63
+ try {
64
+ const stats = (0, node_fs.statSync)(input.path);
65
+ return stats.mtimeMs === input.mtimeMs && stats.size === input.size;
66
+ } catch {
67
+ return false;
68
+ }
69
+ };
70
+ const getCachedTranspilation = (filePath, codeHash, optionsKey) => {
71
+ const cacheEntry = transpileCache.get(filePath);
72
+ if (!cacheEntry) return void 0;
73
+ if (cacheEntry.codeHash !== codeHash) return void 0;
74
+ if (cacheEntry.optionsKey !== optionsKey) return void 0;
75
+ if (!cacheEntry.inputs.every(isInputUnchanged)) return void 0;
76
+ return cacheEntry.output;
77
+ };
78
+ /**
79
+ * Extracts the fingerprints of every bundled input from the esbuild metafile.
80
+ * Returns `undefined` when an input cannot be fingerprinted (the result should
81
+ * then not be cached, as invalidation would be unreliable).
82
+ */
83
+ const getInputFingerprints = (metafile, entryFilePath) => {
84
+ if (!metafile) return void 0;
85
+ const resolvedEntryFilePath = (0, node_path.resolve)(entryFilePath);
86
+ const inputs = [];
87
+ for (const inputPath of Object.keys(metafile.inputs)) {
88
+ if (inputPath === "<stdin>") continue;
89
+ if (inputPath.includes(":") && !(0, node_path.isAbsolute)(inputPath)) return void 0;
90
+ const absoluteInputPath = (0, node_path.isAbsolute)(inputPath) ? inputPath : (0, node_path.resolve)(process.cwd(), inputPath);
91
+ if (absoluteInputPath === resolvedEntryFilePath) continue;
92
+ try {
93
+ const stats = (0, node_fs.statSync)(absoluteInputPath);
94
+ inputs.push({
95
+ path: absoluteInputPath,
96
+ mtimeMs: stats.mtimeMs,
97
+ size: stats.size
98
+ });
99
+ } catch {
100
+ return;
101
+ }
102
+ }
103
+ return inputs;
104
+ };
105
+ const setCachedTranspilation = (filePath, codeHash, optionsKey, moduleResult, output) => {
106
+ const inputs = getInputFingerprints(moduleResult.metafile, filePath);
107
+ if (!inputs) return;
108
+ transpileCache.set(filePath, {
109
+ codeHash,
110
+ optionsKey,
111
+ output,
112
+ inputs
113
+ });
114
+ };
115
+ /** Clears the in-memory transpilation cache (mainly for tests). */
116
+ const clearTranspileCache = () => {
117
+ transpileCache.clear();
118
+ tsConfigPathCache.clear();
119
+ };
40
120
  const transpileTSToCJSSync = (code, filePath, options) => {
41
121
  const loader = require_loadExternalFile_bundleFile.getLoader((0, node_path.extname)(filePath));
42
122
  const { esbuildInstance, ...buildOptions } = options ?? {};
123
+ const codeHash = require_utils_cacheMemory.computeKeyId([code]);
124
+ const optionsKey = require_utils_cacheMemory.computeKeyId([buildOptions]);
125
+ const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);
126
+ if (typeof cachedOutput === "string") return cachedOutput;
43
127
  const esbuildBuildSync = esbuildInstance?.buildSync ?? esbuild.buildSync;
44
128
  const g = globalThis;
45
129
  const hadFilename = typeof g.__filename === "string";
@@ -70,12 +154,18 @@ const transpileTSToCJSSync = (code, filePath, options) => {
70
154
  else g.__dirname = prevDirname;
71
155
  }
72
156
  }
73
- return moduleResult.outputFiles?.[0]?.text;
157
+ const moduleResultString = moduleResult.outputFiles?.[0]?.text;
158
+ if (typeof moduleResultString === "string") setCachedTranspilation(filePath, codeHash, optionsKey, moduleResult, moduleResultString);
159
+ return moduleResultString;
74
160
  };
75
161
  const transpileTSToCJS = async (code, filePath, options) => {
76
162
  const loader = require_loadExternalFile_bundleFile.getLoader((0, node_path.extname)(filePath));
77
163
  const { esbuildInstance, ...buildOptions } = options ?? {};
78
- const ctx = await (esbuildInstance?.context ?? esbuild.context)({
164
+ const codeHash = require_utils_cacheMemory.computeKeyId([code]);
165
+ const optionsKey = require_utils_cacheMemory.computeKeyId([buildOptions]);
166
+ const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);
167
+ if (typeof cachedOutput === "string") return cachedOutput;
168
+ const moduleResult = await (esbuildInstance?.build ?? esbuild.build)({
79
169
  stdin: {
80
170
  contents: code,
81
171
  loader,
@@ -85,14 +175,13 @@ const transpileTSToCJS = async (code, filePath, options) => {
85
175
  ...getTransformationOptions(filePath),
86
176
  ...buildOptions
87
177
  });
88
- try {
89
- return (await ctx.rebuild()).outputFiles?.[0].text;
90
- } finally {
91
- await ctx.dispose();
92
- }
178
+ const moduleResultString = moduleResult.outputFiles?.[0]?.text;
179
+ if (typeof moduleResultString === "string") setCachedTranspilation(filePath, codeHash, optionsKey, moduleResult, moduleResultString);
180
+ return moduleResultString;
93
181
  };
94
182
 
95
183
  //#endregion
184
+ exports.clearTranspileCache = clearTranspileCache;
96
185
  exports.transpileTSToCJS = transpileTSToCJS;
97
186
  exports.transpileTSToCJSSync = transpileTSToCJSSync;
98
187
  //# sourceMappingURL=transpileTSToCJS.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"transpileTSToCJS.cjs","names":["getPackageJsonPath","getLoader","buildSync","context"],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n buildSync,\n context,\n} from 'esbuild';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const tsconfigPath = join(\n getPackageJsonPath(dirname(filePath)).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n return existsSync(tsconfigPath) ? tsconfigPath : undefined;\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n //\n // IMPORTANT: We save/restore the globals so this temporary shim does not leak\n // to other Vite plugins (e.g. `@vitejs/plugin-react-swc`) that check\n // `typeof __dirname !== \"undefined\"` to locate their own assets.\n const g = globalThis as Record<string, unknown>;\n const hadFilename = typeof g.__filename === 'string';\n const prevFilename = g.__filename;\n const prevDirname = g.__dirname;\n\n if (!hadFilename) {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n g.__filename = esbuildEntry;\n g.__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n let moduleResult: BuildResult;\n try {\n moduleResult = esbuildBuildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n } finally {\n // Always restore the previous values so the globals don't linger.\n if (!hadFilename) {\n if (prevFilename === undefined) {\n delete g.__filename;\n } else {\n g.__filename = prevFilename;\n }\n if (prevDirname === undefined) {\n delete g.__dirname;\n } else {\n g.__dirname = prevDirname;\n }\n }\n }\n\n const moduleResultString = moduleResult!.outputFiles?.[0]?.text;\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n // Use context() + rebuild() + dispose() so esbuild deterministically releases\n // Go-subprocess resources for each one-shot transpilation, preventing them\n // from accumulating between rapid HMR-driven file changes.\n const esbuildContext = esbuildInstance?.context ?? context;\n\n const ctx = await esbuildContext({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n try {\n const moduleResult = await ctx.rebuild();\n return moduleResult.outputFiles?.[0].text;\n } finally {\n await ctx.dispose();\n }\n};\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,mBAAmB,aAAyC;CAChE,MAAM,mCACJA,2EAA2B,SAAS,CAAC,CAAC,SACtC,gBACD;AAGD,gCAAkB,aAAa,GAAG,eAAe;;AAGnD,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;EACT;CACD,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,QAAQ;CACR,UAAU,gBAAgB,SAAS;CACnC,QAAQ;EACN,mBAAmB,KAAK,sCAAwB,SAAS,CAAC,KAAK;EAC/D,mBAAmB;EACpB;CACF;AAED,MAAa,wBACX,MACA,UACA,YACuB;CAEvB,MAAM,SAASC,qEADW,SACQ,CAAC;CAEnC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,WAAW,EAAE;CAC1D,MAAM,mBAAmB,iBAAiB,aAAaC;CAYvD,MAAM,IAAI;CACV,MAAM,cAAc,OAAO,EAAE,eAAe;CAC5C,MAAM,eAAe,EAAE;CACvB,MAAM,cAAc,EAAE;AAEtB,KAAI,CAAC,YACH,KAAI;EAEF,MAAM,4FAAuB,CAAC,QAAQ,UAAU;AAChD,IAAE,aAAa;AACf,IAAE,mCAAoB,aAAa;SAC7B;CAKV,IAAI;AACJ,KAAI;AACF,iBAAe,iBAAiB;GAC9B,OAAO;IACL,UAAU;IACV;IACA,mCAAoB,SAAS;IAC7B,YAAY;IACb;GACD,GAAG,yBAAyB,SAAS;GACrC,GAAG;GACJ,CAAC;WACM;AAER,MAAI,CAAC,aAAa;AAChB,OAAI,iBAAiB,OACnB,QAAO,EAAE;OAET,GAAE,aAAa;AAEjB,OAAI,gBAAgB,OAClB,QAAO,EAAE;OAET,GAAE,YAAY;;;AAOpB,QAF2B,aAAc,cAAc,IAAI;;AAK7D,MAAa,mBAAmB,OAC9B,MACA,UACA,YACgC;CAEhC,MAAM,SAASD,qEADW,SACQ,CAAC;CAEnC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,WAAW,EAAE;CAM1D,MAAM,MAAM,OAFW,iBAAiB,WAAWE,iBAElB;EAC/B,OAAO;GACL,UAAU;GACV;GACA,mCAAoB,SAAS;GAC7B,YAAY;GACb;EACD,GAAG,yBAAyB,SAAS;EACrC,GAAG;EACJ,CAAC;AAEF,KAAI;AAEF,UAAO,MADoB,IAAI,SAAS,EACpB,cAAc,GAAG;WAC7B;AACR,QAAM,IAAI,SAAS"}
1
+ {"version":3,"file":"transpileTSToCJS.cjs","names":["getPackageJsonPath","getLoader","computeKeyId","buildSync","build"],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Metafile,\n} from 'esbuild';\nimport { computeKeyId } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\n/**\n * Cache of resolved tsconfig paths keyed by the file's directory.\n * Avoids re-walking to package.json + existsSync on every transpilation.\n */\nconst tsConfigPathCache = new Map<string, string | undefined>();\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const fileDirectory = dirname(filePath);\n\n if (tsConfigPathCache.has(fileDirectory)) {\n return tsConfigPathCache.get(fileDirectory);\n }\n\n let resolvedPath: string | undefined;\n try {\n const tsconfigPath = join(\n getPackageJsonPath(fileDirectory).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : undefined;\n } catch {\n // No package.json found up the tree — transpile without a tsconfig\n resolvedPath = undefined;\n }\n\n tsConfigPathCache.set(fileDirectory, resolvedPath);\n\n return resolvedPath;\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n // The metafile lists every bundled input, which the transpile cache uses to\n // invalidate when an imported file changes (the entry itself is keyed by hash).\n metafile: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\n/** Fingerprint of a bundled input file, used to detect changes without re-reading it. */\ntype TranspileCacheInput = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype TranspileCacheEntry = {\n /** Hash of the entry file's source code. */\n codeHash: string;\n /** Hash of the build options, so different option sets don't collide. */\n optionsKey: string;\n /** The transpiled CJS output. */\n output: string;\n /** Fingerprints of every non-entry input bundled into the output. */\n inputs: TranspileCacheInput[];\n};\n\n/**\n * In-memory cache of transpiled outputs keyed by entry file path (one entry\n * per file, so re-transpilations replace rather than accumulate).\n * The entry file is validated by content hash; bundled relative imports are\n * validated by mtime + size so an edited dependency invalidates the cache.\n */\nconst transpileCache = new Map<string, TranspileCacheEntry>();\n\nconst isInputUnchanged = (input: TranspileCacheInput): boolean => {\n try {\n const stats = statSync(input.path);\n return stats.mtimeMs === input.mtimeMs && stats.size === input.size;\n } catch {\n // File removed or unreadable — treat as changed\n return false;\n }\n};\n\nconst getCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string\n): string | undefined => {\n const cacheEntry = transpileCache.get(filePath);\n\n if (!cacheEntry) return undefined;\n if (cacheEntry.codeHash !== codeHash) return undefined;\n if (cacheEntry.optionsKey !== optionsKey) return undefined;\n if (!cacheEntry.inputs.every(isInputUnchanged)) return undefined;\n\n return cacheEntry.output;\n};\n\n/**\n * Extracts the fingerprints of every bundled input from the esbuild metafile.\n * Returns `undefined` when an input cannot be fingerprinted (the result should\n * then not be cached, as invalidation would be unreliable).\n */\nconst getInputFingerprints = (\n metafile: Metafile | undefined,\n entryFilePath: string\n): TranspileCacheInput[] | undefined => {\n if (!metafile) return undefined;\n\n const resolvedEntryFilePath = resolve(entryFilePath);\n const inputs: TranspileCacheInput[] = [];\n\n for (const inputPath of Object.keys(metafile.inputs)) {\n // The entry itself is provided via stdin and validated by content hash.\n // esbuild labels it \"<stdin>\", or with the sourcefile path when set.\n if (inputPath === '<stdin>') continue;\n // Virtual modules from plugins (e.g. \"plugin:...\") cannot be fingerprinted\n if (inputPath.includes(':') && !isAbsolute(inputPath)) return undefined;\n\n const absoluteInputPath = isAbsolute(inputPath)\n ? inputPath\n : resolve(process.cwd(), inputPath);\n\n if (absoluteInputPath === resolvedEntryFilePath) continue;\n\n try {\n const stats = statSync(absoluteInputPath);\n inputs.push({\n path: absoluteInputPath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {\n return undefined;\n }\n }\n\n return inputs;\n};\n\nconst setCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string,\n moduleResult: BuildResult,\n output: string\n): void => {\n const inputs = getInputFingerprints(moduleResult.metafile, filePath);\n\n // Without a usable metafile the cache cannot be invalidated reliably — skip\n if (!inputs) return;\n\n transpileCache.set(filePath, { codeHash, optionsKey, output, inputs });\n};\n\n/** Clears the in-memory transpilation cache (mainly for tests). */\nexport const clearTranspileCache = (): void => {\n transpileCache.clear();\n tsConfigPathCache.clear();\n};\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n //\n // IMPORTANT: We save/restore the globals so this temporary shim does not leak\n // to other Vite plugins (e.g. `@vitejs/plugin-react-swc`) that check\n // `typeof __dirname !== \"undefined\"` to locate their own assets.\n const g = globalThis as Record<string, unknown>;\n const hadFilename = typeof g.__filename === 'string';\n const prevFilename = g.__filename;\n const prevDirname = g.__dirname;\n\n if (!hadFilename) {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n g.__filename = esbuildEntry;\n g.__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n let moduleResult: BuildResult;\n try {\n moduleResult = esbuildBuildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n } finally {\n // Always restore the previous values so the globals don't linger.\n if (!hadFilename) {\n if (prevFilename === undefined) {\n // biome-ignore lint/performance/noDelete: the global must be truly absent — assigning undefined would leave the key present and break `typeof __filename` checks in other tools\n delete g.__filename;\n } else {\n g.__filename = prevFilename;\n }\n if (prevDirname === undefined) {\n // biome-ignore lint/performance/noDelete: same as __filename above\n delete g.__dirname;\n } else {\n g.__dirname = prevDirname;\n }\n }\n }\n\n const moduleResultString = moduleResult!.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult!,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n // A one-shot build() releases its Go-side resources on completion and costs a\n // single service round-trip (context()+rebuild()+dispose() costs three).\n const esbuildBuild = esbuildInstance?.build ?? build;\n\n const moduleResult = await esbuildBuild({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,oCAAoB,IAAI,IAAgC;AAE9D,MAAM,mBAAmB,aAAyC;CAChE,MAAM,uCAAwB,QAAQ;CAEtC,IAAI,kBAAkB,IAAI,aAAa,GACrC,OAAO,kBAAkB,IAAI,aAAa;CAG5C,IAAI;CACJ,IAAI;EACF,MAAM,mCACJA,oDAAmB,aAAa,CAAC,CAA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AI,CAAC,aAAa;GAChB,IAAI,iBAAiB,QAEnB,OAAO,EAAE;QAET,EAAE,aAAa;GAEjB,IAAI,gBAAgB,QAElB,OAAO,EAAE;QAET,EAAE,YAAY;EAElB;CACF;CAEA,MAAM,qBAAqB,aAAc,cAAc,EAAE,EAAE;CAE3D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT;AAEA,MAAa,mBAAmB,OAC9B,MACA,UACA,YACgC;CAEhC,MAAM,SAASF,qEADW,QACO,CAAC;CAElC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,WAAW,CAAC;CAEzD,MAAM,WAAWC,uCAAa,CAAC,IAAI,CAAC;CACpC,MAAM,aAAaA,uCAAa,CAAC,YAAY,CAAC;CAE9C,MAAM,eAAe,uBAAuB,UAAU,UAAU,UAAU;CAC1E,IAAI,OAAO,iBAAiB,UAAU,OAAO;CAM7C,MAAM,eAAe,OAFA,iBAAiB,SAASE,cAER,CAAC;EACtC,OAAO;GACL,UAAU;GACV;GACA,mCAAoB,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC;CAED,MAAM,qBAAqB,aAAa,cAAc,EAAE,EAAE;CAE1D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT"}
@@ -94,7 +94,8 @@ const colorizeObject = (obj, indentLevel = 0, indentSize = 2, key) => {
94
94
  return `{\n${keys.map((key) => {
95
95
  const coloredKey = colorize(`"${key}"`, require_colors.GREY_LIGHT);
96
96
  const value = obj[key];
97
- return `${nextIndent}${coloredKey}: ${colorizeObject(value, indentLevel + 1, indentSize, key)}`;
97
+ const coloredValue = colorizeObject(value, indentLevel + 1, indentSize, key);
98
+ return `${nextIndent}${coloredKey}: ${coloredValue}`;
98
99
  }).join(",\n")}\n${indent}}`;
99
100
  }
100
101
  return colorize(String(obj), require_colors.GREY);
@@ -1 +1 @@
1
- {"version":3,"file":"logger.cjs","names":["RESET","GREEN","BEIGE","GREY","BLUE","GREY_DARK","WHITE","GREY_LIGHT","RED"],"sources":["../../src/logger.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n CustomIntlayerConfig,\n IntlayerConfig,\n} from '@intlayer/types/config';\nimport type * as ANSIColorsTypes from './colors';\nimport {\n BEIGE,\n BLUE,\n GREEN,\n GREY,\n GREY_DARK,\n GREY_LIGHT,\n RED,\n RESET,\n WHITE,\n} from './colors';\n\nexport type ANSIColorsType =\n (typeof ANSIColorsTypes)[keyof typeof ANSIColorsTypes];\n\nexport type Details = {\n isVerbose?: boolean;\n level?: 'info' | 'warn' | 'error' | 'debug';\n config?: CustomIntlayerConfig['log'];\n};\n\nexport type Logger = (content: any, details?: Details) => void;\n\nlet loggerPrefix: string | undefined;\n\nexport const setPrefix = (prefix: string | undefined) => {\n loggerPrefix = prefix;\n};\n\nexport const getPrefix = (configPrefix?: string): string | undefined => {\n if (typeof loggerPrefix !== 'undefined') {\n return loggerPrefix;\n }\n\n return configPrefix;\n};\n\nexport const logger: Logger = (content, details) => {\n const config = details?.config ?? {};\n const mode = config.mode ?? 'default';\n\n if (mode === 'disabled' || (details?.isVerbose && mode !== 'verbose')) return;\n\n const prefix = getPrefix(config.prefix);\n const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();\n const level = details?.level ?? 'info';\n\n const logMethod =\n config[level] ?? console[level] ?? config.log ?? console.log;\n\n logMethod(...flatContent);\n};\n\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/**\n * The appLogger function takes the logger and merges it with the configuration from the intlayer config file.\n * It allows overriding the default configuration by passing a config object in the details parameter.\n * The configuration is merged with the default configuration from the intlayer config file.\n */\nexport const getAppLogger =\n (configuration?: Pick<IntlayerConfig, 'log'>, globalDetails?: Details) =>\n (content: any, details?: Details) =>\n logger(content, {\n ...(details ?? {}),\n config: {\n ...configuration?.log,\n ...globalDetails?.config,\n ...(details?.config ?? {}),\n },\n });\n\nexport const colorize = (\n string: string,\n color?: ANSIColorsType,\n reset?: boolean | ANSIColorsType\n): string =>\n color && typeof window === 'undefined'\n ? `${color}${string}${reset ? (typeof reset === 'boolean' ? RESET : reset) : RESET}`\n : string;\n\nexport const colorizeLocales = (\n locales: Locale | Locale[],\n color: ANSIColorsType = GREEN,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [locales]\n .flat()\n .map((locale) => colorize(locale, color, reset))\n .join(`, `);\n\nexport const colorizeKey = (\n keyPath: string | string[],\n color: ANSIColorsType = BEIGE,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [keyPath]\n .flat()\n .map((key) => colorize(key, color, reset))\n .join(`, `);\n\nexport const colorizePath = (\n path: string | string[],\n color: ANSIColorsType = GREY,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [path]\n .flat()\n .map((path) => colorize(path, color, reset))\n .join(`, `);\n\nexport const colorizeNumber = (\n number: number | string,\n options: Partial<Record<Intl.LDMLPluralRule, ANSIColorsType>> = {\n zero: BLUE,\n one: BLUE,\n two: BLUE,\n few: BLUE,\n many: BLUE,\n other: BLUE,\n }\n): string => {\n if (number === 0 || number === '0') {\n const color = options.zero ?? GREEN;\n return colorize(number.toString(), color);\n }\n\n // Kept inside the function. Top-level instantiation of classes/APIs\n // is treated as a side-effect and prevents tree-shaking if the function is unused.\n const rule = new Intl.PluralRules('en').select(Number(number));\n const color = options[rule];\n return colorize(number.toString(), color);\n};\n\nexport const colorizeObject = (\n obj: any,\n indentLevel = 0,\n indentSize = 2,\n key?: string\n): string => {\n const indent = ' '.repeat(indentLevel * indentSize);\n const nextIndent = ' '.repeat((indentLevel + 1) * indentSize);\n\n if (obj === null) {\n return colorize('null', BLUE);\n }\n\n if (typeof obj === 'boolean') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'number') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'string') {\n const isDateString = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(obj);\n const isUrl = obj.startsWith('http://') || obj.startsWith('https://');\n const isGlob = obj.includes('*') || obj.includes('?') || obj.includes('{');\n const isPath =\n obj.startsWith('/') ||\n obj.startsWith('./') ||\n obj.startsWith('../') ||\n /\\.[a-zA-Z0-9]{2,5}$/.test(obj);\n const isSecret =\n /^[0-9a-fA-F]{24,}$/.test(obj) || (obj.length >= 40 && !/\\s/.test(obj));\n const hasSpaces = /\\s/.test(obj);\n\n if (isDateString) return colorize(`\"${obj}\"`, BEIGE);\n if (isUrl) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isGlob) return colorize(`\"${obj}\"`, GREY);\n if (isPath) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isSecret) return colorize(`\"${obj}\"`, GREY);\n if (hasSpaces) return colorize(`\"${obj}\"`, WHITE);\n return colorize(`\"${obj}\"`, BLUE);\n }\n\n if (Array.isArray(obj)) {\n if (obj.length === 0) {\n return '[]';\n }\n const items = obj\n .map(\n (item) =>\n `${nextIndent}${colorizeObject(item, indentLevel + 1, indentSize, key)}`\n )\n .join(',\\n');\n return `[\\n${items}\\n${indent}]`;\n }\n\n if (typeof obj === 'object') {\n const keys = Object.keys(obj);\n\n if (keys.length === 0) {\n return '{}';\n }\n\n const fields = keys\n .map((key) => {\n const coloredKey = colorize(`\"${key}\"`, GREY_LIGHT);\n const value = obj[key];\n const coloredValue = colorizeObject(\n value,\n indentLevel + 1,\n indentSize,\n key\n );\n return `${nextIndent}${coloredKey}: ${coloredValue}`;\n })\n .join(',\\n');\n return `{\\n${fields}\\n${indent}}`;\n }\n\n return colorize(String(obj), GREY);\n};\n\nexport const removeColor = (text: string) =>\n // biome-ignore lint/suspicious/noControlCharactersInRegex: we need to remove the color codes\n text.replace(/\\x1b\\[[0-9;]*m/g, '');\n\nconst getLength = (length: number | number[] | string | string[]): number => {\n let value: number = 0;\n if (typeof length === 'number') {\n value = length;\n }\n if (typeof length === 'string') {\n value = length.length;\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'string')\n ) {\n value = Math.max(...length.map((str) => str.length));\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'number')\n ) {\n value = Math.max(...length);\n }\n return Math.max(value, 0);\n};\n\nconst defaultColonOptions = {\n colSize: 0,\n minSize: 0,\n maxSize: Infinity,\n pad: 'right',\n padChar: '0',\n};\n\n/**\n * Create a string of spaces of a given length.\n *\n * @param colSize - The length of the string to create.\n * @returns A string of spaces.\n */\nexport const colon = (\n text: string | string[],\n options?: {\n colSize?: number | number[] | string | string[];\n minSize?: number;\n maxSize?: number;\n pad?: 'left' | 'right';\n padChar?: string;\n }\n): string =>\n [text]\n .flat()\n .map((text) => {\n const { colSize, minSize, maxSize, pad } = {\n ...defaultColonOptions,\n ...(options ?? {}),\n };\n\n const length = getLength(colSize);\n const spacesLength = Math.max(\n minSize!,\n Math.min(maxSize!, length - removeColor(text).length)\n );\n\n if (pad === 'left') {\n return `${' '.repeat(spacesLength)}${text}`;\n }\n\n return `${text}${' '.repeat(spacesLength)}`;\n })\n .join('');\n\nexport const x = colorize('✗', RED);\nexport const v = colorize('✓', GREEN);\nexport const clock = colorize('⏲', BLUE);\n"],"mappings":";;;;AA6BA,IAAI;AAEJ,MAAa,aAAa,WAA+B;AACvD,gBAAe;;AAGjB,MAAa,aAAa,iBAA8C;AACtE,KAAI,OAAO,iBAAiB,YAC1B,QAAO;AAGT,QAAO;;AAGT,MAAa,UAAkB,SAAS,YAAY;CAClD,MAAM,SAAS,SAAS,UAAU,EAAE;CACpC,MAAM,OAAO,OAAO,QAAQ;AAE5B,KAAI,SAAS,cAAe,SAAS,aAAa,SAAS,UAAY;CAEvE,MAAM,SAAS,UAAU,OAAO,OAAO;CACvC,MAAM,cAAc,SAAS,CAAC,QAAQ,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC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,EAAE,SAAS,SAAS,SAAS,QAAQ;EACzC,GAAG;EACH,GAAI,WAAW,EAAE;EAClB;CAED,MAAM,SAAS,UAAU,QAAQ;CACjC,MAAM,eAAe,KAAK,IACxB,SACA,KAAK,IAAI,SAAU,SAAS,YAAY,KAAK,CAAC,OAAO,CACtD;AAED,KAAI,QAAQ,OACV,QAAO,GAAG,IAAI,OAAO,aAAa,GAAG;AAGvC,QAAO,GAAG,OAAO,IAAI,OAAO,aAAa;EACzC,CACD,KAAK,GAAG;AAEb,MAAa,IAAI,SAAS,KAAKK,mBAAI;AACnC,MAAa,IAAI,SAAS,KAAKP,qBAAM;AACrC,MAAa,QAAQ,SAAS,KAAKG,oBAAK"}
1
+ {"version":3,"file":"logger.cjs","names":["RESET","GREEN","BEIGE","GREY","BLUE","GREY_DARK","WHITE","GREY_LIGHT","RED"],"sources":["../../src/logger.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n CustomIntlayerConfig,\n IntlayerConfig,\n} from '@intlayer/types/config';\nimport type * as ANSIColorsTypes from './colors';\nimport {\n BEIGE,\n BLUE,\n GREEN,\n GREY,\n GREY_DARK,\n GREY_LIGHT,\n RED,\n RESET,\n WHITE,\n} from './colors';\n\nexport type ANSIColorsType =\n (typeof ANSIColorsTypes)[keyof typeof ANSIColorsTypes];\n\nexport type Details = {\n isVerbose?: boolean;\n level?: 'info' | 'warn' | 'error' | 'debug';\n config?: CustomIntlayerConfig['log'];\n};\n\nexport type Logger = (content: any, details?: Details) => void;\n\nlet loggerPrefix: string | undefined;\n\nexport const setPrefix = (prefix: string | undefined) => {\n loggerPrefix = prefix;\n};\n\nexport const getPrefix = (configPrefix?: string): string | undefined => {\n if (typeof loggerPrefix !== 'undefined') {\n return loggerPrefix;\n }\n\n return configPrefix;\n};\n\nexport const logger: Logger = (content, details) => {\n const config = details?.config ?? {};\n const mode = config.mode ?? 'default';\n\n if (mode === 'disabled' || (details?.isVerbose && mode !== 'verbose')) return;\n\n const prefix = getPrefix(config.prefix);\n const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();\n const level = details?.level ?? 'info';\n\n const logMethod =\n config[level] ?? console[level] ?? config.log ?? console.log;\n\n logMethod(...flatContent);\n};\n\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/**\n * The appLogger function takes the logger and merges it with the configuration from the intlayer config file.\n * It allows overriding the default configuration by passing a config object in the details parameter.\n * The configuration is merged with the default configuration from the intlayer config file.\n */\nexport const getAppLogger =\n (configuration?: Pick<IntlayerConfig, 'log'>, globalDetails?: Details) =>\n (content: any, details?: Details) =>\n logger(content, {\n ...(details ?? {}),\n config: {\n ...configuration?.log,\n ...globalDetails?.config,\n ...(details?.config ?? {}),\n },\n });\n\nexport const colorize = (\n string: string,\n color?: ANSIColorsType,\n reset?: boolean | ANSIColorsType\n): string =>\n color && typeof window === 'undefined'\n ? `${color}${string}${reset ? (typeof reset === 'boolean' ? RESET : reset) : RESET}`\n : string;\n\nexport const colorizeLocales = (\n locales: Locale | Locale[],\n color: ANSIColorsType = GREEN,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [locales]\n .flat()\n .map((locale) => colorize(locale, color, reset))\n .join(`, `);\n\nexport const colorizeKey = (\n keyPath: string | string[],\n color: ANSIColorsType = BEIGE,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [keyPath]\n .flat()\n .map((key) => colorize(key, color, reset))\n .join(`, `);\n\nexport const colorizePath = (\n path: string | string[],\n color: ANSIColorsType = GREY,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [path]\n .flat()\n .map((path) => colorize(path, color, reset))\n .join(`, `);\n\nexport const colorizeNumber = (\n number: number | string,\n options: Partial<Record<Intl.LDMLPluralRule, ANSIColorsType>> = {\n zero: BLUE,\n one: BLUE,\n two: BLUE,\n few: BLUE,\n many: BLUE,\n other: BLUE,\n }\n): string => {\n if (number === 0 || number === '0') {\n const color = options.zero ?? GREEN;\n return colorize(number.toString(), color);\n }\n\n // Kept inside the function. Top-level instantiation of classes/APIs\n // is treated as a side-effect and prevents tree-shaking if the function is unused.\n const rule = new Intl.PluralRules('en').select(Number(number));\n const color = options[rule];\n return colorize(number.toString(), color);\n};\n\nexport const colorizeObject = (\n obj: any,\n indentLevel = 0,\n indentSize = 2,\n key?: string\n): string => {\n const indent = ' '.repeat(indentLevel * indentSize);\n const nextIndent = ' '.repeat((indentLevel + 1) * indentSize);\n\n if (obj === null) {\n return colorize('null', BLUE);\n }\n\n if (typeof obj === 'boolean') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'number') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'string') {\n const isDateString = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(obj);\n const isUrl = obj.startsWith('http://') || obj.startsWith('https://');\n const isGlob = obj.includes('*') || obj.includes('?') || obj.includes('{');\n const isPath =\n obj.startsWith('/') ||\n obj.startsWith('./') ||\n obj.startsWith('../') ||\n /\\.[a-zA-Z0-9]{2,5}$/.test(obj);\n const isSecret =\n /^[0-9a-fA-F]{24,}$/.test(obj) || (obj.length >= 40 && !/\\s/.test(obj));\n const hasSpaces = /\\s/.test(obj);\n\n if (isDateString) return colorize(`\"${obj}\"`, BEIGE);\n if (isUrl) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isGlob) return colorize(`\"${obj}\"`, GREY);\n if (isPath) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isSecret) return colorize(`\"${obj}\"`, GREY);\n if (hasSpaces) return colorize(`\"${obj}\"`, WHITE);\n return colorize(`\"${obj}\"`, BLUE);\n }\n\n if (Array.isArray(obj)) {\n if (obj.length === 0) {\n return '[]';\n }\n const items = obj\n .map(\n (item) =>\n `${nextIndent}${colorizeObject(item, indentLevel + 1, indentSize, key)}`\n )\n .join(',\\n');\n return `[\\n${items}\\n${indent}]`;\n }\n\n if (typeof obj === 'object') {\n const keys = Object.keys(obj);\n\n if (keys.length === 0) {\n return '{}';\n }\n\n const fields = keys\n .map((key) => {\n const coloredKey = colorize(`\"${key}\"`, GREY_LIGHT);\n const value = obj[key];\n const coloredValue = colorizeObject(\n value,\n indentLevel + 1,\n indentSize,\n key\n );\n return `${nextIndent}${coloredKey}: ${coloredValue}`;\n })\n .join(',\\n');\n return `{\\n${fields}\\n${indent}}`;\n }\n\n return colorize(String(obj), GREY);\n};\n\nexport const removeColor = (text: string) =>\n // biome-ignore lint/suspicious/noControlCharactersInRegex: we need to remove the color codes\n text.replace(/\\x1b\\[[0-9;]*m/g, '');\n\nconst getLength = (length: number | number[] | string | string[]): number => {\n let value: number = 0;\n if (typeof length === 'number') {\n value = length;\n }\n if (typeof length === 'string') {\n value = length.length;\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'string')\n ) {\n value = Math.max(...length.map((str) => str.length));\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'number')\n ) {\n value = Math.max(...length);\n }\n return Math.max(value, 0);\n};\n\nconst defaultColonOptions = {\n colSize: 0,\n minSize: 0,\n maxSize: Infinity,\n pad: 'right',\n padChar: '0',\n};\n\n/**\n * Create a string of spaces of a given length.\n *\n * @param colSize - The length of the string to create.\n * @returns A string of spaces.\n */\nexport const colon = (\n text: string | string[],\n options?: {\n colSize?: number | number[] | string | string[];\n minSize?: number;\n maxSize?: number;\n pad?: 'left' | 'right';\n padChar?: string;\n }\n): string =>\n [text]\n .flat()\n .map((text) => {\n const { colSize, minSize, maxSize, pad } = {\n ...defaultColonOptions,\n ...(options ?? {}),\n };\n\n const length = getLength(colSize);\n const spacesLength = Math.max(\n minSize!,\n Math.min(maxSize!, length - removeColor(text).length)\n );\n\n if (pad === 'left') {\n return `${' '.repeat(spacesLength)}${text}`;\n }\n\n return `${text}${' '.repeat(spacesLength)}`;\n })\n .join('');\n\nexport const x = colorize('✗', RED);\nexport const v = colorize('✓', GREEN);\nexport const clock = colorize('⏲', B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D;CAC3E,IAAI,QAAgB;CACpB,IAAI,OAAO,WAAW,UACpB,QAAQ;CAEV,IAAI,OAAO,WAAW,UACpB,QAAQ,OAAO;CAEjB,IACE,MAAM,QAAQ,MAAM,KACpB,OAAO,OAAO,WAAW,OAAO,WAAW,QAAQ,GAEnD,QAAQ,KAAK,IAAI,GAAG,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC;CAErD,IACE,MAAM,QAAQ,MAAM,KACpB,OAAO,OAAO,WAAW,OAAO,WAAW,QAAQ,GAEnD,QAAQ,KAAK,IAAI,GAAG,MAAM;CAE5B,OAAO,KAAK,IAAI,OAAO,CAAC;AAC1B;AAEA,MAAM,sBAAsB;CAC1B,SAAS;CACT,SAAS;CACT,SAAS;CACT,KAAK;CACL,SAAS;AACX;;;;;;;AAQA,MAAa,SACX,MACA,YAQA,CAAC,IAAI,CAAC,CACH,KAAK,CAAC,CACN,KAAK,SAAS;CACb,MAAM,EAAE,SAAS,SAAS,SAAS,QAAQ;EACzC,GAAG;EACH,GAAI,WAAW,CAAC;CAClB;CAEA,MAAM,SAAS,UAAU,OAAO;CAChC,MAAM,eAAe,KAAK,IACxB,SACA,KAAK,IAAI,SAAU,SAAS,YAAY,IAAI,CAAC,CAAC,MAAM,CACtD;CAEA,IAAI,QAAQ,QACV,OAAO,GAAG,IAAI,OAAO,YAAY,IAAI;CAGvC,OAAO,GAAG,OAAO,IAAI,OAAO,YAAY;AAC1C,CAAC,CAAC,CACD,KAAK,EAAE;AAEZ,MAAa,IAAI,SAAS,KAAKK,kBAAG;AAClC,MAAa,IAAI,SAAS,KAAKP,oBAAK;AACpC,MAAa,QAAQ,SAAS,KAAKG,mBAAI"}
package/dist/cjs/node.cjs CHANGED
@@ -6,6 +6,8 @@ const require_configFile_searchConfigurationFile = require('./configFile/searchC
6
6
  const require_configFile_getConfiguration = require('./configFile/getConfiguration.cjs');
7
7
 
8
8
  exports.aiSchema = require_configFile_configurationSchema.aiSchema;
9
+ exports.analyticsSchema = require_configFile_configurationSchema.analyticsSchema;
10
+ exports.buildAnalyticsFields = require_configFile_buildBrowserConfiguration.buildAnalyticsFields;
9
11
  exports.buildBrowserConfiguration = require_configFile_buildBrowserConfiguration.buildBrowserConfiguration;
10
12
  exports.buildConfigurationFields = require_configFile_buildConfigurationFields.buildConfigurationFields;
11
13
  exports.buildEditorFields = require_configFile_buildBrowserConfiguration.buildEditorFields;
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_utils_getPackageJsonPath = require('./getPackageJsonPath.cjs');
4
3
  let node_module = require("node:module");
5
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"ESMxCJSHelpers.cjs","names":["getPackageJsonPath"],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":";;;;;;AAGA,MAAa,aAAa,yDAA2B;;;;;;AAOrD,MAAa,qBAAqB,aAAsC;CAEtE,MAAM,EAAE,oBAAoBA,oDAAmB,SAAS;AAExD,uCAAqB,gBAAgB;;;;;;;AAQvC,MAAa,uBAAuC,0FAClB,GAC9B"}
1
+ {"version":3,"file":"ESMxCJSHelpers.cjs","names":["getPackageJsonPath"],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":";;;;;AAGA,MAAa,aAAa,yDAA2B;;;;;;AAOrD,MAAa,qBAAqB,aAAsC;CAEtE,MAAM,EAAE,oBAAoBA,oDAAmB,QAAQ;CAEvD,sCAAqB,eAAe;AACtC;;;;;;AAOA,MAAa,uBAAuC,yFACnB,IAC7B"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_utils_getExtension = require('./getExtension.cjs');
4
3
  const require_utils_normalizePath = require('./normalizePath.cjs');
5
4
  let node_path = require("node:path");
@@ -1 +1 @@
1
- {"version":3,"file":"alias.cjs","names":["getExtension","normalizePath"],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\nexport const getAlias = ({\n configuration,\n format,\n formatter = (value: string) => value,\n}: GetAliasOptions) => {\n const extension = getExtension(\n configuration,\n format ?? configuration.build.outputFormat[0] ?? 'esm'\n );\n\n const { baseDir } = configuration.system;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.${extension}`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":";;;;;;;AAWA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAYA,wCAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,MAClD;CAED,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,SAAS,cAAc,cAAc;AAgF7C,QAAO;EACL,gCA1E4B,UAC5BC,kEAFwC,6BADZ,SAAS,gBAAgB,YACY,CAE3B,CAAC,CAyEc;EACrD,yCA5DoC,UACpCA,kEAJA,6BAJA,SACA,yBAAyB,YAID,CAGsB,CAAC,CA2DuB;EACtE,uCA9CkC,UAClCA,kEAJA,6BAJA,SACA,uBAAuB,YAID,CAGsB,CAAC,CA6CqB;EAClE,wCAhCmC,UACnCA,kEAJA,6BAJA,SACA,wBAAwB,YAID,CAGsB,CAAC,CA+BsB;EACpE,sCAlBiC,UACjCA,kEAJA,6BAJA,SACA,sBAAsB,YAID,CAGsB,CAAC,CAiBoB;EAChE,0BAV6B,UAC7BA,kEAFyC,6BADZ,WAAW,iBAAiB,YACU,CAE5B,CAAC,CASQ;EACjD"}
1
+ {"version":3,"file":"alias.cjs","names":["getExtension","normalizePath"],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\nexport const getAlias = ({\n configuration,\n format,\n formatter = (value: string) => value,\n}: GetAliasOptions) => {\n const extension = getExtension(\n configuration,\n format ?? configuration.build.outputFormat[0] ?? 'esm'\n );\n\n const { baseDir } = configuration.system;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.${extension}`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":";;;;;;AAWA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAYA,wCAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,KACnD;CAEA,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,SAAS,cAAc,cAAc;CAgF7C,OAAO;EACL,gCA1E4B,UAC5BC,kEAFwC,6BADZ,SAAS,gBAAgB,WACW,CAE3B,CAAC,CAyEc;EACpD,yCA5DoC,UACpCA,kEAJA,6BAJA,SACA,yBAAyB,WAIF,CAGsB,CAAC,CA2DuB;EACrE,uCA9CkC,UAClCA,kEAJA,6BAJA,SACA,uBAAuB,WAIF,CAGsB,CAAC,CA6CqB;EACjE,wCAhCmC,UACnCA,kEAJA,6BAJA,SACA,wBAAwB,WAIF,CAGsB,CAAC,CA+BsB;EACnE,sCAlBiC,UACjCA,kEAJA,6BAJA,SACA,sBAAsB,WAIF,CAGsB,CAAC,CAiBoB;EAC/D,0BAV6B,UAC7BA,kEAFyC,6BADZ,WAAW,iBAAiB,WACS,CAE5B,CAAC,CASQ;CACjD;AACF"}
@@ -0,0 +1,38 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region src/utils/builtConfigKeys.ts
4
+ /**
5
+ * Canonical list of configuration sections exposed as named exports by
6
+ * `@intlayer/config/built`.
7
+ *
8
+ * At build time, bundler integrations (Vite, webpack, …) alias
9
+ * `@intlayer/config/built` to the generated `.intlayer/config/configuration.mjs`
10
+ * file (see {@link getAlias} and `generateConfigurationContent`). For that alias
11
+ * to be transparent, the generated file MUST expose exactly the same named
12
+ * exports as `built.ts`; otherwise a consumer importing one of them (e.g.
13
+ * `import { analytics } from '@intlayer/config/built'`) triggers a
14
+ * `MISSING_EXPORT` bundler error.
15
+ *
16
+ * Deriving both `built.ts` and the generator from this single array guarantees
17
+ * they can never drift: adding a section here is the only change required to
18
+ * expose it in every build target.
19
+ */
20
+ const BUILT_CONFIG_KEYS = [
21
+ "internationalization",
22
+ "dictionary",
23
+ "routing",
24
+ "content",
25
+ "system",
26
+ "editor",
27
+ "analytics",
28
+ "log",
29
+ "ai",
30
+ "build",
31
+ "compiler",
32
+ "schemas",
33
+ "plugins"
34
+ ];
35
+
36
+ //#endregion
37
+ exports.BUILT_CONFIG_KEYS = BUILT_CONFIG_KEYS;
38
+ //# sourceMappingURL=builtConfigKeys.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builtConfigKeys.cjs","names":[],"sources":["../../../src/utils/builtConfigKeys.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Canonical list of configuration sections exposed as named exports by\n * `@intlayer/config/built`.\n *\n * At build time, bundler integrations (Vite, webpack, …) alias\n * `@intlayer/config/built` to the generated `.intlayer/config/configuration.mjs`\n * file (see {@link getAlias} and `generateConfigurationContent`). For that alias\n * to be transparent, the generated file MUST expose exactly the same named\n * exports as `built.ts`; otherwise a consumer importing one of them (e.g.\n * `import { analytics } from '@intlayer/config/built'`) triggers a\n * `MISSING_EXPORT` bundler error.\n *\n * Deriving both `built.ts` and the generator from this single array guarantees\n * they can never drift: adding a section here is the only change required to\n * expose it in every build target.\n */\nexport const BUILT_CONFIG_KEYS = [\n 'internationalization',\n 'dictionary',\n 'routing',\n 'content',\n 'system',\n 'editor',\n 'analytics',\n 'log',\n 'ai',\n 'build',\n 'compiler',\n 'schemas',\n 'plugins',\n] as const satisfies readonly (keyof IntlayerConfig)[];\n\n/**\n * Union of the configuration section names exposed by `@intlayer/config/built`.\n */\nexport type BuiltConfigKey = (typeof BUILT_CONFIG_KEYS)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
@@ -105,7 +105,8 @@ const cacheDisk = (intlayerConfig, keys, options) => {
105
105
  };
106
106
  const payload = Buffer.from((0, node_v8.serialize)(envelope));
107
107
  const gz = shouldUseCompression(payload, compress) ? (0, node_zlib.gzipSync)(payload) : payload;
108
- await atomicWriteFile(filePath, Buffer.concat([Buffer.from([gz === payload ? 0 : 1]), gz]), tempDir);
108
+ const buf = Buffer.concat([Buffer.from([gz === payload ? 0 : 1]), gz]);
109
+ await atomicWriteFile(filePath, buf, tempDir);
109
110
  } catch {}
110
111
  };
111
112
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"cacheDisk.cjs","names":["computeKeyId","configPackageJson"],"sources":["../../../src/utils/cacheDisk.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport configPackageJson from '@intlayer/types/package.json' with {\n type: 'json',\n};\nimport { type CacheKey, clearAllCache, computeKeyId } from './cacheMemory';\n\n/** ------------------------- Persistence layer ------------------------- **/\n\n/** Cache envelope structure stored on disk */\ntype CacheEnvelope = {\n /** Version of the config package (for cache invalidation) */\n version: string;\n /** Timestamp when the cache entry was created (in milliseconds) */\n timestamp: number;\n /** Data payload (the actual cached value) */\n data: unknown;\n};\n\ntype LocalCacheOptions = {\n /** Preferred new option name */\n persistent?: boolean;\n /** Time-to-live in ms; if expired, disk entry is ignored. */\n ttlMs?: number;\n /** Max age in ms based on stored creation timestamp; invalidates on exceed. */\n maxTimeMs?: number;\n /** Optional namespace to separate different logical caches. */\n namespace?: string;\n /** Gzip values on disk (on by default for blobs > 1KB). */\n compress?: boolean;\n};\n\nconst DEFAULTS: Required<Pick<LocalCacheOptions, 'compress'>> = {\n compress: true,\n};\n\nconst ensureDir = async (dir: string) => {\n await mkdir(dir, { recursive: true });\n};\n\nconst atomicWriteFile = async (\n file: string,\n data: Buffer,\n tempDir?: string\n) => {\n if (tempDir) {\n try {\n await ensureDir(tempDir);\n } catch {}\n }\n\n const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n const tmp = tempDir\n ? join(tempDir, tempFileName)\n : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n try {\n await writeFile(tmp, data);\n await rename(tmp, file);\n } catch (error) {\n try {\n await rm(tmp, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n};\n\nconst shouldUseCompression = (buf: Buffer, force?: boolean) =>\n force === true || (force !== false && buf.byteLength > 1024);\n\n/** Derive on-disk path from config dir + namespace + key id. */\nconst cachePath = (cacheDir: string, id: string, ns?: string) =>\n join(cacheDir, ns ? join(ns, id) : id);\n\n/** ------------------------- Local cache facade ------------------------- **/\n\nconst cacheMap = new Map<string, any>();\n\n/** Clears the in-memory portion of the disk cache without touching disk files. */\nexport const clearDiskCacheMemory = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheDisk = (\n intlayerConfig: IntlayerConfig,\n keys: CacheKey[],\n options?: LocalCacheOptions\n) => {\n const { cacheDir, tempDir } = intlayerConfig.system;\n const buildCacheEnabled = intlayerConfig.build.cache ?? true;\n const persistent =\n options?.persistent === true ||\n (typeof options?.persistent === 'undefined' && buildCacheEnabled);\n\n const { compress, ttlMs, maxTimeMs, namespace } = {\n ...DEFAULTS,\n ...options,\n };\n\n // single stable id for this key tuple (works for both memory & disk)\n const id = computeKeyId(keys);\n const filePath = cachePath(cacheDir, id, namespace);\n\n const readFromDisk = async (): Promise<unknown | undefined> => {\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n\n if (!statValue) return undefined;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return undefined;\n }\n let raw = await readFile(filePath);\n // header: 1 byte flag (0x00 raw, 0x01 gzip)\n const flag = raw[0];\n\n raw = raw.subarray(1);\n\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n let value: unknown;\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof (maybeObj as any).version === 'string' &&\n typeof (maybeObj as any).timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n\n if (entry.version !== configPackageJson.version) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n\n value = entry.data;\n } else {\n // Backward compatibility: old entries had raw serialized value.\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n value = deserialized;\n }\n\n // hydrate memory cache as well\n cacheMap.set(id, value);\n return value;\n } catch {\n return undefined;\n }\n };\n\n const writeToDisk = async (value: unknown) => {\n try {\n await ensureDir(dirname(filePath));\n const envelope: CacheEnvelope = {\n version: configPackageJson.version,\n timestamp: Date.now(),\n data: value,\n };\n const payload = Buffer.from(serialize(envelope));\n\n const gz = shouldUseCompression(payload, compress)\n ? gzipSync(payload)\n : payload;\n\n // prepend a 1-byte header indicating compression\n const buf = Buffer.concat([\n Buffer.from([gz === payload ? 0x00 : 0x01]),\n gz,\n ]);\n\n await atomicWriteFile(filePath, buf, tempDir);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file path for debugging. */\n filePath,\n };\n};\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAA0D,EAC9D,UAAU,MACX;AAED,MAAM,YAAY,OAAO,QAAgB;AACvC,mCAAY,KAAK,EAAE,WAAW,MAAM,CAAC;;AAGvC,MAAM,kBAAkB,OACtB,MACA,MACA,YACG;AACH,KAAI,QACF,KAAI;AACF,QAAM,UAAU,QAAQ;SAClB;CAGV,MAAM,eAAe,2BAAY,KAAK,CAAC,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE;CAChG,MAAM,MAAM,8BACH,SAAS,aAAa,GAC3B,GAAG,KAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE;AACrE,KAAI;AACF,wCAAgB,KAAK,KAAK;AAC1B,qCAAa,KAAK,KAAK;UAChB,OAAO;AACd,MAAI;AACF,kCAAS,KAAK,EAAE,OAAO,MAAM,CAAC;UACxB;AAGR,QAAM;;;AAIV,MAAM,wBAAwB,KAAa,UACzC,UAAU,QAAS,UAAU,SAAS,IAAI,aAAa;;AAGzD,MAAM,aAAa,UAAkB,IAAY,2BAC1C,UAAU,yBAAU,IAAI,GAAG,GAAG,GAAG;;AAIxC,MAAM,2BAAW,IAAI,KAAkB;;AAGvC,MAAa,6BAAmC;AAC9C,UAAS,OAAO;;AAGlB,MAAa,aACX,gBACA,MACA,YACG;CACH,MAAM,EAAE,UAAU,YAAY,eAAe;CAC7C,MAAM,oBAAoB,eAAe,MAAM,SAAS;CACxD,MAAM,aACJ,SAAS,eAAe,QACvB,OAAO,SAAS,eAAe,eAAe;CAEjD,MAAM,EAAE,UAAU,OAAO,WAAW,cAAc;EAChD,GAAG;EACH,GAAG;EACJ;CAGD,MAAM,KAAKA,uCAAa,KAAK;CAC7B,MAAM,WAAW,UAAU,UAAU,IAAI,UAAU;CAEnD,MAAM,e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OAAO,OAAO,UAAU,OAAO,EAEjB;KACd,MAAM,QAAQ;AACd,SAAI,MAAM,YAAYA,qCAAkB,QAAS,QAAO;AAExD,SAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;UADY,KAAK,KAAK,GAAG,MAAM,YACrB,UAAW,QAAO;;AAE9B,YAAO;;AAGT,QAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;SADY,KAAK,KAAK,GAAG,UAAU,UACzB,UAAW,QAAO;;AAE9B,WAAO;WACD;AACN,WAAO;;;;EAIX;;EAEA;EACD"}
1
+ {"version":3,"file":"cacheDisk.cjs","names":["computeKeyId","configPackageJson"],"sources":["../../../src/utils/cacheDisk.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport configPackageJson from '@intlayer/types/package.json' with {\n type: 'json',\n};\nimport { type CacheKey, clearAllCache, computeKeyId } from './cacheMemory';\n\n/** ------------------------- Persistence layer ------------------------- **/\n\n/** Cache envelope structure stored on disk */\ntype CacheEnvelope = {\n /** Version of the config package (for cache invalidation) */\n version: string;\n /** Timestamp when the cache entry was created (in milliseconds) */\n timestamp: number;\n /** Data payload (the actual cached value) */\n data: unknown;\n};\n\ntype LocalCacheOptions = {\n /** Preferred new option name */\n persistent?: boolean;\n /** Time-to-live in ms; if expired, disk entry is ignored. */\n ttlMs?: number;\n /** Max age in ms based on stored creation timestamp; invalidates on exceed. */\n maxTimeMs?: number;\n /** Optional namespace to separate different logical caches. */\n namespace?: string;\n /** Gzip values on disk (on by default for blobs > 1KB). */\n compress?: boolean;\n};\n\nconst DEFAULTS: Required<Pick<LocalCacheOptions, 'compress'>> = {\n compress: true,\n};\n\nconst ensureDir = async (dir: string) => {\n await mkdir(dir, { recursive: true });\n};\n\nconst atomicWriteFile = async (\n file: string,\n data: Buffer,\n tempDir?: string\n) => {\n if (tempDir) {\n try {\n await ensureDir(tempDir);\n } catch {}\n }\n\n const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n const tmp = tempDir\n ? join(tempDir, tempFileName)\n : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n try {\n await writeFile(tmp, data);\n await rename(tmp, file);\n } catch (error) {\n try {\n await rm(tmp, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n};\n\nconst shouldUseCompression = (buf: Buffer, force?: boolean) =>\n force === true || (force !== false && buf.byteLength > 1024);\n\n/** Derive on-disk path from config dir + namespace + key id. */\nconst cachePath = (cacheDir: string, id: string, ns?: string) =>\n join(cacheDir, ns ? join(ns, id) : id);\n\n/** ------------------------- Local cache facade ------------------------- **/\n\nconst cacheMap = new Map<string, any>();\n\n/** Clears the in-memory portion of the disk cache without touching disk files. */\nexport const clearDiskCacheMemory = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheDisk = (\n intlayerConfig: IntlayerConfig,\n keys: CacheKey[],\n options?: LocalCacheOptions\n) => {\n const { cacheDir, tempDir } = intlayerConfig.system;\n const buildCacheEnabled = intlayerConfig.build.cache ?? true;\n const persistent =\n options?.persistent === true ||\n (typeof options?.persistent === 'undefined' && buildCacheEnabled);\n\n const { compress, ttlMs, maxTimeMs, namespace } = {\n ...DEFAULTS,\n ...options,\n };\n\n // single stable id for this key tuple (works for both memory & disk)\n const id = computeKeyId(keys);\n const filePath = cachePath(cacheDir, id, namespace);\n\n const readFromDisk = async (): Promise<unknown | undefined> => {\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n\n if (!statValue) return undefined;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return undefined;\n }\n let raw = await readFile(filePath);\n // header: 1 byte flag (0x00 raw, 0x01 gzip)\n const flag = raw[0];\n\n raw = raw.subarray(1);\n\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n let value: unknown;\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof (maybeObj as any).version === 'string' &&\n typeof (maybeObj as any).timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n\n if (entry.version !== configPackageJson.version) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n\n value = entry.data;\n } else {\n // Backward compatibility: old entries had raw serialized value.\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n value = deserialized;\n }\n\n // hydrate memory cache as well\n cacheMap.set(id, value);\n return value;\n } catch {\n return undefined;\n }\n };\n\n const writeToDisk = async (value: unknown) => {\n try {\n await ensureDir(dirname(filePath));\n const envelope: CacheEnvelope = {\n version: configPackageJson.version,\n timestamp: Date.now(),\n data: value,\n };\n const payload = Buffer.from(serialize(envelope));\n\n const gz = shouldUseCompression(payload, compress)\n ? gzipSync(payload)\n : payload;\n\n // prepend a 1-byte header indicating compression\n const buf = Buffer.concat([\n Buffer.from([gz === payload ? 0x00 : 0x01]),\n gz,\n ]);\n\n await atomicWriteFile(filePath, buf, tempDir);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file path for debugging. */\n filePath,\n };\n};\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAA0D,EAC9D,UAAU,KACZ;AAEA,MAAM,YAAY,OAAO,QAAgB;CACvC,kCAAY,KAAK,EAAE,WAAW,KAAK,CAAC;AACtC;AAEA,MAAM,kBAAkB,OACtB,MACA,MACA,YACG;CACH,IAAI,SACF,IAAI;EACF,MAAM,UAAU,OAAO;CACzB,QAAQ,CAAC;CAGX,MAAM,eAAe,2BAAY,IAAI,EAAE,OAAO,QAAQ,IAAI,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CAC/F,MAAM,MAAM,8BACH,SAAS,YAAY,IAC1B,GAAG,KAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CACpE,IAAI;EACF,sCAAgB,KAAK,IAAI;EACzB,mCAAa,KAAK,IAAI;CACxB,SAAS,OAAO;EACd,IAAI;GACF,+BAAS,KAAK,EAAE,OAAO,KAAK,CAAC;EAC/B,QAAQ,CAER;EACA,MAAM;CACR;AACF;AAEA,MAAM,wBAAwB,KAAa,UACzC,UAAU,QAAS,UAAU,SAAS,IAAI,aAAa;;AAGzD,MAAM,aAAa,UAAkB,IAAY,2BAC1C,UAAU,yBAAU,IAAI,EAAE,IAAI,EAAE;;AAIvC,MAAM,2BAAW,IAAI,IAAiB;;AAGtC,MAAa,6BAAmC;CAC9C,SAAS,MAAM;AACjB;AAEA,MAAa,aACX,gBACA,MACA,YACG;CACH,MAAM,EAAE,UAAU,YAAY,eAAe;CAC7C,MAAM,oBAAoB,eAAe,MAAM,SAAS;CACxD,MAAM,aACJ,SAAS,eAAe,QACvB,OAAO,SAAS,eAAe,eAAe;CAE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WAAW,OAAO;IAEvB,IAAI,OAAO,UAAU,YAAY,QAAQ,GAEvC;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,OAAO,OAAO;IAAK;IAG/B,IAAI,MAAM,qCAAe,QAAQ;IACjC,MAAM,OAAO,IAAI;IACjB,MAAM,IAAI,SAAS,CAAC;IAIpB,MAAM,oCAHU,SAAS,8BAAkB,GAAG,IAAI,GAGtB;IAQ5B,IANE,CAAC,CAAC,YACF,OAAO,aAAa,YACpB,OAAO,SAAS,YAAY,YAC5B,OAAO,SAAS,cAAc,YAC9B,OAAO,OAAO,UAAU,MAAM,GAEhB;KACd,MAAM,QAAQ;KACd,IAAI,MAAM,YAAYA,qCAAkB,SAAS,OAAO;KAExD,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;UADY,KAAK,IAAI,IAAI,MAAM,YACrB,WAAW,OAAO;KAAK;KAEnC,OAAO;IACT;IAEA,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,WAAW,OAAO;IAAK;IAEnC,OAAO;GACT,QAAQ;IACN,OAAO;GACT;EACF;;EAEA;;EAEA;CACF;AACF"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  let node_crypto = require("node:crypto");
4
3
 
5
4
  //#region src/utils/cacheMemory.ts
@@ -1 +1 @@
1
- {"version":3,"file":"cacheMemory.cjs","names":[],"sources":["../../../src/utils/cacheMemory.ts"],"sourcesContent":["import { createHash, type Hash } from 'node:crypto';\n\n/** ------------------------- Utilities ------------------------- **/\n\n/** Prefer a fast non-crypto hash if available, then fast crypto, then sha256. */\nconst pickHashAlgorithm = (): string => {\n try {\n // Node 20+ supports xxhash64 (very fast). We feature-detect at module load.\n createHash('xxhash64').update('test').digest();\n return 'xxhash64';\n } catch {}\n try {\n // sha1 is faster than sha256 and sufficient for cache keys.\n createHash('sha1').update('test').digest();\n return 'sha1';\n } catch {}\n\n return 'sha256';\n};\nconst HASH_ALGORITHM = pickHashAlgorithm();\n\n/** Base64url without padding for compact, file-system-safe ids. */\nconst toBase64Url = (buffer: Buffer): string =>\n buffer\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/g, '');\n\n/** Token helpers to minimize collisions while streaming to the hasher. */\nconst token = {\n start: (hasher: Hash, tag: string) => hasher.update(`<${tag}>`),\n sep: (hasher: Hash) => hasher.update('|'),\n end: (hasher: Hash, tag: string) => hasher.update(`</${tag}>`),\n str: (hasher: Hash, stringValue: string) => {\n // length prefix to avoid ambiguity: len#value\n hasher.update(`${stringValue.length}#`);\n hasher.update(stringValue);\n },\n num: (hasher: Hash, numberValue: number) =>\n hasher.update(\n Number.isNaN(numberValue)\n ? 'NaN'\n : numberValue === Infinity\n ? 'Inf'\n : numberValue === -Infinity\n ? '-Inf'\n : String(numberValue)\n ),\n big: (hasher: Hash, bigintValue: bigint) =>\n hasher.update(bigintValue.toString(10)),\n bool: (hasher: Hash, booleanValue: boolean) =>\n hasher.update(booleanValue ? '1' : '0'),\n};\n\n/** ------------------- Canonical, streaming hasher ------------------- **/\n\ntype Seen = WeakSet<object>;\n\n/**\n * Streams a canonical representation of `value` into `hasher` without\n * constructing large intermediate strings. Objects/Maps/Sets are normalized.\n */\nconst stableHashValue = (hasher: Hash, value: unknown, seen: Seen): void => {\n const valueType = typeof value;\n\n if (value === null) {\n token.start(hasher, 'null');\n token.end(hasher, 'null');\n return;\n }\n\n if (valueType === 'undefined') {\n token.start(hasher, 'undef');\n token.end(hasher, 'undef');\n return;\n }\n\n if (valueType === 'number') {\n token.start(hasher, 'num');\n token.num(hasher, value as number);\n token.end(hasher, 'num');\n return;\n }\n\n if (valueType === 'bigint') {\n token.start(hasher, 'big');\n token.big(hasher, value as bigint);\n token.end(hasher, 'big');\n return;\n }\n\n if (valueType === 'boolean') {\n token.start(hasher, 'bool');\n token.bool(hasher, value as boolean);\n token.end(hasher, 'bool');\n return;\n }\n\n if (valueType === 'string') {\n token.start(hasher, 'str');\n token.str(hasher, value as string);\n token.end(hasher, 'str');\n return;\n }\n\n if (valueType === 'symbol') {\n token.start(hasher, 'sym');\n token.str(hasher, String(value));\n token.end(hasher, 'sym');\n return;\n }\n\n if (valueType === 'function') {\n // Stable-ish fingerprint: name and arity (avoid source text).\n const functionValue = value as Function;\n token.start(hasher, 'fn');\n token.str(hasher, functionValue.name ?? '');\n token.sep(hasher);\n token.num(hasher, functionValue.length);\n token.end(hasher, 'fn');\n return;\n }\n\n // Arrays and typed arrays\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n token.start(hasher, 'arr');\n token.str(hasher, 'Circular');\n token.end(hasher, 'arr');\n return;\n }\n seen.add(value);\n token.start(hasher, 'arr');\n for (let i = 0; i < value.length; i++) {\n token.sep(hasher);\n stableHashValue(hasher, value[i], seen);\n }\n token.end(hasher, 'arr');\n seen.delete(value);\n return;\n }\n\n // Node/Builtins\n if (value instanceof Date) {\n token.start(hasher, 'date');\n token.str(hasher, (value as Date).toISOString());\n token.end(hasher, 'date');\n return;\n }\n\n if (value instanceof RegExp) {\n const regex = value as RegExp;\n token.start(hasher, 're');\n token.str(hasher, regex.source);\n token.sep(hasher);\n token.str(hasher, regex.flags);\n token.end(hasher, 're');\n return;\n }\n\n if (value instanceof Set) {\n const setValue = value as Set<unknown>;\n if (seen.has(setValue)) {\n token.start(hasher, 'set');\n token.str(hasher, 'Circular');\n token.end(hasher, 'set');\n return;\n }\n seen.add(setValue);\n // Normalize by item fingerprints (strings) to sort deterministically.\n const items: string[] = [];\n for (const v of setValue) items.push(stableStringify(v)); // small, bounded use of stringify\n items.sort();\n token.start(hasher, 'set');\n for (const item of items) {\n token.sep(hasher);\n token.str(hasher, item);\n }\n token.end(hasher, 'set');\n seen.delete(setValue);\n return;\n }\n\n if (value instanceof Map) {\n const mapObject = value as Map<unknown, unknown>;\n if (seen.has(mapObject)) {\n token.start(hasher, 'map');\n token.str(hasher, 'Circular');\n token.end(hasher, 'map');\n return;\n }\n seen.add(mapObject);\n // Normalize by sorted key fingerprints.\n const entries: Array<[string, unknown]> = [];\n for (const [k, v] of mapObject.entries())\n entries.push([stableStringify(k), v]);\n entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n token.start(hasher, 'map');\n for (const [keyFingerprint, entryValue] of entries) {\n token.sep(hasher);\n token.str(hasher, keyFingerprint);\n token.sep(hasher);\n stableHashValue(hasher, entryValue, seen);\n }\n token.end(hasher, 'map');\n seen.delete(mapObject);\n return;\n }\n\n // ArrayBuffer & typed arrays\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n token.start(hasher, 'typed');\n token.str(hasher, Object.getPrototypeOf(view).constructor.name);\n token.sep(hasher);\n hasher.update(Buffer.from(view.buffer, view.byteOffset, view.byteLength));\n token.end(hasher, 'typed');\n return;\n }\n if (value instanceof ArrayBuffer) {\n const buffer = Buffer.from(value as ArrayBuffer);\n token.start(hasher, 'ab');\n hasher.update(buffer);\n token.end(hasher, 'ab');\n return;\n }\n\n // URL\n if (typeof URL !== 'undefined' && value instanceof URL) {\n token.start(hasher, 'url');\n token.str(hasher, (value as URL).toString());\n token.end(hasher, 'url');\n return;\n }\n\n // Errors\n if (value instanceof Error) {\n const errorValue = value as Error;\n token.start(hasher, 'err');\n token.str(hasher, errorValue.name || '');\n token.sep(hasher);\n token.str(hasher, errorValue.message || '');\n token.sep(hasher);\n token.str(hasher, errorValue.stack || '');\n token.end(hasher, 'err');\n return;\n }\n\n // Generic objects\n if (valueType === 'object') {\n const objectValue = value as Record<string, unknown>;\n if (seen.has(objectValue)) {\n token.start(hasher, 'obj');\n token.str(hasher, 'Circular');\n token.end(hasher, 'obj');\n return;\n }\n seen.add(objectValue);\n\n const keys = Object.keys(objectValue).sort();\n token.start(hasher, 'obj');\n for (const key of keys) {\n token.sep(hasher);\n token.str(hasher, key);\n token.sep(hasher);\n stableHashValue(hasher, (objectValue as any)[key], seen);\n }\n token.end(hasher, 'obj');\n\n seen.delete(objectValue);\n return;\n }\n\n // Fallback\n token.start(hasher, 'other');\n token.str(hasher, String(value));\n token.end(hasher, 'other');\n};\n\n/** Public stringify kept for convenience / debugging (now faster & broader). */\nexport const stableStringify = (\n value: unknown,\n _stack = new WeakSet<object>()\n): string => {\n const hasher = createHash(HASH_ALGORITHM);\n stableHashValue(hasher, value, _stack);\n return toBase64Url(hasher.digest());\n};\n\n/** Compute a compact, stable id for arbitrary key tuples. */\nexport const computeKeyId = (keyParts: unknown[]): string => {\n const h = createHash(HASH_ALGORITHM);\n token.start(h, 'keys');\n for (let i = 0; i < keyParts.length; i++) {\n token.sep(h);\n stableHashValue(h, keyParts[i], new WeakSet());\n }\n token.end(h, 'keys');\n return toBase64Url(h.digest());\n};\n\n/** ------------------------- In-memory cache ------------------------- **/\n\nexport type CacheKey = unknown;\nconst cacheMap = new Map<string, any>();\n\nexport const getCache = <T>(...key: CacheKey[]): T | undefined => {\n return cacheMap.get(computeKeyId(key));\n};\n\ntype CacheSetArgs<T> = [...keys: CacheKey[], value: T];\n\nexport const setCache = <T>(...args: CacheSetArgs<T>): void => {\n const value = args[args.length - 1] as T;\n const key = args.slice(0, -1) as CacheKey[];\n cacheMap.set(computeKeyId(key), value);\n};\n\nexport const clearCache = (idOrKey: string): void => {\n // Accept either our computed id or a legacy string id the caller already computed.\n cacheMap.delete(idOrKey);\n};\n\nexport const clearAllCache = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheMemory = {\n get: getCache,\n set: setCache,\n clear: clearCache,\n};\n"],"mappings":";;;;;;;AAKA,MAAM,0BAAkC;AACtC,KAAI;AAEF,8BAAW,WAAW,CAAC,OAAO,OAAO,CAAC,QAAQ;AAC9C,SAAO;SACD;AACR,KAAI;AAEF,8BAAW,OAAO,CAAC,OAAO,OAAO,CAAC,QAAQ;AAC1C,SAAO;SACD;AAER,QAAO;;AAET,MAAM,iBAAiB,mBA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],"sources":["../../../src/utils/cacheMemory.ts"],"sourcesContent":["import { createHash, type Hash } from 'node:crypto';\n\n/** ------------------------- Utilities ------------------------- **/\n\n/** Prefer a fast non-crypto hash if available, then fast crypto, then sha256. */\nconst pickHashAlgorithm = (): string => {\n try {\n // Node 20+ supports xxhash64 (very fast). We feature-detect at module load.\n createHash('xxhash64').update('test').digest();\n return 'xxhash64';\n } catch {}\n try {\n // sha1 is faster than sha256 and sufficient for cache keys.\n createHash('sha1').update('test').digest();\n return 'sha1';\n } catch {}\n\n return 'sha256';\n};\nconst HASH_ALGORITHM = pickHashAlgorithm();\n\n/** Base64url without padding for compact, file-system-safe ids. */\nconst toBase64Url = (buffer: Buffer): string =>\n buffer\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/g, '');\n\n/** Token helpers to minimize collisions while streaming to the hasher. */\nconst token = {\n start: (hasher: Hash, tag: string) => hasher.update(`<${tag}>`),\n sep: (hasher: Hash) => hasher.update('|'),\n end: (hasher: Hash, tag: string) => hasher.update(`</${tag}>`),\n str: (hasher: Hash, stringValue: string) => {\n // length prefix to avoid ambiguity: len#value\n hasher.update(`${stringValue.length}#`);\n hasher.update(stringValue);\n },\n num: (hasher: Hash, numberValue: number) =>\n hasher.update(\n Number.isNaN(numberValue)\n ? 'NaN'\n : numberValue === Infinity\n ? 'Inf'\n : numberValue === -Infinity\n ? '-Inf'\n : String(numberValue)\n ),\n big: (hasher: Hash, bigintValue: bigint) =>\n hasher.update(bigintValue.toString(10)),\n bool: (hasher: Hash, booleanValue: boolean) =>\n hasher.update(booleanValue ? '1' : '0'),\n};\n\n/** ------------------- Canonical, streaming hasher ------------------- **/\n\ntype Seen = WeakSet<object>;\n\n/**\n * Streams a canonical representation of `value` into `hasher` without\n * constructing large intermediate strings. Objects/Maps/Sets are normalized.\n */\nconst stableHashValue = (hasher: Hash, value: unknown, seen: Seen): void => {\n const valueType = typeof value;\n\n if (value === null) {\n token.start(hasher, 'null');\n token.end(hasher, 'null');\n return;\n }\n\n if (valueType === 'undefined') {\n token.start(hasher, 'undef');\n token.end(hasher, 'undef');\n return;\n }\n\n if (valueType === 'number') {\n token.start(hasher, 'num');\n token.num(hasher, value as number);\n token.end(hasher, 'num');\n return;\n }\n\n if (valueType === 'bigint') {\n token.start(hasher, 'big');\n token.big(hasher, value as bigint);\n token.end(hasher, 'big');\n return;\n }\n\n if (valueType === 'boolean') {\n token.start(hasher, 'bool');\n token.bool(hasher, value as boolean);\n token.end(hasher, 'bool');\n return;\n }\n\n if (valueType === 'string') {\n token.start(hasher, 'str');\n token.str(hasher, value as string);\n token.end(hasher, 'str');\n return;\n }\n\n if (valueType === 'symbol') {\n token.start(hasher, 'sym');\n token.str(hasher, String(value));\n token.end(hasher, 'sym');\n return;\n }\n\n if (valueType === 'function') {\n // Stable-ish fingerprint: name and arity (avoid source text).\n const functionValue = value as Function;\n token.start(hasher, 'fn');\n token.str(hasher, functionValue.name ?? '');\n token.sep(hasher);\n token.num(hasher, functionValue.length);\n token.end(hasher, 'fn');\n return;\n }\n\n // Arrays and typed arrays\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n token.start(hasher, 'arr');\n token.str(hasher, 'Circular');\n token.end(hasher, 'arr');\n return;\n }\n seen.add(value);\n token.start(hasher, 'arr');\n for (let i = 0; i < value.length; i++) {\n token.sep(hasher);\n stableHashValue(hasher, value[i], seen);\n }\n token.end(hasher, 'arr');\n seen.delete(value);\n return;\n }\n\n // Node/Builtins\n if (value instanceof Date) {\n token.start(hasher, 'date');\n token.str(hasher, (value as Date).toISOString());\n token.end(hasher, 'date');\n return;\n }\n\n if (value instanceof RegExp) {\n const regex = value as RegExp;\n token.start(hasher, 're');\n token.str(hasher, regex.source);\n token.sep(hasher);\n token.str(hasher, regex.flags);\n token.end(hasher, 're');\n return;\n }\n\n if (value instanceof Set) {\n const setValue = value as Set<unknown>;\n if (seen.has(setValue)) {\n token.start(hasher, 'set');\n token.str(hasher, 'Circular');\n token.end(hasher, 'set');\n return;\n }\n seen.add(setValue);\n // Normalize by item fingerprints (strings) to sort deterministically.\n const items: string[] = [];\n for (const v of setValue) items.push(stableStringify(v)); // small, bounded use of stringify\n items.sort();\n token.start(hasher, 'set');\n for (const item of items) {\n token.sep(hasher);\n token.str(hasher, item);\n }\n token.end(hasher, 'set');\n seen.delete(setValue);\n return;\n }\n\n if (value instanceof Map) {\n const mapObject = value as Map<unknown, unknown>;\n if (seen.has(mapObject)) {\n token.start(hasher, 'map');\n token.str(hasher, 'Circular');\n token.end(hasher, 'map');\n return;\n }\n seen.add(mapObject);\n // Normalize by sorted key fingerprints.\n const entries: Array<[string, unknown]> = [];\n for (const [k, v] of mapObject.entries())\n entries.push([stableStringify(k), v]);\n entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n token.start(hasher, 'map');\n for (const [keyFingerprint, entryValue] of entries) {\n token.sep(hasher);\n token.str(hasher, keyFingerprint);\n token.sep(hasher);\n stableHashValue(hasher, entryValue, seen);\n }\n token.end(hasher, 'map');\n seen.delete(mapObject);\n return;\n }\n\n // ArrayBuffer & typed arrays\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n token.start(hasher, 'typed');\n token.str(hasher, Object.getPrototypeOf(view).constructor.name);\n token.sep(hasher);\n hasher.update(Buffer.from(view.buffer, view.byteOffset, view.byteLength));\n token.end(hasher, 'typed');\n return;\n }\n if (value instanceof ArrayBuffer) {\n const buffer = Buffer.from(value as ArrayBuffer);\n token.start(hasher, 'ab');\n hasher.update(buffer);\n token.end(hasher, 'ab');\n return;\n }\n\n // URL\n if (typeof URL !== 'undefined' && value instanceof URL) {\n token.start(hasher, 'url');\n token.str(hasher, (value as URL).toString());\n token.end(hasher, 'url');\n return;\n }\n\n // Errors\n if (value instanceof Error) {\n const errorValue = value as Error;\n token.start(hasher, 'err');\n token.str(hasher, errorValue.name || '');\n token.sep(hasher);\n token.str(hasher, errorValue.message || '');\n token.sep(hasher);\n token.str(hasher, errorValue.stack || '');\n token.end(hasher, 'err');\n return;\n }\n\n // Generic objects\n if (valueType === 'object') {\n const objectValue = value as Record<string, unknown>;\n if (seen.has(objectValue)) {\n token.start(hasher, 'obj');\n token.str(hasher, 'Circular');\n token.end(hasher, 'obj');\n return;\n }\n seen.add(objectValue);\n\n const keys = Object.keys(objectValue).sort();\n token.start(hasher, 'obj');\n for (const key of keys) {\n token.sep(hasher);\n token.str(hasher, key);\n token.sep(hasher);\n stableHashValue(hasher, (objectValue as any)[key], seen);\n }\n token.end(hasher, 'obj');\n\n seen.delete(objectValue);\n return;\n }\n\n // Fallback\n token.start(hasher, 'other');\n token.str(hasher, String(value));\n token.end(hasher, 'other');\n};\n\n/** Public stringify kept for convenience / debugging (now faster & broader). */\nexport const stableStringify = (\n value: unknown,\n _stack = new WeakSet<object>()\n): string => {\n const hasher = createHash(HASH_ALGORITHM);\n stableHashValue(hasher, value, _stack);\n return toBase64Url(hasher.digest());\n};\n\n/** Compute a compact, stable id for arbitrary key tuples. */\nexport const computeKeyId = (keyParts: unknown[]): string => {\n const h = createHash(HASH_ALGORITHM);\n token.start(h, 'keys');\n for (let i = 0; i < keyParts.length; i++) {\n token.sep(h);\n stableHashValue(h, keyParts[i], new WeakSet());\n }\n token.end(h, 'keys');\n return toBase64Url(h.digest());\n};\n\n/** ------------------------- In-memory cache ------------------------- **/\n\nexport type CacheKey = unknown;\nconst cacheMap = new Map<string, any>();\n\nexport const getCache = <T>(...key: CacheKey[]): T | undefined => {\n return cacheMap.get(computeKeyId(key));\n};\n\ntype CacheSetArgs<T> = [...keys: CacheKey[], value: T];\n\nexport const setCache = <T>(...args: CacheSetArgs<T>): void => {\n const value = args[args.length - 1] as T;\n const key = args.slice(0, -1) as CacheKey[];\n cacheMap.set(computeKeyId(key), value);\n};\n\nexport const clearCache = (idOrKey: string): void => {\n // Accept either our computed id or a legacy string id the caller already computed.\n cacheMap.delete(idOrKey);\n};\n\nexport const clearAllCache = (): void => {\n cacheMap.clear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