@senseihq/emaki-cli 0.1.0 → 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.
Files changed (65) hide show
  1. package/README.md +42 -7
  2. package/package.json +4 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin/modules/campaign/README.md +10 -3
  5. package/plugin/modules/campaign/day-script.template.md +2 -1
  6. package/plugin/modules/posting-desk/README.md +2 -2
  7. package/plugin/skills/emaki/references/03-content-model.md +7 -4
  8. package/plugin/skills/emaki/references/04-scene-authoring.md +3 -0
  9. package/plugin/skills/emaki/references/05-voice-and-video.md +41 -8
  10. package/plugin/skills/emaki/references/09-publishing.md +5 -2
  11. package/plugin/skills/story-media/SKILL.md +2 -0
  12. package/plugin/skills/story-publish/SKILL.md +18 -4
  13. package/src/api.js +12 -1
  14. package/src/build-media.js +166 -0
  15. package/src/build-video.js +113 -0
  16. package/src/campaign.js +138 -0
  17. package/src/capture.js +6 -118
  18. package/src/carousel.js +91 -0
  19. package/src/commands/campaign.js +63 -0
  20. package/src/commands/posting.js +74 -0
  21. package/src/commands/production.js +128 -0
  22. package/src/commands/run.js +19 -0
  23. package/src/commands/setup.js +97 -0
  24. package/src/csv.js +42 -0
  25. package/src/day-script.js +66 -0
  26. package/src/desk-client.js +37 -0
  27. package/src/desk-plan.js +57 -0
  28. package/src/film-checks.js +102 -0
  29. package/src/films.js +7 -75
  30. package/src/fit.js +79 -0
  31. package/src/http.js +30 -0
  32. package/src/index.js +10 -184
  33. package/src/init.js +10 -13
  34. package/src/media.js +80 -0
  35. package/src/migrate.js +84 -0
  36. package/src/publish.js +136 -0
  37. package/src/render.js +125 -0
  38. package/src/show-page.js +75 -0
  39. package/src/stage.js +120 -0
  40. package/src/stories.js +66 -0
  41. package/src/takes.js +18 -0
  42. package/src/tts-cloud.js +122 -0
  43. package/src/tts-io.js +51 -0
  44. package/src/tts-offline.js +85 -0
  45. package/src/tts.js +5 -237
  46. package/src/upload/instagram.js +34 -0
  47. package/src/upload/youtube.js +90 -0
  48. package/src/util.js +7 -0
  49. package/src/voice.js +8 -118
  50. package/src/youtube-text.js +58 -0
  51. package/templates/content/films/measure-the-right-work/film.json +9 -0
  52. package/templates/content/films/measure-the-right-work/look.css +1 -0
  53. package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
  54. package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
  55. package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
  56. package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
  57. package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
  58. package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
  59. package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
  60. package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
  61. package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
  62. package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
  63. package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
  64. package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
  65. package/templates/film/look.css +1 -0
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,77 +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
- for (const s of film.scenes) {
35
- const sj = join(d, `scene-${s.id}.json`), js = join(d, `scene-${s.id}.js`)
36
- if (!exists(sj) && !exists(js)) {
37
- issues.push(`scene ${s.id}: no scene-${s.id}.json (or .js)`)
38
- continue
39
- }
40
- if (exists(sj)) {
41
- const spec = load(sj)
42
- keysIn(spec, used)
43
- if (!('portrait' in spec)) issues.push(`scene ${s.id}: no portrait block (needed for 9:16 and article figures)`)
44
- const ids = (spec.components ?? []).map((c) => c.id)
45
- if (ids.length !== new Set(ids).size) issues.push(`scene ${s.id}: duplicate component ids`)
46
- }
47
- if (!(s.dur > 0 && s.dur < 60)) issues.push(`scene ${s.id}: dur ${s.dur} looks wrong`)
48
- }
49
- if (film.scenes.at(-1)?.id !== 'close') issues.push('the last scene should be "close" (the punchline card is the cover)')
50
- for (const loc of p.site.locales) {
51
- const sp = join(d, 'strings', `${loc}.json`)
52
- if (!exists(sp)) {
53
- if (used.size) issues.push(`strings/${loc}.json is missing`)
54
- continue
55
- }
56
- const st = load(sp)
57
- const missing = [...used].filter((k) => !(k in st)).sort()
58
- const unused = Object.keys(st).filter((k) => !used.has(k)).sort()
59
- if (missing.length) issues.push(`strings/${loc}.json: missing ${list(missing)}`)
60
- if (unused.length) issues.push(`strings/${loc}.json: unused ${list(unused)}`)
61
- const vp = join(d, 'voice', `${loc}.json`)
62
- if (exists(vp)) {
63
- const v = new Set(load(vp).map((x) => x.scene))
64
- const gap = film.scenes.map((s) => s.id).filter((id) => !v.has(id))
65
- if (gap.length) issues.push(`voice/${loc}.json: no line for ${gap.join(', ')}`)
66
- }
67
- }
68
- return issues
69
- }
70
-
71
- export function validateStory(p, entry) {
72
- const issues = [], slug = entry.slug
73
- if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.publish_date ?? '')) issues.push('publish_date must be YYYY-MM-DD')
74
- const film = entry.film ?? (exists(join(p.films, slug, 'film.json')) ? slug : null)
75
- const sceneIds = new Set(film ? load(join(p.films, film, 'film.json')).scenes.map((s) => s.id) : [])
76
- for (const loc of p.site.locales) {
77
- const f = join(p.content, 'stories', loc, `${slug}.json`)
78
- if (!exists(f)) {
79
- issues.push(loc === p.site.defaultLocale ? `stories/${loc}/${slug}.json is missing` : `(info) stories/${loc}/${slug}.json not translated yet`)
80
- continue
81
- }
82
- const b = load(f)
83
- for (const k of ['title', 'dek', 'sections']) if (!b[k] || (Array.isArray(b[k]) && !b[k].length)) issues.push(`${loc}: ${k} is empty`)
84
- if (film && !b.takeaway) issues.push(`${loc}: a film story needs a takeaway (the closing line)`)
85
- for (const s of b.sections ?? [])
86
- if (s.motion == null && film && !sceneIds.has(s.id) && !['more', 'sources'].includes(s.id))
87
- issues.push(`(info) ${loc}: section ${s.id} has no figure (no scene of that id)`)
88
- }
89
- return issues
90
- }
91
-
92
23
  /** All problems (lines prefixed "(info)" are notes, not failures). */
