Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
import {
copyFile,
mkdir,
open,
readFile,
readdir,
realpath,
rename,
rm,
stat,
lstat,
writeFile
} from 'node:fs/promises';
import path from 'node:path';
import { ZodError } from 'zod/v3';
import { creatorPresetModuleDefinitions, getCreatorPresetModuleDefinition } from './module-schemas.js';
import { creatorPresetSourceManifestSchema, validatePresetPublicFields } from './schema.js';
import { canonicalJson, sha256 } from './hash.js';
import type {
CompiledCreatorPreset,
CreatorPresetBuildManifest,
CreatorPresetCatalog,
CreatorPresetCompilerOptions,
CreatorPresetModuleDefinition,
CompiledCreatorPresetAsset,
CompiledCreatorPresetVideoAsset,
CreatorPresetSourceManifest
} from './types.js';
const COVER_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']);
const RESOURCE_EXTENSIONS = new Set([...COVER_EXTENSIONS, '.mp4']);
const MIME_BY_EXTENSION = new Map([
['.png', 'image/png'],
['.jpg', 'image/jpeg'],
['.jpeg', 'image/jpeg'],
['.webp', 'image/webp']
] as const);
const MAX_COVER_SIZE = 2 * 1024 * 1024;
const MAX_PREVIEW_SIZE = 4 * 1024 * 1024;
const MAX_AUTHOR_AVATAR_SIZE = 512 * 1024;
const MAX_PREVIEW_VIDEO_SIZE = 8 * 1024 * 1024;
const MAX_PREVIEW_VIDEO_DURATION_SECONDS = 10;
const MAX_PREVIEW_VIDEO_TOTAL_SIZE = 20 * 1024 * 1024;
export async function validateCreatorPresets(
options: CreatorPresetCompilerOptions
): Promise<CreatorPresetCatalog> {
const sourceRoot = path.resolve(options.sourceRoot);
const modules = options.modules ?? creatorPresetModuleDefinitions;
await assertDirectory(sourceRoot);
const entries = await findTemplateManifests(sourceRoot);
const presets: CompiledCreatorPreset[] = [];
const identities = new Set<string>();
let previewVideoTotalSize = 0;
for (const entry of entries) {
const manifest = await readSourceManifest(entry.file, entry.relativeFile);
const definition = getCreatorPresetModuleDefinition(manifest.module, modules);
validateDirectoryIdentity(entry.parts, manifest, entry.relativeFile);
validateRuntimeBinding(definition, manifest, entry.relativeFile);
validatePresetPublicFields(manifest.defaults, `${entry.relativeFile}.defaults`);
for (const [locale, defaults] of Object.entries(manifest.defaultsByLocale ?? {})) {
if (defaults !== undefined) {
validatePresetPublicFields(defaults, `${entry.relativeFile}.defaultsByLocale.${locale}`);
}
}
parseModuleDefaults(definition, manifest, entry.relativeFile);
definition.validateRequirement(manifest.requirements);
const identity = `${manifest.module}/${manifest.id}/${manifest.version}`;
if (identities.has(identity)) {
throw new Error(`${entry.relativeFile}: duplicate preset identity ${identity}`);
}
identities.add(identity);
const cover = await validateCover(sourceRoot, entry.directory, manifest.cover, entry.relativeFile);
const preview = manifest.preview === undefined
? undefined
: await validatePreview(
sourceRoot,
entry.directory,
manifest.preview,
entry.relativeFile
);
const previewVideo = manifest.previewVideo === undefined
? undefined
: await validatePreviewVideo(
sourceRoot,
entry.directory,
manifest.previewVideo,
entry.relativeFile
);
if (previewVideo !== undefined) {
previewVideoTotalSize += previewVideo.size;
if (previewVideoTotalSize > MAX_PREVIEW_VIDEO_TOTAL_SIZE) {
throw new Error(
`${entry.relativeFile}.previewVideo: total preview video size exceeds `
+ `${MAX_PREVIEW_VIDEO_TOTAL_SIZE / 1024 / 1024} MiB`
);
}
}
const authorAvatar = manifest.author?.avatar === undefined
? undefined
: await validateAuthorAvatar(
sourceRoot,
entry.directory,
manifest.author.avatar,
entry.relativeFile
);
const normalizedManifest = normalizeSourceManifest(manifest);
const {
cover: _normalizedCover,
preview: _normalizedPreview,
previewVideo: _normalizedPreviewVideo,
author: normalizedAuthor,
...normalizedPreset
} = normalizedManifest;
const contentHash = sha256(canonicalJson({
...normalizedManifest,
cover: {
path: toPosix(manifest.cover),
sha256: cover.sha256
},
...(preview === undefined ? {} : {
preview: {
path: toPosix(manifest.preview!),
sha256: preview.sha256
}
}),
...(previewVideo === undefined ? {} : {
previewVideo: {
path: toPosix(manifest.previewVideo!),
sha256: previewVideo.sha256
}
}),
...(authorAvatar === undefined ? {} : {
authorAvatar: {
path: toPosix(manifest.author!.avatar!),
sha256: authorAvatar.sha256
}
})
}));
presets.push({
...normalizedPreset,
cover: compileAsset(sourceRoot, cover),
...(preview === undefined ? {} : { preview: compileAsset(sourceRoot, preview) }),
...(previewVideo === undefined ? {} : {
previewVideo: compileVideoAsset(sourceRoot, previewVideo)
}),
...(normalizedAuthor === undefined ? {} : {
author: {
name: normalizedAuthor.name,
...(normalizedAuthor.url === undefined ? {} : { url: normalizedAuthor.url }),
...(authorAvatar === undefined ? {} : { avatar: compileAsset(sourceRoot, authorAvatar) })
}
}),
contentHash
});
}
presets.sort(comparePresets);
return {
schemaVersion: 1,
presets
};
}
export async function compileCreatorPresets(
options: CreatorPresetCompilerOptions
): Promise<CreatorPresetBuildManifest> {
if (options.outputRoot === undefined) {
throw new Error('outputRoot is required when compiling creator presets');
}
const outputRoot = path.resolve(options.outputRoot);
const catalog = await validateCreatorPresets(options);
const parent = path.dirname(outputRoot);
const temporary = path.join(
parent,
`.${path.basename(outputRoot)}.tmp-${process.pid}-${Date.now()}`
);
const backup = path.join(
parent,
`.${path.basename(outputRoot)}.backup-${process.pid}-${Date.now()}`
);
await rm(temporary, { recursive: true, force: true });
await mkdir(path.join(temporary, 'assets'), { recursive: true });
try {
for (const preset of catalog.presets) {
for (const asset of [
preset.cover,
preset.preview,
preset.previewVideo,
preset.author?.avatar
]) {
if (asset === undefined) continue;
const source = path.join(path.resolve(options.sourceRoot), asset.source);
const destination = path.join(temporary, asset.asset);
try {
await stat(destination);
} catch {
await copyFile(source, destination);
}
}
}
const catalogBytes = Buffer.from(`${canonicalJson(catalog)}\n`);
await writeFile(path.join(temporary, 'catalog.json'), catalogBytes);
const assetFiles = await listOutputFiles(temporary, ['catalog.json']);
const catalogHash = sha256(catalogBytes);
const assetEntries = assetFiles.filter(file => file.path.startsWith('assets/'));
const assetSetHash = sha256(canonicalJson(assetEntries));
const manifestWithoutSelf: CreatorPresetBuildManifest = {
schemaVersion: 1,
catalogHash,
assetSetHash,
files: assetFiles
};
await writeFile(
path.join(temporary, 'manifest.json'),
`${canonicalJson(manifestWithoutSelf)}\n`
);
await syncTree(temporary);
await mkdir(parent, { recursive: true });
let hadPrevious = false;
try {
await rename(outputRoot, backup);
hadPrevious = true;
} catch (error) {
if (!isMissing(error)) throw error;
}
try {
await rename(temporary, outputRoot);
await rm(backup, { recursive: true, force: true });
} catch (error) {
if (hadPrevious) await rename(backup, outputRoot);
throw error;
}
return manifestWithoutSelf;
} catch (error) {
await rm(temporary, { recursive: true, force: true });
throw error;
}
}
export { canonicalJson, sha256 } from './hash.js';
async function findTemplateManifests(sourceRoot: string): Promise<Array<{
file: string;
directory: string;
relativeFile: string;
parts: [string, string, string];
}>> {
const results: Array<{
file: string;
directory: string;
relativeFile: string;
parts: [string, string, string];
}> = [];
const modules = await sortedDirectoryEntries(sourceRoot);
for (const moduleEntry of modules) {
await rejectSymlink(moduleEntry, path.join(sourceRoot, moduleEntry.name));
if (!moduleEntry.isDirectory()) {
throw new Error(`${moduleEntry.name}: template root entries must be directories`);
}
const moduleDirectory = path.join(sourceRoot, moduleEntry.name);
for (const idEntry of await sortedDirectoryEntries(moduleDirectory)) {
const idPath = path.join(moduleDirectory, idEntry.name);
await rejectSymlink(idEntry, idPath);
if (!idEntry.isDirectory()) throw new Error(`${toPosix(path.relative(sourceRoot, idPath))}: expected directory`);
for (const versionEntry of await sortedDirectoryEntries(idPath)) {
const versionPath = path.join(idPath, versionEntry.name);
await rejectSymlink(versionEntry, versionPath);
if (!versionEntry.isDirectory()) throw new Error(`${toPosix(path.relative(sourceRoot, versionPath))}: expected directory`);
const files = await sortedDirectoryEntries(versionPath);
const manifestEntry = files.find(file => file.name === 'template.json');
if (manifestEntry === undefined || !manifestEntry.isFile()) {
throw new Error(`${toPosix(path.relative(sourceRoot, versionPath))}/template.json: missing manifest`);
}
for (const file of files) {
await rejectSymlink(file, path.join(versionPath, file.name));
if (file.isDirectory()) {
throw new Error(`${toPosix(path.relative(sourceRoot, path.join(versionPath, file.name)))}: nested directories are not allowed`);
}
if (!file.isFile()) {
throw new Error(`${toPosix(path.relative(sourceRoot, path.join(versionPath, file.name)))}: only regular files are allowed`);
}
const extension = path.extname(file.name).toLowerCase();
if (file.name !== 'template.json' && !RESOURCE_EXTENSIONS.has(extension)) {
throw new Error(`${toPosix(path.relative(sourceRoot, path.join(versionPath, file.name)))}: unsupported template resource`);
}
}
results.push({
file: path.join(versionPath, 'template.json'),
directory: versionPath,
relativeFile: toPosix(path.relative(sourceRoot, path.join(versionPath, 'template.json'))),
parts: [moduleEntry.name, idEntry.name, versionEntry.name]
});
}
}
}
return results;
}
async function readSourceManifest(file: string, relativeFile: string): Promise<CreatorPresetSourceManifest> {
let value: unknown;
try {
value = JSON.parse(await readFile(file, 'utf8'));
} catch (error) {
throw new Error(`${relativeFile}: invalid JSON: ${errorMessage(error)}`);
}
try {
return creatorPresetSourceManifestSchema.parse(value) as CreatorPresetSourceManifest;
} catch (error) {
if (error instanceof ZodError) {
const detail = error.issues
.map(issue => `${relativeFile}.${issue.path.join('.') || '<root>'}: ${issue.message}`)
.join('\n');
throw new Error(detail);
}
throw error;
}
}
function validateDirectoryIdentity(
parts: [string, string, string],
manifest: CreatorPresetSourceManifest,
relativeFile: string
): void {
if (
parts[0] !== manifest.module
|| parts[1] !== manifest.id
|| !/^[1-9]\d*$/.test(parts[2])
|| Number(parts[2]) !== manifest.version
) {
throw new Error(`${relativeFile}: directory identity does not match module/id/version`);
}
}
function validateRuntimeBinding(
definition: CreatorPresetModuleDefinition,
manifest: CreatorPresetSourceManifest,
relativeFile: string
): void {
if (
manifest.runtimeTemplate.id !== definition.runtimeTemplate.id
|| manifest.runtimeTemplate.version !== definition.runtimeTemplate.version
) {
throw new Error(
`${relativeFile}.runtimeTemplate: expected ${definition.runtimeTemplate.id}@${definition.runtimeTemplate.version}`
);
}
}
function parseModuleDefaults(
definition: CreatorPresetModuleDefinition,
manifest: CreatorPresetSourceManifest,
relativeFile: string
): void {
const defaults = definition.defaultsSchema.safeParse(manifest.defaults);
if (!defaults.success) {
throw new Error(formatZodIssues(relativeFile, 'defaults', defaults.error));
}
for (const [locale, value] of Object.entries(manifest.defaultsByLocale ?? {})) {
const localized = definition.localeDefaultsSchema.safeParse(value);
if (!localized.success) {
throw new Error(formatZodIssues(relativeFile, `defaultsByLocale.${locale}`, localized.error));
}
}
}
async function validateCover(
sourceRoot: string,
directory: string,
coverPath: string,
relativeFile: string
): Promise<{
file: string;
extension: '.png' | '.jpg' | '.jpeg' | '.webp';
mime: 'image/png' | 'image/jpeg' | 'image/webp';
sha256: string;
width: number;
height: number;
size: number;
}> {
const image = await validateImageResource({
sourceRoot,
directory,
resourcePath: coverPath,
relativeFile,
field: 'cover',
maxSize: MAX_COVER_SIZE
});
if (image.width < 640 || image.height < 360) {
throw new Error(`${relativeFile}.cover: cover must be at least 640x360`);
}
if (image.width * 9 !== image.height * 16) {
throw new Error(`${relativeFile}.cover: cover must have a 16:9 aspect ratio`);
}
return image;
}
async function validatePreview(
sourceRoot: string,
directory: string,
previewPath: string,
relativeFile: string
): Promise<ValidatedImageResource> {
const image = await validateImageResource({
sourceRoot,
directory,
resourcePath: previewPath,
relativeFile,
field: 'preview',
maxSize: MAX_PREVIEW_SIZE
});
if (image.width < 640 || image.height < 360) {
throw new Error(`${relativeFile}.preview: preview must be at least 640x360`);
}
return image;
}
async function validateAuthorAvatar(
sourceRoot: string,
directory: string,
avatarPath: string,
relativeFile: string
): Promise<ValidatedImageResource> {
const image = await validateImageResource({
sourceRoot,
directory,
resourcePath: avatarPath,
relativeFile,
field: 'author.avatar',
maxSize: MAX_AUTHOR_AVATAR_SIZE
});
if (image.width < 48 || image.height < 48) {
throw new Error(`${relativeFile}.author.avatar: avatar must be at least 48x48`);
}
if (image.width !== image.height) {
throw new Error(`${relativeFile}.author.avatar: avatar must be square`);
}
return image;
}
type ValidatedVideoResource = {
file: string;
extension: '.mp4';
mime: 'video/mp4';
sha256: string;
size: number;
};
async function validatePreviewVideo(
sourceRoot: string,
directory: string,
videoPath: string,
relativeFile: string
): Promise<ValidatedVideoResource> {
const resource = await validateRegularResource({
sourceRoot,
directory,
resourcePath: videoPath,
relativeFile,
field: 'previewVideo',
maxSize: MAX_PREVIEW_VIDEO_SIZE
});
if (path.extname(videoPath).toLowerCase() !== '.mp4') {
throw new Error(`${relativeFile}.previewVideo: unsupported video extension`);
}
const bytes = await readFile(resource.file);
if (bytes.length < 12 || bytes.subarray(4, 8).toString('ascii') !== 'ftyp') {
throw new Error(`${relativeFile}.previewVideo: video contents do not match MP4`);
}
const duration = readMp4Duration(bytes);
if (duration !== undefined && duration > MAX_PREVIEW_VIDEO_DURATION_SECONDS) {
throw new Error(
`${relativeFile}.previewVideo: duration exceeds ${MAX_PREVIEW_VIDEO_DURATION_SECONDS} seconds`
);
}
return {
...resource,
extension: '.mp4',
mime: 'video/mp4',
sha256: sha256(bytes)
};
}
type Mp4Box = {
dataStart: number;
end: number;
};
// Keep preview validation self-contained so builds do not depend on ffprobe.
function readMp4Duration(bytes: Buffer): number | undefined {
const moov = findMp4Box(bytes, 0, bytes.length, 'moov');
if (moov === undefined) return undefined;
const mvhd = findMp4Box(bytes, moov.dataStart, moov.end, 'mvhd');
if (mvhd === undefined || mvhd.dataStart >= mvhd.end) return undefined;
const version = bytes[mvhd.dataStart];
if (version === 0) {
if (mvhd.dataStart + 20 > mvhd.end) return undefined;
const timescale = bytes.readUInt32BE(mvhd.dataStart + 12);
const duration = bytes.readUInt32BE(mvhd.dataStart + 16);
return timescale === 0 ? undefined : duration / timescale;
}
if (version === 1) {
if (mvhd.dataStart + 32 > mvhd.end) return undefined;
const timescale = bytes.readUInt32BE(mvhd.dataStart + 20);
const duration = bytes.readBigUInt64BE(mvhd.dataStart + 24);
return timescale === 0 ? undefined : Number(duration) / timescale;
}
return undefined;
}
function findMp4Box(
bytes: Buffer,
start: number,
end: number,
type: string
): Mp4Box | undefined {
let offset = start;
while (offset + 8 <= end) {
const size32 = bytes.readUInt32BE(offset);
const boxType = bytes.toString('ascii', offset + 4, offset + 8);
let headerSize = 8;
let boxSize: number;
if (size32 === 1) {
if (offset + 16 > end) return undefined;
const extendedSize = bytes.readBigUInt64BE(offset + 8);
if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return undefined;
boxSize = Number(extendedSize);
headerSize = 16;
} else if (size32 === 0) {
boxSize = end - offset;
} else {
boxSize = size32;
}
if (boxSize < headerSize || offset + boxSize > end) return undefined;
if (boxType === type) {
return { dataStart: offset + headerSize, end: offset + boxSize };
}
offset += boxSize;
}
return undefined;
}
type ValidatedImageResource = {
file: string;
extension: '.png' | '.jpg' | '.jpeg' | '.webp';
mime: 'image/png' | 'image/jpeg' | 'image/webp';
sha256: string;
width: number;
height: number;
size: number;
};
async function validateImageResource(input: {
sourceRoot: string;
directory: string;
resourcePath: string;
relativeFile: string;
field: 'cover' | 'preview' | 'author.avatar';
maxSize: number;
}): Promise<ValidatedImageResource> {
const { sourceRoot, directory, resourcePath, relativeFile, field, maxSize } = input;
const resource = await validateRegularResource(input);
const extension = path.extname(resourcePath).toLowerCase() as '.png' | '.jpg' | '.jpeg' | '.webp';
if (!COVER_EXTENSIONS.has(extension)) {
throw new Error(`${relativeFile}.${field}: unsupported image extension`);
}
const bytes = await readFile(resource.file);
const { default: sharp } = await import('sharp');
const dimensions = await sharp(bytes, { failOn: 'error' }).metadata();
if (dimensions.width === undefined || dimensions.height === undefined) {
throw new Error(`${relativeFile}.${field}: image dimensions are unavailable`);
}
const detectedExtension = detectedImageExtension(bytes);
if (detectedExtension === undefined || !extensionsMatch(extension, detectedExtension)) {
throw new Error(`${relativeFile}.${field}: image contents do not match extension`);
}
return {
file: resource.file,
extension,
mime: MIME_BY_EXTENSION.get(extension)!,
sha256: sha256(bytes),
width: dimensions.width,
height: dimensions.height,
size: resource.size
};
}
async function validateRegularResource(input: {
sourceRoot: string;
directory: string;
resourcePath: string;
relativeFile: string;
field: 'cover' | 'preview' | 'author.avatar' | 'previewVideo';
maxSize: number;
}): Promise<{ file: string; size: number }> {
const { sourceRoot, directory, resourcePath, relativeFile, field, maxSize } = input;
if (path.isAbsolute(resourcePath) || resourcePath.includes('\\')) {
throw new Error(`${relativeFile}.${field}: ${field} must be a POSIX relative path`);
}
const segments = resourcePath.split('/');
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
throw new Error(`${relativeFile}.${field}: traversal is not allowed`);
}
const file = path.resolve(directory, resourcePath);
const relative = path.relative(sourceRoot, file);
if (relative.startsWith('..') || path.isAbsolute(relative)) {
throw new Error(`${relativeFile}.${field}: ${field} escapes the template root`);
}
const fileInfo = await lstat(file).catch(() => undefined);
if (fileInfo === undefined || !fileInfo.isFile() || fileInfo.isSymbolicLink()) {
throw new Error(`${relativeFile}.${field}: ${field} must be a regular file`);
}
const sourceReal = await realpath(sourceRoot);
const fileReal = await realpath(file);
if (!isInside(sourceReal, fileReal)) {
throw new Error(`${relativeFile}.${field}: resolved ${field} escapes the template root`);
}
if (fileInfo.size > maxSize) {
throw new Error(`${relativeFile}.${field}: ${field} exceeds ${maxSize / 1024 / 1024} MiB`);
}
return { file, size: fileInfo.size };
}
function compileAsset(
sourceRoot: string,
resource: ValidatedImageResource
): CompiledCreatorPresetAsset {
return {
source: toPosix(path.relative(sourceRoot, resource.file)),
asset: `assets/${resource.sha256}${resource.extension}`,
sha256: resource.sha256,
mime: resource.mime,
width: resource.width,
height: resource.height,
size: resource.size
};
}
function compileVideoAsset(
sourceRoot: string,
resource: ValidatedVideoResource
): CompiledCreatorPresetVideoAsset {
return {
source: toPosix(path.relative(sourceRoot, resource.file)),
asset: `assets/${resource.sha256}${resource.extension}`,
sha256: resource.sha256,
mime: resource.mime,
size: resource.size
};
}
function normalizeSourceManifest(manifest: CreatorPresetSourceManifest): CreatorPresetSourceManifest {
return {
...manifest,
cover: toPosix(manifest.cover),
...(manifest.preview === undefined ? {} : { preview: toPosix(manifest.preview) }),
...(manifest.previewVideo === undefined
? {}
: { previewVideo: toPosix(manifest.previewVideo) }),
...(manifest.author === undefined ? {} : {
author: {
...manifest.author,
...(manifest.author.avatar === undefined
? {}
: { avatar: toPosix(manifest.author.avatar) })
}
}),
tags: [...new Set(manifest.tags)].sort((left, right) => left.localeCompare(right))
};
}
function comparePresets(left: CompiledCreatorPreset, right: CompiledCreatorPreset): number {
return left.module.localeCompare(right.module)
|| left.id.localeCompare(right.id)
|| left.version - right.version;
}
async function sortedDirectoryEntries(directory: string) {
return (await readdir(directory, { withFileTypes: true }))
.filter(entry => entry.name !== '.DS_Store')
.sort((left, right) => left.name.localeCompare(right.name));
}
async function rejectSymlink(entry: { isSymbolicLink(): boolean }, file: string): Promise<void> {
if (entry.isSymbolicLink()) {
throw new Error(`${toPosix(file)}: symbolic links are not allowed`);
}
}
async function assertDirectory(directory: string): Promise<void> {
const info = await lstat(directory).catch(() => undefined);
if (info === undefined || !info.isDirectory() || info.isSymbolicLink()) {
throw new Error(`${directory}: preset source root must be a real directory`);
}
}
async function listOutputFiles(
root: string,
initial: string[] = []
): Promise<CreatorPresetBuildManifest['files']> {
const paths = [...initial];
const walk = async (directory: string): Promise<void> => {
for (const entry of await sortedDirectoryEntries(directory)) {
const absolute = path.join(directory, entry.name);
const relative = toPosix(path.relative(root, absolute));
if (entry.isDirectory()) await walk(absolute);
else if (entry.isFile() && !paths.includes(relative)) paths.push(relative);
}
};
await walk(root);
paths.sort();
return Promise.all(paths.map(async relative => {
const bytes = await readFile(path.join(root, relative));
return {
path: relative,
sha256: sha256(bytes),
size: bytes.length
};
}));
}
async function syncTree(root: string): Promise<void> {
if (process.platform === 'win32') return;
const files = await listOutputFiles(root);
for (const file of files) {
const handle = await open(path.join(root, file.path), 'r');
try {
await handle.sync();
} finally {
await handle.close();
}
}
const directory = await open(root, 'r');
try {
await directory.sync();
} finally {
await directory.close();
}
}
function detectedImageExtension(bytes: Buffer): '.png' | '.jpg' | '.webp' | undefined {
if (bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return '.png';
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return '.jpg';
if (bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP') return '.webp';
return undefined;
}
function extensionsMatch(expected: string, actual: string): boolean {
return expected === actual || ((expected === '.jpg' || expected === '.jpeg') && actual === '.jpg');
}
function formatZodIssues(relativeFile: string, prefix: string, error: ZodError): string {
return error.issues
.map(issue => `${relativeFile}.${prefix}.${issue.path.join('.') || '<root>'}: ${issue.message}`)
.join('\n');
}
function isInside(root: string, candidate: string): boolean {
const relative = path.relative(root, candidate);
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function toPosix(value: string): string {
return value.split(path.sep).join('/');
}