@senseihq/emaki-cli 0.0.0-stage → 0.1.0

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +34 -2
  3. package/package.json +42 -4
  4. package/plugin/.claude-plugin/plugin.json +19 -0
  5. package/plugin/PLAYBOOK.md +137 -0
  6. package/plugin/README.md +51 -0
  7. package/plugin/agents/fact-checker.md +28 -0
  8. package/plugin/agents/localizer.md +34 -0
  9. package/plugin/agents/scene-builder.md +43 -0
  10. package/plugin/agents/story-planner.md +42 -0
  11. package/plugin/agents/story-writer.md +34 -0
  12. package/plugin/agents/visual-reviewer.md +33 -0
  13. package/plugin/modules/campaign/README.md +23 -0
  14. package/plugin/modules/campaign/calendar.csv +2 -0
  15. package/plugin/modules/campaign/day-script.template.md +41 -0
  16. package/plugin/modules/posting-desk/README.md +37 -0
  17. package/plugin/skills/emaki/SKILL.md +107 -0
  18. package/plugin/skills/emaki/references/01-interview.md +68 -0
  19. package/plugin/skills/emaki/references/02-architecture.md +69 -0
  20. package/plugin/skills/emaki/references/03-content-model.md +65 -0
  21. package/plugin/skills/emaki/references/04-scene-authoring.md +96 -0
  22. package/plugin/skills/emaki/references/05-voice-and-video.md +64 -0
  23. package/plugin/skills/emaki/references/06-i18n.md +37 -0
  24. package/plugin/skills/emaki/references/07-quality-gates.md +44 -0
  25. package/plugin/skills/emaki/references/08-feedback-loop.md +32 -0
  26. package/plugin/skills/emaki/references/09-publishing.md +11 -0
  27. package/plugin/skills/story-build/SKILL.md +37 -0
  28. package/plugin/skills/story-localize/SKILL.md +24 -0
  29. package/plugin/skills/story-media/SKILL.md +36 -0
  30. package/plugin/skills/story-publish/SKILL.md +22 -0
  31. package/plugin/skills/story-review/SKILL.md +29 -0
  32. package/plugin/templates/brief.md +32 -0
  33. package/plugin/templates/change-request.md +7 -0
  34. package/plugin/templates/changelog.md +4 -0
  35. package/plugin/templates/decisions.md +5 -0
  36. package/plugin/templates/glossary.md +4 -0
  37. package/plugin/templates/item-card.md +34 -0
  38. package/plugin/templates/outline.md +19 -0
  39. package/plugin/templates/review-sheet.md +12 -0
  40. package/plugin/templates/style-guide.md +21 -0
  41. package/plugin/templates/tracker.md +11 -0
  42. package/src/api.js +9 -0
  43. package/src/capture.js +169 -0
  44. package/src/config.js +32 -0
  45. package/src/films.js +145 -0
  46. package/src/index.js +195 -0
  47. package/src/init.js +109 -0
  48. package/src/plugin.js +106 -0
  49. package/src/tts.js +290 -0
  50. package/src/util.js +59 -0
  51. package/src/voice.js +216 -0
  52. package/templates/content/films/index.json +1 -0
  53. package/templates/content/films/measure-the-right-work/film.json +59 -0
  54. package/templates/content/films/measure-the-right-work/look.css +16 -0
  55. package/templates/content/films/measure-the-right-work/scene-close.json +153 -0
  56. package/templates/content/films/measure-the-right-work/scene-groups.json +99 -0
  57. package/templates/content/films/measure-the-right-work/scene-hook.json +96 -0
  58. package/templates/content/films/measure-the-right-work/scene-pair.json +190 -0
  59. package/templates/content/films/measure-the-right-work/scene-problem.json +162 -0
  60. package/templates/content/films/measure-the-right-work/score.js +19 -0
  61. package/templates/content/films/measure-the-right-work/strings/en.json +50 -0
  62. package/templates/content/films/measure-the-right-work/strings/es.json +50 -0
  63. package/templates/content/films/measure-the-right-work/voice/en.json +7 -0
  64. package/templates/content/films/measure-the-right-work/voice/es.json +7 -0
  65. package/templates/content/logos/brand.svg +1 -0
  66. package/templates/content/site.json +10 -0
  67. package/templates/content/stories/en/measure-the-right-work.json +13 -0
  68. package/templates/content/stories/es/measure-the-right-work.json +13 -0
  69. package/templates/content/stories/index.json +12 -0
  70. package/templates/content/ui/en.json +1 -0
  71. package/templates/content/ui/es.json +1 -0
  72. package/templates/emaki.config.json +67 -0
  73. package/templates/film/look.css +16 -0
  74. package/templates/film/scene-close.json +153 -0
  75. package/templates/film/scene-template.json +71 -0
  76. package/templates/film/score.js +12 -0
