tempo-sdk 0.0.76 → 0.0.79

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 (44) hide show
  1. package/dist/assets/index.js +3 -3
  2. package/dist/astro/asset-preview-client.js +3 -3
  3. package/dist/astro.js +2 -2
  4. package/dist/canvas/astro.js +3 -3
  5. package/dist/canvas/index.js +5 -5
  6. package/dist/canvas/interact-projection.js +4 -4
  7. package/dist/canvas/svelte.js +3 -3
  8. package/dist/canvas/vue.js +3 -3
  9. package/dist/{chunk-R3RYGAPB.js → chunk-4PGZTWKS.js} +2 -2
  10. package/dist/{chunk-GCGRJTTS.js → chunk-54P7S7VU.js} +2 -2
  11. package/dist/{chunk-GCGRJTTS.js.map → chunk-54P7S7VU.js.map} +1 -1
  12. package/dist/{chunk-6AAE4LYV.js → chunk-5M45Z7K6.js} +20 -5
  13. package/dist/{chunk-6AAE4LYV.js.map → chunk-5M45Z7K6.js.map} +1 -1
  14. package/dist/{chunk-5LUQSXSP.js → chunk-BHDCNLCO.js} +2 -2
  15. package/dist/{chunk-5LUQSXSP.js.map → chunk-BHDCNLCO.js.map} +1 -1
  16. package/dist/{chunk-YECMP34I.js → chunk-D3WLLHZU.js} +2 -2
  17. package/dist/{chunk-CXIW4IKC.js → chunk-I5MJ342V.js} +3 -3
  18. package/dist/{chunk-3W4CVWTK.js → chunk-JMG5IDS5.js} +2 -2
  19. package/dist/{chunk-3W4CVWTK.js.map → chunk-JMG5IDS5.js.map} +1 -1
  20. package/dist/{chunk-ZXC7SZIT.js → chunk-QJA366VX.js} +23 -10
  21. package/dist/chunk-QJA366VX.js.map +1 -0
  22. package/dist/{chunk-GKDDNDG3.js → chunk-TFPT6T3K.js} +881 -15
  23. package/dist/chunk-TFPT6T3K.js.map +1 -0
  24. package/dist/{chunk-WBMO4ZYO.js → chunk-XN2K7GED.js} +288 -129
  25. package/dist/chunk-XN2K7GED.js.map +1 -0
  26. package/dist/index.js +2 -2
  27. package/dist/nextjs/plugin.cjs +1 -1
  28. package/dist/nextjs/plugin.cjs.map +1 -1
  29. package/dist/nextjs/plugin.js +1 -1
  30. package/dist/nextjs-loader.cjs +1 -1
  31. package/dist/nextjs-loader.cjs.map +1 -1
  32. package/dist/nextjs.cjs +1 -1
  33. package/dist/nextjs.cjs.map +1 -1
  34. package/dist/nextjs.js +1 -1
  35. package/dist/nuxt/runtime/identity.js +1 -1
  36. package/dist/nuxt.js +1 -1
  37. package/dist/vue.js +1 -1
  38. package/package.json +1 -1
  39. package/dist/chunk-GKDDNDG3.js.map +0 -1
  40. package/dist/chunk-WBMO4ZYO.js.map +0 -1
  41. package/dist/chunk-ZXC7SZIT.js.map +0 -1
  42. /package/dist/{chunk-R3RYGAPB.js.map → chunk-4PGZTWKS.js.map} +0 -0
  43. /package/dist/{chunk-YECMP34I.js.map → chunk-D3WLLHZU.js.map} +0 -0
  44. /package/dist/{chunk-CXIW4IKC.js.map → chunk-I5MJ342V.js.map} +0 -0
@@ -3,9 +3,15 @@ import {
3
3
  readTempoVueInvocationMarker
4
4
  } from "./chunk-SGN7BDRE.js";
5
5
  import {
6
+ beginHeadCapture,
7
+ beginHeadSheet,
6
8
  captureHead,
7
- getHeadTracker
8
- } from "./chunk-WBMO4ZYO.js";
9
+ finishHeadCapture,
10
+ getHeadTracker,
11
+ isDisabledStylesheet,
12
+ resolveUrls,
13
+ shouldIncludeLink
14
+ } from "./chunk-XN2K7GED.js";
9
15
  import {
10
16
  isTempoInteractFrameName
11
17
  } from "./chunk-65B52AR7.js";
@@ -75,7 +81,7 @@ import {
75
81
  watchDom,
76
82
  watchPortal,
77
83
  watchState
78
- } from "./chunk-ZXC7SZIT.js";
84
+ } from "./chunk-QJA366VX.js";
79
85
  import {
80
86
  captureAttributes,
81
87
  captureWithSupplementalRoots,
@@ -89,7 +95,7 @@ import {
89
95
  registerDocumentCaptureProducer,
90
96
  removeScriptTags,
91
97
  resetCaptureFlushCounters
92
- } from "./chunk-6AAE4LYV.js";
98
+ } from "./chunk-5M45Z7K6.js";
93
99
 
94
100
  // ../../modules/iframe-projection/combined/projection-repair-paths.ts
95
101
  function isProjectionRepairPaths(value) {
@@ -98,6 +104,736 @@ function isProjectionRepairPaths(value) {
98
104
  );
99
105
  }
100
106
 
