tempo-sdk 0.0.19 → 0.0.20

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.
@@ -1,3 +1,8 @@
1
+ import {
2
+ TEMPO_INTERACT_FRAME_NAME,
3
+ isTempoInteractFrameName
4
+ } from "../chunk-QXB32HG4.js";
5
+
1
6
  // canvas/canvas.tsx
2
7
  import {
3
8
  Children,
@@ -40,7 +45,8 @@ function Canvas({
40
45
  name,
41
46
  path,
42
47
  backgroundColor,
43
- defaultViewport
48
+ defaultViewport,
49
+ ...sourceAnnotations
44
50
  }) {
45
51
  const contextIdentity = useCanvasIdentity();
46
52
  const canvasName = normalizeId(name, "Canvas name");
@@ -64,6 +70,7 @@ function Canvas({
64
70
  return /* @__PURE__ */ jsx(CanvasIdentityContext.Provider, { value: identity, children: /* @__PURE__ */ jsx(
65
71
  "div",
66
72
  {
73
+ ...sourceAnnotations,
67
74
  "data-tempo-canvas": canvasName,
68
75
  "data-tempo-canvas-path": canvasPath,
69
76
  "data-tempo-canvas-background": backgroundColor,
@@ -82,10 +89,40 @@ function CanvasContext({
82
89
  }
83
90
 
84
91
  // canvas/canvas-host.tsx
92
+ import { useMemo as useMemo4 } from "react";
93
+
94
+ // canvas/canvas-import-boundary.tsx
85
95
  import {
86
- useMemo as useMemo3
96
+ Component,
97
+ lazy,
98
+ Suspense,
99
+ useCallback as useCallback2,
100
+ useEffect,
101
+ useLayoutEffect,
102
+ useMemo as useMemo2,
103
+ useRef,
104
+ useState
87
105
  } from "react";
88
106
 
107
+ // canvas/host-recovery-feed.ts
108
+ var FEED_KEY = "__tempoCanvasHostRecoveryFeed";
109
+ function createFeed() {
110
+ const listeners = /* @__PURE__ */ new Set();
111
+ return {
112
+ publish(event) {
113
+ for (const listener of [...listeners]) listener(event);
114
+ },
115
+ subscribe(listener) {
116
+ listeners.add(listener);
117
+ return () => listeners.delete(listener);
118
+ }
119
+ };
120
+ }
121
+ function getCanvasHostRecoveryFeed() {
122
+ const globals = globalThis;
123
+ return globals[FEED_KEY] ?? (globals[FEED_KEY] = createFeed());
124
+ }
125
+
89
126
  // canvas/runtime-context.ts
90
127
  import { createContext as createContext2, useCallback, useContext as useContext2 } from "react";
91
128
  var CanvasHostContext = createContext2(null);
@@ -115,6 +152,13 @@ function useStoryboardRendered(storyboardId) {
115
152
  host.markStoryboardRendered(renderId);
116
153
  }, [host, renderId]);
117
154
  }
155
+ function useStoryboardUnmounted(storyboardId) {
156
+ const renderId = useCanvasStoryboardRenderId(storyboardId);
157
+ const { markStoryboardUnmounted } = useRequiredCanvasHost();
158
+ return useCallback(() => {
159
+ markStoryboardUnmounted(renderId);
160
+ }, [markStoryboardUnmounted, renderId]);
161
+ }
118
162
  function useStoryboardErrorReporter(storyboardId) {
119
163
  const renderId = useCanvasStoryboardRenderId(storyboardId);
120
164
  const host = useRequiredCanvasHost();
@@ -140,8 +184,109 @@ function useStoryboardPlacement(storyboardId) {
140
184
  return host.getStoryboardPlacement(renderId);
141
185
  }
142
186
 
187
+ // canvas/canvas-import-boundary.tsx
188
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
189
+ var CanvasImportErrorBoundary = class extends Component {
190
+ constructor() {
191
+ super(...arguments);
192
+ this.state = { hasError: false };
193
+ }
194
+ static getDerivedStateFromError() {
195
+ return { hasError: true };
196
+ }
197
+ componentDidCatch(error, info) {
198
+ this.props.reportError({
199
+ message: error instanceof Error ? error.message : String(error),
200
+ stack: error instanceof Error ? error.stack : void 0,
201
+ componentStack: info.componentStack ?? void 0
202
+ });
203
+ }
204
+ render() {
205
+ return this.state.hasError ? null : this.props.children;
206
+ }
207
+ };
208
+ function CanvasCommitSignal({ onCommit }) {
209
+ const onCommitRef = useRef(onCommit);
210
+ const didCommitRef = useRef(false);
211
+ onCommitRef.current = onCommit;
212
+ useLayoutEffect(() => {
213
+ if (didCommitRef.current) return;
214
+ didCommitRef.current = true;
215
+ onCommitRef.current();
216
+ }, []);
217
+ return null;
218
+ }
219
+ function CanvasImportBoundary({
220
+ canvasPath,
221
+ load
222
+ }) {
223
+ const {
224
+ clearCanvasImportError,
225
+ registerCanvasProblemScope,
226
+ reportCanvasImportError
227
+ } = useRequiredCanvasHost();
228
+ const failedRef = useRef(false);
229
+ const loadRef = useRef(load);
230
+ const previousLoadRef = useRef(load);
231
+ loadRef.current = load;
232
+ const [retryRevision, setRetryRevision] = useState(0);
233
+ const lazyIdentity = `${canvasPath}:${retryRevision}`;
234
+ const LazyCanvas = useMemo2(() => {
235
+ void lazyIdentity;
236
+ return lazy(
237
+ () => loadRef.current().catch((error) => {
238
+ getCanvasHostRecoveryFeed().publish({
239
+ type: "module-load-failure",
240
+ path: canvasPath,
241
+ message: error instanceof Error ? error.message : String(error)
242
+ });
243
+ throw error;
244
+ })
245
+ );
246
+ }, [lazyIdentity, canvasPath]);
247
+ const reportError = useCallback2(
248
+ (error) => {
249
+ failedRef.current = true;
250
+ reportCanvasImportError(canvasPath, error);
251
+ },
252
+ [canvasPath, reportCanvasImportError]
253
+ );
254
+ const markCommitted = useCallback2(() => {
255
+ failedRef.current = false;
256
+ clearCanvasImportError(canvasPath);
257
+ }, [canvasPath, clearCanvasImportError]);
258
+ useEffect(() => {
259
+ const loadChanged = previousLoadRef.current !== load;
260
+ previousLoadRef.current = load;
261
+ if (loadChanged && failedRef.current) {
262
+ setRetryRevision((revision) => revision + 1);
263
+ }
264
+ }, [load]);
265
+ useEffect(
266
+ () => () => {
267
+ clearCanvasImportError(canvasPath);
268
+ },
269
+ [canvasPath, clearCanvasImportError]
270
+ );
271
+ useEffect(
272
+ () => registerCanvasProblemScope(canvasPath),
273
+ [canvasPath, registerCanvasProblemScope]
274
+ );
275
+ return /* @__PURE__ */ jsx2(CanvasImportErrorBoundary, { reportError, children: /* @__PURE__ */ jsx2(Suspense, { fallback: null, children: /* @__PURE__ */ jsxs(CanvasContext, { path: canvasPath, children: [
276
+ /* @__PURE__ */ jsx2(LazyCanvas, {}),
277
+ /* @__PURE__ */ jsx2(CanvasCommitSignal, { onCommit: markCommitted })
278
+ ] }) }) }, retryRevision);
279
+ }
280
+
143
281
  // canvas/use-canvas-host-postmessage.ts
144
- import { useCallback as useCallback2, useEffect, useMemo as useMemo2, useRef, useState } from "react";
282
+ import {
283
+ useCallback as useCallback3,
284
+ useEffect as useEffect2,
285
+ useLayoutEffect as useLayoutEffect2,
286
+ useMemo as useMemo3,
287
+ useRef as useRef2,
288
+ useState as useState2
289
+ } from "react";
145
290
 
146
291
  // canvas/canvas-host-runtime.ts
147
292
  function getCanvasHostRuntime() {
@@ -455,7 +600,10 @@ function trackStoryboardPortals(renderId, element, status) {
455
600
  var escapeRenderId = (renderId) => renderId.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
456
601
  var buildRenderSelector = (renderId) => `[data-render-id="${escapeRenderId(renderId)}"]`;
457
602
  var buildRenderContentSelector = (renderId) => `[data-render-content="${escapeRenderId(renderId)}"]`;
458
- var buildRenderContentFiberSelector = (renderId) => `${buildRenderContentSelector(renderId)} > :not([data-tempo-hide-fiber="true"])`;
603
+ var buildRenderContentFiberSelector = (renderId) => [
604
+ `${buildRenderContentSelector(renderId)} > :not([data-tempo-hide-fiber="true"])`,
605
+ `${buildRenderContentSelector(renderId)}:not(:has(> *))`
606
+ ].join(", ");
459
607
  function stripRenderContentWrapperAttributes(capture, renderId) {
460
608
  if (!capture || typeof capture !== "object") return capture;
461
609
  const dom = capture.dom;
@@ -483,12 +631,17 @@ function stripRenderContentWrapperFromCombinedCapture(capture, renderId) {
483
631
  html: stripRenderContentWrapperAttributes(html, renderId)
484
632
  };
485
633
  }
486
- function captureStoryboardImage(renderId, options) {
634
+ var nextAnimationFrame = () => new Promise((resolve) => {
635
+ requestAnimationFrame(() => resolve());
636
+ });
637
+ async function captureStoryboardImage(renderId, options) {
487
638
  const portalSelectors = [
488
639
  ...options?.portalSelectors ?? [],
489
640
  ...getStoryboardPortalSelectors(renderId)
490
641
  ];
491
- return getCanvasHostRuntime().captureSelector(
642
+ await nextAnimationFrame();
643
+ await nextAnimationFrame();
644
+ return await getCanvasHostRuntime().captureSelector(
492
645
  buildRenderSelector(renderId),
493
646
  portalSelectors.length > 0 ? { ...options, portalSelectors: [...new Set(portalSelectors)] } : options
494
647
  );
@@ -553,6 +706,87 @@ function watchStoryboardCombined(renderId, options) {
553
706
  });
554
707
  }
555
708
 
709
+ // canvas/canvas-host-legacy-compat.ts
710
+ var sourceAnnotationSelector = "[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]";
711
+ function getObservedSourceFiles(slot) {
712
+ if (!slot) return [];
713
+ return [
714
+ ...new Set(
715
+ [...slot.querySelectorAll(sourceAnnotationSelector)].flatMap((element) => [
716
+ element.getAttribute("data-tempo-source-file"),
717
+ element.getAttribute("data-tempo-filepath"),
718
+ element.getAttribute("data-tempo-html-filepath"),
719
+ element.getAttribute("data-tempo-source-loc")
720
+ ]).filter((file) => Boolean(file))
721
+ )
722
+ ];
723
+ }
724
+ function latestTimestamp(values) {
725
+ let latest = null;
726
+ for (const value of values.values()) {
727
+ latest = latest === null ? value : Math.max(latest, value);
728
+ }
729
+ return latest;
730
+ }
731
+ function isReactConnected() {
732
+ const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
733
+ return (hook?.renderers?.size ?? 0) > 0;
734
+ }
735
+ function createLegacyHostHealth() {
736
+ const renderCommitTimes = /* @__PURE__ */ new Map();
737
+ const sourceAnnotatedCommitTimes = /* @__PURE__ */ new Map();
738
+ const recordSourceAnnotatedCommit = (renderId, observedAt = Date.now()) => {
739
+ const slot = document.querySelector(buildRenderContentSelector(renderId));
740
+ if (getObservedSourceFiles(slot).length > 0) {
741
+ sourceAnnotatedCommitTimes.set(renderId, observedAt);
742
+ }
743
+ };
744
+ return {
745
+ recordRenderCommit(renderId) {
746
+ const committedAt = Date.now();
747
+ renderCommitTimes.set(renderId, committedAt);
748
+ recordSourceAnnotatedCommit(renderId, committedAt);
749
+ },
750
+ recordSourceAnnotatedCommit(renderId) {
751
+ recordSourceAnnotatedCommit(renderId);
752
+ },
753
+ forgetRender(renderId) {
754
+ renderCommitTimes.delete(renderId);
755
+ sourceAnnotatedCommitTimes.delete(renderId);
756
+ },
757
+ buildSnapshot(renderId, context) {
758
+ const slot = renderId ? document.querySelector(buildRenderContentSelector(renderId)) : null;
759
+ const observedSourceFiles = getObservedSourceFiles(slot);
760
+ return {
761
+ alive: true,
762
+ reactConnected: isReactConnected() || renderCommitTimes.size > 0 || context.hasRenderEntries,
763
+ documentReadyState: document.readyState,
764
+ hasViteOverlayElement: document.querySelector("vite-error-overlay") !== null,
765
+ lastHostRenderCommitAt: latestTimestamp(renderCommitTimes),
766
+ lastClaimRenderCommitAt: renderCommitTimes.get(renderId) ?? null,
767
+ lastHostSourceAnnotatedCommitAt: latestTimestamp(
768
+ sourceAnnotatedCommitTimes
769
+ ),
770
+ lastClaimSourceAnnotatedCommitAt: sourceAnnotatedCommitTimes.get(renderId) ?? null,
771
+ renderSlotExists: slot !== null,
772
+ renderSlotHasSourceAnnotatedContent: observedSourceFiles.length > 0,
773
+ renderSlotObservedSourceFiles: observedSourceFiles,
774
+ claimErrorBoundaryTripped: context.claimErrorBoundaryTripped,
775
+ observedAt: Date.now()
776
+ };
777
+ }
778
+ };
779
+ }
780
+ function applyLegacyRenderIsolation(renderId) {
781
+ document.querySelector("[data-render-isolation]")?.remove();
782
+ if (!renderId) return;
783
+ const style = document.createElement("style");
784
+ style.setAttribute("data-render-isolation", "");
785
+ const escapedId = typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(renderId) : renderId;
786
+ style.textContent = '[data-render-id]:not([data-render-id="' + escapedId + '"]) { opacity: 0 !important; pointer-events: none !important; }';
787
+ document.head.appendChild(style);
788
+ }
789
+
556
790
  // canvas/canvas-host-protocol.ts
557
791
  function isRecord(value) {
558
792
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -570,15 +804,22 @@ var readTrimmedString = (value) => {
570
804
  const normalized = value.trim();
571
805
  return normalized.length > 0 ? normalized : void 0;
572
806
  };
807
+ var readStringArray = (value) => {
808
+ if (!Array.isArray(value)) return void 0;
809
+ const values = value.map(readTrimmedString).filter((entry) => entry !== void 0);
810
+ return values.length > 0 ? [...new Set(values)] : void 0;
811
+ };
573
812
  function resolveRenderTarget(payload) {
574
813
  const explicitRenderId = readTrimmedString(payload.renderId);
575
814
  const canvasPath = readTrimmedString(payload.canvasPath);
576
815
  const storyboardId = readTrimmedString(payload.storyboardId);
816
+ const sourcePaths = readStringArray(payload.sourcePaths);
577
817
  const renderId = explicitRenderId || (canvasPath && storyboardId ? getCanvasStoryboardRenderId(canvasPath, storyboardId) : storyboardId);
578
818
  return renderId ? {
579
819
  renderId,
580
820
  ...canvasPath ? { canvasPath } : {},
581
- ...storyboardId ? { storyboardId } : {}
821
+ ...storyboardId ? { storyboardId } : {},
822
+ ...sourcePaths ? { sourcePaths } : {}
582
823
  } : null;
583
824
  }
584
825
  function requireRenderTarget(commandType, payload) {
@@ -638,6 +879,9 @@ var propsMatch = (a, b) => JSON.stringify(a ?? {}) === JSON.stringify(b ?? {});
638
879
  function renderRequestMatchesEntry(entry, request) {
639
880
  return entry?.importPath === request.importPath && entry.importName === request.importName && entry.width === request.width && entry.height === request.height && entry.intrinsicSize === request.intrinsicSize && propsMatch(entry.props, request.props);
640
881
  }
882
+ function renderRequestTargetsEntry(entry, request) {
883
+ return entry?.importPath === request.importPath && entry.importName === request.importName && propsMatch(entry.props, request.props);
884
+ }
641
885
  function acquireRender(entries, request) {
642
886
  const next = new Map(entries);
643
887
  const current = next.get(request.renderId);
@@ -705,26 +949,210 @@ function buildRenderSizeMap(entries) {
705
949
  );
706
950
  }
707
951
 
952
+ // canvas/source-identity.ts
953
+ function normalizeSourceIdentity(value) {
954
+ let normalized = value.trim().replace(/\\/g, "/");
955
+ const suffixIndex = normalized.search(/[?#]/);
956
+ if (suffixIndex !== -1) normalized = normalized.slice(0, suffixIndex);
957
+ try {
958
+ normalized = decodeURIComponent(normalized);
959
+ } catch {
960
+ }
961
+ normalized = normalized.replace(/^file:\/\//, "").replace(/^\/@fs\//, "/");
962
+ return normalized.replace(/^\.\//, "").replace(/\/{2,}/g, "/");
963
+ }
964
+ function distinctSourceIdentities(paths) {
965
+ return [
966
+ ...new Set(
967
+ paths.map(normalizeSourceIdentity).filter((path) => path.length)
968
+ )
969
+ ];
970
+ }
971
+ function normalizeDiagnosticText(value) {
972
+ const normalized = value.replace(/\\/g, "/");
973
+ try {
974
+ return decodeURIComponent(normalized).replace(/\bhttps?:\/\/[^/\s)]+/g, "").replace(/\/@fs\//g, "/");
975
+ } catch {
976
+ return normalized.replace(/\bhttps?:\/\/[^/\s)]+/g, "").replace(/\/@fs\//g, "/");
977
+ }
978
+ }
979
+ function isPathCharacter(value) {
980
+ return /[A-Za-z0-9._@+-]/.test(value);
981
+ }
982
+ function textMentionsPathSuffix(text, suffix) {
983
+ let fromIndex = 0;
984
+ while (fromIndex < text.length) {
985
+ const index = text.indexOf(suffix, fromIndex);
986
+ if (index < 0) return false;
987
+ const before = index === 0 ? "" : text[index - 1];
988
+ const after = text[index + suffix.length] ?? "";
989
+ if ((before === "" || before === "/" || !isPathCharacter(before)) && (after === "" || !isPathCharacter(after))) {
990
+ return true;
991
+ }
992
+ fromIndex = index + 1;
993
+ }
994
+ return false;
995
+ }
996
+ function textMentionsExactPath(text, path) {
997
+ let fromIndex = 0;
998
+ while (fromIndex < text.length) {
999
+ const index = text.indexOf(path, fromIndex);
1000
+ if (index < 0) return false;
1001
+ const before = index === 0 ? "" : text[index - 1];
1002
+ const after = text[index + path.length] ?? "";
1003
+ if ((before === "" || before !== "/" && !isPathCharacter(before)) && (after === "" || after !== "/" && !isPathCharacter(after))) {
1004
+ return true;
1005
+ }
1006
+ fromIndex = index + 1;
1007
+ }
1008
+ return false;
1009
+ }
1010
+ function projectRootSpellings(projectRoot) {
1011
+ const spellings = [projectRoot];
1012
+ if (/^\/(?:var|tmp)\//.test(projectRoot)) {
1013
+ spellings.push(`/private${projectRoot}`);
1014
+ } else if (/^\/private\/(?:var|tmp)\//.test(projectRoot)) {
1015
+ spellings.push(projectRoot.slice("/private".length));
1016
+ }
1017
+ return spellings;
1018
+ }
1019
+ function rootedDiagnosticAliases(identityValue, projectRootValue) {
1020
+ const identity = normalizeSourceIdentity(identityValue);
1021
+ const projectRoot = normalizeSourceIdentity(projectRootValue).replace(
1022
+ /\/+$/,
1023
+ ""
1024
+ );
1025
+ if (!identity || !projectRoot) return [];
1026
+ const roots = projectRootSpellings(projectRoot);
1027
+ const rootPrefix = roots.find((root) => identity.startsWith(`${root}/`));
1028
+ const relative = rootPrefix ? identity.slice(rootPrefix.length + 1) : identity.startsWith("/") ? identity.slice(1) : identity;
1029
+ return [
1030
+ .../* @__PURE__ */ new Set([
1031
+ relative,
1032
+ `/${relative}`,
1033
+ ...roots.map((root) => `${root}/${relative}`)
1034
+ ])
1035
+ ];
1036
+ }
1037
+ function matchingDiagnosticSegments(text, identity) {
1038
+ const segments = identity.split("/").filter(Boolean);
1039
+ for (let count = segments.length; count >= 2; count -= 1) {
1040
+ if (textMentionsPathSuffix(text, segments.slice(-count).join("/"))) {
1041
+ return count;
1042
+ }
1043
+ }
1044
+ return 0;
1045
+ }
1046
+ function resolveUniqueDiagnosticSourceMatches(textValue, candidates, options = {}) {
1047
+ const text = normalizeDiagnosticText(textValue);
1048
+ if (!text) return [];
1049
+ const projectRoot = options.projectRoot?.trim();
1050
+ if (projectRoot) {
1051
+ const exactMatches = candidates.filter((candidate) => {
1052
+ const aliases = rootedDiagnosticAliases(candidate, projectRoot);
1053
+ if (aliases.some((alias) => textMentionsExactPath(text, alias))) {
1054
+ return true;
1055
+ }
1056
+ if (!options.allowExtensionlessJsTs || /\.(?:[cm]?[jt]sx?)$/i.test(normalizeSourceIdentity(candidate))) {
1057
+ return false;
1058
+ }
1059
+ return aliases.some(
1060
+ (alias) => [".js", ".jsx", ".ts", ".tsx", ".mjs", ".mts", ".cjs", ".cts"].some(
1061
+ (extension) => textMentionsExactPath(text, `${alias}${extension}`)
1062
+ )
1063
+ );
1064
+ });
1065
+ return distinctSourceIdentities(exactMatches).length === 1 ? exactMatches : [];
1066
+ }
1067
+ const evaluated = candidates.map((candidate) => {
1068
+ const identity = normalizeSourceIdentity(candidate);
1069
+ return {
1070
+ candidate,
1071
+ identity,
1072
+ identitySegments: identity.split("/").filter(Boolean).length,
1073
+ matchSegments: matchingDiagnosticSegments(text, identity)
1074
+ };
1075
+ });
1076
+ const pathMatches = evaluated.filter(
1077
+ ({ matchSegments }) => matchSegments > 0
1078
+ );
1079
+ if (pathMatches.length > 0) {
1080
+ const strongest = Math.max(
1081
+ ...pathMatches.map(({ matchSegments }) => matchSegments)
1082
+ );
1083
+ const strongestMatches = pathMatches.filter(
1084
+ ({ matchSegments }) => matchSegments === strongest
1085
+ );
1086
+ const fullMatches = strongestMatches.filter(
1087
+ ({ identitySegments, matchSegments }) => identitySegments === matchSegments
1088
+ );
1089
+ const unambiguousMatches = fullMatches.length > 0 ? fullMatches : strongestMatches;
1090
+ if (distinctSourceIdentities(
1091
+ unambiguousMatches.map(({ identity }) => identity)
1092
+ ).length === 1) {
1093
+ return unambiguousMatches.map(({ candidate }) => candidate);
1094
+ }
1095
+ return [];
1096
+ }
1097
+ const basenameMatches = evaluated.filter(({ identity }) => {
1098
+ const basename = identity.split("/").pop() ?? "";
1099
+ return basename.length > 0 && textMentionsPathSuffix(text, basename);
1100
+ });
1101
+ return distinctSourceIdentities(
1102
+ basenameMatches.map(({ identity }) => identity)
1103
+ ).length === 1 ? basenameMatches.map(({ candidate }) => candidate) : [];
1104
+ }
1105
+
708
1106
  // canvas/runtime-problems.ts
709
1107
  var CanvasHostProblemTracker = class {
710
1108
  constructor() {
711
- this.hostProblemHmrGeneration = 0;
1109
+ this.hostProblemWasNearRender = false;
712
1110
  this.componentProblems = /* @__PURE__ */ new Map();
713
- this.componentProblemHmrGenerations = /* @__PURE__ */ new Map();
714
1111
  this.canvasProblems = /* @__PURE__ */ new Map();
1112
+ this.registeredCanvasPaths = /* @__PURE__ */ new Map();
1113
+ this.registeredRenderSourcePaths = /* @__PURE__ */ new Map();
715
1114
  this.watchers = /* @__PURE__ */ new Set();
716
1115
  this.hostProblemClearedWatchers = /* @__PURE__ */ new Set();
717
- this.hmrGeneration = 0;
718
1116
  }
719
1117
  snapshot() {
1118
+ const componentProblems = new Map(this.componentProblems);
1119
+ const canvasProblems = new Map(this.canvasProblems);
1120
+ const projectViteProblem = (problem) => {
1121
+ const canvasPaths = this.matchingCanvasPaths(problem);
1122
+ if (canvasPaths.length > 0) {
1123
+ for (const canvasPath of canvasPaths) {
1124
+ canvasProblems.set(canvasPath, problem);
1125
+ }
1126
+ return true;
1127
+ }
1128
+ const renderIds = this.matchingRenderIds(problem);
1129
+ if (renderIds.length === 0) return false;
1130
+ for (const renderId of renderIds) {
1131
+ componentProblems.set(
1132
+ renderId,
1133
+ this.problemForMatchedRender(problem, renderId)
1134
+ );
1135
+ }
1136
+ return true;
1137
+ };
720
1138
  const currentViteOverlay = readCurrentViteOverlay();
721
- const hostProblem = currentViteOverlay ?? (this.hostProblem?.sourceKind === "vite-overlay" ? void 0 : this.hostProblem);
1139
+ let hostProblem = this.hostProblem?.sourceKind === "vite-overlay" ? void 0 : this.hostProblem;
1140
+ if (hostProblem && isViteProblemSourceKind(hostProblem.sourceKind) && projectViteProblem(hostProblem)) {
1141
+ hostProblem = void 0;
1142
+ }
1143
+ if (hostProblem && (this.hostProblemWasNearRender || isNearRenderProblemSourceKind(hostProblem.sourceKind)) && projectViteProblem(hostProblem)) {
1144
+ hostProblem = void 0;
1145
+ }
1146
+ if (currentViteOverlay && !projectViteProblem(currentViteOverlay)) {
1147
+ hostProblem = currentViteOverlay;
1148
+ }
722
1149
  return {
723
1150
  hostProblem,
724
- componentProblems: [...this.componentProblems].map(
725
- ([renderId, problem]) => ({ renderId, problem })
726
- ),
727
- canvasProblems: [...this.canvasProblems].map(([canvasPath, problem]) => ({
1151
+ componentProblems: [...componentProblems].map(([renderId, problem]) => ({
1152
+ renderId,
1153
+ problem
1154
+ })),
1155
+ canvasProblems: [...canvasProblems].map(([canvasPath, problem]) => ({
728
1156
  canvasPath,
729
1157
  problem
730
1158
  }))
@@ -744,18 +1172,22 @@ var CanvasHostProblemTracker = class {
744
1172
  }
745
1173
  reportHostProblem(sourceKind, error, details = {}) {
746
1174
  this.hostProblem = createProblem(sourceKind, error, details);
747
- this.hostProblemHmrGeneration = this.hmrGeneration;
1175
+ this.hostProblemWasNearRender = false;
748
1176
  this.publish();
749
1177
  }
750
1178
  reportProblemNearRender(sourceKind, error, details = {}) {
751
1179
  const problem = createProblem(sourceKind, error, details);
752
- const renderId = findRenderIdForProblem(problem);
753
- if (renderId) {
754
- this.componentProblems.set(renderId, problem);
755
- this.componentProblemHmrGenerations.set(renderId, this.hmrGeneration);
1180
+ const renderIds = this.matchingRenderIds(problem);
1181
+ if (renderIds.length > 0) {
1182
+ for (const renderId of renderIds) {
1183
+ this.componentProblems.set(
1184
+ renderId,
1185
+ this.problemForMatchedRender(problem, renderId)
1186
+ );
1187
+ }
756
1188
  } else {
757
1189
  this.hostProblem = problem;
758
- this.hostProblemHmrGeneration = this.hmrGeneration;
1190
+ this.hostProblemWasNearRender = true;
759
1191
  }
760
1192
  this.publish();
761
1193
  }
@@ -769,17 +1201,53 @@ var CanvasHostProblemTracker = class {
769
1201
  );
770
1202
  this.publish();
771
1203
  }
772
- clearCanvasProblem(canvasPath) {
773
- if (!this.canvasProblems.delete(canvasPath)) return;
1204
+ clearCanvasProblem(canvasPath, sourceKinds) {
1205
+ const problem = this.canvasProblems.get(canvasPath);
1206
+ if (!problem) return;
1207
+ if (sourceKinds && !sourceKinds.includes(problem.sourceKind)) return;
1208
+ this.canvasProblems.delete(canvasPath);
774
1209
  this.publish();
775
1210
  }
1211
+ registerCanvasPath(canvasPath) {
1212
+ const normalizedPath = normalizeCanvasPath(canvasPath);
1213
+ if (!normalizedPath) return () => {
1214
+ };
1215
+ this.registeredCanvasPaths.set(
1216
+ normalizedPath,
1217
+ (this.registeredCanvasPaths.get(normalizedPath) ?? 0) + 1
1218
+ );
1219
+ this.publishIfViteProjectionChanged();
1220
+ return () => {
1221
+ const count = this.registeredCanvasPaths.get(normalizedPath) ?? 0;
1222
+ if (count <= 1) {
1223
+ this.registeredCanvasPaths.delete(normalizedPath);
1224
+ this.clearCanvasProblem(normalizedPath, ["vite-overlay"]);
1225
+ } else {
1226
+ this.registeredCanvasPaths.set(normalizedPath, count - 1);
1227
+ }
1228
+ this.publishIfViteProjectionChanged();
1229
+ };
1230
+ }
1231
+ matchingCanvasPaths(problem) {
1232
+ const candidates = [...this.registeredCanvasPaths.keys()];
1233
+ const filenameMatches = resolveUniqueDiagnosticSourceMatches(
1234
+ problem.filename ?? "",
1235
+ candidates,
1236
+ { projectRoot: readTempoProjectRoot() }
1237
+ );
1238
+ if (filenameMatches.length > 0) return filenameMatches;
1239
+ const text = [problem.message, problem.stack, problem.filename].filter(Boolean).join("\n");
1240
+ return resolveUniqueDiagnosticSourceMatches(text, candidates, {
1241
+ projectRoot: readTempoProjectRoot()
1242
+ });
1243
+ }
776
1244
  clearHostProblem(sourceKinds) {
777
1245
  if (!this.hostProblem) return;
778
1246
  if (sourceKinds && !sourceKinds.includes(this.hostProblem.sourceKind))
779
1247
  return;
780
1248
  const clearedProblem = this.hostProblem;
781
1249
  this.hostProblem = void 0;
782
- this.hostProblemHmrGeneration = 0;
1250
+ this.hostProblemWasNearRender = false;
783
1251
  this.publish();
784
1252
  this.publishHostProblemCleared(clearedProblem);
785
1253
  }
@@ -788,7 +1256,6 @@ var CanvasHostProblemTracker = class {
788
1256
  renderId,
789
1257
  createProblem(sourceKind, error, details)
790
1258
  );
791
- this.componentProblemHmrGenerations.set(renderId, this.hmrGeneration);
792
1259
  this.publish();
793
1260
  }
794
1261
  clearComponentProblem(renderId, sourceKinds) {
@@ -796,52 +1263,100 @@ var CanvasHostProblemTracker = class {
796
1263
  if (!problem) return;
797
1264
  if (sourceKinds && !sourceKinds.includes(problem.sourceKind)) return;
798
1265
  this.componentProblems.delete(renderId);
799
- this.componentProblemHmrGenerations.delete(renderId);
800
1266
  this.publish();
801
1267
  }
802
1268
  hasComponentProblem(renderId) {
803
1269
  return this.componentProblems.has(renderId);
804
1270
  }
1271
+ syncRenderSourcePaths(entries) {
1272
+ const next = new Map(
1273
+ entries.flatMap(
1274
+ (entry) => entry.sourcePaths?.length ? [[entry.renderId, entry.sourcePaths]] : []
1275
+ )
1276
+ );
1277
+ const changed = JSON.stringify([...this.registeredRenderSourcePaths]) !== JSON.stringify([...next]);
1278
+ if (!changed) return;
1279
+ this.registeredRenderSourcePaths = next;
1280
+ if (this.hostProblem && (this.hostProblemWasNearRender || isNearRenderProblemSourceKind(this.hostProblem.sourceKind)) && this.matchingRenderIds(this.hostProblem).length > 0) {
1281
+ this.publish();
1282
+ } else {
1283
+ this.publishIfViteProjectionChanged();
1284
+ }
1285
+ }
1286
+ matchingRenderIds(problem) {
1287
+ return findRenderIdsForProblem(
1288
+ problem,
1289
+ [...this.registeredRenderSourcePaths].flatMap(
1290
+ ([renderId, sourcePaths]) => sourcePaths.map((sourceFile) => ({ renderId, sourceFile }))
1291
+ )
1292
+ );
1293
+ }
1294
+ problemForMatchedRender(problem, renderId) {
1295
+ if (problem.sourceKind !== "unhandled-rejection" || !this.matchingDeclaredRenderIds(problem).includes(renderId)) {
1296
+ return problem;
1297
+ }
1298
+ return { ...problem, sourceKind: "render-error-boundary" };
1299
+ }
1300
+ matchingDeclaredRenderIds(problem) {
1301
+ return findRenderIdsForProblem(
1302
+ problem,
1303
+ [...this.registeredRenderSourcePaths].flatMap(
1304
+ ([renderId, sourcePaths]) => sourcePaths.map((sourceFile) => ({ renderId, sourceFile }))
1305
+ ),
1306
+ false
1307
+ );
1308
+ }
805
1309
  clearRecoveredComponentProblemsAfterRender(renderId) {
806
1310
  let changed = false;
807
1311
  const problem = this.componentProblems.get(renderId);
808
- if (problem && problem.sourceKind !== "render-error-boundary" && this.hmrGeneration > (this.componentProblemHmrGenerations.get(renderId) ?? this.hmrGeneration)) {
1312
+ if (problem && problem.sourceKind !== "render-error-boundary") {
809
1313
  this.componentProblems.delete(renderId);
810
- this.componentProblemHmrGenerations.delete(renderId);
811
1314
  changed = true;
812
1315
  }
813
1316
  if (this.clearRecoveredHostProblemAfterRender(renderId)) changed = true;
814
- if (changed) this.publish();
1317
+ if (changed) {
1318
+ this.publish();
1319
+ } else {
1320
+ this.publishIfViteProjectionChanged();
1321
+ }
815
1322
  }
816
- noteHmrUpdateStarted() {
817
- this.hmrGeneration += 1;
1323
+ reconcileViteOverlayProjection() {
1324
+ this.publishIfViteProjectionChanged();
818
1325
  }
819
1326
  dispose() {
820
1327
  this.watchers.clear();
821
1328
  this.hostProblemClearedWatchers.clear();
822
- }
823
- inspectCurrentProblems(options = {}) {
824
- const renderIdFilter = options.renderId ?? void 0;
825
- const currentRenderFailures = [];
826
- for (const [renderId, failure] of this.componentProblems) {
827
- if (renderIdFilter != null && renderId !== renderIdFilter) continue;
828
- currentRenderFailures.push({ renderId, failure });
829
- }
830
- const currentHostFailure = readCurrentViteOverlay() ?? this.hostProblem;
831
- return {
832
- ...currentHostFailure ? { currentHostFailure } : {},
833
- currentRenderFailures,
834
- currentCanvasFailures: [...this.canvasProblems].map(
835
- ([canvasPath, failure]) => ({ canvasPath, failure })
836
- ),
837
- observedAt: Date.now()
838
- };
1329
+ this.registeredCanvasPaths.clear();
1330
+ this.registeredRenderSourcePaths.clear();
839
1331
  }
840
1332
  publish() {
1333
+ this.publishedViteProjectionSignature = this.viteProjectionSignature();
841
1334
  for (const watcher of this.watchers) {
842
1335
  watcher();
843
1336
  }
844
1337
  }
1338
+ publishIfViteProjectionChanged() {
1339
+ const signature = this.viteProjectionSignature();
1340
+ if (this.publishedViteProjectionSignature === void 0) {
1341
+ this.publishedViteProjectionSignature = signature;
1342
+ return;
1343
+ }
1344
+ if (signature === this.publishedViteProjectionSignature) return;
1345
+ this.publish();
1346
+ }
1347
+ viteProjectionSignature() {
1348
+ const snapshot = this.snapshot();
1349
+ const identify = (problem) => [problem.sourceKind, problem.filename, problem.message].join("\0");
1350
+ return JSON.stringify({
1351
+ host: snapshot.hostProblem && isProjectedViteProblemSourceKind(snapshot.hostProblem.sourceKind) ? identify(snapshot.hostProblem) : null,
1352
+ components: snapshot.componentProblems.flatMap(
1353
+ ({ renderId, problem }) => isProjectedViteProblemSourceKind(problem.sourceKind) ? [[renderId, identify(problem)]] : []
1354
+ ),
1355
+ canvases: snapshot.canvasProblems.flatMap(
1356
+ ({ canvasPath, problem }) => isProjectedViteProblemSourceKind(problem.sourceKind) ? [[canvasPath, identify(problem)]] : []
1357
+ )
1358
+ });
1359
+ }
845
1360
  publishHostProblemCleared(problem) {
846
1361
  for (const watcher of this.hostProblemClearedWatchers) {
847
1362
  watcher(problem);
@@ -853,13 +1368,12 @@ var CanvasHostProblemTracker = class {
853
1368
  )) {
854
1369
  return false;
855
1370
  }
856
- if (this.hmrGeneration <= this.hostProblemHmrGeneration) return false;
857
- if (this.hostProblem.sourceKind === "vite-hmr-error" && findRenderIdForProblem(this.hostProblem) !== renderId) {
1371
+ const matchingRenderIds = this.matchingRenderIds(this.hostProblem);
1372
+ if (matchingRenderIds.length > 0 && !matchingRenderIds.includes(renderId))
858
1373
  return false;
859
- }
860
1374
  const clearedProblem = this.hostProblem;
861
1375
  this.hostProblem = void 0;
862
- this.hostProblemHmrGeneration = 0;
1376
+ this.hostProblemWasNearRender = false;
863
1377
  this.publishHostProblemCleared(clearedProblem);
864
1378
  return true;
865
1379
  }
@@ -870,39 +1384,113 @@ function createCanvasHostProblemTracker() {
870
1384
  function installCanvasHostRuntimeProblemTracking(tracker) {
871
1385
  if (typeof window === "undefined") return () => {
872
1386
  };
1387
+ const startupProblems = takeFrameStartupProblems();
873
1388
  const cleanupHostCapture = installHostProblemCapture(tracker);
874
- const cleanupCanvasImportCapture = installCanvasImportProblemCapture(tracker);
875
1389
  const cleanupViteCapture = installViteProblemCapture(tracker);
876
- const cleanupInspector = installCurrentProblemInspector(tracker);
1390
+ const cleanupViteErrorStream = installViteErrorStream(tracker);
1391
+ for (const problem of startupProblems) {
1392
+ tracker.reportProblemNearRender(
1393
+ problem.kind === "error" ? "page-error" : "unhandled-rejection",
1394
+ problem.message,
1395
+ {
1396
+ timestamp: problem.timestamp,
1397
+ stack: problem.stack,
1398
+ filename: problem.filename,
1399
+ line: problem.line,
1400
+ column: problem.column
1401
+ }
1402
+ );
1403
+ }
877
1404
  return () => {
878
1405
  cleanupHostCapture();
879
- cleanupCanvasImportCapture();
880
1406
  cleanupViteCapture();
881
- cleanupInspector();
882
- tracker.dispose();
1407
+ cleanupViteErrorStream();
883
1408
  };
884
1409
  }
885
- function installCanvasImportProblemCapture(tracker) {
886
- const onCanvasImportError = (event) => {
887
- const detail = event.detail;
888
- if (typeof detail !== "object" || detail === null) return;
889
- const canvasPath = typeof detail.canvasPath === "string" ? detail.canvasPath : "";
890
- if (!canvasPath) return;
891
- const message = typeof detail.message === "string" && detail.message ? detail.message : "Canvas module failed to load";
892
- tracker.reportCanvasProblem(canvasPath, "runtime-bootstrap", message, {
893
- stack: typeof detail.stack === "string" ? detail.stack : void 0,
894
- filename: canvasPath
1410
+ function installViteErrorStream(tracker) {
1411
+ if (typeof EventSource === "undefined") return () => {
1412
+ };
1413
+ const source = new EventSource("/__tempo/errors");
1414
+ source.onmessage = (event) => {
1415
+ let problem;
1416
+ try {
1417
+ problem = JSON.parse(event.data);
1418
+ } catch {
1419
+ return;
1420
+ }
1421
+ if (problem === null) {
1422
+ tracker.clearHostProblem(["vite-hmr-error"]);
1423
+ return;
1424
+ }
1425
+ if (typeof problem?.message !== "string") return;
1426
+ tracker.reportHostProblem("vite-hmr-error", problem.message, {
1427
+ stack: problem.stack,
1428
+ filename: problem.file ?? problem.loc?.file
895
1429
  });
896
1430
  };
897
- window.addEventListener("tempo:canvas-import-error", onCanvasImportError);
898
1431
  return () => {
899
- window.removeEventListener(
900
- "tempo:canvas-import-error",
901
- onCanvasImportError
902
- );
1432
+ source.close();
903
1433
  };
904
1434
  }
1435
+ function takeFrameStartupProblems() {
1436
+ const take = window.framePool?.takeStartupErrors;
1437
+ if (typeof take !== "function") return [];
1438
+ let value;
1439
+ try {
1440
+ value = take();
1441
+ } catch {
1442
+ return [];
1443
+ }
1444
+ if (!Array.isArray(value)) return [];
1445
+ return value.flatMap((candidate) => {
1446
+ if (!candidate || typeof candidate !== "object" || candidate.kind !== "error" && candidate.kind !== "unhandledrejection" || typeof candidate.message !== "string" || typeof candidate.timestamp !== "number") {
1447
+ return [];
1448
+ }
1449
+ const record = candidate;
1450
+ return [
1451
+ {
1452
+ kind: record.kind,
1453
+ timestamp: record.timestamp,
1454
+ message: record.message,
1455
+ ...typeof record.stack === "string" && { stack: record.stack },
1456
+ ...typeof record.filename === "string" && {
1457
+ filename: record.filename
1458
+ },
1459
+ ...typeof record.line === "number" && { line: record.line },
1460
+ ...typeof record.column === "number" && { column: record.column }
1461
+ }
1462
+ ];
1463
+ });
1464
+ }
905
1465
  var renderRecoveredHostProblemSourceKinds = ["page-error", "unhandled-rejection", "console-vite-error", "vite-hmr-error"];
1466
+ var FAILED_RELOAD_PROBE_DELAYS_MS = [50, 400, 1600];
1467
+ async function moduleTransformSucceeds(path) {
1468
+ const [pathname, query = ""] = path.split("?");
1469
+ const url = `${pathname}?${query ? `${query}&` : ""}t=${Date.now()}`;
1470
+ const response = await fetch(url, { cache: "no-store" });
1471
+ return response.ok;
1472
+ }
1473
+ async function compileErrorFileStillBroken(file) {
1474
+ const cleaned = file.replace(/:\d+(?::\d+)?$/, "");
1475
+ const candidates = cleaned.startsWith("/@") ? [cleaned] : [`/@fs${cleaned}`, cleaned];
1476
+ for (const candidate of candidates) {
1477
+ try {
1478
+ if (await moduleTransformSucceeds(candidate)) return false;
1479
+ } catch {
1480
+ return true;
1481
+ }
1482
+ }
1483
+ return true;
1484
+ }
1485
+ function isViteProblemSourceKind(sourceKind) {
1486
+ return sourceKind === "vite-hmr-error" || sourceKind === "console-vite-error";
1487
+ }
1488
+ function isNearRenderProblemSourceKind(sourceKind) {
1489
+ return sourceKind === "page-error" || sourceKind === "unhandled-rejection" || sourceKind === "console-vite-error";
1490
+ }
1491
+ function isProjectedViteProblemSourceKind(sourceKind) {
1492
+ return sourceKind === "vite-overlay" || isViteProblemSourceKind(sourceKind);
1493
+ }
906
1494
  function createProblem(sourceKind, error, details = {}) {
907
1495
  return {
908
1496
  sourceKind,
@@ -913,31 +1501,47 @@ function createProblem(sourceKind, error, details = {}) {
913
1501
  ...details
914
1502
  };
915
1503
  }
916
- function findRenderIdForProblem(problem) {
917
- if (typeof document === "undefined") return void 0;
918
- const haystack = [
919
- problem.message,
920
- problem.stack,
921
- problem.componentStack,
922
- problem.filename
923
- ].filter(Boolean).join("\n");
924
- if (!haystack) return void 0;
925
- for (const slot of document.querySelectorAll("[data-render-id]")) {
926
- const renderId = slot.getAttribute("data-render-id");
927
- if (!renderId) continue;
928
- const sourceFiles = getObservedSourceFiles(slot);
929
- if (sourceFiles.some(
930
- (sourceFile) => problemTextMentionsSource(haystack, sourceFile)
931
- )) {
932
- return renderId;
1504
+ function findRenderIdsForProblem(problem, registered = [], includeDom = true) {
1505
+ const observed = [
1506
+ ...registered
1507
+ ];
1508
+ if (includeDom && typeof document !== "undefined") {
1509
+ for (const slot of document.querySelectorAll("[data-render-id]")) {
1510
+ const renderId = slot.getAttribute("data-render-id");
1511
+ if (!renderId) continue;
1512
+ for (const sourceFile of getObservedSourceFiles2(slot)) {
1513
+ observed.push({ renderId, sourceFile });
1514
+ }
933
1515
  }
934
1516
  }
935
- return void 0;
1517
+ if (observed.length === 0) return [];
1518
+ const exactFilenameMatches = new Set(
1519
+ resolveUniqueDiagnosticSourceMatches(
1520
+ problem.filename ?? "",
1521
+ observed.map(({ sourceFile }) => sourceFile),
1522
+ {
1523
+ projectRoot: readTempoProjectRoot(),
1524
+ allowExtensionlessJsTs: true
1525
+ }
1526
+ )
1527
+ );
1528
+ if (exactFilenameMatches.size > 0) {
1529
+ return uniqueRenderIds(
1530
+ observed.filter(({ sourceFile }) => exactFilenameMatches.has(sourceFile))
1531
+ );
1532
+ }
1533
+ const filenameMatches = matchObservedRenderIds(
1534
+ problem.filename ?? "",
1535
+ observed
1536
+ );
1537
+ if (filenameMatches.length > 0) return filenameMatches;
1538
+ const haystack = [problem.message, problem.stack, problem.componentStack].filter(Boolean).join("\n");
1539
+ return matchObservedRenderIds(haystack, observed);
936
1540
  }
937
- var sourceAnnotationSelector = "[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]";
938
- function getObservedSourceFiles(slot) {
1541
+ var sourceAnnotationSelector2 = "[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]";
1542
+ function getObservedSourceFiles2(slot) {
939
1543
  const sourceFiles = /* @__PURE__ */ new Set();
940
- for (const element of slot.querySelectorAll(sourceAnnotationSelector)) {
1544
+ for (const element of slot.querySelectorAll(sourceAnnotationSelector2)) {
941
1545
  for (const attribute of [
942
1546
  "data-tempo-source-file",
943
1547
  "data-tempo-filepath",
@@ -952,10 +1556,30 @@ function getObservedSourceFiles(slot) {
952
1556
  }
953
1557
  return [...sourceFiles];
954
1558
  }
955
- function problemTextMentionsSource(text, sourceFile) {
956
- const normalizedSource = sourceFile.replace(/\\/g, "/");
957
- const basename = normalizedSource.split("/").pop() ?? normalizedSource;
958
- return text.includes(normalizedSource) || basename !== "" && text.includes(basename);
1559
+ function matchObservedRenderIds(text, observed) {
1560
+ const matches = new Set(
1561
+ resolveUniqueDiagnosticSourceMatches(
1562
+ text,
1563
+ observed.map(({ sourceFile }) => sourceFile),
1564
+ {
1565
+ projectRoot: readTempoProjectRoot(),
1566
+ allowExtensionlessJsTs: true
1567
+ }
1568
+ )
1569
+ );
1570
+ return uniqueRenderIds(
1571
+ observed.filter(({ sourceFile }) => matches.has(sourceFile))
1572
+ );
1573
+ }
1574
+ function readTempoProjectRoot() {
1575
+ if (typeof document === "undefined") return null;
1576
+ return document.querySelector('meta[name="tempo-source-identity-root"]')?.content.trim() || document.querySelector('meta[name="tempo-project-root"]')?.content.trim() || null;
1577
+ }
1578
+ function uniqueRenderIds(matches) {
1579
+ return [...new Set(matches.map(({ renderId }) => renderId))];
1580
+ }
1581
+ function normalizeCanvasPath(value) {
1582
+ return value.trim();
959
1583
  }
960
1584
  function installHostProblemCapture(tracker) {
961
1585
  const onError = (event) => {
@@ -987,7 +1611,7 @@ function installHostProblemCapture(tracker) {
987
1611
  return;
988
1612
  }
989
1613
  const url = target.getAttribute("src") || target.getAttribute("href") || "";
990
- const message = "Failed to load " + target.tagName.toLowerCase() + (url ? ": " + url : "");
1614
+ const message = `Failed to load ${target.tagName.toLowerCase()}${url ? `: ${url}` : ""}`;
991
1615
  const renderId = target.closest("[data-render-id]")?.getAttribute("data-render-id");
992
1616
  if (renderId) {
993
1617
  tracker.reportComponentProblem(renderId, "resource-load", message);
@@ -1002,7 +1626,7 @@ function installHostProblemCapture(tracker) {
1002
1626
  const families = faces.map((face) => face.family).filter(Boolean).join(", ");
1003
1627
  tracker.reportHostProblem(
1004
1628
  "resource-load",
1005
- "Failed to load font" + (families ? ": " + families : "")
1629
+ `Failed to load font${families ? `: ${families}` : ""}`
1006
1630
  );
1007
1631
  };
1008
1632
  const fontFaceSet = typeof document.fonts?.addEventListener === "function" ? document.fonts : void 0;
@@ -1021,15 +1645,7 @@ function installHostProblemCapture(tracker) {
1021
1645
  }
1022
1646
  function installViteProblemCapture(tracker) {
1023
1647
  const reconcileViteOverlay = () => {
1024
- const problem = readCurrentViteOverlay();
1025
- if (problem) {
1026
- tracker.reportHostProblem("vite-overlay", problem.message, {
1027
- stack: problem.stack,
1028
- filename: problem.filename
1029
- });
1030
- } else {
1031
- tracker.clearHostProblem(["vite-overlay"]);
1032
- }
1648
+ tracker.reconcileViteOverlayProjection();
1033
1649
  };
1034
1650
  const observer = new MutationObserver(reconcileViteOverlay);
1035
1651
  if (document.body) {
@@ -1037,26 +1653,16 @@ function installViteProblemCapture(tracker) {
1037
1653
  reconcileViteOverlay();
1038
1654
  void Promise.resolve().then(reconcileViteOverlay);
1039
1655
  }
1040
- const viteHmrFailedModules = /* @__PURE__ */ new Map();
1041
- const latestViteHmrFailure = () => {
1656
+ const evalFailedModules = /* @__PURE__ */ new Map();
1657
+ const latestEvaluationFailure = () => {
1042
1658
  let latest;
1043
- for (const problem of viteHmrFailedModules.values()) {
1659
+ for (const problem of evalFailedModules.values()) {
1044
1660
  if (!latest || problem.timestamp >= latest.timestamp) latest = problem;
1045
1661
  }
1046
1662
  return latest;
1047
1663
  };
1048
- const deleteViteHmrFailureForPath = (path) => {
1049
- let removed = false;
1050
- for (const key of [...viteHmrFailedModules.keys()]) {
1051
- if (key !== pathlessViteErrorKey && modulePathsMatch(key, path)) {
1052
- viteHmrFailedModules.delete(key);
1053
- removed = true;
1054
- }
1055
- }
1056
- return removed;
1057
- };
1058
- const reconcileViteHmrHostProblem = () => {
1059
- const latest = latestViteHmrFailure();
1664
+ const reconcileEvaluationHostProblem = () => {
1665
+ const latest = latestEvaluationFailure();
1060
1666
  if (latest) {
1061
1667
  tracker.reportHostProblem("vite-hmr-error", latest.message, latest);
1062
1668
  } else {
@@ -1064,188 +1670,90 @@ function installViteProblemCapture(tracker) {
1064
1670
  }
1065
1671
  };
1066
1672
  const failedReloadPattern = /^Failed to reload (.+?)\. This could be due to/;
1067
- const pathlessViteErrorKey = "__tempo:pathless-vite-error";
1068
- let viteHmrCycleActive = false;
1069
- let cycleFailedPaths = /* @__PURE__ */ new Map();
1070
- let lastCycleViteErrorDetail;
1071
- let hmrCycleSeq = 0;
1072
- const cleanUpdateCycleByPath = /* @__PURE__ */ new Map();
1073
- const onViteBeforeUpdate = () => {
1074
- viteHmrCycleActive = true;
1075
- hmrCycleSeq += 1;
1076
- cycleFailedPaths = /* @__PURE__ */ new Map();
1077
- lastCycleViteErrorDetail = void 0;
1078
- tracker.noteHmrUpdateStarted();
1079
- };
1080
- const onViteAfterUpdate = (payload) => {
1081
- const updatedPaths = readUpdatePaths(payload);
1082
- let shouldReconcile = false;
1083
- const failedThisCycle = [...cycleFailedPaths.keys()];
1084
- for (const updatedPath of updatedPaths) {
1085
- if (failedThisCycle.some((failed) => modulePathsMatch(failed, updatedPath))) {
1086
- continue;
1673
+ let lastViteConsoleErrorDetail = null;
1674
+ const stopClearedWatch = tracker.watchHostProblemCleared((problem) => {
1675
+ if (problem.sourceKind !== "vite-hmr-error") return;
1676
+ const removed = problem.filename ? evalFailedModules.delete(problem.filename) : false;
1677
+ if (!removed) return;
1678
+ queueMicrotask(reconcileEvaluationHostProblem);
1679
+ });
1680
+ const originalConsoleError = console.error;
1681
+ const patchedConsoleError = (...args) => {
1682
+ originalConsoleError(...args);
1683
+ const error = readViteConsoleError(args[0], args[1]);
1684
+ if (!error) return;
1685
+ const failedReload = failedReloadPattern.exec(error.message);
1686
+ if (failedReload) {
1687
+ const path = failedReload[1] ?? error.message;
1688
+ const detail = lastViteConsoleErrorDetail;
1689
+ lastViteConsoleErrorDetail = null;
1690
+ if (detail && !/failed to fetch/i.test(detail.message)) {
1691
+ const problem = createProblem("vite-hmr-error", detail.message, {
1692
+ stack: detail.stack,
1693
+ filename: path
1694
+ });
1695
+ evalFailedModules.set(path, problem);
1696
+ reconcileEvaluationHostProblem();
1697
+ getCanvasHostRecoveryFeed().publish({
1698
+ type: "module-load-failure",
1699
+ path,
1700
+ message: detail.message
1701
+ });
1702
+ return;
1087
1703
  }
1088
- cleanUpdateCycleByPath.set(normalizeModulePath(updatedPath), hmrCycleSeq);
1089
- for (const key of [...viteHmrFailedModules.keys()]) {
1090
- if (key === pathlessViteErrorKey) continue;
1091
- if (modulePathsMatch(key, updatedPath)) {
1092
- viteHmrFailedModules.delete(key);
1093
- shouldReconcile = true;
1094
- }
1095
- }
1096
- }
1097
- if (updatedPaths.length > 0 && !cycleFailedPaths.has(pathlessViteErrorKey)) {
1098
- if (viteHmrFailedModules.delete(pathlessViteErrorKey)) {
1099
- shouldReconcile = true;
1100
- }
1101
- }
1102
- for (const [path, problem] of cycleFailedPaths) {
1103
- viteHmrFailedModules.set(path, problem);
1104
- shouldReconcile = true;
1105
- void verifyModuleStillExists(path).then((exists) => {
1106
- if (exists) return;
1107
- if (deleteViteHmrFailureForPath(path)) {
1108
- reconcileViteHmrHostProblem();
1109
- }
1110
- });
1111
- }
1112
- viteHmrCycleActive = false;
1113
- cycleFailedPaths = /* @__PURE__ */ new Map();
1114
- if (shouldReconcile) reconcileViteHmrHostProblem();
1115
- };
1116
- const onViteError = (payload) => {
1117
- const error = readViteError(payload);
1118
- if (!error) return;
1119
- lastCycleViteErrorDetail = error;
1120
- const path = error.filename ?? pathlessViteErrorKey;
1121
- const problem = createProblem("vite-hmr-error", error.message, {
1122
- stack: error.stack,
1123
- filename: error.filename
1124
- });
1125
- if (viteHmrCycleActive) {
1126
- cycleFailedPaths.set(path, problem);
1127
- } else {
1128
- viteHmrFailedModules.set(path, problem);
1129
- }
1130
- reconcileViteHmrHostProblem();
1131
- };
1132
- let hotEventsCancelled = false;
1133
- let subscribedHot;
1134
- const subscribeHotEvents = (hot2) => {
1135
- subscribedHot = hot2;
1136
- hot2.on?.("vite:beforeUpdate", onViteBeforeUpdate);
1137
- hot2.on?.("vite:afterUpdate", onViteAfterUpdate);
1138
- hot2.on?.("vite:error", onViteError);
1139
- };
1140
- const hot = readViteHot();
1141
- if (hot?.on) {
1142
- subscribeHotEvents(hot);
1143
- } else {
1144
- void import(
1145
- /* @vite-ignore */
1146
- /* webpackIgnore: true */
1147
- /* turbopackIgnore: true */
1148
- "/@vite/client"
1149
- ).then((client) => {
1150
- const createHotContext = client.createHotContext;
1151
- const context = createHotContext?.("/__tempo-canvas-host__");
1152
- if (!context || hotEventsCancelled) return;
1153
- subscribeHotEvents(context);
1154
- }).catch(() => {
1155
- });
1156
- }
1157
- const stopClearedWatch = tracker.watchHostProblemCleared((problem) => {
1158
- if (problem.sourceKind !== "vite-hmr-error") return;
1159
- const filename = problem.filename;
1160
- let removed = false;
1161
- if (filename == null) {
1162
- removed = viteHmrFailedModules.delete(pathlessViteErrorKey);
1163
- } else {
1164
- removed = deleteViteHmrFailureForPath(filename);
1165
- }
1166
- if (!removed) return;
1167
- void Promise.resolve().then(reconcileViteHmrHostProblem);
1168
- });
1169
- const originalConsoleError = console.error;
1170
- const patchedConsoleError = (...args) => {
1171
- originalConsoleError(...args);
1172
- const error = readViteConsoleError(args[0], args[1]);
1173
- if (!error) return;
1174
- const failedReload = failedReloadPattern.exec(error.message);
1175
- if (failedReload) {
1176
- const path = failedReload[1];
1177
- const detail = lastCycleViteErrorDetail;
1178
- const problem = createProblem(
1179
- "vite-hmr-error",
1180
- detail?.message ?? "Failed to reload " + path,
1181
- {
1182
- stack: detail?.stack ?? error.stack,
1183
- filename: detail?.filename ?? path
1704
+ void (async () => {
1705
+ for (const delayMs of FAILED_RELOAD_PROBE_DELAYS_MS) {
1706
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1707
+ try {
1708
+ if (!await moduleTransformSucceeds(path)) continue;
1709
+ const snapshot = tracker.snapshot();
1710
+ const compileErrorFiles = /* @__PURE__ */ new Set();
1711
+ for (const problem of [
1712
+ snapshot.hostProblem,
1713
+ ...snapshot.componentProblems.map((entry) => entry.problem),
1714
+ ...snapshot.canvasProblems.map((entry) => entry.problem)
1715
+ ]) {
1716
+ if (!problem) continue;
1717
+ if (!isProjectedViteProblemSourceKind(problem.sourceKind)) {
1718
+ continue;
1719
+ }
1720
+ if (problem.filename) compileErrorFiles.add(problem.filename);
1721
+ }
1722
+ for (const file of compileErrorFiles) {
1723
+ if (await compileErrorFileStillBroken(file)) return;
1724
+ }
1725
+ getCanvasHostRecoveryFeed().publish({
1726
+ type: "module-update-dropped",
1727
+ path,
1728
+ message: error.message
1729
+ });
1730
+ return;
1731
+ } catch {
1732
+ return;
1733
+ }
1184
1734
  }
1185
- );
1186
- if (detail) {
1187
- cycleFailedPaths.set(path, problem);
1188
- viteHmrFailedModules.set(path, problem);
1189
- reconcileViteHmrHostProblem();
1190
- } else {
1191
- const observedCycleSeq = hmrCycleSeq;
1192
- void verifyModuleStillExists(path).then((exists) => {
1193
- const cleanSeq = cleanUpdateCycleByPath.get(
1194
- normalizeModulePath(path)
1195
- );
1196
- if (cleanSeq !== void 0 && cleanSeq > observedCycleSeq) return;
1197
- if (exists) viteHmrFailedModules.set(path, problem);
1198
- else viteHmrFailedModules.delete(path);
1199
- reconcileViteHmrHostProblem();
1200
- });
1201
- }
1735
+ })();
1202
1736
  return;
1203
1737
  }
1204
- if (viteHmrCycleActive) {
1205
- lastCycleViteErrorDetail = error;
1206
- return;
1207
- }
1208
- tracker.reportProblemNearRender("console-vite-error", error.message, {
1209
- stack: error.stack,
1210
- filename: error.filename
1738
+ lastViteConsoleErrorDetail = error;
1739
+ queueMicrotask(() => {
1740
+ if (lastViteConsoleErrorDetail !== error) return;
1741
+ lastViteConsoleErrorDetail = null;
1742
+ tracker.reportProblemNearRender("console-vite-error", error.message, {
1743
+ stack: error.stack,
1744
+ filename: error.filename
1745
+ });
1211
1746
  });
1212
1747
  };
1213
1748
  console.error = patchedConsoleError;
1214
1749
  return () => {
1215
1750
  observer.disconnect();
1216
1751
  stopClearedWatch();
1217
- hotEventsCancelled = true;
1218
- subscribedHot?.off?.("vite:beforeUpdate", onViteBeforeUpdate);
1219
- subscribedHot?.off?.("vite:afterUpdate", onViteAfterUpdate);
1220
- subscribedHot?.off?.("vite:error", onViteError);
1221
1752
  if (console.error === patchedConsoleError) {
1222
1753
  console.error = originalConsoleError;
1223
1754
  }
1224
1755
  };
1225
1756
  }
1226
- function installCurrentProblemInspector(tracker) {
1227
- const maybeWindow = window;
1228
- const previous = maybeWindow.__tempoErrorTrackingInspectCurrentProblems;
1229
- const inspect = (options = {}) => mergeCurrentProblemSnapshots(
1230
- tracker.inspectCurrentProblems(options),
1231
- previous?.(options) ?? null
1232
- );
1233
- maybeWindow.__tempoErrorTrackingInspectCurrentProblems = inspect;
1234
- return () => {
1235
- if (maybeWindow.__tempoErrorTrackingInspectCurrentProblems === inspect) {
1236
- maybeWindow.__tempoErrorTrackingInspectCurrentProblems = previous;
1237
- }
1238
- };
1239
- }
1240
- function readViteHot() {
1241
- const explicitHot = window.__tempoCanvasHostViteHot;
1242
- if (explicitHot) return explicitHot;
1243
- try {
1244
- return eval("import.meta && import.meta.hot");
1245
- } catch {
1246
- return void 0;
1247
- }
1248
- }
1249
1757
  function readCurrentViteOverlay() {
1250
1758
  if (typeof document === "undefined") return void 0;
1251
1759
  const overlay = document.querySelector("vite-error-overlay");
@@ -1300,77 +1808,9 @@ function readViteConsoleError(first, second) {
1300
1808
  filename: detail?.filename
1301
1809
  } : void 0;
1302
1810
  }
1303
- function readUpdatePaths(payload) {
1304
- const updates = typeof payload === "object" && payload !== null && Array.isArray(payload.updates) ? payload.updates : [];
1305
- const paths = /* @__PURE__ */ new Set();
1306
- const collectPath = (value) => {
1307
- if (typeof value === "string") paths.add(value);
1308
- };
1309
- for (const update of updates) {
1310
- collectPath(update.path);
1311
- collectPath(update.acceptedPath);
1312
- collectPath(update.id);
1313
- }
1314
- return [...paths];
1315
- }
1316
- function normalizeModulePath(value) {
1317
- const cutIndex = value.search(/[?#]/);
1318
- return cutIndex === -1 ? value : value.slice(0, cutIndex);
1319
- }
1320
- function modulePathsMatch(a, b) {
1321
- const left = normalizeModulePath(a);
1322
- const right = normalizeModulePath(b);
1323
- if (!left || !right) return false;
1324
- if (left === right) return true;
1325
- const [longer, shorter] = left.length >= right.length ? [left, right] : [right, left];
1326
- return shorter.startsWith("/") && longer.endsWith(shorter);
1327
- }
1328
- async function verifyModuleStillExists(path) {
1329
- if (typeof fetch !== "function") return true;
1330
- try {
1331
- const response = await fetch(path, { cache: "no-store" });
1332
- if ("ok" in response && response.ok === false) return false;
1333
- const contentType = response.headers.get("content-type") || "";
1334
- return !contentType.includes("text/html");
1335
- } catch {
1336
- return true;
1337
- }
1338
- }
1339
- function mergeCurrentProblemSnapshots(primary, fallback) {
1340
- if (!fallback) return primary;
1341
- const currentRenderFailures = [...primary.currentRenderFailures];
1342
- const seen = new Set(
1343
- currentRenderFailures.map(
1344
- (entry) => `${entry.renderId ?? ""}:${entry.failure.sourceKind}:${entry.failure.message}`
1345
- )
1346
- );
1347
- for (const entry of fallback.currentRenderFailures) {
1348
- const key = `${entry.renderId ?? ""}:${entry.failure.sourceKind}:${entry.failure.message}`;
1349
- if (seen.has(key)) continue;
1350
- seen.add(key);
1351
- currentRenderFailures.push(entry);
1352
- }
1353
- const currentCanvasFailures = [...primary.currentCanvasFailures ?? []];
1354
- const seenCanvas = new Set(
1355
- currentCanvasFailures.map(
1356
- (entry) => `${entry.canvasPath}:${entry.failure.sourceKind}:${entry.failure.message}`
1357
- )
1358
- );
1359
- for (const entry of fallback.currentCanvasFailures ?? []) {
1360
- const key = `${entry.canvasPath}:${entry.failure.sourceKind}:${entry.failure.message}`;
1361
- if (seenCanvas.has(key)) continue;
1362
- seenCanvas.add(key);
1363
- currentCanvasFailures.push(entry);
1364
- }
1365
- return {
1366
- currentHostFailure: primary.currentHostFailure ?? fallback.currentHostFailure,
1367
- currentRenderFailures,
1368
- currentCanvasFailures,
1369
- observedAt: Math.max(primary.observedAt, fallback.observedAt)
1370
- };
1371
- }
1372
1811
 
1373
1812
  // canvas/use-canvas-host-postmessage.ts
1813
+ var DEFAULT_MAX_CACHED_RENDERS = 20;
1374
1814
  function postToMessageSource(source, response, targetOrigin) {
1375
1815
  const origin = safePostMessageTargetOrigin(targetOrigin);
1376
1816
  if (source && "postMessage" in source && source !== window) {
@@ -1386,39 +1826,101 @@ function safePostMessageTargetOrigin(targetOrigin) {
1386
1826
  const currentOrigin = window.location.origin;
1387
1827
  return currentOrigin && currentOrigin !== "null" ? currentOrigin : "*";
1388
1828
  }
1829
+ function acknowledgeWatchEstablishment(request) {
1830
+ if (request.establishment.status !== "pending") return;
1831
+ request.establishment.status = "established";
1832
+ postToMessageSource(
1833
+ request.source,
1834
+ {
1835
+ type: "render-pool:ack",
1836
+ requestId: request.requestId,
1837
+ command: request.commandType
1838
+ },
1839
+ request.targetOrigin
1840
+ );
1841
+ }
1842
+ function rejectWatchEstablishment(request, error) {
1843
+ if (request.establishment.status !== "pending") return;
1844
+ request.establishment.status = "failed";
1845
+ postWatchError(request, error);
1846
+ }
1847
+ function postWatchError(request, error) {
1848
+ postToMessageSource(
1849
+ request.source,
1850
+ {
1851
+ type: "render-pool:error",
1852
+ requestId: request.requestId,
1853
+ watchId: request.watchId,
1854
+ command: request.commandType,
1855
+ error: error.message
1856
+ },
1857
+ request.targetOrigin
1858
+ );
1859
+ }
1860
+ function readWatchResumeOptions(payload) {
1861
+ const flush = payload.flush;
1862
+ const triggers = Array.isArray(payload.triggers) ? payload.triggers.filter(
1863
+ (trigger) => trigger === "viewport-capture"
1864
+ ) : [];
1865
+ const validFlush = flush === "always" || flush === "if-dirty" || flush === "never" ? flush : void 0;
1866
+ return validFlush === void 0 && triggers.length === 0 ? void 0 : { flush: validFlush, triggers };
1867
+ }
1868
+ function setRuntimeWatchPaused(watch, paused, resumeOptions) {
1869
+ if (watch.setPaused) {
1870
+ if (resumeOptions === void 0) {
1871
+ watch.setPaused(paused);
1872
+ } else {
1873
+ watch.setPaused(paused, resumeOptions);
1874
+ }
1875
+ } else if (paused) {
1876
+ watch.pause?.();
1877
+ } else {
1878
+ if (resumeOptions === void 0) {
1879
+ watch.resume?.();
1880
+ } else {
1881
+ watch.resume?.(resumeOptions);
1882
+ }
1883
+ }
1884
+ }
1389
1885
  function useCanvasHostPostMessage() {
1390
- const [renderEntriesById, setRenderEntriesById] = useState(
1886
+ const [renderEntriesById, setRenderEntriesById] = useState2(
1391
1887
  () => /* @__PURE__ */ new Map()
1392
1888
  );
1393
- const [watchRequestsById, setWatchRequestsById] = useState(
1889
+ const [watchRequestsById, setWatchRequestsById] = useState2(
1394
1890
  () => /* @__PURE__ */ new Map()
1395
1891
  );
1396
- const [renderCommitVersionById, setRenderCommitVersionById] = useState(
1892
+ const [renderCommitVersionById, setRenderCommitVersionById] = useState2(
1397
1893
  () => /* @__PURE__ */ new Map()
1398
1894
  );
1399
- const renderEntriesRef = useRef(renderEntriesById);
1400
- const watchRequestsRef = useRef(watchRequestsById);
1401
- const maxCachedRef = useRef(20);
1402
- const renderedRenderIdsRef = useRef(/* @__PURE__ */ new Set());
1403
- const pendingRenderAcksRef = useRef(/* @__PURE__ */ new Map());
1404
- const watchesRef = useRef(/* @__PURE__ */ new Map());
1405
- const problemWatchersRef = useRef(/* @__PURE__ */ new Map());
1406
- const problemTrackerRef = useRef(createCanvasHostProblemTracker());
1407
- const renderCommitTimesRef = useRef(/* @__PURE__ */ new Map());
1408
- const sourceAnnotatedCommitTimesRef = useRef(/* @__PURE__ */ new Map());
1409
- const buildProblemSnapshot = useCallback2(
1410
- () => problemTrackerRef.current.snapshot(),
1411
- []
1895
+ const renderEntriesRef = useRef2(renderEntriesById);
1896
+ const watchRequestsRef = useRef2(watchRequestsById);
1897
+ const maxCachedRef = useRef2(DEFAULT_MAX_CACHED_RENDERS);
1898
+ const legacyHealthRef = useRef2(createLegacyHostHealth());
1899
+ const renderedRenderIdsRef = useRef2(/* @__PURE__ */ new Set());
1900
+ const pendingRenderWaitersRef = useRef2(
1901
+ /* @__PURE__ */ new Map()
1412
1902
  );
1413
- const recordSourceAnnotatedCommit = useCallback2(
1414
- (renderId, observedAt = Date.now()) => {
1415
- if (renderSlotHasSourceAnnotations(renderId)) {
1416
- sourceAnnotatedCommitTimesRef.current.set(renderId, observedAt);
1417
- }
1903
+ const watchesRef = useRef2(/* @__PURE__ */ new Map());
1904
+ const startingWatchesRef = useRef2(
1905
+ /* @__PURE__ */ new Map()
1906
+ );
1907
+ const problemWatchersRef = useRef2(/* @__PURE__ */ new Map());
1908
+ const problemTrackerRef = useRef2(createCanvasHostProblemTracker());
1909
+ const updateWatchRequests = useCallback3(
1910
+ (update) => {
1911
+ const current = watchRequestsRef.current;
1912
+ const next = update(current);
1913
+ if (next === current) return;
1914
+ watchRequestsRef.current = next;
1915
+ setWatchRequestsById(next);
1418
1916
  },
1419
1917
  []
1420
1918
  );
1421
- const publishProblemSnapshot = useCallback2(() => {
1919
+ const buildProblemSnapshot = useCallback3(
1920
+ () => problemTrackerRef.current.snapshot(),
1921
+ []
1922
+ );
1923
+ const publishProblemSnapshot = useCallback3(() => {
1422
1924
  const payload = buildProblemSnapshot();
1423
1925
  for (const watcher of problemWatchersRef.current.values()) {
1424
1926
  postToMessageSource(
@@ -1433,16 +1935,16 @@ function useCanvasHostPostMessage() {
1433
1935
  );
1434
1936
  }
1435
1937
  }, [buildProblemSnapshot]);
1436
- const setEntries = useCallback2(
1938
+ const setEntries = useCallback3(
1437
1939
  (update) => {
1438
1940
  setRenderEntriesById((entries) => {
1439
1941
  const next = update(entries);
1440
1942
  renderEntriesRef.current = next;
1943
+ problemTrackerRef.current.syncRenderSourcePaths([...next.values()]);
1441
1944
  for (const renderId of [...renderedRenderIdsRef.current]) {
1442
1945
  if (!next.has(renderId)) {
1443
1946
  renderedRenderIdsRef.current.delete(renderId);
1444
- renderCommitTimesRef.current.delete(renderId);
1445
- sourceAnnotatedCommitTimesRef.current.delete(renderId);
1947
+ legacyHealthRef.current.forgetRender(renderId);
1446
1948
  }
1447
1949
  }
1448
1950
  return next;
@@ -1450,7 +1952,7 @@ function useCanvasHostPostMessage() {
1450
1952
  },
1451
1953
  []
1452
1954
  );
1453
- const waitForRender = useCallback2(
1955
+ const waitForRender = useCallback3(
1454
1956
  (request) => {
1455
1957
  const current = renderEntriesRef.current.get(request.renderId);
1456
1958
  const alreadyRendered = current?.status === "active" && renderedRenderIdsRef.current.has(request.renderId) && renderRequestMatchesEntry(current, request);
@@ -1459,14 +1961,14 @@ function useCanvasHostPostMessage() {
1459
1961
  return Promise.resolve();
1460
1962
  }
1461
1963
  return new Promise((resolve, reject) => {
1462
- const pendingAcks = pendingRenderAcksRef.current.get(request.renderId) ?? [];
1463
- pendingAcks.push({ resolve, reject });
1464
- pendingRenderAcksRef.current.set(request.renderId, pendingAcks);
1964
+ const pendingWaiters = pendingRenderWaitersRef.current.get(request.renderId) ?? [];
1965
+ pendingWaiters.push({ resolve, reject });
1966
+ pendingRenderWaitersRef.current.set(request.renderId, pendingWaiters);
1465
1967
  });
1466
1968
  },
1467
1969
  [setEntries]
1468
1970
  );
1469
- const releaseRenderLease = useCallback2(
1971
+ const releaseRenderLease = useCallback3(
1470
1972
  (renderId) => {
1471
1973
  setEntries(
1472
1974
  (entries) => releaseRender(entries, renderId, maxCachedRef.current)
@@ -1474,79 +1976,107 @@ function useCanvasHostPostMessage() {
1474
1976
  },
1475
1977
  [setEntries]
1476
1978
  );
1477
- const stopRuntimeWatch = useCallback2(async (watchId) => {
1478
- const existingWatch = watchesRef.current.get(watchId);
1479
- if (!existingWatch) return;
1480
- watchesRef.current.delete(watchId);
1481
- await existingWatch.watch.stop();
1482
- }, []);
1483
- const removeWatchRequest = useCallback2(
1484
- async (watchId) => {
1979
+ const stopRuntimeWatch = useCallback3(
1980
+ async (watchId, establishment) => {
1981
+ const existingWatch = watchesRef.current.get(watchId);
1982
+ if (!existingWatch || establishment && existingWatch.establishment !== establishment) {
1983
+ return;
1984
+ }
1985
+ watchesRef.current.delete(watchId);
1986
+ await existingWatch.watch.stop();
1987
+ },
1988
+ []
1989
+ );
1990
+ const removeWatchRequest = useCallback3(
1991
+ async (watchId, reason) => {
1485
1992
  const existingRequest = watchRequestsRef.current.get(watchId);
1993
+ if (existingRequest) {
1994
+ rejectWatchEstablishment(
1995
+ existingRequest,
1996
+ reason ?? new Error(
1997
+ `Canvas host watch ${watchId} was cancelled before establishment`
1998
+ )
1999
+ );
2000
+ }
1486
2001
  try {
1487
- await stopRuntimeWatch(watchId);
2002
+ await stopRuntimeWatch(watchId, existingRequest?.establishment);
1488
2003
  } finally {
1489
- if (!existingRequest) return;
1490
- setWatchRequestsById((requests) => {
1491
- const next = new Map(requests);
1492
- next.delete(watchId);
1493
- watchRequestsRef.current = next;
1494
- return next;
1495
- });
1496
- releaseRenderLease(existingRequest.request.renderId);
2004
+ if (existingRequest) {
2005
+ updateWatchRequests((requests) => {
2006
+ if (requests.get(watchId)?.establishment !== existingRequest.establishment) {
2007
+ return requests;
2008
+ }
2009
+ const next = new Map(requests);
2010
+ next.delete(watchId);
2011
+ return next;
2012
+ });
2013
+ releaseRenderLease(existingRequest.request.renderId);
2014
+ }
1497
2015
  }
1498
2016
  },
1499
- [releaseRenderLease, stopRuntimeWatch]
2017
+ [releaseRenderLease, stopRuntimeWatch, updateWatchRequests]
1500
2018
  );
1501
- const buildState = useCallback2(
2019
+ const suspendEstablishedWatch = useCallback3(
2020
+ (request) => {
2021
+ if (request.establishment.status !== "established") return;
2022
+ void stopRuntimeWatch(request.watchId, request.establishment).catch(
2023
+ () => {
2024
+ }
2025
+ );
2026
+ },
2027
+ [stopRuntimeWatch]
2028
+ );
2029
+ const buildState = useCallback3(
1502
2030
  () => buildRenderStatePayload(renderEntriesRef.current, maxCachedRef.current),
1503
2031
  []
1504
2032
  );
1505
- const buildHealthSnapshot = useCallback2((renderId) => {
1506
- const slot = renderId ? document.querySelector(buildRenderContentSelector(renderId)) : null;
1507
- const observedSourceFiles = getObservedSourceFiles2(slot);
1508
- return {
1509
- alive: true,
1510
- reactConnected: isReactConnected() || renderCommitTimesRef.current.size > 0 || renderEntriesRef.current.size > 0,
1511
- documentReadyState: document.readyState,
1512
- hasViteOverlayElement: document.querySelector("vite-error-overlay") !== null,
1513
- lastHostRenderCommitAt: latestTimestamp(renderCommitTimesRef.current),
1514
- lastClaimRenderCommitAt: renderCommitTimesRef.current.get(renderId) ?? null,
1515
- lastHostSourceAnnotatedCommitAt: latestTimestamp(
1516
- sourceAnnotatedCommitTimesRef.current
1517
- ),
1518
- lastClaimSourceAnnotatedCommitAt: sourceAnnotatedCommitTimesRef.current.get(renderId) ?? null,
1519
- renderSlotExists: slot !== null,
1520
- renderSlotHasSourceAnnotatedContent: observedSourceFiles.length > 0,
1521
- renderSlotObservedSourceFiles: observedSourceFiles,
1522
- claimErrorBoundaryTripped: problemTrackerRef.current.hasComponentProblem(renderId),
1523
- observedAt: Date.now()
1524
- };
2033
+ const markStoryboardRendered = useCallback3((storyboardId) => {
2034
+ renderedRenderIdsRef.current.add(storyboardId);
2035
+ legacyHealthRef.current.recordRenderCommit(storyboardId);
2036
+ setRenderCommitVersionById((versions) => {
2037
+ const next = new Map(versions);
2038
+ next.set(storyboardId, (next.get(storyboardId) ?? 0) + 1);
2039
+ return next;
2040
+ });
2041
+ problemTrackerRef.current.clearRecoveredComponentProblemsAfterRender(
2042
+ storyboardId
2043
+ );
2044
+ const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);
2045
+ if (!pendingWaiters) return;
2046
+ pendingRenderWaitersRef.current.delete(storyboardId);
2047
+ for (const waiter of pendingWaiters) {
2048
+ waiter.resolve();
2049
+ }
1525
2050
  }, []);
1526
- const markStoryboardRendered = useCallback2(
2051
+ const markStoryboardUnmounted = useCallback3(
1527
2052
  (storyboardId) => {
1528
- const committedAt = Date.now();
1529
- renderedRenderIdsRef.current.add(storyboardId);
1530
- renderCommitTimesRef.current.set(storyboardId, committedAt);
1531
- recordSourceAnnotatedCommit(storyboardId, committedAt);
1532
- setRenderCommitVersionById((versions) => {
1533
- const next = new Map(versions);
1534
- next.set(storyboardId, (next.get(storyboardId) ?? 0) + 1);
1535
- return next;
2053
+ queueMicrotask(() => {
2054
+ const remounted = [
2055
+ ...document.querySelectorAll("[data-render-id]")
2056
+ ].some(
2057
+ (element) => element.getAttribute("data-render-id") === storyboardId
2058
+ );
2059
+ if (remounted) return;
2060
+ renderedRenderIdsRef.current.delete(storyboardId);
2061
+ for (const request of watchRequestsRef.current.values()) {
2062
+ if (request.request.renderId === storyboardId) {
2063
+ suspendEstablishedWatch(request);
2064
+ }
2065
+ }
2066
+ const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);
2067
+ if (!pendingWaiters) return;
2068
+ pendingRenderWaitersRef.current.delete(storyboardId);
2069
+ const error = new Error(
2070
+ `Storyboard ${JSON.stringify(storyboardId)} unmounted before its requested render committed`
2071
+ );
2072
+ for (const waiter of pendingWaiters) {
2073
+ waiter.reject(error);
2074
+ }
1536
2075
  });
1537
- problemTrackerRef.current.clearRecoveredComponentProblemsAfterRender(
1538
- storyboardId
1539
- );
1540
- const pendingAcks = pendingRenderAcksRef.current.get(storyboardId);
1541
- if (!pendingAcks) return;
1542
- pendingRenderAcksRef.current.delete(storyboardId);
1543
- for (const ack of pendingAcks) {
1544
- ack.resolve();
1545
- }
1546
2076
  },
1547
- [recordSourceAnnotatedCommit]
2077
+ [suspendEstablishedWatch]
1548
2078
  );
1549
- const reportStoryboardError = useCallback2(
2079
+ const reportStoryboardError = useCallback3(
1550
2080
  (storyboardId, error) => {
1551
2081
  renderedRenderIdsRef.current.delete(storyboardId);
1552
2082
  problemTrackerRef.current.reportComponentProblem(
@@ -1558,28 +2088,79 @@ function useCanvasHostPostMessage() {
1558
2088
  componentStack: error.componentStack
1559
2089
  }
1560
2090
  );
1561
- const pendingAcks = pendingRenderAcksRef.current.get(storyboardId);
1562
- if (pendingAcks) {
1563
- pendingRenderAcksRef.current.delete(storyboardId);
1564
- const renderError = new Error(error.message);
1565
- for (const ack of pendingAcks) {
1566
- ack.reject(renderError);
2091
+ const renderError = new Error(error.message);
2092
+ const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);
2093
+ if (pendingWaiters) {
2094
+ pendingRenderWaitersRef.current.delete(storyboardId);
2095
+ for (const waiter of pendingWaiters) {
2096
+ waiter.reject(renderError);
2097
+ }
2098
+ }
2099
+ for (const request of watchRequestsRef.current.values()) {
2100
+ if (request.request.renderId !== storyboardId || request.establishment.status === "failed") {
2101
+ continue;
2102
+ }
2103
+ if (request.establishment.status === "pending") {
2104
+ rejectWatchEstablishment(request, renderError);
2105
+ void removeWatchRequest(request.watchId, renderError);
2106
+ } else {
2107
+ postWatchError(request, renderError);
2108
+ suspendEstablishedWatch(request);
1567
2109
  }
1568
2110
  }
1569
2111
  },
2112
+ [removeWatchRequest, suspendEstablishedWatch]
2113
+ );
2114
+ const clearStoryboardError = useCallback3((storyboardId) => {
2115
+ problemTrackerRef.current.clearComponentProblem(storyboardId, [
2116
+ "render-error-boundary"
2117
+ ]);
2118
+ }, []);
2119
+ const reportCanvasImportError = useCallback3(
2120
+ (canvasPath, error) => {
2121
+ const normalizedPath = canvasPath.trim();
2122
+ if (!normalizedPath) return;
2123
+ problemTrackerRef.current.reportCanvasProblem(
2124
+ normalizedPath,
2125
+ "runtime-bootstrap",
2126
+ error.message,
2127
+ {
2128
+ stack: error.stack,
2129
+ componentStack: error.componentStack,
2130
+ filename: normalizedPath
2131
+ }
2132
+ );
2133
+ },
1570
2134
  []
1571
2135
  );
1572
- const clearStoryboardError = useCallback2(
1573
- (storyboardId) => {
1574
- problemTrackerRef.current.clearComponentProblem(storyboardId, [
1575
- "render-error-boundary"
1576
- ]);
2136
+ const clearCanvasImportError = useCallback3((canvasPath) => {
2137
+ const normalizedPath = canvasPath.trim();
2138
+ if (!normalizedPath) return;
2139
+ problemTrackerRef.current.clearCanvasProblem(normalizedPath, [
2140
+ "runtime-bootstrap"
2141
+ ]);
2142
+ }, []);
2143
+ const registerCanvasProblemScope = useCallback3(
2144
+ (canvasPath) => problemTrackerRef.current.registerCanvasPath(canvasPath),
2145
+ []
2146
+ );
2147
+ useEffect2(
2148
+ () => () => {
2149
+ problemTrackerRef.current.dispose();
1577
2150
  },
1578
2151
  []
1579
2152
  );
1580
- useEffect(() => {
2153
+ useLayoutEffect2(() => {
2154
+ if (typeof window === "undefined") return;
2155
+ const stopRuntimeProblemTracking = installCanvasHostRuntimeProblemTracking(
2156
+ problemTrackerRef.current
2157
+ );
2158
+ return () => {
2159
+ stopRuntimeProblemTracking();
2160
+ };
2161
+ }, []);
2162
+ useEffect2(() => {
1581
2163
  if (typeof window === "undefined") return;
1582
- let cancelled = false;
1583
2164
  const activeWatchIds = new Set(watchRequestsById.keys());
1584
2165
  for (const watchId of watchesRef.current.keys()) {
1585
2166
  if (!activeWatchIds.has(watchId)) {
@@ -1587,18 +2168,40 @@ function useCanvasHostPostMessage() {
1587
2168
  }
1588
2169
  }
1589
2170
  for (const request of watchRequestsById.values()) {
2171
+ if (request.establishment.status === "failed") continue;
1590
2172
  const renderEntry = renderEntriesById.get(request.request.renderId);
1591
- const renderReady = renderEntry?.status === "active" && renderedRenderIdsRef.current.has(request.request.renderId) && renderRequestMatchesEntry(renderEntry, request.request);
2173
+ const renderReady = renderEntry?.status === "active" && renderedRenderIdsRef.current.has(request.request.renderId) && renderRequestTargetsEntry(renderEntry, request.request);
1592
2174
  if (!renderReady) continue;
1593
2175
  const existing = watchesRef.current.get(request.watchId);
1594
- if (existing?.bindingKey === request.bindingKey) continue;
2176
+ if (existing?.bindingKey === request.bindingKey && existing.establishment === request.establishment) {
2177
+ const currentRequest = watchRequestsRef.current.get(request.watchId);
2178
+ if (currentRequest?.establishment !== request.establishment) continue;
2179
+ if (currentRequest.paused) setRuntimeWatchPaused(existing.watch, true);
2180
+ acknowledgeWatchEstablishment(currentRequest);
2181
+ continue;
2182
+ }
2183
+ if (!existing && request.paused) continue;
2184
+ const starting = startingWatchesRef.current.get(request.watchId);
2185
+ if (starting?.bindingKey === request.bindingKey && starting.establishment === request.establishment) {
2186
+ continue;
2187
+ }
2188
+ const startToken = {
2189
+ bindingKey: request.bindingKey,
2190
+ establishment: request.establishment
2191
+ };
2192
+ startingWatchesRef.current.set(request.watchId, startToken);
1595
2193
  void (async () => {
1596
2194
  if (existing) {
1597
- await stopRuntimeWatch(request.watchId);
2195
+ await stopRuntimeWatch(request.watchId, existing.establishment);
1598
2196
  }
1599
- if (cancelled) return;
1600
2197
  const onUpdate = (capture) => {
1601
- recordSourceAnnotatedCommit(request.request.renderId);
2198
+ const currentRequest2 = watchRequestsRef.current.get(request.watchId);
2199
+ if (currentRequest2?.establishment !== request.establishment || currentRequest2.establishment.status === "failed") {
2200
+ return;
2201
+ }
2202
+ legacyHealthRef.current.recordSourceAnnotatedCommit(
2203
+ request.request.renderId
2204
+ );
1602
2205
  postToMessageSource(
1603
2206
  request.source,
1604
2207
  {
@@ -1612,17 +2215,14 @@ function useCanvasHostPostMessage() {
1612
2215
  );
1613
2216
  };
1614
2217
  const onError = (error) => {
1615
- postToMessageSource(
1616
- request.source,
1617
- {
1618
- type: "render-pool:error",
1619
- requestId: request.requestId,
1620
- watchId: request.watchId,
1621
- command: request.commandType,
1622
- error: error.message
1623
- },
1624
- request.targetOrigin
1625
- );
2218
+ const currentRequest2 = watchRequestsRef.current.get(request.watchId);
2219
+ if (currentRequest2?.establishment !== request.establishment) return;
2220
+ if (currentRequest2.establishment.status === "pending") {
2221
+ rejectWatchEstablishment(currentRequest2, error);
2222
+ void removeWatchRequest(request.watchId, error);
2223
+ return;
2224
+ }
2225
+ postWatchError(request, error);
1626
2226
  };
1627
2227
  const common = {
1628
2228
  onUpdate,
@@ -1637,44 +2237,47 @@ function useCanvasHostPostMessage() {
1637
2237
  fiberTags: Array.isArray(request.payload.fiberTags) ? request.payload.fiberTags : void 0,
1638
2238
  knownSourceVersion: typeof request.payload.knownSourceVersion === "object" && request.payload.knownSourceVersion !== null ? request.payload.knownSourceVersion : void 0
1639
2239
  });
1640
- if (cancelled || !watchRequestsRef.current.has(request.watchId)) {
2240
+ const currentRequest = watchRequestsRef.current.get(request.watchId);
2241
+ if (currentRequest?.establishment !== request.establishment || currentRequest.establishment.status === "failed") {
1641
2242
  await watch.stop();
1642
2243
  return;
1643
2244
  }
1644
2245
  watchesRef.current.set(request.watchId, {
1645
2246
  renderId: request.request.renderId,
1646
2247
  bindingKey: request.bindingKey,
2248
+ establishment: request.establishment,
1647
2249
  watch
1648
2250
  });
1649
- if (request.paused) {
1650
- if (watch.setPaused) watch.setPaused(true);
1651
- else watch.pause?.();
2251
+ if (currentRequest.paused) {
2252
+ setRuntimeWatchPaused(watch, true);
1652
2253
  }
2254
+ acknowledgeWatchEstablishment(currentRequest);
1653
2255
  })().catch((caught) => {
1654
- postToMessageSource(
1655
- request.source,
1656
- {
1657
- type: "render-pool:error",
1658
- requestId: request.requestId,
1659
- watchId: request.watchId,
1660
- command: request.commandType,
1661
- error: caught instanceof Error ? caught.message : String(caught)
1662
- },
1663
- request.targetOrigin
1664
- );
2256
+ const currentRequest = watchRequestsRef.current.get(request.watchId);
2257
+ if (currentRequest?.establishment !== request.establishment) {
2258
+ return;
2259
+ }
2260
+ const error = caught instanceof Error ? caught : new Error(String(caught));
2261
+ if (currentRequest.establishment.status === "pending") {
2262
+ rejectWatchEstablishment(currentRequest, error);
2263
+ } else {
2264
+ postWatchError(currentRequest, error);
2265
+ }
2266
+ void removeWatchRequest(request.watchId, error);
2267
+ }).finally(() => {
2268
+ if (startingWatchesRef.current.get(request.watchId) === startToken) {
2269
+ startingWatchesRef.current.delete(request.watchId);
2270
+ }
1665
2271
  });
1666
2272
  }
1667
- return () => {
1668
- cancelled = true;
1669
- };
1670
2273
  }, [
1671
- recordSourceAnnotatedCommit,
1672
2274
  renderCommitVersionById,
1673
2275
  renderEntriesById,
2276
+ removeWatchRequest,
1674
2277
  stopRuntimeWatch,
1675
2278
  watchRequestsById
1676
2279
  ]);
1677
- useEffect(() => {
2280
+ useEffect2(() => {
1678
2281
  if (typeof window === "undefined") return;
1679
2282
  const waitForRenderLease = async (request) => {
1680
2283
  try {
@@ -1711,18 +2314,16 @@ function useCanvasHostPostMessage() {
1711
2314
  const postAsyncError = (caught) => {
1712
2315
  error(caught instanceof Error ? caught.message : String(caught));
1713
2316
  };
1714
- const postCaptureResult = (capture) => post({
1715
- type: "render-pool:capture-result",
1716
- requestId: command.requestId,
1717
- command: command.type,
1718
- payload: { capture }
1719
- });
2317
+ const postCaptureResult = (renderId) => (capture) => {
2318
+ legacyHealthRef.current.recordSourceAnnotatedCommit(renderId);
2319
+ post({
2320
+ type: "render-pool:capture-result",
2321
+ requestId: command.requestId,
2322
+ command: command.type,
2323
+ payload: { capture }
2324
+ });
2325
+ };
1720
2326
  try {
1721
- if (command.type === "render-pool:render") {
1722
- const request = readRenderRequest(command.type, payload);
1723
- void waitForRenderLease(request).then(ack).catch(postAsyncError);
1724
- return;
1725
- }
1726
2327
  if (command.type === "render-pool:capture-image") {
1727
2328
  const request = readRenderRequest(command.type, payload);
1728
2329
  void withRenderLease(
@@ -1738,10 +2339,7 @@ function useCanvasHostPostMessage() {
1738
2339
  (selector) => typeof selector === "string"
1739
2340
  ) : void 0
1740
2341
  })
1741
- ).then((capture) => {
1742
- recordSourceAnnotatedCommit(request.renderId);
1743
- postCaptureResult(capture);
1744
- }).catch(postAsyncError);
2342
+ ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
1745
2343
  return;
1746
2344
  }
1747
2345
  if (command.type === "render-pool:capture-html") {
@@ -1751,23 +2349,7 @@ function useCanvasHostPostMessage() {
1751
2349
  () => captureStoryboardHtml(request.renderId, {
1752
2350
  timeout: readOptionalNumber(payload, "timeout")
1753
2351
  })
1754
- ).then((capture) => {
1755
- recordSourceAnnotatedCommit(request.renderId);
1756
- postCaptureResult(capture);
1757
- }).catch(postAsyncError);
1758
- return;
1759
- }
1760
- if (command.type === "render-pool:capture-static-html") {
1761
- const request = readRenderRequest(command.type, payload);
1762
- void withRenderLease(
1763
- request,
1764
- () => captureStoryboardStaticHtml(request.renderId, {
1765
- timeout: readOptionalNumber(payload, "timeout")
1766
- })
1767
- ).then((capture) => {
1768
- recordSourceAnnotatedCommit(request.renderId);
1769
- postCaptureResult(capture);
1770
- }).catch(postAsyncError);
2352
+ ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
1771
2353
  return;
1772
2354
  }
1773
2355
  if (command.type === "render-pool:capture-combined") {
@@ -1779,34 +2361,33 @@ function useCanvasHostPostMessage() {
1779
2361
  fiberTags: Array.isArray(payload.fiberTags) ? payload.fiberTags : void 0,
1780
2362
  timeout: readOptionalNumber(payload, "timeout")
1781
2363
  })
1782
- ).then((capture) => {
1783
- recordSourceAnnotatedCommit(request.renderId);
1784
- postCaptureResult(capture);
1785
- }).catch(postAsyncError);
2364
+ ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
1786
2365
  return;
1787
2366
  }
1788
- if (command.type === "render-pool:watch-html" || command.type === "render-pool:watch-combined") {
2367
+ if (command.type === "render-pool:watch-combined" || command.type === "render-pool:watch-html") {
1789
2368
  const request = readRenderRequest(command.type, payload);
1790
2369
  const watchId = readWatchId(command.type, payload);
1791
2370
  void removeWatchRequest(watchId).then(() => {
1792
2371
  setEntries((entries) => acquireRender(entries, request));
1793
- setWatchRequestsById((requests) => {
2372
+ const establishment = { status: "pending" };
2373
+ const watchRequest = {
2374
+ commandType: command.type,
2375
+ requestId: command.requestId,
2376
+ watchId,
2377
+ source,
2378
+ targetOrigin,
2379
+ request,
2380
+ payload,
2381
+ paused: payload.paused === true,
2382
+ bindingKey: buildWatchBindingKey(command.type, payload),
2383
+ establishment
2384
+ };
2385
+ updateWatchRequests((requests) => {
1794
2386
  const next = new Map(requests);
1795
- next.set(watchId, {
1796
- commandType: command.type,
1797
- requestId: command.requestId,
1798
- watchId,
1799
- source,
1800
- targetOrigin,
1801
- request,
1802
- payload,
1803
- paused: false,
1804
- bindingKey: buildWatchBindingKey(command.type, payload)
1805
- });
1806
- watchRequestsRef.current = next;
2387
+ next.set(watchId, watchRequest);
1807
2388
  return next;
1808
2389
  });
1809
- ack();
2390
+ acknowledgeWatchEstablishment(watchRequest);
1810
2391
  }).catch(postAsyncError);
1811
2392
  return;
1812
2393
  }
@@ -1819,28 +2400,23 @@ function useCanvasHostPostMessage() {
1819
2400
  const watchId = readWatchId(command.type, payload);
1820
2401
  const paused = payload.paused === true;
1821
2402
  const watch = watchesRef.current.get(watchId)?.watch;
1822
- watch?.setPaused?.(paused);
1823
- if (!watch?.setPaused) {
1824
- if (paused) watch?.pause?.();
1825
- else watch?.resume?.();
2403
+ if (watch) {
2404
+ setRuntimeWatchPaused(
2405
+ watch,
2406
+ paused,
2407
+ paused ? void 0 : readWatchResumeOptions(payload)
2408
+ );
1826
2409
  }
1827
- setWatchRequestsById((requests) => {
2410
+ updateWatchRequests((requests) => {
1828
2411
  const current = requests.get(watchId);
1829
2412
  if (!current || current.paused === paused) return requests;
1830
2413
  const next = new Map(requests);
1831
2414
  next.set(watchId, { ...current, paused });
1832
- watchRequestsRef.current = next;
1833
2415
  return next;
1834
2416
  });
1835
2417
  ack();
1836
2418
  return;
1837
2419
  }
1838
- if (command.type === "render-pool:unrender") {
1839
- const target = requireRenderTarget(command.type, payload);
1840
- releaseRenderLease(target.renderId);
1841
- ack();
1842
- return;
1843
- }
1844
2420
  if (command.type === "render-pool:list") {
1845
2421
  post({
1846
2422
  type: "render-pool:state",
@@ -1849,43 +2425,6 @@ function useCanvasHostPostMessage() {
1849
2425
  });
1850
2426
  return;
1851
2427
  }
1852
- if (command.type === "render-pool:set-cache-limit") {
1853
- const maxCached = typeof payload.maxCached === "number" && Number.isInteger(payload.maxCached) ? Math.max(0, payload.maxCached) : maxCachedRef.current;
1854
- maxCachedRef.current = maxCached;
1855
- setEntries((entries) => evictCachedRenders(entries, maxCached));
1856
- ack();
1857
- return;
1858
- }
1859
- if (command.type === "render-pool:isolate") {
1860
- const target = resolveRenderTarget(payload);
1861
- document.querySelector("[data-render-isolation]")?.remove();
1862
- if (target?.renderId) {
1863
- const style = document.createElement("style");
1864
- style.setAttribute("data-render-isolation", "");
1865
- const escapedId = typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(target.renderId) : target.renderId;
1866
- style.textContent = '[data-render-id]:not([data-render-id="' + escapedId + '"]) { opacity: 0 !important; pointer-events: none !important; }';
1867
- document.head.appendChild(style);
1868
- }
1869
- ack();
1870
- return;
1871
- }
1872
- if (command.type === "render-pool:query-health") {
1873
- const target = resolveRenderTarget(payload);
1874
- post({
1875
- type: "render-pool:health-snapshot",
1876
- requestId: command.requestId,
1877
- snapshot: buildHealthSnapshot(target?.renderId ?? "")
1878
- });
1879
- return;
1880
- }
1881
- if (command.type === "render-pool:query-problems") {
1882
- post({
1883
- type: "render-pool:problem-snapshot",
1884
- requestId: command.requestId,
1885
- payload: buildProblemSnapshot()
1886
- });
1887
- return;
1888
- }
1889
2428
  if (command.type === "render-pool:watch-problems") {
1890
2429
  const watchId = typeof payload.watchId === "string" && payload.watchId.trim() ? payload.watchId : String(command.requestId ?? "default");
1891
2430
  problemWatchersRef.current.set(watchId, {
@@ -1907,6 +2446,65 @@ function useCanvasHostPostMessage() {
1907
2446
  const watchId = typeof payload.watchId === "string" && payload.watchId.trim() ? payload.watchId : String(command.requestId ?? "default");
1908
2447
  problemWatchersRef.current.delete(watchId);
1909
2448
  ack();
2449
+ return;
2450
+ }
2451
+ if (command.type === "render-pool:query-problems") {
2452
+ post({
2453
+ type: "render-pool:problem-snapshot",
2454
+ requestId: command.requestId,
2455
+ payload: buildProblemSnapshot()
2456
+ });
2457
+ return;
2458
+ }
2459
+ if (command.type === "render-pool:render") {
2460
+ const request = readRenderRequest(command.type, payload);
2461
+ void waitForRenderLease(request).then(ack).catch(postAsyncError);
2462
+ return;
2463
+ }
2464
+ if (command.type === "render-pool:unrender") {
2465
+ const target = requireRenderTarget(command.type, payload);
2466
+ releaseRenderLease(target.renderId);
2467
+ ack();
2468
+ return;
2469
+ }
2470
+ if (command.type === "render-pool:capture-static-html") {
2471
+ const request = readRenderRequest(command.type, payload);
2472
+ void withRenderLease(
2473
+ request,
2474
+ () => captureStoryboardStaticHtml(request.renderId, {
2475
+ timeout: readOptionalNumber(payload, "timeout")
2476
+ })
2477
+ ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
2478
+ return;
2479
+ }
2480
+ if (command.type === "render-pool:set-cache-limit") {
2481
+ if (typeof payload.maxCached === "number" && Number.isInteger(payload.maxCached)) {
2482
+ maxCachedRef.current = Math.max(0, payload.maxCached);
2483
+ }
2484
+ setEntries(
2485
+ (entries) => evictCachedRenders(entries, maxCachedRef.current)
2486
+ );
2487
+ ack();
2488
+ return;
2489
+ }
2490
+ if (command.type === "render-pool:isolate") {
2491
+ applyLegacyRenderIsolation(
2492
+ resolveRenderTarget(payload)?.renderId ?? null
2493
+ );
2494
+ ack();
2495
+ return;
2496
+ }
2497
+ if (command.type === "render-pool:query-health") {
2498
+ const renderId = resolveRenderTarget(payload)?.renderId ?? "";
2499
+ post({
2500
+ type: "render-pool:health-snapshot",
2501
+ requestId: command.requestId,
2502
+ snapshot: legacyHealthRef.current.buildSnapshot(renderId, {
2503
+ hasRenderEntries: renderEntriesRef.current.size > 0,
2504
+ claimErrorBoundaryTripped: problemTrackerRef.current.hasComponentProblem(renderId)
2505
+ })
2506
+ });
2507
+ return;
1910
2508
  }
1911
2509
  } catch (caught) {
1912
2510
  postAsyncError(caught);
@@ -1919,14 +2517,10 @@ function useCanvasHostPostMessage() {
1919
2517
  const stopProblemPublisher = problemTrackerRef.current.watch(
1920
2518
  publishProblemSnapshot
1921
2519
  );
1922
- const stopRuntimeProblemTracking = installCanvasHostRuntimeProblemTracking(
1923
- problemTrackerRef.current
1924
- );
1925
2520
  window.postMessage({ type: "render-pool:ready" }, "*");
1926
2521
  return () => {
1927
2522
  window.removeEventListener("message", onMessage);
1928
2523
  window.removeEventListener("__render-pool:command", onBridgeCommand);
1929
- stopRuntimeProblemTracking();
1930
2524
  stopProblemPublisher();
1931
2525
  for (const { watch } of watchesRef.current.values()) {
1932
2526
  void watch.stop();
@@ -1935,41 +2529,33 @@ function useCanvasHostPostMessage() {
1935
2529
  problemWatchersRef.current.clear();
1936
2530
  };
1937
2531
  }, [
1938
- buildHealthSnapshot,
1939
2532
  buildProblemSnapshot,
1940
2533
  buildState,
1941
2534
  publishProblemSnapshot,
1942
- recordSourceAnnotatedCommit,
1943
2535
  releaseRenderLease,
1944
2536
  removeWatchRequest,
1945
2537
  setEntries,
2538
+ updateWatchRequests,
1946
2539
  waitForRender
1947
2540
  ]);
1948
2541
  return {
1949
- renderStatusById: useMemo2(
2542
+ renderStatusById: useMemo3(
1950
2543
  () => buildRenderStatusMap(renderEntriesById),
1951
2544
  [renderEntriesById]
1952
2545
  ),
1953
- renderSizeById: useMemo2(
2546
+ renderSizeById: useMemo3(
1954
2547
  () => buildRenderSizeMap(renderEntriesById),
1955
2548
  [renderEntriesById]
1956
2549
  ),
1957
2550
  markStoryboardRendered,
2551
+ markStoryboardUnmounted,
1958
2552
  reportStoryboardError,
1959
- clearStoryboardError
2553
+ clearStoryboardError,
2554
+ reportCanvasImportError,
2555
+ clearCanvasImportError,
2556
+ registerCanvasProblemScope
1960
2557
  };
1961
2558
  }
1962
- function latestTimestamp(values) {
1963
- let latest = null;
1964
- for (const value of values.values()) {
1965
- latest = latest === null ? value : Math.max(latest, value);
1966
- }
1967
- return latest;
1968
- }
1969
- function isReactConnected() {
1970
- const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
1971
- return (hook?.renderers?.size ?? 0) > 0;
1972
- }
1973
2559
  function buildWatchBindingKey(commandType, payload) {
1974
2560
  try {
1975
2561
  return JSON.stringify({ commandType, payload });
@@ -1977,27 +2563,15 @@ function buildWatchBindingKey(commandType, payload) {
1977
2563
  return `${commandType}:${Date.now()}`;
1978
2564
  }
1979
2565
  }
1980
- var sourceAnnotationSelector2 = "[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]";
1981
- function renderSlotHasSourceAnnotations(renderId) {
1982
- const slot = typeof document === "undefined" ? null : document.querySelector(buildRenderContentSelector(renderId));
1983
- return getObservedSourceFiles2(slot).length > 0;
1984
- }
1985
- function getObservedSourceFiles2(slot) {
1986
- if (!slot) return [];
1987
- return [
1988
- ...new Set(
1989
- [...slot.querySelectorAll(sourceAnnotationSelector2)].flatMap((element) => [
1990
- element.getAttribute("data-tempo-source-file"),
1991
- element.getAttribute("data-tempo-filepath"),
1992
- element.getAttribute("data-tempo-html-filepath"),
1993
- element.getAttribute("data-tempo-source-loc")
1994
- ]).filter((file) => Boolean(file))
1995
- )
1996
- ];
1997
- }
1998
2566
 
1999
2567
  // canvas/canvas-host.tsx
2000
- import { jsx as jsx2 } from "react/jsx-runtime";
2568
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
2569
+ var CanvasHostContractError = class extends Error {
2570
+ constructor() {
2571
+ super(...arguments);
2572
+ this.name = "CanvasHostContractError";
2573
+ }
2574
+ };
2001
2575
  function readDirectUrlDimension(value) {
2002
2576
  const match = value.trim().match(/^([0-9]*\.?[0-9]+)(px|vw|vh)?$/);
2003
2577
  if (!match) {
@@ -2041,23 +2615,36 @@ function readDirectUrlRender() {
2041
2615
  }
2042
2616
  function CanvasHost({
2043
2617
  children,
2618
+ canvasModules,
2044
2619
  activeStoryboardIds,
2045
2620
  isStoryboardActive
2046
2621
  }) {
2622
+ if (children !== void 0 && canvasModules !== void 0) {
2623
+ throw new CanvasHostContractError(
2624
+ "CanvasHost cannot receive both children and canvasModules."
2625
+ );
2626
+ }
2047
2627
  const {
2048
2628
  renderStatusById: renderStatusById2,
2049
2629
  renderSizeById,
2050
2630
  markStoryboardRendered,
2631
+ markStoryboardUnmounted,
2051
2632
  reportStoryboardError,
2052
- clearStoryboardError
2633
+ clearStoryboardError,
2634
+ reportCanvasImportError,
2635
+ clearCanvasImportError,
2636
+ registerCanvasProblemScope
2053
2637
  } = useCanvasHostPostMessage();
2054
2638
  const directUrlSearch = typeof window === "undefined" ? "" : window.location.search;
2055
- const directUrlRender = useMemo3(readDirectUrlRender, [directUrlSearch]);
2056
- const propActiveIds = useMemo3(
2639
+ const directUrlRender = useMemo4(() => {
2640
+ void directUrlSearch;
2641
+ return readDirectUrlRender();
2642
+ }, [directUrlSearch]);
2643
+ const propActiveIds = useMemo4(
2057
2644
  () => new Set(activeStoryboardIds ?? []),
2058
2645
  [activeStoryboardIds]
2059
2646
  );
2060
- const runtime = useMemo3(
2647
+ const runtime = useMemo4(
2061
2648
  () => ({
2062
2649
  getStoryboardStatus(storyboardId) {
2063
2650
  const normalizedId = normalizeId(storyboardId, "Storyboard id");
@@ -2078,31 +2665,116 @@ function CanvasHost({
2078
2665
  return directUrlRender?.renderId === normalizedId ? { left: 0, top: 0 } : void 0;
2079
2666
  },
2080
2667
  markStoryboardRendered,
2668
+ markStoryboardUnmounted,
2081
2669
  reportStoryboardError,
2082
- clearStoryboardError
2670
+ clearStoryboardError,
2671
+ reportCanvasImportError,
2672
+ clearCanvasImportError,
2673
+ registerCanvasProblemScope
2083
2674
  }),
2084
2675
  [
2085
2676
  clearStoryboardError,
2677
+ clearCanvasImportError,
2086
2678
  directUrlRender,
2087
2679
  isStoryboardActive,
2088
2680
  markStoryboardRendered,
2681
+ markStoryboardUnmounted,
2089
2682
  propActiveIds,
2683
+ registerCanvasProblemScope,
2684
+ reportCanvasImportError,
2090
2685
  reportStoryboardError,
2091
2686
  renderSizeById,
2092
2687
  renderStatusById2
2093
2688
  ]
2094
2689
  );
2095
- return /* @__PURE__ */ jsx2(CanvasHostContext.Provider, { value: runtime, children });
2690
+ return /* @__PURE__ */ jsxs2(CanvasHostContext.Provider, { value: runtime, children: [
2691
+ children,
2692
+ canvasModules?.map(({ canvasPath, load }) => /* @__PURE__ */ jsx3(
2693
+ CanvasImportBoundary,
2694
+ {
2695
+ canvasPath,
2696
+ load
2697
+ },
2698
+ canvasPath
2699
+ ))
2700
+ ] });
2096
2701
  }
2097
2702
 
2703
+ // canvas/host-capability.ts
2704
+ var canvasHostCapability = {
2705
+ protocolVersion: 1,
2706
+ supportsModules: true
2707
+ };
2708
+
2098
2709
  // canvas/storyboard.tsx
2099
2710
  import {
2100
- Component,
2101
- Suspense,
2102
- useEffect as useEffect2,
2103
- useRef as useRef2
2711
+ Children as Children2,
2712
+ Component as Component2,
2713
+ cloneElement as cloneElement2,
2714
+ isValidElement as isValidElement2,
2715
+ Suspense as Suspense2,
2716
+ useCallback as useCallback5,
2717
+ useEffect as useEffect4,
2718
+ useLayoutEffect as useLayoutEffect3,
2719
+ useMemo as useMemo5,
2720
+ useRef as useRef4,
2721
+ useState as useState3
2104
2722
  } from "react";
2105
- import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
2723
+
2724
+ // canvas/render-error-recovery.ts
2725
+ import { useCallback as useCallback4, useEffect as useEffect3, useRef as useRef3 } from "react";
2726
+ var renderErrorRetryBaseDelayMs = 1e3;
2727
+ var renderErrorRetryMaxDelayMs = 8e3;
2728
+ var beatListeners = /* @__PURE__ */ new Set();
2729
+ function emitRenderErrorRecoveryBeat() {
2730
+ for (const listener of [...beatListeners]) listener();
2731
+ }
2732
+ var hot = import.meta.hot;
2733
+ hot?.on?.("vite:afterUpdate", emitRenderErrorRecoveryBeat);
2734
+ function useRenderErrorRecovery(retryNow) {
2735
+ const retryNowRef = useRef3(retryNow);
2736
+ retryNowRef.current = retryNow;
2737
+ const timerRef = useRef3(null);
2738
+ const nextDelayRef = useRef3(renderErrorRetryBaseDelayMs);
2739
+ const erroredRef = useRef3(false);
2740
+ const clearTimer = useCallback4(() => {
2741
+ if (timerRef.current === null) return;
2742
+ clearTimeout(timerRef.current);
2743
+ timerRef.current = null;
2744
+ }, []);
2745
+ const noteRenderError = useCallback4(() => {
2746
+ erroredRef.current = true;
2747
+ if (timerRef.current !== null) return;
2748
+ const delay = nextDelayRef.current;
2749
+ nextDelayRef.current = Math.min(delay * 2, renderErrorRetryMaxDelayMs);
2750
+ timerRef.current = setTimeout(() => {
2751
+ timerRef.current = null;
2752
+ retryNowRef.current();
2753
+ }, delay);
2754
+ }, []);
2755
+ const noteRecovered = useCallback4(() => {
2756
+ erroredRef.current = false;
2757
+ nextDelayRef.current = renderErrorRetryBaseDelayMs;
2758
+ clearTimer();
2759
+ }, [clearTimer]);
2760
+ useEffect3(() => {
2761
+ const onBeat = () => {
2762
+ nextDelayRef.current = renderErrorRetryBaseDelayMs;
2763
+ if (!erroredRef.current) return;
2764
+ clearTimer();
2765
+ retryNowRef.current();
2766
+ };
2767
+ beatListeners.add(onBeat);
2768
+ return () => {
2769
+ beatListeners.delete(onBeat);
2770
+ clearTimer();
2771
+ };
2772
+ }, [clearTimer]);
2773
+ return { noteRenderError, noteRecovered };
2774
+ }
2775
+
2776
+ // canvas/storyboard.tsx
2777
+ import { Fragment, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
2106
2778
  function Storyboard({
2107
2779
  id,
2108
2780
  name,
@@ -2110,28 +2782,28 @@ function Storyboard({
2110
2782
  layout,
2111
2783
  props
2112
2784
  }) {
2113
- const Component2 = component;
2114
- return /* @__PURE__ */ jsx3(StoryboardSlot, { id, name, layout, kind: "component", children: /* @__PURE__ */ jsx3(Component2, { ...props ?? {} }) });
2785
+ const Component3 = component;
2786
+ return /* @__PURE__ */ jsx4(StoryboardSlot, { id, name, layout, kind: "component", children: /* @__PURE__ */ jsx4(Component3, { ...props ?? {} }) });
2115
2787
  }
2116
2788
  function LegacyStoryboardV1({
2117
2789
  id,
2118
2790
  storyboard
2119
2791
  }) {
2120
- return /* @__PURE__ */ jsx3(
2792
+ return /* @__PURE__ */ jsx4(
2121
2793
  StoryboardSlot,
2122
2794
  {
2123
2795
  id,
2124
2796
  name: storyboard.name,
2125
2797
  layout: storyboard.layout,
2126
2798
  kind: "component",
2127
- children: /* @__PURE__ */ jsx3(LegacyStoryboardV1Render, { render: storyboard.render })
2799
+ children: /* @__PURE__ */ jsx4(LegacyStoryboardV1Render, { render: storyboard.render })
2128
2800
  }
2129
2801
  );
2130
2802
  }
2131
2803
  function LegacyStoryboardV1Render({
2132
2804
  render
2133
2805
  }) {
2134
- return /* @__PURE__ */ jsx3(Fragment, { children: render() });
2806
+ return /* @__PURE__ */ jsx4(Fragment, { children: render() });
2135
2807
  }
2136
2808
  function RouteStoryboard({
2137
2809
  id,
@@ -2139,7 +2811,7 @@ function RouteStoryboard({
2139
2811
  route,
2140
2812
  layout
2141
2813
  }) {
2142
- return /* @__PURE__ */ jsx3(
2814
+ return /* @__PURE__ */ jsx4(
2143
2815
  StoryboardSlot,
2144
2816
  {
2145
2817
  id,
@@ -2157,7 +2829,7 @@ function HtmlStoryboard({
2157
2829
  src,
2158
2830
  layout
2159
2831
  }) {
2160
- return /* @__PURE__ */ jsx3(
2832
+ return /* @__PURE__ */ jsx4(
2161
2833
  StoryboardSlot,
2162
2834
  {
2163
2835
  id,
@@ -2185,22 +2857,65 @@ function StoryboardSlot({
2185
2857
  const renderSize = useStoryboardSize(id);
2186
2858
  const placement = useStoryboardPlacement(id);
2187
2859
  const markRendered = useStoryboardRendered(id);
2860
+ const markUnmounted = useStoryboardUnmounted(id);
2188
2861
  const { reportError, clearError } = useStoryboardErrorReporter(id);
2189
2862
  const renderWidth = renderSize?.width;
2190
2863
  const renderHeight = renderSize?.height;
2864
+ const renderRevision = renderSize?.revision ?? 0;
2191
2865
  const intrinsicSize = renderSize?.intrinsicSize ?? (kind === "component" && layout.intrinsicSizing === "root-element");
2192
- const resetKey = `${renderId}:${renderSize?.revision ?? 0}`;
2193
- const contentRef = useRef2(null);
2194
- useEffect2(() => {
2866
+ const resetKey = `${renderId}:${renderRevision}`;
2867
+ const contentRef = useRef4(null);
2868
+ const errorBoundaryRef = useRef4(null);
2869
+ const lastReportedCommitRef = useRef4(null);
2870
+ const previousChildrenRef = useRef4(children);
2871
+ const [recoveryRevision, setRecoveryRevision] = useState3(0);
2872
+ const commitKey = `${resetKey}:${recoveryRevision}`;
2873
+ const retryRenderNow = useCallback5(() => {
2874
+ if (!errorBoundaryRef.current?.retry()) return false;
2875
+ setRecoveryRevision((revision) => revision + 1);
2876
+ return true;
2877
+ }, []);
2878
+ const { noteRenderError, noteRecovered } = useRenderErrorRecovery(retryRenderNow);
2879
+ const handleRenderError = useCallback5(
2880
+ (error) => {
2881
+ noteRenderError();
2882
+ reportError(error);
2883
+ },
2884
+ [noteRenderError, reportError]
2885
+ );
2886
+ const handleRendered = useCallback5(
2887
+ (reportedCommitKey) => {
2888
+ noteRecovered();
2889
+ if (lastReportedCommitRef.current === reportedCommitKey) return;
2890
+ lastReportedCommitRef.current = reportedCommitKey;
2891
+ clearError();
2892
+ markRendered();
2893
+ },
2894
+ [clearError, markRendered, noteRecovered]
2895
+ );
2896
+ const renderChildren = useMemo5(() => {
2897
+ if (isValidElement2(children)) return cloneElement2(children);
2898
+ return Children2.map(
2899
+ children,
2900
+ (child) => isValidElement2(child) ? cloneElement2(child) : child
2901
+ );
2902
+ }, [children]);
2903
+ useEffect4(() => markUnmounted, [markUnmounted]);
2904
+ useEffect4(() => {
2905
+ const childrenChanged = previousChildrenRef.current !== children;
2906
+ previousChildrenRef.current = children;
2907
+ if (childrenChanged) retryRenderNow();
2908
+ }, [children, retryRenderNow]);
2909
+ useEffect4(() => {
2195
2910
  if (!contentRef.current || status === "unmounted") return;
2196
2911
  return trackStoryboardPortals(renderId, contentRef.current, status);
2197
2912
  }, [renderId, status]);
2198
- useEffect2(() => {
2913
+ useEffect4(() => {
2199
2914
  if (status === "unmounted") return;
2200
2915
  syncStoryboardPortals(renderId, status);
2201
2916
  }, [renderId, status]);
2202
2917
  if (status === "unmounted") return null;
2203
- return /* @__PURE__ */ jsx3(
2918
+ return /* @__PURE__ */ jsx4(
2204
2919
  "div",
2205
2920
  {
2206
2921
  "data-render-id": renderId,
@@ -2225,27 +2940,29 @@ function StoryboardSlot({
2225
2940
  visibility: status === "active" ? "visible" : "hidden",
2226
2941
  pointerEvents: status === "active" ? "auto" : "none"
2227
2942
  },
2228
- children: /* @__PURE__ */ jsx3(
2943
+ children: /* @__PURE__ */ jsx4(
2229
2944
  "div",
2230
2945
  {
2231
2946
  "data-render-content": renderId,
2947
+ "data-tempo-render-mode": kind === "html" ? "static-dom" : void 0,
2948
+ "data-tempo-hide-fiber": "true",
2232
2949
  ref: contentRef,
2233
2950
  style: { width: "100%", height: "100%" },
2234
- children: /* @__PURE__ */ jsx3(
2951
+ children: /* @__PURE__ */ jsx4(
2235
2952
  StoryboardErrorBoundary,
2236
2953
  {
2237
- onError: reportError,
2238
- onRecover: clearError,
2954
+ ref: errorBoundaryRef,
2955
+ onError: handleRenderError,
2239
2956
  resetKey,
2240
- children: /* @__PURE__ */ jsxs(Suspense, { fallback: null, children: [
2241
- children,
2242
- /* @__PURE__ */ jsx3(
2243
- StoryboardReadySentinel,
2957
+ children: /* @__PURE__ */ jsxs3(Suspense2, { fallback: null, children: [
2958
+ renderChildren,
2959
+ /* @__PURE__ */ jsx4(
2960
+ StoryboardCommitSignal,
2244
2961
  {
2245
- active: status === "active",
2246
- clearError,
2247
- markRendered
2248
- }
2962
+ commitKey,
2963
+ onCommit: handleRendered
2964
+ },
2965
+ commitKey
2249
2966
  )
2250
2967
  ] })
2251
2968
  }
@@ -2255,11 +2972,18 @@ function StoryboardSlot({
2255
2972
  }
2256
2973
  );
2257
2974
  }
2258
- var renderErrorRetryDelayMs = 1e3;
2259
- var StoryboardErrorBoundary = class extends Component {
2975
+ function StoryboardCommitSignal({
2976
+ commitKey,
2977
+ onCommit
2978
+ }) {
2979
+ const onCommitRef = useRef4(onCommit);
2980
+ onCommitRef.current = onCommit;
2981
+ useLayoutEffect3(() => onCommitRef.current(commitKey), [commitKey]);
2982
+ return null;
2983
+ }
2984
+ var StoryboardErrorBoundary = class extends Component2 {
2260
2985
  constructor() {
2261
2986
  super(...arguments);
2262
- this.retryTimer = null;
2263
2987
  this.state = {
2264
2988
  error: null,
2265
2989
  componentStack: void 0,
@@ -2271,7 +2995,11 @@ var StoryboardErrorBoundary = class extends Component {
2271
2995
  }
2272
2996
  static getDerivedStateFromProps(props, state) {
2273
2997
  if (props.resetKey !== state.resetKey) {
2274
- return { error: null, componentStack: void 0, resetKey: props.resetKey };
2998
+ return {
2999
+ error: null,
3000
+ componentStack: void 0,
3001
+ resetKey: props.resetKey
3002
+ };
2275
3003
  }
2276
3004
  return null;
2277
3005
  }
@@ -2282,38 +3010,20 @@ var StoryboardErrorBoundary = class extends Component {
2282
3010
  stack: error.stack,
2283
3011
  componentStack: info.componentStack ?? void 0
2284
3012
  });
2285
- this.scheduleRetry();
2286
- }
2287
- componentDidUpdate(_prevProps, prevState) {
2288
- if (this.state.error) {
2289
- if (!this.retryTimer) this.scheduleRetry();
2290
- return;
2291
- }
2292
- this.clearRetryTimer();
2293
- if (prevState.error && !this.state.error) {
2294
- this.props.onRecover();
2295
- }
2296
- }
2297
- componentWillUnmount() {
2298
- this.clearRetryTimer();
2299
3013
  }
2300
- scheduleRetry() {
2301
- this.clearRetryTimer();
2302
- this.retryTimer = setTimeout(() => {
2303
- this.retryTimer = null;
2304
- this.setState(
2305
- (state) => state.error ? { error: null, componentStack: void 0, resetKey: state.resetKey } : null
2306
- );
2307
- }, renderErrorRetryDelayMs);
3014
+ hasError() {
3015
+ return this.state.error !== null;
2308
3016
  }
2309
- clearRetryTimer() {
2310
- if (!this.retryTimer) return;
2311
- clearTimeout(this.retryTimer);
2312
- this.retryTimer = null;
3017
+ retry() {
3018
+ if (!this.state.error) return false;
3019
+ this.setState(
3020
+ (state) => state.error ? { error: null, componentStack: void 0, resetKey: state.resetKey } : null
3021
+ );
3022
+ return true;
2313
3023
  }
2314
3024
  render() {
2315
3025
  if (this.state.error) {
2316
- return /* @__PURE__ */ jsx3(
3026
+ return /* @__PURE__ */ jsx4(
2317
3027
  "div",
2318
3028
  {
2319
3029
  "data-render-error": "true",
@@ -2325,50 +3035,33 @@ var StoryboardErrorBoundary = class extends Component {
2325
3035
  return this.props.children;
2326
3036
  }
2327
3037
  };
2328
- function StoryboardReadySentinel({
2329
- active,
2330
- clearError,
2331
- markRendered
2332
- }) {
2333
- useEffect2(() => {
2334
- if (!active) return;
2335
- let paintFrame = 0;
2336
- const commitFrame = requestAnimationFrame(() => {
2337
- paintFrame = requestAnimationFrame(() => {
2338
- clearError();
2339
- markRendered();
2340
- });
2341
- });
2342
- return () => {
2343
- cancelAnimationFrame(commitFrame);
2344
- cancelAnimationFrame(paintFrame);
2345
- };
2346
- }, [active, clearError, markRendered]);
2347
- return null;
2348
- }
2349
3038
  export {
2350
3039
  Canvas,
2351
3040
  CanvasContext,
2352
3041
  CanvasHost,
3042
+ CanvasHostContractError,
3043
+ CanvasImportBoundary,
2353
3044
  HtmlStoryboard,
2354
3045
  LegacyStoryboardV1,
2355
3046
  RouteStoryboard,
2356
3047
  Storyboard,
2357
3048
  StoryboardSlot,
3049
+ TEMPO_INTERACT_FRAME_NAME,
2358
3050
  buildRenderContentFiberSelector,
2359
3051
  buildRenderContentSelector,
2360
3052
  buildRenderSelector,
3053
+ canvasHostCapability,
2361
3054
  captureStoryboardCombined,
2362
3055
  captureStoryboardHtml,
2363
3056
  captureStoryboardImage,
2364
- captureStoryboardStaticHtml,
3057
+ getCanvasHostRecoveryFeed,
2365
3058
  getCanvasHostRuntime,
2366
3059
  getCanvasStoryboardRenderId,
2367
3060
  getOptionalCanvasHostRuntime,
3061
+ isTempoInteractFrameName,
2368
3062
  stripRenderContentWrapperAttributes,
2369
3063
  stripRenderContentWrapperFromCombinedCapture,
2370
3064
  useActiveState,
2371
- watchStoryboardCombined,
2372
- watchStoryboardHtml
3065
+ watchStoryboardCombined
2373
3066
  };
2374
3067
  //# sourceMappingURL=index.js.map