@capybara-devtools/core 0.7.0 → 0.9.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 (52) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/init.d.ts +5 -0
  6. package/dist/init.d.ts.map +1 -1
  7. package/dist/init.js +4 -0
  8. package/dist/init.js.map +1 -1
  9. package/dist/plugins/network/fetch.d.ts.map +1 -1
  10. package/dist/plugins/network/fetch.js +1 -0
  11. package/dist/plugins/network/fetch.js.map +1 -1
  12. package/dist/plugins/network/settings.d.ts +4 -0
  13. package/dist/plugins/network/settings.d.ts.map +1 -1
  14. package/dist/plugins/network/settings.js.map +1 -1
  15. package/dist/plugins/network/timing.d.ts +9 -0
  16. package/dist/plugins/network/timing.d.ts.map +1 -0
  17. package/dist/plugins/network/timing.js +79 -0
  18. package/dist/plugins/network/timing.js.map +1 -0
  19. package/dist/plugins/network/xhr.d.ts.map +1 -1
  20. package/dist/plugins/network/xhr.js +1 -0
  21. package/dist/plugins/network/xhr.js.map +1 -1
  22. package/dist/plugins/network.d.ts.map +1 -1
  23. package/dist/plugins/network.js +4 -1
  24. package/dist/plugins/network.js.map +1 -1
  25. package/dist/plugins/performance/index.d.ts +41 -0
  26. package/dist/plugins/performance/index.d.ts.map +1 -0
  27. package/dist/plugins/performance/index.js +215 -0
  28. package/dist/plugins/performance/index.js.map +1 -0
  29. package/dist/plugins/performance/observe.d.ts +42 -0
  30. package/dist/plugins/performance/observe.d.ts.map +1 -0
  31. package/dist/plugins/performance/observe.js +1280 -0
  32. package/dist/plugins/performance/observe.js.map +1 -0
  33. package/dist/plugins/performance/profile.d.ts +50 -0
  34. package/dist/plugins/performance/profile.d.ts.map +1 -0
  35. package/dist/plugins/performance/profile.js +196 -0
  36. package/dist/plugins/performance/profile.js.map +1 -0
  37. package/dist/plugins/performance/renders.d.ts +13 -0
  38. package/dist/plugins/performance/renders.d.ts.map +1 -0
  39. package/dist/plugins/performance/renders.js +144 -0
  40. package/dist/plugins/performance/renders.js.map +1 -0
  41. package/package.json +2 -2
  42. package/src/index.ts +2 -0
  43. package/src/init.ts +8 -0
  44. package/src/plugins/network/fetch.ts +1 -0
  45. package/src/plugins/network/settings.ts +4 -0
  46. package/src/plugins/network/timing.ts +82 -0
  47. package/src/plugins/network/xhr.ts +1 -0
  48. package/src/plugins/network.ts +3 -1
  49. package/src/plugins/performance/index.ts +243 -0
  50. package/src/plugins/performance/observe.ts +1291 -0
  51. package/src/plugins/performance/profile.ts +232 -0
  52. package/src/plugins/performance/renders.ts +152 -0
package/src/init.ts CHANGED
@@ -2,6 +2,7 @@ import { CLIENT_PATH, DEFAULT_PORT } from '@capybara-devtools/protocol';
2
2
  import { createClient, getActiveClient, type CapybaraClient, type ClientOptions, type Plugin } from './client.js';
3
3
  import { consolePlugin } from './plugins/console.js';
4
4
  import { networkPlugin, type NetworkPluginOptions } from './plugins/network.js';
5
+ import { performancePlugin, type PerformancePlatform, type PerformancePluginOptions } from './plugins/performance/index.js';
5
6
  import { statePlugin, type StatePluginOptions } from './plugins/state/index.js';
6
7
  import { storagePlugin, type StorageAdapter } from './plugins/storage.js';
7
8
 
@@ -22,6 +23,8 @@ export interface CommonInitOptions {
22
23
  network?: boolean | NetworkPluginOptions;
23
24
  /** Show the app's Redux, Zustand, TanStack Query and SWR stores, and its React Context values. Default true. */
24
25
  state?: boolean | StatePluginOptions;
26
+ /** Measure Web Vitals, slow interactions, long frames, resources and React render times. Default true where the platform can. */
27
+ performance?: boolean | PerformancePluginOptions;
25
28
  plugins?: Plugin[];
26
29
  }
