-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathsdkCutover.ts
More file actions
465 lines (443 loc) · 17.2 KB
/
Copy pathsdkCutover.ts
File metadata and controls
465 lines (443 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import type { MutableRefObject } from "react";
import type { Composition, GsapTweenSpec } from "@hyperframes/sdk";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { EditHistoryKind } from "./editHistory";
import type { PatchOperation } from "./sourcePatcher";
import { STUDIO_SDK_CUTOVER_ENABLED } from "../components/editor/manualEditingAvailability";
import { trackStudioEvent } from "./studioTelemetry";
import { markSelfWrite } from "../hooks/sdkSelfWriteRegistry";
import { patchOpsToSdkEditOps } from "./sdkOpMapping";
import { recordResolverParity, recordAnimationResolverParity } from "./sdkResolverShadow";
const CUTOVER_OP_TYPES = new Set<PatchOperation["type"]>([
"inline-style",
"text-content",
"attribute",
"html-attribute",
]);
// Mirrors the SDK's RESERVED_ATTRS (mutate.ts): a bare `attribute` op is
// force-prefixed `data-`, so e.g. property "end" → "data-end", which the SDK
// rejects with a throw. Detect that up front and decline the whole batch so it
// takes the server path cleanly, instead of throwing inside the dispatch and
// silently falling back per op.
// ponytail: small mirror of the SDK set; if the SDK adds a reserved attr, a new
// op for it just reverts to the (working) throw→fallback path until synced.
const RESERVED_CUTOVER_ATTRS = new Set<string>([
"data-hf-id",
"data-composition-id",
"data-width",
"data-height",
"data-start",
"data-end",
"data-track-index",
"data-hold-start",
"data-hold-end",
"data-hold-fill",
]);
function sdkAttrName(op: PatchOperation): string | null {
if (op.type === "attribute") {
return op.property.startsWith("data-") ? op.property : `data-${op.property}`;
}
if (op.type === "html-attribute") return op.property;
return null;
}
function mapsToReservedAttr(op: PatchOperation): boolean {
const name = sdkAttrName(op);
// Lowercase to match the SDK's validateSetAttribute (it lowercases before the
// reserved check), so "DATA-START" is declined up front too; covers both
// `attribute` (prefixed) and `html-attribute` (raw) ops.
return name !== null && RESERVED_CUTOVER_ATTRS.has(name.toLowerCase());
}
export function shouldUseSdkCutover(
flagEnabled: boolean,
hasSession: boolean,
hfId: string | null | undefined,
ops: PatchOperation[],
): boolean {
return (
flagEnabled &&
hasSession &&
!!hfId &&
ops.length > 0 &&
ops.every((o) => CUTOVER_OP_TYPES.has(o.type)) &&
!ops.some(mapsToReservedAttr)
);
}
export interface CutoverDeps {
editHistory: {
recordEdit: (entry: {
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
files: Record<string, { before: string; after: string }>;
}) => Promise<void>;
};
writeProjectFile: (path: string, content: string) => Promise<void>;
reloadPreview: () => void;
domEditSaveTimestampRef: MutableRefObject<number>;
/**
* Optional post-write refresh. When provided, it REPLACES the default
* reloadPreview() — the GSAP path passes one that soft-reloads (preserving
* the playhead) and invalidates the keyframe/gsap panel cache. Receives the
* serialized document just written.
*/
refresh?: (after: string) => void;
/**
* Path of the composition the SDK session was opened for. The session models
* ONLY this file (serialize() emits the whole active composition), so any edit
* whose targetPath differs (a sub-composition file) must take the server path
* — otherwise we'd write the full active-comp serialization into that file.
*/
compositionPath?: string | null;
/**
* Optional per-key task serializer (the same `gsap-file:${file}` serializer the
* legacy `commitMutation` uses). When provided, every GSAP-op persist routes its
* read-serialize → dispatch → serialize → write through it so two concurrent
* same-file flushes can't interleave their read-modify-write and lose an edit.
* Absent (e.g. in unit tests) → ops run unserialized as before.
*/
serialize?: <T>(key: string, task: () => Promise<T>) => Promise<T>;
/**
* Optional reader for the on-disk content of targetPath. Timing/GSAP persists
* use it to capture the EXACT prior bytes as the undo-history `before`, so undo
* restores the file verbatim instead of a normalized SDK re-emit (which would
* reformat the whole file). The style/delete paths already thread originalContent
* in explicitly; this gives timing/GSAP parity without touching every call site.
* Absent → falls back to the SDK's pre-edit serialize() (the prior behavior).
*/
readProjectFile?: (path: string) => Promise<string>;
}
/**
* Capture the undo-history `before` baseline for timing/GSAP persists: the exact
* on-disk bytes when a reader is available (so undo restores them verbatim),
* falling back to the SDK's pre-edit serialization when it isn't. Never throws —
* a failed read degrades to the serialized fallback rather than aborting the edit.
*/
async function captureOnDiskBefore(
deps: CutoverDeps,
targetPath: string,
serializedFallback: string,
): Promise<string> {
if (!deps.readProjectFile) return serializedFallback;
try {
return await deps.readProjectFile(targetPath);
} catch {
return serializedFallback;
}
}
/** True when targetPath isn't the composition the SDK session models. */
function wrongCompositionFile(deps: CutoverDeps, targetPath: string): boolean {
return deps.compositionPath != null && targetPath !== deps.compositionPath;
}
interface CutoverOptions {
label?: string;
coalesceKey?: string;
/** Skip the preview reload (mirrors the server path's skipRefresh). */
skipRefresh?: boolean;
}
// ponytail: internal; export only if a third caller appears.
// `after` is serialized once by the caller (which also did the no-op check
// against its pre-dispatch snapshot), so this never re-serializes.
async function persistSdkSerialize(
after: string,
targetPath: string,
originalContent: string,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<void> {
deps.domEditSaveTimestampRef.current = Date.now();
// Tag this write with the exact content (by hash) so the file-change
// reload-suppression can recognize its own echo by IDENTITY, not just a 2 s
// clock — an undo write (different bytes, not registered here) then always
// reloads instead of being swallowed by the time window.
markSelfWrite(targetPath, after);
await deps.writeProjectFile(targetPath, after);
await deps.editHistory.recordEdit({
label: options?.label ?? "Edit layer",
kind: "manual",
...(options?.coalesceKey ? { coalesceKey: options.coalesceKey } : {}),
files: { [targetPath]: { before: originalContent, after } },
});
if (deps.refresh) deps.refresh(after);
else if (!options?.skipRefresh) deps.reloadPreview();
}
export async function sdkCutoverPersist(
selection: DomEditSelection,
ops: PatchOperation[],
originalContent: string,
targetPath: string,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
if (!shouldUseSdkCutover(STUDIO_SDK_CUTOVER_ENABLED, !!sdkSession, selection.hfId, ops))
return false;
if (!sdkSession) return false;
const hfId = selection.hfId;
if (!hfId) return false;
if (!sdkSession.getElement(hfId)) return false;
if (wrongCompositionFile(deps, targetPath)) return false;
try {
const before = sdkSession.serialize();
sdkSession.batch(() => {
for (const editOp of patchOpsToSdkEditOps(hfId, ops)) {
sdkSession.dispatch(editOp);
}
});
const after = sdkSession.serialize();
if (after === before) return false;
await persistSdkSerialize(after, targetPath, originalContent, deps, options);
trackStudioEvent("sdk_cutover_success", { hfId, opCount: ops.length });
return true;
} catch (err) {
trackStudioEvent("sdk_cutover_fallback", {
hfId: selection.hfId ?? null,
error: String(err),
});
return false;
}
}
export async function sdkTimingPersist(
hfId: string,
targetPath: string,
timingUpdate: { start?: number; duration?: number; trackIndex?: number },
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
// Resolver tripwire — runs BEFORE the cutover gate (decoupled): records when
// the SDK can't resolve a target the server timing path is addressing.
recordResolverParity(sdkSession, hfId, "setTiming");
// Dark-launch gate: without this, timing cutover runs whenever an SDK session
// exists (it always does, for shadow/selection) — flipping the flag OFF would
// NOT disable it. Gate here so flag-off routes back to the legacy server path.
if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
if (!sdkSession || !sdkSession.getElement(hfId)) return false;
if (wrongCompositionFile(deps, targetPath)) return false;
try {
const serializedBefore = sdkSession.serialize();
sdkSession.batch(() => sdkSession.setTiming(hfId, timingUpdate));
const after = sdkSession.serialize();
if (after === serializedBefore) return false;
// Undo baseline = exact on-disk bytes (matching the style/delete paths), so
// undoing a timing edit restores the file verbatim instead of a normalized
// full-DOM re-emit. Falls back to serializedBefore when no reader is wired.
const undoBefore = await captureOnDiskBefore(deps, targetPath, serializedBefore);
await persistSdkSerialize(after, targetPath, undoBefore, deps, options);
trackStudioEvent("sdk_cutover_success", { hfId, opCount: 1 });
return true;
} catch (err) {
trackStudioEvent("sdk_cutover_fallback", { hfId, error: String(err) });
return false;
}
}
type SdkGsapTweenOp =
| { kind: "add"; target: string; spec: GsapTweenSpec }
| { kind: "set"; animationId: string; properties: Partial<GsapTweenSpec> }
| { kind: "remove"; animationId: string };
export function sdkGsapTweenPersist(
targetPath: string,
op: SdkGsapTweenOp,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
// Resolver tripwire — runs BEFORE this function's own cutover gate (decoupled).
// add targets an element (element-resolution parity); set/remove target an
// animationId (animation-resolution parity). Done here, not via
// dispatchGsapOpAndPersist's resolverTarget, because the gate below returns
// before that call when cutover is off.
if (op.kind === "add") recordResolverParity(sdkSession, op.target, "addGsapTween");
else
recordAnimationResolverParity(
sdkSession,
op.animationId,
op.kind === "set" ? "setGsapTween" : "removeGsapTween",
);
// Leading dark-launch gate so flag-off does no SDK touch (getElement) at all —
// matches the other three chokepoints' discipline.
if (!STUDIO_SDK_CUTOVER_ENABLED) return Promise.resolve(false);
if (op.kind === "add" && sdkSession && !sdkSession.getElement(op.target))
return Promise.resolve(false);
// dispatchGsapOpAndPersist returns false on before===after — that catches stale
// animationIds and unsupported shapes (e.g. from-prop on a plain tween), falling
// back to the server path. This subsumes explicit existence guards for set/remove.
return dispatchGsapOpAndPersist(targetPath, sdkSession, deps, options, (s) => {
s.batch(() => {
if (op.kind === "add") {
s.addGsapTween(op.target, op.spec);
} else if (op.kind === "set") {
s.setGsapTween(op.animationId, op.properties);
} else {
s.removeGsapTween(op.animationId);
}
});
});
}
async function dispatchGsapOpAndPersist(
targetPath: string,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options: CutoverOptions | undefined,
dispatch: (s: Composition) => void,
resolverTarget?: { animationId: string; opLabel: string },
): Promise<boolean> {
// Resolver tripwire — runs BEFORE the cutover gate (decoupled): records when
// the SDK can't resolve the animationId the server GSAP path is addressing.
if (resolverTarget) {
recordAnimationResolverParity(sdkSession, resolverTarget.animationId, resolverTarget.opLabel);
}
// Dark-launch gate (shared chokepoint for every GSAP-op cutover persist):
// flag OFF → return false → caller falls back to the legacy server path.
if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
if (!sdkSession) return false;
if (wrongCompositionFile(deps, targetPath)) return false;
const session = sdkSession;
// Route the whole read-serialize → dispatch → serialize → write through the
// per-file serializer (when provided) so overlapping same-file flushes can't
// interleave their read-modify-write and drop an edit, matching the legacy
// commitMutation path's `gsap-file:${file}` serialization.
const run = async (): Promise<boolean> => {
try {
const serializedBefore = session.serialize();
dispatch(session);
const after = session.serialize();
if (after === serializedBefore) return false;
// Undo baseline = exact on-disk bytes (matching the style/delete paths), so
// undoing a GSAP edit restores the file verbatim instead of a normalized
// full-DOM re-emit. Falls back to serializedBefore when no reader is wired.
const undoBefore = await captureOnDiskBefore(deps, targetPath, serializedBefore);
await persistSdkSerialize(after, targetPath, undoBefore, deps, options);
trackStudioEvent("sdk_cutover_success", { opCount: 1 });
return true;
} catch (err) {
trackStudioEvent("sdk_cutover_fallback", { error: String(err) });
return false;
}
};
return deps.serialize ? deps.serialize(`gsap-file:${targetPath}`, run) : run();
}
export function sdkGsapKeyframePersist(
targetPath: string,
animationId: string,
position: number,
value: Record<string, unknown>,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
deps,
options,
(s) => s.batch(() => s.dispatch({ type: "addGsapKeyframe", animationId, position, value })),
{ animationId, opLabel: "addGsapKeyframe" },
);
}
export function sdkGsapRemoveKeyframePersist(
targetPath: string,
animationId: string,
percentage: number,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
deps,
options,
(s) => s.dispatch({ type: "removeGsapKeyframe", animationId, percentage }),
{ animationId, opLabel: "removeGsapKeyframe" },
);
}
export function sdkGsapRemovePropertyPersist(
targetPath: string,
animationId: string,
property: string,
from: boolean,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
deps,
options,
(s) => s.dispatch({ type: "removeGsapProperty", animationId, property, from }),
{ animationId, opLabel: "removeGsapProperty" },
);
}
export function sdkGsapDeleteAllForSelectorPersist(
targetPath: string,
selector: string,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
return dispatchGsapOpAndPersist(targetPath, sdkSession, deps, options, (s) =>
s.dispatch({ type: "deleteAllForSelector", selector }),
);
}
export function sdkGsapRemoveAllKeyframesPersist(
targetPath: string,
animationId: string,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
deps,
options,
(s) => s.dispatch({ type: "removeAllKeyframes", animationId }),
{ animationId, opLabel: "removeAllKeyframes" },
);
}
export function sdkGsapConvertToKeyframesPersist(
targetPath: string,
animationId: string,
resolvedFromValues: Record<string, number | string> | undefined,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
options?: CutoverOptions,
): Promise<boolean> {
return dispatchGsapOpAndPersist(
targetPath,
sdkSession,
deps,
options,
(s) => s.dispatch({ type: "convertToKeyframes", animationId, resolvedFromValues }),
{ animationId, opLabel: "convertToKeyframes" },
);
}
export async function sdkDeletePersist(
hfId: string,
originalContent: string,
targetPath: string,
sdkSession: Composition | null | undefined,
deps: CutoverDeps,
): Promise<boolean> {
// Resolver tripwire — runs BEFORE the cutover gate (decoupled).
recordResolverParity(sdkSession, hfId, "removeElement");
// Dark-launch gate: flag OFF → legacy server delete path.
if (!STUDIO_SDK_CUTOVER_ENABLED) return false;
if (!sdkSession || !sdkSession.getElement(hfId)) return false;
if (wrongCompositionFile(deps, targetPath)) return false;
try {
const before = sdkSession.serialize();
sdkSession.batch(() => sdkSession.removeElement(hfId));
const after = sdkSession.serialize();
if (after === before) return false;
await persistSdkSerialize(after, targetPath, originalContent, deps, {
label: "Delete element",
});
trackStudioEvent("sdk_cutover_success", { hfId, opCount: 1 });
return true;
} catch (err) {
trackStudioEvent("sdk_cutover_fallback", { hfId, error: String(err) });
return false;
}
}