@jshookmcp/jshook 0.2.9 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -50
- package/README.zh.md +25 -48
- package/dist/AntiCheatDetector-CGVGNfy5.mjs +1 -0
- package/dist/CacheAdapters-CdAxBmVW.mjs +1 -0
- package/dist/CodeInjector-BlgyqTOk.mjs +1 -0
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +490 -0
- package/dist/DOMInspector-BYY_EJ0C.mjs +95 -0
- package/dist/DarwinAPI-DC4HGGLl.mjs +1 -0
- package/dist/DetailedDataManager-BniBJlVv.mjs +1 -0
- package/dist/EventBus-DgciURGg.mjs +1 -0
- package/dist/EvidenceGraphBridge-BIfgB7HP.mjs +1 -0
- package/dist/ExtensionManager-erMpqcLk.mjs +1 -0
- package/dist/FingerprintManager-N7BZqjxP.mjs +1 -0
- package/dist/HardwareBreakpoint-OcJqNFVc.mjs +1 -0
- package/dist/HeapAnalyzer-CqAxZzeS.mjs +1 -0
- package/dist/{HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs → HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs} +66 -174
- package/dist/InstrumentationSession-DxXs0sCp.mjs +1 -0
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +1 -0
- package/dist/MemoryController-BaqstM5w.mjs +2 -0
- package/dist/MemoryScanSession-CaxAjZJf.mjs +1 -0
- package/dist/MemoryScanner-BLYnMJy6.mjs +1 -0
- package/dist/NativeMemoryManager.impl-CI554XbY.mjs +1 -0
- package/dist/NativeMemoryManager.utils-DM4NC3FE.mjs +1 -0
- package/dist/PEAnalyzer-DJyaJTQJ.mjs +1 -0
- package/dist/PageController-D9jVkH0i.mjs +1 -0
- package/dist/PointerChainEngine-5nF9eNlu.mjs +1 -0
- package/dist/PrerequisiteError-Bl3dK8XA.mjs +1 -0
- package/dist/ProcessRegistry-Hf12LlR9.mjs +1 -0
- package/dist/ResponseBuilder-B2lu4KEl.mjs +1 -0
- package/dist/ReverseEvidenceGraph-B931HeoW.mjs +2 -0
- package/dist/ScriptManager-fgqiALgj.mjs +7 -0
- package/dist/Speedhack-l6s8L2Qw.mjs +1 -0
- package/dist/StealthVerifier-Dhbj4B4P.mjs +1 -0
- package/dist/StructureAnalyzer-A-WamfYE.mjs +2 -0
- package/dist/ToolCatalog-D_IKl1Hu.mjs +1 -0
- package/dist/ToolError-DWU_z7gp.mjs +1 -0
- package/dist/ToolProbe-xsfALmN3.mjs +1 -0
- package/dist/ToolRegistry-B0Zs-phN.mjs +1 -0
- package/dist/ToolRouter.policy-CFHoN_Lw.mjs +4 -0
- package/dist/TraceRecorder-Dd8jLXpi.mjs +272 -0
- package/dist/VersionDetector-DMoUWyNm.mjs +9 -0
- package/dist/Win32API-Bhi5xFBe.mjs +1 -0
- package/dist/Win32Debug-CQteFL4F.mjs +1 -0
- package/dist/WorkflowEngine-CxEp2WXH.mjs +1 -0
- package/dist/analysis-BuR-NgX8.mjs +5 -0
- package/dist/{antidebug-CqDTB_uk.mjs → antidebug-BOTZH6-0.mjs} +8 -259
- package/dist/artifactRetention-NBdncOEW.mjs +1 -0
- package/dist/artifacts-B5xQuEa_.mjs +1 -0
- package/dist/authorization-schema-B40obG1A.mjs +1 -0
- package/dist/betterSqlite3-CGaxz4AX.mjs +1 -0
- package/dist/binary-instrument-Cf9qqLlM.mjs +7 -0
- package/dist/bind-helpers-BlAOQrFQ.mjs +1 -0
- package/dist/boringssl-inspector-BST5vtKx.mjs +2 -0
- package/dist/browser-C4Le3xqA.mjs +11 -0
- package/dist/capabilities-DbYCv-HF.mjs +1 -0
- package/dist/chunk-C_pMuVsO.mjs +1 -0
- package/dist/collector-CKO8RPK8.mjs +1 -0
- package/dist/concurrency-CcK46d0h.mjs +1 -0
- package/dist/constants-Cp6hBrrx.mjs +1 -0
- package/dist/coordination-BbijHEHH.mjs +1 -0
- package/dist/debugger-CRJq_krh.mjs +1 -0
- package/dist/definitions-BGobEDQa.mjs +1 -0
- package/dist/definitions-BGwNSkVm.mjs +1 -0
- package/dist/definitions-BbxOUiP-.mjs +1 -0
- package/dist/definitions-CCP9gphV.mjs +1 -0
- package/dist/definitions-CIO9O-Sw.mjs +1 -0
- package/dist/definitions-CYFbewnd.mjs +1 -0
- package/dist/definitions-CdWEuIkI.mjs +1 -0
- package/dist/definitions-CoQFbggH.mjs +1 -0
- package/dist/definitions-CuJRsJ6N.mjs +1 -0
- package/dist/definitions-DI9YXsJk.mjs +1 -0
- package/dist/definitions-DJklW2sS.mjs +1 -0
- package/dist/definitions-DZ8uKusP.mjs +1 -0
- package/dist/definitions-Dds_zrWx.mjs +1 -0
- package/dist/definitions-Dgrg7f3D.mjs +1 -0
- package/dist/definitions-DtE0XLrT.mjs +1 -0
- package/dist/definitions-LaYTuwQd.mjs +26 -0
- package/dist/definitions-NoVp_9Pm.mjs +1 -0
- package/dist/definitions-OvGsfxdt.mjs +1 -0
- package/dist/definitions-jXPaVy4P.mjs +1 -0
- package/dist/encoding-DGcr6Aj_.mjs +2 -0
- package/dist/ensure-browser-core-Buls24LQ.mjs +1 -0
- package/dist/evidence-graph-bridge-B0yhGPcs.mjs +1 -0
- package/dist/factory-Cx_1LorX.mjs +1 -0
- package/dist/flat-target-session-CO5g78k3.mjs +1 -0
- package/dist/formatAddress-C7j2fDlM.mjs +1 -0
- package/dist/graphql-HLf3MS8H.mjs +62 -0
- package/dist/handlers-BLMa4X7l.mjs +54 -0
- package/dist/handlers-BP12ZsWc.mjs +4 -0
- package/dist/handlers-BZoPla6E.mjs +1 -0
- package/dist/handlers-BggKiVx9.mjs +2 -0
- package/dist/handlers-D3iev8g1.mjs +1 -0
- package/dist/handlers-D49r1-1P.mjs +1 -0
- package/dist/handlers-DCE45Ww8.mjs +2 -0
- package/dist/handlers-DW5AbYs5.mjs +5 -0
- package/dist/handlers-De5u62Ga2.mjs +1 -0
- package/dist/handlers-DmQzIc44.mjs +31 -0
- package/dist/handlers-DnJRGp7t.mjs +302 -0
- package/dist/handlers-Dv_runVv.mjs +2 -0
- package/dist/handlers-S9Ws0IGy.mjs +2 -0
- package/dist/{handlers-Bl8zkwz1.mjs → handlers-pVNpaw4A.mjs} +144 -841
- package/dist/handlers.impl-CD2_kOcC.mjs +1 -0
- package/dist/hooks-DDKppogd.mjs +600 -0
- package/dist/index.mjs +12 -5225
- package/dist/logger-sBC6IdRT.mjs +1 -0
- package/dist/maintenance-CutEO84j.mjs +1 -0
- package/dist/manifest-BFGxlDRh.mjs +123 -0
- package/dist/manifest-BPuE6oH2.mjs +1 -0
- package/dist/manifest-BXry5N09.mjs +1 -0
- package/dist/manifest-BeP_zJGb2.mjs +1 -0
- package/dist/manifest-C0g67k6U.mjs +1 -0
- package/dist/manifest-C1nZkTkO.mjs +1 -0
- package/dist/manifest-C7qV1z7F.mjs +1 -0
- package/dist/manifest-CDeUZGUZ.mjs +1 -0
- package/dist/manifest-CDiCtaQT.mjs +1 -0
- package/dist/manifest-CFn0359q2.mjs +1 -0
- package/dist/manifest-CGq4NpqH2.mjs +1 -0
- package/dist/manifest-CJMGt7Qy.mjs +1 -0
- package/dist/manifest-CRIJq4Hs.mjs +1 -0
- package/dist/manifest-C_hEIjSx.mjs +1 -0
- package/dist/manifest-CeQmtQOY.mjs +1 -0
- package/dist/manifest-Cq0j7GZt.mjs +1 -0
- package/dist/manifest-CtPmHAdn.mjs +1 -0
- package/dist/manifest-Cx2IVMUY.mjs +1 -0
- package/dist/manifest-D16xPXro.mjs +1 -0
- package/dist/manifest-D44TaRJU.mjs +1 -0
- package/dist/manifest-D610kxZr.mjs +2 -0
- package/dist/manifest-DC-SMF6b.mjs +1 -0
- package/dist/manifest-DD3rtxvV.mjs +1 -0
- package/dist/manifest-DKUorv5M.mjs +1 -0
- package/dist/manifest-DMJlcsTR.mjs +1 -0
- package/dist/manifest-DWUUWBz0.mjs +1 -0
- package/dist/manifest-De-6Wf2R.mjs +1 -0
- package/dist/manifest-Dgh0uDW-.mjs +1 -0
- package/dist/manifest-Dm0o3i2U.mjs +1 -0
- package/dist/manifest-DsVh7Y4U.mjs +1 -0
- package/dist/manifest-DtEFSRaq.mjs +1 -0
- package/dist/manifest-H-EpAyZQ.mjs +1 -0
- package/dist/manifest-ais9Afrw.mjs +1 -0
- package/dist/manifest-tmb54wmA.mjs +1 -0
- package/dist/manifest-yu2xiQqe.mjs +1 -0
- package/dist/manifest-zrbrpKCC.mjs +1 -0
- package/dist/matchesWildcardPattern-BGqLSmEs.mjs +1 -0
- package/dist/modules-p-PUNv9r.mjs +332 -0
- package/dist/mojo-ipc-VGlv3Qyp.mjs +9 -0
- package/dist/network-BjZ1Y-GB.mjs +7 -0
- package/dist/outputPaths-BonGThuc.mjs +2 -0
- package/dist/parse-args-Cuk7-xUt.mjs +1 -0
- package/dist/platform-C446Lf97.mjs +93 -0
- package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +1 -0
- package/dist/process-C9f2A5zk.mjs +962 -0
- package/dist/proxy-CvRepxgV.mjs +1 -0
- package/dist/registry-DUHIPE-v.mjs +1 -0
- package/dist/response-C7rKQst4.mjs +1 -0
- package/dist/search-defaults-D2bY-rzH.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -293
- package/dist/shared-state-board-Cyg-xh_k.mjs +1 -0
- package/dist/sourcemap-D6Q1UuAp.mjs +1 -0
- package/dist/ssrf-policy-T96MR3r6.mjs +1 -0
- package/dist/streaming-CTX58tbb.mjs +1 -0
- package/dist/tool-builder-CI9914Tf.mjs +1 -0
- package/dist/transform-Cv9P2vVD.mjs +103 -0
- package/dist/types-CuyefmGT.mjs +1 -0
- package/dist/types-DtThH00r.mjs +1 -0
- package/dist/wasm-DaJa8J0V.mjs +174 -0
- package/dist/webcrack-CsLLJIs9.mjs +46 -0
- package/dist/workflow-CYIXtrWD.mjs +101 -0
- package/package.json +12 -7
- package/dist/AntiCheatDetector-BNk-EoBt.mjs +0 -244
- package/dist/CacheAdapters-CDe5WPSV.mjs +0 -80
- package/dist/CodeInjector-Cq8q01kp.mjs +0 -150
- package/dist/ConsoleMonitor-CPVQW1Y-.mjs +0 -2201
- package/dist/DarwinAPI-BNPxu0RH.mjs +0 -363
- package/dist/DetailedDataManager-BQQcxh64.mjs +0 -217
- package/dist/EventBus-DgPmwpeu.mjs +0 -141
- package/dist/EvidenceGraphBridge-SFesNera.mjs +0 -153
- package/dist/ExtensionManager-CWYgw0YW.mjs +0 -714
- package/dist/FingerprintManager-gzWtkKuf.mjs +0 -96
- package/dist/HardwareBreakpoint-B9gZCdFP.mjs +0 -239
- package/dist/HeapAnalyzer-BLDH0dCv.mjs +0 -284
- package/dist/InstrumentationSession-CvPC7Jwy.mjs +0 -244
- package/dist/MemoryController-CbVdCIJF.mjs +0 -167
- package/dist/MemoryScanSession-BsDZbLYm.mjs +0 -278
- package/dist/MemoryScanner-Bcpml6II.mjs +0 -425
- package/dist/NativeMemoryManager.impl-dZtA1ZGn.mjs +0 -482
- package/dist/NativeMemoryManager.utils-B-FjA2mJ.mjs +0 -165
- package/dist/PEAnalyzer-D1lzJ_VG.mjs +0 -385
- package/dist/PageController-Bqm2kZ_X.mjs +0 -417
- package/dist/PointerChainEngine-BOhyVsjx.mjs +0 -322
- package/dist/PrerequisiteError-Dl33Svkz.mjs +0 -20
- package/dist/ResponseBuilder-D3iFYx2N.mjs +0 -143
- package/dist/ReverseEvidenceGraph-Dlsk94LC.mjs +0 -269
- package/dist/ScriptManager-aHHq0X7U.mjs +0 -3000
- package/dist/Speedhack-CqdIFlQl.mjs +0 -156
- package/dist/StealthVerifier-Bo4T3bz8.mjs +0 -135
- package/dist/StructureAnalyzer-DhFaPvRO.mjs +0 -426
- package/dist/ToolCatalog-C0JGZoOm.mjs +0 -582
- package/dist/ToolError-jh9whhMd.mjs +0 -15
- package/dist/ToolProbe-oC7aPrkv.mjs +0 -45
- package/dist/ToolRegistry-BjaF4oNz.mjs +0 -131
- package/dist/ToolRouter.policy-BWV67ZK-.mjs +0 -304
- package/dist/TraceRecorder-DgxyVbdQ.mjs +0 -519
- package/dist/VersionDetector-CwVLVdDM.mjs +0 -104
- package/dist/Win32API-CePkipZY.mjs +0 -340
- package/dist/Win32Debug-BvKs-gxc.mjs +0 -274
- package/dist/WorkflowEngine-CuvkZtWu.mjs +0 -598
- package/dist/analysis-CL9uACt9.mjs +0 -463
- package/dist/artifactRetention-CFEprwPw.mjs +0 -591
- package/dist/artifacts-Bk2-_uPq.mjs +0 -59
- package/dist/betterSqlite3-0pqusHHH.mjs +0 -74
- package/dist/binary-instrument-CXfpx6fT.mjs +0 -979
- package/dist/bind-helpers-xFfRF-qm.mjs +0 -22
- package/dist/boringssl-inspector-BH2D3VKc.mjs +0 -180
- package/dist/browser-BpOr5PEx.mjs +0 -4082
- package/dist/chunk-CjcI7cDX.mjs +0 -15
- package/dist/concurrency-Bt0yv1kJ.mjs +0 -41
- package/dist/constants-B0OANIBL.mjs +0 -519
- package/dist/coordination-qUbyF8KU.mjs +0 -259
- package/dist/debugger-gnKxRSN0.mjs +0 -1271
- package/dist/definitions-6M-eejaT.mjs +0 -53
- package/dist/definitions-B18eyf0B.mjs +0 -18
- package/dist/definitions-B3QdlrHv.mjs +0 -34
- package/dist/definitions-B4rAvHNZ.mjs +0 -63
- package/dist/definitions-BB_4jnmy.mjs +0 -37
- package/dist/definitions-BMfYXoNC.mjs +0 -43
- package/dist/definitions-Beid2EB3.mjs +0 -27
- package/dist/definitions-C1UvM5Iy.mjs +0 -126
- package/dist/definitions-CXEI7QC72.mjs +0 -216
- package/dist/definitions-C_4r7Fo-2.mjs +0 -14
- package/dist/definitions-CkFDALoa.mjs +0 -26
- package/dist/definitions-Cke7zEb8.mjs +0 -94
- package/dist/definitions-ClJLzsJQ.mjs +0 -25
- package/dist/definitions-Cq-zroAU.mjs +0 -28
- package/dist/definitions-Cy3Sl6gV.mjs +0 -34
- package/dist/definitions-D3VsGcvz.mjs +0 -47
- package/dist/definitions-DVGfrn7y.mjs +0 -96
- package/dist/definitions-LKpC3-nL.mjs +0 -9
- package/dist/definitions-bAhHQJq9.mjs +0 -359
- package/dist/encoding-Bvz5jLRv.mjs +0 -1065
- package/dist/evidence-graph-bridge-C_fv9PuC.mjs +0 -135
- package/dist/factory-DxlGh9Xf.mjs +0 -575
- package/dist/formatAddress-DVkj9kpI.mjs +0 -17
- package/dist/graphql-DYWzJ29s.mjs +0 -1026
- package/dist/handlers-9sAbfIg-.mjs +0 -2552
- package/dist/handlers-C67ktuRN.mjs +0 -710
- package/dist/handlers-C87g8oCe.mjs +0 -276
- package/dist/handlers-CTsDAO6p.mjs +0 -681
- package/dist/handlers-Cgyg6c0U.mjs +0 -645
- package/dist/handlers-D6j6yka7.mjs +0 -2124
- package/dist/handlers-DdFzXLvF.mjs +0 -446
- package/dist/handlers-DeLOCd5m.mjs +0 -799
- package/dist/handlers-DlCJN4Td.mjs +0 -757
- package/dist/handlers-DxGIq15_2.mjs +0 -917
- package/dist/handlers-U6L4xhuF.mjs +0 -585
- package/dist/handlers-tB9Mp9ZK.mjs +0 -84
- package/dist/handlers-tiy7EIBp.mjs +0 -572
- package/dist/handlers.impl-DS0d9fUw.mjs +0 -761
- package/dist/hooks-CzCWByww.mjs +0 -898
- package/dist/logger-Dh_xb7_2.mjs +0 -93
- package/dist/maintenance-P7ePRXQC.mjs +0 -830
- package/dist/manifest-2ToTpjv8.mjs +0 -106
- package/dist/manifest-3g71z6Bg.mjs +0 -79
- package/dist/manifest-82baTv4U.mjs +0 -45
- package/dist/manifest-B3QVVeBS.mjs +0 -82
- package/dist/manifest-BB2J8IMJ.mjs +0 -149
- package/dist/manifest-BKbgbSiY.mjs +0 -60
- package/dist/manifest-Bcf-TJzH.mjs +0 -848
- package/dist/manifest-BmtZzQiQ2.mjs +0 -45
- package/dist/manifest-Bnd7kqEY.mjs +0 -55
- package/dist/manifest-BqQX6OQC2.mjs +0 -65
- package/dist/manifest-BqrQ4Tpj.mjs +0 -81
- package/dist/manifest-Br4RPFt5.mjs +0 -370
- package/dist/manifest-C5qDjysN.mjs +0 -107
- package/dist/manifest-C9RT5nk32.mjs +0 -34
- package/dist/manifest-CAhOuvSl.mjs +0 -204
- package/dist/manifest-CBYWCUBJ.mjs +0 -51
- package/dist/manifest-CFADCRa1.mjs +0 -37
- package/dist/manifest-CQVhavRF.mjs +0 -114
- package/dist/manifest-CT7zZBV1.mjs +0 -48
- package/dist/manifest-CV12bcrF.mjs +0 -121
- package/dist/manifest-CXsRWjjI.mjs +0 -224
- package/dist/manifest-CZLUCfG02.mjs +0 -95
- package/dist/manifest-D6phHKFd.mjs +0 -131
- package/dist/manifest-DCyjf4n2.mjs +0 -294
- package/dist/manifest-DHsnKgP6.mjs +0 -60
- package/dist/manifest-Df_dliIe.mjs +0 -55
- package/dist/manifest-Dh8WBmEW.mjs +0 -129
- package/dist/manifest-DhKRAT8_.mjs +0 -92
- package/dist/manifest-DlpTj4ic2.mjs +0 -193
- package/dist/manifest-DrbmZcFl2.mjs +0 -253
- package/dist/manifest-DuwHjUa5.mjs +0 -70
- package/dist/manifest-DzwvxPJX.mjs +0 -38
- package/dist/manifest-NXctwWQq.mjs +0 -68
- package/dist/manifest-Sc_0JQ13.mjs +0 -418
- package/dist/manifest-gZ4s_UtG.mjs +0 -96
- package/dist/manifest-qSleDqdO.mjs +0 -1023
- package/dist/modules-C184v-S9.mjs +0 -11365
- package/dist/mojo-ipc-B_H61Afw.mjs +0 -525
- package/dist/network-671Cw6hV.mjs +0 -3346
- package/dist/outputPaths-B1uGmrWZ.mjs +0 -1145
- package/dist/parse-args-BlRjqlkL.mjs +0 -39
- package/dist/platform-WmNn8Sxb.mjs +0 -2070
- package/dist/process-QcbIy5Zq.mjs +0 -1401
- package/dist/proxy-DqNs0bAd.mjs +0 -170
- package/dist/registry-D-6e18lB.mjs +0 -34
- package/dist/response-BQVP-xUn.mjs +0 -28
- package/dist/shared-state-board-DV-dpHFJ.mjs +0 -586
- package/dist/sourcemap-Dq8ez8vS.mjs +0 -650
- package/dist/ssrf-policy-ZaUfvhq7.mjs +0 -166
- package/dist/streaming-BUQ0VJsg.mjs +0 -725
- package/dist/tool-builder-DCbIC5Eo.mjs +0 -186
- package/dist/transform-CiYJfNX0.mjs +0 -1007
- package/dist/types-Bx92KJfT.mjs +0 -4
- package/dist/types-CPhOReNX.mjs +0 -37
- package/dist/wasm-DQTnHDs4.mjs +0 -531
- package/dist/workflow-f3xJOcjx.mjs +0 -725
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{G as n,K as r,P as i,Rr as a,X as o,q as s}from"./constants-Cp6hBrrx.mjs";import{t as c}from"./ProcessRegistry-Hf12LlR9.mjs";import{a as l,c as u,i as d,n as f,o as p,r as m,s as h,t as g}from"./HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs";import{i as _,n as v}from"./outputPaths-BonGThuc.mjs";import{i as y}from"./artifacts-B5xQuEa_.mjs";import{t as b}from"./PrerequisiteError-Bl3dK8XA.mjs";import{r as x,t as S}from"./concurrency-CcK46d0h.mjs";import{a as ee,i as te,n as ne,r as re,s as C}from"./PageController-D9jVkH0i.mjs";import"./ScriptManager-fgqiALgj.mjs";import{n as ie,t as w}from"./webcrack-CsLLJIs9.mjs";import"./ToolRegistry-B0Zs-phN.mjs";import*as T from"path";import{join as ae}from"path";import E from"crypto";import{tmpdir as oe}from"node:os";import{isAbsolute as se,relative as ce,resolve as D,sep as le}from"node:path";import{writeFile as O}from"node:fs/promises";import{spawn as ue}from"node:child_process";import"rebrowser-puppeteer-core";import*as k from"fs/promises";import{mkdir as de,writeFile as fe}from"fs/promises";import*as pe from"os";import{setImmediate as me}from"node:timers/promises";import*as A from"@babel/parser";import j from"@babel/traverse";import*as M from"@babel/types";import"@babel/generator";function he(e,t,n,r=!1){return`
|
|
2
|
+
(function() {
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const XHR = XMLHttpRequest.prototype;
|
|
6
|
+
const originalOpen = XHR.open;
|
|
7
|
+
const originalSend = XHR.send;
|
|
8
|
+
const originalSetRequestHeader = XHR.setRequestHeader;
|
|
9
|
+
|
|
10
|
+
XHR.open = function(method, url, async, user, password) {
|
|
11
|
+
this._hookData = {
|
|
12
|
+
method: method,
|
|
13
|
+
url: url,
|
|
14
|
+
async: async !== false,
|
|
15
|
+
timestamp: Date.now(),
|
|
16
|
+
headers: {},
|
|
17
|
+
stackTrace: new Error().stack
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
console.log('[XHR Hook] open:', {
|
|
21
|
+
method: method,
|
|
22
|
+
url: url,
|
|
23
|
+
async: async !== false
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
${e===`block`?`return;`:``}
|
|
27
|
+
|
|
28
|
+
return originalOpen.apply(this, arguments);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
XHR.setRequestHeader = function(header, value) {
|
|
32
|
+
if (this._hookData) {
|
|
33
|
+
this._hookData.headers[header] = value;
|
|
34
|
+
console.log('[XHR Hook] setRequestHeader:', { header, value });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return originalSetRequestHeader.apply(this, arguments);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
XHR.send = function(data) {
|
|
41
|
+
const xhr = this;
|
|
42
|
+
|
|
43
|
+
if (xhr._hookData) {
|
|
44
|
+
xhr._hookData.requestData = data;
|
|
45
|
+
xhr._hookData.sendTime = Date.now();
|
|
46
|
+
|
|
47
|
+
console.log('[XHR Hook] send:', {
|
|
48
|
+
url: xhr._hookData.url,
|
|
49
|
+
method: xhr._hookData.method,
|
|
50
|
+
headers: xhr._hookData.headers,
|
|
51
|
+
data: data
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const originalOnReadyStateChange = xhr.onreadystatechange;
|
|
56
|
+
|
|
57
|
+
xhr.onreadystatechange = function() {
|
|
58
|
+
if (xhr.readyState === 4) {
|
|
59
|
+
const responseTime = Date.now() - (xhr._hookData?.sendTime || 0);
|
|
60
|
+
|
|
61
|
+
console.log('[XHR Hook] response:', {
|
|
62
|
+
url: xhr._hookData?.url,
|
|
63
|
+
status: xhr.status,
|
|
64
|
+
statusText: xhr.statusText,
|
|
65
|
+
responseTime: responseTime + 'ms',
|
|
66
|
+
responseHeaders: xhr.getAllResponseHeaders(),
|
|
67
|
+
responseType: xhr.responseType,
|
|
68
|
+
responseURL: xhr.responseURL
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
if (xhr.responseType === '' || xhr.responseType === 'text') {
|
|
73
|
+
console.log('[XHR Hook] responseText:', xhr.responseText?.substring(0, 500));
|
|
74
|
+
} else if (xhr.responseType === 'json') {
|
|
75
|
+
console.log('[XHR Hook] responseJSON:', xhr.response);
|
|
76
|
+
} else {
|
|
77
|
+
console.log('[XHR Hook] response:', typeof xhr.response);
|
|
78
|
+
}
|
|
79
|
+
} catch (e) {
|
|
80
|
+
console.warn('[XHR Hook] Failed to log response:', e);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (originalOnReadyStateChange) {
|
|
85
|
+
return originalOnReadyStateChange.apply(this, arguments);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const originalAddEventListener = xhr.addEventListener;
|
|
90
|
+
xhr.addEventListener = function(event, listener, ...args) {
|
|
91
|
+
if (event === 'load' || event === 'error' || event === 'abort') {
|
|
92
|
+
const wrappedListener = function(e) {
|
|
93
|
+
console.log(\`[XHR Hook] event '\${event}':\`, {
|
|
94
|
+
url: xhr._hookData?.url,
|
|
95
|
+
status: xhr.status
|
|
96
|
+
});
|
|
97
|
+
return listener.apply(this, arguments);
|
|
98
|
+
};
|
|
99
|
+
return originalAddEventListener.call(this, event, wrappedListener, ...args);
|
|
100
|
+
}
|
|
101
|
+
return originalAddEventListener.apply(this, arguments);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
${t||``}
|
|
105
|
+
|
|
106
|
+
return originalSend.apply(this, arguments);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
console.log('[Hook] XHR hooked successfully');
|
|
110
|
+
})();
|
|
111
|
+
`.trim()}function ge(e,t,n,r=!1){return`
|
|
112
|
+
(function() {
|
|
113
|
+
'use strict';
|
|
114
|
+
|
|
115
|
+
const originalFetch = window.fetch;
|
|
116
|
+
|
|
117
|
+
window.fetch = new Proxy(originalFetch, {
|
|
118
|
+
apply: function(target, thisArg, args) {
|
|
119
|
+
const [resource, config] = args;
|
|
120
|
+
|
|
121
|
+
let url, method, headers, body;
|
|
122
|
+
|
|
123
|
+
if (resource instanceof Request) {
|
|
124
|
+
url = resource.url;
|
|
125
|
+
method = resource.method;
|
|
126
|
+
headers = Object.fromEntries(resource.headers.entries());
|
|
127
|
+
body = resource.body;
|
|
128
|
+
} else {
|
|
129
|
+
url = resource;
|
|
130
|
+
method = config?.method || 'GET';
|
|
131
|
+
headers = config?.headers || {};
|
|
132
|
+
body = config?.body;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const hookContext = {
|
|
136
|
+
url: url,
|
|
137
|
+
method: method,
|
|
138
|
+
headers: headers,
|
|
139
|
+
body: body,
|
|
140
|
+
timestamp: Date.now(),
|
|
141
|
+
stackTrace: new Error().stack.split('\\n').slice(2, 5).join('\\n')
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
console.log('[Fetch Hook] request:', hookContext);
|
|
145
|
+
|
|
146
|
+
${e===`block`?`return Promise.reject(new Error("Fetch blocked by hook"));`:``}
|
|
147
|
+
${t||``}
|
|
148
|
+
|
|
149
|
+
const startTime = performance.now();
|
|
150
|
+
|
|
151
|
+
return Reflect.apply(target, thisArg, args)
|
|
152
|
+
.then(async response => {
|
|
153
|
+
const endTime = performance.now();
|
|
154
|
+
const duration = (endTime - startTime).toFixed(2);
|
|
155
|
+
|
|
156
|
+
const clonedResponse = response.clone();
|
|
157
|
+
|
|
158
|
+
const responseInfo = {
|
|
159
|
+
url: url,
|
|
160
|
+
status: response.status,
|
|
161
|
+
statusText: response.statusText,
|
|
162
|
+
ok: response.ok,
|
|
163
|
+
redirected: response.redirected,
|
|
164
|
+
type: response.type,
|
|
165
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
166
|
+
duration: duration + 'ms'
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
console.log('[Fetch Hook] response:', responseInfo);
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
const contentType = response.headers.get('content-type') || '';
|
|
173
|
+
|
|
174
|
+
if (contentType.includes('application/json')) {
|
|
175
|
+
const json = await clonedResponse.json();
|
|
176
|
+
console.log('[Fetch Hook] responseJSON:', json);
|
|
177
|
+
} else if (contentType.includes('text/')) {
|
|
178
|
+
const text = await clonedResponse.text();
|
|
179
|
+
console.log('[Fetch Hook] responseText:', text.substring(0, 500));
|
|
180
|
+
} else {
|
|
181
|
+
console.log('[Fetch Hook] response type:', contentType);
|
|
182
|
+
}
|
|
183
|
+
} catch (e) {
|
|
184
|
+
console.warn('[Fetch Hook] Failed to parse response:', e.message);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return response;
|
|
188
|
+
})
|
|
189
|
+
.catch(error => {
|
|
190
|
+
const endTime = performance.now();
|
|
191
|
+
const duration = (endTime - startTime).toFixed(2);
|
|
192
|
+
|
|
193
|
+
console.error('[Fetch Hook] error:', {
|
|
194
|
+
url: url,
|
|
195
|
+
error: error.message,
|
|
196
|
+
duration: duration + 'ms'
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
throw error;
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
console.log('[Fetch Hook] Successfully hooked window.fetch');
|
|
205
|
+
})();
|
|
206
|
+
`.trim()}function _e(e,t,n,r=!1){return`
|
|
207
|
+
(function() {
|
|
208
|
+
'use strict';
|
|
209
|
+
|
|
210
|
+
const OriginalWebSocket = window.WebSocket;
|
|
211
|
+
let wsCounter = 0;
|
|
212
|
+
|
|
213
|
+
window.WebSocket = function(url, protocols) {
|
|
214
|
+
const wsId = ++wsCounter;
|
|
215
|
+
const connectTime = Date.now();
|
|
216
|
+
|
|
217
|
+
console.log(\`[WebSocket Hook #\${wsId}] connecting:\`, {
|
|
218
|
+
url: url,
|
|
219
|
+
protocols: protocols,
|
|
220
|
+
timestamp: new Date().toISOString()
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
${e===`block`?`throw new Error("WebSocket blocked by hook");`:``}
|
|
224
|
+
|
|
225
|
+
const ws = new OriginalWebSocket(url, protocols);
|
|
226
|
+
|
|
227
|
+
const originalSend = ws.send;
|
|
228
|
+
ws.send = function(data) {
|
|
229
|
+
const dataInfo = {
|
|
230
|
+
wsId: wsId,
|
|
231
|
+
url: url,
|
|
232
|
+
timestamp: new Date().toISOString(),
|
|
233
|
+
dataType: typeof data,
|
|
234
|
+
size: data?.length || data?.byteLength || data?.size || 0
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
if (typeof data === 'string') {
|
|
238
|
+
dataInfo.content = data.length > 500 ? data.substring(0, 500) + '...' : data;
|
|
239
|
+
} else if (data instanceof ArrayBuffer) {
|
|
240
|
+
dataInfo.content = \`ArrayBuffer(\${data.byteLength} bytes)\`;
|
|
241
|
+
} else if (data instanceof Blob) {
|
|
242
|
+
dataInfo.content = \`Blob(\${data.size} bytes, \${data.type})\`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
console.log(\`[WebSocket Hook #\${wsId}] send:\`, dataInfo);
|
|
246
|
+
|
|
247
|
+
${t||``}
|
|
248
|
+
|
|
249
|
+
return originalSend.apply(this, arguments);
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
ws.addEventListener('open', function(event) {
|
|
253
|
+
const duration = Date.now() - connectTime;
|
|
254
|
+
console.log(\`[WebSocket Hook #\${wsId}] open:\`, {
|
|
255
|
+
url: url,
|
|
256
|
+
readyState: ws.readyState,
|
|
257
|
+
protocol: ws.protocol,
|
|
258
|
+
extensions: ws.extensions,
|
|
259
|
+
duration: duration + 'ms'
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
ws.addEventListener('message', function(event) {
|
|
264
|
+
const messageInfo = {
|
|
265
|
+
wsId: wsId,
|
|
266
|
+
url: url,
|
|
267
|
+
timestamp: new Date().toISOString(),
|
|
268
|
+
dataType: typeof event.data
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
if (typeof event.data === 'string') {
|
|
272
|
+
messageInfo.content = event.data.length > 500 ? event.data.substring(0, 500) + '...' : event.data;
|
|
273
|
+
} else if (event.data instanceof ArrayBuffer) {
|
|
274
|
+
messageInfo.content = \`ArrayBuffer(\${event.data.byteLength} bytes)\`;
|
|
275
|
+
} else if (event.data instanceof Blob) {
|
|
276
|
+
messageInfo.content = \`Blob(\${event.data.size} bytes, \${event.data.type})\`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
console.log(\`[WebSocket Hook #\${wsId}] message:\`, messageInfo);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
ws.addEventListener('error', function(event) {
|
|
283
|
+
console.error(\`[WebSocket Hook #\${wsId}] error:\`, {
|
|
284
|
+
url: url,
|
|
285
|
+
readyState: ws.readyState,
|
|
286
|
+
timestamp: new Date().toISOString()
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
ws.addEventListener('close', function(event) {
|
|
291
|
+
const duration = Date.now() - connectTime;
|
|
292
|
+
console.log(\`[WebSocket Hook #\${wsId}] close:\`, {
|
|
293
|
+
url: url,
|
|
294
|
+
code: event.code,
|
|
295
|
+
reason: event.reason,
|
|
296
|
+
wasClean: event.wasClean,
|
|
297
|
+
duration: duration + 'ms',
|
|
298
|
+
timestamp: new Date().toISOString()
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
return ws;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
window.WebSocket.CONNECTING = OriginalWebSocket.CONNECTING;
|
|
306
|
+
window.WebSocket.OPEN = OriginalWebSocket.OPEN;
|
|
307
|
+
window.WebSocket.CLOSING = OriginalWebSocket.CLOSING;
|
|
308
|
+
window.WebSocket.CLOSED = OriginalWebSocket.CLOSED;
|
|
309
|
+
|
|
310
|
+
console.log('[WebSocket Hook] Successfully hooked window.WebSocket');
|
|
311
|
+
})();
|
|
312
|
+
`.trim()}function N(e){return`
|
|
313
|
+
|
|
314
|
+
${e.map(e=>e.script).join(`
|
|
315
|
+
|
|
316
|
+
`)}
|
|
317
|
+
|
|
318
|
+
console.log('[Hook Chain] All ${e.length} hooks initialized');
|
|
319
|
+
`.trim()}function P(e){let t=[],n=e;for(;M.isMemberExpression(n);)M.isIdentifier(n.property)&&t.unshift(n.property.name),n=n.object;return M.isIdentifier(n)&&t.unshift(n.name),t.join(`.`)}function F(e,t){let{callee:n}=e;if(M.isIdentifier(n))return t.has(n.name);if(M.isMemberExpression(n)){let e=P(n);return t.has(e)}return!1}function I(e,n){let r=[];Array.isArray(n.securityRisks)&&n.securityRisks.forEach(e=>{if(typeof e==`object`&&e){let t=e;r.push({type:t.type||`other`,severity:t.severity||`low`,location:{file:`current`,line:t.location?.line||0},description:t.description||``,recommendation:t.recommendation||``})}});try{j(A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),{AssignmentExpression(e){let t=e.node.left,n=e.node.loc?.start.line||0;if(M.isMemberExpression(t)&&M.isIdentifier(t.property)){let e=t.property.name;[`innerHTML`,`outerHTML`,`insertAdjacentHTML`].includes(e)&&r.push({type:`xss`,severity:`high`,location:{file:`current`,line:n},description:`Potential XSS vulnerability: Direct assignment to ${e} without sanitization`,recommendation:`Use textContent for plain text, or DOMPurify.sanitize() for HTML content`}),e===`write`&&M.isIdentifier(t.object)&&t.object.name===`document`&&r.push({type:`xss`,severity:`high`,location:{file:`current`,line:n},description:`Dangerous use of document.write() which can lead to XSS`,recommendation:`Use modern DOM manipulation methods instead`})}},CallExpression(e){let t=e.node.callee,n=e.node.loc?.start.line||0;if(M.isIdentifier(t)&&(t.name===`eval`&&r.push({type:`other`,severity:`critical`,location:{file:`current`,line:n},description:`Critical: Use of eval() allows arbitrary code execution`,recommendation:`Refactor to avoid eval(). Use JSON.parse() for data, or proper function calls`}),t.name===`Function`&&r.push({type:`other`,severity:`critical`,location:{file:`current`,line:n},description:`Critical: Function constructor allows code injection`,recommendation:`Use regular function declarations or arrow functions`}),[`setTimeout`,`setInterval`].includes(t.name))){let i=e.node.arguments[0];(M.isStringLiteral(i)||M.isIdentifier(i)&&i.name!==`function`)&&r.push({type:`other`,severity:`medium`,location:{file:`current`,line:n},description:`${t.name}() with string argument can lead to code injection`,recommendation:`Use ${t.name}() with function reference instead of string`})}if(M.isMemberExpression(t)&&M.isIdentifier(t.property)){let i=t.property.name;if([`query`,`execute`,`exec`,`run`].includes(i)){let t=e.node.arguments[0];(M.isBinaryExpression(t)||M.isTemplateLiteral(t))&&r.push({type:`sql-injection`,severity:`critical`,location:{file:`current`,line:n},description:`Potential SQL injection: Query built with string concatenation`,recommendation:`Use parameterized queries or prepared statements`})}}},MemberExpression(e){let t=e.node.object,n=e.node.property,i=e.node.loc?.start.line||0;if(M.isIdentifier(t)&&t.name===`Math`&&M.isIdentifier(n)&&n.name===`random`){let t=e.parent;(M.isCallExpression(t)||M.isBinaryExpression(t))&&r.push({type:`other`,severity:`medium`,location:{file:`current`,line:i},description:`Math.random() is not cryptographically secure`,recommendation:`Use crypto.getRandomValues() or crypto.randomBytes() for security-sensitive operations`})}},VariableDeclarator(e){let t=e.node.id,n=e.node.init,i=e.node.loc?.start.line||0;if(M.isIdentifier(t)&&M.isStringLiteral(n)){let e=t.name.toLowerCase(),a=n.value;for(let{pattern:t,type:n}of[{pattern:/(password|passwd|pwd)/i,type:`password`},{pattern:/(api[_-]?key|apikey)/i,type:`API key`},{pattern:/(secret|token|auth)/i,type:`secret`},{pattern:/(private[_-]?key|privatekey)/i,type:`private key`}])if(t.test(e)&&a.length>8){r.push({type:`other`,severity:`critical`,location:{file:`current`,line:i},description:`Hardcoded ${n} detected in source code`,recommendation:`Store ${n} in environment variables or secure configuration`});break}}}})}catch(e){t.warn(`Static security analysis failed`,e)}return r.filter((e,t,n)=>t===n.findIndex(t=>t.type===e.type&&t.location.line===e.location.line))}function ve(e,t,n,r,i){let a=100,o=100;t.forEach(e=>{e.severity===`critical`?o-=20:e.severity===`high`?o-=10:e.severity===`medium`?o-=5:o-=2}),o=Math.max(0,o);let s=100;if(r)r.cyclomaticComplexity>20?s-=30:r.cyclomaticComplexity>10?s-=15:r.cyclomaticComplexity>5&&(s-=5),r.cognitiveComplexity>15?s-=20:r.cognitiveComplexity>10&&(s-=10);else{let t=e.functions.reduce((e,t)=>e+t.complexity,0)/(e.functions.length||1);t>10?s-=20:t>5&&(s-=10)}s=Math.max(0,s);let c=r?.maintainabilityIndex||70,l=100;i&&i.forEach(e=>{e.severity===`high`?l-=10:e.severity===`medium`?l-=5:l-=2}),l=Math.max(0,l);let u=70;return typeof n.qualityScore==`number`&&(u=n.qualityScore),a=o*.4+s*.25+c*.2+l*.15,typeof n.qualityScore==`number`&&(a=(a+u)/2),Math.round(Math.max(0,Math.min(100,a)))}function ye(e){let n=[],r=[];try{let t=A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]});j(t,{VariableDeclarator(e){let t=e.node.init;M.isCallExpression(t)&&M.isFunctionExpression(t.callee)&&t.callee.body.body.some(e=>M.isReturnStatement(e)&&M.isObjectExpression(e.argument))&&n.push({name:`Singleton Pattern`,location:e.node.loc?.start.line||0,description:`IIFE returning object (Singleton pattern)`})},ClassDeclaration(e){let t=e.node.body.body.filter(e=>M.isClassMethod(e)).map(e=>M.isClassMethod(e)&&M.isIdentifier(e.key)?e.key.name:``);t.includes(`subscribe`)&&t.includes(`unsubscribe`)&&t.includes(`notify`)&&n.push({name:`Observer Pattern`,location:e.node.loc?.start.line||0,description:`Class with subscribe/unsubscribe/notify methods`})},FunctionDeclaration(e){let t=e.node.loc;if(t){let e=t.end.line-t.start.line;e>50&&r.push({name:`Long Function`,location:t.start.line,severity:`medium`,recommendation:`Function is ${e} lines long. Consider breaking it into smaller functions (max 50 lines)`})}},IfStatement(e){let t=0,n=e.parentPath;for(;n;)(n.isIfStatement()||n.isForStatement()||n.isWhileStatement())&&t++,n=n.parentPath;t>3&&r.push({name:`Deep Nesting`,location:e.node.loc?.start.line||0,severity:`medium`,recommendation:`Nesting depth is ${t}. Consider extracting to separate functions or using early returns`})},NumericLiteral(e){let t=e.node.value,n=e.parent;[0,1,-1,2,10,100,1e3].includes(t)||M.isMemberExpression(n)&&n.property===e.node||M.isAssignmentPattern(n)||r.push({name:`Magic Number`,location:e.node.loc?.start.line||0,severity:`low`,recommendation:`Replace magic number ${t} with a named constant`})},CatchClause(e){e.node.body.body.length===0&&r.push({name:`Empty Catch Block`,location:e.node.loc?.start.line||0,severity:`high`,recommendation:`Empty catch block swallows errors. Add proper error handling or logging`})},VariableDeclaration(e){e.node.kind===`var`&&r.push({name:`Use of var`,location:e.node.loc?.start.line||0,severity:`low`,recommendation:`Use let or const instead of var for better scoping`})}}),xe(t).forEach(e=>{r.push({name:`Duplicate Code`,location:e.location,severity:`medium`,recommendation:`Duplicate code found at lines ${e.location} and ${e.duplicateLocation}. Extract into a reusable function.`})})}catch(e){t.warn(`Code pattern detection failed`,e)}return{patterns:n,antiPatterns:r}}function be(e){let n=1,r=0,i=0,a=0,o=new Set,s=new Set;try{let t=A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),c=0;j(t,{IfStatement(){n++},SwitchCase(){n++},ForStatement(){n++},WhileStatement(){n++},DoWhileStatement(){n++},ConditionalExpression(){n++},LogicalExpression(e){(e.node.operator===`&&`||e.node.operator===`||`)&&n++},CatchClause(){n++},"IfStatement|ForStatement|WhileStatement|DoWhileStatement":{enter(){c++,r+=c},exit(){c--}},BinaryExpression(e){i++,o.add(e.node.operator)},UnaryExpression(e){i++,o.add(e.node.operator)},Identifier(e){a++,s.add(e.node.name)},NumericLiteral(e){a++,s.add(String(e.node.value))},StringLiteral(e){a++,s.add(e.node.value)}})}catch(e){t.warn(`Complexity metrics calculation failed`,e)}let c=o.size,l=s.size,u=i,d=a,f=c+l,p=u+d,m=c/2*(d/(l||1)),h=m*p,g=p*Math.log2(f||1),_=e.split(`
|
|
320
|
+
`).length,v=Math.max(0,171-5.2*Math.log(g||1)-.23*n-16.2*Math.log(_));return{cyclomaticComplexity:n,cognitiveComplexity:r,maintainabilityIndex:Math.round(v),halsteadMetrics:{vocabulary:f,length:p,difficulty:Math.round(m*100)/100,effort:Math.round(h)}}}function xe(e){let n=[],r=[];try{j(e,{FunctionDeclaration(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},FunctionExpression(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},ArrowFunctionExpression(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},ClassMethod(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})}});for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){let i=r[e],a=r[t];if(i.hash===a.hash){n.push({location:i.location,duplicateLocation:a.location,similarity:1});continue}let o=Se(i.normalizedCode,a.normalizedCode);o>=.85&&n.push({location:i.location,duplicateLocation:a.location,similarity:o})}}catch(e){t.debug(`Duplicate code detection failed`,e)}return n}function L(e){let t=JSON.stringify(e,(e,t)=>{if(![`loc`,`start`,`end`,`range`].includes(e)&&!(e===`comments`||e===`leadingComments`||e===`trailingComments`))return t}),n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return n.toString(36)}function R(e){let t=0,n=new Map,r=M.cloneNode(e,!0,!1);return j(M.file(M.program([r])),{Identifier(e){let r=e.node.name;[`console`,`window`,`document`,`Math`,`JSON`,`Array`,`Object`,`String`,`Number`].includes(r)||(n.has(r)||n.set(r,`VAR_${t++}`),e.node.name=n.get(r))},StringLiteral(e){e.node.value=`STRING`},NumericLiteral(e){e.node.value=0}}),JSON.stringify(r)}function Se(e,t){let n=e.length,r=t.length;if(Math.abs(n-r)>Math.max(n,r)*.3)return 0;let i=Array.from({length:n+1},()=>Array.from({length:r+1},()=>0));for(let e=0;e<=n;e++)i[e][0]=e;for(let e=0;e<=r;e++)i[0][e]=e;for(let a=1;a<=n;a++)for(let n=1;n<=r;n++){let r=e[a-1]===t[n-1]?0:1;i[a][n]=Math.min(i[a-1][n]+1,i[a][n-1]+1,i[a-1][n-1]+r)}return 1-i[n][r]/Math.max(n,r)}async function Ce(e){let n={nodes:[],edges:[]},r=[],i=[],a=[],o=new Map,s=new Set(`encodeURIComponent,encodeURI,escape,decodeURIComponent,decodeURI,htmlentities,htmlspecialchars,escapeHtml,escapeHTML,he.encode,he.escape,validator.escape,validator.unescape,validator.stripLow,validator.blacklist,validator.whitelist,validator.trim,validator.isEmail,validator.isURL,validator.isInt,DOMPurify.sanitize,DOMPurify.addHook,crypto.encrypt,crypto.hash,crypto.createHash,crypto.createHmac,CryptoJS.AES.encrypt,CryptoJS.SHA256,CryptoJS.MD5,bcrypt.hash,bcrypt.compare,btoa,atob,Buffer.from,db.prepare,db.query,mysql.escape,pg.query,xss,sanitizeHtml,parseInt,parseFloat,Number,String,JSON.stringify,JSON.parse,String.prototype.replace,String.prototype.trim,Array.prototype.filter,Array.prototype.map`.split(`,`));try{let c=A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]});j(c,{CallExpression(e){let t=e.node.callee,s=e.node.loc?.start.line||0;if(M.isMemberExpression(t)&&M.isIdentifier(t.property)){let i=t.property.name;if([`fetch`,`ajax`,`get`,`post`,`request`,`axios`].includes(i)){let t=`source-network-${s}`;r.push({type:`network`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${i}()`,type:`source`,location:{file:`current`,line:s}});let a=e.parent;M.isVariableDeclarator(a)&&M.isIdentifier(a.id)&&o.set(a.id.name,{sourceType:`network`,sourceLine:s})}else if([`querySelector`,`getElementById`,`getElementsByClassName`,`getElementsByTagName`].includes(i)){let e=`source-dom-${s}`;r.push({type:`user_input`,location:{file:`current`,line:s}}),n.nodes.push({id:e,name:`${i}()`,type:`source`,location:{file:`current`,line:s}})}}if(M.isIdentifier(t)){let r=t.name;if([`eval`,`Function`,`setTimeout`,`setInterval`].includes(r)){let t=`sink-eval-${s}`;i.push({type:`eval`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}()`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}}if(M.isMemberExpression(t)&&M.isIdentifier(t.property)){let r=t.property.name;if([`write`,`writeln`].includes(r)&&M.isIdentifier(t.object)&&t.object.name===`document`){let t=`sink-document-write-${s}`;i.push({type:`xss`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`document.${r}()`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`query`,`execute`,`exec`,`run`].includes(r)){let t=`sink-sql-${s}`;i.push({type:`sql-injection`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (SQL)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`exec`,`spawn`,`execSync`,`spawnSync`].includes(r)){let t=`sink-command-${s}`;i.push({type:`other`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (Command)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`readFile`,`writeFile`,`readFileSync`,`writeFileSync`,`open`].includes(r)){let t=`sink-file-${s}`;i.push({type:`other`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (File)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}}},MemberExpression(e){let t=e.node.object,i=e.node.property,a=e.node.loc?.start.line||0;if(M.isIdentifier(t)&&t.name===`location`&&M.isIdentifier(i)&&[`href`,`search`,`hash`,`pathname`].includes(i.name)){let t=`source-url-${a}`;r.push({type:`user_input`,location:{file:`current`,line:a}}),n.nodes.push({id:t,name:`location.${i.name}`,type:`source`,location:{file:`current`,line:a}});let s=e.parent;M.isVariableDeclarator(s)&&M.isIdentifier(s.id)&&o.set(s.id.name,{sourceType:`url`,sourceLine:a})}if(M.isIdentifier(t)&&t.name===`document`&&M.isIdentifier(i)&&i.name===`cookie`){let e=`source-cookie-${a}`;r.push({type:`storage`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`document.cookie`,type:`source`,location:{file:`current`,line:a}})}if(M.isIdentifier(t)&&[`localStorage`,`sessionStorage`].includes(t.name)){let e=`source-storage-${a}`;r.push({type:`storage`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`${t.name}.getItem()`,type:`source`,location:{file:`current`,line:a}})}if(M.isIdentifier(t)&&t.name===`window`&&M.isIdentifier(i)&&i.name===`name`){let e=`source-window-name-${a}`;r.push({type:`user_input`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`window.name`,type:`source`,location:{file:`current`,line:a}})}if(M.isIdentifier(t)&&t.name===`event`&&M.isIdentifier(i)&&i.name===`data`){let e=`source-postmessage-${a}`;r.push({type:`network`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`event.data (postMessage)`,type:`source`,location:{file:`current`,line:a}})}if(M.isIdentifier(t)&&t.name===`message`&&M.isIdentifier(i)&&i.name===`data`){let e=`source-websocket-${a}`;r.push({type:`network`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`WebSocket message.data`,type:`source`,location:{file:`current`,line:a}})}},AssignmentExpression(e){let t=e.node.left,r=e.node.right,s=e.node.loc?.start.line||0;if(M.isMemberExpression(t)&&M.isIdentifier(t.property)){let e=t.property.name;if([`innerHTML`,`outerHTML`].includes(e)){let t=`sink-dom-${s}`;if(i.push({type:`xss`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:e,type:`sink`,location:{file:`current`,line:s}}),M.isIdentifier(r)&&o.has(r.name)){let e=o.get(r.name);a.push({source:{type:e.sourceType,location:{file:`current`,line:e.sourceLine}},sink:{type:`xss`,location:{file:`current`,line:s}},path:[{file:`current`,line:e.sourceLine},{file:`current`,line:s}]})}}}}}),j(c,{VariableDeclarator(e){let n=e.node.id,r=e.node.init;if(M.isIdentifier(n)&&r){if(M.isCallExpression(r)&&F(r,s)){let e=r.arguments[0];if(M.isIdentifier(e)&&o.has(e.name)){t.debug(`Taint cleaned by sanitizer: ${e.name} -> ${n.name}`);return}}if(M.isIdentifier(r)&&o.has(r.name)){let e=o.get(r.name);o.set(n.name,e)}else if(M.isBinaryExpression(r)){let e=M.isIdentifier(r.left)&&o.has(r.left.name),t=M.isIdentifier(r.right)&&o.has(r.right.name);if(e||t){let t=e?o.get(r.left.name):o.get(r.right.name);o.set(n.name,t)}}else if(M.isCallExpression(r)){let e=r.arguments[0];if(M.isIdentifier(e)&&o.has(e.name)){let t=o.get(e.name);o.set(n.name,t)}}}},AssignmentExpression(e){let t=e.node.left,n=e.node.right;if(M.isIdentifier(t)&&M.isIdentifier(n)&&o.has(n.name)){let e=o.get(n.name);o.set(t.name,e)}}})}catch(e){t.warn(`Data flow analysis failed`,e)}return{graph:n,sources:r,sinks:i,taintPaths:a}}function z(e,t,n,r,i){e.forEach(e=>{if(M.isIdentifier(e)&&t.has(e.name)){let r=t.get(e.name);n.push({source:{type:r.sourceType,location:{file:`current`,line:r.sourceLine}},sink:{type:`eval`,location:{file:`current`,line:i}},path:[{file:`current`,line:r.sourceLine},{file:`current`,line:i}]})}})}const we=e=>typeof e==`object`&&!!e&&`traverse`in e&&typeof e.traverse==`function`;var Te=class{constructor(e){}async understand(e){t.info(`Starting code understanding...`);let n=Date.now();try{let{code:r,context:i,focus:a=`all`}=e,o=await this.analyzeStructure(r);t.debug(`Code structure analyzed`);let s=await this.aiAnalyze(r,a);t.debug(`AI analysis completed`);let c=this.detectTechStack(r,s);t.debug(`Tech stack detected`);let l=this.extractBusinessLogic(s,i);t.debug(`Business logic extracted`);let u=await this.analyzeDataFlow(r);t.debug(`Data flow analyzed`);let d=I(r,s);t.debug(`Security risks identified`);let{patterns:f,antiPatterns:p}=ye(r);t.debug(`Detected ${f.length} patterns and ${p.length} anti-patterns`);let m=be(r);t.debug(`Complexity metrics calculated`);let h=ve(o,d,s,m,p),g=Date.now()-n;return t.success(`Code understanding completed in ${g}ms`),{structure:o,techStack:c,businessLogic:l,dataFlow:u,securityRisks:d,qualityScore:h,codePatterns:f,antiPatterns:p,complexityMetrics:m}}catch(e){throw t.error(`Code understanding failed`,e),e}}async analyzeStructure(e){let n=[],r=[];try{j(A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),{FunctionDeclaration:e=>{let t=e.node;n.push({name:t.id?.name||`anonymous`,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},FunctionExpression:e=>{let t=e.node,r=e.parent,i=`anonymous`;r.type===`VariableDeclarator`&&r.id.type===`Identifier`?i=r.id.name:r.type===`AssignmentExpression`&&r.left.type===`Identifier`&&(i=r.left.name),n.push({name:i,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},ArrowFunctionExpression:e=>{let t=e.node,r=e.parent,i=`arrow`;r.type===`VariableDeclarator`&&r.id.type===`Identifier`&&(i=r.id.name),n.push({name:i,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},ClassDeclaration(e){let t=e.node,n=[],i=[];e.traverse({ClassMethod(e){let t=e.node;n.push({name:t.key.type===`Identifier`?t.key.name:`unknown`,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:1})},ClassProperty(e){let t=e.node;t.key.type===`Identifier`&&i.push({name:t.key.name,type:void 0,value:void 0})}}),r.push({name:t.id?.name||`anonymous`,methods:n,properties:i,location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column}})}})}catch(e){t.warn(`Failed to parse code structure`,e)}return{functions:n,classes:r,modules:this.analyzeModules(e),callGraph:this.buildCallGraph(n,e)}}async aiAnalyze(e,t){return{}}detectTechStack(e,t){let n={other:[]};if(t.techStack&&typeof t.techStack==`object`){let e=t.techStack;n.framework=e.framework,n.bundler=e.bundler,Array.isArray(e.libraries)&&(n.other=e.libraries)}e.includes(`React.`)||e.includes(`useState`)||e.includes(`useEffect`)?n.framework=`React`:e.includes(`Vue.`)||e.includes(`createApp`)?n.framework=`Vue`:e.includes(`@angular/`)&&(n.framework=`Angular`),e.includes(`__webpack_require__`)&&(n.bundler=`Webpack`);let r=[];return e.includes(`CryptoJS`)&&r.push(`CryptoJS`),e.includes(`JSEncrypt`)&&r.push(`JSEncrypt`),e.includes(`crypto-js`)&&r.push(`crypto-js`),r.length>0&&(n.cryptoLibrary=r),n}extractBusinessLogic(e,t){let n={mainFeatures:[],entities:[],rules:[],dataModel:{}};if(e.businessLogic&&typeof e.businessLogic==`object`){let t=e.businessLogic;Array.isArray(t.mainFeatures)&&(n.mainFeatures=t.mainFeatures),typeof t.dataFlow==`string`&&n.rules.push(t.dataFlow)}return t&&(n.dataModel={...n.dataModel,...t}),n}analyzeModules(e){let n=[];try{let t=A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=[],i=[];j(t,{ImportDeclaration(e){r.push(e.node.source.value)},ExportNamedDeclaration(e){e.node.source&&i.push(e.node.source.value)},ExportDefaultDeclaration(){i.push(`default`)}}),(r.length>0||i.length>0)&&n.push({name:`current`,imports:r,exports:i})}catch(e){t.warn(`Module analysis failed`,e)}return n}buildCallGraph(e,n){let r=e.map(e=>({id:e.name,name:e.name,type:`function`})),i=[];try{let t=A.parse(n,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=``;j(t,{FunctionDeclaration(e){r=e.node.id?.name||``},FunctionExpression(e){let t=e.parent;t.type===`VariableDeclarator`&&t.id.type===`Identifier`&&(r=t.id.name)},CallExpression(t){if(r){let n=t.node.callee,a=``;n.type===`Identifier`?a=n.name:n.type===`MemberExpression`&&n.property.type===`Identifier`&&(a=n.property.name),a&&e.some(e=>e.name===a)&&i.push({from:r,to:a})}}})}catch(e){t.warn(`Call graph construction failed`,e)}return{nodes:r,edges:i}}calculateComplexity(e){let t=1;return we(e)&&e.traverse({IfStatement(){t++},SwitchCase(){t++},ForStatement(){t++},WhileStatement(){t++},DoWhileStatement(){t++},ConditionalExpression(){t++},LogicalExpression(e){(e.node.operator===`&&`||e.node.operator===`||`)&&t++},CatchClause(){t++}}),t}async analyzeDataFlow(e){return Ce(e)}};function B(e){return{os:e.os,headless:e.headless,geoip:e.geoip,humanize:e.humanize,proxy:e.proxy,block_images:e.blockImages,block_webrtc:e.blockWebrtc,block_webgl:e.blockWebgl,locale:e.locale,addons:e.addons,fonts:e.fonts,exclude_addons:e.excludeAddons,custom_fonts_only:e.customFontsOnly,screen:e.screen,window:e.window,fingerprint:e.fingerprint,webgl_config:e.webglConfig,firefox_user_prefs:e.firefoxUserPrefs,main_world_eval:e.mainWorldEval,enable_cache:e.enableCache}}var Ee=class e{browser=null;browserServer=null;config;isClosing=!1;launchPromise;constructor(e={}){this.config={os:e.os??`windows`,headless:e.headless??!0,geoip:e.geoip??!1,humanize:e.humanize??!1,blockImages:e.blockImages??!1,blockWebrtc:e.blockWebrtc??!1,proxy:e.proxy,blockWebgl:e.blockWebgl,locale:e.locale,addons:e.addons,fonts:e.fonts,excludeAddons:e.excludeAddons,customFontsOnly:e.customFontsOnly,screen:e.screen,window:e.window,fingerprint:e.fingerprint,webglConfig:e.webglConfig,firefoxUserPrefs:e.firefoxUserPrefs,mainWorldEval:e.mainWorldEval,enableCache:e.enableCache}}async launch(){if(this.browser?.isConnected())return this.browser;if(this.isClosing)throw Error(`Cannot launch browser while closing`);if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch();try{return await this.launchPromise}finally{this.launchPromise=void 0}}async doLaunch(){this.browser&&=(t.info(`Closing existing Camoufox browser before relaunch`),await this.browser.close().catch(e=>t.warn(`Failed to close previous browser:`,e)),null),t.info(`Launching Camoufox (Firefox) [os=${this.config.os}, headless=${this.config.headless}]...`);let e;try{({Camoufox:e}=await import(`camoufox-js`))}catch(e){throw new b(`camoufox-js is not installed or its binaries are missing. Run \`pnpm run install:full\` or \`pnpm exec camoufox-js fetch\` before using the Camoufox driver. Root cause: ${e instanceof Error?e.message:String(e)}`)}this.browser=await e(B(this.config));let n=this.browser;if(typeof n.process==`function`){let e=n.process.call(this.browser);e&&typeof e.unref==`function`&&c.register(e)}if(this.isClosing)throw await this.browser.close().catch(e=>{t.warn(`Failed to close Camoufox browser launched during shutdown:`,e)}),this.browser=null,Error(`Camoufox launch aborted because close was requested`);return t.info(`Camoufox browser launched`),this.browser}async newPage(){this.browser||await this.launch();let e=await this.browser.newPage();return t.info(`New Camoufox page created`),e}async goto(e,n){let r=n??await this.newPage();return t.info(`Navigating to: ${e}`),await r.goto(e,{waitUntil:`networkidle`}),r}async close(){this.isClosing=!0;let e=this.launchPromise;if(e){e.catch(()=>void 0).finally(()=>{this.finalizeClose()});return}await this.finalizeClose()}static BROWSER_CLOSE_TIMEOUT_MS=5e3;async finalizeClose(){try{let n=this.browser;this.browser=null,n&&(await Promise.race([n.close(),new Promise((t,n)=>setTimeout(()=>n(Error(`camoufox browser.close() timed out`)),e.BROWSER_CLOSE_TIMEOUT_MS))]),t.info(`Camoufox browser closed`))}finally{this.isClosing=!1}}async launchAsServer(e,n){t.info(`Launching Camoufox server [os=${this.config.os}, port=${e??`auto`}]...`);let r;try{({launchServer:r}=await import(`camoufox-js`))}catch(e){throw new b(`camoufox-js server support is unavailable. Run \`pnpm run install:full\` or \`pnpm exec camoufox-js fetch\` before launching a Camoufox WebSocket server. Root cause: ${e instanceof Error?e.message:String(e)}`)}let i={...B(this.config),port:e,ws_path:n};this.browserServer&&=(t.info(`Closing existing Camoufox server before relaunch`),await this.browserServer.close().catch(e=>t.warn(`Failed to close previous server:`,e)),null);let a=await r(i);this.browserServer=a;let o=this.browserServer;if(typeof o.process==`function`){let e=o.process.call(this.browserServer);e&&typeof e.unref==`function`&&c.register(e)}let s=a.wsEndpoint();return t.info(`Camoufox server listening on: ${s}`),s}async connectToServer(e){t.info(`Connecting to Camoufox server: ${e}`),this.browser&&=(t.info(`Disconnecting existing browser before new connection`),await this.browser.close().catch(e=>t.warn(`Failed to close previous browser:`,e)),null);let n=(await import(`playwright-core`)).firefox;return this.browser=await n.connect(e),t.info(`Connected to Camoufox server`),this.browser}async closeBrowserServer(){this.browserServer&&(await this.browserServer.close(),this.browserServer=null,t.info(`Camoufox server closed`))}getBrowserServerEndpoint(){return this.browserServer?this.browserServer.wsEndpoint():null}getBrowser(){return this.browser}async getCDPSession(e){return t.warn(`CDP sessions on camoufox (Firefox) have limited support — consider using Chrome driver for CDP-heavy operations`),e.context().newCDPSession(e)}};function V(e){return[...new Set(e)]}const De=[`captcha`,`challenge`,`verify`,`verification`,`robot`,`human`,`security check`,`bot check`,`anti-bot`],Oe=[`browser check`,`security challenge`,`human check`,`verification widget`,`widget challenge`],ke=[`验证码`,`安全验证`,`人机验证`,`滑动验证`,`身份验证`,`安全检测`],Ae=[`captcha`,`challenge`,`verify`,`verification`,`robot-check`,`security-check`,`bot-check`],je=[`cdn-cgi/challenge`,`challenge-platform`,`browser-check`,`security-check`,`interstitial`],Me=[`captcha-frame`,`challenge-frame`,`widget-challenge`,`siteverify`,`sitekey`],Ne=[`slider-verify`,`drag-verify`,`slide-check`],Pe=[`Please verify`,`Verify you are human`,`Complete the security check`,`Slide to verify`,`Click to verify`,`Drag the slider`,`Prove you are human`,`I am not a robot`,`Checking your browser`,`Just a moment`,`Checking if the site connection is secure`,`This process is automatic`,`Protected by`,`Powered by`,`Are you a robot`,`Confirm you are human`,`Security verification required`],Fe=[`请完成安全验证`,`请滑动验证`,`拖动滑块`,`点击验证`,`人机验证`,`安全检测中`,`请证明您是人类`,`正在检查您的浏览器`,`请稍候`,`验证您的身份`,`请完成验证`,`滑动滑块`,`请拖动滑块完成验证`];V([...De,...Oe,...ke]),V([...Ae,...je,...Me,...Ne]),V([...Pe,...Fe]);const H={slider:[`.captcha-slider`,`.verify-slider`,`#captcha-slider`,`.slide-verify`,`[class*="captcha"][class*="slider"]`,`[class*="verify"][class*="slider"]`,`[id*="captcha"][id*="slider"]`,`[id*="verify"][id*="slider"]`,`[aria-label*="slider" i]`],image:[`[class*="captcha-image"]`,`[id*="captcha-image"]`,`.verify-img`,`.captcha-img`,`img[src*="captcha"]`,`img[alt*=""]`,`img[alt*="captcha"]`],widget:[`iframe[src*="captcha" i]`,`iframe[src*="challenge" i]`,`iframe[title*="captcha" i]`,`iframe[title*="verification" i]`,`[data-sitekey]`,`[class*="captcha"][class*="widget"]`,`[class*="challenge"][class*="widget"]`,`[class*="human"][class*="check"]`],browserCheck:[`#challenge-form`,`[id*="challenge-form"]`,`[class*="browser-check"]`,`[class*="security-check"]`,`[class*="challenge-page"]`,`[class*="challenge-container"]`],generic:[`[class*="captcha"]`,`[id*="captcha"]`,`[class*="verify"]`,`[id*="verify"]`,`[class*="challenge"]`,`[id*="challenge"]`,`iframe[src*="captcha"]`,`iframe[src*="verify"]`]};H.slider,H.widget,H.browserCheck;const Ie=[`verification code`,`enter code`,`sms code`,`email verification`,`phone verification`,`verify your email`,`verify your phone`],Le=[`verify-email`,`verify-phone`,`email-verification`,`account-verification`,`verify-account`,`phone-verification`,`sms-verification`,`reset-password`,`forgot-password`],Re=[`Enter verification code`,`Get code`,`Send code`,`Enter the code`,`We sent a code`,`verification code sent`,`Enter your authenticator code`,`Two-factor authentication`],ze=[`短信验证`,`邮箱验证`,`输入验证码`,`手机验证`,`登录验证`,`双重验证`],Be=[`验证邮箱`,`验证手机`,`重置密码`],Ve=[`输入验证码`,`获取验证码`,`发送验证码`,`已发送验证码`,`双因素认证`],He=[`two-factor`,`2fa`,`two-factor authentication`];V([...Ie,...ze,...He]),V([...Le,...Be]),V([...Re,...Ve]);const Ue=[`captcha`,`verification challenge`,`security check`,`human verification`,`slide to verify`,`drag the slider`,`select all images`,`i am not a robot`,`protected by security verification`,`checking your browser`],We=[`验证码`,`人机验证`,`安全验证`,`滑动验证`,`拖动滑块`,`请完成验证`,`请完成安全验证`,`请证明您是人类`,`正在检查您的浏览器`],Ge=[`verification code`,`enter verification code`,`sms code`,`email verification`,`phone verification`,`two-factor authentication`,`authenticator code`],Ke=[`输入验证码`,`短信验证码`,`邮箱验证码`,`获取验证码`,`发送验证码`,`双因素认证`],U=V([...Ue,...We]),qe=V([...Ge,...Ke]),Je=[`slider`,`image`,`widget`,`browser_check`,`page_redirect`,`url_redirect`,`text_input`,`none`,`unknown`],Ye=[`regional_service`,`embedded_widget`,`edge_service`,`managed_service`,`external_review`,`unknown`],Xe={checkbox:`widget`,challenge_widget:`widget`,browsercheck:`browser_check`,"browser-check":`browser_check`,redirect:`page_redirect`},Ze={regional:`regional_service`,embedded:`embedded_widget`,widget:`embedded_widget`,edge:`edge_service`,managed:`managed_service`,"external-ai-required":`external_review`,unknown:`unknown`},Qe=U,$e=[`captcha`,`challenge`,`slider`,`widget`,`checkbox`,`sitekey`,`browser-check`,`security-check`];var et=class{screenshotDir;constructor(e=`./screenshots`){this.screenshotDir=e}async saveScreenshot(e){try{await de(this.screenshotDir,{recursive:!0});let n=`captcha-${Date.now()}.png`,r=ae(this.screenshotDir,n);return await fe(r,Buffer.from(e,`base64`)),t.info(`Screenshot saved: ${r}`),r}catch(e){throw t.error(`Failed to persist CAPTCHA screenshot`,e),e}}async detect(e){try{t.info(`Running rule-based captcha detection...`);let n=await this.getPageInfo(e),r=this.applyLocalGuardrails(n,this.evaluateFallbackTextAnalysis(n));return t.info(`CAPTCHA detection result: ${r.detected?`detected`:`not_detected`} (confidence: ${r.confidence}%)`),r}catch(e){return t.error(`CAPTCHA detection failed`,e),{detected:!1,type:`none`,confidence:0,reasoning:`Detection error: ${e instanceof Error?e.message:String(e)}`}}}async getPageInfo(e){return{url:e.url(),title:await e.title(),...await e.evaluate(()=>{let e=document.body.innerText.substring(0,1e3),t=document.querySelectorAll(`iframe`).length>0,n=[];for(let e of[`[class*="captcha"]`,`[id*="captcha"]`,`[class*="verify"]`,`[id*="verify"]`,`[class*="challenge"]`,`iframe[src*="captcha" i]`,`iframe[src*="challenge" i]`,`[data-sitekey]`,`[class*="browser-check"]`]){let t=document.querySelectorAll(e);t.length>0&&n.push(`${e} (${t.length})`)}return{bodyText:e,hasIframes:t,suspiciousElements:n}})}}normalizeCaptchaType(e,t){if(!t)return`none`;if(typeof e==`string`){if(Je.includes(e))return e;let t=Xe[e.toLowerCase()];if(t)return t}return`unknown`}normalizeProviderHint(e,t){if(typeof e==`string`){if(Ye.includes(e))return e;let t=Ze[e.toLowerCase()];if(t)return t}return t?`unknown`:void 0}normalizeDetected(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return!1}normalizeConfidence(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}applyLocalGuardrails(e,t){return t.detected||!this.hasStrongOverrideSignals(e)?t:{...this.evaluateFallbackTextAnalysis(e),reasoning:`AI reported no CAPTCHA, but local heuristics found strong CAPTCHA signals in the page context. / AI 判定为无验证码,但本地启发式在页面上下文中发现强信号。`,screenshotPath:t.screenshotPath}}hasStrongCaptchaElementSignals(e){return e.some(e=>{let t=e.toLowerCase();return $e.some(e=>t.includes(e))})}hasStrongOverrideSignals(e){let t=`${e.title}\n${e.bodyText}`.toLowerCase();return this.hasStrongCaptchaElementSignals(e.suspiciousElements)?Qe.some(e=>t.includes(e)):!1}evaluateFallbackTextAnalysis(e){let t=`${e.url}\n${e.title}\n${e.bodyText}`.toLowerCase(),n=this.hasStrongCaptchaElementSignals(e.suspiciousElements),r=U.some(e=>t.includes(e)),i=n&&r,a=qe.some(e=>t.includes(e));if(a&&!i)return{detected:!1,type:`none`,confidence:95,reasoning:`Fallback heuristics matched OTP or account verification text, not a CAPTCHA. / 后备启发式匹配到一次性验证码或账户校验文本,不视为 CAPTCHA。`,suggestions:[`Continue the login or verification flow normally / 继续正常登录或验证流程`]};let o=i;return{detected:o,type:o?`unknown`:`none`,confidence:o?a?55:60:90,reasoning:o?a?`Fallback heuristics found strong CAPTCHA signals despite OTP-like wording on the page. / 后备启发式发现了强 CAPTCHA 信号,优先于页面上的一次性验证码类文案。`:`Fallback heuristics matched both suspicious elements and CAPTCHA keywords. / 后备启发式匹配到可疑元素和验证码关键词。`:`Fallback heuristics did not find strong CAPTCHA signals. / 后备启发式未找到强验证码信号。`,suggestions:o?[`Switch to headed mode if needed / 如需要切换到有头模式`,`Wait for manual completion before continuing / 等待手动完成后继续`]:[`Solve the CAPTCHA manually if one is visible / 如有可见验证码请手动解决`]}}async waitForCompletion(e,n=3e5){t.info(`Waiting for CAPTCHA to be solved...`);let r=Date.now();for(;Date.now()-r<n;){let n=await this.detect(e);if(!n.detected||n.confidence<50)return t.info(`CAPTCHA is no longer detected; continuing workflow`),!0;await new Promise(e=>setTimeout(e,3e3))}return t.error(`Timed out while waiting for CAPTCHA completion`),!1}},tt=class{keywordRules=new Map;libraryRules=new Map;constantRules=new Map;patternRules=new Map;securityRules=new Map;constructor(){this.loadDefaultRules()}loadDefaultRules(){this.addKeywordRule({category:`symmetric`,keywords:[`AES`,`DES`,`3DES`,`TripleDES`,`RC4`,`RC2`,`Blowfish`,`Twofish`,`ChaCha20`,`Camellia`,`SEED`,`ARIA`,`SM4`],confidence:.6,description:`Symmetric encryption algorithms`}),this.addKeywordRule({category:`asymmetric`,keywords:[`RSA`,`ECC`,`ECDSA`,`ECDH`,`DSA`,`ElGamal`,`Ed25519`,`X25519`,`Curve25519`,`secp256k1`,`SM2`],confidence:.6,description:`Asymmetric encryption algorithms`}),this.addKeywordRule({category:`hash`,keywords:[`MD5`,`SHA1`,`SHA-1`,`SHA256`,`SHA-256`,`SHA512`,`SHA-512`,`SHA3`,`BLAKE2`,`BLAKE3`,`RIPEMD`,`Whirlpool`,`SM3`,`Keccak`],confidence:.6,description:`Hash algorithms`}),this.addKeywordRule({category:`encoding`,keywords:[`Base64`,`Base32`,`Base58`,`Hex`,`UTF8`,`UTF-8`,`Latin1`,`ASCII`],confidence:.5,description:`Encoding methods`}),this.addKeywordRule({category:`mode`,keywords:[`CBC`,`ECB`,`CTR`,`GCM`,`CFB`,`OFB`,`XTS`,`CCM`],confidence:.7,description:`Block cipher modes`}),this.addKeywordRule({category:`padding`,keywords:[`PKCS7`,`PKCS5`,`PKCS1`,`ISO10126`,`ZeroPadding`,`NoPadding`,`OAEP`,`PSS`],confidence:.7,description:`Padding schemes`}),this.addLibraryRule({name:`CryptoJS`,patterns:[`CryptoJS`,`crypto-js`],versionPattern:/CryptoJS\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`AES`,`DES`,`TripleDES`,`RC4`,`Rabbit`,`MD5`,`SHA1`,`SHA256`,`SHA512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`JSEncrypt`,patterns:[`JSEncrypt`,`jsencrypt`],versionPattern:/version:\s*['"]([^'"]+)['"]/,confidence:.9,features:[`RSA`]}),this.addLibraryRule({name:`forge`,patterns:[`forge.`,`node-forge`],versionPattern:/forge\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`RSA`,`AES`,`DES`,`3DES`,`MD5`,`SHA1`,`SHA256`,`SHA512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`sjcl`,patterns:[`sjcl.`],versionPattern:/sjcl\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`AES`,`SHA256`,`HMAC`,`PBKDF2`,`CCM`,`GCM`]}),this.addLibraryRule({name:`Web Crypto API`,patterns:[`crypto.subtle`,`window.crypto.subtle`,`self.crypto.subtle`],confidence:.95,features:[`AES-CBC`,`AES-CTR`,`AES-GCM`,`RSA-OAEP`,`RSA-PSS`,`ECDSA`,`ECDH`,`SHA-1`,`SHA-256`,`SHA-384`,`SHA-512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`asmCrypto`,patterns:[`asmCrypto`],confidence:.9,features:[`AES`,`RSA`,`SHA256`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`TweetNaCl`,patterns:[`nacl.`,`tweetnacl`],confidence:.9,features:[`Curve25519`,`Ed25519`,`Salsa20`,`Poly1305`]}),this.addLibraryRule({name:`elliptic`,patterns:[`elliptic`,`ec.keyFromPrivate`,`ec.keyFromPublic`],confidence:.9,features:[`ECDSA`,`ECDH`,`secp256k1`]}),this.addConstantRule({name:`MD5`,type:`hash`,values:[1732584193,4023233417,2562383102,271733878],confidence:.95,description:`MD5 initialization vector`}),this.addConstantRule({name:`SHA1`,type:`hash`,values:[1732584193,4023233417,2562383102,271733878,3285377520],confidence:.95,description:`SHA-1 initialization vector`}),this.addConstantRule({name:`SHA256`,type:`hash`,values:[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],confidence:.95,description:`SHA-256 initialization vector`}),this.addConstantRule({name:`AES S-box`,type:`symmetric`,values:[99,124,119,123,242,107,111,197],confidence:.9,description:`AES S-box first 8 values`}),this.addSecurityRule({name:`weak-md5`,severity:`high`,check:e=>e.algorithm===`MD5`,message:`MD5 is cryptographically broken and should not be used`,recommendation:`Use SHA-256 or SHA-3 instead`}),this.addSecurityRule({name:`weak-sha1`,severity:`high`,check:e=>e.algorithm===`SHA1`||e.algorithm===`SHA-1`,message:`SHA-1 is deprecated and vulnerable to collision attacks`,recommendation:`Use SHA-256 or SHA-3 instead`}),this.addSecurityRule({name:`weak-des`,severity:`critical`,check:e=>e.algorithm===`DES`,message:`DES has a very small key size (56 bits) and is easily broken`,recommendation:`Use AES-256 instead`}),this.addSecurityRule({name:`weak-rc4`,severity:`critical`,check:e=>e.algorithm===`RC4`,message:`RC4 has known vulnerabilities and should not be used`,recommendation:`Use AES-GCM or ChaCha20-Poly1305 instead`}),this.addSecurityRule({name:`ecb-mode`,severity:`high`,check:e=>e.mode===`ECB`,message:`ECB mode is insecure as it does not provide semantic security`,recommendation:`Use CBC, CTR, or GCM mode instead`}),this.addSecurityRule({name:`no-padding`,severity:`medium`,check:e=>e.padding===`NoPadding`&&e.mode!==`CTR`&&e.mode!==`GCM`,message:`Using no padding with non-streaming modes can be insecure`,recommendation:`Use PKCS7 padding or switch to CTR/GCM mode`}),this.addSecurityRule({name:`short-key`,severity:`high`,check:e=>!!(e.keySize&&e.keySize<128),message:`Key size is too short and vulnerable to brute force attacks`,recommendation:`Use at least 128-bit keys, preferably 256-bit`})}addKeywordRule(e){this.keywordRules.set(e.category,e)}addLibraryRule(e){this.libraryRules.set(e.name,e)}addConstantRule(e){this.constantRules.set(e.name,e)}addPatternRule(e){this.patternRules.set(e.name,e)}addSecurityRule(e){this.securityRules.set(e.name,e)}getKeywordRules(){return Array.from(this.keywordRules.values())}getLibraryRules(){return Array.from(this.libraryRules.values())}getConstantRules(){return Array.from(this.constantRules.values())}getPatternRules(){return Array.from(this.patternRules.values())}getSecurityRules(){return Array.from(this.securityRules.values())}loadFromJSON(e){try{let t=JSON.parse(e);t.keywords&&t.keywords.forEach(e=>this.addKeywordRule(e)),t.libraries&&t.libraries.forEach(e=>this.addLibraryRule(e)),t.constants&&t.constants.forEach(e=>this.addConstantRule(e))}catch(e){throw Error(`Failed to load rules from JSON: ${e}`,{cause:e})}}exportToJSON(){return JSON.stringify({keywords:this.getKeywordRules(),libraries:this.getLibraryRules(),constants:this.getConstantRules(),patterns:this.getPatternRules(),security:this.getSecurityRules()},null,2)}},nt=class{rulesManager;constructor(e,t){this.rulesManager=t||new tt}loadCustomRules(e){this.rulesManager.loadFromJSON(e)}exportRules(){return this.rulesManager.exportToJSON()}async detect(e){t.info(`Starting crypto detection...`);let n=Date.now();try{let{code:r}=e,i=[],a=[],o=[],s=this.detectByKeywords(r);i.push(...s);let c=this.detectLibraries(r);a.push(...c);let l=this.detectByAST(r);i.push(...l.algorithms),l.parameters&&this.mergeParameters(i,l.parameters);let u=this.mergeResults(i),d=this.evaluateSecurity(u,r);o.push(...d);let f=this.analyzeStrength(u,o),p=u.length>0?u.reduce((e,t)=>e+t.confidence,0)/u.length:0;return t.info(`Crypto detection completed in ${Date.now()-n}ms, found ${u.length} algorithms`),{algorithms:u,libraries:a,confidence:p,securityIssues:o,strength:f}}catch(e){throw t.error(`Crypto detection failed`,e),e}}detectByKeywords(e){let t=[];return this.rulesManager.getKeywordRules().forEach(n=>{n.keywords.forEach(r=>{let i=RegExp(`\\b${this.escapeRegex(r)}\\b`,`gi`),a=e.match(i);if(a){if(n.category===`mode`||n.category===`padding`)return;t.push({name:r,type:n.category,confidence:n.confidence,location:{file:`current`,line:this.findLineNumber(e,r)},usage:`Found ${a.length} occurrence(s) of ${r}${n.description?` (${n.description})`:``}`})}})}),t}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}detectLibraries(e){let t=[];return this.rulesManager.getLibraryRules().forEach(n=>{if(n.patterns.some(t=>e.includes(t))){let r;n.versionPattern&&(r=e.match(n.versionPattern)?.[1]),t.push({name:n.name,version:r,confidence:n.confidence})}}),t}detectByAST(e){let n=[],r=new Map;try{let t=A.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),i=this.rulesManager.getConstantRules();j(t,{VariableDeclarator(e){let t=e.node;t.init?.type===`ArrayExpression`&&t.init.elements.length===256&&t.id.type===`Identifier`&&(t.id.name.toLowerCase().includes(`sbox`)||t.id.name.toLowerCase().includes(`box`)||t.id.name.toLowerCase().includes(`table`))&&n.push({name:`Custom Symmetric Cipher`,type:`symmetric`,confidence:.8,location:{file:`current`,line:t.loc?.start.line||0},usage:`S-box array detected (${t.id.name})`})},CallExpression(e){let t=e.node;if(M.isMemberExpression(t.callee)&&M.isIdentifier(t.callee.property)){let e=t.callee.property.name;[`modPow`,`modInverse`,`gcd`,`isProbablePrime`].includes(e)&&n.push({name:`Asymmetric Encryption`,type:`asymmetric`,confidence:.75,location:{file:`current`,line:t.loc?.start.line||0},usage:`Big number operation detected: ${e}`}),rt(t,r)}},FunctionDeclaration(t){let r=t.node,i=r.id?.name.toLowerCase()||``;if(i.includes(`hash`)||i.includes(`digest`)||i.includes(`checksum`)){let t=e.substring(r.start||0,r.end||0),a=t.includes(`for`)||t.includes(`while`),o=/>>>|<<|&|\||\^/.test(t);a&&o&&n.push({name:`Custom Hash Function`,type:`hash`,confidence:.7,location:{file:`current`,line:r.loc?.start.line||0},usage:`Hash function detected: ${i}`})}},ArrayExpression(e){let t=e.node.elements;if(t.length<4)return;let r=[];t.forEach(e=>{M.isNumericLiteral(e)&&r.push(e.value)}),i.forEach(t=>{if(t.values.every((e,t)=>r[t]===e)){let r=t.type===`other`?`encoding`:t.type;n.push({name:t.name,type:r,confidence:t.confidence,location:{file:`current`,line:e.node.loc?.start.line||0},usage:`${t.name} initialization constants detected`})}})}})}catch(e){t.warn(`AST detection failed`,e)}return{algorithms:n,parameters:r}}mergeParameters(e,t){e.forEach(e=>{let n=t.get(e.name);n&&(e.parameters={...e.parameters,...n})})}evaluateSecurity(e,t){let n=[],r=this.rulesManager.getSecurityRules();return e.forEach(e=>{let t={algorithm:e.name,mode:e.parameters?.mode,padding:e.parameters?.padding,keySize:e.parameters?.keySize};r.forEach(r=>{r.check(t)&&n.push({severity:r.severity,algorithm:e.name,issue:r.message,recommendation:r.recommendation||``,location:e.location})})}),n}analyzeStrength(e,t){let n=100,r=100,i=100,a=100;t.forEach(e=>{let t={critical:40,high:25,medium:15,low:5}[e.severity];e.issue.includes(`algorithm`)||e.issue.includes(`broken`)?n-=t:e.issue.includes(`key`)?r-=t:e.issue.includes(`mode`)?i-=t:a-=t}),n=Math.max(0,n),r=Math.max(0,r),i=Math.max(0,i),a=Math.max(0,a);let o=(n+r+i+a)/4,s;return s=o>=80?`strong`:o>=60?`moderate`:o>=40?`weak`:`broken`,{overall:s,score:Math.round(o),factors:{algorithm:Math.round(n),keySize:Math.round(r),mode:Math.round(i),implementation:Math.round(a)}}}mergeResults(e){let t=new Map;return e.forEach(e=>{let n=`${e.name}-${e.type}`,r=t.get(n);(!r||e.confidence>r.confidence)&&t.set(n,e)}),Array.from(t.values()).toSorted((e,t)=>t.confidence-e.confidence)}findLineNumber(e,t){let n=e.split(`
|
|
321
|
+
`);for(let e=0;e<n.length;e++)if(n[e]?.includes(t))return e+1;return 0}};function rt(e,t){if(!M.isMemberExpression(e.callee))return;let n=it(e.callee);if(n.includes(`CryptoJS`)){let r=n.match(/CryptoJS\.(AES|DES|TripleDES|RC4|Rabbit|RabbitLegacy)/);if(r){let n=r[1],i={};e.arguments.length>=3&&M.isObjectExpression(e.arguments[2])&&e.arguments[2].properties.forEach(e=>{if(M.isObjectProperty(e)&&M.isIdentifier(e.key)){let t=e.key.name;M.isIdentifier(e.value)?i[t]=e.value.name:(M.isStringLiteral(e.value)||M.isNumericLiteral(e.value))&&(i[t]=e.value.value)}}),n&&t.set(n,i)}}if(n.includes(`crypto.subtle`)&&n.match(/\.(encrypt|decrypt|sign|verify|digest|generateKey)/)&&e.arguments.length>0){let n=e.arguments[0];if(M.isObjectExpression(n)){let e={};n.properties.forEach(t=>{if(M.isObjectProperty(t)&&M.isIdentifier(t.key)){let n=t.key.name;(M.isStringLiteral(t.value)||M.isNumericLiteral(t.value))&&(e[n]=t.value.value)}});let r=e.name||`WebCrypto`;r&&t.set(r,e)}}}function it(e){let t=[],n=e=>{M.isMemberExpression(e)?(n(e.object),M.isIdentifier(e.property)&&t.push(e.property.name)):M.isIdentifier(e)&&t.push(e.name)};return n(e),t.join(`.`)}function W(e){let t=[];return(e.includes(`_0x`)||e.includes(`\\x`)||/var\s+_0x[a-f0-9]+\s*=/.test(e))&&t.push(`javascript-obfuscator`),(e.includes(`__webpack_require__`)||e.includes(`webpackJsonp`))&&t.push(`webpack`),e.length>1e3&&!e.includes(`
|
|
322
|
+
`)&&t.push(`uglify`),e.includes(`eval`)&&e.includes(`Function`)&&t.push(`vm-protection`),t.length===0&&t.push(`unknown`),t}function at(e){let t=0;e.includes(`
|
|
323
|
+
`)&&(t+=20);let n=e.match(/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g)||[];return n.reduce((e,t)=>e+t.length,0)/(n.length||1)>3&&(t+=30),e.replace(/\s/g,``).length/e.length<.8&&(t+=20),!e.includes(`_0x`)&&!e.includes(`\\x`)&&(t+=20),Math.min(t,100)}var ot=class{resultCache=new Map;maxCacheSize=100;generateCacheKey(e){let t=JSON.stringify({code:e.code.substring(0,2e3),detectOnly:e.detectOnly,forceOutput:e.forceOutput,includeModuleCode:e.includeModuleCode,jsx:e.jsx,mangle:e.mangle,mappings:e.mappings,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,unpack:e.unpack,unminify:e.unminify});return E.createHash(`md5`).update(t).digest(`hex`)}async deobfuscate(e){let n=this.generateCacheKey(e),r=this.resultCache.get(n);if(r)return t.debug(`Advanced deobfuscation result from cache`),{...r,cached:!0};t.info(`Starting advanced webcrack deobfuscation...`);let i=W(e.code),a=[];if(e.detectOnly){let t={code:e.code,detectedTechniques:i,confidence:Math.min(.6+i.length*.05,.9),warnings:[...a,`detectOnly does not invoke a separate legacy detector anymore; techniques are inferred from the current static signature pass.`],astOptimized:!1,engine:`webcrack`,webcrackApplied:!1};return this.storeCacheEntry(n,t),{...t,cached:!1}}let o=await w(e.code,{unpack:e.unpack,unminify:e.unminify,jsx:e.jsx,mangle:e.mangle,mappings:e.mappings,includeModuleCode:e.includeModuleCode,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,forceOutput:e.forceOutput});if(!o.applied){let e=o.reason??`webcrack did not return a result`;throw t.error(`advanced webcrack deobfuscation failed: ${e}`),Error(e)}o.bundle&&i.push(`bundle-unpack`),o.optionsUsed.unminify&&i.push(`unminify`),o.optionsUsed.jsx&&i.push(`jsx-decompile`),o.optionsUsed.mangle&&i.push(`mangle`),i.push(`webcrack`);let s={code:o.code,detectedTechniques:Array.from(new Set(i)),confidence:this.calculateConfidence(o,i),warnings:a,astOptimized:!1,bundle:o.bundle,savedTo:o.savedTo,savedArtifacts:o.savedArtifacts,engine:`webcrack`,webcrackApplied:!0};return this.storeCacheEntry(n,s),{...s,cached:!1}}storeCacheEntry(e,t){if(this.resultCache.size>=this.maxCacheSize){let e=this.resultCache.keys().next().value;e&&this.resultCache.delete(e)}this.resultCache.set(e,t)}calculateConfidence(e,t){let n=.72+t.length*.03;return e.bundle&&(n+=.08),e.savedTo&&(n+=.04),Math.min(n,.99)}},st=class{resultCache=new Map;maxCacheSize=100;constructor(e){}generateCacheKey(e){let t=JSON.stringify({code:e.code.substring(0,2e3),forceOutput:e.forceOutput,includeModuleCode:e.includeModuleCode,jsx:e.jsx,mangle:e.mangle??e.renameVariables,mappings:e.mappings,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,unpack:e.unpack,unminify:e.unminify});return E.createHash(`md5`).update(t).digest(`hex`)}async deobfuscate(e){let n=this.generateCacheKey(e),r=this.resultCache.get(n);if(r)return t.debug(`Deobfuscation result from cache`),r.cached=!0,r;t.info(`Starting webcrack deobfuscation...`);let i=Date.now(),a=this.detectObfuscationType(e.code),o=await w(e.code,{unpack:e.unpack,unminify:e.unminify,jsx:e.jsx,mangle:e.mangle??e.renameVariables,mappings:e.mappings,includeModuleCode:e.includeModuleCode,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,forceOutput:e.forceOutput});if(!o.applied){let e=o.reason??`webcrack did not return a result`;throw t.error(`webcrack deobfuscation failed: ${e}`),Error(e)}let s=this.buildAnalysis(o,a),c=[{type:`webcrack`,description:`Ran webcrack (unminify=${o.optionsUsed.unminify}, unpack=${o.optionsUsed.unpack}, jsx=${o.optionsUsed.jsx}, mangle=${o.optionsUsed.mangle})`,success:!0},...o.bundle?[{type:`webcrack-unpack`,description:`Recovered ${o.bundle.moduleCount} bundled modules`,success:!0}]:[],...o.savedTo?[{type:`webcrack-save`,description:`Saved webcrack artifacts to ${o.savedTo}`,success:!0}]:[]],l=this.calculateReadabilityScore(o.code),u=this.calculateConfidence(o,l),d=Date.now()-i;t.success(`webcrack deobfuscation completed in ${d}ms (confidence: ${(u*100).toFixed(1)}%)`);let f={code:o.code,readabilityScore:l,confidence:u,obfuscationType:a,transformations:c,analysis:s,bundle:o.bundle,savedTo:o.savedTo,savedArtifacts:o.savedArtifacts,engine:`webcrack`,webcrackApplied:!0};if(this.resultCache.size>=this.maxCacheSize){let e=this.resultCache.keys().next().value;e&&this.resultCache.delete(e)}return f.cached=!1,this.resultCache.set(n,f),f}detectObfuscationType(e){return W(e)}calculateReadabilityScore(e){return at(e)}calculateConfidence(e,t){let n=.7;return n+=t/500,e.bundle&&(n+=.1),e.savedTo&&(n+=.05),Math.min(n,.99)}buildAnalysis(e,t){let n=[`webcrack completed deobfuscation for detected types: ${t.join(`, `)}.`];return e.bundle&&n.push(`Recovered a ${e.bundle.type} bundle with ${e.bundle.moduleCount} modules.`),e.savedTo&&n.push(`Artifacts saved to ${e.savedTo}.`),n.join(` `)}},ct=class{jsvmpDetector;constructor(){this.jsvmpDetector=new ie}detect(e){let n=[],r={},i=[],a=[],o;this.detectJavaScriptObfuscator(e)&&(n.push(`javascript-obfuscator`),r[`javascript-obfuscator`]=.9,i.push(`String array with rotation`),i.push(`Control flow flattening`),a.push(`Use deobfuscate(engine="webcrack") for aggressive webcrack cleanup`)),this.detectWebpack(e)&&(n.push(`webpack`),r.webpack=.85,i.push(`__webpack_require__`),a.push(`Use deobfuscate(engine="webcrack", unpack=true) to recover modules`)),this.detectUglify(e)&&(n.push(`uglify`),r.uglify=.7,i.push(`Minified variable names`),a.push(`Use prettier or beautifier`));let s=this.detectVMProtectionDetailed(e);s&&(n.push(`vm-protection`),r[`vm-protection`]=.95,o=s,i.push(`JSVMP with ${s.instructionCount} instructions`),i.push(`Complexity: ${s.complexity}`),a.push(`Use JSVMPDeobfuscator for advanced deobfuscation`)),this.detectInvisibleUnicode(e)&&(n.push(`invisible-unicode`),r[`invisible-unicode`]=1,i.push(`Zero-width characters`),a.push(`Use AdvancedDeobfuscator.decodeInvisibleUnicode()`)),this.detectControlFlowFlattening(e)&&(n.push(`control-flow-flattening`),r[`control-flow-flattening`]=.8,i.push(`Switch-case state machine`),a.push(`Requires symbolic execution`)),this.detectStringArrayRotation(e)&&(n.push(`string-array-rotation`),r[`string-array-rotation`]=.85,i.push(`Rotated string array`),a.push(`Extract and derotate string array`)),this.detectDeadCodeInjection(e)&&(n.push(`dead-code-injection`),r[`dead-code-injection`]=.75,i.push(`Unreachable code blocks`),a.push(`Use AST-based dead code elimination`)),this.detectOpaquePredicates(e)&&(n.push(`opaque-predicates`),r[`opaque-predicates`]=.7,i.push(`Always-true/false conditions`),a.push(`Use constant folding`)),this.detectJSFuck(e)&&(n.push(`jsfuck`),r.jsfuck=1,i.push(`Only uses []()!+`),a.push(`Use jsfuck decoder`)),this.detectAAEncode(e)&&(n.push(`aaencode`),r.aaencode=1,i.push(`Japanese emoticons`),a.push(`Use aaencode decoder`)),this.detectJJEncode(e)&&(n.push(`jjencode`),r.jjencode=1,i.push(`$={___:++$`),a.push(`Use jjencode decoder`)),this.detectPacker(e)&&(n.push(`packer`),r.packer=.95,i.push(`eval(function(p,a,c,k,e,d)`),a.push(`Use unpacker tools`)),this.detectEvalObfuscation(e)&&(n.push(`eval-obfuscation`),r[`eval-obfuscation`]=.8,i.push(`Multiple eval() calls`),a.push(`Hook eval() and log arguments`)),this.detectBase64Encoding(e)&&(n.push(`base64-encoding`),r[`base64-encoding`]=.9,i.push(`atob() or Base64 strings`),a.push(`Decode Base64 strings`)),this.detectHexEncoding(e)&&(n.push(`hex-encoding`),r[`hex-encoding`]=.85,i.push(`\\x hex sequences`),a.push(`Decode hex strings`)),this.detectSelfModifying(e)&&(n.push(`self-modifying`),r[`self-modifying`]=.9,i.push(`Dynamic code generation`),a.push(`Requires runtime analysis`)),this.detectJScrambler(e)&&(n.push(`jscrambler`),r.jscrambler=.85,i.push(`Control flow flattening + Self-defending`),a.push(`Use JScrambler deobfuscator`)),this.detectURLEncode(e)&&(n.push(`urlencoded`),r.urlencoded=.95,i.push(`URL encoded strings`),a.push(`Decode URL encoding`)),n.length===0&&(n.push(`unknown`),r.unknown=.5,a.push(`Code may be clean or use custom obfuscation`));let c=this.buildClassifier(e,n,r);return t.info(`Detected obfuscation types: ${n.join(`, `)}`),{types:n,confidence:r,features:i,recommendations:a,toolRecommendations:this.buildToolRecommendations(n,e),classifier:c,vmFeatures:o}}buildClassifier(e,t,n){let r=(e,t)=>n[e]??t;return t.includes(`javascript-obfuscator`)?{name:/obfuscator\.io/i.test(e)?`obfuscator.io`:`javascript-obfuscator`,version:`unknown`,confidence:r(`javascript-obfuscator`,.9),deobfuscateStrategy:`Start with deobfuscate(engine="webcrack"), then use analysis_deflat_control_flow when dispatcher-based control flow is present.`}:t.includes(`jsfuck`)?{name:`jsfuck`,version:`unknown`,confidence:r(`jsfuck`,1),deobfuscateStrategy:`Decode the JSFuck payload first, then run deobfuscate for secondary cleanup if needed.`}:t.includes(`aaencode`)?{name:`aaencode`,version:`unknown`,confidence:r(`aaencode`,1),deobfuscateStrategy:`Decode AAEncode first, then run deobfuscate or understand_code on the decoded output.`}:t.includes(`jjencode`)?{name:`jjencode`,version:`unknown`,confidence:r(`jjencode`,1),deobfuscateStrategy:`Decode JJEncode first, then run deobfuscate or understand_code on the decoded output.`}:t.includes(`packer`)?{name:`packer`,version:`unknown`,confidence:r(`packer`,.95),deobfuscateStrategy:`Unpack the wrapper first, then run deobfuscate on the extracted inner payload.`}:t.includes(`jscrambler`)?{name:`jscrambler`,version:`unknown`,confidence:r(`jscrambler`,.85),deobfuscateStrategy:`Prioritize control-flow cleanup and runtime-assisted analysis; static deobfuscation alone is often insufficient.`}:{name:`generic`,version:`unknown`,confidence:Math.max(...t.map(e=>n[e]??0),n.unknown??.5),deobfuscateStrategy:`Use the standard webcrack-backed deobfuscation path first, then escalate to targeted transforms based on detected techniques.`}}buildToolRecommendations(e,t){let n=new Map,r=(e,t,r)=>{n.has(e)||n.set(e,{tool:e,reason:t,suggestedArgs:r})};return(e.includes(`webpack`)||e.includes(`packer`))&&r(`webcrack_unpack`,`Bundle or wrapper markers detected; unpacking modules is likely the highest-value first step.`,{code:t,unpack:!0,unminify:!0}),e.some(e=>[`javascript-obfuscator`,`string-array-rotation`,`hex-encoding`,`base64-encoding`,`urlencoded`,`unknown`].includes(e))&&r(`deobfuscate`,`Static cleanup is likely sufficient; start with the standard webcrack-backed deobfuscation path.`,{code:t,unminify:!0}),e.some(e=>[`vm-protection`,`control-flow-flattening`,`dead-code-injection`,`opaque-predicates`,`invisible-unicode`,`jscrambler`,`jsfuck`,`aaencode`,`jjencode`].includes(e))&&r(`deobfuscate`,`Complex protections detected; use the advanced webcrack-backed flow for deeper cleanup.`,{code:t,engine:`webcrack`,detectOnly:!1,unminify:!0}),(e.includes(`eval-obfuscation`)||e.includes(`self-modifying`))&&r(`ai_hook`,`Runtime-generated code is present; capture or hook execution points before static cleanup if analysis stalls.`,{action:`inject`,target:`eval`,type:`function`}),n.size===0&&r(`deobfuscate`,`No strong signature matched; start with the standard webcrack-backed path.`,{code:t}),Array.from(n.values())}detectVMProtectionDetailed(e){try{return this.jsvmpDetector.detectJSVMP(e)}catch(n){return t.warn(`VM Protection detection failed`,n),this.detectVMProtection(e)?{instructionCount:0,interpreterLocation:`Unknown`,complexity:`medium`,hasSwitch:!0,hasInstructionArray:!1,hasProgramCounter:!1}:null}}detectJavaScriptObfuscator(e){return[/_0x[a-f0-9]{4,6}/i,/var\s+_0x[a-f0-9]+\s*=\s*\[/i,/\(function\s*\(_0x[a-f0-9]+,\s*_0x[a-f0-9]+\)/i,/while\s*\(!!\[\]\)/i].filter(t=>t.test(e)).length>=2}detectWebpack(e){return e.includes(`__webpack_require__`)||e.includes(`webpackJsonp`)||/\/\*\*\*\*\*\*\/\s*\(/m.test(e)}detectUglify(e){return(e.match(/\b[a-z]\b/g)?.length||0)>50}detectVMProtection(e){return[/while\s*\(\s*true\s*\)\s*\{[\s\S]*?switch\s*\(/i,/var\s+\w+\s*=\s*\[\s*\d+(?:\s*,\s*\d+){10,}\s*\]/i,/\w+\[pc\+\+\]/i,/stack\.push|stack\.pop/i].filter(t=>t.test(e)).length>=2}detectInvisibleUnicode(e){return[``,``,``,``,``].some(t=>e.includes(t))}detectControlFlowFlattening(e){return/while\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{[\s\S]*?switch\s*\(/i.test(e)}detectStringArrayRotation(e){return/var\s+\w+\s*=\s*\[.*?\];[\s\S]*?\(\s*function\s*\(\s*\w+,\s*\w+\s*\)/i.test(e)&&/\w+\s*=\s*\w+\s*\+\s*0x[0-9a-f]+/i.test(e)}detectDeadCodeInjection(e){return/if\s*\(\s*false\s*\)\s*\{/i.test(e)||/if\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{/i.test(e)}detectOpaquePredicates(e){return/if\s*\(\s*\d+\s*[<>!=]+\s*\d+\s*\)/i.test(e)}detectJSFuck(e){return/^[[\]()!+\s]+$/.test(e.substring(0,1e3))}detectAAEncode(e){return/゚ω゚|゚ω゚/.test(e)}detectJJEncode(e){return/\$=\{___:\+\+\$/.test(e)}detectPacker(e){return/eval\s*\(\s*function\s*\(\s*p\s*,\s*a\s*,\s*c\s*,\s*k\s*,\s*e\s*,\s*d\s*\)/i.test(e)}detectEvalObfuscation(e){return(e.match(/\beval\s*\(/g)||[]).length>=3}detectBase64Encoding(e){return e.includes(`atob(`)||/[A-Za-z0-9+/]{50,}={0,2}/.test(e)}detectHexEncoding(e){return(e.match(/\\x[0-9a-f]{2}/gi)||[]).length>20}detectSelfModifying(e){return e.includes(`Function(`)||e.includes(`new Function`)||/eval\s*\(\s*[^)]*\+/.test(e)}detectJScrambler(e){let t=0;return(/while\s*\(\s*!!\s*\[\s*\]\s*\)/.test(e)||/while\s*\(\s*true\s*\)\s*{[\s\S]*?switch/.test(e))&&(t+=3),e.includes(`debugger`)&&e.includes(`constructor`)&&(t+=2),/function\s+\w+\s*\([^)]*\)\s*{[\s\S]*?charCodeAt[\s\S]*?fromCharCode/.test(e)&&(t+=2),(e.includes(`Function.prototype.toString`)||e.includes(`.toString.call`))&&(t+=1),t>=3}detectURLEncode(e){return(e.match(/%[0-9A-Fa-f]{2}/g)?.length||0)>10}generateReport(e){let t=`=== Obfuscation Detection Report ===
|
|
324
|
+
|
|
325
|
+
`;return t+=`Classifier:
|
|
326
|
+
`,t+=` - name: ${e.classifier.name}\n`,t+=` - version: ${e.classifier.version}\n`,t+=` - confidence: ${(e.classifier.confidence*100).toFixed(0)}%\n`,t+=` - strategy: ${e.classifier.deobfuscateStrategy}\n`,t+=`Detected Types (${e.types.length}):\n`,e.types.forEach(n=>{let r=e.confidence[n]||0;t+=` - ${n}: ${(r*100).toFixed(0)}% confidence\n`}),t+=`
|
|
327
|
+
Features:
|
|
328
|
+
`,e.features.forEach(e=>{t+=` - ${e}\n`}),t+=`
|
|
329
|
+
Recommendations:
|
|
330
|
+
`,e.recommendations.forEach(e=>{t+=` - ${e}\n`}),e.toolRecommendations.length>0&&(t+=`
|
|
331
|
+
Suggested Tools:
|
|
332
|
+
`,e.toolRecommendations.forEach(e=>{t+=` - ${e.tool}: ${e.reason}\n`,e.suggestedArgs&&(t+=` args: ${JSON.stringify(e.suggestedArgs)}\n`)})),t}},lt=class{runtimeInspector;watches=new Map;watchCounter=0;constructor(e){this.runtimeInspector=e}addWatch(e,n){let r=`watch_${++this.watchCounter}`;return this.watches.set(r,{id:r,expression:e,name:n||e,enabled:!0,lastValue:void 0,lastError:null,valueHistory:[],createdAt:Date.now()}),t.info(`Watch expression added: ${r}`,{expression:e,name:n}),r}removeWatch(e){let n=this.watches.delete(e);return n&&t.info(`Watch expression removed: ${e}`),n}setWatchEnabled(e,n){let r=this.watches.get(e);return r?(r.enabled=n,t.info(`Watch expression ${n?`enabled`:`disabled`}: ${e}`),!0):!1}getAllWatches(){return Array.from(this.watches.values())}getWatch(e){return this.watches.get(e)}async evaluateAll(e,t=a){let n=[];for(let r of this.watches.values())if(r.enabled)try{let i=await Promise.race([this.runtimeInspector.evaluate(r.expression,e),new Promise((e,n)=>setTimeout(()=>n(Error(`Evaluation timeout after ${t}ms`)),t))]),a=!this.deepEqual(i,r.lastValue);a&&(r.valueHistory.push({value:i,timestamp:Date.now()}),r.valueHistory.length>100&&r.valueHistory.shift()),r.lastValue=i,r.lastError=null,n.push({watchId:r.id,name:r.name,expression:r.expression,value:i,error:null,valueChanged:a,timestamp:Date.now()})}catch(e){r.lastError=e,n.push({watchId:r.id,name:r.name,expression:r.expression,value:null,error:e,valueChanged:!1,timestamp:Date.now()})}return n}clearAll(){this.watches.clear(),t.info(`All watch expressions cleared`)}getValueHistory(e){let t=this.watches.get(e);return t?t.valueHistory:null}deepEqual(e,t){if(e===t)return!0;if(e==null||t==null||!this.isRecord(e)||!this.isRecord(t))return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!this.deepEqual(e[r],t[r]))return!1;return!0}isRecord(e){return typeof e==`object`&&!!e}exportWatches(){return Array.from(this.watches.values()).map(e=>({expression:e.expression,name:e.name,enabled:e.enabled}))}importWatches(e){for(let t of e){let e=this.addWatch(t.expression,t.name);t.enabled===!1&&this.setWatchEnabled(e,!1)}t.info(`Imported ${e.length} watch expressions`)}},ut=class{cdpSession;xhrBreakpoints=new Map;breakpointCounter=0;constructor(e){this.cdpSession=e,t.info(`XHRBreakpointManager initialized with shared CDP session`)}async setXHRBreakpoint(e){try{await this.cdpSession.send(`DOMDebugger.setXHRBreakpoint`,{url:e});let n=`xhr_${++this.breakpointCounter}`;return this.xhrBreakpoints.set(n,{id:n,urlPattern:e,enabled:!0,hitCount:0,createdAt:Date.now()}),t.info(`XHR breakpoint set: ${e}`,{breakpointId:n}),n}catch(e){throw t.error(`Failed to set XHR breakpoint:`,e),e}}async removeXHRBreakpoint(e){let n=this.xhrBreakpoints.get(e);if(!n)return!1;try{return await this.cdpSession.send(`DOMDebugger.removeXHRBreakpoint`,{url:n.urlPattern}),this.xhrBreakpoints.delete(e),t.info(`XHR breakpoint removed: ${e}`),!0}catch(e){throw t.error(`Failed to remove XHR breakpoint:`,e),e}}getAllXHRBreakpoints(){return Array.from(this.xhrBreakpoints.values())}getXHRBreakpoint(e){return this.xhrBreakpoints.get(e)}async clearAllXHRBreakpoints(){let e=Array.from(this.xhrBreakpoints.values());for(let n of e)try{await this.cdpSession.send(`DOMDebugger.removeXHRBreakpoint`,{url:n.urlPattern})}catch(e){t.warn(`Failed to remove XHR breakpoint ${n.id}:`,e)}this.xhrBreakpoints.clear(),t.info(`All XHR breakpoints cleared`)}async close(){try{await this.clearAllXHRBreakpoints(),t.info(`XHRBreakpointManager closed`)}catch(e){throw t.error(`Failed to close XHRBreakpointManager:`,e),e}}},dt=class e{cdpSession;eventBreakpoints=new Map;breakpointCounter=0;static MOUSE_EVENTS=[`click`,`dblclick`,`mousedown`,`mouseup`,`mousemove`,`mouseenter`,`mouseleave`];static KEYBOARD_EVENTS=[`keydown`,`keyup`,`keypress`];static TIMER_EVENTS=[`setTimeout`,`setInterval`,`requestAnimationFrame`];static WEBSOCKET_EVENTS=[`message`,`open`,`close`,`error`];constructor(e){this.cdpSession=e,t.info(`EventBreakpointManager initialized with shared CDP session`)}async setEventListenerBreakpoint(e,n){try{await this.cdpSession.send(`DOMDebugger.setEventListenerBreakpoint`,{eventName:e,targetName:n});let r=`event_${++this.breakpointCounter}`;return this.eventBreakpoints.set(r,{id:r,eventName:e,targetName:n,enabled:!0,hitCount:0,createdAt:Date.now()}),t.info(`Event listener breakpoint set: ${e}`,{breakpointId:r,targetName:n}),r}catch(e){throw t.error(`Failed to set event listener breakpoint:`,e),e}}async removeEventListenerBreakpoint(e){let n=this.eventBreakpoints.get(e);if(!n)return!1;try{return await this.cdpSession.send(`DOMDebugger.removeEventListenerBreakpoint`,{eventName:n.eventName,targetName:n.targetName}),this.eventBreakpoints.delete(e),t.info(`Event listener breakpoint removed: ${e}`),!0}catch(e){throw t.error(`Failed to remove event listener breakpoint:`,e),e}}async setMouseEventBreakpoints(){let n=[];for(let t of e.MOUSE_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} mouse event breakpoints`),n}async setKeyboardEventBreakpoints(){let n=[];for(let t of e.KEYBOARD_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} keyboard event breakpoints`),n}async setTimerEventBreakpoints(){let n=[];for(let t of e.TIMER_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} timer event breakpoints`),n}async setWebSocketEventBreakpoints(){let n=[];for(let t of e.WEBSOCKET_EVENTS){let e=await this.setEventListenerBreakpoint(t,`WebSocket`);n.push(e)}return t.info(`Set ${n.length} WebSocket event breakpoints`),n}getAllEventBreakpoints(){return Array.from(this.eventBreakpoints.values())}getEventBreakpoint(e){return this.eventBreakpoints.get(e)}async clearAllEventBreakpoints(){let e=Array.from(this.eventBreakpoints.values());for(let n of e)try{await this.cdpSession.send(`DOMDebugger.removeEventListenerBreakpoint`,{eventName:n.eventName,targetName:n.targetName})}catch(e){t.warn(`Failed to remove event breakpoint ${n.id}:`,e)}this.eventBreakpoints.clear(),t.info(`All event breakpoints cleared`)}async close(){try{await this.clearAllEventBreakpoints(),t.info(`EventBreakpointManager closed`)}catch(e){throw t.error(`Failed to close EventBreakpointManager:`,e),e}}},ft=class e{cdpSession;blackboxedPatterns=new Set;static COMMON_LIBRARY_PATTERNS=[`*jquery*.js`,`*react*.js`,`*react-dom*.js`,`*vue*.js`,`*angular*.js`,`*lodash*.js`,`*underscore*.js`,`*moment*.js`,`*axios*.js`,`*node_modules/*`,`*webpack*`,`*bundle*.js`,`*vendor*.js`];constructor(e){this.cdpSession=e,t.info(`BlackboxManager initialized with shared CDP session`)}normalizePattern(e){let t=String(e||``).trim();if(!t)throw Error(`Pattern cannot be empty`);if(t.includes(`*`)||t.includes(`?`))return t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`);try{return new RegExp(t),t}catch{return t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}}async blackboxByPattern(e){let n=this.normalizePattern(e);this.blackboxedPatterns.add(n);try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Blackboxed pattern: ${e} -> ${n}`)}catch(e){throw t.error(`Failed to set blackbox pattern:`,e),this.blackboxedPatterns.delete(n),e}}async unblackboxByPattern(e){let n=this.normalizePattern(e);if(!this.blackboxedPatterns.delete(n))return!1;try{return await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Unblackboxed pattern: ${e} -> ${n}`),!0}catch(e){throw t.error(`Failed to remove blackbox pattern:`,e),this.blackboxedPatterns.add(n),e}}async blackboxCommonLibraries(){for(let t of e.COMMON_LIBRARY_PATTERNS)this.blackboxedPatterns.add(this.normalizePattern(t));try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Blackboxed ${e.COMMON_LIBRARY_PATTERNS.length} common library patterns`)}catch(e){throw t.error(`Failed to blackbox common libraries:`,e),e}}getAllBlackboxedPatterns(){return Array.from(this.blackboxedPatterns)}async clearAllBlackboxedPatterns(){this.blackboxedPatterns.clear();try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:[]}),t.info(`All blackbox patterns cleared`)}catch(e){throw t.error(`Failed to clear blackbox patterns:`,e),e}}async close(){try{await this.clearAllBlackboxedPatterns(),t.info(`BlackboxManager closed`)}catch(e){throw t.error(`Failed to close BlackboxManager:`,e),e}}},pt=class{debuggerManager;SESSION_IMPORT_BATCH_SIZE=8;SESSION_FILE_READ_BATCH_SIZE=8;constructor(e){this.debuggerManager=e}async processInBatches(e,t,n){for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);await Promise.all(i.map(e=>n(e)))}}async readSessionFile(e){return k.readFile(e,`utf-8`)}async validateFilePath(e){let t=T.resolve(e),n=await k.realpath(process.cwd()),r=await k.realpath(pe.tmpdir()),i=T.dirname(t),a;try{a=await k.realpath(i)}catch{a=i}let o=T.join(a,T.basename(t)),s=o===n||o.startsWith(n+T.sep),c=o===r||o.startsWith(r+T.sep);if(!s&&!c)throw Error(`filePath must be within the current working directory or system temp dir.`);return o}exportSession(e){let n={version:`1.0`,timestamp:Date.now(),breakpoints:Array.from(this.debuggerManager.getBreakpoints().values()).map(e=>({location:{scriptId:e.location.scriptId,url:e.location.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber},condition:e.condition,enabled:e.enabled})),pauseOnExceptions:this.debuggerManager.getPauseOnExceptionsState(),metadata:e||{}};return t.info(`Session exported`,{breakpointCount:n.breakpoints.length,pauseOnExceptions:n.pauseOnExceptions}),n}async saveSession(e,n){let r=this.exportSession(n);if(e){e=await this.validateFilePath(e);let t=T.dirname(e);await k.mkdir(t,{recursive:!0})}else{let t=v();await k.mkdir(t,{recursive:!0}),e=T.join(t,`session-${Date.now()}.json`)}return await k.writeFile(e,JSON.stringify(r,null,2),`utf-8`),t.info(`Session saved to ${e}`,{breakpointCount:r.breakpoints.length}),e}async loadSessionFromFile(e){let n=await this.validateFilePath(e),r=await this.readSessionFile(n),i=JSON.parse(r);await this.importSession(i),t.info(`Session loaded from ${n}`,{breakpointCount:i.breakpoints.length})}async importSession(e){if(!this.debuggerManager.isEnabled())throw Error(`Debugger must be enabled before importing session. Call init() or enable() first.`);let n=typeof e==`string`?JSON.parse(e):e;n.version!==`1.0`&&t.warn(`Session version mismatch: ${n.version} (expected 1.0)`),t.info(`Importing session...`,{breakpointCount:n.breakpoints.length,pauseOnExceptions:n.pauseOnExceptions,timestamp:new Date(n.timestamp).toISOString()}),await this.debuggerManager.clearAllBreakpoints();let r=0,i=0;await this.processInBatches(n.breakpoints,this.SESSION_IMPORT_BATCH_SIZE,async e=>{try{e.location.url?(await this.debuggerManager.setBreakpointByUrl({url:e.location.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber,condition:e.condition}),r++):e.location.scriptId?(await this.debuggerManager.setBreakpoint({scriptId:e.location.scriptId,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber,condition:e.condition}),r++):(t.warn(`Breakpoint has neither url nor scriptId, skipping`,e),i++)}catch(n){t.error(`Failed to restore breakpoint:`,n,e),i++}}),n.pauseOnExceptions&&await this.debuggerManager.setPauseOnExceptions(n.pauseOnExceptions),t.info(`Session imported`,{totalBreakpoints:n.breakpoints.length,successCount:r,failCount:i,pauseOnExceptions:n.pauseOnExceptions})}async listSavedSessions(){let e=v();try{await k.access(e)}catch{return[]}let n=await k.readdir(e),r=[],i=n.filter(e=>e.endsWith(`.json`));return await this.processInBatches(i,this.SESSION_FILE_READ_BATCH_SIZE,async n=>{let i=T.join(e,n);try{let e=await this.readSessionFile(i),t=JSON.parse(e);r.push({path:i,timestamp:t.timestamp,metadata:t.metadata})}catch(e){t.warn(`Failed to read session file ${n}:`,e)}}),r.sort((e,t)=>t.timestamp-e.timestamp),r}};function G(e){return e}async function mt(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)try{await r.ensureSession()}catch(e){throw t.warn(`Debugger auto-reconnect failed: ${e instanceof Error?e.message:String(e)}`),new b(`Debugger is not enabled and auto-reconnect failed. Call init() or enable() first.`)}if(!n.url)throw Error(`url parameter is required`);if(n.lineNumber<0)throw Error(`lineNumber must be a non-negative number`);if(n.columnNumber!==void 0&&n.columnNumber<0)throw Error(`columnNumber must be a non-negative number`);try{let e=await r.cdpSession.send(`Debugger.setBreakpointByUrl`,{url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,condition:n.condition}),i={breakpointId:e.breakpointId,location:{url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition,enabled:!0,hitCount:0,createdAt:Date.now()};return r.breakpoints.set(e.breakpointId,i),t.info(`Breakpoint set: ${n.url}:${n.lineNumber}`,{breakpointId:e.breakpointId,condition:n.condition}),i}catch(e){throw t.error(`Failed to set breakpoint:`,e),e}}async function ht(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)try{await r.ensureSession()}catch(e){throw t.warn(`Debugger auto-reconnect failed: ${e instanceof Error?e.message:String(e)}`),new b(`Debugger is not enabled and auto-reconnect failed. Call init() or enable() first.`)}if(!n.scriptId)throw Error(`scriptId parameter is required`);if(n.lineNumber<0)throw Error(`lineNumber must be a non-negative number`);if(n.columnNumber!==void 0&&n.columnNumber<0)throw Error(`columnNumber must be a non-negative number`);try{let e=await r.cdpSession.send(`Debugger.setBreakpoint`,{location:{scriptId:n.scriptId,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition}),i={breakpointId:e.breakpointId,location:{scriptId:n.scriptId,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition,enabled:!0,hitCount:0,createdAt:Date.now()};return r.breakpoints.set(e.breakpointId,i),t.info(`Breakpoint set: scriptId=${n.scriptId}:${n.lineNumber}`,{breakpointId:e.breakpointId}),i}catch(e){throw t.error(`Failed to set breakpoint:`,e),e}}async function gt(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger is not enabled. Call init() or enable() first.`);if(!n)throw Error(`breakpointId parameter is required`);if(!r.breakpoints.has(n))throw Error(`Breakpoint not found: ${n}. Use listBreakpoints() to see active breakpoints.`);try{await r.cdpSession.send(`Debugger.removeBreakpoint`,{breakpointId:n}),r.breakpoints.delete(n),t.info(`Breakpoint removed: ${n}`)}catch(e){throw t.error(`Failed to remove breakpoint ${n}:`,e),e}}function _t(e){let t=G(e);return Array.from(t.breakpoints.values())}function vt(e,t){return G(e).breakpoints.get(t)}async function yt(e){let n=G(e),r=Array.from(n.breakpoints.keys());for(let e of r)await n.removeBreakpoint(e);t.info(`Cleared ${r.length} breakpoints`)}function K(e){return e}async function bt(e,n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger not enabled`);try{await r.cdpSession.send(`Debugger.setPauseOnExceptions`,{state:n}),r.pauseOnExceptionsState=n,t.info(`Pause on exceptions set to: ${n}`)}catch(e){throw t.error(`Failed to set pause on exceptions:`,e),e}}function xt(e){return K(e).pauseOnExceptionsState}async function St(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.pause`),t.info(`Execution paused`)}catch(e){throw t.error(`Failed to pause execution:`,e),e}}async function Ct(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.resume`),t.info(`Execution resumed`)}catch(e){let n=e instanceof Error?e.message:String(e);if(n.includes(`not paused`)||n.includes(`cannot be resumed`)||n.includes(`while paused`)){t.warn(`Debugger resume skipped: not currently paused`);return}throw t.error(`Failed to resume execution:`,e),e}}async function wt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepInto`),t.info(`Step into`)}catch(e){throw t.error(`Failed to step into:`,e),e}}async function Tt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepOver`),t.info(`Step over`)}catch(e){throw t.error(`Failed to step over:`,e),e}}async function Et(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepOut`),t.info(`Step out`)}catch(e){throw t.error(`Failed to step out:`,e),e}}function Dt(e){return K(e).pausedState}function Ot(e){return K(e).pausedState!==null}async function kt(e,t=i){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger is not enabled. Call init() or enable() first.`);return n.pausedState?n.pausedState:new Promise((e,r)=>{let i=setTimeout(()=>{let t=n.pausedResolvers.indexOf(e);t>-1&&n.pausedResolvers.splice(t,1),r(Error(`Timeout waiting for paused event`))},t);n.pausedResolvers.push(t=>{clearTimeout(i),e(t)})})}async function At(e,n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger not enabled`);if(!r.pausedState)throw new b(`Not in paused state`);try{let e=await r.cdpSession.send(`Debugger.evaluateOnCallFrame`,{callFrameId:n.callFrameId,expression:n.expression,returnByValue:n.returnByValue!==!1});return t.info(`Evaluated on call frame: ${n.expression}`,{result:e.result.value}),e.result}catch(e){throw t.error(`Failed to evaluate on call frame:`,e),e}}function q(e){return e}function J(e){return e instanceof Error?e.message:String(e)}async function jt(e,n={}){let r=q(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger not enabled. Call init() or enable() first.`);if(!r.pausedState)throw new b(`Not in paused state. Use pause() or set a breakpoint first.`);let{callFrameId:i,includeObjectProperties:a=!1,maxDepth:o=1,skipErrors:s=!0}=n;try{let e=i?r.pausedState.callFrames.find(e=>e.callFrameId===i):r.pausedState.callFrames[0];if(!e)throw Error(`Call frame not found: ${i||`top frame`}`);let n=[],c=[],l=0;for(let i of e.scopeChain)try{if(i.object.objectId){let e=await r.cdpSession.send(`Runtime.getProperties`,{objectId:i.object.objectId,ownProperties:!0});for(let s of e.result){if(s.name===`__proto__`)continue;let e={name:s.name,value:s.value?.value,type:s.value?.type||`unknown`,scope:i.type,writable:s.writable,configurable:s.configurable,enumerable:s.enumerable,objectId:s.value?.objectId};if(n.push(e),a&&s.value?.objectId&&o>0)try{let e=await Y(r,s.value.objectId,o-1);for(let t of e)n.push({...t,name:`${s.name}.${t.name}`,scope:i.type})}catch(e){t.debug(`Failed to get nested properties for ${s.name}:`,e)}}l++}}catch(e){let n=J(e);if(t.warn(`Failed to get properties for scope ${i.type}:`,n),c.push({scope:i.type,error:n}),!s)throw e}let u={success:!0,variables:n,callFrameId:e.callFrameId,callFrameInfo:{functionName:e.functionName||`(anonymous)`,location:`${e.url}:${e.location.lineNumber}:${e.location.columnNumber}`},totalScopes:e.scopeChain.length,successfulScopes:l};return c.length>0&&(u.errors=c),t.info(`Got ${n.length} variables from ${l}/${e.scopeChain.length} scopes`,{callFrameId:e.callFrameId,functionName:e.functionName,errors:c.length}),u}catch(e){throw t.error(`Failed to get scope variables:`,e),e}}async function Mt(e,t){let n=q(e);if(!n.enabled||!n.cdpSession)throw Error(`Debugger not enabled`);if(!t||typeof t!=`string`)throw Error(`objectId parameter is required`);try{let e=await n.cdpSession.send(`Runtime.getProperties`,{objectId:t,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),r=[];for(let t of e.result)t.value&&r.push({name:t.name,value:t.value.value??t.value.description,type:t.value.type||`unknown`,objectId:t.value.objectId,className:t.value.className,description:t.value.description});return r}catch(e){let t=J(e);throw t.includes(`Could not find object with given id`)||t.includes(`Invalid remote object id`)?Error(`Object handle is expired or invalid. Pause execution again and reacquire objectId from get_scope_variables_enhanced.`,{cause:e}):e}}async function Y(e,n,r){let i=q(e);if(r<=0||!i.cdpSession)return[];try{let e=await i.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0}),t=[];for(let n of e.result)n.name!==`__proto__`&&t.push({name:n.name,value:n.value?.value,type:n.value?.type||`unknown`,scope:`local`,objectId:n.value?.objectId});return t}catch(e){return t.debug(`Failed to get object properties for ${n}:`,e),[]}}function X(e){return e}function Nt(e,n){let r=X(e);r.breakpointHitCallbacks.add(n),t.info(`Breakpoint hit callback registered`,{totalCallbacks:r.breakpointHitCallbacks.size})}function Pt(e,n){let r=X(e);r.breakpointHitCallbacks.delete(n),t.info(`Breakpoint hit callback removed`,{totalCallbacks:r.breakpointHitCallbacks.size})}function Ft(e){X(e).breakpointHitCallbacks.clear(),t.info(`All breakpoint hit callbacks cleared`)}function It(e){return X(e).breakpointHitCallbacks.size}async function Lt(e,n){let r=X(e);if(r.pausedState={callFrames:n.callFrames,reason:n.reason,data:n.data,hitBreakpoints:n.hitBreakpoints,timestamp:Date.now()},n.hitBreakpoints)for(let e of n.hitBreakpoints){let t=r.breakpoints.get(e);t&&t.hitCount++}if(t.info(`Execution paused`,{reason:n.reason,location:n.callFrames[0]?.location,hitBreakpoints:n.hitBreakpoints}),n.hitBreakpoints&&n.hitBreakpoints.length>0&&r.breakpointHitCallbacks.size>0){let e=n.hitBreakpoints[0],i=n.callFrames[0],a;try{a=(await r.getScopeVariables({skipErrors:!0})).variables}catch(e){t.debug(`Failed to auto-fetch variables for breakpoint hit callback:`,e)}let o={breakpointId:e,breakpointInfo:r.breakpoints.get(e),location:{scriptId:i.location.scriptId,lineNumber:i.location.lineNumber,columnNumber:i.location.columnNumber,url:i.url},callFrames:n.callFrames,timestamp:Date.now(),variables:a,reason:n.reason};for(let e of r.breakpointHitCallbacks)try{await Promise.resolve(e(o))}catch(e){t.error(`Breakpoint hit callback error:`,e)}}for(let e of r.pausedResolvers)e(r.pausedState);r.pausedResolvers=[]}function Rt(e){let n=X(e);n.pausedState=null,t.info(`Execution resumed`)}function zt(e,n){X(e).breakpoints.get(n.breakpointId)&&t.info(`Breakpoint resolved`,{breakpointId:n.breakpointId,location:n.location})}var Bt=class{collector;cdpSession=null;enabled=!1;initPromise;breakpoints=new Map;pausedState=null;pausedResolvers=[];breakpointHitCallbacks=new Set;pauseOnExceptionsState=`none`;watchManager=null;xhrManager=null;eventManager=null;blackboxManager=null;advancedFeatureSession=null;pausedListener=null;resumedListener=null;breakpointResolvedListener=null;sessionManager;constructor(e){this.collector=e,this.sessionManager=new pt(this),this.touchInternalStateForTypeCheck()}touchInternalStateForTypeCheck(){this.pausedState,this.pausedResolvers,this.breakpointHitCallbacks,this.pauseOnExceptionsState}getBreakpoints(){return this.breakpoints}getCDPSession(){if(!this.cdpSession||!this.enabled)throw Error(`Debugger not enabled. Call init() or enable() first to get CDP session.`);return this.cdpSession}getWatchManager(){if(!this.watchManager)throw Error(`WatchExpressionManager not initialized. Call initAdvancedFeatures() first.`);return this.watchManager}getXHRManager(){if(!this.xhrManager)throw Error(`XHRBreakpointManager not initialized. Call initAdvancedFeatures() first.`);return this.xhrManager}getEventManager(){if(!this.eventManager)throw Error(`EventBreakpointManager not initialized. Call initAdvancedFeatures() first.`);return this.eventManager}getBlackboxManager(){if(!this.blackboxManager)throw Error(`BlackboxManager not initialized. Call initAdvancedFeatures() first.`);return this.blackboxManager}async init(){if(!this.enabled){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){try{let e=await this.collector.getActivePage();this.cdpSession=await e.createCDPSession(),this.cdpSession.on(`disconnected`,()=>{t.warn(`CDP session disconnected, marking as disabled`),this.enabled=!1,this.cdpSession=null,this.advancedFeatureSession=null,this.xhrManager=null,this.eventManager=null,this.blackboxManager=null}),await this.cdpSession.send(`Debugger.enable`),this.enabled=!0,this.pausedListener=e=>this.handlePaused(e),this.resumedListener=()=>this.handleResumed(),this.breakpointResolvedListener=e=>this.handleBreakpointResolved(e),this.cdpSession.on(`Debugger.paused`,this.pausedListener),this.cdpSession.on(`Debugger.resumed`,this.resumedListener),this.cdpSession.on(`Debugger.breakpointResolved`,this.breakpointResolvedListener),t.info(`Debugger enabled successfully`)}catch(e){throw t.error(`Failed to enable debugger:`,e),e}}async ensureSession(){if(!this.enabled||!this.cdpSession){t.info(`CDP session not active, reinitializing...`),await this.init();return}try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{t.warn(`Debugger CDP session unresponsive (zombie), reinitializing...`),this.enabled=!1,this.cdpSession=null,this.advancedFeatureSession=null,this.xhrManager=null,this.eventManager=null,this.blackboxManager=null,this.watchManager=null,await this.init()}}isSessionConnected(){return this.enabled&&this.cdpSession!==null}async enable(){return this.init()}async initAdvancedFeatures(e){if(!this.enabled||!this.cdpSession)throw Error(`Debugger must be enabled before initializing advanced features. Call init() first.`);try{e&&(this.watchManager=new lt(e),t.info(`WatchExpressionManager initialized`)),this.xhrManager=new ut(this.cdpSession),t.info(`XHRBreakpointManager initialized`),this.eventManager=new dt(this.cdpSession),t.info(`EventBreakpointManager initialized`),this.blackboxManager=new ft(this.cdpSession),t.info(`BlackboxManager initialized`),this.advancedFeatureSession=this.cdpSession,t.info(`All advanced debugging features initialized`)}catch(e){throw t.error(`Failed to initialize advanced features:`,e),e}}async ensureAdvancedFeatures(){if(await this.ensureSession(),!this.cdpSession)throw Error(`CDP session unavailable after reconnect.`);(this.advancedFeatureSession!==this.cdpSession||!this.xhrManager||!this.eventManager||!this.blackboxManager)&&await this.initAdvancedFeatures()}async disable(){if(!this.enabled||!this.cdpSession){t.warn(`Debugger not enabled`);return}try{this.xhrManager&&=(await this.xhrManager.close(),null),this.eventManager&&=(await this.eventManager.close(),null),this.blackboxManager&&=(await this.blackboxManager.close(),null),this.watchManager&&=(this.watchManager.clearAll(),null),this.pausedListener&&=(this.cdpSession.off(`Debugger.paused`,this.pausedListener),null),this.resumedListener&&=(this.cdpSession.off(`Debugger.resumed`,this.resumedListener),null),this.breakpointResolvedListener&&=(this.cdpSession.off(`Debugger.breakpointResolved`,this.breakpointResolvedListener),null),await this.cdpSession.send(`Debugger.disable`)}catch(e){t.error(`Failed to disable debugger:`,e)}finally{if(this.initPromise=void 0,this.enabled=!1,this.breakpoints.clear(),this.pausedState=null,this.pausedResolvers=[],this.advancedFeatureSession=null,this.cdpSession){try{await this.cdpSession.detach()}catch(e){t.warn(`Failed to detach CDP session:`,e)}this.cdpSession=null}t.info(`Debugger disabled and cleaned up`)}}isEnabled(){return this.enabled}async setBreakpointByUrl(e){return mt(this,e)}async setBreakpoint(e){return ht(this,e)}async removeBreakpoint(e){return gt(this,e)}listBreakpoints(){return _t(this)}getBreakpoint(e){return vt(this,e)}async clearAllBreakpoints(){return yt(this)}async setPauseOnExceptions(e){return bt(this,e)}getPauseOnExceptionsState(){return xt(this)}async pause(){return St(this)}async resume(){return Ct(this)}async stepInto(){return wt(this)}async stepOver(){return Tt(this)}async stepOut(){return Et(this)}getPausedState(){return Dt(this)}isPaused(){return Ot(this)}async waitForPaused(e=i){return kt(this,e)}async evaluateOnCallFrame(e){return At(this,e)}async getScopeVariables(e={}){return jt(this,e)}async getObjectPropertiesById(e){return Mt(this,e)}async getObjectProperties(e,t){return Y(this,e,t)}onBreakpointHit(e){Nt(this,e)}offBreakpointHit(e){Pt(this,e)}clearBreakpointHitCallbacks(){Ft(this)}getBreakpointHitCallbackCount(){return It(this)}async handlePaused(e){return Lt(this,this.normalizePausedEventParams(e))}handleResumed(){Rt(this)}handleBreakpointResolved(e){zt(this,this.normalizeBreakpointResolvedParams(e))}exportSession(e){return this.sessionManager.exportSession(e)}async saveSession(e,t){return this.sessionManager.saveSession(e,t)}async loadSessionFromFile(e){return this.sessionManager.loadSessionFromFile(e)}async importSession(e){return this.sessionManager.importSession(e)}async listSavedSessions(){return this.sessionManager.listSavedSessions()}async close(){this.initPromise=void 0,this.enabled&&await this.disable(),this.cdpSession&&=(await this.cdpSession.detach(),null),t.info(`Debugger manager closed`)}normalizePausedEventParams(e){let t=this.asRecord(e);return{callFrames:(Array.isArray(t.callFrames)?t.callFrames:[]).map(e=>this.normalizeCallFrame(e)),reason:typeof t.reason==`string`?t.reason:`unknown`,data:t.data,hitBreakpoints:Array.isArray(t.hitBreakpoints)?t.hitBreakpoints.filter(e=>typeof e==`string`):void 0}}normalizeBreakpointResolvedParams(e){let t=this.asRecord(e);return{breakpointId:typeof t.breakpointId==`string`?t.breakpointId:``,location:t.location}}normalizeCallFrame(e){let t=this.asRecord(e),n=this.asRecord(t.location),r=Array.isArray(t.scopeChain)?t.scopeChain:[];return{callFrameId:typeof t.callFrameId==`string`?t.callFrameId:``,functionName:typeof t.functionName==`string`?t.functionName:``,location:{scriptId:typeof n.scriptId==`string`?n.scriptId:``,lineNumber:typeof n.lineNumber==`number`?n.lineNumber:0,columnNumber:typeof n.columnNumber==`number`?n.columnNumber:0},url:typeof t.url==`string`?t.url:``,scopeChain:r.map(e=>this.normalizeScope(e)),this:t.this}}normalizeScope(e){let t=this.asRecord(e),n=this.asRecord(t.object),r=this.normalizeScriptLocation(t.startLocation),i=this.normalizeScriptLocation(t.endLocation);return{type:this.normalizeScopeType(t.type),object:{type:typeof n.type==`string`?n.type:`object`,objectId:typeof n.objectId==`string`?n.objectId:void 0,className:typeof n.className==`string`?n.className:void 0,description:typeof n.description==`string`?n.description:void 0},name:typeof t.name==`string`?t.name:void 0,startLocation:r,endLocation:i}}normalizeScriptLocation(e){let t=this.asRecord(e);if(Object.keys(t).length!==0)return{scriptId:typeof t.scriptId==`string`?t.scriptId:``,lineNumber:typeof t.lineNumber==`number`?t.lineNumber:0,columnNumber:typeof t.columnNumber==`number`?t.columnNumber:0}}normalizeScopeType(e){return e===`global`||e===`local`||e===`with`||e===`closure`||e===`catch`||e===`block`||e===`script`||e===`eval`||e===`module`?e:`local`}asRecord(e){return typeof e==`object`&&e?e:{}}},Vt=class{collector;debuggerManager;cdpSession=null;enabled=!1;initPromise;constructor(e,t){this.collector=e,this.debuggerManager=t}async init(){if(!this.enabled){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){try{let e=await this.collector.getActivePage();this.cdpSession=await e.createCDPSession(),await this.cdpSession.send(`Runtime.enable`),this.enabled=!0,t.info(`Runtime inspector enabled`)}catch(e){throw t.error(`Failed to enable runtime inspector:`,e),e}}async enable(){return this.init()}async enableAsyncStackTraces(e=32){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector not enabled. Call init() or enable() first.`);try{await this.cdpSession.send(`Debugger.setAsyncCallStackDepth`,{maxDepth:e}),t.info(`Async stack traces enabled with max depth: ${e}`)}catch(e){throw t.error(`Failed to enable async stack traces:`,e),e}}async disableAsyncStackTraces(){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector not enabled`);try{await this.cdpSession.send(`Debugger.setAsyncCallStackDepth`,{maxDepth:0}),t.info(`Async stack traces disabled`)}catch(e){throw t.error(`Failed to disable async stack traces:`,e),e}}async disable(){if(!(!this.enabled||!this.cdpSession))try{await this.cdpSession.send(`Runtime.disable`),this.enabled=!1,await this.cdpSession.detach(),this.cdpSession=null,t.info(`Runtime inspector disabled and cleaned up`)}catch(e){throw t.error(`Failed to disable runtime inspector:`,e),e}finally{this.initPromise=void 0}}async getCallStack(){let e=this.debuggerManager.getPausedState();if(!e)return t.warn(`Not in paused state, cannot get call stack`),null;try{let n={callFrames:e.callFrames.map(e=>({callFrameId:e.callFrameId,functionName:e.functionName||`(anonymous)`,location:{scriptId:e.location.scriptId,url:e.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber},scopeChain:e.scopeChain.map(e=>({type:e.type,name:e.name}))})),reason:e.reason,timestamp:e.timestamp};return t.info(`Call stack retrieved`,{frameCount:n.callFrames.length,topFrame:n.callFrames[0]?.functionName}),n}catch(e){throw t.error(`Failed to get call stack:`,e),e}}async getScopeVariables(e){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e)throw Error(`callFrameId parameter is required`);let n=this.debuggerManager.getPausedState();if(!n)throw new b(`Not in paused state. Debugger must be paused to get scope variables.`);let r=n.callFrames.find(t=>t.callFrameId===e);if(!r)throw Error(`Call frame not found: ${e}. Use getCallStack() to see available frames.`);try{let n=[];for(let e of r.scopeChain){if(!e.object.objectId)continue;let t=await this.getObjectProperties(e.object.objectId);n.push({scopeType:e.type,scopeName:e.name,variables:t})}return t.info(`Scope variables retrieved for call frame ${e}`,{scopeCount:n.length}),n}catch(e){throw t.error(`Failed to get scope variables:`,e),e}}async getCurrentScopeVariables(){let e=this.debuggerManager.getPausedState();if(!e||e.callFrames.length===0)throw new b(`Not in paused state or no call frames`);let t=e.callFrames[0];if(!t)throw new b(`No top frame available`);return await this.getScopeVariables(t.callFrameId)}async getObjectProperties(e){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e)throw Error(`objectId parameter is required`);try{let n=await this.cdpSession.send(`Runtime.getProperties`,{objectId:e,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),r=[];for(let e of n.result)e.value&&r.push({name:e.name,value:this.formatValue(e.value),type:e.value.type||`unknown`,objectId:e.value.objectId,className:e.value.className,description:e.value.description});return t.info(`Object properties retrieved: ${e}`,{propertyCount:r.length}),r}catch(e){throw t.error(`Failed to get object properties:`,e),e}}async evaluate(e,n){if(!e||e.trim()===``)throw Error(`expression parameter is required and cannot be empty`);let r=this.debuggerManager.getPausedState();if(!r)throw new b(`Not in paused state. Use evaluateGlobal() for global context evaluation.`);let i=n||r.callFrames[0]?.callFrameId;if(!i)throw new b(`No call frame available for evaluation`);try{let n=await this.debuggerManager.evaluateOnCallFrame({callFrameId:i,expression:e,returnByValue:!0});return t.info(`Expression evaluated: ${e}`,{result:n.value}),this.formatValue(n)}catch(e){throw t.error(`Failed to evaluate expression:`,e),e}}async evaluateGlobal(e){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e||e.trim()===``)throw Error(`expression parameter is required and cannot be empty`);try{let n=await this.cdpSession.send(`Runtime.evaluate`,{expression:e,returnByValue:!0});return t.info(`Global expression evaluated: ${e}`,{result:n.result.value}),this.formatValue(n.result)}catch(e){throw t.error(`Failed to evaluate global expression:`,e),e}}formatValue(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.type!==`undefined`)return t.type===`object`&&t.subtype===`null`?null:t.value===void 0?t.description?t.description:`[${t.type||`unknown`}]`:t.value}async close(){this.initPromise=void 0,this.enabled&&await this.disable(),this.cdpSession&&=(await this.cdpSession.detach(),null),t.info(`Runtime inspector closed`)}};const Ht=o,Z=s,Ut=r;function Wt(){return[process.env.TEMP,process.env.TMP,oe(),`/tmp`,`/var/tmp`].filter(e=>!!e)}var Gt=class{registry;constructor(e){this.registry=e}async probeAll(e=!1){return this.registry.probeAll(e)}async run(e){return x(()=>this.runInternal(e))}async runInternal(e){let r=this.registry.getSpec(e.tool),i=this.registry.getCachedProbe(e.tool);if(i&&!i.available)return{ok:!1,exitCode:null,signal:null,stdout:``,stderr:`Tool '${e.tool}' (${r.command}) is not available: ${i.reason}`,durationMs:0,truncated:!1};let a=this.validateCwd(e.cwd),o=[...r.defaultArgs||[],...e.args],s={PATH:process.env.PATH||``};if(process.platform===`win32`){let e=process.env.SYSTEMROOT||process.env.SystemRoot||process.env.WINDIR;e&&(s.SYSTEMROOT=e),process.env.TEMP&&(s.TEMP=process.env.TEMP),process.env.TMP&&(s.TMP=process.env.TMP)}if(r.envAllowlist)for(let e of r.envAllowlist)process.env[e]&&(s[e]=process.env[e]);let l=e.timeoutMs??Ht,u=e.maxStdoutBytes??Z,d=e.maxStderrBytes??Ut;t.debug(`[ExternalToolRunner] Running: ${r.command} ${o.join(` `)}`);let f=Date.now();return new Promise(i=>{let p=ue(r.command,o,{cwd:a,env:s,shell:!1,windowsHide:!0,stdio:[`pipe`,`pipe`,`pipe`]});c.register(p);let m=[],h=[],g=0,_=0,v=!1,y=!1,b=!1,x=setTimeout(()=>{b||(p.kill(`SIGTERM`),setTimeout(()=>{b||(p.kill(`SIGKILL`),S(null,`SIGKILL`))},n),e.onProgress?.({phase:`timeout`,ts:Date.now()}))},l),S=(e,n)=>{if(b)return;b=!0,clearTimeout(x);let a=m.length===1?m[0].toString(`utf-8`):m.length>1?Buffer.concat(m).toString(`utf-8`):``,o=h.length===1?h[0].toString(`utf-8`):h.length>1?Buffer.concat(h).toString(`utf-8`):``;m=[],h=[];let s=Date.now()-f,c={ok:e===0,exitCode:e,signal:n,stdout:a,stderr:o,durationMs:s,truncated:v||y};c.ok?t.debug(`[ExternalToolRunner] ${r.command} completed in ${s}ms`):t.warn(`[ExternalToolRunner] ${r.command} failed (exit=${e}, signal=${n}) in ${s}ms`),i(c)};e.stdin&&p.stdin.write(e.stdin),p.stdin.end(),p.stdout.on(`data`,t=>{if(g<u){let e=u-g,n=t.length<=e?t:t.subarray(0,e);m.push(n),g+=n.length,g>=u&&(v=!0)}e.onProgress?.({phase:`stdout`,bytesRead:g,ts:Date.now()})}),p.stderr.on(`data`,t=>{if(_<d){let e=d-_,n=t.length<=e?t:t.subarray(0,e);h.push(n),_+=n.length,_>=d&&(y=!0)}e.onProgress?.({phase:`stderr`,bytesRead:_,ts:Date.now()})}),p.on(`close`,(e,t)=>{S(e,t)}),p.on(`error`,e=>{let t=Buffer.from(`\nSpawn error: ${e.message}`,`utf-8`);h.push(t),_+=t.length,S(1,null)}),e.onProgress?.({phase:`spawn`,ts:Date.now()})})}validateCwd(e){if(!e)return _();let n=D(e),r=_(),i=ce(r,n);if(i&&!i.startsWith(`..`)&&!se(i))return n;let a=Wt();for(let e of a){let t=D(e);if(n===t||n.startsWith(t+le))return n}return t.warn(`[ExternalToolRunner] CWD '${e}' outside allowed boundaries, using project root`),r}};function Kt(e,t,n,r,i,a=!1){switch(t){case`function`:return p(e,n,r,i,a);case`xhr`:return he(n,r,i,a);case`fetch`:return ge(n,r,i,a);case`websocket`:return _e(n,r,i,a);case`localstorage`:return f(n,r,i,a);case`cookie`:return g(n,r,i,a);case`eval`:return l(n,r,i,a);case`object-method`:return u(e,n,r,i,a);default:throw Error(`Unsupported hook type: ${t}`)}}var qt=class{hooks=new Map;hookScripts=new Map;hookMetadata=new Map;hookConditions=new Map;MAX_HOOK_RECORDS=1e3;MAX_TOTAL_RECORDS=1e4;MAX_HOOKS=200;async createHook(e){if(this.hookScripts.size>=this.MAX_HOOKS){let e=null,n=1/0;for(let[t,r]of this.hookMetadata)r.createdAt<n&&(n=r.createdAt,e=t);e&&(t.warn(`Hook limit (${this.MAX_HOOKS}) reached, evicting oldest: ${e}`),this.deleteHook(e))}t.info(`Creating hook for ${e.target} (type: ${e.type})...`);try{let{target:n,type:r,action:i=`log`,condition:a,performance:o=!1}=e,s=Kt(n,r,i,e.customCode,a,o),c=`${n}-${r}-${Date.now()}`;return this.hookScripts.set(c,s),a&&this.hookConditions.set(c,a),this.hookMetadata.set(c,{id:c,enabled:!0,createdAt:Date.now(),callCount:0,totalExecutionTime:0}),t.success(`Hook created: ${c}`),{hookId:c,script:s,instructions:m(r)}}catch(e){throw t.error(`Failed to create hook`,e),e}}recordHookEvent(e,n){let r={hookId:e,timestamp:Date.now(),context:n},i=this.hooks.get(e)||[];i.push(r),this.hooks.set(e,i),t.debug(`Hook event recorded: ${e}`)}getHookRecords(e){return this.hooks.get(e)||[]}clearHookRecords(e){e?(this.hooks.delete(e),t.info(`Cleared records for hook: ${e}`)):(this.hooks.clear(),t.info(`Cleared all hook records`))}enableHook(e){let n=this.hookMetadata.get(e);n?(n.enabled=!0,t.info(`Hook enabled: ${e}`)):t.warn(`Hook not found: ${e}`)}disableHook(e){let n=this.hookMetadata.get(e);n?(n.enabled=!1,t.info(`Hook disabled: ${e}`)):t.warn(`Hook not found: ${e}`)}getHookMetadata(e){return this.hookMetadata.get(e)}getAllHookMetadata(){return Array.from(this.hookMetadata.values())}exportHookData(e){if(e){let t=this.hookMetadata.get(e),n=this.hooks.get(e)||[],r=this.hookScripts.get(e)||``;return{metadata:t?[t]:[],records:{[e]:n},scripts:{[e]:r}}}let t=Array.from(this.hookMetadata.values()),n={},r={};return this.hooks.forEach((e,t)=>{n[t]=e}),this.hookScripts.forEach((e,t)=>{r[t]=e}),{metadata:t,records:n,scripts:r}}getHookStats(e){let t=this.hookMetadata.get(e);return t?{callCount:t.callCount,avgExecutionTime:t.callCount>0?t.totalExecutionTime/t.callCount:0,totalExecutionTime:t.totalExecutionTime,enabled:t.enabled}:null}deleteHook(e){this.hookScripts.delete(e),this.hookMetadata.delete(e),this.hookConditions.delete(e),this.hooks.delete(e),t.info(`Hook deleted: ${e}`)}getAllHooks(){return Array.from(this.hookScripts.keys())}recordHookCall(e,n){this.hooks.has(e)||this.hooks.set(e,[]);let r=this.hooks.get(e);r.length>=this.MAX_HOOK_RECORDS&&(r.shift(),t.debug(`Hook ${e} reached max records, removed oldest`)),r.push(n),Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0)>this.MAX_TOTAL_RECORDS&&this.cleanupOldestRecords();let i=this.hookMetadata.get(e);i&&(i.callCount++,i.lastCalled=Date.now())}cleanupOldestRecords(){let e=null,n=1/0;for(let[t,r]of this.hooks.entries())if(r.length>0){let i=r[0];i&&i.timestamp<n&&(n=i.timestamp,e=t)}if(e){let n=this.hooks.get(e),r=Math.floor(n.length/2);n.splice(0,r),t.warn(`Cleaned up ${r} old records from ${e} (total records exceeded limit)`)}}getHookRecordsStats(){let e=0,t=null,n=null,r={};for(let[i,a]of this.hooks.entries())if(r[i]=a.length,e+=a.length,a.length>0){let e=a[0],r=a[a.length-1];if(e){let n=e.timestamp;(t===null||n<t)&&(t=n)}if(r){let e=r.timestamp;(n===null||e>n)&&(n=e)}}return{totalHooks:this.hooks.size,totalRecords:e,recordsByHook:r,oldestRecord:t,newestRecord:n}}async createBatchHooks(e){t.info(`Creating ${e.length} hooks...`);let n=[];for(let{target:r,type:i,action:a=`log`}of e)try{let e=await this.createHook({target:r,type:i,action:a});n.push(e)}catch(e){t.error(`Failed to create hook for ${r}:`,e)}return t.success(`Created ${n.length}/${e.length} hooks`),n}generateAntiDebugBypass(){return d()}generateHookTemplate(e,t){return h(e,t)}generateHookChain(e){return N(e)}};function Q(e){return typeof e==`object`&&!!e}function Jt(e){return Q(e)&&typeof e.chunk==`string`}function Yt(e){if(!Q(e))return!1;let{callFrame:t,selfSize:n,children:r}=e;return!(t!==void 0&&(!Q(t)||t.functionName!==void 0&&typeof t.functionName!=`string`||t.url!==void 0&&typeof t.url!=`string`)||n!==void 0&&typeof n!=`number`||r!==void 0&&!Array.isArray(r))}function Xt(e){return Q(e)&&Q(e.profile)&&Yt(e.profile.head)}async function $(){await me()}function Zt(e){let t=/"ph"\s*:/g,n=0;for(;t.exec(e)!==null;)n++;return n}function Qt(e,t,n){if(n<=0||e.length===n&&t.selfSize<=e[e.length-1].selfSize)return;let r=e.findIndex(e=>t.selfSize>e.selfSize);r===-1&&(r=e.length),e.splice(r,0,t),e.length>n&&(e.length=n)}function $t(e,t){let n=[e],r=[],i=0;for(;n.length>0;){let e=n.pop();if(e&&(e.callFrame&&(i++,Qt(r,{functionName:e.callFrame.functionName||`(anonymous)`,url:e.callFrame.url||``,selfSize:e.selfSize||0},t)),Array.isArray(e.children)))for(let t=e.children.length-1;t>=0;t--){let r=e.children[t];r&&n.push(r)}}return{sampleCount:i,topAllocations:r}}async function en(e){await Promise.race([e.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_unreachable`)),500))])}var tn=class{collector;cdpSession=null;coverageEnabled=!1;profilerEnabled=!1;tracingEnabled=!1;heapSamplingEnabled=!1;coveragePage=null;tracingPage=null;constructor(e){this.collector=e}async ensureCDPSession(){if(!this.cdpSession){let e=await this.collector.getActivePage();return this.cdpSession=await Promise.race([e.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),this.cdpSession}try{return await en(this.cdpSession),this.cdpSession}catch(e){if((e instanceof Error?e.message:String(e))!==`cdp_unreachable`)throw e;t.warn(`PerformanceMonitor CDP session unresponsive, recreating...`);try{await this.cdpSession.detach()}catch{}this.cdpSession=null;let n=await this.collector.getActivePage();return this.cdpSession=await Promise.race([n.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),this.cdpSession}}async getPerformanceMetrics(){let e=await C(await this.collector.getActivePage(),()=>{let e={},t=performance.getEntriesByType(`navigation`)[0];t&&(e.domContentLoaded=t.domContentLoadedEventEnd-t.fetchStart,e.loadComplete=t.loadEventEnd-t.fetchStart,e.ttfb=t.responseStart-t.requestStart);let n=performance.getEntriesByType(`paint`).find(e=>e.name===`first-contentful-paint`);n&&(e.fcp=n.startTime);let r=performance.getEntriesByType(`largest-contentful-paint`).at(-1);r&&(e.lcp=r.renderTime||r.loadTime);let i=0,a=performance.getEntriesByType(`layout-shift`);for(let e of a)e.hadRecentInput||(i+=e.value??0);e.cls=i;let o=performance;if(o.memory){let t=o.memory;e.jsHeapSizeLimit=t.jsHeapSizeLimit,e.totalJSHeapSize=t.totalJSHeapSize,e.usedJSHeapSize=t.usedJSHeapSize}return e});return t.info(`Performance metrics collected`,{fcp:e.fcp,lcp:e.lcp,cls:e.cls}),e}async getPerformanceTimeline(){let e=await C(await this.collector.getActivePage(),()=>performance.getEntries().map(e=>({name:e.name,entryType:e.entryType,startTime:e.startTime,duration:e.duration})));return t.info(`Performance timeline collected: ${e.length} entries`),e}async startCoverage(e){let n=await this.collector.getActivePage();await Promise.all([re(n,{resetOnNavigation:e?.resetOnNavigation,reportAnonymousScripts:e?.reportAnonymousScripts}),ne(n,{resetOnNavigation:e?.resetOnNavigation})]),this.coverageEnabled=!0,this.coveragePage=n,t.info(`Code coverage collection started`)}async stopCoverage(){if(!this.coverageEnabled)throw new b(`Coverage not enabled. Call startCoverage() first.`);let e=this.coveragePage??await this.collector.getActivePage(),[n,r]=await Promise.all([ee(e),te(e)]),i=n,a=r;this.coverageEnabled=!1,this.coveragePage=null;let o=[...i,...a].map(e=>{let t=e.text.length,n=e.ranges.reduce((e,t)=>e+(t.end-t.start),0);return{url:e.url,text:e.text,ranges:e.ranges.map(e=>({start:e.start,end:e.end,count:1})),totalBytes:t,usedBytes:n,coveragePercentage:t>0?n/t*100:0}});return t.success(`Code coverage collected: ${o.length} scripts`,{totalScripts:o.length,avgCoverage:o.reduce((e,t)=>e+t.coveragePercentage,0)/o.length}),o}async startCPUProfiling(){let e=await this.ensureCDPSession();await e.send(`Profiler.enable`),await e.send(`Profiler.start`),this.profilerEnabled=!0,t.info(`CPU profiling started`)}async stopCPUProfiling(){if(!this.profilerEnabled)throw new b(`CPU profiling not enabled. Call startCPUProfiling() first.`);let e=await this.ensureCDPSession(),{profile:n}=await e.send(`Profiler.stop`);return await e.send(`Profiler.disable`),this.profilerEnabled=!1,t.success(`CPU profiling stopped`,{nodes:n.nodes.length,samples:n.samples?.length||0}),n}async takeHeapSnapshot(){let e=await this.ensureCDPSession();await e.send(`HeapProfiler.enable`);let n=0,r=e=>{Jt(e)&&(n+=e.chunk.length)};e.on(`HeapProfiler.addHeapSnapshotChunk`,r);try{await e.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1,treatGlobalObjectsAsRoots:!0})}finally{e.off(`HeapProfiler.addHeapSnapshotChunk`,r),await e.send(`HeapProfiler.disable`).catch(()=>{})}return t.success(`Heap snapshot taken`,{size:n}),n}async startTracing(e){return S(async()=>{if(this.tracingEnabled)throw Error(`Tracing already in progress. Call stopTracing() first.`);let n=await this.collector.getActivePage(),r=e?.categories??[`-*`,`devtools.timeline`,`v8.execute`,`disabled-by-default-devtools.timeline`,`disabled-by-default-devtools.timeline.frame`,`toplevel`,`blink.console`,`blink.user_timing`,`latencyInfo`,...e?.screenshots?[`disabled-by-default-devtools.screenshot`]:[]];await n.tracing.start({categories:r,screenshots:e?.screenshots}),this.tracingEnabled=!0,this.tracingPage=n,t.info(`Performance tracing started`,{categories:r.length})})}async stopTracing(e){return S(async()=>{if(!this.tracingEnabled)throw new b(`Tracing not in progress. Call startTracing() first.`);let n=await(this.tracingPage??await this.collector.getActivePage()).tracing.stop(),r=n?Buffer.from(n).toString(`utf-8`):``;this.tracingEnabled=!1,this.tracingPage=null;let i=Zt(r),a;if(e?.artifactPath)await O(e.artifactPath,r,`utf-8`),a=e.artifactPath;else{let{absolutePath:e,displayPath:t}=await y({category:`traces`,toolName:`performance-trace`,ext:`json`});await O(e,r,`utf-8`),a=t}return t.success(`Performance trace saved`,{eventCount:i,sizeBytes:r.length,path:a}),{artifactPath:a,eventCount:i,sizeBytes:r.length}})}async startHeapSampling(e){return S(async()=>{if(this.heapSamplingEnabled)throw Error(`Heap sampling already in progress. Call stopHeapSampling() first.`);let n=await this.ensureCDPSession();await n.send(`HeapProfiler.enable`),await n.send(`HeapProfiler.startSampling`,{samplingInterval:e?.samplingInterval??32768}),this.heapSamplingEnabled=!0,t.info(`Heap sampling profiler started`)})}async stopHeapSampling(e){return S(async()=>{if(!this.heapSamplingEnabled)throw new b(`Heap sampling not in progress. Call startHeapSampling() first.`);let n=await this.ensureCDPSession(),r=await n.send(`HeapProfiler.stopSampling`);if(!Xt(r))throw Error(`Unexpected HeapProfiler.stopSampling payload shape`);let{profile:i}=r;await n.send(`HeapProfiler.disable`),this.heapSamplingEnabled=!1;let a=e?.topN??20;await $();let{sampleCount:o,topAllocations:s}=$t(i.head,a);await $();let c=JSON.stringify(i),l;if(e?.artifactPath)await O(e.artifactPath,c,`utf-8`),l=e.artifactPath;else{let{absolutePath:e,displayPath:t}=await y({category:`profiles`,toolName:`heap-sampling`,ext:`json`});await O(e,c,`utf-8`),l=t}return t.success(`Heap sampling profile saved`,{sampleCount:o,path:l}),{artifactPath:l,sampleCount:o,topAllocations:s}})}async close(){this.cdpSession&&=(this.coverageEnabled&&await this.stopCoverage().catch(()=>{}),this.profilerEnabled&&await this.stopCPUProfiling().catch(()=>{}),this.tracingEnabled&&await this.stopTracing().catch(()=>{}),this.heapSamplingEnabled&&await this.stopHeapSampling().catch(()=>{}),await this.cdpSession.detach(),null),t.info(`PerformanceMonitor closed`)}},nn=class e{constructor(){}static injectedPages=new WeakSet;static async injectAll(e){if(this.injectedPages.has(e)){t.info(`Stealth scripts already injected on this page, skipping`);return}t.info(`Injecting modern stealth scripts...`),await Promise.all([this.hideWebDriver(e),this.mockChrome(e),this.mockPlugins(e),this.fixPermissions(e),this.mockCanvas(e),this.mockWebGL(e),this.fixLanguages(e),this.mockBattery(e),this.fixMediaDevices(e),this.mockNotifications(e)]),await this.injectTimingDefense(e),this.injectedPages.add(e),t.info(` `)}static async injectTimingDefense(e){await e.evaluateOnNewDocument(()=>{let e=performance.now.bind(performance),t=Date.now,n=0;performance.now=function(){let t=window;return typeof t.__cdpTimingOffset==`number`&&(n=t.__cdpTimingOffset),e()-n},Date.now=function(){let e=window;return typeof e.__cdpTimingOffset==`number`&&(n=e.__cdpTimingOffset),t.call(Date)-Math.floor(n)};let r=Date,i=function(...e){return e.length===0?new r(r.now()):new r(...e)};i.now=r.now,i.parse=r.parse.bind(r),i.UTC=r.UTC.bind(r),Object.defineProperty(i,`prototype`,{value:r.prototype}),globalThis.Date=i})}static async hideWebDriver(e){await e.evaluateOnNewDocument(()=>{let e=Object.getPrototypeOf(navigator);delete e.webdriver,Object.defineProperty(navigator,`webdriver`,{get:()=>void 0,configurable:!0});let t=Object.getOwnPropertyNames;if(Object.getOwnPropertyNames=function(e){return t(e).filter(e=>e!==`webdriver`)},typeof document<`u`){let e=document;for(let t of Object.keys(e))(t.startsWith(`cdc_`)||t.startsWith(`$cdc_`))&&delete e[t]}})}static async mockChrome(e){await e.evaluateOnNewDocument(()=>{let e=window;e.chrome={runtime:{connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{},removeListener:()=>{}}},loadTimes:function(){return{commitLoadTime:Date.now()/1e3,connectionInfo:`http/1.1`,finishDocumentLoadTime:Date.now()/1e3,finishLoadTime:Date.now()/1e3,firstPaintAfterLoadTime:0,firstPaintTime:Date.now()/1e3,navigationType:`Other`,npnNegotiatedProtocol:`unknown`,requestTime:0,startLoadTime:Date.now()/1e3,wasAlternateProtocolAvailable:!1,wasFetchedViaSpdy:!1,wasNpnNegotiated:!1}},csi:function(){return{onloadT:Date.now(),pageT:Date.now(),startE:Date.now(),tran:15}},app:{isInstalled:!1,InstallState:{DISABLED:`disabled`,INSTALLED:`installed`,NOT_INSTALLED:`not_installed`},RunningState:{CANNOT_RUN:`cannot_run`,READY_TO_RUN:`ready_to_run`,RUNNING:`running`}}}})}static async mockPlugins(e){await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,`plugins`,{configurable:!0,get:()=>[{0:{type:`application/pdf`,suffixes:`pdf`,description:`Portable Document Format`},description:`Portable Document Format`,filename:`internal-pdf-viewer`,length:1,name:`Chrome PDF Plugin`},{0:{type:`application/x-google-chrome-pdf`,suffixes:`pdf`,description:``},description:``,filename:`internal-pdf-viewer`,length:1,name:`Chrome PDF Viewer`},{0:{type:`application/x-nacl`,suffixes:``,description:`Native Client Executable`},1:{type:`application/x-pnacl`,suffixes:``,description:`Portable Native Client Executable`},description:``,filename:`internal-nacl-plugin`,length:2,name:`Native Client`}]})})}static async fixPermissions(e){await e.evaluateOnNewDocument(()=>{let e=window.navigator.permissions.query.bind(window.navigator.permissions),t=Notification;window.navigator.permissions.query=n=>n.name===`notifications`?Promise.resolve({state:t.permission}):e(n)})}static async mockCanvas(e){await e.evaluateOnNewDocument(()=>{let e=HTMLCanvasElement.prototype.toDataURL,t=CanvasRenderingContext2D.prototype.getImageData;HTMLCanvasElement.prototype.toDataURL=function(...t){let n=this.getContext(`2d`);if(n){let e=n.getImageData(0,0,this.width,this.height),t=e.data;if(t)for(let e=0;e<t.length;e+=4)t[e]=t[e]^1,t[e+1]=t[e+1]^1,t[e+2]=t[e+2]^1;n.putImageData(e,0,0)}return e.apply(this,t)},CanvasRenderingContext2D.prototype.getImageData=function(...e){let n=t.apply(this,e),r=n.data;if(r)for(let e=0;e<r.length;e+=4)r[e]=r[e]^1,r[e+1]=r[e+1]^1,r[e+2]=r[e+2]^1;return n}})}static async mockWebGL(e){await e.evaluateOnNewDocument(()=>{let e=WebGLRenderingContext.prototype.getParameter;WebGLRenderingContext.prototype.getParameter=function(t){return t===37445?`Intel Inc.`:t===37446?`Intel Iris OpenGL Engine`:e.apply(this,[t])}})}static async fixLanguages(e){await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,`language`,{configurable:!0,get:()=>`en-US`}),Object.defineProperty(navigator,`languages`,{configurable:!0,get:()=>[`en-US`,`en`]})})}static async mockBattery(e){await e.evaluateOnNewDocument(()=>{let e=navigator;if(typeof e.getBattery==`function`){let t=e.getBattery;e.getBattery=function(){return t.call(navigator).then(e=>(Object.defineProperty(e,`charging`,{configurable:!0,get:()=>!0}),Object.defineProperty(e,`chargingTime`,{configurable:!0,get:()=>0}),Object.defineProperty(e,`dischargingTime`,{configurable:!0,get:()=>1/0}),Object.defineProperty(e,`level`,{configurable:!0,get:()=>1}),e))}}})}static async fixMediaDevices(e){await e.evaluateOnNewDocument(()=>{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){let e=navigator.mediaDevices.enumerateDevices;navigator.mediaDevices.enumerateDevices=function(){return e.call(navigator.mediaDevices).then(e=>e.length===0?[{deviceId:`default`,kind:`audioinput`,label:`Default - Microphone`,groupId:`default`,toJSON:()=>({})},{deviceId:`default`,kind:`videoinput`,label:`Default - Camera`,groupId:`default`,toJSON:()=>({})}]:e)}}})}static async mockNotifications(e){await e.evaluateOnNewDocument(()=>{`Notification`in window&&Object.defineProperty(Notification,`permission`,{configurable:!0,get:()=>`default`})})}static async setRealisticUserAgent(e,t=`windows`){let n={windows:`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,mac:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,linux:`Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`},r={windows:`Win32`,mac:`MacIntel`,linux:`Linux x86_64`},i={windows:16,mac:12,linux:8};await e.setUserAgent(n[t]);let a=i[t];await e.evaluateOnNewDocument((e,t)=>{Object.defineProperty(navigator,`platform`,{configurable:!0,get:()=>e}),Object.defineProperty(navigator,`vendor`,{configurable:!0,get:()=>`Google Inc.`}),Object.defineProperty(navigator,`hardwareConcurrency`,{configurable:!0,get:()=>t}),Object.defineProperty(navigator,`deviceMemory`,{configurable:!0,get:()=>8})},r[t],a)}static getRecommendedLaunchArgs(){return[`--no-sandbox`,`--disable-setuid-sandbox`,`--disable-blink-features=AutomationControlled`,`--disable-dev-shm-usage`,`--disable-accelerated-2d-canvas`,`--no-first-run`,`--no-zygote`,`--disable-gpu`,`--disable-web-security`,`--disable-features=IsolateOrigins,site-per-process`,`--window-size=1920,1080`,`--disable-infobars`,`--disable-extensions`,`--disable-default-apps`,`--disable-sync`,`--metrics-recording-only`,`--mute-audio`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,...e.getPatchrightLaunchArgs()]}static getPatchrightLaunchArgs(){return[`--disable-component-update`,`--disable-features=OptimizationGuideModelDownloading,OptimizationHintsFetching,OptimizationHints`,`--disable-hang-monitor`,`--disable-domain-reliability`,`--disable-client-side-phishing-detection`,`--disable-popup-blocking`]}},rn=e({AdvancedDeobfuscator:()=>ot,CodeAnalyzer:()=>Te,CryptoDetector:()=>nt,DebuggerManager:()=>Bt,Deobfuscator:()=>st,HookManager:()=>qt,ObfuscationDetector:()=>ct,RuntimeInspector:()=>Vt});export{et as a,Gt as i,nn as n,Ee as o,tn as r,rn as t};
|