@bendyline/squisq-cli 1.2.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -30
- package/dist/api-6KN3F6IQ.js +34 -0
- package/dist/api-6KN3F6IQ.js.map +1 -0
- package/dist/api.d.ts +172 -36
- package/dist/api.js +263 -121
- package/dist/api.js.map +1 -1
- package/dist/chunk-ESFEFKY4.js +175 -0
- package/dist/chunk-ESFEFKY4.js.map +1 -0
- package/dist/chunk-JEE26SZS.js +668 -0
- package/dist/chunk-JEE26SZS.js.map +1 -0
- package/dist/chunk-VM3ZFP3J.js +177 -0
- package/dist/chunk-VM3ZFP3J.js.map +1 -0
- package/dist/index.js +116 -539
- package/dist/index.js.map +1 -1
- package/dist/nativeEncoder-IQPN2RMC.js +15 -0
- package/dist/nativeEncoder-IQPN2RMC.js.map +1 -0
- package/dist/nativeEncoder-WHUIQZLL.js +16 -0
- package/dist/nativeEncoder-WHUIQZLL.js.map +1 -0
- package/package.json +7 -7
- package/dist/nativeEncoder-2HGWDEZZ.js +0 -86
- package/dist/nativeEncoder-2HGWDEZZ.js.map +0 -1
- package/dist/nativeEncoder-DLLAT2RT.js +0 -88
- package/dist/nativeEncoder-DLLAT2RT.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api.ts","../src/util/detectFfmpeg.ts","../src/util/audioMix.ts","../src/util/coverPreRoll.ts","../src/registry.ts","../src/util/readInput.ts"],"sourcesContent":["/**\n * Programmatic Rendered-Media API\n *\n * Provides library-style entry points for rendering Squisq documents to MP4\n * or animated GIF from Node.js callers (e.g., Qualla's pipeline). This avoids\n * the need to shell\n * out to the `squisq video` CLI and gives callers full control over the Doc,\n * MemoryContentContainer, and encoding options.\n *\n * Orchestrates the full pipeline: Doc → render HTML → Playwright frame capture → FFmpeg encode.\n *\n * Usage:\n * import { renderDocToMp4 } from '@bendyline/squisq-cli/api';\n *\n * await renderDocToMp4(doc, container, {\n * outputPath: '/tmp/output.mp4',\n * fps: 30,\n * quality: 'normal',\n * orientation: 'landscape',\n * });\n *\n * await renderDocToGif(doc, container, {\n * outputPath: '/tmp/output.gif',\n * animationsEnabled: false,\n * });\n */\n\nimport type { Doc } from '@bendyline/squisq/schemas';\nimport { resolveMediaSchedule } from '@bendyline/squisq/schemas';\nimport { flattenBlocks } from '@bendyline/squisq/doc';\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport type { GifDither, VideoQuality, VideoOrientation } from '@bendyline/squisq-video';\nimport { ffmpegGifOutputArgs, generateRenderHtml } from '@bendyline/squisq-video';\nimport { resolveDimensions } from '@bendyline/squisq-video';\nimport { convert as formatsConvert } from '@bendyline/squisq-formats';\nimport type {\n ConvertSource,\n ConvertOptions,\n ConversionResult,\n FormatId,\n} from '@bendyline/squisq-formats';\nimport { detectFfmpegDetailed } from './util/detectFfmpeg.js';\nimport { buildMixedAudioTrack } from './util/audioMix.js';\nimport { resolveAppliedCoverPreRoll } from './util/coverPreRoll.js';\nimport { GIF_EXPORT_DEFAULTS } from './util/nativeEncoder.js';\nimport { createCliRegistry } from './registry.js';\nimport type { GifFormatOptions, Mp4FormatOptions } from './registry.js';\n\n// Re-export utility types and functions callers may need\nexport type { GifDither, VideoQuality, VideoOrientation } from '@bendyline/squisq-video';\nexport { MemoryContentContainer } from '@bendyline/squisq/storage';\nexport { readInput } from './util/readInput.js';\nexport type { ReadInputResult } from './util/readInput.js';\nexport {\n GIF_EXPORT_DEFAULTS,\n framesToGifNative,\n framesToGifNativeBytes,\n framesToMp4Native,\n framesToMp4NativeBytes,\n} from './util/nativeEncoder.js';\nexport type { GifExportOptions } from './util/nativeEncoder.js';\nexport type { GifFormatOptions, Mp4FormatOptions } from './registry.js';\n\n/** Convert options with the CLI-only rendered-media adapters strongly typed. */\nexport type CliConvertOptions = Omit<ConvertOptions, 'formatOptions'> & {\n formatOptions?: ConvertOptions['formatOptions'] & {\n mp4?: Mp4FormatOptions;\n gif?: GifFormatOptions;\n };\n};\n\n// ── Format registry / convert() surface ───────────────────────────\n// Re-export the CLI's format registry factory plus the registry types and the\n// structured error, so `@bendyline/squisq-cli/api` is a one-stop programmatic\n// front door for both video rendering and document conversion.\nexport { createCliRegistry } from './registry.js';\nexport { ConversionError } from '@bendyline/squisq-formats';\nexport type {\n ConvertSource,\n ConvertOptions,\n ConversionResult,\n FormatId,\n FormatRegistry,\n FormatDefinition,\n NormalizedInput,\n ConversionErrorCode,\n ConversionErrorOptions,\n} from '@bendyline/squisq-formats';\n\n/**\n * Convert a document to a target format using the CLI's format registry.\n *\n * This is a thin, pre-bound wrapper over `convert()` from\n * `@bendyline/squisq-formats`: it injects the CLI registry (which adds the\n * `mp4` and `gif` formats on top of every built-in exporter) and a default\n * `resolvePlayerScript` that lazily loads the standalone player IIFE bundle\n * (required for HTML/EPUB-style exports). Callers may override either via\n * `options`.\n *\n * @param source - A bytes / markdown / doc {@link ConvertSource}.\n * @param to - Target format id (`docx`, `pdf`, `pptx`, `html`, `mp4`, `gif`, …).\n * @param options - Conversion options; `registry` and `resolvePlayerScript`\n * default to the CLI's values but can be overridden.\n * @returns The encoded bytes plus mime type, suggested filename, and warnings.\n * @throws {@link ConversionError} on any failure, with a stable `code`.\n */\nexport async function convert(\n source: ConvertSource,\n to: FormatId,\n options: CliConvertOptions = {},\n): Promise<ConversionResult> {\n return formatsConvert(source, to, {\n registry: createCliRegistry(),\n resolvePlayerScript: () =>\n import('@bendyline/squisq-react/standalone-source').then((m) => m.PLAYER_BUNDLE),\n ...options,\n });\n}\n\n/** Options for renderDocToMp4. */\nexport interface RenderDocToMp4Options {\n /** Output file path for the MP4. */\n outputPath: string;\n\n /** Frames per second (default: 30). */\n fps?: number;\n\n /** Encoding quality preset (default: 'normal'). */\n quality?: VideoQuality;\n\n /** Video orientation (default: 'landscape'). */\n orientation?: VideoOrientation;\n\n /** Override video width in pixels. */\n width?: number;\n\n /** Override video height in pixels. */\n height?: number;\n\n /** Caption style to bake into the video (default: none). */\n captionStyle?: 'standard' | 'social';\n\n /** Render layer animations and block transitions (default: true). */\n animationsEnabled?: boolean;\n\n /**\n * Seconds of cover-slide pre-roll before the story starts (default: 0).\n *\n * Note: the `squisq video` CLI defaults its `--cover-preroll` flag to 2\n * seconds; this programmatic API deliberately defaults to 0 so library\n * callers get exactly the duration they ask for.\n */\n coverPreRoll?: number;\n\n /**\n * Progress callback. Called with a phase name and 0-100 percentage.\n */\n onProgress?: (phase: string, percent: number) => void;\n}\n\n/** Options for rendering a document to an animated GIF. */\nexport interface RenderDocToGifOptions {\n /** Output file path for the GIF. */\n outputPath: string;\n /** Frames per second (default: 10). */\n fps?: number;\n /** Viewport orientation (default: landscape). */\n orientation?: VideoOrientation;\n /** Override output width (default: 960 landscape / 540 portrait). */\n width?: number;\n /** Override output height (default: 540 landscape / 960 portrait). */\n height?: number;\n /** Caption style to bake into the GIF (default: none). */\n captionStyle?: 'standard' | 'social';\n /** Seconds of cover-slide pre-roll (default: 0). */\n coverPreRoll?: number;\n /** Render layer animations and block transitions (default: false). */\n animationsEnabled?: boolean;\n /** Number of repeats; 0 loops forever and -1 disables looping. */\n loop?: number;\n /** Palette size, from 2 through 256 (default: 256). */\n maxColors?: number;\n /** Palette dithering algorithm (default: sierra2_4a). */\n dither?: GifDither;\n /** Bayer strength when dither is bayer (0-5, default: 3). */\n bayerScale?: number;\n /** Progress callback. */\n onProgress?: (phase: string, percent: number) => void;\n}\n\n/** Result returned by renderDocToMp4. */\nexport interface RenderDocToMp4Result {\n /** Duration of the rendered video in seconds (including pre-roll). */\n duration: number;\n\n /** Number of frames captured. */\n frameCount: number;\n\n /** Output file path. */\n outputPath: string;\n}\n\n/** Result returned by renderDocToGif. */\nexport interface RenderDocToGifResult extends RenderDocToMp4Result {\n /** Non-fatal fidelity warnings, including GIF's lack of audio. */\n warnings: string[];\n}\n\n/** Minimal standalone-player contract used inside Playwright's page realm. */\ninterface BrowserRenderAPI {\n seekTo(time: number): Promise<void>;\n getDuration(): number;\n hasCoverBlock(): boolean;\n showCover(): Promise<void>;\n hideCover(): Promise<void>;\n}\n\ninterface BrowserPlayerHandle {\n getRenderAPI(): BrowserRenderAPI | null;\n}\n\ninterface BrowserStandalonePlayer {\n getHandle(element: Element): BrowserPlayerHandle | undefined;\n}\n\ninterface SquisqBrowserWindow {\n SquisqPlayer?: BrowserStandalonePlayer;\n}\n\ninterface CaptureDocFramesOptions {\n fps: number;\n width: number;\n height: number;\n captionStyle?: 'standard' | 'social';\n coverPreRoll: number;\n animationsEnabled: boolean;\n onProgress?: (phase: string, percent: number) => void;\n}\n\ninterface CapturedDocFrames {\n frames: Uint8Array[];\n totalDuration: number;\n appliedCoverPreRoll: number;\n ffmpegPath: string;\n}\n\n/** Capture deterministic PNG frames once, independent of the output encoder. */\nasync function captureDocFrames(\n doc: Doc,\n container: ContentContainer,\n options: CaptureDocFramesOptions,\n): Promise<CapturedDocFrames> {\n const { fps, width, height, captionStyle, coverPreRoll, animationsEnabled, onProgress } = options;\n\n resolveAppliedCoverPreRoll(coverPreRoll, true);\n const ffmpegPath = (await detectFfmpegDetailed())?.path ?? null;\n if (!ffmpegPath) {\n throw new Error(\n 'ffmpeg is required but not found in PATH.\\n' +\n 'Install it with:\\n' +\n ' macOS: brew install ffmpeg\\n' +\n ' Ubuntu: sudo apt install ffmpeg\\n' +\n ' Windows: winget install ffmpeg\\n' +\n 'Or: npm install ffmpeg-static, or set SQUISQ_FFMPEG to an ffmpeg binary.',\n );\n }\n\n onProgress?.('collecting media', 0);\n const { collectImagePaths } = await import('@bendyline/squisq-formats/html');\n const images = new Map<string, ArrayBuffer>();\n for (const imgPath of collectImagePaths(doc)) {\n const data = await container.readFile(imgPath);\n if (data) images.set(imgPath, data);\n }\n\n // Audio remains available to the headless player even for silent GIF output:\n // narration metadata and media duration still define the visual timeline.\n const audio = new Map<string, ArrayBuffer>();\n for (const seg of doc.audio?.segments ?? []) {\n const data = await container.readFile(seg.src);\n if (data) {\n audio.set(seg.src, data);\n audio.set(seg.name, data);\n }\n }\n\n const mediaSrcs = new Set<string>(resolveMediaSchedule(doc).map((clip) => clip.src));\n for (const block of flattenBlocks(doc.blocks)) {\n for (const layer of block.layers ?? []) {\n if (layer.type === 'video') mediaSrcs.add(layer.content.src);\n }\n }\n for (const src of mediaSrcs) {\n if (images.has(src)) continue;\n const data = await container.readFile(src);\n if (data) images.set(src, data);\n }\n\n onProgress?.('generating render HTML', 10);\n const { PLAYER_BUNDLE } = await import('@bendyline/squisq-react/standalone-source');\n const renderHtml = generateRenderHtml(doc, {\n playerScript: PLAYER_BUNDLE,\n images,\n audio: audio.size > 0 ? audio : undefined,\n width,\n height,\n captionStyle,\n animationsEnabled,\n });\n\n onProgress?.('launching browser', 15);\n const { chromium } = await import('playwright-core');\n let browser: import('playwright-core').Browser;\n try {\n browser = await chromium.launch({ headless: true });\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message.split('\\n')[0] : String(err);\n throw new Error(\n 'Playwright Chromium is not installed. Run: npx playwright install chromium\\n' +\n `(launch failed: ${detail})`,\n );\n }\n\n const page = await browser.newPage({ viewport: { width, height } });\n const pageErrors: string[] = [];\n page.on('pageerror', (err) => pageErrors.push(err.message));\n let renderAPI: import('playwright-core').JSHandle<BrowserRenderAPI> | null = null;\n\n try {\n await page.setContent(renderHtml, { waitUntil: 'load' });\n await page.waitForTimeout(500);\n try {\n await page.waitForFunction(\n () => {\n const root = document.getElementById('squisq-root');\n const player = (window as unknown as SquisqBrowserWindow).SquisqPlayer;\n return root ? player?.getHandle(root)?.getRenderAPI() != null : false;\n },\n { timeout: 15000 },\n );\n } catch {\n const errorDetail = pageErrors.length\n ? `\\nPage errors:\\n ${pageErrors.join('\\n ')}`\n : '\\nNo page errors captured — the player may have failed to mount.';\n throw new Error(\n `The standalone player failed to boot in headless Chromium. ` +\n `Render API did not initialize within 15 seconds.${errorDetail}`,\n );\n }\n\n renderAPI = await page.evaluateHandle(() => {\n const root = document.getElementById('squisq-root');\n const player = (window as unknown as SquisqBrowserWindow).SquisqPlayer;\n const api = root ? player?.getHandle(root)?.getRenderAPI() : null;\n if (!api) throw new Error('Squisq render API disappeared after initialization.');\n return api;\n });\n const docDuration = await renderAPI.evaluate((api) => api.getDuration());\n if (docDuration <= 0) throw new Error('Document has zero duration — nothing to render');\n\n const hasCover =\n coverPreRoll > 0 ? await renderAPI.evaluate((api) => api.hasCoverBlock()) : false;\n const appliedCoverPreRoll = resolveAppliedCoverPreRoll(coverPreRoll, hasCover);\n const storyFrameCount = Math.ceil(docDuration * fps);\n const preRollFrameCount = Math.ceil(appliedCoverPreRoll * fps);\n const totalFrames = preRollFrameCount + storyFrameCount;\n const frames: Uint8Array[] = [];\n onProgress?.('capturing frames', 20);\n\n if (preRollFrameCount > 0) {\n await renderAPI.evaluate((api) => api.showCover());\n await page.waitForTimeout(100);\n const coverFrame = new Uint8Array(await page.screenshot({ type: 'png' }));\n for (let i = 0; i < preRollFrameCount; i++) frames.push(coverFrame);\n await renderAPI.evaluate((api) => api.hideCover());\n }\n\n const frameInterval = 1 / fps;\n for (let i = 0; i < storyFrameCount; i++) {\n const time = i * frameInterval;\n await renderAPI.evaluate((api, t: number) => api.seekTo(t), time);\n frames.push(new Uint8Array(await page.screenshot({ type: 'png' })));\n if (i % Math.max(1, Math.floor(fps / 2)) === 0 || i === storyFrameCount - 1) {\n onProgress?.('capturing frames', 20 + Math.round((frames.length / totalFrames) * 60));\n }\n }\n\n return {\n frames,\n totalDuration: docDuration + appliedCoverPreRoll,\n appliedCoverPreRoll,\n ffmpegPath,\n };\n } finally {\n await renderAPI?.dispose();\n await browser.close();\n }\n}\n\n/** Render a Doc + media container to an MP4 video file. */\nexport async function renderDocToMp4(\n doc: Doc,\n container: ContentContainer,\n options: RenderDocToMp4Options,\n): Promise<RenderDocToMp4Result> {\n const fps = options.fps ?? 30;\n const quality = options.quality ?? 'normal';\n const orientation = options.orientation ?? 'landscape';\n const dimensions = resolveDimensions({\n orientation,\n width: options.width,\n height: options.height,\n fps,\n quality,\n });\n const capture = await captureDocFrames(doc, container, {\n fps,\n width: dimensions.width,\n height: dimensions.height,\n captionStyle: options.captionStyle,\n coverPreRoll: options.coverPreRoll ?? 0,\n animationsEnabled: options.animationsEnabled ?? true,\n onProgress: options.onProgress,\n });\n\n options.onProgress?.('encoding video', 80);\n const encodingAudio = await buildMixedAudioTrack(\n doc,\n container,\n capture.ffmpegPath,\n capture.appliedCoverPreRoll,\n );\n const { framesToMp4Native } = await import('./util/nativeEncoder.js');\n await framesToMp4Native(capture.ffmpegPath, capture.frames, encodingAudio, options.outputPath, {\n fps,\n quality,\n orientation,\n width: dimensions.width,\n height: dimensions.height,\n onProgress: (percent, phase) =>\n options.onProgress?.(`encoding: ${phase}`, 80 + Math.round(percent * 0.2)),\n });\n options.onProgress?.('done', 100);\n return {\n duration: capture.totalDuration,\n frameCount: capture.frames.length,\n outputPath: options.outputPath,\n };\n}\n\n/** Render a Doc + media container to a silent animated GIF. */\nexport async function renderDocToGif(\n doc: Doc,\n container: ContentContainer,\n options: RenderDocToGifOptions,\n): Promise<RenderDocToGifResult> {\n const fps = options.fps ?? GIF_EXPORT_DEFAULTS.fps;\n if (!Number.isFinite(fps) || fps <= 0 || fps > 100) {\n throw new RangeError('GIF FPS must be a finite number between 1 and 100.');\n }\n const orientation = options.orientation ?? 'landscape';\n const portrait = orientation === 'portrait';\n const width =\n options.width ?? (portrait ? GIF_EXPORT_DEFAULTS.height : GIF_EXPORT_DEFAULTS.width);\n const height =\n options.height ?? (portrait ? GIF_EXPORT_DEFAULTS.width : GIF_EXPORT_DEFAULTS.height);\n // Reuse shared dimension validation without inheriting MP4's 1080p defaults.\n resolveDimensions({ orientation, width, height, fps });\n // Validate palette/muxer options before the expensive browser capture.\n ffmpegGifOutputArgs({\n width,\n height,\n loop: options.loop ?? GIF_EXPORT_DEFAULTS.loop,\n maxColors: options.maxColors ?? GIF_EXPORT_DEFAULTS.maxColors,\n dither: options.dither ?? GIF_EXPORT_DEFAULTS.dither,\n bayerScale: options.bayerScale,\n });\n\n const capture = await captureDocFrames(doc, container, {\n fps,\n width,\n height,\n captionStyle: options.captionStyle,\n coverPreRoll: options.coverPreRoll ?? 0,\n animationsEnabled: options.animationsEnabled ?? false,\n onProgress: options.onProgress,\n });\n\n options.onProgress?.('encoding GIF', 80);\n const { framesToGifNative } = await import('./util/nativeEncoder.js');\n await framesToGifNative(capture.ffmpegPath, capture.frames, options.outputPath, {\n fps,\n orientation,\n width,\n height,\n loop: options.loop,\n maxColors: options.maxColors,\n dither: options.dither,\n bayerScale: options.bayerScale,\n onProgress: (percent, phase) =>\n options.onProgress?.(`encoding: ${phase}`, 80 + Math.round(percent * 0.2)),\n });\n options.onProgress?.('done', 100);\n\n const hasAudio =\n (doc.audio?.segments?.length ?? 0) > 0 ||\n resolveMediaSchedule(doc).some((clip) => clip.kind === 'audio');\n return {\n duration: capture.totalDuration,\n frameCount: capture.frames.length,\n outputPath: options.outputPath,\n warnings: hasAudio ? ['Animated GIF does not support audio; audio tracks were omitted.'] : [],\n };\n}\n\n// ── Thumbnail extraction ──────────────────────────────────────────\n\n/** A thumbnail size specification. */\nexport interface ThumbnailSpec {\n /** Label for the thumbnail (used in filename: `{slug}-{width}x{height}.jpg`). */\n name: string;\n /** Output width in pixels. */\n width: number;\n /** Output height in pixels. */\n height: number;\n /** FFmpeg video filter string (e.g., 'scale=1280:720'). */\n filter: string;\n}\n\n/** Options for extractThumbnails. */\nexport interface ExtractThumbnailsOptions {\n /** Path to the source MP4 video. */\n videoPath: string;\n /** Directory to write thumbnails into. */\n outputDir: string;\n /** Base slug for filenames (produces `{slug}-{width}x{height}.jpg`). */\n slug: string;\n /** Thumbnail sizes to generate. */\n sizes: ThumbnailSpec[];\n /** Overwrite existing thumbnails (default: false). */\n force?: boolean;\n}\n\n/**\n * Extract thumbnail images from the first frame of an MP4 video.\n * Produces JPEG files at each specified size using FFmpeg video filters.\n */\nexport async function extractThumbnails(options: ExtractThumbnailsOptions): Promise<void> {\n const { videoPath, outputDir, slug, sizes, force } = options;\n const { existsSync } = await import('node:fs');\n const { join } = await import('node:path');\n const { execFile } = await import('node:child_process');\n\n const ffmpegPath = (await detectFfmpegDetailed())?.path ?? null;\n if (!ffmpegPath) {\n throw new Error(\n 'ffmpeg is required for thumbnail extraction but not found in PATH.\\n' +\n 'Install it with:\\n' +\n ' macOS: brew install ffmpeg\\n' +\n ' Ubuntu: sudo apt install ffmpeg\\n' +\n ' Windows: winget install ffmpeg',\n );\n }\n\n for (const thumb of sizes) {\n const outputPath = join(outputDir, `${slug}-${thumb.width}x${thumb.height}.jpg`);\n if (!force && existsSync(outputPath)) continue;\n\n await new Promise<void>((resolve, reject) => {\n execFile(\n ffmpegPath,\n ['-y', '-i', videoPath, '-vf', thumb.filter, '-frames:v', '1', '-q:v', '2', outputPath],\n { timeout: 30_000 },\n (err) => {\n if (err) reject(new Error(`Thumbnail extraction failed (${thumb.name}): ${err.message}`));\n else resolve();\n },\n );\n });\n }\n}\n","/**\n * detectFfmpeg\n *\n * Locates a native ffmpeg binary. Resolution order:\n * 1. `SQUISQ_FFMPEG` environment variable — verified by running\n * `<path> -version`. A value that is set but broken is a hard error\n * (never silently ignored), so misconfiguration surfaces immediately.\n * 2. System PATH lookup (`which` on macOS/Linux, `where` on Windows).\n * 3. The optional `ffmpeg-static` npm package, when the user has installed\n * it themselves. It is deliberately NOT a dependency of the CLI — the\n * import is opportunistic and falls through cleanly when absent.\n */\n\nimport { execFile } from 'node:child_process';\n\n/** Where a detected ffmpeg binary came from. */\nexport type FfmpegSource = 'env' | 'path' | 'ffmpeg-static';\n\n/** A successfully detected ffmpeg binary. */\nexport interface FfmpegDetection {\n /** Absolute path to the ffmpeg binary. */\n path: string;\n /** Which resolution step found it. */\n source: FfmpegSource;\n}\n\n/** Run a command and resolve with trimmed stdout, or null on any failure. */\nfunction run(command: string, args: string[]): Promise<string | null> {\n return new Promise((resolve) => {\n execFile(command, args, { timeout: 5000 }, (err, stdout) => {\n if (err || !stdout.trim()) {\n resolve(null);\n return;\n }\n resolve(stdout.trim());\n });\n });\n}\n\n/**\n * Run `<path> -version` and return the first line of output\n * (e.g. \"ffmpeg version 7.1 ...\"), or null when the binary fails to run.\n */\nexport async function getFfmpegVersion(path: string): Promise<string | null> {\n const out = await run(path, ['-version']);\n return out ? out.split('\\n')[0].trim() : null;\n}\n\n/**\n * Detect ffmpeg and report which source found it (see module doc for the\n * resolution order). Returns null when no working binary is found.\n *\n * @throws Error when `SQUISQ_FFMPEG` is set but the binary does not run —\n * an explicit override must never be silently ignored.\n */\nexport async function detectFfmpegDetailed(): Promise<FfmpegDetection | null> {\n // 1. Explicit override\n const envPath = process.env.SQUISQ_FFMPEG;\n if (envPath) {\n const version = await getFfmpegVersion(envPath);\n if (!version) {\n throw new Error(\n `SQUISQ_FFMPEG is set to \"${envPath}\" but running \"${envPath} -version\" failed. ` +\n 'Fix the path or unset SQUISQ_FFMPEG.',\n );\n }\n return { path: envPath, source: 'env' };\n }\n\n // 2. System PATH\n const command = process.platform === 'win32' ? 'where' : 'which';\n const found = await run(command, ['ffmpeg']);\n if (found) {\n // `which` and `where` can return multiple lines; take the first\n return { path: found.split('\\n')[0].trim(), source: 'path' };\n }\n\n // 3. Optional ffmpeg-static package. The specifier is a variable so\n // bundlers/TypeScript don't try to resolve a package we don't depend on.\n try {\n const specifier = 'ffmpeg-static';\n const mod = (await import(specifier)) as { default?: unknown } | string;\n // CJS default export shape (`module.exports = path`) surfaces as\n // `mod.default`; some build setups expose the string directly.\n const candidate =\n typeof mod === 'string' ? mod : typeof mod.default === 'string' ? mod.default : null;\n if (candidate) {\n return { path: candidate, source: 'ffmpeg-static' };\n }\n } catch {\n // Not installed — fall through.\n }\n\n return null;\n}\n","/**\n * audioMix — Build the MP4's final audio track from a doc's audio timeline.\n *\n * The schedule is produced by ONE source of truth: `computeAudioTimeline`\n * (from `@bendyline/squisq-video`), which flattens a doc's narration segments\n * (laid sequentially) and its timed media clips (placed at absolute positions\n * via `resolveMediaSchedule`) into a flat list of absolute-timed\n * `AudioTimelineClip`s. This CLI-side helper is a pure *consumer* of that\n * schedule: it loads each clip's bytes and assembles an ffmpeg `amix`\n * filtergraph where every clip is trimmed to its source window and delayed to\n * its absolute start.\n *\n * Because the browser MP4 export and this CLI mix now read the same timeline,\n * their audio placement can no longer drift. In particular, zero-duration\n * narration segments are skipped here exactly as they are in the browser\n * (`computeAudioTimeline` never emits a clip with `durationSec <= 0`).\n *\n * Frame capture stays silent — this reconstructs the audio offline from the\n * same schedule the renderer uses, keeping audio and video aligned.\n */\n\nimport type { Doc } from '@bendyline/squisq/schemas';\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport { computeAudioTimeline } from '@bendyline/squisq-video';\nimport type { AudioTimelineClip } from '@bendyline/squisq-video';\n\n/**\n * Build the final mixed MP3 audio track for a doc's MP4 export.\n *\n * Drives the ffmpeg filtergraph entirely from `computeAudioTimeline(doc,\n * coverPreRoll)`: each clip's `startSec` → `adelay`, `sourceInSec` → `atrim`\n * start, `durationSec` → `atrim` duration, keyed by `src`. All clips are summed\n * with `amix` (`normalize=0` so individual levels are preserved).\n *\n * @param doc - The document whose audio to schedule.\n * @param container - Media container to read each clip's `src` bytes from.\n * @param ffmpegPath - Path to the ffmpeg binary.\n * @param coverPreRoll - Seconds of cover-slide pre-roll; shifts every clip's\n * start (matching the silent leading frames).\n * @returns The mixed MP3 bytes, or `null` when the doc has no audio to place.\n */\nexport async function buildMixedAudioTrack(\n doc: Doc,\n container: ContentContainer,\n ffmpegPath: string,\n coverPreRoll: number,\n): Promise<Uint8Array | null> {\n const timeline = computeAudioTimeline(doc, coverPreRoll);\n if (timeline.length === 0) return null;\n\n // Load each clip's bytes, caching reads by `src` (a src may back several clips).\n const bytesBySrc = new Map<string, ArrayBuffer | null>();\n const readSrc = async (src: string): Promise<ArrayBuffer | null> => {\n if (bytesBySrc.has(src)) return bytesBySrc.get(src)!;\n const data = await container.readFile(src);\n bytesBySrc.set(src, data ?? null);\n return data ?? null;\n };\n\n const usable: Array<{ clip: AudioTimelineClip; buffer: ArrayBuffer }> = [];\n for (const clip of timeline) {\n const buffer = await readSrc(clip.src);\n if (buffer) usable.push({ clip, buffer });\n }\n if (usable.length === 0) return null;\n\n return mixTimelineClips(ffmpegPath, usable);\n}\n\n/** Assemble the ffmpeg `amix` filtergraph and run it, returning the mixed MP3. */\nasync function mixTimelineClips(\n ffmpegPath: string,\n usable: Array<{ clip: AudioTimelineClip; buffer: ArrayBuffer }>,\n): Promise<Uint8Array> {\n const { writeFile, readFile, mkdir, rm } = await import('node:fs/promises');\n const { join } = await import('node:path');\n const { tmpdir } = await import('node:os');\n const { randomBytes } = await import('node:crypto');\n const { execFile } = await import('node:child_process');\n\n const workDir = join(tmpdir(), `squisq-audio-mix-${randomBytes(8).toString('hex')}`);\n await mkdir(workDir, { recursive: true });\n\n const ms = (s: number) => Math.max(0, Math.round(s * 1000));\n\n try {\n const inputs: string[] = [];\n const filters: string[] = [];\n const labels: string[] = [];\n\n for (const { clip, buffer } of usable) {\n const p = join(workDir, `clip-${inputs.length}.mp3`);\n await writeFile(p, new Uint8Array(buffer));\n const i = inputs.push(p) - 1;\n const delayMs = ms(clip.startSec);\n const start = Math.max(0, clip.sourceInSec);\n const end = start + Math.max(0, clip.durationSec);\n filters.push(\n `[${i}:a]atrim=start=${start}:end=${end},asetpts=PTS-STARTPTS,adelay=${delayMs}|${delayMs}[a${i}]`,\n );\n labels.push(`[a${i}]`);\n }\n\n const graph =\n `${filters.join(';')};${labels.join('')}` +\n `amix=inputs=${labels.length}:normalize=0:dropout_transition=0[aout]`;\n\n const outputPath = join(workDir, 'mixed.mp3');\n const args = ['-y'];\n for (const p of inputs) args.push('-i', p);\n args.push(\n '-filter_complex',\n graph,\n '-map',\n '[aout]',\n '-c:a',\n 'libmp3lame',\n '-b:a',\n '192k',\n outputPath,\n );\n\n await new Promise<void>((resolve, reject) => {\n execFile(ffmpegPath, args, { timeout: 180_000 }, (err) => {\n if (err) reject(new Error(`ffmpeg audio mix failed: ${err.message}`));\n else resolve();\n });\n });\n\n const data = await readFile(outputPath);\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n } finally {\n await rm(workDir, { recursive: true, force: true });\n }\n}\n","/**\n * Resolve the pre-roll that will actually be rendered.\n *\n * A requested pre-roll only has meaning when the document exposes a cover.\n * Keeping this decision explicit prevents frame counts, audio offsets, and\n * reported duration from drifting apart when a document has no cover block.\n */\nexport function resolveAppliedCoverPreRoll(requestedSeconds: number, hasCover: boolean): number {\n if (!Number.isFinite(requestedSeconds) || requestedSeconds < 0) {\n throw new Error('Cover pre-roll must be a finite number of seconds greater than or equal to 0');\n }\n return hasCover ? requestedSeconds : 0;\n}\n","/**\n * CLI format registry.\n *\n * The CLI extends the formats package's default registry with `mp4` and `gif`\n * formats so `convert()` can produce rendered media like DOCX/PDF/HTML. These\n * exports are Node-only (Playwright + FFmpeg), which is why they live here\n * rather than in the browser-pure formats package.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { defaultRegistry } from '@bendyline/squisq-formats';\nimport type {\n ConversionResult,\n ConvertOptions,\n FormatDefinition,\n FormatRegistry,\n NormalizedInput,\n} from '@bendyline/squisq-formats';\nimport type { GifDither, VideoOrientation, VideoQuality } from '@bendyline/squisq-video';\n\nexport interface Mp4FormatOptions {\n fps?: number;\n quality?: VideoQuality;\n orientation?: VideoOrientation;\n width?: number;\n height?: number;\n captionStyle?: 'standard' | 'social';\n coverPreRoll?: number;\n animationsEnabled?: boolean;\n}\n\n/** Per-export options for `convert(..., 'gif')`. */\nexport interface GifFormatOptions {\n fps?: number;\n orientation?: VideoOrientation;\n width?: number;\n height?: number;\n captionStyle?: 'standard' | 'social';\n coverPreRoll?: number;\n animationsEnabled?: boolean;\n loop?: number;\n maxColors?: number;\n dither?: GifDither;\n bayerScale?: number;\n}\n\n/** Sensible defaults for `convert(..., 'mp4')` — a full-quality landscape clip. */\nconst MP4_DEFAULTS = {\n fps: 30,\n quality: 'normal' as VideoQuality,\n orientation: 'landscape' as VideoOrientation,\n coverPreRoll: 0,\n animationsEnabled: true,\n} as const;\n\n/** Compression-friendly defaults for `convert(..., 'gif')`. */\nconst GIF_DEFAULTS = {\n fps: 10,\n orientation: 'landscape' as VideoOrientation,\n width: 960,\n height: 540,\n coverPreRoll: 0,\n animationsEnabled: false,\n loop: 0,\n maxColors: 256,\n dither: 'sierra2_4a' as GifDither,\n} as const;\n\n/**\n * The `mp4` {@link FormatDefinition}.\n *\n * Export-only: it renders the normalized Doc to a temporary MP4 on disk via\n * {@link renderDocToMp4}, reads the produced file back into a `Uint8Array`, and\n * always deletes the temp file (even on failure). Per-render knobs (fps,\n * quality, orientation, coverPreRoll) can be supplied through\n * `options.formatOptions.mp4`; otherwise {@link MP4_DEFAULTS} apply.\n */\nfunction mp4Format(): FormatDefinition {\n return {\n id: 'mp4',\n label: 'MP4 Video',\n mimeType: 'video/mp4',\n extensions: ['.mp4'],\n async exportDoc(input: NormalizedInput, options: ConvertOptions): Promise<ConversionResult> {\n // The renderer is lazy-loaded below so api.ts can create this registry\n // without an eager ES-module initialization cycle.\n const mp4Opts = (options.formatOptions?.mp4 ?? {}) as Mp4FormatOptions;\n const fps = typeof mp4Opts.fps === 'number' ? mp4Opts.fps : MP4_DEFAULTS.fps;\n const quality =\n typeof mp4Opts.quality === 'string'\n ? (mp4Opts.quality as VideoQuality)\n : MP4_DEFAULTS.quality;\n const orientation =\n typeof mp4Opts.orientation === 'string'\n ? (mp4Opts.orientation as VideoOrientation)\n : MP4_DEFAULTS.orientation;\n const coverPreRoll =\n typeof mp4Opts.coverPreRoll === 'number' ? mp4Opts.coverPreRoll : MP4_DEFAULTS.coverPreRoll;\n const animationsEnabled =\n typeof mp4Opts.animationsEnabled === 'boolean'\n ? mp4Opts.animationsEnabled\n : MP4_DEFAULTS.animationsEnabled;\n\n const outputPath = join(tmpdir(), `squisq-mp4-${randomBytes(8).toString('hex')}.mp4`);\n try {\n const { renderDocToMp4 } = await import('./api.js');\n await renderDocToMp4(input.doc, input.container, {\n outputPath,\n fps,\n quality,\n orientation,\n width: mp4Opts.width,\n height: mp4Opts.height,\n captionStyle: mp4Opts.captionStyle,\n coverPreRoll,\n animationsEnabled,\n });\n const data = await readFile(outputPath);\n const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return { bytes, mimeType: 'video/mp4', suggestedFilename: '', warnings: [] };\n } finally {\n await rm(outputPath, { force: true });\n }\n },\n };\n}\n\n/** The CLI-only animated GIF format definition. */\nfunction gifFormat(): FormatDefinition {\n return {\n id: 'gif',\n label: 'Animated GIF',\n mimeType: 'image/gif',\n extensions: ['.gif'],\n async exportDoc(input: NormalizedInput, options: ConvertOptions): Promise<ConversionResult> {\n const gifOpts = (options.formatOptions?.gif ?? {}) as GifFormatOptions;\n const orientation =\n typeof gifOpts.orientation === 'string'\n ? (gifOpts.orientation as VideoOrientation)\n : GIF_DEFAULTS.orientation;\n const portrait = orientation === 'portrait';\n const defaultWidth = portrait ? GIF_DEFAULTS.height : GIF_DEFAULTS.width;\n const defaultHeight = portrait ? GIF_DEFAULTS.width : GIF_DEFAULTS.height;\n const outputPath = join(tmpdir(), `squisq-gif-${randomBytes(8).toString('hex')}.gif`);\n try {\n const { renderDocToGif } = await import('./api.js');\n const result = await renderDocToGif(input.doc, input.container, {\n outputPath,\n fps: typeof gifOpts.fps === 'number' ? gifOpts.fps : GIF_DEFAULTS.fps,\n orientation,\n width: typeof gifOpts.width === 'number' ? gifOpts.width : defaultWidth,\n height: typeof gifOpts.height === 'number' ? gifOpts.height : defaultHeight,\n captionStyle: gifOpts.captionStyle,\n coverPreRoll:\n typeof gifOpts.coverPreRoll === 'number'\n ? gifOpts.coverPreRoll\n : GIF_DEFAULTS.coverPreRoll,\n animationsEnabled:\n typeof gifOpts.animationsEnabled === 'boolean'\n ? gifOpts.animationsEnabled\n : GIF_DEFAULTS.animationsEnabled,\n loop: typeof gifOpts.loop === 'number' ? gifOpts.loop : GIF_DEFAULTS.loop,\n maxColors:\n typeof gifOpts.maxColors === 'number' ? gifOpts.maxColors : GIF_DEFAULTS.maxColors,\n dither: gifOpts.dither ?? GIF_DEFAULTS.dither,\n bayerScale: gifOpts.bayerScale,\n });\n const data = await readFile(outputPath);\n const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return {\n bytes,\n mimeType: 'image/gif',\n suggestedFilename: '',\n warnings: result.warnings,\n };\n } finally {\n await rm(outputPath, { force: true });\n }\n },\n };\n}\n\n/**\n * Build the CLI's format registry: every built-in format from\n * `@bendyline/squisq-formats` plus the CLI-only rendered-media exporters.\n */\nexport function createCliRegistry(): FormatRegistry {\n const registry = defaultRegistry();\n registry.register(mp4Format());\n registry.register(gifFormat());\n return registry;\n}\n","/**\n * readInput\n *\n * Unified input reader for the CLI. Accepts a path to a markdown file, a JSON\n * Doc file, a `.zip`/`.dbk` container, a folder, or any importable binary\n * format (`.docx`/`.pptx`/`.pdf`/`.xlsx`/`.csv`/`.html`/`.htm`) and always\n * resolves it to a fully-populated {@link ReadInputResult}: a `Doc`, a\n * `ContentContainer` holding the document + any bundled media, the parsed\n * `MarkdownDocument` when the source was markdown-shaped, and the detected\n * `sourceFormat`.\n *\n * Binary formats are dispatched through the shared format registry's importer\n * (preferring `importContainer`, falling back to `importDoc`); every path\n * derives the `Doc` via `markdownToDoc()` when the source is markdown-shaped.\n */\n\nimport { readFile, readdir, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { parseMarkdown, stringifyMarkdown } from '@bendyline/squisq/markdown';\nimport type { MarkdownDocument } from '@bendyline/squisq/markdown';\nimport { markdownToDoc, resolveAudioMapping } from '@bendyline/squisq/doc';\nimport type { Doc } from '@bendyline/squisq/schemas';\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport { MemoryContentContainer } from '@bendyline/squisq/storage';\nimport { zipToContainer } from '@bendyline/squisq-formats/container';\nimport { defaultRegistry } from '@bendyline/squisq-formats';\nimport type { FormatId } from '@bendyline/squisq-formats';\n\nexport interface ReadInputResult {\n /** The resolved document. Always present. */\n doc: Doc;\n /** Virtual file system holding the document plus any bundled media. */\n container: ContentContainer;\n /**\n * The parsed markdown document. Present when the source was markdown-shaped\n * (`.md`, container/folder markdown, or a binary format imported as\n * markdown); absent for JSON-Doc input.\n */\n markdownDoc?: MarkdownDocument;\n /** Detected source format id (registry id, or `md`/`json`/`dbk`/`folder`). */\n sourceFormat: FormatId;\n}\n\nexport interface ReadInputOptions {\n /**\n * Infer a Squisq theme from an OOXML source's theme part (PPTX today).\n * Default true — the importer carries it as frontmatter.\n */\n inferTheme?: boolean;\n /** Derive custom layout templates from PPTX slide layouts. Default true. */\n inferLayouts?: boolean;\n}\n\n/** MIME type lookup by extension (common content types) */\nconst MIME_TYPES: Record<string, string> = {\n '.md': 'text/markdown',\n '.txt': 'text/plain',\n '.json': 'application/json',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n};\n\n/**\n * Binary extensions dispatched through the registry importer. `.md`, `.zip`,\n * `.dbk`, and `.json` are intentionally excluded — they have dedicated paths\n * that also detect bundled media / doc.json.\n */\nconst IMPORTER_EXTS = ['.docx', '.pptx', '.pdf', '.xlsx', '.csv', '.html', '.htm'];\n\nfunction mimeFromExt(filePath: string): string {\n return MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/**\n * Recursively walk a directory and return all file paths (relative to root).\n */\nasync function walkDir(root: string, prefix = ''): Promise<string[]> {\n const entries = await readdir(root, { withFileTypes: true });\n const paths: string[] = [];\n\n for (const entry of entries) {\n const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n paths.push(...(await walkDir(join(root, entry.name), relPath)));\n } else if (entry.isFile()) {\n paths.push(relPath);\n }\n }\n\n return paths;\n}\n\n/**\n * Read input from a file path (markdown, JSON Doc, ZIP/DBK container, folder,\n * or an importable binary format) and resolve it to a populated\n * {@link ReadInputResult}.\n */\nexport async function readInput(\n inputPath: string,\n options?: ReadInputOptions,\n): Promise<ReadInputResult> {\n const result = await readInputRaw(inputPath, options);\n // Audio rides in the container: a document-anchored narration take\n // (`{[audio src=… anchor=document]}` + timing sidecar) re-times the\n // block timeline, and per-block audio files map into segments — so\n // `squisq convert`/`video` exports pace exactly like the editor preview.\n const doc = await resolveAudioMapping(result.doc, result.container);\n return doc === result.doc ? result : { ...result, doc };\n}\n\nasync function readInputRaw(\n inputPath: string,\n options?: ReadInputOptions,\n): Promise<ReadInputResult> {\n const info = await stat(inputPath);\n\n if (info.isDirectory()) {\n return readFolder(inputPath);\n }\n\n const ext = extname(inputPath).toLowerCase();\n if (ext === '.zip' || ext === '.dbk') {\n return readContainer(inputPath);\n }\n\n if (ext === '.json') {\n return readDocJsonFile(inputPath);\n }\n\n if (IMPORTER_EXTS.includes(ext)) {\n const def = defaultRegistry().byExtension(ext);\n if (def && (def.importContainer || def.importDoc)) {\n return readViaImporter(inputPath, def, options);\n }\n }\n\n // Default: treat as a markdown file\n return readMarkdownFile(inputPath);\n}\n\n/** Read a file into an ArrayBuffer (a fresh copy, not a Buffer view). */\nasync function readArrayBuffer(filePath: string): Promise<ArrayBuffer> {\n const data = await readFile(filePath);\n return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer;\n}\n\nasync function readMarkdownFile(filePath: string): Promise<ReadInputResult> {\n const content = await readFile(filePath, 'utf-8');\n const container = new MemoryContentContainer();\n await container.writeDocument(content);\n const markdownDoc = parseMarkdown(content);\n return { doc: markdownToDoc(markdownDoc), container, markdownDoc, sourceFormat: 'md' };\n}\n\n/**\n * Read a standalone Doc JSON file. The container is empty (no media bundled);\n * callers should populate it or set basePath for media resolution.\n */\nasync function readDocJsonFile(filePath: string): Promise<ReadInputResult> {\n const content = await readFile(filePath, 'utf-8');\n const doc = JSON.parse(content) as Doc;\n const container = new MemoryContentContainer();\n return { doc, container, sourceFormat: 'json' };\n}\n\n/**\n * Dispatch an importable binary format (docx/pptx/pdf/…) through the registry\n * importer. Prefers `importContainer` (extracts media alongside the markdown),\n * falling back to `importDoc` wrapped in a fresh container.\n */\nasync function readViaImporter(\n filePath: string,\n def: import('@bendyline/squisq-formats').FormatDefinition,\n options?: ReadInputOptions,\n): Promise<ReadInputResult> {\n const buffer = await readArrayBuffer(filePath);\n const convertOptions = {\n formatOptions: {\n [def.id]: {\n inferTheme: options?.inferTheme !== false,\n inferLayouts: options?.inferLayouts !== false,\n },\n },\n };\n\n let container: ContentContainer;\n let markdownDoc: MarkdownDocument;\n if (def.importContainer) {\n container = await def.importContainer(buffer, convertOptions);\n const text = await container.readDocument();\n markdownDoc = text ? parseMarkdown(text) : { type: 'document', children: [] };\n } else {\n // importDoc is guaranteed present by the caller's guard.\n markdownDoc = await def.importDoc!(buffer, convertOptions);\n const mem = new MemoryContentContainer();\n await mem.writeDocument(stringifyMarkdown(markdownDoc));\n container = mem;\n }\n\n return { doc: markdownToDoc(markdownDoc), container, markdownDoc, sourceFormat: def.id };\n}\n\n/**\n * Known filenames for Doc JSON inside containers and folders.\n * Checked in priority order before falling back to markdown discovery.\n */\nconst DOC_JSON_NAMES = ['doc.json', 'story.json'];\n\n/** Resolve a container that may hold either a doc.json or a markdown document. */\nasync function resolveContainer(\n container: ContentContainer,\n sourceFormat: FormatId,\n missingMessage: string,\n): Promise<ReadInputResult> {\n // Check for Doc JSON first.\n for (const name of DOC_JSON_NAMES) {\n const jsonData = await container.readFile(name);\n if (jsonData) {\n const doc = JSON.parse(new TextDecoder().decode(jsonData)) as Doc;\n return { doc, container, sourceFormat };\n }\n }\n\n const markdown = await container.readDocument();\n if (!markdown) {\n throw new Error(missingMessage);\n }\n\n const markdownDoc = parseMarkdown(markdown);\n return { doc: markdownToDoc(markdownDoc), container, markdownDoc, sourceFormat };\n}\n\nasync function readContainer(filePath: string): Promise<ReadInputResult> {\n const container = await zipToContainer(await readArrayBuffer(filePath));\n return resolveContainer(\n container,\n 'dbk',\n `No markdown document or doc.json found in container: ${filePath}`,\n );\n}\n\nasync function readFolder(dirPath: string): Promise<ReadInputResult> {\n const container = new MemoryContentContainer();\n const files = await walkDir(dirPath);\n\n for (const relPath of files) {\n const absPath = join(dirPath, relPath);\n const data = await readFile(absPath);\n await container.writeFile(\n relPath,\n new Uint8Array(data.buffer, data.byteOffset, data.byteLength),\n mimeFromExt(relPath),\n );\n }\n\n return resolveContainer(\n container,\n 'folder',\n `No markdown document or doc.json found in folder: ${dirPath}`,\n );\n}\n"],"mappings":";;;;;;AA4BA,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAG9B,SAAS,qBAAqB,0BAA0B;AACxD,SAAS,yBAAyB;AAClC,SAAS,WAAW,sBAAsB;;;ACrB1C,SAAS,gBAAgB;AAczB,SAAS,IAAI,SAAiB,MAAwC;AACpE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,aAAS,SAAS,MAAM,EAAE,SAAS,IAAK,GAAG,CAAC,KAAK,WAAW;AAC1D,UAAI,OAAO,CAAC,OAAO,KAAK,GAAG;AACzB,gBAAQ,IAAI;AACZ;AAAA,MACF;AACA,cAAQ,OAAO,KAAK,CAAC;AAAA,IACvB,CAAC;AAAA,EACH,CAAC;AACH;AAMA,eAAsB,iBAAiB,MAAsC;AAC3E,QAAM,MAAM,MAAM,IAAI,MAAM,CAAC,UAAU,CAAC;AACxC,SAAO,MAAM,IAAI,MAAM,IAAI,EAAE,CAAC,EAAE,KAAK,IAAI;AAC3C;AASA,eAAsB,uBAAwD;AAE5E,QAAM,UAAU,QAAQ,IAAI;AAC5B,MAAI,SAAS;AACX,UAAM,UAAU,MAAM,iBAAiB,OAAO;AAC9C,QAAI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":["readFile","rm","join","tmpdir","randomBytes","execFile","renderDocToMp4","renderDocToGif","MemoryContentContainer","readFile","join","defaultRegistry","framesToMp4Native","framesToGifNative","join","execFile"]}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/util/nativeEncoder.ts
|
|
4
|
+
import { execFile } from "child_process";
|
|
5
|
+
import { writeFile, readFile, mkdir, rm } from "fs/promises";
|
|
6
|
+
import { join } from "path";
|
|
7
|
+
import { tmpdir } from "os";
|
|
8
|
+
import { randomBytes } from "crypto";
|
|
9
|
+
import {
|
|
10
|
+
resolveDimensions,
|
|
11
|
+
ffmpegVideoQualityArgs,
|
|
12
|
+
audioBitrateArg,
|
|
13
|
+
ffmpegAudioMuxArgs,
|
|
14
|
+
ffmpegGifOutputArgs
|
|
15
|
+
} from "@bendyline/squisq-video";
|
|
16
|
+
var GIF_EXPORT_DEFAULTS = {
|
|
17
|
+
fps: 10,
|
|
18
|
+
width: 960,
|
|
19
|
+
height: 540,
|
|
20
|
+
loop: 0,
|
|
21
|
+
maxColors: 256,
|
|
22
|
+
dither: "sierra2_4a"
|
|
23
|
+
};
|
|
24
|
+
function resolveGifDimensions(options) {
|
|
25
|
+
const portrait = options.orientation === "portrait";
|
|
26
|
+
const defaults = portrait ? { width: GIF_EXPORT_DEFAULTS.height, height: GIF_EXPORT_DEFAULTS.width } : { width: GIF_EXPORT_DEFAULTS.width, height: GIF_EXPORT_DEFAULTS.height };
|
|
27
|
+
const width = options.width ?? defaults.width;
|
|
28
|
+
const height = options.height ?? defaults.height;
|
|
29
|
+
for (const [label, value] of [
|
|
30
|
+
["width", width],
|
|
31
|
+
["height", height]
|
|
32
|
+
]) {
|
|
33
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
34
|
+
throw new RangeError(`GIF ${label} must be a positive integer.`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return { width, height };
|
|
38
|
+
}
|
|
39
|
+
function resolveGifFps(options) {
|
|
40
|
+
const fps = options.fps ?? GIF_EXPORT_DEFAULTS.fps;
|
|
41
|
+
if (!Number.isFinite(fps) || fps <= 0 || fps > 100) {
|
|
42
|
+
throw new RangeError("GIF FPS must be a finite number between 1 and 100.");
|
|
43
|
+
}
|
|
44
|
+
return fps;
|
|
45
|
+
}
|
|
46
|
+
async function framesToMp4Native(ffmpegPath, frames, audio, outputPath, options = {}) {
|
|
47
|
+
const fps = options.fps ?? 30;
|
|
48
|
+
const quality = options.quality ?? "normal";
|
|
49
|
+
const { width, height } = resolveDimensions(options);
|
|
50
|
+
const onProgress = options.onProgress;
|
|
51
|
+
if (frames.length === 0) {
|
|
52
|
+
throw new Error("No frames provided for encoding");
|
|
53
|
+
}
|
|
54
|
+
const tmpId = randomBytes(8).toString("hex");
|
|
55
|
+
const workDir = join(tmpdir(), `squisq-video-${tmpId}`);
|
|
56
|
+
await mkdir(workDir, { recursive: true });
|
|
57
|
+
try {
|
|
58
|
+
onProgress?.(0, "writing frames");
|
|
59
|
+
const padLen = String(frames.length).length;
|
|
60
|
+
for (let i = 0; i < frames.length; i++) {
|
|
61
|
+
const name = `frame-${String(i + 1).padStart(padLen, "0")}.png`;
|
|
62
|
+
await writeFile(join(workDir, name), frames[i]);
|
|
63
|
+
if (onProgress && i % 10 === 0) {
|
|
64
|
+
onProgress(Math.round(i / frames.length * 30), "writing frames");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
let audioPath = null;
|
|
68
|
+
if (audio) {
|
|
69
|
+
audioPath = join(workDir, "audio-input");
|
|
70
|
+
await writeFile(audioPath, audio);
|
|
71
|
+
}
|
|
72
|
+
onProgress?.(30, "encoding");
|
|
73
|
+
const padPattern = join(workDir, `frame-%0${padLen}d.png`);
|
|
74
|
+
const args = ["-y", "-framerate", String(fps), "-i", padPattern];
|
|
75
|
+
if (audioPath) {
|
|
76
|
+
args.push("-i", audioPath);
|
|
77
|
+
}
|
|
78
|
+
args.push(
|
|
79
|
+
"-c:v",
|
|
80
|
+
"libx264",
|
|
81
|
+
...ffmpegVideoQualityArgs(quality),
|
|
82
|
+
"-pix_fmt",
|
|
83
|
+
"yuv420p",
|
|
84
|
+
"-vf",
|
|
85
|
+
`scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2`
|
|
86
|
+
);
|
|
87
|
+
if (audioPath) {
|
|
88
|
+
args.push(...ffmpegAudioMuxArgs(audioBitrateArg(quality)));
|
|
89
|
+
}
|
|
90
|
+
args.push(outputPath);
|
|
91
|
+
await new Promise((resolve, reject) => {
|
|
92
|
+
execFile(ffmpegPath, args, { timeout: 6e5 }, (err) => {
|
|
93
|
+
if (err) {
|
|
94
|
+
reject(new Error(`ffmpeg failed: ${err.message}`));
|
|
95
|
+
} else {
|
|
96
|
+
resolve();
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
onProgress?.(100, "done");
|
|
101
|
+
} finally {
|
|
102
|
+
await rm(workDir, { recursive: true, force: true });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function framesToMp4NativeBytes(ffmpegPath, frames, audio, options = {}) {
|
|
106
|
+
const tmpId = randomBytes(8).toString("hex");
|
|
107
|
+
const tmpOutput = join(tmpdir(), `squisq-video-out-${tmpId}.mp4`);
|
|
108
|
+
try {
|
|
109
|
+
await framesToMp4Native(ffmpegPath, frames, audio, tmpOutput, options);
|
|
110
|
+
const data = await readFile(tmpOutput);
|
|
111
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
112
|
+
} finally {
|
|
113
|
+
await rm(tmpOutput, { force: true });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function framesToGifNative(ffmpegPath, frames, outputPath, options = {}) {
|
|
117
|
+
const fps = resolveGifFps(options);
|
|
118
|
+
const { width, height } = resolveGifDimensions(options);
|
|
119
|
+
const onProgress = options.onProgress;
|
|
120
|
+
if (frames.length === 0) {
|
|
121
|
+
throw new Error("No frames provided for encoding");
|
|
122
|
+
}
|
|
123
|
+
const gifOutputArgs = ffmpegGifOutputArgs({
|
|
124
|
+
width,
|
|
125
|
+
height,
|
|
126
|
+
loop: options.loop ?? GIF_EXPORT_DEFAULTS.loop,
|
|
127
|
+
maxColors: options.maxColors ?? GIF_EXPORT_DEFAULTS.maxColors,
|
|
128
|
+
dither: options.dither ?? GIF_EXPORT_DEFAULTS.dither,
|
|
129
|
+
bayerScale: options.bayerScale
|
|
130
|
+
});
|
|
131
|
+
const tmpId = randomBytes(8).toString("hex");
|
|
132
|
+
const workDir = join(tmpdir(), `squisq-gif-${tmpId}`);
|
|
133
|
+
await mkdir(workDir, { recursive: true });
|
|
134
|
+
try {
|
|
135
|
+
onProgress?.(0, "writing frames");
|
|
136
|
+
const padLen = String(frames.length).length;
|
|
137
|
+
for (let i = 0; i < frames.length; i++) {
|
|
138
|
+
const name = `frame-${String(i + 1).padStart(padLen, "0")}.png`;
|
|
139
|
+
await writeFile(join(workDir, name), frames[i]);
|
|
140
|
+
if (onProgress && i % 10 === 0) {
|
|
141
|
+
onProgress(Math.round(i / frames.length * 30), "writing frames");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
onProgress?.(30, "encoding");
|
|
145
|
+
const padPattern = join(workDir, `frame-%0${padLen}d.png`);
|
|
146
|
+
const args = ["-y", "-framerate", String(fps), "-i", padPattern, ...gifOutputArgs, outputPath];
|
|
147
|
+
await new Promise((resolve, reject) => {
|
|
148
|
+
execFile(ffmpegPath, args, { timeout: 6e5 }, (err) => {
|
|
149
|
+
if (err) reject(new Error(`ffmpeg GIF encoding failed: ${err.message}`));
|
|
150
|
+
else resolve();
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
onProgress?.(100, "done");
|
|
154
|
+
} finally {
|
|
155
|
+
await rm(workDir, { recursive: true, force: true });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async function framesToGifNativeBytes(ffmpegPath, frames, options = {}) {
|
|
159
|
+
const tmpId = randomBytes(8).toString("hex");
|
|
160
|
+
const tmpOutput = join(tmpdir(), `squisq-gif-out-${tmpId}.gif`);
|
|
161
|
+
try {
|
|
162
|
+
await framesToGifNative(ffmpegPath, frames, tmpOutput, options);
|
|
163
|
+
const data = await readFile(tmpOutput);
|
|
164
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
165
|
+
} finally {
|
|
166
|
+
await rm(tmpOutput, { force: true });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export {
|
|
171
|
+
GIF_EXPORT_DEFAULTS,
|
|
172
|
+
framesToMp4Native,
|
|
173
|
+
framesToMp4NativeBytes,
|
|
174
|
+
framesToGifNative,
|
|
175
|
+
framesToGifNativeBytes
|
|
176
|
+
};
|
|
177
|
+
//# sourceMappingURL=chunk-VM3ZFP3J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/util/nativeEncoder.ts"],"sourcesContent":["/**\n * Native FFmpeg Encoder\n *\n * Encodes PNG frames to MP4 or animated GIF using a locally installed ffmpeg\n * binary. Writes frames to a temporary directory, invokes ffmpeg as a child\n * process, and reads the resulting media file.\n *\n * This is the Node fast path used after the CLI detects native FFmpeg. Browser\n * callers use the WebCodecs/ffmpeg.wasm paths in the video packages instead.\n */\n\nimport { execFile } from 'node:child_process';\nimport { writeFile, readFile, mkdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { randomBytes } from 'node:crypto';\n\nimport type { GifDither, VideoExportOptions, VideoOrientation } from '@bendyline/squisq-video';\nimport {\n resolveDimensions,\n ffmpegVideoQualityArgs,\n audioBitrateArg,\n ffmpegAudioMuxArgs,\n ffmpegGifOutputArgs,\n} from '@bendyline/squisq-video';\n\n/** Options for native animated-GIF encoding. */\nexport interface GifExportOptions {\n /** Frames per second (default: 10; GIF timing is centisecond-based). */\n fps?: number;\n /** Output width in pixels (default: 960 landscape / 540 portrait). */\n width?: number;\n /** Output height in pixels (default: 540 landscape / 960 portrait). */\n height?: number;\n /** Viewport orientation used for default dimensions. */\n orientation?: VideoOrientation;\n /** Number of repeats; 0 loops forever and -1 disables looping. */\n loop?: number;\n /** Palette size, between 2 and 256 (default: 256). */\n maxColors?: number;\n /** Palette dithering algorithm (default: sierra2_4a). */\n dither?: GifDither;\n /** Bayer strength when dither is bayer (0-5, default: 3). */\n bayerScale?: number;\n /** Encoding progress callback. */\n onProgress?: (percent: number, phase: string) => void;\n}\n\n/** Compression-friendly defaults for animated GIF output. */\nexport const GIF_EXPORT_DEFAULTS = {\n fps: 10,\n width: 960,\n height: 540,\n loop: 0,\n maxColors: 256,\n dither: 'sierra2_4a' as GifDither,\n} as const;\n\nfunction resolveGifDimensions(options: GifExportOptions): { width: number; height: number } {\n const portrait = options.orientation === 'portrait';\n const defaults = portrait\n ? { width: GIF_EXPORT_DEFAULTS.height, height: GIF_EXPORT_DEFAULTS.width }\n : { width: GIF_EXPORT_DEFAULTS.width, height: GIF_EXPORT_DEFAULTS.height };\n const width = options.width ?? defaults.width;\n const height = options.height ?? defaults.height;\n for (const [label, value] of [\n ['width', width],\n ['height', height],\n ] as const) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new RangeError(`GIF ${label} must be a positive integer.`);\n }\n }\n return { width, height };\n}\n\nfunction resolveGifFps(options: GifExportOptions): number {\n const fps = options.fps ?? GIF_EXPORT_DEFAULTS.fps;\n // GIF delays are stored in centiseconds, so rates above 100 cannot be\n // represented without timestamp rounding.\n if (!Number.isFinite(fps) || fps <= 0 || fps > 100) {\n throw new RangeError('GIF FPS must be a finite number between 1 and 100.');\n }\n return fps;\n}\n\n/**\n * Encode frame PNGs to MP4 using native ffmpeg.\n *\n * @param ffmpegPath - Absolute path to the ffmpeg binary\n * @param frames - Array of PNG image bytes (one per frame)\n * @param audio - Optional audio file bytes to mux\n * @param outputPath - Where to write the final MP4\n * @param options - Encoding options (fps, quality, dimensions, progress)\n */\nexport async function framesToMp4Native(\n ffmpegPath: string,\n frames: Uint8Array[],\n audio: Uint8Array | null,\n outputPath: string,\n options: VideoExportOptions = {},\n): Promise<void> {\n const fps = options.fps ?? 30;\n const quality = options.quality ?? 'normal';\n const { width, height } = resolveDimensions(options);\n const onProgress = options.onProgress;\n\n if (frames.length === 0) {\n throw new Error('No frames provided for encoding');\n }\n // Create a temp working directory\n const tmpId = randomBytes(8).toString('hex');\n const workDir = join(tmpdir(), `squisq-video-${tmpId}`);\n await mkdir(workDir, { recursive: true });\n\n try {\n onProgress?.(0, 'writing frames');\n\n // Write frame PNGs to temp directory\n const padLen = String(frames.length).length;\n for (let i = 0; i < frames.length; i++) {\n const name = `frame-${String(i + 1).padStart(padLen, '0')}.png`;\n await writeFile(join(workDir, name), frames[i]);\n\n if (onProgress && i % 10 === 0) {\n onProgress(Math.round((i / frames.length) * 30), 'writing frames');\n }\n }\n\n // Write audio if provided\n let audioPath: string | null = null;\n if (audio) {\n audioPath = join(workDir, 'audio-input');\n await writeFile(audioPath, audio);\n }\n\n onProgress?.(30, 'encoding');\n\n // Build ffmpeg arguments\n const padPattern = join(workDir, `frame-%0${padLen}d.png`);\n const args = ['-y', '-framerate', String(fps), '-i', padPattern];\n\n if (audioPath) {\n args.push('-i', audioPath);\n }\n\n args.push(\n '-c:v',\n 'libx264',\n ...ffmpegVideoQualityArgs(quality),\n '-pix_fmt',\n 'yuv420p',\n '-vf',\n `scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2`,\n );\n\n if (audioPath) {\n args.push(...ffmpegAudioMuxArgs(audioBitrateArg(quality)));\n }\n\n args.push(outputPath);\n\n // Run ffmpeg. execFile buffers stdout/stderr internally for the callback,\n // so the child's pipes are already drained — no manual stderr listener needed.\n await new Promise<void>((resolve, reject) => {\n execFile(ffmpegPath, args, { timeout: 600_000 }, (err) => {\n if (err) {\n reject(new Error(`ffmpeg failed: ${err.message}`));\n } else {\n resolve();\n }\n });\n });\n\n onProgress?.(100, 'done');\n } finally {\n // Clean up temp directory\n await rm(workDir, { recursive: true, force: true });\n }\n}\n\n/**\n * Encode frames using native ffmpeg and return the MP4 bytes (instead of writing to disk).\n * Useful when the caller needs the bytes in memory.\n */\nexport async function framesToMp4NativeBytes(\n ffmpegPath: string,\n frames: Uint8Array[],\n audio: Uint8Array | null,\n options: VideoExportOptions = {},\n): Promise<Uint8Array> {\n const tmpId = randomBytes(8).toString('hex');\n const tmpOutput = join(tmpdir(), `squisq-video-out-${tmpId}.mp4`);\n\n try {\n await framesToMp4Native(ffmpegPath, frames, audio, tmpOutput, options);\n const data = await readFile(tmpOutput);\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n } finally {\n await rm(tmpOutput, { force: true });\n }\n}\n\n/**\n * Encode PNG frames to an animated GIF using native FFmpeg.\n *\n * The shared palette graph uses changed-frame statistics and rectangle-scoped\n * palette application so static slide regions remain stable and compress well.\n * GIF has no audio track; callers should surface that limitation before calling.\n */\nexport async function framesToGifNative(\n ffmpegPath: string,\n frames: Uint8Array[],\n outputPath: string,\n options: GifExportOptions = {},\n): Promise<void> {\n const fps = resolveGifFps(options);\n const { width, height } = resolveGifDimensions(options);\n const onProgress = options.onProgress;\n\n if (frames.length === 0) {\n throw new Error('No frames provided for encoding');\n }\n const gifOutputArgs = ffmpegGifOutputArgs({\n width,\n height,\n loop: options.loop ?? GIF_EXPORT_DEFAULTS.loop,\n maxColors: options.maxColors ?? GIF_EXPORT_DEFAULTS.maxColors,\n dither: options.dither ?? GIF_EXPORT_DEFAULTS.dither,\n bayerScale: options.bayerScale,\n });\n\n const tmpId = randomBytes(8).toString('hex');\n const workDir = join(tmpdir(), `squisq-gif-${tmpId}`);\n await mkdir(workDir, { recursive: true });\n\n try {\n onProgress?.(0, 'writing frames');\n const padLen = String(frames.length).length;\n for (let i = 0; i < frames.length; i++) {\n const name = `frame-${String(i + 1).padStart(padLen, '0')}.png`;\n await writeFile(join(workDir, name), frames[i]);\n if (onProgress && i % 10 === 0) {\n onProgress(Math.round((i / frames.length) * 30), 'writing frames');\n }\n }\n\n onProgress?.(30, 'encoding');\n const padPattern = join(workDir, `frame-%0${padLen}d.png`);\n const args = ['-y', '-framerate', String(fps), '-i', padPattern, ...gifOutputArgs, outputPath];\n\n await new Promise<void>((resolve, reject) => {\n execFile(ffmpegPath, args, { timeout: 600_000 }, (err) => {\n if (err) reject(new Error(`ffmpeg GIF encoding failed: ${err.message}`));\n else resolve();\n });\n });\n onProgress?.(100, 'done');\n } finally {\n await rm(workDir, { recursive: true, force: true });\n }\n}\n\n/** Encode frames with native FFmpeg and return animated-GIF bytes. */\nexport async function framesToGifNativeBytes(\n ffmpegPath: string,\n frames: Uint8Array[],\n options: GifExportOptions = {},\n): Promise<Uint8Array> {\n const tmpId = randomBytes(8).toString('hex');\n const tmpOutput = join(tmpdir(), `squisq-gif-out-${tmpId}.gif`);\n try {\n await framesToGifNative(ffmpegPath, frames, tmpOutput, options);\n const data = await readFile(tmpOutput);\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n } finally {\n await rm(tmpOutput, { force: true });\n }\n}\n"],"mappings":";;;AAWA,SAAS,gBAAgB;AACzB,SAAS,WAAW,UAAU,OAAO,UAAU;AAC/C,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAG5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAyBA,IAAM,sBAAsB;AAAA,EACjC,KAAK;AAAA,EACL,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,WAAW;AAAA,EACX,QAAQ;AACV;AAEA,SAAS,qBAAqB,SAA8D;AAC1F,QAAM,WAAW,QAAQ,gBAAgB;AACzC,QAAM,WAAW,WACb,EAAE,OAAO,oBAAoB,QAAQ,QAAQ,oBAAoB,MAAM,IACvE,EAAE,OAAO,oBAAoB,OAAO,QAAQ,oBAAoB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