@holdyapp/sdk 1.1.0 → 1.6.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 (50) hide show
  1. package/README.md +53 -1
  2. package/dist/arm.d.ts +5 -0
  3. package/dist/arm.d.ts.map +1 -0
  4. package/dist/changes.d.ts +42 -0
  5. package/dist/changes.d.ts.map +1 -0
  6. package/dist/core.d.ts +17 -6
  7. package/dist/core.d.ts.map +1 -1
  8. package/dist/friction.d.ts +91 -0
  9. package/dist/friction.d.ts.map +1 -0
  10. package/dist/holdy.js +6 -1
  11. package/dist/holdy.js.map +4 -4
  12. package/dist/index.cjs +871 -26
  13. package/dist/index.cjs.map +4 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.mjs +871 -26
  17. package/dist/index.mjs.map +4 -4
  18. package/dist/run.d.ts +37 -0
  19. package/dist/run.d.ts.map +1 -0
  20. package/dist/server.cjs +127 -23
  21. package/dist/server.cjs.map +3 -3
  22. package/dist/server.d.ts +14 -0
  23. package/dist/server.d.ts.map +1 -1
  24. package/dist/server.mjs +124 -22
  25. package/dist/server.mjs.map +3 -3
  26. package/dist/skeleton.d.ts +50 -0
  27. package/dist/skeleton.d.ts.map +1 -0
  28. package/dist/types.d.ts +2 -0
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/web.d.ts +26 -0
  31. package/dist/web.d.ts.map +1 -1
  32. package/dist/web.mjs +824 -26
  33. package/dist/web.mjs.map +4 -4
  34. package/package.json +1 -1
  35. package/src/arm.test.ts +47 -0
  36. package/src/arm.ts +25 -0
  37. package/src/changes.test.ts +54 -0
  38. package/src/changes.ts +357 -0
  39. package/src/core.test.ts +78 -4
  40. package/src/core.ts +95 -31
  41. package/src/friction.test.ts +223 -0
  42. package/src/friction.ts +419 -0
  43. package/src/index.ts +1 -0
  44. package/src/run.test.ts +47 -0
  45. package/src/run.ts +80 -0
  46. package/src/server.ts +17 -0
  47. package/src/skeleton.test.ts +60 -0
  48. package/src/skeleton.ts +173 -0
  49. package/src/types.ts +2 -0
  50. package/src/web.ts +71 -1
package/dist/index.mjs CHANGED
@@ -4,6 +4,7 @@ var DEFAULT_FLUSH_AT = 20;
4
4
  var DEFAULT_FLUSH_INTERVAL_MS = 5e3;
5
5
  var MAX_QUEUE = 1e3;
6
6
  var BULK_LIMIT = 500;
