@hyperframes/studio 0.9.64 → 0.9.66

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 (99) hide show
  1. package/dist/assets/hyperframes-player-VGx6ow_e.js +573 -0
  2. package/dist/assets/{index-CVmmHGol.js → index-B8Xt_Oyw.js} +190 -186
  3. package/dist/assets/{index-DN167Uqf.js → index-BH18TdX9.js} +1 -1
  4. package/dist/assets/{pausedVideoDecoder-C8rhpGPx.js → pausedVideoDecoder-Bx3fGNkU.js} +1 -1
  5. package/dist/{chunk-VDDEXNVX.js → chunk-ESTBKVCB.js} +8 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.html +1 -1
  8. package/dist/index.js +1580 -882
  9. package/dist/player.js +1 -1
  10. package/package.json +8 -8
  11. package/src/captions/components/CaptionOverlay.sealed.test.ts +2 -25
  12. package/src/captions/hooks/useCaptionSync.ts +4 -1
  13. package/src/components/editor/LayersPanel.opaque.test.ts +4 -29
  14. package/src/components/editor/MotionPathOverlay.sealed.test.tsx +85 -0
  15. package/src/components/editor/MotionPathOverlay.tsx +26 -12
  16. package/src/components/editor/domEditOverlayCrop.ts +78 -15
  17. package/src/components/editor/domEditOverlayCropFrameLift.test.ts +64 -0
  18. package/src/components/editor/domEditOverlayStartGesture.ts +0 -14
  19. package/src/components/editor/gestureUndoRevert.ts +3 -6
  20. package/src/components/editor/gsapMoveSealedPreview.test.ts +247 -0
  21. package/src/components/editor/manualEditsSnapshot.ts +2 -0
  22. package/src/components/editor/manualOffsetDrag.ts +13 -18
  23. package/src/components/editor/plainTranslate.test.ts +22 -1
  24. package/src/components/editor/plainTranslate.ts +8 -6
  25. package/src/components/editor/previewDrafts.test.ts +13 -39
  26. package/src/components/editor/previewDrafts.ts +4 -0
  27. package/src/components/editor/previewGestureStartRead.test.ts +59 -32
  28. package/src/components/editor/previewGestureStartRead.ts +9 -0
  29. package/src/components/editor/previewLayers.test.ts +3 -20
  30. package/src/components/editor/previewOverlayRects.test.ts +3 -20
  31. package/src/components/editor/previewPointerTargets.test.ts +3 -20
  32. package/src/components/editor/previewSelection.test.ts +51 -35
  33. package/src/components/editor/previewSelection.ts +18 -0
  34. package/src/components/editor/useColorGradingController.sealed.test.ts +5 -30
  35. package/src/components/editor/useMotionPathData.reply.test.ts +40 -0
  36. package/src/components/editor/useMotionPathData.sealed.test.ts +57 -0
  37. package/src/components/editor/useMotionPathData.test.tsx +1 -1
  38. package/src/components/editor/useMotionPathData.ts +83 -33
  39. package/src/components/nle/CompositionBreadcrumb.tsx +2 -5
  40. package/src/components/nle/NLEContext.drillDown.test.ts +85 -0
  41. package/src/components/nle/NLEContext.tsx +21 -23
  42. package/src/components/nle/NLEPreview.test.ts +18 -3
  43. package/src/components/nle/NLEPreview.tsx +10 -1
  44. package/src/components/nle/audioSealedPreview.test.ts +5 -32
  45. package/src/components/panels/motionBlurPanelModel.sealed.test.ts +30 -0
  46. package/src/components/panels/motionBlurPanelModel.ts +37 -7
  47. package/src/hooks/appHotkeysDispatch.ts +38 -1
  48. package/src/hooks/domEditCommits.sealed.test.ts +191 -0
  49. package/src/hooks/domStyleCommit.ts +18 -7
  50. package/src/hooks/draggedGsapPosition.ts +20 -0
  51. package/src/hooks/gsapEditOutcome.ts +3 -0
  52. package/src/hooks/gsapFrameSnapshot.test.ts +113 -0
  53. package/src/hooks/gsapFrameSnapshot.ts +246 -0
  54. package/src/hooks/gsapParsedTween.ts +16 -9
  55. package/src/hooks/gsapResizeIntercept.ts +7 -2
  56. package/src/hooks/gsapRuntimeBridge.ts +4 -0
  57. package/src/hooks/gsapRuntimeKeyframes.ts +23 -15
  58. package/src/hooks/gsapShared.ts +4 -0
  59. package/src/hooks/gsapSnapshotReply.ts +105 -0
  60. package/src/hooks/useAppHotkeys.previewForwarding.test.tsx +134 -0
  61. package/src/hooks/useAppHotkeys.ts +36 -1
  62. package/src/hooks/useDomEditAttributeCommits.ts +43 -19
  63. package/src/hooks/useDomEditCommits.test.tsx +1 -1
  64. package/src/hooks/useDomEditPreviewSync.test.ts +36 -1
  65. package/src/hooks/useDomEditPreviewSync.ts +3 -3
  66. package/src/hooks/useEditorSave.ts +2 -1
  67. package/src/hooks/useEnableKeyframes.sealed.test.ts +70 -0
  68. package/src/hooks/useEnableKeyframes.ts +9 -2
  69. package/src/hooks/useGsapTweenCache.ts +9 -3
  70. package/src/hooks/usePreviewPersistence.ts +18 -11
  71. package/src/hooks/useSdkSession.lifecycle.test.tsx +1 -0
  72. package/src/hooks/useSdkSession.ts +2 -0
  73. package/src/hooks/useSlideshowTabState.test.ts +47 -3
  74. package/src/hooks/useSlideshowTabState.ts +32 -16
  75. package/src/player/hooks/timelinePlayerTestHarness.ts +2 -1
  76. package/src/player/hooks/usePlaybackKeyboard.ts +1 -1
  77. package/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts +2 -29
  78. package/src/player/lib/previewChannel.test.ts +10 -0
  79. package/src/player/lib/previewChannel.ts +9 -0
  80. package/src/player/lib/previewElements.test.ts +34 -1
  81. package/src/player/lib/previewElements.ts +101 -18
  82. package/src/player/lib/sealedPreviewFrame.test-helpers.ts +38 -0
  83. package/src/player/lib/timelineIframeHelpers.ts +1 -1
  84. package/src/telemetry/client.ts +4 -2
  85. package/src/telemetry/eventShape.test.ts +189 -0
  86. package/src/telemetry/eventShape.ts +192 -0
  87. package/src/utils/blockInstaller.test.ts +82 -48
  88. package/src/utils/blockInstaller.ts +6 -14
  89. package/src/utils/domEditSaveQueue.test.ts +12 -2
  90. package/src/utils/domEditSaveQueue.ts +4 -4
  91. package/src/utils/previewCompositionSize.test.ts +61 -0
  92. package/src/utils/previewCompositionSize.ts +21 -1
  93. package/src/utils/sdkEditTransaction.ts +6 -2
  94. package/src/utils/sdkResolverShadow.ts +16 -15
  95. package/src/utils/studioSaveDiagnostics.test.ts +21 -3
  96. package/src/utils/studioSaveDiagnostics.ts +71 -6
  97. package/src/utils/studioTelemetry.ts +6 -1
  98. package/dist/assets/hyperframes-player-mSF_GvRs.js +0 -573
  99. package/src/components/editor/motionPathHome.ts +0 -75
