Skip to content

Code-first video & image, rendered natively on WebGPU.

109 KB
Raw Blame
import { resolveFrameRequest } from "@framefields/core";

export {
	type Ai,
	type AiConfig,
	ApiError,
	ai,
	FRAMEFIELDS_AI_PROXY_URL,
	type QueueStatus,
	type Result,
	type RunOptions,
	ValidationError,
} from "@framefields/ai";
export {
	type AudioPitchOptions,
	type AudioPitchSignals,
	AudioSignal,
	type AudioSignalOptions,
	computed,
	cosineSignal,
	type ExtractedAudioSignalsBundle,
	type FrameSignal,
	Signal,
	type SignalContext,
	type SignalValue,
	type SineSignalOptions,
	signal,
	signalBuilder,
	signalRegistry,
	sineSignal,
} from "./signals/index.js";

import {
	FontManager,
	type MeasuredGlyph,
	type MeasureTextOptions,
	type RegisteredFont,
	type RegisterFontOptions,
	type TextMetrics,
} from "./fonts/index.js";
import { autoId } from "./ids.js";
import { normalizeTextSpans, type TextSpan } from "./rich-text.js";

export {
	encodeStereoWav,
	mixAudioTracks,
	mixSfxInto,
	type RenderedSfx,
	renderSfx,
	type SfxRenderContext,
	type SfxTrigger,
	softLimit,
} from "./audio/index.js";
export {
	accent,
	bold,
	code,
	color,
	italic,
	type MarkOptions,
	mark,
	normalizeTextSpans,
	parseMarkup,
	rich,
	size,
	span,
	sub,
	sup,
	type TextSpan,
	type TextSpanItem,
	type TextSpanMark,
} from "./rich-text.js";
export {
	FontManager,
	type MeasuredGlyph,
	type MeasureTextOptions,
	type RegisteredFont,
	type RegisterFontOptions,
	type TextMetrics,
};

export {
	CannyComputePipeline,
	type CannyOptions,
	type ControlNetConditioningOutputs,
	ControlNetMultiplexer,
	type DeflickerOptions,
	DepthNormalsComputePipeline,
	type DepthNormalsOptions,
	type NormalRelightingOptions,
	OpticalFlowComputePipeline,
	type OpticalFlowOptions,
	TemporalDeflickerPipeline,
	type TensorDimensions,
	type TensorFormat,
	type TensorNode,
	TensorPipeline,
	type TensorPipelineConfig,
	type TensorSource,
	type TensorViewExport,
} from "@framefields/tensor-webgpu";
export {
	COCO_CLASSES,
	COCO17_BONES,
	COCO17_KEYPOINT_NAMES,
	COCO17_KEYPOINTS,
	type DetectedObject,
	type InstanceMask,
	type Landmark3D,
	type LandmarkCoordinateSignals,
	type MaskTrackSignals,
	type NormalizedLandmarkList,
	type ObjectAnchorName,
	type ObjectAnchorsSignals,
	type ObjectBoundingBox,
	type ObjectBoundingBoxSignals,
	type ObjectCollectionSignals,
	type ObjectKinematicsSignals,
	type ObjectTrackSignals,
	type PersonMatte,
	type PinToLandmarkOptions,
	type PinToObjectOptions,
	type PoseLandmarkSignals,
	type PoseResult,
	PoseSkeletonRenderer,
	pinNodeToLandmark,
	pinNodeToObject,
	type SegmentationResult,
	SegmentationTexturePool,
	SpatialLandmarkTransformer,
	TemporalObjectTracker,
	type TrackedObject,
	VisionBundle,
	type VisionConfig,
	VisionNode,
	VisionRunner,
	type VisionTask,
	type VisionVariant,
} from "@framefields/vision";

// Types only, so SAM stays in its own lazily loaded chunk; the trackers are in `framefields/sam`.
export type {
	Sam2FrameResult,
	Sam2Model,
	Sam2Options,
	Sam2Point,
	Sam2Prompt,
	Sam3Options,
	Sam3Precision,
	Sam3Prompt,
} from "@framefields/vision-sam";

import fs from "node:fs/promises";
import path from "node:path";
import { preflightMediaTime } from "@framefields/compositions";
import {
	type AnimatableProp,
	type AnimatablePropsFor,
	type AnimationTrack,
	type BoxNode,
	type CameraNode,
	type CompositorProgramConfig,
	type CompositorToProgramOptions,
	collectLayersOnClock,
	compositorToProgram,
	type EnvironmentPreset,
	type EnvironmentVolumetricFog,
	type EnvironmentVolumetricFogNoise,
	type FlexNode,
	LayerAnimation,
	type LayoutNode,
	type LightAnimatableProp,
	type LightNode,
	lintComposition,
	type MatteMode,
	type MediaAnimatableProp,
	type MediaNode,
	type MediaSignalResolver,
	type Model3DAnimatableProp,
	type Model3DNode,
	mergeAnimationTracks,
	type ShapeAnimatableProp,
	type ShapeNode,
	type SizeSpec,
	type TextAnimatableProp,
	type TextNode,
} from "@framefields/compositions/program";
import {
	appendOperation,
	Effect as CoreEffect,
	createVirtualMedia,
	type DataType,
	type FrameContext,
	type MediaMetadata,
	type MediaOperation,
	type MediaSourceInput,
	type MeshAudioDeformConfig,
	ProgrammaticSignal,
	type RenderDiagnostic,
	type ResolvedMediaTimeRemap,
	type Signal,
	type VirtualMediaData,
} from "@framefields/core";

export type {
	MediaTimeRemap,
	MediaTimeRemapInput,
	MediaTimeSignalRemap,
} from "@framefields/core";

import {
	analyzeSequence as analyzeVisionFrames,
	CLIP_SUBJECT,
	type LandmarkCoordinateSignals,
	type MaskTrackSignals,
	type ObjectTrackSignals,
	type PinToLandmarkOptions,
	type PinToObjectOptions,
	pinNodeToLandmark,
	pinNodeToObject,
	type VisionAnalysisReport,
	VisionBundle,
	VisionNode,
	VisionRunner,
	type VisionTask,
} from "@framefields/vision";

export {
	analyzeSequence,
	type VisionAnalysisReport,
} from "@framefields/vision";

import {
	type DeflickerOptions,
	type NormalRelightingOptions,
	TensorPipeline,
} from "@framefields/tensor-webgpu";
import { inputStore, mediaDecoderCache } from "@framefields/webgpu-renderers";
import { buildChart, type ChartOptions } from "./chart.js";
import { ClipVision, type ClipVisionOptions } from "./clip-vision.js";
import {
	type AnyAudioEffect,
	type AnyEffect,
	type AnyVisualEffect,
	ApplyLUT,
	type ApplyLUTProps,
	Blur,
	type BlurProps,
	ColorBalance,
	type ColorBalanceProps,
	ColorKey,
	type ColorKeyProps,
	Crop,
	type CropProps,
	Curves,
	type CurvesProps,
	CustomEffect,
	type DeflickerProps,
	DepthOfField,
	type DepthOfFieldProps,
	type EffectProp,
	effectFactories,
	FilmGrain,
	type FilmGrainProps,
	GradientMap,
	type GradientMapProps,
	HalftoneScreen,
	type HalftoneScreenProps,
	HighPass,
	type HighPassProps,
	Levels,
	type LevelsProps,
	Modulate,
	type ModulateProps,
	MotionBlur,
	type MotionBlurProps,
	PBRGlass,
	type PBRGlassProps,
	ProceduralVFX,
	type ProceduralVFXProps,
	Relight3D,
	type Relight3DProps,
	SelectiveColor,
	type SelectiveColorProps,
	ShadowsHighlights,
	type ShadowsHighlightsProps,
	SSAO,
	type SSAOProps,
	TemporalDeflicker,
	TileOffset,
	type TileOffsetProps,
	UnsharpMask,
	type UnsharpMaskProps,
	Vignette,
	type VignetteProps,
	Vision,
	type VisionProps,
} from "./effects/index.js";
import {
	contextAtFrame,
	MediaSignalTimeline,
	remapKey,
} from "./media-signals.js";
import { Particles, type ParticlesOptions } from "./particles.js";
import {
	type FrameGridOptions,
	HeadlessMediaRenderer,
	type RenderProgress,
	renderFrameGrid,
	type VideoQaOptions,
	type VideoQaReport,
} from "./renderer/index.js";
import {
	type Carousel3DOptions,
	type Cube3DOptions,
	Layer3D,
	type Plane3DOptions,
	type Prism3DOptions,
	type SolidShape3DNode,
} from "./shapes3d.js";
import {
	type SceneSequenceOptions,
	type SequenceEntry,
	type SequenceNode,
	sequence,
} from "./transitions.js";

export interface SectionOptions {
	readonly id?: string;
	readonly position?: "absolute" | "relative";
	readonly source?: string | MediaNode;
	readonly effects?: AnyVisualEffect[];
	readonly padding?: number;
	readonly borderRadius?: number;
	readonly borderColor?: string;
	readonly borderWidth?: number;
	readonly opacity?: EffectProp<number>;
	readonly blendMode?: string;
	readonly fit?: "cover" | "contain";
	readonly width?: EffectProp<SizeSpec>;
	readonly height?: EffectProp<SizeSpec>;
	readonly compositionWidth?: number;
	readonly compositionHeight?: number;
	readonly compWidth?: number;
	readonly compHeight?: number;
	readonly x?: EffectProp<number>;
	readonly y?: EffectProp<number>;
	readonly hideWhenLost?: boolean;
	readonly smoothFrames?: number;
	readonly children?: LayoutNode[];
}

export type SectionNode = AnimatableNode<BoxNode, "visual"> & {
	readonly innerMedia: AnimatableNode<MediaNode, "hybrid">;
	// Any visual effect, whatever its config shape (Blur, FilmGrain, …).
	readonly effects: AnyVisualEffect[];
	addEffect(effect: AnyVisualEffect): SectionNode;
	withEffect(effect: AnyVisualEffect): SectionNode;
	withEffects(effects: AnyVisualEffect[]): SectionNode;
};

export type TrackedRegionOptions = SectionOptions;

/** Editing helpers attached to every tracked object (see decorateTrackSignals). */
export interface TrackEditing {
	/** A section of the source that follows this track */
	section(
		sourceOrOptions?: string | MediaNode | SectionOptions,
		options?: SectionOptions,
	): SectionNode;
	/** A blur confined to this track's region */
	blurEffect(options?: Partial<BlurProps>): Blur;
	/** The tracked region of `source`, cut out as a section */
	isolate(
		source: string | MediaNode,
		options?: TrackedRegionOptions,
	): SectionNode;
}

/** A tracked object with its editing helpers, as vision hands it out. */
export type EditableObjectTrack = ObjectTrackSignals & TrackEditing;

function decorateTrackSignals<T extends ObjectTrackSignals>(
	track: T,
	source?: string | MediaNode,
): T {
	if (!track) return track;
	if (source && !track.source) {
		Object.defineProperty(track, "source", {
			value: source,
			enumerable: true,
			writable: true,
			configurable: true,
		});
	}
	if (typeof track.section !== "function") {
		Object.defineProperty(track, "section", {
			value: (
				sourceOrOptions?: string | MediaNode | SectionOptions,
				options?: SectionOptions,
			) => {
				if (
					typeof sourceOrOptions === "object" &&
					sourceOrOptions !== null &&
					!("kind" in sourceOrOptions) &&
					!("inputHandleId" in sourceOrOptions) &&
					!("src" in sourceOrOptions)
				) {
					const resolvedSource =
						(sourceOrOptions as SectionOptions).source ??
						(track.source as string | MediaNode | undefined) ??
						source;
					return Layer.section(
						resolvedSource as string | MediaNode,
						track,
						sourceOrOptions as SectionOptions,
					);
				}
				const resolvedSource =
					sourceOrOptions ??
					(track.source as string | MediaNode | undefined) ??
					source;
				return Layer.section(
					resolvedSource as string | MediaNode,
					track,
					options,
				);
			},
			enumerable: false,
			writable: true,
			configurable: true,
		});
	}
	if (typeof track.blurEffect !== "function") {
		Object.defineProperty(track, "blurEffect", {
			value: (options?: Partial<BlurProps>) => new Blur({ track, ...options }),
			enumerable: false,
			writable: true,
			configurable: true,
		});
	}
	if (typeof track.isolate !== "function") {
		Object.defineProperty(track, "isolate", {
			value: (sourceArg: string | MediaNode, options?: TrackedRegionOptions) =>
				Layer.section(sourceArg, track, options),
			enumerable: false,
			writable: true,
			configurable: true,
		});
	}
	return track;
}

const origVisionAttach = VisionNode.attach;
VisionNode.attach = function (
	source: Parameters<typeof origVisionAttach>[0],
	config?: Parameters<typeof origVisionAttach>[1],
	bundleOptions?: Parameters<typeof origVisionAttach>[2],
): ReturnType<typeof origVisionAttach> {
	const bundle = origVisionAttach.call(this, source, config, bundleOptions);
	if (bundle?.objects) {
		const src = source as string | MediaNode;
		const origGet = bundle.objects.get.bind(bundle.objects);
		bundle.objects.get = (id: number) => decorateTrackSignals(origGet(id), src);

		const origByCategory = bundle.objects.byCategory.bind(bundle.objects);
		bundle.objects.byCategory = (cat: string, rank?: number) =>
			decorateTrackSignals(origByCategory(cat, rank), src);

		if (bundle.objects.primary) {
			decorateTrackSignals(bundle.objects.primary, src);
		}
	}
	return bundle;
};

