-
-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathindex.ts
More file actions
482 lines (418 loc) · 13.1 KB
/
Copy pathindex.ts
File metadata and controls
482 lines (418 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
/* eslint-disable no-console */
import { Signal, Effect, Computed, effect } from "@preact/signals-core";
import {
formatValue,
getModelInfo,
getSignalId,
getSignalLabel,
getSignalName,
getSignalSearchText,
} from "./utils";
import { UpdateInfo, Node, Computed as ComputedType } from "./internal";
import { getExtensionBridge } from "./extension-bridge";
import "./devtools"; // Initialize DevTools integration
// Initialize the ExtensionBridge immediately so it can receive CONFIGURE_DEBUG messages
// from embedded devtools-ui even before any signals are created
getExtensionBridge();
const inflightUpdates = new Set<Signal | Effect>();
const updateInfoMap = new WeakMap<Signal | Effect, UpdateInfo[]>();
const trackers = new WeakMap<Signal | Effect, number>();
const signalValues = new WeakMap<Signal | Effect, any>();
const subscriptions = new WeakMap<Signal | Effect, () => void>();
const internalEffects = new WeakSet<Effect>();
const signalDependencies = new WeakMap<Signal | Effect, Set<string>>(); // Track what each signal depends on
export function setDebugOptions(options: {
grouped?: boolean;
enabled?: boolean;
consoleLogging?: boolean;
spacing?: number;
}) {
if (typeof options.grouped === "boolean") isGrouped = options.grouped;
if (typeof options.enabled === "boolean") debugEnabled = options.enabled;
if (typeof options.consoleLogging === "boolean")
consoleLoggingEnabled = options.consoleLogging;
if (typeof options.spacing === "number") spacing = options.spacing;
}
let isGrouped = true,
debugEnabled = true,
consoleLoggingEnabled = true,
initializing = false,
spacing = 0;
function trackDependency(target: Signal | Effect, source: Signal | Effect) {
const sourceId = getSignalId(source);
if (!signalDependencies.has(target)) {
signalDependencies.set(target, new Set());
}
signalDependencies.get(target)?.add(sourceId);
}
// Store original methods
const originalSubscribe = Signal.prototype._subscribe;
const originalUnsubscribe = Signal.prototype._unsubscribe;
// Track subscriptions for statistics
Signal.prototype._subscribe = function (node: Node) {
if (initializing) return originalSubscribe.call(this, node);
const tracker = trackers.get(this) || 0;
trackers.set(this, tracker + 1);
if (tracker === 0 && !("_fn" in this)) {
// Initialize tracked value and set up subscription for logging
const initialValue = this.peek();
signalValues.set(this, initialValue);
const sig = this as Signal;
// Set up a subscription to track value changes
initializing = true;
let internalEffect: Effect | undefined;
const unsubscribe = effect(function (this: Effect) {
// Capture the effect reference on first run and add to internalEffects
// to prevent it from being treated as a user effect
if (!internalEffect) {
internalEffect = this;
internalEffects.add(this);
}
const newValue = sig.value;
const prevValue = signalValues.get(sig);
if (!debugEnabled) return;
if (prevValue !== newValue) {
signalValues.set(sig, newValue);
inflightUpdates.add(sig);
updateInfoMap.set(sig, [
{
signal: sig,
prevValue,
newValue,
timestamp: Date.now(),
depth: 0,
type: "value",
},
]);
scheduleFlush();
}
});
initializing = false;
subscriptions.set(sig, () => {
unsubscribe();
internalEffect && internalEffects.delete(internalEffect);
});
}
return originalSubscribe.call(this, node);
};
const originalRefresh = Computed.prototype._refresh;
Computed.prototype._refresh = function () {
const prevValue = this._value;
const result = originalRefresh.call(this);
const newValue = this._value;
const baseSignal = bubbleUpToBaseSignal(this as any);
if (baseSignal && prevValue !== newValue) {
// Track dependency
trackDependency(this, baseSignal.signal);
const updateInfoList = updateInfoMap.get(baseSignal.signal) || [];
updateInfoList.push({
signal: this,
prevValue,
newValue,
timestamp: Date.now(),
depth: baseSignal.depth,
type: "value",
subscribedTo: getSignalId(baseSignal.signal),
allDependencies: getAllCurrentDependencies(this as any),
});
updateInfoMap.set(baseSignal.signal, updateInfoList);
}
return result;
};
const originalComputedUnsubscribe = Computed.prototype._unsubscribe;
Computed.prototype._unsubscribe = function (node: Node) {
const result = originalComputedUnsubscribe.call(this, node);
// When a computed signal loses all subscribers, it unsubscribes from its sources
// Check if this computed is now completely disconnected (no targets)
if (this._targets === undefined) {
// Notify devtools that this computed is disposed (no more subscribers)
if (
debugEnabled &&
typeof window !== "undefined" &&
(window as any).__PREACT_SIGNALS_DEVTOOLS__
) {
(window as any).__PREACT_SIGNALS_DEVTOOLS__.sendDisposal?.(
this,
"computed"
);
}
}
return result;
};
Signal.prototype._unsubscribe = function (node: Node) {
const tracker = trackers.get(this) || 0;
if (tracker > 0) {
trackers.set(this, tracker - 1);
if (tracker === 1) {
signalValues.delete(this);
trackers.delete(this);
// Clean up our debug subscription
const unsubscribe = subscriptions.get(this);
if (unsubscribe) {
unsubscribe();
subscriptions.delete(this);
}
// Notify devtools that this signal is disposed (no more subscribers)
// Only for plain signals - computed signals have their own disposal handler
if (
!("_fn" in this) &&
typeof window !== "undefined" &&
(window as any).__PREACT_SIGNALS_DEVTOOLS__
) {
(window as any).__PREACT_SIGNALS_DEVTOOLS__.sendDisposal?.(
this,
"signal"
);
}
}
}
return originalUnsubscribe.call(this, node);
};
function hasUpdateEntry(signal: Signal) {
const inFlightUpdate = updateInfoMap.get(signal);
if (
inFlightUpdate &&
!inFlightUpdate.find(updateInfo => updateInfo.signal === signal)
) {
return true;
}
return false;
}
export interface ModelInfo {
id: string;
name: string;
path?: string;
}
export interface DependencyInfo {
id: string;
name: string;
type: "signal" | "computed";
models?: ModelInfo[];
}
/**
* Get all current dependencies for a computed or effect by walking the _sources linked list.
* This provides the complete picture of what signals a computed/effect depends on,
* not just the one that triggered an update.
*
* Returns rich dependency info (id, name, type) so the devtools can render
* dependency nodes even if they haven't had their own updates.
*/
function getAllCurrentDependencies(
node: ComputedType | Effect
): DependencyInfo[] | undefined {
if (!("_sources" in node)) {
return undefined;
}
const dependencies = new Map<string, DependencyInfo>();
let sourceNode = (node as ComputedType)._sources;
while (sourceNode) {
const source = sourceNode._source as Signal;
const id = getSignalId(source);
if (!dependencies.has(id)) {
dependencies.set(id, {
id,
name: getSignalName(source, "value"),
type: "_fn" in source ? "computed" : "signal",
models: getModelInfo(source),
});
}
sourceNode = sourceNode._nextSource;
}
return dependencies.size > 0 ? Array.from(dependencies.values()) : undefined;
}
function bubbleUpToBaseSignal(
node: ComputedType,
depth = 1
): { signal: Signal; depth: number } | null {
if (!("_sources" in node)) {
return null;
}
// Get the head of the sources linked list
let sourceNode = node._sources;
// Iterate through all sources in the linked list
while (sourceNode) {
const source = sourceNode._source as Signal;
if (inflightUpdates.has(source) && !hasUpdateEntry(source)) {
return { signal: source, depth };
}
sourceNode = sourceNode._nextSource;
}
// If no direct source found, recurse into all sources to find the inflight update
sourceNode = node._sources;
while (sourceNode) {
const result = bubbleUpToBaseSignal(sourceNode._source as any, depth + 1);
if (result) {
return result;
}
sourceNode = sourceNode._nextSource;
}
return null;
}
Effect.prototype._debugCallback = function (this: Effect) {
if (!debugEnabled || internalEffects.has(this)) return;
if ("_sources" in this) {
const baseSignal = bubbleUpToBaseSignal(this as any);
if (baseSignal) {
// Track dependency
trackDependency(this, baseSignal.signal);
const updateInfoList = updateInfoMap.get(baseSignal.signal) || [];
updateInfoList.push({
signal: this,
timestamp: Date.now(),
depth: baseSignal.depth,
type: "component",
subscribedTo: getSignalId(baseSignal.signal),
allDependencies: getAllCurrentDependencies(this as any),
});
updateInfoMap.set(baseSignal.signal, updateInfoList);
}
}
};
const originalEffectCallback = Effect.prototype._callback;
Effect.prototype._callback = function (this: Effect) {
if (!debugEnabled || internalEffects.has(this))
return originalEffectCallback.call(this);
if ("_sources" in this) {
const baseSignal = bubbleUpToBaseSignal(this as any);
if (baseSignal) {
// Track dependency
trackDependency(this, baseSignal.signal);
const updateInfoList = updateInfoMap.get(baseSignal.signal) || [];
updateInfoList.push({
signal: this,
timestamp: Date.now(),
depth: baseSignal.depth,
type: "effect",
subscribedTo: getSignalId(baseSignal.signal),
allDependencies: getAllCurrentDependencies(this as any),
});
updateInfoMap.set(baseSignal.signal, updateInfoList);
}
}
return originalEffectCallback.call(this);
};
// Patch Effect.prototype._dispose to emit disposal events
const originalEffectDispose = Effect.prototype._dispose;
Effect.prototype._dispose = function (this: Effect) {
// Notify devtools that this effect is being disposed
if (
debugEnabled &&
!internalEffects.has(this) &&
typeof window !== "undefined" &&
(window as any).__PREACT_SIGNALS_DEVTOOLS__
) {
(window as any).__PREACT_SIGNALS_DEVTOOLS__.sendDisposal?.(this, "effect");
}
return originalEffectDispose.call(this);
};
let scheduled = false;
function scheduleFlush() {
if (!scheduled) {
scheduled = true;
queueMicrotask(() => {
flushUpdates();
scheduled = false;
});
}
}
function flushUpdates() {
const signals = Array.from(inflightUpdates);
inflightUpdates.clear();
const bridge = getExtensionBridge();
for (const signal of signals) {
const updateInfoList = updateInfoMap.get(signal) || [];
// Send updates to Chrome DevTools extension with filtering and throttling
if (typeof window !== "undefined" && !bridge.shouldThrottleUpdate()) {
// Filter updates based on signal names
const filteredUpdates = updateInfoList.filter(updateInfo =>
bridge.matchesFilter(
getSignalSearchText(updateInfo.signal, updateInfo.type)
)
);
if (
filteredUpdates.length > 0 &&
(window as any).__PREACT_SIGNALS_DEVTOOLS__
) {
(window as any).__PREACT_SIGNALS_DEVTOOLS__.sendUpdate?.(
filteredUpdates
);
}
}
let prevDepth = -1;
let openGroups = 0;
let prevOpenedGroup = false;
for (const updateInfo of updateInfoList) {
const openedGroup = logUpdate(updateInfo, prevDepth, prevOpenedGroup);
if (openedGroup) {
openGroups++;
}
prevDepth = updateInfo.depth;
prevOpenedGroup = openedGroup;
}
updateInfoMap.delete(signal);
new Array(openGroups).fill(0).map(endUpdateGroup);
}
}
/* eslint-disable no-console */
function logUpdate(
info: UpdateInfo,
prevDepth: number,
prevOpenedGroup: boolean
): boolean {
if (!debugEnabled || !consoleLoggingEnabled) return false;
const { signal, type, depth } = info;
const name = getSignalLabel(signal, type);
// Effects can't have descendants, so we use a normal log instead of a group
if (type === "effect" || type === "component") {
const copy = type === "effect" ? "effect" : "component render";
// Only close the previous group if the previous item opened one and we're at the same depth
if (isGrouped && prevDepth === depth && prevOpenedGroup) {
endUpdateGroup();
}
console.log(`${" ".repeat(depth * 2)}↪️ Triggered ${copy}: ${name}`);
// Return false to indicate we didn't open a group
return false;
}
const formattedPrev = formatValue(info.prevValue);
const formattedNew = formatValue(info.newValue);
if (isGrouped) {
// Only close the previous group if the previous item opened one and we're at the same depth
if (prevDepth === depth && prevOpenedGroup) {
endUpdateGroup();
}
if (depth === 0) {
console.group(`🎯 Signal Update: ${name}`);
} else {
console.groupCollapsed(
`${" ".repeat(depth * 2)}↪️ Triggered update: ${name}`
);
}
console.log(`${" ".repeat(depth * spacing)}From:`, formattedPrev);
console.log(`${" ".repeat(depth * spacing)}To:`, formattedNew);
if ("_fn" in signal) {
console.log(`${" ".repeat(depth * spacing)}Type: Computed`);
}
// Return true to indicate we opened a group
return true;
} else {
console.log(
`${depth === 0 ? "🎯" : "↪️"} ${name}: ${formattedPrev} → ${formattedNew}`
);
return false;
}
}
function endUpdateGroup() {
if (debugEnabled && consoleLoggingEnabled && isGrouped) {
console.groupEnd();
}
}
/* eslint-enable no-console */
// Export extension utilities
export interface ExtensionConfig {
enabled?: boolean;
grouped?: boolean;
spacing?: number;
consoleLogging?: boolean;
maxUpdatesPerSecond?: number;
filterPatterns?: string[];
}