Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.
// Định dạng gói mẫu .lumpack (1 file JSON) — đọc + kiểm (L8, L6, L7, L10, L11), cài nguyên tử, gỡ, xuất.
// THIET-KE gói mẫu §2. Không lấy đường dẫn nào từ trong gói: mọi file ghi ra tự ghép từ id/slug đã kiểm.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { lintGuidance, lintEditStyle, lintWebp } from './lint.mjs';
import {
packsDir, packDir, validPackId, validSlug, RESERVED_AUTHORS, KINDS, readPackManifest, resolveTemplate, resolveEditStyle,
parsePackRef, listPacks,
} from './registry.mjs';
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
export const ENGINE_VERSION = (() => { try { return JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version; } catch { return '0.0.0'; } })();
export const MAX_FILE_BYTES = 12 * 1024 * 1024;
export const MAX_ITEMS = 200;
export const LICENSES = ['CC0-1.0', 'CC-BY-4.0', 'CC-BY-SA-4.0', 'MIT'];
export const PROVENANCE = ['original', 'own-video', 'style-study'];
const TOP_KEYS = ['lumpack', 'id', 'version', 'name', 'nameEn', 'description', 'author', 'license', 'engine', 'createdAt', 'provenance', 'items', 'contentHash', 'sig'];
const ITEM_KEYS = ['kind', 'slug', 'spec', 'text', 'blurb', 'thumb'];
const SEMVER = /^(\d{1,4})\.(\d{1,4})\.(\d{1,4})$/;
// eslint-disable-next-line no-control-regex
const PLAIN = /^[^<>{}`\\\u0000-\u001f\u007f]*$/u;
const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex');
export function cmpVersion(a, b) {
const x = SEMVER.exec(a).slice(1).map(Number); const y = SEMVER.exec(b).slice(1).map(Number);
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
return 0;
}
/** sha256 của "kind\nslug\nsha256(text)\nsha256(byte ảnh hoặc rỗng)\n" theo thứ tự kind, slug. */
export function contentHash(items) {
const lines = [...items].sort((a, b) => (a.kind === b.kind ? (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0) : a.kind < b.kind ? -1 : 1))
.map((it) => `${it.kind}\n${it.slug}\n${sha256(Buffer.from(it.text, 'utf8'))}\n${sha256(it.thumb ? Buffer.from(it.thumb, 'base64') : Buffer.alloc(0))}\n`);
return 'sha256:' + sha256(lines.join(''));
}
/**
* Đọc + kiểm 1 gói. input: Buffer | đường dẫn file. opts.source: 'file' | 'library' | 'local' | 'export'.
* Trả {manifest, items:[{kind, slug, text (đã chuẩn hoá), blurb, thumbBuf, preset?, frontmatter?, warnings[]}], report:{errors[], warnings[]}, fileSha256}.
* Có lỗi thì items vẫn trả (để xem) nhưng installPack từ chối.
*/
export function readPack(input, { source = 'file' } = {}) {
const errors = [];
const warnings = [];
const fail = (msg) => ({ manifest: null, items: [], report: { errors: [...errors, msg], warnings }, fileSha256: null });
let buf;
if (Buffer.isBuffer(input)) buf = input;
else {
let st;
try { st = fs.statSync(input); } catch { return fail('không đọc được file gói'); }
if (!st.isFile()) return fail('không phải file');
if (st.size > MAX_FILE_BYTES) return fail(`file gói > ${MAX_FILE_BYTES / 1024 / 1024} MB`);
buf = fs.readFileSync(input);
}
if (buf.length > MAX_FILE_BYTES) return fail(`file gói > ${MAX_FILE_BYTES / 1024 / 1024} MB`);
const fileSha256 = sha256(buf);
let j;
try { j = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(buf)); } catch { return { ...fail('không phải file gói (.lumpack là JSON UTF-8)'), fileSha256 }; }
if (!j || typeof j !== 'object' || Array.isArray(j)) return { ...fail('không phải file gói'), fileSha256 };
if (j.lumpack !== 1) return { ...fail('không phải gói LumReels (thiếu "lumpack": 1) hoặc định dạng mới hơn'), fileSha256 };
const extra = Object.keys(j).filter((k) => !TOP_KEYS.includes(k));
if (extra.length) errors.push(`khoá lạ ở gói: ${extra.slice(0, 5).join(', ')}`);
const str = (v, max, name, { required = true } = {}) => {
if (v === undefined && !required) return;
if (typeof v !== 'string' || !v.trim() || v.length > max || !PLAIN.test(v)) errors.push(`${name}: chữ 1–${max} ký tự, không có < > { } \` \\ hay ký tự điều khiển`);
};
// id + tác giả dành riêng (2.3)
if (!validPackId(j.id)) errors.push('id gói phải dạng tac-gia.ten-goi (chữ thường, số, gạch nối; mỗi nửa 2–24 ký tự)');
else {
const author = j.id.split('.')[0];
if (author === 'local' && source !== 'local') errors.push('tác giả "local" chỉ dành cho mẫu tự tạo trên máy');
if (['lumreels', 'lumtek'].includes(author) && source !== 'export') errors.push(`tác giả "${author}" chỉ nhận khi có chữ ký hợp lệ (bản này chưa kiểm chữ ký)`);
}
if (typeof j.version !== 'string' || !SEMVER.test(j.version)) errors.push('version phải dạng 1.0.0');
str(j.name, 60, 'name'); str(j.nameEn, 60, 'nameEn', { required: false }); str(j.description, 300, 'description', { required: false });
if (!j.author || typeof j.author !== 'object' || Array.isArray(j.author)) errors.push('author phải là {name, contact?}');
else {
const ak = Object.keys(j.author).filter((k) => !['name', 'contact'].includes(k));
if (ak.length) errors.push(`khoá lạ ở author: ${ak.join(', ')}`);
str(j.author.name, 60, 'author.name'); str(j.author.contact, 100, 'author.contact', { required: false });
}
if (!LICENSES.includes(j.license)) errors.push(`license phải là 1 trong ${LICENSES.join(', ')}`);
if (!j.engine || typeof j.engine !== 'object' || Object.keys(j.engine).some((k) => k !== 'min') || typeof j.engine.min !== 'string' || !SEMVER.test(j.engine.min)) errors.push('engine phải là {min: "x.y.z"}');
else if (cmpVersion(j.engine.min, ENGINE_VERSION) > 0) errors.push(`gói cần LumReels ≥ ${j.engine.min} (máy này: ${ENGINE_VERSION})`);
if (j.createdAt !== undefined && (typeof j.createdAt !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(j.createdAt))) errors.push('createdAt phải dạng YYYY-MM-DD');
if (!PROVENANCE.includes(j.provenance)) errors.push(`provenance phải là 1 trong ${PROVENANCE.join(', ')}`);
if (j.sig !== null && j.sig !== undefined) warnings.push('gói có chữ ký nhưng bản này chưa kiểm chữ ký: bỏ qua (không nới quyền)');
if (!Array.isArray(j.items) || !j.items.length) return { ...fail('gói không có mục nào'), fileSha256 };
if (j.items.length > MAX_ITEMS) return { ...fail(`gói có ${j.items.length} mục, tối đa ${MAX_ITEMS}`), fileSha256 };
const items = [];
const seen = new Set();
j.items.forEach((it, i) => {
const at = `mục ${i + 1}`;
if (!it || typeof it !== 'object' || Array.isArray(it)) { errors.push(`${at}: phải là object`); return; }
const ik = Object.keys(it).filter((k) => !ITEM_KEYS.includes(k));
if (ik.length) errors.push(`${at}: khoá lạ ${ik.slice(0, 5).join(', ')}`);
if (!KINDS[it.kind]) { errors.push(`${at}: kind phải là template | edit-style`); return; }
if (!validSlug(it.slug)) { errors.push(`${at}: slug "${String(it.slug).slice(0, 40)}" không hợp lệ (chữ thường/số/gạch nối, 2–32 ký tự, không phải tên thiết bị Windows)`); return; }
const name = `${at} (${it.kind} ${it.slug})`;
const key = `${it.kind}/${it.slug}`;
if (seen.has(key)) errors.push(`${name}: trùng slug`);
seen.add(key);
if (it.spec !== 1) errors.push(`${name}: spec phải = 1`);
if (typeof it.text !== 'string') { errors.push(`${name}: thiếu text`); return; }
if (it.blurb !== undefined) str(it.blurb, 140, `${name} blurb`);
const r = it.kind === 'template' ? lintGuidance(it.text) : lintEditStyle(it.text, { slug: it.slug });
for (const e of r.errors) errors.push(`${name}: ${e}`);
let thumbBuf = null;
if (it.thumb !== undefined && it.thumb !== null) {
if (typeof it.thumb !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(it.thumb) || it.thumb.length > 300 * 1024) errors.push(`${name}: ảnh phải là base64 ≤ 200 KB`);
else {
thumbBuf = Buffer.from(it.thumb, 'base64');
for (const e of lintWebp(thumbBuf).errors) errors.push(`${name}: ${e}`);
}
}
items.push({ kind: it.kind, slug: it.slug, text: r.text, rawText: it.text, blurb: it.blurb, thumbBuf, preset: r.preset, frontmatter: r.frontmatter, warnings: r.warnings });
for (const w of r.warnings) warnings.push(`${name}: ${w}`);
});
if (typeof j.contentHash !== 'string') errors.push('thiếu contentHash');
else if (!errors.length && contentHash(j.items) !== j.contentHash) errors.push('contentHash không khớp nội dung (file bị sửa?)');
const { items: _i, ...rest } = j;
const manifest = { ...rest, items: items.map((x) => ({ kind: x.kind, slug: x.slug, spec: 1, ...(x.blurb ? { blurb: x.blurb } : {}), thumb: !!x.thumbBuf })) };
return { manifest, items, report: { errors, warnings }, fileSha256 };
}
/** Một lúc 1 lượt cài (L12). */
let installing = false;
/**
* Cài gói đã đọc (kết quả readPack). opts.replace: cho thay bản đã cài (phiên bản cao hơn).
* Nguyên tử: ghi vào packs/.tmp-<rand> rồi rename; lỗi giữa chừng thì xoá thư mục tạm. Trả manifest đã cài.
*/
export function installPack(pack, { source = 'file', replace = false } = {}) {
if (!pack?.manifest || pack.report.errors.length) throw new Error('gói bị từ chối: ' + (pack?.report?.errors?.[0] || 'không đọc được'));
if (installing) throw new Error('đang cài 1 gói khác');
installing = true;
const id = pack.manifest.id;
const base = packsDir();
const dest = packDir(id);
let tmp = null;
try {
const cur = readPackManifest(id);
if (cur) {
const c = cmpVersion(pack.manifest.version, cur.version);
if (c === 0 && cur.contentHash === pack.manifest.contentHash) throw new Error(`gói ${id} ${cur.version} đã cài rồi`);
if (c === 0) throw new Error(`gói ${id} ${cur.version} đã cài, bản này cùng phiên bản mà nội dung khác: từ chối`);
if (c < 0) throw new Error(`đã cài ${id} ${cur.version}, mới hơn bản này (${pack.manifest.version})`);
if (!replace) throw new Error(`đã cài ${id} ${cur.version}; cài ${pack.manifest.version} cần --replace`);
}
fs.mkdirSync(base, { recursive: true });
tmp = path.join(base, `.tmp-${crypto.randomBytes(6).toString('hex')}`);
fs.mkdirSync(tmp);
const inTmp = (...p) => {
const f = path.resolve(tmp, ...p);
if (!f.startsWith(tmp + path.sep)) throw new Error('đường dẫn ra ngoài thư mục gói');
return f;
};
for (const sub of ['templates', 'styles', 'thumbs']) fs.mkdirSync(inTmp(sub));
for (const it of pack.items) {
if (!validSlug(it.slug) || !KINDS[it.kind]) throw new Error('mục không hợp lệ');
fs.writeFileSync(inTmp(KINDS[it.kind], `${it.slug}.md`), it.text, { flag: 'wx' });
if (it.thumbBuf) fs.writeFileSync(inTmp('thumbs', `${it.kind}-${it.slug}.webp`), it.thumbBuf, { flag: 'wx' });
}
const manifest = { ...pack.manifest, installedAt: new Date().toISOString(), source, fileSha256: pack.fileSha256, verified: false };
fs.writeFileSync(inTmp('pack.json'), JSON.stringify(manifest, null, 2));
let old = null;
if (fs.existsSync(dest)) { old = path.join(base, `.old-${crypto.randomBytes(6).toString('hex')}`); fs.renameSync(dest, old); }
try { fs.renameSync(tmp, dest); } catch (e) { if (old) fs.renameSync(old, dest); throw e; }
tmp = null;
if (old) fs.rmSync(old, { recursive: true, force: true });
return manifest;
} finally {
if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
installing = false;
}
}
/** Gỡ cả gói. local.mine (mẫu tự tạo) không gỡ cả gói được. Job cũ vẫn chạy lại được (PROMPT.md đã chụp guidance). */
export function uninstallPack(packId) {
if (packId === 'local.mine') throw new Error('không gỡ cả local.mine được, chỉ xoá từng mục');
const d = packDir(packId);
if (!fs.existsSync(path.join(d, 'pack.json'))) throw new Error(`chưa cài gói ${packId}`);
fs.rmSync(d, { recursive: true, force: true });
return true;
}
/** Xoá 1 mục của gói tự tạo (local.*). Gói cộng đồng chỉ gỡ cả gói. Hết mục thì xoá luôn thư mục gói. */
export function removeItem(packId, kind, slug) {
if (!String(packId).startsWith('local.')) throw new Error('chỉ xoá từng mục được với mẫu tự tạo; gói cộng đồng thì gỡ cả gói');
if (!KINDS[kind] || !validSlug(slug)) throw new Error('mục không hợp lệ');
const d = packDir(packId);
const man = readPackManifest(packId);
if (!man?.items?.some((x) => x.kind === kind && x.slug === slug)) throw new Error(`không thấy mục ${kind} ${slug} trong ${packId}`);
const items = man.items.filter((x) => !(x.kind === kind && x.slug === slug));
if (!items.length) { fs.rmSync(d, { recursive: true, force: true }); return { removed: true, packRemoved: true }; }
const tmp = path.join(d, `.pack-${crypto.randomBytes(4).toString('hex')}.json`);
fs.writeFileSync(tmp, JSON.stringify({ ...man, items }, null, 2));
fs.renameSync(tmp, path.join(d, 'pack.json'));
fs.rmSync(path.join(d, KINDS[kind], `${slug}.md`), { force: true });
fs.rmSync(path.join(d, 'thumbs', `${kind}-${slug}.webp`), { force: true });
return { removed: true, packRemoved: false };
}
/** "009" | "template:009" | "style:sach-gon" | "tac-gia.goi/slug" → {kind, ref, file, thumbFile, slug, blurb} */
function resolveItem(spec) {
const m = /^(template|style|edit-style):(.+)$/.exec(String(spec).trim());
const want = m ? (m[1] === 'template' ? 'template' : 'edit-style') : null;
const ref = m ? m[2] : String(spec).trim();
const t = want !== 'edit-style' ? resolveTemplate(ref) : null;
const s = want !== 'template' ? resolveEditStyle(ref) : null;
if (t && s) throw new Error(`"${ref}" vừa là mẫu dựng vừa là cách dựng: ghi rõ template:${ref} hoặc style:${ref}`);
if (t) {
if (!t.file) throw new Error(`mẫu ${ref} chưa có guidance`);
const slug = t.source === 'builtin' ? `mau-${t.ref}` : parsePackRef(t.ref).slug;
return { kind: 'template', ref: t.ref, file: t.file, thumbFile: t.thumbFile, slug, blurb: t.meta.blurb || undefined, packId: t.packId };
}
if (s) return { kind: 'edit-style', ref: s.ref, file: s.file, thumbFile: s.thumbFile, slug: s.slug, packId: s.packId };
throw new Error(`không thấy mẫu / cách dựng "${ref}"`);
}
/** Xuất gói → {buffer, report}. Gói không qua bộ kiểm lúc nhập thì không xuất (throw). */
export function exportPack({ id, version = '1.0.0', name, nameEn, description, author, license = 'CC-BY-4.0', provenance = 'original', items, createdAt }) {
if (!Array.isArray(items) || !items.length) throw new Error('chưa chọn mục nào để xuất');
const out = [];
for (const spec of items) {
const r = resolveItem(spec);
const lint = r.kind === 'template' ? lintGuidance(fs.readFileSync(r.file)) : lintEditStyle(fs.readFileSync(r.file), { slug: r.slug });
if (lint.errors.length) throw new Error(`${r.ref}: ${lint.errors[0]}`);
// §4.3 luật 3: ảnh của mẫu tự tạo phải cắt từ job dựng thử trên máy (thumbFrom ghi lúc Lưu), không bao giờ từ video tham khảo
if (r.packId === 'local.mine' && r.thumbFile && !readPackManifest('local.mine')?.items?.find((x) => x.kind === r.kind && x.slug === r.slug)?.thumbFrom) {
throw new Error(`${r.ref}: ảnh đại diện không ghi nguồn từ job dựng thử (thiếu thumbFrom) — không xuất`);
}
const thumb = r.thumbFile ? fs.readFileSync(r.thumbFile) : null;
out.push({ kind: r.kind, slug: r.slug, spec: 1, text: lint.text, ...(r.blurb ? { blurb: r.blurb.slice(0, 140) } : {}), ...(thumb ? { thumb: thumb.toString('base64') } : {}) });
}
const pack = {
lumpack: 1, id, version, name, ...(nameEn ? { nameEn } : {}), ...(description ? { description } : {}),
author: typeof author === 'string' ? { name: author } : author, license, engine: { min: ENGINE_VERSION },
createdAt: createdAt || new Date().toISOString().slice(0, 10), provenance, items: out, contentHash: contentHash(out), sig: null,
};
const buffer = Buffer.from(JSON.stringify(pack, null, 1) + '\n', 'utf8');
const check = readPack(buffer, { source: 'export' });
if (check.report.errors.length) throw new Error('gói không qua bộ kiểm: ' + check.report.errors.slice(0, 3).join(' | '));
return { buffer, report: check.report, manifest: check.manifest, fileSha256: check.fileSha256 };
}
/** Mã tham chiếu mọi mục của các gói đã cài (cho `pack export --mine`). */
export function mineRefs() {
const m = listPacks().find((p) => p.id === 'local.mine');
return m ? m.items.map((x) => `${x.kind === 'template' ? 'template' : 'style'}:local.mine/${x.slug}`) : [];
}