export {
	type AdvancedTextAnimator,
	AdvancedTextAnimatorBuilder,
	AdvancedTextAnimatorSchema,
	// Text Animations & After Effects Parity
	type AETextAnimator,
	AETextAnimatorSchema,
	type AnchorGrouping,
	AnchorGroupingSchema,
	type AnchorPreset,
	AnchorPresetSchema,
	type AnimatableGlyphProps,
	AnimatableGlyphPropsSchema,
	type AnimatableProp,
	type AnimationTrack,
	type ArcLengthLUTEntry,
	type AudioSpectrumTypography,
	AudioSpectrumTypographySchema,
	applyStaggerToChildren,
	type BlockNode,
	type BloomConfig,
	BloomConfigSchema,
	type BoxNode,
	BoxNodeSchema,
	buildPathLUT,
	CameraAnimation,
	type CameraDoF,
	type CameraLens,
	type CameraNode,
	CameraNodeSchema,
	type CameraShake,
	type CarrierHandoffConfig,
	CarrierHandoffConfigSchema,
	type CarrierState,
	type ChromaticGlitchConfig,
	ChromaticGlitchConfigSchema,
	type ColorSignalOptions,
	type ColorStop,
	ColorStopSchema,
	type CompositorProgramConfig,
	CompositorProgramSchema,
	type CompositorToProgramOptions,
	type CubicBezierSegment,
	CubicBezierSegmentSchema,
	calculateSequenceTimeline,
	collectNodeOps,
	compositorToProgram,
	computeAnchorPivotOffset,
	computeCarrierContinuity,
	computeLayout,
	computeLayoutSync,
	computeLineLeadingDisplacement,
	computeRangeSelectorWeight,
	computeStaggerDelay,
	type DynamicStrokeProperties,
	DynamicStrokePropertiesSchema,
	deterministicWigglyNoise,
	distanceToCurveParameter,
	type EaseRef,
	type EnhancedTextNode,
	EnhancedTextNodeSchema,
	type EnvironmentFloor,
	EnvironmentFloorSchema,
	type EnvironmentFog,
	EnvironmentFogSchema,
	type EnvironmentGi,
	EnvironmentGiSchema,
	type EnvironmentPreset,
	EnvironmentPresetSchema,
	type EnvironmentSsr,
	EnvironmentSsrSchema,
	type EnvironmentVolumetricFog,
	type EnvironmentVolumetricFogNoise,
	EnvironmentVolumetricFogNoiseSchema,
	EnvironmentVolumetricFogSchema,
	type ExpressionEvaluationContext,
	type ExpressionSelector,
	ExpressionSelectorSchema,
	type ExtendedGlyphProperties,
	ExtendedGlyphPropertiesSchema,
	ellipseToCubicBeziers,
	evaluateAnimationAtFrame,
	evaluateCubicBezier,
	evaluateCubicBezierDerivative,
	evaluateExpressionSelector,
	evaluateMarqueeOffset,
	evaluateSelectorCombination,
	evaluateSkewMatrix,
	evaluateSpringProgress,
	evaluateTrackAtFrame,
	evaluateTypewriterState,
	evaluateVolumetricFormation,
	type FlexNode,
	FlexNodeSchema,
	type FromToOptions,
	type GeometryOutlineOptions,
	GeometryOutlineOptionsSchema,
	type GlyphAnchorGrouping,
	GlyphAnchorGroupingSchema,
	type GlyphAnchorPoint,
	GlyphAnchorPointSchema,
	generateArcLengthLUT,
	generatePathSegments,
	getScramblePool,
	getShuffledOrder,
	hoistMattes,
	type Keyframe,
	type KeyframeTuple,
	type KineticMarqueeConfig,
	KineticMarqueeConfigSchema,
	LayerAnimation,
	type LayoutNode,
	LayoutNodeSchema,
	type LightNode,
	LightNodeSchema,
	type LightType,
	LightTypeSchema,
	type LineSpacingDynamics,
	LineSpacingDynamicsSchema,
	type LongShadowConfig,
	LongShadowConfigSchema,
	lintComposition,
	type MaterialType,
	MaterialTypeSchema,
	type MatteMode,
	MatteModeSchema,
	type MediaNode,
	MediaNodeSchema,
	type Model3DNode,
	Model3DNodeSchema,
	mergeAnimationTracks,
	type ParticleDissolveConfig,
	ParticleDissolveConfigSchema,
	type PathChainLUT,
	type PathChainLUTEntry,
	parseSvgPathToCubicBeziers,
	Scene,
	type SceneDefinition,
	SceneDefinitionSchema,
	type SceneOptions,
	type SceneTransitionType,
	SceneTransitionTypeSchema,
	type SelectorBasedOn,
	SelectorBasedOnSchema,
	type SelectorMode,
	SelectorModeSchema,
	type SelectorShape,
	SelectorShapeSchema,
	type SelectorUnits,
	SelectorUnitsSchema,
	Sequence,
	type SequenceOptions,
	type SequenceTimelineResult,
	type ShapeNode,
	ShapeNodeSchema,
	type SignalTrackOptions,
	type SkewProperties,
	SkewPropertiesSchema,
	type Spatial3DProperties,
	Spatial3DPropertiesSchema,
	type SpringOptions,
	type SpringPhysics,
	SpringPhysicsSchema,
	sampleAudioSpectrumScale,
	sampleCurveGeometry,
	samplePathChainGeometry,
	type TextAnchorConfig,
	TextAnchorConfigSchema,
	TextAnimator,
	TextAnimatorBuilder,
	TextAnimatorSchema,
	type TextCursorConfig,
	TextCursorConfigSchema,
	type TextCursorStyle,
	TextCursorStyleSchema,
	type TextNode,
	TextNodeSchema,
	TextPathBuilder,
	type TextPathOptions,
	TextPathOptionsSchema,
	type TextPathSource,
	TextPathSourceSchema,
	type TextRangeSelector,
	TextRangeSelectorSchema,
	type TextScrambleConfig,
	TextScrambleConfigSchema,
	type TextSelector,
	TextSelectorSchema,
	type TextSignalSelector,
	TextSignalSelectorSchema,
	TextSpanMarkSchema,
	TextSpanSchema,
	type TextWigglySelector,
	TextWigglySelectorSchema,
	type ToneMapping,
	ToneMappingSchema,
	type ToonShading,
	ToonShadingSchema,
	type TrackSource,
	type TypewriterAnimator,
	TypewriterAnimatorSchema,
	type TypingCadence,
	TypingCadenceSchema,
	type VariableFontAxes,
	VariableFontAxesSchema,
	type Vec2,
	Vec2Schema,
	type VolumetricFormationConfig,
	VolumetricFormationConfigSchema,
	type VolumetricFormationMode,
	VolumetricFormationModeSchema,
	type WiggleOptions,
	waveToCubicBeziers,
} from "@framefields/compositions/program";
export * from "@framefields/core";
export * from "@framefields/renderers";
export type {
	AnimatablePropsFor,
	LightAnimatableProp,
	TextAnimatableProp,
	ShapeAnimatableProp,
	MediaAnimatableProp,
	Model3DAnimatableProp,
	SizeSpec,
};
export {
	type AnimationClip3D,
	type AudioLatentData,
	AudioLatentEngine,
	AudioLatentTrackCache,
	AudioMeshDeformPipeline,
	type BlendMode,
	type Bone3D,
	Camera3D,
	EffectPipeline,
	ensureDevice,
	GlassPipeline,
	type GPULightData,
	inputStore,
	Light3D,
	type Light3DOptions,
	type LoadModelOptions,
	loadFBX,
	loadModel3D,
	loadOBJ,
	lutStore,
	type Material3D,
	type Mesh3DData,
	type Model3DData,
	MotionBlurPipeline,
	type NodeAnimationTrack3D,
	Path3D,
	parseFBX,
	parseMTL,
	parseOBJ,
	type RenderContextValue,
	Renderer2D,
	Renderer3D,
	ShadowPipeline,
	type Skeleton3D,
	SlugFontCache,
	SlugPipeline,
	SSAOPipeline,
	shaderStore,
	textureCache,
	VolumetricFogPipeline,
} from "@framefields/webgpu-renderers";
export {
	type ChartAnimationOptions,
	type ChartAxisOptions,
	type ChartCandle,
	type ChartDatum,
	type ChartOptions,
	type ChartPadding,
	type ChartSeries,
	type ChartSlice,
	type ChartType,
	type ChartX,
	DEFAULT_CHART_COLORS,
} from "./chart.js";
export {
	ClipVision,
	type ClipVisionOptions,
	type PersonPlacement,
	PersonTrack,
	type PoseKeypointName,
} from "./clip-vision.js";
export type {
	AnyAudioEffect,
	AnyEffect,
	AnyVisualEffect,
	EffectConfigMap,
	EffectOp,
	EffectPropsFor,
} from "./effects/index.js";
export {
	ApplyLUT,
	type ApplyLUTProps,
	Ascii,
	type AsciiProps,
	AudioCompressor,
	type AudioCompressorProps,
	AudioDelay,
	type AudioDelayProps,
	AudioFade,
	type AudioFadeProps,
	AudioNoiseGate,
	type AudioNoiseGateProps,
	AudioParametricEq,
	type AudioParametricEqProps,
	AudioReverb,
	type AudioReverbProps,
	AudioSignalExtractor,
	type AudioSignalExtractorProps,
	Blur,
	type BlurProps,
	CameraParallax3D,
	type CameraParallax3DProps,
	ChannelMerger,
	type ChannelMergerProps,
	ChannelSplitter,
	type ChannelSplitterProps,
	ColorBalance,
	type ColorBalanceProps,
	ColorKey,
	type ColorKeyProps,
	Contour,
	type ContourProps,
	CornerPin,
	type CornerPinProps,
	CRT,
	type CRTProps,
	Crop,
	type CropProps,
	Curves,
	type CurvesChannelPoint,
	type CurvesProps,
	CustomEffect,
	Datamosh,
	type DatamoshProps,
	type DeflickerProps,
	DepthOfField,
	type DepthOfFieldProps,
	DisplacementMap,
	type DisplacementMapProps,
	Dither,
	type DitherProps,
	ExtractLUT,
	type ExtractLUTProps,
	effectFactories,
	effectMeta,
	FilmGrain,
	type FilmGrainProps,
	Flip,
	type FlipProps,
	Gooey,
	type GooeyProps,
	GradientMap,
	type GradientMapProps,
	type GradientMapStop,
	type HalftoneDotShape,
	type HalftoneMode,
	HalftoneScreen,
	type HalftoneScreenProps,
	HighPass,
	type HighPassProps,
	Iridescence,
	type IridescenceProps,
	Kaleidoscope,
	type KaleidoscopeProps,
	KenBurns,
	type KenBurnsProps,
	LayerStyle,
	type LayerStyleProps,
	type LevelChannel,
	Levels,
	type LevelsProps,
	Liquify,
	type LiquifyProps,
	MaskMath,
	type MaskMathProps,
	MeshWarp,
	type MeshWarpProps,
	Modulate,
	type ModulateProps,
	MotionBlur,
	type MotionBlurProps,
	NoiseGenerator,
	type NoiseGeneratorProps,
	OpArt,
	type OpArtProps,
	Paint,
	Painterly,
	type PainterlyProps,
	type PaintProps,
	PatchHeal,
	type PatchHealProps,
	PBRGlass,
	type PBRGlassProps,
	Pixelate,
	type PixelateProps,
	Posterize,
	type PosterizeProps,
	ProceduralVFX,
	type ProceduralVFXProps,
	RefineEdge,
	type RefineEdgeProps,
	RefractionCaustics3D,
	type RefractionCaustics3DProps,
	Relight3D,
	type Relight3DProps,
	ResizerScaler,
	type ResizerScalerProps,
	RGBSplit,
	type RGBSplitProps,
	Rotate,
	type RotateProps,
	SelectiveColor,
	type SelectiveColorAdjustment,
	type SelectiveColorProps,
	ShadowsHighlights,
	type ShadowsHighlightsProps,
	SSAO,
	type SSAOProps,
	StereoPanning,
	type StereoPanningProps,
	TemporalDeflicker,
	TileOffset,
	type TileOffsetEdgeMode,
	type TileOffsetProps,
	Toon,
	type ToonProps,
	Trails,
	type TrailsProps,
	UnsharpMask,
	type UnsharpMaskProps,
	Vignette,
	type VignetteProps,
	Vision,
	type VisionProps,
} from "./effects/index.js";
export {
	Lighting,
	type LightingRig,
	type LightingRigOptions,
} from "./lighting.js";
export {
	type EmitterShape,
	type ParticleBlend,
	type ParticleBounds,
	type ParticleShape,
	Particles,
	type ParticlesOptions,
} from "./particles.js";
export {
	type Body2DOptions,
	type Body3DOptions,
	type BodyCommonOptions,
	type FieldSample2D,
	type FieldSample3D,
	Fracture3D,
	type Fracture3DOptions,
	Physics,
	type PhysicsBakeOptions,
	PhysicsBody2D,
	PhysicsBody3D,
	type PhysicsBox3D,
	type PhysicsCollision,
	type PhysicsDriver,
	type PhysicsGroundOptions,
	type PhysicsRect,
	type PhysicsRope3DOptions,
	type PhysicsRopeOptions,
	type PhysicsSpring3DOptions,
	type PhysicsSpringOptions,
	type PhysicsWallsOptions,
	PhysicsWorld2D,
	PhysicsWorld3D,
	type PhysicsWorldOptions,
	type World2DOptions,
	type World3DOptions,
} from "./physics/index.js";
export {
	type Capsule3DOptions,
	type Carousel3DOptions,
	type Cube3DOptions,
	type CubeFaceConfig,
	type CubeFaceInput,
	type Cylinder3DOptions,
	type ExtrudedText3DOptions,
	type ExtrudeShape3DOptions,
	type Grid3DOptions,
	type Icosphere3DOptions,
	type Instances3DOptions,
	type InstanceTransform3D,
	type Lathe3DOptions,
	Layer3D,
	type Line3DOptions,
	type Plane3DOptions,
	type Points3DOptions,
	type Polyhedron3DOptions,
	type Primitive3DNodeOptions,
	type Prism3DOptions,
	type Pyramid3DOptions,
	type Ring3DOptions,
	type RoundedBox3DOptions,
	type Shape3DContainer,
	type Shard3DOptions,
	type SolidShape3DNode,
	type Sphere3DOptions,
	type Surface3DOptions,
	type Text3DOptions,
	type Torus3DOptions,
	type Tube3DOptions,
} from "./shapes3d.js";

import { scatterCoverage } from "./procedural3d.js";

export type {
	AimConstraint,
	CrowdConfig,
	JointPose,
	LookAtConstraint,
	ModelAnimationLayer,
	NumberTrack,
	SpringBoneChain,
	TrackSignal,
	TwoBoneIkConstraint,
	Vec3Track,
	WindConfig,
} from "@framefields/compositions/program";
export type {
	ScatterPoint,
	SdfPrimitive,
	TerrainColorByElevation,
	TerrainNoiseOptions,
} from "@framefields/webgpu-renderers";
export type {
	Scatter3DNode,
	Scatter3DOptions,
	Sdf3DOptions,
	Terrain3DNode,
	Terrain3DOptions,
	TerrainSurface,
} from "./procedural3d.js";
export {
	type PoseSource,
	type RetargetBone,
	type RetargetOptions,
	RIG_PRESETS,
	type RigMap,
	retargetPose,
} from "./retarget.js";
export { type StyleName, Styles } from "./styles.js";
export type { Swarm3DOptions } from "./swarm3d.js";
export {
	type SceneSequenceOptions,
	type SequenceEntry,
	type SequenceNode,
	Transition,
	type TransitionDirection,
	type TransitionSpec,
} from "./transitions.js";

export interface CompositionOptions {
	width: number;
	height: number;
	fps?: number;
	durationMs?: number;
	durationFrames?: number;
	backgroundColor?: string;
	fonts?: string[];
	signals?: Record<string, unknown>;
	/**
	 * Smooth the edges of 3D meshes (extruded text, models) with 4x MSAA.
	 * Default true; set false to save ~60-125 MB of GPU memory at 1080p.
	 */
	antialias3d?: boolean;
}

/**
 * Fluent builder for single clips and chained visual/audio effect pipelines.
 */
export class Media {
	public readonly virtualMedia: VirtualMediaData;

	constructor(source: MediaSourceInput, type: DataType = "Video") {
		this.virtualMedia = createVirtualMedia(source, type);
	}

	static video(source: MediaSourceInput, meta?: Partial<MediaMetadata>): Media {
		const m = new Media(source, "Video");
		if (meta) Object.assign(m.virtualMedia.metadata, meta);
		return m;
	}

	static image(source: MediaSourceInput, meta?: Partial<MediaMetadata>): Media {
		const m = new Media(source, "Image");
		if (meta) Object.assign(m.virtualMedia.metadata, meta);
		return m;
	}

	static lottie(
		source: MediaSourceInput,
		meta?: Partial<MediaMetadata>,
	): Media {
		const m = new Media(source, "Lottie");
		if (meta) Object.assign(m.virtualMedia.metadata, meta);
		return m;
	}

	static audio(source: MediaSourceInput, meta?: Partial<MediaMetadata>): Media {
		const m = new Media(source, "Audio");
		if (meta) Object.assign(m.virtualMedia.metadata, meta);
		return m;
	}

