@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
@@ -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,66 @@
1
+ // A campaign day script (<campaign>/days/day-NN-<slug>.md, or days/<locale>/…): one piece's copy for every channel.
2
+ // Reads both the website's labels (**YouTube title:**, **YouTube description:**) and the plugin template's (**Title:**,
3
+ // **Description:** under "## N · YouTube").
4
+ import { readdirSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { exists } from './util.js'
7
+
8
+ /** The campaign folder: emaki.config.json "campaign" (default campaign/). */
9
+ export const campaignDir = (p) => join(p.root, p.cfg.campaign ?? 'campaign')
10
+
11
+ /** The slug in a day script's file name: day-07-some-slug.md → some-slug. */
12
+ export const slugOfScript = (file) => file.replace(/^.*\//, '').replace(/\.md$/, '').replace(/^day-\d+-/, '')
13
+
14
+ /** Path of the day script for a slug (the locale's folder first), or null. */
15
+ export function dayScriptPath(p, slug, locale) {
16
+ for (const dir of [join(campaignDir(p), 'days', locale), join(campaignDir(p), 'days')]) {
17
+ if (!exists(dir)) continue
18
+ const f = readdirSync(dir).sort().find((n) => /^day-\d+-.+\.md$/.test(n) && slugOfScript(n) === slug)
19
+ if (f) return join(dir, f)
20
+ }
21
+ return null
22
+ }
23
+
24
+ export const dayScript = (p, slug, locale) => {
25
+ const f = dayScriptPath(p, slug, locale)
26
+ return f ? readFileSync(f, 'utf-8') : null
27
+ }
28
+
29
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
30
+
31
+ /** The text after **Label:** up to a blank line before the next label, the next label line, a heading, or the end. */
32
+ export function field(md, ...labels) {
33
+ for (const label of labels) {
34
+ const m = md.match(new RegExp(`\\*\\*${esc(label)}:\\*\\*[ \\t]*([\\s\\S]*?)(?=\\n\\s*\\n\\*\\*|\\n\\*\\*[^*\\n]+:\\*\\*|\\n#{1,6} |$(?![\\s\\S]))`))
35
+ if (m) return m[1].trim()
36
+ }
37
+ return ''
38
+ }
39
+
40
+ /** "1. text" lines of a block, numbers dropped. */
41
+ export const numbered = (block) => block.split('\n').map((l) => l.trim()).filter((l) => /^\d+\.\s/.test(l)).map((l) => l.replace(/^\d+\.\s*/, '').trim())
42
+
43
+ /** The channel copy of a day script. */
44
+ export function channelCopy(md) {
45
+ const ytDesc = field(md, 'YouTube description', 'Description')
46
+ const thread = md.includes('**Thread:**') ? md.split('**Thread:**')[1].split('\n## ')[0] : ''
47
+ return {
48
+ youtube: { title: field(md, 'YouTube title', 'Title').slice(0, 100), description: ytDesc, tags: [...ytDesc.matchAll(/#(\w+)/g)].map((m) => m[1]) },
49
+ caption: [field(md, 'Caption'), field(md, 'Hashtags')].filter(Boolean).join('\n\n'),
50
+ x: { text: field(md, 'Post'), thread: numbered(thread) }
51
+ }
52
+ }
53
+
54
+ /** The topic in the heading: "# Day 01 · Mon Nov 16 · DBD: Title" → DBD. */
55
+ export const topicOf = (md) => md.match(/^# Day \d+ · .+? · (.+?): /m)?.[1] ?? ''
56
+
57
+ /** The carousel slides: the numbered lines of "## N · Instagram carousel" before **Caption:** (\n in a line breaks it). */
58
+ export function slidesOf(md) {
59
+ const parts = md.split(/^## \d+ · Instagram carousel.*$/m)
60
+ if (parts.length < 2) return []
61
+ const block = parts[1].split('**Caption:**')[0].split(/^## /m)[0]
62
+ return numbered(block).map((s) => s.replaceAll('\\n', '\n'))
63
+ }
64
+
65
+ /** The voiceover table: | # | Voiceover | On screen | rows. */
66
+ export const beatsOf = (md) => [...md.matchAll(/^\| (\d+) \| (.+?) \| (.+?) \|$/gm)].map((m) => ({ n: Number(m[1]), text: m[2].trim(), screen: m[3].trim() }))
@@ -0,0 +1,37 @@
1
+ // The posting desk as the producing machine sees it: the HTTP contract of @senseihq/emaki-posting's createDesk
2
+ // (media/<key> PUT, stage, production, requests), called with the stager's Cloudflare Access service token.
3
+ // ADMIN_ORIGIN (default: content/site.json url), ADMIN_API (default /api/admin),
4
+ // STAGER_CLIENT_ID, STAGER_CLIENT_SECRET.
5
+ import { createHash } from 'node:crypto'
6
+ import { validKey } from '@senseihq/emaki-posting'
7
+ import { callJson, need } from './http.js'
8
+ import { die } from './util.js'
9
+
10
+ export const deskOrigin = (p, env) => (env.ADMIN_ORIGIN || p.site.url || '').replace(/\/$/, '')
11
+
12
+ export function deskClient(p, { env = process.env, fetch = globalThis.fetch } = {}) {
13
+ need(env, 'STAGER_CLIENT_ID', 'STAGER_CLIENT_SECRET')
14
+ const origin = deskOrigin(p, env)
15
+ if (!origin) die('no desk origin: set ADMIN_ORIGIN, or "url" in content/site.json')
16
+ const api = origin + (env.ADMIN_API || '/api/admin').replace(/\/$/, '')
17
+ const auth = { 'CF-Access-Client-Id': env.STAGER_CLIENT_ID, 'CF-Access-Client-Secret': env.STAGER_CLIENT_SECRET }
18
+ const post = (path, data) => callJson(fetch, 'POST', api + path, { body: JSON.stringify(data), headers: { ...auth, 'content-type': 'application/json' } })
19
+ return {
20
+ origin,
21
+ /** Uploads one file to the desk's media store; the desk checks the sha256. */
22
+ async putMedia(key, bytes, type) {
23
+ if (!validKey(key)) die(`bad media key "${key}": <slug>/<file>, lower-case letters, digits, . _ -`)
24
+ const sha256 = createHash('sha256').update(bytes).digest('hex')
25
+ await callJson(fetch, 'PUT', `${api}/media/${key}`, { body: bytes, headers: { ...auth, 'x-content-sha256': sha256, 'content-type': type } })
26
+ return sha256
27
+ },
28
+ /** Stages one channel's post (media already uploaded); returns { content_sha }. */
29
+ stage: (slug, channel, postBody) => post('/stage', { slug, channel, post: postBody }),
30
+ /** Reports scripts and production status for the desk's plan; returns { saved }. */
31
+ production: (items) => post('/production', { items }),
32
+ /** The open requests from the desk, each with its thread. */
33
+ requests: async () => (await callJson(fetch, 'GET', api + '/requests', { headers: auth })).requests ?? [],
34
+ /** Answers a request, optionally moving it to working or done. */
35
+ reply: (id, reply, status) => post('/requests', { id, reply, ...(status ? { status } : {}) })
36
+ }
37
+ }
@@ -0,0 +1,57 @@
1
+ // emaki stage status | requests | reply: the producing machine's side of the desk's plan. It reports each piece's
2
+ // script and what exists for it (the desk shows it beside the piece), reads the open motion requests people left on
3
+ // the desk, and answers them.
4
+ import { readdirSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { campaignDir, dayScriptPath } from './day-script.js'
7
+ import { deskClient } from './desk-client.js'
8
+ import { filmFiles, storiesIndex } from './stories.js'
9
+ import { die, exists, load } from './util.js'
10
+
11
+ const count = (dir, test) => (exists(dir) ? readdirSync(dir).filter(test).length : 0)
12
+
13
+ /** One piece's script and production status, in the shape the desk stores (Production in @senseihq/emaki-posting). */
14
+ export function pieceStatus(p, slug, locale) {
15
+ const film = join(p.films, slug), files = filmFiles(p, slug, locale)
16
+ const voice = join(film, 'voice', `${locale}.json`), fj = join(film, 'film.json')
17
+ const takesNeeded = exists(voice) ? load(voice).length : exists(fj) ? (load(fj).scenes ?? []).length : 0
18
+ const base = { motion: exists(fj), takes: count(p.prod(slug, locale, 'takes'), (n) => /^take-\d+\.(wav|mp3|m4a|aiff)$/.test(n)), takesNeeded }
19
+ const day = dayScriptPath(p, slug, locale)
20
+ if (day)
21
+ return { script: readFileSync(day, 'utf-8'), status: { ...base, short: Boolean(files.tall), carousel: count(join(campaignDir(p), 'carousels', slug), (n) => n.endsWith('.png')) } }
22
+ const script = join(film, 'script.md')
23
+ return { script: exists(script) ? readFileSync(script, 'utf-8') : null, status: { ...base, film: true, render: Boolean(files.wide) } }
24
+ }
25
+
26
+ /** Reports every story (or one) to the desk's plan. */
27
+ export async function productionStatus(p, slug, { locale, env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
28
+ locale ??= p.site.defaultLocale
29
+ const desk = deskClient(p, { env, fetch })
30
+ const ip = storiesIndex(p)
31
+ const slugs = (exists(ip) ? load(ip) : []).map((e) => e.slug).filter((s) => !slug || s === slug)
32
+ if (slug && !slugs.length) die(`${slug} is not in ${p.rel(ip)}`)
33
+ const r = await desk.production(slugs.map((s) => ({ slug: s, ...pieceStatus(p, s, locale) })))
34
+ log(`reported ${r.saved} piece(s)`)
35
+ return r
36
+ }
37
+
38
+ /** The open motion requests, each with its thread. */
39
+ export async function deskRequests(p, { env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
40
+ const list = await deskClient(p, { env, fetch }).requests()
41
+ if (!list.length) log('no open requests')
42
+ for (const r of list) {
43
+ log(`#${r.id} ${r.slug} · ${r.kind} · ${r.status} · ${r.author} ${String(r.at ?? '').slice(0, 16)}`)
44
+ log(` ${r.body}`)
45
+ for (const t of r.thread ?? []) log(` ↳ ${t.author}: ${t.body}`)
46
+ }
47
+ return list
48
+ }
49
+
50
+ /** Answers request `id`; status 'working' or 'done' moves it on the desk. */
51
+ export async function deskReply(p, id, text, { status, env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
52
+ const n = Number(id)
53
+ if (!Number.isInteger(n) || n <= 0) die(`request id must be a number (got "${id}")`)
54
+ if (status && !['working', 'done'].includes(status)) die(`status must be working or done (got "${status}")`)
55
+ await deskClient(p, { env, fetch }).reply(n, text ?? '', status)
56
+ log('sent')
57
+ }
@@ -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
+ }