7
+ var MAX_BACKOFF_MS = 6e4;
7
8
  var HoldyCore = class {
8
9
  apiKey;
9
10
  baseUrl;
@@ -13,6 +14,9 @@ var HoldyCore = class {
13
14
  queue = [];
14
15
  timer = null;
15
16
  flushing = null;
17
+ retryAt = 0;
18
+ failures = 0;
19
+ warned = /* @__PURE__ */ new Set();
16
20
  userId = null;
17
21
  anonymousId = null;
18
22
  accountKey = null;
@@ -46,13 +50,14 @@ var HoldyCore = class {
46
50
  event: name,
47
51
  occurred_at: occurredAt,
48
52
  source: this.source,
53
+ external_id: newEventId(),
49
54
  ...userId ? { user_id: userId } : {},
50
55
  ...this.anonymousId ? { anonymous_id: this.anonymousId } : {},
51
56
  properties: properties ?? {},
52
57
  ...Object.keys(context).length > 0 ? { context } : {}
53
58
  };
54
59
  this.queue.push(event);
55
- if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
60
+ this.trimQueue();
56
61
  if (this.queue.length >= this.flushAt) void this.flush();
57
62
  }
58
63
  identify(userId, traits) {
@@ -65,14 +70,9 @@ var HoldyCore = class {
65
70
  this.accountKey = accountKey;
66
71
  this.track("$group", traits ?? {});
67
72
  }
68
- /** Drena a fila. Nunca lança — falha re-enfileira e loga em debug. */
73
+ /** Drena a fila. Nunca lança — falha re-enfileira e espera antes de tentar de novo. */
69
74
  async flush() {
70
- if (this.flushing) return this.flushing;
71
- if (this.queue.length === 0) return;
72
- this.flushing = this.drain().finally(() => {
73
- this.flushing = null;
74
- });
75
- return this.flushing;
75
+ return this.startFlush(false);
76
76
  }
77
77
  /** Flush final + para o timer. Chamar em shutdown do server / unload do web. */
78
78
  async shutdown() {
@@ -80,17 +80,42 @@ var HoldyCore = class {
80
80
  clearInterval(this.timer);
81
81
  this.timer = null;
82
82
  }
83
- await this.flush();
83
+ await this.startFlush(true);
84
+ }
85
+ startFlush(force) {
86
+ if (this.flushing) return this.flushing;
87
+ if (this.queue.length === 0) return Promise.resolve();
88
+ if (!force && Date.now() < this.retryAt) return Promise.resolve();
89
+ this.flushing = this.drain().finally(() => {
90
+ this.flushing = null;
91
+ });
92
+ return this.flushing;
84
93
  }
85
94
  async drain() {
86
95
  while (this.queue.length > 0) {
87
96
  const batch = this.queue.splice(0, BULK_LIMIT);
88
- const ok = await this.send(batch);
89
- if (!ok) {
97
+ const outcome = await this.send(batch);
98
+ if (outcome.kind === "retry") {
90
99
  this.queue.unshift(...batch);
100
+ this.trimQueue();
101
+ this.scheduleRetry(outcome.afterMs);
91
102
  return;
92
103
  }
104
+ this.failures = 0;
105
+ this.retryAt = 0;
106
+ }
107
+ }
108
+ scheduleRetry(afterMs) {
109
+ this.failures += 1;
110
+ if (afterMs !== null) {
111
+ this.retryAt = Date.now() + afterMs;
112
+ return;
93
113
  }
114
+ const backoff = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.failures - 1));
115
+ this.retryAt = Date.now() + backoff + Math.floor(Math.random() * backoff * 0.2);
116
+ }
117
+ trimQueue() {
118
+ if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
94
119
  }
95
120
  async send(events) {
96
121
  try {
@@ -103,23 +128,38 @@ var HoldyCore = class {
103
128
  body: JSON.stringify({ events }),
104
129
  ...this.source === "sdk_web" ? { keepalive: true } : {}
105
130
  });
106
- if (!res.ok) {
107
- if (res.status >= 400 && res.status < 500) {
108
- this.log(`bulk rejected ${res.status} \xB7 batch dropped`);
109
- return true;
110
- }
111
- this.log(`bulk failed ${res.status} \xB7 will retry`);
112
- return false;
131
+ if (res.ok) return { kind: "sent" };
132
+ if (res.status === 429) {
133
+ this.log("rate limited \xB7 will retry after Retry-After");
134
+ return { kind: "retry", afterMs: retryAfterMs(res) };
113
135
  }
114
- return true;
136
+ if (res.status >= 500) {
137
+ this.log(`bulk failed ${res.status} \xB7 will retry with backoff`);
138
+ return { kind: "retry", afterMs: null };
139
+ }
140
+ if (res.status === 401) {
141
+ this.warnOnce("401", "API key inv\xE1lida ou revogada \xB7 eventos descartados. Confira a chave em Configura\xE7\xF5es \u203A SDK.");
142
+ return { kind: "dropped" };
143
+ }
144
+ if (res.status === 403) {
145
+ this.warnOnce("403", "Origem n\xE3o permitida ou chave sem escopo events:write \xB7 eventos descartados.");
146
+ return { kind: "dropped" };
147
+ }
148
+ this.log(`bulk rejected ${res.status} \xB7 batch dropped`);
149
+ return { kind: "dropped" };
115
150
  } catch (err) {
116
- this.log(`bulk network error: ${err.message} \xB7 will retry`);
117
- return false;
151
+ this.log(`bulk network error: ${err.message} \xB7 will retry with backoff`);
152
+ return { kind: "retry", afterMs: null };
118
153
  }
119
154
  }
120
155
  log(msg) {
121
156
  if (this.debug) console.warn(`[holdy] ${msg}`);
122
157
  }
158
+ warnOnce(key, msg) {
159
+ if (this.warned.has(key)) return;
160
+ this.warned.add(key);
161
+ console.warn(`[holdy] ${msg}`);
162
+ }
123
163
  /**
124
164
  * Ambiente que o SDK observa sozinho (url, referrer, browser, utm…).
125
165
  * Vazio no core; `HoldyWeb` preenche. O server não infere ambiente — não
@@ -133,12 +173,72 @@ var HoldyCore = class {
133
173
  return this.queue.length;
134
174
  }
135
175
  };
176
+ function retryAfterMs(res) {
177
+ const raw = typeof res.headers?.get === "function" ? res.headers.get("Retry-After") : null;
178
+ if (!raw) return null;
179
+ const seconds = Number(raw);
180
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
181
+ return Math.min(MAX_BACKOFF_MS, seconds * 1e3);
182
+ }
183
+ function newEventId() {
184
+ const c = globalThis.crypto;
185
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
186
+ const rand = () => Math.random().toString(36).slice(2, 12);
187
+ return `${Date.now().toString(36)}-${rand()}-${rand()}`;
188
+ }
189
+
190
+ // src/run.ts
191
+ function newRunId() {
192
+ const c = globalThis.crypto;
193
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
194
+ return `run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
195
+ }
196
+ function runEventName(name, suffix) {
197
+ const base = name.trim().replace(/\.$/, "");
198
+ return `${base || "run"}.${suffix}`;
199
+ }
200
+ async function withRun(track, opts, fn) {
201
+ if (!opts || !opts.name) throw new Error("[holdy] run: name is required");
202
+ const id = opts.runId && opts.runId.length > 0 ? opts.runId : newRunId();
203
+ const base = { ...opts.properties ?? {}, ai_run_id: id };
204
+ const overrides = {
205
+ ...opts.accountKey ? { accountKey: opts.accountKey } : {},
206
+ ...opts.userId ? { userId: opts.userId } : {}
207
+ };
208
+ const emit = (event, properties) => track(event, { ...base, ...properties ?? {}, ai_run_id: id }, overrides);
209
+ const startedAt = Date.now();
210
+ emit(runEventName(opts.name, "started"));
211
+ try {
212
+ const result = await fn({ id, track: emit });
213
+ emit(runEventName(opts.name, "completed"), { duration_ms: Date.now() - startedAt });
214
+ return result;
215
+ } catch (err) {
216
+ emit(runEventName(opts.name, "failed"), {
217
+ duration_ms: Date.now() - startedAt,
218
+ error: err instanceof Error ? err.name : "Error"
219
+ });
220
+ throw err;
221
+ }
222
+ }
136
223
 
137
224
  // src/server.ts
138
225
  var Holdy = class extends HoldyCore {
139
226
  constructor(opts) {
140
227
  super("sdk_server", opts);
141
228
  }
229
+ /**
230
+ * Executa `fn` como UMA execução de agente: todo evento lá dentro carrega a
231
+ * mesma `ai_run_id`, e `<name>.started` / `.completed` / `.failed` saem
232
+ * sozinhos.
233
+ *
234
+ * await holdy.run({ name: 'support_agent', accountKey: 'acme' }, async (run) => {
235
+ * run.track('ticket_drafted', { ai_tokens: 1200, ai_cost_usd: 0.02 })
236
+ * return resolveTicket(ticket)
237
+ * })
238
+ */
239
+ run(opts, fn) {
240
+ return withRun((name, properties, overrides) => this.track(name, properties, overrides), opts, fn);
241
+ }
142
242
  };
143
243
 
144
244
  // src/auto-capture.ts
@@ -204,6 +304,415 @@ function currentPath() {
204
304
  return `${location.pathname}${location.search}${location.hash}`;
205
305
  }
206
306
 