	/**
	 * Appends any Effect instance or shader operation onto the current media AST.
	 */
	public apply<TProps extends object>(effect: Effect<TProps>): Media;
	public apply<
		TConfig extends Record<string, unknown> = Record<string, unknown>,
	>(op: string, config?: TConfig): Media;
	public apply(
		effectOrOp: Effect<object> | string,
		config: Record<string, unknown> = {},
	): Media {
		let opPayload: Record<string, unknown>;
		if (
			effectOrOp instanceof Effect ||
			(typeof effectOrOp === "object" &&
				effectOrOp !== null &&
				"op" in effectOrOp)
		) {
			opPayload = (effectOrOp as Effect<object>).toOperation();
		} else {
			opPayload = {
				op: effectOrOp,
				...config,
			};
		}

		const nextVM = appendOperation(this.virtualMedia, {
			...opPayload,
			dataType: this.virtualMedia.operation.dataType,
		} as MediaOperation);
		return new Media(nextVM);
	}

	/**
	 * Returns the underlying VirtualMediaData AST node ready for rendering.
	 */
	public toVirtualMedia(): VirtualMediaData {
		return this.virtualMedia;
	}

	/**
	 * Renders a single frame from this media pipeline to an image or raw RGBA Buffer.
	 * Can render either by timestamp in milliseconds (`atMs`) or by frame index (`frame`).
	 */
	public async renderFrame(
		options: {
			atMs?: number;
			frame?: number;
			fps?: number;
			renderId?: string;
			format?: "png" | "rgba" | "raw" | "jpeg" | "jpg" | "webp";
			renderer?: HeadlessMediaRenderer;
		} = {},
	): Promise<Buffer> {
		const renderer = options.renderer ?? new HeadlessMediaRenderer();
		return renderer.renderFrame(this.virtualMedia, options);
	}

	get fps(): number | undefined {
		return this.virtualMedia.metadata?.fps ?? undefined;
	}

	get durationMs(): number | undefined {
		return this.virtualMedia.metadata?.durationMs ?? undefined;
	}

	get width(): number | undefined {
		return this.virtualMedia.metadata?.width ?? undefined;
	}

	get height(): number | undefined {
		return this.virtualMedia.metadata?.height ?? undefined;
	}

	/**
	 * Renders an image grid of sequential frames across a given frame or millisecond range.
	 * Ideal for automated visual inspection of animation motion, easing curves, and layout stability.
	 */
	public async renderFrameGrid(
		options: FrameGridOptions = {},
	): Promise<Buffer> {
		return renderFrameGrid(this, options);
	}

	/**
	 * Renders this media pipeline into an MP4/WebM video file with audio.
	 */
	public async renderVideo(
		outputPathOrOptions: string | RenderVideoOptions = {},
		options: RenderVideoOptions = {},
	): Promise<RenderVideoResult> {
		const opts =
			typeof outputPathOrOptions === "string"
				? { ...options, outputPath: outputPathOrOptions }
				: outputPathOrOptions;
		const renderer = opts.renderer ?? new HeadlessMediaRenderer();
		const result = await renderer.renderVideo(this.virtualMedia, opts);
		return deliverToOutputPath(result, opts.outputPath);
	}
}

/**
 * Copies a rendered temp file to `outputPath` and drops the temp, so the
 * returned `filePath` is where the video actually lives.
 */
async function deliverToOutputPath(
	result: RenderVideoResult,
	outputPath: string | undefined,
): Promise<RenderVideoResult> {
	if (!outputPath) return result;
	const target = path.resolve(outputPath);
	await fs.mkdir(path.dirname(target), { recursive: true });
	await fs.copyFile(result.filePath, target);
	await result.cleanup();
	return { ...result, filePath: target, cleanup: async () => {} };
}

export interface RenderVideoOptions {
	codec?: string;
	audioCodec?: string;
	quality?: string;
	concurrency?: number;
	/**
	 * Depth of the DMA staging ring used to overlap GPU rendering with hardware
	 * encoding (default 2, clamped 2–8). A deeper ring hides more encoder
	 * latency at the cost of VRAM (~8.3MB/slot at 1080p RGBA). Also settable
	 * via `FRAMEFIELDS_RING_CAPACITY`.
	 */
	ringCapacity?: number;
	outputPath?: string;
	renderer?: HeadlessMediaRenderer;
	/**
	 * Check the output while it renders and return the findings as `qa`:
	 * dropped, black or frozen frames, loudness (LUFS), clipping, silence and
	 * document warnings such as truncated animations. `true` uses defaults;
	 * pass thresholds (e.g. `{ targetLufs: -14 }`) to tighten them.
	 */
	qa?: boolean | VideoQaOptions;
	/**
	 * Stops the render between frames. The promise rejects with
	 * `signal.reason` and no file is left behind.
	 */
	signal?: AbortSignal;
	/**
	 * Called as the render moves through its phases: "prepare", each frame
	 * ("render"), "audio" (per clip mixed), "audio-encode", "mux", "convert"
	 * (GIF only) and "done". The engine logs the same phases on its own.
	 */
	onProgress?: (progress: RenderProgress) => void;
	/**
	 * Renders only frames `start` (inclusive) to `end` (exclusive): one chunk
	 * of a render split across workers. Chunks start on a keyframe with
	 * timestamps from 0; join them with `stitchChunks` from
	 * `framefields/renderer`. Effects that carry state between frames
	 * (trails, particles, datamosh) rebuild it before `start`.
	 */
	frames?: { start: number; end: number };
	/**
	 * `false` writes no audio track, as for chunks: render the timeline's
	 * audio once with `codec: "aac"` and pass it to `stitchChunks`.
	 */
	audio?: boolean;
}

export interface RenderVideoResult {
	filePath: string;
	cleanup: () => Promise<void>;
	/** Present when rendered with `qa`; print it with `formatQaReport` */
	qa?: VideoQaReport;
}

export interface SubjectSandwichOptions {
	readonly source: string | MediaNode;
	readonly subject?: MaskTrackSignals | ObjectTrackSignals;
	readonly behind: readonly LayoutNode[];
	readonly feather?: number;
	readonly fit?: "cover" | "contain" | "fill";
	readonly variant?: VisionProps["variant"];
	readonly confidence?: number;
	readonly keyBackground?: boolean;
	readonly backgroundKeyThreshold?: number;
	readonly muted?: boolean;
	readonly volume?: number;
}

export interface SmartFramingOptions {
	readonly source: string | MediaNode;
	readonly targetAspect?: number;
	readonly sourceAspect?: number;
	readonly target: ObjectTrackSignals | MaskTrackSignals;
	readonly damping?: number;
	readonly leadHeadroom?: number;
	readonly fit?: "cover" | "contain" | "fill";
	readonly variant?: VisionProps["variant"];
	readonly muted?: boolean;
	readonly volume?: number;
}

export interface SubjectOutlineOptions {
	readonly source?: string | MediaNode;
	readonly color?: string;
	readonly width?: number;
	readonly blur?: number;
	readonly pulseSignal?: ProgrammaticSignal | Signal<number>;
	readonly muted?: boolean;
	readonly volume?: number;
}

/**
 * High-level programmatic builder for multi-layer Framefields compositions.
 */
export class Composition {
	public width: number;
	public height: number;
	public fps: number;
	public durationMs?: number;
	public backgroundColor: string;
	public antialias3d?: boolean;
	public fonts: string[];
	public children: LayoutNode[] = [];
	public audioTracks: MediaNode[] = [];
	public signals: Record<string, unknown> = {};
	private _frameHooks: Array<(ctx: FrameContext) => void> = [];
	private _prepareHooks: Array<(ctx: FrameContext) => Promise<void> | void> =
		[];
	private readonly _clipVision = new Map<string, ClipVision>();
	private _linking = false;
	private _mediaSignals?: MediaSignalTimeline;
	private _visionConfig?: VisionProps;
	private _visionBundle?: VisionBundle;
	private _effects: AnyEffect[] = [];

	/**
	 * Applies a whole-composition post-processing effect or vision pipeline.
	 */
	public apply(effect: AnyEffect): this {
		if (effect instanceof Vision) {
			this.withVision(effect);
			return this;
		}
		this._effects.push(effect);
		return this;
	}

	/**
	 * Runs vision on the whole composition — the rendered frame (composition, blur, crop,
	 * anything upstream) is the inference input. Models are LAZY: nothing downloads until
	 * the first frame actually runs a task.
	 * Returns the reactive VisionBundle (objects / masks / pose / classes signals).
	 */
	public withVision(config: VisionProps | Vision = {}): VisionBundle {
		this._visionBundle ??= new VisionBundle({
			width: this.width,
			height: this.height,
			fps: this.fps,
		});
		const rawConfig =
			config instanceof Vision ? (config.config as VisionProps) : config;
		this._visionConfig = {
			...rawConfig,
			visionBundle: this._visionBundle,
		};
		return this._visionBundle;
	}

	/**
	 * Vision for a clip, analysed per frame on demand and shared by everything
	 * that reads it (see {@link ClipVision}): `comp.vision("dancer.mp4").person`
	 * gives pose keypoints and a silhouette at any frame. Each frame is
	 * analysed just before it renders, so nothing runs up front. Results
	 * persist on disk in Node. The same clip and options return one instance.
	 */
	public vision(
		sourceOrLayer: string | MediaNode,
		options: ClipVisionOptions = {},
	): ClipVision {
		const source =
			typeof sourceOrLayer === "string"
				? sourceOrLayer
				: (sourceOrLayer.src ?? sourceOrLayer.inputHandleId);
		if (typeof sourceOrLayer !== "string") {
			// A clip is analysed frame by frame, so its signal time is live.
			const vm = this.toVirtualMedia({
				resolveMediaSignal: this.mediaSignalResolver(true),
			});
			// Layers inside a 3D scene count too, with their start on this clock.
			const found = collectLayersOnClock(vm.children).find(
				({ vm: node }) =>
					(node.operation as unknown as { id?: string }).id ===
					sourceOrLayer.id,
			);
			const layer = found && {
				operation: { ...found.vm.operation, startFrame: found.startFrame },
			};
			if (!layer)
				throw new Error(
					"Add the media layer to the composition before calling comp.vision(layer)",
				);
			options = {
				startFrame: layer.operation.startFrame ?? sourceOrLayer.startFrame,
				trimStartSec: sourceOrLayer.trimStartSec,
				timeRemap: (
					layer.operation as unknown as { timeRemap?: ResolvedMediaTimeRemap }
				).timeRemap,
				durationFrames: sourceOrLayer.durationFrames,
				...options,
			};
		}
		const key = `${source}\u0000${JSON.stringify({ ...options, timeRemap: remapKey(options.timeRemap) })}`;
		let clip = this._clipVision.get(key);
		if (!clip) {
			clip = new ClipVision(source, this.fps, options);
			this._clipVision.set(key, clip);
		}
		return clip;
	}

	/**
	 * @internal Analyses every `comp.vision` clip up to a composition frame
	 * (frames already analysed are skipped), so consumers that step frame by
	 * frame — physics, particles — always find every frame before it.
	 */
	public async prepareVision(frame: number): Promise<void> {
		this.linkClipLayers();
		await Promise.all(
			[...this._clipVision.values()].map((clip) => clip.ready(0, frame)),
		);
	}

	/**
	 * Points matte-family, skeleton and depth `withVision` layers at the
	 * `comp.vision` clip they show, so the cutout reuses that clip's per-frame
	 * subject, the skeleton draws its matched pose and the depth layer its
	 * frame's depth, instead of analysing the frame again during render. Only layers whose settings would give the same subject are
	 * linked; the rest keep their own pass.
	 */
	private linkClipLayers(): void {
		let layers:
			| Map<
					string | undefined,
					{ startFrame?: number; timeRemap?: ResolvedMediaTimeRemap }
			  >
			| undefined;
		const walk = (node: unknown): void => {
			if (!node || typeof node !== "object") return;
			const n = node as {
				id?: string;
				kind?: string;
				dataType?: string;
				inputHandleId?: unknown;
				src?: string;
				startFrame?: number;
				trimStartSec?: number;
				vision?: unknown;
				children?: unknown;
				matte?: { node?: unknown };
				relief?: { node?: unknown };
			};
			if (
				n.kind === "media" &&
				n.dataType === "Video" &&
				typeof n.inputHandleId === "string" &&
				n.vision instanceof Vision &&
				!(CLIP_SUBJECT in n.vision)
			) {
				// Scenes' layers too: a layer inside a 3D scene starts on the
				// scene's clock, and its clip must analyse on this one.
				layers ??= new Map(
					collectLayersOnClock(this.toVirtualMedia().children).map(
						({ vm, startFrame }) => {
							const op = vm.operation as unknown as {
								id?: string;
								timeRemap?: ResolvedMediaTimeRemap;
							};
							return [op.id, { startFrame, timeRemap: op.timeRemap }];
						},
					),
				);
				const layer = layers.get(n.id);
				const clip = this.clipForLayer(n.src ?? n.inputHandleId, n.vision, {
					trimStartSec: n.trimStartSec,
					startFrame: layer?.startFrame ?? n.startFrame,
					timeRemap: layer?.timeRemap,
				});
				if (clip) {
					if (n.vision.mode !== "skeleton" && n.vision.mode !== "depth")
						clip.keepSubjects();
					Object.defineProperty(n.vision, CLIP_SUBJECT, {
						value: clip,
						enumerable: false,
						configurable: true,
					});
				}
			}
			if (Array.isArray(n.children)) for (const c of n.children) walk(c);
			// Companion layers (a matte, a relief) can show a clip too.
			walk(n.matte?.node);
			walk(n.relief?.node);
		};
		for (const child of this.children) walk(child);
	}

	/** The `comp.vision` clip a matte or skeleton layer of the same source reads instead of analysing. */
	private clipForLayer(
		source: string,
		v: Vision,
		layer: {
			startFrame?: number;
			trimStartSec?: number;
			timeRemap?: ResolvedMediaTimeRemap;
		},
	): ClipVision | undefined {
		const mode = v.mode ?? "passthrough";
		if (mode === "depth") return this.depthClip(source, layer);
		const skeleton = mode === "skeleton";
		if (mode !== "matte" && mode !== "mask" && mode !== "crop" && !skeleton)
			return;
		// Anything that changes the subject, or needs results the clip lacks.
		if (
			v.classes !== undefined ||
			v.enableMatte === true ||
			v.visionBundle !== undefined ||
			(!skeleton &&
				(v.matteSource === "selfie" ||
					v.keyBackground === true ||
					v.enablePose === true ||
					(v.maskThreshold ?? 0.5) !== 0.5 ||
					v.featherRadius !== undefined))
		) {
			return;
		}
		for (const clip of this._clipVision.values()) {
			const o = clip.options;
			if (
				clip.source === source &&
				clip.startFrame === (layer.startFrame ?? 0) &&
				clip.trimStartSec === (layer.trimStartSec ?? 0) &&
				remapKey(o.timeRemap) === remapKey(layer.timeRemap) &&
				(o.variant ?? "s") === (v.variant ?? "s") &&
				(o.confidence ?? 0.3) === (v.confidence ?? 0.3)
			) {
				// A skeleton of a selected person must draw that person, never whoever is detected first.
				if (skeleton && !clip.tracksPose) {
					if (clip.exact)
						throw new Error(
							"A skeleton layer of a prompted comp.vision clip needs `pose: true` on that clip.",
						);
					continue;
				}
				return clip;
			}
		}
		return undefined;
	}

