@biunow/agent-biutalk 0.0.0-stage → 1.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.
- package/bin/server.js +355 -0
- package/engine/AGENTS.md +1414 -0
- package/engine/CLAUDE.md +1 -0
- package/engine/LICENSE +21 -0
- package/engine/README.md +216 -0
- package/engine/bin/explainroo.js +19 -0
- package/engine/dev/audio-lab.mjs +268 -0
- package/engine/docs/media/contact-sheet.jpg +0 -0
- package/engine/docs/media/dns-poster.jpg +0 -0
- package/engine/docs/media/intro-poster.jpg +0 -0
- package/engine/docs/media/logo-dark.png +0 -0
- package/engine/docs/media/logo-light.png +0 -0
- package/engine/docs/media/looks-dark.webp +0 -0
- package/engine/docs/media/looks-light.webp +0 -0
- package/engine/docs/media/product-demo.webp +0 -0
- package/engine/docs/media/rebase-poster.jpg +0 -0
- package/engine/docs/media/sizes-dark.webp +0 -0
- package/engine/docs/media/sizes-light.webp +0 -0
- package/engine/engine/audio/dsp.js +69 -0
- package/engine/engine/audio/instruments.js +147 -0
- package/engine/engine/audio/music.js +576 -0
- package/engine/engine/audio/pcm.js +93 -0
- package/engine/engine/audio/rng.js +40 -0
- package/engine/engine/audio/sfx.js +287 -0
- package/engine/engine/audio/soundtrack.js +201 -0
- package/engine/engine/audio/synth.js +721 -0
- package/engine/engine/audio/theory.js +105 -0
- package/engine/engine/audio/wav.js +47 -0
- package/engine/engine/captions.js +131 -0
- package/engine/engine/clips.js +107 -0
- package/engine/engine/code.js +179 -0
- package/engine/engine/director.js +475 -0
- package/engine/engine/frame.html +135 -0
- package/engine/engine/icons/LICENSE-lucide.txt +43 -0
- package/engine/engine/icons/lucide-tags.json +1 -0
- package/engine/engine/icons/lucide.json +1 -0
- package/engine/engine/layout.js +69 -0
- package/engine/engine/pathdata.js +234 -0
- package/engine/engine/pen.js +240 -0
- package/engine/engine/player.html +67 -0
- package/engine/engine/player.js +219 -0
- package/engine/engine/readability.js +9 -0
- package/engine/engine/runtime.js +690 -0
- package/engine/engine/stage.js +2247 -0
- package/engine/engine/studio.html +216 -0
- package/engine/engine/text.js +81 -0
- package/engine/engine/themes.js +360 -0
- package/engine/engine/transitions.js +161 -0
- package/engine/engine/ui.js +1042 -0
- package/engine/engine/upload.js +32 -0
- package/engine/engine/util.js +204 -0
- package/engine/examples/callbacks-to-async-await/code-versions.js +34 -0
- package/engine/examples/callbacks-to-async-await/scenes.js +106 -0
- package/engine/examples/callbacks-to-async-await/script.md +22 -0
- package/engine/examples/callbacks-to-async-await/video.json +16 -0
- package/engine/examples/circle-area/scenes.js +228 -0
- package/engine/examples/circle-area/script.md +37 -0
- package/engine/examples/circle-area/video.json +14 -0
- package/engine/examples/explainroo-intro/scenes.js +133 -0
- package/engine/examples/explainroo-intro/script.md +27 -0
- package/engine/examples/explainroo-intro/video.json +8 -0
- package/engine/examples/how-dns-works/scenes.js +130 -0
- package/engine/examples/how-dns-works/script.md +28 -0
- package/engine/examples/how-dns-works/video.json +8 -0
- package/engine/examples/leap-years/scenes.js +156 -0
- package/engine/examples/leap-years/script.md +25 -0
- package/engine/examples/leap-years/video.json +16 -0
- package/engine/examples/leap-years-ja/scenes.js +194 -0
- package/engine/examples/leap-years-ja/script.md +32 -0
- package/engine/examples/leap-years-ja/video.json +17 -0
- package/engine/examples/merge-vs-rebase/scenes.js +129 -0
- package/engine/examples/merge-vs-rebase/script.md +22 -0
- package/engine/examples/merge-vs-rebase/video.json +8 -0
- package/engine/examples/password-storage-zh/scenes.js +185 -0
- package/engine/examples/password-storage-zh/script.md +25 -0
- package/engine/examples/password-storage-zh/video.json +19 -0
- package/engine/examples/sqlite-demo/README.md +19 -0
- package/engine/examples/sqlite-demo/scenes.js +423 -0
- package/engine/examples/sqlite-demo/script.md +35 -0
- package/engine/examples/sqlite-demo/video.json +17 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-400.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-500.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-600.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-700.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-OFL.txt +93 -0
- package/engine/examples/unspar-demo/assets/unspar-logo.svg +23 -0
- package/engine/examples/unspar-demo/scenes.js +367 -0
- package/engine/examples/unspar-demo/script.md +25 -0
- package/engine/examples/unspar-demo/video.json +21 -0
- package/engine/examples/why-is-the-sky-blue-es/scenes.js +160 -0
- package/engine/examples/why-is-the-sky-blue-es/script.md +22 -0
- package/engine/examples/why-is-the-sky-blue-es/video.json +15 -0
- package/engine/fonts/ArchitectsDaughter-400-latin-ext.woff2 +0 -0
- package/engine/fonts/ArchitectsDaughter-400-latin.woff2 +0 -0
- package/engine/fonts/CabinSketch-400-latin.woff2 +0 -0
- package/engine/fonts/CabinSketch-700-latin.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-italic-latin-ext.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-italic-latin.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-normal-latin-ext.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-normal-latin.woff2 +0 -0
- package/engine/fonts/Inter-400-latin-ext.woff2 +0 -0
- package/engine/fonts/Inter-400-latin.woff2 +0 -0
- package/engine/fonts/JetBrainsMono-400-latin-ext.woff2 +0 -0
- package/engine/fonts/JetBrainsMono-400-latin.woff2 +0 -0
- package/engine/fonts/Kalam-400-latin-ext.woff2 +0 -0
- package/engine/fonts/Kalam-400-latin.woff2 +0 -0
- package/engine/fonts/Kalam-700-latin-ext.woff2 +0 -0
- package/engine/fonts/Kalam-700-latin.woff2 +0 -0
- package/engine/fonts/NotoSansDevanagari-400.ttf +0 -0
- package/engine/fonts/NotoSansDevanagari-700.ttf +0 -0
- package/engine/fonts/PatrickHand-400-latin-ext.woff2 +0 -0
- package/engine/fonts/PatrickHand-400-latin.woff2 +0 -0
- package/engine/fonts/PlusJakartaSans-600-latin-ext.woff2 +0 -0
- package/engine/fonts/PlusJakartaSans-600-latin.woff2 +0 -0
- package/engine/fonts/SpaceGrotesk-500-latin-ext.woff2 +0 -0
- package/engine/fonts/SpaceGrotesk-500-latin.woff2 +0 -0
- package/engine/fonts/fonts.json +216 -0
- package/engine/fonts/licenses/ArchitectsDaughter-OFL.txt +93 -0
- package/engine/fonts/licenses/CabinSketch-OFL.txt +93 -0
- package/engine/fonts/licenses/InstrumentSerif-OFL.txt +93 -0
- package/engine/fonts/licenses/Inter-OFL.txt +93 -0
- package/engine/fonts/licenses/JetBrainsMono-OFL.txt +93 -0
- package/engine/fonts/licenses/Kalam-OFL.txt +93 -0
- package/engine/fonts/licenses/NotoSansDevanagari-OFL.txt +118 -0
- package/engine/fonts/licenses/PatrickHand-OFL.txt +93 -0
- package/engine/fonts/licenses/PlusJakartaSans-OFL.txt +93 -0
- package/engine/fonts/licenses/SpaceGrotesk-OFL.txt +93 -0
- package/engine/package-lock.json +1201 -0
- package/engine/package.json +67 -0
- package/engine/scripts/build-icons.mjs +74 -0
- package/engine/scripts/fetch-fonts.mjs +68 -0
- package/engine/skills/explainroo/SKILL.md +51 -0
- package/engine/src/align.js +357 -0
- package/engine/src/browser.js +121 -0
- package/engine/src/capture.js +315 -0
- package/engine/src/chapters.js +32 -0
- package/engine/src/cli.js +421 -0
- package/engine/src/clips.js +19 -0
- package/engine/src/elevenlabs.js +90 -0
- package/engine/src/env.js +16 -0
- package/engine/src/export.js +187 -0
- package/engine/src/ffmpeg.js +103 -0
- package/engine/src/fonts.js +86 -0
- package/engine/src/g2p.py +76 -0
- package/engine/src/images.js +151 -0
- package/engine/src/licenses/misaki-Apache-2.0.txt +201 -0
- package/engine/src/math.js +83 -0
- package/engine/src/models.js +161 -0
- package/engine/src/phonemes.js +162 -0
- package/engine/src/pipeline.js +63 -0
- package/engine/src/project.js +331 -0
- package/engine/src/qa.js +186 -0
- package/engine/src/recordings.js +89 -0
- package/engine/src/render.js +156 -0
- package/engine/src/script.js +266 -0
- package/engine/src/server.js +288 -0
- package/engine/src/subtitles.js +78 -0
- package/engine/src/timeline.js +55 -0
- package/engine/src/voice.js +240 -0
- package/engine/src/wav.js +98 -0
- package/engine/templates/starter/scenes.js +31 -0
- package/engine/templates/starter/script.md +14 -0
- package/engine/test/align.test.js +108 -0
- package/engine/test/brand.test.js +41 -0
- package/engine/test/browser.test.js +89 -0
- package/engine/test/camera-browser.test.js +225 -0
- package/engine/test/caption-phrases.test.js +35 -0
- package/engine/test/capture-browser.test.js +90 -0
- package/engine/test/capture-fixture.js +46 -0
- package/engine/test/capture.test.js +62 -0
- package/engine/test/chapters.test.js +41 -0
- package/engine/test/cjk-browser.test.js +101 -0
- package/engine/test/cjk.test.js +232 -0
- package/engine/test/cli-exit.test.js +25 -0
- package/engine/test/cli.test.js +116 -0
- package/engine/test/clips-browser.test.js +125 -0
- package/engine/test/clips.test.js +67 -0
- package/engine/test/code-morph-browser.test.js +99 -0
- package/engine/test/code-morph.test.js +110 -0
- package/engine/test/contrast-browser.test.js +63 -0
- package/engine/test/contrast.test.js +80 -0
- package/engine/test/director.test.js +316 -0
- package/engine/test/engine-pure.test.js +29 -0
- package/engine/test/export-browser.test.js +224 -0
- package/engine/test/export.test.js +96 -0
- package/engine/test/fixtures/capture.html +55 -0
- package/engine/test/formats-pace.test.js +104 -0
- package/engine/test/languages-browser.test.js +78 -0
- package/engine/test/languages.test.js +140 -0
- package/engine/test/looks-browser.test.js +109 -0
- package/engine/test/looks-preview.test.js +57 -0
- package/engine/test/looks.test.js +130 -0
- package/engine/test/math-browser.test.js +114 -0
- package/engine/test/math.test.js +54 -0
- package/engine/test/multi-size-browser.test.js +133 -0
- package/engine/test/multi-size.test.js +116 -0
- package/engine/test/phonemes.test.js +92 -0
- package/engine/test/readability-browser.test.js +36 -0
- package/engine/test/readability.test.js +20 -0
- package/engine/test/render-options.test.js +52 -0
- package/engine/test/script.test.js +67 -0
- package/engine/test/server.test.js +256 -0
- package/engine/test/stills-browser.test.js +70 -0
- package/engine/test/subtitles.test.js +83 -0
- package/engine/test/timeline.test.js +31 -0
- package/engine/test/transparent-browser.test.js +123 -0
- package/engine/test/ui-kit.test.js +96 -0
- package/engine/test/upload-browser.test.js +55 -0
- package/engine/test/voice-providers.test.js +338 -0
- package/lib/host.mjs +480 -0
- package/manifest.json +54 -0
- package/package.json +8 -4
- package/skills/biutalk/SKILL.md +21 -0
- package/studio/app.js +209 -0
- package/studio/assert-panel-permit.mjs +67 -0
- package/studio/composer.css +354 -0
- package/studio/composer.js +169 -0
- package/studio/index.html +82 -0
- package/studio/looks/blueprint.svg +21 -0
- package/studio/looks/chalk.svg +15 -0
- package/studio/looks/clean.svg +20 -0
- package/studio/looks/editorial.svg +18 -0
- package/studio/looks/midnight.svg +17 -0
- package/studio/looks/paper.svg +11 -0
- package/studio/select-menu.js +268 -0
- package/studio/styles.css +4 -0
- package/README.md +0 -3
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Finds a Chrome or Chromium binary and runs the engine page headless.
|
|
2
|
+
// Every browser started here is closed again, also on errors and Ctrl+C.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
// Where "npx playwright install" puts browsers on each system.
|
|
8
|
+
function playwrightBase() {
|
|
9
|
+
if (process.env.PLAYWRIGHT_BROWSERS_PATH) return process.env.PLAYWRIGHT_BROWSERS_PATH;
|
|
10
|
+
if (process.platform === 'win32') return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'ms-playwright');
|
|
11
|
+
if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Caches', 'ms-playwright');
|
|
12
|
+
return path.join(os.homedir(), '.cache', 'ms-playwright');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function playwrightCandidates() {
|
|
16
|
+
const base = playwrightBase();
|
|
17
|
+
if (!fs.existsSync(base)) return [];
|
|
18
|
+
const dirs = fs.readdirSync(base)
|
|
19
|
+
.filter((d) => /^chromium(_headless_shell)?-\d+$/.test(d))
|
|
20
|
+
.sort((a, b) => Number(b.split('-').pop()) - Number(a.split('-').pop()) || (a.includes('headless') ? -1 : 1));
|
|
21
|
+
const out = [];
|
|
22
|
+
for (const d of dirs) {
|
|
23
|
+
const root = path.join(base, d);
|
|
24
|
+
for (const sub of fs.readdirSync(root)) {
|
|
25
|
+
for (const bin of ['headless_shell', 'chrome', 'Chromium.app/Contents/MacOS/Chromium', 'chrome-headless-shell', 'headless_shell.exe', 'chrome.exe', 'chrome-headless-shell.exe']) {
|
|
26
|
+
out.push(path.join(root, sub, bin));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function findChrome() {
|
|
34
|
+
const env = process.env.EXPLAINROO_CHROME || process.env.CHROME_PATH;
|
|
35
|
+
if (env) {
|
|
36
|
+
if (!fs.existsSync(env)) throw new Error(`EXPLAINROO_CHROME points to ${env}, which does not exist`);
|
|
37
|
+
return env;
|
|
38
|
+
}
|
|
39
|
+
const system = process.platform === 'darwin'
|
|
40
|
+
? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium']
|
|
41
|
+
: process.platform === 'win32'
|
|
42
|
+
? [
|
|
43
|
+
path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Google/Chrome/Application/chrome.exe'),
|
|
44
|
+
path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Google/Chrome/Application/chrome.exe'),
|
|
45
|
+
path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google/Chrome/Application/chrome.exe'),
|
|
46
|
+
path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Microsoft/Edge/Application/msedge.exe'),
|
|
47
|
+
path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Microsoft/Edge/Application/msedge.exe'),
|
|
48
|
+
]
|
|
49
|
+
: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium'];
|
|
50
|
+
for (const p of [...playwrightCandidates(), ...system]) {
|
|
51
|
+
if (fs.existsSync(p)) return p;
|
|
52
|
+
}
|
|
53
|
+
throw new Error('no Chrome or Chromium found. Install Google Chrome, or run "npx playwright install chromium-headless-shell", or set EXPLAINROO_CHROME.');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const open = new Set();
|
|
57
|
+
let hooked = false;
|
|
58
|
+
function hookExit() {
|
|
59
|
+
if (hooked) return;
|
|
60
|
+
hooked = true;
|
|
61
|
+
const closeAll = async () => {
|
|
62
|
+
await Promise.allSettled([...open].map((b) => b.close()));
|
|
63
|
+
};
|
|
64
|
+
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
65
|
+
process.once(sig, async () => {
|
|
66
|
+
await closeAll();
|
|
67
|
+
process.exit(130);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function launch() {
|
|
73
|
+
const { chromium } = await import('playwright-core');
|
|
74
|
+
hookExit();
|
|
75
|
+
const args = ['--no-sandbox', '--disable-dev-shm-usage', '--hide-scrollbars', '--mute-audio', '--autoplay-policy=no-user-gesture-required', '--font-render-hinting=none'];
|
|
76
|
+
const browser = await chromium.launch({ executablePath: findChrome(), headless: true, args });
|
|
77
|
+
open.add(browser);
|
|
78
|
+
const origClose = browser.close.bind(browser);
|
|
79
|
+
browser.close = async () => {
|
|
80
|
+
open.delete(browser);
|
|
81
|
+
await origClose().catch(() => {});
|
|
82
|
+
};
|
|
83
|
+
return browser;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Opens the render page and waits until the engine has loaded fonts, icons,
|
|
87
|
+
// images and the scenes module. Throws with the page's error if boot fails.
|
|
88
|
+
export async function openEngine(browser, serverUrl, { scale = 1, transparent = false, onConsole, timeout = 30000 } = {}) {
|
|
89
|
+
let page;
|
|
90
|
+
let errors;
|
|
91
|
+
// A busy machine sometimes leaves the first page load hanging, or loads
|
|
92
|
+
// the page without its scripts. A fresh page almost always loads, so either
|
|
93
|
+
// case is tried once more.
|
|
94
|
+
for (let attempt = 1; ; attempt++) {
|
|
95
|
+
page = await browser.newPage({ viewport: { width: 800, height: 600 }, deviceScaleFactor: 1 });
|
|
96
|
+
errors = [];
|
|
97
|
+
page.on('pageerror', (e) => errors.push(e));
|
|
98
|
+
page.on('console', (m) => {
|
|
99
|
+
if (onConsole) onConsole(m.type(), m.text());
|
|
100
|
+
});
|
|
101
|
+
try {
|
|
102
|
+
await page.goto(`${serverUrl}/frame.html?scale=${scale}${transparent ? '&transparent=1' : ''}`, { waitUntil: 'load', timeout });
|
|
103
|
+
if (await page.evaluate(() => window.explainrooReady !== undefined)) break;
|
|
104
|
+
throw Object.assign(new Error('the engine page loaded, but its scripts did not'), { name: 'ScriptsMissing' });
|
|
105
|
+
} catch (e) {
|
|
106
|
+
await page.close().catch(() => {});
|
|
107
|
+
if (attempt === 2 || !['TimeoutError', 'ScriptsMissing'].includes(e.name)) throw e;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const boot = await page.evaluate(async () => {
|
|
111
|
+
try {
|
|
112
|
+
await window.explainrooReady;
|
|
113
|
+
return { ok: true };
|
|
114
|
+
} catch (e) {
|
|
115
|
+
return { ok: false, message: e && e.message ? e.message : String(e), stack: e && e.stack };
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
if (!boot.ok) throw new Error(`engine failed to start: ${boot.message}`);
|
|
119
|
+
if (errors.length) throw new Error(`engine page error: ${errors[0].message}`);
|
|
120
|
+
return page;
|
|
121
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { launch } from './browser.js';
|
|
4
|
+
import { ProjectError, findProjectDir } from './project.js';
|
|
5
|
+
|
|
6
|
+
const BUILT_IN_FONTS = new Set(JSON.parse(fs.readFileSync(new URL('../fonts/fonts.json', import.meta.url), 'utf8')).map((f) => f.family));
|
|
7
|
+
|
|
8
|
+
export function validateUrl(value) {
|
|
9
|
+
let url;
|
|
10
|
+
try { url = new URL(value); } catch {}
|
|
11
|
+
if (!url || !['http:', 'https:'].includes(url.protocol) || ['.', '..'].includes(url.hostname)) {
|
|
12
|
+
throw new ProjectError('capture needs an http:// or https:// URL.');
|
|
13
|
+
}
|
|
14
|
+
if (url.username || url.password) throw new ProjectError('capture does not log in. Remove the username and password from the URL.');
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function isGoogleFont(value, hostCheck = (host) => host === 'fonts.gstatic.com') {
|
|
19
|
+
try {
|
|
20
|
+
const url = new URL(value);
|
|
21
|
+
return ['http:', 'https:'].includes(url.protocol) && hostCheck(url.hostname);
|
|
22
|
+
} catch { return false; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function pickColors(samples, exclude = []) {
|
|
26
|
+
const totals = new Map();
|
|
27
|
+
for (const { color, area = 1 } of samples) {
|
|
28
|
+
if (!/^#[0-9a-f]{6}$/i.test(color) || area <= 0) continue;
|
|
29
|
+
const key = color.toLowerCase();
|
|
30
|
+
const item = totals.get(key) || { color: key, area: 0, count: 0 };
|
|
31
|
+
item.area += area;
|
|
32
|
+
item.count++;
|
|
33
|
+
totals.set(key, item);
|
|
34
|
+
}
|
|
35
|
+
const saturated = (hex) => {
|
|
36
|
+
const rgb = hex.slice(1).match(/../g).map((n) => parseInt(n, 16) / 255);
|
|
37
|
+
const hi = Math.max(...rgb), lo = Math.min(...rgb);
|
|
38
|
+
return hi > 0.15 && lo < 0.9 && hi - lo > 0.12 && (hi - lo) / hi > 0.25;
|
|
39
|
+
};
|
|
40
|
+
const ranked = [...totals.values()].sort((a, b) => b.area * b.count - a.area * a.count || a.color.localeCompare(b.color));
|
|
41
|
+
const sum = [...totals.values()].reduce((n, x) => n + x.area, 0);
|
|
42
|
+
return {
|
|
43
|
+
accent: ranked.find((x) => saturated(x.color))?.color || null,
|
|
44
|
+
other: [...totals.values()].filter((x) => !exclude.includes(x.color)).sort((a, b) => b.area - a.area || a.color.localeCompare(b.color)).slice(0, 6)
|
|
45
|
+
.map((x) => ({ color: x.color, share: Math.round(x.area / sum * 1000) / 1000 })),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function rankLogos(candidates) {
|
|
50
|
+
const score = (c) => c.type === 'svg' ? (c.kind === 'brand' ? 4 : 3) : (c.kind === 'og' ? 1 : 2);
|
|
51
|
+
const seen = new Set();
|
|
52
|
+
return candidates.filter((c) => ['svg', 'png'].includes(c.type))
|
|
53
|
+
.sort((a, b) => score(b) - score(a) || b.area - a.area)
|
|
54
|
+
.filter((c) => {
|
|
55
|
+
const key = c.url || c.svg;
|
|
56
|
+
if (seen.has(key)) return false;
|
|
57
|
+
seen.add(key);
|
|
58
|
+
return true;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// This runs in the visited page. Read computed styles so CSS variables and
|
|
63
|
+
// inherited colors agree with the screenshots.
|
|
64
|
+
function inspectPage({ stylesheets, loadedFonts }) {
|
|
65
|
+
const clean = (v) => (v || '').trim();
|
|
66
|
+
const family = (v) => clean(v.split(',')[0]).replace(/^['"]|['"]$/g, '');
|
|
67
|
+
const style = (el) => getComputedStyle(el);
|
|
68
|
+
const visible = (el) => {
|
|
69
|
+
const r = el.getBoundingClientRect(), c = style(el);
|
|
70
|
+
return r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < 8000 && c.display !== 'none' && c.visibility === 'visible' && Number(c.opacity) > 0 && el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
|
|
71
|
+
};
|
|
72
|
+
const elements = [...document.querySelectorAll('body *')].filter(visible);
|
|
73
|
+
const select = (q) => [...document.querySelectorAll(q)].filter(visible);
|
|
74
|
+
const labels = (els, attr) => [...new Set(els.map((el) => clean(attr ? el.getAttribute(attr) : el.innerText || el.textContent)).filter(Boolean))].slice(0, 40);
|
|
75
|
+
const canvas = document.createElement('canvas');
|
|
76
|
+
canvas.width = canvas.height = 1;
|
|
77
|
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
|
78
|
+
const hex = (value) => {
|
|
79
|
+
ctx.clearRect(0, 0, 1, 1);
|
|
80
|
+
ctx.fillStyle = value;
|
|
81
|
+
ctx.fillRect(0, 0, 1, 1);
|
|
82
|
+
const rgb = ctx.getImageData(0, 0, 1, 1).data;
|
|
83
|
+
return rgb[3] ? '#' + [...rgb].slice(0, 3).map((n) => n.toString(16).padStart(2, '0')).join('') : null;
|
|
84
|
+
};
|
|
85
|
+
const area = (el) => {
|
|
86
|
+
const r = el.getBoundingClientRect();
|
|
87
|
+
return Math.max(0, Math.min(r.right, innerWidth) - Math.max(0, r.left)) * Math.max(0, Math.min(r.bottom, 8000) - Math.max(0, r.top));
|
|
88
|
+
};
|
|
89
|
+
const buttons = elements.filter((el) => el.matches('button, input[type=submit], input[type=button], [role=button]') ||
|
|
90
|
+
(el.matches('a') && (/btn|button/i.test(el.className) || (hex(style(el).backgroundColor) && parseFloat(style(el).paddingLeft) >= 8))));
|
|
91
|
+
const headings = select('h1, h2, h3, h4, h5, h6');
|
|
92
|
+
const links = select('a');
|
|
93
|
+
const body = document.body;
|
|
94
|
+
const colors = {
|
|
95
|
+
background: hex(style(body).backgroundColor) || hex(style(document.documentElement).backgroundColor) || '#ffffff',
|
|
96
|
+
text: hex(style(body).color),
|
|
97
|
+
heading: headings[0] ? hex(style(headings[0]).color) : null,
|
|
98
|
+
link: links[0] ? hex(style(links[0]).color) : null,
|
|
99
|
+
};
|
|
100
|
+
const samples = elements.flatMap((el) => {
|
|
101
|
+
const c = style(el), a = area(el);
|
|
102
|
+
const r = el.getBoundingClientRect();
|
|
103
|
+
return [{ color: hex(c.backgroundColor), area: a }, { color: hex(c.color), area: el.childNodes.length && [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim()) ? a : 0 },
|
|
104
|
+
{ color: hex(c.borderTopColor), area: parseFloat(c.borderTopWidth) * r.width }, { color: hex(c.borderBottomColor), area: parseFloat(c.borderBottomWidth) * r.width },
|
|
105
|
+
{ color: hex(c.borderLeftColor), area: parseFloat(c.borderLeftWidth) * r.height }, { color: hex(c.borderRightColor), area: parseFloat(c.borderRightWidth) * r.height }];
|
|
106
|
+
});
|
|
107
|
+
samples.push({ color: colors.background, area: innerWidth * Math.min(8000, document.documentElement.scrollHeight) });
|
|
108
|
+
const buttonSamples = buttons.map((el) => ({ color: hex(style(el).backgroundColor), area: area(el) }));
|
|
109
|
+
const fonts = { body: family(style(body).fontFamily), headings: [...new Set(headings.map((el) => family(style(el).fontFamily)))], buttons: [...new Set(buttons.map((el) => family(style(el).fontFamily)))], families: [] };
|
|
110
|
+
const names = [...new Set([fonts.body, ...fonts.headings, ...fonts.buttons])].filter(Boolean);
|
|
111
|
+
const used = [body, ...elements];
|
|
112
|
+
for (const name of names) {
|
|
113
|
+
const uses = used.filter((el) => family(style(el).fontFamily) === name).map((el) => ({ weight: Number(style(el).fontWeight), style: style(el).fontStyle }));
|
|
114
|
+
fonts.families.push({ family: name, uses: [...new Map(uses.map((u) => [JSON.stringify(u), u])).values()], faces: [], sources: [] });
|
|
115
|
+
}
|
|
116
|
+
for (const face of document.fonts) {
|
|
117
|
+
const f = fonts.families.find((f) => f.family === family(face.family));
|
|
118
|
+
if (f) f.faces.push({ weight: face.weight, style: face.style, status: face.status });
|
|
119
|
+
}
|
|
120
|
+
const loaded = new Set([...performance.getEntriesByType('resource').map((r) => r.name), ...loadedFonts]);
|
|
121
|
+
const readRules = (rules, base) => {
|
|
122
|
+
for (const rule of rules) {
|
|
123
|
+
if (rule.type === CSSRule.FONT_FACE_RULE) {
|
|
124
|
+
const f = fonts.families.find((f) => f.family === family(rule.style.getPropertyValue('font-family')));
|
|
125
|
+
if (!f) continue;
|
|
126
|
+
for (const match of rule.style.getPropertyValue('src').matchAll(/url\(\s*['"]?([^'"\s)]+)['"]?\s*\)/g)) {
|
|
127
|
+
const url = new URL(match[1], base).href;
|
|
128
|
+
const weight = rule.style.getPropertyValue('font-weight').replace(/normal/g, '400').replace(/bold/g, '700') || '400';
|
|
129
|
+
const source = { url, weight, style: rule.style.getPropertyValue('font-style') || 'normal', loaded: loaded.has(url) };
|
|
130
|
+
if (!f.sources.some((s) => JSON.stringify(s) === JSON.stringify(source))) f.sources.push(source);
|
|
131
|
+
}
|
|
132
|
+
} else if (rule.styleSheet) {
|
|
133
|
+
try { readRules(rule.styleSheet.cssRules, rule.styleSheet.href || base); } catch {}
|
|
134
|
+
} else if (rule.cssRules) readRules(rule.cssRules, base);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
for (const sheet of document.styleSheets) {
|
|
138
|
+
try { readRules(sheet.cssRules, sheet.href || document.baseURI); } catch {}
|
|
139
|
+
}
|
|
140
|
+
// Cross-origin stylesheets may hide their CSSOM. Their already loaded
|
|
141
|
+
// response bodies still let us match font URLs to families without a fetch.
|
|
142
|
+
for (const { css, url } of stylesheets) {
|
|
143
|
+
try {
|
|
144
|
+
const sheet = new CSSStyleSheet();
|
|
145
|
+
sheet.replaceSync(css);
|
|
146
|
+
readRules(sheet.cssRules, url);
|
|
147
|
+
} catch {}
|
|
148
|
+
}
|
|
149
|
+
const siteName = clean(document.querySelector('meta[property="og:site_name"]')?.content) || location.hostname.replace(/^www\./, '').split('.')[0];
|
|
150
|
+
const candidates = [];
|
|
151
|
+
const firstHome = [...document.querySelectorAll('a[href]')].find((el) => {
|
|
152
|
+
try { const u = new URL(el.href); return u.origin === location.origin && u.pathname === '/'; } catch { return false; }
|
|
153
|
+
});
|
|
154
|
+
const type = (url, mime = '') => /svg/i.test(mime) || /\.svg(?:[?#]|$)|^data:image\/svg\+xml/i.test(url) ? 'svg' : /png/i.test(mime) || /\.png(?:[?#]|$)|^data:image\/png/i.test(url) ? 'png' : null;
|
|
155
|
+
for (const el of select('header svg, header img, nav svg, nav img, [role=banner] svg, [role=banner] img, a svg, a img')) {
|
|
156
|
+
if (!el.closest('header, nav, [role=banner]') && !firstHome?.contains(el)) continue;
|
|
157
|
+
const parent = el.closest('a');
|
|
158
|
+
const identity = [el, parent].filter(Boolean).flatMap((n) => ['id', 'class', 'alt', 'aria-label', 'src'].map((a) => n.getAttribute(a) || '')).join(' ').toLowerCase();
|
|
159
|
+
if (!identity.includes('logo') && !(siteName.length > 1 && identity.includes(siteName.toLowerCase()))) continue;
|
|
160
|
+
const c = { kind: 'brand', area: area(el), color: style(el).color };
|
|
161
|
+
if (el.tagName.toLowerCase() === 'svg') {
|
|
162
|
+
const copy = el.cloneNode(true);
|
|
163
|
+
copy.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
|
164
|
+
const copies = [copy, ...copy.querySelectorAll('*')];
|
|
165
|
+
[el, ...el.querySelectorAll('*')].forEach((original, i) => {
|
|
166
|
+
const target = copies[i], computed = style(original);
|
|
167
|
+
for (const attr of target.getAttributeNames()) target.setAttribute(attr, target.getAttribute(attr).replace(/currentColor/gi, computed.color));
|
|
168
|
+
for (const prop of ['fill', 'stroke', 'color']) target.style.setProperty(prop, computed[prop].replace(/url\(["']?[^)"']*#([^)'" ]+)["']?\)/g, 'url(#$1)'));
|
|
169
|
+
});
|
|
170
|
+
candidates.push({ ...c, type: 'svg', svg: new XMLSerializer().serializeToString(copy) });
|
|
171
|
+
} else candidates.push({ ...c, type: type(el.currentSrc || el.src), url: el.currentSrc || el.src });
|
|
172
|
+
}
|
|
173
|
+
for (const el of document.querySelectorAll('link[rel~="icon"], link[rel="apple-touch-icon"], meta[property="og:image"]')) {
|
|
174
|
+
const url = el.href || new URL(el.content, document.baseURI).href;
|
|
175
|
+
const sizes = (el.getAttribute('sizes') || '').match(/(\d+)x(\d+)/);
|
|
176
|
+
candidates.push({ kind: el.tagName === 'META' ? 'og' : 'icon', type: type(url, el.type), url, area: sizes ? Number(sizes[1]) * Number(sizes[2]) : 0 });
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
url: location.href, title: document.title, description: document.querySelector('meta[name="description"]')?.content || null,
|
|
180
|
+
themeColor: hex(document.querySelector('meta[name="theme-color"]')?.content || 'transparent'),
|
|
181
|
+
colors, samples, buttonSamples, fonts, candidates,
|
|
182
|
+
text: { h1: labels(select('h1')), h2: labels(select('h2')), navigation: labels(select('nav a, [role=navigation] a')), buttons: [...new Set(buttons.map((el) => clean(el.value || el.innerText || el.getAttribute('aria-label'))).filter(Boolean))].slice(0, 40), labels: labels(select('label')), placeholders: labels(select('input[placeholder], textarea[placeholder]'), 'placeholder') },
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function loadPage(page, url) {
|
|
187
|
+
try {
|
|
188
|
+
const response = await page.goto(url, { waitUntil: 'load', timeout: 30000 });
|
|
189
|
+
if (!response || !response.ok()) throw new Error('page returned an error');
|
|
190
|
+
validateUrl(page.url());
|
|
191
|
+
// Background polling may never stop. Give it time to settle, then capture
|
|
192
|
+
// the loaded page; fonts still have to finish within the same limit.
|
|
193
|
+
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {});
|
|
194
|
+
await page.waitForFunction(() => document.fonts.status === 'loaded', { timeout: 10000 });
|
|
195
|
+
} catch {
|
|
196
|
+
throw new ProjectError('the page did not load. Check the URL and try capture again.');
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function screenshots(page, dir, prefix = '') {
|
|
201
|
+
await page.screenshot({ path: path.join(dir, prefix ? 'mobile.png' : 'page.png'), timeout: 15000 });
|
|
202
|
+
const height = await page.evaluate(() => Math.min(8000, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, innerHeight)));
|
|
203
|
+
await page.screenshot({ path: path.join(dir, `${prefix}full.png`), fullPage: true, clip: { x: 0, y: 0, width: page.viewportSize().width, height }, timeout: 15000 });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function download(context, url) {
|
|
207
|
+
if (/^data:/i.test(url)) {
|
|
208
|
+
const match = /^data:image\/(svg\+xml|png)(;base64)?,([\s\S]*)$/i.exec(url);
|
|
209
|
+
if (!match) throw new Error('unsupported image');
|
|
210
|
+
return Buffer.from(match[2] ? match[3] : decodeURIComponent(match[3]), match[2] ? 'base64' : 'utf8');
|
|
211
|
+
}
|
|
212
|
+
validateUrl(url);
|
|
213
|
+
const response = await context.request.get(url, { timeout: 15000 });
|
|
214
|
+
if (!response.ok()) throw new Error('file did not load');
|
|
215
|
+
return response.body();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export async function capture(project, value, { mobile = false, googleHostCheck } = {}) {
|
|
219
|
+
const url = validateUrl(value);
|
|
220
|
+
const projectDir = findProjectDir(typeof project === 'string' ? project : project?.dir);
|
|
221
|
+
const host = url.hostname.replace(/[:[\]]/g, '_');
|
|
222
|
+
const relative = `assets/capture/${host}`;
|
|
223
|
+
const dest = path.join(projectDir, relative);
|
|
224
|
+
for (const folder of ['assets', 'assets/capture', relative]) {
|
|
225
|
+
const file = path.join(projectDir, folder);
|
|
226
|
+
const stat = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
227
|
+
if (stat && !stat.isDirectory()) throw new ProjectError(`${folder} must be a folder, not a link or file. Move it and try capture again.`);
|
|
228
|
+
}
|
|
229
|
+
const browser = await launch();
|
|
230
|
+
let temp;
|
|
231
|
+
try {
|
|
232
|
+
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 2 });
|
|
233
|
+
const page = await context.newPage();
|
|
234
|
+
const cssResponses = [];
|
|
235
|
+
const loadedFonts = [];
|
|
236
|
+
page.on('response', (response) => {
|
|
237
|
+
if (response.request().resourceType() === 'stylesheet') {
|
|
238
|
+
cssResponses.push(response.text().then((css) => ({ css, url: response.url() })).catch(() => null));
|
|
239
|
+
}
|
|
240
|
+
if (response.request().resourceType() === 'font' && response.ok()) loadedFonts.push(response.url());
|
|
241
|
+
});
|
|
242
|
+
await loadPage(page, url.href);
|
|
243
|
+
const stylesheets = (await Promise.all(cssResponses)).filter(Boolean);
|
|
244
|
+
const data = await page.evaluate(inspectPage, { stylesheets, loadedFonts });
|
|
245
|
+
const { samples, buttonSamples, candidates, ...result } = data;
|
|
246
|
+
result.colors.accent = pickColors(buttonSamples).accent;
|
|
247
|
+
result.colors.other = pickColors(samples, Object.values(result.colors).filter(Boolean)).other;
|
|
248
|
+
result.brand = {};
|
|
249
|
+
for (const [key, val] of Object.entries({ accent: result.colors.accent, background: result.colors.background, ink: result.colors.text, font: result.fonts.body })) {
|
|
250
|
+
if (val) result.brand[key] = val;
|
|
251
|
+
}
|
|
252
|
+
result.notes = [];
|
|
253
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
254
|
+
temp = fs.mkdtempSync(path.join(path.dirname(dest), `.${host}-`));
|
|
255
|
+
await screenshots(page, temp);
|
|
256
|
+
result.logo = { picked: null, candidates: [] };
|
|
257
|
+
const logos = [];
|
|
258
|
+
for (const candidate of candidates) {
|
|
259
|
+
try {
|
|
260
|
+
const bytes = candidate.svg ? Buffer.from(candidate.svg) : await download(context, candidate.url);
|
|
261
|
+
const png = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
|
|
262
|
+
const type = png ? 'png' : /<svg[\s>]/i.test(bytes.toString()) ? 'svg' : null;
|
|
263
|
+
if (type) logos.push({ ...candidate, bytes, type, area: png && bytes.length >= 24 ? bytes.readUInt32BE(16) * bytes.readUInt32BE(20) : candidate.area });
|
|
264
|
+
} catch { result.notes.push(`Could not save a logo from ${candidate.url || 'the page'}.`); }
|
|
265
|
+
}
|
|
266
|
+
for (const candidate of rankLogos(logos).slice(0, 3)) {
|
|
267
|
+
const n = result.logo.candidates.length;
|
|
268
|
+
const file = `${relative}/logo${n ? '-' + (n + 1) : ''}.${candidate.type}`;
|
|
269
|
+
fs.writeFileSync(path.join(temp, path.basename(file)), candidate.bytes);
|
|
270
|
+
result.logo.candidates.push({ file, source: candidate.url || 'inline SVG', kind: candidate.kind });
|
|
271
|
+
}
|
|
272
|
+
result.logo.picked = result.logo.candidates[0]?.file || null;
|
|
273
|
+
if (result.logo.picked) result.brand.logo = result.logo.picked;
|
|
274
|
+
const savedFonts = [];
|
|
275
|
+
for (const f of result.fonts.families) {
|
|
276
|
+
if (BUILT_IN_FONTS.has(f.family)) {
|
|
277
|
+
result.notes.push(`${f.family} is built into explainroo. It needs no font files.`);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
let saved = false;
|
|
281
|
+
for (const source of f.sources) {
|
|
282
|
+
const range = source.weight.split(/\s+/).map(Number);
|
|
283
|
+
const used = f.uses.some((u) => u.weight >= range[0] && u.weight <= range.at(-1) && u.style === source.style);
|
|
284
|
+
if (!source.loaded || !used || !isGoogleFont(source.url, googleHostCheck)) continue;
|
|
285
|
+
try {
|
|
286
|
+
const bytes = await download(context, source.url);
|
|
287
|
+
const ext = /\.(woff2?|ttf|otf)$/i.exec(new URL(source.url).pathname)?.[0] || '.woff2';
|
|
288
|
+
const name = f.family.replace(/[^a-z0-9-]/gi, '-') || 'font';
|
|
289
|
+
const file = `${relative}/fonts/${name}-${source.weight.replace(/\s+/g, '-')}-${savedFonts.length + 1}${ext}`;
|
|
290
|
+
fs.mkdirSync(path.join(temp, 'fonts'), { recursive: true });
|
|
291
|
+
fs.writeFileSync(path.join(temp, 'fonts', path.basename(file)), bytes);
|
|
292
|
+
savedFonts.push({ family: f.family, src: file, weight: range.length === 1 ? range[0] : source.weight, style: source.style });
|
|
293
|
+
saved = true;
|
|
294
|
+
} catch { result.notes.push(`Could not save ${f.family}. Get the font files and check the license.`); }
|
|
295
|
+
}
|
|
296
|
+
if (!saved) result.notes.push(`${f.family}: get the font files and check the license. Copy the license file next to them.`);
|
|
297
|
+
}
|
|
298
|
+
if (mobile) {
|
|
299
|
+
const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
|
|
300
|
+
const mobilePage = await phone.newPage();
|
|
301
|
+
await loadPage(mobilePage, url.href);
|
|
302
|
+
await screenshots(mobilePage, temp, 'mobile-');
|
|
303
|
+
}
|
|
304
|
+
result.suggestion = { brand: result.brand, fonts: savedFonts };
|
|
305
|
+
const files = fs.readdirSync(temp).filter((name) => name !== 'fonts').map((name) => `${relative}/${name}`);
|
|
306
|
+
result.files = [...files, ...savedFonts.map((f) => f.src), `${relative}/capture.json`].sort();
|
|
307
|
+
fs.writeFileSync(path.join(temp, 'capture.json'), JSON.stringify(result, null, 2) + '\n');
|
|
308
|
+
fs.rmSync(dest, { recursive: true, force: true });
|
|
309
|
+
fs.renameSync(temp, dest);
|
|
310
|
+
return result;
|
|
311
|
+
} finally {
|
|
312
|
+
await browser.close();
|
|
313
|
+
if (temp) fs.rmSync(temp, { recursive: true, force: true });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Chapters share the scene boundaries used by the video.
|
|
2
|
+
export function buildChapters(timeline, title) {
|
|
3
|
+
const named = timeline.scenes.filter((s) => s.attrs?.chapter !== undefined);
|
|
4
|
+
if (!named.length) return [];
|
|
5
|
+
if (named[0] !== timeline.scenes[0]) named.unshift({ ...timeline.scenes[0], attrs: { chapter: title } });
|
|
6
|
+
return named.map((s, i) => ({ title: s.attrs.chapter, start: s.start, end: named[i + 1]?.start ?? timeline.duration, scene: s.id }));
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function chapterHints(chapters) {
|
|
10
|
+
if (!chapters.length) return [];
|
|
11
|
+
const issues = [];
|
|
12
|
+
if (chapters.length < 3) issues.push({ level: 'hint', scene: null, t: null, message: `the video has ${chapters.length} chapter${chapters.length === 1 ? '' : 's'}, and YouTube shows chapters only when there are at least 3 chapters. Name chapters in more scenes, or leave them out.` });
|
|
13
|
+
for (const c of chapters) {
|
|
14
|
+
if (c.end - c.start < 10) issues.push({ level: 'hint', scene: c.scene, t: null, message: `chapter "${c.title}" lasts ${(c.end - c.start).toFixed(1)}s, and YouTube shows chapters only when each lasts at least 10 seconds. Start it at another scene or join it with the next one.` });
|
|
15
|
+
}
|
|
16
|
+
return issues;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function toChaptersText(chapters) {
|
|
20
|
+
return chapters.map((c) => {
|
|
21
|
+
const seconds = Math.floor(c.start);
|
|
22
|
+
const minutes = Math.floor(seconds / 60);
|
|
23
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
24
|
+
const time = seconds >= 3600 ? `${Math.floor(minutes / 60)}:${pad(minutes % 60)}:${pad(seconds % 60)}` : `${minutes}:${pad(seconds % 60)}`;
|
|
25
|
+
return `${time} ${c.title}\n`;
|
|
26
|
+
}).join('');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function toChapterMetadata(chapters) {
|
|
30
|
+
const escape = (text) => String(text).replace(/[\\=;#\n]/g, '\\$&');
|
|
31
|
+
return ';FFMETADATA1\n' + chapters.map((c) => `[CHAPTER]\nTIMEBASE=1/1000\nSTART=${Math.round(c.start * 1000)}\nEND=${Math.round(c.end * 1000)}\ntitle=${escape(c.title)}\n`).join('');
|
|
32
|
+
}
|