beatsheet 0.0.0-stage → 0.2.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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/bin/beatsheet.js +14 -0
  4. package/bin/register-fallback.mjs +23 -0
  5. package/bin/resolve-fallback.mjs +83 -0
  6. package/package.json +45 -4
  7. package/player/env.d.ts +5 -0
  8. package/player/gallery-audio.ts +147 -0
  9. package/player/gallery-css.ts +144 -0
  10. package/player/gallery-detail.ts +385 -0
  11. package/player/gallery-music.ts +257 -0
  12. package/player/gallery-pick-state.ts +167 -0
  13. package/player/gallery-pick.ts +749 -0
  14. package/player/gallery-sounds.ts +137 -0
  15. package/player/gallery-state.ts +457 -0
  16. package/player/gallery.ts +612 -0
  17. package/player/index.html +49 -0
  18. package/player/main.ts +83 -0
  19. package/skill/SKILL.md +658 -0
  20. package/skill/examples/library/assets/tour/avatar-mk.svg +1 -0
  21. package/skill/examples/library/assets/tour/dashboard-insights.svg +1 -0
  22. package/skill/examples/library/assets/tour/dashboard.svg +1 -0
  23. package/skill/examples/library/assets/tour/settings.svg +1 -0
  24. package/skill/examples/library/library-tour.plan.md +32 -0
  25. package/skill/examples/library/library-tour.video.json +268 -0
  26. package/skill/reference/scene-techniques.md +306 -0
  27. package/skill/scripts/beats.ts +34 -0
  28. package/skill/scripts/catalogue.ts +120 -0
  29. package/skill/scripts/frames.ts +105 -0
  30. package/src/args.ts +344 -0
  31. package/src/cli.ts +95 -0
  32. package/src/commands.ts +812 -0
  33. package/src/default-project.config.ts +9 -0
  34. package/src/index.ts +47 -0
  35. package/src/packages.ts +17 -0
  36. package/src/paths.ts +32 -0
  37. package/src/project.ts +200 -0
  38. package/src/render/browser.ts +185 -0
  39. package/src/render/capture.ts +320 -0
  40. package/src/render/ffmpeg.ts +229 -0
  41. package/src/render/gif-info.ts +61 -0
  42. package/src/render/render.ts +220 -0
  43. package/src/samples.ts +557 -0
  44. package/src/server/api.ts +494 -0
  45. package/src/server/jobs.ts +210 -0
  46. package/src/server/security.ts +47 -0
  47. package/src/server/server.ts +191 -0
  48. package/src/server/sse.ts +76 -0
  49. package/src/server/static.ts +127 -0
  50. package/src/server/vite.ts +100 -0
  51. package/src/skill.ts +111 -0
  52. package/src/snap.ts +212 -0
  53. package/src/speech.ts +689 -0
  54. package/src/svg-text.ts +136 -0
  55. package/src/voicefx.ts +311 -0
  56. package/studio/3rdpartylicenses.txt +287 -0
  57. package/studio/favicon.ico +0 -0
  58. package/studio/icons/apple-touch-icon.png +0 -0
  59. package/studio/icons/icon-192.png +0 -0
  60. package/studio/icons/icon-512.png +0 -0
  61. package/studio/icons/icon.svg +1 -0
  62. package/studio/icons/maskable-512.png +0 -0
  63. package/studio/index.html +18 -0
  64. package/studio/main-KMYDBWZH.js +15 -0
  65. package/studio/manifest.webmanifest +17 -0
  66. package/studio/offline.html +92 -0
  67. package/studio/styles-NJ2CULOW.css +1 -0
  68. package/studio/sw.js +71 -0