	/**
	 * The clip a depth layer reads: one of the same source and timing that
	 * tracks depth, or a new depth clip, since depth is never analysed at render
	 * time (it would trail the picture by a frame).
	 */
	private depthClip(
		source: string,
		layer: {
			startFrame?: number;
			trimStartSec?: number;
			timeRemap?: ResolvedMediaTimeRemap;
		},
	): ClipVision {
		for (const clip of this._clipVision.values()) {
			if (
				clip.tracksDepth &&
				clip.source === source &&
				clip.startFrame === (layer.startFrame ?? 0) &&
				clip.trimStartSec === (layer.trimStartSec ?? 0) &&
				remapKey(clip.options.timeRemap) === remapKey(layer.timeRemap)
			)
				return clip;
		}
		return this.vision(source, {
			depth: true,
			...(layer.startFrame !== undefined && { startFrame: layer.startFrame }),
			...(layer.trimStartSec !== undefined && {
				trimStartSec: layer.trimStartSec,
			}),
			...(layer.timeRemap !== undefined && { timeRemap: layer.timeRemap }),
		});
	}

	/**
	 * One-shot, ffmpeg-free vision analysis of a media source.
	 *
	 * Decodes frames through the same mediabunny pipeline the renderer uses, runs the requested
	 * tasks lazily (only those models download), temporally tracks detections, and returns a
	 * zod-serializable report. The decoder is released and the runner closed on completion.
	 */
	public async analyzeVisionSequence(
		source: string,
		options: {
			tasks?: readonly VisionTask[];
			categories?: readonly string[];
			fps?: number;
			totalFrames?: number;
			pathStride?: number;
			includeMasks?: boolean;
			modelsDir?: string;
			baseUrl?: string;
			confidence?: number;
			variant?: VisionProps["variant"];
			/** Tracker box-association IoU. Default 0.25. */
			iouThreshold?: number;
		} = {},
	): Promise<VisionAnalysisReport> {
		const fps = options.fps ?? this.fps;
		const durationMs = this.durationMs ?? (await this.computeDuration());
		const totalFrames =
			options.totalFrames ?? Math.max(1, Math.round((durationMs / 1000) * fps));

		const runner = VisionRunner.create({
			modelsDir: options.modelsDir,
			baseUrl: options.baseUrl,
			...(options.confidence !== undefined
				? { confidence: options.confidence }
				: {}),
			...(options.variant !== undefined ? { variant: options.variant } : {}),
		});

		const decoder = mediaDecoderCache.getVideo(source, true);
		async function* frameSource(): AsyncGenerator<{
			data: Uint8Array;
			width: number;
			height: number;
		}> {
			for (let i = 0; i < totalFrames; i++) {
				const frame = await decoder.getFrame(i / fps);
				if (frame?.buffer && frame.width > 0 && frame.height > 0) {
					yield {
						data: frame.buffer,
						width: frame.width,
						height: frame.height,
					};
				}
			}
		}

		try {
			return await analyzeVisionFrames(frameSource(), {
				runner,
				source,
				fps,
				...(options.tasks !== undefined ? { tasks: options.tasks } : {}),
				...(options.categories !== undefined
					? { categories: options.categories }
					: {}),
				...(options.pathStride !== undefined
					? { pathStride: options.pathStride }
					: {}),
				...(options.includeMasks !== undefined
					? { includeMasks: options.includeMasks }
					: {}),
				...(options.iouThreshold !== undefined
					? { iouThreshold: options.iouThreshold }
					: {}),
			});
		} finally {
			runner.close();
			decoder.destroy();
		}
	}

	/**
	 * Game-engine per-frame lifecycle hook for the composition.
	 * Invoked before rendering each frame so scripts or agents can mutate properties and signals.
	 */
	public onRequestFrame(callback: (ctx: FrameContext) => void): this {
		this._frameHooks.push(callback);
		return this;
	}

	/**
	 * Async work a frame needs before it is evaluated (vision, a live physics
	 * world). Every render path awaits these, in order, before drawing the
	 * frame; they may run more than once per frame, so keep them idempotent.
	 */
	public onPrepareFrame(
		callback: (ctx: FrameContext) => Promise<void> | void,
	): this {
		this._prepareHooks.push(callback);
		return this;
	}

	public notifyFrame(ctx: FrameContext): Promise<void> | undefined {
		const skipped = this._mediaSignals?.framesBefore(ctx.frame) ?? [];
		if (skipped.length === 0) return this.runFrame(ctx);
		// Live signal time has no gaps: a seek forward runs the frames it skips.
		return (async () => {
			for (const frame of skipped)
				await this.runFrame(contextAtFrame(ctx, frame));
			await this.runFrame(ctx);
		})();
	}

	private runFrame(ctx: FrameContext): Promise<void> | undefined {
		for (const hook of this._frameHooks) {
			hook(ctx);
		}
		const signals = this._mediaSignals;
		signals?.advance(ctx.frame);
		// Depth layers bring their own clip, so links come before the check.
		this.linkClipLayers();
		if (this._clipVision.size === 0 && this._prepareHooks.length === 0) {
			signals?.reach(ctx.frame);
			return undefined;
		}
		return (async () => {
			await this.prepareVision(ctx.frame);
			for (const hook of this._prepareHooks) await hook(ctx);
			signals?.reach(ctx.frame);
		})();
	}

	/**
	 * @internal Runs the frame clock through the last frame while a live
	 * signal `timeRemap` history is incomplete, so audio can be mixed before
	 * any frame renders (the preview does). Compile the composition first.
	 */
	public async prepareMediaTime(): Promise<void> {
		const durationMs = this.durationMs ?? (await this.computeDuration());
		const last = Math.round((durationMs / 1000) * this.fps) - 1;
		if (!this._mediaSignals?.pending || last < 0) return;
		await this.notifyFrame(
			contextAtFrame(
				{
					frame: 0,
					fps: this.fps,
					time: 0,
					duration: durationMs / 1000,
					durationMs,
					progress: 0,
					deltaTime: 1 / this.fps,
				},
				last,
			),
		);
	}

	/**
	 * Resolves signal `timeRemap`s to one shared history per layer: sampled
	 * when nothing can change a signal mid-render, recorded live otherwise.
	 */
	private mediaSignalResolver(
		live = this.hasFrameHooks(),
		durationMs = this.durationMs,
		signals = this.signals,
	): MediaSignalResolver {
		this._mediaSignals ??= new MediaSignalTimeline(this.fps);
		return this._mediaSignals.resolver({
			live,
			compositionDurationFrames: Math.round(
				((durationMs ?? 0) / 1000) * this.fps,
			),
			signals,
		});
	}

	private hasFrameHooks(): boolean {
		return (
			this._frameHooks.length > 0 ||
			this._prepareHooks.length > 0 ||
			this._clipVision.size > 0
		);
	}

	constructor(options: CompositionOptions) {
		this.width = options.width;
		this.height = options.height;
		this.fps = options.fps ?? 60;
		this.durationMs =
			options.durationMs ??
			(options.durationFrames !== undefined
				? (options.durationFrames / this.fps) * 1000
				: undefined);
		this.backgroundColor = options.backgroundColor ?? "#000000";
		this.antialias3d = options.antialias3d;
		this.fonts = options.fonts ?? [];
		this.signals = options.signals ?? {};
	}

	public static create(options: CompositionOptions): Composition {
		return new Composition(options);
	}

	public addSignal(name: string, signal: unknown): this {
		this.signals[name] = signal;
		return this;
	}

	public add(
		layerOrFirst:
			| LayoutNode
			| LayoutNode[]
			| TensorPipeline
			| VisionNode
			| { node: unknown },
		...rest: Array<
			| LayoutNode
			| LayoutNode[]
			| TensorPipeline
			| VisionNode
			| { node: unknown }
			| LayerAnimation
			| { tracks: AnimationTrack[] }
		>
	): this {
		if (layerOrFirst instanceof TensorPipeline) {
			this.children.push(layerOrFirst.toNode() as unknown as LayoutNode);
		} else if (layerOrFirst instanceof VisionNode) {
			this.children.push(layerOrFirst.toNode() as unknown as LayoutNode);
		} else if (
			layerOrFirst &&
			typeof layerOrFirst === "object" &&
			"node" in layerOrFirst
		) {
			this.add(
				(
					layerOrFirst as {
						node: LayoutNode | TensorPipeline | { node: unknown };
					}
				).node as LayoutNode,
				...rest,
			);
			return this;
		} else if (Array.isArray(layerOrFirst)) {
			for (const l of layerOrFirst) {
				this.add(l);
			}
		} else {
			const targetNode = layerOrFirst as LayoutNode;
			const animCandidate = rest[0];
			if (
				animCandidate &&
				!(animCandidate instanceof TensorPipeline) &&
				!Array.isArray(animCandidate) &&
				(animCandidate instanceof LayerAnimation || "tracks" in animCandidate)
			) {
				targetNode.animation =
					animCandidate instanceof LayerAnimation
						? animCandidate.toSpec()
						: animCandidate;
				this.children.push(targetNode);
				return this;
			}
			this.children.push(targetNode);
		}

		for (const item of rest) {
			if (item && !(item instanceof LayerAnimation) && !("tracks" in item)) {
				this.add(
					item as
						| LayoutNode
						| LayoutNode[]
						| TensorPipeline
						| { node: unknown },
				);
			}
		}

		return this;
	}

	public addAudio(track: MediaNode): this {
		this.audioTracks.push(track);
		return this;
	}

	/**
	 * Turnkey "Text Behind Subject" ("Sandwich") Primitive.
	 * Lowers into:
	 * 1. Bottom Layer: Full background video plate
	 * 2. Middle Layer: User-supplied `behind` nodes
	 * 3. Top Layer: Subject cutout video with continuous matte alpha registered at identical coordinates
	 */
	public addSubjectSandwich(options: SubjectSandwichOptions): this {
		const src =
			typeof options.source === "string"
				? options.source
				: (options.source.inputHandleId ?? "");
		const fit = options.fit ?? "cover";
		const feather = options.feather ?? 4;
		const featherVal = feather > 1 ? feather / 100 : feather;
		const variant = options.variant ?? "s";

		// 1. Bottom Layer: Full background video plate
		const bottomPlate = Layer.video(src, {
			width: this.width,
			height: this.height,
			position: "absolute",
			x: 0,
			y: 0,
			fit,
			muted: options.muted ?? false,
			volume: options.muted ? 0 : (options.volume ?? 1),
		});
		this.add(bottomPlate);

		// 2. Middle Layer: User-supplied `behind` nodes
		for (const node of options.behind) {
			this.add(node);
		}

		// 3. Top Layer: Subject cutout video with continuous matte alpha registered at identical coordinates
		const topPlate = Layer.video(src, {
			width: this.width,
			height: this.height,
			position: "absolute",
			x: 0,
			y: 0,
			fit,
			muted: true,
			volume: 0,
		}).withVision({
			mode: "matte",
			enableSegmentation: true,
			variant,
			confidence: options.confidence ?? 0.25,
			featherRadius: featherVal,
			keyBackground: options.keyBackground ?? true,
			backgroundKeyThreshold: options.backgroundKeyThreshold,
		});
		this.add(topPlate);

		return this;
	}

	/**
	 * Dynamic Smart Re-Framing (16:9 → 9:16 Auto-Crop).
	 * Automatically transforms landscape footage into vertical shorts/reels by framing the
	 * tracked subject with smooth camera physics and lead headroom.
	 */
	public addSmartFraming(options: SmartFramingOptions): this {
		const src =
			typeof options.source === "string"
				? options.source
				: (options.source.inputHandleId ?? "");
		const damping = Math.max(0, Math.min(0.99, options.damping ?? 0.8));
		const headroom = options.leadHeadroom ?? 0.18;
		const compW = this.width;
		const compH = this.height;

		const sourceAspect = options.sourceAspect ?? 16 / 9;
		const compAspect = compW / compH;

		// Calculate canvas coverage dimensions to avoid black bars during pan
		const plateWidth =
			compAspect < sourceAspect ? Math.round(compH * sourceAspect) : compW;
		const plateHeight =
			compAspect < sourceAspect ? compH : Math.round(compW / sourceAspect);

		const minOffsetX = compW - plateWidth; // <= 0
		const minOffsetY = compH - plateHeight; // <= 0

		const targetObj = options.target as unknown as {
			center?: {
				x?: ProgrammaticSignal;
				y?: ProgrammaticSignal;
				screenX?: ProgrammaticSignal;
				screenY?: ProgrammaticSignal;
			};
			bounds?: {
				x?: ProgrammaticSignal;
				y?: ProgrammaticSignal;
				width?: ProgrammaticSignal;
				height?: ProgrammaticSignal;
				centerX?: ProgrammaticSignal;
				centerY?: ProgrammaticSignal;
			};
		};

		const rawOffsetX = new ProgrammaticSignal(
			(ctx) => {
				if (minOffsetX >= 0) return 0;
				const normX = targetObj.center?.x
					? targetObj.center.x.get(ctx)
					: targetObj.bounds?.centerX
						? targetObj.bounds.centerX.get(ctx) / compW
						: targetObj.center?.screenX
							? targetObj.center.screenX.get(ctx) / compW
							: 0.5;
				const clampedNormX = Math.max(0, Math.min(1, normX));
				const targetPx = clampedNormX * plateWidth;
				const desired = compW / 2 - targetPx;
				return Math.max(minOffsetX, Math.min(0, desired));
			},
			{ fps: this.fps, label: "smart_framing_pan_x" },
		);

		const rawOffsetY = new ProgrammaticSignal(
			(ctx) => {
				if (minOffsetY >= 0) return 0;
				const normY = targetObj.center?.y
					? targetObj.center.y.get(ctx)
					: targetObj.bounds?.centerY
						? targetObj.bounds.centerY.get(ctx) / compH
						: targetObj.center?.screenY
							? targetObj.center.screenY.get(ctx) / compH
							: 0.5;
				const clampedNormY = Math.max(0, Math.min(1, normY));
				const targetPy = clampedNormY * plateHeight;
				const desired = compH * headroom - targetPy;
				return Math.max(minOffsetY, Math.min(0, desired));
			},
			{ fps: this.fps, label: "smart_framing_pan_y" },
		);

		// Damped camera smoothing
		const smoothOffsetX = new ProgrammaticSignal(
			(ctx) => {
				const targetFrame = ctx.frame;
				if (targetFrame <= 0) return rawOffsetX.get(ctx);
				let filtered = rawOffsetX.get({ ...ctx, frame: 0, time: 0 });
				const alpha = 1.0 - damping;
				for (let f = 1; f <= targetFrame; f++) {
					const val = rawOffsetX.get({ ...ctx, frame: f, time: f / ctx.fps });
					filtered = filtered + alpha * (val - filtered);
				}
				return filtered;
			},
			{ fps: this.fps, label: "smart_framing_smooth_x" },
		);

		const smoothOffsetY = new ProgrammaticSignal(
			(ctx) => {
				const targetFrame = ctx.frame;
				if (targetFrame <= 0) return rawOffsetY.get(ctx);
				let filtered = rawOffsetY.get({ ...ctx, frame: 0, time: 0 });
				const alpha = 1.0 - damping;
				for (let f = 1; f <= targetFrame; f++) {
					const val = rawOffsetY.get({ ...ctx, frame: f, time: f / ctx.fps });
					filtered = filtered + alpha * (val - filtered);
				}
				return filtered;
			},
			{ fps: this.fps, label: "smart_framing_smooth_y" },
		);

		const container = Layer.box({
			width: compW,
			height: compH,
			overflow: "hidden",
			position: "relative",
		});

		const videoPlate = Layer.video(src, {
			width: plateWidth,
			height: plateHeight,
			position: "absolute",
			x: smoothOffsetX as unknown as number,
			y: smoothOffsetY as unknown as number,
			fit: options.fit ?? "cover",
			muted: options.muted ?? false,
			volume: options.muted ? 0 : (options.volume ?? 1),
		});

		if (!container.children) {
			container.children = [];
		}
		container.children.push(videoPlate);
		this.add(container);
		return this;
	}

