@jshookmcp/jshook 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/README.md +25 -50
  2. package/README.zh.md +25 -48
  3. package/dist/AntiCheatDetector-CGVGNfy5.mjs +1 -0
  4. package/dist/CacheAdapters-CdAxBmVW.mjs +1 -0
  5. package/dist/CodeInjector-BlgyqTOk.mjs +1 -0
  6. package/dist/ConsoleMonitor-Dkqc0HNi.mjs +490 -0
  7. package/dist/DOMInspector-BYY_EJ0C.mjs +95 -0
  8. package/dist/DarwinAPI-DC4HGGLl.mjs +1 -0
  9. package/dist/DetailedDataManager-BniBJlVv.mjs +1 -0
  10. package/dist/EventBus-DgciURGg.mjs +1 -0
  11. package/dist/EvidenceGraphBridge-BIfgB7HP.mjs +1 -0
  12. package/dist/ExtensionManager-erMpqcLk.mjs +1 -0
  13. package/dist/FingerprintManager-N7BZqjxP.mjs +1 -0
  14. package/dist/HardwareBreakpoint-OcJqNFVc.mjs +1 -0
  15. package/dist/HeapAnalyzer-CqAxZzeS.mjs +1 -0
  16. package/dist/{HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs → HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs} +66 -101
  17. package/dist/InstrumentationSession-DxXs0sCp.mjs +1 -0
  18. package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +1 -0
  19. package/dist/MemoryController-BaqstM5w.mjs +2 -0
  20. package/dist/MemoryScanSession-CaxAjZJf.mjs +1 -0
  21. package/dist/MemoryScanner-BLYnMJy6.mjs +1 -0
  22. package/dist/NativeMemoryManager.impl-CI554XbY.mjs +1 -0
  23. package/dist/NativeMemoryManager.utils-DM4NC3FE.mjs +1 -0
  24. package/dist/PEAnalyzer-DJyaJTQJ.mjs +1 -0
  25. package/dist/PageController-D9jVkH0i.mjs +1 -0
  26. package/dist/PointerChainEngine-5nF9eNlu.mjs +1 -0
  27. package/dist/PrerequisiteError-Bl3dK8XA.mjs +1 -0
  28. package/dist/ProcessRegistry-Hf12LlR9.mjs +1 -0
  29. package/dist/ResponseBuilder-B2lu4KEl.mjs +1 -0
  30. package/dist/ReverseEvidenceGraph-B931HeoW.mjs +2 -0
  31. package/dist/ScriptManager-fgqiALgj.mjs +7 -0
  32. package/dist/Speedhack-l6s8L2Qw.mjs +1 -0
  33. package/dist/StealthVerifier-Dhbj4B4P.mjs +1 -0
  34. package/dist/StructureAnalyzer-A-WamfYE.mjs +2 -0
  35. package/dist/ToolCatalog-D_IKl1Hu.mjs +1 -0
  36. package/dist/ToolError-DWU_z7gp.mjs +1 -0
  37. package/dist/ToolProbe-xsfALmN3.mjs +1 -0
  38. package/dist/ToolRegistry-B0Zs-phN.mjs +1 -0
  39. package/dist/ToolRouter.policy-CFHoN_Lw.mjs +4 -0
  40. package/dist/TraceRecorder-Dd8jLXpi.mjs +272 -0
  41. package/dist/VersionDetector-DMoUWyNm.mjs +9 -0
  42. package/dist/Win32API-Bhi5xFBe.mjs +1 -0
  43. package/dist/Win32Debug-CQteFL4F.mjs +1 -0
  44. package/dist/WorkflowEngine-CxEp2WXH.mjs +1 -0
  45. package/dist/analysis-BuR-NgX8.mjs +5 -0
  46. package/dist/{antidebug-BRKeyt27.mjs → antidebug-BOTZH6-0.mjs} +8 -259
  47. package/dist/artifactRetention-NBdncOEW.mjs +1 -0
  48. package/dist/artifacts-B5xQuEa_.mjs +1 -0
  49. package/dist/authorization-schema-B40obG1A.mjs +1 -0
  50. package/dist/betterSqlite3-CGaxz4AX.mjs +1 -0
  51. package/dist/binary-instrument-Cf9qqLlM.mjs +7 -0
  52. package/dist/bind-helpers-BlAOQrFQ.mjs +1 -0
  53. package/dist/boringssl-inspector-BST5vtKx.mjs +2 -0
  54. package/dist/browser-C4Le3xqA.mjs +11 -0
  55. package/dist/capabilities-DbYCv-HF.mjs +1 -0
  56. package/dist/chunk-C_pMuVsO.mjs +1 -0
  57. package/dist/collector-CKO8RPK8.mjs +1 -0
  58. package/dist/concurrency-CcK46d0h.mjs +1 -0
  59. package/dist/constants-Cp6hBrrx.mjs +1 -0
  60. package/dist/coordination-BbijHEHH.mjs +1 -0
  61. package/dist/debugger-CRJq_krh.mjs +1 -0
  62. package/dist/definitions-BGobEDQa.mjs +1 -0
  63. package/dist/definitions-BGwNSkVm.mjs +1 -0
  64. package/dist/definitions-BbxOUiP-.mjs +1 -0
  65. package/dist/definitions-CCP9gphV.mjs +1 -0
  66. package/dist/definitions-CIO9O-Sw.mjs +1 -0
  67. package/dist/definitions-CYFbewnd.mjs +1 -0
  68. package/dist/definitions-CdWEuIkI.mjs +1 -0
  69. package/dist/definitions-CoQFbggH.mjs +1 -0
  70. package/dist/definitions-CuJRsJ6N.mjs +1 -0
  71. package/dist/definitions-DI9YXsJk.mjs +1 -0
  72. package/dist/definitions-DJklW2sS.mjs +1 -0
  73. package/dist/definitions-DZ8uKusP.mjs +1 -0
  74. package/dist/definitions-Dds_zrWx.mjs +1 -0
  75. package/dist/definitions-Dgrg7f3D.mjs +1 -0
  76. package/dist/definitions-DtE0XLrT.mjs +1 -0
  77. package/dist/definitions-LaYTuwQd.mjs +26 -0
  78. package/dist/definitions-NoVp_9Pm.mjs +1 -0
  79. package/dist/definitions-OvGsfxdt.mjs +1 -0
  80. package/dist/definitions-jXPaVy4P.mjs +1 -0
  81. package/dist/encoding-DGcr6Aj_.mjs +2 -0
  82. package/dist/ensure-browser-core-Buls24LQ.mjs +1 -0
  83. package/dist/evidence-graph-bridge-B0yhGPcs.mjs +1 -0
  84. package/dist/factory-Cx_1LorX.mjs +1 -0
  85. package/dist/flat-target-session-CO5g78k3.mjs +1 -0
  86. package/dist/formatAddress-C7j2fDlM.mjs +1 -0
  87. package/dist/graphql-HLf3MS8H.mjs +62 -0
  88. package/dist/handlers-BLMa4X7l.mjs +54 -0
  89. package/dist/handlers-BP12ZsWc.mjs +4 -0
  90. package/dist/handlers-BZoPla6E.mjs +1 -0
  91. package/dist/handlers-BggKiVx9.mjs +2 -0
  92. package/dist/handlers-D3iev8g1.mjs +1 -0
  93. package/dist/handlers-D49r1-1P.mjs +1 -0
  94. package/dist/handlers-DCE45Ww8.mjs +2 -0
  95. package/dist/handlers-DW5AbYs5.mjs +5 -0
  96. package/dist/handlers-De5u62Ga2.mjs +1 -0
  97. package/dist/handlers-DmQzIc44.mjs +31 -0
  98. package/dist/handlers-DnJRGp7t.mjs +302 -0
  99. package/dist/handlers-Dv_runVv.mjs +2 -0
  100. package/dist/handlers-S9Ws0IGy.mjs +2 -0
  101. package/dist/{handlers-Dz9PYsCa.mjs → handlers-pVNpaw4A.mjs} +118 -904
  102. package/dist/handlers.impl-CD2_kOcC.mjs +1 -0
  103. package/dist/hooks-DDKppogd.mjs +600 -0
  104. package/dist/index.mjs +12 -5235
  105. package/dist/logger-sBC6IdRT.mjs +1 -0
  106. package/dist/maintenance-CutEO84j.mjs +1 -0
  107. package/dist/manifest-BFGxlDRh.mjs +123 -0
  108. package/dist/manifest-BPuE6oH2.mjs +1 -0
  109. package/dist/manifest-BXry5N09.mjs +1 -0
  110. package/dist/manifest-BeP_zJGb2.mjs +1 -0
  111. package/dist/manifest-C0g67k6U.mjs +1 -0
  112. package/dist/manifest-C1nZkTkO.mjs +1 -0
  113. package/dist/manifest-C7qV1z7F.mjs +1 -0
  114. package/dist/manifest-CDeUZGUZ.mjs +1 -0
  115. package/dist/manifest-CDiCtaQT.mjs +1 -0
  116. package/dist/manifest-CFn0359q2.mjs +1 -0
  117. package/dist/manifest-CGq4NpqH2.mjs +1 -0
  118. package/dist/manifest-CJMGt7Qy.mjs +1 -0
  119. package/dist/manifest-CRIJq4Hs.mjs +1 -0
  120. package/dist/manifest-C_hEIjSx.mjs +1 -0
  121. package/dist/manifest-CeQmtQOY.mjs +1 -0
  122. package/dist/manifest-Cq0j7GZt.mjs +1 -0
  123. package/dist/manifest-CtPmHAdn.mjs +1 -0
  124. package/dist/manifest-Cx2IVMUY.mjs +1 -0
  125. package/dist/manifest-D16xPXro.mjs +1 -0
  126. package/dist/manifest-D44TaRJU.mjs +1 -0
  127. package/dist/manifest-D610kxZr.mjs +2 -0
  128. package/dist/manifest-DC-SMF6b.mjs +1 -0
  129. package/dist/manifest-DD3rtxvV.mjs +1 -0
  130. package/dist/manifest-DKUorv5M.mjs +1 -0
  131. package/dist/manifest-DMJlcsTR.mjs +1 -0
  132. package/dist/manifest-DWUUWBz0.mjs +1 -0
  133. package/dist/manifest-De-6Wf2R.mjs +1 -0
  134. package/dist/manifest-Dgh0uDW-.mjs +1 -0
  135. package/dist/manifest-Dm0o3i2U.mjs +1 -0
  136. package/dist/manifest-DsVh7Y4U.mjs +1 -0
  137. package/dist/manifest-DtEFSRaq.mjs +1 -0
  138. package/dist/manifest-H-EpAyZQ.mjs +1 -0
  139. package/dist/manifest-ais9Afrw.mjs +1 -0
  140. package/dist/manifest-tmb54wmA.mjs +1 -0
  141. package/dist/manifest-yu2xiQqe.mjs +1 -0
  142. package/dist/manifest-zrbrpKCC.mjs +1 -0
  143. package/dist/matchesWildcardPattern-BGqLSmEs.mjs +1 -0
  144. package/dist/modules-p-PUNv9r.mjs +332 -0
  145. package/dist/mojo-ipc-VGlv3Qyp.mjs +9 -0
  146. package/dist/network-BjZ1Y-GB.mjs +7 -0
  147. package/dist/outputPaths-BonGThuc.mjs +2 -0
  148. package/dist/parse-args-Cuk7-xUt.mjs +1 -0
  149. package/dist/platform-C446Lf97.mjs +93 -0
  150. package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +1 -0
  151. package/dist/process-C9f2A5zk.mjs +962 -0
  152. package/dist/proxy-CvRepxgV.mjs +1 -0
  153. package/dist/registry-DUHIPE-v.mjs +1 -0
  154. package/dist/response-C7rKQst4.mjs +1 -0
  155. package/dist/search-defaults-D2bY-rzH.mjs +1 -0
  156. package/dist/server/plugin-api.mjs +1 -293
  157. package/dist/shared-state-board-Cyg-xh_k.mjs +1 -0
  158. package/dist/sourcemap-D6Q1UuAp.mjs +1 -0
  159. package/dist/ssrf-policy-T96MR3r6.mjs +1 -0
  160. package/dist/streaming-CTX58tbb.mjs +1 -0
  161. package/dist/tool-builder-CI9914Tf.mjs +1 -0
  162. package/dist/transform-Cv9P2vVD.mjs +103 -0
  163. package/dist/types-CuyefmGT.mjs +1 -0
  164. package/dist/types-DtThH00r.mjs +1 -0
  165. package/dist/wasm-DaJa8J0V.mjs +174 -0
  166. package/dist/webcrack-CsLLJIs9.mjs +46 -0
  167. package/dist/workflow-CYIXtrWD.mjs +101 -0
  168. package/package.json +50 -78
  169. package/dist/AntiCheatDetector-CqGDXmfc.mjs +0 -350
  170. package/dist/CacheAdapters-jJFy20G-.mjs +0 -80
  171. package/dist/CodeInjector-BdjRfNx7.mjs +0 -150
  172. package/dist/ConsoleMonitor-DykL3IAw.mjs +0 -2269
  173. package/dist/DarwinAPI-ETyy0xyo.mjs +0 -363
  174. package/dist/DetailedDataManager-HT49OrvF.mjs +0 -217
  175. package/dist/EventBus-DFKvADm3.mjs +0 -141
  176. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +0 -153
  177. package/dist/ExtensionManager-BDMsY2Dz.mjs +0 -721
  178. package/dist/FingerprintManager-BN4UQWnX.mjs +0 -96
  179. package/dist/HardwareBreakpoint-Cc2AFq1Y.mjs +0 -239
  180. package/dist/HeapAnalyzer-DruMgsgj.mjs +0 -284
  181. package/dist/InstrumentationSession-DLH0vd-z.mjs +0 -244
  182. package/dist/MemoryController-CMtviNW_.mjs +0 -167
  183. package/dist/MemoryScanSession-ITgb_NMi.mjs +0 -278
  184. package/dist/MemoryScanner-CiL7Z3ey.mjs +0 -428
  185. package/dist/NativeMemoryManager.impl-D9Lkovvn.mjs +0 -485
  186. package/dist/NativeMemoryManager.utils-BBlAixF5.mjs +0 -165
  187. package/dist/PEAnalyzer-DMQ44gen.mjs +0 -385
  188. package/dist/PageController-BPJNqqBN.mjs +0 -431
  189. package/dist/PointerChainEngine-K7wN8Z-w.mjs +0 -325
  190. package/dist/PrerequisiteError-TuyZIs6n.mjs +0 -20
  191. package/dist/ProcessRegistry-zGg12QbE.mjs +0 -74
  192. package/dist/ResponseBuilder-CJXWmWNw.mjs +0 -143
  193. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +0 -269
  194. package/dist/ScriptManager-ZuWD-0Jg.mjs +0 -3003
  195. package/dist/Speedhack-D-z0umeT.mjs +0 -156
  196. package/dist/StealthVerifier-BWmPgQsv.mjs +0 -135
  197. package/dist/StructureAnalyzer-Cav5AVSL.mjs +0 -429
  198. package/dist/ToolCatalog-5OJdMiF0.mjs +0 -582
  199. package/dist/ToolError-jh9whhMd.mjs +0 -15
  200. package/dist/ToolProbe-DbCFGyrg.mjs +0 -45
  201. package/dist/ToolRegistry-B9krbTtI.mjs +0 -180
  202. package/dist/ToolRouter.policy-BGDAGyeH.mjs +0 -344
  203. package/dist/TraceRecorder-B41Z5XBj.mjs +0 -1286
  204. package/dist/VersionDetector-K3V4vGsw.mjs +0 -104
  205. package/dist/Win32API-C2kjj0ze.mjs +0 -346
  206. package/dist/Win32Debug-CKrGOTpo.mjs +0 -274
  207. package/dist/WorkflowEngine-DJ6M4opp.mjs +0 -569
  208. package/dist/analysis-BHeJW2Nb.mjs +0 -1234
  209. package/dist/artifactRetention-CPXkUJXp.mjs +0 -598
  210. package/dist/artifacts-DkfosXH3.mjs +0 -59
  211. package/dist/authorization-schema-DRqyJMSk.mjs +0 -31
  212. package/dist/betterSqlite3-DLSBZodi.mjs +0 -74
  213. package/dist/binary-instrument--V3MAhJ4.mjs +0 -971
  214. package/dist/bind-helpers-ClV34xdn.mjs +0 -42
  215. package/dist/boringssl-inspector-Bo_LOLaS.mjs +0 -180
  216. package/dist/browser-Dx3_S2cG.mjs +0 -4369
  217. package/dist/capabilities-CcHlvWgK.mjs +0 -33
  218. package/dist/chunk-CjcI7cDX.mjs +0 -15
  219. package/dist/concurrency-Drev_Vz9.mjs +0 -41
  220. package/dist/constants-CDZLOoVv.mjs +0 -534
  221. package/dist/coordination-DgItD9DL.mjs +0 -259
  222. package/dist/debugger-RS3RSAqs.mjs +0 -1288
  223. package/dist/definitions-BEoYofW5.mjs +0 -47
  224. package/dist/definitions-BRaefg3u.mjs +0 -365
  225. package/dist/definitions-BbkvZkiv.mjs +0 -96
  226. package/dist/definitions-BtWSHJ3o.mjs +0 -17
  227. package/dist/definitions-C1gCHO0i.mjs +0 -43
  228. package/dist/definitions-CDOg_b-l.mjs +0 -138
  229. package/dist/definitions-CVPD9hzZ.mjs +0 -54
  230. package/dist/definitions-Cea8Lgl7.mjs +0 -94
  231. package/dist/definitions-DAgIyjxM.mjs +0 -10
  232. package/dist/definitions-DJA27nsL.mjs +0 -66
  233. package/dist/definitions-DKPFU3LW.mjs +0 -25
  234. package/dist/definitions-DPRpZQ96.mjs +0 -47
  235. package/dist/definitions-DUE5gmdn.mjs +0 -18
  236. package/dist/definitions-DYVjOtxa.mjs +0 -26
  237. package/dist/definitions-DcYLVLCo.mjs +0 -37
  238. package/dist/definitions-Pp5LI2H4.mjs +0 -27
  239. package/dist/definitions-j9KdHVNR.mjs +0 -14
  240. package/dist/definitions-uzkjBwa7.mjs +0 -258
  241. package/dist/definitions-va-AnLuQ.mjs +0 -28
  242. package/dist/encoding-DJeqHmpd.mjs +0 -1079
  243. package/dist/evidence-graph-bridge-DcYizFk2.mjs +0 -136
  244. package/dist/factory-C90tBff6.mjs +0 -575
  245. package/dist/flat-target-session-Dgax2Cy3.mjs +0 -29
  246. package/dist/formatAddress-nnMvEohD.mjs +0 -17
  247. package/dist/graphql-CoHrhweh.mjs +0 -1197
  248. package/dist/handlers-4jmR0nMs.mjs +0 -898
  249. package/dist/handlers-BAHPxcch.mjs +0 -789
  250. package/dist/handlers-BOs9b907.mjs +0 -2600
  251. package/dist/handlers-BWXEy6ef.mjs +0 -917
  252. package/dist/handlers-Bndn6QvE.mjs +0 -111
  253. package/dist/handlers-BqC4bD4s.mjs +0 -681
  254. package/dist/handlers-BtYq60bM2.mjs +0 -276
  255. package/dist/handlers-BzgcB4iv.mjs +0 -799
  256. package/dist/handlers-CRyRWj2b.mjs +0 -859
  257. package/dist/handlers-CVv2H1uq.mjs +0 -592
  258. package/dist/handlers-Dl5a7JS4.mjs +0 -572
  259. package/dist/handlers-Dx2d7jt7.mjs +0 -2537
  260. package/dist/handlers-HujRKC3b.mjs +0 -661
  261. package/dist/handlers.impl-XWXkQfyi.mjs +0 -807
  262. package/dist/hooks-B1B8NRHL.mjs +0 -898
  263. package/dist/logger-Dh_xb7_2.mjs +0 -93
  264. package/dist/maintenance-PRMkLVRW.mjs +0 -835
  265. package/dist/manifest-67Bok-Si.mjs +0 -58
  266. package/dist/manifest-6lNTMZAB2.mjs +0 -87
  267. package/dist/manifest-B2duEHiH.mjs +0 -90
  268. package/dist/manifest-B6EY9Vm8.mjs +0 -57
  269. package/dist/manifest-B6nKSbyY.mjs +0 -95
  270. package/dist/manifest-BL8AQNPF.mjs +0 -106
  271. package/dist/manifest-BSZvJJmV.mjs +0 -47
  272. package/dist/manifest-BU7qzUyX.mjs +0 -418
  273. package/dist/manifest-Bl62e8WK.mjs +0 -49
  274. package/dist/manifest-Bo5cXjdt.mjs +0 -82
  275. package/dist/manifest-BpS4gtUK.mjs +0 -1347
  276. package/dist/manifest-Bv65_e2W.mjs +0 -101
  277. package/dist/manifest-BytNIF4Z.mjs +0 -117
  278. package/dist/manifest-C-xtsjS3.mjs +0 -81
  279. package/dist/manifest-CDYl7OhA.mjs +0 -66
  280. package/dist/manifest-CRZ3xmkD.mjs +0 -61
  281. package/dist/manifest-CoW6u4Tp.mjs +0 -132
  282. package/dist/manifest-Cq5zN_8A.mjs +0 -50
  283. package/dist/manifest-D7YZM_2e.mjs +0 -194
  284. package/dist/manifest-DE_VrAeQ.mjs +0 -314
  285. package/dist/manifest-DGsXSCpT.mjs +0 -39
  286. package/dist/manifest-DJ2vfEuW.mjs +0 -156
  287. package/dist/manifest-DPXDYhEu.mjs +0 -80
  288. package/dist/manifest-Dd4fQb0a.mjs +0 -322
  289. package/dist/manifest-Deq6opGg.mjs +0 -223
  290. package/dist/manifest-DfJTafJK.mjs +0 -37
  291. package/dist/manifest-DgOdgN_j.mjs +0 -50
  292. package/dist/manifest-DlbMW4v4.mjs +0 -47
  293. package/dist/manifest-DmVfbH0w.mjs +0 -374
  294. package/dist/manifest-Dog6Ddjr.mjs +0 -109
  295. package/dist/manifest-DvgU5FWb.mjs +0 -58
  296. package/dist/manifest-HsfDBs7j.mjs +0 -50
  297. package/dist/manifest-I8oQHvCG.mjs +0 -186
  298. package/dist/manifest-NvH_a-av.mjs +0 -786
  299. package/dist/manifest-cEJU1v0Z.mjs +0 -129
  300. package/dist/manifest-wOl5XLB12.mjs +0 -112
  301. package/dist/modules-tZozf0LQ.mjs +0 -10635
  302. package/dist/mojo-ipc-DXNEXEqb.mjs +0 -640
  303. package/dist/network-CPVvwvFg.mjs +0 -3852
  304. package/dist/outputPaths-um7lCRY3.mjs +0 -1141
  305. package/dist/parse-args-B4cY5Vx5.mjs +0 -39
  306. package/dist/platform-CYeFoTWp.mjs +0 -2161
  307. package/dist/process-BTbgcVc6.mjs +0 -1306
  308. package/dist/proxy-r8YN6nP1.mjs +0 -192
  309. package/dist/registry-Bl8ZQW61.mjs +0 -34
  310. package/dist/response-CWhh2aLo.mjs +0 -34
  311. package/dist/shared-state-board-BoZnSoj-.mjs +0 -586
  312. package/dist/sourcemap-BIDHUVXy.mjs +0 -934
  313. package/dist/ssrf-policy-Dsqd-DTX.mjs +0 -166
  314. package/dist/streaming-Dal6utPp.mjs +0 -725
  315. package/dist/tool-builder-BHJp32mV.mjs +0 -186
  316. package/dist/transform-DRVgGG90.mjs +0 -1011
  317. package/dist/types-Bx92KJfT.mjs +0 -4
  318. package/dist/types-DDBWs9UP.mjs +0 -37
  319. package/dist/wasm-BYx5UOeG.mjs +0 -1044
  320. package/dist/webcrack-Be0_FccV.mjs +0 -747
  321. package/dist/workflow-BpuKEtvn.mjs +0 -725
