@hyperframes/studio-server 0.8.119 → 0.8.121

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.
@@ -207,7 +207,7 @@ function stampNewChildIds(parent) {
207
207
  el.setAttribute("data-hf-id", mintHfId(el, assigned));
208
208
  }
209
209
  }
210
- function patchElementInHtml(source, target, operations) {
210
+ function patchElementInHtml(source, target, operations, takenIds) {
211
211
  const { document, wrappedFragment } = parseSourceDocument(source);
212
212
  const el = findTargetElement(document, target);
213
213
  if (!el || !isHTMLElement(el)) return { html: source, matched: false };
@@ -247,6 +247,10 @@ function patchElementInHtml(source, target, operations) {
247
247
  opTarget.removeAttribute(op.property);
248
248
  }
249
249
  break;
250
+ case "ensure-id":
251
+ if (opTarget.getAttribute("id") || !op.value) break;
252
+ opTarget.setAttribute("id", nextUniqueId(document, op.value, takenIds));
253
+ break;
250
254
  case "text-content":
251
255
  if (op.value != null) {
252
256
  const inner = opTarget.children.length === 1 ? opTarget.firstElementChild : null;
@@ -268,8 +272,15 @@ function patchElementInHtml(source, target, operations) {
268
272
  }
269
273
  }
270
274
  const html = wrappedFragment ? document.body.innerHTML || "" : document.toString();
271
- if (html === originalHtml) return { html: source, matched: true };
272
- return { html: ensureHfIds(html), matched: true };
275
+ const elementId = htmlEl.getAttribute("id");
276
+ if (html === originalHtml) return { html: source, matched: true, elementId };
277
+ return { html: ensureHfIds(html), matched: true, elementId };
278
+ }
279
+ function nextUniqueId(document, base, takenIds) {
280
+ let id = base;
281
+ let suffix = 2;
282
+ while (document.getElementById(id) || takenIds?.has(id)) id = `${base}-${suffix++}`;
283
+ return id;
273
284
  }
274
285
  function probeElementsInSource(source, targets) {
275
286
  const { document } = parseSourceDocument(source);
@@ -306,13 +317,7 @@ function splitElementInHtml(source, target, splitTime, newId, fallbackTiming) {
306
317
  if (duration <= 0 || splitTime <= start || splitTime >= start + duration) {
307
318
  return { html: source, matched: false, newId: null };
308
319
  }
309
- if (document.getElementById(newId)) {
310
- let suffix = 2;
311
- const base = newId;
312
- while (document.getElementById(newId)) {
313
- newId = `${base}-${suffix++}`;
314
- }
315
- }
320
+ newId = nextUniqueId(document, newId);
316
321
  const firstDuration = splitTime - start;
317
322
  const secondDuration = duration - firstDuration;
318
323
  const clone = el.cloneNode(true);
@@ -370,13 +375,7 @@ function setInlineLeftTop(el, left, top) {
370
375
  }
371
376
  function uniqueGroupDomId(document, groupId) {
372
377
  const base = groupId.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "group";
373
- let id = base;
374
- let n = 2;
375
- while (document.getElementById(id)) {
376
- id = `${base}-${n}`;
377
- n += 1;
378
- }
379
- return id;
378
+ return nextUniqueId(document, base);
380
379
  }
381
380
  function wrapElementsInHtml(source, targets, groupId, bbox, rebases) {
382
381
  const { document, wrappedFragment } = parseSourceDocument(source);
@@ -512,6 +511,7 @@ export {
512
511
  isHTMLElement,
513
512
  dedupeClonedCompositionId,
514
513
  patchElementInHtml,
514
+ nextUniqueId,
515
515
  probeElementsInSource,
516
516
  probeElementInSource,
517
517
  splitElementInHtml,
@@ -519,4 +519,4 @@ export {
519
519
  unwrapElementsFromHtml,
520
520
  relinkSplitHalvesInHtml
521
521
  };
522
- //# sourceMappingURL=chunk-G4YB7Q2Q.js.map
522
+ //# sourceMappingURL=chunk-CLWFZQUU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/helpers/sourceMutation.ts","../src/helpers/sourceStyleMutation.ts"],"sourcesContent":["import { parseHTML } from \"linkedom\";\nimport { removeElementWithGsapCascade } from \"@hyperframes/parsers\";\nimport { readMediaOffsetSeconds, readPlaybackRate } from \"@hyperframes/parsers/media-duration\";\nimport postcss from \"postcss\";\nimport selectorParser from \"postcss-selector-parser\";\nimport { isAllowedHtmlAttribute, isSafeAttributeValue } from \"@hyperframes/core/html-attr-safety\";\nimport { sanitizeRichTextChildren } from \"@hyperframes/core/rich-text-sanitize\";\nimport {\n EXCLUDED_TAGS,\n ensureHfIds,\n mintHfId,\n walkCompositionDescendants,\n} from \"@hyperframes/parsers/hf-ids\";\nimport { readClipTiming, writeClipTiming } from \"@hyperframes/core/composition-contract\";\nimport { relinkSplitHalves } from \"@hyperframes/core/media-link\";\nimport { parseStyleDecls, patchStyleAttrString } from \"./sourceStyleMutation.js\";\n\nexport interface SourceMutationTarget {\n id?: string | null;\n hfId?: string;\n selector?: string;\n selectorIndex?: number;\n}\n\nexport function parseSourceDocument(raw: string): {\n document: Document;\n wrappedFragment: boolean;\n} {\n const source = ensureHfIds(raw);\n const hasDocumentShell = /<!doctype|<html[\\s>]/i.test(source);\n if (hasDocumentShell) {\n return { document: parseHTML(source).document, wrappedFragment: false };\n }\n return {\n document: parseHTML(`<!DOCTYPE html><html><head></head><body>${source}</body></html>`).document,\n wrappedFragment: true,\n };\n}\n\nfunction duplicateCssRulesForId(document: Document, originalId: string, newId: string): void {\n const idToken = `#${originalId}`;\n const transform = selectorParser((selectors) => {\n selectors.walkIds((node) => {\n if (node.value === originalId) node.value = newId;\n });\n });\n for (const styleEl of document.querySelectorAll(\"style\")) {\n const css = styleEl.textContent ?? \"\";\n let root: postcss.Root;\n try {\n root = postcss.parse(css);\n } catch {\n continue;\n }\n const clones: postcss.Rule[] = [];\n root.walkRules((rule) => {\n if (!rule.selector.includes(idToken)) return;\n const newSelector = transform.processSync(rule.selector);\n if (newSelector === rule.selector) return;\n const clone = rule.clone({ selector: newSelector });\n clones.push(clone);\n });\n if (clones.length > 0) {\n for (const c of clones) root.append(c);\n styleEl.textContent = root.toString();\n }\n }\n}\n\nfunction querySelectorAllWithTemplates(root: Document | Element, selector: string): Element[] {\n const matches = Array.from(root.querySelectorAll(selector));\n if (matches.length > 0) return matches;\n // querySelectorAll doesn't traverse <template> content in linkedom.\n // Search directly on each template element (NOT .content — removing from\n // .content's DocumentFragment doesn't update the serialized output).\n // Recurse so NESTED templates resolve too — ensureHfIds and the SDK's\n // querySelectorAllDeep descend nested composition templates, so ids exist at\n // any template depth; a one-level search here would silently no-op\n // server-side ops on those ids while the SDK resolves them.\n const templates = Array.from(root.querySelectorAll(\"template\"));\n for (const tmpl of templates) {\n const inner = querySelectorAllWithTemplates(tmpl, selector);\n if (inner.length > 0) return inner;\n }\n return [];\n}\n\n// Prevent CSS attribute-selector injection via a crafted hfId: escape\n// backslashes first, then double-quotes. Keeps a malformed/hostile value from\n// breaking out of the `[data-hf-id=\"…\"]` selector once callers beyond the\n// internal mint contract (R2+ user flows) pass values here.\nfunction escapeCssAttrValue(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\nfunction findByHfId(document: Document, hfId: string): Element | null {\n try {\n const matches = querySelectorAllWithTemplates(\n document,\n `[data-hf-id=\"${escapeCssAttrValue(hfId)}\"]`,\n );\n if (matches.length > 1) {\n // The mint contract guarantees uniqueness; a duplicate means upstream\n // id drift. Don't silently patch an arbitrary one — surface it.\n // eslint-disable-next-line no-console\n console.warn(\n `sourceMutation: data-hf-id \"${hfId}\" matched ${matches.length} elements; using the first. ids must be unique per document.`,\n );\n }\n return matches[0] ?? null;\n } catch {\n // Malformed selector despite escaping — let the caller fall back.\n return null;\n }\n}\n\nexport function findTargetElement(\n document: Document,\n target: SourceMutationTarget,\n): Element | null {\n if (target.hfId) {\n const el = findByHfId(document, target.hfId);\n if (el) return el;\n }\n\n if (target.id) {\n const byId = document.getElementById(target.id);\n if (byId) return byId;\n }\n\n if (!target.selector) return null;\n try {\n const matches = querySelectorAllWithTemplates(document, target.selector);\n return matches[target.selectorIndex ?? 0] ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Removes every target in one parse and one serialization. A target nested inside one already\n * removed no longer matches, which is a normal outcome rather than a failure.\n */\nexport function removeElementsFromHtml(\n source: string,\n targets: readonly SourceMutationTarget[],\n): string {\n const { document, wrappedFragment } = parseSourceDocument(source);\n let removed = false;\n for (const target of targets) {\n const element = findTargetElement(document, target);\n if (!element) continue;\n removeElementWithGsapCascade(document, element);\n removed = true;\n }\n if (!removed) return source;\n return wrappedFragment ? document.body.innerHTML || \"\" : document.toString();\n}\n\nexport function removeElementFromHtml(source: string, target: SourceMutationTarget): string {\n return removeElementsFromHtml(source, [target]);\n}\n\nexport function isHTMLElement(el: Node): el is HTMLElement {\n const HTMLEl = el.ownerDocument?.defaultView?.HTMLElement;\n return HTMLEl ? el instanceof HTMLEl : el.nodeType === 1 && \"style\" in el;\n}\n\nexport function dedupeClonedCompositionId(document: Document, clone: Element): void {\n const compositionId = clone.getAttribute(\"data-composition-id\");\n if (!compositionId) return;\n const usedCompositionIds = new Set(\n querySelectorAllWithTemplates(document, \"[data-composition-id]\").map((node) =>\n node.getAttribute(\"data-composition-id\"),\n ),\n );\n const base = `${compositionId}-split`;\n let nextCompositionId = base;\n let suffix = 2;\n while (usedCompositionIds.has(nextCompositionId)) nextCompositionId = `${base}-${suffix++}`;\n clone.setAttribute(\"data-composition-id\", nextCompositionId);\n}\n\nexport interface PatchOperation {\n /** `ensure-id` keeps the element's id, else writes `value` made unique in this file and `takenIds`. */\n type:\n | \"inline-style\"\n | \"attribute\"\n | \"html-attribute\"\n | \"text-content\"\n | \"rich-text\"\n | \"ensure-id\";\n property: string;\n value: string | null;\n childSelector?: string;\n childIndex?: number;\n}\n\ninterface ResolvedPatchOperation {\n op: PatchOperation;\n target: HTMLElement;\n}\n\nfunction resolveOperationTarget(parent: HTMLElement, op: PatchOperation): HTMLElement | null {\n if (op.childSelector === undefined) return parent;\n try {\n const child = parent.querySelectorAll(op.childSelector)[op.childIndex ?? 0] ?? null;\n return child && isHTMLElement(child) ? child : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Give the elements a rich-text patch just introduced their stable ids, here,\n * in the bytes about to be written and handed back.\n *\n * Otherwise the next preview request mints them and writes the file a second\n * time, after Studio has already recorded the edit in its history. The recorded\n * \"after\" stops matching disk, the content check refuses, and undo reports the\n * file as changed outside Studio — for every colour applied to a run of\n * characters and every text layer added. The clip split stamps its own clone\n * for exactly this reason.\n *\n * Minted one element at a time with the same function `ensureHfIds` uses, so\n * these ids are the ones the next pass would have assigned. Not `ensureHfIds`\n * itself: it takes a whole document, and handing it this element's markup would\n * put the markup back as one.\n */\nfunction stampNewChildIds(parent: Element): void {\n const assigned = new Set<string>();\n const root = parent.ownerDocument?.body ?? parent;\n walkCompositionDescendants(root, (el) => {\n const id = el.getAttribute(\"data-hf-id\");\n if (id) assigned.add(id);\n });\n for (const el of parent.querySelectorAll(\"*\")) {\n if (el.getAttribute(\"data-hf-id\")) continue;\n if (EXCLUDED_TAGS.has(el.tagName.toLowerCase())) continue;\n el.setAttribute(\"data-hf-id\", mintHfId(el, assigned));\n }\n}\n\n// fallow-ignore-next-line complexity\nexport function patchElementInHtml(\n source: string,\n target: SourceMutationTarget,\n operations: PatchOperation[],\n takenIds?: ReadonlySet<string>,\n): { html: string; matched: boolean; elementId?: string | null } {\n const { document, wrappedFragment } = parseSourceDocument(source);\n const el = findTargetElement(document, target);\n if (!el || !isHTMLElement(el)) return { html: source, matched: false };\n const htmlEl = el;\n const originalHtml = wrappedFragment ? document.body.innerHTML || \"\" : document.toString();\n\n const resolved: ResolvedPatchOperation[] = [];\n for (const op of operations) {\n const opTarget = resolveOperationTarget(htmlEl, op);\n if (!opTarget) return { html: source, matched: false };\n resolved.push({ op, target: opTarget });\n }\n\n for (const { op, target: opTarget } of resolved) {\n switch (op.type) {\n case \"inline-style\":\n // linkedom's CSSStyleDeclaration does not support CSS custom properties\n // (--foo) or newer individual transform properties (translate, rotate,\n // scale) via style.setProperty(). Manipulate the style attribute string\n // directly so all property names survive the round-trip.\n {\n const raw = opTarget.getAttribute(\"style\") ?? \"\";\n const patched = patchStyleAttrString(raw, op.property, op.value);\n opTarget.setAttribute(\"style\", patched);\n }\n break;\n case \"attribute\":\n {\n const fullAttr = op.property.startsWith(\"data-\") ? op.property : `data-${op.property}`;\n if (op.value != null) {\n opTarget.setAttribute(fullAttr, op.value);\n } else {\n opTarget.removeAttribute(fullAttr);\n }\n }\n break;\n case \"html-attribute\":\n if (!isAllowedHtmlAttribute(op.property)) break;\n if (op.value != null) {\n if (!isSafeAttributeValue(op.property, op.value)) break;\n opTarget.setAttribute(op.property, op.value);\n } else {\n opTarget.removeAttribute(op.property);\n }\n break;\n case \"ensure-id\":\n if (opTarget.getAttribute(\"id\") || !op.value) break;\n opTarget.setAttribute(\"id\", nextUniqueId(document, op.value, takenIds));\n break;\n case \"text-content\":\n if (op.value != null) {\n const inner = opTarget.children.length === 1 ? opTarget.firstElementChild : null;\n const textTarget = inner && isHTMLElement(inner) ? inner : opTarget;\n textTarget.textContent = op.value;\n }\n break;\n // The one operation that can write markup, so the one that has to check\n // it. Assigned first and sanitised after, rather than sanitising a\n // string: parsing is what turns a payload into the tree the allowlist\n // can actually judge, and linkedom never runs anything it parses.\n case \"rich-text\":\n if (op.value != null) {\n opTarget.innerHTML = op.value;\n sanitizeRichTextChildren(opTarget);\n stampNewChildIds(opTarget);\n }\n break;\n }\n }\n\n const html = wrappedFragment ? document.body.innerHTML || \"\" : document.toString();\n const elementId = htmlEl.getAttribute(\"id\");\n if (html === originalHtml) return { html: source, matched: true, elementId };\n return { html: ensureHfIds(html), matched: true, elementId };\n}\n\nexport function nextUniqueId(\n document: Document,\n base: string,\n takenIds?: ReadonlySet<string>,\n): string {\n let id = base;\n let suffix = 2;\n while (document.getElementById(id) || takenIds?.has(id)) id = `${base}-${suffix++}`;\n return id;\n}\n\n/** Whether each target exists in `source`; the document is parsed once however many targets ask. */\nexport function probeElementsInSource(\n source: string,\n targets: readonly SourceMutationTarget[],\n): boolean[] {\n const { document } = parseSourceDocument(source);\n return targets.map((target) => {\n if (!target.id && !target.hfId && !target.selector) return false;\n const el = findTargetElement(document, target);\n return el != null && isHTMLElement(el);\n });\n}\n\nexport function probeElementInSource(source: string, target: SourceMutationTarget): boolean {\n return probeElementsInSource(source, [target])[0] ?? false;\n}\n\nexport interface SplitElementResult {\n html: string;\n matched: boolean;\n newId: string | null;\n}\n\nfunction resolveElementTiming(el: Element): {\n start: number;\n duration: number;\n} {\n const timing = readClipTiming(el);\n return { start: timing.start ?? 0, duration: timing.duration ?? 0 };\n}\n\nfunction setElementDuration(\n el: Element,\n start: number,\n duration: number,\n trackIndex?: number,\n): void {\n writeClipTiming(el, {\n start: Math.round(start * 1000) / 1000,\n duration: Math.round(duration * 1000) / 1000,\n ...(trackIndex != null ? { trackIndex } : {}),\n });\n}\n\n// fallow-ignore-next-line complexity\nexport function splitElementInHtml(\n source: string,\n target: SourceMutationTarget,\n splitTime: number,\n newId: string,\n fallbackTiming?: {\n start: number;\n duration: number;\n playbackStart?: number;\n playbackRate?: number;\n stampPlaybackStart?: boolean;\n // The element's current resolved track (authored, or the runtime's\n // positional-index fallback when unauthored). Stamped onto both halves so\n // inserting the clone can't shift either one to a different row — see\n // parseAuthoredTrack's fallback in core/runtime/timeline.ts.\n track?: number;\n },\n): SplitElementResult {\n const { document, wrappedFragment } = parseSourceDocument(source);\n const el = findTargetElement(document, target);\n if (!el || !isHTMLElement(el)) return { html: source, matched: false, newId: null };\n\n const timing = resolveElementTiming(el);\n let { start, duration } = timing;\n // GSAP-animated elements carry their timing in the script, not in data-* attrs,\n // so the source has no authored duration. Fall back to the store's (GSAP-derived)\n // range — the runtime windows visibility off data-start/data-duration regardless\n // of class, so stamping both halves below makes each half show only in its window.\n if (duration <= 0 && fallbackTiming && fallbackTiming.duration > 0) {\n start = fallbackTiming.start;\n duration = fallbackTiming.duration;\n }\n if (duration <= 0 || splitTime <= start || splitTime >= start + duration) {\n return { html: source, matched: false, newId: null };\n }\n\n newId = nextUniqueId(document, newId);\n\n const firstDuration = splitTime - start;\n const secondDuration = duration - firstDuration;\n\n const clone = el.cloneNode(true);\n if (!isHTMLElement(clone)) return { html: source, matched: false, newId: null };\n clone.setAttribute(\"id\", newId);\n dedupeClonedCompositionId(document, clone);\n clone.removeAttribute(\"data-hf-id\");\n // Descendants carry their own data-hf-id; leaving them duplicates the id of\n // every nested node (e.g. an inner <span>), so strip them on the clone too.\n for (const node of clone.querySelectorAll(\"[data-hf-id]\")) node.removeAttribute(\"data-hf-id\");\n setElementDuration(clone, splitTime, secondDuration, fallbackTiming?.track);\n\n // Keep the \"clip\" class — the runtime uses it to control visibility\n // based on data-start/data-duration timing.\n\n // A split creates two views over the same media source. Even an untrimmed\n // audio/video element needs an explicit zero in-point stamped on the first\n // half so the second half can advance from it instead of restarting at zero.\n const playbackStartAttr = el.hasAttribute(\"data-playback-start\")\n ? \"data-playback-start\"\n : el.hasAttribute(\"data-media-start\")\n ? \"data-media-start\"\n : fallbackTiming?.stampPlaybackStart\n ? \"data-playback-start\"\n : el.matches(\"audio, video\")\n ? \"data-media-start\"\n : null;\n if (playbackStartAttr) {\n const readAttr = (name: string) => el.getAttribute(name);\n const authoredTrim = el.getAttribute(playbackStartAttr);\n const currentTrim =\n authoredTrim !== null\n ? readMediaOffsetSeconds(readAttr)\n : (fallbackTiming?.playbackStart ?? 0);\n const rate = readPlaybackRate(readAttr, fallbackTiming?.playbackRate);\n if (authoredTrim === null || Number(authoredTrim) !== currentTrim)\n el.setAttribute(playbackStartAttr, String(Math.round(currentTrim * 1000) / 1000));\n clone.setAttribute(\n playbackStartAttr,\n String(Math.round((currentTrim + firstDuration * rate) * 1000) / 1000),\n );\n }\n\n // Duplicate CSS rules targeting the original ID so the clone inherits the same styles.\n const originalId = el.getAttribute(\"id\");\n if (originalId) {\n duplicateCssRulesForId(document, originalId, newId);\n }\n\n // Trim the original element's duration. A GSAP element had no data-start; stamp\n // it so the runtime windows the first half (visibility selects on [data-start]).\n setElementDuration(el, start, firstDuration, fallbackTiming?.track);\n\n // Insert clone after original\n if (el.nextSibling) {\n el.parentElement!.insertBefore(clone, el.nextSibling);\n } else {\n el.parentElement!.appendChild(clone);\n }\n\n const html = wrappedFragment ? document.body.innerHTML || \"\" : document.toString();\n return {\n // The split owns its new nodes' stable ids. Leaving the clone unstamped makes\n // the next preview request persist different bytes after history is recorded.\n html: ensureHfIds(html),\n matched: true,\n newId,\n };\n}\n\n// --- Element grouping -------------------------------------------------------\n// A group is a real `<div data-hf-group=\"…\">` wrapping its members in the DOM.\n// Wrapping rebases each member's left/top so its absolute position is unchanged:\n// the wrapper sits at the selection bbox top-left, and each child's new left/top\n// is its old left/top minus the wrapper origin (computed client-side, where live\n// layout is available, and passed in via `rebases`). GSAP x/y, CSS translate and\n// --hf-studio-offset vars are deltas relative to flow position and stay untouched.\n\nexport interface WrapElementsResult {\n html: string;\n matched: boolean;\n groupId: string | null;\n error?: string;\n}\n\nexport interface UnwrapElementsResult {\n html: string;\n unwrapped: boolean;\n /** The unwrapped wrapper's id, so callers can strip GSAP that targeted it\n * (the wrapper is gone; a leftover `gsap.set(\"#id\")` would throw at runtime). */\n unwrappedGroupId?: string;\n /** Members (id'd children) with their absolute layout centres (post un-rebase),\n * so the caller can BAKE the group's GSAP transform into each member before\n * stripping it — otherwise the group's moves are lost on ungroup. */\n members?: Array<{ id: string; cx: number; cy: number }>;\n /** The wrapper's layout centre — the pivot for baking the group's rotation/scale. */\n groupCenter?: { cx: number; cy: number };\n}\n\nexport interface ElementRebase {\n target: SourceMutationTarget;\n left: number;\n top: number;\n /** The member's current resolved track (authored, or the runtime's\n * positional-index fallback). Stamped explicitly so moving it into the\n * wrapper can't shift its computed row — same hazard split closes. */\n track?: number;\n}\n\nfunction getInlineStylePx(el: Element, property: string): number {\n const style = (isHTMLElement(el) ? el.getAttribute(\"style\") : null) ?? \"\";\n const { props } = parseStyleDecls(style);\n const raw = props.get(property);\n if (!raw) return 0;\n const n = parseFloat(raw);\n return Number.isFinite(n) ? n : 0;\n}\n\nfunction setInlineLeftTop(el: HTMLElement, left: number, top: number): void {\n let style = el.getAttribute(\"style\") ?? \"\";\n style = patchStyleAttrString(style, \"left\", `${left}px`);\n style = patchStyleAttrString(style, \"top\", `${top}px`);\n el.setAttribute(\"style\", style);\n}\n\n// Slug the group name (\"Group 1\" → \"group-1\") into a unique, valid element id.\nfunction uniqueGroupDomId(document: Document, groupId: string): string {\n const base =\n groupId\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n // Normalization above leaves at most one hyphen at either edge.\n .replace(/^-|-$/g, \"\") || \"group\";\n return nextUniqueId(document, base);\n}\n\n// fallow-ignore-next-line complexity\nexport function wrapElementsInHtml(\n source: string,\n targets: SourceMutationTarget[],\n groupId: string,\n bbox: { left: number; top: number; width: number; height: number },\n rebases: ElementRebase[],\n): WrapElementsResult {\n const { document, wrappedFragment } = parseSourceDocument(source);\n if (targets.length === 0) {\n return { html: source, matched: false, groupId: null, error: \"no targets\" };\n }\n\n // Resolve + dedupe by element ref (two targets may point at the same node).\n const els: HTMLElement[] = [];\n const seen = new Set<Element>();\n for (const target of targets) {\n const el = findTargetElement(document, target);\n if (!el || !isHTMLElement(el) || seen.has(el)) continue;\n seen.add(el);\n els.push(el);\n }\n if (els.length === 0) {\n return { html: source, matched: false, groupId: null, error: \"no targets matched\" };\n }\n\n // P1: require a single common parent (LCA multi-parent wrapping is P2).\n const parent = els[0]?.parentElement;\n if (!parent || els.some((el) => el.parentElement !== parent)) {\n return {\n html: source,\n matched: false,\n groupId: null,\n error: \"grouped elements must share a single parent\",\n };\n }\n\n // Order members by their position in the parent (= z-order / stacking order).\n const memberSet = new Set<Element>(els);\n const ordered = Array.from(parent.children).filter((c): c is HTMLElement => memberSet.has(c));\n\n // Map each member to its rebased left/top and track (resolved against the same document).\n const rebaseByEl = new Map<Element, { left: number; top: number; track?: number }>();\n for (const rebase of rebases) {\n const el = findTargetElement(document, rebase.target);\n if (el) rebaseByEl.set(el, { left: rebase.left, top: rebase.top, track: rebase.track });\n }\n\n const wrapper = document.createElement(\"div\");\n wrapper.setAttribute(\"data-hf-group\", groupId);\n // A real `id` (slug of the group name) makes the wrapper a first-class node in the\n // clip manifest / timeline parent-map (both keyed by id) and a clean GSAP target —\n // without it the wrapper is invisible to the timeline and breaks child enumeration.\n wrapper.setAttribute(\"id\", uniqueGroupDomId(document, groupId));\n // Adopt the topmost member's stacking level. A group is one stacking unit, so a\n // non-member interleaved between two selected members can't stay \"between\" them\n // once they unify. Matching Figma/Sketch, the group lifts to the topmost selected\n // layer: the wrapper goes at the LAST member's slot and carries the max member\n // z-index — so an interleaved non-member falls below the group instead of hoisting\n // above it, and explicit member z-indexes are honored.\n const memberZIndexes = ordered\n .map((el) =>\n Number.parseInt(\n parseStyleDecls(el.getAttribute(\"style\") ?? \"\").props.get(\"z-index\") ?? \"\",\n 10,\n ),\n )\n .filter((z) => Number.isFinite(z));\n const maxZ = memberZIndexes.length > 0 ? Math.max(...memberZIndexes) : null;\n wrapper.setAttribute(\n \"style\",\n `position: absolute; left: ${bbox.left}px; top: ${bbox.top}px; width: ${bbox.width}px; height: ${bbox.height}px` +\n (maxZ !== null ? `; z-index: ${maxZ}` : \"\"),\n );\n\n // Insert the wrapper at the topmost member's slot, then move members into it.\n parent.insertBefore(wrapper, ordered[ordered.length - 1] ?? null);\n for (const el of ordered) {\n const rebase = rebaseByEl.get(el);\n if (rebase) setInlineLeftTop(el, rebase.left, rebase.top);\n if (rebase?.track != null) writeClipTiming(el, { trackIndex: Math.round(rebase.track) });\n wrapper.appendChild(el); // appendChild moves the node, preserving order\n }\n\n return {\n html: wrappedFragment ? document.body.innerHTML || \"\" : document.toString(),\n matched: true,\n groupId,\n };\n}\n\nexport interface UnwrapChildTrack {\n target: SourceMutationTarget;\n /** The child's current resolved track, same hazard and fix as wrap's members. */\n track?: number;\n}\n\n// Only children actually inside the group and given a resolved track qualify —\n// same hazard and fix as wrap's members, scoped to this group's own children.\nfunction buildChildTrackMap(\n document: Document,\n group: Element,\n childTracks: UnwrapChildTrack[],\n): Map<Element, number> {\n const trackByEl = new Map<Element, number>();\n for (const entry of childTracks) {\n const el = findTargetElement(document, entry.target);\n if (el && group.contains(el) && entry.track != null) trackByEl.set(el, entry.track);\n }\n return trackByEl;\n}\n\n// Undoes the wrap-side rebase (child absolute = child rebased + wrapper\n// origin), stamps each child's resolved track where one was given, and moves\n// every child back into the parent ahead of the wrapper — preserving order.\nfunction relocateGroupChildren(\n group: Element,\n parent: Element,\n wLeft: number,\n wTop: number,\n trackByEl: Map<Element, number>,\n): Array<{ id: string; cx: number; cy: number }> {\n const members: Array<{ id: string; cx: number; cy: number }> = [];\n for (const child of Array.from(group.children)) {\n if (isHTMLElement(child)) {\n const newLeft = getInlineStylePx(child, \"left\") + wLeft;\n const newTop = getInlineStylePx(child, \"top\") + wTop;\n setInlineLeftTop(child, newLeft, newTop);\n const track = trackByEl.get(child);\n if (track != null) writeClipTiming(child, { trackIndex: Math.round(track) });\n if (child.id) {\n members.push({\n id: child.id,\n cx: newLeft + getInlineStylePx(child, \"width\") / 2,\n cy: newTop + getInlineStylePx(child, \"height\") / 2,\n });\n }\n }\n parent.insertBefore(child, group);\n }\n return members;\n}\n\nexport function unwrapElementsFromHtml(\n source: string,\n groupTarget: SourceMutationTarget,\n childTracks: UnwrapChildTrack[] = [],\n): UnwrapElementsResult {\n const { document, wrappedFragment } = parseSourceDocument(source);\n const group = findTargetElement(document, groupTarget);\n if (!group || !isHTMLElement(group)) return { html: source, unwrapped: false };\n // Shape guard mirroring the wrap-side contract: only ever dissolve an actual\n // group wrapper. A stale/desynced selection that resolves to a plain <div>\n // would otherwise be unwrapped — rebasing its children by the parent's origin\n // (silent corruption). Wrap enforces invariants; unwrap must too.\n if (!group.hasAttribute(\"data-hf-group\")) return { html: source, unwrapped: false };\n\n const parent = group.parentElement;\n if (!parent) return { html: source, unwrapped: false };\n\n const trackByEl = buildChildTrackMap(document, group, childTracks);\n\n // Undo the rebase: child absolute position = child (rebased) + wrapper origin.\n const wLeft = getInlineStylePx(group, \"left\");\n const wTop = getInlineStylePx(group, \"top\");\n const groupCenter = {\n cx: wLeft + getInlineStylePx(group, \"width\") / 2,\n cy: wTop + getInlineStylePx(group, \"height\") / 2,\n };\n\n const members = relocateGroupChildren(group, parent, wLeft, wTop, trackByEl);\n const groupId = group.id || undefined;\n group.remove();\n\n return {\n html: wrappedFragment ? document.body.innerHTML || \"\" : document.toString(),\n unwrapped: true,\n unwrappedGroupId: groupId,\n members,\n groupCenter,\n };\n}\n\n/** After a cut, give each linked group's right halves their own `data-link` and `data-sync-origin`. */\nexport function relinkSplitHalvesInHtml(source: string, rightHalfIds: readonly string[]): string {\n const { document, wrappedFragment } = parseSourceDocument(source);\n const carriesPairing = (id: string) => {\n const el = document.getElementById(id);\n return Boolean(el?.hasAttribute(\"data-link\") || el?.hasAttribute(\"data-sync-origin\"));\n };\n if (!rightHalfIds.some(carriesPairing)) {\n return source;\n }\n relinkSplitHalves(document, rightHalfIds);\n return wrappedFragment ? document.body.innerHTML || \"\" : document.toString();\n}\n","// fallow-ignore-next-line complexity\nexport function parseStyleDecls(style: string): { props: Map<string, string>; order: string[] } {\n const props = new Map<string, string>();\n const order: string[] = [];\n let i = 0;\n while (i < style.length) {\n let depth = 0;\n let inSingle = false;\n let inDouble = false;\n const start = i;\n while (i < style.length) {\n const ch = style[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (!inSingle && !inDouble) {\n if (ch === \"(\") depth++;\n else if (ch === \")\") depth = Math.max(0, depth - 1);\n else if (ch === \";\" && depth === 0) break;\n }\n i++;\n }\n const decl = style.slice(start, i).trim();\n i++;\n if (!decl) continue;\n const colon = decl.indexOf(\":\");\n if (colon < 0) continue;\n const key = decl.slice(0, colon).trim();\n const val = decl.slice(colon + 1).trim();\n if (!key) continue;\n if (!props.has(key)) order.push(key);\n props.set(key, val);\n }\n return { props, order };\n}\n\nfunction serializeStyleDecls(props: Map<string, string>, order: string[]): string {\n return order\n .map((k) => `${k}: ${props.get(k) ?? \"\"}`)\n .filter((d) => d.trim())\n .join(\"; \");\n}\n\nexport function patchStyleAttrString(\n style: string,\n property: string,\n value: string | null,\n): string {\n const { props, order } = parseStyleDecls(style);\n if (value === null) {\n props.delete(property);\n const idx = order.indexOf(property);\n if (idx >= 0) order.splice(idx, 1);\n } else {\n if (!props.has(property)) order.push(property);\n props.set(property, value);\n }\n return serializeStyleDecls(props, order);\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,oCAAoC;AAC7C,SAAS,wBAAwB,wBAAwB;AACzD,OAAO,aAAa;AACpB,OAAO,oBAAoB;AAC3B,SAAS,wBAAwB,4BAA4B;AAC7D,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,uBAAuB;AAChD,SAAS,yBAAyB;;;ACb3B,SAAS,gBAAgB,OAAgE;AAC9F,QAAM,QAAQ,oBAAI,IAAoB;AACtC,QAAM,QAAkB,CAAC;AACzB,MAAI,IAAI;AACR,SAAO,IAAI,MAAM,QAAQ;AACvB,QAAI,QAAQ;AACZ,QAAI,WAAW;AACf,QAAI,WAAW;AACf,UAAM,QAAQ;AACd,WAAO,IAAI,MAAM,QAAQ;AACvB,YAAM,KAAK,MAAM,CAAC;AAClB,UAAI,OAAO,OAAO,CAAC,SAAU,YAAW,CAAC;AAAA,eAChC,OAAO,OAAO,CAAC,SAAU,YAAW,CAAC;AAAA,eACrC,CAAC,YAAY,CAAC,UAAU;AAC/B,YAAI,OAAO,IAAK;AAAA,iBACP,OAAO,IAAK,SAAQ,KAAK,IAAI,GAAG,QAAQ,CAAC;AAAA,iBACzC,OAAO,OAAO,UAAU,EAAG;AAAA,MACtC;AACA;AAAA,IACF;AACA,UAAM,OAAO,MAAM,MAAM,OAAO,CAAC,EAAE,KAAK;AACxC;AACA,QAAI,CAAC,KAAM;AACX,UAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,QAAI,QAAQ,EAAG;AACf,UAAM,MAAM,KAAK,MAAM,GAAG,KAAK,EAAE,KAAK;AACtC,UAAM,MAAM,KAAK,MAAM,QAAQ,CAAC,EAAE,KAAK;AACvC,QAAI,CAAC,IAAK;AACV,QAAI,CAAC,MA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AAM,SAAS,MAAM;AACrB,MAAI,CAAC,OAAQ,QAAO,EAAE,MAAM,QAAQ,WAAW,MAAM;AAErD,QAAM,YAAY,mBAAmB,UAAU,OAAO,WAAW;AAGjE,QAAM,QAAQ,iBAAiB,OAAO,MAAM;AAC5C,QAAM,OAAO,iBAAiB,OAAO,KAAK;AAC1C,QAAM,cAAc;AAAA,IAClB,IAAI,QAAQ,iBAAiB,OAAO,OAAO,IAAI;AAAA,IAC/C,IAAI,OAAO,iBAAiB,OAAO,QAAQ,IAAI;AAAA,EACjD;AAEA,QAAM,UAAU,sBAAsB,OAAO,QAAQ,OAAO,MAAM,SAAS;AAC3E,QAAM,UAAU,MAAM,MAAM;AAC5B,QAAM,OAAO;AAEb,SAAO;AAAA,IACL,MAAM,kBAAkB,SAAS,KAAK,aAAa,KAAK,SAAS,SAAS;AAAA,IAC1E,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,EACF;AACF;AAGO,SAAS,wBAAwB,QAAgB,cAAyC;AAC/F,QAAM,EAAE,UAAU,gBAAgB,IAAI,oBAAoB,MAAM;AAChE,QAAM,iBAAiB,CAAC,OAAe;AACrC,UAAM,KAAK,SAAS,eAAe,EAAE;AACrC,WAAO,QAAQ,IAAI,aAAa,WAAW,KAAK,IAAI,aAAa,kBAAkB,CAAC;AAAA,EACtF;AACA,MAAI,CAAC,aAAa,KAAK,cAAc,GAAG;AACtC,WAAO;AAAA,EACT;AACA,oBAAkB,UAAU,YAAY;AACxC,SAAO,kBAAkB,SAAS,KAAK,aAAa,KAAK,SAAS,SAAS;AAC7E;","names":[]}
@@ -18,16 +18,19 @@ declare function removeElementFromHtml(source: string, target: SourceMutationTar
18
18
  declare function isHTMLElement(el: Node): el is HTMLElement;
19
19
  declare function dedupeClonedCompositionId(document: Document, clone: Element): void;
20
20
  interface PatchOperation {
21
- type: "inline-style" | "attribute" | "html-attribute" | "text-content" | "rich-text";
21
+ /** `ensure-id` keeps the element's id, else writes `value` made unique in this file and `takenIds`. */
22
+ type: "inline-style" | "attribute" | "html-attribute" | "text-content" | "rich-text" | "ensure-id";
22
23
  property: string;
23
24
  value: string | null;
24
25
  childSelector?: string;
25
26
  childIndex?: number;
26
27
  }
27
- declare function patchElementInHtml(source: string, target: SourceMutationTarget, operations: PatchOperation[]): {
28
+ declare function patchElementInHtml(source: string, target: SourceMutationTarget, operations: PatchOperation[], takenIds?: ReadonlySet<string>): {
28
29
  html: string;
29
30
  matched: boolean;
31
+ elementId?: string | null;
30
32
  };
33
+ declare function nextUniqueId(document: Document, base: string, takenIds?: ReadonlySet<string>): string;
31
34
  /** Whether each target exists in `source`; the document is parsed once however many targets ask. */
32
35
  declare function probeElementsInSource(source: string, targets: readonly SourceMutationTarget[]): boolean[];
33
36
  declare function probeElementInSource(source: string, target: SourceMutationTarget): boolean;
@@ -94,4 +97,4 @@ declare function unwrapElementsFromHtml(source: string, groupTarget: SourceMutat
94
97
  /** After a cut, give each linked group's right halves their own `data-link` and `data-sync-origin`. */
95
98
  declare function relinkSplitHalvesInHtml(source: string, rightHalfIds: readonly string[]): string;
96
99
 
97
- export { type ElementRebase, type PatchOperation, type SourceMutationTarget, type SplitElementResult, type UnwrapChildTrack, type UnwrapElementsResult, type WrapElementsResult, dedupeClonedCompositionId, findTargetElement, isHTMLElement, parseSourceDocument, patchElementInHtml, probeElementInSource, probeElementsInSource, relinkSplitHalvesInHtml, removeElementFromHtml, removeElementsFromHtml, splitElementInHtml, unwrapElementsFromHtml, wrapElementsInHtml };
100
+ export { type ElementRebase, type PatchOperation, type SourceMutationTarget, type SplitElementResult, type UnwrapChildTrack, type UnwrapElementsResult, type WrapElementsResult, dedupeClonedCompositionId, findTargetElement, isHTMLElement, nextUniqueId, parseSourceDocument, patchElementInHtml, probeElementInSource, probeElementsInSource, relinkSplitHalvesInHtml, removeElementFromHtml, removeElementsFromHtml, splitElementInHtml, unwrapElementsFromHtml, wrapElementsInHtml };
@@ -2,6 +2,7 @@ import {
2
2
  dedupeClonedCompositionId,
3
3
  findTargetElement,
4
4
  isHTMLElement,
5
+ nextUniqueId,
5
6
  parseSourceDocument,
6
7
  patchElementInHtml,
7
8
  probeElementInSource,
@@ -12,11 +13,12 @@ import {
12
13
  splitElementInHtml,
13
14
  unwrapElementsFromHtml,
14
15
  wrapElementsInHtml
15
- } from "../chunk-G4YB7Q2Q.js";
16
+ } from "../chunk-CLWFZQUU.js";
16
17
  export {
17
18
  dedupeClonedCompositionId,
18
19
  findTargetElement,
19
20
  isHTMLElement,
21
+ nextUniqueId,
20
22
  parseSourceDocument,
21
23
  patchElementInHtml,
22
24
  probeElementInSource,
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  dedupeClonedCompositionId,
7
7
  findTargetElement,
8
8
  isHTMLElement,
9
+ nextUniqueId,
9
10
  parseSourceDocument,
10
11
  patchElementInHtml,
11
12
  probeElementInSource,
@@ -16,7 +17,7 @@ import {
16
17
  splitElementInHtml,
17
18
  unwrapElementsFromHtml,
18
19
  wrapElementsInHtml
19
- } from "./chunk-G4YB7Q2Q.js";
20
+ } from "./chunk-CLWFZQUU.js";
20
21
  import {
21
22
  isCompositionSource,
22
23
  stampProjectHfIds
@@ -1002,6 +1003,21 @@ function foldElementPatches(originalContent, patches) {
1002
1003
  return { content, matched };
1003
1004
  }
1004
1005
  var PATCH_CONFLICT_ATTEMPTS = 3;
1006
+ var ID_ATTRIBUTE = /[\s"'/]id\s*=\s*(?=(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))/gi;
1007
+ function projectHtmlIds(projectDir) {
1008
+ const ids = /* @__PURE__ */ new Set();
1009
+ for (const rel of walkDir(projectDir)) {
1010
+ if (!rel.endsWith(".html") || isInHiddenOrVendorDir(rel)) continue;
1011
+ let html;
1012
+ try {
1013
+ html = readFileSync3(join5(projectDir, rel), "utf-8");
1014
+ } catch {
1015
+ continue;
1016
+ }
1017
+ for (const m of html.matchAll(ID_ATTRIBUTE)) ids.add(m[1] ?? m[2] ?? m[3] ?? "");
1018
+ }
1019
+ return ids;
1020
+ }
1005
1021
  function commitElementPatchBatches(projectDir, batches, writeFile = (path, content) => replaceFileAtomically2(path, content, statSync3(path).mode), requestToken) {
1006
1022
  for (let attempt = 1; ; attempt += 1) {
1007
1023
  try {
@@ -2893,7 +2909,13 @@ function registerFileRoutes(api, adapter) {
2893
2909
  } catch {
2894
2910
  return c.json({ error: "not found" }, 404);
2895
2911
  }
2896
- const element = patchElementInHtml(originalContent, parsed.target, parsed.body.operations);
2912
+ const takenIds = parsed.body.operations.some((op) => op.type === "ensure-id") ? projectHtmlIds(ctx.project.dir) : void 0;
2913
+ const element = patchElementInHtml(
2914
+ originalContent,
2915
+ parsed.target,
2916
+ parsed.body.operations,
2917
+ takenIds
2918
+ );
2897
2919
  const { matched } = element;
2898
2920
  const patched = matched && isStudioFontFaceCss(fontFaceCss) ? ensureStudioFontFaceCss(element.html, fontFaceCss) : element.html;
2899
2921
  if (patched === originalContent) {
@@ -2903,6 +2925,7 @@ function registerFileRoutes(api, adapter) {
2903
2925
  ok: true,
2904
2926
  changed: false,
2905
2927
  matched,
2928
+ elementId: element.elementId,
2906
2929
  content: originalContent,
2907
2930
  path: ctx.filePath,
2908
2931
  version: version2
@@ -2926,6 +2949,7 @@ function registerFileRoutes(api, adapter) {
2926
2949
  ok: true,
2927
2950
  changed: true,
2928
2951
  matched,
2952
+ elementId: element.elementId,
2929
2953
  content: patched,
2930
2954
  path: ctx.filePath,
2931
2955
  version,
@@ -4977,11 +5001,6 @@ function spans(el, time) {
4977
5001
  if (start === null || duration === null) return false;
4978
5002
  return time > start + EPSILON && time < start + duration - EPSILON;
4979
5003
  }
4980
- function uniqueId(document, base) {
4981
- let id = base;
4982
- for (let n = 2; document.getElementById(id); n++) id = `${base}-${n}`;
4983
- return id;
4984
- }
4985
5004
  function shiftTracks(document, tracks, from, by) {
4986
5005
  for (const el of document.querySelectorAll("[data-start]")) {
4987
5006
  if (el.hasAttribute("data-composition-id") || !tracks.has(trackOf(el))) continue;
@@ -5065,7 +5084,7 @@ function applyFreezeFrameToHtml(html, input) {
5065
5084
  shiftTracks(document, tracks, input.playhead, hold);
5066
5085
  const leftHalf = findTargetElement(document, input.target);
5067
5086
  if (!leftHalf?.parentElement) return null;
5068
- const freezeId = uniqueId(document, `${video.getAttribute("id") || "clip"}-freeze`);
5087
+ const freezeId = nextUniqueId(document, `${video.getAttribute("id") || "clip"}-freeze`);
5069
5088
  const still = buildStill(document, leftHalf, {
5070
5089
  id: freezeId,
5071
5090
  imageSrc: input.imageSrc,
@@ -6145,23 +6164,17 @@ function duplicateElementInHtml(source, target, newId, at) {
6145
6164
  if (duration === null || numericAttribute(element, "data-start") === null) {
6146
6165
  return { html: source, matched: false, newId: null };
6147
6166
  }
6148
- const uniqueId2 = nextUniqueId(document, newId);
6167
+ const uniqueId = nextUniqueId(document, newId);
6149
6168
  rippleElements(document, element, at, duration, track);
6150
6169
  const clone = element.cloneNode(true);
6151
6170
  if (!isHTMLElement(clone)) return { html: source, matched: false, newId: null };
6152
- clone.setAttribute("id", uniqueId2);
6171
+ clone.setAttribute("id", uniqueId);
6153
6172
  dedupeClonedCompositionId(document, clone);
6154
6173
  stripStableIds(clone);
6155
6174
  clone.setAttribute("data-start", String(at));
6156
6175
  element.parentElement.insertBefore(clone, element.nextSibling);
6157
6176
  const html = wrappedFragment ? document.body.innerHTML || "" : document.toString();
6158
- return { html: ensureHfIds4(html), matched: true, newId: uniqueId2 };
6159
- }
6160
- function nextUniqueId(document, newId) {
6161
- let uniqueId2 = newId;
6162
- let suffix = 2;
6163
- while (document.getElementById(uniqueId2)) uniqueId2 = `${newId}-${suffix++}`;
6164
- return uniqueId2;
6177
+ return { html: ensureHfIds4(html), matched: true, newId: uniqueId };
6165
6178
  }
6166
6179
  function rippleElements(document, element, at, duration, track) {
6167
6180
  for (const candidate of Array.from(document.querySelectorAll("[data-start][data-duration]"))) {