	/**
	 * Subject Contour Glow & Neon Outline.
	 * Strokes the silhouette boundary with a stylized bloom/glow and optional audio-reactive pulse.
	 */
	public addSubjectOutline(
		_subject: MaskTrackSignals | ObjectTrackSignals,
		options: SubjectOutlineOptions = {},
	): this {
		const blur = options.blur ?? 12;
		const compW = this.width;
		const compH = this.height;

		const pulse = options.pulseSignal;
		const baseOpacity = pulse
			? new ProgrammaticSignal(
					(ctx) => Math.max(0, Math.min(1, Number(pulse.get(ctx)) || 0)),
					{ fps: this.fps, label: "outline_pulse" },
				)
			: 1.0;

		const src =
			typeof options.source === "string"
				? options.source
				: (options.source?.inputHandleId ?? "");

		const outlineLayer = Layer.box({
			width: compW,
			height: compH,
			position: "absolute",
			x: 0,
			y: 0,
			opacity: baseOpacity as unknown as number,
		});

		if (src) {
			const maskVideo = Layer.video(src, {
				width: compW,
				height: compH,
				position: "absolute",
				x: 0,
				y: 0,
				fit: "cover",
				muted: true,
				volume: 0,
			}).withVision({
				mode: "mask",
				enableSegmentation: true,
			});
			if (!outlineLayer.children) {
				outlineLayer.children = [];
			}
			outlineLayer.children.push(maskVideo);
		}

		outlineLayer.apply(
			new Blur({
				strength: blur,
				blurType: "Gaussian",
			}),
		);

		this.add(outlineLayer);
		return this;
	}

	/**
	 * Creates an isolated, styled section of the composition or underlying source plate.
	 * Any WebGPU effects (Blur, FilmGrain, Curves, Vignette, etc.) can be applied to this section.
	 */
	public section(
		sourceOrTargetOrOptions?:
			| string
			| MediaNode
			| ObjectTrackSignals
			| SectionOptions,
		targetOrOptions?: ObjectTrackSignals | SectionOptions,
		options?: SectionOptions,
	): SectionNode {
		let source: string | MediaNode | undefined;
		let target: ObjectTrackSignals | undefined;
		let opts: SectionOptions = {};

		const isFirstTrack =
			sourceOrTargetOrOptions !== null &&
			typeof sourceOrTargetOrOptions === "object" &&
			"bounds" in sourceOrTargetOrOptions;

		const isFirstMedia =
			typeof sourceOrTargetOrOptions === "string" ||
			(sourceOrTargetOrOptions !== null &&
				typeof sourceOrTargetOrOptions === "object" &&
				("kind" in sourceOrTargetOrOptions ||
					"src" in sourceOrTargetOrOptions ||
					"inputHandleId" in sourceOrTargetOrOptions));

		if (
			isFirstMedia &&
			targetOrOptions &&
			typeof targetOrOptions === "object" &&
			"bounds" in targetOrOptions
		) {
			source = sourceOrTargetOrOptions as string | MediaNode;
			target = targetOrOptions as ObjectTrackSignals;
			opts = options ?? {};
		} else if (isFirstMedia && targetOrOptions) {
			source = sourceOrTargetOrOptions as string | MediaNode;
			opts = targetOrOptions as SectionOptions;
		} else if (isFirstTrack) {
			target = sourceOrTargetOrOptions as ObjectTrackSignals;
			opts = (targetOrOptions as SectionOptions) ?? {};
			source = opts.source ?? (target.source as string | MediaNode | undefined);
		} else if (
			sourceOrTargetOrOptions &&
			typeof sourceOrTargetOrOptions === "object"
		) {
			opts = sourceOrTargetOrOptions as SectionOptions;
			source = opts.source;
		}

		if (!source) {
			const mediaChild = this.children.find(
				(c) =>
					c.kind === "media" &&
					(c.dataType === "Video" || c.dataType === "Image"),
			) as MediaNode | undefined;
			if (mediaChild) {
				source = mediaChild;
			}
		}

		return Layer.section(source ?? "", target ?? opts, {
			compositionWidth: this.width,
			compositionHeight: this.height,
			...opts,
		});
	}

	/**
	 * Creates a section and immediately adds it to the composition layout tree.
	 */
	public addSection(
		sourceOrTargetOrOptions?:
			| string
			| MediaNode
			| ObjectTrackSignals
			| SectionOptions,
		targetOrOptions?: ObjectTrackSignals | SectionOptions,
		options?: SectionOptions,
	): SectionNode {
		const node = this.section(
			sourceOrTargetOrOptions,
			targetOrOptions,
			options,
		);
		this.add(node);
		return node;
	}

	/**
	 * Dynamically calculates composition duration from the longest media or animation layer.
	 */
	public async computeDuration(): Promise<number> {
		if (this.durationMs !== undefined) return this.durationMs;
		let maxDurationMs = 0;
		const mediaSources: string[] = [];

		for (const node of [...this.children, ...this.audioTracks]) {
			if (node.kind === "media") {
				const src = node.inputHandleId;
				if (
					typeof src === "string" &&
					(node.dataType === "Video" || node.dataType === "Audio")
				) {
					mediaSources.push(src);
				}
			}
			if (typeof node.durationFrames === "number") {
				const start = typeof node.startFrame === "number" ? node.startFrame : 0;
				const durMs = ((start + node.durationFrames) / this.fps) * 1000;
				if (durMs > maxDurationMs) maxDurationMs = durMs;
			}
		}

		for (const src of mediaSources) {
			try {
				const input = await inputStore.acquire(src);
				const sec = await input.computeDuration();
				if (Number.isFinite(sec) && sec > 0) {
					const ms = Math.round(sec * 1000);
					if (ms > maxDurationMs) maxDurationMs = ms;
				}
			} catch (_) {}
		}

		return maxDurationMs > 0 ? maxDurationMs : 5000;
	}

	public async registerFont(
		optionsOrFamilyOrSource: RegisterFontOptions | string,
		source?: string | Uint8Array,
	): Promise<this> {
		const reg = await FontManager.register(optionsOrFamilyOrSource, source);
		if (reg.filePath && !this.fonts.includes(reg.filePath)) {
			this.fonts.push(reg.filePath);
		}
		return this;
	}

	/** Sets the color emoji font; see {@link FontManager.registerEmojiFont}. */
	public async registerEmojiFont(source: string | Uint8Array): Promise<this> {
		await FontManager.registerEmojiFont(source);
		return this;
	}

	public toSpec(): CompositorProgramConfig {
		const layoutItems: LayoutNode[] = [...this.children, ...this.audioTracks];
		const registeredPaths = FontManager.getRegisteredFontPaths();
		const mergedFonts = Array.from(
			new Set([...this.fonts, ...registeredPaths]),
		);
		return {
			width: this.width,
			height: this.height,
			fps: this.fps,
			mode: "Video",
			backgroundColor: this.backgroundColor,
			...(this.antialias3d !== undefined && { antialias3d: this.antialias3d }),
			layout: layoutItems,
			fonts: mergedFonts,
			signals: this.signals,
			...(this._effects.length > 0 && { effects: this._effects }),
			...(this._visionConfig && { vision: this._visionConfig }),
			...(this.hasFrameHooks() && {
				onRequestFrame: (ctx: FrameContext) => this.notifyFrame(ctx),
			}),
		} as unknown as CompositorProgramConfig;
	}

	/**
	 * Compiles the composition into a VirtualMediaData AST ready for WebGPU rendering.
	 */
	public toVirtualMedia(
		options: Partial<CompositorToProgramOptions> = {},
	): VirtualMediaData {
		// Every compile links vision layers to their clips (a depth layer makes
		// its own), so the very first frame drawn reads them.
		if (!this._linking) {
			this._linking = true;
			try {
				this.linkClipLayers();
			} finally {
				this._linking = false;
			}
		}
		const durationMs = options.durationMs ?? this.durationMs;
		const signals = options.signals ?? this.signals;
		return compositorToProgram(this.toSpec(), {
			isVideoMode: true,
			fps: this.fps,
			durationMs,
			signals,
			resolveMediaSignal: this.mediaSignalResolver(
				undefined,
				durationMs,
				signals,
			),
			...(this._effects.length > 0 && { effects: this._effects }),
			...(this._visionConfig && { vision: this._visionConfig }),
			...options,
		});
	}

	/**
	 * Compiles the composition into a VirtualMediaData AST with dynamically resolved duration.
	 */
	public async toVirtualMediaAsync(
		options: Partial<CompositorToProgramOptions> = {},
	): Promise<VirtualMediaData> {
		const durationMs =
			options.durationMs ?? this.durationMs ?? (await this.computeDuration());
		this.durationMs = durationMs;
		const signals = options.signals ?? this.signals;
		const vm = compositorToProgram(this.toSpec(), {
			isVideoMode: true,
			fps: this.fps,
			durationMs,
			signals,
			resolveMediaSignal: this.mediaSignalResolver(
				undefined,
				durationMs,
				signals,
			),
			...(this._effects.length > 0 && { effects: this._effects }),
			...(this._visionConfig && { vision: this._visionConfig }),
			...options,
		});
		await preflightMediaTime(vm, this.fps);
		return vm;
	}

	/**
	 * Renders a single frame from the composition to an image or raw RGBA Buffer.
	 * Can render either by timestamp in milliseconds (`atMs`) or by frame index (`frame`).
	 */
	public async renderFrame(
		frameOrOptions:
			| number
			| {
					atMs?: number;
					fps?: number;
					frame?: number;
					renderId?: string;
					format?: "png" | "rgba" | "raw" | "jpeg" | "jpg" | "webp";
					renderer?: HeadlessMediaRenderer;
			  } = {},
	): Promise<Buffer> {
		const options =
			typeof frameOrOptions === "number"
				? { frame: frameOrOptions }
				: frameOrOptions;
		const { frame } = resolveFrameRequest(options, this.fps);
		if (options.fps !== undefined && options.fps !== this.fps)
			throw new Error(
				`Composition fps is ${this.fps}; cannot render at fps ${options.fps}.`,
			);

		// Compile first: the frame's hooks then record its live signal time.
		const vm = this.toVirtualMedia();
		if (this.hasFrameHooks()) {
			const targetFrame = frame;
			await this.notifyFrame({
				frame: targetFrame,
				fps: this.fps,
				time: this.fps > 0 ? targetFrame / this.fps : 0,
				duration: (this.durationMs ?? 0) / 1000,
				durationMs: this.durationMs ?? 0,
				progress:
					this.durationMs && this.durationMs > 0
						? Math.max(
								0,
								Math.min(
									1,
									((targetFrame / this.fps) * 1000) / this.durationMs,
								),
							)
						: 0,
				deltaTime: this.fps > 0 ? 1 / this.fps : 0,
			});
		}
		const renderer = options.renderer ?? new HeadlessMediaRenderer();
		return renderer.renderFrame(vm, {
			fps: this.fps,
			frame,
			renderId: options.renderId,
			format: options.format,
		});
	}

	/**
	 * Renders an image grid of sequential frames across a given frame or millisecond range.
	 * Ideal for automated visual inspection of animation motion, easing curves, and layout stability.
	 */
	public async renderFrameGrid(
		options: FrameGridOptions = {},
	): Promise<Buffer> {
		return renderFrameGrid(this, options);
	}

	/**
	 * Renders this composition into an MP4/WebM video file with audio.
	 */
	public async renderVideo(
		outputPathOrOptions: string | RenderVideoOptions = {},
		options: RenderVideoOptions = {},
	): Promise<RenderVideoResult> {
		const opts =
			typeof outputPathOrOptions === "string"
				? { ...options, outputPath: outputPathOrOptions }
				: outputPathOrOptions;
		const renderer = opts.renderer ?? new HeadlessMediaRenderer();
		const result = await renderer.renderVideo(this.toVirtualMedia(), opts);
		if (result.qa) {
			// Fold the document checks into the output checks.
			const lint = this.lint();
			const issues = [
				...result.qa.issues,
				...lint.map((d) => ({
					severity: d.severity,
					code: d.code,
					message: d.message,
					...(d.layerId !== undefined && { layerId: d.layerId }),
				})),
			];
			result.qa = {
				...result.qa,
				issues,
				// Lint warnings advise; only a lint error fails the render.
				passed: result.qa.passed && !lint.some((d) => d.severity === "error"),
			};
		}
		return deliverToOutputPath(result, opts.outputPath);
	}

	/**
	 * Checks the document for things that render without error but not as
	 * intended: unreadable colors or gradients (drawn transparent),
	 * low-contrast text, layers parked off-canvas, shadows on lights that
	 * cannot cast them, physical materials without an environment, tracks that
	 * never change. `renderVideo({ qa })` includes these automatically.
	 */
	public lint(): RenderDiagnostic[] {
		return lintComposition(this.toSpec(), {
			emojiFont: FontManager.hasEmojiFont(),
			scatterCoverage,
		});
	}
}

/**
 * Layer helpers for constructing composition nodes with clean URL/path strings.
 */

export type NodeCapability = "visual" | "audio" | "hybrid";

export type CompatibleEffect<TCap extends NodeCapability> =
	TCap extends "hybrid"
		? AnyEffect
		: TCap extends "visual"
			? AnyVisualEffect
			: TCap extends "audio"
				? AnyAudioEffect
				: Effect<object>;

export type AnimatableNode<
	T extends LayoutNode = LayoutNode,
	TCap extends NodeCapability = "visual",