@@ -0,0 +1,189 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+
4
+ vi.mock("./policy", () => ({ browserTelemetryAllowed: () => true }));
5
+ vi.mock("./canary", () => ({ canaryEventProperties: () => ({}) }));
6
+
7
+ const CONTENT = [
8
+ "/Users/ana/客户/秘密 video.mp4",
9
+ "compositions/intro.html",
10
+ "C:\\Users\\ana\\proj\\index.html",
11
+ "#hero-title",
12
+ '[data-composition-id="intro"]',
13
+ ".cta",
14
+ "forbidden path: compositions/x.html",
15
+ ];
16
+
17
+ const PROPERTIES = {
18
+ file_path: CONTENT[0],
19
+ target_source_file: CONTENT[1],
20
+ source_file: CONTENT[2],
21
+ target_selector: CONTENT[3],
22
+ selector: CONTENT[4],
23
+ target_id: "hero-title",
24
+ detail: CONTENT[5],
25
+ error_message: CONTENT[6],
26
+ status_code: 403,
27
+ };
28
+
29
+ type Sent = Array<{ event: string; properties: Record<string, unknown> }>;
30
+
31
+ describe("Studio analytics leave the machine without paths or selectors", () => {
32
+ let fetchMock: ReturnType<typeof vi.fn>;
33
+
34
+ beforeEach(() => {
35
+ localStorage.clear();
36
+ sessionStorage.clear();
37
+ vi.resetModules();
38
+ vi.useFakeTimers();
39
+ fetchMock = vi.fn(() => Promise.resolve({ ok: true } as Response));
40
+ vi.stubGlobal("fetch", fetchMock);
41
+ });
42
+
43
+ afterEach(() => {
44
+ vi.useRealTimers();
45
+ vi.unstubAllGlobals();
46
+ });
47
+
48
+ async function sent(): Promise<{ body: string; batch: Sent }> {
49
+ await vi.runOnlyPendingTimersAsync();
50
+ const bodies = fetchMock.mock.calls.map((call) =>
51
+ String((call[1] as { body?: string })?.body ?? ""),
52
+ );
53
+ const batch = bodies.flatMap((body) => (JSON.parse(body) as { batch: Sent }).batch);
54
+ return { body: bodies.join("\n"), batch };
55
+ }
56
+
57
+ async function send(transport: "studio:*" | "studio_*", event: string, properties: object) {
58
+ if (transport === "studio:*")
59
+ (await import("../utils/studioTelemetry")).trackStudioEvent(event, properties as never);
60
+ else (await import("./client")).trackEvent(event, properties as never);
61
+ }
62
+
63
+ it.each(["studio:*", "studio_*"] as const)(
64
+ "the %s transport sends none of the content, only facts that still group it",
65
+ async (transport) => {
66
+ await send(transport, "save_failure", PROPERTIES);
67
+ await send(transport, "save_failure", PROPERTIES);
68
+ const { body, batch } = await sent();
69
+
70
+ expect(batch).toHaveLength(2);
71
+ for (const text of [...CONTENT, "hero-title", "intro.html", "秘密"]) {
72
+ expect(body).not.toContain(JSON.stringify(text).slice(1, -1));
73
+ }
74
+ const [first, second] = batch.map((e) => e.properties);
75
+ expect(first).toMatchObject({
76
+ file_path_ext: "mp4",
77
+ file_path_kind: "asset",
78
+ target_source_file_kind: "composition",
79
+ target_source_file_depth: 1,
80
+ source_file_ext: "html",
81
+ target_selector_kind: "id",
82
+ selector_kind: "attribute",
83
+ target_id_kind: "id",
84
+ status_code: 403,
85
+ dropped_fields: "detail",
86
+ });
87
+ expect(first?.error_message_shape).toMatch(/^[0-9a-f]{8}$/);
88
+ expect(first?.file_path_hash).toMatch(/^[0-9a-f]{8}$/);
89
+ // The same path from the same install groups; the salt that keys it never leaves.
90
+ expect(second?.file_path_hash).toBe(first?.file_path_hash);
91
+ expect(body).not.toContain(
92
+ localStorage.getItem("hyperframes-studio:telemetrySalt") ?? "missing-salt",
93
+ );
94
+ },
95
+ );
96
+
97
+ it("keeps the session's own fields when a caller sends the same names", async () => {
98
+ await send("studio:*", "navigation", { url_hash: "custom", tab_id: "custom" });
99
+ const { batch } = await sent();
100
+ expect(batch[0]?.properties.url_hash).not.toBe("custom");
101
+ expect(batch[0]?.properties.tab_id).not.toBe("custom");
102
+ });
103
+
104
+ const PROJECT_FRAME =
105
+ "http://localhost:3002/api/projects/acme-launch/preview/compositions/intro.html:12:3";
106
+ const STACK = [
107
+ "Error: Failed to save compositions/intro.html (403): forbidden path: /Users/ana/客户/x.html",
108
+ ` at mountClip (${PROJECT_FRAME})`,
109
+ ` at commitEdit (${location.origin}/assets/index-B4x2.js:40:7)`,
110
+ ` at ${location.origin}/assets/vendor-C9.js:1:99`,
111
+ ].join("\n");
112
+ const LEAKS = ["acme-launch", "intro.html", "客户", "/Users/ana", "forbidden path", "mountClip"];
113
+
114
+ it.each(["studio:*", "studio_*"] as const)(
115
+ "the %s transport sends an error's class, a shape and its own frames, never its words",
116
+ async (transport) => {
117
+ await send(transport, "crash", {
118
+ error_message:
119
+ "Failed to save compositions/intro.html (403): forbidden path: /Users/ana/客户/x.html",
120
+ error_name: "StudioSaveHttpError",
121
+ stack_trace: STACK,
122
+ component_stack: `\n at ClipRow (${PROJECT_FRAME})\n at Timeline (${location.origin}/assets/index-B4x2.js:9:1)`,
123
+ });
124
+ await send(transport, "unhandled_promise_rejection", {
125
+ error_message: "acme-launch secret",
126
+ error_name: null,
127
+ stack_trace: null,
128
+ });
129
+ await send(transport, "unhandled_error", {
130
+ error: "x",
131
+ filename: PROJECT_FRAME.replace(/:\d+:\d+$/, ""),
132
+ });
133
+ const { body, batch } = await sent();
134
+
135
+ for (const text of LEAKS) expect(body).not.toContain(text);
136
+ const [crash, rejection, uncaught] = batch.map((e) => e.properties);
137
+ expect(crash).toMatchObject({
138
+ error_name: "StudioSaveHttpError",
139
+ error_message_status: 403,
140
+ stack_trace: "?\ncommitEdit@index-B4x2.js:40:7\n<anonymous>@vendor-C9.js:1:99",
141
+ component_stack: "ClipRow\nTimeline",
142
+ });
143
+ expect(crash?.error_message_shape).toMatch(/^[0-9a-f]{8}$/);
144
+ expect(rejection?.error_message_shape).toMatch(/^[0-9a-f]{8}$/);
145
+ expect(uncaught?.dropped_fields).toBe("filename");
146
+ },
147
+ );
148
+
149
+ it("leaves feedback text the person typed to send", async () => {
150
+ await send("studio_*", "studio_feedback", {
151
+ comment: "export of compositions/intro.html froze",
152
+ });
153
+ const { batch } = await sent();
154
+ expect(batch[0]?.properties.comment).toBe("export of compositions/intro.html froze");
155
+ });
156
+ });
157
+
158
+ describe("errors leave no project name, even shaped", () => {
159
+ const shape = async (properties: Record<string, string>) =>
160
+ (await import("./eventShape")).shapeEventProperties("studio:crash", properties);
161
+
162
+ it("keeps only frames with an absolute address on Studio's own origin", async () => {
163
+ const shaped = await shape({
164
+ stack_trace: [
165
+ "Error: acme-launch@acme-launch.js:1:2",
166
+ " at secretHandler (/home/ana/acme-launch/server.js:10:5)",
167
+ " at secretHandler (acme-launch-intro.js:10:5)",
168
+ ].join("\n"),
169
+ filename: "acme-launch.js",
170
+ });
171
+ expect(JSON.stringify(shaped)).not.toMatch(/acme|secretHandler/);
172
+ expect(shaped.dropped_fields).toBe("filename");
173
+ });
174
+
175
+ it("gives two projects' same failure the same shape", async () => {
176
+ const pairs = [
177
+ ["acme-launch", "other-proj"].map(
178
+ (name) =>
179
+ `Failed to fetch dynamically imported module: http://localhost/api/projects/${name}/preview/x.js`,
180
+ ),
181
+ ["#acme-title", "#other-title"].map((id) => `GSAP target ${id} not found.`),
182
+ ];
183
+ for (const [a, b] of pairs) {
184
+ expect((await shape({ error_message: a! })).error_message_shape).toBe(
185
+ (await shape({ error_message: b! })).error_message_shape,
186
+ );
187
+ }
188
+ });
189
+ });
@@ -0,0 +1,192 @@
1
+ // The one place Studio's event values are shaped before they leave the machine, for both
2
+ // transports. A path or a selector becomes facts that still group and debug (extension, kind,
3
+ // depth, a per-install hash); any other value that reads as one is dropped and named.
4
+ import { redactTelemetryString } from "@hyperframes/core/telemetry-redaction";
5
+ import { hashContent } from "../hooks/sdkSelfWriteRegistry";
6
+
7
+ type Value = string | number | boolean | null | undefined;
8
+ type Facts = Record<string, string | number>;
9
+
10
+ const PATH_KEYS = new Set([
11
+ "file_path",
12
+ "target_source_file",
13
+ "source_file",
14
+ "path",
15
+ "composition",
16
+ "render_composition",
17
+ ]);
18
+ const SELECTOR_KEYS = new Set(["target_selector", "selector", "target_id", "animationId"]);
19
+ const MESSAGE_KEYS = new Set(["error_message", "error", "render_error", "render_stage"]);
20
+ // Text the person typed to send to us on purpose.
21
+ const KEPT_AS_TYPED: Record<string, ReadonlySet<string>> = {
22
+ studio_feedback: new Set(["comment"]),
23
+ };
24
+
25
+ const SALT_KEY = "hyperframes-studio:telemetrySalt";
26
+ let sessionSalt: string | undefined;
27
+
28
+ function newSalt(): string {
29
+ const bytes = new Uint8Array(16);
30
+ crypto.getRandomValues(bytes);
31
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
32
+ }
33
+
34
+ /** Kept on this install and never sent: a hash groups repeats here but names nothing elsewhere. */
35
+ function installSalt(): string {
36
+ try {
37
+ const saved = localStorage.getItem(SALT_KEY);
38
+ if (saved && /^[0-9a-f]{32}$/.test(saved)) return saved;
39
+ const salt = newSalt();
40
+ localStorage.setItem(SALT_KEY, salt);
41
+ return salt;
42
+ } catch {
43
+ sessionSalt ??= newSalt();
44
+ return sessionSalt;
45
+ }
46
+ }
47
+
48
+ // ponytail: 32-bit FNV-1a groups one install's repeats; a collision only merges two groups.
49
+ const hashOf = (value: string): string =>
50
+ hashContent(`${installSalt()}\0${value}`).padStart(8, "0");
51
+
52
+ const KINDS: Record<string, string> = {
53
+ html: "composition",
54
+ htm: "composition",
55
+ js: "script",
56
+ mjs: "script",
57
+ cjs: "script",
58
+ ts: "script",
59
+ tsx: "script",
60
+ jsx: "script",
61
+ css: "style",
62
+ scss: "style",
63
+ less: "style",
64
+ };
65
+
66
+ function pathFacts(key: string, value: string): Facts {
67
+ const paths = value.split(",").filter((p) => p.trim().length > 0);
68
+ const first = paths[0] ?? value;
69
+ const segments = first.split(/[\\/]/).filter(Boolean);
70
+ const name = segments.at(-1) ?? "";
71
+ const dot = name.lastIndexOf(".");
72
+ const raw = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
73
+ const ext = /^[a-z0-9]{1,8}$/.test(raw) ? raw : "none";
74
+ const kind = ext === "none" ? "other" : (KINDS[ext] ?? "asset");
75
+ return {
76
+ [`${key}_ext`]: ext,
77
+ [`${key}_kind`]: kind,
78
+ [`${key}_depth`]: Math.max(segments.length - 1, 0),
79
+ [`${key}_hash`]: hashOf(first),
80
+ ...(paths.length > 1 ? { [`${key}_count`]: paths.length } : {}),
81
+ };
82
+ }
83
+
84
+ function selectorFacts(key: string, value: string): Facts {
85
+ const s = value.trim();
86
+ const kind =
87
+ key === "target_id"
88
+ ? "id"
89
+ : s.startsWith("#")
90
+ ? "id"
91
+ : s.startsWith(".")
92
+ ? "class"
93
+ : s.startsWith("[")
94
+ ? "attribute"
95
+ : "other";
96
+ return { [`${key}_kind`]: kind, [`${key}_hash`]: hashOf(s) };
97
+ }
98
+
99
+ function messageFacts(key: string, value: string): Facts {
100
+ const line = redactTelemetryString(value.split("\n", 1)[0] ?? "", Number.MAX_SAFE_INTEGER)
101
+ .replace(/\b(?:https?|blob|data|file|[a-z-]+-extension):\S*/gi, "<url>")
102
+ .replace(/(^|[\s(])[#.][A-Za-z_][\w-]*/g, "$1<sel>")
103
+ .replace(/(["'`]).*?\1/g, "?")
104
+ .replace(/\d+/g, "#");
105
+ const status = /(?:\(|HTTP |status |failed: )([1-5]\d\d)\b/.exec(value)?.[1];
106
+ return {
107
+ [`${key}_shape`]: hashOf(line),
108
+ ...(status ? { [`${key}_status`]: Number(status) } : {}),
109
+ };
110
+ }
111
+
112
+ function bundleFile(url: string): string | null {
113
+ if (!/^https?:\/\//i.test(url)) return null;
114
+ try {
115
+ const at = new URL(url);
116
+ if (at.origin !== location.origin || at.pathname.startsWith("/api/")) return null;
117
+ const name = at.pathname.split("/").pop() ?? "";
118
+ return /^[\w.-]+\.(?:m?js|tsx?|jsx?)$/.test(name) ? name : null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ const V8_FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
125
+ const GECKO_FRAME = /^(.*?)@(.+?):(\d+):(\d+)\s*$/;
126
+
127
+ function shapedFrames(stack: string): string {
128
+ const frames: string[] = [];
129
+ for (const line of stack.split("\n")) {
130
+ const m = V8_FRAME.exec(line) ?? GECKO_FRAME.exec(line);
131
+ if (!m) continue;
132
+ const file = bundleFile(m[2] ?? "");
133
+ frames.push(file ? `${m[1]?.trim() || "<anonymous>"}@${file}:${m[3]}:${m[4]}` : "?");
134
+ if (frames.length === 20) break;
135
+ }
136
+ return frames.join("\n");
137
+ }
138
+
139
+ const componentNames = (stack: string): string =>
140
+ [...stack.matchAll(/^\s*(?:at|in)\s+([A-Za-z_$][\w$.]*)/gm)]
141
+ .slice(0, 30)
142
+ .map((m) => m[1])
143
+ .join("\n");
144
+
145
+ const ATTRIBUTE_SELECTOR = /\[[\w:-]+(?:[~|^$*]?=[^\]]*)?\]/;
146
+ const ID_OR_CLASS = /^\s*[#.][A-Za-z_-][\w-]*/;
147
+ const HEX_COLOUR = /^#[0-9a-f]{3,8}$/i;
148
+
149
+ function readsAsPathOrSelector(value: string): boolean {
150
+ if (redactTelemetryString(value, Number.MAX_SAFE_INTEGER) !== value) return true;
151
+ return (
152
+ ATTRIBUTE_SELECTOR.test(value) || (ID_OR_CLASS.test(value) && !HEX_COLOUR.test(value.trim()))
153
+ );
154
+ }
155
+
156
+ type Shaper = (key: string, value: string) => Facts | null;
157
+ const single =
158
+ (shape: (value: string) => string | null): Shaper =>
159
+ (key, value) => {
160
+ const shaped = shape(value);
161
+ return shaped === null ? null : { [key]: shaped };
162
+ };
163
+ const otherValue: Shaper = (key, value) => (readsAsPathOrSelector(value) ? null : { [key]: value });
164
+ const SHAPERS: Record<string, Shaper> = {
165
+ ...Object.fromEntries([...MESSAGE_KEYS].map((key) => [key, messageFacts])),
166
+ ...Object.fromEntries([...PATH_KEYS].map((key) => [key, pathFacts])),
167
+ ...Object.fromEntries([...SELECTOR_KEYS].map((key) => [key, selectorFacts])),
168
+ stack_trace: single(shapedFrames),
169
+ component_stack: single(componentNames),
170
+ filename: single(bundleFile),
171
+ };
172
+
173
+ /** A caller's properties as they may leave the machine; runs before the transport's own fields. */
174
+ export function shapeEventProperties<V extends Value>(
175
+ event: string,
176
+ properties: Record<string, V>,
177
+ ): Record<string, V | string | number> {
178
+ const kept = KEPT_AS_TYPED[event];
179
+ const out: Record<string, V | string | number> = {};
180
+ const dropped: string[] = [];
181
+ for (const [key, value] of Object.entries(properties)) {
182
+ if (typeof value !== "string" || value === "" || kept?.has(key)) {
183
+ out[key] = value;
184
+ continue;
185
+ }
186
+ const facts = (SHAPERS[key] ?? otherValue)(key, value);
187
+ if (facts) Object.assign(out, facts);
188
+ else dropped.push(key);
189
+ }
190
+ if (dropped.length > 0) out.dropped_fields = dropped.join(",");
191
+ return out;
192
+ }
@@ -1,64 +1,74 @@
1
1
  // @vitest-environment happy-dom
2
2
 
3
3
  import { afterEach, describe, expect, it, vi } from "vitest";
4
+ import { previewRequest } from "../player/lib/previewChannel";
4
5
  import { addBlockToProject } from "./blockInstaller";
5
6
 
7
+ vi.mock("../player/lib/previewChannel", async (importOriginal) => {
8
+ const actual = await importOriginal<typeof import("../player/lib/previewChannel")>();
9
+ return { ...actual, previewRequest: vi.fn(async () => null) };
10
+ });
11
+
6
12
  afterEach(() => {
7
13
  vi.unstubAllGlobals();
8
14
  });
9
15
 
10
- describe("addBlockToProject", () => {
11
- it("uses an explicit selected-media duration and track for a Registry overlay block", async () => {
12
- const componentPath = "compositions/camcorder-hud.html";
13
- const targetPath = "compositions/scene.html";
14
- const files = new Map([
15
- [
16
- componentPath,
17
- `<body><div data-composition-id="camcorder-hud"><div class="hud"></div></div></body>`,
18
- ],
19
- [
20
- targetPath,
21
- `<main data-composition-id="scene" data-duration="10" data-width="1920" data-height="1080"></main>`,
22
- ],
23
- ]);
24
- vi.stubGlobal(
25
- "fetch",
26
- vi.fn().mockResolvedValue({
27
- ok: true,
28
- json: async () => ({
29
- written: [componentPath],
30
- block: {
31
- name: "camcorder-hud",
32
- title: "Camcorder HUD",
33
- description: "HUD",
34
- type: "hyperframes:block",
35
- files: [],
36
- dimensions: { width: 1920, height: 1080 },
37
- duration: 4,
38
- },
39
- }),
16
+ async function addHud(extra: Partial<Parameters<typeof addBlockToProject>[0]> = {}) {
17
+ const componentPath = "compositions/camcorder-hud.html";
18
+ const targetPath = "compositions/scene.html";
19
+ const files = new Map([
20
+ [
21
+ componentPath,
22
+ `<body><div data-composition-id="camcorder-hud"><div class="hud"></div></div></body>`,
23
+ ],
24
+ [
25
+ targetPath,
26
+ `<main data-composition-id="scene" data-duration="10" data-width="1920" data-height="1080"></main>`,
27
+ ],
28
+ ]);
29
+ vi.stubGlobal(
30
+ "fetch",
31
+ vi.fn().mockResolvedValue({
32
+ ok: true,
33
+ json: async () => ({
34
+ written: [componentPath],
35
+ block: {
36
+ name: "camcorder-hud",
37
+ title: "Camcorder HUD",
38
+ description: "HUD",
39
+ type: "hyperframes:block",
40
+ files: [],
41
+ dimensions: { width: 1920, height: 1080 },
42
+ duration: 4,
43
+ },
40
44
  }),
41
- );
42
- const writeProjectFile = vi.fn(async (path: string, content: string) => {
43
- files.set(path, content);
44
- });
45
+ }),
46
+ );
47
+ const writeProjectFile = vi.fn(async (path: string, content: string) => {
48
+ files.set(path, content);
49
+ });
45
50
 
46
- const result = await addBlockToProject({
47
- projectId: "project",
48
- blockName: "camcorder-hud",
49
- activeCompPath: targetPath,
50
- placement: { start: 2.5, duration: 4.25, track: 3 },
51
- timelineElements: [],
52
- readProjectFile: async (path) => files.get(path) ?? "",
53
- writeProjectFile,
54
- recordEdit: vi.fn().mockResolvedValue(undefined),
55
- refreshFileTree: vi.fn().mockResolvedValue(undefined),
56
- reloadPreview: vi.fn(),
57
- showToast: vi.fn(),
58
- });
51
+ const result = await addBlockToProject({
52
+ projectId: "project",
53
+ blockName: "camcorder-hud",
54
+ activeCompPath: targetPath,
55
+ placement: { start: 2.5, duration: 4.25, track: 3 },
56
+ timelineElements: [],
57
+ readProjectFile: async (path) => files.get(path) ?? "",
58
+ writeProjectFile,
59
+ recordEdit: vi.fn().mockResolvedValue(undefined),
60
+ refreshFileTree: vi.fn().mockResolvedValue(undefined),
61
+ reloadPreview: vi.fn(),
62
+ showToast: vi.fn(),
63
+ ...extra,
64
+ });
65
+ return { result, source: files.get(targetPath) };
66
+ }
59
67
 
68
+ describe("addBlockToProject", () => {
69
+ it("uses an explicit selected-media duration and track for a Registry overlay block", async () => {
70
+ const { result, source } = await addHud();
60
71
  expect(result?.block.name).toBe("camcorder-hud");
61
- const source = files.get(targetPath);
62
72
  expect(source).toContain('data-composition-src="compositions/camcorder-hud.html"');
63
73
  expect(source).toContain('data-start="2.5"');
64
74
  expect(source).toContain('data-duration="4.25"');
@@ -68,4 +78,28 @@ describe("addBlockToProject", () => {
68
78
  expect(result?.hostKey).toBe("compositions/scene.html#camcorder-hud");
69
79
  expect(source).toContain('id="camcorder-hud"');
70
80
  });
81
+
82
+ it("stacks the block above everything a sealed preview paints, read over its editing port", async () => {
83
+ const iframe = document.createElement("iframe");
84
+ Object.defineProperty(iframe, "contentDocument", {
85
+ get() {
86
+ throw new DOMException(
87
+ "Blocked a frame from accessing a cross-origin frame.",
88
+ "SecurityError",
89
+ );
90
+ },
91
+ });
92
+ vi.mocked(previewRequest).mockResolvedValueOnce({ zIndex: 41 });
93
+ const { source } = await addHud({ previewIframe: iframe });
94
+ expect(vi.mocked(previewRequest)).toHaveBeenCalledWith(iframe, "max-z-index", {});
95
+ expect(source).toContain("z-index: 42");
96
+ });
97
+
98
+ it("stacks at 1 when the preview's z-index is not a whole number of zero or more", async () => {
99
+ for (const zIndex of [-5, 0.5, 1e308]) {
100
+ vi.mocked(previewRequest).mockResolvedValueOnce({ zIndex });
101
+ const { source } = await addHud({ previewIframe: document.createElement("iframe") });
102
+ expect(source).toContain('z-index: 1"');
103
+ }
104
+ });
71
105
  });
@@ -13,20 +13,11 @@ import { serializeStudioFileMutation } from "./studioFileMutationCoordinator";
13
13
  import { extendRootDurationInSource } from "./rootDuration";
14
14
  import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";
15
15
  import { studioApiFetch } from "./studioApiFetch";
16
+ import { previewRequest } from "../player/lib/previewChannel";
16
17
 
17
- function getMaxZIndexFromIframe(iframe: HTMLIFrameElement | null): number {
18
- try {
19
- const doc = iframe?.contentDocument;
20
- if (!doc) return 0;
21
- let max = 0;
22
- for (const el of doc.body.querySelectorAll("*")) {
23
- const z = parseInt(getComputedStyle(el).zIndex, 10);
24
- if (Number.isFinite(z) && z > max) max = z;
25
- }
26
- return max;
27
- } catch {
28
- return 0;
29
- }
18
+ async function previewMaxZIndex(iframe: HTMLIFrameElement | null): Promise<number> {
19
+ const zIndex = iframe ? (await previewRequest(iframe, "max-z-index", {}))?.zIndex : undefined;
20
+ return Number.isSafeInteger(zIndex) && (zIndex as number) >= 0 ? (zIndex as number) : 0;
30
21
  }
31
22
 
32
23
  interface AddBlockOptions {
@@ -214,6 +205,7 @@ export async function addBlockToProject(
214
205
  timelineElements: relevantElements,
215
206
  currentTime: opts.currentTime ?? 0,
216
207
  });
208
+ const zIndex = (await previewMaxZIndex(opts.previewIframe ?? null)) + 1;
217
209
  let hostId = "";
218
210
  const insertHost = (originalContent: string) => {
219
211
  const { width, height } = resolveTimelineAssetCompositionSize(originalContent);
@@ -228,7 +220,7 @@ export async function addBlockToProject(
228
220
  height,
229
221
  left: visualPosition ? Math.round(visualPosition.left) : 0,
230
222
  top: visualPosition ? Math.round(visualPosition.top) : 0,
231
- zIndex: getMaxZIndexFromIframe(opts.previewIframe ?? null) + 1,
223
+ zIndex,
232
224
  });
233
225
  return extendRootDurationInSource(
234
226
  insertTimelineAssetIntoSource(originalContent, subComposition),
@@ -29,7 +29,12 @@ describe("dom edit save queue", () => {
29
29
 
30
30
  expect(onOpen).toHaveBeenCalledWith({
31
31
  consecutiveFailures: 2,
32
- errorMessage: "Still down",
32
+ errorCodes: {
33
+ error_class: "StudioSaveHttpError",
34
+ error_key: "http",
35
+ server_why: "other",
36
+ block_reason: undefined,
37
+ },
33
38
  statusCode: 503,
34
39
  });
35
40
 
@@ -146,7 +151,12 @@ describe("dom edit save queue", () => {
146
151
 
147
152
  expect(onOpen).toHaveBeenCalledWith({
148
153
  consecutiveFailures: 1,
149
- errorMessage: "File changed elsewhere",
154
+ errorCodes: {
155
+ error_class: "StudioSaveHttpError",
156
+ error_key: "http",
157
+ server_why: "other",
158
+ block_reason: undefined,
159
+ },
150
160
  statusCode: 409,
151
161
  });
152
162
  await expect(queue.enqueue(async () => {})).rejects.toThrow("Auto-save is paused");
@@ -1,13 +1,13 @@
1
1
  import {
2
- getStudioSaveErrorMessage,
3
2
  getStudioSaveStatusCode,
3
+ studioSaveErrorCodes,
4
4
  StudioFileConflictError,
5
5
  type StudioSaveDrainResult,
6
6
  } from "./studioSaveDiagnostics";
7
7
 
8
- interface DomEditSaveQueueOpenEvent {
8
+ export interface DomEditSaveQueueOpenEvent {
9
9
  consecutiveFailures: number;
10
- errorMessage: string;
10
+ errorCodes: ReturnType<typeof studioSaveErrorCodes>;
11
11
  statusCode: number | null;
12
12
  }
13
13
 
@@ -58,7 +58,7 @@ export function createDomEditSaveQueue(options: DomEditSaveQueueOptions = {}): D
58
58
  breakerOpen = true;
59
59
  options.onOpen?.({
60
60
  consecutiveFailures,
61
- errorMessage: getStudioSaveErrorMessage(error),
61
+ errorCodes: studioSaveErrorCodes(error),
62
62
  statusCode: getStudioSaveStatusCode(error) ?? null,
63
63
  });
64
64
  };