mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-03 04:38:33 +00:00
fix(studio): reject unsafe keyframe values (#1389)
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
|
||||
export const PROPERTY_DEFAULTS: Record<string, number> = {
|
||||
@@ -31,3 +32,97 @@ export function ensureElementAddressable(selection: DomEditSelection): {
|
||||
el.setAttribute("id", id);
|
||||
return { selector: `#${id}`, autoId: id };
|
||||
}
|
||||
|
||||
export class GsapMutationHttpError extends Error {
|
||||
constructor(
|
||||
readonly statusCode: number,
|
||||
readonly responseBody: unknown,
|
||||
) {
|
||||
super(formatGsapMutationHttpErrorMessage(statusCode, responseBody));
|
||||
this.name = "GsapMutationHttpError";
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
export async function readJsonResponseBody(res: Response): Promise<unknown> {
|
||||
const contentType = res.headers.get("content-type") ?? "";
|
||||
if (!contentType.includes("application/json")) {
|
||||
return await res.text().catch(() => null);
|
||||
}
|
||||
return await res.json().catch(() => null);
|
||||
}
|
||||
|
||||
function formatGsapMutationHttpErrorMessage(statusCode: number, body: unknown): string {
|
||||
if (isRecord(body) && typeof body.error === "string") {
|
||||
return body.error;
|
||||
}
|
||||
return `GSAP mutation failed with status ${statusCode}`;
|
||||
}
|
||||
|
||||
export function formatGsapMutationRejectionToast(error: GsapMutationHttpError): string {
|
||||
const body = error.responseBody;
|
||||
if (isRecord(body)) {
|
||||
const fields = Array.isArray(body.fields)
|
||||
? body.fields.filter((field): field is string => typeof field === "string")
|
||||
: [];
|
||||
const suffix = fields.length > 0 ? ` (${fields.join(", ")})` : "";
|
||||
return `Couldn't save animation: ${formatGsapMutationHttpErrorMessage(
|
||||
error.statusCode,
|
||||
body,
|
||||
)}${suffix}`;
|
||||
}
|
||||
return `Couldn't save animation: ${error.message}`;
|
||||
}
|
||||
|
||||
interface AssignAutoIdParams {
|
||||
projectId: string;
|
||||
targetPath: string;
|
||||
selection: DomEditSelection;
|
||||
autoId: string;
|
||||
showToast?: (message: string, tone?: "error" | "info") => void;
|
||||
}
|
||||
|
||||
export async function assignGsapTargetAutoIdIfNeeded({
|
||||
projectId,
|
||||
targetPath,
|
||||
selection,
|
||||
autoId,
|
||||
showToast,
|
||||
}: AssignAutoIdParams): Promise<boolean> {
|
||||
const patchBody = {
|
||||
target: {
|
||||
id: selection.id,
|
||||
hfId: selection.hfId,
|
||||
selector: selection.selector,
|
||||
selectorIndex: selection.selectorIndex,
|
||||
},
|
||||
operations: [{ type: "html-attribute", property: "id", value: autoId }],
|
||||
};
|
||||
const unsafePatchFields = findUnsafeDomPatchValues(patchBody);
|
||||
if (unsafePatchFields.length > 0) {
|
||||
showToast?.("Couldn't assign element id because the patch contains invalid values", "error");
|
||||
return false;
|
||||
}
|
||||
const res = await fetch(
|
||||
`/api/projects/${encodeURIComponent(projectId)}/file-mutations/patch-element/${encodeURIComponent(targetPath)}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(patchBody),
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
showToast?.(
|
||||
formatGsapMutationRejectionToast(
|
||||
new GsapMutationHttpError(res.status, await readJsonResponseBody(res)),
|
||||
),
|
||||
"error",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const data = (await res.json()) as { changed?: boolean };
|
||||
return data.changed === true;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";
|
||||
import { usePlayerStore } from "../player";
|
||||
import { STUDIO_GSAP_DRAG_INTERCEPT_ENABLED } from "../components/editor/manualEditingAvailability";
|
||||
import { FONT_EXT } from "../utils/mediaTypes";
|
||||
@@ -38,6 +39,27 @@ import { useDomEditTextCommits } from "./useDomEditTextCommits";
|
||||
// ── Helpers ──
|
||||
type TimelineLike = { getChildren?: (nested: boolean) => Array<{ targets?: () => Element[] }> };
|
||||
|
||||
function formatUnsafeFieldList(fields: Array<{ path: string }>): string {
|
||||
return fields.map((field) => field.path).join(", ");
|
||||
}
|
||||
|
||||
async function readErrorResponseBody(
|
||||
response: Response,
|
||||
): Promise<{ error?: string; fields?: string[] } | null> {
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
if (!contentType.includes("application/json")) return null;
|
||||
return (await response.json().catch(() => null)) as { error?: string; fields?: string[] } | null;
|
||||
}
|
||||
|
||||
function formatPatchRejectionMessage(body: { error?: string; fields?: string[] } | null): string {
|
||||
if (!body?.error) return "Couldn't save edit";
|
||||
const fields = Array.isArray(body.fields)
|
||||
? body.fields.filter((field): field is string => typeof field === "string")
|
||||
: [];
|
||||
const suffix = fields.length > 0 ? ` (${fields.join(", ")})` : "";
|
||||
return `Couldn't save edit: ${body.error}${suffix}`;
|
||||
}
|
||||
|
||||
export const GSAP_CSS_FALLBACK_BLOCKED_MESSAGE =
|
||||
"This element is GSAP-animated — dragging via CSS would corrupt keyframes";
|
||||
|
||||
@@ -192,6 +214,13 @@ export function useDomEditCommits({
|
||||
if (options?.shouldSave && !options.shouldSave()) return;
|
||||
|
||||
const patchTarget = buildDomEditPatchTarget(selection);
|
||||
const patchBody = { target: patchTarget, operations };
|
||||
const unsafeFields = findUnsafeDomPatchValues(patchBody);
|
||||
if (unsafeFields.length > 0) {
|
||||
const fields = formatUnsafeFieldList(unsafeFields);
|
||||
showToast("Couldn't save edit because it contains invalid layout values", "error");
|
||||
throw new Error(`DOM patch contains unsafe values: ${fields}`);
|
||||
}
|
||||
|
||||
// Mark the save timestamp before the file write so the SSE file-change
|
||||
// handler suppresses the reload even if the event arrives before the
|
||||
@@ -203,10 +232,11 @@ export function useDomEditCommits({
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ target: patchTarget, operations }),
|
||||
body: JSON.stringify(patchBody),
|
||||
},
|
||||
);
|
||||
if (!patchResponse.ok) {
|
||||
showToast(formatPatchRejectionMessage(await readErrorResponseBody(patchResponse)), "error");
|
||||
throw await createStudioSaveHttpError(patchResponse, `Failed to patch ${targetPath}`);
|
||||
}
|
||||
|
||||
@@ -266,6 +296,7 @@ export function useDomEditCommits({
|
||||
projectIdRef,
|
||||
domEditSaveTimestampRef,
|
||||
reloadPreview,
|
||||
showToast,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";
|
||||
import { findUnsafeMutationValues } from "@hyperframes/core/studio-api/finite-mutation";
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
import type { EditHistoryKind } from "../utils/editHistory";
|
||||
import { applySoftReload } from "../utils/gsapSoftReload";
|
||||
@@ -11,12 +12,18 @@ import {
|
||||
readKeyframeSnapshot,
|
||||
writeKeyframeCache,
|
||||
} from "./gsapKeyframeCacheHelpers";
|
||||
import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics";
|
||||
import {
|
||||
useGsapSaveFailureTelemetry,
|
||||
useSafeGsapCommitMutation,
|
||||
} from "./useSafeGsapCommitMutation";
|
||||
import { ensureElementAddressable, PROPERTY_DEFAULTS } from "./gsapScriptCommitHelpers";
|
||||
import {
|
||||
GsapMutationHttpError,
|
||||
assignGsapTargetAutoIdIfNeeded,
|
||||
ensureElementAddressable,
|
||||
formatGsapMutationRejectionToast,
|
||||
PROPERTY_DEFAULTS,
|
||||
readJsonResponseBody,
|
||||
} from "./gsapScriptCommitHelpers";
|
||||
|
||||
interface MutationResult {
|
||||
ok: boolean;
|
||||
@@ -41,7 +48,7 @@ async function mutateGsapScript(
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
throw await createStudioSaveHttpError(res, `Failed to update GSAP in ${sourceFile}`);
|
||||
throw new GsapMutationHttpError(res.status, await readJsonResponseBody(res));
|
||||
}
|
||||
const result = (await res.json()) as MutationResult;
|
||||
if (!result.ok) {
|
||||
@@ -124,8 +131,28 @@ export function useGsapScriptCommits({
|
||||
) => {
|
||||
const pid = projectIdRef.current;
|
||||
if (!pid) return;
|
||||
const unsafeFields = findUnsafeMutationValues(mutation);
|
||||
if (unsafeFields.length > 0) {
|
||||
showToast?.(
|
||||
"Couldn't read element layout — try again at a different playhead time",
|
||||
"error",
|
||||
);
|
||||
if (options.skipReload) return;
|
||||
throw new Error(
|
||||
`Mutation contains unsafe values: ${unsafeFields.map((field) => field.path).join(", ")}`,
|
||||
);
|
||||
}
|
||||
const targetPath = selection.sourceFile || activeCompPath || "index.html";
|
||||
const result = await mutateGsapScript(pid, targetPath, mutation);
|
||||
let result: MutationResult;
|
||||
try {
|
||||
result = await mutateGsapScript(pid, targetPath, mutation);
|
||||
} catch (error) {
|
||||
if (error instanceof GsapMutationHttpError) {
|
||||
showToast?.(formatGsapMutationRejectionToast(error), "error");
|
||||
}
|
||||
if (options.skipReload) return;
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (result.changed === false) {
|
||||
if (options.skipReload) return;
|
||||
@@ -184,6 +211,7 @@ export function useGsapScriptCommits({
|
||||
reloadPreview,
|
||||
onCacheInvalidate,
|
||||
onFileContentChanged,
|
||||
showToast,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -280,32 +308,14 @@ export function useGsapScriptCommits({
|
||||
const pid = projectIdRef.current;
|
||||
const targetPath = selection.sourceFile || activeCompPath || "index.html";
|
||||
if (!pid) return;
|
||||
const res = await fetch(
|
||||
`/api/projects/${encodeURIComponent(pid)}/file-mutations/patch-element/${encodeURIComponent(targetPath)}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
target: {
|
||||
id: selection.id,
|
||||
hfId: selection.hfId,
|
||||
selector: selection.selector,
|
||||
selectorIndex: selection.selectorIndex,
|
||||
},
|
||||
operations: [{ type: "html-attribute", property: "id", value: autoId }],
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
throw await createStudioSaveHttpError(
|
||||
res,
|
||||
`Failed to assign element id in ${targetPath}`,
|
||||
);
|
||||
}
|
||||
const data = (await res.json()) as { changed?: boolean };
|
||||
if (!data.changed) {
|
||||
throw new Error(`Failed to assign element id in ${targetPath}`);
|
||||
}
|
||||
const assigned = await assignGsapTargetAutoIdIfNeeded({
|
||||
projectId: pid,
|
||||
targetPath,
|
||||
selection,
|
||||
autoId,
|
||||
showToast,
|
||||
});
|
||||
if (!assigned) return;
|
||||
}
|
||||
|
||||
const elStart = Number.parseFloat(selection.dataAttributes?.start ?? "0") || 0;
|
||||
@@ -334,7 +344,7 @@ export function useGsapScriptCommits({
|
||||
{ label: `Add GSAP ${method} animation` },
|
||||
);
|
||||
},
|
||||
[commitMutation, projectIdRef, activeCompPath],
|
||||
[commitMutation, projectIdRef, activeCompPath, showToast],
|
||||
);
|
||||
const addGsapProperty = useCallback(
|
||||
// fallow-ignore-next-line complexity
|
||||
|
||||
Reference in New Issue
Block a user