307
+ // src/friction.ts
308
+ var INSTALLED_FLAG2 = "__holdy_friction__";
309
+ var INTERACTIVE_SELECTOR = 'button, a, input, select, textarea, summary, [role="button"], [role="link"], [role="menuitem"], [role="tab"]';
310
+ var INTERACTIVE_TAGS = /* @__PURE__ */ new Set(["button", "a", "input", "select", "textarea", "summary"]);
311
+ var FORM_CONTROL_TAGS = /* @__PURE__ */ new Set(["input", "select", "textarea"]);
312
+ var RageClickDetector = class {
313
+ constructor(threshold = 3, windowMs = 1e3, radiusPx = 30) {
314
+ this.threshold = threshold;
315
+ this.windowMs = windowMs;
316
+ this.radiusPx = radiusPx;
317
+ }
318
+ clicks = [];
319
+ push(x, y, t) {
320
+ this.clicks = this.clicks.filter(
321
+ (c) => t - c.t <= this.windowMs && Math.hypot(c.x - x, c.y - y) <= this.radiusPx
322
+ );
323
+ this.clicks.push({ x, y, t });
324
+ if (this.clicks.length >= this.threshold) {
325
+ this.clicks = [];
326
+ return true;
327
+ }
328
+ return false;
329
+ }
330
+ };
331
+ var NavLoopDetector = class {
332
+ constructor(windowMs = 6e4) {
333
+ this.windowMs = windowMs;
334
+ }
335
+ visits = [];
336
+ push(path, t) {
337
+ this.visits = [...this.visits, { path, t }].filter((v) => t - v.t <= this.windowMs).slice(-4);
338
+ if (this.visits.length < 4) return null;
339
+ const [a, b, c, d] = this.visits.map((v) => v.path);
340
+ if (a === c && b === d && a !== b) {
341
+ this.visits = [];
342
+ return { from: a, to: b };
343
+ }
344
+ return null;
345
+ }
346
+ };
347
+ function resolveInteractive(el) {
348
+ if (!el) return null;
349
+ const viaClosest = el.closest?.(INTERACTIVE_SELECTOR) ?? null;
350
+ if (viaClosest) return viaClosest;
351
+ const tag = el.tagName.toLowerCase();
352
+ if (INTERACTIVE_TAGS.has(tag)) return el;
353
+ const role = el.getAttribute("role");
354
+ if (role === "button" || role === "link" || role === "menuitem" || role === "tab") return el;
355
+ return null;
356
+ }
357
+ function isDeadClickTarget(el) {
358
+ const target = resolveInteractive(el);
359
+ if (!target) return false;
360
+ if (target.disabled === true) return true;
361
+ if (target.getAttribute("disabled") !== null) return true;
362
+ if (target.getAttribute("aria-disabled") === "true") return true;
363
+ const tag = target.tagName.toLowerCase();
364
+ if (tag === "a") {
365
+ const href = target.getAttribute("href");
366
+ if (!href || href === "#" || href.startsWith("javascript:")) return true;
367
+ }
368
+ return false;
369
+ }
370
+ function describeElement(el) {
371
+ const target = resolveInteractive(el) ?? el;
372
+ if (!target) return {};
373
+ const out = { element: target.tagName.toLowerCase() };
374
+ if (target.id) out.element_id = target.id;
375
+ const role = target.getAttribute("role");
376
+ if (role) out.element_role = role;
377
+ const label = target.getAttribute("aria-label") ?? target.textContent ?? "";
378
+ const text = label.replace(/\s+/g, " ").trim().slice(0, 60);
379
+ if (text) out.element_text = text;
380
+ const name = target.getAttribute("name") ?? target.getAttribute("data-testid");
381
+ if (name) out.element_name = name;
382
+ return out;
383
+ }
384
+ function stripRequestUrl(input, base) {
385
+ try {
386
+ const url = new URL(input, base);
387
+ return `${url.origin}${url.pathname}`;
388
+ } catch {
389
+ return input.split("?")[0].split("#")[0];
390
+ }
391
+ }
392
+ function errorMessage(reason) {
393
+ if (reason instanceof Error) return reason.message;
394
+ if (typeof reason === "string") return reason;
395
+ try {
396
+ return JSON.stringify(reason);
397
+ } catch {
398
+ return String(reason);
399
+ }
400
+ }
401
+ function isAbortError(err) {
402
+ return typeof err === "object" && err !== null && err.name === "AbortError";
403
+ }
404
+ function isIgnoredUrl(url, ignore) {
405
+ return ignore.some((prefix) => prefix.length > 0 && url.startsWith(prefix));
406
+ }
407
+ function registrableDomain(host) {
408
+ const labels = host.toLowerCase().split(".").filter(Boolean);
409
+ if (labels.length <= 2) return labels.join(".");
410
+ return labels.slice(-2).join(".");
411
+ }
412
+ function isFirstPartyRequest(url, pageUrl, extraOrigins = []) {
413
+ let target;
414
+ let page;
415
+ try {
416
+ target = new URL(url, pageUrl);
417
+ page = new URL(pageUrl);
418
+ } catch {
419
+ return true;
420
+ }
421
+ if (target.protocol !== "http:" && target.protocol !== "https:") return true;
422
+ if (target.host === page.host) return true;
423
+ if (extraOrigins.some((o) => o.length > 0 && target.origin === o)) return true;
424
+ const targetDomain = registrableDomain(target.hostname);
425
+ return targetDomain.length > 0 && targetDomain === registrableDomain(page.hostname);
426
+ }
427
+ function classifyRequest(outcome) {
428
+ if (outcome.aborted) return null;
429
+ if (!outcome.opaque && (outcome.status === null || outcome.status >= 400)) return "http_error";
430
+ return outcome.durationMs >= outcome.slowMs ? "slow_request" : null;
431
+ }
432
+ function documentStatus(perf) {
433
+ try {
434
+ const entry = perf?.getEntriesByType?.("navigation")?.[0];
435
+ const status = entry?.responseStatus;
436
+ return typeof status === "number" && status > 0 ? status : null;
437
+ } catch {
438
+ return null;
439
+ }
440
+ }
441
+ function formKey(form) {
442
+ return form.id || form.getAttribute("name") || form.getAttribute("data-testid") || stripRequestUrl(form.getAttribute("action") ?? "", location.href).replace(location.origin, "") || "form";
443
+ }
444
+ function currentPath2() {
445
+ return typeof location === "undefined" ? "/" : location.pathname || "/";
446
+ }
447
+ function installFrictionCapture(opts) {
448
+ const noop = { onNavigate: () => void 0, teardown: () => void 0 };
449
+ if (typeof window === "undefined" || typeof document === "undefined") return noop;
450
+ const w = window;
451
+ if (w[INSTALLED_FLAG2]) return noop;
452
+ w[INSTALLED_FLAG2] = true;
453
+ const emit = (kind, properties) => {
454
+ try {
455
+ opts.onFriction({ kind, properties: { path: currentPath2(), ...properties } });
456
+ } catch {
457
+ return;
458
+ }
459
+ };
460
+ const cleanups = [];
461
+ const rage = new RageClickDetector(opts.rageClicks, opts.rageWindowMs, opts.rageRadiusPx);
462
+ const navLoop = new NavLoopDetector(opts.navLoopWindowMs);
463
+ const slowMs = opts.slowRequestMs ?? 3e3;
464
+ const touched = /* @__PURE__ */ new Map();
465
+ const onClick = (ev) => {
466
+ const el = ev.target instanceof Element ? ev.target : null;
467
+ if (isDeadClickTarget(el)) emit("dead_click", describeElement(el));
468
+ if (rage.push(ev.clientX, ev.clientY, ev.timeStamp || Date.now())) {
469
+ emit("rage_click", describeElement(el));
470
+ }
471
+ };
472
+ document.addEventListener("click", onClick, true);
473
+ cleanups.push(() => document.removeEventListener("click", onClick, true));
474
+ const onError = (ev) => {
475
+ emit("js_error", {
476
+ message: String(ev.message ?? "").slice(0, 200),
477
+ ...ev.filename ? { source: stripRequestUrl(ev.filename, location.href) } : {},
478
+ ...ev.lineno ? { line: ev.lineno } : {}
479
+ });
480
+ };
481
+ window.addEventListener("error", onError);
482
+ cleanups.push(() => window.removeEventListener("error", onError));
483
+ const onRejection = (ev) => {
484
+ emit("js_error", { message: errorMessage(ev.reason).slice(0, 200), unhandled_rejection: true });
485
+ };
486
+ window.addEventListener("unhandledrejection", onRejection);
487
+ cleanups.push(() => window.removeEventListener("unhandledrejection", onRejection));
488
+ const ignore = (opts.ignoreUrls ?? []).map((url) => stripRequestUrl(url, location.href));
489
+ const apiOrigins = (opts.apiOrigins ?? []).map((o) => {
490
+ try {
491
+ return new URL(o, location.href).origin;
492
+ } catch {
493
+ return "";
494
+ }
495
+ });
496
+ const reportRequest = (url, method, started, status, flags = {}) => {
497
+ const target = stripRequestUrl(url, location.href);
498
+ if (isIgnoredUrl(target, ignore)) return;
499
+ if (!isFirstPartyRequest(target, location.href, apiOrigins)) return;
500
+ const durationMs = performance.now() - started;
501
+ const kind = classifyRequest({ status, durationMs, slowMs, ...flags });
502
+ if (!kind) return;
503
+ emit(kind, {
504
+ url: target,
505
+ method,
506
+ duration_ms: Math.round(durationMs),
507
+ ...flags.opaque ? {} : status !== null ? { status } : { failed: true }
508
+ });
509
+ };
510
+ const originalFetch = window.fetch;
511
+ if (typeof originalFetch === "function") {
512
+ const patched = async (input, init) => {
513
+ const started = performance.now();
514
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
515
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
516
+ try {
517
+ const res = await originalFetch(input, init);
518
+ reportRequest(url, method, started, res.status, {
519
+ opaque: res.type === "opaque" || res.type === "opaqueredirect"
520
+ });
521
+ return res;
522
+ } catch (err) {
523
+ reportRequest(url, method, started, null, { aborted: isAbortError(err) });
524
+ throw err;
525
+ }
526
+ };
527
+ window.fetch = patched;
528
+ cleanups.push(() => {
529
+ window.fetch = originalFetch;
530
+ });
531
+ }
532
+ const xhrProto = typeof XMLHttpRequest === "function" ? XMLHttpRequest.prototype : null;
533
+ if (xhrProto) {
534
+ const originalOpen = xhrProto.open;
535
+ const originalSend = xhrProto.send;
536
+ const requests = /* @__PURE__ */ new WeakMap();
537
+ xhrProto.open = function(method, url, ...rest) {
538
+ requests.set(this, { method: String(method).toUpperCase(), url: String(url) });
539
+ return originalOpen.apply(this, [method, url, ...rest]);
540
+ };
541
+ xhrProto.send = function(body) {
542
+ const request = requests.get(this);
543
+ if (request) {
544
+ const started = performance.now();
545
+ let aborted = false;
546
+ this.addEventListener("abort", () => {
547
+ aborted = true;
548
+ });
549
+ this.addEventListener("loadend", () => {
550
+ reportRequest(request.url, request.method, started, this.status === 0 ? null : this.status, { aborted });
551
+ });
552
+ }
553
+ return originalSend.call(this, body);
554
+ };
555
+ cleanups.push(() => {
556
+ xhrProto.open = originalOpen;
557
+ xhrProto.send = originalSend;
558
+ });
559
+ }
560
+ const loadStatus = documentStatus(typeof performance === "undefined" ? void 0 : performance);
561
+ if (loadStatus !== null && loadStatus >= 400) {
562
+ emit("http_error", { document: true, status: loadStatus, url: stripRequestUrl(location.href) });
563
+ }
564
+ const onFocusIn = (ev) => {
565
+ const el = ev.target;
566
+ if (!el || !FORM_CONTROL_TAGS.has(el.tagName.toLowerCase())) return;
567
+ const form = el.form;
568
+ if (!form) return;
569
+ const entry = touched.get(form) ?? { form: formKey(form), fields: /* @__PURE__ */ new Set() };
570
+ const field = el.name || el.id || el.tagName.toLowerCase();
571
+ entry.fields.add(field);
572
+ touched.set(form, entry);
573
+ };
574
+ document.addEventListener("focusin", onFocusIn, true);
575
+ cleanups.push(() => document.removeEventListener("focusin", onFocusIn, true));
576
+ const onSubmit = (ev) => {
577
+ if (ev.target instanceof HTMLFormElement) touched.delete(ev.target);
578
+ };
579
+ document.addEventListener("submit", onSubmit, true);
580
+ cleanups.push(() => document.removeEventListener("submit", onSubmit, true));
581
+ const flushAbandons = () => {
582
+ for (const entry of touched.values()) {
583
+ emit("form_abandon", { form: entry.form, fields_touched: entry.fields.size });
584
+ }
585
+ touched.clear();
586
+ };
587
+ window.addEventListener("pagehide", flushAbandons);
588
+ cleanups.push(() => window.removeEventListener("pagehide", flushAbandons));
589
+ return {
590
+ onNavigate: (path) => {
591
+ flushAbandons();
592
+ const loop = navLoop.push(path, Date.now());
593
+ if (loop) emit("nav_loop", { from: loop.from, to: loop.to });
594
+ },
595
+ teardown: () => {
596
+ for (const cleanup of cleanups) cleanup();
597
+ touched.clear();
598
+ w[INSTALLED_FLAG2] = false;
599
+ }
600
+ };
601
+ }
602
+
603
+ // src/skeleton.ts
604
+ var SKELETON_SELECTOR = 'a[href], button, input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [role="switch"], [data-testid]';
605
+ var SKELETON_MAX_ELEMENTS = 80;
606
+ var SKELETON_DELAY_MS = 1500;
607
+ var SENT_STORAGE_KEY = "holdy_skeletons";
608
+ var SENT_STORAGE_MAX = 200;
609
+ function fnv1a(input) {
610
+ let hash = 2166136261;
611
+ for (let i = 0; i < input.length; i++) {
612
+ hash ^= input.charCodeAt(i);
613
+ hash = Math.imul(hash, 16777619) >>> 0;
614
+ }
615
+ return hash.toString(16).padStart(8, "0");
616
+ }
617
+ function attr(el, name, max) {
618
+ const value = el.getAttribute(name);
619
+ if (!value) return void 0;
620
+ const trimmed = value.replace(/\s+/g, " ").trim().slice(0, max);
621
+ return trimmed || void 0;
622
+ }
623
+ function isVisible(el) {
624
+ if (!el.getBoundingClientRect) return true;
625
+ const rect = el.getBoundingClientRect();
626
+ return rect.width > 0 && rect.height > 0;
627
+ }
628
+ function relativeBox(rect, viewport) {
629
+ const pct = (value, base) => base > 0 ? Math.max(0, Math.min(100, Math.round(value / base * 100))) : 0;
630
+ return [pct(rect.x, viewport.width), pct(rect.y + viewport.scrollY, viewport.height), pct(rect.width, viewport.width), pct(rect.height, viewport.height)];
631
+ }
632
+ function describeSkeletonElement(el, viewport) {
633
+ const out = { t: el.tagName.toLowerCase() };
634
+ const role = attr(el, "role", 40);
635
+ if (role) out.r = role;
636
+ const testid = attr(el, "data-testid", 80);
637
+ if (testid) out.id = testid;
638
+ const name = attr(el, "name", 80);
639
+ if (name) out.n = name;
640
+ const label = attr(el, "aria-label", 80);
641
+ if (label) out.l = label;
642
+ if (out.t === "input" || out.t === "button") {
643
+ const type = attr(el, "type", 20);
644
+ if (type) out.k = type.toLowerCase();
645
+ }
646
+ if (viewport && el.getBoundingClientRect) out.b = relativeBox(el.getBoundingClientRect(), viewport);
647
+ return out;
648
+ }
649
+ function collectSkeleton(root, path, viewport) {
650
+ const found = root.querySelectorAll(SKELETON_SELECTOR);
651
+ const visible = [];
652
+ for (let i = 0; i < found.length; i++) {
653
+ const el = found[i];
654
+ if (el.tagName.toLowerCase() === "input" && (el.getAttribute("type") ?? "").toLowerCase() === "hidden") continue;
655
+ if (!isVisible(el)) continue;
656
+ visible.push(el);
657
+ }
658
+ const elements = visible.slice(0, SKELETON_MAX_ELEMENTS).map((el) => describeSkeletonElement(el, viewport));
659
+ const structural = elements.map(({ b: _b, ...rest }) => rest);
660
+ return { path, hash: fnv1a(JSON.stringify(structural)), count: visible.length, elements };
661
+ }
662
+ function loadSent() {
663
+ try {
664
+ const raw = sessionStorage.getItem(SENT_STORAGE_KEY);
665
+ const list = raw ? JSON.parse(raw) : [];
666
+ return new Set(Array.isArray(list) ? list.filter((x) => typeof x === "string") : []);
667
+ } catch {
668
+ return /* @__PURE__ */ new Set();
669
+ }
670
+ }
671
+ function saveSent(sent) {
672
+ try {
673
+ sessionStorage.setItem(SENT_STORAGE_KEY, JSON.stringify([...sent].slice(-SENT_STORAGE_MAX)));
674
+ } catch {
675
+ return;
676
+ }
677
+ }
678
+ function installSkeletonCapture(opts) {
679
+ if (typeof window === "undefined" || typeof document === "undefined") {
680
+ return { onNavigate: () => void 0, teardown: () => void 0 };
681
+ }
682
+ const delay = opts.delayMs ?? SKELETON_DELAY_MS;
683
+ const sent = loadSent();
684
+ let pending = null;
685
+ const capture = (path) => {
686
+ pending = null;
687
+ if (location.pathname !== path) return;
688
+ try {
689
+ const viewport = {
690
+ width: window.innerWidth,
691
+ height: Math.max(document.documentElement.scrollHeight, window.innerHeight),
692
+ scrollY: window.scrollY
693
+ };
694
+ const skeleton = collectSkeleton(document, path, viewport);
695
+ const key = `${path}:${skeleton.hash}`;
696
+ if (sent.has(key)) return;
697
+ sent.add(key);
698
+ saveSent(sent);
699
+ opts.onSkeleton(skeleton);
700
+ } catch {
701
+ return;
702
+ }
703
+ };
704
+ return {
705
+ onNavigate: (path) => {
706
+ if (pending) clearTimeout(pending);
707
+ pending = setTimeout(() => capture(path), delay);
708
+ },
709
+ teardown: () => {
710
+ if (pending) clearTimeout(pending);
711
+ pending = null;
712
+ }
713
+ };
714
+ }
715
+
207
716
  // src/web-context.ts
