@jshookmcp/jshook 0.3.2 → 0.3.3

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 (241) hide show
  1. package/README.md +3 -3
  2. package/README.zh.md +3 -3
  3. package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
  4. package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
  5. package/dist/CodeInjector-Btj9upnf.mjs +1 -0
  6. package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
  7. package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
  8. package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
  9. package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
  10. package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
  11. package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
  12. package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
  13. package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
  14. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
  15. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  16. package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
  17. package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
  18. package/dist/MemoryScanner-Dxd657li.mjs +1 -0
  19. package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
  20. package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
  21. package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
  22. package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
  23. package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
  24. package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
  25. package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
  26. package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
  27. package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
  28. package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
  29. package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
  30. package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
  31. package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
  32. package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
  33. package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
  34. package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
  35. package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
  36. package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
  37. package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
  38. package/dist/antidebug-CsnpOR9z.mjs +1 -0
  39. package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
  40. package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
  41. package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
  42. package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
  43. package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
  44. package/dist/browser-BUaB25bk.mjs +11 -0
  45. package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
  46. package/dist/collector-CB2syQEg.mjs +1 -0
  47. package/dist/constants-DMv3svps.mjs +2 -0
  48. package/dist/coordination-Dbohmj6D.mjs +1 -0
  49. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  50. package/dist/debugger-CLzkObIO.mjs +1 -0
  51. package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
  52. package/dist/definitions-B3a9QC2t.mjs +1 -0
  53. package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
  54. package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
  55. package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
  56. package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
  57. package/dist/definitions-DBYSxChX.mjs +1 -0
  58. package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
  59. package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
  60. package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
  61. package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
  62. package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
  63. package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
  64. package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
  65. package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
  66. package/dist/definitions-EGmqr85H.mjs +1 -0
  67. package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
  68. package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
  69. package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
  70. package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
  71. package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
  72. package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
  73. package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
  74. package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
  75. package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
  76. package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
  77. package/dist/handlers-6iNsXOVT.mjs +7 -0
  78. package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
  79. package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
  80. package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
  81. package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
  82. package/dist/handlers-CWKBBjai.mjs +1 -0
  83. package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
  84. package/dist/handlers-CrJsKnEI.mjs +1 -0
  85. package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
  86. package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
  87. package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
  88. package/dist/handlers-gVscChvl.mjs +1 -0
  89. package/dist/handlers-xFvI9P_y.mjs +1 -0
  90. package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
  91. package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
  92. package/dist/index.mjs +11 -11
  93. package/dist/macro-p8kuJVcm.mjs +2 -0
  94. package/dist/maintenance-DAqADb6Z.mjs +302 -0
  95. package/dist/manifest-4lmM6MZR.mjs +1 -0
  96. package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
  97. package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
  98. package/dist/manifest-Box-jWfr.mjs +1 -0
  99. package/dist/manifest-Bp33di0Q.mjs +1 -0
  100. package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
  101. package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
  102. package/dist/manifest-C7TdXCWY.mjs +1 -0
  103. package/dist/manifest-CM-n64K0.mjs +1 -0
  104. package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
  105. package/dist/manifest-CWJS45iO.mjs +1 -0
  106. package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
  107. package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
  108. package/dist/manifest-Cgxu2qdv.mjs +1 -0
  109. package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
  110. package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
  111. package/dist/manifest-CvDpVToN.mjs +1 -0
  112. package/dist/manifest-D8TL9RLE.mjs +1 -0
  113. package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
  114. package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
  115. package/dist/manifest-DLGtZH-0.mjs +1 -0
  116. package/dist/manifest-DXHdPt2T.mjs +1 -0
  117. package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
  118. package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
  119. package/dist/manifest-G2H52LKz.mjs +131 -0
  120. package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
  121. package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
  122. package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
  123. package/dist/manifest-dG6MuR1U.mjs +1 -0
  124. package/dist/manifest-nWXtgq5Y2.mjs +1 -0
  125. package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
  126. package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
  127. package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
  128. package/dist/native-g095qhpK.mjs +961 -0
  129. package/dist/network-Dvxm7eEI.mjs +7 -0
  130. package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
  131. package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
  132. package/dist/platform-DjWbuiF8.mjs +93 -0
  133. package/dist/process-Dq5I-KZW.mjs +2 -0
  134. package/dist/proxy-DPNgM7TE.mjs +2 -0
  135. package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
  136. package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
  137. package/dist/search-defaults-CJik67or.mjs +1 -0
  138. package/dist/server/plugin-api.mjs +1 -1
  139. package/dist/sourcemap-DqEW15Ao.mjs +1 -0
  140. package/dist/streaming-Dbk4eStJ.mjs +1 -0
  141. package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
  142. package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
  143. package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
  144. package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
  145. package/package.json +2 -2
  146. package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
  147. package/dist/DOMInspector-C19J4zeq.mjs +0 -95
  148. package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
  149. package/dist/ExtensionManager-BD724zkO.mjs +0 -1
  150. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
  151. package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
  152. package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
  153. package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
  154. package/dist/PageController-Dfsm1_o7.mjs +0 -1
  155. package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
  156. package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
  157. package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
  158. package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
  159. package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
  160. package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
  161. package/dist/VersionDetector-CHT36Az0.mjs +0 -9
  162. package/dist/apk-packer-BqXcInnX.mjs +0 -1
  163. package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
  164. package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
  165. package/dist/browser-Qqco2rOT.mjs +0 -11
  166. package/dist/collector-Bpl6qy2L.mjs +0 -1
  167. package/dist/constants-BYj8Xek8.mjs +0 -1
  168. package/dist/coordination-CWXW1o8K.mjs +0 -1
  169. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  170. package/dist/debugger-DyALjYMk.mjs +0 -1
  171. package/dist/definitions-BftdXgXI.mjs +0 -1
  172. package/dist/definitions-Bio5XJYy.mjs +0 -1
  173. package/dist/definitions-CMZRSy3k.mjs +0 -1
  174. package/dist/definitions-DP1vgxEY.mjs +0 -1
  175. package/dist/definitions-Tls8c0A0.mjs +0 -1
  176. package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
  177. package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
  178. package/dist/handlers-8zN_vBIz.mjs +0 -1
  179. package/dist/handlers-DHO3rjsW.mjs +0 -1
  180. package/dist/handlers-FJ80VzUI.mjs +0 -2
  181. package/dist/handlers-VHWrxbM_.mjs +0 -1
  182. package/dist/handlers-mPFiNPe8.mjs +0 -302
  183. package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
  184. package/dist/maintenance-BUpIukhg.mjs +0 -1
  185. package/dist/manifest-B7NB2rh2.mjs +0 -1
  186. package/dist/manifest-BDi4nbH1.mjs +0 -1
  187. package/dist/manifest-BLDfkE7n.mjs +0 -1
  188. package/dist/manifest-BcXbB4gf.mjs +0 -1
  189. package/dist/manifest-Bdnc_vrc.mjs +0 -1
  190. package/dist/manifest-BuYKgCnp.mjs +0 -1
  191. package/dist/manifest-CBfNnGPV.mjs +0 -1
  192. package/dist/manifest-CPS1Xv69.mjs +0 -1
  193. package/dist/manifest-CRryuZF4.mjs +0 -1
  194. package/dist/manifest-CvTe5ZGV2.mjs +0 -1
  195. package/dist/manifest-D-5GH0DV.mjs +0 -1
  196. package/dist/manifest-D3Ssf3IC.mjs +0 -1
  197. package/dist/manifest-D5ck3NvC.mjs +0 -1
  198. package/dist/manifest-DG19q-Ld.mjs +0 -1
  199. package/dist/manifest-DLMlD0Zc.mjs +0 -1
  200. package/dist/manifest-DwL2ik8P.mjs +0 -1
  201. package/dist/manifest-ItF5P8A12.mjs +0 -1
  202. package/dist/manifest-KZphqIyX.mjs +0 -1
  203. package/dist/manifest-RcpX_MyZ.mjs +0 -123
  204. package/dist/manifest-Zy7Odg5J.mjs +0 -1
  205. package/dist/manifest-ff1H7Pdp.mjs +0 -1
  206. package/dist/manifest-iuhF6pTL2.mjs +0 -1
  207. package/dist/manifest-yC16OhL2.mjs +0 -1
  208. package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
  209. package/dist/native-j8l473zn.mjs +0 -961
  210. package/dist/network-T0VRwNPd.mjs +0 -7
  211. package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
  212. package/dist/platform-CzaQtISh.mjs +0 -93
  213. package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
  214. package/dist/process-CWhsCWrf.mjs +0 -2
  215. package/dist/proxy-DZFlDsG3.mjs +0 -2
  216. package/dist/search-defaults-lYBVn_3L.mjs +0 -1
  217. package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
  218. package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
  219. package/dist/streaming-BcJ0B6ao.mjs +0 -1
  220. package/dist/types-D9EiE5o9.mjs +0 -1
  221. /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  222. /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  223. /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  224. /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  225. /package/dist/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
  226. /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.mjs} +0 -0
  227. /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
  228. /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  229. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  230. /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  231. /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  232. /package/dist/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
  233. /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
  234. /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  235. /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  236. /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  237. /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
  238. /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
  239. /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  240. /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  241. /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -0,0 +1 @@
