Skip to content

Programmatic API

Everything the CLI does is available as an ESM TypeScript API from the package root (src/index.ts re-exports every module). The package is ESM-only ("type": "module", import condition only) and requires Node.js >= 22.

import {
buildReel,
freezeReel,
hydrateReel,
loadStorageConfig,
StorageRegistry,
validateReel,
} from "@mathrunet/rereel";

Unlike the CLI, API functions throw RereelError instead of printing JSON, and return the same result objects the CLI prints.

import {
buildReel,
freezeReel,
loadStorageConfig,
RereelError,
StorageRegistry,
validateReel,
} from "@mathrunet/rereel";
const storage = new StorageRegistry(loadStorageConfig()); // same lookup as the CLI
try {
const frozen = await freezeReel({
reelDir: "./reels/ep01",
propsPath: "./work/props.json",
mixPlanPath: "./work/mix_plan.json",
templateDir: "./remotion-template",
storage,
spec: {
schemaVersion: 1,
kind: "remotion_single",
template: { source: "local", name: "basic", path: "../../remotion-template", composition: "Main" },
video: { width: 1920, height: 1080, aspect: "16:9", fps: 30, chunkFrames: 300 },
slicePreset: "auto",
audioMode: "mix_plan",
},
});
console.log(frozen.lockedCount);
const report = validateReel("./reels/ep01");
if (!report.valid) throw new Error(JSON.stringify(report.errors));
const built = await buildReel({ reelDir: "./reels/ep01", storage });
console.log(`${built.chunksRendered}/${built.chunksTotal} chunks rendered → ${built.outPath}`);
} catch (err) {
if (err instanceof RereelError) {
console.error(err.code, err.message, err.details);
process.exitCode = err.code;
} else {
throw err;
}
}

function freezeReel(options: FreezeOptions): Promise<FreezeResult>;
interface FreezeOptions {
reelDir: string;
spec: RereelSpec;
propsPath?: string;
mixPlanPath?: string;
templateDir?: string;
timingPath?: string;
captionsPath?: string;
chaptersPath?: string;
/** Optional map of local file path -> pre-existing URI (e.g. from asset:// IDs). */
knownUris?: Record<string, string>;
providerName?: string;
tags?: string;
/** Keep local hydrated copies in `<reelDir>/media/` after freezing (default true). */
keepLocalMedia?: boolean;
storage: StorageRegistry;
}
interface FreezeResult {
status: "frozen";
reelDir: string;
lockedCount: number;
storedCount: number;
templateCount: number;
rereelSha256: string;
}

The spec is written as given (only schemaVersion, propsFile, mixPlanFile, lockFile are filled in). Unlike the CLI, this preserves fields such as customSlices, parts, and video.remotionArgs. knownUris (keys resolved to absolute paths) skips provider.store() for files that already have a URI. Behaviour: rereel freeze.

function hydrateReel(options: HydrateOptions): Promise<HydrateResult>;
interface HydrateOptions {
reelDir: string;
templateDir?: string;
storage: StorageRegistry;
/** If true, do not fetch from remote storage; fail if any storage asset is missing locally. */
offline?: boolean;
}
interface HydrateResult {
status: "hydrated";
reelDir: string;
total: number;
fetched: number;
cached: number;
templateStatic: number;
}

Behaviour: rereel hydrate.

function validateReel(
reelDirInput: string,
options?: { offline?: boolean; checkMediaOnDisk?: boolean },
): ValidateResult;
interface ValidationIssue {
level: "error" | "warning";
code: string;
path: string;
message: string;
}
interface ValidateResult {
valid: boolean;
reelDir: string;
errors: ValidationIssue[];
warnings: ValidationIssue[];
}

Synchronous, and does not throw for invalid bundles. offline is accepted but currently has no effect. Issue codes: rereel validate.

function inspectReel(reelDirInput: string, sceneFilter?: string): InspectResult;
interface InspectResult {
reelDir: string;
kind: RereelSpec["kind"];
video: RereelSpec["video"];
audioMode: RereelSpec["audioMode"];
lockedAssets: number;
scenes: Array<{ id: string; startSec?: number; endSec?: number; durationSec?: number; text?: string }>;
cutsCount: number;
narrationSegments: number;
bgmCues: number;
sfxCues: number;
}
function buildReel(options: BuildReelOptions): Promise<BuildReelResult>;
interface BuildReelOptions {
reelDir: string;
storage: StorageRegistry;
outPath?: string;
templateDir?: string;
offline?: boolean;
/** Optional custom renderer hook for testing or alternative renderers. */
renderChunkFn?: (args: {
startFrame: number;
endFrame: number;
chunkPath: string;
propsPath: string;
workTemplateDir: string;
spec: RereelSpec;
}) => void;
}
interface BuildReelResult {
status: "built";
reelDir: string;
outPath: string;
sha256: string;
totalFrames: number;
fps: number;
chunksTotal: number;
chunksRendered: number;
chunksReused: number;
}

