@hyperframes/studio 0.9.56 → 0.9.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/assets/hyperframes-player-bya4hgms.js +573 -0
  2. package/dist/assets/{index-yuN1pZrv.js → index--dcfSUzI.js} +1 -1
  3. package/dist/assets/{index-CgyBYe2L.js → index-Bxh5lW0C.js} +178 -178
  4. package/dist/assets/{pausedVideoDecoder-DtvSF8bV.js → pausedVideoDecoder-BKym1jA6.js} +1 -1
  5. package/dist/index.d.ts +88 -3
  6. package/dist/index.html +1 -1
  7. package/dist/index.js +912 -814
  8. package/package.json +8 -8
  9. package/src/components/nle/NLEPreview.test.ts +35 -3
  10. package/src/components/nle/NLEPreview.tsx +5 -4
  11. package/src/hooks/gsapRuntimePatch.ts +2 -3
  12. package/src/hooks/gsapRuntimeReaders.test.ts +5 -40
  13. package/src/hooks/gsapRuntimeReaders.ts +3 -27
  14. package/src/hooks/useExternalFileChangeCoordinator.test.tsx +20 -0
  15. package/src/hooks/useExternalFileChangeCoordinator.ts +1 -1
  16. package/src/hooks/useMusicBeatAnalysis.test.tsx +131 -0
  17. package/src/hooks/useMusicBeatAnalysis.ts +51 -66
  18. package/src/hooks/useRenderClipContent.test.ts +21 -0
  19. package/src/hooks/useRenderClipContent.ts +3 -1
  20. package/src/index.ts +18 -0
  21. package/src/player/components/studioShortcuts.ts +3 -2
  22. package/src/player/hooks/timelinePlayerTestHarness.ts +2 -0
  23. package/src/player/hooks/timelineSyncHydration.test.ts +28 -2
  24. package/src/player/hooks/timelineSyncHydration.ts +3 -7
  25. package/src/player/hooks/usePlaybackKeyboard.test.ts +107 -2
  26. package/src/player/hooks/usePlaybackKeyboard.ts +38 -1
  27. package/src/player/hooks/useShadowPreviewReload.ts +131 -14
  28. package/src/player/hooks/useTimelinePlayer.reloadStill.test.ts +241 -0
  29. package/src/player/hooks/useTimelinePlayer.ts +13 -1
  30. package/src/player/hooks/useTimelineSyncCallbacks.ts +4 -0
  31. package/src/player/lib/previewElements.test.ts +4 -0
  32. package/src/player/lib/previewElements.ts +1 -0
  33. package/src/sealedPreviewExports.test.ts +21 -0
  34. package/src/utils/externalConflictStorage.test.ts +66 -14
  35. package/src/utils/externalConflictStorage.ts +36 -82
  36. package/src/utils/gsapSoftReload.ts +2 -14
  37. package/src/utils/timelineInspector.test.ts +49 -2
  38. package/src/utils/timelineInspector.ts +21 -2
  39. package/dist/assets/hyperframes-player-SRLbmEDB.js +0 -565