package/src/films.js ADDED
@@ -0,0 +1,145 @@
1
+ // manifest, validate, new: the content contracts. A film is a folder (film.json, look.css, scene-<id>.json, score.js,
2
+ // strings/<locale>.json, voice/<locale>.json, timing.<locale>.json); a story is index.json + stories/<locale>/<slug>.json.
3
+ import { readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { KEY } from './config.js'
7
+ import { die, exists, load, save, today } from './util.js'
8
+
9
+ export const TEMPLATES = fileURLToPath(new URL('../templates/', import.meta.url))
10
+
11
+ export const filmSlugs = (p) =>
12
+ exists(p.films) ? readdirSync(p.films).filter((d) => exists(join(p.films, d, 'film.json'))).sort() : []
13
+
14
+ /** content/films/index.json: the film list the fetch loader reads. */
15
+ export function manifest(p) {
16
+ const slugs = filmSlugs(p)
17
+ save(join(p.films, 'index.json'), slugs)
18
+ return { count: slugs.length, path: p.rel(join(p.films, 'index.json')) }
19
+ }
20
+
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
+ /** All problems (lines prefixed "(info)" are notes, not failures). */
93
+ export function validate(p, slug) {
94
+ const ip = join(p.content, 'stories', 'index.json')
95
+ const index = exists(ip) ? load(ip) : []
96
+ const out = []
97
+ for (const s of slug ? [slug] : filmSlugs(p)) for (const i of validateFilm(p, s)) out.push(`film ${s}: ${i}`)
98
+ for (const e of index) if (!slug || e.slug === slug) for (const i of validateStory(p, e)) out.push(`story ${e.slug}: ${i}`)
99
+ return { lines: out, problems: out.filter((l) => !l.includes('(info)')).length }
100
+ }
101
+
102
+ /** Scaffolds a story + film with every locale's strings, voice script and story body. */
103
+ export function newFilm(p, slug, { scenes, title, date } = {}) {
104
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) die('slug: lower-case letters, digits and dashes')
105
+ const d = join(p.films, slug)
106
+ if (exists(d)) die(`${p.rel(d)} already exists`)
107
+ const ids = String(scenes ?? 'hook,idea,how').split(',').map((s) => s.trim()).filter(Boolean)
108
+ if (ids.at(-1) !== 'close') ids.push('close')
109
+ const T = join(TEMPLATES, 'film')
110
+ const name = (i) => i.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
111
+ const film = {
112
+ title: title || name(slug), look: 'Describe the look in one paragraph.', background: '#F3F0E9',
113
+ fonts: { display: { family: 'Fraunces', weights: [300, 400] }, sans: { family: 'Inter', weights: [400, 600] } },
114
+ scenes: ids.map((i) => ({ id: i, name: name(i), dur: i === 'close' ? 5.5 : 10, desc: 'What this scene shows.' }))
115
+ }
116
+ save(join(d, 'film.json'), film)
117
+ mkdirSync(d, { recursive: true })
118
+ writeFileSync(join(d, 'look.css'), readFileSync(join(T, 'look.css'), 'utf-8'))
119
+ writeFileSync(join(d, 'score.js'), readFileSync(join(T, 'score.js'), 'utf-8'))
120
+ const tpl = readFileSync(join(T, 'scene-template.json'), 'utf-8'), close = readFileSync(join(T, 'scene-close.json'), 'utf-8')
121
+ let strings = {}
122
+ const voice = []
123
+ for (const i of ids) {
124
+ writeFileSync(join(d, `scene-${i}.json`), (i === 'close' ? close : tpl).replaceAll('__ID__', i))
125
+ strings = i === 'close'
126
+ ? { ...strings, 'close.title': 'The punchline.', 'close.sub': 'One line under it.' }
127
+ : { ...strings, [`${i}.eyebrow`]: name(i), [`${i}.line`]: 'The headline for this scene.', [`${i}.sub`]: 'One supporting line.', [`${i}.label`]: 'Label' }
128
+ voice.push({ scene: i, text: 'What the narrator says over this scene.', say: null })
129
+ }
130
+ for (const loc of p.site.locales) {
131
+ save(join(d, 'strings', `${loc}.json`), strings)
132
+ save(join(d, 'voice', `${loc}.json`), voice)
133
+ save(join(p.content, 'stories', loc, `${slug}.json`), {
134
+ title: film.title, dek: 'One or two sentences.',
135
+ sections: ids.filter((i) => !['hook', 'close'].includes(i)).map((i) => ({ id: i, eyebrow: name(i), title: 'Section title', body: ['Paragraph.'] })),
136
+ takeaway: strings['close.title'], takeawaySub: strings['close.sub'], sources: []
137
+ })
138
+ }
139
+ const ip = join(p.content, 'stories', 'index.json')
140
+ const index = exists(ip) ? load(ip) : []
141
+ index.push({ slug, publish_date: date || today(), kind: 'film', tags: [], minutes: 4 })
142
+ save(ip, index.sort((a, b) => a.publish_date.localeCompare(b.publish_date)))
143
+ manifest(p)
144
+ return { slug, scenes: ids.length, locales: p.site.locales.length }
145
+ }
package/src/index.js ADDED
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable no-console */
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.
5
+ import sade from 'sade'
6
+ 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'
10
+
11
+ const prog = sade('emaki')
12
+ prog.version(pkg.version)
13
+
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
+ }))
194
+
195
+ prog.parse(process.argv)
package/src/init.js ADDED
@@ -0,0 +1,109 @@
1
+ // `emaki init`: sets a project up for motion stories. Adds the sample content (one film in en + es), a
2
+ // emaki.config.json, and the framework glue: a film source (Vite globs, or the fetch loader) and the /show capture
3
+ // route where the framework allows writing one. Never overwrites a file that exists.
4
+ import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
5
+ import { dirname, join } from 'node:path'
6
+ import { TEMPLATES } from './films.js'
7
+ import { load, save } from './util.js'
8
+
9
+ /** Which framework a project uses, from its package.json. */
10
+ export function detectFramework(cwd) {
11
+ 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'
21
+ }
22
+
23
+ export const PACKAGES = {
24
+ sveltekit: ['@senseihq/emaki', '@senseihq/emaki-svelte'],
25
+ svelte: ['@senseihq/emaki', '@senseihq/emaki-svelte'],
26
+ react: ['@senseihq/emaki', '@senseihq/emaki-react'],
27
+ next: ['@senseihq/emaki', '@senseihq/emaki-react'],
28
+ vue: ['@senseihq/emaki', '@senseihq/emaki-vue'],
29
+ nuxt: ['@senseihq/emaki', '@senseihq/emaki-vue'],
30
+ vanilla: ['@senseihq/emaki']
31
+ }
32
+
33
+ const GLOBS = (content) => `const g = {
34
+ films: import.meta.glob('/${content}/films/*/film.json', { eager: true, import: 'default' }),
35
+ scenes: import.meta.glob('/${content}/films/*/scene-*.json', { import: 'default' }),
36
+ strings: import.meta.glob('/${content}/films/*/strings/*.json', { import: 'default' }),
37
+ timings: import.meta.glob('/${content}/films/*/timing*.json', { eager: true, import: 'default' }),
38
+ raw: import.meta.glob(['/${content}/films/*/*.js', '/${content}/films/*/look.css'], { query: '?raw', import: 'default' }),
39
+ index: import.meta.glob('/${content}/stories/index.json', { eager: true, import: 'default' }),
40
+ bodies: import.meta.glob('/${content}/stories/*/*.json', { import: 'default' }),
41
+ logos: import.meta.glob('/${content}/logos/*.svg', { eager: true, query: '?raw', import: 'default' }),
42
+ site: import.meta.glob('/${content}/site.json', { eager: true, import: 'default' }),
43
+ };`
44
+
45
+ const viteSourceFile = (content) => `// Where films and stories come from (written by \`emaki init\`). Vite expands these globs at build time, so every
46
+ // film under /${content} is bundled; scene files and sounds load on demand. Call startMotion() once on the client.
47
+ import { setupMotion } from '@senseihq/emaki';
48
+ import { viteSource } from '@senseihq/emaki/loaders/vite';
49
+
50
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
+ ${GLOBS(content)}
52
+
53
+ export const { filmSource, contentSource, logos, site } = viteSource(g as any);
54
+
55
+ let started = false;
56
+ export function startMotion() {
57
+ if (started) return;
58
+ started = true;
59
+ setupMotion({ source: filmSource, site, logos });
60
+ }
61
+ `
62
+
63
+ const FILES = {
64
+ sveltekit: (c) => ({
65
+ '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`
68
+ }),
69
+ svelte: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
70
+ react: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
71
+ vue: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
72
+ 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`
74
+ }),
75
+ nuxt: () => ({}),
76
+ 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`
78
+ })
79
+ }
80
+
81
+ export function init({ cwd = process.cwd(), framework, content = 'content', sample = true } = {}) {
82
+ const fw = framework ?? detectFramework(cwd)
83
+ const wrote = [], kept = []
84
+ const write = (rel, text) => {
85
+ const f = join(cwd, rel)
86
+ if (existsSync(f)) return kept.push(rel)
87
+ mkdirSync(dirname(f), { recursive: true })
88
+ writeFileSync(f, text)
89
+ wrote.push(rel)
90
+ }
91
+ if (sample && !existsSync(join(cwd, content))) {
92
+ cpSync(join(TEMPLATES, 'content'), join(cwd, content), { recursive: true })
93
+ wrote.push(`${content}/ (sample film "measure-the-right-work" in en + es)`)
94
+ } else if (existsSync(join(cwd, content))) kept.push(`${content}/`)
95
+ const cfgPath = join(cwd, 'emaki.config.json')
96
+ if (!existsSync(cfgPath)) {
97
+ const cfg = JSON.parse(readFileSync(join(TEMPLATES, 'emaki.config.json'), 'utf-8'))
98
+ cfg.content = content
99
+ if (fw === 'sveltekit') cfg.coversDir = 'static/covers'
100
+ cfg.showPath = fw === 'vanilla' ? '/show.html?film={slug}&capture=1&o={layout}&locale={locale}' : cfg.showPath
101
+ save(cfgPath, cfg)
102
+ wrote.push('emaki.config.json')
103
+ } else kept.push('emaki.config.json')
104
+ for (const [rel, text] of Object.entries(FILES[fw](content))) write(rel, text)
105
+ const gi = join(cwd, '.gitignore')
106
+ const ignore = existsSync(gi) ? readFileSync(gi, 'utf-8') : ''
107
+ if (!/^production\/?$/m.test(ignore)) { writeFileSync(gi, ignore + (ignore && !ignore.endsWith('\n') ? '\n' : '') + '# motion stories: takes, renders, sheets (never deployed)\nproduction/\n'); wrote.push('.gitignore (production/)') }
108
+ return { framework: fw, packages: PACKAGES[fw], wrote, kept }
109
+ }
package/src/plugin.js ADDED
@@ -0,0 +1,106 @@
1
+ // The Claude plugin ships inside this package (plugin/): skills, agents, the playbook and planning templates. These
2
+ // commands copy it into a project's .claude/ so Claude Code / Cowork picks it up, the same way @rokkit/cli does.
3
+ /* eslint-disable no-console */
4
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ export const PLUGIN_DIR = (() => {
9
+ try {
10
+ return fileURLToPath(new URL('../plugin/', import.meta.url))
11
+ } catch {
12
+ return resolve(process.cwd(), 'packages/emaki-cli/plugin')
13
+ }
14
+ })()
15
+
16
+ /** name + description from a SKILL.md or agent .md frontmatter. */
17
+ export function parseFrontmatter(md) {
18
+ const block = md.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? ''
19
+ const field = (key) => {
20
+ const m = block.match(new RegExp(`^${key}:[ \t]*(.*)$`, 'm'))
21
+ if (!m) return ''
22
+ if (!/^[>|][-+]?$/.test(m[1].trim())) return m[1].trim()
23
+ // A folded (>) or literal (|) block: the indented lines that follow.
24
+ const rest = block.slice(m.index + m[0].length + 1).split('\n')
25
+ const lines = []
26
+ for (const l of rest) { if (l && !/^\s/.test(l)) break; lines.push(l.trim()) }
27
+ return lines.join(m[1].startsWith('|') ? '\n' : ' ').trim()
28
+ }
29
+ return { name: field('name'), description: field('description') }
30
+ }
31
+
32
+ export function listSkills({ dir = PLUGIN_DIR } = {}) {
33
+ const root = join(dir, 'skills')
34
+ if (!existsSync(root)) return []
35
+ return readdirSync(root)
36
+ .filter((e) => existsSync(join(root, e, 'SKILL.md')))
37
+ .map((e) => ({ ...parseFrontmatter(readFileSync(join(root, e, 'SKILL.md'), 'utf-8')), folder: e }))
38
+ .filter((s) => s.name)
39
+ .sort((a, b) => a.name.localeCompare(b.name))
40
+ }
41
+
42
+ export function listAgents({ dir = PLUGIN_DIR } = {}) {
43
+ const root = join(dir, 'agents')
44
+ if (!existsSync(root)) return []
45
+ return readdirSync(root)
46
+ .filter((e) => e.endsWith('.md'))
47
+ .map((e) => ({ ...parseFrontmatter(readFileSync(join(root, e), 'utf-8')), file: e }))
48
+ .filter((a) => a.name)
49
+ .sort((a, b) => a.name.localeCompare(b.name))
50
+ }
51
+
52
+ /** Copies skills into <cwd>/.claude/skills/<name>/ (idempotent unless force). */
53
+ export function installSkills(names, { cwd = process.cwd(), force = false, dir = PLUGIN_DIR } = {}) {
54
+ const catalog = new Map(listSkills({ dir }).map((s) => [s.name, s]))
55
+ const target = resolve(cwd, '.claude', 'skills')
56
+ return names.map((name) => {
57
+ const s = catalog.get(name)
58
+ if (!s) return { name, status: 'unknown' }
59
+ const dest = join(target, name)
60
+ if (existsSync(dest) && !force) return { name, status: 'skipped' }
61
+ mkdirSync(target, { recursive: true })
62
+ cpSync(join(dir, 'skills', s.folder), dest, { recursive: true })
63
+ return { name, status: 'added' }
64
+ })
65
+ }
66
+
67
+ /** Copies agents into <cwd>/.claude/agents/<name>.md. */
68
+ export function installAgents(names, { cwd = process.cwd(), force = false, dir = PLUGIN_DIR } = {}) {
69
+ const catalog = new Map(listAgents({ dir }).map((a) => [a.name, a]))
70
+ const target = resolve(cwd, '.claude', 'agents')
71
+ return names.map((name) => {
72
+ const a = catalog.get(name)
73
+ if (!a) return { name, status: 'unknown' }
74
+ const dest = join(target, `${name}.md`)
75
+ if (existsSync(dest) && !force) return { name, status: 'skipped' }
76
+ mkdirSync(target, { recursive: true })
77
+ cpSync(join(dir, 'agents', a.file), dest)
78
+ return { name, status: 'added' }
79
+ })
80
+ }
81
+
82
+ /** The whole plugin into the project: every skill and agent, plus the playbook and planning templates under
83
+ * .claude/emaki/ (the skills read them from there). */
84
+ export function installPlugin({ cwd = process.cwd(), force = false, dir = PLUGIN_DIR } = {}) {
85
+ const skills = installSkills(listSkills({ dir }).map((s) => s.name), { cwd, force, dir })
86
+ const agents = installAgents(listAgents({ dir }).map((a) => a.name), { cwd, force, dir })
87
+ const home = resolve(cwd, '.claude', 'emaki')
88
+ const extras = []
89
+ for (const f of ['PLAYBOOK.md', 'README.md', 'templates', 'modules']) {
90
+ const src = join(dir, f), dest = join(home, f)
91
+ if (!existsSync(src)) continue
92
+ if (existsSync(dest) && !force) { extras.push({ name: f, status: 'skipped' }); continue }
93
+ mkdirSync(home, { recursive: true })
94
+ cpSync(src, dest, { recursive: true })
95
+ extras.push({ name: f, status: 'added' })
96
+ }
97
+ return { skills, agents, extras }
98
+ }
99
+
100
+ export function report(kind, results) {
101
+ for (const r of results) {
102
+ if (r.status === 'added') console.info(` added ${kind} ${r.name}`)
103
+ else if (r.status === 'skipped') console.info(` skipped ${kind} ${r.name} (exists; --force to overwrite)`)
104
+ else { console.error(` unknown ${kind}: ${r.name}`); process.exitCode = 1 }
105
+ }
106
+ }