208
717
  var UTM_KEYS = [
209
718
  "utm_source",
@@ -246,17 +755,17 @@ function parseUserAgent(ua) {
246
755
  device
247
756
  };
248
757
  }
249
- function readStorage(storage, key) {
758
+ function readStorage(storage2, key) {
250
759
  try {
251
- const s = storage === "session" ? sessionStorage : localStorage;
760
+ const s = storage2 === "session" ? sessionStorage : localStorage;
252
761
  return s.getItem(key);
253
762
  } catch {
254
763
  return null;
255
764
  }
256
765
  }
257
- function writeStorage(storage, key, value) {
766
+ function writeStorage(storage2, key, value) {
258
767
  try {
259
- const s = storage === "session" ? sessionStorage : localStorage;
768
+ const s = storage2 === "session" ? sessionStorage : localStorage;
260
769
  s.setItem(key, value);
261
770
  } catch {
262
771
  }
@@ -321,10 +830,307 @@ function buildWebContext() {
321
830
  };
322
831
  }
323
832
 
833
+ // src/arm.ts
834
+ function fnv1a2(input) {
835
+ let hash = 2166136261;
836
+ for (let i = 0; i < input.length; i++) {
837
+ hash ^= input.charCodeAt(i);
838
+ hash = Math.imul(hash, 16777619) >>> 0;
839
+ }
840
+ return hash >>> 0;
841
+ }
842
+ function changeBucket(changeId, accountKey) {
843
+ return fnv1a2(`${changeId}:${accountKey}`) % 100;
844
+ }
845
+ function changeArm(changeId, accountKey, holdoutPct) {
846
+ return changeBucket(changeId, accountKey) < holdoutPct ? "holdout" : "change";
847
+ }
848
+ function matchesPathTemplate(template, path) {
849
+ const t = template.split(/[?#]/)[0].split("/").filter(Boolean);
850
+ const p = path.split(/[?#]/)[0].split("/").filter(Boolean);
851
+ if (t.length !== p.length) return false;
852
+ return t.every((segment, i) => segment.startsWith(":") || segment === p[i]);
853
+ }
854
+
855
+ // src/changes.ts
856
+ var REFRESH_MS = 5 * 60 * 1e3;
857
+ var NAV_REFRESH_MS = 60 * 1e3;
858
+ var SCAN_DEBOUNCE_MS = 250;
859
+ var SEEN_KEY = "holdy_changes_seen";
860
+ var DISMISSED_KEY = "holdy_changes_dismissed";
861
+ var TIP_GAP_PX = 8;
862
+ var TIP_CSS = `:host{all:initial}
863
+ .tip{position:fixed;box-sizing:border-box;max-width:280px;padding:10px 12px;border-radius:8px;background:#111;color:#fff;font:13px/1.45 system-ui,-apple-system,sans-serif;box-shadow:0 8px 24px rgba(0,0,0,.18);pointer-events:auto;display:flex;gap:10px;align-items:flex-start}
864
+ .tip p{margin:0;flex:1}
865
+ .tip button{all:unset;cursor:pointer;opacity:.7;font-size:15px;line-height:1}
866
+ .tip button:hover,.tip button:focus-visible{opacity:1}
867
+ @media (prefers-color-scheme:dark){.tip{background:#fff;color:#111}}`;
868
+ function normalizeText(text) {
869
+ return text.replace(/\s+/g, " ").trim();
870
+ }
871
+ function parseChanges(body) {
872
+ const list = body?.changes;
873
+ return Array.isArray(list) ? list.filter(isChange) : [];
874
+ }
875
+ function isAnchor(value) {
876
+ const a = value;
877
+ if (a?.kind === "page") return true;
878
+ return (a?.kind === "selector" || a?.kind === "text") && typeof a.value === "string" && a.value.length > 0;
879
+ }
880
+ function isChange(value) {
881
+ const c = value;
882
+ return typeof c?.id === "string" && (c.kind === "copy" || c.kind === "guidance") && typeof c.path === "string" && isAnchor(c.anchor) && typeof c.content?.text === "string" && typeof c.holdout_pct === "number";
883
+ }
884
+ function changesForPage(changes, path, accountKey) {
885
+ if (!accountKey) return [];
886
+ return changes.filter((c) => matchesPathTemplate(c.path, path)).map((change) => ({ change, arm: changeArm(change.id, accountKey, change.holdout_pct) }));
887
+ }
888
+ function storage(kind) {
889
+ try {
890
+ return kind === "local" ? window.localStorage : window.sessionStorage;
891
+ } catch {
892
+ return void 0;
893
+ }
894
+ }
895
+ function readSet(store, key) {
896
+ try {
897
+ return new Set(JSON.parse(store?.getItem(key) ?? "[]"));
898
+ } catch {
899
+ return /* @__PURE__ */ new Set();
900
+ }
901
+ }
902
+ function addToSet(store, key, value) {
903
+ try {
904
+ const set = readSet(store, key);
905
+ set.add(value);
906
+ store?.setItem(key, JSON.stringify([...set].slice(-200)));
907
+ } catch {
908
+ return;
909
+ }
910
+ }
911
+ function query(selector) {
912
+ try {
913
+ return document.querySelector(selector);
914
+ } catch {
915
+ return null;
916
+ }
917
+ }
918
+ var TEXT_ANCHOR_TAGS = 'button,a,[role="button"],label,summary,h1,h2,h3,h4,li,td,th,p,span,strong';
919
+ var TEXT_ANCHOR_SCAN_LIMIT = 3e3;
920
+ function findByText(value) {
921
+ const wanted = normalizeText(value);
922
+ let best = null;
923
+ let bestLength = Number.POSITIVE_INFINITY;
924
+ const nodes = document.querySelectorAll(TEXT_ANCHOR_TAGS);
925
+ const total = Math.min(nodes.length, TEXT_ANCHOR_SCAN_LIMIT);
926
+ for (let i = 0; i < total; i += 1) {
927
+ const el = nodes[i];
928
+ const raw = el.textContent ?? "";
929
+ if (raw.length >= bestLength || normalizeText(raw) !== wanted) continue;
930
+ best = el;
931
+ bestLength = raw.length;
932
+ }
933
+ return best;
934
+ }
935
+ function findAnchor(anchor) {
936
+ if (anchor.kind === "page") return null;
937
+ return anchor.kind === "selector" ? query(anchor.value) : findByText(anchor.value);
938
+ }
939
+ function findTextNode(el, match) {
940
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
941
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
942
+ if (match(normalizeText(node.textContent ?? ""))) return node;
943
+ }
944
+ return null;
945
+ }
946
+ function installProductChanges(opts) {
947
+ if (typeof window === "undefined" || typeof document === "undefined") {
948
+ return { onNavigate: () => void 0, refresh: async () => void 0, teardown: () => void 0 };
949
+ }
950
+ let changes = [];
951
+ let lastFetch = 0;
952
+ let timer = null;
953
+ let root = null;
954
+ let host = null;
955
+ const copies = /* @__PURE__ */ new Map();
956
+ const tips = /* @__PURE__ */ new Map();
957
+ const log = (message) => {
958
+ if (opts.debug) console.warn(`[holdy] ${message}`);
959
+ };
960
+ const expose = (change, arm) => {
961
+ const key = `${change.id}:${arm}`;
962
+ const session = storage("session");
963
+ if (readSet(session, SEEN_KEY).has(key)) return;
964
+ addToSet(session, SEEN_KEY, key);
965
+ opts.track("$change_exposure", { change_id: change.id, arm, kind: change.kind });
966
+ };
967
+ const eligibleCopyNode = (el, change) => {
968
+ const expected = change.expected_text ? normalizeText(change.expected_text) : null;
969
+ const next = normalizeText(change.content.text);
970
+ return findTextNode(el, (text) => text.length > 0 && (text === next || expected === null || text === expected));
971
+ };
972
+ const applyCopy = (el, change) => {
973
+ const next = normalizeText(change.content.text);
974
+ const current = copies.get(change.id);
975
+ if (current && current.node.isConnected && normalizeText(current.node.textContent ?? "") === next) return true;
976
+ const node = eligibleCopyNode(el, change);
977
+ if (!node) return false;
978
+ const text = node.textContent ?? "";
979
+ if (normalizeText(text) !== next) {
980
+ copies.set(change.id, { node, original: text, next: change.content.text });
981
+ node.textContent = text.replace(text.trim(), change.content.text);
982
+ }
983
+ return true;
984
+ };
985
+ const restoreCopy = (id) => {
986
+ const applied = copies.get(id);
987
+ if (!applied) return;
988
+ if (applied.node.isConnected && normalizeText(applied.node.textContent ?? "") === normalizeText(applied.next)) {
989
+ applied.node.textContent = applied.original;
990
+ }
991
+ copies.delete(id);
992
+ };
993
+ const ensureRoot = () => {
994
+ if (root) return root;
995
+ if (!document.body) return null;
996
+ host = document.createElement("holdy-changes");
997
+ host.setAttribute("data-holdy-root", "1");
998
+ host.style.cssText = "position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;pointer-events:none";
999
+ root = host.attachShadow({ mode: "closed" });
1000
+ const style = document.createElement("style");
1001
+ style.textContent = TIP_CSS;
1002
+ root.appendChild(style);
1003
+ document.body.appendChild(host);
1004
+ return root;
1005
+ };
1006
+ const showTip = (anchor, change) => {
1007
+ if (tips.has(change.id)) return true;
1008
+ if (readSet(storage("local"), DISMISSED_KEY).has(change.id)) return true;
1009
+ const shadow = ensureRoot();
1010
+ if (!shadow) return false;
1011
+ const card = document.createElement("div");
1012
+ card.className = "tip";
1013
+ card.setAttribute("role", "tooltip");
1014
+ const text = document.createElement("p");
1015
+ text.textContent = change.content.text;
1016
+ const close = document.createElement("button");
1017
+ close.type = "button";
1018
+ close.setAttribute("aria-label", "Fechar");
1019
+ close.textContent = "\xD7";
1020
+ card.append(text, close);
1021
+ card.style.top = "-9999px";
1022
+ card.style.left = "-9999px";
1023
+ shadow.appendChild(card);
1024
+ const remove = () => {
1025
+ card.remove();
1026
+ window.removeEventListener("scroll", position, true);
1027
+ window.removeEventListener("resize", position);
1028
+ tips.delete(change.id);
1029
+ };
1030
+ function position() {
1031
+ if (!anchor) {
1032
+ const corner = card.getBoundingClientRect();
1033
+ card.style.top = `${Math.max(8, window.innerHeight - corner.height - 16)}px`;
1034
+ card.style.left = `${Math.max(8, window.innerWidth - corner.width - 16)}px`;
1035
+ return;
1036
+ }
1037
+ if (!anchor.isConnected) {
1038
+ remove();
1039
+ return;
1040
+ }
1041
+ const a = anchor.getBoundingClientRect();
1042
+ const c = card.getBoundingClientRect();
1043
+ let top = a.bottom + TIP_GAP_PX;
1044
+ if (top + c.height > window.innerHeight - 8) top = a.top - c.height - TIP_GAP_PX;
1045
+ const left = Math.min(Math.max(8, a.left + a.width / 2 - c.width / 2), window.innerWidth - c.width - 8);
1046
+ card.style.top = `${Math.max(8, top)}px`;
1047
+ card.style.left = `${Math.max(8, left)}px`;
1048
+ }
1049
+ close.addEventListener("click", () => {
1050
+ addToSet(storage("local"), DISMISSED_KEY, change.id);
1051
+ opts.track("$change_dismissed", { change_id: change.id, kind: change.kind });
1052
+ remove();
1053
+ });
1054
+ tips.set(change.id, remove);
1055
+ requestAnimationFrame(position);
1056
+ window.addEventListener("scroll", position, true);
1057
+ window.addEventListener("resize", position);
1058
+ return true;
1059
+ };
1060
+ const scan = () => {
1061
+ timer = null;
1062
+ const active = changesForPage(changes, location.pathname, opts.getAccountKey());
1063
+ const activeIds = new Set(active.map((a) => a.change.id));
1064
+ for (const id of [...copies.keys()]) if (!activeIds.has(id)) restoreCopy(id);
1065
+ for (const [id, remove] of [...tips]) if (!activeIds.has(id)) remove();
1066
+ for (const { change, arm } of active) {
1067
+ const el = findAnchor(change.anchor);
1068
+ if (!el && change.anchor.kind !== "page") continue;
1069
+ if (change.kind === "copy") {
1070
+ if (!el) continue;
1071
+ const shown = arm === "change" ? applyCopy(el, change) : eligibleCopyNode(el, change) !== null;
1072
+ if (shown) expose(change, arm);
1073
+ } else if (arm === "holdout" || showTip(el, change)) {
1074
+ expose(change, arm);
1075
+ }
1076
+ }
1077
+ };
1078
+ const schedule = () => {
1079
+ if (timer === null) timer = setTimeout(scan, SCAN_DEBOUNCE_MS);
1080
+ };
1081
+ const refresh = async () => {
1082
+ lastFetch = Date.now();
1083
+ try {
1084
+ const res = await fetch(`${opts.baseUrl}/runtime/changes`, {
1085
+ headers: { Authorization: `Bearer ${opts.apiKey}` }
1086
+ });
1087
+ if (!res.ok) {
1088
+ log(`changes ${res.status}`);
1089
+ return;
1090
+ }
1091
+ changes = parseChanges(await res.json());
1092
+ schedule();
1093
+ } catch (err) {
1094
+ log(`changes network error: ${err.message}`);
1095
+ }
1096
+ };
1097
+ const observer = typeof MutationObserver !== "undefined" ? new MutationObserver(() => {
1098
+ if (changes.length > 0 || copies.size > 0 || tips.size > 0) schedule();
1099
+ }) : null;
1100
+ const observe = () => {
1101
+ if (document.body) observer?.observe(document.body, { childList: true, subtree: true, characterData: true });
1102
+ };
1103
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", observe, { once: true });
1104
+ else observe();
1105
+ const interval = setInterval(() => void refresh(), REFRESH_MS);
1106
+ void refresh();
1107
+ return {
1108
+ onNavigate: () => {
1109
+ if (Date.now() - lastFetch > NAV_REFRESH_MS) void refresh();
1110
+ schedule();
1111
+ },
1112
+ refresh,
1113
+ teardown: () => {
1114
+ clearInterval(interval);
1115
+ if (timer !== null) clearTimeout(timer);
1116
+ observer?.disconnect();
1117
+ for (const id of [...copies.keys()]) restoreCopy(id);
1118
+ for (const remove of [...tips.values()]) remove();
1119
+ host?.remove();
1120
+ host = null;
1121
+ root = null;
1122
+ changes = [];
1123
+ }
1124
+ };
1125
+ }
1126
+
324
1127
  // src/web.ts
325
1128
  var ANON_STORAGE_KEY = "holdy_anon_id";
326
1129
  var HoldyWeb = class extends HoldyCore {
327
1130
  teardownAutoCapture = null;
1131
+ friction = null;
1132
+ changes = null;
1133
+ skeleton = null;
328
1134
  constructor(opts) {
329
1135
  super("sdk_web", opts);
330
1136
  this.anonymousId = resolveAnonymousId();
@@ -334,9 +1140,37 @@ var HoldyWeb = class extends HoldyCore {
334
1140
  if (document.visibilityState === "hidden") void this.flush();
335
1141
  });
336
1142
  }
1143
+ if (opts.friction !== false) {
1144
+ const frictionOpts = typeof opts.friction === "object" ? opts.friction : {};
1145
+ this.friction = installFrictionCapture({
1146
+ ...frictionOpts,
1147
+ ignoreUrls: [...frictionOpts.ignoreUrls ?? [], this.baseUrl],
1148
+ onFriction: (signal) => this.track(`$${signal.kind}`, signal.properties)
1149
+ });
1150
+ }
1151
+ if (opts.skeleton !== false) {
1152
+ this.skeleton = installSkeletonCapture({
1153
+ onSkeleton: (skeleton) => this.track("$page_skeleton", { ...skeleton })
1154
+ });
1155
+ }
337
1156
  if (opts.autoCapture !== false) {
338
1157
  this.teardownAutoCapture = installAutoCapture({
339
- onNavigate: (kind) => this.page(void 0, { navigation: kind })
1158
+ onNavigate: (kind) => {
1159
+ this.page(void 0, { navigation: kind });
1160
+ const path = typeof location !== "undefined" ? location.pathname : "/";
1161
+ this.friction?.onNavigate(path);
1162
+ this.changes?.onNavigate();
1163
+ this.skeleton?.onNavigate(path);
1164
+ }
1165
+ });
1166
+ }
1167
+ if (opts.productChanges !== false && typeof window !== "undefined") {
1168
+ this.changes = installProductChanges({
1169
+ baseUrl: this.baseUrl,
1170
+ apiKey: this.apiKey,
1171
+ getAccountKey: () => this.accountKey,
1172
+ track: (name, properties) => this.track(name, properties),
1173
+ debug: opts.debug
340
1174
  });
341
1175
  }
342
1176
  }
@@ -354,6 +1188,10 @@ var HoldyWeb = class extends HoldyCore {
354
1188
  ...typeof document !== "undefined" && document.title ? { title: document.title } : {}
355
1189
  });
356
1190
  }
1191
+ group(accountKey, traits) {
1192
+ super.group(accountKey, traits);
1193
+ this.changes?.onNavigate();
1194
+ }
357
1195
  reset() {
358
1196
  this.userId = null;
359
1197
  this.accountKey = null;
@@ -362,11 +1200,18 @@ var HoldyWeb = class extends HoldyCore {
362
1200
  } catch {
363
1201
  }
364
1202
  this.anonymousId = resolveAnonymousId();
1203
+ this.changes?.onNavigate();
365
1204
  }
366
1205
  /** Flush final + desinstala o auto-capture (devolve `history` ao original). */
367
1206
  async shutdown() {
368
1207
  this.teardownAutoCapture?.();
369
1208
  this.teardownAutoCapture = null;
1209
+ this.friction?.teardown();
1210
+ this.friction = null;
1211
+ this.changes?.teardown();
1212
+ this.changes = null;
1213
+ this.skeleton?.teardown();
1214
+ this.skeleton = null;
370
1215
  await super.shutdown();
371
1216
  }
372
1217
  environmentContext() {