@jshookmcp/jshook 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +36 -5
  2. package/README.zh.md +36 -5
  3. package/dist/{AntiCheatDetector-S8VRj-dD.mjs → AntiCheatDetector-CqGDXmfc.mjs} +160 -54
  4. package/dist/{CodeInjector-4Z3ngPoX.mjs → CodeInjector-BdjRfNx7.mjs} +5 -5
  5. package/dist/ConsoleMonitor-DykL3IAw.mjs +2269 -0
  6. package/dist/{DarwinAPI-B8hg_yhz.mjs → DarwinAPI-ETyy0xyo.mjs} +1 -1
  7. package/dist/DetailedDataManager-HT49OrvF.mjs +217 -0
  8. package/dist/EventBus-DFKvADm3.mjs +141 -0
  9. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +153 -0
  10. package/dist/{ExtensionManager-D5-bO9D8.mjs → ExtensionManager-BDMsY2Dz.mjs} +27 -13
  11. package/dist/{FingerprintManager-BVxFJL2-.mjs → FingerprintManager-BN4UQWnX.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-DK1yjWkV.mjs → HardwareBreakpoint-Cc2AFq1Y.mjs} +3 -3
  13. package/dist/{HeapAnalyzer-CEbo10xU.mjs → HeapAnalyzer-DruMgsgj.mjs} +21 -21
  14. package/dist/HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs +566 -0
  15. package/dist/InstrumentationSession-DLH0vd-z.mjs +244 -0
  16. package/dist/{MemoryController-DdtnBdD4.mjs → MemoryController-CMtviNW_.mjs} +3 -3
  17. package/dist/{MemoryScanSession-RMixN3bX.mjs → MemoryScanSession-ITgb_NMi.mjs} +81 -78
  18. package/dist/{MemoryScanner-QjK4ld0B.mjs → MemoryScanner-CiL7Z3ey.mjs} +50 -21
  19. package/dist/{NativeMemoryManager.impl-CB6gJ0NM.mjs → NativeMemoryManager.impl-D9Lkovvn.mjs} +20 -56
  20. package/dist/{NativeMemoryManager.utils-BML4q1ry.mjs → NativeMemoryManager.utils-BBlAixF5.mjs} +1 -1
  21. package/dist/{PEAnalyzer-CK0xe0Fs.mjs → PEAnalyzer-DMQ44gen.mjs} +16 -16
  22. package/dist/PageController-BPJNqqBN.mjs +431 -0
  23. package/dist/{PointerChainEngine-Cd73qu5b.mjs → PointerChainEngine-K7wN8Z-w.mjs} +10 -7
  24. package/dist/PrerequisiteError-TuyZIs6n.mjs +20 -0
  25. package/dist/ProcessRegistry-zGg12QbE.mjs +74 -0
  26. package/dist/ResponseBuilder-CJXWmWNw.mjs +143 -0
  27. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +269 -0
  28. package/dist/ScriptManager-ZuWD-0Jg.mjs +3003 -0
  29. package/dist/{Speedhack-CeF0XmEz.mjs → Speedhack-D-z0umeT.mjs} +2 -2
  30. package/dist/{StructureAnalyzer-D4GkMduU.mjs → StructureAnalyzer-Cav5AVSL.mjs} +9 -6
  31. package/dist/ToolCatalog-5OJdMiF0.mjs +582 -0
  32. package/dist/ToolError-jh9whhMd.mjs +15 -0
  33. package/dist/ToolProbe-DbCFGyrg.mjs +45 -0
  34. package/dist/ToolRegistry-B9krbTtI.mjs +180 -0
  35. package/dist/ToolRouter.policy-BGDAGyeH.mjs +344 -0
  36. package/dist/TraceRecorder-B41Z5XBj.mjs +1286 -0
  37. package/dist/{Win32API-Bc0QnQsN.mjs → Win32API-C2kjj0ze.mjs} +19 -13
  38. package/dist/{Win32Debug-DUHt9XUn.mjs → Win32Debug-CKrGOTpo.mjs} +3 -3
  39. package/dist/WorkflowEngine-DJ6M4opp.mjs +569 -0
  40. package/dist/analysis-BHeJW2Nb.mjs +1234 -0
  41. package/dist/antidebug-BRKeyt27.mjs +1081 -0
  42. package/dist/artifactRetention-CPXkUJXp.mjs +598 -0
  43. package/dist/artifacts-DkfosXH3.mjs +59 -0
  44. package/dist/authorization-schema-DRqyJMSk.mjs +31 -0
  45. package/dist/betterSqlite3-DLSBZodi.mjs +74 -0
  46. package/dist/binary-instrument--V3MAhJ4.mjs +971 -0
  47. package/dist/bind-helpers-ClV34xdn.mjs +42 -0
  48. package/dist/boringssl-inspector-Bo_LOLaS.mjs +180 -0
  49. package/dist/browser-Dx3_S2cG.mjs +4369 -0
  50. package/dist/capabilities-CcHlvWgK.mjs +33 -0
  51. package/dist/concurrency-Drev_Vz9.mjs +41 -0
  52. package/dist/{constants-CCvsN80K.mjs → constants-CDZLOoVv.mjs} +105 -48
  53. package/dist/coordination-DgItD9DL.mjs +259 -0
  54. package/dist/debugger-RS3RSAqs.mjs +1288 -0
  55. package/dist/definitions-BEoYofW5.mjs +47 -0
  56. package/dist/definitions-BRaefg3u.mjs +365 -0
  57. package/dist/definitions-BbkvZkiv.mjs +96 -0
  58. package/dist/definitions-BtWSHJ3o.mjs +17 -0
  59. package/dist/definitions-C1gCHO0i.mjs +43 -0
  60. package/dist/definitions-CDOg_b-l.mjs +138 -0
  61. package/dist/definitions-CVPD9hzZ.mjs +54 -0
  62. package/dist/definitions-Cea8Lgl7.mjs +94 -0
  63. package/dist/definitions-DAgIyjxM.mjs +10 -0
  64. package/dist/definitions-DJA27nsL.mjs +66 -0
  65. package/dist/definitions-DKPFU3LW.mjs +25 -0
  66. package/dist/definitions-DPRpZQ96.mjs +47 -0
  67. package/dist/definitions-DUE5gmdn.mjs +18 -0
  68. package/dist/definitions-DYVjOtxa.mjs +26 -0
  69. package/dist/definitions-DcYLVLCo.mjs +37 -0
  70. package/dist/definitions-Pp5LI2H4.mjs +27 -0
  71. package/dist/definitions-j9KdHVNR.mjs +14 -0
  72. package/dist/definitions-uzkjBwa7.mjs +258 -0
  73. package/dist/definitions-va-AnLuQ.mjs +28 -0
  74. package/dist/encoding-DJeqHmpd.mjs +1079 -0
  75. package/dist/evidence-graph-bridge-DcYizFk2.mjs +136 -0
  76. package/dist/{factory-CibqTNC8.mjs → factory-C90tBff6.mjs} +41 -56
  77. package/dist/flat-target-session-Dgax2Cy3.mjs +29 -0
  78. package/dist/graphql-CoHrhweh.mjs +1197 -0
  79. package/dist/handlers-4jmR0nMs.mjs +898 -0
  80. package/dist/handlers-BAHPxcch.mjs +789 -0
  81. package/dist/handlers-BOs9b907.mjs +2600 -0
  82. package/dist/handlers-BWXEy6ef.mjs +917 -0
  83. package/dist/handlers-Bndn6QvE.mjs +111 -0
  84. package/dist/handlers-BqC4bD4s.mjs +681 -0
  85. package/dist/handlers-BtYq60bM2.mjs +276 -0
  86. package/dist/handlers-BzgcB4iv.mjs +799 -0
  87. package/dist/handlers-CRyRWj2b.mjs +859 -0
  88. package/dist/handlers-CVv2H1uq.mjs +592 -0
  89. package/dist/handlers-Dl5a7JS4.mjs +572 -0
  90. package/dist/handlers-Dx2d7jt7.mjs +2537 -0
  91. package/dist/handlers-Dz9PYsCa.mjs +2805 -0
  92. package/dist/handlers-HujRKC3b.mjs +661 -0
  93. package/dist/handlers.impl-XWXkQfyi.mjs +807 -0
  94. package/dist/hooks-B1B8NRHL.mjs +898 -0
  95. package/dist/index.mjs +491 -259
  96. package/dist/{logger-BmWzC2lM.mjs → logger-Dh_xb7_2.mjs} +14 -6
  97. package/dist/maintenance-PRMkLVRW.mjs +835 -0
  98. package/dist/manifest-67Bok-Si.mjs +58 -0
  99. package/dist/manifest-6lNTMZAB2.mjs +87 -0
  100. package/dist/manifest-B2duEHiH.mjs +90 -0
  101. package/dist/manifest-B6EY9Vm8.mjs +57 -0
  102. package/dist/manifest-B6nKSbyY.mjs +95 -0
  103. package/dist/manifest-BL8AQNPF.mjs +106 -0
  104. package/dist/manifest-BSZvJJmV.mjs +47 -0
  105. package/dist/manifest-BU7qzUyX.mjs +418 -0
  106. package/dist/manifest-Bl62e8WK.mjs +49 -0
  107. package/dist/manifest-Bo5cXjdt.mjs +82 -0
  108. package/dist/manifest-BpS4gtUK.mjs +1347 -0
  109. package/dist/manifest-Bv65_e2W.mjs +101 -0
  110. package/dist/manifest-BytNIF4Z.mjs +117 -0
  111. package/dist/manifest-C-xtsjS3.mjs +81 -0
  112. package/dist/manifest-CDYl7OhA.mjs +66 -0
  113. package/dist/manifest-CRZ3xmkD.mjs +61 -0
  114. package/dist/manifest-CoW6u4Tp.mjs +132 -0
  115. package/dist/manifest-Cq5zN_8A.mjs +50 -0
  116. package/dist/manifest-D7YZM_2e.mjs +194 -0
  117. package/dist/manifest-DE_VrAeQ.mjs +314 -0
  118. package/dist/manifest-DGsXSCpT.mjs +39 -0
  119. package/dist/manifest-DJ2vfEuW.mjs +156 -0
  120. package/dist/manifest-DPXDYhEu.mjs +80 -0
  121. package/dist/manifest-Dd4fQb0a.mjs +322 -0
  122. package/dist/manifest-Deq6opGg.mjs +223 -0
  123. package/dist/manifest-DfJTafJK.mjs +37 -0
  124. package/dist/manifest-DgOdgN_j.mjs +50 -0
  125. package/dist/manifest-DlbMW4v4.mjs +47 -0
  126. package/dist/manifest-DmVfbH0w.mjs +374 -0
  127. package/dist/manifest-Dog6Ddjr.mjs +109 -0
  128. package/dist/manifest-DvgU5FWb.mjs +58 -0
  129. package/dist/manifest-HsfDBs7j.mjs +50 -0
  130. package/dist/manifest-I8oQHvCG.mjs +186 -0
  131. package/dist/manifest-NvH_a-av.mjs +786 -0
  132. package/dist/manifest-cEJU1v0Z.mjs +129 -0
  133. package/dist/manifest-wOl5XLB12.mjs +112 -0
  134. package/dist/modules-tZozf0LQ.mjs +10635 -0
  135. package/dist/mojo-ipc-DXNEXEqb.mjs +640 -0
  136. package/dist/network-CPVvwvFg.mjs +3852 -0
  137. package/dist/{artifacts-BbdOMET5.mjs → outputPaths-um7lCRY3.mjs} +219 -216
  138. package/dist/parse-args-B4cY5Vx5.mjs +39 -0
  139. package/dist/platform-CYeFoTWp.mjs +2161 -0
  140. package/dist/process-BTbgcVc6.mjs +1306 -0
  141. package/dist/proxy-r8YN6nP1.mjs +192 -0
  142. package/dist/registry-Bl8ZQW61.mjs +34 -0
  143. package/dist/response-CWhh2aLo.mjs +34 -0
  144. package/dist/server/plugin-api.mjs +2 -2
  145. package/dist/shared-state-board-BoZnSoj-.mjs +586 -0
  146. package/dist/sourcemap-BIDHUVXy.mjs +934 -0
  147. package/dist/ssrf-policy-Dsqd-DTX.mjs +166 -0
  148. package/dist/streaming-Dal6utPp.mjs +725 -0
  149. package/dist/tool-builder-BHJp32mV.mjs +186 -0
  150. package/dist/transform-DRVgGG90.mjs +1011 -0
  151. package/dist/types-Bx92KJfT.mjs +4 -0
  152. package/dist/wasm-BYx5UOeG.mjs +1044 -0
  153. package/dist/webcrack-Be0_FccV.mjs +747 -0
  154. package/dist/workflow-BpuKEtvn.mjs +725 -0
  155. package/package.json +82 -49
  156. package/dist/ExtensionManager-CPTJhHFg.mjs +0 -2
  157. package/dist/ToolCatalog-Bq4V2sbJ.mjs +0 -67201
  158. package/dist/{CacheAdapters-CzFNpD9a.mjs → CacheAdapters-jJFy20G-.mjs} +0 -0
  159. package/dist/{StealthVerifier-BzBCFiwx.mjs → StealthVerifier-BWmPgQsv.mjs} +0 -0
  160. package/dist/{VersionDetector-CNXcvD46.mjs → VersionDetector-K3V4vGsw.mjs} +0 -0
  161. package/dist/{formatAddress-ChCSIRWT.mjs → formatAddress-nnMvEohD.mjs} +0 -0
  162. package/dist/{types-BBjOqye-.mjs → types-DDBWs9UP.mjs} +1 -1
