-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsync.content.ts
More file actions
448 lines (416 loc) · 13.8 KB
/
Copy pathsync.content.ts
File metadata and controls
448 lines (416 loc) · 13.8 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
import type { Mutation, Query } from "@tanstack/query-core";
import type {
ActionType,
BridgeMessage,
ChangeEvent,
PathSegment,
} from "@/types/messages";
import { BRIDGE_SOURCE, BRIDGE_SOURCE_ACTION } from "@/types/messages";
import type {
MutationEntry,
MutationState,
MutationStatus,
QueryDisplayStatus,
QueryEntry,
QueryState,
} from "@/types/ui";
import { encodeBigInts } from "@/utils/serialization";
import { deleteAtPath, setAtPath } from "@/utils/set-at-path";
const POLL_INTERVAL_MS = 250;
const MAX_POLL_MS = 30_000;
/**
* This script runs in the page's MAIN world and QueryCache.notify iterates its
* subscribers without catching, so an exception thrown here unwinds into the
* inspected application's own render/commit and trips its error boundary.
* Nothing the devtools do may escape into the page.
*/
function safely(label: string, fn: () => void): void {
try {
fn();
} catch (error: unknown) {
console.warn(`[tanstack-query-devtools] skipped ${label}:`, error);
}
}
/** Wraps a callback so it is invoked through `safely` without re-indenting its body. */
function guarded<A extends readonly unknown[]>(
label: string,
fn: (...args: A) => void,
): (...args: A) => void {
return (...args: A) => safely(label, () => fn(...args));
}
function deriveQueryStatus(query: Query): QueryDisplayStatus {
if (query.state.fetchStatus === "fetching") return "fetching";
if (query.getObserversCount() === 0) return "inactive";
if (query.state.fetchStatus === "paused") return "paused";
if (query.isStale()) return "stale";
return "fresh";
}
function sanitizeFetchMeta(
meta: Record<string, unknown> | null,
): Record<string, unknown> | null {
if (!meta) return null;
const { __previousQueryOptions, ...rest } = meta;
if (__previousQueryOptions !== undefined) {
return { ...rest, __previousQueryOptions: true };
}
return Object.keys(rest).length > 0 ? rest : null;
}
function extractQueryState(query: Query): QueryState {
const s = query.state;
return {
data: s.data,
dataUpdateCount: s.dataUpdateCount,
dataUpdatedAt: s.dataUpdatedAt,
error: s.error,
errorUpdateCount: s.errorUpdateCount,
errorUpdatedAt: s.errorUpdatedAt,
fetchFailureCount: s.fetchFailureCount,
fetchFailureReason: s.fetchFailureReason,
fetchMeta: sanitizeFetchMeta(s.fetchMeta as Record<string, unknown> | null),
isInvalidated: s.isInvalidated,
status: s.status,
fetchStatus: s.fetchStatus,
};
}
function extractQuery(query: Query): QueryEntry {
return {
queryHash: query.queryHash,
queryKey: [...query.queryKey],
observerCount: query.getObserversCount(),
status: deriveQueryStatus(query),
dataUpdatedAt: query.state.dataUpdatedAt,
data: query.state.data,
isActive: query.isActive(),
isDisabled: query.isDisabled(),
meta: query.meta,
state: extractQueryState(query),
};
}
function extractMutationState(mutation: Mutation): MutationState {
return {
status: mutation.state.status as MutationStatus,
variables: mutation.state.variables,
context: mutation.state.context,
data: mutation.state.data,
error: mutation.state.error,
failureCount: mutation.state.failureCount,
failureReason: mutation.state.failureReason,
isPaused: mutation.state.isPaused,
submittedAt: mutation.state.submittedAt,
};
}
function extractMutation(mutation: Mutation): MutationEntry {
return {
mutationId: mutation.mutationId,
mutationKey: mutation.options.mutationKey
? [...mutation.options.mutationKey]
: null,
status: mutation.state.status as MutationEntry["status"],
timestamp: mutation.state.submittedAt,
variables: mutation.state.variables,
context: mutation.state.context,
data: mutation.state.data,
error: mutation.state.error,
state: extractMutationState(mutation),
};
}
function postBridge<T extends BridgeMessage["type"]>(
type: T,
payload: BridgeMessage<T>["payload"],
): void {
const message: BridgeMessage<T> = { source: BRIDGE_SOURCE, type, payload };
window.postMessage(message, "*");
}
function postChange(change: ChangeEvent): void {
postBridge(
"SYNC_UPDATE",
encodeBigInts({ changes: [change] }) as { changes: readonly ChangeEvent[] },
);
}
function startSync(client: NonNullable<Window["__TANSTACK_QUERY_CLIENT__"]>) {
const queryCache = client.getQueryCache();
const mutationCache = client.getMutationCache();
// Build and send initial snapshot
safely("initial snapshot", () => {
const queries = queryCache.getAll().map((q) => extractQuery(q));
const mutations = mutationCache.getAll().map((m) => extractMutation(m));
postBridge(
"SYNC_SNAPSHOT",
encodeBigInts({ queries, mutations }) as {
queries: QueryEntry[];
mutations: MutationEntry[];
},
);
});
// Subscribe to QueryCache
const unsubQuery = queryCache.subscribe(
guarded("query cache update", (event) => {
const type = event.type;
if (
type === "observerResultsUpdated" ||
type === "observerOptionsUpdated"
) {
return; // Ignored
}
const query = event.query;
if (type === "removed") {
postChange({
entityType: "query",
changeType: "removed",
queryHash: query.queryHash,
entry: undefined,
});
return;
}
// Skip events for queries that have been removed from the cache
// (e.g., observerRemoved firing after removeQueries was called)
if (!queryCache.get(query.queryHash)) {
return;
}
// added, updated, observerAdded, observerRemoved all map to entry updates
const changeType = type === "added" ? "added" : "updated";
postChange({
entityType: "query",
changeType,
queryHash: query.queryHash,
entry: extractQuery(query),
});
}),
);
// Subscribe to MutationCache
const unsubMutation = mutationCache.subscribe(
guarded("mutation cache update", (event) => {
const type = event.type;
if (
type === "observerAdded" ||
type === "observerRemoved" ||
type === "observerOptionsUpdated"
) {
return; // Ignored
}
const mutation = event.mutation;
if (type === "removed") {
postChange({
entityType: "mutation",
changeType: "removed",
mutationId: mutation.mutationId,
entry: undefined,
});
return;
}
const changeType = type === "added" ? "added" : "updated";
postChange({
entityType: "mutation",
changeType,
mutationId: mutation.mutationId,
entry: extractMutation(mutation),
});
}),
);
// Return cleanup function
return () => {
unsubQuery();
unsubMutation();
};
}
export default defineContentScript({
matches: ["<all_urls>"],
world: "MAIN",
main() {
let cleanup: (() => void) | null = null;
let elapsed = 0;
function handleAction(action: ActionType, queryHash: string) {
const client = window.__TANSTACK_QUERY_CLIENT__;
const query = client?.getQueryCache().get(queryHash);
if (!client) return;
if (!query) return;
if (action === "invalidate") {
void client.invalidateQueries({ queryKey: query.queryKey });
} else if (action === "refetch") {
void client.refetchQueries({ queryKey: query.queryKey });
} else if (action === "reset") {
void client.resetQueries({ queryKey: query.queryKey });
} else if (action === "remove") {
client.removeQueries({ queryKey: query.queryKey });
} else if (action === "triggerError") {
const __previousQueryOptions = query.options;
query.setState({
data: undefined,
status: "error",
error: new Error("Unknown error from devtools"),
fetchMeta: {
...query.state.fetchMeta,
__previousQueryOptions,
} as Record<string, unknown>,
});
} else if (action === "restoreError") {
void client.resetQueries({ queryKey: query.queryKey });
} else if (action === "triggerLoading") {
const __previousQueryOptions = query.options;
void query.fetch({
...query.options,
queryFn: () =>
new Promise(() => {
/* Never resolves */
}),
gcTime: -1,
});
query.setState({
data: undefined,
status: "pending",
fetchMeta: {
...query.state.fetchMeta,
__previousQueryOptions,
} as Record<string, unknown>,
});
} else if (action === "restoreLoading") {
const meta = query.state.fetchMeta as Record<string, unknown> | null;
const previousOptions = meta?.__previousQueryOptions as
| typeof query.options
| undefined;
void query.cancel({ silent: true });
query.setState({
...query.state,
fetchStatus: "idle",
fetchMeta: null,
});
if (previousOptions) {
void query.fetch(previousOptions);
}
}
}
// Listen for reverse-direction action messages from the devtools panel
window.addEventListener(
"message",
guarded("panel request", (event: MessageEvent) => {
if (
event.source !== window ||
(event.data as Record<string, unknown>)?.source !==
BRIDGE_SOURCE_ACTION
) {
return;
}
const data = event.data as {
type?: string;
payload: Record<string, unknown>;
};
if (data.type === "RESYNC_REQUEST") {
const client = window.__TANSTACK_QUERY_CLIENT__;
if (!client) return;
const queryCache = client.getQueryCache();
const mutationCache = client.getMutationCache();
const queries = queryCache.getAll().map((q) => extractQuery(q));
const mutations = mutationCache
.getAll()
.map((m) => extractMutation(m));
postBridge(
"SYNC_SNAPSHOT",
encodeBigInts({ queries, mutations }) as {
queries: QueryEntry[];
mutations: MutationEntry[];
},
);
return;
}
if (data.type === "SET_DATA_REQUEST") {
const { queryHash, path, value } = data.payload as {
queryHash: string;
path: readonly PathSegment[];
value: string | number | boolean;
};
const client = window.__TANSTACK_QUERY_CLIENT__;
if (!client) return;
const query = client.getQueryCache().get(queryHash);
if (!query) return;
client.setQueryData(query.queryKey, (old: unknown) =>
setAtPath(old, path, value),
);
return;
}
if (data.type === "DELETE_DATA_REQUEST") {
const { queryHash, path } = data.payload as {
queryHash: string;
path: readonly PathSegment[];
};
const client = window.__TANSTACK_QUERY_CLIENT__;
if (!client) return;
const query = client.getQueryCache().get(queryHash);
if (!query) return;
client.setQueryData(query.queryKey, (old: unknown) =>
deleteAtPath(old, path),
);
return;
}
if (data.type === "REMOVE_ALL_QUERIES_REQUEST") {
const client = window.__TANSTACK_QUERY_CLIENT__;
if (!client) return;
client.getQueryCache().clear();
return;
}
if (data.type === "CLEAR_MUTATION_CACHE_REQUEST") {
const client = window.__TANSTACK_QUERY_CLIENT__;
if (!client) return;
client.getMutationCache().clear();
return;
}
if (data.type === "CLEAR_ARRAY_REQUEST") {
const { queryHash, path } = data.payload as {
queryHash: string;
path: readonly PathSegment[];
};
const client = window.__TANSTACK_QUERY_CLIENT__;
if (!client) return;
const query = client.getQueryCache().get(queryHash);
if (!query) return;
client.setQueryData(query.queryKey, (old: unknown) => {
// Navigate to the target to check if it's a Set
let target = old;
for (const segment of path) {
if (target == null || typeof target !== "object") return old;
if (typeof segment === "object" && "mapKey" in segment) {
if (target instanceof Map) target = target.get(segment.mapKey);
else return old;
} else if (target instanceof Set) {
target = Array.from(target)[Number(segment)];
} else {
target = (target as Record<string, unknown>)[segment];
}
}
const clearValue = target instanceof Set ? new Set() : [];
return setAtPath(old, path, clearValue);
});
return;
}
const { payload } = data as {
payload: { action: ActionType; queryHash: string };
};
handleAction(payload.action, payload.queryHash);
}),
);
// Immediate check
const client = window.__TANSTACK_QUERY_CLIENT__;
if (client) {
cleanup = startSync(client);
return;
}
const timer = setInterval(
guarded("client detection", () => {
const c = window.__TANSTACK_QUERY_CLIENT__;
if (c) {
clearInterval(timer);
cleanup = startSync(c);
return;
}
elapsed += POLL_INTERVAL_MS;
if (elapsed >= MAX_POLL_MS) {
clearInterval(timer);
postBridge("SYNC_DISCONNECTED", {} as Record<string, never>);
}
}),
POLL_INTERVAL_MS,
);
// Note: MAIN-world scripts don't have context for cleanup,
// but if the page unloads the script is destroyed anyway.
void cleanup;
},
});