27
30
 
@@ -38,6 +41,8 @@ export interface PlatformSetup {
38
41
  networkNoise: RegExp[];
39
42
  /** Without adapters, the Storage tab is off. */
40
43
  storage?: StorageAdapter[];
44
+ /** What the platform measures performance with; without it there is no performance plugin. */
45
+ performance?: PerformancePlatform;
41
46
  }
42
47
 
43
48
  /** The part of `init()` the SDKs share: whether to run, the plugins to turn on, and the connection. */
@@ -57,6 +62,9 @@ export function initClient(options: CommonInitOptions, production: boolean, plat
57
62
  }
58
63
  if (setup.storage) plugins.push(storagePlugin(setup.storage));
59
64
  if (options.state !== false) plugins.push(statePlugin(typeof options.state === 'object' ? options.state : {}));
65
+ if (options.performance !== false && setup.performance) {
66
+ plugins.push(performancePlugin(typeof options.performance === 'object' ? options.performance : {}, setup.performance));
67
+ }
60
68
  plugins.push(...(options.plugins ?? []));
61
69
 
62
70
  const host = options.host ?? setup.host;
@@ -45,6 +45,7 @@ export function patchFetch(ctx: PluginContext, settings: Settings): () => void {
45
45
  headers: settings.redact(request.headers),
46
46
  body: request.body,
47
47
  });
48
+ settings.timing?.track(id, request.url, start);
48
49
 
49
50
  let promise: Promise<Response>;
