Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat: add source-backed studio parameters

kashorin470a373164f5
diff --git a/packages/markup/src/syntax.ts b/packages/markup/src/syntax.ts
index d1cba398..75f5f74e 100644
--- a/packages/markup/src/syntax.ts
+++ b/packages/markup/src/syntax.ts
@@ -1,4 +1,5 @@
import { MarkupFrontendError } from "./error.js";
+import type { SourceRange } from "@hypit/protocol";
import type {
MarkupSource,
StructuredElement,
@@ -15,6 +16,7 @@ const REFERENCE = /^[A-Za-z_][A-Za-z0-9_.:-]*(?:\.[A-Za-z_][A-Za-z0-9_.:-]*)*$/u
type OpeningTag = {
readonly name: string;
readonly attributes: Readonly<Record<string, MarkupAttributeValue>>;
+ readonly attributeValueRanges: Readonly<Record<string, SourceRange>>;
readonly start: number;
readonly end: number;
readonly selfClosing: boolean;
@@ -67,7 +69,7 @@ function parseName(source: MarkupSource, start: number): { readonly value: strin
function parseAttributeValue(
source: MarkupSource,
start: number,
-): { readonly value: MarkupAttributeValue; readonly end: number } {
+): { readonly value: MarkupAttributeValue; readonly end: number; readonly valueStart: number; readonly valueEnd: number } {
const quote = source.text[start];
if (quote === "\"" || quote === "'") {
const close = source.text.indexOf(quote, start + 1);
@@ -75,6 +77,8 @@ function parseAttributeValue(
return {
value: decodeEntities(source.text.slice(start + 1, close), source, start),
end: close + 1,
+ valueStart: start + 1,
+ valueEnd: close,
};
}
if (quote === "{") {
@@ -82,7 +86,7 @@ function parseAttributeValue(
if (close < 0) fail(source, "MARKUP_REFERENCE", "Unclosed reference attribute.", start);
const path = source.text.slice(start + 1, close).trim();
if (!REFERENCE.test(path)) fail(source, "MARKUP_REFERENCE", `Invalid reference "${path}".`, start);
- return { value: { kind: "reference", path }, end: close + 1 };
+ return { value: { kind: "reference", path }, end: close + 1, valueStart: start, valueEnd: close + 1 };
}
fail(source, "MARKUP_ATTRIBUTE", "Attribute values must be quoted strings or whole-value references.", start);
}
@@ -94,13 +98,18 @@ export function parseOpeningTag(source: MarkupSource, start: number): OpeningTag
const parsedName = parseName(source, start + 1);
let cursor = parsedName.end;
const attributes: Record<string, MarkupAttributeValue> = {};
+ const attributeValueRanges: Record<string, SourceRange> = {};
while (cursor < source.text.length) {
cursor = skipSpace(source.text, cursor);
if (source.text.startsWith("/>", cursor)) {
- return { name: parsedName.value, attributes, start, end: cursor + 2, selfClosing: true };
+ return {
+ name: parsedName.value, attributes, attributeValueRanges, start, end: cursor + 2, selfClosing: true,
+ };
}
if (source.text[cursor] === ">") {
- return { name: parsedName.value, attributes, start, end: cursor + 1, selfClosing: false };
+ return {
+ name: parsedName.value, attributes, attributeValueRanges, start, end: cursor + 1, selfClosing: false,
+ };
}
const attribute = parseName(source, cursor);
if (Object.hasOwn(attributes, attribute.value)) {
@@ -116,6 +125,7 @@ export function parseOpeningTag(source: MarkupSource, start: number): OpeningTag
configurable: true,
writable: true,
});
+ attributeValueRanges[attribute.value] = { start: value.valueStart, end: value.valueEnd };
cursor = value.end;
}
fail(source, "MARKUP_OPEN", `Opening tag <${parsedName.value}> is not closed.`, start);
@@ -140,6 +150,7 @@ export function parseStructuredElement(
kind: "element",
name: opening.name,
attributes: opening.attributes,
+ attributeValueRanges: opening.attributeValueRanges,
children: [],
range: { start, end: opening.end },
},
@@ -165,6 +176,7 @@ export function parseStructuredElement(
kind: "element",
name: opening.name,
attributes: opening.attributes,
+ attributeValueRanges: opening.attributeValueRanges,
children,
range: { start, end: close.end },
},
diff --git a/packages/markup/src/types.ts b/packages/markup/src/types.ts
index 6c6b99a6..c447064a 100644
--- a/packages/markup/src/types.ts
+++ b/packages/markup/src/types.ts
@@ -52,6 +52,8 @@ export type StructuredElement = {
readonly kind: "element";
readonly name: string;
readonly attributes: Readonly<Record<string, MarkupAttributeValue>>;
+ /** Exact ranges of literal/reference values in the opening tag. */
+ readonly attributeValueRanges?: Readonly<Record<string, SourceRange>>;
readonly children: readonly StructuredNode[];
readonly range: SourceRange;
};
diff --git a/packages/studio-adapter/src/index.ts b/packages/studio-adapter/src/index.ts
index 73646d7d..b5df3683 100644
--- a/packages/studio-adapter/src/index.ts
+++ b/packages/studio-adapter/src/index.ts
@@ -49,6 +49,56 @@ export type StudioInteraction = {
readonly writeback: "source" | "none";
};
+export type StudioParameterControl = "text" | "number" | "boolean" | "select";
+export type StudioParameterLanguage = "svml" | "svs" | "svrun";
+
+/** A real source value that an Inspector may display or edit. */
+export type StudioParameter = {
+ readonly id: string;
+ readonly label: string;
+ readonly control: StudioParameterControl;
+ readonly value: string;
+ readonly language: StudioParameterLanguage;
+ readonly writable: boolean;
+ readonly options?: readonly string[];
+ readonly unit?: string;
+ readonly source: {
+ readonly path: string;
+ readonly range: Range;
+ readonly preimage: string;
+ };
+ readonly disabledReason?: string;
+};
+
+/** Adapter-owned allowlist for source parameters exposed by Studio. */
+export type StudioParameterDeclaration = {
+ readonly name: string;
+ readonly label?: string;
+ readonly control?: StudioParameterControl;
+ readonly writable?: boolean;
+ readonly options?: readonly string[];
+ readonly unit?: string;
+};
+
+export type StudioEditOperation =
+ | "move"
+ | "trim-start"
+ | "trim-end"
+ | "slip"
+ | "split"
+ | "delete"
+ | "duplicate"
+ | "canvas-transform";
+
+/** A timeline affordance is present only when its source write is explicit. */
+export type StudioEditHandle = {
+ readonly id: string;
+ readonly operation: StudioEditOperation;
+ readonly enabled: boolean;
+ readonly source?: StudioParameter["source"];
+ readonly disabledReason?: string;
+};
+
export type StudioMaterialPreview =
| { readonly kind: "image"; readonly url: string }
| { readonly kind: "video"; readonly url: string }
@@ -141,10 +191,12 @@ export type StudioObservedValue = {
};
export type StudioPlacementChild = {
+ readonly sourcePath: string;
readonly tag: string;
readonly id?: string;
readonly range: Range;
readonly attributes: Readonly<Record<string, string>>;
+ readonly attributeValueRanges: Readonly<Record<string, Range>>;
readonly references: readonly string[];
readonly referenceAttributes: Readonly<Record<string, string>>;
readonly referenceTypes: Readonly<Record<string, string>>;
@@ -152,6 +204,7 @@ export type StudioPlacementChild = {
};
export type StudioPlacement = {
+ readonly sourcePath: string;
readonly tag: string;
readonly module: { readonly name: string; readonly version: string };
readonly surface: string;
@@ -163,6 +216,7 @@ export type StudioPlacement = {
readonly outputPorts: readonly { readonly name: string; readonly ref: string }[];
readonly children: readonly StudioPlacementChild[];
readonly attributes: Readonly<Record<string, string>>;
+ readonly attributeValueRanges: Readonly<Record<string, Range>>;
readonly referenceAttributes: Readonly<Record<string, string>>;
readonly referenceTypes: Readonly<Record<string, string>>;
readonly references: readonly string[];
@@ -223,6 +277,8 @@ export type StudioEntityDraft = {
readonly preview?: StudioMaterialPreview;
/** Studio-local lane partition; omitted means the root lane. */
readonly lane?: string;
+ readonly parameters?: readonly StudioParameter[];
+ readonly editHandles?: readonly StudioEditHandle[];
};
export type StudioAdapterContext = {
@@ -259,6 +315,7 @@ export type StudioAdapter = {
readonly interaction?: StudioInteraction;
readonly lane?: StudioLaneDescription;
readonly inspector?: StudioInspectorDescription;
+ readonly parameters?: readonly StudioParameterDeclaration[];
readonly project?: (context: StudioAdapterContext) => readonly StudioEntityDraft[];
};
@@ -313,6 +370,7 @@ export type StudioLaneAttachment = {
readonly lane: StudioLaneDescription;
readonly interaction?: StudioInteraction;
readonly inspector?: StudioInspectorDescription;
+ readonly parameters?: readonly StudioParameterDeclaration[];
};
export const readonlyInteraction: StudioInteraction = {
diff --git a/packages/studio-video-adapters/src/deck.ts b/packages/studio-video-adapters/src/deck.ts
index fac2a8d4..8bd75b78 100644
--- a/packages/studio-video-adapters/src/deck.ts
+++ b/packages/studio-video-adapters/src/deck.ts
@@ -53,6 +53,11 @@ export const deckAdapters: readonly StudioAdapter[] = [
id: "deck", role: "track",
output: { type: "VisualTrack", surface: "track", modules: ["@hypit/deck-track"] },
family: "component", icon: "layers", realizationPorts: ["program"],
+ parameters: [
+ { name: "frame", label: "Frame", writable: false },
+ { name: "appearance", label: "Appearance", writable: false },
+ { name: "until", label: "Until", writable: false },
+ ],
interaction: readonlyInteraction, project: projectDeck,
lane: { layout: "flat", height: videoLaneHeights.component },
},
diff --git a/packages/studio-video-adapters/src/generic.ts b/packages/studio-video-adapters/src/generic.ts
index c253b85d..a8f99c72 100644
--- a/packages/studio-video-adapters/src/generic.ts
+++ b/packages/studio-video-adapters/src/generic.ts
@@ -115,12 +115,30 @@ export const genericAdapters: readonly StudioAdapter[] = [
{
id: "text", role: "text", output: { type: "VisualTrack", surface: "track", modules: ["@hypit/typography-track"] },
family: "text", icon: "text", interaction: readonlyInteraction,
+ parameters: [
+ { name: "placement", label: "Placement", writable: false },
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ { name: "style", label: "Style", writable: false },
+ ],
realizationPorts: ["program"], project: projectText,
lane: { layout: "flat", height: videoLaneHeights.text },
},
{
id: "caption", role: "caption", output: { type: "VisualTrack", surface: "track", modules: ["@hypit/caption-fine"] },
family: "caption", icon: "captions", interaction: readonlyInteraction,
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ { name: "style", label: "Style", writable: false },
+ { name: "program", label: "Program", writable: false },
+ ],
project: projectCaption,
lane: { layout: "flat", height: videoLaneHeights.text },
},
@@ -128,10 +146,33 @@ export const genericAdapters: readonly StudioAdapter[] = [
id: "component", role: "track",
output: { type: "VisualTrack", modules: ["@hypit/ranking", "@hypit/comment-sticker", "@hypit/screen-overlay"] },
family: "component", icon: "component", interaction: readonlyInteraction,
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ { name: "until", label: "Until", writable: false },
+ { name: "z", label: "Z", control: "number", writable: true },
+ ],
lane: { layout: "flat", height: videoLaneHeights.component },
},
{ id: "audio-track", role: "track", output: { type: "AudioTrack" }, family: "audio", icon: "waveform", interaction: readonlyInteraction,
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ ],
project: projectTerminalAudio, lane: { layout: "flat", height: videoLaneHeights.audio } },
{ id: "visual-track", role: "track", output: { type: "VisualTrack" }, family: "media", icon: "video", interaction: readonlyInteraction,
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ ],
project: projectTerminalVisual, lane: { layout: "flat", height: videoLaneHeights.picture } },
];
diff --git a/packages/studio-video-adapters/src/media.ts b/packages/studio-video-adapters/src/media.ts
index b27bf429..64a32d1c 100644
--- a/packages/studio-video-adapters/src/media.ts
+++ b/packages/studio-video-adapters/src/media.ts
@@ -90,6 +90,17 @@ export const mediaAdapters: readonly StudioAdapter[] = [
id: "media-visual", role: "media",
output: { type: "VisualTrack", surface: "track", modules: ["@hypit/media-track"] },
family: "media", icon: "video", interaction: readonlyInteraction,
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ { name: "frame", label: "Frame", writable: false },
+ { name: "appearance", label: "Appearance", writable: false },
+ { name: "motion", label: "Motion", writable: false },
+ { name: "z", label: "Z", control: "number", writable: true },
+ ],
realizationPorts: ["program"], project: projectMedia,
lane: { layout: "flat", height: videoLaneHeights.picture },
},
@@ -97,6 +108,17 @@ export const mediaAdapters: readonly StudioAdapter[] = [
id: "media-audio", role: "media",
output: { type: "AudioTrack", surface: "track", modules: ["@hypit/media-track"] },
family: "media", icon: "waveform", interaction: readonlyInteraction,
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ { name: "frame", label: "Frame", writable: false },
+ { name: "appearance", label: "Appearance", writable: false },
+ { name: "motion", label: "Motion", writable: false },
+ { name: "z", label: "Z", control: "number", writable: true },
+ ],
realizationPorts: ["program"], project: projectMedia,
lane: { layout: "flat", height: videoLaneHeights.audio },
},
diff --git a/packages/studio-video-adapters/src/ranking.ts b/packages/studio-video-adapters/src/ranking.ts
index 6f97c2ae..69e2ff56 100644
--- a/packages/studio-video-adapters/src/ranking.ts
+++ b/packages/studio-video-adapters/src/ranking.ts
@@ -114,6 +114,15 @@ export const rankingAdapters: readonly StudioAdapter[] = [
id: "ranking-column", role: "track",
output: { type: "VisualTrack", surface: "column", modules: ["@hypit/ranking"] },
family: "component", label: "Ranking", icon: "ranking", realizationPorts: ["schedule"],
+ parameters: [
+ { name: "style", label: "Style", writable: false },
+ { name: "during", label: "During", writable: false },
+ { name: "start", label: "Start", writable: true },
+ { name: "end", label: "End", writable: true },
+ { name: "at", label: "At", writable: false },
+ { name: "for", label: "For", writable: true },
+ { name: "frame", label: "Frame", writable: false },
+ ],
poster: { source: "surface-preview" },
lane: {
layout: "flat",
@@ -131,6 +140,11 @@ export const rankingAdapters: readonly StudioAdapter[] = [
height: { minPx: 34, preferredPx: 40, maxPx: 56 },
expandedByDefault: true,
},
+ parameters: [
+ { name: "during", label: "During", writable: false },
+ { name: "at", label: "At", writable: false },
+ { name: "stack", label: "Stack", control: "number", writable: true },
+ ],
}],
interaction: readonlyInteraction, project: projectRanking,
},
diff --git a/packages/studio-video-adapters/src/speech.ts b/packages/studio-video-adapters/src/speech.ts
index 1c8385e2..4f9c7b61 100644
--- a/packages/studio-video-adapters/src/speech.ts
+++ b/packages/studio-video-adapters/src/speech.ts
@@ -37,6 +37,11 @@ export const speechAdapters: readonly StudioAdapter[] = [
output: { type: "VisualTrack", surface: "track", modules: ["@hypit/speech-track"] },
family: "media", label: "Speech Visual", icon: "video",
interaction: readonlyInteraction,
+ parameters: [
+ { name: "visual-frame", label: "Frame", writable: false },
+ { name: "visual-appearance", label: "Appearance", writable: false },
+ { name: "visual-z", label: "Z", control: "number", writable: true },
+ ],
project: projectSpeechVisual,
lane: { layout: "flat", height: videoLaneHeights.picture },
},
@@ -45,6 +50,9 @@ export const speechAdapters: readonly StudioAdapter[] = [
output: { type: "AudioTrack", surface: "track", modules: ["@hypit/speech-track"] },
family: "audio", label: "Speech Audio", icon: "waveform",
interaction: readonlyInteraction,
+ parameters: [
+ { name: "z", label: "Z", control: "number", writable: true },
+ ],
project: projectSpeechAudio,
lane: { layout: "flat", height: videoLaneHeights.audio },
},
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 5b578b64..15508f0d 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -21,6 +21,7 @@
"@hypit/runtime-host-node": "workspace:*",
"@hypit/script": "workspace:*",
"@hypit/semantic-track": "workspace:*",
+ "@hypit/svs": "workspace:*",
"@hypit/studio-adapter": "workspace:*",
"@hypit/studio-video-adapters": "workspace:*",
"@hypit/validation": "workspace:*",
diff --git a/packages/studio/src/observe.ts b/packages/studio/src/observe.ts
index 7f73f92e..0a6c193f 100644
--- a/packages/studio/src/observe.ts
+++ b/packages/studio/src/observe.ts
@@ -114,6 +114,8 @@ export function createObserver(
placements.push({
tag: input.element.name,
module: { ...module },
+ sourcePath: input.sourceName,
+ attributeValueRanges: input.element.attributeValueRanges ?? {},
surface: found.surface,
...(typeof id === "string" ? { id } : {}),
range: { start: input.element.range.start, end: input.element.range.end },
@@ -137,6 +139,8 @@ export function createObserver(
const childId = child.attributes.id;
return {
tag: child.name,
+ sourcePath: input.sourceName,
+ attributeValueRanges: child.attributeValueRanges ?? {},
...(typeof childId === "string" ? { id: childId } : {}),
range: { start: child.range.start, end: child.range.end },
attributes: written(child),
diff --git a/packages/studio/src/parameters.ts b/packages/studio/src/parameters.ts
new file mode 100644
index 00000000..073f7347
--- /dev/null
+++ b/packages/studio/src/parameters.ts
@@ -0,0 +1,199 @@
+import { dirname, isAbsolute, relative, resolve } from "node:path";
+
+import type {
+ StudioParameter,
+ StudioParameterDeclaration,
+ StudioEntityDraft,
+ StudioPlacement,
+} from "@hypit/studio-adapter";
+import { parseSvs } from "@hypit/svs";
+
+import type { Range } from "./shared.js";
+import type { Placement } from "./observe.js";
+
+export type StudioSourceFile = {
+ readonly path: string;
+ readonly text: string;
+ readonly language: "svml" | "svs" | "svrun";
+ readonly imports?: readonly { readonly alias: string; readonly source: string }[];
+};
+
+type AuthorElement = {
+ readonly sourcePath: string;
+ readonly attributes: Readonly<Record<string, string>>;
+ readonly references: Readonly<Record<string, string>>;
+ readonly attributeValueRanges: Readonly<Record<string, Range>>;
+};
+
+function sameRange(left: Range | undefined, right: Range | undefined): boolean {
+ return left !== undefined && right !== undefined && left.start === right.start && left.end === right.end;
+}
+
+function elementFor(placement: StudioPlacement, draft: StudioEntityDraft): AuthorElement | undefined {
+ const candidates: readonly (AuthorElement & { readonly id?: string; readonly range: Range })[] = [
+ {
+ sourcePath: placement.sourcePath,
+ attributes: placement.attributes,
+ references: placement.referenceAttributes,
+ attributeValueRanges: placement.attributeValueRanges,
+ ...(placement.id === undefined ? {} : { id: placement.id }),
+ range: placement.range,
+ },
+ ...placement.children.map((child) => ({
+ sourcePath: child.sourcePath,
+ attributes: child.attributes,
+ references: child.referenceAttributes,
+ attributeValueRanges: child.attributeValueRanges,
+ ...(child.id === undefined ? {} : { id: child.id }),
+ range: child.range,
+ })),
+ ];
+ return candidates.find((candidate) => sameRange(candidate.range, draft.elementRange))
+ ?? candidates.find((candidate) => candidate.id === draft.authoredId);
+}
+
+function languageOf(path: string): StudioSourceFile["language"] {
+ if (path.endsWith(".svs")) return "svs";
+ if (path.endsWith(".svrun")) return "svrun";
+ return "svml";
+}
+
+function sourceFor(
+ root: string,
+ path: string,
+ files: readonly StudioSourceFile[],
+ base?: string,
+): StudioSourceFile | undefined {
+ const absolute = isAbsolute(path)
+ ? resolve(path)
+ : resolve(base === undefined ? root : dirname(base), path);
+ return files.find((file) => resolve(file.path) === absolute)
+ ?? files.find((file) => file.path === relative(root, absolute));
+}
+
+function svsText(source: string): string {
+ const header = /^\s*<\?svml[\s\S]*?\?>/u.exec(source);
+ if (header === null) return source;
+ return `${header[0].replace(/[^\r\n]/gu, " ")}${source.slice(header[0].length)}`;
+}
+
+function recipeParameters(input: {
+ readonly root: string;
+ readonly files: readonly StudioSourceFile[];
+ readonly current: StudioSourceFile;
+ readonly draft: StudioEntityDraft;
+ readonly referenceName: string;
+ readonly referencePath: string;
+ readonly placements: readonly Placement[];
+}): readonly StudioParameter[] {
+ const local = input.placements.find((candidate) => candidate.id === input.referencePath);
+ if (local !== undefined) {
+ const next = ["recipe", "default", "style", "appearance", "motion", "program"]
+ .map((name) => local.referenceAttributes[name])
+ .find((value) => value !== undefined);
+ if (next !== undefined && next !== input.referencePath) {
+ return recipeParameters({
+ ...input,
+ current: sourceFor(input.root, local.sourcePath, input.files) ?? input.current,
+ referencePath: next,
+ });
+ }
+ }
+ const [alias, ...parts] = input.referencePath.split(".");
+ if (alias === undefined || parts.length === 0) return [];
+ const imported = input.current.imports?.find((item) => item.alias === alias);
+ if (imported === undefined) return [];
+ const source = sourceFor(input.root, imported.source, input.files, input.current.path);
+ if (source === undefined || source.language !== "svs") return [];
+ const recipePath = parts.join(".");
+ const parsed = parseSvs(source.path, svsText(source.text));
+ const recipe = parsed.recipes.find((item) => item.value.path === recipePath);
+ if (recipe === undefined) return [];
+ return recipe.properties.map((property) => {
+ const preimage = source.text.slice(property.valueRange.start, property.valueRange.end);
+ const raw = preimage.trim();
+ const control = raw === "true" || raw === "false"
+ ? "boolean" as const
+ : /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/u.test(raw) ? "number" as const : "text" as const;
+ return {
+ id: `${input.draft.id}:${input.referenceName}:${property.name}`,
+ label: `${input.referenceName} · ${property.name}`,
+ control,
+ value: raw,
+ language: "svs" as const,
+ writable: true,
+ source: {
+ path: relative(input.root, resolve(source.path)),
+ range: property.valueRange,
+ preimage,
+ },
+ } satisfies StudioParameter;
+ });
+}
+
+/**
+ * Expose only attributes a package explicitly registered. The source range is
+ * still discovered by the generic markup frontend, while the meaning and
+ * editability remain package-owned Studio ABI data.
+ */
+export function parametersForDraft(input: {
+ readonly root: string;
+ readonly files: readonly StudioSourceFile[];
+ readonly placement: StudioPlacement | undefined;
+ readonly draft: StudioEntityDraft;
+ readonly declarations: readonly StudioParameterDeclaration[];
+ readonly placements?: readonly Placement[];
+}): readonly StudioParameter[] {
+ const placement = input.placement;
+ if (placement === undefined || input.declarations.length === 0) return [];
+ const element = elementFor(placement, input.draft);
+ if (element === undefined) return [];
+ const file = sourceFor(input.root, element.sourcePath, input.files);
+ if (file === undefined) return [];
+
+ const direct = input.declarations.flatMap((declaration) => {
+ const name = declaration.name;
+ const range = element.attributeValueRanges[name];
+ if (range === undefined) return [];
+ const preimage = file.text.slice(range.start, range.end);
+ const reference = element.references[name];
+ const value = reference === undefined
+ ? (element.attributes[name] ?? preimage)
+ : reference;
+ const isReference = reference !== undefined;
+ const writable = declaration.writable === true && !isReference;
+ return [{
+ id: `${input.draft.id}:${name}`,
+ label: declaration.label ?? name,
+ control: declaration.control ?? "text",
+ value,
+ language: languageOf(element.sourcePath),
+ writable,
+ ...(declaration.options === undefined ? {} : { options: declaration.options }),
+ ...(declaration.unit === undefined ? {} : { unit: declaration.unit }),
+ source: {
+ path: relative(input.root, resolve(element.sourcePath)),
+ range,
+ preimage,
+ },
+ ...(!writable
+ ? { disabledReason: isReference ? "引用由作者在 SVML 中绑定,面板不替换引用关系。" : "该参数由组件声明为只读。" }
+ : {}),
+ } satisfies StudioParameter];
+ });
+ const recipes = input.declarations.flatMap((declaration) => {
+ const referencePath = element.references[declaration.name];
+ if (referencePath === undefined
+ || !["appearance", "visual-appearance", "motion", "style", "recipe", "program", "default"].includes(declaration.name)) return [];
+ return recipeParameters({
+ root: input.root,
+ files: input.files,
+ current: file,
+ draft: input.draft,
+ referenceName: declaration.label ?? declaration.name,
+ referencePath,
+ placements: input.placements ?? [],
+ });
+ });
+ return [...direct, ...recipes];
+}
diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.ts
index bb86e68d..5c1e6093 100644
--- a/packages/studio/src/server.ts
+++ b/packages/studio/src/server.ts
@@ -1,7 +1,8 @@
import { watch } from "node:fs";
import type { FSWatcher } from "node:fs";
-import { writeFile } from "node:fs/promises";
-import { relative } from "node:path";
+import { existsSync } from "node:fs";
+import { readFile, rename, writeFile, unlink } from "node:fs/promises";
+import { isAbsolute, relative, resolve, dirname, join } from "node:path";
import type { Plugin, ViteDevServer } from "vite";
@@ -53,6 +54,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
let timer: ReturnType<typeof setTimeout> | undefined;
let requestedRevision = 0;
let currentSource = options.source;
+ let allowedSourceFiles = new Set<string>();
const watched = new Map<string, FSWatcher>();
const storyboards = new Map<string, Promise<StudioStoryboard>>();
@@ -79,6 +81,11 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
currentSource = run.authorSource;
watchSource(options.runPath);
for (const unit of run.source.compiled.closure.units) watchSource(unit.id);
+ allowedSourceFiles = new Set([
+ options.runPath,
+ run.authorSource,
+ ...run.source.compiled.closure.units.map((unit) => unit.id).filter((path) => existsSync(path)),
+ ].map((path) => resolve(path)));
const result = await readStudioSession({
domain: options.domain,
registry: options.registry,
@@ -86,6 +93,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
...(options.archive === undefined ? {} : { archive: options.archive }),
revision: attempt,
sourcePath: relative(options.workspaceRoot, run.authorSource),
+ workspaceRoot: options.workspaceRoot,
});
if (attempt !== requestedRevision) return;
revision = attempt;
@@ -112,6 +120,70 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
timer = setTimeout(() => void publish(attempt), 80);
};
+ type Patch = {
+ readonly path: string;
+ readonly range: Range;
+ readonly replacement: string;
+ readonly preimage: string;
+ };
+
+ const applyTransaction = async (patches: readonly Patch[], expectedRevision: number): Promise<void> => {
+ if (snapshot !== undefined && expectedRevision !== snapshot.revision) {
+ throw new Error("The Source changed outside Studio.");
+ }
+ const grouped = new Map<string, Patch[]>();
+ for (const patch of patches) {
+ if (isAbsolute(patch.path)) throw new Error("Studio patches must use workspace-relative paths.");
+ const absolute = resolve(options.workspaceRoot, patch.path);
+ const rel = relative(options.workspaceRoot, absolute);
+ if (rel.startsWith("..") || isAbsolute(rel) || !allowedSourceFiles.has(absolute)) {
+ throw new Error(`Studio cannot write source file ${patch.path}.`);
+ }
+ if (!Number.isInteger(patch.range.start) || !Number.isInteger(patch.range.end)
+ || patch.range.start < 0 || patch.range.end < patch.range.start) {
+ throw new Error(`Invalid source range for ${patch.path}.`);
+ }
+ const held = grouped.get(absolute) ?? [];
+ held.push(patch);
+ grouped.set(absolute, held);
+ }
+ const nextFiles = new Map<string, string>();
+ for (const [absolute, filePatches] of grouped) {
+ const text = await readFile(absolute, "utf8");
+ const ordered = [...filePatches].sort((left, right) => left.range.start - right.range.start);
+ for (let index = 1; index < ordered.length; index += 1) {
+ const previous = ordered[index - 1]!;
+ const current = ordered[index]!;
+ if (current.range.start < previous.range.end) {
+ throw new Error(`Overlapping source patches are not allowed: ${relative(options.workspaceRoot, absolute)}.`);
+ }
+ }
+ let next = text;
+ for (const patch of [...filePatches].sort((left, right) => right.range.start - left.range.start)) {
+ if (patch.range.end > text.length) throw new Error(`Source range exceeds file: ${patch.path}.`);
+ const current = next.slice(patch.range.start, patch.range.end);
+ if (current !== patch.preimage) throw new Error(`Source changed outside Studio: ${patch.path}.`);
+ next = `${next.slice(0, patch.range.start)}${patch.replacement}${next.slice(patch.range.end)}`;
+ }
+ nextFiles.set(absolute, next);
+ }
+ // Validate every file before touching any file. Temp files make a single
+ // multi-file write observable as one Studio transaction in normal hosts.
+ const temporaries: { readonly path: string; readonly temporary: string }[] = [];
+ try {
+ for (const [absolute, text] of nextFiles) {
+ const temporary = join(dirname(absolute), `.${absolute.split("/").at(-1) ?? "source"}.hypit-studio.tmp`);
+ await writeFile(temporary, text, "utf8");
+ temporaries.push({ path: absolute, temporary });
+ }
+ for (const item of temporaries) await rename(item.temporary, item.path);
+ } finally {
+ for (const item of temporaries) {
+ try { await unlink(item.temporary); } catch { /* already renamed */ }
+ }
+ }
+ };
+
return {
name: "hypit-studio",
configureServer(value) {
@@ -137,7 +209,13 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
json(response, 409, { error: "The Source changed outside Studio." });
return;
}
- await writeFile(currentSource, body.text, "utf8");
+ const current = await readFile(currentSource, "utf8");
+ await applyTransaction([{
+ path: relative(options.workspaceRoot, currentSource),
+ range: { start: 0, end: current.length },
+ replacement: body.text,
+ preimage: current,
+ }], body.revision);
schedule();
response.statusCode = 202;
response.end();
@@ -147,6 +225,37 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
})();
return;
}
+ if (request.method === "POST" && url.pathname === "/__studio/transaction") {
+ void (async () => {
+ try {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
+ readonly revision?: unknown;
+ readonly patches?: unknown;
+ };
+ if (typeof body.revision !== "number" || !Array.isArray(body.patches)) {
+ json(response, 400, { error: "Expected a revision and source patches." });
+ return;
+ }
+ const patches = body.patches as Patch[];
+ if (patches.some((patch) => typeof patch.path !== "string"
+ || typeof patch.replacement !== "string"
+ || typeof patch.preimage !== "string"
+ || typeof patch.range !== "object" || patch.range === null)) {
+ json(response, 400, { error: "Invalid source patch." });
+ return;
+ }
+ await applyTransaction(patches, body.revision);
+ schedule();
+ json(response, 202, { revision: body.revision });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ json(response, message.includes("changed outside") ? 409 : 500, { error: message });
+ }
+ })();
+ return;
+ }
if (request.method !== "GET" && request.method !== "HEAD") {
next();
return;
diff --git a/packages/studio/src/session.ts b/packages/studio/src/session.ts
index 5e625849..46df98b3 100644
--- a/packages/studio/src/session.ts
+++ b/packages/studio/src/session.ts
@@ -1,4 +1,4 @@
-import { readFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import type { StudioArchive } from "./archive.js";
import type { ServedFile } from "./compile.js";
@@ -12,6 +12,26 @@ import type { StudioAdapterRegistry } from "./studio-registry.js";
import { snapshot } from "./snapshot.js";
import { inspectStudioRun } from "./studio-preflight.js";
import type { StudioProjection } from "./studio-preflight.js";
+import type { StudioSourceFile } from "./parameters.js";
+
+function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {
+ const paths = [run.authorSource, ...run.source.compiled.closure.units.map((unit) => unit.id)];
+ return [...new Set(paths)].flatMap((path): StudioSourceFile[] => {
+ if (!existsSync(path)) return [];
+ try {
+ const language = path.endsWith(".svs") ? "svs" : path.endsWith(".svrun") ? "svrun" : "svml";
+ const unit = run.source.compiled.closure.units.find((candidate) => candidate.id === path);
+ return [{
+ path,
+ text: readFileSync(path, "utf8"),
+ language,
+ ...(unit === undefined ? {} : { imports: unit.imports }),
+ }];
+ } catch {
+ return [];
+ }
+ });
+}
export type StudioSession = {
readonly snapshot: StudioSnapshot;
@@ -27,6 +47,7 @@ export async function readStudioSession(input: {
readonly archive?: StudioArchive;
readonly revision: number;
readonly sourcePath?: string;
+ readonly workspaceRoot: string;
}): Promise<StudioSession> {
const source = input.run.source;
const inspection = inspectStudioRun(input.registry, source, input.run);
@@ -49,6 +70,7 @@ export async function readStudioSession(input: {
served: new Set(built.served.keys()),
});
const text = readFileSync(input.run.authorSource, "utf8");
+ const files = sourceFiles(input.run);
return {
snapshot: snapshot(input.registry, built, {
revision: input.revision,
@@ -57,6 +79,8 @@ export async function readStudioSession(input: {
canvas: built.canvas,
frameRate: built.frameRate,
preview: { kind: "hyperframes", srcdoc: rendered },
+ workspaceRoot: input.workspaceRoot,
+ sourceFiles: files,
}),
material: built.served,
observations: source.observations,
diff --git a/packages/studio/src/shared.ts b/packages/studio/src/shared.ts
index 7bedb258..78101eaf 100644
--- a/packages/studio/src/shared.ts
+++ b/packages/studio/src/shared.ts
@@ -6,9 +6,11 @@
import type {
Range,
StudioInteraction,
+ StudioEditHandle,
StudioInspectorDescription,
StudioLaneDescription,
StudioMaterialPreview,
+ StudioParameter,
StudioSemanticAnchor,
StudioSemanticSegment,
StudioSemanticTimeline,
@@ -24,9 +26,11 @@ import type {
export type {
Range,
StudioInteraction,
+ StudioEditHandle,
StudioInspectorDescription,
StudioLaneDescription,
StudioMaterialPreview,
+ StudioParameter,
StudioTemporalLineage,
StudioTemporalPhase,
StudioTemporalProjection,
@@ -101,6 +105,8 @@ export type Clip = {
readonly interaction: StudioInteraction;
/** Rendering identities implementing this author entity; optional for non-visual entities. */
readonly renderIds: readonly string[];
+ readonly parameters: readonly StudioParameter[];
+ readonly editHandles: readonly StudioEditHandle[];
};
export type Track = {
diff --git a/packages/studio/src/snapshot.ts b/packages/studio/src/snapshot.ts
index 0160f53d..f98c5080 100644
--- a/packages/studio/src/snapshot.ts
+++ b/packages/studio/src/snapshot.ts
@@ -22,6 +22,8 @@ import {
} from "./studio-registry.js";
import type { StudioAdapterRegistry } from "./studio-registry.js";
import type { StudioEntityDraft } from "./studio-registry.js";
+import { parametersForDraft } from "./parameters.js";
+import type { StudioSourceFile } from "./parameters.js";
type Present = {
readonly id: string;
@@ -273,6 +275,8 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:
readonly canvas: { readonly width: number; readonly height: number; readonly clearColor: string };
readonly frameRate: { readonly numerator: number; readonly denominator: number };
readonly preview: StudioSnapshot["preview"];
+ readonly workspaceRoot: string;
+ readonly sourceFiles: readonly StudioSourceFile[];
}): StudioSnapshot {
const located = authored(built.source.observations.placements);
const script = scriptMap(built.source.observations.sourceMaps, built);
@@ -333,6 +337,16 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:
values: built.values,
semantic,
generic,
+ }).map((draft) => {
+ const parameters = parametersForDraft({
+ root: input.workspaceRoot,
+ files: input.sourceFiles,
+ placement,
+ draft,
+ declarations: registry.parameterDeclarations(item, placement, draft.lane),
+ placements: built.source.observations.placements,
+ });
+ return parameters.length === 0 ? draft : { ...draft, parameters };
});
const clips: Clip[] = drafts
.filter((draft) => draft.lane === undefined)
diff --git a/packages/studio/src/studio-registry.ts b/packages/studio/src/studio-registry.ts
index ef5280f2..ac63995f 100644
--- a/packages/studio/src/studio-registry.ts
+++ b/packages/studio/src/studio-registry.ts
@@ -187,6 +187,18 @@ export class StudioAdapterRegistry {
? draft
: { ...draft, preview });
}
+
+ parameterDeclarations(
+ track: StudioResolvedTrack,
+ placement: Placement | undefined,
+ lane?: string,
+ ) {
+ const adapter = this.#trackAdapter(track);
+ if (lane !== undefined) {
+ return adapter.attachments?.find((attachment) => attachment.id === lane)?.parameters ?? [];
+ }
+ return adapter.parameters ?? [];
+ }
}
export function sealStudioClip(
@@ -211,6 +223,8 @@ export function sealStudioClip(
},
...(draft.temporal === undefined ? {} : { temporal: draft.temporal }),
...(draft.preview === undefined ? {} : { preview: draft.preview }),
+ parameters: draft.parameters ?? [],
+ editHandles: draft.editHandles ?? [],
interaction: draft.interaction ?? fallback.interaction,
renderIds: draft.renderIds ?? (draft.presentId === undefined ? [] : [draft.presentId]),
};
diff --git a/packages/studio/src/style.css b/packages/studio/src/style.css
index 119fd568..0948fa91 100644
--- a/packages/studio/src/style.css
+++ b/packages/studio/src/style.css
@@ -411,6 +411,38 @@ button:focus-visible, textarea:focus-visible {
}
.property-code > strong { font: 11px/1.3 var(--font-mono); }
.property-number > strong { font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
+.parameter-group .property-grid { display: flex; flex-direction: column; gap: 4px; }
+.parameter-row {
+ min-width: 0;
+ min-height: 32px;
+ display: grid;
+ grid-template-columns: minmax(76px, .8fr) minmax(0, 1.2fr);
+ grid-template-rows: 20px 12px;
+ column-gap: 10px;
+ align-items: center;
+ padding: 2px 0;
+}
+.parameter-label { min-width: 0; overflow: hidden; color: var(--text-3); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
+.parameter-right { min-width: 0; display: flex; align-items: center; justify-content: flex-end; gap: 4px; }
+.parameter-value {
+ min-width: 0;
+ width: 100%;
+ box-sizing: border-box;
+ border: 1px solid var(--line-strong);
+ border-radius: 3px;
+ padding: 3px 6px;
+ background: var(--panel-2);
+ color: var(--text);
+ font: 11px/1.2 var(--font-mono);
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+}
+.parameter-value:focus { outline: 1px solid var(--brand-500); outline-offset: 1px; }
+.parameter-readonly .parameter-value { border: 0; padding-right: 0; background: transparent; color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.parameter-source { grid-column: 1 / -1; min-width: 0; overflow: hidden; color: var(--text-3); font: 9px/1 var(--font-mono); opacity: .7; text-overflow: ellipsis; white-space: nowrap; }
+.parameter-right > small { flex: none; color: var(--text-3); font-size: 10px; }
+.status.saving { color: var(--text-2); }
+.status.saved { color: var(--ok); }
/* Timeline */
.timeline { height: 100%; min-height: 0; display: flex; flex-direction: column; background: #0f1013; }
diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.ts
index d0db58b5..d90dd64f 100644
--- a/packages/studio/src/ui/main.ts
+++ b/packages/studio/src/ui/main.ts
@@ -1,4 +1,4 @@
-import type { StudioFailure, StudioSnapshot } from "../shared.js";
+import type { Clip, StudioFailure, StudioSnapshot } from "../shared.js";
import { createCodePane } from "./code.js";
import { setIcon } from "./icons.js";
import { createHandle } from "./resize.js";
@@ -129,6 +129,88 @@ function group(label: string, items: readonly HTMLElement[], className = ""): HT
return node;
}
+function parameterControl(parameter: Clip["parameters"][number]): HTMLElement {
+ const row = document.createElement("label");
+ row.className = `parameter-row${parameter.writable ? " parameter-editable" : " parameter-readonly"}`;
+ const name = document.createElement("span");
+ name.className = "parameter-label";
+ name.textContent = parameter.label;
+ const source = document.createElement("small");
+ source.className = "parameter-source";
+ source.textContent = `${parameter.language.toUpperCase()} · ${parameter.source.path}:${parameter.source.range.start}`;
+ source.title = parameter.disabledReason ?? parameter.source.preimage;
+ const value = parameter.writable
+ ? document.createElement(parameter.control === "select" ? "select" : "input")
+ : document.createElement("strong");
+ value.className = "parameter-value";
+ if (value instanceof HTMLInputElement) {
+ value.type = parameter.control === "number" ? "number" : parameter.control === "boolean" ? "checkbox" : "text";
+ if (value.type === "checkbox") value.checked = parameter.value === "true";
+ else value.value = parameter.value;
+ value.dataset.parameterId = parameter.id;
+ value.title = parameter.source.preimage;
+ value.addEventListener("change", () => {
+ void writeParameter(parameter, value.type === "checkbox" ? String(value.checked) : value.value);
+ });
+ } else if (value instanceof HTMLSelectElement) {
+ for (const option of parameter.options ?? []) {
+ const item = document.createElement("option");
+ item.value = option;
+ item.textContent = option;
+ item.selected = option === parameter.value;
+ value.append(item);
+ }
+ value.addEventListener("change", () => void writeParameter(parameter, value.value));
+ } else {
+ value.textContent = parameter.value;
+ value.title = parameter.disabledReason ?? parameter.source.preimage;
+ }
+ const suffix = parameter.unit === undefined ? "" : ` ${parameter.unit}`;
+ const right = document.createElement("span");
+ right.className = "parameter-right";
+ right.append(value);
+ if (suffix.length > 0) {
+ const unit = document.createElement("small");
+ unit.textContent = suffix;
+ right.append(unit);
+ }
+ row.append(name, right, source);
+ if (!parameter.writable) row.title = parameter.disabledReason ?? "Read-only source parameter";
+ return row;
+}
+
+let parameterWriteState: "" | "Saving" | "Saved" | "Failed" = "";
+async function writeParameter(parameter: Clip["parameters"][number], replacement: string): Promise<void> {
+ const state = store.current();
+ if (state === undefined || !parameter.writable) return;
+ parameterWriteState = "Saving";
+ status.textContent = parameterWriteState;
+ status.className = "status saving";
+ try {
+ const response = await fetch("/__studio/transaction", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ revision: state.snapshot.revision,
+ patches: [{
+ path: parameter.source.path,
+ range: parameter.source.range,
+ replacement,
+ preimage: parameter.source.preimage,
+ }],
+ }),
+ });
+ if (!response.ok) throw new Error(await response.text());
+ parameterWriteState = "Saved";
+ status.textContent = parameterWriteState;
+ status.className = "status saved";
+ } catch (error) {
+ parameterWriteState = "Failed";
+ status.textContent = error instanceof Error ? "Save failed" : parameterWriteState;
+ status.className = "status error";
+ }
+}
+
/**
* A single strip between the picture and the timeline. It is a row of the
* layout rather than a floating card, so it can never cover the frame being
@@ -176,7 +258,16 @@ function renderInspector(snapshot: StudioSnapshot, clipId: string | undefined):
property("To", clip.temporal.projection.endExpression, "property-wide property-code"),
]),
]);
- inspector.replaceChildren(hero, placement, timing, ...(source === undefined ? [] : [source]));
+ const run = track === undefined ? undefined : group("Run", [
+ property("Output", track.provenance.output, "property-wide property-code"),
+ ...(track.provenance.candidateId === undefined ? [] : [
+ property("Candidate", track.provenance.candidateId, "property-wide property-code"),
+ ]),
+ property("Status", track.provenance.status),
+ property("Writeback", "Read-only"),
+ ]);
+ const parameters = clip.parameters.length === 0 ? undefined : group("Parameters", clip.parameters.map(parameterControl), "parameter-group");
+ inspector.replaceChildren(hero, placement, timing, ...(parameters === undefined ? [] : [parameters]), ...(source === undefined ? [] : [source]), ...(run === undefined ? [] : [run]));
}
function renderSemanticInspector(snapshot: StudioSnapshot, segmentId: string): void {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9402e9b0..165798af 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2496,6 +2496,9 @@ importers:
'@hypit/semantic-track':
specifier: workspace:*
version: link:../semantic-track
+ '@hypit/svs':
+ specifier: workspace:*
+ version: link:../svs
'@hypit/studio-adapter':
specifier: workspace:*
version: link:../studio-adapter