deictic 0.3.1 → 0.4.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 (165) hide show
  1. package/API.md +26 -17
  2. package/README.md +6 -26
  3. package/dist/annotations/client.d.ts +1 -1
  4. package/dist/annotations/client.js +1 -1
  5. package/dist/annotations/index.d.ts +2 -101
  6. package/dist/annotations/index.js +1 -22
  7. package/dist/astro.d.ts +1 -1
  8. package/dist/astro.js +1 -1
  9. package/dist/cli.d.ts +1 -0
  10. package/dist/cli.js +37 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/index.js +1 -10
  13. package/dist/logs/client.d.ts +1 -1
  14. package/dist/logs/client.js +1 -1
  15. package/dist/logs/index.d.ts +2 -18
  16. package/dist/logs/index.js +1 -21
  17. package/dist/network/client.d.ts +1 -1
  18. package/dist/network/client.js +1 -1
  19. package/dist/network/index.d.ts +1 -1
  20. package/dist/network/index.js +1 -37
  21. package/dist/recommended/index.d.ts +7 -7
  22. package/dist/recommended/index.js +1 -26
  23. package/dist/recordings/client.d.ts +1 -1
  24. package/dist/recordings/client.js +1 -1
  25. package/dist/recordings/index.d.ts +1 -1
  26. package/dist/screenshots/client.d.ts +1 -1
  27. package/dist/screenshots/client.js +1 -108
  28. package/dist/screenshots/dom.d.ts +1 -1
  29. package/dist/screenshots/dom.js +1 -1
  30. package/dist/screenshots/index.d.ts +1 -1
  31. package/dist/screenshots/index.js +1 -103
  32. package/dist/screenshots/rrweb.d.ts +1 -1
  33. package/dist/screenshots/rrweb.js +1 -1
  34. package/dist/shared/annotations.js +22 -0
  35. package/dist/shared/annotations.js.map +1 -0
  36. package/dist/shared/board.js +190 -0
  37. package/dist/shared/board.js.map +1 -0
  38. package/dist/shared/client.js +108 -0
  39. package/dist/shared/endpoints.js +4 -1
  40. package/dist/shared/endpoints.js.map +1 -1
  41. package/dist/shared/find.js +156 -0
  42. package/dist/shared/find.js.map +1 -0
  43. package/dist/shared/frame.js +75 -0
  44. package/dist/shared/frame.js.map +1 -0
  45. package/dist/shared/index.d.ts +5 -0
  46. package/dist/shared/index.d.ts.map +1 -1
  47. package/dist/shared/index2.d.ts +85 -88
  48. package/dist/shared/index2.d.ts.map +1 -1
  49. package/dist/shared/index3.d.ts +83 -89
  50. package/dist/shared/index3.d.ts.map +1 -1
  51. package/dist/shared/index4.d.ts +98 -50
  52. package/dist/shared/index4.d.ts.map +1 -1
  53. package/dist/shared/index5.d.ts +13 -219
  54. package/dist/shared/index5.d.ts.map +1 -1
  55. package/dist/shared/index6.d.ts +55 -61
  56. package/dist/shared/index6.d.ts.map +1 -1
  57. package/dist/shared/index7.d.ts +224 -0
  58. package/dist/shared/index7.d.ts.map +1 -0
  59. package/dist/shared/index8.d.ts +52 -0
  60. package/dist/shared/index8.d.ts.map +1 -0
  61. package/dist/shared/index9.d.ts +70 -0
  62. package/dist/shared/index9.d.ts.map +1 -0
  63. package/dist/shared/init.js +472 -0
  64. package/dist/shared/init.js.map +1 -0
  65. package/dist/shared/local.js +165 -0
  66. package/dist/shared/local.js.map +1 -0
  67. package/dist/shared/logs.js +22 -0
  68. package/dist/shared/logs.js.map +1 -0
  69. package/dist/shared/network.js +39 -0
  70. package/dist/shared/network.js.map +1 -0
  71. package/dist/shared/packages.js +125 -0
  72. package/dist/shared/packages.js.map +1 -0
  73. package/dist/shared/recommended.js +26 -0
  74. package/dist/shared/recommended.js.map +1 -0
  75. package/dist/shared/recording.js +316 -0
  76. package/dist/shared/recording.js.map +1 -0
  77. package/dist/shared/recordings.js +2 -1
  78. package/dist/shared/recordings.js.map +1 -1
  79. package/dist/shared/screenshots.js +108 -0
  80. package/dist/shared/screenshots.js.map +1 -0
  81. package/dist/shared/src.js +10 -0
  82. package/dist/shared/src.js.map +1 -0
  83. package/dist/shared/task.js +108 -0
  84. package/dist/shared/task.js.map +1 -0
  85. package/dist/shared/tasks.js +7 -180
  86. package/dist/shared/tasks.js.map +1 -1
  87. package/dist/shared/transcribe.js +128 -0
  88. package/dist/shared/transcribe.js.map +1 -0
  89. package/dist/shared/vb.js +13 -0
  90. package/dist/shared/vb.js.map +1 -0
  91. package/dist/shared/vite.d.ts +16 -0
  92. package/dist/shared/vite.d.ts.map +1 -0
  93. package/dist/shared/vite.js +61 -0
  94. package/dist/shared/vite.js.map +1 -0
  95. package/dist/shared/voice.js +84 -0
  96. package/dist/{voice/index.js.map → shared/voice.js.map} +1 -1
  97. package/dist/shared/voice2.js +90 -0
  98. package/dist/shared/voice2.js.map +1 -0
  99. package/dist/shared/watch.js +209 -0
  100. package/dist/shared/watch.js.map +1 -0
  101. package/dist/shared/watchers.js +62 -0
  102. package/dist/shared/watchers.js.map +1 -0
  103. package/dist/tailwind/client.d.ts +1 -1
  104. package/dist/tailwind/client.js +1 -1
  105. package/dist/tailwind/index.d.ts +1 -1
  106. package/dist/tailwind/index.js +1 -1
  107. package/dist/tasks/client.d.ts +1 -1
  108. package/dist/tasks/client.js +1 -1
  109. package/dist/tasks/index.d.ts +1 -1
  110. package/dist/tasks/index.js +3 -1
  111. package/dist/vite.d.ts +2 -15
  112. package/dist/vite.js +2 -60
  113. package/dist/voice/client.d.ts +1 -1
  114. package/dist/voice/client.js +1 -1
  115. package/dist/voice/index.d.ts +2 -52
  116. package/dist/voice/index.js +1 -84
  117. package/package.json +6 -9
  118. package/skills/deictic/SKILL.md +27 -42
  119. package/skills/deictic/references/recordings.md +9 -108
  120. package/skills/deictic/references/tasks.md +21 -112
  121. package/skills/deictic/references/watch.md +13 -68
  122. package/src/cli/board.ts +204 -0
  123. package/src/cli/bun.ts +133 -0
  124. package/src/cli/edit.ts +56 -0
  125. package/src/cli/find.ts +147 -0
  126. package/src/cli/frame.ts +90 -0
  127. package/src/cli/init.ts +388 -0
  128. package/src/cli/recording.ts +383 -0
  129. package/src/cli/task.ts +126 -0
  130. package/src/cli/transcribe.ts +129 -0
  131. package/src/cli/vb.ts +11 -0
  132. package/src/cli/voice.ts +59 -0
  133. package/src/cli/watch.ts +221 -0
  134. package/src/cli.ts +37 -0
  135. package/src/index.ts +5 -0
  136. package/src/plugins/logs/index.ts +1 -0
  137. package/src/plugins/network/index.ts +1 -0
  138. package/src/plugins/recordings/index.ts +1 -0
  139. package/src/plugins/screenshots/index.ts +5 -1
  140. package/src/plugins/tasks/index.ts +3 -2
  141. package/src/plugins/tasks/local.ts +19 -6
  142. package/src/plugins/tasks/watchers.ts +41 -6
  143. package/src/tools/endpoints.ts +3 -0
  144. package/src/tools/packages.ts +107 -0
  145. package/dist/annotations/index.d.ts.map +0 -1
  146. package/dist/annotations/index.js.map +0 -1
  147. package/dist/index.js.map +0 -1
  148. package/dist/logs/index.d.ts.map +0 -1
  149. package/dist/logs/index.js.map +0 -1
  150. package/dist/network/index.js.map +0 -1
  151. package/dist/recommended/index.js.map +0 -1
  152. package/dist/screenshots/index.js.map +0 -1
  153. package/dist/vite.d.ts.map +0 -1
  154. package/dist/vite.js.map +0 -1
  155. package/dist/voice/index.d.ts.map +0 -1
  156. package/skills/deictic/references/install.md +0 -103
  157. package/skills/deictic/scripts/frame.mjs +0 -62
  158. package/skills/deictic/scripts/lib.mjs +0 -283
  159. package/skills/deictic/scripts/recording.mjs +0 -266
  160. package/skills/deictic/scripts/task.mjs +0 -120
  161. package/skills/deictic/scripts/transcribe.mjs +0 -93
  162. package/skills/deictic/scripts/vb.mjs +0 -12
  163. package/skills/deictic/scripts/voice.mjs +0 -50
  164. package/skills/deictic/scripts/watch.mjs +0 -152
  165. /package/dist/{screenshots → shared}/client.js.map +0 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * What the agent's commands share: the board's CLI (`vb`, the project's `@vercel/board`) on the board the dev server
3
+ * uses, the project's `.deictic/` folders, and failing with what to do.
4
+ */
5
+ import { spawnSync, type SpawnSyncOptions } from 'node:child_process';
6
+ import { existsSync, readdirSync } from 'node:fs';
7
+ import { dirname, join, resolve } from 'node:path';
8
+ import { parseArgs as parse, type ParseArgsConfig } from 'node:util';
9
+
10
+ import { runningAt, vbScript } from '#src/plugins/tasks/local.ts';
11
+
12
+ /** How the commands name each other in what they print, for an agent to run. */
13
+ export const ME = 'npx deictic';
14
+
15
+ export function fail(message: string): never {
16
+ console.error(message);
17
+ process.exit(1);
18
+ }
19
+
20
+ /** A command's options and arguments, or a failure saying what's wrong with them. */
21
+ export function parseArgs<T extends NonNullable<ParseArgsConfig['options']>>(args: string[], options: T) {
22
+ try {
23
+ return parse({ args, options, allowPositionals: true, allowNegative: true, strict: true });
24
+ } catch (e) {
25
+ return fail((e as Error).message);
26
+ }
27
+ }
28
+
29
+ /** `1:02.5`, from milliseconds. */
30
+ export function clock(ms: number): string {
31
+ const s = Math.max(0, ms) / 1000;
32
+ return `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`;
33
+ }
34
+
35
+ /** `30m`, `45s`, `1h` or a bare number of seconds, as milliseconds. */
36
+ export function duration(text: string): number {
37
+ const [, n, unit = 's'] = /^(\d+(?:\.\d+)?)([smh])?$/.exec(text) ?? [];
38
+ if (n === undefined) fail(`"${text}" isn't a duration: 30m, 45s, 1h, or seconds as a number.`);
39
+ return Number(n) * { s: 1000, m: 60_000, h: 3_600_000 }[unit as 's' | 'm' | 'h'];
40
+ }
41
+
42
+ /** This directory and each above it. */
43
+ function* upFrom(dir = process.cwd()) {
44
+ for (let at = resolve(dir); ; at = dirname(at)) {
45
+ yield at;
46
+ if (dirname(at) === at) return;
47
+ }
48
+ }
49
+
50
+ /** Every `.deictic/` near here: in this directory or above, or in a folder of it (a site/, an app/). */
51
+ export function deicticDirs(): string[] {
52
+ const found = [...upFrom()].map((d) => join(d, '.deictic')).filter((p) => existsSync(p));
53
+ const walk = (dir: string, depth: number) => {
54
+ if (depth === 0) return;
55
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
56
+ if (!e.isDirectory() || e.name === 'node_modules' || (e.name.startsWith('.') && e.name !== '.deictic')) continue;
57
+ const path = join(dir, e.name);
58
+ if (e.name === '.deictic') found.push(path);
59
+ else walk(path, depth - 1);
60
+ }
61
+ };
62
+ walk(process.cwd(), 3);
63
+ return [...new Set(found)];
64
+ }
65
+
66
+ /** The board a `.deictic/` names: the one its dev server started. */
67
+ export const boardIn = (dir: string) => runningAt(join(dir, 'board.json'))?.url;
68
+
69
+ /**
70
+ * The board's URL: `BOARD_URL`, or with none, the board the dev server started for the project, which
71
+ * `.deictic/board.json` names. Nothing where there's neither: `vb` then finds the team's board.
72
+ */
73
+ export function boardUrl(): string | undefined {
74
+ const given = process.env.BOARD_URL;
75
+ if (given !== undefined && given !== '') return given;
76
+ return deicticDirs()
77
+ .map(boardIn)
78
+ .find((url) => url !== undefined);
79
+ }
80
+
81
+ /**
82
+ * The coding agents a shell of theirs says it is, by a variable each sets only there. Not one a person's terminal has
83
+ * too (Replit's `REPL_ID`, a `TERM_PROGRAM`): a person writes as themselves.
84
+ */
85
+ const AGENTS: [name: string, variables: string[]][] = [
86
+ ['claude', ['CLAUDECODE', 'CLAUDE_CODE']],
87
+ ['codex', ['CODEX_SANDBOX', 'CODEX_THREAD_ID']],
88
+ ['gemini', ['GEMINI_CLI']],
89
+ ['cursor', ['CURSOR_AGENT']],
90
+ ['copilot', ['COPILOT_AGENT', 'COPILOT_CLI']],
91
+ ['opencode', ['OPENCODE']],
92
+ ['auggie', ['AUGMENT_AGENT']],
93
+ ['goose', ['GOOSE_PROVIDER']],
94
+ ['junie', ['JUNIE_DATA', 'JUNIE_SHIM_PATH']],
95
+ ];
96
+
97
+ /** A board's profile name: a letter, then up to 31 letters, digits and hyphens. */
98
+ const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
99
+
100
+ /**
101
+ * Who the board's CLI writes as: `BOARD_PROFILE` where it's set, or else the coding agent this runs in, so its claims,
102
+ * replies and results are its own, not the person's, without its setting anything on each command. By the variable
103
+ * its harness sets, then by `AI_AGENT` (`claude-code_2-1-330_agent` is `claude`). Nothing at a person's terminal.
104
+ */
105
+ export function profileOf(env: NodeJS.ProcessEnv = process.env): string | undefined {
106
+ if (env.BOARD_PROFILE !== undefined && env.BOARD_PROFILE !== '') return env.BOARD_PROFILE;
107
+ const known = AGENTS.find(([, variables]) => variables.some((v) => env[v] !== undefined && env[v] !== ''));
108
+ if (known !== undefined) return known[0];
109
+ const named = env.AI_AGENT?.toLowerCase();
110
+ if (named === undefined || named === '') return undefined;
111
+ if (named.startsWith('github_copilot')) return 'copilot';
112
+ // The agent's name, without its version, its kind or what it is (`-code`, `-cli`).
113
+ const name = (named.split('_')[0] ?? '').replace(/-(code|cli|agent)$/, '');
114
+ return PROFILE.test(name) ? name : undefined;
115
+ }
116
+
117
+ /**
118
+ * How to run the board's CLI, as `spawn`'s command, arguments and options, on the environment's board or the
119
+ * project's own, as the agent running it (`profileOf`): the project's `@vercel/board`, run by this runtime, so it
120
+ * needn't be on the PATH and no shell reads the arguments; with none installed, `vb` from the PATH.
121
+ */
122
+ export function vbCommand(args: string[]): [string, string[], SpawnSyncOptions] {
123
+ const url = boardUrl();
124
+ const profile = profileOf();
125
+ const env = {
126
+ ...process.env,
127
+ ...(url === undefined ? {} : { BOARD_URL: url }),
128
+ ...(profile === undefined ? {} : { BOARD_PROFILE: profile }),
129
+ };
130
+ const script = vbScript();
131
+ if (script !== undefined) return [process.execPath, [script, ...args], { env }];
132
+ // npm's shims on Windows are .cmd files, which only a shell runs; the arguments here are IDs and names.
133
+ if (process.platform === 'win32') return [`vb ${args.map((a) => `"${a}"`).join(' ')}`, [], { env, shell: true }];
134
+ return ['vb', args, { env }];
135
+ }
136
+
137
+ const unreachable = (message: string) => fail(`vb: ${message}. Install @vercel/board in the project (${ME} init), or put vb on the PATH.`);
138
+
139
+ /** Runs the board's CLI and answers what it printed. */
140
+ export function vb(args: string[]): string {
141
+ const [command, argv, options] = vbCommand(args);
142
+ const run = spawnSync(command, argv, { ...options, encoding: 'utf8', maxBuffer: 1 << 28 });
143
+ if (run.error) unreachable(run.error.message);
144
+ if (run.status !== 0) fail(`vb ${args.join(' ')}: ${run.stderr.trim() || `exit ${run.status}`}`);
145
+ return run.stdout;
146
+ }
147
+
148
+ /** The board's CLI's answer as JSON. */
149
+ export const vbJson = <T>(args: string[]): T => JSON.parse(vb([...args, '--json'])) as T;
150
+
151
+ /** Runs the board's CLI on this terminal, and answers its exit code. */
152
+ export function vbHere(args: string[]): number {
153
+ const [command, argv, options] = vbCommand(args);
154
+ const run = spawnSync(command, argv, { ...options, stdio: 'inherit' });
155
+ if (run.error) unreachable(run.error.message);
156
+ return run.status ?? 1;
157
+ }
158
+
159
+ /** Whether the board answers now, as whoever the CLI writes as: asked of one that may be starting again. */
160
+ export function answers(): boolean {
161
+ const [command, argv, options] = vbCommand(['whoami', '--json']);
162
+ return spawnSync(command, argv, { ...options, encoding: 'utf8' }).status === 0;
163
+ }
164
+
165
+ /**
166
+ * Who the CLI writes as. `profile` is the name `BOARD_PROFILE` (or `--as`) gave, and `null` without one: then what's
167
+ * written is the person's own, as the board sees it.
168
+ */
169
+ export interface Me {
170
+ actor: string;
171
+ handle?: string;
172
+ name?: string;
173
+ profile: string | null;
174
+ }
175
+
176
+ export const whoami = () => vbJson<Me>(['whoami']);
177
+
178
+ export interface Attachment {
179
+ id: string;
180
+ name: string;
181
+ type: string;
182
+ size: number;
183
+ }
184
+
185
+ export interface Message {
186
+ id: number;
187
+ channel: string;
188
+ text: string;
189
+ labels: Record<string, string>;
190
+ attachments: Attachment[];
191
+ createdAt: string;
192
+ by: { actor: string };
193
+ author?: { handle?: string };
194
+ task?: { state: string; claim?: { actor: string; until: string }; result?: string; reason?: string };
195
+ }
196
+
197
+ /** A task's root message and its replies, by its ID (`68` or `#68`). */
198
+ export const read = (id: string) => vbJson<{ message: Message; replies: Message[] }>(['read', id.replace(/^#/, '')]);
199
+
200
+ /** A task's root message. */
201
+ export const task = (id: string) => read(id).message;
202
+
203
+ /** Writes an attachment to a file. */
204
+ export const download = (attachment: Attachment, path: string) => vb(['download', attachment.id, path]);
package/src/cli/bun.ts ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * `init` for Bun's own dev server: `Bun.serve` with HTML imports, which bundles the page with the plugins bunfig.toml
3
+ * names. Only that: a Bun project that runs Vite, Next.js or another bundler is that bundler's, and one with no HTML
4
+ * imports has no page of Bun's for deictic to be in. Three steps, as the API has them: the plugin's module, bunfig's
5
+ * `[serve.static] plugins`, and its routes spread into `Bun.serve`'s.
6
+ */
7
+ import { readdirSync, readFileSync } from 'node:fs';
8
+ import { dirname, join, relative } from 'node:path';
9
+
10
+ import MagicString from 'magic-string';
11
+ import { type CallExpression, parseSync, Visitor } from 'oxc-parser';
12
+
13
+ import { addFirst, addImports, eolOf } from './edit.ts';
14
+
15
+ /** The plugin's module, from the root, which bunfig names and the server imports. */
16
+ export const MODULE = 'deictic.plugin.ts';
17
+
18
+ export const PLUGIN = `import { deictic } from 'deictic/bun';
19
+ import { recommended } from 'deictic/recommended';
20
+
21
+ // One module for both: bunfig.toml names it as the dev server's bundler plugin, and the server spreads its routes,
22
+ // deictic's endpoints, into its own.
23
+ export default deictic({ plugins: recommended() });
24
+ `;
25
+
26
+ const SOURCE = /\.[cm]?[jt]sx?$/;
27
+ const SKIP = new Set(['node_modules', 'dist', 'build', 'out']);
28
+ const SERVE = /\bBun\.serve\s*\(/;
29
+ const HTML = /\bfrom\s*['"][^'"]+\.html['"]/;
30
+
31
+ /**
32
+ * The module that serves the page with Bun's bundler: it calls `Bun.serve` and imports an HTML file. Looked for under
33
+ * the root, not in dependencies, builds or dot folders, a few folders deep.
34
+ */
35
+ export function serverOf(root: string): string | undefined {
36
+ const walk = (dir: string, depth: number): string | undefined => {
37
+ let entries;
38
+ try {
39
+ entries = readdirSync(dir, { withFileTypes: true });
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ for (const e of entries) {
44
+ if (!e.isFile() || !SOURCE.test(e.name)) continue;
45
+ const path = join(dir, e.name);
46
+ const code = readFileSync(path, 'utf8');
47
+ if (SERVE.test(code) && HTML.test(code)) return path;
48
+ }
49
+ if (depth === 0) return undefined;
50
+ for (const e of entries) {
51
+ if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;
52
+ const found = walk(join(dir, e.name), depth - 1);
53
+ if (found !== undefined) return found;
54
+ }
55
+ return undefined;
56
+ };
57
+ return walk(root, 3);
58
+ }
59
+
60
+ /**
61
+ * bunfig.toml with the plugin's module first in `[serve.static] plugins` (first, so it sees the source as written),
62
+ * made where there's none; unchanged where it's there already, and nothing where bunfig says it another way (a dotted
63
+ * key, an inline table) and it can't tell where.
64
+ */
65
+ export function addToBunfig(text: string | undefined, entry = `./${MODULE}`): string | undefined {
66
+ const quoted = JSON.stringify(entry);
67
+ if (text === undefined) return `[serve.static]\nplugins = [${quoted}]\n`;
68
+ if (text.includes(entry)) return text;
69
+ if (/serve\.static\.|static\s*=\s*\{/.test(text)) return undefined;
70
+ const eol = eolOf(text);
71
+ const header = /^[ \t]*\[serve\.static\][ \t]*(#.*)?$/m.exec(text);
72
+ if (header === null)
73
+ return `${text}${text === '' || text.endsWith('\n') ? '' : eol}${eol}[serve.static]${eol}plugins = [${quoted}]${eol}`;
74
+ const bodyStart = header.index + header[0].length;
75
+ const next = /^[ \t]*\[/m.exec(text.slice(bodyStart));
76
+ const body = text.slice(bodyStart, next === null ? text.length : bodyStart + next.index);
77
+ const list = /^[ \t]*plugins[ \t]*=[ \t]*\[/m.exec(body);
78
+ if (list === null) return `${text.slice(0, bodyStart)}${eol}plugins = [${quoted}]${text.slice(bodyStart)}`;
79
+ const open = bodyStart + list.index + list[0].length;
80
+ const rest = text.slice(open);
81
+ const empty = /^\s*\]/.test(rest);
82
+ const lineBreak = /^[ \t]*\r?\n([ \t]*)/.exec(rest);
83
+ if (empty) return `${text.slice(0, open)}${quoted}${rest.trimStart()}`;
84
+ if (lineBreak !== null) return `${text.slice(0, open)}${eol}${lineBreak[1]}${quoted},${rest}`;
85
+ return `${text.slice(0, open)}${quoted}, ${rest.trimStart()}`;
86
+ }
87
+
88
+ /**
89
+ * The server with the plugin's routes first in `Bun.serve`'s `routes`, or `routes` with them where it has none, and
90
+ * the module imported: nothing where `Bun.serve` isn't given an object it can see, or its routes aren't one.
91
+ */
92
+ export function addToServer(file: string, code: string, root: string): string | undefined {
93
+ const { program, errors } = parseSync(file, code, { preserveParens: false });
94
+ if (errors.length > 0) return undefined;
95
+ const calls: CallExpression[] = [];
96
+ new Visitor({
97
+ CallExpression(node) {
98
+ const { callee } = node;
99
+ if (
100
+ callee.type === 'MemberExpression' &&
101
+ callee.object.type === 'Identifier' &&
102
+ callee.object.name === 'Bun' &&
103
+ callee.property.type === 'Identifier' &&
104
+ callee.property.name === 'serve'
105
+ )
106
+ calls.push(node);
107
+ },
108
+ }).visit(program);
109
+ const options = calls.length === 1 ? calls[0]!.arguments[0] : undefined;
110
+ if (options?.type !== 'ObjectExpression') return undefined;
111
+
112
+ // `tools`, as the API names it, unless the module has a `tools` of its own.
113
+ const name = /\btools\b/.test(code) ? 'deicticTools' : 'tools';
114
+ const out = new MagicString(code);
115
+ const routes = options.properties.find(
116
+ (p) => p.type === 'Property' && !p.computed && p.key.type === 'Identifier' && p.key.name === 'routes',
117
+ );
118
+ if (routes === undefined) {
119
+ addFirst(out, code, options.start, options.properties[0], `routes: { ...${name}.routes }`);
120
+ } else {
121
+ if (routes.type !== 'Property' || routes.value.type !== 'ObjectExpression') return undefined;
122
+ addFirst(out, code, routes.value.start, routes.value.properties[0], `...${name}.routes`);
123
+ }
124
+ const from = relative(dirname(file), join(root, MODULE)).replaceAll('\\', '/');
125
+ addImports(out, program, code, [[name, from.startsWith('.') ? from : `./${from}`]]);
126
+ return out.toString();
127
+ }
128
+
129
+ /** What to add by hand, for a server or a bunfig it can't edit. */
130
+ export const BY_HAND = {
131
+ bunfig: `[serve.static]\nplugins = ["./${MODULE}"]`,
132
+ server: `import tools from './${MODULE}';\nBun.serve({ routes: { ...tools.routes, '/*': index } });`,
133
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Editing a project's own source the way it's written: its quotes, semicolons, line endings and indentation. What
3
+ * `init` adds to a bundler's config and to a Bun server goes through here.
4
+ */
5
+ import type MagicString from 'magic-string';
6
+ import type { Program } from 'oxc-parser';
7
+
8
+ /** The file's line ending. */
9
+ export const eolOf = (code: string) => (code.includes('\r\n') ? '\r\n' : '\n');
10
+
11
+ /** The whitespace a line starts with, for the line `offset` is on. */
12
+ export function indentAt(code: string, offset: number): string {
13
+ const start = code.lastIndexOf('\n', offset - 1) + 1;
14
+ return /^[ \t]*/.exec(code.slice(start))![0];
15
+ }
16
+
17
+ /**
18
+ * Adds import lines after the module's last import (or `require`, in CommonJS), or at its top: written in the quotes
19
+ * and semicolons of its first import. Each line is `[what, from]`: `import ${what} from '${from}'`, or as a `require`.
20
+ */
21
+ export function addImports(out: MagicString, program: Program, code: string, lines: [string, string][], commonjs = false): void {
22
+ const eol = eolOf(code);
23
+ const imports = program.body.filter((s) => s.type === 'ImportDeclaration');
24
+ const first = imports[0];
25
+ const quote = first === undefined ? "'" : code[first.source.start]!;
26
+ const semi = first === undefined || code.slice(first.start, first.end).trimEnd().endsWith(';') ? ';' : '';
27
+ const q = (s: string) => `${quote}${s}${quote}`;
28
+ const text = lines
29
+ .map(([what, from]) => (commonjs ? `const ${what} = require(${q(from)})${semi}` : `import ${what} from ${q(from)}${semi}`))
30
+ .join(eol);
31
+ const after = imports.at(-1) ?? requiresOf(program).at(-1);
32
+ if (after === undefined) out.prepend(`${text}${eol}${eol}`);
33
+ else out.appendLeft(after.end, `${eol}${text}`);
34
+ }
35
+
36
+ /** The top-level `const … = require(…)` statements of a CommonJS module, to put new ones after. */
37
+ function requiresOf(program: Program) {
38
+ return program.body.filter(
39
+ (s) =>
40
+ s.type === 'VariableDeclaration' &&
41
+ s.declarations.some(
42
+ (d) => d.init?.type === 'CallExpression' && d.init.callee.type === 'Identifier' && d.init.callee.name === 'require',
43
+ ),
44
+ );
45
+ }
46
+
47
+ /** Inserts `text` as the first property of the object literal that starts at `open` (its `{`), as the object is laid out. */
48
+ export function addFirst(out: MagicString, code: string, open: number, first: { start: number } | undefined, text: string): void {
49
+ const eol = eolOf(code);
50
+ if (first === undefined) {
51
+ out.appendLeft(open + 1, ` ${text} `);
52
+ return;
53
+ }
54
+ const multiline = code.slice(open, first.start).includes('\n');
55
+ out.appendLeft(first.start, multiline ? `${text},${eol}${indentAt(code, first.start)}` : `${text}, `);
56
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Finding what a task carries: a recording or a voice clip, by a task's ID, a recording's ID, a replay URL or a path,
3
+ * kept under a `.deictic/` near here or downloaded from the board. And the tools outside deictic some commands run
4
+ * (ffmpeg, the project's Playwright).
5
+ */
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync, mkdtempSync, readdirSync, readFileSync } from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+
13
+ import type { Kept } from '#src/plugins/recordings/index.ts';
14
+
15
+ import { deicticDirs, download, fail, type Message, task } from './board.ts';
16
+
17
+ const TASK = /^#?\d+$/;
18
+
19
+ export interface Found {
20
+ kept: Kept;
21
+ id: string;
22
+ /** Where it replays, where that's known. */
23
+ replay?: string;
24
+ /** The task it's attached to, where it was found by one. */
25
+ task?: Message;
26
+ }
27
+
28
+ const parsed = (path: string) => JSON.parse(readFileSync(path, 'utf8')) as Kept;
29
+
30
+ /** An attachment of a task, written to a temporary folder: its path. */
31
+ function fetched(root: Message, name: string): string {
32
+ const file = root.attachments.find((a) => a.name === name);
33
+ if (file === undefined) fail(`Task #${root.id} has no ${name}.`);
34
+ const path = join(mkdtempSync(join(tmpdir(), 'deictic-')), file.name);
35
+ download(file, path);
36
+ return path;
37
+ }
38
+
39
+ /**
40
+ * A recording, with where it came from. `ref` is a task's ID (its first recording, or the `nth`), a replay or
41
+ * recording URL, a recording's ID kept under a `.deictic/`, or a path.
42
+ */
43
+ export async function loadRecording(ref: string | undefined, nth = 1): Promise<Found> {
44
+ if (ref === undefined) fail('Name a recording: a task (68), a replay URL, a recording ID or a JSON file.');
45
+ if (TASK.test(ref)) {
46
+ const root = task(ref);
47
+ const files = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
48
+ const file = files[nth - 1];
49
+ if (file === undefined) fail(`Task #${root.id} has ${files.length} recording(s), not a ${nth}th.`);
50
+ const id = file.name.slice('recording-'.length, -'.json'.length);
51
+ const replay = new RegExp(`https?://\\S+/replay/${id}`).exec(root.text)?.[0];
52
+ return { kept: parsed(fetched(root, file.name)), id, replay, task: root };
53
+ }
54
+ if (/^https?:/.test(ref)) {
55
+ const url = new URL(ref);
56
+ const id = url.pathname.split('/').at(-1) ?? '';
57
+ const json = new URL(url.pathname.replace(/\/(replay|recording)\/[^/]+$/, `/recording/${id}`), url);
58
+ const res = await fetch(json);
59
+ if (!res.ok) fail(`${json.href}: ${res.status} ${await res.text()}`);
60
+ return { kept: (await res.json()) as Kept, id, replay: new URL(json.pathname.replace(/\/recording\//, '/replay/'), url).href };
61
+ }
62
+ if (existsSync(ref)) return { kept: parsed(ref), id: ref.replace(/^.*[\\/]|\.json$/g, '') };
63
+ for (const dir of deicticDirs()) {
64
+ const path = join(dir, 'recordings', `${ref}.json`);
65
+ if (existsSync(path)) return { kept: parsed(path), id: ref };
66
+ }
67
+ return fail(`No recording ${ref} in ${deicticDirs().join(', ') || 'any .deictic/ near here'}: name its task or replay URL instead.`);
68
+ }
69
+
70
+ /** A voice clip kept under a `.deictic/` near here, by its ID. */
71
+ function keptClip(id: string): string | undefined {
72
+ for (const dir of deicticDirs()) {
73
+ const voice = join(dir, 'voice');
74
+ const name = existsSync(voice) ? readdirSync(voice).find((f) => f.startsWith(`${id}.`)) : undefined;
75
+ if (name !== undefined) return join(voice, name);
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ /** A voice clip's audio as a file: kept under a `.deictic/`, or downloaded from `from`. */
81
+ function voiceFile(id: string, from?: Message): string {
82
+ const kept = keptClip(id);
83
+ if (kept !== undefined) return kept;
84
+ const file = from?.attachments.find((a) => a.name.startsWith(`voice-${id}.`));
85
+ if (from === undefined || file === undefined) fail(`No voice clip ${id} here${from ? ` or on task #${from.id}` : ''}.`);
86
+ return fetched(from, file.name);
87
+ }
88
+
89
+ export interface Clip {
90
+ id: string;
91
+ file: string;
92
+ /** Where it starts in its recording, or 0 for a voice note on its own. */
93
+ at: number;
94
+ recording?: string;
95
+ }
96
+
97
+ /**
98
+ * The voice clips `ref` names: a task (every recording's clips and its voice notes), a recording as `loadRecording`
99
+ * takes one, or a clip's ID.
100
+ */
101
+ export async function voiceClips(ref: string | undefined): Promise<Clip[]> {
102
+ if (ref === undefined) fail('Name a task, a recording or a voice clip.');
103
+ const clips: Clip[] = [];
104
+ if (TASK.test(ref)) {
105
+ const root = task(ref);
106
+ const recordings = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
107
+ const inRecordings = new Set<string>();
108
+ for (let n = 1; n <= recordings.length; n++) {
109
+ const { kept, id } = await loadRecording(ref, n);
110
+ for (const c of kept.voice ?? []) {
111
+ inRecordings.add(c.id);
112
+ clips.push({ id: c.id, file: voiceFile(c.id, root), at: c.at, recording: id });
113
+ }
114
+ }
115
+ for (const a of root.attachments) {
116
+ const id = /^voice-(.+)\.\w+$/.exec(a.name)?.[1];
117
+ if (id !== undefined && !inRecordings.has(id)) clips.push({ id, file: voiceFile(id, root), at: 0 });
118
+ }
119
+ } else if (!/^https?:/.test(ref) && !existsSync(ref) && keptClip(ref) !== undefined) {
120
+ clips.push({ id: ref, file: voiceFile(ref), at: 0 });
121
+ } else {
122
+ const { kept, id } = await loadRecording(ref);
123
+ for (const c of kept.voice ?? []) clips.push({ id: c.id, file: voiceFile(c.id), at: c.at, recording: id });
124
+ }
125
+ if (clips.length === 0) fail(`No voice on ${ref}.`);
126
+ return clips;
127
+ }
128
+
129
+ /** Runs ffmpeg, which reads what MediaRecorder makes, and answers its log (stderr) and what it wrote to stdout. */
130
+ export function ffmpeg(args: string[]): { stdout: Buffer; log: string } {
131
+ const run = spawnSync('ffmpeg', ['-hide_banner', '-nostats', ...args], { maxBuffer: 1 << 30 });
132
+ if (run.error) fail('Needs ffmpeg on the PATH (https://ffmpeg.org/download.html).');
133
+ return { stdout: run.stdout, log: run.stderr.toString('utf8') };
134
+ }
135
+
136
+ /** The project's own copy of a package deictic doesn't bring (Playwright, either of its names), from here. */
137
+ export async function fromProject<T>(...names: string[]): Promise<T> {
138
+ const project = createRequire(join(process.cwd(), 'package.json'));
139
+ for (const name of names) {
140
+ try {
141
+ return (await import(pathToFileURL(project.resolve(name)).href)) as T;
142
+ } catch {
143
+ // Not this one: the next name.
144
+ }
145
+ }
146
+ return fail(`Needs ${names.join(' or ')} in the project: npm install -D ${names[0]}`);
147
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `deictic frame`: screenshots of a recording at moments of it, as its replay page shows them (marks and pointer
3
+ * included), at the recorded viewport's size. By default: just after each change to the marks, and the end. Needs
4
+ * the dev server running (it serves the replay) and Playwright in the project.
5
+ */
6
+ import { mkdirSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { join, resolve } from 'node:path';
9
+
10
+ import type { Browser, chromium } from 'playwright-core';
11
+
12
+ import { clock, fail, parseArgs } from './board.ts';
13
+ import { fromProject, loadRecording } from './find.ts';
14
+
15
+ export const usage =
16
+ 'frame <task | replay URL | recording ID | file> [--at 4.2 ...] [--every 2] [--out dir] [--base url] PNGs of a recording';
17
+
18
+ interface Marks {
19
+ type: number;
20
+ timestamp: number;
21
+ data: { tag?: string; payload?: { svg?: string } };
22
+ }
23
+
24
+ export async function run(args: string[]): Promise<void> {
25
+ const { values, positionals } = parseArgs(args, {
26
+ nth: { type: 'string', default: '1' },
27
+ at: { type: 'string', multiple: true },
28
+ every: { type: 'string' },
29
+ out: { type: 'string' },
30
+ base: { type: 'string' },
31
+ });
32
+ const { kept, id, replay } = await loadRecording(positionals[0], Number(values.nth));
33
+ // The replay is served by the dev server that recorded it, under deictic's routes.
34
+ const page =
35
+ values.base === undefined
36
+ ? (replay ?? `${new URL(kept.page).origin}/__deictic/plugins/recordings/replay/${id}`)
37
+ : `${values.base.replace(/\/$/, '')}/__deictic/plugins/recordings/replay/${id}`;
38
+
39
+ const events = kept.events as Marks[];
40
+ const t0 = events[0]?.timestamp ?? 0;
41
+ const end = kept.duration / 1000;
42
+ let times = (values.at ?? []).map(Number);
43
+ if (values.every !== undefined) for (let t = 0; t <= end; t += Number(values.every)) times.push(t);
44
+ if (times.length === 0) {
45
+ // Just after each change to the marks, so it's drawn, then the end.
46
+ const marks = events.filter((e) => e.type === 5 && e.data.tag === 'deictic.annotations' && (e.data.payload?.svg ?? '') !== '');
47
+ times = [...marks.map((e) => (e.timestamp - t0 + 50) / 1000), end];
48
+ }
49
+ times = [...new Set(times.map((t) => Math.min(Math.max(0, t), end)))].sort((a, b) => a - b);
50
+ if (times.some((t) => !Number.isFinite(t))) fail('--at and --every take seconds: --at 4.2');
51
+
52
+ const out = resolve(values.out ?? join(tmpdir(), 'deictic-frames', id));
53
+ mkdirSync(out, { recursive: true });
54
+
55
+ const playwright = await fromProject<{ chromium: typeof chromium }>('playwright-core', 'playwright');
56
+ let browser: Browser | undefined;
57
+ for (const channel of [undefined, 'chrome', 'msedge']) {
58
+ try {
59
+ browser = await playwright.chromium.launch(channel === undefined ? {} : { channel });
60
+ break;
61
+ } catch {
62
+ // Not this one: the next.
63
+ }
64
+ }
65
+ if (browser === undefined) fail('No Chromium to launch: npx playwright install chromium, or install Chrome or Edge.');
66
+ try {
67
+ // `bare`: the replay alone, at the recorded size, so a window that size shows it 1:1.
68
+ const view = await browser.newPage({ viewport: kept.viewport });
69
+ for (const t of times) {
70
+ const url = new URL(page);
71
+ url.searchParams.set('t', t.toFixed(2));
72
+ url.searchParams.set('bare', '');
73
+ const res = await view.goto(url.href).catch((e: unknown) => (e instanceof Error ? e.message.split('\n')[0] : String(e)));
74
+ if (typeof res === 'string' || !res?.ok()) {
75
+ const why = typeof res === 'string' ? res : String(res?.status());
76
+ await browser.close();
77
+ fail(`${url.href}: ${why}. Is the dev server running? Start it, or pass --base with its URL.`);
78
+ }
79
+ await view.waitForSelector('body[data-ready]', { timeout: 15_000 });
80
+ // The replayed page's images and fonts.
81
+ await view.waitForLoadState('networkidle').catch(() => {});
82
+ await view.waitForTimeout(200);
83
+ const path = join(out, `${String(Math.round(t * 1000)).padStart(6, '0')}.png`);
84
+ await view.screenshot({ path });
85
+ console.log(`${clock(t * 1000).padStart(6)} ${path}`);
86
+ }
87
+ } finally {
88
+ await browser.close();
89
+ }
90
+ }