@@ -0,0 +1,725 @@
1
+ import { t as logger } from "./logger-Dh_xb7_2.mjs";
2
+ import { Hr as WS_PAYLOAD_PREVIEW_LIMIT, Ur as WS_PAYLOAD_SAMPLE_LIMIT } from "./constants-CDZLOoVv.mjs";
3
+ import { o as evaluateOnNewDocumentWithTimeout, s as evaluateWithTimeout } from "./PageController-BPJNqqBN.mjs";
4
+ import "./definitions-DcYLVLCo.mjs";
5
+ //#region src/utils/RingBuffer.ts
6
+ /**
7
+ * Fixed-capacity ring buffer with O(1) push/shift.
8
+ * Drop-in replacement for arrays used as bounded FIFO queues.
9
+ */
10
+ var RingBuffer = class {
11
+ buf;
12
+ head = 0;
13
+ tail = 0;
14
+ count = 0;
15
+ constructor(capacity) {
16
+ this.capacity = capacity;
17
+ this.buf = Array.from({ length: capacity });
18
+ }
19
+ get length() {
20
+ return this.count;
21
+ }
22
+ push(item) {
23
+ if (this.count === this.buf.length) if (this.buf.length < this.capacity) this.grow();
24
+ else {
25
+ this.buf[this.tail] = item;
26
+ this.tail = (this.tail + 1) % this.buf.length;
27
+ this.head = (this.head + 1) % this.buf.length;
28
+ return;
29
+ }
30
+ this.buf[this.tail] = item;
31
+ this.tail = (this.tail + 1) % this.buf.length;
32
+ this.count++;
33
+ }
34
+ shift() {
35
+ if (this.count === 0) return void 0;
36
+ const item = this.buf[this.head];
37
+ this.buf[this.head] = void 0;
38
+ this.head = (this.head + 1) % this.buf.length;
39
+ this.count--;
40
+ return item;
41
+ }
42
+ clear() {
43
+ this.buf = Array.from({ length: Math.min(64, this.capacity) });
44
+ this.head = 0;
45
+ this.tail = 0;
46
+ this.count = 0;
47
+ }
48
+ *[Symbol.iterator]() {
49
+ for (let i = 0; i < this.count; i++) yield this.buf[(this.head + i) % this.buf.length];
50
+ }
51
+ toArray() {
52
+ const result = Array.from({ length: this.count });
53
+ for (let i = 0; i < this.count; i++) result[i] = this.buf[(this.head + i) % this.buf.length];
54
+ return result;
55
+ }
56
+ map(fn) {
57
+ const result = Array.from({ length: this.count });
58
+ for (let i = 0; i < this.count; i++) result[i] = fn(this.buf[(this.head + i) % this.buf.length], i);
59
+ return result;
60
+ }
61
+ grow() {
62
+ const newSize = Math.min(this.buf.length * 2, this.capacity);
63
+ const newBuf = Array.from({ length: newSize });
64
+ for (let i = 0; i < this.count; i++) newBuf[i] = this.buf[(this.head + i) % this.buf.length];
65
+ this.buf = newBuf;
66
+ this.head = 0;
67
+ this.tail = this.count;
68
+ }
69
+ };
70
+ //#endregion
71
+ //#region src/server/domains/streaming/handlers/shared.ts
72
+ function createStreamingSharedState(collector) {
73
+ return {
74
+ collector,
75
+ wsSession: null,
76
+ wsListeners: null,
77
+ wsConfig: {
78
+ enabled: false,
79
+ maxFrames: 1e3
80
+ },
81
+ wsFramesByRequest: /* @__PURE__ */ new Map(),
82
+ wsFrameOrder: new RingBuffer(1e3),
83
+ wsConnections: /* @__PURE__ */ new Map(),
84
+ sseConfig: { maxEvents: 2e3 }
85
+ };
86
+ }
87
+ function asJson(payload) {
88
+ return { content: [{
89
+ type: "text",
90
+ text: JSON.stringify(payload, null, 2)
91
+ }] };
92
+ }
93
+ function parseOptionalStringArg(value) {
94
+ if (typeof value !== "string") return void 0;
95
+ const normalized = value.trim();
96
+ return normalized.length > 0 ? normalized : void 0;
97
+ }
98
+ function parseNumberArg(value, options) {
99
+ let parsed;
100
+ if (typeof value === "number" && Number.isFinite(value)) parsed = value;
101
+ else if (typeof value === "string") {
102
+ const n = Number(value.trim());
103
+ if (Number.isFinite(n)) parsed = n;
104
+ }
105
+ if (parsed === void 0) parsed = options.defaultValue;
106
+ if (options.integer) parsed = Math.trunc(parsed);
107
+ if (parsed < options.min) parsed = options.min;
108
+ if (parsed > options.max) parsed = options.max;
109
+ return parsed;
110
+ }
111
+ function parseWsDirection(value) {
112
+ if (value === "sent" || value === "received" || value === "all") return value;
113
+ return "all";
114
+ }
115
+ function compileRegex(pattern) {
116
+ try {
117
+ return { regex: new RegExp(pattern) };
118
+ } catch (error) {
119
+ return { error: error instanceof Error ? error.message : String(error) };
120
+ }
121
+ }
122
+ //#endregion
123
+ //#region src/server/domains/streaming/handlers/ws-handlers.ts
124
+ /**
125
+ * WebSocket monitoring handlers — enable, disable, get frames, get connections.
126
+ */
127
+ const asRecord = (value) => typeof value === "object" && value !== null ? value : void 0;
128
+ const getStringField = (value, key) => {
129
+ const field = asRecord(value)?.[key];
130
+ return typeof field === "string" ? field : void 0;
131
+ };
132
+ const getNumberField = (value, key) => {
133
+ const field = asRecord(value)?.[key];
134
+ return typeof field === "number" ? field : void 0;
135
+ };
136
+ const getRecordField = (value, key) => {
137
+ const nested = asRecord(value)?.[key];
138
+ return asRecord(nested);
139
+ };
140
+ var WsHandlers = class {
141
+ constructor(s) {
142
+ this.s = s;
143
+ }
144
+ async teardownWsSession() {
145
+ if (this.s.wsSession && this.s.wsListeners) {
146
+ try {
147
+ this.s.wsSession.off("Network.webSocketCreated", this.s.wsListeners.created);
148
+ } catch (e) {
149
+ logger.debug("[ws-teardown] Failed to remove webSocketCreated listener", e);
150
+ }
151
+ try {
152
+ this.s.wsSession.off("Network.webSocketClosed", this.s.wsListeners.closed);
153
+ } catch (e) {
154
+ logger.debug("[ws-teardown] Failed to remove webSocketClosed listener", e);
155
+ }
156
+ try {
157
+ this.s.wsSession.off("Network.webSocketHandshakeResponseReceived", this.s.wsListeners.handshake);
158
+ } catch (e) {
159
+ logger.debug("[ws-teardown] Failed to remove handshakeResponseReceived listener", e);
160
+ }
161
+ try {
162
+ this.s.wsSession.off("Network.webSocketFrameSent", this.s.wsListeners.frameSent);
163
+ } catch (e) {
164
+ logger.debug("[ws-teardown] Failed to remove webSocketFrameSent listener", e);
165
+ }
166
+ try {
167
+ this.s.wsSession.off("Network.webSocketFrameReceived", this.s.wsListeners.frameReceived);
168
+ } catch (e) {
169
+ logger.debug("[ws-teardown] Failed to remove webSocketFrameReceived listener", e);
170
+ }
171
+ }
172
+ if (this.s.wsSession) try {
173
+ await this.s.wsSession.detach();
174
+ } catch (e) {
175
+ logger.debug("[ws-teardown] Failed to detach CDP session", e);
176
+ }
177
+ this.s.wsSession = null;
178
+ this.s.wsListeners = null;
179
+ }
180
+ handleWsFrame(direction, params) {
181
+ const requestId = getStringField(params, "requestId");
182
+ if (!requestId) return;
183
+ if (!this.s.wsConnections.get(requestId)) {
184
+ if (this.s.wsConfig.urlFilter) return;
185
+ this.s.wsConnections.set(requestId, {
186
+ requestId,
187
+ url: "unknown",
188
+ status: "open",
189
+ framesCount: 0,
190
+ createdTimestamp: Date.now() / 1e3
191
+ });
192
+ }
193
+ const connection = this.s.wsConnections.get(requestId);
194
+ if (!connection) return;
195
+ if (this.s.wsConfig.urlFilter && connection.url !== "unknown" && !this.s.wsConfig.urlFilter.test(connection.url)) return;
196
+ const response = getRecordField(params, "response");
197
+ const opcode = getNumberField(response, "opcode") ?? -1;
198
+ const payloadData = getStringField(response, "payloadData") ?? "";
199
+ const payloadPreview = payloadData.length > WS_PAYLOAD_PREVIEW_LIMIT ? `${payloadData.slice(0, WS_PAYLOAD_PREVIEW_LIMIT)}…` : payloadData;
200
+ const payloadSample = payloadData.length > WS_PAYLOAD_SAMPLE_LIMIT ? payloadData.slice(0, WS_PAYLOAD_SAMPLE_LIMIT) : payloadData;
201
+ const frame = {
202
+ requestId,
203
+ timestamp: getNumberField(params, "timestamp") ?? Date.now() / 1e3,
204
+ direction,
205
+ opcode,
206
+ payloadLength: payloadData.length,
207
+ payloadPreview,
208
+ payloadSample,
209
+ isBinary: opcode === 2
210
+ };
211
+ this.appendWsFrame(requestId, frame);
212
+ }
213
+ appendWsFrame(requestId, frame) {
214
+ const list = this.s.wsFramesByRequest.get(requestId) ?? [];
215
+ list.push(frame);
216
+ this.s.wsFramesByRequest.set(requestId, list);
217
+ const connection = this.s.wsConnections.get(requestId);
218
+ if (connection) {
219
+ connection.framesCount += 1;
220
+ if (connection.status === "connecting") connection.status = "open";
221
+ }
222
+ this.s.wsFrameOrder.push({
223
+ requestId,
224
+ frame
225
+ });
226
+ this.enforceWsFrameLimit();
227
+ }
228
+ enforceWsFrameLimit() {
229
+ while (this.s.wsFrameOrder.length > this.s.wsConfig.maxFrames) {
230
+ const oldest = this.s.wsFrameOrder.shift();
231
+ if (!oldest) break;
232
+ const bucket = this.s.wsFramesByRequest.get(oldest.requestId);
233
+ if (bucket && bucket.length > 0) {
234
+ bucket.shift();
235
+ if (bucket.length === 0) this.s.wsFramesByRequest.delete(oldest.requestId);
236
+ else this.s.wsFramesByRequest.set(oldest.requestId, bucket);
237
+ }
238
+ const connection = this.s.wsConnections.get(oldest.requestId);
239
+ if (connection) connection.framesCount = Math.max(0, connection.framesCount - 1);
240
+ }
241
+ }
242
+ getWsFrameStats() {
243
+ let sent = 0;
244
+ let received = 0;
245
+ for (const entry of this.s.wsFrameOrder) if (entry.frame.direction === "sent") sent += 1;
246
+ else received += 1;
247
+ return {
248
+ total: this.s.wsFrameOrder.length,
249
+ sent,
250
+ received
251
+ };
252
+ }
253
+ async handleWsMonitorEnable(args) {
254
+ const maxFrames = parseNumberArg(args.maxFrames, {
255
+ defaultValue: 1e3,
256
+ min: 1,
257
+ max: 2e4,
258
+ integer: true
259
+ });
260
+ const urlFilterRaw = parseOptionalStringArg(args.urlFilter);
261
+ let urlFilter;
262
+ if (urlFilterRaw) {
263
+ const compiled = compileRegex(urlFilterRaw);
264
+ if (compiled.error) return asJson({
265
+ success: false,
266
+ error: `Invalid urlFilter regex: ${compiled.error}`
267
+ });
268
+ urlFilter = compiled.regex;
269
+ }
270
+ await this.teardownWsSession();
271
+ this.s.wsFramesByRequest.clear();
272
+ this.s.wsFrameOrder = new RingBuffer(maxFrames);
273
+ this.s.wsConnections.clear();
274
+ const session = await (await this.s.collector.getActivePage()).createCDPSession();
275
+ await session.send("Network.enable");
276
+ const listeners = {
277
+ created: (params) => {
278
+ const reqId = getStringField(params, "requestId");
279
+ const url = getStringField(params, "url");
280
+ if (!reqId || !url) return;
281
+ if (urlFilter && !urlFilter.test(url)) return;
282
+ const existing = this.s.wsConnections.get(reqId);
283
+ this.s.wsConnections.set(reqId, {
284
+ requestId: reqId,
285
+ url,
286
+ status: existing?.status ?? "connecting",
287
+ framesCount: existing?.framesCount ?? 0,
288
+ createdTimestamp: existing?.createdTimestamp ?? Date.now() / 1e3,
289
+ closedTimestamp: existing?.closedTimestamp,
290
+ handshakeStatus: existing?.handshakeStatus
291
+ });
292
+ },
293
+ closed: (params) => {
294
+ const reqId = getStringField(params, "requestId");
295
+ if (!reqId) return;
296
+ const connection = this.s.wsConnections.get(reqId);
297
+ if (!connection) return;
298
+ connection.status = "closed";
299
+ const ts = getNumberField(params, "timestamp");
300
+ connection.closedTimestamp = ts !== void 0 ? ts : Date.now() / 1e3;
301
+ },
302
+ handshake: (params) => {
303
+ const reqId = getStringField(params, "requestId");
304
+ if (!reqId) return;
305
+ const connection = this.s.wsConnections.get(reqId);
306
+ if (!connection) return;
307
+ const status = getNumberField(getRecordField(params, "response"), "status");
308
+ if (status !== void 0) {
309
+ connection.handshakeStatus = status;
310
+ connection.status = status >= 100 && status < 400 ? "open" : "error";
311
+ }
312
+ },
313
+ frameSent: (params) => {
314
+ this.handleWsFrame("sent", params);
315
+ },
316
+ frameReceived: (params) => {
317
+ this.handleWsFrame("received", params);
318
+ }
319
+ };
320
+ session.on("Network.webSocketCreated", listeners.created);
321
+ session.on("Network.webSocketClosed", listeners.closed);
322
+ session.on("Network.webSocketHandshakeResponseReceived", listeners.handshake);
323
+ session.on("Network.webSocketFrameSent", listeners.frameSent);
324
+ session.on("Network.webSocketFrameReceived", listeners.frameReceived);
325
+ this.s.wsSession = session;
326
+ this.s.wsListeners = listeners;
327
+ this.s.wsConfig = {
328
+ enabled: true,
329
+ maxFrames,
330
+ urlFilterRaw,
331
+ urlFilter
332
+ };
333
+ return asJson({
334
+ success: true,
335
+ message: "WebSocket monitor enabled",
336
+ config: {
337
+ maxFrames,
338
+ urlFilter: urlFilterRaw ?? null
339
+ },
340
+ stats: {
341
+ trackedConnections: this.s.wsConnections.size,
342
+ capturedFrames: this.s.wsFrameOrder.length
343
+ }
344
+ });
345
+ }
346
+ async handleWsMonitorDisable(_args) {
347
+ const stats = this.getWsFrameStats();
348
+ const connections = Array.from(this.s.wsConnections.values());
349
+ const summary = {
350
+ success: true,
351
+ message: "WebSocket monitor disabled",
352
+ config: {
353
+ maxFrames: this.s.wsConfig.maxFrames,
354
+ urlFilter: this.s.wsConfig.urlFilterRaw ?? null
355
+ },
356
+ summary: {
357
+ trackedConnections: connections.length,
358
+ activeConnections: connections.filter((c) => c.status === "open" || c.status === "connecting").length,
359
+ closedConnections: connections.filter((c) => c.status === "closed").length,
360
+ totalFrames: stats.total,
361
+ sentFrames: stats.sent,
362
+ receivedFrames: stats.received
363
+ }
364
+ };
365
+ await this.teardownWsSession();
366
+ this.s.wsConfig = {
367
+ ...this.s.wsConfig,
368
+ enabled: false
369
+ };
370
+ return asJson(summary);
371
+ }
372
+ async handleWsGetFrames(args) {
373
+ const direction = parseWsDirection(args.direction);
374
+ const limit = parseNumberArg(args.limit, {
375
+ defaultValue: 100,
376
+ min: 1,
377
+ max: 5e3,
378
+ integer: true
379
+ });
380
+ const offset = parseNumberArg(args.offset, {
381
+ defaultValue: 0,
382
+ min: 0,
383
+ max: Number.MAX_SAFE_INTEGER,
384
+ integer: true
385
+ });
386
+ const payloadFilterRaw = parseOptionalStringArg(args.payloadFilter);
387
+ let payloadFilter;
388
+ if (payloadFilterRaw) {
389
+ const compiled = compileRegex(payloadFilterRaw);
390
+ if (compiled.error) return asJson({
391
+ success: false,
392
+ error: `Invalid payloadFilter regex: ${compiled.error}`
393
+ });
394
+ payloadFilter = compiled.regex;
395
+ }
396
+ const filtered = this.s.wsFrameOrder.toArray().map((entry) => entry.frame).filter((frame) => direction === "all" ? true : frame.direction === direction).filter((frame) => payloadFilter ? payloadFilter.test(frame.payloadSample) : true);
397
+ const pageItems = filtered.slice(offset, offset + limit).map((frame) => ({
398
+ requestId: frame.requestId,
399
+ timestamp: frame.timestamp,
400
+ direction: frame.direction,
401
+ opcode: frame.opcode,
402
+ payloadLength: frame.payloadLength,
403
+ payloadPreview: frame.payloadPreview,
404
+ isBinary: frame.isBinary
405
+ }));
406
+ return asJson({
407
+ success: true,
408
+ monitorEnabled: this.s.wsConfig.enabled,
409
+ filters: {
410
+ direction,
411
+ payloadFilter: payloadFilterRaw ?? null
412
+ },
413
+ page: {
414
+ offset,
415
+ limit,
416
+ returned: pageItems.length,
417
+ totalAfterFilter: filtered.length,
418
+ hasMore: offset + pageItems.length < filtered.length,
419
+ nextOffset: offset + pageItems.length < filtered.length ? offset + pageItems.length : null
420
+ },
421
+ frames: pageItems
422
+ });
423
+ }
424
+ async handleWsGetConnections(_args) {
425
+ const connections = Array.from(this.s.wsConnections.values()).toSorted((a, b) => a.createdTimestamp - b.createdTimestamp).map((conn) => ({
426
+ requestId: conn.requestId,
427
+ url: conn.url,
428
+ status: conn.status,
429
+ framesCount: conn.framesCount
430
+ }));
431
+ return asJson({
432
+ success: true,
433
+ monitorEnabled: this.s.wsConfig.enabled,
434
+ total: connections.length,
435
+ connections
436
+ });
437
+ }
438
+ };
439
+ //#endregion
440
+ //#region src/server/domains/streaming/handlers/sse-handlers.ts
441
+ function sseInjectionFn(config) {
442
+ const globalWindow = window;
443
+ if (!globalWindow.__jshookSSEMonitor) globalWindow.__jshookSSEMonitor = {
444
+ enabled: true,
445
+ patched: false,
446
+ maxEvents: config.maxEvents,
447
+ urlFilterRaw: config.urlFilterRaw,
448
+ events: [],
449
+ sources: {}
450
+ };
451
+ const state = globalWindow.__jshookSSEMonitor;
452
+ state.enabled = true;
453
+ state.maxEvents = config.maxEvents;
454
+ state.urlFilterRaw = config.urlFilterRaw;
455
+ if (state.events.length > state.maxEvents) state.events = state.events.slice(-state.maxEvents);
456
+ const shouldCapture = (sourceUrl) => {
457
+ if (!state.urlFilterRaw) return true;
458
+ try {
459
+ return new RegExp(state.urlFilterRaw).test(sourceUrl);
460
+ } catch {
461
+ return true;
462
+ }
463
+ };
464
+ const toDataString = (value) => {
465
+ if (typeof value === "string") return value;
466
+ if (value === null || value === void 0) return "";
467
+ if (typeof value === "object") try {
468
+ return JSON.stringify(value);
469
+ } catch {
470
+ return "[unserializable]";
471
+ }
472
+ return String(value);
473
+ };
474
+ const pushEvent = (sourceUrl, eventType, rawData, lastEventId) => {
475
+ if (!state.enabled || !shouldCapture(sourceUrl)) return;
476
+ const dataString = toDataString(rawData);
477
+ const record = {
478
+ sourceUrl,
479
+ eventType,
480
+ dataPreview: dataString.length > 200 ? `${dataString.slice(0, 200)}…` : dataString,
481
+ dataLength: dataString.length,
482
+ lastEventId,
483
+ timestamp: Date.now()
484
+ };
485
+ state.events.push(record);
486
+ while (state.events.length > state.maxEvents) state.events.shift();
487
+ const source = state.sources[sourceUrl] ?? {
488
+ url: sourceUrl,
489
+ status: "connecting",
490
+ eventCount: 0
491
+ };
492
+ source.eventCount += 1;
493
+ source.lastEventTimestamp = record.timestamp;
494
+ state.sources[sourceUrl] = source;
495
+ };
496
+ if (typeof globalWindow.EventSource === "undefined") return {
497
+ success: false,
498
+ error: "EventSource is not available in current page context"
499
+ };
500
+ if (!state.patched) {
501
+ const OriginalEventSource = globalWindow.EventSource;
502
+ const WrappedEventSource = function(url, eventSourceInitDict) {
503
+ const sourceUrl = String(url);
504
+ const es = new OriginalEventSource(url, eventSourceInitDict);
505
+ if (shouldCapture(sourceUrl)) {
506
+ const source = state.sources[sourceUrl] ?? {
507
+ url: sourceUrl,
508
+ status: "connecting",
509
+ eventCount: 0
510
+ };
511
+ state.sources[sourceUrl] = source;
512
+ }
513
+ es.addEventListener("open", () => {
514
+ const source = state.sources[sourceUrl];
515
+ if (source) source.status = "open";
516
+ pushEvent(sourceUrl, "open", "", null);
517
+ });
518
+ es.addEventListener("error", () => {
519
+ const source = state.sources[sourceUrl];
520
+ if (source) source.status = "error";
521
+ pushEvent(sourceUrl, "error", "", null);
522
+ });
523
+ es.addEventListener("message", (event) => {
524
+ const lastEventId = typeof event.lastEventId === "string" && event.lastEventId.length > 0 ? event.lastEventId : null;
525
+ pushEvent(sourceUrl, event.type || "message", event.data, lastEventId);
526
+ });
527
+ const originalAddEventListener = es.addEventListener.bind(es);
528
+ const callOriginalAddEventListener = (type, listener, listenerOpts) => {
529
+ originalAddEventListener(type, listener, listenerOpts);
530
+ };
531
+ const wrappedAddEventListener = (type, listener, listenerOpts) => {
532
+ if (type !== "message" && type !== "open" && type !== "error" && listener) {
533
+ const wrapped = (evt) => {
534
+ const messageEvent = evt;
535
+ const lastEventId = typeof messageEvent.lastEventId === "string" && messageEvent.lastEventId.length > 0 ? messageEvent.lastEventId : null;
536
+ pushEvent(sourceUrl, type, messageEvent.data, lastEventId);
537
+ if (typeof listener === "function") listener.call(es, evt);
538
+ else listener.handleEvent(evt);
539
+ };
540
+ callOriginalAddEventListener(type, wrapped, listenerOpts);
541
+ return;
542
+ }
543
+ callOriginalAddEventListener(type, listener, listenerOpts);
544
+ };
545
+ Object.defineProperty(es, "addEventListener", {
546
+ value: wrappedAddEventListener,
547
+ configurable: true,
548
+ writable: true
549
+ });
550
+ return es;
551
+ };
552
+ WrappedEventSource.prototype = OriginalEventSource.prototype;
553
+ try {
554
+ Object.defineProperty(WrappedEventSource, "CONNECTING", { value: OriginalEventSource.CONNECTING });
555
+ Object.defineProperty(WrappedEventSource, "OPEN", { value: OriginalEventSource.OPEN });
556
+ Object.defineProperty(WrappedEventSource, "CLOSED", { value: OriginalEventSource.CLOSED });
557
+ } catch {}
558
+ globalWindow.EventSource = WrappedEventSource;
559
+ state.originalEventSource = OriginalEventSource;
560
+ state.patched = true;
561
+ }
562
+ return {
563
+ success: true,
564
+ message: "SSE monitor enabled",
565
+ patched: state.patched,
566
+ urlFilter: state.urlFilterRaw,
567
+ maxEvents: state.maxEvents,
568
+ existingEvents: state.events.length
569
+ };
570
+ }
571
+ var SseHandlers = class {
572
+ constructor(s) {
573
+ this.s = s;
574
+ }
575
+ async enableSseInterceptor(maxEvents, urlFilterRaw, options) {
576
+ const page = await this.s.collector.getActivePage();
577
+ if (options?.persistent) {
578
+ await evaluateOnNewDocumentWithTimeout(page, sseInjectionFn, {
579
+ maxEvents,
580
+ urlFilterRaw
581
+ });
582
+ return {
583
+ success: true,
584
+ message: "SSE monitor enabled (persistent — survives navigations)",
585
+ patched: true,
586
+ urlFilter: urlFilterRaw,
587
+ maxEvents,
588
+ existingEvents: 0
589
+ };
590
+ }
591
+ return await evaluateWithTimeout(page, sseInjectionFn, {
592
+ maxEvents,
593
+ urlFilterRaw
594
+ });
595
+ }
596
+ async handleSseMonitorEnable(args) {
597
+ const maxEvents = parseNumberArg(args.maxEvents, {
598
+ defaultValue: 2e3,
599
+ min: 1,
600
+ max: 5e4,
601
+ integer: true
602
+ });
603
+ const urlFilterRaw = parseOptionalStringArg(args.urlFilter);
604
+ if (urlFilterRaw) {
605
+ const compiled = compileRegex(urlFilterRaw);
606
+ if (compiled.error) return asJson({
607
+ success: false,
608
+ error: `Invalid urlFilter regex: ${compiled.error}`
609
+ });
610
+ }
611
+ const persistent = args.persistent === true;
612
+ const result = await this.enableSseInterceptor(maxEvents, urlFilterRaw, { persistent });
613
+ if (!result.success) return asJson(result);
614
+ this.s.sseConfig = {
615
+ maxEvents,
616
+ urlFilterRaw
617
+ };
618
+ return asJson({
619
+ success: true,
620
+ message: result.message,
621
+ patched: result.patched,
622
+ config: {
623
+ maxEvents: this.s.sseConfig.maxEvents,
624
+ urlFilter: this.s.sseConfig.urlFilterRaw ?? null
625
+ },
626
+ existingEvents: result.existingEvents
627
+ });
628
+ }
629
+ async handleSseGetEvents(args) {
630
+ const sourceUrl = parseOptionalStringArg(args.sourceUrl);
631
+ const eventType = parseOptionalStringArg(args.eventType);
632
+ const limit = parseNumberArg(args.limit, {
633
+ defaultValue: 100,
634
+ min: 1,
635
+ max: 5e3,
636
+ integer: true
637
+ });
638
+ const offset = parseNumberArg(args.offset, {
639
+ defaultValue: 0,
640
+ min: 0,
641
+ max: Number.MAX_SAFE_INTEGER,
642
+ integer: true
643
+ });
644
+ return asJson(await evaluateWithTimeout(await this.s.collector.getActivePage(), (query) => {
645
+ const state = window.__jshookSSEMonitor;
646
+ if (!state) return {
647
+ success: false,
648
+ message: "SSE monitor is not enabled. Call sse_monitor_enable first."
649
+ };
650
+ let events = state.events;
651
+ if (query.sourceUrl) events = events.filter((evt) => evt.sourceUrl === query.sourceUrl);
652
+ if (query.eventType) events = events.filter((evt) => evt.eventType === query.eventType);
653
+ const totalAfterFilter = events.length;
654
+ const paged = events.slice(query.offset, query.offset + query.limit);
655
+ return {
656
+ success: true,
657
+ filters: {
658
+ sourceUrl: query.sourceUrl ?? null,
659
+ eventType: query.eventType ?? null
660
+ },
661
+ page: {
662
+ offset: query.offset,
663
+ limit: query.limit,
664
+ returned: paged.length,
665
+ totalAfterFilter,
666
+ hasMore: query.offset + paged.length < totalAfterFilter,
667
+ nextOffset: query.offset + paged.length < totalAfterFilter ? query.offset + paged.length : null
668
+ },
669
+ monitor: {
670
+ enabled: state.enabled,
671
+ patched: state.patched,
672
+ maxEvents: state.maxEvents,
673
+ urlFilter: state.urlFilterRaw ?? null,
674
+ sourceCount: Object.keys(state.sources).length
675
+ },
676
+ events: paged
677
+ };
678
+ }, {
679
+ sourceUrl,
680
+ eventType,
681
+ limit,
682
+ offset
683
+ }));
684
+ }
685
+ };
686
+ //#endregion
687
+ //#region src/server/domains/streaming/handlers.impl.core.ts
688
+ var StreamingToolHandlers = class {
689
+ collector;
690
+ state;
691
+ ws;
692
+ sse;
693
+ get wsConnections() {
694
+ return this.state.wsConnections;
695
+ }
696
+ get wsFrameOrder() {
697
+ return this.state.wsFrameOrder;
698
+ }
699
+ get wsConfig() {
700
+ return this.state.wsConfig;
701
+ }
702
+ get wsFramesByRequest() {
703
+ return this.state.wsFramesByRequest;
704
+ }
705
+ get sseConfig() {
706
+ return this.state.sseConfig;
707
+ }
708
+ constructor(collector) {
709
+ this.collector = collector;
710
+ this.state = createStreamingSharedState(collector);
711
+ this.ws = new WsHandlers(this.state);
712
+ this.sse = new SseHandlers(this.state);
713
+ }
714
+ handleWsMonitorDispatch = (args) => {
715
+ return String(args["action"] ?? "") === "disable" ? this.ws.handleWsMonitorDisable(args) : this.ws.handleWsMonitorEnable(args);
716
+ };
717
+ handleWsMonitorEnable = (args) => this.ws.handleWsMonitorEnable(args);
718
+ handleWsMonitorDisable = (args) => this.ws.handleWsMonitorDisable(args);
719
+ handleWsGetFrames = (args) => this.ws.handleWsGetFrames(args);
720
+ handleWsGetConnections = (args) => this.ws.handleWsGetConnections(args);
721
+ handleSseMonitorEnable = (args) => this.sse.handleSseMonitorEnable(args);
722
+ handleSseGetEvents = (args) => this.sse.handleSseGetEvents(args);
723
+ };
724
+ //#endregion
725
+ export { StreamingToolHandlers };