> = T & {
	glass?: Record<string, unknown>;
	audioDeform?: MeshAudioDeformConfig | Record<string, unknown>;
	crop?: CropProps | Crop;
	vision?: Vision;
	relighting?: NormalRelightingOptions;
	matte?: { node: LayoutNode; mode?: MatteMode };
	relief?: { node: LayoutNode; amount?: number };
	deflicker?: DeflickerOptions;
	effects?: CompatibleEffect<TCap>[];
	blurRegions?: unknown[];
	animate<P extends AnimatableProp = AnimatableProp>(
		...anim: (
			| ([AnimatableProp] extends [P]
					? LayerAnimation
					: LayerAnimation<P & AnimatablePropsFor<T>>)
			| {
					tracks: AnimationTrack<
						[AnimatableProp] extends [P]
							? AnimatableProp
							: P & AnimatablePropsFor<T>
					>[];
			  }
			| (
					| ([AnimatableProp] extends [P]
							? LayerAnimation
							: LayerAnimation<P & AnimatablePropsFor<T>>)
					| {
							tracks: AnimationTrack<
								[AnimatableProp] extends [P]
									? AnimatableProp
									: P & AnimatablePropsFor<T>
							>[];
					  }
			  )[]
		)[]
	): AnimatableNode<T, TCap>;
	pinToLandmark(
		target:
			| LandmarkCoordinateSignals
			| {
					x: number;
					y: number;
					z?: number;
					screenX?: number;
					screenY?: number;
			  },
		options?: PinToLandmarkOptions,
	): AnimatableNode<T, TCap>;
	pinToObject(
		target:
			| ObjectTrackSignals
			| LandmarkCoordinateSignals
			| {
					x: number;
					y: number;
					z?: number;
					screenX?: number;
					screenY?: number;
			  },
		options?: PinToObjectOptions,
	): AnimatableNode<T, TCap>;
	/**
	 * Track matte: `matte` (any layer) masks this one by its alpha or
	 * brightness. It is laid out like a sibling (same parent) and timed with
	 * this node; with no x/y/width/height it covers this node's box. Animate
	 * the matte for wipes and reveals: text through a sliding box, video
	 * inside type, an iris circle.
	 */
	withMatte(matte: LayoutNode, mode?: MatteMode): AnimatableNode<T, TCap>;
	/** Alias of {@link withMatte}. */
	withMask(mask: LayoutNode, mode?: MatteMode): AnimatableNode<T, TCap>;
	/**
	 * Relief (3D layers): `relief` (any layer, typically a video's
	 * `withVision({ mode: "depth" })`) lifts this layer's plane into a surface,
	 * white `amount` px toward the camera. The surface is pushed along the
	 * default camera's rays, so from that lens it looks exactly like the flat
	 * layer; a moving camera then sees it in 3D, lit by the scene's lights and
	 * hiding what passes behind it. Where the relief jumps (an object's
	 * outline) the surface stretches across with the edge pixels, so keep
	 * camera moves modest; footage never saw those sides. Laid out and timed
	 * like a matte; drawn flat over this node's box.
	 */
	withRelief(
		relief: LayoutNode,
		options?: { amount?: number },
	): AnimatableNode<T, TCap>;
	withPbrGlass(options?: Record<string, unknown>): AnimatableNode<T, TCap>;
	deformWithAudio(
		config?: MeshAudioDeformConfig | Record<string, unknown>,
	): AnimatableNode<T, TCap>;
	withCrop(cropConfig: CropProps | Crop): AnimatableNode<T, TCap>;
	/** Runs vision on this node's rendered output (see `Vision` for options and modes). */
	withVision(config?: VisionProps | Vision): AnimatableNode<T, TCap>;
	withRelighting(options?: NormalRelightingOptions): AnimatableNode<T, TCap>;
	relight(options?: NormalRelightingOptions): AnimatableNode<T, TCap>;
	withDeflicker(options?: DeflickerOptions): AnimatableNode<T, TCap>;
	apply(effect: CompatibleEffect<TCap>): AnimatableNode<T, TCap>;
	withEffect(effect: CompatibleEffect<TCap>): AnimatableNode<T, TCap>;
	withEffects(effects: CompatibleEffect<TCap>[]): AnimatableNode<T, TCap>;
	section(
		targetOrOptions?: ObjectTrackSignals | SectionOptions,
		options?: SectionOptions,
	): SectionNode;
	blurRegion(
		trackTarget: ObjectTrackSignals,
		options?: Partial<BlurProps>,
	): AnimatableNode<T, TCap>;
	withBlurRegion(
		trackTarget: ObjectTrackSignals,
		options?: Partial<BlurProps>,
	): AnimatableNode<T, TCap>;
};

function withAnimation<
	T extends LayoutNode,
	TCap extends NodeCapability = "visual",
