state-surgeon 1.0.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1798 @@
1
+ import { v4 } from 'uuid';
2
+ import express, { Router } from 'express';
3
+ import { WebSocketServer } from 'ws';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
7
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
8
+ }) : x)(function(x) {
9
+ if (typeof require !== "undefined") return require.apply(this, arguments);
10
+ throw Error('Dynamic require of "' + x + '" is not supported');
11
+ });
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // src/core/diff.ts
18
+ function deepClone(obj) {
19
+ if (obj === null || typeof obj !== "object") {
20
+ return obj;
21
+ }
22
+ if (Array.isArray(obj)) {
23
+ return obj.map((item) => deepClone(item));
24
+ }
25
+ if (obj instanceof Date) {
26
+ return new Date(obj.getTime());
27
+ }
28
+ if (obj instanceof Map) {
29
+ const clonedMap = /* @__PURE__ */ new Map();
30
+ obj.forEach((value, key) => {
31
+ clonedMap.set(deepClone(key), deepClone(value));
32
+ });
33
+ return clonedMap;
34
+ }
35
+ if (obj instanceof Set) {
36
+ const clonedSet = /* @__PURE__ */ new Set();
37
+ obj.forEach((value) => {
38
+ clonedSet.add(deepClone(value));
39
+ });
40
+ return clonedSet;
41
+ }
42
+ const cloned = {};
43
+ for (const key in obj) {
44
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
45
+ cloned[key] = deepClone(obj[key]);
46
+ }
47
+ }
48
+ return cloned;
49
+ }
50
+ function calculateDiff(before, after, path = "") {
51
+ const diffs = [];
52
+ if (before === after) {
53
+ return diffs;
54
+ }
55
+ if (before === null || before === void 0 || typeof before !== "object") {
56
+ if (after === null || after === void 0 || typeof after !== "object") {
57
+ if (before !== after) {
58
+ if (before === void 0) {
59
+ diffs.push({ path: path || "root", operation: "ADD", newValue: after });
60
+ } else if (after === void 0) {
61
+ diffs.push({ path: path || "root", operation: "REMOVE", oldValue: before });
62
+ } else {
63
+ diffs.push({ path: path || "root", operation: "UPDATE", oldValue: before, newValue: after });
64
+ }
65
+ }
66
+ return diffs;
67
+ }
68
+ diffs.push({ path: path || "root", operation: "UPDATE", oldValue: before, newValue: after });
69
+ return diffs;
70
+ }
71
+ if (after === null || after === void 0 || typeof after !== "object") {
72
+ diffs.push({ path: path || "root", operation: "UPDATE", oldValue: before, newValue: after });
73
+ return diffs;
74
+ }
75
+ if (Array.isArray(before) || Array.isArray(after)) {
76
+ if (!Array.isArray(before) || !Array.isArray(after)) {
77
+ diffs.push({ path: path || "root", operation: "UPDATE", oldValue: before, newValue: after });
78
+ return diffs;
79
+ }
80
+ const maxLength = Math.max(before.length, after.length);
81
+ for (let i = 0; i < maxLength; i++) {
82
+ const itemPath = path ? `${path}[${i}]` : `[${i}]`;
83
+ if (i >= before.length) {
84
+ diffs.push({ path: itemPath, operation: "ADD", newValue: after[i] });
85
+ } else if (i >= after.length) {
86
+ diffs.push({ path: itemPath, operation: "REMOVE", oldValue: before[i] });
87
+ } else {
88
+ diffs.push(...calculateDiff(before[i], after[i], itemPath));
89
+ }
90
+ }
91
+ return diffs;
92
+ }
93
+ const beforeObj = before;
94
+ const afterObj = after;
95
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(beforeObj), ...Object.keys(afterObj)]);
96
+ for (const key of allKeys) {
97
+ const keyPath = path ? `${path}.${key}` : key;
98
+ const beforeValue = beforeObj[key];
99
+ const afterValue = afterObj[key];
100
+ if (!(key in beforeObj)) {
101
+ diffs.push({ path: keyPath, operation: "ADD", newValue: afterValue });
102
+ } else if (!(key in afterObj)) {
103
+ diffs.push({ path: keyPath, operation: "REMOVE", oldValue: beforeValue });
104
+ } else {
105
+ diffs.push(...calculateDiff(beforeValue, afterValue, keyPath));
106
+ }
107
+ }
108
+ return diffs;
109
+ }
110
+ function applyDiff(state, diffs) {
111
+ const result = deepClone(state);
112
+ for (const diff of diffs) {
113
+ setValueAtPath(result, diff.path, diff.operation === "REMOVE" ? void 0 : diff.newValue);
114
+ }
115
+ return result;
116
+ }
117
+ function getValueAtPath(obj, path) {
118
+ if (!path || path === "root") return obj;
119
+ const parts = parsePath(path);
120
+ let current = obj;
121
+ for (const part of parts) {
122
+ if (current === null || current === void 0) {
123
+ return void 0;
124
+ }
125
+ current = current[part];
126
+ }
127
+ return current;
128
+ }
129
+ function setValueAtPath(obj, path, value) {
130
+ if (!path || path === "root") return;
131
+ const parts = parsePath(path);
132
+ let current = obj;
133
+ for (let i = 0; i < parts.length - 1; i++) {
134
+ const part = parts[i];
135
+ if (current[part] === void 0) {
136
+ const nextPart = parts[i + 1];
137
+ current[part] = /^\d+$/.test(nextPart) ? [] : {};
138
+ }
139
+ current = current[part];
140
+ }
141
+ const lastPart = parts[parts.length - 1];
142
+ if (value === void 0) {
143
+ delete current[lastPart];
144
+ } else {
145
+ current[lastPart] = value;
146
+ }
147
+ }
148
+ function parsePath(path) {
149
+ const parts = [];
150
+ let current = "";
151
+ let inBracket = false;
152
+ for (const char of path) {
153
+ if (char === "." && !inBracket) {
154
+ if (current) parts.push(current);
155
+ current = "";
156
+ } else if (char === "[") {
157
+ if (current) parts.push(current);
158
+ current = "";
159
+ inBracket = true;
160
+ } else if (char === "]") {
161
+ if (current) parts.push(current);
162
+ current = "";
163
+ inBracket = false;
164
+ } else {
165
+ current += char;
166
+ }
167
+ }
168
+ if (current) parts.push(current);
169
+ return parts;
170
+ }
171
+ function deepEqual(a, b) {
172
+ if (a === b) return true;
173
+ if (typeof a !== typeof b) return false;
174
+ if (a === null || b === null) return a === b;
175
+ if (typeof a !== "object") return a === b;
176
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
177
+ if (Array.isArray(a) && Array.isArray(b)) {
178
+ if (a.length !== b.length) return false;
179
+ return a.every((item, index) => deepEqual(item, b[index]));
180
+ }
181
+ const aObj = a;
182
+ const bObj = b;
183
+ const aKeys = Object.keys(aObj);
184
+ const bKeys = Object.keys(bObj);
185
+ if (aKeys.length !== bKeys.length) return false;
186
+ return aKeys.every((key) => deepEqual(aObj[key], bObj[key]));
187
+ }
188
+ var logicalClock = 0;
189
+ function createMutation(options) {
190
+ const {
191
+ source,
192
+ sessionId,
193
+ previousState,
194
+ nextState,
195
+ actionType = "CUSTOM",
196
+ actionPayload,
197
+ component,
198
+ function: funcName,
199
+ captureStack = true,
200
+ metadata
201
+ } = options;
202
+ logicalClock++;
203
+ const mutation = {
204
+ id: `mut_${Date.now()}_${v4().slice(0, 8)}`,
205
+ timestamp: typeof performance !== "undefined" ? performance.now() : Date.now(),
206
+ logicalClock,
207
+ sessionId,
208
+ source,
209
+ component,
210
+ function: funcName,
211
+ actionType,
212
+ actionPayload,
213
+ previousState,
214
+ nextState,
215
+ metadata
216
+ };
217
+ if (captureStack) {
218
+ mutation.callStack = parseCallStack(new Error().stack);
219
+ }
220
+ return mutation;
221
+ }
222
+ function parseCallStack(stack) {
223
+ if (!stack) return [];
224
+ return stack.split("\n").slice(2).map((line) => line.trim()).filter((line) => line.startsWith("at ")).map((line) => {
225
+ const match = line.match(/at\s+(.+?)\s+\((.+):(\d+):(\d+)\)/);
226
+ if (match) {
227
+ return `${match[1]} (${match[2].split("/").pop()}:${match[3]})`;
228
+ }
229
+ const simpleMatch = line.match(/at\s+(.+):(\d+):(\d+)/);
230
+ if (simpleMatch) {
231
+ return `anonymous (${simpleMatch[1].split("/").pop()}:${simpleMatch[2]})`;
232
+ }
233
+ return line.replace("at ", "");
234
+ }).slice(0, 10);
235
+ }
236
+ function getLogicalClock() {
237
+ return logicalClock;
238
+ }
239
+ function resetLogicalClock() {
240
+ logicalClock = 0;
241
+ }
242
+ function generateSessionId() {
243
+ return `session_${Date.now()}_${v4().slice(0, 8)}`;
244
+ }
245
+
246
+ // src/core/utils.ts
247
+ function deepMerge(target, source) {
248
+ const result = { ...target };
249
+ for (const key in source) {
250
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
251
+ const sourceValue = source[key];
252
+ const targetValue = target[key];
253
+ if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue)) {
254
+ result[key] = deepMerge(
255
+ targetValue,
256
+ sourceValue
257
+ );
258
+ } else {
259
+ result[key] = sourceValue;
260
+ }
261
+ }
262
+ }
263
+ return result;
264
+ }
265
+ function debounce(fn, ms) {
266
+ let timeoutId;
267
+ return function(...args) {
268
+ if (timeoutId) {
269
+ clearTimeout(timeoutId);
270
+ }
271
+ timeoutId = setTimeout(() => {
272
+ fn.apply(this, args);
273
+ }, ms);
274
+ };
275
+ }
276
+ function throttle(fn, ms) {
277
+ let lastCall = 0;
278
+ let timeoutId;
279
+ return function(...args) {
280
+ const now = Date.now();
281
+ const remaining = ms - (now - lastCall);
282
+ if (remaining <= 0) {
283
+ if (timeoutId) {
284
+ clearTimeout(timeoutId);
285
+ timeoutId = void 0;
286
+ }
287
+ lastCall = now;
288
+ fn.apply(this, args);
289
+ } else if (!timeoutId) {
290
+ timeoutId = setTimeout(() => {
291
+ lastCall = Date.now();
292
+ timeoutId = void 0;
293
+ fn.apply(this, args);
294
+ }, remaining);
295
+ }
296
+ };
297
+ }
298
+ function compress(data) {
299
+ return data;
300
+ }
301
+ function decompress(data) {
302
+ return data;
303
+ }
304
+ function formatBytes(bytes) {
305
+ if (bytes === 0) return "0 B";
306
+ const k = 1024;
307
+ const sizes = ["B", "KB", "MB", "GB"];
308
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
309
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
310
+ }
311
+ function formatDuration(ms) {
312
+ if (ms < 1) return `${(ms * 1e3).toFixed(2)}\u03BCs`;
313
+ if (ms < 1e3) return `${ms.toFixed(2)}ms`;
314
+ return `${(ms / 1e3).toFixed(2)}s`;
315
+ }
316
+ function simpleHash(str) {
317
+ let hash = 0;
318
+ for (let i = 0; i < str.length; i++) {
319
+ const char = str.charCodeAt(i);
320
+ hash = (hash << 5) - hash + char;
321
+ hash = hash & hash;
322
+ }
323
+ return Math.abs(hash).toString(16);
324
+ }
325
+ function isBrowser() {
326
+ return typeof window !== "undefined" && typeof document !== "undefined";
327
+ }
328
+ function isNode() {
329
+ return typeof process !== "undefined" && process.versions?.node !== void 0;
330
+ }
331
+ function safeStringify(obj, space) {
332
+ const seen = /* @__PURE__ */ new WeakSet();
333
+ return JSON.stringify(obj, (_, value) => {
334
+ if (typeof value === "object" && value !== null) {
335
+ if (seen.has(value)) {
336
+ return "[Circular]";
337
+ }
338
+ seen.add(value);
339
+ }
340
+ if (typeof value === "function") {
341
+ return `[Function: ${value.name || "anonymous"}]`;
342
+ }
343
+ if (typeof value === "symbol") {
344
+ return value.toString();
345
+ }
346
+ if (value instanceof Error) {
347
+ return {
348
+ name: value.name,
349
+ message: value.message,
350
+ stack: value.stack
351
+ };
352
+ }
353
+ if (value instanceof Map) {
354
+ return { __type: "Map", entries: Array.from(value.entries()) };
355
+ }
356
+ if (value instanceof Set) {
357
+ return { __type: "Set", values: Array.from(value.values()) };
358
+ }
359
+ return value;
360
+ }, space);
361
+ }
362
+ function safeParse(json) {
363
+ return JSON.parse(json, (_, value) => {
364
+ if (value && typeof value === "object") {
365
+ if (value.__type === "Map") {
366
+ return new Map(value.entries);
367
+ }
368
+ if (value.__type === "Set") {
369
+ return new Set(value.values);
370
+ }
371
+ }
372
+ return value;
373
+ });
374
+ }
375
+
376
+ // src/instrument/index.ts
377
+ var instrument_exports = {};
378
+ __export(instrument_exports, {
379
+ MutationTransport: () => MutationTransport,
380
+ StateSurgeonClient: () => StateSurgeonClient,
381
+ createReduxMiddleware: () => createReduxMiddleware,
382
+ instrumentFetch: () => instrumentFetch,
383
+ instrumentReact: () => instrumentReact,
384
+ instrumentReduxStore: () => instrumentReduxStore,
385
+ instrumentXHR: () => instrumentXHR,
386
+ instrumentZustand: () => instrumentZustand
387
+ });
388
+
389
+ // src/instrument/transport.ts
390
+ var MutationTransport = class {
391
+ constructor(url, options = {}) {
392
+ this.ws = null;
393
+ this.buffer = [];
394
+ this.flushTimer = null;
395
+ this.reconnectAttempts = 0;
396
+ this.isConnecting = false;
397
+ this.shouldReconnect = true;
398
+ this.url = url;
399
+ this.options = {
400
+ batchSize: options.batchSize ?? 50,
401
+ flushInterval: options.flushInterval ?? 100,
402
+ reconnectDelay: options.reconnectDelay ?? 1e3,
403
+ maxReconnectAttempts: options.maxReconnectAttempts ?? 10,
404
+ onConnect: options.onConnect ?? (() => {
405
+ }),
406
+ onDisconnect: options.onDisconnect ?? (() => {
407
+ }),
408
+ onError: options.onError ?? (() => {
409
+ }),
410
+ onMessage: options.onMessage ?? (() => {
411
+ })
412
+ };
413
+ }
414
+ /**
415
+ * Establishes WebSocket connection
416
+ */
417
+ connect() {
418
+ if (this.ws || this.isConnecting) {
419
+ return;
420
+ }
421
+ this.isConnecting = true;
422
+ this.shouldReconnect = true;
423
+ try {
424
+ const WebSocketImpl = typeof WebSocket !== "undefined" ? WebSocket : __require("ws");
425
+ this.ws = new WebSocketImpl(this.url);
426
+ this.ws.onopen = () => {
427
+ this.isConnecting = false;
428
+ this.reconnectAttempts = 0;
429
+ this.startFlushTimer();
430
+ this.options.onConnect();
431
+ };
432
+ this.ws.onclose = () => {
433
+ this.isConnecting = false;
434
+ this.stopFlushTimer();
435
+ this.ws = null;
436
+ this.options.onDisconnect();
437
+ this.attemptReconnect();
438
+ };
439
+ this.ws.onerror = (event) => {
440
+ this.isConnecting = false;
441
+ const error = new Error("WebSocket error");
442
+ this.options.onError(error);
443
+ };
444
+ this.ws.onmessage = (event) => {
445
+ try {
446
+ const message = JSON.parse(event.data);
447
+ this.options.onMessage(message);
448
+ } catch (e) {
449
+ }
450
+ };
451
+ } catch (error) {
452
+ this.isConnecting = false;
453
+ this.options.onError(error instanceof Error ? error : new Error(String(error)));
454
+ this.attemptReconnect();
455
+ }
456
+ }
457
+ /**
458
+ * Closes the WebSocket connection
459
+ */
460
+ disconnect() {
461
+ this.shouldReconnect = false;
462
+ this.stopFlushTimer();
463
+ if (this.ws) {
464
+ this.ws.close();
465
+ this.ws = null;
466
+ }
467
+ }
468
+ /**
469
+ * Sends a message (adds to buffer)
470
+ */
471
+ send(message) {
472
+ this.buffer.push(message);
473
+ if (this.buffer.length >= this.options.batchSize) {
474
+ this.flush();
475
+ }
476
+ }
477
+ /**
478
+ * Flushes the buffer immediately
479
+ */
480
+ flush() {
481
+ if (this.buffer.length === 0) {
482
+ return;
483
+ }
484
+ if (this.ws && this.ws.readyState === 1) {
485
+ try {
486
+ const batch = {
487
+ type: "MUTATION_BATCH",
488
+ payload: {
489
+ mutations: this.buffer.map((m) => m.payload),
490
+ timestamp: Date.now()
491
+ }
492
+ };
493
+ this.ws.send(JSON.stringify(batch));
494
+ this.buffer = [];
495
+ } catch (error) {
496
+ this.options.onError(
497
+ error instanceof Error ? error : new Error(String(error))
498
+ );
499
+ }
500
+ }
501
+ }
502
+ /**
503
+ * Checks if transport is connected
504
+ */
505
+ isConnected() {
506
+ return this.ws !== null && this.ws.readyState === 1;
507
+ }
508
+ /**
509
+ * Gets the current buffer size
510
+ */
511
+ getBufferSize() {
512
+ return this.buffer.length;
513
+ }
514
+ startFlushTimer() {
515
+ if (this.flushTimer) {
516
+ clearInterval(this.flushTimer);
517
+ }
518
+ this.flushTimer = setInterval(() => {
519
+ this.flush();
520
+ }, this.options.flushInterval);
521
+ }
522
+ stopFlushTimer() {
523
+ if (this.flushTimer) {
524
+ clearInterval(this.flushTimer);
525
+ this.flushTimer = null;
526
+ }
527
+ }
528
+ attemptReconnect() {
529
+ if (!this.shouldReconnect) {
530
+ return;
531
+ }
532
+ if (this.reconnectAttempts >= this.options.maxReconnectAttempts) {
533
+ this.options.onError(new Error("Max reconnection attempts reached"));
534
+ return;
535
+ }
536
+ this.reconnectAttempts++;
537
+ const delay = this.options.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1);
538
+ setTimeout(() => {
539
+ if (this.shouldReconnect) {
540
+ this.connect();
541
+ }
542
+ }, Math.min(delay, 3e4));
543
+ }
544
+ };
545
+
546
+ // src/instrument/client.ts
547
+ var StateSurgeonClient = class {
548
+ constructor(options = {}) {
549
+ this.transport = null;
550
+ this.listeners = /* @__PURE__ */ new Set();
551
+ this.isConnected = false;
552
+ // Track mutations locally for offline support
553
+ this.localMutations = [];
554
+ this.maxLocalMutations = 1e4;
555
+ this.sessionId = options.sessionId || generateSessionId();
556
+ this.appId = options.appId || "default";
557
+ this.debug = options.debug || false;
558
+ this.serverUrl = options.serverUrl || "ws://localhost:8081";
559
+ this.transportOptions = {
560
+ batchSize: options.batchSize || 50,
561
+ flushInterval: options.flushInterval || 100,
562
+ ...options.transport
563
+ };
564
+ if (options.autoConnect !== false) {
565
+ this.connect();
566
+ }
567
+ this.log("State Surgeon Client initialized", { sessionId: this.sessionId, appId: this.appId });
568
+ }
569
+ /**
570
+ * Connects to the recorder server
571
+ */
572
+ connect() {
573
+ if (this.transport) {
574
+ return;
575
+ }
576
+ this.transport = new MutationTransport(this.serverUrl, {
577
+ ...this.transportOptions,
578
+ onConnect: () => {
579
+ this.isConnected = true;
580
+ this.log("Connected to State Surgeon recorder");
581
+ this.sendHandshake();
582
+ },
583
+ onDisconnect: () => {
584
+ this.isConnected = false;
585
+ this.log("Disconnected from State Surgeon recorder");
586
+ },
587
+ onError: (error) => {
588
+ this.log("Transport error:", error);
589
+ }
590
+ });
591
+ this.transport.connect();
592
+ }
593
+ /**
594
+ * Disconnects from the recorder server
595
+ */
596
+ disconnect() {
597
+ if (this.transport) {
598
+ this.transport.disconnect();
599
+ this.transport = null;
600
+ }
601
+ this.isConnected = false;
602
+ }
603
+ /**
604
+ * Sends the initial handshake to register the session
605
+ */
606
+ sendHandshake() {
607
+ if (this.transport) {
608
+ this.transport.send({
609
+ type: "REGISTER_SESSION",
610
+ payload: {
611
+ appId: this.appId,
612
+ sessionId: this.sessionId,
613
+ timestamp: Date.now(),
614
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "node",
615
+ url: typeof window !== "undefined" ? window.location.href : void 0
616
+ }
617
+ });
618
+ }
619
+ }
620
+ /**
621
+ * Records a mutation
622
+ */
623
+ recordMutation(mutation) {
624
+ this.localMutations.push(mutation);
625
+ if (this.localMutations.length > this.maxLocalMutations) {
626
+ this.localMutations.shift();
627
+ }
628
+ for (const listener of this.listeners) {
629
+ try {
630
+ listener(mutation);
631
+ } catch (error) {
632
+ this.log("Listener error:", error);
633
+ }
634
+ }
635
+ if (this.transport && this.isConnected) {
636
+ this.transport.send({
637
+ type: "MUTATION_RECORDED",
638
+ payload: mutation
639
+ });
640
+ }
641
+ this.log("Mutation recorded:", mutation.id, mutation.source);
642
+ }
643
+ /**
644
+ * Creates and records a mutation from state change
645
+ */
646
+ captureStateChange(source, previousState, nextState, options = {}) {
647
+ const mutation = createMutation({
648
+ source,
649
+ sessionId: this.sessionId,
650
+ previousState: deepClone(previousState),
651
+ nextState: deepClone(nextState),
652
+ actionType: options.actionType || "CUSTOM",
653
+ actionPayload: options.actionPayload,
654
+ component: options.component,
655
+ function: options.function,
656
+ captureStack: true
657
+ });
658
+ mutation.diff = calculateDiff(mutation.previousState, mutation.nextState);
659
+ this.recordMutation(mutation);
660
+ return mutation;
661
+ }
662
+ /**
663
+ * Adds a mutation listener
664
+ */
665
+ addListener(listener) {
666
+ this.listeners.add(listener);
667
+ return () => this.listeners.delete(listener);
668
+ }
669
+ /**
670
+ * Gets the current session ID
671
+ */
672
+ getSessionId() {
673
+ return this.sessionId;
674
+ }
675
+ /**
676
+ * Gets all local mutations
677
+ */
678
+ getMutations() {
679
+ return [...this.localMutations];
680
+ }
681
+ /**
682
+ * Clears local mutations
683
+ */
684
+ clearMutations() {
685
+ this.localMutations = [];
686
+ }
687
+ /**
688
+ * Checks if connected to server
689
+ */
690
+ isServerConnected() {
691
+ return this.isConnected;
692
+ }
693
+ /**
694
+ * Flushes any pending mutations
695
+ */
696
+ flush() {
697
+ if (this.transport) {
698
+ this.transport.flush();
699
+ }
700
+ }
701
+ log(...args) {
702
+ if (this.debug) {
703
+ console.log("[State Surgeon]", ...args);
704
+ }
705
+ }
706
+ };
707
+ var globalClient = null;
708
+ function getClient(options) {
709
+ if (!globalClient) {
710
+ globalClient = new StateSurgeonClient(options);
711
+ }
712
+ return globalClient;
713
+ }
714
+
715
+ // src/instrument/api.ts
716
+ var originalFetch = null;
717
+ var fetchInstrumented = false;
718
+ var originalXHROpen = null;
719
+ var originalXHRSend = null;
720
+ var xhrInstrumented = false;
721
+ function instrumentFetch(options = {}) {
722
+ if (fetchInstrumented) {
723
+ console.warn("[State Surgeon] Fetch already instrumented");
724
+ return () => {
725
+ };
726
+ }
727
+ if (typeof fetch === "undefined") {
728
+ console.warn("[State Surgeon] Fetch not available in this environment");
729
+ return () => {
730
+ };
731
+ }
732
+ const client = options.client || getClient();
733
+ const ignoreUrls = options.ignoreUrls || [];
734
+ const captureRequestBody = options.captureRequestBody !== false;
735
+ const captureResponseBody = options.captureResponseBody !== false;
736
+ const maxBodySize = options.maxBodySize || 1e4;
737
+ originalFetch = fetch;
738
+ globalThis.fetch = async function instrumentedFetch(input, init) {
739
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
740
+ if (ignoreUrls.some((ignore) => url.includes(ignore))) {
741
+ return originalFetch(input, init);
742
+ }
743
+ const startTime = Date.now();
744
+ const requestId = `req_${startTime}_${Math.random().toString(36).slice(2, 8)}`;
745
+ const requestInfo = {
746
+ url,
747
+ method: init?.method || "GET",
748
+ headers: init?.headers
749
+ };
750
+ if (captureRequestBody && init?.body) {
751
+ requestInfo.body = truncateBody(init.body, maxBodySize);
752
+ }
753
+ try {
754
+ const response = await originalFetch(input, init);
755
+ const duration = Date.now() - startTime;
756
+ const clonedResponse = response.clone();
757
+ const responseInfo = {
758
+ status: response.status,
759
+ statusText: response.statusText,
760
+ headers: Object.fromEntries(response.headers.entries())
761
+ };
762
+ if (captureResponseBody) {
763
+ try {
764
+ const text = await clonedResponse.text();
765
+ responseInfo.body = truncateBody(text, maxBodySize);
766
+ } catch {
767
+ responseInfo.body = "[Unable to read response body]";
768
+ }
769
+ }
770
+ client.captureStateChange("api", requestInfo, responseInfo, {
771
+ actionType: "API_RESPONSE",
772
+ actionPayload: {
773
+ requestId,
774
+ url,
775
+ method: requestInfo.method,
776
+ status: response.status,
777
+ duration
778
+ },
779
+ function: "fetch"
780
+ });
781
+ return response;
782
+ } catch (error) {
783
+ const duration = Date.now() - startTime;
784
+ client.captureStateChange("api", requestInfo, {
785
+ error: error instanceof Error ? error.message : String(error),
786
+ stack: error instanceof Error ? error.stack : void 0
787
+ }, {
788
+ actionType: "API_RESPONSE",
789
+ actionPayload: {
790
+ requestId,
791
+ url,
792
+ method: requestInfo.method,
793
+ status: 0,
794
+ error: true,
795
+ duration
796
+ },
797
+ function: "fetch"
798
+ });
799
+ throw error;
800
+ }
801
+ };
802
+ fetchInstrumented = true;
803
+ return () => {
804
+ if (originalFetch) {
805
+ globalThis.fetch = originalFetch;
806
+ originalFetch = null;
807
+ }
808
+ fetchInstrumented = false;
809
+ };
810
+ }
811
+ function instrumentXHR(options = {}) {
812
+ if (xhrInstrumented) {
813
+ console.warn("[State Surgeon] XHR already instrumented");
814
+ return () => {
815
+ };
816
+ }
817
+ if (typeof XMLHttpRequest === "undefined") {
818
+ console.warn("[State Surgeon] XMLHttpRequest not available in this environment");
819
+ return () => {
820
+ };
821
+ }
822
+ const client = options.client || getClient();
823
+ const ignoreUrls = options.ignoreUrls || [];
824
+ const captureResponseBody = options.captureResponseBody !== false;
825
+ const maxBodySize = options.maxBodySize || 1e4;
826
+ originalXHROpen = XMLHttpRequest.prototype.open;
827
+ originalXHRSend = XMLHttpRequest.prototype.send;
828
+ XMLHttpRequest.prototype.open = function(method, url, async = true, username, password) {
829
+ this._stateSurgeon = {
830
+ method,
831
+ url: url.toString(),
832
+ startTime: 0
833
+ };
834
+ return originalXHROpen.call(this, method, url, async, username, password);
835
+ };
836
+ XMLHttpRequest.prototype.send = function(body) {
837
+ const info = this._stateSurgeon;
838
+ if (!info || ignoreUrls.some((ignore) => info.url.includes(ignore))) {
839
+ return originalXHRSend.call(this, body);
840
+ }
841
+ info.startTime = Date.now();
842
+ const requestId = `xhr_${info.startTime}_${Math.random().toString(36).slice(2, 8)}`;
843
+ const requestInfo = {
844
+ url: info.url,
845
+ method: info.method
846
+ };
847
+ this.addEventListener("loadend", () => {
848
+ const duration = Date.now() - info.startTime;
849
+ const responseInfo = {
850
+ status: this.status,
851
+ statusText: this.statusText
852
+ };
853
+ if (captureResponseBody && this.responseText) {
854
+ responseInfo.body = truncateBody(this.responseText, maxBodySize);
855
+ }
856
+ client.captureStateChange("api", requestInfo, responseInfo, {
857
+ actionType: "API_RESPONSE",
858
+ actionPayload: {
859
+ requestId,
860
+ url: info.url,
861
+ method: info.method,
862
+ status: this.status,
863
+ duration
864
+ },
865
+ function: "XMLHttpRequest"
866
+ });
867
+ });
868
+ return originalXHRSend.call(this, body);
869
+ };
870
+ xhrInstrumented = true;
871
+ return () => {
872
+ if (originalXHROpen) {
873
+ XMLHttpRequest.prototype.open = originalXHROpen;
874
+ originalXHROpen = null;
875
+ }
876
+ if (originalXHRSend) {
877
+ XMLHttpRequest.prototype.send = originalXHRSend;
878
+ originalXHRSend = null;
879
+ }
880
+ xhrInstrumented = false;
881
+ };
882
+ }
883
+ function truncateBody(body, maxSize) {
884
+ let str;
885
+ if (typeof body === "string") {
886
+ str = body;
887
+ } else if (body instanceof FormData) {
888
+ str = "[FormData]";
889
+ } else if (body instanceof Blob) {
890
+ str = `[Blob: ${body.size} bytes]`;
891
+ } else if (body instanceof ArrayBuffer) {
892
+ str = `[ArrayBuffer: ${body.byteLength} bytes]`;
893
+ } else {
894
+ try {
895
+ str = JSON.stringify(body);
896
+ } catch {
897
+ str = String(body);
898
+ }
899
+ }
900
+ if (str.length > maxSize) {
901
+ return str.slice(0, maxSize) + "... [truncated]";
902
+ }
903
+ return str;
904
+ }
905
+
906
+ // src/instrument/react.ts
907
+ var originalUseState = null;
908
+ var originalUseReducer = null;
909
+ var isInstrumented = false;
910
+ function instrumentReact(React, options = {}) {
911
+ if (isInstrumented) {
912
+ console.warn("[State Surgeon] React already instrumented");
913
+ return () => {
914
+ };
915
+ }
916
+ const client = options.client || getClient();
917
+ const captureComponentName = options.captureComponentName !== false;
918
+ originalUseState = React.useState;
919
+ originalUseReducer = React.useReducer;
920
+ React.useState = function(initialState) {
921
+ const [state, originalSetState] = originalUseState(initialState);
922
+ const instrumentedSetState = (newStateOrUpdater) => {
923
+ const previousState = deepClone(state);
924
+ const newState = typeof newStateOrUpdater === "function" ? newStateOrUpdater(state) : newStateOrUpdater;
925
+ client.captureStateChange("react", previousState, newState, {
926
+ actionType: "SET_STATE",
927
+ component: captureComponentName ? getComponentName() : void 0,
928
+ function: "useState"
929
+ });
930
+ return originalSetState(newStateOrUpdater);
931
+ };
932
+ return [state, instrumentedSetState];
933
+ };
934
+ React.useReducer = function(reducer, initialArg, init) {
935
+ const instrumentedReducer = ((state, action) => {
936
+ const previousState = deepClone(state);
937
+ const newState = reducer(state, action);
938
+ client.captureStateChange("react", previousState, newState, {
939
+ actionType: "DISPATCH",
940
+ actionPayload: action,
941
+ component: captureComponentName ? getComponentName() : void 0,
942
+ function: "useReducer"
943
+ });
944
+ return newState;
945
+ });
946
+ return originalUseReducer(instrumentedReducer, initialArg, init);
947
+ };
948
+ isInstrumented = true;
949
+ return () => {
950
+ if (originalUseState) {
951
+ React.useState = originalUseState;
952
+ }
953
+ if (originalUseReducer) {
954
+ React.useReducer = originalUseReducer;
955
+ }
956
+ isInstrumented = false;
957
+ originalUseState = null;
958
+ originalUseReducer = null;
959
+ };
960
+ }
961
+ function getComponentName() {
962
+ const stack = new Error().stack;
963
+ if (!stack) return void 0;
964
+ const lines = stack.split("\n");
965
+ for (const line of lines) {
966
+ if (line.includes("instrumentedSetState") || line.includes("instrumentedReducer") || line.includes("useState") || line.includes("useReducer") || line.includes("react-dom") || line.includes("react.development")) {
967
+ continue;
968
+ }
969
+ const match = line.match(/at\s+([A-Z][A-Za-z0-9_]*)/);
970
+ if (match) {
971
+ return match[1];
972
+ }
973
+ }
974
+ return void 0;
975
+ }
976
+
977
+ // src/instrument/redux.ts
978
+ function createReduxMiddleware(options = {}) {
979
+ const client = options.client || getClient();
980
+ const ignoreActions = new Set(options.ignoreActions || []);
981
+ const storeName = options.storeName || "redux";
982
+ return (storeAPI) => (next) => (action) => {
983
+ const actionType = action?.type;
984
+ if (actionType && ignoreActions.has(actionType)) {
985
+ return next(action);
986
+ }
987
+ const previousState = deepClone(storeAPI.getState());
988
+ const startTime = typeof performance !== "undefined" ? performance.now() : Date.now();
989
+ const result = next(action);
990
+ const nextState = deepClone(storeAPI.getState());
991
+ const duration = (typeof performance !== "undefined" ? performance.now() : Date.now()) - startTime;
992
+ const mutation = client.captureStateChange("redux", previousState, nextState, {
993
+ actionType: "DISPATCH",
994
+ actionPayload: action,
995
+ component: storeName,
996
+ function: actionType || "dispatch"
997
+ });
998
+ mutation.duration = duration;
999
+ return result;
1000
+ };
1001
+ }
1002
+ function instrumentReduxStore(store, options = {}) {
1003
+ const client = options.client || getClient();
1004
+ const ignoreActions = new Set(options.ignoreActions || []);
1005
+ const storeName = options.storeName || "redux";
1006
+ const originalDispatch = store.dispatch;
1007
+ store.dispatch = function instrumentedDispatch(action) {
1008
+ const actionType = action?.type;
1009
+ if (actionType && ignoreActions.has(actionType)) {
1010
+ return originalDispatch(action);
1011
+ }
1012
+ const previousState = deepClone(store.getState());
1013
+ const startTime = typeof performance !== "undefined" ? performance.now() : Date.now();
1014
+ const result = originalDispatch(action);
1015
+ const nextState = deepClone(store.getState());
1016
+ const duration = (typeof performance !== "undefined" ? performance.now() : Date.now()) - startTime;
1017
+ const mutation = client.captureStateChange("redux", previousState, nextState, {
1018
+ actionType: "DISPATCH",
1019
+ actionPayload: action,
1020
+ component: storeName,
1021
+ function: actionType || "dispatch"
1022
+ });
1023
+ mutation.duration = duration;
1024
+ return result;
1025
+ };
1026
+ return () => {
1027
+ store.dispatch = originalDispatch;
1028
+ };
1029
+ }
1030
+
1031
+ // src/instrument/zustand.ts
1032
+ function instrumentZustand(stateCreator, options = {}) {
1033
+ const client = options.client || getClient();
1034
+ const storeName = options.storeName || "zustand";
1035
+ return (set, get, api) => {
1036
+ const instrumentedSet = (partial, replace) => {
1037
+ const previousState = deepClone(get());
1038
+ set(partial, replace);
1039
+ const nextState = deepClone(get());
1040
+ client.captureStateChange("zustand", previousState, nextState, {
1041
+ actionType: "SET_STATE",
1042
+ actionPayload: typeof partial === "function" ? "updater function" : partial,
1043
+ component: storeName,
1044
+ function: "set"
1045
+ });
1046
+ };
1047
+ return stateCreator(instrumentedSet, get, api);
1048
+ };
1049
+ }
1050
+
1051
+ // src/recorder/index.ts
1052
+ var recorder_exports = {};
1053
+ __export(recorder_exports, {
1054
+ MutationStore: () => MutationStore,
1055
+ TimelineReconstructor: () => TimelineReconstructor,
1056
+ createAPIRoutes: () => createAPIRoutes,
1057
+ createRecorderServer: () => createRecorderServer
1058
+ });
1059
+ function createAPIRoutes(store, reconstructor) {
1060
+ const router = Router();
1061
+ router.get("/health", (_req, res) => {
1062
+ res.json({ status: "ok", timestamp: Date.now() });
1063
+ });
1064
+ router.get("/sessions", (req, res) => {
1065
+ try {
1066
+ const appId = req.query.appId;
1067
+ const sessions = store.getSessions(appId);
1068
+ res.json({ sessions });
1069
+ } catch (error) {
1070
+ res.status(500).json({ error: String(error) });
1071
+ }
1072
+ });
1073
+ router.get("/sessions/:sessionId", (req, res) => {
1074
+ try {
1075
+ const session = store.getSession(req.params.sessionId);
1076
+ if (!session) {
1077
+ return res.status(404).json({ error: "Session not found" });
1078
+ }
1079
+ res.json({ session });
1080
+ } catch (error) {
1081
+ res.status(500).json({ error: String(error) });
1082
+ }
1083
+ });
1084
+ router.delete("/sessions/:sessionId", (req, res) => {
1085
+ try {
1086
+ const deleted = store.deleteSession(req.params.sessionId);
1087
+ res.json({ deleted });
1088
+ } catch (error) {
1089
+ res.status(500).json({ error: String(error) });
1090
+ }
1091
+ });
1092
+ router.get("/sessions/:sessionId/timeline", (req, res) => {
1093
+ try {
1094
+ const timeline = store.getTimeline(req.params.sessionId);
1095
+ res.json({ timeline, count: timeline.length });
1096
+ } catch (error) {
1097
+ res.status(500).json({ error: String(error) });
1098
+ }
1099
+ });
1100
+ router.get("/mutations", (req, res) => {
1101
+ try {
1102
+ const options = {
1103
+ sessionId: req.query.sessionId,
1104
+ startTime: req.query.startTime ? Number(req.query.startTime) : void 0,
1105
+ endTime: req.query.endTime ? Number(req.query.endTime) : void 0,
1106
+ source: req.query.source,
1107
+ component: req.query.component,
1108
+ limit: req.query.limit ? Number(req.query.limit) : 100,
1109
+ offset: req.query.offset ? Number(req.query.offset) : 0,
1110
+ sortOrder: req.query.sortOrder || "asc"
1111
+ };
1112
+ const mutations = store.queryMutations(options);
1113
+ res.json({ mutations, count: mutations.length });
1114
+ } catch (error) {
1115
+ res.status(500).json({ error: String(error) });
1116
+ }
1117
+ });
1118
+ router.get("/mutations/:mutationId", (req, res) => {
1119
+ try {
1120
+ const mutation = store.getMutation(req.params.mutationId);
1121
+ if (!mutation) {
1122
+ return res.status(404).json({ error: "Mutation not found" });
1123
+ }
1124
+ res.json({ mutation });
1125
+ } catch (error) {
1126
+ res.status(500).json({ error: String(error) });
1127
+ }
1128
+ });
1129
+ router.get("/mutations/:mutationId/state", async (req, res) => {
1130
+ try {
1131
+ const state = await reconstructor.getStateAtMutation(req.params.mutationId);
1132
+ res.json({ state });
1133
+ } catch (error) {
1134
+ res.status(500).json({ error: String(error) });
1135
+ }
1136
+ });
1137
+ router.get("/mutations/:mutationId/chain", async (req, res) => {
1138
+ try {
1139
+ const maxDepth = req.query.maxDepth ? Number(req.query.maxDepth) : 100;
1140
+ const chain = await reconstructor.findCausalChain(req.params.mutationId, maxDepth);
1141
+ res.json({ chain });
1142
+ } catch (error) {
1143
+ res.status(500).json({ error: String(error) });
1144
+ }
1145
+ });
1146
+ router.get("/sessions/:sessionId/path", async (req, res) => {
1147
+ try {
1148
+ const path = req.query.path;
1149
+ if (!path) {
1150
+ return res.status(400).json({ error: "Path is required" });
1151
+ }
1152
+ const mutations = await reconstructor.findMutationsForPath(req.params.sessionId, path);
1153
+ res.json({ mutations, count: mutations.length });
1154
+ } catch (error) {
1155
+ res.status(500).json({ error: String(error) });
1156
+ }
1157
+ });
1158
+ router.get("/sessions/:sessionId/summary", async (req, res) => {
1159
+ try {
1160
+ const startTime = Number(req.query.startTime);
1161
+ const endTime = Number(req.query.endTime);
1162
+ if (isNaN(startTime) || isNaN(endTime)) {
1163
+ return res.status(400).json({ error: "startTime and endTime are required" });
1164
+ }
1165
+ const summary = await reconstructor.summarizeTimeRange(
1166
+ req.params.sessionId,
1167
+ startTime,
1168
+ endTime
1169
+ );
1170
+ res.json({ summary });
1171
+ } catch (error) {
1172
+ res.status(500).json({ error: String(error) });
1173
+ }
1174
+ });
1175
+ router.get("/stats", (_req, res) => {
1176
+ try {
1177
+ const stats = store.getStats();
1178
+ res.json({ stats });
1179
+ } catch (error) {
1180
+ res.status(500).json({ error: String(error) });
1181
+ }
1182
+ });
1183
+ router.delete("/clear", (_req, res) => {
1184
+ try {
1185
+ store.clear();
1186
+ reconstructor.clearCache();
1187
+ res.json({ success: true });
1188
+ } catch (error) {
1189
+ res.status(500).json({ error: String(error) });
1190
+ }
1191
+ });
1192
+ return router;
1193
+ }
1194
+
1195
+ // src/recorder/reconstructor.ts
1196
+ var TimelineReconstructor = class {
1197
+ constructor(store) {
1198
+ this.stateCache = /* @__PURE__ */ new Map();
1199
+ this.maxCacheSize = 1e3;
1200
+ this.store = store;
1201
+ }
1202
+ /**
1203
+ * Reconstructs the state at a specific mutation
1204
+ */
1205
+ async getStateAtMutation(mutationId) {
1206
+ const cached = this.stateCache.get(mutationId);
1207
+ if (cached !== void 0) {
1208
+ return deepClone(cached);
1209
+ }
1210
+ const targetMutation = this.store.getMutation(mutationId);
1211
+ if (!targetMutation) {
1212
+ throw new Error(`Mutation not found: ${mutationId}`);
1213
+ }
1214
+ const timeline = this.store.getTimeline(targetMutation.sessionId);
1215
+ const targetIndex = timeline.findIndex((m) => m.id === mutationId);
1216
+ if (targetIndex === -1) {
1217
+ throw new Error(`Mutation not in timeline: ${mutationId}`);
1218
+ }
1219
+ let state = {};
1220
+ for (let i = 0; i <= targetIndex; i++) {
1221
+ const mutation = timeline[i];
1222
+ state = mutation.nextState;
1223
+ this.cacheState(mutation.id, state);
1224
+ }
1225
+ return deepClone(state);
1226
+ }
1227
+ /**
1228
+ * Reconstructs the state at a specific timestamp
1229
+ */
1230
+ async getStateAtTime(sessionId, timestamp) {
1231
+ const timeline = this.store.getTimeline(sessionId);
1232
+ let lastMutation = null;
1233
+ for (const mutation of timeline) {
1234
+ if (mutation.timestamp <= timestamp) {
1235
+ lastMutation = mutation;
1236
+ } else {
1237
+ break;
1238
+ }
1239
+ }
1240
+ if (!lastMutation) {
1241
+ return {};
1242
+ }
1243
+ return this.getStateAtMutation(lastMutation.id);
1244
+ }
1245
+ /**
1246
+ * Finds the causal chain leading to a mutation
1247
+ */
1248
+ async findCausalChain(mutationId, maxDepth = 100) {
1249
+ const chain = [];
1250
+ let currentId = mutationId;
1251
+ let depth = 0;
1252
+ while (currentId && depth < maxDepth) {
1253
+ const mutation = this.store.getMutation(currentId);
1254
+ if (!mutation) break;
1255
+ chain.push(mutation);
1256
+ if (mutation.parentMutationId) {
1257
+ currentId = mutation.parentMutationId;
1258
+ } else if (mutation.causes && mutation.causes.length > 0) {
1259
+ currentId = mutation.causes[0];
1260
+ } else {
1261
+ break;
1262
+ }
1263
+ depth++;
1264
+ }
1265
+ return {
1266
+ mutations: chain.reverse(),
1267
+ rootCause: chain[0]
1268
+ };
1269
+ }
1270
+ /**
1271
+ * Binary search to find when state became invalid
1272
+ */
1273
+ async findStateCorruption(sessionId, validator) {
1274
+ const timeline = this.store.getTimeline(sessionId);
1275
+ if (timeline.length === 0) {
1276
+ return null;
1277
+ }
1278
+ let left = 0;
1279
+ let right = timeline.length - 1;
1280
+ let firstBad = null;
1281
+ while (left <= right) {
1282
+ const mid = Math.floor((left + right) / 2);
1283
+ const state = await this.getStateAtMutation(timeline[mid].id);
1284
+ const isValid = validator(state);
1285
+ if (isValid) {
1286
+ left = mid + 1;
1287
+ } else {
1288
+ firstBad = mid;
1289
+ right = mid - 1;
1290
+ }
1291
+ }
1292
+ return firstBad !== null ? timeline[firstBad] : null;
1293
+ }
1294
+ /**
1295
+ * Finds all mutations that touched a specific path
1296
+ */
1297
+ async findMutationsForPath(sessionId, path) {
1298
+ const timeline = this.store.getTimeline(sessionId);
1299
+ const result = [];
1300
+ for (const mutation of timeline) {
1301
+ if (mutation.diff) {
1302
+ for (const diff of mutation.diff) {
1303
+ if (diff.path === path || diff.path.startsWith(path + ".") || diff.path.startsWith(path + "[")) {
1304
+ result.push(mutation);
1305
+ break;
1306
+ }
1307
+ }
1308
+ } else {
1309
+ const prevValue = getValueAtPath(mutation.previousState, path);
1310
+ const nextValue = getValueAtPath(mutation.nextState, path);
1311
+ if (prevValue !== nextValue) {
1312
+ result.push(mutation);
1313
+ }
1314
+ }
1315
+ }
1316
+ return result;
1317
+ }
1318
+ /**
1319
+ * Compares two sessions to find divergence points
1320
+ */
1321
+ async compareSessions(sessionId1, sessionId2) {
1322
+ const timeline1 = this.store.getTimeline(sessionId1);
1323
+ const timeline2 = this.store.getTimeline(sessionId2);
1324
+ let divergencePoint;
1325
+ const minLength = Math.min(timeline1.length, timeline2.length);
1326
+ for (let i = 0; i < minLength; i++) {
1327
+ const state1 = await this.getStateAtMutation(timeline1[i].id);
1328
+ const state2 = await this.getStateAtMutation(timeline2[i].id);
1329
+ if (JSON.stringify(state1) !== JSON.stringify(state2)) {
1330
+ divergencePoint = i;
1331
+ break;
1332
+ }
1333
+ }
1334
+ const actions1 = new Set(timeline1.map((m) => `${m.actionType}:${JSON.stringify(m.actionPayload)}`));
1335
+ const actions2 = new Set(timeline2.map((m) => `${m.actionType}:${JSON.stringify(m.actionPayload)}`));
1336
+ const session1Only = timeline1.filter(
1337
+ (m) => !actions2.has(`${m.actionType}:${JSON.stringify(m.actionPayload)}`)
1338
+ );
1339
+ const session2Only = timeline2.filter(
1340
+ (m) => !actions1.has(`${m.actionType}:${JSON.stringify(m.actionPayload)}`)
1341
+ );
1342
+ return {
1343
+ divergencePoint,
1344
+ session1Only,
1345
+ session2Only
1346
+ };
1347
+ }
1348
+ /**
1349
+ * Generates a summary of what happened in a time range
1350
+ */
1351
+ async summarizeTimeRange(sessionId, startTime, endTime) {
1352
+ const mutations = this.store.queryMutations({
1353
+ sessionId,
1354
+ startTime,
1355
+ endTime
1356
+ });
1357
+ const componentBreakdown = {};
1358
+ const sourceBreakdown = {};
1359
+ const pathsSet = /* @__PURE__ */ new Set();
1360
+ for (const mutation of mutations) {
1361
+ const component = mutation.component || "unknown";
1362
+ componentBreakdown[component] = (componentBreakdown[component] || 0) + 1;
1363
+ sourceBreakdown[mutation.source] = (sourceBreakdown[mutation.source] || 0) + 1;
1364
+ if (mutation.diff) {
1365
+ for (const diff of mutation.diff) {
1366
+ pathsSet.add(diff.path);
1367
+ }
1368
+ }
1369
+ }
1370
+ return {
1371
+ mutationCount: mutations.length,
1372
+ componentBreakdown,
1373
+ sourceBreakdown,
1374
+ pathsChanged: Array.from(pathsSet)
1375
+ };
1376
+ }
1377
+ /**
1378
+ * Clears the state cache
1379
+ */
1380
+ clearCache() {
1381
+ this.stateCache.clear();
1382
+ }
1383
+ cacheState(mutationId, state) {
1384
+ if (this.stateCache.size >= this.maxCacheSize) {
1385
+ const firstKey = this.stateCache.keys().next().value;
1386
+ if (firstKey) {
1387
+ this.stateCache.delete(firstKey);
1388
+ }
1389
+ }
1390
+ this.stateCache.set(mutationId, deepClone(state));
1391
+ }
1392
+ };
1393
+
1394
+ // src/recorder/store.ts
1395
+ var MutationStore = class {
1396
+ constructor(options = {}) {
1397
+ this.sessions = /* @__PURE__ */ new Map();
1398
+ this.mutations = /* @__PURE__ */ new Map();
1399
+ this.totalMutationCount = 0;
1400
+ this.options = {
1401
+ maxMutationsPerSession: options.maxMutationsPerSession ?? 1e4,
1402
+ maxTotalMutations: options.maxTotalMutations ?? 1e5,
1403
+ sessionTimeout: options.sessionTimeout ?? 30 * 60 * 1e3,
1404
+ // 30 minutes
1405
+ debug: options.debug ?? false
1406
+ };
1407
+ }
1408
+ /**
1409
+ * Creates or updates a session
1410
+ */
1411
+ registerSession(sessionId, appId, metadata) {
1412
+ let session = this.sessions.get(sessionId);
1413
+ if (!session) {
1414
+ session = {
1415
+ id: sessionId,
1416
+ appId,
1417
+ startTime: /* @__PURE__ */ new Date(),
1418
+ metadata,
1419
+ mutationCount: 0
1420
+ };
1421
+ this.sessions.set(sessionId, session);
1422
+ this.mutations.set(sessionId, []);
1423
+ this.log("Session registered:", sessionId);
1424
+ }
1425
+ return session;
1426
+ }
1427
+ /**
1428
+ * Ends a session
1429
+ */
1430
+ endSession(sessionId) {
1431
+ const session = this.sessions.get(sessionId);
1432
+ if (session) {
1433
+ session.endTime = /* @__PURE__ */ new Date();
1434
+ this.log("Session ended:", sessionId);
1435
+ }
1436
+ }
1437
+ /**
1438
+ * Stores a mutation
1439
+ */
1440
+ storeMutation(mutation) {
1441
+ const sessionId = mutation.sessionId;
1442
+ if (!this.sessions.has(sessionId)) {
1443
+ this.registerSession(sessionId, "unknown");
1444
+ }
1445
+ let sessionMutations = this.mutations.get(sessionId);
1446
+ if (!sessionMutations) {
1447
+ sessionMutations = [];
1448
+ this.mutations.set(sessionId, sessionMutations);
1449
+ }
1450
+ if (!mutation.diff && mutation.previousState !== void 0 && mutation.nextState !== void 0) {
1451
+ mutation.diff = calculateDiff(mutation.previousState, mutation.nextState);
1452
+ }
1453
+ if (sessionMutations.length >= this.options.maxMutationsPerSession) {
1454
+ sessionMutations.shift();
1455
+ this.totalMutationCount--;
1456
+ }
1457
+ if (this.totalMutationCount >= this.options.maxTotalMutations) {
1458
+ this.evictOldestMutations();
1459
+ }
1460
+ sessionMutations.push(mutation);
1461
+ this.totalMutationCount++;
1462
+ const session = this.sessions.get(sessionId);
1463
+ session.mutationCount++;
1464
+ this.log("Mutation stored:", mutation.id);
1465
+ }
1466
+ /**
1467
+ * Stores multiple mutations at once
1468
+ */
1469
+ storeMutations(mutations) {
1470
+ for (const mutation of mutations) {
1471
+ this.storeMutation(mutation);
1472
+ }
1473
+ }
1474
+ /**
1475
+ * Gets a session by ID
1476
+ */
1477
+ getSession(sessionId) {
1478
+ return this.sessions.get(sessionId);
1479
+ }
1480
+ /**
1481
+ * Gets all sessions
1482
+ */
1483
+ getSessions(appId) {
1484
+ const sessions = Array.from(this.sessions.values());
1485
+ if (appId) {
1486
+ return sessions.filter((s) => s.appId === appId);
1487
+ }
1488
+ return sessions;
1489
+ }
1490
+ /**
1491
+ * Gets a specific mutation by ID
1492
+ */
1493
+ getMutation(mutationId) {
1494
+ for (const sessionMutations of this.mutations.values()) {
1495
+ const mutation = sessionMutations.find((m) => m.id === mutationId);
1496
+ if (mutation) return mutation;
1497
+ }
1498
+ return void 0;
1499
+ }
1500
+ /**
1501
+ * Queries mutations with filters
1502
+ */
1503
+ queryMutations(options = {}) {
1504
+ let results = [];
1505
+ if (options.sessionId) {
1506
+ const sessionMutations = this.mutations.get(options.sessionId);
1507
+ if (sessionMutations) {
1508
+ results = [...sessionMutations];
1509
+ }
1510
+ } else {
1511
+ for (const sessionMutations of this.mutations.values()) {
1512
+ results.push(...sessionMutations);
1513
+ }
1514
+ }
1515
+ if (options.startTime !== void 0) {
1516
+ results = results.filter((m) => m.timestamp >= options.startTime);
1517
+ }
1518
+ if (options.endTime !== void 0) {
1519
+ results = results.filter((m) => m.timestamp <= options.endTime);
1520
+ }
1521
+ if (options.source) {
1522
+ results = results.filter((m) => m.source === options.source);
1523
+ }
1524
+ if (options.component) {
1525
+ results = results.filter((m) => m.component === options.component);
1526
+ }
1527
+ results.sort((a, b) => {
1528
+ const order = options.sortOrder === "desc" ? -1 : 1;
1529
+ return (a.logicalClock - b.logicalClock) * order;
1530
+ });
1531
+ if (options.offset !== void 0) {
1532
+ results = results.slice(options.offset);
1533
+ }
1534
+ if (options.limit !== void 0) {
1535
+ results = results.slice(0, options.limit);
1536
+ }
1537
+ return results;
1538
+ }
1539
+ /**
1540
+ * Gets the timeline for a session
1541
+ */
1542
+ getTimeline(sessionId) {
1543
+ const mutations = this.mutations.get(sessionId) || [];
1544
+ return [...mutations].sort((a, b) => a.logicalClock - b.logicalClock);
1545
+ }
1546
+ /**
1547
+ * Deletes a session and its mutations
1548
+ */
1549
+ deleteSession(sessionId) {
1550
+ const sessionMutations = this.mutations.get(sessionId);
1551
+ if (sessionMutations) {
1552
+ this.totalMutationCount -= sessionMutations.length;
1553
+ }
1554
+ this.mutations.delete(sessionId);
1555
+ return this.sessions.delete(sessionId);
1556
+ }
1557
+ /**
1558
+ * Clears all data
1559
+ */
1560
+ clear() {
1561
+ this.sessions.clear();
1562
+ this.mutations.clear();
1563
+ this.totalMutationCount = 0;
1564
+ this.log("Store cleared");
1565
+ }
1566
+ /**
1567
+ * Gets store statistics
1568
+ */
1569
+ getStats() {
1570
+ const mutationsPerSession = {};
1571
+ for (const [sessionId, mutations] of this.mutations.entries()) {
1572
+ mutationsPerSession[sessionId] = mutations.length;
1573
+ }
1574
+ return {
1575
+ sessionCount: this.sessions.size,
1576
+ totalMutations: this.totalMutationCount,
1577
+ mutationsPerSession
1578
+ };
1579
+ }
1580
+ /**
1581
+ * Evicts oldest mutations when capacity is exceeded
1582
+ */
1583
+ evictOldestMutations() {
1584
+ let oldestSession = null;
1585
+ let oldestTime = Infinity;
1586
+ for (const [sessionId, session] of this.sessions.entries()) {
1587
+ if (session.startTime.getTime() < oldestTime) {
1588
+ oldestTime = session.startTime.getTime();
1589
+ oldestSession = sessionId;
1590
+ }
1591
+ }
1592
+ if (oldestSession) {
1593
+ const mutations = this.mutations.get(oldestSession);
1594
+ if (mutations && mutations.length > 0) {
1595
+ mutations.shift();
1596
+ this.totalMutationCount--;
1597
+ this.log("Evicted oldest mutation from:", oldestSession);
1598
+ }
1599
+ }
1600
+ }
1601
+ log(...args) {
1602
+ if (this.options.debug) {
1603
+ console.log("[MutationStore]", ...args);
1604
+ }
1605
+ }
1606
+ };
1607
+
1608
+ // src/recorder/server.ts
1609
+ function createRecorderServer(options = {}) {
1610
+ const port = options.port ?? 8080;
1611
+ const wsPort = options.wsPort ?? 8081;
1612
+ const apiPath = options.apiPath ?? "/api";
1613
+ const debug = options.debug ?? false;
1614
+ const store = new MutationStore(options.storeOptions);
1615
+ const reconstructor = new TimelineReconstructor(store);
1616
+ const app = express();
1617
+ app.use(express.json({ limit: "10mb" }));
1618
+ if (options.cors !== false) {
1619
+ app.use((_req, res, next) => {
1620
+ res.header("Access-Control-Allow-Origin", "*");
1621
+ res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
1622
+ res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
1623
+ next();
1624
+ });
1625
+ }
1626
+ app.use(apiPath, createAPIRoutes(store, reconstructor));
1627
+ app.get("/_surgeon", (_req, res) => {
1628
+ res.send(`
1629
+ <!DOCTYPE html>
1630
+ <html>
1631
+ <head>
1632
+ <title>State Surgeon Dashboard</title>
1633
+ <style>
1634
+ body { font-family: system-ui, sans-serif; padding: 2rem; background: #1a1a2e; color: #eee; }
1635
+ h1 { color: #00d9ff; }
1636
+ .stats { background: #16213e; padding: 1rem; border-radius: 8px; margin: 1rem 0; }
1637
+ pre { background: #0f0f23; padding: 1rem; border-radius: 4px; overflow: auto; }
1638
+ </style>
1639
+ </head>
1640
+ <body>
1641
+ <h1>\u{1F52C} State Surgeon Dashboard</h1>
1642
+ <p>Recorder is running. Connect your application to start capturing mutations.</p>
1643
+ <div class="stats">
1644
+ <h3>Quick Stats</h3>
1645
+ <div id="stats">Loading...</div>
1646
+ </div>
1647
+ <h3>Recent Sessions</h3>
1648
+ <pre id="sessions">Loading...</pre>
1649
+ <script>
1650
+ async function loadData() {
1651
+ try {
1652
+ const statsRes = await fetch('${apiPath}/stats');
1653
+ const stats = await statsRes.json();
1654
+ document.getElementById('stats').innerHTML =
1655
+ '<pre>' + JSON.stringify(stats, null, 2) + '</pre>';
1656
+
1657
+ const sessionsRes = await fetch('${apiPath}/sessions');
1658
+ const sessions = await sessionsRes.json();
1659
+ document.getElementById('sessions').textContent =
1660
+ JSON.stringify(sessions, null, 2);
1661
+ } catch (e) {
1662
+ document.getElementById('stats').textContent = 'Error loading stats';
1663
+ }
1664
+ }
1665
+ loadData();
1666
+ setInterval(loadData, 5000);
1667
+ </script>
1668
+ </body>
1669
+ </html>
1670
+ `);
1671
+ });
1672
+ const httpServer = app.listen(0);
1673
+ httpServer.close();
1674
+ let wss;
1675
+ const clients = /* @__PURE__ */ new Map();
1676
+ function log(...args) {
1677
+ if (debug) {
1678
+ console.log("[State Surgeon Recorder]", ...args);
1679
+ }
1680
+ }
1681
+ function handleMessage(ws, message) {
1682
+ log("Received message:", message.type);
1683
+ switch (message.type) {
1684
+ case "REGISTER_SESSION": {
1685
+ const payload = message.payload;
1686
+ store.registerSession(payload.sessionId, payload.appId, {
1687
+ userAgent: payload.userAgent,
1688
+ url: payload.url
1689
+ });
1690
+ clients.set(ws, { sessionId: payload.sessionId });
1691
+ ws.send(JSON.stringify({
1692
+ type: "SESSION_CONFIRMED",
1693
+ payload: { sessionId: payload.sessionId }
1694
+ }));
1695
+ log("Session registered:", payload.sessionId);
1696
+ break;
1697
+ }
1698
+ case "MUTATION_RECORDED": {
1699
+ const mutation = message.payload;
1700
+ store.storeMutation(mutation);
1701
+ ws.send(JSON.stringify({
1702
+ type: "MUTATION_ACKNOWLEDGED",
1703
+ payload: { mutationId: mutation.id, receivedAt: Date.now() }
1704
+ }));
1705
+ break;
1706
+ }
1707
+ case "MUTATION_BATCH": {
1708
+ const payload = message.payload;
1709
+ store.storeMutations(payload.mutations);
1710
+ ws.send(JSON.stringify({
1711
+ type: "BATCH_ACKNOWLEDGED",
1712
+ payload: { count: payload.mutations.length, receivedAt: Date.now() }
1713
+ }));
1714
+ log("Batch received:", payload.mutations.length, "mutations");
1715
+ break;
1716
+ }
1717
+ case "END_SESSION": {
1718
+ const clientInfo = clients.get(ws);
1719
+ if (clientInfo?.sessionId) {
1720
+ store.endSession(clientInfo.sessionId);
1721
+ log("Session ended:", clientInfo.sessionId);
1722
+ }
1723
+ break;
1724
+ }
1725
+ default:
1726
+ log("Unknown message type:", message.type);
1727
+ }
1728
+ }
1729
+ const server = {
1730
+ app,
1731
+ httpServer: null,
1732
+ wss: null,
1733
+ store,
1734
+ reconstructor,
1735
+ async start() {
1736
+ return new Promise((resolve) => {
1737
+ server.httpServer = app.listen(port, () => {
1738
+ log(`HTTP server listening on port ${port}`);
1739
+ });
1740
+ wss = new WebSocketServer({ port: wsPort });
1741
+ server.wss = wss;
1742
+ wss.on("connection", (ws) => {
1743
+ log("Client connected");
1744
+ clients.set(ws, {});
1745
+ ws.on("message", (data) => {
1746
+ try {
1747
+ const message = JSON.parse(data.toString());
1748
+ handleMessage(ws, message);
1749
+ } catch (error) {
1750
+ log("Error parsing message:", error);
1751
+ }
1752
+ });
1753
+ ws.on("close", () => {
1754
+ const clientInfo = clients.get(ws);
1755
+ if (clientInfo?.sessionId) {
1756
+ store.endSession(clientInfo.sessionId);
1757
+ }
1758
+ clients.delete(ws);
1759
+ log("Client disconnected");
1760
+ });
1761
+ ws.on("error", (error) => {
1762
+ log("WebSocket error:", error);
1763
+ });
1764
+ });
1765
+ wss.on("listening", () => {
1766
+ log(`WebSocket server listening on port ${wsPort}`);
1767
+ resolve();
1768
+ });
1769
+ });
1770
+ },
1771
+ async stop() {
1772
+ return new Promise((resolve) => {
1773
+ for (const ws of clients.keys()) {
1774
+ ws.close();
1775
+ }
1776
+ clients.clear();
1777
+ if (wss) {
1778
+ wss.close(() => {
1779
+ log("WebSocket server closed");
1780
+ });
1781
+ }
1782
+ if (server.httpServer) {
1783
+ server.httpServer.close(() => {
1784
+ log("HTTP server closed");
1785
+ resolve();
1786
+ });
1787
+ } else {
1788
+ resolve();
1789
+ }
1790
+ });
1791
+ }
1792
+ };
1793
+ return server;
1794
+ }
1795
+
1796
+ export { applyDiff, calculateDiff, compress, createMutation, debounce, decompress, deepClone, deepEqual, deepMerge, formatBytes, formatDuration, generateSessionId, getLogicalClock, getValueAtPath, instrument_exports as instrument, isBrowser, isNode, parseCallStack, recorder_exports as recorder, resetLogicalClock, safeParse, safeStringify, setValueAtPath, simpleHash, throttle };
1797
+ //# sourceMappingURL=index.mjs.map
1798
+ //# sourceMappingURL=index.mjs.map