@senseihq/emaki-cli 0.1.1 → 0.1.2

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.
@@ -0,0 +1,74 @@
1
+ // emaki stage (+ status, requests, reply), publish, carousel: after the build, stage for approval on the posting desk,
2
+ // or publish straight to a platform. Credentials come from the environment only (STAGER_*, MEDIA_URL_SECRET, YT_*,
3
+ // IG_*; see the README).
4
+ import { MotionError } from '../util.js'
5
+ import { act, P } from './run.js'
6
+
7
+ const list = (v) => [v ?? []].flat().flatMap((x) => String(x).split(',')).map((x) => x.trim()).filter(Boolean)
8
+
9
+ /** Staging on the desk, publishing, and the carousel. */
10
+ export function postingCommands(prog) {
11
+ prog.command('stage <slug>')
12
+ .describe('Upload a finished piece\'s media and post text to the posting desk for approval (STAGER_CLIENT_ID/SECRET).')
13
+ .option('--channels', 'youtube,instagram_reel,instagram_carousel,x (default: all)')
14
+ .option('--locale', 'Locale (default: the site default)')
15
+ .option('--dry-run', 'Print the posts; send nothing', false)
16
+ .action(act(async (slug, o) => {
17
+ const { stage } = await import('../stage.js')
18
+ await stage(P(), slug, { locale: o.locale, channels: o.channels ? list(o.channels) : undefined, dryRun: o['dry-run'] })
19
+ }))
20
+
21
+ prog.command('stage status [slug]')
22
+ .describe('Report each piece\'s script and what is produced to the desk\'s plan.')
23
+ .option('--locale', 'Locale (default: the site default)')
24
+ .action(act(async (slug, o) => {
25
+ const { productionStatus } = await import('../desk-plan.js')
26
+ await productionStatus(P(), slug, { locale: o.locale })
27
+ }))
28
+
29
+ prog.command('stage requests')
30
+ .describe('The open motion requests from the desk, with their threads.')
31
+ .action(act(async () => {
32
+ const { deskRequests } = await import('../desk-plan.js')
33
+ await deskRequests(P())
34
+ }))
35
+
36
+ prog.command('stage reply <id> [text]')
37
+ .describe('Answer a motion request; --working or --done moves it on.')
38
+ .option('--working', 'Mark it working', false)
39
+ .option('--done', 'Mark it done', false)
40
+ .action(act(async (id, text, o) => {
41
+ if (o.working && o.done) throw new MotionError('--working or --done, not both')
42
+ const { deskReply } = await import('../desk-plan.js')
43
+ await deskReply(P(), id, text ?? '', { status: o.done ? 'done' : o.working ? 'working' : undefined })
44
+ }))
45
+
46
+ prog.command('publish <channel> [slug]')
47
+ .describe('Post a finished film straight to youtube or instagram and record the link (YT_* / IG_* keys).')
48
+ .option('--locale', 'Locale (default: the site default)')
49
+ .option('--privacy', 'YouTube: public | unlisted | private', 'unlisted')
50
+ .option('--update', 'YouTube: refresh this uploaded video id in place (no re-upload)')
51
+ .option('--force-new', 'YouTube: upload even when an id is already recorded', false)
52
+ .option('--description-mode', 'With --update: prepend | replace', 'prepend')
53
+ .option('--video-url', 'Instagram: public MP4 URL (skips staging on the desk)')
54
+ .option('--cover-url', 'Instagram: public JPEG URL for the cover (with --video-url)')
55
+ .option('--dry-run', 'Print exactly what would post; touch nothing', false)
56
+ .option('--verify', 'Check the credentials (read-only) and name the account', false)
57
+ .action(act(async (channel, slug, o) => {
58
+ if (!o.verify && !slug) throw new MotionError('a slug is required (or --verify)')
59
+ const { publish } = await import('../publish.js')
60
+ await publish(P(), channel, slug, {
61
+ locale: o.locale, privacy: o.privacy, update: o.update && String(o.update), forceNew: o['force-new'], descriptionMode: o['description-mode'],
62
+ videoUrl: o['video-url'], coverUrl: o['cover-url'], dryRun: o['dry-run'], verify: o.verify
63
+ })
64
+ }))
65
+
66
+ prog.command('carousel [slug]')
67
+ .describe('Render a campaign day\'s Instagram carousel (1080×1350 PNGs) from its day script (needs Playwright).')
68
+ .option('--all', 'Every day script', false)
69
+ .option('--locale', 'Locale (default: the site default)')
70
+ .action(act(async (slug, o) => {
71
+ const { carousel } = await import('../carousel.js')
72
+ await carousel(P(), [slug, ...o._].filter(Boolean).map(String), { all: o.all, locale: o.locale })
73
+ }))
74
+ }
@@ -0,0 +1,128 @@
1
+ // emaki sheet, tts-check, set-voice, voices, voice, fit, voice-web, render, build: the production steps, per film and
2
+ // per locale.
3
+ import { MotionError, parseOpts } from '../util.js'
4
+ import { act, loc, P } from './run.js'
5
+
6
+ /** A tts-check row's provider: its label, and whether it is ready here. */
7
+ const providerState = (x) => `${x.provider} (${x.label}) ${x.ready ? 'ready' : `not ready: ${x.note}`}`
8
+
9
+ /** One scene of the fit table: design, holds, take and running time, and whether it now runs longer or shorter. */
10
+ function fitRow(x) {
11
+ const change = x.longer ? ' ← longer' : x.shorter ? ' ← shorter' : ''
12
+ return `${x.scene.padEnd(12)} ${x.design.toFixed(1).padStart(6)} ${x.holds.toFixed(1).padStart(6)} ${x.take.toFixed(1).padStart(6)} ${x.runs.toFixed(1).padStart(6)}${change}${x.take ? '' : ' (no take)'}`
13
+ }
14
+
15
+ /** The production steps: sheet, voice, fit, render, build. */
16
+ export function productionCommands(prog) {
17
+ prog.command('sheet <slug>')
18
+ .describe('Contact sheet: each scene\'s final picture in both orientations (needs Playwright).')
19
+ .option('--locale', 'Locale (default: the site default)')
20
+ .option('--url', 'A running site (default: start the dev server)')
21
+ .option('--at', 'scene:t,scene:t instead of each scene\'s final picture')
22
+ .action(act(async (slug, o) => {
23
+ const { sheet } = await import('../capture.js')
24
+ const p = P()
25
+ await sheet(p, slug, { locale: loc(o, p), url: o.url, at: o.at })
26
+ }))
27
+
28
+ prog.command('tts-check')
29
+ .describe('Which voice provider each locale uses, whether it is ready here, and which offline engines exist.')
30
+ .action(act(async () => {
31
+ const { ttsCheck } = await import('../voice.js')
32
+ const r = ttsCheck(P())
33
+ for (const x of r.rows) console.info(`${x.locale}: ${x.provider ? providerState(x) : 'no provider set'}`)
34
+ console.info(`offline engines on this machine: ${r.offline.join(', ') || 'none'}`)
35
+ }))
36
+
37
+ prog.command('set-voice')
38
+ .describe('Choose the voice provider for a locale (or "default"); options with --opt key=value. Keys stay in env vars.')
39
+ .option('--locale', 'Locale, a language, or default', 'default')
40
+ .option('--provider', 'piper | kokoro | macos | espeak | elevenlabs | openai | azure | google | polly | manual')
41
+ .option('--opt', 'key=value (voice, voice_id, model, instructions, rate, …); repeatable')
42
+ .action(act(async (o) => {
43
+ const { setVoice } = await import('../voice.js')
44
+ if (!o.provider) throw new MotionError('--provider is required')
45
+ const r = setVoice(P(), o.locale, o.provider, parseOpts(o.opt))
46
+ r.dropped.forEach((k) => console.info(`dropped "${k}": keys belong in environment variables, not emaki.config.json`))
47
+ console.info(`voice.${o.locale} = ${JSON.stringify(r.block)}`)
48
+ }))
49
+
50
+ prog.command('voices')
51
+ .describe('List the voices a provider offers for a locale.')
52
+ .option('--locale', 'Locale (default: the site default)')
53
+ .option('--provider', 'Override the configured provider')
54
+ .action(act(async (o) => {
55
+ const { listVoices } = await import('../voice.js')
56
+ const p = P()
57
+ for (const v of await listVoices(p, loc(o, p), o.provider)) console.info(v)
58
+ }))
59
+
60
+ prog.command('voice <slug>')
61
+ .describe('Synthesise the takes from voice/<locale>.json with the configured provider.')
62
+ .option('--locale', 'Locale (default: the site default)')
63
+ .option('--only', 'Take numbers, e.g. 2,5')
64
+ .option('--provider', 'Override the configured provider for this run')
65
+ .option('--opt', 'key=value override, e.g. voice=nova; repeatable')
66
+ .action(act(async (slug, o) => {
67
+ const { voice } = await import('../voice.js')
68
+ const p = P()
69
+ await voice(p, slug, { locale: loc(o, p), only: o.only, provider: o.provider, opts: parseOpts(o.opt) })
70
+ }))
71
+
72
+ prog.command('fit <slug>')
73
+ .describe('Fit each scene\'s running time to its take: timing.<locale>.json.')
74
+ .option('--locale', 'Locale (default: the site default)')
75
+ .option('--check', 'Report only; write nothing', false)
76
+ .action(act(async (slug, o) => {
77
+ const { fit } = await import('../voice.js')
78
+ const p = P()
79
+ const r = fit(p, slug, { locale: loc(o, p), check: o.check })
80
+ console.info(`${'scene'.padEnd(12)} ${'design'.padStart(6)} ${'holds'.padStart(6)} ${'take'.padStart(6)} ${'runs'.padStart(6)}`)
81
+ for (const x of r.rows) console.info(fitRow(x))
82
+ console.info(`total ${r.total.toFixed(1)} s (${loc(o, p)})${r.written ? `\nwrote ${r.path}` : ''}`)
83
+ }))
84
+
85
+ prog.command('voice-web <slug>')
86
+ .describe('Narration for the browser: each take as voice/<locale>/<scene>.m4a, and its start in timing.<locale>.json (needs ffmpeg).')
87
+ .option('--locale', 'Locale (default: the site default)')
88
+ .action(act(async (slug, o) => {
89
+ const { voiceWeb } = await import('../voice.js')
90
+ const p = P()
91
+ const r = voiceWeb(p, slug, { locale: loc(o, p), log: (l) => console.info(`wrote ${l}`) })
92
+ for (const f of r.removed) console.info(`removed ${f} (no take)`)
93
+ console.info(`wrote ${r.timing}`)
94
+ }))
95
+
96
+ prog.command('render <slug>')
97
+ .describe('Capture the picture frame by frame (with the score) and the covers (needs Playwright + ffmpeg).')
98
+ .option('--locale', 'Locale (default: the site default)')
99
+ .option('--url', 'A running site (default: start the dev server)')
100
+ .option('--o', 'both | landscape | portrait', 'both')
101
+ .option('--fps', 'Frames per second', 30)
102
+ .option('--from', 'Start at this film time (s)', 0)
103
+ .option('--to', 'Stop at this film time (s; default the end)')
104
+ .option('--out', 'Output: a .mp4 file (one layout) or a folder (default production/<slug>/<locale>/render/)')
105
+ .option('--music', 'synth (the film\'s score) | export (audio of production/<slug>/<locale>/<slug>.mp4) | none', 'synth')
106
+ .option('--audio-only', 'Lay the music on the existing render; capture no frames', false)
107
+ .option('--cover-only', 'Just save the cover frames', false)
108
+ .action(act(async (slug, o) => {
109
+ const { render } = await import('../capture.js')
110
+ const p = P()
111
+ await render(p, slug, {
112
+ locale: loc(o, p), url: o.url, o: o.o, fps: Number(o.fps), from: Number(o.from), to: o.to == null ? undefined : Number(o.to),
113
+ out: o.out, music: o.music, audioOnly: o['audio-only'], coverOnly: o['cover-only']
114
+ })
115
+ }))
116
+
117
+ prog.command('build <slug>')
118
+ .describe('Final videos: picture + voice + ducked score, captions (.srt/.vtt and burned in), -14 LUFS.')
119
+ .option('--locale', 'Locale (default: the site default)')
120
+ .option('--no-captions', 'Do not burn captions in')
121
+ .option('--check', 'Print each scene\'s take, freeze and start; build nothing', false)
122
+ .option('--out', 'Output folder (default production/<slug>/<locale>/out/)')
123
+ .action(act(async (slug, o) => {
124
+ const { build } = await import('../voice.js')
125
+ const p = P()
126
+ build(p, slug, { locale: loc(o, p), noCaptions: o.captions === false, check: o.check, out: o.out })
127
+ }))
128
+ }
@@ -0,0 +1,19 @@
1
+ // What every command shares: act() turns a MotionError into "emaki: <message>" and exit 1 (anything else is a bug and
2
+ // shows its stack), P() reads the project in the current folder, loc() is --locale or the site's default.
3
+ import { project } from '../config.js'
4
+ import { MotionError } from '../util.js'
5
+
6
+ /** Runs a command; a MotionError prints its message and exits 1, anything else is a bug and shows its stack. */
7
+ export const act = (fn) => async (...args) => {
8
+ try {
9
+ await fn(...args)
10
+ } catch (e) {
11
+ if (e instanceof MotionError) {
12
+ console.error(`emaki: ${e.message}`)
13
+ process.exit(1)
14
+ }
15
+ throw e
16
+ }
17
+ }
18
+ export const P = () => project()
19
+ export const loc = (o, p) => o.locale ?? p.site.defaultLocale
@@ -0,0 +1,97 @@
1
+ // emaki init, plugin install, skills, agents, manifest, validate, migrate, new: setting a project up and keeping its
2
+ // content in shape.
3
+ import { project } from '../config.js'
4
+ import { manifest, newFilm, validate } from '../films.js'
5
+ import { migrate } from '../migrate.js'
6
+ import { act, P } from './run.js'
7
+
8
+ /** The commands that set a project up and check its content. */
9
+ export function setupCommands(prog) {
10
+ prog.command('init')
11
+ .describe('Set this project up: sample content, emaki.config.json, the film source and the /show capture route.')
12
+ .option('--framework', 'sveltekit | svelte | react | next | vue | nuxt | vanilla (default: detected)')
13
+ .option('--content', 'Content folder', 'content')
14
+ .option('--no-sample', 'Skip the sample film')
15
+ .option('--plugin', 'Also install the Claude plugin (skills, agents, playbook)', true)
16
+ .action(act(async (o) => {
17
+ const { init } = await import('../init.js')
18
+ const r = init({ framework: o.framework, content: o.content, sample: o.sample !== false })
19
+ console.info(`framework: ${r.framework}`)
20
+ r.wrote.forEach((f) => console.info(` wrote ${f}`))
21
+ r.kept.forEach((f) => console.info(` kept ${f} (exists)`))
22
+ if (o.plugin !== false) {
23
+ const { installPlugin, report } = await import('../plugin.js')
24
+ const x = installPlugin()
25
+ report('skill', x.skills); report('agent', x.agents); report('file', x.extras)
26
+ }
27
+ console.info(`\nNext:\n npm i ${r.packages.join(' ')}\n npm i -D playwright && npx playwright install chromium (sheet, render)\n npx emaki validate && npx emaki tts-check`)
28
+ console.info('Then in Claude: "build our motion stories" (the emaki skill interviews you and plans the work).')
29
+ }))
30
+
31
+ prog.command('plugin install')
32
+ .describe('Install the Claude plugin into .claude/: every skill and agent, plus the playbook and templates.')
33
+ .option('--force', 'Overwrite what exists', false)
34
+ .action(act(async (o) => {
35
+ const { installPlugin, report } = await import('../plugin.js')
36
+ const x = installPlugin({ force: o.force })
37
+ report('skill', x.skills); report('agent', x.agents); report('file', x.extras)
38
+ }))
39
+
40
+ prog.command('skills [sub]')
41
+ .describe('List the bundled skills, or add some: emaki skills add <name...> | --all')
42
+ .option('--all', 'Every skill', false)
43
+ .option('--force', 'Overwrite', false)
44
+ .action(act(async (sub, o) => {
45
+ const { listSkills, installSkills, report } = await import('../plugin.js')
46
+ if (sub === 'add') return report('skill', installSkills(o.all ? listSkills().map((s) => s.name) : o._, { force: o.force }))
47
+ for (const s of listSkills()) console.info(`${s.name}\n ${s.description}`)
48
+ console.info('\nInstall with: emaki skills add <name> [...] (or --all)')
49
+ }))
50
+
51
+ prog.command('agents [sub]')
52
+ .describe('List the bundled agents, or add some: emaki agents add <name...> | --all')
53
+ .option('--all', 'Every agent', false)
54
+ .option('--force', 'Overwrite', false)
55
+ .action(act(async (sub, o) => {
56
+ const { listAgents, installAgents, report } = await import('../plugin.js')
57
+ if (sub === 'add') return report('agent', installAgents(o.all ? listAgents().map((a) => a.name) : o._, { force: o.force }))
58
+ for (const a of listAgents()) console.info(`${a.name}\n ${a.description}`)
59
+ console.info('\nInstall with: emaki agents add <name> [...] (or --all)')
60
+ }))
61
+
62
+ prog.command('manifest')
63
+ .describe('Write content/films/index.json (the fetch loader reads it).')
64
+ .action(act(() => { const r = manifest(P()); console.info(`${r.count} films → ${r.path}`) }))
65
+
66
+ prog.command('validate [slug]')
67
+ .describe('Check the contracts: files, scene ids, {{keys}} in every locale, voice lines, story bodies.')
68
+ .action(act((slug) => {
69
+ const r = validate(P(), slug)
70
+ r.lines.forEach((l) => console.info(l))
71
+ console.info(r.problems ? `${r.problems} problem(s)` : 'ok')
72
+ if (r.problems) process.exitCode = 1
73
+ }))
74
+
75
+ prog.command('migrate <from>')
76
+ .describe('Move a sensei-hq.com-style site (src/lib/motion, src/lib/content/articles, films/) into content/ and production/. Never overwrites.')
77
+ .option('--locale', 'The locale the site was written in', 'en')
78
+ .action(act((from, o) => {
79
+ const p = P(), r = migrate(p, from, { locale: o.locale })
80
+ r.wrote.forEach((f) => console.info(` wrote ${f}`))
81
+ if (r.kept.length) console.info(` kept ${r.kept.length} existing file(s)`)
82
+ const v = validate(project())
83
+ v.lines.forEach((l) => console.info(l))
84
+ console.info(v.problems ? `${v.problems} problem(s) left: fix them, then \`emaki validate\`` : 'migrated; emaki validate: ok')
85
+ if (v.problems) process.exitCode = 1
86
+ }))
87
+
88
+ prog.command('new <slug>')
89
+ .describe('Scaffold a story and its film in every locale.')
90
+ .option('--scenes', 'Scene ids, comma separated (close is added last)', 'hook,idea,how')
91
+ .option('--title', 'Film title')
92
+ .option('--date', 'Publish date YYYY-MM-DD (default today)')
93
+ .action(act((slug, o) => {
94
+ const r = newFilm(P(), slug, { scenes: o.scenes, title: o.title, date: o.date })
95
+ console.info(`scaffolded ${r.slug}: ${r.scenes} scenes, ${r.locales} locale(s). Next: write the scenes, then \`emaki sheet ${r.slug}\`.`)
96
+ }))
97
+ }
package/src/csv.js ADDED
@@ -0,0 +1,42 @@
1
+ // CSV with a header line (the campaign's calendar.csv). A small state machine: one handler per character, inside or
2
+ // outside quotes; each returns how many extra characters it consumed.
3
+
4
+ const endCell = (s) => { s.row.push(s.cell); s.cell = '' }
5
+ const endRow = (s) => { endCell(s); s.rows.push(s.row); s.row = [] }
6
+
7
+ /** Inside quotes: "" is a quote, a lone " closes the quotes, anything else (commas, newlines) is text. */
8
+ function quotedChar(s, text, i) {
9
+ const c = text[i]
10
+ if (c !== '"') s.cell += c
11
+ else if (text[i + 1] === '"') { s.cell += '"'; return 1 }
12
+ else s.quoted = false
13
+ return 0
14
+ }
15
+
16
+ /** Outside quotes: " opens quotes, a comma ends the cell, \n, \r or \r\n ends the row. */
17
+ const PLAIN = {
18
+ '"': (s) => { s.quoted = true; return 0 },
19
+ ',': (s) => { endCell(s); return 0 },
20
+ '\n': (s) => { endRow(s); return 0 },
21
+ '\r': (s, text, i) => { endRow(s); return text[i + 1] === '\n' ? 1 : 0 }
22
+ }
23
+ function plainChar(s, text, i) {
24
+ const special = PLAIN[text[i]]
25
+ if (special) return special(s, text, i)
26
+ s.cell += text[i]
27
+ return 0
28
+ }
29
+
30
+ /** Every row of `text` as an array of cells, blank rows included. */
31
+ function csvRows(text) {
32
+ const s = { rows: [], row: [], cell: '', quoted: false }
33
+ for (let i = 0; i < text.length; i++) i += (s.quoted ? quotedChar : plainChar)(s, text, i)
34
+ if (s.cell || s.row.length) endRow(s)
35
+ return s.rows
36
+ }
37
+
38
+ /** Rows of a CSV with a header line, as objects. Quoted fields may hold commas, newlines and "" quotes. */
39
+ export function parseCsv(text) {
40
+ const [head = [], ...body] = csvRows(text).filter((r) => r.some((x) => x !== ''))
41
+ return body.map((r) => Object.fromEntries(head.map((h, i) => [h.trim(), r[i] ?? ''])))
42
+ }
@@ -0,0 +1,102 @@
1
+ // The content contracts validate checks: a film's files, scenes, strings and voice lines per locale, and a story's
2
+ // date and bodies. Each check returns its problems as lines; lines prefixed "(info)" are notes, not failures.
3
+ import { readFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { KEY } from './config.js'
6
+ import { exists, load } from './util.js'
7
+
8
+ /** Every {{key}} a scene uses. */
9
+ export function keysIn(obj, out = new Set()) {
10
+ if (typeof obj === 'string') for (const m of obj.matchAll(KEY)) out.add(m[1])
11
+ else if (Array.isArray(obj)) obj.forEach((x) => keysIn(x, out))
12
+ else if (obj && typeof obj === 'object') Object.values(obj).forEach((x) => keysIn(x, out))
13
+ return out
14
+ }
15
+
16
+ const list = (xs) => xs.slice(0, 8).join(', ') + (xs.length > 8 ? ' …' : '')
17
+ const DARK = '#stage[data-mode="dark"]'
18
+
19
+ /** look.css exists, and its dark styles and film.json's dark block come together: one without the other is a mistake. */
20
+ function lookIssues(d, film) {
21
+ if (!exists(join(d, 'look.css'))) return ['look.css is missing']
22
+ const styled = readFileSync(join(d, 'look.css'), 'utf-8').includes(DARK)
23
+ if (film.dark && !styled) return [`film.json has a dark block but look.css never styles ${DARK}`]
24
+ if (!film.dark && styled) return [`look.css styles ${DARK} but film.json has no dark block (those styles never apply)`]
25
+ return []
26
+ }
27
+
28
+ /** A JSON scene's own problems; collects the {{keys}} it uses into `used`. */
29
+ function specIssues(spec, used) {
30
+ keysIn(spec, used)
31
+ const ids = (spec.components ?? []).map((c) => c.id)
32
+ return [
33
+ ...('portrait' in spec ? [] : ['no portrait block (needed for 9:16 and article figures)']),
34
+ ...(ids.length === new Set(ids).size ? [] : ['duplicate component ids'])
35
+ ]
36
+ }
37
+
38
+ function sceneIssues(d, s, used) {
39
+ const sj = join(d, `scene-${s.id}.json`), js = join(d, `scene-${s.id}.js`)
40
+ if (!exists(sj) && !exists(js)) return [`scene ${s.id}: no scene-${s.id}.json (or .js)`]
41
+ const out = exists(sj) ? specIssues(load(sj), used) : []
42
+ if (!(s.dur > 0 && s.dur < 60)) out.push(`dur ${s.dur} looks wrong`)
43
+ return out.map((m) => `scene ${s.id}: ${m}`)
44
+ }
45
+
46
+ const coverIssues = (film) =>
47
+ film.cover || film.scenes.at(-1)?.id === 'close' ? [] : ['the last scene should be "close" (the punchline card is the cover), or film.json should name its cover']
48
+
49
+ function stringIssues(st, loc, used) {
50
+ const missing = [...used].filter((k) => !(k in st)).sort()
51
+ const unused = Object.keys(st).filter((k) => !used.has(k)).sort()
52
+ return [['missing', missing], ['unused', unused]].filter(([, ks]) => ks.length).map(([what, ks]) => `strings/${loc}.json: ${what} ${list(ks)}`)
53
+ }
54
+
55
+ function voiceIssues(d, film, loc) {
56
+ const vp = join(d, 'voice', `${loc}.json`)
57
+ if (!exists(vp)) return []
58
+ const v = new Set(load(vp).map((x) => x.scene))
59
+ const gap = film.scenes.map((s) => s.id).filter((id) => !v.has(id))
60
+ return gap.length ? [`voice/${loc}.json: no line for ${gap.join(', ')}`] : []
61
+ }
62
+
63
+ function localeIssues(d, film, loc, used) {
64
+ const sp = join(d, 'strings', `${loc}.json`)
65
+ if (!exists(sp)) return used.size ? [`strings/${loc}.json is missing`] : []
66
+ return [...stringIssues(load(sp), loc, used), ...voiceIssues(d, film, loc)]
67
+ }
68
+
69
+ export function validateFilm(p, slug) {
70
+ const d = p.filmDir(slug), film = load(join(d, 'film.json')), used = new Set()
71
+ // In this order: the scenes collect the {{keys}} the locales are checked against.
72
+ const look = lookIssues(d, film), scenes = film.scenes.flatMap((s) => sceneIssues(d, s, used))
73
+ return [...look, ...scenes, ...coverIssues(film), ...p.site.locales.flatMap((loc) => localeIssues(d, film, loc, used))]
74
+ }
75
+
76
+ const isEmpty = (v) => !v || (Array.isArray(v) && !v.length)
77
+ const NO_FIGURE = ['more', 'sources']
78
+ const hasFigure = (s, sceneIds) => s.motion != null || s.figure != null || sceneIds.has(s.id)
79
+
80
+ /** A film story's sections that show nothing: no motion, no figure and no scene of the same id. */
81
+ const figureNotes = (b, loc, sceneIds) => (b.sections ?? [])
82
+ .filter((s) => !hasFigure(s, sceneIds) && !NO_FIGURE.includes(s.id))
83
+ .map((s) => `(info) ${loc}: section ${s.id} has no figure (no scene of that id)`)
84
+
85
+ function bodyIssues(p, slug, loc, film, sceneIds) {
86
+ const f = join(p.content, 'stories', loc, `${slug}.json`)
87
+ if (!exists(f)) return [loc === p.site.defaultLocale ? `stories/${loc}/${slug}.json is missing` : `(info) stories/${loc}/${slug}.json not translated yet`]
88
+ const b = load(f)
89
+ const empty = ['title', 'dek', 'sections'].filter((k) => isEmpty(b[k])).map((k) => `${loc}: ${k} is empty`)
90
+ if (!film) return empty
91
+ return [...empty, ...(b.takeaway ? [] : [`${loc}: a film story needs a takeaway (the closing line)`]), ...figureNotes(b, loc, sceneIds)]
92
+ }
93
+
94
+ /** The film a story shows: index.json "film", else the film of the same slug, else none. */
95
+ const storyFilm = (p, entry) => entry.film ?? (exists(join(p.films, entry.slug, 'film.json')) ? entry.slug : null)
96
+
97
+ export function validateStory(p, entry) {
98
+ const film = storyFilm(p, entry)
99
+ const sceneIds = new Set(film ? load(join(p.films, film, 'film.json')).scenes.map((s) => s.id) : [])
100
+ const date = /^\d{4}-\d{2}-\d{2}$/.test(entry.publish_date ?? '') ? [] : ['publish_date must be YYYY-MM-DD']
101
+ return [...date, ...p.site.locales.flatMap((loc) => bodyIssues(p, entry.slug, loc, film, sceneIds))]
102
+ }
package/src/films.js CHANGED
@@ -3,9 +3,11 @@
3
3
  import { readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
4
4
  import { join } from 'node:path'
5
5
  import { fileURLToPath } from 'node:url'
6
- import { KEY } from './config.js'
6
+ import { keysIn, validateFilm, validateStory } from './film-checks.js'
7
7
  import { die, exists, load, save, today } from './util.js'
8
8
 
9
+ export { keysIn, validateFilm, validateStory }
10
+
9
11
  export const TEMPLATES = fileURLToPath(new URL('../templates/', import.meta.url))
10
12
 
11
13
  export const filmSlugs = (p) =>
@@ -18,83 +20,6 @@ export function manifest(p) {
18
20
  return { count: slugs.length, path: p.rel(join(p.films, 'index.json')) }
19
21
  }
20
22
 
21
- /** Every {{key}} a scene uses. */
22
- export function keysIn(obj, out = new Set()) {
23
- if (typeof obj === 'string') for (const m of obj.matchAll(KEY)) out.add(m[1])
24
- else if (Array.isArray(obj)) obj.forEach((x) => keysIn(x, out))
25
- else if (obj && typeof obj === 'object') Object.values(obj).forEach((x) => keysIn(x, out))
26
- return out
27
- }
28
-
29
- const list = (xs) => xs.slice(0, 8).join(', ') + (xs.length > 8 ? ' …' : '')
30
-
31
- export function validateFilm(p, slug) {
32
- const issues = [], d = p.filmDir(slug), film = load(join(d, 'film.json')), used = new Set()
33
- if (!exists(join(d, 'look.css'))) issues.push('look.css is missing')
34
- else {
35
- // Dark is opt-in: film.json's dark block turns it on, look.css draws it. One without the other is a mistake.
36
- const styled = readFileSync(join(d, 'look.css'), 'utf-8').includes('#stage[data-mode="dark"]')
37
- if (film.dark && !styled) issues.push('film.json has a dark block but look.css never styles #stage[data-mode="dark"]')
38
- if (!film.dark && styled) issues.push('look.css styles #stage[data-mode="dark"] but film.json has no dark block (those styles never apply)')
39
- }
40
- for (const s of film.scenes) {
41
- const sj = join(d, `scene-${s.id}.json`), js = join(d, `scene-${s.id}.js`)
42
- if (!exists(sj) && !exists(js)) {
43
- issues.push(`scene ${s.id}: no scene-${s.id}.json (or .js)`)
44
- continue
45
- }
46
- if (exists(sj)) {
47
- const spec = load(sj)
48
- keysIn(spec, used)
49
- if (!('portrait' in spec)) issues.push(`scene ${s.id}: no portrait block (needed for 9:16 and article figures)`)
50
- const ids = (spec.components ?? []).map((c) => c.id)
51
- if (ids.length !== new Set(ids).size) issues.push(`scene ${s.id}: duplicate component ids`)
52
- }
53
- if (!(s.dur > 0 && s.dur < 60)) issues.push(`scene ${s.id}: dur ${s.dur} looks wrong`)
54
- }
55
- if (!film.cover && film.scenes.at(-1)?.id !== 'close') issues.push('the last scene should be "close" (the punchline card is the cover), or film.json should name its cover')
56
- for (const loc of p.site.locales) {
57
- const sp = join(d, 'strings', `${loc}.json`)
58
- if (!exists(sp)) {
59
- if (used.size) issues.push(`strings/${loc}.json is missing`)
60
- continue
61
- }
62
- const st = load(sp)
63
- const missing = [...used].filter((k) => !(k in st)).sort()
64
- const unused = Object.keys(st).filter((k) => !used.has(k)).sort()
65
- if (missing.length) issues.push(`strings/${loc}.json: missing ${list(missing)}`)
66
- if (unused.length) issues.push(`strings/${loc}.json: unused ${list(unused)}`)
67
- const vp = join(d, 'voice', `${loc}.json`)
68
- if (exists(vp)) {
69
- const v = new Set(load(vp).map((x) => x.scene))
70
- const gap = film.scenes.map((s) => s.id).filter((id) => !v.has(id))
71
- if (gap.length) issues.push(`voice/${loc}.json: no line for ${gap.join(', ')}`)
72
- }
73
- }
74
- return issues
75
- }
76
-
77
- export function validateStory(p, entry) {
78
- const issues = [], slug = entry.slug
79
- if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.publish_date ?? '')) issues.push('publish_date must be YYYY-MM-DD')
80
- const film = entry.film ?? (exists(join(p.films, slug, 'film.json')) ? slug : null)
81
- const sceneIds = new Set(film ? load(join(p.films, film, 'film.json')).scenes.map((s) => s.id) : [])
82
- for (const loc of p.site.locales) {
83
- const f = join(p.content, 'stories', loc, `${slug}.json`)
84
- if (!exists(f)) {
85
- issues.push(loc === p.site.defaultLocale ? `stories/${loc}/${slug}.json is missing` : `(info) stories/${loc}/${slug}.json not translated yet`)
86
- continue
87
- }
88
- const b = load(f)
89
- for (const k of ['title', 'dek', 'sections']) if (!b[k] || (Array.isArray(b[k]) && !b[k].length)) issues.push(`${loc}: ${k} is empty`)
90
- if (film && !b.takeaway) issues.push(`${loc}: a film story needs a takeaway (the closing line)`)
91
- for (const s of b.sections ?? [])
92
- if (s.motion == null && s.figure == null && film && !sceneIds.has(s.id) && !['more', 'sources'].includes(s.id))
93
- issues.push(`(info) ${loc}: section ${s.id} has no figure (no scene of that id)`)
94
- }
95
- return issues
96
- }
97
-
98
23
  /** All problems (lines prefixed "(info)" are notes, not failures). */
