@jshookmcp/jshook 0.3.0 → 0.3.2

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 (346) hide show
  1. package/LICENSE +661 -661
  2. package/README.md +32 -49
  3. package/README.zh.md +32 -47
  4. package/dist/AntiCheatDetector-B6d4Qe9D.mjs +1 -0
  5. package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
  6. package/dist/CacheAdapters-CsNtQIR8.mjs +1 -0
  7. package/dist/CodeInjector-Cll_7bLJ.mjs +1 -0
  8. package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
  9. package/dist/DOMInspector-C19J4zeq.mjs +95 -0
  10. package/dist/DarwinAPI-ZfQdpLNI.mjs +1 -0
  11. package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
  12. package/dist/EventBus-DL8iLA09.mjs +1 -0
  13. package/dist/EvidenceGraphBridge-BtbwXsLC.mjs +1 -0
  14. package/dist/ExtensionManager-BD724zkO.mjs +1 -0
  15. package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
  16. package/dist/FingerprintManager-DT0EAUEo.mjs +1 -0
  17. package/dist/HardwareBreakpoint-BUfPdp0f.mjs +1 -0
  18. package/dist/HeapAnalyzer-B_aqY8oj.mjs +1 -0
  19. package/dist/{HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +66 -101
  20. package/dist/InstrumentationSession-D_G1ZPyd.mjs +1 -0
  21. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
  22. package/dist/MemoryController-X1XNSn1n.mjs +2 -0
  23. package/dist/MemoryScanSession-DG_F-PjE.mjs +1 -0
  24. package/dist/MemoryScanner-g1_L1ub5.mjs +1 -0
  25. package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +1 -0
  26. package/dist/NativeMemoryManager.utils-BHy1P_jM.mjs +1 -0
  27. package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
  28. package/dist/PEAnalyzer-yWQaGrcx.mjs +1 -0
  29. package/dist/PageController-Dfsm1_o7.mjs +1 -0
  30. package/dist/PointerChainEngine-BhCUkmxY.mjs +1 -0
  31. package/dist/PrerequisiteError-BjCQA-gK.mjs +1 -0
  32. package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
  33. package/dist/ResponseBuilder-BfWP-uaT.mjs +1 -0
  34. package/dist/ReverseEvidenceGraph-BhSYYdiI.mjs +2 -0
  35. package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
  36. package/dist/ScriptManager-LWGPTdvD.mjs +7 -0
  37. package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
  38. package/dist/Speedhack-yseDPSZ9.mjs +1 -0
  39. package/dist/StealthVerifier-BmcxfwSF.mjs +1 -0
  40. package/dist/StructureAnalyzer-C5lpuZkg.mjs +2 -0
  41. package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
  42. package/dist/ToolError-DWU_z7gp.mjs +1 -0
  43. package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
  44. package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
  45. package/dist/ToolRouter.policy-CfhJczkt.mjs +4 -0
  46. package/dist/TraceRecorder-BiJWBXHX.mjs +272 -0
  47. package/dist/VersionDetector-CHT36Az0.mjs +9 -0
  48. package/dist/Win32API-eUCF57l_.mjs +1 -0
  49. package/dist/Win32Debug-CYrIQBvr.mjs +1 -0
  50. package/dist/WorkflowEngine-D876meOO.mjs +1 -0
  51. package/dist/analysis-D4swdMvq.mjs +6 -0
  52. package/dist/{antidebug-BRKeyt27.mjs → antidebug-7L3ygj_9.mjs} +8 -259
  53. package/dist/apk-packer-BqXcInnX.mjs +1 -0
  54. package/dist/artifactRetention-BCPQASm7.mjs +1 -0
  55. package/dist/artifacts-CkodUM4j.mjs +1 -0
  56. package/dist/authorization-schema-BOFwSXUN.mjs +1 -0
  57. package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
  58. package/dist/binary-instrument-DU7V6TUM.mjs +7 -0
  59. package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
  60. package/dist/bind-helpers-m2U8glkF.mjs +1 -0
  61. package/dist/boringssl-inspector-BBaJwwkU.mjs +2 -0
  62. package/dist/browser-Qqco2rOT.mjs +11 -0
  63. package/dist/capabilities-CyXuKUl1.mjs +1 -0
  64. package/dist/chunk-C_pMuVsO.mjs +1 -0
  65. package/dist/collector-Bpl6qy2L.mjs +1 -0
  66. package/dist/concurrency-DCr8WQ2M.mjs +1 -0
  67. package/dist/constants-BYj8Xek8.mjs +1 -0
  68. package/dist/coordination-CWXW1o8K.mjs +1 -0
  69. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  70. package/dist/debugger-DyALjYMk.mjs +1 -0
  71. package/dist/definitions-BWxBke3r.mjs +1 -0
  72. package/dist/definitions-BYwATKc-.mjs +1 -0
  73. package/dist/definitions-B_83XfNQ.mjs +1 -0
  74. package/dist/definitions-Bf3H1EwV.mjs +1 -0
  75. package/dist/definitions-BftdXgXI.mjs +1 -0
  76. package/dist/definitions-Bio5XJYy.mjs +1 -0
  77. package/dist/definitions-C3qNgSn1.mjs +1 -0
  78. package/dist/definitions-CB6vmOer.mjs +1 -0
  79. package/dist/definitions-CMZRSy3k.mjs +1 -0
  80. package/dist/definitions-CQd7yCQH.mjs +1 -0
  81. package/dist/definitions-CT8ln6GQ.mjs +1 -0
  82. package/dist/definitions-Cenu6mxo.mjs +1 -0
  83. package/dist/definitions-D4g-MS10.mjs +1 -0
  84. package/dist/definitions-D5wl_8HN.mjs +1 -0
  85. package/dist/definitions-DAQm1Xar.mjs +1 -0
  86. package/dist/definitions-DP1vgxEY.mjs +1 -0
  87. package/dist/definitions-DxFNRQNK2.mjs +1 -0
  88. package/dist/definitions-Ibci7e_L.mjs +1 -0
  89. package/dist/definitions-OeLvmlQy.mjs +1 -0
  90. package/dist/definitions-RZYGD_Ey.mjs +1 -0
  91. package/dist/definitions-Tls8c0A0.mjs +1 -0
  92. package/dist/definitions-bybDvnG0.mjs +26 -0
  93. package/dist/definitions-l7TjdE6V.mjs +1 -0
  94. package/dist/encoding-ycOaz8Vr.mjs +2 -0
  95. package/dist/ensure-browser-core-DxWC-NTp.mjs +1 -0
  96. package/dist/evidence-graph-bridge-CV_UdYqj.mjs +1 -0
  97. package/dist/factory-CKr4fAE1.mjs +1 -0
  98. package/dist/flat-target-session-DvcQX7J5.mjs +1 -0
  99. package/dist/formatAddress-vLA_hOJt.mjs +1 -0
  100. package/dist/graphql-B2TiPEow.mjs +62 -0
  101. package/dist/handlers-0yKLRIfo.mjs +2 -0
  102. package/dist/handlers-8zN_vBIz.mjs +1 -0
  103. package/dist/handlers-B62K4FTc.mjs +1 -0
  104. package/dist/handlers-BpDlVVVU.mjs +1 -0
  105. package/dist/handlers-CMJK7m1c.mjs +31 -0
  106. package/dist/handlers-D2ZOul9p.mjs +54 -0
  107. package/dist/handlers-D5E40ssn.mjs +5 -0
  108. package/dist/handlers-DGbdQAgD.mjs +4 -0
  109. package/dist/handlers-DHO3rjsW.mjs +1 -0
  110. package/dist/handlers-FJ80VzUI.mjs +2 -0
  111. package/dist/handlers-VHWrxbM_.mjs +1 -0
  112. package/dist/handlers-l8QIKqBj.mjs +2 -0
  113. package/dist/handlers-mPFiNPe8.mjs +302 -0
  114. package/dist/{handlers-Dz9PYsCa.mjs → handlers-yo_xYzT8.mjs} +118 -904
  115. package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
  116. package/dist/hooks-D4XLfgtV.mjs +600 -0
  117. package/dist/index.mjs +13 -5240
  118. package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
  119. package/dist/logger-sBC6IdRT.mjs +1 -0
  120. package/dist/maintenance-BUpIukhg.mjs +1 -0
  121. package/dist/manifest-0Jpt_AQa.mjs +1 -0
  122. package/dist/manifest-B3fZbSWR.mjs +1 -0
  123. package/dist/manifest-B7NB2rh2.mjs +1 -0
  124. package/dist/manifest-BDi4nbH1.mjs +1 -0
  125. package/dist/manifest-BLDfkE7n.mjs +1 -0
  126. package/dist/manifest-BcXbB4gf.mjs +1 -0
  127. package/dist/manifest-Bdnc_vrc.mjs +1 -0
  128. package/dist/manifest-BuYKgCnp.mjs +1 -0
  129. package/dist/manifest-CBfNnGPV.mjs +1 -0
  130. package/dist/manifest-CPS1Xv69.mjs +1 -0
  131. package/dist/manifest-CQH9FhwI.mjs +1 -0
  132. package/dist/manifest-CRryuZF4.mjs +1 -0
  133. package/dist/manifest-CctIumog.mjs +1 -0
  134. package/dist/manifest-CvTe5ZGV2.mjs +1 -0
  135. package/dist/manifest-D-5GH0DV.mjs +1 -0
  136. package/dist/manifest-D3Ssf3IC.mjs +1 -0
  137. package/dist/manifest-D5ck3NvC.mjs +1 -0
  138. package/dist/manifest-D9jUUJAu.mjs +1 -0
  139. package/dist/manifest-DCx6w2XV.mjs +1 -0
  140. package/dist/manifest-DG19q-Ld.mjs +1 -0
  141. package/dist/manifest-DLMlD0Zc.mjs +1 -0
  142. package/dist/manifest-DYpn8w_h.mjs +1 -0
  143. package/dist/manifest-DYzWI8Xs.mjs +1 -0
  144. package/dist/manifest-D_obs5F4.mjs +1 -0
  145. package/dist/manifest-DujQqEQR.mjs +2 -0
  146. package/dist/manifest-DwL2ik8P.mjs +1 -0
  147. package/dist/manifest-ItF5P8A12.mjs +1 -0
  148. package/dist/manifest-KZphqIyX.mjs +1 -0
  149. package/dist/manifest-LG42zPLY2.mjs +1 -0
  150. package/dist/manifest-LLdI5m4T.mjs +1 -0
  151. package/dist/manifest-QYbQXJn0.mjs +1 -0
  152. package/dist/manifest-RcpX_MyZ.mjs +123 -0
  153. package/dist/manifest-YgVd8Sgz.mjs +1 -0
  154. package/dist/manifest-Zy7Odg5J.mjs +1 -0
  155. package/dist/manifest-ff1H7Pdp.mjs +1 -0
  156. package/dist/manifest-iuhF6pTL2.mjs +1 -0
  157. package/dist/manifest-nXHmtMSp2.mjs +1 -0
  158. package/dist/manifest-xWfu6iLo.mjs +1 -0
  159. package/dist/manifest-yC16OhL2.mjs +1 -0
  160. package/dist/manifest-ztWJoXy4.mjs +1 -0
  161. package/dist/matchesWildcardPattern-BAG6LvX5.mjs +1 -0
  162. package/dist/modules-BPBcSaM-.mjs +333 -0
  163. package/dist/mojo-ipc-BhwsdVUW.mjs +9 -0
  164. package/dist/native/scripts/linux/enum-windows.sh +12 -12
  165. package/dist/native/scripts/macos/enum-windows.applescript +22 -22
  166. package/dist/native-j8l473zn.mjs +961 -0
  167. package/dist/network-T0VRwNPd.mjs +7 -0
  168. package/dist/outputPaths-B4Ic4RZh.mjs +2 -0
  169. package/dist/parse-args-Bw413PlW.mjs +1 -0
  170. package/dist/platform-CzaQtISh.mjs +93 -0
  171. package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +1 -0
  172. package/dist/process-CWhsCWrf.mjs +2 -0
  173. package/dist/proxy-DZFlDsG3.mjs +2 -0
  174. package/dist/registry-DH4sc1dt.mjs +1 -0
  175. package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
  176. package/dist/response-C7rKQst4.mjs +1 -0
  177. package/dist/search-defaults-lYBVn_3L.mjs +1 -0
  178. package/dist/server/plugin-api.d.mts +19 -36
  179. package/dist/server/plugin-api.mjs +1 -293
  180. package/dist/shared-state-board-BSjXLUV1.mjs +1 -0
  181. package/dist/sourcemap-Dh3Ai_ur.mjs +1 -0
  182. package/dist/ssrf-policy-CsIJGkpd.mjs +1 -0
  183. package/dist/streaming-BcJ0B6ao.mjs +1 -0
  184. package/dist/tool-builder-qif8M9-K.mjs +1 -0
  185. package/dist/transform-DOxzeWPB.mjs +103 -0
  186. package/dist/types-D9EiE5o9.mjs +1 -0
  187. package/dist/types-Fz69RzbZ.mjs +1 -0
  188. package/dist/wasm-CZ_HTfKR.mjs +174 -0
  189. package/dist/webcrack-C1iYG_EX.mjs +46 -0
  190. package/dist/workflow-BdwQmARn.mjs +101 -0
  191. package/package.json +55 -82
  192. package/src/native/scripts/linux/enum-windows.sh +12 -12
  193. package/src/native/scripts/macos/enum-windows.applescript +22 -22
  194. package/dist/AntiCheatDetector-CqGDXmfc.mjs +0 -350
  195. package/dist/CacheAdapters-jJFy20G-.mjs +0 -80
  196. package/dist/CodeInjector-BdjRfNx7.mjs +0 -150
  197. package/dist/ConsoleMonitor-DykL3IAw.mjs +0 -2269
  198. package/dist/DarwinAPI-ETyy0xyo.mjs +0 -363
  199. package/dist/DetailedDataManager-HT49OrvF.mjs +0 -217
  200. package/dist/EventBus-DFKvADm3.mjs +0 -141
  201. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +0 -153
  202. package/dist/ExtensionManager-BDMsY2Dz.mjs +0 -721
  203. package/dist/FingerprintManager-BN4UQWnX.mjs +0 -96
  204. package/dist/HardwareBreakpoint-Cc2AFq1Y.mjs +0 -239
  205. package/dist/HeapAnalyzer-DruMgsgj.mjs +0 -284
  206. package/dist/InstrumentationSession-DLH0vd-z.mjs +0 -244
  207. package/dist/MemoryController-CMtviNW_.mjs +0 -167
  208. package/dist/MemoryScanSession-ITgb_NMi.mjs +0 -278
  209. package/dist/MemoryScanner-CiL7Z3ey.mjs +0 -428
  210. package/dist/NativeMemoryManager.impl-D9Lkovvn.mjs +0 -485
  211. package/dist/NativeMemoryManager.utils-BBlAixF5.mjs +0 -165
  212. package/dist/PEAnalyzer-DMQ44gen.mjs +0 -385
  213. package/dist/PageController-BPJNqqBN.mjs +0 -431
  214. package/dist/PointerChainEngine-K7wN8Z-w.mjs +0 -325
  215. package/dist/PrerequisiteError-TuyZIs6n.mjs +0 -20
  216. package/dist/ProcessRegistry-zGg12QbE.mjs +0 -74
  217. package/dist/ResponseBuilder-CJXWmWNw.mjs +0 -143
  218. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +0 -269
  219. package/dist/ScriptManager-ZuWD-0Jg.mjs +0 -3003
  220. package/dist/Speedhack-D-z0umeT.mjs +0 -156
  221. package/dist/StealthVerifier-BWmPgQsv.mjs +0 -135
  222. package/dist/StructureAnalyzer-Cav5AVSL.mjs +0 -429
  223. package/dist/ToolCatalog-5OJdMiF0.mjs +0 -582
  224. package/dist/ToolError-jh9whhMd.mjs +0 -15
  225. package/dist/ToolProbe-DbCFGyrg.mjs +0 -45
  226. package/dist/ToolRegistry-B9krbTtI.mjs +0 -180
  227. package/dist/ToolRouter.policy-BGDAGyeH.mjs +0 -344
  228. package/dist/TraceRecorder-B41Z5XBj.mjs +0 -1286
  229. package/dist/VersionDetector-K3V4vGsw.mjs +0 -104
  230. package/dist/Win32API-C2kjj0ze.mjs +0 -346
  231. package/dist/Win32Debug-CKrGOTpo.mjs +0 -274
  232. package/dist/WorkflowEngine-DJ6M4opp.mjs +0 -569
  233. package/dist/analysis-BHeJW2Nb.mjs +0 -1234
  234. package/dist/artifactRetention-CPXkUJXp.mjs +0 -598
  235. package/dist/artifacts-DkfosXH3.mjs +0 -59
  236. package/dist/authorization-schema-DRqyJMSk.mjs +0 -31
  237. package/dist/betterSqlite3-DLSBZodi.mjs +0 -74
  238. package/dist/binary-instrument--V3MAhJ4.mjs +0 -971
  239. package/dist/bind-helpers-ClV34xdn.mjs +0 -42
  240. package/dist/boringssl-inspector-Bo_LOLaS.mjs +0 -180
  241. package/dist/browser-Dx3_S2cG.mjs +0 -4369
  242. package/dist/capabilities-CcHlvWgK.mjs +0 -33
  243. package/dist/chunk-CjcI7cDX.mjs +0 -15
  244. package/dist/concurrency-Drev_Vz9.mjs +0 -41
  245. package/dist/constants-CDZLOoVv.mjs +0 -534
  246. package/dist/coordination-DgItD9DL.mjs +0 -259
  247. package/dist/debugger-RS3RSAqs.mjs +0 -1288
  248. package/dist/definitions-BEoYofW5.mjs +0 -47
  249. package/dist/definitions-BRaefg3u.mjs +0 -365
  250. package/dist/definitions-BbkvZkiv.mjs +0 -96
  251. package/dist/definitions-BtWSHJ3o.mjs +0 -17
  252. package/dist/definitions-C1gCHO0i.mjs +0 -43
  253. package/dist/definitions-CDOg_b-l.mjs +0 -138
  254. package/dist/definitions-CVPD9hzZ.mjs +0 -54
  255. package/dist/definitions-Cea8Lgl7.mjs +0 -94
  256. package/dist/definitions-DAgIyjxM.mjs +0 -10
  257. package/dist/definitions-DJA27nsL.mjs +0 -66
  258. package/dist/definitions-DKPFU3LW.mjs +0 -25
  259. package/dist/definitions-DPRpZQ96.mjs +0 -47
  260. package/dist/definitions-DUE5gmdn.mjs +0 -18
  261. package/dist/definitions-DYVjOtxa.mjs +0 -26
  262. package/dist/definitions-DcYLVLCo.mjs +0 -37
  263. package/dist/definitions-Pp5LI2H4.mjs +0 -27
  264. package/dist/definitions-j9KdHVNR.mjs +0 -14
  265. package/dist/definitions-uzkjBwa7.mjs +0 -258
  266. package/dist/definitions-va-AnLuQ.mjs +0 -28
  267. package/dist/encoding-DJeqHmpd.mjs +0 -1079
  268. package/dist/evidence-graph-bridge-DcYizFk2.mjs +0 -136
  269. package/dist/factory-C90tBff6.mjs +0 -575
  270. package/dist/flat-target-session-Dgax2Cy3.mjs +0 -29
  271. package/dist/formatAddress-nnMvEohD.mjs +0 -17
  272. package/dist/graphql-CoHrhweh.mjs +0 -1197
  273. package/dist/handlers-4jmR0nMs.mjs +0 -898
  274. package/dist/handlers-BAHPxcch.mjs +0 -789
  275. package/dist/handlers-BOs9b907.mjs +0 -2600
  276. package/dist/handlers-BWXEy6ef.mjs +0 -917
  277. package/dist/handlers-Bndn6QvE.mjs +0 -111
  278. package/dist/handlers-BqC4bD4s.mjs +0 -681
  279. package/dist/handlers-BtYq60bM2.mjs +0 -276
  280. package/dist/handlers-BzgcB4iv.mjs +0 -799
  281. package/dist/handlers-CRyRWj2b.mjs +0 -859
  282. package/dist/handlers-CVv2H1uq.mjs +0 -592
  283. package/dist/handlers-Dl5a7JS4.mjs +0 -572
  284. package/dist/handlers-Dx2d7jt7.mjs +0 -2537
  285. package/dist/handlers-HujRKC3b.mjs +0 -661
  286. package/dist/handlers.impl-XWXkQfyi.mjs +0 -807
  287. package/dist/hooks-B1B8NRHL.mjs +0 -898
  288. package/dist/logger-Dh_xb7_2.mjs +0 -93
  289. package/dist/maintenance-PRMkLVRW.mjs +0 -835
  290. package/dist/manifest-67Bok-Si.mjs +0 -58
  291. package/dist/manifest-6lNTMZAB2.mjs +0 -87
  292. package/dist/manifest-B2duEHiH.mjs +0 -90
  293. package/dist/manifest-B6EY9Vm8.mjs +0 -57
  294. package/dist/manifest-B6nKSbyY.mjs +0 -95
  295. package/dist/manifest-BL8AQNPF.mjs +0 -106
  296. package/dist/manifest-BSZvJJmV.mjs +0 -47
  297. package/dist/manifest-BU7qzUyX.mjs +0 -418
  298. package/dist/manifest-Bl62e8WK.mjs +0 -49
  299. package/dist/manifest-Bo5cXjdt.mjs +0 -82
  300. package/dist/manifest-BpS4gtUK.mjs +0 -1347
  301. package/dist/manifest-Bv65_e2W.mjs +0 -101
  302. package/dist/manifest-BytNIF4Z.mjs +0 -117
  303. package/dist/manifest-C-xtsjS3.mjs +0 -81
  304. package/dist/manifest-CDYl7OhA.mjs +0 -66
  305. package/dist/manifest-CRZ3xmkD.mjs +0 -61
  306. package/dist/manifest-CoW6u4Tp.mjs +0 -132
  307. package/dist/manifest-Cq5zN_8A.mjs +0 -50
  308. package/dist/manifest-D7YZM_2e.mjs +0 -194
  309. package/dist/manifest-DE_VrAeQ.mjs +0 -314
  310. package/dist/manifest-DGsXSCpT.mjs +0 -39
  311. package/dist/manifest-DJ2vfEuW.mjs +0 -156
  312. package/dist/manifest-DPXDYhEu.mjs +0 -80
  313. package/dist/manifest-Dd4fQb0a.mjs +0 -322
  314. package/dist/manifest-Deq6opGg.mjs +0 -223
  315. package/dist/manifest-DfJTafJK.mjs +0 -37
  316. package/dist/manifest-DgOdgN_j.mjs +0 -50
  317. package/dist/manifest-DlbMW4v4.mjs +0 -47
  318. package/dist/manifest-DmVfbH0w.mjs +0 -374
  319. package/dist/manifest-Dog6Ddjr.mjs +0 -109
  320. package/dist/manifest-DvgU5FWb.mjs +0 -58
  321. package/dist/manifest-HsfDBs7j.mjs +0 -50
  322. package/dist/manifest-I8oQHvCG.mjs +0 -186
  323. package/dist/manifest-NvH_a-av.mjs +0 -786
  324. package/dist/manifest-cEJU1v0Z.mjs +0 -129
  325. package/dist/manifest-wOl5XLB12.mjs +0 -112
  326. package/dist/modules-tZozf0LQ.mjs +0 -10635
  327. package/dist/mojo-ipc-DXNEXEqb.mjs +0 -640
  328. package/dist/network-CPVvwvFg.mjs +0 -3852
  329. package/dist/outputPaths-um7lCRY3.mjs +0 -1141
  330. package/dist/parse-args-B4cY5Vx5.mjs +0 -39
  331. package/dist/platform-CYeFoTWp.mjs +0 -2161
  332. package/dist/process-BTbgcVc6.mjs +0 -1306
  333. package/dist/proxy-r8YN6nP1.mjs +0 -192
  334. package/dist/registry-Bl8ZQW61.mjs +0 -34
  335. package/dist/response-CWhh2aLo.mjs +0 -34
  336. package/dist/shared-state-board-BoZnSoj-.mjs +0 -586
  337. package/dist/sourcemap-BIDHUVXy.mjs +0 -934
  338. package/dist/ssrf-policy-Dsqd-DTX.mjs +0 -166
  339. package/dist/streaming-Dal6utPp.mjs +0 -725
  340. package/dist/tool-builder-BHJp32mV.mjs +0 -186
  341. package/dist/transform-DRVgGG90.mjs +0 -1011
  342. package/dist/types-Bx92KJfT.mjs +0 -4
  343. package/dist/types-DDBWs9UP.mjs +0 -37
  344. package/dist/wasm-BYx5UOeG.mjs +0 -1044
  345. package/dist/webcrack-Be0_FccV.mjs +0 -747
  346. package/dist/workflow-BpuKEtvn.mjs +0 -725
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`jadx_search_code`,e=>e.desc(`Read-only ripgrep-backed search over an existing jadx decompile directory. ReDoS-guarded; Node fallback.`).string(`decompileDir`,`Absolute path to an existing jadx decompile output directory. The tool does not decompile — run jadx via the binary-instrument domain first.`).string(`query`,"Search query (regex unless `literal:true`)").boolean(`literal`,"Treat `query` as a literal string, not a regex",{default:!1}).boolean(`caseInsensitive`,`Case-insensitive matching`,{default:!1}).integer(`contextLines`,`Lines of context around each match`,{default:2,minimum:0,maximum:20}).integer(`maxMatchesPerFile`,`Cap on matches recorded per file`,{minimum:1}).integer(`maxResults`,`Hard ceiling on total matches across all files`,{minimum:1}).array(`globs`,{type:`string`,description:`Glob pattern (negative globs may start with !)`},"File globs applied during enumeration. Defaults to `**/*.java`, `**/*.kt`.").required(`decompileDir`,`query`).query())];export{t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[`constant_fold`,`string_decrypt`,`dead_code_remove`,`control_flow_flatten`,`rename_vars`],n=[e(`ast_transform_preview`,e=>e.desc(`Preview lightweight AST-like transforms (string/regex based) and return before/after diff.`).string(`code`,`Source code to transform.`).array(`transforms`,{type:`string`,enum:t},`Ordered transform list.`).boolean(`preview`,`Whether to generate line diff output.`,{default:!0}).required(`code`,`transforms`).query()),e(`ast_transform_chain`,e=>e.desc(`Create and store an in-memory transform chain.`).string(`name`,`Chain name.`).array(`transforms`,{type:`string`,enum:t},`Ordered transform list.`).string(`description`,`Optional chain description.`).required(`name`,`transforms`)),e(`ast_transform_apply`,e=>e.desc(`Apply transforms to input code or a live page scriptId.`).string(`scriptId`,`Target script ID from page debugger context.`).string(`code`,`Direct source code input.`).string(`chainName`,`Use a saved transform chain by name.`).array(`transforms`,{type:`string`,enum:t},`Direct transform list (used when chainName is not provided).`)),e(`crypto_extract_standalone`,e=>e.desc(`Extract crypto/sign/encrypt function from current page and generate standalone runnable code.`).string(`targetFunction`,`Target function name/path, e.g. "window.sign".`).boolean(`includePolyfills`,`Include minimal runtime polyfills.`,{default:!0}).required(`targetFunction`)),e(`crypto_test_harness`,e=>e.desc(`Run extracted crypto code in worker_threads + vm sandbox and return deterministic test results.`).string(`code`,`Standalone function code.`).string(`functionName`,`Exported function name to execute.`).array(`testInputs`,{type:`string`},`Input list for test execution.`).required(`code`,`functionName`,`testInputs`).query()),e(`crypto_compare`,e=>e.desc(`Compare two crypto implementations against identical test vectors.`).string(`code1`,`Implementation A code.`).string(`code2`,`Implementation B code.`).string(`functionName`,`Function name shared by both implementations.`).array(`testInputs`,{type:`string`},`Input list for comparison.`).required(`code1`,`code2`,`functionName`,`testInputs`).query())];export{n as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t={type:`object`,additionalProperties:!1,properties:{allowPrivateNetwork:{type:`boolean`,description:`Allow access to private/reserved targets only when the request also matches allowedHosts or allowedCidrs.`},allowInsecureHttp:{type:`boolean`,description:`Allow non-loopback HTTP targets only when the request also matches allowedHosts or allowedCidrs.`},allowedHosts:{type:`array`,items:{type:`string`},description:`Exact hostname or host:port allowlist for the primary target (for example ["labs.example.com", "localhost:8080"]).`},allowedCidrs:{type:`array`,items:{type:`string`},description:`CIDR allowlist applied after DNS resolution (for example ["10.10.0.0/16", "192.168.1.10/32"]).`},allowedRedirectHosts:{type:`array`,items:{type:`string`},description:`Optional hostname or host:port allowlist for redirect hops. When omitted, redirects inherit allowedHosts/allowedCidrs.`}},description:`Request-level network authorization policy. Use this instead of process-wide bypasses when you need to reach a real lab target, private address, or plain HTTP service.`},n=[e(`js_bundle_search`,e=>e.desc(`Fetch a remote JS bundle and search it with named regex patterns, with caching and noise filtering.`).string(`url`,`Remote URL of the JavaScript bundle to analyze`).array(`patterns`,{type:`object`,properties:{name:{type:`string`,description:`Human-readable label for this pattern`},regex:{type:`string`,description:`JavaScript regex string`},contextBefore:{type:`number`,description:`Characters of context before match (default: 80)`},contextAfter:{type:`number`,description:`Characters of context after match (default: 80)`}},required:[`name`,`regex`]},`Named regex patterns to search for`).boolean(`cacheBundle`,`Cache the bundle for 5 minutes to avoid re-downloads`,{default:!0}).boolean(`stripNoise`,`Skip matches inside SVG path data or base64 blobs`,{default:!0}).number(`maxMatches`,`Maximum matches to return per pattern`,{default:10,minimum:1,maximum:1e3}).prop(`networkPolicy`,t).requiredOpenWorld(`url`,`patterns`)),e(`page_script_register`,e=>e.desc(`Register a named reusable JS snippet in the Script Library. Execute with page_script_run.`).string(`name`,`Unique script name (e.g. "my_extractor")`).string(`code`,'JavaScript expression/IIFE to register. Use `typeof __params__ !== "undefined" ? __params__ : {}` to safely access runtime parameters.').string(`description`,`Optional human-readable description of the script`).required(`name`,`code`)),e(`page_script_run`,e=>e.desc(`Execute a named script from the Script Library with optional runtime params (__params__).`).string(`name`,`Script name to run (built-in or registered)`).prop(`params`,{type:`object`,additionalProperties:!0,description:`Optional parameters injected as __params__ (must be JSON-serializable)`}).requiredOpenWorld(`name`)),e(`api_probe_batch`,e=>e.desc(`Batch-probe API endpoints in browser context with auto token injection and HTML skip.`).string(`baseUrl`,`Base URL prefix (e.g. "https://chat.qwen.ai") — trailing slash will be stripped`).array(`paths`,{type:`string`},`Paths to probe (e.g. ["/api/v1/users", "/api/v1/chats"])`).enum(`method`,[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],`HTTP method for all probes`,{default:`GET`}).object(`headers`,{additionalProperties:{type:`string`}},`Additional HTTP headers to include in all requests`).string(`bodyTemplate`,`JSON body string to send for POST/PUT/PATCH requests (optional)`).array(`includeBodyStatuses`,{type:`number`},`Status codes for which to include response body snippet (default: [200, 201, 204])`).number(`maxBodySnippetLength`,`Max characters per response body snippet`,{default:500,minimum:0,maximum:1e4}).boolean(`autoInjectAuth`,`Auto-inject Bearer token from localStorage (token / active_token / access_token).`,{default:!0}).prop(`networkPolicy`,t).requiredOpenWorld(`baseUrl`,`paths`)),e(`list_extension_workflows`,e=>e.desc(`List runtime-loaded extension workflows from plugins/ or workflows/ directories.`).query()),e(`run_extension_workflow`,e=>e.desc(`Execute an extension workflow by workflowId with optional config and timeout overrides.`).string(`workflowId`,`Registered extension workflow id to execute`).string(`profile`,`Optional profile label exposed to the workflow execution context`).prop(`config`,{type:`object`,additionalProperties:!0,description:`Optional config overrides read through ctx.getConfig(path, fallback)`}).prop(`nodeInputOverrides`,{type:`object`,additionalProperties:{type:`object`,additionalProperties:!0},description:`Optional shallow input overrides keyed by workflow node id`}).number(`timeoutMs`,`Optional override for total workflow timeout in milliseconds`).requiredOpenWorld(`workflowId`))];export{n as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`ai_hook`,e=>e.desc(`Manage AI hooks. Actions: inject (inject code into page), get_data (retrieve captured hook data), list (all active hooks), clear (remove hook data by id or all), toggle (enable/disable a hook), export (export data as JSON/CSV).`).enum(`action`,[`inject`,`get_data`,`list`,`clear`,`toggle`,`export`],`Operation to perform`).string(`hookId`,`Hook identifier (required for inject/get_data/toggle; optional for clear/export)`).string(`code`,`Hook code to inject (required for action=inject)`).enum(`method`,[`evaluateOnNewDocument`,`evaluate`],`Injection method (for action=inject)`,{default:`evaluate`}).boolean(`enabled`,`Enable or disable hook (required for action=toggle)`).enum(`format`,[`json`,`csv`],`Export format (for action=export)`,{default:`json`}).required(`action`))],n=[e(`hook_preset`,e=>e.desc(`Install a pre-built JavaScript hook from 20+ built-in presets (eval, atob/btoa, Proxy, Reflect, Object.defineProperty, etc.), or provide customTemplate/customTemplates to install your own reusable hook bodies. Use listPresets=true to see all available preset descriptions.`).string(`preset`,`Single preset name to install. Accepts built-in preset ids or ids provided by customTemplate/customTemplates.`).array(`presets`,{type:`string`},`List of preset names to install simultaneously. Accepts built-in ids and custom template ids.`).prop(`customTemplate`,{type:`object`,properties:{id:{type:`string`,description:`Stable preset id, for example deobfuscation-sinks`},description:{type:`string`,description:`Human-readable description for listPresets output.`},body:{type:`string`,description:`Hook body snippet inserted into the preset wrapper.`}},required:[`id`,`body`],description:`Inline custom template. body should contain the hook body inserted into the standard buildHookCode wrapper. Use {{STACK_CODE}} and {{LOG_FN}} placeholders when needed.`}).prop(`customTemplates`,{type:`array`,items:{type:`object`,properties:{id:{type:`string`},description:{type:`string`},body:{type:`string`}},required:[`id`,`body`]},description:`List of inline custom templates to register for this invocation.`}).boolean(`captureStack`,`Include call stack in captured data (has performance impact)`,{default:!1}).boolean(`logToConsole`,`Log hook events to browser console`,{default:!0}).enum(`method`,[`evaluate`,`evaluateOnNewDocument`],`Injection method: evaluate=current page, evaluateOnNewDocument=before page scripts`,{default:`evaluate`}).boolean(`listPresets`,`Set to true to list all available presets with descriptions instead of installing.`,{default:!1}))];export{n,t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`ws_monitor`,e=>e.desc(`Enable or disable WebSocket frame capture.`).enum(`action`,[`enable`,`disable`],`Monitor action`).string(`urlFilter`,`Regex filter for WebSocket URL (action=enable)`).number(`maxFrames`,`Maximum frames in memory (action=enable, default: 1000)`,{default:1e3,minimum:1,maximum:1e5}).required(`action`).destructive()),e(`ws_get_frames`,e=>e.desc(`Get captured WebSocket frames with pagination and payload filter.`).enum(`direction`,[`sent`,`received`,`all`],`Frame direction filter`,{default:`all`}).number(`limit`,`Maximum frames to return`,{default:100,minimum:1,maximum:1e4}).number(`offset`,`Pagination offset`,{default:0,minimum:0}).string(`payloadFilter`,`Regex filter on frame payload`).readOnly()),e(`ws_get_connections`,e=>e.desc(`Get tracked WebSocket connections and frame counts.`).readOnly()),e(`sse_monitor_enable`,e=>e.desc(`Enable SSE monitoring by injecting EventSource interceptor.`).string(`urlFilter`,`Regex filter for EventSource URL`).number(`maxEvents`,`Maximum SSE events in memory`,{default:2e3,minimum:1,maximum:1e5}).boolean(`persistent`,`Survive page navigations via evaluateOnNewDocument`)),e(`sse_get_events`,e=>e.desc(`Get captured SSE events with filters and pagination.`).string(`sourceUrl`,`Filter by EventSource URL`).string(`eventType`,`Filter by SSE event type`).number(`limit`,`Maximum events`,{default:100,minimum:1,maximum:1e4}).number(`offset`,`Pagination offset`,{default:0,minimum:0}).readOnly())];export{t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`apk_packer_detect`,e=>e.desc("Detect Android APK packers by matching `lib/<abi>/lib*.so` filenames against user-supplied customSignatures (ReDoS-guarded regex compilation). The framework ships no built-in signature table — callers provide their own. **Does not unpack, execute, or otherwise interact with the packed payload.**").string(`apkPath`,`Absolute path to the .apk (or .aab) file to inspect`).string(`dirPath`,`Optional path to a directory containing an already-unpacked APK tree`).enum(`ruleMode`,[`append`,`prepend`,`replace`],`How customSignatures interact with the default (empty) signature table`,{default:`append`}).array(`customSignatures`,{type:`object`,properties:{name:{type:`string`,description:`Display name of the fingerprint entry`},category:{type:`string`,description:`Optional free-form category label supplied by the caller`},libPatterns:{type:`array`,items:{type:`string`},description:`lib basenames or anchored regex sources (case-insensitive; ReDoS-guarded)`},confidence:{type:`string`,enum:[`high`,`medium`,`low`],description:`Optional single-hit confidence hint (default: medium)`},notes:{type:`string`,description:`Free-form notes surfaced in list-signatures`}},required:[`name`,`libPatterns`]},`Fingerprints supplied by the caller. Compile-time and runtime ReDoS guards apply.`).query()),e(`apk_packer_list_signatures`,e=>e.desc("List the in-process signature table used by `apk_packer_detect`. Empty by default; reflects caller-managed state at request time. Optionally filter by case-insensitive category substring.").string(`category`,`Optional case-insensitive category substring filter`).query()),e(`apk_signing_block_parse`,e=>e.desc(`Read-only parser for the APK Signing Block (schemes v2/v3/v3.1/v4) plus key-rotation lineage detection and residue-block / dex-prefix / magic-offset anomaly flags. Never mutates the APK.`).string(`apkPath`,`Absolute path to the .apk file to parse`).required(`apkPath`).query())];export{t};
@@ -0,0 +1,26 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`debugger_lifecycle`,e=>e.desc(`Enable or disable the CDP debugger session.`).enum(`action`,[`enable`,`disable`],`Action to perform`).required(`action`).idempotent()),e(`debugger_pause`,e=>e.desc(`Pause execution at the next statement.`)),e(`debugger_resume`,e=>e.desc(`Resume execution.`)),e(`debugger_step`,e=>e.desc(`Step execution: into (enter next call), over (skip next call), out (exit current function).`).enum(`direction`,[`into`,`over`,`out`],`Step direction`).required(`direction`)),e(`breakpoint`,e=>e.desc(`Manage breakpoints: code (line/script), XHR (URL pattern), event listener, event category, and exception breakpoints.
2
+
3
+ Actions:
4
+ - set: Create a breakpoint. Type determines required params.
5
+ - remove: Remove a breakpoint by ID.
6
+ - list: List active breakpoints of the given type.
7
+
8
+ Types & params:
9
+ - code: lineNumber (required), scriptId?, columnNumber?, condition?
10
+ - xhr: urlPattern (required for set)
11
+ - event: eventName (required for set), targetName?
12
+ - event_category: category (required for set)
13
+ - exception: state (required for set)`).enum(`action`,[`set`,`remove`,`list`],`Breakpoint operation`).enum(`type`,[`code`,`xhr`,`event`,`event_category`,`exception`],`Breakpoint type (default: code)`,{default:`code`}).string(`url`,`Script URL (type=code, alternative to scriptId)`).string(`scriptId`,`Script ID (type=code)`).number(`lineNumber`,`Line number 0-based (type=code, action=set)`).number(`columnNumber`,`Column number 0-based (type=code)`).string(`condition`,`Conditional expression (type=code)`).string(`urlPattern`,`URL pattern with wildcards (type=xhr, action=set)`).string(`eventName`,`Event name e.g. "click" (type=event, action=set)`).string(`targetName`,`Target name e.g. "WebSocket" (type=event)`).enum(`category`,[`mouse`,`keyboard`,`timer`,`websocket`],`Event category (type=event_category)`).enum(`state`,[`none`,`uncaught`,`all`],`Exception pause state (type=exception)`).string(`breakpointId`,`Breakpoint ID (action=remove)`).required(`action`).idempotent()),e(`get_call_stack`,e=>e.desc(`Get the current call stack.`).query()),e(`debugger_evaluate`,e=>e.desc(`Evaluate a JavaScript expression. context="frame" evaluates in the current call frame (requires paused state); context="global" evaluates in the global context (no pause required).`).enum(`context`,[`frame`,`global`],`Evaluation context`,{default:`frame`}).string(`expression`,`JavaScript expression to evaluate`).string(`callFrameId`,`Call frame ID (for context=frame; from get_call_stack, defaults to current frame)`).requiredOpenWorld(`expression`)),e(`debugger_wait_for_paused`,e=>e.desc(`Wait for debugger pause after setting breakpoints.`).number(`timeout`,`Timeout in milliseconds (default: 30000)`,{default:3e4,minimum:1e3,maximum:12e4}).query()),e(`debugger_get_paused_state`,e=>e.desc(`Get current paused state and reason.`).query()),e(`get_object_properties`,e=>e.desc(`Get properties of an object by objectId.`).string(`objectId`,`Object ID (from get_scope_variables)`).required(`objectId`).query()),e(`get_scope_variables_enhanced`,e=>e.desc(`Enhanced scope variable inspection with deep object traversal.`).string(`callFrameId`,`Call frame ID (from get_call_stack, defaults to current frame)`).boolean(`includeObjectProperties`,`Expand object properties recursively (default: false)`,{default:!1}).number(`maxDepth`,`Maximum traversal depth for nested objects (default: 1)`,{default:1,minimum:1,maximum:10}).boolean(`skipErrors`,`Skip properties that throw errors during access (default: true)`,{default:!0}).query()),e(`debugger_session`,e=>e.desc(`Manage debugger sessions. Actions: save (persist current session to file), load (restore session from file/JSON), export (export session as JSON string), list (list saved sessions in ./debugger-sessions/).`).enum(`action`,[`save`,`load`,`export`,`list`],`Session operation`).string(`filePath`,`File path for save/load actions`).string(`sessionData`,`Session JSON string for load action (alternative to filePath)`).object(`metadata`,{},`Optional metadata for save/export actions`).required(`action`))],n=[e(`watch`,e=>e.desc(`Manage watch expressions for monitoring variable values during debugging.
14
+
15
+ Actions:
16
+ - add: Add a watch expression (requires expression)
17
+ - remove: Remove by watchId
18
+ - list: List all watches
19
+ - evaluate_all: Evaluate all enabled watches (optional callFrameId)
20
+ - clear_all: Clear all watches`).enum(`action`,[`add`,`remove`,`list`,`evaluate_all`,`clear_all`],`Watch operation`).string(`expression`,`JavaScript expression to watch (action=add)`).string(`name`,`Friendly name for the watch (action=add)`).string(`watchId`,`Watch expression ID (action=remove)`).string(`callFrameId`,`Call frame ID (action=evaluate_all)`).required(`action`)),e(`blackbox_add`,e=>e.desc(`Blackbox scripts (skip during debugging)
21
+
22
+ Usage:
23
+ - Skip third-party library c...`).string(`urlPattern`,`URL pattern to blackbox (supports wildcards *)`).required(`urlPattern`).idempotent()),e(`blackbox_add_common`,e=>e.desc(`Blackbox all common libraries (one-click)
24
+
25
+ Includes:
26
+ - jquery, react, vue, an...`).idempotent()),e(`blackbox_list`,e=>e.desc(`List script blackbox patterns.`).query())],r=[...t,...n];export{r as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";import{t}from"./authorization-schema-BOFwSXUN.mjs";const n=[e(`network_extract_auth`,e=>e.desc(`Extract authentication data from captured network requests.`).number(`minConfidence`,`Minimum confidence threshold 0-1`,{default:.4,minimum:0,maximum:1})),e(`network_export_har`,e=>e.desc(`Export captured network traffic as HAR.`).string(`outputPath`,`File path to write the HAR file. If omitted, returns HAR as JSON.`).boolean(`includeBodies`,`Include response bodies in the HAR (may be slow for large captures). Default: false`,{default:!1}).openWorld()),e(`network_replay_request`,e=>e.desc(`Replay a captured network request with optional changes.`).string(`requestId`,`Request ID from network_get_requests to replay`).object(`headerPatch`,{additionalProperties:{type:`string`}},`Headers to add or override (key-value pairs)`).object(`sessionProfile`,{cookies:{type:`array`,items:{type:`object`,properties:{name:{type:`string`},value:{type:`string`},domain:{type:`string`},path:{type:`string`},expires:{type:`number`},httpOnly:{type:`boolean`},secure:{type:`boolean`},sameSite:{type:`string`,enum:[`Strict`,`Lax`,`None`]}},required:[`name`,`value`]}},userAgent:{type:`string`},acceptLanguage:{type:`string`},referer:{type:`string`},clientHints:{type:`object`,properties:{"sec-ch-ua":{type:`string`},"sec-ch-ua-mobile":{type:`string`},"sec-ch-ua-platform":{type:`string`},"sec-ch-ua-full-version-list":{type:`string`}}},platform:{type:`string`},origin:{type:`string`},collectedAt:{type:`number`},ttlSec:{type:`number`}},`Inject browser cookies, User-Agent and Accept-Language from a captured session into the replay.`).string(`bodyPatch`,`Replace the entire request body with this string`).string(`methodOverride`,`Override the HTTP method`).string(`urlOverride`,`Override the request URL`).object(`authorization`,t,`Request-scoped authorization policy for private-network or insecure-HTTP replay. Use exact hosts/CIDRs instead of process-wide bypasses.`).string(`authorizationCapability`,`Base64url-encoded JSON capability for request-scoped authorization. Payload fields mirror authorization and must include requestId.`).number(`timeoutMs`,`Request timeout in milliseconds`,{default:3e4,minimum:1e3,maximum:12e4}).boolean(`dryRun`,`Preview the request without sending it`,{default:!0}).requiredOpenWorld(`requestId`)),e(`network_intercept`,e=>e.desc(`Manage network interception rules.`).enum(`action`,[`add`,`list`,`disable`],`Intercept operation`).string(`urlPattern`,`URL pattern to match`).enum(`urlPatternType`,[`glob`,`regex`],`How to interpret urlPattern`,{default:`glob`}).enum(`interceptAction`,[`continue`,`abort`,`fulfill`],`Match action`,{default:`fulfill`}).enum(`stage`,[`Request`,`Response`],`Intercept stage. Response (default) intercepts after server responds.`,{default:`Response`}).number(`responseCode`,`HTTP status code to return`,{default:200,minimum:100,maximum:599}).object(`responseHeaders`,{additionalProperties:{type:`string`}},`Custom response headers as key-value pairs.`).string(`responseBody`,`Custom response body string.`).array(`rules`,{type:`object`,properties:{urlPattern:{type:`string`},urlPatternType:{type:`string`,enum:[`glob`,`regex`]},interceptAction:{type:`string`,enum:[`continue`,`abort`,`fulfill`]},stage:{type:`string`,enum:[`Request`,`Response`]},responseCode:{type:`number`},responseHeaders:{type:`object`,additionalProperties:{type:`string`}},responseBody:{type:`string`}},required:[`urlPattern`]},`Rule objects to add`).string(`ruleId`,`Rule ID to remove`).boolean(`all`,`Remove all rules`,{default:!1}).required(`action`)),e(`network_tls_fingerprint`,e=>e.desc(`Compute TLS/HTTP fingerprint hashes for bot detection.`).enum(`mode`,[`analyze_request`,`compute_tls`,`compute_http`],`Fingerprint mode`).string(`requestId`,`Request ID to analyze`).array(`tlsVersions`,{type:`string`},`TLS version codes in order`).array(`ciphers`,{type:`string`},`Cipher suite codes in order`).array(`extensions`,{type:`string`},`Extension type codes in order`).array(`signatureAlgorithms`,{type:`string`},`Signature algorithm codes in order`).enum(`protocol`,[`tls`,`quic`,`dtls`],`Transport protocol type`,{default:`tls`}).boolean(`sni`,`Whether SNI (Server Name Indication) extension is present`,{default:!0}).string(`alpn`,`ALPN value`).array(`httpHeaders`,{type:`string`},`HTTP header names in order`).string(`userAgent`,`User-Agent value`).string(`httpMethod`,`HTTP method`,{default:`GET`}).string(`httpVersion`,`HTTP version`,{default:`1.1`}).string(`cookieHeader`,`Cookie header value`).string(`acceptLanguage`,`Accept-Language header value`).boolean(`includeAnalysis`,`Include detailed fingerprint breakdown`,{default:!0}).required(`mode`)),e(`network_bot_detect_analyze`,e=>e.desc(`Analyze captured requests for bot-detection signals.`).number(`limit`,`Maximum requests to analyze`,{default:50,minimum:1,maximum:500}).boolean(`includeDetails`,`Include per-request analysis details`,{default:!1}).query())],r=[e(`network_enable`,e=>e.desc(`Enable network request monitoring.`).boolean(`enableExceptions`,`Also capture uncaught exceptions`,{default:!0})),e(`network_disable`,e=>e.desc(`Disable network request monitoring`).destructive()),e(`network_get_status`,e=>e.desc(`Get network monitoring status.`).query()),e(`network_monitor`,e=>e.desc(`Manage network request monitoring.`).enum(`action`,[`enable`,`disable`,`status`],`Action to perform`).boolean(`enableExceptions`,`Only for enable action: Also capture uncaught exceptions`,{default:!0}).required(`action`)),e(`network_get_requests`,e=>e.desc(`Get captured network requests.`).string(`url`,`Filter by URL substring`).string(`urlRegex`,`Filter by URL regex pattern`).string(`method`,`Filter by HTTP method (GET, POST, PUT, DELETE)`).number(`sinceTimestamp`,`Only return requests after this epoch timestamp (milliseconds). Useful for incremental polling.`).string(`sinceRequestId`,`Only return requests after this requestId (exclusive). Useful for incremental retrieval.`).number(`tail`,`Return the last N requests after filtering`).number(`limit`,`Maximum number of results per page`,{default:100,minimum:1,maximum:1e3}).number(`offset`,`Skip results for pagination`,{default:0,minimum:0}).boolean(`autoEnable`,`Auto-enable network monitoring when currently disabled`,{default:!0}).boolean(`enableExceptions`,`When autoEnable=true, also enable uncaught exception monitoring`,{default:!0}).array(`fields`,{type:`string`},`Only include these fields per request (e.g. ["url","method","status"]). Reduces response size drastically.`).boolean(`deduplicateUrls`,`Deduplicate URLs by stripping query params and normalizing path segments (UUIDs/IDs → {id}). Returns unique endpoint patterns with counts instead of individual requests.`,{default:!1})),e(`network_get_response_body`,e=>e.desc(`Get the response body for a captured request.`).string(`requestId`,`Request ID (from network_get_requests)`).number(`maxSize`,`Maximum response size in bytes`,{default:1e5,minimum:1024,maximum:2e7}).boolean(`returnSummary`,`Return only size and preview instead of full body`,{default:!1}).number(`retries`,`Retry count when response body is not yet available`,{default:3,minimum:0,maximum:10}).number(`retryIntervalMs`,`Retry interval in milliseconds`,{default:500,minimum:100,maximum:1e4}).boolean(`autoEnable`,`Auto-enable network monitoring when currently disabled`,{default:!1}).boolean(`enableExceptions`,`When autoEnable=true, also enable uncaught exception monitoring`,{default:!0}).required(`requestId`)),e(`network_get_stats`,e=>e.desc(`Get network statistics.`).query()),e(`performance_get_metrics`,e=>e.desc(`Get page performance metrics.`).boolean(`includeTimeline`,`Include detailed timeline events`,{default:!1}).query()),e(`performance_coverage`,e=>e.desc(`Start or stop code coverage recording.`).enum(`action`,[`start`,`stop`],`Coverage action`).required(`action`)),e(`performance_take_heap_snapshot`,e=>e.desc(`Take a V8 heap memory snapshot`)),e(`performance_trace`,e=>e.desc(`Start or stop a Chrome performance trace.`).enum(`action`,[`start`,`stop`],`Trace action`).array(`categories`,{type:`string`},`Trace categories to capture`).boolean(`screenshots`,`Capture screenshots during tracing`,{default:!1}).string(`artifactPath`,`Custom output path`).required(`action`)),e(`profiler_cpu`,e=>e.desc(`Start or stop CPU profiling.`).enum(`action`,[`start`,`stop`],`Profiler action`).string(`artifactPath`,`Custom output path`).required(`action`)),e(`profiler_heap_sampling`,e=>e.desc(`Start or stop heap allocation sampling.`).enum(`action`,[`start`,`stop`],`Sampling action`).number(`samplingInterval`,`Sampling interval in bytes`,{default:32768,minimum:256,maximum:1048576}).string(`artifactPath`,`Custom output path`).number(`topN`,`Number of top allocators to return`,{default:20,minimum:1,maximum:100}).required(`action`))],i=[e(`console_get_exceptions`,e=>e.desc(`Get captured uncaught exceptions from the page`).string(`url`,`Filter by URL substring`).number(`limit`,`Maximum number of exceptions to return`,{default:50,minimum:1,maximum:1e3}).readOnly()),e(`console_inject`,e=>e.desc(`Inject an in-page script, XHR, fetch, or function monitor.`).enum(`type`,[`script`,`xhr`,`fetch`,`function`],`Injection type`).string(`functionName`,`Global function path to trace`).boolean(`persistent`,`Keep the injection across page navigations`,{default:!1}).required(`type`).openWorld()),e(`console_inject_fetch_interceptor`,e=>e.desc(`Inject a fetch interceptor.`).boolean(`persistent`,`Keep the injection across page navigations`,{default:!1}).openWorld()),e(`console_inject_xhr_interceptor`,e=>e.desc(`Inject an XMLHttpRequest interceptor.`).boolean(`persistent`,`Keep the injection across page navigations`,{default:!1}).openWorld()),e(`console_buffers`,e=>e.desc(`Manage injected interceptor state.`).enum(`action`,[`clear`,`reset`],`Buffer action: clear buffers or reset interceptors`).required(`action`))],a=[e(`network_traceroute`,e=>e.desc(`Run an ICMP traceroute.`).string(`target`,`Target hostname or IP address to trace route to`).number(`maxHops`,`Maximum number of hops`,{default:30,minimum:1,maximum:64}).number(`timeout`,`Per-hop timeout in milliseconds`,{default:5e3,minimum:100,maximum:3e4}).number(`packetSize`,`ICMP echo request payload size in bytes`,{default:32,minimum:8,maximum:65500}).required(`target`).query()),e(`network_icmp_probe`,e=>e.desc(`Run an ICMP echo probe.`).string(`target`,`Target hostname or IP address to probe`).number(`ttl`,`Time-to-live value`,{default:128,minimum:1,maximum:255}).number(`packetSize`,`ICMP echo request payload size in bytes`,{default:32,minimum:8,maximum:65500}).number(`timeout`,`Timeout in milliseconds`,{default:5e3,minimum:100,maximum:3e4}).required(`target`).query())],o=[e(`http_request_build`,e=>e.desc(`Build a raw HTTP/1.x request payload.`).string(`method`,`HTTP method token`).string(`target`,`Request target, such as /path, *, or an absolute-form URL`).string(`host`,`Optional Host header value to inject when addHostHeader is enabled`).object(`headers`,{additionalProperties:{type:`string`}},`Optional HTTP headers to include in the request`).string(`body`,`Optional UTF-8 request body`).enum(`httpVersion`,[`1.0`,`1.1`],`HTTP protocol version to emit`,{default:`1.1`}).boolean(`addHostHeader`,`Auto-add the Host header when host is provided`,{default:!0}).boolean(`addContentLength`,`Auto-add Content-Length when a body is present and Transfer-Encoding is absent`,{default:!0}).boolean(`addConnectionClose`,`Auto-add Connection: close when absent`,{default:!0}).requiredOpenWorld(`method`,`target`)),e(`http_plain_request`,e=>e.desc(`Send a raw HTTP request over plain TCP.`).string(`host`,`Target hostname or IP literal`).number(`port`,`TCP port to connect to. Default: 80`,{default:80,minimum:1,maximum:65535}).string(`requestText`,`Raw HTTP request text to send as UTF-8 bytes`).object(`authorization`,t,`Request-scoped authorization policy for private-network or insecure-HTTP targets. Use exact hosts/CIDRs instead of process-wide bypasses.`).number(`timeoutMs`,`Socket timeout in milliseconds`,{default:3e4,minimum:1e3,maximum:12e4}).number(`maxResponseBytes`,`Maximum number of raw response bytes to capture before truncating the exchange`,{default:512e3,minimum:1024,maximum:10485760}).requiredOpenWorld(`host`,`requestText`)),e(`http2_probe`,e=>e.desc(`Probe an HTTP/2 endpoint.`).string(`url`,`Absolute http:// or https:// URL to probe`).string(`method`,`HTTP method token to send. Default: GET`).object(`headers`,{additionalProperties:{type:`string`}},`Optional request headers to include. Header names are normalized to lowercase for HTTP/2.`).string(`body`,`Optional UTF-8 request body to send with the probe`).array(`alpnProtocols`,{type:`string`},`ALPN protocols to offer`).object(`authorization`,t,`Request-scoped authorization policy for private-network or insecure-HTTP targets. Use exact hosts/CIDRs instead of process-wide bypasses.`).number(`timeoutMs`,`Probe timeout in milliseconds`,{default:3e4,minimum:1e3,maximum:12e4}).number(`maxBodyBytes`,`Maximum number of response body bytes to capture for the snippet before truncating`,{default:32768,minimum:1024,maximum:1048576}).requiredOpenWorld(`url`)),e(`http2_frame_build`,e=>e.desc(`Build a raw HTTP/2 frame.`).string(`frameType`,`HTTP/2 frame type: DATA, SETTINGS, PING, WINDOW_UPDATE, RST_STREAM, GOAWAY, or RAW`).number(`streamId`,`Stream identifier (0 for connection-level frames). Default: 0`,{default:0,minimum:0,maximum:2147483647}).number(`flags`,`Raw flags byte (0-255). Overrides type-specific defaults when set.`,{minimum:0,maximum:255}).number(`frameTypeCode`,`Explicit frame type code for RAW frames (0-255). Required when frameType is RAW.`,{minimum:0,maximum:255}).string(`payloadHex`,`Frame payload as a hex string. Mutually exclusive with payloadText.`).string(`payloadText`,`Frame payload as a text string. Mutually exclusive with payloadHex.`).string(`payloadEncoding`,`Encoding for payloadText: utf8 or ascii. Default: utf8`).array(`settings`,{type:`object`,properties:{id:{type:`number`},value:{type:`number`}},required:[`id`,`value`]},`Array of {id, value} entries for SETTINGS frames`).boolean(`ack`,`Set the ACK flag on SETTINGS or PING frames`).string(`pingOpaqueDataHex`,`Exactly 8 bytes of opaque data for PING frames (hex string)`).number(`windowSizeIncrement`,`Window size increment for WINDOW_UPDATE frames (1 to 2^31-1)`).number(`errorCode`,`Error code for RST_STREAM or GOAWAY frames (0 to 2^32-1)`).number(`lastStreamId`,`Last stream ID for GOAWAY frames (0 to 2^31-1)`).string(`debugDataText`,`Optional debug data for GOAWAY frames`).string(`debugDataEncoding`,`Encoding for debugDataText: utf8 or ascii. Default: utf8`).requiredOpenWorld(`frameType`)),e(`dns_resolve`,e=>e.desc(`Resolve a hostname to DNS records using the system resolver.`).string(`hostname`,`Hostname to resolve (e.g. google.com)`).string(`rrType`,`DNS record type: A, AAAA, MX, TXT, NS, CNAME, SOA, PTR, SRV, or ANY`,{default:`A`}).requiredOpenWorld(`hostname`)),e(`dns_reverse`,e=>e.desc(`Reverse DNS lookup — find hostnames for an IP address.`).string(`ip`,`IP address to reverse lookup (e.g. 8.8.8.8)`).requiredOpenWorld(`ip`)),e(`dns_probe`,e=>e.desc(`Run a DNS query and return structured status instead of throwing.`).string(`hostname`,`Hostname to query`).string(`rrType`,`DNS record type: A, AAAA, MX, TXT, NS, CNAME, SOA, PTR, SRV, or ANY`,{default:`A`}).requiredOpenWorld(`hostname`)),e(`dns_cname_chain`,e=>e.desc(`Trace the full CNAME chain for a hostname.`).string(`hostname`,`Hostname to trace CNAME chain for`).number(`maxDepth`,`Maximum chain depth to follow. Default: 10`,{default:10,minimum:1,maximum:30}).requiredOpenWorld(`hostname`)),e(`dns_bulk_resolve`,e=>e.desc(`Resolve many hostnames concurrently with per-host status.`).array(`hostnames`,{type:`string`},`List of hostnames to resolve (max 1000)`).string(`rrType`,`DNS record type: A, AAAA, MX, TXT, NS, CNAME, SOA, PTR, SRV, or ANY`,{default:`A`}).number(`concurrency`,`Maximum number of concurrent DNS queries. Default: 10`,{default:10,minimum:1,maximum:50}).requiredOpenWorld(`hostnames`)),e(`network_rtt_measure`,e=>e.desc(`Measure round-trip time to a target URL.`).string(`url`,`Target URL to measure RTT to`).string(`probeType`,`Probe type: tcp, tls, or http. Default: tcp`,{default:`tcp`}).number(`iterations`,`Number of probe iterations (1-50). Default: 5`,{default:5,minimum:1,maximum:50}).number(`timeoutMs`,`Per-probe timeout in milliseconds (100-30000). Default: 5000`,{default:5e3,minimum:100,maximum:3e4}).object(`authorization`,{additionalProperties:{type:`string`}},`Authorization policy for network access`).requiredOpenWorld(`url`)),e(`network_latency_stats`,e=>e.desc(`Measure repeated latency and compute percentile stats.`).string(`url`,`Target URL to measure`).enum(`probeType`,[`tcp`,`tls`,`http`],`Probe type`,{default:`http`}).number(`iterations`,`Number of probes`,{default:20,minimum:5,maximum:100}).number(`concurrency`,`Max concurrent probes`,{default:5,minimum:1,maximum:20}).number(`timeoutMs`,`Per-probe timeout ms`,{default:5e3,minimum:100,maximum:3e4}).object(`authorization`,{additionalProperties:{type:`string`}},`Authorization policy for network access`).requiredOpenWorld(`url`))],s=[...r,...i,...o,...n,...a];export{s as t};
@@ -0,0 +1,2 @@
1
+ import{a as e,n as t,r as n}from"./parse-args-Bw413PlW.mjs";import"./definitions-CB6vmOer.mjs";import{homedir as r,tmpdir as i}from"node:os";import{isAbsolute as a,resolve as o}from"node:path";import{readFile as s,realpath as c}from"node:fs/promises";function l(e,t,n){let r=[],i=0,a=0;for(;i<e.length;){let o=d(e,i);if(o.error)return{fields:r,bytesConsumed:i,error:o.error};let s=o.value;i=o.offset;let c=Number(s>>3n),l=Number(s&7n);if(c<=0)return{fields:r,bytesConsumed:i,error:`Invalid field number ${c} at offset ${i}`};if(l===0){let t=d(e,i);if(t.error)return{fields:r,bytesConsumed:i,error:t.error};i=t.offset,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:p(t.value)})}else if(l===1){if(i+8>e.length)return{fields:r,bytesConsumed:i,error:`Unexpected EOF for fixed64 at offset ${i}`};let t=e.subarray(i,i+8),n=t.readBigUInt64LE(0);i+=8,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:{uint64:p(n),hex:t.toString(`hex`)}})}else if(l===2){let o=d(e,i);if(o.error)return{fields:r,bytesConsumed:i,error:o.error};i=o.offset;let s=o.value;if(s>BigInt(2**53-1))return{fields:r,bytesConsumed:i,error:`Length-delimited field is too large at offset ${i}`};let p=Number(s);if(p<0||i+p>e.length)return{fields:r,bytesConsumed:i,error:`Invalid length-delimited field length=${p} at offset ${i}`};let m=e.subarray(i,i+p);i+=p,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:u(m,t,n)})}else if(l===5){if(i+4>e.length)return{fields:r,bytesConsumed:i,error:`Unexpected EOF for fixed32 at offset ${i}`};let t=e.subarray(i,i+4),n=t.readUInt32LE(0);i+=4,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:{uint32:n,hex:t.toString(`hex`)}})}else return{fields:r,bytesConsumed:i,error:`Unsupported wire type ${l} at offset ${i}`};a+=1}return{fields:r,bytesConsumed:i}}function u(e,t,n){if(e.length===0)return{kind:`empty`,length:0};if(t<n){let r=l(e,t+1,n);if(!r.error&&r.bytesConsumed===e.length&&r.fields.length>0)return{kind:`message`,fields:r.fields}}let r=m(e);return r!==null&&h(r)?{kind:`string`,value:r}:{kind:`bytes`,length:e.length,hex:e.toString(`hex`),base64:e.toString(`base64`)}}function d(e,t){let n=0n,r=0n,i=t;for(let t=0;t<10;t+=1){let t=e[i];if(t===void 0)return{error:`Unexpected EOF while parsing varint at offset ${i}`};let a=BigInt(t);if(n|=(a&127n)<<r,i+=1,(a&128n)==0n)return{value:n,offset:i};r+=7n}return{error:`Varint exceeds 10 bytes at offset ${t}`}}function f(e){return e===0?`varint`:e===1?`fixed64`:e===2?`length-delimited`:e===5?`fixed32`:`unknown`}function p(e){let t=BigInt(2**53-1),n=BigInt(-(2**53-1));return e<=t&&e>=n?Number(e):e.toString()}function m(e){let t=e.toString(`utf8`);return(t.match(/\uFFFD/g)??[]).length>0?null:t}function h(e){if(e.length===0)return!0;let t=0;for(let n of e){let e=n.charCodeAt(0);(e>=32&&e<=126||e===9||e===10||e===13)&&(t+=1)}return t/e.length>=.85}function g(e){let t=_(e,0,0);if(t.offset!==e.length)throw Error(`MessagePack decode ended early: consumed ${t.offset} of ${e.length} bytes`);return t.value}function _(e,t,n){if(n>64)throw Error(`MessagePack decode depth exceeds safety limit`);let r=e[t];if(r===void 0)throw Error(`Unexpected EOF at offset ${t}`);let i=t+1;if(r<=127)return{value:r,offset:i};if(r>=224)return{value:r-256,offset:i};if(r>=160&&r<=191){let t=r&31;return x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r>=144&&r<=159){let t=r&15;return v(e,i,t,n+1)}if(r>=128&&r<=143){let t=r&15;return y(e,i,t,n+1)}if(r===192)return{value:null,offset:i};if(r===194)return{value:!1,offset:i};if(r===195)return{value:!0,offset:i};if(r===204)return x(e,i,1),{value:e.readUInt8(i),offset:i+1};if(r===205)return x(e,i,2),{value:e.readUInt16BE(i),offset:i+2};if(r===206)return x(e,i,4),{value:e.readUInt32BE(i),offset:i+4};if(r===207)return x(e,i,8),{value:p(e.readBigUInt64BE(i)),offset:i+8};if(r===208)return x(e,i,1),{value:e.readInt8(i),offset:i+1};if(r===209)return x(e,i,2),{value:e.readInt16BE(i),offset:i+2};if(r===210)return x(e,i,4),{value:e.readInt32BE(i),offset:i+4};if(r===211)return x(e,i,8),{value:p(e.readBigInt64BE(i)),offset:i+8};if(r===202)return x(e,i,4),{value:e.readFloatBE(i),offset:i+4};if(r===203)return x(e,i,8),{value:e.readDoubleBE(i),offset:i+8};if(r===217){x(e,i,1);let t=e.readUInt8(i);return i+=1,x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r===218){x(e,i,2);let t=e.readUInt16BE(i);return i+=2,x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r===219){x(e,i,4);let t=e.readUInt32BE(i);return i+=4,x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r===196){x(e,i,1);let t=e.readUInt8(i);i+=1,x(e,i,t);let n=e.subarray(i,i+t);return{value:{type:`bytes`,base64:n.toString(`base64`),hex:n.toString(`hex`)},offset:i+t}}if(r===197){x(e,i,2);let t=e.readUInt16BE(i);i+=2,x(e,i,t);let n=e.subarray(i,i+t);return{value:{type:`bytes`,base64:n.toString(`base64`),hex:n.toString(`hex`)},offset:i+t}}if(r===198){x(e,i,4);let t=e.readUInt32BE(i);i+=4,x(e,i,t);let n=e.subarray(i,i+t);return{value:{type:`bytes`,base64:n.toString(`base64`),hex:n.toString(`hex`)},offset:i+t}}if(r===220){x(e,i,2);let t=e.readUInt16BE(i);return i+=2,v(e,i,t,n+1)}if(r===221){x(e,i,4);let t=e.readUInt32BE(i);return i+=4,v(e,i,t,n+1)}if(r===222){x(e,i,2);let t=e.readUInt16BE(i);return i+=2,y(e,i,t,n+1)}if(r===223){x(e,i,4);let t=e.readUInt32BE(i);return i+=4,y(e,i,t,n+1)}if(r>=212&&r<=216){let t={212:1,213:2,214:4,215:8,216:16}[r];x(e,i,1+t);let n=e.readInt8(i),a=e.subarray(i+1,i+1+t);return{value:{type:`ext`,extType:n,base64:a.toString(`base64`),hex:a.toString(`hex`)},offset:i+1+t}}if(r===199||r===200||r===201){let t=r===199?1:r===200?2:4;x(e,i,t);let n=t===1?e.readUInt8(i):t===2?e.readUInt16BE(i):e.readUInt32BE(i);i+=t,x(e,i,1+n);let a=e.readInt8(i),o=e.subarray(i+1,i+1+n);return{value:{type:`ext`,extType:a,base64:o.toString(`base64`),hex:o.toString(`hex`)},offset:i+1+n}}throw Error(`Unsupported MessagePack prefix 0x${r.toString(16)} at offset ${t}`)}function v(e,t,n,r){let i=t,a=[];for(let t=0;t<n;t+=1){let t=_(e,i,r);a.push(t.value),i=t.offset}return{value:a,offset:i}}function y(e,t,n,r){let i=t,a={};for(let t=0;t<n;t+=1){let t=_(e,i,r);i=t.offset;let n=_(e,i,r);i=n.offset;let o=b(t.value);a[o]=n.value}return{value:a,offset:i}}function b(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`bigint`)return e.toString();if(e===null)return`null`;try{return JSON.stringify(e)}catch{return String(e)}}function x(e,t,n){if(t<0||n<0||t+n>e.length)throw Error(`Unexpected EOF while reading ${n} bytes at offset ${t}`)}const S=[{format:`png`,bytes:[137,80,78,71]},{format:`jpeg`,bytes:[255,216,255]},{format:`gif`,bytes:[71,73,70]},{format:`wasm`,bytes:[0,97,115,109]},{format:`zip/apk`,bytes:[80,75,3,4]},{format:`pdf`,bytes:[37,80,68,70]}],C=new Set([`base64`,`hex`,`file`,`raw`]),w=new Set([`base64`,`hex`,`raw`,`file`]),T=new Set([`base64`,`hex`,`url`,`protobuf`,`msgpack`]),E=new Set([`hex`,`utf8`,`json`]),D=new Set([`utf8`,`hex`,`json`]),O=new Set([`base64`,`hex`,`url`]);function k(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function A(e,t){return k({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}function j(e){let t=e.trim().replace(/^0x/i,``).replace(/[\s:,-]/g,``);if(t.length===0)return Buffer.alloc(0);if(t.length%2!=0||!/^[0-9a-fA-F]+$/.test(t))throw Error(`Invalid hex string`);return Buffer.from(t,`hex`)}function M(e){let t=e.trim().replace(/\s+/g,``);if(t.length===0)return Buffer.alloc(0);if(!F(t))throw Error(`Invalid base64 string`);return Buffer.from(t,`base64`)}function N(e){let t=e.trim();return t.length===0?Buffer.alloc(0):P(t)?j(t):F(t)?M(t):Buffer.from(t,`utf8`)}function P(e){let t=e.trim().replace(/^0x/i,``).replace(/[\s:,-]/g,``);return t.length>0&&t.length%2==0&&/^[0-9a-fA-F]+$/.test(t)}function F(e){let t=e.trim().replace(/\s+/g,``);if(t.length===0||t.length%4!=0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))return!1;try{let e=Buffer.from(t,`base64`);return t.replace(/=+$/,``)===e.toString(`base64`).replace(/=+$/,``)}catch{return!1}}function I(e){return/%[0-9a-fA-F]{2}/.test(e)||/\+/.test(e)}function L(e){return decodeURIComponent(e.replace(/\+/g,`%20`))}function R(e){let t=``;for(let n of e.values())t+=n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===45||n===46||n===95||n===126?String.fromCharCode(n):`%${n.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function z(e){let t=e.toString(`utf8`);return(t.match(/\uFFFD/g)??[]).length>0?null:t}function B(e){try{return JSON.parse(e)}catch{return null}}function V(e,t){return Array.from(e.subarray(0,t).values()).map(e=>e.toString(16).padStart(2,`0`)).join(` `)}function H(e,t=16){let n=[];for(let r=0;r<e.length;r+=t){let i=e.subarray(r,r+t),a=Array.from(i.values()).map(e=>e.toString(16).padStart(2,`0`)).join(` `),o=Array.from(i.values()).map(e=>e>=32&&e<=126?String.fromCharCode(e):`.`).join(``);n.push(`${r.toString(16).padStart(8,`0`)} ${a.padEnd(47)} |${o}|`)}return n.join(`
2
+ `)}function U(e){let{encoding:t,outputFormat:n,buffer:r,jsonValue:i}=e;if(n===`hex`)return k({success:!0,encoding:t,outputFormat:n,byteLength:r.length,result:r.toString(`hex`),hexDump:H(r)});if(n===`utf8`)return k({success:!0,encoding:t,outputFormat:n,byteLength:r.length,result:r.toString(`utf8`)});let a=z(r),o=a===null?null:B(a);return k({success:!0,encoding:t,outputFormat:n,byteLength:r.length,result:i??{parsedJson:o,utf8:a,hex:r.toString(`hex`)}})}async function W(e){let{source:t,data:n,filePath:l,maxBytes:u}=e;if(t===`file`){if(!l)throw Error(`filePath is required when source=file`);let e=await c(o(l));if(!(await Promise.all([i(),r(),process.cwd()].map(async e=>{let t=a(e)?e:o(e);try{return await c(t)}catch{return t}}))).some(t=>e.startsWith(t)))throw Error(`File access denied: path "${l}" is outside allowed directories`);let t=await s(e);return typeof u==`number`?t.subarray(0,u):t}if(t===`base64`){if(!n)throw Error(`data is required for base64 source`);return M(n)}if(t===`hex`){if(!n)throw Error(`data is required for hex source`);return j(n)}return Buffer.from(n??``,`utf8`)}async function G(e,t){try{let n=await(await e.getActivePage()).evaluate(e=>{let t=t=>{if(!t||typeof t!=`object`)return null;let n=t;if(n.requestId!==e)return null;if(typeof n.responseBody==`string`)return{body:n.responseBody,base64Encoded:!!n.base64Encoded};if(typeof n.body==`string`)return{body:n.body,base64Encoded:!!n.base64Encoded};let r=n.response;if(r&&typeof r==`object`){let e=r;if(typeof e.body==`string`)return{body:e.body,base64Encoded:!!e.base64Encoded}}return null},n=e=>{if(!Array.isArray(e))return null;for(let n of e){let e=t(n);if(e)return e}return null},r=n(window.__capturedAPIs);if(r)return r;try{let e=window.localStorage.getItem(`__capturedAPIs`);return e?n(JSON.parse(e)):null}catch{return null}},t);if(!n||typeof n!=`object`)return null;let r=n;if(typeof r.body!=`string`)return null;if(r.base64Encoded)return Buffer.from(r.body,`base64`);let i=r.body.trim();return F(i)?Buffer.from(i,`base64`):Buffer.from(r.body,`utf8`)}catch{return null}}function K(e){let t=[];for(let n of S){if(e.length<n.bytes.length)continue;let r=!0;for(let t=0;t<n.bytes.length;t+=1)if(e[t]!==n.bytes[t]){r=!1;break}r&&t.push(n.format)}return t}function q(e){let t=e[0];if(t===void 0)return[];let n=new Set;return[8,16,24,32].includes(t)&&n.add(`protobuf`),(t>=128&&t<=143||t>=144&&t<=159||t>=160&&t<=191)&&n.add(`messagepack`),(t>=160&&t<=191||t>=128&&t<=159)&&n.add(`cbor`),Array.from(n)}function J(e,t,n){let r=new Set;if((e===`base64`||t&&F(t.trim()))&&r.add(`base64`),(e===`hex`||t&&P(t))&&r.add(`hex`),t&&I(t)&&r.add(`url-encoded`),n.length>=3){let[e,t,i]=n;e===239&&t===187&&i===191&&r.add(`utf8-bom`)}return Array.from(r)}function Y(e){if(e.length===0)return 0;let t=Array.from({length:256},()=>0);for(let n of e.values())t[n]+=1;let n=0;for(let r of t){if(r===0)continue;let t=r/e.length;n-=t*Math.log2(t)}return Number(n.toFixed(6))}function X(e){if(e.length===0)return[];let t=Array.from({length:256},()=>0);for(let n of e.values())t[n]+=1;let n=[];for(let r=0;r<256;r+=1){let i=t[r];i!==0&&n.push({byte:`0x${r.toString(16).padStart(2,`0`)}`,count:i,ratio:Number((i/e.length).toFixed(6))})}return n.sort((e,t)=>t.count-e.count),n}function Z(e,t){if(e.length===0)return[];let n=[],r=0;for(let i=0;i<e.length;i+=t){let a=Math.min(i+t,e.length);n.push({index:r,start:i,end:a,entropy:Y(e.subarray(i,a))}),r+=1}return n}function Q(e,t){let n=$(t);return e<3.8&&n>.85?`plaintext`:e<5.8?`encoded`:e<7.2?`compressed`:e<7.8?`encrypted`:`random`}function $(e){if(e.length===0)return 1;let t=0;for(let n of e.values())(n>=32&&n<=126||n===9||n===10||n===13)&&(t+=1);return t/e.length}var ee=class{collector;responseBodyResolver;constructor(e,t){this.collector=e,this.responseBodyResolver=t}async resolveCapturedRequestBody(e){if(this.responseBodyResolver)try{let t=await this.responseBodyResolver(e);if(t&&typeof t.body==`string`){if(t.base64Encoded)return Buffer.from(t.body,`base64`);let e=t.body.trim();return F(e)?Buffer.from(e,`base64`):Buffer.from(t.body,`utf8`)}}catch{}return G(this.collector,e)}async handleBinaryDetectFormat(n){try{let r=t(n,`source`,C,`raw`),i=e(n,`data`),a=e(n,`filePath`),o=e(n,`requestId`),s=null,c=!1;if(r===`raw`&&o&&(s=await this.resolveCapturedRequestBody(o),c=s!==null),!s){if(r!==`file`&&!i)throw Error(`data is required for non-file source when requestId payload is unavailable`);s=await W({source:r,data:i,filePath:a,maxBytes:r===`file`?512:void 0})}let l=Y(s);return k({success:!0,source:r,requestId:o??null,requestBodyUsed:c,byteLength:s.length,previewHex:V(s,64),magicFormats:K(s),structuredFormats:q(s),encodingSignals:J(r,i,s),entropy:l,assessment:Q(l,s),topBytes:X(s).slice(0,8)})}catch(e){return A(`binary_detect_format`,e)}}async handleBinaryDecode(n){try{let r=e(n,`data`,``),i=t(n,`encoding`,T),a=t(n,`outputFormat`,E,`hex`);if(!r)throw Error(`data is required`);if(!i)throw Error(`encoding is required`);if(i===`url`){let e=L(r);if(a===`hex`){let t=Buffer.from(e,`utf8`);return k({success:!0,encoding:i,outputFormat:a,byteLength:t.length,result:t.toString(`hex`),hexDump:H(t)})}return k(a===`utf8`?{success:!0,encoding:i,outputFormat:a,result:e}:{success:!0,encoding:i,outputFormat:a,result:B(e)??{text:e}})}let o=i===`base64`?M(r):i===`hex`?j(r):N(r);if(i===`protobuf`){let e=l(o,0,5);return U({encoding:i,outputFormat:a,buffer:o,jsonValue:{fields:e.fields,bytesConsumed:e.bytesConsumed,error:e.error??null}})}return U(i===`msgpack`?{encoding:i,outputFormat:a,buffer:o,jsonValue:g(o)}:{encoding:i,outputFormat:a,buffer:o})}catch(e){return A(`binary_decode`,e)}}async handleBinaryEncode(n){try{let r=e(n,`data`,``),i=t(n,`inputFormat`,D,`utf8`),a=t(n,`outputEncoding`,O,`base64`);if(!r)throw Error(`data is required`);let o;if(i===`utf8`)o=Buffer.from(r,`utf8`);else if(i===`hex`)o=j(r);else{let e=JSON.parse(r);o=Buffer.from(JSON.stringify(e),`utf8`)}let s=a===`base64`?o.toString(`base64`):a===`hex`?o.toString(`hex`):R(o);return k({success:!0,inputFormat:i,outputEncoding:a,byteLength:o.length,output:s})}catch(e){return A(`binary_encode`,e)}}async handleBinaryEntropyAnalysis(r){try{let i=t(r,`source`,w,`raw`),a=e(r,`data`),o=e(r,`filePath`);if(i!==`file`&&!a)throw Error(`data is required for non-file source`);let s=n(r,`blockSize`,256),c=Math.max(16,Math.min(8192,Math.trunc(s||256))),l=await W({source:i,data:a,filePath:o}),u=Y(l);return k({success:!0,source:i,byteLength:l.length,blockSize:c,overallEntropy:u,blockEntropies:Z(l,c),byteFrequency:X(l).slice(0,20),assessment:Q(u,l)})}catch(e){return A(`binary_entropy_analysis`,e)}}async handleProtobufDecodeRaw(t){try{let r=e(t,`data`,``);if(!r)throw Error(`data is required`);let i=n(t,`maxDepth`,5),a=Math.max(1,Math.min(20,Math.trunc(i||5))),o=M(r),s=l(o,0,a);return k({success:s.error===void 0,byteLength:o.length,maxDepth:a,parsedBytes:s.bytesConsumed,fields:s.fields,error:s.error??null})}catch(e){return A(`protobuf_decode_raw`,e)}}};export{ee as EncodingToolHandlers};
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./PageController-Dfsm1_o7.mjs";import{n,t as r}from"./DOMInspector-C19J4zeq.mjs";import{t as i}from"./ScriptManager-LWGPTdvD.mjs";var a=e({ensureBrowserCore:()=>c});let o=null;async function s(){return o||=(await import(`./ConsoleMonitor-CxDJV15E.mjs`)).ConsoleMonitor,o}async function c(e){e.collector||(e.collector=new n(e.config.puppeteer),e.registerCaches()),e.pageController||=new t(e.collector),e.domInspector||=new r(e.collector),e.scriptManager||=new i(e.collector),e.consoleMonitor||=new(await(s()))(e.collector)}export{a as n,c as t};
@@ -0,0 +1 @@
1
+ var e=class{graph;constructor(e){this.graph=e}getGraph(){return this.graph}addNode(e,t,n){return this.graph.addNode(e,t,n)}addV8Object(e,t){let n=this.graph.addNode(`v8-heap-object`,e.name,{domain:`v8-inspector`,address:e.address,name:e.name});return t&&this.graph.addEdge(t,n.id,`heap-allocates`,{domain:`cross-domain`,relation:`script-allocates-heap-object`}),n}addNetworkRequest(e,t){let n=e.method?`${e.method} ${e.url}`:e.url,r=this.graph.addNode(`network-request`,n,{domain:`network`,requestId:e.requestId,url:e.url,method:e.method??`GET`}),i;return t&&(i=this.graph.getNode(t),this.graph.addEdge(t,r.id,`network-initiated-by`,{domain:`cross-domain`,relation:`heap-initiates-network`})),{node:r,initiatorNode:i}}addCanvasNode(e,t){let n=this.graph.addNode(`canvas-scene-node`,e.label,{domain:`canvas`,nodeId:e.nodeId,label:e.label});return t&&this.graph.addEdge(t,n.id,`canvas-rendered-by`,{domain:`cross-domain`,relation:`heap-creates-canvas-node`}),n}addSyscallEvent(e,t){let n=this.graph.addNode(`syscall-event`,e.syscallName,{domain:`syscall-hook`,pid:e.pid,tid:e.tid,syscallName:e.syscallName,timestamp:e.timestamp});return t&&this.graph.addEdge(t,n.id,`syscall-emitted-by`,{domain:`cross-domain`,relation:`js-triggers-syscall`}),n}addMojoMessage(e,t){let n=this.graph.addNode(`mojo-message`,`${e.interface}:${e.method}`,{domain:`mojo-ipc`,interface:e.interface,method:e.method,timestamp:e.timestamp});return t&&this.graph.addEdge(t,n.id,`mojo-routed-to`,{domain:`cross-domain`,relation:`cdp-routes-to-mojo`}),n}addBinarySymbol(e,t){let n=this.graph.addNode(`binary-symbol`,e.symbolName,{domain:`binary-instrument`,moduleName:e.moduleName,symbolName:e.symbolName,address:e.address});return t&&this.graph.addEdge(t,n.id,`binary-exports`,{domain:`cross-domain`,relation:`js-references-native-symbol`}),n}queryByHeapAddress(e){let t=this.graph.exportJson(),n=[];for(let r of t.nodes){let t=r.metadata.address;typeof t==`string`&&t.includes(e)&&n.push(r.id)}return this.collectConnectedNodes(n)}queryByNetworkUrl(e){return this.graph.queryByUrl(e)}exportGraph(){return this.graph.exportJson()}getStats(){let e=this.graph.exportJson(),t={};for(let n of e.nodes){let e=t[n.type]??0;t[n.type]=e+1}return{nodeCount:e.nodes.length,edgeCount:e.edges.length,nodesByType:t}}collectConnectedNodes(e){let t=new Map;for(let n of e){for(let e of this.graph.getEvidenceChain(n,`forward`))t.set(e.id,e);for(let e of this.graph.getEvidenceChain(n,`backward`))t.set(e.id,e)}return[...t.values()]}};export{e as CrossDomainEvidenceBridge};
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";import{_ as t,b as n,d as r,f as i,h as a,i as o,l as s,m as c,n as l,p as u,s as d,t as f,u as p,v as ee,y as m}from"./Win32API-eUCF57l_.mjs";import{_ as h,a as g,b as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,u as te,v as j,y as M}from"./DarwinAPI-ZfQdpLNI.mjs";import N from"node:fs";const P=new WeakMap;function F(e){let t=P.get(e);if(t===void 0)throw Error(`Invalid ProcessHandle — not a Win32 handle`);return t}function I(e){let t=0;return e&p.READONLY&&(t|=1),e&p.READWRITE&&(t|=3),e&p.WRITECOPY&&(t|=17),e&p.EXECUTE&&(t|=4),e&p.EXECUTE_READ&&(t|=5),e&p.EXECUTE_READWRITE&&(t|=7),e&p.EXECUTE_WRITECOPY&&(t|=21),e&p.GUARD&&(t|=8),t}function L(e){let t=(e&1)!=0,n=(e&2)!=0,r=(e&4)!=0,i=p.NOACCESS;return t&&n&&r?i=p.EXECUTE_READWRITE:t&&r?i=p.EXECUTE_READ:t&&n?i=p.READWRITE:r?i=p.EXECUTE:t&&(i=p.READONLY),e&8&&(i|=p.GUARD),i}function R(e){return e===s.COMMIT?`committed`:e===s.RESERVE?`reserved`:`free`}function z(e){return e===16777216?`image`:e===262144?`mapped`:e===131072?`private`:`unknown`}var B=class{platform=`win32`;async checkAvailability(){return m()?ee()?{available:!0,platform:`win32`}:{available:!1,reason:`koffi FFI library not available`,platform:`win32`}:{available:!1,reason:`Not running on Windows`,platform:`win32`}}openProcess(e,t){let r=n(e,t),i={pid:e,writeAccess:t};return P.set(i,r),i}closeProcess(e){f(F(e))}readMemory(e,t,n){let i=r(F(e),t,n);return{data:i,bytesRead:i.length}}writeMemory(e,n,r){return{bytesWritten:t(F(e),n,r)}}queryRegion(e,t){let{success:n,info:r}=a(F(e),t);if(!n||r.RegionSize===0n)return null;let i=I(r.Protect);return{baseAddress:r.BaseAddress,size:Number(r.RegionSize),protection:i,state:R(r.State),type:z(r.Type),isReadable:(i&1)!=0,isWritable:(i&2)!=0,isExecutable:(i&4)!=0}}changeProtection(e,t,n,r){let{success:i,oldProtect:a}=c(F(e),t,n,L(r));if(!i)throw Error(`VirtualProtectEx failed`);return{oldProtection:I(a)}}allocateMemory(e,t,n){let r=F(e),a=L(n),o=i(r,0n,t,s.COMMIT|s.RESERVE,a);if(!o)throw Error(`VirtualAllocEx failed`);return{address:o}}freeMemory(e,t,n){u(F(e),t,0,s.RELEASE)}enumerateModules(e){let t=F(e),{success:n,modules:r,count:i}=l(t);if(!n)throw Error(`EnumProcessModules failed`);let a=[];for(let e=0;e<i;e++){let n=r[e];if(!n)continue;let i=o(t,n),{success:s,info:c}=d(t,n);s&&c&&a.push({name:i,baseAddress:BigInt(c.lpBaseOfDll),size:c.SizeOfImage})}return a}};const V=new WeakMap;function H(e){let t=V.get(e);if(t===void 0)throw Error(`Invalid ProcessHandle — not a Darwin handle`);return t}function U(e){let t=0;return e&g.READ&&(t|=1),e&g.WRITE&&(t|=2),e&g.EXECUTE&&(t|=4),t}function W(e){let t=g.NONE;return e&1&&(t|=g.READ),e&2&&(t|=g.WRITE),e&4&&(t|=g.EXECUTE),t}function G(e){switch(e){case k.PRIVATE:case k.PRIVATE_ALIASED:case k.COW:return`private`;case k.SHARED:case k.TRUESHARED:case k.SHARED_ALIASED:return`mapped`;case k.EMPTY:return`unknown`;default:return`unknown`}}var K=class{platform=`darwin`;async checkAvailability(){if(!w())return{available:!1,reason:`Not running on macOS`,platform:`darwin`};if(!te())return{available:!1,reason:`koffi FFI library cannot load libSystem.B.dylib`,platform:`darwin`};try{let{kr:e}=_(O(),process.pid);if(e!==E.SUCCESS)return{available:!1,reason:`task_for_pid failed (${y(e)}). Run with sudo or add debugger entitlement.`,platform:`darwin`}}catch(e){let t=e instanceof Error?e.message:String(e);return{available:!1,reason:/signal|bus error|segfault|abort/i.test(t)?`Mach API call crashed (${t}). This may be caused by SIP (System Integrity Protection) on ARM64 macOS. Disable SIP or use a code-signed binary with com.apple.security.cs.debugger entitlement.`:`task_for_pid permission check failed: ${t}. Run with sudo or add debugger entitlement.`,platform:`darwin`}}return{available:!0,platform:`darwin`}}openProcess(e,t){let{kr:n,task:r}=_(O(),e);if(n!==E.SUCCESS)throw Error(`Failed to open process ${e}: ${y(n)} (${n}). `+(n===E.FAILURE?`Run with sudo or sign with com.apple.security.cs.debugger entitlement.`:n===E.INVALID_ARGUMENT?`Invalid PID — process may not exist.`:`Check macOS permissions.`));let i={pid:e,writeAccess:t};return V.set(i,{task:r}),i}closeProcess(e){let t=H(e);b(O(),t.task)}readMemory(e,t,n){let{kr:r,data:i,outsize:a}=h(H(e).task,t,n);if(r!==E.SUCCESS)throw Error(`mach_vm_read_overwrite failed at 0x${t.toString(16)}: ${y(r)} (${r})`);return{data:i,bytesRead:Number(a)}}writeMemory(e,t,n){let r=M(H(e).task,t,n);if(r!==E.SUCCESS)throw Error(`mach_vm_write failed at 0x${t.toString(16)}: ${y(r)} (${r})`);return{bytesWritten:n.length}}queryRegion(e,t){let{kr:n,address:r,size:i,info:a}=j(H(e).task,t);if(n!==E.SUCCESS)return null;let o=U(a.protection);return{baseAddress:r,size:Number(i),protection:o,state:`committed`,type:G(a.behavior),isReadable:(o&1)!=0,isWritable:(o&2)!=0,isExecutable:(o&4)!=0}}changeProtection(e,t,n,r){let i=H(e),a=W(r),{kr:o,info:s}=j(i.task,t),c=o===E.SUCCESS?U(s.protection):0;if((a&g.WRITE)!==0&&(a&g.EXECUTE)!==0){let e=x(i.task,t,BigInt(n),!0,g.ALL);if(e!==E.SUCCESS)throw Error(`mach_vm_protect (set_maximum) failed at 0x${t.toString(16)}: ${y(e)} (${e})`)}let l=x(i.task,t,BigInt(n),!1,a);if(l!==E.SUCCESS)throw Error(`mach_vm_protect failed at 0x${t.toString(16)}: ${y(l)} (${l})`);return{oldProtection:c}}allocateMemory(e,t,n){let r=H(e),{kr:i,address:a}=T(r.task,BigInt(t),C.ANYWHERE);if(i!==E.SUCCESS)throw Error(`mach_vm_allocate failed: ${y(i)} (${i})`);let o=W(n);if(o!==(g.READ|g.WRITE)){let e=x(r.task,a,BigInt(t),!1,o);if(e!==E.SUCCESS)throw S(r.task,a,BigInt(t)),Error(`mach_vm_protect after allocate failed: ${y(e)} (${e})`)}return{address:a}}freeMemory(e,t,n){let r=S(H(e).task,t,BigInt(n));if(r!==E.SUCCESS)throw Error(`mach_vm_deallocate failed at 0x${t.toString(16)}: ${y(r)} (${r})`)}enumerateModules(e){let t=H(e);return e.pid===process.pid?this.enumerateModulesSelf():this.enumerateModulesRemote(t.task)}enumerateModulesSelf(){let e=v(),t=[];for(let n=0;n<e;n++){let e=A(n),r=D(n);if(!e||r===0n)continue;let i=e.split(`/`).pop()??e;t.push({name:i,baseAddress:r,size:0})}return t}enumerateModulesRemote(e){let t=[],n=0n;for(let r=0;r<1e4;r++){let{kr:r,address:i,size:a,info:o}=j(e,n);if(r!==E.SUCCESS)break;let s=(o.protection&g.READ)!==0,c=(o.protection&g.EXECUTE)!==0;if(s&&c&&a>0n)try{let{kr:n,data:r}=h(e,i,4);if(n===E.SUCCESS&&r.length>=4){let e=r.readUInt32LE(0);(e===4277009103||e===4277009102)&&t.push({name:`module_0x${i.toString(16)}`,baseAddress:i,size:Number(a)})}}catch{}n=i+a}return t}};const q=/^([0-9a-f]+)-([0-9a-f]+)\s+([r-][w-][x-][ps])\s+([0-9a-f]+)\s+(\S+)\s+(\d+)\s*(.*)$/i;function J(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trimEnd().match(q);if(!e)continue;let r=e[3];t.push({start:BigInt(`0x${e[1]}`),end:BigInt(`0x${e[2]}`),permissions:{read:r[0]===`r`,write:r[1]===`w`,exec:r[2]===`x`,private:r[3]===`p`},offset:BigInt(`0x${e[4]}`),dev:e[5],inode:parseInt(e[6],10),pathname:e[7]?.trim()??``})}return t}function Y(e){return`${e.read?`r`:`-`}${e.write?`w`:`-`}${e.exec?`x`:`-`}`}function X(){return process.platform===`linux`}function Z(e){let t=0;return e.includes(`r`)&&(t|=1),e.includes(`w`)&&(t|=2),e.includes(`x`)&&(t|=4),t}function ne(e){let t=Z(e.perms);return{baseAddress:e.start,size:Number(e.end-e.start),protection:t,state:`committed`,type:e.path?`mapped`:`private`,isReadable:(t&1)!=0,isWritable:(t&2)!=0,isExecutable:(t&4)!=0}}function re(e){return Buffer.isBuffer(e)?e:e.startsWith(`0x`)&&e.length%2==0?Buffer.from(e.slice(2),`hex`):Buffer.from(e,`utf8`)}var ie=class{pid;platform=`linux`;constructor(e=process.pid){this.pid=e}isAvailable(){return X()}async read(e,t){let n=this.openProcess(this.pid,!1);return this.readMemory(n,e,t).data}async write(e,t){let n=this.openProcess(this.pid,!0);return this.writeMemory(n,e,t).bytesWritten===t.length}async scan(e){let t=re(e),n=this.openProcess(this.pid,!1),r=await this.queryRegions(),i=[];for(let e of r){if(!e.perms.includes(`r`))continue;let r=Number(e.end-e.start);if(!(r<=0))try{let a=this.readMemory(n,e.start,r).data,o=a.indexOf(t);for(;o>=0;)i.push(e.start+BigInt(o)),o=a.indexOf(t,o+1)}catch{continue}}return i}async queryRegions(){let e=`/proc/${this.pid}/maps`;return J(await N.promises.readFile(e,`utf8`)).map(e=>({start:e.start,end:e.end,perms:`${e.permissions.read?`r`:`-`}${e.permissions.write?`w`:`-`}${e.permissions.exec?`x`:`-`}${e.permissions.private?`p`:`s`}`,path:e.pathname||void 0}))}async checkAvailability(){return this.isAvailable()?{available:!0,platform:`linux`}:{available:!1,platform:`linux`,reason:`Not running on Linux`}}openProcess(e,t){return{pid:e,writeAccess:t}}closeProcess(e){}readMemory(e,t,n){let r=`/proc/${e.pid}/mem`,i=N.openSync(r,e.writeAccess?`r+`:`r`),a=Buffer.alloc(n);try{let e=N.readSync(i,a,0,n,Number(t));return{data:a.subarray(0,e),bytesRead:e}}finally{N.closeSync(i)}}writeMemory(e,t,n){let r=`/proc/${e.pid}/mem`,i=N.openSync(r,`r+`);try{return{bytesWritten:N.writeSync(i,n,0,n.length,Number(t))}}finally{N.closeSync(i)}}queryRegion(e,t){let n=`/proc/${e.pid}/maps`,r=J(N.readFileSync(n,`utf8`));for(let e of r)if(t>=e.start&&t<e.end)return ne({start:e.start,end:e.end,perms:`${e.permissions.read?`r`:`-`}${e.permissions.write?`w`:`-`}${e.permissions.exec?`x`:`-`}${e.permissions.private?`p`:`s`}`,path:e.pathname||void 0});return null}changeProtection(e,t,n,r){throw Error(`Linux memory protection changes are not supported by LinuxMemoryProviderImpl`)}allocateMemory(e,t,n){throw Error(`Linux remote memory allocation is not supported by LinuxMemoryProviderImpl`)}freeMemory(e,t,n){throw Error(`Linux remote memory free is not supported by LinuxMemoryProviderImpl`)}enumerateModules(e){let t=`/proc/${e.pid}/maps`,n=J(N.readFileSync(t,`utf8`)),r=new Map;for(let e of n){if(!e.pathname||e.pathname.startsWith(`[`))continue;let t=r.get(e.pathname);if(t){let n=Number(e.end-t.baseAddress);r.set(e.pathname,{...t,size:n>t.size?n:t.size});continue}r.set(e.pathname,{name:e.pathname.split(`/`).pop()??e.pathname,baseAddress:e.start,size:Number(e.end-e.start)})}return[...r.values()]}},ae=class extends ie{},oe=e({createPlatformProvider:()=>$});let Q=null;function $(){if(Q)return Q;switch(process.platform){case`win32`:Q=new B;break;case`darwin`:Q=new K;break;case`linux`:Q=new ae;break;default:throw Error(`Unsupported platform: ${process.platform}. Memory operations require Windows, macOS, or Linux.`)}if(!Q)throw Error(`Failed to create memory provider`);return Q}export{J as i,oe as n,Y as r,$ as t};
@@ -0,0 +1 @@
1
+ function e(e){if(typeof e!=`object`||!e)return null;let t=e.sessionId;return typeof t==`string`&&t.length>0?t:null}function t(e){let t=e.id?.();return typeof t==`string`&&t.length>0?t:null}async function n(t,n){let r=e(await t.send(`Target.attachToTarget`,{targetId:n,flatten:!0}));if(!r)throw Error(`Target.attachToTarget did not return sessionId for ${n}`);let i=t.connection?.();if(!i||typeof i.session!=`function`)throw Error(`CDP connection lookup unavailable for attached target ${n}`);let a=i.session(r);if(!a)throw Error(`CDP attached target session ${r} was not registered for ${n}`);return a}async function r(e,n){let r=t(n);if(!r)throw Error(`CDP attached target session id unavailable for detach`);await e.send(`Target.detachFromTarget`,{sessionId:r})}export{r as n,n as t};
@@ -0,0 +1 @@
1
+ function e(e){return`0x${e.toString(16).toUpperCase()}`}function t(e){return BigInt(e.startsWith(`0x`)||e.startsWith(`0X`)?e:`0x${e}`)}export{t as n,e as t};
@@ -0,0 +1,62 @@
1
+ import{_t as e,bt as t,vt as n,xt as r,yt as i}from"./constants-BYj8Xek8.mjs";import{t as a}from"./ToolError-DWU_z7gp.mjs";import{t as o}from"./PrerequisiteError-BjCQA-gK.mjs";import{a as s,i as c,r as l,t as u}from"./parse-args-Bw413PlW.mjs";import{s as d}from"./PageController-Dfsm1_o7.mjs";import{c as f}from"./ssrf-policy-CsIJGkpd.mjs";import"./definitions-CQd7yCQH.mjs";function p(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function m(e,t){let n={success:!1,error:h(e)};e instanceof a&&(n.code=e.code,e.toolName&&(n.toolName=e.toolName),e.details&&(n.details=e.details)),t&&(n.context=t);let r=e instanceof o;return{content:[{type:`text`,text:JSON.stringify(n,null,2)}],...r?{}:{isError:!0}}}function h(e){return e instanceof Error?e.message:String(e)}function g(e,t,n,r,i){let a=e[t],o=n;if(typeof a==`number`&&Number.isFinite(a))o=a;else if(typeof a==`string`){let e=Number(a);Number.isFinite(e)&&(o=e)}return o<r?r:o>i?i:Math.trunc(o)}function _(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=new Set([`__proto__`,`constructor`,`prototype`]),n=Object.create(null);for(let[r,i]of Object.entries(e))t.has(r)||(typeof i==`string`?n[r]=i:(typeof i==`number`||typeof i==`boolean`)&&(n[r]=String(i)));return n}function v(e){let t;try{t=new URL(e)}catch{return{error:`Invalid endpoint URL: ${e}`}}return t.protocol!==`http:`&&t.protocol!==`https:`?{error:`Unsupported endpoint protocol: ${t.protocol} — only http/https allowed`}:{parsedEndpoint:t}}async function y(e){let t=v(e);return`error`in t?t.error:await f(t.parsedEndpoint.toString())?`Blocked: endpoint "${e}" resolves to a private/reserved address`:null}async function b(e,t){let n=v(e);if(`error`in n)return n.error;if(!await f(n.parsedEndpoint.toString()))return null;if(typeof t==`string`&&t.length>0)try{if(new URL(t).origin===n.parsedEndpoint.origin)return null}catch{}return`Blocked: endpoint "${e}" resolves to a private/reserved address`}function x(e,t){return e.length<=t?{preview:e,truncated:!1,totalLength:e.length}:{preview:`${e.slice(0,t)}\n... (truncated)`,truncated:!0,totalLength:e.length}}function S(e,t){let n;if(typeof e==`string`)n=e;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}return x(n,t)}function ee(e){return e===`exact`||e===`contains`||e===`regex`?e:`contains`}function C(){return`script_rule_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function w(e){if(typeof e.isInterceptResolutionHandled!=`function`)return!1;try{return e.isInterceptResolutionHandled()}catch{return!1}}async function T(e){if(!w(e))try{await e.continue()}catch{}}function te(e,t){if(e.matchType===`exact`)return t===e.url;if(e.matchType===`contains`)return t.includes(e.url);try{return new RegExp(e.url).test(t)}catch{return!1}}function E(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r&&te(r,t))return r}return null}async function D(e,t){if(w(t))return;if(t.resourceType()!==`script`){await T(t);return}let n=E(e,t.url());if(!n){await T(t);return}n.hits+=1;try{await t.respond({status:200,contentType:`application/javascript; charset=utf-8`,headers:{"cache-control":`no-store`,"x-script-replaced-by":`script_replace_persist`},body:n.replacement})}catch{await T(t)}}async function ne(e,t,n){if(t.has(n))return;await n.setRequestInterception(!0);let r=t=>{D(e,t)},i=n;typeof i.prependListener==`function`?i.prependListener(`request`,r):i.on(`request`,r),t.add(n)}function O(e){let t=[`kind`,`name`];return e>0&&t.push(`ofType { ${O(e-1)} }`),t.join(`
2
+ `)}const k=`
3
+ query IntrospectionQuery {
4
+ __schema {
5
+ queryType { name }
6
+ mutationType { name }
7
+ subscriptionType { name }
8
+ types { ...FullType }
9
+ directives {
10
+ name
11
+ description
12
+ locations
13
+ args(includeDeprecated: true) { ...InputValue }
14
+ }
15
+ }
16
+ }
17
+ fragment FullType on __Type {
18
+ kind
19
+ name
20
+ description
21
+ fields(includeDeprecated: true) {
22
+ name
23
+ description
24
+ args(includeDeprecated: true) { ...InputValue }
25
+ type { ...TypeRef }
26
+ isDeprecated
27
+ deprecationReason
28
+ }
29
+ inputFields(includeDeprecated: true) { ...InputValue }
30
+ interfaces { ...TypeRef }
31
+ enumValues(includeDeprecated: true) {
32
+ name
33
+ description
34
+ isDeprecated
35
+ deprecationReason
36
+ }
37
+ possibleTypes { ...TypeRef }
38
+ }
39
+ fragment InputValue on __InputValue {
40
+ name
41
+ description
42
+ type { ...TypeRef }
43
+ defaultValue
44
+ isDeprecated
45
+ deprecationReason
46
+ }
47
+ fragment TypeRef on __Type {
48
+ ${O(7)}
49
+ }
50
+ `.trim();var A=class{collector;constructor(e){this.collector=e}async handleCallGraphAnalyze(t){try{let r=g(t,`maxDepth`,5,1,20),i=s(t,`filterPattern`)?.trim()||``;if(i)try{RegExp(i)}catch(e){return m(`Invalid filterPattern regex`,{filterPattern:i,reason:e instanceof Error?e.message:String(e)})}let a=await d(await this.collector.getActivePage(),({maxDepth:e,filterPattern:t})=>{let n=window,r=new Map,i=new Map,a=0,o=0,s=t?new RegExp(t):null,c=e=>s?(s.lastIndex=0,s.test(e)):!0,l=(e,t)=>s?c(e)||c(t):!0,u=(e,t=1)=>{let n=i.get(e);if(n){n.callCount+=t;return}i.set(e,{id:e,name:e,callCount:t})},d=(e,t)=>{let n=typeof e==`string`&&e.trim()||``,i=typeof t==`string`&&t.trim()||``;if(!n||!i||n===i||!l(n,i))return;let a=`${n}__->__${i}`,o=r.get(a);o?o.count+=1:r.set(a,{source:n,target:i,count:1}),u(n,1),u(i,1)},f=(t,n)=>{a+=1;let r=t.callee??t.functionName??t.fn??t.name??t.method??t.target??n,i=typeof r==`string`&&r.trim()||n,s=t.caller??t.parent??t.from??``,c=typeof s==`string`&&s.trim()||``,l=!1;c&&i&&(d(c,i),l=!0);let u=t.stack??t.stackTrace??t.trace,f=typeof u==`string`&&u.trim().length>0?u.split(`
51
+ `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>{let t=e.match(/at\s+([^(<\s]+)/);if(t?.[1])return t[1];let n=e.match(/^([^(<\s]+)@/);return n?.[1]?n[1]:``}).filter(e=>e.length>0):[];if(f.length>1){let t=Math.min(e,f.length-1);for(let e=0;e<t;e+=1)d(f[e+1],f[e]);l=!0}else f.length===1&&i&&f[0]!==i&&(d(f[0],i),l=!0);l&&(o+=1)},p=n.__aiHooks;if(p&&typeof p==`object`){for(let[e,t]of Object.entries(p))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}for(let e of[`__functionTraceRecords`,`__functionTracerRecords`,`__functionCalls`,`__callTrace`,`__traceCalls`]){let t=n[e];if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}let m=n.__functionTracer;if(m&&typeof m==`object`){let e=m.records;if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&f(t,`functionTracer.records`)}let h=Array.from(i.values()).toSorted((e,t)=>t.callCount-e.callCount),g=Array.from(r.values()).toSorted((e,t)=>t.count-e.count);return{nodes:h,edges:g,stats:{scannedRecords:a,acceptedRecords:o,nodeCount:h.length,edgeCount:g.length,maxDepth:e,filterPattern:t||null}}},{maxDepth:r,filterPattern:i}),o=a.nodes.length>n,c=a.edges.length>e;return p({success:!0,nodes:a.nodes.slice(0,n),edges:a.edges.slice(0,e),stats:{...a.stats,nodesReturned:Math.min(a.nodes.length,n),edgesReturned:Math.min(a.edges.length,e),nodesTruncated:o,edgesTruncated:c}})}catch(e){return m(e)}}},j=class{collector;scriptReplaceRules=[];interceptionInstalledPages=new WeakSet;constructor(e){this.collector=e}async handleScriptReplacePersist(e){try{let t=s(e,`url`)?.trim(),n=s(e,`replacement`),r=ee(e.matchType);if(!t)return m(`Missing required argument: url`);if(typeof n!=`string`||n.length===0)return m(`Missing required argument: replacement`);if(r===`regex`)try{RegExp(t)}catch(e){return m(`Invalid regex in url for matchType=regex`,{url:t,reason:h(e)})}let a=await this.collector.getActivePage(),o={id:C(),url:t,replacement:n,matchType:r,createdAt:Date.now(),hits:0};this.scriptReplaceRules.push(o),await ne(this.scriptReplaceRules,this.interceptionInstalledPages,a),await a.evaluateOnNewDocument(e=>{let t=window,n=`__scriptReplacePersistRules`,r=(Array.isArray(t[n])?t[n]:[]).filter(t=>t&&t.id!==e.id);r.push(e),t[n]=r},{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt});let c=x(n,i);return p({success:!0,message:`Script replacement rule registered and interception enabled`,rule:{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt},replacement:{length:n.length,preview:c.preview,truncated:c.truncated},activeRuleCount:this.scriptReplaceRules.length})}catch(e){return m(e)}}},re=class{collector;constructor(e){this.collector=e}async handleGraphqlIntrospect(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),r=await b(t,typeof e.url==`function`?e.url():null);return r?m(r):await this.introspectViaBrowser(e,t,n)}let r=await y(t);return r?m(r):await this.introspectViaNode(t,n)}catch(e){return m(e)}}async introspectViaNode(e,t){let n={"content-type":`application/json`,...t},i,a;try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e4);try{i=await fetch(e,{method:`POST`,headers:n,body:JSON.stringify({query:k,operationName:`IntrospectionQuery`}),signal:t.signal}),a=await i.text()}finally{clearTimeout(r)}}catch(t){return p({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,error:t instanceof Error?t.message:String(t)})}let o={};i.headers.forEach((e,t)=>{o[t]=e});let s=null;try{s=JSON.parse(a)}catch{}if(a=``,!i.ok&&!s)return p({success:!1,endpoint:e,status:i.status,statusText:i.statusText,error:`Introspection request failed`});let c=s&&typeof s==`object`?s:null,l=c&&`data`in c?c.data:s,u=s!=null&&l!==void 0?S(l,r):{preview:``,truncated:!1,totalLength:0},d={success:i.ok,endpoint:e,status:i.status,statusText:i.statusText,schemaLength:u.totalLength,schemaPreview:u.preview,schemaTruncated:u.truncated,responseHeaders:o};return u.truncated||(d.schema=l),c&&Array.isArray(c.errors)&&(d.errors=c.errors),p(d)}async introspectViaBrowser(e,t,n){let a=await d(e,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,operationName:`IntrospectionQuery`}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o={};a.headers.forEach((e,t)=>{o[t]=e});let s=i.length,c=null;try{c=JSON.parse(i)}catch{}let l=c===null?i:``;return i=``,{ok:a.ok,status:a.status,statusText:a.statusText,responseHeaders:o,totalLength:s,preview:l,truncated:!1,json:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseHeaders:{},totalLength:0,preview:``,truncated:!1,json:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:t,headers:n,query:k,maxSchemaChars:r});if(!a.ok&&!a.json)return p({success:!1,endpoint:t,status:a.status,statusText:a.statusText,error:a.error??`Introspection request failed`,responsePreview:x(a.preview||``,i)});let o=a.json&&typeof a.json==`object`?a.json:null,s=o&&`data`in o?o.data:a.json,c=a.json!==null&&a.json!==void 0&&s!==void 0?S(s,r):{preview:a.preview??``,truncated:a.truncated??!1,totalLength:a.totalLength??0},l={success:a.ok,endpoint:t,status:a.status,statusText:a.statusText,schemaLength:c.totalLength,schemaPreview:c.preview,schemaTruncated:c.truncated,responseHeaders:a.responseHeaders??{}};return c.truncated||(l.schema=s),o&&Array.isArray(o.errors)&&(l.errors=o.errors),a.error&&(l.error=a.error),p(l)}};function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e,t,n){if(!t)return;let r=t.query;if(typeof r!=`string`||r.trim().length===0)return;let i=t.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;e.push({source:n.source,url:n.url,method:n.method,operationName:a,query:r,variables:t.variables??null,timestamp:n.timestamp,contentType:n.contentType})}function P(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(M(e))return e}catch{}if(t.includes(`query=`))try{let e=new URLSearchParams(t),n=e.get(`query`);if(n){let t=e.get(`operationName`),r=e.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:t,variables:i}}}catch{}return t.startsWith(`query `)||t.startsWith(`mutation `)||t.startsWith(`subscription `)?{query:t}:null}function F(e){return M(e.headers)?e.headers:M(e.requestHeaders)?e.requestHeaders:{}}function I(e){let t=F(e);for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`content-type`)return typeof n==`string`?n.toLowerCase():String(n).toLowerCase();return``}function L(e){let t=[e.body,e.postData];return M(e.options)&&t.push(e.options.body),M(e.request)&&t.push(e.request.postData),t}function R(e,t){let n={scannedRecords:0,extracted:[]};if(!Array.isArray(e))return n;for(let r of e){if(!M(r))continue;n.scannedRecords+=1;let e=typeof r.url==`string`?r.url:``,i=typeof r.method==`string`?r.method:`POST`,a=typeof r.timestamp==`number`?r.timestamp:null,o=I(r);for(let s of L(r)){let r=null;M(s)?r=s:typeof s==`string`&&(r=P(s)),N(n.extracted,r,{source:t,url:e,method:i,timestamp:a,contentType:o})}o.includes(`application/graphql`)&&typeof r.body==`string`&&N(n.extracted,{query:r.body,variables:null,operationName:null},{source:t,url:e,method:i,timestamp:a,contentType:o})}return n}function z(e){let t=e.toSorted((e,t)=>(t.timestamp??0)-(e.timestamp??0)),n=[],r=new Set;for(let e of t){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;r.has(t)||(r.add(t),n.push(e))}return n}var B=class{deps;constructor(e){this.deps=`collector`in e?e:{collector:e}}async handleGraphqlExtractQueries(e){try{let n=g(e,`limit`,50,1,200),r=await d(await this.deps.collector.getActivePage(),e=>{let t=window,n=[],r=0,i=(e,t)=>{if(!e)return;let r=e.query;if(typeof r!=`string`||r.trim().length===0)return;let i=e.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;n.push({source:t.source,url:t.url,method:t.method,operationName:a,query:r,variables:e.variables??null,timestamp:t.timestamp,contentType:t.contentType})},a=e=>{if(!e)return null;try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}if(e.includes(`query=`))try{let t=new URLSearchParams(e),n=t.get(`query`);if(n){let e=t.get(`operationName`),r=t.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:e,variables:i}}}catch{}return e.startsWith(`query `)||e.startsWith(`mutation `)||e.startsWith(`subscription `)?{query:e}:null},o=(e,t)=>{r+=1;let n=typeof e.url==`string`?e.url:``,o=typeof e.method==`string`?e.method:`POST`,s=typeof e.timestamp==`number`?e.timestamp:null,c=(e.headers&&typeof e.headers==`object`&&!Array.isArray(e.headers)?e.headers:null)??(e.requestHeaders&&typeof e.requestHeaders==`object`&&!Array.isArray(e.requestHeaders)?e.requestHeaders:null)??{},l=``;for(let[e,t]of Object.entries(c))if(e.toLowerCase()===`content-type`){l=typeof t==`string`?t:String(t);break}l=l.toLowerCase();let u=[e.body,e.postData];e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&u.push(e.options.body);for(let e of u){let r=null;e&&typeof e==`object`&&!Array.isArray(e)?r=e:typeof e==`string`&&(r=a(e)),i(r,{source:t,url:n,method:o,timestamp:s,contentType:l})}l.includes(`application/graphql`)&&typeof e.body==`string`&&i({query:e.body,variables:null,operationName:null},{source:t,url:n,method:o,timestamp:s,contentType:l})},s=(e,t)=>{if(Array.isArray(e))for(let n of e)n&&typeof n==`object`&&o(n,t)},c=Array.isArray(t.__fetchRequests)?t.__fetchRequests:typeof t.__getFetchRequests==`function`?t.__getFetchRequests():void 0,l=Array.isArray(t.__xhrRequests)?t.__xhrRequests:typeof t.__getXHRRequests==`function`?t.__getXHRRequests():void 0;s(c,`window.__fetchRequests`),s(l,`window.__xhrRequests`),s(t.__networkRequests,`window.__networkRequests`);let u=t.__aiHooks;if(u&&typeof u==`object`){for(let[e,t]of Object.entries(u))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&o(n,`window.__aiHooks.${e}`)}n.sort((e,t)=>(t.timestamp??0)-(e.timestamp??0));let d=[],f=new Set;for(let e of n){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;f.has(t)||(f.add(t),d.push(e))}return{scannedRecords:r,totalExtracted:d.length,extracted:d.slice(0,e)}},n),a=r.scannedRecords,o=[...r.extracted];if(this.deps.consoleMonitor){let e=typeof this.deps.consoleMonitor.getFetchRequests==`function`?this.deps.consoleMonitor.getFetchRequests().catch(()=>[]):Promise.resolve([]),t=typeof this.deps.consoleMonitor.getXHRRequests==`function`?this.deps.consoleMonitor.getXHRRequests().catch(()=>[]):Promise.resolve([]),[n,r]=await Promise.all([e,t]),i=[];try{i=typeof this.deps.consoleMonitor.getNetworkRequests==`function`?this.deps.consoleMonitor.getNetworkRequests({limit:500}):[]}catch{i=[]}let s=[R(n,`consoleMonitor.fetchRequests`),R(r,`consoleMonitor.xhrRequests`),R(i,`consoleMonitor.networkRequests`)];for(let e of s)a+=e.scannedRecords,o.push(...e.extracted)}let s=z(o),c=Math.max(r.totalExtracted,s.length),l=s.slice(0,n).map((e,n)=>{let r=x(e.query,t),a=S(e.variables,i),o={index:n,source:e.source,url:e.url,method:e.method,operationName:e.operationName,contentType:e.contentType,timestamp:e.timestamp,queryLength:e.query.length,queryPreview:r.preview,queryTruncated:r.truncated};return r.truncated||(o.query=e.query),a.truncated?(o.variablesPreview=a.preview,o.variablesTruncated=!0):o.variables=e.variables,o});return p({success:!0,limit:n,stats:{scannedRecords:a,totalExtracted:c,returned:l.length},queries:l})}catch(e){return m(e)}}},V=class{collector;constructor(e){this.collector=e}async handleGraphqlReplay(e){try{let t=s(e,`endpoint`)?.trim(),n=s(e,`query`);if(!t)return m(`Missing required argument: endpoint`);if(typeof n!=`string`||n.trim().length===0)return m(`Missing required argument: query`);let r=c(e,`variables`)??{},i=s(e,`operationName`),a=i&&i.trim().length>0?i.trim():null,o=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),i=await b(t,typeof e.url==`function`?e.url():null);return i?m(i):await this.replayViaBrowser(e,t,n,r,a,o)}let l=await y(t);return l?m(l):await this.replayViaNode(t,n,r,a,o)}catch(e){return m(e)}}async replayViaNode(e,t,n,r,i){let a={"content-type":`application/json`,...i},o,s;try{let i=new AbortController,c=setTimeout(()=>i.abort(),1e4);try{o=await fetch(e,{method:`POST`,headers:a,body:JSON.stringify({query:t,variables:n,operationName:r}),signal:i.signal}),s=await o.text()}finally{clearTimeout(c)}}catch(t){return p({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,error:t instanceof Error?t.message:String(t),operationName:r})}let c={};o.headers.forEach((e,t)=>{c[t]=e});let l=null;try{l=JSON.parse(s)}catch{l=null}return s=``,p(H(l,e,r,o.ok,o.status,o.statusText,c))}async replayViaBrowser(e,t,n,i,a,o){let s=await d(e,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,variables:e.variables,operationName:e.operationName}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o=null;try{o=JSON.parse(i)}catch{o=null}let s=o===null?i:``;i=``;let c={};return a.headers.forEach((e,t)=>{c[t]=e}),{ok:a.ok,status:a.status,statusText:a.statusText,responseText:s,responseJson:o,responseHeaders:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseText:``,responseJson:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:t,query:n,variables:i,operationName:a,headers:o}),c={success:s.ok,endpoint:t,status:s.status,statusText:s.statusText,operationName:a,responseHeaders:s.responseHeaders??{}};if(s.responseJson!==null){let e=S(s.responseJson,r);c.responseLength=e.totalLength,c.responsePreview=e.preview,c.responseTruncated=e.truncated,e.truncated||(c.response=s.responseJson)}else if(s.responseText){let e=s.responseText;c.responseFormat=`text`,c.responseLength=e.length,c.responsePreview=e.length>r?e.slice(0,r):e,c.responseTruncated=e.length>r}return s.error&&(c.error=s.error),p(c)}};function H(e,t,n,i,a,o,s){let c={success:i,endpoint:t,status:a,statusText:o,operationName:n,responseHeaders:s};if(e!==null){let t=S(e,r);c.responseLength=t.totalLength,c.responsePreview=t.preview,c.responseTruncated=t.truncated,t.truncated||(c.response=e)}return c}const U=new Map;function W(e){let t=U.get(e);if(t)return t;let n=`
52
+ query EnumSchemaTypeProbe($typeName: String!) {
53
+ __type(name: $typeName) {
54
+ fields(includeDeprecated: true) {
55
+ name
56
+ type {
57
+ ${O(e)}
58
+ }
59
+ }
60
+ }
61
+ }
62
+ `.trim();return U.set(e,n),n}function G(e){let t=e??null;for(;t;){if(typeof t.name==`string`&&t.name.length>0)return{kind:typeof t.kind==`string`?t.kind:null,name:t.name};t=t.ofType??null}return{kind:null,name:null}}function K(e){return e===`OBJECT`||e===`INTERFACE`}function q(e){return e&&typeof e.data==`object`&&e.data!==null&&`__type`in e.data?e.data.__type:null}function J(e){let t=q(e);return Array.isArray(t?.fields)?t.fields.filter(e=>typeof e==`object`&&!!e&&typeof e.name==`string`):[]}function Y(e){let t=e??null,n=0;for(;t;){if(n+=1,typeof t.name==`string`&&t.name.length>0)return null;if(!t.ofType)return t.kind===`LIST`||t.kind===`NON_NULL`?n:null;t=t.ofType??null}return null}function ie(e){let t=null;for(let n of e){let e=Y(n.type);e!==null&&(t=Math.max(t??0,e))}return t}function ae(e){let t=[],n=e??null;for(;n;)t.push(`${n.kind??``}:${n.name??``}`),n=n.ofType??null;return t.join(`>`)}function oe(e){return e.map(e=>`${e.name??``}=${ae(e.type)}`).join(`|`)}async function se(e,t,n){let r=null,i=null,a=0;for(;;){let o=await X(e,t,{query:W(a),variables:{typeName:n}});if(!q(o.record))return r;let s=J(o.record);r=s;let c=ie(s);if(c===null)return r;let l=oe(s);if(c<=a||l===i)return r;i=l,a=c}}async function X(e,t,n){let r={"content-type":`application/json`,...t};try{let t=new AbortController,i=setTimeout(()=>t.abort(),1e4);try{let i=await fetch(e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:t.signal}),a=await i.text(),o=null;try{o=JSON.parse(a)}catch{o=null}let s=o&&typeof o==`object`?o:null,c=Array.isArray(s?.errors)?s.errors:[];return{ok:i.ok||c.length>0,status:i.status,statusText:i.statusText,record:s,errors:c}}finally{clearTimeout(i)}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,record:null,errors:[],error:e instanceof Error?e.message:String(e)}}}async function ce(e,t,n,r){let i=[{typeName:n,depth:0}],a=new Map,o=new Set;for(;i.length>0;){let n=i.shift();if(o.has(n.typeName))continue;o.add(n.typeName);let s=await se(e,t,n.typeName);if(!s)return a.size>0?a:null;if(a.set(n.typeName,s.map(e=>e.name?.trim()??``).filter(e=>e.length>0)),!(n.depth+1>=r))for(let e of s){let t=G(e.type);!t.name||!K(t.kind)||o.has(t.name)||i.push({typeName:t.name,depth:n.depth+1})}}return a}const le=/Cannot query field\s+"[^"]+"\s+on type\s+"([^"]+)".*?Did you mean\s+(.+?)\?/i,ue=/"([^"]+)"/g,Z=`__jshook_probe__`;function de(e){let t=le.exec(e);if(!t)return null;let[,n,r]=t;if(!n||!r)return null;let i=Array.from(r.matchAll(ue),e=>e[1]??``).filter(e=>e.length>0);return i.length>0?{typeName:n,suggestions:i}:null}function Q(e){return e.length===0?`query EnumSchemaProbe { ${Z} }`:`query EnumSchemaProbe { ${e.join(` { `)} { ${Z} }${`}`.repeat(e.length)} }`}function $(e){let t=e.discovered.get(e.parentType)??e.discovered.get(e.typeName)??[],n=JSON.stringify({rootType:e.typeName,parentType:e.parentType,fields:t},null,2);return p({success:!0,endpoint:e.endpoint,typeName:e.typeName,parentType:e.parentType,maxDepth:e.maxDepth,concurrency:e.concurrency,fields:t,discoveredTypes:Object.fromEntries(Array.from(e.discovered.entries()).filter(([e])=>!e.includes(`.`))),responsePreview:n.length>r?`${n.slice(0,r)}\n... (truncated)`:n})}var fe=class{async handleGraphqlEnumSchema(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=await y(t);if(n)return m(n);let r=_(e.headers),i=s(e,`typeName`,`Query`)?.trim()||`Query`,a=s(e,`parentType`,i)?.trim()||i,o=l(e,`maxDepth`,1)??1,c=Math.min(Math.max(Math.trunc(o),1),6),u=l(e,`concurrency`,3)??3,d=Math.min(Math.max(Math.trunc(u),1),10),f=await X(t,r,{query:Q([])});if(!f.ok)return p({success:!1,endpoint:t,typeName:i,parentType:a,status:f.status,statusText:f.statusText,error:f.error??`Schema enumeration request failed`});let h=this.extractSuggestions(f.errors);if(!h)return $({endpoint:t,typeName:i,parentType:a,maxDepth:c,concurrency:d,discovered:await ce(t,r,a,c)??new Map([[a,[]]])});let g=[],v=new Map;if(v.set(h.typeName,h.suggestions),c>1)for(let e of h.suggestions){let t=[e],n=t.join(`.`);v.has(n)||(v.set(n,[]),g.push({path:t,depth:1,typeName:e}))}for(;g.length>0;){let e=g.shift(),n=await X(t,r,{query:Q(e.path)});if(!n.ok)return p({success:!1,endpoint:t,typeName:i,parentType:a,status:n.status,statusText:n.statusText,error:n.error??`Schema enumeration request failed`});let o=this.extractSuggestions(n.errors);if(!o){v.set(e.typeName,[]);continue}if(v.set(o.typeName,o.suggestions),!(e.depth+1>=c))for(let t of o.suggestions){let n=[...e.path,t],r=n.join(`.`);v.has(r)||(v.set(r,[]),g.push({path:n,depth:e.depth+1,typeName:t}))}}return $({endpoint:t,typeName:i,parentType:a,maxDepth:c,concurrency:d,discovered:v})}catch(e){return m(e)}}extractSuggestions(e){for(let t of e){if(typeof t.message!=`string`)continue;let e=de(t.message);if(e)return e}return null}};function pe(e){return`collector`in e?e:{collector:e}}var me=class{callGraph;scriptReplace;introspection;extract;replay;schemaEnum;constructor(e){let t=pe(e);this.callGraph=new A(t.collector),this.scriptReplace=new j(t.collector),this.introspection=new re(t.collector),this.extract=new B(t),this.replay=new V(t.collector),this.schemaEnum=new fe}async handleCallGraphAnalyze(e){return this.callGraph.handleCallGraphAnalyze(e)}async handleScriptReplacePersist(e){return this.scriptReplace.handleScriptReplacePersist(e)}async handleGraphqlIntrospect(e){return this.introspection.handleGraphqlIntrospect(e)}async handleGraphqlExtractQueries(e){return this.extract.handleGraphqlExtractQueries(e)}async handleGraphqlReplay(e){return this.replay.handleGraphqlReplay(e)}async handleGraphqlEnumSchema(e){return this.schemaEnum.handleGraphqlEnumSchema(e)}};export{me as GraphQLToolHandlers};
@@ -0,0 +1,2 @@
1
+ import{n as e,r as t}from"./response-C7rKQst4.mjs";var n=class{graph;constructor(e){this.graph=e}pickStringArg(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}serializeNodes(e){return e.map(e=>({id:e.id,type:e.type,label:e.label,metadata:e.metadata}))}handleQueryDispatch(e){switch(e.by){case`function`:return this.handleQueryFunction({...e,name:this.pickStringArg(e,[`name`,`value`,`query`])});case`script`:return this.handleQueryScript({...e,scriptId:this.pickStringArg(e,[`scriptId`,`value`,`query`])});default:return this.handleQueryUrl({...e,url:this.pickStringArg(e,[`url`,`value`,`query`])})}}handleExportDispatch(e){return e.format===`markdown`?this.handleExportMarkdown():this.handleExportJson()}handleQueryUrl(t){let n=t.url,r=this.graph.queryByUrl(n);return e({query:{type:`url`,value:n},resultCount:r.length,nodes:this.serializeNodes(r)})}handleQueryFunction(t){let n=t.name,r=this.graph.queryByFunction(n);return e({query:{type:`function`,value:n},resultCount:r.length,nodes:this.serializeNodes(r)})}handleQueryScript(t){let n=t.scriptId,r=this.graph.queryByScriptId(n);return e({query:{type:`scriptId`,value:n},resultCount:r.length,nodes:this.serializeNodes(r)})}handleExportJson(){return e(this.graph.exportJson())}handleExportMarkdown(){let e=this.graph.exportMarkdown(),n=this.graph.exportJson();if(!n||!Array.isArray(n.nodes))return t(e);let r=n.nodes.filter(e=>n.edges.filter(t=>t.target===e.id).length===0),i=n.nodes.filter(e=>n.edges.filter(t=>t.source===e.id).length===0),a=n.edges.filter(e=>e.metadata&&typeof e.metadata.confidence==`number`&&e.metadata.confidence<.3),o=[];return o.push(``),o.push(`## Evidence Gaps`),o.push(``),o.push(`- **Dangling nodes (no inbound edges):** ${r.length}`),r.length>0&&o.push(` ${r.slice(0,10).map(e=>`\`${e.type}:${e.label}\``).join(`, `)}`),o.push(`- **Dangling nodes (no outbound edges):** ${i.length}`),i.length>0&&o.push(` ${i.slice(0,10).map(e=>`\`${e.type}:${e.label}\``).join(`, `)}`),o.push(`- **Low-confidence edges (<0.3):** ${a.length}`),r.length===0&&i.length===0&&a.length===0&&o.push(`- **Status:** No gaps detected — evidence chain is fully connected.`),o.push(``),t(e+o.join(`
2
+ `))}handleChain(t){let n=t.nodeId,r=t.direction??`forward`,i=this.graph.getEvidenceChain(n,r);return e({startNode:n,direction:r,chainLength:i.length,nodes:this.serializeNodes(i)})}};export{n as EvidenceHandlers};
@@ -0,0 +1 @@
1
+ import{t as e}from"./ToolError-DWU_z7gp.mjs";import{a as t,o as n,t as r}from"./parse-args-Bw413PlW.mjs";function i(e){return typeof e!=`object`||!e||!(`evaluate`in e)?!1:typeof e.evaluate==`function`}function a(e){return typeof e!=`object`||!e||!(`getExtension`in e)||!(`getParameter`in e)||!(`RENDERER`in e)||!(`VERSION`in e)?!1:typeof e.getExtension==`function`&&typeof e.getParameter==`function`}function o(e){let t=(e??``).toLowerCase();return t.includes(`vulkan`)?`vulkan`:t.includes(`metal`)?`metal`:t.includes(`d3d`)||t.includes(`direct3d`)?`direct3d`:t.includes(`angle`)||t.includes(`opengl`)||t.includes(`mesa`)||t.includes(`gl`)?`opengl`:t.includes(`swiftshader`)||t.includes(`software`)||t.includes(`cpu`)?`cpu`:t.length>0?`gpu`:`cpu`}function s(e){let t=0;for(let n of e)t+=1,t+=s(n.children);return t}function c(e){let t=e.getAttribute(`aria-label`);if(t)return t;if(e.id)return e.id;let n=typeof e.className==`string`?e.className.trim():``;return n.length>0?n:e.tagName.toLowerCase()}function l(e){if(typeof e.getBoundingClientRect!=`function`)return;let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function u(e){if(!(e instanceof HTMLElement)||typeof window>`u`)return;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`}function d(e,t){let n=Array.from(e.children).slice(0,12).map((e,n)=>d(e,`${t}-${n}`));return{id:e.id||t,type:e.tagName.toLowerCase(),label:c(e),children:n,visible:u(e),bounds:l(e)}}function f(){let e=[{id:`mock-root`,type:`canvas`,label:`mock-skia-surface`,visible:!0,bounds:{x:0,y:0,width:640,height:480},children:[{id:`mock-layer`,type:`layer`,label:`mock-layer`,visible:!0,bounds:{x:16,y:16,width:320,height:160},children:[]}]}];return{rootNodes:e,totalNodes:s(e),extractedAt:new Date().toISOString()}}function p(e){let t=`software`,n=`Raster`;return e.backend===`vulkan`?(t=`vulkan`,n=`Vulkan`):e.backend===`metal`?(t=`metal`,n=`Metal`):(e.backend===`opengl`||e.backend===`direct3d`||e.backend===`gpu`)&&(t=`gl`,n=`OpenGL`),{isSkiaBacked:e.backend!==`cpu`,version:e.version??null,gpuBackend:t,shaderPipeline:n,rendererStrings:e.gpu?[e.gpu]:[],features:e.backend===`cpu`?[]:[`backend:${e.backend}`],confidence:e.backend===`cpu`?.2:.8,evidence:e.gpu?[`Renderer string: ${e.gpu}`]:[`No renderer information available`]}}function m(e,t){return e.x>=t.x&&e.y>=t.y&&e.x+e.width<=t.x+t.width&&e.y+e.height<=t.y+t.height}function h(e){let t=(e??``).toLowerCase();return t.includes(`rrect`)||t.includes(`round`)?`drawRRect`:t.includes(`rect`)?`drawRect`:t.includes(`text`)?`drawText`:t.includes(`image`)||t.includes(`sprite`)?`drawImage`:t.includes(`path`)?`drawPath`:t.includes(`circle`)||t.includes(`arc`)?`drawCircle`:t.includes(`line`)?`drawLine`:`unknown`}function g(e){let t=e.layers.map((e,t)=>({id:e.id??`layer-${t}`,name:e.name??`layer-${t}`,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:e.transform??[1,0,0,0,1,0,0,0,1],opacity:e.opacity??1,visible:e.visible??!0,children:[],customData:e.customData})),n=t[0]??null;if(n)for(let e=1;e<t.length;e+=1){let r=t[e];r&&m(r.bounds,n.bounds)&&n.children.push(r)}let r=e.drawCommands.map(e=>({type:h(e.type),bounds:e.bounds??{x:0,y:0,width:0,height:0},paintInfo:e.paintInfo??{},layerId:e.layerId}));return{rootLayer:n,layers:t,drawCommands:r,totalLayers:t.length,totalDrawCommands:r.length,canvas:{id:e.canvas.id,width:e.canvas.width??0,height:e.canvas.height??0,dpr:e.canvas.dpr??1,contextType:e.canvas.contextType??`unknown`}}}function _(e){return{id:e.id,name:e.label,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:[1,0,0,0,1,0,0,0,1],opacity:1,visible:e.visible??!0,children:e.children.map(e=>_(e))}}function v(e){let t=e.rootNodes.map(e=>_(e));return{rootLayer:t[0]??null,layers:t,drawCommands:[],totalLayers:t.length,totalDrawCommands:0,canvas:{width:t[0]?.bounds.width??0,height:t[0]?.bounds.height??0,dpr:1,contextType:`mock`}}}function y(e){for(let t of e){let e=t.match(/(\d+\.\d+(?:\.\d+)?)/);if(e&&e[1])return e[1]}return null}function b(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`metal`:t.includes(`vulkan`)?`vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`software`:t.length>0?`gl`:`software`}function x(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`Metal`:t.includes(`vulkan`)?`Vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`Raster`:t.length>0?`OpenGL`:`Raster`}function S(e,t,n){let r=e.flatMap(e=>{let t=[];return e.unmaskedRenderer&&t.push(e.unmaskedRenderer),e.renderer&&t.push(e.renderer),t}),i=[],a=[];t.hasSkiaFontSignatures&&(i.push(`fontBoundingBoxAscent/Descent available`),a.push(`Canvas text metrics expose font bounding boxes`));for(let e of n.engines)i.push(`engine:${e}`),a.push(`Detected known Skia-adjacent engine: ${e}`);for(let t of e)t.hasSkiaBackend&&t.unmaskedRenderer&&a.push(`Renderer probe: ${t.unmaskedRenderer}`);let o=e.some(e=>e.hasSkiaBackend)||n.isSkiaEngine||t.hasSkiaFontSignatures,s=.1;e.some(e=>e.hasSkiaBackend)&&(s+=.5),n.isSkiaEngine&&(s+=.3),t.hasSkiaFontSignatures&&(s+=.1);let c=o?b(r):`software`,l=o?x(r):`Raster`;return{isSkiaBacked:o,version:y(r),gpuBackend:c,shaderPipeline:l,rendererStrings:r,features:i,confidence:Math.min(s,1),evidence:a}}var C=class{detectSkiaRenderer(){if(typeof document>`u`)return{backend:`cpu`,version:`mock`,gpu:`browser-context-unavailable`};let e=document.querySelector(`canvas`);if(!(e instanceof HTMLCanvasElement))return{backend:`cpu`,version:`mock`,gpu:`no-canvas-detected`};let t=e.getContext(`webgl2`)||e.getContext(`webgl`)||e.getContext(`experimental-webgl`);if(!a(t))return{backend:`cpu`,version:`mock`,gpu:`canvas-without-webgl`};let n,r=t.getExtension(`WEBGL_debug_renderer_info`);if(r){let e=t.getParameter(r.UNMASKED_RENDERER_WEBGL);typeof e==`string`&&e.trim().length>0&&(n=e)}if(!n){let e=t.getParameter(t.RENDERER);typeof e==`string`&&e.trim().length>0&&(n=e)}let i,s=t.getParameter(t.VERSION);return typeof s==`string`&&s.trim().length>0&&(i=s),{backend:o(n),version:i,gpu:n}}extractSceneTree(e){if(typeof document>`u`)return f();let t=e?document.querySelector(e):document.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return f();let n=d(t,`skia-root`);if(t.parentElement){let e=Array.from(t.parentElement.children).filter(e=>e!==t).slice(0,8).map((e,t)=>d(e,`skia-sibling-${t}`));n.children.push(...e)}let r=[n];return{rootNodes:r,totalNodes:s(r),extractedAt:new Date().toISOString()}}};async function w(e,t){return i(e)?S(await e.evaluate(`(() => { /* UNMASKED_RENDERER_WEBGL ${t??``} */ return []; })()`),await e.evaluate(`(() => { /* fontBoundingBoxAscent */ return { hasSkiaFontSignatures: false, textMetrics: null }; })()`),await e.evaluate(`(() => { /* window.cc window.legacyCC */ return { engines: [], isSkiaEngine: false }; })()`)):p(new C().detectSkiaRenderer())}async function T(e,t,n=!0){return i(e)?g(await e.evaluate(`(() => { /* drawCommands canvasMeta ${t??``} */ return { canvas: {}, layers: [], drawCommands: [] }; })()`)):v(new C().extractSceneTree(t))}function E(e,t){let n=[],r=new Set,i=new Set,a=O(e);for(let e of a){let a=null;for(let n of t){let t=D(e,n);t&&(!a||t.confidence>a.confidence)&&(a=t)}a&&a.confidence>=.3&&(n.push(a),r.add(a.skiaObjectId),i.add(a.jsObjectId))}let o=[...new Set(a.map(e=>e.id))].filter(e=>!r.has(e)),s=t.filter(e=>!i.has(e.objectId)).map(e=>e.objectId),c=n.reduce((e,t)=>e+t.confidence,0),l=n.length>0?c/n.length:0;return{correlations:n,unmatchedJSObjects:s,unmatchedSkiaObjects:o,summary:{totalSkiaObjects:a.length,totalJSObjects:t.length,matchedCount:n.length,averageConfidence:Math.round(l*100)/100}}}function D(e,t){if(e.text){for(let n of t.stringProps)if(n===e.text||n.includes(e.text)&&e.text.length>3)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.85,matchType:`text`,explanation:`Draw text "${e.text.slice(0,50)}" matches JS string property`}}let n=j(e.bounds,t.numericProps);if(n)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:n.confidence,matchType:`dimension`,explanation:n.explanation};if(e.color){for(let n of t.colorProps)if(P(n,e.color))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.7,matchType:`color`,explanation:`Color ${e.color} matches JS color property "${n}"`}}if(e.type===`drawImage`){let n=e.color;if(n){for(let r of t.urlProps)if(r===n||r.includes(n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.8,matchType:`url`,explanation:`Image URL matches JS property`}}}if(e.name){if(t.name&&N(e.name,t.name))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name,confidence:.75,matchType:`name`,explanation:`Object name "${e.name}" matches JS object "${t.name}"`};for(let n of t.stringProps)if(N(e.name,n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.6,matchType:`name`,explanation:`Skia layer name matches JS string property`}}let r=M(e.bounds,t.numericProps);return r?{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:r.confidence,matchType:`geometry`,explanation:r.explanation}:null}function O(e){let t=[];for(let n of e.layers)t.push({id:n.id,type:`layer`,name:n.name,bounds:n.bounds,color:n.customData?.color});for(let n of e.drawCommands){let e=k(n.paintInfo),r=A(n.paintInfo);t.push({id:`cmd_${n.type}_${n.bounds.x}_${n.bounds.y}`,type:n.type,name:`${n.type} at (${n.bounds.x}, ${n.bounds.y})`,text:e,bounds:n.bounds,color:r})}return t}function k(e){if(typeof e.text==`string`)return e.text;if(typeof e.content==`string`)return e.content}function A(e){if(typeof e.color==`string`)return e.color;if(typeof e.fillColor==`string`)return e.fillColor;if(typeof e.strokeColor==`string`)return e.strokeColor;if(typeof e.url==`string`)return e.url;if(typeof e.src==`string`)return e.src}function j(e,t){let n=[`width`,`height`,`w`,`h`,`sizeX`,`sizeY`,`sw`,`sh`],r=!1,i=!1;for(let a of n){let n=t[a];n!==void 0&&((a===`width`||a===`w`||a===`sizeX`||a===`sw`)&&Math.abs(n-e.width)<=2&&(r=!0),(a===`height`||a===`h`||a===`sizeY`||a===`sh`)&&Math.abs(n-e.height)<=2&&(i=!0))}return r&&i?{confidence:.75,explanation:`Dimensions ${e.width}x${e.height} match JS numeric properties`}:r||i?{confidence:.45,explanation:`Partial dimension match for ${e.width}x${e.height}`}:null}function M(e,t){let n=!1,r=!1;for(let[i,a]of Object.entries(t))(i===`x`||i===`posX`||i===`left`)&&Math.abs(a-e.x)<=5&&(n=!0),(i===`y`||i===`posY`||i===`top`)&&Math.abs(a-e.y)<=5&&(r=!0);return n&&r?{confidence:.5,explanation:`Position (${e.x}, ${e.y}) matches JS numeric properties`}:null}function N(e,t){return e.toLowerCase()===t.toLowerCase()||e.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(e.toLowerCase())}function P(e,t){return e.toLowerCase().replace(/\s/g,``)===t.toLowerCase().replace(/\s/g,``)}async function F(e,n){let r=t(n,`canvasId`);return{rendererInfo:await w(e,r||void 0),canvasId:r||`auto`,detectionComplete:!0}}async function I(e,n){let i=t(n,`canvasId`),a=r(n,`includeDrawCommands`,!0);return{sceneTree:await T(e,i||void 0,a),canvasId:i||`auto`,extractionComplete:!0}}async function L(r,i,a){let o=t(i,`canvasId`),s=n(i,`skiaNodeIds`),c=await T(r,o||void 0,!0);if(c.layers.length===0&&c.drawCommands.length===0)throw new e(`PREREQUISITE`,`No Skia scene data available for correlation`);let l=[];if(a)try{l=await a()}catch{l=[]}let u=c;if(s.length>0){let e=new Set(s);u={...c,layers:c.layers.filter(t=>e.has(t.id)),drawCommands:c.drawCommands.filter(t=>{let n=t.layerId;return n===void 0||e.has(n)})}}return{correlations:E(u,l),canvasId:o||`auto`,skiaNodeIds:s.length>0?s:void 0,correlationComplete:!0}}var R=class{deps;constructor(e){this.deps=e}async handleSkiaDetectRenderer(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return F(this.deps.pageController,t)}async handleSkiaExtractScene(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);let n=await I(this.deps.pageController,t),r=n?.sceneTree;return r&&this.deps.eventBus?.emit(`skia:scene_captured`,{canvasId:t.canvasId??`auto`,nodeCount:(r.layers?.length??0)+(r.drawCommands?.length??0),timestamp:new Date().toISOString()}),n}async handleSkiaCorrelateObjects(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return L(this.deps.pageController,t,this.deps.getJSObjects)}};export{R as SkiaCaptureHandlers};
@@ -0,0 +1 @@
1
+ import{n as e}from"./response-C7rKQst4.mjs";import{a as t}from"./parse-args-Bw413PlW.mjs";import{n}from"./ResponseBuilder-BfWP-uaT.mjs";var r=class{sessionManager;deps;constructor(e,t={}){this.sessionManager=e,this.deps=t}async handleSessionDispatch(n){let r=t(n,`action`);switch(r){case`create`:return this.handleSessionCreate(n);case`list`:return this.handleSessionList(n);case`destroy`:return this.handleSessionDestroy(n);case`status`:return this.handleSessionStatus(n);default:return e({success:!1,error:`Unknown action: ${r}. Valid: create, list, destroy, status`})}}async handleOperationDispatch(n){let r=t(n,`action`);switch(r){case`register`:return this.handleOperationRegister(n);case`list`:return this.handleOperationList(n);default:return e({success:!1,error:`Unknown action: ${r}. Valid: register, list`})}}async handleArtifactDispatch(n){let r=t(n,`action`);switch(r){case`record`:return this.handleArtifactRecord(n);case`query`:return this.handleArtifactQuery(n);default:return e({success:!1,error:`Unknown action: ${r}. Valid: record, query`})}}async handleSessionCreate(e){return n(async()=>{let n=t(e,`name`);return{session:this.sessionManager.createSession(n||void 0)}})}async handleSessionList(e){return n(async()=>{let e=this.sessionManager.listSessions();return{totalSessions:e.length,sessions:e}})}async handleSessionDestroy(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);return this.sessionManager.destroySession(n),{sessionId:n,message:`Session destroyed`}})}async handleSessionStatus(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);let r=this.sessionManager.getSession(n);if(!r)throw Error(`Session "${n}" not found`);return{session:r,stats:this.sessionManager.getSessionStats(n)}})}async handleOperationList(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);let r=this.sessionManager.getSessionOperations(n),i=t(e,`type`);return i&&(r=r.filter(e=>e.type===i)),{totalOperations:r.length,operations:r}})}async handleOperationRegister(e){return n(async()=>{let n=t(e,`sessionId`,``),r=t(e,`type`,``),i=t(e,`target`,``),a=e.config&&typeof e.config==`object`&&!Array.isArray(e.config)?e.config:{};if(!n)throw Error(`sessionId is required`);if(!r)throw Error(`type is required`);if(!i)throw Error(`target is required`);return{operation:this.sessionManager.registerOperation(n,r,i,a)}})}async handleArtifactQuery(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);let r=t(e,`type`)||void 0,i=typeof e.limit==`number`?e.limit:50,a=this.sessionManager.getArtifacts(n,r);return i>0&&(a=a.slice(0,i)),{totalArtifacts:a.length,artifacts:a}})}async handleArtifactRecord(e){return n(async()=>{let n=t(e,`operationId`,``),r=e.data&&typeof e.data==`object`&&!Array.isArray(e.data)?e.data:void 0;if(!n)throw Error(`operationId is required`);if(!r)throw Error(`data is required`);return{artifact:this.sessionManager.recordArtifact(n,r)}})}async handleHookPreset(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);if(!this.deps.hookPresetHandlers)throw Error(`hookPresetHandlers is not available`);let r={...e};delete r.sessionId;let i=await this.sessionManager.applyHookPreset(n,this.deps.hookPresetHandlers,r);return{operation:i.operation,artifacts:i.artifacts,result:i.payload}})}async handleNetworkReplay(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);if(!this.deps.advancedHandlers)throw Error(`advancedHandlers is not available`);let r={...e};delete r.sessionId;let i=await this.sessionManager.replayNetworkRequest(n,this.deps.advancedHandlers,r);return{operation:i.operation,artifacts:i.artifacts,result:i.payload}})}};export{r as InstrumentationHandlers};
@@ -0,0 +1 @@
1
+ import{ui as e}from"./constants-BYj8Xek8.mjs";import{n as t}from"./response-C7rKQst4.mjs";import{i as n,r}from"./outputPaths-B4Ic4RZh.mjs";import{a as i,i as a,s as o}from"./parse-args-Bw413PlW.mjs";import s from"node:http";import{createHash as c}from"node:crypto";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f}from"node:fs";import p from"node:path";import{fileURLToPath as m,pathToFileURL as h}from"node:url";import{mkdir as g,readFile as _,writeFile as v}from"node:fs/promises";import{EventEmitter as y}from"node:events";function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x(e){let t=e.trim().toLowerCase().replace(/\//g,`-`).replace(/(?!^@)[^a-z0-9@_-]+/g,`-`);return t.length>0?t:`plugin-${Date.now()}`}function S(e){if(!b(e))return null;let{id:t,name:n,version:r,entry:i,permissions:a,status:o}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||o!==`loaded`&&o!==`unloaded`?null:{id:t,name:n,version:r,entry:i,permissions:Array.isArray(a)?a.filter(e=>typeof e==`string`):[],status:o}}var C=class{rootDir;legacyPluginRoots;useLegacyScanApi;registryFile;moduleCacheDir;installedPlugins=new Map;loadedPlugins=new Map;constructor(e=r(),t=[]){let n=typeof e==`string`?e:r();this.useLegacyScanApi=typeof e!=`string`,this.rootDir=n,this.registryFile=p.join(n,`plugins.json`),this.moduleCacheDir=p.join(n,`modules`),this.legacyPluginRoots=t.length>0?t:process.env.JSHOOKMCP_PLUGIN_ROOT?[process.env.JSHOOKMCP_PLUGIN_ROOT]:[],!this.useLegacyScanApi&&this.initializeFromDisk()}async register(e){let t=x(e.id||e.name),n={id:t,name:e.name,version:e.version,entry:e.entry,permissions:e.permissions?[...e.permissions]:[],status:this.loadedPlugins.has(t)?`loaded`:`unloaded`};return this.installedPlugins.set(t,n),await this.persist(),t}async unregister(e){await this.unloadPlugin(e),this.installedPlugins.delete(e),await this.persist()}listInstalled(){return[...this.installedPlugins.values()].map(e=>({id:e.id,name:e.name,version:e.version,status:e.status,permissions:[...e.permissions]})).toSorted((e,t)=>e.name.localeCompare(t.name))}async loadPlugin(e){let t=this.installedPlugins.get(e);if(!t)throw Error(`Plugin not found: ${e}`);let n=this.loadedPlugins.get(e);if(n)return{manifest:this.toPublicManifest(n.manifest),exports:n.exports};let r=h(await this.resolveEntryPath(t));r.searchParams.set(`ts`,String(Date.now()));let i=await import(r.href),a=b(i)?i:{};return t.status=`loaded`,this.loadedPlugins.set(e,{manifest:t,exports:a}),await this.persist(),{manifest:this.toPublicManifest(t),exports:a}}async unloadPlugin(e){let t=this.installedPlugins.get(e);t&&(this.loadedPlugins.delete(e),t.status=`unloaded`,await this.persist())}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),l(this.moduleCacheDir)||u(this.moduleCacheDir,{recursive:!0}),!l(this.registryFile))return;let e=d(this.registryFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=S(e);t&&this.installedPlugins.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await g(this.moduleCacheDir,{recursive:!0}),await v(this.registryFile,JSON.stringify([...this.installedPlugins.values()],null,2),`utf8`)}async resolveEntryPath(e){return e.entry.startsWith(`http://`)||e.entry.startsWith(`https://`)?this.downloadRemoteModule(e.id,e.entry):e.entry.startsWith(`file://`)?m(new URL(e.entry)):p.isAbsolute(e.entry)?e.entry:p.resolve(n(),e.entry)}async downloadRemoteModule(e,t){let n=await fetch(t);if(!n.ok)throw Error(`Failed to download plugin module: ${n.status} ${n.statusText}`);let r=await n.text(),i=p.join(this.moduleCacheDir,`${x(e)}.mjs`),a=c(`sha256`).update(r).digest(`hex`);try{let e=await _(i,`utf8`);if(c(`sha256`).update(e).digest(`hex`)===a)return i}catch{}return await g(this.moduleCacheDir,{recursive:!0}),await v(i,r,`utf8`),i}toPublicManifest(e){return{id:e.id,name:e.name,version:e.version,entry:e.entry,permissions:[...e.permissions]}}listPlugins(){let e=[];for(let t of this.legacyPluginRoots){if(!l(t))continue;let n=f(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`))continue;let n=p.join(t,r.name,`package.json`);if(l(n))try{let t=JSON.parse(d(n,`utf8`)),r=this.toLegacyPluginInfo(t);r&&e.push(r)}catch{continue}}}return e}searchPlugins(e){let t=e.trim().toLowerCase();return t?this.listPlugins().filter(e=>e.name.toLowerCase().includes(t)||(e.description??``).toLowerCase().includes(t)||(e.capabilities??[]).some(e=>e.toLowerCase().includes(t))||(e.dependencies??[]).some(e=>e.toLowerCase().includes(t))):this.listPlugins()}async installPlugin(e){if(/^https:\/\/github\.com\/.+\.git$/u.test(e)||/^git@github\.com:.+\.git$/u.test(e))return{id:`git-plugin`,name:e.split(`/`).pop()?.replace(/\.git$/u,``)??`plugin`,version:`0.0.0`};if(e.includes(`://`)||e.startsWith(`git@`)||e===`invalid-url`)throw Error(`Invalid git URL`);if(e.startsWith(`/`)||e.includes(`\\`)){let t=p.join(e,`package.json`);if(!l(t))throw Error(`No package.json`);let n=JSON.parse(d(t,`utf8`)),r=this.toLegacyPluginInfo(n);if(!r)throw Error(`No package.json`);return r}for(let t of this.legacyPluginRoots){let n=p.join(t,e,`package.json`);if(!l(n))continue;let r=JSON.parse(d(n,`utf8`)),i=this.toLegacyPluginInfo(r);if(i)return i}throw Error(`Plugin not found`)}getPluginInfo(e){return this.listPlugins().find(t=>t.id===e||t.name===e)}getPluginDependencies(e){return this.getPluginInfo(e)?.dependencies??[]}async uninstallPlugin(e){}toLegacyPluginInfo(e){if(typeof e.name!=`string`)return null;let t=b(e.dependencies)?Object.keys(e.dependencies):[];return{id:x(e.name),name:e.name,version:typeof e.version==`string`?e.version:`0.0.0`,description:typeof e.description==`string`?e.description:void 0,capabilities:Array.isArray(e.capabilities)?e.capabilities.filter(e=>typeof e==`string`):void 0,dependencies:t}}};function w(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T(e){if(!w(e))return null;let{id:t,url:n,events:r,active:i}=e;return typeof t!=`string`||typeof n!=`string`||!Array.isArray(r)||typeof i!=`boolean`?null:{id:t,url:n,events:r.filter(e=>typeof e==`string`),active:i}}var E=class{rootDir;storageFile;webhooks=new Map;constructor(e=r()){this.rootDir=e,this.storageFile=p.join(e,`webhooks.json`),this.initializeFromDisk()}async registerWebhook(e,t){new URL(e);let n={id:`webhook-${Date.now()}-${this.webhooks.size+1}`,url:e,events:[...new Set(t.filter(e=>e.trim().length>0))],active:!0};return this.webhooks.set(n.id,n),await this.persist(),n.id}async sendEvent(e,t){let n=[...this.webhooks.values()].filter(t=>t.active&&(t.events.includes(e)||t.events.includes(`*`)));for(let r of n){let n=await fetch(r.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:e,payload:t,timestamp:new Date().toISOString()})});if(!n.ok)throw Error(`Webhook delivery failed for ${r.url}: ${n.status} ${n.statusText}`)}}listWebhooks(){return[...this.webhooks.values()].map(e=>({id:e.id,url:e.url,events:[...e.events],active:e.active}))}registerExternalCallback(e,t){let n=this.webhooks.get(e);if(n){n.url=t;return}this.webhooks.set(e,{id:e,url:t,events:[`*`],active:!0})}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),!l(this.storageFile))return;let e=d(this.storageFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=T(e);t&&this.webhooks.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await v(this.storageFile,JSON.stringify([...this.webhooks.values()],null,2),`utf8`)}};function D(e){return{...e}}function O(){return new Date().toISOString()}var k=class extends y{maxQueueSize;commands=new Map;order=[];maxRetries;retryDelay;processTimeout;nextId=1;constructor(t={}){super(),this.maxQueueSize=typeof t.maxQueueSize==`number`?t.maxQueueSize:1e3,this.maxRetries=typeof t.maxRetries==`number`?t.maxRetries:3,this.retryDelay=typeof t.retryDelay==`number`?t.retryDelay:0,this.processTimeout=typeof t.processTimeout==`number`?t.processTimeout:e}enqueue(e){if(this.order.length>=this.maxQueueSize)throw Error(`Command queue is full (${this.maxQueueSize})`);let t=`cmd-${this.nextId}`;this.nextId+=1;let n=O(),r={id:t,endpointId:e.endpointId,event:e.event,payload:e.payload,status:`pending`,retries:0,createdAt:n,updatedAt:n};return this.commands.set(t,r),this.order.push(t),this.emit(`enqueued`,D(r)),t}dequeue(e){if(!e){let e=this.getCommandsByFilter({status:`pending`})[0];return e?D(e):void 0}return this.getCommandsByFilter(e).map(D)}getStatus(e){let t=this.commands.get(e);return t?t.status===`processed`?`completed`:t.status:`failed`}retry(e){let t=this.commands.get(e);if(!t)throw Error(`Command ${e} not found`);if(t.status!==`failed`)throw Error(`Command ${e} is not in failed state`);t.status=`pending`,t.retries=0,t.lastError=void 0,t.updatedAt=O()}getCommand(e){return this.commands.get(e)}getCommandsByFilter(e){let t=e.status===`completed`?`processed`:e.status,n=[];for(let r of this.order){let i=this.commands.get(r);i&&(t&&i.status!==t||e.endpointId&&i.endpointId!==e.endpointId||n.push(i))}return n}updateStatus(e,t,n){let r=this.commands.get(e);if(!r)throw Error(`Command ${e} not found`);return r.status=t,r.updatedAt=O(),r.lastError=n,r}},A=class extends k{async process(e,t){let n=this.getCommand(e);if(!n)throw Error(`Command ${e} not found`);if(n.status===`processed`)throw Error(`Command ${e} already processed`);if(n.status===`failed`)throw Error(`Command ${e} already processed with failure`);if(n.status===`processing`)throw Error(`Command ${e} is already processing`);this.updateStatus(e,`processing`);let r=`processed`,i;try{await Promise.race([Promise.resolve(t(D(n))),new Promise((e,t)=>{setTimeout(()=>{t(Error(`Process timeout`))},this.processTimeout)})])}catch(e){i=e instanceof Error?e.message:String(e),r=n.retries+1>=this.maxRetries?`failed`:`pending`}if(i!==void 0&&this.retryDelay>0&&setTimeout(()=>{},this.retryDelay),r===`processed`){let t=this.updateStatus(e,`processed`);this.emit(`processed`,D(t))}else if(r===`pending`){n.retries+=1;let t=this.updateStatus(e,`pending`,i);throw this.emit(`retried`,D(t)),Error(i===void 0?`retry`:i)}else{let t=this.updateStatus(e,`failed`,i);throw this.emit(`failed`,D(t)),Error(i===void 0?`failed`:i)}}async retry(e){super.retry(e)}exportState(){let e=[];for(let t of this.order){let n=this.commands.get(t);n&&e.push(D(n))}return e}importState(e){this.commands.clear(),this.order.length=0;let t=0;for(let n of e){let e=D(n);this.commands.set(e.id,e),this.order.push(e.id);let r=/^cmd-(\d+)$/.exec(e.id);if(r&&r[1]){let e=parseInt(r[1],10);e>t&&(t=e)}}t>0&&(this.nextId=t+1)}};function j(e){return e===`tool_called`||e===`domain_activated`||e===`evidence_added`||e===`workflow_completed`}function M(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{rawBody:e}}}var N=class extends y{endpoints=new Map;eventHandlers=new Map;port;commandQueue;stats={eventsRegistered:0,webhooksSent:0};server;nextEndpointId=1;constructor(e={}){super(),this.port=typeof e.port==`number`?e.port:18789,this.commandQueue=e.commandQueue}registerEndpoint(e){let t=`ep-${this.nextEndpointId}`;return this.nextEndpointId+=1,this.endpoints.set(t,{id:t,path:e.path,method:e.method??`POST`,secret:e.secret}),this.emit(`endpointRegistered`,t),t}removeEndpoint(e){if(!this.endpoints.delete(e))throw Error(`Endpoint ${e} not found`);this.emit(`endpointRemoved`,e)}listEndpoints(){return[...this.endpoints.values()].map(e=>({...e}))}getPort(){return this.port}isRunning(){return this.server!==void 0}registerEvent(e,t){let n=this.eventHandlers.get(e)??[];n.push(t),this.eventHandlers.set(e,n),this.stats.eventsRegistered+=1}start(){if(this.server)throw Error(`Webhook server already started`);this.server=s.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.listen(this.port),this.emit(`started`,this.port)}async stop(){if(!this.server)return;let e=this.server;this.server=void 0,await new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})}),this.emit(`stopped`)}async sendWebhook(e,t,n){await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:t,payload:n})}),this.stats.webhooksSent+=1,this.stats.lastSentAt=new Date().toISOString()}getStats(){return{...this.stats}}async handleRequest(e,t){let n=e.method??`GET`,r=e.url??`/`,i=[...this.endpoints.values()].find(e=>e.path===r&&e.method===n);if(!i){t.statusCode=404,t.end(`not found`);return}if(i.secret&&e.headers[`x-webhook-secret`]!==i.secret){t.statusCode=401,t.end(`unauthorized`);return}let a=[];await new Promise((t,n)=>{e.setEncoding(`utf8`),e.on(`data`,e=>{a.push(e)}),e.on(`end`,()=>{t()}),e.on(`error`,e=>{n(e)})});let o=M(a.join(``));this.commandQueue&&this.commandQueue.enqueue({endpointId:i.id,payload:o}),o&&typeof o==`object`&&`event`in o&&typeof o.event==`string`&&await this.invokeEventHandlers(o.event,o),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!0,endpointId:i.id}))}async invokeEventHandlers(e,t){if(!j(e))return;let n=this.eventHandlers.get(e)??[];for(let e of n)await Promise.resolve(e(t))}},P=class extends N{};function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return typeof e==`function`}var L=class{registry;webhook;webhookServer;commandQueue;constructor(e,t){this.registry=e,this.webhook=t}async handleListInstalled(){return t({success:!0,plugins:this.getRegistry().listInstalled()})}async handleExecuteInContext(e){let n=o(e,`pluginId`),r=o(e,`contextName`),i=a(e,`args`)??{},{manifest:s,exports:c}=await this.getRegistry().loadPlugin(n),l=this.resolveContext(c,r);if(!l)throw Error(`Context "${r}" was not found in plugin "${n}"`);let u=await Promise.resolve(l(i));return this.emitEvent(`extension.executed`,{pluginId:n,contextName:r}),t({success:!0,manifest:s,contextName:r,result:u})}async handleReload(e){let n=o(e,`pluginId`);await this.getRegistry().unloadPlugin(n);let r=await this.getRegistry().loadPlugin(n);return this.emitEvent(`extension.reloaded`,{pluginId:n}),t({success:!0,pluginId:n,manifest:r.manifest,exportedKeys:Object.keys(r.exports).toSorted()})}async handleUninstall(e){let n=o(e,`pluginId`);return await this.getRegistry().unregister(n),this.emitEvent(`extension.uninstalled`,{pluginId:n}),t({success:!0,pluginId:n})}async handleWebhookCreate(e){let n=o(e,`name`),r=o(e,`path`),a=i(e,`secret`),s=Array.isArray(e.events)?e.events.filter(e=>typeof e==`string`):[],c=this.getWebhookServer();c.isRunning()||c.start();let l=c.registerEndpoint({path:r,method:`POST`,secret:a??void 0}),u=this.getWebhook(),d=`http://localhost:${c.getPort()}${r}`;return u.registerExternalCallback(l,d),t({success:!0,endpointId:l,url:d,name:n,events:s})}async handleWebhookList(){let e=this.getWebhookServer();return t({success:!0,endpoints:e.listEndpoints(),port:e.getPort(),running:e.isRunning()})}async handleWebhookDelete(e){let n=o(e,`endpointId`),r=this.getWebhookServer();try{r.removeEndpoint(n)}catch(e){throw Error(`GRACEFUL: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return t({success:!0,endpointId:n})}async handleWebhookCommands(e){let n=o(e,`endpointId`),r=i(e,`status`),s=a(e,`command`);if(s)return t({success:!0,commandId:this.getCommandQueue().enqueue({endpointId:n,payload:s}),status:`pending`});let c=this.getCommandQueue(),l={endpointId:n};r&&(l.status=r);let u=c.dequeue(l);return t({success:!0,endpointId:n,commands:u,count:Array.isArray(u)?u.length:+!!u})}getWebhookServer(){return this.webhookServer||=(this.commandQueue=new A,new P({commandQueue:this.commandQueue})),this.webhookServer}async startWebhookServer(){let e=this.getWebhookServer();e.isRunning()||e.start()}async stopWebhookServer(){this.webhookServer&&(await this.webhookServer.stop(),this.webhookServer=void 0,this.commandQueue=void 0)}getRegistry(){return this.registry||=new C,this.registry}getWebhook(){return this.webhook||=new E,this.webhook}getCommandQueue(){return this.commandQueue||=new A,this.commandQueue}emitEvent(e,t){this.getWebhook().sendEvent(e,t).catch(()=>void 0)}resolveContext(e,t){let n=e[t];if(I(n))return n;let r=e.default;if(t===`default`&&I(r))return r;if(F(r)){let e=r[t];if(I(e))return e}return null}async handleWebhookDispatch(e){let n=i(e,`action`);switch(n){case`create`:return this.handleWebhookCreate(e);case`list`:return this.handleWebhookList();case`delete`:return this.handleWebhookDelete(e);case`commands`:return this.handleWebhookCommands(e);default:return t({error:`Invalid action: "${n}". Expected one of: create, list, delete, commands`})}}};export{L as ExtensionRegistryHandlers};
@@ -0,0 +1,31 @@
1
+ import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-CkodUM4j.mjs";import{t as n}from"./PrerequisiteError-BjCQA-gK.mjs";import{t as r}from"./TraceRecorder-BiJWBXHX.mjs";import{n as i}from"./parse-args-Bw413PlW.mjs";import{t as a}from"./ResponseBuilder-BfWP-uaT.mjs";import{readFile as o,writeFile as s}from"node:fs/promises";const c=(e,t)=>typeof e==`boolean`?e:t,l=(e,t)=>{let n=typeof e==`number`&&Number.isFinite(e)?e:t.defaultValue;return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n},u=(e,t)=>{let n={};for(let r=0;r<e.length;r++)n[e[r]]=t[r];return n},d=e=>{try{return JSON.parse(e)}catch{return e}},f=e=>({timestamp:e.timestamp,wallTime:e.wallTime??null,monotonicTime:e.monotonicTime??null,category:e.category,eventType:e.eventType,data:typeof e.data==`string`?d(e.data):e.data,scriptId:e.scriptId,lineNumber:e.lineNumber,requestId:e.requestId??null,sequence:e.sequence??null}),p=e=>({requestId:e.requestId,url:e.url,method:e.method,resourceType:e.resourceType,requestHeaders:d(e.requestHeaders),requestPostDataPresent:e.requestPostData!==null,status:e.status,statusText:e.statusText,responseHeaders:d(e.responseHeaders),mimeType:e.mimeType,protocol:e.protocol,remoteAddress:e.remoteAddress,fromDiskCache:e.fromDiskCache,fromServiceWorker:e.fromServiceWorker,startedWallTime:e.startedWallTime,responseWallTime:e.responseWallTime,finishedWallTime:e.finishedWallTime,startedMonotonicTime:e.startedMonotonicTime,responseMonotonicTime:e.responseMonotonicTime,finishedMonotonicTime:e.finishedMonotonicTime,encodedDataLength:e.encodedDataLength,receivedDataLength:e.receivedDataLength,receivedEncodedDataLength:e.receivedEncodedDataLength,chunkCount:e.chunkCount,streamingEnabled:e.streamingEnabled,streamingSupported:e.streamingSupported,streamingError:e.streamingError,bodyCaptureState:e.bodyCaptureState,bodySize:e.bodySize,bodyBase64Encoded:e.bodyBase64Encoded,bodyTruncated:e.bodyTruncated,bodyArtifactPath:e.bodyArtifactPath,bodyError:e.bodyError,failed:e.failed,errorText:e.errorText}),m=e=>({sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonicTime,dataLength:e.dataLength,encodedDataLength:e.encodedDataLength,hasChunkData:e.chunkData!==null,chunkPreview:e.chunkData===null?null:`${e.chunkData.slice(0,120)}${e.chunkData.length>120?`...`:``}`,chunkIsBase64:e.chunkIsBase64}),h=async(e,t)=>{if(e.bodyCaptureState===`none`&&e.bodyInline===null&&e.bodyArtifactPath===null)return null;let n=await y(e);if(n===null)return{state:e.bodyCaptureState,error:e.bodyError??`Body content is not available`,truncated:e.bodyTruncated};let r=e.bodySize??n.length;return t.returnSummary||r>t.maxBodyBytes?{state:e.bodyCaptureState,summary:{size:r,sizeKB:(r/1024).toFixed(2),base64Encoded:e.bodyBase64Encoded,preview:`${n.slice(0,500)}${n.length>500?`...`:``}`,truncated:e.bodyTruncated||r>t.maxBodyBytes,reason:t.returnSummary?`Summary mode enabled`:`Response too large (${(r/1024).toFixed(2)} KB > ${(t.maxBodyBytes/1024).toFixed(2)} KB)`}}:{state:e.bodyCaptureState,body:n,base64Encoded:e.bodyBase64Encoded,size:r,sizeKB:(r/1024).toFixed(2),truncated:e.bodyTruncated,...e.bodyError?{warning:e.bodyError}:{}}},g=(e,t,n,r)=>e.query(`
2
+ SELECT
3
+ timestamp,
4
+ category,
5
+ event_type,
6
+ data,
7
+ script_id,
8
+ line_number,
9
+ wall_time,
10
+ monotonic_time,
11
+ request_id,
12
+ sequence
13
+ FROM events
14
+ WHERE ${t} >= ${n} AND ${t} <= ${r}
15
+ ORDER BY ${t} ASC, sequence ASC
16
+ `).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:e[3],scriptId:e[4]??null,lineNumber:e[5]??null,wallTime:e[6]??null,monotonicTime:e[7]??null,requestId:e[8]??null,sequence:e[9]??null})),_=(e,t)=>{let n=e.detailedData;return n?n.smartHandle(t,25600):t},v=(e,t)=>{if(t)return new r({dbPath:t});let n=e.getDB();if(!n)throw Error(`GRACEFUL: No active recording and no dbPath specified. Start a recording or provide a dbPath.`);return n.flush(),n},y=async e=>typeof e.bodyInline==`string`?e.bodyInline:e.bodyArtifactPath?o(e.bodyArtifactPath,`utf8`):null;function b(e,t=`balanced`){if(e.length===0)return{detail:t,totalEvents:0,timeRange:{start:0,end:0,durationMs:0},categories:[],keyMoments:t===`compact`?void 0:[]};let n=e.map(e=>e.timestamp),r=Math.min(...n),i=Math.max(...n),a=new Map;for(let t of e){let e=a.get(t.category);e||(e={count:0,first:t.timestamp,last:t.timestamp,types:new Map},a.set(t.category,e)),e.count++,e.first=Math.min(e.first,t.timestamp),e.last=Math.max(e.last,t.timestamp),e.types.set(t.eventType,(e.types.get(t.eventType)??0)+1)}let o=[...a.entries()].toSorted((e,t)=>t[1].count-e[1].count).map(([e,t])=>({category:e,count:t.count,firstTimestamp:t.first,lastTimestamp:t.last,topEventTypes:[...t.types.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({type:e,count:t}))})),s={detail:t,totalEvents:e.length,timeRange:{start:r,end:i,durationMs:i-r},categories:o};return(t===`balanced`||t===`full`)&&(s.keyMoments=x(e)),s}function x(e){let t=[];for(let n of e)n.eventType===`Debugger.paused`?t.push({timestamp:n.timestamp,type:`breakpoint`,description:`Debugger paused${n.scriptId?` at script ${n.scriptId}`:``}${n.lineNumber?`:${n.lineNumber}`:``}`,data:n.data}):n.eventType===`Network.loadingFinished`?t.push({timestamp:n.timestamp,type:`network_complete`,description:`Network request completed`,data:n.data}):n.eventType===`Runtime.exceptionThrown`?t.push({timestamp:n.timestamp,type:`exception`,description:`Runtime exception thrown`,data:n.data}):(n.eventType===`Page.frameNavigated`||n.eventType===`Page.navigatedWithinDocument`)&&t.push({timestamp:n.timestamp,type:`navigation`,description:`Page navigation`,data:n.data});return t}function S(e){if(e.length===0)return{totalDeltas:0,uniqueAddresses:0,anomalies:[],topAddresses:[]};let t=new Map;for(let n of e)t.set(n.address,(t.get(n.address)??0)+1);let n=t.size,r=e.length,i=r/n,a=[...t.entries()].toSorted((e,t)=>t[1]-e[1]),o=a.slice(0,10).map(([e,t])=>({address:e,writeCount:t})),s=i*3;return{totalDeltas:r,uniqueAddresses:n,anomalies:a.filter(([,e])=>e>s).map(([e,t])=>({address:e,writeCount:t,description:`${t} writes (${(t/i).toFixed(1)}× average)`})),topAddresses:o}}var C=class{recorder;ctx;constructor(e,t){this.recorder=e,this.ctx=t}async handleTraceRecording(e){return i(e,`action`,new Set([`start`,`stop`]))===`stop`?this.handleStopTraceRecording():this.handleStartTraceRecording(e)}async handleStartTraceRecording(e){let t=e.cdpDomains,r=e.recordMemoryDeltas,i=e.recordResponseBodies,o=e.streamResponseChunks,s=e.networkBodyMaxBytes,c=e.networkInlineBodyBytes,l=this.ctx.eventBus;if(!l)throw new n(`EventBus not available on server context`);let u=null;try{if(this.ctx.collector){let e=await this.ctx.collector.getActivePage();typeof e.createCDPSession==`function`&&(u=await e.createCDPSession())}}catch{}let d=await this.recorder.start(l,u,{cdpDomains:t,recordMemoryDeltas:r??!0,ownsSession:u!==null,network:{recordResponseBodies:i,streamResponseChunks:o,maxBodyBytes:s,inlineBodyBytes:c}});return a.ok().merge({status:`recording`,sessionId:d.sessionId,dbPath:d.dbPath,network:{recordResponseBodies:i??!0,streamResponseChunks:o??!0,maxBodyBytes:s??10*1024*1024,inlineBodyBytes:c??256*1024},message:`Recording started. CDP session: ${u?`active`:`not available`}`}).json()}async handleStopTraceRecording(){let e=await this.recorder.stop(),t=e.stoppedAt?e.stoppedAt-e.startedAt:0,n=e.cleanupErrors??[],r=n.length>0?`stopped_with_errors`:`stopped`;return a.ok().merge({status:r,sessionId:e.sessionId,dbPath:e.dbPath,eventCount:e.eventCount,memoryDeltaCount:e.memoryDeltaCount,heapSnapshotCount:e.heapSnapshotCount,networkRequestCount:e.networkRequestCount??0,networkChunkCount:e.networkChunkCount??0,networkBodyCount:e.networkBodyCount??0,durationMs:t,...n.length>0?{cleanupErrors:n}:{},message:n.length>0?`Recording stopped with cleanup errors. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`:`Recording stopped. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`}).json()}async handleQueryTraceSql(t){let i=t.sql,o=t.dbPath;if(!i)throw new e(`VALIDATION`,`sql parameter is required`);let s,c=null;try{if(o)c=new r({dbPath:o}),s=c.query(i);else{let e=this.recorder.getDB();if(!e)throw new n(`No active recording and no dbPath specified. Start a recording or provide a dbPath.`);e.flush(),s=e.query(i)}return a.ok().merge({columns:s.columns,rows:s.rows,rowCount:s.rowCount}).json()}finally{c&&c.close()}}async handleSeekToTimestamp(t){let n=t.timestamp,r=t.dbPath,i=t.windowMs??100,o=t.timeDomain??`wall`;if(!n)throw new e(`VALIDATION`,`timestamp parameter is required`);let s=null;try{let e=v(this.recorder,r);r&&(s=e);let t=o===`monotonic`?`COALESCE(monotonic_time, timestamp)`:`timestamp`,c=o===`monotonic`?`COALESCE(finished_monotonic_time, response_monotonic_time, started_monotonic_time)`:`COALESCE(finished_wall_time, response_wall_time, started_wall_time)`,l=o===`wall`?e.getEventsByTimeRange(n-i,n+i):g(e,t,n-i,n+i),d=e.query(`SELECT * FROM events WHERE category = 'debugger' AND ${t} <= ${n} ORDER BY ${t} DESC, sequence DESC LIMIT 5`),p=o===`wall`?e.query(`SELECT m1.* FROM memory_deltas m1
17
+ INNER JOIN (SELECT address, MAX(timestamp) as max_ts FROM memory_deltas WHERE timestamp <= ${n} GROUP BY address) m2
18
+ ON m1.address = m2.address AND m1.timestamp = m2.max_ts
19
+ ORDER BY m1.address`):null,m=e.query(`SELECT * FROM network_resources
20
+ WHERE ${c} IS NOT NULL AND ${c} <= ${n}
21
+ ORDER BY ${c} DESC
22
+ LIMIT 20`);m.rowCount===0&&(m=e.query(`SELECT * FROM events
23
+ WHERE category = 'network'
24
+ AND event_type = 'Network.loadingFinished'
25
+ AND ${t} <= ${n}
26
+ ORDER BY ${t} DESC
27
+ LIMIT 20`));let h=o===`wall`?e.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE timestamp <= ${n} ORDER BY timestamp DESC LIMIT 1`):null;return a.ok().merge({seekTimestamp:n,timeDomain:o,windowMs:i,events:l.map(f),debuggerState:{recentEvents:d.rows.map(e=>u(d.columns,e))},memoryState:{addressValues:p?.rows.map(e=>u(p.columns,e))??[],...o===`monotonic`?{omittedReason:`Memory state is only indexed by wall-clock timestamps and is omitted for monotonic seeks.`}:{}},networkState:{completedRequests:m.rows.map(e=>u(m.columns,e))},nearestHeapSnapshot:h&&h.rows.length>0?u(h.columns,h.rows[0]):null,...o===`monotonic`?{nearestHeapSnapshotOmittedReason:`Heap snapshots are only indexed by wall-clock timestamps and are omitted for monotonic seeks.`}:{}}).json()}finally{s&&s.close()}}async handleGetTraceNetworkFlow(t){let n=typeof t.requestId==`string`?t.requestId:``,r=t.dbPath,i=c(t.includeBody,!0),o=c(t.includeChunks,!0),s=c(t.includeEvents,!0),u=l(t.chunkLimit,{defaultValue:200,min:1,max:5e3,integer:!0}),d=l(t.maxBodyBytes,{defaultValue:1e5,min:1024,max:50*1024*1024,integer:!0}),g=c(t.returnSummary,!1);if(!n)throw new e(`VALIDATION`,`requestId parameter is required`);let y=null;try{let t=v(this.recorder,r);r&&(y=t);let c=t.getNetworkResource(n);if(!c)throw new e(`NOT_FOUND`,`No recorded network flow found for requestId: ${n}`);let l=o?t.getNetworkChunks(n,u):[],b=s?t.getEventsByRequestId(n):[],x=i?await h(c,{maxBodyBytes:d,returnSummary:g}):null,S=_(this.ctx,{requestId:n,request:p(c),body:x,chunks:o?{total:c.chunkCount,returned:l.length,limit:u,hasMore:c.chunkCount>l.length,items:l.map(m)}:null,events:s?b.map(f):null});return a.ok().merge(S).json()}finally{y&&y.close()}}async handleDiffHeapSnapshots(t){let n=t.snapshotId1,r=t.snapshotId2,i=t.dbPath;if(!n||!r)throw new e(`VALIDATION`,`snapshotId1 and snapshotId2 are required`);let o=null;try{let t=v(this.recorder,i);i&&(o=t);let s=t.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${n}`),c=t.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${r}`);if(s.rowCount===0)throw new e(`NOT_FOUND`,`Snapshot with id ${n} not found`);if(c.rowCount===0)throw new e(`NOT_FOUND`,`Snapshot with id ${r} not found`);let l=u(s.columns,s.rows[0]),f=u(c.columns,c.rows[0]),p=d(l.summary),m=d(f.summary),h=p.objectCounts??{},g=m.objectCounts??{},_=new Set([...Object.keys(h),...Object.keys(g)]),y=[],b=[],x=[];for(let e of _){let t=h[e]??0,n=g[e]??0;t===0&&n>0?y.push({name:e,count:n}):t>0&&n===0?b.push({name:e,count:t}):t!==n&&x.push({name:e,countBefore:t,countAfter:n,delta:n-t})}x.sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta));let S=p.totalSize??0,C=m.totalSize??0;return a.ok().merge({snapshot1:{id:l.id,timestamp:l.timestamp,totalSize:S,nodeCount:p.nodeCount??0},snapshot2:{id:f.id,timestamp:f.timestamp,totalSize:C,nodeCount:m.nodeCount??0},diff:{added:y.slice(0,50),removed:b.slice(0,50),changed:x.slice(0,100),totalSizeDelta:C-S,addedCount:y.length,removedCount:b.length,changedCount:x.length}}).json()}finally{o&&o.close()}}async handleExportTrace(e){let n=e.dbPath,r=e.outputPath,i=null;try{let e=v(this.recorder,n);n&&(i=e);let o=e.query(`SELECT timestamp, category, event_type, data, script_id, line_number FROM events ORDER BY timestamp ASC, sequence ASC`),c=new Set([`Debugger.paused`]),l=new Set([`Debugger.resumed`]),u=o.rows.map(e=>{let t=e[0]*1e3,n=e[1],r=e[2],i=e[3],a=`i`;return c.has(r)?a=`B`:l.has(r)&&(a=`E`),{name:r,cat:n,ph:a,ts:t,pid:1,tid:1,args:d(i),...a===`i`?{s:`g`}:{}}}),f=r||(await t({category:`traces`,toolName:`trace_export`,ext:`json`})).absolutePath;return await s(f,JSON.stringify(u,null,2),`utf-8`),a.ok().merge({exportedPath:f,eventCount:u.length,format:`Chrome Trace Event JSON`,message:`Exported ${u.length} events to ${f}. Open in chrome://tracing or ui.perfetto.dev`}).json()}finally{i&&i.close()}}async handleSummarizeTrace(e){let t=e.detail??`balanced`,i=e.dbPath,o,s=!1;if(i)o=new r({dbPath:i}),s=!0;else if(this.recorder.getState()===`recording`){let e=this.recorder.getDB();if(!e)throw new n(`Active recording has no database`);o=e}else throw new n(`No trace database specified and no active recording`);try{let e=o.query(`SELECT timestamp, category, event_type, data, script_id, line_number, wall_time, monotonic_time, request_id, sequence FROM events ORDER BY timestamp, sequence`).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:typeof e[3]==`string`?d(e[3]):e[3],scriptId:e[4]??void 0,lineNumber:e[5]??void 0})),n=o.query(`SELECT timestamp, address, old_value, new_value, size, value_type FROM memory_deltas ORDER BY timestamp`).rows.map(e=>({timestamp:e[0],address:e[1],oldValue:e[2],newValue:e[3],size:e[4],valueType:e[5]})),r=o.query(`SELECT
28
+ COUNT(*) as requestCount,
29
+ COALESCE(SUM(chunk_count), 0) as chunkCount,
30
+ SUM(CASE WHEN body_capture_state IN ('inline', 'artifact', 'truncated') THEN 1 ELSE 0 END) as bodyCount
31
+ FROM network_resources`);return a.ok().merge({events:b(e,t),memory:S(n),network:r.rows.length>0?u(r.columns,r.rows[0]):{requestCount:0,chunkCount:0,bodyCount:0},metadata:{dbPath:i??`active recording`,generatedAt:new Date().toISOString()}}).json()}finally{s&&o.close()}}};export{C as TraceToolHandlers};
@@ -0,0 +1,54 @@
1
+ import{Jr as e,Yr as t,qr as n}from"./constants-BYj8Xek8.mjs";const r=[`etw`,`strace`,`dtrace`],i=3e3,a={etw:[{syscall:`NtCreateFile`,args:[`C:\\Windows\\Temp\\jshookmcp.log`,`GENERIC_READ`],returnValue:0,duration:.7},{syscall:`NtReadFile`,args:[`handle=0x90`,`buffer=4096`],returnValue:512,duration:.2},{syscall:`NtWriteFile`,args:[`handle=0x90`,`buffer=128`],returnValue:128,duration:.3},{syscall:`NtDeviceIoControlFile`,args:[`handle=0x44`,`code=0x222004`],returnValue:0,duration:1.1}],strace:[{syscall:`openat`,args:[`/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.4},{syscall:`read`,args:[`fd=3`,`count=4096`],returnValue:256,duration:.1},{syscall:`write`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=18`,`127.0.0.1:9222`],returnValue:0,duration:1.4}],dtrace:[{syscall:`open_nocancel`,args:[`/private/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.5},{syscall:`read_nocancel`,args:[`fd=3`,`count=4096`],returnValue:320,duration:.1},{syscall:`write_nocancel`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=21`,`127.0.0.1:9222`],returnValue:0,duration:1.3}]};function o(e){return e===`etw`?process.platform===`win32`:e===`strace`?process.platform===`linux`:e===`dtrace`?process.platform===`darwin`:!1}function s(){return process.platform===`win32`?`etw`:process.platform===`linux`?`strace`:process.platform===`darwin`?`dtrace`:`etw`}function c(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function l(e,t,n,r){let a=!1,o=setTimeout(()=>{if(!a){a=!0;try{r?.()}catch{}n(Error(`${e} did not signal readiness within ${i}ms`))}},i);return{resolveReady(e){a||(a=!0,clearTimeout(o),t(e))},rejectReady(e){a||(a=!0,clearTimeout(o),n(e))}}}function u(e,t){return t?!(t.pid!==void 0&&e.pid!==t.pid||t.name&&t.name.length>0&&!t.name.includes(e.syscall)):!0}function d(e,t,n){let r=/^(\d+)\s+([\d:.]+)\s+(\w+)\(([^)]*)\)\s*=\s*(-?\d+)(?:\s+<([\d.]+)>)?$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[5]),s=r[6]?Number(r[6]):void 0,c=a.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:t,syscall:i,args:c,returnValue:Number.isFinite(o)?o:void 0,duration:s!==void 0&&Number.isFinite(s)?s*1e3:void 0}}function f(e,t,n){let r=/^\[([^\]]+)\]\s+PID=(\d+)\s+(\w+)\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}function p(e,t,n){let r=/^\s*(\d+)\s+\d+\s+(\d+)\s+(\w+):\w+\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}var m=class{activeState;capturedEvents=[];lastBackend=s();subprocessError;async start(e){let t=e?.backend??s(),n=Date.now();if(!o(t))throw Error(`Backend "${t}" is not available on platform "${process.platform}"`);if(e?.simulate??process.env.JSHOOK_SIMULATE===`1`){this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}let r=e?.pid??process.pid,i;try{t===`strace`?i=await this.captureWithStrace(r,n):t===`etw`?i=await this.captureWithETW(r,n):t===`dtrace`&&(i=await this.captureWithDTrace(r,n))}catch(r){this.subprocessError=r instanceof Error?r.message:String(r),this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0,subprocess:i},this.lastBackend=t,this.capturedEvents.length=0,this.subprocessError=void 0}async stop(){this.activeState?.subprocess&&(this.activeState.subprocess.kill(`SIGTERM`),this.activeState.subprocess=void 0),this.activeState=void 0}async captureEvents(e){return this.activeState&&!this.activeState.subprocess&&this.generateSyntheticEvents(),this.capturedEvents.filter(t=>u(t,e)).map(c)}getStats(){let e=this.activeState?.backend??this.lastBackend,t=this.activeState?Date.now()-this.activeState.startedAt:0;return{eventsCaptured:this.capturedEvents.length,uptime:t,backend:e,subprocessActive:!!this.activeState?.subprocess,subprocessError:this.subprocessError}}getSupportedBackends(){return r.filter(e=>o(e))}isRunning(){return this.activeState!==void 0}async captureWithStrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`strace`,[`-p`,String(e),`-f`,`-e`,`trace=all`,`-t`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`strace process`,r,i,()=>a.kill(`SIGTERM`)),s=``,c=``;a.stdout?.on(`data`,t=>{c+=t.toString(),this.processLineBuffer(c,e,`strace`)}),a.stderr?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r)if(n.length>0){let r=d(n,e,t);r&&this.capturedEvents.push(r)}}),a.on(`error`,e=>{o.rejectReady(Error(`strace process error: ${e.message}. Is strace installed?`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithETW(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`logman`,[`create`,`trace`,`JSHookETW_${e}`,`-p`,`NT Kernel Logger`,`0x10000`,`-o`,`jshook_etw_${e}.etl`,`-ets`],{stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),o=l(`ETW trace session`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=f(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t.length>0&&t.startsWith(`The command completed successfully`)}),a.on(`error`,e=>{o.rejectReady(Error(`ETW trace error: ${e.message}. Run as Administrator.`))}),a.on(`exit`,e=>{e!==0&&e!==void 0&&o.rejectReady(Error(`ETW trace session ended (code ${e}). Check permissions.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithDTrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`dtrace`,[`-n`,`
2
+ syscall:::entry
3
+ /pid == ${e}/
4
+ {
5
+ printf("%d %d %s:entry %s", pid, probeproc, probefunc, copyinstr(arg0));
6
+ }
7
+ `],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`dtrace process`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=p(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,()=>{}),a.on(`error`,e=>{o.rejectReady(Error(`dtrace error: ${e.message}. Run with sudo.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}generateSyntheticEvents(){if(!this.activeState)return;let e=a[this.activeState.backend];if(!e)return;let t=Date.now()-this.activeState.startedAt,n=Math.max(1,Math.min(e.length*3,Math.floor(t/150)+1)),r=this.activeState.pid??process.pid;for(;this.activeState.generatedEvents<n;){let t=e[this.activeState.generatedEvents%e.length];if(!t)break;let n=this.activeState.generatedEvents*75;this.capturedEvents.push({timestamp:n,pid:r,syscall:t.syscall,args:[...t.args],returnValue:t.returnValue,duration:t.duration}),this.activeState.generatedEvents+=1}}processLineBuffer(e,t,n){}};const h=[{syscallNames:[`NtCreateFile`,`openat`,`open_nocancel`],jsFunction:`fs.open`,baseConfidence:.8,explanation:`File open syscalls commonly originate from Node.js file-system entry points.`},{syscallNames:[`NtReadFile`,`read`,`read_nocancel`],jsFunction:`fs.readFile`,baseConfidence:.78,explanation:`Read-oriented syscalls usually map back to file or stream reads in JavaScript.`},{syscallNames:[`NtWriteFile`,`write`,`write_nocancel`],jsFunction:`fs.writeFile`,baseConfidence:.78,explanation:`Write-oriented syscalls are strongly associated with Node.js file writes.`},{syscallNames:[`NtDeviceIoControlFile`,`ioctl`],jsFunction:`child_process.spawn`,baseConfidence:.55,explanation:`Device and control syscalls are often triggered by child processes or native helpers.`},{syscallNames:[`connect`,`sendto`,`recvfrom`],jsFunction:`fetch`,baseConfidence:.7,explanation:`Socket syscalls generally indicate outbound network activity from fetch-like APIs.`}];function g(e){return h.find(t=>t.syscallNames.includes(e))}function _(e){return e<0?0:e>1?1:e}function v(e,t){return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}var y=class{map(e){let t=this.findJSFunction(e.syscall);if(!t)return null;let n=g(e.syscall);if(!n)return null;let r=n.baseConfidence;return t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&(r+=.08),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&(r+=.1),{syscall:{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration},jsFunction:t,confidence:_(r),reasoning:this.getCorrelationReason(e,t)}}findJSFunction(e){let t=g(e);return t?t.jsFunction:null}getCorrelationReason(e,t){let n=g(e.syscall),r=[];return n&&r.push(n.explanation),t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&r.push(`The syscall arguments reference module-like file extensions, which strengthens the fs correlation.`),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&r.push(`The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.`),r.length===0&&r.push(`Mapped ${e.syscall} to ${t} using the default syscall-to-JS heuristic table.`),r.join(` `)}};function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e==`number`&&Number.isFinite(e))return e}function S(e){if(typeof e==`boolean`)return e}function C(e){if(typeof e==`string`)return e}function w(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)return;t.push(n)}return t}const T=/^[a-z][a-z0-9_]*$/;function E(e){return T.test(e)&&e.length<=64}function D(e){if(e===`etw`||e===`strace`||e===`dtrace`)return e}function O(e){if(!b(e))return;let t={},n=w(e.name),r=x(e.pid);return n&&(t.name=n),r!==void 0&&(t.pid=r),t}function k(e){if(!b(e))return!1;let t=x(e.timestamp),n=x(e.pid),r=C(e.syscall),i=w(e.args),a=e.returnValue,o=e.duration,s=a===void 0||x(a)!==void 0,c=o===void 0||x(o)!==void 0;return t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0&&s&&c}function A(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function j(e){return e instanceof Error?e.message:`Unknown syscall-hook error`}var M=class{monitor;mapper;eventBus;constructor(e,t,n){this.monitor=e,this.mapper=t,this.eventBus=n}async handleSyscallStartMonitor(e){let t=D(e.backend);if(!t)return{ok:!1,error:`backend must be one of: etw, strace, dtrace`};let n=x(e.pid),r=S(e.simulate)??!1;if(e.pid!==void 0&&e.pid!==null&&(n===void 0||!Number.isInteger(n)||n<0))return{ok:!1,error:`pid must be a non-negative integer when provided`};let i=n,a=this.ensureMonitor();try{return await a.start({backend:t,pid:i,simulate:r}),this.eventBus?.emit(`syscall:trace_started`,{backend:t,pid:i,simulate:r,timestamp:new Date().toISOString()}),{ok:!0,started:!0,backend:t,pid:i,simulate:r,stats:a.getStats()}}catch(e){return{ok:!1,error:j(e),requestedBackend:t,supportedBackends:a.getSupportedBackends()}}}async handleSyscallStopMonitor(){let e=this.ensureMonitor();try{return await e.stop(),{ok:!0,stopped:!0,stats:e.getStats()}}catch(e){return{ok:!1,error:j(e)}}}async handleSyscallCaptureEvents(e){let t=this.ensureMonitor(),n=O(e.filter),r=await t.captureEvents(n);return{ok:!0,events:r,count:r.length,stats:t.getStats()}}async handleSyscallCorrelateJs(e){let t=e.syscallEvents;if(!Array.isArray(t)||!t.every(e=>k(e)))return{ok:!1,error:`syscallEvents must be an array of valid SyscallEvent objects`};let n=this.ensureMapper(),r=[],i=[];for(let e of t){let t=A(e),a=n.map(t);a?r.push(a):i.push(t)}return{ok:!0,correlations:r,matched:r.length,unmatched:i}}async handleSyscallFilter(e){let t=w(e.names);if(e.names!==void 0&&t===void 0)return{ok:!1,error:`names must be an array of strings when provided`};let n=await this.ensureMonitor().captureEvents(t&&t.length>0?{name:t}:void 0);return{ok:!0,names:t,events:n,count:n.length}}async handleSyscallGetStats(){let e=this.ensureMonitor();return{ok:!0,...e.getStats(),running:e.isRunning(),supportedBackends:e.getSupportedBackends()}}async handleSyscallEbpfTrace(r){let i=x(r.pid),a=w(r.syscalls),o=x(r.durationSec)??n,s=S(r.simulate)??!1;if(r.pid!==void 0&&r.pid!==null&&(i===void 0||!Number.isInteger(i)||i<0))return{ok:!1,error:`pid must be a non-negative integer (0 for all processes)`};let c=i??0;if(o<t||o>e)return{ok:!1,error:`durationSec must be between ${t} and ${e}`};if(a?.length){let e=a.filter(e=>!E(e));if(e.length>0)return{ok:!1,error:`Invalid syscall names (must be lowercase alphanumeric with underscores): ${e.join(`, `)}`}}if(s){let e=[],t=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`],n=o*50;for(let r=0;r<20;r++)e.push({timestamp:r*n,pid:c||1234,syscall:t[r%t.length]??`read`,args:[`fd=${r%5+3}`,`count=${(r+1)*64}`],returnValue:r%3==0?-1:(r+1)*64,duration:Math.random()*2});return{ok:!0,backend:`ebpf`,simulated:!0,pid:c,durationSec:o,events:e,count:e.length,syscallsTraced:t}}let l=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`,`connect`,`sendto`,`recvfrom`,`clone`,`execve`],u=c>0?`/pid == ${c}/`:``,d=l.map(e=>`tracepoint:syscalls:sys_enter_${e}`).join(`, `),f=l.map(e=>`tracepoint:syscalls:sys_exit_${e}`).join(`, `),p=`#!/usr/bin/env bpftrace
8
+ // Generated by jshookmcp syscall_ebpf_trace
9
+ // Target PID: ${c||`all`} | Duration: ${o}s | Syscalls: ${l.join(`, `)}
10
+
11
+ BEGIN {
12
+ printf("=== eBPF syscall trace started (pid=${c||`all`}, duration=${o}s) ===\\n");
13
+ }
14
+
15
+ ${d} ${u}
16
+ {
17
+ @enter_ts[tid] = nsecs;
18
+ printf("{\\"timestamp\\": %llu, \\"pid\\": %d, \\"tid\\": %d, \\"syscall\\": \\"%s\\", \\"phase\\": \\"enter\\", \\"args\\": {",
19
+ elapsed / 1000000, pid, tid, probe);
20
+ // Log key arguments based on syscall
21
+ if (probe == "tracepoint:syscalls:sys_enter_openat" || probe == "tracepoint:syscalls:sys_enter_open") {
22
+ printf("\\"pathname\\": \\"%s\\", \\"flags\\": %d, \\"mode\\": %d", args->pathname, args->flags, args->mode);
23
+ } else if (probe == "tracepoint:syscalls:sys_enter_read" || probe == "tracepoint:syscalls:sys_enter_write") {
24
+ printf("\\"fd\\": %d, \\"count\\": %d", args->fd, args->count);
25
+ } else if (probe == "tracepoint:syscalls:sys_enter_connect") {
26
+ printf("\\"fd\\": %d", args->fd);
27
+ } else if (probe == "tracepoint:syscalls:sys_enter_mmap") {
28
+ printf("\\"addr\\": %llu, \\"length\\": %llu, \\"prot\\": %d, \\"flags\\": %d, \\"fd\\": %d", args->addr, args->length, args->prot, args->flags, args->fd);
29
+ } else if (probe == "tracepoint:syscalls:sys_enter_execve") {
30
+ printf("\\"filename\\": \\"%s\\"", args->filename);
31
+ } else {
32
+ printf("\\"raw_args\\": \\"(see bpftrace -v output)\\"");
33
+ }
34
+ printf("}}\\n");
35
+ }
36
+
37
+ ${f} ${u}
38
+ {
39
+ $elapsed_ns = nsecs - @enter_ts[tid];
40
+ printf("{\\"timestamp\\": %llu, \\"pid\\": %d, \\"tid\\": %d, \\"syscall\\": \\"%s\\", \\"phase\\": \\"exit\\", \\"ret\\": %d, \\"duration_us\\": %llu}\\n",
41
+ elapsed / 1000000, pid, tid, probe, args->ret, $elapsed_ns / 1000);
42
+ delete(@enter_ts[tid]);
43
+ }
44
+
45
+ interval:s:${o} {
46
+ printf("=== Trace duration (${o}s) elapsed, exiting ===\\n");
47
+ exit();
48
+ }
49
+
50
+ END {
51
+ printf("=== eBPF syscall trace complete ===\\n");
52
+ clear(@enter_ts);
53
+ }
54
+ `;return{ok:!0,backend:`ebpf`,mode:`script`,pid:c,durationSec:o,syscallCount:l.length,syscallsTraced:l,script:p,usage:`bpftrace -e '${p.replace(/'/g,`'\\''`)}'`,note:`Run the generated bpftrace script on a Linux system with bpftrace installed and CAP_BPF/root privileges.`,requiredCapabilities:[`CAP_BPF`,`root`,`bpftrace`]}}ensureMonitor(){return this.monitor||=new m,this.monitor}ensureMapper(){return this.mapper||=new y,this.mapper}};export{M as SyscallHookHandlers};