@jshookmcp/jshook 0.2.9 → 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 (187) hide show
  1. package/README.md +2 -2
  2. package/README.zh.md +2 -2
  3. package/dist/{AntiCheatDetector-BNk-EoBt.mjs → AntiCheatDetector-CqGDXmfc.mjs} +159 -53
  4. package/dist/{CodeInjector-Cq8q01kp.mjs → CodeInjector-BdjRfNx7.mjs} +5 -5
  5. package/dist/{ConsoleMonitor-CPVQW1Y-.mjs → ConsoleMonitor-DykL3IAw.mjs} +85 -17
  6. package/dist/{DetailedDataManager-BQQcxh64.mjs → DetailedDataManager-HT49OrvF.mjs} +1 -1
  7. package/dist/{ExtensionManager-CWYgw0YW.mjs → ExtensionManager-BDMsY2Dz.mjs} +15 -8
  8. package/dist/{HardwareBreakpoint-B9gZCdFP.mjs → HardwareBreakpoint-Cc2AFq1Y.mjs} +3 -3
  9. package/dist/{HeapAnalyzer-BLDH0dCv.mjs → HeapAnalyzer-DruMgsgj.mjs} +20 -20
  10. package/dist/{HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs → HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs} +1 -74
  11. package/dist/{InstrumentationSession-CvPC7Jwy.mjs → InstrumentationSession-DLH0vd-z.mjs} +2 -2
  12. package/dist/{MemoryController-CbVdCIJF.mjs → MemoryController-CMtviNW_.mjs} +3 -3
  13. package/dist/{MemoryScanSession-BsDZbLYm.mjs → MemoryScanSession-ITgb_NMi.mjs} +2 -2
  14. package/dist/{MemoryScanner-Bcpml6II.mjs → MemoryScanner-CiL7Z3ey.mjs} +12 -9
  15. package/dist/{NativeMemoryManager.impl-dZtA1ZGn.mjs → NativeMemoryManager.impl-D9Lkovvn.mjs} +13 -10
  16. package/dist/{NativeMemoryManager.utils-B-FjA2mJ.mjs → NativeMemoryManager.utils-BBlAixF5.mjs} +1 -1
  17. package/dist/{PEAnalyzer-D1lzJ_VG.mjs → PEAnalyzer-DMQ44gen.mjs} +15 -15
  18. package/dist/{PageController-Bqm2kZ_X.mjs → PageController-BPJNqqBN.mjs} +18 -4
  19. package/dist/{PointerChainEngine-BOhyVsjx.mjs → PointerChainEngine-K7wN8Z-w.mjs} +10 -7
  20. package/dist/ProcessRegistry-zGg12QbE.mjs +74 -0
  21. package/dist/{ResponseBuilder-D3iFYx2N.mjs → ResponseBuilder-CJXWmWNw.mjs} +10 -10
  22. package/dist/{ScriptManager-aHHq0X7U.mjs → ScriptManager-ZuWD-0Jg.mjs} +195 -192
  23. package/dist/{Speedhack-CqdIFlQl.mjs → Speedhack-D-z0umeT.mjs} +2 -2
  24. package/dist/{StructureAnalyzer-DhFaPvRO.mjs → StructureAnalyzer-Cav5AVSL.mjs} +9 -6
  25. package/dist/{ToolCatalog-C0JGZoOm.mjs → ToolCatalog-5OJdMiF0.mjs} +81 -81
  26. package/dist/{ToolProbe-oC7aPrkv.mjs → ToolProbe-DbCFGyrg.mjs} +1 -1
  27. package/dist/{ToolRegistry-BjaF4oNz.mjs → ToolRegistry-B9krbTtI.mjs} +51 -2
  28. package/dist/{ToolRouter.policy-BWV67ZK-.mjs → ToolRouter.policy-BGDAGyeH.mjs} +60 -20
  29. package/dist/TraceRecorder-B41Z5XBj.mjs +1286 -0
  30. package/dist/{Win32API-CePkipZY.mjs → Win32API-C2kjj0ze.mjs} +18 -12
  31. package/dist/{Win32Debug-BvKs-gxc.mjs → Win32Debug-CKrGOTpo.mjs} +2 -2
  32. package/dist/{WorkflowEngine-CuvkZtWu.mjs → WorkflowEngine-DJ6M4opp.mjs} +226 -255
  33. package/dist/analysis-BHeJW2Nb.mjs +1234 -0
  34. package/dist/{antidebug-CqDTB_uk.mjs → antidebug-BRKeyt27.mjs} +3 -3
  35. package/dist/{artifactRetention-CFEprwPw.mjs → artifactRetention-CPXkUJXp.mjs} +13 -6
  36. package/dist/{artifacts-Bk2-_uPq.mjs → artifacts-DkfosXH3.mjs} +1 -1
  37. package/dist/authorization-schema-DRqyJMSk.mjs +31 -0
  38. package/dist/{binary-instrument-CXfpx6fT.mjs → binary-instrument--V3MAhJ4.mjs} +19 -27
  39. package/dist/bind-helpers-ClV34xdn.mjs +42 -0
  40. package/dist/{boringssl-inspector-BH2D3VKc.mjs → boringssl-inspector-Bo_LOLaS.mjs} +1 -1
  41. package/dist/{browser-BpOr5PEx.mjs → browser-Dx3_S2cG.mjs} +324 -37
  42. package/dist/capabilities-CcHlvWgK.mjs +33 -0
  43. package/dist/{constants-B0OANIBL.mjs → constants-CDZLOoVv.mjs} +18 -3
  44. package/dist/{coordination-qUbyF8KU.mjs → coordination-DgItD9DL.mjs} +2 -2
  45. package/dist/{debugger-gnKxRSN0.mjs → debugger-RS3RSAqs.mjs} +30 -13
  46. package/dist/definitions-BEoYofW5.mjs +47 -0
  47. package/dist/{definitions-bAhHQJq9.mjs → definitions-BRaefg3u.mjs} +11 -5
  48. package/dist/{definitions-DVGfrn7y.mjs → definitions-BbkvZkiv.mjs} +2 -2
  49. package/dist/definitions-BtWSHJ3o.mjs +17 -0
  50. package/dist/{definitions-BMfYXoNC.mjs → definitions-C1gCHO0i.mjs} +1 -1
  51. package/dist/{definitions-C1UvM5Iy.mjs → definitions-CDOg_b-l.mjs} +14 -2
  52. package/dist/definitions-CVPD9hzZ.mjs +54 -0
  53. package/dist/{definitions-Cke7zEb8.mjs → definitions-Cea8Lgl7.mjs} +1 -1
  54. package/dist/definitions-DAgIyjxM.mjs +10 -0
  55. package/dist/{definitions-B4rAvHNZ.mjs → definitions-DJA27nsL.mjs} +12 -9
  56. package/dist/{definitions-ClJLzsJQ.mjs → definitions-DKPFU3LW.mjs} +1 -1
  57. package/dist/{definitions-D3VsGcvz.mjs → definitions-DPRpZQ96.mjs} +7 -7
  58. package/dist/{definitions-B18eyf0B.mjs → definitions-DUE5gmdn.mjs} +1 -1
  59. package/dist/definitions-DYVjOtxa.mjs +26 -0
  60. package/dist/{definitions-BB_4jnmy.mjs → definitions-DcYLVLCo.mjs} +1 -1
  61. package/dist/{definitions-Beid2EB3.mjs → definitions-Pp5LI2H4.mjs} +1 -1
  62. package/dist/definitions-j9KdHVNR.mjs +14 -0
  63. package/dist/definitions-uzkjBwa7.mjs +258 -0
  64. package/dist/{definitions-Cq-zroAU.mjs → definitions-va-AnLuQ.mjs} +4 -4
  65. package/dist/{encoding-Bvz5jLRv.mjs → encoding-DJeqHmpd.mjs} +18 -4
  66. package/dist/{evidence-graph-bridge-C_fv9PuC.mjs → evidence-graph-bridge-DcYizFk2.mjs} +1 -0
  67. package/dist/{factory-DxlGh9Xf.mjs → factory-C90tBff6.mjs} +6 -6
  68. package/dist/flat-target-session-Dgax2Cy3.mjs +29 -0
  69. package/dist/{graphql-DYWzJ29s.mjs → graphql-CoHrhweh.mjs} +205 -34
  70. package/dist/{handlers-C67ktuRN.mjs → handlers-4jmR0nMs.mjs} +220 -32
  71. package/dist/{handlers-DlCJN4Td.mjs → handlers-BAHPxcch.mjs} +122 -90
  72. package/dist/{handlers-9sAbfIg-.mjs → handlers-BOs9b907.mjs} +849 -801
  73. package/dist/{handlers-DxGIq15_2.mjs → handlers-BWXEy6ef.mjs} +16 -16
  74. package/dist/{handlers-tB9Mp9ZK.mjs → handlers-Bndn6QvE.mjs} +31 -4
  75. package/dist/{handlers-CTsDAO6p.mjs → handlers-BqC4bD4s.mjs} +1 -1
  76. package/dist/{handlers-C87g8oCe.mjs → handlers-BtYq60bM2.mjs} +1 -1
  77. package/dist/{handlers-DeLOCd5m.mjs → handlers-BzgcB4iv.mjs} +17 -17
  78. package/dist/{handlers-Cgyg6c0U.mjs → handlers-CRyRWj2b.mjs} +237 -23
  79. package/dist/{handlers-U6L4xhuF.mjs → handlers-CVv2H1uq.mjs} +24 -17
  80. package/dist/{handlers-tiy7EIBp.mjs → handlers-Dl5a7JS4.mjs} +3 -3
  81. package/dist/{handlers-D6j6yka7.mjs → handlers-Dx2d7jt7.mjs} +1893 -1480
  82. package/dist/{handlers-Bl8zkwz1.mjs → handlers-Dz9PYsCa.mjs} +95 -6
  83. package/dist/handlers-HujRKC3b.mjs +661 -0
  84. package/dist/{handlers.impl-DS0d9fUw.mjs → handlers.impl-XWXkQfyi.mjs} +70 -24
  85. package/dist/{hooks-CzCWByww.mjs → hooks-B1B8NRHL.mjs} +3 -3
  86. package/dist/index.mjs +154 -144
  87. package/dist/{maintenance-P7ePRXQC.mjs → maintenance-PRMkLVRW.mjs} +35 -30
  88. package/dist/manifest-67Bok-Si.mjs +58 -0
  89. package/dist/{manifest-B3QVVeBS.mjs → manifest-6lNTMZAB2.mjs} +33 -28
  90. package/dist/manifest-B2duEHiH.mjs +90 -0
  91. package/dist/manifest-B6EY9Vm8.mjs +57 -0
  92. package/dist/{manifest-gZ4s_UtG.mjs → manifest-B6nKSbyY.mjs} +32 -33
  93. package/dist/{manifest-2ToTpjv8.mjs → manifest-BL8AQNPF.mjs} +31 -31
  94. package/dist/{manifest-DzwvxPJX.mjs → manifest-BSZvJJmV.mjs} +23 -14
  95. package/dist/{manifest-Sc_0JQ13.mjs → manifest-BU7qzUyX.mjs} +23 -23
  96. package/dist/{manifest-CT7zZBV1.mjs → manifest-Bl62e8WK.mjs} +24 -23
  97. package/dist/manifest-Bo5cXjdt.mjs +82 -0
  98. package/dist/manifest-BpS4gtUK.mjs +1347 -0
  99. package/dist/manifest-Bv65_e2W.mjs +101 -0
  100. package/dist/manifest-BytNIF4Z.mjs +117 -0
  101. package/dist/{manifest-BqrQ4Tpj.mjs → manifest-C-xtsjS3.mjs} +23 -23
  102. package/dist/{manifest-NXctwWQq.mjs → manifest-CDYl7OhA.mjs} +36 -38
  103. package/dist/manifest-CRZ3xmkD.mjs +61 -0
  104. package/dist/manifest-CoW6u4Tp.mjs +132 -0
  105. package/dist/manifest-Cq5zN_8A.mjs +50 -0
  106. package/dist/{manifest-CAhOuvSl.mjs → manifest-D7YZM_2e.mjs} +75 -85
  107. package/dist/{manifest-DCyjf4n2.mjs → manifest-DE_VrAeQ.mjs} +27 -7
  108. package/dist/manifest-DGsXSCpT.mjs +39 -0
  109. package/dist/{manifest-BB2J8IMJ.mjs → manifest-DJ2vfEuW.mjs} +48 -41
  110. package/dist/{manifest-3g71z6Bg.mjs → manifest-DPXDYhEu.mjs} +26 -25
  111. package/dist/manifest-Dd4fQb0a.mjs +322 -0
  112. package/dist/{manifest-CXsRWjjI.mjs → manifest-Deq6opGg.mjs} +95 -96
  113. package/dist/{manifest-C9RT5nk32.mjs → manifest-DfJTafJK.mjs} +14 -11
  114. package/dist/manifest-DgOdgN_j.mjs +50 -0
  115. package/dist/{manifest-BmtZzQiQ2.mjs → manifest-DlbMW4v4.mjs} +17 -15
  116. package/dist/{manifest-DrbmZcFl2.mjs → manifest-DmVfbH0w.mjs} +212 -91
  117. package/dist/manifest-Dog6Ddjr.mjs +109 -0
  118. package/dist/manifest-DvgU5FWb.mjs +58 -0
  119. package/dist/manifest-HsfDBs7j.mjs +50 -0
  120. package/dist/manifest-I8oQHvCG.mjs +186 -0
  121. package/dist/manifest-NvH_a-av.mjs +786 -0
  122. package/dist/{manifest-Dh8WBmEW.mjs → manifest-cEJU1v0Z.mjs} +24 -24
  123. package/dist/manifest-wOl5XLB12.mjs +112 -0
  124. package/dist/{modules-C184v-S9.mjs → modules-tZozf0LQ.mjs} +130 -860
  125. package/dist/{mojo-ipc-B_H61Afw.mjs → mojo-ipc-DXNEXEqb.mjs} +141 -26
  126. package/dist/{network-671Cw6hV.mjs → network-CPVvwvFg.mjs} +1329 -823
  127. package/dist/{outputPaths-B1uGmrWZ.mjs → outputPaths-um7lCRY3.mjs} +4 -8
  128. package/dist/{platform-WmNn8Sxb.mjs → platform-CYeFoTWp.mjs} +101 -10
  129. package/dist/{process-QcbIy5Zq.mjs → process-BTbgcVc6.mjs} +251 -346
  130. package/dist/{proxy-DqNs0bAd.mjs → proxy-r8YN6nP1.mjs} +30 -8
  131. package/dist/{registry-D-6e18lB.mjs → registry-Bl8ZQW61.mjs} +3 -3
  132. package/dist/{response-BQVP-xUn.mjs → response-CWhh2aLo.mjs} +7 -1
  133. package/dist/{shared-state-board-DV-dpHFJ.mjs → shared-state-board-BoZnSoj-.mjs} +2 -2
  134. package/dist/{sourcemap-Dq8ez8vS.mjs → sourcemap-BIDHUVXy.mjs} +350 -66
  135. package/dist/{streaming-BUQ0VJsg.mjs → streaming-Dal6utPp.mjs} +13 -13
  136. package/dist/{tool-builder-DCbIC5Eo.mjs → tool-builder-BHJp32mV.mjs} +1 -1
  137. package/dist/{transform-CiYJfNX0.mjs → transform-DRVgGG90.mjs} +18 -14
  138. package/dist/wasm-BYx5UOeG.mjs +1044 -0
  139. package/dist/webcrack-Be0_FccV.mjs +747 -0
  140. package/dist/{workflow-f3xJOcjx.mjs → workflow-BpuKEtvn.mjs} +8 -8
  141. package/package.json +76 -43
  142. package/dist/TraceRecorder-DgxyVbdQ.mjs +0 -519
  143. package/dist/analysis-CL9uACt9.mjs +0 -463
  144. package/dist/bind-helpers-xFfRF-qm.mjs +0 -22
  145. package/dist/definitions-6M-eejaT.mjs +0 -53
  146. package/dist/definitions-B3QdlrHv.mjs +0 -34
  147. package/dist/definitions-CXEI7QC72.mjs +0 -216
  148. package/dist/definitions-C_4r7Fo-2.mjs +0 -14
  149. package/dist/definitions-CkFDALoa.mjs +0 -26
  150. package/dist/definitions-Cy3Sl6gV.mjs +0 -34
  151. package/dist/definitions-LKpC3-nL.mjs +0 -9
  152. package/dist/handlers-DdFzXLvF.mjs +0 -446
  153. package/dist/manifest-82baTv4U.mjs +0 -45
  154. package/dist/manifest-BKbgbSiY.mjs +0 -60
  155. package/dist/manifest-Bcf-TJzH.mjs +0 -848
  156. package/dist/manifest-Bnd7kqEY.mjs +0 -55
  157. package/dist/manifest-BqQX6OQC2.mjs +0 -65
  158. package/dist/manifest-Br4RPFt5.mjs +0 -370
  159. package/dist/manifest-C5qDjysN.mjs +0 -107
  160. package/dist/manifest-CBYWCUBJ.mjs +0 -51
  161. package/dist/manifest-CFADCRa1.mjs +0 -37
  162. package/dist/manifest-CQVhavRF.mjs +0 -114
  163. package/dist/manifest-CV12bcrF.mjs +0 -121
  164. package/dist/manifest-CZLUCfG02.mjs +0 -95
  165. package/dist/manifest-D6phHKFd.mjs +0 -131
  166. package/dist/manifest-DHsnKgP6.mjs +0 -60
  167. package/dist/manifest-Df_dliIe.mjs +0 -55
  168. package/dist/manifest-DhKRAT8_.mjs +0 -92
  169. package/dist/manifest-DlpTj4ic2.mjs +0 -193
  170. package/dist/manifest-DuwHjUa5.mjs +0 -70
  171. package/dist/manifest-qSleDqdO.mjs +0 -1023
  172. package/dist/wasm-DQTnHDs4.mjs +0 -531
  173. /package/dist/{CacheAdapters-CDe5WPSV.mjs → CacheAdapters-jJFy20G-.mjs} +0 -0
  174. /package/dist/{DarwinAPI-BNPxu0RH.mjs → DarwinAPI-ETyy0xyo.mjs} +0 -0
  175. /package/dist/{EventBus-DgPmwpeu.mjs → EventBus-DFKvADm3.mjs} +0 -0
  176. /package/dist/{EvidenceGraphBridge-SFesNera.mjs → EvidenceGraphBridge-318Oi0Lf.mjs} +0 -0
  177. /package/dist/{FingerprintManager-gzWtkKuf.mjs → FingerprintManager-BN4UQWnX.mjs} +0 -0
  178. /package/dist/{PrerequisiteError-Dl33Svkz.mjs → PrerequisiteError-TuyZIs6n.mjs} +0 -0
  179. /package/dist/{ReverseEvidenceGraph-Dlsk94LC.mjs → ReverseEvidenceGraph-C02-gXOh.mjs} +0 -0
  180. /package/dist/{StealthVerifier-Bo4T3bz8.mjs → StealthVerifier-BWmPgQsv.mjs} +0 -0
  181. /package/dist/{VersionDetector-CwVLVdDM.mjs → VersionDetector-K3V4vGsw.mjs} +0 -0
  182. /package/dist/{betterSqlite3-0pqusHHH.mjs → betterSqlite3-DLSBZodi.mjs} +0 -0
  183. /package/dist/{concurrency-Bt0yv1kJ.mjs → concurrency-Drev_Vz9.mjs} +0 -0
  184. /package/dist/{formatAddress-DVkj9kpI.mjs → formatAddress-nnMvEohD.mjs} +0 -0
  185. /package/dist/{parse-args-BlRjqlkL.mjs → parse-args-B4cY5Vx5.mjs} +0 -0
  186. /package/dist/{ssrf-policy-ZaUfvhq7.mjs → ssrf-policy-Dsqd-DTX.mjs} +0 -0
  187. /package/dist/{types-CPhOReNX.mjs → types-DDBWs9UP.mjs} +0 -0