When renderChunkFn is provided, template staging is skipped entirely (workTemplateDir is the bundle directory, the template hash is the constant "custom-renderer", and the entry defaults to template.entry ?? "src/index.ts"). The function must synchronously write an MP4 with exactly endFrame − startFrame + 1 frames to chunkPath. Behaviour: rereel build.

function cutRetakesAndSilence(options: CutRetakesOptions): CutRetakesResult;
interface CutRetakesOptions {
inputPath: string;
asrJsonPath?: string; // Whisper JSON with word timestamps
scriptPath?: string; // target script for script-guided retake removal
silenceDb?: number; // default -40
minSilenceSec?: number; // default 0.45
keepGapSec?: number; // default 0.14
padEdgeSec?: number; // default 0.05
fadeSec?: number; // default 0.015
targetDurationSec?: number;
maxStretchRatio?: number; // default 0.15
}
function detectSilenceIntervals(inputPath: string, silenceDb?: number, minSilenceSec?: number): Array<[number, number]>;

Also exported: AsrJson, AsrSegment, AsrWord. Behaviour and result shape: rereel cut-retakes, cuts.json.

function rippleShiftReel(options: RippleShiftOptions): {
status: "patched"; atSec: number; deltaSec: number; filesUpdated: string[];
};
interface RippleShiftOptions { reelDir: string; atSec: number; deltaSec: number }
function trimNarrationSegment(
reelDirInput: string,
segmentId: string,
updates: { srcStartSec?: number; durationSec?: number; startSec?: number; gainDb?: number },
): { status: "patched"; segmentId: string };
function swapLockedAsset(
reelDirInput: string,
oldRef: string,
newRef: string,
newEntry?: RereelLock["items"][string],
): { status: "patched"; replacements: number };

swapLockedAsset additionally writes newEntry into the lockfile under newRef when provided (the CLI never passes it). The old entry is not removed. Behaviour: rereel patch.


interface StorageProvider {
readonly name: string;
/** Upload/store a local asset and return its canonical URI. */
store(options: StoreAssetOptions): Promise<string>;
/** Fetch/copy an asset identified by URI to destPath. */
resolve(options: ResolveAssetOptions): Promise<void>;
}
interface StoreAssetOptions { localPath: string; sha256: string; kind: MediaKind; tags?: string }
interface ResolveAssetOptions { uri: string; destPath: string; expectedSha256?: string }
function defaultStorageConfig(): StorageConfig;
function loadStorageConfig(configPath?: string, cwd?: string): StorageConfig;
function createStorageProvider(name: string, cfg: StorageProviderConfig): StorageProvider;
class StorageRegistry {
constructor(config: StorageConfig);
get defaultProviderName(): string;
/** Returns (and caches) the named provider, or the default provider when name is empty. */
get(name?: string): StorageProvider;
}
class LocalCacheStorageProvider implements StorageProvider { constructor(name: string, cfg: StorageProviderConfig) }
class S3CompatibleStorageProvider implements StorageProvider { constructor(name: string, cfg: StorageProviderConfig) }
class HttpStorageProvider implements StorageProvider { constructor(name: string, cfg: StorageProviderConfig) }
class CommandStorageProvider implements StorageProvider { constructor(name: string, cfg: StorageProviderConfig) }

loadStorageConfig follows the lookup rules. cwd defaults to process.cwd() and only affects the ./rereel.storage.json candidate. StorageRegistry.get throws RereelError (code 2, details.available) for unknown names.

The registry only instantiates the four built-in types. To use a custom in-process provider, call it directly or wrap it in a command provider.


function compileAudio(options: CompileAudioOptions): CompileAudioResult;
interface CompileAudioOptions {
plan: MixPlan;
baseDir: string; // media paths in the plan resolve against this
outDir: string; // writes mix.wav and stems/
scope: "chapter" | "final";
videoPath?: string; // muted video to mux onto
outVideoPath?: string; // default <outDir>/output.mp4
timeoutMs?: number; // per FFmpeg call, default 600000
}
interface CompileAudioResult {
status: "mixed";
scope: "chapter" | "final";
durationSec: number;
mixWav: string;
stems: Record<string, string>; // narration, bgm, sfx, brand → absolute .wav paths
video?: string;
videoSha256?: string;
}
function measureLoudness(filePath: string): { integratedLufs: number | null; truePeakDbfs: number | null };
function deriveMixPlanFromProps(props: Record<string, unknown>, durationSec: number): MixPlan | null;
const DEFAULT_AUDIO_SETTINGS: AudioSettings;

scope: "final" applies two-pass loudnorm. "chapter" writes the limited premix as-is and extends BGM by crossfade_sec for a later merge. plan.duration_sec must be positive. Mix plan semantics: mix_plan.json.