107
+ // ../../modules/rate-limiter/browser-frame-clock.ts
108
+ function browserFrameClock() {
109
+ let next = 0;
110
+ const pending = /* @__PURE__ */ new Map();
111
+ return {
112
+ requestFrame(callback) {
113
+ const id = ++next;
114
+ let timer;
115
+ const document2 = globalThis.document;
116
+ const cleanup = () => {
117
+ cancelAnimationFrame(native);
118
+ clearTimeout(timer);
119
+ document2?.removeEventListener("visibilitychange", visibility);
120
+ pending.delete(id);
121
+ };
122
+ const finish = (time) => {
123
+ cleanup();
124
+ callback(time);
125
+ };
126
+ const visibility = () => {
127
+ clearTimeout(timer);
128
+ timer = document2?.hidden ? setTimeout(() => finish(performance.now()), 1e3 / 60) : void 0;
129
+ };
130
+ const native = requestAnimationFrame(finish);
131
+ pending.set(id, cleanup);
132
+ document2?.addEventListener("visibilitychange", visibility);
133
+ visibility();
134
+ return id;
135
+ },
136
+ cancelFrame(id) {
137
+ pending.get(id)?.();
138
+ }
139
+ };
140
+ }
141
+
142
+ // ../../modules/rate-limiter/work-scheduler.ts
143
+ var browserClock = () => ({
144
+ now: () => performance.now(),
145
+ ...browserFrameClock(),
146
+ task: (callback) => {
147
+ const scheduler = globalThis.scheduler;
148
+ if (scheduler)
149
+ void scheduler.postTask(callback, { priority: "user-visible" });
150
+ else setTimeout(callback, 0);
151
+ },
152
+ requestIdle: typeof requestIdleCallback === "function" ? (callback, options) => requestIdleCallback(callback, options) : void 0,
153
+ cancelIdle: (handle) => globalThis.cancelIdleCallback?.(handle),
154
+ inputPending: () => globalThis.navigator?.scheduling?.isInputPending({ includeContinuous: true }) === true
155
+ });
156
+ function createWorkScheduler(options = {}) {
157
+ const clock = options.clock ?? browserClock();
158
+ const budget = options.budgetMs ?? 2;
159
+ const foregroundBudget = options.foregroundBudgetMs ?? budget;
160
+ const timeout = options.timeoutMs ?? 50;
161
+ const continuationTicks = 32;
162
+ if (!(budget > 0 && Number.isFinite(budget)))
163
+ throw new RangeError("budgetMs must be finite and positive");
164
+ if (!(foregroundBudget > 0 && Number.isFinite(foregroundBudget)))
165
+ throw new RangeError("foregroundBudgetMs must be finite and positive");
166
+ const queues = {
167
+ visible: /* @__PURE__ */ new Set(),
168
+ background: /* @__PURE__ */ new Set(),
169
+ frame: /* @__PURE__ */ new Set(),
170
+ input: /* @__PURE__ */ new Set()
171
+ };
172
+ const interactive = /* @__PURE__ */ new Set();
173
+ const foreground = /* @__PURE__ */ new Set();
174
+ const foregroundListeners = /* @__PURE__ */ new Set();
175
+ let frame = null;
176
+ let idle = null;
177
+ let taskPending = false;
178
+ let disposed = false;
179
+ let draining = false;
180
+ let blockedUntilFrame = false;
181
+ let spent = 0;
182
+ let frameAt = null;
183
+ let interval = 1e3 / 120;
184
+ let sampledInterval = null;
185
+ let slices = 0, overruns = 0, maxSliceMs = 0;
186
+ const count = () => queues.visible.size + queues.background.size + queues.frame.size + queues.input.size;
187
+ const first = (queue) => queue.values().next().value;
188
+ const frameBudget = () => foreground.size ? foregroundBudget : budget;
189
+ const allowance = () => blockedUntilFrame ? 0 : Math.min(
190
+ frameBudget() - spent,
191
+ frameAt === null ? frameBudget() - spent : frameAt + interval - Math.max(2, interval * 0.35) - clock.now()
192
+ );
193
+ const remove = (job) => {
194
+ queues[job.priority].delete(job);
195
+ job.signal?.removeEventListener("abort", job.abort);
196
+ };
197
+ const eligible = (job) => !foreground.size || job.foreground?.() === true;
198
+ const candidate = (queue) => {
199
+ let ordinary;
200
+ for (const job of queue) {
201
+ if (job.foreground?.()) return job;
202
+ if (!ordinary && eligible(job)) ordinary = job;
203
+ }
204
+ return ordinary;
205
+ };
206
+ const choose = (kind) => {
207
+ if (kind === "frame" && interactive.size && queues.input.size)
208
+ return first(queues.input);
209
+ const urgentInput = candidate(queues.input);
210
+ if (urgentInput?.foreground?.()) return urgentInput;
211
+ if (kind === "frame" && queues.input.size) return first(queues.input);
212
+ if (interactive.size) return void 0;
213
+ const candidates = [
214
+ candidate(queues.visible),
215
+ candidate(queues.background),
216
+ ...kind === "frame" ? [candidate(queues.frame)] : []
217
+ ].filter((job) => !!job);
218
+ const urgent = candidates.find((job) => job.foreground?.());
219
+ if (urgent) return urgent;
220
+ return candidates.filter((job) => clock.now() - job.at >= timeout).sort((a, b) => a.at - b.at)[0] ?? (kind === "frame" ? candidate(queues.frame) : void 0) ?? candidate(queues.visible) ?? candidate(queues.background);
221
+ };
222
+ async function pump(kind, deadline) {
223
+ if (disposed || draining) return;
224
+ draining = true;
225
+ const start = clock.now();
226
+ const forced = deadline?.didTimeout === true || [
227
+ first(queues.visible),
228
+ first(queues.background),
229
+ first(queues.frame),
230
+ first(queues.input)
231
+ ].some((job) => job && clock.now() - job.at >= timeout);
232
+ const available = Math.max(0, forced ? frameBudget() - spent : allowance());
233
+ let runningInput = false;
234
+ const hasTime = () => clock.now() - start < Math.min(available, frameBudget() - spent) && (!deadline || deadline.didTimeout || deadline.timeRemaining() > 0) && (runningInput || kind === "frame" && queues.input.size > 0 || forced || !clock.inputPending?.());
235
+ let served = false;
236
+ let active = true;
237
+ const owesStep = () => forced && available > 0 && !served;
238
+ try {
239
+ while (owesStep() || hasTime()) {
240
+ let job = choose(kind);
241
+ for (let tick = 0; served && !job && tick < continuationTicks; tick++) {
242
+ await Promise.resolve();
243
+ job = choose(kind);
244
+ }
245
+ if (!job || !owesStep() && !hasTime()) break;
246
+ remove(job);
247
+ runningInput = job.priority === "input";
248
+ const current = job;
249
+ job.run({
250
+ hasTime,
251
+ canContinue: () => active && eligible(current) && (!interactive.size || current.priority === "input") && hasTime() && choose(kind) === void 0
252
+ });
253
+ runningInput = false;
254
+ served = true;
255
+ }
256
+ } finally {
257
+ active = false;
258
+ const elapsed = clock.now() - start;
259
+ spent += elapsed;
260
+ if (!served && elapsed === 0 && count()) blockedUntilFrame = true;
261
+ slices++;
262
+ maxSliceMs = Math.max(maxSliceMs, elapsed);
263
+ if (elapsed > available + 0.25) overruns++;
264
+ draining = false;
265
+ request();
266
+ }
267
+ }
268
+ function request() {
269
+ if (disposed || draining || !count()) return;
270
+ if (interactive.size && !queues.input.size) return;
271
+ if (foreground.size && !queues.input.size && !Object.values(queues).some((queue) => candidate(queue)))
272
+ return;
273
+ if (frame === null)
274
+ frame = clock.requestFrame((time) => {
275
+ frame = null;
276
+ const delta = frameAt === null ? null : time - frameAt;
277
+ if (delta !== null && delta >= 4 && delta < 250) {
278
+ sampledInterval = Math.min(sampledInterval ?? delta, delta);
279
+ interval = Math.min(1e3 / 60, sampledInterval);
280
+ }
281
+ frameAt = time;
282
+ spent = 0;
283
+ blockedUntilFrame = false;
284
+ if (queues.input.size || queues.frame.size || candidate(queues.visible)?.foreground?.() === true || candidate(queues.background)?.foreground?.() === true || [first(queues.visible), first(queues.background)].some(
285
+ (job) => job && clock.now() - job.at >= timeout
286
+ ))
287
+ void pump("frame");
288
+ request();
289
+ });
290
+ if (allowance() <= 0) return;
291
+ const urgentInput = candidate(queues.input)?.foreground?.() === true;
292
+ if (interactive.size && !urgentInput) return;
293
+ if ((urgentInput || candidate(queues.visible) || candidate(queues.background)?.foreground?.()) && !taskPending) {
294
+ taskPending = true;
295
+ clock.task(() => {
296
+ taskPending = false;
297
+ void pump("task");
298
+ });
299
+ } else if (candidate(queues.background) && idle === null) {
300
+ if (clock.requestIdle)
301
+ idle = clock.requestIdle(
302
+ (deadline) => {
303
+ idle = null;
304
+ void pump("idle", deadline);
305
+ },
306
+ { timeout }
307
+ );
308
+ else if (!taskPending) {
309
+ taskPending = true;
310
+ clock.task(() => {
311
+ taskPending = false;
312
+ void pump("task");
313
+ });
314
+ }
315
+ }
316
+ }
317
+ const scheduler = {
318
+ async run(steps, settings = {}) {
319
+ for (; ; ) {
320
+ const next = await scheduler.schedule((slice) => {
321
+ let next2;
322
+ do {
323
+ next2 = steps.next();
324
+ } while (!next2.done && slice.hasTime());
325
+ return next2;
326
+ }, settings);
327
+ if (disposed || settings.signal?.aborted)
328
+ throw settings.signal?.reason ?? new Error("Work scheduler disposed");
329
+ if (next.done) return next.value;
330
+ }
331
+ },
332
+ schedule(work, settings = {}) {
333
+ if (disposed || settings.signal?.aborted)
334
+ return Promise.reject(
335
+ settings.signal?.reason ?? new Error("Work scheduler disposed")
336
+ );
337
+ return new Promise((resolve, reject) => {
338
+ const job = {
339
+ at: clock.now(),
340
+ priority: settings.priority ?? "visible",
341
+ signal: settings.signal,
342
+ foreground: settings.foreground,
343
+ abort() {
344
+ remove(job);
345
+ reject(
346
+ settings.signal?.reason ?? new Error("Work scheduler disposed")
347
+ );
348
+ },
349
+ run(slice) {
350
+ try {
351
+ const value = work(slice);
352
+ if (value && typeof value.then === "function")
353
+ throw new TypeError("Scheduled work must be synchronous");
354
+ resolve(value);
355
+ } catch (error) {
356
+ reject(error);
357
+ }
358
+ }
359
+ };
360
+ queues[job.priority].add(job);
361
+ settings.signal?.addEventListener("abort", job.abort, { once: true });
362
+ request();
363
+ });
364
+ },
365
+ hasForeground: () => foreground.size > 0,
366
+ subscribeForeground(listener) {
367
+ foregroundListeners.add(listener);
368
+ return () => {
369
+ foregroundListeners.delete(listener);
370
+ };
371
+ },
372
+ claimForeground() {
373
+ const token = {};
374
+ foreground.add(token);
375
+ if (foreground.size === 1)
376
+ for (const listener of foregroundListeners) listener();
377
+ request();
378
+ return () => {
379
+ if (!foreground.delete(token)) return;
380
+ if (foreground.size === 0)
381
+ for (const listener of foregroundListeners) listener();
382
+ request();
383
+ };
384
+ },
385
+ claimInteractive() {
386
+ const token = {};
387
+ interactive.add(token);
388
+ if (idle !== null) clock.cancelIdle?.(idle);
389
+ idle = null;
390
+ return () => {
391
+ if (!interactive.delete(token)) return;
392
+ request();
393
+ };
394
+ },
395
+ promote(signal) {
396
+ for (const job of queues.background) {
397
+ if (job.signal !== signal) continue;
398
+ queues.background.delete(job);
399
+ job.priority = "visible";
400
+ queues.visible.add(job);
401
+ }
402
+ request();
403
+ },
404
+ get diagnostics() {
405
+ return {
406
+ interactiveClaims: interactive.size,
407
+ foregroundClaims: foreground.size,
408
+ eligibleJobs: Object.values(queues).reduce(
409
+ (total, queue) => total + [...queue].filter(eligible).length,
410
+ 0
411
+ ),
412
+ queued: count(),
413
+ oldestMs: Math.max(
414
+ 0,
415
+ ...Object.values(queues).map((queue) => {
416
+ const job = first(queue);
417
+ return job ? clock.now() - job.at : 0;
418
+ })
419
+ ),
420
+ slices,
421
+ overruns,
422
+ maxSliceMs
423
+ };
424
+ },
425
+ dispose() {
426
+ disposed = true;
427
+ if (frame !== null) clock.cancelFrame(frame);
428
+ if (idle !== null) clock.cancelIdle?.(idle);
429
+ for (const queue of Object.values(queues))
430
+ for (const job of queue) job.abort();
431
+ }
432
+ };
433
+ return scheduler;
434
+ }
435
+
436
+ // ../../modules/iframe-projection/html/head-worker-source.ts
437
+ var HEAD_WORKER_SOURCE = '(function() {\n "use strict";\n function extractStyleSourceEvidence(text) {\n const attributes = {};\n const clone = {\n setAttribute: (key, value) => {\n attributes[key] = value;\n }\n };\n const reference = [\n ...text.matchAll(/\\/\\*[#@]\\s*sourceMappingURL\\s*=\\s*(\\S+?)\\s*\\*\\//g)\n ].slice(-1)[0]?.[1];\n if (!reference || reference.length > 1024 * 1024) return attributes;\n const inline = /^data:application\\/json(?:;charset=[\\w-]+)?(;base64)?,(.*)$/is.exec(\n reference\n );\n if (!inline) {\n try {\n const url = new URL(reference);\n if (/^https?:$/.test(url.protocol))\n clone.setAttribute("data-projection-css-source-map-url", url.href);\n } catch {\n }\n return attributes;\n }\n function compact(raw, depth) {\n if (!raw || typeof raw !== "object" || depth > 16) return null;\n const map = raw;\n if (map.version !== 3) return null;\n const sources = Array.isArray(map.sources) && map.sources.length <= 4096 && map.sources.every((source) => typeof source === "string") ? map.sources : void 0;\n const sections = Array.isArray(map.sections) && map.sections.length <= 256 ? map.sections.flatMap((section) => {\n const nested = section && typeof section === "object" ? compact(section.map, depth + 1) : null;\n return nested ? [{ map: nested }] : [];\n }) : void 0;\n return {\n version: 3,\n ...typeof map.file === "string" ? { file: map.file } : {},\n ...typeof map.sourceRoot === "string" ? { sourceRoot: map.sourceRoot } : {},\n ...sources ? { sources } : {},\n ...sections ? { sections } : {}\n };\n }\n try {\n const json = inline[1] ? new TextDecoder().decode(\n Uint8Array.from(\n atob(inline[2]),\n (character) => character.charCodeAt(0)\n )\n ) : decodeURIComponent(inline[2]);\n const metadata = compact(JSON.parse(json), 0);\n if (!metadata) return attributes;\n const serialized = JSON.stringify(metadata);\n if (serialized.length <= 64 * 1024)\n clone.setAttribute("data-projection-css-source-map", serialized);\n } catch {\n }\n return attributes;\n }\n function absolutifyCssReferences(cssText, baseHref) {\n const resolve = (value) => {\n const trimmed = value.trim();\n if (!trimmed || trimmed.startsWith("#") || /^(?:data|blob|javascript):/i.test(trimmed)) {\n return /^javascript:/i.test(trimmed) ? "" : trimmed;\n }\n try {\n return new URL(trimmed, baseHref).href;\n } catch {\n return trimmed;\n }\n };\n return cssText.replace(\n /url\\(\\s*(["\']?)([^"\')]+)\\1\\s*\\)/gi,\n (_match, quote, value) => `url(${quote}${resolve(value)}${quote})`\n ).replace(\n /@import\\s+(["\'])([^"\']+)\\1/gi,\n (_match, quote, value) => `@import ${quote}${resolve(value)}${quote}`\n );\n }\n const scope = globalThis;\n scope.onmessage = async ({ data }) => {\n const stages = {};\n const measure = (name, work) => {\n if (!data.measure) return work();\n const start = performance.now();\n const value = work();\n stages[name] = performance.now() - start;\n return value;\n };\n try {\n const metadata = data.metadata ?? measure(\n "sourceMetadata",\n () => extractStyleSourceEvidence(data.authored ?? "")\n );\n const rawCss = measure("joinRules", () => data.rules.join("\\n"));\n const css = measure(\n "resolveUrls",\n () => absolutifyCssReferences(rawCss, data.base)\n );\n const start = data.measure ? performance.now() : 0;\n const digest = await crypto.subtle.digest(\n "SHA-256",\n new TextEncoder().encode(css)\n );\n const hash = Array.from(\n new Uint8Array(digest),\n (byte) => byte.toString(16).padStart(2, "0")\n ).join("");\n if (data.measure) stages.resourceHash = performance.now() - start;\n scope.postMessage({\n id: data.id,\n result: { css, hash, metadata, stages }\n });\n } catch (error) {\n scope.postMessage({ id: data.id, error: String(error) });\n }\n };\n})();\n';
438
+
439
+ // ../../modules/iframe-projection/html/head-worker.ts
440
+ var WORKER_TIMEOUT_MS = 3e4;
441
+ function createHeadWorker() {
442
+ let worker;
443
+ let url;
444
+ let sequence = 0;
445
+ const pending = /* @__PURE__ */ new Map();
446
+ const dispose = (error = new Error("Head worker stopped")) => {
447
+ if (worker) {
448
+ worker.onmessage = null;
449
+ worker.onerror = null;
450
+ worker.onmessageerror = null;
451
+ worker.terminate();
452
+ }
453
+ worker = void 0;
454
+ if (url) URL.revokeObjectURL(url);
455
+ url = void 0;
456
+ for (const job of pending.values()) {
457
+ clearTimeout(job.timer);
458
+ job.reject(error);
459
+ }
460
+ pending.clear();
461
+ };
462
+ return {
463
+ process(input) {
464
+ if (!worker) {
465
+ url = URL.createObjectURL(
466
+ new Blob([HEAD_WORKER_SOURCE], { type: "text/javascript" })
467
+ );
468
+ try {
469
+ worker = new Worker(url);
470
+ } catch (error) {
471
+ dispose();
472
+ return Promise.reject(error);
473
+ }
474
+ worker.onmessage = ({ data }) => {
475
+ const job = pending.get(data.id);
476
+ if (!job) return;
477
+ pending.delete(data.id);
478
+ clearTimeout(job.timer);
479
+ if (data.error) job.reject(new Error(data.error));
480
+ else job.resolve(data.result);
481
+ };
482
+ worker.onerror = () => dispose();
483
+ worker.onmessageerror = () => dispose();
484
+ }
485
+ return new Promise((resolve, reject) => {
486
+ const id = ++sequence;
487
+ const timer = setTimeout(() => {
488
+ dispose(new Error("Head worker timed out after 30000ms"));
489
+ }, WORKER_TIMEOUT_MS);
490
+ pending.set(id, { resolve, reject, timer });
491
+ try {
492
+ worker.postMessage({ ...input, id });
493
+ } catch (error) {
494
+ pending.delete(id);
495
+ clearTimeout(timer);
496
+ reject(error);
497
+ }
498
+ });
499
+ },
500
+ dispose
501
+ };
502
+ }
503
+
504
+ // ../../modules/iframe-projection/html/prepared-head.ts
505
+ var documents = /* @__PURE__ */ new WeakMap();
506
+ function createPreparedHead(doc, clock) {
507
+ let shared = documents.get(doc);
508
+ if (!shared) {
509
+ shared = { head: buildPreparedHead(doc, clock), owners: 0 };
510
+ documents.set(doc, shared);
511
+ }
512
+ shared.owners++;
513
+ const owner = shared;
514
+ let disposed = false;
515
+ return {
516
+ ...owner.head,
517
+ dispose() {
518
+ if (disposed) return;
519
+ disposed = true;
520
+ if (--owner.owners === 0) {
521
+ owner.head.dispose();
522
+ documents.delete(doc);
523
+ }
524
+ }
525
+ };
526
+ }
527
+ function buildPreparedHead(doc, clock) {
528
+ const work = createWorkScheduler({ clock });
529
+ const worker = createHeadWorker();
530
+ const abort = new AbortController();
531
+ const cache = /* @__PURE__ */ new Map();
532
+ const versions = /* @__PURE__ */ new Map();
533
+ const mutable = /* @__PURE__ */ new Set();
534
+ let consumed = false;
535
+ const metadata = /* @__PURE__ */ new WeakMap();
536
+ let revision = 0;
537
+ let preparedRevision = -1;
538
+ let base = doc.baseURI;
539
+ let adopted = [];
540
+ let ordered = [];
541
+ let lastOutput;
542
+ let pending;
543
+ let disposed = false;
544
+ const subscription = getHeadTracker().subscribe(doc, (detail) => {
545
+ revision++;
546
+ if (detail.allStyles) {
547
+ cache.clear();
548
+ for (const source of versions.keys()) versions.set(source, revision);
549
+ } else {
550
+ for (const source of [
551
+ ...detail.elements ?? [],
552
+ ...detail.sheets ?? []
553
+ ]) {
554
+ cache.delete(source);
555
+ if (detail.mutable) mutable.add(source);
556
+ versions.set(source, revision);
557
+ }
558
+ }
559
+ });
560
+ const sync = () => {
561
+ getHeadTracker().flushPending?.(doc);
562
+ const currentAdopted = doc.adoptedStyleSheets ?? [];
563
+ if (currentAdopted.length !== adopted.length || currentAdopted.some((sheet, index) => sheet !== adopted[index])) {
564
+ adopted = Array.from(currentAdopted);
565
+ revision++;
566
+ }
567
+ if (base !== doc.baseURI) {
568
+ const samePath = base.split(/[?#]/)[0] === doc.baseURI.split(/[?#]/)[0];
569
+ base = doc.baseURI;
570
+ revision++;
571
+ for (const source of versions.keys()) {
572
+ const value = cache.get(source);
573
+ if (!value || !samePath || "tagName" in source && source.tagName !== "STYLE") {
574
+ cache.delete(source);
575
+ versions.set(source, revision);
576
+ }
577
+ }
578
+ }
579
+ };
580
+ function* read(source, timing) {
581
+ const isElement = "tagName" in source;
582
+ const node = isElement ? source.cloneNode(false) : doc.createElement("style");
583
+ let sheet;
584
+ let authored;
585
+ let cssBase = base;
586
+ if (isElement) {
587
+ sheet = source.sheet;
588
+ if (source.tagName === "STYLE") {
589
+ authored = source.textContent ?? "";
590
+ } else if (source.tagName === "LINK")
591
+ cssBase = source.href;
592
+ } else {
593
+ sheet = source;
594
+ node.setAttribute("data-projection-adopted-stylesheet", "true");
595
+ }
596
+ let list;
597
+ try {
598
+ if (!sheet) throw new Error("No stylesheet");
599
+ const started = timing ? performance.now() : 0;
600
+ list = Array.from(sheet.cssRules);
601
+ if (timing) {
602
+ const elapsed = performance.now() - started;
603
+ timing.report.stages.snapshotRuleIdentities = (timing.report.stages.snapshotRuleIdentities ?? 0) + elapsed;
604
+ if (timing.sheet) timing.sheet.stages.snapshotRuleIdentities = elapsed;
605
+ }
606
+ } catch {
607
+ if (authored !== void 0)
608
+ return { node, rules: [authored], authored, cssBase, count: 0 };
609
+ return { node, rules: null, cssBase, count: 0 };
610
+ }
611
+ const rules = [];
612
+ for (let offset = 0; offset < list.length; ) {
613
+ const start = timing ? performance.now() : 0;
614
+ const end = Math.min(offset + 32, list.length);
615
+ for (; offset < end; offset++) rules.push(list[offset].cssText);
616
+ if (timing) {
617
+ const elapsed = performance.now() - start;
618
+ timing.report.stages.readCssRules = (timing.report.stages.readCssRules ?? 0) + elapsed;
619
+ if (timing.sheet)
620
+ timing.sheet.stages.readCssRules = (timing.sheet.stages.readCssRules ?? 0) + elapsed;
621
+ }
622
+ yield;
623
+ }
624
+ return { node, rules, authored, cssBase, count: rules.length };
625
+ }
626
+ async function prepare(reason) {
627
+ const timing = beginHeadCapture(doc);
628
+ if (timing) timing.report.reason = reason;
629
+ try {
630
+ sync();
631
+ const epoch = revision;
632
+ const sources = [
633
+ ...Array.from(doc.head?.children ?? []).filter((node) => {
634
+ if (node.tagName === "LINK")
635
+ return shouldIncludeLink(node) && !isDisabledStylesheet(node);
636
+ if (node.tagName === "META") {
637
+ const name = node.getAttribute("name")?.toLowerCase();
638
+ return node.getAttribute("http-equiv")?.toLowerCase() !== "content-security-policy" && name !== "content-security-policy" && name !== "theme-color";
639
+ }
640
+ return node.tagName === "STYLE" || node.tagName === "BASE";
641
+ }),
642
+ ...adopted
643
+ ];
644
+ const next = [];
645
+ for (const source of sources) {
646
+ if (disposed) throw new Error("Head preparation stopped");
647
+ const hit = cache.get(source);
648
+ if (hit) {
649
+ next.push(hit);
650
+ if (timing) timing.report.cacheHits++;
651
+ continue;
652
+ }
653
+ if (timing) timing.report.cacheMisses++;
654
+ const sourceVersion = versions.get(source) ?? revision;
655
+ versions.set(source, sourceVersion);
656
+ const kind = "tagName" in source ? source.tagName : "adopted";
657
+ const sheetTiming = beginHeadSheet(timing, kind);
658
+ if (sheetTiming?.sheet && "tagName" in source)
659
+ sheetTiming.sheet.source = (source.getAttribute("data-vite-dev-id") ?? source.getAttribute("href") ?? source.id).split(/[?#]/)[0].split("/").slice(-2).join("/").slice(0, 256);
660
+ let prepared;
661
+ if (kind === "META" || kind === "BASE") {
662
+ const node = source.cloneNode(true);
663
+ resolveUrls(node, base);
664
+ prepared = { node, rules: 0 };
665
+ } else {
666
+ const queued = timing ? performance.now() : 0;
667
+ const input = await work.run(read(source, sheetTiming), {
668
+ signal: abort.signal,
669
+ priority: "visible"
670
+ });
671
+ if (timing) timing.report.readWallMs += performance.now() - queued;
672
+ let node = input.node;
673
+ if (input.rules === null) {
674
+ node.removeAttribute("crossorigin");
675
+ resolveUrls(node, base);
676
+ prepared = { node, rules: 0 };
677
+ } else {
678
+ if (kind === "LINK") {
679
+ node = doc.createElement("style");
680
+ for (const attribute of Array.from(input.node.attributes)) {
681
+ if (![
682
+ "as",
683
+ "crossorigin",
684
+ "fetchpriority",
685
+ "href",
686
+ "integrity",
687
+ "referrerpolicy",
688
+ "rel"
689
+ ].includes(attribute.name.toLowerCase()))
690
+ node.setAttribute(attribute.name, attribute.value);
691
+ }
692
+ node.setAttribute(
693
+ "data-projection-stylesheet-href",
694
+ input.cssBase
695
+ );
696
+ }
697
+ const previous = "tagName" in source ? metadata.get(source) : void 0;
698
+ const authored = input.authored;
699
+ const started = timing ? performance.now() : 0;
700
+ const text = await worker.process({
701
+ rules: input.rules,
702
+ authored: authored && authored.length <= 5 * 1024 * 1024 ? authored : "",
703
+ base: input.cssBase,
704
+ metadata: previous?.authored === authored ? previous?.value : void 0,
705
+ measure: !!timing
706
+ });
707
+ if (timing) {
708
+ timing.report.workerWallMs += performance.now() - started;
709
+ for (const [stage, elapsed] of Object.entries(text.stages)) {
710
+ timing.report.stages[stage] = (timing.report.stages[stage] ?? 0) + elapsed;
711
+ if (sheetTiming?.sheet)
712
+ sheetTiming.sheet.stages[stage] = elapsed;
713
+ }
714
+ }
715
+ node.removeAttribute("data-projection-css-source-map");
716
+ node.removeAttribute("data-projection-css-source-map-url");
717
+ for (const [key, value] of Object.entries(text.metadata))
718
+ node.setAttribute(key, value);
719
+ if ("tagName" in source && authored !== void 0)
720
+ metadata.set(source, { authored, value: text.metadata });
721
+ resolveUrls(node, base);
722
+ prepared = { node, text, rules: input.count };
723
+ if (sheetTiming?.sheet) {
724
+ sheetTiming.sheet.rules = input.count;
725
+ sheetTiming.sheet.characters = text.css.length;
726
+ }
727
+ }
728
+ }
729
+ sync();
730
+ if (sourceVersion === versions.get(source)) cache.set(source, prepared);
731
+ next.push(prepared);
732
+ }
733
+ sync();
734
+ ordered = next;
735
+ preparedRevision = epoch;
736
+ const retained = new Set(sources);
737
+ for (const source of cache.keys())
738
+ if (!retained.has(source)) cache.delete(source);
739
+ for (const source of versions.keys())
740
+ if (!retained.has(source)) versions.delete(source);
741
+ for (const source of mutable)
742
+ if (!retained.has(source)) mutable.delete(source);
743
+ } finally {
744
+ if (timing) {
745
+ timing.report.revision = revision;
746
+ timing.report.maxSliceSinceDocumentStartMs = work.diagnostics.maxSliceMs;
747
+ finishHeadCapture(doc, timing);
748
+ }
749
+ }
750
+ }
751
+ return {
752
+ prepare(reason = "head-request") {
753
+ sync();
754
+ if (preparedRevision >= 0 && !consumed) return;
755
+ if (consumed && mutable.size) {
756
+ revision++;
757
+ for (const source of mutable) {
758
+ cache.delete(source);
759
+ versions.set(source, revision);
760
+ }
761
+ }
762
+ consumed = false;
763
+ if (preparedRevision === revision) return;
764
+ if (!pending)
765
+ pending = prepare(reason).finally(() => {
766
+ pending = void 0;
767
+ });
768
+ return pending;
769
+ },
770
+ hasPendingChanges() {
771
+ sync();
772
+ return preparedRevision !== revision;
773
+ },
774
+ capture(resource) {
775
+ sync();
776
+ if (preparedRevision < 0) throw new Error("Head has not been prepared");
777
+ consumed = true;
778
+ const timing = beginHeadCapture(doc);
779
+ if (timing) {
780
+ timing.report.reason = "prepared-head-reuse";
781
+ timing.report.revision = revision;
782
+ timing.report.cacheHits = ordered.length;
783
+ }
784
+ try {
785
+ let changed = lastOutput?.ordered !== ordered;
786
+ const fragments = ordered.map((entry) => {
787
+ const { node, text } = entry;
788
+ if (!text) return node.outerHTML;
789
+ if (node.hasAttribute("data-projection-adopted-stylesheet") && !text.css)
790
+ return "";
791
+ const type = node.getAttribute("type")?.trim().toLowerCase();
792
+ const href = !type || type === "text/css" ? resource?.(text.css, text.hash) : null;
793
+ const previous = entry.markup;
794
+ if (previous && previous.href === (href ?? null))
795
+ return previous.html;
796
+ changed = true;
797
+ if (href) {
798
+ const link = doc.createElement("link");
799
+ for (const attribute of Array.from(node.attributes)) {
800
+ if (!["type", "href", "rel", "integrity", "crossorigin"].includes(
801
+ attribute.name
802
+ ))
803
+ link.setAttribute(attribute.name, attribute.value);
804
+ }
805
+ link.rel = "stylesheet";
806
+ link.href = href;
807
+ const html3 = link.outerHTML;
808
+ entry.markup = { href, html: html3 };
809
+ return html3;
810
+ }
811
+ node.textContent = text.css.replace(/<\//gi, "<\\/");
812
+ const html2 = node.outerHTML;
813
+ entry.markup = { href: null, html: html2 };
814
+ return html2;
815
+ });
816
+ if (!changed && lastOutput) return lastOutput.html;
817
+ const html = fragments.filter(Boolean).join("\n");
818
+ lastOutput = { ordered, html };
819
+ return html;
820
+ } finally {
821
+ if (timing) finishHeadCapture(doc, timing);
822
+ }
823
+ },
824
+ dispose() {
825
+ disposed = true;
826
+ abort.abort();
827
+ subscription.unsubscribe();
828
+ worker.dispose();
829
+ work.dispose();
830
+ cache.clear();
831
+ versions.clear();
832
+ ordered = [];
833
+ }
834
+ };
835
+ }
836
+
101
837
  // ../../modules/iframe-projection/html/document-assets.ts
102
838
  var observers = /* @__PURE__ */ new WeakMap();
103
839
  function observeDocumentAssets(doc, listener) {
@@ -208,6 +944,50 @@ function buildProjectionCapturePerf(input) {
208
944
  };
209
945
  }
210
946
 
947
+ // ../../modules/iframe-projection/html/root-coordinates.ts
948
+ var ROOT_COORDINATES_ATTRIBUTE = "data-projection-root-coordinates";
949
+ function captureRootCoordinates(root, portals = []) {
950
+ const doc = root.ownerDocument, view = doc.defaultView;
951
+ if (!view || root === doc.body || root === doc.documentElement) return;
952
+ for (const portal of portals) {
953
+ const css = view.getComputedStyle(portal);
954
+ if (css.position === "fixed" || css.position === "sticky" || css.position && css.position !== "static" && css.zIndex && css.zIndex !== "auto")
955
+ continue;
956
+ if (capturePortalCoordinateSpace(root, portal)?.origin === "viewport")
957
+ return;
958
+ }
959
+ const rect = root.getBoundingClientRect();
960
+ if (!rect.width || !rect.height) return;
961
+ const containingBlock = [doc.body, doc.documentElement].find((element) => {
962
+ if (!element) return false;
963
+ const css = view.getComputedStyle(element);
964
+ const active = (value) => Boolean(value && value !== "none");
965
+ return active(css.transform) || active(css.translate) || active(css.rotate) || active(css.scale) || active(css.perspective) || active(css.filter) || active(css.backdropFilter) || /layout|paint|strict|content/.test(css.contain) || /transform|perspective|filter/.test(css.willChange);
966
+ });
967
+ let layout;
968
+ if (containingBlock) {
969
+ let element = root, left = 0, top = 0;
970
+ while (element && element !== containingBlock) {
971
+ left += element.offsetLeft;
972
+ top += element.offsetTop;
973
+ element = element.offsetParent;
974
+ }
975
+ for (let parent = root.parentElement; parent && parent !== containingBlock; parent = parent.parentElement) {
976
+ left -= parent.scrollLeft;
977
+ top -= parent.scrollTop;
978
+ }
979
+ if (element === containingBlock && Number.isFinite(left) && Number.isFinite(top))
980
+ layout = { layoutLeft: left, layoutTop: top };
981
+ }
982
+ return {
983
+ left: rect.left,
984
+ top: rect.top,
985
+ width: containingBlock?.clientWidth || view.innerWidth,
986
+ height: containingBlock?.clientHeight || view.innerHeight,
987
+ ...layout
988
+ };
989
+ }
990
+
211
991
  // ../../modules/iframe-projection/root-color.ts
212
992
  var PROJECTION_ROOT_COLOR_ATTR = "data-tempo-root-color";
213
993
  function captureProjectionRootColor(documentElement) {
@@ -287,7 +1067,9 @@ function captureFullDom(root, portals, observedFiles) {
287
1067
  }
288
1068
  const body = root.ownerDocument.body;
289
1069
  const rootDomId = ensureProjectionDomId(root);
1070
+ const coordinates = captureRootCoordinates(root, portals);
290
1071
  const dom = {
1072
+ ...coordinates ? { coordinates } : {},
291
1073
  html: removeScriptTags(clone.innerHTML),
292
1074
  ...rootDomId ? { rootDomId } : {},
293
1075
  documentElementAttributes: {
@@ -2870,6 +3652,8 @@ function createProjectionOutbox(options) {
2870
3652
  const rootRevisions = /* @__PURE__ */ new Map();
2871
3653
  let headRevision = 0;
2872
3654
  let lastHead;
3655
+ let preparingHead = false;
3656
+ let headPrepared = false;
2873
3657
  let stopped = false;
2874
3658
  let fixedWindow;
2875
3659
  const sizePending = (rootId) => {
@@ -2878,7 +3662,7 @@ function createProjectionOutbox(options) {
2878
3662
  return size !== void 0 && (size.width !== emitted?.width || size.height !== emitted?.height);
2879
3663
  };
2880
3664
  const gated = (rootId) => credited.has(rootId) && awaitingAck.has(rootId) && !full.has(rootId);
2881
- const hasWork = () => roots.size > 0 && (dirtyHead || dirtyModules || dirtyHeadRoots.size > 0 || [...dirty].some((rootId) => !gated(rootId)) || assets.size > 0 || [...roots].some(sizePending));
3665
+ const hasWork = () => !preparingHead && roots.size > 0 && (dirtyHead || dirtyModules || dirtyHeadRoots.size > 0 || [...dirty].some((rootId) => !gated(rootId)) || assets.size > 0 || [...roots].some(sizePending));
2882
3666
  const report = (error) => {
2883
3667
  try {
2884
3668
  options.onError?.(error);
@@ -2908,6 +3692,37 @@ function createProjectionOutbox(options) {
2908
3692
  const flushOnce = (timing) => {
2909
3693
  const activeSession = sessionId;
2910
3694
  if (stopped || !activeSession || !hasWork()) return;
3695
+ if (!headPrepared && (dirtyHead || dirtyHeadRoots.size > 0)) {
3696
+ try {
3697
+ const preparation = options.prepareHead?.({
3698
+ initialForSession: sequence === 0,
3699
+ triggerReasons: [...triggerReasons]
3700
+ });
3701
+ if (preparation) {
3702
+ preparingHead = true;
3703
+ void preparation.then(
3704
+ () => {
3705
+ preparingHead = false;
3706
+ headPrepared = true;
3707
+ if (!stopped) fixedWindow.flushNow();
3708
+ },
3709
+ (error) => {
3710
+ preparingHead = false;
3711
+ if (!stopped) {
3712
+ report(error);
3713
+ fixedWindow.schedule();
3714
+ }
3715
+ }
3716
+ );
3717
+ return;
3718
+ }
3719
+ } catch (error) {
3720
+ report(error);
3721
+ fixedWindow.schedule();
3722
+ return;
3723
+ }
3724
+ }
3725
+ headPrepared = false;
2911
3726
  const requestedRoots = [...requested].filter((rootId) => dirty.has(rootId));
2912
3727
  const rootIds = (requestedRoots.length ? requestedRoots : [...dirty]).filter((rootId) => !gated(rootId)).slice(0, rootLimit);
2913
3728
  const fullRootIds = new Set(full);
@@ -2969,6 +3784,10 @@ function createProjectionOutbox(options) {
2969
3784
  lastHead = head;
2970
3785
  headRevision = ++revision;
2971
3786
  }
3787
+ if (shouldCaptureHead && options.hasPendingHead?.()) {
3788
+ dirtyHead = true;
3789
+ fixedWindow.schedule();
3790
+ }
2972
3791
  const includesFull = changes.some((change) => change.kind === "full");
2973
3792
  const modules = includeModules || includesFull ? options.captureModules?.(includesFull) : void 0;
2974
3793
  const pendingSizeRootIds = [...roots].filter(sizePending);
@@ -3414,6 +4233,8 @@ function createProjectionRootAccumulator(options) {
3414
4233
  const removedPortals = /* @__PURE__ */ new Map();
3415
4234
  const sentPortalCoordinates = /* @__PURE__ */ new Map();
3416
4235
  let stopped = false;
4236
+ let sentCoordinates;
4237
+ const hasCoordinateFrame = () => sentCoordinates !== void 0;
3417
4238
  const ancestorsOf = (element) => {
3418
4239
  const chain = [];
3419
4240
  for (let ancestor = element.parentElement; ancestor; ancestor = ancestor.parentElement) {
@@ -3433,7 +4254,7 @@ function createProjectionRootAccumulator(options) {
3433
4254
  }
3434
4255
  const restyled = records.some((record) => record.type === "attributes");
3435
4256
  if (!reparented && !restyled) return;
3436
- if (portals.size === 0) return;
4257
+ if (portals.size === 0 && !hasCoordinateFrame()) return;
3437
4258
  options.onChange("portal-coordinate-change");
3438
4259
  });
3439
4260
  function observeAncestors(chain) {
@@ -3448,6 +4269,17 @@ function createProjectionRootAccumulator(options) {
3448
4269
  }
3449
4270
  }
3450
4271
  observeAncestors(ancestorsOf(options.root));
4272
+ const view = options.root.ownerDocument.defaultView;
4273
+ const invalidateCoordinates = () => {
4274
+ if (!stopped && (hasCoordinateFrame() || portals.size > 0))
4275
+ options.onChange("portal-coordinate-change");
4276
+ };
4277
+ const onScroll = (event) => {
4278
+ const target = event.target;
4279
+ if (target?.contains?.(options.root)) invalidateCoordinates();
4280
+ };
4281
+ view?.addEventListener("resize", invalidateCoordinates);
4282
+ view?.addEventListener("scroll", onScroll, true);
3451
4283
  const registerPortals = options.registerPortals ?? ((registration) => getPortalTracker().register({
3452
4284
  element: options.root,
3453
4285
  ...registration
@@ -3482,6 +4314,10 @@ function createProjectionRootAccumulator(options) {
3482
4314
  if (stopped) return 0;
3483
4315
  return dom.takePendingRecords();
3484
4316
  },
4317
+ hasCoordinateFrame,
4318
+ rememberCoordinates(coordinates) {
4319
+ sentCoordinates = coordinates ? JSON.stringify(coordinates) : void 0;
4320
+ },
3485
4321
  hasPortals() {
3486
4322
  return !stopped && portals.size > 0;
3487
4323
  },
@@ -3559,6 +4395,7 @@ function createProjectionRootAccumulator(options) {
3559
4395
  portalPatches.push(captured.portal);
3560
4396
  observedFiles.merge(captured.observedFiles);
3561
4397
  layerObservedFiles.merge(captured.observedFiles);
4398
+ states.push(...captured.state);
3562
4399
  for (const event of pending.state) {
3563
4400
  const statePatch = captureProjectionStatePatch(
3564
4401
  portal,
@@ -3571,15 +4408,15 @@ function createProjectionRootAccumulator(options) {
3571
4408
  dirtyPortals.clear();
3572
4409
  for (const portal of portals.keys()) {
3573
4410
  if (resentPortals.has(portal)) continue;
3574
- const coordinates = captureProjectionPortalCoordinates(
4411
+ const coordinates2 = captureProjectionPortalCoordinates(
3575
4412
  options.root,
3576
4413
  portal
3577
4414
  );
3578
- if (!coordinates) continue;
3579
- const measured = JSON.stringify(coordinates.coordinateSpace);
4415
+ if (!coordinates2) continue;
4416
+ const measured = JSON.stringify(coordinates2.coordinateSpace);
3580
4417
  if (sentPortalCoordinates.get(portal) === measured) continue;
3581
4418
  sentPortalCoordinates.set(portal, measured);
3582
- portalPatches.push(coordinates);
4419
+ portalPatches.push(coordinates2);
3583
4420
  }
3584
4421
  const observedSnapshot = observedFiles.snapshot();
3585
4422
  for (const snapshot of metadata)
@@ -3589,9 +4426,22 @@ function createProjectionRootAccumulator(options) {
3589
4426
  ...metadata.length > 0 ? { metadata } : {},
3590
4427
  ...Object.keys(layerObservedSnapshot).length > 0 ? { observedFiles: layerObservedSnapshot } : {}
3591
4428
  };
4429
+ const coordinates = captureRootCoordinates(options.root, portals.keys());
4430
+ const measuredCoordinates = coordinates ? JSON.stringify(coordinates) : void 0;
4431
+ const coordinatesChanged = measuredCoordinates !== sentCoordinates;
4432
+ sentCoordinates = measuredCoordinates;
4433
+ const domPatches = [...mutationPatch.dom];
4434
+ if (coordinatesChanged)
4435
+ domPatches.push({
4436
+ kind: "attributes",
4437
+ targetId: PROJECTION_ROOT_TARGET_ID,
4438
+ attributes: {
4439
+ [ROOT_COORDINATES_ATTRIBUTE]: measuredCoordinates ?? null
4440
+ }
4441
+ });
3592
4442
  const patch = {
3593
4443
  ...Object.keys(layers).length > 0 ? { layers } : {},
3594
- ...mutationPatch.dom.length > 0 ? { dom: mutationPatch.dom } : {},
4444
+ ...domPatches.length > 0 ? { dom: domPatches } : {},
3595
4445
  ...mutationPatch.pointerEventsNone ? { pointerEventsNone: mutationPatch.pointerEventsNone } : {},
3596
4446
  ...states.length > 0 ? { state: states } : {},
3597
4447
  ...portalPatches.length > 0 ? { portals: portalPatches } : {},
@@ -3625,6 +4475,8 @@ function createProjectionRootAccumulator(options) {
3625
4475
  stopped = true;
3626
4476
  unregisterPortals();
3627
4477
  frameWatcher.disconnect();
4478
+ view?.removeEventListener("resize", invalidateCoordinates);
4479
+ view?.removeEventListener("scroll", onScroll, true);
3628
4480
  dom.stop();
3629
4481
  state.stop();
3630
4482
  for (const portal of portals.values()) portal.stop();
@@ -3660,6 +4512,7 @@ function collectDomLayerTargets(root, mutations) {
3660
4512
  var MODULE_EVALUATED_GRACE_MS = 3e3;
3661
4513
  function createCombinedDocumentProducer(options) {
3662
4514
  const reactHook = initHook();
4515
+ const preparedHead = options.prepareHead ? createPreparedHead(options.document, options.headWorkClock) : void 0;
3663
4516
  const roots = /* @__PURE__ */ new Map();
3664
4517
  const captureStats = /* @__PURE__ */ new WeakMap();
3665
4518
  let stopped = false;
@@ -3777,6 +4630,10 @@ function createCombinedDocumentProducer(options) {
3777
4630
  return Object.keys(absent).length ? absent : void 0;
3778
4631
  }
3779
4632
  const core = createProjectionOutbox({
4633
+ hasPendingHead: preparedHead ? () => preparedHead.hasPendingChanges() : void 0,
4634
+ prepareHead: preparedHead ? (context) => preparedHead.prepare(
4635
+ context.initialForSession ? "session-baseline" : context.triggerReasons.join(",") || "baseline-request"
4636
+ ) : void 0,
3780
4637
  emit(batch) {
3781
4638
  recordSourceViewport();
3782
4639
  const sourceViewportSamples = pendingSourceViewportSamples.splice(0);
@@ -3948,6 +4805,7 @@ function createCombinedDocumentProducer(options) {
3948
4805
  layerAdapter: runtime.layerAdapter
3949
4806
  });
3950
4807
  const { snapshot } = captured;
4808
+ accumulator.rememberCoordinates(snapshot.dom.coordinates);
3951
4809
  const documentContext = JSON.stringify([
3952
4810
  snapshot.dom.documentElementAttributes,
3953
4811
  snapshot.dom.bodyAttributes,
@@ -4198,7 +5056,7 @@ function createCombinedDocumentProducer(options) {
4198
5056
  captureHead(flushContext) {
4199
5057
  if (flushContext.candidateRootCount === 0) resetCaptureFlushCounters();
4200
5058
  const startedAt = Date.now();
4201
- const head = captureHead(options.document, options.styleResource);
5059
+ const head = preparedHead ? preparedHead.capture(options.styleResource) : captureHead(options.document, options.styleResource);
4202
5060
  headSnapshotMs = Date.now() - startedAt;
4203
5061
  headPerfContext = flushContext;
4204
5062
  return head;
@@ -4458,7 +5316,8 @@ function createCombinedDocumentProducer(options) {
4458
5316
  if (stopped) return;
4459
5317
  const rootIds = [];
4460
5318
  for (const [rootId, runtime] of roots) {
4461
- if (runtime.accumulator?.hasPortals()) rootIds.push(rootId);
5319
+ if (runtime.accumulator?.hasPortals() || runtime.accumulator?.hasCoordinateFrame())
5320
+ rootIds.push(rootId);
4462
5321
  }
4463
5322
  core.record({
4464
5323
  head: true,
@@ -4474,6 +5333,7 @@ function createCombinedDocumentProducer(options) {
4474
5333
  moduleLog?.close();
4475
5334
  sourceWindow?.removeEventListener("resize", recordSourceViewport);
4476
5335
  core.stop();
5336
+ preparedHead?.dispose();
4477
5337
  throw error;
4478
5338
  }
4479
5339
  const unregisterDocumentProducer = registerDocumentCaptureProducer(
@@ -4588,6 +5448,7 @@ function createCombinedDocumentProducer(options) {
4588
5448
  if (stopped) return;
4589
5449
  stopped = true;
4590
5450
  core.stop();
5451
+ preparedHead?.dispose();
4591
5452
  for (const runtime of roots.values()) {
4592
5453
  stopRootObserver(runtime);
4593
5454
  }
@@ -5592,7 +6453,12 @@ function triggersForBatch(batch) {
5592
6453
  continue;
5593
6454
  }
5594
6455
  const patch = change.patch;
5595
- if (patch.dom?.length) triggers.add("dom");
6456
+ if (patch.dom?.some(
6457
+ (change2) => change2.kind !== "attributes" || change2.targetId !== PROJECTION_ROOT_TARGET_ID || Object.keys(change2.attributes).some(
6458
+ (name) => name !== ROOT_COORDINATES_ATTRIBUTE
6459
+ )
6460
+ ))
6461
+ triggers.add("dom");
5596
6462
  if (patch.state?.length) triggers.add("state");
5597
6463
  for (const portal of patch.portals ?? []) {
5598
6464
  if (portal.kind === "replace" && portal.coordinatesOnly) continue;
@@ -7324,4 +8190,4 @@ function installTempoInteractProjectionSource() {
7324
8190
  export {
7325
8191
  installTempoInteractProjectionSource
7326
8192
  };
7327
- //# sourceMappingURL=chunk-GKDDNDG3.js.map
8193
+ //# sourceMappingURL=chunk-TFPT6T3K.js.map