@@ -0,0 +1,241 @@
1
+ // @vitest-environment happy-dom
2
+ // fails without the fix: a reload kept the live page beside its own until promotion, so a heavy project held two whole
3
+ // pages (1.7x the app's resident memory) and ran out of memory. A host that can show the live
4
+ // frame as a still now gets one page at a time.
5
+
6
+ import { act } from "react";
7
+ import { createRoot } from "react-dom/client";
8
+ import { afterEach, describe, expect, it, vi } from "vitest";
9
+ import { SHADOW_READY_BUDGETS, SHADOW_READY_TIMEOUT_MS } from "./useShadowPreviewReload";
10
+ import { usePlayerStore } from "../store/playerStore";
11
+ import {
12
+ makeAdapterWindow,
13
+ makeFakeIframe,
14
+ renderTimelinePlayerHarness,
15
+ resetPlayerStore,
16
+ } from "./timelinePlayerTestHarness";
17
+
18
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
19
+
20
+ vi.mock("../../utils/gsapSoftReload", async (importOriginal) => ({
21
+ ...(await importOriginal<typeof import("../../utils/gsapSoftReload")>()),
22
+ ensureMotionPathPluginLoaded: vi.fn(),
23
+ }));
24
+
25
+ afterEach(() => {
26
+ vi.useRealTimers();
27
+ vi.restoreAllMocks();
28
+ document.body.innerHTML = "";
29
+ resetPlayerStore();
30
+ });
31
+
32
+ const unmount = (root: ReturnType<typeof createRoot>) => act(() => root.unmount());
33
+
34
+ /** A loaded live preview at 3 s, and a reload asked for with `hold` as the host's still. */
35
+ async function reloadWithStill(
36
+ hold: (live: HTMLIFrameElement) => Promise<(() => void) | null>,
37
+ { playing = false } = {},
38
+ ) {
39
+ const harness = renderTimelinePlayerHarness({ holdPreviewStill: hold });
40
+ const { adapter, win } = makeAdapterWindow();
41
+ adapter.getTime = vi.fn(() => 3);
42
+ const live = makeFakeIframe(win);
43
+ act(() => {
44
+ harness.getApi().iframeRef.current = live;
45
+ harness.getApi().onIframeLoad();
46
+ });
47
+ if (playing) act(() => usePlayerStore.getState().setIsPlaying(true));
48
+ await act(async () => {
49
+ harness.getApi().refreshPlayer();
50
+ await Promise.resolve();
51
+ });
52
+ return { ...harness, live, liveAdapter: adapter };
53
+ }
54
+
55
+ describe("a reload behind the host's still", () => {
56
+ it("drops the live page before the reload's page loads, and the still once the new page shows the live time", async () => {
57
+ const release = vi.fn();
58
+ const hold = vi.fn(async () => release);
59
+ const { getApi, root, live } = await reloadWithStill(hold);
60
+
61
+ expect(hold).toHaveBeenCalledWith(live);
62
+ const slots = getApi().previewSlots;
63
+ expect(slots.map((slot) => slot.role)).toEqual(["shadow"]);
64
+ expect(release).not.toHaveBeenCalled();
65
+
66
+ const { adapter, win } = makeAdapterWindow();
67
+ adapter.seek = vi.fn(adapter.seek);
68
+ const next = makeFakeIframe(win);
69
+ const gen = slots[0]!.gen;
70
+ act(() => {
71
+ getApi().setShadowIframeNode(next);
72
+ getApi().onShadowIframeLoad(gen);
73
+ getApi().onShadowReadyChange(gen, true);
74
+ });
75
+
76
+ expect(getApi().previewSlots).toEqual([{ gen, role: "live", url: slots[0]!.url }]);
77
+ expect(getApi().iframeRef.current).toBe(next);
78
+ expect(adapter.seek).toHaveBeenCalledWith(3);
79
+ await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));
80
+ unmount(root);
81
+ });
82
+
83
+ it("resumes a playing preview from where the still was taken", async () => {
84
+ const { getApi, root } = await reloadWithStill(async () => () => {}, { playing: true });
85
+ const gen = getApi().previewSlots[0]!.gen;
86
+ const { adapter, win } = makeAdapterWindow();
87
+ adapter.getDuration = vi.fn(() => 10);
88
+ adapter.seek = vi.fn(adapter.seek);
89
+ adapter.play = vi.fn(adapter.play);
90
+ act(() => {
91
+ getApi().setShadowIframeNode(makeFakeIframe(win));
92
+ getApi().onShadowIframeLoad(gen);
93
+ getApi().onShadowReadyChange(gen, true);
94
+ });
95
+ expect(adapter.seek).toHaveBeenCalledWith(3);
96
+ expect(adapter.play).toHaveBeenCalled();
97
+ unmount(root);
98
+ });
99
+
100
+ it("brings the live page back at its time when the reload gives up, and drops the still once it loads", async () => {
101
+ vi.useFakeTimers();
102
+ vi.spyOn(console, "error").mockImplementation(() => {});
103
+ const release = vi.fn();
104
+ const onPreviewReloadFailed = vi.fn();
105
+ const harness = renderTimelinePlayerHarness({
106
+ holdPreviewStill: async () => release,
107
+ onPreviewReloadFailed,
108
+ });
109
+ const { adapter, win } = makeAdapterWindow();
110
+ adapter.getTime = vi.fn(() => 3);
111
+ const live = makeFakeIframe(win);
112
+ act(() => {
113
+ harness.getApi().iframeRef.current = live;
114
+ harness.getApi().onIframeLoad();
115
+ });
116
+ await act(async () => {
117
+ harness.getApi().refreshPlayer();
118
+ await Promise.resolve();
119
+ });
120
+
121
+ act(() => void vi.advanceTimersByTime(SHADOW_READY_TIMEOUT_MS * SHADOW_READY_BUDGETS));
122
+ expect(onPreviewReloadFailed).toHaveBeenCalledWith(expect.stringContaining("too long"));
123
+ expect(harness.getApi().previewSlots).toEqual([{ gen: 0, role: "live" }]);
124
+ expect(release).not.toHaveBeenCalled();
125
+
126
+ // The live slot mounts again and loads at once, as a cached page does: that load drops the still.
127
+ act(() => {
128
+ harness.getApi().iframeRef.current = makeFakeIframe(makeAdapterWindow().win);
129
+ harness.getApi().onIframeLoad();
130
+ vi.advanceTimersByTime(3_000);
131
+ });
132
+ expect(release).toHaveBeenCalledTimes(1);
133
+ unmount(harness.root);
134
+ });
135
+
136
+ it("drops a still kept for a give-up even if the live page never loads again", async () => {
137
+ vi.useFakeTimers();
138
+ vi.spyOn(console, "error").mockImplementation(() => {});
139
+ const release = vi.fn();
140
+ const harness = renderTimelinePlayerHarness({ holdPreviewStill: async () => release });
141
+ act(() => {
142
+ harness.getApi().iframeRef.current = makeFakeIframe(makeAdapterWindow().win);
143
+ harness.getApi().onIframeLoad();
144
+ });
145
+ await act(async () => {
146
+ harness.getApi().refreshPlayer();
147
+ await Promise.resolve();
148
+ });
149
+ act(() => void vi.advanceTimersByTime(SHADOW_READY_TIMEOUT_MS * SHADOW_READY_BUDGETS));
150
+ expect(release).not.toHaveBeenCalled();
151
+ act(() => void vi.advanceTimersByTime(SHADOW_READY_TIMEOUT_MS));
152
+ expect(release).toHaveBeenCalledTimes(1);
153
+ unmount(harness.root);
154
+ });
155
+
156
+ it("drops a still that answers after the composition switched, and starts no reload for the old one", async () => {
157
+ let answer: (release: () => void) => void = () => {};
158
+ const release = vi.fn();
159
+ const harness = renderTimelinePlayerHarness({
160
+ holdPreviewStill: () => new Promise((resolve) => (answer = resolve)),
161
+ });
162
+ const live = makeFakeIframe(makeAdapterWindow().win);
163
+ act(() => {
164
+ harness.getApi().iframeRef.current = live;
165
+ harness.getApi().onIframeLoad();
166
+ });
167
+ act(() => harness.getApi().refreshPlayer());
168
+ act(() => harness.getApi().resetPreviewSlots());
169
+ await act(async () => {
170
+ answer(release);
171
+ await Promise.resolve();
172
+ });
173
+ expect(release).toHaveBeenCalledTimes(1);
174
+ expect(harness.getApi().previewSlots).toEqual([{ gen: 0, role: "live" }]);
175
+ unmount(harness.root);
176
+ });
177
+
178
+ it("keeps both pages for a reload when the host has no still to show, and a playing preview plays on", async () => {
179
+ const harness = renderTimelinePlayerHarness({ holdPreviewStill: async () => null });
180
+ const { adapter, win } = makeAdapterWindow();
181
+ adapter.play = vi.fn(adapter.play);
182
+ act(() => {
183
+ harness.getApi().iframeRef.current = makeFakeIframe(win);
184
+ harness.getApi().onIframeLoad();
185
+ });
186
+ act(() => usePlayerStore.getState().setIsPlaying(true));
187
+ await act(async () => {
188
+ harness.getApi().refreshPlayer();
189
+ await Promise.resolve();
190
+ });
191
+ expect(harness.getApi().previewSlots.map((slot) => slot.role)).toEqual(["live", "shadow"]);
192
+ expect(adapter.play).toHaveBeenCalled();
193
+ unmount(harness.root);
194
+ });
195
+
196
+ it("a host that throws while taking the still keeps both pages and a playing preview plays on", async () => {
197
+ const harness = renderTimelinePlayerHarness({
198
+ holdPreviewStill: () => {
199
+ throw new Error("capture unavailable");
200
+ },
201
+ });
202
+ const { adapter, win } = makeAdapterWindow();
203
+ adapter.play = vi.fn(adapter.play);
204
+ act(() => {
205
+ harness.getApi().iframeRef.current = makeFakeIframe(win);
206
+ harness.getApi().onIframeLoad();
207
+ });
208
+ act(() => usePlayerStore.getState().setIsPlaying(true));
209
+ await act(async () => {
210
+ expect(() => harness.getApi().refreshPlayer()).not.toThrow();
211
+ await Promise.resolve();
212
+ await Promise.resolve();
213
+ });
214
+ expect(harness.getApi().previewSlots.map((slot) => slot.role)).toEqual(["live", "shadow"]);
215
+ expect(adapter.play).toHaveBeenCalled();
216
+ unmount(harness.root);
217
+ });
218
+
219
+ it("pauses a playing preview before the still is taken, so the reload resumes from the frame it shows", async () => {
220
+ const order: string[] = [];
221
+ const harness = renderTimelinePlayerHarness({
222
+ holdPreviewStill: async () => {
223
+ order.push("still");
224
+ return () => {};
225
+ },
226
+ });
227
+ const { adapter, win } = makeAdapterWindow();
228
+ act(() => {
229
+ harness.getApi().iframeRef.current = makeFakeIframe(win);
230
+ harness.getApi().onIframeLoad();
231
+ });
232
+ act(() => usePlayerStore.getState().setIsPlaying(true));
233
+ adapter.pause = vi.fn(() => void order.push("pause"));
234
+ await act(async () => {
235
+ harness.getApi().refreshPlayer();
236
+ await Promise.resolve();
237
+ });
238
+ expect(order).toEqual(["pause", "still"]);
239
+ unmount(harness.root);
240
+ });
241
+ });
@@ -51,6 +51,7 @@ export interface UseTimelinePlayerOptions {
51
51
  onShadowPromoted?: () => void;
52
52
  /** A reload was abandoned (cause in the message); the previous preview is still showing. */
53
53
  onPreviewReloadFailed?: (message: string) => void;
54
+ holdPreviewStill?: (live: HTMLIFrameElement) => Promise<(() => void) | null>;
54
55
  }
