@intlayer/engine 9.5.10 → 9.5.12

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 (266) hide show
  1. package/dist/assets/installSkills/skills/bundle-optimization.md +123 -0
  2. package/dist/assets/installSkills/skills/compat.md +0 -4
  3. package/dist/assets/installSkills/skills/content.md +8 -2
  4. package/dist/assets/installSkills/skills/next-js.md +2 -2
  5. package/dist/assets/installSkills/skills/usage.md +1 -1
  6. package/dist/cjs/build.cjs +5 -0
  7. package/dist/cjs/cli.cjs +1 -0
  8. package/dist/cjs/docReview/alignBlocks.cjs +53 -36
  9. package/dist/cjs/docReview/alignBlocks.cjs.map +1 -1
  10. package/dist/cjs/docReview/rebuildDocument.cjs +3 -1
  11. package/dist/cjs/docReview/rebuildDocument.cjs.map +1 -1
  12. package/dist/cjs/docReview/segmentDocument.cjs +8 -5
  13. package/dist/cjs/docReview/segmentDocument.cjs.map +1 -1
  14. package/dist/cjs/init/frameworkSetup/nextAppRouter/transforms.cjs +4 -1
  15. package/dist/cjs/init/frameworkSetup/nextAppRouter/transforms.cjs.map +1 -1
  16. package/dist/cjs/init/index.cjs +2 -12
  17. package/dist/cjs/init/index.cjs.map +1 -1
  18. package/dist/cjs/init/utils/backendPackages.cjs +15 -0
  19. package/dist/cjs/init/utils/backendPackages.cjs.map +1 -0
  20. package/dist/cjs/init/utils/index.cjs +2 -3
  21. package/dist/cjs/installMCP/installMCP.cjs +1 -1
  22. package/dist/cjs/installMCP/installMCP.cjs.map +1 -1
  23. package/dist/cjs/installSkills/index.cjs +2 -0
  24. package/dist/cjs/installSkills/index.cjs.map +1 -1
  25. package/dist/cjs/loadDictionaries/loadDictionaries.cjs +9 -8
  26. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  27. package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs +3 -1
  28. package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
  29. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +4 -6
  30. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
  31. package/dist/cjs/loadDictionaries/log.cjs +1 -1
  32. package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
  33. package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs +19 -12
  34. package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
  35. package/dist/cjs/loadDictionaries/remoteDictionaryClient.cjs +18 -0
  36. package/dist/cjs/loadDictionaries/remoteDictionaryClient.cjs.map +1 -0
  37. package/dist/cjs/prepareIntlayerServer.cjs +132 -0
  38. package/dist/cjs/prepareIntlayerServer.cjs.map +1 -0
  39. package/dist/cjs/scan/analyzeBundleContent.cjs +26 -12
  40. package/dist/cjs/scan/analyzeBundleContent.cjs.map +1 -1
  41. package/dist/cjs/scan/calculateScore.cjs +4 -1
  42. package/dist/cjs/scan/calculateScore.cjs.map +1 -1
  43. package/dist/cjs/scan/checks.cjs +394 -221
  44. package/dist/cjs/scan/checks.cjs.map +1 -1
  45. package/dist/cjs/scan/detection/checkDetails.cjs +56 -0
  46. package/dist/cjs/scan/detection/checkDetails.cjs.map +1 -0
  47. package/dist/cjs/scan/detection/classifyInternalLinks.cjs +47 -0
  48. package/dist/cjs/scan/detection/classifyInternalLinks.cjs.map +1 -0
  49. package/dist/cjs/scan/detection/detectRoutingStrategy.cjs +143 -0
  50. package/dist/cjs/scan/detection/detectRoutingStrategy.cjs.map +1 -0
  51. package/dist/cjs/scan/detection/detectTechnologies.cjs +89 -0
  52. package/dist/cjs/scan/detection/detectTechnologies.cjs.map +1 -0
  53. package/dist/cjs/scan/detection/index.cjs +36 -0
  54. package/dist/cjs/scan/detection/localeCode.cjs +118 -0
  55. package/dist/cjs/scan/detection/localeCode.cjs.map +1 -0
  56. package/dist/cjs/scan/detection/localizedPages.cjs +48 -0
  57. package/dist/cjs/scan/detection/localizedPages.cjs.map +1 -0
  58. package/dist/cjs/scan/detection/technologySignatures.cjs +564 -0
  59. package/dist/cjs/scan/detection/technologySignatures.cjs.map +1 -0
  60. package/dist/cjs/scan/detection/url.cjs +53 -0
  61. package/dist/cjs/scan/detection/url.cjs.map +1 -0
  62. package/dist/cjs/scan/fetchText.cjs +56 -0
  63. package/dist/cjs/scan/fetchText.cjs.map +1 -0
  64. package/dist/cjs/scan/index.cjs +59 -3
  65. package/dist/cjs/scan/parseHtml.cjs +55 -10
  66. package/dist/cjs/scan/parseHtml.cjs.map +1 -1
  67. package/dist/cjs/scan/robots.cjs +65 -0
  68. package/dist/cjs/scan/robots.cjs.map +1 -0
  69. package/dist/cjs/scan/runScanChecks.cjs +89 -0
  70. package/dist/cjs/scan/runScanChecks.cjs.map +1 -0
  71. package/dist/cjs/scan/scanWebsite.cjs +58 -52
  72. package/dist/cjs/scan/scanWebsite.cjs.map +1 -1
  73. package/dist/cjs/scan/sitemap.cjs +109 -0
  74. package/dist/cjs/scan/sitemap.cjs.map +1 -0
  75. package/dist/cjs/utils/chunkJSON.cjs +24 -9
  76. package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
  77. package/dist/cjs/utils/getChunk.cjs +2 -2
  78. package/dist/cjs/utils/getChunk.cjs.map +1 -1
  79. package/dist/cjs/utils/getProcessChainCommands.cjs +117 -0
  80. package/dist/cjs/utils/getProcessChainCommands.cjs.map +1 -0
  81. package/dist/cjs/utils/index.cjs +2 -0
  82. package/dist/cjs/utils/runParallel/index.cjs +1 -1
  83. package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
  84. package/dist/cjs/utils/runParallel/pidTree.cjs +23 -11
  85. package/dist/cjs/utils/runParallel/pidTree.cjs.map +1 -1
  86. package/dist/cjs/utils/runParallel/ps.cjs +8 -3
  87. package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
  88. package/dist/cjs/utils/runParallel/runTask.cjs +2 -1
  89. package/dist/cjs/utils/runParallel/runTask.cjs.map +1 -1
  90. package/dist/cjs/utils/runParallel/wmic.cjs +8 -3
  91. package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
  92. package/dist/cjs/utils/startContentWatcher.cjs +99 -0
  93. package/dist/cjs/utils/startContentWatcher.cjs.map +1 -0
  94. package/dist/cjs/watcher.cjs +2 -2
  95. package/dist/cjs/watcher.cjs.map +1 -1
  96. package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs +7 -4
  97. package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs.map +1 -1
  98. package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs +2 -2
  99. package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs.map +1 -1
  100. package/dist/cjs/writeJsonIfChanged.cjs.map +1 -1
  101. package/dist/esm/build.mjs +2 -1
  102. package/dist/esm/cli.mjs +2 -2
  103. package/dist/esm/docReview/alignBlocks.mjs +53 -36
  104. package/dist/esm/docReview/alignBlocks.mjs.map +1 -1
  105. package/dist/esm/docReview/rebuildDocument.mjs +3 -1
  106. package/dist/esm/docReview/rebuildDocument.mjs.map +1 -1
  107. package/dist/esm/docReview/segmentDocument.mjs +8 -5
  108. package/dist/esm/docReview/segmentDocument.mjs.map +1 -1
  109. package/dist/esm/init/frameworkSetup/nextAppRouter/transforms.mjs +4 -1
  110. package/dist/esm/init/frameworkSetup/nextAppRouter/transforms.mjs.map +1 -1
  111. package/dist/esm/init/index.mjs +1 -11
  112. package/dist/esm/init/index.mjs.map +1 -1
  113. package/dist/esm/init/utils/backendPackages.mjs +14 -0
  114. package/dist/esm/init/utils/backendPackages.mjs.map +1 -0
  115. package/dist/esm/init/utils/index.mjs +2 -2
  116. package/dist/esm/installMCP/installMCP.mjs +1 -1
  117. package/dist/esm/installMCP/installMCP.mjs.map +1 -1
  118. package/dist/esm/installSkills/index.mjs +2 -0
  119. package/dist/esm/installSkills/index.mjs.map +1 -1
  120. package/dist/esm/loadDictionaries/loadDictionaries.mjs +9 -8
  121. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  122. package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs +3 -1
  123. package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs.map +1 -1
  124. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs +3 -5
  125. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
  126. package/dist/esm/loadDictionaries/log.mjs +1 -1
  127. package/dist/esm/loadDictionaries/log.mjs.map +1 -1
  128. package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs +19 -12
  129. package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
  130. package/dist/esm/loadDictionaries/remoteDictionaryClient.mjs +16 -0
  131. package/dist/esm/loadDictionaries/remoteDictionaryClient.mjs.map +1 -0
  132. package/dist/esm/prepareIntlayerServer.mjs +128 -0
  133. package/dist/esm/prepareIntlayerServer.mjs.map +1 -0
  134. package/dist/esm/scan/analyzeBundleContent.mjs +26 -12
  135. package/dist/esm/scan/analyzeBundleContent.mjs.map +1 -1
  136. package/dist/esm/scan/calculateScore.mjs +4 -1
  137. package/dist/esm/scan/calculateScore.mjs.map +1 -1
  138. package/dist/esm/scan/checks.mjs +387 -220
  139. package/dist/esm/scan/checks.mjs.map +1 -1
  140. package/dist/esm/scan/detection/checkDetails.mjs +54 -0
  141. package/dist/esm/scan/detection/checkDetails.mjs.map +1 -0
  142. package/dist/esm/scan/detection/classifyInternalLinks.mjs +46 -0
  143. package/dist/esm/scan/detection/classifyInternalLinks.mjs.map +1 -0
  144. package/dist/esm/scan/detection/detectRoutingStrategy.mjs +141 -0
  145. package/dist/esm/scan/detection/detectRoutingStrategy.mjs.map +1 -0
  146. package/dist/esm/scan/detection/detectTechnologies.mjs +87 -0
  147. package/dist/esm/scan/detection/detectTechnologies.mjs.map +1 -0
  148. package/dist/esm/scan/detection/index.mjs +10 -0
  149. package/dist/esm/scan/detection/localeCode.mjs +108 -0
  150. package/dist/esm/scan/detection/localeCode.mjs.map +1 -0
  151. package/dist/esm/scan/detection/localizedPages.mjs +46 -0
  152. package/dist/esm/scan/detection/localizedPages.mjs.map +1 -0
  153. package/dist/esm/scan/detection/technologySignatures.mjs +563 -0
  154. package/dist/esm/scan/detection/technologySignatures.mjs.map +1 -0
  155. package/dist/esm/scan/detection/url.mjs +47 -0
  156. package/dist/esm/scan/detection/url.mjs.map +1 -0
  157. package/dist/esm/scan/fetchText.mjs +55 -0
  158. package/dist/esm/scan/fetchText.mjs.map +1 -0
  159. package/dist/esm/scan/index.mjs +15 -3
  160. package/dist/esm/scan/parseHtml.mjs +52 -11
  161. package/dist/esm/scan/parseHtml.mjs.map +1 -1
  162. package/dist/esm/scan/robots.mjs +63 -0
  163. package/dist/esm/scan/robots.mjs.map +1 -0
  164. package/dist/esm/scan/runScanChecks.mjs +88 -0
  165. package/dist/esm/scan/runScanChecks.mjs.map +1 -0
  166. package/dist/esm/scan/scanWebsite.mjs +59 -53
  167. package/dist/esm/scan/scanWebsite.mjs.map +1 -1
  168. package/dist/esm/scan/sitemap.mjs +105 -0
  169. package/dist/esm/scan/sitemap.mjs.map +1 -0
  170. package/dist/esm/utils/chunkJSON.mjs +24 -9
  171. package/dist/esm/utils/chunkJSON.mjs.map +1 -1
  172. package/dist/esm/utils/getChunk.mjs +2 -2
  173. package/dist/esm/utils/getChunk.mjs.map +1 -1
  174. package/dist/esm/utils/getProcessChainCommands.mjs +115 -0
  175. package/dist/esm/utils/getProcessChainCommands.mjs.map +1 -0
  176. package/dist/esm/utils/index.mjs +2 -1
  177. package/dist/esm/utils/runParallel/index.mjs +1 -1
  178. package/dist/esm/utils/runParallel/index.mjs.map +1 -1
  179. package/dist/esm/utils/runParallel/pidTree.mjs +23 -11
  180. package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
  181. package/dist/esm/utils/runParallel/ps.mjs +8 -3
  182. package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
  183. package/dist/esm/utils/runParallel/runTask.mjs +2 -1
  184. package/dist/esm/utils/runParallel/runTask.mjs.map +1 -1
  185. package/dist/esm/utils/runParallel/wmic.mjs +8 -3
  186. package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
  187. package/dist/esm/utils/startContentWatcher.mjs +98 -0
  188. package/dist/esm/utils/startContentWatcher.mjs.map +1 -0
  189. package/dist/esm/watcher.mjs +1 -1
  190. package/dist/esm/watcher.mjs.map +1 -1
  191. package/dist/esm/writeContentDeclaration/detectExportedComponentName.mjs +7 -4
  192. package/dist/esm/writeContentDeclaration/detectExportedComponentName.mjs.map +1 -1
  193. package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs +2 -2
  194. package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs.map +1 -1
  195. package/dist/esm/writeJsonIfChanged.mjs +1 -1
  196. package/dist/esm/writeJsonIfChanged.mjs.map +1 -1
  197. package/dist/types/build.d.ts +2 -1
  198. package/dist/types/cli.d.ts +2 -2
  199. package/dist/types/docReview/rebuildDocument.d.ts.map +1 -1
  200. package/dist/types/docReview/segmentDocument.d.ts.map +1 -1
  201. package/dist/types/init/frameworkSetup/nextAppRouter/transforms.d.ts.map +1 -1
  202. package/dist/types/init/index.d.ts +1 -1
  203. package/dist/types/init/index.d.ts.map +1 -1
  204. package/dist/types/init/utils/backendPackages.d.ts +5 -0
  205. package/dist/types/init/utils/backendPackages.d.ts.map +1 -0
  206. package/dist/types/init/utils/index.d.ts +2 -2
  207. package/dist/types/installSkills/index.d.ts +1 -0
  208. package/dist/types/installSkills/index.d.ts.map +1 -1
  209. package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +1 -1
  210. package/dist/types/loadDictionaries/logTypeScriptErrors.d.ts.map +1 -1
  211. package/dist/types/loadDictionaries/remoteDictionaryClient.d.ts +14 -0
  212. package/dist/types/loadDictionaries/remoteDictionaryClient.d.ts.map +1 -0
  213. package/dist/types/prepareIntlayerServer.d.ts +67 -0
  214. package/dist/types/prepareIntlayerServer.d.ts.map +1 -0
  215. package/dist/types/scan/analyzeBundleContent.d.ts.map +1 -1
  216. package/dist/types/scan/calculateScore.d.ts +4 -1
  217. package/dist/types/scan/calculateScore.d.ts.map +1 -1
  218. package/dist/types/scan/checks.d.ts +114 -21
  219. package/dist/types/scan/checks.d.ts.map +1 -1
  220. package/dist/types/scan/detection/checkDetails.d.ts +29 -0
  221. package/dist/types/scan/detection/checkDetails.d.ts.map +1 -0
  222. package/dist/types/scan/detection/classifyInternalLinks.d.ts +44 -0
  223. package/dist/types/scan/detection/classifyInternalLinks.d.ts.map +1 -0
  224. package/dist/types/scan/detection/detectRoutingStrategy.d.ts +60 -0
  225. package/dist/types/scan/detection/detectRoutingStrategy.d.ts.map +1 -0
  226. package/dist/types/scan/detection/detectTechnologies.d.ts +60 -0
  227. package/dist/types/scan/detection/detectTechnologies.d.ts.map +1 -0
  228. package/dist/types/scan/detection/index.d.ts +9 -0
  229. package/dist/types/scan/detection/localeCode.d.ts +49 -0
  230. package/dist/types/scan/detection/localeCode.d.ts.map +1 -0
  231. package/dist/types/scan/detection/localizedPages.d.ts +40 -0
  232. package/dist/types/scan/detection/localizedPages.d.ts.map +1 -0
  233. package/dist/types/scan/detection/technologySignatures.d.ts +48 -0
  234. package/dist/types/scan/detection/technologySignatures.d.ts.map +1 -0
  235. package/dist/types/scan/detection/url.d.ts +27 -0
  236. package/dist/types/scan/detection/url.d.ts.map +1 -0
  237. package/dist/types/scan/fetchText.d.ts +30 -0
  238. package/dist/types/scan/fetchText.d.ts.map +1 -0
  239. package/dist/types/scan/index.d.ts +16 -4
  240. package/dist/types/scan/parseHtml.d.ts +17 -0
  241. package/dist/types/scan/parseHtml.d.ts.map +1 -1
  242. package/dist/types/scan/robots.d.ts +23 -0
  243. package/dist/types/scan/robots.d.ts.map +1 -0
  244. package/dist/types/scan/runScanChecks.d.ts +43 -0
  245. package/dist/types/scan/runScanChecks.d.ts.map +1 -0
  246. package/dist/types/scan/scanWebsite.d.ts.map +1 -1
  247. package/dist/types/scan/sitemap.d.ts +49 -0
  248. package/dist/types/scan/sitemap.d.ts.map +1 -0
  249. package/dist/types/scan/types.d.ts +15 -0
  250. package/dist/types/scan/types.d.ts.map +1 -1
  251. package/dist/types/utils/chunkJSON.d.ts.map +1 -1
  252. package/dist/types/utils/getProcessChainCommands.d.ts +35 -0
  253. package/dist/types/utils/getProcessChainCommands.d.ts.map +1 -0
  254. package/dist/types/utils/index.d.ts +2 -1
  255. package/dist/types/utils/runParallel/pidTree.d.ts.map +1 -1
  256. package/dist/types/utils/startContentWatcher.d.ts +40 -0
  257. package/dist/types/utils/startContentWatcher.d.ts.map +1 -0
  258. package/dist/types/watcher.d.ts.map +1 -1
  259. package/dist/types/writeContentDeclaration/writeMarkdownFile.d.ts.map +1 -1
  260. package/package.json +15 -7
  261. package/dist/cjs/init/utils/devScript.cjs +0 -57
  262. package/dist/cjs/init/utils/devScript.cjs.map +0 -1
  263. package/dist/esm/init/utils/devScript.mjs +0 -55
  264. package/dist/esm/init/utils/devScript.mjs.map +0 -1
  265. package/dist/types/init/utils/devScript.d.ts +0 -48
  266. package/dist/types/init/utils/devScript.d.ts.map +0 -1