93
24
  export function validate(p, slug) {
94
25
  const ip = join(p.content, 'stories', 'index.json')
@@ -109,7 +40,7 @@ export function newFilm(p, slug, { scenes, title, date } = {}) {
109
40
  const T = join(TEMPLATES, 'film')
110
41
  const name = (i) => i.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
111
42
  const film = {
112
- title: title || name(slug), look: 'Describe the look in one paragraph.', background: '#F3F0E9',
43
+ title: title || name(slug), look: 'Describe the look in one paragraph.', background: '#F3F0E9', dark: { background: '#1E1B18' },
113
44
  fonts: { display: { family: 'Fraunces', weights: [300, 400] }, sans: { family: 'Inter', weights: [400, 600] } },
114
45
  scenes: ids.map((i) => ({ id: i, name: name(i), dur: i === 'close' ? 5.5 : 10, desc: 'What this scene shows.' }))
115
46
  }
@@ -130,7 +61,8 @@ export function newFilm(p, slug, { scenes, title, date } = {}) {
130
61
  for (const loc of p.site.locales) {
131
62
  save(join(d, 'strings', `${loc}.json`), strings)
132
63
  save(join(d, 'voice', `${loc}.json`), voice)
133
- save(join(p.content, 'stories', loc, `${slug}.json`), {
64
+ const body = join(p.content, 'stories', loc, `${slug}.json`)
65
+ if (!exists(body)) save(body, {
134
66
  title: film.title, dek: 'One or two sentences.',
135
67
  sections: ids.filter((i) => !['hook', 'close'].includes(i)).map((i) => ({ id: i, eyebrow: name(i), title: 'Section title', body: ['Paragraph.'] })),
136
68
  takeaway: strings['close.title'], takeawaySub: strings['close.sub'], sources: []
@@ -138,7 +70,7 @@ export function newFilm(p, slug, { scenes, title, date } = {}) {
138
70
  }
139
71
  const ip = join(p.content, 'stories', 'index.json')
140
72
  const index = exists(ip) ? load(ip) : []
141
- index.push({ slug, publish_date: date || today(), kind: 'film', tags: [], minutes: 4 })
73
+ if (!index.some((e) => e.slug === slug)) index.push({ slug, publish_date: date || today(), kind: 'film', tags: [], minutes: 4 })
142
74
  save(ip, index.sort((a, b) => a.publish_date.localeCompare(b.publish_date)))
143
75
  manifest(p)
144
76
  return { slug, scenes: ids.length, locales: p.site.locales.length }
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
+ }
package/src/http.js ADDED
@@ -0,0 +1,30 @@
1
+ // HTTP for the media pipeline (stage, publish): one injectable fetch, and failures as MotionErrors that name the
2
+ // method, the URL without its query (where tokens travel) and the response status and text. Credentials go in headers
3
+ // or bodies, never into a message.
4
+ import { die } from './util.js'
5
+
6
+ const bare = (url) => String(url).split('?')[0]
7
+
8
+ /** Sends one request; a non-2xx answer or a network error stops the run. Returns the Response. */
9
+ export async function call(fetchFn, method, url, { body, headers = {} } = {}) {
10
+ let r
11
+ try {
12
+ r = await fetchFn(url, { method, body, headers })
13
+ } catch (e) {
14
+ die(`${method} ${bare(url)}: ${e instanceof Error ? e.message : e}`)
15
+ }
16
+ if (!r.ok) die(`${method} ${bare(url)} → ${r.status}: ${(await r.text()).slice(0, 400)}`)
17
+ return r
18
+ }
19
+
20
+ /** call() and parse the JSON answer ({} for an empty body). */
21
+ export async function callJson(fetchFn, method, url, opts) {
22
+ const text = await (await call(fetchFn, method, url, opts)).text()
23
+ return text ? JSON.parse(text) : {}
24
+ }
25
+
26
+ /** Dies naming every missing variable: credentials come from the environment (or CI secrets) only. */
27
+ export function need(env, ...names) {
28
+ const missing = names.filter((n) => !env[n])
29
+ if (missing.length) die(`missing ${missing.join(', ')}: set them in the environment (or CI secrets), never in emaki.config.json`)
30
+ }
package/src/index.js CHANGED
@@ -1,195 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  /* eslint-disable no-console */
3
3
  // emaki: set a project up for motion stories, install the Claude plugin, and run the production steps
4
- // (validate, sheet, voice, fit, render, build) per film and per locale.
4
+ // (validate, sheet, voice, fit, render, build) per film and per locale. Each group of commands is in commands/; they are
5
+ // registered in this order, which is the order --help lists them in.
5
6
  import sade from 'sade'
6
7
  import pkg from '../package.json' with { type: 'json' }
7
- import { project } from './config.js'
8
- import { manifest, newFilm, validate } from './films.js'
9
- import { MotionError, parseOpts } from './util.js'
8
+ import { campaignCommands } from './commands/campaign.js'
9
+ import { postingCommands } from './commands/posting.js'
10
+ import { productionCommands } from './commands/production.js'
11
+ import { setupCommands } from './commands/setup.js'
10
12
 
11
13
  const prog = sade('emaki')
12
14
  prog.version(pkg.version)
13
15
 
14
- /** Runs a command; a MotionError prints its message and exits 1, anything else is a bug and shows its stack. */
15
- const act = (fn) => async (...args) => {
16
- try {
17
- await fn(...args)
18
- } catch (e) {
19
- if (e instanceof MotionError) {
20
- console.error(`emaki: ${e.message}`)
21
- process.exit(1)
22
- }
23
- throw e
24
- }
25
- }
26
- const P = () => project()
27
- const loc = (o, p) => o.locale ?? p.site.defaultLocale
28
-
29
- prog.command('init')
30
- .describe('Set this project up: sample content, emaki.config.json, the film source and the /show capture route.')
31
- .option('--framework', 'sveltekit | svelte | react | next | vue | nuxt | vanilla (default: detected)')
32
- .option('--content', 'Content folder', 'content')
33
- .option('--no-sample', 'Skip the sample film')
34
- .option('--plugin', 'Also install the Claude plugin (skills, agents, playbook)', true)
35
- .action(act(async (o) => {
36
- const { init } = await import('./init.js')
37
- const r = init({ framework: o.framework, content: o.content, sample: o.sample !== false })
38
- console.info(`framework: ${r.framework}`)
39
- r.wrote.forEach((f) => console.info(` wrote ${f}`))
40
- r.kept.forEach((f) => console.info(` kept ${f} (exists)`))
41
- if (o.plugin !== false) {
42
- const { installPlugin, report } = await import('./plugin.js')
43
- const x = installPlugin()
44
- report('skill', x.skills); report('agent', x.agents); report('file', x.extras)
45
- }
46
- 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`)
47
- console.info('Then in Claude: "build our motion stories" (the emaki skill interviews you and plans the work).')
48
- }))
49
-
50
- prog.command('plugin install')
51
- .describe('Install the Claude plugin into .claude/: every skill and agent, plus the playbook and templates.')
52
- .option('--force', 'Overwrite what exists', false)
53
- .action(act(async (o) => {
54
- const { installPlugin, report } = await import('./plugin.js')
55
- const x = installPlugin({ force: o.force })
56
- report('skill', x.skills); report('agent', x.agents); report('file', x.extras)
57
- }))
58
-
59
- prog.command('skills [sub]')
60
- .describe('List the bundled skills, or add some: emaki skills add <name...> | --all')
61
- .option('--all', 'Every skill', false)
62
- .option('--force', 'Overwrite', false)
63
- .action(act(async (sub, o) => {
64
- const { listSkills, installSkills, report } = await import('./plugin.js')
65
- if (sub === 'add') return report('skill', installSkills(o.all ? listSkills().map((s) => s.name) : o._, { force: o.force }))
66
- for (const s of listSkills()) console.info(`${s.name}\n ${s.description}`)
67
- console.info('\nInstall with: emaki skills add <name> [...] (or --all)')
68
- }))
69
-
70
- prog.command('agents [sub]')
71
- .describe('List the bundled agents, or add some: emaki agents add <name...> | --all')
72
- .option('--all', 'Every agent', false)
73
- .option('--force', 'Overwrite', false)
74
- .action(act(async (sub, o) => {
75
- const { listAgents, installAgents, report } = await import('./plugin.js')
76
- if (sub === 'add') return report('agent', installAgents(o.all ? listAgents().map((a) => a.name) : o._, { force: o.force }))
77
- for (const a of listAgents()) console.info(`${a.name}\n ${a.description}`)
78
- console.info('\nInstall with: emaki agents add <name> [...] (or --all)')
79
- }))
80
-
81
- prog.command('manifest')
82
- .describe('Write content/films/index.json (the fetch loader reads it).')
83
- .action(act(() => { const r = manifest(P()); console.info(`${r.count} films → ${r.path}`) }))
84
-
85
- prog.command('validate [slug]')
86
- .describe('Check the contracts: files, scene ids, {{keys}} in every locale, voice lines, story bodies.')
87
- .action(act((slug) => {
88
- const r = validate(P(), slug)
89
- r.lines.forEach((l) => console.info(l))
90
- console.info(r.problems ? `${r.problems} problem(s)` : 'ok')
91
- if (r.problems) process.exitCode = 1
92
- }))
93
-
94
- prog.command('new <slug>')
95
- .describe('Scaffold a story and its film in every locale.')
96
- .option('--scenes', 'Scene ids, comma separated (close is added last)', 'hook,idea,how')
97
- .option('--title', 'Film title')
98
- .option('--date', 'Publish date YYYY-MM-DD (default today)')
99
- .action(act((slug, o) => {
100
- const r = newFilm(P(), slug, { scenes: o.scenes, title: o.title, date: o.date })
101
- console.info(`scaffolded ${r.slug}: ${r.scenes} scenes, ${r.locales} locale(s). Next: write the scenes, then \`emaki sheet ${r.slug}\`.`)
102
- }))
103
-
104
- prog.command('sheet <slug>')
105
- .describe('Contact sheet: each scene\'s final picture in both orientations (needs Playwright).')
106
- .option('--locale', 'Locale (default: the site default)')
107
- .option('--url', 'A running site (default: start the dev server)')
108
- .option('--at', 'scene:t,scene:t instead of each scene\'s final picture')
109
- .action(act(async (slug, o) => {
110
- const { sheet } = await import('./capture.js')
111
- const p = P()
112
- await sheet(p, slug, { locale: loc(o, p), url: o.url, at: o.at })
113
- }))
114
-
115
- prog.command('tts-check')
116
- .describe('Which voice provider each locale uses, whether it is ready here, and which offline engines exist.')
117
- .action(act(async () => {
118
- const { ttsCheck } = await import('./voice.js')
119
- const r = ttsCheck(P())
120
- for (const x of r.rows) console.info(`${x.locale}: ${x.provider ? `${x.provider} (${x.label}) ${x.ready ? 'ready' : `not ready: ${x.note}`}` : 'no provider set'}`)
121
- console.info(`offline engines on this machine: ${r.offline.join(', ') || 'none'}`)
122
- }))
123
-
124
- prog.command('set-voice')
125
- .describe('Choose the voice provider for a locale (or "default"); options with --opt key=value. Keys stay in env vars.')
126
- .option('--locale', 'Locale, a language, or default', 'default')
127
- .option('--provider', 'piper | kokoro | macos | espeak | elevenlabs | openai | azure | google | polly | manual')
128
- .option('--opt', 'key=value (voice, voice_id, model, instructions, rate, …); repeatable')
129
- .action(act(async (o) => {
130
- const { setVoice } = await import('./voice.js')
131
- if (!o.provider) throw new MotionError('--provider is required')
132
- const r = setVoice(P(), o.locale, o.provider, parseOpts(o.opt))
133
- r.dropped.forEach((k) => console.info(`dropped "${k}": keys belong in environment variables, not emaki.config.json`))
134
- console.info(`voice.${o.locale} = ${JSON.stringify(r.block)}`)
135
- }))
136
-
137
- prog.command('voices')
138
- .describe('List the voices a provider offers for a locale.')
139
- .option('--locale', 'Locale (default: the site default)')
140
- .option('--provider', 'Override the configured provider')
141
- .action(act(async (o) => {
142
- const { listVoices } = await import('./voice.js')
143
- const p = P()
144
- for (const v of await listVoices(p, loc(o, p), o.provider)) console.info(v)
145
- }))
146
-
147
- prog.command('voice <slug>')
148
- .describe('Synthesise the takes from voice/<locale>.json with the configured provider.')
149
- .option('--locale', 'Locale (default: the site default)')
150
- .option('--only', 'Take numbers, e.g. 2,5')
151
- .option('--provider', 'Override the configured provider for this run')
152
- .option('--opt', 'key=value override, e.g. voice=nova; repeatable')
153
- .action(act(async (slug, o) => {
154
- const { voice } = await import('./voice.js')
155
- const p = P()
156
- await voice(p, slug, { locale: loc(o, p), only: o.only, provider: o.provider, opts: parseOpts(o.opt) })
157
- }))
158
-
159
- prog.command('fit <slug>')
160
- .describe('Fit each scene\'s running time to its take: timing.<locale>.json.')
161
- .option('--locale', 'Locale (default: the site default)')
162
- .option('--check', 'Report only; write nothing', false)
163
- .action(act(async (slug, o) => {
164
- const { fit } = await import('./voice.js')
165
- const p = P()
166
- const r = fit(p, slug, { locale: loc(o, p), check: o.check })
167
- console.info(`${'scene'.padEnd(12)} ${'design'.padStart(6)} ${'holds'.padStart(6)} ${'take'.padStart(6)} ${'runs'.padStart(6)}`)
168
- for (const x of r.rows)
169
- console.info(`${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)}${x.longer ? ' ← longer' : ''}${x.take ? '' : ' (no take)'}`)
170
- console.info(`total ${r.total.toFixed(1)} s (${loc(o, p)})${r.written ? `\nwrote ${r.path}` : ''}`)
171
- }))
172
-
173
- prog.command('render <slug>')
174
- .describe('Capture the picture frame by frame (with the score) and the covers (needs Playwright + ffmpeg).')
175
- .option('--locale', 'Locale (default: the site default)')
176
- .option('--url', 'A running site (default: start the dev server)')
177
- .option('--o', 'both | landscape | portrait', 'both')
178
- .option('--fps', 'Frames per second', 30)
179
- .action(act(async (slug, o) => {
180
- const { render } = await import('./capture.js')
181
- const p = P()
182
- await render(p, slug, { locale: loc(o, p), url: o.url, o: o.o, fps: Number(o.fps) })
183
- }))
184
-
185
- prog.command('build <slug>')
186
- .describe('Final videos: picture + voice + ducked score, captions (.srt/.vtt and burned in), -14 LUFS.')
187
- .option('--locale', 'Locale (default: the site default)')
188
- .option('--no-captions', 'Do not burn captions in')
189
- .action(act(async (slug, o) => {
190
- const { build } = await import('./voice.js')
191
- const p = P()
192
- build(p, slug, { locale: loc(o, p), noCaptions: o.captions === false })
193
- }))
16
+ setupCommands(prog)
17
+ productionCommands(prog)
18
+ postingCommands(prog)
19
+ campaignCommands(prog)
194
20
 
195
21
  prog.parse(process.argv)
package/src/init.js CHANGED
@@ -6,18 +6,14 @@ import { dirname, join } from 'node:path'
6
6
  import { TEMPLATES } from './films.js'
7
7
  import { load, save } from './util.js'
8
8
 
9
+ /** [dependency, framework], most specific first: a meta-framework wins over the library it is built on. */
10
+ const DETECT = [['@sveltejs/kit', 'sveltekit'], ['svelte', 'svelte'], ['next', 'next'], ['nuxt', 'nuxt'], ['react', 'react'], ['vue', 'vue']]
11
+
9
12
  /** Which framework a project uses, from its package.json. */
10
13
  export function detectFramework(cwd) {
11
14
  const pj = join(cwd, 'package.json')
12
- if (!existsSync(pj)) return 'vanilla'
13
- const p = load(pj), deps = { ...p.dependencies, ...p.devDependencies }
14
- if (deps['@sveltejs/kit']) return 'sveltekit'
15
- if (deps.svelte) return 'svelte'
16
- if (deps.next) return 'next'
17
- if (deps.nuxt) return 'nuxt'
18
- if (deps.react) return 'react'
19
- if (deps.vue) return 'vue'
20
- return 'vanilla'
15
+ const p = existsSync(pj) ? load(pj) : {}, deps = { ...p.dependencies, ...p.devDependencies }
16
+ return DETECT.find(([dep]) => deps[dep])?.[1] ?? 'vanilla'
21
17
  }
22
18
 
23
19
  export const PACKAGES = {
@@ -40,6 +36,7 @@ const GLOBS = (content) => `const g = {
40
36
  bodies: import.meta.glob('/${content}/stories/*/*.json', { import: 'default' }),
41
37
  logos: import.meta.glob('/${content}/logos/*.svg', { eager: true, query: '?raw', import: 'default' }),
42
38
  site: import.meta.glob('/${content}/site.json', { eager: true, import: 'default' }),
39
+ voice: import.meta.glob('/${content}/films/*/voice/*/*.m4a', { eager: true, query: '?url', import: 'default' }),
43
40
  };`
44
41
 
45
42
  const viteSourceFile = (content) => `// Where films and stories come from (written by \`emaki init\`). Vite expands these globs at build time, so every
@@ -63,18 +60,18 @@ export function startMotion() {
63
60
  const FILES = {
64
61
  sveltekit: (c) => ({
65
62
  'src/lib/emaki-source.ts': viteSourceFile(c),
66
- 'src/routes/show/[film]/+page.ts': `// The capture page the video pipeline drives; client-only.\nexport const ssr = false;\nexport const prerender = false;\nexport const load = ({ params, url }) => ({\n film: params.film,\n capture: url.searchParams.get('capture') === '1',\n layout: url.searchParams.get('o') === 'portrait' ? 'portrait' : 'landscape',\n locale: url.searchParams.get('locale') ?? 'en',\n});\n`,
67
- 'src/routes/show/[film]/+page.svelte': `<script lang="ts">\n import { ShowPage } from '@senseihq/emaki-svelte';\n import { startMotion } from '$lib/emaki-source';\n let { data } = $props();\n startMotion();\n</script>\n\n<ShowPage film={data.film} layout={data.layout} locale={data.locale} capture={data.capture} />\n`
63
+ 'src/routes/show/[film]/+page.ts': `// The capture page the video pipeline drives; client-only.\nexport const ssr = false;\nexport const prerender = false;\nexport const load = ({ params, url }) => ({\n film: params.film,\n capture: url.searchParams.get('capture') === '1',\n layout: url.searchParams.get('o') === 'portrait' ? 'portrait' : 'landscape',\n locale: url.searchParams.get('locale') ?? 'en',\n src: url.searchParams.get('src') === 'json' || url.searchParams.get('src') === 'js' ? url.searchParams.get('src') : undefined,\n mode: url.searchParams.get('mode') === 'dark' ? 'dark' : 'light',\n});\n`,
64
+ 'src/routes/show/[film]/+page.svelte': `<script lang="ts">\n import { ShowPage } from '@senseihq/emaki-svelte';\n import { startMotion } from '$lib/emaki-source';\n let { data } = $props();\n startMotion();\n</script>\n\n<ShowPage film={data.film} layout={data.layout} locale={data.locale} capture={data.capture} src={data.src} mode={data.mode} />\n`
68
65
  }),
69
66
  svelte: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
70
67
  react: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
71
68
  vue: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
72
69
  next: () => ({
73
- 'app/show/[film]/page.tsx': `'use client';\n// The capture page the video pipeline drives. Films are read at runtime from /public/content (emaki manifest\n// writes content/films/index.json; copy or symlink content/ into public/).\nimport { useEffect, useState } from 'react';\nimport { useSearchParams, useParams } from 'next/navigation';\nimport { setupMotion } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { ShowPage } from '@senseihq/emaki-react';\n\nexport default function Page() {\n const { film } = useParams<{ film: string }>();\n const q = useSearchParams();\n const [ready, setReady] = useState(false);\n useEffect(() => { setupMotion({ source: fetchFilmSource('/content') }); setReady(true); }, []);\n if (!ready) return null;\n return <ShowPage film={film} capture={q.get('capture') === '1'} layout={q.get('o') === 'portrait' ? 'portrait' : 'landscape'} locale={q.get('locale') ?? 'en'} />;\n}\n`
70
+ 'app/show/[film]/page.tsx': `'use client';\n// The capture page the video pipeline drives. Films are read at runtime from /public/content (emaki manifest\n// writes content/films/index.json; copy or symlink content/ into public/).\nimport { useEffect, useState } from 'react';\nimport { useSearchParams, useParams } from 'next/navigation';\nimport { setupMotion } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { ShowPage } from '@senseihq/emaki-react';\n\nexport default function Page() {\n const { film } = useParams<{ film: string }>();\n const q = useSearchParams();\n const [ready, setReady] = useState(false);\n useEffect(() => { setupMotion({ source: fetchFilmSource('/content') }); setReady(true); }, []);\n if (!ready) return null;\n return <ShowPage film={film} capture={q.get('capture') === '1'} layout={q.get('o') === 'portrait' ? 'portrait' : 'landscape'} locale={q.get('locale') ?? 'en'} src={(q.get('src') as 'json' | 'js' | null) ?? undefined} mode={q.get('mode') === 'dark' ? 'dark' : 'light'} />;\n}\n`
74
71
  }),
75
72
  nuxt: () => ({}),
76
73
  vanilla: () => ({
77
- 'motion.ts': `// Plain pages: films are read at runtime from /content (run \`emaki manifest\` after adding films).\nimport { setupMotion, installCapture } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { defineMotionElements } from '@senseihq/emaki/elements';\n\nsetupMotion({ source: fetchFilmSource('/content') });\ndefineMotionElements(); // <motion-scene film=… scene=…> and <motion-show film=…>\n\n// The capture page: /show.html?film=<slug>&capture=1&o=landscape&locale=en\nconst q = new URLSearchParams(location.search);\nif (q.get('capture') === '1') installCapture(document.getElementById('stage')!, q.get('film')!, q.get('o') === 'portrait' ? 'portrait' : 'landscape', q.get('locale') ?? 'en');\n`
74
+ 'motion.ts': `// Plain pages: films are read at runtime from /content (run \`emaki manifest\` after adding films).\nimport { setupMotion, installCapture } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { defineMotionElements } from '@senseihq/emaki/elements';\n\nsetupMotion({ source: fetchFilmSource('/content') });\ndefineMotionElements(); // <motion-scene film=… scene=…> and <motion-show film=…>\n\n// The capture page: /show.html?film=<slug>&capture=1&o=landscape&locale=en\nconst q = new URLSearchParams(location.search);\nif (q.get('capture') === '1') installCapture(document.getElementById('stage')!, q.get('film')!, q.get('o') === 'portrait' ? 'portrait' : 'landscape', q.get('locale') ?? 'en', { src: (q.get('src') as 'json' | 'js' | null) ?? undefined, mode: q.get('mode') === 'dark' ? 'dark' : 'light' });\n`
78
75
  })
79
76
  }
80
77
 
package/src/media.js ADDED
@@ -0,0 +1,80 @@
1
+ // What render and build decide, as pure functions: frame ranges, output paths, ffmpeg arguments, the freeze table,
2
+ // chapters, the description. render.js and build-video.js run what these return (Playwright, ffmpeg); the specs test these.
3
+ // Build's own decisions live in build-media.js and are re-exported here.
4
+ // The reference is the sensei-hq.com website's films/tools/render.py and build.py.
5
+ import { join, resolve } from 'node:path'
6
+ import { SUFFIX } from './config.js'
7
+ import { die } from './util.js'
8
+
9
+ export {
10
+ buildPlan, planTable, ffmeta, ytChapters, chaptersText, description, storyLink, posterSteps, webArgs, webNote, webVoiceArgs, buildArgs
11
+ } from './build-media.js'
12
+
13
+ /** The frames to capture: from `from` (default 0) to `to` (default and at most the film's end), at least one. */
14
+ export function frameRange(duration, fps, from = 0, to = undefined) {
15
+ const t0 = Math.max(0, Number(from ?? 0))
16
+ const end = Math.min(to == null ? duration : Number(to), duration)
17
+ if (!Number.isFinite(t0) || !Number.isFinite(end) || !(end > t0))
18
+ die(`--from ${from ?? 0} --to ${to ?? 'the end'} is not a range inside the film (it runs ${duration.toFixed(1)} s)`)
19
+ const frames = Math.max(1, Math.round((end - t0) * fps))
20
+ return { t0, end, frames, seconds: frames / fps }
21
+ }
22
+
23
+ /** Where a layout's render goes: the render folder by default; --out FILE.mp4 for one layout, --out FOLDER for any. */
24
+ export function renderOut(dir, slug, locale, layout, { out = undefined, layouts = 1 } = {}) {
25
+ const name = `${slug}-${locale}-${SUFFIX[layout]}.mp4`
26
+ if (!out) return join(dir, name)
27
+ if (!/\.mp4$/i.test(out)) return resolve(out, name)
28
+ if (layouts > 1) die(`--out ${out} is one file, so it takes one layout: add --o landscape or --o portrait, or give a folder`)
29
+ return resolve(out)
30
+ }
31
+
32
+ /** Where the music comes from (--music): `synth` the page's score (window.__show.audio(), on the film's own timing),
33
+ * `export` the audio of an exported film (`exportFile`; silent if it is missing), `none` a silent picture. */
34
+ export function musicFor(mode = 'synth', { exportFile = '', exists = (_f) => false } = {}) {
35
+ if (mode === 'synth') return { kind: 'synth' }
36
+ if (mode === 'none') return { kind: 'none' }
37
+ if (mode !== 'export') die(`--music ${mode}: use synth | export | none`)
38
+ if (exists(exportFile)) return { kind: 'file', file: exportFile }
39
+ return { kind: 'none', note: `no ${exportFile}: silent picture` }
40
+ }
41
+
42
+ /** What a render run does: capture frames, lay the music, save the covers. --audio-only lays the music on the
43
+ * existing render; --cover-only saves just the covers. */
44
+ export function renderSteps({ audioOnly = false, coverOnly = false } = {}) {
45
+ if (audioOnly && coverOnly) die('--audio-only and --cover-only exclude each other')
46
+ return { frames: !audioOnly && !coverOnly, music: !coverOnly, cover: true }
47
+ }
48
+
49
+ /** ffmpeg reading JPEG frames from stdin; `audio` (from film time t0) laid under them. */
50
+ export function encodeArgs({ fps, seconds, dst, audio = null, t0 = 0 }) {
51
+ return ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',
52
+ ...(audio ? ['-ss', t0.toFixed(3), '-i', audio, '-map', '0:v', '-map', '1:a'] : []),
53
+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p', '-r', String(fps),
54
+ ...(audio ? ['-c:a', 'aac', '-b:a', '192k'] : []), '-t', seconds.toFixed(3), '-movflags', '+faststart', dst]
55
+ }
56
+
57
+ /** --audio-only: copies the picture and lays `audio` (from film time t0, for dur) under it. */
58
+ export function muxArgs(video, audio, t0, dur, dst) {
59
+ return ['-y', '-loglevel', 'error', '-i', video, '-ss', t0.toFixed(3), '-i', audio, '-map', '0:v', '-map', '1:a',
60
+ '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-t', dur.toFixed(3), '-movflags', '+faststart', dst]
61
+ }
62
+
63
+ /** Runs `fn`; when it fails (the dev server reloaded the page under it), awaits `recover` (the show coming back)
64
+ * and runs it again, up to `attempts` times in all, then lets the last error through. */
65
+ export async function retrying(fn, recover, attempts = 8) {
66
+ for (let i = 1; ; i++) {
67
+ try {
68
+ return await fn()
69
+ } catch (e) {
70
+ if (i >= attempts) throw e
71
+ await recover(e)
72
+ }
73
+ }
74
+ }
75
+
76
+ /** A warning when an existing render no longer runs as long as the film (after a retiming): its frames are stale. */
77
+ export function staleRender(rendered, film, ranged = false) {
78
+ if (ranged || Math.abs(rendered - film) <= 0.2) return null
79
+ return `the render runs ${rendered.toFixed(1)} s but the film now runs ${film.toFixed(1)} s; render the frames again`
80
+ }