50
51
  try {
@@ -1,5 +1,6 @@
1
1
  import { MAX_BODY_SIZE } from '@capybara-devtools/protocol';
2
2
  import { failureExplainer, type FailureExplainer } from './failure.js';
3
+ import type { RequestTiming } from './timing.js';
3
4
 
4
5
  export interface NetworkPluginOptions {
5
6
  /** Patch `fetch`. Where fetch runs on XHR (whatwg-fetch), its requests are recorded once, by the XHR patch, as fetch. */
@@ -15,6 +16,8 @@ export interface NetworkPluginOptions {
15
16
  maxMessageSize?: number;
16
17
  /** Header names (case-insensitive) whose values are replaced with "[redacted]". */
17
18
  redactHeaders?: string[];
19
+ /** How long each step of a request took, from the browser's Resource Timing, where it reports it. Default true. */
20
+ timing?: boolean;
18
21
  }
19
22
 
20
23
  export interface Settings {
@@ -22,6 +25,7 @@ export interface Settings {
22
25
  isIgnored(url: string): boolean;
23
26
  redact(headers: Record<string, string>): Record<string, string>;
24
27
  failures: FailureExplainer;
28
+ timing?: RequestTiming;
25
29
  }
26
30
 
27
31
  export function resolveSettings(options: NetworkPluginOptions): Settings {
@@ -0,0 +1,82 @@
1
+ import type { NetworkTimingPayload } from '@capybara-devtools/protocol';
2
+ import type { PluginContext } from '../../client.js';
3
+ import { now } from '../../utils.js';
4
+
5
+ export interface RequestTiming {
6
+ /** Waits for the browser's Resource Timing entry of a request the plugin recorded, and reports its steps. */
7
+ track(id: string, url: string, start: number): void;
8
+ stop(): void;
9
+ }
10
+
11
+ /** The entry comes once the whole body is in, which for a slow download can take a while. */
12
+ const WAIT_MS = 60_000;
13
+ const MAX_TRACKED = 500;
14
+ /** The browser's clock for the entry and `now()` for the call can differ by a rounding step. */
15
+ const SLACK_MS = 1;
16
+
17
+ /** Undefined where the runtime reports no resource entries (React Native before 0.84, old browsers). */
18
+ export function requestTiming(ctx: PluginContext): RequestTiming | undefined {
19
+ const Observer = (globalThis as { PerformanceObserver?: any }).PerformanceObserver;
20
+ if (typeof Observer !== 'function' || !Observer.supportedEntryTypes?.includes('resource')) return undefined;
21
+ const tracked: Array<{ id: string; url: string; start: number }> = [];
22
+ let observer: { observe(options: object): void; disconnect(): void } | undefined;
23
+ try {
24
+ observer = new Observer((list: { getEntries(): any[] }) => {
25
+ for (const entry of list.getEntries()) {
26
+ if (entry.initiatorType !== 'fetch' && entry.initiatorType !== 'xmlhttprequest') continue;
27
+ // The latest request to the URL that began before the browser did.
28
+ let index = -1;
29
+ for (let i = tracked.length - 1; i >= 0; i--) {
30
+ const request = tracked[i]!;
31
+ if (request.url === entry.name && request.start <= entry.startTime + SLACK_MS) {
32
+ index = i;
33
+ break;
34
+ }
35
+ }
36
+ if (index < 0) continue;
37
+ const [request] = tracked.splice(index, 1);
38
+ try {
39
+ ctx.emit('network.timing', timingOf(request!.id, entry));
40
+ } catch {
41
+ // never surface SDK failures to the app
42
+ }
43
+ }
44
+ });
45
+ // Not buffered: only requests recorded from now on are matched.
46
+ observer?.observe({ type: 'resource' });
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ return {
51
+ track(id, url, start) {
52
+ const cutoff = now() - WAIT_MS;
53
+ while (tracked.length > 0 && (tracked.length >= MAX_TRACKED || tracked[0]!.start < cutoff)) tracked.shift();
54
+ tracked.push({ id, url, start });
55
+ },
56
+ stop() {
57
+ observer?.disconnect();
58
+ tracked.length = 0;
59
+ },
60
+ };
61
+ }
62
+
63
+ function timingOf(id: string, entry: any): NetworkTimingPayload {
64
+ const round = (value: number) => Math.round(value * 10) / 10;
65
+ const total = round(entry.duration);
66
+ // Another origin's request without Timing-Allow-Origin: every step reads 0.
67
+ if (!(entry.requestStart > 0)) return { id, hidden: true, total, ...(entry.nextHopProtocol && { protocol: entry.nextHopProtocol }) };
68
+ const dns = entry.domainLookupEnd - entry.domainLookupStart;
69
+ const connect = entry.connectEnd - entry.connectStart;
70
+ return {
71
+ id,
72
+ queued: round(Math.max(0, entry.requestStart - entry.startTime - dns - connect)),
73
+ dns: round(dns),
74
+ connect: round(connect),
75
+ ...(entry.secureConnectionStart > 0 && { tls: round(entry.connectEnd - entry.secureConnectionStart) }),
76
+ waiting: round(entry.responseStart - entry.requestStart),
77
+ download: round(entry.responseEnd - entry.responseStart),
78
+ total,
79
+ ...(entry.nextHopProtocol && { protocol: entry.nextHopProtocol }),
80
+ ...(((entry.transferSize === 0 && entry.decodedBodySize > 0) || entry.deliveryType === 'cache') && { cached: true }),
81
+ };
82
+ }
@@ -65,6 +65,7 @@ export function patchXhr(ctx: PluginContext, settings: Settings, fetchOverXhr: b
65
65
  headers: settings.redact(info.headers),
66
66
  body: previewRequestBody(body, settings.maxBody, findHeader(info.headers, 'content-type')),
67
67
  });
68
+ settings.timing?.track(id, absoluteUrl(info.url), start);
68
69
 
69
70
  let failure: 'error' | 'timeout' | 'abort' | undefined;
70
71
  const listeners: Record<string, () => void> = {
@@ -2,6 +2,7 @@ import { MAX_SOCKET_MESSAGE_SIZE } from '@capybara-devtools/protocol';
2
2
  import type { Plugin } from '../client.js';
3
3
  import { isXhrFetch, patchFetch } from './network/fetch.js';
4
4
  import { resolveSettings, type NetworkPluginOptions } from './network/settings.js';
5
+ import { requestTiming } from './network/timing.js';
5
6
  import { patchXhr } from './network/xhr.js';
6
7
  import { hookWebSockets } from './websocket.js';
7
8
 
@@ -15,7 +16,8 @@ export function networkPlugin(options: NetworkPluginOptions = {}): Plugin {
15
16
  name: 'network',
16
17
  setup(ctx) {
17
18
  const settings = resolveSettings(options);
18
- const teardowns: Array<() => void> = [() => settings.failures.stop()];
19
+ if (options.timing !== false) settings.timing = requestTiming(ctx);
20
+ const teardowns: Array<() => void> = [() => settings.failures.stop(), () => settings.timing?.stop()];
19
21
  const fetchOverXhr = options.xhr !== false && isXhrFetch();
20
22
  if (options.fetch !== false && !fetchOverXhr) teardowns.push(patchFetch(ctx, settings));
21
23
  if (options.xhr !== false) teardowns.push(patchXhr(ctx, settings, fetchOverXhr));
@@ -0,0 +1,243 @@
1
+ import { PERF_MAX_MONITOR_MS, type PerfCommit, type PerfEnvPayload, type PerformanceCommands } from '@capybara-devtools/protocol';
2
+ import { getActiveClient, type Plugin, type PluginContext } from '../../client.js';
3
+ import type { PerfCollector, PerfEmit } from './observe.js';
4
+ import type { StackSampler } from './profile.js';
5
+ import { watchRenders } from './renders.js';
6
+
7
+ export { observePerformance, type ObserveOptions, type PerfCollector, type PerfEmit, type WebVitalsLike } from './observe.js';
8
+ export { sampleStacks, type SamplerOptions, type StackSampler } from './profile.js';
9
+
10
+ export interface PerformancePluginOptions {
11
+ /** Interactions quicker than this many ms are not recorded. Default 16, the shortest browsers report. */
12
+ interactionThreshold?: number;
13
+ /** React component render times, from development builds of React. Default true. */
14
+ renders?: boolean;
15
+ /** What the page loads, from Resource Timing. Default true. */
16
+ resources?: boolean;
17
+ /**
18
+ * Which functions ran during a slow interaction or long frame, from samples of the call stacks, where the browser
19
+ * can take them and the page is served with `Document-Policy: js-profiling`. Default true.
20
+ */
21
+ profile?: boolean;
22
+ }
23
+
24
+ /** What a platform measures with; the web SDK observes the page and its Web Vitals. */
25
+ export interface PerformancePlatform {
26
+ build: 'development' | 'production';
27
+ observe?: (emit: PerfEmit, isConnected: () => boolean, options: { threshold: number; resources: boolean; serialize: (value: unknown) => unknown }) => PerfCollector;
28
+ /** Starts sampling numbers for `monitor` until `stop`. */
29
+ monitor?: () => { read(): Record<string, number>; stop(): void };
30
+ highlight?: (selector: string) => boolean;
31
+ entryTypes?: () => string[];
32
+ timeOrigin?: () => number | undefined;
33
+ /** Whether the page is out of view now, as the measuring starts. */
34
+ background?: () => boolean;
35
+ /** Starts sampling call stacks; `connected` says whether anyone would get them. */
36
+ profile?: (connected: () => boolean) => StackSampler;
37
+ }
38
+
39
+ /** React commits sent per batch, the slowest; the rest are counted as skipped. */
40
+ const COMMITS_PER_BATCH = 20;
41
+ /** Commits held while Capybara is not connected. */
42
+ const COMMITS_WAITING = 200;
43
+ const BATCH_MS = 1_000;
44
+ const SAMPLE_MS = 1_000;
45
+ /** Interactions and frames at least this long get a profile: under 10 samples say too little. */
46
+ const PROFILE_FROM_MS = 100;
47
+ /** A profile starts this much before what it is about and ends as much after, for what led to it. */
48
+ const PROFILE_MARGIN_MS = 20;
49
+ const PROFILES_PER_BATCH = 3;
50
+ const PROFILES_PER_MINUTE = 30;
51
+ /** How often sampling is stopped while no one is connected, and started again once someone is. */
52
+ const PROFILE_CHECK_MS = 5_000;
53
+
54
+ export function performancePlugin(options: PerformancePluginOptions, platform: PerformancePlatform): Plugin {
55
+ let ctx: PluginContext | undefined;
56
+ let env: PerfEnvPayload = { source: 'sdk', build: platform.build };
57
+ let until = 0;
58
+ let sampler: StackSampler | undefined;
59
+ let monitorSampler: { read(): Record<string, number>; stop(): void } | undefined;
60
+ let sampleTimer: ReturnType<typeof setInterval> | undefined;
61
+ let collector: PerfCollector | undefined;
62
+
63
+ const isConnected = () => getActiveClient()?.connected === true;
64
+ const announce = (change: Partial<PerfEnvPayload>) => {
65
+ env = { ...env, ...change };
66
+ ctx?.emit('perf.env', env);
67
+ };
68
+
69
+ const stopSampling = () => {
70
+ if (sampleTimer !== undefined) clearInterval(sampleTimer);
71
+ sampleTimer = undefined;
72
+ monitorSampler?.stop();
73
+ monitorSampler = undefined;
74
+ };
75
+ const sample = () => {
76
+ if (!monitorSampler || Date.now() > until) return stopSampling();
77
+ try {
78
+ ctx?.emit('perf.samples', { source: 'page', samples: [{ t: Date.now(), values: monitorSampler.read() }] });
79
+ } catch {
80
+ stopSampling();
81
+ }
82
+ };
83
+ const announceProfiler = () => {
84
+ if (sampler && env.profiler?.state !== sampler.state()) announce({ profiler: { state: sampler.state() } });
85
+ };
86
+
87
+ const commands: { [M in keyof PerformanceCommands]: (params: PerformanceCommands[M]['params']) => PerformanceCommands[M]['result'] } = {
88
+ status: () => ({ env, monitoring: monitorSampler !== undefined && Date.now() <= until }),
89
+ // Viewers cannot be told apart, so the latest end of all their leases wins.
90
+ monitor: (params) => {
91
+ const ttl = Math.min(Math.max(Number(params?.ttl) || 0, 0), PERF_MAX_MONITOR_MS);
92
+ until = Math.max(until, Date.now() + ttl);
93
+ if (!monitorSampler && platform.monitor && ttl > 0) {
94
+ monitorSampler = platform.monitor();
95
+ sampleTimer = setInterval(sample, SAMPLE_MS);
96
+ }
97
+ return { until };
98
+ },
99
+ highlight: (params) => ({ found: typeof params?.selector === 'string' && platform.highlight?.(params.selector) === true }),
100
+ inspect: () => ({ sent: collector?.inspect?.() === true }),
101
+ profile: (params) => {
102
+ sampler?.hold(params?.hold === true);
103
+ announceProfiler();
104
+ return { state: sampler?.state() ?? 'off' };
105
+ },
106
+ };
107
+
108
+ return {
109
+ name: 'performance',
110
+ commands,
111
+ setup(context) {
112
+ ctx = context;
113
+ const teardowns: Array<() => void> = [stopSampling];
114
+ announce({
115
+ ...(platform.timeOrigin?.() !== undefined && { timeOrigin: platform.timeOrigin?.() }),
116
+ ...(platform.entryTypes && { entryTypes: platform.entryTypes() }),
117
+ ...(platform.background?.() && { background: true as const }),
118
+ });
119
+
120
+ let emit: PerfEmit = context.emit;
121
+ if (options.profile !== false && platform.profile) {
122
+ const stacks = platform.profile(isConnected);
123
+ sampler = stacks;
124
+ announceProfiler();
125
+ let spans: Array<[number, number]> = [];
126
+ let cutting: ReturnType<typeof setTimeout> | undefined;
127
+ const sent: number[] = [];
128
+ let dropped = 0;
129
+ const cut = async () => {
130
+ cutting = undefined;
131
+ // Spans that overlap are one moment: a slow click and the long frame it ran in.
132
+ const merged: Array<[number, number]> = [];
133
+ for (const span of spans.splice(0).sort((a, b) => a[0] - b[0])) {
134
+ const last = merged.at(-1);
135
+ if (last && span[0] <= last[1]) last[1] = Math.max(last[1], span[1]);
136
+ else merged.push([...span]);
137
+ }
138
+ const time = Date.now();
139
+ while (sent.length > 0 && time - sent[0]! > 60_000) sent.shift();
140
+ const room = Math.max(0, Math.min(PROFILES_PER_BATCH, PROFILES_PER_MINUTE - sent.length));
141
+ const chosen = merged.sort((a, b) => b[1] - b[0] - (a[1] - a[0])).slice(0, room);
142
+ dropped += merged.length - chosen.length;
143
+ if (chosen.length === 0) return;
144
+ try {
145
+ for (const profile of await stacks.cut(chosen.sort((a, b) => a[0] - b[0]))) {
146
+ sent.push(Date.now());
147
+ ctx?.emit('perf.profile', dropped > 0 ? { ...profile, skipped: dropped } : profile);
148
+ dropped = 0;
149
+ }
150
+ } catch {
151
+ // A profile lost is a section missing, not a page broken.
152
+ }
153
+ announceProfiler();
154
+ };
155
+ emit = (kind, payload) => {
156
+ context.emit(kind, payload);
157
+ // The collector sends only once connected: the first thing it sends starts the sampling the plugin could
158
+ // not start before.
159
+ if (stacks.state() === 'paused') {
160
+ stacks.check();
161
+ announceProfiler();
162
+ }
163
+ if (kind !== 'perf.interaction' && kind !== 'perf.frame') return;
164
+ const { start, duration } = payload as { start: number; duration: number };
165
+ if (!(duration >= PROFILE_FROM_MS)) return;
166
+ spans.push([start - PROFILE_MARGIN_MS, start + duration + PROFILE_MARGIN_MS]);
167
+ cutting ??= setTimeout(() => void cut(), 0);
168
+ };
169
+ const checking = setInterval(() => {
170
+ stacks.check();
171
+ announceProfiler();
172
+ }, PROFILE_CHECK_MS);
173
+ teardowns.push(() => {
174
+ clearInterval(checking);
175
+ if (cutting !== undefined) clearTimeout(cutting);
176
+ spans = [];
177
+ stacks.stop();
178
+ sampler = undefined;
179
+ });
180
+ }
181
+
182
+ if (platform.observe) {
183
+ const observed = platform.observe(emit, isConnected, {
184
+ threshold: options.interactionThreshold ?? 16,
185
+ resources: options.resources !== false,
186
+ serialize: context.serialize,
187
+ });
188
+ collector = observed;
189
+ teardowns.push(() => {
190
+ observed();
191
+ collector = undefined;
192
+ });
193
+ }
194
+
195
+ if (options.renders !== false) {
196
+ let commits: PerfCommit[] = [];
197
+ let skipped = 0;
198
+ let timer: ReturnType<typeof setTimeout> | undefined;
199
+ const flush = () => {
200
+ timer = undefined;
201
+ if (!isConnected()) {
202
+ if (commits.length > 0) timer = setTimeout(flush, BATCH_MS);
203
+ return;
204
+ }
205
+ const batch = commits.splice(0).sort((a, b) => b.duration - a.duration);
206
+ skipped += Math.max(0, batch.length - COMMITS_PER_BATCH);
207
+ const sent = batch.slice(0, COMMITS_PER_BATCH).sort((a, b) => a.start - b.start);
208
+ if (sent.length > 0) context.emit('perf.render', skipped > 0 ? { commits: sent, skipped } : { commits: sent });
209
+ skipped = 0;
210
+ };
211
+ const stop = watchRenders(
212
+ (commit) => {
213
+ commits.push(commit);
214
+ if (commits.length > COMMITS_WAITING) {
215
+ skipped += commits.length - COMMITS_WAITING;
216
+ commits = commits.slice(-COMMITS_WAITING);
217
+ }
218
+ timer ??= setTimeout(flush, BATCH_MS);
219
+ },
220
+ (react) => {
221
+ const notes = (env.notes ?? []).filter((note) => !note.startsWith('React reports render times'));
222
+ if (react.note) notes.push(react.note);
223
+ announce({ react: { version: react.version, profiling: react.profiling }, notes: notes.length > 0 ? notes : undefined });
224
+ },
225
+ (error) => {
226
+ const note = `Stopped timing React renders: ${error instanceof Error ? error.message : String(error)}`;
227
+ context.console.warn(`[capybara] ${note}`);
228
+ announce({ notes: [...(env.notes ?? []), note] });
229
+ },
230
+ );
231
+ teardowns.push(() => {
232
+ stop();
233
+ if (timer !== undefined) clearTimeout(timer);
234
+ });
235
+ }
236
+
237
+ return () => {
238
+ for (const teardown of teardowns) teardown();
239
+ ctx = undefined;
240
+ };
241
+ },
242
+ };
243
+ }