@@ -0,0 +1,132 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_utils_startContentWatcher = require('./utils/startContentWatcher.cjs');
3
+ const require_prepareIntlayer = require('./prepareIntlayer.cjs');
4
+ const require_utils_getProcessChainCommands = require('./utils/getProcessChainCommands.cjs');
5
+ let _intlayer_config_logger = require("@intlayer/config/logger");
6
+
7
+ //#region src/prepareIntlayerServer.ts
8
+ /**
9
+ * Explicit override, for any setup the detection below does not recognise:
10
+ * `INTLAYER_WATCH=true` forces the content watcher on, `INTLAYER_WATCH=false`
11
+ * forces it off.
12
+ */
13
+ const INTLAYER_WATCH_ENV_VAR = "INTLAYER_WATCH";
14
+ /** Runtime flags that restart or reload the process on file changes. */
15
+ const WATCH_MODE_EXEC_ARGUMENTS = [
16
+ "--watch",
17
+ "--watch-path",
18
+ "--hot"
19
+ ];
20
+ /**
21
+ * Environment variables set on the child process by a restarting watcher:
22
+ * `node --watch` and `ts-node-dev`.
23
+ */
24
+ const WATCH_MODE_ENV_VARS = ["WATCH_REPORT_DEPENDENCIES", "TS_NODE_DEV"];
25
+ /**
26
+ * Package script names that start a dev server (`dev`, `start:dev`,
27
+ * `dev:api`, `watch`…), matched on the `npm_lifecycle_event` that npm, pnpm,
28
+ * yarn and bun set for `<pm> run <script>`.
29
+ */
30
+ const DEV_SCRIPT_NAME_PATTERN = /\b(dev|develop|development|watch)\b/;
31
+ /**
32
+ * Command lines of the tools that restart a server on file changes, matched on
33
+ * this process and the ones above it. Needed because most of them leave no
34
+ * trace in the child itself.
35
+ *
36
+ * - Dedicated restarters, matched on their executable name (`nodemon`,
37
+ * `watchexec`, `entr`…).
38
+ * - `tsx watch`, whose watch mode is a subcommand.
39
+ * - Any runtime or CLI given `--watch` / `--hot`: `deno run --watch` (which
40
+ * restarts in-process), `nest start --watch`, `tsup --watch --onSuccess`…
41
+ * - The `-w` shorthand of build tools that run the server on each rebuild
42
+ * (`tsdown -w --on-success "node dist/index.mjs"`).
43
+ */
44
+ const DEV_WATCHER_COMMAND_PATTERNS = [
45
+ /(^|[\s/])(nodemon|ts-node-dev|tsnd|node-dev|tsc-watch|supervisor|watchexec|entr|chokidar|onchange)(\.c?m?js)?(\s|$)/,
46
+ /(^|[\s/])tsx(\/dist\/cli\.m?js)?\s+watch(\s|$)/,
47
+ /\s--(watch|watch-path|hot)(=|\s|$)/,
48
+ /(^|[\s/])(tsdown|tsup|tsc|rollup|rolldown)(\/\S*)?(\s+\S+)*\s+-w(\s|$)/
49
+ ];
50
+ /**
51
+ * Whether a command line is a watcher that restarts its child on changes.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * getIsDevWatcherCommand('node /app/node_modules/.bin/nodemon src/index.ts'); // → true
56
+ * getIsDevWatcherCommand('node dist/index.js'); // → false
57
+ * ```
58
+ */
59
+ const getIsDevWatcherCommand = (command) => DEV_WATCHER_COMMAND_PATTERNS.some((pattern) => pattern.test(command));
60
+ /**
61
+ * Whether this process runs under a watcher that restarts or reloads it
62
+ * (`bun --watch`/`--hot`, `node --watch`, `ts-node-dev`).
63
+ */
64
+ const getIsWatchModeProcess = () => process.execArgv.some((argument) => WATCH_MODE_EXEC_ARGUMENTS.some((flag) => argument === flag || argument.startsWith(`${flag}=`))) || WATCH_MODE_ENV_VARS.some((envVar) => Boolean(process.env[envVar]));
65
+ /**
66
+ * Whether a server process runs in development, and so should watch the
67
+ * content declarations.
68
+ *
69
+ * `INTLAYER_WATCH=true|false` decides first, then `NODE_ENV` when set. An unset
70
+ * `NODE_ENV` is not a sign of development (`bun dist/index.mjs` rarely sets
71
+ * it), so the process must then show a positive signal, cheapest first:
72
+ * 1. a runtime watch flag or marker (`bun --watch`/`--hot`, `node --watch`,
73
+ * `ts-node-dev`);
74
+ * 2. a `dev`-like package script;
75
+ * 3. a restarting watcher in its own command line or its ancestors'
76
+ * (`deno run --watch`, `nodemon`, `tsx watch`…), for those started
77
+ * directly rather than through a script.
78
+ */
79
+ const getIsServerDevelopment = async () => {
80
+ const watchOverride = process.env[INTLAYER_WATCH_ENV_VAR]?.toLowerCase();
81
+ if (watchOverride === "true" || watchOverride === "1") return true;
82
+ if (watchOverride === "false" || watchOverride === "0") return false;
83
+ const nodeEnv = process.env.NODE_ENV;
84
+ if (nodeEnv) return nodeEnv === "development";
85
+ if (getIsWatchModeProcess()) return true;
86
+ if (DEV_SCRIPT_NAME_PATTERN.test(process.env["npm_lifecycle_event"] ?? "")) return true;
87
+ return (await require_utils_getProcessChainCommands.getProcessChainCommands()).some(getIsDevWatcherCommand);
88
+ };
89
+ /**
90
+ * The dev check of this process, computed once: its answer cannot change for
91
+ * the life of the process, and Fastify, Elysia or Remix may register the
92
+ * integration more than once.
93
+ */
94
+ let serverDevelopmentPromise;
95
+ const getIsServerDevelopmentOnce = () => {
96
+ serverDevelopmentPromise ??= getIsServerDevelopment();
97
+ return serverDevelopmentPromise;
98
+ };
99
+ /**
100
+ * Prepares the dictionaries for a server integration (Express, Fastify, Hono…)
101
+ * and, in development, keeps them in sync with the content declarations.
102
+ *
103
+ * Replaces wrapping the dev server in `intlayer watch --with`: the watcher runs
104
+ * inside the server, deduplicated through the project's watcher lock, so a
105
+ * server restarted by `tsx watch` / `node --watch` hands it over to its
106
+ * successor, and a remaining `intlayer watch` makes it stand down.
107
+ *
108
+ * Fire-and-forget: the server must not wait on the build to start listening.
109
+ *
110
+ * @param configuration - The resolved Intlayer configuration.
111
+ * @param options - How the integration identifies itself, and whether to watch.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * prepareIntlayerServer(getConfiguration(), { label: 'express-intlayer' });
116
+ * ```
117
+ */
118
+ const prepareIntlayerServer = (configuration, { label, watch }) => {
119
+ require_prepareIntlayer.prepareIntlayer(configuration).then(async () => {
120
+ if (!configuration.content.watch) return;
121
+ if (watch ?? await getIsServerDevelopmentOnce()) require_utils_startContentWatcher.startContentWatcher(configuration, { label });
122
+ }).catch((error) => {
123
+ (0, _intlayer_config_logger.getAppLogger)(configuration)(["Failed to prepare Intlayer dictionaries:", error], { level: "error" });
124
+ });
125
+ };
126
+
127
+ //#endregion
128
+ exports.INTLAYER_WATCH_ENV_VAR = INTLAYER_WATCH_ENV_VAR;
129
+ exports.getIsDevWatcherCommand = getIsDevWatcherCommand;
130
+ exports.getIsServerDevelopment = getIsServerDevelopment;
131
+ exports.prepareIntlayerServer = prepareIntlayerServer;
132
+ //# sourceMappingURL=prepareIntlayerServer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepareIntlayerServer.cjs","names":["getProcessChainCommands"],"sources":["../../src/prepareIntlayerServer.ts"],"sourcesContent":["import { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport { getProcessChainCommands } from './utils/getProcessChainCommands';\nimport { startContentWatcher } from './utils/startContentWatcher';\n\n/**\n * Explicit override, for any setup the detection below does not recognise:\n * `INTLAYER_WATCH=true` forces the content watcher on, `INTLAYER_WATCH=false`\n * forces it off.\n */\nexport const INTLAYER_WATCH_ENV_VAR = 'INTLAYER_WATCH';\n\n/** Runtime flags that restart or reload the process on file changes. */\nconst WATCH_MODE_EXEC_ARGUMENTS = ['--watch', '--watch-path', '--hot'];\n\n/**\n * Environment variables set on the child process by a restarting watcher:\n * `node --watch` and `ts-node-dev`.\n */\nconst WATCH_MODE_ENV_VARS = ['WATCH_REPORT_DEPENDENCIES', 'TS_NODE_DEV'];\n\n/**\n * Package script names that start a dev server (`dev`, `start:dev`,\n * `dev:api`, `watch`…), matched on the `npm_lifecycle_event` that npm, pnpm,\n * yarn and bun set for `<pm> run <script>`.\n */\nconst DEV_SCRIPT_NAME_PATTERN = /\\b(dev|develop|development|watch)\\b/;\n\n/**\n * Command lines of the tools that restart a server on file changes, matched on\n * this process and the ones above it. Needed because most of them leave no\n * trace in the child itself.\n *\n * - Dedicated restarters, matched on their executable name (`nodemon`,\n * `watchexec`, `entr`…).\n * - `tsx watch`, whose watch mode is a subcommand.\n * - Any runtime or CLI given `--watch` / `--hot`: `deno run --watch` (which\n * restarts in-process), `nest start --watch`, `tsup --watch --onSuccess`…\n * - The `-w` shorthand of build tools that run the server on each rebuild\n * (`tsdown -w --on-success \"node dist/index.mjs\"`).\n */\nconst DEV_WATCHER_COMMAND_PATTERNS = [\n /(^|[\\s/])(nodemon|ts-node-dev|tsnd|node-dev|tsc-watch|supervisor|watchexec|entr|chokidar|onchange)(\\.c?m?js)?(\\s|$)/,\n /(^|[\\s/])tsx(\\/dist\\/cli\\.m?js)?\\s+watch(\\s|$)/,\n /\\s--(watch|watch-path|hot)(=|\\s|$)/,\n // `-w` alone is too common a flag (`grep -w`), so it only counts after a\n // build tool whose `-w` means watch (`tsdown -w --on-success …`, `tsup -w`).\n /(^|[\\s/])(tsdown|tsup|tsc|rollup|rolldown)(\\/\\S*)?(\\s+\\S+)*\\s+-w(\\s|$)/,\n];\n\n/**\n * Whether a command line is a watcher that restarts its child on changes.\n *\n * @example\n * ```ts\n * getIsDevWatcherCommand('node /app/node_modules/.bin/nodemon src/index.ts'); // → true\n * getIsDevWatcherCommand('node dist/index.js'); // → false\n * ```\n */\nexport const getIsDevWatcherCommand = (command: string): boolean =>\n DEV_WATCHER_COMMAND_PATTERNS.some((pattern) => pattern.test(command));\n\n/**\n * Whether this process runs under a watcher that restarts or reloads it\n * (`bun --watch`/`--hot`, `node --watch`, `ts-node-dev`).\n */\nconst getIsWatchModeProcess = (): boolean =>\n process.execArgv.some((argument) =>\n WATCH_MODE_EXEC_ARGUMENTS.some(\n (flag) => argument === flag || argument.startsWith(`${flag}=`)\n )\n ) || WATCH_MODE_ENV_VARS.some((envVar) => Boolean(process.env[envVar]));\n\n/**\n * Whether a server process runs in development, and so should watch the\n * content declarations.\n *\n * `INTLAYER_WATCH=true|false` decides first, then `NODE_ENV` when set. An unset\n * `NODE_ENV` is not a sign of development (`bun dist/index.mjs` rarely sets\n * it), so the process must then show a positive signal, cheapest first:\n * 1. a runtime watch flag or marker (`bun --watch`/`--hot`, `node --watch`,\n * `ts-node-dev`);\n * 2. a `dev`-like package script;\n * 3. a restarting watcher in its own command line or its ancestors'\n * (`deno run --watch`, `nodemon`, `tsx watch`…), for those started\n * directly rather than through a script.\n */\nexport const getIsServerDevelopment = async (): Promise<boolean> => {\n const watchOverride = process.env[INTLAYER_WATCH_ENV_VAR]?.toLowerCase();\n\n if (watchOverride === 'true' || watchOverride === '1') return true;\n if (watchOverride === 'false' || watchOverride === '0') return false;\n\n const nodeEnv = process.env['NODE_ENV'];\n\n if (nodeEnv) return nodeEnv === 'development';\n\n if (getIsWatchModeProcess()) return true;\n\n if (DEV_SCRIPT_NAME_PATTERN.test(process.env['npm_lifecycle_event'] ?? '')) {\n return true;\n }\n\n const processChainCommands = await getProcessChainCommands();\n\n return processChainCommands.some(getIsDevWatcherCommand);\n};\n\n/**\n * The dev check of this process, computed once: its answer cannot change for\n * the life of the process, and Fastify, Elysia or Remix may register the\n * integration more than once.\n */\nlet serverDevelopmentPromise: Promise<boolean> | undefined;\n\nconst getIsServerDevelopmentOnce = (): Promise<boolean> => {\n serverDevelopmentPromise ??= getIsServerDevelopment();\n\n return serverDevelopmentPromise;\n};\n\nexport type PrepareIntlayerServerOptions = {\n /**\n * How the integration names itself in the watcher lock and in messages, e.g.\n * `express-intlayer`.\n */\n label: string;\n /**\n * Whether to watch the content declarations after preparing them.\n * Defaults to {@link getIsServerDevelopment}.\n */\n watch?: boolean;\n};\n\n/**\n * Prepares the dictionaries for a server integration (Express, Fastify, Hono…)\n * and, in development, keeps them in sync with the content declarations.\n *\n * Replaces wrapping the dev server in `intlayer watch --with`: the watcher runs\n * inside the server, deduplicated through the project's watcher lock, so a\n * server restarted by `tsx watch` / `node --watch` hands it over to its\n * successor, and a remaining `intlayer watch` makes it stand down.\n *\n * Fire-and-forget: the server must not wait on the build to start listening.\n *\n * @param configuration - The resolved Intlayer configuration.\n * @param options - How the integration identifies itself, and whether to watch.\n *\n * @example\n * ```ts\n * prepareIntlayerServer(getConfiguration(), { label: 'express-intlayer' });\n * ```\n */\nexport const prepareIntlayerServer = (\n configuration: IntlayerConfig,\n { label, watch }: PrepareIntlayerServerOptions\n): void => {\n prepareIntlayer(configuration)\n .then(async () => {\n if (!configuration.content.watch) return;\n\n const shouldWatch = watch ?? (await getIsServerDevelopmentOnce());\n\n if (shouldWatch) startContentWatcher(configuration, { label });\n })\n .catch((error: unknown) => {\n getAppLogger(configuration)(\n ['Failed to prepare Intlayer dictionaries:', error],\n { level: 'error' }\n );\n });\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,yBAAyB;;AAGtC,MAAM,4BAA4B;CAAC;CAAW;CAAgB;AAAO;;;;;AAMrE,MAAM,sBAAsB,CAAC,6BAA6B,aAAa;;;;;;AAOvE,MAAM,0BAA0B;;;;;;;;;;;;;;AAehC,MAAM,+BAA+B;CACnC;CACA;CACA;CAGA;AACF;;;;;;;;;;AAWA,MAAa,0BAA0B,YACrC,6BAA6B,MAAM,YAAY,QAAQ,KAAK,OAAO,CAAC;;;;;AAMtE,MAAM,8BACJ,QAAQ,SAAS,MAAM,aACrB,0BAA0B,MACvB,SAAS,aAAa,QAAQ,SAAS,WAAW,GAAG,KAAK,EAAE,CAC/D,CACF,KAAK,oBAAoB,MAAM,WAAW,QAAQ,QAAQ,IAAI,OAAO,CAAC;;;;;;;;;;;;;;;AAgBxE,MAAa,yBAAyB,YAA8B;CAClE,MAAM,gBAAgB,QAAQ,IAAI,uBAAuB,EAAE,YAAY;CAEvE,IAAI,kBAAkB,UAAU,kBAAkB,KAAK,OAAO;CAC9D,IAAI,kBAAkB,WAAW,kBAAkB,KAAK,OAAO;CAE/D,MAAM;CAEN,IAAI,SAAS,OAAO,YAAY;CAEhC,IAAI,sBAAsB,GAAG,OAAO;CAEpC,IAAI,wBAAwB,KAAK,QAAQ,IAAI,0BAA0B,EAAE,GACvE,OAAO;CAKT,QAAO,MAF4BA,8DAAwB,EAEhC,CAAC,KAAK,sBAAsB;AACzD;;;;;;AAOA,IAAI;AAEJ,MAAM,mCAAqD;CACzD,6BAA6B,uBAAuB;CAEpD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,yBACX,eACA,EAAE,OAAO,YACA;CACT,wCAAgB,aAAa,CAAC,CAC3B,KAAK,YAAY;EAChB,IAAI,CAAC,cAAc,QAAQ,OAAO;EAIlC,IAFoB,SAAU,MAAM,2BAA2B,GAE9C,sDAAoB,eAAe,EAAE,MAAM,CAAC;CAC/D,CAAC,CAAC,CACD,OAAO,UAAmB;EACzB,0CAAa,aAAa,CAAC,CACzB,CAAC,4CAA4C,KAAK,GAClD,EAAE,OAAO,QAAQ,CACnB;CACF,CAAC;AACL"}
@@ -16,18 +16,20 @@ const isLocaleCode = (key) => allLocaleValues.has(key) || /^[a-z]{2}(-[A-Z]{2,4}
16
16
  /** Find the end index of the value following a `locale:` key. */
17
17
  const extractValueEnd = (text, valueStart) => {
18
18
  let cursor = valueStart;
19
- while (cursor < text.length && " \n\r".includes(text[cursor])) cursor++;
19
+ while (cursor < text.length && " \n\r".includes(text[cursor] ?? "")) cursor++;
20
20
  if (cursor >= text.length) return valueStart;
21
21
  const char = text[cursor];
22
+ if (!char) return valueStart;
22
23
  if (char === "{" || char === "[") {
23
24
  const endChar = char === "{" ? "}" : "]";
24
25
  let depth = 1;
25
26
  cursor++;
26
27
  while (cursor < text.length && depth > 0) {
27
- if (text[cursor] === char) depth++;
28
- else if (text[cursor] === endChar) depth--;
29
- else if (text[cursor] === "\"" || text[cursor] === "`") {
30
- const quote = text[cursor];
28
+ const c = text[cursor];
29
+ if (c === char) depth++;
30
+ else if (c === endChar) depth--;
31
+ else if (c === "\"" || c === "`") {
32
+ const quote = c;
31
33
  cursor++;
32
34
  while (cursor < text.length) {
33
35
  if (text[cursor] === "\\") {
@@ -74,7 +76,7 @@ const analyzeChunkLocaleContent = (text, baseCurrent) => {
74
76
  let match = regex.exec(text);
75
77
  while (match !== null) {
76
78
  const locale = match[1] ?? match[2];
77
- if (isLocaleCode(locale)) {
79
+ if (locale && isLocaleCode(locale)) {
78
80
  const valueStart = match.index + match[0].length;
79
81
  const valueEnd = extractValueEnd(text, valueStart);
80
82
  const valueSize = valueEnd - valueStart;
@@ -89,12 +91,22 @@ const analyzeChunkLocaleContent = (text, baseCurrent) => {
89
91
  }
90
92
  match = regex.exec(text);
91
93
  }
94
+ const languageOf = (candidate) => (candidate.locale.split("-")[0] ?? "").toLowerCase();
92
95
  const isI18nMatch = (idx) => {
93
- const base = candidates[idx].locale.split("-")[0].toLowerCase();
96
+ const currentCandidate = candidates[idx];
97
+ if (!currentCandidate) return false;
98
+ const base = languageOf(currentCandidate);
99
+ let hasOtherLanguage = false;
100
+ let hasCurrentLanguage = base === baseCurrent;
94
101
  for (let j = 0; j < candidates.length; j++) {
95
102
  if (j === idx) continue;
96
- if (Math.abs(candidates[j].position - candidates[idx].position) > LOCALE_CLUSTER_WINDOW) continue;
97
- if (candidates[j].locale.split("-")[0].toLowerCase() !== base) return true;
103
+ const neighbor = candidates[j];
104
+ if (!neighbor) continue;
105
+ if (Math.abs(neighbor.position - currentCandidate.position) > LOCALE_CLUSTER_WINDOW) continue;
106
+ const neighborLanguage = languageOf(neighbor);
107
+ if (neighborLanguage !== base) hasOtherLanguage = true;
108
+ if (neighborLanguage === baseCurrent) hasCurrentLanguage = true;
109
+ if (hasOtherLanguage && hasCurrentLanguage) return true;
98
110
  }
99
111
  return false;
100
112
  };
@@ -103,9 +115,11 @@ const analyzeChunkLocaleContent = (text, baseCurrent) => {
103
115
  let dictionariesFound = 0;
104
116
  for (let i = 0; i < candidates.length; i++) {
105
117
  if (!isI18nMatch(i)) continue;
106
- const { locale, valueSize } = candidates[i];
118
+ const candidate = candidates[i];
119
+ if (!candidate) continue;
120
+ const { locale, valueSize } = candidate;
107
121
  dictionariesFound++;
108
- if (locale.split("-")[0].toLowerCase() === baseCurrent) usedLocaleSize += valueSize;
122
+ if ((locale.split("-")[0] ?? "").toLowerCase() === baseCurrent) usedLocaleSize += valueSize;
109
123
  else unusedLocaleSize += valueSize;
110
124
  }
111
125
  return {
@@ -141,7 +155,7 @@ const analyzeBundleContent = (chunks, htmlContent, currentLocale, totalPageSize)
141
155
  pageStrings.forEach((text) => {
142
156
  renderedContentSize += require_scan_parseHtml.byteLength(text);
143
157
  });
144
- const baseCurrent = currentLocale.split("-")[0].toLowerCase();
158
+ const baseCurrent = (currentLocale.split("-")[0] ?? "").toLowerCase();
145
159
  const mainBundleChunks = [];
146
160
  const lazyBundleChunks = [];
147
161
  for (const chunk of chunks) {
@@ -1 +1 @@
1
- {"version":3,"file":"analyzeBundleContent.cjs","names":["ALL_LOCALES","extractVisibleTextStrings","byteLength"],"sources":["../../../src/scan/analyzeBundleContent.ts"],"sourcesContent":["import { ALL_LOCALES } from '@intlayer/types/allLocales';\nimport { byteLength, extractVisibleTextStrings } from './parseHtml';\nimport type {\n BundleChunkInput,\n BundleContentAnalysis,\n ChunkAnalysis,\n} from './types';\n\n/**\n * Detect and measure localized (i18n) content embedded in JavaScript bundles.\n *\n * This is a dependency-free port of the hosted backend bundle analyzer: it\n * estimates how many translation strings ship in each chunk and, of those, how\n * many belong to locales other than the one currently rendered (i.e. dead\n * weight that a build-time optimization could strip).\n */\n\nconst allLocaleValues = new Set(Object.values(ALL_LOCALES) as string[]);\n\nconst isLocaleCode = (key: string): boolean =>\n allLocaleValues.has(key) || /^[a-z]{2}(-[A-Z]{2,4})?$/.test(key);\n\n/** Find the end index of the value following a `locale:` key. */\nconst extractValueEnd = (text: string, valueStart: number): number => {\n let cursor = valueStart;\n while (cursor < text.length && ' \\t\\n\\r'.includes(text[cursor])) cursor++;\n if (cursor >= text.length) return valueStart;\n\n const char = text[cursor];\n if (char === '{' || char === '[') {\n const endChar = char === '{' ? '}' : ']';\n let depth = 1;\n cursor++;\n while (cursor < text.length && depth > 0) {\n if (text[cursor] === char) depth++;\n else if (text[cursor] === endChar) depth--;\n else if (text[cursor] === '\"' || text[cursor] === '`') {\n const quote = text[cursor];\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === '\\\\') {\n cursor += 2;\n continue;\n }\n if (text[cursor] === quote) break;\n cursor++;\n }\n }\n cursor++;\n }\n return cursor;\n }\n if (char === '\"' || char === '`') {\n const quote = char;\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === '\\\\') {\n cursor += 2;\n continue;\n }\n if (text[cursor] === quote) {\n cursor++;\n break;\n }\n cursor++;\n }\n return cursor;\n }\n const endMatch = text.slice(cursor).search(/[,}\\]\\s]/);\n return endMatch === -1 ? text.length : cursor + endMatch;\n};\n\n// Matches both quoted (\"en\":) and unquoted (en:) locale keys followed by {\n// Works for any i18n solution — intlayer, i18next, vue-i18n, FormatJS, etc.\nconst LOCALE_KEY_PATTERN =\n /(?:\"([a-z]{2}(?:-[A-Z]{2,4})?)\"|\\b([a-z]{2}(?:-[A-Z]{2,4})?)\\b)\\s*:\\s*(?=\\{)/g;\n\n// Maximum character gap between two locale key positions to consider them\n// part of the same i18n object. Large enough for big translation objects.\nconst LOCALE_CLUSTER_WINDOW = 10_000;\n\n// Returns false when a candidate value is clearly not i18n text:\n// - contains hex/control escape sequences (ANSI codes, binary data)\nconst looksLikeI18nContent = (valueText: string): boolean => {\n if (/\\\\x[0-9a-fA-F]{2}/.test(valueText)) return false;\n if (/\\\\u00[01][0-9a-fA-F]/.test(valueText)) return false;\n return true;\n};\n\ntype LocaleMatch = {\n locale: string;\n position: number;\n valueStart: number;\n valueEnd: number;\n valueSize: number;\n};\n\nconst analyzeChunkLocaleContent = (\n text: string,\n baseCurrent: string\n): {\n unusedLocaleSize: number;\n usedLocaleSize: number;\n dictionariesFound: number;\n} => {\n // Step 1: collect all candidate locale key matches\n const candidates: LocaleMatch[] = [];\n const regex = new RegExp(LOCALE_KEY_PATTERN.source, 'g');\n let match = regex.exec(text);\n\n while (match !== null) {\n const locale = match[1] ?? match[2];\n if (isLocaleCode(locale)) {\n const valueStart = match.index + match[0].length;\n const valueEnd = extractValueEnd(text, valueStart);\n const valueSize = valueEnd - valueStart;\n const valueText = text.slice(valueStart, valueEnd);\n if (valueSize >= 5 && looksLikeI18nContent(valueText)) {\n candidates.push({\n locale,\n position: match.index,\n valueStart,\n valueEnd,\n valueSize,\n });\n }\n }\n match = regex.exec(text);\n }\n\n // Step 2: a locale key is i18n content only if another locale key with a\n // DIFFERENT locale code exists within LOCALE_CLUSTER_WINDOW chars.\n const isI18nMatch = (idx: number): boolean => {\n const base = candidates[idx].locale.split('-')[0].toLowerCase();\n for (let j = 0; j < candidates.length; j++) {\n if (j === idx) continue;\n const dist = Math.abs(candidates[j].position - candidates[idx].position);\n if (dist > LOCALE_CLUSTER_WINDOW) continue;\n if (candidates[j].locale.split('-')[0].toLowerCase() !== base)\n return true;\n }\n return false;\n };\n\n let unusedLocaleSize = 0;\n let usedLocaleSize = 0;\n let dictionariesFound = 0;\n\n for (let i = 0; i < candidates.length; i++) {\n if (!isI18nMatch(i)) continue;\n\n const { locale, valueSize } = candidates[i];\n dictionariesFound++;\n\n if (locale.split('-')[0].toLowerCase() === baseCurrent) {\n usedLocaleSize += valueSize;\n } else {\n unusedLocaleSize += valueSize;\n }\n }\n\n return { unusedLocaleSize, usedLocaleSize, dictionariesFound };\n};\n\n/**\n * Analyze the locale weight of a page's JavaScript bundles.\n *\n * @param chunks - The fetched JavaScript chunks (main + lazy).\n * @param htmlContent - The page HTML, used to estimate rendered content size.\n * @param currentLocale - The locale currently rendered by the page.\n * @param totalPageSize - The total transferred bytes measured for the page.\n * @returns The aggregated {@link BundleContentAnalysis}.\n */\nexport const analyzeBundleContent = (\n chunks: BundleChunkInput[],\n htmlContent: string,\n currentLocale: string,\n totalPageSize: number\n): BundleContentAnalysis => {\n const empty: BundleContentAnalysis = {\n currentLocale,\n totalPageSize,\n renderedContentSize: 0,\n contentSize: 0,\n totalLocaleSize: 0,\n totalUnusedLocaleSize: 0,\n unusedPercentOfLocale: 0,\n mainBundleChunks: [],\n lazyBundleChunks: [],\n };\n\n if (!chunks.length && !htmlContent) return empty;\n\n // Rendered content size from HTML visible text (deduplicated).\n const pageStrings = new Set(extractVisibleTextStrings(htmlContent));\n\n let renderedContentSize = 0;\n pageStrings.forEach((text) => {\n renderedContentSize += byteLength(text);\n });\n\n const baseCurrent = currentLocale.split('-')[0].toLowerCase();\n\n const mainBundleChunks: ChunkAnalysis[] = [];\n const lazyBundleChunks: ChunkAnalysis[] = [];\n\n for (const chunk of chunks) {\n const { unusedLocaleSize, usedLocaleSize, dictionariesFound } =\n analyzeChunkLocaleContent(chunk.content, baseCurrent);\n\n const totalLocaleSize = unusedLocaleSize + usedLocaleSize;\n const analysis: ChunkAnalysis = {\n url: chunk.url,\n fileSize: byteLength(chunk.content),\n totalLocaleSize,\n unusedLocaleSize,\n usedLocaleSize,\n dictionariesFound,\n unusedPercent:\n totalLocaleSize > 0\n ? Math.round((unusedLocaleSize / totalLocaleSize) * 100)\n : 0,\n };\n\n if (chunk.isMainBundle) {\n mainBundleChunks.push(analysis);\n } else if (dictionariesFound > 0) {\n lazyBundleChunks.push(analysis);\n }\n }\n\n const totalUnusedLocaleSize =\n mainBundleChunks.reduce((sum, c) => sum + c.unusedLocaleSize, 0) +\n lazyBundleChunks.reduce((sum, c) => sum + c.unusedLocaleSize, 0);\n const totalLocaleSize =\n mainBundleChunks.reduce((sum, c) => sum + c.totalLocaleSize, 0) +\n lazyBundleChunks.reduce((sum, c) => sum + c.totalLocaleSize, 0);\n const contentSize = renderedContentSize + totalLocaleSize;\n\n const unusedPercentOfLocale =\n totalLocaleSize > 0\n ? Math.round((totalUnusedLocaleSize / totalLocaleSize) * 100)\n : 0;\n\n return {\n currentLocale,\n totalPageSize,\n renderedContentSize,\n contentSize,\n totalLocaleSize,\n totalUnusedLocaleSize,\n unusedPercentOfLocale,\n mainBundleChunks,\n lazyBundleChunks,\n };\n};\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,kBAAkB,IAAI,IAAI,OAAO,OAAOA,sCAAW,CAAa;AAEtE,MAAM,gBAAgB,QACpB,gBAAgB,IAAI,GAAG,KAAK,2BAA2B,KAAK,GAAG;;AAGjE,MAAM,mBAAmB,MAAc,eAA+B;CACpE,IAAI,SAAS;CACb,OAAO,SAAS,KAAK,UAAU,SAAU,SAAS,KAAK,OAAO,GAAG;CACjE,IAAI,UAAU,KAAK,QAAQ,OAAO;CAElC,MAAM,OAAO,KAAK;CAClB,IAAI,SAAS,OAAO,SAAS,KAAK;EAChC,MAAM,UAAU,SAAS,MAAM,MAAM;EACrC,IAAI,QAAQ;EACZ;EACA,OAAO,SAAS,KAAK,UAAU,QAAQ,GAAG;GACxC,IAAI,KAAK,YAAY,MAAM;QACtB,IAAI,KAAK,YAAY,SAAS;QAC9B,IAAI,KAAK,YAAY,QAAO,KAAK,YAAY,KAAK;IACrD,MAAM,QAAQ,KAAK;IACnB;IACA,OAAO,SAAS,KAAK,QAAQ;KAC3B,IAAI,KAAK,YAAY,MAA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MAAM,SAAS,WAAW;EAEtD,MAAM,kBAAkB,mBAAmB;EAC3C,MAAM,WAA0B;GAC9B,KAAK,MAAM;GACX,UAAUA,kCAAW,MAAM,OAAO;GAClC;GACA;GACA;GACA;GACA,eACE,kBAAkB,IACd,KAAK,MAAO,mBAAmB,kBAAmB,GAAG,IACrD;EACR;EAEA,IAAI,MAAM,cACR,iBAAiB,KAAK,QAAQ;OACzB,IAAI,oBAAoB,GAC7B,iBAAiB,KAAK,QAAQ;CAElC;CAEA,MAAM,wBACJ,iBAAiB,QAAQ,KAAK,MAAM,MAAM,EAAE,kBAAkB,CAAC,IAC/D,iBAAiB,QAAQ,KAAK,MAAM,MAAM,EAAE,kBAAkB,CAAC;CACjE,MAAM,kBACJ,iBAAiB,QAAQ,KAAK,MAAM,MAAM,EAAE,iBAAiB,CAAC,IAC9D,iBAAiB,QAAQ,KAAK,MAAM,MAAM,EAAE,iBAAiB,CAAC;CAChE,MAAM,cAAc,sBAAsB;CAE1C,MAAM,wBACJ,kBAAkB,IACd,KAAK,MAAO,wBAAwB,kBAAmB,GAAG,IAC1D;CAEN,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"analyzeBundleContent.cjs","names":["ALL_LOCALES","extractVisibleTextStrings","byteLength"],"sources":["../../../src/scan/analyzeBundleContent.ts"],"sourcesContent":["import { ALL_LOCALES } from '@intlayer/types/allLocales';\nimport { byteLength, extractVisibleTextStrings } from './parseHtml';\nimport type {\n BundleChunkInput,\n BundleContentAnalysis,\n ChunkAnalysis,\n} from './types';\n\n/**\n * Detect and measure localized (i18n) content embedded in JavaScript bundles.\n *\n * This is a dependency-free port of the hosted backend bundle analyzer: it\n * estimates how many translation strings ship in each chunk and, of those, how\n * many belong to locales other than the one currently rendered (i.e. dead\n * weight that a build-time optimization could strip).\n */\n\nconst allLocaleValues = new Set(Object.values(ALL_LOCALES) as string[]);\n\nconst isLocaleCode = (key: string): boolean =>\n allLocaleValues.has(key) || /^[a-z]{2}(-[A-Z]{2,4})?$/.test(key);\n\n/** Find the end index of the value following a `locale:` key. */\nconst extractValueEnd = (text: string, valueStart: number): number => {\n let cursor = valueStart;\n\n while (cursor < text.length && ' \\t\\n\\r'.includes(text[cursor] ?? ''))\n cursor++;\n\n if (cursor >= text.length) return valueStart;\n\n const char = text[cursor];\n\n if (!char) return valueStart;\n\n if (char === '{' || char === '[') {\n const endChar = char === '{' ? '}' : ']';\n let depth = 1;\n cursor++;\n while (cursor < text.length && depth > 0) {\n const c = text[cursor];\n\n if (c === char) depth++;\n else if (c === endChar) depth--;\n else if (c === '\"' || c === '`') {\n const quote = c;\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === '\\\\') {\n cursor += 2;\n continue;\n }\n\n if (text[cursor] === quote) break;\n cursor++;\n }\n }\n cursor++;\n }\n return cursor;\n }\n\n if (char === '\"' || char === '`') {\n const quote = char;\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === '\\\\') {\n cursor += 2;\n continue;\n }\n\n if (text[cursor] === quote) {\n cursor++;\n break;\n }\n cursor++;\n }\n return cursor;\n }\n const endMatch = text.slice(cursor).search(/[,}\\]\\s]/);\n return endMatch === -1 ? text.length : cursor + endMatch;\n};\n\n// Matches both quoted (\"en\":) and unquoted (en:) locale keys followed by {\n// Works for any i18n solution — intlayer, i18next, vue-i18n, FormatJS, etc.\nconst LOCALE_KEY_PATTERN =\n /(?:\"([a-z]{2}(?:-[A-Z]{2,4})?)\"|\\b([a-z]{2}(?:-[A-Z]{2,4})?)\\b)\\s*:\\s*(?=\\{)/g;\n\n// Maximum character gap between two locale key positions to consider them\n// part of the same i18n object. Large enough for big translation objects.\nconst LOCALE_CLUSTER_WINDOW = 10_000;\n\n// Returns false when a candidate value is clearly not i18n text:\n// - contains hex/control escape sequences (ANSI codes, binary data)\nconst looksLikeI18nContent = (valueText: string): boolean => {\n if (/\\\\x[0-9a-fA-F]{2}/.test(valueText)) return false;\n\n if (/\\\\u00[01][0-9a-fA-F]/.test(valueText)) return false;\n return true;\n};\n\ntype LocaleMatch = {\n locale: string;\n position: number;\n valueStart: number;\n valueEnd: number;\n valueSize: number;\n};\n\nconst analyzeChunkLocaleContent = (\n text: string,\n baseCurrent: string\n): {\n unusedLocaleSize: number;\n usedLocaleSize: number;\n dictionariesFound: number;\n} => {\n // Step 1: collect all candidate locale key matches\n const candidates: LocaleMatch[] = [];\n const regex = new RegExp(LOCALE_KEY_PATTERN.source, 'g');\n let match = regex.exec(text);\n\n while (match !== null) {\n const locale = match[1] ?? match[2];\n\n if (locale && isLocaleCode(locale)) {\n const valueStart = match.index + match[0].length;\n const valueEnd = extractValueEnd(text, valueStart);\n const valueSize = valueEnd - valueStart;\n const valueText = text.slice(valueStart, valueEnd);\n\n if (valueSize >= 5 && looksLikeI18nContent(valueText)) {\n candidates.push({\n locale,\n position: match.index,\n valueStart,\n valueEnd,\n valueSize,\n });\n }\n }\n match = regex.exec(text);\n }\n\n // Step 2: a locale key is i18n content only if, within\n // LOCALE_CLUSTER_WINDOW chars, another locale key with a DIFFERENT language\n // exists AND the rendered locale is part of the cluster. The second rule\n // discards minified object keys that happen to be locale codes (`id:{`,\n // `as:{`, `to:{`…), which never come with the page locale next to them.\n const languageOf = (candidate: LocaleMatch): string =>\n (candidate.locale.split('-')[0] ?? '').toLowerCase();\n\n const isI18nMatch = (idx: number): boolean => {\n const currentCandidate = candidates[idx];\n\n if (!currentCandidate) return false;\n const base = languageOf(currentCandidate);\n let hasOtherLanguage = false;\n let hasCurrentLanguage = base === baseCurrent;\n for (let j = 0; j < candidates.length; j++) {\n if (j === idx) continue;\n const neighbor = candidates[j];\n\n if (!neighbor) continue;\n const dist = Math.abs(neighbor.position - currentCandidate.position);\n\n if (dist > LOCALE_CLUSTER_WINDOW) continue;\n const neighborLanguage = languageOf(neighbor);\n\n if (neighborLanguage !== base) hasOtherLanguage = true;\n\n if (neighborLanguage === baseCurrent) hasCurrentLanguage = true;\n\n if (hasOtherLanguage && hasCurrentLanguage) return true;\n }\n return false;\n };\n\n let unusedLocaleSize = 0;\n let usedLocaleSize = 0;\n let dictionariesFound = 0;\n\n for (let i = 0; i < candidates.length; i++) {\n if (!isI18nMatch(i)) continue;\n\n const candidate = candidates[i];\n\n if (!candidate) continue;\n const { locale, valueSize } = candidate;\n dictionariesFound++;\n\n if ((locale.split('-')[0] ?? '').toLowerCase() === baseCurrent) {\n usedLocaleSize += valueSize;\n } else {\n unusedLocaleSize += valueSize;\n }\n }\n\n return { unusedLocaleSize, usedLocaleSize, dictionariesFound };\n};\n\n/**\n * Analyze the locale weight of a page's JavaScript bundles.\n *\n * @param chunks - The fetched JavaScript chunks (main + lazy).\n * @param htmlContent - The page HTML, used to estimate rendered content size.\n * @param currentLocale - The locale currently rendered by the page.\n * @param totalPageSize - The total transferred bytes measured for the page.\n * @returns The aggregated {@link BundleContentAnalysis}.\n */\nexport const analyzeBundleContent = (\n chunks: BundleChunkInput[],\n htmlContent: string,\n currentLocale: string,\n totalPageSize: number\n): BundleContentAnalysis => {\n const empty: BundleContentAnalysis = {\n currentLocale,\n totalPageSize,\n renderedContentSize: 0,\n contentSize: 0,\n totalLocaleSize: 0,\n totalUnusedLocaleSize: 0,\n unusedPercentOfLocale: 0,\n mainBundleChunks: [],\n lazyBundleChunks: [],\n };\n\n if (!chunks.length && !htmlContent) return empty;\n\n // Rendered content size from HTML visible text (deduplicated).\n const pageStrings = new Set(extractVisibleTextStrings(htmlContent));\n\n let renderedContentSize = 0;\n pageStrings.forEach((text) => {\n renderedContentSize += byteLength(text);\n });\n\n const baseCurrent = (currentLocale.split('-')[0] ?? '').toLowerCase();\n\n const mainBundleChunks: ChunkAnalysis[] = [];\n const lazyBundleChunks: ChunkAnalysis[] = [];\n\n for (const chunk of chunks) {\n const { unusedLocaleSize, usedLocaleSize, dictionariesFound } =\n analyzeChunkLocaleContent(chunk.content, baseCurrent);\n\n const totalLocaleSize = unusedLocaleSize + usedLocaleSize;\n const analysis: ChunkAnalysis = {\n url: chunk.url,\n fileSize: byteLength(chunk.content),\n totalLocaleSize,\n unusedLocaleSize,\n usedLocaleSize,\n dictionariesFound,\n unusedPercent:\n totalLocaleSize > 0\n ? Math.round((unusedLocaleSize / totalLocaleSize) * 100)\n : 0,\n };\n\n if (chunk.isMainBundle) {\n mainBundleChunks.push(analysis);\n } else if (dictionariesFound > 0) {\n lazyBundleChunks.push(analysis);\n }\n }\n\n const totalUnusedLocaleSize =\n mainBundleChunks.reduce((sum, c) => sum + c.unusedLocaleSize, 0) +\n lazyBundleChunks.reduce((sum, c) => sum + c.unusedLocaleSize, 0);\n const totalLocaleSize =\n mainBundleChunks.reduce((sum, c) => sum + c.totalLocaleSize, 0) +\n lazyBundleChunks.reduce((sum, c) => sum + c.totalLocaleSize, 0);\n const contentSize = renderedContentSize + totalLocaleSize;\n\n const unusedPercentOfLocale =\n totalLocaleSize > 0\n ? Math.round((totalUnusedLocaleSize / totalLocaleSize) * 100)\n : 0;\n\n return {\n currentLocale,\n totalPageSize,\n renderedContentSize,\n contentSize,\n totalLocaleSize,\n totalUnusedLocaleSize,\n unusedPercentOfLocale,\n mainBundleChunks,\n lazyBundleChunks,\n };\n};\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,kBAAkB,IAAI,IAAI,OAAO,OAAOA,sCAAW,CAAa;AAEtE,MAAM,gBAAgB,QACpB,gBAAgB,IAAI,GAAG,KAAK,2BAA2B,KAAK,GAAG;;AAGjE,MAAM,mBAAmB,MAAc,eAA+B;CACpE,IAAI,SAAS;CAEb,OAAO,SAAS,KAAK,UAAU,SAAU,SAAS,KAAK,WAAW,EAAE,GAClE;CAEF,IAAI,UAAU,KAAK,QAAQ,OAAO;CAElC,MAAM,OAAO,KAAK;CAElB,IAAI,CAAC,MAAM,OAAO;CAElB,IAAI,SAAS,OAAO,SAAS,KAAK;EAChC,MAAM,UAAU,SAAS,MAAM,MAAM;EACrC,IAAI,QAAQ;EACZ;EACA,OAAO,SAAS,KAAK,UAAU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F"}
@@ -23,10 +23,13 @@ const scoreRecord = {
23
23
  url_htmlDir: 3,
24
24
  url_hasCanonical: 10,
25
25
  url_hreflang: 9,
26
+ url_hreflangReciprocal: 8,
26
27
  url_hasLocalizedLinks: 8,
27
28
  url_hasXDefault: 7,
28
29
  url_allAnchorsLocalized: 6,
29
- url_currentLocale: 3,
30
+ url_hasLangSelector: 6,
31
+ url_currentLocale: 5,
32
+ url_ogLocale: 3,
30
33
  url_unusedBundleContent: 8
31
34
  };
32
35
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"calculateScore.cjs","names":[],"sources":["../../../src/scan/calculateScore.ts"],"sourcesContent":["/**\n * Mutualized SEO/i18n scoring logic.\n *\n * This module is the single source of truth for turning audit/scan events into\n * a weighted score. It is consumed both by the hosted backend SEO audit\n * (`apps/backend`) and by the `intlayer scan` CLI command, so it must stay free\n * of any server-only dependency (no Fastify, no Cheerio, no logger coupling).\n */\n\n/** Accumulated score across all checks that ran. */\nexport type Score = {\n /** Sum of points obtained (success = full, warning = half, error = none). */\n score: number;\n /** Maximum achievable points for the checks that ran. */\n totalScore: number;\n};\n\n/**\n * Minimal shape of an event needed to contribute to the score.\n *\n * The `type` is the check identifier. URL-scoped checks are suffixed with the\n * URL using a backslash separator (e.g. `url_htmlLang\\https://example.com`), so\n * only the part before the first backslash is used to look up the weight.\n */\nexport type ScorableEvent = {\n type?: string;\n status?: string;\n};\n\n/**\n * Resolve how many points an event contributes based on its status.\n * - `warning` → half of the weight\n * - `error` → none\n * - anything else (`success`, `started`, `done`, …) → full weight\n */\nconst scoreCheck = (score: number, event: ScorableEvent): number => {\n if (event.status === 'warning') return score / 2;\n if (event.status === 'error') return 0;\n return score;\n};\n\n/** Weight (in points) of every scorable check. */\nexport const scoreRecord = {\n robots_robotsPresent: 10,\n robots_noLocalizedUrlsForgotten: 8,\n sitemap_sitemapPresent: 10,\n sitemap_noLocalizedUrlsForgotten: 9,\n sitemap_hasAlternates: 8,\n sitemap_hasXDefault: 7,\n url_htmlLang: 9,\n url_htmlDir: 3,\n url_hasCanonical: 10,\n url_hreflang: 9,\n url_hasLocalizedLinks: 8,\n url_hasXDefault: 7,\n url_allAnchorsLocalized: 6,\n url_currentLocale: 3,\n url_unusedBundleContent: 8,\n} as const;\n\n/** Identifier of a scorable check (without the URL suffix). */\nexport type ScoreCheckType = keyof typeof scoreRecord;\n\n/**\n * Apply a single event to the running score, returning a new {@link Score}.\n * Unknown check types are ignored so the function is safe to call on every\n * emitted event.\n *\n * @param score - The current accumulated score.\n * @param event - The event to fold into the score.\n * @returns A new score with the event applied.\n */\nexport const mutateScore = (score: Score, event: ScorableEvent): Score => {\n const newScore: Score = { ...score };\n\n const typeWithoutUrl = event.type?.split('\\\\')[0];\n\n if (!typeWithoutUrl) {\n return newScore;\n }\n\n const scoreValue = scoreRecord[typeWithoutUrl as ScoreCheckType];\n\n if (typeof scoreValue === 'number') {\n newScore.score += scoreCheck(scoreValue, event);\n newScore.totalScore += scoreValue;\n }\n\n return newScore;\n};\n\n/**\n * Convert a raw {@link Score} into a 0–100 percentage.\n *\n * @param score - The accumulated score.\n * @returns The rounded percentage, or 0 when no check ran.\n */\nexport const toScorePercent = (score: Score): number =>\n Math.round(score.totalScore > 0 ? (score.score / score.totalScore) * 100 : 0);\n"],"mappings":";;;;;;;;AAmCA,MAAM,cAAc,OAAe,UAAiC;CAClE,IAAI,MAAM,WAAW,WAAW,OAAO,QAAQ;CAC/C,IAAI,MAAM,WAAW,SAAS,OAAO;CACrC,OAAO;AACT;;AAGA,MAAa,cAAc;CACzB,sBAAsB;CACtB,iCAAiC;CACjC,wBAAwB;CACxB,kCAAkC;CAClC,uBAAuB;CACvB,qBAAqB;CACrB,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,cAAc;CACd,uBAAuB;CACvB,iBAAiB;CACjB,yBAAyB;CACzB,mBAAmB;CACnB,yBAAyB;AAC3B;;;;;;;;;;AAcA,MAAa,eAAe,OAAc,UAAgC;CACxE,MAAM,WAAkB,EAAE,GAAG,MAAM;CAEnC,MAAM,iBAAiB,MAAM,MAAM,MAAM,IAAI,CAAC,CAAC;CAE/C,IAAI,CAAC,gBACH,OAAO;CAGT,MAAM,aAAa,YAAY;CAE/B,IAAI,OAAO,eAAe,UAAU;EAClC,SAAS,SAAS,WAAW,YAAY,KAAK;EAC9C,SAAS,cAAc;CACzB;CAEA,OAAO;AACT;;;;;;;AAQA,MAAa,kBAAkB,UAC7B,KAAK,MAAM,MAAM,aAAa,IAAK,MAAM,QAAQ,MAAM,aAAc,MAAM,CAAC"}
1
+ {"version":3,"file":"calculateScore.cjs","names":[],"sources":["../../../src/scan/calculateScore.ts"],"sourcesContent":["/**\n * Mutualized SEO/i18n scoring logic.\n *\n * This module is the single source of truth for turning audit/scan events into\n * a weighted score. It is consumed both by the hosted backend SEO audit\n * (`apps/backend`) and by the `intlayer scan` CLI command, so it must stay free\n * of any server-only dependency (no Fastify, no Cheerio, no logger coupling).\n */\n\n/** Accumulated score across all checks that ran. */\nexport type Score = {\n /** Sum of points obtained (success = full, warning = half, error = none). */\n score: number;\n /** Maximum achievable points for the checks that ran. */\n totalScore: number;\n};\n\n/**\n * Minimal shape of an event needed to contribute to the score.\n *\n * The `type` is the check identifier. URL-scoped checks are suffixed with the\n * URL using a backslash separator (e.g. `url_htmlLang\\https://example.com`), so\n * only the part before the first backslash is used to look up the weight.\n */\nexport type ScorableEvent = {\n type?: string;\n status?: string;\n};\n\n/**\n * Resolve how many points an event contributes based on its status.\n * - `warning` → half of the weight\n * - `error` → none\n * - anything else (`success`, `started`, `done`, …) → full weight\n */\nconst scoreCheck = (score: number, event: ScorableEvent): number => {\n if (event.status === 'warning') return score / 2;\n if (event.status === 'error') return 0;\n return score;\n};\n\n/** Weight (in points) of every scorable check. */\nexport const scoreRecord = {\n robots_robotsPresent: 10,\n robots_noLocalizedUrlsForgotten: 8,\n sitemap_sitemapPresent: 10,\n sitemap_noLocalizedUrlsForgotten: 9,\n sitemap_hasAlternates: 8,\n sitemap_hasXDefault: 7,\n url_htmlLang: 9,\n url_htmlDir: 3,\n url_hasCanonical: 10,\n url_hreflang: 9,\n url_hreflangReciprocal: 8,\n url_hasLocalizedLinks: 8,\n url_hasXDefault: 7,\n url_allAnchorsLocalized: 6,\n url_hasLangSelector: 6,\n url_currentLocale: 5,\n url_ogLocale: 3,\n url_unusedBundleContent: 8,\n} as const;\n\n/** Identifier of a scorable check (without the URL suffix). */\nexport type ScoreCheckType = keyof typeof scoreRecord;\n\n/**\n * Apply a single event to the running score, returning a new {@link Score}.\n * Unknown check types are ignored so the function is safe to call on every\n * emitted event.\n *\n * @param score - The current accumulated score.\n * @param event - The event to fold into the score.\n * @returns A new score with the event applied.\n */\nexport const mutateScore = (score: Score, event: ScorableEvent): Score => {\n const newScore: Score = { ...score };\n\n const typeWithoutUrl = event.type?.split('\\\\')[0];\n\n if (!typeWithoutUrl) {\n return newScore;\n }\n\n const scoreValue = scoreRecord[typeWithoutUrl as ScoreCheckType];\n\n if (typeof scoreValue === 'number') {\n newScore.score += scoreCheck(scoreValue, event);\n newScore.totalScore += scoreValue;\n }\n\n return newScore;\n};\n\n/**\n * Convert a raw {@link Score} into a 0–100 percentage.\n *\n * @param score - The accumulated score.\n * @returns The rounded percentage, or 0 when no check ran.\n */\nexport const toScorePercent = (score: Score): number =>\n Math.round(score.totalScore > 0 ? (score.score / score.totalScore) * 100 : 0);\n"],"mappings":";;;;;;;;AAmCA,MAAM,cAAc,OAAe,UAAiC;CAClE,IAAI,MAAM,WAAW,WAAW,OAAO,QAAQ;CAC/C,IAAI,MAAM,WAAW,SAAS,OAAO;CACrC,OAAO;AACT;;AAGA,MAAa,cAAc;CACzB,sBAAsB;CACtB,iCAAiC;CACjC,wBAAwB;CACxB,kCAAkC;CAClC,uBAAuB;CACvB,qBAAqB;CACrB,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,cAAc;CACd,wBAAwB;CACxB,uBAAuB;CACvB,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;CACrB,mBAAmB;CACnB,cAAc;CACd,yBAAyB;AAC3B;;;;;;;;;;AAcA,MAAa,eAAe,OAAc,UAAgC;CACxE,MAAM,WAAkB,EAAE,GAAG,MAAM;CAEnC,MAAM,iBAAiB,MAAM,MAAM,MAAM,IAAI,CAAC,CAAC;CAE/C,IAAI,CAAC,gBACH,OAAO;CAGT,MAAM,aAAa,YAAY;CAE/B,IAAI,OAAO,eAAe,UAAU;EAClC,SAAS,SAAS,WAAW,YAAY,KAAK;EAC9C,SAAS,cAAc;CACzB;CAEA,OAAO;AACT;;;;;;;AAQA,MAAa,kBAAkB,UAC7B,KAAK,MAAM,MAAM,aAAa,IAAK,MAAM,QAAQ,MAAM,aAAc,MAAM,CAAC"}