55
56
 
56
57
  const publishSeek = (time: number, options?: { follow?: boolean }) =>
@@ -60,6 +61,7 @@ const publishSeek = (time: number, options?: { follow?: boolean }) =>
60
61
  export function useTimelinePlayer({
61
62
  onShadowPromoted,
62
63
  onPreviewReloadFailed,
64
+ holdPreviewStill,
63
65
  }: UseTimelinePlayerOptions = {}) {
64
66
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
65
67
  const rafRef = useRef<number>(0);
@@ -420,6 +422,7 @@ export function useTimelinePlayer({
420
422
  beginShadowReload,
421
423
  resetPreviewSlots,
422
424
  previewGeneration,
425
+ onLiveLoaded,
423
426
  } = useShadowPreviewReload({
424
427
  iframeRef,
425
428
  getAdapter,
@@ -434,6 +437,7 @@ export function useTimelinePlayer({
434
437
  applyPreviewAudioState,
435
438
  onPromoted: onShadowPromoted,
436
439
  onReloadFailed: onPreviewReloadFailed,
440
+ holdStill: holdPreviewStill,
437
441
  handOverPlayback: (time, playing) => {
438
442
  // keepPlaying: move the playhead without the paused-seek audio scrub.
439
443
  seek(time, { keepPlaying: true, follow: false });
@@ -566,13 +570,21 @@ export function useTimelinePlayer({
566
570
  });
567
571
  }, [applyPlaybackRate, applyPreviewAudioState]);
568
572
 
573
+ const onLiveIframeLoad = useCallback(
574
+ (context?: number) => {
575
+ onIframeLoad(context);
576
+ onLiveLoaded();
577
+ },
578
+ [onIframeLoad, onLiveLoaded],
579
+ );
580
+
569
581
  return {
570
582
  iframeRef,
571
583
  play,
572
584
  pause,
573
585
  togglePlay,
574
586
  seek,
575
- onIframeLoad,
587
+ onIframeLoad: onLiveIframeLoad,
576
588
  refreshPlayer,
577
589
  saveSeekPosition,
578
590
  resetPlayer,
@@ -111,6 +111,10 @@ export function planShadowReload(
111
111
  return live ? [live, { gen: nextGen, role: "shadow", url }] : [{ gen: nextGen, role: "live" }];
112
112
  }
113
113
 
114
+ export function planShadowAlone(nextGen: number, url: string): PreviewIframeSlot[] {
115
+ return [{ gen: nextGen, role: "shadow", url }];
116
+ }
117
+
114
118
  /** Drop any pending shadow; the live slot (and its key) is untouched. */
115
119
  export function planShadowDiscard(slots: PreviewIframeSlot[]): PreviewIframeSlot[] {
116
120
  return slots.filter((slot) => slot.role === "live");
@@ -50,6 +50,7 @@ function described(n: number, extra: Partial<EditingElementDescription> = {}) {
50
50
  handle: h(n),
51
51
  parent: null,
52
52
  tag: "div",
53
+ label: "Text",
53
54
  id: null,
54
55
  selector: null,
55
56
  matchesBefore: null,
@@ -68,6 +69,8 @@ function described(n: number, extra: Partial<EditingElementDescription> = {}) {
68
69
  describe("readPreviewElement", () => {
69
70
  it("takes a description with the wire shape and refuses anything off it", () => {
70
71
  expect(readPreviewElement(described(1))).toEqual(described(1));
72
+ const { label: _label, ...fromAnOlderRuntime } = described(1);
73
+ expect(readPreviewElement(fromAnOlderRuntime)).toEqual(fromAnOlderRuntime);
71
74
  for (const bad of [
72
75
  null,
73
76
  [],
@@ -77,6 +80,7 @@ describe("readPreviewElement", () => {
77
80
  described(1, { handle: `${LOAD.toUpperCase()}:1` }),
78
81
  described(1, { parent: "x" }),
79
82
  described(1, { tag: 1 as never }),
83
+ described(1, { label: 1 as never }),
80
84
  described(1, { source: { file: 1 } as never }),
81
85
  described(1, { locked: "yes" as never }),
82
86
  described(1, { attributes: [["a"]] as never }),
@@ -70,6 +70,7 @@ function readHit(value: unknown): PreviewElementHit | null {
70
70
  export function readPreviewElement(value: unknown): PreviewElement | null {
71
71
  if (!readHit(value) || !isFields(value)) return null;
72
72
  if (value.parent !== null && !isHandle(value.parent)) return null;
73
+ if (value.label !== undefined && !isText(value.label)) return null;
73
74
  if (!isTextOrNull(value.id) || !isTextOrNull(value.selector)) return null;
74
75
  if (!isSource(value.source) || typeof value.locked !== "boolean") return null;
75
76
  if (!isTextRecord(value.inlineStyles) || !isText(value.text)) return null;
@@ -0,0 +1,21 @@
1
+ import { expect, it } from "vitest";
2
+ import * as studio from "@hyperframes/studio";
3
+ import * as elements from "./player/lib/previewElements";
4
+ import * as selection from "./components/editor/previewSelection";
5
+
6
+ it("exports a sealed preview's checked element reads and stand-ins as the ones Studio uses", () => {
7
+ expect(studio.describePreviewElements).toBe(elements.describePreviewElements);
8
+ expect(studio.previewAncestors).toBe(elements.previewAncestors);
9
+ expect(studio.previewElementsAtPoint).toBe(elements.previewElementsAtPoint);
10
+ expect(studio.previewGeometry).toBe(elements.previewGeometry);
11
+ expect(studio.previewLayers).toBe(elements.previewLayers);
12
+ expect(studio.previewPointerTargets).toBe(elements.previewPointerTargets);
13
+ expect(studio.queryPreviewElements).toBe(elements.queryPreviewElements);
14
+ expect(studio.findPreviewElementForSelection).toBe(selection.findPreviewElementForSelection);
15
+ expect(studio.findPreviewElementForTimelineElement).toBe(
16
+ selection.findPreviewElementForTimelineElement,
17
+ );
18
+ expect(studio.readable).toBe(selection.readable);
19
+ expect(studio.standInFor).toBe(selection.standInFor);
20
+ expect(studio.standInHandle).toBe(selection.standInHandle);
21
+ });
@@ -1,4 +1,8 @@
1
+ import { createStudioApi } from "@hyperframes/studio-server";
1
2
  import { IDBFactory } from "fake-indexeddb";
3
+ import { mkdtempSync, readdirSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
2
6
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
7
  import {
4
8
  createMemoryExternalConflictStorage,
@@ -9,6 +13,27 @@ import {
9
13
  } from "./externalConflictStorage";
10
14
  import { StudioFileConflictError } from "./studioSaveDiagnostics";
11
15
 
16
+ const made: string[] = [];
17
+
18
+ /** Studio's real API for one project, "demo", answering the store's fetches. */
19
+ function serveProject(): string {
20
+ const dir = mkdtempSync(join(tmpdir(), "hf-drafts-"));
21
+ made.push(dir);
22
+ const api = createStudioApi({
23
+ listProjects: () => [],
24
+ resolveProject: async (id: string) => (id === "demo" ? { id, dir, title: "Demo" } : null),
25
+ bundle: async () => null,
26
+ lint: async () => ({ findings: [] }),
27
+ runtimeUrl: "/api/runtime.js",
28
+ rendersDir: () => join(dir, "renders"),
29
+ startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "" }),
30
+ });
31
+ vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
32
+ api.fetch(new Request(`http://localhost${input.replace(/^\/api/, "")}`, init)),
33
+ );
34
+ return dir;
35
+ }
36
+
12
37
  describe("external conflict snapshots", () => {
13
38
  beforeEach(() => {
14
39
  vi.stubGlobal("indexedDB", new IDBFactory());
@@ -17,6 +42,7 @@ describe("external conflict snapshots", () => {
17
42
  afterEach(() => {
18
43
  vi.restoreAllMocks();
19
44
  vi.unstubAllGlobals();
45
+ for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });
20
46
  });
21
47
 
22
48
  it("durably records both complete file versions before resolution", async () => {
@@ -54,8 +80,8 @@ describe("external conflict snapshots", () => {
54
80
  expect(await storage.get("project-a", "index.html")).toEqual(snapshot);
55
81
  });
56
82
 
57
- it("persists, loads, and deletes a snapshot through the production IndexedDB adapter", async () => {
58
- vi.spyOn(Date, "now").mockReturnValue(1234);
83
+ it("persists, loads, and deletes a draft through the project's own server", async () => {
84
+ const project = serveProject();
59
85
  const conflict = new StudioFileConflictError({
60
86
  filePath: "index.html",
61
87
  currentVersion: "v2",
@@ -63,24 +89,50 @@ describe("external conflict snapshots", () => {
63
89
  attemptedContent: "studio full file",
64
90
  });
65
91
 
66
- await persistExternalConflictSnapshot("indexeddb-project", conflict);
67
- await expect(loadExternalConflictSnapshot("indexeddb-project", "index.html")).resolves.toEqual({
92
+ await persistExternalConflictSnapshot("demo", conflict);
93
+ expect(readdirSync(join(project, ".hyperframes", "recovery"))).toHaveLength(1);
94
+ await expect(loadExternalConflictSnapshot("demo", "index.html")).resolves.toMatchObject({
68
95
  kind: "conflict",
69
- projectId: "indexeddb-project",
96
+ projectId: "demo",
70
97
  filePath: "index.html",
71
98
  externalVersion: "v2",
72
99
  externalContent: "external full file",
73
100
  studioContent: "studio full file",
74
- createdAt: 1234,
75
101
  });
76
- await deleteExternalConflictSnapshot("indexeddb-project", "index.html");
77
- await expect(
78
- loadExternalConflictSnapshot("indexeddb-project", "index.html"),
79
- ).resolves.toBeNull();
102
+ await deleteExternalConflictSnapshot("demo", "index.html");
103
+ await expect(loadExternalConflictSnapshot("demo", "index.html")).resolves.toBeNull();
104
+ });
105
+
106
+ // Every project previewed on a port shares the origin's IndexedDB, and so does each one's composition code.
107
+ it("never offers a draft another project's code planted in the browser's shared IndexedDB", async () => {
108
+ serveProject();
109
+ const open = indexedDB.open("hyperframes-studio-external-conflicts", 1);
110
+ open.onupgradeneeded = () => open.result.createObjectStore("file-conflicts");
111
+ const db = await new Promise<IDBDatabase>(
112
+ (resolve) => (open.onsuccess = () => resolve(open.result)),
113
+ );
114
+ const planted = db.transaction("file-conflicts", "readwrite");
115
+ planted.objectStore("file-conflicts").put(
116
+ {
117
+ kind: "failed",
118
+ projectId: "demo",
119
+ filePath: "index.html",
120
+ externalVersion: null,
121
+ externalContent: null,
122
+ studioContent: "<script>planted</script>",
123
+ failureMessage: "Recovered draft",
124
+ createdAt: Date.now(),
125
+ },
126
+ "demo\0index.html",
127
+ );
128
+ await new Promise((resolve) => (planted.oncomplete = resolve));
129
+ db.close();
130
+
131
+ await expect(loadExternalConflictSnapshot("demo", "index.html")).resolves.toBeNull();
80
132
  });
81
133
 
82
- it("rejects persistence when IndexedDB is unavailable", async () => {
83
- vi.stubGlobal("indexedDB", undefined);
134
+ it("rejects persistence when the server cannot keep the draft", async () => {
135
+ vi.stubGlobal("fetch", async () => new Response("{}", { status: 500 }));
84
136
  const conflict = new StudioFileConflictError({
85
137
  filePath: "index.html",
86
138
  currentVersion: "v2",
@@ -88,8 +140,8 @@ describe("external conflict snapshots", () => {
88
140
  attemptedContent: "studio",
89
141
  });
90
142
 
91
- await expect(persistExternalConflictSnapshot("project-a", conflict)).rejects.toThrow(
92
- "IndexedDB is unavailable; conflict recovery snapshot was not saved",
143
+ await expect(persistExternalConflictSnapshot("demo", conflict)).rejects.toThrow(
144
+ "Recovery draft storage failed (500)",
93
145
  );
94
146
  });
95
147
  });
@@ -1,4 +1,5 @@
1
1
  import type { StudioFileConflictError } from "./studioSaveDiagnostics";
2
+ import { studioApiFetch } from "./studioApiFetch";
2
3
 
3
4
  interface ExternalRecoverySnapshotBase {
4
5
  projectId: string;
@@ -19,10 +20,6 @@ export interface ExternalConflictStorage {
19
20
  delete(projectId: string, filePath: string): Promise<void>;
20
21
  }
21
22
 
22
- const DB_NAME = "hyperframes-studio-external-conflicts";
23
- const DB_VERSION = 1;
24
- const STORE_NAME = "file-conflicts";
25
-
26
23
  function key(projectId: string, filePath: string): string {
27
24
  return `${projectId}\0${filePath}`;
28
25
  }
@@ -43,85 +40,46 @@ export function createMemoryExternalConflictStorage(): ExternalConflictStorage {
43
40
  };
44
41
  }
45
42
 
46
- function openDb(): Promise<IDBDatabase> {
47
- return new Promise((resolve, reject) => {
48
- if (!globalThis.indexedDB) {
49
- reject(new Error("IndexedDB is unavailable; conflict recovery snapshot was not saved"));
50
- return;
51
- }
52
- const request = globalThis.indexedDB.open(DB_NAME, DB_VERSION);
53
- request.onupgradeneeded = () => {
54
- if (!request.result.objectStoreNames.contains(STORE_NAME)) {
55
- request.result.createObjectStore(STORE_NAME);
56
- }
57
- };
58
- request.onerror = () => reject(request.error ?? new Error("Failed to open conflict storage"));
59
- request.onsuccess = () => resolve(request.result);
60
- });
61
- }
62
-
63
- function withStore<T>(
64
- mode: IDBTransactionMode,
65
- callback: (store: IDBObjectStore) => IDBRequest<T>,
66
- ): Promise<T> {
67
- return openDb().then(
68
- (db) =>
69
- new Promise<T>((resolve, reject) => {
70
- const transaction = db.transaction(STORE_NAME, mode);
71
- const request = callback(transaction.objectStore(STORE_NAME));
72
- let result!: T;
73
- request.onerror = () => reject(request.error ?? new Error("Conflict storage failed"));
74
- request.onsuccess = () => {
75
- result = request.result;
76
- };
77
- transaction.oncomplete = () => {
78
- db.close();
79
- resolve(result);
80
- };
81
- transaction.onerror = () => {
82
- db.close();
83
- reject(transaction.error ?? new Error("Conflict storage transaction failed"));
84
- };
85
- transaction.onabort = () => {
86
- db.close();
87
- reject(transaction.error ?? new Error("Conflict storage transaction was aborted"));
88
- };
89
- }),
90
- );
43
+ function draftUrl(projectId: string, filePath: string): string {
44
+ return `/api/projects/${encodeURIComponent(projectId)}/recovery-drafts/${encodeURIComponent(filePath)}`;
91
45
  }
92
46
 
93
- function createIndexedDbExternalConflictStorage(): ExternalConflictStorage {
94
- return {
95
- async get(projectId, filePath) {
96
- return (
97
- (await withStore<ExternalConflictSnapshot | undefined>("readonly", (store) =>
98
- store.get(key(projectId, filePath)),
99
- )) ?? null
100
- );
101
- },
102
- async set(snapshot) {
103
- await withStore<IDBValidKey>("readwrite", (store) =>
104
- store.put(snapshot, key(snapshot.projectId, snapshot.filePath)),
105
- );
106
- },
107
- async delete(projectId, filePath) {
108
- await withStore<undefined>("readwrite", (store) => store.delete(key(projectId, filePath)));
109
- },
110
- };
47
+ async function draftRequest(
48
+ projectId: string,
49
+ filePath: string,
50
+ init?: RequestInit,
51
+ ): Promise<Response> {
52
+ const res = await studioApiFetch(draftUrl(projectId, filePath), init);
53
+ if (!res.ok) throw new Error(`Recovery draft storage failed (${res.status})`);
54
+ return res;
111
55
  }
112
56
 
113
- const indexedDbStorage = createIndexedDbExternalConflictStorage();
57
+ /** Kept by the project's own server: an origin-wide browser store is shared with every project on the port. */
58
+ const projectStorage: ExternalConflictStorage = {
59
+ async get(projectId, filePath) {
60
+ const { draft } = (await (await draftRequest(projectId, filePath)).json()) as {
61
+ draft: ExternalConflictSnapshot | null;
62
+ };
63
+ return draft?.projectId === projectId && draft.filePath === filePath ? draft : null;
64
+ },
65
+ async set(snapshot) {
66
+ await draftRequest(snapshot.projectId, snapshot.filePath, {
67
+ method: "PUT",
68
+ headers: { "content-type": "application/json" },
69
+ body: JSON.stringify(snapshot),
70
+ });
71
+ },
72
+ async delete(projectId, filePath) {
73
+ await draftRequest(projectId, filePath, { method: "DELETE" });
74
+ },
75
+ };
114
76
 
115
- /**
116
- * Persist a conflict before offering destructive recovery actions.
117
- * Callers must await this promise: rejection means the Studio draft was not saved durably and
118
- * must remain available in memory while the storage failure is surfaced to the user.
119
- */
77
+ /** Saved before destructive recovery is offered; on a rejection the draft stays only in memory and the user is told. */
120
78
  export async function persistExternalConflictSnapshot(
121
79
  projectId: string,
122
80
  conflict: StudioFileConflictError,
123
81
  ): Promise<void> {
124
- await indexedDbStorage.set({
82
+ await projectStorage.set({
125
83
  kind: "conflict",
126
84
  projectId,
127
85
  filePath: conflict.filePath,
@@ -132,11 +90,7 @@ export async function persistExternalConflictSnapshot(
132
90
  });
133
91
  }
134
92
 
135
- /**
136
- * Persist the final Studio candidate after its file write fails.
137
- * Callers must await this promise: rejection means the Studio draft was not saved durably and
138
- * must remain available in memory while the storage failure is surfaced to the user.
139
- */
93
+ /** Studio's final candidate after its file write failed; awaited like persistExternalConflictSnapshot. */
140
94
  export async function persistExternalFailureSnapshot(
141
95
  projectId: string,
142
96
  filePath: string,
@@ -145,7 +99,7 @@ export async function persistExternalFailureSnapshot(
145
99
  externalContent: string | null,
146
100
  error: unknown,
147
101
  ): Promise<void> {
148
- await indexedDbStorage.set({
102
+ await projectStorage.set({
149
103
  kind: "failed",
150
104
  projectId,
151
105
  filePath,
@@ -161,12 +115,12 @@ export async function loadExternalConflictSnapshot(
161
115
  projectId: string,
162
116
  filePath: string,
163
117
  ): Promise<ExternalConflictSnapshot | null> {
164
- return indexedDbStorage.get(projectId, filePath);
118
+ return projectStorage.get(projectId, filePath);
165
119
  }
166
120
 
167
121
  export async function deleteExternalConflictSnapshot(
168
122
  projectId: string,
169
123
  filePath: string,
170
124
  ): Promise<void> {
171
- await indexedDbStorage.delete(projectId, filePath);
125
+ await projectStorage.delete(projectId, filePath);
172
126
  }