@jshookmcp/jshook 0.3.2 → 0.3.4

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 (357) hide show
  1. package/README.md +19 -4
  2. package/README.zh.md +19 -4
  3. package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
  4. package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
  5. package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
  6. package/dist/CodeInjector-B099WO6x.mjs +1 -0
  7. package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
  8. package/dist/CpuEngine-BC8jayy9.mjs +1 -0
  9. package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
  10. package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
  11. package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
  12. package/dist/DetailedDataManager-Dgh402Gp.mjs +5 -0
  13. package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
  14. package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
  15. package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
  16. package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
  17. package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
  18. package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
  19. package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
  20. package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
  21. package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
  22. package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
  23. package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
  24. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  25. package/dist/MemoryController-CCsGuGJS.mjs +2 -0
  26. package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
  27. package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
  28. package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
  29. package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
  30. package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
  31. package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
  32. package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
  33. package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
  34. package/dist/{handlers-mPFiNPe8.mjs → QuickJSSandbox-CIde-jzG.mjs} +2 -5
  35. package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
  36. package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
  37. package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
  38. package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
  39. package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
  40. package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
  41. package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
  42. package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
  43. package/dist/ToolRouter.policy-Bgb3S8jc.mjs +4 -0
  44. package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
  45. package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
  46. package/dist/Win32API-G7QPyckq.mjs +1 -0
  47. package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
  48. package/dist/allocation-track-CiI-CnaI.mjs +1 -0
  49. package/dist/analysis-CojUzwX-.mjs +27 -0
  50. package/dist/antidebug-CgU84TE1.mjs +1 -0
  51. package/dist/apk-DrPBsOq8.mjs +1 -0
  52. package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
  53. package/dist/artifacts-Bx9GLx4J.mjs +1 -0
  54. package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
  55. package/dist/ast-utils-B9E5k_v1.mjs +1 -0
  56. package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
  57. package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
  58. package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
  59. package/dist/browser-QDUu5ML9.mjs +29 -0
  60. package/dist/{handlers-yo_xYzT8.mjs → canvas-g5kmLdY-.mjs} +1098 -24
  61. package/dist/{capabilities-CyXuKUl1.mjs → capabilities-DwzyxL2w.mjs} +1 -1
  62. package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
  63. package/dist/collector-Cld4i-E4.mjs +1 -0
  64. package/dist/config-5ODJ3Aj0.mjs +3 -0
  65. package/dist/constants-nvsLpSri.mjs +1 -0
  66. package/dist/coordination-C6y2gM9O.mjs +98 -0
  67. package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
  68. package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
  69. package/dist/debugger-C2SpiXoO.mjs +1 -0
  70. package/dist/definitions-0mtilYzG.mjs +1 -0
  71. package/dist/definitions-9csunmeX.mjs +1 -0
  72. package/dist/definitions-B11MudW_.mjs +1 -0
  73. package/dist/definitions-BKpRDjcI.mjs +1 -0
  74. package/dist/definitions-BXE3H4re.mjs +1 -0
  75. package/dist/definitions-BlPHe5DX.mjs +1 -0
  76. package/dist/definitions-Bob4XMxI.mjs +27 -0
  77. package/dist/definitions-BpIQN2nm.mjs +1 -0
  78. package/dist/definitions-BvolWeSu.mjs +1 -0
  79. package/dist/definitions-C-6j3Ejl.mjs +1 -0
  80. package/dist/definitions-C-AdFfFu.mjs +1 -0
  81. package/dist/definitions-CArdw_9T.mjs +1 -0
  82. package/dist/definitions-CCvIcRrT.mjs +1 -0
  83. package/dist/definitions-CJPE5PIl.mjs +1 -0
  84. package/dist/definitions-CbqeW06u.mjs +1 -0
  85. package/dist/definitions-Cexmkypg.mjs +1 -0
  86. package/dist/definitions-D1dxl8qt.mjs +1 -0
  87. package/dist/definitions-D3uT-ZbU.mjs +1 -0
  88. package/dist/definitions-DtOY5iUc.mjs +1 -0
  89. package/dist/{definitions-DxFNRQNK2.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
  90. package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
  91. package/dist/definitions-ihxOqOC4.mjs +1 -0
  92. package/dist/deopt-trace-qnAcC931.mjs +17 -0
  93. package/dist/disasm-DoxSucGp.mjs +1 -0
  94. package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
  95. package/dist/encoding-UMtwgy4M.mjs +2 -0
  96. package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
  97. package/dist/factory-BeND77hf.mjs +2 -0
  98. package/dist/graphql-CF7QKJME.mjs +68 -0
  99. package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
  100. package/dist/handlers--qCl9vNv.mjs +1 -0
  101. package/dist/handlers-BHIu1LqA.mjs +1 -0
  102. package/dist/{antidebug-7L3ygj_9.mjs → handlers-BQ4K8Jbr.mjs} +2 -2
  103. package/dist/handlers-BxQv-wtf.mjs +8 -0
  104. package/dist/handlers-ByYG27-5.mjs +1 -0
  105. package/dist/handlers-C0I9-BtX.mjs +5 -0
  106. package/dist/handlers-CL0Iokmw.mjs +1 -0
  107. package/dist/handlers-CNbhIdSK.mjs +4 -0
  108. package/dist/handlers-CnTTSJFs.mjs +109 -0
  109. package/dist/handlers-CoDx6akJ2.mjs +49 -0
  110. package/dist/{handlers-0yKLRIfo.mjs → handlers-DASJI0Pn.mjs} +1 -1
  111. package/dist/handlers-DRKMaA-_.mjs +74 -0
  112. package/dist/handlers-Dalu0olz.mjs +2 -0
  113. package/dist/handlers-KY0g31ny.mjs +9 -0
  114. package/dist/handlers-oGo60aVv.mjs +1 -0
  115. package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
  116. package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
  117. package/dist/{hooks-D4XLfgtV.mjs → hooks-COK3t5rT.mjs} +52 -33
  118. package/dist/index.mjs +11 -11
  119. package/dist/logger-BGCcd-jJ.mjs +1 -0
  120. package/dist/macro-nUYUjKNZ.mjs +2 -0
  121. package/dist/maintenance-CfnE7ZKU.mjs +4 -0
  122. package/dist/manifest-7EOTUc0D.mjs +1 -0
  123. package/dist/manifest-B5ujuQmf.mjs +1 -0
  124. package/dist/manifest-BErXl3zn.mjs +1 -0
  125. package/dist/manifest-BKA-mD3J.mjs +1 -0
  126. package/dist/manifest-BUXj23bX.mjs +1 -0
  127. package/dist/manifest-BfXt9cau.mjs +1 -0
  128. package/dist/manifest-Bx-tpURK.mjs +1 -0
  129. package/dist/manifest-C0owVAdq.mjs +1 -0
  130. package/dist/manifest-C5XqYc9o.mjs +1 -0
  131. package/dist/manifest-CVKzLjsA.mjs +1 -0
  132. package/dist/manifest-CaeFjdhj.mjs +1 -0
  133. package/dist/manifest-CegBgip0.mjs +1 -0
  134. package/dist/manifest-CoJHqlgS.mjs +1 -0
  135. package/dist/manifest-D0dbtDqd.mjs +1 -0
  136. package/dist/manifest-D5Gr8ujd.mjs +12 -0
  137. package/dist/manifest-D82z-5og.mjs +1 -0
  138. package/dist/manifest-DA2afIwh.mjs +1 -0
  139. package/dist/manifest-DAbiFP5o.mjs +1 -0
  140. package/dist/manifest-DEY0s1O72.mjs +1 -0
  141. package/dist/manifest-DTOqNqiA.mjs +1 -0
  142. package/dist/manifest-DZ6ELNgX.mjs +1 -0
  143. package/dist/manifest-DjHkjddT.mjs +1 -0
  144. package/dist/manifest-DocA_itf2.mjs +1 -0
  145. package/dist/manifest-Dpnhvfq0.mjs +1 -0
  146. package/dist/manifest-DucPMG_a.mjs +1 -0
  147. package/dist/manifest-Dw5yYEac.mjs +1 -0
  148. package/dist/manifest-Ic_Cg66S.mjs +1 -0
  149. package/dist/manifest-JHaG6GMN.mjs +1 -0
  150. package/dist/manifest-QdkIzmYM.mjs +1 -0
  151. package/dist/manifest-YZqaCe25.mjs +1 -0
  152. package/dist/manifest-f0lUeXwq.mjs +1 -0
  153. package/dist/manifest-h-Ebisf8.mjs +1 -0
  154. package/dist/manifest-oOfTymBS.mjs +1 -0
  155. package/dist/manifest-qXqrO6KC.mjs +2 -0
  156. package/dist/mapsParser-DrJoeC0c.mjs +1 -0
  157. package/dist/modules-CC_ADmwi.mjs +333 -0
  158. package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
  159. package/dist/native-D9ouskXO.mjs +961 -0
  160. package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
  161. package/dist/network-C5Y-S87J.mjs +7 -0
  162. package/dist/one-gadget-CiWFE17F.mjs +1 -0
  163. package/dist/outputPaths-CHtELDyi.mjs +1 -0
  164. package/dist/parse-args-B6dwWc9k.mjs +1 -0
  165. package/dist/platform-BIXgJaM3.mjs +94 -0
  166. package/dist/process-aDIfLC0v.mjs +6 -0
  167. package/dist/proxy-DsHsQ1I4.mjs +2 -0
  168. package/dist/registry-7h8jJ9y9.mjs +1 -0
  169. package/dist/{registry-DH4sc1dt.mjs → registry-DJDnkQW2.mjs} +1 -1
  170. package/dist/response-R8ghbZSb.mjs +1 -0
  171. package/dist/retry-policy-DtYv0kDi.mjs +1 -0
  172. package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
  173. package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
  174. package/dist/search-defaults-BBRJNAzC.mjs +1 -0
  175. package/dist/server/plugin-api.mjs +1 -1
  176. package/dist/server/search/EmbeddingWorker.d.mts +1 -0
  177. package/dist/server/search/EmbeddingWorker.mjs +1 -0
  178. package/dist/shared-BKtWZDGN.mjs +1 -0
  179. package/dist/sourcemap-2VIeVeKw.mjs +3 -0
  180. package/dist/streaming-DkpE3GGU.mjs +15 -0
  181. package/dist/syscall-DGZoYM_U.mjs +1 -0
  182. package/dist/transform-BJqsBC_-.mjs +105 -0
  183. package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
  184. package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
  185. package/dist/types-CWSvzmIh.mjs +1 -0
  186. package/dist/v8-inspector-CTJo08-K.mjs +297 -0
  187. package/dist/wasm-DX4Qm2Vs.mjs +235 -0
  188. package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
  189. package/dist/webgpu-D4-DxbxZ.mjs +6 -0
  190. package/dist/workflow-DHktRNF2.mjs +108 -0
  191. package/package.json +33 -27
  192. package/dist/AntiCheatDetector-B6d4Qe9D.mjs +0 -1
  193. package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
  194. package/dist/ConsoleMonitor-CxDJV15E.mjs +0 -306
  195. package/dist/DOMInspector-C19J4zeq.mjs +0 -95
  196. package/dist/DarwinAPI-ZfQdpLNI.mjs +0 -1
  197. package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
  198. package/dist/ExtensionManager-BD724zkO.mjs +0 -1
  199. package/dist/ExtensionManager.tools-oVMJgPcN.mjs +0 -1
  200. package/dist/FingerprintManager-DT0EAUEo.mjs +0 -1
  201. package/dist/HardwareBreakpoint-BUfPdp0f.mjs +0 -1
  202. package/dist/HeapAnalyzer-B_aqY8oj.mjs +0 -1
  203. package/dist/InstrumentationSession-D_G1ZPyd.mjs +0 -1
  204. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
  205. package/dist/MemoryController-X1XNSn1n.mjs +0 -2
  206. package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
  207. package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
  208. package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
  209. package/dist/PEAnalyzer-yWQaGrcx.mjs +0 -1
  210. package/dist/PageController-Dfsm1_o7.mjs +0 -1
  211. package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
  212. package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
  213. package/dist/ProcessRegistry-C-bN48oR.mjs +0 -1
  214. package/dist/ReverseEvidenceGraph-BhSYYdiI.mjs +0 -2
  215. package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
  216. package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
  217. package/dist/Speedhack-yseDPSZ9.mjs +0 -1
  218. package/dist/StructureAnalyzer-C5lpuZkg.mjs +0 -2
  219. package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
  220. package/dist/ToolRegistry-C5oB8KP8.mjs +0 -1
  221. package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
  222. package/dist/TraceRecorder-BiJWBXHX.mjs +0 -272
  223. package/dist/VersionDetector-CHT36Az0.mjs +0 -9
  224. package/dist/Win32API-eUCF57l_.mjs +0 -1
  225. package/dist/WorkflowEngine-D876meOO.mjs +0 -1
  226. package/dist/analysis-D4swdMvq.mjs +0 -6
  227. package/dist/apk-packer-BqXcInnX.mjs +0 -1
  228. package/dist/artifactRetention-BCPQASm7.mjs +0 -1
  229. package/dist/artifacts-CkodUM4j.mjs +0 -1
  230. package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
  231. package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
  232. package/dist/boringssl-inspector-BBaJwwkU.mjs +0 -2
  233. package/dist/browser-Qqco2rOT.mjs +0 -11
  234. package/dist/collector-Bpl6qy2L.mjs +0 -1
  235. package/dist/constants-BYj8Xek8.mjs +0 -1
  236. package/dist/coordination-CWXW1o8K.mjs +0 -1
  237. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  238. package/dist/debugger-DyALjYMk.mjs +0 -1
  239. package/dist/definitions-BWxBke3r.mjs +0 -1
  240. package/dist/definitions-BYwATKc-.mjs +0 -1
  241. package/dist/definitions-B_83XfNQ.mjs +0 -1
  242. package/dist/definitions-Bf3H1EwV.mjs +0 -1
  243. package/dist/definitions-BftdXgXI.mjs +0 -1
  244. package/dist/definitions-Bio5XJYy.mjs +0 -1
  245. package/dist/definitions-C3qNgSn1.mjs +0 -1
  246. package/dist/definitions-CB6vmOer.mjs +0 -1
  247. package/dist/definitions-CMZRSy3k.mjs +0 -1
  248. package/dist/definitions-CQd7yCQH.mjs +0 -1
  249. package/dist/definitions-CT8ln6GQ.mjs +0 -1
  250. package/dist/definitions-D4g-MS10.mjs +0 -1
  251. package/dist/definitions-D5wl_8HN.mjs +0 -1
  252. package/dist/definitions-DAQm1Xar.mjs +0 -1
  253. package/dist/definitions-DP1vgxEY.mjs +0 -1
  254. package/dist/definitions-Ibci7e_L.mjs +0 -1
  255. package/dist/definitions-OeLvmlQy.mjs +0 -1
  256. package/dist/definitions-RZYGD_Ey.mjs +0 -1
  257. package/dist/definitions-Tls8c0A0.mjs +0 -1
  258. package/dist/definitions-bybDvnG0.mjs +0 -26
  259. package/dist/definitions-l7TjdE6V.mjs +0 -1
  260. package/dist/encoding-ycOaz8Vr.mjs +0 -2
  261. package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
  262. package/dist/factory-CKr4fAE1.mjs +0 -1
  263. package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
  264. package/dist/graphql-B2TiPEow.mjs +0 -62
  265. package/dist/handlers-8zN_vBIz.mjs +0 -1
  266. package/dist/handlers-B62K4FTc.mjs +0 -1
  267. package/dist/handlers-BpDlVVVU.mjs +0 -1
  268. package/dist/handlers-CMJK7m1c.mjs +0 -31
  269. package/dist/handlers-D2ZOul9p.mjs +0 -54
  270. package/dist/handlers-D5E40ssn.mjs +0 -5
  271. package/dist/handlers-DGbdQAgD.mjs +0 -4
  272. package/dist/handlers-DHO3rjsW.mjs +0 -1
  273. package/dist/handlers-FJ80VzUI.mjs +0 -2
  274. package/dist/handlers-VHWrxbM_.mjs +0 -1
  275. package/dist/handlers-l8QIKqBj.mjs +0 -2
  276. package/dist/handlers.impl-D9Hh8Bgl.mjs +0 -1
  277. package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
  278. package/dist/logger-sBC6IdRT.mjs +0 -1
  279. package/dist/maintenance-BUpIukhg.mjs +0 -1
  280. package/dist/manifest-0Jpt_AQa.mjs +0 -1
  281. package/dist/manifest-B3fZbSWR.mjs +0 -1
  282. package/dist/manifest-B7NB2rh2.mjs +0 -1
  283. package/dist/manifest-BDi4nbH1.mjs +0 -1
  284. package/dist/manifest-BLDfkE7n.mjs +0 -1
  285. package/dist/manifest-BcXbB4gf.mjs +0 -1
  286. package/dist/manifest-Bdnc_vrc.mjs +0 -1
  287. package/dist/manifest-BuYKgCnp.mjs +0 -1
  288. package/dist/manifest-CBfNnGPV.mjs +0 -1
  289. package/dist/manifest-CPS1Xv69.mjs +0 -1
  290. package/dist/manifest-CQH9FhwI.mjs +0 -1
  291. package/dist/manifest-CRryuZF4.mjs +0 -1
  292. package/dist/manifest-CctIumog.mjs +0 -1
  293. package/dist/manifest-CvTe5ZGV2.mjs +0 -1
  294. package/dist/manifest-D-5GH0DV.mjs +0 -1
  295. package/dist/manifest-D3Ssf3IC.mjs +0 -1
  296. package/dist/manifest-D5ck3NvC.mjs +0 -1
  297. package/dist/manifest-D9jUUJAu.mjs +0 -1
  298. package/dist/manifest-DCx6w2XV.mjs +0 -1
  299. package/dist/manifest-DG19q-Ld.mjs +0 -1
  300. package/dist/manifest-DLMlD0Zc.mjs +0 -1
  301. package/dist/manifest-DYpn8w_h.mjs +0 -1
  302. package/dist/manifest-DYzWI8Xs.mjs +0 -1
  303. package/dist/manifest-D_obs5F4.mjs +0 -1
  304. package/dist/manifest-DujQqEQR.mjs +0 -2
  305. package/dist/manifest-DwL2ik8P.mjs +0 -1
  306. package/dist/manifest-ItF5P8A12.mjs +0 -1
  307. package/dist/manifest-KZphqIyX.mjs +0 -1
  308. package/dist/manifest-LG42zPLY2.mjs +0 -1
  309. package/dist/manifest-LLdI5m4T.mjs +0 -1
  310. package/dist/manifest-QYbQXJn0.mjs +0 -1
  311. package/dist/manifest-RcpX_MyZ.mjs +0 -123
  312. package/dist/manifest-YgVd8Sgz.mjs +0 -1
  313. package/dist/manifest-Zy7Odg5J.mjs +0 -1
  314. package/dist/manifest-ff1H7Pdp.mjs +0 -1
  315. package/dist/manifest-iuhF6pTL2.mjs +0 -1
  316. package/dist/manifest-nXHmtMSp2.mjs +0 -1
  317. package/dist/manifest-xWfu6iLo.mjs +0 -1
  318. package/dist/manifest-yC16OhL2.mjs +0 -1
  319. package/dist/manifest-ztWJoXy4.mjs +0 -1
  320. package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
  321. package/dist/modules-BPBcSaM-.mjs +0 -333
  322. package/dist/mojo-ipc-BhwsdVUW.mjs +0 -9
  323. package/dist/native-j8l473zn.mjs +0 -961
  324. package/dist/network-T0VRwNPd.mjs +0 -7
  325. package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
  326. package/dist/parse-args-Bw413PlW.mjs +0 -1
  327. package/dist/platform-CzaQtISh.mjs +0 -93
  328. package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
  329. package/dist/process-CWhsCWrf.mjs +0 -2
  330. package/dist/proxy-DZFlDsG3.mjs +0 -2
  331. package/dist/renderer-pid-9tJnZ_9N.mjs +0 -1
  332. package/dist/response-C7rKQst4.mjs +0 -1
  333. package/dist/search-defaults-lYBVn_3L.mjs +0 -1
  334. package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
  335. package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
  336. package/dist/streaming-BcJ0B6ao.mjs +0 -1
  337. package/dist/transform-DOxzeWPB.mjs +0 -103
  338. package/dist/types-D9EiE5o9.mjs +0 -1
  339. package/dist/wasm-CZ_HTfKR.mjs +0 -174
  340. package/dist/webcrack-C1iYG_EX.mjs +0 -46
  341. package/dist/workflow-BdwQmARn.mjs +0 -101
  342. /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  343. /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  344. /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  345. /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  346. /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
  347. /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  348. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  349. /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  350. /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  351. /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  352. /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  353. /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  354. /package/dist/{chunk-C_pMuVsO.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
  355. /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  356. /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  357. /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -0,0 +1,68 @@
1
+ import{C as e,E as t,S as n,T as r,w as i}from"./constants-nvsLpSri.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{d as o,v as s}from"./ensure-browser-core-BP70x0TB.mjs";import{c,i as l,n as u,r as d,s as f,t as p}from"./parse-args-B6dwWc9k.mjs";import{r as m}from"./ResponseBuilder-BLicSCjn.mjs";import{c as h}from"./ssrf-policy-B72vdy23.mjs";import"./definitions-CJPE5PIl.mjs";function g(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function _(e,t){let n={success:!1,error:v(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 s;return{content:[{type:`text`,text:JSON.stringify(n,null,2)}],...r?{}:{isError:!0}}}function v(e){return e instanceof Error?e.message:String(e)}function y(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 b(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 x(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 S(e){let t=x(e);return`error`in t?t.error:await h(t.parsedEndpoint.toString())?`Blocked: endpoint "${e}" resolves to a private/reserved address`:null}async function C(e,t){let n=x(e);if(`error`in n)return n.error;if(!await h(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 w(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 T(e,t){let n;if(typeof e==`string`)n=e;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}return w(n,t)}function E(e){return e===`exact`||e===`contains`||e===`regex`?e:`contains`}function D(){return`script_rule_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function O(e){if(typeof e.isInterceptResolutionHandled!=`function`)return!1;try{return e.isInterceptResolutionHandled()}catch{return!1}}async function k(e){if(!O(e))try{await e.continue()}catch{}}function A(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 j(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r&&A(r,t))return r}return null}async function M(e,t){if(O(t))return;if(t.resourceType()!==`script`){await k(t);return}let n=j(e,t.url());if(!n){await k(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 k(t)}}async function N(e,t,n){if(t.has(n))return;await n.setRequestInterception(!0);let r=t=>{M(e,t)},i=n;typeof i.prependListener==`function`?i.prependListener(`request`,r):i.on(`request`,r),t.add(n)}function P(e){let t=[`kind`,`name`];return e>0&&t.push(`ofType { ${P(e-1)} }`),t.join(`
2
+ `)}const F=`
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
+ ${P(7)}
49
+ }
50
+ `.trim(),I=`query FederationServiceQuery {
51
+ _service {
52
+ sdl
53
+ }
54
+ }`;var ee=class{collector;constructor(e){this.collector=e}async handleCallGraphAnalyze(t){try{let r=y(t,`maxDepth`,5,1,20),i=c(t,`filterPattern`)?.trim()||``;if(i)try{RegExp(i)}catch(e){return _(`Invalid filterPattern regex`,{filterPattern:i,reason:e instanceof Error?e.message:String(e)})}let a=await o(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(`
55
+ `).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}),s=a.nodes.length>e,l=a.edges.length>n;return g({success:!0,nodes:a.nodes.slice(0,e),edges:a.edges.slice(0,n),stats:{...a.stats,nodesReturned:Math.min(a.nodes.length,e),edgesReturned:Math.min(a.edges.length,n),nodesTruncated:s,edgesTruncated:l}})}catch(e){return _(e)}}},te=class{collector;scriptReplaceRules=[];interceptionInstalledPages=new WeakSet;constructor(e){this.collector=e}async handleScriptReplacePersist(e){try{let t=c(e,`url`)?.trim(),n=c(e,`replacement`),r=E(e.matchType);if(!t)return _(`Missing required argument: url`);if(typeof n!=`string`||n.length===0)return _(`Missing required argument: replacement`);if(r===`regex`)try{RegExp(t)}catch(e){return _(`Invalid regex in url for matchType=regex`,{url:t,reason:v(e)})}let a=await this.collector.getActivePage(),o={id:D(),url:t,replacement:n,matchType:r,createdAt:Date.now(),hits:0};this.scriptReplaceRules.push(o),await N(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 s=w(n,i);return g({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:s.preview,truncated:s.truncated},activeRuleCount:this.scriptReplaceRules.length})}catch(e){return _(e)}}};function L(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function ne(e){let t=new Set;for(let n of e.matchAll(/@([_A-Za-z][_0-9A-Za-z]*)\b/g))n[1]&&t.add(n[1]);return[...t].toSorted()}function re(e){let t=new Set;for(let n of e.matchAll(/(?:^|\n)\s*(?:extend\s+)?(?:type|interface)\s+([_A-Za-z][_0-9A-Za-z]*)[^{\n]*@key\b/g))n[1]&&t.add(n[1]);return[...t].toSorted()}function R(e){if(!e)return{attempted:!1,supported:!1};let n={attempted:!0,supported:!1,status:e.status,statusText:e.statusText,responseHeaders:e.responseHeaders??{}};e.error&&(n.error=e.error);let r=L(e.json??e.responseJson);r&&Array.isArray(r.errors)&&(n.errors=r.errors);let i=L(L(r?.data)?._service)?.sdl;if(typeof i!=`string`)return n;let a=w(i,t);return n.supported=!0,n.sdlLength=a.totalLength,n.sdlPreview=a.preview,n.sdlTruncated=a.truncated,n.directives=ne(i),n.entityTypes=re(i),a.truncated||(n.sdl=i),n}var ie=class{collector;constructor(e){this.collector=e}async handleGraphqlIntrospect(e){try{let t=c(e,`endpoint`)?.trim();if(!t)return _(`Missing required argument: endpoint`);let n=b(e.headers),r=u(e,`useBrowser`,!0),i=u(e,`includeFederation`,!0);if(r){let e=await this.collector.getActivePage(),r=await C(t,typeof e.url==`function`?e.url():null);return r?_(r):await this.introspectViaBrowser(e,t,n,i)}let a=await S(t);return a?_(a):await this.introspectViaNode(t,n,i)}catch(e){return _(e)}}async postGraphqlViaNode(e,t,n,r){let i,a;try{let o=new AbortController,s=setTimeout(()=>o.abort(),1e4);try{i=await fetch(e,{method:`POST`,headers:t,body:JSON.stringify({query:n,operationName:r}),signal:o.signal}),a=await i.text()}finally{clearTimeout(s)}}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)}}let o={};i.headers.forEach((e,t)=>{o[t]=e});let s=a.length,c=null;try{c=JSON.parse(a)}catch{}let l=c===null?a:``;return a=``,{ok:i.ok,status:i.status,statusText:i.statusText,responseHeaders:o,totalLength:s,preview:l,truncated:!1,json:c}}async introspectViaNode(e,n,r){let a={"content-type":`application/json`,...n},o=await this.postGraphqlViaNode(e,a,F,`IntrospectionQuery`),s=r?await this.postGraphqlViaNode(e,a,I,`FederationServiceQuery`):void 0;if(!o.ok&&!o.json)return g({success:!1,endpoint:e,status:o.status,statusText:o.statusText,error:o.error??`Introspection request failed`,responsePreview:w(o.preview||``,i),...r?{federation:R(s)}:{}});let c=o.json,l=L(c),u=l&&`data`in l?l.data:c,d=c!=null&&u!==void 0?T(u,t):{preview:``,truncated:!1,totalLength:0},f={success:o.ok,endpoint:e,status:o.status,statusText:o.statusText,schemaLength:d.totalLength,schemaPreview:d.preview,schemaTruncated:d.truncated,responseHeaders:o.responseHeaders??{}};return d.truncated||(f.schema=u),l&&Array.isArray(l.errors)&&(f.errors=l.errors),r&&(f.federation=R(s)),g(f)}async introspectViaBrowser(e,n,r,a){let s=await o(e,async e=>{let t={"content-type":`application/json`,...e.headers},n=async(n,r)=>{let i=new AbortController,a=setTimeout(()=>i.abort(),1e4),o,s;try{s=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:n,operationName:r}),signal:i.signal}),o=await s.text()}finally{clearTimeout(a)}let c={};s.headers.forEach((e,t)=>{c[t]=e});let l=o.length,u=null;try{u=JSON.parse(o)}catch{}let d=u===null?o:``;return o=``,{ok:s.ok,status:s.status,statusText:s.statusText,responseHeaders:c,totalLength:l,preview:d,truncated:!1,json:u}};try{let t=await n(e.query,`IntrospectionQuery`);if(!e.includeFederation)return t;let r=await n(e.federationQuery,`FederationServiceQuery`);return{...t,federation:r}}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:n,headers:r,query:F,federationQuery:I,includeFederation:a,maxSchemaChars:t});if(!s.ok&&!s.json)return g({success:!1,endpoint:n,status:s.status,statusText:s.statusText,error:s.error??`Introspection request failed`,responsePreview:w(s.preview||``,i),...a?{federation:R(s.federation)}:{}});let c=L(s.json),l=c&&`data`in c?c.data:s.json,u=s.json!==null&&s.json!==void 0&&l!==void 0?T(l,t):{preview:s.preview??``,truncated:s.truncated??!1,totalLength:s.totalLength??0},d={success:s.ok,endpoint:n,status:s.status,statusText:s.statusText,schemaLength:u.totalLength,schemaPreview:u.preview,schemaTruncated:u.truncated,responseHeaders:s.responseHeaders??{}};return u.truncated||(d.schema=l),c&&Array.isArray(c.errors)&&(d.errors=c.errors),a&&(d.federation=R(s.federation)),s.error&&(d.error=s.error),g(d)}};const z=/\.\.\.|[{}()[\]:,@!|]|[_A-Za-z][_0-9A-Za-z]*|-?\d+(?:\.\d+)?/g,B=new Set([`query`,`mutation`,`subscription`]),V=/^[_A-Za-z][_0-9A-Za-z]*$/,ae=new Set([`:`,`on`,`@`,`...`]);function oe(e){let t=``,n=0,r=e.length;for(;n<r;){let i=e[n];if(i===`#`){for(;n<r&&e[n]!==`
56
+ `;)n+=1;continue}if(i===`"`){if(e[n+1]===`"`&&e[n+2]===`"`){for(n+=3;n<r;){if(e[n]===`"`&&e[n+1]===`"`&&e[n+2]===`"`){n+=3;break}n+=1}t+=`""`;continue}for(n+=1;n<r&&e[n]!==`"`&&e[n]!==`
57
+ `;)e[n]===`\\`&&(n+=1),n+=1;n+=1,t+=`""`;continue}t+=i,n+=1}return t}function se(e){return z.lastIndex=0,e.match(z)??[]}function ce(e){let t=new Set,n=new Set,r=i=>{if(n.has(i))return!0;if(t.has(i))return!1;t.add(i),n.add(i);let a=e.get(i);if(a){for(let t of a)if(e.has(t)&&r(t))return!0}return n.delete(i),!1};for(let t of e.keys())if(r(t))return!0;return!1}function le(e){let t=se(oe(typeof e==`string`?e:``)),n=`unknown`,r=null,i=-1,a=[],o=0,s=0,c=0,l=``,u=!1,d=null,f=0,p=0,m=0,h=new Map;for(let e=0;e<t.length;e+=1){let g=t[e];if(g){if(g===`(`){s+=1,l=`(`;continue}if(g===`)`){s>0&&--s,l=`)`;continue}if(g===`[`){c+=1,l=`[`;continue}if(g===`]`){c>0&&--c,l=`]`;continue}if(!(s>0||c>0)){if(g===`{`){i+=1,a[i]===void 0&&(a[i]=0),l=`{`;continue}if(g===`}`){i===0&&u&&(u=!1,d=null),i>=0&&--i,l=`}`;continue}if(g===`,`){l=`,`;continue}if(g===`...`){let n=t[e+1];if(n===`on`)m+=1;else if(n!==void 0&&V.test(n)&&(p+=1,d)){let e=h.get(d)??[];e.push(n),h.set(d,e)}l=`...`;continue}if(e===0&&B.has(g)){n=g,l=g;continue}if(B.has(l)&&V.test(g)){r=g,l=g;continue}if(g===`fragment`&&i<0){let n=t[e+1];n&&V.test(n)&&n!==`on`&&(d=n,f+=1,h.set(n,[]),u=!0),l=`fragment`;continue}if(g===`on`||g===`@`){l=g;continue}if(i>=0&&!u&&V.test(g)){if(ae.has(l)){l=g;continue}n===`unknown`&&(n=`query`),a[i]=(a[i]??0)+1,o+=1,l=g;continue}l=g}}}let g=a.length;for(;g>0&&(a[g-1]??0)===0;)--g;let _=a.slice(0,g),v=_.reduce((e,t)=>t>e?t:e,0),y=_.reduce((e,t,n)=>e+t*(n+1),0);return{operationType:n,operationName:r,depth:g,breadthByLevel:_,maxBreadth:v,totalFields:o,costScore:y,fragments:{definitions:f,spreads:p,inline:m},hasCycle:ce(h)}}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(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 ue(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(H(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 de(e){return H(e.headers)?e.headers:H(e.requestHeaders)?e.requestHeaders:{}}function fe(e){let t=de(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 pe(e){let t=[e.body,e.postData];return H(e.options)&&t.push(e.options.body),H(e.request)&&t.push(e.request.postData),t}function W(e,t){let n={scannedRecords:0,extracted:[]};if(!Array.isArray(e))return n;for(let r of e){if(!H(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=fe(r);for(let s of pe(r)){let r=null;H(s)?r=s:typeof s==`string`&&(r=ue(s)),U(n.extracted,r,{source:t,url:e,method:i,timestamp:a,contentType:o})}o.includes(`application/graphql`)&&typeof r.body==`string`&&U(n.extracted,{query:r.body,variables:null,operationName:null},{source:t,url:e,method:i,timestamp:a,contentType:o})}return n}function me(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 he=class{deps;constructor(e){this.deps=`collector`in e?e:{collector:e}}async handleGraphqlExtractQueries(e){try{let t=y(e,`limit`,50,1,200),n=await o(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)}},t),a=n.scannedRecords,s=[...n.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 o=[W(n,`consoleMonitor.fetchRequests`),W(r,`consoleMonitor.xhrRequests`),W(i,`consoleMonitor.networkRequests`)];for(let e of o)a+=e.scannedRecords,s.push(...e.extracted)}let c=me(s),l=Math.max(n.totalExtracted,c.length),u=c.slice(0,t).map((e,t)=>{let n=w(e.query,r),a=T(e.variables,i),o=le(e.query),s={index:t,source:e.source,url:e.url,method:e.method,operationName:e.operationName,operationType:o.operationType,contentType:e.contentType,timestamp:e.timestamp,queryLength:e.query.length,queryPreview:n.preview,queryTruncated:n.truncated,shape:o};return n.truncated||(s.query=e.query),a.truncated?(s.variablesPreview=a.preview,s.variablesTruncated=!0):s.variables=e.variables,s});return g({success:!0,limit:t,stats:{scannedRecords:a,totalExtracted:l,returned:u.length},queries:u})}catch(e){return _(e)}}};function ge(e){if(!e)return null;let t=e.sha256Hash;if(typeof t!=`string`||t.trim().length===0)return null;let n=e.version,r=typeof n==`number`&&Number.isFinite(n)?Math.trunc(n):1;return{sha256Hash:t,version:r<1?1:r}}function _e(e){if(!e||e.length===0)return;let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return{error:`batch items must be objects`};let e=n,r=e.query;if(typeof r!=`string`||r.trim().length===0)return{error:`Each batch item requires a non-empty query string`};let i=e.variables,a=i&&typeof i==`object`&&!Array.isArray(i)?i:{},o=e.operationName,s=typeof o==`string`&&o.trim().length>0?o.trim():null;t.push({query:r,variables:a,operationName:s})}return t}function ve(e,t,n,r,i){let a=i?{extensions:{persistedQuery:{sha256Hash:i.sha256Hash,version:i.version}}}:{};return r&&r.length>0?JSON.stringify(r.map(e=>({query:e.query,variables:e.variables,operationName:e.operationName,...a}))):JSON.stringify({query:e,variables:t,operationName:n,...a})}function G(e){if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e.errors;if(Array.isArray(t))return{graphqlErrors:t,hasGraphqlErrors:t.length>0}}return{graphqlErrors:null,hasGraphqlErrors:!1}}var ye=class{collector;constructor(e){this.collector=e}async handleGraphqlReplay(e){try{let t=c(e,`endpoint`)?.trim();if(!t)return _(`Missing required argument: endpoint`);let n=c(e,`query`),r=typeof n==`string`?n.trim():``,i=f(e,`variables`)??{},a=c(e,`operationName`),o=a&&a.trim().length>0?a.trim():null,s=b(e.headers),l=u(e,`useBrowser`,!0),d=ge(f(e,`persistedQuery`)),m=_e(p(e,`batch`));if(m&&!Array.isArray(m))return _(m.error);let h=m;if(!h&&r.length===0)return _(`Missing required argument: query (or provide a non-empty batch)`);let g=ve(h?null:r,i,o,h,d),v={mode:h?`batch`:`single`,operationName:h?null:o,batchSize:h?.length??0};if(l){let e=await this.collector.getActivePage(),n=await C(t,typeof e.url==`function`?e.url():null);return n?_(n):await this.replayViaBrowser(e,t,g,s,v)}let y=await S(t);return y?_(y):await this.replayViaNode(t,g,s,v)}catch(e){return _(e)}}async replayViaNode(e,t,n,r){let i={"content-type":`application/json`,...n},a,o;try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4);try{a=await fetch(e,{method:`POST`,headers:i,body:t,signal:n.signal}),o=await a.text()}finally{clearTimeout(r)}}catch(t){return g({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,mode:r.mode,error:t instanceof Error?t.message:String(t)})}let s={};a.headers.forEach((e,t)=>{s[t]=e});let c=null;try{c=JSON.parse(o)}catch{c=null}return o=``,g(be(c,e,a.ok,a.status,a.statusText,s,r))}async replayViaBrowser(e,n,r,i,a){let s=await o(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:e.body,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:n,body:r,headers:i}),c={success:s.ok,endpoint:n,status:s.status,statusText:s.statusText,mode:a.mode,responseHeaders:s.responseHeaders??{}};if(a.mode===`single`?c.operationName=a.operationName:c.batchSize=a.batchSize,s.responseJson!==null){let e=T(s.responseJson,t);if(c.responseLength=e.totalLength,c.responsePreview=e.preview,c.responseTruncated=e.truncated,e.truncated||(c.response=s.responseJson),a.mode===`single`){let{graphqlErrors:e,hasGraphqlErrors:t}=G(s.responseJson);e!==null&&(c.graphqlErrors=e,c.hasGraphqlErrors=t)}}else if(s.responseText){let e=s.responseText;c.responseFormat=`text`,c.responseLength=e.length,c.responsePreview=e.length>t?e.slice(0,t):e,c.responseTruncated=e.length>t}return s.error&&(c.error=s.error),g(c)}};function be(e,n,r,i,a,o,s){let c={success:r,endpoint:n,status:i,statusText:a,mode:s.mode,responseHeaders:o};if(s.mode===`single`?c.operationName=s.operationName:c.batchSize=s.batchSize,e!==null){let n=T(e,t);if(c.responseLength=n.totalLength,c.responsePreview=n.preview,c.responseTruncated=n.truncated,n.truncated||(c.response=e),s.mode===`single`){let{graphqlErrors:t,hasGraphqlErrors:n}=G(e);t!==null&&(c.graphqlErrors=t,c.hasGraphqlErrors=n)}}return c}const K=`graphql-transport-ws`;function xe(e){switch(e){case`connection_init`:case`connection_ack`:case`connection_error`:case`complete`:case`ping`:case`pong`:return e;case`subscribe`:case`start`:return`subscribe`;case`next`:case`data`:return`next`;case`error`:return`error`;case`stop`:case`connection_terminate`:return`complete`;default:return`unknown`}}function Se(e){let t={type:`connection_init`};return e&&typeof e==`object`&&(t.payload=e),JSON.stringify(t)}function Ce(e,t,n){let r=e===`graphql-ws`?`start`:`subscribe`,i={query:n.query};return n.variables&&typeof n.variables==`object`&&(i.variables=n.variables),n.operationName&&(i.operationName=n.operationName),JSON.stringify({id:t,type:r,payload:i})}function we(e,t){return JSON.stringify({id:t,type:e===`graphql-ws`?`stop`:`complete`})}function Te(e){let t=e.trim();if(!t)return{error:`Missing required argument: endpoint`};let n,r;if(t.startsWith(`ws://`))n=t,r=`http://${t.slice(5)}`;else if(t.startsWith(`wss://`))n=t,r=`https://${t.slice(6)}`;else if(t.startsWith(`http://`))n=`ws://${t.slice(7)}`,r=t;else if(t.startsWith(`https://`))n=`wss://${t.slice(8)}`,r=t;else return{error:`Unsupported endpoint protocol: "${t}" — only ws/wss/http/https allowed`};return{wsUrl:n,httpEquiv:r}}var Ee=class{collector;constructor(e){this.collector=e}async handleGraphqlSubscribe(e){try{let n=c(e,`endpoint`)?.trim();if(!n)return _(`Missing required argument: endpoint`);let r=Te(n);if(`error`in r)return _(r.error);let i=c(e,`query`),a=typeof i==`string`?i.trim():``;if(a.length===0)return _(`Missing required argument: query`);let s=f(e,`variables`)??{},u=c(e,`operationName`),p=u&&u.trim().length>0?u.trim():null,m=f(e,`connectionPayload`)??null,h=d(e,`protocol`,new Set([K,`graphql-ws`]),K),v=l(e,`collectMs`,3e3),y=l(e,`connectTimeoutMs`,5e3);if(v<100||!Number.isFinite(v))return _(`Invalid argument: collectMs (must be >= 100)`);if(y<500||!Number.isFinite(y))return _(`Invalid argument: connectTimeoutMs (must be >= 500)`);if(y+v+3e3>3e4)return _(`Invalid arguments: connectTimeoutMs + collectMs must leave at least 3s of headroom under the 30s evaluation ceiling (keep their sum <= 27000)`);let x=await this.collector.getActivePage(),S=typeof x.url==`function`?x.url():null,w=await C(r.httpEquiv,S);if(w)return _(w);b(e.headers);let E=Se(m),D=Ce(h,`1`,{query:a,variables:s,operationName:p}),O=we(h,`1`),k=await o(x,async e=>{let t=[],n=!1,r=e=>n?{error:null,frames:t}:(n=!0,{error:e,frames:t}),i;try{i=new WebSocket(e.endpoint,e.protocols)}catch(e){return r(`WebSocket constructor failed: ${e instanceof Error?e.message:String(e)}`)}return new Promise(a=>{let o=setTimeout(()=>a(r(`hard timeout exceeded`)),e.connectTimeoutMs+e.collectMs+2e3),s=()=>{clearTimeout(o);try{i.send(e.completeFrame),t.push({type:`complete`,id:e.subscribeId,direction:`sent`,timestamp:typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()})}catch{}try{i.close()}catch{}a(r(null))},c=!1,l=!1;i.addEventListener(`open`,()=>{t.push({type:`connection_init`,direction:`sent`,timestamp:typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()});try{i.send(e.initFrame)}catch(e){clearTimeout(o),a(r(`Failed to send connection_init: ${e instanceof Error?e.message:String(e)}`))}}),i.addEventListener(`message`,n=>{let u=typeof n.data==`string`?n.data:``,d=`__raw__`,f,p=u.length>e.maxPayloadChars?`${u.slice(0,e.maxPayloadChars)}…`:u;if(u.length>0)try{let e=JSON.parse(u);if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e;d=typeof t.type==`string`?t.type:`__unknown__`,f=typeof t.id==`string`?t.id:void 0,`payload`in t&&(p=t.payload)}}catch{}if(t.push({type:d,id:f,payload:p,direction:`received`,timestamp:typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}),!l&&d===`connection_ack`){if(l=!0,!c){c=!0;try{i.send(e.subscribeFrame),t.push({type:`subscribe`,id:e.subscribeId,direction:`sent`,timestamp:typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()})}catch(e){clearTimeout(o),a(r(`Failed to send subscribe frame: ${e instanceof Error?e.message:String(e)}`));return}setTimeout(s,e.collectMs)}}else d===`connection_error`?(clearTimeout(o),a(r(`connection_error from server: ${JSON.stringify(p)}`))):d===`complete`&&s()}),i.addEventListener(`error`,()=>{l||(clearTimeout(o),a(r(`WebSocket error before connection_ack (server rejected protocol/auth or unreachable)`)))}),i.addEventListener(`close`,e=>{clearTimeout(o),!e.wasClean&&!n?a(r(`WebSocket closed unexpectedly (code=${e.code}, reason="${e.reason||`no reason`}")`)):n||a(r(null))}),setTimeout(()=>{if(!l&&!n){clearTimeout(o);try{i.close()}catch{}a(r(`Timed out waiting for connection_ack after ${e.connectTimeoutMs}ms`))}},e.connectTimeoutMs)})},{endpoint:r.wsUrl,protocols:[h],initFrame:E,subscribeFrame:D,completeFrame:O,subscribeId:`1`,collectMs:v,connectTimeoutMs:y,maxPayloadChars:t}),A=k.frames.map(e=>({...e,canonicalType:xe(e.type)})),j=A.some(e=>e.canonicalType===`connection_ack`&&e.direction===`received`),M=A.filter(e=>e.canonicalType===`next`),N=A.filter(e=>e.canonicalType===`error`),P=M.map(e=>e.payload),F=T(P,t),I={success:!k.error,endpoint:r.wsUrl,protocol:h,connectionAck:j,collectMs:v,stats:{totalFrames:A.length,nextFrames:M.length,errorFrames:N.length},frames:A};return M.length>0&&(I.dataLength=F.totalLength,I.dataPreview=F.preview,I.dataTruncated=F.truncated,F.truncated||(I.data=P)),N.length>0&&(I.graphqlErrors=N.map(e=>e.payload)),k.error&&(I.error=k.error),g(I)}catch(e){return _(e)}}};const q=new Map;function De(e){let t=q.get(e);if(t)return t;let n=`
58
+ query EnumSchemaTypeProbe($typeName: String!) {
59
+ __type(name: $typeName) {
60
+ fields(includeDeprecated: true) {
61
+ name
62
+ type {
63
+ ${P(e)}
64
+ }
65
+ }
66
+ }
67
+ }
68
+ `.trim();return q.set(e,n),n}function Oe(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 ke(e){return e===`OBJECT`||e===`INTERFACE`}function J(e){return e&&typeof e.data==`object`&&e.data!==null&&`__type`in e.data?e.data.__type:null}function Ae(e){let t=J(e);return Array.isArray(t?.fields)?t.fields.filter(e=>typeof e==`object`&&!!e&&typeof e.name==`string`):[]}function je(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 Me(e){let t=null;for(let n of e){let e=je(n.type);e!==null&&(t=Math.max(t??0,e))}return t}function Ne(e){let t=[],n=e??null;for(;n;)t.push(`${n.kind??``}:${n.name??``}`),n=n.ofType??null;return t.join(`>`)}function Pe(e){return e.map(e=>`${e.name??``}=${Ne(e.type)}`).join(`|`)}async function Fe(e,t,n){let r=null,i=null,a=0;for(;;){let o=await Y(e,t,{query:De(a),variables:{typeName:n}});if(!J(o.record))return r;let s=Ae(o.record);r=s;let c=Me(s);if(c===null)return r;let l=Pe(s);if(c<=a||l===i)return r;i=l,a=c}}async function Y(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 Ie(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 Fe(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=Oe(e.type);!t.name||!ke(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,X=/"([^"]+)"/g,Z=`__jshook_probe__`;function Re(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(X),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 n=e.discovered.get(e.parentType)??e.discovered.get(e.typeName)??[],r=JSON.stringify({rootType:e.typeName,parentType:e.parentType,fields:n},null,2);return g({success:!0,endpoint:e.endpoint,typeName:e.typeName,parentType:e.parentType,maxDepth:e.maxDepth,concurrency:e.concurrency,fields:n,discoveredTypes:Object.fromEntries(Array.from(e.discovered.entries()).filter(([e])=>!e.includes(`.`))),responsePreview:r.length>t?`${r.slice(0,t)}\n... (truncated)`:r})}var ze=class{async handleGraphqlEnumSchema(e){try{let t=c(e,`endpoint`)?.trim();if(!t)return _(`Missing required argument: endpoint`);let n=await S(t);if(n)return _(n);let r=b(e.headers),i=c(e,`typeName`,`Query`)?.trim()||`Query`,a=c(e,`parentType`,i)?.trim()||i,o=l(e,`maxDepth`,1)??1,s=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 Y(t,r,{query:Q([])});if(!f.ok)return g({success:!1,endpoint:t,typeName:i,parentType:a,status:f.status,statusText:f.statusText,error:f.error??`Schema enumeration request failed`});let p=this.extractSuggestions(f.errors);if(!p)return $({endpoint:t,typeName:i,parentType:a,maxDepth:s,concurrency:d,discovered:await Ie(t,r,a,s)??new Map([[a,[]]])});let m=[],h=new Map;if(h.set(p.typeName,p.suggestions),s>1)for(let e of p.suggestions){let t=[e],n=t.join(`.`);h.has(n)||(h.set(n,[]),m.push({path:t,depth:1,typeName:e}))}for(;m.length>0;){let e=m.shift(),n=await Y(t,r,{query:Q(e.path)});if(!n.ok)return g({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){h.set(e.typeName,[]);continue}if(h.set(o.typeName,o.suggestions),!(e.depth+1>=s))for(let t of o.suggestions){let n=[...e.path,t],r=n.join(`.`);h.has(r)||(h.set(r,[]),m.push({path:n,depth:e.depth+1,typeName:t}))}}return $({endpoint:t,typeName:i,parentType:a,maxDepth:s,concurrency:d,discovered:h})}catch(e){return _(e)}}extractSuggestions(e){for(let t of e){if(typeof t.message!=`string`)continue;let e=Re(t.message);if(e)return e}return null}};function Be(e){return`collector`in e?e:{collector:e}}var Ve=class{callGraph;scriptReplace;introspection;extract;replay;subscribe;schemaEnum;constructor(e){let t=Be(e);this.callGraph=new ee(t.collector),this.scriptReplace=new te(t.collector),this.introspection=new ie(t.collector),this.extract=new he(t),this.replay=new ye(t.collector),this.subscribe=new Ee(t.collector),this.schemaEnum=new ze}async handleCallGraphAnalyzeTool(e){return m(async()=>await this.handleCallGraphAnalyze(e))}async handleCallGraphAnalyze(e){return this.callGraph.handleCallGraphAnalyze(e)}async handleScriptReplacePersistTool(e){return m(async()=>await this.handleScriptReplacePersist(e))}async handleScriptReplacePersist(e){return this.scriptReplace.handleScriptReplacePersist(e)}async handleGraphqlIntrospectTool(e){return m(async()=>await this.handleGraphqlIntrospect(e))}async handleGraphqlIntrospect(e){return this.introspection.handleGraphqlIntrospect(e)}async handleGraphqlExtractQueriesTool(e){return m(async()=>await this.handleGraphqlExtractQueries(e))}async handleGraphqlExtractQueries(e){return this.extract.handleGraphqlExtractQueries(e)}async handleGraphqlReplayTool(e){return m(async()=>await this.handleGraphqlReplay(e))}async handleGraphqlReplay(e){return this.replay.handleGraphqlReplay(e)}async handleGraphqlSubscribeTool(e){return m(async()=>await this.handleGraphqlSubscribe(e))}async handleGraphqlSubscribe(e){return this.subscribe.handleGraphqlSubscribe(e)}async handleGraphqlEnumSchemaTool(e){return m(async()=>await this.handleGraphqlEnumSchema(e))}async handleGraphqlEnumSchema(e){return this.schemaEnum.handleGraphqlEnumSchema(e)}};export{Ve as GraphQLToolHandlers};
@@ -0,0 +1 @@
1
+ function e(e,t){let n=e.replace(/\s+/g,``).trim();if(n.length===0)throw Error(`data must be a non-empty string`);if(t===`hex`){if(n.length%2!=0||!/^[0-9a-fA-F]+$/.test(n))throw Error(`data must be an even-length hexadecimal string when encoding=hex`);return Buffer.from(n,`hex`)}if(!/^[A-Za-z0-9+/_-]*={0,2}$/.test(n))throw Error(`data must be valid base64 when encoding=base64`);let r=n.replace(/-/g,`+`).replace(/_/g,`/`);return Buffer.from(r,`base64`)}function t(t,n=`hex`){let r=e(t,n),i=[],a=[],o=0;for(;o+5<=r.length;){let e=r[o],t=r.readUInt32BE(o+1),n=o+5,s=r.length-n;if(t>s){let o=r.subarray(n);i.push({index:i.length,compressed:(e&1)!=0,isTrailer:(e&128)!=0,flag:e,declaredLength:t,payloadBytes:o.length,payloadHex:o.toString(`hex`),payloadBase64:o.toString(`base64`),truncated:!0}),a.push(`message ${String(i.length-1)} declares ${String(t)} payload bytes but only ${String(s)} remain; captured partial payload`);break}let c=r.subarray(n,n+t);i.push({index:i.length,compressed:(e&1)!=0,isTrailer:(e&128)!=0,flag:e,declaredLength:t,payloadBytes:t,payloadHex:c.toString(`hex`),payloadBase64:c.toString(`base64`),truncated:!1}),o=n+t}let s=r.length-o;return s>0&&a.push(i.length===0?`input is ${String(r.length)} bytes, shorter than a single gRPC frame header (5 bytes); no messages parsed`:`trailing ${String(s)} bytes after last complete message; ignored`),{frames:i,totalBytes:r.length,warnings:a}}function n(e,t){let n=e.replace(/\s+/g,``).trim();if(n.length%2!=0||!/^[0-9a-fA-F]*$/.test(n))throw Error(`messages[${String(t)}].payloadHex must be an even-length hex string`);return Buffer.from(n,`hex`)}function r(e){if(!Array.isArray(e)||e.length===0)throw Error(`messages must be a non-empty array`);let t=[];for(let r=0;r<e.length;r++){let i=e[r],a=n(i.payloadHex,r);if(a.length>4294967295)throw Error(`messages[${String(r)}].payload exceeds the 4-byte gRPC length limit (4294967295 bytes)`);let o=Buffer.alloc(5),s=0;i.compressed&&(s|=1),i.isTrailer&&(s|=128),o[0]=s,o.writeUInt32BE(a.length,1),t.push(o,a)}let r=Buffer.concat(t);return{hex:r.toString(`hex`),base64:r.toString(`base64`),bytes:r.length,messageCount:e.length}}export{t as n,r as t};
@@ -0,0 +1 @@
1
+ import{i as e}from"./artifacts-Bx9GLx4J.mjs";import{n as t}from"./response-R8ghbZSb.mjs";import{c as n}from"./parse-args-B6dwWc9k.mjs";import{r}from"./ResponseBuilder-BLicSCjn.mjs";import{t as i}from"./types-CWSvzmIh.mjs";import{i as a}from"./safeOutput-Dt4mfjXA.mjs";function o(e){return`${e.type}:${JSON.stringify(e.data)}`}function s(e){let t=new Map;for(let n of e)t.set(n.type,(t.get(n.type)??0)+1);return t}function c(e,t){let n=new Map(e.operations.map(e=>[e.id,e])),r=[],i=[];for(let e of t.operations)n.has(e.id)?i.push({id:e.id,type:e.type,target:e.target}):r.push(e);let a=[],c=new Set(t.operations.map(e=>e.id));for(let t of e.operations)c.has(t.id)||a.push(t);let l=new Set(e.artifacts.map(o)),u=new Set(t.artifacts.map(o)),d=0,f=0;for(let e of l)u.has(e)?f++:d++;let p=0;for(let e of u)l.has(e)||p++;let m=s(e.artifacts),h=s(t.artifacts),g=[...new Set([...m.keys(),...h.keys()])].map(e=>{let t=m.get(e)??0,n=h.get(e)??0;return{type:e,countA:t,countB:n,delta:n-t}});return{sessions:{aId:e.session.id,bId:t.session.id},operations:{addedInB:r,removedFromA:a,common:i},artifacts:{onlyInA:d,onlyInB:p,common:f,byType:g},stats:{operationCountDelta:t.operations.length-e.operations.length,artifactCountDelta:t.artifacts.length-e.artifacts.length}}}const l=new Set(Object.values(i));var u=class{sessionManager;deps;constructor(e,t={}){this.sessionManager=e,this.deps=t}async handleSessionDispatch(e){let r=n(e,`action`);switch(r){case`create`:return this.handleSessionCreate(e);case`list`:return this.handleSessionList(e);case`destroy`:return this.handleSessionDestroy(e);case`status`:return this.handleSessionStatus(e);default:return t({success:!1,error:`Unknown action: ${r}. Valid: create, list, destroy, status`})}}async handleOperationDispatch(e){let r=n(e,`action`);switch(r){case`register`:return this.handleOperationRegister(e);case`list`:return this.handleOperationList(e);case`status`:return this.handleOperationStatus(e);case`stop`:return this.handleOperationStop(e);default:return t({success:!1,error:`Unknown action: ${r}. Valid: register, list, status, stop`})}}async handleArtifactDispatch(e){let r=n(e,`action`);switch(r){case`record`:return this.handleArtifactRecord(e);case`query`:return this.handleArtifactQuery(e);default:return t({success:!1,error:`Unknown action: ${r}. Valid: record, query`})}}async handleSessionCreate(e){return r(async()=>{let t=n(e,`name`);return{session:this.sessionManager.createSession(t||void 0)}})}async handleSessionList(e){return r(async()=>{let e=this.sessionManager.listSessions();return{totalSessions:e.length,sessions:e}})}async handleSessionDestroy(e){return r(async()=>{let t=n(e,`sessionId`,``);if(!t)throw Error(`sessionId is required`);return this.sessionManager.destroySession(t),{sessionId:t,message:`Session destroyed`}})}async handleSessionStatus(e){return r(async()=>{let t=n(e,`sessionId`,``);if(!t)throw Error(`sessionId is required`);let r=this.sessionManager.getSession(t);if(!r)throw Error(`Session "${t}" not found`);return{session:r,stats:this.sessionManager.getSessionStats(t)}})}async handleSessionExport(t){return r(async()=>{let r=n(t,`sessionId`,``);if(!r)throw Error(`sessionId is required`);let i=this.sessionManager.getSessionSnapshot(r);if(!i)throw Error(`Session "${r}" not found`);let o=await e({category:`sessions`,toolName:`instrumentation_session_export`,target:r,ext:`json`,customDir:n(t,`outputDir`)}),s=JSON.stringify({schemaVersion:1,exportedAt:new Date().toISOString(),snapshot:i},null,2);return await a(o.absolutePath,s),{sessionId:r,exportedPath:o.absolutePath,displayPath:o.displayPath,operationCount:i.operations.length,artifactCount:i.artifacts.length,bytesWritten:Buffer.byteLength(s,`utf8`)}})}async handleSessionDiff(e){return r(async()=>{let t=n(e,`sessionIdA`,``),r=n(e,`sessionIdB`,``);if(!t)throw Error(`sessionIdA is required`);if(!r)throw Error(`sessionIdB is required`);let i=this.sessionManager.getSessionSnapshot(t),a=this.sessionManager.getSessionSnapshot(r);if(!i)throw Error(`Session "${t}" not found`);if(!a)throw Error(`Session "${r}" not found`);return{diff:c(i,a)}})}async handleSessionMerge(e){return r(async()=>{let t=n(e,`sessionIdA`,``),r=n(e,`sessionIdB`,``),i=n(e,`name`);if(!t)throw Error(`sessionIdA is required`);if(!r)throw Error(`sessionIdB is required`);let a=this.sessionManager.getSessionSnapshot(t),o=this.sessionManager.getSessionSnapshot(r);if(!a)throw Error(`Session "${t}" not found`);if(!o)throw Error(`Session "${r}" not found`);let s=i||`merge:${a.session.id}+${o.session.id}`,c=this.sessionManager.createSession(s),l=new Map;for(let e of[...a.operations,...o.operations]){let t=this.sessionManager.registerOperation(c.id,e.type,e.target,e.config);l.set(e.id,t.id)}let u=0;for(let e of[...a.artifacts,...o.artifacts]){let t=l.get(e.operationId);t&&(this.sessionManager.recordArtifact(t,e.data),u++)}let d=this.sessionManager.getSessionSnapshot(c.id);return{mergedSessionId:c.id,sourceSessions:[t,r],operationsMerged:l.size,artifactsMerged:u,snapshot:d}})}async handleOperationList(e){return r(async()=>{let t=n(e,`sessionId`,``);if(!t)throw Error(`sessionId is required`);let r=this.sessionManager.getSessionOperations(t),i=n(e,`type`);return i&&(r=r.filter(e=>e.type===i)),{totalOperations:r.length,operations:r}})}async handleOperationStatus(e){return r(async()=>{let t=n(e,`sessionId`,``),r=n(e,`operationId`,``);if(!t)throw Error(`sessionId is required`);if(!r)throw Error(`operationId is required`);let i=this.sessionManager.getOperation(t,r);if(!i)throw Error(`Operation "${r}" not found`);return{operation:i}})}async handleOperationStop(e){return r(async()=>{let t=n(e,`sessionId`,``),r=n(e,`operationId`,``);if(!t)throw Error(`sessionId is required`);if(!r)throw Error(`operationId is required`);return{operation:this.sessionManager.stopOperation(t,r),message:`Operation stopped`}})}async handleOperationRegister(e){return r(async()=>{let t=n(e,`sessionId`,``),r=d(e.type),i=n(e,`target`,``),a=e.config&&typeof e.config==`object`&&!Array.isArray(e.config)?e.config:{};if(!t)throw Error(`sessionId is required`);if(!r)throw Error(`type is required`);if(!i)throw Error(`target is required`);return{operation:this.sessionManager.registerOperation(t,r,i,a)}})}async handleArtifactQuery(e){return r(async()=>{let t=n(e,`sessionId`,``);if(!t)throw Error(`sessionId is required`);let r=d(e.type),i=f(e.limit),a=this.sessionManager.getArtifacts(t,r);return a=a.slice(0,i),{totalArtifacts:a.length,artifacts:a}})}async handleArtifactRecord(e){return r(async()=>{let t=n(e,`operationId`,``),r=e.data&&typeof e.data==`object`&&!Array.isArray(e.data)?e.data:void 0;if(!t)throw Error(`operationId is required`);if(!r)throw Error(`data is required`);return{artifact:this.sessionManager.recordArtifact(t,r)}})}async handleHookPreset(e){return r(async()=>{let t=n(e,`sessionId`,``);if(!t)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(t,this.deps.hookPresetHandlers,r);return{operation:i.operation,artifacts:i.artifacts,result:i.payload}})}async handleNetworkReplay(e){return r(async()=>{let t=n(e,`sessionId`,``);if(!t)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(t,this.deps.advancedHandlers,r);return{operation:i.operation,artifacts:i.artifacts,result:i.payload}})}};function d(e){if(!(e==null||e===``)){if(typeof e==`string`&&l.has(e))return e;throw Error(`Invalid instrumentation type: ${String(e)}. Expected one of: ${[...l].join(`, `)}`)}}function f(e){return Math.min(500,Math.max(1,typeof e==`number`&&Number.isFinite(e)?Math.floor(e):50))}export{u as InstrumentationHandlers};
@@ -0,0 +1 @@
1
+ import{u as e}from"./constants-nvsLpSri.mjs";import{i as t,r as n}from"./outputPaths-CHtELDyi.mjs";import{n as r}from"./response-R8ghbZSb.mjs";import{c as i,l as a,s as o,u as s}from"./parse-args-B6dwWc9k.mjs";import{r as c}from"./ResponseBuilder-BLicSCjn.mjs";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f}from"node:fs";import p from"node:path";import{mkdir as m,readFile as h,stat as g,writeFile as _}from"node:fs/promises";import{fileURLToPath as v,pathToFileURL as y}from"node:url";import b from"node:http";import{createHash as x,createHmac as S,timingSafeEqual as C}from"node:crypto";import{EventEmitter as w}from"node:events";function T(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function E(e){let t=e.trim().toLowerCase().replace(/\//g,`-`).replace(/(?!^@)[^a-z0-9@_-]+/g,`-`);return t.length>0?t:`plugin-${Date.now()}`}function D(e){if(!T(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 O=class{rootDir;legacyPluginRoots;useLegacyScanApi;registryFile;moduleCacheDir;installedPlugins=new Map;loadedPlugins=new Map;constructor(e=n(),t=[]){let r=typeof e==`string`?e:n();this.useLegacyScanApi=typeof e!=`string`,this.rootDir=r,this.registryFile=p.join(r,`plugins.json`),this.moduleCacheDir=p.join(r,`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=E(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))}getInstalled(e){let t=this.installedPlugins.get(e);if(t)return{id:t.id,name:t.name,version:t.version,entry:t.entry,permissions:[...t.permissions],status:t.status}}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=y(await this.resolveEntryPath(t));r.searchParams.set(`ts`,String(Date.now()));let i=await import(r.href),a=T(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=D(e);t&&this.installedPlugins.set(t.id,t)}}async persist(){await m(this.rootDir,{recursive:!0}),await m(this.moduleCacheDir,{recursive:!0}),await _(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://`)?v(new URL(e.entry)):p.isAbsolute(e.entry)?e.entry:p.resolve(t(),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,`${E(e)}.mjs`),a=x(`sha256`).update(r).digest(`hex`);try{let e=await h(i,`utf8`);if(x(`sha256`).update(e).digest(`hex`)===a)return i}catch{}return await m(this.moduleCacheDir,{recursive:!0}),await _(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=T(e.dependencies)?Object.keys(e.dependencies):[];return{id:E(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 k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e){if(!k(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 j=class{rootDir;storageFile;webhooks=new Map;constructor(e=n()){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=A(e);t&&this.webhooks.set(t.id,t)}}async persist(){await m(this.rootDir,{recursive:!0}),await _(this.storageFile,JSON.stringify([...this.webhooks.values()],null,2),`utf8`)}};function M(e){return{...e}}function N(){return new Date().toISOString()}var P=class extends w{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=N(),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`,M(r)),t}dequeue(e){if(!e){let e=this.getCommandsByFilter({status:`pending`})[0];return e?M(e):void 0}return this.getCommandsByFilter(e).map(M)}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=N()}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=N(),r.lastError=n,r}},F=class extends P{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(M(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`,M(t))}else if(r===`pending`){n.retries+=1;let t=this.updateStatus(e,`pending`,i);throw this.emit(`retried`,M(t)),Error(i===void 0?`retry`:i)}else{let t=this.updateStatus(e,`failed`,i);throw this.emit(`failed`,M(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(M(n))}return e}importState(e){this.commands.clear(),this.order.length=0;let t=0;for(let n of e){let e=M(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 I(e){return e===`tool_called`||e===`domain_activated`||e===`evidence_added`||e===`workflow_completed`}function L(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{rawBody:e}}}function R(e,t,n,r){let i=t.replace(/^sha256=/,``);if(n!==void 0){let e=Number(n);if(Number.isNaN(e)||e<=0)return{valid:!1,error:`invalid timestamp`};if(Math.abs(Date.now()-e)>3e5)return{valid:!1,error:`timestamp expired`}}let a=S(`sha256`,r).update(e,`utf8`).digest(`hex`),o=Buffer.from(a,`utf8`),s=Buffer.from(i,`utf8`);return o.length!==s.length||!C(o,s)?{valid:!1,error:`invalid signature`}:{valid:!0}}var z=class extends w{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=b.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}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=a.join(``);if(i.secret){let n=e.headers[`x-webhook-signature`];if(!n||typeof n!=`string`){t.statusCode=401,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({error:`missing signature header`}));return}let r=e.headers[`x-webhook-timestamp`],a=R(o,n,typeof r==`string`?r:void 0,i.secret);if(!a.valid){t.statusCode=401,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({error:a.error}));return}}let s=L(o);this.commandQueue&&this.commandQueue.enqueue({endpointId:i.id,payload:s}),s&&typeof s==`object`&&`event`in s&&typeof s.event==`string`&&await this.invokeEventHandlers(s.event,s),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!0,endpointId:i.id}))}async invokeEventHandlers(e,t){if(!I(e))return;let n=this.eventHandlers.get(e)??[];for(let e of n)await Promise.resolve(e(t))}},B=class extends z{};function V(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function H(e){return typeof e==`function`}function U(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function W(e){return p.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function G(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function K(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`)}function q(e){let t=U(e)?new URL(e).pathname:e;return p.basename(t).replace(/\.[cm]?js$/u,``)||`extension-plugin`}function J(e){return W(e)?p.normalize(e):p.resolve(t(),e)}async function Y(e){let t=JSON.parse(await h(e,`utf8`));if(!V(t))throw Error(`Expected JSON object in ${e}`);return t}function X(e){return K((V(e.jshookmcp)?e.jshookmcp:void 0)?.permissions)??K(e.permissions)}function Z(e){let t=V(e.jshookmcp)?e.jshookmcp:void 0,n=e.exports;return G(t?.entry)??G(e.entry)??G(e.jshookmcpEntry)??G(e.module)??G(e.main)??G(n)}function Q(e){let t={},n=G(e.id),r=G(e.name),i=G(e.version),a=G(e.entry),o=K(e.permissions);return n&&(t.id=n),r&&(t.name=r),i&&(t.version=i),a&&(t.entry=a),o&&(t.permissions=o),t}var $=class{registry;webhook;webhookServer;commandQueue;constructor(e,t){this.registry=e,this.webhook=t}async handleInstallTool(e){return c(async()=>await this.handleInstall(e))}async handleInstall(e){let t=await this.resolveInstallManifest(e),n=await this.getRegistry().register(t);return this.emitEvent(`extension.installed`,{pluginId:n}),r({success:!0,pluginId:n,manifest:this.getRegistry().getInstalled(n)??{...t,id:n,permissions:t.permissions??[],status:`unloaded`}})}async handleListInstalledTool(){return c(async()=>await this.handleListInstalled())}async handleListInstalled(){return r({success:!0,plugins:this.getRegistry().listInstalled()})}async handleInfoTool(e){return c(async()=>await this.handleInfo(e))}async handleInfo(e){let t=s(e,`pluginId`),n=this.getRegistry().getInstalled(t);if(!n)throw Error(`Plugin not found: ${t}`);return r({success:!0,pluginId:t,manifest:n})}async handleExecuteInContextTool(e){return c(async()=>await this.handleExecuteInContext(e))}async handleExecuteInContext(e){let t=s(e,`pluginId`),n=s(e,`contextName`),i=o(e,`args`)??{},{manifest:a,exports:c}=await this.getRegistry().loadPlugin(t),l=this.resolveContext(c,n);if(!l)throw Error(`Context "${n}" was not found in plugin "${t}"`);let u=await Promise.resolve(l(i));return this.emitEvent(`extension.executed`,{pluginId:t,contextName:n}),r({success:!0,manifest:a,contextName:n,result:u})}async handleReloadTool(e){return c(async()=>await this.handleReload(e))}async handleReload(e){let t=s(e,`pluginId`);await this.getRegistry().unloadPlugin(t);let n=await this.getRegistry().loadPlugin(t);return this.emitEvent(`extension.reloaded`,{pluginId:t}),r({success:!0,pluginId:t,manifest:n.manifest,exportedKeys:Object.keys(n.exports).toSorted()})}async handleUninstallTool(e){return c(async()=>await this.handleUninstall(e))}async handleUninstall(e){let t=s(e,`pluginId`);return await this.getRegistry().unregister(t),this.emitEvent(`extension.uninstalled`,{pluginId:t}),r({success:!0,pluginId:t})}async handleWebhookDispatchTool(e){return c(async()=>await this.handleWebhookDispatch(e))}async handleWebhookCreate(e){let t=s(e,`name`),n=s(e,`path`),a=i(e,`secret`),o=Array.isArray(e.events)?e.events.filter(e=>typeof e==`string`):[],c=this.getWebhookServer();c.isRunning()||c.start();let l=c.registerEndpoint({path:n,method:`POST`,secret:a??void 0}),u=this.getWebhook(),d=`http://localhost:${c.getPort()}${n}`,f=i(e,`url`);return f&&u.registerExternalCallback(l,f),r({success:!0,endpointId:l,url:d,...f?{externalUrl:f}:{},name:t,events:o})}async handleWebhookList(){let e=this.getWebhookServer();return r({success:!0,endpoints:e.listEndpoints(),port:e.getPort(),running:e.isRunning()})}async handleWebhookDelete(e){let t=s(e,`endpointId`),n=this.getWebhookServer();try{n.removeEndpoint(t)}catch(e){throw Error(`GRACEFUL: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return r({success:!0,endpointId:t})}async handleWebhookCommands(e){let t=s(e,`endpointId`),n=i(e,`status`),a=o(e,`command`);if(a)return r({success:!0,commandId:this.getCommandQueue().enqueue({endpointId:t,payload:a}),status:`pending`});let c=this.getCommandQueue(),l={endpointId:t};n&&(l.status=n);let u=c.dequeue(l);return r({success:!0,endpointId:t,commands:u,count:Array.isArray(u)?u.length:+!!u})}getWebhookServer(){return this.webhookServer||=(this.commandQueue=new F,new B({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 O,this.registry}getWebhook(){return this.webhook||=new j,this.webhook}getCommandQueue(){return this.commandQueue||=new F,this.commandQueue}async resolveInstallManifest(e){let t=i(e,`source`),n=t?await this.manifestFromSource(t):{},r=o(e,`manifest`),s=r?Q(r):{},c=Q(e),l=Array.isArray(e.permissions)?a(e,`permissions`):c.permissions??s.permissions??n.permissions,u={...n,...s,...c,permissions:l},d=u.name,f=u.entry;if(!d||!f)throw Error(`extension_install requires name and entry via source, manifest, or top-level arguments`);return{id:u.id??d,name:d,version:u.version??`0.0.0`,entry:f,permissions:u.permissions??[]}}async manifestFromSource(e){if(U(e))return{id:q(e),name:q(e),version:`0.0.0`,entry:e};let t=J(e);return(await g(t).catch(t=>{throw Error(`Extension source not found: ${e}`,{cause:t})})).isDirectory()?this.manifestFromPackageJson(p.join(t,`package.json`),t):p.basename(t).toLowerCase()===`package.json`||p.extname(t).toLowerCase()===`.json`?this.manifestFromPackageJson(t,p.dirname(t)):{id:q(t),name:q(t),version:`0.0.0`,entry:y(t).href}}async manifestFromPackageJson(e,t){let n=await Y(e),r=Z(n),i=r?U(r)||r.startsWith(`file://`)?r:y(p.resolve(t,r)).href:void 0;return{id:G(n.id)??G(n.name),name:G(n.name),version:G(n.version)??`0.0.0`,entry:i,permissions:X(n)}}emitEvent(e,t){this.getWebhook().sendEvent(e,t).catch(()=>void 0)}resolveContext(e,t){let n=e[t];if(H(n))return n;let r=e.default;if(t==="default"&&H(r))return r;if(V(r)){let e=r[t];if(H(e))return e}return null}async handleWebhookDispatch(e){let t=i(e,`action`);switch(t){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 r({error:`Invalid action: "${t}". Expected one of: create, list, delete, commands`})}}};export{$ as ExtensionRegistryHandlers};
@@ -1,4 +1,4 @@
1
- import{o as e,r as t,t as n}from"./parse-args-Bw413PlW.mjs";import{o as r,s as i}from"./PageController-Dfsm1_o7.mjs";import{n as a}from"./ResponseBuilder-BfWP-uaT.mjs";import"./definitions-Cenu6mxo.mjs";const o={bypassDebuggerStatement:`(function () {
1
+ import{d as e,u as t}from"./ensure-browser-core-BP70x0TB.mjs";import{i as n,l as r,n as i}from"./parse-args-B6dwWc9k.mjs";import{r as a}from"./ResponseBuilder-BLicSCjn.mjs";const o={bypassDebuggerStatement:`(function () {
2
2
  var globalObj = typeof window !== 'undefined' ? window : globalThis;
3
3
  var installFlag = '__ANTI_DEBUGGER_STATEMENT_INSTALLED__';
4
4
  if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
@@ -827,4 +827,4 @@ import{o as e,r as t,t as n}from"./parse-args-Bw413PlW.mjs";import{o as r,s as i
827
827
  sourceBytesApprox: sourceBlob.length
828
828
  }
829
829
  };
830
- })();`},l={...o,...s,...c};var u=class o{collector;static DEFAULT_DEBUGGER_MODE=`remove`;static DEFAULT_MAX_DRIFT=50;static DEFAULT_STACK_FILTER_PATTERNS=[`puppeteer`,`devtools`,`__puppeteer`,`CDP`];constructor(e){this.collector=e}parseDebuggerMode(e){if(e===`remove`||e===`noop`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`remove`||t===`noop`)return t}return o.DEFAULT_DEBUGGER_MODE}mergeStackFilterPatterns(e){let t=[...o.DEFAULT_STACK_FILTER_PATTERNS,...e].map(e=>e.trim());return Array.from(new Set(t.filter(e=>e.length>0)))}buildScript(e,t){let n=e;for(let[e,r]of Object.entries(t))n=n.split(e).join(r);return n}buildDebuggerBypassScript(e){return this.buildScript(l.bypassDebuggerStatement,{__ANTI_DEBUG_MODE__:JSON.stringify(e)})}buildTimingBypassScript(e){return this.buildScript(l.bypassTiming,{__ANTI_DEBUG_MAX_DRIFT__:String(e)})}buildStackTraceBypassScript(e){return this.buildScript(l.bypassStackTrace,{__ANTI_DEBUG_FILTER_PATTERNS__:JSON.stringify(e)})}async injectScripts(e,t,n){if(n)for(let n of t)await r(e,n);for(let n of t)await i(e,n)}async getPage(){return this.collector.getActivePage()}async handleAntiDebugBypassAll(e){return a(async()=>{let t=n(e,`persistent`,!0),r=await this.getPage(),i=[this.buildDebuggerBypassScript(o.DEFAULT_DEBUGGER_MODE),this.buildTimingBypassScript(o.DEFAULT_MAX_DRIFT),this.buildStackTraceBypassScript(this.mergeStackFilterPatterns([])),l.bypassConsoleDetect];return await this.injectScripts(r,i,t),{tool:`antidebug_bypass_all`,persistent:t,injectedCount:i.length,injected:[`bypassDebuggerStatement`,`bypassTiming`,`bypassStackTrace`,`bypassConsoleDetect`]}})}async handleAntiDebugBypassDebuggerStatement(e){return a(async()=>{let t=this.parseDebuggerMode(e.mode),n=await this.getPage(),r=this.buildDebuggerBypassScript(t);return await this.injectScripts(n,[r],!0),{tool:`antidebug_bypass_debugger_statement`,mode:t,persistent:!0}})}async handleAntiDebugBypassTiming(e){return a(async()=>{let n=t(e,`maxDrift`,o.DEFAULT_MAX_DRIFT)??o.DEFAULT_MAX_DRIFT,r=await this.getPage(),i=this.buildTimingBypassScript(n);return await this.injectScripts(r,[i],!0),{tool:`antidebug_bypass_timing`,maxDrift:n,persistent:!0}})}async handleAntiDebugBypassStackTrace(t){return a(async()=>{let n=e(t,`filterPatterns`),r=this.mergeStackFilterPatterns(n),i=await this.getPage(),a=this.buildStackTraceBypassScript(r);return await this.injectScripts(i,[a],!0),{tool:`antidebug_bypass_stack_trace`,filterPatterns:r,persistent:!0}})}async handleAntiDebugBypassConsoleDetect(e){return a(async()=>{let e=await this.getPage();return await this.injectScripts(e,[l.bypassConsoleDetect],!0),{tool:`antidebug_bypass_console_detect`,persistent:!0}})}async handleAntiDebugDetectProtections(e){return a(async()=>{let e=await i(await this.getPage(),l.detectProtections);return{tool:`antidebug_detect_protections`,detected:e?.detected??!1,count:e?.count??0,protections:e?.protections??[],recommendations:e?.recommendations??[],evidence:e?.evidence??{}}})}async handleAntidebugBypass(r){let i=r.types,s=Array.isArray(i)?i:[`all`],c=s.length===0?[`all`]:s;if(c.includes(`all`))return this.handleAntiDebugBypassAll(r);let u=n(r,`persistent`,!0),d=this.parseDebuggerMode(r.mode),f=t(r,`maxDrift`,o.DEFAULT_MAX_DRIFT)??o.DEFAULT_MAX_DRIFT,p=e(r,`filterPatterns`);return a(async()=>{let e=await this.getPage(),t=[];if(c.includes(`debugger_statement`)){let n=this.buildDebuggerBypassScript(d);await this.injectScripts(e,[n],u),t.push(`debugger_statement`)}if(c.includes(`timing`)){let n=this.buildTimingBypassScript(f);await this.injectScripts(e,[n],u),t.push(`timing`)}if(c.includes(`stack_trace`)){let n=this.mergeStackFilterPatterns(p),r=this.buildStackTraceBypassScript(n);await this.injectScripts(e,[r],u),t.push(`stack_trace`)}return c.includes(`console_detect`)&&(await this.injectScripts(e,[l.bypassConsoleDetect],u),t.push(`console_detect`)),{tool:`antidebug_bypass`,applied:t,persistent:u}})}};export{u as AntiDebugToolHandlers};
830
+ })();`},l={...o,...s,...c};var u=class o{collector;static DEFAULT_DEBUGGER_MODE=`remove`;static DEFAULT_MAX_DRIFT=50;static DEFAULT_STACK_FILTER_PATTERNS=[`puppeteer`,`devtools`,`__puppeteer`,`CDP`];constructor(e){this.collector=e}parseDebuggerMode(e){if(e===`remove`||e===`noop`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`remove`||t===`noop`)return t}return o.DEFAULT_DEBUGGER_MODE}mergeStackFilterPatterns(e){let t=[...o.DEFAULT_STACK_FILTER_PATTERNS,...e].map(e=>e.trim());return Array.from(new Set(t.filter(e=>e.length>0)))}buildScript(e,t){let n=e;for(let[e,r]of Object.entries(t))n=n.split(e).join(r);return n}buildDebuggerBypassScript(e){return this.buildScript(l.bypassDebuggerStatement,{__ANTI_DEBUG_MODE__:JSON.stringify(e)})}buildTimingBypassScript(e){return this.buildScript(l.bypassTiming,{__ANTI_DEBUG_MAX_DRIFT__:String(e)})}buildStackTraceBypassScript(e){return this.buildScript(l.bypassStackTrace,{__ANTI_DEBUG_FILTER_PATTERNS__:JSON.stringify(e)})}async injectScripts(n,r,i){if(i)for(let e of r)await t(n,e);for(let t of r)await e(n,t)}async getPage(){return this.collector.getActivePage()}async handleAntiDebugBypassAll(e){return a(async()=>{let t=i(e,`persistent`,!0),n=await this.getPage(),r=[this.buildDebuggerBypassScript(o.DEFAULT_DEBUGGER_MODE),this.buildTimingBypassScript(o.DEFAULT_MAX_DRIFT),this.buildStackTraceBypassScript(this.mergeStackFilterPatterns([])),l.bypassConsoleDetect];return await this.injectScripts(n,r,t),{tool:`antidebug_bypass_all`,persistent:t,injectedCount:r.length,injected:[`bypassDebuggerStatement`,`bypassTiming`,`bypassStackTrace`,`bypassConsoleDetect`]}})}async handleAntiDebugBypassDebuggerStatement(e){return a(async()=>{let t=this.parseDebuggerMode(e.mode),n=await this.getPage(),r=this.buildDebuggerBypassScript(t);return await this.injectScripts(n,[r],!0),{tool:`antidebug_bypass_debugger_statement`,mode:t,persistent:!0}})}async handleAntiDebugBypassTiming(e){return a(async()=>{let t=n(e,`maxDrift`,o.DEFAULT_MAX_DRIFT)??o.DEFAULT_MAX_DRIFT,r=await this.getPage(),i=this.buildTimingBypassScript(t);return await this.injectScripts(r,[i],!0),{tool:`antidebug_bypass_timing`,maxDrift:t,persistent:!0}})}async handleAntiDebugBypassStackTrace(e){return a(async()=>{let t=r(e,`filterPatterns`),n=this.mergeStackFilterPatterns(t),i=await this.getPage(),a=this.buildStackTraceBypassScript(n);return await this.injectScripts(i,[a],!0),{tool:`antidebug_bypass_stack_trace`,filterPatterns:n,persistent:!0}})}async handleAntiDebugBypassConsoleDetect(e){return a(async()=>{let e=await this.getPage();return await this.injectScripts(e,[l.bypassConsoleDetect],!0),{tool:`antidebug_bypass_console_detect`,persistent:!0}})}async handleAntiDebugDetectProtections(t){return a(async()=>{let t=await e(await this.getPage(),l.detectProtections);return{tool:`antidebug_detect_protections`,detected:t?.detected??!1,count:t?.count??0,protections:t?.protections??[],recommendations:t?.recommendations??[],evidence:t?.evidence??{}}})}async handleAntidebugBypass(e){let t=e.types,s=Array.isArray(t)?t:[`all`],c=s.length===0?[`all`]:s;if(c.includes(`all`))return this.handleAntiDebugBypassAll(e);let u=i(e,`persistent`,!0),d=this.parseDebuggerMode(e.mode),f=n(e,`maxDrift`,o.DEFAULT_MAX_DRIFT)??o.DEFAULT_MAX_DRIFT,p=r(e,`filterPatterns`);return a(async()=>{let e=await this.getPage(),t=[];if(c.includes(`debugger_statement`)){let n=this.buildDebuggerBypassScript(d);await this.injectScripts(e,[n],u),t.push(`debugger_statement`)}if(c.includes(`timing`)){let n=this.buildTimingBypassScript(f);await this.injectScripts(e,[n],u),t.push(`timing`)}if(c.includes(`stack_trace`)){let n=this.mergeStackFilterPatterns(p),r=this.buildStackTraceBypassScript(n);await this.injectScripts(e,[r],u),t.push(`stack_trace`)}return c.includes(`console_detect`)&&(await this.injectScripts(e,[l.bypassConsoleDetect],u),t.push(`console_detect`)),{tool:`antidebug_bypass`,applied:t,persistent:u}})}};export{l as n,u as t};
@@ -0,0 +1,8 @@
1
+ import{G as e,J as t,K as n,U as r,W as i,Y as a,ft as o,q as s}from"./constants-nvsLpSri.mjs";import{t as c}from"./ToolError-g3rjWzhx.mjs";import{t as l}from"./ToolProbe-B02GC3ZY.mjs";import{a as u,c as d,i as f,n as p,o as m,r as h,s as g}from"./binary-instrument-DiE1BP0x.mjs";import{n as ee,t as _}from"./capabilities-DwzyxL2w.mjs";import{t as v}from"./reverseEngineeringConfig-BhZLOa3C.mjs";import{tmpdir as y}from"node:os";import{promises as te}from"node:fs";import{basename as ne,join as b,posix as re,relative as ie,resolve as ae,sep as x}from"node:path";import{access as oe,mkdir as S,mkdtemp as se,open as ce,readFile as C,readdir as le,rm as ue,stat as w,writeFile as de}from"node:fs/promises";import{promisify as fe}from"node:util";import{randomUUID as pe}from"node:crypto";import{execFile as T,spawn as me}from"node:child_process";import{open as he}from"yauzl";const ge={plugin_frida_bridge:`Install @jshookmcpextension/plugin-frida-bridge and reload extensions.`,plugin_ghidra_bridge:`Install @jshookmcpextension/plugin-ghidra-bridge and reload extensions.`,plugin_ida_bridge:`Install @jshookmcpextension/plugin-ida-bridge and reload extensions.`,plugin_jadx_bridge:`Install @jshookmcpextension/plugin-jadx-bridge and reload extensions.`};function E(e){return{content:[{type:`text`,text:e}]}}function D(e){return E(JSON.stringify(e))}function O(e,t){let n=e[t];if(typeof n!=`string`||n.trim().length===0)throw Error(`${t} is required`);return n.trim()}function k(e,t){let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():void 0}function A(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function j(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function M(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.length>0):[]}function N(e){return typeof e==`object`&&!!e}function _e(e){return N(e)&&e.extensionPluginsById instanceof Map&&e.extensionPluginRuntimeById instanceof Map}function ve(e,t){if(!e)return;let n=e.extensionPluginsById;if(n instanceof Map)return n.has(t)}function ye(e){return ge[e]}function P(e,t){let n=ve(e,t);return n===!0?{status:`available`,fix:ye(t)}:n===!1?{status:`unavailable`,reason:`Plugin ${t.replaceAll(`_`,`-`)} is not installed`,fix:ye(t)}:{status:`unknown`,reason:`Extension plugin registry is not available in the current server context`,fix:`Run inside the full MCP server with extension support enabled.`}}async function F(e,t,n,r){let i=P(e,t);if(!e||i.status!==`available`)return D({..._(n,t,i.reason??`Plugin ${t.replaceAll(`_`,`-`)} is not available`,i.fix),status:i.status});let a=await u(e,{pluginId:t,toolName:n,args:r});return a.success?D(a):D({..._(n,t,a.error??`Plugin invocation failed`,i.fix)})}function be(e,t){let n=e[t];if(!N(n))return;let r={},i=n.includeArgs,a=n.includeRetAddr;return typeof i==`boolean`&&(r.includeArgs=i),typeof a==`boolean`&&(r.includeRetAddr=a),r}async function xe(){let e=process.env.UNIDBG_JAR??``;if(e.length===0)return{available:!1,reason:`UNIDBG_JAR is not configured`,command:`java`,jarPath:``};try{await oe(e)}catch{return{available:!1,reason:`UNIDBG_JAR not found: ${e}`,command:`java`,jarPath:e}}return{available:!0,reason:``,command:`java`,jarPath:e}}function I(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}function Se(e){return N(e)&&Array.isArray(e.functions)&&Array.isArray(e.imports)}function Ce(e){let t=[];for(let n of e){if(!N(n))continue;let e=L(n,`functionName`),r=L(n,`hookCode`),i=L(n,`description`),a=we(n.parameters);!e||!r||!i||t.push({functionName:e,hookCode:r,description:i,parameters:a})}return t}function L(e,t){let n=e[t];return typeof n==`string`?n:void 0}function we(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!N(n))continue;let e=L(n,`name`),r=L(n,`type`),i=L(n,`description`);e&&r&&i&&t.push({name:e,type:r,description:i})}return t}var Te=class{state;constructor(e){this.state=e}async handleBinaryInstrumentCapabilities(){let[e,t,n,r,i]=await Promise.all([this.getFridaSession().getAvailability(),this.getGhidraAnalyzer().getAvailability(),l(`jadx`,[`--version`]),l(`apktool`,[`--version`]),xe()]);return D(ee(`binary_instrument_capabilities`,[{capability:`frida_cli`,status:e.available?`available`:`unavailable`,reason:e.reason,fix:e.available?void 0:`Install frida-tools and ensure the frida CLI is on PATH.`,details:{tools:[`frida_attach`,`frida_spawn`,`frida_resume`,`frida_enumerate_modules`,`frida_run_script`,`frida_attach_interceptor`,`frida_generate_script`,`frida_enumerate_functions`,`frida_find_symbols`,`frida_memory_scan`,`frida_memory_read`],...e.path?{path:e.path}:{},...e.version?{version:e.version}:{}}},{capability:`plugin_frida_bridge`,...P(this.state.context,`plugin_frida_bridge`),details:{tools:[`frida_attach`,`frida_detach`,`frida_list_sessions`]}},{capability:`ghidra_headless`,status:t.available?`available`:`unavailable`,reason:t.reason,fix:t.available?void 0:`Install Ghidra and ensure analyzeHeadless is on PATH.`,details:{tools:[`ghidra_analyze`],...t.path?{path:t.path}:{},...t.version?{version:t.version}:{}}},{capability:`plugin_ghidra_bridge`,...P(this.state.context,`plugin_ghidra_bridge`),details:{tools:[`ghidra_decompile`]}},{capability:`plugin_ida_bridge`,...P(this.state.context,`plugin_ida_bridge`),details:{tools:[`ida_decompile`]}},{capability:`jadx_cli`,status:n.available?`available`:`unavailable`,reason:n.reason,fix:n.available?void 0:`Install JADX and ensure the jadx CLI is on PATH.`,details:{tools:[`jadx_decompile`],...n.path?{path:n.path}:{},...n.version?{version:n.version}:{}}},{capability:`plugin_jadx_bridge`,...P(this.state.context,`plugin_jadx_bridge`),details:{tools:[`jadx_decompile`]}},{capability:`apktool_cli`,status:r.available?`available`:`unavailable`,reason:r.reason,fix:r.available?void 0:`Install apktool and ensure it is on PATH.`,details:{tools:[`apktool_decode`],...r.path?{path:r.path}:{},...r.version?{version:r.version}:{}}},{capability:`unidbg_jar`,status:i.available?`available`:`unavailable`,reason:i.reason||void 0,fix:i.available?void 0:`Set UNIDBG_JAR to a reachable Unidbg JAR path.`,details:{tools:[`unidbg_emulate`,`unidbg_launch`,`unidbg_call`,`unidbg_trace`],command:i.command,jarPath:i.jarPath}}]))}getFridaSession(){return this.state.fridaSession||(this.state.fridaSession=new d),this.state.fridaSession}getGhidraAnalyzer(){return this.state.ghidra||(this.state.ghidra=new g),this.state.ghidra}},Ee=class{state;constructor(e){this.state=e}async handleFridaAttach(e){let t=k(e,`pid`);if(!k(e,`target`)&&t)return F(this.state.context,`plugin_frida_bridge`,`frida_attach`,e);let n=O(e,`target`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return D({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,target:n,reason:i.reason??`Frida CLI is not available`});let a;try{a=await r.attach(n)}catch(e){return D({success:!1,available:!0,capability:`frida_attach`,fix:`Run the server elevated or choose a target process that allows Frida injection.`,target:n,reason:e instanceof Error?e.message:String(e),sessions:r.listSessions()})}return this.state.context?.eventBus.emit(`frida:attached`,{target:n,sessionId:a,timestamp:new Date().toISOString()}),D({success:!0,available:!0,target:n,sessionId:a,sessions:r.listSessions()})}async handleFridaSpawn(e){let t=O(e,`target`),n=this.getFridaSession(),r=await n.getAvailability();if(!r.available)return D({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,target:t,reason:r.reason??`Frida CLI is not available`});let i;try{i=await n.spawn(t)}catch(e){return D({success:!1,available:!0,capability:`frida_spawn`,fix:`Confirm the package or executable exists and that Frida has spawn privileges.`,target:t,reason:e instanceof Error?e.message:String(e),sessions:n.listSessions()})}return this.state.context?.eventBus.emit(`frida:spawned`,{target:t,sessionId:i,timestamp:new Date().toISOString()}),D({success:!0,available:!0,target:t,sessionId:i,mode:`spawn`,resumed:!1,sessions:n.listSessions()})}async handleFridaEnumerateModules(e){let t=O(e,`sessionId`),n=this.getFridaSession(),r=await n.getAvailability();if(!r.available)return D({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:r.reason??`Frida CLI is not available`,modules:[]});if(!n.useSession(t))return D({success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,modules:[]});let i=await n.enumerateModules(),a=n.getSessionDiagnostics(t);return a?.status===`error`&&a.lastError?D({success:!1,available:!0,sessionId:t,reason:a.lastError,modules:i}):D({success:!0,available:!0,sessionId:t,modules:i})}async handleFridaRunScript(e){let t=k(e,`sessionId`);if(!t)return E(`Missing required string argument: sessionId`);let n=O(e,`script`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:i.reason??`Frida CLI is not available`,execution:{output:``,error:`Frida unavailable`}};if(!r.useSession(t))return{success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,execution:{output:``,error:`Unknown session`}};let a=await r.executeScript(n);return a.error?D({success:!1,available:!0,sessionId:t,reason:a.error,execution:a}):D({success:!0,available:!0,sessionId:t,execution:a})}async handleFridaResume(e){let t=O(e,`sessionId`),n=this.getFridaSession(),r=await n.getAvailability();if(!r.available)return D({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:r.reason??`Frida CLI is not available`});if(!n.useSession(t))return D({success:!1,available:!1,capability:`frida_session`,fix:`Call frida_spawn first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`});let i=await n.resume(t);return i.error?D({success:!1,available:!0,sessionId:t,resumed:!1,reason:i.error,execution:i,sessions:n.listSessions()}):D({success:!0,available:!0,sessionId:t,resumed:!0,execution:i,sessions:n.listSessions()})}async handleFridaDetach(e){let t=k(e,`sessionId`);if(!t)return E(`Missing required string argument: sessionId`);let n=this.getFridaSession();return(await n.getAvailability()).available&&n.hasSession(t)?(n.useSession(t),await n.detach(),D({success:!0,sessionId:t,detached:!0})):F(this.state.context,`plugin_frida_bridge`,`frida_detach`,e)}async handleFridaListSessions(e){let t=this.getFridaSession(),n=await t.getAvailability(),r=t.listSessions();if(n.available)return D({success:!0,available:!0,sessions:r,count:r.length});let i=P(this.state.context,`plugin_frida_bridge`);return r.length>0||i.status===`unavailable`?D({success:!0,available:!1,capability:`frida_cli`,reason:n.reason??`Frida CLI is not available`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessions:r,count:r.length}):F(this.state.context,`plugin_frida_bridge`,`frida_list_sessions`,e)}async handleFridaGenerateScript(e){let t=k(e,`target`)??`unknown`,n=k(e,`template`)??`trace`,r=k(e,`functionName`)??`target_function`,i=k(e,`moduleName`)??(t===`unknown`?void 0:t),a=k(e,`address`),o=this.readInterceptorArgSpec(e);return D({success:!0,target:t,template:n,functionName:r,moduleName:i,address:a,argSpec:o,script:this.buildInterceptorScript({moduleName:i,symbol:r,address:a,argSpec:o,onEnterBody:k(e,`onEnterBody`),onLeaveBody:k(e,`onLeaveBody`)})})}async handleFridaAttachInterceptor(e){let t=O(e,`symbol`),n=k(e,`moduleName`),r=k(e,`address`),i=k(e,`sessionId`),a=j(e,`install`)??!1,o=this.readInterceptorArgSpec(e),s=this.buildInterceptorScript({moduleName:n,symbol:t,address:r,argSpec:o,onEnterBody:k(e,`onEnterBody`),onLeaveBody:k(e,`onLeaveBody`)});if(!a)return D({success:!0,installed:!1,moduleName:n,symbol:t,address:r,argSpec:o,script:s});if(!i)return E(`Missing required string argument: sessionId`);let c=this.getFridaSession(),l=await c.getAvailability();if(!l.available)return D({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:i,moduleName:n,symbol:t,reason:l.reason??`Frida CLI is not available`,script:s});if(!c.useSession(i))return D({success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach or frida_spawn first and reuse the returned sessionId.`,sessionId:i,moduleName:n,symbol:t,reason:`Unknown Frida session: ${i}`,script:s});let u=await c.executeScript(s);return u.error?D({success:!1,available:!0,installed:!1,sessionId:i,moduleName:n,symbol:t,reason:u.error,execution:u,script:s}):D({success:!0,available:!0,installed:!0,sessionId:i,moduleName:n,symbol:t,execution:u,script:s})}async handleFridaEnumerateFunctions(e){let t=O(e,`sessionId`),n=O(e,`moduleName`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,moduleName:n,reason:i.reason??`Frida CLI is not available`,functions:[]};if(!r.useSession(t))return{success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,functions:[]};let a=await r.enumerateFunctions(n),o=r.getSessionDiagnostics(t);return o?.status===`error`&&o.lastError?D({success:!1,available:!0,sessionId:t,moduleName:n,reason:o.lastError,functions:a,count:a.length}):D({success:!0,available:!0,sessionId:t,moduleName:n,functions:a,count:a.length})}async handleFridaFindSymbols(e){let t=O(e,`sessionId`),n=O(e,`pattern`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,pattern:n,reason:i.reason??`Frida CLI is not available`,symbols:[]};if(!r.useSession(t))return{success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,symbols:[]};let a=await r.findSymbols(n),o=r.getSessionDiagnostics(t);return o?.status===`error`&&o.lastError?D({success:!1,available:!0,sessionId:t,pattern:n,reason:o.lastError,symbols:a,count:a.length}):D({success:!0,available:!0,sessionId:t,pattern:n,symbols:a,count:a.length})}async handleFridaMemoryScan(e){let t=O(e,`sessionId`),n=O(e,`pattern`),r=k(e,`moduleName`),i=k(e,`address`),a=typeof e.size==`number`?e.size:void 0,o=typeof e.max==`number`?e.max:void 0,s=this.getFridaSession(),c=await s.getAvailability();if(!c.available)return{success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,pattern:n,reason:c.reason??`Frida CLI is not available`,matches:[]};if(!s.useSession(t))return{success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,matches:[]};let l=await s.memoryScan(n,{moduleName:r??void 0,address:i??void 0,size:a,max:o}),u=s.getSessionDiagnostics(t);return u?.status===`error`&&u.lastError?D({success:!1,available:!0,sessionId:t,pattern:n,reason:u.lastError,matches:l,count:l.length}):D({success:!0,available:!0,sessionId:t,pattern:n,matches:l,count:l.length})}async handleFridaMemoryRead(e){let t=O(e,`sessionId`),n=O(e,`address`),r=typeof e.size==`number`?e.size:0;if(r<=0)return D({success:!1,available:!0,sessionId:t,address:n,reason:`size must be a positive number of bytes (capped at 65536)`});let i=this.getFridaSession(),a=await i.getAvailability();if(!a.available)return{success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,address:n,reason:a.reason??`Frida CLI is not available`};if(!i.useSession(t))return{success:!1,available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`};let o=await i.memoryRead(n,r),s=i.getSessionDiagnostics(t);return s?.status===`error`&&s.lastError?D({success:!1,available:!0,sessionId:t,reason:s.lastError,...o}):D({success:!0,available:!0,sessionId:t,...o})}buildInterceptorScript(e){let t=e.address?`ptr(${JSON.stringify(e.address)})`:`Module.findExportByName(${e.moduleName?JSON.stringify(e.moduleName):`null`}, ${JSON.stringify(e.symbol)})`,n=e.argSpec.map(e=>` console.log('[arg] ${e.name}=' + __jshookReadArg(args, ${e.index}, ${JSON.stringify(e.type)}));`),r=this.indentScriptBody(e.onEnterBody,4),i=this.indentScriptBody(e.onLeaveBody,4);return[`'use strict';`,`const targetName = ${JSON.stringify(e.symbol)};`,`const targetAddress = ${t};`,`if (targetAddress === null) {`,` throw new Error('Unable to resolve Frida export: ' + targetName);`,`}`,`function __jshookReadArg(args, index, type) {`,` const value = args[index];`,` try {`,` switch (type) {`,` case 'int':`,` return value.toInt32();`,` case 'uint':`,` return value.toUInt32();`,` case 'string':`,` case 'cstring':`,` case 'utf8':`,` return Memory.readUtf8String(value);`,` case 'pointer':`,` default:`,` return String(value);`,` }`,` } catch (error) {`,` return '<read-error:' + error.message + '>';`,` }`,`}`,`Interceptor.attach(targetAddress, {`,` onEnter(args) {`,` console.log('[enter] ' + targetName + ' @ ' + targetAddress);`,...n,...r?[r]:[],` },`,` onLeave(retval) {`,` console.log('[leave] ' + targetName + ' => ' + retval);`,...i?[i]:[],` },`,`});`,``].join(`
2
+ `)}readInterceptorArgSpec(e){let t=e.argSpec;if(!Array.isArray(t))return[];let n=[];for(let[e,r]of t.entries()){if(!this.isRecord(r))continue;let t=this.readFiniteInteger(r.index)??e,i=typeof r.name==`string`?r.name.trim():``,a=typeof r.type==`string`?r.type.trim():``;n.push({index:t,name:i||`arg${t}`,type:a||`pointer`})}return n}indentScriptBody(e,t){let n=e?.trim();if(!n)return;let r=` `.repeat(t);return n.split(/\r?\n/).map(e=>`${r}${e}`).join(`
3
+ `)}readFiniteInteger(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:void 0}isRecord(e){return typeof e==`object`&&!!e}getFridaSession(){return this.state.fridaSession||(this.state.fridaSession=new d),this.state.fridaSession}};const R=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=parseInt(n,10);return Number.isFinite(r)?r:t},De=(e,t)=>process.env[e]||t,Oe=R(`JADX_SEARCH_MAX_RESULTS`,500),ke=R(`JADX_SEARCH_DEFAULT_CONTEXT_LINES`,2),Ae=R(`JADX_SEARCH_MAX_CONTEXT_LINES`,20),je=R(`JADX_SEARCH_MAX_MATCHES_PER_FILE`,100),Me=R(`JADX_SEARCH_TIMEOUT_MS`,6e4),Ne=R(`JADX_SEARCH_REGEX_TIMEOUT_MS`,50),Pe=R(`JADX_SEARCH_MAX_QUERY_LENGTH`,1024),Fe=R(`JADX_SEARCH_FALLBACK_FILE_LIMIT`,5e4),Ie=R(`JADX_SEARCH_RG_MAX_BUFFER_BYTES`,128*1024*1024),Le=De(`JADX_SEARCH_DEFAULT_GLOBS`,`**/*.java,**/*.kt`).split(`,`),Re=R(`JADX_SEARCH_MAX_LINE_BYTES`,64*1024),ze=Object.freeze([/\([^()]*[+*][^()]*\)[+*]/,/\([^()]*\|[^()]*\)[+*][^()]*[+*]/]);function Be(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`)}function Ve(e,t,n){let r=t?Be(e):e;if(!t){for(let t of ze)if(t.test(r))throw new c(`VALIDATION`,`query rejected as potentially catastrophic (ReDoS heuristic match)`,{details:{query:e}})}let i=n?`gi`:`g`;try{return new RegExp(r,i)}catch(t){throw new c(`VALIDATION`,`query failed to compile as regex: ${t.message}`,{cause:t,details:{query:e}})}}function He(e){return e.map(e=>{let t=e.startsWith(`!`);return{negate:t,re:Ge(t?e.slice(1):e)}})}function Ue(e,t){let n=!1,r=!1;for(let{negate:i,re:a}of t)if(i||(r=!0),a.test(e)){if(i)return!1;n=!0}return r?n:!0}const We=/[\\^$.+()|[\]{}]/;function Ge(e){let t=`^`,n=0;for(;n<e.length;){let r=e[n];if(r===`*`){if(e[n+1]===`*`){t+=`.*`,n+=2,e[n]===`/`&&(n+=1);continue}t+=`[^/]*`}else r===`?`?t+=`[^/]`:r!==void 0&&We.test(r)?t+=`\\`+r:r===`/`?t+=`/`:r!==void 0&&(t+=r);n+=1}return t+=`$`,new RegExp(t)}function Ke(e,t){let n=e.split(x).join(`/`),r=t.split(x).join(`/`),i=r.endsWith(`/`)?r:`${r}/`;return n.startsWith(i)?n.slice(i.length):n}function qe(e){return e.split(/\r?\n/)}function Je(e,t,n){e.lastIndex=n;let r=performance.now(),i=e.exec(t),a=performance.now()-r;if(a>Ne)throw new c(`TIMEOUT`,`Regex match exceeded JADX_SEARCH_REGEX_TIMEOUT_MS (${Ne} ms): ${a.toFixed(2)} ms`,{details:{pattern:e.source,elapsedMs:a}});return i}async function Ye(e,t,n=Fe){let r;try{r=await te.readdir(e,{recursive:!0})}catch(t){throw new c(`NOT_FOUND`,`decompileDir not readable: ${e}`,{cause:t})}let i=He(t),a=[];for(let e of r){if(a.length>=n)break;let t=e.split(x).join(`/`);Ue(t,i)&&a.push(t)}return a}var Xe=class{async run(e){let t=ae(e.decompileDir),n=await Ye(t,e.globs),r=Ve(e.query,e.literal,e.caseInsensitive),i=[],a=new Set,o=!1;outer:for(let s of n){let n=re.join(t.split(x).join(`/`),s),c;try{c=await te.readFile(n,`utf8`)}catch{continue}let l=qe(c),u=0,d=Ke(n,t);for(let t=0;t<l.length;t+=1){let n=l[t];if(n===void 0||n.length>Re)continue;let s=0,c=Je(r,n,s);for(;c!==null;){if(u>=e.maxMatchesPerFile){o=!0;break}let f=c.index+1,p=c.index+c[0].length+1,m={file:d,line:t+1,column:f,text:n,matchStart:f,matchEnd:p};if(e.contextLines>0){let n=[];for(let r=Math.max(0,t-e.contextLines);r<t;r+=1){let e=l[r];e!==void 0&&n.push({line:r+1,text:e})}let r=[];for(let n=t+1;n<Math.min(l.length,t+1+e.contextLines);n+=1){let e=l[n];e!==void 0&&r.push({line:n+1,text:e})}m.context={before:n,after:r}}if(i.push(m),a.add(d),u+=1,i.length>=e.maxResults){o=!0;break outer}let h=c[0].length;if(s=c.index+(h>0?h:1),s>n.length)break;c=Je(r,n,s)}}}return{matches:i,filesMatched:a.size,truncated:o}}};const Ze=fe(T);let z,B;async function Qe(e=3e3){return z||B||(B=(async()=>{try{let t=process.platform===`win32`?`where`:`which`,{stdout:n}=await Ze(t,[`rg`],{timeout:e,windowsHide:!0}),r=n.trim().split(/\r?\n/)[0];if(!r){let e={available:!1,reason:`'${t} rg' produced empty output`};return z=e,e}let i;try{let{stdout:t}=await Ze(`rg`,[`--version`],{timeout:e,windowsHide:!0}),n=t.trim().split(/\r?\n/)[0];i=n?n.substring(0,100):void 0}catch{}let a=i?{available:!0,path:r,version:i}:{available:!0,path:r};return z=a,a}catch(e){let t=typeof e==`object`&&e&&`code`in e?e.code:void 0,n=e instanceof Error?e.message:String(e?.message??e),r={available:!1,reason:t===`ENOENT`?`Command 'rg' not found in PATH — install ripgrep (brew/apt/scoop install ripgrep)`:`Probe failed: ${n.substring(0,200)}`};return z=r,r}finally{B=void 0}})(),B)}function V(e,t){let n=t.split(x).join(`/`),r=e.split(x).join(`/`),i=n.endsWith(`/`)?n:`${n}/`;return r.startsWith(i)?r.slice(i.length):r}function $e(e){return e.endsWith(`\r
4
+ `)?e.slice(0,-2):e.endsWith(`
5
+ `)||e.endsWith(`\r`)?e.slice(0,-1):e}function et(e){return $e(e)}function tt(e){let t=[`--json`,`--no-heading`,`-n`,`--no-config`];e.literal&&t.push(`-F`),e.caseInsensitive&&t.push(`-i`),e.contextLines>0&&t.push(`-C`,String(e.contextLines)),t.push(`--max-count`,String(e.maxMatchesPerFile));for(let n of e.globs)t.push(`--glob`,n);return t.push(`--`,e.query,e.decompileDir),t}var nt=class{spawnFn;rgExecutable;constructor(e=me,t=`rg`){this.spawnFn=e,this.rgExecutable=t}async run(e){let t=ae(e.decompileDir),n=tt({...e,decompileDir:t}),r=this.spawnFn(this.rgExecutable,n,{stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),i=0,a=``,o=``,s=[],l=new Set,u=!1,d=new Map,f=e=>{d.delete(e)},p=n=>{if(n.type===`begin`){let e=n.data.path.text,r=V(e,t);return d.has(r)||d.set(r,{recentLines:[],pendingAfter:[],matchCount:0}),!0}if(n.type===`end`){let e=n.data.path.text;return f(V(e,t)),!0}if(n.type===`context`){let r=n,i=V(r.data.path.text,t),a=d.get(i);if(!a)return!0;let o=et(r.data.lines.text),s={line:r.data.line_number,text:o},c=[];for(let e of a.pendingAfter)e.afterRemaining>0&&e.match.context&&(e.match.context.after.push(s),--e.afterRemaining),e.afterRemaining>0&&c.push(e);return a.pendingAfter=c,a.recentLines.push(s),a.recentLines.length>Math.max(e.contextLines,8)&&a.recentLines.shift(),!0}if(n.type===`match`){let r=n,i=V(r.data.path.text,t),a=d.get(i)??{recentLines:[],pendingAfter:[],matchCount:0};if(d.has(i)||d.set(i,a),a.matchCount>=e.maxMatchesPerFile)return u=!0,!0;if(s.length>=e.maxResults)return u=!0,!1;let o=r.data.submatches[0];if(!o)return!0;let c=et(r.data.lines.text),f=o.start+1,p=o.end+1,m={file:i,line:r.data.line_number,column:f,text:c,matchStart:f,matchEnd:p};return e.contextLines>0&&(m.context={before:a.recentLines.filter(e=>e.line<r.data.line_number).slice(-e.contextLines),after:[]},a.pendingAfter.push({match:m,afterRemaining:e.contextLines})),s.push(m),l.add(i),a.matchCount+=1,s.length>=e.maxResults?(u=!0,!1):!0}return!0};return new Promise((e,t)=>{let n=setTimeout(()=>{r.kill(`SIGKILL`),t(new c(`TIMEOUT`,`ripgrep timed out after ${Me} ms`,{details:{timeoutMs:Me}}))},Me),d=!1,f=()=>{d||(d=!0,clearTimeout(n))};r.stdout?.setEncoding(`utf8`),r.stderr?.setEncoding(`utf8`),r.stdout?.on(`data`,e=>{if(d)return;if(i+=e.length,i>Ie){r.kill(`SIGKILL`),f(),t(new c(`RUNTIME`,`ripgrep stdout exceeded JADX_SEARCH_RG_MAX_BUFFER_BYTES (${Ie} bytes)`));return}o+=e;let n=o.indexOf(`
6
+ `);for(;n!==-1;){let e=o.slice(0,n).trimEnd();if(o=o.slice(n+1),e.length>0){let t;try{t=JSON.parse(e)}catch{}if(t&&!p(t)){o=``,f(),r.kill(`SIGTERM`);break}}n=o.indexOf(`
7
+ `)}}),r.stderr?.on(`data`,e=>{a+=e}),r.on(`error`,e=>{f(),t(new c(`RUNTIME`,`ripgrep spawn failed: ${e.message}`,{cause:e}))}),r.on(`close`,(n,r)=>{if(f(),n===2&&r!==`SIGTERM`&&r!==`SIGKILL`){t(new c(`RUNTIME`,`ripgrep exited with code 2: ${a.trim()}`,{details:{exitCode:n,signal:r??null,stderr:a.trim()}}));return}e({matches:s,filesMatched:l.size,truncated:u})})})}},rt=class{rg;fallback;probe;constructor(e={}){this.rg=e.ripgrep??new nt,this.fallback=e.fallback??new Xe,this.probe=e.probe??(()=>Qe())}async search(e){let t=await this.validateAndNormalize(e),n=performance.now(),r=`node-fallback`,i;if(e.forceFallback)i=await this.fallback.run(t);else if((await this.probe()).available){r=`ripgrep`;try{i=await this.rg.run(t)}catch(e){if(e instanceof c&&e.code===`VALIDATION`)throw e;r=`node-fallback`,i=await this.fallback.run(t)}}else i=await this.fallback.run(t);let a=Math.round(performance.now()-n),o={matches:i.matches,filesMatched:i.filesMatched,totalMatches:i.matches.length,engine:r,decompileDir:t.decompileDir,durationMs:a};return i.truncated&&(o.truncated=!0),o}async validateAndNormalize(e){if(typeof e.decompileDir!=`string`||e.decompileDir.length===0)throw new c(`VALIDATION`,`decompileDir must be a non-empty string`);if(typeof e.query!=`string`||e.query.length===0)throw new c(`VALIDATION`,`query must be a non-empty string`);if(e.query.length>Pe)throw new c(`VALIDATION`,`query length ${e.query.length} exceeds JADX_SEARCH_MAX_QUERY_LENGTH (${Pe})`);let t=e.contextLines??ke;if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw new c(`VALIDATION`,`contextLines must be a non-negative integer`);if(t>Ae)throw new c(`VALIDATION`,`contextLines ${t} exceeds JADX_SEARCH_MAX_CONTEXT_LINES (${Ae})`);let n=e.maxMatchesPerFile??je;if(!Number.isFinite(n)||n<1||!Number.isInteger(n))throw new c(`VALIDATION`,`maxMatchesPerFile must be a positive integer`);let r=e.maxResults??Oe;if(!Number.isFinite(r)||r<1||!Number.isInteger(r))throw new c(`VALIDATION`,`maxResults must be a positive integer`);let i=ae(e.decompileDir),a;try{a=await te.stat(i)}catch(e){throw new c(`NOT_FOUND`,`decompileDir not found: ${i}`,{cause:e,details:{decompileDir:i}})}if(!a.isDirectory())throw new c(`VALIDATION`,`decompileDir is not a directory: ${i}`);let o=e.globs&&e.globs.length>0?Array.from(e.globs):[...Le];return{decompileDir:i,query:e.query,globs:o,literal:e.literal===!0,caseInsensitive:e.caseInsensitive===!0,contextLines:t,maxMatchesPerFile:n,maxResults:r}}};const it=/^lib\/.+\/[^/]*(loader|shell|stub|protect|guard|pack|anti|decrypt|unpack)[^/]*\.so$/,at=/(^|\/)(assets|unknown)\//,ot=/\.(dex|cdex|jar|dat|bin|dve|y)$/,st=/(^|\/)classes[2-9]\d*\.(dex|cdex)$/,ct=/^lib\/.+\/[^/]+\.so$/,lt=/android:name="[^"]*(loader|shell|stub|wrapper|protect|guard)[^"]*"/,ut=/android\.permission\.(internet|access_network_state)/,dt=/<(service|receiver|provider)\b/;function ft(e,t,n={}){let r=_t(e,t);return{protectorHints:bt(pt(r),ht(r,n,`protector`)),sdkHints:bt(mt(r),ht(r,n,`sdk`))}}function pt(e){let t=[],n=U(e,e=>it.test(e.lower));n.length>0&&t.push({name:`native-loader-surface`,evidence:n});let r=U(e,e=>at.test(e.lower)&&ot.test(e.lower));r.length>0&&t.push({name:`secondary-code-container`,evidence:r});let i=U(e,e=>st.test(e.lower));i.length>0&&t.push({name:`multi-dex-surface`,evidence:i});let a=H(e,[lt]);return a.length>0&&t.push({name:`startup-wrapper-surface`,evidence:a}),t}function mt(e){let t=[],n=H(e,[ut]);n.length>0&&t.push({name:`network-permission-surface`,evidence:n});let r=H(e,[dt]);r.length>0&&t.push({name:`background-component-surface`,evidence:r});let i=U(e,e=>ct.test(e.lower));i.length>0&&t.push({name:`native-bridge-surface`,evidence:i});let a=[...U(e,e=>e.lower.includes(`webview`)),...H(e,[/webview/])].slice(0,10);return a.length>0&&t.push({name:`webview-surface`,evidence:a}),t}function ht(e,t,n){let r=t.customSurfaceHints??[];if(r.length===0)return[];let i=r.filter(e=>(e.kind??`protector`)===n).map(e=>({name:e.name,patterns:gt(e.patterns)})).filter(e=>e.patterns.length>0);if(i.length===0)return[];let a=new Map,o=[...e.entries.slice(0,5e3),...e.xml];for(let e of o)for(let t of i){let n=a.get(t.name)??new Set;n.size>=10||t.patterns.some(t=>e.lower.includes(t))&&(n.add(e.clipped),a.set(t.name,n))}return i.map(e=>({name:e.name,evidence:[...a.get(e.name)??[]]})).filter(e=>e.evidence.length>0)}function H(e,t){let n=[];for(let r of t)for(let t of e.xml)if(r.test(t.lower)&&n.push(t.clipped),n.length>=10)return n;return[...new Set(n)].slice(0,10)}function U(e,t){let n=[];for(let r of e.entries)if(t(r)&&n.push(r.raw),n.length>=10)return n;return n}function gt(e){return e.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,50)}function _t(e,t){return{entries:e.map(vt),xml:yt(t).map(vt)}}function vt(e){return{raw:e,lower:e.toLowerCase(),clipped:e.slice(0,160)}}function yt(e){return e.split(/\r?\n|(?=<)/).map(e=>e.trim()).filter(Boolean)}function bt(...e){let t=new Map;for(let n of e)for(let e of n){let n=t.get(e.name)??new Set;for(let t of e.evidence)n.add(t);t.set(e.name,n)}return[...t.entries()].map(([e,t])=>({name:e,evidence:[...t].slice(0,10)}))}function xt(e){return/\.(dex|cdex)$/i.test(e)}function St(e,t){let n=v().binaryMagic,r=t.subarray(0,4).equals(Buffer.from(n.compactDexMagicAscii,`ascii`))?`cdex`:`dex`,i={version:t.subarray(4,7).toString(`latin1`).replaceAll(`\0`,``)||void 0};t.length>=112&&r===`dex`&&(i.fileSize=t.readUInt32LE(32),i.headerSize=t.readUInt32LE(36),i.endianTag=`0x${t.readUInt32LE(40).toString(16)}`,i.mapOff=t.readUInt32LE(52),i.stringIdsSize=t.readUInt32LE(56),i.typeIdsSize=t.readUInt32LE(64),i.protoIdsSize=t.readUInt32LE(72),i.fieldIdsSize=t.readUInt32LE(80),i.methodIdsSize=t.readUInt32LE(88),i.classDefsSize=t.readUInt32LE(96));let a=r===`dex`?Ct(t,i,50):[],o=r===`dex`?wt(t,i,a,50):[],s=r===`dex`?At(t,i,100):[],c=r===`dex`?Et(t,i,a,o,50):[],l=r===`dex`?Dt(t,i,a,o,50):[],u=r===`dex`?Ot(t,i,a,o,c,50):[],d=r===`dex`?Tt(t,i,o,50):[];return{path:e,kind:r,size:t.length,header:i,...s.length>0?{mapItems:s}:{},...a.length>0?{stringsPreview:a}:{},...o.length>0?{typeDescriptorsPreview:o}:{},...c.length>0?{protoIdsPreview:c}:{},...l.length>0?{fieldIdsPreview:l}:{},...u.length>0?{methodIdsPreview:u}:{},...d.length>0?{classDefsPreview:d}:{}}}function Ct(e,t,n){let r=t.stringIdsSize??0,i=W(e,60);if(!i||r<=0)return[];let a=[],o=Math.min(r,n);for(let t=0;t<o;t++){let n=G(e,i+t*4);if(!n)continue;let r=jt(e,n);r&&a.push(r)}return a}function wt(e,t,n,r){let i=t.typeIdsSize??0,a=W(e,68);if(!a||i<=0)return[];let o=[],s=Math.min(i,r);for(let t=0;t<s;t++){let r=G(e,a+t*4);if(r===void 0)continue;let i=n[r];i&&o.push(i)}return o}function Tt(e,t,n,r){let i=t.classDefsSize??0,a=W(e,100);if(!a||i<=0)return[];let o=[],s=Math.min(i,r);for(let t=0;t<s;t++){let r=a+t*32,i=G(e,r),s=G(e,r+4),c=G(e,r+8);i===void 0||s===void 0||o.push({classIdx:i,classType:n[i],...c!==void 0&&c!==4294967295?{superClassIdx:c,superClassType:n[c]}:{},accessFlags:s})}return o}function Et(e,t,n,r,i){let a=t.protoIdsSize??0,o=W(e,76);if(!o||a<=0)return[];let s=[],c=Math.min(a,i);for(let t=0;t<c;t++){let i=o+t*12,a=G(e,i),c=G(e,i+4),l=G(e,i+8);a===void 0||c===void 0||s.push({protoIdx:t,shorty:n[a],returnType:r[c],parameters:l?kt(e,l,r,50):[]})}return s}function Dt(e,t,n,r,i){let a=t.fieldIdsSize??0,o=W(e,84);if(!o||a<=0)return[];let s=[],c=Math.min(a,i);for(let t=0;t<c;t++){let i=o+t*8;if(i+8>e.length)break;let a=e.readUInt16LE(i),c=e.readUInt16LE(i+2),l=e.readUInt32LE(i+4),u=r[a],d=r[c],f=n[l];s.push({fieldIdx:t,classType:u,type:d,name:f,...u&&f&&d?{descriptor:`${u}->${f}:${d}`}:{}})}return s}function Ot(e,t,n,r,i,a){let o=t.methodIdsSize??0,s=W(e,92);if(!s||o<=0)return[];let c=[],l=Math.min(o,a);for(let t=0;t<l;t++){let a=s+t*8;if(a+8>e.length)break;let o=e.readUInt16LE(a),l=e.readUInt16LE(a+2),u=e.readUInt32LE(a+4),d=r[o],f=i[l],p=n[u],m=f?.parameters??[],h=f?.returnType;c.push({methodIdx:t,classType:d,protoIdx:l,name:p,returnType:h,parameters:m,...d&&p&&h?{descriptor:`${d}->${p}(${m.join(``)})${h}`}:{}})}return c}function kt(e,t,n,r){if(t+4>e.length)return[];let i=G(e,t)??0,a=[],o=Math.min(i,r);for(let r=0;r<o;r++){let i=t+4+r*2;if(i+2>e.length)break;let o=n[e.readUInt16LE(i)];o&&a.push(o)}return a}function At(e,t,n){let r=t.mapOff;if(!r||r+4>e.length)return[];let i=G(e,r)??0,a=[],o=Math.min(i,n);for(let t=0;t<o;t++){let n=r+4+t*12;if(n+12>e.length)break;let i=e.readUInt16LE(n),o=e.readUInt32LE(n+4),s=e.readUInt32LE(n+8);a.push({type:i,typeName:Nt(i),size:o,offset:s})}return a}function jt(e,t){if(t>=e.length)return;let n=Mt(e,t);if(!n)return;let r=n.nextOffset,i=r,a=Math.min(e.length,r+v().dex.stringScanMaxBytes);for(;i<a&&e[i]!==0;)i+=1;if(!(i>=e.length))return e.subarray(r,i).toString(`utf8`)}function Mt(e,t){let n=0,r=0;for(let i=0;i<5;i++){let a=t+i;if(a>=e.length)return;let o=e[a];if(n|=(o&127)<<r,!(o&128))return{value:n,nextOffset:a+1};r+=7}}function W(e,t){let n=G(e,t);return n&&n<e.length?n:void 0}function G(e,t){return t+4<=e.length?e.readUInt32LE(t):void 0}function Nt(e){switch(e){case 0:return`header`;case 1:return`string_id`;case 2:return`type_id`;case 3:return`proto_id`;case 4:return`field_id`;case 5:return`method_id`;case 6:return`class_def`;case 4096:return`map_list`;case 4097:return`type_list`;case 8192:return`class_data`;case 8193:return`code`;case 8194:return`string_data`;default:return`unknown_${e.toString(16)}`}}async function Pt(e){let t=v().dex,n=Math.max(1,Math.min(Math.floor(e.limit??t.artifactDefaultLimit),t.artifactMaxLimit)),r=Ft(e.maxFileBytes??t.artifactDefaultMaxFileBytes,t.artifactMinReadBytes,t.artifactMaxReadBytes),i=Ft(e.maxTotalBytes??t.artifactDefaultMaxTotalBytes,t.artifactMinReadBytes,t.artifactMaxReadBytes),a=[],o=0,s=async t=>{if(a.length>=n)return;let c=await le(t,{withFileTypes:!0}).catch(()=>[]);for(let l of c){if(a.length>=n)return;let c=b(t,l.name);if(l.isDirectory()){await s(c);continue}if(!l.isFile()||!xt(l.name))continue;let u=await w(c).catch(()=>void 0);if(!u?.isFile())continue;let d=i-o;if(d<=0)return;let f=Math.min(u.size,r,d);if(f<=0)continue;let p=await It(c,f);o+=p.length;let m=St(ie(e.rootDir,c).replace(/\\/g,`/`),p);a.push({...m,...u.size===m.size?{}:{sourceSize:u.size,truncated:!0}})}};return await s(e.rootDir),a}function Ft(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(Math.floor(e),n)):t}async function It(e,t){let n=await ce(e,`r`);try{let e=Buffer.alloc(t),{bytesRead:r}=await n.read(e,0,t,0);return r===e.length?e:e.subarray(0,r)}finally{await n.close()}}async function Lt(e){let t=v(),n=t.apk,r=t.dex,i=Rt(e.maxEntries??n.staticTriageDefaultEntries,n.staticTriageMinEntries,n.staticTriageMaxEntries),a=Rt(e.maxDexFiles??n.dexIntakeDefaultDexFiles,1,n.dexIntakeMaxDexFiles),o=Rt(e.maxDexBytes??r.artifactDefaultMaxFileBytes,r.artifactMinReadBytes,r.artifactMaxReadBytes),s=Rt(e.maxTotalDexBytes??r.artifactDefaultMaxTotalBytes,r.artifactMinReadBytes,r.artifactMaxReadBytes),c=await w(e.apkPath).catch(()=>void 0),l=await Gt(e.apkPath,{maxDexFiles:a,maxDexBytes:o,maxTotalDexBytes:s}),u=l.map(e=>e.name),d=l.find(e=>e.name===`AndroidManifest.xml`),f=d?.buffer?Vt(d.buffer):null,p=Bt(d,f,e.includeRawManifest??!1),m=f??``,h=l.filter(e=>zt(e.name)&&e.buffer).map(e=>Wt(e)),g=u.filter(e=>/^lib\/.+\/[^/]+\.so$/i.test(e)).map(e=>{let t=e.split(`/`);return{path:e,abi:t[1]??``,name:t[t.length-1]??``}}),ee=u.filter(e=>/(^|\/)(assets|unknown)\//i.test(e)&&/\.(jar|dex|dat|bin|json|txt|dve|y)$/i.test(e)).slice(0,n.staticTriageAssetHintLimit),_=ft(u,m,e.customSurfaceHints?{customSurfaceHints:e.customSurfaceHints}:{});return{success:!0,apkPath:e.apkPath,artifact:{kind:`apk-dex-intake`,file:{size:c?.isFile()?c.size:void 0,readable:c?.isFile()??!1},zip:{entryCount:u.length,entries:u.slice(0,i),truncated:u.length>i},manifest:p,dex:{count:h.length,files:h},nativeLibs:{count:g.length,abis:K(g.map(e=>e.abi)),libraries:g.slice(0,n.staticTriageNativeLibLimit)},assetHints:ee,protectorHints:_.protectorHints,sdkHints:_.sdkHints,recommendedNextSteps:Ut(_.protectorHints.length,g.length)}}}function Rt(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(Math.floor(e),n)):t}function K(e,t=v().apk.dexIntakeUniqueLimitDefault){return[...new Set(e.filter(Boolean))].slice(0,t)}function zt(e){return/(^|\/)classes/i.test(e)&&xt(e)}function Bt(e,t,n){return e?.buffer?t===null?{format:`binary-axml`,decodedBy:`zip-entry`,size:e.buffer.length,error:`Manifest is binary AXML; run apk_manifest_dump for base64 or JADX XML decode.`}:{format:`xml`,decodedBy:`zip-entry`,summary:Ht(t),...n?{rawManifest:t}:{}}:{format:`missing`,error:`AndroidManifest.xml not found`}}function Vt(e){if(e.length===0)return``;let t=e.subarray(0,Math.min(e.length,v().apk.dexIntakeManifestTextSampleBytes)),n=0;for(let e of t){if(e===0)return null;(e<9||e>13&&e<32)&&(n+=1)}if(n>t.length*v().apk.dexIntakeManifestControlByteRatio)return null;let r=e.toString(`utf8`);return r.trimStart().startsWith(`<`)?r:null}function q(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return e.match(RegExp(`\\b${n}\\s*=\\s*"([^"]*)"`,`i`))?.[1]??e.match(RegExp(`\\bandroid:${n}\\s*=\\s*"([^"]*)"`,`i`))?.[1]}function J(e,t){let n=[],r=RegExp(`<${t}\\b[^>]*(?:/>|>[\\s\\S]*?<\\/${t}>)`,`gi`),i;for(;(i=r.exec(e))!==null;)i[0]&&n.push(i[0]);return n}function Ht(e){let t=v().apk,n=e.match(/<manifest\b[^>]*>/i)?.[0]??``,r=e.match(/<application\b[^>]*>/i)?.[0]??``,i=J(e,`activity`),a=J(e,`activity-alias`),o=J(e,`service`),s=J(e,`receiver`),c=J(e,`provider`),l=K([...e.matchAll(/<uses-permission\b[^>]*\bandroid:name="([^"]+)"/gi)].map(e=>e[1]??``),t.dexIntakeComponentLimit),u=K([...e.matchAll(/<uses-feature\b[^>]*\bandroid:name="([^"]+)"/gi)].map(e=>e[1]??``),t.dexIntakeFeatureLimit),d=[...i,...a].find(e=>/android\.intent\.action\.MAIN/i.test(e)&&/android\.intent\.category\.LAUNCHER/i.test(e))??``,f={activities:K(i.map(e=>q(e,`name`)??``),t.dexIntakeComponentLimit),activityAliases:K(a.map(e=>q(e,`name`)??``),t.dexIntakeFeatureLimit),services:K(o.map(e=>q(e,`name`)??``),t.dexIntakeComponentLimit),receivers:K(s.map(e=>q(e,`name`)??``),t.dexIntakeComponentLimit),providers:K(c.map(e=>q(e,`name`)??``),t.dexIntakeComponentLimit)};return{packageName:q(n,`package`),versionCode:q(n,`versionCode`),versionName:q(n,`versionName`),minSdk:e.match(/<uses-sdk\b[^>]*\bandroid:minSdkVersion="([^"]+)"/i)?.[1],targetSdk:e.match(/<uses-sdk\b[^>]*\bandroid:targetSdkVersion="([^"]+)"/i)?.[1],applicationClass:q(r,`name`),applicationLabel:q(r,`label`),debuggable:q(r,`debuggable`),launcherActivity:d?q(d,`name`):void 0,permissions:l,usesFeatures:u,components:f,counts:{permissions:l.length,activities:f.activities.length,services:f.services.length,receivers:f.receivers.length,providers:f.providers.length}}}function Ut(e,t){return[e>0?`Packed/protected APK detected: preserve this intake artifact, then start runtime dumping with adb/frida before static decompilation assumptions.`:`No strong protector hint found: run jadx_decompile_apk then jadx_search_code for startup and crypto paths.`,t>0?`Native libraries present: inspect relevant .so files with apk_native_libs_list, ghidra/unidbg, and native-emulator import diagnostics.`:`Native library surface appears small or absent.`]}function Wt(e){let t=St(e.name,e.buffer);return{...t,...e.sourceSize!==void 0&&e.sourceSize!==t.size?{sourceSize:e.sourceSize}:{},...e.truncated?{truncated:!0}:{}}}async function Gt(e,t){let n=await Kt(e);return new Promise((e,r)=>{let i=[],a=0,o=0,s=!1,c=e=>{s||(s=!0,n.removeListener(`entry`,f),n.removeListener(`end`,u),n.removeListener(`error`,d),e())},l=()=>{try{n.close()}catch{}},u=()=>{c(()=>{l(),e(i)})},d=e=>{c(()=>{l(),r(e)})},f=e=>{let s=e.fileName,u=zt(s),d=e.uncompressedSize,f=typeof d==`number`&&Number.isFinite(d)?Math.max(0,Math.floor(d)):void 0,p=Math.max(0,t.maxTotalDexBytes-o);if(!(s===`AndroidManifest.xml`||u&&a<t.maxDexFiles&&p>0)){i.push({name:s,...f===void 0?{}:{sourceSize:f},...u&&p<=0?{truncated:!0}:{}}),n.readEntry();return}u&&(a+=1),n.openReadStream(e,(e,a)=>{if(e||!a){c(()=>{l(),r(e??Error(`Unable to read ZIP entry: ${s}`))});return}qt(a,u?Math.min(t.maxDexBytes,p):void 0).then(e=>{u&&(o+=e.buffer.length);let t=e.truncated||f!==void 0&&e.buffer.length<f;i.push({name:s,buffer:e.buffer,...f===void 0?{}:{sourceSize:f},...t?{truncated:!0}:{}}),n.readEntry()}).catch(e=>{c(()=>{l(),r(e)})})})};n.on(`entry`,f),n.on(`end`,u),n.on(`error`,d),n.readEntry()})}function Kt(e){return new Promise((t,n)=>{he(e,{autoClose:!0,lazyEntries:!0,decodeStrings:!0,validateEntrySizes:!0,strictFileNames:!1},(r,i)=>{if(r||!i){n(r??Error(`Unable to open ZIP archive: ${e}`));return}t(i)})})}function qt(e,t=1/0){return new Promise((n,r)=>{let i=[],a=0,o=!1,s=e=>{o||(o=!0,n(e))};e.on(`data`,n=>{if(o)return;let r=Buffer.isBuffer(n)?n:Buffer.from(n);if(a+r.length>t){let n=Math.max(0,t-a);n>0&&(i.push(r.subarray(0,n)),a+=n),s({buffer:Buffer.concat(i,a),truncated:!0});let o=e;typeof o.destroy==`function`&&o.destroy();return}i.push(r),a+=r.length}),e.on(`end`,()=>s({buffer:Buffer.concat(i,a),truncated:!1})),e.on(`error`,e=>{o||r(e)})})}const Y={XML:524291,STRING_POOL:1835009,RESOURCE_MAP:524672,XML_START_NAMESPACE:1048832,XML_END_NAMESPACE:1048833,XML_START_TAG:1048834,XML_END_TAG:1048835,XML_TEXT:1048836},X={NULL:0,REFERENCE:1,ATTRIBUTE:2,STRING:3,FLOAT:4,DIMENSION:5,FRACTION:6,INT_DEC:16,INT_HEX:17,INT_BOOLEAN:18};var Jt=class{buffer;offset=0;stringPool={strings:[],styleOffsets:[]};namespaceMap=new Map;constructor(e){this.buffer=e}parse(){let e=this.readHeader();if(e.chunkType!==Y.XML)throw Error(`Invalid AXML header: expected 0x${Y.XML.toString(16)}, got 0x${e.chunkType.toString(16)}`);let t=this.readUInt32();if(t!==Y.STRING_POOL)throw Error(`Expected STRING_POOL chunk (0x${Y.STRING_POOL.toString(16)}), got 0x${t.toString(16)}`);this.offset-=4,this.stringPool=this.readStringPool(),this.offset<this.buffer.length&&this.peekUInt32()===Y.RESOURCE_MAP&&(this.readUInt32(),this.readResourceMap());let n=[];for(;this.offset<this.buffer.length;){let e=this.readUInt32(),t=this.readXmlChunk(e);t&&n.push(t)}return this.eventsToXml(n)}readHeader(){if(this.buffer.length<8)throw Error(`Buffer too small: ${this.buffer.length} bytes (minimum 8 required)`);return{chunkType:this.readUInt32(),chunkSize:this.readUInt32(),fileSize:this.buffer.length}}readStringPool(){let e=this.readUInt32(),t=this.readUInt32(),n=this.readUInt32(),r=this.readUInt32(),i=this.readUInt32();this.readUInt32();let a=(r&256)!=0,o=[];for(let e=0;e<t;e++)o.push(this.readUInt32());let s=[];for(let e=0;e<n;e++)s.push(this.readUInt32());let c=this.offset-28-t*4-n*4,l=c+i,u=[];for(let e of o){let t=l+e;u.push(this.readStringAt(t,a))}return this.offset=c+e,{strings:u,styleOffsets:s}}readStringAt(e,t){if(e>=this.buffer.length)return``;let n=this.offset;this.offset=e;try{if(t){this.readUInt8();let e=this.readUInt8();if(e===0)return this.offset=n,``;let t=[];for(let n=0;n<e&&this.offset<this.buffer.length;n++){let e=this.readUInt8();if(e===0)break;t.push(e)}return this.offset=n,Buffer.from(t).toString(`utf8`)}else{let e=this.readUInt16();if(e&32768){let t=this.readUInt16();e=(e&32767)<<16|t}if(e===0)return this.offset=n,``;let t=[];for(let n=0;n<e&&this.offset<this.buffer.length;n++){let e=this.readUInt16();if(e===0)break;t.push(e)}return this.offset=n,String.fromCharCode(...t)}}catch{return this.offset=n,``}}readResourceMap(){let e=(this.readUInt32()-8)/4,t=[];for(let n=0;n<e;n++)t.push(this.readUInt32());return t}readXmlChunk(e){let t=this.readUInt32(),n=this.offset-8;switch(e){case Y.XML_START_NAMESPACE:return this.readStartNamespace();case Y.XML_END_NAMESPACE:return this.readEndNamespace();case Y.XML_START_TAG:return this.readStartTag();case Y.XML_END_TAG:return this.readEndTag();case Y.XML_TEXT:return this.readText();default:return this.offset=n+t,null}}readStartNamespace(){this.readUInt32(),this.readUInt32();let e=this.readUInt32(),t=this.readUInt32();if(e!==4294967295&&t!==4294967295){let n=this.getString(t);this.namespaceMap.set(e,n)}return null}readEndNamespace(){return this.readUInt32(),this.readUInt32(),this.readUInt32(),this.readUInt32(),null}readStartTag(){let e=this.readUInt32();this.readUInt32();let t=this.readUInt32(),n=this.readUInt32();this.readUInt16(),this.readUInt16();let r=this.readUInt16();this.readUInt16(),this.readUInt16(),this.readUInt16();let i=t===4294967295?``:this.getString(t),a=this.getString(n),o=[];for(let e=0;e<r;e++)o.push(this.readAttribute());return{type:`start`,namespace:i,name:a,attributes:o,_lineNumber:e}}readEndTag(){let e=this.readUInt32();this.readUInt32();let t=this.readUInt32(),n=this.readUInt32();return{type:`end`,namespace:t===4294967295?``:this.getString(t),name:this.getString(n),_lineNumber:e}}readText(){let e=this.readUInt32();this.readUInt32();let t=this.readUInt32();return this.readUInt32(),this.readUInt32(),{type:`text`,text:t===4294967295?``:this.getString(t),_lineNumber:e}}readAttribute(){let e=this.readUInt32(),t=this.readUInt32(),n=this.readUInt32();this.readUInt16(),this.readUInt8();let r=this.readUInt8(),i=this.readUInt32();return{namespace:e===4294967295?``:this.getString(e),name:this.getString(t),rawValue:n===4294967295?``:this.getString(n),typedValue:{type:r,data:i}}}eventsToXml(e){let t=[`<?xml version="1.0" encoding="utf-8"?>`],n=[],r=0;for(let i of e)if(i.type===`start`){let e=this.formatStartTag(i,r);t.push(e),n.push(i.name??``),r++}else if(i.type===`end`){r--;let e=n.pop(),a=i.name??``;if(e!==a)throw Error(`Mismatched XML tags: expected close of "${e??`undefined`}", got "${a??`undefined`}"`);t.push(`${` `.repeat(r)}</${a}>`)}else i.type===`text`&&i.text&&t.push(`${` `.repeat(r)}${this.escapeXml(i.text)}`);if(n.length>0)throw Error(`Unclosed XML tags: ${n.join(`, `)}`);return t.join(`
8
+ `)}formatStartTag(e,t){let n=` `.repeat(t),r=e.attributes??[];if(r.length===0)return`${n}<${e.name}>`;let i=r.map(e=>this.formatAttribute(e));return`${n}<${e.name} ${i.join(` `)}>`}formatAttribute(e){let t=e.namespace?`${e.namespace}:${e.name}`:e.name,n=this.formatAttributeValue(e);return`${t}="${this.escapeXml(n)}"`}formatAttributeValue(e){let{type:t,data:n}=e.typedValue;switch(t){case X.STRING:return e.rawValue;case X.INT_DEC:return n.toString();case X.INT_HEX:return`0x${n.toString(16)}`;case X.INT_BOOLEAN:return n===0?`false`:`true`;case X.REFERENCE:return`@0x${n.toString(16)}`;case X.NULL:return``;default:return e.rawValue||`0x${n.toString(16)}`}}escapeXml(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&apos;`)}getString(e){return e<0||e>=this.stringPool.strings.length?``:this.stringPool.strings[e]??``}readUInt8(){let e=this.buffer.readUInt8(this.offset);return this.offset+=1,e}readUInt16(){let e=this.buffer.readUInt16LE(this.offset);return this.offset+=2,e}readUInt32(){let e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}peekUInt32(){return this.buffer.readUInt32LE(this.offset)}};function Yt(e){try{return new Jt(e).parse()}catch{return null}}async function Xt(e){try{let t=await $t(e);return{success:!0,entries:await new Promise((e,n)=>{let r=[],i=!1,a=e=>{i||(i=!0,t.removeListener(`entry`,o),t.removeListener(`end`,s),t.removeListener(`error`,c),e())},o=e=>{r.push(e.fileName),t.readEntry()},s=()=>a(()=>e(r)),c=e=>a(()=>n(e));t.on(`entry`,o),t.on(`end`,s),t.on(`error`,c),t.readEntry()})}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Zt(e,t){try{let n=await $t(e);return{success:!0,buffer:await new Promise((e,r)=>{let i=!1,a=()=>{try{n.close()}catch{}},o=e=>{i||(i=!0,n.removeListener(`entry`,s),n.removeListener(`end`,c),n.removeListener(`error`,l),e())},s=i=>{if(i.fileName!==t){n.readEntry();return}n.openReadStream(i,(n,i)=>{if(n||!i){o(()=>r(n??Error(`Unable to read ZIP entry: ${t}`))),a();return}en(i).then(t=>{o(()=>e(t)),a()}).catch(e=>{o(()=>r(e)),a()})})},c=()=>o(()=>r(Error(`ZIP entry not found: ${t}`))),l=e=>o(()=>r(e));n.on(`entry`,s),n.on(`end`,c),n.on(`error`,l),n.readEntry()})}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Qt(e,t={}){let n=await Zt(e,`AndroidManifest.xml`);if(!n.success)return{success:!1,error:n.error};let r=tn(n.buffer);if(r!==null)return{success:!0,format:`xml`,decodedBy:`zip-entry`,manifest:r};let i=await t.decodeBinaryManifest?.();if(i?.trimStart().startsWith(`<`))return{success:!0,format:`xml`,decodedBy:`jadx_cli`,manifest:i};let a=Yt(n.buffer);return a?.trimStart().startsWith(`<`)?{success:!0,format:`xml`,decodedBy:`axml_parser`,manifest:a}:{success:!0,format:`binary-axml`,decodedBy:`zip-entry`,buffer:n.buffer}}function $t(e){return new Promise((t,n)=>{he(e,{autoClose:!0,lazyEntries:!0,decodeStrings:!0,validateEntrySizes:!0,strictFileNames:!1},(r,i)=>{if(r||!i){n(r??Error(`Unable to open ZIP archive: ${e}`));return}t(i)})})}function en(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>{r.push(Buffer.isBuffer(e)?e:Buffer.from(e))}),e.on(`end`,()=>t(Buffer.concat(r))),e.on(`error`,n)})}function tn(e){if(e.length===0)return``;let t=v().apk,n=e.subarray(0,Math.min(e.length,t.dexIntakeManifestTextSampleBytes)),r=0;for(let e of n){if(e===0)return null;(e<9||e>13&&e<32)&&(r+=1)}if(r>n.length*t.dexIntakeManifestControlByteRatio)return null;let i=e.toString(`utf8`);return i.trimStart().startsWith(`<`)?i:null}async function nn(e,t){let n=sn(e,t);try{return await C(n,`utf8`),{success:!0,classFile:n,resolvedClassName:t}}catch{}let r=await cn(e,t);if(r.length===0)return{success:!1,suggestions:[]};if(r.length===1){let e=r[0];return e?{success:!0,classFile:e.classFile,resolvedClassName:e.className}:{success:!1,suggestions:[]}}let i=r[0],a=r[1];return!i||!a?{success:!1,suggestions:r.slice(0,10).map(e=>e.className)}:i.score>a.score?{success:!0,classFile:i.classFile,resolvedClassName:i.className}:{success:!1,suggestions:r.slice(0,10).map(e=>e.className)}}function rn(e,t){let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n+=1;let i=0,a=Math.min(e.length,t.length);for(;i<a&&e[e.length-1-i]===t[t.length-1-i];)i+=1;return n*10+i}function an(e,t){let n=RegExp(`(?:public|private|protected|static|final|abstract|synchronized|native)\\s+[\\w<>\\[\\]]+\\s+${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}\\s*\\([^)]*\\)\\s*(?:throws[^{]*)?\\{`),r=e.search(n);if(r===-1)return null;let i=0,a=e.indexOf(`{`,r);for(;a<e.length;a++)if(e[a]===`{`)i+=1;else if(e[a]===`}`&&(--i,i===0))break;return e.slice(r,a+1)}async function on(e,t,n){let r=[],i=t.map(e=>e.toLowerCase()),a=async t=>{if(r.length>=n)return;let o=await le(t,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(r.length>=n)return;let o=b(t,s.name);if(s.isDirectory()){await a(o);continue}s.isFile()&&i.some(e=>s.name.toLowerCase().endsWith(e))&&r.push(ie(e,o).replace(/\\/g,`/`))}};return await a(e),r}function sn(e,t){let n=t.split(`.`),r=(n[n.length-1]??``).split(`$`)[0]??``;return b(e,...n.slice(0,-1),`${r}.java`)}async function cn(e,t){let n=t.split(`.`),r=(n[n.length-1]??``).split(`$`)[0]??``,i=n.slice(0,-1),a=`${r}.java`,o=[],s=async t=>{let n=await le(t,{withFileTypes:!0});for(let r of n){let n=b(t,r.name);if(r.isDirectory()){await s(n);continue}if(!r.isFile()||r.name!==a)continue;let c=ie(e,n).replace(/\\/g,`/`).replace(/\.java$/i,``).split(`/`).join(`.`),l=c.split(`.`).slice(0,-1);o.push({className:c,classFile:n,score:rn(i,l)})}};return await s(e),o.toSorted((e,t)=>t.score-e.score||e.className.localeCompare(t.className))}function Z(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return e.match(RegExp(`\\b${n}\\s*=\\s*"([^"]*)"`,`i`))?.[1]??e.match(RegExp(`\\bandroid:${n}\\s*=\\s*"([^"]*)"`,`i`))?.[1]}function Q(e,t){let n=[],r=RegExp(`<${t}\\b[^>]*(?:/>|>[\\s\\S]*?<\\/${t}>)`,`gi`),i;for(;(i=r.exec(e))!==null;)i[0]&&n.push(i[0]);return n}function $(e,t=200){return[...new Set(e.filter(Boolean))].slice(0,t)}function ln(e){let t=e.match(/<manifest\b[^>]*>/i)?.[0]??``,n=e.match(/<application\b[^>]*>/i)?.[0]??``,r=Q(e,`activity`),i=Q(e,`activity-alias`),a=Q(e,`service`),o=Q(e,`receiver`),s=Q(e,`provider`),c=$([...e.matchAll(/<uses-permission\b[^>]*\bandroid:name="([^"]+)"/gi)].map(e=>e[1]??``),500),l=$([...e.matchAll(/<uses-feature\b[^>]*\bandroid:name="([^"]+)"/gi)].map(e=>e[1]??``),200),u=[...r,...i].find(e=>/android\.intent\.action\.MAIN/i.test(e)&&/android\.intent\.category\.LAUNCHER/i.test(e))??``,d={activities:$(r.map(e=>Z(e,`name`)??``),500),activityAliases:$(i.map(e=>Z(e,`name`)??``),200),services:$(a.map(e=>Z(e,`name`)??``),500),receivers:$(o.map(e=>Z(e,`name`)??``),500),providers:$(s.map(e=>Z(e,`name`)??``),500)};return{packageName:Z(t,`package`),versionCode:Z(t,`versionCode`),versionName:Z(t,`versionName`),minSdk:e.match(/<uses-sdk\b[^>]*\bandroid:minSdkVersion="([^"]+)"/i)?.[1],targetSdk:e.match(/<uses-sdk\b[^>]*\bandroid:targetSdkVersion="([^"]+)"/i)?.[1],applicationClass:Z(n,`name`),applicationLabel:Z(n,`label`),debuggable:Z(n,`debuggable`),launcherActivity:u?Z(u,`name`):void 0,permissions:c,usesFeatures:l,components:d,counts:{permissions:c.length,activities:d.activities.length,services:d.services.length,receivers:d.receivers.length,providers:d.providers.length}}}function un(e,t=200){return[...new Set(e.filter(Boolean))].slice(0,t)}function dn(e){let t=fn(e);return t?{customSurfaceHints:t}:{}}function fn(e){let t=e.customSurfaceHints;if(t===void 0)return;if(!Array.isArray(t))throw new c(`VALIDATION`,`customSurfaceHints must be an array of objects`);if(t.length>50)throw new c(`VALIDATION`,`customSurfaceHints supports at most 50 rules`);let n=[];return t.forEach((e,t)=>{if(!N(e))throw new c(`VALIDATION`,`customSurfaceHints[${t}] must be an object`);let r=e.name,i=e.patterns,a=e.kind;if(typeof r!=`string`||r.trim().length===0)throw new c(`VALIDATION`,`customSurfaceHints[${t}].name is required`);if(!Array.isArray(i)||i.length===0)throw new c(`VALIDATION`,`customSurfaceHints[${t}].patterns is required`);let o=i.map((e,n)=>{if(typeof e!=`string`||e.trim().length===0)throw new c(`VALIDATION`,`customSurfaceHints[${t}].patterns[${n}] must be a non-empty string`);if(e.length>256)throw new c(`VALIDATION`,`customSurfaceHints[${t}].patterns[${n}] exceeds 256 characters`);return e.trim()});if(a!==void 0&&a!==`protector`&&a!==`sdk`)throw new c(`VALIDATION`,`customSurfaceHints[${t}].kind must be protector or sdk`);n.push({name:r.trim(),patterns:o.slice(0,50),...a?{kind:a}:{}})}),n}var pn=class{state;constructor(e){this.state=e}async handleJadxDecompile(e){let t=O(e,`apkPath`),n=O(e,`className`),r=k(e,`methodName`),i=await l(`jadx`,[`--version`]);return i.available?this.jadxNativeDecompile(i.path??`jadx`,t,n,r):F(this.state.context,`plugin_jadx_bridge`,`jadx_decompile`,e)}async handleJadxDecompileApk(e){let t=O(e,`apkPath`),n=k(e,`outputDir`),r=j(e,`noResources`)??!1,i=j(e,`force`)??!1,a=await l(`jadx`,[`--version`]);if(!a.available)return D({available:!1,capability:`jadx_cli`,fix:`Install JADX and ensure jadx is on PATH.`,apkPath:t,reason:a.reason??`jadx is not available`});let o=n??await se(b(y(),`jshook-jadx-${ne(t)}-`));n&&i&&await ue(n,{recursive:!0,force:!0}),await S(o,{recursive:!0});let s=[`--no-debug-info`];r&&s.push(`--no-res`),s.push(`-d`,o,t);try{await this.runJadx(a.path??`jadx`,s,3e5);let e=b(o,`sources`),n=await w(e).then(e=>e.isDirectory()).catch(()=>!1)?await on(e,[`.java`,`.kt`],20):[];return D({available:!0,apkPath:t,outputDir:o,sourcesDir:e,resourcesDir:b(o,`resources`),noResources:r,sampleFiles:n,next:`Use jadx_search_code with decompileDir set to sourcesDir.`})}catch(e){return D({available:!0,apkPath:t,outputDir:o,error:e instanceof Error?e.message:String(e)})}}async handleJadxSearchCode(e){let t=k(e,`decompileDir`),n=k(e,`apkPath`),r=O(e,`query`);if(!t&&!n)throw new c(`VALIDATION`,`Either decompileDir or apkPath must be provided for jadx_search_code.`);let i=!1;if(!t&&n){let e=await l(`jadx`,[`--version`]);if(!e.available)return D({success:!1,available:!1,capability:`jadx_cli`,fix:`Install JADX and ensure jadx is on PATH.`,apkPath:n,reason:e.reason??`jadx is not available`});let r=await se(b(y(),`jshook-jadx-search-${ne(n)}-`));await this.runJadx(e.path??`jadx`,[`--no-res`,`--no-debug-info`,`-d`,r,n],3e5),t=b(r,`sources`),i=!0}let a={decompileDir:t,query:r},o=j(e,`literal`);o!==void 0&&(a.literal=o);let s=j(e,`caseInsensitive`);s!==void 0&&(a.caseInsensitive=s);let u=A(e,`contextLines`);u!==void 0&&(a.contextLines=u);let d=A(e,`maxMatchesPerFile`);d!==void 0&&(a.maxMatchesPerFile=d);let f=A(e,`maxResults`);f!==void 0&&(a.maxResults=f);let p=e.globs;if(p!==void 0){if(!Array.isArray(p))throw new c(`VALIDATION`,`globs must be an array of strings`);let t=M(e,`globs`);if(t.length!==p.length)throw new c(`VALIDATION`,`globs contains non-string entries`);t.length>0&&(a.globs=t)}let m=await this.getJadxSearchEngine().search(a);return D({success:!0,matches:m.matches,filesMatched:m.filesMatched,totalMatches:m.totalMatches,engine:m.engine,durationMs:m.durationMs,decompileDir:m.decompileDir,...i?{autoDecompiled:!0}:{},...n?{apkPath:n}:{},...m.truncated?{truncated:!0}:{}})}async handleApkManifestDump(e){let t=O(e,`apkPath`),n=await this.decodeManifest(t);return n.success?n.format===`xml`?D({available:!0,apkPath:t,entry:`AndroidManifest.xml`,format:`xml`,decodedBy:n.decodedBy,manifest:n.manifest}):D({available:!0,apkPath:t,entry:`AndroidManifest.xml`,format:`binary-axml`,decodedBy:`zip-entry`,size:n.buffer.length,manifestBase64:n.buffer.toString(`base64`)}):D({available:!1,apkPath:t,entry:`AndroidManifest.xml`,error:n.error})}async handleApkManifestQuery(e){let t=O(e,`apkPath`),n=j(e,`includeRawManifest`)??!1,r=await this.decodeManifest(t);if(!r.success)return D({available:!1,apkPath:t,error:r.error});if(r.format!==`xml`)return D({available:!0,apkPath:t,format:r.format,decodedBy:r.decodedBy,error:`Manifest is binary AXML and all decoders (JADX CLI, AXML parser) failed.`,size:r.buffer.length});let i=await Xt(t),a=i.success?i.entries:[],o=ln(r.manifest),s=ft(a,r.manifest,dn(e));return D({available:!0,apkPath:t,format:`xml`,decodedBy:r.decodedBy,summary:o,sdkHints:s.sdkHints,protectorHints:s.protectorHints,...n?{manifest:r.manifest}:{}})}async handleApkStaticTriage(e){let t=O(e,`apkPath`),n=v().apk,r=Math.max(n.staticTriageMinEntries,Math.min(A(e,`maxEntries`)??n.staticTriageDefaultEntries,n.staticTriageMaxEntries)),i=await w(t).catch(()=>void 0);if(!i?.isFile())return D({available:!1,apkPath:t,error:`APK path is not a regular file`});let a=await Xt(t);if(!a.success)return D({available:!1,apkPath:t,error:a.error});let o=a.entries,s=await this.decodeManifest(t),c=s.success&&s.format===`xml`?s.manifest:``,l=o.filter(e=>/^lib\/.+\/[^/]+\.so$/i.test(e)).map(e=>{let t=e.split(`/`);return{path:e,abi:t[1]??``,name:t[t.length-1]??``}}),u=o.filter(e=>/(^|\/)classes.*\.(dex|cdex)$/i.test(e)),d=o.filter(e=>/(^|\/)(assets|unknown)\//i.test(e)&&/\.(jar|dex|dat|bin|json|txt|dve|y)$/i.test(e)).slice(0,n.staticTriageAssetHintLimit),f=ft(o,c,dn(e));return D({available:!0,apkPath:t,file:{size:i.size},zip:{entryCount:o.length,entries:o.slice(0,r),truncated:o.length>r},manifest:c.length>0?{decodedBy:s.success?s.decodedBy:void 0,summary:ln(c)}:{decodedBy:s.success?s.decodedBy:void 0,error:s.success?`Manifest is not decoded XML`:s.error},nativeLibs:{count:l.length,abis:un(l.map(e=>e.abi)),libraries:l.slice(0,n.staticTriageNativeLibLimit)},dexFiles:u,assetHints:d,protectorHints:f.protectorHints,sdkHints:f.sdkHints,recommendedNextSteps:[f.protectorHints.length>0?`Packed/protected APK detected: start with adb_app_cold_start_trace/logcat and local APK artifact triage before escalating to device-specific runtime dumping.`:`No strong protector hint found: run jadx_decompile_apk then jadx_search_code for startup/splash logic.`,l.length>0?`Inspect native libraries relevant to protectors or startup SDKs with apk_native_libs_list and ghidra/unidbg tools.`:`Native library surface appears small or absent.`]})}async handleApkDexIntake(e){let t=O(e,`apkPath`),n=A(e,`maxEntries`),r=j(e,`includeRawManifest`),i=A(e,`maxDexFiles`),a=A(e,`maxDexBytes`),o=A(e,`maxTotalDexBytes`),s=fn(e);return D(await Lt({apkPath:t,...n===void 0?{}:{maxEntries:n},...r===void 0?{}:{includeRawManifest:r},...i===void 0?{}:{maxDexFiles:i},...a===void 0?{}:{maxDexBytes:a},...o===void 0?{}:{maxTotalDexBytes:o},...s?{customSurfaceHints:s}:{}}))}getJadxSearchEngine(){return this.state.jadxSearchEngine||(this.state.jadxSearchEngine=new rt),this.state.jadxSearchEngine}async jadxNativeDecompile(e,t,n,r){let i=await se(b(y(),`jshook-jadx-`));try{let a=[`--no-res`,`--no-debug-info`,`-d`,i,t];await this.runJadx(e,a);let o=await nn(b(i,`sources`),n);if(!o.success)return D({available:!0,apkPath:t,className:n,error:`Class file not found after decompilation: ${n}`,suggestions:o.suggestions});let s;try{s=await C(o.classFile,`utf8`)}catch{return D({available:!0,apkPath:t,className:n,...o.resolvedClassName===n?{}:{resolvedClassName:o.resolvedClassName},error:`Class file not found after decompilation: ${n}`})}if(r){let e=an(s,r);return D(e?{available:!0,apkPath:t,className:n,...o.resolvedClassName===n?{}:{resolvedClassName:o.resolvedClassName},methodName:r,source:e}:{available:!0,apkPath:t,className:n,...o.resolvedClassName===n?{}:{resolvedClassName:o.resolvedClassName},methodName:r,source:``,error:`Method ${r} not found in ${n}`})}return D({available:!0,apkPath:t,className:n,...o.resolvedClassName===n?{}:{resolvedClassName:o.resolvedClassName},source:s})}catch(e){return D({available:!0,apkPath:t,className:n,error:e instanceof Error?e.message:String(e)})}finally{await ue(i,{recursive:!0,force:!0})}}async decodeManifest(e){return Qt(e,{decodeBinaryManifest:async()=>{let t=await l(`jadx`,[`--version`]);if(!t.available)return;let n=await this.decodeManifestWithJadx(t.path??`jadx`,e);return n.success?n.manifest:void 0}})}async decodeManifestWithJadx(e,t){let n=await se(b(y(),`jshook-jadx-manifest-`));try{await this.runJadx(e,[`--no-src`,`-d`,n,t]);let r=await C(b(n,`resources`,`AndroidManifest.xml`),`utf8`);return r.trimStart().startsWith(`<`)?{success:!0,manifest:r}:{success:!1,error:`Decoded manifest is not XML`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{await ue(n,{recursive:!0,force:!0})}}async runJadx(e,t,n=12e4){await new Promise((r,i)=>{T(e,t,{encoding:`utf8`,windowsHide:!0,timeout:n},e=>{if(e&&e.code!==1){i(e);return}r()})})}};function mn(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);for(let e of t.toReversed())try{let t=JSON.parse(e);if(!N(t))continue;let n=t.returnValue??t.retval??t.result;if(typeof n==`string`&&n.trim().length>0)return n.trim();if(typeof n==`number`&&Number.isFinite(n))return String(n)}catch{}return/\b(?:returnValue|retval|return|ret)[=:\s]+(0x[0-9a-fA-F]+|-?\d+)\b/i.exec(e)?.[1]}var hn=class{state;constructor(e){this.state=e}async handleUnidbgEmulate(e){let t=O(e,`binaryPath`),n=O(e,`functionName`),r=M(e,`args`),i=await xe();if(!i.available)return{success:!1,available:!1,capability:`unidbg_jar`,fix:`Set UNIDBG_JAR to a reachable Unidbg JAR path.`,binaryPath:t,functionName:n,args:r,reason:i.reason};let a=await I(i.command,[`-jar`,i.jarPath,t,n,...r],o),s=mn(a.stdout);return{success:!0,available:!0,binaryPath:t,functionName:n,args:r,result:{...s===void 0?{returnValueKnown:!1}:{returnValue:s},stdout:a.stdout.trim(),stderr:a.stderr.trim(),trace:[]}}}async handleUnidbgLaunch(e){let t=k(e,`soPath`);if(!t)return E(`Missing required string argument: soPath`);let n=k(e,`arch`)??`arm`;try{let e=await this.state.unidbgRunner.launch(t,n);return{available:!0,sessionId:e.sessionId,soPath:e.soPath,arch:e.arch,sessions:this.state.unidbgRunner.listSessions()}}catch(e){return{available:!1,capability:`unidbg_jar`,fix:`Set UNIDBG_JAR to a reachable Unidbg JAR path and retry.`,soPath:t,arch:n,reason:e instanceof Error?e.message:String(e),sessions:this.state.unidbgRunner.listSessions()}}}async handleUnidbgCall(e){let t=k(e,`sessionId`);if(!t)return E(`Missing required string argument: sessionId`);let n=k(e,`functionName`);if(!n)return E(`Missing required string argument: functionName`);let r=N(e.args)?e.args:{};try{return D(await this.state.unidbgRunner.callFunction(t,n,r))}catch(e){let t=e instanceof Error?e.message:String(e);return E(t.startsWith(`No unidbg session found`)?`${t} (not found)`:t)}}async handleUnidbgTrace(e){let t=k(e,`sessionId`);if(!t)return E(`Missing required string argument: sessionId`);try{return D(await this.state.unidbgRunner.trace(t))}catch(e){let t=e instanceof Error?e.message:String(e);return E(t.startsWith(`No unidbg session found`)?`${t} (not found)`:t)}}},gn=class{state;constructor(e){this.state=e}async handleGhidraAnalyze(e){let t=O(e,`binaryPath`),n=A(e,`timeout`),r=this.getGhidraAnalyzer(),i=await r.getAvailability();if(!i.available){let e=await C(t).catch(()=>Buffer.alloc(0)),n=this.extractPrintableStringsStatic(e);return{available:!1,capability:`ghidra_headless`,fix:`Install Ghidra and ensure analyzeHeadless is on PATH.`,binaryPath:t,reason:i.reason??`Ghidra analyzeHeadless is not available`,functions:[],imports:[],exports:[],strings:n}}return{available:!0,binaryPath:t,analysis:await r.analyze(t,n===void 0?void 0:{timeout:n})}}async handleGhidraDecompile(e){let{invokeLegacyPlugin:t}=await import(`./shared-BKtWZDGN.mjs`);return t(this.state.context,`plugin_ghidra_bridge`,`ghidra_decompile`,e)}getGhidraAnalyzer(){return this.state.ghidra||(this.state.ghidra=new g),this.state.ghidra}extractPrintableStringsStatic(e){let t=[],n=``;for(let r of e.values()){if(r>=32&&r<=126){n+=String.fromCharCode(r);continue}n.length>=4&&t.push(n),n=``}return n.length>=4&&t.push(n),Array.from(new Set(t)).slice(0,500)}},_n=class{async handleBinaryStringsExtract(o){let c=O(o,`filePath`),l=Math.max(s,Math.min(A(o,`minLength`)??n,e)),u=Math.max(1,Math.min(A(o,`maxResults`)??r,i)),d=k(o,`pattern`),f=d?new RegExp(d,`i`):void 0,p=await C(c),m=[],h=(e,t,n)=>{n.length<l||f&&!f.test(n)||m.push({offset:e,encoding:t,value:n})},g=-1;for(let e=0;e<=p.length;e++){let n=e<p.length?p[e]:0,r=n>=a&&n<=t;if(r&&g<0&&(g=e),(!r||e===p.length)&&g>=0){if(h(g,`ascii`,p.subarray(g,e).toString(`utf8`)),m.length>=u)break;g=-1}}for(let e=0;e+l*2<=p.length&&m.length<u;e+=2){if(p[e+1]!==0)continue;let n=e,r=e;for(;r+1<p.length&&p[r+1]===0&&p[r]>=a&&p[r]<=t;)r+=2;r>n&&(h(n,`utf16le`,p.subarray(n,r).toString(`utf16le`)),e=r)}return D({success:!0,filePath:c,size:p.length,minLength:l,pattern:d,count:m.length,strings:m.slice(0,u),truncated:m.length>=u})}async handleDexScanFile(e){let t=O(e,`filePath`),n=k(e,`outputDir`),r=v(),i=r.dex,a=Math.max(1,Math.min(A(e,`maxHits`)??i.scanDefaultMaxHits,i.scanMaxHits)),o=j(e,`extract`)??!1,s=await C(t);o&&n&&await S(n,{recursive:!0});let c=[],l=[{kind:`dex`,magic:Buffer.from(r.binaryMagic.dexMagicAscii,`ascii`)},{kind:`cdex`,magic:Buffer.from(r.binaryMagic.compactDexMagicAscii,`ascii`)}];for(let e=0;e<s.length&&c.length<a;e++){let t=l.find(t=>e+t.magic.length<=s.length&&s.subarray(e,e+t.magic.length).equals(t.magic));if(!t)continue;let r=s.subarray(e+t.magic.length,Math.min(e+t.magic.length+4,s.length)).toString(`latin1`).replaceAll(`\0`,``),a=e+36<=s.length?s.readUInt32LE(e+32):void 0,u=a!==void 0&&a>112&&a<=s.length-e&&a<i.scanMaxExtractBytes?a:void 0,d;o&&n&&u&&(d=b(n,`${t.kind}_${e.toString(16)}.${t.kind}`),await de(d,s.subarray(e,e+u))),c.push({kind:t.kind,offset:e,offsetHex:`0x${e.toString(16)}`,version:r,fileSize:a,plausibleSize:u,...d?{extractedPath:d}:{}}),e+=Math.max(0,t.magic.length-1)}return D({success:!0,filePath:t,size:s.length,count:c.length,hits:c,truncated:c.length>=a})}async handleBinaryEntropyProfile(e){let t=O(e,`filePath`),n=Math.max(64,A(e,`chunkSize`)??256),r=Math.max(1,A(e,`maxChunks`)??2e3),i=await C(t),a=Math.ceil(i.length/n),o=Math.min(a,r),s=[],c=8,l=0,u=0;for(let e=0;e<o;e++){let t=e*n,r=Math.min(t+n,i.length),a=vn(i.subarray(t,r)),o=a>=7?`high`:a>=4?`medium`:`low`;s.push({index:e,offset:t,offsetHex:`0x${t.toString(16)}`,entropy:Number(a.toFixed(3)),classification:o}),a<c&&(c=a),a>l&&(l=a),u+=a}let d=o>0?u/o:0,f=s.filter(e=>e.classification===`high`);return D({success:!0,filePath:t,size:i.length,chunkSize:n,chunksAnalyzed:o,totalChunks:a,truncated:a>o,stats:{minEntropy:Number(c.toFixed(3)),maxEntropy:Number(l.toFixed(3)),avgEntropy:Number(d.toFixed(3))},highEntropyRegionCount:f.length,highEntropyRegions:f.slice(0,50),note:f.length>0?`${f.length} high-entropy regions (>=7.0 bits/byte) detected — likely encrypted, packed, or compressed. Cross-reference offsets with section headers.`:`No high-entropy regions detected. The binary does not appear to contain encrypted/packed sections at the requested chunk size.`})}};function vn(e){if(e.length===0)return 0;let t=Array.from({length:256},()=>0);for(let n=0;n<e.length;n++)t[e[n]]++;let n=0,r=e.length;for(let e=0;e<256;e++){let i=t[e];if(i===0)continue;let a=i/r;n-=a*Math.log2(a)}return n}var yn=class{state;constructor(e){this.state=e}async handleGenerateHooks(e){let t=k(e,`ghidraOutput`);if(t)return this.handleLegacyGenerateHooks(t);let n=e.ghidraOutput;if(N(n))return this.handleLegacyGenerateHooks(JSON.stringify(n));let r=M(e,`symbols`);if(r.length===0)return E(`symbols or ghidraOutput is required`);let i=be(e,`options`),a=this.getHookGenerator().generateFridaHookScript(r,i);return D({available:!0,symbolCount:r.length,script:a})}async handleExportHookScript(e){let t=k(e,`hookTemplates`);if(!t){let e=this.state.hookCodeGenerator.exportScript([],`frida`);return D({format:`frida`,hookCount:0,script:e.includes(`Java.perform`)?e:`Java.perform(function() {\n${e}\n});`})}try{let e=JSON.parse(t);if(!Array.isArray(e))return E(`Invalid JSON`);let n=Ce(e),r=this.state.hookCodeGenerator.exportScript(n,`frida`);return D({format:`frida`,hookCount:n.length,script:r})}catch{return E(`Invalid JSON`)}}getHookGenerator(){return this.state.hookGen||(this.state.hookGen=new h),this.state.hookGen}handleLegacyGenerateHooks(e){let t;try{t=JSON.parse(e)}catch{return E(`Invalid JSON`)}if(!Se(t))return E(`ghidraOutput is required`);let n=this.state.hookCodeGenerator.generateHooks(t);return D({count:n.length,hooks:n})}},bn=class{async handleFridaDexDump(e){let t=O(e,`outputDir`),n=k(e,`target`),r=A(e,`pid`),i=j(e,`usb`)??!0,a=v().frida,o=A(e,`timeoutMs`)??a.dexDumpTimeoutMs;if(!r&&!n)throw new c(`VALIDATION`,`Either pid or target must be provided for frida_dex_dump`);let s=await l(`frida-dexdump`,[`--help`]);if(!s.available)return D({available:!1,capability:`frida-dexdump`,fix:"Install with `pip install frida-dexdump` and ensure it is on PATH.",reason:s.reason??`frida-dexdump is not available`});await S(t,{recursive:!0});let u=[];i&&u.push(`-U`),r?u.push(`-p`,String(r)):n&&u.push(`-n`,n),u.push(`-o`,t);let d=await new Promise(e=>{T(s.path??`frida-dexdump`,u,{encoding:`utf8`,windowsHide:!0,timeout:o,maxBuffer:a.dexDumpMaxBufferBytes},(t,n,r)=>{e({stdout:typeof n==`string`?n:``,stderr:typeof r==`string`?r:``,exitCode:typeof t?.code==`number`?t.code??1:0,signal:typeof t?.signal==`string`?t.signal??void 0:void 0})})}),f=await this.findFilesByExtension(t,[`.dex`,`.cdex`],a.dexDumpFileLimit),p=d.exitCode===0&&f.length>0;return D({available:!0,success:p,target:n,pid:r,outputDir:t,dumpedFiles:f,count:f.length,...!p&&d.exitCode===0?{reason:`No DEX/CDEX artifacts were produced by frida-dexdump.`}:{},stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode,...d.signal?{signal:d.signal}:{}})}async findFilesByExtension(e,t,n){let{readdir:r}=await import(`node:fs/promises`),{join:i,relative:a}=await import(`node:path`),o=[],s=t.map(e=>e.toLowerCase()),c=async t=>{if(o.length>=n)return;let l=await r(t,{withFileTypes:!0}).catch(()=>[]);for(let r of l){if(o.length>=n)return;let l=i(t,r.name);if(r.isDirectory()){await c(l);continue}r.isFile()&&s.some(e=>r.name.toLowerCase().endsWith(e))&&o.push(a(e,l).replace(/\\/g,`/`))}};return await c(e),o}},xn=class{async handleApktoolDecode(e){let t=O(e,`apkPath`),n=k(e,`outputDir`),r=j(e,`force`)??!1,i=await l(`apktool`,[`--version`]);if(!i.available)return D({available:!1,capability:`apktool_cli`,fix:`Install apktool and ensure it is on PATH.`,apkPath:t,reason:i.reason??`apktool is not available`});let a=n??b(y(),`jshook-apktool-${Date.now()}`);n&&await S(a,{recursive:!0});try{let e=[`decode`,`--output`,a];r&&e.push(`--force`),e.push(t);let n=await I(i.path??`apktool`,e,12e4);return D({available:!0,apkPath:t,outputDir:a,force:r,stdout:n.stdout.trim(),stderr:n.stderr.trim()})}catch(e){return D({available:!0,apkPath:t,outputDir:a,force:r,error:e instanceof Error?e.message:String(e)})}}async handleApktoolBuild(e){let t=O(e,`sourceDir`),n=k(e,`outputPath`),r=j(e,`force`)??!1,i=await l(`apktool`,[`--version`]);if(!i.available)return D({available:!1,capability:`apktool_cli`,fix:`Install apktool and ensure it is on PATH.`,sourceDir:t,reason:i.reason??`apktool is not available`});try{let e=[`b`,t];n&&e.push(`-o`,n),r&&e.push(`-f`);let a=await I(i.path??`apktool`,e,18e4);return D({available:!0,sourceDir:t,outputPath:n??null,force:r,stdout:a.stdout.trim(),stderr:a.stderr.trim()})}catch(e){return D({available:!0,sourceDir:t,outputPath:n??null,force:r,error:e instanceof Error?e.message:String(e)})}}async handleApktoolSign(e){let t=O(e,`apkPath`),n=k(e,`keystore`),r=k(e,`keystorePassword`),i=k(e,`keyAlias`),a=k(e,`keyPassword`),o=k(e,`outputPath`),s=await l(`apksigner`,[`--version`]);if(!s.available)return D({available:!1,capability:`apksigner`,fix:`Install Android build-tools and ensure apksigner is on PATH.`,apkPath:t,reason:s.reason??`apksigner is not available`});if(!n)return D({available:!0,capability:`apksigner`,apkPath:t,signed:!1,fix:`Provide a keystore path (keystore) plus keystorePassword/keyAlias/keyPassword, or build a debug keystore with keytool first.`});try{let e=[`sign`,`--ks`,n];r&&e.push(`--ks-pass`,`pass:${r}`),i&&e.push(`--ks-key-alias`,i),a&&e.push(`--key-pass`,`pass:${a}`),o&&e.push(`--out`,o),e.push(t);let c=await I(s.path??`apksigner`,e,18e4);return D({available:!0,apkPath:t,signed:!0,outputPath:o??null,stdout:c.stdout.trim(),stderr:c.stderr.trim()})}catch(e){return D({available:!0,apkPath:t,signed:!1,outputPath:o??null,error:e instanceof Error?e.message:String(e)})}}},Sn=class{async handleApkNativeLibsList(e){let t=O(e,`apkPath`),n=await Xt(t);if(!n.success)return D({available:!1,apkPath:t,error:n.error});let r=n.entries.filter(e=>/^lib\/.+\/[^/]+\.so$/i.test(e)).map(e=>{let t=e.split(`/`);return{path:e,abi:t[1]??``,name:t[t.length-1]??``}});return D({available:!0,apkPath:t,count:r.length,libraries:r})}},Cn=class{sessions=new Map;async start(e){let t=await Pt({rootDir:e.outputDir,limit:e.maxDexFiles,...e.maxDexFileBytes===void 0?{}:{maxFileBytes:e.maxDexFileBytes},...e.maxTotalDexBytes===void 0?{}:{maxTotalBytes:e.maxTotalDexBytes}}),n=e.mapsPath?await wn(e.mapsPath,{maxBytes:e.maxMapsBytes,moduleLimit:e.maxMapsModules}):{modules:[]},r={sessionId:pe(),createdAt:new Date().toISOString(),target:{...e.packageName?{packageName:e.packageName}:{},...e.pid===void 0?{}:{pid:e.pid}},outputDir:e.outputDir,...e.mapsPath?{mapsPath:e.mapsPath}:{},evidence:{dumpedDex:{count:t.length,files:t},maps:{moduleCount:n.modules.length,modules:n.modules,...n.truncated?{truncated:!0}:{},...n.sourceSize===void 0?{}:{sourceSize:n.sourceSize},...n.bytesRead===void 0?{}:{bytesRead:n.bytesRead}}},recommendedNextSteps:On(t.length,n.modules)};return this.sessions.set(r.sessionId,r),r}status(e){return this.sessions.get(e.sessionId)}list(){return[...this.sessions.values()]}};async function wn(e,t={}){let n=await w(e).catch(()=>void 0);if(!n?.isFile())return{modules:[]};let r=v().androidRuntime,i=En(t.maxBytes,r.mapsMaxBytes),a=En(t.moduleLimit,r.mapsModuleLimit),o=await Tn(e,Math.min(n.size,i)).catch(()=>Buffer.alloc(0)),s=o.toString(`utf8`),c=[],l=new Set;for(let e of s.split(/\r?\n/)){let t=Dn(e);if(!(!t||l.has(t.path))&&(l.add(t.path),c.push(t),c.length>=a))break}return{modules:c,...o.length<n.size||c.length>=a?{truncated:!0}:{},sourceSize:n.size,bytesRead:o.length}}async function Tn(e,t){let n=await ce(e,`r`);try{let e=Buffer.alloc(t),{bytesRead:r}=await n.read(e,0,t,0);return r===e.length?e:e.subarray(0,r)}finally{await n.close()}}function En(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(Math.floor(e),t))}function Dn(e){let t=/^([0-9a-fA-F]+)-([0-9a-fA-F]+)\s+(\S+)\s+([0-9a-fA-F]+)\s+\S+\s+\S+\s*(.*)$/.exec(e.trim());if(!t)return null;let n=(t[5]??``).trim();return!n||n.startsWith(`[`)?null:{start:`0x${t[1]}`,end:`0x${t[2]}`,perms:t[3]??``,offset:`0x${t[4]??`0`}`,path:n}}function On(e,t){let n=t.filter(e=>/\.so$/i.test(e.path));return[e>0?`Run dex_scan_file or jadx_decompile_apk against dumped DEX artifacts selected from this session.`:`No DEX artifacts found in outputDir; rerun frida_dex_dump or collect /proc/PID/mem ranges from maps.`,n.length>0?`Map native modules back to APK libraries, then inspect suspicious .so files with ghidra/unidbg/native-emulator.`:`No native .so modules found in maps snapshot.`]}var kn=class{state;constructor(e){this.state=e}async handleAndroidRuntimeDumpSession(e){let t=k(e,`action`)??`start`,n=this.getAndroidRuntimeDumpManager();if(t===`start`){let r=O(e,`outputDir`),i=k(e,`packageName`),a=A(e,`pid`),o=k(e,`mapsPath`),s=A(e,`maxDexFiles`),c=A(e,`maxDexFileBytes`),l=A(e,`maxTotalDexBytes`),u=A(e,`maxMapsBytes`),d=A(e,`maxMapsModules`),f=await n.start({...i?{packageName:i}:{},...a===void 0?{}:{pid:a},outputDir:r,...o?{mapsPath:o}:{},...s===void 0?{}:{maxDexFiles:s},...c===void 0?{}:{maxDexFileBytes:c},...l===void 0?{}:{maxTotalDexBytes:l},...u===void 0?{}:{maxMapsBytes:u},...d===void 0?{}:{maxMapsModules:d}}),p=f.evidence.dumpedDex.count>0;return D({success:p,action:t,...f,...p?{}:{reason:`No DEX/CDEX artifacts were indexed from outputDir.`}})}if(t===`status`){let r=O(e,`sessionId`),i=n.status({sessionId:r});return D(i?{success:!0,action:t,...i}:{success:!1,action:t,sessionId:r,reason:`Unknown Android runtime dump session: ${r}`})}if(t===`list`){let e=n.list();return D({success:!0,action:t,sessions:e,count:e.length})}throw new c(`VALIDATION`,`action must be one of: start, status, list`)}getAndroidRuntimeDumpManager(){return this.state.androidRuntimeDumpManager||(this.state.androidRuntimeDumpManager=new Cn),this.state.androidRuntimeDumpManager}},An=class{state;constructor(e){this.state=e}async handleGetAvailablePlugins(e){let t=this.state.context?f(this.state.context):[];return D({plugins:t,count:t.length})}},jn=class{state;constructor(e){this.state=e}async handleIdaDecompile(e){return F(this.state.context,`plugin_ida_bridge`,`ida_decompile`,e)}},Mn=class{state;capabilities;fridaSession;jadx;unidbg;ghidra;binaryScan;hooksGeneration;fridaDexDump;apktool;nativeLibs;runtimeDump;pluginBridge;ida;constructor(e,t,n){this.state={hookCodeGenerator:new m,unidbgRunner:new p},e instanceof d?this.state.fridaSession=e:_e(e)&&(this.state.context=e),t&&(this.state.ghidra=t),n&&(this.state.hookGen=n),this.capabilities=new Te(this.state),this.fridaSession=new Ee(this.state),this.jadx=new pn(this.state),this.unidbg=new hn(this.state),this.ghidra=new gn(this.state),this.binaryScan=new _n,this.hooksGeneration=new yn(this.state),this.fridaDexDump=new bn,this.apktool=new xn,this.nativeLibs=new Sn,this.runtimeDump=new kn(this.state),this.pluginBridge=new An(this.state),this.ida=new jn(this.state)}handleBinaryInstrumentCapabilities(){return this.capabilities.handleBinaryInstrumentCapabilities()}handleGetAvailablePlugins(e){return this.pluginBridge.handleGetAvailablePlugins(e)}handleFridaAttach(e){return this.fridaSession.handleFridaAttach(e)}handleFridaSpawn(e){return this.fridaSession.handleFridaSpawn(e)}handleFridaEnumerateModules(e){return this.fridaSession.handleFridaEnumerateModules(e)}handleFridaRunScript(e){return this.fridaSession.handleFridaRunScript(e)}handleFridaResume(e){return this.fridaSession.handleFridaResume(e)}handleFridaDetach(e){return this.fridaSession.handleFridaDetach(e)}handleFridaListSessions(e){return this.fridaSession.handleFridaListSessions(e)}handleFridaGenerateScript(e){return this.fridaSession.handleFridaGenerateScript(e)}handleFridaAttachInterceptor(e){return this.fridaSession.handleFridaAttachInterceptor(e)}handleFridaEnumerateFunctions(e){return this.fridaSession.handleFridaEnumerateFunctions(e)}handleFridaFindSymbols(e){return this.fridaSession.handleFridaFindSymbols(e)}handleFridaMemoryScan(e){return this.fridaSession.handleFridaMemoryScan(e)}handleFridaMemoryRead(e){return this.fridaSession.handleFridaMemoryRead(e)}handleFridaDexDump(e){return this.fridaDexDump.handleFridaDexDump(e)}handleJadxDecompile(e){return this.jadx.handleJadxDecompile(e)}handleJadxDecompileApk(e){return this.jadx.handleJadxDecompileApk(e)}handleJadxSearchCode(e){return this.jadx.handleJadxSearchCode(e)}handleApkManifestDump(e){return this.jadx.handleApkManifestDump(e)}handleApkManifestQuery(e){return this.jadx.handleApkManifestQuery(e)}handleApkStaticTriage(e){return this.jadx.handleApkStaticTriage(e)}handleApkDexIntake(e){return this.jadx.handleApkDexIntake(e)}handleApktoolDecode(e){return this.apktool.handleApktoolDecode(e)}handleApktoolBuild(e){return this.apktool.handleApktoolBuild(e)}handleApktoolSign(e){return this.apktool.handleApktoolSign(e)}handleApkNativeLibsList(e){return this.nativeLibs.handleApkNativeLibsList(e)}handleDexScanFile(e){return this.binaryScan.handleDexScanFile(e)}handleBinaryStringsExtract(e){return this.binaryScan.handleBinaryStringsExtract(e)}handleBinaryEntropyProfile(e){return this.binaryScan.handleBinaryEntropyProfile(e)}handleGenerateHooks(e){return this.hooksGeneration.handleGenerateHooks(e)}handleExportHookScript(e){return this.hooksGeneration.handleExportHookScript(e)}handleUnidbgEmulate(e){return this.unidbg.handleUnidbgEmulate(e)}handleUnidbgLaunch(e){return this.unidbg.handleUnidbgLaunch(e)}handleUnidbgCall(e){return this.unidbg.handleUnidbgCall(e)}handleUnidbgTrace(e){return this.unidbg.handleUnidbgTrace(e)}handleGhidraAnalyze(e){return this.ghidra.handleGhidraAnalyze(e)}handleGhidraDecompile(e){return this.ghidra.handleGhidraDecompile(e)}handleIdaDecompile(e){return this.ida.handleIdaDecompile(e)}handleAndroidRuntimeDumpSession(e){return this.runtimeDump.handleAndroidRuntimeDumpSession(e)}};export{Mn as BinaryInstrumentHandlers,E as _,ve as a,N as c,be as d,j as f,M as g,O as h,xe as i,_e as l,k as m,ye as n,F as o,A as p,P as r,Se as s,I as t,D as u,Ce as v};