>(node: T): AnimatableNode<T, TCap> {
	const target = node as AnimatableNode<T, TCap>;
	const raw = target as unknown as Record<string, unknown>;
	if (raw.rotationX !== undefined) {
		if (raw.rotateX === undefined) raw.rotateX = raw.rotationX;
		delete raw.rotationX;
	}
	if (raw.rotationY !== undefined) {
		if (raw.rotateY === undefined) raw.rotateY = raw.rotationY;
		delete raw.rotationY;
	}
	if (raw.rotationZ !== undefined) {
		if (raw.rotateZ === undefined) raw.rotateZ = raw.rotationZ;
		delete raw.rotationZ;
	}
	// Animation builders are structurally valid inputs, but carry enumerable
	// authoring defaults that are not fields of the strict program schema.
	if (target.animation instanceof LayerAnimation)
		target.animation = target.animation.toSpec();
	Object.defineProperty(target, "animate", {
		value: (
			...anims: (
				| LayerAnimation
				| { tracks: AnimationTrack[] }
				| LayerAnimation[]
			)[]
		) => {
			// Every call layers onto what is already there: keyframe tracks on
			// the same prop merge (a later key wins on a shared frame).
			const incoming = anims
				.flat()
				.flatMap((a) =>
					a instanceof LayerAnimation
						? a.tracks
						: ((a as { tracks?: AnimationTrack[] }).tracks ?? []),
				);
			const current = target.animation as
				| { tracks?: AnimationTrack[]; frameStep?: number }
				| undefined;
			const existing = current?.tracks ?? [];
			// The last `.stepped()` wins; stepping applies to the whole layer.
			const frameStep =
				anims
					.flat()
					.map((a) => (a as { frameStep?: number }).frameStep)
					.filter((n): n is number => n !== undefined)
					.at(-1) ?? current?.frameStep;
			target.animation = {
				tracks: mergeAnimationTracks([...existing, ...incoming]),
				...(frameStep !== undefined && frameStep > 1 && { frameStep }),
			};
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "pinToLandmark", {
		value: (
			landmarkTarget:
				| LandmarkCoordinateSignals
				| {
						x: number;
						y: number;
						z?: number;
						screenX?: number;
						screenY?: number;
				  },
			options?: PinToLandmarkOptions,
		) => {
			pinNodeToLandmark(
				target as unknown as { x?: unknown; y?: unknown; z?: unknown },
				landmarkTarget,
				options,
			);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "pinToObject", {
		value: (
			objectTarget:
				| ObjectTrackSignals
				| LandmarkCoordinateSignals
				| {
						x: number;
						y: number;
						z?: number;
						screenX?: number;
						screenY?: number;
				  },
			options?: PinToObjectOptions,
		) => {
			pinNodeToObject(
				target as unknown as {
					x?: unknown;
					y?: unknown;
					z?: unknown;
					width?: unknown;
					height?: unknown;
					opacity?: unknown;
				},
				objectTarget,
				options,
			);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	const withMatte = (matte: LayoutNode, mode?: MatteMode) => {
		target.matte = { node: matte, ...(mode && { mode }) };
		return target;
	};
	for (const name of ["withMatte", "withMask"]) {
		Object.defineProperty(target, name, {
			value: withMatte,
			enumerable: false,
			writable: true,
			configurable: true,
		});
	}

	Object.defineProperty(target, "withRelief", {
		value: (relief: LayoutNode, options: { amount?: number } = {}) => {
			target.relief = { node: relief, ...options };
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withPbrGlass", {
		value: (options?: Record<string, unknown>) => {
			target.glass = options ?? {};
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "deformWithAudio", {
		value: (config?: MeshAudioDeformConfig | Record<string, unknown>) => {
			target.audioDeform = config ?? {};
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withCrop", {
		value: (cropConfig: CropProps | Crop) => {
			target.crop =
				cropConfig instanceof Crop ? cropConfig : new Crop(cropConfig);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withVision", {
		value: (config?: VisionProps | Vision) => {
			target.vision = config instanceof Vision ? config : new Vision(config);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withRelighting", {
		value: (options?: NormalRelightingOptions) => {
			target.relighting = options ?? {};
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "relight", {
		value: (options?: NormalRelightingOptions) => {
			target.relighting = options ?? {};
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withDeflicker", {
		value: (options?: DeflickerOptions) => {
			target.deflicker = options ?? {};
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "apply", {
		value: (effect: CompatibleEffect<TCap>) => {
			if (!target.effects) {
				target.effects = [];
			}
			target.effects.push(effect);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withEffect", {
		value: (effect: CompatibleEffect<TCap>) => {
			if (!target.effects) {
				target.effects = [];
			}
			target.effects.push(effect);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withEffects", {
		value: (effects: CompatibleEffect<TCap>[]) => {
			if (!target.effects) {
				target.effects = [];
			}
			target.effects.push(...effects);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "section", {
		value: (
			targetOrOptions: ObjectTrackSignals | SectionOptions = {},
			options?: SectionOptions,
		) => {
			if (
				targetOrOptions !== null &&
				typeof targetOrOptions === "object" &&
				"bounds" in targetOrOptions
			) {
				return Layer.section(
					target as MediaNode,
					targetOrOptions as ObjectTrackSignals,
					options,
				);
			}
			return Layer.section(
				target as MediaNode,
				targetOrOptions as SectionOptions,
			);
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "blurRegion", {
		value: (trackTarget: ObjectTrackSignals, options?: Partial<BlurProps>) => {
			const blur = new Blur({
				track: trackTarget,
				strength: options?.strength ?? 25,
				shape: options?.shape ?? "ellipse",
				...options,
			});
			if (!target.effects) {
				target.effects = [];
			}
			target.effects.push(blur as CompatibleEffect<TCap>);
			return target;
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	Object.defineProperty(target, "withBlurRegion", {
		value: (trackTarget: ObjectTrackSignals, options?: Partial<BlurProps>) => {
			return (
				target as {
					blurRegion: (
						t: ObjectTrackSignals,
						o?: Partial<BlurProps>,
					) => unknown;
				}
			).blurRegion(trackTarget, options);
		},
		enumerable: false,
		writable: true,
		configurable: true,
	});

	bindMaterialSignals(target);
	return target;
}

/**
 * Numeric surface props a live `Signal` may drive directly (`clearcoat: sig`):
 * the value written to the node is the static fallback, the signal becomes a
 * draw-time signal track. `iridescence` counts only when it is the number form.
 */
const MATERIAL_SIGNAL_PROPS: ReadonlyArray<{
	prop: AnimatableProp;
	fallback: number;
}> = [
	{ prop: "roughness", fallback: 0.5 },
	{ prop: "metallic", fallback: 0 },
	{ prop: "emissiveIntensity", fallback: 1 },
	{ prop: "clearcoat", fallback: 0 },
	{ prop: "clearcoatRoughness", fallback: 0.08 },
	{ prop: "anisotropy", fallback: 0 },
	{ prop: "anisotropyRotation", fallback: 0 },
	{ prop: "subsurface", fallback: 0 },
	{ prop: "sheen", fallback: 0 },
	{ prop: "sheenRoughness", fallback: 0.5 },
	{ prop: "iridescence", fallback: 0 },
	{ prop: "iridescenceThickness", fallback: 400 },
	{ prop: "iridescenceIor", fallback: 1.3 },
	{ prop: "triplanarScale", fallback: 1 },
	{ prop: "triplanarSharpness", fallback: 4 },
];

/** Moves signal-valued material props of a node onto signal tracks. */
function bindMaterialSignals<T extends LayoutNode, TCap extends NodeCapability>(
	target: AnimatableNode<T, TCap>,
): void {
	const raw = target as unknown as Record<string, unknown>;
	let anim: LayerAnimation<AnimatableProp> | undefined;
	for (const { prop, fallback } of MATERIAL_SIGNAL_PROPS) {
		const val = raw[prop];
		if (!isSignalLike(val)) continue;
		anim ??= LayerAnimation.create<AnimatableProp>();
		anim.signal(prop, val);
		raw[prop] = fallback;
	}
	if (anim) target.animate(anim);
}

export const Layer = {
	video: (
		src: string,
		options: Partial<MediaNode> = {},
	): AnimatableNode<MediaNode, "hybrid"> =>
		withAnimation({
			id: options.id ?? autoId("video"),
			kind: "media",
			inputHandleId: src,
			dataType: "Video",
			fit: options.fit ?? "cover",
			...options,
		}),
	image: (
		src: string,
		options: Partial<MediaNode> = {},
	): AnimatableNode<MediaNode, "visual"> => {
		if (typeof src === "string") {
			if (
				/\.(json|lottie)(\?.*)?$/i.test(src) ||
				src.startsWith("data:application/json")
			) {
				console.warn(
					`[Layer.image] '${src}' is a Lottie vector animation, not a static image. Use Layer.lottie('${src}', options) instead.`,
				);
			} else if (/\.(mp4|mov|webm|mkv)(\?.*)?$/i.test(src)) {
				console.warn(
					`[Layer.image] '${src}' is a video file, not a static image. Use Layer.video('${src}', options) instead.`,
				);
			} else if (/\.(mp3|wav|ogg|m4a|aac)(\?.*)?$/i.test(src)) {
				console.warn(
					`[Layer.image] '${src}' is an audio file, not a static image. Use Layer.audio('${src}', options) instead.`,
				);
			}
		}
		return withAnimation({
			id: options.id ?? autoId("img"),
			kind: "media",
			inputHandleId: src,
			dataType: "Image",
			fit: options.fit ?? "cover",
			...options,
		});
	},
	svg: (
		src: string,
		options: Partial<MediaNode> = {},
	): AnimatableNode<MediaNode, "visual"> =>
		withAnimation({
			id: options.id ?? autoId("svg"),
			kind: "media",
			inputHandleId: src,
			dataType: "SVG",
			fit: options.fit ?? "contain",
			...options,
		}),
	lottie: (
		src: string,
		options: Partial<MediaNode> = {},
	): AnimatableNode<MediaNode, "visual"> =>
		withAnimation({
			id: options.id ?? autoId("lottie"),
			kind: "media",
			inputHandleId: src,
			dataType: "Lottie",
			fit: options.fit ?? "contain",
			...options,
		}),
	audio: (
		src: string,
		options: Partial<MediaNode> = {},
	): AnimatableNode<MediaNode, "audio"> =>
		withAnimation({
			id: options.id ?? autoId("audio"),
			kind: "media",
			inputHandleId: src,
			dataType: "Audio",
			volume: options.volume ?? 1,
			...options,
		}),
	text: (
		contentOrOptions:
			| string
			| TextSpan[]
			| (string | TextSpan)[]
			| Partial<TextNode>,
		maybeOptions: Partial<TextNode> = {},
	): AnimatableNode<TextNode, "visual"> => {
		const isArray = Array.isArray(contentOrOptions);
		const isObj =
			!isArray &&
			typeof contentOrOptions === "object" &&
			contentOrOptions !== null;
		const options = isObj
			? (contentOrOptions as Partial<TextNode>)
			: maybeOptions;

		let textContent = "";
		let spans: TextSpan[] | undefined = options.spans;

		if (isArray) {
			const normalized = normalizeTextSpans(
				contentOrOptions as (string | TextSpan)[],
			);
			textContent = normalized.text;
			spans = normalized.spans;
		} else if (isObj) {
			if (options.spans && !options.text) {
				const normalized = normalizeTextSpans(options.spans);
				textContent = normalized.text;
			} else {
				textContent = (options.text as string) ?? "";
			}
		} else {
			textContent =
				typeof contentOrOptions === "string"
					? contentOrOptions
					: String(contentOrOptions ?? "");
		}

		return withAnimation({
			id: options.id ?? autoId("text"),
			kind: "text",
			fontFamily:
				options.fontFamily ?? FontManager.getAll()[0]?.family ?? "Inter",
			fontSize: options.fontSize ?? 48,
			fill: options.fill ?? "#ffffff",
			...options,
			text: options.text ?? textContent,
			spans: options.spans ?? spans,
		});
	},
	caption: (
		src: string,
		options: Partial<MediaNode> = {},
	): AnimatableNode<MediaNode> =>
		withAnimation({
			id: options.id ?? autoId("caption"),
			kind: "media",
			inputHandleId: src,
			dataType: options.dataType ?? "Caption",
			fontFamily:
				options.fontFamily ?? FontManager.getAll()[0]?.family ?? "Inter",
			fontSize: options.fontSize ?? 48,
			fill: options.fill ?? "#ffffff",
			...options,
		}),
	shape: (
		shapeType:
			| "rect"
			| "circle"
			| "ellipse"
			| "polygon"
			| "star"
			| "arrow"
			| "path" = "rect",
		options: Partial<ShapeNode> & {
			/** Alias of `fillColor`: a color or a CSS gradient string. */
			fill?: string;
		} = {},
	): AnimatableNode<ShapeNode> => {
		// `fill` and `fillColor` are the same thing; either may hold a
		// color or a CSS gradient. Only `fillColor` reaches the node.
		const { fill, ...rest } = options;
		return withAnimation({
			id: rest.id ?? autoId("shape"),
			kind: "shape",
			shapeType: rest.shapeType ?? shapeType,
			...rest,
			fillColor: rest.fillColor ?? fill ?? "#3b82f6",
		});
	},
	flex: (options: Partial<FlexNode> = {}): AnimatableNode<FlexNode> =>
		withAnimation({
			id: options.id ?? autoId("flex"),
			kind: "flex",
			dir: options.dir ?? "column",
			children: options.children ?? [],
			...options,
		}),
	box: (options: Partial<BoxNode> = {}): AnimatableNode<BoxNode> =>
		withAnimation({
			id: options.id ?? autoId("box"),
			kind: "box",
			background: options.background ?? "transparent",
			children: options.children ?? [],
			...options,
		}),
	/**
	 * A GPU particle system as a layer: tens of thousands of particles
	 * simulated in a compute shader and drawn in one call (see
	 * {@link ParticlesOptions}). Positions are in the layer's own px; drivers
	 * (rate, gravity, noise, attractors) are read every frame, and a
	 * performer can push particles with `push: { person }`.
	 */
	particles: (options: ParticlesOptions): AnimatableNode<MediaNode> => {
		const system = new Particles(options);
		// A media layer whose source is the particle op itself: it draws into
		// the layer's own texture, composited like any clip.
		const source = {
			metadata: { width: options.width, height: options.height },
			operation: { ...system.toOperation(), effect: system, dataType: "Video" },
			children: [],
		};
		return withAnimation({
			id: options.id ?? autoId("particles"),
			kind: "media",
			dataType: "Video",
			src: source,
			position: "absolute",
			x: options.x ?? 0,
			y: options.y ?? 0,
			width: options.width,
			height: options.height,
			...(options.startFrame !== undefined && {
				startFrame: options.startFrame,
			}),
			...(options.durationFrames !== undefined && {
				durationFrames: options.durationFrames,
			}),
			...(options.zIndex !== undefined && { zIndex: options.zIndex }),
		} as unknown as MediaNode);
	},
	/**
	 * A procedural VFX layer (smoke, fire, rain, snow, aurora, …) drawn by
	 * the GPU, transparent where there is no effect. Put it above or below
	 * other layers like any clip.
	 */
	vfx: (
		options: Partial<ProceduralVFXProps> & {
			x?: number;
			y?: number;
			width: number;
			height: number;
			id?: string;
			startFrame?: number;
			durationFrames?: number;
			zIndex?: number;
		},
	): AnimatableNode<MediaNode> => {
		const { x, y, id, startFrame, durationFrames, zIndex, ...props } = options;
		const vfx = new ProceduralVFX({
			outputType: "Video",
			...props,
		} as ProceduralVFXProps);
		const source = {
			metadata: { width: options.width, height: options.height },
			operation: { ...vfx.toOperation(), effect: vfx, dataType: "Video" },
			children: [],
		};
		return withAnimation({
			id: id ?? autoId("vfx"),
			kind: "media",
			dataType: "Video",
			src: source,
			position: "absolute",
			x: x ?? 0,
			y: y ?? 0,
			width: options.width,
			height: options.height,
			...(startFrame !== undefined && { startFrame }),
			...(durationFrames !== undefined && { durationFrames }),
			...(zIndex !== undefined && { zIndex }),
		} as unknown as MediaNode);
	},
	section: (
		source: string | MediaNode | Composition,
		targetOrOptions: ObjectTrackSignals | SectionOptions = {},
		options: SectionOptions = {},
	): SectionNode => {
		let realSource: string | MediaNode = source as string | MediaNode;
		if (
			source &&
			typeof source === "object" &&
			"toSpec" in source &&
			"children" in source
		) {
			const compMedia = (
				((source as Composition).children || []) as LayoutNode[]
			).find(
				(c) =>
					c.kind === "media" &&
					(c.dataType === "Video" || c.dataType === "Image"),
			) as MediaNode | undefined;
			if (compMedia) {
				realSource = compMedia;
			}
		}

		const isTracked =
			targetOrOptions !== null &&
			typeof targetOrOptions === "object" &&
			"bounds" in targetOrOptions;
		const opts: SectionOptions = isTracked
			? options
			: (targetOrOptions as SectionOptions);
		const target = isTracked
			? (targetOrOptions as ObjectTrackSignals)
			: undefined;

		const padding = opts.padding ?? 0;
		const src =
			typeof realSource === "string"
				? realSource
				: (realSource?.inputHandleId ??
					(realSource as { src?: string })?.src ??
					"");
		const dataType =
			typeof realSource === "object" && realSource?.dataType
				? realSource.dataType
				: "Video";
		const compW =
			(opts.compositionWidth as number) ??
			(opts.compWidth as number) ??
			(isTracked ? (opts.width as number) : undefined) ??
			1920;
		const compH =
			(opts.compositionHeight as number) ??
			(opts.compHeight as number) ??
			(isTracked ? (opts.height as number) : undefined) ??
			1080;

		const effList: Effect[] = Array.isArray(opts.effects)
			? ([...opts.effects] as Effect[])
			: opts.effects
				? [opts.effects as Effect]
				: [];

		const innerX = target
			? target.bounds.screenX.multiply(-1).add(padding)
			: typeof opts.x === "number"
				? -opts.x
				: opts.x &&
						typeof (opts.x as { multiply?: unknown }).multiply === "function"
					? (
							opts.x as unknown as { multiply: (n: number) => unknown }
						).multiply(-1)
					: 0;

		const innerY = target
			? target.bounds.screenY.multiply(-1).add(padding)
			: typeof opts.y === "number"
				? -opts.y
				: opts.y &&
						typeof (opts.y as { multiply?: unknown }).multiply === "function"
					? (
							opts.y as unknown as { multiply: (n: number) => unknown }
						).multiply(-1)
					: 0;

		const innerMedia = (
			dataType === "Image"
				? Layer.image(src, {
						position: "absolute",
						width: compW,
						height: compH,
						fit: opts.fit ?? "cover",
						x: innerX as number,
						y: innerY as number,
					})
				: Layer.video(src, {
						position: "absolute",
						width: compW,
						height: compH,
						fit: opts.fit ?? "cover",
						x: innerX as number,
						y: innerY as number,
					})
		).withEffects(effList);

		const boxWidth = target
			? target.bounds.screenWidth.add(padding * 2)
			: opts.width !== undefined
				? opts.width
				: compW;

		const boxHeight = target
			? target.bounds.screenHeight.add(padding * 2)
			: opts.height !== undefined
				? opts.height
				: compH;

		const boxChildren = [innerMedia, ...(opts.children ?? [])];

		const boxId =
			opts.id ??
			(target ? autoId(`section-track-${target.trackId}`) : autoId("section"));

		let box = Layer.box({
			id: boxId,
			position: (opts.position as "absolute" | "relative") ?? "absolute",
			width: boxWidth as number,
			height: boxHeight as number,
			x: target ? undefined : (opts.x as number),
			y: target ? undefined : (opts.y as number),
			borderRadius: opts.borderRadius ?? 0,
			borderColor: opts.borderColor,
			borderWidth: opts.borderWidth,
			opacity: (opts.opacity as number) ?? 1,
			overflow: "hidden",
			children: boxChildren,
		});

		if (target) {
			box = box.pinToObject(target, {
				anchor: "topLeft",
				offsetX: -padding,
				offsetY: -padding,
				hideWhenLost: opts.hideWhenLost ?? true,
				smoothFrames: opts.smoothFrames,
			});
		}

		const sectionNode = box as SectionNode;
		Object.defineProperty(sectionNode, "innerMedia", {
			value: innerMedia,
			enumerable: true,
			writable: false,
		});
		Object.defineProperty(sectionNode, "effects", {
			get: () => effList,
			enumerable: true,
		});
		Object.defineProperty(sectionNode, "addEffect", {
			value: (effect: Effect) => {
				effList.push(effect);
				innerMedia.effects = effList;
				return sectionNode;
			},
			enumerable: true,
			writable: false,
		});
		Object.defineProperty(sectionNode, "withEffect", {
			value: (effect: Effect) => sectionNode.addEffect(effect),
			enumerable: true,
			writable: false,
		});
		Object.defineProperty(sectionNode, "withEffects", {
			value: (effects: Effect[]) => {
				for (const eff of effects) {
					sectionNode.addEffect(eff);
				}
				return sectionNode;
			},
			enumerable: true,
			writable: false,
		});

		return sectionNode;
	},
	trackedRegion: (
		source: string | MediaNode,
		target: ObjectTrackSignals,
		options: TrackedRegionOptions = {},
	): SectionNode => {
		return Layer.section(source, target, options);
	},
	blurTrackedRegion: (
		source: string | MediaNode,
		target: ObjectTrackSignals,
		options: Partial<BlurProps> & {
			borderRadius?: number;
			padding?: number;
			borderColor?: string;
			borderWidth?: number;
		} = {},
	): SectionNode => {
		// Section styling is not a Blur prop; keep it out of the effect config.
		const { padding, borderRadius, borderColor, borderWidth, ...blurOptions } =
			options;
		return Layer.section(source, target, {
			padding: padding ?? 8,
			borderRadius: borderRadius ?? 12,
			borderColor,
			borderWidth,
			effects: [
				new Blur({
					strength: blurOptions.strength ?? 25,
					blurType: blurOptions.blurType ?? "Gaussian",
					...blurOptions,
				}),
			],
		});
	},
	/**
	 * A line, area, bar, scatter, candlestick, pie or donut chart. Returns a box
	 * of ordinary nodes (bars are boxes, lines and slices are path shapes,
	 * labels are text), so it positions, animates and composites like any layer.
	 * `props` applies to that box: position, id, timing, effects.
	 */
	chart: (
		options: ChartOptions,
		props: Partial<BoxNode> = {},
	): AnimatableNode<BoxNode> =>
		buildChart(options, props, FontManager.getAll()[0]?.family ?? "Inter"),
	camera: (options: CameraOptions = {}): AnimatableNode<CameraNode> => {
		const {
			fov,
			focalLength,
			sensorWidth,
			near,
			far,
			zoom,
			lens: existingLens,
			...rest
		} = options;
		const hasTopLens =
			fov !== undefined ||
			focalLength !== undefined ||
			sensorWidth !== undefined ||
			near !== undefined ||
			far !== undefined ||
			zoom !== undefined;
		const mergedLens =
			hasTopLens || existingLens !== undefined
				? {
						...existingLens,
						...(fov !== undefined && { fov }),
						...(focalLength !== undefined && { focalLength }),
						...(sensorWidth !== undefined && { sensorWidth }),
						...(near !== undefined && { near }),
						...(far !== undefined && { far }),
						...(zoom !== undefined && { zoom }),
					}
				: undefined;
		return withAnimation<CameraNode>({
			id: rest.id ?? autoId("camera"),
			kind: "camera",
			mode: rest.mode ?? "lookAt",
			pitch: rest.pitch ?? 0,
			yaw: rest.yaw ?? 0,
			roll: rest.roll ?? 0,
			...rest,
			...(mergedLens !== undefined && { lens: mergedLens }),
		});
	},
	light: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		buildLightNode(
			{
				id: options.id ?? autoId("light"),
				kind: "light",
				lightType: options.lightType ?? "point",
				color: options.color ?? "#ffffff",
				intensity: 1.0,
			},
			options as Record<string, unknown>,
		),
	ambientLight: (
		color: string | LightOptions = "#ffffff",
		intensity: SignalOrNumber = 0.5,
		options: LightOptions = {},
	): AnimatableNode<LightNode> => Light.ambient(color, intensity, options),
	/**
	 * Scenes back to back with transitions between them; see `Transition`.
	 * `comp.add(Layer.sequence([{ scene: hero(), duration: 90 },
	 *   { scene: next(), duration: 120, transition: Transition.push("left") }]))`.
	 * The result's `totalFrames` is the sequence length.
	 */
	sequence: (
		entries: SequenceEntry[],
		options?: SceneSequenceOptions,
	): SequenceNode => sequence(entries, options),
	/** See {@link Light.environment}: `Layer.environment("studio", { exposure: 0.3 })` or `Layer.environment("sky.hdr")`. */
	environment: (
		presetOrOptions:
			| EnvironmentPreset
			| HdriPath
			| EnvironmentOptions = "studio",
		options: EnvironmentOptions = {},
	): AnimatableNode<LightNode> => Light.environment(presetOrOptions, options),
	directionalLight: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		Light.directional(options),
	pointLight: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		Light.point(options),
	spotLight: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		Light.spot(options),
	rectLight: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		Light.rect(options),
	cube: (options: Cube3DOptions): AnimatableNode<BoxNode> =>
		Layer3D.cube(options),
	carousel3d: (options: Carousel3DOptions): AnimatableNode<BoxNode> =>
		Layer3D.carousel(options),
	plane3d: (options: Plane3DOptions): AnimatableNode<BoxNode> =>
		Layer3D.plane(options),
	prism3d: (options: Prism3DOptions = {}): SolidShape3DNode =>
		Layer3D.prism(options),
	model: (options: Model3DOptions = {}): AnimatableNode<Model3DNode> =>
		withAnimation({
			id: options.id ?? autoId("model3d"),
			kind: "model3d",
			is3D: options.is3D ?? true,
			modelFormat: options.modelFormat ?? "auto",
			loop: options.loop ?? true,
			scale: options.scale ?? 1.0,
			scaleX: options.scaleX ?? 1.0,
			scaleY: options.scaleY ?? 1.0,
			scaleZ: options.scaleZ ?? 1.0,
			opacity: options.opacity ?? 1.0,
			// material and twoSided stay unset unless given: the model's own
			// materials (toon, single-sided, …) decide, falling back to lit.
			...options,
		}),
	obj: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "obj",
			...options,
		}),
	fbx: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "fbx",
			...options,
		}),
	gltf: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "gltf",
			...options,
		}),
	glb: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "glb",
			...options,
		}),
	stl: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "stl",
			...options,
		}),
	ply: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "ply",
			...options,
		}),
	vox: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "vox",
			...options,
		}),
	threeDS: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "3ds",
			...options,
		}),
	off: (
		src: string,
		options: Model3DOptions = {},
	): AnimatableNode<Model3DNode> =>
		Layer.model({
			src,
			modelFormat: "off",
			...options,
		}),
};

export interface CameraOptions extends Partial<CameraNode> {
	/** Top-level shorthand for `lens.fov` (vertical field of view in degrees). */
	fov?: number;
	/** Top-level shorthand for `lens.focalLength` (mm). */
	focalLength?: number;
	/** Top-level shorthand for `lens.sensorWidth` (mm). */
	sensorWidth?: number;
	/** Top-level shorthand for `lens.near` clipping plane. */
	near?: number;
	/** Top-level shorthand for `lens.far` clipping plane. */
	far?: number;
	/** Top-level shorthand for `lens.zoom` multiplier. */
	zoom?: number;
}

export interface Model3DOptions extends Partial<Model3DNode> {
	/** Alias for `rotateX`. */
	rotationX?: number;
	/** Alias for `rotateY`. */
	rotationY?: number;
	/** Alias for `rotateZ`. */
	rotationZ?: number;
}

export type SignalOrNumber =
	| number
	| ProgrammaticSignal
	| Signal<number>
	| { get: (ctx: FrameContext) => number };

export interface VolumetricFogNoiseOptions
	extends Omit<EnvironmentVolumetricFogNoise, "strength"> {
	strength?: SignalOrNumber;
}

export interface VolumetricFogOptions
	extends Omit<EnvironmentVolumetricFog, "density" | "anisotropy" | "noise"> {
	density?: SignalOrNumber;
	anisotropy?: SignalOrNumber;
	noise?: boolean | VolumetricFogNoiseOptions;
}

/** An equirectangular panorama path (Radiance `.hdr` or OpenEXR `.exr`), usable in place of a preset name. */
export type HdriPath =
	| `${string}.hdr`
	| `${string}.HDR`
	| `${string}.exr`
	| `${string}.EXR`;

function isHdriPath(value: string): value is HdriPath {
	return /\.(hdr|exr)$/i.test(value);
}

/** World settings for `Layer.environment` (see `LightNode` for every field). */
export interface EnvironmentOptions
	extends Partial<
		Pick<
			LightNode,
			| "id"
			| "preset"
			| "hdri"
			| "color"
			| "top"
			| "horizon"
			| "bottom"
			| "softboxes"
			| "toneMapping"
			| "fog"
			| "floor"
			| "outlines"
			| "ssr"
			| "gi"
			| "bloom"
			| "startFrame"
			| "durationFrames"
		>
	> {
	intensity?: SignalOrNumber;
	rotation?: SignalOrNumber;
	exposure?: SignalOrNumber;
	volumetricFog?: boolean | VolumetricFogOptions;
	volumetricFogDensity?: SignalOrNumber;
	volumetricFogAnisotropy?: SignalOrNumber;
	volumetricFogNoiseStrength?: SignalOrNumber;
}

/** Options for `Light.*` and `Layer.*Light` (numeric fields also accept live `Signal`s). */
export interface LightOptions
	extends Omit<
		Partial<LightNode>,
		| "intensity"
		| "x"
		| "y"
		| "z"
		| "targetX"
		| "targetY"
		| "targetZ"
		| "radius"
		| "angle"
		| "penumbra"
		| "decay"
		| "width"
		| "height"
		| "rotation"
		| "exposure"
		| "volumetricFog"
		| "volumetricFogDensity"
		| "volumetricFogAnisotropy"
		| "volumetricFogNoiseStrength"
	> {
	intensity?: SignalOrNumber;
	x?: SignalOrNumber;
	y?: SignalOrNumber;
	z?: SignalOrNumber;
	targetX?: SignalOrNumber;
	targetY?: SignalOrNumber;
	targetZ?: SignalOrNumber;
	radius?: SignalOrNumber;
	angle?: SignalOrNumber;
	penumbra?: SignalOrNumber;
	decay?: SignalOrNumber;
	width?: SignalOrNumber;
	height?: SignalOrNumber;
	rotation?: SignalOrNumber;
	exposure?: SignalOrNumber;
	volumetricFog?: boolean | VolumetricFogOptions;
	volumetricFogDensity?: SignalOrNumber;
	volumetricFogAnisotropy?: SignalOrNumber;
	volumetricFogNoiseStrength?: SignalOrNumber;
}

const LIGHT_SIGNAL_PROPS: ReadonlyArray<{
	prop: LightAnimatableProp;
	fallback: number;
}> = [
	{ prop: "intensity", fallback: 1.0 },
	{ prop: "x", fallback: 0 },
	{ prop: "y", fallback: 0 },
	{ prop: "z", fallback: 0 },
	{ prop: "targetX", fallback: 0 },
	{ prop: "targetY", fallback: 0 },
	{ prop: "targetZ", fallback: 0 },
	{ prop: "radius", fallback: 1000 },
	{ prop: "angle", fallback: 45 },
	{ prop: "penumbra", fallback: 0.2 },
	{ prop: "decay", fallback: 1.0 },
	{ prop: "width", fallback: 240 },
	{ prop: "height", fallback: 140 },
	{ prop: "rotation", fallback: 0 },
	{ prop: "exposure", fallback: 0 },
	{ prop: "volumetricFogDensity", fallback: 0.02 },
	{ prop: "volumetricFogAnisotropy", fallback: 0.55 },
	{ prop: "volumetricFogNoiseStrength", fallback: 0.45 },
];

function isSignalLike(val: unknown): boolean {
	if (!val || typeof val !== "object") return false;
	const obj = val as {
		get?: unknown;
		inputHandleId?: unknown;
		gpuBinding?: unknown;
	};
	return (
		typeof obj.get === "function" ||
		typeof obj.inputHandleId === "string" ||
		typeof obj.gpuBinding === "object"
	);
}

function buildLightNode(
	defaults: LightNode,
	rawOpts: Record<string, unknown>,
): AnimatableNode<LightNode> {
	const cleaned: Record<string, unknown> = { ...defaults, ...rawOpts };
	const signalBindings: Array<[LightAnimatableProp, unknown]> = [];

	for (const { prop, fallback } of LIGHT_SIGNAL_PROPS) {
		const val = cleaned[prop];
		if (isSignalLike(val)) {
			signalBindings.push([prop, val]);
			const defVal = (defaults as unknown as Record<string, unknown>)[prop];
			cleaned[prop] = typeof defVal === "number" ? defVal : fallback;
		}
	}

	const rawVf = cleaned.volumetricFog;
	if (rawVf && typeof rawVf === "object") {
		const vfCopy: Record<string, unknown> = {
			...(rawVf as Record<string, unknown>),
		};
		if (isSignalLike(vfCopy.density)) {
			signalBindings.push(["volumetricFogDensity", vfCopy.density]);
			vfCopy.density = 0.02;
		}
		if (isSignalLike(vfCopy.anisotropy)) {
			signalBindings.push(["volumetricFogAnisotropy", vfCopy.anisotropy]);
			vfCopy.anisotropy = 0.55;
		}
		if (vfCopy.noise && typeof vfCopy.noise === "object") {
			const noiseCopy: Record<string, unknown> = {
				...(vfCopy.noise as Record<string, unknown>),
			};
			if (isSignalLike(noiseCopy.strength)) {
				signalBindings.push(["volumetricFogNoiseStrength", noiseCopy.strength]);
				noiseCopy.strength = 0.45;
			}
			vfCopy.noise = noiseCopy;
		}
		cleaned.volumetricFog = vfCopy;
	}

	let node = withAnimation(cleaned as unknown as LightNode);
	if (signalBindings.length > 0) {
		const anim = LayerAnimation.create<LightAnimatableProp>();
		for (const [prop, sig] of signalBindings) {
			anim.signal(prop, sig as never);
		}
		node = node.animate(anim);
	}
	return node;
}

export const Light = {
	/**
	 * The scene's world: a procedural studio environment that lights and
	 * reflects off every surface, plus exposure, tone mapping, fog and
	 * volumetric light shafts. Adding one switches the scene to physically
	 * based shading (GGX, real `roughness` / `metallic`, `emissive` that
	 * blooms past white). Pass a `.hdr` or `.exr` path instead of a preset name to light
	 * and reflect from a captured equirectangular panorama:
	 * `Light.environment("assets/hdri/studio.hdr", { intensity: 1.5 })`.
	 */
	environment: (
		presetOrOptions:
			| EnvironmentPreset
			| HdriPath
			| EnvironmentOptions = "studio",
		options: EnvironmentOptions = {},
	): AnimatableNode<LightNode> => {
		const first: EnvironmentOptions =
			typeof presetOrOptions !== "string"
				? presetOrOptions
				: isHdriPath(presetOrOptions)
					? { hdri: presetOrOptions }
					: { preset: presetOrOptions };
		const opts = { ...first, ...options };
		return buildLightNode(
			{
				id: opts.id ?? autoId("environment"),
				kind: "light",
				lightType: "environment",
				preset: "studio",
				intensity: 1,
			},
			opts as Record<string, unknown>,
		);
	},
	ambient: (
		color: string | LightOptions = "#ffffff",
		intensity: SignalOrNumber = 0.5,
		options: LightOptions = {},
	): AnimatableNode<LightNode> => {
		const merged: LightOptions = {
			color: typeof color === "string" ? color : (color.color ?? "#ffffff"),
			intensity,
			...(typeof color === "object" && color),
			...options,
		};
		return buildLightNode(
			{
				id: merged.id ?? autoId("light-ambient"),
				kind: "light",
				lightType: "ambient",
				color: "#ffffff",
				intensity: 0.5,
			},
			merged as Record<string, unknown>,
		);
	},
	directional: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		buildLightNode(
			{
				id: options.id ?? autoId("light-directional"),
				kind: "light",
				lightType: "directional",
				color: options.color ?? "#ffffff",
				intensity: 1.0,
				x: 0,
				y: -1000,
				z: -1000,
				targetX: 0,
				targetY: 0,
				targetZ: 0,
			},
			options as Record<string, unknown>,
		),
	point: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		buildLightNode(
			{
				id: options.id ?? autoId("light-point"),
				kind: "light",
				lightType: "point",
				color: options.color ?? "#ffffff",
				intensity: 1.0,
				x: 0,
				y: 0,
				z: -500,
				radius: 1000,
				decay: 1.0,
			},
			options as Record<string, unknown>,
		),
	spot: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		buildLightNode(
			{
				id: options.id ?? autoId("light-spot"),
				kind: "light",
				lightType: "spot",
				color: options.color ?? "#ffffff",
				intensity: 1.0,
				x: 0,
				y: -500,
				z: -1000,
				targetX: 0,
				targetY: 0,
				targetZ: 0,
				angle: 45,
				penumbra: 0.2,
				radius: 2000,
				decay: 1.0,
			},
			options as Record<string, unknown>,
		),
	/**
	 * A rectangular area light (studio softbox / LED panel / neon window)
	 * with solid-angle diffuse illumination and representative-point GGX
	 * specular reflections.
	 */
	rect: (options: LightOptions = {}): AnimatableNode<LightNode> =>
		buildLightNode(
			{
				id: options.id ?? autoId("light-rect"),
				kind: "light",
				lightType: "rect",
				color: options.color ?? "#ffffff",
				intensity: 1.0,
				x: 0,
				y: -300,
				z: -800,
				targetX: 0,
				targetY: 0,
				targetZ: 0,
				width: 240,
				height: 140,
				twoSided: false,
				radius: 2000,
				decay: 1.5,
			},
			options as Record<string, unknown>,
		),
};

export {
	type PreviewCloseReason,
	type PreviewOptions,
	type PreviewSession,
	type PreviewSource,
	startPreview,
} from "./preview/index.js";
export {
	type AudioQaStats,
	type ChunkPlan,
	type ChunkPlanOptions,
	computeGridLayout,
	describeGpu,
	type FrameCostSample,
	type FrameGridOptions,
	type FrameGridRenderable,
	type FrameSamplePoint,
	formatQaReport,
	type GpuAdapterDescription,
	HeadlessMediaRenderer,
	HeadlessWebGPURenderer,
	type PlannedChunk,
	planChunks,
	type QaIssue,
	type QaSegment,
	type RenderProgress,
	renderFrameGrid,
	renderSemaphore,
	resetRenderCaches,
	resolveSamplePoints,
	type StitchOptions,
	type StitchResult,
	stitchChunks,
	type VideoQaOptions,
	type VideoQaReport,
	type VideoQaStats,
} from "./renderer/index.js";

export function section(
	source: string | MediaNode | Composition,
	targetOrOptions: ObjectTrackSignals | SectionOptions = {},
	options: SectionOptions = {},
): SectionNode {
	return Layer.section(source, targetOrOptions, options);
}

export function blurRegion(
	sourceOrLayer: string | AnimatableNode<MediaNode>,
	target: ObjectTrackSignals,
	options: Partial<BlurProps> & {
		borderRadius?: number;
		padding?: number;
		borderColor?: string;
		borderWidth?: number;
	} = {},
): AnimatableNode<MediaNode> | AnimatableNode<BoxNode> {
	if (typeof sourceOrLayer === "object" && "blurRegion" in sourceOrLayer) {
		return (sourceOrLayer as AnimatableNode<MediaNode>).blurRegion(
			target,
			options,
		);
	}
	return Layer.blurTrackedRegion(sourceOrLayer as string, target, options);
}

export function editTrackedRegion(
	source: string | MediaNode,
	target: ObjectTrackSignals,
	options: TrackedRegionOptions = {},
): SectionNode {
	return Layer.section(source, target, options);
}

export const Effect = Object.assign(CoreEffect, effectFactories, {
	blur: (config?: BlurProps) => new Blur(config),
	vignette: (config?: VignetteProps) => new Vignette(config),
	colorBalance: (config?: ColorBalanceProps) => new ColorBalance(config),
	colorKey: (config?: ColorKeyProps) => new ColorKey(config),
	levels: (config?: LevelsProps) => new Levels(config),
	filmGrain: (config?: FilmGrainProps) => new FilmGrain(config),
	curves: (config?: CurvesProps) => new Curves(config),
	selectiveColor: (config?: SelectiveColorProps) => new SelectiveColor(config),
	gradientMap: (config?: GradientMapProps) => new GradientMap(config),
	shadowsHighlights: (config?: ShadowsHighlightsProps) =>
		new ShadowsHighlights(config),
	applyLut: (config?: ApplyLUTProps) => new ApplyLUT(config),
	unsharpMask: (config?: UnsharpMaskProps) => new UnsharpMask(config),
	highPass: (config?: HighPassProps) => new HighPass(config),
	halftoneScreen: (config?: HalftoneScreenProps) => new HalftoneScreen(config),
	tileOffset: (config?: TileOffsetProps) => new TileOffset(config),
	motionBlur: (config?: MotionBlurProps) => new MotionBlur(config),
	ssao: (config?: SSAOProps) => new SSAO(config),
	pbrGlass: (config?: PBRGlassProps) => new PBRGlass(config),
	depthOfField: (config?: DepthOfFieldProps) => new DepthOfField(config),
	crop: (config?: CropProps) => new Crop(config),
	vision: (config?: VisionProps) => new Vision(config),
	relight3d: (config?: Relight3DProps) => new Relight3D(config),
	modulate: (config?: ModulateProps) => new Modulate(config),
	deflicker: (config?: DeflickerProps) => new TemporalDeflicker(config),
	custom: (op: string, config: Record<string, unknown> = {}) =>
		new CustomEffect(op, config),
});

export type Effect<TConfig extends object = Record<string, unknown>> =
	CoreEffect<TConfig>;

// Components: `npx framefields add <name>` copies a component's source into
// the project. The root carries what users touch around them; the authoring
// toolkit (timing, paths, strokes, baking) lives at `framefields/components`.
export {
	type Anchor,
	type AudioLevels,
	after,
	type BaseProps,
	type Cue,
	type Cues,
	defineTheme,
	type MotionPreset,
	pulseKeys,
	type Target,
	type Theme,
	type ThemeInput,
	themes,
	withDefaults,
} from "@framefields/components/toolkit";
export {
	analyzeAudio,
	bindComponent,
	type ComponentNode,
} from "./components/index.js";