@jshookmcp/jshook 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
- package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
- package/dist/CodeInjector-Btj9upnf.mjs +1 -0
- package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
- package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
- package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
- package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
- package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
- package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
- package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
- package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
- package/dist/MemoryScanner-Dxd657li.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
- package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
- package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
- package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
- package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
- package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
- package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
- package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
- package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
- package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
- package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
- package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
- package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
- package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
- package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
- package/dist/antidebug-CsnpOR9z.mjs +1 -0
- package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
- package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
- package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
- package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
- package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
- package/dist/browser-BUaB25bk.mjs +11 -0
- package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
- package/dist/collector-CB2syQEg.mjs +1 -0
- package/dist/constants-DMv3svps.mjs +2 -0
- package/dist/coordination-Dbohmj6D.mjs +1 -0
- package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
- package/dist/debugger-CLzkObIO.mjs +1 -0
- package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
- package/dist/definitions-B3a9QC2t.mjs +1 -0
- package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
- package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
- package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
- package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
- package/dist/definitions-DBYSxChX.mjs +1 -0
- package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
- package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
- package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
- package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
- package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
- package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
- package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
- package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
- package/dist/definitions-EGmqr85H.mjs +1 -0
- package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
- package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
- package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
- package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
- package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
- package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
- package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
- package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
- package/dist/handlers-6iNsXOVT.mjs +7 -0
- package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
- package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
- package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
- package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
- package/dist/handlers-CWKBBjai.mjs +1 -0
- package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
- package/dist/handlers-CrJsKnEI.mjs +1 -0
- package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
- package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
- package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
- package/dist/handlers-gVscChvl.mjs +1 -0
- package/dist/handlers-xFvI9P_y.mjs +1 -0
- package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
- package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
- package/dist/index.mjs +11 -11
- package/dist/macro-p8kuJVcm.mjs +2 -0
- package/dist/maintenance-DAqADb6Z.mjs +302 -0
- package/dist/manifest-4lmM6MZR.mjs +1 -0
- package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
- package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
- package/dist/manifest-Box-jWfr.mjs +1 -0
- package/dist/manifest-Bp33di0Q.mjs +1 -0
- package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
- package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
- package/dist/manifest-C7TdXCWY.mjs +1 -0
- package/dist/manifest-CM-n64K0.mjs +1 -0
- package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
- package/dist/manifest-CWJS45iO.mjs +1 -0
- package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
- package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
- package/dist/manifest-Cgxu2qdv.mjs +1 -0
- package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
- package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
- package/dist/manifest-CvDpVToN.mjs +1 -0
- package/dist/manifest-D8TL9RLE.mjs +1 -0
- package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
- package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
- package/dist/manifest-DLGtZH-0.mjs +1 -0
- package/dist/manifest-DXHdPt2T.mjs +1 -0
- package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
- package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
- package/dist/manifest-G2H52LKz.mjs +131 -0
- package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
- package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
- package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
- package/dist/manifest-dG6MuR1U.mjs +1 -0
- package/dist/manifest-nWXtgq5Y2.mjs +1 -0
- package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
- package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
- package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
- package/dist/native-g095qhpK.mjs +961 -0
- package/dist/network-Dvxm7eEI.mjs +7 -0
- package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
- package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
- package/dist/platform-DjWbuiF8.mjs +93 -0
- package/dist/process-Dq5I-KZW.mjs +2 -0
- package/dist/proxy-DPNgM7TE.mjs +2 -0
- package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
- package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
- package/dist/search-defaults-CJik67or.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/sourcemap-DqEW15Ao.mjs +1 -0
- package/dist/streaming-Dbk4eStJ.mjs +1 -0
- package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
- package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
- package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
- package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
- package/package.json +2 -2
- package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
- package/dist/DOMInspector-C19J4zeq.mjs +0 -95
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
- package/dist/ExtensionManager-BD724zkO.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
- package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
- package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
- package/dist/PageController-Dfsm1_o7.mjs +0 -1
- package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
- package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
- package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
- package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
- package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
- package/dist/VersionDetector-CHT36Az0.mjs +0 -9
- package/dist/apk-packer-BqXcInnX.mjs +0 -1
- package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
- package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
- package/dist/browser-Qqco2rOT.mjs +0 -11
- package/dist/collector-Bpl6qy2L.mjs +0 -1
- package/dist/constants-BYj8Xek8.mjs +0 -1
- package/dist/coordination-CWXW1o8K.mjs +0 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/debugger-DyALjYMk.mjs +0 -1
- package/dist/definitions-BftdXgXI.mjs +0 -1
- package/dist/definitions-Bio5XJYy.mjs +0 -1
- package/dist/definitions-CMZRSy3k.mjs +0 -1
- package/dist/definitions-DP1vgxEY.mjs +0 -1
- package/dist/definitions-Tls8c0A0.mjs +0 -1
- package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
- package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
- package/dist/handlers-8zN_vBIz.mjs +0 -1
- package/dist/handlers-DHO3rjsW.mjs +0 -1
- package/dist/handlers-FJ80VzUI.mjs +0 -2
- package/dist/handlers-VHWrxbM_.mjs +0 -1
- package/dist/handlers-mPFiNPe8.mjs +0 -302
- package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
- package/dist/maintenance-BUpIukhg.mjs +0 -1
- package/dist/manifest-B7NB2rh2.mjs +0 -1
- package/dist/manifest-BDi4nbH1.mjs +0 -1
- package/dist/manifest-BLDfkE7n.mjs +0 -1
- package/dist/manifest-BcXbB4gf.mjs +0 -1
- package/dist/manifest-Bdnc_vrc.mjs +0 -1
- package/dist/manifest-BuYKgCnp.mjs +0 -1
- package/dist/manifest-CBfNnGPV.mjs +0 -1
- package/dist/manifest-CPS1Xv69.mjs +0 -1
- package/dist/manifest-CRryuZF4.mjs +0 -1
- package/dist/manifest-CvTe5ZGV2.mjs +0 -1
- package/dist/manifest-D-5GH0DV.mjs +0 -1
- package/dist/manifest-D3Ssf3IC.mjs +0 -1
- package/dist/manifest-D5ck3NvC.mjs +0 -1
- package/dist/manifest-DG19q-Ld.mjs +0 -1
- package/dist/manifest-DLMlD0Zc.mjs +0 -1
- package/dist/manifest-DwL2ik8P.mjs +0 -1
- package/dist/manifest-ItF5P8A12.mjs +0 -1
- package/dist/manifest-KZphqIyX.mjs +0 -1
- package/dist/manifest-RcpX_MyZ.mjs +0 -123
- package/dist/manifest-Zy7Odg5J.mjs +0 -1
- package/dist/manifest-ff1H7Pdp.mjs +0 -1
- package/dist/manifest-iuhF6pTL2.mjs +0 -1
- package/dist/manifest-yC16OhL2.mjs +0 -1
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
- package/dist/native-j8l473zn.mjs +0 -961
- package/dist/network-T0VRwNPd.mjs +0 -7
- package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
- package/dist/platform-CzaQtISh.mjs +0 -93
- package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
- package/dist/process-CWhsCWrf.mjs +0 -2
- package/dist/proxy-DZFlDsG3.mjs +0 -2
- package/dist/search-defaults-lYBVn_3L.mjs +0 -1
- package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
- package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
- package/dist/streaming-BcJ0B6ao.mjs +0 -1
- package/dist/types-D9EiE5o9.mjs +0 -1
- /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
- /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
- /package/dist/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
- /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.mjs} +0 -0
- /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
- /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
- /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
- /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
- /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
- /package/dist/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
- /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
- /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
- /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
- /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
- /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
- /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
- /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
package/README.md
CHANGED
|
@@ -65,9 +65,9 @@ No global install needed — add to your MCP client config and you're ready:
|
|
|
65
65
|
The built-in surface below is generated from the runtime registry and checked in CI.
|
|
66
66
|
|
|
67
67
|
<!-- metadata-sync:start -->
|
|
68
|
-
- Package version: `0.3.
|
|
69
|
-
- Built-in Tools: `
|
|
70
|
-
- Domains: `adb-bridge`, `
|
|
68
|
+
- Package version: `0.3.3`
|
|
69
|
+
- Built-in Tools: `451`
|
|
70
|
+
- Domains: `adb-bridge`, `binary-instrument`, `boringssl-inspector`, `browser`, `canvas`, `coordination`, `core`, `cross-domain`, `dart-inspector`, `debugger`, `encoding`, `extension-registry`, `graphql`, `instrumentation`, `maintenance`, `memory`, `mojo-ipc`, `native-emulator`, `network`, `platform`, `process`, `protocol-analysis`, `proxy`, `sourcemap`, `streaming`, `syscall-hook`, `trace`, `transform`, `v8-inspector`, `wasm`, `workflow`
|
|
71
71
|
- Note: this snapshot is generated from the runtime registry; do not edit the counts by hand.
|
|
72
72
|
<!-- metadata-sync:end -->
|
|
73
73
|
|
package/README.zh.md
CHANGED
|
@@ -65,9 +65,9 @@
|
|
|
65
65
|
下面的内置能力快照由运行时 registry 动态生成,并在 CI 中校验。
|
|
66
66
|
|
|
67
67
|
<!-- metadata-sync:start -->
|
|
68
|
-
- 包版本:`0.3.
|
|
69
|
-
- 内置工具数:`
|
|
70
|
-
- 域列表:`adb-bridge`, `
|
|
68
|
+
- 包版本:`0.3.3`
|
|
69
|
+
- 内置工具数:`451`
|
|
70
|
+
- 域列表:`adb-bridge`, `binary-instrument`, `boringssl-inspector`, `browser`, `canvas`, `coordination`, `core`, `cross-domain`, `dart-inspector`, `debugger`, `encoding`, `extension-registry`, `graphql`, `instrumentation`, `maintenance`, `memory`, `mojo-ipc`, `native-emulator`, `network`, `platform`, `process`, `protocol-analysis`, `proxy`, `sourcemap`, `streaming`, `syscall-hook`, `trace`, `transform`, `v8-inspector`, `wasm`, `workflow`
|
|
71
71
|
- 说明:以上数据由运行时 registry 动态生成,不要手改计数。
|
|
72
72
|
<!-- metadata-sync:end -->
|
|
73
73
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{a as t,b as n,d as r,h as i,i as a,n as o,s,t as c,u as l}from"./Win32API-DoP3MMHS.mjs";import{PEAnalyzer as u}from"./PEAnalyzer-CMu9Ua9T.mjs";import{promises as d}from"node:fs";import{createHash as f}from"node:crypto";const p=[{dll:`kernel32.dll`,funcs:[{name:`IsDebuggerPresent`,mechanism:`anti_debug_api`,confidence:`high`,bypass:`Hook IsDebuggerPresent to return 0, or patch PEB.BeingDebugged field`},{name:`CheckRemoteDebuggerPresent`,mechanism:`anti_debug_api`,confidence:`high`,bypass:`Hook CheckRemoteDebuggerPresent to set output to FALSE and return TRUE`},{name:`OutputDebugStringA`,mechanism:`exception_based`,confidence:`low`,bypass:`May be used for anti-debug timing — monitor for exception handler abuse`},{name:`GetTickCount`,mechanism:`timing_check`,confidence:`low`,bypass:`Hook GetTickCount to return consistent delta values`},{name:`GetTickCount64`,mechanism:`timing_check`,confidence:`low`,bypass:`Hook GetTickCount64 to return consistent delta values`},{name:`QueryPerformanceCounter`,mechanism:`timing_check`,confidence:`medium`,bypass:`Hook QPC to filter out debugging time deltas`}]},{dll:`ntdll.dll`,funcs:[{name:`NtQueryInformationProcess`,mechanism:`ntquery_debug`,confidence:`high`,bypass:`Hook NtQueryInformationProcess: return 0 for ProcessDebugPort (7), ProcessDebugObjectHandle (30), ProcessDebugFlags (31)`},{name:`NtSetInformationThread`,mechanism:`thread_hiding`,confidence:`medium`,bypass:`Hook NtSetInformationThread: intercept ThreadHideFromDebugger (0x11) calls`},{name:`NtClose`,mechanism:`exception_based`,confidence:`low`,bypass:`NtClose with invalid handle detects debugger via exception — hook to suppress`},{name:`RtlGetNtGlobalFlags`,mechanism:`heap_flags`,confidence:`medium`,bypass:`Clear NtGlobalFlag (FLG_HEAP_*) in PEB at offset 0xBC (x64)`}]}],m=[`GetThreadContext`,`SetThreadContext`],h={guardPageMaxRegions:2e4,guardPageTimeoutMs:2e3,integrityMaxModules:32,integrityMaxSections:128,integrityMaxBytes:16*1024*1024,integrityMaxSectionBytes:2*1024*1024,integrityTimeoutMs:3e3};var g=class{peAnalyzer=new u;options;constructor(e={}){this.options={...h,...e}}async detect(t){let r=[],i=n(t);try{let n=this.enumerateModules(i);for(let i of n)try{let e=await this.peAnalyzer.parseImports(t,i.base);for(let t of e){let e=t.dllName.toLowerCase();for(let n of p)if(e.includes(n.dll.toLowerCase().replace(`.dll`,``)))for(let e of n.funcs)t.functions.some(t=>t.name===e.name)&&r.push({mechanism:e.mechanism,confidence:e.confidence,location:`import:${e.name}`,moduleName:i.name,details:`${i.name} imports ${e.name} from ${t.dllName}`,bypassSuggestion:e.bypass});for(let e of t.functions)m.includes(e.name)&&r.push({mechanism:`hardware_breakpoint`,confidence:`medium`,location:`import:${e.name}`,moduleName:i.name,details:`${i.name} imports ${e.name} — may check debug registers for hardware breakpoints`,bypassSuggestion:`Hook GetThreadContext to zero out DR0-DR3 and DR6/DR7 before returning`})}}catch(t){e.debug(`Import scan skipped for ${i.name}: ${t}`)}}finally{c(i)}return r}async findGuardPages(e){return(await this.scanGuardPages(e)).guardPages}async scanGuardPages(e){let t=[],r=n(e),a=Date.now(),o={scannedRegions:0,queryFailures:0,durationMs:0,timedOut:!1,truncated:!1,maxRegions:this.options.guardPageMaxRegions,timeoutMs:this.options.guardPageTimeoutMs};try{let e=this.enumerateModules(r),n=0n;for(;n<140737488355327n;){if(this.isTimedOut(a,o.timeoutMs)){o.timedOut=!0,o.truncated=!0;break}if(o.scannedRegions>=o.maxRegions){o.truncated=!0;break}try{let a=i(r,n);if(!a.success)break;let s=a.info,c=s.BaseAddress+s.RegionSize;if(o.scannedRegions+=1,(s.Protect&l.GUARD)!==0){let n=null;for(let t of e){let e=BigInt(t.base);if(s.BaseAddress>=e&&s.BaseAddress<e+BigInt(t.size)){n=t.name;break}}t.push({address:`0x${s.BaseAddress.toString(16)}`,size:Number(s.RegionSize),moduleName:n,nearbySymbol:null})}if(s.RegionSize<=0n||c<=n||c<=s.BaseAddress){o.truncated=!0;break}n=c}catch{o.queryFailures+=1,n+=4096n}}}finally{o.durationMs=Date.now()-a,c(r)}return{guardPages:t,stats:o}}async checkIntegrity(e,t){return(await this.scanIntegrity(e,t)).sections}async scanIntegrity(t,i){let a=[],o=n(t),s=Date.now(),l={scannedModules:0,scannedSections:0,hashedBytes:0,skippedModules:0,skippedSections:0,durationMs:0,timedOut:!1,truncated:!1,maxModules:this.options.integrityMaxModules,maxSections:this.options.integrityMaxSections,maxBytes:this.options.integrityMaxBytes,timeoutMs:this.options.integrityTimeoutMs},u=!1;try{let n=this.enumerateModules(o),c=i?n.filter(e=>e.name.toLowerCase().includes(i.toLowerCase())):n;for(let n of c){if(this.shouldStopIntegrityScan(l,s)){this.isTimedOut(s,l.timeoutMs)&&(l.timedOut=!0),l.truncated=!0;break}l.scannedModules+=1;try{let e=await d.readFile(n.path),i=await this.peAnalyzer.listSections(t,n.base);for(let t of i){if(this.shouldStopIntegrityScan(l,s)){this.isTimedOut(s,l.timeoutMs)&&(l.timedOut=!0),l.truncated=!0,u=!0;break}if(!t.isExecutable)continue;let i=parseInt(t.virtualAddress,16),c=Math.min(t.virtualSize,t.rawSize);if(c<=0)continue;if(c>this.options.integrityMaxSectionBytes){l.skippedSections+=1;continue}if(l.hashedBytes+c>l.maxBytes){l.truncated=!0,u=!0;break}let d=r(o,BigInt(n.base)+BigInt(i),c),p=this.rvaToFileOffset(e,i);if(p<0||p+c>e.length)continue;let m=e.subarray(p,p+c),h=f(`sha256`).update(d).digest(`hex`),g=f(`sha256`).update(m).digest(`hex`);a.push({sectionName:t.name,moduleName:n.name,diskHash:g,memoryHash:h,isModified:h!==g}),l.scannedSections+=1,l.hashedBytes+=c}}catch(t){l.skippedModules+=1,e.debug(`Integrity check skipped for ${n.name}: ${t}`)}if(u)break}}finally{l.durationMs=Date.now()-s,c(o)}return{sections:a,stats:l}}enumerateModules(n){let r=[];try{let{modules:e,count:i}=o(n);for(let o=0;o<i;o++){let i=e[o],c=a(n,i),l=s(n,i),u=t(n,i)??c;l.success&&r.push({name:c,base:`0x${l.info.lpBaseOfDll.toString(16)}`,path:u,size:l.info.SizeOfImage})}}catch(t){e.debug(`Module enumeration failed: ${t}`)}return r}rvaToFileOffset(e,t){let n=e.readUInt32LE(60),r=e.readUInt16LE(n+6),i=e.readUInt16LE(n+20),a=n+24+i;for(let n=0;n<r;n++){let r=a+n*40;if(r+40>e.length)break;let i=e.readUInt32LE(r+12),o=e.readUInt32LE(r+8),s=e.readUInt32LE(r+20);if(t>=i&&t<i+o)return s+(t-i)}return-1}isTimedOut(e,t){return Date.now()-e>=t}shouldStopIntegrityScan(e,t){return this.isTimedOut(t,e.timeoutMs)||e.scannedModules>=e.maxModules||e.scannedSections>=e.maxSections||e.hashedBytes>=e.maxBytes}};const _=new g;export{g as AntiCheatDetector,_ as antiCheatDetector};
|
package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{AsyncLocalStorage as t}from"node:async_hooks";let n=0;var r=class{pageIdByHandle=new WeakMap;tabsById=new Map;aliasToPageId=new Map;currentPageId=null;sharedContext=new Map;upsertPage(e,t){let n=this.pageIdByHandle.get(e),r=n?this.tabsById.get(n)?.meta:null,i=typeof t.index==`number`&&Number.isFinite(t.index)?t.index:r?.index??0;return this.registerPage(e,{index:i,url:t.url,title:t.title})}registerPage(t,r){let i=t,a=this.pageIdByHandle.get(i);if(a){let e=this.tabsById.get(a);return e?(e.meta=r,e.stale=!1):this.tabsById.set(a,{page:t,meta:r,stale:!1}),a}n+=1;let o=`tab-${n}`;return this.pageIdByHandle.set(i,o),this.tabsById.set(o,{page:t,meta:r,stale:!1}),e.debug(`[TabRegistry] Registered page ${o} (index=${r.index}, url=${r.url})`),o}reconcilePages(t,n){let r=new Set;for(let e=0;e<t.length;e++){let i=t[e],a=n[e]??{index:e,url:``,title:``},o=this.registerPage(i,{...a,index:e});r.add(o)}let i=[];for(let[t,n]of this.tabsById)r.has(t)||(n.stale?i.push(t):(n.stale=!0,e.debug(`[TabRegistry] Page ${t} marked stale`)));for(let t of i)this.tabsById.delete(t),e.debug(`[TabRegistry] Page ${t} pruned (was already stale)`);return this.currentPageId&&!r.has(this.currentPageId)&&(e.debug(`[TabRegistry] Current page ${this.currentPageId} is stale, clearing`),this.currentPageId=null),this.listTabs()}bindAlias(e,t){return this.tabsById.has(t)?(this.aliasToPageId.set(e,t),!0):!1}bindAliasByIndex(e,t){for(let[n,r]of this.tabsById)if(r.meta.index===t&&!r.stale)return this.aliasToPageId.set(e,n),n;return null}unbindAlias(e){return this.aliasToPageId.delete(e)}resolveAlias(e){let t=this.aliasToPageId.get(e);if(!t)return null;let n=this.tabsById.get(t);return!n||n.stale?null:t}getPageById(e){let t=this.tabsById.get(e);return!t||t.stale?null:t.page}getTabById(e){let t=this.tabsById.get(e);if(!t)return null;let n=this.getAliasesForPageId(e);return{pageId:e,index:t.meta.index,url:t.meta.url,title:t.meta.title,page:t.page,aliases:n,stale:t.stale}}getTabByIndex(e){for(let[t,n]of this.tabsById)if(n.meta.index===e&&!n.stale)return this.getTabById(t);return null}findTab(e){for(let[t]of this.tabsById){let n=this.getTabById(t);if(n&&e(n))return n}return null}setCurrentPageId(e){let t=this.tabsById.get(e);return!t||t.stale?!1:(this.currentPageId=e,!0)}setCurrentByIndex(e){let t=this.getTabByIndex(e);return t&&(this.currentPageId=t.pageId),t}getCurrentPageId(){return this.currentPageId}getCurrentPage(){return this.currentPageId?this.getPageById(this.currentPageId):null}getCurrentTabInfo(e){let t=[],n=[];for(let[e,r]of this.aliasToPageId){let i=this.tabsById.get(r),a=!i||i.stale;t.push({alias:e,pageId:r,index:i?.meta.index??null,stale:a}),a&&n.push(e)}let r=this.currentPageId?this.tabsById.get(this.currentPageId):null,i=r&&!r.stale?r:null;return{driver:e,currentPageId:i?this.currentPageId:null,currentIndex:i?.meta.index??null,url:i?.meta.url??null,title:i?.meta.title??null,aliases:t,staleAliases:n}}getContextMeta(){let e=this.currentPageId?this.tabsById.get(this.currentPageId):null,t=e&&!e.stale?e:null;return{url:t?.meta.url??null,title:t?.meta.title??null,tabIndex:t?.meta.index??null,pageId:t?this.currentPageId:null}}listTabs(){let e=[];for(let[t,n]of this.tabsById)if(!n.stale){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:!1})}return e.toSorted((e,t)=>e.index-t.index)}listAllTabs(){let e=[];for(let[t,n]of this.tabsById){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:n.stale})}return e.toSorted((e,t)=>e.index-t.index)}setSharedContext(e,t){this.sharedContext.set(e,t)}getSharedContext(e){return{value:this.sharedContext.get(e)??null,found:this.sharedContext.has(e)}}getSharedContextMap(){let e={};return this.sharedContext.forEach((t,n)=>{e[n]=t}),e}clear(){this.tabsById.clear(),this.aliasToPageId.clear(),this.sharedContext.clear(),this.currentPageId=null}getAliasesForPageId(e){let t=[];for(let[n,r]of this.aliasToPageId)r===e&&t.push(n);return t}};function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(e){try{return JSON.parse(e)}catch{return null}}function o(e){if(!i(e)||!Array.isArray(e.content)||e.content.length===0)return null;let t=e.content[0];if(!i(t)||typeof t.text!=`string`)return null;let n=a(t.text);return i(n)?{currentTabIndex:typeof n.selectedIndex==`number`&&Number.isFinite(n.selectedIndex)?n.selectedIndex:typeof n.currentIndex==`number`&&Number.isFinite(n.currentIndex)?n.currentIndex:null,currentPageId:typeof n.selectedPageId==`string`?n.selectedPageId:null,currentTargetId:typeof n.targetId==`string`?n.targetId:null,lastToolName:typeof n.toolName==`string`?n.toolName:null,lastTouchedAt:new Date().toISOString()}:null}var s=class{getCollector;executionContext=new t;sessions=new Map;lastActiveSessionId=null;executionQueue=Promise.resolve();constructor(e){this.getCollector=e}normalizeSessionId(e){return typeof e!=`string`||e.trim().length===0?`default`:e}getCurrentSessionId(){return this.executionContext.getStore()?.sessionId??null}getOrCreateSession(e){let t=this.normalizeSessionId(e),n=this.sessions.get(t);return n||(n={tabRegistry:new r,currentTabIndex:null,currentPageId:null,currentTargetId:null,lastToolName:null,lastTouchedAt:null},this.sessions.set(t,n)),n}getTabRegistry(e){return this.getOrCreateSession(e).tabRegistry}noteToolResult(e,t,n){let r=this.getOrCreateSession(e);n?.currentTabIndex!==void 0&&(r.currentTabIndex=n.currentTabIndex??null),n?.currentPageId!==void 0&&(r.currentPageId=n.currentPageId??null),n?.currentTargetId!==void 0&&(r.currentTargetId=n.currentTargetId??null),r.lastToolName=t,r.lastTouchedAt=new Date().toISOString(),this.lastActiveSessionId=this.normalizeSessionId(e)}getSnapshot(e){let t=this.getOrCreateSession(e);return{currentTabIndex:t.currentTabIndex,currentPageId:t.currentPageId,currentTargetId:t.currentTargetId,lastToolName:t.lastToolName,lastTouchedAt:t.lastTouchedAt}}async restoreSessionContext(t){let n=this.normalizeSessionId(t),r=this.getOrCreateSession(n),i=this.getCollector();if(!i){this.lastActiveSessionId=n;return}if(this.lastActiveSessionId===n||r.currentTabIndex===null&&r.currentTargetId===null){this.lastActiveSessionId=n;return}if(typeof r.currentTabIndex==`number`)try{await i.selectPage(r.currentTabIndex)}catch(t){e.warn(`[browser-session] Failed to restore page index ${r.currentTabIndex} for session ${n}: ${t instanceof Error?t.message:String(t)}`)}if(r.currentTargetId)try{await i.attachCdpTarget(r.currentTargetId)}catch(t){e.warn(`[browser-session] Failed to restore target ${r.currentTargetId} for session ${n}: ${t instanceof Error?t.message:String(t)}`)}this.lastActiveSessionId=n}async runExclusive(e,t){let n=this.normalizeSessionId(e);if(this.executionContext.getStore()?.sessionId===n)return await t();let r=this.executionQueue,i,a=new Promise(e=>{i=e});this.executionQueue=r.then(()=>a),await r;try{return await this.executionContext.run({sessionId:n},t)}finally{i()}}};export{o as n,r,s as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rt as e}from"./constants-DMv3svps.mjs";import{t}from"./ToolError-g3rjWzhx.mjs";import{r as n}from"./native-g095qhpK.mjs";import{_ as r,b as i,d as a,f as o,h as s,l as c,m as l,p as u,t as d,u as f}from"./Win32API-DoP3MMHS.mjs";import{l as p}from"./Win32Debug-DwF8mQGm.mjs";import{n as m}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{randomUUID as h}from"node:crypto";var g=class{patches=new Map;async patchBytes(e,t,n){let o=BigInt(t.startsWith(`0x`)?t:`0x${t}`),s=Buffer.from(n),c=i(e,!0);try{let t=a(c,o,s.length),{success:i,oldProtect:u}=l(c,o,s.length,f.EXECUTE_READWRITE);r(c,o,s),p(c,o,s.length),i&&l(c,o,s.length,u);let d={id:h(),pid:e,address:`0x${o.toString(16).toUpperCase()}`,originalBytes:Array.from(t),patchBytes:n,isApplied:!0,timestamp:Date.now()};return this.patches.set(d.id,d),d}finally{d(c)}}async unpatch(e){let t=this.patches.get(e);if(!t?.isApplied)return!1;let n=BigInt(t.address),a=Buffer.from(t.originalBytes),o=i(t.pid,!0);try{let{oldProtect:e}=l(o,n,a.length,f.EXECUTE_READWRITE);return r(o,n,a),p(o,n,a.length),l(o,n,a.length,e),t.isApplied=!1,!0}finally{d(o)}}async nopBytes(e,t,n){let r=Array.from({length:n},()=>144);return this.patchBytes(e,t,r)}async findCodeCaves(t,r){let o=r??e,c=[],l=i(t,!1);try{let e=await n.enumerateModules(t);if(!e.success||!e.modules)return c;for(let t of e.modules){let e=BigInt(t.baseAddress.startsWith(`0x`)?t.baseAddress:`0x${t.baseAddress}`),n=e,r=e+BigInt(t.size);for(;n<r;){let{success:e,info:r}=s(l,n);if(!e||r.RegionSize===0n)break;let i=Number(r.RegionSize);if(m(r.Protect)&&i>0)try{let e=a(l,r.BaseAddress,Math.min(i,4*1024*1024)),n=-1;for(let i=0;i<e.length;i++){let a=e[i];if(a===0||a===204)n===-1&&(n=i);else if(n!==-1){let e=i-n;if(e>=o){let i=r.BaseAddress+BigInt(n);c.push({address:`0x${i.toString(16).toUpperCase()}`,size:e,module:t.name,section:`.text`})}n=-1}}if(n!==-1){let i=e.length-n;if(i>=o){let e=r.BaseAddress+BigInt(n);c.push({address:`0x${e.toString(16).toUpperCase()}`,size:i,module:t.name,section:`.text`})}}}catch{}n=r.BaseAddress+r.RegionSize}}}finally{d(l)}return c.toSorted((e,t)=>t.size-e.size)}async allocateRemote(e,n){let r=i(e,!0);try{let e=o(r,0n,n,c.COMMIT|c.RESERVE,f.EXECUTE_READWRITE);if(e===0n)throw new t(`RUNTIME`,`VirtualAllocEx failed`);return`0x${e.toString(16).toUpperCase()}`}finally{d(r)}}async freeRemote(e,t,n){let r=BigInt(t.startsWith(`0x`)?t:`0x${t}`),a=i(e,!0);try{return u(a,r,0,c.RELEASE)}finally{d(a)}}listPatches(){return Array.from(this.patches.values())}};const _=new g;export{g as CodeInjector,_ as codeInjector};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{_ as t,v as n}from"./ensure-browser-core-JHwDo5ql.mjs";import{randomUUID as r}from"node:crypto";var i=class{page;networkEnabled=!1;requests=new Map;responses=new Map;MAX_NETWORK_RECORDS=500;MAX_INJECTED_RECORDS=500;requestCounter=0;responseBodyCache=new Map;MAX_BODY_CACHE_ENTRIES=200;requestIdMap=new WeakMap;boundOnRequest=null;boundOnResponse=null;constructor(e){this.page=e}setPage(e){if(this.page===e)return;let t=this.page,n=this.networkEnabled,r=this.boundOnRequest,i=this.boundOnResponse;if(n&&t&&r)try{t.off(`request`,r)}catch{}if(n&&t&&i)try{t.off(`response`,i)}catch{}if(this.page=e,!n||!this.page){this.page||(this.networkEnabled=!1);return}r&&this.page.on(`request`,r),i&&this.page.on(`response`,i)}getPageOrThrow(){if(!this.page)throw Error(`Playwright page not initialized`);return this.page}async evaluateInPage(e){let t=this.getPageOrThrow();if(!t.evaluate)throw Error(`Playwright page.evaluate is not available`);return t.evaluate(e)}async evaluateOnNewDocumentInPage(e){let t=this.getPageOrThrow();if(!t.evaluateOnNewDocument)throw Error(`Playwright page.evaluateOnNewDocument is not available`);return t.evaluateOnNewDocument(e)}isUnknownArray(e){return Array.isArray(e)}isClearedBuffersResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrCleared==`number`&&typeof t.fetchCleared==`number`}isResetInterceptorsResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrReset==`boolean`&&typeof t.fetchReset==`boolean`}isPlaywrightLikeRequest(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.url==`function`&&typeof t.method==`function`&&typeof t.headers==`function`&&typeof t.postData==`function`&&typeof t.resourceType==`function`}isPlaywrightLikeResponse(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.request==`function`&&typeof t.url==`function`&&typeof t.status==`function`&&typeof t.statusText==`function`&&typeof t.headers==`function`}normalizeHttpVersion(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`http/1.0`||t===`1.0`)return`1.0`;if(t===`http/1.1`||t===`1.1`)return`1.1`;if(t===`http/2`||t===`2`||t===`2.0`||t===`h2`)return`h2`;if(t===`http/3`||t===`3`||t===`3.0`||t===`h3`)return`h3`}detectHttpVersion(e){let t=typeof e.httpVersion==`function`?e.httpVersion():void 0,n=this.normalizeHttpVersion(t);if(n)return n;let r=typeof e.protocol==`function`?e.protocol():void 0;return this.normalizeHttpVersion(r)}async enable(){if(this.networkEnabled){e.warn(`PlaywrightNetworkMonitor already enabled`);return}this.boundOnRequest=e=>{if(!this.isPlaywrightLikeRequest(e))return;let t=`pw-${++this.requestCounter}`;this.requestIdMap.set(e,t);let n={requestId:t,url:e.url(),method:e.method(),headers:e.headers(),postData:e.postData()??void 0,timestamp:Date.now(),type:e.resourceType()};if(this.requests.set(t,n),this.requests.size>this.MAX_NETWORK_RECORDS){let e=this.requests.keys().next().value;e&&this.requests.delete(e)}},this.boundOnResponse=t=>{if(!this.isPlaywrightLikeResponse(t))return;let n=t.request(),r=`pw-res-${Date.now()}-${Math.random()}`,i=this.isPlaywrightLikeRequest(n)?this.requestIdMap.get(n)??r:r,a=this.detectHttpVersion(t),o=this.requests.get(i);o&&a&&(o.httpVersion=a);let s={requestId:i,url:t.url(),status:t.status(),statusText:t.statusText(),headers:t.headers(),mimeType:t.headers()[`content-type`]??`unknown`,timestamp:Date.now()};if(this.responses.set(i,s),this.responses.size>this.MAX_NETWORK_RECORDS){let e=this.responses.keys().next().value;e&&this.responses.delete(e)}if(typeof t.body==`function`){let n=i;t.body().then(t=>{if(t.length>1048576){e.debug(`[PW-BodyCache] Skipping oversized body for ${n} (${t.length} bytes)`);return}if(this.responseBodyCache.size>=this.MAX_BODY_CACHE_ENTRIES){let e=this.responseBodyCache.keys().next().value;e&&this.responseBodyCache.delete(e)}/^(text\/|application\/(json|javascript|xml|x-www-form-urlencoded))/i.test(s.mimeType)?this.responseBodyCache.set(n,{body:t.toString(`utf-8`),base64Encoded:!1}):this.responseBodyCache.set(n,{body:t.toString(`base64`),base64Encoded:!0}),e.debug(`[PW-BodyCache] Cached body for ${n} (${t.length} bytes)`)}).catch(t=>{e.debug(`[PW-BodyCache] Could not capture body for ${n}: ${t instanceof Error?t.message:String(t)}`)})}};let t=this.getPageOrThrow();t.on(`request`,this.boundOnRequest),t.on(`response`,this.boundOnResponse),this.networkEnabled=!0,e.info(`PlaywrightNetworkMonitor enabled`)}async disable(){let t=this.getPageOrThrow();if(this.boundOnRequest){try{t.off(`request`,this.boundOnRequest)}catch{}this.boundOnRequest=null}if(this.boundOnResponse){try{t.off(`response`,this.boundOnResponse)}catch{}this.boundOnResponse=null}this.networkEnabled=!1,e.info(`PlaywrightNetworkMonitor disabled`)}isEnabled(){return this.networkEnabled}getRequests(e){let t=Array.from(this.requests.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.method&&(t=t.filter(t=>t.method.toUpperCase()===e.method.toUpperCase())),e?.limit&&(t=t.slice(-e.limit)),t}getResponses(e){let t=Array.from(this.responses.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.status&&(t=t.filter(t=>t.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getStatus(){return{enabled:this.networkEnabled,requestCount:this.requests.size,responseCount:this.responses.size,listenerCount:this.networkEnabled?2:0,cdpSessionActive:!1}}getActivity(e){return{request:this.requests.get(e),response:this.responses.get(e)}}clearRecords(){this.requests.clear(),this.responses.clear(),this.responseBodyCache.clear()}getStats(){let e=Array.from(this.requests.values()),t=Array.from(this.responses.values()),n={};e.forEach(e=>{n[e.method]=(n[e.method]||0)+1});let r={};t.forEach(e=>{r[e.status]=(r[e.status]||0)+1});let i={};return e.forEach(e=>{let t=e.type||`unknown`;i[t]=(i[t]||0)+1}),{totalRequests:e.length,totalResponses:t.length,byMethod:n,byStatus:r,byType:i}}async getResponseBody(t){let n=this.responseBodyCache.get(t);return n?(this.responseBodyCache.delete(t),this.responseBodyCache.set(t,n),e.debug(`[PW-BodyCache] Cache hit for ${t}`),n):(e.warn(`getResponseBody: no cached body for ${t} in Playwright mode`),null)}async injectScript(e){await this.evaluateInPage(e)}async injectXHRInterceptor(e){let t=`
|
|
2
2
|
(function() {
|
|
3
3
|
if (window.__xhrInterceptorInjected) return;
|
|
4
4
|
window.__xhrInterceptorInjected = true;
|
|
@@ -109,7 +109,7 @@ import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./PrerequisiteError-BjCQ
|
|
|
109
109
|
};
|
|
110
110
|
console.log('[PlaywrightFetch] Fetch interceptor injected');
|
|
111
111
|
})();
|
|
112
|
-
`;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async getXHRRequests(){try{let e=await this.evaluateInPage(()=>window.__xhrRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get XHR requests: ${t instanceof Error?t.message:String(t)}`),[]}}async getFetchRequests(){try{let e=await this.evaluateInPage(()=>window.__fetchRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get fetch requests: ${t instanceof Error?t.message:String(t)}`),[]}}async clearInjectedBuffers(){try{let e=await this.evaluateInPage(()=>{let e=window,t=e.__xhrRequests,n=e.__fetchRequests,r=Array.isArray(t)?t.length:0,i=Array.isArray(n)?n.length:0;return Array.isArray(t)&&(t.length=0),Array.isArray(n)&&(n.length=0),{xhrCleared:r,fetchCleared:i}});return this.isClearedBuffersResult(e)?e:{xhrCleared:0,fetchCleared:0}}catch(t){return e.warn(`[PW] Failed to clear injected buffers: ${t instanceof Error?t.message:String(t)}`),{xhrCleared:0,fetchCleared:0}}}async resetInjectedInterceptors(){try{let e=await this.evaluateInPage(()=>{let e=window,t=!1,n=!1;return e.__pwOriginalXMLHttpRequest&&(e.XMLHttpRequest=e.__pwOriginalXMLHttpRequest,t=!0),e.__pwOriginalFetch&&(e.fetch=e.__pwOriginalFetch,n=!0),Array.isArray(e.__xhrRequests)&&(e.__xhrRequests.length=0),Array.isArray(e.__fetchRequests)&&(e.__fetchRequests.length=0),e.__xhrInterceptorInjected=!1,e.__fetchInterceptorInjected=!1,{xhrReset:t,fetchReset:n}});return this.isResetInterceptorsResult(e)?e:{xhrReset:!1,fetchReset:!1}}catch(t){return e.warn(`[PW] Failed to reset interceptors: ${t instanceof Error?t.message:String(t)}`),{xhrReset:!1,fetchReset:!1}}}async getAllJavaScriptResponses(){return Array.from(this.responses.values()).filter(e=>e.mimeType.includes(`javascript`))}},a=class{cdpSession;rules=new Map;enabled=!1;eventHandler=null;compiledPatterns=new Map;constructor(e){this.cdpSession=e}async enable(t){let n=[];for(let e of t){let t=this.createRule(e);this.rules.set(t.id,t),this.compiledPatterns.set(t.id,this.compilePattern(t)),n.push(t)}return await this.applyRules(),this.eventHandler||(this.eventHandler=e=>{this.handleRequestPaused(e)},this.cdpSession.on(`Fetch.requestPaused`,this.eventHandler)),this.enabled=!0,e.info(`FetchInterceptor enabled with ${this.rules.size} rule(s)`),n}async disable(){let t=this.rules.size;if(this.eventHandler){try{this.cdpSession.off(`Fetch.requestPaused`,this.eventHandler)}catch{}this.eventHandler=null}try{await this.cdpSession.send(`Fetch.disable`)}catch(t){e.warn(`Fetch.disable failed:`,t)}return this.rules.clear(),this.compiledPatterns.clear(),this.enabled=!1,e.info(`FetchInterceptor disabled, removed ${t} rule(s)`),{removedRules:t}}async removeRule(e){let t=this.rules.delete(e);return this.compiledPatterns.delete(e),t&&(this.rules.size===0?await this.disable():await this.applyRules()),t}listRules(){let e=Array.from(this.rules.values());return{enabled:this.enabled,rules:e,totalHits:e.reduce((e,t)=>e+t.hitCount,0)}}isEnabled(){return this.enabled}createRule(e){let t=[];if(e.responseHeaders)for(let[n,r]of Object.entries(e.responseHeaders))t.push({name:n,value:r});return{id:r().slice(0,8),urlPattern:e.urlPattern,urlPatternType:e.urlPatternType??`glob`,stage:e.stage??`Response`,interceptAction:e.interceptAction??`fulfill`,responseCode:e.responseCode??200,responseHeaders:t,responseBody:e.responseBody??``,hitCount:0,createdAt:Date.now()}}compilePattern(e){if(e.urlPatternType===`regex`)try{return new RegExp(e.urlPattern,`i`)}catch{return new RegExp(e.urlPattern.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`i`)}let t=e.urlPattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`⟨GLOBSTAR⟩`).replace(/\*/g,`[^/]*`).replace(/⟨GLOBSTAR⟩/g,`.*`);return new RegExp(t,`i`)}async applyRules(){let t=[];for(let e of this.rules.values())t.push({urlPattern:e.urlPatternType===`glob`?e.urlPattern:`*`,requestStage:e.stage});if(t.length!==0)try{try{await this.cdpSession.send(`Fetch.disable`)}catch{}await this.cdpSession.send(`Fetch.enable`,{patterns:t.length>0?t:[{urlPattern:`*`,requestStage:`Response`}],handleAuthRequests:!1})}catch(t){throw e.error(`Failed to apply Fetch interception rules:`,t),t}}async handleRequestPaused(t){let n=t.request.url;for(let[r,i]of this.rules){let a=this.compiledPatterns.get(r);if(a&&a.test(n)&&(i.hitCount++,e.info(`[FetchInterceptor] Rule "${i.urlPattern}" matched: ${n}`),await this.applyMatchedRule(i,t,n)))return}await this.continueOriginalRequest(t,n)}async applyMatchedRule(t,n,r){try{switch(t.interceptAction){case`continue`:return await this.continuePausedRequest(n),!0;case`abort`:return await this.cdpSession.send(`Fetch.failRequest`,{requestId:n.requestId,errorReason:`Failed`}),!0;case`fulfill`:return await this.cdpSession.send(`Fetch.fulfillRequest`,{requestId:n.requestId,responseCode:t.responseCode,responseHeaders:this.buildFulfillHeaders(t),body:Buffer.from(t.responseBody,`utf-8`).toString(`base64`)}),!0}}catch(n){return e.error(`[FetchInterceptor] ${t.interceptAction} failed for ${r}:`,n),!1}}buildFulfillHeaders(e){let t=[...e.responseHeaders];return t.some(e=>e.name.toLowerCase()===`content-type`)||(e.responseBody.startsWith(`{`)||e.responseBody.startsWith(`[`)?t.push({name:`Content-Type`,value:`application/json`}):t.push({name:`Content-Type`,value:`text/plain`})),t.some(e=>e.name.toLowerCase()===`access-control-allow-origin`)||t.push({name:`Access-Control-Allow-Origin`,value:`*`}),t}async continuePausedRequest(e){if(e.responseStatusCode!==void 0){await this.cdpSession.send(`Fetch.continueResponse`,{requestId:e.requestId});return}await this.cdpSession.send(`Fetch.continueRequest`,{requestId:e.requestId})}async continueOriginalRequest(t,n){try{await this.continuePausedRequest(t)}catch(t){e.warn(`[FetchInterceptor] continue failed for ${n}:`,t)}}};function o(e){return e}function s(t,n){let r=o(t);if(r.contextSwitchPending)return[];let i=r.messages;n?.type&&(i=i.filter(e=>e.type===n.type));let a=n?.since;return a!==void 0&&(i=i.filter(e=>e.timestamp>=a)),n?.limit&&(i=i.slice(-n.limit)),e.debug(`getLogs: ${i.length} messages`),i}function c(t){let n=o(t);n.messages=[],e.info(`Console logs cleared`)}function l(e){let t=o(e);if(t.contextSwitchPending)return{totalMessages:0,byType:{}};let n={};for(let e of t.messages)n[e.type]=(n[e.type]||0)+1;return{totalMessages:t.messages.length,byType:n}}function u(e,t){let n=o(e);if(n.contextSwitchPending)return[];let r=n.exceptions;t?.url&&(r=r.filter(e=>e.url?.includes(t.url)));let i=t?.since;return i!==void 0&&(r=r.filter(e=>e.timestamp>=i)),t?.limit&&(r=r.slice(-t.limit)),r}function d(t){let n=o(t);n.exceptions=[],e.info(`Exceptions cleared`)}function f(e){return e}function p(e){return e.contextSwitchPending===!0}function m(e){let t=f(e);return p(t)?!1:(t.networkMonitor?.isEnabled()??!1)||(t.playwrightNetworkMonitor?.isEnabled()??!1)}function h(e){let t=f(e);return p(t)?{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:!1}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStatus():t.networkMonitor?t.networkMonitor.getStatus():{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:t.cdpSession!==null}}function g(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getRequests(t):n.networkMonitor?.getRequests(t)??[]}function _(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getResponses(t):n.networkMonitor?.getResponses(t)??[]}function v(e,t){let n=f(e);return p(n)?{}:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getActivity(t):n.networkMonitor?.getActivity(t)??{}}async function y(t,n){let r=f(t);return p(r)?null:r.playwrightNetworkMonitor?r.playwrightNetworkMonitor.getResponseBody(n):r.networkMonitor?r.networkMonitor.getResponseBody(n):(e.error(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`),null)}async function b(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getAllJavaScriptResponses():t.networkMonitor?t.networkMonitor.getAllJavaScriptResponses():[]}function x(e){let t=f(e);t.networkMonitor?.clearRecords(),t.playwrightNetworkMonitor?.clearRecords()}async function S(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.clearInjectedBuffers(),dynamicScriptsCleared:0};let n=t.networkMonitor?await t.networkMonitor.clearInjectedBuffers():{xhrCleared:0,fetchCleared:0},r=await t.clearDynamicScriptBuffer();return{...n,...r}}async function C(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.resetInjectedInterceptors(),scriptMonitorReset:!1};let n=t.networkMonitor?await t.networkMonitor.resetInjectedInterceptors():{xhrReset:!1,fetchReset:!1},r=await t.resetDynamicScriptMonitoring();return{...n,...r}}function w(e){let t=f(e);return p(t)?{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStats():t.networkMonitor?.getStats()??{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}}async function T(e,n){let r=f(e);if(p(r))throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectXHRInterceptor(n);if(!r.networkMonitor)throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectXHRInterceptor(n)}async function E(e,n){let r=f(e);if(p(r))throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectFetchInterceptor(n);if(!r.networkMonitor)throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectFetchInterceptor(n)}async function D(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getXHRRequests():t.networkMonitor?t.networkMonitor.getXHRRequests():[]}async function O(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getFetchRequests():t.networkMonitor?t.networkMonitor.getFetchRequests():[]}async function k(t,n){let r=t;if(await r.ensureSession(),!r.cdpSession)throw Error(`CDP session not available after reconnect attempt`);if(r.objectCache.has(n)){let e=r.objectCache.get(n);if(e!==void 0)return e}try{let t=await r.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),i={};for(let e of t.result){if(!e.value)continue;let t=e.value;i[e.name]={value:r.extractValue(t),type:t.type,objectId:t.objectId,description:t.description}}if(!r.objectCache.has(n))for(;r.objectCache.size>=r.MAX_OBJECT_CACHE_SIZE;){let e=r.objectCache.keys().next().value;if(e===void 0)break;r.objectCache.delete(e)}return r.objectCache.set(n,i),e.info(`Object inspected: ${n}`,{propertyCount:Object.keys(i).length}),i}catch(t){throw e.error(`Failed to inspect object:`,t),t}}function A(t){t.objectCache.clear(),e.info(`Object cache cleared`)}function j(e){return e}async function M(n,r){let i=j(n);if(await i.ensureSession(),!i.cdpSession)throw new t(`CDP session not available after reconnect attempt`);let a=`
|
|
112
|
+
`;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async getXHRRequests(){try{let e=await this.evaluateInPage(()=>window.__xhrRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get XHR requests: ${t instanceof Error?t.message:String(t)}`),[]}}async getFetchRequests(){try{let e=await this.evaluateInPage(()=>window.__fetchRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get fetch requests: ${t instanceof Error?t.message:String(t)}`),[]}}async clearInjectedBuffers(){try{let e=await this.evaluateInPage(()=>{let e=window,t=e.__xhrRequests,n=e.__fetchRequests,r=Array.isArray(t)?t.length:0,i=Array.isArray(n)?n.length:0;return Array.isArray(t)&&(t.length=0),Array.isArray(n)&&(n.length=0),{xhrCleared:r,fetchCleared:i}});return this.isClearedBuffersResult(e)?e:{xhrCleared:0,fetchCleared:0}}catch(t){return e.warn(`[PW] Failed to clear injected buffers: ${t instanceof Error?t.message:String(t)}`),{xhrCleared:0,fetchCleared:0}}}async resetInjectedInterceptors(){try{let e=await this.evaluateInPage(()=>{let e=window,t=!1,n=!1;return e.__pwOriginalXMLHttpRequest&&(e.XMLHttpRequest=e.__pwOriginalXMLHttpRequest,t=!0),e.__pwOriginalFetch&&(e.fetch=e.__pwOriginalFetch,n=!0),Array.isArray(e.__xhrRequests)&&(e.__xhrRequests.length=0),Array.isArray(e.__fetchRequests)&&(e.__fetchRequests.length=0),e.__xhrInterceptorInjected=!1,e.__fetchInterceptorInjected=!1,{xhrReset:t,fetchReset:n}});return this.isResetInterceptorsResult(e)?e:{xhrReset:!1,fetchReset:!1}}catch(t){return e.warn(`[PW] Failed to reset interceptors: ${t instanceof Error?t.message:String(t)}`),{xhrReset:!1,fetchReset:!1}}}async getAllJavaScriptResponses(){return Array.from(this.responses.values()).filter(e=>e.mimeType.includes(`javascript`))}},a=class{cdpSession;rules=new Map;enabled=!1;eventHandler=null;compiledPatterns=new Map;constructor(e){this.cdpSession=e}async enable(t){let n=[];for(let e of t){let t=this.createRule(e);this.rules.set(t.id,t),this.compiledPatterns.set(t.id,this.compilePattern(t)),n.push(t)}return await this.applyRules(),this.eventHandler||(this.eventHandler=e=>{this.handleRequestPaused(e)},this.cdpSession.on(`Fetch.requestPaused`,this.eventHandler)),this.enabled=!0,e.info(`FetchInterceptor enabled with ${this.rules.size} rule(s)`),n}async disable(){let t=this.rules.size;if(this.eventHandler){try{this.cdpSession.off(`Fetch.requestPaused`,this.eventHandler)}catch{}this.eventHandler=null}try{await this.cdpSession.send(`Fetch.disable`)}catch(t){e.warn(`Fetch.disable failed:`,t)}return this.rules.clear(),this.compiledPatterns.clear(),this.enabled=!1,e.info(`FetchInterceptor disabled, removed ${t} rule(s)`),{removedRules:t}}async removeRule(e){let t=this.rules.delete(e);return this.compiledPatterns.delete(e),t&&(this.rules.size===0?await this.disable():await this.applyRules()),t}listRules(){let e=Array.from(this.rules.values());return{enabled:this.enabled,rules:e,totalHits:e.reduce((e,t)=>e+t.hitCount,0)}}isEnabled(){return this.enabled}createRule(e){let t=[];if(e.responseHeaders)for(let[n,r]of Object.entries(e.responseHeaders))t.push({name:n,value:r});return{id:r().slice(0,8),urlPattern:e.urlPattern,urlPatternType:e.urlPatternType??`glob`,stage:e.stage??`Response`,interceptAction:e.interceptAction??`fulfill`,responseCode:e.responseCode??200,responseHeaders:t,responseBody:e.responseBody??``,hitCount:0,createdAt:Date.now()}}compilePattern(e){if(e.urlPatternType===`regex`)try{return new RegExp(e.urlPattern,`i`)}catch{return new RegExp(e.urlPattern.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`i`)}let t=e.urlPattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`⟨GLOBSTAR⟩`).replace(/\*/g,`[^/]*`).replace(/⟨GLOBSTAR⟩/g,`.*`);return new RegExp(t,`i`)}async applyRules(){let t=[];for(let e of this.rules.values())t.push({urlPattern:e.urlPatternType===`glob`?e.urlPattern:`*`,requestStage:e.stage});if(t.length!==0)try{try{await this.cdpSession.send(`Fetch.disable`)}catch{}await this.cdpSession.send(`Fetch.enable`,{patterns:t.length>0?t:[{urlPattern:`*`,requestStage:`Response`}],handleAuthRequests:!1})}catch(t){throw e.error(`Failed to apply Fetch interception rules:`,t),t}}async handleRequestPaused(t){let n=t.request.url;for(let[r,i]of this.rules){let a=this.compiledPatterns.get(r);if(a&&a.test(n)&&(i.hitCount++,e.info(`[FetchInterceptor] Rule "${i.urlPattern}" matched: ${n}`),await this.applyMatchedRule(i,t,n)))return}await this.continueOriginalRequest(t,n)}async applyMatchedRule(t,n,r){try{switch(t.interceptAction){case`continue`:return await this.continuePausedRequest(n),!0;case`abort`:return await this.cdpSession.send(`Fetch.failRequest`,{requestId:n.requestId,errorReason:`Failed`}),!0;case`fulfill`:return await this.cdpSession.send(`Fetch.fulfillRequest`,{requestId:n.requestId,responseCode:t.responseCode,responseHeaders:this.buildFulfillHeaders(t),body:Buffer.from(t.responseBody,`utf-8`).toString(`base64`)}),!0}}catch(n){return e.error(`[FetchInterceptor] ${t.interceptAction} failed for ${r}:`,n),!1}}buildFulfillHeaders(e){let t=[...e.responseHeaders];return t.some(e=>e.name.toLowerCase()===`content-type`)||(e.responseBody.startsWith(`{`)||e.responseBody.startsWith(`[`)?t.push({name:`Content-Type`,value:`application/json`}):t.push({name:`Content-Type`,value:`text/plain`})),t.some(e=>e.name.toLowerCase()===`access-control-allow-origin`)||t.push({name:`Access-Control-Allow-Origin`,value:`*`}),t}async continuePausedRequest(e){if(e.responseStatusCode!==void 0){await this.cdpSession.send(`Fetch.continueResponse`,{requestId:e.requestId});return}await this.cdpSession.send(`Fetch.continueRequest`,{requestId:e.requestId})}async continueOriginalRequest(t,n){try{await this.continuePausedRequest(t)}catch(t){e.warn(`[FetchInterceptor] continue failed for ${n}:`,t)}}};function o(e){return e}function s(t,n){let r=o(t);if(r.contextSwitchPending)return[];let i=r.messages;n?.type&&(i=i.filter(e=>e.type===n.type));let a=n?.since;return a!==void 0&&(i=i.filter(e=>e.timestamp>=a)),n?.limit&&(i=i.slice(-n.limit)),e.debug(`getLogs: ${i.length} messages`),i}function c(t){let n=o(t);n.messages=[],e.info(`Console logs cleared`)}function l(e){let t=o(e);if(t.contextSwitchPending)return{totalMessages:0,byType:{}};let n={};for(let e of t.messages)n[e.type]=(n[e.type]||0)+1;return{totalMessages:t.messages.length,byType:n}}function u(e,t){let n=o(e);if(n.contextSwitchPending)return[];let r=n.exceptions;t?.url&&(r=r.filter(e=>e.url?.includes(t.url)));let i=t?.since;return i!==void 0&&(r=r.filter(e=>e.timestamp>=i)),t?.limit&&(r=r.slice(-t.limit)),r}function d(t){let n=o(t);n.exceptions=[],e.info(`Exceptions cleared`)}function f(e){return e}function p(e){return e.contextSwitchPending===!0}function m(e){let t=f(e);return p(t)?!1:(t.networkMonitor?.isEnabled()??!1)||(t.playwrightNetworkMonitor?.isEnabled()??!1)}function h(e){let t=f(e);return p(t)?{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:!1}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStatus():t.networkMonitor?t.networkMonitor.getStatus():{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:t.cdpSession!==null}}function g(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getRequests(t):n.networkMonitor?.getRequests(t)??[]}function _(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getResponses(t):n.networkMonitor?.getResponses(t)??[]}function v(e,t){let n=f(e);return p(n)?{}:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getActivity(t):n.networkMonitor?.getActivity(t)??{}}async function y(t,n){let r=f(t);return p(r)?null:r.playwrightNetworkMonitor?r.playwrightNetworkMonitor.getResponseBody(n):r.networkMonitor?r.networkMonitor.getResponseBody(n):(e.error(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`),null)}async function b(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getAllJavaScriptResponses():t.networkMonitor?t.networkMonitor.getAllJavaScriptResponses():[]}function x(e){let t=f(e);t.networkMonitor?.clearRecords(),t.playwrightNetworkMonitor?.clearRecords()}async function S(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.clearInjectedBuffers(),dynamicScriptsCleared:0};let n=t.networkMonitor?await t.networkMonitor.clearInjectedBuffers():{xhrCleared:0,fetchCleared:0},r=await t.clearDynamicScriptBuffer();return{...n,...r}}async function C(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.resetInjectedInterceptors(),scriptMonitorReset:!1};let n=t.networkMonitor?await t.networkMonitor.resetInjectedInterceptors():{xhrReset:!1,fetchReset:!1},r=await t.resetDynamicScriptMonitoring();return{...n,...r}}function w(e){let t=f(e);return p(t)?{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStats():t.networkMonitor?.getStats()??{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}}async function T(e,t){let r=f(e);if(p(r))throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectXHRInterceptor(t);if(!r.networkMonitor)throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectXHRInterceptor(t)}async function E(e,t){let r=f(e);if(p(r))throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectFetchInterceptor(t);if(!r.networkMonitor)throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectFetchInterceptor(t)}async function D(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getXHRRequests():t.networkMonitor?t.networkMonitor.getXHRRequests():[]}async function O(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getFetchRequests():t.networkMonitor?t.networkMonitor.getFetchRequests():[]}async function k(t,n){let r=t;if(await r.ensureSession(),!r.cdpSession)throw Error(`CDP session not available after reconnect attempt`);if(r.objectCache.has(n)){let e=r.objectCache.get(n);if(e!==void 0)return e}try{let t=await r.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),i={};for(let e of t.result){if(!e.value)continue;let t=e.value;i[e.name]={value:r.extractValue(t),type:t.type,objectId:t.objectId,description:t.description}}if(!r.objectCache.has(n))for(;r.objectCache.size>=r.MAX_OBJECT_CACHE_SIZE;){let e=r.objectCache.keys().next().value;if(e===void 0)break;r.objectCache.delete(e)}return r.objectCache.set(n,i),e.info(`Object inspected: ${n}`,{propertyCount:Object.keys(i).length}),i}catch(t){throw e.error(`Failed to inspect object:`,t),t}}function A(t){t.objectCache.clear(),e.info(`Object cache cleared`)}function j(e){return e}async function M(t,r){let i=j(t);if(await i.ensureSession(),!i.cdpSession)throw new n(`CDP session not available after reconnect attempt`);let a=`
|
|
113
113
|
(function() {
|
|
114
114
|
if (window.__dynamicScriptMonitorInstalled) {
|
|
115
115
|
console.log('[ScriptMonitor] Already installed');
|
|
@@ -251,7 +251,7 @@ import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./PrerequisiteError-BjCQ
|
|
|
251
251
|
|
|
252
252
|
return { scriptMonitorReset };
|
|
253
253
|
})()
|
|
254
|
-
`,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`scriptMonitorReset`in e&&typeof e.scriptMonitorReset==`boolean`?e:{scriptMonitorReset:!1}}catch(t){return e.error(`Failed to reset dynamic script monitoring:`,t),{scriptMonitorReset:!1}}}async function F(
|
|
254
|
+
`,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`scriptMonitorReset`in e&&typeof e.scriptMonitorReset==`boolean`?e:{scriptMonitorReset:!1}}catch(t){return e.error(`Failed to reset dynamic script monitoring:`,t),{scriptMonitorReset:!1}}}async function F(t){let r=j(t);if(!r.cdpSession)throw new n(`CDP session not initialized`);try{let e=(await r.cdpSession.send(`Runtime.evaluate`,{expression:`window.__getDynamicScripts ? window.__getDynamicScripts() : []`,returnByValue:!0})).result?.value;return Array.isArray(e)?e:[]}catch(t){return e.error(`Failed to get dynamic scripts:`,t),[]}}async function I(t,r,i){let a=j(t);if(!a.cdpSession)throw new n(`CDP session not initialized`);let o=`
|
|
255
255
|
(function() {
|
|
256
256
|
const originalFunc = window.${r};
|
|
257
257
|
if (typeof originalFunc !== 'function') {
|
|
@@ -278,7 +278,7 @@ import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./PrerequisiteError-BjCQ
|
|
|
278
278
|
|
|
279
279
|
console.log('[Tracer] ${r} is now being traced');
|
|
280
280
|
})();
|
|
281
|
-
`;i?.persistent?(await a.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:o}),e.info(`Function tracer injected for: ${r} (persistent)`)):(await a.cdpSession.send(`Runtime.evaluate`,{expression:o}),e.info(`Function tracer injected for: ${r}`))}async function L(
|
|
281
|
+
`;i?.persistent?(await a.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:o}),e.info(`Function tracer injected for: ${r} (persistent)`)):(await a.cdpSession.send(`Runtime.evaluate`,{expression:o}),e.info(`Function tracer injected for: ${r}`))}async function L(t,r,i,a){let o=j(t);if(!o.cdpSession)throw new n(`CDP session not initialized`);let s=`
|
|
282
282
|
(function() {
|
|
283
283
|
const obj = ${r};
|
|
284
284
|
if (!obj) {
|
|
@@ -303,4 +303,4 @@ import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./PrerequisiteError-BjCQ
|
|
|
303
303
|
|
|
304
304
|
console.log('[Watcher] Property watcher installed for ${r}.${i}');
|
|
305
305
|
})();
|
|
306
|
-
`;a?.persistent?(await o.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:s}),e.info(`Property watcher injected for: ${r}.${i} (persistent)`)):(await o.cdpSession.send(`Runtime.evaluate`,{expression:s}),e.info(`Property watcher injected for: ${r}.${i}`))}function R(e){return e}async function z(t,r,i,a){let o=R(t);o.cdpSession=r,o.usingManagedTargetSession=i,o.lastEnableOptions={...a},o.cdpSession.on(`disconnected`,()=>{e.warn(`ConsoleMonitor CDP session disconnected`),o.cdpSession=null,o.networkMonitor=null,o.usingManagedTargetSession=!1}),await H(o.cdpSession,`Runtime.enable`,{},5e3),await H(o.cdpSession,`Console.enable`,{},5e3),o.cdpSession.on(`Runtime.consoleAPICalled`,t=>{let n=t.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],r={type:t.type,text:t.args.map(e=>o.formatRemoteObject(e)).join(` `),args:t.args.map(e=>o.extractValue(e)),timestamp:t.timestamp,stackTrace:n,url:n[0]?.url,lineNumber:n[0]?.lineNumber,columnNumber:n[0]?.columnNumber};o.messages.push(r),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2))),e.debug(`Console ${t.type}: ${r.text}`)}),o.cdpSession.on(`Console.messageAdded`,e=>{let t=e.message,n={type:t.level||`log`,text:t.text,timestamp:Date.now(),url:t.url,lineNumber:t.line,columnNumber:t.column};o.messages.push(n),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2)))}),a?.enableExceptions!==!1&&o.cdpSession.on(`Runtime.exceptionThrown`,t=>{let n=t.exceptionDetails,r=n.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],i={text:n.exception?.description||n.text,exceptionId:n.exceptionId,timestamp:Date.now(),stackTrace:r,url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,scriptId:n.scriptId};o.exceptions.push(i),o.exceptions.length>o.MAX_EXCEPTIONS&&(o.exceptions=o.exceptions.slice(-Math.floor(o.MAX_EXCEPTIONS/2))),e.error(`Exception thrown: ${i.text}`,{url:i.url,line:i.lineNumber})}),a?.enableNetwork&&(o.networkMonitor=o.getManagedTargetNetworkMonitor?.()??new n(o.cdpSession),await o.networkMonitor.enable()),e.info(`ConsoleMonitor enabled`,{network:a?.enableNetwork||!1,exceptions:a?.enableExceptions!==!1})}async function B(t,n){let r=R(t);if(r.playwrightConsoleHandler){n?.enableNetwork&&!r.playwrightNetworkMonitor&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor Playwright session`));return}let a=r.playwrightPage;r.playwrightConsoleHandler=e=>{let t={type:e.type()||`log`,text:e.text(),timestamp:Date.now()};r.messages.push(t),r.messages.length>r.MAX_MESSAGES&&(r.messages=r.messages.slice(-Math.floor(r.MAX_MESSAGES/2)))},a.on(`console`,r.playwrightConsoleHandler),n?.enableExceptions!==!1&&(r.playwrightErrorHandler=e=>{let t={text:e.message,exceptionId:Date.now(),timestamp:Date.now()};r.exceptions.push(t),r.exceptions.length>r.MAX_EXCEPTIONS&&(r.exceptions=r.exceptions.slice(-Math.floor(r.MAX_EXCEPTIONS/2)))},a.on(`pageerror`,r.playwrightErrorHandler)),n?.enableNetwork&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable()),e.info(`ConsoleMonitor enabled (Playwright/camoufox mode)`,{network:n?.enableNetwork||!1})}async function V(t){let n=R(t);if(n.playwrightPage){let e=n.playwrightPage;if(n.playwrightConsoleHandler){try{e.off(`console`,n.playwrightConsoleHandler)}catch{}n.playwrightConsoleHandler=null}if(n.playwrightErrorHandler){try{e.off(`pageerror`,n.playwrightErrorHandler)}catch{}n.playwrightErrorHandler=null}}if(n.playwrightNetworkMonitor&&=(await n.playwrightNetworkMonitor.disable(),null),n.cdpSession){n.networkMonitor&&=(await n.networkMonitor.disable(),null);try{await n.cdpSession.send(`Console.disable`)}catch(t){e.warn(`Failed to disable Console domain:`,t)}try{await n.cdpSession.send(`Runtime.disable`)}catch(t){e.warn(`Failed to disable Runtime domain:`,t)}if(n.usingManagedTargetSession)e.debug(`ConsoleMonitor released managed target session without detaching target`);else try{await n.cdpSession.detach()}catch(t){e.warn(`Failed to detach ConsoleMonitor CDP session:`,t)}n.cdpSession=null,n.usingManagedTargetSession=!1,e.info(`ConsoleMonitor disabled`)}}async function H(e,t,n,r=3e4){return Promise.race([e.send(t,n),new Promise((e,n)=>setTimeout(()=>n(Error(`CDP ${t} timed out after ${r}ms`)),r))])}var U=class{collector;cdpSession=null;networkMonitor=null;fetchInterceptor=null;playwrightNetworkMonitor=null;playwrightPage=null;usingManagedTargetSession=!1;contextSwitchPending=!1;playwrightConsoleHandler=null;playwrightErrorHandler=null;messages=[];MAX_MESSAGES=1e3;exceptions=[];MAX_EXCEPTIONS=500;MAX_INJECTED_DYNAMIC_SCRIPTS=500;MAX_OBJECT_CACHE_SIZE=1e3;objectCache=new Map;initPromise;lastEnableOptions={};constructor(e){this.collector=e,this.touchSplitMembersForTypeCheck()}touchSplitMembersForTypeCheck(){this.MAX_INJECTED_DYNAMIC_SCRIPTS,this.MAX_OBJECT_CACHE_SIZE,this.clearDynamicScriptBuffer,this.resetDynamicScriptMonitoring,this.usingManagedTargetSession,this.playwrightErrorHandler,this.messages,this.MAX_MESSAGES,this.exceptions,this.MAX_EXCEPTIONS,this.formatRemoteObject,this.extractValue}setPlaywrightPage(e){this.playwrightPage=e,this.playwrightNetworkMonitor?.setPage(e)}clearPlaywrightPage(){this.playwrightPage=null,this.contextSwitchPending=!1,this.playwrightConsoleHandler=null,this.playwrightErrorHandler=null,this.playwrightNetworkMonitor?.setPage(null),this.playwrightNetworkMonitor=null}getManagedTargetSession(){return this.collector.getAttachedTargetSession?.()??null}getManagedTargetNetworkMonitor(){return this.collector.getBrowserTargetSessionManager?.()??null}async createCdpSession(){let e=this.getManagedTargetSession();if(e)return{session:e,managed:!0};let t=await this.collector.getActivePage();return{session:await Promise.race([t.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),managed:!1}}markContextChanged(){!this.cdpSession&&!this.playwrightPage&&!this.networkMonitor&&!this.playwrightNetworkMonitor&&!this.fetchInterceptor||(this.contextSwitchPending=!0,this.clearLogs(),this.clearExceptions(),this.networkMonitor?.persistsAcrossContextSwitches?.()||this.clearNetworkRecords(),this.clearObjectCache(),e.info(`ConsoleMonitor marked stale after active context switch`))}async enable(e){if(this.contextSwitchPending&&await this.disable(),this.initPromise){await this.initPromise,await this.applyPostEnableOptions(e);return}this.initPromise=this.doEnable(e);try{await this.initPromise}finally{this.initPromise=void 0}}async doEnable(t){if(this.playwrightPage)return this.lastEnableOptions={...t},B(this,t);if(this.cdpSession){t?.enableNetwork&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new n(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`));return}let{session:r,managed:i}=await this.createCdpSession();await z(this,r,i,t)}async applyPostEnableOptions(t){if(t?.enableNetwork){if(this.lastEnableOptions={...this.lastEnableOptions,...t},this.playwrightPage&&this.playwrightConsoleHandler&&!this.playwrightNetworkMonitor){await B(this,t);return}this.cdpSession&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new n(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`))}}async disable(){try{this.cdpSession&&this.fetchInterceptor&&(await this.fetchInterceptor.disable(),this.fetchInterceptor=null),await V(this)}finally{this.fetchInterceptor=null,this.initPromise=void 0,this.contextSwitchPending=!1,this.objectCache.clear()}}async ensureSession(){if(this.contextSwitchPending){e.info(`ConsoleMonitor context switched, rebinding on demand...`);let t={...this.lastEnableOptions};await this.disable(),await this.enable(t);return}if(!this.cdpSession&&!this.playwrightPage){e.info(`ConsoleMonitor CDP session lost, reinitializing...`),await this.enable(this.lastEnableOptions);return}if(this.cdpSession)try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{e.warn(`ConsoleMonitor CDP session unresponsive (zombie), reinitializing...`),this.cdpSession=null,this.networkMonitor=null,this.fetchInterceptor=null,this.usingManagedTargetSession=!1,await this.enable(this.lastEnableOptions)}}isSessionActive(){return!this.contextSwitchPending&&(this.cdpSession!==null||this.playwrightPage!==null)}getLogs(e){return s(this,e)}async execute(t){await this.ensureSession();try{let n=await H(this.cdpSession,`Runtime.evaluate`,{expression:t,returnByValue:!0});if(n.exceptionDetails)throw e.error(`Console execute error:`,n.exceptionDetails),Error(n.exceptionDetails.text);return e.info(`Console expression executed`),n.result.value}catch(t){throw e.error(`Console execute failed:`,t),t}}clearLogs(){c(this)}getStats(){return l(this)}async close(){try{await this.disable()}finally{this.initPromise=void 0,this.objectCache.clear()}}isNetworkEnabled(){return m(this)}getNetworkStatus(){return h(this)}getNetworkRequests(e){return g(this,e)}getNetworkResponses(e){return _(this,e)}getNetworkActivity(e){return v(this,e)}async getResponseBody(e){return y(this,e)}async getAllJavaScriptResponses(){return b(this)}clearNetworkRecords(){x(this)}async clearInjectedBuffers(){return S(this)}async resetInjectedInterceptors(){return C(this)}getNetworkStats(){return w(this)}async injectXHRInterceptor(e){return T(this,e)}async injectFetchInterceptor(e){return E(this,e)}async getXHRRequests(){return D(this)}async getFetchRequests(){return O(this)}getExceptions(e){return u(this,e)}clearExceptions(){d(this)}async inspectObject(e){return k(this,e)}clearObjectCache(){A(this)}async enableDynamicScriptMonitoring(e){return M(this,e)}async clearDynamicScriptBuffer(){return N(this)}async resetDynamicScriptMonitoring(){return P(this)}async getDynamicScripts(){return F(this)}async injectFunctionTracer(e,t){return I(this,e,t)}async injectPropertyWatcher(e,t,n){return L(this,e,t,n)}async enableFetchIntercept(e){if(await this.ensureSession(),!this.cdpSession)throw Error(`No CDP session available for Fetch interception`);return this.fetchInterceptor||=new a(this.cdpSession),this.fetchInterceptor.enable(e)}async disableFetchIntercept(){if(!this.fetchInterceptor)return{removedRules:0};let e=await this.fetchInterceptor.disable();return this.fetchInterceptor=null,e}async removeFetchInterceptRule(e){if(!this.fetchInterceptor)return!1;let t=await this.fetchInterceptor.removeRule(e);return this.fetchInterceptor.isEnabled()||(this.fetchInterceptor=null),t}getFetchInterceptStatus(){return this.fetchInterceptor?this.fetchInterceptor.listRules():{enabled:!1,rules:[],totalHits:0}}formatRemoteObject(e){return e.value===void 0?e.description?e.description:e.type===`undefined`?`undefined`:e.type===`object`&&e.subtype===`null`?`null`:`[${e.type}]`:String(e.value)}extractValue(e){if(e.value!==void 0)return e.value;if(e.type!==`undefined`)return e.type===`object`&&e.subtype===`null`?null:e.objectId?{__objectId:e.objectId,__type:e.type,__description:e.description}:e.description||`[${e.type}]`}};export{U as ConsoleMonitor};
|
|
306
|
+
`;a?.persistent?(await o.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:s}),e.info(`Property watcher injected for: ${r}.${i} (persistent)`)):(await o.cdpSession.send(`Runtime.evaluate`,{expression:s}),e.info(`Property watcher injected for: ${r}.${i}`))}function R(e){return e}async function z(n,r,i,a){let o=R(n);o.cdpSession=r,o.usingManagedTargetSession=i,o.lastEnableOptions={...a},o.cdpSession.on(`disconnected`,()=>{e.warn(`ConsoleMonitor CDP session disconnected`),o.cdpSession=null,o.networkMonitor=null,o.usingManagedTargetSession=!1}),await H(o.cdpSession,`Runtime.enable`,{},5e3),await H(o.cdpSession,`Console.enable`,{},5e3),o.cdpSession.on(`Runtime.consoleAPICalled`,t=>{let n=t.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],r={type:t.type,text:t.args.map(e=>o.formatRemoteObject(e)).join(` `),args:t.args.map(e=>o.extractValue(e)),timestamp:t.timestamp,stackTrace:n,url:n[0]?.url,lineNumber:n[0]?.lineNumber,columnNumber:n[0]?.columnNumber};o.messages.push(r),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2))),e.debug(`Console ${t.type}: ${r.text}`)}),o.cdpSession.on(`Console.messageAdded`,e=>{let t=e.message,n={type:t.level||`log`,text:t.text,timestamp:Date.now(),url:t.url,lineNumber:t.line,columnNumber:t.column};o.messages.push(n),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2)))}),a?.enableExceptions!==!1&&o.cdpSession.on(`Runtime.exceptionThrown`,t=>{let n=t.exceptionDetails,r=n.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],i={text:n.exception?.description||n.text,exceptionId:n.exceptionId,timestamp:Date.now(),stackTrace:r,url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,scriptId:n.scriptId};o.exceptions.push(i),o.exceptions.length>o.MAX_EXCEPTIONS&&(o.exceptions=o.exceptions.slice(-Math.floor(o.MAX_EXCEPTIONS/2))),e.error(`Exception thrown: ${i.text}`,{url:i.url,line:i.lineNumber})}),a?.enableNetwork&&(o.networkMonitor=o.getManagedTargetNetworkMonitor?.()??new t(o.cdpSession),await o.networkMonitor.enable()),e.info(`ConsoleMonitor enabled`,{network:a?.enableNetwork||!1,exceptions:a?.enableExceptions!==!1})}async function B(t,n){let r=R(t);if(r.playwrightConsoleHandler){n?.enableNetwork&&!r.playwrightNetworkMonitor&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor Playwright session`));return}let a=r.playwrightPage;r.playwrightConsoleHandler=e=>{let t={type:e.type()||`log`,text:e.text(),timestamp:Date.now()};r.messages.push(t),r.messages.length>r.MAX_MESSAGES&&(r.messages=r.messages.slice(-Math.floor(r.MAX_MESSAGES/2)))},a.on(`console`,r.playwrightConsoleHandler),n?.enableExceptions!==!1&&(r.playwrightErrorHandler=e=>{let t={text:e.message,exceptionId:Date.now(),timestamp:Date.now()};r.exceptions.push(t),r.exceptions.length>r.MAX_EXCEPTIONS&&(r.exceptions=r.exceptions.slice(-Math.floor(r.MAX_EXCEPTIONS/2)))},a.on(`pageerror`,r.playwrightErrorHandler)),n?.enableNetwork&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable()),e.info(`ConsoleMonitor enabled (Playwright/camoufox mode)`,{network:n?.enableNetwork||!1})}async function V(t){let n=R(t);if(n.playwrightPage){let e=n.playwrightPage;if(n.playwrightConsoleHandler){try{e.off(`console`,n.playwrightConsoleHandler)}catch{}n.playwrightConsoleHandler=null}if(n.playwrightErrorHandler){try{e.off(`pageerror`,n.playwrightErrorHandler)}catch{}n.playwrightErrorHandler=null}}if(n.playwrightNetworkMonitor&&=(await n.playwrightNetworkMonitor.disable(),null),n.cdpSession){n.networkMonitor&&=(await n.networkMonitor.disable(),null);try{await n.cdpSession.send(`Console.disable`)}catch(t){e.warn(`Failed to disable Console domain:`,t)}try{await n.cdpSession.send(`Runtime.disable`)}catch(t){e.warn(`Failed to disable Runtime domain:`,t)}if(n.usingManagedTargetSession)e.debug(`ConsoleMonitor released managed target session without detaching target`);else try{await n.cdpSession.detach()}catch(t){e.warn(`Failed to detach ConsoleMonitor CDP session:`,t)}n.cdpSession=null,n.usingManagedTargetSession=!1,e.info(`ConsoleMonitor disabled`)}}async function H(e,t,n,r=3e4){return Promise.race([e.send(t,n),new Promise((e,n)=>setTimeout(()=>n(Error(`CDP ${t} timed out after ${r}ms`)),r))])}var U=class{collector;cdpSession=null;networkMonitor=null;fetchInterceptor=null;playwrightNetworkMonitor=null;playwrightPage=null;usingManagedTargetSession=!1;contextSwitchPending=!1;playwrightConsoleHandler=null;playwrightErrorHandler=null;messages=[];MAX_MESSAGES=1e3;exceptions=[];MAX_EXCEPTIONS=500;MAX_INJECTED_DYNAMIC_SCRIPTS=500;MAX_OBJECT_CACHE_SIZE=1e3;objectCache=new Map;initPromise;lastEnableOptions={};constructor(e){this.collector=e,this.touchSplitMembersForTypeCheck()}touchSplitMembersForTypeCheck(){this.MAX_INJECTED_DYNAMIC_SCRIPTS,this.MAX_OBJECT_CACHE_SIZE,this.clearDynamicScriptBuffer,this.resetDynamicScriptMonitoring,this.usingManagedTargetSession,this.playwrightErrorHandler,this.messages,this.MAX_MESSAGES,this.exceptions,this.MAX_EXCEPTIONS,this.formatRemoteObject,this.extractValue}setPlaywrightPage(e){this.playwrightPage=e,this.playwrightNetworkMonitor?.setPage(e)}clearPlaywrightPage(){this.playwrightPage=null,this.contextSwitchPending=!1,this.playwrightConsoleHandler=null,this.playwrightErrorHandler=null,this.playwrightNetworkMonitor?.setPage(null),this.playwrightNetworkMonitor=null}getManagedTargetSession(){return this.collector.getAttachedTargetSession?.()??null}getManagedTargetNetworkMonitor(){return this.collector.getBrowserTargetSessionManager?.()??null}async createCdpSession(){let e=this.getManagedTargetSession();if(e)return{session:e,managed:!0};let t=await this.collector.getActivePage();return{session:await Promise.race([t.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),managed:!1}}markContextChanged(){!this.cdpSession&&!this.playwrightPage&&!this.networkMonitor&&!this.playwrightNetworkMonitor&&!this.fetchInterceptor||(this.contextSwitchPending=!0,this.clearLogs(),this.clearExceptions(),this.networkMonitor?.persistsAcrossContextSwitches?.()||this.clearNetworkRecords(),this.clearObjectCache(),e.info(`ConsoleMonitor marked stale after active context switch`))}async enable(e){if(this.contextSwitchPending&&await this.disable(),this.initPromise){await this.initPromise,await this.applyPostEnableOptions(e);return}this.initPromise=this.doEnable(e);try{await this.initPromise}finally{this.initPromise=void 0}}async doEnable(n){if(this.playwrightPage)return this.lastEnableOptions={...n},B(this,n);if(this.cdpSession){n?.enableNetwork&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new t(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`));return}let{session:r,managed:i}=await this.createCdpSession();await z(this,r,i,n)}async applyPostEnableOptions(n){if(n?.enableNetwork){if(this.lastEnableOptions={...this.lastEnableOptions,...n},this.playwrightPage&&this.playwrightConsoleHandler&&!this.playwrightNetworkMonitor){await B(this,n);return}this.cdpSession&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new t(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`))}}async disable(){try{this.cdpSession&&this.fetchInterceptor&&(await this.fetchInterceptor.disable(),this.fetchInterceptor=null),await V(this)}finally{this.fetchInterceptor=null,this.initPromise=void 0,this.contextSwitchPending=!1,this.objectCache.clear()}}async ensureSession(){if(this.contextSwitchPending){e.info(`ConsoleMonitor context switched, rebinding on demand...`);let t={...this.lastEnableOptions};await this.disable(),await this.enable(t);return}if(!this.cdpSession&&!this.playwrightPage){e.info(`ConsoleMonitor CDP session lost, reinitializing...`),await this.enable(this.lastEnableOptions);return}if(this.cdpSession)try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{e.warn(`ConsoleMonitor CDP session unresponsive (zombie), reinitializing...`),this.cdpSession=null,this.networkMonitor=null,this.fetchInterceptor=null,this.usingManagedTargetSession=!1,await this.enable(this.lastEnableOptions)}}isSessionActive(){return!this.contextSwitchPending&&(this.cdpSession!==null||this.playwrightPage!==null)}getLogs(e){return s(this,e)}async execute(t){await this.ensureSession();try{let n=await H(this.cdpSession,`Runtime.evaluate`,{expression:t,returnByValue:!0});if(n.exceptionDetails)throw e.error(`Console execute error:`,n.exceptionDetails),Error(n.exceptionDetails.text);return e.info(`Console expression executed`),n.result.value}catch(t){throw e.error(`Console execute failed:`,t),t}}clearLogs(){c(this)}getStats(){return l(this)}async close(){try{await this.disable()}finally{this.initPromise=void 0,this.objectCache.clear()}}isNetworkEnabled(){return m(this)}getNetworkStatus(){return h(this)}getNetworkRequests(e){return g(this,e)}getNetworkResponses(e){return _(this,e)}getNetworkActivity(e){return v(this,e)}async getResponseBody(e){return y(this,e)}async getAllJavaScriptResponses(){return b(this)}clearNetworkRecords(){x(this)}async clearInjectedBuffers(){return S(this)}async resetInjectedInterceptors(){return C(this)}getNetworkStats(){return w(this)}async injectXHRInterceptor(e){return T(this,e)}async injectFetchInterceptor(e){return E(this,e)}async getXHRRequests(){return D(this)}async getFetchRequests(){return O(this)}getExceptions(e){return u(this,e)}clearExceptions(){d(this)}async inspectObject(e){return k(this,e)}clearObjectCache(){A(this)}async enableDynamicScriptMonitoring(e){return M(this,e)}async clearDynamicScriptBuffer(){return N(this)}async resetDynamicScriptMonitoring(){return P(this)}async getDynamicScripts(){return F(this)}async injectFunctionTracer(e,t){return I(this,e,t)}async injectPropertyWatcher(e,t,n){return L(this,e,t,n)}async enableFetchIntercept(e){if(await this.ensureSession(),!this.cdpSession)throw Error(`No CDP session available for Fetch interception`);return this.fetchInterceptor||=new a(this.cdpSession),this.fetchInterceptor.enable(e)}async disableFetchIntercept(){if(!this.fetchInterceptor)return{removedRules:0};let e=await this.fetchInterceptor.disable();return this.fetchInterceptor=null,e}async removeFetchInterceptRule(e){if(!this.fetchInterceptor)return!1;let t=await this.fetchInterceptor.removeRule(e);return this.fetchInterceptor.isEnabled()||(this.fetchInterceptor=null),t}getFetchInterceptStatus(){return this.fetchInterceptor?this.fetchInterceptor.listRules():{enabled:!1,rules:[],totalHits:0}}formatRemoteObject(e){return e.value===void 0?e.description?e.description:e.type===`undefined`?`undefined`:e.type===`object`&&e.subtype===`null`?`null`:`[${e.type}]`:String(e.value)}extractValue(e){if(e.value!==void 0)return e.value;if(e.type!==`undefined`)return e.type===`object`&&e.subtype===`null`?null:e.objectId?{__objectId:e.objectId,__type:e.type,__description:e.description}:e.description||`[${e.type}]`}};export{U as ConsoleMonitor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import n from"koffi";var r=e({KERN:()=>i,SM:()=>l,VM_FLAGS:()=>c,VM_PROT:()=>s,VM_REGION_BASIC_INFO_64:()=>9,VM_REGION_BASIC_INFO_COUNT_64:()=>9,dyldGetImageHeader:()=>O,dyldGetImageName:()=>D,dyldImageCount:()=>E,isDarwin:()=>f,isKoffiAvailableOnDarwin:()=>p,kernReturnName:()=>o,machPortDeallocate:()=>_,machTaskSelf:()=>h,machVmAllocate:()=>S,machVmDeallocate:()=>C,machVmProtect:()=>x,machVmReadOverwrite:()=>v,machVmRegion:()=>b,machVmWrite:()=>y,taskForPid:()=>g,taskResume:()=>T,taskSuspend:()=>w});const i={SUCCESS:0,INVALID_ADDRESS:1,PROTECTION_FAILURE:2,NO_SPACE:3,INVALID_ARGUMENT:4,FAILURE:5,RESOURCE_SHORTAGE:6,NOT_RECEIVER:7,NO_ACCESS:8,MEMORY_FAILURE:9,MEMORY_ERROR:10,ALREADY_IN_SET:11,NOT_IN_SET:12,NAME_EXISTS:13,ABORTED:14,INVALID_NAME:15,INVALID_TASK:16,INVALID_RIGHT:17,INVALID_VALUE:18,UREFS_OVERFLOW:19,INVALID_CAPABILITY:20,RIGHT_EXISTS:21,INVALID_HOST:22,MEMORY_PRESENT:23,MEMORY_DATA_MOVED:24,MEMORY_RESTART_COPY:25,INVALID_PROCESSOR_SET:26,POLICY_LIMIT:27,INVALID_POLICY:28,INVALID_OBJECT:29,ALREADY_WAITING:30,DEFAULT_SET:31,EXCEPTION_PROTECTED:32,INVALID_LEDGER:33,INVALID_MEMORY_CONTROL:34,INVALID_SECURITY:35,NOT_DEPRESSED:36,TERMINATED:37,LOCK_SET_DESTROYED:38,LOCK_UNSTABLE:39,LOCK_OWNED:40,LOCK_OWNED_SELF:41,SEMAPHORE_DESTROYED:42,RPC_SERVER_TERMINATED:43,RPC_TERMINATE_ORPHAN:44,RPC_CONTINUE_ORPHAN:45,NOT_SUPPORTED:46,NODE_DOWN:47,NOT_WAITING:48,OPERATION_TIMED_OUT:49,CODESIGN_ERROR:50,POLICY_STATIC:51},a={[i.SUCCESS]:`KERN_SUCCESS`,[i.INVALID_ADDRESS]:`KERN_INVALID_ADDRESS`,[i.PROTECTION_FAILURE]:`KERN_PROTECTION_FAILURE`,[i.NO_SPACE]:`KERN_NO_SPACE`,[i.INVALID_ARGUMENT]:`KERN_INVALID_ARGUMENT`,[i.FAILURE]:`KERN_FAILURE`,[i.NO_ACCESS]:`KERN_NO_ACCESS`,[i.INVALID_TASK]:`KERN_INVALID_TASK`,[i.INVALID_RIGHT]:`KERN_INVALID_RIGHT`,[i.CODESIGN_ERROR]:`KERN_CODESIGN_ERROR`};function o(e){return a[e]??`KERN_UNKNOWN(${e})`}const s={NONE:0,READ:1,WRITE:2,EXECUTE:4,ALL:7},c={FIXED:0,ANYWHERE:1,PURGABLE:2,RANDOM_ADDR:8,OVERWRITE:16384},l={COW:1,PRIVATE:2,EMPTY:3,SHARED:4,TRUESHARED:5,PRIVATE_ALIASED:6,SHARED_ALIASED:7,LARGE_PAGE:8};let u=null,d=null;function f(){return process.platform===`darwin`}function p(){if(d!==null)return d;try{return n.load(`/usr/lib/libSystem.B.dylib`).unload(),d=!0,!0}catch{return d=!1,!1}}function m(){return u||(u=n.load(`/usr/lib/libSystem.B.dylib`),t.debug(`Loaded libSystem.B.dylib via koffi`)),u}function h(){return m().func(`uint32 mach_task_self()`)()}function g(e,t){let n=m().func(`int32 task_for_pid(uint32, int32, _Out_ uint32 *)`),r=Buffer.alloc(4);return{kr:n(e,t,r),task:r.readUInt32LE(0)}}function _(e,t){return m().func(`int32 mach_port_deallocate(uint32, uint32)`)(e,t)}function v(e,t,n){let r=m().func(`int32 mach_vm_read_overwrite(uint32, uint64, uint64, _Out_ uint8_t *, uint64, _Out_ uint64 *)`),i=Buffer.alloc(n),a=Buffer.alloc(8);return{kr:r(e,t,BigInt(n),i,BigInt(n),a),data:i,outsize:a.readBigUInt64LE(0)}}function y(e,t,n){return m().func(`int32 mach_vm_write(uint32, uint64, uint8_t *, uint32)`)(e,t,n,n.length)}function b(e,t){let n=m().func(`int32 mach_vm_region(uint32, _Inout_ uint64 *, _Out_ uint64 *, int32, _Out_ uint8_t *, _Inout_ uint32 *, _Out_ uint32 *)`),r=Buffer.alloc(8);r.writeBigUInt64LE(t);let i=Buffer.alloc(8),a=Buffer.alloc(36),o=Buffer.alloc(4);o.writeUInt32LE(9);let s=n(e,r,i,9,a,o,Buffer.alloc(4)),c={protection:a.readUInt32LE(0),max_protection:a.readUInt32LE(4),inheritance:a.readUInt32LE(8),shared:a.readUInt32LE(12)!==0,reserved:a.readUInt32LE(16)!==0,offset:a.readBigUInt64LE(20),behavior:a.readUInt32LE(28),user_wired_count:a.readUInt32LE(32)};return{kr:s,address:r.readBigUInt64LE(0),size:i.readBigUInt64LE(0),info:c}}function x(e,t,n,r,i){return m().func(`int32 mach_vm_protect(uint32, uint64, uint64, int32, int32)`)(e,t,n,+!!r,i)}function S(e,t,n){let r=m().func(`int32 mach_vm_allocate(uint32, _Inout_ uint64 *, uint64, int32)`),i=Buffer.alloc(8);return i.writeBigUInt64LE(0n),{kr:r(e,i,t,n),address:i.readBigUInt64LE(0)}}function C(e,t,n){return m().func(`int32 mach_vm_deallocate(uint32, uint64, uint64)`)(e,t,n)}function w(e){return m().func(`int32 task_suspend(uint32)`)(e)}function T(e){return m().func(`int32 task_resume(uint32)`)(e)}function E(){return m().func(`uint32 _dyld_image_count()`)()}function D(e){let t=m().func(`const char * _dyld_get_image_name(uint32)`)(e);return t?String(t):``}function O(e){let t=m().func(`void * _dyld_get_image_header(uint32)`);return BigInt(t(e))}export{v as _,s as a,g as b,E as c,o as d,_ as f,x as g,C as h,c as i,f as l,S as m,i as n,O as o,h as p,l as r,D as s,r as t,p as u,b as v,y};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{At as t,Mt as n,jt as r,tr as i}from"./constants-DMv3svps.mjs";import{i as a}from"./outputPaths-D2ddHrOJ.mjs";import{n as o,r as s}from"./artifacts-D-4pSS_N.mjs";import{mkdirSync as c,promises as l,readFileSync as u,writeFileSync as d}from"node:fs";import{join as f,relative as p,resolve as m}from"node:path";import{gunzipSync as h,gzip as g}from"node:zlib";import{promisify as _}from"node:util";const v=/^data:([a-zA-Z0-9/+.-]+);base64,/;function y(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function b(e){return`_offload`in e}function x(e,t,n){c(n,{recursive:!0});let r=m(n,`offload-${new Date().toISOString().replace(/[:.]/g,`-`).replace(`T`,`_`).slice(0,19)}-${Math.random().toString(36).substring(2,8)}.${t?`bin`:`txt`}`),i=t?e.match(v):null;if(i){let t=e.slice(i[0].length);d(r,Buffer.from(t,`base64`))}else d(r,e,`utf8`);return p(a(),r).replace(/\\/g,`/`)}function S(t,n){let r=t.match(v)?.[1],i=t.slice(0,128),a=``;if(n.writeFile)try{a=x(t,r,n.outputDir)}catch(t){e.warn(`[sanitizeForCache] Failed to offload field to disk: ${String(t)}`)}return{_offload:{type:`file`,path:a,size:y(Buffer.byteLength(t,`utf8`)),...r?{mimeType:r}:{},sample:i}}}function C(e,t){return v.test(e)||e.length>t}function w(e,t,n){if(typeof e==`string`)return C(e,t.threshold)?S(e,t):e;if(typeof e!=`object`||!e||b(e)||n.has(e))return e;if(n.add(e),Array.isArray(e)){let r=!1,i=e.map(e=>{let i=w(e,t,n);return i!==e&&(r=!0),i});return n.delete(e),r?i:e}let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=w(o,t,n);e!==o&&(r=!0),i[a]=e}return n.delete(e),r?i:e}function T(e,t={}){return w(e,{threshold:t.threshold??i,outputDir:t.outputDir??o(`offloaded`),writeFile:t.writeFile??!0},new WeakSet)}function E(){return s()}const D=_(g),O=1024;var k=class i{static instance;cache=new Map;cleanupInterval=null;persistDir;metadataPath;persistenceEnabled=!0;disposed=!1;DEFAULT_TTL=t;MAX_TTL=r;MAX_CACHE_SIZE=100;MAX_TOTAL_MEMORY_BYTES=50*1024*1024;AUTO_EXTEND_ON_ACCESS=!0;EXTEND_DURATION=900*1e3;serializationMemo=new WeakMap;metrics={diskWriteCount:0,diskWriteFailCount:0,diskReadCount:0,diskReadFailCount:0,diskReadLazyCount:0,gzipCompressCount:0,gzipDecompressCount:0,evictedBySizeCount:0,evictedByLRUCount:0,totalBytesWritten:0,totalBytesRead:0};constructor(){this.persistDir=f(o(`tmp`),`detailed-data`),this.metadataPath=f(this.persistDir,`.metadata.jsonl`),this.cleanupInterval=setInterval(()=>this.cleanup(),300*1e3),typeof this.cleanupInterval==`object`&&`unref`in this.cleanupInterval&&this.cleanupInterval.unref(),this.init()}static getInstance(){return this.instance||=new i,this.instance}shutdown(){this.disposed=!0,this.cleanupInterval&&=(clearInterval(this.cleanupInterval),null),this.cache.clear(),i.instance=void 0}async init(){try{if(await l.mkdir(this.persistDir,{recursive:!0}),this.disposed||(await this.loadPersistedEntries(),this.disposed))return;await this.cleanupExpired()}catch(t){if(this.disposed)return;e.warn(`Failed to initialize persistence, falling back to memory-only`,t),this.persistenceEnabled=!1}}async loadPersistedEntries(){try{let t=await l.readFile(this.metadataPath,`utf-8`);if(this.disposed)return;let n=t.trim().split(`
|
|
2
|
+
`).filter(Boolean),r=Date.now();for(let e of n){if(this.disposed)return;let t=JSON.parse(e);t.expiresAt>r&&this.cache.set(t.detailId,{data:null,expiresAt:t.expiresAt,createdAt:t.createdAt,lastAccessedAt:r,accessCount:0,size:t.size,persistPath:f(this.persistDir,`${t.detailId}${t.compressed?`.gz`:`.json`}`),compressed:t.compressed})}this.disposed||e.info(`Loaded ${this.cache.size} persisted detail entries`)}catch(t){!this.disposed&&t.code!==`ENOENT`&&e.warn(`Failed to load persisted metadata`,t)}}async cleanupExpired(){if(this.disposed||!this.persistenceEnabled)return;let t=Date.now(),n=[];for(let[e,r]of this.cache.entries())if(r.expiresAt<=t&&(n.push(e),r.persistPath&&(await l.unlink(r.persistPath).catch(()=>{}),this.disposed)))return;n.length>0&&(n.forEach(e=>this.cache.delete(e)),await this.rebuildMetadata(),this.disposed||e.info(`Cleaned up ${n.length} expired detail entries`))}async rebuildMetadata(){if(this.disposed||!this.persistenceEnabled)return;let e=[];for(let[t,n]of this.cache.entries())if(n.persistPath){let r={detailId:t,expiresAt:n.expiresAt,createdAt:n.createdAt,size:n.size};e.push(JSON.stringify(r))}this.disposed||await l.writeFile(this.metadataPath,e.join(`
|
|
3
|
+
`)+`
|
|
4
|
+
`).catch(()=>{})}serializeWithMemo(e){if(typeof e==`object`&&e){let t=this.serializationMemo.get(e);if(t)return t}let t=JSON.stringify(e),n={json:t,size:t.length};return typeof e==`object`&&e&&this.serializationMemo.set(e,n),n}isRecord(e){return typeof e==`object`&&!!e}readPathSegment(e,t){return Object(e)[t]}smartHandle(t,r=n){if(t==null||typeof t!=`object`&&typeof t!=`string`||typeof t==`string`&&t.length<=r)return t;let{json:i,size:a}=this.serializeWithMemo(t);return a<=r?t:(e.info(`Data too large (${(a/1024).toFixed(1)}KB), returning summary with detailId`),this.createDetailedResponseWithSize(t,i,a))}createDetailedResponseWithSize(e,t,n){let r=this.storeWithSize(e,n);return{summary:this.generateSummaryFromJson(e,t,n),detailId:r,hint:`Data too large. Use get_detailed_data("${r}") to retrieve full data, or get_detailed_data("${r}", path="key.subkey") for specific part.`,expiresAt:Date.now()+this.DEFAULT_TTL}}store(e,t){let{size:n}=this.serializeWithMemo(e);return this.storeWithSize(e,n,t)}storeWithSize(t,n,r){this.cache.size>=this.MAX_CACHE_SIZE&&this.evictLRU();let i=T(t),a=i===t?n:this.serializeWithMemo(i).size,o=`detail_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,s=Date.now(),c=r||this.DEFAULT_TTL,l=s+c,u=a>O,d=this.persistenceEnabled?f(this.persistDir,`${o}${u?`.gz`:`.json`}`):void 0,p={data:i,expiresAt:l,createdAt:s,lastAccessedAt:s,accessCount:0,size:a,persistPath:d,compressed:u};return this.cache.set(o,p),d&&this.persistToDisk(d,i,u).then(e=>(this.metrics.diskWriteCount++,this.metrics.totalBytesWritten+=e,this.appendMetadata({detailId:o,expiresAt:l,createdAt:s,size:a,compressed:u}))).catch(t=>{this.metrics.diskWriteFailCount++,e.warn(`Failed to persist ${o}`,t)}),e.debug(`Stored detailed data: ${o}, size: ${(a/1024).toFixed(1)}KB, expires in ${c/1e3}s`),o}async appendMetadata(t){try{await l.appendFile(this.metadataPath,JSON.stringify(t)+`
|
|
5
|
+
`)}catch(t){e.warn(`Failed to append metadata`,t)}}retrieve(t,n){let r=this.cache.get(t);if(!r)throw Error(`DetailId not found or expired: ${t}`);let i=Date.now();if(i>r.expiresAt)throw this.cache.delete(t),r.persistPath&&l.unlink(r.persistPath).catch(()=>{}),Error(`DetailId expired: ${t}`);if(r.data===null&&r.persistPath)try{let e=u(r.persistPath);if(r.compressed){let t=h(e);r.data=JSON.parse(t.toString(`utf-8`)),this.metrics.gzipDecompressCount++,this.metrics.totalBytesRead+=t.length}else r.data=JSON.parse(e.toString(`utf-8`)),this.metrics.totalBytesRead+=e.length;this.metrics.diskReadCount++,this.metrics.diskReadLazyCount++}catch(n){throw this.metrics.diskReadFailCount++,e.warn(`Failed to load persisted data for ${t}`,n),Error(`DetailId not found or expired: ${t}`,{cause:n})}return r.lastAccessedAt=i,r.accessCount++,this.AUTO_EXTEND_ON_ACCESS&&r.expiresAt-i<300*1e3&&(r.expiresAt=Math.min(i+this.EXTEND_DURATION,i+this.MAX_TTL),e.debug(`Auto-extended detailId ${t}, new expiry: ${new Date(r.expiresAt).toISOString()}`)),n?this.getByPath(r.data,n):r.data}getByPath(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)throw Error(`Path not found: ${t} (stopped at ${e})`);r=this.readPathSegment(r,e)}return r}generateSummaryFromJson(e,t,n){let r={type:Array.isArray(e)?`array`:typeof e,size:n,sizeKB:(n/1024).toFixed(1)+`KB`,preview:t.substring(0,200)+(n>200?`...`:``)};if(this.isRecord(e)){let t=Object.keys(e);if(r.structure={keys:t.slice(0,50)},Array.isArray(e))r.structure.length=e.length;else{let n=t.filter(t=>typeof e[t]==`function`),i=t.filter(t=>typeof e[t]!=`function`);r.structure.methods=n.slice(0,30),r.structure.properties=i.slice(0,50)}}return r}cleanup(){let t=Date.now(),n=0;for(let[e,r]of this.cache.entries())t>r.expiresAt&&(this.cache.delete(e),n++);n>0&&e.debug(`Cleaned ${n} expired detailed data entries`)}evictLRU(){if(this.cache.size===0)return;let t=this.computeTotalMemory();if(t>this.MAX_TOTAL_MEMORY_BYTES){this.evictBySize(t-this.MAX_TOTAL_MEMORY_BYTES);return}let n=null,r=1/0;for(let[e,t]of this.cache.entries())t.lastAccessedAt<r&&(r=t.lastAccessedAt,n=e);if(n){let t=this.cache.get(n);this.cache.delete(n),this.metrics.evictedByLRUCount++,e.info(`Evicted LRU entry: ${n}, last accessed: ${new Date(t.lastAccessedAt).toISOString()}, access count: ${t.accessCount}`)}}evictBySize(t){let n=Array.from(this.cache.entries()).toSorted((e,t)=>e[1].lastAccessedAt-t[1].lastAccessedAt),r=0;for(let[i,a]of n){if(r>=t)break;this.cache.delete(i),r+=a.size,this.metrics.evictedBySizeCount++,e.info(`Evicted oversized entry: ${i}, freed: ${(a.size/1024).toFixed(1)}KB`)}}computeTotalMemory(){let e=0;for(let t of this.cache.values())e+=t.size;return e}async persistToDisk(e,t,n){let r=JSON.stringify(t);if(n){let t=await D(Buffer.from(r,`utf-8`));return await l.writeFile(e,t),this.metrics.gzipCompressCount++,t.length}return await l.writeFile(e,r,`utf-8`),r.length}extend(t,n){let r=this.cache.get(t);if(!r)throw Error(`DetailId not found: ${t}`);let i=Date.now();if(i>r.expiresAt)throw Error(`DetailId already expired: ${t}`);let a=n||this.EXTEND_DURATION,o=Math.min(r.expiresAt+a,i+this.MAX_TTL);r.expiresAt=o,e.info(`Extended detailId ${t} by ${a/1e3}s, new expiry: ${new Date(o).toISOString()}`)}getStats(){let e=0,t=0,n=0,r=0,i=Array.from(this.cache.values());for(let a of i)e+=a.size,t+=a.accessCount,a.persistPath&&n++,a.compressed&&r++;return{cacheSize:this.cache.size,maxCacheSize:this.MAX_CACHE_SIZE,totalMemoryMB:(e/(1024*1024)).toFixed(2),maxMemoryMB:(this.MAX_TOTAL_MEMORY_BYTES/(1024*1024)).toFixed(0),memoryUtilization:(e/this.MAX_TOTAL_MEMORY_BYTES*100).toFixed(1)+`%`,defaultTTLSeconds:this.DEFAULT_TTL/1e3,maxTTLSeconds:this.MAX_TTL/1e3,totalSizeKB:(e/1024).toFixed(1),avgAccessCount:i.length>0?(t/i.length).toFixed(1):`0`,autoExtendEnabled:this.AUTO_EXTEND_ON_ACCESS,extendDurationSeconds:this.EXTEND_DURATION/1e3,persistence:{enabled:this.persistenceEnabled,persistedCount:n,compressedCount:r,gzipEnabled:!0,gzipThresholdKB:(O/1024).toFixed(1)},metrics:{...this.metrics}}}getDetailedStats(){let e=Date.now(),t=Array.from(this.cache.entries()).map(([t,n])=>({detailId:t,sizeKB:(n.size/1024).toFixed(1),createdAt:new Date(n.createdAt).toISOString(),lastAccessedAt:new Date(n.lastAccessedAt).toISOString(),expiresAt:new Date(n.expiresAt).toISOString(),remainingSeconds:Math.max(0,Math.floor((n.expiresAt-e)/1e3)),accessCount:n.accessCount,isExpired:e>n.expiresAt}));return t.sort((e,t)=>new Date(t.lastAccessedAt).getTime()-new Date(e.lastAccessedAt).getTime()),t}clear(){this.cache.clear(),e.info(`Cleared all detailed data cache`)}};export{T as a,E as i,v as n,y as r,k as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./ToolCatalog-DgmQXdsm.mjs";const t=[`search`,`workflow`,`full`];function n(e){return e.profiles&&e.profiles.length>0?e.profiles:t}function r(t,n){for(let r of t.selectedTools)if(e(r.name)===n)return!0;for(let r of t.activatedToolNames){let i=t.extensionToolsByName.get(r);if(i){if(i.domain===n)return!0;continue}if(e(r)===n)return!0}return!1}function i(e,t){if(r(e,t)){e.enabledDomains.add(t);return}e.enabledDomains.delete(t)}function a(e,t){return n(t).includes(e)}function o(e,t,n=`activate_tools`){if(e.activatedToolNames.has(t.name))return e.enabledDomains.add(t.domain),t.activationSource??=n,t.activatedAt??=new Date().toISOString(),!1;let r=e.registerSingleTool(t.tool);return e.activatedToolNames.add(t.name),e.activatedRegisteredTools.set(t.name,r),t.registeredTool=r,t.activationSource=n,t.activatedAt=new Date().toISOString(),e.enabledDomains.add(t.domain),t.handler&&e.router.addHandlers({[t.name]:t.handler}),!0}function s(e,t,n={}){let r=t.registeredTool??e.activatedRegisteredTools.get(t.name),a=!!r||e.activatedToolNames.has(t.name)||e.activatedRegisteredTools.has(t.name);if(r&&!n.skipRegisteredToolRemoval)try{r.remove()}catch(e){n.onRemoveError?.(e)}return e.router.removeHandler(t.name),e.activatedToolNames.delete(t.name),e.activatedRegisteredTools.delete(t.name),t.registeredTool=void 0,t.activationSource=void 0,t.activatedAt=void 0,n.removeDefinition&&e.extensionToolsByName.delete(t.name),i(e,t.domain),a}export{a as n,s as r,o as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./chunk-
|
|
1
|
+
import{n as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";var n=class n{static instance=null;activeProfile=null;available=null;constructor(){}static getInstance(){return n.instance||=new n,n.instance}isAvailable(){if(this.available!==null)return this.available;try{e.resolve(`fingerprint-generator`),e.resolve(`fingerprint-injector`),this.available=!0}catch{this.available=!1}return this.available}async generateFingerprint(e){if(!this.isAvailable())return t.warn(`fingerprint-generator not installed. Run: pnpm add fingerprint-generator fingerprint-injector`),null;try{let{FingerprintGenerator:n}=await import(`fingerprint-generator`),r=new n,i={};e?.os&&(i.operatingSystems=[{windows:`windows`,macos:`macos`,linux:`linux`}[e.os]??`windows`]),e?.browser&&(i.browsers=[e.browser]),e?.locale&&(i.locales=[e.locale]),e?.screen&&(i.screen=e.screen);let a=r.getFingerprint(i);return this.activeProfile={fingerprint:a.fingerprint,headers:a.headers??{},generatedAt:Date.now(),os:e?.os??`windows`,browser:e?.browser??`chrome`},t.info(`Fingerprint generated for ${this.activeProfile.os}/${this.activeProfile.browser}`),this.activeProfile}catch(e){return t.error(`Failed to generate fingerprint:`,e),null}}async injectFingerprint(e,n){if(!this.isAvailable())throw Error(`fingerprint-injector not installed`);try{let{newInjectedPage:r}=await import(`fingerprint-injector`);await r(e,{fingerprint:`fingerprint`in n?n.fingerprint:n}),t.info(`Fingerprint injected into page`)}catch(e){throw t.error(`Failed to inject fingerprint:`,e),e}}getActiveProfile(){return this.activeProfile}clearProfile(){this.activeProfile=null}static resetInstance(){n.instance=null}};export{n as FingerprintManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{U as e,W as t}from"./constants-DMv3svps.mjs";import{t as n}from"./ToolError-g3rjWzhx.mjs";import{t as r}from"./Win32API-DoP3MMHS.mjs";import{_ as i,a,c as o,d as s,f as c,g as l,h as u,i as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v,v as y,y as b}from"./Win32Debug-DwF8mQGm.mjs";import{randomUUID as x}from"node:crypto";const S=e=>`0x${e.toString(16).toUpperCase()}`;var C=class{breakpoints=new Map;attachedPids=new Set;drAllocation=[!1,!1,!1,!1];async attach(e){if(!this.attachedPids.has(e)){d(e),p(!1),this.attachedPids.add(e);for(let e=0;e<100;e++){let e=u(100);if(!e)break;f(e.processId,e.threadId,h.CONTINUE)}}}async detach(e){for(let[t,n]of this.breakpoints)n.pid===e&&(this.clearDR(e,n.drIndex),this.drAllocation[n.drIndex]=!1,this.breakpoints.delete(t));if(this.attachedPids.has(e)){try{a(e)}catch{}this.attachedPids.delete(e)}}async setBreakpoint(e,t,n,r=4){this.attachedPids.has(e)||await this.attach(e);let i=this.allocateDR(),a=BigInt(t.startsWith(`0x`)?t:`0x${t}`);this.applyDRToAllThreads(e,i,a,n,r,!0);let o={id:x(),pid:e,address:`0x${a.toString(16).toUpperCase()}`,access:n,size:r,enabled:!0,drIndex:i,hitCount:0};return this.breakpoints.set(o.id,o),o}async removeBreakpoint(e){let t=this.breakpoints.get(e);return t?(this.clearDR(t.pid,t.drIndex),this.drAllocation[t.drIndex]=!1,this.breakpoints.delete(e),!0):!1}listBreakpoints(){return Array.from(this.breakpoints.values()).map(e=>({id:e.id,address:e.address,access:e.access,size:e.size,enabled:e.enabled,hitCount:e.hitCount,lastHit:e.lastHit}))}async waitForHit(t){let n=t??e,r=Date.now()+n;for(;Date.now()<r;){let e=Math.max(100,r-Date.now()),t=u(Math.min(e,500));if(t)if(t.exceptionCode===g.SINGLE_STEP){let e=this.processHit(t.threadId,t.processId,t.exceptionAddress);if(f(t.processId,t.threadId,h.CONTINUE),e)return e}else f(t.processId,t.threadId,h.CONTINUE)}return null}async traceAccess(n,r,i,a,o){let s=a??t,c=o??e,l=await this.setBreakpoint(n,r,i),u=[],d=Date.now()+c;for(;u.length<s&&Date.now()<d;){let e=await this.waitForHit(Math.min(1e3,d-Date.now()));e?.breakpointId===l.id&&u.push(e)}return await this.removeBreakpoint(l.id),u}allocateDR(){for(let e=0;e<4;e++)if(!this.drAllocation[e])return this.drAllocation[e]=!0,e;throw new n(`PREREQUISITE`,`All 4 hardware breakpoint registers (DR0-DR3) are in use`)}applyDRToAllThreads(e,t,n,a,u,d){let f=o(e),p={execute:`execute`,write:`write`,readwrite:`readwrite`,read:`read`};for(let e of f){let o;try{o=i(e)}catch{continue}try{m(o);let e=v(o,_.ALL),r=[72,80,88,96];d?e.writeBigUInt64LE(n,r[t]):e.writeBigUInt64LE(0n,r[t]);let i=Array.from(this.breakpoints.values()).filter(e=>e.enabled).map(e=>({drIndex:e.drIndex,enabled:!0,access:p[e.access],size:e.size}));d&&i.push({drIndex:t,enabled:!0,access:p[a],size:u});let f=l(i);e.writeBigUInt64LE(f,112),b(e,{contextFlags:_.ALL}),c(o,e),s(o)}catch{try{s(o)}catch{}}finally{r(o)}}}clearDR(e,t){this.applyDRToAllThreads(e,t,0n,`write`,1,!1)}processHit(e,t,n){let a;try{a=i(e)}catch{return null}try{let n=v(a,_.ALL),r=y(n);for(let[i,o]of this.breakpoints){if(o.pid!==t)continue;let s=1n<<BigInt(o.drIndex);if(r.dr6&s)return o.hitCount++,o.lastHit=Date.now(),n.writeBigUInt64LE(0n,104),c(a,n),{breakpointId:i,address:o.address,accessAddress:o.address,instructionAddress:S(r.rip),threadId:e,accessType:o.access,timestamp:Date.now(),registers:{rax:S(r.rax),rbx:S(r.rbx),rcx:S(r.rcx),rdx:S(r.rdx),rsi:S(r.rsi),rdi:S(r.rdi),rsp:S(r.rsp),rbp:S(r.rbp),r8:S(r.r8),r9:S(r.r9),r10:S(r.r10),r11:S(r.r11),r12:S(r.r12),r13:S(r.r13),r14:S(r.r14),r15:S(r.r15),rip:S(r.rip),rflags:`0x${r.eflags.toString(16).toUpperCase()}`}}}return null}finally{r(a)}}};const w=new C;export{C as HardwareBreakpointEngine,w as hardwareBreakpointEngine};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{cn as t,ln as n,on as r,sn as i}from"./constants-DMv3svps.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{b as o,d as s,t as c}from"./Win32API-DoP3MMHS.mjs";import{m as l}from"./Win32Debug-DwF8mQGm.mjs";import u from"koffi";const d={FIXED:1,FREE:2,MOVEABLE:4},f={DEFAULT:1,SHARED:2};let p=null;function m(){let e=u.load(`kernel32.dll`);return{CreateToolhelp32Snapshot:e.func(`CreateToolhelp32Snapshot`,`intptr`,[`uint32`,`uint32`]),Heap32ListFirst:e.func(`Heap32ListFirst`,`bool`,[`intptr`,`_Inout_ uint8_t *`]),Heap32ListNext:e.func(`Heap32ListNext`,`bool`,[`intptr`,`_Inout_ uint8_t *`]),Heap32First:e.func(`Heap32First`,`bool`,[`_Inout_ uint8_t *`,`uint32`,`uintptr_t`]),Heap32Next:e.func(`Heap32Next`,`bool`,[`_Inout_ uint8_t *`]),CloseHandle:e.func(`int CloseHandle(intptr)`),HEAPLIST32_SIZE:36,HEAPENTRY32_SIZE:56}}function h(){return p||=m(),p}const g=[[`0-64B`,0,64],[`64-256B`,64,256],[`256B-1KB`,256,1024],[`1-4KB`,1024,4096],[`4-16KB`,4096,16384],[`16-64KB`,16384,65536],[`64KB-1MB`,65536,1048576],[`>1MB`,1048576,2**53-1]];function _(e){for(let t=0;t<g.length;t++){let n=g[t];if(e>=n[1]&&e<n[2])return t}return g.length-1}var v=class{async enumerateHeaps(e){let t=h(),n=t.CreateToolhelp32Snapshot(l.SNAPHEAPLIST,e);if(n===-1n&&typeof n==`bigint`)throw new a(`RUNTIME`,`Failed to create heap snapshot for PID ${e}`);let i=[];try{let a=Buffer.alloc(t.HEAPLIST32_SIZE);a.writeBigUInt64LE(BigInt(t.HEAPLIST32_SIZE),0);let o=t.Heap32ListFirst(n,a);for(;o;){let s=a.readUInt32LE(8),c=a.readBigUInt64LE(12),l=a.readUInt32LE(20),u=await this.enumerateBlocksInternal(e,c,r);i.push({heapId:`0x${c.toString(16)}`,processId:s,flags:l,isDefault:(l&f.DEFAULT)!==0,blockCount:u.length,totalSize:u.reduce((e,t)=>e+t.size,0)}),a.writeBigUInt64LE(BigInt(t.HEAPLIST32_SIZE),0),o=t.Heap32ListNext(n,a)}}finally{t.CloseHandle(n)}return{heaps:i,stats:this.computeStats(i,[])}}async enumerateBlocks(e,t,n){let i=BigInt(t),a=n?.maxBlocks??r;return this.enumerateBlocksInternal(e,i,a)}async getStats(e){let{heaps:t}=await this.enumerateHeaps(e),n=[];for(let i of t){let t=await this.enumerateBlocksInternal(e,BigInt(i.heapId),r);n.push(...t)}return this.computeStats(t,n)}async detectAnomalies(e){let t=[],{heaps:n}=await this.enumerateHeaps(e);for(let i of n){let n=await this.enumerateBlocksInternal(e,BigInt(i.heapId),r);this.detectSpray(n,i.heapId,t),this.detectSuspiciousSizes(n,i.heapId,t),await this.detectPossibleUaf(e,n,i.heapId,t)}return t}async enumerateBlocksInternal(e,t,n){let r=h(),i=[],a=Buffer.alloc(r.HEAPENTRY32_SIZE);a.writeBigUInt64LE(BigInt(r.HEAPENTRY32_SIZE),0);let o=r.Heap32First(a,e,t);for(;o&&i.length<n;){let e=a.readBigUInt64LE(16),n=Number(a.readBigUInt64LE(24)),s=a.readUInt32LE(32);i.push({address:`0x${e.toString(16)}`,size:n,flags:s,heapId:`0x${t.toString(16)}`,isFree:(s&d.FREE)!==0}),a.writeBigUInt64LE(BigInt(r.HEAPENTRY32_SIZE),0),o=r.Heap32Next(a)}return i}computeStats(e,t){let n=g.map(([e])=>({range:e,count:0,totalBytes:0})),r=0,i=0,a=0,o=2**53-1;for(let e of t){r+=e.size,e.isFree&&(i+=e.size),e.size>a&&(a=e.size),!e.isFree&&e.size<o&&(o=e.size);let t=_(e.size);n[t].count++,n[t].totalBytes+=e.size}return o===2**53-1&&(o=0),r===0&&e.length>0&&(r=e.reduce((e,t)=>e+t.totalSize,0)),{totalHeaps:e.length,totalBlocks:t.length||e.reduce((e,t)=>e+t.blockCount,0),totalSize:r,freeSize:i,usedSize:r-i,largestBlock:a,smallestBlock:o,averageBlockSize:t.length>0?Math.round(r/t.length):0,sizeDistribution:n,fragmentationRatio:r>0?i/r:0}}detectSpray(e,n,r){let a=new Map;for(let t of e){if(t.isFree)continue;let e=Math.round(t.size/i)*i,n=a.get(e)??[];n.push(t),a.set(e,n)}for(let[e,i]of a)i.length>=t&&r.push({type:`heap_spray_pattern`,severity:`high`,address:i[0].address,details:`${i.length} blocks of ~${e} bytes detected — possible heap spray`,heapId:n})}detectSuspiciousSizes(e,t,r){for(let i of e)i.size===0?r.push({type:`suspicious_size`,severity:`medium`,address:i.address,details:`Block with zero size`,heapId:t}):i.size>n&&r.push({type:`suspicious_size`,severity:`medium`,address:i.address,details:`Unusually large block: ${(i.size/(1024*1024)).toFixed(1)} MB`,heapId:t})}async detectPossibleUaf(t,n,r,i){let a=n.filter(e=>e.isFree&&e.size>=8).slice(0,100),l=null;try{l=o(t);for(let e of a){let t=BigInt(e.address),n=s(l,t,8);n&&n.readBigUInt64LE(0)!==0n&&i.push({type:`possible_uaf`,severity:`low`,address:e.address,details:`Free block has non-zero data: 0x${n.readBigUInt64LE(0).toString(16)}`,heapId:r})}}catch(n){e.debug(`UAF check failed for PID ${t}: ${n}`)}finally{l&&c(l)}}};const y=new v;export{v as HeapAnalyzer,y as heapAnalyzer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{i as t}from"./ToolCatalog-DgmQXdsm.mjs";import{n}from"./ServerRuntimeState-CgqBBwfd.mjs";function r(t,n,r,i){if(o(t,n),r<=0)return;let a=r*60*1e3,c=new Set(i),l=setTimeout(()=>{e.info(`Domain "${n}" TTL expired (${r}min) — auto-deactivating ${c.size} tools`),s(t,n).catch(t=>{e.error(`Failed to deactivate domain "${n}" on TTL expiry:`,t)})},a);t.domainTtlEntries.set(n,{timer:l,ttlMs:a,toolNames:c})}function i(t,n){let r=t.domainTtlEntries.get(n);if(!r)return;clearTimeout(r.timer);let i=r.ttlMs/6e4;r.timer=setTimeout(()=>{e.info(`Domain "${n}" TTL expired (${i}min) — auto-deactivating`),s(t,n).catch(t=>{e.error(`Failed to deactivate domain "${n}" on TTL expiry:`,t)})},r.ttlMs)}function a(e,n){let r=t(n);if(!r){let t=e.extensionToolsByName.get(n);t&&(r=t.domain)}r&&e.domainTtlEntries.has(r)&&i(e,r)}function o(e,t){let r=e.domainTtlEntries.get(t);r&&(clearTimeout(r.timer),e.domainTtlEntries.delete(t)),n(e)?.clearPendingDomainActivation(t)}async function s(r,i){let a=r.domainTtlEntries.get(i);if(!a)return;let o=a.toolNames;r.domainTtlEntries.delete(i),n(r)?.clearPendingDomainActivation(i);let s=0;for(let t of o){if(!r.activatedToolNames.has(t))continue;let n=r.activatedRegisteredTools.get(t);if(n)try{n.remove()}catch(n){e.warn(`Failed to remove tool "${t}" on domain TTL expiry:`,n)}r.router.removeHandler(t),r.activatedToolNames.delete(t),r.activatedRegisteredTools.delete(t);let i=r.extensionToolsByName.get(t);i&&(i.registeredTool=void 0),s++}if(s>0){r.enabledDomains.delete(i);for(let e of r.activatedToolNames)if(t(e)===i){r.enabledDomains.add(i);break}for(let e of r.selectedTools)if(t(e.name)===i){r.enabledDomains.add(i);break}try{await r.server.sendToolListChanged()}catch(t){e.warn(`sendToolListChanged failed after domain TTL expiry:`,t)}e.info(`Domain "${i}" deactivated: removed ${s} tools`)}}export{a as n,r,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{$r as t,Ai as n,Ci as r,Di as i,Ei as a,Jr as o,Oi as s,Qr as c,Si as l,Ti as u,Yr as d,Zr as f,_i as p,ai as m,bi as h,ci as g,di as _,ei as v,fi as y,gi as b,hi as x,ii as ee,li as te,mi as ne,ni as S,oi as re,pi as ie,qr as ae,ri as C,si as w,ti as oe,ui as se,vi as ce,xi as T,yi as le}from"./constants-DMv3svps.mjs";import{t as E}from"./search-defaults-CJik67or.mjs";import{i as D,l as O,m as k,n as A,p as ue,r as de}from"./ToolCatalog-DgmQXdsm.mjs";import{t as fe}from"./ProcessRegistry-D5y1yuP2.mjs";import{t as pe}from"./RingBuffer-B6RTHmij.mjs";import{Worker as me}from"worker_threads";const he=[[`navigate`,`go`,`open`,`visit`,`browse`,`load`],[`intercept`,`capture`,`monitor`,`sniff`,`collect`,`record`,`track`],[`request`,`fetch`,`xhr`,`ajax`,`http`,`api`],[`authenticate`,`auth`,`login`,`credential`,`token`,`jwt`,`session`],[`breakpoint`,`pause`,`halt`,`stop`,`break`],[`step`,`next`,`continue`,`resume`],[`deobfuscate`,`beautify`,`unminify`,`decode`,`transform`,`decompile`],[`screenshot`,`snapshot`,`image`,`picture`,`photo`],[`evaluate`,`execute`,`run`,`eval`,`invoke`,`call`],[`element`,`node`,`selector`,`dom`,`component`],[`click`,`tap`,`press`,`interact`,`trigger`],[`type`,`input`,`enter`,`fill`,`write`],[`cookie`,`localstorage`,`storage`,`cache`,`indexeddb`],[`websocket`,`ws`,`socket`,`realtime`],[`scroll`,`swipe`,`drag`],[`search`,`find`,`query`,`lookup`,`discover`,`locate`],[`hook`,`patch`,`override`,`replace`,`wrap`,`proxy`],[`script`,`code`,`source`,`javascript`,`js`],[`bundle`,`webpack`,`module`,`pack`,`chunk`],[`block`,`filter`,`deny`,`reject`,`prevent`],[`allow`,`permit`,`whitelist`,`accept`,`enable`],[`remove`,`delete`,`clear`,`clean`,`purge`,`erase`],[`list`,`show`,`display`,`enumerate`,`get`],[`set`,`configure`,`config`,`setup`,`assign`],[`stealth`,`antidetect`,`fingerprint`,`evasion`,`undetected`],[`mobile`,`device`,`emulate`,`responsive`,`phone`],[`performance`,`profile`,`benchmark`,`metric`,`vitals`],[`register`,`signup`,`account`,`enroll`,`join`],[`captcha`,`challenge`,`verification`,`verify`,`solve`],[`tab`,`window`,`page`],[`inspect`,`examine`,`analyze`,`analyse`,`debug`,`investigate`],[`wait`,`delay`,`sleep`,`timeout`,`poll`],[`close`,`disconnect`,`quit`,`exit`,`shutdown`,`terminate`],[`traffic`,`network`,`request`,`response`,`connection`],[`heap`,`memory`,`allocation`,`gc`,`garbage`],[`export`,`save`,`dump`,`download`,`extract`],[`replay`,`resend`,`repeat`,`redo`,`retry`],[`variable`,`scope`,`local`,`closure`,`context`],[`watch`,`observe`,`monitor`,`trace`,`track`],[`protobuf`,`proto`,`binary`,`msgpack`,`grpc`],[`wasm`,`webassembly`,`assembly`],[`sse`,`eventsource`,`stream`,`streaming`],[`graphql`,`gql`,`introspect`,`mutation`,`subscription`],[`v8`,`heap`,`snapshot`,`bytecode`,`jit`,`turbofan`,`ignition`,`hiddenclass`],[`tls`,`ssl`,`boringssl`,`cert`,`certificate`,`pinning`,`handshake`,`keylog`],[`skia`,`gpu`,`render`,`scenegraph`,`scene`,`draw`,`paint`,`raster`,`layer`],[`frida`,`ghidra`,`ida`,`unidbg`,`jadx`,`binary`,`disassemble`,`decompile`,`instrument`],[`mojo`,`ipc`,`chromium`,`interface`,`broker`,`message`],[`syscall`,`etw`,`strace`,`dtrace`,`kernel`,`systemcall`,`tracefs`],[`adb`,`android`,`webview`,`apk`,`dalvik`,`art`,`emulator`],[`extension`,`plugin`,`addon`,`webhook`,`c2`,`bluetooth`,`ble`,`hid`,`serial`,`registry`]];var ge=class e{reverseMap;constructor(){this.reverseMap=e.buildReverseMap(he)}expand(e){let t=this.reverseMap.get(e.toLowerCase());return t?[...t]:[]}expandQuery(e){let t=new Set(e.map(e=>e.toLowerCase())),n=[],r=x;for(let i of e){let e=this.reverseMap.get(i.toLowerCase());if(!e)continue;let a=0;for(let i of e){if(a>=r)break;t.has(i)||(n.push(i),t.add(i),a++)}}return n}static buildReverseMap(e){let t=new Map;for(let n of e)for(let e of n){let r=e.toLowerCase(),i=t.get(r);i||(i=new Set,t.set(r,i));for(let e of n){let t=e.toLowerCase();t!==r&&i.add(t)}}return t}};const _e=c,ve=f;var ye=class e{queryCategoryProfiles;cjkQueryAliases;synonymExpander;constructor(t){this.queryCategoryProfiles=t?.queryCategoryProfiles===void 0?e.compileQueryCategoryProfiles(E.queryCategoryProfiles):e.compileQueryCategoryProfiles(t.queryCategoryProfiles),this.cjkQueryAliases=t?.cjkQueryAliases===void 0?e.compileCjkQueryAliasRules(E.cjkQueryAliases):e.compileCjkQueryAliasRules(t.cjkQueryAliases),this.synonymExpander=new ge}static compileQueryCategoryProfiles(e){return e.flatMap(e=>{if(!e||typeof e.pattern!=`string`||!Array.isArray(e.domainBoosts))return[];let t;try{t=new RegExp(e.pattern,e.flags)}catch{return[]}let n=new Map(e.domainBoosts.flatMap(e=>!e||typeof e.domain!=`string`||e.domain.length===0||typeof e.weight!=`number`||!Number.isFinite(e.weight)?[]:[[e.domain,e.weight]]));return[{pattern:t,domainBoosts:n}]})}static compileCjkQueryAliasRules(e){return e.flatMap(e=>{if(!e||typeof e.pattern!=`string`||!Array.isArray(e.tokens))return[];let t;try{t=new RegExp(e.pattern,e.flags)}catch{return[]}let n=e.tokens.filter(e=>typeof e==`string`&&e.length>0);return[{pattern:t,tokens:n}]})}detectQueryCategoryBoosts(e){let t=new Map;for(let n of this.queryCategoryProfiles)if(n.pattern.test(e))for(let[e,r]of n.domainBoosts){let n=t.get(e)??1;t.set(e,Math.max(n,r))}return t}expandCjkAliasTokens(e){let t=e.toLowerCase(),n=new Set;for(let e of this.cjkQueryAliases)if(e.pattern.test(t))for(let t of e.tokens)n.add(t);return[...n]}tokenise(e,t){let n=e.replace(/[_-]/g,` `);n=n.replace(/([\u4e00-\u9fff])/g,` $1 `);let r=n.split(/[^a-zA-Z0-9\u4e00-\u9fff]+/).filter(Boolean),i=[];for(let e of r){let t=e.toLowerCase(),n=e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/\s+/);if(n.length>1){for(let e of n)i.push(e.toLowerCase());i.push(t)}else i.push(t)}return i.push(...this.expandCjkAliasTokens(e)),t?.expandSynonyms&&i.push(...this.synonymExpander.expandQuery(i)),i}getK1(){return _e}getB(){return ve}},be=class{worker=null;ready=!1;nextId=0;pending=new Map;isReady(){return this.ready}async embed(e){this.ensureWorker();let t=this.nextId++;return new Promise((n,r)=>{this.pending.set(t,{resolve:n,reject:r}),this.worker.postMessage({type:`embed`,id:t,text:e})})}async embedBatch(e){if(e.length===0)return[];this.ensureWorker();let t=this.nextId++;return new Promise((n,r)=>{this.pending.set(t,{resolve:n,reject:r}),this.worker.postMessage({type:`embed_batch`,id:t,texts:e})})}async terminate(){if(this.worker){for(let[,e]of this.pending)e.reject(Error(`EmbeddingEngine terminated`));this.pending.clear(),await this.worker.terminate(),this.worker=null,this.ready=!1}}ensureWorker(){if(this.worker)return;let e=new URL(`./EmbeddingWorker.js`,import.meta.url);this.worker=new me(e),typeof this.worker.unref==`function`&&this.worker.unref(),fe.register(this.worker),this.worker.on(`message`,e=>{let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.type===`result`?(this.ready=!0,t.resolve(e.embedding)):e.type===`error`&&t.reject(Error(e.message??`Unknown worker error`)))}),this.worker.on(`error`,e=>{for(let[,t]of this.pending)t.reject(e);this.pending.clear(),this.worker=null,this.ready=!1}),this.worker.on(`exit`,e=>{if(e!==0){let t=Error(`Embedding worker exited with code ${e}`);for(let[,e]of this.pending)e.reject(t);this.pending.clear()}this.worker=null,this.ready=!1})}},j=class e{compiledRules;constructor(t){this.compiledRules=t===void 0?e.compileIntentToolBoostRules(E.intentToolBoostRules):e.compileIntentToolBoostRules(t)}static compileIntentToolBoostRules(e){let t=[];for(let n of e){if(!n||typeof n.pattern!=`string`||!Array.isArray(n.boosts)||n.boosts.length===0)continue;let e;try{e=new RegExp(n.pattern,n.flags??`i`)}catch{continue}let r=n.boosts.filter(e=>e&&typeof e.tool==`string`&&e.tool.length>0).map(e=>({tool:e.tool,bonus:Number.isFinite(e.bonus)?e.bonus:0})).filter(e=>e.bonus>0);r.length!==0&&t.push({pattern:e,boosts:r})}return t}resolveIntentToolBonuses(e){let t=e.toLowerCase(),n=new Map;for(let e of this.compiledRules)if(e.pattern.test(t))for(let{tool:t,bonus:r}of e.boosts){let e=n.get(t)??0;n.set(t,Math.max(e,r))}return n}getCompiledRules(){return this.compiledRules}},M=class e{trigramSets;constructor(t){this.trigramSets=t.map(t=>e.extractTrigrams(t))}search(t,n=h){let r=e.extractTrigrams(t);if(r.size===0)return new Map;let i=new Map;for(let t=0;t<this.trigramSets.length;t++){let a=this.trigramSets[t];if(a.size===0)continue;let o=e.jaccardSimilarity(r,a);o>=n&&i.set(t,o)}return i}static extractTrigrams(e){let t=e.toLowerCase().replace(/[_\-\s]+/g,``),n=new Set;for(let e=0;e<=t.length-3;e++)n.add(t.slice(e,e+3));return n}static jaccardSimilarity(e,t){let n=0,[r,i]=e.size<=t.size?[e,t]:[t,e];for(let e of r)i.has(e)&&n++;let a=e.size+t.size-n;return a===0?0:n/a}};const N=.1,P=.8;var xe=class{vectorWeight;lastVectorRanking=null;topN;learnUp;learnDown;constructor(e){this.vectorWeight=e?.vectorCosineWeight??r,this.topN=Math.max(1,i),this.learnUp=Math.max(0,s),this.learnDown=Math.max(0,a)}getVectorWeight(){return this.vectorWeight}recordVectorRanking(e){this.lastVectorRanking=e}recordToolCallFeedback(e,t){if(!this.lastVectorRanking||!t)return!1;let n=this.lastVectorRanking.get(e),r=this.vectorWeight;return n===void 0?this.vectorWeight=Math.max(N,this.vectorWeight-this.learnDown):n<this.topN?this.vectorWeight=Math.min(P,this.vectorWeight+this.learnUp):n<this.topN*2?this.vectorWeight=Math.min(P,this.vectorWeight+this.learnUp*.3):this.vectorWeight=Math.max(N,this.vectorWeight-this.learnDown),this.vectorWeight!==r}};const Se=new Set(`the.a.an.is.are.was.were.be.been.to.of.in.for.on.with.at.by.from.or.and.not.this.that.it.its.if.as.will.can.may.must.should.would.could.e.g.default.optional.required.when.set`.split(`.`)),F={extractParamTokens(e){let t=[];if(!e||typeof e!=`object`)return t;let n=e.properties;if(!n||typeof n!=`object`)return t;for(let[e,r]of Object.entries(n)){let n=e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[\s_-]+/);for(let e of n){let n=e.toLowerCase();n.length>1&&t.push(n)}if(r&&typeof r==`object`){let e=r.description;if(typeof e==`string`){let n=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);for(let e of n)e.length>2&&!Se.has(e)&&t.push(e)}}}return t},extractShortDescription(e){if(!e)return``;let t=e.match(/^[^.!?\n]+[.!?]?/);if(t){let e=t[0].trim();return e.length>120?e.slice(0,117)+`...`:e}return e.length>120?e.slice(0,117)+`...`:e},containsCJK(e){return/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(e)},normalizeToolName(e){return e.toLowerCase().replace(/[\s-]+/g,`_`)}},I={queryToolNameMatch:.35,descriptionKeywordOverlap:.25,domainRelevance:.2,intentAlignment:.2};function L(e){return e.toLowerCase().replace(/[\s-]+/g,`_`).replace(/[^a-z0-9_]/g,``)}function R(e){return e.toLowerCase().replace(/[_-]/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Ce(e,t){if(e===t)return 1;if(e.length===0||t.length===0)return 0;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=new Float64Array(n.length+1),a=new Float64Array(n.length+1);for(let e=1;e<=r.length;e++){let t=r[e-1];for(let e=1;e<=n.length;e++){let r=i[e-1]??0;t===n[e-1]?a[e]=r+1:a[e]=Math.max(i[e]??0,a[e-1]??0)}let o=i;i=a,a=o,a.fill(0)}return(i[n.length]??0)/Math.max(e.length,t.length)}function we(e,t){if(e.size===0)return 0;let n=R(t),r=0;for(let t of n)e.has(t)&&r++;return r/e.size}var Te=class{weights;domainKeywords;constructor(e){this.weights=e?{...I,...e}:I,this.domainKeywords=new Map}buildFromTools(e){let t=new Map;for(let n of e){if(!n.domain)continue;let e=t.get(n.domain);e||(e=new Map,t.set(n.domain,e));let r=R(n.name);for(let t of r)e.set(t,(e.get(t)??0)+1);let i=R(n.description);for(let t of i)t.length>=3&&e.set(t,(e.get(t)??0)+1)}for(let[e,n]of t){let t=[...n.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,15);this.domainKeywords.set(e,new Set(t.map(([e])=>e)))}}reRank(e,t,n){if(t.length===0)return[];let r=n??t.length,i=L(e),a=R(e),o=new Set(a),s=this.inferTargetDomain(a),c=[];for(let e=0;e<t.length;e++){let n=t[e],r=Ce(i,L(n.toolName)),l=we(o,n.description),u=0;s.size>0&&n.domain&&(u=+!!s.has(n.domain));let d=this.computeIntentAlignment(a,n.description),f=this.weights.queryToolNameMatch*r+this.weights.descriptionKeywordOverlap*l+this.weights.domainRelevance*u+this.weights.intentAlignment*d,p=n.score*.3+f*.7;c.push({result:n,originalRank:e,reRankScore:p})}return c.toSorted((e,t)=>t.reRankScore-e.reRankScore).slice(0,r).map(e=>({toolName:e.result.toolName,originalRank:e.originalRank,reRankedScore:Math.round(e.reRankScore*1e4)/1e4}))}inferTargetDomain(e){let t=new Set,n=new Set(e);for(let[e,r]of this.domainKeywords)for(let i of r)if(n.has(i)){t.add(e);break}return t}computeIntentAlignment(e,t){if(e.length===0||this.domainKeywords.size===0)return 0;let n=t.toLowerCase(),r=[];for(let e of this.domainKeywords.values())for(let t of e)r.push(t);let i=e.filter(e=>r.includes(e));if(i.length===0)return 0;let a=0;for(let e of i)n.includes(e)&&a++;return a/i.length}};let Ee=0;function De(){return`sq-${Date.now()}-${++Ee}`}function z(e,t){if(e.length===0)return 0;let n=Math.ceil(t/100*e.length)-1;return e[Math.max(0,n)]??0}var B=class{MAX_HISTORY=1e3;records=new pe(this.MAX_HISTORY);lastRecordId;recordSearch(e,t,n,r){let i=De(),a={id:i,query:e,timestamp:Date.now(),returnedTools:t,returnedScores:n,latencyMs:r};return this.records.push(a),this.lastRecordId=i,i}recordToolUsed(e,t){let n=this.records.toArray();for(let r=n.length-1;r>=0;r--){let i=n[r];if(i.id===e){i.usedTool=t;let e=i.returnedTools.indexOf(t);i.usedToolRank=e>=0?e+1:void 0;return}}}associateLastSearch(e){if(!this.lastRecordId)return;let t=this.records.toArray();for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.id===this.lastRecordId){let t=r.returnedTools.indexOf(e);t>=0&&(r.usedTool=e,r.usedToolRank=t+1);return}}}computeMetrics(){let e=this.records.toArray(),t=e.length;if(t===0)return{totalQueries:0,avgLatencyMs:0,p50LatencyMs:0,p99LatencyMs:0,toolUsedRate:0,avgUsedRank:0,mrr:0,topKDistribution:{}};let n=e.map(e=>e.latencyMs).toSorted((e,t)=>e-t),r=n.reduce((e,t)=>e+t,0),i=e.filter(e=>e.usedTool!==void 0),a=i.length/t,o=0,s=0,c={};if(i.length>0){let e=0,t=0;for(let n of i){let r=n.usedToolRank;if(r!==void 0&&r>0){e+=r,t+=1/r;let n=String(r);c[n]=(c[n]??0)+1}}o=e/i.length,s=t/i.length}return{totalQueries:t,avgLatencyMs:r/t,p50LatencyMs:z(n,50),p99LatencyMs:z(n,99),toolUsedRate:a,avgUsedRank:o,mrr:s,topKDistribution:c}}getRecentRecords(e=10){return this.records.toArray().slice(-e)}getStats(){return this.computeMetrics()}getEnhancementSuggestions(e,t,n){if(t>=5&&n>=.5)return null;let r=[];return t===0?r.push(`No tools found for "${e}". Try broader terms or use search_tools with a different query.`):t<3&&r.push(`Only ${t} tools found. Consider using synonyms or breaking down the query.`),n<.3&&t>0&&r.push(`Low relevance scores. Try more specific tool names or domain prefixes (e.g., "page_", "hook_", "network_").`),r.length>0?r:null}};function V(e,t,n){if(!t)return-1;let r=e.indexOf(t);for(;r>=0;){let i=r>0?e[r-1]:null,a=r+t.length<e.length?e[r+t.length]:null,o=i===null||!n.test(i),s=a===null||!n.test(a);if(o&&s)return r;r=e.indexOf(t,r+1)}return-1}function Oe(e){let t=new Map,n=new Map;for(let t=0;t<e.length;t++){let r=e[t].name,i=r.indexOf(`_`);if(i<=0)continue;let a=r.slice(0,i),o=n.get(a)??[];o.push(t),n.set(a,o)}for(let[,e]of n){if(e.length<2||e.length>15)continue;let n=ae/Math.sqrt(e.length);for(let r of e){let i=t.get(r)??[];for(let t of e)t!==r&&i.push({docIndex:t,weight:n});t.set(r,i)}}return t}function ke(e){let t=[];for(let n=0;n<e.length;n++)e[n]>0&&t.push({idx:n,score:e[n]});t.sort((e,t)=>t.score-e.score);let n=new Map;for(let e=0;e<t.length;e++)n.set(t[e].idx,e);return n}function H(e){let t=[...e.entries()].toSorted((e,t)=>t[1]-e[1]),n=new Map;for(let e=0;e<t.length;e++)n.set(t[e][0],e);return n}function Ae(e,t){for(let n=0;n<e.length;n++){let r=t[n];r<=0||(e[n]=e[n]+r*y*se)}}function je(e){let{scores:t,docs:n,affinityGraph:r}=e,i=[];for(let e=0;e<t.length;e++)t[e]>0&&i.push({idx:e,score:t[e]});if(i.length!==0){if(i.sort((e,t)=>t.score-e.score),r.size>0){let e=Math.min(d,i.length);for(let n=0;n<e;n++){let{idx:e,score:a}=i[n],s=r.get(e);if(!s)continue;let c=1/(1+n);for(let{docIndex:e,weight:n}of s)t[e]>0&&(t[e]+=a*n*c*o)}}if(S>0&&i.length>=S){let e=i.slice(0,10),r=new Map;for(let{idx:t}of e){let e=n[t].domain;e&&r.set(e,(r.get(e)??0)+1)}for(let[e,i]of r)if(!(i<S))for(let r=0;r<n.length;r++)t[r]>0&&n[r].domain===e&&(t[r]*=oe)}}}function Me(e,t,n,r){return`${`${e}\0${t}`}${!n||n.size===0?``:`\0${[...n].toSorted().join(`|`)}`}${r?`\0${r}`:``}`}var U=class{capacity;map=new Map;constructor(e){this.capacity=Math.max(1,e)}get(e){let t=this.map.get(e);return t!==void 0&&(this.map.delete(e),this.map.set(e,t)),t}set(e,t){if(this.map.delete(e),this.map.set(e,t),this.map.size>this.capacity){let e=this.map.keys().next().value;this.map.delete(e)}}clear(){this.map.clear()}},Ne=class{docs=[];invertedIndex=new Map;sortedKeys;avgDocLength;docCount;domainOverrides;domainScoreMultipliers;toolScoreMultipliers;extensionEtag=``;docNameIndex=new Map;affinityGraph;queryCache;trigramIndex;embeddingEngine;toolEmbeddings=null;feedbackTracker;recencyTracker=new Map;bm25Scorer;intentBoost;reRanker;qualityTracker=new B;constructor(e,t,n,r,i,a){let o=e??A;this.domainOverrides=t,this.domainScoreMultipliers=n,this.toolScoreMultipliers=r,this.docCount=o.length,this.bm25Scorer=new ye(i);let s=i?.vectorEnabled??u;this.embeddingEngine=s?new be:null,this.feedbackTracker=new xe(i),this.intentBoost=new j(i?.intentToolBoostRules);let c=0;for(let e=0;e<o.length;e++){let t=o[e],n=this.domainOverrides?.get(t.name)??D(t.name),r=t.description??``,i=F.extractShortDescription(r),s=this.bm25Scorer.tokenise(t.name),l=new Set(s),u=n?this.bm25Scorer.tokenise(n):[],d=this.bm25Scorer.tokenise(r),f=F.extractParamTokens(t.inputSchema),p=[...s,...u,...d,...f],m={name:t.name,domain:n,description:r,shortDescription:i,tokens:p,length:p.length,nameTokens:s,nameTokenSet:l,nameTokenCount:l.size};this.docs.push(m),this.docNameIndex.set(t.name,e),c+=m.length;let h=new Map;for(let e of s){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,3),h.set(e,t)}for(let e of u){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,2),h.set(e,t)}for(let e of d){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,1),h.set(e,t)}for(let e of f){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,ee),h.set(e,t)}let g=a?.get(t.name);if(g)for(let e of g){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,ie),h.set(e,t)}for(let[t,{tf:n,weight:r}]of h){let i=this.invertedIndex.get(t);i||(i=[],this.invertedIndex.set(t,i)),i.push({docIndex:e,tf:n,weight:r})}}this.avgDocLength=this.docCount>0?c/this.docCount:1,this.sortedKeys=[...this.invertedIndex.keys()].toSorted(),this.reRanker=new Te,this.reRanker.buildFromTools(this.docs.map(e=>({name:e.name,domain:e.domain??``,description:e.description}))),this.affinityGraph=Oe(this.docs),this.trigramIndex=new M(this.docs.map(e=>e.name)),this.queryCache=new U(re)}async search(e,t=10,n,r,i){let a=performance.now(),o=this.bm25Scorer.tokenise(e);if(o.length===0)return[];if(ne&&this.isSimpleQuery(e,o))return this.quickPathSearch(e,o,t,n);if(o.length>6){let e=o.filter(e=>this.invertedIndex.has(e));if(e.length>=3){let t=e.map(e=>{let t=this.invertedIndex.get(e).length;return{token:e,idf:Math.log((this.docCount-t+.5)/(t+.5)+1)}});t.sort((e,t)=>t.idf-e.idf);let n=new Set(t.slice(0,6).map(e=>e.token));o=o.filter(e=>n.has(e))}}let s=this.bm25Scorer.tokenise(o.join(` `),{expandSynonyms:!0}).filter(e=>!o.includes(e));o.push(...s);let c=(()=>{let t=e.toLowerCase();if(!/(?:\b(?:call|use|run|invoke|execute)\b|调用|执行|使用|运行)/i.test(t))return null;let n=/[a-z0-9_]/,r=/[a-z0-9]/,i=null,a=1/0;for(let e of this.docNameIndex.keys()){let o=V(t,e,n);o<0&&e.includes(`_`)&&(o=V(t,e.replace(/_/g,`-`),r),o<0&&(o=V(t,e.replace(/_/g,` `),r))),!(o<0)&&(o<a||o===a&&e.length>(i?.length??0))&&(i=e,a=o)}return i})(),l=Me(e,t,r,this.extensionEtag),u=this.queryCache.get(l);if(u&&this.isCachedEntryFresh(u)){let e=n??new Set;return u.results.map(t=>({...t,isActive:e.has(t.name)}))}let d=this.intentBoost.resolveIntentToolBonuses(e),f=new Float64Array(this.docCount);for(let e of o)if(this.scoreToken(e,f),e.length>=3){let t=this.findPrefixMatches(e);for(let n of t)if(n!==e){let e=this.invertedIndex.get(n);e&&this.scorePostings(e,this.docCount,f,m)}}await this.applyRRFFusion(o,e,f);let p=this.bm25Scorer.detectQueryCategoryBoosts(e),h=e.toLowerCase().replace(/[\s-]+/g,`_`),g=new Set(o);for(let e=0;e<this.docCount;e++){let t=this.docs[e],n=d.get(t.name)??0;if(f[e]<=0&&n<=0)continue;if(t.name===h){f[e]*=C;continue}let r=0;for(let e of o)t.nameTokenSet.has(e)&&r++;if(r>0&&t.nameTokenCount>0&&g.size>0){let n=r/t.nameTokenCount,i=r/g.size;f[e]*=1+v*n*i}let i=t.domain?this.domainScoreMultipliers?.get(t.domain)??1:1;if(i!==1&&(f[e]*=i),t.domain&&p.size>0){let n=p.get(t.domain);n!==void 0&&n>1&&(f[e]*=n)}let a=this.toolScoreMultipliers?.get(t.name)??1;a!==1&&(f[e]*=a)}if(this.applyIntentBonusBand(f,d),this.applyGraphExpansion(f),this.applyRecencyBoost(f),this.applyTierPenalty(f,r,i),c){let e=this.docNameIndex.get(c);if(e!==void 0){let t=0;for(let e=0;e<this.docCount;e++){let n=f[e];n>t&&(t=n)}let n=Math.max(1,t+1);f[e]+=n}}let _=n??new Set,y=[];for(let e=0;e<this.docCount;e++)if(f[e]>0){let t=this.docs[e];y.push({name:t.name,domain:t.domain,shortDescription:t.shortDescription,score:Math.round(f[e]*1e3)/1e3,isActive:_.has(t.name)})}y.sort((e,t)=>t.score-e.score);let b=y.slice(0,t);if(b.length>1){let n=b.map(e=>({toolName:e.name,score:e.score,domain:e.domain??``,description:this.docs[this.docNameIndex.get(e.name)??0]?.description??``})),r=this.reRanker.reRank(e,n,t),i=new Map(r.map((e,t)=>[e.toolName,t]));b=b.slice().toSorted((e,t)=>(i.get(e.name)??0)-(i.get(t.name)??0))}this.queryCache.set(l,{results:b,vectorWeightAtCache:this.feedbackTracker.getVectorWeight(),cachedAtMs:Date.now()});let x=performance.now()-a;return this.qualityTracker.recordSearch(e,b.map(e=>e.name),b.map(e=>e.score),x),b}isCachedEntryFresh(e){let n=this.feedbackTracker.getVectorWeight();return Math.abs(n-e.vectorWeightAtCache)<=t}isSimpleQuery(e,t){let n=e.toLowerCase().replace(/[\s-]+/g,`_`);return!!(this.docNameIndex.has(n)||t.length===1)}quickPathSearch(e,t,n,r){let i=new Float64Array(this.docCount);for(let e of t)if(this.scoreToken(e,i),e.length>=3){let t=this.findPrefixMatches(e);for(let n of t)if(n!==e){let e=this.invertedIndex.get(n);e&&this.scorePostings(e,this.docCount,i,m)}}let a=this.trigramIndex.search(e,h),o=T;if(o>0)for(let[e,t]of a)t>0&&(i[e]+=t*o);let s=e.toLowerCase().replace(/[\s-]+/g,`_`);if(this.docNameIndex.has(s)){let e=this.docNameIndex.get(s);i[e]*=C}let c=r??new Set,l=[];for(let e=0;e<this.docCount;e++)if(i[e]>0){let t=this.docs[e];l.push({name:t.name,domain:t.domain,shortDescription:t.shortDescription,score:Math.round(i[e]*1e3)/1e3,isActive:c.has(t.name)})}return l.sort((e,t)=>t.score-e.score),l.slice(0,n)}applyRecencyBoost(e){if(w<=0||this.recencyTracker.size===0)return;let t=te;if(t<=0)return;let n=Date.now(),r=w;for(let[i,a]of this.recencyTracker){let o=n-a;if(o<0||o>t)continue;let s=this.docNameIndex.get(i);if(s===void 0||e[s]<=0)continue;let c=1+r*(1-o/t);e[s]*=c}}applyTierPenalty(e,t,n){let r=n?n===`full`?p:n===`workflow`?le:ce:b;if(r>=1||r<=0)return;let i=t&&t.size>0;for(let n=0;n<this.docCount;n++){if(e[n]<=0)continue;let a=this.docs[n].domain;a&&(!i||!t.has(a))&&(e[n]*=r,e[n]<=0&&r>0&&(e[n]=1e-6))}}getDomainSummary(){let e=new Map;for(let t of this.docs){let n=e.get(t.domain)??[];n.push(t.name),e.set(t.domain,n)}return Array.from(e.entries()).map(([e,t])=>({domain:e,count:t.length,tools:t})).toSorted((e,t)=>t.count-e.count)}scoreToken(e,t){let n=this.invertedIndex.get(e);n&&this.scorePostings(n,this.docCount,t,1)}findPrefixMatches(e){let t=this.sortedKeys,n=0,r=t.length;for(;n<r;){let i=n+r>>>1;t[i]<e?n=i+1:r=i}let i=[];for(;n<t.length&&t[n].startsWith(e);)i.push(t[n]),n++;return i}scorePostings(e,t,n,r){let i=e.length,a=Math.log((this.docCount-i+.5)/(i+.5)+1),o=f,s=c;for(let{docIndex:t,tf:i,weight:c}of e){let e=this.docs[t],l=1-o+o*(e.length/this.avgDocLength),u=i*(s+1)/(i+s*l);n[t]+=a*u*c*r}}async applyRRFFusion(e,t,n){let r=_,i=T,a=ke(n),o=H(this.trigramIndex.search(t,h)),s,c;if(l>0&&a.size>0){let e=[...a.entries()].find(([,e])=>e===0)?.[0];(e===void 0?0:n[e])>=l?(s=new Map,c=new Map):(s=await this.computeVectorCosineScores(t),c=H(s))}else s=await this.computeVectorCosineScores(t),c=H(s);let u=new Map;for(let[e,t]of c)u.set(this.docs[e].name,t);this.feedbackTracker.recordVectorRanking(u);let d=new Float64Array(this.docCount);for(let e=0;e<this.docCount;e++){let t=0,n=a.get(e);n!==void 0&&(t+=1/(r+n));let s=o.get(e);s!==void 0&&i>0&&(t+=i*(1/(r+s)));let l=c.get(e);l!==void 0&&this.feedbackTracker.getVectorWeight()>0&&(t+=this.feedbackTracker.getVectorWeight()*(1/(r+l))),d[e]=t}Ae(n,d)}async ensureToolEmbeddings(){if(this.toolEmbeddings||!this.embeddingEngine)return;let e=this.docs.map(e=>`${e.name.replace(/_/g,` `)}: ${e.description}`);this.toolEmbeddings=await this.embeddingEngine.embedBatch(e)}async computeVectorCosineScores(e){if(!this.embeddingEngine)return new Map;try{await this.ensureToolEmbeddings()}catch{return new Map}if(!this.toolEmbeddings)return new Map;let t;try{t=await this.embeddingEngine.embed(e)}catch{return new Map}let n=new Map;for(let e=0;e<this.toolEmbeddings.length;e++){let r=this.toolEmbeddings[e],i=0;for(let e=0;e<t.length;e++)i+=t[e]*r[e];i>0&&n.set(e,i)}return n}recordToolCallFeedback(e,t){for(this.feedbackTracker.recordToolCallFeedback(e,!!this.embeddingEngine),this.recencyTracker.delete(e),this.recencyTracker.set(e,Date.now());this.recencyTracker.size>g;){let e=this.recencyTracker.keys().next().value;if(e===void 0)break;this.recencyTracker.delete(e)}}associateLastSearch(e){this.qualityTracker.associateLastSearch(e)}getSearchQualityMetrics(){return this.qualityTracker.computeMetrics()}getSearchQualityTracker(){return this.qualityTracker}applyIntentBonusBand(e,t){if(t.size===0)return;let n=0;for(let t=0;t<this.docCount;t++)n=Math.max(n,e[t]);let r=0;for(let e of t.values())r=Math.max(r,e);if(r<=0)return;let i=Math.max(1,n+1),a=[...new Set([...t.values()].filter(e=>e>0))].toSorted((e,t)=>e-t),o=new Map;for(let e=0;e<a.length;e++)o.set(a[e],e+1);for(let[n,r]of t){if(r<=0)continue;let t=this.docNameIndex.get(n);if(t===void 0)continue;let a=o.get(r);a!==void 0&&(e[t]+=i*a)}}applyGraphExpansion(e){je({scores:e,docs:this.docs,affinityGraph:this.affinityGraph})}},Pe=e({buildDomainDescription:()=>$,buildSearchSignature:()=>Z,getActiveToolNames:()=>W,getBaseTier:()=>K,getCombinedTools:()=>J,getExtensionDomainMap:()=>q,getSearchEngine:()=>Q,getToolByName:()=>Y,getVisibleDomainsForTier:()=>G});function W(e){let t=new Set(e.selectedTools.map(e=>e.name));for(let n of e.activatedToolNames)t.add(n);return t}function G(e){let t=new Set(de(e.baseTier));for(let n of e.enabledDomains)t.add(n);for(let n of e.extensionToolsByName.values())t.add(n.domain);for(let n of W(e)){let r=e.extensionToolsByName.get(n)?.domain;if(r){t.add(r);continue}let i=D(n);i&&t.add(i)}return t}function K(e){return e.baseTier}function q(e){let t=new Map;for(let n of e.extensionToolsByName.values())t.set(n.name,n.domain);return t}async function J(e){await O();let t=new Map(A.map(e=>[e.name,e]));for(let n of e.extensionToolsByName.values())t.set(n.name,n.tool);return[...t.values()]}async function Y(e){return new Map((await J(e)).map(e=>[e.name,e]))}const X=new WeakMap;function Fe(){let e=new Map;for(let t of ue())if(t.sceneKeywords)for(let[n,r]of Object.entries(t.sceneKeywords))r.length>0&&e.set(n,r);return e}function Z(e){let t=[];for(let[n,r]of e.extensionToolsByName)t.push(`${n}:${r.domain}`);return t.sort(),[e.extensionWorkflowRuntimeById.size,t.join(`|`)].join(`::`)}async function Q(e){await O();let t=Z(e),r=X.get(e);if(r?.signature===t)return r.engine;let i=await J(e),a=q(e),o=new Map,s=new Map;for(let t of e.extensionToolsByName.values())s.set(t.name,1.12);e.extensionWorkflowRuntimeById.size>0&&(o.set(`workflow`,n),s.set(`run_extension_workflow`,1.35),s.set(`list_extension_workflows`,1.25));let c=new Ne(i,a,o,s,e.config.search,Fe());return c.extensionEtag=t,X.set(e,{signature:t,engine:c}),c}function $(e){let t={};for(let e of k())t[e.domain]=(t[e.domain]??0)+1;for(let n of e.extensionToolsByName.values())t[n.domain]=(t[n.domain]??0)+1;let n=k().length,r=e.extensionToolsByName.size;return`Search ${n+r} tools across ${Object.keys(t).length} capability domains. This includes built-in tools plus any loaded plugin/workflow tools (${r} currently loaded). In search-tier sessions, call this before assuming a capability is unavailable. Use activate_tools for exact matches, activate_domain for an entire domain. Domains: ${Object.entries(t).toSorted((e,t)=>t[1]-e[1]).map(([e,t])=>`${e} (${t})`).join(` | `)}. Query tip: before searching, distill your intent into key concepts (action verb + target + domain). Pass distilled keywords, not full sentences — the search engine works on token matching, not semantic understanding.`}export{Q as a,B as c,K as i,$ as n,Y as o,W as r,G as s,Pe as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){let t=e.trim();if(!t.startsWith(`mcp__`))return t;let n=t.split(`__`);return n.length<3?t:n.slice(2).join(`__`)}function t(t){let n=t.names;if(typeof n==`string`&&n.trim().startsWith(`[`))try{let e=JSON.parse(n);Array.isArray(e)&&(n=e)}catch{}if(!Array.isArray(n))return{names:[],error:`names must be an array`};let r=[];for(let t of n){if(typeof t!=`string`||t.trim().length===0)return{names:[],error:`invalid tool name: expected non-empty string`};r.push(e(t))}return{names:r}}export{t as n,e as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Jt as e,ga as t}from"./constants-DMv3svps.mjs";import{_ as n,b as r,d as i,m as a,t as o,u as s}from"./Win32API-DoP3MMHS.mjs";import{i as c}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{randomUUID as l}from"node:crypto";var u=class{freezes=new Map;writeHistory=[];undoneStack=[];async writeValue(e,u,d,f){let p=BigInt(u.startsWith(`0x`)?u:`0x${u}`),{patternBytes:m}=c(d,f),h=Buffer.from(m),g=r(e,!0);try{let r=i(g,p,h.length),{oldProtect:o}=a(g,p,h.length,s.READWRITE);n(g,p,h),a(g,p,h.length,o);let c={id:l(),pid:e,address:`0x${p.toString(16).toUpperCase()}`,oldValue:Array.from(r),newValue:Array.from(h),timestamp:Date.now(),undone:!1};return this.writeHistory.push(c),this.undoneStack=[],this.writeHistory.length>t&&(this.writeHistory=this.writeHistory.slice(-t)),c}finally{o(g)}}async undo(){for(let e=this.writeHistory.length-1;e>=0;e--){let t=this.writeHistory[e];if(!t.undone){let e=BigInt(t.address),i=Buffer.from(t.oldValue),c=r(t.pid,!0);try{let{oldProtect:t}=a(c,e,i.length,s.READWRITE);n(c,e,i),a(c,e,i.length,t)}finally{o(c)}return t.undone=!0,this.undoneStack.push(t),t}}return null}async redo(){let e=this.undoneStack.pop();if(!e)return null;let t=BigInt(e.address),i=Buffer.from(e.newValue),c=r(e.pid,!0);try{let{oldProtect:e}=a(c,t,i.length,s.READWRITE);n(c,t,i),a(c,t,i.length,e)}finally{o(c)}return e.undone=!1,e}async freeze(t,i,u,d,f){let p=BigInt(i.startsWith(`0x`)?i:`0x${i}`),{patternBytes:m}=c(u,d),h=Buffer.from(m),g=f??e,_={id:l(),pid:t,address:`0x${p.toString(16).toUpperCase()}`,value:Array.from(h),valueType:d,intervalMs:g,isActive:!0};return _.timer=setInterval(()=>{try{let e=r(t,!0);try{let{oldProtect:t}=a(e,p,h.length,s.READWRITE);n(e,p,h),a(e,p,h.length,t)}finally{o(e)}}catch{_.isActive=!1,_.timer&&clearInterval(_.timer),this.freezes.delete(_.id)}},g),typeof _.timer.unref==`function`&&_.timer.unref(),this.freezes.set(_.id,_),_}async unfreeze(e){let t=this.freezes.get(e);return t?(t.timer&&clearInterval(t.timer),t.isActive=!1,this.freezes.delete(e),!0):!1}async unfreezeAll(){let e=0;for(let[t]of this.freezes)await this.unfreeze(t),e++;return e}listFreezes(){return Array.from(this.freezes.values()).map(({timer:e,...t})=>t)}async dumpMemory(e,t,n){let a=BigInt(t.startsWith(`0x`)?t:`0x${t}`),s=r(e,!1);try{return i(s,a,n)}finally{o(s)}}async dumpMemoryHex(e,t,n){let r=await this.dumpMemory(e,t,n),i=[],a=BigInt(t.startsWith(`0x`)?t:`0x${t}`);for(let e=0;e<r.length;e+=16){let t=a+BigInt(e),n=Array.from(r.subarray(e,Math.min(e+16,r.length))).map(e=>e.toString(16).padStart(2,`0`)).join(` `),o=Array.from(r.subarray(e,Math.min(e+16,r.length))).map(e=>e>=32&&e<=126?String.fromCharCode(e):`.`).join(``);i.push(`${t.toString(16).padStart(12,`0`)} ${n.padEnd(47)} |${o}|`)}return i.join(`
|
|
2
2
|
`)}getWriteHistory(){return[...this.writeHistory]}};const d=new u;export{u as MemoryController,d as memoryController};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ur as e,Wr as t}from"./constants-DMv3svps.mjs";import{n,t as r}from"./formatAddress-DAcw4Ckg.mjs";import{randomUUID as i}from"node:crypto";function a(e){switch(e){case`byte`:case`int8`:return 1;case`int16`:case`uint16`:return 2;case`int32`:case`uint32`:case`float`:return 4;case`int64`:case`uint64`:case`double`:case`pointer`:return 8;case`hex`:case`string`:return 0;default:return 4}}function o(e){switch(e){case`byte`:case`int8`:return 1;case`int16`:case`uint16`:return 2;case`int32`:case`uint32`:case`float`:return 4;case`int64`:case`uint64`:case`double`:case`pointer`:return 8;default:return 1}}function s(e){switch(e){case`byte`:return e=>e.readUInt8(0);case`int8`:return e=>e.readInt8(0);case`int16`:return e=>e.readInt16LE(0);case`uint16`:return e=>e.readUInt16LE(0);case`int32`:return e=>e.readInt32LE(0);case`uint32`:return e=>e.readUInt32LE(0);case`int64`:return e=>e.readBigInt64LE(0);case`uint64`:case`pointer`:return e=>e.readBigUInt64LE(0);case`float`:return e=>e.readFloatLE(0);case`double`:return e=>e.readDoubleLE(0);default:return e=>e.readInt32LE(0)}}function c(e){return e===`float`?(e,t)=>Math.abs(Number(e)-Number(t))<1e-6:e===`double`?(e,t)=>Math.abs(Number(e)-Number(t))<1e-12:e===`int64`||e===`uint64`||e===`pointer`?(e,t)=>e===t:(e,t)=>Number(e)===Number(t)}function l(e,t){let n=s(t),r=c(t),i=t===`int64`||t===`uint64`||t===`pointer`?(e,t)=>{let n=BigInt(e),r=BigInt(t);return n<r?-1:+(n>r)}:(e,t)=>Number(e)-Number(t);switch(e){case`exact`:return(e,t,i,a)=>i?r(n(e),n(i)):!1;case`unknown_initial`:return()=>!0;case`changed`:return(e,t,i,a)=>t?!r(n(e),n(t)):!1;case`unchanged`:return(e,t,i,a)=>t?r(n(e),n(t)):!0;case`increased`:return(e,t,r,a)=>t?i(n(e),n(t))>0:!1;case`decreased`:return(e,t,r,a)=>t?i(n(e),n(t))<0:!1;case`greater_than`:return(e,t,r,a)=>r?i(n(e),n(r))>0:!1;case`less_than`:return(e,t,r,a)=>r?i(n(e),n(r))<0:!1;case`between`:return(e,t,r,a)=>!r||!a?!1:i(n(e),n(r))>=0&&i(n(e),n(a))<=0;case`not_equal`:return(e,t,i,a)=>i?!r(n(e),n(i)):!1;default:return()=>!1}}const u=new Map;function d(e,t){let n=`${e}:${t}`,r=u.get(n);return r||(r=l(e,t),u.set(n,r)),r}function f(e,t,n,r,i,a){return d(i,a)(e,t,n,r)}var p=class{sessions=new Map;maxSessions;sessionTtlMs;constructor(n=e,r=t){this.maxSessions=n,this.sessionTtlMs=r}createSession(e,t){if(this.cleanup(),this.sessions.size>=this.maxSessions){let e=null,t=1/0;for(let[n,r]of this.sessions)r.createdAt<t&&(t=r.createdAt,e=n);e&&this.sessions.delete(e)}let n=i(),r=t.alignment??o(t.valueType),a=Date.now(),s={id:n,pid:e,valueType:t.valueType,alignment:r,createdAt:a,lastScanAt:a,scanCount:0,addresses:[],previousValues:new Map};return this.sessions.set(n,s),n}getSession(e){let t=this.sessions.get(e);if(!t)throw Error(`Scan session not found: ${e}`);if(Date.now()-t.lastScanAt>this.sessionTtlMs)throw this.sessions.delete(e),Error(`Scan session expired: ${e}`);return t}updateSession(e,t,n){let r=this.getSession(e);r.addresses=t,r.previousValues=n,r.lastScanAt=Date.now(),r.scanCount++}listSessions(){this.cleanup();let e=[],t=Date.now();for(let n of this.sessions.values()){let r=t-n.createdAt,i=Math.floor(r/6e4),a=Math.floor(r%6e4/1e3);e.push({id:n.id,pid:n.pid,valueType:n.valueType,addressCount:n.addresses.length,scanCount:n.scanCount,age:i>0?`${i}m${a}s`:`${a}s`})}return e}deleteSession(e){return this.sessions.delete(e)}cleanup(){let e=Date.now(),t=0;for(let[n,r]of this.sessions)e-r.lastScanAt>this.sessionTtlMs&&(this.sessions.delete(n),t++);return t}exportSession(e){let t=this.getSession(e),n={...t,addresses:t.addresses.map(e=>r(e)),previousValues:Array.from(t.previousValues.entries()).map(([e,t])=>[r(e),t.toString(`hex`)])};return JSON.stringify(n)}importSession(e){let t=JSON.parse(e),r=i(),a=Date.now(),o=new Map;if(Array.isArray(t.previousValues))for(let[e,r]of t.previousValues)typeof e==`string`&&typeof r==`string`&&o.set(n(e),Buffer.from(r,`hex`));let s=[];if(Array.isArray(t.addresses))for(let e of t.addresses)typeof e==`string`&&s.push(n(e));let c={id:r,pid:t.pid,valueType:t.valueType,alignment:t.alignment??4,createdAt:a,lastScanAt:a,scanCount:t.scanCount??0,addresses:s,previousValues:o};return this.sessions.set(r,c),r}};const m=new p;export{p as MemoryScanSessionManager,o as n,a as r,m as scanSessionManager,f as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Br as e,Gr as t,Hr as n,Vr as r,Xi as i,zr as a}from"./constants-DMv3svps.mjs";import{t as o}from"./ToolError-g3rjWzhx.mjs";import{r as s}from"./native-g095qhpK.mjs";import{t as c}from"./factory-BxNdBiZa.mjs";import{i as l}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{n as u,t as d}from"./formatAddress-DAcw4Ckg.mjs";import{n as f,r as p,scanSessionManager as m,t as h}from"./MemoryScanSession-zfoVZJB0.mjs";var g=class{nmm;providerCache=null;get provider(){return this.providerCache||=c(),this.providerCache}set provider(e){this.providerCache=e}constructor(e){this.nmm=e}async firstScan(e,t,n){let i=performance.now(),s=n.valueType,c=p(s),u=n.alignment??f(s),h=n.maxResults??r;if(c===0)return this.patternFirstScan(e,t,s,n);let{patternBytes:g}=l(t,s===`pointer`?`uint64`:s);if(g.length===0)throw new o(`VALIDATION`,`Invalid pattern for type ${s}: "${t}"`);let _=Buffer.from(g),v=m.createSession(e,n),y=[],b=new Map,x=this.provider.openProcess(e,!1);try{let e=this.getFilteredRegions(x,n),t=e.length,r=0;for(let i of e){if(n.onProgress&&n.onProgress(r,t),r++,y.length>=h)break;let e=i.baseAddress,a=i.size,o=16*1024*1024;for(let t=0;t<a&&y.length<h;t+=o){let n=Math.min(o,a-t),r=e+BigInt(t),i;try{i=this.provider.readMemory(x,r,n).data}catch{break}if(u===c&&c>0){let e=this.getAlignStep(u),t=this.getAlignedChunkStart(r,e);for(;t<=i.length-c&&y.length<h;){let n=i.indexOf(_,t);if(n===-1)break;if(!this.isAlignedAddress(r+BigInt(n),e)){t=n+1;continue}let a=r+BigInt(n);y.push(a),b.set(a,Buffer.from(i.subarray(n,n+c))),t=n+e}}else{let e=this.getAlignStep(u),t=this.getAlignedChunkStart(r,e);for(let n=t;n<=i.length-c;n+=e)if(Buffer.compare(i.subarray(n,n+c),_)===0){let e=r+BigInt(n);if(y.push(e),b.set(e,Buffer.from(i.subarray(n,n+c))),y.length>=h)break}}}}}finally{this.provider.closeProcess(x)}m.updateSession(v,y,b);let S=`${(performance.now()-i).toFixed(1)}ms`,C=y.slice(0,a).map(d);return{sessionId:v,matchCount:y.length,scanNumber:1,addresses:C,totalMatches:y.length,truncated:y.length>a,elapsed:S}}async nextScan(e,t,n,r){let i=performance.now(),s=m.getSession(e),{pid:c,valueType:u,addresses:f,previousValues:g}=s,_=p(u);if(_===0)throw new o(`VALIDATION`,`Next-scan is not supported for variable-length types (hex/string)`);let v=null,y=null;if(n!==void 0){let{patternBytes:e}=l(n,u===`pointer`?`uint64`:u);v=Buffer.from(e)}if(r!==void 0){let{patternBytes:e}=l(r,u===`pointer`?`uint64`:u);y=Buffer.from(e)}let b=[],x=new Map,S=this.provider.openProcess(c,!1);try{for(let e of f){let n;try{n=this.provider.readMemory(S,e,_).data}catch{continue}let r=g.get(e)??null;h(n,r,v,y,t,u)&&(b.push(e),x.set(e,Buffer.from(n)))}}finally{this.provider.closeProcess(S)}m.updateSession(e,b,x);let C=`${(performance.now()-i).toFixed(1)}ms`,w=b.slice(0,a).map(d);return{sessionId:e,matchCount:b.length,scanNumber:s.scanCount,addresses:w,totalMatches:b.length,truncated:b.length>a,elapsed:C}}async unknownInitialScan(e,n){let r=performance.now(),i=n.valueType,s=p(i),c=n.alignment??f(i),l=n.maxResults??t;if(s===0)throw new o(`VALIDATION`,`Unknown initial scan is not supported for variable-length types`);let u=m.createSession(e,n),h=[],g=new Map,_=this.provider.openProcess(e,!1);try{let e=this.getFilteredRegions(_,n),t=e.length,r=0;for(let i of e){if(n.onProgress&&n.onProgress(r,t),r++,h.length>=l)break;let e=i.baseAddress,a=i.size,o=16*1024*1024;for(let t=0;t<a&&h.length<l;t+=o){let n=Math.min(o,a-t),r=e+BigInt(t),i;try{i=this.provider.readMemory(_,r,n).data}catch{break}let u=this.getAlignStep(c),d=this.getAlignedChunkStart(r,u);for(let e=d;e<=i.length-s;e+=u){let t=r+BigInt(e);if(h.push(t),g.set(t,Buffer.from(i.subarray(e,e+s))),h.length>=l)break}}}}finally{this.provider.closeProcess(_)}m.updateSession(u,h,g);let v=`${(performance.now()-r).toFixed(1)}ms`;return{sessionId:u,matchCount:h.length,scanNumber:1,addresses:h.slice(0,a).map(d),totalMatches:h.length,truncated:h.length>a,elapsed:v}}async pointerScan(e,t,r={}){let i=performance.now(),o=r.maxResults??n,s=u(t),c={valueType:`pointer`,alignment:8,regionFilter:{moduleOnly:r.moduleOnly}},l=m.createSession(e,c),f=[],p=this.provider.openProcess(e,!1);try{let e=this.getFilteredRegions(p,c);for(let t of e){if(f.length>=o)break;let e=t.baseAddress,n=t.size,r=16*1024*1024;for(let t=0;t<n&&f.length<o;t+=r){let i=Math.min(r,n-t),a=e+BigInt(t),c;try{c=this.provider.readMemory(p,a,i).data}catch{break}for(let e=0;e<=c.length-8;e+=8){let t=c.readBigUInt64LE(e);if(Number(t>s?t-s:s-t)<=4096){let n=a+BigInt(e),r=t>=s?Number(t-s):-Number(s-t);if(f.push({address:d(n),value:d(t),offsetFromTarget:r}),f.length>=o)break}}}}}finally{this.provider.closeProcess(p)}let h=f.map(e=>u(e.address));m.updateSession(l,h,new Map);let g=`${(performance.now()-i).toFixed(1)}ms`;return{sessionId:l,pointers:f.slice(0,a),totalFound:f.length,elapsed:g}}async groupScan(t,n,i){let s=performance.now();if(n.length===0)throw new o(`VALIDATION`,`Group scan requires at least one value pattern`);let c=Math.max(...n.map(e=>e.offset+p(e.type)));if(c>e)throw new o(`VALIDATION`,`Group pattern too large: ${c} bytes (max ${e})`);let u=Array.from({length:c},()=>0),f=Array.from({length:c},()=>0);for(let e of n){let t=e.type===`pointer`?`uint64`:e.type,{patternBytes:n,mask:r}=l(e.value,t);for(let t=0;t<n.length;t++)u[e.offset+t]=n[t],f[e.offset+t]=r[t]}let h=i?.alignment??4,g=i?.maxResults??r,_={valueType:`int32`,alignment:h},v=m.createSession(t,_),y=[],b=this.provider.openProcess(t,!1);try{let e=this.getFilteredRegions(b,_);for(let t of e){if(y.length>=g)break;let e=t.baseAddress,n=t.size,r=16*1024*1024,i=c-1;for(let t=0;t<n&&y.length<g;t+=r){let a=Math.min(r+i,n-t),o=e+BigInt(t),s;try{s=this.provider.readMemory(b,o,a).data}catch{break}let l=this.getAlignStep(h),d=this.getAlignedChunkStart(o,l);for(let e=d;e<=s.length-c;e+=l){let t=!0;for(let n=0;n<c;n++)if(f[n]===1&&s[e+n]!==u[n]){t=!1;break}if(t){let t=o+BigInt(e);if(y.push(t),y.length>=g)break}}}}}finally{this.provider.closeProcess(b)}m.updateSession(v,y,new Map);let x=`${(performance.now()-s).toFixed(1)}ms`;return{sessionId:v,matchCount:y.length,scanNumber:1,addresses:y.slice(0,a).map(d),totalMatches:y.length,truncated:y.length>a,elapsed:x}}getAlignStep(e){return e>0?e:1}getAlignedChunkStart(e,t){let n=BigInt(t),r=e%n;return r===0n?0:Number(n-r)}isAlignedAddress(e,t){return e%BigInt(t)===0n}async patternFirstScan(e,t,n,i){let s=performance.now(),c=n===`hex`?`hex`:`string`,l=await this.nmm.scanMemory(e,t,c);if(!l.success)throw new o(`RUNTIME`,l.error??`Scan failed`);let f=m.createSession(e,i),p=i.maxResults??r,h=l.addresses.slice(0,p).map(u);m.updateSession(f,h,new Map);let g=`${(performance.now()-s).toFixed(1)}ms`;return{sessionId:f,matchCount:h.length,scanNumber:1,addresses:h.slice(0,a).map(d),totalMatches:l.addresses.length,truncated:h.length>a,elapsed:g}}getFilteredRegions(e,t){let n=[],r=0n,a=i,o=t.regionFilter;for(;r<a;){let t=this.provider.queryRegion(e,r);if(!t)break;let i=t.size;if(t.isReadable&&i>0&&i<=2**53-1){let e=!0;o?.writable&&!t.isWritable&&(e=!1),o?.executable&&!t.isExecutable&&(e=!1),o?.moduleOnly&&t.type!==`image`&&(e=!1),e&&n.push({baseAddress:t.baseAddress,size:i})}r=t.baseAddress+BigInt(t.size)}return n}};const _=new g(s);export{g as MemoryScanner,_ as memoryScanner};
|
package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{u as e,v as t}from"./Win32API-
|
|
1
|
+
import{u as e,v as t}from"./Win32API-DoP3MMHS.mjs";function n(){return t()}function r(e,t){let n=[],r=[];switch(t){case`hex`:{let t=e.trim().split(/\s+/);for(let e of t)if(e===`??`||e===`**`||e===`?`)n.push(0),r.push(0);else{let t=parseInt(e,16);isNaN(t)||(n.push(t),r.push(1))}break}case`int32`:{let t=parseInt(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(4);e.writeInt32LE(t,0),n.push(...e),r.push(1,1,1,1)}break}case`int64`:{let t=BigInt(e),i=Buffer.allocUnsafe(8);i.writeBigInt64LE(t,0),n.push(...i),r.push(1,1,1,1,1,1,1,1);break}case`float`:{let t=parseFloat(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(4);e.writeFloatLE(t,0),n.push(...e),r.push(1,1,1,1)}break}case`double`:{let t=parseFloat(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(8);e.writeDoubleLE(t,0),n.push(...e),r.push(1,1,1,1,1,1,1,1)}break}case`string`:{let t=Buffer.from(e,`utf8`);n.push(...t),r.push(...t.map(()=>1));break}case`byte`:{let t=parseInt(e)&255;n.push(t),r.push(1);break}case`int8`:{let t=parseInt(e),i=Buffer.allocUnsafe(1);i.writeInt8(t,0),n.push(...i),r.push(1);break}case`int16`:{let t=parseInt(e),i=Buffer.allocUnsafe(2);i.writeInt16LE(t,0),n.push(...i),r.push(1,1);break}case`uint16`:{let t=parseInt(e),i=Buffer.allocUnsafe(2);i.writeUInt16LE(t,0),n.push(...i),r.push(1,1);break}case`uint32`:{let t=parseInt(e)>>>0,i=Buffer.allocUnsafe(4);i.writeUInt32LE(t,0),n.push(...i),r.push(1,1,1,1);break}case`uint64`:case`pointer`:{let t=BigInt(e),i=Buffer.allocUnsafe(8);i.writeBigUInt64LE(t,0),n.push(...i),r.push(1,1,1,1,1,1,1,1);break}}return{patternBytes:n,mask:r}}function i(e,t){let n=[],r=t.length;if(r===0||e.length<r)return n;let i=r-1,a=new Uint32Array(256);a.fill(r);for(let e=0;e<i;e++){let n=t[e];n!==void 0&&(a[n]=i-e)}let o=0;for(;o<=e.length-r;){let s=i;for(;s>=0&&e[o+s]===t[s];)s--;if(s<0){n.push(o),o+=1;continue}let c=e[o+i];if(c===void 0)break;o+=a[c]??r}return n}function a(e,t,n){if(t.length===0)return[];if(n.every(e=>e===1))return i(e,t);let r=[];for(let i=0;i<=e.length-t.length;i++){let a=!0;for(let r=0;r<t.length;r++)if(n[r]===1&&e[i+r]!==t[r]){a=!1;break}a&&r.push(i)}return r}function o(t){return(t&e.EXECUTE)!==0||(t&e.EXECUTE_READ)!==0||(t&e.EXECUTE_READWRITE)!==0}export{r as i,o as n,n as r,a as t};
|