1
+ import{Mi as e,Ni as t}from"./constants-DMv3svps.mjs";import{i as n}from"./artifacts-D-4pSS_N.mjs";import{d as r,h as i,m as a}from"./ensure-browser-core-JHwDo5ql.mjs";import"./definitions-DtZ6Ktx2.mjs";import{dirname as o,resolve as s}from"node:path";import{mkdir as c,writeFile as l}from"node:fs/promises";const u=new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e,t]));function d(e){let t=(e&1)==1,n=e>>1;return t?-n:n}function f(e){let t=[],n=0;for(;n<e.length;){let r=0,i=0,a=!0;for(;a;){let t=e.charAt(n);if(!t)throw Error(`Unexpected end of VLQ segment: "${e}"`);n+=1;let o=u.get(t);if(o===void 0)throw Error(`Invalid VLQ base64 char "${t}" in segment "${e}"`);a=(o&32)!=0;let s=o&31;r+=s<<i,i+=5}t.push(d(r))}return t}function p(e){let t=[],n=0;for(;n<e.length;){let r=0,i=0,a=!0;for(;a;){let t=e.charAt(n);if(!t)throw Error(`Unexpected end of VLQ segment: "${e}"`);n+=1;let o=u.get(t);if(o===void 0)throw Error(`Invalid VLQ base64 char "${t}" in segment "${e}"`);a=(o&32)!=0;let s=o&31;r+=s<<i,i+=5}t.push(r)}return t}function m(e){if(!e)return[];let t=[],n=0,r=0,i=0,a=0,o=e.split(`;`);for(let e=0;e<o.length;e+=1){let s=o[e]??``,c=0;if(!s)continue;let l=s.split(`,`);for(let o of l){if(!o)continue;let s=f(o),l=s[0];if(l===void 0)continue;c+=l;let u={generatedLine:e+1,generatedColumn:c};s.length>=4&&(n+=s[1]??0,r+=s[2]??0,i+=s[3]??0,u.sourceIndex=n,u.originalLine=r+1,u.originalColumn=i,s.length>=5&&(a+=s[4]??0,u.nameIndex=a)),t.push(u)}}return t}function h(e){if(!e)return{mappingsCount:0,segmentCount:0};let t=0,n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`;`?(r&&t++,r=!1):a===`,`?n++:r||(r=!0,n++)}return r&&t++,{mappingsCount:t,segmentCount:n}}function g(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function _(e,t){return g({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}function v(e){return typeof e==`object`&&e?e:{}}function y(e){return typeof e==`string`?e:void 0}function b(e){return/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)}function x(e,t){return typeof e==`boolean`?e:t}function S(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} is required`);return e.trim()}function C(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}async function w(e){if(e.detach)try{await e.detach()}catch{}}async function T(e,t,n){try{await e.send(t,n)}catch{}}async function E(e){await new Promise(t=>setTimeout(()=>t(),e))}var D=class{state;constructor(e){this.state=e}async handleExtensionListInstalled(e){let t=await(await this.state.collector.getActivePage()).createCDPSession();try{return g((await this.getExtensionTargets(t)).map(e=>({extensionId:e.extensionId,name:e.name,type:e.type,url:e.url})))}catch(e){return _(`extension_list_installed`,e)}finally{await w(t)}}async handleExtensionExecuteInContext(e){let t=S(e.extensionId,`extensionId`),n=S(e.code,`code`),r=x(e.returnByValue,!0),o=await(await this.state.collector.getActivePage()).createCDPSession(),s=null;try{let e=await this.getExtensionTargets(o,t);if(e.length===0)throw Error(`No background target found for extension: ${t}`);let i=this.pickPreferredExtensionTarget(e);s=await a(o,i.targetId);let c=await this.evaluateInAttachedTarget(s,n,r);return g({extensionId:t,target:{type:i.type,url:i.url,name:i.name},result:c.result,exceptionDetails:c.exceptionDetails})}catch(e){return _(`extension_execute_in_context`,e)}finally{s&&await i(o,s).catch(()=>void 0),await w(o)}}async getExtensionTargets(e,t){let n=v(await e.send(`Target.getTargets`)),r=Array.isArray(n.targetInfos)?n.targetInfos:[],i=new Set([`service_worker`,`background_page`]),a=[];for(let e of r){let n=v(e),r=y(n.targetId),o=y(n.type),s=y(n.url);if(!r||!o||!s||!i.has(o))continue;let c=this.extractExtensionId(s);if(!c||t&&c!==t)continue;let l=y(n.title)??``;a.push({targetId:r,extensionId:c,name:l||c,type:o,url:s})}return a.sort((e,t)=>{let n=e.type===`service_worker`?0:1,r=t.type===`service_worker`?0:1;return n===r?e.extensionId.localeCompare(t.extensionId):n-r}),a}pickPreferredExtensionTarget(e){return e.find(e=>e.type===`service_worker`)??e[0]}extractExtensionId(e){return e.match(/^chrome-extension:\/\/([a-p]{32})(?:\/|$)/i)?.[1]??null}async evaluateInAttachedTarget(e,t,n){let r=v(await e.send(`Runtime.evaluate`,{expression:t,returnByValue:n,awaitPromise:!0})),i=v(r.result);return{result:n&&i.value!==void 0?i.value:Object.keys(i).length>0?i:null,exceptionDetails:r.exceptionDetails===void 0?null:r.exceptionDetails}}};function O(e,t,n){return A(e,t,n).then(e=>{let t=m(e.map.mappings),n=new Set(t.map(e=>e.generatedLine));return{resolvedUrl:e.resolvedUrl,map:e.map,mappings:t,mappingsCount:n.size,segmentCount:t.length}})}function k(e,t,n){return A(e,t,n).then(e=>{let{mappingsCount:t,segmentCount:n}=h(e.map.mappings);return{resolvedUrl:e.resolvedUrl,map:e.map,mappingsCount:t,segmentCount:n}})}async function A(e,t,n){let r=F(e,t??``),i=``;i=r.startsWith(`data:`)?P(r):await M(r,n);let a;try{a=JSON.parse(i)}catch{throw Error(`Invalid SourceMap JSON: ${r}`)}return{resolvedUrl:r,map:j(a)}}function j(e){let t=v(e);if(t.version!==3)throw Error(`Only SourceMap version 3 is supported`);let n=y(t.mappings);if(n===void 0)throw Error(`SourceMap.mappings is required`);let r=(Array.isArray(t.sources)?t.sources:[]).map(e=>y(e)).filter(e=>typeof e==`string`),i=(Array.isArray(t.names)?t.names:[]).map(e=>y(e)).filter(e=>typeof e==`string`),a=y(t.sourceRoot),o;return Array.isArray(t.sourcesContent)&&(o=t.sourcesContent.map(e=>typeof e==`string`?e:null)),{version:3,sources:r,sourcesContent:o,mappings:n,names:i,sourceRoot:a}}async function M(e,t){N(e);{let t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{let n=await fetch(e,{signal:t.signal});if(!n.ok)throw Error(`HTTP ${n.status} ${n.statusText}`);return await n.text()}catch(t){if(t.name===`AbortError`)throw Error(`SourceMap fetch timed out after 10s: ${e}`,{cause:t})}finally{clearTimeout(n)}}let n=await r(await t.getActivePage(),async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{let n=await fetch(e,{signal:t.signal});return n.ok?await n.text():`__FETCH_ERROR__HTTP ${n.status} ${n.statusText}`}catch(e){return`__FETCH_ERROR__${e instanceof Error?e.message:String(e)}`}finally{clearTimeout(n)}},e);if(typeof n!=`string`)throw Error(`Failed to fetch SourceMap content`);if(n.startsWith(`__FETCH_ERROR__`))throw Error(n.slice(15)||`Failed to fetch SourceMap content`);return n}function N(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Blocked: unsupported protocol "${t.protocol}"`);let n=t.hostname.toLowerCase(),r=[/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^0\./,/^169\.254\./,/^\[?::1\]?$/,/^\[?fe80:/i,/^\[?fc00:/i,/^\[?fd/i];if([`localhost`,`metadata.google.internal`,`metadata`].includes(n))throw Error(`SSRF blocked: hostname "${n}" is not allowed`);for(let e of r)if(e.test(n))throw Error(`SSRF blocked: protected/reserved IP "${n}" is not allowed`)}function P(e){let t=e.indexOf(`,`);if(t===-1)throw Error(`Invalid data URI source map`);let n=e.slice(0,t),r=e.slice(t+1);return/;base64/i.test(n)?Buffer.from(r,`base64`).toString(`utf-8`):decodeURIComponent(r)}function F(e,t){let n=e.trim();if(!n)return``;if(n.startsWith(`data:`)||b(n)||!t)return n;try{return new URL(n,t).toString()}catch{return n}}function I(e){let t=e.slice(-8192),n=/(?:\/\/[@#]\s*sourceMappingURL=([^\s]+)|\/\*[@#]\s*sourceMappingURL=([^*]+)\*\/)/g,r,i=null;for(;r=n.exec(t),r;){let e=(r[1]??r[2]??``).trim();e&&(i=e)}return i}function L(e,t){if(!e)return t;if(!t)return e;if(b(t)||t.startsWith(`/`))return t;if(b(e))try{let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t,n).toString()}catch{return`${e.replace(/\/+$/g,``)}/${t.replace(/^\/+/g,``)}`}return`${e.replace(/\/+$/g,``)}/${t.replace(/^\/+/g,``)}`}function R(e,t){let n=e.trim();if(!n)return`source_${t+1}.js`;if(n.startsWith(`webpack://`)&&(n=n.slice(10)),n.startsWith(`data:`))return`inline/source_${t+1}.txt`;if(b(n))try{let e=new URL(n);n=`${e.hostname}${e.pathname}`}catch{n=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,``)}n=n.replace(/[?#].*$/g,``),n=n.replace(/^[A-Za-z]:[\\/]/,``),n=n.replace(/^\/+/,``);let r=n.split(/[\\/]+/).map(e=>z(e)).filter(e=>e!==``&&e!==`.`&&e!==`..`);return r.length===0?`source_${t+1}.js`:r.join(`/`)}function z(e){let t=Array.from(e,e=>{let t=e.codePointAt(0);return t!==void 0&&(t<=31||`<>:"|?*`.includes(e))?`_`:e}).join(``).replace(/\s+/g,` `).trim();return!t||t===`.`||t===`..`?`_`:t}function B(e){return e.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,``).replace(/[^a-zA-Z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_|_$/g,``).slice(0,48)}function V(e){let t=0;for(let n of e)n&&(t+=1+V(n.children));return t}var H=class{state;constructor(e){this.state=e}async handleSourcemapDiscover(e){let n=x(e.includeInline,!0),r=await(await this.state.collector.getActivePage()).createCDPSession(),i=new Map,a=e=>{let t=v(e),n=y(t.scriptId);if(!n)return;let r=y(t.url)??``,a=y(t.sourceMapURL)??``,o=i.get(n),s=a?F(a,r):o?.sourceMapUrl??``;i.set(n,{scriptId:n,scriptUrl:r||o?.scriptUrl||``,sourceMapUrl:s,isInline:s.startsWith(`data:`)})};try{r.on?.(`Debugger.scriptParsed`,a),await r.send(`Debugger.enable`),await E(t);for(let e of i.values())if(!e.sourceMapUrl&&!(!e.scriptId||!e.scriptUrl))try{let t=y(v(await r.send(`Debugger.getScriptSource`,{scriptId:e.scriptId})).scriptSource);if(!t)continue;let n=I(t);if(!n)continue;let i=F(n,e.scriptUrl);e.sourceMapUrl=i,e.isInline=i.startsWith(`data:`)}catch{continue}return g(Array.from(i.values()).filter(e=>e.sourceMapUrl.length>0).filter(e=>n||!e.isInline).toSorted((e,t)=>{let n=`${e.scriptUrl}|${e.scriptId}`,r=`${t.scriptUrl}|${t.scriptId}`;return n.localeCompare(r)}).map(e=>({scriptUrl:e.scriptUrl,sourceMapUrl:e.sourceMapUrl,isInline:e.isInline,scriptId:e.scriptId})))}catch(e){return _(`sourcemap_discover`,e)}finally{r.off?.(`Debugger.scriptParsed`,a),await T(r,`Debugger.disable`),await w(r)}}async handleSourcemapFetchAndParse(e){try{let t=await O(S(e.sourceMapUrl,`sourceMapUrl`),C(e.scriptUrl),this.state.collector),n={sources:t.map.sources,mappingsCount:t.mappingsCount,segmentCount:t.segmentCount};return Array.isArray(t.map.sourcesContent)&&(n.sourcesContent=t.map.sourcesContent),g(n)}catch(e){return _(`sourcemap_fetch_and_parse`,e)}}async handleSourcemapCoverage(e){try{let t=S(e.sourceMapUrl,`sourceMapUrl`),n=await O(t,C(e.scriptUrl),this.state.collector),r=new Map,i=new Map,a=0;for(let e=0;e<n.mappings.length;e+=1){let t=n.mappings[e];if(!t)continue;let o=n.mappings[e+1],s=1;if(o&&o.generatedLine===t.generatedLine&&(s=Math.max(o.generatedColumn-t.generatedColumn,1)),t?.sourceIndex===void 0){a+=s;continue}r.set(t.sourceIndex,(r.get(t.sourceIndex)??0)+s),i.set(t.sourceIndex,(i.get(t.sourceIndex)??0)+1)}let o=n.map.sources.map((e,t)=>{let a=r.get(t)??0,o=i.get(t)??0,s=n.map.sourcesContent?.[t],c=typeof s==`string`?Buffer.byteLength(s,`utf-8`):null,l=c===null?null:Math.max(c-a,0),u=c&&c>0?Number((a/c*100).toFixed(2)):null;return{source:e,generatedSegments:o,mappedBytes:a,coveredBytes:a,unmappedBytes:l,coveragePercent:u,coveredPercent:u,sourceContentBytes:c}}),s=o.reduce((e,t)=>e+(typeof t.coveredBytes==`number`?t.coveredBytes:0),0);return g({sourceMapUrl:t,resolvedUrl:n.resolvedUrl,totalMappings:n.segmentCount,mappedSourceCount:o.filter(e=>e.generatedSegments>0).length,coveredBytes:s,uncoveredGeneratedBytes:a,buckets:[{source:`[unmapped]`,generatedSegments:n.mappings.filter(e=>e.sourceIndex===void 0).length,coveredBytes:a}],sources:o})}catch(e){return _(`sourcemap_coverage`,e)}}async handleSourcemapLookup(e){try{let t=S(e.sourceMapUrl,`sourceMapUrl`),n=C(e.scriptUrl),r=Number(e.line),i=Number(e.column);if(!Number.isInteger(r)||r<1)throw Error(`line must be a positive integer`);if(!Number.isFinite(i)||i<0)throw Error(`column must be a non-negative number`);let a=await O(t,n,this.state.collector),o=a.mappings.find(e=>e.generatedLine===r&&e.generatedColumn===i);if(!o){let e=a.mappings.filter(e=>e.generatedLine===r&&e.generatedColumn<=i);o=e.length>0?e[e.length-1]:void 0}if(!o||o.sourceIndex===void 0)return g({success:!1,sourceMapUrl:t,resolvedUrl:a.resolvedUrl,generated:{line:r,column:i},error:`No original source mapping found for generated position`});let s=o.sourceIndex;return g({success:!0,sourceMapUrl:t,resolvedUrl:a.resolvedUrl,generated:{line:r,column:i},original:{source:a.map.sources[s]??null,line:o.originalLine??null,column:o.originalColumn??null,name:typeof o.nameIndex==`number`?a.map.names[o.nameIndex]??null:null,sourceIndex:s},matchType:o.generatedLine===r&&o.generatedColumn===i?`exact`:`closest-preceding`})}catch(e){return _(`sourcemap_lookup`,e)}}async handleSourcemapReconstructTree(e){try{let t=S(e.sourceMapUrl,`sourceMapUrl`),r=C(e.outputDir),i=await k(t,void 0,this.state.collector),a=await n({category:`reports`,toolName:`sourcemap-tree`,target:B(i.resolvedUrl),ext:`tmp`,...r?{customDir:r}:{}}),u=a.absolutePath.replace(/\.tmp$/i,``),d=a.displayPath.replace(/\.tmp$/i,``);await c(u,{recursive:!0});let f=[],p=0;for(let e=0;e<i.map.sources.length;e+=1){let t=i.map.sources[e]??``,n=L(i.map.sourceRoot,t),r=R(n,e),a=s(u,r),d=i.map.sourcesContent&&e<i.map.sourcesContent.length?i.map.sourcesContent[e]:null,m=typeof d==`string`?d:`/* source content missing in source map: ${n} */\n`;try{await c(o(a),{recursive:!0}),await l(a,m,`utf-8`),f.push(r)}catch{p+=1}}return g({outputDir:d,totalSources:i.map.sources.length,writtenFiles:f.length,skippedFiles:p,files:f})}catch(e){return _(`sourcemap_reconstruct_tree`,e)}}async handleSourcemapParseV4(t){let n=S(t.sourceMapUrl,`sourceMapUrl`),r=x(t.extractScopes,!0),i=x(t.extractDebugIds,!0);try{let a=await M(n,this.state.collector),o=JSON.parse(a),s=Array.isArray(o.names)?o.names.filter(e=>typeof e==`string`):[],c=Array.isArray(o.sources)?o.sources.filter(e=>typeof e==`string`):[],l={version:o.version,sources:c.length,names:s.length,mappings:typeof o.mappings==`string`?o.mappings.length:0,hasFile:typeof o.file==`string`,hasSourceRoot:typeof o.sourceRoot==`string`},u={success:!0,sourceMapUrl:n,version:o.version,v3Baseline:l};if(i&&typeof o.debugId==`string`){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o.debugId);u.debugId=o.debugId,u.debugIdValid=e}let d=typeof o.scopes==`string`?o.scopes:typeof o.x_scopes==`string`?o.x_scopes:void 0;if(r&&d)try{let e=U(d,s,c);u.isV4=!0,u.scopes=e,u.scopeCount=V(e.originalScopes),u.generatedRangeCount=e.generatedRanges.length}catch(t){u.success=!1,u.scopeDecodeError=t instanceof Error?t.message:String(t),u.rawScopesField=d.substring(0,e)+(d.length>e?`...`:``),u.isV4=!0}let f={};return o.x_scopeLines&&(f.x_scopeLines=o.x_scopeLines),o.x_namesIdx&&(f.x_namesIdx=o.x_namesIdx),o.x_computedBases&&(f.x_computedBases=o.x_computedBases),Object.keys(f).length>0&&(u.extensions=f),!d&&!o.debugId&&Object.keys(f).length===0&&(u.isV4=!1,u.note=`No v4 fields (scopes/debugId) found. This source map is v3 only.`),t.compareV3===!0&&(u.comparison={v3Only:[`version`,`sources`,`names`,`mappings`,`file`,`sourceRoot`],v4Only:Object.keys(u).filter(e=>![`success`,`sourceMapUrl`,`version`,`v3Baseline`,`comparison`].includes(e))}),g(u)}catch(e){return _(`sourcemap_parse_v4`,e)}}};function U(e,t,n){let r=e.split(`,`),i={value:0},a=[],o=0,s=0,c=0,l=0,u=0,d=0,m=e=>e>0&&e<=t.length?t[e-1]:void 0;function h(e){return e>=0&&e<r.length?r[e]:void 0}function g(e,n){let l=h(i.value++);if(!l?.startsWith(`B`))throw Error(`expected original scope start 'B', got "${l}"`);let u=p(l.slice(1)),d=f(l.slice(1)),m=0,_=u[m++]??0,v=n.line+(u[m++]??0),y=u[m++]??0,b=v===n.line?n.column+y:y,x;_&1&&(o+=d[m++]??0,x=t[o]);let S;_&2&&(s+=d[m++]??0,S=t[s]);let C={index:a.length,sourceIndex:e,start:{line:v,column:b},end:{line:v,column:b},name:x,kind:S,isStackFrame:(_&4)!=0,variables:[],children:[]};a.push(C);let w={line:v,column:b};for(;i.value<r.length;){let n=r[i.value]??``;if(n.startsWith(`D`)){i.value++;let e=f(n.slice(1));for(let n of e)c+=n,C.variables.push(t[c]??`<name:${c}>`);continue}if(n.startsWith(`B`)){let t=g(e,w);w={...t.end},C.children.push(t);continue}break}let T=h(i.value++);if(!T?.startsWith(`C`))throw Error(`expected original scope end 'C', got "${T}"`);let E=p(T.slice(1)),D=w.line+(E[0]??0),O=E[1]??0;return C.end={line:D,column:D===w.line?w.column+O:O},C}function _(e){let t=h(i.value++);if(!t?.startsWith(`E`))throw Error(`expected generated range start 'E', got "${t}"`);let n=p(t.slice(1)),a=f(t.slice(1)),o=0,s=n[o++]??0,c=(s&1)!=0,g=e.line+(c?n[o++]??0:0),v=n[o++]??0,y=g===e.line?e.column+v:v,b;s&2&&(d+=a[o++]??0,b=d);let x={start:{line:g,column:y},end:{line:g,column:y},isStackFrame:(s&4)!=0,isHidden:(s&8)!=0,definitionIndex:b,children:[]},S=new Map,C=0,w={line:g,column:y};for(;i.value<r.length;){let e=r[i.value]??``;if(e.startsWith(`G`)){i.value++,x.bindings=p(e.slice(1)).map(e=>m(e));continue}if(e.startsWith(`H`)){i.value++;let t=p(e.slice(1));x.bindings||=[];let n=0;C+=t[n++]??0;let r=C,a=[],o=S.get(r)??{line:x.start.line,column:x.start.column};for(;n<t.length;){let e=m(t[n++]??0),r=t[n++]??0,i=o.line+r,s=t[n++]??0,c=i===o.line?o.column+s:s;a.push({from:{line:i,column:c},expression:e}),o={line:i,column:c}}for(S.set(r,o);x.bindings.length<=r;)x.bindings.push(void 0);x.bindings[r]=a;continue}if(e.startsWith(`I`)){i.value++;let t=p(e.slice(1));x.callsite={sourceIndex:t[0]??0,line:t[1]??0,column:t[2]??0};continue}if(e.startsWith(`E`)){let e=_(w);w={...e.end},x.children.push(e);continue}break}let T=h(i.value++);if(!T?.startsWith(`F`))throw Error(`expected generated range end 'F', got "${T}"`);let E=p(T.slice(1)),D=E.length===2,O=w.line+(D?E[0]??0:0),k=E[+!!D]??0,A=O===w.line?w.column+k:k;return x.end={line:O,column:A},l=O,u=A,x}let v=Array.from({length:n.length},()=>null);for(let e=0;e<n.length&&i.value<r.length;e++){if((r[i.value]??``)===``){i.value++;continue}if(!(r[i.value]??``).startsWith(`B`))break;v[e]=g(e,{line:0,column:0}),(r[i.value]??``)===``&&i.value++}let y=[];for(;i.value<r.length;){if((r[i.value]??``)===``){i.value++;continue}y.push(_({line:l,column:u}))}return{originalScopes:v,generatedRanges:y}}var W=class{collector;extension;sourcemap;constructor(e){this.collector=e;let t={collector:e};this.extension=new D(t),this.sourcemap=new H(t)}handleExtensionListInstalled(e){return this.extension.handleExtensionListInstalled(e)}handleExtensionExecuteInContext(e){return this.extension.handleExtensionExecuteInContext(e)}handleSourcemapDiscover(e){return this.sourcemap.handleSourcemapDiscover(e)}handleSourcemapFetchAndParse(e){return this.sourcemap.handleSourcemapFetchAndParse(e)}handleSourcemapCoverage(e){return this.sourcemap.handleSourcemapCoverage(e)}handleSourcemapLookup(e){return this.sourcemap.handleSourcemapLookup(e)}handleSourcemapReconstructTree(e){return this.sourcemap.handleSourcemapReconstructTree(e)}handleSourcemapParseV4(e){return this.sourcemap.handleSourcemapParseV4(e)}};export{W as SourcemapToolHandlers};
@@ -0,0 +1 @@
1
+ import{t as e}from"./logger-CCikqqvj.mjs";import{_a as t,va as n}from"./constants-DMv3svps.mjs";import{t as r}from"./RingBuffer-B6RTHmij.mjs";import{d as i,u as a}from"./ensure-browser-core-JHwDo5ql.mjs";import"./definitions-DywfwPMb.mjs";function o(e){return{collector:e,wsSession:null,wsListeners:null,wsConfig:{enabled:!1,maxFrames:1e3},wsFramesByRequest:new Map,wsFrameOrder:new r(1e3),wsConnections:new Map,sseConfig:{maxEvents:2e3}}}function s(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function c(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function l(e,t){let n;if(typeof e==`number`&&Number.isFinite(e))n=e;else if(typeof e==`string`){let t=Number(e.trim());Number.isFinite(t)&&(n=t)}return n===void 0&&(n=t.defaultValue),t.integer&&(n=Math.trunc(n)),n<t.min&&(n=t.min),n>t.max&&(n=t.max),n}function u(e){return e===`sent`||e===`received`||e===`all`?e:`all`}function d(e){try{return{regex:new RegExp(e)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}const f=e=>typeof e==`object`&&e?e:void 0,p=(e,t)=>{let n=f(e)?.[t];return typeof n==`string`?n:void 0},m=(e,t)=>{let n=f(e)?.[t];return typeof n==`number`?n:void 0},h=(e,t)=>{let n=f(e)?.[t];return f(n)};var g=class{s;constructor(e){this.s=e}async teardownWsSession(){if(this.s.wsSession&&this.s.wsListeners){try{this.s.wsSession.off(`Network.webSocketCreated`,this.s.wsListeners.created)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketCreated listener`,t)}try{this.s.wsSession.off(`Network.webSocketClosed`,this.s.wsListeners.closed)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketClosed listener`,t)}try{this.s.wsSession.off(`Network.webSocketHandshakeResponseReceived`,this.s.wsListeners.handshake)}catch(t){e.debug(`[ws-teardown] Failed to remove handshakeResponseReceived listener`,t)}try{this.s.wsSession.off(`Network.webSocketFrameSent`,this.s.wsListeners.frameSent)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketFrameSent listener`,t)}try{this.s.wsSession.off(`Network.webSocketFrameReceived`,this.s.wsListeners.frameReceived)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketFrameReceived listener`,t)}}if(this.s.wsSession)try{await this.s.wsSession.detach()}catch(t){e.debug(`[ws-teardown] Failed to detach CDP session`,t)}this.s.wsSession=null,this.s.wsListeners=null}handleWsFrame(e,r){let i=p(r,`requestId`);if(!i)return;if(!this.s.wsConnections.get(i)){if(this.s.wsConfig.urlFilter)return;this.s.wsConnections.set(i,{requestId:i,url:`unknown`,status:`open`,framesCount:0,createdTimestamp:Date.now()/1e3})}let a=this.s.wsConnections.get(i);if(!a||this.s.wsConfig.urlFilter&&a.url!==`unknown`&&!this.s.wsConfig.urlFilter.test(a.url))return;let o=h(r,`response`),s=m(o,`opcode`)??-1,c=p(o,`payloadData`)??``,l=c.length>t?`${c.slice(0,t)}…`:c,u=c.length>n?c.slice(0,n):c,d={requestId:i,timestamp:m(r,`timestamp`)??Date.now()/1e3,direction:e,opcode:s,payloadLength:c.length,payloadPreview:l,payloadSample:u,isBinary:s===2};this.appendWsFrame(i,d)}appendWsFrame(e,t){let n=this.s.wsFramesByRequest.get(e)??[];n.push(t),this.s.wsFramesByRequest.set(e,n);let r=this.s.wsConnections.get(e);r&&(r.framesCount+=1,r.status===`connecting`&&(r.status=`open`)),this.s.wsFrameOrder.push({requestId:e,frame:t}),this.enforceWsFrameLimit()}enforceWsFrameLimit(){for(;this.s.wsFrameOrder.length>this.s.wsConfig.maxFrames;){let e=this.s.wsFrameOrder.shift();if(!e)break;let t=this.s.wsFramesByRequest.get(e.requestId);t&&t.length>0&&(t.shift(),t.length===0?this.s.wsFramesByRequest.delete(e.requestId):this.s.wsFramesByRequest.set(e.requestId,t));let n=this.s.wsConnections.get(e.requestId);n&&(n.framesCount=Math.max(0,n.framesCount-1))}}getWsFrameStats(){let e=0,t=0;for(let n of this.s.wsFrameOrder)n.frame.direction===`sent`?e+=1:t+=1;return{total:this.s.wsFrameOrder.length,sent:e,received:t}}async handleWsMonitorEnable(e){let t=l(e.maxFrames,{defaultValue:1e3,min:1,max:2e4,integer:!0}),n=c(e.urlFilter),i;if(n){let e=d(n);if(e.error)return s({success:!1,error:`Invalid urlFilter regex: ${e.error}`});i=e.regex}await this.teardownWsSession(),this.s.wsFramesByRequest.clear(),this.s.wsFrameOrder=new r(t),this.s.wsConnections.clear();let a=await(await this.s.collector.getActivePage()).createCDPSession();await a.send(`Network.enable`);let o={created:e=>{let t=p(e,`requestId`),n=p(e,`url`);if(!t||!n||i&&!i.test(n))return;let r=this.s.wsConnections.get(t);this.s.wsConnections.set(t,{requestId:t,url:n,status:r?.status??`connecting`,framesCount:r?.framesCount??0,createdTimestamp:r?.createdTimestamp??Date.now()/1e3,closedTimestamp:r?.closedTimestamp,handshakeStatus:r?.handshakeStatus})},closed:e=>{let t=p(e,`requestId`);if(!t)return;let n=this.s.wsConnections.get(t);if(!n)return;n.status=`closed`;let r=m(e,`timestamp`);n.closedTimestamp=r===void 0?Date.now()/1e3:r},handshake:e=>{let t=p(e,`requestId`);if(!t)return;let n=this.s.wsConnections.get(t);if(!n)return;let r=m(h(e,`response`),`status`);r!==void 0&&(n.handshakeStatus=r,n.status=r>=100&&r<400?`open`:`error`)},frameSent:e=>{this.handleWsFrame(`sent`,e)},frameReceived:e=>{this.handleWsFrame(`received`,e)}};return a.on(`Network.webSocketCreated`,o.created),a.on(`Network.webSocketClosed`,o.closed),a.on(`Network.webSocketHandshakeResponseReceived`,o.handshake),a.on(`Network.webSocketFrameSent`,o.frameSent),a.on(`Network.webSocketFrameReceived`,o.frameReceived),this.s.wsSession=a,this.s.wsListeners=o,this.s.wsConfig={enabled:!0,maxFrames:t,urlFilterRaw:n,urlFilter:i},s({success:!0,message:`WebSocket monitor enabled`,config:{maxFrames:t,urlFilter:n??null},stats:{trackedConnections:this.s.wsConnections.size,capturedFrames:this.s.wsFrameOrder.length}})}async handleWsMonitorDisable(e){let t=this.getWsFrameStats(),n=Array.from(this.s.wsConnections.values()),r={success:!0,message:`WebSocket monitor disabled`,config:{maxFrames:this.s.wsConfig.maxFrames,urlFilter:this.s.wsConfig.urlFilterRaw??null},summary:{trackedConnections:n.length,activeConnections:n.filter(e=>e.status===`open`||e.status===`connecting`).length,closedConnections:n.filter(e=>e.status===`closed`).length,totalFrames:t.total,sentFrames:t.sent,receivedFrames:t.received}};return await this.teardownWsSession(),this.s.wsConfig={...this.s.wsConfig,enabled:!1},s(r)}async handleWsGetFrames(e){let t=u(e.direction),n=l(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),r=l(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0}),i=c(e.payloadFilter),a;if(i){let e=d(i);if(e.error)return s({success:!1,error:`Invalid payloadFilter regex: ${e.error}`});a=e.regex}let o=this.s.wsFrameOrder.toArray().map(e=>e.frame).filter(e=>t===`all`?!0:e.direction===t).filter(e=>a?a.test(e.payloadSample):!0),f=o.slice(r,r+n).map(e=>({requestId:e.requestId,timestamp:e.timestamp,direction:e.direction,opcode:e.opcode,payloadLength:e.payloadLength,payloadPreview:e.payloadPreview,isBinary:e.isBinary}));return s({success:!0,monitorEnabled:this.s.wsConfig.enabled,filters:{direction:t,payloadFilter:i??null},page:{offset:r,limit:n,returned:f.length,totalAfterFilter:o.length,hasMore:r+f.length<o.length,nextOffset:r+f.length<o.length?r+f.length:null},frames:f})}async handleWsGetConnections(e){let t=Array.from(this.s.wsConnections.values()).toSorted((e,t)=>e.createdTimestamp-t.createdTimestamp).map(e=>({requestId:e.requestId,url:e.url,status:e.status,framesCount:e.framesCount}));return s({success:!0,monitorEnabled:this.s.wsConfig.enabled,total:t.length,connections:t})}};function _(e){let t=window;t.__jshookSSEMonitor||={enabled:!0,patched:!1,maxEvents:e.maxEvents,urlFilterRaw:e.urlFilterRaw,events:[],sources:{}};let n=t.__jshookSSEMonitor;n.enabled=!0,n.maxEvents=e.maxEvents,n.urlFilterRaw=e.urlFilterRaw,n.events.length>n.maxEvents&&(n.events=n.events.slice(-n.maxEvents));let r=e=>{if(!n.urlFilterRaw)return!0;try{return new RegExp(n.urlFilterRaw).test(e)}catch{return!0}},i=e=>{if(typeof e==`string`)return e;if(e==null)return``;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return`[unserializable]`}return String(e)},a=(e,t,a,o)=>{if(!n.enabled||!r(e))return;let s=i(a),c={sourceUrl:e,eventType:t,dataPreview:s.length>200?`${s.slice(0,200)}…`:s,dataLength:s.length,lastEventId:o,timestamp:Date.now()};for(n.events.push(c);n.events.length>n.maxEvents;)n.events.shift();let l=n.sources[e]??{url:e,status:`connecting`,eventCount:0};l.eventCount+=1,l.lastEventTimestamp=c.timestamp,n.sources[e]=l};if(t.EventSource===void 0)return{success:!1,error:`EventSource is not available in current page context`};if(!n.patched){let e=t.EventSource,i=function(t,i){let o=String(t),s=new e(t,i);if(r(o)){let e=n.sources[o]??{url:o,status:`connecting`,eventCount:0};n.sources[o]=e}s.addEventListener(`open`,()=>{let e=n.sources[o];e&&(e.status=`open`),a(o,`open`,``,null)}),s.addEventListener(`error`,()=>{let e=n.sources[o];e&&(e.status=`error`),a(o,`error`,``,null)}),s.addEventListener(`message`,e=>{let t=typeof e.lastEventId==`string`&&e.lastEventId.length>0?e.lastEventId:null;a(o,e.type||`message`,e.data,t)});let c=s.addEventListener.bind(s),l=(e,t,n)=>{c(e,t,n)};return Object.defineProperty(s,"addEventListener",{value:(e,t,n)=>{if(e!==`message`&&e!==`open`&&e!==`error`&&t){l(e,n=>{let r=n,i=typeof r.lastEventId==`string`&&r.lastEventId.length>0?r.lastEventId:null;a(o,e,r.data,i),typeof t==`function`?t.call(s,n):t.handleEvent(n)},n);return}l(e,t,n)},configurable:!0,writable:!0}),s};i.prototype=e.prototype;try{Object.defineProperty(i,"CONNECTING",{value:e.CONNECTING}),Object.defineProperty(i,"OPEN",{value:e.OPEN}),Object.defineProperty(i,"CLOSED",{value:e.CLOSED})}catch{}t.EventSource=i,n.originalEventSource=e,n.patched=!0}return{success:!0,message:`SSE monitor enabled`,patched:n.patched,urlFilter:n.urlFilterRaw,maxEvents:n.maxEvents,existingEvents:n.events.length}}var v=class{s;constructor(e){this.s=e}async enableSseInterceptor(e,t,n){let r=await this.s.collector.getActivePage();return n?.persistent?(await a(r,_,{maxEvents:e,urlFilterRaw:t}),{success:!0,message:`SSE monitor enabled (persistent — survives navigations)`,patched:!0,urlFilter:t,maxEvents:e,existingEvents:0}):await i(r,_,{maxEvents:e,urlFilterRaw:t})}async handleSseMonitorEnable(e){let t=l(e.maxEvents,{defaultValue:2e3,min:1,max:5e4,integer:!0}),n=c(e.urlFilter);if(n){let e=d(n);if(e.error)return s({success:!1,error:`Invalid urlFilter regex: ${e.error}`})}let r=e.persistent===!0,i=await this.enableSseInterceptor(t,n,{persistent:r});return i.success?(this.s.sseConfig={maxEvents:t,urlFilterRaw:n},s({success:!0,message:i.message,patched:i.patched,config:{maxEvents:this.s.sseConfig.maxEvents,urlFilter:this.s.sseConfig.urlFilterRaw??null},existingEvents:i.existingEvents})):s(i)}async handleSseGetEvents(e){let t=c(e.sourceUrl),n=c(e.eventType),r=l(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),a=l(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0});return s(await i(await this.s.collector.getActivePage(),e=>{let t=window.__jshookSSEMonitor;if(!t)return{success:!1,message:`SSE monitor is not enabled. Call sse_monitor_enable first.`};let n=t.events;e.sourceUrl&&(n=n.filter(t=>t.sourceUrl===e.sourceUrl)),e.eventType&&(n=n.filter(t=>t.eventType===e.eventType));let r=n.length,i=n.slice(e.offset,e.offset+e.limit);return{success:!0,filters:{sourceUrl:e.sourceUrl??null,eventType:e.eventType??null},page:{offset:e.offset,limit:e.limit,returned:i.length,totalAfterFilter:r,hasMore:e.offset+i.length<r,nextOffset:e.offset+i.length<r?e.offset+i.length:null},monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,sourceCount:Object.keys(t.sources).length},events:i}},{sourceUrl:t,eventType:n,limit:r,offset:a}))}},y=class{collector;state;ws;sse;get wsConnections(){return this.state.wsConnections}get wsFrameOrder(){return this.state.wsFrameOrder}get wsConfig(){return this.state.wsConfig}get wsFramesByRequest(){return this.state.wsFramesByRequest}get sseConfig(){return this.state.sseConfig}constructor(e){this.collector=e,this.state=o(e),this.ws=new g(this.state),this.sse=new v(this.state)}handleWsMonitorDispatch=e=>String(e.action??``)===`disable`?this.ws.handleWsMonitorDisable(e):this.ws.handleWsMonitorEnable(e);handleWsMonitorEnable=e=>this.ws.handleWsMonitorEnable(e);handleWsMonitorDisable=e=>this.ws.handleWsMonitorDisable(e);handleWsGetFrames=e=>this.ws.handleWsGetFrames(e);handleWsGetConnections=e=>this.ws.handleWsGetConnections(e);handleSseMonitorEnable=e=>this.sse.handleSseMonitorEnable(e);handleSseGetEvents=e=>this.sse.handleSseGetEvents(e)};export{y as StreamingToolHandlers};
@@ -1,4 +1,4 @@
1
- import{$r as e,Qr as t,Zr as n,ei as r,gi as i,hi as a,mi as o,pi as s,ti as c}from"./constants-BYj8Xek8.mjs";import{a as l,n as u}from"./response-C7rKQst4.mjs";import{t as d}from"./ProcessRegistry-C-bN48oR.mjs";import"./modules-BPBcSaM-.mjs";import{s as f}from"./PageController-Dfsm1_o7.mjs";import{t as p}from"./ScriptManager-LWGPTdvD.mjs";import"./definitions-DxFNRQNK2.mjs";import{Worker as m}from"node:worker_threads";const h=i,g=a,_=s,v=o;var y=class{name;workerScript;minWorkers;maxWorkers;idleTimeoutMs;resourceLimits;workers=new Map;queuedJobs=[];activeJobs=new Map;nextWorkerId=1;nextJobId=1;closed=!1;constructor(e){if(this.name=e.name??`worker-pool`,this.workerScript=e.workerScript,this.minWorkers=e.minWorkers??h,this.maxWorkers=e.maxWorkers??g,this.idleTimeoutMs=e.idleTimeoutMs??_,this.resourceLimits=e.resourceLimits,!this.workerScript||this.workerScript.trim().length===0)throw this.toError(`workerScript must be a non-empty string`);if(!Number.isInteger(this.minWorkers)||this.minWorkers<0)throw this.toError(`minWorkers must be an integer >= 0`);if(!Number.isInteger(this.maxWorkers)||this.maxWorkers<1)throw this.toError(`maxWorkers must be an integer >= 1`);if(this.minWorkers>this.maxWorkers)throw this.toError(`minWorkers cannot be greater than maxWorkers`);this.ensureMinWorkers()}submit(e,t=v){return this.closed?Promise.reject(this.toError(`pool is closed`)):new Promise((n,r)=>{let i={id:this.nextJobId++,payload:e,timeoutMs:t,resolve:n,reject:r};this.queuedJobs.push(i),this.pumpQueue()})}async warmup(e=1){if(this.closed)return;let t=Math.min(e,this.maxWorkers-this.workers.size);for(let e=0;e<t;e++){let e=this.spawnWorker();this.armIdleTimer(e)}}async close(){if(this.closed)return;this.closed=!0;let e=this.toError(`pool is closed`);for(;this.queuedJobs.length>0;)this.queuedJobs.shift()?.reject(e);for(let t of this.activeJobs.values())t.timeoutHandle&&clearTimeout(t.timeoutHandle),t.reject(e);this.activeJobs.clear();let t=Array.from(this.workers.keys());await Promise.all(t.map(e=>this.terminateWorker(e)))}async drainIdle(){if(this.closed)return;let e=[];for(let[t,n]of this.workers)!n.busy&&this.workers.size-e.length>this.minWorkers&&e.push(t);await Promise.all(e.map(e=>this.terminateWorker(e)))}ensureMinWorkers(){if(!this.closed)for(;this.workers.size<this.minWorkers;)this.spawnWorker()}pumpQueue(){if(!this.closed)for(;this.queuedJobs.length>0;){let e=this.findIdleWorker();if(!e)if(this.workers.size<this.maxWorkers)e=this.spawnWorker();else return;let t=this.queuedJobs.shift();if(!t)return;this.dispatchJob(e,t)}}findIdleWorker(){for(let e of this.workers.values())if(!e.busy)return e}spawnWorker(){let e=this.nextWorkerId++,t=new m(this.workerScript,{eval:!0,resourceLimits:this.resourceLimits});typeof t.unref==`function`&&t.unref(),d.register(t);let n={id:e,worker:t,busy:!1,activeJobId:null,idleTimer:null};return t.on(`message`,t=>this.handleWorkerMessage(e,t)),t.on(`error`,t=>this.handleWorkerFailure(e,t)),t.on(`exit`,t=>this.handleWorkerExit(e,t)),this.workers.set(e,n),n}dispatchJob(e,t){e.busy=!0,e.activeJobId=t.id,e.idleTimer&&=(clearTimeout(e.idleTimer),null);let n=setTimeout(()=>{this.handleJobTimeout(t.id,t.timeoutMs)},t.timeoutMs);this.activeJobs.set(t.id,{...t,workerId:e.id,timeoutHandle:n});try{e.worker.postMessage({jobId:t.id,payload:t.payload})}catch(n){let r=this.activeJobs.get(t.id);r?.timeoutHandle&&clearTimeout(r.timeoutHandle),this.activeJobs.delete(t.id),e.busy=!1,e.activeJobId=null,t.reject(this.toError(n instanceof Error?n.message:String(n))),this.terminateWorker(e.id).then(()=>{this.ensureMinWorkers(),this.pumpQueue()})}}handleWorkerMessage(e,t){let n=t;if(!n||typeof n!=`object`||typeof n.jobId!=`number`)return;let r=this.activeJobs.get(n.jobId);if(!r)return;r.timeoutHandle&&clearTimeout(r.timeoutHandle),this.activeJobs.delete(n.jobId);let i=this.workers.get(e);i&&(i.busy=!1,i.activeJobId=null,this.armIdleTimer(i)),n.ok?n.result===void 0?r.reject(this.toError(`worker returned empty result`)):r.resolve(n.result):r.reject(this.toError(n.error??`worker task failed`)),this.pumpQueue()}handleWorkerFailure(e,t){let n=this.workers.get(e);if(!n)return;let r=n.activeJobId;if(r!==null){let e=this.activeJobs.get(r);e&&(e.timeoutHandle&&clearTimeout(e.timeoutHandle),this.activeJobs.delete(r),e.reject(this.toError(t.message)))}this.terminateWorker(e).then(()=>{this.ensureMinWorkers(),this.pumpQueue()})}handleWorkerExit(e,t){let n=this.workers.get(e);if(!n)return;let r=n.activeJobId;if(this.workers.delete(e),n.idleTimer&&clearTimeout(n.idleTimer),r!==null){let e=this.activeJobs.get(r);e&&(e.timeoutHandle&&clearTimeout(e.timeoutHandle),this.activeJobs.delete(r),e.reject(this.toError(`worker exited unexpectedly with code ${t}`)))}this.ensureMinWorkers(),this.pumpQueue()}handleJobTimeout(e,t){let n=this.activeJobs.get(e);n&&(this.activeJobs.delete(e),n.reject(this.toError(`worker task timed out after ${t}ms`)),this.terminateWorker(n.workerId).then(()=>{this.ensureMinWorkers(),this.pumpQueue()}))}armIdleTimer(e){this.idleTimeoutMs<=0||this.workers.size<=this.minWorkers||(e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{let t=this.workers.get(e.id);!t||t.busy||this.workers.size<=this.minWorkers||this.terminateWorker(e.id)},this.idleTimeoutMs))}async terminateWorker(e){let t=this.workers.get(e);if(t){this.workers.delete(e),t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=null,t.worker.removeAllListeners(`message`),t.worker.removeAllListeners(`error`),t.worker.removeAllListeners(`exit`);try{await t.worker.terminate()}catch{}}}toError(e){return Error(`[${this.name}] ${e}`)}};const b=new Set([`constant_fold`,`string_decrypt`,`dead_code_remove`,`control_flow_flatten`,`rename_vars`]),x=/\b(-?\d+(?:\.\d+)?)\s*([+\-*/%])\s*(-?\d+(?:\.\d+)?)\b/g,S=/(['"])((?:\\.|(?!\1)[^\\])*)\1\s*\+\s*(['"])((?:\\.|(?!\3)[^\\])*)\3/g,C=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,w=/if\s*\(\s*(?:false|0|!0\s*===\s*!1)\s*\)\s*\{([\s\S]*?)\}\s*else\s*\{([\s\S]*?)\}/g,T=/if\s*\(\s*(?:false|0|!0\s*===\s*!1)\s*\)\s*\{[\s\S]*?\}/g,E=c,D=[`cryptojs`,`md5`,`sha`,`hmac`,`sign`,`signature`,`encrypt`,`decrypt`,`aes`,`rsa`];function O(i){return{collector:i,chains:new Map,cryptoHarnessPool:new y({name:`crypto-harness`,workerScript:`
1
+ import{Gi as e,Ji as t,Ki as n,Wi as r,ca as i,la as a,qi as o,sa as s,ua as c}from"./constants-DMv3svps.mjs";import{a as l,n as u}from"./response-B1RuVVfD.mjs";import{t as d}from"./ProcessRegistry-D5y1yuP2.mjs";import"./modules-DO3jXCgj.mjs";import{d as f,r as p}from"./ensure-browser-core-JHwDo5ql.mjs";import"./definitions-Cv5r8xwq.mjs";import{Worker as m}from"node:worker_threads";const h=c,g=a,_=s,v=i;var y=class{name;workerScript;minWorkers;maxWorkers;idleTimeoutMs;resourceLimits;workers=new Map;queuedJobs=[];activeJobs=new Map;nextWorkerId=1;nextJobId=1;closed=!1;constructor(e){if(this.name=e.name??`worker-pool`,this.workerScript=e.workerScript,this.minWorkers=e.minWorkers??h,this.maxWorkers=e.maxWorkers??g,this.idleTimeoutMs=e.idleTimeoutMs??_,this.resourceLimits=e.resourceLimits,!this.workerScript||this.workerScript.trim().length===0)throw this.toError(`workerScript must be a non-empty string`);if(!Number.isInteger(this.minWorkers)||this.minWorkers<0)throw this.toError(`minWorkers must be an integer >= 0`);if(!Number.isInteger(this.maxWorkers)||this.maxWorkers<1)throw this.toError(`maxWorkers must be an integer >= 1`);if(this.minWorkers>this.maxWorkers)throw this.toError(`minWorkers cannot be greater than maxWorkers`);this.ensureMinWorkers()}submit(e,t=v){return this.closed?Promise.reject(this.toError(`pool is closed`)):new Promise((n,r)=>{let i={id:this.nextJobId++,payload:e,timeoutMs:t,resolve:n,reject:r};this.queuedJobs.push(i),this.pumpQueue()})}async warmup(e=1){if(this.closed)return;let t=Math.min(e,this.maxWorkers-this.workers.size);for(let e=0;e<t;e++){let e=this.spawnWorker();this.armIdleTimer(e)}}async close(){if(this.closed)return;this.closed=!0;let e=this.toError(`pool is closed`);for(;this.queuedJobs.length>0;)this.queuedJobs.shift()?.reject(e);for(let t of this.activeJobs.values())t.timeoutHandle&&clearTimeout(t.timeoutHandle),t.reject(e);this.activeJobs.clear();let t=Array.from(this.workers.keys());await Promise.all(t.map(e=>this.terminateWorker(e)))}async drainIdle(){if(this.closed)return;let e=[];for(let[t,n]of this.workers)!n.busy&&this.workers.size-e.length>this.minWorkers&&e.push(t);await Promise.all(e.map(e=>this.terminateWorker(e)))}ensureMinWorkers(){if(!this.closed)for(;this.workers.size<this.minWorkers;)this.spawnWorker()}pumpQueue(){if(!this.closed)for(;this.queuedJobs.length>0;){let e=this.findIdleWorker();if(!e)if(this.workers.size<this.maxWorkers)e=this.spawnWorker();else return;let t=this.queuedJobs.shift();if(!t)return;this.dispatchJob(e,t)}}findIdleWorker(){for(let e of this.workers.values())if(!e.busy)return e}spawnWorker(){let e=this.nextWorkerId++,t=new m(this.workerScript,{eval:!0,resourceLimits:this.resourceLimits});typeof t.unref==`function`&&t.unref(),d.register(t);let n={id:e,worker:t,busy:!1,activeJobId:null,idleTimer:null};return t.on(`message`,t=>this.handleWorkerMessage(e,t)),t.on(`error`,t=>this.handleWorkerFailure(e,t)),t.on(`exit`,t=>this.handleWorkerExit(e,t)),this.workers.set(e,n),n}dispatchJob(e,t){e.busy=!0,e.activeJobId=t.id,e.idleTimer&&=(clearTimeout(e.idleTimer),null);let n=setTimeout(()=>{this.handleJobTimeout(t.id,t.timeoutMs)},t.timeoutMs);this.activeJobs.set(t.id,{...t,workerId:e.id,timeoutHandle:n});try{e.worker.postMessage({jobId:t.id,payload:t.payload})}catch(n){let r=this.activeJobs.get(t.id);r?.timeoutHandle&&clearTimeout(r.timeoutHandle),this.activeJobs.delete(t.id),e.busy=!1,e.activeJobId=null,t.reject(this.toError(n instanceof Error?n.message:String(n))),this.terminateWorker(e.id).then(()=>{this.ensureMinWorkers(),this.pumpQueue()})}}handleWorkerMessage(e,t){let n=t;if(!n||typeof n!=`object`||typeof n.jobId!=`number`)return;let r=this.activeJobs.get(n.jobId);if(!r)return;r.timeoutHandle&&clearTimeout(r.timeoutHandle),this.activeJobs.delete(n.jobId);let i=this.workers.get(e);i&&(i.busy=!1,i.activeJobId=null,this.armIdleTimer(i)),n.ok?n.result===void 0?r.reject(this.toError(`worker returned empty result`)):r.resolve(n.result):r.reject(this.toError(n.error??`worker task failed`)),this.pumpQueue()}handleWorkerFailure(e,t){let n=this.workers.get(e);if(!n)return;let r=n.activeJobId;if(r!==null){let e=this.activeJobs.get(r);e&&(e.timeoutHandle&&clearTimeout(e.timeoutHandle),this.activeJobs.delete(r),e.reject(this.toError(t.message)))}this.terminateWorker(e).then(()=>{this.ensureMinWorkers(),this.pumpQueue()})}handleWorkerExit(e,t){let n=this.workers.get(e);if(!n)return;let r=n.activeJobId;if(this.workers.delete(e),n.idleTimer&&clearTimeout(n.idleTimer),r!==null){let e=this.activeJobs.get(r);e&&(e.timeoutHandle&&clearTimeout(e.timeoutHandle),this.activeJobs.delete(r),e.reject(this.toError(`worker exited unexpectedly with code ${t}`)))}this.ensureMinWorkers(),this.pumpQueue()}handleJobTimeout(e,t){let n=this.activeJobs.get(e);n&&(this.activeJobs.delete(e),n.reject(this.toError(`worker task timed out after ${t}ms`)),this.terminateWorker(n.workerId).then(()=>{this.ensureMinWorkers(),this.pumpQueue()}))}armIdleTimer(e){this.idleTimeoutMs<=0||this.workers.size<=this.minWorkers||(e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{let t=this.workers.get(e.id);!t||t.busy||this.workers.size<=this.minWorkers||this.terminateWorker(e.id)},this.idleTimeoutMs))}async terminateWorker(e){let t=this.workers.get(e);if(t){this.workers.delete(e),t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=null,t.worker.removeAllListeners(`message`),t.worker.removeAllListeners(`error`),t.worker.removeAllListeners(`exit`);try{await t.worker.terminate()}catch{}}}toError(e){return Error(`[${this.name}] ${e}`)}};const b=new Set([`constant_fold`,`string_decrypt`,`dead_code_remove`,`control_flow_flatten`,`rename_vars`]),x=/\b(-?\d+(?:\.\d+)?)\s*([+\-*/%])\s*(-?\d+(?:\.\d+)?)\b/g,S=/(['"])((?:\\.|(?!\1)[^\\])*)\1\s*\+\s*(['"])((?:\\.|(?!\3)[^\\])*)\3/g,C=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,w=/if\s*\(\s*(?:false|0|!0\s*===\s*!1)\s*\)\s*\{([\s\S]*?)\}\s*else\s*\{([\s\S]*?)\}/g,T=/if\s*\(\s*(?:false|0|!0\s*===\s*!1)\s*\)\s*\{[\s\S]*?\}/g,E=t,D=[`cryptojs`,`md5`,`sha`,`hmac`,`sign`,`signature`,`encrypt`,`decrypt`,`aes`,`rsa`];function O(t){return{collector:t,chains:new Map,cryptoHarnessPool:new y({name:`crypto-harness`,workerScript:`
2
2
  const __bootstrap = async () => {
3
3
  const [workerThreads, vm, perfHooks] = await Promise.all([
4
4
  import('node:worker_threads'), import('node:vm'), import('node:perf_hooks'),
@@ -81,7 +81,7 @@ __bootstrap().catch((error) => {
81
81
  if (typeof console !== 'undefined' && typeof console.error === 'function')
82
82
  console.error('crypto harness worker bootstrap failed:', error && error.message ? error.message : String(error));
83
83
  });
84
- `,minWorkers:0,maxWorkers:e,idleTimeoutMs:n,resourceLimits:{maxOldGenerationSizeMb:t,maxYoungGenerationSizeMb:r,stackSizeMb:8}})}}function k(e,t){return u({tool:e,...l(t)})}function A(e){let t=Array.isArray(e)?e.map(e=>String(e).trim()).filter(e=>e.length>0):typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];if(t.length===0)throw Error(`transforms must contain at least one transform`);let n=[],r=new Set;for(let e of t){if(!b.has(e))throw Error(`Unsupported transform: ${e}`);r.has(e)||(r.add(e),n.push(e))}return n}function j(e){if(!Array.isArray(e))throw Error(`testInputs must be an array of strings`);let t=e.map(e=>String(e));if(t.length===0)throw Error(`testInputs cannot be empty`);return t}function M(e,t){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return t}function N(e,t){if(typeof e!=`string`||e.length===0)throw Error(`${t} must be a non-empty string`);return e}function P(e,t){let n=e.replace(/\\/g,`\\\\`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);return t===`"`?n.replace(/"/g,`\\"`):n.replace(/'/g,`\\'`)}function F(e){return e.replace(/\\x([0-9a-fA-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\u\{([0-9a-fA-F]{1,6})\}/g,(e,t)=>String.fromCodePoint(parseInt(t,16))).replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\n/g,`
84
+ `,minWorkers:0,maxWorkers:n,idleTimeoutMs:r,resourceLimits:{maxOldGenerationSizeMb:e,maxYoungGenerationSizeMb:o,stackSizeMb:8}})}}function k(e,t){return u({tool:e,...l(t)})}function A(e){let t=Array.isArray(e)?e.map(e=>String(e).trim()).filter(e=>e.length>0):typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];if(t.length===0)throw Error(`transforms must contain at least one transform`);let n=[],r=new Set;for(let e of t){if(!b.has(e))throw Error(`Unsupported transform: ${e}`);r.has(e)||(r.add(e),n.push(e))}return n}function j(e){if(!Array.isArray(e))throw Error(`testInputs must be an array of strings`);let t=e.map(e=>String(e));if(t.length===0)throw Error(`testInputs cannot be empty`);return t}function M(e,t){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return t}function N(e,t){if(typeof e!=`string`||e.length===0)throw Error(`${t} must be a non-empty string`);return e}function P(e,t){let n=e.replace(/\\/g,`\\\\`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);return t===`"`?n.replace(/"/g,`\\"`):n.replace(/'/g,`\\'`)}function F(e){return e.replace(/\\x([0-9a-fA-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\u\{([0-9a-fA-F]{1,6})\}/g,(e,t)=>String.fromCodePoint(parseInt(t,16))).replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\n/g,`
85
85
  `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\v/g,`\v`).replace(/\\f/g,`\f`).replace(/\\0/g,`\0`).replace(/\\"/g,`"`).replace(/\\'/g,`'`).replace(/\\\\/g,`\\`)}async function I(e,t){let n=null;try{n=new p(e);let r=await n.getScriptSource(t);if(r?.source&&r.source.length>0)return r.source}catch{}finally{if(n)try{await n.close()}catch{}}let r=e.getFileByUrl(t);if(r?.content&&r.content.length>0)return r.content;let i=await(await e.getActivePage()).evaluate(async e=>{let t=Array.from(document.scripts),n=Number(e);if(Number.isInteger(n)&&n>=0&&n<t.length){let e=t[n];if(e.textContent&&e.textContent.trim().length>0)return e.textContent;if(e.src)try{let t=await fetch(e.src);if(t.ok)return await t.text()}catch{}}for(let n of t){if(n.id===e||n.dataset?.scriptId===e){if(n.textContent&&n.textContent.trim().length>0)return n.textContent;if(n.src)try{let e=await fetch(n.src);if(e.ok)return await e.text()}catch{}}if(n.src&&n.src.includes(e))try{let e=await fetch(n.src);if(e.ok)return await e.text()}catch{}}return``},t);if(typeof i==`string`&&i.length>0)return i;throw Error(`Unable to resolve source from scriptId: ${t}`)}function L(e){let t=(e.startsWith(`window.`)?e.slice(7):e).split(`.`).filter(Boolean);return t.length>0?t[t.length-1]:``}function R(e,t,n){let r=L(e);if(z(r))return r;let i=L(t);if(z(i))return i;let a=n.match(/function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/);return a?.[1]&&z(a[1])?a[1]:`extractedCryptoFn`}function z(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function B(e){await e.warmup(1)}function V(){return`const __textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;
86
86
  const __textDecoder = typeof TextDecoder !== 'undefined' ? new TextDecoder() : null;
87
87
  if (typeof globalThis.atob === 'undefined') {
@@ -1,7 +1,7 @@
1
- import{ai as e,ci as t,ii as n,oi as r,si as i}from"./constants-BYj8Xek8.mjs";import{i as a}from"./modules-BPBcSaM-.mjs";import{i as o}from"./artifacts-CkodUM4j.mjs";import{a as s,o as c,r as l,s as u,t as d}from"./parse-args-Bw413PlW.mjs";import{t as f}from"./ResponseBuilder-BfWP-uaT.mjs";import{n as p}from"./capabilities-CyXuKUl1.mjs";import{t as m}from"./ToolRegistry-C5oB8KP8.mjs";import"./definitions-CT8ln6GQ.mjs";import{tmpdir as h}from"node:os";import{createHash as g}from"node:crypto";import{join as _,normalize as v,resolve as y,sep as b}from"node:path";import{mkdir as x,stat as S,writeFile as C}from"node:fs/promises";const w=e=>typeof e==`object`&&!!e,T=e=>w(e)&&typeof e.error==`string`;function E(e){let t=y(e),n=v(process.cwd()),r=v(h());if(!t.startsWith(`${n}${b}`)&&!t.startsWith(`${r}${b}`))throw Error(`Path traversal blocked: outputPath must be under project root or temp directory`);return t}var D=class{state;constructor(e){this.state=e}ok(e){return{content:[{type:`text`,text:JSON.stringify({success:!0,...e},null,2)}]}}fail(e,t){return{content:[{type:`text`,text:JSON.stringify({success:!1,error:e,...t===void 0?{}:{exitCode:t}},null,2)}]}}async writeTextArtifact(e){let{outputPath:t,artifact:n,content:r,pathMode:i=`display`}=e;if(t){let e=E(t);return await C(e,r,`utf-8`),e}let{absolutePath:a,displayPath:s}=await o(n);return await C(a,r,`utf-8`),i===`absolute`?a:s}async resolveArtifactOutputPath(e){let{outputPath:t,artifact:n,pathMode:r=`absolute`}=e;if(t)return E(t);let{absolutePath:i,displayPath:a}=await o(n);return r===`display`?a:i}preview(e,t){let n=e.split(`
1
+ import{$i as e,Qi as t,ea as n,na as r,ta as i}from"./constants-DMv3svps.mjs";import{i as a}from"./artifacts-D-4pSS_N.mjs";import{i as o}from"./modules-DO3jXCgj.mjs";import{c as s,o as c,r as l,s as u,t as d}from"./parse-args-ngRrvF9e.mjs";import{t as f}from"./ResponseBuilder-nPXl_khE.mjs";import{n as p}from"./capabilities-L1ax5EHS.mjs";import{t as m}from"./ToolRegistry-eMZEBiR1.mjs";import"./definitions-cnG6tj17.mjs";import{tmpdir as h}from"node:os";import{join as g,normalize as _,resolve as v,sep as y}from"node:path";import{mkdir as b,stat as x,writeFile as S}from"node:fs/promises";import{createHash as C}from"node:crypto";const w=e=>typeof e==`object`&&!!e,T=e=>w(e)&&typeof e.error==`string`;function E(e){let t=v(e),n=_(process.cwd()),r=_(h());if(!t.startsWith(`${n}${y}`)&&!t.startsWith(`${r}${y}`))throw Error(`Path traversal blocked: outputPath must be under project root or temp directory`);return t}var D=class{state;constructor(e){this.state=e}ok(e){return{content:[{type:`text`,text:JSON.stringify({success:!0,...e},null,2)}]}}fail(e,t){return{content:[{type:`text`,text:JSON.stringify({success:!1,error:e,...t===void 0?{}:{exitCode:t}},null,2)}]}}async writeTextArtifact(e){let{outputPath:t,artifact:n,content:r,pathMode:i=`display`}=e;if(t){let e=E(t);return await S(e,r,`utf-8`),e}let{absolutePath:o,displayPath:s}=await a(n);return await S(o,r,`utf-8`),i===`absolute`?o:s}async resolveArtifactOutputPath(e){let{outputPath:t,artifact:n,pathMode:r=`absolute`}=e;if(t)return E(t);let{absolutePath:i,displayPath:o}=await a(n);return r===`display`?o:i}preview(e,t){let n=e.split(`
2
2
  `);return n.slice(0,t).join(`
3
3
  `)+(n.length>t?`
4
- ... (truncated)`:``)}async tryStatSize(e){try{return(await S(e)).size}catch{return 0}}};function O(e){return/^[a-z]:[\\/]/i.test(e)||/^\\\\[^\\]+\\[^\\]+/i.test(e)||/^file:\/\//i.test(e)||/^\/(?:Users|home|tmp|var|etc|opt|usr|srv|mnt|media|private|root|run|dev|proc|sys|Library|Volumes)(?:\/|$)/.test(e)}var k=class extends D{async handleWasmDetectObfuscation(r){let a=u(r,`inputPath`),o=d(r,`verbose`,!1),s=await this.state.runner.run({tool:`wabt.wasm2wat`,args:[a],timeoutMs:i});if(!s.ok)return this.fail(`Failed to disassemble: ${s.stderr}`);let c=s.stdout,l=[],f=(c.match(/br_table/g)||[]).length;f>5&&l.push({type:`control-flow-flattening`,confidence:Math.min(f/20,.95),description:`${f} br_table dispatches detected — likely flattened control flow`});let p=(c.match(/i32\.xor/g)||[]).length,m=(c.match(/i32\.rotl|i32\.rotr/g)||[]).length,h=(c.match(/i32\.shl|i32\.shr_[su]/g)||[]).length;p+m+h>n&&l.push({type:`constant-encoding`,confidence:Math.min((p+m+h)/50,.9),description:`High density of bitwise ops (${p} xor, ${h} shift, ${m} rotate) — constant decoding`});let g=c.match(/br\s+(?:\$\d+|\d+)\s*\n\s*(?!end\b|\))\S.*$/gm)||[];g.length>e&&l.push({type:`dead-code-injection`,confidence:Math.min(g.length/30,.85),description:`${g.length} code blocks after unconditional branches`});let _=/\(loop/.test(c),v=/br_table/.test(c),y=/local\.get\s+\d+/.test(c);if(_&&v&&y){let e=(c.match(/\(loop/g)||[]).length;e>t&&l.push({type:`vm-dispatch`,confidence:.75,description:`Loop + br_table + local.get pattern (${e} loops) — possible WASM VM interpreter`})}let b=(c.match(/\(func\s/g)||[]).length,x=c.length;b>0&&x/b>5e3&&l.push({type:`code-bloat`,confidence:.5,description:`Average ${(x/b).toFixed(0)} chars/function across ${b} functions — unusually large`});let S=(c.match(/\bcall_indirect\b/g)||[]).length,C=(c.match(/\bcall\s+(?!indirect)/g)||[]).length;S>3&&S>=C*.3&&l.push({type:`indirect-call-dispatch`,confidence:Math.min(S/15,.85),description:`${S} call_indirect vs ${C} direct calls — indirect call ratio suggests dispatch-based VM or obfuscation`});let w=(c.match(/\(import\s+"env"\s+"(\w+)"/g)||[]).map(e=>e.split(`"`)[3]??``).filter(e=>![`memory`,`table`,`__linear_memory`,`__indirect_function_table`].includes(e));w.length>20&&l.push({type:`large-import-surface`,confidence:Math.min(w.length/50,.7),description:`${w.length} env imports — large import surface typical of obfuscated/wrapped modules`});let T=l.length>0,E=l.reduce((e,t)=>Math.max(e,t.confidence),0);return this.ok({inputPath:a,hasObfuscation:T,overallConfidence:T?E:0,detectionCount:l.length,detections:l,summary:T?`Detected ${l.length} obfuscation pattern(s). Highest confidence: ${(E*100).toFixed(0)}%`:`No obfuscation patterns detected.`,...o?{watPreview:this.preview(c,200)}:{}})}async handleWasmInstrumentTrace(e){let t=u(e,`inputPath`),n=d(e,`allHooks`,!0),r=c(e,`hooks`),a=s(e,`outputPath`),o=await this.state.runner.run({tool:`wabt.wasm2wat`,args:[t],timeoutMs:i});if(!o.ok)return this.fail(o.stderr);let l=o.stdout,f=n?[`call`,`memory`,`branch`,`loop`,`local`]:r.length>0?r:[`call`],p=l.match(/\(func\s/g)||[],m=l.match(/\(export/g)||[],h=l.match(/\(import/g)||[],g=l.match(/\(table\b/g)||[],_=l.match(/\bcall_indirect\b/g)||[],v=[],y=[],b=/\(export\s+"([^"]+)"\s+\((\w+)\s+(\$?[\w.]+)\)\)/g,x=/\(import\s+"([^"]+)"\s+"([^"]+)"/g,S;for(;(S=b.exec(l))!==null;)S[1]&&v.push(S[1]);for(;(S=x.exec(l))!==null;)S[1]&&S[2]&&y.push({module:S[1],name:S[2]});let w={call:`
4
+ ... (truncated)`:``)}async tryStatSize(e){try{return(await x(e)).size}catch{return 0}}};function O(e){return/^[a-z]:[\\/]/i.test(e)||/^\\\\[^\\]+\\[^\\]+/i.test(e)||/^file:\/\//i.test(e)||/^\/(?:Users|home|tmp|var|etc|opt|usr|srv|mnt|media|private|root|run|dev|proc|sys|Library|Volumes)(?:\/|$)/.test(e)}var k=class extends D{async handleWasmDetectObfuscation(n){let a=s(n,`inputPath`),o=d(n,`verbose`,!1),c=await this.state.runner.run({tool:`wabt.wasm2wat`,args:[a],timeoutMs:i});if(!c.ok)return this.fail(`Failed to disassemble: ${c.stderr}`);let l=c.stdout,u=[],f=(l.match(/br_table/g)||[]).length;f>5&&u.push({type:`control-flow-flattening`,confidence:Math.min(f/20,.95),description:`${f} br_table dispatches detected — likely flattened control flow`});let p=(l.match(/i32\.xor/g)||[]).length,m=(l.match(/i32\.rotl|i32\.rotr/g)||[]).length,h=(l.match(/i32\.shl|i32\.shr_[su]/g)||[]).length;p+m+h>t&&u.push({type:`constant-encoding`,confidence:Math.min((p+m+h)/50,.9),description:`High density of bitwise ops (${p} xor, ${h} shift, ${m} rotate) — constant decoding`});let g=l.match(/br\s+(?:\$\d+|\d+)\s*\n\s*(?!end\b|\))\S.*$/gm)||[];g.length>e&&u.push({type:`dead-code-injection`,confidence:Math.min(g.length/30,.85),description:`${g.length} code blocks after unconditional branches`});let _=/\(loop/.test(l),v=/br_table/.test(l),y=/local\.get\s+\d+/.test(l);if(_&&v&&y){let e=(l.match(/\(loop/g)||[]).length;e>r&&u.push({type:`vm-dispatch`,confidence:.75,description:`Loop + br_table + local.get pattern (${e} loops) — possible WASM VM interpreter`})}let b=(l.match(/\(func\s/g)||[]).length,x=l.length;b>0&&x/b>5e3&&u.push({type:`code-bloat`,confidence:.5,description:`Average ${(x/b).toFixed(0)} chars/function across ${b} functions — unusually large`});let S=(l.match(/\bcall_indirect\b/g)||[]).length,C=(l.match(/\bcall\s+(?!indirect)/g)||[]).length;S>3&&S>=C*.3&&u.push({type:`indirect-call-dispatch`,confidence:Math.min(S/15,.85),description:`${S} call_indirect vs ${C} direct calls — indirect call ratio suggests dispatch-based VM or obfuscation`});let w=(l.match(/\(import\s+"env"\s+"(\w+)"/g)||[]).map(e=>e.split(`"`)[3]??``).filter(e=>![`memory`,`table`,`__linear_memory`,`__indirect_function_table`].includes(e));w.length>20&&u.push({type:`large-import-surface`,confidence:Math.min(w.length/50,.7),description:`${w.length} env imports — large import surface typical of obfuscated/wrapped modules`});let T=u.length>0,E=u.reduce((e,t)=>Math.max(e,t.confidence),0);return this.ok({inputPath:a,hasObfuscation:T,overallConfidence:T?E:0,detectionCount:u.length,detections:u,summary:T?`Detected ${u.length} obfuscation pattern(s). Highest confidence: ${(E*100).toFixed(0)}%`:`No obfuscation patterns detected.`,...o?{watPreview:this.preview(l,200)}:{}})}async handleWasmInstrumentTrace(e){let t=s(e,`inputPath`),n=d(e,`allHooks`,!0),r=u(e,`hooks`),a=c(e,`outputPath`),o=await this.state.runner.run({tool:`wabt.wasm2wat`,args:[t],timeoutMs:i});if(!o.ok)return this.fail(o.stderr);let l=o.stdout,f=n?[`call`,`memory`,`branch`,`loop`,`local`]:r.length>0?r:[`call`],p=l.match(/\(func\s/g)||[],m=l.match(/\(export/g)||[],h=l.match(/\(import/g)||[],g=l.match(/\(table\b/g)||[],_=l.match(/\bcall_indirect\b/g)||[],v=[],y=[],b=/\(export\s+"([^"]+)"\s+\((\w+)\s+(\$?[\w.]+)\)\)/g,x=/\(import\s+"([^"]+)"\s+"([^"]+)"/g,C;for(;(C=b.exec(l))!==null;)C[1]&&v.push(C[1]);for(;(C=x.exec(l))!==null;)C[1]&&C[2]&&y.push({module:C[1],name:C[2]});let w={call:`
5
5
  const callLog = [];
6
6
  for (const [name, value] of Object.entries(instance.exports)) {
7
7
  if (typeof value === 'function') {
@@ -168,7 +168,7 @@ ${T.map(e=>` ${e}: ${e===`call`?`callLog`:e===`memory`?`memoryLog`:e===`bra
168
168
  }
169
169
  };
170
170
  })();
171
- `,N;if(a){let e=E(a);await C(e,M,`utf-8`),N=e}else N=await this.writeTextArtifact({artifact:{category:`wasm`,toolName:`wasm-instrument`,ext:`js`},content:M});let P=O(t),F=[P?`Wrapper embeds the provided inputPath into browser-side fetch(). Local filesystem paths are not browser-accessible; provide an http(s) URL instead, or upload the module with wasm_dump and use the resulting URL.`:void 0,T.includes(`branch`)&&_.length>0?`Branch hook only observes JS-visible WebAssembly.Table access. This module contains ${_.length} call_indirect site(s), which are dispatched inside the Wasm engine and will not appear in branch logs.`:void 0].filter(e=>typeof e==`string`&&e.length>0),I=F.length>0?F.join(` `):void 0;return this.ok({artifactPath:N,hookTypes:T,functionCount:p.length,exportCount:m.length,importCount:h.length,wrapperSizeBytes:M.length,note:`Wasabi-style instrumentation wrapper generated. Load in browser with WASM module to trace execution.`,metadata:{inputPathKind:P?`local-path`:`url`,wrapperFetchesBrowserUrl:!0,...T.includes(`branch`)?{branchHookMode:`js-table-access-only`,callIndirectSites:_.length,tableCount:g.length}:{}},...I?{warning:I}:{}})}},A=class extends D{async handleWasmDisassemble(e){let t=u(e,`inputPath`),n=s(e,`outputPath`),r=d(e,`foldExprs`,!0),a=[t,`-o`,`/dev/stdout`];r&&a.push(`--fold-exprs`);let o=await this.state.runner.run({tool:`wabt.wasm2wat`,args:a,timeoutMs:i,requireNonEmptyOutput:!0,outputLabel:`wasm text output`});if(!o.ok)return this.fail(o.stderr,o.exitCode??void 0);let c=await this.writeTextArtifact({outputPath:n,artifact:{category:`wasm`,toolName:`wasm-disassemble`,ext:`wat`},content:o.stdout});return this.ok({artifactPath:c,totalLines:o.stdout.split(`
172
- `).length,sizeBytes:o.stdout.length,preview:this.preview(o.stdout,50),durationMs:o.durationMs})}async handleWasmDecompile(e){let t=u(e,`inputPath`),n=s(e,`outputPath`),r=await this.state.runner.run({tool:`wabt.wasm-decompile`,args:[t,`-o`,`/dev/stdout`],timeoutMs:i,requireNonEmptyOutput:!0,outputLabel:`wasm decompile output`});if(!r.ok)return this.fail(r.stderr,r.exitCode??void 0);let a=await this.writeTextArtifact({outputPath:n,artifact:{category:`wasm`,toolName:`wasm-decompile`,ext:`dcmp`},content:r.stdout});return this.ok({artifactPath:a,totalLines:r.stdout.split(`
173
- `).length,preview:this.preview(r.stdout,60),durationMs:r.durationMs})}async handleWasmInspectSections(e){let t=u(e,`inputPath`),n=({headers:`-h`,details:`-x`,disassemble:`-d`,all:`-h -x -d`}[s(e,`sections`,`details`)]||`-x`).split(` `),r=await this.state.runner.run({tool:`wabt.wasm-objdump`,args:[...n,t],timeoutMs:i,requireNonEmptyOutput:!0,outputLabel:`wasm section dump`});return r.ok?this.ok({totalLines:r.stdout.split(`
174
- `).length,preview:this.preview(r.stdout,100),durationMs:r.durationMs}):this.fail(r.stderr,r.exitCode??void 0)}async handleWasmToC(e){let t=u(e,`inputPath`),n=s(e,`outputDir`),r=await this.resolveArtifactOutputPath({outputPath:n,artifact:{category:`wasm`,toolName:`wasm2c`,ext:`dir`},pathMode:`absolute`});await x(r,{recursive:!0});let a=y(t).replace(/\.wasm$/i,``).split(/[/\\]/).pop()||`output`,o=_(r,`${a}.c`),c=_(r,`${a}.h`),l=await this.state.runner.run({tool:`wabt.wasm2c`,args:[t,`-o`,o],timeoutMs:i,expectedOutputPaths:[o,c],outputLabel:`wasm2c output`});return l.ok?this.ok({outputDir:r,cFile:o,hFile:c,cSizeBytes:await this.tryStatSize(o),hSizeBytes:await this.tryStatSize(c),durationMs:l.durationMs}):this.fail(l.stderr,l.exitCode??void 0)}},j=class extends D{async handleWasmOfflineRun(e){let t=u(e,`inputPath`),n=u(e,`functionName`),r=c(e,`args`),i=s(e,`runtime`,`auto`),a=l(e,`timeoutMs`,1e4),o;if(i===`auto`){let e=await this.state.runner.probeAll();if(e[`runtime.wasmtime`]?.available)o=`runtime.wasmtime`;else if(e[`runtime.wasmer`]?.available)o=`runtime.wasmer`;else return this.fail(`No WASM runtime found. Install wasmtime or wasmer.`)}else o=i===`wasmer`?`runtime.wasmer`:`runtime.wasmtime`;let d=o===`runtime.wasmtime`?[`run`,`--invoke`,n,t,...r]:[`run`,t,`--invoke`,n,`--`,...r],f=await this.state.runner.run({tool:o,args:d,timeoutMs:a,requireNonEmptyOutput:!0,outputLabel:`runtime output`});return this.ok({runtime:o,functionName:n,args:r,output:f.stdout.trim(),stderr:f.stderr.trim()||void 0,exitCode:f.exitCode,durationMs:f.durationMs,success:f.ok})}async handleWasmOptimize(e){let t=u(e,`inputPath`),n=s(e,`outputPath`),i=s(e,`level`,`O2`),a=await this.resolveArtifactOutputPath({outputPath:n,artifact:{category:`wasm`,toolName:`wasm-opt`,ext:`wasm`},pathMode:`absolute`}),o=await this.state.runner.run({tool:`binaryen.wasm-opt`,args:[`-${i}`,t,`-o`,a],timeoutMs:r,expectedOutputPaths:[a],outputLabel:`optimized wasm`});if(!o.ok)return this.fail(o.stderr,o.exitCode??void 0);let c=await this.tryStatSize(t),l=await this.tryStatSize(a);return this.ok({artifactPath:a,optimizationLevel:i,inputSizeBytes:c,outputSizeBytes:l,reductionPercent:c>0?((1-l/c)*100).toFixed(1):`0`,durationMs:o.durationMs})}},M=class{conversion;runtime;analysis;constructor(e){this.conversion=new A(e),this.runtime=new j(e),this.analysis=new k(e)}handleWasmDisassemble(e){return this.conversion.handleWasmDisassemble(e)}handleWasmDecompile(e){return this.conversion.handleWasmDecompile(e)}handleWasmInspectSections(e){return this.conversion.handleWasmInspectSections(e)}handleWasmOfflineRun(e){return this.runtime.handleWasmOfflineRun(e)}handleWasmOptimize(e){return this.runtime.handleWasmOptimize(e)}handleWasmToC(e){return this.conversion.handleWasmToC(e)}handleWasmDetectObfuscation(e){return this.analysis.handleWasmDetectObfuscation(e)}handleWasmInstrumentTrace(e){return this.analysis.handleWasmInstrumentTrace(e)}},N=class{state;constructor(e){this.state=e}async handleWasmDump(e){let t=l(e,`moduleIndex`,0),n=s(e,`outputPath`),r=await this.state.collector.getActivePage(),i=await r.evaluate(e=>{let t=window.__aiHooks?.[`preset-webassembly-full`];if(!Array.isArray(t)||t.length===0)return{error:`No WASM modules captured. Ensure the webassembly-full hook preset is active and the page has loaded WASM.`};let n=t.filter(e=>e.type===`instantiated`);if(e>=n.length)return{error:`Module index ${e} out of range. Found ${n.length} instantiated modules.`};let r=n[e];return{exports:r.exports,importMods:r.importMods,size:r.size,moduleCount:n.length}},t);if(T(i))return{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.error})}]};let a=await r.evaluate(e=>{let t=window.__wasmModuleStorage;if(!t?.[e])return null;let n=t[e];return Array.from(new Uint8Array(n))},t),c,u;if(a){let e=Buffer.from(a);if(u=g(`sha256`).update(e).digest(`hex`).substring(0,16),n){let t=E(n);await C(t,e),c=t}else{let{absolutePath:t,displayPath:n}=await o({category:`wasm`,toolName:`wasm-dump`,target:u,ext:`wasm`});await C(t,e),c=n}}else c=`(binary not available — hook did not store raw bytes)`;return{content:[{type:`text`,text:JSON.stringify({success:!0,artifactPath:c,hash:u,size:i.size,exports:i.exports,importModules:i.importMods,totalModules:i.moduleCount,hint:a?`Use wasm_disassemble or wasm_decompile on the dumped file for further analysis.`:`Binary not captured. Inject hook_preset("webassembly-full") BEFORE page navigation, with window.__wasmModuleStorage patching.`},null,2)}]}}async handleWasmVmpTrace(e){let t=l(e,`maxEvents`,5e3),n=s(e,`filterModule`),r=await(await this.state.collector.getActivePage()).evaluate(e=>{let t=window.__aiHooks?.[`preset-webassembly-full`];if(!Array.isArray(t)||t.length===0)return{error:`No WASM hook data. Inject hook_preset("webassembly-full") and reload the page.`};let n=t.filter(e=>e.type===`import_call`);e.filterModule&&(n=n.filter(t=>t.mod===e.filterModule));let r=n.slice(0,e.maxEvents),i={};for(let e of r){let t=`${String(e.mod)}.${String(e.fn)}`;i[t]=(i[t]||0)+1}let a=Object.entries(i).toSorted((e,t)=>t[1]-e[1]).slice(0,30).map(([e,t])=>({name:e,count:t}));return{totalEvents:n.length,capturedEvents:r.length,topFunctions:a,trace:r.slice(0,200).map(e=>({mod:e.mod,fn:e.fn,args:e.args,ts:e.ts}))}},{maxEvents:t,filterModule:n});return T(r)?{content:[{type:`text`,text:JSON.stringify({success:!1,error:r.error})}]}:{content:[{type:`text`,text:JSON.stringify({success:!0,...r,hint:`Top functions show VMP handler dispatch patterns. Use wasm_disassemble to analyze their implementation.`},null,2)}]}}async handleWasmMemoryInspect(e){let t=l(e,`offset`,0),n=Math.min(l(e,`length`,256),65536),r=s(e,`format`,`both`),i=s(e,`searchPattern`),a=await(await this.state.collector.getActivePage()).evaluate(e=>{let t=window,n=t.__aiHooks?.[`preset-webassembly-full`],r=(Array.isArray(n)?n:[]).filter(e=>e.type===`memory_created`),i=t.__wasmInstances;if(!Array.isArray(i)||i.length===0)return{error:`No WASM memory available. Ensure the webassembly-full hook is active and a WASM module is instantiated.`};try{let t=i[0].exports?.memory;if(!t?.buffer)return{error:`WASM module has no exported memory.`};let n=new Uint8Array(t.buffer),a=Array.from(n.slice(e.offset,e.offset+e.length)),o;if(e.searchPattern){o=[];let t=e.searchPattern;if(/^[0-9a-fA-F\s]+$/.test(t)){let r=t.replace(/\s/g,``).match(/.{2}/g)?.map(e=>parseInt(e,16))||[];for(let t=e.offset;t<=Math.min(e.offset+e.length-r.length,n.length-r.length);t++){let e=!0;for(let i=0;i<r.length;i++)if(n[t+i]!==r[i]){e=!1;break}e&&o.push({offset:t})}}else{let r=new TextEncoder().encode(t);for(let t=e.offset;t<=Math.min(e.offset+e.length-r.length,n.length-r.length);t++){let e=!0;for(let i=0;i<r.length;i++)if(n[t+i]!==r[i]){e=!1;break}e&&o.push({offset:t})}}}return{totalMemoryPages:t.buffer.byteLength/65536,totalMemoryBytes:t.buffer.byteLength,requestedOffset:e.offset,requestedLength:e.length,data:a,searchResults:o,memoryInfo:r[0]||null}}catch(e){return{error:`Failed to read WASM memory: ${e instanceof Error?e.message:String(e)}`}}},{offset:t,length:n,searchPattern:i});if(T(a))return{content:[{type:`text`,text:JSON.stringify({success:!1,error:a.error})}]};let o=a.data,c=``,u=``;if(r===`hex`||r===`both`)for(let e=0;e<o.length;e+=16){let n=o.slice(e,e+16),r=(t+e).toString(16).padStart(8,`0`),i=n.map(e=>e.toString(16).padStart(2,`0`)).join(` `),a=n.map(e=>e>=32&&e<127?String.fromCharCode(e):`.`).join(``);c+=`${r} ${i.padEnd(48)} |${a}|\n`}return r===`ascii`&&(u=o.map(e=>e>=32&&e<127?String.fromCharCode(e):`.`).join(``)),{content:[{type:`text`,text:JSON.stringify({success:!0,totalMemoryPages:a.totalMemoryPages,totalMemoryBytes:a.totalMemoryBytes,offset:t,length:o.length,hexDump:r===`ascii`?void 0:c,asciiDump:r===`ascii`?u:void 0,searchResults:a.searchResults},null,2)}]}}};function P(e,t,n,r,i,a,o){return{capability:e,status:n?`available`:`unavailable`,reason:r,fix:n?void 0:i,details:{tools:a,...o?.path?{path:o.path}:{},...o?.version?{version:o.version}:{},backend:t}}}var F=class{state;constructor(e){this.state=e}async handleWasmCapabilities(){let e=await this.state.runner.probeAll(),t=await this.getCurrentPageCapability(),n=e[`runtime.wasmtime`]?.available===!0||e[`runtime.wasmer`]?.available===!0;return f.raw(p(`wasm_capabilities`,[t,P(`wabt_wasm2wat`,`wabt.wasm2wat`,e[`wabt.wasm2wat`]?.available===!0,e[`wabt.wasm2wat`]?.reason,`Install WABT so wasm2wat is available on PATH.`,[`wasm_disassemble`],e[`wabt.wasm2wat`]),P(`wabt_wasm_decompile`,`wabt.wasm-decompile`,e[`wabt.wasm-decompile`]?.available===!0,e[`wabt.wasm-decompile`]?.reason,`Install WABT so wasm-decompile is available on PATH.`,[`wasm_decompile`],e[`wabt.wasm-decompile`]),P(`wabt_wasm_objdump`,`wabt.wasm-objdump`,e[`wabt.wasm-objdump`]?.available===!0,e[`wabt.wasm-objdump`]?.reason,`Install WABT so wasm-objdump is available on PATH.`,[`wasm_inspect_sections`],e[`wabt.wasm-objdump`]),P(`binaryen_wasm_opt`,`binaryen.wasm-opt`,e[`binaryen.wasm-opt`]?.available===!0,e[`binaryen.wasm-opt`]?.reason,`Install Binaryen so wasm-opt is available on PATH.`,[`wasm_optimize`],e[`binaryen.wasm-opt`]),{capability:`wasm_offline_runtime`,status:n?`available`:`unavailable`,reason:n?void 0:`No offline WASM runtime is available on PATH.`,fix:n?void 0:`Install wasmtime or wasmer to enable wasm_offline_run.`,details:{tools:[`wasm_offline_run`],runtimes:{wasmtime:e[`runtime.wasmtime`],wasmer:e[`runtime.wasmer`]},preferredRuntime:e[`runtime.wasmtime`]?.available?`runtime.wasmtime`:e[`runtime.wasmer`]?.available?`runtime.wasmer`:null}}]))}async getCurrentPageCapability(){let e;try{e=await this.state.collector.getActivePage()}catch(e){return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Attach or launch a browser page before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!1}}}if(!e)return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`No active page is attached.`,fix:`Attach or launch a browser page before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!1}};try{let t=await e.evaluate(()=>{let e=window,t=e.__aiHooks?.[`preset-webassembly-full`],n=Array.isArray(t)?t:[];return{url:location.href,hookEventCount:n.length,instantiatedCount:n.filter(e=>e.type===`instantiated`).length,importCallCount:n.filter(e=>e.type===`import_call`).length,memoryEventCount:n.filter(e=>e.type===`memory_created`).length,storageCount:Array.isArray(e.__wasmModuleStorage)?e.__wasmModuleStorage.length:0,instanceCount:Array.isArray(e.__wasmInstances)?e.__wasmInstances.length:0}}),n=t.instantiatedCount>0||t.memoryEventCount>0||t.storageCount>0||t.instanceCount>0;return{capability:`wasm_browser_capture_current_page`,status:n?`available`:`unavailable`,reason:n?void 0:`No captured WASM modules or exported memory are visible on the current page.`,fix:n?void 0:`Load a page that instantiates WASM. For dump/trace flows, inject hook_preset("webassembly-full") before navigation.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!0,...t}}}catch(e){return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Ensure an attached page is still reachable before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!0}}}}},I=class{state;externalTools;browser;capabilities;constructor(e){let t=new a(new m);this.state={collector:e,runner:t},this.externalTools=new M(this.state),this.browser=new N(this.state),this.capabilities=new F(this.state)}handleWasmCapabilities(){return this.capabilities.handleWasmCapabilities()}handleWasmDump(e){return this.browser.handleWasmDump(e)}handleWasmDisassemble(e){return this.externalTools.handleWasmDisassemble(e)}handleWasmDecompile(e){return this.externalTools.handleWasmDecompile(e)}handleWasmInspectSections(e){return this.externalTools.handleWasmInspectSections(e)}handleWasmOfflineRun(e){return this.externalTools.handleWasmOfflineRun(e)}handleWasmOptimize(e){return this.externalTools.handleWasmOptimize(e)}handleWasmVmpTrace(e){return this.browser.handleWasmVmpTrace(e)}handleWasmMemoryInspect(e){return this.browser.handleWasmMemoryInspect(e)}handleWasmToC(e){return this.externalTools.handleWasmToC(e)}handleWasmDetectObfuscation(e){return this.externalTools.handleWasmDetectObfuscation(e)}handleWasmInstrumentTrace(e){return this.externalTools.handleWasmInstrumentTrace(e)}};export{I as WasmToolHandlers};
171
+ `,N;if(a){let e=E(a);await S(e,M,`utf-8`),N=e}else N=await this.writeTextArtifact({artifact:{category:`wasm`,toolName:`wasm-instrument`,ext:`js`},content:M});let P=O(t),F=[P?`Wrapper embeds the provided inputPath into browser-side fetch(). Local filesystem paths are not browser-accessible; provide an http(s) URL instead, or upload the module with wasm_dump and use the resulting URL.`:void 0,T.includes(`branch`)&&_.length>0?`Branch hook only observes JS-visible WebAssembly.Table access. This module contains ${_.length} call_indirect site(s), which are dispatched inside the Wasm engine and will not appear in branch logs.`:void 0].filter(e=>typeof e==`string`&&e.length>0),I=F.length>0?F.join(` `):void 0;return this.ok({artifactPath:N,hookTypes:T,functionCount:p.length,exportCount:m.length,importCount:h.length,wrapperSizeBytes:M.length,note:`Wasabi-style instrumentation wrapper generated. Load in browser with WASM module to trace execution.`,metadata:{inputPathKind:P?`local-path`:`url`,wrapperFetchesBrowserUrl:!0,...T.includes(`branch`)?{branchHookMode:`js-table-access-only`,callIndirectSites:_.length,tableCount:g.length}:{}},...I?{warning:I}:{}})}},A=class extends D{async handleWasmDisassemble(e){let t=s(e,`inputPath`),n=c(e,`outputPath`),r=d(e,`foldExprs`,!0),a=[t,`-o`,`/dev/stdout`];r&&a.push(`--fold-exprs`);let o=await this.state.runner.run({tool:`wabt.wasm2wat`,args:a,timeoutMs:i,requireNonEmptyOutput:!0,outputLabel:`wasm text output`});if(!o.ok)return this.fail(o.stderr,o.exitCode??void 0);let l=await this.writeTextArtifact({outputPath:n,artifact:{category:`wasm`,toolName:`wasm-disassemble`,ext:`wat`},content:o.stdout});return this.ok({artifactPath:l,totalLines:o.stdout.split(`
172
+ `).length,sizeBytes:o.stdout.length,preview:this.preview(o.stdout,50),durationMs:o.durationMs})}async handleWasmDecompile(e){let t=s(e,`inputPath`),n=c(e,`outputPath`),r=await this.state.runner.run({tool:`wabt.wasm-decompile`,args:[t,`-o`,`/dev/stdout`],timeoutMs:i,requireNonEmptyOutput:!0,outputLabel:`wasm decompile output`});if(!r.ok)return this.fail(r.stderr,r.exitCode??void 0);let a=await this.writeTextArtifact({outputPath:n,artifact:{category:`wasm`,toolName:`wasm-decompile`,ext:`dcmp`},content:r.stdout});return this.ok({artifactPath:a,totalLines:r.stdout.split(`
173
+ `).length,preview:this.preview(r.stdout,60),durationMs:r.durationMs})}async handleWasmInspectSections(e){let t=s(e,`inputPath`),n=({headers:`-h`,details:`-x`,disassemble:`-d`,all:`-h -x -d`}[c(e,`sections`,`details`)]||`-x`).split(` `),r=await this.state.runner.run({tool:`wabt.wasm-objdump`,args:[...n,t],timeoutMs:i,requireNonEmptyOutput:!0,outputLabel:`wasm section dump`});return r.ok?this.ok({totalLines:r.stdout.split(`
174
+ `).length,preview:this.preview(r.stdout,100),durationMs:r.durationMs}):this.fail(r.stderr,r.exitCode??void 0)}async handleWasmToC(e){let t=s(e,`inputPath`),n=c(e,`outputDir`),r=await this.resolveArtifactOutputPath({outputPath:n,artifact:{category:`wasm`,toolName:`wasm2c`,ext:`dir`},pathMode:`absolute`});await b(r,{recursive:!0});let a=v(t).replace(/\.wasm$/i,``).split(/[/\\]/).pop()||`output`,o=g(r,`${a}.c`),l=g(r,`${a}.h`),u=await this.state.runner.run({tool:`wabt.wasm2c`,args:[t,`-o`,o],timeoutMs:i,expectedOutputPaths:[o,l],outputLabel:`wasm2c output`});return u.ok?this.ok({outputDir:r,cFile:o,hFile:l,cSizeBytes:await this.tryStatSize(o),hSizeBytes:await this.tryStatSize(l),durationMs:u.durationMs}):this.fail(u.stderr,u.exitCode??void 0)}},j=class extends D{async handleWasmOfflineRun(e){let t=s(e,`inputPath`),n=s(e,`functionName`),r=u(e,`args`),i=c(e,`runtime`,`auto`),a=l(e,`timeoutMs`,1e4),o;if(i===`auto`){let e=await this.state.runner.probeAll();if(e[`runtime.wasmtime`]?.available)o=`runtime.wasmtime`;else if(e[`runtime.wasmer`]?.available)o=`runtime.wasmer`;else return this.fail(`No WASM runtime found. Install wasmtime or wasmer.`)}else o=i===`wasmer`?`runtime.wasmer`:`runtime.wasmtime`;let d=o===`runtime.wasmtime`?[`run`,`--invoke`,n,t,...r]:[`run`,t,`--invoke`,n,`--`,...r],f=await this.state.runner.run({tool:o,args:d,timeoutMs:a,requireNonEmptyOutput:!0,outputLabel:`runtime output`});return this.ok({runtime:o,functionName:n,args:r,output:f.stdout.trim(),stderr:f.stderr.trim()||void 0,exitCode:f.exitCode,durationMs:f.durationMs,success:f.ok})}async handleWasmOptimize(e){let t=s(e,`inputPath`),r=c(e,`outputPath`),i=c(e,`level`,`O2`),a=await this.resolveArtifactOutputPath({outputPath:r,artifact:{category:`wasm`,toolName:`wasm-opt`,ext:`wasm`},pathMode:`absolute`}),o=await this.state.runner.run({tool:`binaryen.wasm-opt`,args:[`-${i}`,t,`-o`,a],timeoutMs:n,expectedOutputPaths:[a],outputLabel:`optimized wasm`});if(!o.ok)return this.fail(o.stderr,o.exitCode??void 0);let l=await this.tryStatSize(t),u=await this.tryStatSize(a);return this.ok({artifactPath:a,optimizationLevel:i,inputSizeBytes:l,outputSizeBytes:u,reductionPercent:l>0?((1-u/l)*100).toFixed(1):`0`,durationMs:o.durationMs})}},M=class{conversion;runtime;analysis;constructor(e){this.conversion=new A(e),this.runtime=new j(e),this.analysis=new k(e)}handleWasmDisassemble(e){return this.conversion.handleWasmDisassemble(e)}handleWasmDecompile(e){return this.conversion.handleWasmDecompile(e)}handleWasmInspectSections(e){return this.conversion.handleWasmInspectSections(e)}handleWasmOfflineRun(e){return this.runtime.handleWasmOfflineRun(e)}handleWasmOptimize(e){return this.runtime.handleWasmOptimize(e)}handleWasmToC(e){return this.conversion.handleWasmToC(e)}handleWasmDetectObfuscation(e){return this.analysis.handleWasmDetectObfuscation(e)}handleWasmInstrumentTrace(e){return this.analysis.handleWasmInstrumentTrace(e)}},N=class{state;constructor(e){this.state=e}async handleWasmDump(e){let t=l(e,`moduleIndex`,0),n=c(e,`outputPath`),r=await this.state.collector.getActivePage(),i=await r.evaluate(e=>{let t=window.__aiHooks?.[`preset-webassembly-full`];if(!Array.isArray(t)||t.length===0)return{error:`No WASM modules captured. Ensure the webassembly-full hook preset is active and the page has loaded WASM.`};let n=t.filter(e=>e.type===`instantiated`);if(e>=n.length)return{error:`Module index ${e} out of range. Found ${n.length} instantiated modules.`};let r=n[e];return{exports:r.exports,importMods:r.importMods,size:r.size,moduleCount:n.length}},t);if(T(i))return{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.error})}]};let o=await r.evaluate(e=>{let t=window.__wasmModuleStorage;if(!t?.[e])return null;let n=t[e];return Array.from(new Uint8Array(n))},t),s,u;if(o){let e=Buffer.from(o);if(u=C(`sha256`).update(e).digest(`hex`).substring(0,16),n){let t=E(n);await S(t,e),s=t}else{let{absolutePath:t,displayPath:n}=await a({category:`wasm`,toolName:`wasm-dump`,target:u,ext:`wasm`});await S(t,e),s=n}}else s=`(binary not available — hook did not store raw bytes)`;return{content:[{type:`text`,text:JSON.stringify({success:!0,artifactPath:s,hash:u,size:i.size,exports:i.exports,importModules:i.importMods,totalModules:i.moduleCount,hint:o?`Use wasm_disassemble or wasm_decompile on the dumped file for further analysis.`:`Binary not captured. Inject hook_preset("webassembly-full") BEFORE page navigation, with window.__wasmModuleStorage patching.`},null,2)}]}}async handleWasmVmpTrace(e){let t=l(e,`maxEvents`,5e3),n=c(e,`filterModule`),r=await(await this.state.collector.getActivePage()).evaluate(e=>{let t=window.__aiHooks?.[`preset-webassembly-full`];if(!Array.isArray(t)||t.length===0)return{error:`No WASM hook data. Inject hook_preset("webassembly-full") and reload the page.`};let n=t.filter(e=>e.type===`import_call`);e.filterModule&&(n=n.filter(t=>t.mod===e.filterModule));let r=n.slice(0,e.maxEvents),i={};for(let e of r){let t=`${String(e.mod)}.${String(e.fn)}`;i[t]=(i[t]||0)+1}let a=Object.entries(i).toSorted((e,t)=>t[1]-e[1]).slice(0,30).map(([e,t])=>({name:e,count:t}));return{totalEvents:n.length,capturedEvents:r.length,topFunctions:a,trace:r.slice(0,200).map(e=>({mod:e.mod,fn:e.fn,args:e.args,ts:e.ts}))}},{maxEvents:t,filterModule:n});return T(r)?{content:[{type:`text`,text:JSON.stringify({success:!1,error:r.error})}]}:{content:[{type:`text`,text:JSON.stringify({success:!0,...r,hint:`Top functions show VMP handler dispatch patterns. Use wasm_disassemble to analyze their implementation.`},null,2)}]}}async handleWasmMemoryInspect(e){let t=l(e,`offset`,0),n=Math.min(l(e,`length`,256),65536),r=c(e,`format`,`both`),i=c(e,`searchPattern`),a=await(await this.state.collector.getActivePage()).evaluate(e=>{let t=window,n=t.__aiHooks?.[`preset-webassembly-full`],r=(Array.isArray(n)?n:[]).filter(e=>e.type===`memory_created`),i=t.__wasmInstances;if(!Array.isArray(i)||i.length===0)return{error:`No WASM memory available. Ensure the webassembly-full hook is active and a WASM module is instantiated.`};try{let t=i[0].exports?.memory;if(!t?.buffer)return{error:`WASM module has no exported memory.`};let n=new Uint8Array(t.buffer),a=Array.from(n.slice(e.offset,e.offset+e.length)),o;if(e.searchPattern){o=[];let t=e.searchPattern;if(/^[0-9a-fA-F\s]+$/.test(t)){let r=t.replace(/\s/g,``).match(/.{2}/g)?.map(e=>parseInt(e,16))||[];for(let t=e.offset;t<=Math.min(e.offset+e.length-r.length,n.length-r.length);t++){let e=!0;for(let i=0;i<r.length;i++)if(n[t+i]!==r[i]){e=!1;break}e&&o.push({offset:t})}}else{let r=new TextEncoder().encode(t);for(let t=e.offset;t<=Math.min(e.offset+e.length-r.length,n.length-r.length);t++){let e=!0;for(let i=0;i<r.length;i++)if(n[t+i]!==r[i]){e=!1;break}e&&o.push({offset:t})}}}return{totalMemoryPages:t.buffer.byteLength/65536,totalMemoryBytes:t.buffer.byteLength,requestedOffset:e.offset,requestedLength:e.length,data:a,searchResults:o,memoryInfo:r[0]||null}}catch(e){return{error:`Failed to read WASM memory: ${e instanceof Error?e.message:String(e)}`}}},{offset:t,length:n,searchPattern:i});if(T(a))return{content:[{type:`text`,text:JSON.stringify({success:!1,error:a.error})}]};let o=a.data,s=``,u=``;if(r===`hex`||r===`both`)for(let e=0;e<o.length;e+=16){let n=o.slice(e,e+16),r=(t+e).toString(16).padStart(8,`0`),i=n.map(e=>e.toString(16).padStart(2,`0`)).join(` `),a=n.map(e=>e>=32&&e<127?String.fromCharCode(e):`.`).join(``);s+=`${r} ${i.padEnd(48)} |${a}|\n`}return r===`ascii`&&(u=o.map(e=>e>=32&&e<127?String.fromCharCode(e):`.`).join(``)),{content:[{type:`text`,text:JSON.stringify({success:!0,totalMemoryPages:a.totalMemoryPages,totalMemoryBytes:a.totalMemoryBytes,offset:t,length:o.length,hexDump:r===`ascii`?void 0:s,asciiDump:r===`ascii`?u:void 0,searchResults:a.searchResults},null,2)}]}}};function P(e,t,n,r,i,a,o){return{capability:e,status:n?`available`:`unavailable`,reason:r,fix:n?void 0:i,details:{tools:a,...o?.path?{path:o.path}:{},...o?.version?{version:o.version}:{},backend:t}}}var F=class{state;constructor(e){this.state=e}async handleWasmCapabilities(){let e=await this.state.runner.probeAll(),t=await this.getCurrentPageCapability(),n=e[`runtime.wasmtime`]?.available===!0||e[`runtime.wasmer`]?.available===!0;return f.raw(p(`wasm_capabilities`,[t,P(`wabt_wasm2wat`,`wabt.wasm2wat`,e[`wabt.wasm2wat`]?.available===!0,e[`wabt.wasm2wat`]?.reason,`Install WABT so wasm2wat is available on PATH.`,[`wasm_disassemble`],e[`wabt.wasm2wat`]),P(`wabt_wasm_decompile`,`wabt.wasm-decompile`,e[`wabt.wasm-decompile`]?.available===!0,e[`wabt.wasm-decompile`]?.reason,`Install WABT so wasm-decompile is available on PATH.`,[`wasm_decompile`],e[`wabt.wasm-decompile`]),P(`wabt_wasm_objdump`,`wabt.wasm-objdump`,e[`wabt.wasm-objdump`]?.available===!0,e[`wabt.wasm-objdump`]?.reason,`Install WABT so wasm-objdump is available on PATH.`,[`wasm_inspect_sections`],e[`wabt.wasm-objdump`]),P(`binaryen_wasm_opt`,`binaryen.wasm-opt`,e[`binaryen.wasm-opt`]?.available===!0,e[`binaryen.wasm-opt`]?.reason,`Install Binaryen so wasm-opt is available on PATH.`,[`wasm_optimize`],e[`binaryen.wasm-opt`]),{capability:`wasm_offline_runtime`,status:n?`available`:`unavailable`,reason:n?void 0:`No offline WASM runtime is available on PATH.`,fix:n?void 0:`Install wasmtime or wasmer to enable wasm_offline_run.`,details:{tools:[`wasm_offline_run`],runtimes:{wasmtime:e[`runtime.wasmtime`],wasmer:e[`runtime.wasmer`]},preferredRuntime:e[`runtime.wasmtime`]?.available?`runtime.wasmtime`:e[`runtime.wasmer`]?.available?`runtime.wasmer`:null}}]))}async getCurrentPageCapability(){let e;try{e=await this.state.collector.getActivePage()}catch(e){return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Attach or launch a browser page before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!1}}}if(!e)return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`No active page is attached.`,fix:`Attach or launch a browser page before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!1}};try{let t=await e.evaluate(()=>{let e=window,t=e.__aiHooks?.[`preset-webassembly-full`],n=Array.isArray(t)?t:[];return{url:location.href,hookEventCount:n.length,instantiatedCount:n.filter(e=>e.type===`instantiated`).length,importCallCount:n.filter(e=>e.type===`import_call`).length,memoryEventCount:n.filter(e=>e.type===`memory_created`).length,storageCount:Array.isArray(e.__wasmModuleStorage)?e.__wasmModuleStorage.length:0,instanceCount:Array.isArray(e.__wasmInstances)?e.__wasmInstances.length:0}}),n=t.instantiatedCount>0||t.memoryEventCount>0||t.storageCount>0||t.instanceCount>0;return{capability:`wasm_browser_capture_current_page`,status:n?`available`:`unavailable`,reason:n?void 0:`No captured WASM modules or exported memory are visible on the current page.`,fix:n?void 0:`Load a page that instantiates WASM. For dump/trace flows, inject hook_preset("webassembly-full") before navigation.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!0,...t}}}catch(e){return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Ensure an attached page is still reachable before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!0}}}}},I=class{state;externalTools;browser;capabilities;constructor(e){let t=new o(new m);this.state={collector:e,runner:t},this.externalTools=new M(this.state),this.browser=new N(this.state),this.capabilities=new F(this.state)}handleWasmCapabilities(){return this.capabilities.handleWasmCapabilities()}handleWasmDump(e){return this.browser.handleWasmDump(e)}handleWasmDisassemble(e){return this.externalTools.handleWasmDisassemble(e)}handleWasmDecompile(e){return this.externalTools.handleWasmDecompile(e)}handleWasmInspectSections(e){return this.externalTools.handleWasmInspectSections(e)}handleWasmOfflineRun(e){return this.externalTools.handleWasmOfflineRun(e)}handleWasmOptimize(e){return this.externalTools.handleWasmOptimize(e)}handleWasmVmpTrace(e){return this.browser.handleWasmVmpTrace(e)}handleWasmMemoryInspect(e){return this.browser.handleWasmMemoryInspect(e)}handleWasmToC(e){return this.externalTools.handleWasmToC(e)}handleWasmDetectObfuscation(e){return this.externalTools.handleWasmDetectObfuscation(e)}handleWasmInstrumentTrace(e){return this.externalTools.handleWasmInstrumentTrace(e)}};export{I as WasmToolHandlers};
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{Gn as t,Hn as n,Kn as r,Mt as i,Nt as a,Wn as o}from"./constants-BYj8Xek8.mjs";import{t as s}from"./ProcessRegistry-C-bN48oR.mjs";import{n as c}from"./concurrency-DCr8WQ2M.mjs";import l from"node:path";import{readdir as u,rm as d,stat as f}from"node:fs/promises";import*as p from"@babel/parser";import m from"@babel/traverse";import*as h from"@babel/types";import g from"@babel/generator";import{Worker as _}from"node:worker_threads";var v=class{async execute(e){return c(()=>this.executeInternal(e))}executeInternal(i){let a=i.timeoutMs??n,c=i.memoryLimitMB??o,l=Date.now();return new Promise(n=>{let o=!1,u=setTimeout(()=>{o||(f.terminate(),e.warn(`[ExecutionSandbox] Worker terminated after ${a+r}ms`),p({ok:!1,error:`Execution timed out (worker terminated)`,timedOut:!0}))},a+r),d={eval:!0,workerData:{code:i.code,timeoutMs:a},resourceLimits:{maxOldGenerationSizeMb:c,maxYoungGenerationSizeMb:Math.ceil(c/4),stackSizeMb:t}};d.type=`module`;let f=new _(`
1
+ import{t as e}from"./logger-CCikqqvj.mjs";import{Ir as t,Lr as n,Pr as r,Rr as i,_n as a,gn as o}from"./constants-DMv3svps.mjs";import{t as s}from"./ProcessRegistry-D5y1yuP2.mjs";import{n as c}from"./concurrency-Dehnw4JC.mjs";import l from"node:path";import{readdir as u,rm as d,stat as f}from"node:fs/promises";import*as p from"@babel/parser";import m from"@babel/traverse";import*as h from"@babel/types";import g from"@babel/generator";import{Worker as _}from"node:worker_threads";var v=class{async execute(e){return c(()=>this.executeInternal(e))}executeInternal(a){let o=a.timeoutMs??r,c=a.memoryLimitMB??t,l=Date.now();return new Promise(t=>{let r=!1,u=setTimeout(()=>{r||(f.terminate(),e.warn(`[ExecutionSandbox] Worker terminated after ${o+i}ms`),p({ok:!1,error:`Execution timed out (worker terminated)`,timedOut:!0}))},o+i),d={eval:!0,workerData:{code:a.code,timeoutMs:o},resourceLimits:{maxOldGenerationSizeMb:c,maxYoungGenerationSizeMb:Math.ceil(c/4),stackSizeMb:n}};d.type=`module`;let f=new _(`
2
2
  import { workerData, parentPort } from 'node:worker_threads';
3
3
  import * as vm from 'node:vm';
4
4
 
@@ -42,5 +42,5 @@ try {
42
42
  timedOut: err.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT',
43
43
  });
44
44
  }
45
- `,d);typeof f.unref==`function`&&f.unref(),s.register(f);let p=e=>{o||(o=!0,u&&clearTimeout(u),n({...e,durationMs:Date.now()-l}))};f.on(`message`,e=>{p({ok:e.ok,output:e.output,error:e.error,timedOut:e.timedOut||!1}),f.terminate()}),f.on(`error`,e=>{p({ok:!1,error:`Worker error: ${e.message}`,timedOut:!1})}),f.on(`exit`,e=>{o||p({ok:!1,error:`Worker exited unexpectedly with code ${e}`,timedOut:!1})})})}};async function y(e,t,n,r){let i=[],a=[];return n===`obfuscator.io`?b(e,t,r,i,a):n===`jsfuck`?x(e,t,i):n===`jjencode`?S(e,t,i):C(e,t,r,i,a)}async function b(t,n,r,i,a){let o=n,s=.5;try{let c=n.match(/var\s+(_0x[a-f0-9]+)\s*=\s*(\[.*?\]);/s);if(c){let n=c[1],r=c[2];e.info(` : ${n}`);try{let i=await t.sandbox.execute({code:`return ${r||`[]`};`,timeoutMs:3e3}),a=i.ok?i.output:void 0;if(Array.isArray(a)){e.info(`String array detected, ${a.length} strings found`);let t=RegExp(`${n}\\[(\\d+)\\]`,`g`);o=o.replace(t,(e,t)=>{let n=parseInt(t,10);return n<a.length?JSON.stringify(a[n]):e}),s+=.2}}catch(e){i.push(`: ${e}`),a.push({location:`String Array`,reason:``,suggestion:``})}}return o=o.replace(/\(function\s*\(_0x[a-f0-9]+,\s*_0x[a-f0-9]+\)\s*\{[\s\S]*?\}\(_0x[a-f0-9]+,\s*0x[a-f0-9]+\)\);?/g,``),r&&(o=o.replace(/\(function\s*\(\)\s*\{([\s\S]*)\}\(\)\);?/g,`$1`),s+=.1),o=o.replace(/0x([0-9a-f]+)/gi,(e,t)=>String(parseInt(t,16))),o=o.replace(/;\s*;/g,`;`),o=o.replace(/\{\s*\}/g,`{}`),i.push(`obfuscator.io detected, may need special handling`),{code:o,confidence:Math.min(s,1),warnings:i,unresolvedParts:a.length>0?a:void 0}}catch(e){return i.push(`obfuscator.io: ${e}`),{code:n,confidence:.2,warnings:i,unresolvedParts:a}}}async function x(t,n,r){try{e.info(`JSFuck detected, attempting deobfuscation...`);try{if(n.length>1e5)return r.push(`JSFuck code detected, file too large to process directly.`),r.push(`Consider using an online JSFuck decoder tool.`),{code:n,confidence:.1,warnings:r};let i=await t.sandbox.execute({code:`return ${n};`,timeoutMs:5e3}),a=i.ok?i.output:void 0;return typeof a==`string`?(e.info(` JSFuck`),{code:a,confidence:.9,warnings:[`JSFuck`]}):(r.push(`JSFuck`),{code:n,confidence:.2,warnings:r})}catch(e){return r.push(`JSFuck: ${e}`),r.push(`Consider using an online JSFuck decoder tool.`),{code:n,confidence:.1,warnings:r}}}catch(e){return r.push(`JSFuck: ${e}`),{code:n,confidence:.1,warnings:r}}}async function S(t,n,r){try{e.info(`JJEncode detected, attempting deobfuscation...`);try{let i=n.split(`
46
- `).filter(e=>e.trim());if((i.length>0?i[i.length-1]:``)?.includes(`$$$$`)){let r=await t.sandbox.execute({code:`${n}; return $$$$()`,timeoutMs:5e3}),i=r.ok?r.output:void 0;if(typeof i==`string`)return e.info(` JJEncode`),{code:i,confidence:.9,warnings:[`JJEncode`]}}let a=await t.sandbox.execute({code:n,timeoutMs:5e3});return a.ok||e.warn(`JJEncode sandbox execution failed:`,a.error),r.push(`JJEncode deobfuscation may be incomplete`),r.push(`Result may still contain JJEncode fragments`),{code:n,confidence:.2,warnings:r}}catch(e){return r.push(`JJEncode: ${e}`),r.push(`Result may contain evaluation artifacts`),{code:n,confidence:.1,warnings:r}}}catch(e){return r.push(`JJEncode: ${e}`),{code:n,confidence:.1,warnings:r}}}async function C(e,t,n,r,i){return r.push(`AI-assisted deobfuscation removed, using fallback directly.`),w(t,n,r,i)}function w(e,t,n,r){let i=e,a=.3;try{return i=i.replace(/if\s*\([^)]*\)\s*\{\s*\}/g,``),i=i.replace(/!!\s*\(/g,`Boolean(`),i=i.replace(/""\s*\+\s*/g,``),t&&(i=i.replace(/debugger;?/g,``),a+=.1,i=i.replace(/\?\s*([^:]+)\s*:\s*\1/g,`$1`),a+=.05),n.push(`Analysis incomplete, partial results may be returned`),n.push(`For better results, configure an LLM API key`),r.push({location:`Custom VM`,reason:`VM`,suggestion:`VM protection detected, LLM-assisted analysis recommended`}),{code:i,confidence:a,warnings:n,unresolvedParts:r.length>0?r:void 0}}catch(t){return n.push(`: ${t}`),{code:e,confidence:.1,warnings:n,unresolvedParts:r}}}var T=class{sandbox=new v;async deobfuscate(t){let n=Date.now(),{code:r,aggressive:o=!1,extractInstructions:s=!1,timeout:c=i,maxIterations:l=a}=t;e.info(` JSVMP...`);try{let t=this.detectJSVMP(r);if(!t)return e.info(`JSVMP`),{isJSVMP:!1,deobfuscatedCode:r,confidence:0,warnings:[`JSVMP`]};e.info(`JSVMP analysis complete, complexity: ${t.complexity}`),e.info(` : ${t.instructionCount}`);let i=this.identifyVMType(r,t);e.info(` : ${i}`);let a;s&&(e.info(` ...`),a=this.extractInstructions(r,t),e.info(` ${a.length} `)),e.info(` ...`);let u=await this.restoreCode(r,t,i,o,c,l),d=Date.now()-n,f={isJSVMP:!0,vmType:i,vmFeatures:t,instructions:a,deobfuscatedCode:u.code,confidence:u.confidence,warnings:u.warnings,unresolvedParts:u.unresolvedParts,stats:{originalSize:r.length,deobfuscatedSize:u.code.length,reductionRate:1-u.code.length/r.length,processingTime:d}};return e.info(`JSVMP deobfuscation complete in ${d}ms`),e.info(` : ${(f.confidence*100).toFixed(1)}%`),f}catch(t){return e.error(`JSVMP`,t),{isJSVMP:!1,deobfuscatedCode:r,confidence:0,warnings:[`: ${t}`]}}}detectJSVMP(t){try{let n=p.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=!1,i=!1,a=!1,o=0,s=``,c=0,l=!1,u=!1,d=!1,f=!1;if(m(n,{SwitchStatement(e){let t=e.node.cases.length;t>10&&(r=!0,t>c&&(c=t,o=t,s=`Line ${e.node.loc?.start.line||0}`))},ArrayExpression(e){e.node.elements.length>50&&(i=!0)},UpdateExpression(e){if(e.node.operator===`++`||e.node.operator===`--`){let t=e.node.argument;h.isIdentifier(t)&&t.name.length<=3&&(a=!0)}},CallExpression(e){if(h.isIdentifier(e.node.callee,{name:`parseInt`})&&e.node.arguments.length>=2){let t=e.node.arguments[0];h.isBinaryExpression(t)&&t.operator===`+`&&(f=!0,l=!0)}h.isMemberExpression(e.node.callee)&&h.isIdentifier(e.node.callee.property,{name:`apply`})&&(u=!0)},WhileStatement(e){(h.isBooleanLiteral(e.node.test,{value:!0})||h.isNumericLiteral(e.node.test,{value:1}))&&(d=!0)},ForStatement(e){e.node.test||(d=!0)}}),r&&(i||a)&&(u||d||f)){let t=o>100?`high`:o>50?`medium`:`low`;return e.info(` JSVMP:`),e.info(` - Switch: ${r} (${c} cases)`),e.info(` - : ${i}`),e.info(` - : ${a}`),e.info(` - : ${l}`),e.info(` - Apply: ${u}`),e.info(` - : ${d}`),e.info(` - : ${f}`),{instructionCount:o,interpreterLocation:s,complexity:t,hasSwitch:r,hasInstructionArray:i,hasProgramCounter:a}}return null}catch(n){return e.warn(`JSVMP analysis failed`,n),this.detectJSVMPWithRegex(t)}}detectJSVMPWithRegex(t){let n=(t.match(/switch\s*\(/g)?.length||0)>0,r=/parseInt\s*\(\s*["']?\s*\+\s*\w+\[/g.test(t),i=/\.apply\s*\(/g.test(t),a=/while\s*\(\s*(true|1)\s*\)/g.test(t);return n&&(r||i||a)?(e.info(` JSVMP`),{instructionCount:0,interpreterLocation:`Unknown`,complexity:`medium`,hasSwitch:!0,hasInstructionArray:r,hasProgramCounter:i}):null}identifyVMType(e,t){return e.includes(`_0x`)&&e.includes(`function(_0x`)?`obfuscator.io`:/^\s*\[\s*\]\s*\[\s*\(/.test(e)?`jsfuck`:e.includes(`$=~[];`)?`jjencode`:`custom`}extractInstructions(t,n){let r=[];try{m(p.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]}),{SwitchStatement:e=>{e.node.cases.length===n.instructionCount&&e.node.cases.forEach((e,t)=>{let n=e.test&&(h.isNumericLiteral(e.test)||h.isStringLiteral(e.test))?e.test.value:t,i=this.inferInstructionType(e);r.push({opcode:n,name:`INST_${n}`,type:i,description:`Instruction ${n}`})})}})}catch(t){e.warn(``,t)}return r}inferInstructionType(e){let t=g(e).code,n=e.consequent,r=!1,i=!1,a=!1,o=!1,s=!1;for(let e of n){if(h.isExpressionStatement(e)){let t=e.expression;h.isAssignmentExpression(t)&&(r=!0),h.isMemberExpression(t)&&h.isNumericLiteral(t.property)&&(i=!0),h.isCallExpression(t)&&(a=!0),h.isBinaryExpression(t)&&[`+`,`-`,`*`,`/`,`%`,`**`].includes(t.operator)&&(o=!0)}(h.isIfStatement(e)||h.isWhileStatement(e)||h.isBreakStatement(e)||h.isContinueStatement(e)||h.isReturnStatement(e))&&(s=!0)}return(t.includes(`push`)||t.includes(`.push(`))&&(i||t.includes(`[`))?`load`:r&&!o&&!a?`store`:o||t.match(/[+\-*/%]/)?`arithmetic`:s||t.includes(`break`)||t.includes(`continue`)?`control`:a||t.includes(`.apply(`)||t.includes(`.call(`)?`call`:`unknown`}async restoreCode(e,t,n,r,i,a){return this.restoreCustomVMBasic,y({sandbox:this.sandbox},e,n,r)}restoreCustomVMBasic(e,t,n,r){return w(e,t,n,r)}};const E={jsx:!0,mangle:!1,unminify:!0,unpack:!0};function D(e){return{jsx:e.jsx??E.jsx,mangle:e.mangle??E.mangle,unminify:e.unminify??E.unminify,unpack:e.unpack??E.unpack}}function O(){let[e=`0`,t=`0`]=process.versions.node.split(`.`),n=Number.parseInt(e,10),r=Number.parseInt(t,10);return!Number.isFinite(n)||!Number.isFinite(r)?!1:n===22?r>=12:n===24}function k(e,t){let n=t.target===`path`?e.path:e.code,r=t.matchType??`includes`;if(r===`exact`)return n===t.pattern;if(r===`regex`)try{return new RegExp(t.pattern,`m`).test(n)}catch{return!1}return n.includes(t.pattern)}function A(e,t){let n=new Map;if(!t||t.length===0)return n;for(let r of e.modules.values())for(let e of t)if(!(!e.path||!e.pattern)&&k(r,e)){r.path!==e.path&&(n.set(r.id,{fromPath:r.path}),r.path=e.path);break}return n}function j(e,t,n){let r=t.maxBundleModules??100,i=Array.from(e.modules.values()).toSorted((e,t)=>e.isEntry===t.isEntry?e.path.localeCompare(t.path):e.isEntry?-1:1).slice(0,r).map(e=>({id:e.id,path:e.path,isEntry:e.isEntry,size:e.code.length,code:t.includeModuleCode?e.code:void 0,mappedPathFrom:n.get(e.id)?.fromPath}));return{type:e.type,entryId:e.entryId,moduleCount:e.modules.size,truncated:e.modules.size>r,mappingsApplied:n.size,modules:i}}async function M(e,t=e){let n=await u(t,{withFileTypes:!0}),r=[];for(let i of n){let n=l.join(t,i.name);if(i.isDirectory()){r.push(...await M(e,n));continue}if(!i.isFile())continue;let a=await f(n);r.push({path:l.relative(e,n).replace(/\\/g,`/`),size:a.size,type:`file`})}return r.toSorted((e,t)=>e.path.localeCompare(t.path))}async function N(t,n){let r=D(n);if(!O()){let n=`webcrack requires Node.js 22.12+ or 24.x; current runtime is ${process.versions.node}`;return e.warn(n),{applied:!1,code:t,optionsUsed:r,reason:n}}try{let{webcrack:e}=await import(`webcrack`),i=await e(t,{jsx:r.jsx,unpack:r.unpack,deobfuscate:!0,unminify:r.unminify,mangle:r.mangle}),a=i.bundle?A(i.bundle,n.mappings):new Map,o,s;if(typeof n.outputDir==`string`&&n.outputDir.trim().length>0){o=l.resolve(n.outputDir);let e=process.cwd(),t=l.relative(e,o);if(l.isAbsolute(t)||t.startsWith(`..`)||o===`/`||o===l.parse(o).root)throw Error(`outputDir must resolve to a path within the project root. Got: ${o}`);n.forceOutput&&await d(o,{recursive:!0,force:!0}),await i.save(o),s=await M(o)}return{applied:!0,code:i.code,bundle:i.bundle?j(i.bundle,{includeModuleCode:n.includeModuleCode,maxBundleModules:n.maxBundleModules},a):void 0,savedTo:o,savedArtifacts:s,optionsUsed:r}}catch(n){let i=n instanceof Error?n.message:String(n);return e.warn(`webcrack execution failed, falling back to legacy pipeline`,n),{applied:!1,code:t,optionsUsed:r,reason:i}}}export{T as n,N as t};
45
+ `,d);typeof f.unref==`function`&&f.unref(),s.register(f);let p=e=>{r||(r=!0,u&&clearTimeout(u),t({...e,durationMs:Date.now()-l}))};f.on(`message`,e=>{p({ok:e.ok,output:e.output,error:e.error,timedOut:e.timedOut||!1}),f.terminate()}),f.on(`error`,e=>{p({ok:!1,error:`Worker error: ${e.message}`,timedOut:!1})}),f.on(`exit`,e=>{r||p({ok:!1,error:`Worker exited unexpectedly with code ${e}`,timedOut:!1})})})}};async function y(e,t,n,r){let i=[],a=[];return n===`obfuscator.io`?b(e,t,r,i,a):n===`jsfuck`?x(e,t,i):n===`jjencode`?S(e,t,i):C(e,t,r,i,a)}async function b(t,n,r,i,a){let o=n,s=.5;try{let c=n.match(/var\s+(_0x[a-f0-9]+)\s*=\s*(\[.*?\]);/s);if(c){let n=c[1],r=c[2];e.info(` : ${n}`);try{let i=await t.sandbox.execute({code:`return ${r||`[]`};`,timeoutMs:3e3}),a=i.ok?i.output:void 0;if(Array.isArray(a)){e.info(`String array detected, ${a.length} strings found`);let t=RegExp(`${n}\\[(\\d+)\\]`,`g`);o=o.replace(t,(e,t)=>{let n=parseInt(t,10);return n<a.length?JSON.stringify(a[n]):e}),s+=.2}}catch(e){i.push(`: ${e}`),a.push({location:`String Array`,reason:``,suggestion:``})}}return o=o.replace(/\(function\s*\(_0x[a-f0-9]+,\s*_0x[a-f0-9]+\)\s*\{[\s\S]*?\}\(_0x[a-f0-9]+,\s*0x[a-f0-9]+\)\);?/g,``),r&&(o=o.replace(/\(function\s*\(\)\s*\{([\s\S]*)\}\(\)\);?/g,`$1`),s+=.1),o=o.replace(/0x([0-9a-f]+)/gi,(e,t)=>String(parseInt(t,16))),o=o.replace(/;\s*;/g,`;`),o=o.replace(/\{\s*\}/g,`{}`),i.push(`obfuscator.io detected, may need special handling`),{code:o,confidence:Math.min(s,1),warnings:i,unresolvedParts:a.length>0?a:void 0}}catch(e){return i.push(`obfuscator.io: ${e}`),{code:n,confidence:.2,warnings:i,unresolvedParts:a}}}async function x(t,n,r){try{e.info(`JSFuck detected, attempting deobfuscation...`);try{if(n.length>1e5)return r.push(`JSFuck code detected, file too large to process directly.`),r.push(`Consider using an online JSFuck decoder tool.`),{code:n,confidence:.1,warnings:r};let i=await t.sandbox.execute({code:`return ${n};`,timeoutMs:5e3}),a=i.ok?i.output:void 0;return typeof a==`string`?(e.info(` JSFuck`),{code:a,confidence:.9,warnings:[`JSFuck`]}):(r.push(`JSFuck`),{code:n,confidence:.2,warnings:r})}catch(e){return r.push(`JSFuck: ${e}`),r.push(`Consider using an online JSFuck decoder tool.`),{code:n,confidence:.1,warnings:r}}}catch(e){return r.push(`JSFuck: ${e}`),{code:n,confidence:.1,warnings:r}}}async function S(t,n,r){try{e.info(`JJEncode detected, attempting deobfuscation...`);try{let i=n.split(`
46
+ `).filter(e=>e.trim());if((i.length>0?i[i.length-1]:``)?.includes(`$$$$`)){let r=await t.sandbox.execute({code:`${n}; return $$$$()`,timeoutMs:5e3}),i=r.ok?r.output:void 0;if(typeof i==`string`)return e.info(` JJEncode`),{code:i,confidence:.9,warnings:[`JJEncode`]}}let a=await t.sandbox.execute({code:n,timeoutMs:5e3});return a.ok||e.warn(`JJEncode sandbox execution failed:`,a.error),r.push(`JJEncode deobfuscation may be incomplete`),r.push(`Result may still contain JJEncode fragments`),{code:n,confidence:.2,warnings:r}}catch(e){return r.push(`JJEncode: ${e}`),r.push(`Result may contain evaluation artifacts`),{code:n,confidence:.1,warnings:r}}}catch(e){return r.push(`JJEncode: ${e}`),{code:n,confidence:.1,warnings:r}}}async function C(e,t,n,r,i){return r.push(`AI-assisted deobfuscation removed, using fallback directly.`),w(t,n,r,i)}function w(e,t,n,r){let i=e,a=.3;try{return i=i.replace(/if\s*\([^)]*\)\s*\{\s*\}/g,``),i=i.replace(/!!\s*\(/g,`Boolean(`),i=i.replace(/""\s*\+\s*/g,``),t&&(i=i.replace(/debugger;?/g,``),a+=.1,i=i.replace(/\?\s*([^:]+)\s*:\s*\1/g,`$1`),a+=.05),n.push(`Analysis incomplete, partial results may be returned`),n.push(`For better results, configure an LLM API key`),r.push({location:`Custom VM`,reason:`VM`,suggestion:`VM protection detected, LLM-assisted analysis recommended`}),{code:i,confidence:a,warnings:n,unresolvedParts:r.length>0?r:void 0}}catch(t){return n.push(`: ${t}`),{code:e,confidence:.1,warnings:n,unresolvedParts:r}}}var T=class{sandbox=new v;async deobfuscate(t){let n=Date.now(),{code:r,aggressive:i=!1,extractInstructions:s=!1,timeout:c=o,maxIterations:l=a}=t;e.info(` JSVMP...`);try{let t=this.detectJSVMP(r);if(!t)return e.info(`JSVMP`),{isJSVMP:!1,deobfuscatedCode:r,confidence:0,warnings:[`JSVMP`]};e.info(`JSVMP analysis complete, complexity: ${t.complexity}`),e.info(` : ${t.instructionCount}`);let a=this.identifyVMType(r,t);e.info(` : ${a}`);let o;s&&(e.info(` ...`),o=this.extractInstructions(r,t),e.info(` ${o.length} `)),e.info(` ...`);let u=await this.restoreCode(r,t,a,i,c,l),d=Date.now()-n,f={isJSVMP:!0,vmType:a,vmFeatures:t,instructions:o,deobfuscatedCode:u.code,confidence:u.confidence,warnings:u.warnings,unresolvedParts:u.unresolvedParts,stats:{originalSize:r.length,deobfuscatedSize:u.code.length,reductionRate:1-u.code.length/r.length,processingTime:d}};return e.info(`JSVMP deobfuscation complete in ${d}ms`),e.info(` : ${(f.confidence*100).toFixed(1)}%`),f}catch(t){return e.error(`JSVMP`,t),{isJSVMP:!1,deobfuscatedCode:r,confidence:0,warnings:[`: ${t}`]}}}detectJSVMP(t){try{let n=p.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=!1,i=!1,a=!1,o=0,s=``,c=0,l=!1,u=!1,d=!1,f=!1;if(m(n,{SwitchStatement(e){let t=e.node.cases.length;t>10&&(r=!0,t>c&&(c=t,o=t,s=`Line ${e.node.loc?.start.line||0}`))},ArrayExpression(e){e.node.elements.length>50&&(i=!0)},UpdateExpression(e){if(e.node.operator===`++`||e.node.operator===`--`){let t=e.node.argument;h.isIdentifier(t)&&t.name.length<=3&&(a=!0)}},CallExpression(e){if(h.isIdentifier(e.node.callee,{name:`parseInt`})&&e.node.arguments.length>=2){let t=e.node.arguments[0];h.isBinaryExpression(t)&&t.operator===`+`&&(f=!0,l=!0)}h.isMemberExpression(e.node.callee)&&h.isIdentifier(e.node.callee.property,{name:`apply`})&&(u=!0)},WhileStatement(e){(h.isBooleanLiteral(e.node.test,{value:!0})||h.isNumericLiteral(e.node.test,{value:1}))&&(d=!0)},ForStatement(e){e.node.test||(d=!0)}}),r&&(i||a)&&(u||d||f)){let t=o>100?`high`:o>50?`medium`:`low`;return e.info(` JSVMP:`),e.info(` - Switch: ${r} (${c} cases)`),e.info(` - : ${i}`),e.info(` - : ${a}`),e.info(` - : ${l}`),e.info(` - Apply: ${u}`),e.info(` - : ${d}`),e.info(` - : ${f}`),{instructionCount:o,interpreterLocation:s,complexity:t,hasSwitch:r,hasInstructionArray:i,hasProgramCounter:a}}return null}catch(n){return e.warn(`JSVMP analysis failed`,n),this.detectJSVMPWithRegex(t)}}detectJSVMPWithRegex(t){let n=(t.match(/switch\s*\(/g)?.length||0)>0,r=/parseInt\s*\(\s*["']?\s*\+\s*\w+\[/g.test(t),i=/\.apply\s*\(/g.test(t),a=/while\s*\(\s*(true|1)\s*\)/g.test(t);return n&&(r||i||a)?(e.info(` JSVMP`),{instructionCount:0,interpreterLocation:`Unknown`,complexity:`medium`,hasSwitch:!0,hasInstructionArray:r,hasProgramCounter:i}):null}identifyVMType(e,t){return e.includes(`_0x`)&&e.includes(`function(_0x`)?`obfuscator.io`:/^\s*\[\s*\]\s*\[\s*\(/.test(e)?`jsfuck`:e.includes(`$=~[];`)?`jjencode`:`custom`}extractInstructions(t,n){let r=[];try{m(p.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]}),{SwitchStatement:e=>{e.node.cases.length===n.instructionCount&&e.node.cases.forEach((e,t)=>{let n=e.test&&(h.isNumericLiteral(e.test)||h.isStringLiteral(e.test))?e.test.value:t,i=this.inferInstructionType(e);r.push({opcode:n,name:`INST_${n}`,type:i,description:`Instruction ${n}`})})}})}catch(t){e.warn(``,t)}return r}inferInstructionType(e){let t=g(e).code,n=e.consequent,r=!1,i=!1,a=!1,o=!1,s=!1;for(let e of n){if(h.isExpressionStatement(e)){let t=e.expression;h.isAssignmentExpression(t)&&(r=!0),h.isMemberExpression(t)&&h.isNumericLiteral(t.property)&&(i=!0),h.isCallExpression(t)&&(a=!0),h.isBinaryExpression(t)&&[`+`,`-`,`*`,`/`,`%`,`**`].includes(t.operator)&&(o=!0)}(h.isIfStatement(e)||h.isWhileStatement(e)||h.isBreakStatement(e)||h.isContinueStatement(e)||h.isReturnStatement(e))&&(s=!0)}return(t.includes(`push`)||t.includes(`.push(`))&&(i||t.includes(`[`))?`load`:r&&!o&&!a?`store`:o||t.match(/[+\-*/%]/)?`arithmetic`:s||t.includes(`break`)||t.includes(`continue`)?`control`:a||t.includes(`.apply(`)||t.includes(`.call(`)?`call`:`unknown`}async restoreCode(e,t,n,r,i,a){return this.restoreCustomVMBasic,y({sandbox:this.sandbox},e,n,r)}restoreCustomVMBasic(e,t,n,r){return w(e,t,n,r)}};const E={jsx:!0,mangle:!1,unminify:!0,unpack:!0};function D(e){return{jsx:e.jsx??E.jsx,mangle:e.mangle??E.mangle,unminify:e.unminify??E.unminify,unpack:e.unpack??E.unpack}}function O(){let[e=`0`,t=`0`]=process.versions.node.split(`.`),n=Number.parseInt(e,10),r=Number.parseInt(t,10);return!Number.isFinite(n)||!Number.isFinite(r)?!1:n===22?r>=12:n===24}function k(e,t){let n=t.target===`path`?e.path:e.code,r=t.matchType??`includes`;if(r===`exact`)return n===t.pattern;if(r===`regex`)try{return new RegExp(t.pattern,`m`).test(n)}catch{return!1}return n.includes(t.pattern)}function A(e,t){let n=new Map;if(!t||t.length===0)return n;for(let r of e.modules.values())for(let e of t)if(!(!e.path||!e.pattern)&&k(r,e)){r.path!==e.path&&(n.set(r.id,{fromPath:r.path}),r.path=e.path);break}return n}function j(e,t,n){let r=t.maxBundleModules??100,i=Array.from(e.modules.values()).toSorted((e,t)=>e.isEntry===t.isEntry?e.path.localeCompare(t.path):e.isEntry?-1:1).slice(0,r).map(e=>({id:e.id,path:e.path,isEntry:e.isEntry,size:e.code.length,code:t.includeModuleCode?e.code:void 0,mappedPathFrom:n.get(e.id)?.fromPath}));return{type:e.type,entryId:e.entryId,moduleCount:e.modules.size,truncated:e.modules.size>r,mappingsApplied:n.size,modules:i}}async function M(e,t=e){let n=await u(t,{withFileTypes:!0}),r=[];for(let i of n){let n=l.join(t,i.name);if(i.isDirectory()){r.push(...await M(e,n));continue}if(!i.isFile())continue;let a=await f(n);r.push({path:l.relative(e,n).replace(/\\/g,`/`),size:a.size,type:`file`})}return r.toSorted((e,t)=>e.path.localeCompare(t.path))}async function N(t,n){let r=D(n);if(!O()){let n=`webcrack requires Node.js 22.12+ or 24.x; current runtime is ${process.versions.node}`;return e.warn(n),{applied:!1,code:t,optionsUsed:r,reason:n}}try{let{webcrack:e}=await import(`webcrack`),i=await e(t,{jsx:r.jsx,unpack:r.unpack,deobfuscate:!0,unminify:r.unminify,mangle:r.mangle}),a=i.bundle?A(i.bundle,n.mappings):new Map,o,s;if(typeof n.outputDir==`string`&&n.outputDir.trim().length>0){o=l.resolve(n.outputDir);let e=process.cwd(),t=l.relative(e,o);if(l.isAbsolute(t)||t.startsWith(`..`)||o===`/`||o===l.parse(o).root)throw Error(`outputDir must resolve to a path within the project root. Got: ${o}`);n.forceOutput&&await d(o,{recursive:!0,force:!0}),await i.save(o),s=await M(o)}return{applied:!0,code:i.code,bundle:i.bundle?j(i.bundle,{includeModuleCode:n.includeModuleCode,maxBundleModules:n.maxBundleModules},a):void 0,savedTo:o,savedArtifacts:s,optionsUsed:r}}catch(n){let i=n instanceof Error?n.message:String(n);return e.warn(`webcrack execution failed, falling back to legacy pipeline`,n),{applied:!1,code:t,optionsUsed:r,reason:i}}}export{T as n,N as t};
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{_i as t,bi as n,vi as r,xi as i,yi as a}from"./constants-BYj8Xek8.mjs";import{a as o,i as s,r as c,t as l}from"./parse-args-Bw413PlW.mjs";import{t as u}from"./ResponseBuilder-BfWP-uaT.mjs";import{a as d,s as f}from"./ssrf-policy-CsIJGkpd.mjs";import"./definitions-Ibci7e_L.mjs";import{BlockList as p,isIP as m}from"node:net";import{lookup as h}from"node:dns/promises";const g=[{name:`auth_extract`,description:`Extract auth tokens from localStorage and cookies`,code:`(function(){
1
+ import{t as e}from"./logger-CCikqqvj.mjs";import{da as t,fa as n,ha as r,ma as i,pa as a}from"./constants-DMv3svps.mjs";import{a as o,o as s,r as c,t as l}from"./parse-args-ngRrvF9e.mjs";import{t as u}from"./ResponseBuilder-nPXl_khE.mjs";import{a as d,s as f}from"./ssrf-policy-B72vdy23.mjs";import"./definitions-BOvju5t2.mjs";import{BlockList as p,isIP as m}from"node:net";import{lookup as h}from"node:dns/promises";const g=[{name:`auth_extract`,description:`Extract auth tokens from localStorage and cookies`,code:`(function(){
2
2
  var keys=['token','active_token','access_token','jwt','auth_token','userRole','id_token','refresh_token'];
3
3
  var r={};
4
4
  for(var i=0;i<keys.length;i++){var v=localStorage.getItem(keys[i]);if(v)r[keys[i]]=v;}
@@ -49,7 +49,7 @@ import{t as e}from"./logger-sBC6IdRT.mjs";import{_i as t,bi as n,vi as r,xi as i
49
49
  }
50
50
  });
51
51
  return r;
52
- })()`}];function _(e){let t={deps:e,scriptRegistry:new Map,bundleCache:new Map,bundleCacheBytes:0};return y(t.scriptRegistry),t}const v={BUNDLE_CACHE_TTL_MS:r,MAX_SCRIPTS:100,MAX_BUNDLE_CACHE:50,MAX_BUNDLE_CACHE_BYTES:t};function y(e){for(let t of g)e.set(t.name,{code:t.code,description:t.description,source:`core`,protectedFromEviction:!0})}function b(e){let t=Date.now();for(let[n,r]of e.bundleCache)t-r.cachedAt>=v.BUNDLE_CACHE_TTL_MS&&(e.bundleCacheBytes-=r.text.length,e.bundleCache.delete(n));for(;e.bundleCache.size>=v.MAX_BUNDLE_CACHE||e.bundleCacheBytes>v.MAX_BUNDLE_CACHE_BYTES;){let t=e.bundleCache.keys().next().value;if(t!==void 0){let n=e.bundleCache.get(t);n&&(e.bundleCacheBytes-=n.text.length),e.bundleCache.delete(t)}else break}}function x(e){return e.replace(/[<>/\u2028\u2029]/g,e=>{switch(e){case`<`:return`\\u003C`;case`>`:return`\\u003E`;case`/`:return`\\u002F`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return e}})}function S(e){return typeof e==`string`?e:void 0}function C(e){if(!(typeof e!=`object`||!e||Array.isArray(e)))return e}function w(e){return u.raw(e)}var T=class{state;constructor(e){this.state=e}async handlePageScriptRegister(e){let t=S(e.name),n=S(e.code),r=S(e.description)??``;if(!t||!n)return w({success:!1,error:`name and code are required`});let i=this.state.scriptRegistry.has(t);if(!i&&this.state.scriptRegistry.size>=v.MAX_SCRIPTS){for(let[e,t]of this.state.scriptRegistry)if(!t.protectedFromEviction){this.state.scriptRegistry.delete(e);break}}let a=this.state.scriptRegistry.get(t);return this.state.scriptRegistry.set(t,{code:n,description:r,source:a?.source??`user`,protectedFromEviction:a?.protectedFromEviction??!1}),w({success:!0,action:i?`updated`:`registered`,name:t,description:r,totalScripts:this.state.scriptRegistry.size,available:Array.from(this.state.scriptRegistry.keys())})}async handlePageScriptRun(t){let n=S(t.name),r=C(t.params),i=n?this.state.scriptRegistry.get(n):void 0;if(!i){let e=Array.from(this.state.scriptRegistry.keys());return w({success:!1,error:`Script "${n}" not found`,available:e})}let a;a=r===void 0?i.code:`(function(){const __params__=JSON.parse(${x(JSON.stringify(JSON.stringify(r)))});return(${i.code});})()`;try{return await this.state.deps.browserHandlers.handlePageEvaluate({code:a})}catch(t){return e.error(`[page_script_run] Script "${n}" failed:`,t),w({success:!1,script:n,error:t instanceof Error?t.message:String(t)})}}async handleListExtensionWorkflows(){let e=this.state.deps.serverContext;if(!e)return w({success:!1,error:`Extension workflow runtime is unavailable in this handler context`});let{ensureWorkflowsLoaded:t}=await import(`./ExtensionManager-BD724zkO.mjs`).then(e=>e.t);await t(e);let n=[...e.extensionWorkflowsById.values()].filter(e=>e.route?.kind!==`preset`);n.sort((e,t)=>e.id.localeCompare(t.id));let r=n.map(e=>({id:e.id,displayName:e.displayName,description:e.description,tags:e.tags,timeoutMs:e.timeoutMs,defaultMaxConcurrency:e.defaultMaxConcurrency,source:e.source,route:e.route?{kind:e.route.kind,priority:e.route.priority,requiredDomains:e.route.requiredDomains,triggerPatterns:e.route.triggerPatterns.map(e=>e.source),steps:e.route.steps}:void 0}));return w({success:!0,count:r.length,workflows:r})}async handleRunExtensionWorkflow(t){let n=this.state.deps.serverContext;if(!n)return w({success:!1,error:`Extension workflow runtime is unavailable in this handler context`});let r=S(t.workflowId)??S(t.id);if(!r)return w({success:!1,error:`workflowId is required`});let{ensureWorkflowsLoaded:i}=await import(`./ExtensionManager-BD724zkO.mjs`).then(e=>e.t);await i(n);let a=n.extensionWorkflowRuntimeById.get(r);if(!a){let e=[...n.extensionWorkflowsById.values()].filter(e=>e.route?.kind!==`preset`).map(e=>e.id);return e.sort((e,t)=>e.localeCompare(t)),w({success:!1,error:`Extension workflow "${r}" not found`,available:e})}if(a.route?.kind===`preset`)return w({success:!1,workflowId:r,error:`Extension workflow "${r}" is a routing preset and cannot be executed directly. Use route_tool or the suggested preset steps instead.`});let o=S(t.profile),l=C(t.config),u=s(t,`nodeInputOverrides`),d=c(t,`timeoutMs`);try{let{executeExtensionWorkflow:e}=await import(`./WorkflowEngine-D876meOO.mjs`).then(e=>e.t);return w({success:!0,...await e(n,a.workflow,{profile:o,config:l,nodeInputOverrides:u,timeoutMs:d})})}catch(t){return e.error(`[run_extension_workflow] Workflow "${r}" failed:`,t),w({success:!1,workflowId:r,error:t instanceof Error?t.message:String(t)})}}};function E(e){return e.trim().replace(/^\[|\]$/g,``).toLowerCase()}function D(e){if(e===void 0)return[];let t=typeof e==`string`?(()=>{try{return JSON.parse(e)}catch{return null}})():e;if(!Array.isArray(t))return null;let n=t.filter(e=>typeof e==`string`);return n.length===t.length?n.map(e=>e.trim()).filter(e=>e.length>0):null}function O(e){let t=e.trim(),n=t.includes(`://`)?t:`http://${t}`;try{let e=new URL(n);return e.port.length>0?{scope:`host`,value:e.host.toLowerCase()}:{scope:`hostname`,value:E(e.hostname)}}catch{return{scope:`hostname`,value:E(t)}}}function k(e,t){return e===void 0?{ok:!0,value:!1}:typeof e==`boolean`?{ok:!0,value:e}:{ok:!1,error:`${t} must be a boolean when provided`}}function A(e){let t=e.networkPolicy;if(t===void 0)return{policy:{allowPrivateNetwork:!1,allowInsecureHttp:!1,allowedHosts:[],allowedRedirectHosts:[],allowedCidrs:[],allowedCidrBlockList:new p}};let n=typeof t==`string`?(()=>{try{return JSON.parse(t)}catch{return null}})():t;if(!n||typeof n!=`object`||Array.isArray(n))return{error:`networkPolicy must be an object or valid JSON object string`};let r=n,i=k(r.allowPrivateNetwork,`networkPolicy.allowPrivateNetwork`);if(!i.ok)return{error:i.error};let a=k(r.allowInsecureHttp,`networkPolicy.allowInsecureHttp`);if(!a.ok)return{error:a.error};let o=D(r.allowedHosts);if(o===null)return{error:`networkPolicy.allowedHosts must be an array of strings`};let s=D(r.allowedRedirectHosts);if(s===null)return{error:`networkPolicy.allowedRedirectHosts must be an array of strings`};let c=D(r.allowedCidrs);if(c===null)return{error:`networkPolicy.allowedCidrs must be an array of strings`};let l=new p;for(let e of c){let[t,n]=e.split(`/`);if(!t||!n)return{error:`Invalid CIDR in networkPolicy.allowedCidrs: "${e}"`};let r=m(t);if(r===0)return{error:`Invalid CIDR base address in networkPolicy.allowedCidrs: "${e}"`};let i=Number(n),a=r===4?32:128;if(!Number.isInteger(i)||i<0||i>a)return{error:`Invalid CIDR prefix in networkPolicy.allowedCidrs: "${e}"`};l.addSubnet(t,i,r===4?`ipv4`:`ipv6`)}return{policy:{allowPrivateNetwork:i.value,allowInsecureHttp:a.value,allowedHosts:o.map(O),allowedRedirectHosts:s.map(O),allowedCidrs:c,allowedCidrBlockList:l}}}async function j(e,t,n){let r;try{r=new URL(e)}catch{throw Error(`Invalid ${n.label}: ${e}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`Unsupported protocol for ${n.label}: ${r.protocol} — only http/https allowed`);let i=E(r.hostname),a=r.host.toLowerCase(),o=m(i),s=o===0?await h(i).then(e=>e.address).catch(t=>{throw Error(`DNS resolution failed for "${e}"`,{cause:t})}):i,c=m(s),l=c!==0&&t.allowedCidrs.length>0&&t.allowedCidrBlockList.check(s,c===4?`ipv4`:`ipv6`),u=n.allowRedirectHosts&&t.allowedRedirectHosts.length>0?t.allowedRedirectHosts:t.allowedHosts,p=u.some(e=>e.scope===`host`?e.value===a:e.value===i),g=u.length>0||t.allowedCidrs.length>0,_=!g||p||l;if(f(i)||f(s)){if(!t.allowPrivateNetwork)throw Error(`Blocked: ${n.label} "${e}" resolves to a private/reserved address`);if(!g||!_)throw Error(`Blocked: ${n.label} "${e}" requires an explicit networkPolicy host or CIDR allow rule`)}else if(g&&!_)throw Error(`Blocked: ${n.label} "${e}" is not authorized by networkPolicy`);let v=d(i)||d(s);if(r.protocol===`http:`&&!v){if(!t.allowInsecureHttp)throw Error(`Blocked: insecure HTTP requires networkPolicy.allowInsecureHttp for "${e}"`);if(!g||!_)throw Error(`Blocked: insecure HTTP target "${e}" requires an explicit networkPolicy host or CIDR allow rule`)}let y={},b=r.toString();if(n.rewriteHttpHostToResolvedIp&&r.protocol===`http:`&&o===0){let e=r.host,t=new URL(r.toString());t.hostname=s.includes(`:`)?`[${s}]`:s,b=t.toString(),y.Host=e}return{parsedUrl:r,resolvedIp:s,fetchUrl:b,headers:y}}var M=class{state;constructor(e){this.state=e}async handleApiProbeBatch(t){let n=typeof t.baseUrl==`string`?t.baseUrl.trim():``;if(n.length===0)return u.fail(`baseUrl is required and must be a non-empty string`).json();let r=A(t);if(!r.policy)return u.fail(r.error).json();let i,a={};try{let e=await j(n,r.policy,{label:`baseUrl`,rewriteHttpHostToResolvedIp:!0});i=e.fetchUrl.replace(/\/$/,``),a=e.headers}catch(e){return u.fail(e).json()}let d=i,f=t.paths,p=Array.isArray(f)?f:typeof f==`string`?(()=>{try{return JSON.parse(f)}catch{return[]}})():[],m=(o(t,`method`)??`GET`).toUpperCase(),h=s(t,`headers`)??{},g=o(t,`bodyTemplate`)??null,_=Array.isArray(t.includeBodyStatuses)?t.includeBodyStatuses.filter(e=>typeof e==`number`):[200,201,204],v=Math.max(0,Math.min(c(t,`maxBodySnippetLength`,500),1e4)),y=l(t,`autoInjectAuth`,!0);if(!p||p.length===0)return u.fail(`paths array is required and must not be empty`).json();let b=`(async function() {
52
+ })()`}];function _(e){let t={deps:e,scriptRegistry:new Map,bundleCache:new Map,bundleCacheBytes:0};return y(t.scriptRegistry),t}const v={BUNDLE_CACHE_TTL_MS:n,MAX_SCRIPTS:100,MAX_BUNDLE_CACHE:50,MAX_BUNDLE_CACHE_BYTES:t};function y(e){for(let t of g)e.set(t.name,{code:t.code,description:t.description,source:`core`,protectedFromEviction:!0})}function b(e){let t=Date.now();for(let[n,r]of e.bundleCache)t-r.cachedAt>=v.BUNDLE_CACHE_TTL_MS&&(e.bundleCacheBytes-=r.text.length,e.bundleCache.delete(n));for(;e.bundleCache.size>=v.MAX_BUNDLE_CACHE||e.bundleCacheBytes>v.MAX_BUNDLE_CACHE_BYTES;){let t=e.bundleCache.keys().next().value;if(t!==void 0){let n=e.bundleCache.get(t);n&&(e.bundleCacheBytes-=n.text.length),e.bundleCache.delete(t)}else break}}function x(e){return e.replace(/[<>/\u2028\u2029]/g,e=>{switch(e){case`<`:return`\\u003C`;case`>`:return`\\u003E`;case`/`:return`\\u002F`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return e}})}function S(e){return typeof e==`string`?e:void 0}function C(e){if(!(typeof e!=`object`||!e||Array.isArray(e)))return e}function w(e){return u.raw(e)}var T=class{state;constructor(e){this.state=e}async handlePageScriptRegister(e){let t=S(e.name),n=S(e.code),r=S(e.description)??``;if(!t||!n)return w({success:!1,error:`name and code are required`});let i=this.state.scriptRegistry.has(t);if(!i&&this.state.scriptRegistry.size>=v.MAX_SCRIPTS){for(let[e,t]of this.state.scriptRegistry)if(!t.protectedFromEviction){this.state.scriptRegistry.delete(e);break}}let a=this.state.scriptRegistry.get(t);return this.state.scriptRegistry.set(t,{code:n,description:r,source:a?.source??`user`,protectedFromEviction:a?.protectedFromEviction??!1}),w({success:!0,action:i?`updated`:`registered`,name:t,description:r,totalScripts:this.state.scriptRegistry.size,available:Array.from(this.state.scriptRegistry.keys())})}async handlePageScriptRun(t){let n=S(t.name),r=C(t.params),i=n?this.state.scriptRegistry.get(n):void 0;if(!i){let e=Array.from(this.state.scriptRegistry.keys());return w({success:!1,error:`Script "${n}" not found`,available:e})}let a;a=r===void 0?i.code:`(function(){const __params__=JSON.parse(${x(JSON.stringify(JSON.stringify(r)))});return(${i.code});})()`;try{return await this.state.deps.browserHandlers.handlePageEvaluate({code:a})}catch(t){return e.error(`[page_script_run] Script "${n}" failed:`,t),w({success:!1,script:n,error:t instanceof Error?t.message:String(t)})}}async handleListExtensionWorkflows(){let e=this.state.deps.serverContext;if(!e)return w({success:!1,error:`Extension workflow runtime is unavailable in this handler context`});let{ensureWorkflowsLoaded:t}=await import(`./index.mjs`).then(e=>e.t);await t(e);let n=[...e.extensionWorkflowsById.values()].filter(e=>e.route?.kind!==`preset`);n.sort((e,t)=>e.id.localeCompare(t.id));let r=n.map(e=>({id:e.id,displayName:e.displayName,description:e.description,tags:e.tags,timeoutMs:e.timeoutMs,defaultMaxConcurrency:e.defaultMaxConcurrency,source:e.source,route:e.route?{kind:e.route.kind,priority:e.route.priority,requiredDomains:e.route.requiredDomains,triggerPatterns:e.route.triggerPatterns.map(e=>e.source),steps:e.route.steps}:void 0}));return w({success:!0,count:r.length,workflows:r})}async handleRunExtensionWorkflow(t){let n=this.state.deps.serverContext;if(!n)return w({success:!1,error:`Extension workflow runtime is unavailable in this handler context`});let r=S(t.workflowId)??S(t.id);if(!r)return w({success:!1,error:`workflowId is required`});let{ensureWorkflowsLoaded:i}=await import(`./index.mjs`).then(e=>e.t);await i(n);let a=n.extensionWorkflowRuntimeById.get(r);if(!a){let e=[...n.extensionWorkflowsById.values()].filter(e=>e.route?.kind!==`preset`).map(e=>e.id);return e.sort((e,t)=>e.localeCompare(t)),w({success:!1,error:`Extension workflow "${r}" not found`,available:e})}if(a.route?.kind===`preset`)return w({success:!1,workflowId:r,error:`Extension workflow "${r}" is a routing preset and cannot be executed directly. Use route_tool or the suggested preset steps instead.`});let s=S(t.profile),l=C(t.config),u=o(t,`nodeInputOverrides`),d=c(t,`timeoutMs`);try{let{executeExtensionWorkflow:e}=await import(`./WorkflowEngine-CldHG5b4.mjs`).then(e=>e.t);return w({success:!0,...await e(n,a.workflow,{profile:s,config:l,nodeInputOverrides:u,timeoutMs:d})})}catch(t){return e.error(`[run_extension_workflow] Workflow "${r}" failed:`,t),w({success:!1,workflowId:r,error:t instanceof Error?t.message:String(t)})}}};function E(e){return e.trim().replace(/^\[|\]$/g,``).toLowerCase()}function D(e){if(e===void 0)return[];let t=typeof e==`string`?(()=>{try{return JSON.parse(e)}catch{return null}})():e;if(!Array.isArray(t))return null;let n=t.filter(e=>typeof e==`string`);return n.length===t.length?n.map(e=>e.trim()).filter(e=>e.length>0):null}function O(e){let t=e.trim(),n=t.includes(`://`)?t:`http://${t}`;try{let e=new URL(n);return e.port.length>0?{scope:`host`,value:e.host.toLowerCase()}:{scope:`hostname`,value:E(e.hostname)}}catch{return{scope:`hostname`,value:E(t)}}}function k(e,t){return e===void 0?{ok:!0,value:!1}:typeof e==`boolean`?{ok:!0,value:e}:{ok:!1,error:`${t} must be a boolean when provided`}}function A(e){let t=e.networkPolicy;if(t===void 0)return{policy:{allowPrivateNetwork:!1,allowInsecureHttp:!1,allowedHosts:[],allowedRedirectHosts:[],allowedCidrs:[],allowedCidrBlockList:new p}};let n=typeof t==`string`?(()=>{try{return JSON.parse(t)}catch{return null}})():t;if(!n||typeof n!=`object`||Array.isArray(n))return{error:`networkPolicy must be an object or valid JSON object string`};let r=n,i=k(r.allowPrivateNetwork,`networkPolicy.allowPrivateNetwork`);if(!i.ok)return{error:i.error};let a=k(r.allowInsecureHttp,`networkPolicy.allowInsecureHttp`);if(!a.ok)return{error:a.error};let o=D(r.allowedHosts);if(o===null)return{error:`networkPolicy.allowedHosts must be an array of strings`};let s=D(r.allowedRedirectHosts);if(s===null)return{error:`networkPolicy.allowedRedirectHosts must be an array of strings`};let c=D(r.allowedCidrs);if(c===null)return{error:`networkPolicy.allowedCidrs must be an array of strings`};let l=new p;for(let e of c){let[t,n]=e.split(`/`);if(!t||!n)return{error:`Invalid CIDR in networkPolicy.allowedCidrs: "${e}"`};let r=m(t);if(r===0)return{error:`Invalid CIDR base address in networkPolicy.allowedCidrs: "${e}"`};let i=Number(n),a=r===4?32:128;if(!Number.isInteger(i)||i<0||i>a)return{error:`Invalid CIDR prefix in networkPolicy.allowedCidrs: "${e}"`};l.addSubnet(t,i,r===4?`ipv4`:`ipv6`)}return{policy:{allowPrivateNetwork:i.value,allowInsecureHttp:a.value,allowedHosts:o.map(O),allowedRedirectHosts:s.map(O),allowedCidrs:c,allowedCidrBlockList:l}}}async function j(e,t,n){let r;try{r=new URL(e)}catch{throw Error(`Invalid ${n.label}: ${e}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`Unsupported protocol for ${n.label}: ${r.protocol} — only http/https allowed`);let i=E(r.hostname),a=r.host.toLowerCase(),o=m(i),s=o===0?await h(i).then(e=>e.address).catch(t=>{throw Error(`DNS resolution failed for "${e}"`,{cause:t})}):i,c=m(s),l=c!==0&&t.allowedCidrs.length>0&&t.allowedCidrBlockList.check(s,c===4?`ipv4`:`ipv6`),u=n.allowRedirectHosts&&t.allowedRedirectHosts.length>0?t.allowedRedirectHosts:t.allowedHosts,p=u.some(e=>e.scope===`host`?e.value===a:e.value===i),g=u.length>0||t.allowedCidrs.length>0,_=!g||p||l;if(f(i)||f(s)){if(!t.allowPrivateNetwork)throw Error(`Blocked: ${n.label} "${e}" resolves to a private/reserved address`);if(!g||!_)throw Error(`Blocked: ${n.label} "${e}" requires an explicit networkPolicy host or CIDR allow rule`)}else if(g&&!_)throw Error(`Blocked: ${n.label} "${e}" is not authorized by networkPolicy`);let v=d(i)||d(s);if(r.protocol===`http:`&&!v){if(!t.allowInsecureHttp)throw Error(`Blocked: insecure HTTP requires networkPolicy.allowInsecureHttp for "${e}"`);if(!g||!_)throw Error(`Blocked: insecure HTTP target "${e}" requires an explicit networkPolicy host or CIDR allow rule`)}let y={},b=r.toString();if(n.rewriteHttpHostToResolvedIp&&r.protocol===`http:`&&o===0){let e=r.host,t=new URL(r.toString());t.hostname=s.includes(`:`)?`[${s}]`:s,b=t.toString(),y.Host=e}return{parsedUrl:r,resolvedIp:s,fetchUrl:b,headers:y}}var M=class{state;constructor(e){this.state=e}async handleApiProbeBatch(t){let n=typeof t.baseUrl==`string`?t.baseUrl.trim():``;if(n.length===0)return u.fail(`baseUrl is required and must be a non-empty string`).json();let r=A(t);if(!r.policy)return u.fail(r.error).json();let i,a={};try{let e=await j(n,r.policy,{label:`baseUrl`,rewriteHttpHostToResolvedIp:!0});i=e.fetchUrl.replace(/\/$/,``),a=e.headers}catch(e){return u.fail(e).json()}let d=i,f=t.paths,p=Array.isArray(f)?f:typeof f==`string`?(()=>{try{return JSON.parse(f)}catch{return[]}})():[],m=(s(t,`method`)??`GET`).toUpperCase(),h=o(t,`headers`)??{},g=s(t,`bodyTemplate`)??null,_=Array.isArray(t.includeBodyStatuses)?t.includeBodyStatuses.filter(e=>typeof e==`number`):[200,201,204],v=Math.max(0,Math.min(c(t,`maxBodySnippetLength`,500),1e4)),y=l(t,`autoInjectAuth`,!0);if(!p||p.length===0)return u.fail(`paths array is required and must not be empty`).json();let b=`(async function() {
53
53
  var baseUrl = ${JSON.stringify(d)};
54
54
  var paths = ${JSON.stringify(p)};
55
55
  var method = ${JSON.stringify(m)};
@@ -98,4 +98,4 @@ import{t as e}from"./logger-sBC6IdRT.mjs";import{_i as t,bi as n,vi as r,xi as i
98
98
  }
99
99
  }));
100
100
  return {probed: paths.length, method: method, baseUrl: baseUrl, results: results};
101
- })()`;try{let e=await this.state.deps.browserHandlers.handlePageEvaluate({code:b}),t=u.parse(e);return u.ok().merge(t).json()}catch(t){return e.error(`[api_probe_batch] Error:`,t),u.fail(t).json()}}},N=class{state;constructor(e){this.state=e}async handleJsBundleSearch(e){let t=o(e,`url`,``),r=e.patterns,s=Array.isArray(r)?r:typeof r==`string`?(()=>{try{return JSON.parse(r)}catch{return[]}})():[],d=l(e,`cacheBundle`,!0),f=l(e,`stripNoise`,!0),p=c(e,`maxMatches`,10),m=A(e);if(!t||!s||s.length===0)return u.fail(`url and patterns are required`).json();if(!m.policy)return u.fail(m.error).json();let h=m.policy,g=i,_=n,y=async(e,t)=>{let n=e;for(let e=0;e<_;e++){let r=await j(n,h,{label:e===0?`bundle URL`:`redirect target`,allowRedirectHosts:e>0,rewriteHttpHostToResolvedIp:!0}),i=await fetch(r.fetchUrl,{signal:t,redirect:`manual`,headers:r.headers});if(i.status>=300&&i.status<400){let e=i.headers.get(`location`);if(!e)throw Error(`Redirect ${i.status} without Location header`);n=new URL(e,n).toString();continue}return i}throw Error(`Too many redirects (>${_})`)},x,S=!1;try{if(d){let e=this.state.bundleCache.get(t);if(e&&Date.now()-e.cachedAt<v.BUNDLE_CACHE_TTL_MS)x=e.text,S=!0;else{let e=new AbortController,n=setTimeout(()=>e.abort(),a);try{let n=await y(t,e.signal);if(!n.ok)return u.fail(`Fetch failed: ${n.status} ${n.statusText}`).merge({url:t}).json();if(x=await n.text(),x.length>g)return u.fail(`Response too large: ${x.length} bytes exceeds ${g} limit`).merge({url:t}).json();b(this.state),this.state.bundleCache.set(t,{text:x,cachedAt:Date.now()}),this.state.bundleCacheBytes+=x.length}finally{clearTimeout(n)}}}else{let e=new AbortController,n=setTimeout(()=>e.abort(),3e4);try{let n=await y(t,e.signal);if(!n.ok)return u.fail(`Fetch failed: ${n.status} ${n.statusText}`).merge({url:t}).json();if(x=await n.text(),x.length>g)return u.fail(`Response too large: ${x.length} bytes exceeds ${g} limit`).merge({url:t}).json()}finally{clearTimeout(n)}}}catch(e){return u.fail(e).merge({url:t}).json()}let C={};for(let e of s){let t=e.contextBefore??80,n=e.contextAfter??80,r;try{r=new RegExp(e.regex,`g`)}catch(t){C[e.name]=[{match:``,index:-1,context:`Invalid regex: ${t instanceof Error?t.message:String(t)}`}];continue}let i=[],a;for(;(a=r.exec(x))!==null;){let e=Math.max(0,a.index-t),r=Math.min(x.length,a.index+a[0].length+n),o=x.slice(e,r);if(!(f&&(/[Mm]\d{1,6}(?:\.\d+)?[, ]\d{1,6}(?:\.\d+)?[CLHVSQTAZclhvsqtaz]/.test(o)||/data:[a-z+-]+\/[a-z+-]+;base64,/i.test(o)||o.replace(/[^A-Za-z0-9+/=]/g,``).length>o.length*.85&&o.length>200))&&(i.push({match:a[0],index:a.index,context:o}),i.length>=p))break}C[e.name]=i}return u.ok().merge({bundleUrl:t,bundleSize:x.length,cached:S,patternsSearched:s.length,results:C}).json()}},P=class{scripts;api;account;constructor(e){let t=_(e);this.scripts=new T(t),this.api=new M(t),this.account=new N(t)}handlePageScriptRegister(e){return this.scripts.handlePageScriptRegister(e)}handlePageScriptRun(e){return this.scripts.handlePageScriptRun(e)}handleListExtensionWorkflows(){return this.scripts.handleListExtensionWorkflows()}handleRunExtensionWorkflow(e){return this.scripts.handleRunExtensionWorkflow(e)}handleApiProbeBatch(e){return this.api.handleApiProbeBatch(e)}handleJsBundleSearch(e){return this.account.handleJsBundleSearch(e)}};export{P as WorkflowHandlers};
101
+ })()`;try{let e=await this.state.deps.browserHandlers.handlePageEvaluate({code:b}),t=u.parse(e);return u.ok().merge(t).json()}catch(t){return e.error(`[api_probe_batch] Error:`,t),u.fail(t).json()}}},N=class{state;constructor(e){this.state=e}async handleJsBundleSearch(e){let t=s(e,`url`,``),n=e.patterns,o=Array.isArray(n)?n:typeof n==`string`?(()=>{try{return JSON.parse(n)}catch{return[]}})():[],d=l(e,`cacheBundle`,!0),f=l(e,`stripNoise`,!0),p=c(e,`maxMatches`,10),m=A(e);if(!t||!o||o.length===0)return u.fail(`url and patterns are required`).json();if(!m.policy)return u.fail(m.error).json();let h=m.policy,g=r,_=i,y=async(e,t)=>{let n=e;for(let e=0;e<_;e++){let r=await j(n,h,{label:e===0?`bundle URL`:`redirect target`,allowRedirectHosts:e>0,rewriteHttpHostToResolvedIp:!0}),i=await fetch(r.fetchUrl,{signal:t,redirect:`manual`,headers:r.headers});if(i.status>=300&&i.status<400){let e=i.headers.get(`location`);if(!e)throw Error(`Redirect ${i.status} without Location header`);n=new URL(e,n).toString();continue}return i}throw Error(`Too many redirects (>${_})`)},x,S=!1;try{if(d){let e=this.state.bundleCache.get(t);if(e&&Date.now()-e.cachedAt<v.BUNDLE_CACHE_TTL_MS)x=e.text,S=!0;else{let e=new AbortController,n=setTimeout(()=>e.abort(),a);try{let n=await y(t,e.signal);if(!n.ok)return u.fail(`Fetch failed: ${n.status} ${n.statusText}`).merge({url:t}).json();if(x=await n.text(),x.length>g)return u.fail(`Response too large: ${x.length} bytes exceeds ${g} limit`).merge({url:t}).json();b(this.state),this.state.bundleCache.set(t,{text:x,cachedAt:Date.now()}),this.state.bundleCacheBytes+=x.length}finally{clearTimeout(n)}}}else{let e=new AbortController,n=setTimeout(()=>e.abort(),3e4);try{let n=await y(t,e.signal);if(!n.ok)return u.fail(`Fetch failed: ${n.status} ${n.statusText}`).merge({url:t}).json();if(x=await n.text(),x.length>g)return u.fail(`Response too large: ${x.length} bytes exceeds ${g} limit`).merge({url:t}).json()}finally{clearTimeout(n)}}}catch(e){return u.fail(e).merge({url:t}).json()}let C={};for(let e of o){let t=e.contextBefore??80,n=e.contextAfter??80,r;try{r=new RegExp(e.regex,`g`)}catch(t){C[e.name]=[{match:``,index:-1,context:`Invalid regex: ${t instanceof Error?t.message:String(t)}`}];continue}let i=[],a;for(;(a=r.exec(x))!==null;){let e=Math.max(0,a.index-t),r=Math.min(x.length,a.index+a[0].length+n),o=x.slice(e,r);if(!(f&&(/[Mm]\d{1,6}(?:\.\d+)?[, ]\d{1,6}(?:\.\d+)?[CLHVSQTAZclhvsqtaz]/.test(o)||/data:[a-z+-]+\/[a-z+-]+;base64,/i.test(o)||o.replace(/[^A-Za-z0-9+/=]/g,``).length>o.length*.85&&o.length>200))&&(i.push({match:a[0],index:a.index,context:o}),i.length>=p))break}C[e.name]=i}return u.ok().merge({bundleUrl:t,bundleSize:x.length,cached:S,patternsSearched:o.length,results:C}).json()}},P=class{scripts;api;account;constructor(e){let t=_(e);this.scripts=new T(t),this.api=new M(t),this.account=new N(t)}handlePageScriptRegister(e){return this.scripts.handlePageScriptRegister(e)}handlePageScriptRun(e){return this.scripts.handlePageScriptRun(e)}handleListExtensionWorkflows(){return this.scripts.handleListExtensionWorkflows()}handleRunExtensionWorkflow(e){return this.scripts.handleRunExtensionWorkflow(e)}handleApiProbeBatch(e){return this.api.handleApiProbeBatch(e)}handleJsBundleSearch(e){return this.account.handleJsBundleSearch(e)}};export{P as WorkflowHandlers};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jshookmcp/jshook",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "MCP server with built-in tools across multiple domains for AI-assisted JavaScript analysis and security analysis — browser automation, CDP debugging, network monitoring, JS hooks, code analysis, and workflow orchestration",
5
5
  "keywords": [
6
6
  "ai",
@@ -91,7 +91,7 @@
91
91
  "cross-env": "^10.1.0",
92
92
  "lefthook": "^2.1.8",
93
93
  "medium-zoom": "^1.1.0",
94
- "oxfmt": "^0.51.0",
94
+ "oxfmt": "^0.53.0",
95
95
  "oxlint": "^1.66.0",
96
96
  "rollup-plugin-visualizer": "^7.0.1",
97
97
  "tinyglobby": "^0.2.16",
@@ -1 +0,0 @@
1
- import{E as e}from"./constants-BYj8Xek8.mjs";import{t}from"./ToolError-DWU_z7gp.mjs";import{_ as n,b as r,d as i,f as a,h as o,l as s,m as c,p as l,t as u,u as d}from"./Win32API-eUCF57l_.mjs";import{l as f}from"./Win32Debug-CYrIQBvr.mjs";import{n as p}from"./NativeMemoryManager.utils-BHy1P_jM.mjs";import{t as m}from"./NativeMemoryManager.impl-DniBe2wf.mjs";import{randomUUID as h}from"node:crypto";var g=class{patches=new Map;async patchBytes(e,t,a){let o=BigInt(t.startsWith(`0x`)?t:`0x${t}`),s=Buffer.from(a),l=r(e,!0);try{let t=i(l,o,s.length),{success:r,oldProtect:u}=c(l,o,s.length,d.EXECUTE_READWRITE);n(l,o,s),f(l,o,s.length),r&&c(l,o,s.length,u);let p={id:h(),pid:e,address:`0x${o.toString(16).toUpperCase()}`,originalBytes:Array.from(t),patchBytes:a,isApplied:!0,timestamp:Date.now()};return this.patches.set(p.id,p),p}finally{u(l)}}async unpatch(e){let t=this.patches.get(e);if(!t?.isApplied)return!1;let i=BigInt(t.address),a=Buffer.from(t.originalBytes),o=r(t.pid,!0);try{let{oldProtect:e}=c(o,i,a.length,d.EXECUTE_READWRITE);return n(o,i,a),f(o,i,a.length),c(o,i,a.length,e),t.isApplied=!1,!0}finally{u(o)}}async nopBytes(e,t,n){let r=Array.from({length:n},()=>144);return this.patchBytes(e,t,r)}async findCodeCaves(t,n){let a=n??e,s=[],c=r(t,!1);try{let e=await m.enumerateModules(t);if(!e.success||!e.modules)return s;for(let t of e.modules){let e=BigInt(t.baseAddress.startsWith(`0x`)?t.baseAddress:`0x${t.baseAddress}`),n=e,r=e+BigInt(t.size);for(;n<r;){let{success:e,info:r}=o(c,n);if(!e||r.RegionSize===0n)break;let l=Number(r.RegionSize);if(p(r.Protect)&&l>0)try{let e=i(c,r.BaseAddress,Math.min(l,4*1024*1024)),n=-1;for(let i=0;i<e.length;i++){let o=e[i];if(o===0||o===204)n===-1&&(n=i);else if(n!==-1){let e=i-n;if(e>=a){let i=r.BaseAddress+BigInt(n);s.push({address:`0x${i.toString(16).toUpperCase()}`,size:e,module:t.name,section:`.text`})}n=-1}}if(n!==-1){let i=e.length-n;if(i>=a){let e=r.BaseAddress+BigInt(n);s.push({address:`0x${e.toString(16).toUpperCase()}`,size:i,module:t.name,section:`.text`})}}}catch{}n=r.BaseAddress+r.RegionSize}}}finally{u(c)}return s.toSorted((e,t)=>t.size-e.size)}async allocateRemote(e,n){let i=r(e,!0);try{let e=a(i,0n,n,s.COMMIT|s.RESERVE,d.EXECUTE_READWRITE);if(e===0n)throw new t(`RUNTIME`,`VirtualAllocEx failed`);return`0x${e.toString(16).toUpperCase()}`}finally{u(i)}}async freeRemote(e,t,n){let i=BigInt(t.startsWith(`0x`)?t:`0x${t}`),a=r(e,!0);try{return l(a,i,0,s.RELEASE)}finally{u(a)}}listPatches(){return Array.from(this.patches.values())}};const _=new g;export{g as CodeInjector,_ as codeInjector};