@@ -0,0 +1,9 @@
1
+ import { defineProject } from '@beatsheet/core';
2
+ import { builtinScenes, defaultTheme } from '@beatsheet/scenes';
3
+
4
+ /**
5
+ * The project of a folder without beatsheet.config.ts (DEFAULT_CONFIG_PATH): the default theme and
6
+ * the built-in scenes, with that folder as the root. Its name is the folder's (projectContext treats
7
+ * an empty name as none).
8
+ */
9
+ export default defineProject({ name: '', theme: defaultTheme, scenes: builtinScenes });
package/src/index.ts ADDED
@@ -0,0 +1,47 @@
1
+ export { main } from './cli';
2
+ export { parseCli, parseFormats, parseTimes, parseList, USAGE, UsageError, type Command } from './args';
3
+ export { findConfig, loadProject, discoverProject, projectContext, videoName, CONFIG_FILE, type ProjectContext } from './project';
4
+ export { startServer, type ServerOptions, type RunningServer } from './server/server';
5
+ export { handleApi, checkDoc, videoPath, type ApiContext } from './server/api';
6
+ export { RenderJobs, SpeechJobs, type RenderJob, type RenderRunner, type SpeechJob, type SpeechRunner } from './server/jobs';
7
+ export { formatSse } from './server/sse';
8
+ export { beatsheetProjectPlugin, createPlayerVite, PROJECT_MODULE_ID } from './server/vite';
9
+ export { renderVideo, playerUrl, openPlayer, defaultStillTimes, beatStillTimes, checkTimes, settledTime, type RenderOutput } from './render/render';
10
+ export { openBridgePage, captureVideo, captureStills, collectLayoutIssues, frameTime, type BridgePage } from './render/capture';
11
+ export { encodeArgs, sheetArgs, probeMedia, parseMediaInfo, parseFrameCount } from './render/ffmpeg';
12
+ export { launchBrowser, findChromium } from './render/browser';
13
+ export { runRender, runStills, runCheck, runSpeak, runStudio, loadVideo, videoServer, validateVideo, formatLoudness, speechWarnings, type LoadedVideo, type SpeakReport } from './commands';
14
+ export {
15
+ projectSpeechPlugins,
16
+ pluginPackage,
17
+ planSpeech,
18
+ speakVideo,
19
+ speechStatus,
20
+ speechPreflight,
21
+ unusedClips,
22
+ parseWavHeader,
23
+ readWavInfo,
24
+ encodePcm16Wav,
25
+ SpeechPlanError,
26
+ type SpeechPlugins,
27
+ type SpeechPlan,
28
+ type SpeechVideo,
29
+ type WavInfo,
30
+ } from './speech';
31
+ export {
32
+ loadSamples,
33
+ samplesName,
34
+ runCheckSamples,
35
+ runStillsSamples,
36
+ formatSamplesCheck,
37
+ formatSampleLayoutIssue,
38
+ formatSampleValidationIssue,
39
+ sampleLabel,
40
+ buildLabelledSheets,
41
+ type SampleInfo,
42
+ type SamplesCheckReport,
43
+ type SampleLayoutIssue,
44
+ type SampleValidationIssue,
45
+ type SampleStillsResult,
46
+ } from './samples';
47
+ export { ASSET_PREFIX, PLAYER_BASE, SPEECH_PREFIX } from './paths';
@@ -0,0 +1,17 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import { CLI_DIR } from './paths';
4
+
5
+ /**
6
+ * The beatsheet packages a project imports that the CLI brings along: a project without its own
7
+ * install gets the CLI's copies. bin/resolve-fallback.mjs (Node) keeps a copy of this pattern.
8
+ */
9
+ export const BEATSHEET_PACKAGE = /^@beatsheet\/(core|scenes)(\/|$)/;
10
+
11
+ /** Folders of @beatsheet/core and @beatsheet/scenes as the CLI in `cliDir` resolves them. */
12
+ export function beatsheetPackageDirs(cliDir: string = CLI_DIR): { core: string; scenes: string } {
13
+ const require = createRequire(path.join(cliDir, 'package.json'));
14
+ // Each entry is <package>/src/index.ts, so the package folder is two levels up.
15
+ const dir = (name: string): string => path.dirname(path.dirname(require.resolve(name)));
16
+ return { core: dir('@beatsheet/core'), scenes: dir('@beatsheet/scenes') };
17
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import path from 'node:path';
3
+
4
+ /** packages/cli (the `beatsheet` package root). */
5
+ export const CLI_DIR: string = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..');
6
+
7
+ /** Vite root of the player page (index.html + main.ts). */
8
+ export const PLAYER_DIR: string = path.join(CLI_DIR, 'player');
9
+
10
+ /** URL prefix of the player page; Vite serves everything below it. */
11
+ export const PLAYER_BASE = '/player/';
12
+
13
+ /** URL prefix under which the project's assetsDir is served (PlayerOptions.assetBase). */
14
+ export const ASSET_PREFIX = '/project-assets/';
15
+
16
+ /** URL prefix of the narration clips: /speech/<key>.wav from the videos folder's speech/ (PlayerOptions.speechBase default). */
17
+ export const SPEECH_PREFIX = '/speech/';
18
+
19
+ /** The config of a folder without beatsheet.config.ts: the default theme and the built-in scenes. */
20
+ export const DEFAULT_CONFIG_PATH: string = path.join(CLI_DIR, 'src', 'default-project.config.ts');
21
+
22
+ /**
23
+ * The folder the user ran the command in. `npx beatsheet` inside a workspace package's subfolder
24
+ * runs with the package root as cwd; npm keeps the original in INIT_CWD, used when it lies below
25
+ * the cwd (an outer `npm run -w <pkg>` sets it above the cwd, where the cwd is right).
26
+ */
27
+ export function userCwd(env: NodeJS.ProcessEnv = process.env, cwd: string = process.cwd()): string {
28
+ const init = env.INIT_CWD;
29
+ if (!init) return cwd;
30
+ const rel = path.relative(cwd, path.resolve(init));
31
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? path.resolve(init) : cwd;
32
+ }
package/src/project.ts ADDED
@@ -0,0 +1,200 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import type { ProjectConfig } from '@beatsheet/core';
5
+ import { DEFAULT_CONFIG_PATH, userCwd } from './paths';
6
+
7
+ export const CONFIG_FILE = 'beatsheet.config.ts';
8
+ export const VIDEO_SUFFIX = '.video.json';
9
+
10
+ /** A loaded project: the config plus its folders as absolute paths. */
11
+ export interface ProjectContext {
12
+ /** beatsheet.config.ts, or DEFAULT_CONFIG_PATH for a folder without one. */
13
+ configPath: string;
14
+ /** Folder of beatsheet.config.ts (for the default project: the folder the command ran in). */
15
+ root: string;
16
+ /** False for the default project (no beatsheet.config.ts: default theme, built-in scenes). */
17
+ configured: boolean;
18
+ name: string;
19
+ videosDir: string;
20
+ assetsDir: string;
21
+ outDir: string;
22
+ config: ProjectConfig;
23
+ }
24
+
25
+ /**
26
+ * Nearest beatsheet.config.ts upward from `from` (a file or a folder). A path ending in
27
+ * .json (or an existing file) starts the search in its folder.
28
+ */
29
+ export function findConfig(from: string): string | null {
30
+ let dir = folderOf(from);
31
+ for (;;) {
32
+ const candidate = path.join(dir, CONFIG_FILE);
33
+ if (fs.existsSync(candidate)) return candidate;
34
+ const parent = path.dirname(dir);
35
+ if (parent === dir) return null;
36
+ dir = parent;
37
+ }
38
+ }
39
+
40
+ /** The folder of a path: itself for a folder, its parent for a file (or a missing path that looks like one). */
41
+ function folderOf(fileOrDir: string): string {
42
+ const p = path.resolve(fileOrDir);
43
+ const isFile = (fs.existsSync(p) && fs.statSync(p).isFile()) || (!fs.existsSync(p) && /\.[a-z0-9]+$/i.test(p));
44
+ return isFile ? path.dirname(p) : p;
45
+ }
46
+
47
+ /** Absolute folders of a project config (defaults: videos, assets, out); `root` defaults to the config's folder. */
48
+ export function projectContext(configPath: string, config: ProjectConfig, root: string = path.dirname(path.resolve(configPath))): ProjectContext {
49
+ root = path.resolve(root);
50
+ return {
51
+ configPath: path.resolve(configPath),
52
+ root,
53
+ configured: path.resolve(configPath) !== DEFAULT_CONFIG_PATH,
54
+ name: typeof config.name === 'string' && config.name ? config.name : path.basename(root),
55
+ videosDir: path.resolve(root, config.videosDir ?? 'videos'),
56
+ assetsDir: path.resolve(root, config.assetsDir ?? 'assets'),
57
+ outDir: path.resolve(root, config.outDir ?? 'out'),
58
+ config,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Imports beatsheet.config.ts in Node. The CLI registers tsx in bin/beatsheet.js, so a plain
64
+ * dynamic import handles TypeScript (Vitest transforms it the same way in tests).
65
+ */
66
+ export async function loadProject(configPath: string, root?: string): Promise<ProjectContext> {
67
+ return projectContext(configPath, await importConfig(configPath), root);
68
+ }
69
+
70
+ /** 'acme (/p/beatsheet.config.ts)', or for the default project what it is made of. */
71
+ export function describeProject(p: Pick<ProjectContext, 'name' | 'configPath' | 'configured'>): string {
72
+ return p.configured ? `${p.name} (${p.configPath})` : `${p.name} (no ${CONFIG_FILE}: default theme, built-in scenes)`;
73
+ }
74
+
75
+ /** The default export of beatsheet.config.ts; `version` (a query) makes Node import the file afresh. */
76
+ async function importConfig(configPath: string, version?: string): Promise<ProjectConfig> {
77
+ let mod: { default?: unknown };
78
+ try {
79
+ const url = pathToFileURL(path.resolve(configPath)).href;
80
+ mod = (await import(version === undefined ? url : `${url}?v=${version}`)) as { default?: unknown };
81
+ } catch (err) {
82
+ throw new Error(`Could not load ${configPath}: ${errorMessage(err)}`);
83
+ }
84
+ const config = mod.default;
85
+ if (!config || typeof config !== 'object') {
86
+ throw new Error(`${configPath} has no default export (export default defineProject({...}))`);
87
+ }
88
+ return config as ProjectConfig;
89
+ }
90
+
91
+ function mtimeOf(file: string): number | null {
92
+ try {
93
+ return fs.statSync(file).mtimeMs;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The project with the config beatsheet.config.ts has now, for a server that runs while it is
101
+ * edited (the studio; its player re-imports the config through Vite): the folders stay the ones it
102
+ * started with, the config (a project `voice`, …) is imported again after the file changed, through
103
+ * the same import as loadProject with the file's mtime as a query, so only beatsheet.config.ts itself
104
+ * is evaluated again (what it imports stays cached). A stat per call; an import only after an edit.
105
+ * Keeps the last config that loaded while the file is missing or does not load (`onError` says why).
106
+ * The default project stays as it is: a beatsheet.config.ts that appears in its root takes a
107
+ * restart (its folders may differ), which `onError` says once.
108
+ */
109
+ export function projectReloader(project: ProjectContext, onError?: (message: string) => void): () => Promise<ProjectContext> {
110
+ if (!project.configured) return defaultProjectReloader(project, onError);
111
+ let current = project;
112
+ let seen = mtimeOf(project.configPath);
113
+ let loading: Promise<ProjectContext> | null = null;
114
+ return async (): Promise<ProjectContext> => {
115
+ const mtime = mtimeOf(project.configPath);
116
+ if (mtime === null || mtime === seen) return current;
117
+ loading ??= (async (): Promise<ProjectContext> => {
118
+ try {
119
+ current = { ...project, config: await importConfig(project.configPath, String(mtime)) };
120
+ } catch (err) {
121
+ onError?.(`${errorMessage(err)} (keeping the config loaded before)`);
122
+ }
123
+ seen = mtime;
124
+ loading = null;
125
+ return current;
126
+ })();
127
+ return loading;
128
+ };
129
+ }
130
+
131
+ function defaultProjectReloader(project: ProjectContext, onError?: (message: string) => void): () => Promise<ProjectContext> {
132
+ const configPath = path.join(project.root, CONFIG_FILE);
133
+ let told = false;
134
+ return async (): Promise<ProjectContext> => {
135
+ if (!told && fs.existsSync(configPath)) {
136
+ told = true;
137
+ onError?.(`${configPath} appeared: restart beatsheet to use it (keeping the default theme and built-in scenes until then)`);
138
+ }
139
+ return project;
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Finds and loads the project for a video file (or the cwd when no file is given): the nearest
145
+ * beatsheet.config.ts up the tree, else the default project (default theme, built-in scenes). The
146
+ * default project's root is the parent of a folder named `videos` (the video's folder, or the cwd),
147
+ * so `check` run inside videos/ finds ../assets and `render` writes ../out; else `fallbackRoot`.
148
+ * Writes nothing.
149
+ */
150
+ export async function discoverProject(fileOrDir: string, fallbackRoot: string = userCwd()): Promise<ProjectContext> {
151
+ const configPath = findConfig(fileOrDir);
152
+ if (configPath) return loadProject(configPath);
153
+ const dir = folderOf(fileOrDir);
154
+ return loadProject(DEFAULT_CONFIG_PATH, path.basename(dir) === 'videos' ? path.dirname(dir) : fallbackRoot);
155
+ }
156
+
157
+ /**
158
+ * The path with its file name spelled as it is on disk. On a case-insensitive file system
159
+ * (macOS, Windows) `OCTOBER.video.json` opens `october.video.json`, so anything keyed by the
160
+ * name (render locks, write queues, output files) must use the one on-disk spelling. Matched by
161
+ * directory entry (same device and inode, case- and Unicode-folded name), so a symlink is not
162
+ * followed out of its folder. Unchanged when the name is already exact or the file is missing.
163
+ */
164
+ export async function canonicalPath(file: string): Promise<string> {
165
+ const dir = path.dirname(file);
166
+ const base = path.basename(file);
167
+ let entries: string[];
168
+ try {
169
+ entries = await fs.promises.readdir(dir);
170
+ } catch {
171
+ return file;
172
+ }
173
+ if (entries.includes(base)) return file;
174
+ let target: fs.Stats;
175
+ try {
176
+ target = await fs.promises.lstat(file);
177
+ } catch {
178
+ return file;
179
+ }
180
+ const fold = (s: string): string => s.normalize('NFC').toLowerCase();
181
+ for (const entry of entries.filter((e) => fold(e) === fold(base))) {
182
+ try {
183
+ const s = await fs.promises.lstat(path.join(dir, entry));
184
+ if (s.ino === target.ino && s.dev === target.dev) return path.join(dir, entry);
185
+ } catch {
186
+ // vanished meanwhile
187
+ }
188
+ }
189
+ return file;
190
+ }
191
+
192
+ /** 'october-cli.video.json' -> 'october-cli'. */
193
+ export function videoName(file: string): string {
194
+ const base = path.basename(file);
195
+ return base.endsWith(VIDEO_SUFFIX) ? base.slice(0, -VIDEO_SUFFIX.length) : base.replace(/\.json$/, '');
196
+ }
197
+
198
+ export function errorMessage(err: unknown): string {
199
+ return err instanceof Error ? err.message : String(err);
200
+ }
@@ -0,0 +1,185 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { chromium, type Browser } from 'playwright';
7
+ import { CLI_DIR } from '../paths';
8
+
9
+ /** Playwright's browser cache folder. */
10
+ export function playwrightCacheDir(): string {
11
+ const env = process.env.PLAYWRIGHT_BROWSERS_PATH;
12
+ if (env && env !== '0') return env;
13
+ if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Caches', 'ms-playwright');
14
+ if (process.platform === 'win32') return path.join(process.env.LOCALAPPDATA ?? os.homedir(), 'ms-playwright');
15
+ return path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), '.cache'), 'ms-playwright');
16
+ }
17
+
18
+ /**
19
+ * Newest cached chromium_headless_shell-<rev>/chrome-headless-shell-<platform>/chrome-headless-shell
20
+ * in the Playwright cache dir, or undefined. Never downloads a browser.
21
+ */
22
+ export function findChromium(cacheDir: string = playwrightCacheDir()): string | undefined {
23
+ let entries: string[];
24
+ try {
25
+ entries = fs.readdirSync(cacheDir);
26
+ } catch {
27
+ return undefined;
28
+ }
29
+ const builds = entries
30
+ .map((e) => /^chromium_headless_shell-(\d+)$/.exec(e))
31
+ .filter((m): m is RegExpExecArray => m !== null)
32
+ .sort((a, b) => Number(b[1]) - Number(a[1]));
33
+ const exe = process.platform === 'win32' ? 'chrome-headless-shell.exe' : 'chrome-headless-shell';
34
+ for (const m of builds) {
35
+ const dir = path.join(cacheDir, m[0]);
36
+ let platforms: string[];
37
+ try {
38
+ platforms = fs.readdirSync(dir).filter((d) => d.startsWith('chrome-headless-shell-'));
39
+ } catch {
40
+ continue;
41
+ }
42
+ for (const p of platforms) {
43
+ const candidate = path.join(dir, p, exe);
44
+ if (fs.existsSync(candidate)) return candidate;
45
+ }
46
+ }
47
+ return undefined;
48
+ }
49
+
50
+ /**
51
+ * Flags for stable, deterministic pixels. --disable-partial-raster: without it Chromium keeps a
52
+ * tile's pixels from an earlier frame and redraws only the part that changed, and a part drawn
53
+ * through that smaller clip is not bit for bit what the whole tile gives (a gradient under an
54
+ * opacity came out 1 of 255 off over about 1,000 pixels), so a frame depended on the frames before.
55
+ */
56
+ export const CHROMIUM_ARGS = [
57
+ '--font-render-hinting=none',
58
+ '--disable-lcd-text',
59
+ '--force-color-profile=srgb',
60
+ '--hide-scrollbars',
61
+ '--disable-gpu-rasterization',
62
+ '--disable-partial-raster',
63
+ '--autoplay-policy=no-user-gesture-required',
64
+ ];
65
+
66
+ /**
67
+ * The playwright-core the CLI launches with: found through playwright (its dependency), not through
68
+ * hoisting, so a strict pnpm install finds it too.
69
+ */
70
+ export function playwrightCore(): { dir: string; version: string } {
71
+ const playwrightPkg = createRequire(path.join(CLI_DIR, 'package.json')).resolve('playwright/package.json');
72
+ const pkg = createRequire(playwrightPkg).resolve('playwright-core/package.json');
73
+ return { dir: path.dirname(pkg), version: (JSON.parse(fs.readFileSync(pkg, 'utf8')) as { version: string }).version };
74
+ }
75
+
76
+ function pinnedPlaywright(): string {
77
+ try {
78
+ return `playwright@${playwrightCore().version}`;
79
+ } catch {
80
+ return 'playwright';
81
+ }
82
+ }
83
+
84
+ /** Pinned to the CLI's playwright-core: a newer playwright may download a headless shell this one does not launch. */
85
+ export const INSTALL_HINT = `run \`npx -y ${pinnedPlaywright()} install chromium-headless-shell\` (or set BEATSHEET_CHROMIUM to a Chromium binary)`;
86
+
87
+ /** True for Playwright's "browser is not installed" launch error. */
88
+ export function isMissingBrowser(err: unknown): boolean {
89
+ const msg = err instanceof Error ? err.message : String(err);
90
+ return /Executable doesn't exist|playwright install|browserType\.launch: .*not found/i.test(msg);
91
+ }
92
+
93
+ /** What launchBrowser runs; tests stub these. Defaults: Playwright's chromium, the Playwright cache, installChromium, stderr, process.env. */
94
+ export interface LaunchDeps {
95
+ launch?: (executablePath?: string) => Promise<Browser>;
96
+ cachedBuild?: () => string | null;
97
+ install?: (log: (line: string) => void) => Promise<void>;
98
+ log?: (line: string) => void;
99
+ env?: NodeJS.ProcessEnv;
100
+ }
101
+
102
+ /**
103
+ * Node arguments that run playwright-core's cli.js `install chromium-headless-shell` with
104
+ * process.argv[1] = 'beatsheet': Playwright prints an "install your project's dependencies first"
105
+ * box when argv[1] (the script path) lies in the npx cache (`_npx`), which is where the CLI's own
106
+ * playwright-core lies under `npx beatsheet`. Its command parser reads argv.slice(2) either way.
107
+ */
108
+ export function chromiumInstallArgs(cli: string): string[] {
109
+ return ['-e', `require(${JSON.stringify(cli)})`, 'beatsheet', 'install', 'chromium-headless-shell'];
110
+ }
111
+
112
+ /**
113
+ * Downloads Playwright's chromium-headless-shell into the Playwright cache with the playwright-core
114
+ * the CLI launches with, so the build matches. The download's progress goes to stderr (a TTY stays
115
+ * one, so the progress bar renders).
116
+ */
117
+ export async function installChromium(log: (line: string) => void): Promise<void> {
118
+ log('Chromium is not installed yet: downloading it once (about 100 MB) …');
119
+ const cli = path.join(playwrightCore().dir, 'cli.js');
120
+ return new Promise((resolve, reject) => {
121
+ const child = spawn(process.execPath, chromiumInstallArgs(cli), { stdio: ['ignore', 2, 2] });
122
+ child.on('error', reject);
123
+ child.on('exit', (code, signal) => {
124
+ if (code === 0) resolve();
125
+ else reject(new Error(`playwright install chromium-headless-shell exited with ${signal ?? `code ${code}`}`));
126
+ });
127
+ });
128
+ }
129
+
130
+ /** The install per installer in this process, shared by concurrent launches; a failed one is forgotten, so a later launch tries again. */
131
+ const installs = new WeakMap<(log: (line: string) => void) => Promise<void>, Promise<void>>();
132
+
133
+ /**
134
+ * Launch order: $BEATSHEET_CHROMIUM if set; else Playwright's default browser; if that build is
135
+ * not installed, the newest cached chromium_headless_shell build (respects PLAYWRIGHT_BROWSERS_PATH);
136
+ * else, unless BEATSHEET_NO_DOWNLOAD is set, download Chromium once and launch again; else an
137
+ * error with an install hint.
138
+ */
139
+ export async function launchBrowser(deps: LaunchDeps = {}): Promise<Browser> {
140
+ const launch = deps.launch ?? ((executablePath?: string): Promise<Browser> => chromium.launch({ executablePath, headless: true, args: CHROMIUM_ARGS }));
141
+ const cachedBuild = deps.cachedBuild ?? ((): string | null => findChromium() ?? null);
142
+ const install = deps.install ?? installChromium;
143
+ const log = deps.log ?? ((line: string): void => console.error(line));
144
+ const env = deps.env ?? process.env;
145
+ const firstLine = (err: unknown): string => (err instanceof Error ? err.message.split('\n')[0] : String(err));
146
+ const fail = (what: string, err: unknown): Error => new Error(`Could not launch Chromium (${what}): ${firstLine(err)}`);
147
+
148
+ const custom = env.BEATSHEET_CHROMIUM;
149
+ if (custom) {
150
+ try {
151
+ return await launch(custom);
152
+ } catch (err) {
153
+ throw fail(`BEATSHEET_CHROMIUM=${custom}`, err);
154
+ }
155
+ }
156
+ try {
157
+ return await launch();
158
+ } catch (err) {
159
+ if (!isMissingBrowser(err)) throw fail("Playwright's default browser", err);
160
+ }
161
+ const cached = cachedBuild();
162
+ if (cached) {
163
+ try {
164
+ return await launch(cached);
165
+ } catch (err) {
166
+ throw fail(`cached ${cached}`, err);
167
+ }
168
+ }
169
+ if (env.BEATSHEET_NO_DOWNLOAD) {
170
+ throw new Error(`Playwright's Chromium is not installed and no cached chromium_headless_shell build was found in ${playwrightCacheDir()}; ${INSTALL_HINT}`);
171
+ }
172
+ let pending = installs.get(install);
173
+ try {
174
+ if (!pending) installs.set(install, (pending = install(log)));
175
+ await pending;
176
+ } catch (err) {
177
+ if (installs.get(install) === pending) installs.delete(install);
178
+ throw new Error(`Could not download Chromium: ${firstLine(err)}; ${INSTALL_HINT}`);
179
+ }
180
+ try {
181
+ return await launch();
182
+ } catch (err) {
183
+ throw new Error(`Could not launch Chromium after downloading it: ${firstLine(err)}; ${INSTALL_HINT}`);
184
+ }
185
+ }