99
24
  export function validate(p, slug) {
100
25
  const ip = join(p.content, 'stories', 'index.json')
package/src/fit.js ADDED
@@ -0,0 +1,79 @@
1
+ // timing.<locale>.json from the takes: `fit` times each narrated scene to its take, `voiceWeb` encodes the takes for the
2
+ // browser and records where each one starts.
3
+ import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { localizeScene, motionEnd } from '@senseihq/emaki'
6
+ import { webVoiceArgs } from './media.js'
7
+ import { takesFor } from './takes.js'
8
+ import { die, load, mediaLength, run, save } from './util.js'
9
+
10
+ /** The narration for the browser: each take as voice/<locale>/<scene>.m4a beside the film, and in timing.<locale>.json
11
+ * each narrated scene's `voice` start (the same lead the videos use), so the story player and article figures speak
12
+ * in step with the picture. A scene whose take is gone loses its file and its start. Run after `fit`. */
13
+ export function voiceWeb(p, slug, { locale, encode = (src, dst) => run('ffmpeg', webVoiceArgs(src, dst)), log = () => {} } = {}) {
14
+ const d = p.filmDir(slug), takes = takesFor(p, slug, locale)
15
+ if (!takes.size) die(`${slug} has no takes for ${locale}: record or synthesise them first (emaki voice ${slug} --locale ${locale})`)
16
+ const film = load(join(d, 'film.json')), dir = join(d, 'voice', locale), tp = join(d, `timing.${locale}.json`)
17
+ const timing = existsSync(tp) ? load(tp) : { scenes: {} }
18
+ const tsc = (timing.scenes ??= {})
19
+ mkdirSync(dir, { recursive: true })
20
+ const wrote = [], removed = []
21
+ for (const s of film.scenes) {
22
+ const dst = join(dir, `${s.id}.m4a`), c = tsc[s.id] ?? {}
23
+ if (takes.has(s.id)) {
24
+ encode(takes.get(s.id)[0], dst)
25
+ wrote.push(p.rel(dst))
26
+ log(`${p.rel(dst)}`)
27
+ c.voice = p.lead
28
+ } else {
29
+ if (existsSync(dst)) { rmSync(dst); removed.push(p.rel(dst)) }
30
+ delete c.voice
31
+ }
32
+ if (Object.keys(c).length) tsc[s.id] = c
33
+ else delete tsc[s.id]
34
+ }
35
+ if (!readdirSync(dir).length) rmSync(dir, { recursive: true })
36
+ save(tp, timing)
37
+ return { wrote, removed, timing: p.rel(tp) }
38
+ }
39
+
40
+ const up = (v) => Math.ceil(v * 10 - 1e-9) / 10
41
+
42
+ /** When scene `s` stops moving, in scene seconds: film.json "settle", else the end of its JSON scene's tracks in this
43
+ * locale (word counts follow the translation), else null (a JS scene: its motion cannot be read). */
44
+ function settleOf(d, s, locale) {
45
+ if (s.settle != null) return s.settle
46
+ const f = join(d, `scene-${s.id}.json`)
47
+ if (!existsSync(f)) return null
48
+ const sp = join(d, `strings/${locale}.json`)
49
+ return motionEnd(localizeScene(load(f), existsSync(sp) ? load(sp) : {}))
50
+ }
51
+
52
+ /** timing.<locale>.json: a narrated scene runs lead + take + tail, longer or shorter than its design, but never ends
53
+ * before its motion settles; a scene without a take, or a JS scene without "settle", keeps its design time. */
54
+ export function fit(p, slug, { locale, check = false, length = mediaLength } = {}) {
55
+ const d = p.filmDir(slug), film = load(join(d, 'film.json')), takes = takesFor(p, slug, locale)
56
+ const tp = join(d, `timing.${locale}.json`)
57
+ const timing = existsSync(tp) ? load(tp) : { scenes: {} }
58
+ const tsc = (timing.scenes ??= {})
59
+ const rows = []
60
+ for (const s of film.scenes) {
61
+ const c = tsc[s.id] ?? {}
62
+ const holds = (c.holds ?? []).reduce((n, h) => n + h[1], 0)
63
+ const L = takes.has(s.id) ? length(takes.get(s.id)[0]) : 0
64
+ const base = s.dur + holds
65
+ let runs = base
66
+ if (L) {
67
+ const settle = settleOf(d, s, locale)
68
+ const floor = settle == null ? base : Math.min(base, up(settle + holds))
69
+ runs = Math.max(floor, up(p.lead + L + p.tail))
70
+ }
71
+ if (Math.abs(runs - base) > 1e-6) c.dur = runs
72
+ else delete c.dur
73
+ if (Object.keys(c).length) tsc[s.id] = c
74
+ else delete tsc[s.id]
75
+ rows.push({ scene: s.id, design: s.dur, holds, take: L, runs, longer: runs > base + 1e-6, shorter: runs < base - 1e-6 })
76
+ }
77
+ if (!check) save(tp, timing)
78
+ return { rows, total: rows.reduce((n, r) => n + r.runs, 0), path: p.rel(tp), written: !check }
79
+ }