#!/usr/bin/env node
// Draws each cover's exact title (and the small kicker line above it) onto its text-free art, locally, so every
// word is spelled exactly. Every title sits inside the title box from assets/safe-zones.json: inside the 3:4
// profile-grid crop and clear of the Reels and TikTok buttons and captions. By default the whole set shares one
// title size, so the covers read as a series.
//
// Usage:
// node scripts/compose-covers.mjs --series series.json --out-dir covers/
// [--font "Helvetica Neue"] [--font-file brand.ttf] [--per-cover-size] [--guides]
//
// Writes covers/cover-01.png ... (1080 x 1920 PNG) and covers/manifest.json (title boxes, title size, contrast
// and a fingerprint of each file) for scripts/check-covers.mjs and scripts/grid-preview.mjs.
// --guides also writes covers/guides/cover-01.png ... with the safe zones drawn over each cover.
// --font-file takes a .ttf or .otf; set --font to that font's family name so it is picked.
// Needs sharp: run `npm install sharp` in the Skill folder (Node 20.9 or newer).
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
let sharp
try {
sharp = (await import('sharp')).default
} catch {
console.error('This script needs the sharp package. Run `npm install sharp` in the Skill folder (Node 20.9 or newer), then try again.')
process.exit(1)
}
const FLAGS = new Set(['series', 'out-dir', 'font', 'font-file', 'per-cover-size', 'guides'])
const SWITCHES = new Set(['per-cover-size', 'guides'])
function fail(message) {
console.error(message)
process.exit(1)
}
const opts = {}
const argv = process.argv.slice(2)
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (!a.startsWith('--')) fail(`Unexpected argument "${a}". Flags look like --name value.`)
const key = a.slice(2)
if (!FLAGS.has(key)) fail(`Unknown flag --${key}. Allowed: ${[...FLAGS].map((f) => `--${f}`).join(', ')}`)
if (SWITCHES.has(key)) { opts[key] = true; continue }
const value = argv[i + 1]
if (value === undefined || value.startsWith('--')) fail(`--${key} needs a value.`)
opts[key] = value
i++
}
if (!opts.series || !opts['out-dir']) fail('Usage: node scripts/compose-covers.mjs --series series.json --out-dir covers/ [--font-file brand.ttf --font "Family"] [--per-cover-size] [--guides]')
if (!existsSync(opts.series)) fail(`Plan not found: ${opts.series}`)
let plan
try {
plan = JSON.parse(readFileSync(opts.series, 'utf8'))
} catch {
fail(`${opts.series} is not valid JSON.`)
}
const zones = JSON.parse(readFileSync(new URL('../assets/safe-zones.json', import.meta.url), 'utf8'))
const base = dirname(resolve(opts.series))
const rel = (p) => (isAbsolute(p) ? p : join(base, p))
const outDir = resolve(opts['out-dir'])
const style = plan.style ?? {}
const covers = plan.covers ?? []
if (![3, 6, 9].includes(covers.length)) fail(`The plan has ${covers.length} covers. Plan 3, 6 or 9.`)
const hex = (name, v) => {
if (typeof v !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(v)) fail(`style.${name} must be a #hex colour like #141414.`)
return v.toLowerCase()
}
const ink = hex('ink', style.ink ?? '#ffffff')
const accent = hex('accent', style.accent ?? '#141414')
const treatment = style.treatment ?? 'shadow'
const position = style.position ?? 'top'
const align = style.align ?? 'left'
const caseRule = style.case ?? 'as-written'
if (!['block', 'shadow', 'plain'].includes(treatment)) fail('style.treatment must be block, shadow or plain.')
if (!['top', 'middle', 'bottom'].includes(position)) fail('style.position must be top, middle or bottom.')
if (!['left', 'center'].includes(align)) fail('style.align must be left or center.')
if (!['as-written', 'upper'].includes(caseRule)) fail('style.case must be as-written or upper.')
const family = opts.font ?? style.font ?? 'Helvetica Neue'
if (!/^[A-Za-z0-9][A-Za-z0-9 ._-]{0,60}$/.test(family)) fail('The font must be a plain family name (letters, digits, spaces).')
const fontFile = opts['font-file'] ? resolve(opts['font-file']) : style.font_file ? rel(style.font_file) : ''
if (fontFile && !existsSync(fontFile)) fail(`Font file not found: ${fontFile}`)
const W = zones.frame.width
const H = zones.frame.height
const box = zones.title_box
const MIN = zones.min_title_px
const MAX = 156
// Centred titles keep equal margins on both sides, so they use the narrower column inside the title box.
const inset = Math.max(box.x, W - (box.x + box.width))
const col = align === 'center' ? { left: inset, right: W - inset } : { left: box.x + 6, right: box.x + box.width - 6 }
// Where the text block may sit for each position: the calm band the art leaves empty (assets/generation-input.json).
const BAND = {
top: [box.y + 24, Math.round(H * 0.41)],
middle: [Math.round(H * 0.23), Math.round(H * 0.57)],
bottom: [Math.round(H * 0.4), box.y + box.height - 24],
}
const maxBlock = BAND[position][1] - BAND[position][0]
const drawnTitle = (c) => (caseRule === 'upper' ? c.title.toUpperCase() : c.title)
const drawnKicker = (c) => {
const raw = (c.kicker || style.kicker || '').replace(/\{\{nn\}\}/g, String(c.n).padStart(2, '0')).replace(/\{\{n\}\}/g, String(c.n))
return raw.trim().toUpperCase()
}
for (const c of covers) {
if (typeof c.title !== 'string' || !c.title.trim()) fail(`Cover ${c.n} has no title.`)
if (c.title.trim().split(/\s+/).length > 6 || c.title.length > 32) fail(`Cover ${c.n} title "${c.title}" is too long: at most 6 words and 32 characters.`)
if (!c.art) fail(`Cover ${c.n} has no approved art in "art". Generate it (build-requests.mjs --stage final) and put the path in series.json.`)
if (!existsSync(rel(c.art))) fail(`Cover ${c.n} art not found: ${rel(c.art)}`)
}
const xml = (s) => String(s).replace(/[<>&]/g, (ch) => ({ '<': '<', '>': '>', '&': '&' })[ch])
const cache = new Map()
async function render(text, { size, color, spacing = 0, opacity = 1 }) {
const key = JSON.stringify([text, size, color, spacing, opacity])
if (cache.has(key)) return cache.get(key)
const alpha = opacity < 1 ? Math.round(opacity * 255).toString(16).padStart(2, '0') : ''
const markup = `${xml(text)}`
const options = { text: markup, font: `${family} Bold ${size}`, rgba: true, dpi: 72 }
if (fontFile) options.fontfile = fontFile
const { data, info } = await sharp({ text: options }).png().toBuffer({ resolveWithObject: true })
const r = { input: data, width: info.width, height: info.height }
cache.set(key, r)
return r
}
const pad = (size) => (treatment === 'block' ? { x: Math.round(size * 0.26), y: Math.round(size * 0.1) } : { x: 0, y: 0 })
const titleStyle = (size) => ({ size, color: ink, spacing: -size * 0.015 })
async function pack(words, size, limit) {
const lines = []
let cur = ''
for (const w of words) {
const next = cur ? `${cur} ${w}` : w
if (cur && (await render(next, titleStyle(size))).width > limit) { lines.push(cur); cur = w } else cur = next
}
if (cur) lines.push(cur)
return lines
}
/** The fewest lines (at most 3) that fit, balanced so no line is left with one short word; null if none fit. */
async function wrap(text, size) {
const limit = col.right - col.left - 2 * pad(size).x
const words = text.split(/\s+/).filter(Boolean)
const widths = await Promise.all(words.map(async (w) => (await render(w, titleStyle(size))).width))
if (Math.max(...widths) > limit) return null
if ((await render(words.join(' '), titleStyle(size))).width <= limit) return [words.join(' ')]
for (let n = 2; n <= 3; n++) {
if ((await pack(words, size, limit)).length > n) continue
let lo = Math.max(...widths)
let hi = limit
while (hi - lo > 6) {
const mid = Math.round((lo + hi) / 2)
if ((await pack(words, size, mid)).length <= n) hi = mid
else lo = mid
}
return pack(words, size, hi)
}
return null
}
/** Where the ink of a line sits inside its rendered image, from a sample with tall and deep letters. */
const metrics = new Map()
async function inkBox(size, spacing, sample) {
const key = `${size}|${spacing}|${sample}`
if (metrics.has(key)) return metrics.get(key)
const img = await render(sample, { size, color: '#000000', spacing })
const { info } = await sharp(img.input).trim().toBuffer({ resolveWithObject: true })
const top = -(info.trimOffsetTop ?? 0)
const m = { top, bottom: top + info.height }
metrics.set(key, m)
return m
}
/** The title and kicker layout for one cover at one size, or null when the title does not fit in 3 lines. */
async function layout(c, size) {
const title = drawnTitle(c)
const kicker = drawnKicker(c)
const lines = await wrap(title, size)
if (!lines) return null
const p = pad(size)
const m = await inkBox(size, titleStyle(size).spacing, caseRule === 'upper' ? 'H0' : 'Hhdkgjpqy')
const kSize = Math.max(40, Math.round(size * 0.32))
const kp = pad(kSize)
const kStyle = { size: kSize, color: treatment === 'block' ? ink : accent, spacing: kSize * 0.12 }
const km = kicker ? await inkBox(kSize, kStyle.spacing, 'H0') : null
const lineH = m.bottom - m.top + 2 * p.y
const pitch = treatment === 'block' ? lineH : Math.round(size * 1.1)
const kH = km ? km.bottom - km.top + 2 * kp.y : 0
const gap = km ? Math.round(size * 0.16) : 0
const blockH = kH + gap + pitch * (lines.length - 1) + lineH
return { title, kicker, lines, p, m, kSize, kp, kStyle, km, lineH, pitch, kH, gap, blockH }
}
async function largestSize(c) {
for (let size = MAX; size >= MIN; size -= 4) {
const l = await layout(c, size)
if (l && l.blockH <= maxBlock) return size
}
return 0
}
// One title size for the whole set (the largest every title fits at), unless --per-cover-size.
const fits = []
for (const c of covers) {
const size = await largestSize(c)
if (!size) fail(`Cover ${c.n}: "${drawnTitle(c)}" does not fit in 3 lines at ${MIN} px inside the calm band for a ${position} title. Shorten it (a long word is the usual cause).`)
fits.push(size)
}
const shared = Math.min(...fits)
function luminance(r, g, b) {
const lin = (v) => {
const s = v / 255
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
}
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
}
const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16))
const ratio = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
async function behind(baseImage, r) {
const x = Math.max(0, Math.round(r.x))
const y = Math.max(0, Math.round(r.y))
const width = Math.min(W - x, Math.round(r.width))
const height = Math.min(H - y, Math.round(r.height))
// stats() reads the input, not the pipeline, so crop to a buffer first or it measures the whole cover.
const crop = await sharp(baseImage).extract({ left: x, top: y, width, height }).toBuffer()
const stats = await sharp(crop).stats()
const [cr, cg, cb] = stats.channels
return { lum: luminance(cr.mean, cg.mean, cb.mean), busy: (cr.stdev + cg.stdev + cb.stdev) / 3 }
}
mkdirSync(outDir, { recursive: true })
if (opts.guides) mkdirSync(join(outDir, 'guides'), { recursive: true })
const records = []
for (const [index, c] of covers.entries()) {
const size = opts['per-cover-size'] ? fits[index] : shared
const L = await layout(c, size)
const { title, kicker, lines, p, m, kSize, kp, km } = L
const kImg = kicker ? await render(kicker, L.kStyle) : null
const imgs = await Promise.all(lines.map((t) => render(t, titleStyle(size))))
const top = position === 'top' ? BAND.top[0] : position === 'bottom' ? BAND.bottom[1] - L.blockH : Math.round((BAND.middle[0] + BAND.middle[1]) / 2 - L.blockH / 2)
const xFor = (w, padX) => (align === 'center' ? Math.round(W / 2 - w / 2) : col.left + padX)
const layers = []
const shapes = []
const boxes = []
const radius = (s) => Math.round(s * 0.16)
let y = top
if (kImg) {
const left = xFor(kImg.width, kp.x)
const r = { x: left - kp.x, y, width: kImg.width + 2 * kp.x, height: L.kH }
if (treatment === 'block') shapes.push(``)
boxes.push({ role: 'kicker', ...r })
layers.push({ input: kImg.input, left, top: y + kp.y - km.top })
y += L.kH + L.gap
}
for (const [i, img] of imgs.entries()) {
const left = xFor(img.width, p.x)
const lineTop = y + i * L.pitch
const r = { x: left - p.x, y: lineTop, width: img.width + 2 * p.x, height: L.lineH }
if (treatment === 'block') shapes.push(``)
boxes.push({ role: 'title', line: i + 1, ...r })
layers.push({ input: img.input, left, top: lineTop + p.y - m.top })
}
const art = rel(c.art)
const baseImage = await sharp(art).resize(W, H, { fit: 'cover' }).png().toBuffer()
const meta = await sharp(art).metadata()
if (meta.width < W || meta.height < H) console.warn(`warning: cover ${c.n} art is ${meta.width} x ${meta.height}, smaller than ${W} x ${H}, so it is upscaled. Use the final art (1088 x 1936), not a draft.`)
if (Math.abs(meta.width / meta.height - 9 / 16) > 0.02) console.warn(`warning: cover ${c.n} art is ${meta.width} x ${meta.height}, not 9:16, so its edges are cropped.`)
// Contrast between the title colour and what sits behind it (the block, or the average of the art).
const titleBoxes = boxes.filter((b) => b.role === 'title')
let contrast
let busy = 0
if (treatment === 'block') contrast = ratio(luminance(...rgb(ink)), luminance(...rgb(accent)))
else {
const seen = await Promise.all(titleBoxes.map((b) => behind(baseImage, b)))
contrast = Math.min(...seen.map((s) => ratio(luminance(...rgb(ink)), s.lum)))
busy = Math.max(...seen.map((s) => s.busy))
}
const extra = []
if (treatment === 'shadow') {
for (const i of imgs.keys()) {
const spread = Math.round(size * 0.18)
const shade = await render(lines[i], { ...titleStyle(size), color: '#000000', opacity: 0.6 })
const blurred = await sharp(shade.input).extend({ top: spread, bottom: spread, left: spread, right: spread, background: { r: 0, g: 0, b: 0, alpha: 0 } }).blur(Math.max(1, size * 0.07)).png().toBuffer()
const l = layers[(kImg ? 1 : 0) + i]
extra.push({ input: blurred, left: l.left - spread, top: l.top - spread + Math.round(size * 0.04) })
}
if (kImg) {
const spread = Math.round(kSize * 0.3)
const shade = await render(kicker, { size: kSize, color: '#000000', spacing: kSize * 0.12, opacity: 0.6 })
const blurred = await sharp(shade.input).extend({ top: spread, bottom: spread, left: spread, right: spread, background: { r: 0, g: 0, b: 0, alpha: 0 } }).blur(Math.max(1, kSize * 0.08)).png().toBuffer()
extra.push({ input: blurred, left: layers[0].left - spread, top: layers[0].top - spread + 2 })
}
}
const svg = Buffer.from(``)
const name = `cover-${String(c.n).padStart(2, '0')}.png`
const file = join(outDir, name)
const png = await sharp(baseImage).composite([...extra, { input: svg, left: 0, top: 0 }, ...layers]).png().toBuffer()
writeFileSync(file, png)
if (opts.guides) {
const keepOut = zones.zones.filter((z) => z.kind === 'keep-out').map((z) => ``)
const grid = zones.zones.find((z) => z.id === 'grid-3x4').rect
const square = zones.zones.find((z) => z.id === 'square-1x1').rect
const guide = ``
await sharp(png).composite([{ input: Buffer.from(guide), left: 0, top: 0 }]).png().toFile(join(outDir, 'guides', name))
}
const sha = (buf) => createHash('sha256').update(buf).digest('hex')
records.push({
n: c.n,
file: name,
sha256: sha(png),
art: relative(outDir, art),
art_sha256: sha(readFileSync(art)),
title: c.title,
title_drawn: title,
kicker_drawn: kicker,
lines,
title_px: size,
boxes,
contrast: Number(contrast.toFixed(2)),
busy: Number(busy.toFixed(1)),
})
const bottom = Math.max(...boxes.map((b) => b.y + b.height))
console.log(`${file} ${W}x${H}, title ${size}px, ${lines.length} line(s), text from y ${Math.min(...boxes.map((b) => b.y))} to ${bottom}, contrast ${contrast.toFixed(1)}:1`)
}
const manifest = {
schema: 'reel-cover-set-manifest/1',
series: plan.series?.name ?? '',
plan: relative(outDir, resolve(opts.series)),
zones_checked: zones.checked,
frame: { width: W, height: H },
settings: { font: fontFile ? relative(outDir, fontFile) : family, ink, accent, treatment, position, align, case: caseRule, shared_size: !opts['per-cover-size'], title_px: shared },
covers: records,
}
writeFileSync(join(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)
console.log(`Fonts: ${fontFile || `${family} Bold`} (system fonts are resolved by fontconfig; a missing family falls back, DejaVu on Linux). Pass --font-file for exact brand type.`)
console.log(`Wrote ${join(outDir, 'manifest.json')}. Next: node scripts/check-covers.mjs --series ${opts.series} --manifest ${join(opts['out-dir'], 'manifest.json')}`)