import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import type { SeedEntryInput } from "./cli"; import { DocumentMetadataError, validateDescription } from "./store/validation"; export type SeedFileEntry = { name: string; description?: string; }; export function exportSeedFiles( directory: string, names: string[], batchSize: number, ): string[] { mkdirSync(directory, { recursive: true }); const files: string[] = []; for (let index = 0; index < names.length; index += batchSize) { const entries = names .slice(index, index + batchSize) .map((name) => ({ name })); const file = join(directory, `seed-${String(files.length + 1).padStart(4, "0")}.json`); writeFileSync(file, `${JSON.stringify({ entries }, null, 2)}\n`); files.push(file); } return files; } export function importSeedFiles(directory: string): SeedEntryInput[] { const files = readdirSync(directory) .filter((file) => file.endsWith(".json")) .sort(); const entries: SeedEntryInput[] = []; for (const file of files) { const payload = JSON.parse(readFileSync(join(directory, file), "utf8")) as { entries?: SeedFileEntry[]; }; if (!Array.isArray(payload.entries)) { throw new Error(`seed file \`${file}\` must contain an entries array`); } for (const entry of payload.entries) { if (!entry.name?.trim()) { throw new Error(`seed file \`${file}\` contains an entry with an empty name`); } const normalized: SeedEntryInput = { name: entry.name.trim() }; if (entry.description !== undefined) { normalized.description = validateDescription(entry.description); } entries.push(normalized); } } return entries; } export function fallbackSeedDescription(): string { return "Installed command line tool available on this system."; } export function normalizeSeedDescription(description?: string): string { if (description === undefined) { return fallbackSeedDescription(); } try { return validateDescription(description); } catch (error) { if (error instanceof DocumentMetadataError) { throw error; } throw error; } }