@@ -0,0 +1,7 @@
1
+ import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./matchesWildcardPattern-BGqLSmEs.mjs";import{setImmediate as n}from"node:timers/promises";const r=e=>e instanceof Error?e.message:String(e),i=e=>typeof e==`object`&&e?e:null,a=e=>typeof e==`function`?e:null,o=(e,t)=>{let n=i(e),r=n?.default;return a(i(r)?.default)??a(r)??a(n?.[t])??a(e)};async function s(t,n,i,a={}){let{maxDepth:s=3,maxSize:c=500,includeComments:l=!0}=a,u=await t.getScriptSource(n);if(!u?.source)throw Error(`Script not found: ${n}`);let d,f,p,m;try{d=await import(`@babel/parser`);let e=o(await import(`@babel/traverse`),`traverse`);if(typeof e!=`function`)throw Error(`Invalid @babel/traverse export shape`);f=e;let t=o(await import(`@babel/generator`),`generate`);if(typeof t!=`function`)throw Error(`Invalid @babel/generator export shape`);p=t,m=await import(`@babel/types`)}catch(e){throw Error(`Failed to load Babel dependencies. Please install: npm install @babel/parser @babel/traverse @babel/generator @babel/types\nError: ${r(e)}`,{cause:e})}let h;try{h=d.parse(u.source,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){throw Error(`Failed to parse script ${n}: ${r(e)}`,{cause:e})}let g=new Map,_={},v=e=>{let t=new Set;return e.traverse({CallExpression(e){m.isIdentifier(e.node.callee)&&t.add(e.node.callee.name)}}),Array.from(t)};f(h,{FunctionDeclaration(e){let t=e.node.id?.name;if(!t)return;let n=p(e.node,{comments:l}).code,r=v(e);g.set(t,{name:t,code:n,startLine:e.node.loc?.start.line||0,endLine:e.node.loc?.end.line||0,dependencies:r,size:n.length}),_[t]=r},VariableDeclarator(e){if(m.isIdentifier(e.node.id)&&(m.isFunctionExpression(e.node.init)||m.isArrowFunctionExpression(e.node.init))){let t=e.node.id.name,n=p(e.node,{comments:l}).code,r=v(e);g.set(t,{name:t,code:n,startLine:e.node.loc?.start.line||0,endLine:e.node.loc?.end.line||0,dependencies:r,size:n.length}),_[t]=r}}});let y=new Set,b=[i],x=0;for(;b.length>0&&x<s;){let e=b.shift();if(y.has(e))continue;let t=g.get(e);if(t){y.add(e);for(let e of t.dependencies)!y.has(e)&&g.has(e)&&b.push(e);x++}}let S=Array.from(y).map(e=>g.get(e)).filter(Boolean),C=S.map(e=>e.code).join(`
2
+
3
+ `),w=C.length;return w>c*1024&&e.warn(`Extracted code size (${(w/1024).toFixed(2)}KB) exceeds limit (${c}KB)`),e.info(`extractFunctionTree: ${i} - extracted ${S.length} functions (${(w/1024).toFixed(2)}KB)`),{mainFunction:i,code:C,functions:S,callGraph:_,totalSize:w,extractedCount:S.length}}var c=class r{collector;static SOURCE_LOAD_BATCH_SIZE=8;static SEARCH_LINE_YIELD_INTERVAL=250;static SEARCH_SCRIPT_YIELD_INTERVAL=10;cdpSession=null;scripts=new Map;scriptsByUrl=new Map;initialized=!1;initPromise;keywordIndex=new Map;scriptChunks=new Map;CHUNK_SIZE=100*1024;MAX_KEYWORD_INDEX_ENTRIES=5e4;CDP_HEALTH_PROBE_INTERVAL_MS=3e4;lastHealthProbeAt=0;constructor(e){this.collector=e}async init(){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){let t=await this.collector.getActivePage();this.cdpSession=await t.createCDPSession(),this.cdpSession.on(`Debugger.scriptParsed`,t=>{let n={scriptId:t.scriptId,url:t.url,startLine:t.startLine,startColumn:t.startColumn,endLine:t.endLine,endColumn:t.endColumn,sourceLength:t.length};this.scripts.set(t.scriptId,n),t.url&&(this.scriptsByUrl.has(t.url)||this.scriptsByUrl.set(t.url,[]),this.scriptsByUrl.get(t.url).push(n)),e.debug(`Script parsed: ${t.url||`inline`} (${t.scriptId})`)}),await this.cdpSession.send(`Debugger.enable`),this.initialized=!0,this.lastHealthProbeAt=Date.now(),e.info(`ScriptManager initialized`)}async loadScriptSourceInternal(t){if(t.source)return!0;try{let{scriptSource:e}=await this.cdpSession.send(`Debugger.getScriptSource`,{scriptId:t.scriptId});return t.source=e,t.sourceLength=e.length,this.buildKeywordIndex(t.scriptId,t.url,e),this.chunkScript(t.scriptId,e),!0}catch(n){return e.warn(`Failed to get source for script ${t.scriptId}:`,n),!1}}async enable(){return this.init()}async ensureCdpSession(){if(!this.cdpSession){await this.init();return}if(!this.initialized){await this.init();return}let t=Date.now();if(!(t-this.lastHealthProbeAt<this.CDP_HEALTH_PROBE_INTERVAL_MS))try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]),this.lastHealthProbeAt=t}catch{e.warn(`ScriptManager CDP session unresponsive (zombie), reinitializing...`),this.cdpSession=null,this.initialized=!1,this.lastHealthProbeAt=0,this.scripts.clear(),this.scriptsByUrl.clear(),this.keywordIndex.clear(),this.scriptChunks.clear(),await this.init()}}async getAllScripts(t=!1,i=1e3){await this.ensureCdpSession();let a=Array.from(this.scripts.values());a.length>i&&e.warn(`Found ${a.length} scripts, limiting to ${i}. Increase maxScripts parameter if needed.`);let o=a.slice(0,i);if(t){e.warn(`Loading source code for ${o.length} scripts. This may use significant memory.`);let t=0,i=0,a=o.filter(e=>!e.source);for(let s=0;s<a.length;s+=r.SOURCE_LOAD_BATCH_SIZE){let c=a.slice(s,s+r.SOURCE_LOAD_BATCH_SIZE),l=await Promise.allSettled(c.map(async n=>{await this.loadScriptSourceInternal(n)?(t++,t%10==0&&e.debug(`Loaded ${t}/${o.length} scripts...`)):i++}));for(let e of l)e.status===`rejected`&&i++;await n()}e.info(`getAllScripts: ${o.length} scripts (loaded: ${t}, failed: ${i})`)}else e.info(`getAllScripts: ${o.length} scripts (source not included)`);return o}async getScriptSource(n,r){if(!n&&!r)throw Error(`Either scriptId or url parameter must be provided`);await this.ensureCdpSession();let i;if(n)i=this.scripts.get(n);else if(r){for(let[e,n]of this.scriptsByUrl.entries())if(t(e,r)){i=n[0];break}}return i?!i.source&&!await this.loadScriptSourceInternal(i)?(e.error(`Failed to get script source for ${i.scriptId}`),null):(e.info(`getScriptSource: ${i.url||`inline`} (${i.sourceLength} bytes)`),i):(e.warn(`Script not found: ${n||r}`),null)}async findScriptsByUrl(n){await this.ensureCdpSession();let r=[];for(let[e,i]of this.scriptsByUrl.entries())t(e,n)&&r.push(...i);return e.info(`findScriptsByUrl: ${n} - found ${r.length} scripts`),r}clearCache(){this.clear()}async searchInScripts(t,i={}){await this.ensureCdpSession();let{isRegex:a=!1,caseSensitive:o=!1,contextLines:s=3,maxMatches:c=100}=i,l=a?new RegExp(t,o?`g`:`gi`):new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),o?`g`:`gi`),u=[],d=await this.getAllScripts(!0,500);for(let[e,t]of d.entries()){if(!t.source)continue;if(u.length>=c)break;let i=t.source.split(`
4
+ `);for(let e=0;e<i.length;e++){let a=i[e];if(!a)continue;let o=Array.from(a.matchAll(l));for(let n of o){if(u.length>=c)break;let r=Math.max(0,e-s),o=Math.min(i.length-1,e+s),l=i.slice(r,o+1).join(`
5
+ `);if(l.length>2e3){let e=n.index||0,t=Math.max(0,e-100),r=Math.min(a.length,e+100);l=(t>0?`...`:``)+a.substring(t,r)+(r<a.length?`...`:``)}u.push({scriptId:t.scriptId,url:t.url||`inline`,line:e+1,column:n.index||0,matchText:n[0],context:l})}(e+1)%r.SEARCH_LINE_YIELD_INTERVAL===0&&await n()}(e+1)%r.SEARCH_SCRIPT_YIELD_INTERVAL===0&&await n()}return e.info(`searchInScripts: "${t}" - found ${u.length} matches`),{keyword:t,totalMatches:u.length,matches:u}}async extractFunctionTree(e,t,n={}){return s(this,e,t,n)}clear(){this.scripts.clear(),this.scriptsByUrl.clear(),this.keywordIndex.clear(),this.scriptChunks.clear(),e.info(` ScriptManager cleared - ready for new website`)}async close(){if(this.initPromise=void 0,this.clear(),this.cdpSession){try{await this.cdpSession.send(`Debugger.disable`),await this.cdpSession.detach(),e.info(`CDP session closed`)}catch(t){e.warn(`Failed to close CDP session:`,t)}this.cdpSession=null}this.initialized=!1,e.info(` ScriptManager closed`)}getStats(){let e=0;for(let t of this.scriptChunks.values())e+=t.length;return{totalScripts:this.scripts.size,totalUrls:this.scriptsByUrl.size,indexedKeywords:this.keywordIndex.size,totalChunks:e}}buildKeywordIndex(t,n,r){let i=r.split(`
6
+ `),a=/\b[a-zA-Z_$][a-zA-Z0-9_$]{2,}\b/g;for(let e=0;e<i.length;e++){let r=i[e];if(!r)continue;let o=Array.from(r.matchAll(a));for(let a of o){let o=a[0].toLowerCase(),s=Math.max(0,e-3),c=Math.min(i.length-1,e+3),l=i.slice(s,c+1).join(`
7
+ `);if(l.length>1e3){let e=a.index||0,t=Math.max(0,e-50),n=Math.min(r.length,e+50);l=(t>0?`...`:``)+r.substring(t,n)+(n<r.length?`...`:``)}let u={scriptId:t,url:n,line:e+1,column:a.index||0,context:l};this.keywordIndex.has(o)||this.keywordIndex.set(o,[]),this.keywordIndex.get(o).push(u)}}if(e.debug(` Indexed ${this.keywordIndex.size} keywords for ${n}`),this.keywordIndex.size>this.MAX_KEYWORD_INDEX_ENTRIES){let t=this.keywordIndex.size-this.MAX_KEYWORD_INDEX_ENTRIES,n=0;for(let[e]of this.keywordIndex){if(n>=t)break;this.keywordIndex.delete(e),n++}e.debug(` Keyword index pruned ${n} entries (cap: ${this.MAX_KEYWORD_INDEX_ENTRIES})`)}}chunkScript(t,n){let r=[],i=0,a=0;for(;i<n.length;){let e=n.substring(i,i+this.CHUNK_SIZE);r.push({scriptId:t,chunkIndex:a,content:e,size:e.length}),i+=this.CHUNK_SIZE,a++}this.scriptChunks.set(t,r),e.debug(` Chunked script ${t} into ${r.length} chunks`)}getScriptChunk(e,t){let n=this.scriptChunks.get(e);if(!n||t>=n.length)return null;let r=n[t];return r?r.content:null}async searchInScriptsEnhanced(t,n={}){let{isRegex:r=!1,caseSensitive:i=!1,maxMatches:a=100}=n,o=i?t:t.toLowerCase(),s=[];if(r)return{...await this.searchInScripts(t,n),searchMethod:`regex`};for(let[e,t]of this.keywordIndex.entries()){if(e.includes(o)){for(let n of t)if(s.push({scriptId:n.scriptId,url:n.url,line:n.line,column:n.column,matchText:e,context:n.context}),s.length>=a)break}if(s.length>=a)break}return e.info(` Enhanced search (indexed) found ${s.length} matches for "${t}"`),{keyword:t,totalMatches:s.length,matches:s,searchMethod:`indexed`}}};export{c as t};
@@ -0,0 +1 @@
1
+ import{_ as e,b as t,c as n,d as r,f as i,l as a,m as o,o as s,p as c,t as l,u}from"./Win32API-Bhi5xFBe.mjs";import{l as d}from"./Win32Debug-CQteFL4F.mjs";var f=class{states=new Map;async apply(r,o){this.states.has(r)&&await this.remove(r);let c=t(r,!0),d=[],f=[];try{let t=s(`kernel32.dll`);if(t===0n)throw Error(`Cannot find kernel32.dll`);let l=i(c,0n,4096,a.COMMIT|a.RESERVE,u.EXECUTE_READWRITE);if(l===0n)throw Error(`VirtualAllocEx failed for speedhack shared memory`);let p=Buffer.alloc(8);p.writeDoubleLE(o,0),e(c,l,p);let m=Buffer.alloc(8,0);e(c,l+8n,m),e(c,l+16n,m);let h=n(t,`GetTickCount64`);h!==0n&&await this.hookTimeFunction(c,h,l,256n,`gettick64`)&&(d.push(`GetTickCount64`),f.push(`gettick64`));let g=n(t,`QueryPerformanceCounter`);return g!==0n&&await this.hookTimeFunction(c,g,l,512n,`qpc`)&&(d.push(`QueryPerformanceCounter`),f.push(`qpc`)),this.states.set(r,{pid:r,speed:o,hookedApis:d,isActive:!0,allocatedMemory:`0x${l.toString(16).toUpperCase()}`,patchIds:f}),{success:d.length>0,hookedApis:d}}catch(e){throw l(c),e}finally{l(c)}}async setSpeed(n,r){let i=this.states.get(n);if(!i||!i.isActive||!i.allocatedMemory)return!1;let a=BigInt(i.allocatedMemory),o=t(n,!0);try{let t=Buffer.alloc(8);return t.writeDoubleLE(r,0),e(o,a,t),i.speed=r,!0}finally{l(o)}}getSpeed(e){let t=this.states.get(e);return t?.isActive?t.speed:null}async remove(n){let i=this.states.get(n);if(!i)return!1;let s=t(n,!0);try{if(i.allocatedMemory){let t=BigInt(i.allocatedMemory);for(let n=0;n<i.patchIds.length;n++)try{let i=r(s,t+(3072n+BigInt(n*32)),32),a=i.readBigUInt64LE(0),c=i.readUInt32LE(8);if(a!==0n&&c>0&&c<=16){let t=i.subarray(12,12+c),{oldProtect:n}=o(s,a,c,u.EXECUTE_READWRITE);e(s,a,t),d(s,a,c),o(s,a,c,n)}}catch{}c(s,t,0,a.RELEASE)}}finally{l(s)}return i.isActive=!1,this.states.delete(n),!0}isActive(e){return this.states.get(e)?.isActive??!1}listActive(){return Array.from(this.states.values()).filter(e=>e.isActive)}async hookTimeFunction(t,n,i,a,s){try{let s=r(t,n,14),c=i+a;e(t,c,s);let l=n+14n,f=this.buildAbsoluteJump(l);e(t,c+14n,Buffer.from(f));let p=this.buildAbsoluteJump(c),{oldProtect:m}=o(t,n,14,u.EXECUTE_READWRITE);e(t,n,Buffer.from(p)),d(t,n,14),o(t,n,14,m);let h=this.states.size,g=3072n+BigInt(h*32),_=Buffer.alloc(32);return _.writeBigUInt64LE(n,0),_.writeUInt32LE(14,8),s.copy(_,12),e(t,i+g,_),d(t,c,32),!0}catch{return!1}}buildAbsoluteJump(e){let t=Buffer.alloc(14);return t[0]=255,t[1]=37,t.writeUInt32LE(0,2),t.writeBigUInt64LE(e,6),Array.from(t)}};const p=new f;export{f as Speedhack,p as speedhack};
@@ -0,0 +1 @@
1
+ import"rebrowser-puppeteer-core";var e=class{async verify(e){let t=await e.evaluate(async()=>{let e=[],t=navigator.webdriver;e.push({name:`navigator.webdriver`,passed:t===void 0||t===!1,expected:`undefined`,actual:String(t)});let n=window,r=typeof n.chrome==`object`&&n.chrome!==null;e.push({name:`window.chrome`,passed:r,expected:`object`,actual:typeof n.chrome});let i=r?n.chrome.app:null,a=i&&typeof i==`object`&&`isInstalled`in i;e.push({name:`chrome.app.isInstalled`,passed:!!a,expected:`exists (false)`,actual:a?String(i.isInstalled):`missing`});let o=navigator.plugins?.length??0;e.push({name:`navigator.plugins`,passed:o>=3,expected:`>= 3`,actual:String(o)});let s=navigator.languages;e.push({name:`navigator.languages`,passed:s.length>0,expected:`non-empty`,actual:JSON.stringify(s)});let c=navigator.userAgent,l=navigator.platform,u=!0;c.includes(`Windows`)&&!l.includes(`Win`)&&(u=!1),c.includes(`Macintosh`)&&!l.includes(`Mac`)&&(u=!1),c.includes(`Linux`)&&!l.includes(`Linux`)&&(u=!1),e.push({name:`platform/UA consistency`,passed:u,expected:`consistent`,actual:`UA=${c.substring(0,50)}... platform=${l}`});let d=`unavailable`;try{let e=document.createElement(`canvas`).getContext(`webgl`);if(e){let t=e.getExtension(`WEBGL_debug_renderer_info`);t&&(d=e.getParameter(t.UNMASKED_VENDOR_WEBGL)||`empty`)}}catch{d=`error`}e.push({name:`WebGL vendor`,passed:d!==`empty`&&d!==`error`,expected:`non-empty vendor string`,actual:d});let f=Object.keys(document).filter(e=>e.startsWith(`cdc_`)||e.startsWith(`$cdc_`));e.push({name:`cdc_ variables`,passed:f.length===0,expected:`none`,actual:f.length===0?`none`:f.join(`, `)});let p=navigator.hardwareConcurrency??0;e.push({name:`hardwareConcurrency`,passed:p>=4,expected:`>= 4`,actual:String(p)});let m=navigator.deviceMemory;e.push({name:`deviceMemory`,passed:m!==void 0&&m>=4,expected:`>= 4`,actual:String(m??`undefined`)});let h=window.__commandLineAPI;e.push({name:`__commandLineAPI`,passed:h===void 0,expected:`undefined`,actual:typeof h});let g=window.__pwInitScripts;e.push({name:`__pwInitScripts`,passed:g===void 0,expected:`undefined`,actual:typeof g});let _=r&&typeof n.chrome.runtime==`object`?n.chrome.runtime.id:void 0;e.push({name:`chrome.runtime.id`,passed:_===void 0,expected:`undefined`,actual:String(_??`undefined`)});let v=`clean`;try{let e=String(Error(`stealth-check`).stack??``).toLowerCase();(e.includes(`playwright`)||e.includes(`puppeteer`)||e.includes(`__pw`))&&(v=`detected`)}catch{v=`error`}e.push({name:`Error.stack leak`,passed:v===`clean`,expected:`clean`,actual:v});let y=`unsupported`;try{let e=navigator.permissions;if(e?.query){let t=await e.query({name:`notifications`});y=String(t?.state??`unknown`)}}catch{y=`error`}let b=typeof Notification==`object`&&Notification!==null?String(Notification.permission??`unknown`):`unknown`,x=y===`unsupported`||y===`error`||y===b;return e.push({name:`permissions consistency`,passed:x,expected:`matches Notification.permission`,actual:`permissions=${y} notification=${b}`}),e}),n=t.filter(e=>e.passed).length,r=t.length,i=Math.round(n/r*100),a=[];for(let e of t)if(!e.passed)switch(e.name){case`navigator.webdriver`:a.push(`Run stealth_inject to hide navigator.webdriver`);break;case`window.chrome`:a.push(`Run stealth_inject to inject window.chrome object`);break;case`chrome.app.isInstalled`:a.push(`Update stealth scripts to include chrome.app structure`);break;case`navigator.plugins`:a.push(`Run stealth_inject to restore navigator.plugins`);break;case`platform/UA consistency`:a.push(`Run stealth_set_user_agent with matching platform before stealth_inject`);break;case`cdc_ variables`:a.push(`Run stealth_inject to clean up ChromeDriver cdc_ variables`);break;case`__commandLineAPI`:a.push(`Remove leaked Playwright command-line globals before navigation`);break;case`__pwInitScripts`:a.push(`Remove leaked Playwright init-script globals before navigation`);break;case`chrome.runtime.id`:a.push(`Do not expose chrome.runtime.id unless an extension is expected`);break;case`Error.stack leak`:a.push(`Patch stack traces to avoid Playwright or Puppeteer markers`);break;case`permissions consistency`:a.push(`Keep navigator.permissions and Notification.permission in sync`);break;default:a.push(`Fix: ${e.name} — expected ${e.expected}, got ${e.actual}`)}return{passed:n===r,checks:t,score:i,passedCount:n,totalCount:r,recommendations:a}}};export{e as StealthVerifier};
@@ -0,0 +1,2 @@
1
+ import{br as e,xr as t,yr as n}from"./constants-Cp6hBrrx.mjs";import{t as r}from"./factory-Cx_1LorX.mjs";import{t as i}from"./NativeMemoryManager.impl-CI554XbY.mjs";var a=class{providerCache=null;get provider(){return this.providerCache||=r(),this.providerCache}set provider(e){this.providerCache=e}async analyzeStructure(e,t,r){let i=r?.size??n,a=BigInt(t.startsWith(`0x`)?t:`0x${t}`),o=this.provider.openProcess(e,!1);try{let t=this.provider.readMemory(o,a,i).data,n=[],s=0;for(;s<i;){let e=i-s;if(e<1)break;let r=this.classifyValue(t,o,a,s,e);n.push({offset:s,size:r.size,type:r.type,name:`field_0x${s.toString(16).padStart(2,`0`).toUpperCase()}`,value:r.value,confidence:r.confidence,notes:r.notes}),s+=r.size}let c,l,u;if(n.length>0&&n[0].type===`vtable_ptr`&&(c=n[0].value,r?.parseRtti!==!1&&c))try{let t=await this.parseRtti(e,c,o);t&&(l=t.className,u=t.baseClasses)}catch{}return{baseAddress:`0x${a.toString(16).toUpperCase()}`,totalSize:i,fields:n,vtableAddress:c,className:l,baseClasses:u,timestamp:Date.now()}}finally{this.provider.closeProcess(o)}}async parseVtable(e,n){let r=BigInt(n.startsWith(`0x`)?n:`0x${n}`),i=this.provider.openProcess(e,!1);try{let a=[],o=await this.getModuleEntries(e);for(let e=0;e<t;e++){let t=r+BigInt(e*8),n;try{n=this.provider.readMemory(i,t,8).data.readBigUInt64LE(0)}catch{break}if(!this.isValidExecutablePointer(i,n))break;let s=this.resolveToModule(n,o);a.push({index:e,address:`0x${n.toString(16).toUpperCase()}`,module:s?.module,moduleOffset:s?.offset})}let s,c;try{let t=await this.parseRtti(e,n,i);t&&(s=t.className,c=t.baseClasses)}catch{}return{address:`0x${r.toString(16).toUpperCase()}`,functionCount:a.length,functions:a,rttiName:s,baseClasses:c}}finally{this.provider.closeProcess(i)}}async parseRtti(t,n,r){let i=BigInt(n.startsWith(`0x`)?n:`0x${n}`),a=!r,o=r??this.provider.openProcess(t,!1);try{let t=this.provider.readMemory(o,i-8n,8).data.readBigUInt64LE(0);if(!this.isValidReadablePointer(o,t))return null;let n=this.provider.readMemory(o,t,24).data;if(n.readUInt32LE(0)!==1)return null;let r=n.readUInt32LE(12),a=n.readUInt32LE(16),s=n.readUInt32LE(20),c=t-BigInt(s),l=c+BigInt(r),u=this.readCString(o,l+16n,e);if(!u)return null;let d=this.demangleMsvcName(u),f=[];try{let t=c+BigInt(a),n=this.provider.readMemory(o,t,16).data,r=n.readUInt32LE(8),i=n.readUInt32LE(12);if(r>0&&r<20){let t=c+BigInt(i),n=this.provider.readMemory(o,t,r*4).data;for(let t=1;t<r;t++){let r=n.readUInt32LE(t*4),i=c+BigInt(r);try{let t=this.provider.readMemory(o,i,8).data.readUInt32LE(0),n=c+BigInt(t),r=this.readCString(o,n+16n,e);r&&f.push(this.demangleMsvcName(r))}catch{break}}}}catch{}return{className:d,baseClasses:f}}catch{return null}finally{a&&this.provider.closeProcess(o)}}exportToCStruct(e,t){let n=t??e.className??`UnknownStruct`,r=[];r.push(`struct ${n} { // size: 0x${e.totalSize.toString(16).toUpperCase()} (${e.totalSize} bytes)`);for(let t of e.fields){let e=this.fieldTypeToCType(t.type,t.size),n=`0x${t.offset.toString(16).padStart(2,`0`).toUpperCase()}`,i=t.notes?`// +${n} ${t.notes}`:`// +${n} = ${t.value}`;t.type===`padding`?r.push(` uint8_t _pad_${t.offset.toString(16)}[${t.size}]; ${i}`):r.push(` ${e} ${t.name}; ${i}`)}return r.push(`};`),{name:n,definition:r.join(`
2
+ `),size:e.totalSize,fieldCount:e.fields.filter(e=>e.type!==`padding`).length}}async compareInstances(e,t,r,i){let a=i??n,[o,s]=await Promise.all([this.analyzeStructure(e,t,{size:a,parseRtti:!1}),this.analyzeStructure(e,r,{size:a,parseRtti:!1})]),c=[],l=[],u=new Map(s.fields.map(e=>[e.offset,e]));for(let e of o.fields){let t=u.get(e.offset);t&&(e.value===t.value&&e.type===t.type?c.push(e):l.push({offset:e.offset,value1:e.value,value2:t.value,type:e.type}))}return{matching:c,differing:l}}classifyValue(e,t,n,r,i){if(i>=8){let n=e.readBigUInt64LE(r);if(r===0&&n!==0n&&this.isValidExecutablePointer(t,n))try{let e=this.provider.readMemory(t,n,16).data.readBigUInt64LE(0);if(this.isValidExecutablePointer(t,e))return{type:`vtable_ptr`,size:8,value:`0x${n.toString(16).toUpperCase()}`,confidence:.9,notes:`likely vtable pointer (points to array of executable pointers)`}}catch{}if(n!==0n&&n>65536n&&n<140737488355327n&&this.isValidReadablePointer(t,n)){let e=this.readCString(t,n,64);return e&&e.length>=2?{type:`string_ptr`,size:8,value:`0x${n.toString(16).toUpperCase()} → "${e.slice(0,32)}${e.length>32?`...`:``}"`,confidence:.75,notes:`string pointer: "${e.slice(0,64)}"`}:{type:`pointer`,size:8,value:`0x${n.toString(16).toUpperCase()}`,confidence:.7,notes:`valid pointer to readable memory`}}}if(i>=4){let t=e.readUInt32LE(r),n=e.readInt32LE(r),a=e.readFloatLE(r);if(t===0&&i>=8&&e.readUInt32LE(r+4)===0){let t=0;for(let n=r;n<e.length&&e[n]===0;n++)t++;let n=Math.min(t,i)&-8;return{type:`padding`,size:n,value:`0x${`00`.repeat(Math.min(n,8))}`,confidence:.6}}if(t===0)return{type:`int32`,size:4,value:`0`,confidence:.4,notes:`zero value — could be int, bool, or padding`};if(t===1)return{type:`bool`,size:4,value:`true`,confidence:.5,notes:`value is 1 — could be boolean`};if(isFinite(a)&&!isNaN(a)&&Math.abs(a)>1e-10&&Math.abs(a)<1e8){let e=t>0&&t<1e5,n=Math.abs(a-Math.round(a))>.001;if(n||!e&&Math.abs(a)<1e4)return{type:`float`,size:4,value:a.toFixed(6),confidence:n?.8:.5,notes:n?`IEEE 754 float with fractional part`:`could be float or int`}}return t<2147483648?{type:`int32`,size:4,value:n.toString(),confidence:.6}:{type:`uint32`,size:4,value:t.toString(),confidence:.5}}return i>=2?{type:`uint16`,size:2,value:e.readUInt16LE(r).toString(),confidence:.4}:{type:`uint8`,size:1,value:e.readUInt8(r).toString(),confidence:.3}}isValidReadablePointer(e,t){try{let n=this.provider.queryRegion(e,t);return n?n.isReadable:!1}catch{return!1}}isValidExecutablePointer(e,t){try{let n=this.provider.queryRegion(e,t);return n?n.isReadable&&n.isExecutable:!1}catch{return!1}}readCString(e,t,n){try{let r=this.provider.readMemory(e,t,n).data,i=r.indexOf(0);if(i<0)return null;let a=r.subarray(0,i).toString(`ascii`);return/^[\x20-\x7E]+$/.test(a)&&a.length>=1?a:null}catch{return null}}demangleMsvcName(e){let t=e.match(/\.?\?A[VU](.+?)@@/);if(t)return t[1];let n=e.match(/\.?\?AW4(.+?)@@/);return n?n[1]:e.replace(/^\./,``).replace(/@@$/,``)}fieldTypeToCType(e,t){switch(e){case`int8`:return`int8_t`;case`uint8`:return`uint8_t`;case`int16`:return`int16_t`;case`uint16`:return`uint16_t`;case`int32`:return`int32_t`;case`uint32`:return`uint32_t`;case`int64`:return`int64_t`;case`uint64`:return`uint64_t`;case`float`:return`float`;case`double`:return`double`;case`pointer`:return`void*`;case`vtable_ptr`:return`void**`;case`string_ptr`:return`char*`;case`bool`:return`bool`;case`padding`:return`uint8_t[${t}]`;case`unknown`:return`uint8_t[${t}]`;default:return`uint8_t[${t}]`}}async getModuleEntries(e){let t=new Map;try{let n=await i.enumerateModules(e);if(n.success&&n.modules)for(let e of n.modules){let n=BigInt(e.baseAddress.startsWith(`0x`)?e.baseAddress:`0x${e.baseAddress}`);t.set(e.name.toLowerCase(),{name:e.name,base:n,size:e.size})}}catch{}return t}resolveToModule(e,t){for(let n of t.values())if(e>=n.base&&e<n.base+BigInt(n.size))return{module:n.name,offset:Number(e-n.base)};return null}};const o=new a;export{a as StructureAnalyzer,o as structureAnalyzer};
@@ -0,0 +1 @@
1
+ import{t as e}from"./logger-sBC6IdRT.mjs";const t=[{domain:`adb-bridge`,depKey:`adbBridgeHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BXry5N09.mjs`)},{domain:`core`,depKey:`coreAnalysisHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D610kxZr.mjs`)},{domain:`antidebug`,depKey:`antidebugHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D16xPXro.mjs`)},{domain:`binary-instrument`,depKey:`binaryInstrumentHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DD3rtxvV.mjs`)},{domain:`boringssl-inspector`,depKey:`boringsslInspectorHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DMJlcsTR.mjs`)},{domain:`browser`,depKey:`browserHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-zrbrpKCC.mjs`)},{domain:`canvas`,depKey:`canvasHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CtPmHAdn.mjs`)},{domain:`coordination`,depKey:`coordinationHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-ais9Afrw.mjs`)},{domain:`cross-domain`,depKey:`crossDomainHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-yu2xiQqe.mjs`)},{domain:`debugger`,depKey:`debuggerHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Cx2IVMUY.mjs`)},{domain:`encoding`,depKey:`encodingHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DC-SMF6b.mjs`)},{domain:`evidence`,depKey:`evidenceHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-De-6Wf2R.mjs`)},{domain:`extension-registry`,depKey:`extensionRegistryHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-C1nZkTkO.mjs`)},{domain:`graphql`,depKey:`graphqlHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DWUUWBz0.mjs`)},{domain:`hooks`,depKey:`aiHookHandlers`,profiles:[`full`],secondaryDepKeys:[`hookPresetHandlers`],load:()=>import(`./manifest-BeP_zJGb2.mjs`)},{domain:`instrumentation`,depKey:`instrumentationHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DsVh7Y4U.mjs`)},{domain:`macro`,depKey:`macroHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CJMGt7Qy.mjs`)},{domain:`maintenance`,depKey:`coreMaintenanceHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`extensionManagementHandlers`],load:()=>import(`./manifest-CFn0359q2.mjs`)},{domain:`memory`,depKey:`memoryScanHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DtEFSRaq.mjs`)},{domain:`mojo-ipc`,depKey:`mojoIpcHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CGq4NpqH2.mjs`)},{domain:`network`,depKey:`advancedHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-C7qV1z7F.mjs`)},{domain:`platform`,depKey:`platformHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D44TaRJU.mjs`)},{domain:`process`,depKey:`processHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Cq0j7GZt.mjs`)},{domain:`protocol-analysis`,depKey:`protocolAnalysisHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CeQmtQOY.mjs`)},{domain:`proxy`,depKey:`proxyHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CDeUZGUZ.mjs`)},{domain:`sandbox`,depKey:`sandboxHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CRIJq4Hs.mjs`)},{domain:`shared-state-board`,depKey:`sharedStateBoardHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-C0g67k6U.mjs`)},{domain:`skia-capture`,depKey:`skiaCaptureHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-H-EpAyZQ.mjs`)},{domain:`sourcemap`,depKey:`sourcemapHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DKUorv5M.mjs`)},{domain:`streaming`,depKey:`streamingHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-tmb54wmA.mjs`)},{domain:`syscall-hook`,depKey:`syscallHookHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Dgh0uDW-.mjs`)},{domain:`trace`,depKey:`traceHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BPuE6oH2.mjs`)},{domain:`transform`,depKey:`transformHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Dm0o3i2U.mjs`)},{domain:`v8-inspector`,depKey:`v8InspectorHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BFGxlDRh.mjs`)},{domain:`wasm`,depKey:`wasmHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CDiCtaQT.mjs`)},{domain:`workflow`,depKey:`workflowHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-C_hEIjSx.mjs`)}],n={"adb-bridge":[`full`],core:[`workflow`,`full`],antidebug:[`full`],"binary-instrument":[`full`],"boringssl-inspector":[`full`],browser:[`workflow`,`full`],canvas:[`full`],coordination:[`full`],"cross-domain":[`full`],debugger:[`workflow`,`full`],encoding:[`workflow`,`full`],evidence:[`full`],"extension-registry":[`full`],graphql:[`workflow`,`full`],hooks:[`full`],instrumentation:[`full`],macro:[`full`],maintenance:[`workflow`,`full`],memory:[`full`],"mojo-ipc":[`full`],network:[`workflow`,`full`],platform:[`full`],process:[`full`],"protocol-analysis":[`full`],proxy:[`full`],sandbox:[`full`],"shared-state-board":[`workflow`,`full`],"skia-capture":[`full`],sourcemap:[`full`],streaming:[`workflow`,`full`],"syscall-hook":[`full`],trace:[`full`],transform:[`full`],"v8-inspector":[`workflow`,`full`],wasm:[`full`],workflow:[`workflow`,`full`]};function r(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.kind===`domain-manifest`&&t.version===1&&typeof t.domain==`string`&&typeof t.depKey==`string`&&Array.isArray(t.profiles)&&Array.isArray(t.registrations)&&typeof t.ensure==`function`}function i(e){if(!e||typeof e!=`object`)return null;let t=e;for(let e of[`default`,`manifest`,`domainManifest`]){let n=t[e];if(r(n))return n}return null}function a(e){let t=new Set;for(let[r,i]of Object.entries(n))i.includes(e)&&t.add(r);return t}function o(){return new Set(Object.keys(n))}function s(){return t}async function c(n){let r=[],a=new Set,o=new Set;for(let{domain:s,load:c}of t)if(!(n&&!n.has(s)))try{let t=i(await c());if(!t){e.warn(`[discovery] Skipping domain "${s}": no valid DomainManifest export`);continue}if(a.has(t.domain)){e.warn(`[discovery] Duplicate domain "`+t.domain+`" in generated manifests - skipping`);continue}if(o.has(t.depKey)){e.warn(`[discovery] Duplicate depKey "`+t.depKey+`" in generated manifests - skipping`);continue}a.add(t.domain),o.add(t.depKey),r.push(t),e.info(`[discovery] Loaded domain "`+t.domain+`" (`+String(t.registrations.length)+` tools)`)}catch(t){if(e.error(`[discovery] Failed to load domain "${s}"`,t),process.env.DISCOVERY_STRICT===`true`)throw t}let s=r.reduce((e,t)=>e+t.registrations.length,0);return e.info(`[discovery] Discovered `+String(r.length)+` domains, `+String(s)+` tools total`),r}async function l(n){let r=t.find(e=>e.domain===n);if(!r)return null;try{let t=i(await r.load());return t?(e.info(`[discovery] On-demand loaded domain "`+t.domain+`" (`+String(t.registrations.length)+` tools)`),t):(e.warn(`[discovery] Domain "${n}": no valid DomainManifest export`),null)}catch(t){return e.error(`[discovery] Failed to load domain "${n}"`,t),null}}function u(e,t){let n=new Set(t);return e.every(e=>n.has(e))}let d=null,f=null,p=null,m=null,h=null,g=null;async function _(t){if(d===null){if(p){await p;return}p=(async()=>{let n=await c(t?a(t):void 0);d=n,g=new Map;for(let t of n)for(let n of t.registrations){let r=n.domain?n:{...n,domain:t.domain},i=g.get(r.tool.name);i?e.warn(`[registry] Duplicate tool name "${r.tool.name}": domain "${r.domain}" conflicts with "${i.domain}" — keeping first`):g.set(r.tool.name,r)}f=[...g.values()],m=new Set(d.map(e=>e.domain)),h=new Set(f.map(e=>e.tool.name))})(),await p}}async function v(e){await _(e)}async function y(e){if(!d)throw Error(`[registry] Not initialised - call initRegistry() first.`);if(d.some(t=>t.domain===e))return d.find(t=>t.domain===e);let t=await l(e);if(!t)return null;d.push(t),m.add(t.domain);for(let e of t.registrations){let n=e.domain?e:{...e,domain:t.domain};g.has(n.tool.name)||g.set(n.tool.name,n)}f=[...g.values()],L();for(let e of t.registrations)h.add(e.tool.name);return t}async function b(){if(!d)throw Error(`[registry] Not initialised - call initRegistry() first.`);let t=o(),n=new Set(d.map(e=>e.domain)),r=[...t].filter(e=>!n.has(e));r.length!==0&&(e.info(`[registry] Loading ${r.length} remaining domains for full discovery`),await Promise.all(r.map(e=>y(e))))}function x(){if(!d)throw Error(`[registry] Not initialised - call initRegistry() first.`);return d}function S(){if(!f)throw Error(`[registry] Not initialised - call initRegistry() first.`);return f}function C(){return x()}function w(){return S()}function T(){if(!m)throw Error(`[registry] Not initialised - call initRegistry() first.`);return m}function E(){return o()}function D(){let e={};for(let t of S())(e[t.domain]??=[]).push(t.tool);return e}function O(){let e=new Map;for(let t of S())e.has(t.tool.name)||e.set(t.tool.name,t.domain);return e}function k(){return S().map(e=>e.tool)}function A(e,t){let n=t?S().filter(e=>t.has(e.tool.name)):[...S()],r=[];for(let t of n)try{r.push([t.tool.name,t.bind(e)])}catch{}return Object.fromEntries(r)}function j(){let t={search:new Set,workflow:new Set,full:new Set};for(let[e,r]of Object.entries(n))for(let n of r)t[n]?.add(e);let r={};for(let[e,n]of Object.entries(t))r[e]=[...n];return u(r.search,r.workflow)||e.warn(`[registry] Profile hierarchy: search not subset of workflow`),u(r.workflow,r.full)||e.warn(`[registry] Profile hierarchy: workflow not subset of full`),r}let M=null,N=null,P=null,F=null;function I(){return M||=D(),M}function L(){M=null}function R(){return N||=O(),N}function z(){return P||=j(),P}const B=new Proxy([],{get(e,t){F||=k();let n=F,r=n[t];return typeof r==`function`?r.bind(n):r}});function V(e){let t=new Map;for(let n of e)t.set(n.name,n);return Array.from(t.values())}function H(e){if(!e?.trim())return null;let t=T(),n=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean).filter(e=>t.has(e));return n.length>0?Array.from(new Set(n)):null}function U(e){return V(e.flatMap(e=>I()[e]??[]))}function W(e){let t=z()[e];if(!t)return[];let n=new Set(t);return V([...w()].filter(t=>!(!n.has(t.domain)||t.profiles&&!t.profiles.includes(e))).map(e=>e.tool))}function G(e){return R().get(e)??null}function K(e){return z()[e]??[]}export{W as a,b as c,E as d,C as f,s as h,U as i,y as l,v as m,K as n,H as o,w as p,G as r,A as s,B as t,T as u};
@@ -0,0 +1 @@
1
+ var e=class extends Error{code;toolName;details;constructor(e,t,n){super(t,{cause:n?.cause}),this.name=`ToolError`,this.code=e,this.toolName=n?.toolName,this.details=n?.details}};export{e as t};
@@ -0,0 +1 @@
1
+ import"./logger-sBC6IdRT.mjs";import{Y as e}from"./constants-Cp6hBrrx.mjs";import{execFile as t}from"node:child_process";import{promisify as n}from"node:util";const r=n(t);async function i(t,n=[`--version`],i=e){try{let{stdout:e}=await r(process.platform===`win32`?`where`:`which`,[t],{timeout:i,windowsHide:!0}),a=e.trim().split(/\r?\n/)[0],o;try{let{stdout:e}=await r(t,n,{timeout:i,windowsHide:!0}),a=e.trim().split(/\r?\n/)[0];o=a?a.substring(0,100):void 0}catch{}return{available:!0,path:a,version:o}}catch(e){let n=typeof e==`object`&&e&&`code`in e?e.code:void 0,r=e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message??``):String(e??``);return{available:!1,reason:n===`ENOENT`?`Command '${t}' not found in PATH`:`Probe failed: ${r.substring(0,200)}`}}}export{i as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./logger-sBC6IdRT.mjs";import{J as t}from"./constants-Cp6hBrrx.mjs";import{t as n}from"./ToolProbe-xsfALmN3.mjs";const r=[{name:`wabt.wasm2wat`,command:`wasm2wat`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`wabt.wasm-objdump`,command:`wasm-objdump`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`wabt.wasm-decompile`,command:`wasm-decompile`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`wabt.wasm2c`,command:`wasm2c`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`binaryen.wasm-opt`,command:`wasm-opt`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`runtime.wasmtime`,command:`wasmtime`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`runtime.wasmer`,command:`wasmer`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`miniapp.unpacker`,command:`unveilr`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`platform.jadx`,command:`jadx`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.ast-grep`,command:`ast-grep`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.wakaru`,command:`wakaru`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.restringer`,command:`restringer`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.z3`,command:`z3`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`syscall.strace`,command:`strace`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`syscall.bpftrace`,command:`bpftrace`,versionArgs:[`--version`],required:!1,envAllowlist:[]}];var i=class{specs=new Map;probeCache=new Map;probeCacheExpiry=0;PROBE_CACHE_TTL=t;constructor(e){for(let e of r)this.specs.set(e.name,e);if(e)for(let t of e)this.specs.set(t.name,t)}getSpec(e){let t=this.specs.get(e);if(!t)throw Error(`Tool '${e}' is not registered in the allowlist`);return t}isRegistered(e){return this.specs.has(e)}getRegisteredTools(){return Array.from(this.specs.keys())}async probeAll(t=!1){let r=Date.now();if(!t&&this.probeCache.size>0&&r<this.probeCacheExpiry)return Object.fromEntries(this.probeCache);let i={},a=[];for(let[e,t]of this.specs)a.push(n(t.command,t.versionArgs).then(t=>{i[e]=t,this.probeCache.set(e,t)}));await Promise.all(a),this.probeCacheExpiry=r+this.PROBE_CACHE_TTL;let o=Object.values(i).filter(e=>e.available).length;return e.info(`[ToolRegistry] Probed ${this.specs.size} tools: ${o} available`),i}getCachedProbe(e){return this.probeCache.get(e)}register(t){this.specs.set(t.name,t),this.probeCache.delete(t.name),e.debug(`[ToolRegistry] Registered tool: ${t.name} -> ${t.command}`)}};export{i as t};
@@ -0,0 +1,4 @@
1
+ import{_n as e,dn as t,fn as n,gn as r,hn as i,mn as a,pn as o,un as s,vn as c}from"./constants-Cp6hBrrx.mjs";import{f as l,r as u,t as d}from"./ToolCatalog-D_IKl1Hu.mjs";const f=/(browser|page|navigate|click|type|screenshot|scrape|network|request|response|api|traffic|hook|capture|intercept|monitor|浏览器|页面|导航|点击|输入|截图|爬取|网络|请求|响应|接口|流量|抓包|拦截|监控)/i,p=/(token budget|cache|artifact|extension|plugin|reload|doctor|cleanup|memory|profile|tool list|令牌预算|缓存|工件|扩展|插件|重载|环境诊断|清理|内存|配置)/i,m=/(stateless|deterministic|pure compute|offline|decode|encode|hex|base64|protobuf|msgpack|checksum|hash|payload|frame|packet|bytes?|bytecode|pcap|protocol|state machine|field inference|ast transform|crypto harness|无状态|确定性|纯算|离线|解码|编码|十六进制|校验和|载荷|字节|协议|报文|帧|字段推断|状态机|构包)/i;let h=null;const g=new Map;function _(){if(h)return h;let e=[];for(let t of l())t.workflowRule&&e.push({patterns:[...t.workflowRule.patterns],domain:t.domain,priority:t.workflowRule.priority,tools:[...t.workflowRule.tools],hint:t.workflowRule.hint});return h=[...e].toSorted((e,t)=>t.priority-e.priority),g.clear(),h}function v(e){let t=g.get(e);if(t!==void 0)return t;let n=[];for(let t of _())for(let r of t.patterns)if(r.test(e)){n.push(t);break}let r=n.length===0?null:n.toSorted((e,t)=>t.priority-e.priority)[0];if(g.size>=64){let e=g.keys().next().value;e!==void 0&&g.delete(e)}return g.set(e,r),r}function y(e,t){let n=null;for(let[r,i]of t.extensionWorkflowRuntimeById.entries()){let a=i.route??i.workflow.route;if(!a)continue;let o=t.extensionWorkflowsById.get(r),s=o?.displayName??i.workflow.displayName,c=o?.description??i.workflow.description??`Workflow route`;for(let t of a.triggerPatterns){if(!t.test(e))continue;let i=a.priority/100;(!n||i>n.confidence)&&(n={workflow:{id:r,name:s,description:c,route:a},confidence:i,matchedPattern:t.source});break}}return n}function b(e,t){return t?.domain!==`browser`&&t?.domain!==`network`&&S(e)?!1:t?.domain===`browser`||t?.domain===`network`||f.test(e)}function x(e){return p.test(e)}function S(e){return m.test(e)}function C(e,t){if(e.length<2)return null;let n=l();if(n.length===0)return null;let r=new Map,i=new Map;for(let e of n)if(e.toolDependencies)for(let a of e.toolDependencies){let e=new Set(T(a,n)),o=w(a.from,n),s=w(a.to,n);if(o&&s&&o!==s){let e=r.get(o)??new Set;e.add(s),r.set(o,e);let n=i.get(o)??new Set;n.add(a.from),t.has(a.to)&&n.add(a.to),i.set(o,n)}for(let t of e)if(t!==o&&o){let e=r.get(o)??new Set;e.add(t),r.set(o,e)}}let a=new Set;for(let t of e)t.domain&&a.add(t.domain);if(a.size<2)return null;let o=[...a];for(let e=0;e<o.length;e++)for(let i=e+1;i<o.length;i++){let a=o[e],s=o[i];if(!(r.get(a)?.has(s)||r.get(s)?.has(a)))continue;let c=new Set;for(let e of n)if(e.toolDependencies)for(let r of e.toolDependencies){let e=w(r.from,n),i=w(r.to,n);(e===a&&i===s||e===s&&i===a)&&(t.has(r.from)&&c.add(r.from),t.has(r.to)&&c.add(r.to))}let l=[...c];if(!(l.length<2))return{id:`dynamic-${a}-${s}`,hint:`${a} ↔ ${s} (declared dependency)`,domains:[a,s],tools:l.slice(0,5),priority:75}}return null}function w(e,t){for(let n of t)for(let t of n.registrations)if(t.tool.name===e)return t.domain??n.domain;return null}function T(e,t){return[w(e.from,t),w(e.to,t)].filter(e=>e!==null)}function E(e){let t=e.trim();if(!t.startsWith(`mcp__`))return t;let n=t.split(`__`);return n.length<3?t:n.slice(2).join(`__`)}function D(e){let t=e.names;if(typeof t==`string`&&t.trim().startsWith(`[`))try{let e=JSON.parse(t);Array.isArray(e)&&(t=e)}catch{}if(!Array.isArray(t))return{names:[],error:`names must be an array`};let n=[];for(let e of t){if(typeof e!=`string`||e.trim().length===0)return{names:[],error:`invalid tool name: expected non-empty string`};n.push(E(e))}return{names:n}}let O=null;function k(){return O||=new Map(d.map(e=>[e.name,e])),O}function A(e,t){let n=E(e),r=k().get(n);if(r)return r.inputSchema;let i=t.extensionToolsByName.get(n);if(i)return i.tool.inputSchema;let a=t.metaToolsByName.get(n);if(a)return a.inputSchema}function j(e,t){let n=E(e),r=k().get(n);if(r?.description)return r.description.split(`
2
+ `)[0]||`No description available`;let i=t.extensionToolsByName.get(n);if(i?.tool?.description)return i.tool.description.split(`
3
+ `)[0]||`No description available`;let a=t.metaToolsByName.get(n);return a?.description&&a.description.split(`
4
+ `)[0]||`No description available`}function M(e,t){let n=E(e);return new Set([...t.selectedTools.map(e=>e.name),...t.activatedToolNames]).has(n)}function N(e){return new Set([...d.map(e=>e.name),...e.extensionToolsByName.keys()])}function P(e,t){return u(e)??t.extensionToolsByName.get(e)?.domain??null}async function F(e){if(!e.pageController||typeof e.pageController.getPage!=`function`)return!1;try{return!!await e.pageController.getPage()}catch{return!1}}function I(e){if(!e.consoleMonitor)return!1;try{if(typeof e.consoleMonitor.getNetworkStatus==`function`)return!!e.consoleMonitor.getNetworkStatus().enabled;if(typeof e.consoleMonitor.isNetworkEnabled==`function`)return!!e.consoleMonitor.isNetworkEnabled()}catch{}return!1}function L(e){if(!e.consoleMonitor||typeof e.consoleMonitor.getNetworkRequests!=`function`)return 0;try{let t=e.consoleMonitor.getNetworkRequests({limit:1});return Array.isArray(t)?t.length:0}catch{try{let t=e.consoleMonitor.getNetworkRequests();return Array.isArray(t)?t.length:0}catch{return 0}}}async function R(e){return{hasActivePage:await F(e),networkEnabled:I(e),capturedRequestCount:L(e)}}function z(e,t){if(!S(e))return[];let n=[],r=(e,r)=>{t.has(e)&&!n.some(t=>t.name===e)&&n.push({name:e,description:r})};return r(`binary_detect_format`,`Detect the payload encoding or container before decoding`),r(`binary_decode`,`Decode the payload into deterministic offline bytes or structured output`),r(`proto_auto_detect`,`Infer a likely protocol layout from repeated payload samples`),r(`proto_infer_fields`,`Derive stable field boundaries and candidate semantics`),r(`proto_infer_state_machine`,`Infer request/response state transitions from repeated samples`),r(`crypto_test_harness`,`Validate extracted signing or crypto logic with deterministic test vectors`),r(`crypto_compare`,`Compare competing crypto implementations against the same vectors`),r(`network_get_requests`,`Collect request or response samples only if payload bytes still need to be extracted`),n}function B(e){return e.includes(`Browser must be launched`)?e=>e.hasActivePage:e.includes(`Network monitoring must be enabled`)?e=>e.networkEnabled:e.includes(`Debugger must be enabled`)||e.includes(`Debugger must be attached`)||e.includes(`Page must be navigated`)||e.includes(`WebSocket monitoring`)?e=>e.hasActivePage:()=>!1}let V=null;function H(){if(V)return V;let e={};for(let t of l())if(t.prerequisites)for(let[n,r]of Object.entries(t.prerequisites))e[n]=r.map(e=>({condition:e.condition,check:B(e.condition),fix:e.fix}));return V=e,V}function U(e,t,n){let r=[],i=e=>{n.has(e)&&!r.includes(e)&&r.push(e)};(e.domain===`browser`||e.domain===`network`)&&!t.hasActivePage&&(i(`browser_launch`),i(`browser_attach`)),e.domain===`network`&&(t.hasActivePage&&!t.networkEnabled&&i(`network_monitor`),t.hasActivePage&&t.networkEnabled&&t.capturedRequestCount>0&&i(`network_get_requests`));for(let t of e.tools)i(t);return e.domain===`network`&&t.hasActivePage&&t.networkEnabled&&i(`network_get_requests`),r}function W(e,t,n){let r=[],i=new Set,a=e.workflow.route.requiredDomains.includes(`browser`)||e.workflow.route.requiredDomains.includes(`network`),o=(e,t)=>{!n.has(e)||i.has(e)||(i.add(e),r.push({name:e,description:t}))};!t.hasActivePage&&a&&(o(`browser_launch`,`Launch a browser session before executing the preset`),o(`browser_attach`,`Attach preset tooling to the active browser session before capture begins`));for(let t of e.workflow.route.steps)o(t.toolName,t.description);return r}function G(e,t,n,r){return W(e,t,r).map((t,r)=>({name:t.name,domain:P(t.name,n),shortDescription:t.description,score:e.workflow.route.priority+e.confidence-r*.01,isActive:M(t.name,n)}))}function K(e,t,n){return z(e,n).map((e,n)=>({name:e.name,domain:P(e.name,t),shortDescription:e.description,score:90-n*.01,isActive:M(e.name,t)}))}function q(e,t){return{name:`run_extension_workflow`,domain:P(`run_extension_workflow`,t),shortDescription:`Execute routed workflow ${e.workflow.name} (${e.workflow.id}) via run_extension_workflow`,score:e.workflow.route.priority+e.confidence,isActive:M(`run_extension_workflow`,t)}}function J(e,t){return{kind:e.workflow.route.kind,id:e.workflow.id,name:e.workflow.name,description:e.workflow.description,confidence:e.confidence,matchedPattern:e.matchedPattern,requiredDomains:[...e.workflow.route.requiredDomains],steps:e.workflow.route.steps.map(e=>({id:e.id,toolName:e.toolName,domain:u(e.toolName)??t.extensionToolsByName.get(e.toolName)?.domain??null,description:e.description,prerequisites:[...e.prerequisites],parallel:e.parallel,isActive:M(e.toolName,t)}))}}function Y(l,u,d,f){let p=b(u,d),m=x(u),h=S(u),g=l.map(l=>{let u=l.score;return p&&!m&&l.domain===`maintenance`&&(u*=n),h&&((l.domain===`browser`||l.domain===`network`||l.domain===`debugger`||l.domain===`hooks`||l.domain===`maintenance`)&&(u*=e),(l.domain===`core`||l.domain===`streaming`||l.domain===`workflow`)&&(u*=r),(l.domain===`encoding`||l.domain===`transform`||l.domain===`protocol-analysis`||l.domain===`sourcemap`||l.domain===`core`)&&(u*=i),(l.name===`binary_detect_format`||l.name===`binary_decode`||l.name===`crypto_test_harness`||l.name===`ast_transform_apply`||l.name===`proto_auto_detect`||l.name===`proto_infer_fields`||l.name===`proto_infer_state_machine`||l.name===`proto_fingerprint`)&&(u*=c)),p&&(!f.hasActivePage&&l.name===`browser_launch`&&(u*=t),!f.hasActivePage&&l.name===`browser_attach`&&(u*=s),f.hasActivePage&&!f.networkEnabled&&l.name===`network_monitor`&&(u*=a),f.hasActivePage&&f.networkEnabled&&f.capturedRequestCount>0&&l.name===`network_get_requests`&&(u*=o)),{...l,score:u}});return g.sort((e,t)=>t.score-e.score),g}export{v as _,U as a,S as b,N as c,P as d,A as f,C as g,D as h,q as i,R as l,E as m,J as n,H as o,M as p,K as r,Y as s,G as t,j as u,b as v,y as x,x as y};
@@ -0,0 +1,272 @@
1
+ import{n as e}from"./chunk-C_pMuVsO.mjs";import{i as t}from"./artifacts-B5xQuEa_.mjs";import{t as n}from"./betterSqlite3-CGaxz4AX.mjs";import{randomUUID as r}from"node:crypto";import{writeFile as i}from"node:fs/promises";const a={Debugger:[`Debugger.paused`,`Debugger.resumed`,`Debugger.scriptParsed`],Runtime:[`Runtime.consoleAPICalled`,`Runtime.exceptionThrown`],Network:[`Network.requestWillBeSent`,`Network.requestServedFromCache`,`Network.responseReceived`,`Network.dataReceived`,`Network.loadingFinished`,`Network.loadingFailed`,`Network.eventSourceMessageReceived`,`Network.webSocketCreated`,`Network.webSocketWillSendHandshakeRequest`,`Network.webSocketHandshakeResponseReceived`,`Network.webSocketFrameReceived`,`Network.webSocketFrameSent`,`Network.webSocketFrameError`,`Network.webSocketClosed`],Page:[`Page.navigatedWithinDocument`,`Page.loadEventFired`]},o=[`Debugger`,`Runtime`,`Network`,`Page`],s={recordResponseBodies:!0,streamResponseChunks:!0,maxBodyBytes:10*1024*1024,inlineBodyBytes:256*1024},c=16*1024,l=e=>typeof e==`object`&&!!e,u=e=>typeof e==`string`?e:null,d=e=>typeof e==`number`&&Number.isFinite(e)?e:null,f=e=>{let t=d(e);return t===null?null:t>0xe8d4a51000?t:t*1e3},p=e=>l(e)&&typeof e.body==`string`&&typeof e.base64Encoded==`boolean`,m=e=>{let t=Date.now();if(!l(e))return{timestamp:t,wallTime:t,monotonicTime:null};let n=f(e.wallTime),r=f(e.timestamp);return{timestamp:n??t,wallTime:n??t,monotonicTime:r}},h=e=>l(e)&&typeof e.requestId==`string`?e.requestId:null,g=(e,t)=>{let n=null,r=null;if(!l(t))return{scriptId:n,lineNumber:r};if(`scriptId`in t&&(n=String(t.scriptId)),`lineNumber`in t&&(r=Number(t.lineNumber)||null),e===`Debugger.paused`&&Array.isArray(t.callFrames)){let e=t.callFrames[0];if(e){let t=e.location;t&&(n=String(t.scriptId??n),r=Number(t.lineNumber??r)||null)}}return{scriptId:n,lineNumber:r}},_=(e,t)=>{if(!l(t))return t??{};let n={...t};if(e===`Network.dataReceived`&&typeof n.data==`string`){let e=n.data;n.hasChunkData=!0,n.chunkDataBytes=Buffer.byteLength(e,`utf8`),n.data=`[captured in network_chunks]`}if(e===`Network.eventSourceMessageReceived`&&typeof n.data==`string`&&Buffer.byteLength(n.data,`utf8`)>c&&(n.data=`${n.data.slice(0,c)}...[truncated]`,n.truncatedData=!0),(e===`Network.webSocketFrameReceived`||e===`Network.webSocketFrameSent`)&&l(n.response)&&typeof n.response.payloadData==`string`){let e={...n.response},t=e.payloadData;Buffer.byteLength(t,`utf8`)>c&&(e.payloadData=`${t.slice(0,c)}...[truncated]`,e.truncatedPayloadData=!0,n.response=e)}return n},v=e=>{let t=u(e.remoteIPAddress),n=d(e.remotePort);return t?n===null?t:`${t}:${n}`:null},y=e=>({requestId:e,url:null,method:null,resourceType:null,requestHeaders:`{}`,requestPostData:null,status:null,statusText:null,responseHeaders:`{}`,mimeType:null,protocol:null,remoteAddress:null,fromDiskCache:!1,fromServiceWorker:!1,startedWallTime:null,responseWallTime:null,finishedWallTime:null,startedMonotonicTime:null,responseMonotonicTime:null,finishedMonotonicTime:null,encodedDataLength:null,receivedDataLength:0,receivedEncodedDataLength:0,chunkCount:0,streamingEnabled:!1,streamingSupported:null,streamingError:null,bodyCaptureState:`none`,bodyInline:null,bodyArtifactPath:null,bodyBase64Encoded:!1,bodySize:null,bodyTruncated:!1,bodyError:null,failed:!1,errorText:null});var b=class{deps;resources=new Map;options={...s};counts={networkRequestCount:0,networkChunkCount:0,networkBodyCount:0};constructor(e){this.deps=e}configure(e){return this.resources.clear(),this.counts={networkRequestCount:0,networkChunkCount:0,networkBodyCount:0},this.options={...s,...e},this.getOptions()}clear(){this.resources.clear(),this.counts={networkRequestCount:0,networkChunkCount:0,networkBodyCount:0}}getOptions(){return{...this.options}}getCounts(){return{...this.counts}}handleEvent(e,t,n){let r=h(t);if(r)switch(e){case`Network.requestWillBeSent`:this.handleRequestWillBeSent(r,t,n);return;case`Network.requestServedFromCache`:this.handleRequestServedFromCache(r);return;case`Network.responseReceived`:this.handleResponseReceived(r,t,n);return;case`Network.dataReceived`:this.handleDataReceived(r,t,n);return;case`Network.loadingFinished`:this.handleLoadingFinished(r,t,n);return;case`Network.loadingFailed`:this.handleLoadingFailed(r,t,n);return;default:return}}handleRequestWillBeSent(e,t,n){let r=this.getOrCreateResource(e),i=l(t)&&l(t.request)?t.request:null;r.url=i?u(i.url):r.url,r.method=i?u(i.method):r.method,r.resourceType=l(t)&&typeof t.type==`string`?t.type:r.resourceType,r.requestHeaders=i?JSON.stringify(i.headers??{}):r.requestHeaders,r.requestPostData=i?u(i.postData):r.requestPostData,r.startedWallTime=n.wallTime??r.startedWallTime??n.timestamp,r.startedMonotonicTime=n.monotonicTime??r.startedMonotonicTime,this.syncResource(r)}handleRequestServedFromCache(e){let t=this.getOrCreateResource(e);t.fromDiskCache=!0,this.syncResource(t)}handleResponseReceived(e,t,n){let r=this.getOrCreateResource(e),i=l(t)&&l(t.response)?t.response:null;r.url=i?u(i.url)??r.url:r.url,r.status=i?d(i.status):r.status,r.statusText=i?u(i.statusText):r.statusText,r.responseHeaders=i?JSON.stringify(i.headers??{}):r.responseHeaders,r.mimeType=i?u(i.mimeType):r.mimeType,r.protocol=i?u(i.protocol):r.protocol,r.remoteAddress=i?v(i):r.remoteAddress,r.fromDiskCache=i?!!i.fromDiskCache:r.fromDiskCache,r.fromServiceWorker=i?!!i.fromServiceWorker:r.fromServiceWorker,r.responseWallTime=n.wallTime??r.responseWallTime??n.timestamp,r.responseMonotonicTime=n.monotonicTime??r.responseMonotonicTime,this.syncResource(r),this.options.streamResponseChunks&&r.streamingSupported===null&&this.deps.trackOperation(this.enableStreamingForRequest(e))}handleDataReceived(e,t,n){let r=this.getOrCreateResource(e),i=l(t)?t:null,a=i?d(i.dataLength)??0:0,o=i?d(i.encodedDataLength)??0:0,s=i?u(i.data):null;r.receivedDataLength+=a,r.receivedEncodedDataLength+=o,r.chunkCount+=1;let c=r.receivedDataLength<=this.options.maxBodyBytes,f={requestId:e,sequence:r.chunkCount,timestamp:n.timestamp,monotonicTime:n.monotonicTime,dataLength:a,encodedDataLength:o,chunkData:c?s:null,chunkIsBase64:s!==null};try{this.deps.getDb()?.insertNetworkChunk(f),this.counts.networkChunkCount++}catch{}this.syncResource(r)}handleLoadingFinished(e,t,n){let r=this.getOrCreateResource(e);r.finishedWallTime=n.wallTime??n.timestamp,r.finishedMonotonicTime=n.monotonicTime??r.finishedMonotonicTime,l(t)&&(r.encodedDataLength=d(t.encodedDataLength)??r.encodedDataLength),this.syncResource(r),this.options.recordResponseBodies&&this.deps.trackOperation(this.captureResponseBody(e))}handleLoadingFailed(e,t,n){let r=this.getOrCreateResource(e);r.finishedWallTime=n.wallTime??n.timestamp,r.finishedMonotonicTime=n.monotonicTime??r.finishedMonotonicTime,r.failed=!0,r.errorText=l(t)?u(t.errorText):null,this.syncResource(r)}async enableStreamingForRequest(e){let t=this.deps.getCdpSession(),n=this.deps.getDb();if(!t||!n||!this.options.streamResponseChunks)return;let r=this.resources.get(e);if(!(!r||r.streamingSupported!==null))try{let i=await t.send(`Network.streamResourceContent`,{requestId:e});if(r.streamingEnabled=!0,r.streamingSupported=!0,r.streamingError=null,l(i)){let t=u(i.bufferedData);if(t){let i=Buffer.from(t,`base64`).length,a={requestId:e,sequence:r.chunkCount+1,timestamp:Date.now(),monotonicTime:r.responseMonotonicTime,dataLength:i,encodedDataLength:i,chunkData:r.receivedDataLength+i<=this.options.maxBodyBytes?t:null,chunkIsBase64:!0};r.chunkCount+=1,r.receivedDataLength+=i,r.receivedEncodedDataLength+=i,n.insertNetworkChunk(a),this.counts.networkChunkCount++}}}catch(e){r.streamingEnabled=!1,r.streamingSupported=!1,r.streamingError=e instanceof Error?e.message:String(e)}finally{this.syncResource(r)}}async captureResponseBody(e){let n=this.deps.getCdpSession();if(!n||!this.deps.getDb()||!this.options.recordResponseBodies)return;let r=this.resources.get(e);if(r)try{let a=await n.send(`Network.getResponseBody`,{requestId:e});if(!p(a))return;if(r.bodyBase64Encoded=a.base64Encoded,r.bodySize=a.base64Encoded?Buffer.from(a.body,`base64`).length:Buffer.byteLength(a.body,`utf8`),r.bodyTruncated=r.bodySize>this.options.maxBodyBytes,r.bodyTruncated)r.bodyCaptureState=`truncated`,r.bodyInline=a.body.slice(0,this.options.inlineBodyBytes),r.bodyArtifactPath=null,r.bodyError=`Body exceeded configured maxBodyBytes (${this.options.maxBodyBytes})`;else if(r.bodySize<=this.options.inlineBodyBytes)r.bodyCaptureState=`inline`,r.bodyInline=a.body,r.bodyArtifactPath=null,r.bodyError=null;else{let n=a.base64Encoded?`b64`:`txt`,{absolutePath:o}=await t({category:`traces`,toolName:`trace_body`,target:e.slice(0,32),ext:n});await i(o,a.body,`utf8`),r.bodyCaptureState=`artifact`,r.bodyInline=null,r.bodyArtifactPath=o,r.bodyError=null}this.counts.networkBodyCount++}catch(e){r.bodyCaptureState=r.bodyCaptureState===`none`?`error`:r.bodyCaptureState,r.bodyError=e instanceof Error?e.message:String(e)}finally{this.syncResource(r)}}getOrCreateResource(e){let t=this.resources.get(e);if(t)return t;let n=y(e);return this.resources.set(e,n),this.counts.networkRequestCount++,n}syncResource(e){try{this.deps.getDb()?.upsertNetworkResource(e)}catch{}}};function x(e){e.exec(`
2
+ CREATE TABLE IF NOT EXISTS events (
3
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
4
+ timestamp REAL NOT NULL,
5
+ category TEXT NOT NULL,
6
+ event_type TEXT NOT NULL,
7
+ data TEXT NOT NULL DEFAULT '{}',
8
+ script_id TEXT,
9
+ line_number INTEGER,
10
+ wall_time REAL,
11
+ monotonic_time REAL,
12
+ request_id TEXT,
13
+ sequence INTEGER
14
+ );
15
+ CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
16
+ CREATE INDEX IF NOT EXISTS idx_events_category_type ON events(category, event_type);
17
+ CREATE INDEX IF NOT EXISTS idx_events_script_id ON events(script_id);
18
+ CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);
19
+
20
+ CREATE TABLE IF NOT EXISTS memory_deltas (
21
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
22
+ timestamp REAL NOT NULL,
23
+ address TEXT NOT NULL,
24
+ old_value TEXT NOT NULL,
25
+ new_value TEXT NOT NULL,
26
+ size INTEGER NOT NULL,
27
+ value_type TEXT NOT NULL
28
+ );
29
+ CREATE INDEX IF NOT EXISTS idx_memory_timestamp ON memory_deltas(timestamp);
30
+ CREATE INDEX IF NOT EXISTS idx_memory_address ON memory_deltas(address);
31
+
32
+ CREATE TABLE IF NOT EXISTS heap_snapshots (
33
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
34
+ timestamp REAL NOT NULL,
35
+ snapshot_data BLOB,
36
+ summary TEXT NOT NULL DEFAULT '{}'
37
+ );
38
+
39
+ CREATE TABLE IF NOT EXISTS metadata (
40
+ key TEXT PRIMARY KEY,
41
+ value TEXT NOT NULL
42
+ );
43
+
44
+ CREATE TABLE IF NOT EXISTS network_resources (
45
+ request_id TEXT PRIMARY KEY,
46
+ url TEXT,
47
+ method TEXT,
48
+ resource_type TEXT,
49
+ request_headers TEXT NOT NULL DEFAULT '{}',
50
+ request_post_data TEXT,
51
+ status INTEGER,
52
+ status_text TEXT,
53
+ response_headers TEXT NOT NULL DEFAULT '{}',
54
+ mime_type TEXT,
55
+ protocol TEXT,
56
+ remote_address TEXT,
57
+ from_disk_cache INTEGER NOT NULL DEFAULT 0,
58
+ from_service_worker INTEGER NOT NULL DEFAULT 0,
59
+ started_wall_time REAL,
60
+ response_wall_time REAL,
61
+ finished_wall_time REAL,
62
+ started_monotonic_time REAL,
63
+ response_monotonic_time REAL,
64
+ finished_monotonic_time REAL,
65
+ encoded_data_length INTEGER,
66
+ received_data_length INTEGER NOT NULL DEFAULT 0,
67
+ received_encoded_data_length INTEGER NOT NULL DEFAULT 0,
68
+ chunk_count INTEGER NOT NULL DEFAULT 0,
69
+ streaming_enabled INTEGER NOT NULL DEFAULT 0,
70
+ streaming_supported INTEGER,
71
+ streaming_error TEXT,
72
+ body_capture_state TEXT NOT NULL DEFAULT 'none',
73
+ body_inline TEXT,
74
+ body_artifact_path TEXT,
75
+ body_base64_encoded INTEGER NOT NULL DEFAULT 0,
76
+ body_size INTEGER,
77
+ body_truncated INTEGER NOT NULL DEFAULT 0,
78
+ body_error TEXT,
79
+ failed INTEGER NOT NULL DEFAULT 0,
80
+ error_text TEXT
81
+ );
82
+ CREATE INDEX IF NOT EXISTS idx_network_resources_started_wall_time
83
+ ON network_resources(started_wall_time);
84
+
85
+ CREATE TABLE IF NOT EXISTS network_chunks (
86
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
87
+ request_id TEXT NOT NULL,
88
+ sequence INTEGER NOT NULL,
89
+ timestamp REAL NOT NULL,
90
+ monotonic_time REAL,
91
+ data_length INTEGER NOT NULL,
92
+ encoded_data_length INTEGER NOT NULL,
93
+ chunk_data TEXT,
94
+ chunk_is_base64 INTEGER NOT NULL DEFAULT 0
95
+ );
96
+ CREATE INDEX IF NOT EXISTS idx_network_chunks_request_sequence
97
+ ON network_chunks(request_id, sequence);
98
+ CREATE INDEX IF NOT EXISTS idx_network_chunks_timestamp
99
+ ON network_chunks(timestamp);
100
+ `),E(e,`events`,`wall_time`,`REAL`),E(e,`events`,`monotonic_time`,`REAL`),E(e,`events`,`request_id`,`TEXT`),E(e,`events`,`sequence`,`INTEGER`)}function S(e){return{insertEventStmt:e.prepare(`
101
+ INSERT INTO events (
102
+ timestamp,
103
+ category,
104
+ event_type,
105
+ data,
106
+ script_id,
107
+ line_number,
108
+ wall_time,
109
+ monotonic_time,
110
+ request_id,
111
+ sequence
112
+ )
113
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
114
+ `),insertDeltaStmt:e.prepare(`
115
+ INSERT INTO memory_deltas (timestamp, address, old_value, new_value, size, value_type)
116
+ VALUES (?, ?, ?, ?, ?, ?)
117
+ `),insertSnapshotStmt:e.prepare(`
118
+ INSERT INTO heap_snapshots (timestamp, snapshot_data, summary)
119
+ VALUES (?, ?, ?)
120
+ `),upsertMetadataStmt:e.prepare(`
121
+ INSERT INTO metadata (key, value) VALUES (?, ?)
122
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
123
+ `),upsertNetworkResourceStmt:e.prepare(`
124
+ INSERT INTO network_resources (
125
+ request_id,
126
+ url,
127
+ method,
128
+ resource_type,
129
+ request_headers,
130
+ request_post_data,
131
+ status,
132
+ status_text,
133
+ response_headers,
134
+ mime_type,
135
+ protocol,
136
+ remote_address,
137
+ from_disk_cache,
138
+ from_service_worker,
139
+ started_wall_time,
140
+ response_wall_time,
141
+ finished_wall_time,
142
+ started_monotonic_time,
143
+ response_monotonic_time,
144
+ finished_monotonic_time,
145
+ encoded_data_length,
146
+ received_data_length,
147
+ received_encoded_data_length,
148
+ chunk_count,
149
+ streaming_enabled,
150
+ streaming_supported,
151
+ streaming_error,
152
+ body_capture_state,
153
+ body_inline,
154
+ body_artifact_path,
155
+ body_base64_encoded,
156
+ body_size,
157
+ body_truncated,
158
+ body_error,
159
+ failed,
160
+ error_text
161
+ )
162
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
163
+ ON CONFLICT(request_id) DO UPDATE SET
164
+ url = excluded.url,
165
+ method = excluded.method,
166
+ resource_type = excluded.resource_type,
167
+ request_headers = excluded.request_headers,
168
+ request_post_data = excluded.request_post_data,
169
+ status = excluded.status,
170
+ status_text = excluded.status_text,
171
+ response_headers = excluded.response_headers,
172
+ mime_type = excluded.mime_type,
173
+ protocol = excluded.protocol,
174
+ remote_address = excluded.remote_address,
175
+ from_disk_cache = excluded.from_disk_cache,
176
+ from_service_worker = excluded.from_service_worker,
177
+ started_wall_time = excluded.started_wall_time,
178
+ response_wall_time = excluded.response_wall_time,
179
+ finished_wall_time = excluded.finished_wall_time,
180
+ started_monotonic_time = excluded.started_monotonic_time,
181
+ response_monotonic_time = excluded.response_monotonic_time,
182
+ finished_monotonic_time = excluded.finished_monotonic_time,
183
+ encoded_data_length = excluded.encoded_data_length,
184
+ received_data_length = excluded.received_data_length,
185
+ received_encoded_data_length = excluded.received_encoded_data_length,
186
+ chunk_count = excluded.chunk_count,
187
+ streaming_enabled = excluded.streaming_enabled,
188
+ streaming_supported = excluded.streaming_supported,
189
+ streaming_error = excluded.streaming_error,
190
+ body_capture_state = excluded.body_capture_state,
191
+ body_inline = excluded.body_inline,
192
+ body_artifact_path = excluded.body_artifact_path,
193
+ body_base64_encoded = excluded.body_base64_encoded,
194
+ body_size = excluded.body_size,
195
+ body_truncated = excluded.body_truncated,
196
+ body_error = excluded.body_error,
197
+ failed = excluded.failed,
198
+ error_text = excluded.error_text
199
+ `),insertNetworkChunkStmt:e.prepare(`
200
+ INSERT INTO network_chunks (
201
+ request_id,
202
+ sequence,
203
+ timestamp,
204
+ monotonic_time,
205
+ data_length,
206
+ encoded_data_length,
207
+ chunk_data,
208
+ chunk_is_base64
209
+ )
210
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
211
+ `)}}function C(e){return{id:e.id,timestamp:e.timestamp,category:e.category,eventType:e.event_type,data:e.data,scriptId:e.script_id??null,lineNumber:e.line_number??null,wallTime:e.wall_time??null,monotonicTime:e.monotonic_time??null,requestId:e.request_id??null,sequence:e.sequence??null}}function w(e,t){return{id:e.id,requestId:e.request_id,sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonic_time??null,dataLength:e.data_length,encodedDataLength:e.encoded_data_length,chunkData:e.chunk_data??null,chunkIsBase64:t(e.chunk_is_base64)}}function T(e,t){return{requestId:e.request_id,url:e.url??null,method:e.method??null,resourceType:e.resource_type??null,requestHeaders:e.request_headers??`{}`,requestPostData:e.request_post_data??null,status:e.status??null,statusText:e.status_text??null,responseHeaders:e.response_headers??`{}`,mimeType:e.mime_type??null,protocol:e.protocol??null,remoteAddress:e.remote_address??null,fromDiskCache:t(e.from_disk_cache),fromServiceWorker:t(e.from_service_worker),startedWallTime:e.started_wall_time??null,responseWallTime:e.response_wall_time??null,finishedWallTime:e.finished_wall_time??null,startedMonotonicTime:e.started_monotonic_time??null,responseMonotonicTime:e.response_monotonic_time??null,finishedMonotonicTime:e.finished_monotonic_time??null,encodedDataLength:e.encoded_data_length??null,receivedDataLength:e.received_data_length??0,receivedEncodedDataLength:e.received_encoded_data_length??0,chunkCount:e.chunk_count??0,streamingEnabled:t(e.streaming_enabled),streamingSupported:e.streaming_supported===null||e.streaming_supported===void 0?null:t(e.streaming_supported),streamingError:e.streaming_error??null,bodyCaptureState:e.body_capture_state??`none`,bodyInline:e.body_inline??null,bodyArtifactPath:e.body_artifact_path??null,bodyBase64Encoded:t(e.body_base64_encoded),bodySize:e.body_size??null,bodyTruncated:t(e.body_truncated),bodyError:e.body_error??null,failed:t(e.failed),errorText:e.error_text??null}}function E(e,t,n,r){e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)||e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`)}let D;try{D=e(`better-sqlite3`)}catch{}const O=/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|ATTACH|DETACH|REPLACE|PRAGMA)\b/i;var k=class{options;db;batchSize;eventBuffer=[];memoryBuffer=[];networkChunkBuffer=[];closed=!1;insertEventStmt;insertDeltaStmt;insertSnapshotStmt;upsertMetadataStmt;upsertNetworkResourceStmt;insertNetworkChunkStmt;constructor(e){if(this.options=e,!D)throw Error(n(Error(`Cannot find package 'better-sqlite3'`)));try{this.db=new D(e.dbPath)}catch(e){throw Error(n(e),{cause:e})}this.batchSize=e.batchSize??200,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`synchronous = NORMAL`),x(this.db);let t=S(this.db);this.insertEventStmt=t.insertEventStmt,this.insertDeltaStmt=t.insertDeltaStmt,this.insertSnapshotStmt=t.insertSnapshotStmt,this.upsertMetadataStmt=t.upsertMetadataStmt,this.upsertNetworkResourceStmt=t.upsertNetworkResourceStmt,this.insertNetworkChunkStmt=t.insertNetworkChunkStmt}get dbPath(){return this.options.dbPath}insertEvent(e){this.ensureOpen(),this.eventBuffer.push(e),this.eventBuffer.length>=this.batchSize&&this.flush()}insertMemoryDelta(e){this.ensureOpen(),this.memoryBuffer.push(e),this.memoryBuffer.length>=this.batchSize&&this.flush()}insertNetworkChunk(e){this.ensureOpen(),this.networkChunkBuffer.push(e),this.networkChunkBuffer.length>=this.batchSize&&this.flush()}upsertNetworkResource(e){this.ensureOpen(),this.upsertNetworkResourceStmt.run(e.requestId,e.url,e.method,e.resourceType,e.requestHeaders,e.requestPostData,e.status,e.statusText,e.responseHeaders,e.mimeType,e.protocol,e.remoteAddress,+!!e.fromDiskCache,+!!e.fromServiceWorker,e.startedWallTime,e.responseWallTime,e.finishedWallTime,e.startedMonotonicTime,e.responseMonotonicTime,e.finishedMonotonicTime,e.encodedDataLength,e.receivedDataLength,e.receivedEncodedDataLength,e.chunkCount,+!!e.streamingEnabled,e.streamingSupported===null?null:+!!e.streamingSupported,e.streamingError,e.bodyCaptureState,e.bodyInline,e.bodyArtifactPath,+!!e.bodyBase64Encoded,e.bodySize,+!!e.bodyTruncated,e.bodyError,+!!e.failed,e.errorText)}insertHeapSnapshot(e){this.ensureOpen(),this.insertSnapshotStmt.run(e.timestamp,e.snapshotData,e.summary)}setMetadata(e,t){this.ensureOpen(),this.upsertMetadataStmt.run(e,t)}flush(){this.closed||(this.db.transaction(()=>{for(let e of this.eventBuffer)this.insertEventStmt.run(e.timestamp,e.category,e.eventType,e.data,e.scriptId,e.lineNumber,e.wallTime??null,e.monotonicTime??null,e.requestId??null,e.sequence??null);for(let e of this.memoryBuffer)this.insertDeltaStmt.run(e.timestamp,e.address,e.oldValue,e.newValue,e.size,e.valueType);for(let e of this.networkChunkBuffer)this.insertNetworkChunkStmt.run(e.requestId,e.sequence,e.timestamp,e.monotonicTime,e.dataLength,e.encodedDataLength,e.chunkData,+!!e.chunkIsBase64)})(),this.eventBuffer=[],this.memoryBuffer=[],this.networkChunkBuffer=[])}query(e){if(this.ensureOpen(),O.test(e))throw Error(`Write operations are not allowed in trace queries. Rejected SQL: ${e.slice(0,100)}`);let t=this.db.prepare(e),n=t.all();if(n.length===0)return{columns:t.columns().map(e=>e.name),rows:[],rowCount:0};let r=Object.keys(n[0]);return{columns:r,rows:n.map(e=>r.map(t=>e[t])),rowCount:n.length}}getEventsByTimeRange(e,t){return this.ensureOpen(),this.flush(),this.db.prepare(`
212
+ SELECT
213
+ id,
214
+ timestamp,
215
+ category,
216
+ event_type,
217
+ data,
218
+ script_id,
219
+ line_number,
220
+ wall_time,
221
+ monotonic_time,
222
+ request_id,
223
+ sequence
224
+ FROM events
225
+ WHERE timestamp >= ? AND timestamp <= ?
226
+ ORDER BY timestamp ASC, sequence ASC, id ASC
227
+ `).all(e,t).map(C)}getEventsByRequestId(e){return this.ensureOpen(),this.flush(),this.db.prepare(`
228
+ SELECT
229
+ id,
230
+ timestamp,
231
+ category,
232
+ event_type,
233
+ data,
234
+ script_id,
235
+ line_number,
236
+ wall_time,
237
+ monotonic_time,
238
+ request_id,
239
+ sequence
240
+ FROM events
241
+ WHERE request_id = ?
242
+ ORDER BY COALESCE(monotonic_time, timestamp) ASC, sequence ASC, id ASC
243
+ `).all(e).map(C)}getNetworkResource(e){this.ensureOpen(),this.flush();let t=this.db.prepare(`
244
+ SELECT *
245
+ FROM network_resources
246
+ WHERE request_id = ?
247
+ LIMIT 1
248
+ `).get(e);return t?T(t,this.fromSqliteBoolean):null}getNetworkChunks(e,t){this.ensureOpen(),this.flush();let n=`
249
+ SELECT
250
+ id,
251
+ request_id,
252
+ sequence,
253
+ timestamp,
254
+ monotonic_time,
255
+ data_length,
256
+ encoded_data_length,
257
+ chunk_data,
258
+ chunk_is_base64
259
+ FROM network_chunks
260
+ WHERE request_id = ?
261
+ ORDER BY sequence ASC
262
+ ${typeof t==`number`?`LIMIT ?`:``}
263
+ `,r=this.db.prepare(n);return(typeof t==`number`?r.all(e,t):r.all(e)).map(e=>w(e,this.fromSqliteBoolean))}getMemoryDeltasByAddress(e){return this.ensureOpen(),this.flush(),this.db.prepare(`
264
+ SELECT id, timestamp, address, old_value, new_value, size, value_type
265
+ FROM memory_deltas
266
+ WHERE address = ?
267
+ ORDER BY timestamp ASC
268
+ `).all(e).map(e=>({id:e.id,timestamp:e.timestamp,address:e.address,oldValue:e.old_value,newValue:e.new_value,size:e.size,valueType:e.value_type}))}getHeapSnapshots(){return this.ensureOpen(),this.db.prepare(`
269
+ SELECT id, timestamp, snapshot_data, summary
270
+ FROM heap_snapshots
271
+ ORDER BY timestamp ASC
272
+ `).all().map(e=>({id:e.id,timestamp:e.timestamp,snapshotData:e.snapshot_data,summary:e.summary}))}getMetadata(){this.ensureOpen();let e=this.db.prepare(`SELECT key, value FROM metadata`).all(),t={};for(let n of e)t[n.key]=n.value;return t}close(){this.closed||=(this.flush(),this.db.close(),!0)}get isClosed(){return this.closed}fromSqliteBoolean(e){return e===1||e===!0}ensureOpen(){if(this.closed)throw Error(`TraceDB is closed`)}},A=class{db=null;state=`idle`;session=null;eventBusUnsub=null;cdpListeners=new Map;enabledCdpDomains=new Set;cdpSession=null;ownsCdpSession=!1;eventCount=0;memoryDeltaCount=0;heapSnapshotCount=0;eventSequence=0;pendingOperations=new Set;networkCapture=new b({getDb:()=>this.db,getCdpSession:()=>this.cdpSession,trackOperation:e=>this.trackOperation(e)});async start(e,n,i){if(this.state===`recording`)throw Error(`Recording already in progress`);let s=r(),{absolutePath:c}=await t({category:`traces`,toolName:`trace_recorder`,target:s.slice(0,8),ext:`db`}),l=n?(i?.cdpDomains??o).filter(e=>a[e]):[];this.db=new k({dbPath:c}),this.eventCount=0,this.memoryDeltaCount=0,this.heapSnapshotCount=0,this.eventSequence=0,this.pendingOperations.clear(),this.cdpListeners.clear(),this.enabledCdpDomains.clear(),this.cdpSession=n,this.ownsCdpSession=i?.ownsSession??!1;try{let t=this.networkCapture.configure(i?.network);if(n)for(let e of l)await n.send(`${e}.enable`),this.enabledCdpDomains.add(e);let r=Date.now();if(this.db.setMetadata(`sessionId`,s),this.db.setMetadata(`platform`,process.platform),this.db.setMetadata(`startedAt`,String(r)),this.db.setMetadata(`nodeVersion`,process.version),this.db.setMetadata(`network.recordResponseBodies`,String(t.recordResponseBodies)),this.db.setMetadata(`network.streamResponseChunks`,String(t.streamResponseChunks)),this.db.setMetadata(`network.maxBodyBytes`,String(t.maxBodyBytes)),this.db.setMetadata(`network.inlineBodyBytes`,String(t.inlineBodyBytes)),this.eventBusUnsub=e.onAny(e=>{if(this.state===`recording`)try{let t=Date.now();this.db?.insertEvent({timestamp:t,wallTime:t,monotonicTime:null,category:this.mapEventCategory(String(e.event)),eventType:String(e.event),data:JSON.stringify(e.payload??{}),scriptId:null,lineNumber:null,requestId:null,sequence:this.nextSequence()}),this.eventCount++}catch{}}),n)for(let e of l){let t=a[e]??[];for(let r of t){let t=t=>{if(!(this.state!==`recording`||!this.db))try{let n=m(t),i=h(t),{scriptId:a,lineNumber:o}=g(r,t),s=JSON.stringify(_(r,t));this.db.insertEvent({timestamp:n.timestamp,wallTime:n.wallTime,monotonicTime:n.monotonicTime,category:e.toLowerCase(),eventType:r,data:s,scriptId:a,lineNumber:o,requestId:i,sequence:this.nextSequence()}),this.eventCount++,e===`Network`&&this.networkCapture.handleEvent(r,t,n)}catch{}};n.on(r,t),this.cdpListeners.set(r,t)}}return this.session={sessionId:s,dbPath:c,startedAt:r,eventCount:0,memoryDeltaCount:0,heapSnapshotCount:0,...this.networkCapture.getCounts()},this.state=`recording`,{...this.session}}catch(e){throw await this.cleanupFailedStart(),e}}recordMemoryDelta(e){if(!(this.state!==`recording`||!this.db))try{this.db.insertMemoryDelta(e),this.memoryDeltaCount++}catch{}}async captureActiveHeapSnapshot(){if(!this.cdpSession)throw Error(`Cannot capture heap snapshot: no active CDP session`);return await this.captureHeapSnapshot(this.cdpSession)}async captureHeapSnapshot(e){if(this.state!==`recording`||!this.db)throw Error(`Cannot capture heap snapshot: not recording`);let t=[],n=!1,r=e=>{if(typeof e==`object`&&e){let n=e.chunk;typeof n==`string`&&t.push(n)}};try{await e.send(`HeapProfiler.enable`),e.on(`HeapProfiler.addHeapSnapshotChunk`,r),n=!0,await e.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1});let i=t.join(``),a=Buffer.from(i,`utf-8`),o=this.extractHeapSummary(i);return this.db.insertHeapSnapshot({timestamp:Date.now(),snapshotData:a,summary:JSON.stringify(o)}),this.heapSnapshotCount++,a.byteLength}finally{n&&e.off(`HeapProfiler.addHeapSnapshotChunk`,r),await e.send(`HeapProfiler.disable`).catch(()=>{})}}async stop(){if(this.state!==`recording`)throw Error(`GRACEFUL: Cannot stop: not currently recording`);if(this.eventBusUnsub&&=(this.eventBusUnsub(),null),this.cdpSession)for(let[e,t]of this.cdpListeners)this.cdpSession.off(e,t);this.cdpListeners.clear(),await this.waitForPendingOperations();let e;if(this.cdpSession){if(this.enabledCdpDomains.size>0){let t=Array.from(this.enabledCdpDomains);e=(await Promise.allSettled(t.map(e=>this.cdpSession.send(`${e}.disable`)))).flatMap((e,n)=>e.status===`rejected`?[`${t[n]}.disable failed: ${e.reason instanceof Error?e.reason.message:String(e.reason)}`]:[])}if(this.enabledCdpDomains.clear(),this.ownsCdpSession&&typeof this.cdpSession.detach==`function`)try{await this.cdpSession.detach()}catch(t){(e??=[]).push(`cdpSession.detach failed: ${t instanceof Error?t.message:String(t)}`)}this.cdpSession=null,this.ownsCdpSession=!1}if(this.db){let t=Date.now(),n=this.networkCapture.getCounts();this.db.setMetadata(`stoppedAt`,String(t)),this.db.setMetadata(`eventCount`,String(this.eventCount)),this.db.setMetadata(`memoryDeltaCount`,String(this.memoryDeltaCount)),this.db.setMetadata(`heapSnapshotCount`,String(this.heapSnapshotCount)),this.db.setMetadata(`networkRequestCount`,String(n.networkRequestCount)),this.db.setMetadata(`networkChunkCount`,String(n.networkChunkCount)),this.db.setMetadata(`networkBodyCount`,String(n.networkBodyCount)),this.db.close(),this.session&&(this.session.stoppedAt=t,this.session.eventCount=this.eventCount,this.session.memoryDeltaCount=this.memoryDeltaCount,this.session.heapSnapshotCount=this.heapSnapshotCount,this.session.networkRequestCount=n.networkRequestCount,this.session.networkChunkCount=n.networkChunkCount,this.session.networkBodyCount=n.networkBodyCount,e&&e.length>0?this.session.cleanupErrors=e:delete this.session.cleanupErrors)}this.state=`stopped`;let t=this.session?{...this.session}:this.createEmptySession();return this.db=null,this.networkCapture.clear(),t}getState(){return this.state}getSession(){return this.session?{...this.session}:null}getDB(){return this.db}trackOperation(e){this.pendingOperations.add(e),e.finally(()=>{this.pendingOperations.delete(e)})}async waitForPendingOperations(){for(;this.pendingOperations.size>0;)await Promise.allSettled(Array.from(this.pendingOperations))}async cleanupFailedStart(){if(this.eventBusUnsub&&=(this.eventBusUnsub(),null),this.cdpSession)for(let[e,t]of this.cdpListeners)this.cdpSession.off(e,t);if(this.cdpListeners.clear(),this.cdpSession&&this.enabledCdpDomains.size>0&&await Promise.allSettled(Array.from(this.enabledCdpDomains).map(e=>this.cdpSession.send(`${e}.disable`))),this.enabledCdpDomains.clear(),this.cdpSession&&this.ownsCdpSession&&typeof this.cdpSession.detach==`function`&&await this.cdpSession.detach().catch(()=>{}),this.cdpSession=null,this.ownsCdpSession=!1,this.db){try{this.db.close()}catch{}this.db=null}this.session=null,this.state=`idle`,this.eventCount=0,this.memoryDeltaCount=0,this.heapSnapshotCount=0,this.eventSequence=0,this.pendingOperations.clear(),this.networkCapture.clear()}nextSequence(){return this.eventSequence+=1,this.eventSequence}mapEventCategory(e){let t=e.indexOf(`:`);return t>0?e.substring(0,t):`other`}extractHeapSummary(e){try{let t=JSON.parse(e),n=t.snapshot;if(!n)return{totalSize:0,nodeCount:0,objectCounts:{}};let r=n.meta,i=n.node_count??0,a=r?.node_fields,o=r?.node_types,s=t.nodes,c={},l=0;if(a&&s&&o){let e=a.length,n=a.indexOf(`type`),r=a.indexOf(`name`),i=a.indexOf(`self_size`),o=t.strings??[];for(let t=0;t<s.length;t+=e){let e=i>=0?s[t+i]??0:0;if(l+=e,r>=0){let e=o[s[t+r]??0]??`type_${s[t+(n>=0?n:0)]}`;e&&(c[e]=(c[e]??0)+1)}}}return{totalSize:l,nodeCount:i,objectCounts:c}}catch{return{totalSize:0,nodeCount:0,objectCounts:{}}}}createEmptySession(){return{sessionId:``,dbPath:``,startedAt:0,eventCount:0,memoryDeltaCount:0,heapSnapshotCount:0,networkRequestCount:0,networkChunkCount:0,networkBodyCount:0}}};export{A as TraceRecorder,k as t};
@@ -0,0 +1,9 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";var t=e({VersionDetector:()=>o});function n(e){return typeof e==`object`&&!!e}function r(e){return n(e)&&typeof e.createCDPSession==`function`}function i(e,t){let n=e[t];return typeof n==`string`?n:null}function a(e){if(typeof e==`boolean`)return e;if(n(e)){let t=e.value;return typeof t==`boolean`?t:!1}return!1}var o=class{getPage;constructor(e){this.getPage=e}async detectV8Version(){return await this.detectBrowserVersion()||(typeof process.versions.v8==`string`&&process.versions.v8.length>0?this.parseV8Version(process.versions.v8):null)}parseV8Version(e){let t=/(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:\.(?<commit>[A-Za-z0-9._-]+))?/u.exec(e.trim());if(!t?.groups)return{major:0,minor:0,patch:0,commit:``};let n=Number(t.groups.major??0),r=Number(t.groups.minor??0),i=Number(t.groups.patch??0);return{major:Number.isFinite(n)?n:0,minor:Number.isFinite(r)?r:0,patch:Number.isFinite(i)?i:0,commit:t.groups.commit??``}}async supportsNativesSyntax(){if(process.execArgv.includes(`--allow-natives-syntax`))return!0;let e=await this.createSession();if(!e)return!1;try{let t=await e.send(`Runtime.evaluate`,{expression:`
2
+ (() => {
3
+ try {
4
+ return Boolean(new Function("return %HaveSameMap({}, {})")());
5
+ } catch (error) {
6
+ return false;
7
+ }
8
+ })()
9
+ `,returnByValue:!0,awaitPromise:!1});return n(t)?a(t.result):!1}catch{return!1}finally{await e.detach().catch(()=>void 0)}}async detectBrowserVersion(){let e=await this.createSession();if(!e)return null;try{let t=await e.send(`Browser.getVersion`);if(!n(t))return null;let r=i(t,`jsVersion`);if(r)return this.parseV8Version(r);let a=i(t,`product`);return a?this.parseV8Version(a):null}catch{return null}finally{await e.detach().catch(()=>void 0)}}async createSession(){if(!this.getPage)return null;try{let e=await this.getPage();return r(e)?await e.createCDPSession():null}catch{return null}}};export{t as n,o as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import n from"koffi";var r=e({CloseHandle:()=>v,CreateRemoteThread:()=>T,EnumProcessModules:()=>A,GetLastError:()=>O,GetModuleBaseName:()=>j,GetModuleFileNameEx:()=>M,GetModuleHandle:()=>E,GetModuleInformation:()=>N,GetProcAddress:()=>D,MEM:()=>a,NtQueryInformationProcess:()=>k,OpenProcess:()=>_,PAGE:()=>o,PROCESS_ACCESS:()=>i,ReadProcessMemory:()=>y,VirtualAllocEx:()=>C,VirtualFreeEx:()=>w,VirtualProtectEx:()=>S,VirtualQueryEx:()=>x,WriteProcessMemory:()=>b,isKoffiAvailable:()=>d,isWindows:()=>f,openProcessForMemory:()=>P});const i={TERMINATE:1,CREATE_THREAD:2,SET_SESSIONID:4,VM_OPERATION:8,VM_READ:16,VM_WRITE:32,DUP_HANDLE:64,CREATE_PROCESS:128,SET_QUOTA:256,SET_INFORMATION:512,QUERY_INFORMATION:1024,SUSPEND_RESUME:2048,QUERY_LIMITED_INFORMATION:4096,ALL_ACCESS:2035711},a={COMMIT:4096,RESERVE:8192,DECOMMIT:16384,RELEASE:32768,FREE:65536,PRIVATE:131072,MAPPED:262144,RESET:524288,TOP_DOWN:1048576,WRITE_WATCH:2097152,PHYSICAL:4194304,LARGE_PAGES:536870912},o={NOACCESS:1,READONLY:2,READWRITE:4,WRITECOPY:8,EXECUTE:16,EXECUTE_READ:32,EXECUTE_READWRITE:64,EXECUTE_WRITECOPY:128,GUARD:256,NOCACHE:512,WRITECOMBINE:1024};let s=null,c=null,l=null,u=null;function d(){if(u!==null)return u;try{return n.load(`kernel32.dll`).unload(),u=!0,!0}catch{return u=!1,!1}}function f(){return process.platform===`win32`}function p(){return s||(s=n.load(`kernel32.dll`),t.debug(`Loaded kernel32.dll via koffi`)),s}function m(){return c||(c=n.load(`ntdll.dll`),t.debug(`Loaded ntdll.dll via koffi`)),c}function h(){return l||(l=n.load(`psapi.dll`),t.debug(`Loaded psapi.dll via koffi`)),l}function g(e){return e==null?0n:typeof e==`bigint`?e:typeof e==`number`?BigInt(e):n.address(e)}function _(e,t,n){return g(p().func(`void * OpenProcess(uint32, int, uint32)`)(e,+!!t,n))}function v(e){return p().func(`int CloseHandle(void *)`)(e)!==0}function y(e,t,n){let r=p().func(`int ReadProcessMemory(void *, void *, _Out_ uint8_t *, size_t, _Out_ size_t *)`),i=Buffer.alloc(n),a=Buffer.alloc(8);if(r(e,t,i,BigInt(n),a)===0){let e=O();throw Error(`ReadProcessMemory failed. Error: 0x${e.toString(16)}`)}return i}function b(e,t,n){let r=p().func(`int WriteProcessMemory(void *, void *, uint8_t *, size_t, _Out_ size_t *)`),i=Buffer.alloc(8);if(r(e,t,n,BigInt(n.length),i)===0){let e=O();throw Error(`WriteProcessMemory failed. Error: 0x${e.toString(16)}`)}return Number(i.readBigUInt64LE())}function x(e,t){let n=p().func(`size_t VirtualQueryEx(void *, void *, _Out_ uint8_t *, size_t)`),r=Buffer.alloc(48),i=n(e,t,r,BigInt(48));return Number(i)===48?{success:!0,info:{BaseAddress:r.readBigUInt64LE(0),AllocationBase:r.readBigUInt64LE(8),AllocationProtect:r.readUInt32LE(16),RegionSize:r.readBigUInt64LE(24),State:r.readUInt32LE(32),Protect:r.readUInt32LE(36),Type:r.readUInt32LE(40)}}:{success:!1,info:{}}}function S(e,t,n,r){let i=p().func(`int VirtualProtectEx(void *, void *, size_t, uint32, _Out_ uint32 *)`),a=Buffer.alloc(4);return{success:i(e,t,BigInt(n),r,a)!==0,oldProtect:a.readUInt32LE(0)}}function C(e,t,n,r,i){return g(p().func(`void * VirtualAllocEx(void *, void *, size_t, uint32, uint32)`)(e,t,BigInt(n),r,i))}function w(e,t,n,r){return p().func(`int VirtualFreeEx(void *, void *, size_t, uint32)`)(e,t,BigInt(n),r)!==0}function T(e,t,n){let r=p().func(`void * CreateRemoteThread(void *, void *, size_t, void *, void *, uint32, _Out_ uint32 *)`),i=Buffer.alloc(4);return{handle:g(r(e,null,0n,t,n,0,i)),threadId:i.readUInt32LE(0)}}function E(e){return g(p().func(`void * GetModuleHandleA(char *)`)(e))}function D(e,t){return g(p().func(`void * GetProcAddress(void *, char *)`)(e,t))}function O(){return p().func(`uint32 GetLastError()`)()}function k(e,t){let n=m().func(`int32 NtQueryInformationProcess(void *, uint32, _Out_ void *, uint32, void *)`),r=Buffer.alloc(8);return{status:n(e,t,r,8,null),debugPort:Number(r.readBigUInt64LE())}}function A(e,t=1024){let n=h().func(`int EnumProcessModules(void *, _Out_ void *, uint32, _Out_ uint32 *)`),r=Buffer.alloc(t*8),i=Buffer.alloc(4),a=n(e,r,t*8,i),o=i.readUInt32LE(0),s=Math.floor(o/8),c=[];for(let e=0;e<s;e++)c.push(r.readBigUInt64LE(e*8));return{success:a!==0,modules:c,count:s}}function j(e,t,n=260){let r=h().func(`uint32 GetModuleBaseNameA(void *, void *, _Out_ char *, uint32)`),i=Buffer.alloc(n);r(e,t,i,n);let a=0;for(;a<n&&i[a]!==0;)a++;return i.toString(`utf8`,0,a)}function M(e,t,n=32768){let r=h().func(`uint32 GetModuleFileNameExA(void *, void *, _Out_ char *, uint32)`),i=Buffer.alloc(n),a=r(e,t,i,n);if(typeof a!=`number`||a<=0)return null;let o=0;for(;o<n&&i[o]!==0;)o++;return o>0?i.toString(`utf8`,0,o):null}function N(e,t){let n=h().func(`int GetModuleInformation(void *, void *, _Out_ uint8_t *, uint32)`),r=Buffer.alloc(24),i=n(e,t,r,24),a={lpBaseOfDll:r.readBigUInt64LE(0),SizeOfImage:r.readUInt32LE(8),EntryPoint:r.readBigUInt64LE(16)};return{success:i!==0,info:a}}function P(e,t=!1){let n=_(t?i.VM_READ|i.VM_WRITE|i.VM_OPERATION|i.QUERY_INFORMATION:i.VM_READ|i.QUERY_INFORMATION,!1,e);if(n===0n){let t=O();throw Error(`Failed to open process ${e}. Error: 0x${t.toString(16)}. Run as Administrator.`)}return n}export{b as _,M as a,P as b,D as c,y as d,C as f,r as g,x as h,j as i,a as l,S as m,A as n,E as o,w as p,O as r,N as s,v as t,o as u,d as v,f as y};
@@ -0,0 +1 @@
1
+ import{t as e}from"./logger-sBC6IdRT.mjs";import{r as t,t as n}from"./Win32API-Bhi5xFBe.mjs";import r from"koffi";const i={TERMINATE:1,SUSPEND_RESUME:2,GET_CONTEXT:8,SET_CONTEXT:16,SET_INFORMATION:32,QUERY_INFORMATION:64,SET_THREAD_TOKEN:128,IMPERSONATE:256,DIRECT_IMPERSONATION:512,ALL_ACCESS:2032639},a={AMD64:1048576,CONTROL:1048577,INTEGER:1048578,SEGMENTS:1048580,FLOATING_POINT:1048584,DEBUG_REGISTERS:1048592,FULL:1048587,ALL:1048607},o={EXCEPTION_DEBUG_EVENT:1,CREATE_THREAD_DEBUG_EVENT:2,CREATE_PROCESS_DEBUG_EVENT:3,EXIT_THREAD_DEBUG_EVENT:4,EXIT_PROCESS_DEBUG_EVENT:5,LOAD_DLL_DEBUG_EVENT:6,UNLOAD_DLL_DEBUG_EVENT:7,OUTPUT_DEBUG_STRING_EVENT:8,RIP_EVENT:9},s={SINGLE_STEP:2147483652,BREAKPOINT:2147483651,ACCESS_VIOLATION:3221225477},c={CONTINUE:65538,EXCEPTION_NOT_HANDLED:2147549185,REPLY_LATER:1073807361},l={SNAPHEAPLIST:1,SNAPTHREAD:4,SNAPMODULE:8};function u(e){return{contextFlags:e.readUInt32LE(48),eflags:e.readUInt32LE(68),dr0:e.readBigUInt64LE(72),dr1:e.readBigUInt64LE(80),dr2:e.readBigUInt64LE(88),dr3:e.readBigUInt64LE(96),dr6:e.readBigUInt64LE(104),dr7:e.readBigUInt64LE(112),rax:e.readBigUInt64LE(120),rcx:e.readBigUInt64LE(128),rdx:e.readBigUInt64LE(136),rbx:e.readBigUInt64LE(144),rsp:e.readBigUInt64LE(152),rbp:e.readBigUInt64LE(160),rsi:e.readBigUInt64LE(168),rdi:e.readBigUInt64LE(176),r8:e.readBigUInt64LE(184),r9:e.readBigUInt64LE(192),r10:e.readBigUInt64LE(200),r11:e.readBigUInt64LE(208),r12:e.readBigUInt64LE(216),r13:e.readBigUInt64LE(224),r14:e.readBigUInt64LE(232),r15:e.readBigUInt64LE(240),rip:e.readBigUInt64LE(248)}}function d(e,t){t.contextFlags!==void 0&&e.writeUInt32LE(t.contextFlags,48),t.eflags!==void 0&&e.writeUInt32LE(t.eflags,68),t.dr0!==void 0&&e.writeBigUInt64LE(t.dr0,72),t.dr1!==void 0&&e.writeBigUInt64LE(t.dr1,80),t.dr2!==void 0&&e.writeBigUInt64LE(t.dr2,88),t.dr3!==void 0&&e.writeBigUInt64LE(t.dr3,96),t.dr6!==void 0&&e.writeBigUInt64LE(t.dr6,104),t.dr7!==void 0&&e.writeBigUInt64LE(t.dr7,112),t.rip!==void 0&&e.writeBigUInt64LE(t.rip,248)}let f=null;function p(){return f||(f=r.load(`kernel32.dll`),e.debug(`Loaded kernel32.dll for debug APIs`)),f}function m(e,t,n){return p().func(`void * OpenThread(uint32, int, uint32)`)(e,+!!t,n)}function h(e){let n=p().func(`uint32 SuspendThread(void *)`)(e);if(n===4294967295)throw Error(`SuspendThread failed. Error: 0x${t().toString(16)}`);return n}function g(e){let n=p().func(`uint32 ResumeThread(void *)`)(e);if(n===4294967295)throw Error(`ResumeThread failed. Error: 0x${t().toString(16)}`);return n}function _(e,n){let r=p().func(`int GetThreadContext(void *, _Inout_ uint8_t[1232])`),i=Buffer.alloc(1232);if(i.writeUInt32LE(n,48),r(e,i)===0)throw Error(`GetThreadContext failed. Error: 0x${t().toString(16)}`);return i}function v(e,n){if(p().func(`int SetThreadContext(void *, uint8_t[1232])`)(e,n)===0)throw Error(`SetThreadContext failed. Error: 0x${t().toString(16)}`)}function y(e){if(p().func(`int DebugActiveProcess(uint32)`)(e)===0)throw Error(`DebugActiveProcess failed for pid ${e}. Error: 0x${t().toString(16)}`)}function b(e){if(p().func(`int DebugActiveProcessStop(uint32)`)(e)===0)throw Error(`DebugActiveProcessStop failed. Error: 0x${t().toString(16)}`)}function x(e){p().func(`int DebugSetProcessKillOnExit(int)`)(+!!e)}function S(e){let t=p().func(`int WaitForDebugEvent(_Out_ uint8_t *, uint32)`),n=Buffer.alloc(176);if(t(n,e)===0)return null;let r={debugEventCode:n.readUInt32LE(0),processId:n.readUInt32LE(4),threadId:n.readUInt32LE(8)};return r.debugEventCode===o.EXCEPTION_DEBUG_EVENT&&(r.exceptionCode=n.readUInt32LE(16),r.exceptionAddress=n.readBigUInt64LE(32),r.firstChance=n.readUInt32LE(20)===0),r}function C(e,n,r){if(p().func(`int ContinueDebugEvent(uint32, uint32, uint32)`)(e,n,r)===0)throw Error(`ContinueDebugEvent failed. Error: 0x${t().toString(16)}`)}function w(e,t,n){p().func(`int FlushInstructionCache(void *, void *, size_t)`)(e,t,BigInt(n))}function T(e){let r=p().func(`void * CreateToolhelp32Snapshot(uint32, uint32)`),i=p().func(`int Thread32First(void *, _Inout_ uint8_t[28])`),a=p().func(`int Thread32Next(void *, _Inout_ uint8_t[28])`),o=r(l.SNAPTHREAD,0);if(o===0n||o===BigInt(`0xFFFFFFFFFFFFFFFF`))throw Error(`CreateToolhelp32Snapshot failed. Error: 0x${t().toString(16)}`);let s=[],c=Buffer.alloc(28);c.writeUInt32LE(28,0);try{if(i(o,c)!==0)do c.readUInt32LE(12)===e&&s.push(c.readUInt32LE(8)),c.writeUInt32LE(28,0);while(a(o,c)!==0);n(o)}catch(e){console.error(`[EnumerateProcessThreads] cleanup error:`,e)}return s}function E(e){let n=m(i.SUSPEND_RESUME|i.GET_CONTEXT|i.SET_CONTEXT|i.QUERY_INFORMATION,!1,e);if(n===0n)throw Error(`Failed to open thread ${e}. Error: 0x${t().toString(16)}`);return n}function D(e){let t=0n;for(let n of e){if(!n.enabled)continue;let{drIndex:e,access:r,size:i}=n;t|=1n<<BigInt(e*2);let a=0;switch(r){case`execute`:a=0;break;case`write`:a=1;break;case`readwrite`:case`read`:a=3;break}t|=BigInt(a)<<BigInt(16+e*4);let o=0;switch(i){case 1:o=0;break;case 2:o=1;break;case 4:o=3;break;case 8:o=2;break}t|=BigInt(o)<<BigInt(18+e*4)}return t}export{E as _,b as a,T as c,g as d,v as f,D as g,S as h,y as i,w as l,l as m,C as n,x as o,h as p,c as r,s,a as t,_ as u,u as v,d as y};
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{l as n,o as r}from"./ToolRouter.policy-CFHoN_Lw.mjs";import{randomUUID as i}from"node:crypto";var a=class{store=new Map;set(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}getValueAtPath(e,t){let n=this.store.get(e);if(!n||typeof n!=`object`)return n;let r=o(n)||n;return t.split(`.`).reduce((e,t)=>{if(e&&typeof e==`object`){let n=t.match(/^(\d+)$/);return n&&Array.isArray(e)?e[Number(n[1])]:e[t]}},r)}resolve(e){let t=e.match(/^\$\{(.+)\}$/);if(!t||!t[1])return e;let n=t[1],r=n.indexOf(`.`);return r===-1?this.store.get(n):this.getValueAtPath(n.slice(0,r),n.slice(r+1))}};function o(e){if(!e||typeof e!=`object`)return;let t=e.content?.find(e=>e.type===`text`)?.text;if(typeof t==`string`)try{let e=JSON.parse(t);return e&&typeof e==`object`?e:void 0}catch{return}}function s(e){if(!e||typeof e!=`object`)return;if(e.isError)return`Tool returned MCP error response`;let t=o(e);if(t?.success===!1)return typeof t.error==`string`?t.error:`Tool reported success=false`}function c(e){if(Array.isArray(e))return e.reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0});if(!e||typeof e!=`object`)return{success:0,failure:0};let t=e;if(Array.isArray(t.__order))return t.__order.reduce((e,n)=>{let r=c(t[n]);return e.success+=r.success,e.failure+=r.failure,e},{success:0,failure:0});let n=o(e);return n?.success===!0?{success:1,failure:0}:n?.success===!1||`error`in t?{success:0,failure:1}:{success:0,failure:0}}function l(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=i.startsWith("${")?i:`\${${i}}`;n[r]=t.resolve(e)}return n}function u(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}function d(e,t){if(typeof e==`string`)return t.resolve(e);if(Array.isArray(e))return e.map(e=>d(e,t));if(e&&typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}return e}function f(e,t){if(e.has(t))return e.get(t);let[n,...r]=t.split(`.`);if(!n||!e.has(n))return;let i=e.get(n);if(i&&typeof i==`object`){let e=o(i);e&&(i=e)}for(let e of r){if(i&&typeof i==`object`){let t=e.match(/^(\d+)$/);if(t&&Array.isArray(i)){i=i[Number(t[1])];continue}i=i[e];continue}return}return i}function p(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){let n=e,r=t;return n.length===r.length&&n.every((e,t)=>p(e,r[t]))}let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>p(e[n],t[n])):!1}return!1}async function m(e,t){if(e.predicateFn)return await e.predicateFn(t);if(e.predicateId===`always_true`)return!0;if(e.predicateId===`always_false`)return!1;if(e.predicateId===`any_step_failed`)return[...t.stepResults.values()].some(e=>c(e).failure>0);let n=e.predicateId.match(/success_rate_gte_(\d+)/i);if(n?.[1]){let e=Number(n[1]),r=[...t.stepResults.values()].reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0}),i=r.success+r.failure;return i>0&&r.success/i>=e/100}let r=e.predicateId.match(/^variable_equals_(.+?)_(.+)$/);if(r?.[1]&&r[2])return p(f(t.stepResults,r[1]),r[2]);let i=e.predicateId.match(/^variable_contains_(.+?)_(.+)$/);if(i?.[1]&&i[2]){let e=f(t.stepResults,i[1]);return typeof e!=`string`&&!Array.isArray(e)?!1:String(e).includes(i[2])}let a=e.predicateId.match(/^variable_matches_(.+?)_(.+)$/);if(a?.[1]&&a[2]){let e=f(t.stepResults,a[1]);if(typeof e!=`string`)return!1;try{return new RegExp(a[2]).test(e)}catch{return!1}}throw Error(`Unknown workflow predicateId "${e.predicateId}"`)}function h(e){switch(e.kind){case`tool`:return[e];case`sequence`:case`parallel`:return e.steps.flatMap(e=>h(e));case`branch`:return[...h(e.whenTrue),...e.whenFalse?h(e.whenFalse):[]];case`fallback`:return[...h(e.primary),...h(e.fallback)];default:return[]}}function g(e){try{let t=e.getDomainInstance(`evidenceGraph`);return t?{hasGraph:!0,nodeCount:t.nodeCount,edgeCount:t.edgeCount}:{hasGraph:!1,nodeCount:0,edgeCount:0}}catch{return{hasGraph:!1,nodeCount:0,edgeCount:0}}}function _(e,t){let n=r(),i=[];for(let r of h(e)){let e=n[r.toolName]??[];for(let n of e)n.check(t)||i.push({nodeId:r.id,toolName:r.toolName,condition:n.condition,fix:n.fix})}return i}var v=class{runs=new Map;lastSuccess=new Map;recordSuccess(e){let n={workflowId:e.workflowId,runId:e.runId,startedAt:e.startedAt,finishedAt:e.finishedAt,durationMs:e.durationMs,status:`success`,stepResultKeys:Object.keys(e.stepResults)};this.runs.set(e.runId,n),this.lastSuccess.set(e.workflowId,e),t.debug(`workflow run recorded: ${e.runId} (${e.workflowId})`)}recordError(e,n,r,i){let a={workflowId:e,runId:n,startedAt:r,finishedAt:new Date().toISOString(),durationMs:Date.now()-new Date(r).getTime(),status:`error`,stepResultKeys:[]};this.runs.set(n,a),t.debug(`workflow run error: ${n} (${e}): ${i}`)}getRun(e){return this.runs.get(e)}getLastSuccess(e){return this.lastSuccess.get(e)}listRuns(e){let t=[...this.runs.values()];return e?t.filter(t=>t.workflowId===e):t}clear(){this.runs.clear(),this.lastSuccess.clear()}},y=class extends Error{warnings;constructor(e){super(`Workflow preflight failed with ${e.length} unsatisfied prerequisite(s)`),this.warnings=e,this.name=`PreflightError`}},b=e({executeExtensionWorkflow:()=>O});const x=new v;function S(e,t,n){let r=t.split(`.`).filter(Boolean),i=e;for(let e of r){if(!i||typeof i!=`object`)return n;i=i[e]}return i??n}function C(e){return new Promise(t=>setTimeout(t,e))}async function w(e,t,n){return!Number.isFinite(t)||t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}async function T(e,t,n,r){let i=t.inputFrom?l(t.inputFrom,r.dataBus):{},a={...t.input?u(t.input,r.dataBus):{},...i,...n?.[t.id]},o=async()=>{let n=await w(e.executeToolWithTracking(t.toolName,a),t.timeoutMs??0,`Workflow tool node "${t.id}"`),i=s(n);if(i)throw Error(i);return r.dataBus.set(t.id,n),n},c=t.retry;if(!c)return o();let d=0,f=c.backoffMs;for(;d<c.maxAttempts;)try{return await o()}catch(e){if(d+=1,d>=c.maxAttempts)throw e;await C(f),f=Math.max(0,Math.floor(f*(c.multiplier??1)))}throw Error(`Workflow tool node "${t.id}" exhausted retries`)}async function E(e,t,n,r){let i=Math.max(1,t.maxConcurrency??4),a={__order:[]},o=0,s=!1,c=async()=>{for(;;){if(s)return;let i=o;if(o+=1,i>=t.steps.length)return;let c=t.steps[i];if(!c)return;try{let t=await D(e,c,n,r);a[c.id]=t,a.__order.push(c.id)}catch(e){if(t.failFast)throw s=!0,e;a[c.id]={success:!1,error:e instanceof Error?e.message:String(e)},a.__order.push(c.id)}}};return await Promise.all(Array.from({length:Math.min(i,t.steps.length)},()=>c())),a}async function D(e,t,n,r){n.emitSpan(`workflow.node.start`,{nodeId:t.id,kind:t.kind});let i;switch(t.kind){case`tool`:i=await T(e,t,r.nodeInputOverrides,n);break;case`sequence`:{let a=t,o=[];for(let t of a.steps)o.push(await D(e,t,n,r));i=o;break}case`parallel`:i=await E(e,t,n,r);break;case`branch`:{let a=t,o=await m(a,n)?a.whenTrue:a.whenFalse;i=o?await D(e,o,n,r):void 0;break}case`fallback`:{let a=t;try{i=await D(e,a.primary,n,r)}catch(t){n.emitSpan(`workflow.node.fallback`,{nodeId:a.id,primaryNodeId:a.primary.id,fallbackNodeId:a.fallback.id,error:t instanceof Error?t.message:String(t)}),i=await D(e,a.fallback,n,r)}break}default:throw Error(`Unsupported workflow node kind: ${t.kind}`)}return n.stepResults.set(t.id,i),n.emitSpan(`workflow.node.finish`,{nodeId:t.id,kind:t.kind}),i}async function O(e,t,r={}){let o=i(),s=r.profile??String(e.baseTier??`workflow`),c=new Date().toISOString(),l=Date.now(),u=[],d=[],f=new Map,p=new a,m=r.config?{...e.config,...r.config}:e.config,h={workflowRunId:o,profile:s,stepResults:f,dataBus:p,invokeTool(t,n){return e.executeToolWithTracking(t,n)},emitSpan(e,t){d.push({name:e,attrs:t,at:new Date().toISOString()})},emitMetric(e,t,n,r){u.push({name:e,value:t,type:n,attrs:r,at:new Date().toISOString()})},getConfig(e,t){return S(m,e,t)}};try{await t.onStart?.(h);let i=t.build(h),a=r.preflightMode??`warn`,p=[];if(a===`skip`)h.emitSpan(`workflow.preflight`,{mode:a,skipped:!0,evidenceState:g(e),warningCount:0});else try{let t=await n(e),r=g(e);if(p=_(i,t),h.emitSpan(`workflow.preflight`,{mode:a,routingState:t,evidenceState:r,warningCount:p.length,warnings:p}),a===`strict`&&p.length>0)throw new y(p)}catch(t){if(t instanceof y)throw t;h.emitSpan(`workflow.preflight`,{mode:a,warningCount:0,skipped:!0,error:t instanceof Error?t.message:String(t),evidenceState:g(e)})}let m=await w(D(e,i,h,r),r.timeoutMs??t.timeoutMs??0,`Workflow "${t.id}"`);await t.onFinish?.(h,m);try{let t=typeof e.getDomainInstance==`function`?e.getDomainInstance(`evidenceGraph`):void 0;t&&t.nodeCount>0&&(f.set(`__evidenceSnapshot`,t.exportJson()),h.emitSpan(`workflow.evidence.auto-export`,{nodeCount:t.nodeCount,edgeCount:t.edgeCount}))}catch(e){h.emitSpan(`workflow.evidence.auto-export`,{skipped:!0,error:e instanceof Error?e.message:String(e)})}let v={workflowId:t.id,displayName:t.displayName,runId:o,profile:s,startedAt:c,finishedAt:new Date().toISOString(),durationMs:Date.now()-l,result:m,stepResults:Object.fromEntries(f.entries()),metrics:u,spans:d};return x.recordSuccess(v),v}catch(e){let n=e instanceof Error?e:Error(String(e));throw x.recordError(t.id,o,c,n),await t.onError?.(h,n),n}}export{O as n,b as t};
@@ -0,0 +1,5 @@
1
+ import{t as e}from"./logger-sBC6IdRT.mjs";import{d as t,f as n,u as r}from"./constants-Cp6hBrrx.mjs";import{a as i,n as a,r as o,t as s}from"./response-C7rKQst4.mjs";import{a as c,i as l,n as u,r as d,s as f,t as p}from"./parse-args-Cuk7-xUt.mjs";import{s as m}from"./PageController-D9jVkH0i.mjs";import"./definitions-CuJRsJ6N.mjs";import{n as h,t as g}from"./webcrack-CsLLJIs9.mjs";import*as _ from"@babel/parser";import v from"@babel/traverse";import*as y from"@babel/types";import b from"@babel/generator";const x=new Set([`=`,`(`,`[`,`,`,`;`,`{`,`!`,`&`,`|`,`?`,`:`,`~`,`^`,`+`,`-`,`*`,`%`,`<`,`>`,`
2
+ `]);function S(e){return new RegExp(e.source,e.flags)}function ee(e){if(e.length===0)return[];let t=[],n=e.toSorted((e,t)=>e.start-t.start||e.end-t.end);for(let e of n){let n=t[t.length-1];if(!n||e.start>n.end){t.push({...e});continue}n.end=Math.max(n.end,e.end)}return t}function C(e){try{let t=_.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),n=[],r=(e,t)=>{typeof e==`number`&&typeof t==`number`&&t>e&&n.push({start:e,end:t})},i=Array.isArray(t.comments)?t.comments:[];for(let e of i)r(e.start,e.end);return v(t,{StringLiteral(e){r(e.node.start,e.node.end),e.skip()},TemplateElement(e){r(e.node.start,e.node.end),e.skip()},RegExpLiteral(e){r(e.node.start,e.node.end),e.skip()}}),ee(n)}catch{return null}}function w(e){let t=e[e.length-2];if(typeof t==`number`)return t;let n=e[e.length-3];return typeof n==`number`?n:null}function T(e,t){let n=t-1;for(;n>=0&&(e[n]===` `||e[n]===` `||e[n]===`\r`);)n--;if(n<0)return!0;let r=e[n];if(x.has(r))return!0;if(r!==`)`)return!1;let i=1,a=n-1;for(;a>=0&&i>0;)e[a]===`)`&&i++,e[a]===`(`&&i--,a--;for(a--;a>=0&&(e[a]===` `||e[a]===` `);)a--;let o=``;for(;a>=0&&/[a-z]/.test(e[a]);)o=e[a]+o,a--;return[`if`,`while`,`for`,`switch`,`return`,`typeof`,`void`,`in`,`of`,`case`].includes(o)}function E(e,t){let n=null,r=!1,i=!1,a=!1;for(let o=0;o<t;o++){let s=e[o];if(r){s===`*`&&e[o+1]===`/`&&(r=!1,o++);continue}if(i){s===`
3
+ `&&(i=!1);continue}if(a){if(s===`\\`){o++;continue}if(s===`/`){for(a=!1,o++;o<t&&/[gimsuy]/.test(e[o]);)o++;continue}if(s===`[`){for(o++;o<t&&e[o]!==`]`;)e[o]===`\\`&&o++,o++;continue}continue}if(n){if(s===`\\`){o++;continue}s===n&&(n=null);continue}if(s===`/`&&e[o+1]===`/`){i=!0,o++;continue}if(s===`/`&&e[o+1]===`*`){r=!0,o++;continue}if(s===`/`&&T(e,o)){a=!0;continue}(s===`'`||s===`"`||s==="`")&&(n=s)}return n!==null||r||i||a}function D(e,t,n){let r=e=>e.replace(S(t),n),i=C(e);if(i===null)return e.replace(S(t),(...t)=>{let r=typeof t[0]==`string`?t[0]:``,i=w(t);return i!==null&&E(e,i)?r:typeof n==`string`?n:n(r,...t.slice(1))});if(i.length===0)return r(e);let a=``,o=0;for(let t of i)o<t.start&&(a+=r(e.slice(o,t.start))),a+=e.slice(t.start,t.end),o=t.end;return o<e.length&&(a+=r(e.slice(o))),a}const te=/\b(-?\d+(?:\.\d+)?)\s*([+\-%*/])\s*(-?\d+(?:\.\d+)?)\b/g,ne=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*/g,O=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*else\s*\{([^}]*)\}/g,k=/if\s*\(\s*true\s*\)\s*\{([^}]*)\}\s*(?:else\s*\{[^}]*\}\s*)?/g,A=/var\s+([A-Za-z_$]\w*)\s*=\s*['"]([^'"]+)['"]\.split\(['"]\|['"]\)\s*;\s*var\s+(\w+)\s*=\s*0\s*;\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\s*\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,j=/var\s+([A-Za-z_$]\w*)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\];\s*var\s+(\w+)\s*=\s*(\d+);\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,M=/['"]([^'"]*)['"]\s*\+\s*['"]([^'"]*)['"]/g;function N(e,t,n){for(let r=t;r>=0&&r<e.length;r+=n){let t=e[r];if(t&&!/\s/.test(t))return t}return``}function P(e,t){let n=t.toSorted((e,t)=>t.start-e.start||t.end-e.end),r=e;for(let e of n)r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`;return r}function F(e,t){let n=t.get(e.node.name);if(!n)return null;let r=e.scope.getBinding(e.node.name);if(!r||!y.isVariableDeclarator(r.path.node)||!y.isIdentifier(r.path.node.id)||!t.has(r.path.node.id.name))return null;let i=r.identifier===e.node,a=e.isReferencedIdentifier(),o=e.key===`left`&&e.parentPath.isAssignmentExpression(),s=e.key===`left`&&(e.parentPath.isForInStatement()||e.parentPath.isForOfStatement()),c=e.key===`argument`&&e.parentPath.isUpdateExpression();return!i&&!a&&!o&&!s&&!c?null:n}function I(e,t){try{let n=_.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=new Map;return v(n,{ObjectProperty(e){if(!e.node.shorthand||!y.isIdentifier(e.node.key)||!y.isIdentifier(e.node.value))return;let n=e.get(`value`);if(!n.isIdentifier())return;let i=F(n,t),{start:a,end:o}=e.node;!i||a==null||o!=null&&(r.set(`${a}:${o}`,{start:a,end:o,text:`${e.node.key.name}: ${i}`}),e.skip())},Identifier(e){let n=F(e,t),{start:i,end:a}=e.node;!n||i==null||a!=null&&r.set(`${i}:${a}`,{start:i,end:a,text:n})}}),r.size===0?e:P(e,[...r.values()])}catch{return null}}function L(e){let t=e;return t=D(t,te,(e,t,n,r)=>{let i=Number(t),a=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a))return e;let o=null;return n===`+`?o=i+a:n===`-`?o=i-a:n===`*`?o=i*a:n===`/`&&a!==0?o=i/a:n===`%`&&a!==0&&(o=i%a),o===null||!Number.isFinite(o)?e:String(Number.isInteger(o)?o:Number(o.toFixed(12)))}),t=D(t,M,(e,t,n)=>JSON.stringify(`${t}${n}`)),t=D(t,/--(\d)/g,(e,t)=>t),t=D(t,/\+\s*(\d+(?:\.\d+)?)/g,(e,t)=>t),t=D(t,/\b0x([0-9a-fA-F]{2,8})\b/g,(e,t)=>{let n=Number.parseInt(t,16);return Number.isFinite(n)?String(n):e}),t}function R(e){let t=e;return t=D(t,O,(e,t)=>t),t=D(t,ne,``),t=D(t,k,(e,t)=>t),t=D(t,/\btrue\s*\?\s*([^:]+)\s*:\s*([^,;)\]}]+)/g,(e,t)=>t),t=D(t,/\bfalse\s*\?\s*[^:]+\s*:\s*([^,;)}\]]+)/g,(e,t)=>t),t=D(t,/if\s*\([^)]*\)\s*\{\s*\}\s*/g,``),t}function z(e){let t=e;return t=D(t,A,(e,t,n,r,i)=>{let a=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,o=new Map,s;for(;(s=a.exec(i))!==null;){let e=s[1],t=(s[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&o.set(e,t)}let c=n.split(`|`).map(e=>e.trim()).map(e=>o.get(e)).filter(e=>!!e).join(`
4
+ `);return c.length>0?c:e}),t=D(t,j,(e,t,n,r,i,a)=>{let o=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,s=new Map,c;for(;(c=o.exec(a))!==null;){let e=c[1],t=(c[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&s.set(e,t)}let l=n.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``).trim()).map(e=>s.get(e)).filter(e=>!!e).join(`
5
+ `);return l.length>0?l:e}),t}function B(e){let t=new Set,n=/\b(?:var|let|const)\s+([A-Za-z_$]\w{0,3})\b/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];e&&(e.length<=2||e.startsWith(`_0x`)||e.startsWith(`_`))&&t.add(e)}if(t.size===0)return{code:e,count:0};let i=new Map,a=1;for(let e of t)i.set(e,`var_${a}`),a++;let o=I(e,i);if(o!==null)return{code:o,count:o===e?0:i.size};let s=e.replace(RegExp(`\\b(${[...t].map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b`,`g`),(e,t,n,r)=>{let a=i.get(t);if(!a)return e;let o=n>0?r[n-1]:``,s=N(r,n-1,-1),c=N(r,n+e.length,1);return o===`.`||o===`'`||o===`"`||o==="`"||o===`$`||(s===`{`||s===`,`)&&(c===`:`||c===`(`)?e:a});return{code:s,count:s===e?0:i.size}}const V={"<":(e,t)=>e<t,">":(e,t)=>e>t,"<=":(e,t)=>e<=t,"<==":(e,t)=>e<=t,">=":(e,t)=>e>=t,">==":(e,t)=>e>=t,"==":(e,t)=>e===t,"===":(e,t)=>e===t,"!=":(e,t)=>e!==t,"!==":(e,t)=>e!==t},H=[{pattern:`jsfuck`,regex:/\[!\[\]\]\[\(['"]\)constructor['"]\)\]\(!!\[\]\+\[\]\)\(\)/g,replacement:`"function Boolean() { [native code] }"`},{pattern:`jsfuck`,regex:/!!\[\]\+\[\]/g,replacement:`"true"`},{pattern:`jsfuck`,regex:/!\[\]\+\[\]/g,replacement:`"false"`},{pattern:`jsfuck`,regex:/\+!!\[\]/g,replacement:`1`},{pattern:`jsfuck`,regex:/\[\]\+\[\]/g,replacement:`""`},{pattern:`jsfuck`,regex:/\+\[\]/g,replacement:`0`}],U=[{pattern:`boolean-literal`,regex:/!!\[\]/g,replacement:`true`},{pattern:`boolean-literal`,regex:/!\[\]/g,replacement:`false`},{pattern:`undefined-literal`,regex:/void\s+0/g,replacement:`undefined`}],W={pattern:`opaque-truthy`,regex:/!0x0\b|!\b0(?![.\d])/g,replacement:`true`},G=[{pattern:`type-coercion`,regex:/typeof\s+undefined\s*===?\s*["']undefined["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+null\s*===?\s*["']object["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+NaN\s*===?\s*["']number["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*==\s*undefined/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*===\s*undefined/g,replacement:`false`},{pattern:`type-coercion`,regex:/NaN\s*===?\s*NaN/g,replacement:`false`}],K=/if\s*\(\s*(-?\d+(?:\.\d+)?)\s*([<>!=]+)\s*(-?\d+(?:\.\d+)?)\s*\)/g,q=/!\s*(-?\d+(?:\.\d+)?)(?![.\d\s\w])/g,re=/(?:var|let|const)\s+(\w+)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\]/g;function J(e,t,n,r){return e.solved.push({pattern:t,original:n,result:r}),r}function Y(e,t){for(let n of t)e.output=D(e.output,n.regex,t=>J(e,n.pattern,t,n.replacement))}function X(e){e.output=D(e.output,K,(t,n,r,i)=>{if(e.iterations>=e.maxIterations)return t;let a=V[r];if(!a)return t;e.iterations+=1;let o=a(Number(n),Number(i));return J(e,`constant-comparison`,t,String(o)),e.replaceInPlace?`/* ${t} => ${o} */ if (${o})`:`if (${o})`})}function ie(e){e.output=D(e.output,q,(t,n)=>{let r=Number(n);return r===0||!Number.isFinite(r)?t:J(e,`opaque-falsy`,t,`false`)})}function ae(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function oe(e){let t=new Map;return D(e,re,(e,n,r)=>{let i=r.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``));return t.set(n,i),e}),t}function se(e){let t=oe(e.output);if(t.size!==0)for(let[n,r]of t){let t=RegExp(`${ae(n)}\\(['"]?(0x[0-9a-fA-F]+|\\d+)['"]?\\)`,`g`);e.output=D(e.output,t,(t,n)=>{if(e.iterations>=e.maxIterations)return t;let i=n.startsWith(`0x`)?Number.parseInt(n,16):Number(n);return i<0||i>=r.length?t:(e.iterations+=1,J(e,`string-array-access`,t,JSON.stringify(r[i])))})}}function ce(e){let t={output:e.code,solved:[],replaceInPlace:e.replaceInPlace,maxIterations:e.maxIterations,iterations:0};return X(t),Y(t,H),Y(t,U),Y(t,[W]),ie(t),se(t),Y(t,G),{success:!0,solvedCount:t.solved.length,solved:t.solved,transformedCode:e.replaceInPlace?t.output:void 0}}const le=[{type:`for-switch`,test:/for.*switch/s},{type:`while-switch`,test:/while.*switch/s},{type:`if-else-chain`,test:/if\s*\(\s*\w+\s*===?\s*\w+/}];function ue(e){for(let t of le)if(t.test.test(e))return t.type;return`switch`}function de(e){let t=new Map;for(let n of e){let e=n.type||`unknown`;t.set(e,(t.get(e)||0)+1)}return Object.fromEntries(t)}function fe(e){let{code:t,extractBytecode:n,mapOpcodes:r,vmResult:i}=e;if(!i.isJSVMP)return{success:!0,isVM:!1,message:`No VM/JSVMP patterns detected.`};let a={isVM:!0,vmType:i.vmType,dispatchType:ue(t),complexity:i.vmFeatures?.complexity,instructionCount:i.vmFeatures?.instructionCount,interpreterLocation:i.vmFeatures?.interpreterLocation};return n&&i.instructions&&(a.bytecode=i.instructions),r&&i.instructions&&(a.opcodeDistribution=de(i.instructions),a.suggestedStrategy=i.vmFeatures?.complexity===`high`?`Use symbolic execution (js_deobfuscate_jsvmp with aggressive=true) for high-complexity VMs`:`Use standard deobfuscation pipeline (js_deobfuscate_pipeline)`),{success:!0,analysis:a}}async function pe(t,n){let r=c(n,`searchKeyword`,``),i=p(n,`forceRequireAll`,!!r),o=Math.min(d(n,`maxResults`,20),100);try{let n=await m(await t.getActivePage(),async e=>{let t=window,n=null;typeof t.__webpack_require__==`function`&&(n=t.__webpack_require__);let r=Object.keys(t).filter(e=>e.startsWith(`webpackChunk`)||e.startsWith(`webpackJsonp`)),i=new Set;for(let e of r){let n=t[e];if(!Array.isArray(n))continue;let r=n;if(r.m&&typeof r.m==`object`)for(let e of Object.keys(r.m))i.add(e);for(let e of n)if(Array.isArray(e)&&e[1]&&typeof e[1]==`object`)for(let t of Object.keys(e[1]))i.add(t)}if(typeof t.__webpack_modules__==`object`&&t.__webpack_modules__)for(let e of Object.keys(t.__webpack_modules__))i.add(e);if(!n)for(let e of r){let r=t[e];if(r?.m&&typeof r.m==`object`){let e=r.m;n=t=>{try{let n=e[t];return typeof n==`function`?n():n}catch{return}};break}}let a=Array.from(i);if(!e.forceRequireAll||!n)return{total:a.length,requireFound:!!n,chunkKeys:r,moduleIds:a.slice(0,200),matches:[]};let o=n,s=[];for(let t of a){if(s.length>=e.maxResults)break;try{let n=o(t);if(n==null)continue;let r;try{r=JSON.stringify(n)}catch{r=String(n)}(!e.searchKeyword||r.toLowerCase().includes(e.searchKeyword.toLowerCase()))&&s.push({id:t,preview:r.slice(0,600)})}catch{}}return{total:a.length,requireFound:!0,chunkKeys:r,moduleIds:a.slice(0,200),matches:s}},{searchKeyword:r,forceRequireAll:i,maxResults:o});return e.info(`webpack_enumerate: found ${n.total} modules, ${n.matches.length} matches`),a(n)}catch(e){return s(e)}}function me(t){e.info(`Derotating string array...`);try{let n=_.parse(t,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=0;return v(n,{CallExpression(t){if(!y.isFunctionExpression(t.node.callee)&&!y.isArrowFunctionExpression(t.node.callee))return;let n=t.node.callee;if(!y.isFunctionExpression(n)||!y.isBlockStatement(n.body))return;let i=n.body.body.some(e=>y.isWhileStatement(e)),a=JSON.stringify(n.body).includes(`push`)&&JSON.stringify(n.body).includes(`shift`);i&&a&&(e.debug(`Found string array rotation IIFE`),t.remove(),r++)}}),r>0?(e.info(`Removed ${r} string array rotation functions`),b(n,{comments:!0,compact:!1}).code):t}catch(n){return e.error(`Failed to derotate string array:`,n),t}}const Z=v.default??v,Q=b.default??b,he=new Set([`summary`,`priority`,`incremental`,`full`]),ge=new Set([`structure`,`business`,`security`,`all`]),$=new Set([`function`,`xhr`,`fetch`,`websocket`,`localstorage`,`cookie`]),_e=new Set([`log`,`block`,`modify`]),ve=new Set([`call`,`apply`]);var ye=class{collector;scriptManager;deobfuscator;advancedDeobfuscator;obfuscationDetector;analyzer;cryptoDetector;hookManager;jsvmpDeobfuscator;constructor(e){this.collector=e.collector,this.scriptManager=e.scriptManager,this.deobfuscator=e.deobfuscator,this.advancedDeobfuscator=e.advancedDeobfuscator,this.obfuscationDetector=e.obfuscationDetector,this.analyzer=e.analyzer,this.cryptoDetector=e.cryptoDetector,this.hookManager=e.hookManager,this.jsvmpDeobfuscator=new h}requireCodeArg(t,n){let r=t.code;return typeof r!=`string`||r.trim().length===0?(e.warn(`${n} called without valid code argument`),null):r}extractWebcrackArgs(e){let t={},n=p(e,`unpack`),r=p(e,`unminify`),i=p(e,`jsx`),a=p(e,`mangle`),o=p(e,`forceOutput`),s=p(e,`includeModuleCode`),l=c(e,`outputDir`),u=d(e,`maxBundleModules`);return n!==void 0&&(t.unpack=n),r!==void 0&&(t.unminify=r),i!==void 0&&(t.jsx=i),a!==void 0&&(t.mangle=a),o!==void 0&&(t.forceOutput=o),s!==void 0&&(t.includeModuleCode=s),l?.trim()&&(t.outputDir=l),u!==void 0&&(t.maxBundleModules=u),Array.isArray(e.mappings)&&(t.mappings=e.mappings.filter(e=>typeof e==`object`&&!!e&&typeof e.path==`string`&&typeof e.pattern==`string`)),t}async handleCollectCode(i){let o=p(i,`returnSummaryOnly`,!1),s=u(i,`smartMode`,he),c=n,l=e=>e.slice(0,c).map(e=>({url:e.url,type:e.type,size:e.size,sizeKB:(e.size/1024).toFixed(2),truncated:e.metadata?.truncated||!1,preview:`${e.content.substring(0,200)}...`})),m=e=>{let t=(Array.isArray(e.summaries)&&e.summaries.length>0?e.summaries:l(e.files)).slice(0,c),n=Array.isArray(e.summaries)?e.summaries.length:e.files.length,r=e.totalSize>0?e.totalSize:Array.isArray(e.summaries)?e.summaries.reduce((e,t)=>e+(typeof t.size==`number`?t.size:0),0):e.files.reduce((e,t)=>e+t.size,0);return{totalSize:r,totalSizeKB:(r/1024).toFixed(2),filesCount:n,summarizedFiles:t.length,omittedFiles:Math.max(0,n-t.length),collectTime:e.collectTime,summary:t}};s||=`summary`;let h=await this.collector.collect({url:f(i,`url`),includeInline:p(i,`includeInline`),includeExternal:p(i,`includeExternal`),includeDynamic:p(i,`includeDynamic`),smartMode:s,compress:p(i,`compress`),maxTotalSize:d(i,`maxTotalSize`),maxFileSize:i.maxFileSize?d(i,`maxFileSize`,0)*1024:void 0,priorities:i.priorities});if(o)return a({mode:`summary`,...m(h),hint:`Use get_script_source for specific files.`});let g=r,_=t,v=Buffer.byteLength(JSON.stringify(h),`utf8`);return h.totalSize>g||v>_?(e.warn(`Collected code is too large (collected=${(h.totalSize/1024).toFixed(2)}KB, response=${(v/1024).toFixed(2)}KB), returning summary mode.`),a({warning:`Code size exceeds safe response threshold; summary returned.`,...m(h),estimatedResponseSize:v,estimatedResponseSizeKB:(v/1024).toFixed(2),recommendations:[`Use get_script_source for targeted files.`,`Use more specific priority filters.`,`Use smartMode=summary for initial reconnaissance.`]})):a(h)}async handleSearchInScripts(e){await this.scriptManager.init();let t=c(e,`keyword`);if(!t)return a({success:!1,error:`keyword is required`});let n=d(e,`maxMatches`,100),r=p(e,`returnSummary`,!1),i=d(e,`maxContextSize`,5e4),o=await this.scriptManager.searchInScripts(t,{isRegex:p(e,`isRegex`),caseSensitive:p(e,`caseSensitive`),contextLines:d(e,`contextLines`),maxMatches:n}),s=JSON.stringify(o).length;if(r||s>i){let t=o.matches??[];return a({success:!0,keyword:e.keyword,totalMatches:t.length,resultSize:s,resultSizeKB:(s/1024).toFixed(2),truncated:s>i,reason:s>i?`Result too large (${(s/1024).toFixed(2)}KB > ${(i/1024).toFixed(2)}KB)`:`Summary mode enabled`,matchesSummary:t.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url,line:e.line,preview:`${(e.context??``).substring(0,100)}...`})),recommendations:[`Use more specific keywords.`,`Reduce maxMatches (current: ${n}).`,`Use get_script_source for targeted file retrieval.`]})}return a(o)}async handleExtractFunctionTree(e){let t=c(e,`scriptId`),n=c(e,`functionName`);if(!t)return a({success:!1,error:`scriptId is required`,hint:`Use get_all_scripts() to list available scripts and their scriptIds`});if(!n)return a({success:!1,error:`functionName is required`,hint:`Specify the name of the function to extract`});await this.scriptManager.init();let r=await this.scriptManager.getAllScripts();if(!r.some(e=>String(e.scriptId)===String(t))){let e=r.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url?.substring(0,80)}));return a({success:!1,error:`Script not found: ${t}`,hint:`The specified scriptId does not exist. Use get_all_scripts() to list available scripts.`,availableScripts:e.length>0?e:`No scripts loaded. Navigate to a page first.`,totalScripts:r.length})}try{return a({success:!0,...await this.scriptManager.extractFunctionTree(t,n,{maxDepth:d(e,`maxDepth`),maxSize:d(e,`maxSize`),includeComments:p(e,`includeComments`)})})}catch(e){return a({success:!1,error:e instanceof Error?e.message:String(e),hint:`Make sure the function name exists in the specified script`})}}async handleDeobfuscate(e){let t=this.requireCodeArg(e,`deobfuscate`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});if(u(e,`engine`,new Set([`auto`,`webcrack`]),`auto`)===`webcrack`)return a(await this.advancedDeobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e),...typeof e.detectOnly==`boolean`?{detectOnly:e.detectOnly}:{}}));let n=await this.deobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e)});return n&&typeof n==`object`&&`success`in n&&n.success===!1&&!(`error`in n)?a({...n,error:n.reason||`deobfuscation failed`}):a(n)}async handleUnderstandCode(e){let t=this.requireCodeArg(e,`understand_code`);return a(t?await this.analyzer.understand({code:t,context:l(e,`context`),focus:u(e,`focus`,ge,`all`)}):{success:!1,error:`code is required and must be a non-empty string`})}async handleDetectCrypto(e){let t=this.requireCodeArg(e,`detect_crypto`);return a(t?await this.cryptoDetector.detect({code:t}):{success:!1,error:`code is required and must be a non-empty string`})}async handleManageHooks(e){let t=f(e,`action`);switch(t){case`create`:return a(await this.hookManager.createHook({target:f(e,`target`),type:u(e,`type`,$)??`function`,action:u(e,`hookAction`,_e,`log`),customCode:c(e,`customCode`)}));case`list`:return a({hooks:this.hookManager.getAllHooks()});case`records`:return a({records:this.hookManager.getHookRecords(f(e,`hookId`))});case`clear`:return this.hookManager.clearHookRecords(c(e,`hookId`)),a({success:!0,message:`Hook records cleared`});default:return a({success:!1,message:`Unknown hook action: ${t}. Valid actions: create, list, records, clear`})}}async handleDetectObfuscation(e){let t=this.requireCodeArg(e,`detect_obfuscation`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});let n=p(e,`generateReport`,!0),r=this.obfuscationDetector.detect(t);if(!n)return a(r);let i=this.obfuscationDetector.generateReport(r);return o(`${JSON.stringify(r,null,2)}\n\n${i}`)}async handleWebcrackUnpack(e){let t=this.requireCodeArg(e,`webcrack_unpack`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});let n=await g(t,{unpack:p(e,`unpack`,!0),unminify:p(e,`unminify`,!0),jsx:p(e,`jsx`,!0),mangle:p(e,`mangle`,!1),...this.extractWebcrackArgs(e)});return n.applied?a({success:!0,code:n.code,bundle:n.bundle,savedTo:n.savedTo,savedArtifacts:n.savedArtifacts,optionsUsed:n.optionsUsed,engine:`webcrack`}):a({success:!1,error:n.reason||`webcrack execution failed`,optionsUsed:n.optionsUsed,engine:`webcrack`})}async handleWebpackEnumerate(e){return pe(this.collector,e)}async handleClearCollectedData(){try{return await this.collector.clearAllData(),this.scriptManager.clear(),a({success:!0,message:`All collected data cleared.`,cleared:{fileCache:!0,compressionCache:!0,collectedUrls:!0,scriptManager:!0}})}catch(t){return e.error(`Failed to clear collected data:`,t),a(i(t))}}async handleGetCollectionStats(){try{let e=await this.collector.getAllStats();return a({success:!0,stats:e,summary:{totalCachedFiles:e.cache.memoryEntries+e.cache.diskEntries,totalCacheSize:`${(e.cache.totalSize/1024).toFixed(2)} KB`,compressionRatio:`${e.compression.averageRatio.toFixed(1)}%`,cacheHitRate:e.compression.cacheHits>0?`${(e.compression.cacheHits/(e.compression.cacheHits+e.compression.cacheMisses)*100).toFixed(1)}%`:`0%`,collectedUrls:e.collector.collectedUrls}})}catch(t){return e.error(`Failed to get collection stats:`,t),a(i(t))}}async handleJsDeobfuscateJsvmp(e){let t=this.requireCodeArg(e,`js_deobfuscate_jsvmp`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});let n=p(e,`detectOnly`,!1),r=await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:p(e,`aggressive`,!1),extractInstructions:p(e,`extractInstructions`,!0),timeout:d(e,`timeout`,3e4)});return a(n?{success:!0,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,confidence:r.confidence,instructionCount:r.instructions?.length}:{success:r.isJSVMP,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,instructions:r.instructions,deobfuscatedCode:r.deobfuscatedCode,confidence:r.confidence,warnings:r.warnings,unresolvedParts:r.unresolvedParts,stats:r.stats})}async handleJsDeobfuscatePipeline(e){let t=this.requireCodeArg(e,`js_deobfuscate_pipeline`);if(!t)return a({success:!1,error:`code is required`});let n=p(e,`useWebcrack`,!0),r=p(e,`aggressive`,!1),i=p(e,`humanize`,!0),o=p(e,`returnStageDetails`,!1),s=Date.now(),c=t,l=[],u=L(c);u!==c&&(c=u,l.push(`constant_fold`));let d=R(c);d!==c&&(c=d,l.push(`dead_code_remove`));let f=c,m=!1,h,_;if(n)try{let e=await g(c,{unminify:!0,unpack:!0});e.applied?(f=e.code,m=!0):h=e.reason?`webcrack stage did not apply: ${e.reason}`:`webcrack stage did not apply any transformation.`}catch(e){_=e instanceof Error?e.message:String(e)}if(r){let e=z(f);e!==f&&(f=e)}let v=f,y=0;if(i){let e=B(v);e.code!==v&&(v=e.code,y=e.count)}let b=Date.now()-s,x=t.length>0?1-v.length/t.length:0,S={success:!h&&!_,deobfuscatedCode:v,...h?{warning:h}:{},..._?{error:`webcrack stage failed: ${_}`}:{},stats:{originalSize:t.length,finalSize:v.length,reductionRate:Math.round(x*1e3)/10,processingTimeMs:b,stages:{preprocessor:{transforms:l,sizeAfter:c.length},deobfuscator:{webcrackApplied:m,sizeAfter:f.length,...h?{warning:h}:{},..._?{error:_}:{}},humanizer:{renameCount:y,sizeAfter:v.length}}}};return o&&(S.stageDetails={preprocessed:c.substring(0,5e3),deobfuscated:f.substring(0,5e3)}),a(S)}async handleJsAnalyzeVm(e){let t=this.requireCodeArg(e,`js_analyze_vm`);if(!t)return a({success:!1,error:`code is required`});let n=p(e,`extractBytecode`,!0);return a(fe({code:t,extractBytecode:n,mapOpcodes:p(e,`mapOpcodes`,!0),vmResult:await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:!1,extractInstructions:n,timeout:15e3})}))}async handleJsSolveConstraints(e){let t=this.requireCodeArg(e,`js_solve_constraints`);return a(t?ce({code:t,replaceInPlace:p(e,`replaceInPlace`,!0),maxIterations:d(e,`maxIterations`,100)}):{success:!1,error:`code is required`})}async handleAnalysisAstMatch(e){let t=c(e,`code`);if(!t)return a({success:!1,error:`code is required`});let n=c(e,`nodeType`);if(!n)return a({success:!1,error:`nodeType is required`});let r=d(e,`maxResults`,50),i=c(e,`filter`),o;if(i)try{o=JSON.parse(i)}catch{return a({success:!1,error:`filter must be valid JSON`})}let s;try{s=_.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let l=[],u=n;function f(e){if(!o)return!0;for(let[t,n]of Object.entries(o)){let r=t.split(`.`),i=e;for(let e of r){if(typeof i!=`object`||!i)return!1;i=i[e]}if(String(i)!==String(n))return!1}return!0}function p(e){let t={};for(let n of Object.keys(e)){if(n===`type`||n===`start`||n===`end`||n===`loc`||n===`range`)continue;let r=e[n];r==null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t[n]=r:Array.isArray(r)&&r.length<=5?t[n]=r.map(e=>typeof e==`object`&&e&&`type`in e?{type:e.type}:e):typeof r==`object`&&r&&`type`in r&&(t[n]={type:r.type})}return t}return Z(s,{enter(e){let n=e.node;n.type===u&&f(n)&&(l.push({type:n.type,start:n.start??-1,end:n.end??-1,code:t.slice(n.start??0,n.end??0),properties:p(n)}),l.length>=r&&e.stop())}}),a({success:!0,matches:l,total:l.length,nodeType:n})}async handleAnalysisDeflatControlFlow(e){let t=c(e,`code`);if(!t)return a({success:!1,error:`code is required`});let n;try{n=_.parse(t,{sourceType:`unambiguous`})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let r=p(e,`removeDispatcher`,!0),i=this.preprocessDeflatCode(t);if(i.code!==t)try{n=_.parse(i.code,{sourceType:`unambiguous`})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let o=0,s=new Set,l=this.resolveDispatcherArray.bind(this);Z(n,{WhileStatement:e=>{let t=e.node.test;if(t.type!==`BooleanLiteral`||t.value!==!0)return;let n=e.node.body;if(n.type!==`BlockStatement`)return;let r=n.body.find(e=>e.type===`SwitchStatement`);if(!r)return;let i=r.discriminant;if(i.type!==`MemberExpression`||!i.computed)return;let a=i.object;if(a.type!==`Identifier`)return;let c=a.name,u,d=i.property;if(d.type===`Identifier`?u=d.name:d.type===`UpdateExpression`&&d.argument.type===`Identifier`&&(u=d.argument.name),!u)return;let f=r.cases;if(f.length===0)return;let p=new Map;for(let e of f)!e.test||e.test.type!==`StringLiteral`||p.set(e.test.value,e.consequent);let m=e.scope.getBinding(c),h=e.scope.getBinding(u);if(!m||!h)return;let g=l(e,c);if(!g)return;let _=[];if(g.type===`ArrayExpression`)for(let e of g.elements)e&&e.type===`StringLiteral`&&_.push(e.value);else if(g.type===`CallExpression`&&g.callee.type===`MemberExpression`&&g.callee.property.type===`Identifier`&&g.callee.property.name===`split`&&g.arguments[0]?.type===`StringLiteral`){let e=g.arguments[0].value,t=g.callee.object;t.type===`StringLiteral`&&_.push(...t.value.split(e))}if(_.length===0)return;let v=[];for(let e of _){let t=p.get(e);if(t)for(let e of t)e.type!==`BreakStatement`&&e.type!==`ContinueStatement`&&v.push(e)}e.replaceWith(y.blockStatement(v)),s.add(m.identifier),s.add(h.identifier),o++}}),r&&s.size>0&&Z(n,{VariableDeclarator(e){if(e.node.id.type===`Identifier`&&s.has(e.node.id)){let t=e.parent;t.type===`VariableDeclaration`&&t.declarations.length===1?e.parentPath.remove():e.remove()}}});let u=Q(n,{retainLines:!0}).code;return a({success:!0,code:u,flattenedCount:o,dispatchersRemoved:r?s.size:0,helperTransforms:i.transforms})}async handleAnalysisDecodeStringArray(e){let t=c(e,`code`);if(!t)return a({success:!1,error:`code is required`});let n=d(e,`maxReplacements`,200),r=p(e,`removeRotation`,!0),i=r?me(t):t,o=new Map,s;try{s=_.parse(i,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}Z(s,{VariableDeclarator(e){if(!y.isIdentifier(e.node.id)||!y.isArrayExpression(e.node.init))return;let t=[];for(let n of e.node.init.elements){if(!y.isStringLiteral(n))return;t.push(n.value)}o.set(e.node.id.name,t)}});let l=[],u=0;return Z(s,{CallExpression(e){if(u>=n){e.stop();return}if(!y.isIdentifier(e.node.callee))return;let t=e.node.callee.name,r=o.get(t);if(!r||e.node.arguments.length!==1)return;let i=e.node.arguments[0];if(!y.isNumericLiteral(i)&&!y.isStringLiteral(i))return;let a=y.isNumericLiteral(i)?i.value:i.value.startsWith(`0x`)?Number.parseInt(i.value,16):Number(i.value);if(!Number.isInteger(a)||a<0||a>=r.length)return;let s=r[a];typeof s==`string`&&(l.push({arrayName:t,index:a,value:s,original:Q(e.node,{compact:!0}).code}),e.replaceWith(y.stringLiteral(s)),u+=1)}}),a({success:!0,code:Q(s,{retainLines:!0}).code,replacedCount:u,arraysFound:o.size,rotationRemoved:r&&i!==t,replacements:l})}preprocessDeflatCode(e){let t=e,n=[];return t=t.replace(/(\b[a-zA-Z_$][\w$]*)\[['"]([a-zA-Z_$][\w$]*)['"]\]\(([^)]*)\)/g,(e,t,r,i)=>ve.has(r)?(n.push(`helper-member-call`),`${t}.${r}(${i})`):e),{code:t,transforms:n}}resolveDispatcherArray(e,t){let n=e.scope.getBinding(t);if(!n?.path.isVariableDeclarator())return null;let r=n.path.node.init;if(r)return r;let i=n.path.parentPath;if(!i.isVariableDeclaration())return null;let a=i.getAllNextSiblings();for(let e of a){if(!e.isExpressionStatement())continue;let n=e.node.expression;if(!(!y.isAssignmentExpression(n)||n.operator!==`=`||!y.isIdentifier(n.left,{name:t})))return n.right}return null}};export{ye as CoreAnalysisHandlers};