import { compileAudio, readJsonFile, type MixPlan } from "@mathrunet/rereel";
const res = compileAudio({
plan: readJsonFile<MixPlan>("./reels/ep01/mix_plan.json"),
baseDir: "./reels/ep01",
outDir: "./reels/ep01/build",
scope: "final",
videoPath: "./reels/ep01/build/video.muted.mp4",
outVideoPath: "./reels/ep01/build/output.mp4",
});

function detectSlicePreset(props: Record<string, unknown>): SlicePreset;
function extractPropsSlice(
props: Record<string, unknown>,
startFrame: number,
endFrame: number,
fps: number,
preset?: SlicePreset, // default "auto"
customSlices?: CustomSliceExtractor[],
): Record<string, unknown>;
interface SliceHashInput {
props: Record<string, unknown>;
lock: RereelLock;
templateSha256: string;
composition: string;
entry: string;
fps: number;
imageFormat: string;
jpegQuality: number;
extraArgs: string[];
startFrame: number;
endFrame: number;
slicePreset?: SlicePreset;
customSlices?: CustomSliceExtractor[];
}
function computeChunkSliceHash(input: SliceHashInput): string;

Use these to predict which chunks an edit will invalidate:

import { computeChunkSliceHash, readJsonFile, type RereelLock } from "@mathrunet/rereel";
const before = readJsonFile<Record<string, unknown>>("props.before.json");
const after = readJsonFile<Record<string, unknown>>("props.json");
const lock = readJsonFile<RereelLock>("rereel.lock.json");
const base = { lock, templateSha256: "x", composition: "Main", entry: "src/index.ts", fps: 30,
imageFormat: "jpeg", jpegQuality: 80, extraArgs: [] };
for (let start = 0; start < 1800; start += 300) {
const end = Math.min(1800, start + 300) - 1;
const a = computeChunkSliceHash({ ...base, props: before, startFrame: start, endFrame: end });
const b = computeChunkSliceHash({ ...base, props: after, startFrame: start, endFrame: end });
if (a !== b) console.log(`chunk ${start}-${end} will re-render`);
}

Rules: slice presets.

const ENTRY_CANDIDATES: string[]; // ["src/index.ts", "src/index.tsx", "src/index.js", "src/Root.tsx"]
function computeTemplateSourceSha(templateDir: string): string;
function detectTemplateEntry(templateDir: string, explicitEntry?: string): string;
function resolveRemotionBin(templateDir: string): string[];
function resolveTemplateDirectory(template: TemplateRef, reelDir: string, storage: StorageRegistry): Promise<string>;
function stageTemplateWorkspace(
spec: RereelSpec,
reelDir: string,
storage: StorageRegistry,
explicitTemplateDir?: string,
): Promise<{ workTemplateDir: string; sourceTemplateDir: string }>;

class RereelError extends Error {
readonly code: number; // exit code, default 1
readonly details?: Record<string, unknown>; // spread into the CLI error JSON
constructor(message: string, code?: number, details?: Record<string, unknown>);
}
const EXIT_OK = 0;
const EXIT_FAIL = 1;
const EXIT_USAGE = 2;
const EXIT_DEPENDENCY = 3;
const EXIT_COMMAND = 4;

See Exit codes.

Export Signature Notes
canonicalJson (value: unknown) => string Sorted keys, undefined dropped.
sha256String / sha256Json / sha256File (text) / (value) / (filePath) => string sha256Json hashes canonicalJson.
readJsonFile <T>(filePath: string) => T Throws code 2 when missing or invalid.
writeJsonFile (filePath: string, data: unknown) => void Creates parent dirs, 2-space indent, trailing newline.
fastCopyFile (src: string, dest: string) => void Copy-on-write clone with fallback.
detectMediaKind (filePath: string) => MediaKind By extension.
runProcess (cmd, args, { cwd?, timeoutMs?, allowFailure?, env? }) => RunResult Throws code 3 on ENOENT, 4 on non-zero exit.
ffmpegBin / ffprobeBin () => string Honour REREEL_FFMPEG_BIN / REREEL_FFPROBE_BIN.
filterScriptArgs (path: string) => string[] -/filter_complex (FFmpeg 7.1+) or -filter_complex_script.
probeMedia (filePath: string) => MediaProbeInfo durationSec, width, height, fps, avgFps, vfr, nbFrames, hasAudio, hasVideo.
countVideoFrames (filePath: string) => number -1 if unknown.
fileByteSize (filePath: string) => number
parseSrt / formatSrt (content) => SrtCue[] / (cues) => string SrtCue = { index, startSec, endSec, text }.

All types from types.ts (RereelSpec, TemplateRef, VideoSpec, RereelLock, LockedAsset, MixPlan, AudioSettings, StorageConfig, CutRetakesResult, …) are exported as well. They are documented in File formats.