@jshookmcp/jshook 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -661
- package/README.md +11 -3
- package/README.zh.md +11 -3
- package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
- package/dist/BrowserSessionCoordinator-QIt3tetp.mjs +1 -0
- package/dist/CodeInjector-Btj9upnf.mjs +1 -0
- package/dist/ConsoleMonitor-DIjN5Afa.mjs +306 -0
- package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
- package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
- package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
- package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
- package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
- package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +1 -0
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/MemoryController-DjtgiING.mjs +2 -0
- package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
- package/dist/MemoryScanner-Dxd657li.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
- package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
- package/dist/ProcessRegistry-D5y1yuP2.mjs +1 -0
- package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-nPXl_khE.mjs} +1 -1
- package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
- package/dist/RingBuffer-B6RTHmij.mjs +1 -0
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
- package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
- package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
- package/dist/ToolProbe-DQiREmNp.mjs +1 -0
- package/dist/ToolRegistry-eMZEBiR1.mjs +1 -0
- package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
- package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
- package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
- package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-DoP3MMHS.mjs} +1 -1
- package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
- package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
- package/dist/analysis-C-ln0Brh.mjs +6 -0
- package/dist/antidebug-CsnpOR9z.mjs +1 -0
- package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
- package/dist/{artifacts-B5xQuEa_.mjs → artifacts-D-4pSS_N.mjs} +1 -1
- package/dist/betterSqlite3-Bdo_ifuJ.mjs +1 -0
- package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
- package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
- package/dist/browser-BUaB25bk.mjs +11 -0
- package/dist/{handlers-pVNpaw4A.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-CCP9gphV.mjs → definitions-0hxnrDU72.mjs} +1 -1
- package/dist/definitions-B3a9QC2t.mjs +1 -0
- package/dist/{definitions-DtE0XLrT.mjs → definitions-BOvju5t2.mjs} +1 -1
- package/dist/definitions-CXj_cEVt.mjs +1 -0
- package/dist/definitions-Co6AvTjH.mjs +1 -0
- package/dist/{definitions-Dds_zrWx.mjs → definitions-Cv5r8xwq.mjs} +1 -1
- package/dist/definitions-DBYSxChX.mjs +1 -0
- package/dist/{definitions-DI9YXsJk.mjs → definitions-D_dTDX9B.mjs} +1 -1
- package/dist/{definitions-Dgrg7f3D.mjs → definitions-Db9t2ddh.mjs} +1 -1
- package/dist/{definitions-DZ8uKusP.mjs → definitions-DbN2CjI2.mjs} +1 -1
- package/dist/{definitions-jXPaVy4P.mjs → definitions-DlmmHmZc.mjs} +1 -1
- package/dist/definitions-DnYpoGig.mjs +1 -0
- package/dist/{definitions-CYFbewnd.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
- package/dist/{definitions-CuJRsJ6N.mjs → definitions-DuIPS8gq.mjs} +1 -1
- package/dist/{definitions-BbxOUiP-.mjs → definitions-DywfwPMb.mjs} +1 -1
- package/dist/definitions-EGmqr85H.mjs +1 -0
- package/dist/{definitions-LaYTuwQd.mjs → definitions-Fetw_Cge.mjs} +3 -3
- package/dist/{definitions-NoVp_9Pm.mjs → definitions-LdkeuOeA.mjs} +1 -1
- package/dist/{definitions-DJklW2sS.mjs → definitions-Ym8niHDb.mjs} +1 -1
- package/dist/{definitions-BGwNSkVm.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/{definitions-CIO9O-Sw.mjs → definitions-cnG6tj17.mjs} +1 -1
- package/dist/{encoding-DGcr6Aj_.mjs → encoding-B4xZWErf.mjs} +2 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
- package/dist/{factory-Cx_1LorX.mjs → factory-BxNdBiZa.mjs} +1 -1
- package/dist/{graphql-HLf3MS8H.mjs → graphql-GBWsZ9xC.mjs} +4 -4
- package/dist/{handlers-DW5AbYs5.mjs → handlers-5nzR8B0a.mjs} +3 -3
- package/dist/handlers-6iNsXOVT.mjs +7 -0
- package/dist/{handlers-BZoPla6E.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
- package/dist/{handlers-Dv_runVv.mjs → handlers-BbLxNbbT.mjs} +1 -1
- package/dist/{handlers-BP12ZsWc.mjs → handlers-BbS4hssc.mjs} +2 -2
- package/dist/{handlers-BggKiVx9.mjs → handlers-CIKOP4aI.mjs} +2 -2
- package/dist/handlers-CWKBBjai.mjs +1 -0
- package/dist/handlers-Cmb6SoRC.mjs +1 -0
- package/dist/handlers-CrJsKnEI.mjs +1 -0
- package/dist/{antidebug-BOTZH6-0.mjs → handlers-DB6xVVWq.mjs} +4 -4
- package/dist/{handlers-DmQzIc44.mjs → handlers-DOOCWUNR.mjs} +3 -3
- package/dist/{handlers-BLMa4X7l.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-BsFTW6SD.mjs +1 -0
- package/dist/{hooks-DDKppogd.mjs → hooks-DPouiS7I.mjs} +9 -9
- package/dist/index.mjs +11 -15
- package/dist/macro-p8kuJVcm.mjs +2 -0
- package/dist/maintenance-DAqADb6Z.mjs +302 -0
- package/dist/manifest-4lmM6MZR.mjs +1 -0
- package/dist/{manifest-D610kxZr.mjs → manifest-AxaxRSt6.mjs} +2 -2
- package/dist/{manifest-CDeUZGUZ.mjs → manifest-BIqRE1Qz.mjs} +1 -1
- package/dist/{manifest-Dm0o3i2U.mjs → manifest-Box-jWfr.mjs} +1 -1
- package/dist/manifest-Bp33di0Q.mjs +1 -0
- package/dist/{manifest-CGq4NpqH2.mjs → manifest-BvRX4nRP.mjs} +1 -1
- package/dist/{manifest-yu2xiQqe.mjs → manifest-C6KoB1XE.mjs} +1 -1
- package/dist/manifest-C7TdXCWY.mjs +1 -0
- package/dist/manifest-CM-n64K0.mjs +1 -0
- package/dist/{manifest-DWUUWBz0.mjs → manifest-CUokxCUN.mjs} +1 -1
- package/dist/manifest-CWJS45iO.mjs +1 -0
- package/dist/{manifest-D44TaRJU.mjs → manifest-Cdxdgo-D.mjs} +1 -1
- package/dist/{manifest-DKUorv5M.mjs → manifest-Cf6SmamD.mjs} +1 -1
- package/dist/manifest-Cgxu2qdv.mjs +1 -0
- package/dist/manifest-CowGSURa2.mjs +1 -0
- package/dist/manifest-CsGIrh34.mjs +1 -0
- package/dist/manifest-CvDpVToN.mjs +1 -0
- package/dist/manifest-D8TL9RLE.mjs +1 -0
- package/dist/{manifest-C7qV1z7F.mjs → manifest-DIhtCBe6.mjs} +1 -1
- package/dist/{manifest-CeQmtQOY.mjs → manifest-DJbruNOg.mjs} +1 -1
- package/dist/manifest-DLGtZH-0.mjs +1 -0
- package/dist/manifest-DXHdPt2T.mjs +1 -0
- package/dist/{manifest-DMJlcsTR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
- package/dist/{manifest-C1nZkTkO.mjs → manifest-DzGoTS0R.mjs} +1 -1
- package/dist/manifest-G2H52LKz.mjs +131 -0
- package/dist/manifest-P0Futrgb.mjs +1 -0
- package/dist/{manifest-CDiCtaQT.mjs → manifest-Qw7xgvjv.mjs} +1 -1
- package/dist/{manifest-Dgh0uDW-.mjs → manifest-W3qvVrP2.mjs} +1 -1
- package/dist/manifest-dG6MuR1U.mjs +1 -0
- package/dist/manifest-nWXtgq5Y2.mjs +1 -0
- package/dist/{manifest-BPuE6oH2.mjs → manifest-vp1upSSq.mjs} +1 -1
- package/dist/modules-DO3jXCgj.mjs +333 -0
- package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
- package/dist/native/scripts/linux/enum-windows.sh +12 -12
- package/dist/native/scripts/macos/enum-windows.applescript +22 -22
- 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-Cuk7-xUt.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-DUHIPE-v.mjs → registry-xB8Wgmyj.mjs} +1 -1
- package/dist/renderer-pid-7jbTR8f5.mjs +1 -0
- package/dist/search-defaults-CJik67or.mjs +1 -0
- package/dist/server/plugin-api.d.mts +19 -36
- 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-D-peM3aO.mjs +103 -0
- package/dist/wasm-CZajRaad.mjs +174 -0
- package/dist/{webcrack-CsLLJIs9.mjs → webcrack-phEfVt5y.mjs} +3 -3
- package/dist/{workflow-CYIXtrWD.mjs → workflow-wkXb3x-U.mjs} +4 -4
- package/package.json +16 -15
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/CodeInjector-BlgyqTOk.mjs +0 -1
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
- package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
- package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
- package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
- package/dist/MemoryController-BaqstM5w.mjs +0 -2
- package/dist/MemoryScanner-BLYnMJy6.mjs +0 -1
- package/dist/NativeMemoryManager.impl-CI554XbY.mjs +0 -1
- package/dist/PageController-D9jVkH0i.mjs +0 -1
- package/dist/PointerChainEngine-5nF9eNlu.mjs +0 -1
- package/dist/PrerequisiteError-Bl3dK8XA.mjs +0 -1
- package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
- package/dist/ScriptManager-fgqiALgj.mjs +0 -7
- package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
- package/dist/ToolProbe-xsfALmN3.mjs +0 -1
- package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
- package/dist/ToolRouter.policy-CFHoN_Lw.mjs +0 -4
- package/dist/VersionDetector-DMoUWyNm.mjs +0 -9
- package/dist/analysis-BuR-NgX8.mjs +0 -5
- package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
- package/dist/binary-instrument-Cf9qqLlM.mjs +0 -7
- package/dist/browser-C4Le3xqA.mjs +0 -11
- package/dist/collector-CKO8RPK8.mjs +0 -1
- package/dist/constants-Cp6hBrrx.mjs +0 -1
- package/dist/coordination-BbijHEHH.mjs +0 -1
- package/dist/debugger-CRJq_krh.mjs +0 -1
- package/dist/definitions-BGobEDQa.mjs +0 -1
- package/dist/definitions-CdWEuIkI.mjs +0 -1
- package/dist/definitions-CoQFbggH.mjs +0 -1
- package/dist/definitions-OvGsfxdt.mjs +0 -1
- package/dist/ensure-browser-core-Buls24LQ.mjs +0 -1
- package/dist/flat-target-session-CO5g78k3.mjs +0 -1
- package/dist/handlers-D3iev8g1.mjs +0 -1
- package/dist/handlers-D49r1-1P.mjs +0 -1
- package/dist/handlers-DCE45Ww8.mjs +0 -2
- package/dist/handlers-De5u62Ga2.mjs +0 -1
- package/dist/handlers-DnJRGp7t.mjs +0 -302
- package/dist/handlers-S9Ws0IGy.mjs +0 -2
- package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
- package/dist/maintenance-CutEO84j.mjs +0 -1
- package/dist/manifest-BFGxlDRh.mjs +0 -123
- package/dist/manifest-BXry5N09.mjs +0 -1
- package/dist/manifest-BeP_zJGb2.mjs +0 -1
- package/dist/manifest-C0g67k6U.mjs +0 -1
- package/dist/manifest-CFn0359q2.mjs +0 -1
- package/dist/manifest-CJMGt7Qy.mjs +0 -1
- package/dist/manifest-CRIJq4Hs.mjs +0 -1
- package/dist/manifest-C_hEIjSx.mjs +0 -1
- package/dist/manifest-Cq0j7GZt.mjs +0 -1
- package/dist/manifest-CtPmHAdn.mjs +0 -1
- package/dist/manifest-Cx2IVMUY.mjs +0 -1
- package/dist/manifest-D16xPXro.mjs +0 -1
- package/dist/manifest-DC-SMF6b.mjs +0 -1
- package/dist/manifest-DD3rtxvV.mjs +0 -1
- package/dist/manifest-De-6Wf2R.mjs +0 -1
- package/dist/manifest-DsVh7Y4U.mjs +0 -1
- package/dist/manifest-DtEFSRaq.mjs +0 -1
- package/dist/manifest-H-EpAyZQ.mjs +0 -1
- package/dist/manifest-ais9Afrw.mjs +0 -1
- package/dist/manifest-tmb54wmA.mjs +0 -1
- package/dist/manifest-zrbrpKCC.mjs +0 -1
- package/dist/matchesWildcardPattern-BGqLSmEs.mjs +0 -1
- package/dist/modules-p-PUNv9r.mjs +0 -332
- package/dist/network-BjZ1Y-GB.mjs +0 -7
- package/dist/outputPaths-BonGThuc.mjs +0 -2
- package/dist/platform-C446Lf97.mjs +0 -93
- package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +0 -1
- package/dist/process-C9f2A5zk.mjs +0 -962
- package/dist/proxy-CvRepxgV.mjs +0 -1
- package/dist/search-defaults-D2bY-rzH.mjs +0 -1
- package/dist/shared-state-board-Cyg-xh_k.mjs +0 -1
- package/dist/sourcemap-D6Q1UuAp.mjs +0 -1
- package/dist/streaming-CTX58tbb.mjs +0 -1
- package/dist/transform-Cv9P2vVD.mjs +0 -103
- package/dist/types-DtThH00r.mjs +0 -1
- package/dist/wasm-DaJa8J0V.mjs +0 -174
- /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
- /package/dist/{EventBus-DgciURGg.mjs → EventBus-Cm-t-B65.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
- /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
- /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
- /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
- /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
- /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
- /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-L1ax5EHS.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
- /package/dist/{concurrency-CcK46d0h.mjs → concurrency-Dehnw4JC.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
- /package/dist/{formatAddress-C7j2fDlM.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-T96MR3r6.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
- /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
- /package/dist/{types-CuyefmGT.mjs → types-BzPBzmVB.mjs} +0 -0
package/dist/proxy-CvRepxgV.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{a as t,r as n,s as r,t as i}from"./parse-args-Cuk7-xUt.mjs";import{t as a}from"./ResponseBuilder-B2lu4KEl.mjs";import"./definitions-DZ8uKusP.mjs";import{createPrivateKey as o}from"node:crypto";import s from"node:path";import{access as c,mkdir as l,readFile as u,writeFile as d}from"node:fs/promises";const f={success:e=>a.ok().merge(e).json(),error:e=>a.fail(e).mcpError().json()};async function p(e){try{return await c(e),!0}catch{return!1}}function m(e){let t=e.trim(),n=/^\/(.+)\/([a-z]*)$/.exec(t);if(n&&n[1]!==void 0){let e=n[1],t=n[2]??``;return new RegExp(e,t)}return new RegExp(t)}var h=class{server=null;caPathDir;currentPort=null;captureBuffer=[];mockttpModule=null;caReady=!1;constructor(){let e=process.env.HOME||process.env.USERPROFILE||`/tmp`;this.caPathDir=s.join(e,`.jshookmcp`,`ca`)}appendCapture(e){this.captureBuffer.push(e),this.captureBuffer.length>5e3&&this.captureBuffer.shift()}async ensureCa(t){let n=s.join(this.caPathDir,`ca.key`),r=s.join(this.caPathDir,`ca.pem`);this.caReady||=(await l(this.caPathDir,{recursive:!0}),!0);let i=await p(n),a=await p(r);if(!i||!a){e.info(`[proxy] generating new CA certificates`);let i=await t.generateCACertificate();try{i.key=o(i.key).export({type:`pkcs8`,format:`pem`}).toString()}catch{}await d(n,i.key,{mode:384}),await d(r,i.cert)}return{key:await u(n,`utf8`),cert:await u(r,`utf8`),certPath:r}}async handleProxyStart(e){let t=n(e,`port`)||8080,r=i(e,`useHttps`)??!0;if(this.server)return f.error(`Proxy is already running on port ${this.currentPort}`);try{let e=this.mockttpModule??await import(`mockttp`);this.mockttpModule=e;let n=null,i;if(r){let{key:t,cert:r,certPath:a}=await this.ensureCa(e);n=a,i=e.getLocal({https:{key:t,cert:r},cors:!0})}else i=e.getLocal();let a=i;return a.on(`request`,e=>{let t=e;this.appendCapture({type:`request`,id:t.id,method:t.method,url:t.url,headers:t.headers,timestamp:Date.now()})}),a.on(`response`,e=>{let t=e;this.appendCapture({type:`response`,id:t.id,status:t.statusCode,headers:t.headers,timestamp:Date.now()})}),await i.start(t),this.server=i,this.currentPort=t,f.success({message:`Proxy started.`,port:this.currentPort,caCertPath:n})}catch(e){this.server=null;let t=e instanceof Error?e.message:String(e);return f.error(`Failed to start proxy: ${t}`)}}async handleProxyStop(e){return this.server?(await this.server.stop(),this.server=null,this.currentPort=null,f.success({message:`Proxy stopped successfully`})):f.error(`Proxy is not running.`)}async handleProxyStatus(e){return f.success({running:!!this.server,port:this.currentPort,caDir:this.caPathDir,caCertPath:s.join(this.caPathDir,`ca.pem`)})}async handleProxyExportCa(e){let t=s.join(this.caPathDir,`ca.pem`);if(!await p(t))return f.error(`CA certificate not found. Start the proxy with HTTPS enabled first.`);let n=await u(t,`utf8`);return f.success({path:t,content:n})}async handleProxyAddRule(e){if(!this.server)return f.error(`Proxy must be running to add rules.`);let i=r(e,`action`),a=(t(e,`method`)||`GET`).toUpperCase(),o=t(e,`urlPattern`)||`.*`;try{let r=m(o),s=this.server,c;c=a===`GET`?s.forGet(r):a===`POST`?s.forPost(r):a===`PUT`?s.forPut(r):a===`DELETE`?s.forDelete(r):s.forAnyRequest();let l;if(i===`forward`)l=await c.thenPassThrough();else if(i===`block`)l=await c.thenCloseConnection();else if(i===`mock_response`){let r=n(e,`mockStatus`)||200,i=t(e,`mockBody`)||``;l=await c.thenReply(r,i)}else return f.error(`Unknown action: ${i}`);return f.success({message:`Rule added successfully`,endpointId:l.id})}catch(e){let t=e instanceof Error?e.message:String(e);return f.error(`Failed to add rule: ${t}`)}}async handleProxyGetRequests(e){let n=t(e,`urlFilter`),r=this.captureBuffer;return n&&(r=r.filter(e=>e.url!==void 0&&e.url.includes(n))),f.success({count:r.length,logs:r.slice(-100)})}async handleProxyClearLogs(e){return this.captureBuffer=[],f.success({message:`Captured proxy logs cleared.`})}async handleProxySetupAdbDevice(e){let n=this.currentPort;if(!n)return f.error(`Proxy must be running locally to setup ADB device reverse tethering.`);let r=s.join(this.caPathDir,`ca.pem`);if(!await p(r))return f.error(`CA certificate not found. Start the proxy with HTTPS enabled first.`);let{exec:i}=await import(`node:child_process`),{promisify:o}=await import(`node:util`),c=o(i),l=t(e,`deviceSerial`),u=l?`-s ${l}`:``;try{try{await c(`adb version`)}catch(e){let t=e instanceof Error?e.message:String(e);return a.fail(`ADB binary not available: ${t}`).merge({available:!1,capability:`adb_binary`,status:`unavailable`,fix:"Install Android Platform Tools and ensure `adb` is available on PATH."}).json()}await c(`adb ${u} get-state`),await c(`adb ${u} push "${r}" /data/local/tmp/ca.pem`),await c(`adb ${u} reverse tcp:${n} tcp:${n}`),await c(`adb ${u} shell settings put global http_proxy 127.0.0.1:${n}`);let e=`ADB Configuration Applied Automatically:\n- Verified device connection.\n- Pushed CA to /data/local/tmp/ca.pem\n- Reversed forwarded tcp:${n} -> tcp:${n}\n- Set global http_proxy to 127.0.0.1:${n}\n\nNote: For HTTPS decryption, you still need to manually install the CA cert from /data/local/tmp/ca.pem in Android Settings (due to security restrictions) unless device is rooted.`;return f.success({message:`ADB device successfully configured.`,deviceId:l||`default`,instructions:e})}catch(e){let t=e instanceof Error?e.message:String(e);return f.error(`Failed to configure ADB device: ${t}`)}}};export{h as ProxyHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{cr as e,lr as t,mr as n,ur as r}from"./constants-Cp6hBrrx.mjs";const i={queryCategoryProfiles:[{pattern:`(?:security|vuln|xss|injection|csrf|exploit|attack|prototype\\s*pollution|漏洞|安全|注入|攻击)`,flags:`i`,domainBoosts:[{domain:`hooks`,weight:1.35},{domain:`antidebug`,weight:1.2},{domain:`core`,weight:1.1}]},{pattern:`(?:debug|breakpoint|pause|step\\s*over|step\\s*into|stack\\s*trace|断点|调试|单步)`,flags:`i`,domainBoosts:[{domain:`debugger`,weight:1.6},{domain:`v8-inspector`,weight:1.2}]},{pattern:`(?:network|request|response|header|cookie|fetch|xhr|网络|请求|抓包)`,flags:`i`,domainBoosts:[{domain:`network`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:transform|deobfuscate|beautify|minify|decode|encode|解密|混淆|反混淆|转换)`,flags:`i`,domainBoosts:[{domain:`transform`,weight:1.6},{domain:`core`,weight:1.2}]},{pattern:`(?:memory|heap|dump|scan|inject|内存|堆|扫描)`,flags:`i`,domainBoosts:[{domain:`memory`,weight:1.6},{domain:`process`,weight:1.15},{domain:`binary-instrument`,weight:1.1}]},{pattern:`(?:wasm|webassembly)`,flags:`i`,domainBoosts:[{domain:`wasm`,weight:1.6}]},{pattern:`(?:browser|page|tab|navigate|click|screenshot|浏览器|页面|标签)`,flags:`i`,domainBoosts:[{domain:`browser`,weight:1.4}]},{pattern:`(?:captcha|人机验证|验证码|图形验证)`,flags:`i`,domainBoosts:[{domain:`browser`,weight:1.65}]},{pattern:`(?:reverse|mission|signature|hook|crypto|encrypt|websocket|\\bws\\b|protocol|bundle|webpack|deobfusc|stealthfingerprint|evidence|\\bhar\\b|逆向|签名|加签|协议|反混淆|反检测|指纹|证据|报告)`,flags:`i`,domainBoosts:[{domain:`workflow`,weight:1.8},{domain:`core`,weight:1.1}]},{pattern:`(?:v8|heap\\s?(?:snapshot|dump|profile)|bytecode|jit|turbofan|ignition|hidden\\s?class)`,flags:`i`,domainBoosts:[{domain:`v8-inspector`,weight:1.6},{domain:`memory`,weight:1.2}]},{pattern:`(?:tls|ssl|boringssl|cert(?:ificate)?|pinning|handshake|keylog|nss)`,flags:`i`,domainBoosts:[{domain:`boringssl-inspector`,weight:1.6},{domain:`network`,weight:1.1}]},{pattern:`(?:skia|gpu|render|scenegraph|scene\\s?tree|raster|draw\\s?call|layer)`,flags:`i`,domainBoosts:[{domain:`skia-capture`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:frida|ghidra|ida|unidbg|jadx|disassemble|instrument)`,flags:`i`,domainBoosts:[{domain:`binary-instrument`,weight:1.6},{domain:`memory`,weight:1.2}]},{pattern:`(?:adb|android|webview|apk|dalvik|art\\s?(?:runtime)?)`,flags:`i`,domainBoosts:[{domain:`adb-bridge`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:mojo|ipc|chromium.*ipc|broker|chromium.*interface)`,flags:`i`,domainBoosts:[{domain:`mojo-ipc`,weight:1.6},{domain:`debugger`,weight:1.1}]},{pattern:`(?:syscall|etw|strace|dtrace|kernel.*call|system\\s?call|tracefs)`,flags:`i`,domainBoosts:[{domain:`syscall-hook`,weight:1.6},{domain:`process`,weight:1.1}]},{pattern:`(?:protocol.*analy|state\\s?machine|packet.*decode|field.*extract)`,flags:`i`,domainBoosts:[{domain:`protocol-analysis`,weight:1.6},{domain:`network`,weight:1.1}]},{pattern:`(?:extension.*(?:install|registry|list)|plugin.*(?:install|manage)|addon|webhook.*(?:create|manage))`,flags:`i`,domainBoosts:[{domain:`extension-registry`,weight:1.6},{domain:`workflow`,weight:1.1}]}],cjkQueryAliases:[{pattern:`工作流|流程编排|流程自动化|编排`,tokens:[`workflow`,`flow`,`orchestration`]},{pattern:`抓包|抓取|采集|捕获`,tokens:[`capture`,`sniff`,`collect`]},{pattern:`接口|端点`,tokens:[`api`,`endpoint`,`request`]},{pattern:`探测|探针|扫描`,tokens:[`probe`,`scan`]},{pattern:`账号|账户|用户`,tokens:[`account`,`user`]},{pattern:`注册|开户|报名`,tokens:[`register`,`signup`]},{pattern:`验证|校验|激活`,tokens:[`verify`,`verification`,`activation`]},{pattern:`验证码|图形验证码|人机验证`,tokens:[`captcha`,`verify`,`verification`]},{pattern:`邮箱|邮件`,tokens:[`email`,`mail`]},{pattern:`keygen|密钥|注册码|激活码`,tokens:[`keygen`,`key`,`activation`]},{pattern:`轮询|监听`,tokens:[`poll`,`watch`]},{pattern:`批量|并发`,tokens:[`batch`,`parallel`]},{pattern:`令牌|凭证|鉴权|认证`,tokens:[`token`,`auth`,`credential`]},{pattern:`提取|抽取|解析`,tokens:[`extract`,`parse`]},{pattern:`签名|加签|加密|hook`,tokens:[`signature`,`crypto`,`hook`,`sign`]},{pattern:`协议|消息|帧|handler`,tokens:[`websocket`,`protocol`,`ws`,`handler`]},{pattern:`打包|webpack|混淆|反混淆`,tokens:[`bundle`,`webpack`,`deobfuscate`,`unpack`]},{pattern:`反爬|反检测|指纹|stealth`,tokens:[`antibot`,`stealth`,`fingerprint`,`detection`]},{pattern:`证据|取证|导出|报告|快照`,tokens:[`evidence`,`export`,`report`,`forensic`]},{pattern:`多标签页|多标签|标签页`,tokens:[`tab`,`multi`]},{pattern:`脚本库|脚本仓库`,tokens:[`script`,`library`]},{pattern:`脚本`,tokens:[`script`]},{pattern:`执行|运行`,tokens:[`run`,`execute`]},{pattern:`导出`,tokens:[`export`]},{pattern:`回放|重放`,tokens:[`replay`]},{pattern:`请求`,tokens:[`request`]},{pattern:`鉴权面|认证面|授权面|凭证枚举`,tokens:[`auth`,`surface`,`token`,`credential`]},{pattern:`通道|通信|协议注册|协议枚举`,tokens:[`protocol`,`channel`,`registry`]},{pattern:`人机|挑战|风控|拦截页`,tokens:[`challenge`,`captcha`,`cloudflare`,`turnstile`]},{pattern:`签名谱系|签名链路|加签链路|签名追踪`,tokens:[`signing`,`lineage`,`signature`,`trace`]},{pattern:`复现|重发|篡改|参数篡改`,tokens:[`replay`,`tamper`,`request`]},{pattern:`反混淆链|反混淆管道|清洗|还原`,tokens:[`deobfuscate`,`pipeline`,`transform`,`ast`]},{pattern:`桌面应用|electron|nwjs|预加载`,tokens:[`electron`,`bridge`,`preload`,`ipc`]}],intentToolBoostRules:[{pattern:`(?:端到端闭环|全链路闭环|一键闭环|api(?:[_\\s-]*)capture(?:[_\\s-]*)session|抓取接口|抓包流程)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:18},{tool:`list_extension_workflows`,bonus:12},{tool:`api_probe_batch`,bonus:18},{tool:`network_extract_auth`,bonus:10},{tool:`network_export_har`,bonus:8}]},{pattern:`(?:register|signup|sign\\s*up|账号注册|账户注册|邮箱验证|验证账号|激活账号|注册验证|验证码|邮箱激活|激活链接|mail\\s*verify|email\\s*verifyaccount\\s*pending|keygen)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:12},{tool:`list_extension_workflows`,bonus:8},{tool:`tab_workflow`,bonus:8}]},{pattern:`(?:script\\s*library|script\\s*preset|run\\s*script|脚本库执行|脚本库|执行脚本)`,flags:`i`,boosts:[{tool:`page_script_run`,bonus:22},{tool:`page_script_register`,bonus:16},{tool:`run_extension_workflow`,bonus:10}]},{pattern:`(?:bundle|webpack|js\\s*bundle|脚本包|静态包|源码包)`,flags:`i`,boosts:[{tool:`js_bundle_search`,bonus:20},{tool:`sourcemap_fetch_and_parse`,bonus:10},{tool:`webpack_enumerate`,bonus:8}]},{pattern:`(?:workflow|orchestration|工作流|流程编排|流程自动化)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:26},{tool:`list_extension_workflows`,bonus:16}]},{pattern:`(?=.*(?:抓包|抓取|捕获|capture|sniff|collect))(?=.*(?:鉴权|认证|令牌|凭证|jwt|token|auth|credential))`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:18},{tool:`list_extension_workflows`,bonus:12},{tool:`network_extract_auth`,bonus:18}]},{pattern:`(?:signature|crypto|encrypt|hash|hook|签名|加签|加密)`,flags:`i`,boosts:[{tool:`search_in_scripts`,bonus:14},{tool:`detect_crypto`,bonus:12},{tool:`manage_hooks`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:websocket|\\bws\\b|protocol|socket|handler|协议|消息|帧)`,flags:`i`,boosts:[{tool:`ws_monitor`,bonus:14},{tool:`ws_get_frames`,bonus:12},{tool:`ws_get_connections`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:bundle|webpack|chunk|source.*map|deobfusc|源码|打包|混淆|反混淆)`,flags:`i`,boosts:[{tool:`js_bundle_search`,bonus:18},{tool:`collect_code`,bonus:12},{tool:`sourcemap_fetch_and_parse`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:stealth|fingerprint|webdriver|antibot|bot.*detect|反爬|反检测|指纹)`,flags:`i`,boosts:[{tool:`stealth_inject`,bonus:14},{tool:`stealth_generate_fingerprint`,bonus:12},{tool:`stealth_verify`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:evidence|export.*(?:har|markdown|json)|har|report|证据|导出|报告|取证)`,flags:`i`,boosts:[{tool:`evidence_query`,bonus:16},{tool:`evidence_export`,bonus:14},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:auth.*surface|token.*enum|credential.*map|鉴权面|认证面|凭证枚举|jwt|csrf|api.?key|授权)`,flags:`i`,boosts:[{tool:`network_extract_auth`,bonus:16},{tool:`run_extension_workflow`,bonus:6},{tool:`list_extension_workflows`,bonus:4}]},{pattern:`(?:protocol.*registry|channel.*enum|通道枚举|协议注册|协议归类|SSE|EventSource|beacon|postMessage)`,flags:`i`,boosts:[{tool:`ws_monitor`,bonus:12},{tool:`network_get_requests`,bonus:10},{tool:`sse_monitor_enable`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:challenge|turnstile|cloudflare|hcaptcha|datadome|akamai|perimeterx|kasada|人机|挑战|风控|拦截页)`,flags:`i`,boosts:[{tool:`captcha_detect`,bonus:16},{tool:`stealth_verify`,bonus:12},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:signing.*lineage|签名谱系|签名链路|加签链路|签名追踪|plaintext.*cipher|明文.*密文)`,flags:`i`,boosts:[{tool:`detect_crypto`,bonus:14},{tool:`extract_function_tree`,bonus:12},{tool:`manage_hooks`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:replay.*lab|request.*replay|复现|重发|篡改|参数篡改|request.*tamper)`,flags:`i`,boosts:[{tool:`network_replay_request`,bonus:16},{tool:`instrumentation_network_replay`,bonus:14},{tool:`network_export_har`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:deobfusc.*pipeline|反混淆链|反混淆管道|清洗|还原|ast.*transform|packer|unpack)`,flags:`i`,boosts:[{tool:`webcrack_unpack`,bonus:16},{tool:`ast_transform_apply`,bonus:14},{tool:`deobfuscate`,bonus:12},{tool:`detect_obfuscation`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:electron|nwjs|preload|ipc|asar|桌面应用|预加载|桥接|electron.*bridge)`,flags:`i`,boosts:[{tool:`electron_inspect_app`,bonus:16},{tool:`electron_ipc_sniff`,bonus:14},{tool:`asar_search`,bonus:12},{tool:`electron_check_fuses`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]}],vectorEnabled:r,vectorModelId:n,vectorCosineWeight:e,vectorDynamicWeight:t};export{i as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./response-C7rKQst4.mjs";import{t}from"./ToolError-DWU_z7gp.mjs";import{a as n,i as r,r as i,s as a,t as o}from"./parse-args-Cuk7-xUt.mjs";import"./definitions-BGobEDQa.mjs";import{randomUUID as s}from"node:crypto";function c(e){return e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)}function l(e,t){return t?RegExp(`^${t.split(`*`).map(e=>c(e)).join(`.*`)}$`).test(e):!0}var u=class{state=new Map;history=new Map;watches=new Map;maxHistoryPerKey=100;maxWatches=200;watchIdleTtlMs=30*6e4;mutationSeq=0;lastPersistedSeq=0;persistNotifier;pruneExpiredWatches(){let e=Date.now(),t=0;for(let[n,r]of this.watches)r.expiresAt<e&&(this.watches.delete(n),t++);if(this.watches.size>this.maxWatches){let e=[...this.watches.entries()].toSorted((e,t)=>e[1].lastChecked-t[1].lastChecked),n=this.watches.size-this.maxWatches;for(let r=0;r<n;r++){let n=e[r];n&&(this.watches.delete(n[0]),t++)}}return t}setPersistNotifier(e){this.persistNotifier=e}markDirty(){this.mutationSeq++,this.persistNotifier?.()}recordChange(e,t){this.markDirty();let n=this.history.get(e);n||(n=[],this.history.set(e,n)),n.push(t),n.length>this.maxHistoryPerKey&&n.splice(0,n.length-this.maxHistoryPerKey)}deleteEntry(e){let t=this.state.get(e);t&&(this.state.delete(e),this.recordChange(e,{id:s().slice(0,8),key:t.key,namespace:t.namespace,action:`delete`,oldValue:t.value,timestamp:Date.now()}))}isExpired(e){return!!(e.expiresAt&&Date.now()>e.expiresAt)}cleanupExpired(){let e=Date.now(),t=0;for(let[n,r]of this.state.entries())r.expiresAt&&e>r.expiresAt&&(this.state.delete(n),this.recordChange(n,{id:s().slice(0,8),key:r.key,namespace:r.namespace,action:`expire`,oldValue:r.value,timestamp:e}),t++);return t}getSnapshotSeq(){return this.mutationSeq}getLastPersistedSeq(){return this.lastPersistedSeq}markPersisted(){this.lastPersistedSeq=this.mutationSeq}isPersistDirty(){return this.mutationSeq!==this.lastPersistedSeq}exportSnapshot(){return{schemaVersion:1,savedAt:new Date().toISOString(),entries:[...this.state.entries()],history:[...this.history.entries()]}}restoreSnapshot(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion!==1)return;let n=Date.now();if(this.state.clear(),this.history.clear(),t.entries)for(let[e,r]of t.entries)r.expiresAt&&n>r.expiresAt||this.state.set(e,r);if(t.history)for(let[e,n]of t.history)this.history.set(e,n);this.mutationSeq=this.state.size,this.lastPersistedSeq=this.mutationSeq}},d=class{store;constructor(e){this.store=e}async handleSet(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=e.value,o=n(e,`namespace`,`default`),c=i(e,`ttlSeconds`),l=`${o}:${t}`,u=Date.now(),d=this.store.state.get(l),f=d?.version??0,p=d?.value,m={key:t,value:r,namespace:o,createdAt:d?.createdAt??u,updatedAt:u,ttlSeconds:c,expiresAt:c?u+c*1e3:void 0,version:f+1};return this.store.state.set(l,m),this.store.recordChange(l,{id:s().slice(0,8),key:t,namespace:o,action:`set`,oldValue:p,newValue:r,timestamp:u}),{success:!0,key:t,namespace:o,version:m.version,expiresAt:m.expiresAt?new Date(m.expiresAt).toISOString():void 0}}async handleGet(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=n(e,`namespace`,`default`),i=`${r}:${t}`,o=this.store.state.get(i);return o?this.store.isExpired(o)?(this.store.deleteEntry(i),{found:!1,key:t,namespace:r,expired:!0}):{found:!0,key:t,namespace:r,value:o.value,version:o.version,createdAt:new Date(o.createdAt).toISOString(),updatedAt:new Date(o.updatedAt).toISOString(),ttlSeconds:o.ttlSeconds,expiresAt:o.expiresAt?new Date(o.expiresAt).toISOString():void 0}:{found:!1,key:t,namespace:r}}async handleDelete(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=n(e,`namespace`,`default`),i=`${r}:${t}`;return this.store.state.get(i)?(this.store.deleteEntry(i),{deleted:!0,key:t,namespace:r}):{deleted:!1,key:t,namespace:r,reason:`not_found`}}async handleList(e){let t=n(e,`namespace`),r=o(e,`includeValues`,!1),i=[],a=[];for(let e of this.store.state.values())if(!(t&&e.namespace!==t)){if(this.store.isExpired(e)){a.push(`${e.namespace}:${e.key}`);continue}i.push({key:e.key,namespace:e.namespace,version:e.version,updatedAt:new Date(e.updatedAt).toISOString(),...r?{value:e.value}:{}})}for(let e of a)this.store.deleteEntry(e);return i.sort((e,t)=>e.namespace===t.namespace?e.key.localeCompare(t.key):e.namespace.localeCompare(t.namespace)),{entries:i,total:i.length,namespaces:[...new Set(i.map(e=>e.namespace))]}}async handleClear(e){let t=n(e,`namespace`),r=n(e,`keyPattern`),i=[];for(let[e,n]of this.store.state.entries())t&&n.namespace!==t||l(n.key,r)&&i.push(e);for(let e of i)this.store.deleteEntry(e);return{cleared:i.length,namespace:t??`all`,pattern:r}}async handleStats(){let e=Date.now(),t={},n=0;for(let[,r]of this.store.state.entries()){if(r.expiresAt&&e>r.expiresAt){n++;continue}t[r.namespace]=(t[r.namespace]??0)+1}let r=0;for(let e of this.store.history.values())r+=e.length;return{totalEntries:Object.values(t).reduce((e,t)=>e+t,0),entriesByNamespace:t,expiredEntries:n,totalWatches:this.store.watches.size,historySize:r}}},f=class{store;constructor(e){this.store=e}async handleWatch(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=n(e,`namespace`,`default`),o=i(e,`pollIntervalMs`,1e3);this.store.pruneExpiredWatches();let c=`watch_${s().slice(0,8)}`,u=t.includes(`*`),d=Date.now(),f={id:c,key:t,namespace:r,pattern:u,pollIntervalMs:o,lastChecked:d,lastVersion:{},createdAt:d,expiresAt:d+this.store.watchIdleTtlMs},p=`${r}:`;for(let[e,n]of this.store.state.entries())e.startsWith(p)&&(u?l(n.key,t)&&(f.lastVersion[n.key]=n.version):n.key===t&&(f.lastVersion[n.key]=n.version));return this.store.watches.set(c,f),{watchId:c,key:t,namespace:r,pattern:u,pollIntervalMs:o,initialKeys:Object.keys(f.lastVersion)}}async handleUnwatch(e){let t=a(e,`watchId`),n=this.store.watches.get(t);return n?(this.store.watches.delete(t),{removed:!0,watchId:t,wasWatching:n.key}):{removed:!1,watchId:t,reason:`not_found`}}async handlePoll(e){let t=a(e,`watchId`),n=this.store.watches.get(t);if(!n)throw Error(`Watch "${t}" not found`);let r=Date.now(),i=[],o=`${n.namespace}:`;if(n.pattern){for(let[e,t]of this.store.state.entries())if(e.startsWith(o)&&l(t.key,n.key)){let e=n.lastVersion[t.key];e===void 0?i.push({key:t.key,namespace:t.namespace,action:`created`}):t.version>e&&i.push({key:t.key,namespace:t.namespace,action:`changed`}),n.lastVersion[t.key]=t.version}for(let e of Object.keys(n.lastVersion))!this.store.state.has(`${n.namespace}:${e}`)&&l(e,n.key)&&(i.push({key:e,namespace:n.namespace,action:`deleted`}),delete n.lastVersion[e])}else{let e=`${n.namespace}:${n.key}`,t=this.store.state.get(e),r=n.lastVersion[n.key];!t&&r!==void 0?(i.push({key:n.key,namespace:n.namespace,action:`deleted`}),delete n.lastVersion[n.key]):t&&(r===void 0?i.push({key:t.key,namespace:t.namespace,action:`created`}):t.version>r&&i.push({key:t.key,namespace:t.namespace,action:`changed`}),n.lastVersion[n.key]=t.version)}return n.lastChecked=r,n.expiresAt=r+this.store.watchIdleTtlMs,{watchId:t,changes:i,hasChanges:i.length>0,checkedAt:new Date(r).toISOString()}}},p=class{store;constructor(e){this.store=e}async handleHistory(e){let t=a(e,`key`),r=n(e,`namespace`,`default`),o=i(e,`limit`,50),s=`${r}:${t}`,c=this.store.history.get(s)??[],l=[...c].toSorted((e,t)=>t.timestamp-e.timestamp).slice(0,o);return{key:t,namespace:r,history:l.map(e=>({...e,timestamp:new Date(e.timestamp).toISOString()})),total:c.length,returned:l.length}}async handleExport(e){let t=n(e,`namespace`),r=n(e,`keyPattern`),i=Date.now(),a={};for(let[e,n]of this.store.state.entries())t&&n.namespace!==t||l(n.key,r)&&(n.expiresAt&&i>n.expiresAt||(a[n.key]=n.value));return{data:a,count:Object.keys(a).length,namespace:t??`all`,exportedAt:new Date(i).toISOString()}}async handleImport(e){let t=r(e,`data`),i=n(e,`namespace`,`default`),a=o(e,`overwrite`,!1);if(!t)throw Error(`data must be an object`);let c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){let t=`${i}:${e}`,r=this.store.state.get(t);if(r&&!a){l.push(e);continue}r&&a&&u.push(e);let o=Date.now(),d={key:e,value:n,namespace:i,createdAt:r?.createdAt??o,updatedAt:o,version:(r?.version??0)+1};this.store.state.set(t,d),this.store.recordChange(t,{id:s().slice(0,8),key:e,namespace:i,action:`set`,oldValue:r?.value,newValue:n,timestamp:o,source:`import`}),c.push(e)}return{imported:c.length,skipped:l.length,overwritten:u.length,total:Object.keys(t).length,keys:c}}},m=class{store;storeHandlers;watchHandlers;ioHandlers;constructor(){this.store=new u,this.storeHandlers=new d(this.store),this.watchHandlers=new f(this.store),this.ioHandlers=new p(this.store)}setPersistNotifier(e){this.store.setPersistNotifier(e)}handleSet(e){return this.storeHandlers.handleSet(e)}handleGet(e){return this.storeHandlers.handleGet(e)}handleDelete(e){return this.storeHandlers.handleDelete(e)}handleList(e){return this.storeHandlers.handleList(e)}handleWatchDispatch(e){let t=String(e.action??``);return t===`stop`?this.watchHandlers.handleUnwatch(e):t===`poll`?this.watchHandlers.handlePoll(e):this.watchHandlers.handleWatch(e)}handleIODispatch(e){return String(e.action??``)===`import`?this.ioHandlers.handleImport(e):this.ioHandlers.handleExport(e)}handleWatch(e){return this.watchHandlers.handleWatch(e)}handleUnwatch(e){return this.watchHandlers.handleUnwatch(e)}handlePoll(e){return this.watchHandlers.handlePoll(e)}handleHistory(e){return this.ioHandlers.handleHistory(e)}handleExport(e){return this.ioHandlers.handleExport(e)}handleImport(e){return this.ioHandlers.handleImport(e)}handleClear(e){return this.storeHandlers.handleClear(e)}handleDispatch(n){let r=String(n.action??``);switch(r){case`set`:return this.storeHandlers.handleSet(n);case`get`:return this.storeHandlers.handleGet(n);case`delete`:return this.storeHandlers.handleDelete(n);case`list`:return this.storeHandlers.handleList(n);case`history`:return this.ioHandlers.handleHistory(n);case`clear`:return this.storeHandlers.handleClear(n);default:return Promise.resolve(e(new t(`VALIDATION`,`Invalid action: "${r}". Expected one of: set, get, delete, list, history, clear`,{toolName:`state_board`})))}}handleStats(){return this.storeHandlers.handleStats()}cleanupExpired(){return this.store.cleanupExpired()}getStore(){return this.store}};export{m as SharedStateBoardHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_r as e,vr as t}from"./constants-Cp6hBrrx.mjs";import{i as n}from"./artifacts-B5xQuEa_.mjs";import{s as r}from"./PageController-D9jVkH0i.mjs";import{n as i,t as a}from"./flat-target-session-CO5g78k3.mjs";import"./definitions-CYFbewnd.mjs";import{dirname as o,resolve as s}from"node:path";import{mkdir as c,writeFile as l}from"node:fs/promises";const u=new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e,t]));function d(e){let t=(e&1)==1,n=e>>1;return t?-n:n}function f(e){let t=[],n=0;for(;n<e.length;){let r=0,i=0,a=!0;for(;a;){let t=e.charAt(n);if(!t)throw Error(`Unexpected end of VLQ segment: "${e}"`);n+=1;let o=u.get(t);if(o===void 0)throw Error(`Invalid VLQ base64 char "${t}" in segment "${e}"`);a=(o&32)!=0;let s=o&31;r+=s<<i,i+=5}t.push(d(r))}return t}function p(e){let t=[],n=0;for(;n<e.length;){let r=0,i=0,a=!0;for(;a;){let t=e.charAt(n);if(!t)throw Error(`Unexpected end of VLQ segment: "${e}"`);n+=1;let o=u.get(t);if(o===void 0)throw Error(`Invalid VLQ base64 char "${t}" in segment "${e}"`);a=(o&32)!=0;let s=o&31;r+=s<<i,i+=5}t.push(r)}return t}function m(e){if(!e)return[];let t=[],n=0,r=0,i=0,a=0,o=e.split(`;`);for(let e=0;e<o.length;e+=1){let s=o[e]??``,c=0;if(!s)continue;let l=s.split(`,`);for(let o of l){if(!o)continue;let s=f(o),l=s[0];if(l===void 0)continue;c+=l;let u={generatedLine:e+1,generatedColumn:c};s.length>=4&&(n+=s[1]??0,r+=s[2]??0,i+=s[3]??0,u.sourceIndex=n,u.originalLine=r+1,u.originalColumn=i,s.length>=5&&(a+=s[4]??0,u.nameIndex=a)),t.push(u)}}return t}function h(e){if(!e)return{mappingsCount:0,segmentCount:0};let t=0,n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`;`?(r&&t++,r=!1):a===`,`?n++:r||(r=!0,n++)}return r&&t++,{mappingsCount:t,segmentCount:n}}function g(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function _(e,t){return g({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}function v(e){return typeof e==`object`&&e?e:{}}function y(e){return typeof e==`string`?e:void 0}function b(e){return/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)}function x(e,t){return typeof e==`boolean`?e:t}function S(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} is required`);return e.trim()}function C(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}async function w(e){if(e.detach)try{await e.detach()}catch{}}async function T(e,t,n){try{await e.send(t,n)}catch{}}async function E(e){await new Promise(t=>setTimeout(()=>t(),e))}var D=class{state;constructor(e){this.state=e}async handleExtensionListInstalled(e){let t=await(await this.state.collector.getActivePage()).createCDPSession();try{return g((await this.getExtensionTargets(t)).map(e=>({extensionId:e.extensionId,name:e.name,type:e.type,url:e.url})))}catch(e){return _(`extension_list_installed`,e)}finally{await w(t)}}async handleExtensionExecuteInContext(e){let t=S(e.extensionId,`extensionId`),n=S(e.code,`code`),r=x(e.returnByValue,!0),o=await(await this.state.collector.getActivePage()).createCDPSession(),s=null;try{let e=await this.getExtensionTargets(o,t);if(e.length===0)throw Error(`No background target found for extension: ${t}`);let i=this.pickPreferredExtensionTarget(e);s=await a(o,i.targetId);let c=await this.evaluateInAttachedTarget(s,n,r);return g({extensionId:t,target:{type:i.type,url:i.url,name:i.name},result:c.result,exceptionDetails:c.exceptionDetails})}catch(e){return _(`extension_execute_in_context`,e)}finally{s&&await i(o,s).catch(()=>void 0),await w(o)}}async getExtensionTargets(e,t){let n=v(await e.send(`Target.getTargets`)),r=Array.isArray(n.targetInfos)?n.targetInfos:[],i=new Set([`service_worker`,`background_page`]),a=[];for(let e of r){let n=v(e),r=y(n.targetId),o=y(n.type),s=y(n.url);if(!r||!o||!s||!i.has(o))continue;let c=this.extractExtensionId(s);if(!c||t&&c!==t)continue;let l=y(n.title)??``;a.push({targetId:r,extensionId:c,name:l||c,type:o,url:s})}return a.sort((e,t)=>{let n=e.type===`service_worker`?0:1,r=t.type===`service_worker`?0:1;return n===r?e.extensionId.localeCompare(t.extensionId):n-r}),a}pickPreferredExtensionTarget(e){return e.find(e=>e.type===`service_worker`)??e[0]}extractExtensionId(e){return e.match(/^chrome-extension:\/\/([a-p]{32})(?:\/|$)/i)?.[1]??null}async evaluateInAttachedTarget(e,t,n){let r=v(await e.send(`Runtime.evaluate`,{expression:t,returnByValue:n,awaitPromise:!0})),i=v(r.result);return{result:n&&i.value!==void 0?i.value:Object.keys(i).length>0?i:null,exceptionDetails:r.exceptionDetails===void 0?null:r.exceptionDetails}}};function O(e,t,n){return A(e,t,n).then(e=>{let t=m(e.map.mappings),n=new Set(t.map(e=>e.generatedLine));return{resolvedUrl:e.resolvedUrl,map:e.map,mappings:t,mappingsCount:n.size,segmentCount:t.length}})}function k(e,t,n){return A(e,t,n).then(e=>{let{mappingsCount:t,segmentCount:n}=h(e.map.mappings);return{resolvedUrl:e.resolvedUrl,map:e.map,mappingsCount:t,segmentCount:n}})}async function A(e,t,n){let r=F(e,t??``),i=``;i=r.startsWith(`data:`)?P(r):await M(r,n);let a;try{a=JSON.parse(i)}catch{throw Error(`Invalid SourceMap JSON: ${r}`)}return{resolvedUrl:r,map:j(a)}}function j(e){let t=v(e);if(t.version!==3)throw Error(`Only SourceMap version 3 is supported`);let n=y(t.mappings);if(n===void 0)throw Error(`SourceMap.mappings is required`);let r=(Array.isArray(t.sources)?t.sources:[]).map(e=>y(e)).filter(e=>typeof e==`string`),i=(Array.isArray(t.names)?t.names:[]).map(e=>y(e)).filter(e=>typeof e==`string`),a=y(t.sourceRoot),o;return Array.isArray(t.sourcesContent)&&(o=t.sourcesContent.map(e=>typeof e==`string`?e:null)),{version:3,sources:r,sourcesContent:o,mappings:n,names:i,sourceRoot:a}}async function M(e,t){N(e);{let t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{let n=await fetch(e,{signal:t.signal});if(!n.ok)throw Error(`HTTP ${n.status} ${n.statusText}`);return await n.text()}catch(t){if(t.name===`AbortError`)throw Error(`SourceMap fetch timed out after 10s: ${e}`,{cause:t})}finally{clearTimeout(n)}}let n=await r(await t.getActivePage(),async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{let n=await fetch(e,{signal:t.signal});return n.ok?await n.text():`__FETCH_ERROR__HTTP ${n.status} ${n.statusText}`}catch(e){return`__FETCH_ERROR__${e instanceof Error?e.message:String(e)}`}finally{clearTimeout(n)}},e);if(typeof n!=`string`)throw Error(`Failed to fetch SourceMap content`);if(n.startsWith(`__FETCH_ERROR__`))throw Error(n.slice(15)||`Failed to fetch SourceMap content`);return n}function N(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Blocked: unsupported protocol "${t.protocol}"`);let n=t.hostname.toLowerCase(),r=[/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^0\./,/^169\.254\./,/^\[?::1\]?$/,/^\[?fe80:/i,/^\[?fc00:/i,/^\[?fd/i];if([`localhost`,`metadata.google.internal`,`metadata`].includes(n))throw Error(`SSRF blocked: hostname "${n}" is not allowed`);for(let e of r)if(e.test(n))throw Error(`SSRF blocked: protected/reserved IP "${n}" is not allowed`)}function P(e){let t=e.indexOf(`,`);if(t===-1)throw Error(`Invalid data URI source map`);let n=e.slice(0,t),r=e.slice(t+1);return/;base64/i.test(n)?Buffer.from(r,`base64`).toString(`utf-8`):decodeURIComponent(r)}function F(e,t){let n=e.trim();if(!n)return``;if(n.startsWith(`data:`)||b(n)||!t)return n;try{return new URL(n,t).toString()}catch{return n}}function I(e){let t=e.slice(-8192),n=/(?:\/\/[@#]\s*sourceMappingURL=([^\s]+)|\/\*[@#]\s*sourceMappingURL=([^*]+)\*\/)/g,r,i=null;for(;r=n.exec(t),r;){let e=(r[1]??r[2]??``).trim();e&&(i=e)}return i}function L(e,t){if(!e)return t;if(!t)return e;if(b(t)||t.startsWith(`/`))return t;if(b(e))try{let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t,n).toString()}catch{return`${e.replace(/\/+$/g,``)}/${t.replace(/^\/+/g,``)}`}return`${e.replace(/\/+$/g,``)}/${t.replace(/^\/+/g,``)}`}function R(e,t){let n=e.trim();if(!n)return`source_${t+1}.js`;if(n.startsWith(`webpack://`)&&(n=n.slice(10)),n.startsWith(`data:`))return`inline/source_${t+1}.txt`;if(b(n))try{let e=new URL(n);n=`${e.hostname}${e.pathname}`}catch{n=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,``)}n=n.replace(/[?#].*$/g,``),n=n.replace(/^[A-Za-z]:[\\/]/,``),n=n.replace(/^\/+/,``);let r=n.split(/[\\/]+/).map(e=>z(e)).filter(e=>e!==``&&e!==`.`&&e!==`..`);return r.length===0?`source_${t+1}.js`:r.join(`/`)}function z(e){let t=Array.from(e,e=>{let t=e.codePointAt(0);return t!==void 0&&(t<=31||`<>:"|?*`.includes(e))?`_`:e}).join(``).replace(/\s+/g,` `).trim();return!t||t===`.`||t===`..`?`_`:t}function B(e){return e.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,``).replace(/[^a-zA-Z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_|_$/g,``).slice(0,48)}function V(e){let t=0;for(let n of e)n&&(t+=1+V(n.children));return t}var H=class{state;constructor(e){this.state=e}async handleSourcemapDiscover(e){let n=x(e.includeInline,!0),r=await(await this.state.collector.getActivePage()).createCDPSession(),i=new Map,a=e=>{let t=v(e),n=y(t.scriptId);if(!n)return;let r=y(t.url)??``,a=y(t.sourceMapURL)??``,o=i.get(n),s=a?F(a,r):o?.sourceMapUrl??``;i.set(n,{scriptId:n,scriptUrl:r||o?.scriptUrl||``,sourceMapUrl:s,isInline:s.startsWith(`data:`)})};try{r.on?.(`Debugger.scriptParsed`,a),await r.send(`Debugger.enable`),await E(t);for(let e of i.values())if(!e.sourceMapUrl&&!(!e.scriptId||!e.scriptUrl))try{let t=y(v(await r.send(`Debugger.getScriptSource`,{scriptId:e.scriptId})).scriptSource);if(!t)continue;let n=I(t);if(!n)continue;let i=F(n,e.scriptUrl);e.sourceMapUrl=i,e.isInline=i.startsWith(`data:`)}catch{continue}return g(Array.from(i.values()).filter(e=>e.sourceMapUrl.length>0).filter(e=>n||!e.isInline).toSorted((e,t)=>{let n=`${e.scriptUrl}|${e.scriptId}`,r=`${t.scriptUrl}|${t.scriptId}`;return n.localeCompare(r)}).map(e=>({scriptUrl:e.scriptUrl,sourceMapUrl:e.sourceMapUrl,isInline:e.isInline,scriptId:e.scriptId})))}catch(e){return _(`sourcemap_discover`,e)}finally{r.off?.(`Debugger.scriptParsed`,a),await T(r,`Debugger.disable`),await w(r)}}async handleSourcemapFetchAndParse(e){try{let t=await O(S(e.sourceMapUrl,`sourceMapUrl`),C(e.scriptUrl),this.state.collector),n={sources:t.map.sources,mappingsCount:t.mappingsCount,segmentCount:t.segmentCount};return Array.isArray(t.map.sourcesContent)&&(n.sourcesContent=t.map.sourcesContent),g(n)}catch(e){return _(`sourcemap_fetch_and_parse`,e)}}async handleSourcemapCoverage(e){try{let t=S(e.sourceMapUrl,`sourceMapUrl`),n=await O(t,C(e.scriptUrl),this.state.collector),r=new Map,i=new Map,a=0;for(let e=0;e<n.mappings.length;e+=1){let t=n.mappings[e];if(!t)continue;let o=n.mappings[e+1],s=1;if(o&&o.generatedLine===t.generatedLine&&(s=Math.max(o.generatedColumn-t.generatedColumn,1)),t?.sourceIndex===void 0){a+=s;continue}r.set(t.sourceIndex,(r.get(t.sourceIndex)??0)+s),i.set(t.sourceIndex,(i.get(t.sourceIndex)??0)+1)}let o=n.map.sources.map((e,t)=>{let a=r.get(t)??0,o=i.get(t)??0,s=n.map.sourcesContent?.[t],c=typeof s==`string`?Buffer.byteLength(s,`utf-8`):null,l=c===null?null:Math.max(c-a,0),u=c&&c>0?Number((a/c*100).toFixed(2)):null;return{source:e,generatedSegments:o,mappedBytes:a,coveredBytes:a,unmappedBytes:l,coveragePercent:u,coveredPercent:u,sourceContentBytes:c}}),s=o.reduce((e,t)=>e+(typeof t.coveredBytes==`number`?t.coveredBytes:0),0);return g({sourceMapUrl:t,resolvedUrl:n.resolvedUrl,totalMappings:n.segmentCount,mappedSourceCount:o.filter(e=>e.generatedSegments>0).length,coveredBytes:s,uncoveredGeneratedBytes:a,buckets:[{source:`[unmapped]`,generatedSegments:n.mappings.filter(e=>e.sourceIndex===void 0).length,coveredBytes:a}],sources:o})}catch(e){return _(`sourcemap_coverage`,e)}}async handleSourcemapLookup(e){try{let t=S(e.sourceMapUrl,`sourceMapUrl`),n=C(e.scriptUrl),r=Number(e.line),i=Number(e.column);if(!Number.isInteger(r)||r<1)throw Error(`line must be a positive integer`);if(!Number.isFinite(i)||i<0)throw Error(`column must be a non-negative number`);let a=await O(t,n,this.state.collector),o=a.mappings.find(e=>e.generatedLine===r&&e.generatedColumn===i);if(!o){let e=a.mappings.filter(e=>e.generatedLine===r&&e.generatedColumn<=i);o=e.length>0?e[e.length-1]:void 0}if(!o||o.sourceIndex===void 0)return g({success:!1,sourceMapUrl:t,resolvedUrl:a.resolvedUrl,generated:{line:r,column:i},error:`No original source mapping found for generated position`});let s=o.sourceIndex;return g({success:!0,sourceMapUrl:t,resolvedUrl:a.resolvedUrl,generated:{line:r,column:i},original:{source:a.map.sources[s]??null,line:o.originalLine??null,column:o.originalColumn??null,name:typeof o.nameIndex==`number`?a.map.names[o.nameIndex]??null:null,sourceIndex:s},matchType:o.generatedLine===r&&o.generatedColumn===i?`exact`:`closest-preceding`})}catch(e){return _(`sourcemap_lookup`,e)}}async handleSourcemapReconstructTree(e){try{let t=S(e.sourceMapUrl,`sourceMapUrl`),r=C(e.outputDir),i=await k(t,void 0,this.state.collector),a=await n({category:`reports`,toolName:`sourcemap-tree`,target:B(i.resolvedUrl),ext:`tmp`,...r?{customDir:r}:{}}),u=a.absolutePath.replace(/\.tmp$/i,``),d=a.displayPath.replace(/\.tmp$/i,``);await c(u,{recursive:!0});let f=[],p=0;for(let e=0;e<i.map.sources.length;e+=1){let t=i.map.sources[e]??``,n=L(i.map.sourceRoot,t),r=R(n,e),a=s(u,r),d=i.map.sourcesContent&&e<i.map.sourcesContent.length?i.map.sourcesContent[e]:null,m=typeof d==`string`?d:`/* source content missing in source map: ${n} */\n`;try{await c(o(a),{recursive:!0}),await l(a,m,`utf-8`),f.push(r)}catch{p+=1}}return g({outputDir:d,totalSources:i.map.sources.length,writtenFiles:f.length,skippedFiles:p,files:f})}catch(e){return _(`sourcemap_reconstruct_tree`,e)}}async handleSourcemapParseV4(t){let n=S(t.sourceMapUrl,`sourceMapUrl`),r=x(t.extractScopes,!0),i=x(t.extractDebugIds,!0);try{let a=await M(n,this.state.collector),o=JSON.parse(a),s=Array.isArray(o.names)?o.names.filter(e=>typeof e==`string`):[],c=Array.isArray(o.sources)?o.sources.filter(e=>typeof e==`string`):[],l={version:o.version,sources:c.length,names:s.length,mappings:typeof o.mappings==`string`?o.mappings.length:0,hasFile:typeof o.file==`string`,hasSourceRoot:typeof o.sourceRoot==`string`},u={success:!0,sourceMapUrl:n,version:o.version,v3Baseline:l};if(i&&typeof o.debugId==`string`){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o.debugId);u.debugId=o.debugId,u.debugIdValid=e}let d=typeof o.scopes==`string`?o.scopes:typeof o.x_scopes==`string`?o.x_scopes:void 0;if(r&&d)try{let e=U(d,s,c);u.isV4=!0,u.scopes=e,u.scopeCount=V(e.originalScopes),u.generatedRangeCount=e.generatedRanges.length}catch(t){u.success=!1,u.scopeDecodeError=t instanceof Error?t.message:String(t),u.rawScopesField=d.substring(0,e)+(d.length>e?`...`:``),u.isV4=!0}let f={};return o.x_scopeLines&&(f.x_scopeLines=o.x_scopeLines),o.x_namesIdx&&(f.x_namesIdx=o.x_namesIdx),o.x_computedBases&&(f.x_computedBases=o.x_computedBases),Object.keys(f).length>0&&(u.extensions=f),!d&&!o.debugId&&Object.keys(f).length===0&&(u.isV4=!1,u.note=`No v4 fields (scopes/debugId) found. This source map is v3 only.`),t.compareV3===!0&&(u.comparison={v3Only:[`version`,`sources`,`names`,`mappings`,`file`,`sourceRoot`],v4Only:Object.keys(u).filter(e=>![`success`,`sourceMapUrl`,`version`,`v3Baseline`,`comparison`].includes(e))}),g(u)}catch(e){return _(`sourcemap_parse_v4`,e)}}};function U(e,t,n){let r=e.split(`,`),i={value:0},a=[],o=0,s=0,c=0,l=0,u=0,d=0,m=e=>e>0&&e<=t.length?t[e-1]:void 0;function h(e){return e>=0&&e<r.length?r[e]:void 0}function g(e,n){let l=h(i.value++);if(!l?.startsWith(`B`))throw Error(`expected original scope start 'B', got "${l}"`);let u=p(l.slice(1)),d=f(l.slice(1)),m=0,_=u[m++]??0,v=n.line+(u[m++]??0),y=u[m++]??0,b=v===n.line?n.column+y:y,x;_&1&&(o+=d[m++]??0,x=t[o]);let S;_&2&&(s+=d[m++]??0,S=t[s]);let C={index:a.length,sourceIndex:e,start:{line:v,column:b},end:{line:v,column:b},name:x,kind:S,isStackFrame:(_&4)!=0,variables:[],children:[]};a.push(C);let w={line:v,column:b};for(;i.value<r.length;){let n=r[i.value]??``;if(n.startsWith(`D`)){i.value++;let e=f(n.slice(1));for(let n of e)c+=n,C.variables.push(t[c]??`<name:${c}>`);continue}if(n.startsWith(`B`)){let t=g(e,w);w={...t.end},C.children.push(t);continue}break}let T=h(i.value++);if(!T?.startsWith(`C`))throw Error(`expected original scope end 'C', got "${T}"`);let E=p(T.slice(1)),D=w.line+(E[0]??0),O=E[1]??0;return C.end={line:D,column:D===w.line?w.column+O:O},C}function _(e){let t=h(i.value++);if(!t?.startsWith(`E`))throw Error(`expected generated range start 'E', got "${t}"`);let n=p(t.slice(1)),a=f(t.slice(1)),o=0,s=n[o++]??0,c=(s&1)!=0,g=e.line+(c?n[o++]??0:0),v=n[o++]??0,y=g===e.line?e.column+v:v,b;s&2&&(d+=a[o++]??0,b=d);let x={start:{line:g,column:y},end:{line:g,column:y},isStackFrame:(s&4)!=0,isHidden:(s&8)!=0,definitionIndex:b,children:[]},S=new Map,C=0,w={line:g,column:y};for(;i.value<r.length;){let e=r[i.value]??``;if(e.startsWith(`G`)){i.value++,x.bindings=p(e.slice(1)).map(e=>m(e));continue}if(e.startsWith(`H`)){i.value++;let t=p(e.slice(1));x.bindings||=[];let n=0;C+=t[n++]??0;let r=C,a=[],o=S.get(r)??{line:x.start.line,column:x.start.column};for(;n<t.length;){let e=m(t[n++]??0),r=t[n++]??0,i=o.line+r,s=t[n++]??0,c=i===o.line?o.column+s:s;a.push({from:{line:i,column:c},expression:e}),o={line:i,column:c}}for(S.set(r,o);x.bindings.length<=r;)x.bindings.push(void 0);x.bindings[r]=a;continue}if(e.startsWith(`I`)){i.value++;let t=p(e.slice(1));x.callsite={sourceIndex:t[0]??0,line:t[1]??0,column:t[2]??0};continue}if(e.startsWith(`E`)){let e=_(w);w={...e.end},x.children.push(e);continue}break}let T=h(i.value++);if(!T?.startsWith(`F`))throw Error(`expected generated range end 'F', got "${T}"`);let E=p(T.slice(1)),D=E.length===2,O=w.line+(D?E[0]??0:0),k=E[+!!D]??0,A=O===w.line?w.column+k:k;return x.end={line:O,column:A},l=O,u=A,x}let v=Array.from({length:n.length},()=>null);for(let e=0;e<n.length&&i.value<r.length;e++){if((r[i.value]??``)===``){i.value++;continue}if(!(r[i.value]??``).startsWith(`B`))break;v[e]=g(e,{line:0,column:0}),(r[i.value]??``)===``&&i.value++}let y=[];for(;i.value<r.length;){if((r[i.value]??``)===``){i.value++;continue}y.push(_({line:l,column:u}))}return{originalScopes:v,generatedRanges:y}}var W=class{collector;extension;sourcemap;constructor(e){this.collector=e;let t={collector:e};this.extension=new D(t),this.sourcemap=new H(t)}handleExtensionListInstalled(e){return this.extension.handleExtensionListInstalled(e)}handleExtensionExecuteInContext(e){return this.extension.handleExtensionExecuteInContext(e)}handleSourcemapDiscover(e){return this.sourcemap.handleSourcemapDiscover(e)}handleSourcemapFetchAndParse(e){return this.sourcemap.handleSourcemapFetchAndParse(e)}handleSourcemapCoverage(e){return this.sourcemap.handleSourcemapCoverage(e)}handleSourcemapLookup(e){return this.sourcemap.handleSourcemapLookup(e)}handleSourcemapReconstructTree(e){return this.sourcemap.handleSourcemapReconstructTree(e)}handleSourcemapParseV4(e){return this.sourcemap.handleSourcemapParseV4(e)}};export{W as SourcemapToolHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{$r as t,Qr as n}from"./constants-Cp6hBrrx.mjs";import{o as r,s as i}from"./PageController-D9jVkH0i.mjs";import"./definitions-BbxOUiP-.mjs";var a=class{capacity;buf;head=0;tail=0;count=0;constructor(e){this.capacity=e,this.buf=Array.from({length:e})}get length(){return this.count}push(e){if(this.count===this.buf.length)if(this.buf.length<this.capacity)this.grow();else{this.buf[this.tail]=e,this.tail=(this.tail+1)%this.buf.length,this.head=(this.head+1)%this.buf.length;return}this.buf[this.tail]=e,this.tail=(this.tail+1)%this.buf.length,this.count++}shift(){if(this.count===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.buf.length,this.count--,e}clear(){this.buf=Array.from({length:Math.min(64,this.capacity)}),this.head=0,this.tail=0,this.count=0}*[Symbol.iterator](){for(let e=0;e<this.count;e++)yield this.buf[(this.head+e)%this.buf.length]}toArray(){let e=Array.from({length:this.count});for(let t=0;t<this.count;t++)e[t]=this.buf[(this.head+t)%this.buf.length];return e}map(e){let t=Array.from({length:this.count});for(let n=0;n<this.count;n++)t[n]=e(this.buf[(this.head+n)%this.buf.length],n);return t}grow(){let e=Math.min(this.buf.length*2,this.capacity),t=Array.from({length:e});for(let e=0;e<this.count;e++)t[e]=this.buf[(this.head+e)%this.buf.length];this.buf=t,this.head=0,this.tail=this.count}};function o(e){return{collector:e,wsSession:null,wsListeners:null,wsConfig:{enabled:!1,maxFrames:1e3},wsFramesByRequest:new Map,wsFrameOrder:new a(1e3),wsConnections:new Map,sseConfig:{maxEvents:2e3}}}function s(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function c(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function l(e,t){let n;if(typeof e==`number`&&Number.isFinite(e))n=e;else if(typeof e==`string`){let t=Number(e.trim());Number.isFinite(t)&&(n=t)}return n===void 0&&(n=t.defaultValue),t.integer&&(n=Math.trunc(n)),n<t.min&&(n=t.min),n>t.max&&(n=t.max),n}function u(e){return e===`sent`||e===`received`||e===`all`?e:`all`}function d(e){try{return{regex:new RegExp(e)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}const f=e=>typeof e==`object`&&e?e:void 0,p=(e,t)=>{let n=f(e)?.[t];return typeof n==`string`?n:void 0},m=(e,t)=>{let n=f(e)?.[t];return typeof n==`number`?n:void 0},h=(e,t)=>{let n=f(e)?.[t];return f(n)};var g=class{s;constructor(e){this.s=e}async teardownWsSession(){if(this.s.wsSession&&this.s.wsListeners){try{this.s.wsSession.off(`Network.webSocketCreated`,this.s.wsListeners.created)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketCreated listener`,t)}try{this.s.wsSession.off(`Network.webSocketClosed`,this.s.wsListeners.closed)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketClosed listener`,t)}try{this.s.wsSession.off(`Network.webSocketHandshakeResponseReceived`,this.s.wsListeners.handshake)}catch(t){e.debug(`[ws-teardown] Failed to remove handshakeResponseReceived listener`,t)}try{this.s.wsSession.off(`Network.webSocketFrameSent`,this.s.wsListeners.frameSent)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketFrameSent listener`,t)}try{this.s.wsSession.off(`Network.webSocketFrameReceived`,this.s.wsListeners.frameReceived)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketFrameReceived listener`,t)}}if(this.s.wsSession)try{await this.s.wsSession.detach()}catch(t){e.debug(`[ws-teardown] Failed to detach CDP session`,t)}this.s.wsSession=null,this.s.wsListeners=null}handleWsFrame(e,r){let i=p(r,`requestId`);if(!i)return;if(!this.s.wsConnections.get(i)){if(this.s.wsConfig.urlFilter)return;this.s.wsConnections.set(i,{requestId:i,url:`unknown`,status:`open`,framesCount:0,createdTimestamp:Date.now()/1e3})}let a=this.s.wsConnections.get(i);if(!a||this.s.wsConfig.urlFilter&&a.url!==`unknown`&&!this.s.wsConfig.urlFilter.test(a.url))return;let o=h(r,`response`),s=m(o,`opcode`)??-1,c=p(o,`payloadData`)??``,l=c.length>n?`${c.slice(0,n)}…`:c,u=c.length>t?c.slice(0,t):c,d={requestId:i,timestamp:m(r,`timestamp`)??Date.now()/1e3,direction:e,opcode:s,payloadLength:c.length,payloadPreview:l,payloadSample:u,isBinary:s===2};this.appendWsFrame(i,d)}appendWsFrame(e,t){let n=this.s.wsFramesByRequest.get(e)??[];n.push(t),this.s.wsFramesByRequest.set(e,n);let r=this.s.wsConnections.get(e);r&&(r.framesCount+=1,r.status===`connecting`&&(r.status=`open`)),this.s.wsFrameOrder.push({requestId:e,frame:t}),this.enforceWsFrameLimit()}enforceWsFrameLimit(){for(;this.s.wsFrameOrder.length>this.s.wsConfig.maxFrames;){let e=this.s.wsFrameOrder.shift();if(!e)break;let t=this.s.wsFramesByRequest.get(e.requestId);t&&t.length>0&&(t.shift(),t.length===0?this.s.wsFramesByRequest.delete(e.requestId):this.s.wsFramesByRequest.set(e.requestId,t));let n=this.s.wsConnections.get(e.requestId);n&&(n.framesCount=Math.max(0,n.framesCount-1))}}getWsFrameStats(){let e=0,t=0;for(let n of this.s.wsFrameOrder)n.frame.direction===`sent`?e+=1:t+=1;return{total:this.s.wsFrameOrder.length,sent:e,received:t}}async handleWsMonitorEnable(e){let t=l(e.maxFrames,{defaultValue:1e3,min:1,max:2e4,integer:!0}),n=c(e.urlFilter),r;if(n){let e=d(n);if(e.error)return s({success:!1,error:`Invalid urlFilter regex: ${e.error}`});r=e.regex}await this.teardownWsSession(),this.s.wsFramesByRequest.clear(),this.s.wsFrameOrder=new a(t),this.s.wsConnections.clear();let i=await(await this.s.collector.getActivePage()).createCDPSession();await i.send(`Network.enable`);let o={created:e=>{let t=p(e,`requestId`),n=p(e,`url`);if(!t||!n||r&&!r.test(n))return;let i=this.s.wsConnections.get(t);this.s.wsConnections.set(t,{requestId:t,url:n,status:i?.status??`connecting`,framesCount:i?.framesCount??0,createdTimestamp:i?.createdTimestamp??Date.now()/1e3,closedTimestamp:i?.closedTimestamp,handshakeStatus:i?.handshakeStatus})},closed:e=>{let t=p(e,`requestId`);if(!t)return;let n=this.s.wsConnections.get(t);if(!n)return;n.status=`closed`;let r=m(e,`timestamp`);n.closedTimestamp=r===void 0?Date.now()/1e3:r},handshake:e=>{let t=p(e,`requestId`);if(!t)return;let n=this.s.wsConnections.get(t);if(!n)return;let r=m(h(e,`response`),`status`);r!==void 0&&(n.handshakeStatus=r,n.status=r>=100&&r<400?`open`:`error`)},frameSent:e=>{this.handleWsFrame(`sent`,e)},frameReceived:e=>{this.handleWsFrame(`received`,e)}};return i.on(`Network.webSocketCreated`,o.created),i.on(`Network.webSocketClosed`,o.closed),i.on(`Network.webSocketHandshakeResponseReceived`,o.handshake),i.on(`Network.webSocketFrameSent`,o.frameSent),i.on(`Network.webSocketFrameReceived`,o.frameReceived),this.s.wsSession=i,this.s.wsListeners=o,this.s.wsConfig={enabled:!0,maxFrames:t,urlFilterRaw:n,urlFilter:r},s({success:!0,message:`WebSocket monitor enabled`,config:{maxFrames:t,urlFilter:n??null},stats:{trackedConnections:this.s.wsConnections.size,capturedFrames:this.s.wsFrameOrder.length}})}async handleWsMonitorDisable(e){let t=this.getWsFrameStats(),n=Array.from(this.s.wsConnections.values()),r={success:!0,message:`WebSocket monitor disabled`,config:{maxFrames:this.s.wsConfig.maxFrames,urlFilter:this.s.wsConfig.urlFilterRaw??null},summary:{trackedConnections:n.length,activeConnections:n.filter(e=>e.status===`open`||e.status===`connecting`).length,closedConnections:n.filter(e=>e.status===`closed`).length,totalFrames:t.total,sentFrames:t.sent,receivedFrames:t.received}};return await this.teardownWsSession(),this.s.wsConfig={...this.s.wsConfig,enabled:!1},s(r)}async handleWsGetFrames(e){let t=u(e.direction),n=l(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),r=l(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0}),i=c(e.payloadFilter),a;if(i){let e=d(i);if(e.error)return s({success:!1,error:`Invalid payloadFilter regex: ${e.error}`});a=e.regex}let o=this.s.wsFrameOrder.toArray().map(e=>e.frame).filter(e=>t===`all`?!0:e.direction===t).filter(e=>a?a.test(e.payloadSample):!0),f=o.slice(r,r+n).map(e=>({requestId:e.requestId,timestamp:e.timestamp,direction:e.direction,opcode:e.opcode,payloadLength:e.payloadLength,payloadPreview:e.payloadPreview,isBinary:e.isBinary}));return s({success:!0,monitorEnabled:this.s.wsConfig.enabled,filters:{direction:t,payloadFilter:i??null},page:{offset:r,limit:n,returned:f.length,totalAfterFilter:o.length,hasMore:r+f.length<o.length,nextOffset:r+f.length<o.length?r+f.length:null},frames:f})}async handleWsGetConnections(e){let t=Array.from(this.s.wsConnections.values()).toSorted((e,t)=>e.createdTimestamp-t.createdTimestamp).map(e=>({requestId:e.requestId,url:e.url,status:e.status,framesCount:e.framesCount}));return s({success:!0,monitorEnabled:this.s.wsConfig.enabled,total:t.length,connections:t})}};function _(e){let t=window;t.__jshookSSEMonitor||={enabled:!0,patched:!1,maxEvents:e.maxEvents,urlFilterRaw:e.urlFilterRaw,events:[],sources:{}};let n=t.__jshookSSEMonitor;n.enabled=!0,n.maxEvents=e.maxEvents,n.urlFilterRaw=e.urlFilterRaw,n.events.length>n.maxEvents&&(n.events=n.events.slice(-n.maxEvents));let r=e=>{if(!n.urlFilterRaw)return!0;try{return new RegExp(n.urlFilterRaw).test(e)}catch{return!0}},i=e=>{if(typeof e==`string`)return e;if(e==null)return``;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return`[unserializable]`}return String(e)},a=(e,t,a,o)=>{if(!n.enabled||!r(e))return;let s=i(a),c={sourceUrl:e,eventType:t,dataPreview:s.length>200?`${s.slice(0,200)}…`:s,dataLength:s.length,lastEventId:o,timestamp:Date.now()};for(n.events.push(c);n.events.length>n.maxEvents;)n.events.shift();let l=n.sources[e]??{url:e,status:`connecting`,eventCount:0};l.eventCount+=1,l.lastEventTimestamp=c.timestamp,n.sources[e]=l};if(t.EventSource===void 0)return{success:!1,error:`EventSource is not available in current page context`};if(!n.patched){let e=t.EventSource,i=function(t,i){let o=String(t),s=new e(t,i);if(r(o)){let e=n.sources[o]??{url:o,status:`connecting`,eventCount:0};n.sources[o]=e}s.addEventListener(`open`,()=>{let e=n.sources[o];e&&(e.status=`open`),a(o,`open`,``,null)}),s.addEventListener(`error`,()=>{let e=n.sources[o];e&&(e.status=`error`),a(o,`error`,``,null)}),s.addEventListener(`message`,e=>{let t=typeof e.lastEventId==`string`&&e.lastEventId.length>0?e.lastEventId:null;a(o,e.type||`message`,e.data,t)});let c=s.addEventListener.bind(s),l=(e,t,n)=>{c(e,t,n)};return Object.defineProperty(s,`addEventListener`,{value:(e,t,n)=>{if(e!==`message`&&e!==`open`&&e!==`error`&&t){l(e,n=>{let r=n,i=typeof r.lastEventId==`string`&&r.lastEventId.length>0?r.lastEventId:null;a(o,e,r.data,i),typeof t==`function`?t.call(s,n):t.handleEvent(n)},n);return}l(e,t,n)},configurable:!0,writable:!0}),s};i.prototype=e.prototype;try{Object.defineProperty(i,`CONNECTING`,{value:e.CONNECTING}),Object.defineProperty(i,`OPEN`,{value:e.OPEN}),Object.defineProperty(i,`CLOSED`,{value:e.CLOSED})}catch{}t.EventSource=i,n.originalEventSource=e,n.patched=!0}return{success:!0,message:`SSE monitor enabled`,patched:n.patched,urlFilter:n.urlFilterRaw,maxEvents:n.maxEvents,existingEvents:n.events.length}}var v=class{s;constructor(e){this.s=e}async enableSseInterceptor(e,t,n){let a=await this.s.collector.getActivePage();return n?.persistent?(await r(a,_,{maxEvents:e,urlFilterRaw:t}),{success:!0,message:`SSE monitor enabled (persistent — survives navigations)`,patched:!0,urlFilter:t,maxEvents:e,existingEvents:0}):await i(a,_,{maxEvents:e,urlFilterRaw:t})}async handleSseMonitorEnable(e){let t=l(e.maxEvents,{defaultValue:2e3,min:1,max:5e4,integer:!0}),n=c(e.urlFilter);if(n){let e=d(n);if(e.error)return s({success:!1,error:`Invalid urlFilter regex: ${e.error}`})}let r=e.persistent===!0,i=await this.enableSseInterceptor(t,n,{persistent:r});return i.success?(this.s.sseConfig={maxEvents:t,urlFilterRaw:n},s({success:!0,message:i.message,patched:i.patched,config:{maxEvents:this.s.sseConfig.maxEvents,urlFilter:this.s.sseConfig.urlFilterRaw??null},existingEvents:i.existingEvents})):s(i)}async handleSseGetEvents(e){let t=c(e.sourceUrl),n=c(e.eventType),r=l(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),a=l(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0});return s(await i(await this.s.collector.getActivePage(),e=>{let t=window.__jshookSSEMonitor;if(!t)return{success:!1,message:`SSE monitor is not enabled. Call sse_monitor_enable first.`};let n=t.events;e.sourceUrl&&(n=n.filter(t=>t.sourceUrl===e.sourceUrl)),e.eventType&&(n=n.filter(t=>t.eventType===e.eventType));let r=n.length,i=n.slice(e.offset,e.offset+e.limit);return{success:!0,filters:{sourceUrl:e.sourceUrl??null,eventType:e.eventType??null},page:{offset:e.offset,limit:e.limit,returned:i.length,totalAfterFilter:r,hasMore:e.offset+i.length<r,nextOffset:e.offset+i.length<r?e.offset+i.length:null},monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,sourceCount:Object.keys(t.sources).length},events:i}},{sourceUrl:t,eventType:n,limit:r,offset:a}))}},y=class{collector;state;ws;sse;get wsConnections(){return this.state.wsConnections}get wsFrameOrder(){return this.state.wsFrameOrder}get wsConfig(){return this.state.wsConfig}get wsFramesByRequest(){return this.state.wsFramesByRequest}get sseConfig(){return this.state.sseConfig}constructor(e){this.collector=e,this.state=o(e),this.ws=new g(this.state),this.sse=new v(this.state)}handleWsMonitorDispatch=e=>String(e.action??``)===`disable`?this.ws.handleWsMonitorDisable(e):this.ws.handleWsMonitorEnable(e);handleWsMonitorEnable=e=>this.ws.handleWsMonitorEnable(e);handleWsMonitorDisable=e=>this.ws.handleWsMonitorDisable(e);handleWsGetFrames=e=>this.ws.handleWsGetFrames(e);handleWsGetConnections=e=>this.ws.handleWsGetConnections(e);handleSseMonitorEnable=e=>this.sse.handleSseMonitorEnable(e);handleSseGetEvents=e=>this.sse.handleSseGetEvents(e)};export{y as StreamingToolHandlers};
|
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import{Ar as e,Dr as t,Er as n,Gr as r,Hr as i,Or as a,Ur as o,Wr as s,kr as c}from"./constants-Cp6hBrrx.mjs";import{t as l}from"./ProcessRegistry-Hf12LlR9.mjs";import"./modules-p-PUNv9r.mjs";import{s as u}from"./PageController-D9jVkH0i.mjs";import{t as d}from"./ScriptManager-fgqiALgj.mjs";import"./definitions-Dds_zrWx.mjs";import{Worker as f}from"node:worker_threads";const p=r,m=s,h=i,g=o;var _=class{name;workerScript;minWorkers;maxWorkers;idleTimeoutMs;resourceLimits;workers=new Map;queuedJobs=[];activeJobs=new Map;nextWorkerId=1;nextJobId=1;closed=!1;constructor(e){if(this.name=e.name??`worker-pool`,this.workerScript=e.workerScript,this.minWorkers=e.minWorkers??p,this.maxWorkers=e.maxWorkers??m,this.idleTimeoutMs=e.idleTimeoutMs??h,this.resourceLimits=e.resourceLimits,!this.workerScript||this.workerScript.trim().length===0)throw this.toError(`workerScript must be a non-empty string`);if(!Number.isInteger(this.minWorkers)||this.minWorkers<0)throw this.toError(`minWorkers must be an integer >= 0`);if(!Number.isInteger(this.maxWorkers)||this.maxWorkers<1)throw this.toError(`maxWorkers must be an integer >= 1`);if(this.minWorkers>this.maxWorkers)throw this.toError(`minWorkers cannot be greater than maxWorkers`);this.ensureMinWorkers()}submit(e,t=g){return this.closed?Promise.reject(this.toError(`pool is closed`)):new Promise((n,r)=>{let i={id:this.nextJobId++,payload:e,timeoutMs:t,resolve:n,reject:r};this.queuedJobs.push(i),this.pumpQueue()})}async warmup(e=1){if(this.closed)return;let t=Math.min(e,this.maxWorkers-this.workers.size);for(let e=0;e<t;e++){let e=this.spawnWorker();this.armIdleTimer(e)}}async close(){if(this.closed)return;this.closed=!0;let e=this.toError(`pool is closed`);for(;this.queuedJobs.length>0;)this.queuedJobs.shift()?.reject(e);for(let t of this.activeJobs.values())t.timeoutHandle&&clearTimeout(t.timeoutHandle),t.reject(e);this.activeJobs.clear();let t=Array.from(this.workers.keys());await Promise.all(t.map(e=>this.terminateWorker(e)))}async drainIdle(){if(this.closed)return;let e=[];for(let[t,n]of this.workers)!n.busy&&this.workers.size-e.length>this.minWorkers&&e.push(t);await Promise.all(e.map(e=>this.terminateWorker(e)))}ensureMinWorkers(){if(!this.closed)for(;this.workers.size<this.minWorkers;)this.spawnWorker()}pumpQueue(){if(!this.closed)for(;this.queuedJobs.length>0;){let e=this.findIdleWorker();if(!e)if(this.workers.size<this.maxWorkers)e=this.spawnWorker();else return;let t=this.queuedJobs.shift();if(!t)return;this.dispatchJob(e,t)}}findIdleWorker(){for(let e of this.workers.values())if(!e.busy)return e}spawnWorker(){let e=this.nextWorkerId++,t=new f(this.workerScript,{eval:!0,resourceLimits:this.resourceLimits});typeof t.unref==`function`&&t.unref(),l.register(t);let n={id:e,worker:t,busy:!1,activeJobId:null,idleTimer:null};return t.on(`message`,t=>this.handleWorkerMessage(e,t)),t.on(`error`,t=>this.handleWorkerFailure(e,t)),t.on(`exit`,t=>this.handleWorkerExit(e,t)),this.workers.set(e,n),n}dispatchJob(e,t){e.busy=!0,e.activeJobId=t.id,e.idleTimer&&=(clearTimeout(e.idleTimer),null);let n=setTimeout(()=>{this.handleJobTimeout(t.id,t.timeoutMs)},t.timeoutMs);this.activeJobs.set(t.id,{...t,workerId:e.id,timeoutHandle:n});try{e.worker.postMessage({jobId:t.id,payload:t.payload})}catch(n){let r=this.activeJobs.get(t.id);r?.timeoutHandle&&clearTimeout(r.timeoutHandle),this.activeJobs.delete(t.id),e.busy=!1,e.activeJobId=null,t.reject(this.toError(n instanceof Error?n.message:String(n))),this.terminateWorker(e.id).then(()=>{this.ensureMinWorkers(),this.pumpQueue()})}}handleWorkerMessage(e,t){let n=t;if(!n||typeof n!=`object`||typeof n.jobId!=`number`)return;let r=this.activeJobs.get(n.jobId);if(!r)return;r.timeoutHandle&&clearTimeout(r.timeoutHandle),this.activeJobs.delete(n.jobId);let i=this.workers.get(e);i&&(i.busy=!1,i.activeJobId=null,this.armIdleTimer(i)),n.ok?n.result===void 0?r.reject(this.toError(`worker returned empty result`)):r.resolve(n.result):r.reject(this.toError(n.error??`worker task failed`)),this.pumpQueue()}handleWorkerFailure(e,t){let n=this.workers.get(e);if(!n)return;let r=n.activeJobId;if(r!==null){let e=this.activeJobs.get(r);e&&(e.timeoutHandle&&clearTimeout(e.timeoutHandle),this.activeJobs.delete(r),e.reject(this.toError(t.message)))}this.terminateWorker(e).then(()=>{this.ensureMinWorkers(),this.pumpQueue()})}handleWorkerExit(e,t){let n=this.workers.get(e);if(!n)return;let r=n.activeJobId;if(this.workers.delete(e),n.idleTimer&&clearTimeout(n.idleTimer),r!==null){let e=this.activeJobs.get(r);e&&(e.timeoutHandle&&clearTimeout(e.timeoutHandle),this.activeJobs.delete(r),e.reject(this.toError(`worker exited unexpectedly with code ${t}`)))}this.ensureMinWorkers(),this.pumpQueue()}handleJobTimeout(e,t){let n=this.activeJobs.get(e);n&&(this.activeJobs.delete(e),n.reject(this.toError(`worker task timed out after ${t}ms`)),this.terminateWorker(n.workerId).then(()=>{this.ensureMinWorkers(),this.pumpQueue()}))}armIdleTimer(e){this.idleTimeoutMs<=0||this.workers.size<=this.minWorkers||(e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{let t=this.workers.get(e.id);!t||t.busy||this.workers.size<=this.minWorkers||this.terminateWorker(e.id)},this.idleTimeoutMs))}async terminateWorker(e){let t=this.workers.get(e);if(t){this.workers.delete(e),t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=null,t.worker.removeAllListeners(`message`),t.worker.removeAllListeners(`error`),t.worker.removeAllListeners(`exit`);try{await t.worker.terminate()}catch{}}}toError(e){return Error(`[${this.name}] ${e}`)}};const v=new Set([`constant_fold`,`string_decrypt`,`dead_code_remove`,`control_flow_flatten`,`rename_vars`]),y=/\b(-?\d+(?:\.\d+)?)\s*([+\-*/%])\s*(-?\d+(?:\.\d+)?)\b/g,b=/(['"])((?:\\.|(?!\1)[^\\])*)\1\s*\+\s*(['"])((?:\\.|(?!\3)[^\\])*)\3/g,x=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,S=/if\s*\(\s*(?:false|0|!0\s*===\s*!1)\s*\)\s*\{([\s\S]*?)\}\s*else\s*\{([\s\S]*?)\}/g,C=/if\s*\(\s*(?:false|0|!0\s*===\s*!1)\s*\)\s*\{[\s\S]*?\}/g,w=e,T=[`cryptojs`,`md5`,`sha`,`hmac`,`sign`,`signature`,`encrypt`,`decrypt`,`aes`,`rsa`];function E(e){return{collector:e,chains:new Map,cryptoHarnessPool:new _({name:`crypto-harness`,workerScript:`
|
|
2
|
-
const __bootstrap = async () => {
|
|
3
|
-
const [workerThreads, vm, perfHooks] = await Promise.all([
|
|
4
|
-
import('node:worker_threads'), import('node:vm'), import('node:perf_hooks'),
|
|
5
|
-
]);
|
|
6
|
-
const parentPort = workerThreads.parentPort;
|
|
7
|
-
const performance = perfHooks.performance;
|
|
8
|
-
if (!parentPort) throw new Error('worker parentPort is unavailable');
|
|
9
|
-
function normalizeOutput(value) {
|
|
10
|
-
if (value === undefined) return '__undefined__';
|
|
11
|
-
if (value === null) return 'null';
|
|
12
|
-
if (typeof value === 'string') return value;
|
|
13
|
-
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);
|
|
14
|
-
try { return JSON.stringify(value); } catch { return String(value); }
|
|
15
|
-
}
|
|
16
|
-
parentPort.on('message', async (msg) => {
|
|
17
|
-
const { jobId, payload } = msg;
|
|
18
|
-
try {
|
|
19
|
-
const { code, functionName, testInputs } = payload;
|
|
20
|
-
const sandbox = Object.create(null);
|
|
21
|
-
sandbox.console = Object.freeze({ log() {}, warn() {}, error() {} });
|
|
22
|
-
sandbox.Buffer = {
|
|
23
|
-
from: (...args) => Buffer.from(...args),
|
|
24
|
-
alloc: (size) => Buffer.alloc(Math.min(size, 1048576)),
|
|
25
|
-
concat: (...args) => Buffer.concat(...args),
|
|
26
|
-
};
|
|
27
|
-
Object.freeze(sandbox.Buffer);
|
|
28
|
-
sandbox.TextEncoder = TextEncoder; sandbox.TextDecoder = TextDecoder;
|
|
29
|
-
sandbox.atob = (v) => Buffer.from(String(v), 'base64').toString('binary');
|
|
30
|
-
sandbox.btoa = (v) => Buffer.from(String(v), 'binary').toString('base64');
|
|
31
|
-
sandbox.globalThis = sandbox; Object.freeze(sandbox);
|
|
32
|
-
const context = vm.createContext(sandbox);
|
|
33
|
-
const isValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(functionName);
|
|
34
|
-
const targetExpression = isValidIdentifier
|
|
35
|
-
? "(typeof " + functionName + " !== 'undefined' ? " +
|
|
36
|
-
functionName + " : globalThis[" + JSON.stringify(functionName) + "])"
|
|
37
|
-
: "globalThis[" + JSON.stringify(functionName) + "]";
|
|
38
|
-
const script = new vm.Script(
|
|
39
|
-
"(() => {\\n" + code + "\\n;return " + targetExpression + ";\\n})()",
|
|
40
|
-
{ timeout: 5000 },
|
|
41
|
-
);
|
|
42
|
-
const targetFn = script.runInContext(context, { timeout: 5000 });
|
|
43
|
-
if (typeof targetFn !== 'function') throw new Error("Function not found or not callable: " + functionName);
|
|
44
|
-
const rows = [];
|
|
45
|
-
for (const input of testInputs) {
|
|
46
|
-
const started = performance.now();
|
|
47
|
-
try {
|
|
48
|
-
const raw = targetFn(input);
|
|
49
|
-
const resolved = raw && typeof raw.then === 'function' ? await raw : raw;
|
|
50
|
-
rows.push(
|
|
51
|
-
{
|
|
52
|
-
input,
|
|
53
|
-
output: normalizeOutput(resolved),
|
|
54
|
-
duration: Number((performance.now() - started).toFixed(3)),
|
|
55
|
-
}
|
|
56
|
-
);
|
|
57
|
-
} catch (err) {
|
|
58
|
-
rows.push(
|
|
59
|
-
{
|
|
60
|
-
input,
|
|
61
|
-
output: '',
|
|
62
|
-
error: err && err.message ? err.message : String(err),
|
|
63
|
-
duration: Number((performance.now() - started).toFixed(3)),
|
|
64
|
-
}
|
|
65
|
-
);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
parentPort.postMessage({ jobId, ok: true, result: { ok: true, results: rows } });
|
|
69
|
-
} catch (error) {
|
|
70
|
-
parentPort.postMessage(
|
|
71
|
-
{
|
|
72
|
-
jobId,
|
|
73
|
-
ok: true,
|
|
74
|
-
result: { ok: false, error: error && error.message ? error.message : String(error), results: [] },
|
|
75
|
-
}
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
};
|
|
80
|
-
__bootstrap().catch((error) => {
|
|
81
|
-
if (typeof console !== 'undefined' && typeof console.error === 'function')
|
|
82
|
-
console.error('crypto harness worker bootstrap failed:', error && error.message ? error.message : String(error));
|
|
83
|
-
});
|
|
84
|
-
`,minWorkers:0,maxWorkers:a,idleTimeoutMs:n,resourceLimits:{maxOldGenerationSizeMb:t,maxYoungGenerationSizeMb:c,stackSizeMb:8}})}}function D(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function O(e,t){return D({tool:e,error:t instanceof Error?t.message:String(t)})}function k(e){let t=Array.isArray(e)?e.map(e=>String(e).trim()).filter(e=>e.length>0):typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];if(t.length===0)throw Error(`transforms must contain at least one transform`);let n=[],r=new Set;for(let e of t){if(!v.has(e))throw Error(`Unsupported transform: ${e}`);r.has(e)||(r.add(e),n.push(e))}return n}function A(e){if(!Array.isArray(e))throw Error(`testInputs must be an array of strings`);let t=e.map(e=>String(e));if(t.length===0)throw Error(`testInputs cannot be empty`);return t}function j(e,t){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return t}function M(e,t){if(typeof e!=`string`||e.length===0)throw Error(`${t} must be a non-empty string`);return e}function N(e,t){let n=e.replace(/\\/g,`\\\\`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);return t===`"`?n.replace(/"/g,`\\"`):n.replace(/'/g,`\\'`)}function P(e){return e.replace(/\\x([0-9a-fA-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\u\{([0-9a-fA-F]{1,6})\}/g,(e,t)=>String.fromCodePoint(parseInt(t,16))).replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\n/g,`
|
|
85
|
-
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\v/g,`\v`).replace(/\\f/g,`\f`).replace(/\\0/g,`\0`).replace(/\\"/g,`"`).replace(/\\'/g,`'`).replace(/\\\\/g,`\\`)}async function F(e,t){let n=null;try{n=new d(e);let r=await n.getScriptSource(t);if(r?.source&&r.source.length>0)return r.source}catch{}finally{if(n)try{await n.close()}catch{}}let r=e.getFileByUrl(t);if(r?.content&&r.content.length>0)return r.content;let i=await(await e.getActivePage()).evaluate(async e=>{let t=Array.from(document.scripts),n=Number(e);if(Number.isInteger(n)&&n>=0&&n<t.length){let e=t[n];if(e.textContent&&e.textContent.trim().length>0)return e.textContent;if(e.src)try{let t=await fetch(e.src);if(t.ok)return await t.text()}catch{}}for(let n of t){if(n.id===e||n.dataset?.scriptId===e){if(n.textContent&&n.textContent.trim().length>0)return n.textContent;if(n.src)try{let e=await fetch(n.src);if(e.ok)return await e.text()}catch{}}if(n.src&&n.src.includes(e))try{let e=await fetch(n.src);if(e.ok)return await e.text()}catch{}}return``},t);if(typeof i==`string`&&i.length>0)return i;throw Error(`Unable to resolve source from scriptId: ${t}`)}function I(e){let t=(e.startsWith(`window.`)?e.slice(7):e).split(`.`).filter(Boolean);return t.length>0?t[t.length-1]:``}function L(e,t,n){let r=I(e);if(R(r))return r;let i=I(t);if(R(i))return i;let a=n.match(/function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/);return a?.[1]&&R(a[1])?a[1]:`extractedCryptoFn`}function R(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function z(e){await e.warmup(1)}function B(){return`const __textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;
|
|
86
|
-
const __textDecoder = typeof TextDecoder !== 'undefined' ? new TextDecoder() : null;
|
|
87
|
-
if (typeof globalThis.atob === 'undefined') {
|
|
88
|
-
globalThis.atob = (value) => Buffer.from(String(value), 'base64').toString('binary');
|
|
89
|
-
;
|
|
90
|
-
}
|
|
91
|
-
if (typeof globalThis.btoa === 'undefined') {
|
|
92
|
-
globalThis.btoa = (value) => Buffer.from(String(value), 'binary').toString('base64');
|
|
93
|
-
;
|
|
94
|
-
}`}async function V(e,t,n,r){try{let i=await e.submit({code:t,functionName:n,testInputs:r},w);if(!i.ok)return{results:r.map(e=>({input:e,output:``,duration:0,error:i.error??`Worker execution failed`})),allPassed:!1};let a=Array.isArray(i.results)?i.results:[];return{results:a,allPassed:a.every(e=>!e.error)}}catch(e){return{results:r.map(t=>({input:t,output:``,duration:0,error:e instanceof Error?e.message:String(e)})),allPassed:!1}}}function H(e,t,n){if(t.length>0){let n=e.get(t);if(!n)throw Error(`Transform chain not found: ${t}`);return[...n.transforms]}return k(n)}function U(e,t){let n=e,r=[];for(let e of t){let t=n;n=W(n,e),n!==t&&r.push(e)}return{transformed:n,appliedTransforms:r}}function W(e,t){switch(t){case`constant_fold`:return G(e);case`string_decrypt`:return K(e);case`dead_code_remove`:return q(e);case`control_flow_flatten`:return J(e);case`rename_vars`:return Y(e);default:return e}}function G(e){let t=e;for(let e=0;e<4;e++){let e=t.replace(y,(e,t,n,r)=>{let i=Number(t),a=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a))return`${t}${n}${r}`;let o=null;switch(n){case`+`:o=i+a;break;case`-`:o=i-a;break;case`*`:o=i*a;break;case`/`:a!==0&&(o=i/a);break;case`%`:a!==0&&(o=i%a);break;default:o=null}return o===null||!Number.isFinite(o)?`${t}${n}${r}`:String(Number.isInteger(o)?o:Number(o.toFixed(12)))}).replace(b,(e,t,n,r,i)=>{let a=t===r?t:`'`;return`${a}${N(`${n}${i}`,a)}${a}`});if(e===t)break;t=e}return t}function K(e){return e.replace(x,(e,t,n)=>{let r=P(n);return r===n?`${t}${n}${t}`:`${t}${N(r,t)}${t}`})}function q(e){return e.replace(S,(e,t,n)=>n).replace(C,``)}function J(e){return e.replace(/var\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*['"]([^'"]+)['"]\.split\(\s*['"]\|['"]\s*\)\s*;\s*var\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*0\s*;\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\s*\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,(e,t,n,r,i)=>{let a=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,o=new Map,s;for(;(s=a.exec(i))!==null;){let e=s[1],t=(s[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&o.set(e,t)}let c=n.split(`|`).map(e=>e.trim()).map(e=>o.get(e)).filter(e=>typeof e==`string`&&e.length>0).join(`
|
|
95
|
-
`);return c.length>0?c:e})}function Y(e){let t=new Set,n=/\b(?:var|let|const)\s+([A-Za-z])\b/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];e&&t.add(e)}if(t.size===0)return e;let i=new Map,a=1;for(let e of t)i.set(e,`var_${a}`),a+=1;return e.replace(/\b([A-Za-z])\b/g,(e,t,n,r)=>{let a=i.get(t);if(!a)return e;let o=n>0?r[n-1]:``;return o===`.`||o===`'`||o===`"`||o==="`"||o===`$`?e:a})}function X(e,t){if(e===t)return``;let n=e.split(`
|
|
96
|
-
`),r=t.split(`
|
|
97
|
-
`);if(n.length*r.length>25e4)return Z(n,r);let i=n.length,a=r.length,o=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let e=i-1;e>=0;e--)for(let t=a-1;t>=0;t--)o[e][t]=n[e]===r[t]?o[e+1][t+1]+1:Math.max(o[e+1][t],o[e][t+1]);let s=[],c=0,l=0;for(;c<i&&l<a;){if(n[c]===r[l]){s.push(` ${n[c]}`),c+=1,l+=1;continue}o[c+1][l]>=o[c][l+1]?(s.push(`-${n[c]}`),c+=1):(s.push(`+${r[l]}`),l+=1)}for(;c<i;)s.push(`-${n[c]}`),c+=1;for(;l<a;)s.push(`+${r[l]}`),l+=1;return s.join(`
|
|
98
|
-
`)}function Z(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;let r=e.length-1,i=t.length-1;for(;r>=n&&i>=n&&e[r]===t[i];)--r,--i;let a=e.slice(n,r+1).map(e=>`-${e}`),o=t.slice(n,i+1).map(e=>`+${e}`);return[...a,...o].join(`
|
|
99
|
-
`)}var Q=class{state;constructor(e){this.state=e}async handleAstTransformPreview(e){try{let t=M(e.code,`code`),n=k(e.transforms),r=j(e.preview,!0),i=U(t,n),a=r?X(t,i.transformed):``;return D({original:t,transformed:i.transformed,diff:a,appliedTransforms:i.appliedTransforms})}catch(e){return O(`ast_transform_preview`,e)}}async handleAstTransformChain(e){try{let t=M(e.name,`name`).trim(),n=typeof e.description==`string`&&e.description.trim().length>0?e.description.trim():void 0,r=k(e.transforms);if(t.length===0)throw Error(`name cannot be empty`);return this.state.chains.set(t,{name:t,transforms:r,description:n,createdAt:Date.now()}),D({name:t,transforms:r,created:!0})}catch(e){return O(`ast_transform_chain`,e)}}async handleAstTransformApply(e){try{let t=typeof e.chainName==`string`?e.chainName.trim():``,n=typeof e.code==`string`?e.code:``,r=typeof e.scriptId==`string`?e.scriptId.trim():``,i=n.length>0?n:r.length>0?await F(this.state.collector,r):``;if(i.length===0)throw Error(`Either code or scriptId must be provided`);let a=U(i,H(this.state.chains,t,e.transforms));return D({transformed:a.transformed,stats:{originalSize:i.length,transformedSize:a.transformed.length,transformsApplied:a.appliedTransforms}})}catch(e){return O(`ast_transform_apply`,e)}}},$=class{state;constructor(e){this.state=e}async runCryptoHarnessProxy(e,t,n){return V(this.state.cryptoHarnessPool,e,t,n)}async handleCryptoExtractStandalone(e){try{let t=M(e.targetFunction,`targetFunction`).trim(),n=j(e.includePolyfills,!0),r=await u(await this.state.collector.getActivePage(),(e,t)=>{let n=(Array.isArray(t)?t:[]).map(e=>String(e).toLowerCase()),r=window,i=(e,t)=>{let r=(e+`
|
|
100
|
-
`+t).toLowerCase(),i=0;for(let e of n)r.includes(e)&&(i+=1);return i},a=[],o=(e,t,n=0)=>{if(typeof t!=`function`)return;let r=Function.prototype.toString.call(t);if(r.includes(`[native code]`))return;let o=i(e,r)+n;o<=0&&n<=0||a.push({path:e,source:r,score:o})};e.length>0&&o(e,(()=>{let t=(e.startsWith(`window.`)?e.slice(7):e).split(`.`).filter(Boolean),n=window;for(let e of t){if(n==null||typeof n!=`object`&&typeof n!=`function`)return;let t=n;if(!(e in t))return;n=t[e]}return n})(),100);let s=Object.getOwnPropertyNames(r).slice(0,800);for(let e of s){let t=r[e];if(o(`window.`+e,t),t&&typeof t==`object`){let n=t,r=Object.keys(n).slice(0,40);for(let t of r)o(`window.`+e+`.`+t,n[t])}}a.sort((e,t)=>t.score-e.score);let c=a[0];if(!c)return{targetPath:null,targetSource:``,candidates:[],dependencies:[],dependencySnippets:[]};let l=/\b[A-Za-z_$][A-Za-z0-9_$]{1,}\b/g,u=new Set(`function.return.const.let.var.if.else.for.while.switch.case.break.continue.new.this.window.globalThis.Math.JSON.Date.Array.Object.String.Number.Boolean.Promise.RegExp.Error.null.undefined.true.false.async.await`.split(`.`)),d=Array.from(new Set((c.source.match(l)??[]).filter(e=>!u.has(e)))).slice(0,30),f=[];for(let e of d){if(!(e in r))continue;let t=r[e];if(typeof t==`function`){let n=Function.prototype.toString.call(t);!n.includes(`[native code]`)&&n.length<5e4&&f.push(`const `+e+` = `+n+`;`);continue}if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`boolean`){f.push(`const `+e+` = `+JSON.stringify(t)+`;`);continue}if(typeof t==`object`)try{let n=JSON.stringify(t);n&&n.length<4e3&&f.push(`const `+e+` = `+n+`;`)}catch{}}return{targetPath:c.path,targetSource:c.source,candidates:a.slice(0,20),dependencies:d,dependencySnippets:f}},t,T);if(!r||r.targetSource.trim().length===0)throw Error(`No crypto/signature-like function found on current page`);let i=L(t,r.targetPath??``,r.targetSource),a=r.dependencySnippets.filter(e=>!e.startsWith(`const ${i} = `)),o=r.dependencies.filter(e=>e!==i),s=[`'use strict';`];n&&s.push(B()),a.length>0&&s.push(a.join(`
|
|
101
|
-
`)),s.push(`const ${i} = ${r.targetSource.trim()};`),s.push(`if (typeof globalThis !== 'undefined') { globalThis.${i} = ${i}; }`);let c=s.filter(e=>e.trim().length>0).join(`
|
|
102
|
-
|
|
103
|
-
`);return D({extractedCode:c,dependencies:o,size:c.length})}catch(e){return O(`crypto_extract_standalone`,e)}}async handleCryptoTestHarness(e){try{let t=M(e.code,`code`),n=M(e.functionName,`functionName`),r=A(e.testInputs);await z(this.state.cryptoHarnessPool);try{let e=await V(this.state.cryptoHarnessPool,t,n,r);return D({results:e.results.map(e=>({input:e.input,output:e.output,duration:e.duration,...e.error?{error:e.error}:{}})),allPassed:e.allPassed})}finally{this.state.cryptoHarnessPool.drainIdle?.()}}catch(e){return O(`crypto_test_harness`,e)}}async handleCryptoCompare(e){try{let t=M(e.code1,`code1`),n=M(e.code2,`code2`),r=M(e.functionName,`functionName`),i=A(e.testInputs);await z(this.state.cryptoHarnessPool);try{let[e,a]=await Promise.all([V(this.state.cryptoHarnessPool,t,r,i),V(this.state.cryptoHarnessPool,n,r,i)]),o=i.map((t,n)=>{let r=e.results[n]??{input:t,output:``,duration:0,error:`missing result from implementation #1`},i=a.results[n]??{input:t,output:``,duration:0,error:`missing result from implementation #2`},o=r.output===i.output,s=!r.error&&!i.error;return{input:t,output1:r.output,output2:i.output,duration1:r.duration,duration2:i.duration,match:o&&s,...r.error?{error1:r.error}:{},...i.error?{error2:i.error}:{}}}),s=o.filter(e=>e.match).length;return D({matches:s,mismatches:o.length-s,results:o})}finally{this.state.cryptoHarnessPool.drainIdle?.()}}catch(e){return O(`crypto_compare`,e)}}},ee=class{collector;state;ast;crypto;constructor(e){this.collector=e,this.state=E(e),this.ast=new Q(this.state),this.crypto=new $(this.state)}async close(){await this.state.cryptoHarnessPool.close()}get chains(){return this.state.chains}get cryptoHarnessPool(){return this.state.cryptoHarnessPool}async runCryptoHarness(e,t,n){return this.crypto.runCryptoHarnessProxy(e,t,n)}handleAstTransformPreview=e=>this.ast.handleAstTransformPreview(e);handleAstTransformChain=e=>this.ast.handleAstTransformChain(e);handleAstTransformApply=e=>this.ast.handleAstTransformApply(e);handleCryptoExtractStandalone=e=>this.crypto.handleCryptoExtractStandalone(e);handleCryptoTestHarness=e=>this.crypto.handleCryptoTestHarness(e);handleCryptoCompare=e=>this.crypto.handleCryptoCompare(e)};export{ee as TransformToolHandlers};
|
package/dist/types-DtThH00r.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-C_pMuVsO.mjs";import{exec as t,execFile as n}from"child_process";import{promisify as r}from"util";var i=e({execAsync:()=>a,execFileAsync:()=>o,executePowerShellScript:()=>c});const a=r(t),o=r(n);function s(){return process.platform===`win32`?`powershell.exe`:`powershell`}async function c(e,t={}){let n=[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,Buffer.from(e,`utf16le`).toString(`base64`)],{stdout:r,stderr:i}=await o(s(),n,{maxBuffer:t.maxBuffer??1024*1024,timeout:t.timeout,windowsHide:!0});return{stdout:String(r??``),stderr:String(i??``)}}export{i,o as n,c as r,a as t};
|
package/dist/wasm-DaJa8J0V.mjs
DELETED
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
import{Fr as e,Ir as t,Lr as n,Nr as r,Pr as i}from"./constants-Cp6hBrrx.mjs";import{i as a}from"./modules-p-PUNv9r.mjs";import{i as o}from"./artifacts-B5xQuEa_.mjs";import{a as s,o as c,r as l,s as u,t as d}from"./parse-args-Cuk7-xUt.mjs";import{n as f}from"./capabilities-DbYCv-HF.mjs";import{t as p}from"./ToolRegistry-B0Zs-phN.mjs";import{t as m}from"./ResponseBuilder-B2lu4KEl.mjs";import"./definitions-CIO9O-Sw.mjs";import{tmpdir as h}from"node:os";import{createHash as g}from"node:crypto";import{join as _,normalize as v,resolve as y,sep as b}from"node:path";import{mkdir as x,stat as S,writeFile as C}from"node:fs/promises";const w=e=>typeof e==`object`&&!!e,T=e=>w(e)&&typeof e.error==`string`;function E(e){let t=y(e),n=v(process.cwd()),r=v(h());if(!t.startsWith(`${n}${b}`)&&!t.startsWith(`${r}${b}`))throw Error(`Path traversal blocked: outputPath must be under project root or temp directory`);return t}var D=class{state;constructor(e){this.state=e}ok(e){return{content:[{type:`text`,text:JSON.stringify({success:!0,...e},null,2)}]}}fail(e,t){return{content:[{type:`text`,text:JSON.stringify({success:!1,error:e,...t===void 0?{}:{exitCode:t}},null,2)}]}}async writeTextArtifact(e){let{outputPath:t,artifact:n,content:r,pathMode:i=`display`}=e;if(t){let e=E(t);return await C(e,r,`utf-8`),e}let{absolutePath:a,displayPath:s}=await o(n);return await C(a,r,`utf-8`),i===`absolute`?a:s}async resolveArtifactOutputPath(e){let{outputPath:t,artifact:n,pathMode:r=`absolute`}=e;if(t)return E(t);let{absolutePath:i,displayPath:a}=await o(n);return r===`display`?a:i}preview(e,t){let n=e.split(`
|
|
2
|
-
`);return n.slice(0,t).join(`
|
|
3
|
-
`)+(n.length>t?`
|
|
4
|
-
... (truncated)`:``)}async tryStatSize(e){try{return(await S(e)).size}catch{return 0}}};function O(e){return/^[a-z]:[\\/]/i.test(e)||/^\\\\[^\\]+\\[^\\]+/i.test(e)||/^file:\/\//i.test(e)||/^\/(?:Users|home|tmp|var|etc|opt|usr|srv|mnt|media|private|root|run|dev|proc|sys|Library|Volumes)(?:\/|$)/.test(e)}var k=class extends D{async handleWasmDetectObfuscation(e){let a=u(e,`inputPath`),o=d(e,`verbose`,!1),s=await this.state.runner.run({tool:`wabt.wasm2wat`,args:[a],timeoutMs:t});if(!s.ok)return this.fail(`Failed to disassemble: ${s.stderr}`);let c=s.stdout,l=[],f=(c.match(/br_table/g)||[]).length;f>5&&l.push({type:`control-flow-flattening`,confidence:Math.min(f/20,.95),description:`${f} br_table dispatches detected — likely flattened control flow`});let p=(c.match(/i32\.xor/g)||[]).length,m=(c.match(/i32\.rotl|i32\.rotr/g)||[]).length,h=(c.match(/i32\.shl|i32\.shr_[su]/g)||[]).length;p+m+h>r&&l.push({type:`constant-encoding`,confidence:Math.min((p+m+h)/50,.9),description:`High density of bitwise ops (${p} xor, ${h} shift, ${m} rotate) — constant decoding`});let g=c.match(/br\s+(?:\$\d+|\d+)\s*\n\s*(?!end\b|\))\S.*$/gm)||[];g.length>i&&l.push({type:`dead-code-injection`,confidence:Math.min(g.length/30,.85),description:`${g.length} code blocks after unconditional branches`});let _=/\(loop/.test(c),v=/br_table/.test(c),y=/local\.get\s+\d+/.test(c);if(_&&v&&y){let e=(c.match(/\(loop/g)||[]).length;e>n&&l.push({type:`vm-dispatch`,confidence:.75,description:`Loop + br_table + local.get pattern (${e} loops) — possible WASM VM interpreter`})}let b=(c.match(/\(func\s/g)||[]).length,x=c.length;b>0&&x/b>5e3&&l.push({type:`code-bloat`,confidence:.5,description:`Average ${(x/b).toFixed(0)} chars/function across ${b} functions — unusually large`});let S=(c.match(/\bcall_indirect\b/g)||[]).length,C=(c.match(/\bcall\s+(?!indirect)/g)||[]).length;S>3&&S>=C*.3&&l.push({type:`indirect-call-dispatch`,confidence:Math.min(S/15,.85),description:`${S} call_indirect vs ${C} direct calls — indirect call ratio suggests dispatch-based VM or obfuscation`});let w=(c.match(/\(import\s+"env"\s+"(\w+)"/g)||[]).map(e=>e.split(`"`)[3]??``).filter(e=>![`memory`,`table`,`__linear_memory`,`__indirect_function_table`].includes(e));w.length>20&&l.push({type:`large-import-surface`,confidence:Math.min(w.length/50,.7),description:`${w.length} env imports — large import surface typical of obfuscated/wrapped modules`});let T=l.length>0,E=l.reduce((e,t)=>Math.max(e,t.confidence),0);return this.ok({inputPath:a,hasObfuscation:T,overallConfidence:T?E:0,detectionCount:l.length,detections:l,summary:T?`Detected ${l.length} obfuscation pattern(s). Highest confidence: ${(E*100).toFixed(0)}%`:`No obfuscation patterns detected.`,...o?{watPreview:this.preview(c,200)}:{}})}async handleWasmInstrumentTrace(e){let n=u(e,`inputPath`),r=d(e,`allHooks`,!0),i=c(e,`hooks`),a=s(e,`outputPath`),o=await this.state.runner.run({tool:`wabt.wasm2wat`,args:[n],timeoutMs:t});if(!o.ok)return this.fail(o.stderr);let l=o.stdout,f=r?[`call`,`memory`,`branch`,`loop`,`local`]:i.length>0?i:[`call`],p=l.match(/\(func\s/g)||[],m=l.match(/\(export/g)||[],h=l.match(/\(import/g)||[],g=l.match(/\(table\b/g)||[],_=l.match(/\bcall_indirect\b/g)||[],v=[],y=[],b=/\(export\s+"([^"]+)"\s+\((\w+)\s+(\$?[\w.]+)\)\)/g,x=/\(import\s+"([^"]+)"\s+"([^"]+)"/g,S;for(;(S=b.exec(l))!==null;)S[1]&&v.push(S[1]);for(;(S=x.exec(l))!==null;)S[1]&&S[2]&&y.push({module:S[1],name:S[2]});let w={call:`
|
|
5
|
-
const callLog = [];
|
|
6
|
-
for (const [name, value] of Object.entries(instance.exports)) {
|
|
7
|
-
if (typeof value === 'function') {
|
|
8
|
-
hookedExports[name] = new Proxy(value, {
|
|
9
|
-
apply(target, thisArg, argumentsList) {
|
|
10
|
-
const entry = { type: 'call', name, args: argumentsList.map(String), timestamp: Date.now() };
|
|
11
|
-
callLog.push(entry);
|
|
12
|
-
try {
|
|
13
|
-
const result = Reflect.apply(target, thisArg, argumentsList);
|
|
14
|
-
callLog.push({ type: 'return', name, result: String(result), timestamp: Date.now() });
|
|
15
|
-
return result;
|
|
16
|
-
} catch (err) {
|
|
17
|
-
callLog.push({ type: 'throw', name, error: String(err), timestamp: Date.now() });
|
|
18
|
-
throw err;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
}`,memory:`
|
|
24
|
-
const memoryLog = [];
|
|
25
|
-
const originalMemory = instance.exports.memory || Object.values(instance.exports).find(e => e instanceof WebAssembly.Memory);
|
|
26
|
-
const memTracker = { reads: 0, writes: 0, growEvents: [] };
|
|
27
|
-
if (originalMemory) {
|
|
28
|
-
const memSnapshot = () => {
|
|
29
|
-
const view = new DataView(originalMemory.buffer);
|
|
30
|
-
return { byteLength: view.byteLength, pages: view.byteLength / 65536 };
|
|
31
|
-
};
|
|
32
|
-
memTracker.snapshot = memSnapshot;
|
|
33
|
-
const origGrow = originalMemory.grow?.bind(originalMemory);
|
|
34
|
-
if (origGrow) {
|
|
35
|
-
originalMemory.grow = function(delta) {
|
|
36
|
-
const beforePages = originalMemory.buffer.byteLength / 65536;
|
|
37
|
-
memoryLog.push({ op: 'grow', delta, beforePages, timestamp: Date.now() });
|
|
38
|
-
memTracker.growEvents.push({ delta, beforePages });
|
|
39
|
-
return origGrow(delta);
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
const memProxy = new Proxy(originalMemory, {
|
|
43
|
-
get(target, prop) {
|
|
44
|
-
if (prop === 'buffer') {
|
|
45
|
-
memTracker.reads++;
|
|
46
|
-
}
|
|
47
|
-
const val = Reflect.get(target, prop, target);
|
|
48
|
-
return typeof val === 'function' ? val.bind(target) : val;
|
|
49
|
-
}
|
|
50
|
-
});
|
|
51
|
-
const memExportName = Object.entries(instance.exports).find(([, v]) => v === originalMemory)?.[0] || 'memory';
|
|
52
|
-
hookedExports[memExportName] = memProxy;
|
|
53
|
-
memTracker.buffer = originalMemory.buffer;
|
|
54
|
-
}`,branch:`
|
|
55
|
-
// === Branch Hook: Tracks JS-visible WebAssembly.Table access only ===
|
|
56
|
-
// Internal call_indirect dispatch stays inside the Wasm engine and is not observable from JS.
|
|
57
|
-
const branchLog = [];
|
|
58
|
-
for (const [tableName, table] of Object.entries(instance.exports)) {
|
|
59
|
-
if (!(table instanceof WebAssembly.Table)) continue;
|
|
60
|
-
const origGet = table.get.bind(table);
|
|
61
|
-
const origGrow = table.grow?.bind(table);
|
|
62
|
-
hookedExports[tableName] = new Proxy(table, {
|
|
63
|
-
get(t, prop) {
|
|
64
|
-
if (prop === 'get') {
|
|
65
|
-
return (idx) => {
|
|
66
|
-
branchLog.push({ type: 'table_get', table: tableName, index: idx, timestamp: Date.now() });
|
|
67
|
-
return origGet(idx);
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
if (prop === 'grow' && origGrow) {
|
|
71
|
-
return (delta) => {
|
|
72
|
-
branchLog.push({ type: 'table_grow', table: tableName, delta, timestamp: Date.now() });
|
|
73
|
-
return origGrow(delta);
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
const val = t[prop];
|
|
77
|
-
return typeof val === 'function' ? val.bind(t) : val;
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
}`,loop:`
|
|
81
|
-
const loopLog = [];
|
|
82
|
-
const loopCallCounts = {};
|
|
83
|
-
const loopSource = hookedExports;
|
|
84
|
-
for (const [name, value] of Object.entries(loopSource)) {
|
|
85
|
-
if (typeof value === 'function') {
|
|
86
|
-
hookedExports[name] = new Proxy(value, {
|
|
87
|
-
apply(target, thisArg, args) {
|
|
88
|
-
loopCallCounts[name] = (loopCallCounts[name] || 0) + 1;
|
|
89
|
-
if (loopCallCounts[name] > 1) {
|
|
90
|
-
loopLog.push({ type: 'loop-iteration', func: name, count: loopCallCounts[name], timestamp: Date.now() });
|
|
91
|
-
}
|
|
92
|
-
return Reflect.apply(target, thisArg, args);
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}`,local:`
|
|
97
|
-
const localLog = [];
|
|
98
|
-
for (const [globalName, global] of Object.entries(instance.exports)) {
|
|
99
|
-
if (!(global instanceof WebAssembly.Global)) continue;
|
|
100
|
-
hookedExports[globalName] = new Proxy(global, {
|
|
101
|
-
get(target, prop) {
|
|
102
|
-
if (prop === 'valueOf' || prop === Symbol.toPrimitive) {
|
|
103
|
-
return (...args) => Reflect.apply(target.valueOf, target, args);
|
|
104
|
-
}
|
|
105
|
-
const val = Reflect.get(target, prop, target);
|
|
106
|
-
if (prop === 'value' && typeof val === 'function') {
|
|
107
|
-
return target.valueOf();
|
|
108
|
-
}
|
|
109
|
-
return typeof val === 'function' ? val.bind(target) : val;
|
|
110
|
-
},
|
|
111
|
-
set(target, prop, newValue) {
|
|
112
|
-
if (prop === 'value') {
|
|
113
|
-
const oldValue = target.valueOf();
|
|
114
|
-
localLog.push({ type: 'global-set', name: globalName, oldValue, newValue, timestamp: Date.now() });
|
|
115
|
-
target.value = newValue;
|
|
116
|
-
return true;
|
|
117
|
-
}
|
|
118
|
-
return Reflect.set(target, prop, newValue, target);
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
}`},T=f.filter(e=>e in w),D=`
|
|
122
|
-
const hookedExports = {};
|
|
123
|
-
for (const [k, v] of Object.entries(instance.exports)) { hookedExports[k] = v; }
|
|
124
|
-
`+T.map(e=>w[e]).join(`
|
|
125
|
-
`),k=JSON.stringify(n),A=[...new Set(y.map(({module:e})=>e))].filter(e=>e!==`env`).map(e=>` ${JSON.stringify(e)}: {},`).join(`
|
|
126
|
-
`),j=y.map(({module:e,name:t})=>{let n=JSON.stringify(e),r=JSON.stringify(t);return`if (!imports[${n}]) imports[${n}] = {};\n if (!imports[${n}][${r}]) imports[${n}][${r}] = () => {};`}).join(`
|
|
127
|
-
`),M=`// WASM Instrumentation Wrapper (Wasabi-style)
|
|
128
|
-
// Generated by jshookmcp wasm_instrument_trace
|
|
129
|
-
// Hooks: ${T.join(`, `)}
|
|
130
|
-
// Functions: ${p.length} | Exports: ${v.join(`, `)||`none`} | Imports: ${y.length}
|
|
131
|
-
|
|
132
|
-
(async function() {
|
|
133
|
-
const wasmBytes = await fetch(${k}).then(r => r.arrayBuffer());
|
|
134
|
-
const module = await WebAssembly.compile(wasmBytes);
|
|
135
|
-
|
|
136
|
-
const imports = {
|
|
137
|
-
env: {
|
|
138
|
-
abort: () => console.warn('[wasabi] abort called'),
|
|
139
|
-
memory: new WebAssembly.Memory({ initial: 256, maximum: 1024 }),
|
|
140
|
-
seed: () => Math.random(),
|
|
141
|
-
'Math.log': Math.log,
|
|
142
|
-
'Math.random': Math.random,
|
|
143
|
-
console: { log: (...a) => console.log('[wasabi]', ...a) },
|
|
144
|
-
},
|
|
145
|
-
${A?`${A}\n`:``} };
|
|
146
|
-
|
|
147
|
-
${j}
|
|
148
|
-
|
|
149
|
-
const instance = await WebAssembly.instantiate(module, imports);
|
|
150
|
-
|
|
151
|
-
${D}
|
|
152
|
-
|
|
153
|
-
const tracedExports = hookedExports;
|
|
154
|
-
|
|
155
|
-
return {
|
|
156
|
-
instance,
|
|
157
|
-
exports: tracedExports,
|
|
158
|
-
hooks: {
|
|
159
|
-
${T.map(e=>` ${e}: ${e===`call`?`callLog`:e===`memory`?`memoryLog`:e===`branch`?`branchLog`:e===`loop`?`loopLog`:`localLog`}`).join(`,
|
|
160
|
-
`)}
|
|
161
|
-
},
|
|
162
|
-
stats: {
|
|
163
|
-
functions: ${p.length},
|
|
164
|
-
exports: ${m.length},
|
|
165
|
-
imports: ${h.length},
|
|
166
|
-
exportNames: ${JSON.stringify(v)},
|
|
167
|
-
hookTypes: ${JSON.stringify(T)}
|
|
168
|
-
}
|
|
169
|
-
};
|
|
170
|
-
})();
|
|
171
|
-
`,N;if(a){let e=E(a);await C(e,M,`utf-8`),N=e}else N=await this.writeTextArtifact({artifact:{category:`wasm`,toolName:`wasm-instrument`,ext:`js`},content:M});let P=O(n),F=[P?`Wrapper embeds the provided inputPath into browser-side fetch(). Local filesystem paths are not browser-accessible; provide an http(s) URL instead, or upload the module with wasm_dump and use the resulting URL.`:void 0,T.includes(`branch`)&&_.length>0?`Branch hook only observes JS-visible WebAssembly.Table access. This module contains ${_.length} call_indirect site(s), which are dispatched inside the Wasm engine and will not appear in branch logs.`:void 0].filter(e=>typeof e==`string`&&e.length>0),I=F.length>0?F.join(` `):void 0;return this.ok({artifactPath:N,hookTypes:T,functionCount:p.length,exportCount:m.length,importCount:h.length,wrapperSizeBytes:M.length,note:`Wasabi-style instrumentation wrapper generated. Load in browser with WASM module to trace execution.`,metadata:{inputPathKind:P?`local-path`:`url`,wrapperFetchesBrowserUrl:!0,...T.includes(`branch`)?{branchHookMode:`js-table-access-only`,callIndirectSites:_.length,tableCount:g.length}:{}},...I?{warning:I}:{}})}},A=class extends D{async handleWasmDisassemble(e){let n=u(e,`inputPath`),r=s(e,`outputPath`),i=d(e,`foldExprs`,!0),a=[n,`-o`,`/dev/stdout`];i&&a.push(`--fold-exprs`);let o=await this.state.runner.run({tool:`wabt.wasm2wat`,args:a,timeoutMs:t});if(!o.ok)return this.fail(o.stderr,o.exitCode??void 0);let c=await this.writeTextArtifact({outputPath:r,artifact:{category:`wasm`,toolName:`wasm-disassemble`,ext:`wat`},content:o.stdout});return this.ok({artifactPath:c,totalLines:o.stdout.split(`
|
|
172
|
-
`).length,sizeBytes:o.stdout.length,preview:this.preview(o.stdout,50),durationMs:o.durationMs})}async handleWasmDecompile(e){let n=u(e,`inputPath`),r=s(e,`outputPath`),i=await this.state.runner.run({tool:`wabt.wasm-decompile`,args:[n,`-o`,`/dev/stdout`],timeoutMs:t});if(!i.ok)return this.fail(i.stderr,i.exitCode??void 0);let a=await this.writeTextArtifact({outputPath:r,artifact:{category:`wasm`,toolName:`wasm-decompile`,ext:`dcmp`},content:i.stdout});return this.ok({artifactPath:a,totalLines:i.stdout.split(`
|
|
173
|
-
`).length,preview:this.preview(i.stdout,60),durationMs:i.durationMs})}async handleWasmInspectSections(e){let n=u(e,`inputPath`),r=({headers:`-h`,details:`-x`,disassemble:`-d`,all:`-h -x -d`}[s(e,`sections`,`details`)]||`-x`).split(` `),i=await this.state.runner.run({tool:`wabt.wasm-objdump`,args:[...r,n],timeoutMs:t});return i.ok?this.ok({totalLines:i.stdout.split(`
|
|
174
|
-
`).length,preview:this.preview(i.stdout,100),durationMs:i.durationMs}):this.fail(i.stderr,i.exitCode??void 0)}async handleWasmToC(e){let n=u(e,`inputPath`),r=s(e,`outputDir`),i=await this.resolveArtifactOutputPath({outputPath:r,artifact:{category:`wasm`,toolName:`wasm2c`,ext:`dir`},pathMode:`absolute`});await x(i,{recursive:!0});let a=y(n).replace(/\.wasm$/i,``).split(/[/\\]/).pop()||`output`,o=_(i,`${a}.c`),c=_(i,`${a}.h`),l=await this.state.runner.run({tool:`wabt.wasm2c`,args:[n,`-o`,o],timeoutMs:t});return l.ok?this.ok({outputDir:i,cFile:o,hFile:c,cSizeBytes:await this.tryStatSize(o),hSizeBytes:await this.tryStatSize(c),durationMs:l.durationMs}):this.fail(l.stderr,l.exitCode??void 0)}},j=class extends D{async handleWasmOfflineRun(e){let t=u(e,`inputPath`),n=u(e,`functionName`),r=c(e,`args`),i=s(e,`runtime`,`auto`),a=l(e,`timeoutMs`,1e4),o;if(i===`auto`){let e=await this.state.runner.probeAll();if(e[`runtime.wasmtime`]?.available)o=`runtime.wasmtime`;else if(e[`runtime.wasmer`]?.available)o=`runtime.wasmer`;else return this.fail(`No WASM runtime found. Install wasmtime or wasmer.`)}else o=i===`wasmer`?`runtime.wasmer`:`runtime.wasmtime`;let d=o===`runtime.wasmtime`?[`run`,`--invoke`,n,t,...r]:[`run`,t,`--invoke`,n,`--`,...r],f=await this.state.runner.run({tool:o,args:d,timeoutMs:a});return this.ok({runtime:o,functionName:n,args:r,output:f.stdout.trim(),stderr:f.stderr.trim()||void 0,exitCode:f.exitCode,durationMs:f.durationMs,success:f.ok})}async handleWasmOptimize(t){let n=u(t,`inputPath`),r=s(t,`outputPath`),i=s(t,`level`,`O2`),a=await this.resolveArtifactOutputPath({outputPath:r,artifact:{category:`wasm`,toolName:`wasm-opt`,ext:`wasm`},pathMode:`absolute`}),o=await this.state.runner.run({tool:`binaryen.wasm-opt`,args:[`-${i}`,n,`-o`,a],timeoutMs:e});if(!o.ok)return this.fail(o.stderr,o.exitCode??void 0);let c=await this.tryStatSize(n),l=await this.tryStatSize(a);return this.ok({artifactPath:a,optimizationLevel:i,inputSizeBytes:c,outputSizeBytes:l,reductionPercent:c>0?((1-l/c)*100).toFixed(1):`0`,durationMs:o.durationMs})}},M=class{conversion;runtime;analysis;constructor(e){this.conversion=new A(e),this.runtime=new j(e),this.analysis=new k(e)}handleWasmDisassemble(e){return this.conversion.handleWasmDisassemble(e)}handleWasmDecompile(e){return this.conversion.handleWasmDecompile(e)}handleWasmInspectSections(e){return this.conversion.handleWasmInspectSections(e)}handleWasmOfflineRun(e){return this.runtime.handleWasmOfflineRun(e)}handleWasmOptimize(e){return this.runtime.handleWasmOptimize(e)}handleWasmToC(e){return this.conversion.handleWasmToC(e)}handleWasmDetectObfuscation(e){return this.analysis.handleWasmDetectObfuscation(e)}handleWasmInstrumentTrace(e){return this.analysis.handleWasmInstrumentTrace(e)}},N=class{state;constructor(e){this.state=e}async handleWasmDump(e){let t=l(e,`moduleIndex`,0),n=s(e,`outputPath`),r=await this.state.collector.getActivePage(),i=await r.evaluate(e=>{let t=window.__aiHooks?.[`preset-webassembly-full`];if(!Array.isArray(t)||t.length===0)return{error:`No WASM modules captured. Ensure the webassembly-full hook preset is active and the page has loaded WASM.`};let n=t.filter(e=>e.type===`instantiated`);if(e>=n.length)return{error:`Module index ${e} out of range. Found ${n.length} instantiated modules.`};let r=n[e];return{exports:r.exports,importMods:r.importMods,size:r.size,moduleCount:n.length}},t);if(T(i))return{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.error})}]};let a=await r.evaluate(e=>{let t=window.__wasmModuleStorage;if(!t?.[e])return null;let n=t[e];return Array.from(new Uint8Array(n))},t),c,u;if(a){let e=Buffer.from(a);if(u=g(`sha256`).update(e).digest(`hex`).substring(0,16),n){let t=E(n);await C(t,e),c=t}else{let{absolutePath:t,displayPath:n}=await o({category:`wasm`,toolName:`wasm-dump`,target:u,ext:`wasm`});await C(t,e),c=n}}else c=`(binary not available — hook did not store raw bytes)`;return{content:[{type:`text`,text:JSON.stringify({success:!0,artifactPath:c,hash:u,size:i.size,exports:i.exports,importModules:i.importMods,totalModules:i.moduleCount,hint:a?`Use wasm_disassemble or wasm_decompile on the dumped file for further analysis.`:`Binary not captured. Inject hook_preset("webassembly-full") BEFORE page navigation, with window.__wasmModuleStorage patching.`},null,2)}]}}async handleWasmVmpTrace(e){let t=l(e,`maxEvents`,5e3),n=s(e,`filterModule`),r=await(await this.state.collector.getActivePage()).evaluate(e=>{let t=window.__aiHooks?.[`preset-webassembly-full`];if(!Array.isArray(t)||t.length===0)return{error:`No WASM hook data. Inject hook_preset("webassembly-full") and reload the page.`};let n=t.filter(e=>e.type===`import_call`);e.filterModule&&(n=n.filter(t=>t.mod===e.filterModule));let r=n.slice(0,e.maxEvents),i={};for(let e of r){let t=`${String(e.mod)}.${String(e.fn)}`;i[t]=(i[t]||0)+1}let a=Object.entries(i).toSorted((e,t)=>t[1]-e[1]).slice(0,30).map(([e,t])=>({name:e,count:t}));return{totalEvents:n.length,capturedEvents:r.length,topFunctions:a,trace:r.slice(0,200).map(e=>({mod:e.mod,fn:e.fn,args:e.args,ts:e.ts}))}},{maxEvents:t,filterModule:n});return T(r)?{content:[{type:`text`,text:JSON.stringify({success:!1,error:r.error})}]}:{content:[{type:`text`,text:JSON.stringify({success:!0,...r,hint:`Top functions show VMP handler dispatch patterns. Use wasm_disassemble to analyze their implementation.`},null,2)}]}}async handleWasmMemoryInspect(e){let t=l(e,`offset`,0),n=Math.min(l(e,`length`,256),65536),r=s(e,`format`,`both`),i=s(e,`searchPattern`),a=await(await this.state.collector.getActivePage()).evaluate(e=>{let t=window,n=t.__aiHooks?.[`preset-webassembly-full`],r=(Array.isArray(n)?n:[]).filter(e=>e.type===`memory_created`),i=t.__wasmInstances;if(!Array.isArray(i)||i.length===0)return{error:`No WASM memory available. Ensure the webassembly-full hook is active and a WASM module is instantiated.`};try{let t=i[0].exports?.memory;if(!t?.buffer)return{error:`WASM module has no exported memory.`};let n=new Uint8Array(t.buffer),a=Array.from(n.slice(e.offset,e.offset+e.length)),o;if(e.searchPattern){o=[];let t=e.searchPattern;if(/^[0-9a-fA-F\s]+$/.test(t)){let r=t.replace(/\s/g,``).match(/.{2}/g)?.map(e=>parseInt(e,16))||[];for(let t=e.offset;t<=Math.min(e.offset+e.length-r.length,n.length-r.length);t++){let e=!0;for(let i=0;i<r.length;i++)if(n[t+i]!==r[i]){e=!1;break}e&&o.push({offset:t})}}else{let r=new TextEncoder().encode(t);for(let t=e.offset;t<=Math.min(e.offset+e.length-r.length,n.length-r.length);t++){let e=!0;for(let i=0;i<r.length;i++)if(n[t+i]!==r[i]){e=!1;break}e&&o.push({offset:t})}}}return{totalMemoryPages:t.buffer.byteLength/65536,totalMemoryBytes:t.buffer.byteLength,requestedOffset:e.offset,requestedLength:e.length,data:a,searchResults:o,memoryInfo:r[0]||null}}catch(e){return{error:`Failed to read WASM memory: ${e instanceof Error?e.message:String(e)}`}}},{offset:t,length:n,searchPattern:i});if(T(a))return{content:[{type:`text`,text:JSON.stringify({success:!1,error:a.error})}]};let o=a.data,c=``,u=``;if(r===`hex`||r===`both`)for(let e=0;e<o.length;e+=16){let n=o.slice(e,e+16),r=(t+e).toString(16).padStart(8,`0`),i=n.map(e=>e.toString(16).padStart(2,`0`)).join(` `),a=n.map(e=>e>=32&&e<127?String.fromCharCode(e):`.`).join(``);c+=`${r} ${i.padEnd(48)} |${a}|\n`}return r===`ascii`&&(u=o.map(e=>e>=32&&e<127?String.fromCharCode(e):`.`).join(``)),{content:[{type:`text`,text:JSON.stringify({success:!0,totalMemoryPages:a.totalMemoryPages,totalMemoryBytes:a.totalMemoryBytes,offset:t,length:o.length,hexDump:r===`ascii`?void 0:c,asciiDump:r===`ascii`?u:void 0,searchResults:a.searchResults},null,2)}]}}};function P(e,t,n,r,i,a,o){return{capability:e,status:n?`available`:`unavailable`,reason:r,fix:n?void 0:i,details:{tools:a,...o?.path?{path:o.path}:{},...o?.version?{version:o.version}:{},backend:t}}}var F=class{state;constructor(e){this.state=e}async handleWasmCapabilities(){let e=await this.state.runner.probeAll(),t=await this.getCurrentPageCapability(),n=e[`runtime.wasmtime`]?.available===!0||e[`runtime.wasmer`]?.available===!0;return m.raw(f(`wasm_capabilities`,[t,P(`wabt_wasm2wat`,`wabt.wasm2wat`,e[`wabt.wasm2wat`]?.available===!0,e[`wabt.wasm2wat`]?.reason,`Install WABT so wasm2wat is available on PATH.`,[`wasm_disassemble`],e[`wabt.wasm2wat`]),P(`wabt_wasm_decompile`,`wabt.wasm-decompile`,e[`wabt.wasm-decompile`]?.available===!0,e[`wabt.wasm-decompile`]?.reason,`Install WABT so wasm-decompile is available on PATH.`,[`wasm_decompile`],e[`wabt.wasm-decompile`]),P(`wabt_wasm_objdump`,`wabt.wasm-objdump`,e[`wabt.wasm-objdump`]?.available===!0,e[`wabt.wasm-objdump`]?.reason,`Install WABT so wasm-objdump is available on PATH.`,[`wasm_inspect_sections`],e[`wabt.wasm-objdump`]),P(`binaryen_wasm_opt`,`binaryen.wasm-opt`,e[`binaryen.wasm-opt`]?.available===!0,e[`binaryen.wasm-opt`]?.reason,`Install Binaryen so wasm-opt is available on PATH.`,[`wasm_optimize`],e[`binaryen.wasm-opt`]),{capability:`wasm_offline_runtime`,status:n?`available`:`unavailable`,reason:n?void 0:`No offline WASM runtime is available on PATH.`,fix:n?void 0:`Install wasmtime or wasmer to enable wasm_offline_run.`,details:{tools:[`wasm_offline_run`],runtimes:{wasmtime:e[`runtime.wasmtime`],wasmer:e[`runtime.wasmer`]},preferredRuntime:e[`runtime.wasmtime`]?.available?`runtime.wasmtime`:e[`runtime.wasmer`]?.available?`runtime.wasmer`:null}}]))}async getCurrentPageCapability(){let e;try{e=await this.state.collector.getActivePage()}catch(e){return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Attach or launch a browser page before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!1}}}if(!e)return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`No active page is attached.`,fix:`Attach or launch a browser page before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!1}};try{let t=await e.evaluate(()=>{let e=window,t=e.__aiHooks?.[`preset-webassembly-full`],n=Array.isArray(t)?t:[];return{url:location.href,hookEventCount:n.length,instantiatedCount:n.filter(e=>e.type===`instantiated`).length,importCallCount:n.filter(e=>e.type===`import_call`).length,memoryEventCount:n.filter(e=>e.type===`memory_created`).length,storageCount:Array.isArray(e.__wasmModuleStorage)?e.__wasmModuleStorage.length:0,instanceCount:Array.isArray(e.__wasmInstances)?e.__wasmInstances.length:0}}),n=t.instantiatedCount>0||t.memoryEventCount>0||t.storageCount>0||t.instanceCount>0;return{capability:`wasm_browser_capture_current_page`,status:n?`available`:`unavailable`,reason:n?void 0:`No captured WASM modules or exported memory are visible on the current page.`,fix:n?void 0:`Load a page that instantiates WASM. For dump/trace flows, inject hook_preset("webassembly-full") before navigation.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!0,...t}}}catch(e){return{capability:`wasm_browser_capture_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Ensure an attached page is still reachable before using browser-backed WASM tools.`,details:{tools:[`wasm_dump`,`wasm_vmp_trace`,`wasm_memory_inspect`],pageAttached:!0}}}}},I=class{state;externalTools;browser;capabilities;constructor(e){let t=new a(new p);this.state={collector:e,runner:t},this.externalTools=new M(this.state),this.browser=new N(this.state),this.capabilities=new F(this.state)}handleWasmCapabilities(){return this.capabilities.handleWasmCapabilities()}handleWasmDump(e){return this.browser.handleWasmDump(e)}handleWasmDisassemble(e){return this.externalTools.handleWasmDisassemble(e)}handleWasmDecompile(e){return this.externalTools.handleWasmDecompile(e)}handleWasmInspectSections(e){return this.externalTools.handleWasmInspectSections(e)}handleWasmOfflineRun(e){return this.externalTools.handleWasmOfflineRun(e)}handleWasmOptimize(e){return this.externalTools.handleWasmOptimize(e)}handleWasmVmpTrace(e){return this.browser.handleWasmVmpTrace(e)}handleWasmMemoryInspect(e){return this.browser.handleWasmMemoryInspect(e)}handleWasmToC(e){return this.externalTools.handleWasmToC(e)}handleWasmDetectObfuscation(e){return this.externalTools.handleWasmDetectObfuscation(e)}handleWasmInstrumentTrace(e){return this.externalTools.handleWasmInstrumentTrace(e)}};export{I as WasmToolHandlers};
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|