@@ -1,519 +0,0 @@
1
- import { n as __require } from "./chunk-CjcI7cDX.mjs";
2
- import { i as resolveArtifactPath } from "./artifacts-Bk2-_uPq.mjs";
3
- import { t as formatBetterSqlite3Error } from "./betterSqlite3-0pqusHHH.mjs";
4
- import { randomUUID } from "node:crypto";
5
- //#region src/modules/trace/TraceDB.ts
6
- let Database;
7
- try {
8
- Database = __require("better-sqlite3");
9
- } catch {}
10
- /** Write-modify SQL keywords rejected by the safety filter. */
11
- const WRITE_SQL_PATTERN = /\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|ATTACH|DETACH|REPLACE|PRAGMA)\b/i;
12
- var TraceDB = class {
13
- db;
14
- batchSize;
15
- eventBuffer = [];
16
- memoryBuffer = [];
17
- closed = false;
18
- insertEventStmt;
19
- insertDeltaStmt;
20
- insertSnapshotStmt;
21
- upsertMetadataStmt;
22
- constructor(options) {
23
- this.options = options;
24
- if (!Database) throw new Error(formatBetterSqlite3Error(/* @__PURE__ */ new Error("Cannot find package 'better-sqlite3'")));
25
- try {
26
- this.db = new Database(options.dbPath);
27
- } catch (error) {
28
- throw new Error(formatBetterSqlite3Error(error), { cause: error });
29
- }
30
- this.batchSize = options.batchSize ?? 200;
31
- this.db.pragma("journal_mode = WAL");
32
- this.db.pragma("synchronous = NORMAL");
33
- this.createSchema();
34
- this.prepareStatements();
35
- }
36
- /** Database file path. */
37
- get dbPath() {
38
- return this.options.dbPath;
39
- }
40
- createSchema() {
41
- this.db.exec(`
42
- CREATE TABLE IF NOT EXISTS events (
43
- id INTEGER PRIMARY KEY AUTOINCREMENT,
44
- timestamp REAL NOT NULL,
45
- category TEXT NOT NULL,
46
- event_type TEXT NOT NULL,
47
- data TEXT NOT NULL DEFAULT '{}',
48
- script_id TEXT,
49
- line_number INTEGER
50
- );
51
- CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
52
- CREATE INDEX IF NOT EXISTS idx_events_category_type ON events(category, event_type);
53
- CREATE INDEX IF NOT EXISTS idx_events_script_id ON events(script_id);
54
-
55
- CREATE TABLE IF NOT EXISTS memory_deltas (
56
- id INTEGER PRIMARY KEY AUTOINCREMENT,
57
- timestamp REAL NOT NULL,
58
- address TEXT NOT NULL,
59
- old_value TEXT NOT NULL,
60
- new_value TEXT NOT NULL,
61
- size INTEGER NOT NULL,
62
- value_type TEXT NOT NULL
63
- );
64
- CREATE INDEX IF NOT EXISTS idx_memory_timestamp ON memory_deltas(timestamp);
65
- CREATE INDEX IF NOT EXISTS idx_memory_address ON memory_deltas(address);
66
-
67
- CREATE TABLE IF NOT EXISTS heap_snapshots (
68
- id INTEGER PRIMARY KEY AUTOINCREMENT,
69
- timestamp REAL NOT NULL,
70
- snapshot_data BLOB,
71
- summary TEXT NOT NULL DEFAULT '{}'
72
- );
73
-
74
- CREATE TABLE IF NOT EXISTS metadata (
75
- key TEXT PRIMARY KEY,
76
- value TEXT NOT NULL
77
- );
78
- `);
79
- }
80
- prepareStatements() {
81
- this.insertEventStmt = this.db.prepare(`
82
- INSERT INTO events (timestamp, category, event_type, data, script_id, line_number)
83
- VALUES (?, ?, ?, ?, ?, ?)
84
- `);
85
- this.insertDeltaStmt = this.db.prepare(`
86
- INSERT INTO memory_deltas (timestamp, address, old_value, new_value, size, value_type)
87
- VALUES (?, ?, ?, ?, ?, ?)
88
- `);
89
- this.insertSnapshotStmt = this.db.prepare(`
90
- INSERT INTO heap_snapshots (timestamp, snapshot_data, summary)
91
- VALUES (?, ?, ?)
92
- `);
93
- this.upsertMetadataStmt = this.db.prepare(`
94
- INSERT INTO metadata (key, value) VALUES (?, ?)
95
- ON CONFLICT(key) DO UPDATE SET value = excluded.value
96
- `);
97
- }
98
- /** Buffer an event for batched insertion. */
99
- insertEvent(event) {
100
- this.ensureOpen();
101
- this.eventBuffer.push(event);
102
- if (this.eventBuffer.length >= this.batchSize) this.flush();
103
- }
104
- /** Buffer a memory delta for batched insertion. */
105
- insertMemoryDelta(delta) {
106
- this.ensureOpen();
107
- this.memoryBuffer.push(delta);
108
- if (this.memoryBuffer.length >= this.batchSize) this.flush();
109
- }
110
- /** Insert a heap snapshot immediately (infrequent, large). */
111
- insertHeapSnapshot(snapshot) {
112
- this.ensureOpen();
113
- this.insertSnapshotStmt.run(snapshot.timestamp, snapshot.snapshotData, snapshot.summary);
114
- }
115
- /** Set or update a metadata key-value pair. */
116
- setMetadata(key, value) {
117
- this.ensureOpen();
118
- this.upsertMetadataStmt.run(key, value);
119
- }
120
- /** Flush all buffered events and memory deltas to disk in a single transaction. */
121
- flush() {
122
- if (this.closed) return;
123
- this.db.transaction(() => {
124
- for (const e of this.eventBuffer) this.insertEventStmt.run(e.timestamp, e.category, e.eventType, e.data, e.scriptId, e.lineNumber);
125
- for (const d of this.memoryBuffer) this.insertDeltaStmt.run(d.timestamp, d.address, d.oldValue, d.newValue, d.size, d.valueType);
126
- })();
127
- this.eventBuffer = [];
128
- this.memoryBuffer = [];
129
- }
130
- /**
131
- * Execute a read-only SQL query against the trace database.
132
- * Write statements are rejected for safety.
133
- */
134
- query(sql) {
135
- this.ensureOpen();
136
- if (WRITE_SQL_PATTERN.test(sql)) throw new Error(`Write operations are not allowed in trace queries. Rejected SQL: ${sql.slice(0, 100)}`);
137
- const stmt = this.db.prepare(sql);
138
- const rows = stmt.all();
139
- if (rows.length === 0) return {
140
- columns: stmt.columns().map((c) => c.name),
141
- rows: [],
142
- rowCount: 0
143
- };
144
- const columns = Object.keys(rows[0]);
145
- return {
146
- columns,
147
- rows: rows.map((row) => columns.map((col) => row[col])),
148
- rowCount: rows.length
149
- };
150
- }
151
- /** Get events within a time range. */
152
- getEventsByTimeRange(start, end) {
153
- this.ensureOpen();
154
- this.flush();
155
- return this.db.prepare(`
156
- SELECT id, timestamp, category, event_type, data, script_id, line_number
157
- FROM events
158
- WHERE timestamp >= ? AND timestamp <= ?
159
- ORDER BY timestamp ASC
160
- `).all(start, end).map((row) => ({
161
- id: row["id"],
162
- timestamp: row["timestamp"],
163
- category: row["category"],
164
- eventType: row["event_type"],
165
- data: row["data"],
166
- scriptId: row["script_id"] ?? null,
167
- lineNumber: row["line_number"] ?? null
168
- }));
169
- }
170
- /** Get memory deltas for a specific address. */
171
- getMemoryDeltasByAddress(address) {
172
- this.ensureOpen();
173
- this.flush();
174
- return this.db.prepare(`
175
- SELECT id, timestamp, address, old_value, new_value, size, value_type
176
- FROM memory_deltas
177
- WHERE address = ?
178
- ORDER BY timestamp ASC
179
- `).all(address).map((row) => ({
180
- id: row["id"],
181
- timestamp: row["timestamp"],
182
- address: row["address"],
183
- oldValue: row["old_value"],
184
- newValue: row["new_value"],
185
- size: row["size"],
186
- valueType: row["value_type"]
187
- }));
188
- }
189
- /** Get all heap snapshots ordered by timestamp. */
190
- getHeapSnapshots() {
191
- this.ensureOpen();
192
- return this.db.prepare(`
193
- SELECT id, timestamp, snapshot_data, summary
194
- FROM heap_snapshots
195
- ORDER BY timestamp ASC
196
- `).all().map((row) => ({
197
- id: row["id"],
198
- timestamp: row["timestamp"],
199
- snapshotData: row["snapshot_data"],
200
- summary: row["summary"]
201
- }));
202
- }
203
- /** Get all metadata as a key-value record. */
204
- getMetadata() {
205
- this.ensureOpen();
206
- const rows = this.db.prepare("SELECT key, value FROM metadata").all();
207
- const result = {};
208
- for (const row of rows) result[row.key] = row.value;
209
- return result;
210
- }
211
- /** Flush buffers and close the database connection. */
212
- close() {
213
- if (this.closed) return;
214
- this.flush();
215
- this.db.close();
216
- this.closed = true;
217
- }
218
- /** Check if the database is closed. */
219
- get isClosed() {
220
- return this.closed;
221
- }
222
- ensureOpen() {
223
- if (this.closed) throw new Error("TraceDB is closed");
224
- }
225
- };
226
- //#endregion
227
- //#region src/modules/trace/TraceRecorder.ts
228
- /**
229
- * TraceRecorder — Event capture engine for time-travel debugging.
230
- *
231
- * Subscribes to EventBus events and CDP session events, capturing them
232
- * into a TraceDB instance. Handles recording lifecycle (start/stop),
233
- * selective CDP domain filtering, and differential memory tracing.
234
- */
235
- /**
236
- * Known CDP events to subscribe to per domain.
237
- * CDP sessions don't support wildcards, so we explicitly list relevant events.
238
- */
239
- const CDP_EVENTS_BY_DOMAIN = {
240
- Debugger: [
241
- "Debugger.paused",
242
- "Debugger.resumed",
243
- "Debugger.scriptParsed"
244
- ],
245
- Runtime: ["Runtime.consoleAPICalled", "Runtime.exceptionThrown"],
246
- Network: [
247
- "Network.requestWillBeSent",
248
- "Network.responseReceived",
249
- "Network.loadingFinished"
250
- ],
251
- Page: ["Page.navigatedWithinDocument", "Page.loadEventFired"]
252
- };
253
- const DEFAULT_CDP_DOMAINS = [
254
- "Debugger",
255
- "Runtime",
256
- "Network",
257
- "Page"
258
- ];
259
- var TraceRecorder = class {
260
- db = null;
261
- state = "idle";
262
- session = null;
263
- eventBusUnsub = null;
264
- cdpListeners = /* @__PURE__ */ new Map();
265
- cdpSession = null;
266
- eventCount = 0;
267
- memoryDeltaCount = 0;
268
- heapSnapshotCount = 0;
269
- /**
270
- * Start recording events into a new trace database.
271
- *
272
- * @param eventBus The server EventBus to subscribe to
273
- * @param cdpSession Optional CDP session for browser event recording
274
- * @param options Recording configuration
275
- * @returns The recording session details
276
- */
277
- async start(eventBus, cdpSession, options) {
278
- if (this.state === "recording") throw new Error("Recording already in progress");
279
- const sessionId = randomUUID();
280
- const { absolutePath } = await resolveArtifactPath({
281
- category: "traces",
282
- toolName: "trace_recorder",
283
- target: sessionId.slice(0, 8),
284
- ext: "db"
285
- });
286
- this.db = new TraceDB({ dbPath: absolutePath });
287
- this.eventCount = 0;
288
- this.memoryDeltaCount = 0;
289
- this.heapSnapshotCount = 0;
290
- const startedAt = Date.now();
291
- this.db.setMetadata("sessionId", sessionId);
292
- this.db.setMetadata("platform", process.platform);
293
- this.db.setMetadata("startedAt", String(startedAt));
294
- this.db.setMetadata("nodeVersion", process.version);
295
- this.eventBusUnsub = eventBus.onAny((wrapped) => {
296
- if (this.state !== "recording" || !this.db) return;
297
- try {
298
- this.db.insertEvent({
299
- timestamp: Date.now(),
300
- category: this.mapEventCategory(String(wrapped.event)),
301
- eventType: String(wrapped.event),
302
- data: JSON.stringify(wrapped.payload ?? {}),
303
- scriptId: null,
304
- lineNumber: null
305
- });
306
- this.eventCount++;
307
- } catch {}
308
- });
309
- this.cdpSession = cdpSession;
310
- if (cdpSession) {
311
- const domains = options?.cdpDomains ?? DEFAULT_CDP_DOMAINS;
312
- for (const domain of domains) {
313
- const events = CDP_EVENTS_BY_DOMAIN[domain];
314
- if (!events) continue;
315
- for (const eventName of events) {
316
- const handler = (params) => {
317
- if (this.state !== "recording" || !this.db) return;
318
- try {
319
- let scriptId = null;
320
- let lineNumber = null;
321
- if (typeof params === "object" && params !== null) {
322
- const p = params;
323
- if ("scriptId" in p) scriptId = String(p["scriptId"]);
324
- if ("lineNumber" in p) lineNumber = Number(p["lineNumber"]) || null;
325
- if (eventName === "Debugger.paused" && Array.isArray(p["callFrames"])) {
326
- const frame = p["callFrames"][0];
327
- if (frame) {
328
- const loc = frame["location"];
329
- if (loc) {
330
- scriptId = String(loc["scriptId"] ?? scriptId);
331
- lineNumber = Number(loc["lineNumber"] ?? lineNumber) || null;
332
- }
333
- }
334
- }
335
- }
336
- this.db.insertEvent({
337
- timestamp: Date.now(),
338
- category: domain.toLowerCase(),
339
- eventType: eventName,
340
- data: JSON.stringify(params ?? {}),
341
- scriptId,
342
- lineNumber
343
- });
344
- this.eventCount++;
345
- } catch {}
346
- };
347
- cdpSession.on(eventName, handler);
348
- this.cdpListeners.set(eventName, handler);
349
- }
350
- }
351
- }
352
- this.session = {
353
- sessionId,
354
- dbPath: absolutePath,
355
- startedAt,
356
- eventCount: 0,
357
- memoryDeltaCount: 0,
358
- heapSnapshotCount: 0
359
- };
360
- this.state = "recording";
361
- return { ...this.session };
362
- }
363
- /**
364
- * Record a memory write delta.
365
- * Silently ignored if not currently recording.
366
- */
367
- recordMemoryDelta(delta) {
368
- if (this.state !== "recording" || !this.db) return;
369
- try {
370
- this.db.insertMemoryDelta(delta);
371
- this.memoryDeltaCount++;
372
- } catch {}
373
- }
374
- /**
375
- * Capture a heap snapshot via CDP HeapProfiler.
376
- * Requires an active CDP session and recording in progress.
377
- */
378
- async captureHeapSnapshot(cdpSession) {
379
- if (this.state !== "recording" || !this.db) throw new Error("Cannot capture heap snapshot: not recording");
380
- const chunks = [];
381
- const chunkHandler = (params) => {
382
- if (typeof params === "object" && params !== null) {
383
- const chunk = params["chunk"];
384
- if (typeof chunk === "string") chunks.push(chunk);
385
- }
386
- };
387
- try {
388
- await cdpSession.send("HeapProfiler.enable");
389
- cdpSession.on("HeapProfiler.addHeapSnapshotChunk", chunkHandler);
390
- await cdpSession.send("HeapProfiler.takeHeapSnapshot", { reportProgress: false });
391
- cdpSession.off("HeapProfiler.addHeapSnapshotChunk", chunkHandler);
392
- const snapshotStr = chunks.join("");
393
- const snapshotBuffer = Buffer.from(snapshotStr, "utf-8");
394
- const summary = this.extractHeapSummary(snapshotStr);
395
- this.db.insertHeapSnapshot({
396
- timestamp: Date.now(),
397
- snapshotData: snapshotBuffer,
398
- summary: JSON.stringify(summary)
399
- });
400
- this.heapSnapshotCount++;
401
- } finally {
402
- await cdpSession.send("HeapProfiler.disable").catch(() => {});
403
- }
404
- }
405
- /**
406
- * Stop recording and finalize the trace database.
407
- * @returns Final session summary with event counts
408
- */
409
- stop() {
410
- if (this.state !== "recording") throw new Error("GRACEFUL: Cannot stop: not currently recording");
411
- if (this.eventBusUnsub) {
412
- this.eventBusUnsub();
413
- this.eventBusUnsub = null;
414
- }
415
- if (this.cdpSession) {
416
- for (const [event, handler] of this.cdpListeners) this.cdpSession.off(event, handler);
417
- this.cdpListeners.clear();
418
- this.cdpSession = null;
419
- }
420
- if (this.db) {
421
- const stoppedAt = Date.now();
422
- this.db.setMetadata("stoppedAt", String(stoppedAt));
423
- this.db.setMetadata("eventCount", String(this.eventCount));
424
- this.db.setMetadata("memoryDeltaCount", String(this.memoryDeltaCount));
425
- this.db.setMetadata("heapSnapshotCount", String(this.heapSnapshotCount));
426
- this.db.close();
427
- if (this.session) {
428
- this.session.stoppedAt = stoppedAt;
429
- this.session.eventCount = this.eventCount;
430
- this.session.memoryDeltaCount = this.memoryDeltaCount;
431
- this.session.heapSnapshotCount = this.heapSnapshotCount;
432
- }
433
- }
434
- this.state = "stopped";
435
- const finalSession = this.session ? { ...this.session } : this.createEmptySession();
436
- this.db = null;
437
- return finalSession;
438
- }
439
- /** Get the current recording state. */
440
- getState() {
441
- return this.state;
442
- }
443
- /** Get the current session details (null if not recording). */
444
- getSession() {
445
- return this.session ? { ...this.session } : null;
446
- }
447
- /** Get the active TraceDB instance (null if not recording). */
448
- getDB() {
449
- return this.db;
450
- }
451
- /**
452
- * Map an EventBus event name to a trace category.
453
- * E.g., 'tool:called' → 'tool', 'debugger:breakpoint_hit' → 'debugger'
454
- */
455
- mapEventCategory(event) {
456
- const colonIdx = event.indexOf(":");
457
- return colonIdx > 0 ? event.substring(0, colonIdx) : "other";
458
- }
459
- /**
460
- * Extract a lightweight summary from a V8 heap snapshot.
461
- * Only parses the minimal structure needed for diffing.
462
- */
463
- extractHeapSummary(snapshotStr) {
464
- try {
465
- const snapshot = JSON.parse(snapshotStr);
466
- const snapshotInfo = snapshot["snapshot"];
467
- if (!snapshotInfo) return {
468
- totalSize: 0,
469
- nodeCount: 0,
470
- objectCounts: {}
471
- };
472
- const meta = snapshotInfo["meta"];
473
- const nodeCount = snapshotInfo["node_count"] ?? 0;
474
- const nodeFields = meta?.["node_fields"];
475
- const nodeTypes = meta?.["node_types"];
476
- const nodes = snapshot["nodes"];
477
- const objectCounts = {};
478
- let totalSize = 0;
479
- if (nodeFields && nodes && nodeTypes) {
480
- const fieldCount = nodeFields.length;
481
- const typeIndex = nodeFields.indexOf("type");
482
- const nameIndex = nodeFields.indexOf("name");
483
- const selfSizeIndex = nodeFields.indexOf("self_size");
484
- const strings = snapshot["strings"] ?? [];
485
- for (let i = 0; i < nodes.length; i += fieldCount) {
486
- const selfSize = selfSizeIndex >= 0 ? nodes[i + selfSizeIndex] ?? 0 : 0;
487
- totalSize += selfSize;
488
- if (nameIndex >= 0) {
489
- const name = strings[nodes[i + nameIndex] ?? 0] ?? `type_${nodes[i + (typeIndex >= 0 ? typeIndex : 0)]}`;
490
- if (name) objectCounts[name] = (objectCounts[name] ?? 0) + 1;
491
- }
492
- }
493
- }
494
- return {
495
- totalSize,
496
- nodeCount,
497
- objectCounts
498
- };
499
- } catch {
500
- return {
501
- totalSize: 0,
502
- nodeCount: 0,
503
- objectCounts: {}
504
- };
505
- }
506
- }
507
- createEmptySession() {
508
- return {
509
- sessionId: "",
510
- dbPath: "",
511
- startedAt: 0,
512
- eventCount: 0,
513
- memoryDeltaCount: 0,
514
- heapSnapshotCount: 0
515
- };
516
- }
517
- };
518
- //#endregion
519
- export { TraceRecorder, TraceDB as t };