@jshookmcp/jshook 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/LICENSE +661 -661
  2. package/README.md +11 -3
  3. package/README.zh.md +11 -3
  4. package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
  5. package/dist/BrowserSessionCoordinator-QIt3tetp.mjs +1 -0
  6. package/dist/CodeInjector-Btj9upnf.mjs +1 -0
  7. package/dist/ConsoleMonitor-DIjN5Afa.mjs +306 -0
  8. package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
  9. package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
  10. package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
  11. package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
  13. package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
  14. package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +1 -0
  15. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
  16. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  17. package/dist/MemoryController-DjtgiING.mjs +2 -0
  18. package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
  19. package/dist/MemoryScanner-Dxd657li.mjs +1 -0
  20. package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
  21. package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
  22. package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
  23. package/dist/ProcessRegistry-D5y1yuP2.mjs +1 -0
  24. package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-nPXl_khE.mjs} +1 -1
  25. package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
  26. package/dist/RingBuffer-B6RTHmij.mjs +1 -0
  27. package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
  28. package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
  29. package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
  30. package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
  31. package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
  32. package/dist/ToolProbe-DQiREmNp.mjs +1 -0
  33. package/dist/ToolRegistry-eMZEBiR1.mjs +1 -0
  34. package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
  35. package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
  36. package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
  37. package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-DoP3MMHS.mjs} +1 -1
  38. package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
  39. package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
  40. package/dist/analysis-C-ln0Brh.mjs +6 -0
  41. package/dist/antidebug-CsnpOR9z.mjs +1 -0
  42. package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
  43. package/dist/{artifacts-B5xQuEa_.mjs → artifacts-D-4pSS_N.mjs} +1 -1
  44. package/dist/betterSqlite3-Bdo_ifuJ.mjs +1 -0
  45. package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
  46. package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
  47. package/dist/browser-BUaB25bk.mjs +11 -0
  48. package/dist/{handlers-pVNpaw4A.mjs → canvas-396ieNv5.mjs} +22 -22
  49. package/dist/collector-CB2syQEg.mjs +1 -0
  50. package/dist/constants-DMv3svps.mjs +2 -0
  51. package/dist/coordination-Dbohmj6D.mjs +1 -0
  52. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  53. package/dist/debugger-CLzkObIO.mjs +1 -0
  54. package/dist/{definitions-CCP9gphV.mjs → definitions-0hxnrDU72.mjs} +1 -1
  55. package/dist/definitions-B3a9QC2t.mjs +1 -0
  56. package/dist/{definitions-DtE0XLrT.mjs → definitions-BOvju5t2.mjs} +1 -1
  57. package/dist/definitions-CXj_cEVt.mjs +1 -0
  58. package/dist/definitions-Co6AvTjH.mjs +1 -0
  59. package/dist/{definitions-Dds_zrWx.mjs → definitions-Cv5r8xwq.mjs} +1 -1
  60. package/dist/definitions-DBYSxChX.mjs +1 -0
  61. package/dist/{definitions-DI9YXsJk.mjs → definitions-D_dTDX9B.mjs} +1 -1
  62. package/dist/{definitions-Dgrg7f3D.mjs → definitions-Db9t2ddh.mjs} +1 -1
  63. package/dist/{definitions-DZ8uKusP.mjs → definitions-DbN2CjI2.mjs} +1 -1
  64. package/dist/{definitions-jXPaVy4P.mjs → definitions-DlmmHmZc.mjs} +1 -1
  65. package/dist/definitions-DnYpoGig.mjs +1 -0
  66. package/dist/{definitions-CYFbewnd.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
  67. package/dist/{definitions-CuJRsJ6N.mjs → definitions-DuIPS8gq.mjs} +1 -1
  68. package/dist/{definitions-BbxOUiP-.mjs → definitions-DywfwPMb.mjs} +1 -1
  69. package/dist/definitions-EGmqr85H.mjs +1 -0
  70. package/dist/{definitions-LaYTuwQd.mjs → definitions-Fetw_Cge.mjs} +3 -3
  71. package/dist/{definitions-NoVp_9Pm.mjs → definitions-LdkeuOeA.mjs} +1 -1
  72. package/dist/{definitions-DJklW2sS.mjs → definitions-Ym8niHDb.mjs} +1 -1
  73. package/dist/{definitions-BGwNSkVm.mjs → definitions-aeRd5DAR.mjs} +1 -1
  74. package/dist/{definitions-CIO9O-Sw.mjs → definitions-cnG6tj17.mjs} +1 -1
  75. package/dist/{encoding-DGcr6Aj_.mjs → encoding-B4xZWErf.mjs} +2 -2
  76. package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
  77. package/dist/{factory-Cx_1LorX.mjs → factory-BxNdBiZa.mjs} +1 -1
  78. package/dist/{graphql-HLf3MS8H.mjs → graphql-GBWsZ9xC.mjs} +4 -4
  79. package/dist/{handlers-DW5AbYs5.mjs → handlers-5nzR8B0a.mjs} +3 -3
  80. package/dist/handlers-6iNsXOVT.mjs +7 -0
  81. package/dist/{handlers-BZoPla6E.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
  82. package/dist/{handlers-Dv_runVv.mjs → handlers-BbLxNbbT.mjs} +1 -1
  83. package/dist/{handlers-BP12ZsWc.mjs → handlers-BbS4hssc.mjs} +2 -2
  84. package/dist/{handlers-BggKiVx9.mjs → handlers-CIKOP4aI.mjs} +2 -2
  85. package/dist/handlers-CWKBBjai.mjs +1 -0
  86. package/dist/handlers-Cmb6SoRC.mjs +1 -0
  87. package/dist/handlers-CrJsKnEI.mjs +1 -0
  88. package/dist/{antidebug-BOTZH6-0.mjs → handlers-DB6xVVWq.mjs} +4 -4
  89. package/dist/{handlers-DmQzIc44.mjs → handlers-DOOCWUNR.mjs} +3 -3
  90. package/dist/{handlers-BLMa4X7l.mjs → handlers-Z_B5aVaU.mjs} +2 -2
  91. package/dist/handlers-gVscChvl.mjs +1 -0
  92. package/dist/handlers-xFvI9P_y.mjs +1 -0
  93. package/dist/handlers.impl-BsFTW6SD.mjs +1 -0
  94. package/dist/{hooks-DDKppogd.mjs → hooks-DPouiS7I.mjs} +9 -9
  95. package/dist/index.mjs +11 -15
  96. package/dist/macro-p8kuJVcm.mjs +2 -0
  97. package/dist/maintenance-DAqADb6Z.mjs +302 -0
  98. package/dist/manifest-4lmM6MZR.mjs +1 -0
  99. package/dist/{manifest-D610kxZr.mjs → manifest-AxaxRSt6.mjs} +2 -2
  100. package/dist/{manifest-CDeUZGUZ.mjs → manifest-BIqRE1Qz.mjs} +1 -1
  101. package/dist/{manifest-Dm0o3i2U.mjs → manifest-Box-jWfr.mjs} +1 -1
  102. package/dist/manifest-Bp33di0Q.mjs +1 -0
  103. package/dist/{manifest-CGq4NpqH2.mjs → manifest-BvRX4nRP.mjs} +1 -1
  104. package/dist/{manifest-yu2xiQqe.mjs → manifest-C6KoB1XE.mjs} +1 -1
  105. package/dist/manifest-C7TdXCWY.mjs +1 -0
  106. package/dist/manifest-CM-n64K0.mjs +1 -0
  107. package/dist/{manifest-DWUUWBz0.mjs → manifest-CUokxCUN.mjs} +1 -1
  108. package/dist/manifest-CWJS45iO.mjs +1 -0
  109. package/dist/{manifest-D44TaRJU.mjs → manifest-Cdxdgo-D.mjs} +1 -1
  110. package/dist/{manifest-DKUorv5M.mjs → manifest-Cf6SmamD.mjs} +1 -1
  111. package/dist/manifest-Cgxu2qdv.mjs +1 -0
  112. package/dist/manifest-CowGSURa2.mjs +1 -0
  113. package/dist/manifest-CsGIrh34.mjs +1 -0
  114. package/dist/manifest-CvDpVToN.mjs +1 -0
  115. package/dist/manifest-D8TL9RLE.mjs +1 -0
  116. package/dist/{manifest-C7qV1z7F.mjs → manifest-DIhtCBe6.mjs} +1 -1
  117. package/dist/{manifest-CeQmtQOY.mjs → manifest-DJbruNOg.mjs} +1 -1
  118. package/dist/manifest-DLGtZH-0.mjs +1 -0
  119. package/dist/manifest-DXHdPt2T.mjs +1 -0
  120. package/dist/{manifest-DMJlcsTR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
  121. package/dist/{manifest-C1nZkTkO.mjs → manifest-DzGoTS0R.mjs} +1 -1
  122. package/dist/manifest-G2H52LKz.mjs +131 -0
  123. package/dist/manifest-P0Futrgb.mjs +1 -0
  124. package/dist/{manifest-CDiCtaQT.mjs → manifest-Qw7xgvjv.mjs} +1 -1
  125. package/dist/{manifest-Dgh0uDW-.mjs → manifest-W3qvVrP2.mjs} +1 -1
  126. package/dist/manifest-dG6MuR1U.mjs +1 -0
  127. package/dist/manifest-nWXtgq5Y2.mjs +1 -0
  128. package/dist/{manifest-BPuE6oH2.mjs → manifest-vp1upSSq.mjs} +1 -1
  129. package/dist/modules-DO3jXCgj.mjs +333 -0
  130. package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
  131. package/dist/native/scripts/linux/enum-windows.sh +12 -12
  132. package/dist/native/scripts/macos/enum-windows.applescript +22 -22
  133. package/dist/native-g095qhpK.mjs +961 -0
  134. package/dist/network-Dvxm7eEI.mjs +7 -0
  135. package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
  136. package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-ngRrvF9e.mjs} +1 -1
  137. package/dist/platform-DjWbuiF8.mjs +93 -0
  138. package/dist/process-Dq5I-KZW.mjs +2 -0
  139. package/dist/proxy-DPNgM7TE.mjs +2 -0
  140. package/dist/{registry-DUHIPE-v.mjs → registry-xB8Wgmyj.mjs} +1 -1
  141. package/dist/renderer-pid-7jbTR8f5.mjs +1 -0
  142. package/dist/search-defaults-CJik67or.mjs +1 -0
  143. package/dist/server/plugin-api.d.mts +19 -36
  144. package/dist/server/plugin-api.mjs +1 -1
  145. package/dist/sourcemap-DqEW15Ao.mjs +1 -0
  146. package/dist/streaming-Dbk4eStJ.mjs +1 -0
  147. package/dist/transform-D-peM3aO.mjs +103 -0
  148. package/dist/wasm-CZajRaad.mjs +174 -0
  149. package/dist/{webcrack-CsLLJIs9.mjs → webcrack-phEfVt5y.mjs} +3 -3
  150. package/dist/{workflow-CYIXtrWD.mjs → workflow-wkXb3x-U.mjs} +4 -4
  151. package/package.json +16 -15
  152. package/src/native/scripts/linux/enum-windows.sh +12 -12
  153. package/src/native/scripts/macos/enum-windows.applescript +22 -22
  154. package/dist/CodeInjector-BlgyqTOk.mjs +0 -1
  155. package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
  156. package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
  157. package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
  158. package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
  159. package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
  160. package/dist/MemoryController-BaqstM5w.mjs +0 -2
  161. package/dist/MemoryScanner-BLYnMJy6.mjs +0 -1
  162. package/dist/NativeMemoryManager.impl-CI554XbY.mjs +0 -1
  163. package/dist/PageController-D9jVkH0i.mjs +0 -1
  164. package/dist/PointerChainEngine-5nF9eNlu.mjs +0 -1
  165. package/dist/PrerequisiteError-Bl3dK8XA.mjs +0 -1
  166. package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
  167. package/dist/ScriptManager-fgqiALgj.mjs +0 -7
  168. package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
  169. package/dist/ToolProbe-xsfALmN3.mjs +0 -1
  170. package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
  171. package/dist/ToolRouter.policy-CFHoN_Lw.mjs +0 -4
  172. package/dist/VersionDetector-DMoUWyNm.mjs +0 -9
  173. package/dist/analysis-BuR-NgX8.mjs +0 -5
  174. package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
  175. package/dist/binary-instrument-Cf9qqLlM.mjs +0 -7
  176. package/dist/browser-C4Le3xqA.mjs +0 -11
  177. package/dist/collector-CKO8RPK8.mjs +0 -1
  178. package/dist/constants-Cp6hBrrx.mjs +0 -1
  179. package/dist/coordination-BbijHEHH.mjs +0 -1
  180. package/dist/debugger-CRJq_krh.mjs +0 -1
  181. package/dist/definitions-BGobEDQa.mjs +0 -1
  182. package/dist/definitions-CdWEuIkI.mjs +0 -1
  183. package/dist/definitions-CoQFbggH.mjs +0 -1
  184. package/dist/definitions-OvGsfxdt.mjs +0 -1
  185. package/dist/ensure-browser-core-Buls24LQ.mjs +0 -1
  186. package/dist/flat-target-session-CO5g78k3.mjs +0 -1
  187. package/dist/handlers-D3iev8g1.mjs +0 -1
  188. package/dist/handlers-D49r1-1P.mjs +0 -1
  189. package/dist/handlers-DCE45Ww8.mjs +0 -2
  190. package/dist/handlers-De5u62Ga2.mjs +0 -1
  191. package/dist/handlers-DnJRGp7t.mjs +0 -302
  192. package/dist/handlers-S9Ws0IGy.mjs +0 -2
  193. package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
  194. package/dist/maintenance-CutEO84j.mjs +0 -1
  195. package/dist/manifest-BFGxlDRh.mjs +0 -123
  196. package/dist/manifest-BXry5N09.mjs +0 -1
  197. package/dist/manifest-BeP_zJGb2.mjs +0 -1
  198. package/dist/manifest-C0g67k6U.mjs +0 -1
  199. package/dist/manifest-CFn0359q2.mjs +0 -1
  200. package/dist/manifest-CJMGt7Qy.mjs +0 -1
  201. package/dist/manifest-CRIJq4Hs.mjs +0 -1
  202. package/dist/manifest-C_hEIjSx.mjs +0 -1
  203. package/dist/manifest-Cq0j7GZt.mjs +0 -1
  204. package/dist/manifest-CtPmHAdn.mjs +0 -1
  205. package/dist/manifest-Cx2IVMUY.mjs +0 -1
  206. package/dist/manifest-D16xPXro.mjs +0 -1
  207. package/dist/manifest-DC-SMF6b.mjs +0 -1
  208. package/dist/manifest-DD3rtxvV.mjs +0 -1
  209. package/dist/manifest-De-6Wf2R.mjs +0 -1
  210. package/dist/manifest-DsVh7Y4U.mjs +0 -1
  211. package/dist/manifest-DtEFSRaq.mjs +0 -1
  212. package/dist/manifest-H-EpAyZQ.mjs +0 -1
  213. package/dist/manifest-ais9Afrw.mjs +0 -1
  214. package/dist/manifest-tmb54wmA.mjs +0 -1
  215. package/dist/manifest-zrbrpKCC.mjs +0 -1
  216. package/dist/matchesWildcardPattern-BGqLSmEs.mjs +0 -1
  217. package/dist/modules-p-PUNv9r.mjs +0 -332
  218. package/dist/network-BjZ1Y-GB.mjs +0 -7
  219. package/dist/outputPaths-BonGThuc.mjs +0 -2
  220. package/dist/platform-C446Lf97.mjs +0 -93
  221. package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +0 -1
  222. package/dist/process-C9f2A5zk.mjs +0 -962
  223. package/dist/proxy-CvRepxgV.mjs +0 -1
  224. package/dist/search-defaults-D2bY-rzH.mjs +0 -1
  225. package/dist/shared-state-board-Cyg-xh_k.mjs +0 -1
  226. package/dist/sourcemap-D6Q1UuAp.mjs +0 -1
  227. package/dist/streaming-CTX58tbb.mjs +0 -1
  228. package/dist/transform-Cv9P2vVD.mjs +0 -103
  229. package/dist/types-DtThH00r.mjs +0 -1
  230. package/dist/wasm-DaJa8J0V.mjs +0 -174
  231. /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  232. /package/dist/{EventBus-DgciURGg.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  233. /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  234. /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  235. /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
  236. /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  237. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  238. /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  239. /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  240. /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-L1ax5EHS.mjs} +0 -0
  241. /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
  242. /package/dist/{concurrency-CcK46d0h.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  243. /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  244. /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  245. /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
  246. /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
  247. /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  248. /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  249. /package/dist/{types-CuyefmGT.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -0,0 +1 @@
1
+ import{Qn as e,Xn as t,Zn as n}from"./constants-DMv3svps.mjs";import{t as r}from"./ToolError-g3rjWzhx.mjs";import{c as i,i as a,n as o,o as s,r as c,s as l,t as u}from"./parse-args-ngRrvF9e.mjs";import{n as d}from"./ResponseBuilder-nPXl_khE.mjs";import{readFile as f}from"node:fs/promises";import{randomUUID as p}from"node:crypto";import{open as m}from"yauzl";const h=[127,69,76,70];var g=class{is64Bit;isLittleEndian;type;machine;entry;bytes;view;phoff;phentsize;phnum;shoff;shentsize;shnum;constructor(e){if(e.length<64||e[0]!==h[0]||e[1]!==h[1]||e[2]!==h[2]||e[3]!==h[3])throw Error(`Not an ELF file (bad magic)`);if(this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.is64Bit=e[4]===2,this.isLittleEndian=e[5]===1,!this.is64Bit)throw Error(`Only ELF64 is supported`);let t=this.isLittleEndian;this.type=this.view.getUint16(16,t),this.machine=this.view.getUint16(18,t),this.entry=Number(this.view.getBigUint64(24,t)),this.phoff=Number(this.view.getBigUint64(32,t)),this.phentsize=this.view.getUint16(54,t),this.phnum=this.view.getUint16(56,t),this.shoff=Number(this.view.getBigUint64(40,t)),this.shentsize=this.view.getUint16(58,t),this.shnum=this.view.getUint16(60,t)}loadableSegments(){let e=this.isLittleEndian,t=[];for(let n=0;n<this.phnum;n++){let r=this.phoff+n*this.phentsize;if(this.view.getUint32(r+0,e)!==1)continue;let i=this.view.getUint32(r+4,e),a=Number(this.view.getBigUint64(r+8,e)),o=Number(this.view.getBigUint64(r+16,e)),s=Number(this.view.getBigUint64(r+32,e)),c=Number(this.view.getBigUint64(r+40,e)),l=new Uint8Array(c);l.set(this.bytes.subarray(a,a+s),0),t.push({vaddr:o,fileSize:s,memSize:c,readable:(i&4)!=0,writable:(i&2)!=0,executable:(i&1)!=0,data:l})}return t}exportedSymbols(){let e=new Map,t=this.isLittleEndian,n=-1;for(let e=0;e<this.shnum;e++){let r=this.shoff+e*this.shentsize;if(this.view.getUint32(r+4,t)===11){n=r;break}}if(n<0)return this.exportedSymbolsFromDynamic();let r=Number(this.view.getBigUint64(n+24,t)),i=Number(this.view.getBigUint64(n+32,t)),a=this.view.getUint32(n+40,t),o=this.shoff+a*this.shentsize,s=Number(this.view.getBigUint64(o+24,t)),c=Number(this.view.getBigUint64(o+32,t)),l=Math.floor(i/24);for(let n=1;n<l;n++){let i=r+n*24,a=this.view.getUint32(i+0,t),o=Number(this.view.getBigUint64(i+8,t)),l=this.view.getUint16(i+6,t),u=this.readCString(s,c,a);u&&l!==0&&e.set(u,o)}return e}exportedSymbolsFromDynamic(){let e=new Map,t=this.dynamicInfo();if(!t||t.symtab===0||t.strtab===0)return e;let n=this.isLittleEndian,r=this.vaddrToOffset(t.symtab),i=this.vaddrToOffset(t.strtab);if(r<0||i<0)return e;let a=i>r?i:this.bytes.length,o=Math.floor((a-r)/24);for(let a=1;a<o;a++){let o=r+a*24;if(o+24>this.bytes.length)break;let s=this.view.getUint32(o+0,n),c=this.view.getUint16(o+6,n),l=Number(this.view.getBigUint64(o+8,n)),u=this.readCString(i,t.strsz||this.bytes.length-i,s);u&&c!==0&&e.set(u,l)}return e}relocations(){let e=this.dynamicInfo();if(!e)return[];let t=this.isLittleEndian,n=[],r=e.symtab?this.vaddrToOffset(e.symtab):-1,i=e.strtab?this.vaddrToOffset(e.strtab):-1,a=(a,o)=>{if(a===0||o===0)return;let s=this.vaddrToOffset(a);if(s<0)return;let c=Math.floor(o/24);for(let a=0;a<c;a++){let o=s+a*24;if(o+24>this.bytes.length)break;let c=Number(this.view.getBigUint64(o+0,t)),l=this.view.getBigUint64(o+8,t),u=Number(BigInt.asIntN(64,this.view.getBigUint64(o+16,t))),d=Number(l&4294967295n),f=Number(l>>32n),p=``,m=0;if(f>0&&r>=0){let n=r+f*24;if(n+24<=this.bytes.length){let r=this.view.getUint32(n+0,t);m=Number(this.view.getBigUint64(n+8,t)),i>=0&&(p=this.readCString(i,e.strsz||this.bytes.length-i,r))}}n.push({offset:c,type:d,addend:u,symbolName:p,symbolValue:m})}};return a(e.rela,e.relasz),a(e.jmprel,e.pltrelsz),n}initializers(){let e=this.dynamicInfo();if(!e)return{init:0,arraySlots:[]};let t=[],n=Math.floor(e.initArraySz/8);for(let r=0;r<n;r++)t.push(e.initArray+r*8);return{init:e.init,arraySlots:t}}dynamicInfo(){let e=this.isLittleEndian,t=-1,n=0;for(let r=0;r<this.phnum;r++){let i=this.phoff+r*this.phentsize;if(this.view.getUint32(i+0,e)===2){t=Number(this.view.getBigUint64(i+8,e)),n=Number(this.view.getBigUint64(i+32,e));break}}if(t<0)return null;let r={symtab:0,strtab:0,strsz:0,rela:0,relasz:0,jmprel:0,pltrelsz:0,init:0,initArray:0,initArraySz:0},i=Math.floor(n/16);for(let n=0;n<i;n++){let i=t+n*16,a=Number(BigInt.asIntN(64,this.view.getBigUint64(i+0,e))),o=Number(this.view.getBigUint64(i+8,e));if(a===0)break;switch(a){case 6:r.symtab=o;break;case 5:r.strtab=o;break;case 10:r.strsz=o;break;case 7:r.rela=o;break;case 8:r.relasz=o;break;case 23:r.jmprel=o;break;case 2:r.pltrelsz=o;break;case 12:r.init=o;break;case 25:r.initArray=o;break;case 27:r.initArraySz=o;break;default:break}}return r}vaddrToOffset(e){let t=this.isLittleEndian;for(let n=0;n<this.phnum;n++){let r=this.phoff+n*this.phentsize;if(this.view.getUint32(r+0,t)!==1)continue;let i=Number(this.view.getBigUint64(r+8,t)),a=Number(this.view.getBigUint64(r+16,t)),o=Number(this.view.getBigUint64(r+32,t));if(e>=a&&e<a+o)return i+(e-a)}return-1}readCString(e,t,n){if(n<=0||n>=t)return``;let r=e+n,i=e+t;for(;r<i&&this.bytes[r]!==0;)r++;return new TextDecoder().decode(this.bytes.subarray(e+n,r))}};const ee=Uint8Array.from([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),te=Uint8Array.from([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]);function _(e,t){let n=0,r=e,i=t;for(let e=0;e<8;e++){i&1&&(n^=r);let e=r&128;r=r<<1&255,e&&(r^=27),i>>=1}return n&255}function ne(e){let t=e.slice();for(let n=0;n<4;n++)for(let r=0;r<4;r++)e[r*4+n]=t[(r+n)%4*4+n]??0}function re(e){let t=e.slice();for(let n=0;n<4;n++)for(let r=0;r<4;r++)e[r*4+n]=t[((r-n)%4+4)%4*4+n]??0}function ie(e,t){for(let n=0;n<16;n++)e[n]=t[e[n]??0]??0}function ae(e){for(let t=0;t<4;t++){let n=e[t*4]??0,r=e[t*4+1]??0,i=e[t*4+2]??0,a=e[t*4+3]??0;e[t*4]=_(n,2)^_(r,3)^i^a,e[t*4+1]=n^_(r,2)^_(i,3)^a,e[t*4+2]=n^r^_(i,2)^_(a,3),e[t*4+3]=_(n,3)^r^i^_(a,2)}}function oe(e){for(let t=0;t<4;t++){let n=e[t*4]??0,r=e[t*4+1]??0,i=e[t*4+2]??0,a=e[t*4+3]??0;e[t*4]=_(n,14)^_(r,11)^_(i,13)^_(a,9),e[t*4+1]=_(n,9)^_(r,14)^_(i,11)^_(a,13),e[t*4+2]=_(n,13)^_(r,9)^_(i,14)^_(a,11),e[t*4+3]=_(n,11)^_(r,13)^_(i,9)^_(a,14)}}function se(e,t){let n=Uint8Array.from(e);for(let e=0;e<16;e++)n[e]=(n[e]??0)^(t[e]??0);return ne(n),ie(n,ee),n}function ce(e,t){let n=Uint8Array.from(e);for(let e=0;e<16;e++)n[e]=(n[e]??0)^(t[e]??0);return re(n),ie(n,te),n}function le(e){let t=Uint8Array.from(e);return ae(t),t}function ue(e){let t=Uint8Array.from(e);return oe(t),t}const v=e=>e>>>0,y=(e,t)=>v(e>>>t|e<<32-t),b=(...e)=>e.reduce((e,t)=>v(e+t),0),de=e=>y(e,2)^y(e,13)^y(e,22),fe=e=>y(e,6)^y(e,11)^y(e,25),pe=e=>y(e,7)^y(e,18)^e>>>3,me=e=>y(e,17)^y(e,19)^e>>>10,he=(e,t,n)=>e&t^~e&n,ge=(e,t,n)=>e&t^e&n^t&n;function x(e){let t=new DataView(e.buffer,e.byteOffset,16);return[t.getUint32(0,!0),t.getUint32(4,!0),t.getUint32(8,!0),t.getUint32(12,!0)]}function S(e,t,n,r){let i=new Uint8Array(16),a=new DataView(i.buffer);return a.setUint32(0,v(e),!0),a.setUint32(4,v(t),!0),a.setUint32(8,v(n),!0),a.setUint32(12,v(r),!0),i}function _e(e,t,n){let[r,i,a,o]=e,[s,c,l,u]=t;for(let e=0;e<4;e++){let t=b(u,fe(s),he(s,c,l),n[e]??0),d=b(de(r),ge(r,i,a));u=l,l=c,c=s,s=b(o,t),o=a,a=i,i=r,r=b(t,d)}return{abcd:[r,i,a,o],efgh:[s,c,l,u]}}function ve(e,t,n){let r=_e(x(e),x(t),x(n));return S(r.abcd[0],r.abcd[1],r.abcd[2],r.abcd[3])}function ye(e,t,n){let r=_e(x(t),x(e),x(n));return S(r.efgh[0],r.efgh[1],r.efgh[2],r.efgh[3])}function be(e,t){let[n,r,i,a]=x(e),o=x(t)[0];return S(b(n,pe(r)),b(r,pe(i)),b(i,pe(a)),b(a,pe(o)))}function xe(e,t,n){let r=x(e),i=x(t),a=x(n),o=b(r[0],i[1],me(a[2])),s=b(r[1],i[2],me(a[3]));return S(o,s,b(r[2],i[3],me(o)),b(r[3],a[0],me(s)))}const C=(e,t)=>v(e<<t|e>>>32-t),Se=(e,t,n)=>e&t|~e&n,Ce=(e,t,n)=>e^t^n,we=(e,t,n)=>e&t|e&n|t&n;function Te(e){return C(v(e),30)}function Ee(e,t,n,r){let i=r===`choose`?Se:r===`majority`?we:Ce,[a,o,s,c]=x(e),l=v(t),u=x(n);for(let e=0;e<4;e++){let t=b(C(a,5),i(o,s,c),l,u[e]??0);l=c,c=s,s=C(o,30),o=a,a=t}return{abcd:S(a,o,s,c),e:l}}function De(e,t,n){let r=x(e),i=x(t),a=x(n);return S(r[0]^r[2]^a[0],r[1]^r[3]^a[1],r[2]^i[0]^a[2],r[3]^i[1]^a[3])}function Oe(e,t){let n=x(e),r=x(t),i=C(n[0]^r[1],1);return S(i,C(n[1]^r[2],1),C(n[2]^r[3],1),C(n[3]^i,1))}function ke(e,t){let n=0n,r=e&18446744073709551615n,i=t&18446744073709551615n;for(;i!==0n;)i&1n&&(n^=r),r<<=1n,i>>=1n;return n&(1n<<128n)-1n}function Ae(e,t){return new DataView(e.buffer,e.byteOffset,16).getBigUint64(t*8,!0)}function je(e){let t=new Uint8Array(16),n=new DataView(t.buffer);return n.setBigUint64(0,e&18446744073709551615n,!0),n.setBigUint64(8,e>>64n&18446744073709551615n,!0),t}function Me(e,t){return je(ke(Ae(e,0),Ae(t,0)))}function Ne(e,t){return je(ke(Ae(e,1),Ae(t,1)))}const w=e=>Math.fround(e);function Pe(e){return new DataView(e.buffer,e.byteOffset,16).getFloat32(0,!0)}function Fe(e){return new DataView(e.buffer,e.byteOffset,16).getFloat64(0,!0)}function Ie(e){let t=new Uint8Array(16);return new DataView(t.buffer).setFloat32(0,w(e),!0),t}function Le(e){let t=new Uint8Array(16);return new DataView(t.buffer).setFloat64(0,e,!0),t}function T(e,t){return t?Fe(e):Pe(e)}function E(e,t){return t?Le(e):Ie(e)}const Re=(e,t,n)=>n?e+t:w(e+t),ze=(e,t,n)=>n?e-t:w(e-t),Be=(e,t,n)=>n?e*t:w(e*t),Ve=(e,t,n)=>n?e/t:w(e/t),He=(e,t,n)=>n?-(e*t):w(-(e*t)),Ue=(e,t,n)=>Number.isNaN(e)||Number.isNaN(t)?n?NaN:w(NaN):e===0&&t===0?Object.is(e,-0)?t:e:n?Math.max(e,t):w(Math.max(e,t)),We=(e,t,n)=>Number.isNaN(e)||Number.isNaN(t)?n?NaN:w(NaN):e===0&&t===0?Object.is(e,-0)?e:t:n?Math.min(e,t):w(Math.min(e,t)),Ge=(e,t)=>t?Math.abs(e):w(Math.abs(e)),Ke=(e,t)=>t?-e:w(-e),qe=(e,t)=>t?Math.sqrt(e):w(Math.sqrt(e));function Je(e,t){return Number.isNaN(e)||Number.isNaN(t)?{n:!1,z:!1,c:!0,v:!0}:e<t?{n:!0,z:!1,c:!1,v:!1}:e===t?{n:!1,z:!0,c:!0,v:!1}:{n:!1,z:!1,c:!0,v:!1}}function Ye(e,t){switch(t){case`zero`:return Math.trunc(e);case`minus`:return Math.floor(e);case`plus`:return Math.ceil(e);case`away`:return e<0?-Math.round(-e):Math.round(e);case`nearest`:{let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2==0?t:t+1}}}function Xe(e,t,n,r){if(Number.isNaN(e))return 0n;let i=Ye(e,t);if(n){let e=r===64?-(2n**63n):-(2n**31n),t=r===64?2n**63n-1n:2n**31n-1n;if(i===1/0||i>Number(t))return t;if(i===-1/0||i<Number(e))return e;let n=BigInt(Math.trunc(i));return n>t&&(n=t),n<e&&(n=e),n}let a=r===64?2n**64n-1n:2n**32n-1n;if(i<=0)return 0n;if(i===1/0||i>Number(a))return a;let o=BigInt(Math.trunc(i));return o>a&&(o=a),o}function Ze(e,t,n,r){let i=BigInt.asUintN(n,e),a=t?BigInt.asIntN(n,i):i;return r?Number(a):w(Number(a))}function Qe(e,t){return t?e:w(e)}const D=e=>1<<e;function O(e,t,n){let r=D(t),i=(n===1?16:8)/r,a=new DataView(e.buffer,e.byteOffset,16),o=[];for(let e=0;e<i;e++){let t=e*r;switch(r){case 1:o.push(BigInt(a.getUint8(t)));break;case 2:o.push(BigInt(a.getUint16(t,!0)));break;case 4:o.push(BigInt(a.getUint32(t,!0)));break;default:o.push(a.getBigUint64(t,!0));break}}return o}function k(e,t){let n=D(t),r=new Uint8Array(16),i=new DataView(r.buffer);for(let t=0;t<e.length;t++){let r=t*n;if(r+n>16)break;let a=e[t]??0n;switch(n){case 1:i.setUint8(r,Number(a&255n));break;case 2:i.setUint16(r,Number(a&65535n),!0);break;case 4:i.setUint32(r,Number(a&4294967295n),!0);break;default:i.setBigUint64(r,a&18446744073709551615n,!0);break}}return r}const A=e=>(1n<<BigInt(e*8))-1n;function j(e,t){let n=BigInt(t*8);return(e&1n<<n-1n)==0n?e:e-(1n<<n)}function M(e,t,n,r,i){let a=O(e,n,r),o=O(t,n,r),s=D(n),c=A(s);return k(a.map((e,t)=>i(e,o[t]??0n,c,s)&c),n)}const $e=(e,t,n,r)=>M(e,t,n,r,(e,t)=>e+t),et=(e,t,n,r)=>M(e,t,n,r,(e,t)=>e-t),tt=(e,t,n,r)=>M(e,t,n,r,(e,t)=>e*t),nt=(e,t,n)=>M(e,t,3,n,(e,t)=>e&t),rt=(e,t,n)=>M(e,t,3,n,(e,t)=>e|t),it=(e,t,n)=>M(e,t,3,n,(e,t)=>e^t),at=(e,t,n)=>M(e,t,3,n,(e,t,n)=>e&~t&n),ot=(e,t,n)=>M(e,t,3,n,(e,t,n)=>e|~t&n),st=(e,t,n,r)=>{let i=O(e,3,r),a=O(t,3,r),o=O(n,3,r),s=A(8);return k(i.map((e,t)=>(e&(a[t]??0n)|(o[t]??0n)&~(a[t]??0n)&s)&s),3)},N=e=>e,P=0n,ct=(e,t,n,r)=>M(e,t,n,r,(e,t,n)=>e===t?N(n):P),lt=(e,t,n,r)=>M(e,t,n,r,(e,t,n,r)=>j(e,r)>j(t,r)?N(n):P),ut=(e,t,n,r)=>M(e,t,n,r,(e,t,n,r)=>j(e,r)>=j(t,r)?N(n):P),dt=(e,t,n,r)=>M(e,t,n,r,(e,t,n)=>e>t?N(n):P),ft=(e,t,n,r)=>M(e,t,n,r,(e,t,n)=>e>=t?N(n):P),pt=(e,t,n,r)=>M(e,t,n,r,(e,t,n)=>(e&t)===0n?P:N(n)),mt=(e,t,n,r)=>M(e,t,n,r,(e,t,n,r)=>j(e,r)>j(t,r)?e:t),ht=(e,t,n,r)=>M(e,t,n,r,(e,t,n,r)=>j(e,r)<j(t,r)?e:t),gt=(e,t,n,r)=>M(e,t,n,r,(e,t)=>e>t?e:t),_t=(e,t,n,r)=>M(e,t,n,r,(e,t)=>e<t?e:t);function F(e,t,n,r){let i=O(e,t,n),a=D(t),o=A(a);return k(i.map(e=>r(e,o,a)&o),t)}const vt=(e,t,n)=>F(e,t,n,(e,t)=>~e+1n&t),yt=(e,t,n)=>F(e,t,n,(e,t,n)=>{let r=j(e,n);return(r<0n?-r:r)&t}),bt=(e,t)=>F(e,0,t,(e,t)=>~e&t),xt=(e,t)=>F(e,0,t,e=>{let t=e&255n,n=0n;for(;t;)n+=t&1n,t>>=1n;return n}),St=(e,t,n)=>F(e,t,n,(e,t,n)=>{let r=n*8;if(e===0n)return BigInt(r);let i=0n;for(let t=r-1;t>=0&&!(e>>BigInt(t)&1n);t--)i++;return i}),Ct=(e,t,n)=>F(e,t,n,(e,t)=>e===0n?t:0n);function wt(e,t,n){let r=n===1?16:8,i=new Uint8Array(16);for(let n=0;n<r;n+=t)for(let r=0;r<t;r++)i[n+r]=e[n+t-1-r]??0;return i}function Tt(e,t,n,r){let i=O(e,t,1)[n]??0n,a=(r===1?16:8)/D(t);return k(Array.from({length:a},()=>i),t)}function Et(e,t,n){let r=e&A(D(t)),i=(n===1?16:8)/D(t);return k(Array.from({length:i},()=>r),t)}const Dt=(e,t,n,r)=>F(e,t,r,(e,t)=>e<<BigInt(n)&t),Ot=(e,t,n,r)=>F(e,t,r,e=>e>>BigInt(n)),kt=(e,t,n,r)=>F(e,t,r,(e,t,r)=>j(e,r)>>BigInt(n)&t);function I(e,t,n,r){let i=O(e,t,n),a=D(t),o=i[0]??0n;for(let e=1;e<i.length;e++)o=r(o,i[e]??0n,a);return k([o&A(a)],t)}const At=(e,t,n)=>I(e,t,n,(e,t)=>e+t),jt=(e,t,n)=>I(e,t,n,(e,t,n)=>j(e,n)>=j(t,n)?e:t),Mt=(e,t,n)=>I(e,t,n,(e,t,n)=>j(e,n)<=j(t,n)?e:t),Nt=(e,t,n)=>I(e,t,n,(e,t)=>e>=t?e:t),Pt=(e,t,n)=>I(e,t,n,(e,t)=>e<=t?e:t);function Ft(e,t,n,r,i){let a=O(e,n,r),o=O(t,n,r),s=a.length,c=i*s/2,l=[];for(let e=0;e<s;e++){let t=e>>1;l.push(e&1?o[c+t]??0n:a[c+t]??0n)}return k(l,n)}function It(e,t,n,r,i){let a=O(e,n,r),o=O(t,n,r),s=a.length,c=[];for(let e=0;e<s;e++){let t=2*e+i;c.push(t<s?a[t]??0n:o[t-s]??0n)}return k(c,n)}function Lt(e,t,n,r,i){let a=O(e,n,r),o=O(t,n,r),s=a.length,c=[];for(let e=0;e<s;e++){let t=(e&-2)+i;c.push(e&1?o[t]??0n:a[t]??0n)}return k(c,n)}function Rt(e,t,n,r){let i=r===1?16:8,a=new Uint8Array(i*2);a.set(e.subarray(0,i),0),a.set(t.subarray(0,i),i);let o=new Uint8Array(16);for(let e=0;e<i;e++)o[e]=a[n+e]??0;return o}function zt(e,t,n,r,i){let a=n===1?16:8,o=e.length,s=new Uint8Array(16);i&&s.set(r.subarray(0,16));for(let n=0;n<a;n++){let r=t[n]??0;r<o?s[n]=e[r]??0:i||(s[n]=0)}return n===0&&s.fill(0,8),s}const L=e=>e|e<<32n;function Bt(e,t,n){let r=t>>1&7,i=t&1,a=BigInt(n&255);switch(r){case 0:return L(a);case 1:return L(a<<8n);case 2:return L(a<<16n);case 3:return L(a<<24n);case 4:return L(a|a<<16n);case 5:return L(a<<8n|a<<24n);case 6:{let e=i===0?8n:16n,t=(1n<<e)-1n;return L(a<<e|t)}default:if(i===0){let e=0n;for(let t=0;t<8;t++)e|=a<<BigInt(t*8);return e}if(e===0){let e=0n;for(let t=0;t<8;t++)n>>t&1&&(e|=255n<<BigInt(t*8));return e}return L(a)}}function Vt(e,t){let n=(e,n)=>t>>>n&(1<<e-n+1)-1,r=n(29,27);return r===7?Ut(e,t):r===5?Wt(e,t):r===3&&n(25,24)===0?Gt(e,t):r===1&&n(24,24)===0?Ht(e,t):!1}function Ht(e,t){let n=t>>>30&1,r=(t>>>22&1)==1,i=(t>>>23&1)==1,a=t>>>12&15,o=t>>>16&31,s=t>>>5&31,c=t&31,l=a===7?1:a===10?2:a===6?3:a===2?4:0;if(l===0)return!1;let u=n===1?16:8,d=Number(e.gprReadSp(s)),f=d;for(let t=0;t<l;t++){let n=(c+t)%32;if(r){let t=e.memRead(f,u),r=new Uint8Array(16);r.set(t.subarray(0,u)),e.vSetBytes(n,r)}else e.memWrite(f,e.vGetBytes(n).subarray(0,u));f+=u}if(i){let t=o===31?l*u:Number(e.gprRead(o));e.gprWrite(s,BigInt(d+t))}return!0}function R(e,t,n,r,i){if(t){let t=e.memRead(r,i),a=new Uint8Array(16);a.set(t.subarray(0,i)),e.vSetBytes(n,a)}else e.memWrite(r,e.vGetBytes(n).subarray(0,i))}function Ut(e,t){let n=t>>>30&3,r=t>>>22&3,i=n|r>>1<<2;if(i>4)return!1;let a=1<<i,o=(r&1)==1,s=t>>>5&31,c=t&31,l=Number(e.gprReadSp(s));if((t>>>24&3)==1)return R(e,o,c,l+(t>>>10&4095)*a,a),!0;if(!(t>>>24&3)){if((t>>>21&1)==1){let n=t>>>16&31,r=t>>>13&7,s=t>>>12&1,u=Kt(e.gprRead(n),r,s?i:0);return R(e,o,c,l+Number(u),a),!0}let n=qt(t>>>12&511),r=t>>>10&3,u=l;return(r===3||r===0)&&(u=l+n),R(e,o,c,u,a),(r===1||r===3)&&e.gprWrite(s,BigInt(l+n)),!0}return!1}function Wt(e,t){let n=t>>>30&3;if(n>2)return!1;let r=n===0?4:n===1?8:16,i=(t>>>22&1)==1,a=Jt(t>>>15&127)*r,o=t>>>10&31,s=t>>>5&31,c=t&31,l=t>>>23&3,u=Number(e.gprReadSp(s)),d=l===1?u:u+a;return R(e,i,c,d,r),R(e,i,o,d+r,r),(l===1||l===3)&&e.gprWrite(s,BigInt(u+a)),!0}function Gt(e,t){let n=t>>>30&3;if(n>2)return!1;let r=n===0?4:n===1?8:16,i=Yt(t>>>5&524287);return R(e,!0,t&31,e.getPc()+i*4,r),!0}function Kt(e,t,n){let r;switch(t){case 2:r=e&4294967295n;break;case 6:r=BigInt.asIntN(32,e&4294967295n);break;case 7:r=BigInt.asIntN(64,e);break;default:r=e;break}return r<<BigInt(n)}const qt=e=>e&256?e-512:e,Jt=e=>e&64?e-128:e,Yt=e=>e&262144?e-524288:e;function Xt(e,t){let n=Zt(t);return Qt(n)?$t(e,n):en(n)?tn(e,n):nn(n)?rn(e,n):an(n)?on(e,n):sn(n)?cn(e,n):mn(n)?hn(e,n):Cn(n)?wn(e,n):Tn(n)?Dn(e,n):gn(n)?_n(e,n):vn(n)?yn(e,n):bn(n)?Sn(e,n):On(n)?kn(e,n):An(n)?jn(e,n):Mn(n)?Nn(e,n):!1}function Zt(e){return{insn:e,high8:e>>>24&255,q:e>>>30&1,u:e>>>29&1,base28_24:e>>>24&31,size:e>>>22&3,bit21:e>>>21&1,field21_17:e>>>17&31,bit15:e>>>15&1,op16_12:e>>>12&31,op15_12:e>>>12&15,op14_12:e>>>12&7,low11_10:e>>>10&3,rm:e>>>16&31,rn:e>>>5&31,rd:e&31,ftype:e>>>22&3,fpOp1Src:e>>>15&63,fpOp2Src:e>>>12&15,fpCond:e>>>12&15,fpRmode:e>>>19&3,fpConvOp:e>>>16&7,sf:e>>>31&1,neonOpcode:e>>>11&31,base29_24:e>>>24&63,base28_19:e>>>19&1023,op29:e>>>29&1,neonOp16_12:e>>>12&31,neonOp14_12:e>>>12&7,imm5:e>>>16&31,imm4:e>>>11&15,cmode:e>>>12&15,immh:e>>>19&15,immb:e>>>16&7,len:e>>>13&3,tbx:e>>>12&1}}const Qt=e=>e.high8===78&&e.field21_17===20&&e.low11_10===2;function $t(e,t){let n=e.vGetBytes(t.rd),r=e.vGetBytes(t.rn);switch(t.op16_12){case 4:return e.vSetBytes(t.rd,se(n,r)),!0;case 5:return e.vSetBytes(t.rd,ce(n,r)),!0;case 6:return e.vSetBytes(t.rd,le(r)),!0;case 7:return e.vSetBytes(t.rd,ue(r)),!0;default:return!1}}const en=e=>e.high8===94&&e.size===0&&e.bit21===0&&e.bit15===0&&e.low11_10===0;function tn(e,t){switch(t.op14_12){case 0:case 1:case 2:{let n=t.op14_12===0?`choose`:t.op14_12===2?`majority`:`parity`,r=Number(e.vGetLane(t.rn,2,0)&4294967295n),i=Ee(e.vGetBytes(t.rd),r,e.vGetBytes(t.rm),n);return e.vSetBytes(t.rd,i.abcd),!0}case 3:return e.vSetBytes(t.rd,De(e.vGetBytes(t.rd),e.vGetBytes(t.rn),e.vGetBytes(t.rm))),!0;case 4:return e.vSetBytes(t.rd,ve(e.vGetBytes(t.rd),e.vGetBytes(t.rn),e.vGetBytes(t.rm))),!0;case 5:return e.vSetBytes(t.rd,ye(e.vGetBytes(t.rd),e.vGetBytes(t.rn),e.vGetBytes(t.rm))),!0;case 6:return e.vSetBytes(t.rd,xe(e.vGetBytes(t.rd),e.vGetBytes(t.rn),e.vGetBytes(t.rm))),!0;default:return!1}}const nn=e=>e.high8===94&&e.field21_17===20&&e.low11_10===2;function rn(e,t){switch(t.op16_12){case 0:{let n=Number(e.vGetLane(t.rn,2,0)&4294967295n),r=new Uint8Array(16);return new DataView(r.buffer).setUint32(0,Te(n)>>>0,!0),e.vSetBytes(t.rd,r),!0}case 1:return e.vSetBytes(t.rd,Oe(e.vGetBytes(t.rd),e.vGetBytes(t.rn))),!0;case 2:return e.vSetBytes(t.rd,be(e.vGetBytes(t.rd),e.vGetBytes(t.rn))),!0;default:return!1}}const an=e=>e.u===0&&e.base28_24===14&&e.size===3&&e.bit21===1&&e.op15_12===14&&e.low11_10===0;function on(e,t){let n=e.vGetBytes(t.rn),r=e.vGetBytes(t.rm);return e.vSetBytes(t.rd,t.q===1?Ne(n,r):Me(n,r)),!0}const sn=e=>(e.insn>>>31&1)==0&&(e.insn>>>30&1)==0&&e.u===0&&e.base28_24===30&&e.bit21===1&&(e.ftype===0||e.ftype===1);function cn(e,t){let n=t.ftype===1,r=t.insn>>>10&63,i=t.insn>>>10&31,a=t.insn>>>10&15,o=t.insn>>>10&3;return r===0?pn(e,t,n):a===8?dn(e,t,n):i===16?un(e,t,n):o===2?ln(e,t,n):o===3?fn(e,t,n):!1}function ln(e,t,n){let r=T(e.vGetBytes(t.rn),n),i=T(e.vGetBytes(t.rm),n),a;switch(t.fpOp2Src){case 0:a=Be(r,i,n);break;case 1:a=Ve(r,i,n);break;case 2:a=Re(r,i,n);break;case 3:a=ze(r,i,n);break;case 4:a=Ue(r,i,n);break;case 5:a=We(r,i,n);break;case 8:a=He(r,i,n);break;default:return!1}return e.vSetBytes(t.rd,E(a,n)),!0}function un(e,t,n){let r=T(e.vGetBytes(t.rn),n);switch(t.fpOp1Src){case 0:return e.vSetBytes(t.rd,E(r,n)),!0;case 1:return e.vSetBytes(t.rd,E(Ge(r,n),n)),!0;case 2:return e.vSetBytes(t.rd,E(Ke(r,n),n)),!0;case 3:return e.vSetBytes(t.rd,E(qe(r,n),n)),!0;case 4:{let n=Qe(r,!1);return e.vSetBytes(t.rd,E(n,!1)),!0}case 5:{let n=Qe(r,!0);return e.vSetBytes(t.rd,E(n,!0)),!0}default:return!1}}function dn(e,t,n){let r=t.insn&31,i=Je(T(e.vGetBytes(t.rn),n),r&8?0:T(e.vGetBytes(t.rm),n));return e.setNZCV(i.n,i.z,i.c,i.v),!0}function fn(e,t,n){let r=e.conditionHolds(t.fpCond)?t.rn:t.rm;return e.vSetBytes(t.rd,E(T(e.vGetBytes(r),n),n)),!0}function pn(e,t,n){let r=t.sf===1?64:32,i=t.fpRmode,a=t.fpConvOp,o=i===0?`nearest`:i===1?`plus`:i===2?`minus`:`zero`;switch(a){case 0:{let i=T(e.vGetBytes(t.rn),n);return e.gprWrite(t.rd,BigInt.asUintN(64,Xe(i,o,!0,r))),!0}case 1:{let i=T(e.vGetBytes(t.rn),n);return e.gprWrite(t.rd,BigInt.asUintN(64,Xe(i,o,!1,r))),!0}case 2:{let i=e.gprRead(t.rn);return e.vSetBytes(t.rd,E(Ze(i,!0,r,n),n)),!0}case 3:{let i=e.gprRead(t.rn);return e.vSetBytes(t.rd,E(Ze(i,!1,r,n),n)),!0}case 6:{let r=e.vGetBytes(t.rn),i=new DataView(r.buffer,r.byteOffset,16);return e.gprWrite(t.rd,n?i.getBigUint64(0,!0):BigInt(i.getUint32(0,!0))),!0}case 7:{let r=e.gprRead(t.rn),i=new Uint8Array(16),a=new DataView(i.buffer);return n?a.setBigUint64(0,BigInt.asUintN(64,r),!0):a.setUint32(0,Number(BigInt.asUintN(32,r)),!0),e.vSetBytes(t.rd,i),!0}default:return!1}}const mn=e=>(e.insn>>>31&1)==0&&e.base28_24===14&&e.bit21===1&&(e.insn>>>10&1)==1;function hn(e,t){let{rd:n,rn:r,rm:i,size:a,q:o,u:s}=t,c=e.vGetBytes(r),l=e.vGetBytes(i);switch(t.neonOpcode){case 3:if(s===0)switch(a){case 0:return e.vSetBytes(n,nt(c,l,o)),!0;case 1:return e.vSetBytes(n,at(c,l,o)),!0;case 2:return e.vSetBytes(n,rt(c,l,o)),!0;default:return e.vSetBytes(n,ot(c,l,o)),!0}return a===0?(e.vSetBytes(n,it(c,l,o)),!0):a===1?(e.vSetBytes(n,st(e.vGetBytes(n),c,l,o)),!0):!1;case 16:return e.vSetBytes(n,s===0?$e(c,l,a,o):et(c,l,a,o)),!0;case 19:return s===0?(e.vSetBytes(n,tt(c,l,a,o)),!0):!1;case 6:return e.vSetBytes(n,s===0?lt(c,l,a,o):dt(c,l,a,o)),!0;case 7:return e.vSetBytes(n,s===0?ut(c,l,a,o):ft(c,l,a,o)),!0;case 17:return e.vSetBytes(n,s===0?pt(c,l,a,o):ct(c,l,a,o)),!0;case 12:return e.vSetBytes(n,s===0?mt(c,l,a,o):gt(c,l,a,o)),!0;case 13:return e.vSetBytes(n,s===0?ht(c,l,a,o):_t(c,l,a,o)),!0;default:return!1}}const gn=e=>(e.insn>>>31&1)==0&&e.base28_24===14&&e.field21_17===16&&e.low11_10===2;function _n(e,t){let{rd:n,rn:r,size:i,q:a,u:o}=t,s=e.vGetBytes(r);switch(t.neonOp16_12){case 0:return e.vSetBytes(n,wt(s,8,a)),!0;case 1:return e.vSetBytes(n,wt(s,2,a)),!0;case 2:return e.vSetBytes(n,wt(s,4,a)),!0;case 4:return e.vSetBytes(n,St(s,i,a)),!0;case 5:return e.vSetBytes(n,o===0?xt(s,a):bt(s,a)),!0;case 11:return e.vSetBytes(n,o===0?yt(s,i,a):vt(s,i,a)),!0;case 9:return o===0?(e.vSetBytes(n,Ct(s,i,a)),!0):!1;default:return!1}}const vn=e=>(e.insn>>>31&1)==0&&e.base28_24===14&&e.field21_17===24&&e.low11_10===2;function yn(e,t){let{rd:n,rn:r,size:i,q:a,u:o}=t,s=e.vGetBytes(r);switch(t.neonOp16_12){case 27:return e.vSetBytes(n,At(s,i,a)),!0;case 10:return e.vSetBytes(n,o===0?jt(s,i,a):Nt(s,i,a)),!0;case 26:return e.vSetBytes(n,o===0?Mt(s,i,a):Pt(s,i,a)),!0;default:return!1}}const bn=e=>(e.insn>>>31&1)==0&&(e.insn>>>21&255)==112&&(e.insn>>>10&1)==1;function xn(e){return(e&1)==1?{size:0,index:e>>1}:(e&3)==2?{size:1,index:e>>2}:(e&7)==4?{size:2,index:e>>3}:(e&15)==8?{size:3,index:e>>4}:null}function Sn(e,t){let n=xn(t.imm5);if(!n)return!1;let{size:r,index:i}=n;return t.op29===0&&t.imm4===0?(e.vSetBytes(t.rd,Tt(e.vGetBytes(t.rn),r,i,t.q)),!0):t.op29===0&&t.imm4===1?(e.vSetBytes(t.rd,Et(e.gprRead(t.rn),r,t.q)),!0):!1}const Cn=e=>(e.insn>>>31&1)==0&&e.base28_19===480&&(e.insn>>>10&1)==1;function wn(e,t){let n=t.insn>>>16&7,r=t.insn>>>5&31,i=n<<5|r,a=t.cmode,o=t.op29;if(a===15&&o===0)return!1;let s=Bt(o,a,i),c=e=>Array.from({length:t.q===1?2:1},()=>e),l=a&1;if(o===0&&l===0)return e.vSetBytes(t.rd,k(c(s),3)),!0;if(o===1&&l===0)return e.vSetBytes(t.rd,k(c(~s&18446744073709551615n),3)),!0;let u=e.vGetBytes(t.rd),d=new DataView(u.buffer,u.byteOffset,16),f=new Uint8Array(16),p=new DataView(f.buffer),m=e=>o===0?e|s:e&~s&18446744073709551615n;return p.setBigUint64(0,m(d.getBigUint64(0,!0)),!0),t.q===1&&p.setBigUint64(8,m(d.getBigUint64(8,!0)),!0),e.vSetBytes(t.rd,f),!0}const Tn=e=>(e.insn>>>31&1)==0&&(e.insn>>>23&63)==30&&e.immh!==0&&(e.insn>>>10&1)==1;function En(e){return e&8?3:e&4?2:e&2?1:0}function Dn(e,t){let n=En(t.immh),r=8<<n,i=t.immh<<3|t.immb,a=e.vGetBytes(t.rn);switch(t.insn>>>11&31){case 10:{let o=i-r;return e.vSetBytes(t.rd,Dt(a,n,o,t.q)),!0}case 0:{let o=2*r-i;return e.vSetBytes(t.rd,t.u===0?kt(a,n,o,t.q):Ot(a,n,o,t.q)),!0}default:return!1}}const On=e=>(e.insn>>>31&1)==0&&e.base29_24===46&&(e.insn>>>22&3)==0&&e.bit21===0&&(e.insn>>>15&1)==0&&(e.insn>>>10&1)==0;function kn(e,t){return e.vSetBytes(t.rd,Rt(e.vGetBytes(t.rn),e.vGetBytes(t.rm),t.imm4,t.q)),!0}const An=e=>(e.insn>>>31&1)==0&&e.base29_24===14&&e.bit21===0&&(e.insn>>>15&1)==0&&e.low11_10===2;function jn(e,t){let{rd:n,rn:r,rm:i,size:a,q:o}=t,s=e.vGetBytes(r),c=e.vGetBytes(i);switch(t.neonOp14_12){case 1:return e.vSetBytes(n,It(s,c,a,o,0)),!0;case 5:return e.vSetBytes(n,It(s,c,a,o,1)),!0;case 2:return e.vSetBytes(n,Lt(s,c,a,o,0)),!0;case 6:return e.vSetBytes(n,Lt(s,c,a,o,1)),!0;case 3:return e.vSetBytes(n,Ft(s,c,a,o,0)),!0;case 7:return e.vSetBytes(n,Ft(s,c,a,o,1)),!0;default:return!1}}const Mn=e=>(e.insn>>>31&1)==0&&e.base29_24===14&&(e.insn>>>21&7)==0&&(e.insn>>>15&1)==0&&e.low11_10===0;function Nn(e,t){let n=t.len+1,r=new Uint8Array(n*16);for(let i=0;i<n;i++){let n=(t.rn+i)%32;r.set(e.vGetBytes(n).subarray(0,16),i*16)}return e.vSetBytes(t.rd,zt(r,e.vGetBytes(t.rm),t.q,e.vGetBytes(t.rd),t.tbx===1)),!0}var Pn=class extends Error{constructor(e){super(e),this.name=`NullIndirectCallError`}};const z=(1n<<64n)-1n,B=(1n<<32n)-1n,Fn=1e6,In=1879048192;var Ln=class{gpr=Array.from({length:31},()=>0n);sp=0n;pc=0;regions=[];symbols=new Map;branched=!1;flagN=!1;flagZ=!1;flagC=!1;flagV=!1;hostFns=new Map;syscalls=new Map;stackTop=0;tlsBase=0;importStubBump=1744830464;instructionHooks=[];constructorFaults=[];stopRequested=!1;vreg=Array.from({length:32},()=>new Uint8Array(16));vview=this.vreg.map(e=>new DataView(e.buffer));isAvailable(){return!0}requestStop(){this.stopRequested=!0}mapMemory(e,t){this.regions.push({base:e,size:t,data:new Uint8Array(t)})}writeCode(e,t){let n=this.findRegion(e,t.length);n.data.set(t,e-n.base)}loadElf(e,t){let n=new g(e);if(n.machine!==183)throw Error(`Unsupported ELF machine 0x${n.machine.toString(16)} (expected AArch64)`);for(let e of n.loadableSegments())this.regions.push({base:e.vaddr,size:e.data.length,data:e.data});return this.symbols=n.exportedSymbols(),this.applyRelocations(n,t),this.runInitializers(n),{entry:n.entry}}runInitializers(e){let{init:t,arraySlots:n}=e.initializers(),r=[];t!==0&&r.push(t);for(let e of n){let t=Number(this.loadValue(e,8));t!==0&&r.push(t)}for(let e of r)this.runConstructor(e)}runConstructor(e){this.gpr[0]=0n,this.gpr[1]=0n,this.gpr[2]=0n,this.gpr[30]=BigInt(0),this.sp=BigInt(this.ensureStack());try{this.run(e,0)}catch(t){if(t instanceof Pn){this.constructorFaults.push(`ctor@0x${e.toString(16)}: ${t.message}`);return}throw t}}applyRelocations(e,t){for(let n of e.relocations())switch(n.type){case 1027:this.storeValue(n.offset,8,BigInt(n.addend));break;case 257:case 1025:case 1026:{let e=this.resolveRelocSymbol(n.symbolName,n.symbolValue,t);this.storeValue(n.offset,8,BigInt(e+n.addend));break}default:break}}resolveRelocSymbol(e,t,n){if(e&&this.symbols.has(e))return this.symbols.get(e);if(e&&n?.has(e)){let t=n.get(e),r=this.importStubBump;return this.importStubBump+=8,this.registerHostFunction(r,t),r}return t}callSymbol(e,t){let n=this.symbols.get(e);if(n===void 0)throw Error(`Unknown symbol: "${e}" is not an exported function`);if(t.length>8)throw Error(`callSymbol supports up to 8 register arguments, got ${t.length}`);for(let e=0;e<t.length;e++)this.gpr[e]=BigInt.asUintN(64,BigInt(t[e]));return this.gpr[30]=BigInt(0),this.sp=BigInt(this.ensureStack()),this.run(n,0),Number(this.gpr[0])}exportedSymbolNames(){return[...this.symbols.keys()]}constructorFaultLog(){return this.constructorFaults}writeRegister(e,t){this.writeNamed(e,BigInt(t)&z)}readRegister(e){return Number(this.readNamed(e))}registerHostFunction(e,t){this.hostFns.set(e,t)}registerSyscall(e,t){this.syscalls.set(e,t)}addInstructionHook(e){return this.instructionHooks.push(e),()=>{let t=this.instructionHooks.indexOf(e);t>=0&&this.instructionHooks.splice(t,1)}}readMemory(e,t){let n=this.findRegion(e,t),r=e-n.base;return n.data.slice(r,r+t)}ensureStack(){return this.stackTop===0&&(this.mapMemory(2147418112,65536),this.stackTop=2147483648),this.stackTop}ensureTls(){if(this.tlsBase===0){this.mapMemory(In,4096),this.tlsBase=In;let e=new Uint8Array([0,17,34,51,68,85,102,119]);this.writeCode(1879048232,e)}return this.tlsBase}callHost(e){let t=this.hostFns.get(e);if(!t)throw Error(`No host function registered at 0x${e.toString(16)}`);this.invokeHost(t)}hostContext(){return{x:e=>this.readGpr(e),setX:(e,t)=>this.writeGpr(e,BigInt.asUintN(64,t)),read:(e,t)=>this.readMemory(e,t),write:(e,t)=>this.writeCode(e,t)}}readVReg(e){return Uint8Array.from(this.vreg[e]??new Uint8Array(16))}writeVReg(e,t){let n=this.vreg[e];n&&(n.fill(0),n.set(t.subarray(0,16)))}readGprValue(e){return this.readGpr(e)}writeGprValue(e,t){this.writeGpr(e,t)}vGet128(e){let t=this.vview[e];if(!t)return 0n;let n=t.getBigUint64(0,!0);return t.getBigUint64(8,!0)<<64n|n}vSet128(e,t){let n=this.vview[e];if(!n)return;let r=BigInt.asUintN(128,t);n.setBigUint64(0,r&z,!0),n.setBigUint64(8,r>>64n&z,!0)}vGetLane(e,t,n){let r=this.vview[e];if(!r)return 0n;let i=n<<t;if(i<0||i+(1<<t)>16)return 0n;switch(t){case 0:return BigInt(r.getUint8(i));case 1:return BigInt(r.getUint16(i,!0));case 2:return BigInt(r.getUint32(i,!0));default:return r.getBigUint64(i,!0)}}vSetLane(e,t,n,r){let i=this.vview[e];if(!i)return;let a=n<<t;if(!(a<0||a+(1<<t)>16))switch(t){case 0:i.setUint8(a,Number(r&255n));break;case 1:i.setUint16(a,Number(r&65535n),!0);break;case 2:i.setUint32(a,Number(r&4294967295n),!0);break;default:i.setBigUint64(a,r&z,!0);break}}simdContext(){return{vGetBytes:e=>this.readVReg(e),vSetBytes:(e,t)=>this.writeVReg(e,t),vGet128:e=>this.vGet128(e),vSet128:(e,t)=>this.vSet128(e,t),vGetLane:(e,t,n)=>this.vGetLane(e,t,n),vSetLane:(e,t,n,r)=>this.vSetLane(e,t,n,r),memRead:(e,t)=>this.readMemory(e,t),memWrite:(e,t)=>this.writeCode(e,t),gprRead:e=>this.readGpr(e),gprWrite:(e,t)=>this.writeGpr(e,BigInt.asUintN(64,t)),gprReadSp:e=>this.readGprSp(e),setNZCV:(e,t,n,r)=>{this.flagN=e,this.flagZ=t,this.flagC=n,this.flagV=r},conditionHolds:e=>this.conditionHolds(e),getPc:()=>this.pc}}invokeHost(e){let t=e(this.hostContext());t!==void 0&&(this.gpr[0]=BigInt.asUintN(64,BigInt(t)))}start(e,t){this.run(e,t)}run(e,t){this.pc=e,this.stopRequested=!1;let n=0;for(;this.pc!==t;){if(this.stopRequested)return;if(++n>Fn)throw Error(`Execution exceeded ${Fn} steps (no halt before ${t})`);if(this.hostFns.size>0){let e=this.hostFns.get(this.pc);if(e){this.invokeHost(e),this.pc=Number(this.readGpr(30));continue}}let e=this.findRegion(this.pc,4),r=this.pc-e.base,i=e.data,a=(i[r]|i[r+1]<<8|i[r+2]<<16|i[r+3]<<24)>>>0;this.instructionHooks.length>0&&this.fireInstructionHooks(this.pc,a,n),this.branched=!1,this.execute(a),this.branched||(this.pc+=4)}}fireInstructionHooks(e,t,n){let r={pc:e,insn:t,step:n,x:e=>this.readGpr(e),reg:e=>this.readRegister(e)};for(let e of this.instructionHooks)e(r)}execute(e){let t=e>>>25&15;if(t===8||t===9){if(this.execDataProcessingImmediate(e))return}else if(t===10||t===11){if(this.execBranchSystem(e))return}else if((t&7)==5){if(this.execDataProcessingRegister(e))return}else if((t&5)==4){if(this.execLoadStore(e))return}else if((t&7)==7&&Xt(this.simdContext(),e))return;throw Error(`Unsupported ARM64 opcode 0x${(e>>>0).toString(16).padStart(8,`0`)} at pc=0x${this.pc.toString(16)}`)}execDataProcessingImmediate(e){let t=e>>>29&3;if((e>>>24&31)==16){let t=e>>>31,n=e>>>29&3,r=e>>>5&524287,i=e&31,a=this.signExtend(BigInt(r<<2|n),21),o=t===1?BigInt(this.pc&-4096)+(a<<12n):BigInt(this.pc)+a;return this.writeGpr(i,BigInt.asUintN(64,o)),!0}if(t===0&&(e>>>23&63)==34){let t=e>>>31,n=e>>>22&1,r=e>>>10&4095;n===1&&(r<<=12);let i=e>>>5&31,a=e&31,o=this.readGprSp(i)+BigInt(r);return this.writeGprSp(a,t===1?BigInt.asUintN(64,o):BigInt.asUintN(32,o)),!0}if(t===1&&(e>>>23&63)==34){let t=e>>>31,n=e>>>22&1,r=e>>>10&4095;n===1&&(r<<=12);let i=e>>>5&31,a=e&31,o=this.addWithFlags(this.readGprSp(i),BigInt(r),t);return this.writeGpr(a,o),!0}if(t===2&&(e>>>23&63)==34){let t=e>>>31,n=e>>>22&1,r=e>>>10&4095;n===1&&(r<<=12);let i=e>>>5&31,a=e&31,o=this.readGprSp(i)-BigInt(r);return this.writeGprSp(a,t===1?BigInt.asUintN(64,o):BigInt.asUintN(32,o)),!0}if(t===0&&(e>>>23&63)==37){let t=e>>>31,n=e>>>21&3,r=e>>>5&65535,i=e&31,a=~(BigInt(r)<<BigInt(n*16));return this.writeGpr(i,t===1?BigInt.asUintN(64,a):BigInt.asUintN(32,a)),!0}if(t===2&&(e>>>23&63)==37){let t=e>>>31,n=e>>>21&3,r=e>>>5&65535,i=e&31,a=BigInt(r)<<BigInt(n*16);return this.writeGpr(i,t===1?BigInt.asUintN(64,a):BigInt.asUintN(32,a)),!0}if(t===3&&(e>>>23&63)==37){let t=e>>>31,n=e>>>21&3,r=e>>>5&65535,i=e&31,a=BigInt(n*16),o=this.readGpr(i)&~(65535n<<a)|BigInt(r)<<a;return this.writeGpr(i,t===1?BigInt.asUintN(64,o):BigInt.asUintN(32,o)),!0}if(t===3&&(e>>>23&63)==34){let t=e>>>31,n=e>>>22&1,r=e>>>10&4095;n===1&&(r<<=12);let i=e>>>5&31,a=e&31,o=this.subWithFlags(this.readGprSp(i),BigInt(r),t);return this.writeGpr(a,o),!0}if((e>>>23&63)==36){let t=e>>>31,n=e>>>29&3,r=e>>>22&1,i=e>>>16&63,a=e>>>10&63,o=e>>>5&31,s=e&31;if(t===0&&r===1)return!1;let c=this.decodeBitMask(r,i,a,t),l=this.readGpr(o),u;switch(n){case 0:case 3:u=l&c;break;case 1:u=l|c;break;default:u=l^c;break}if(u=t===1?BigInt.asUintN(64,u):BigInt.asUintN(32,u),n===3){let e=t===1?64n:32n;this.flagN=u>>e-1n==1n,this.flagZ=u===0n,this.flagC=!1,this.flagV=!1,this.writeGpr(s,u)}else this.writeGprSp(s,u);return!0}if((e>>>23&63)==38){let t=e>>>31,n=e>>>29&3;if(n===3)return!1;let r=e>>>16&63,i=e>>>10&63,a=e>>>5&31,o=e&31,s=t===1?64:32,c=this.readGpr(a)&(t===1?z:B),l=r%s,u=i,d=BigInt(s),f=(c>>BigInt(l)|c<<d-BigInt(l))&(t===1?z:B),p=u+1,m=p>=s?t===1?z:B:(1n<<BigInt(p))-1n,h=f&m,g;return n===1?g=this.readGpr(o)&(t===1?z:B)&~m|h:n===2?g=h:(g=this.signExtend(h,p),g=BigInt.asUintN(64,g)),this.writeGpr(o,t===1?BigInt.asUintN(64,g):BigInt.asUintN(32,g)),!0}if((e>>>23&63)==39){let t=e>>>31,n=e>>>16&31,r=e>>>10&63,i=e>>>5&31,a=e&31,o=t===1?64:32,s=this.readGpr(i)&(t===1?z:B),c=this.readGpr(n)&(t===1?z:B),l=(s<<BigInt(o)|c)>>BigInt(r)&(t===1?z:B);return this.writeGpr(a,t===1?BigInt.asUintN(64,l):BigInt.asUintN(32,l)),!0}return!1}assertIndirectTarget(e,t){if(e===0)throw new Pn(`NULL indirect call: ${t} to address 0 at pc=0x${this.pc.toString(16)} (likely an uninitialised function pointer)`)}execBranchSystem(e){if(e>>>26==5)return this.pc+=this.branchOffset(e),this.branched=!0,!0;if(e>>>26==37)return this.gpr[30]=BigInt(this.pc+4),this.pc+=this.branchOffset(e),this.branched=!0,!0;if((e&4294966303)>>>0==3596550144){let t=e>>>5&31;return this.pc=Number(this.readGpr(t)),this.branched=!0,!0}if((e&4294966303)>>>0==3592355840){let t=e>>>5&31,n=Number(this.readGpr(t));return this.assertIndirectTarget(n,`BR`),this.pc=n,this.branched=!0,!0}if((e&4294966303)>>>0==3594452992){let t=e>>>5&31,n=Number(this.readGpr(t));return this.assertIndirectTarget(n,`BLR`),this.gpr[30]=BigInt(this.pc+4),this.pc=n,this.branched=!0,!0}if((e>>>25&63)==26){let t=e>>>31,n=e>>>24&1,r=e&31,i=(t===1?this.readGpr(r):BigInt.asUintN(32,this.readGpr(r)))===0n;return(n===0?i:!i)&&(this.pc+=this.imm19Offset(e),this.branched=!0),!0}if(e>>>24==84&&!(e>>>4&1)){let t=e&15;return this.conditionHolds(t)&&(this.pc+=this.imm19Offset(e),this.branched=!0),!0}if((e>>>25&63)==27){let t=e>>>24&1,n=e>>>31,r=e>>>19&31,i=n<<5|r,a=e&31,o=e>>>5&16383,s=Number(this.signExtend(BigInt(o),14))*4,c=(this.readGpr(a)>>BigInt(i)&1n)==1n;return(t===0?!c:c)&&(this.pc+=s,this.branched=!0),!0}if((e&4294963231)>>>0==3573751839||(e&4294963231)>>>0==3573755935)return!0;if(e>>>20==3411){let t=e&31,n=e>>>16&7,r=e>>>12&15,i=e>>>8&15,a=e>>>5&7,o=n===3&&r===13&&i===0&&a===2;return this.gpr[t]=o?BigInt(this.ensureTls()):0n,!0}if((e&4292870175)>>>0==3556769793){let e=Number(this.readGpr(8)),t=this.syscalls.get(e);if(!t)throw Error(`Unimplemented syscall ${e} (x8) at pc=0x${this.pc.toString(16)}`);let n=t(this.hostContext());return n!==void 0&&(this.gpr[0]=BigInt.asUintN(64,BigInt(n))),!0}return!1}execDataProcessingRegister(e){let t=e>>>29&3;if(t===0&&(e>>>24&31)==11&&!(e>>>21&1)){let t=e>>>31,n=e>>>22&3,r=e>>>16&31,i=e>>>10&63,a=e>>>5&31,o=e&31,s=i===0?this.readGpr(a)+this.readGpr(r):this.readGpr(a)+this.applyShift(this.readGpr(r),n,i,t);return this.writeGpr(o,t===1?BigInt.asUintN(64,s):BigInt.asUintN(32,s)),!0}if(t===2&&(e>>>24&31)==11&&!(e>>>21&1)){let t=e>>>31,n=e>>>22&3,r=e>>>16&31,i=e>>>10&63,a=e>>>5&31,o=e&31,s=this.applyShift(this.readGpr(r),n,i,t),c=this.readGpr(a)-s;return this.writeGpr(o,t===1?BigInt.asUintN(64,c):BigInt.asUintN(32,c)),!0}if(t===1&&(e>>>24&31)==10&&!(e>>>21&1)){let t=e>>>31,n=e>>>22&3,r=e>>>16&31,i=e>>>10&63,a=e>>>5&31,o=e&31,s=this.applyShift(this.readGpr(r),n,i,t),c=this.readGpr(a)|s;return this.writeGpr(o,t===1?BigInt.asUintN(64,c):BigInt.asUintN(32,c)),!0}if(t===2&&(e>>>24&31)==10&&!(e>>>21&1)){let t=e>>>31,n=e>>>22&3,r=e>>>16&31,i=e>>>10&63,a=e>>>5&31,o=e&31,s=this.applyShift(this.readGpr(r),n,i,t),c=this.readGpr(a)^s;return this.writeGpr(o,t===1?BigInt.asUintN(64,c):BigInt.asUintN(32,c)),!0}if(t===3&&(e>>>24&31)==11&&!(e>>>21&1)){let t=e>>>31,n=e>>>22&3,r=e>>>16&31,i=e>>>10&63,a=e>>>5&31,o=e&31,s=this.applyShift(this.readGpr(r),n,i,t),c=this.subWithFlags(this.readGpr(a),s,t);return this.writeGpr(o,c),!0}if(t===1&&(e>>>24&31)==11&&!(e>>>21&1)){let t=e>>>31,n=e>>>22&3,r=e>>>16&31,i=e>>>10&63,a=e>>>5&31,o=e&31,s=this.applyShift(this.readGpr(r),n,i,t),c=this.addWithFlags(this.readGpr(a),s,t);return this.writeGpr(o,c),!0}if((e>>>24&31)==10){let t=e>>>31,n=e>>>29&3,r=e>>>21&1;if(!(r===0&&(n===1||n===2))){let i=e>>>22&3,a=e>>>16&31,o=e>>>10&63,s=e>>>5&31,c=e&31,l=this.applyShift(this.readGpr(a),i,o,t);r===1&&(l=~l);let u=this.readGpr(s),d;if(d=n===0||n===3?u&l:n===1?u|l:u^l,d=t===1?BigInt.asUintN(64,d):BigInt.asUintN(32,d),n===3){let e=t===1?64n:32n;this.flagN=d>>e-1n==1n,this.flagZ=d===0n,this.flagC=!1,this.flagV=!1}return this.writeGpr(c,d),!0}}if((e>>>24&31)==11&&(e>>>21&7)==1){let t=e>>>31,n=e>>>30&1,r=e>>>29&1,i=e>>>16&31,a=e>>>13&7,o=e>>>10&7,s=e>>>5&31,c=e&31,l=this.extendReg(this.readGpr(i),a,o,t);if(r===1){let e=n===0?this.addWithFlags(this.readGprSp(s),l,t):this.subWithFlags(this.readGprSp(s),l,t);this.writeGpr(c,e)}else{let e=this.readGprSp(s),r=n===0?e+l:e-l;this.writeGprSp(c,t===1?BigInt.asUintN(64,r):BigInt.asUintN(32,r))}return!0}if((e>>>21&255)==208){let t=e>>>31,n=e>>>30&1,r=e>>>29&1,i=e>>>16&31,a=e>>>5&31,o=e&31,s=this.flagC?1n:0n;if(n===0){let e=r===1?this.addWithFlags(this.readGpr(a),this.readGpr(i),t,s):this.readGpr(a)+this.readGpr(i)+s;this.writeGpr(o,t===1?BigInt.asUintN(64,e):BigInt.asUintN(32,e))}else{let e=~this.readGpr(i),n=r===1?this.addWithFlags(this.readGpr(a),e,t,s):this.readGpr(a)+e+s;this.writeGpr(o,t===1?BigInt.asUintN(64,n):BigInt.asUintN(32,n))}return!0}if((e>>>24&31)==27){let t=e>>>31,n=e>>>21&7,r=e>>>15&1,i=e>>>16&31,a=e>>>10&31,o=e>>>5&31,s=e&31;if(n===0){let e=this.readGpr(o)*this.readGpr(i),n=this.readGpr(a),c=r===0?n+e:n-e;return this.writeGpr(s,t===1?BigInt.asUintN(64,c):BigInt.asUintN(32,c)),!0}if(n===2&&r===0){let e=BigInt.asIntN(64,this.readGpr(o)),t=BigInt.asIntN(64,this.readGpr(i));return this.writeGpr(s,BigInt.asUintN(64,e*t>>64n)),!0}if(n===6&&r===0){let e=this.readGpr(o)&z,t=this.readGpr(i)&z;return this.writeGpr(s,e*t>>64n&z),!0}if(n===1){let e=BigInt.asIntN(32,this.readGpr(o)&B),t=BigInt.asIntN(32,this.readGpr(i)&B),n=BigInt.asIntN(64,this.readGpr(a)),c=r===0?n+e*t:n-e*t;return this.writeGpr(s,BigInt.asUintN(64,c)),!0}if(n===5){let e=this.readGpr(o)&B,t=this.readGpr(i)&B,n=this.readGpr(a)&z,c=r===0?n+e*t:n-e*t;return this.writeGpr(s,BigInt.asUintN(64,c)),!0}}if((e>>>21&255)==214&&!(e>>>30&1)){let t=e>>>31,n=e>>>10&63,r=e>>>16&31,i=e>>>5&31,a=e&31,o=t===1?64:32,s=t===1?z:B,c=this.readGpr(i)&s,l=this.readGpr(r)&s;switch(n){case 2:{let e=l===0n?0n:c/l;return this.writeGpr(a,e&s),!0}case 3:{let e=BigInt.asIntN(o,c),t=BigInt.asIntN(o,l),n=t===0n?0n:e/t;return this.writeGpr(a,BigInt.asUintN(o,n)),!0}case 8:return this.writeGpr(a,this.applyShift(c,0,Number(l%BigInt(o)),t)),!0;case 9:return this.writeGpr(a,this.applyShift(c,1,Number(l%BigInt(o)),t)),!0;case 10:return this.writeGpr(a,this.applyShift(c,2,Number(l%BigInt(o)),t)),!0;case 11:return this.writeGpr(a,this.applyShift(c,3,Number(l%BigInt(o)),t)),!0;default:break}}if((e>>>21&255)==212){let t=e>>>31,n=e>>>30&1,r=e>>>16&31,i=e>>>12&15,a=e>>>10&3,o=e>>>5&31,s=e&31,c=t===1?z:B,l;if(this.conditionHolds(i))l=this.readGpr(o)&c;else{let e=this.readGpr(r)&c;n===0&&a===1?e=e+1n&c:n===1&&a===0?e=~e&c:n===1&&a===1&&(e=~e+1n&c),l=e}return this.writeGpr(s,l),!0}if((e>>>21&255)==210&&!(e>>>11&1)&&!(e>>>4&1)){let t=e>>>31,n=e>>>30&1,r=e>>>16&31,i=e>>>12&15,a=e>>>5&31,o=e&15;return this.conditionHolds(i)?n===1?this.subWithFlags(this.readGpr(a),this.readGpr(r),t):this.addWithFlags(this.readGpr(a),this.readGpr(r),t):(this.flagN=(o>>3&1)==1,this.flagZ=(o>>2&1)==1,this.flagC=(o>>1&1)==1,this.flagV=(o&1)==1),!0}if((e>>>21&255)==210&&(e>>>11&1)==1&&!(e>>>4&1)){let t=e>>>31,n=e>>>30&1,r=BigInt(e>>>16&31),i=e>>>12&15,a=e>>>5&31,o=e&15;return this.conditionHolds(i)?n===1?this.subWithFlags(this.readGpr(a),r,t):this.addWithFlags(this.readGpr(a),r,t):(this.flagN=(o>>3&1)==1,this.flagZ=(o>>2&1)==1,this.flagC=(o>>1&1)==1,this.flagV=(o&1)==1),!0}if((e>>>21&255)==214&&(e>>>30&1)==1){let t=e>>>31,n=e>>>10&63,r=e>>>5&31,i=e&31,a=t===1?64:32,o=this.readGpr(r)&(t===1?z:B);switch(n){case 0:return this.writeGpr(i,this.reverseBits(o,a)),!0;case 1:return this.writeGpr(i,this.reverseBytes(o,a,2)),!0;case 2:return this.writeGpr(i,this.reverseBytes(o,a,t===1?4:a/8)),!0;case 3:return this.writeGpr(i,this.reverseBytes(o,a,a/8)),!0;case 4:return this.writeGpr(i,BigInt(this.countLeadingZeros(o,a))),!0;default:break}}return!1}execLoadStore(e){if((e>>>26&1)==1)return Vt(this.simdContext(),e);if((e>>>24&63)==8){let t=1<<(e>>>30),n=(e>>>22&1)==1,r=e>>>16&31,i=e>>>5&31,a=e&31,o=Number(this.readGprSp(i));return n?this.writeGpr(a,this.loadValue(o,t)):(this.storeValue(o,t,this.readGpr(a)),this.writeGpr(r,0n)),!0}if((e>>>27&7)==7&&!(e>>>26&1)){let t=e>>>30,n=e>>>22&3,r=e>>>24&3,i=e>>>5&31,a=e&31,o=1<<t,s=n!==0,c=n===2||n===3,l=n===3?32:64,u=e=>{let t=this.loadValue(e,o),n=c?BigInt.asUintN(l,this.signExtend(t,o*8)):t;this.writeGpr(a,n)};if(r===1){let t=e>>>10&4095,n=Number(this.readGprSp(i))+t*o;return s?u(n):this.storeValue(n,o,this.readGpr(a)),!0}if(r===0&&(e>>>21&1)==1&&(e>>>10&3)==2){let n=e>>>16&31,r=e>>>13&7,c=(e>>>12&1)==1?t:0,l=this.extendReg(this.readGpr(n),r,c,1),d=Number(this.readGprSp(i))+Number(l);return s?u(d):this.storeValue(d,o,this.readGpr(a)),!0}if(r===0){let t=e>>>12&511,n=t&256?t-512:t,r=e>>>10&3,c=Number(this.readGprSp(i)),l=r===1?c:c+n;return s?u(l):this.storeValue(l,o,this.readGpr(a)),(r===3||r===1)&&this.writeGprSp(i,BigInt.asUintN(64,BigInt(c+n))),!0}}if((e>>>24&63)==24&&!(e>>>26&1)){let t=e>>>30==1?8:4,n=e&31,r=this.pc+this.imm19Offset(e);return this.writeGpr(n,this.loadValue(r,t)),!0}if((e>>>25&31)==20){let t=e>>>30==2?8:4,n=e>>>23&3,r=(e>>>22&1)==1,i=e>>>15&127,a=(i&64?i-128:i)*t,o=e>>>10&31,s=e>>>5&31,c=e&31,l=Number(this.readGprSp(s)),u=n===1?l:l+a;return r?(this.writeGpr(c,this.loadValue(u,t)),this.writeGpr(o,this.loadValue(u+t,t))):(this.storeValue(u,t,this.readGpr(c)),this.storeValue(u+t,t,this.readGpr(o))),n!==2&&this.writeGprSp(s,BigInt.asUintN(64,BigInt(l+a))),!0}return!1}branchOffset(e){let t=e&67108863;return(t&33554432?t-67108864:t)*4}imm19Offset(e){let t=e>>>5&524287;return(t&262144?t-524288:t)*4}subWithFlags(e,t,n){let r=n===1?64n:32n,i=(1n<<r)-1n,a=e&i,o=t&i,s=a-o&i;this.flagN=s>>r-1n==1n,this.flagZ=s===0n,this.flagC=a>=o;let c=a>>r-1n&1n,l=o>>r-1n&1n,u=s>>r-1n&1n;return this.flagV=c!==l&&c!==u,s}conditionHolds(e){let t=this.flagN,n=this.flagZ,r=this.flagC,i=this.flagV;switch(e>>1){case 0:return e&1?!n:n;case 1:return e&1?!r:r;case 2:return e&1?!t:t;case 3:return e&1?!i:i;case 4:return e&1?!(r&&!n):r&&!n;case 5:return e&1?t!==i:t===i;case 6:return e&1?!(!n&&t===i):!n&&t===i;default:return!0}}applyShift(e,t,n,r){if(n===0)return e;let i=r===1?z:B,a=r===1?64n:32n,o=BigInt(n);switch(t){case 0:return e<<o&i;case 1:return(e&i)>>o;case 2:{let t=1n<<a-1n;return(e&i&t?(e&i)-(1n<<a):e&i)>>o&i}case 3:{let t=e&i,n=o%a;return(t>>n|t<<a-n)&i}default:throw Error(`Unsupported shift type ${t}`)}}addWithFlags(e,t,n,r=0n){let i=n===1?64n:32n,a=(1n<<i)-1n,o=e&a,s=t&a,c=o+s+r,l=c&a;this.flagN=l>>i-1n==1n,this.flagZ=l===0n,this.flagC=c>a;let u=o>>i-1n&1n,d=s>>i-1n&1n,f=l>>i-1n&1n;return this.flagV=u===d&&u!==f,l}decodeBitMask(e,t,n,r){let i=e<<6|~n&63,a=-1;for(let e=6;e>=0;e--)if(i>>e&1){a=e;break}if(a<1)throw Error(`Reserved logical-immediate encoding (N=${e}, imms=0x${n.toString(16)})`);let o=1<<a,s=o-1,c=n&s,l=t&s;if(c===s)throw Error(`Reserved logical-immediate encoding (imms all-ones)`);let u=BigInt(o),d=(1n<<BigInt(c+1))-1n,f=BigInt(l),p=(d>>f|d<<u-f)&(1n<<u)-1n,m=r===1?64:32,h=0n;for(let e=0;e<m;e+=o)h|=p<<BigInt(e);return h&(r===1?z:B)}signExtend(e,t){let n=BigInt(t),r=1n<<n-1n,i=e&(1n<<n)-1n;return i&r?i-(1n<<n):i}extendReg(e,t,n,r){let i=r===1?z:B,a;switch(t){case 0:a=e&255n;break;case 1:a=e&65535n;break;case 2:a=e&4294967295n;break;case 3:a=e&z;break;case 4:a=BigInt.asUintN(64,this.signExtend(e,8));break;case 5:a=BigInt.asUintN(64,this.signExtend(e,16));break;case 6:a=BigInt.asUintN(64,this.signExtend(e,32));break;default:a=e&z;break}return a<<BigInt(n)&i}reverseBits(e,t){let n=0n,r=e;for(let e=0;e<t;e++)n=n<<1n|r&1n,r>>=1n;return n}countLeadingZeros(e,t){for(let n=t-1;n>=0;n--)if(e>>BigInt(n)&1n)return t-1-n;return t}reverseBytes(e,t,n){let r=t/8,i=[],a=e;for(let e=0;e<r;e++)i.push(a&255n),a>>=8n;let o=0n;for(let e=0;e<r;e+=n)for(let t=0;t<n;t++){let r=i[e+n-1-t]??0n;o|=r<<BigInt((e+t)*8)}return o}readGpr(e){return e===31?0n:this.gpr[e]??0n}writeGpr(e,t){e!==31&&(this.gpr[e]=BigInt.asUintN(64,t))}readGprSp(e){return e===31?this.sp:this.gpr[e]??0n}writeGprSp(e,t){if(e===31){this.sp=BigInt.asUintN(64,t);return}this.gpr[e]=BigInt.asUintN(64,t)}writeNamed(e,t){let n=e.toLowerCase();if(n===`sp`){this.sp=t;return}if(n===`pc`){this.pc=Number(t);return}n!==`xzr`&&(this.gpr[this.gprIndex(n)]=t)}readNamed(e){let t=e.toLowerCase();return t===`sp`?this.sp:t===`pc`?BigInt(this.pc):t===`xzr`?0n:this.gpr[this.gprIndex(t)]??0n}gprIndex(e){let t=/^x(\d{1,2})$/.exec(e),n=t?Number(t[1]):NaN;if(!Number.isInteger(n)||n<0||n>=31)throw Error(`Unknown register: "${e}"`);return n}findRegion(e,t){for(let n of this.regions)if(e>=n.base&&e+t<=n.base+n.size)return n;throw Error(`Unmapped memory access at 0x${e.toString(16)} (len ${t})`)}loadValue(e,t){let n=this.findRegion(e,t),r=n.data,i=e-n.base,a=0n;for(let e=0;e<t;e++)a|=BigInt(r[i++])<<BigInt(e*8);return a}storeValue(e,t,n){let r=this.findRegion(e,t),i=r.data,a=e-r.base,o=n;for(let e=0;e<t;e++)i[a++]=Number(o&255n),o>>=8n}};const V={GetVersion:4,FindClass:6,GetObjectClass:31,IsInstanceOf:32,GetMethodID:33,CallObjectMethod:34,CallBooleanMethod:37,CallIntMethod:49,CallLongMethod:51,CallVoidMethod:61,GetFieldID:94,GetObjectField:95,GetBooleanField:96,GetIntField:100,GetLongField:101,SetObjectField:104,SetBooleanField:105,SetIntField:109,SetLongField:110,GetStaticMethodID:113,CallStaticObjectMethod:114,CallStaticBooleanMethod:117,CallStaticIntMethod:119,CallStaticLongMethod:121,CallStaticVoidMethod:143,GetStaticFieldID:144,GetStaticObjectField:145,GetStaticBooleanField:146,GetStaticIntField:150,GetStaticLongField:151,SetStaticObjectField:154,SetStaticIntField:159,NewStringUTF:167,GetStringUTFLength:168,GetStringUTFChars:169,ReleaseStringUTFChars:170,GetArrayLength:171,NewObjectArray:172,GetObjectArrayElement:173,SetObjectArrayElement:174,NewByteArray:176,GetByteArrayElements:184,ReleaseByteArrayElements:187,GetByteArrayRegion:208,SetByteArrayRegion:209,RegisterNatives:215,GetJavaVM:219,Throw:13,ThrowNew:14,ExceptionOccurred:15,ExceptionClear:17,ExceptionCheck:228,NewGlobalRef:21,DeleteGlobalRef:22,DeleteLocalRef:23,NewLocalRef:25,IsSameObject:24},Rn={DestroyJavaVM:3,AttachCurrentThread:4,DetachCurrentThread:5,GetEnv:6,AttachCurrentThreadAsDaemon:7},zn=1610612736,Bn=1610612992,Vn=1610743808,Hn=1610744064;var Un=class{engine;stubBump=1611661312;vmStubBump=1611792384;handleBump=1879048192;handles=new Map;classes=new Map;classByHandle=new Map;natives=new Map;arrayElements=new Map;javaMethods=new Map;javaFields=new Map;pendingException=0;constructor(e){this.engine=e,this.installEnvTable(),this.installVmTable()}envPointer(){return zn}javaVmPointer(){return Vn}defineClass(e){let t=this.classes.get(e);if(t!==void 0)return t;let n=this.allocHandle({kind:`class`,name:e});return this.classes.set(e,n),this.classByHandle.set(n,{name:e,methods:new Map,fields:new Map}),n}classNameOf(e){return this.classByHandle.get(e)?.name}registerJavaMethod(e,t,n,r){let i=this.classByHandle.get(this.defineClass(e));if(!i)return;let a=`${t}#${n}`,o=i.methods.get(a);o===void 0&&(o=this.allocHandle({kind:`method`,name:t,sig:n,cls:e}),i.methods.set(a,o)),this.javaMethods.set(o,{className:e,name:t,sig:n,impl:r})}registerJavaField(e,t,n,r){let i=this.classByHandle.get(this.defineClass(e));if(!i)return;let a=`${t}#${n}`,o=i.fields.get(a);o===void 0&&(o=this.allocHandle({kind:`field`,name:t,sig:n,cls:e}),i.fields.set(a,o)),this.javaFields.set(o,{className:e,name:t,sig:n,value:r})}nativeBinding(e,t,n){return this.natives.get(`${e}#${t}#${n}`)}valueOf(e){return this.handles.get(e)}allocHandle(e){let t=this.handleBump;return this.handleBump+=8,this.handles.set(t,e),t}installEnvTable(){this.engine.mapMemory(zn,8),this.engine.mapMemory(Bn,1856),this.writePointer(zn,Bn),this.bind(V.GetVersion,()=>BigInt(65542)),this.bind(V.FindClass,e=>this.jniFindClass(e)),this.bind(V.GetMethodID,e=>this.jniGetMethodID(e)),this.bind(V.RegisterNatives,e=>this.jniRegisterNatives(e)),this.bind(V.NewStringUTF,e=>this.jniNewStringUTF(e)),this.bind(V.GetStringUTFChars,e=>this.jniGetStringUTFChars(e)),this.bind(V.ReleaseStringUTFChars,()=>void 0),this.bind(V.NewByteArray,e=>this.jniNewByteArray(e)),this.bind(V.GetArrayLength,e=>this.jniGetArrayLength(e)),this.bind(V.GetByteArrayElements,e=>this.jniGetByteArrayElements(e)),this.bind(V.ReleaseByteArrayElements,e=>this.jniReleaseByteArrayElements(e)),this.bind(V.SetByteArrayRegion,e=>this.jniSetByteArrayRegion(e)),this.bind(V.GetByteArrayRegion,e=>this.jniGetByteArrayRegion(e)),this.bind(V.GetJavaVM,e=>this.jniGetJavaVM(e)),this.bind(V.GetStaticMethodID,e=>this.jniGetMethodID(e)),this.bind(V.CallObjectMethod,e=>this.jniCallMethod(e)),this.bind(V.CallBooleanMethod,e=>this.jniCallMethod(e)),this.bind(V.CallIntMethod,e=>this.jniCallMethod(e)),this.bind(V.CallVoidMethod,e=>this.jniCallMethod(e)),this.bind(V.CallStaticObjectMethod,e=>this.jniCallMethod(e)),this.bind(V.CallStaticIntMethod,e=>this.jniCallMethod(e)),this.bind(V.CallLongMethod,e=>this.jniCallMethod(e)),this.bind(V.CallStaticBooleanMethod,e=>this.jniCallMethod(e)),this.bind(V.CallStaticLongMethod,e=>this.jniCallMethod(e)),this.bind(V.CallStaticVoidMethod,e=>this.jniCallMethod(e)),this.bind(V.GetFieldID,e=>this.jniGetFieldID(e)),this.bind(V.GetStaticFieldID,e=>this.jniGetFieldID(e)),this.bind(V.GetObjectField,e=>this.jniGetField(e)),this.bind(V.GetBooleanField,e=>this.jniGetField(e)),this.bind(V.GetIntField,e=>this.jniGetField(e)),this.bind(V.GetLongField,e=>this.jniGetField(e)),this.bind(V.GetStaticObjectField,e=>this.jniGetStaticField(e)),this.bind(V.GetStaticBooleanField,e=>this.jniGetStaticField(e)),this.bind(V.GetStaticIntField,e=>this.jniGetStaticField(e)),this.bind(V.GetStaticLongField,e=>this.jniGetStaticField(e)),this.bind(V.SetObjectField,()=>void 0),this.bind(V.SetBooleanField,()=>void 0),this.bind(V.SetIntField,()=>void 0),this.bind(V.SetLongField,()=>void 0),this.bind(V.SetStaticObjectField,()=>void 0),this.bind(V.SetStaticIntField,()=>void 0),this.bind(V.GetStringUTFLength,e=>this.jniGetStringUTFLength(e)),this.bind(V.GetObjectClass,e=>this.jniGetObjectClass(e)),this.bind(V.NewObjectArray,e=>this.jniNewObjectArray(e)),this.bind(V.GetObjectArrayElement,e=>this.jniGetObjectArrayElement(e)),this.bind(V.SetObjectArrayElement,e=>this.jniSetObjectArrayElement(e)),this.bind(V.Throw,e=>(this.pendingException=Number(e.x(1)),0n)),this.bind(V.ThrowNew,e=>(this.pendingException=this.allocHandle({kind:`throwable`,cls:Number(e.x(1))}),0n)),this.bind(V.ExceptionOccurred,()=>BigInt(this.pendingException)),this.bind(V.ExceptionCheck,()=>this.pendingException===0?0n:1n),this.bind(V.ExceptionClear,()=>{this.pendingException=0}),this.bind(V.NewGlobalRef,e=>e.x(1)),this.bind(V.NewLocalRef,e=>e.x(1)),this.bind(V.DeleteGlobalRef,()=>void 0),this.bind(V.DeleteLocalRef,()=>void 0),this.bind(V.IsSameObject,e=>e.x(1)===e.x(2)?1n:0n),this.bind(V.IsInstanceOf,()=>1n)}installVmTable(){this.engine.mapMemory(Vn,8),this.engine.mapMemory(Hn,128),this.writePointer(Vn,Hn),this.bindVm(Rn.GetEnv,e=>{let t=Number(e.x(1));return this.writePointer(t,zn),0n})}bind(e,t){let n=this.stubBump;this.stubBump+=8,this.engine.registerHostFunction(n,t),this.writePointer(Bn+e*8,n)}bindVm(e,t){let n=this.vmStubBump;this.vmStubBump+=8,this.engine.registerHostFunction(n,t),this.writePointer(Hn+e*8,n)}jniFindClass(e){let t=this.readCString(e,Number(e.x(1)));return BigInt(this.defineClass(t))}jniGetMethodID(e){let t=this.classByHandle.get(Number(e.x(1))),n=this.readCString(e,Number(e.x(2))),r=this.readCString(e,Number(e.x(3))),i=`${n}#${r}`;if(t){let e=t.methods.get(i);if(e!==void 0)return BigInt(e);let a=this.allocHandle({kind:`method`,name:n,sig:r,cls:t.name});return t.methods.set(i,a),BigInt(a)}return BigInt(this.allocHandle({kind:`method`,name:n,sig:r}))}jniRegisterNatives(e){let t=this.classByHandle.get(Number(e.x(1))),n=Number(e.x(2)),r=Number(e.x(3));for(let i=0;i<r;i++){let r=n+i*24,a=this.readPointer(e,r),o=this.readPointer(e,r+8),s=this.readPointer(e,r+16),c=this.readCString(e,a),l=this.readCString(e,o),u=t?.name??``;this.natives.set(`${u}#${c}#${l}`,{name:c,signature:l,fnAddr:s})}return 0n}jniNewStringUTF(e){let t=this.readCString(e,Number(e.x(1)));return BigInt(this.allocHandle({kind:`string`,value:t}))}jniGetStringUTFChars(e){let t=this.handles.get(Number(e.x(1))),n=Wn(t)?t.value:``,r=new TextEncoder().encode(n+`\0`),i=this.allocGuestBuffer(r);return BigInt(i)}jniNewByteArray(e){let t=Number(e.x(1));return BigInt(this.allocHandle({kind:`bytes`,value:new Uint8Array(t)}))}jniGetArrayLength(e){let t=this.handles.get(Number(e.x(1)));return Gn(t)||Kn(t)?BigInt(t.value.length):0n}jniGetByteArrayElements(e){let t=Number(e.x(1)),n=this.handles.get(t),r=Gn(n)?n.value:new Uint8Array,i=this.allocGuestBuffer(r);return this.arrayElements.set(i,{handle:t,length:r.length}),BigInt(i)}jniReleaseByteArrayElements(e){let t=Number(e.x(2)),n=Number(e.x(3)),r=this.arrayElements.get(t);if(!r)return;let i=this.handles.get(r.handle);n!==2&&Gn(i)&&i.value.set(e.read(t,r.length)),n!==1&&this.arrayElements.delete(t)}jniSetByteArrayRegion(e){let t=this.handles.get(Number(e.x(1)));if(!Gn(t))return;let n=Number(e.x(2)),r=Number(e.x(3)),i=Number(e.x(4)),a=e.read(i,r);t.value.set(a.subarray(0,r),n)}jniGetByteArrayRegion(e){let t=this.handles.get(Number(e.x(1)));if(!Gn(t))return;let n=Number(e.x(2)),r=Number(e.x(3)),i=Number(e.x(4));e.write(i,t.value.subarray(n,n+r))}jniGetJavaVM(e){let t=Number(e.x(1));return this.writePointer(t,Vn),0n}jniCallMethod(e){let t=Number(e.x(1)),n=Number(e.x(2)),r=this.javaMethods.get(n);if(!r)return 0n;let i=[e.x(3),e.x(4),e.x(5),e.x(6),e.x(7)],a=r.impl({args:i,self:t,jni:this});return a===void 0?0n:BigInt.asUintN(64,BigInt(a))}jniGetFieldID(e){let t=this.classByHandle.get(Number(e.x(1))),n=this.readCString(e,Number(e.x(2))),r=this.readCString(e,Number(e.x(3))),i=`${n}#${r}`;if(t){let e=t.fields.get(i);if(e!==void 0)return BigInt(e);let a=this.allocHandle({kind:`field`,name:n,sig:r,cls:t.name});return t.fields.set(i,a),BigInt(a)}return BigInt(this.allocHandle({kind:`field`,name:n,sig:r}))}jniGetField(e){let t=this.javaFields.get(Number(e.x(2)));return t?t.value:0n}jniGetStaticField(e){let t=this.javaFields.get(Number(e.x(2)));return t?t.value:0n}jniGetStringUTFLength(e){let t=this.handles.get(Number(e.x(1))),n=Wn(t)?t.value:``;return BigInt(new TextEncoder().encode(n).length)}jniGetObjectClass(e){let t=this.handles.get(Number(e.x(1)));if(t&&typeof t==`object`&&`cls`in t){let e=t.cls;if(typeof e==`string`)return BigInt(this.defineClass(e))}return BigInt(this.defineClass(`java/lang/Object`))}jniNewObjectArray(e){let t=Number(e.x(1)),n=e.x(3),r=Array.from({length:t}).fill(n);return BigInt(this.allocHandle({kind:`objarray`,value:r}))}jniGetObjectArrayElement(e){let t=this.handles.get(Number(e.x(1))),n=Number(e.x(2));return Kn(t)?t.value[n]??0n:0n}jniSetObjectArrayElement(e){let t=this.handles.get(Number(e.x(1))),n=Number(e.x(2));Kn(t)&&(t.value[n]=e.x(3))}allocGuestBuffer(e){let t=this.handleBump;return this.handleBump+=Math.max(8,e.length+8),this.engine.mapMemory(t,Math.max(8,e.length+8)),e.length>0&&this.engine.writeCode(t,e),t}writePointer(e,t){let n=new Uint8Array(8),r=BigInt(t);for(let e=0;e<8;e++)n[e]=Number(r&255n),r>>=8n;this.engine.writeCode(e,n)}readPointer(e,t){let n=e.read(t,8),r=0;for(let e=0;e<8;e++)r+=n[e]*2**(e*8);return r}readCString(e,t){if(t===0)return``;let n=[],r=t;for(;;){let t=e.read(r,1)[0];if(t===0)break;n.push(t),r++}return new TextDecoder().decode(Uint8Array.from(n))}};function Wn(e){return typeof e==`object`&&!!e&&e.kind===`string`}function Gn(e){return typeof e==`object`&&!!e&&e.kind===`bytes`}function Kn(e){return typeof e==`object`&&!!e&&e.kind===`objarray`}const qn=1048576;function Jn(e,t){if(t===0)return``;let n=[];for(let r=0;;r++){let i=e.read(t+r,1)[0]??0;if(i===0)break;n.push(i)}return new TextDecoder().decode(Uint8Array.from(n))}function Yn(e,t={}){let n=new Map,r=qn,i=new Map,a=t=>{let n=Math.max(16,t+16-1&-16),a=r;return e.mapMemory(a,n),r+=n,i.set(a,t),a},o=new Map,s=t.files;return n.set(`strlen`,e=>{let t=Number(e.x(0)),n=0;for(;e.read(t+n,1)[0]!==0;)n++;return BigInt(n)}),n.set(`memcpy`,e=>{let t=Number(e.x(0));return e.write(t,e.read(Number(e.x(1)),Number(e.x(2)))),e.x(0)}),n.set(`memmove`,e=>{let t=Number(e.x(0)),n=Uint8Array.from(e.read(Number(e.x(1)),Number(e.x(2))));return e.write(t,n),e.x(0)}),n.set(`memset`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)&255n),r=Number(e.x(2));return e.write(t,new Uint8Array(r).fill(n)),e.x(0)}),n.set(`memcmp`,e=>{let t=e.read(Number(e.x(0)),Number(e.x(2))),n=e.read(Number(e.x(1)),Number(e.x(2)));for(let e=0;e<t.length;e++){let r=(t[e]??0)-(n[e]??0);if(r!==0)return BigInt(r<0?-1:1)}return 0n}),n.set(`strcmp`,e=>{let t=Number(e.x(0)),n=Number(e.x(1));for(;;){let r=e.read(t++,1)[0]??0,i=e.read(n++,1)[0]??0;if(r!==i)return BigInt(r<i?-1:1);if(r===0)return 0n}}),n.set(`strncmp`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)),r=Number(e.x(2));for(let i=0;i<r;i++){let r=e.read(t++,1)[0]??0,i=e.read(n++,1)[0]??0;if(r!==i)return BigInt(r<i?-1:1);if(r===0)break}return 0n}),n.set(`strcpy`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)),r=0;for(;;){let i=e.read(n++,1)[0]??0;if(e.write(t+r,Uint8Array.of(i)),r++,i===0)break}return e.x(0)}),n.set(`strncpy`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)),r=Number(e.x(2)),i=!1;for(let a=0;a<r;a++){let r=i?0:e.read(n+a,1)[0]??0;e.write(t+a,Uint8Array.of(r)),r===0&&(i=!0)}return e.x(0)}),n.set(`strchr`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)&255n);for(let r=0;;r++){let i=e.read(t+r,1)[0]??0;if(i===n)return BigInt(t+r);if(i===0)return 0n}}),n.set(`strdup`,e=>{let t=Number(e.x(0)),n=0;for(;e.read(t+n,1)[0]!==0;)n++;let r=a(n+1);return e.write(r,e.read(t,n+1)),BigInt(r)}),n.set(`malloc`,e=>BigInt(a(Number(e.x(0))))),n.set(`calloc`,e=>{let t=Number(e.x(0))*Number(e.x(1)),n=a(t);return e.write(n,new Uint8Array(t)),BigInt(n)}),n.set(`realloc`,e=>{let t=Number(e.x(0)),n=Number(e.x(1));if(t===0)return BigInt(a(n));let r=a(n),o=i.get(t)??0;return o>0&&e.write(r,e.read(t,Math.min(o,n))),BigInt(r)}),n.set(`free`,()=>void 0),n.set(`__stack_chk_fail`,()=>{throw Error(`bionic: __stack_chk_fail (stack canary corrupted in emulated code)`)}),n.set(`abort`,()=>{throw Error(`bionic: abort() called by emulated code`)}),n.set(`fopen`,e=>{let t=Jn(e,Number(e.x(0))),n=s?.get(t);if(!n)return 0n;let r=a(1);return o.set(r,{bytes:n,pos:0}),BigInt(r)}),n.set(`fclose`,e=>(o.delete(Number(e.x(0))),0n)),n.set(`fread`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)),r=Number(e.x(2)),i=o.get(Number(e.x(3)));if(!i||n===0)return 0n;let a=n*r,s=i.bytes.subarray(i.pos,i.pos+a);return s.length>0&&e.write(t,s),i.pos+=s.length,BigInt(Math.floor(s.length/n))}),n.set(`fgets`,e=>{let t=Number(e.x(0)),n=Number(e.x(1)),r=o.get(Number(e.x(2)));if(!r||n<=0||r.pos>=r.bytes.length)return 0n;let i=[];for(;i.length<n-1&&r.pos<r.bytes.length;){let e=r.bytes[r.pos++]??0;if(i.push(e),e===10)break}return i.push(0),e.write(t,Uint8Array.from(i)),BigInt(t)}),n.set(`feof`,e=>{let t=o.get(Number(e.x(0)));return t&&t.pos>=t.bytes.length?1n:0n}),n.set(`__android_log_print`,e=>{let n=Number(e.x(0)),r=Jn(e,Number(e.x(1))),i=Jn(e,Number(e.x(2)));return t.onLog?.(n,r,i),1n}),n.set(`__cxa_atexit`,()=>0n),n.set(`__cxa_finalize`,()=>void 0),n}function Xn(e,t){if(t.strlen!==void 0&&e.registerHostFunction(t.strlen,e=>{let t=Number(e.x(0)),n=0;for(;e.read(t+n,1)[0]!==0;)n++;return BigInt(n)}),t.memcpy!==void 0&&e.registerHostFunction(t.memcpy,e=>{let t=Number(e.x(0)),n=Number(e.x(1)),r=Number(e.x(2));return e.write(t,e.read(n,r)),e.x(0)}),t.memset!==void 0&&e.registerHostFunction(t.memset,e=>{let t=Number(e.x(0)),n=Number(e.x(1)&255n),r=Number(e.x(2));return e.write(t,new Uint8Array(r).fill(n)),e.x(0)}),t.malloc!==void 0){let n=qn;e.registerHostFunction(t.malloc,t=>{let r=Number(t.x(0)),i=Math.max(16,r+16-1&-16),a=n;return e.mapMemory(a,i),n+=i,BigInt(a)})}t.free!==void 0&&e.registerHostFunction(t.free,()=>void 0)}const Zn=4096;function Qn(e,t={}){let n=t.pid??1e4;e.registerSyscall(172,()=>BigInt(n)),e.registerSyscall(178,()=>BigInt(t.tid??n)),e.registerSyscall(113,e=>(rr(e,Number(e.x(1)),tr(t)),0n)),e.registerSyscall(169,e=>{let n=Number(e.x(0));return n!==0&&ir(e,n,tr(t)),0n}),e.registerSyscall(64,e=>{let n=Number(e.x(0)),r=Number(e.x(1)),i=Number(e.x(2)),a=e.read(r,i);return t.onWrite?.(n,a),BigInt(i)}),e.registerSyscall(63,e=>{let n=Number(e.x(0)),r=Number(e.x(1)),i=Number(e.x(2)),a=t.onRead?.(n,i)??new Uint8Array,o=Math.min(a.length,i);return o>0&&e.write(r,a.subarray(0,o)),BigInt(o)}),e.registerSyscall(57,()=>0n);let r=1342177280;e.registerSyscall(222,t=>{let n=Number(t.x(1)),i=Math.max(Zn,n+Zn-1&-4096),a=r;return e.mapMemory(a,i),r+=i,BigInt(a)}),e.registerSyscall(215,()=>0n),e.registerSyscall(226,()=>0n),e.registerSyscall(29,()=>0n),e.registerSyscall(98,()=>0n),e.registerSyscall(135,()=>0n),e.registerSyscall(96,()=>BigInt(t.tid??n)),e.registerSyscall(278,e=>{let n=Number(e.x(0)),r=Number(e.x(1)),i=t.onGetrandom?.(r)??$n(r),a=Math.min(i.length,r);return a>0&&e.write(n,i.subarray(0,a)),BigInt(a)});let i=3;e.registerSyscall(56,e=>{let n=er(e,Number(e.x(1))),r=Number(e.x(2)),a=t.onOpen?.(n,r);return BigInt(a===void 0?-2:a>=0?a:i++)}),e.registerSyscall(62,e=>{let t=Number(e.x(1)),n=Number(e.x(2));return BigInt(n===0?t:0)}),e.registerSyscall(80,e=>{let t=Number(e.x(1));return t!==0&&e.write(t,new Uint8Array(128)),0n}),e.registerSyscall(93,()=>{e.requestStop()}),e.registerSyscall(94,()=>{e.requestStop()})}function $n(e){let t=new Uint8Array(Math.max(0,e)),n=625341585;for(let e=0;e<t.length;e++)n=Math.imul(n,1103515245)+12345>>>0,t[e]=n>>>16&255;return t}function er(e,t,n=4096){if(t===0)return``;let r=[];for(let i=0;i<n;i++){let n=e.read(t+i,1)[0]??0;if(n===0)break;r.push(n)}return new TextDecoder().decode(Uint8Array.from(r))}function tr(e){return e.clockSeconds??Math.floor(Date.now()/1e3)}function nr(e,t,n){let r=new Uint8Array(8),i=BigInt(n);for(let e=0;e<8;e++)r[e]=Number(i&255n),i>>=8n;e.write(t,r)}function rr(e,t,n){nr(e,t,n),nr(e,t+8,0)}function ir(e,t,n){nr(e,t,n),nr(e,t+8,0)}var ar=class{engine;jni;bionic;constructor(e={}){this.engine=new Ln,this.jni=new Un(this.engine),this.bionic=Yn(this.engine,e.bionic??{}),e.syscalls!==!1&&Qn(this.engine,e.syscalls??{})}isAvailable(){return this.engine.isAvailable()}loadLibrary(e){return this.engine.loadElf(e,this.bionic)}installLibc(e){Xn(this.engine,e)}call(e,t=[]){return this.engine.callSymbol(e,t)}callJniExport(e,t=[],n=0){return this.engine.callSymbol(e,[this.jni.envPointer(),n,...t])}setupJava(e,t,n,r){this.jni.registerJavaMethod(e,t,n,r)}setupJavaField(e,t,n,r){this.jni.registerJavaField(e,t,n,r)}newByteArray(e){return this.jni.allocHandle({kind:`bytes`,value:e})}bytesOf(e){let t=this.jni.valueOf(e);return or(t)?t.value:void 0}stringOf(e){let t=this.jni.valueOf(e);return sr(t)?t.value:void 0}};function or(e){return typeof e==`object`&&!!e&&`kind`in e&&e.kind===`bytes`}function sr(e){return typeof e==`object`&&!!e&&`kind`in e&&e.kind===`string`}var cr=class{sessions=new Map;idleTtlMs;sweepIntervalMs;maxSessions;emulatorOptions;sweepTimer=null;constructor(r={}){this.idleTtlMs=r.idleTtlMs??n,this.sweepIntervalMs=r.sweepIntervalMs??e,this.maxSessions=r.maxSessions??t,this.emulatorOptions=r.emulatorOptions??{},this.startSweep()}createSession(e={}){if(this.sessions.size>=this.maxSessions)throw Error(`Emulator session limit reached (${this.maxSessions}); destroy an existing session first`);let t=e.syscalls===void 0?this.emulatorOptions:{...this.emulatorOptions,syscalls:e.syscalls},n=Date.now(),r={id:p(),emulator:new ar(t),createdAt:n,lastUsedAt:n};return this.sessions.set(r.id,r),r}getSession(e){let t=this.sessions.get(e);return t&&(t.lastUsedAt=Date.now()),t}requireSession(e){let t=this.getSession(e);if(!t)throw Error(`Unknown emulator session: ${e}`);return t}destroySession(e){return this.sessions.delete(e)}listSessions(){let e=[];for(let t of this.sessions.values())e.push({id:t.id,createdAt:t.createdAt,lastUsedAt:t.lastUsedAt});return e}count(){return this.sessions.size}dispose(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear()}startSweep(){this.sweepTimer=setInterval(()=>this.sweep(),this.sweepIntervalMs),this.sweepTimer.unref&&this.sweepTimer.unref()}sweep(){let e=Date.now();for(let[t,n]of this.sessions)e-n.lastUsedAt>=this.idleTtlMs&&this.sessions.delete(t)}};const lr=/^lib\/arm64-v8a\/(lib[^/]+\.so)$/i;async function ur(e){if(!e||e.length===0)throw new r(`VALIDATION`,`apkPath must be a non-empty string`);return new Promise((t,n)=>{m(e,{lazyEntries:!0,autoClose:!0},(i,a)=>{if(i||!a){n(new r(`VALIDATION`,`Failed to open APK as ZIP: ${i?.message??`unknown`}`,{details:{apkPath:e},cause:i??void 0}));return}let o=a,s=[],c=t=>{let i=lr.exec(t.fileName);if(!i){o.readEntry();return}let a=i[1];o.openReadStream(t,(t,i)=>{if(t||!i){d(),o.close(),n(new r(`RUNTIME`,`Failed to read ${a}: ${t?.message??`unknown`}`,{details:{apkPath:e,name:a},cause:t??void 0}));return}dr(i,268435456).then(e=>{s.push({name:a,bytes:e}),o.readEntry()},t=>{d(),o.close(),n(new r(`RUNTIME`,`Reading ${a} failed: ${t.message}`,{details:{apkPath:e,name:a},cause:t}))})})},l=()=>{d(),t(s)},u=t=>{d(),o.close(),n(new r(`RUNTIME`,`ZIP read failed: ${t.message}`,{details:{apkPath:e},cause:t}))};function d(){o.removeListener(`entry`,c),o.removeListener(`end`,l),o.removeListener(`error`,u)}o.on(`entry`,c),o.on(`end`,l),o.on(`error`,u),o.readEntry()})})}function dr(e,t){return new Promise((n,r)=>{let i=[],a=0;e.on(`data`,n=>{if(a+=n.length,a>t){e.destroy(),r(Error(`extracted .so exceeds ${t} bytes`));return}i.push(n)}),e.on(`end`,()=>n(Uint8Array.from(Buffer.concat(i)))),e.on(`error`,r)})}function fr(e,t){let n=pr(e,t);return n?`${n.mnemonic.padEnd(8)} ${n.operands}`:`<unknown> 0x${e.toString(16).padStart(8,`0`)}`}function pr(e,t){if(e===3596551104)return{mnemonic:`ret`,operands:``};if(e===3573751839)return{mnemonic:`nop`,operands:``};if(H(e,2145452e3,704644064)){let t=e>>16&31,n=e&31,r=e>>31&1?`x`:`w`;return{mnemonic:`mov`,operands:`${r}${n}, ${r}${t}`}}return H(e,4293918720,3576692736)?jr(e):H(e,4293918720,3574595584)?Mr(e):H(e,520093696,268435456)?mr(e,t):H(e,520093696,285212672)?hr(e):H(e,528482304,301989888)?gr(e):H(e,528482304,310378496)?vr(e):H(e,528482304,318767104)?yr(e):H(e,2080374784,335544320)?br(e,t):H(e,4278190096,1409286144)?xr(e,t):H(e,2113929216,872415232)?Sr(e,t):H(e,4294966303,3594452992)?{mnemonic:`blr`,operands:`x${e>>5&31}`}:H(e,4294966303,3592355840)?{mnemonic:`br`,operands:`x${e>>5&31}`}:H(e,989855744,402653184)?Cr(e,t):H(e,989855744,956301312)?wr(e):H(e,991955968,939525120)?Tr(e):H(e,939524096,671088640)?Er(e):H(e,1056964608,134217728)?Dr(e):H(e,522190848,167772160)?Or(e):H(e,522190848,184549376)?kr(e):H(e,534773760,444596224)?Ar(e):H(e,522190848,236978176)?Nr(e):null}function H(e,t,n){return(e&t)>>>0==n>>>0}function mr(e,t){let n=e>>31&1,r=e>>29&3,i=e&31,a=e>>5&524287,o=BigInt(a)<<2n|BigInt(r),s=1n<<20n,c=(o^s)-s;return n?{mnemonic:`adrp`,operands:`x${i}, 0x${((t>>12n<<12n)+(c<<12n)).toString(16)}`}:{mnemonic:`adr`,operands:`x${i}, 0x${(t+c).toString(16)}`}}function hr(e){let t=e>>31&1,n=e>>30&1,r=e>>29&1,i=e>>22&1,a=e>>10&4095,o=e>>5&31,s=e&31,c=t?`x`:`w`,l=i?a<<12:a;return{mnemonic:r?n?`subs`:`adds`:n?`sub`:`add`,operands:`${c}${s}, ${c}${o}, #${l}`}}function gr(e){let t=e>>31&1,n=e>>29&3,r=e&31,i=e>>5&31,a=t?`x`:`w`,o=e>>16&63,s=e>>10&63,c=_r(e>>22&1,o,s,t);return{mnemonic:[`and`,`orr`,`eor`,`ands`][n]||`logical`,operands:`${a}${r}, ${a}${i}, #0x${c.toString(16)}`}}function _r(e,t,n,r){let i=r?e?6:32-Math.clz32(~n&63):e?0:32-Math.clz32(~n&63);if(i<1)return 0n;let a=(1<<i)-1,o=n&a,s=t&a,c=1<<i,l=BigInt((1<<o+1)-1);if(s>0){let e=BigInt(c),t=BigInt(s);l=(l>>t|l<<e-t)&(1n<<BigInt(c))-1n}let u=0n,d=BigInt(c),f=r?64n:32n;for(let e=0n;e<f;e+=d)u|=l<<e;return u}function vr(e){let t=e>>31&1,n=e>>29&3,r=e>>21&3,i=e>>5&65535,a=e&31,o=t?`x`:`w`,s=[`movn`,`reserved`,`movz`,`movk`],c=r*16;return n===2&&!c?{mnemonic:`mov`,operands:`${o}${a}, #0x${i.toString(16)}`}:{mnemonic:s[n]||`mov`,operands:c?`${o}${a}, #0x${i.toString(16)}, lsl #${c}`:`${o}${a}, #0x${i.toString(16)}`}}function yr(e){let t=e>>31&1,n=e>>29&3,r=e>>16&63,i=e>>10&63,a=e>>5&31,o=e&31,s=t?`x`:`w`,c=t?64:32;if(n===2){if(i===c-1)return{mnemonic:`lsr`,operands:`${s}${o}, ${s}${a}, #${r}`};if(i+1===r)return{mnemonic:`ubfx`,operands:`${s}${o}, ${s}${a}, #${r}, #${i-r+1}`};if(r===0){if(i===7)return{mnemonic:`uxtb`,operands:`${s}${o}, ${s}${a}`};if(i===15)return{mnemonic:`uxth`,operands:`${s}${o}, ${s}${a}`}}return{mnemonic:`ubfm`,operands:`${s}${o}, ${s}${a}, #${r}, #${i}`}}if(n===0){if(i===c-1)return{mnemonic:`asr`,operands:`${s}${o}, ${s}${a}, #${r}`};if(r===0){if(i===7)return{mnemonic:`sxtb`,operands:`${s}${o}, ${s}${a}`};if(i===15)return{mnemonic:`sxth`,operands:`${s}${o}, ${s}${a}`};if(i===31&&t)return{mnemonic:`sxtw`,operands:`x${o}, w${a}`}}return{mnemonic:`sbfm`,operands:`${s}${o}, ${s}${a}, #${r}, #${i}`}}return{mnemonic:`bfm`,operands:`${s}${o}, ${s}${a}, #${r}, #${i}`}}function br(e,t){let n=e>>31&1,r=e&67108863,i=t+(BigInt(r<<6)>>4n);return{mnemonic:n?`bl`:`b`,operands:`0x${i.toString(16)}`}}function xr(e,t){let n=e&15,r=e>>5&524287,i=t+(BigInt(r)<<45n>>43n);return{mnemonic:`b.${[`eq`,`ne`,`cs`,`cc`,`mi`,`pl`,`vs`,`vc`,`hi`,`ls`,`ge`,`lt`,`gt`,`le`,`al`,`nv`][n]}`,operands:`0x${i.toString(16)}`}}function Sr(e,t){let n=e>>31&1,r=e>>24&1,i=e>>5&524287,a=e&31,o=t+(BigInt(i)<<45n>>43n);return{mnemonic:r?`cbnz`:`cbz`,operands:`${n?`x`:`w`}${a}, 0x${o.toString(16)}`}}function Cr(e,t){let n=e>>30&3,r=e>>26&1,i=e>>5&524287,a=e&31,o=t+(BigInt(i)<<45n>>43n);return r?{mnemonic:`ldr`,operands:`${[`b`,`h`,`s`,`d`][n]}${a}, 0x${o.toString(16)}`}:{mnemonic:`ldr`,operands:`${[`w`,`w`,`x`,`x`][n]}${a}, 0x${o.toString(16)}`}}function wr(e){let t=e>>30&3,n=e>>26&1,r=e>>22&3,i=e>>10&4095,a=e>>5&31,o=e&31;if(n)return{mnemonic:`ldr/str`,operands:`<simd>`};let s=i<<t,c=r&1,l=t===3?`x`:`w`;return{mnemonic:c?`ldr`:`str`,operands:s?`${l}${o}, [x${a}, #${s}]`:`${l}${o}, [x${a}]`}}function Tr(e){let t=e>>30&3,n=e>>22&3,r=e>>16&31,i=e>>13&7,a=e>>12&1,o=e>>5&31,s=e&31,c=n&1,l=t===3?`x`:`w`,u=[`uxtw`,`uxth`,`uxtb`,`sxtw`,`sxth`,`sxtb`,`lsl`][i]||`lsl`,d=a?`#${t}`:``;return{mnemonic:c?`ldr`:`str`,operands:`${l}${s}, [x${o}, x${r}${u===`lsl`?``:`, ${u}`}${d?` ${d}`:``}]`}}function Er(e){let t=e>>30&3,n=e>>26&1,r=e>>22&1,i=e>>15&127,a=e>>10&31,o=e>>5&31,s=e&31;if(n)return{mnemonic:`ldp/stp`,operands:`<simd>`};let c=2+t,l=i<<25>>25<<c,u=t===2?`x`:`w`;return{mnemonic:r?`ldp`:`stp`,operands:`${u}${s}, ${u}${a}, [x${o}, #${l}]`}}function Dr(e){let t=e>>30&3,n=e>>15&1,r=e>>22&1,i=e>>16&31,a=e&31,o=e>>5&31,s=t===3?`x`:`w`;return r?n?{mnemonic:`ldaxr`,operands:`${s}${a}, [x${o}]`}:{mnemonic:`ldxr`,operands:`${s}${a}, [x${o}]`}:{mnemonic:`stxr`,operands:`${s}${i}, ${s}${a}, [x${o}]`}}function Or(e){let t=e>>31&1,n=e>>29&3,r=e>>22&3,i=e>>16&31,a=e>>10&63,o=e>>5&31,s=e&31,c=t?`x`:`w`;return{mnemonic:[`and`,`bic`,`orr`,`orn`,`eor`,`eon`,`ands`,`bics`][n]||`logical`,operands:a?`${c}${s}, ${c}${o}, ${c}${i}, ${[`lsl`,`lsr`,`asr`,`ror`][r]} #${a}`:`${c}${s}, ${c}${o}, ${c}${i}`}}function kr(e){let t=e>>31&1,n=e>>30&1,r=e>>29&1,i=e>>22&3,a=e>>16&31,o=e>>10&63,s=e>>5&31,c=e&31,l=t?`x`:`w`;return{mnemonic:r?n?`subs`:`adds`:n?`sub`:`add`,operands:o?`${l}${c}, ${l}${s}, ${l}${a}, ${[`lsl`,`lsr`,`asr`,`reserved`][i]} #${o}`:`${l}${c}, ${l}${s}, ${l}${a}`}}function Ar(e){let t=e>>31&1,n=e>>16&31,r=e>>12&15,i=e>>10&3,a=e>>5&31,o=e&31,s=t?`x`:`w`;return{mnemonic:[`csel`,`csinc`,`csinv`,`csneg`][i]||`csel`,operands:`${s}${o}, ${s}${a}, ${s}${n}, ${[`eq`,`ne`,`cs`,`cc`,`mi`,`pl`,`vs`,`vc`,`hi`,`ls`,`ge`,`lt`,`gt`,`le`,`al`,`nv`][r]}`}}function jr(e){return{mnemonic:`mrs`,operands:`x${e&31}, ${`s${e>>16&7}_${e>>12&15}_${e>>8&15}_${e>>5&7}`}`}}function Mr(e){let t=e>>16&7,n=e>>12&15,r=e>>8&15,i=e>>5&7,a=e&31;return{mnemonic:`msr`,operands:`${`s${t}_${n}_${r}_${i}`}, x${a}`}}function Nr(e){if((e&1595932672)==1579155456){let t=e>>22&3,n=e>>12&31,r=e>>5&31,i=e&31,a=[`b`,`h`,`s`,`d`],o=a[t]||`s`;if(n===4)return{mnemonic:`fcvt`,operands:`${a[e>>15&3]||`s`}${i}, ${o}${r}`};if(n===1)return{mnemonic:`fabs`,operands:`${o}${i}, ${o}${r}`};if(n===2)return{mnemonic:`fneg`,operands:`${o}${i}, ${o}${r}`};if(n===3)return{mnemonic:`fsqrt`,operands:`${o}${i}, ${o}${r}`};if(n>=6&&n<=9)return{mnemonic:[`frintn`,`frintm`,`frintp`,`frintz`][n-6]||`frint`,operands:`${o}${i}, ${o}${r}`};if(n===10)return{mnemonic:`frinta`,operands:`${o}${i}, ${o}${r}`};if(n===14)return{mnemonic:`frintx`,operands:`${o}${i}, ${o}${r}`};if(n===15)return{mnemonic:`frinti`,operands:`${o}${i}, ${o}${r}`}}if((e&1595948032)==505421824){let t=e>>22&3,n=e>>16&31,r=e>>3&3,i=e>>5&31,a=[`b`,`h`,`s`,`d`][t]||`s`;if(r===0)return{mnemonic:`fcmp`,operands:`${a}${i}, ${a}${n}`};if(r===1)return{mnemonic:`fcmpe`,operands:`${a}${i}, ${a}${n}`}}if((e&1595964416)==505421824){let t=e>>22&3,n=e>>5&31;return{mnemonic:`fcmp`,operands:`${[`b`,`h`,`s`,`d`][t]||`s`}${n}, #0.0`}}if((e&1595935744)==505415680){let t=e>>22&3,n=e>>16&31,r=e>>12&15,i=e>>5&31,a=e&31,o=[`b`,`h`,`s`,`d`][t]||`s`,s=[`fmul`,`fdiv`,`fadd`,`fsub`,`fmax`,`fmin`,`fmaxnm`,`fminnm`][r];if(s)return{mnemonic:s,operands:`${o}${a}, ${o}${i}, ${o}${n}`}}if((e&1610596352)==505430016){let t=e>>22&3,n=e>>5&31,r=e&31,i=[`b`,`h`,`s`,`d`][t]||`s`;return{mnemonic:`fmov`,operands:`${i}${r}, ${i}${n}`}}if((e&1595935744)==505416704){let t=e>>22&3,n=e>>16&31,r=e>>12&15,i=e>>5&31,a=e&31,o=[`b`,`h`,`s`,`d`][t]||`s`;return{mnemonic:`fcsel`,operands:`${o}${a}, ${o}${i}, ${o}${n}, ${[`eq`,`ne`,`cs`,`cc`,`mi`,`pl`,`vs`,`vc`,`hi`,`ls`,`ge`,`lt`,`gt`,`le`,`al`,`nv`][r]}`}}if((e&1595936768)==505417728){let t=e>>22&3,n=e&31;return{mnemonic:`fmov`,operands:`${[`b`,`h`,`s`,`d`][t]||`s`}${n}, #<fp-imm>`}}return null}function U(e){return`${e.mnemonic.padEnd(8)} ${e.operands}`}function Pr(e,t){if(typeof e==`number`)return e>>>0;let n=Array.from(e);if(n.length<4)throw Error(`Need at least 4 bytes for fixed-width instruction decode, got ${n.length}`);let r=W(n,0),i=W(n,1),a=W(n,2),o=W(n,3);return t===`little`?(r|i<<8|a<<16|o<<24)>>>0:(r<<24|i<<16|a<<8|o)>>>0}function Fr(e){return typeof e==`number`?e<=255?[e&255]:[e&255,e>>>8&255,e>>>16&255,e>>>24&255]:Array.from(e,e=>e&255)}function W(e,t){return(e[t]??0)&255}function Ir(e,t){let n=W(e,t);return n&128?n-256:n}function Lr(e,t){return W(e,t)|W(e,t+1)<<8|W(e,t+2)<<16|W(e,t+3)<<24}function Rr(e,t){return Lr(e,t)>>>0}function zr(e,t){let n=BigInt(Rr(e,t));return BigInt(Rr(e,t+4))<<32n|n}function G(e,t){let n=32-t;return e<<n>>n}function K(e,t,n){return`0x${(e+BigInt(t)+BigInt(n)).toString(16)}`}const Br=`$zero.$at.$v0.$v1.$a0.$a1.$a2.$a3.$t0.$t1.$t2.$t3.$t4.$t5.$t6.$t7.$s0.$s1.$s2.$s3.$s4.$s5.$s6.$s7.$t8.$t9.$k0.$k1.$gp.$sp.$fp.$ra`.split(`.`);function Vr(e,t){if(e===0)return U({mnemonic:`nop`,operands:``});let n=e>>>26&63,r=e>>>21&31,i=e>>>16&31,a=e>>>11&31,o=e>>>6&31,s=e&63,c=e&65535,l=G(c,16);if(n===0)return U(Hr(r,i,a,o,s,e));if(n===2||n===3){let r=t+4n&4026531840n|BigInt(e&67108863)<<2n;return U({mnemonic:n===3?`jal`:`j`,operands:`0x${r.toString(16)}`})}if(n===4||n===5){let e=t+4n+(BigInt(l)<<2n);return U({mnemonic:n===4?`beq`:`bne`,operands:`${q(r)}, ${q(i)}, 0x${e.toString(16)}`})}if(n===15)return U({mnemonic:`lui`,operands:`${q(i)}, #0x${c.toString(16)}`});let u=Wr[n];if(u){let e=n===12||n===13||n===14?`#0x${c.toString(16)}`:`#${l}`;return U({mnemonic:u,operands:`${q(i)}, ${q(r)}, ${e}`})}let d=Gr[n];return d?U({mnemonic:d,operands:`${q(i)}, ${l}(${q(r)})`}):`<unknown> 0x${e.toString(16).padStart(8,`0`)}`}function Hr(e,t,n,r,i,a){if(i===8)return{mnemonic:`jr`,operands:q(e)};if(i===9)return{mnemonic:`jalr`,operands:`${q(n)}, ${q(e)}`};if(i===0)return{mnemonic:`sll`,operands:`${q(n)}, ${q(t)}, #${r}`};if(i===2)return{mnemonic:`srl`,operands:`${q(n)}, ${q(t)}, #${r}`};if(i===3)return{mnemonic:`sra`,operands:`${q(n)}, ${q(t)}, #${r}`};let o=Ur[i];return o?{mnemonic:o,operands:`${q(n)}, ${q(e)}, ${q(t)}`}:{mnemonic:`<unknown>`,operands:`0x${a.toString(16).padStart(8,`0`)}`}}const Ur={32:`add`,33:`addu`,34:`sub`,35:`subu`,36:`and`,37:`or`,38:`xor`,39:`nor`,42:`slt`,43:`sltu`},Wr={8:`addi`,9:`addiu`,10:`slti`,11:`sltiu`,12:`andi`,13:`ori`,14:`xori`},Gr={32:`lb`,33:`lh`,35:`lw`,36:`lbu`,37:`lhu`,40:`sb`,41:`sh`,43:`sw`};function q(e){return Br[e]??`$r${e}`}const Kr=Array.from({length:32},(e,t)=>`x${t}`);function qr(e,t){if(e===19)return U({mnemonic:`nop`,operands:``});if(e===32871)return U({mnemonic:`ret`,operands:``});let n=e&127,r=e>>7&31,i=e>>12&7,a=e>>15&31,o=e>>20&31,s=e>>25&127;if(n===19){let t=G(e>>>20,12),n=[`addi`,`slli`,`slti`,`sltiu`,`xori`,`srli`,`ori`,`andi`][i];if(i===5&&s===32)return U({mnemonic:`srai`,operands:`${J(r)}, ${J(a)}, #${e>>20&31}`});if(n)return U({mnemonic:n,operands:`${J(r)}, ${J(a)}, #${t}`})}if(n===51){let e=Jr[`${s}:${i}`];if(e)return U({mnemonic:e,operands:`${J(r)}, ${J(a)}, ${J(o)}`})}if(n===3){let t=G(e>>>20,12),n=[`lb`,`lh`,`lw`,`ld`,`lbu`,`lhu`,`lwu`][i];if(n)return U({mnemonic:n,operands:`${J(r)}, ${t}(${J(a)})`})}if(n===35){let t=G(e>>7&31|(e>>25&127)<<5,12),n=[`sb`,`sh`,`sw`,`sd`][i];if(n)return U({mnemonic:n,operands:`${J(o)}, ${t}(${J(a)})`})}if(n===99){let n=G(e>>7&30|e>>20&2016|e<<4&2048|e>>19&4096,13),r=[`beq`,`bne`,void 0,void 0,`blt`,`bge`,`bltu`,`bgeu`][i];if(r)return U({mnemonic:r,operands:`${J(a)}, ${J(o)}, 0x${(t+BigInt(n)).toString(16)}`})}if(n===111){let n=G((e>>21&1023)<<1|(e>>20&1)<<11|(e>>12&255)<<12|(e>>31&1)<<20,21);return U({mnemonic:`jal`,operands:`${J(r)}, 0x${(t+BigInt(n)).toString(16)}`})}if(n===103){let t=G(e>>>20,12);return U({mnemonic:`jalr`,operands:`${J(r)}, ${t}(${J(a)})`})}return n===55?U({mnemonic:`lui`,operands:`${J(r)}, #0x${(e&4294963200).toString(16)}`}):n===23?U({mnemonic:`auipc`,operands:`${J(r)}, #0x${(e&4294963200).toString(16)}`}):`<unknown> 0x${e.toString(16).padStart(8,`0`)}`}const Jr={"0:0":`add`,"32:0":`sub`,"0:1":`sll`,"0:2":`slt`,"0:3":`sltu`,"0:4":`xor`,"0:5":`srl`,"32:5":`sra`,"0:6":`or`,"0:7":`and`};function J(e){return Kr[e]??`x${e}`}const Yr=[`o`,`no`,`b`,`ae`,`e`,`ne`,`be`,`a`,`s`,`ns`,`p`,`np`,`l`,`ge`,`le`,`g`],Xr=[`eax`,`ecx`,`edx`,`ebx`,`esp`,`ebp`,`esi`,`edi`,`r8d`,`r9d`,`r10d`,`r11d`,`r12d`,`r13d`,`r14d`,`r15d`],Zr=[`rax`,`rcx`,`rdx`,`rbx`,`rsp`,`rbp`,`rsi`,`rdi`,`r8`,`r9`,`r10`,`r11`,`r12`,`r13`,`r14`,`r15`];function Qr(e,t,n){let r=Fr(e),i=0,a=0,o=`none`;for(;ei(W(r,i));)o=ti(W(r,i))??o,i++;let s=ni(r,i,n);if(s)return s;n===`x64`&&W(r,i)>=64&&W(r,i)<=79&&(a=W(r,i),i++);let c=W(r,i++),l=n===`x64`&&(a&8)!=0;if(c===144)return U({mnemonic:`nop`,operands:``});if(c===195)return U({mnemonic:`ret`,operands:``});if(c===204)return U({mnemonic:`int3`,operands:``});if(c>=80&&c<=87)return U({mnemonic:`push`,operands:$(c-80+(a&1?8:0),n===`x64`?`64`:`32`)});if(c>=88&&c<=95)return U({mnemonic:`pop`,operands:$(c-88+(a&1?8:0),n===`x64`?`64`:`32`)});if(c>=112&&c<=127){let e=Yr[c&15],n=K(t,i+1,Ir(r,i));return U({mnemonic:`j${e}`,operands:n})}if(c===15){let e=W(r,i++);if(e>=128&&e<=143){let n=Yr[e&15],a=K(t,i+4,Lr(r,i));return U({mnemonic:`j${n}`,operands:a})}if(e===56){let e=oi(2,W(r,i++),o,r,i,a,l);if(e)return U(e)}if(e===58){let e=oi(3,W(r,i++),o,r,i,a,l);if(e)return U(e)}let n=ai(e,o,r,i,a,l);if(n)return U(n)}if(c===232)return U({mnemonic:`call`,operands:K(t,i+4,Lr(r,i))});if(c===233)return U({mnemonic:`jmp`,operands:K(t,i+4,Lr(r,i))});if(c===235)return U({mnemonic:`jmp`,operands:K(t,i+1,Ir(r,i))});if(c>=184&&c<=191){let e=$(c-184+(a&1?8:0),l?`64`:`32`);return l&&r.length>=i+8?U({mnemonic:`mov`,operands:`${e}, #0x${zr(r,i).toString(16)}`}):U({mnemonic:`mov`,operands:`${e}, #0x${Rr(r,i).toString(16)}`})}let u={1:[`add`,!1],3:[`add`,!0],41:[`sub`,!1],43:[`sub`,!0],49:[`xor`,!1],51:[`xor`,!0],57:[`cmp`,!1],59:[`cmp`,!0],137:[`mov`,!1],139:[`mov`,!0]}[c];if(u&&r.length>i){let[e,t]=u;return U($r(e,t,W(r,i),a,l))}return`<unknown> ${r.map(e=>e.toString(16).padStart(2,`0`)).join(` `)}`}function $r(e,t,n,r,i){let a=n>>6&3,o=(n>>3&7)+(r&4?8:0),s=(n&7)+(r&1?8:0),c=i?`64`:`32`,l=$(o,c),u=a===3?$(s,c):`[${$(s,`64`)}]`;return{mnemonic:e,operands:t?`${l}, ${u}`:`${u}, ${l}`}}function ei(e){return e===102||e===242||e===243||e===240||e===46||e===54||e===62||e===38||e===100||e===101||e===103}function ti(e){return e===102?`66`:e===242?`f2`:e===243?`f3`:null}function ni(e,t,n){let r=ri(e,t,n);if(!r)return null;let i=W(e,r.opIndex),a=r.opIndex+1;if(e.length<=a)return U({mnemonic:r.evex?`evex`:`vex`,operands:`0x${i.toString(16)}`});if(r.map===1){let t=r.evex?ui(i,r,e,a):si(i,r,e,a);if(t)return U(t)}if(r.map===2){let t=r.evex?di(i,r,e,a):ci(i,r,e,a);if(t)return U(t)}if(r.map===3){let t=li(i,r,e,a);if(t)return U(t)}return null}function ri(e,t,n){let r=W(e,t);if(r===197&&e.length>t+2){let r=W(e,t+1);return{evex:!1,map:1,pp:ii(r&3),w:0,vectorBits:r&4?256:128,opIndex:t+2,regExt:n===`x64`&&!(r&128)?8:0,rmExt:0,vvvv:~(r>>3)&15}}if(r===196&&e.length>t+3){let r=W(e,t+1),i=W(e,t+2);return{evex:!1,map:r&31,pp:ii(i&3),w:i>>7&1,vectorBits:i&4?256:128,opIndex:t+3,regExt:n===`x64`&&!(r&128)?8:0,rmExt:n===`x64`&&!(r&32)?8:0,vvvv:~(i>>3)&15}}if(r===98&&e.length>t+4){let n=W(e,t+1),r=W(e,t+2),i=W(e,t+3),a=i&64?512:i&32?256:128,o=n&128?0:8,s=n&16?0:16,c=n&64?0:8,l=n&32?0:8;return{evex:!0,map:n&3,pp:ii(r&3),w:r>>7&1,vectorBits:a,opIndex:t+4,regExt:o+s,rmExt:l+c,vvvv:~(r>>3)&15,opmask:i&7,zeroing:(i&128)!=0,broadcastOrRounding:(i&16)!=0}}return null}function ii(e){return e===1?`66`:e===2?`f3`:e===3?`f2`:`none`}function ai(e,t,n,r,i,a){if(n.length<=r)return null;let o=W(n,r),s=gi[Y(t,e)];return s?X(s,`xmm`,o,Z(i),Q(i)):t===`66`&&e===111?X(`movdqa`,`xmm`,o,Z(i),Q(i)):t===`f3`&&e===111?X(`movdqu`,`xmm`,o,Z(i),Q(i)):t===`66`&&e===127?X(`movdqa`,`xmm`,o,Z(i),Q(i),!1):t===`f3`&&e===127?X(`movdqu`,`xmm`,o,Z(i),Q(i),!1):t===`66`&&e===56?null:t===`f3`&&e===184?$r(`popcnt`,!0,o,i,(a?`64`:`32`)==`64`):t===`f3`&&e===189?$r(`lzcnt`,!0,o,i,(a?`64`:`32`)==`64`):null}function oi(e,t,n,r,i,a,o){if(r.length<=i)return null;let s=W(r,i);if(e===2){if(n===`66`&&t===219)return X(`aesimc`,`xmm`,s,Z(a),Q(a));if(n===`66`&&t>=220&&t<=223)return X([`aesenc`,`aesenclast`,`aesdec`,`aesdeclast`][t-220],`xmm`,s,Z(a),Q(a));if(n===`66`&&t===64)return X(`pmulld`,`xmm`,s,Z(a),Q(a));if(n===`66`&&t===65)return X(`phminposuw`,`xmm`,s,Z(a),Q(a))}if(e===3){if(n===`66`&&t===68)return fi(`pclmulqdq`,`xmm`,s,r,i+1,Z(a),Q(a));if(n===`66`&&t===223)return fi(`aeskeygenassist`,`xmm`,s,r,i+1,Z(a),Q(a))}return n===`f3`&&e===2&&t===245?$r(`bzhi`,!0,s,a,o):null}function si(e,t,n,r){let i=W(n,r),a=t.vectorBits===256?`ymm`:`xmm`,o=_i[Y(t.pp,e)];return o?X(o,a,i,t.regExt,t.rmExt,!0,t.vvvv):t.pp===`66`&&e===111?X(`vmovdqa`,a,i,t.regExt,t.rmExt):t.pp===`f3`&&e===111?X(`vmovdqu`,a,i,t.regExt,t.rmExt):t.pp===`66`&&e===127?X(`vmovdqa`,a,i,t.regExt,t.rmExt,!1):t.pp===`f3`&&e===127?X(`vmovdqu`,a,i,t.regExt,t.rmExt,!1):null}function ci(e,t,n,r){let i=W(n,r),a=t.vectorBits===256?`ymm`:`xmm`,o=vi[Y(t.pp,e)];return o?X(o,a,i,t.regExt,t.rmExt,!0,t.vvvv):null}function li(e,t,n,r){let i=W(n,r),a=t.vectorBits===256?`ymm`:`xmm`;return t.pp===`66`&&e===68?fi(`vpclmulqdq`,a,i,n,r+1,t.regExt,t.rmExt,t.vvvv):null}function ui(e,t,n,r){let i=W(n,r),a=hi(t),o=yi[Y(t.pp,e)];return o?X(o,a,i,t.regExt,t.rmExt,!0,t.vvvv,t):t.pp===`66`&&e===111?X(`vmovdqa64`,a,i,t.regExt,t.rmExt,!0,void 0,t):t.pp===`f3`&&e===111?X(`vmovdqu64`,a,i,t.regExt,t.rmExt,!0,void 0,t):t.pp===`66`&&e===127?X(`vmovdqa64`,a,i,t.regExt,t.rmExt,!1,void 0,t):t.pp===`f3`&&e===127?X(`vmovdqu64`,a,i,t.regExt,t.rmExt,!1,void 0,t):null}function di(e,t,n,r){let i=W(n,r),a=hi(t),o=bi[Y(t.pp,e)];return o?X(o,a,i,t.regExt,t.rmExt,!0,t.vvvv,t):null}function Y(e,t){return`${e}:${t.toString(16).padStart(2,`0`)}`}function X(e,t,n,r,i,a=!0,o,s){let c=(n>>3&7)+r,l=(n&7)+i,u=`${t}${c}${pi(s)}`,d=(n>>6&3)==3?`${t}${l}`:`[${Zr[l&15]??`r${l}`}]`,f=o===void 0?void 0:`${t}${o}`,p=a?u:d,m=a?d:u;return{mnemonic:e,operands:f?`${p}, ${f}, ${m}${mi(s)}`:`${p}, ${m}${mi(s)}`}}function fi(e,t,n,r,i,a,o,s){let c=X(e,t,n,a,o,!0,s);return{mnemonic:c.mnemonic,operands:`${c.operands}, #0x${W(r,i).toString(16)}`}}function pi(e){return!e?.evex||!e.opmask?``:`{k${e.opmask}}${e.zeroing?`{z}`:``}`}function mi(e){return e?.evex&&e.broadcastOrRounding?` {evex-b}`:``}function hi(e){return e.vectorBits===512?`zmm`:e.vectorBits===256?`ymm`:`xmm`}function Z(e){return e&4?8:0}function Q(e){return e&1?8:0}const gi={"none:58":`addps`,"66:58":`addpd`,"f3:58":`addss`,"f2:58":`addsd`,"none:59":`mulps`,"66:59":`mulpd`,"f3:59":`mulss`,"f2:59":`mulsd`,"none:5c":`subps`,"66:5c":`subpd`,"f3:5c":`subss`,"f2:5c":`subsd`,"none:5e":`divps`,"66:5e":`divpd`,"f3:5e":`divss`,"f2:5e":`divsd`,"none:28":`movaps`,"66:28":`movapd`,"none:10":`movups`,"66:10":`movupd`,"66:74":`pcmpeqb`,"66:75":`pcmpeqw`,"66:76":`pcmpeqd`,"66:db":`pand`,"66:df":`pandn`,"66:eb":`por`,"66:ef":`pxor`},_i={"none:58":`vaddps`,"66:58":`vaddpd`,"f3:58":`vaddss`,"f2:58":`vaddsd`,"none:59":`vmulps`,"66:59":`vmulpd`,"f3:59":`vmulss`,"f2:59":`vmulsd`,"none:5c":`vsubps`,"66:5c":`vsubpd`,"f3:5c":`vsubss`,"f2:5c":`vsubsd`,"none:5e":`vdivps`,"66:5e":`vdivpd`,"f3:5e":`vdivss`,"f2:5e":`vdivsd`,"none:28":`vmovaps`,"66:28":`vmovapd`,"none:10":`vmovups`,"66:10":`vmovupd`,"66:74":`vpcmpeqb`,"66:75":`vpcmpeqw`,"66:76":`vpcmpeqd`,"66:db":`vpand`,"66:df":`vpandn`,"66:eb":`vpor`,"66:ef":`vpxor`},vi={"66:40":`vpmulld`,"66:dc":`vaesenc`,"66:dd":`vaesenclast`,"66:de":`vaesdec`,"66:df":`vaesdeclast`,"66:f6":`vpsadbw`,"66:5a":`vbroadcasti128`},yi={"none:58":`vaddps`,"66:58":`vaddpd`,"f3:58":`vaddss`,"f2:58":`vaddsd`,"none:59":`vmulps`,"66:59":`vmulpd`,"none:5c":`vsubps`,"66:5c":`vsubpd`,"none:5e":`vdivps`,"66:5e":`vdivpd`,"none:28":`vmovaps`,"66:28":`vmovapd`,"none:10":`vmovups`,"66:10":`vmovupd`},bi={"66:25":`vpternlogd`,"66:40":`vpmulld`,"66:58":`vpbroadcastd`,"66:59":`vpbroadcastq`,"66:7c":`vpbroadcastd`,"66:7e":`vpbroadcastq`,"66:dc":`vaesenc`,"66:dd":`vaesenclast`,"66:de":`vaesdec`,"66:df":`vaesdeclast`};function $(e,t){return(t===`64`?Zr:Xr)[e]??`r${e}`}const xi=[`arm64`,`aarch64`,`x86`,`x64`,`riscv32`,`riscv64`,`mips`,`mips32`,`mipsel`];function Si(e){switch(e){case`arm64`:case`aarch64`:return`arm64`;case`x86`:return`x86`;case`x64`:return`x64`;case`riscv32`:case`riscv64`:return`riscv`;case`mips`:case`mips32`:return`mips`;case`mipsel`:return`mipsel`}}function Ci(e,t,n=0n){switch(Si(e)){case`arm64`:return fr(Pr(t,`little`),n);case`x86`:return Qr(t,n,`x86`);case`x64`:return Qr(t,n,`x64`);case`riscv`:return qr(Pr(t,`little`),n);case`mips`:return Vr(Pr(t,`big`),n);case`mipsel`:return Vr(Pr(t,`little`),n)}}const wi=new Set(xi);var Ti=class{sessions;constructor(e){this.sessions=e??new cr}handleCapabilities(e){return d(async()=>({backend:`self-built-arm64`,available:!0,external_dependencies:[],features:`load-elf-so.elf-relocations.init-array-constructors.pt-dynamic-symbols.auto-wire-bionic-libc.bionic-stdio-vfs.android-syscalls.getrandom.system-register-read.memory-barriers.exclusive-load-store.simd-fp-load-store.simd-ld1-st1-multi.aes-crypto.sha1-crypto.sha256-crypto.pmull-ghash.scalar-fp.neon-integer-simd.call-exported-symbol.call-jni-export.null-indirect-call-detection.jni-object-array-iteration.java-mock-callback.java-mock-field.apk-arm64-extract.instruction-trace`.split(`.`),isa:`aarch64-integer+neon+crypto+fp`,activeSessions:this.sessions.count(),note:'In-process AArch64 interpreter: integer ISA (incl. DMB/DSB/ISB barriers as no-ops) + SIMD/FP load-store incl. contiguous LD1/ST1 of multiple registers + AES/SHA/PMULL crypto-extension (bit-exact vs FIPS-197/180-4/180-1) + scalar IEEE-754 floating-point (FADD/FMUL/FDIV/FSQRT/FCVT/FCMP/FCSEL, float32 via fround) + NEON integer-lane SIMD (three-same ADD/SUB/MUL/logical/compare/min-max, two-register-misc, DUP, MOVI/MVNI, shift-by-immediate, across-lanes reductions, ZIP/UZP/TRN, EXT, TBL/TBX). On load, DT_INIT + DT_INIT_ARRAY constructors run after relocation (like a real linker), so a `.so` with C++ static constructors initializes its globals before its API is called; a constructor that hits a NULL indirect call is tolerated (logged, load continues). A BR/BLR through a register holding 0 (a call/jump via an uninitialised function pointer — a real-hardware SIGSEGV) throws "NULL indirect call" from call_symbol/call_jni_export rather than silently halting as a fake return, so a failed emulation surfaces honestly instead of masquerading as success. Not yet emulated: the de-interleaving LD2/LD3/LD4 structures and the long/widening + saturating NEON variants (e.g. SQADD, SADDL); a `.so` relying on those hits an unsupported opcode (reported with the raw opcode). libapp.so (Flutter Dart AOT) is not executable here.'}))}handleCreateSession(e){return d(async()=>{let t=u(e,`installSyscalls`,!0),n=this.sessions.createSession(t?{}:{syscalls:!1});return{sessionId:n.id,createdAt:n.createdAt,activeSessions:this.sessions.count()}})}handleDestroySession(e){return d(async()=>{let t=i(e,`sessionId`);return{sessionId:t,destroyed:this.sessions.destroySession(t),activeSessions:this.sessions.count()}})}handleListSessions(e){return d(async()=>({sessions:this.sessions.listSessions(),count:this.sessions.count()}))}handleLoadLibrary(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`soPath`),r=await f(n),{entry:a}=t.emulator.loadLibrary(Ei(r));return{sessionId:t.id,soPath:n,entry:a,symbols:t.emulator.engine.exportedSymbolNames()}})}handleExtractApkLibs(e){return d(async()=>{let t=i(e,`apkPath`),n=await ur(t);return{apkPath:t,abi:`arm64-v8a`,libs:n.map(e=>({name:e.name,bytes:e.bytes.length})),count:n.length}})}handleLoadApkLibrary(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`apkPath`),r=i(e,`libName`),a=await ur(n),o=a.find(e=>e.name===r);if(!o)throw Error(`Library "${r}" not found in ${n} (available: ${a.map(e=>e.name).join(`, `)||`none`})`);let{entry:s}=t.emulator.loadLibrary(o.bytes);return{sessionId:t.id,apkPath:n,libName:r,entry:s,symbols:t.emulator.engine.exportedSymbolNames()}})}handleListSymbols(e){return d(async()=>{let t=this.requireSession(e),n=t.emulator.engine.exportedSymbolNames();return{sessionId:t.id,symbols:n,count:n.length}})}handleCallSymbol(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`symbol`),r=a(e,`args`),o=t.emulator.call(n,r);return{sessionId:t.id,symbol:n,result:o}})}handleCallJniExport(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`symbol`),r=a(e,`javaArgs`),o=c(e,`thiz`,0),s=t.emulator.callJniExport(n,r,o);return{sessionId:t.id,symbol:n,result:s}})}handleSetupJavaMock(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`className`),r=i(e,`methodName`),a=i(e,`signature`),o=ji(e);return t.emulator.setupJava(n,r,a,o.fn),{sessionId:t.id,className:n,methodName:r,signature:a,returns:o.kind}})}handleSetupJavaField(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`className`),r=i(e,`fieldName`),a=i(e,`signature`),o=Mi(t,e);return t.emulator.setupJavaField(n,r,a,o.value),{sessionId:t.id,className:n,fieldName:r,signature:a,kind:o.kind}})}handleNewByteArray(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`dataBase64`),r=Ei(Buffer.from(n,`base64`)),a=t.emulator.newByteArray(r);return{sessionId:t.id,handle:a,length:r.length}})}handleReadByteArray(e){return d(async()=>{let t=this.requireSession(e),n=c(e,`handle`);if(n===void 0)throw Error(`Missing required number argument: "handle"`);let r=t.emulator.bytesOf(n);if(!r)throw Error(`Handle ${n} does not resolve to a byte array`);return{sessionId:t.id,handle:n,dataBase64:Buffer.from(r).toString(`base64`),length:r.length}})}handleTrace(e){return d(async()=>{let t=this.requireSession(e),n=i(e,`symbol`),r=a(e,`args`),o=l(e,`captureRegisters`),s=Math.min(c(e,`maxSteps`,1e3),1e5),u=[],d=!1,f=t.emulator.engine.addInstructionHook(e=>{if(u.length>=s){d=!0;return}u.push(Ai(e,o))});try{let e=t.emulator.call(n,r);return{sessionId:t.id,symbol:n,result:e,steps:u.length,truncated:d,trace:u}}finally{f()}})}handleDisassemble(e){return d(async()=>{let t=o(e,`architecture`,wi,`arm64`),n=Di(e.opcode),r=Oi(s(e,`pc`,`0x0`)),i=Ci(t,n,r);return{architecture:t,normalizedArchitecture:Si(t),opcode:ki(n),pc:`0x${r.toString(16)}`,asm:i}})}dispose(){this.sessions.dispose()}requireSession(e){return this.sessions.requireSession(i(e,`sessionId`))}};function Ei(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Di(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<0)throw Error(`opcode number must be a finite unsigned integer`);return Math.trunc(e)>>>0}if(typeof e!=`string`)throw Error(`Missing required opcode argument`);let t=e.trim();if(!t)throw Error(`opcode must not be empty`);if(/^(?:0x)?[0-9a-f]+$/i.test(t)&&t.replace(/^0x/i,``).length>2)return Number.parseInt(t.replace(/^0x/i,``),16)>>>0;let n=t.replace(/,/g,` `).split(/\s+/).filter(Boolean).map(e=>{let t=e.replace(/^0x/i,``);if(!/^[0-9a-f]{1,2}$/i.test(t))throw Error(`Invalid opcode byte: ${e}`);return Number.parseInt(t,16)});if(n.length===0)throw Error(`opcode must include at least one byte`);return n}function Oi(e){let t=e.trim();if(!t)return 0n;if(/^0x[0-9a-f]+$/i.test(t)||/^\d+$/.test(t))return BigInt(t);throw Error(`Invalid pc: ${e}`)}function ki(e){return typeof e==`number`?`0x${e.toString(16)}`:Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Ai(e,t){let n={step:e.step,pc:`0x${e.pc.toString(16)}`,insn:`0x${e.insn.toString(16).padStart(8,`0`)}`,asm:Ci(`arm64`,e.insn,BigInt(e.pc))};if(t.length>0){let r={};for(let n of t)r[n]=e.reg(n);n.registers=r}return n}function ji(e){let t=c(e,`returnInt`),n=s(e,`returnString`),r=s(e,`returnBytes`);if(t!==void 0)return{kind:`int`,fn:()=>BigInt(Math.trunc(t))};if(n!==void 0)return{kind:`string`,fn:e=>BigInt(e.jni.allocHandle({kind:`string`,value:n}))};if(r!==void 0){let e=Ei(Buffer.from(r,`base64`));return{kind:`bytes`,fn:t=>BigInt(t.jni.allocHandle({kind:`bytes`,value:e}))}}return{kind:`void`,fn:()=>void 0}}function Mi(e,t){let n=c(t,`valueInt`),r=s(t,`valueString`),i=s(t,`valueBytes`);if(n!==void 0)return{kind:`int`,value:BigInt(Math.trunc(n))};if(r!==void 0){let t=e.emulator.jni.allocHandle({kind:`string`,value:r});return{kind:`string`,value:BigInt(t)}}if(i!==void 0){let t=Ei(Buffer.from(i,`base64`)),n=e.emulator.newByteArray(t);return{kind:`bytes`,value:BigInt(n)}}return{kind:`int`,value:0n}}export{Ti as NativeEmulatorHandlers};
@@ -1,4 +1,4 @@
1
- import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i}from"./PageController-D9jVkH0i.mjs";import"./definitions-BGwNSkVm.mjs";const a={bypassDebuggerStatement:`(function () {
1
+ import{d as e,u as t}from"./ensure-browser-core-JHwDo5ql.mjs";import{r as n,s as r,t as i}from"./parse-args-ngRrvF9e.mjs";import{n as a}from"./ResponseBuilder-nPXl_khE.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)) {
@@ -486,7 +486,7 @@ import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i
486
486
  globalObj.Error = PatchedError;
487
487
  } catch (_) {}
488
488
  }
489
- })();`},o={bypassConsoleDetect:`(function () {
489
+ })();`},s={bypassConsoleDetect:`(function () {
490
490
  var globalObj = typeof window !== 'undefined' ? window : globalThis;
491
491
  var installFlag = '__ANTI_DEBUG_CONSOLE_INSTALLED__';
492
492
  if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
@@ -672,7 +672,7 @@ import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i
672
672
  } catch (_) {}
673
673
  }
674
674
  }
675
- })();`},s={detectProtections:`(async function () {
675
+ })();`},c={detectProtections:`(async function () {
676
676
  function pushUnique(list, value) {
677
677
  if (list.indexOf(value) === -1) {
678
678
  list.push(value);
@@ -827,4 +827,4 @@ import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i
827
827
  sourceBytesApprox: sourceBlob.length
828
828
  }
829
829
  };
830
- })();`},c={...a,...o,...s};var l=class a{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}toTextResponse(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}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 a.DEFAULT_DEBUGGER_MODE}mergeStackFilterPatterns(e){let t=[...a.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(c.bypassDebuggerStatement,{__ANTI_DEBUG_MODE__:JSON.stringify(e)})}buildTimingBypassScript(e){return this.buildScript(c.bypassTiming,{__ANTI_DEBUG_MAX_DRIFT__:String(e)})}buildStackTraceBypassScript(e){return this.buildScript(c.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){try{let t=n(e,`persistent`,!0),r=await this.getPage(),i=[this.buildDebuggerBypassScript(a.DEFAULT_DEBUGGER_MODE),this.buildTimingBypassScript(a.DEFAULT_MAX_DRIFT),this.buildStackTraceBypassScript(this.mergeStackFilterPatterns([])),c.bypassConsoleDetect];return await this.injectScripts(r,i,t),this.toTextResponse({success:!0,tool:`antidebug_bypass_all`,persistent:t,injectedCount:i.length,injected:[`bypassDebuggerStatement`,`bypassTiming`,`bypassStackTrace`,`bypassConsoleDetect`]})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_bypass_all`,error:e instanceof Error?e.message:String(e)})}}async handleAntiDebugBypassDebuggerStatement(e){try{let t=this.parseDebuggerMode(e.mode),n=await this.getPage(),r=this.buildDebuggerBypassScript(t);return await this.injectScripts(n,[r],!0),this.toTextResponse({success:!0,tool:`antidebug_bypass_debugger_statement`,mode:t,persistent:!0})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_bypass_debugger_statement`,error:e instanceof Error?e.message:String(e)})}}async handleAntiDebugBypassTiming(e){try{let n=t(e,`maxDrift`,a.DEFAULT_MAX_DRIFT)??a.DEFAULT_MAX_DRIFT,r=await this.getPage(),i=this.buildTimingBypassScript(n);return await this.injectScripts(r,[i],!0),this.toTextResponse({success:!0,tool:`antidebug_bypass_timing`,maxDrift:n,persistent:!0})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_bypass_timing`,error:e instanceof Error?e.message:String(e)})}}async handleAntiDebugBypassStackTrace(t){try{let n=e(t,`filterPatterns`),r=this.mergeStackFilterPatterns(n),i=await this.getPage(),a=this.buildStackTraceBypassScript(r);return await this.injectScripts(i,[a],!0),this.toTextResponse({success:!0,tool:`antidebug_bypass_stack_trace`,filterPatterns:r,persistent:!0})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_bypass_stack_trace`,error:e instanceof Error?e.message:String(e)})}}async handleAntiDebugBypassConsoleDetect(e){try{let e=await this.getPage();return await this.injectScripts(e,[c.bypassConsoleDetect],!0),this.toTextResponse({success:!0,tool:`antidebug_bypass_console_detect`,persistent:!0})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_bypass_console_detect`,error:e instanceof Error?e.message:String(e)})}}async handleAntiDebugDetectProtections(e){try{let e=await i(await this.getPage(),c.detectProtections);return this.toTextResponse({success:e?.success??!0,tool:`antidebug_detect_protections`,detected:e?.detected??!1,count:e?.count??0,protections:e?.protections??[],recommendations:e?.recommendations??[],evidence:e?.evidence??{}})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_detect_protections`,error:e instanceof Error?e.message:String(e)})}}async handleAntidebugBypass(r){let i=r.types,o=Array.isArray(i)?i:[`all`],s=o.length===0?[`all`]:o;if(s.includes(`all`))return this.handleAntiDebugBypassAll(r);let l=n(r,`persistent`,!0),u=this.parseDebuggerMode(r.mode),d=t(r,`maxDrift`,a.DEFAULT_MAX_DRIFT)??a.DEFAULT_MAX_DRIFT,f=e(r,`filterPatterns`),p=[];try{let e=await this.getPage();if(s.includes(`debugger_statement`)){let t=this.buildDebuggerBypassScript(u);await this.injectScripts(e,[t],l),p.push(`debugger_statement`)}if(s.includes(`timing`)){let t=this.buildTimingBypassScript(d);await this.injectScripts(e,[t],l),p.push(`timing`)}if(s.includes(`stack_trace`)){let t=this.mergeStackFilterPatterns(f),n=this.buildStackTraceBypassScript(t);await this.injectScripts(e,[n],l),p.push(`stack_trace`)}return s.includes(`console_detect`)&&(await this.injectScripts(e,[c.bypassConsoleDetect],l),p.push(`console_detect`)),this.toTextResponse({success:!0,tool:`antidebug_bypass`,applied:p,persistent:l})}catch(e){return this.toTextResponse({success:!1,tool:`antidebug_bypass`,error:e instanceof Error?e.message:String(e)})}}};export{l 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};
@@ -1,4 +1,4 @@
1
- import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-B5xQuEa_.mjs";import{t as n}from"./PrerequisiteError-Bl3dK8XA.mjs";import{t as r}from"./TraceRecorder-Dd8jLXpi.mjs";import{n as i}from"./parse-args-Cuk7-xUt.mjs";import{t as a}from"./ResponseBuilder-B2lu4KEl.mjs";import{readFile as o,writeFile as s}from"node:fs/promises";const c=(e,t)=>typeof e==`boolean`?e:t,l=(e,t)=>{let n=typeof e==`number`&&Number.isFinite(e)?e:t.defaultValue;return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n},u=(e,t)=>{let n={};for(let r=0;r<e.length;r++)n[e[r]]=t[r];return n},d=e=>{try{return JSON.parse(e)}catch{return e}},f=e=>({timestamp:e.timestamp,wallTime:e.wallTime??null,monotonicTime:e.monotonicTime??null,category:e.category,eventType:e.eventType,data:typeof e.data==`string`?d(e.data):e.data,scriptId:e.scriptId,lineNumber:e.lineNumber,requestId:e.requestId??null,sequence:e.sequence??null}),p=e=>({requestId:e.requestId,url:e.url,method:e.method,resourceType:e.resourceType,requestHeaders:d(e.requestHeaders),requestPostDataPresent:e.requestPostData!==null,status:e.status,statusText:e.statusText,responseHeaders:d(e.responseHeaders),mimeType:e.mimeType,protocol:e.protocol,remoteAddress:e.remoteAddress,fromDiskCache:e.fromDiskCache,fromServiceWorker:e.fromServiceWorker,startedWallTime:e.startedWallTime,responseWallTime:e.responseWallTime,finishedWallTime:e.finishedWallTime,startedMonotonicTime:e.startedMonotonicTime,responseMonotonicTime:e.responseMonotonicTime,finishedMonotonicTime:e.finishedMonotonicTime,encodedDataLength:e.encodedDataLength,receivedDataLength:e.receivedDataLength,receivedEncodedDataLength:e.receivedEncodedDataLength,chunkCount:e.chunkCount,streamingEnabled:e.streamingEnabled,streamingSupported:e.streamingSupported,streamingError:e.streamingError,bodyCaptureState:e.bodyCaptureState,bodySize:e.bodySize,bodyBase64Encoded:e.bodyBase64Encoded,bodyTruncated:e.bodyTruncated,bodyArtifactPath:e.bodyArtifactPath,bodyError:e.bodyError,failed:e.failed,errorText:e.errorText}),m=e=>({sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonicTime,dataLength:e.dataLength,encodedDataLength:e.encodedDataLength,hasChunkData:e.chunkData!==null,chunkPreview:e.chunkData===null?null:`${e.chunkData.slice(0,120)}${e.chunkData.length>120?`...`:``}`,chunkIsBase64:e.chunkIsBase64}),h=async(e,t)=>{if(e.bodyCaptureState===`none`&&e.bodyInline===null&&e.bodyArtifactPath===null)return null;let n=await y(e);if(n===null)return{state:e.bodyCaptureState,error:e.bodyError??`Body content is not available`,truncated:e.bodyTruncated};let r=e.bodySize??n.length;return t.returnSummary||r>t.maxBodyBytes?{state:e.bodyCaptureState,summary:{size:r,sizeKB:(r/1024).toFixed(2),base64Encoded:e.bodyBase64Encoded,preview:`${n.slice(0,500)}${n.length>500?`...`:``}`,truncated:e.bodyTruncated||r>t.maxBodyBytes,reason:t.returnSummary?`Summary mode enabled`:`Response too large (${(r/1024).toFixed(2)} KB > ${(t.maxBodyBytes/1024).toFixed(2)} KB)`}}:{state:e.bodyCaptureState,body:n,base64Encoded:e.bodyBase64Encoded,size:r,sizeKB:(r/1024).toFixed(2),truncated:e.bodyTruncated,...e.bodyError?{warning:e.bodyError}:{}}},g=(e,t,n,r)=>e.query(`
1
+ import{i as e}from"./artifacts-D-4pSS_N.mjs";import{t}from"./ToolError-g3rjWzhx.mjs";import{v as n}from"./ensure-browser-core-JHwDo5ql.mjs";import{t as r}from"./TraceRecorder-B5ktv3nP.mjs";import{n as i}from"./parse-args-ngRrvF9e.mjs";import{t as a}from"./ResponseBuilder-nPXl_khE.mjs";import{readFile as o,writeFile as s}from"node:fs/promises";const c=(e,t)=>typeof e==`boolean`?e:t,l=(e,t)=>{let n=typeof e==`number`&&Number.isFinite(e)?e:t.defaultValue;return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n},u=(e,t)=>{let n={};for(let r=0;r<e.length;r++)n[e[r]]=t[r];return n},d=e=>{try{return JSON.parse(e)}catch{return e}},f=e=>({timestamp:e.timestamp,wallTime:e.wallTime??null,monotonicTime:e.monotonicTime??null,category:e.category,eventType:e.eventType,data:typeof e.data==`string`?d(e.data):e.data,scriptId:e.scriptId,lineNumber:e.lineNumber,requestId:e.requestId??null,sequence:e.sequence??null}),p=e=>({requestId:e.requestId,url:e.url,method:e.method,resourceType:e.resourceType,requestHeaders:d(e.requestHeaders),requestPostDataPresent:e.requestPostData!==null,status:e.status,statusText:e.statusText,responseHeaders:d(e.responseHeaders),mimeType:e.mimeType,protocol:e.protocol,remoteAddress:e.remoteAddress,fromDiskCache:e.fromDiskCache,fromServiceWorker:e.fromServiceWorker,startedWallTime:e.startedWallTime,responseWallTime:e.responseWallTime,finishedWallTime:e.finishedWallTime,startedMonotonicTime:e.startedMonotonicTime,responseMonotonicTime:e.responseMonotonicTime,finishedMonotonicTime:e.finishedMonotonicTime,encodedDataLength:e.encodedDataLength,receivedDataLength:e.receivedDataLength,receivedEncodedDataLength:e.receivedEncodedDataLength,chunkCount:e.chunkCount,streamingEnabled:e.streamingEnabled,streamingSupported:e.streamingSupported,streamingError:e.streamingError,bodyCaptureState:e.bodyCaptureState,bodySize:e.bodySize,bodyBase64Encoded:e.bodyBase64Encoded,bodyTruncated:e.bodyTruncated,bodyArtifactPath:e.bodyArtifactPath,bodyError:e.bodyError,failed:e.failed,errorText:e.errorText}),m=e=>({sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonicTime,dataLength:e.dataLength,encodedDataLength:e.encodedDataLength,hasChunkData:e.chunkData!==null,chunkPreview:e.chunkData===null?null:`${e.chunkData.slice(0,120)}${e.chunkData.length>120?`...`:``}`,chunkIsBase64:e.chunkIsBase64}),h=async(e,t)=>{if(e.bodyCaptureState===`none`&&e.bodyInline===null&&e.bodyArtifactPath===null)return null;let n=await y(e);if(n===null)return{state:e.bodyCaptureState,error:e.bodyError??`Body content is not available`,truncated:e.bodyTruncated};let r=e.bodySize??n.length;return t.returnSummary||r>t.maxBodyBytes?{state:e.bodyCaptureState,summary:{size:r,sizeKB:(r/1024).toFixed(2),base64Encoded:e.bodyBase64Encoded,preview:`${n.slice(0,500)}${n.length>500?`...`:``}`,truncated:e.bodyTruncated||r>t.maxBodyBytes,reason:t.returnSummary?`Summary mode enabled`:`Response too large (${(r/1024).toFixed(2)} KB > ${(t.maxBodyBytes/1024).toFixed(2)} KB)`}}:{state:e.bodyCaptureState,body:n,base64Encoded:e.bodyBase64Encoded,size:r,sizeKB:(r/1024).toFixed(2),truncated:e.bodyTruncated,...e.bodyError?{warning:e.bodyError}:{}}},g=(e,t,n,r)=>e.query(`
2
2
  SELECT
3
3
  timestamp,
4
4
  category,
@@ -13,7 +13,7 @@ import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-B5xQ
13
13
  FROM events
14
14
  WHERE ${t} >= ${n} AND ${t} <= ${r}
15
15
  ORDER BY ${t} ASC, sequence ASC
16
- `).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:e[3],scriptId:e[4]??null,lineNumber:e[5]??null,wallTime:e[6]??null,monotonicTime:e[7]??null,requestId:e[8]??null,sequence:e[9]??null})),_=(e,t)=>{let n=e.detailedData;return n?n.smartHandle(t,25600):t},v=(e,t)=>{if(t)return new r({dbPath:t});let n=e.getDB();if(!n)throw Error(`GRACEFUL: No active recording and no dbPath specified. Start a recording or provide a dbPath.`);return n.flush(),n},y=async e=>typeof e.bodyInline==`string`?e.bodyInline:e.bodyArtifactPath?o(e.bodyArtifactPath,`utf8`):null;function b(e,t=`balanced`){if(e.length===0)return{detail:t,totalEvents:0,timeRange:{start:0,end:0,durationMs:0},categories:[],keyMoments:t===`compact`?void 0:[]};let n=e.map(e=>e.timestamp),r=Math.min(...n),i=Math.max(...n),a=new Map;for(let t of e){let e=a.get(t.category);e||(e={count:0,first:t.timestamp,last:t.timestamp,types:new Map},a.set(t.category,e)),e.count++,e.first=Math.min(e.first,t.timestamp),e.last=Math.max(e.last,t.timestamp),e.types.set(t.eventType,(e.types.get(t.eventType)??0)+1)}let o=[...a.entries()].toSorted((e,t)=>t[1].count-e[1].count).map(([e,t])=>({category:e,count:t.count,firstTimestamp:t.first,lastTimestamp:t.last,topEventTypes:[...t.types.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({type:e,count:t}))})),s={detail:t,totalEvents:e.length,timeRange:{start:r,end:i,durationMs:i-r},categories:o};return(t===`balanced`||t===`full`)&&(s.keyMoments=x(e)),s}function x(e){let t=[];for(let n of e)n.eventType===`Debugger.paused`?t.push({timestamp:n.timestamp,type:`breakpoint`,description:`Debugger paused${n.scriptId?` at script ${n.scriptId}`:``}${n.lineNumber?`:${n.lineNumber}`:``}`,data:n.data}):n.eventType===`Network.loadingFinished`?t.push({timestamp:n.timestamp,type:`network_complete`,description:`Network request completed`,data:n.data}):n.eventType===`Runtime.exceptionThrown`?t.push({timestamp:n.timestamp,type:`exception`,description:`Runtime exception thrown`,data:n.data}):(n.eventType===`Page.frameNavigated`||n.eventType===`Page.navigatedWithinDocument`)&&t.push({timestamp:n.timestamp,type:`navigation`,description:`Page navigation`,data:n.data});return t}function S(e){if(e.length===0)return{totalDeltas:0,uniqueAddresses:0,anomalies:[],topAddresses:[]};let t=new Map;for(let n of e)t.set(n.address,(t.get(n.address)??0)+1);let n=t.size,r=e.length,i=r/n,a=[...t.entries()].toSorted((e,t)=>t[1]-e[1]),o=a.slice(0,10).map(([e,t])=>({address:e,writeCount:t})),s=i*3;return{totalDeltas:r,uniqueAddresses:n,anomalies:a.filter(([,e])=>e>s).map(([e,t])=>({address:e,writeCount:t,description:`${t} writes (${(t/i).toFixed(1)}× average)`})),topAddresses:o}}var C=class{recorder;ctx;constructor(e,t){this.recorder=e,this.ctx=t}async handleTraceRecording(e){return i(e,`action`,new Set([`start`,`stop`]))===`stop`?this.handleStopTraceRecording():this.handleStartTraceRecording(e)}async handleStartTraceRecording(e){let t=e.cdpDomains,r=e.recordMemoryDeltas,i=e.recordResponseBodies,o=e.streamResponseChunks,s=e.networkBodyMaxBytes,c=e.networkInlineBodyBytes,l=this.ctx.eventBus;if(!l)throw new n(`EventBus not available on server context`);let u=null;try{if(this.ctx.collector){let e=await this.ctx.collector.getActivePage();typeof e.createCDPSession==`function`&&(u=await e.createCDPSession())}}catch{}let d=await this.recorder.start(l,u,{cdpDomains:t,recordMemoryDeltas:r??!0,ownsSession:u!==null,network:{recordResponseBodies:i,streamResponseChunks:o,maxBodyBytes:s,inlineBodyBytes:c}});return a.ok().merge({status:`recording`,sessionId:d.sessionId,dbPath:d.dbPath,network:{recordResponseBodies:i??!0,streamResponseChunks:o??!0,maxBodyBytes:s??10*1024*1024,inlineBodyBytes:c??256*1024},message:`Recording started. CDP session: ${u?`active`:`not available`}`}).json()}async handleStopTraceRecording(){let e=await this.recorder.stop(),t=e.stoppedAt?e.stoppedAt-e.startedAt:0,n=e.cleanupErrors??[],r=n.length>0?`stopped_with_errors`:`stopped`;return a.ok().merge({status:r,sessionId:e.sessionId,dbPath:e.dbPath,eventCount:e.eventCount,memoryDeltaCount:e.memoryDeltaCount,heapSnapshotCount:e.heapSnapshotCount,networkRequestCount:e.networkRequestCount??0,networkChunkCount:e.networkChunkCount??0,networkBodyCount:e.networkBodyCount??0,durationMs:t,...n.length>0?{cleanupErrors:n}:{},message:n.length>0?`Recording stopped with cleanup errors. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`:`Recording stopped. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`}).json()}async handleQueryTraceSql(t){let i=t.sql,o=t.dbPath;if(!i)throw new e(`VALIDATION`,`sql parameter is required`);let s,c=null;try{if(o)c=new r({dbPath:o}),s=c.query(i);else{let e=this.recorder.getDB();if(!e)throw new n(`No active recording and no dbPath specified. Start a recording or provide a dbPath.`);e.flush(),s=e.query(i)}return a.ok().merge({columns:s.columns,rows:s.rows,rowCount:s.rowCount}).json()}finally{c&&c.close()}}async handleSeekToTimestamp(t){let n=t.timestamp,r=t.dbPath,i=t.windowMs??100,o=t.timeDomain??`wall`;if(!n)throw new e(`VALIDATION`,`timestamp parameter is required`);let s=null;try{let e=v(this.recorder,r);r&&(s=e);let t=o===`monotonic`?`COALESCE(monotonic_time, timestamp)`:`timestamp`,c=o===`monotonic`?`COALESCE(finished_monotonic_time, response_monotonic_time, started_monotonic_time)`:`COALESCE(finished_wall_time, response_wall_time, started_wall_time)`,l=o===`wall`?e.getEventsByTimeRange(n-i,n+i):g(e,t,n-i,n+i),d=e.query(`SELECT * FROM events WHERE category = 'debugger' AND ${t} <= ${n} ORDER BY ${t} DESC, sequence DESC LIMIT 5`),p=o===`wall`?e.query(`SELECT m1.* FROM memory_deltas m1
16
+ `).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:e[3],scriptId:e[4]??null,lineNumber:e[5]??null,wallTime:e[6]??null,monotonicTime:e[7]??null,requestId:e[8]??null,sequence:e[9]??null})),_=(e,t)=>{let n=e.detailedData;return n?n.smartHandle(t,25600):t},v=(e,t)=>{if(t)return new r({dbPath:t});let n=e.getDB();if(!n)throw Error(`GRACEFUL: No active recording and no dbPath specified. Start a recording or provide a dbPath.`);return n.flush(),n},y=async e=>typeof e.bodyInline==`string`?e.bodyInline:e.bodyArtifactPath?o(e.bodyArtifactPath,`utf8`):null;function b(e,t=`balanced`){if(e.length===0)return{detail:t,totalEvents:0,timeRange:{start:0,end:0,durationMs:0},categories:[],keyMoments:t===`compact`?void 0:[]};let n=e.map(e=>e.timestamp),r=Math.min(...n),i=Math.max(...n),a=new Map;for(let t of e){let e=a.get(t.category);e||(e={count:0,first:t.timestamp,last:t.timestamp,types:new Map},a.set(t.category,e)),e.count++,e.first=Math.min(e.first,t.timestamp),e.last=Math.max(e.last,t.timestamp),e.types.set(t.eventType,(e.types.get(t.eventType)??0)+1)}let o=[...a.entries()].toSorted((e,t)=>t[1].count-e[1].count).map(([e,t])=>({category:e,count:t.count,firstTimestamp:t.first,lastTimestamp:t.last,topEventTypes:[...t.types.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({type:e,count:t}))})),s={detail:t,totalEvents:e.length,timeRange:{start:r,end:i,durationMs:i-r},categories:o};return(t===`balanced`||t===`full`)&&(s.keyMoments=x(e)),s}function x(e){let t=[];for(let n of e)n.eventType===`Debugger.paused`?t.push({timestamp:n.timestamp,type:`breakpoint`,description:`Debugger paused${n.scriptId?` at script ${n.scriptId}`:``}${n.lineNumber?`:${n.lineNumber}`:``}`,data:n.data}):n.eventType===`Network.loadingFinished`?t.push({timestamp:n.timestamp,type:`network_complete`,description:`Network request completed`,data:n.data}):n.eventType===`Runtime.exceptionThrown`?t.push({timestamp:n.timestamp,type:`exception`,description:`Runtime exception thrown`,data:n.data}):(n.eventType===`Page.frameNavigated`||n.eventType===`Page.navigatedWithinDocument`)&&t.push({timestamp:n.timestamp,type:`navigation`,description:`Page navigation`,data:n.data});return t}function S(e){if(e.length===0)return{totalDeltas:0,uniqueAddresses:0,anomalies:[],topAddresses:[]};let t=new Map;for(let n of e)t.set(n.address,(t.get(n.address)??0)+1);let n=t.size,r=e.length,i=r/n,a=[...t.entries()].toSorted((e,t)=>t[1]-e[1]),o=a.slice(0,10).map(([e,t])=>({address:e,writeCount:t})),s=i*3;return{totalDeltas:r,uniqueAddresses:n,anomalies:a.filter(([,e])=>e>s).map(([e,t])=>({address:e,writeCount:t,description:`${t} writes (${(t/i).toFixed(1)}× average)`})),topAddresses:o}}var C=class{recorder;ctx;constructor(e,t){this.recorder=e,this.ctx=t}async handleTraceRecording(e){return i(e,`action`,new Set([`start`,`stop`]))===`stop`?this.handleStopTraceRecording():this.handleStartTraceRecording(e)}async handleStartTraceRecording(e){let t=e.cdpDomains,r=e.recordMemoryDeltas,i=e.recordResponseBodies,o=e.streamResponseChunks,s=e.networkBodyMaxBytes,c=e.networkInlineBodyBytes,l=this.ctx.eventBus;if(!l)throw new n(`EventBus not available on server context`);let u=null;try{if(this.ctx.collector){let e=await this.ctx.collector.getActivePage();typeof e.createCDPSession==`function`&&(u=await e.createCDPSession())}}catch{}let d=await this.recorder.start(l,u,{cdpDomains:t,recordMemoryDeltas:r??!0,ownsSession:u!==null,network:{recordResponseBodies:i,streamResponseChunks:o,maxBodyBytes:s,inlineBodyBytes:c}});return a.ok().merge({status:`recording`,sessionId:d.sessionId,dbPath:d.dbPath,network:{recordResponseBodies:i??!0,streamResponseChunks:o??!0,maxBodyBytes:s??10*1024*1024,inlineBodyBytes:c??256*1024},message:`Recording started. CDP session: ${u?`active`:`not available`}`}).json()}async handleStopTraceRecording(){let e=await this.recorder.stop(),t=e.stoppedAt?e.stoppedAt-e.startedAt:0,n=e.cleanupErrors??[],r=n.length>0?`stopped_with_errors`:`stopped`;return a.ok().merge({status:r,sessionId:e.sessionId,dbPath:e.dbPath,eventCount:e.eventCount,memoryDeltaCount:e.memoryDeltaCount,heapSnapshotCount:e.heapSnapshotCount,networkRequestCount:e.networkRequestCount??0,networkChunkCount:e.networkChunkCount??0,networkBodyCount:e.networkBodyCount??0,durationMs:t,...n.length>0?{cleanupErrors:n}:{},message:n.length>0?`Recording stopped with cleanup errors. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`:`Recording stopped. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`}).json()}async handleQueryTraceSql(e){let i=e.sql,o=e.dbPath;if(!i)throw new t(`VALIDATION`,`sql parameter is required`);let s,c=null;try{if(o)c=new r({dbPath:o}),s=c.query(i);else{let e=this.recorder.getDB();if(!e)throw new n(`No active recording and no dbPath specified. Start a recording or provide a dbPath.`);e.flush(),s=e.query(i)}return a.ok().merge({columns:s.columns,rows:s.rows,rowCount:s.rowCount}).json()}finally{c&&c.close()}}async handleSeekToTimestamp(e){let n=e.timestamp,r=e.dbPath,i=e.windowMs??100,o=e.timeDomain??`wall`;if(!n)throw new t(`VALIDATION`,`timestamp parameter is required`);let s=null;try{let e=v(this.recorder,r);r&&(s=e);let t=o===`monotonic`?`COALESCE(monotonic_time, timestamp)`:`timestamp`,c=o===`monotonic`?`COALESCE(finished_monotonic_time, response_monotonic_time, started_monotonic_time)`:`COALESCE(finished_wall_time, response_wall_time, started_wall_time)`,l=o===`wall`?e.getEventsByTimeRange(n-i,n+i):g(e,t,n-i,n+i),d=e.query(`SELECT * FROM events WHERE category = 'debugger' AND ${t} <= ${n} ORDER BY ${t} DESC, sequence DESC LIMIT 5`),p=o===`wall`?e.query(`SELECT m1.* FROM memory_deltas m1
17
17
  INNER JOIN (SELECT address, MAX(timestamp) as max_ts FROM memory_deltas WHERE timestamp <= ${n} GROUP BY address) m2
18
18
  ON m1.address = m2.address AND m1.timestamp = m2.max_ts
19
19
  ORDER BY m1.address`):null,m=e.query(`SELECT * FROM network_resources
@@ -24,7 +24,7 @@ import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-B5xQ
24
24
  AND event_type = 'Network.loadingFinished'
25
25
  AND ${t} <= ${n}
26
26
  ORDER BY ${t} DESC
27
- LIMIT 20`));let h=o===`wall`?e.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE timestamp <= ${n} ORDER BY timestamp DESC LIMIT 1`):null;return a.ok().merge({seekTimestamp:n,timeDomain:o,windowMs:i,events:l.map(f),debuggerState:{recentEvents:d.rows.map(e=>u(d.columns,e))},memoryState:{addressValues:p?.rows.map(e=>u(p.columns,e))??[],...o===`monotonic`?{omittedReason:`Memory state is only indexed by wall-clock timestamps and is omitted for monotonic seeks.`}:{}},networkState:{completedRequests:m.rows.map(e=>u(m.columns,e))},nearestHeapSnapshot:h&&h.rows.length>0?u(h.columns,h.rows[0]):null,...o===`monotonic`?{nearestHeapSnapshotOmittedReason:`Heap snapshots are only indexed by wall-clock timestamps and are omitted for monotonic seeks.`}:{}}).json()}finally{s&&s.close()}}async handleGetTraceNetworkFlow(t){let n=typeof t.requestId==`string`?t.requestId:``,r=t.dbPath,i=c(t.includeBody,!0),o=c(t.includeChunks,!0),s=c(t.includeEvents,!0),u=l(t.chunkLimit,{defaultValue:200,min:1,max:5e3,integer:!0}),d=l(t.maxBodyBytes,{defaultValue:1e5,min:1024,max:50*1024*1024,integer:!0}),g=c(t.returnSummary,!1);if(!n)throw new e(`VALIDATION`,`requestId parameter is required`);let y=null;try{let t=v(this.recorder,r);r&&(y=t);let c=t.getNetworkResource(n);if(!c)throw new e(`NOT_FOUND`,`No recorded network flow found for requestId: ${n}`);let l=o?t.getNetworkChunks(n,u):[],b=s?t.getEventsByRequestId(n):[],x=i?await h(c,{maxBodyBytes:d,returnSummary:g}):null,S=_(this.ctx,{requestId:n,request:p(c),body:x,chunks:o?{total:c.chunkCount,returned:l.length,limit:u,hasMore:c.chunkCount>l.length,items:l.map(m)}:null,events:s?b.map(f):null});return a.ok().merge(S).json()}finally{y&&y.close()}}async handleDiffHeapSnapshots(t){let n=t.snapshotId1,r=t.snapshotId2,i=t.dbPath;if(!n||!r)throw new e(`VALIDATION`,`snapshotId1 and snapshotId2 are required`);let o=null;try{let t=v(this.recorder,i);i&&(o=t);let s=t.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${n}`),c=t.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${r}`);if(s.rowCount===0)throw new e(`NOT_FOUND`,`Snapshot with id ${n} not found`);if(c.rowCount===0)throw new e(`NOT_FOUND`,`Snapshot with id ${r} not found`);let l=u(s.columns,s.rows[0]),f=u(c.columns,c.rows[0]),p=d(l.summary),m=d(f.summary),h=p.objectCounts??{},g=m.objectCounts??{},_=new Set([...Object.keys(h),...Object.keys(g)]),y=[],b=[],x=[];for(let e of _){let t=h[e]??0,n=g[e]??0;t===0&&n>0?y.push({name:e,count:n}):t>0&&n===0?b.push({name:e,count:t}):t!==n&&x.push({name:e,countBefore:t,countAfter:n,delta:n-t})}x.sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta));let S=p.totalSize??0,C=m.totalSize??0;return a.ok().merge({snapshot1:{id:l.id,timestamp:l.timestamp,totalSize:S,nodeCount:p.nodeCount??0},snapshot2:{id:f.id,timestamp:f.timestamp,totalSize:C,nodeCount:m.nodeCount??0},diff:{added:y.slice(0,50),removed:b.slice(0,50),changed:x.slice(0,100),totalSizeDelta:C-S,addedCount:y.length,removedCount:b.length,changedCount:x.length}}).json()}finally{o&&o.close()}}async handleExportTrace(e){let n=e.dbPath,r=e.outputPath,i=null;try{let e=v(this.recorder,n);n&&(i=e);let o=e.query(`SELECT timestamp, category, event_type, data, script_id, line_number FROM events ORDER BY timestamp ASC, sequence ASC`),c=new Set([`Debugger.paused`]),l=new Set([`Debugger.resumed`]),u=o.rows.map(e=>{let t=e[0]*1e3,n=e[1],r=e[2],i=e[3],a=`i`;return c.has(r)?a=`B`:l.has(r)&&(a=`E`),{name:r,cat:n,ph:a,ts:t,pid:1,tid:1,args:d(i),...a===`i`?{s:`g`}:{}}}),f=r||(await t({category:`traces`,toolName:`trace_export`,ext:`json`})).absolutePath;return await s(f,JSON.stringify(u,null,2),`utf-8`),a.ok().merge({exportedPath:f,eventCount:u.length,format:`Chrome Trace Event JSON`,message:`Exported ${u.length} events to ${f}. Open in chrome://tracing or ui.perfetto.dev`}).json()}finally{i&&i.close()}}async handleSummarizeTrace(e){let t=e.detail??`balanced`,i=e.dbPath,o,s=!1;if(i)o=new r({dbPath:i}),s=!0;else if(this.recorder.getState()===`recording`){let e=this.recorder.getDB();if(!e)throw new n(`Active recording has no database`);o=e}else throw new n(`No trace database specified and no active recording`);try{let e=o.query(`SELECT timestamp, category, event_type, data, script_id, line_number, wall_time, monotonic_time, request_id, sequence FROM events ORDER BY timestamp, sequence`).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:typeof e[3]==`string`?d(e[3]):e[3],scriptId:e[4]??void 0,lineNumber:e[5]??void 0})),n=o.query(`SELECT timestamp, address, old_value, new_value, size, value_type FROM memory_deltas ORDER BY timestamp`).rows.map(e=>({timestamp:e[0],address:e[1],oldValue:e[2],newValue:e[3],size:e[4],valueType:e[5]})),r=o.query(`SELECT
27
+ LIMIT 20`));let h=o===`wall`?e.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE timestamp <= ${n} ORDER BY timestamp DESC LIMIT 1`):null;return a.ok().merge({seekTimestamp:n,timeDomain:o,windowMs:i,events:l.map(f),debuggerState:{recentEvents:d.rows.map(e=>u(d.columns,e))},memoryState:{addressValues:p?.rows.map(e=>u(p.columns,e))??[],...o===`monotonic`?{omittedReason:`Memory state is only indexed by wall-clock timestamps and is omitted for monotonic seeks.`}:{}},networkState:{completedRequests:m.rows.map(e=>u(m.columns,e))},nearestHeapSnapshot:h&&h.rows.length>0?u(h.columns,h.rows[0]):null,...o===`monotonic`?{nearestHeapSnapshotOmittedReason:`Heap snapshots are only indexed by wall-clock timestamps and are omitted for monotonic seeks.`}:{}}).json()}finally{s&&s.close()}}async handleGetTraceNetworkFlow(e){let n=typeof e.requestId==`string`?e.requestId:``,r=e.dbPath,i=c(e.includeBody,!0),o=c(e.includeChunks,!0),s=c(e.includeEvents,!0),u=l(e.chunkLimit,{defaultValue:200,min:1,max:5e3,integer:!0}),d=l(e.maxBodyBytes,{defaultValue:1e5,min:1024,max:50*1024*1024,integer:!0}),g=c(e.returnSummary,!1);if(!n)throw new t(`VALIDATION`,`requestId parameter is required`);let y=null;try{let e=v(this.recorder,r);r&&(y=e);let c=e.getNetworkResource(n);if(!c)throw new t(`NOT_FOUND`,`No recorded network flow found for requestId: ${n}`);let l=o?e.getNetworkChunks(n,u):[],b=s?e.getEventsByRequestId(n):[],x=i?await h(c,{maxBodyBytes:d,returnSummary:g}):null,S=_(this.ctx,{requestId:n,request:p(c),body:x,chunks:o?{total:c.chunkCount,returned:l.length,limit:u,hasMore:c.chunkCount>l.length,items:l.map(m)}:null,events:s?b.map(f):null});return a.ok().merge(S).json()}finally{y&&y.close()}}async handleDiffHeapSnapshots(e){let n=e.snapshotId1,r=e.snapshotId2,i=e.dbPath;if(!n||!r)throw new t(`VALIDATION`,`snapshotId1 and snapshotId2 are required`);let o=null;try{let e=v(this.recorder,i);i&&(o=e);let s=e.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${n}`),c=e.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${r}`);if(s.rowCount===0)throw new t(`NOT_FOUND`,`Snapshot with id ${n} not found`);if(c.rowCount===0)throw new t(`NOT_FOUND`,`Snapshot with id ${r} not found`);let l=u(s.columns,s.rows[0]),f=u(c.columns,c.rows[0]),p=d(l.summary),m=d(f.summary),h=p.objectCounts??{},g=m.objectCounts??{},_=new Set([...Object.keys(h),...Object.keys(g)]),y=[],b=[],x=[];for(let e of _){let t=h[e]??0,n=g[e]??0;t===0&&n>0?y.push({name:e,count:n}):t>0&&n===0?b.push({name:e,count:t}):t!==n&&x.push({name:e,countBefore:t,countAfter:n,delta:n-t})}x.sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta));let S=p.totalSize??0,C=m.totalSize??0;return a.ok().merge({snapshot1:{id:l.id,timestamp:l.timestamp,totalSize:S,nodeCount:p.nodeCount??0},snapshot2:{id:f.id,timestamp:f.timestamp,totalSize:C,nodeCount:m.nodeCount??0},diff:{added:y.slice(0,50),removed:b.slice(0,50),changed:x.slice(0,100),totalSizeDelta:C-S,addedCount:y.length,removedCount:b.length,changedCount:x.length}}).json()}finally{o&&o.close()}}async handleExportTrace(t){let n=t.dbPath,r=t.outputPath,i=null;try{let t=v(this.recorder,n);n&&(i=t);let o=t.query(`SELECT timestamp, category, event_type, data, script_id, line_number FROM events ORDER BY timestamp ASC, sequence ASC`),c=new Set([`Debugger.paused`]),l=new Set([`Debugger.resumed`]),u=o.rows.map(e=>{let t=e[0]*1e3,n=e[1],r=e[2],i=e[3],a=`i`;return c.has(r)?a=`B`:l.has(r)&&(a=`E`),{name:r,cat:n,ph:a,ts:t,pid:1,tid:1,args:d(i),...a===`i`?{s:`g`}:{}}}),f=r||(await e({category:`traces`,toolName:`trace_export`,ext:`json`})).absolutePath;return await s(f,JSON.stringify(u,null,2),`utf-8`),a.ok().merge({exportedPath:f,eventCount:u.length,format:`Chrome Trace Event JSON`,message:`Exported ${u.length} events to ${f}. Open in chrome://tracing or ui.perfetto.dev`}).json()}finally{i&&i.close()}}async handleSummarizeTrace(e){let t=e.detail??`balanced`,i=e.dbPath,o,s=!1;if(i)o=new r({dbPath:i}),s=!0;else if(this.recorder.getState()===`recording`){let e=this.recorder.getDB();if(!e)throw new n(`Active recording has no database`);o=e}else throw new n(`No trace database specified and no active recording`);try{let e=o.query(`SELECT timestamp, category, event_type, data, script_id, line_number, wall_time, monotonic_time, request_id, sequence FROM events ORDER BY timestamp, sequence`).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:typeof e[3]==`string`?d(e[3]):e[3],scriptId:e[4]??void 0,lineNumber:e[5]??void 0})),n=o.query(`SELECT timestamp, address, old_value, new_value, size, value_type FROM memory_deltas ORDER BY timestamp`).rows.map(e=>({timestamp:e[0],address:e[1],oldValue:e[2],newValue:e[3],size:e[4],valueType:e[5]})),r=o.query(`SELECT
28
28
  COUNT(*) as requestCount,
29
29
  COALESCE(SUM(chunk_count), 0) as chunkCount,
30
30
  SUM(CASE WHEN body_capture_state IN ('inline', 'artifact', 'truncated') THEN 1 ELSE 0 END) as bodyCount
@@ -1,10 +1,10 @@
1
- import{Cr as e,Sr as t,wr as n}from"./constants-Cp6hBrrx.mjs";const r=[`etw`,`strace`,`dtrace`],i=3e3,a={etw:[{syscall:`NtCreateFile`,args:[`C:\\Windows\\Temp\\jshookmcp.log`,`GENERIC_READ`],returnValue:0,duration:.7},{syscall:`NtReadFile`,args:[`handle=0x90`,`buffer=4096`],returnValue:512,duration:.2},{syscall:`NtWriteFile`,args:[`handle=0x90`,`buffer=128`],returnValue:128,duration:.3},{syscall:`NtDeviceIoControlFile`,args:[`handle=0x44`,`code=0x222004`],returnValue:0,duration:1.1}],strace:[{syscall:`openat`,args:[`/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.4},{syscall:`read`,args:[`fd=3`,`count=4096`],returnValue:256,duration:.1},{syscall:`write`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=18`,`127.0.0.1:9222`],returnValue:0,duration:1.4}],dtrace:[{syscall:`open_nocancel`,args:[`/private/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.5},{syscall:`read_nocancel`,args:[`fd=3`,`count=4096`],returnValue:320,duration:.1},{syscall:`write_nocancel`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=21`,`127.0.0.1:9222`],returnValue:0,duration:1.3}]};function o(e){return e===`etw`?process.platform===`win32`:e===`strace`?process.platform===`linux`:e===`dtrace`?process.platform===`darwin`:!1}function s(){return process.platform===`win32`?`etw`:process.platform===`linux`?`strace`:process.platform===`darwin`?`dtrace`:`etw`}function c(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function l(e,t,n,r){let a=!1,o=setTimeout(()=>{if(!a){a=!0;try{r?.()}catch{}n(Error(`${e} did not signal readiness within ${i}ms`))}},i);return{resolveReady(e){a||(a=!0,clearTimeout(o),t(e))},rejectReady(e){a||(a=!0,clearTimeout(o),n(e))}}}function u(e,t){return t?!(t.pid!==void 0&&e.pid!==t.pid||t.name&&t.name.length>0&&!t.name.includes(e.syscall)):!0}function d(e,t,n){let r=/^(\d+)\s+([\d:.]+)\s+(\w+)\(([^)]*)\)\s*=\s*(-?\d+)(?:\s+<([\d.]+)>)?$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[5]),s=r[6]?Number(r[6]):void 0,c=a.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:t,syscall:i,args:c,returnValue:Number.isFinite(o)?o:void 0,duration:s!==void 0&&Number.isFinite(s)?s*1e3:void 0}}function f(e,t,n){let r=/^\[([^\]]+)\]\s+PID=(\d+)\s+(\w+)\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}function p(e,t,n){let r=/^\s*(\d+)\s+\d+\s+(\d+)\s+(\w+):\w+\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}var m=class{activeState;capturedEvents=[];lastBackend=s();subprocessError;async start(e){let t=e?.backend??s(),n=Date.now();if(!o(t))throw Error(`Backend "${t}" is not available on platform "${process.platform}"`);if(e?.simulate??process.env.JSHOOK_SIMULATE===`1`){this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}let r=e?.pid??process.pid,i;try{t===`strace`?i=await this.captureWithStrace(r,n):t===`etw`?i=await this.captureWithETW(r,n):t===`dtrace`&&(i=await this.captureWithDTrace(r,n))}catch(r){this.subprocessError=r instanceof Error?r.message:String(r),this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0,subprocess:i},this.lastBackend=t,this.capturedEvents.length=0,this.subprocessError=void 0}async stop(){this.activeState?.subprocess&&(this.activeState.subprocess.kill(`SIGTERM`),this.activeState.subprocess=void 0),this.activeState=void 0}async captureEvents(e){return this.activeState&&!this.activeState.subprocess&&this.generateSyntheticEvents(),this.capturedEvents.filter(t=>u(t,e)).map(c)}getStats(){let e=this.activeState?.backend??this.lastBackend,t=this.activeState?Date.now()-this.activeState.startedAt:0;return{eventsCaptured:this.capturedEvents.length,uptime:t,backend:e,subprocessActive:!!this.activeState?.subprocess,subprocessError:this.subprocessError}}getSupportedBackends(){return r.filter(e=>o(e))}isRunning(){return this.activeState!==void 0}async captureWithStrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`strace`,[`-p`,String(e),`-f`,`-e`,`trace=all`,`-t`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`strace process`,r,i,()=>a.kill(`SIGTERM`)),s=``,c=``;a.stdout?.on(`data`,t=>{c+=t.toString(),this.processLineBuffer(c,e,`strace`)}),a.stderr?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r)if(n.length>0){let r=d(n,e,t);r&&this.capturedEvents.push(r)}}),a.on(`error`,e=>{o.rejectReady(Error(`strace process error: ${e.message}. Is strace installed?`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithETW(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`logman`,[`create`,`trace`,`JSHookETW_${e}`,`-p`,`NT Kernel Logger`,`0x10000`,`-o`,`jshook_etw_${e}.etl`,`-ets`],{stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),o=l(`ETW trace session`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=f(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t.length>0&&t.startsWith(`The command completed successfully`)}),a.on(`error`,e=>{o.rejectReady(Error(`ETW trace error: ${e.message}. Run as Administrator.`))}),a.on(`exit`,e=>{e!==0&&e!==void 0&&o.rejectReady(Error(`ETW trace session ended (code ${e}). Check permissions.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithDTrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`dtrace`,[`-n`,`
1
+ import{Bi as e,Hi as t,Vi as n}from"./constants-DMv3svps.mjs";const r=[`etw`,`strace`,`dtrace`],i=3e3,a={etw:[{syscall:`NtCreateFile`,args:[`C:\\Windows\\Temp\\jshookmcp.log`,`GENERIC_READ`],returnValue:0,duration:.7},{syscall:`NtReadFile`,args:[`handle=0x90`,`buffer=4096`],returnValue:512,duration:.2},{syscall:`NtWriteFile`,args:[`handle=0x90`,`buffer=128`],returnValue:128,duration:.3},{syscall:`NtDeviceIoControlFile`,args:[`handle=0x44`,`code=0x222004`],returnValue:0,duration:1.1}],strace:[{syscall:`openat`,args:[`/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.4},{syscall:`read`,args:[`fd=3`,`count=4096`],returnValue:256,duration:.1},{syscall:`write`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=18`,`127.0.0.1:9222`],returnValue:0,duration:1.4}],dtrace:[{syscall:`open_nocancel`,args:[`/private/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.5},{syscall:`read_nocancel`,args:[`fd=3`,`count=4096`],returnValue:320,duration:.1},{syscall:`write_nocancel`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=21`,`127.0.0.1:9222`],returnValue:0,duration:1.3}]};function o(e){return e===`etw`?process.platform===`win32`:e===`strace`?process.platform===`linux`:e===`dtrace`?process.platform===`darwin`:!1}function s(){return process.platform===`win32`?`etw`:process.platform===`linux`?`strace`:process.platform===`darwin`?`dtrace`:`etw`}function c(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function l(e,t,n,r){let a=!1,o=setTimeout(()=>{if(!a){a=!0;try{r?.()}catch{}n(Error(`${e} did not signal readiness within ${i}ms`))}},i);return{resolveReady(e){a||(a=!0,clearTimeout(o),t(e))},rejectReady(e){a||(a=!0,clearTimeout(o),n(e))}}}function u(e,t){return t?!(t.pid!==void 0&&e.pid!==t.pid||t.name&&t.name.length>0&&!t.name.includes(e.syscall)):!0}function d(e,t,n){let r=/^(\d+)\s+([\d:.]+)\s+(\w+)\(([^)]*)\)\s*=\s*(-?\d+)(?:\s+<([\d.]+)>)?$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[5]),s=r[6]?Number(r[6]):void 0,c=a.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:t,syscall:i,args:c,returnValue:Number.isFinite(o)?o:void 0,duration:s!==void 0&&Number.isFinite(s)?s*1e3:void 0}}function f(e,t,n){let r=/^\[([^\]]+)\]\s+PID=(\d+)\s+(\w+)\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}function p(e,t,n){let r=/^\s*(\d+)\s+\d+\s+(\d+)\s+(\w+):\w+\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}var m=class{activeState;capturedEvents=[];lastBackend=s();subprocessError;async start(e){let t=e?.backend??s(),n=Date.now();if(!o(t))throw Error(`Backend "${t}" is not available on platform "${process.platform}"`);if(e?.simulate??process.env.JSHOOK_SIMULATE===`1`){this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}let r=e?.pid??process.pid,i;try{t===`strace`?i=await this.captureWithStrace(r,n):t===`etw`?i=await this.captureWithETW(r,n):t===`dtrace`&&(i=await this.captureWithDTrace(r,n))}catch(r){this.subprocessError=r instanceof Error?r.message:String(r),this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0,subprocess:i},this.lastBackend=t,this.capturedEvents.length=0,this.subprocessError=void 0}async stop(){this.activeState?.subprocess&&(this.activeState.subprocess.kill(`SIGTERM`),this.activeState.subprocess=void 0),this.activeState=void 0}async captureEvents(e){return this.activeState&&!this.activeState.subprocess&&this.generateSyntheticEvents(),this.capturedEvents.filter(t=>u(t,e)).map(c)}getStats(){let e=this.activeState?.backend??this.lastBackend,t=this.activeState?Date.now()-this.activeState.startedAt:0;return{eventsCaptured:this.capturedEvents.length,uptime:t,backend:e,subprocessActive:!!this.activeState?.subprocess,subprocessError:this.subprocessError}}getSupportedBackends(){return r.filter(e=>o(e))}isRunning(){return this.activeState!==void 0}async captureWithStrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`strace`,[`-p`,String(e),`-f`,`-e`,`trace=all`,`-t`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`strace process`,r,i,()=>a.kill(`SIGTERM`)),s=``,c=``;a.stdout?.on(`data`,t=>{c+=t.toString(),this.processLineBuffer(c,e,`strace`)}),a.stderr?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r)if(n.length>0){let r=d(n,e,t);r&&this.capturedEvents.push(r)}}),a.on(`error`,e=>{o.rejectReady(Error(`strace process error: ${e.message}. Is strace installed?`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithETW(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`logman`,[`create`,`trace`,`JSHookETW_${e}`,`-p`,`NT Kernel Logger`,`0x10000`,`-o`,`jshook_etw_${e}.etl`,`-ets`],{stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),o=l(`ETW trace session`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=f(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t.length>0&&t.startsWith(`The command completed successfully`)}),a.on(`error`,e=>{o.rejectReady(Error(`ETW trace error: ${e.message}. Run as Administrator.`))}),a.on(`exit`,e=>{e!==0&&e!==void 0&&o.rejectReady(Error(`ETW trace session ended (code ${e}). Check permissions.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithDTrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`dtrace`,[`-n`,`
2
2
  syscall:::entry
3
3
  /pid == ${e}/
4
4
  {
5
5
  printf("%d %d %s:entry %s", pid, probeproc, probefunc, copyinstr(arg0));
6
6
  }
7
- `],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`dtrace process`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=p(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,()=>{}),a.on(`error`,e=>{o.rejectReady(Error(`dtrace error: ${e.message}. Run with sudo.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}generateSyntheticEvents(){if(!this.activeState)return;let e=a[this.activeState.backend];if(!e)return;let t=Date.now()-this.activeState.startedAt,n=Math.max(1,Math.min(e.length*3,Math.floor(t/150)+1)),r=this.activeState.pid??process.pid;for(;this.activeState.generatedEvents<n;){let t=e[this.activeState.generatedEvents%e.length];if(!t)break;let n=this.activeState.generatedEvents*75;this.capturedEvents.push({timestamp:n,pid:r,syscall:t.syscall,args:[...t.args],returnValue:t.returnValue,duration:t.duration}),this.activeState.generatedEvents+=1}}processLineBuffer(e,t,n){}};const h=[{syscallNames:[`NtCreateFile`,`openat`,`open_nocancel`],jsFunction:`fs.open`,baseConfidence:.8,explanation:`File open syscalls commonly originate from Node.js file-system entry points.`},{syscallNames:[`NtReadFile`,`read`,`read_nocancel`],jsFunction:`fs.readFile`,baseConfidence:.78,explanation:`Read-oriented syscalls usually map back to file or stream reads in JavaScript.`},{syscallNames:[`NtWriteFile`,`write`,`write_nocancel`],jsFunction:`fs.writeFile`,baseConfidence:.78,explanation:`Write-oriented syscalls are strongly associated with Node.js file writes.`},{syscallNames:[`NtDeviceIoControlFile`,`ioctl`],jsFunction:`child_process.spawn`,baseConfidence:.55,explanation:`Device and control syscalls are often triggered by child processes or native helpers.`},{syscallNames:[`connect`,`sendto`,`recvfrom`],jsFunction:`fetch`,baseConfidence:.7,explanation:`Socket syscalls generally indicate outbound network activity from fetch-like APIs.`}];function g(e){return h.find(t=>t.syscallNames.includes(e))}function _(e){return e<0?0:e>1?1:e}function v(e,t){return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}var y=class{map(e){let t=this.findJSFunction(e.syscall);if(!t)return null;let n=g(e.syscall);if(!n)return null;let r=n.baseConfidence;return t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&(r+=.08),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&(r+=.1),{syscall:{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration},jsFunction:t,confidence:_(r),reasoning:this.getCorrelationReason(e,t)}}findJSFunction(e){let t=g(e);return t?t.jsFunction:null}getCorrelationReason(e,t){let n=g(e.syscall),r=[];return n&&r.push(n.explanation),t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&r.push(`The syscall arguments reference module-like file extensions, which strengthens the fs correlation.`),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&r.push(`The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.`),r.length===0&&r.push(`Mapped ${e.syscall} to ${t} using the default syscall-to-JS heuristic table.`),r.join(` `)}};function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e==`number`&&Number.isFinite(e))return e}function S(e){if(typeof e==`boolean`)return e}function C(e){if(typeof e==`string`)return e}function w(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)return;t.push(n)}return t}const T=/^[a-z][a-z0-9_]*$/;function E(e){return T.test(e)&&e.length<=64}function D(e){if(e===`etw`||e===`strace`||e===`dtrace`)return e}function O(e){if(!b(e))return;let t={},n=w(e.name),r=x(e.pid);return n&&(t.name=n),r!==void 0&&(t.pid=r),t}function k(e){if(!b(e))return!1;let t=x(e.timestamp),n=x(e.pid),r=C(e.syscall),i=w(e.args),a=e.returnValue,o=e.duration,s=a===void 0||x(a)!==void 0,c=o===void 0||x(o)!==void 0;return t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0&&s&&c}function A(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function j(e){return e instanceof Error?e.message:`Unknown syscall-hook error`}var M=class{monitor;mapper;eventBus;constructor(e,t,n){this.monitor=e,this.mapper=t,this.eventBus=n}async handleSyscallStartMonitor(e){let t=D(e.backend);if(!t)return{ok:!1,error:`backend must be one of: etw, strace, dtrace`};let n=x(e.pid),r=S(e.simulate)??!1;if(e.pid!==void 0&&e.pid!==null&&(n===void 0||!Number.isInteger(n)||n<0))return{ok:!1,error:`pid must be a non-negative integer when provided`};let i=n,a=this.ensureMonitor();try{return await a.start({backend:t,pid:i,simulate:r}),this.eventBus?.emit(`syscall:trace_started`,{backend:t,pid:i,simulate:r,timestamp:new Date().toISOString()}),{ok:!0,started:!0,backend:t,pid:i,simulate:r,stats:a.getStats()}}catch(e){return{ok:!1,error:j(e),requestedBackend:t,supportedBackends:a.getSupportedBackends()}}}async handleSyscallStopMonitor(){let e=this.ensureMonitor();try{return await e.stop(),{ok:!0,stopped:!0,stats:e.getStats()}}catch(e){return{ok:!1,error:j(e)}}}async handleSyscallCaptureEvents(e){let t=this.ensureMonitor(),n=O(e.filter),r=await t.captureEvents(n);return{ok:!0,events:r,count:r.length,stats:t.getStats()}}async handleSyscallCorrelateJs(e){let t=e.syscallEvents;if(!Array.isArray(t)||!t.every(e=>k(e)))return{ok:!1,error:`syscallEvents must be an array of valid SyscallEvent objects`};let n=this.ensureMapper(),r=[],i=[];for(let e of t){let t=A(e),a=n.map(t);a?r.push(a):i.push(t)}return{ok:!0,correlations:r,matched:r.length,unmatched:i}}async handleSyscallFilter(e){let t=w(e.names);if(e.names!==void 0&&t===void 0)return{ok:!1,error:`names must be an array of strings when provided`};let n=await this.ensureMonitor().captureEvents(t&&t.length>0?{name:t}:void 0);return{ok:!0,names:t,events:n,count:n.length}}async handleSyscallGetStats(){let e=this.ensureMonitor();return{ok:!0,...e.getStats(),running:e.isRunning(),supportedBackends:e.getSupportedBackends()}}async handleSyscallEbpfTrace(r){let i=x(r.pid),a=w(r.syscalls),o=x(r.durationSec)??t,s=S(r.simulate)??!1;if(r.pid!==void 0&&r.pid!==null&&(i===void 0||!Number.isInteger(i)||i<0))return{ok:!1,error:`pid must be a non-negative integer (0 for all processes)`};let c=i??0;if(o<n||o>e)return{ok:!1,error:`durationSec must be between ${n} and ${e}`};if(a?.length){let e=a.filter(e=>!E(e));if(e.length>0)return{ok:!1,error:`Invalid syscall names (must be lowercase alphanumeric with underscores): ${e.join(`, `)}`}}if(s){let e=[],t=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`],n=o*50;for(let r=0;r<20;r++)e.push({timestamp:r*n,pid:c||1234,syscall:t[r%t.length]??`read`,args:[`fd=${r%5+3}`,`count=${(r+1)*64}`],returnValue:r%3==0?-1:(r+1)*64,duration:Math.random()*2});return{ok:!0,backend:`ebpf`,simulated:!0,pid:c,durationSec:o,events:e,count:e.length,syscallsTraced:t}}let l=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`,`connect`,`sendto`,`recvfrom`,`clone`,`execve`],u=c>0?`/pid == ${c}/`:``,d=l.map(e=>`tracepoint:syscalls:sys_enter_${e}`).join(`, `),f=l.map(e=>`tracepoint:syscalls:sys_exit_${e}`).join(`, `),p=`#!/usr/bin/env bpftrace
7
+ `],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`dtrace process`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=p(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,()=>{}),a.on(`error`,e=>{o.rejectReady(Error(`dtrace error: ${e.message}. Run with sudo.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}generateSyntheticEvents(){if(!this.activeState)return;let e=a[this.activeState.backend];if(!e)return;let t=Date.now()-this.activeState.startedAt,n=Math.max(1,Math.min(e.length*3,Math.floor(t/150)+1)),r=this.activeState.pid??process.pid;for(;this.activeState.generatedEvents<n;){let t=e[this.activeState.generatedEvents%e.length];if(!t)break;let n=this.activeState.generatedEvents*75;this.capturedEvents.push({timestamp:n,pid:r,syscall:t.syscall,args:[...t.args],returnValue:t.returnValue,duration:t.duration}),this.activeState.generatedEvents+=1}}processLineBuffer(e,t,n){}};const h=[{syscallNames:[`NtCreateFile`,`openat`,`open_nocancel`],jsFunction:`fs.open`,baseConfidence:.8,explanation:`File open syscalls commonly originate from Node.js file-system entry points.`},{syscallNames:[`NtReadFile`,`read`,`read_nocancel`],jsFunction:`fs.readFile`,baseConfidence:.78,explanation:`Read-oriented syscalls usually map back to file or stream reads in JavaScript.`},{syscallNames:[`NtWriteFile`,`write`,`write_nocancel`],jsFunction:`fs.writeFile`,baseConfidence:.78,explanation:`Write-oriented syscalls are strongly associated with Node.js file writes.`},{syscallNames:[`NtDeviceIoControlFile`,`ioctl`],jsFunction:`child_process.spawn`,baseConfidence:.55,explanation:`Device and control syscalls are often triggered by child processes or native helpers.`},{syscallNames:[`connect`,`sendto`,`recvfrom`],jsFunction:`fetch`,baseConfidence:.7,explanation:`Socket syscalls generally indicate outbound network activity from fetch-like APIs.`}];function g(e){return h.find(t=>t.syscallNames.includes(e))}function _(e){return e<0?0:e>1?1:e}function v(e,t){return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}var y=class{map(e){let t=this.findJSFunction(e.syscall);if(!t)return null;let n=g(e.syscall);if(!n)return null;let r=n.baseConfidence;return t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&(r+=.08),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&(r+=.1),{syscall:{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration},jsFunction:t,confidence:_(r),reasoning:this.getCorrelationReason(e,t)}}findJSFunction(e){let t=g(e);return t?t.jsFunction:null}getCorrelationReason(e,t){let n=g(e.syscall),r=[];return n&&r.push(n.explanation),t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&r.push(`The syscall arguments reference module-like file extensions, which strengthens the fs correlation.`),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&r.push(`The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.`),r.length===0&&r.push(`Mapped ${e.syscall} to ${t} using the default syscall-to-JS heuristic table.`),r.join(` `)}};function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e==`number`&&Number.isFinite(e))return e}function S(e){if(typeof e==`boolean`)return e}function C(e){if(typeof e==`string`)return e}function w(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)return;t.push(n)}return t}const T=/^[a-z][a-z0-9_]*$/;function E(e){return T.test(e)&&e.length<=64}function D(e){if(e===`etw`||e===`strace`||e===`dtrace`)return e}function O(e){if(!b(e))return;let t={},n=w(e.name),r=x(e.pid);return n&&(t.name=n),r!==void 0&&(t.pid=r),t}function k(e){if(!b(e))return!1;let t=x(e.timestamp),n=x(e.pid),r=C(e.syscall),i=w(e.args),a=e.returnValue,o=e.duration,s=a===void 0||x(a)!==void 0,c=o===void 0||x(o)!==void 0;return t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0&&s&&c}function A(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function j(e){return e instanceof Error?e.message:`Unknown syscall-hook error`}var M=class{monitor;mapper;eventBus;constructor(e,t,n){this.monitor=e,this.mapper=t,this.eventBus=n}async handleSyscallStartMonitor(e){let t=D(e.backend);if(!t)return{ok:!1,error:`backend must be one of: etw, strace, dtrace`};let n=x(e.pid),r=S(e.simulate)??!1;if(e.pid!==void 0&&e.pid!==null&&(n===void 0||!Number.isInteger(n)||n<0))return{ok:!1,error:`pid must be a non-negative integer when provided`};let i=n,a=this.ensureMonitor();try{return await a.start({backend:t,pid:i,simulate:r}),this.eventBus?.emit(`syscall:trace_started`,{backend:t,pid:i,simulate:r,timestamp:new Date().toISOString()}),{ok:!0,started:!0,backend:t,pid:i,simulate:r,stats:a.getStats()}}catch(e){return{ok:!1,error:j(e),requestedBackend:t,supportedBackends:a.getSupportedBackends()}}}async handleSyscallStopMonitor(){let e=this.ensureMonitor();try{return await e.stop(),{ok:!0,stopped:!0,stats:e.getStats()}}catch(e){return{ok:!1,error:j(e)}}}async handleSyscallCaptureEvents(e){let t=this.ensureMonitor(),n=O(e.filter),r=await t.captureEvents(n);return{ok:!0,events:r,count:r.length,stats:t.getStats()}}async handleSyscallCorrelateJs(e){let t=e.syscallEvents;if(!Array.isArray(t)||!t.every(e=>k(e)))return{ok:!1,error:`syscallEvents must be an array of valid SyscallEvent objects`};let n=this.ensureMapper(),r=[],i=[];for(let e of t){let t=A(e),a=n.map(t);a?r.push(a):i.push(t)}return{ok:!0,correlations:r,matched:r.length,unmatched:i}}async handleSyscallFilter(e){let t=w(e.names);if(e.names!==void 0&&t===void 0)return{ok:!1,error:`names must be an array of strings when provided`};let n=await this.ensureMonitor().captureEvents(t&&t.length>0?{name:t}:void 0);return{ok:!0,names:t,events:n,count:n.length}}async handleSyscallGetStats(){let e=this.ensureMonitor();return{ok:!0,...e.getStats(),running:e.isRunning(),supportedBackends:e.getSupportedBackends()}}async handleSyscallEbpfTrace(r){let i=x(r.pid),a=w(r.syscalls),o=x(r.durationSec)??e,s=S(r.simulate)??!1;if(r.pid!==void 0&&r.pid!==null&&(i===void 0||!Number.isInteger(i)||i<0))return{ok:!1,error:`pid must be a non-negative integer (0 for all processes)`};let c=i??0;if(o<t||o>n)return{ok:!1,error:`durationSec must be between ${t} and ${n}`};if(a?.length){let e=a.filter(e=>!E(e));if(e.length>0)return{ok:!1,error:`Invalid syscall names (must be lowercase alphanumeric with underscores): ${e.join(`, `)}`}}if(s){let e=[],t=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`],n=o*50;for(let r=0;r<20;r++)e.push({timestamp:r*n,pid:c||1234,syscall:t[r%t.length]??`read`,args:[`fd=${r%5+3}`,`count=${(r+1)*64}`],returnValue:r%3==0?-1:(r+1)*64,duration:Math.random()*2});return{ok:!0,backend:`ebpf`,simulated:!0,pid:c,durationSec:o,events:e,count:e.length,syscallsTraced:t}}let l=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`,`connect`,`sendto`,`recvfrom`,`clone`,`execve`],u=c>0?`/pid == ${c}/`:``,d=l.map(e=>`tracepoint:syscalls:sys_enter_${e}`).join(`, `),f=l.map(e=>`tracepoint:syscalls:sys_exit_${e}`).join(`, `),p=`#!/usr/bin/env bpftrace
8
8
  // Generated by jshookmcp syscall_ebpf_trace
9
9
  // Target PID: ${c||`all`} | Duration: ${o}s | Syscalls: ${l.join(`, `)}
10
10
 
@@ -0,0 +1 @@
1
+ import{t as e}from"./ToolError-g3rjWzhx.mjs";import{n as t,o as n}from"./parse-args-ngRrvF9e.mjs";import{n as r}from"./ResponseBuilder-nPXl_khE.mjs";import{basename as i,join as a}from"node:path";import{open as o,readdir as s,stat as c}from"node:fs/promises";import{createHash as l}from"node:crypto";import{open as u}from"yauzl";const d=Object.freeze([]),f=(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},p=f(`APK_PACKER_MAX_APK_BYTES`,512*1024*1024),m=f(`APK_PACKER_MAX_ZIP_ENTRIES`,2e5),h=f(`APK_PACKER_MAX_REGEX_PATTERN_LENGTH`,256),g=f(`APK_PACKER_REGEX_TIMEOUT_MS`,50),_=f(`APK_SIGBLOCK_EOCD_SCAN_BYTES`,65536),v=f(`APK_SIGBLOCK_MAX_BYTES`,1024*1024),y=f(`APK_SIGBLOCK_DEX_PREFIX_HEAD_BYTES`,4),b=Object.freeze([/\([^()]*[+*][^()]*\)[+*]/,/\([^()]*\|[^()]*\)[+*][^()]*[+*]/]);function x(t,n){return new e(`VALIDATION`,t,{details:n})}function S(e){return/[\^$*+?()[\]{}|]/.test(e)}function C(e){if(!e.name||e.name.length===0)throw x(`customSignature.name must be a non-empty string`);if(e.category!==void 0&&typeof e.category!=`string`)throw x(`customSignature.category, when present, must be a string`,{name:e.name});if(!Array.isArray(e.libPatterns)||e.libPatterns.length===0)throw x(`customSignature.libPatterns must be a non-empty array`,{name:e.name});let t=[];for(let n=0;n<e.libPatterns.length;n++){let r=e.libPatterns[n];if(typeof r!=`string`||r.length===0)throw x(`customSignature.libPatterns[${n}] must be a non-empty string`,{name:e.name});if(r.length>h)throw x(`customSignature.libPatterns[${n}] exceeds APK_PACKER_MAX_REGEX_PATTERN_LENGTH (${h})`,{name:e.name,length:r.length});S(r)?(w(r,e.name),t.push(T(r,`i`,e.name))):t.push(r.toLowerCase())}return{name:e.name,libPatterns:t,...e.category?{category:e.category}:{},...e.confidence?{confidence:e.confidence}:{},...e.notes?{notes:e.notes}:{}}}function w(e,t){for(let n of b)if(n.test(e))throw x(`customSignature pattern rejected as potentially catastrophic (ReDoS heuristic match)`,{name:t,pattern:e})}function T(t,n,r){try{return new RegExp(t,n)}catch(i){throw new e(`VALIDATION`,`customSignature regex failed to compile: ${i.message}`,{details:{name:r,pattern:t,flags:n},cause:i})}}function E(e,t,n){return n===`replace`?Object.freeze([...t??[]]):!t||t.length===0?Object.freeze([...e]):Object.freeze(n===`prepend`?[...t,...e]:[...e,...t])}function D(t,n,r=g,i){let a=performance.now(),o=t.test(n),s=performance.now()-a;if(s>r)throw new e(`TIMEOUT`,`Regex match exceeded APK_PACKER_REGEX_TIMEOUT_MS (${r} ms): ${s.toFixed(2)} ms`,{details:{signatureName:i,pattern:t.source,flags:t.flags,elapsedMs:s,timeoutMs:r}});return o}const O=/^lib\/[^/]+\/(lib[^/]+\.so)$/i;var k=class{defaults;constructor(e=d){this.defaults=e}async detectFromApk(t,n={}){if(!t||t.length===0)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);let r;try{r=await c(t)}catch(n){throw new e(`NOT_FOUND`,`APK not found: ${t}`,{details:{apkPath:t},cause:n})}if(!r.isFile())throw new e(`VALIDATION`,`APK path is not a regular file: ${t}`,{details:{apkPath:t}});if(r.size>p)throw new e(`VALIDATION`,`APK exceeds APK_PACKER_MAX_APK_BYTES (${p} bytes): ${r.size}`,{details:{apkPath:t,size:r.size,max:p}});let i=await M(t);return this.matchBasenames(i,n)}async detectFromDir(t,n={}){if(!t||t.length===0)throw new e(`VALIDATION`,`dirPath must be a non-empty string`);let r;try{r=await c(t)}catch(n){throw new e(`NOT_FOUND`,`Directory not found: ${t}`,{details:{dirPath:t},cause:n})}if(!r.isDirectory())throw new e(`VALIDATION`,`Path is not a directory: ${t}`,{details:{dirPath:t}});let i=await N(t);return this.matchBasenames(i,n)}matchBasenames(e,t={}){let n=E(this.defaults,t.customSignatures,t.ruleMode??`append`),r=[];for(let t of n){let n=new Set;for(let r of e)A(r,t)&&n.add(r.path);if(n.size===0)continue;let i=t.confidence??`medium`,a=n.size>=2?`high`:i;r.push({name:t.name,...t.category?{category:t.category}:{},matchedLibs:[...n].toSorted(),confidence:a})}let i=r.length;return{packers:r,confidence:j(r),layerCount:i}}};function A(e,t){for(let n of t.libPatterns)if(typeof n==`string`){if(e.basename===n)return!0}else if(D(n,e.basename,g,t.name))return!0;return!1}function j(e){if(e.length===0)return 0;let t=.5;return e.some(e=>e.confidence===`high`)&&(t+=.25),e.length>=2&&(t+=.25),Math.min(t,1)}async function M(t){return new Promise((n,r)=>{u(t,{lazyEntries:!0,autoClose:!0},(i,a)=>{if(i||!a){r(new e(`VALIDATION`,`Failed to open APK as ZIP: ${i?.message??`unknown`}`,{details:{apkPath:t},cause:i??void 0}));return}let o=[],s=0,c=a,l=n=>{if(s+=1,s>m){c.close(),r(new e(`VALIDATION`,`APK has too many ZIP entries (> ${m})`,{details:{apkPath:t}}));return}let i=n.fileName,a=O.exec(i);if(a){let e=a[1].toLowerCase();o.push({path:i.toLowerCase(),basename:e})}c.readEntry()},u=()=>{f(),n(o)},d=n=>{f(),c.close(),r(new e(`RUNTIME`,`ZIP read failed: ${n.message}`,{details:{apkPath:t},cause:n}))};function f(){c.removeListener(`entry`,l),c.removeListener(`end`,u),c.removeListener(`error`,d)}c.on(`entry`,l),c.on(`end`,u),c.on(`error`,d),c.readEntry()})})}async function N(e){let t=a(e,`lib`),n;try{n=await s(t)}catch{return[]}let r=[];for(let e of n){let n=a(t,e),o;try{if(!(await c(n)).isDirectory())continue;o=await s(n)}catch{continue}for(let t of o){if(!t.toLowerCase().endsWith(`.so`))continue;let n=`lib/${e}/${t}`.toLowerCase();r.push({path:n,basename:i(t).toLowerCase()})}}return r}const P=`APK Sig Block 42`,F=Buffer.from(P,`utf8`);var I=class{async parse(t){if(!t||typeof t!=`string`)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);let n;try{n=await c(t)}catch(n){throw new e(`NOT_FOUND`,`APK not found: ${t}`,{details:{apkPath:t},cause:n})}if(!n.isFile())throw new e(`VALIDATION`,`Path is not a regular file: ${t}`,{details:{apkPath:t}});if(n.size>p)throw new e(`VALIDATION`,`APK exceeds APK_PACKER_MAX_APK_BYTES (${p} bytes): ${n.size}`,{details:{apkPath:t,size:n.size,max:p}});let r;try{return r=await o(t,`r`),await this.parseHandle(r,t,n.size)}finally{r&&await r.close()}}async parseHandle(e,t,n){let r={schemes:{},unknownBlocks:[],warnings:[],anomalies:[]},i=Math.min(_,n),a=Buffer.alloc(i);await e.read(a,0,i,n-i);let o=R(a);if(o<0)return r.anomalies.push({kind:`eocd-not-found`,evidence:`Scanned trailing ${i} bytes — no EOCD signature 0x06054b50`}),L(t,n,r,!1);let s=a.readUInt32LE(o+16);if(s>=n-i+o||s<24)return r.warnings.push(`Implausible centralDirOffset ${s} given file size ${n}`),L(t,n,r,!1);let c=Buffer.alloc(24);if(await e.read(c,0,24,s-24),!c.subarray(8).equals(F)){let i=Math.min(s,_),a=Buffer.alloc(i);await e.read(a,0,i,s-i);let o=a.indexOf(F);if(o<0)return L(t,n,r,!1);let c=i-(o+F.length);return r.anomalies.push({kind:`magic-offset`,evidence:`APK Sig Block 42 magic located ${c} bytes before expected position`}),L(t,n,r,!1)}let l;try{l=J(c,0)}catch(e){return r.warnings.push(`Signing block size field unreadable: ${e.message}`),L(t,n,r,!1)}if(l<=0||l>v)return r.warnings.push(`Signing block size ${l} outside [1, ${v}] — refusing to read`),L(t,n,r,!1);let u=s-l-8;if(u<0)return r.warnings.push(`Computed signing block start offset is negative — refusing to read`),L(t,n,r,!1);let d=l+8;if(d>v)return r.warnings.push(`Signing block total length ${d} exceeds APK_SIGBLOCK_MAX_BYTES — refusing to read`),L(t,n,r,!1);let f=Buffer.alloc(Number(d));if(await e.read(f,0,Number(d),u),z(f,r),n>=4){let t=Math.min(y,n),i=Buffer.alloc(t);await e.read(i,0,t,0),i.length>=4&&i.readUInt32BE(0)===1684371466&&r.anomalies.push({kind:`dex-prefix-anomaly`,evidence:`DEX magic (0x6465780a) at file head with a valid Signing Block — possible dex-prefix injection pattern`})}return L(t,n,r,!0,{magic:P,size:Number(d),offset:u})}};function L(e,t,n,r,i){return{apkPath:e,fileSize:t,signingBlock:r&&i?{found:!0,magic:i.magic,size:i.size,offset:i.offset}:{found:!1},schemes:n.schemes,unknownBlocks:n.unknownBlocks,warnings:n.warnings,anomalies:n.anomalies}}function R(e){if(e.length<22)return-1;for(let t=e.length-22;t>=0;t--)if(e.readUInt32LE(t)===101010256){let n=e.readUInt16LE(t+20);if(t+22+n===e.length)return t}return-1}function z(e,t){let n=e.length-24,r=8;for(;r+12<=n;){let i=J(e,r);if(i<4||r+8+i>n){t.warnings.push(`Truncated ID-value pair at offset ${r} (pairSize ${i})`);return}let a=e.readUInt32LE(r+8),o=r+12,s=r+8+i;B(a,e.subarray(o,s),t),r=s}}function B(e,t,n){switch(e){case 1896449818:{let e=V(t,!1,n);n.schemes.v2?(n.anomalies.push({kind:`duplicate-scheme`,evidence:`v2 signers block (0x7109871a) appears more than once`}),n.schemes.v2.signers.push(...e)):n.schemes.v2={signers:e};return}case 4031998144:{let e=V(t,!0,n),r=U(e);n.schemes.v3=r?{signers:e,keyRotation:r}:{signers:e};return}case 462663009:{let e=V(t,!0,n);n.schemes.v3_1={signers:e};return}case 1114793335:{let e=W(t);e&&(n.schemes.v4=e);return}case 1347109971:return;case 1111638594:n.unknownBlocks.push({id:q(e),size:t.length}),n.anomalies.push({kind:`extra-block-anomaly`,evidence:`Block ID 0x42424242 present (size=${t.length}) — non-standard residue marker`}),n.warnings.push(`Unknown block 0x42424242 detected — non-standard block ID observed in some legacy tooling. Manual review recommended.`);return;default:n.unknownBlocks.push({id:q(e),size:t.length}),n.anomalies.push({kind:`extra-block`,evidence:`Unknown block id ${q(e)} size=${t.length}`});return}}function V(e,t,n){let r=new Y(e,`signers`),i=r.readU32();if(i===0)return[];let a=r.readSlice(i,`signersBuf`),o=[],s=new Y(a,`signers-inner`);for(;s.remaining()>0;){let e=s.readU32(),r=s.readSlice(e,`signer`);try{o.push(H(r,t))}catch(e){n.warnings.push(`Skipped malformed signer: ${e.message}`)}}return o}function H(e,t){let n=new Y(e,`signer`),r=n.readU32(),i=n.readSlice(r,`signedData`),a=0,o=0;t&&(a=n.readU32(),o=n.readU32());let s=n.readU32(),c=n.readSlice(s,`signatures`),l=[],u=new Y(c,`signatures-inner`);for(;u.remaining()>0;){let e=u.readU32(),t=u.readSlice(e,`signature`);if(t.length<4)continue;let n=t.readUInt32LE(0);l.push({algorithm:K(n),algorithmId:n})}let d=new Y(i,`signedData`),f=d.readU32(),p=d.readSlice(f,`digests`),m=[],h=new Y(p,`digests-inner`);for(;h.remaining()>0;){let e=h.readU32(),t=h.readSlice(e,`digest`);if(t.length<4)continue;let n=t.readUInt32LE(0);m.push({algorithm:K(n),algorithmId:n})}let g=d.readU32(),_=d.readSlice(g,`certificates`),v=[],y=new Y(_,`certs-inner`);for(;y.remaining()>0;){let e=y.readU32(),t=y.readSlice(e,`certificate`);v.push(G(t))}let b=d.readU32(),x=d.readSlice(b,`attributes`),S=[],C=new Y(x,`attrs-inner`);for(;C.remaining()>0;){let e=C.readU32(),t=C.readSlice(e,`attribute`);if(t.length<4)continue;let n=t.readUInt32LE(0);S.push({id:q(n),size:t.length})}let w={digests:m,signatures:l,certificates:v,additionalAttributes:S};return t?{...w,minSdkVersion:a,maxSdkVersion:o}:w}function U(e){for(let t of e)for(let e of t.additionalAttributes)if(e.id===q(1000370060))return{levels:[]}}function W(e){try{let t=new Y(e,`v4`),n=t.readU32(),r=t.readU32(),i=t.readSlice(r,`v4-hash`),a=0;return t.remaining()>=8?a=J(e,t.position()):t.remaining()>=4&&(a=t.readU32()),{algorithm:K(n),rootHash:i.toString(`hex`),treeSize:a}}catch{return}}function G(e){let t=l(`sha256`).update(e).digest(`hex`),n=e.subarray(0,Math.min(32,e.length)).toString(`hex`);return{sha256Fingerprint:t,derLength:e.length,derPreview:n}}function K(e){switch(e){case 257:return`RSA_PSS_SHA256`;case 258:return`RSA_PSS_SHA512`;case 259:return`RSA_PKCS1_V1_5_SHA256`;case 260:return`RSA_PKCS1_V1_5_SHA512`;case 513:return`ECDSA_SHA256`;case 514:return`ECDSA_SHA512`;case 769:return`DSA_SHA256`;case 1057:return`VERITY_RSA_PKCS1_V1_5_SHA256`;case 1059:return`VERITY_ECDSA_SHA256`;case 1061:return`VERITY_DSA_SHA256`;default:return`UNKNOWN`}}function q(e){return`0x${(e>>>0).toString(16).padStart(8,`0`)}`}function J(t,n){let r=t.readUInt32LE(n),i=t.readUInt32LE(n+4);if(i>2097151)throw new e(`VALIDATION`,`u64 length exceeds Number.MAX_SAFE_INTEGER at offset ${n}`);return i*4294967296+r}var Y=class{buf;label;cursor=0;constructor(e,t){this.buf=e,this.label=t}position(){return this.cursor}remaining(){return this.buf.length-this.cursor}readU32(){if(this.remaining()<4)throw new e(`VALIDATION`,`Underflow reading u32 in ${this.label}`);let t=this.buf.readUInt32LE(this.cursor);return this.cursor+=4,t}readSlice(t,n){if(t<0||t>this.remaining())throw new e(`VALIDATION`,`Underflow reading slice "${n}" (need ${t}, have ${this.remaining()}) in ${this.label}`);let r=this.buf.subarray(this.cursor,this.cursor+t);return this.cursor+=t,r}};const X=new Set([`append`,`prepend`,`replace`]),Z=new Set([`high`,`medium`,`low`]);function Q(t){if(t!=null){if(!Array.isArray(t))throw new e(`VALIDATION`,`customSignatures must be an array of signature objects`);return t.map((t,n)=>{if(typeof t!=`object`||!t||Array.isArray(t))throw new e(`VALIDATION`,`customSignatures[${n}] must be an object`);let{name:r,category:i,libPatterns:a,confidence:o,notes:s}=t;if(typeof r!=`string`)throw new e(`VALIDATION`,`customSignatures[${n}].name must be a string`);if(i!==void 0&&typeof i!=`string`)throw new e(`VALIDATION`,`customSignatures[${n}].category, when present, must be a string`);if(!Array.isArray(a))throw new e(`VALIDATION`,`customSignatures[${n}].libPatterns must be a string array`);for(let t=0;t<a.length;t++)if(typeof a[t]!=`string`)throw new e(`VALIDATION`,`customSignatures[${n}].libPatterns[${t}] must be a string`);let c={name:r,libPatterns:a};if(typeof i==`string`&&(c.category=i),typeof o==`string`){if(!Z.has(o))throw new e(`VALIDATION`,`customSignatures[${n}].confidence must be one of: high, medium, low`);c.confidence=o}return typeof s==`string`&&(c.notes=s),C(c)})}}function $(e){return{name:e.name,...e.category?{category:e.category}:{},libPatterns:e.libPatterns.map(e=>typeof e==`string`?{type:`literal`,value:e}:{type:`regex`,value:e.source}),...e.category?{category:e.category}:{},...e.confidence?{confidence:e.confidence}:{},...e.notes?{notes:e.notes}:{}}}var ee=class{detector;signingBlockParser;constructor(e=new k,t=new I){this.detector=e,this.signingBlockParser=t}handleApkPackerDetect(i){return r(async()=>{let r=n(i,`apkPath`),a=n(i,`dirPath`);if(!r&&!a)throw new e(`VALIDATION`,`Either apkPath or dirPath must be provided`);if(r&&a)throw new e(`VALIDATION`,`Provide only one of apkPath or dirPath, not both`);let o=Q(i.customSignatures),s=t(i,`ruleMode`,X),c={...o===void 0?{}:{customSignatures:o},...s===void 0?{}:{ruleMode:s}},l=r?await this.detector.detectFromApk(r,c):await this.detector.detectFromDir(a,c);return{packers:l.packers,confidence:l.confidence,layerCount:l.layerCount}})}handleApkPackerListSignatures(e){return r(async()=>{let t=n(e,`category`);return{signatures:(t?d.filter(e=>(e.category??``).toLowerCase().includes(t.toLowerCase())):d).map($)}})}handleApkSigningBlockParse(t){return r(async()=>{let r=n(t,`apkPath`);if(!r)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);return{report:await this.signingBlockParser.parse(r)}})}};export{ee as ApkPackerHandlers};
@@ -0,0 +1 @@
1
+ import{S as e,_ as t,b as n,c as r,d as i,f as a,g as o,h as s,j as c,l,m as u,o as d,p as f,s as p,u as m,v as h,x as g,y as _}from"./constants-DMv3svps.mjs";import{n as v}from"./response-B1RuVVfD.mjs";import{t as y}from"./ToolError-g3rjWzhx.mjs";import{t as b}from"./ToolProbe-DQiREmNp.mjs";import{c as x,o as S,r as C,s as w,t as T}from"./parse-args-ngRrvF9e.mjs";import{basename as E,dirname as D,join as O}from"node:path";import{mkdir as k,open as A,stat as j}from"node:fs/promises";import{execFile as M}from"node:child_process";function N(e){return e instanceof Error?e.message:String(e)}function P(e){return e?[`-s`,e]:[]}async function F(e,t,n={}){return new Promise((r,i)=>{M(e,t,{encoding:`utf8`,windowsHide:!0,timeout:n.timeoutMs??a,maxBuffer:n.maxBufferBytes??_},(e,t,a)=>{let o={stdout:t??``,stderr:a??``,exitCode:typeof e?.code==`number`?e.code??1:0,signal:typeof e?.signal==`string`?e.signal??void 0:void 0};if(e&&!n.allowNonZero){i(e);return}r(o)})})}function I(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e.startsWith(`package:`))continue;let r=e.slice(8).trim();r&&t.push(r)}return t}function L(e){return e.replace(/[^A-Za-z0-9._-]+/g,`_`).replace(/^_+|_+$/g,``)||`file`}function R(e){let t={};for(let n of[`Status`,`LaunchState`,`Activity`,`ThisTime`,`TotalTime`,`WaitTime`]){let r=e.match(RegExp(`^${n}:\\s*(.+)$`,`m`));if(!r?.[1])continue;let i=r[1].trim();t[n.charAt(0).toLowerCase()+n.slice(1)]=n.endsWith(`Time`)&&/^\d+$/.test(i)?Number(i):i}return t}function z(e){return e.match(/\buserId=(\d+)/)?.[1]??e.match(/\buid=(\d+)/)?.[1]??e.match(/\bappId=(\d+)/)?.[1]}async function B(e){let t=await j(e);if(!t.isFile())throw Error(`Pulled APK path is not a regular file: ${e}`);if(t.size<=0)throw Error(`Pulled APK is empty: ${e}`);let n=await A(e,`r`),r=Buffer.alloc(4);try{await n.read(r,0,4,0)}finally{await n.close()}let i=r.toString(`hex`).toLowerCase(),a=c.some(e=>e===i);return{size:t.size,zipLike:a}}async function V(e,t){let{stdout:n}=await F(e,[...P(t),`shell`,`cat /proc/net/unix`]),r=[];for(let e of n.split(/\r?\n/)){let t=e.trim();if(t.includes(`@webview_devtools_remote`)){let e=t.match(/@webview_devtools_remote\S+/);e&&r.push(e[0])}}return r}function H(e){return e.trim().replace(/\/+$/,``)}function U(e,t,n){let r=new Set;for(let i of[/nativeLibraryDir=([^\s]+)/g,/legacyNativeLibraryDir=([^\s]+)/g,/secondaryNativeLibraryDir=([^\s]+)/g]){let a;for(;(a=i.exec(e))!==null;){let e=H(a[1]??``);e&&(!n&&!e.includes(t)||r.add(e))}}return[...r]}var W=class{cachedAdb;async resolveAdb(){if(this.cachedAdb)return this.cachedAdb;let e=await b(`adb`);if(!e.available)throw new y(`PREREQUISITE`,e.reason??`adb not found in PATH. Install Android Platform Tools.`,{toolName:`adb-bridge`});return this.cachedAdb=e.path??`adb`,this.cachedAdb}async run(e,t){try{return v(await t())}catch(t){throw t instanceof y?t:new y(`RUNTIME`,N(t),{toolName:e})}}async handleDeviceList(e){return this.run(`adb_device_list`,async()=>{let{stdout:e}=await F(await this.resolveAdb(),[`devices`,`-l`]),t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`List of devices`))continue;let r=e.split(/\s+/),i=r[0];if(!i)continue;let a={};for(let e=2;e<r.length;e++){let t=r[e];if(!t)continue;let n=t.indexOf(`:`);if(n>0){let e=t.slice(0,n),r=t.slice(n+1);e&&r&&(a[e]=r)}}t.push({serial:i,state:r[1]??``,model:a.model??``,product:a.product??``})}return{success:!0,count:t.length,devices:t}})}async handleShell(e){return this.run(`adb_shell`,async()=>{let t=x(e,`serial`),n=x(e,`command`),r=T(e,`allowNonZero`)??!0,i=C(e,`timeoutMs`)??g,a=C(e,`maxBufferBytes`),{stdout:o,stderr:s,exitCode:c,signal:l}=await F(await this.resolveAdb(),[...P(t),`shell`,n],{allowNonZero:r,timeoutMs:i,maxBufferBytes:a});return{success:c===0,serial:t,command:n,stdout:o,stderr:s||``,exitCode:c,...l?{signal:l}:{}}})}async handleApkPull(e){return this.run(`adb_apk_pull`,async()=>{let t=x(e,`serial`),n=S(e,`packageName`),r=S(e,`outputPath`)??`.`,i=S(e,`outputFile`),a=T(e,`includeSplits`)??!1,o=T(e,`validateZip`)??!0;if(!n)return{success:!1,error:`packageName is required`};if(a&&i)return{success:!1,error:`outputFile can only be used for a single base APK pull; omit it with includeSplits=true`};let s=await this.resolveAdb(),{stdout:c}=await F(s,[...P(t),`shell`,`pm path ${n}`]),l=I(c);if(l.length===0)return{success:!1,error:`APK not found for ${n}`,raw:c};let u=l.find(e=>/\/base\.apk$/i.test(e))??l[0],d=a?l:[u],p=[];for(let e of d){let c=E(e)||`base.apk`,u=i??O(r,a?`${n}-${L(c)}`:`${n}.apk`);u=u.replace(/\\/g,`/`),await k(D(u),{recursive:!0});let d;try{if((await j(u)).isDirectory()){let e=O(r,`${n}-${L(c)}`).replace(/\\/g,`/`);d=`Destination existed as a directory; wrote to ${e} instead.`,u=e,await k(D(u),{recursive:!0})}}catch{}await F(s,[...P(t),`pull`,e,u],{timeoutMs:f,maxBufferBytes:_});let m=await B(u);if(o&&!m.zipLike)return{success:!1,serial:t,packageName:n,remotePaths:l,error:`Pulled file does not look like a ZIP/APK: ${u}`,localPath:u,size:m.size};p.push({remotePath:e,localPath:u,size:m.size,zipLike:m.zipLike,...d?{warning:d}:{}})}return{success:!0,serial:t,packageName:n,includeSplits:a,remotePaths:l,remotePath:p[0]?.remotePath,localPath:p[0]?.localPath,files:p}})}async handleAnalyzeApk(e){return this.run(`adb_apk_analyze`,async()=>{let t=x(e,`serial`),n=x(e,`packageName`);return{success:!0,serial:t,...await this.buildPackageSummary(t,n)}})}async handlePackageSummary(e){return this.run(`adb_package_summary`,async()=>{let t=x(e,`serial`),n=x(e,`packageName`);return{success:!0,serial:t,...await this.buildPackageSummary(t,n)}})}async buildPackageSummary(e,t){let{stdout:r}=await F(await this.resolveAdb(),[...P(e),`shell`,`dumpsys package ${t}`],{timeoutMs:g,maxBufferBytes:u}),i={packageName:t},a=r.match(/versionName=([^\s]+)/);a?.[1]&&(i.versionName=a[1]);let o=r.match(/versionCode=(\d+)/);o?.[1]&&(i.versionCode=o[1]);let s=r.match(/minSdk=(\d+)/);s?.[1]&&(i.minSdk=s[1]);let c=r.match(/targetSdk=(\d+)/);c?.[1]&&(i.targetSdk=c[1]);let l=z(r);l&&(i.uid=l);let d=[],f=[],p=[],m=[],h=``;for(let e of r.split(/\r?\n/)){if(e.includes(`requested permissions:`)||e.includes(`install permissions:`)){h=`permissions`;continue}if(e.includes(`Activity Resolver Table`)||e.includes(`activities:`)){h=`activities`;continue}if(e.includes(`Service Resolver Table`)||e.includes(`services:`)){h=`services`;continue}if(e.includes(`Receiver Resolver Table`)||e.includes(`receivers:`)){h=`receivers`;continue}let n=e.trim(),r=n.split(/\s+/)[0];h===`permissions`?r&&n.startsWith(`android.permission.`)&&d.push(r):h===`activities`&&n.includes(t)?r&&f.push(r):h===`services`&&n.includes(t)?r&&p.push(r):h===`receivers`&&n.includes(t)&&r&&m.push(r)}i.permissions=[...new Set(d)].slice(0,n),i.activities=[...new Set(f)].slice(0,n),i.services=[...new Set(p)].slice(0,n),i.receivers=[...new Set(m)].slice(0,n),i.nativeLibraryDirs=U(r,t,!0);let _=await this.resolveLauncherActivity(e,t);return _&&(i.launcherActivity=_),i}async resolveLauncherActivity(e,t){let{stdout:n}=await F(await this.resolveAdb(),[...P(e),`shell`,`cmd package resolve-activity --brief ${t} android.intent.action.MAIN`],{allowNonZero:!0,timeoutMs:g});return n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).findLast(e=>e.includes(`/`))}async resolvePackagePid(e,t){let{stdout:n,exitCode:r}=await F(await this.resolveAdb(),[...P(e),`shell`,`pidof -s ${t}`],{allowNonZero:!0,timeoutMs:g});if(r===0)return n.trim().split(/\s+/)[0]||void 0}async handleLogcatQuery(e){return this.run(`adb_logcat_query`,async()=>{let n=x(e,`serial`),r=S(e,`packageName`),i=S(e,`pid`),a=S(e,`pattern`),c=Math.max(1,Math.min(C(e,`tail`)??t,h)),l=Math.max(1,Math.min(C(e,`maxLines`)??s,o)),d=T(e,`clearBefore`)??!1,f=await this.resolveAdb();d&&await F(f,[...P(n),`shell`,`logcat -c`],{allowNonZero:!0,timeoutMs:g}),!i&&r&&(i=await this.resolvePackagePid(n,r));let{stdout:p,stderr:m,exitCode:_}=await F(f,[...P(n),`shell`,`logcat -d -t ${c}`],{allowNonZero:!0,timeoutMs:g,maxBufferBytes:u}),v=a?new RegExp(a,`i`):void 0,y=p.split(/\r?\n/).filter(e=>!(!e.trim()||i&&!e.includes(` ${i} `)||r&&!i&&!e.includes(r)||v&&!v.test(e))).slice(-l);return{success:_===0,serial:n,packageName:r,pid:i,pattern:a,tail:c,count:y.length,lines:y,stderr:m,exitCode:_}})}async handleAppColdStartTrace(e){return this.run(`adb_app_cold_start_trace`,async()=>{let t=x(e,`serial`),n=x(e,`packageName`),a=Math.max(0,Math.min(C(e,`waitMs`)??m,i)),o=Math.max(r,Math.min(C(e,`logcatTail`)??d,p)),s=w(e,`extraPatterns`),c=await this.resolveAdb(),f=S(e,`activity`)??await this.resolveLauncherActivity(t,n);if(!f)return{success:!1,serial:t,packageName:n,error:`Unable to resolve launcher activity`};let h=this.normalizeActivityComponent(n,f);await F(c,[...P(t),`shell`,`am force-stop ${n}`],{allowNonZero:!0,timeoutMs:g}),await F(c,[...P(t),`shell`,`logcat -c`],{allowNonZero:!0,timeoutMs:g});let v=await F(c,[...P(t),`shell`,`am start -W -S ${h}`],{allowNonZero:!0,timeoutMs:g,maxBufferBytes:_});a>0&&await new Promise(e=>setTimeout(e,a));let y=await this.resolvePackagePid(t,n),b=await F(c,[...P(t),`shell`,`logcat -d -t ${o}`],{allowNonZero:!0,timeoutMs:g,maxBufferBytes:u}),T=new RegExp([n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`ActivityManager`,`ActivityTaskManager`,`Displayed`,`Looper`,`Choreographer`,`skipped`,`ANR`,`bindApplication`,`DexHelper`,`secneo`,`dlopen`,`permission`,...s].join(`|`),`i`),E=b.stdout.split(/\r?\n/).filter(e=>e.trim()?y&&e.includes(` ${y} `)?!0:T.test(e):!1).slice(-l),D=E.map(e=>{let t=e.match(/\blatency=(\d+)ms/)?.[1],n=e.match(/\bwall=(\d+)ms/)?.[1];if(!(!t&&!n))return{latencyMs:t?Number(t):void 0,wallMs:n?Number(n):void 0,line:e}}).filter(e=>e!==void 0);return{success:v.exitCode===0,serial:t,packageName:n,activity:h,pid:y,launch:{...R(v.stdout),stdout:v.stdout,stderr:v.stderr,exitCode:v.exitCode},logcat:{tail:o,exitCode:b.exitCode,count:E.length,timeline:E,looperEvents:D}}})}normalizeActivityComponent(e,t){let n=t.trim();return n.includes(`/`)?n:(n.startsWith(`.`)||n.startsWith(e),`${e}/${n}`)}async handleFilePull(e){return this.run(`adb_file_pull`,async()=>{let t=x(e,`serial`),n=x(e,`remotePath`),r=x(e,`localPath`).replace(/\\/g,`/`),i=await this.resolveAdb();await k(D(r),{recursive:!0});let a=await F(i,[...P(t),`pull`,n,r],{timeoutMs:f,maxBufferBytes:_});return{success:!0,serial:t,remotePath:n,localPath:r,size:(await j(r)).size,stdout:a.stdout,stderr:a.stderr}})}async handleFilePush(e){return this.run(`adb_file_push`,async()=>{let t=x(e,`serial`),n=x(e,`localPath`).replace(/\\/g,`/`),r=x(e,`remotePath`),i=await this.resolveAdb(),a=await j(n);if(!a.isFile())return{success:!1,serial:t,localPath:n,remotePath:r,error:`localPath is not a file`};let o=await F(i,[...P(t),`push`,n,r],{timeoutMs:f,maxBufferBytes:_});return{success:!0,serial:t,localPath:n,remotePath:r,size:a.size,stdout:o.stdout,stderr:o.stderr}})}async handlePullNativeLibs(e){return this.run(`adb_pull_native_libs`,async()=>{let t=x(e,`serial`),n=x(e,`packageName`),r=S(e,`outputPath`)??`.`,i=T(e,`includeSystemLibs`)??!1,a=await this.resolveAdb(),{stdout:o}=await F(a,[...P(t),`shell`,`dumpsys package ${n}`]),s=U(o,n,i);if(s.length===0)return{success:!1,serial:t,packageName:n,error:`No native library directories found for ${n}`};let c=O(r,`${n}-native-libs`).replace(/\\/g,`/`);await k(c,{recursive:!0});let l=[];for(let e of s){let n=O(c,e.split(`/`).filter(Boolean).pop()??`lib`).replace(/\\/g,`/`);await k(n,{recursive:!0}),await F(a,[...P(t),`pull`,e,n],{timeoutMs:f,maxBufferBytes:_}),l.push({remoteDir:e,localPath:n})}return{success:!0,serial:t,packageName:n,includeSystemLibs:i,count:l.length,outputPath:c,libraries:l}})}async handleWebViewList(t){return this.run(`adb_webview_list`,async()=>{let n=x(t,`serial`),r=C(t,`hostPort`)??e,i=await this.resolveAdb(),a=await V(i,n);if(a.length===0)return{success:!0,serial:n,hostPort:r,webviews:[],count:0};let o=a[0];await F(i,[...P(n),`forward`,`tcp:${r}`,`localabstract:${o}`]);let s=await import(`node:http`),c=await new Promise(e=>{s.get(`http://localhost:${r}/json/list`,t=>{let n=``;t.on(`data`,e=>{n+=e}),t.on(`end`,()=>{try{e(JSON.parse(n))}catch{e([])}})}).on(`error`,()=>e([]))});return{success:!0,serial:n,hostPort:r,webviews:c.map(e=>({id:e.id,url:e.url,title:e.title,webSocketDebuggerUrl:e.webSocketDebuggerUrl})),count:c.length}})}async handleWebViewAttach(t){return this.run(`adb_webview_attach`,async()=>{let n=x(t,`serial`),r=x(t,`targetId`),i=C(t,`hostPort`)??e,a=await this.resolveAdb(),o=await V(a,n);if(o.length===0)return{success:!1,error:`No WebView devtools sockets found on device`};let s=o[0];await F(a,[...P(n),`forward`,`tcp:${i}`,`localabstract:${s}`]);let c=await import(`node:http`),l=await new Promise(e=>{c.get(`http://localhost:${i}/json`,t=>{let n=``;t.on(`data`,e=>{n+=e}),t.on(`end`,()=>{try{e(JSON.parse(n).find(e=>e.id===r)?.webSocketDebuggerUrl)}catch{e(void 0)}})}).on(`error`,()=>e(void 0))});return l?{success:!0,serial:n,targetId:r,hostPort:i,webSocketDebuggerUrl:l,attached:!0}:{success:!1,error:`Target ${r} not found`}})}};export{W as ADBBridgeHandlers};
@@ -0,0 +1 @@
1
+ import{Un as e}from"./constants-DMv3svps.mjs";import{n as t}from"./ResponseBuilder-nPXl_khE.mjs";import{t as n}from"./renderer-pid-7jbTR8f5.mjs";var r=class{sessionManager;constructor(e){this.sessionManager=e}async handleScanList(e){return t(async()=>{let e=this.sessionManager.listSessions();return{sessions:e,count:e.length}})}async handleScanDelete(e){return t(async()=>({deleted:this.sessionManager.deleteSession(e.sessionId)}))}async handleScanExport(e){return t(async()=>({exportedData:this.sessionManager.exportSession(e.sessionId)}))}};async function i(e,t,r){return await n(e,t,r)}function a(t){return t===void 0||!Number.isFinite(t)||t<=0?e:Math.min(t,e)}var o=class{scanner;eventBus;processManager;ctx;constructor(e,t,n,r){this.scanner=e,this.eventBus=t,this.processManager=n,this.ctx=r}async resolvePid(e){return this.processManager?await i(e,this.processManager,this.ctx):e}async handleFirstScan(e){return t(async()=>{let t=await this.resolvePid(e.pid),n={valueType:e.valueType,alignment:e.alignment,maxResults:a(e.maxResults),regionFilter:e.regionFilter,onProgress:e.onProgress},r=await this.scanner.firstScan(t,e.value,n);return this.eventBus?.emit(`memory:scan_completed`,{scanType:`first`,resultCount:r.totalMatches??0,timestamp:new Date().toISOString()}),{...r,hint:r.totalMatches>0?`Found ${r.totalMatches} matches. Use memory_next_scan with sessionId "${r.sessionId}" to narrow down.`:`No matches found. Try a different value or type.`}})}async handleNextScan(e){return t(async()=>{let t=await this.scanner.nextScan(e.sessionId,e.mode,e.value,e.value2);return{...t,hint:t.totalMatches<=10?`Few matches remaining — inspect these addresses.`:`${t.totalMatches} matches remain. Continue narrowing with memory_next_scan.`}})}async handleUnknownScan(e){return t(async()=>{let t=await this.resolvePid(e.pid),n={valueType:e.valueType,alignment:e.alignment,maxResults:a(e.maxResults),regionFilter:e.regionFilter,onProgress:e.onProgress},r=await this.scanner.unknownInitialScan(t,n);return{...r,hint:`Captured ${r.totalMatches} addresses. Use memory_next_scan with changed/unchanged/increased/decreased to narrow.`}})}async handlePointerScan(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.scanner.pointerScan(t,e.targetAddress,{maxResults:a(e.maxResults),moduleOnly:e.moduleOnly})}})}async handleGroupScan(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.scanner.groupScan(t,e.pattern,{alignment:e.alignment,maxResults:a(e.maxResults)})}})}},s=class{ptrEngine;processManager;ctx;constructor(e,t,n){this.ptrEngine=e,this.processManager=t,this.ctx=n}async resolvePid(e){return this.processManager?await i(e,this.processManager,this.ctx):e}async handlePointerChainScan(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.ptrEngine.scan(t,e.targetAddress,{maxDepth:e.maxDepth,maxOffset:e.maxOffset,staticOnly:e.staticOnly,modules:e.modules,maxResults:e.maxResults});return{...n,hint:n.totalFound>0?`Found ${n.totalFound} pointer chains. Static chains survive process restarts.`:`No pointer chains found. Try increasing maxDepth or maxOffset.`}})}async handlePointerChainValidate(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=JSON.parse(e.chains),r=await this.ptrEngine.validateChains(t,n);return{results:r,validCount:r.filter(e=>e.isValid).length,totalChecked:n.length}})}async handlePointerChainResolve(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=JSON.parse(e.chain),r=await this.ptrEngine.resolveChain(t,n);return{chainId:n.id,resolvedAddress:r,isResolvable:r!==null}})}async handlePointerChainExport(e){return t(async()=>{let t=JSON.parse(e.chains);return{exportedData:this.ptrEngine.exportChains(t),chainCount:t.length}})}};const c={int8_t:`int8`,uint8_t:`uint8`,int16_t:`int16`,uint16_t:`uint16`,int32_t:`int32`,uint32_t:`uint32`,int64_t:`int64`,uint64_t:`uint64`,void_ptr:`pointer`,char_ptr:`string_ptr`};function l(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase().replace(/\s+/g,`_`).replace(/\*/g,`_ptr`);return c[t]??t}function u(e){if(!e||typeof e!=`object`)throw Error(`structure must be a JSON object`);let t=e,n=(Array.isArray(t.fields)?t.fields:[]).map((e,t)=>{let n=e;return{offset:typeof n.offset==`number`?n.offset:0,size:typeof n.size==`number`?n.size:1,type:l(n.type),name:typeof n.name==`string`&&n.name.length>0?n.name:`field_${t}`,value:typeof n.value==`string`?n.value:``,confidence:typeof n.confidence==`number`?n.confidence:1,notes:typeof n.notes==`string`?n.notes:void 0}}),r=n.reduce((e,t)=>Math.max(e,t.offset+t.size),0),i=typeof t.totalSize==`number`?t.totalSize:typeof t.size==`number`?t.size:r;return{baseAddress:typeof t.baseAddress==`string`?t.baseAddress:`0x0`,totalSize:i,fields:n,vtableAddress:typeof t.vtableAddress==`string`?t.vtableAddress:void 0,className:typeof t.className==`string`?t.className:void 0,baseClasses:Array.isArray(t.baseClasses)?t.baseClasses.filter(e=>typeof e==`string`):void 0,timestamp:typeof t.timestamp==`number`?t.timestamp:Date.now()}}var d=class{structAnalyzer;processManager;ctx;constructor(e,t,n){this.structAnalyzer=e,this.processManager=t,this.ctx=n}async resolvePid(e){return this.processManager?await i(e,this.processManager,this.ctx):e}async handleStructureAnalyze(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.structAnalyzer.analyzeStructure(t,e.address,{size:e.size,otherInstances:e.otherInstances,parseRtti:e.parseRtti});return{...n,hint:n.className?`Detected class: ${n.className}${n.baseClasses?.length?` (inherits: ${n.baseClasses.join(` → `)})`:``}`:`Inferred ${n.fields.length} fields. Use memory_structure_export_c to export as C struct.`}})}async handleVtableParse(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.structAnalyzer.parseVtable(t,e.vtableAddress)}})}async handleStructureExportC(e){return t(async()=>{let t=u(JSON.parse(e.structure));return{...this.structAnalyzer.exportToCStruct(t,e.name)}})}async handleStructureCompare(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.structAnalyzer.compareInstances(t,e.address1,e.address2,e.size);return{matchingFieldCount:n.matching.length,differingFieldCount:n.differing.length,...n}})}},f=class{bpEngine;injector;processManager;ctx;constructor(e,t,n,r){this.bpEngine=e,this.injector=t,this.processManager=n,this.ctx=r}async resolvePid(e){return this.processManager?await i(e,this.processManager,this.ctx):e}async handleBreakpointSet(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.bpEngine.setBreakpoint(t,e.address,e.access,e.size??4),hint:`Hardware breakpoint set on DR register. Use memory_breakpoint with action='trace' to collect hits.`}})}async handleBreakpointRemove(e){return t(async()=>({removed:await this.bpEngine.removeBreakpoint(e.breakpointId)}))}async handleBreakpointList(e){return t(async()=>{let e=this.bpEngine.listBreakpoints();return{breakpoints:e,count:e.length}})}async handleBreakpointTrace(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.bpEngine.traceAccess(t,e.address,e.access,e.maxHits,e.timeoutMs);return{hits:n,hitCount:n.length,hint:n.length>0?`${n.length} accesses captured. Check instructionAddress to find the code accessing this address.`:`No hits captured within timeout.`}})}async handlePatchBytes(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.injector.patchBytes(t,e.address,e.bytes);return{...n,hint:`Patch applied. Use memory_patch_undo with patchId "${n.id}" to restore.`}})}async handlePatchNop(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.injector.nopBytes(t,e.address,e.count),hint:`${e.count} bytes NOP'd. Use memory_patch_undo to restore.`}})}async handlePatchUndo(e){return t(async()=>({restored:await this.injector.unpatch(e.patchId)}))}async handleCodeCaves(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.injector.findCodeCaves(t,e.minSize);return{caves:n,count:n.length}})}},p=class{memCtrl;processManager;ctx;constructor(e,t,n){this.memCtrl=e,this.processManager=t,this.ctx=n}async resolvePid(e){return this.processManager?await i(e,this.processManager,this.ctx):e}async handleWriteValue(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.memCtrl.writeValue(t,e.address,e.value,e.valueType),hint:`Use memory_write_history with action='undo' to revert.`}})}async handleFreeze(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.memCtrl.freeze(t,e.address,e.value,e.valueType,e.intervalMs);return{...n,hint:`Frozen. Use memory_freeze with action="unfreeze" and freezeId "${n.id}" to stop.`}})}async handleUnfreeze(e){return t(async()=>({unfrozen:await this.memCtrl.unfreeze(e.freezeId)}))}async handleDump(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{dump:await this.memCtrl.dumpMemoryHex(t,e.address,e.size??256)}})}async handleWriteUndo(e){return t(async()=>{let e=await this.memCtrl.undo();return{undone:e!==null,entry:e}})}async handleWriteRedo(e){return t(async()=>{let e=await this.memCtrl.redo();return{redone:e!==null,entry:e}})}},m=class{speedhackEngine;heapAnalyzer;peAnalyzer;antiCheatDetector;processManager;ctx;constructor(e,t,n,r,i,a){this.speedhackEngine=e,this.heapAnalyzer=t,this.peAnalyzer=n,this.antiCheatDetector=r,this.processManager=i,this.ctx=a}async resolvePid(e){return this.processManager?await i(e,this.processManager,this.ctx):e}async handleSpeedhackApply(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.speedhackEngine.apply(t,e.speed),hint:`Speedhack active (${e.speed}x). Use memory_speedhack({ action: 'set' }) to adjust.`}})}async handleSpeedhackSet(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{updated:await this.speedhackEngine.setSpeed(t,e.speed),newSpeed:e.speed}})}async handleHeapEnumerate(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.heapAnalyzer.enumerateHeaps(t);return{...n,hint:`Enumerated ${n.heaps.length} heaps. Use memory_heap_stats for statistics or memory_heap_anomalies to check for issues.`}})}async handleHeapStats(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.heapAnalyzer.getStats(t)}})}async handleHeapAnomalies(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.heapAnalyzer.detectAnomalies(t);return{anomalies:n,count:n.length,hint:n.length>0?`Found ${n.length} anomalies — inspect types for spray, UAF, or suspicious patterns.`:`No heap anomalies detected.`}})}async handlePEHeaders(e){return t(async()=>{let t=await this.resolvePid(e.pid);return{...await this.peAnalyzer.parseHeaders(t,e.moduleBase)}})}async handlePEImportsExports(e){return t(async()=>{let t=e.table||`both`,n=e.moduleBase,r=await this.resolvePid(e.pid),i={};return(t===`imports`||t===`both`)&&(i.imports=await this.peAnalyzer.parseImports(r,n)),(t===`exports`||t===`both`)&&(i.exports=await this.peAnalyzer.parseExports(r,n)),i})}async handleInlineHookDetect(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.peAnalyzer.detectInlineHooks(t,e.moduleName);return{hooks:n,count:n.length,hint:n.length>0?`Detected ${n.length} inline hooks — check hookType and jumpTarget for each.`:`No inline hooks detected — exports match disk bytes.`}})}async handleAntiCheatDetect(e){return t(async()=>{let t=await this.resolvePid(e.pid),n=await this.antiCheatDetector.detect(t);return{detections:n,count:n.length,hint:n.length>0?`Found ${n.length} anti-debug mechanisms. Each includes a bypassSuggestion.`:`No anti-debug mechanisms detected in imports.`}})}async handleGuardPages(e){return t(async()=>{let t=await this.resolvePid(e.pid),{guardPages:n,stats:r}=await this.antiCheatDetector.scanGuardPages(t);return{guardPages:n,count:n.length,scan:r,hint:r.truncated?`Scan stopped after ${r.scannedRegions} regions in ${r.durationMs}ms to avoid hanging. Results may be partial.`:n.length>0?`Found ${n.length} guard page regions — these may indicate anti-tampering.`:`No guard pages found.`}})}async handleIntegrityCheck(e){return t(async()=>{let t=await this.resolvePid(e.pid),{sections:n,stats:r}=await this.antiCheatDetector.scanIntegrity(t,e.moduleName),i=n.filter(e=>e.isModified);return{sections:n,totalChecked:n.length,modifiedCount:i.length,scan:r,hint:r.truncated?`Checked ${r.scannedSections} executable section(s) across ${r.scannedModules} module(s) before hitting safety limits. Results may be partial.`:i.length>0?`${i.length} section(s) modified — code may have been patched or hooked.`:`All checked sections match disk — no runtime modifications detected.`}})}},h=class{sessions;scans;ptrChains;structures;hooks;readwrite;integrity;constructor(e,t,n,i,a,c,l,u,h,g,_,v,y,b){this.sessions=new r(t),this.scans=new o(e,v,y,b),this.ptrChains=new s(n,y,b),this.structures=new d(i,y,b),this.hooks=new f(a,c,y,b),this.readwrite=new p(l,y,b),this.integrity=new m(u,h,g,_,y,b)}handleScanSessionDispatch(e){switch(String(e.action??``)){case`delete`:return this.sessions.handleScanDelete(e);case`export`:return this.sessions.handleScanExport(e);default:return this.sessions.handleScanList(e)}}handleScanList=e=>this.sessions.handleScanList(e);handleScanDelete=e=>this.sessions.handleScanDelete(e);handleScanExport=e=>this.sessions.handleScanExport(e);handleFirstScan=e=>this.scans.handleFirstScan(e);handleNextScan=e=>this.scans.handleNextScan(e);handleUnknownScan=e=>this.scans.handleUnknownScan(e);handlePointerScan=e=>this.scans.handlePointerScan(e);handleGroupScan=e=>this.scans.handleGroupScan(e);handlePointerChainDispatch(e){switch(String(e.action??``)){case`validate`:return this.ptrChains.handlePointerChainValidate(e);case`resolve`:return this.ptrChains.handlePointerChainResolve(e);case`export`:return this.ptrChains.handlePointerChainExport(e);default:return this.ptrChains.handlePointerChainScan(e)}}handlePointerChainScan=e=>this.ptrChains.handlePointerChainScan(e);handlePointerChainValidate=e=>this.ptrChains.handlePointerChainValidate(e);handlePointerChainResolve=e=>this.ptrChains.handlePointerChainResolve(e);handlePointerChainExport=e=>this.ptrChains.handlePointerChainExport(e);handleStructureAnalyze=e=>this.structures.handleStructureAnalyze(e);handleVtableParse=e=>this.structures.handleVtableParse(e);handleStructureExportC=e=>this.structures.handleStructureExportC(e);handleStructureCompare=e=>this.structures.handleStructureCompare(e);handleBreakpointDispatch(e){switch(String(e.action??``)){case`remove`:return this.hooks.handleBreakpointRemove(e);case`list`:return this.hooks.handleBreakpointList(e);case`trace`:return this.hooks.handleBreakpointTrace(e);default:return this.hooks.handleBreakpointSet(e)}}handleBreakpointSet=e=>this.hooks.handleBreakpointSet(e);handleBreakpointRemove=e=>this.hooks.handleBreakpointRemove(e);handleBreakpointList=e=>this.hooks.handleBreakpointList(e);handleBreakpointTrace=e=>this.hooks.handleBreakpointTrace(e);handlePatchBytes=e=>this.hooks.handlePatchBytes(e);handlePatchNop=e=>this.hooks.handlePatchNop(e);handlePatchUndo=e=>this.hooks.handlePatchUndo(e);handleCodeCaves=e=>this.hooks.handleCodeCaves(e);handleFreezeDispatch(e){return String(e.action??``)===`unfreeze`?this.readwrite.handleUnfreeze(e):this.readwrite.handleFreeze(e)}handleWriteHistoryDispatch(e){return String(e.action??``)===`redo`?this.readwrite.handleWriteRedo(e):this.readwrite.handleWriteUndo(e)}handleWriteValue=e=>this.readwrite.handleWriteValue(e);handleFreeze=e=>this.readwrite.handleFreeze(e);handleUnfreeze=e=>this.readwrite.handleUnfreeze(e);handleDump=e=>this.readwrite.handleDump(e);handleWriteUndo=e=>this.readwrite.handleWriteUndo(e);handleWriteRedo=e=>this.readwrite.handleWriteRedo(e);handleSpeedhackDispatch(e){return String(e.action??``)===`set`?this.integrity.handleSpeedhackSet(e):this.integrity.handleSpeedhackApply(e)}handleSpeedhackApply=e=>this.integrity.handleSpeedhackApply(e);handleSpeedhackSet=e=>this.integrity.handleSpeedhackSet(e);handleHeapEnumerate=e=>this.integrity.handleHeapEnumerate(e);handleHeapStats=e=>this.integrity.handleHeapStats(e);handleHeapAnomalies=e=>this.integrity.handleHeapAnomalies(e);handlePEHeaders=e=>this.integrity.handlePEHeaders(e);handlePEImportsExports=e=>this.integrity.handlePEImportsExports(e);handleInlineHookDetect=e=>this.integrity.handleInlineHookDetect(e);handleAntiCheatDetect=e=>this.integrity.handleAntiCheatDetect(e);handleGuardPages=e=>this.integrity.handleGuardPages(e);handleIntegrityCheck=e=>this.integrity.handleIntegrityCheck(e)};export{h as MemoryScanHandlers};