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,100 @@
1
+ import path from 'node:path';
2
+ import type { Server } from 'node:http';
3
+ import { createServer, normalizePath, searchForWorkspaceRoot, type Plugin, type ViteDevServer, type LogLevel } from 'vite';
4
+ import { BEATSHEET_PACKAGE, beatsheetPackageDirs } from '../packages';
5
+ import { CLI_DIR, PLAYER_BASE, PLAYER_DIR } from '../paths';
6
+
7
+ export const PROJECT_MODULE_ID = 'virtual:beatsheet/project';
8
+ const RESOLVED_PROJECT_ID = '\0' + PROJECT_MODULE_ID;
9
+
10
+ /**
11
+ * Provides `virtual:beatsheet/project`, re-exporting the default export of beatsheet.config.ts. With
12
+ * `name` (ProjectContext.name), a config without a name (the default project) gets that one.
13
+ */
14
+ export function beatsheetProjectPlugin(configPath: string, name?: string): Plugin {
15
+ const target = normalizePath(path.resolve(configPath));
16
+ return {
17
+ name: 'beatsheet:project',
18
+ resolveId(id: string): string | undefined {
19
+ return id === PROJECT_MODULE_ID ? RESOLVED_PROJECT_ID : undefined;
20
+ },
21
+ load(id: string): string | undefined {
22
+ if (id !== RESOLVED_PROJECT_ID) return undefined;
23
+ const project = name ? `{ ...project, name: project.name || ${JSON.stringify(name)} }` : 'project';
24
+ return `import project from ${JSON.stringify(target)};\nexport default ${project};\n`;
25
+ },
26
+ };
27
+ }
28
+
29
+ /**
30
+ * A project without its own install imports @beatsheet/core and @beatsheet/scenes from the CLI's
31
+ * copies (bin/register-fallback.mjs does the same in Node). Its own install still wins.
32
+ */
33
+ export function beatsheetPackagesFallback(cliDir: string = CLI_DIR): Plugin {
34
+ const cliImporter = path.join(cliDir, 'package.json');
35
+ return {
36
+ name: 'beatsheet:packages-fallback',
37
+ async resolveId(id, importer, options) {
38
+ if (!BEATSHEET_PACKAGE.test(id)) return null;
39
+ const own = await this.resolve(id, importer, { ...options, skipSelf: true });
40
+ return own ?? this.resolve(id, cliImporter, { ...options, skipSelf: true });
41
+ },
42
+ };
43
+ }
44
+
45
+ /** Render pages have no HMR websocket; drop the injected Vite client so it doesn't try to connect. */
46
+ export function stripViteClient(): Plugin {
47
+ return {
48
+ name: 'beatsheet:strip-vite-client',
49
+ transformIndexHtml: {
50
+ order: 'post',
51
+ handler(html: string): string {
52
+ return html.replace(/<script type="module" src="[^"]*\/@vite\/client"><\/script>\s*/g, '');
53
+ },
54
+ },
55
+ };
56
+ }
57
+
58
+ export interface PlayerViteOptions {
59
+ configPath: string;
60
+ /** Project root (ProjectContext.root): Vite may serve files below it. */
61
+ root: string;
62
+ /** Project name (ProjectContext.name): the player's name for a config without one. */
63
+ name?: string;
64
+ /** HTTP server for the HMR websocket; null disables HMR (render commands). */
65
+ httpServer: Server | null;
66
+ logLevel?: LogLevel;
67
+ }
68
+
69
+ /** Vite in middleware mode serving the player page under /player/. */
70
+ export async function createPlayerVite(o: PlayerViteOptions): Promise<ViteDevServer> {
71
+ const projectRoot = path.resolve(o.root);
72
+ const hmr = o.httpServer !== null;
73
+ const packages = beatsheetPackageDirs();
74
+ const allow = [
75
+ ...new Set([PLAYER_DIR, projectRoot, searchForWorkspaceRoot(projectRoot), searchForWorkspaceRoot(CLI_DIR), packages.core, packages.scenes]),
76
+ ];
77
+ return createServer({
78
+ configFile: false,
79
+ envDir: false,
80
+ root: PLAYER_DIR,
81
+ base: PLAYER_BASE,
82
+ appType: 'mpa',
83
+ logLevel: o.logLevel ?? 'warn',
84
+ clearScreen: false,
85
+ cacheDir: path.join(CLI_DIR, 'node_modules', hmr ? '.vite-player-studio' : '.vite-player-render'),
86
+ plugins: [beatsheetProjectPlugin(o.configPath, o.name), beatsheetPackagesFallback(), ...(hmr ? [] : [stripViteClient()])],
87
+ server: {
88
+ middlewareMode: true,
89
+ hmr: hmr && o.httpServer ? { server: o.httpServer } : false,
90
+ // No websocket at all for render pages (middleware mode would otherwise bind port 24678).
91
+ ws: hmr ? undefined : false,
92
+ watch: hmr ? {} : null,
93
+ fs: { strict: true, allow },
94
+ },
95
+ optimizeDeps: {
96
+ entries: [path.join(PLAYER_DIR, 'main.ts')],
97
+ include: ['zod'],
98
+ },
99
+ });
100
+ }
package/src/skill.ts ADDED
@@ -0,0 +1,111 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { beatsheetPackageDirs } from './packages';
7
+ import { CLI_DIR } from './paths';
8
+ import type { Log } from './commands';
9
+
10
+ /** The skill's helper scripts, run by `beatsheet <name>`: skill/scripts/<name>.ts. */
11
+ export const SKILL_SCRIPTS = ['catalogue', 'beats', 'frames'] as const;
12
+ export type SkillScript = (typeof SKILL_SCRIPTS)[number];
13
+
14
+ /**
15
+ * The agent skill: the package's own skill/ (the published package, copied there by scripts/prepack.mjs),
16
+ * else skills/beatsheet in a checkout. Null when neither has a SKILL.md.
17
+ */
18
+ export function skillDir(cliDir: string = CLI_DIR): string | null {
19
+ for (const dir of [path.join(cliDir, 'skill'), path.resolve(cliDir, '../../skills/beatsheet')]) {
20
+ if (fs.existsSync(path.join(dir, 'SKILL.md'))) return dir;
21
+ }
22
+ return null;
23
+ }
24
+
25
+ /**
26
+ * The library tour, a finished example video, and the folder of the images it shows: the package's copy in
27
+ * skill/examples/library (scripts/copy-skill.mjs), else the checkout's examples/library. Null when neither exists.
28
+ */
29
+ export function libraryTourSource(cliDir: string = CLI_DIR): { video: string; assets: string } | null {
30
+ const packaged = path.join(cliDir, 'skill', 'examples', 'library');
31
+ const checkout = path.resolve(cliDir, '../../examples/library');
32
+ const candidates = [
33
+ { video: path.join(packaged, 'library-tour.video.json'), assets: path.join(packaged, 'assets') },
34
+ { video: path.join(checkout, 'videos', 'library-tour.video.json'), assets: path.join(checkout, 'assets') },
35
+ ];
36
+ return candidates.find((c) => fs.existsSync(c.video)) ?? null;
37
+ }
38
+
39
+ /**
40
+ * `beatsheet paths`: the version and where the sources of @beatsheet/core and @beatsheet/scenes, the skill
41
+ * and the example videos are, one per line, for an agent that wants to read them. A missing skill or tour
42
+ * reads "(not found)".
43
+ */
44
+ export function pathsReport(cliDir: string = CLI_DIR): string[] {
45
+ const { version } = JSON.parse(fs.readFileSync(path.join(cliDir, 'package.json'), 'utf8')) as { version: string };
46
+ const { core, scenes } = beatsheetPackageDirs(cliDir);
47
+ const tour = libraryTourSource(cliDir);
48
+ return [
49
+ `beatsheet ${version}`,
50
+ `core ${path.join(core, 'src')}`,
51
+ `scenes ${path.join(scenes, 'src')}`,
52
+ `skill ${skillDir(cliDir) ?? '(not found)'}`,
53
+ `examples ${tour ? path.dirname(tour.video) : '(not found)'}`,
54
+ ];
55
+ }
56
+
57
+ /** Where `skill install` puts the skill without --dir: Claude Code's personal skills folder. */
58
+ export function defaultSkillsDir(home: string = os.homedir()): string {
59
+ return path.join(home, '.claude', 'skills');
60
+ }
61
+
62
+ export interface InstallSkillOptions {
63
+ /** The skills folder; the skill lands in <dir>/beatsheet. */
64
+ dir: string;
65
+ /** Replace an existing <dir>/beatsheet (a folder, a file or a link). */
66
+ force: boolean;
67
+ /** The skill to copy (default: skillDir()). */
68
+ from?: string;
69
+ }
70
+
71
+ /** Copies the skill to <dir>/beatsheet and returns that path. */
72
+ export function installSkill(o: InstallSkillOptions, log: Log): string {
73
+ const from = o.from ?? skillDir();
74
+ if (!from) throw new Error('this beatsheet package has no skill/ folder');
75
+ const target = path.join(path.resolve(o.dir), 'beatsheet');
76
+ let exists = false;
77
+ try {
78
+ fs.lstatSync(target);
79
+ exists = true;
80
+ } catch {
81
+ // free
82
+ }
83
+ if (exists) {
84
+ if (!o.force) throw new Error(`${target} already exists; run again with --force to replace it`);
85
+ fs.rmSync(target, { recursive: true, force: true });
86
+ }
87
+ fs.mkdirSync(path.dirname(target), { recursive: true });
88
+ fs.cpSync(from, target, { recursive: true });
89
+ log(`installed the beatsheet skill in ${target}`);
90
+ log('Claude Code picks it up in its next session: run `npx beatsheet studio` in a folder for your videos and tell Claude Code your idea there, or type /beatsheet.');
91
+ return target;
92
+ }
93
+
94
+ /**
95
+ * Runs one of the skill's helper scripts in a child process (TypeScript through tsx) with the user's cwd and
96
+ * args; resolves with its exit code. The script resolves `@beatsheet/core` and `beatsheet` from where it lies:
97
+ * the installed package, or the checkout's root node_modules; the project's config falls back to the CLI's
98
+ * @beatsheet packages (bin/register-fallback.mjs) when the project has none.
99
+ */
100
+ export async function runSkillScript(name: SkillScript, args: string[], cwd: string, dir: string | null = skillDir()): Promise<number> {
101
+ if (!dir) throw new Error('this beatsheet package has no skill/ folder');
102
+ const script = path.join(dir, 'scripts', `${name}.ts`);
103
+ if (!fs.existsSync(script)) throw new Error(`no script ${script}`);
104
+ const tsx = import.meta.resolve('tsx');
105
+ const fallback = pathToFileURL(path.join(CLI_DIR, 'bin', 'register-fallback.mjs')).href;
106
+ const child = spawn(process.execPath, ['--import', tsx, '--import', fallback, script, ...args], { cwd, stdio: 'inherit' });
107
+ return new Promise((resolve, reject) => {
108
+ child.on('error', reject);
109
+ child.on('exit', (code, signal) => resolve(code ?? (signal ? 1 : 0)));
110
+ });
111
+ }
package/src/snap.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * `beatsheet snap <file>`: every scene's duration rewritten so its end lands on the beat grid of the
3
+ * video's music track, so nobody adds up beat times by hand. The maths is core's snapDurations (the
4
+ * studio's "Snap all scenes to the beat" is the same function in mode 'up'); here the default is the
5
+ * nearest beat, held above what a scene needs for its last beat, its transitions and its narration.
6
+ * Only the scene durations change in the file: everything else keeps its bytes.
7
+ */
8
+ import fs from 'node:fs/promises';
9
+ import {
10
+ SPEECH_END_TAIL,
11
+ SPEECH_TAIL,
12
+ beatSeconds,
13
+ resolveTimeline,
14
+ snapDuration,
15
+ snapDurations,
16
+ trackBpm,
17
+ transitionTake,
18
+ type ResolvedTimeline,
19
+ } from '@beatsheet/core';
20
+ import type { Command } from './args';
21
+ import { loadVideo, type LoadedVideo, type Log } from './commands';
22
+ import { clipDurations, videoClips, writeFileAtomic } from './speech';
23
+
24
+ export interface SnapChange {
25
+ index: number;
26
+ sceneId: string;
27
+ from: number;
28
+ to: number;
29
+ /** Set when the nearest beat was too early: what the scene needs, e.g. 'its narration ends at 4.4 s'. */
30
+ held?: string;
31
+ }
32
+
33
+ export interface SnapReport {
34
+ track: string;
35
+ bpm: number;
36
+ changes: SnapChange[];
37
+ /** Ids of the scenes that got shorter (read time is not checked here). */
38
+ shortened: string[];
39
+ /** Sum of the durations before and after. */
40
+ total: { from: number; to: number };
41
+ written: boolean;
42
+ }
43
+
44
+ interface Floor {
45
+ seconds: number;
46
+ why: string;
47
+ }
48
+
49
+ const secs = (x: number): string => String(Math.round(x * 1000) / 1000);
50
+
51
+ /**
52
+ * What each scene must keep, as far as it is known without a browser: its last beat, the transitions
53
+ * into and out of it, and its narration (offset + clip + tail, for clips that are spoken). Read time
54
+ * is measured in the player, so it is not in here.
55
+ */
56
+ export function sceneFloors(timeline: ResolvedTimeline, clips: Readonly<Record<string, number>> = {}): (Floor | undefined)[] {
57
+ const last = timeline.scenes.at(-1);
58
+ return timeline.scenes.map((scene, i) => {
59
+ const floors: Floor[] = [];
60
+ const beat = scene.beats.reduce((max, b) => Math.max(max, b.offset), 0);
61
+ if (beat > 0) floors.push({ seconds: beat, why: `its last beat is at ${secs(beat)} s` });
62
+ const take = (i > 0 ? transitionTake(scene.transitionIn).after : 0) + transitionTake(timeline.scenes[i + 1]?.transitionIn).before;
63
+ if (take > 0) floors.push({ seconds: take, why: `its transitions take ${secs(take)} s` });
64
+ const n = scene.narration;
65
+ const clip = n && Object.prototype.hasOwnProperty.call(clips, n.key) ? clips[n.key] : undefined;
66
+ if (n && clip !== undefined && Number.isFinite(clip)) {
67
+ const runsTo = n.at - scene.start + clip;
68
+ floors.push({ seconds: runsTo + (scene === last ? SPEECH_END_TAIL : SPEECH_TAIL), why: `its narration runs to ${secs(runsTo)} s` });
69
+ }
70
+ return floors.sort((a, b) => b.seconds - a.seconds)[0];
71
+ });
72
+ }
73
+
74
+ /** The music track's tempo, or the plain error of a video that has no beat to snap to. */
75
+ function videoTempo(v: Pick<LoadedVideo, 'doc' | 'project'>, file: string): { track: string; bpm: number } {
76
+ const track = v.doc.music?.track;
77
+ if (!track) throw new Error(`snap: ${file} has no music, so there is no beat to snap to (set "music": { "track": "<id>" } first)`);
78
+ const tracks: object = v.project.config.theme?.music ?? {};
79
+ if (!Object.prototype.hasOwnProperty.call(tracks, track)) throw new Error(`snap: music track "${track}" is not in the project's theme`);
80
+ const bpm = trackBpm(v.project.config.theme?.music?.[track]);
81
+ if (bpm === undefined) throw new Error(`snap: music track "${track}" has no tempo, so there is no beat to snap to (a file track gets one with "bpm" in the theme)`);
82
+ return { track, bpm };
83
+ }
84
+
85
+ export async function runSnap(cmd: Extract<Command, { cmd: 'snap' }>, log: Log): Promise<SnapReport> {
86
+ const v = await loadVideo(cmd.file);
87
+ const { track, bpm } = videoTempo(v, cmd.file);
88
+ const beat = beatSeconds(bpm);
89
+ const mode = cmd.up ? 'up' : 'nearest';
90
+
91
+ let floors: (Floor | undefined)[] = [];
92
+ try {
93
+ const clips = videoClips(v);
94
+ floors = sceneFloors(resolveTimeline(v.doc, v.project.config), clips.length ? await clipDurations(clips) : {});
95
+ } catch {
96
+ // A video whose timeline does not resolve still snaps; `check` reports what is wrong with it.
97
+ }
98
+
99
+ const from = v.doc.scenes.map((s) => s.duration);
100
+ const to = snapDurations(from, beat, mode, floors.map((f) => f?.seconds));
101
+ const changes: SnapChange[] = [];
102
+ let start = 0;
103
+ to.forEach((d, index) => {
104
+ if (d !== from[index]) {
105
+ const held = d !== snapDuration(start, from[index]!, beat, mode) ? floors[index]?.why : undefined;
106
+ changes.push({ index, sceneId: v.doc.scenes[index]!.id, from: from[index]!, to: d, ...(held ? { held } : {}) });
107
+ }
108
+ start += d;
109
+ });
110
+ const shortened = changes.filter((c) => c.to < c.from).map((c) => c.sceneId);
111
+ const sum = (ds: readonly number[]): number => Math.round(ds.reduce((a, b) => a + b, 0) * 1000) / 1000;
112
+ const report: SnapReport = { track, bpm, changes, shortened, total: { from: sum(from), to: sum(to) }, written: false };
113
+
114
+ log(`snap ${cmd.file} · ${track}, ${secs(bpm)} bpm (a beat is ${secs(beat)} s) · ${cmd.up ? 'next beat, never shorter' : 'nearest beat'}${cmd.dryRun ? ' · dry run' : ''}`);
115
+ const width = Math.max(0, ...changes.map((c) => c.sceneId.length));
116
+ for (const c of changes) {
117
+ log(` ${c.sceneId.padEnd(width)} ${secs(c.from)} s → ${secs(c.to)} s${c.held ? ` (${c.held}, so not the beat before)` : ''}`);
118
+ }
119
+ const n = v.doc.scenes.length;
120
+ if (changes.length === 0) {
121
+ log(` every scene ends on the beat already: nothing to change (${n} scene${n === 1 ? '' : 's'}, ${secs(report.total.to)} s)`);
122
+ return report;
123
+ }
124
+ log(` ${changes.length} of ${n} scene${n === 1 ? '' : 's'} ${cmd.dryRun ? 'would change' : 'changed'} · video ${secs(report.total.from)} s → ${secs(report.total.to)} s`);
125
+ if (shortened.length) {
126
+ log(` shorter now: ${shortened.join(', ')}. Read time is measured in the browser, not here: run beatsheet check ${cmd.file} (snap --up only lengthens)`);
127
+ }
128
+ if (cmd.dryRun) return report;
129
+
130
+ const text = await fs.readFile(v.path, 'utf8');
131
+ await writeFileAtomic(v.path, withSceneDurations(text, new Map(changes.map((c) => [c.index, c.to]))));
132
+ report.written = true;
133
+ return report;
134
+ }
135
+
136
+ /**
137
+ * The video file's text with the given scene durations (by scene index) and nothing else changed:
138
+ * only the number after each of those scenes' "duration" is replaced, so key order, indentation and
139
+ * every other value keep their bytes. Falls back to the studio's form (2 spaces, a final newline)
140
+ * when the text cannot be patched in place.
141
+ */
142
+ export function withSceneDurations(text: string, durations: ReadonlyMap<number, number>): string {
143
+ const json = JSON.parse(text) as { scenes: { duration: number }[] };
144
+ for (const [i, d] of durations) json.scenes[i]!.duration = d;
145
+ const spans = new Map<number, [number, number]>();
146
+ walk(text, 0, (key, start) => {
147
+ if (key !== 'scenes') return;
148
+ walk(text, start, (index, sceneStart) => {
149
+ walk(text, sceneStart, (k, s, e) => {
150
+ if (k === 'duration' && typeof index === 'number') spans.set(index, [s, e]);
151
+ });
152
+ });
153
+ });
154
+ let out = text;
155
+ for (const [i, d] of [...durations].sort((a, b) => b[0] - a[0])) {
156
+ const span = spans.get(i);
157
+ if (!span) return JSON.stringify(json, null, 2) + '\n';
158
+ out = out.slice(0, span[0]) + String(d) + out.slice(span[1]);
159
+ }
160
+ try {
161
+ if (JSON.stringify(JSON.parse(out)) === JSON.stringify(json)) return out;
162
+ } catch {
163
+ // fall through
164
+ }
165
+ return JSON.stringify(json, null, 2) + '\n';
166
+ }
167
+
168
+ const isSpace = (c: string | undefined): boolean => c === ' ' || c === '\n' || c === '\r' || c === '\t';
169
+
170
+ function skipSpace(t: string, i: number): number {
171
+ while (isSpace(t[i])) i++;
172
+ return i;
173
+ }
174
+
175
+ /** `i` is on the opening quote; returns the index after the closing one. */
176
+ function skipString(t: string, i: number): number {
177
+ i++;
178
+ while (i < t.length && t[i] !== '"') i += t[i] === '\\' ? 2 : 1;
179
+ return i + 1;
180
+ }
181
+
182
+ /**
183
+ * Steps over the JSON value at `i` (valid JSON, already parsed once) and returns the index after it.
184
+ * For an object or an array, `visit` gets each member: its key or index and the span of its value.
185
+ */
186
+ function walk(t: string, i: number, visit?: (key: string | number, start: number, end: number) => void): number {
187
+ i = skipSpace(t, i);
188
+ const open = t[i];
189
+ if (open === '"') return skipString(t, i);
190
+ if (open === '{' || open === '[') {
191
+ const close = open === '{' ? '}' : ']';
192
+ let count = 0;
193
+ i = skipSpace(t, i + 1);
194
+ while (i < t.length && t[i] !== close) {
195
+ let key: string | number = count++;
196
+ if (open === '{') {
197
+ const keyStart = i;
198
+ i = skipString(t, i);
199
+ key = JSON.parse(t.slice(keyStart, i)) as string;
200
+ i = skipSpace(t, i) + 1; // the colon
201
+ }
202
+ const start = skipSpace(t, i);
203
+ const end = walk(t, start);
204
+ visit?.(key, start, end);
205
+ i = skipSpace(t, end);
206
+ if (t[i] === ',') i = skipSpace(t, i + 1);
207
+ }
208
+ return i + 1;
209
+ }
210
+ while (i < t.length && !isSpace(t[i]) && t[i] !== ',' && t[i] !== ']' && t[i] !== '}') i++;
211
+ return i;
212
+ }