deictic 0.0.0-stage → 0.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.
Files changed (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -2
  3. package/dist/annotations/client.d.ts +4 -0
  4. package/dist/annotations/client.d.ts.map +1 -0
  5. package/dist/annotations/client.js +497 -0
  6. package/dist/annotations/client.js.map +1 -0
  7. package/dist/annotations/index.d.ts +110 -0
  8. package/dist/annotations/index.d.ts.map +1 -0
  9. package/dist/annotations/index.js +22 -0
  10. package/dist/annotations/index.js.map +1 -0
  11. package/dist/astro.d.ts +29 -0
  12. package/dist/astro.d.ts.map +1 -0
  13. package/dist/astro.js +24 -0
  14. package/dist/astro.js.map +1 -0
  15. package/dist/bun.d.ts +12 -0
  16. package/dist/bun.d.ts.map +1 -0
  17. package/dist/bun.js +67 -0
  18. package/dist/bun.js.map +1 -0
  19. package/dist/client/index.d.ts +93 -0
  20. package/dist/client/index.d.ts.map +1 -0
  21. package/dist/client/index.js +1329 -0
  22. package/dist/client/index.js.map +1 -0
  23. package/dist/endpoints.js +354 -0
  24. package/dist/endpoints.js.map +1 -0
  25. package/dist/index.d.ts +220 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +10 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/index2.d.ts +23 -0
  30. package/dist/index3.d.ts +98 -0
  31. package/dist/index3.d.ts.map +1 -0
  32. package/dist/index4.d.ts +74 -0
  33. package/dist/index4.d.ts.map +1 -0
  34. package/dist/index5.d.ts +70 -0
  35. package/dist/index5.d.ts.map +1 -0
  36. package/dist/integration.d.ts +19 -0
  37. package/dist/integration.d.ts.map +1 -0
  38. package/dist/integration.js +277 -0
  39. package/dist/integration.js.map +1 -0
  40. package/dist/kept.js +23 -0
  41. package/dist/kept.js.map +1 -0
  42. package/dist/loader.d.ts +15 -0
  43. package/dist/loader.d.ts.map +1 -0
  44. package/dist/loader.js +17 -0
  45. package/dist/loader.js.map +1 -0
  46. package/dist/marks.js +14 -0
  47. package/dist/marks.js.map +1 -0
  48. package/dist/next.d.ts +17 -0
  49. package/dist/next.d.ts.map +1 -0
  50. package/dist/next.js +150 -0
  51. package/dist/next.js.map +1 -0
  52. package/dist/playwright.js +105 -0
  53. package/dist/playwright.js.map +1 -0
  54. package/dist/recommended/index.d.ts +25 -0
  55. package/dist/recommended/index.d.ts.map +1 -0
  56. package/dist/recommended/index.js +19 -0
  57. package/dist/recommended/index.js.map +1 -0
  58. package/dist/recordings/client.d.ts +4 -0
  59. package/dist/recordings/client.d.ts.map +1 -0
  60. package/dist/recordings/client.js +376 -0
  61. package/dist/recordings/client.js.map +1 -0
  62. package/dist/recordings/index.d.ts +2 -0
  63. package/dist/recordings/index.js +3 -0
  64. package/dist/recordings.js +235 -0
  65. package/dist/recordings.js.map +1 -0
  66. package/dist/screenshots/client.d.ts +23 -0
  67. package/dist/screenshots/client.d.ts.map +1 -0
  68. package/dist/screenshots/client.js +76 -0
  69. package/dist/screenshots/client.js.map +1 -0
  70. package/dist/screenshots/dom.d.ts +4 -0
  71. package/dist/screenshots/dom.d.ts.map +1 -0
  72. package/dist/screenshots/dom.js +92 -0
  73. package/dist/screenshots/dom.js.map +1 -0
  74. package/dist/screenshots/index.d.ts +2 -0
  75. package/dist/screenshots/index.js +98 -0
  76. package/dist/screenshots/index.js.map +1 -0
  77. package/dist/screenshots/rrweb.d.ts +9 -0
  78. package/dist/screenshots/rrweb.d.ts.map +1 -0
  79. package/dist/screenshots/rrweb.js +60 -0
  80. package/dist/screenshots/rrweb.js.map +1 -0
  81. package/dist/shortcut.js +63 -0
  82. package/dist/shortcut.js.map +1 -0
  83. package/dist/tailwind/client.d.ts +4 -0
  84. package/dist/tailwind/client.d.ts.map +1 -0
  85. package/dist/tailwind/client.js +613 -0
  86. package/dist/tailwind/client.js.map +1 -0
  87. package/dist/tailwind/index.d.ts +2 -0
  88. package/dist/tailwind/index.js +557 -0
  89. package/dist/tailwind/index.js.map +1 -0
  90. package/dist/tasks/client.d.ts +6 -0
  91. package/dist/tasks/client.d.ts.map +1 -0
  92. package/dist/tasks/client.js +642 -0
  93. package/dist/tasks/client.js.map +1 -0
  94. package/dist/tasks/index.d.ts +159 -0
  95. package/dist/tasks/index.d.ts.map +1 -0
  96. package/dist/tasks/index.js +348 -0
  97. package/dist/tasks/index.js.map +1 -0
  98. package/dist/vite.d.ts +17 -0
  99. package/dist/vite.d.ts.map +1 -0
  100. package/dist/vite.js +44 -0
  101. package/dist/vite.js.map +1 -0
  102. package/dist/voice/client.d.ts +4 -0
  103. package/dist/voice/client.d.ts.map +1 -0
  104. package/dist/voice/client.js +66 -0
  105. package/dist/voice/client.js.map +1 -0
  106. package/dist/voice/index.d.ts +47 -0
  107. package/dist/voice/index.d.ts.map +1 -0
  108. package/dist/voice/index.js +74 -0
  109. package/dist/voice/index.js.map +1 -0
  110. package/dist/waveform.js +93 -0
  111. package/dist/waveform.js.map +1 -0
  112. package/dist/webpack.d.ts +50 -0
  113. package/dist/webpack.d.ts.map +1 -0
  114. package/dist/webpack.js +78 -0
  115. package/dist/webpack.js.map +1 -0
  116. package/package.json +313 -4
  117. package/skills/deictic/SKILL.md +47 -0
  118. package/skills/deictic/references/install.md +81 -0
  119. package/skills/deictic/references/recordings.md +83 -0
  120. package/skills/deictic/references/tasks.md +79 -0
  121. package/skills/deictic/references/watch.md +43 -0
  122. package/skills/deictic/scripts/frame.mjs +62 -0
  123. package/skills/deictic/scripts/lib.mjs +193 -0
  124. package/skills/deictic/scripts/recording.mjs +186 -0
  125. package/skills/deictic/scripts/task.mjs +84 -0
  126. package/skills/deictic/scripts/transcribe.mjs +93 -0
  127. package/skills/deictic/scripts/voice.mjs +50 -0
  128. package/skills/deictic/scripts/watch.mjs +51 -0
  129. package/src/astro.ts +34 -0
  130. package/src/bun.ts +79 -0
  131. package/src/client/index.ts +833 -0
  132. package/src/client/lightbox.ts +256 -0
  133. package/src/client/style.ts +243 -0
  134. package/src/client/tooltip.ts +78 -0
  135. package/src/client/waveform.ts +98 -0
  136. package/src/index.ts +240 -0
  137. package/src/loader.ts +28 -0
  138. package/src/next.ts +133 -0
  139. package/src/plugins/annotations/client.ts +301 -0
  140. package/src/plugins/annotations/draw.ts +169 -0
  141. package/src/plugins/annotations/index.ts +105 -0
  142. package/src/plugins/annotations/svg.ts +61 -0
  143. package/src/plugins/recommended/index.ts +35 -0
  144. package/src/plugins/recordings/client.ts +315 -0
  145. package/src/plugins/recordings/index.ts +174 -0
  146. package/src/plugins/recordings/marks.ts +11 -0
  147. package/src/plugins/recordings/ours.ts +70 -0
  148. package/src/plugins/recordings/replay.ts +139 -0
  149. package/src/plugins/screenshots/client.ts +63 -0
  150. package/src/plugins/screenshots/dom.ts +79 -0
  151. package/src/plugins/screenshots/index.ts +194 -0
  152. package/src/plugins/screenshots/playwright.ts +119 -0
  153. package/src/plugins/screenshots/rrweb.ts +45 -0
  154. package/src/plugins/tailwind/catalog.ts +396 -0
  155. package/src/plugins/tailwind/client.ts +669 -0
  156. package/src/plugins/tailwind/index.ts +267 -0
  157. package/src/plugins/tasks/client.ts +622 -0
  158. package/src/plugins/tasks/index.ts +513 -0
  159. package/src/plugins/voice/client.ts +57 -0
  160. package/src/plugins/voice/index.ts +114 -0
  161. package/src/shortcut.ts +83 -0
  162. package/src/tools/astro.ts +81 -0
  163. package/src/tools/editor.ts +22 -0
  164. package/src/tools/endpoints.ts +163 -0
  165. package/src/tools/history.ts +203 -0
  166. package/src/tools/integration.ts +106 -0
  167. package/src/tools/kept.ts +21 -0
  168. package/src/tools/locate.ts +94 -0
  169. package/src/tools/plugins.ts +41 -0
  170. package/src/tools/source.ts +72 -0
  171. package/src/vite.ts +62 -0
  172. package/src/webpack.ts +107 -0
@@ -0,0 +1,513 @@
1
+ /**
2
+ * `deictic/tasks`: open its tab on an element to add a task about it to a Vercel Board
3
+ * (`@vercel/board`). The task says what to change, in the words typed, and where: the element's file,
4
+ * line and tag, the page and the project, all as labels beside the short facts (viewport, how many, where
5
+ * it is in the shot). Whatever works the board's tasks (a person, or an agent of theirs claiming them) takes it
6
+ * from there; deictic only adds them.
7
+ *
8
+ * Adding one is a change like any other: undo cancels the task, while no one has claimed it, and redo
9
+ * adds it again, as a new task. Each task carries `deictic.at=<file:line:column>`, so the panel
10
+ * lists the ones about the element clicked, until its line moves.
11
+ */
12
+ import { readFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+
15
+ import type { Board } from '@vercel/board';
16
+
17
+ import { definePlugin, Refusal, type ServerContext, type Shortcut, type Source, type Target } from '#src/index.ts';
18
+ // For `use('screenshots')`'s type: the plugin may not be loaded, and nothing of it runs here.
19
+ import type { Recordings } from '#src/plugins/recordings/index.ts';
20
+ import type { Box } from '#src/plugins/screenshots/index.ts';
21
+ import type { Clips } from '#src/plugins/voice/index.ts';
22
+
23
+ /** What the plugin uses of a board: `board()` from `@vercel/board` is one. */
24
+ export type TaskBoard = Pick<Board, 'tasks' | 'thread' | 'discovery' | 'upload' | 'edit'>;
25
+
26
+ export interface TasksOptions {
27
+ /**
28
+ * The board, as `@vercel/board`'s `board()` answers it: by default the one `BOARD_URL` names (`npx vb serve`
29
+ * runs one on this machine), or your team's default board, through `vercel login`.
30
+ */
31
+ board?: TaskBoard;
32
+ /** The channel tasks go to: `deictic` by default. */
33
+ channel?: string;
34
+ /**
35
+ * The project the tasks are about, as the `deictic.project` label, to tell them apart on a board several
36
+ * projects share: by default the `name` in the root's `package.json`, and no label where it has none.
37
+ */
38
+ project?: string;
39
+ /** Labels every task gets besides deictic's own, for whoever works them to filter by (`vb tail --label`). None by default. */
40
+ labels?: Record<string, string>;
41
+ /**
42
+ * Where the panel links the channel to, for a person to see its tasks, and with `task`, where it links
43
+ * that task's ID to. By default the board's own pages when it's one `vb serve` runs on this machine
44
+ * (`http://127.0.0.1:4100/c/deictic`, and `?thread=<id>` on it), and none for another board, whose pages
45
+ * deictic can't know.
46
+ */
47
+ link?: (channel: string, task?: string) => string | undefined;
48
+ /** What opens its tab directly, beside deictic's own shortcut, which opens any: none by default. */
49
+ shortcut?: Shortcut;
50
+ }
51
+
52
+ export interface Task {
53
+ id: string;
54
+ /** The first line of what was typed. */
55
+ title: string;
56
+ /** What was typed, whole: what an edit changes. */
57
+ text: string;
58
+ state: string;
59
+ /** Whether it can still be edited or deleted: no one has claimed it. */
60
+ open: boolean;
61
+ /** Its page on the board, when there's one to link to. */
62
+ link?: string;
63
+ }
64
+
65
+ export interface Model {
66
+ channel: string;
67
+ /** The channel's page, when there's one to link to. */
68
+ link?: string;
69
+ /** Tasks about this element, oldest first, canceled ones left out. */
70
+ tasks: Task[];
71
+ }
72
+
73
+ /**
74
+ * What the Task tab asks for: a new task (an `Op`), other words for one it lists (`edit` is its ID), or
75
+ * that one deleted (`remove` is its ID), which cancels it on the board.
76
+ */
77
+ export type Change = Op | { edit: string; text: string } | { remove: string };
78
+
79
+ /** A new task: what the page knows and the source doesn't. */
80
+ export interface Op {
81
+ text: string;
82
+ /** The page's URL. */
83
+ page: string;
84
+ viewport: { width: number; height: number };
85
+ /**
86
+ * What was under the pointer inside the element, where nothing marked it (a dependency's markup, or a
87
+ * shadow root's): its path from the element, and its HTML, cut short.
88
+ */
89
+ pointed?: { path: string; html: string };
90
+ /** How many elements on the page come from the same place in the source. */
91
+ count: number;
92
+ /**
93
+ * Shots the screenshots plugin took of it, to attach, where that plugin is loaded: each with where the
94
+ * element is in it, and the marks drawn on it in the panel, where there are any.
95
+ */
96
+ screenshots?: { id: string; box: Box; marks?: Marks }[];
97
+ /**
98
+ * Recordings the recordings plugin made, to attach, where that plugin is loaded: how long each ran,
99
+ * where it plays back, and the voice plugin's clips of the mic in it, attached too.
100
+ */
101
+ recordings?: { id: string; duration: number; replay: string; voice?: string[] }[];
102
+ /** Voice notes the voice plugin kept, to attach, where that plugin is loaded, and how long each runs. */
103
+ voice?: { id: string; duration: number }[];
104
+ /** The page's annotations, where that plugin is loaded and there are any: how many, and their notes' text. */
105
+ annotations?: Marks;
106
+ }
107
+
108
+ /**
109
+ * A task the Task tab just added, as the page hears of it: the `detail` of a `deictic:task` event on `window`, for a
110
+ * page that shows its own tasks (deictic's playground lists them as a board does).
111
+ */
112
+ export interface TaskAdded {
113
+ id: string;
114
+ /** The first line of what was typed. */
115
+ title: string;
116
+ state: string;
117
+ channel: string;
118
+ /** The element: its file, line and column, and its tag. */
119
+ target: Target;
120
+ /** The page's URL. */
121
+ page: string;
122
+ /** How many of each were attached; `marks` counts those drawn on shots and on the page. */
123
+ attached: { screenshots: number; recordings: number; voice: number; marks: number };
124
+ }
125
+
126
+ /** Marks, as a task tells of them: how many, and what the notes among them say. */
127
+ export interface Marks {
128
+ count: number;
129
+ notes: string[];
130
+ }
131
+
132
+ export interface Added {
133
+ channel: string;
134
+ id: string;
135
+ text: string;
136
+ labels: Record<string, string>;
137
+ /** What's attached, by the board's IDs: kept, so a redo attaches the same without uploading it again. */
138
+ attachments?: string[];
139
+ }
140
+
141
+ /** A task's words changed: its message's whole text before and after. */
142
+ export interface Edited {
143
+ kind: 'edited';
144
+ id: string;
145
+ before: string;
146
+ after: string;
147
+ }
148
+
149
+ /**
150
+ * A task deleted in the panel: canceled on the board, for good, as a board has it. So it's kept whole, and
151
+ * an undo adds it again, as a new task whose ID the record then has.
152
+ */
153
+ export interface Removed extends Added {
154
+ kind: 'removed';
155
+ }
156
+
157
+ /** What the history keeps of a change: a task added has no `kind`, as it had none before there were others. */
158
+ export type Kept = Added | Edited | Removed;
159
+
160
+ const AT = 'deictic.at';
161
+ /** What parts what was typed from the rest of a task's text. */
162
+ const REST = '\n---\n';
163
+ const OPEN = new Set(['waiting', 'ready', 'blocked']);
164
+
165
+ export function tasks(options: TasksOptions = {}) {
166
+ const channel = options.channel ?? 'deictic';
167
+ let team: Promise<TaskBoard> | undefined;
168
+ // Loaded when first used, so a project that doesn't add this plugin needn't install the SDK.
169
+ const boardOf = () => (team ??= options.board ? Promise.resolve(options.board) : import('@vercel/board').then((m) => m.board()));
170
+ let link: Promise<string | undefined> | undefined;
171
+ // Asked once, unless asking failed: no link is no reason to keep the panel from showing the tasks.
172
+ const linkOf = () =>
173
+ (link ??= (options.link ? Promise.resolve(options.link(channel)) : boardOf().then((b) => localPage(b, channel))).catch(() => {
174
+ link = undefined;
175
+ return undefined;
176
+ }));
177
+ /** A task's page: what `link` says, or its thread on the channel's own page on this machine. */
178
+ const taskLink = (page: string | undefined, id: string) =>
179
+ options.link ? options.link(channel, id) : page === undefined ? undefined : `${page}?thread=${encodeURIComponent(id)}`;
180
+ /**
181
+ * One of this channel's tasks about an element, while it's still open: the page names it by ID, so
182
+ * nothing else on the board is its to change, nor a task someone has taken up.
183
+ */
184
+ const openTask = async (team: TaskBoard, id: string, verb: string) => {
185
+ const { message } = await team.thread(id);
186
+ if (message.channel !== channel || message.labels[AT] === undefined)
187
+ throw new Refusal(`#${id} isn't a task of deictic's in #${channel}: reload the page for the ones that are`);
188
+
189
+ const { task } = message;
190
+ if (task !== undefined && !OPEN.has(task.state)) {
191
+ throw new Refusal(
192
+ `task ${id} is ${task.state}${task.claim ? ` by ${task.claim.actor}` : ''} now: ${verb} it on the board if you still mean to`,
193
+ );
194
+ }
195
+ return message;
196
+ };
197
+ /** Cancels an open task of ours, and answers it as it was. */
198
+ const cancel = async (id: string, reason: string) => {
199
+ const team = await boardOf();
200
+ const message = await openTask(team, id, 'cancel');
201
+ await team.tasks.cancel(id, reason);
202
+ return message;
203
+ };
204
+ /** Puts a task's text from one to the other, unless it reads as neither any more. */
205
+ const rewrite = async (id: string, from: string, to: string) => {
206
+ const team = await boardOf();
207
+ const message = await openTask(team, id, 'edit');
208
+ if (message.text === to) return;
209
+ if (message.text !== from) throw new Refusal(`task ${id} has been edited since: change it on the board`);
210
+ await team.edit(id, to, { revision: message.revision });
211
+ };
212
+ const create = async (record: Omit<Added, 'id'>): Promise<Added> => {
213
+ const { task } = await (
214
+ await boardOf()
215
+ ).tasks.create(record.channel, {
216
+ text: record.text,
217
+ labels: record.labels,
218
+ ...(record.attachments === undefined ? {} : { attachments: record.attachments }),
219
+ });
220
+ return { ...record, id: task.id };
221
+ };
222
+
223
+ // Kept from `setup`, to `use` another plugin when an op asks for it.
224
+ let context: ServerContext | undefined;
225
+ let project = options.project;
226
+ /** The screenshots and recordings to attach, uploaded to the board, or nothing when there are none. */
227
+ const attach = async (op: Op): Promise<string[] | undefined> => {
228
+ // All read first, so one no longer kept uploads none.
229
+ const files = [
230
+ ...(op.screenshots ?? []).map(({ id }) => {
231
+ const shot = context?.use('screenshots')?.read(id);
232
+ if (shot === undefined) throw new Refusal(`screenshot ${id} isn't kept any more: take it again`);
233
+ return shot;
234
+ }),
235
+ ...(op.recordings ?? []).map(({ id }) => {
236
+ const recording: ReturnType<Recordings['read']> = context?.use('recordings')?.read(id);
237
+ if (recording === undefined) throw new Refusal(`recording ${id} isn't kept any more: record it again`);
238
+ return recording;
239
+ }),
240
+ ...[...(op.recordings ?? []).flatMap((r) => r.voice ?? []), ...(op.voice ?? []).map((v) => v.id)].map((id) => {
241
+ const clip: ReturnType<Clips['read']> = context?.use('voice')?.read(id);
242
+ if (clip === undefined) throw new Refusal(`voice clip ${id} isn't kept any more: record it again`);
243
+ return clip;
244
+ }),
245
+ ];
246
+ if (files.length === 0) return undefined;
247
+ const team = await boardOf();
248
+ return Promise.all(files.map(async (file) => (await team.upload(file)).id));
249
+ };
250
+
251
+ return definePlugin<Model, Change, Kept>({
252
+ name: 'tasks',
253
+ client: 'deictic/tasks/client',
254
+ shortcut: options.shortcut,
255
+ setup: (given) => {
256
+ context = given;
257
+ project ??= nameOf(given.root);
258
+ },
259
+ read: (_source, target) =>
260
+ asked(async () => {
261
+ const [{ tasks: found }, page] = await Promise.all([
262
+ (await boardOf()).tasks.list({ channel, label: { [AT]: atOf(target) }, state: 'all' }),
263
+ linkOf(),
264
+ ]);
265
+ return {
266
+ channel,
267
+ ...(page === undefined ? {} : { link: page }),
268
+ tasks: found
269
+ .map(({ message }) => {
270
+ const text = message.text.split(REST, 1)[0]!;
271
+ const state = message.task?.state ?? 'ready';
272
+ const to = taskLink(page, message.id);
273
+ return {
274
+ id: message.id,
275
+ title: text.split('\n', 1)[0]!,
276
+ text,
277
+ state,
278
+ open: OPEN.has(state),
279
+ ...(to === undefined ? {} : { link: to }),
280
+ };
281
+ })
282
+ .filter((t) => t.state !== 'canceled'),
283
+ };
284
+ }),
285
+ apply: (source, target, op) => {
286
+ if ('remove' in op) {
287
+ return asked(async () => {
288
+ const message = await cancel(op.remove, 'deleted in deictic');
289
+ // The board's own labels (`board.task`) are its to set on the task an undo adds.
290
+ const labels = Object.fromEntries(Object.entries(message.labels).filter(([key]) => !key.startsWith('board.')));
291
+ const attachments = message.attachments.map((a) => a.id);
292
+ const kept = { channel, id: op.remove, text: message.text, labels, ...(attachments.length === 0 ? {} : { attachments }) };
293
+ return { done: { kind: 'removed' as const, ...kept } };
294
+ });
295
+ }
296
+ // A new task may go without words where something attached says it; a task's words are never changed to none.
297
+ if (op.text.trim() === '' && ('edit' in op || shown(op) === undefined)) throw new Refusal('say what should change first');
298
+ if ('edit' in op) {
299
+ return asked(async () => {
300
+ const before = (await openTask(await boardOf(), op.edit, 'edit')).text;
301
+ // What follows the words (what's attached, what was pointed at) stays as it was.
302
+ const rest = before.includes(REST) ? before.slice(before.indexOf(REST)) : '';
303
+ const after = clip(op.text.trim(), 10_000 - rest.length) + rest;
304
+ await rewrite(op.edit, before, after);
305
+ return { done: { kind: 'edited' as const, id: op.edit, before, after } };
306
+ });
307
+ }
308
+ const labels = {
309
+ ...options.labels,
310
+ ...(project === undefined ? {} : { 'deictic.project': clip(project, LABEL) }),
311
+ ...labelsOf(source, target, op),
312
+ };
313
+ return asked(async () => {
314
+ const attachments = await attach(op);
315
+ return {
316
+ done: await create({ channel, text: textOf(op), labels, ...(attachments === undefined ? {} : { attachments }) }),
317
+ };
318
+ });
319
+ },
320
+ undo: (record) =>
321
+ asked(async () => {
322
+ if (!('kind' in record)) {
323
+ await cancel(record.id, 'undone in deictic');
324
+ return undefined;
325
+ }
326
+ if (record.kind === 'edited') {
327
+ await rewrite(record.id, record.after, record.before);
328
+ return undefined;
329
+ }
330
+ const { kind, id: _, ...task } = record;
331
+ return { kind, ...(await create(task)) };
332
+ }),
333
+ redo: (record) =>
334
+ asked(async () => {
335
+ if (!('kind' in record)) {
336
+ const { id: _, ...added } = record;
337
+ return create(added);
338
+ }
339
+ if (record.kind === 'edited') {
340
+ await rewrite(record.id, record.before, record.after);
341
+ return record;
342
+ }
343
+ await cancel(record.id, 'deleted in deictic');
344
+ return record;
345
+ }),
346
+ describe: (op, before) => {
347
+ const named = (id: string) => `task "${clip(before.tasks.find((t) => t.id === id)?.title ?? `#${id}`, 60)}"`;
348
+ if ('remove' in op) return `delete ${named(op.remove)}`;
349
+ if ('edit' in op) return `edit ${named(op.edit)}`;
350
+ return `task "${clip(wordsOf(op).split('\n', 1)[0]!, 60)}"`;
351
+ },
352
+ });
353
+ }
354
+
355
+ /**
356
+ * The channel's page on a board `vb serve` runs on this machine, which serves its pages beside its API:
357
+ * `/api/board` there, `/c/<channel>` beside it. Nothing for any other board.
358
+ */
359
+ async function localPage(team: TaskBoard, channel: string): Promise<string | undefined> {
360
+ const url = new URL((await team.discovery()).url);
361
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) || !url.pathname.endsWith('/api/board')) return undefined;
362
+ return `${url.origin}${url.pathname.slice(0, -'/api/board'.length)}/c/${channel.split('/').map(encodeURIComponent).join('/')}`;
363
+ }
364
+
365
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;
366
+ const said = (notes: string[]) => (notes.length === 0 ? '' : `; the notes say: ${notes.map((n) => JSON.stringify(n)).join(', ')}`);
367
+
368
+ /** What was marked on the page: how many marks, and what the notes say. */
369
+ function annotated({ count, notes }: Marks, shots: number, recordings: number): string {
370
+ const where = [
371
+ ...(shots === 0 ? [] : [shots === 1 ? 'the screenshot' : 'the screenshots']),
372
+ ...(recordings === 0 ? [] : [recordings === 1 ? 'the recording' : 'the recordings']),
373
+ ];
374
+ const drawn = where.length === 0 ? '' : `, drawn in ${where.join(' and ')}`;
375
+ return `${plural(count, 'mark')} on the page${drawn}${said(notes)}`;
376
+ }
377
+
378
+ /** How long each recording ran, and where it plays back, while the dev server keeps it. */
379
+ function recordingsOf(recordings: NonNullable<Op['recordings']>): string[] {
380
+ return recordings.map(({ duration, replay, voice }, i) => {
381
+ const name = recordings.length === 1 ? 'A recording' : `Recording ${i + 1}`;
382
+ const spoken = voice === undefined || voice.length === 0 ? '' : `, with the voice (${voice.map((id) => `voice-${id}`).join(', ')})`;
383
+ return `${name}, ${clock(duration)} long, attached as rrweb events${spoken}; it replays at ${replay}`;
384
+ });
385
+ }
386
+
387
+ /** How long each voice note runs, and the attachment it's in. */
388
+ function voicesOf(voice: NonNullable<Op['voice']>): string[] {
389
+ return voice.map(({ id, duration }, i) => {
390
+ const name = voice.length === 1 ? 'A voice note' : `Voice note ${i + 1}`;
391
+ return `${name}, ${clock(duration)} long, attached as voice-${id}`;
392
+ });
393
+ }
394
+
395
+ const clock = (ms: number) => {
396
+ const s = Math.round(ms / 1000);
397
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
398
+ };
399
+
400
+ /**
401
+ * What was drawn on each shot, and with several, where the element is in each: nothing marks it there. One
402
+ * shot's place is the `deictic.position` and `deictic.size` labels, so a shot with no marks has no line.
403
+ */
404
+ function shotsOf(shots: NonNullable<Op['screenshots']>): string[] {
405
+ const [only] = shots;
406
+ if (shots.length === 1 && only !== undefined) {
407
+ const { marks } = only;
408
+ return marks === undefined || marks.count === 0
409
+ ? []
410
+ : [`The screenshot has ${plural(marks.count, 'mark')} drawn on it${said(marks.notes)}`];
411
+ }
412
+ return shots.map(({ box, marks }, i) => {
413
+ const drawn = marks === undefined || marks.count === 0 ? '' : `, with ${plural(marks.count, 'mark')} drawn on it${said(marks.notes)}`;
414
+ const [x, y, width, height] = boxOf(box);
415
+ return `In screenshot ${i + 1} at x ${x}, y ${y}, ${width}×${height}${drawn}`;
416
+ });
417
+ }
418
+
419
+ /** A box as `x,y,width,height`, in whole CSS pixels from the shot's top left. */
420
+ const boxOf = ({ x, y, width, height }: Box) => [x, y, width, height].map(Math.round);
421
+
422
+ /** A label's value: a board holds 256 characters. */
423
+ const LABEL = 256;
424
+
425
+ /** The project's name: the `name` in the root's `package.json`, or nothing where it has none. */
426
+ function nameOf(root: string): string | undefined {
427
+ try {
428
+ const { name } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: unknown };
429
+ return typeof name === 'string' && name !== '' ? name : undefined;
430
+ } catch {
431
+ return undefined;
432
+ }
433
+ }
434
+
435
+ /**
436
+ * The facts about the element, as labels: short values a script reads without parsing the text, and a watch
437
+ * filters by. `deictic.line` is the opening tag's first line as the task saw it, to tell later that it moved.
438
+ * `deictic.url` is the page's whole URL, where a label holds it: `textOf` says a longer one.
439
+ */
440
+ function labelsOf({ code, element }: Source, target: Target, op: Op): Record<string, string> {
441
+ const [shot] = op.screenshots ?? [];
442
+ return {
443
+ [AT]: atOf(target),
444
+ 'deictic.tag': target.tag,
445
+ 'deictic.line': clip(code.slice(element.start, element.end).split('\n', 1)[0]!.trim(), LABEL),
446
+ 'deictic.page': clip(new URL(op.page).pathname, LABEL),
447
+ ...(op.page.length <= LABEL ? { 'deictic.url': op.page } : {}),
448
+ 'deictic.viewport': `${op.viewport.width}x${op.viewport.height}`,
449
+ 'deictic.count': String(op.count),
450
+ ...(op.screenshots?.length === 1 && shot !== undefined ? placeOf(shot.box) : {}),
451
+ };
452
+ }
453
+
454
+ /** Where the element is in the one shot, from its top left, and how big: `87,387` and `138x32`, as the viewport is written. */
455
+ function placeOf(box: Box): Record<string, string> {
456
+ const [x, y, width, height] = boxOf(box);
457
+ return { 'deictic.position': `${x},${y}`, 'deictic.size': `${width}x${height}` };
458
+ }
459
+
460
+ const atOf = ({ loc }: Target) => `${loc.file}:${loc.line}:${loc.column}`;
461
+
462
+ /**
463
+ * The task's text: what was typed, and after a `---` only what no label holds: what's attached and drawn, what
464
+ * was pointed at inside the element, and a URL too long for one. A board holds 10,000 characters.
465
+ */
466
+ function textOf(op: Op): string {
467
+ const more = [
468
+ ...(op.page.length <= LABEL ? [] : [op.page]),
469
+ ...shotsOf(op.screenshots ?? []),
470
+ ...recordingsOf(op.recordings ?? []),
471
+ ...voicesOf(op.voice ?? []),
472
+ ...(op.annotations === undefined ? [] : [annotated(op.annotations, op.screenshots?.length ?? 0, op.recordings?.length ?? 0)]),
473
+ ...(op.pointed === undefined ? [] : [`Pointed at, inside it: \`${op.pointed.path}\``, fence(op.pointed.html, 'html')]),
474
+ ];
475
+ const tail = more.length === 0 ? '' : REST + more.join('\n');
476
+ return clip(wordsOf(op), 10_000 - tail.length) + tail;
477
+ }
478
+
479
+ /** The task's words: what was typed, or where nothing was, a line that sends the reader to what's attached. */
480
+ const wordsOf = (op: Op) => (op.text.trim() === '' ? (shown(op) ?? '') : op.text.trim());
481
+
482
+ /** `See the recording and the voice note`: what stands for the words of a task sent with none, where something is attached. */
483
+ function shown(op: Op): string | undefined {
484
+ const named = (count: number | undefined, word: string) =>
485
+ count === undefined || count === 0 ? [] : [`the ${word}${count === 1 ? '' : 's'}`];
486
+ const attached = [
487
+ ...named(op.screenshots?.length, 'screenshot'),
488
+ ...named(op.recordings?.length, 'recording'),
489
+ ...named(op.voice?.length, 'voice note'),
490
+ ];
491
+ return attached.length === 0 ? undefined : `See ${new Intl.ListFormat('en', { type: 'conjunction' }).format(attached)}`;
492
+ }
493
+
494
+ const fence = (text: string, lang: string) => `\`\`\`\`${lang}\n${clip(text, 1500)}\n\`\`\`\``;
495
+
496
+ const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
497
+
498
+ /** The board's answer, or a `Refusal` saying what to do when there's no board to ask or it said no. */
499
+ async function asked<T>(ask: () => Promise<T>): Promise<T> {
500
+ try {
501
+ return await ask();
502
+ } catch (e) {
503
+ if (e instanceof Refusal) throw e;
504
+ const { code, message, hint } = e as { code?: unknown; message?: string; hint?: string };
505
+ if (typeof code === 'string') throw new Refusal(`the board says: ${message}${hint === undefined ? '' : ` (${hint})`}`, { cause: e });
506
+ throw new Refusal(
507
+ `can't reach the board (${message ?? String(e)}): run \`npx vb serve\` and set BOARD_URL for the dev server, or \`vercel login\``,
508
+ { cause: e },
509
+ );
510
+ }
511
+ }
512
+
513
+ export default tasks;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The voice plugin's page half: `start()` asks for the mic (the browser asks the user the first time) and
3
+ * records it with `MediaRecorder`. `stop` sends the take to the `add` route and lets the mic go, so the
4
+ * browser's recording light goes out between takes.
5
+ */
6
+ import { defineClientPlugin } from '#src/index.ts';
7
+
8
+ import type { Clip, Voice } from './index.ts';
9
+
10
+ /** What the browser can record, best first: Opus in WebM where it can (Chrome, Firefox), else MP4 (Safari). */
11
+ const TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
12
+
13
+ export default defineClientPlugin<never, never, Voice>({
14
+ name: 'voice',
15
+ setup: ({ base, request }) => ({
16
+ start: async () => {
17
+ if (typeof MediaRecorder === 'undefined' || navigator.mediaDevices?.getUserMedia === undefined)
18
+ throw new Error("voice: this browser can't record the mic here: it needs a secure page (https or localhost)");
19
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((e: unknown) => {
20
+ throw new Error(`voice: the mic isn't available: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
21
+ });
22
+ const mimeType = TYPES.find((t) => MediaRecorder.isTypeSupported(t));
23
+ const recorder = new MediaRecorder(stream, mimeType === undefined ? {} : { mimeType });
24
+ const chunks: Blob[] = [];
25
+ recorder.addEventListener('dataavailable', (e) => chunks.push(e.data));
26
+ const started = Date.now();
27
+ recorder.start();
28
+ const release = () => {
29
+ for (const track of stream.getTracks()) track.stop();
30
+ };
31
+ const ended = () =>
32
+ new Promise<void>((done) => {
33
+ if (recorder.state === 'inactive') return done();
34
+ recorder.addEventListener('stop', () => done(), { once: true });
35
+ recorder.stop();
36
+ });
37
+
38
+ return {
39
+ started,
40
+ stream,
41
+ cancel: () => {
42
+ void ended().then(release);
43
+ },
44
+ stop: async (): Promise<Clip> => {
45
+ await ended();
46
+ release();
47
+ const duration = Date.now() - started;
48
+ const type = (recorder.mimeType || mimeType || 'audio/webm').split(';')[0]!;
49
+ const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body: new Blob(chunks, { type }) });
50
+ const { id, problem } = (await res.json()) as { id?: string; problem?: string };
51
+ if (id === undefined) throw new Error(`voice: ${problem ?? res.statusText}`);
52
+ return { id, url: `${base}__deictic/plugins/voice/clip/${id}`, duration, type };
53
+ },
54
+ };
55
+ },
56
+ }),
57
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * `deictic/voice`: records the mic, for other plugins to attach (tasks does) or play along with
3
+ * something (a recording does). No tab of its own. The page half asks for the mic the first time, records
4
+ * with `MediaRecorder` and sends each take to the `add` route; the server half keeps the latest `keep`
5
+ * clips under `.deictic/voice` and serves them at `clip/<id>`.
6
+ */
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { join, resolve } from 'node:path';
9
+
10
+ import { definePlugin } from '#src/index.ts';
11
+ import { keptIn } from '#src/tools/kept.ts';
12
+
13
+ /** A clip as the page knows it: its ID, where it plays from, how long it runs in milliseconds, and its type. */
14
+ export interface Clip {
15
+ id: string;
16
+ url: string;
17
+ duration: number;
18
+ type: string;
19
+ }
20
+
21
+ /** A take going on: `stop` ends it and keeps it, `cancel` ends it and keeps nothing. */
22
+ export interface Take {
23
+ /** When it started, as `Date.now()`. */
24
+ started: number;
25
+ /** The mic, while it's recorded: to show it's heard (`liveWaveform` from `deictic/client`). */
26
+ stream: MediaStream;
27
+ stop(): Promise<Clip>;
28
+ cancel(): void;
29
+ }
30
+
31
+ /** The page's half, for other plugins' page halves. */
32
+ export interface Voice {
33
+ /** Starts recording the mic, asking for it the first time: rejects when it's refused or there's none. */
34
+ start(): Promise<Take>;
35
+ }
36
+
37
+ /** The server's half, for other plugins' server halves. */
38
+ export interface Clips {
39
+ /** A clip's audio, or nothing for one not kept (any more). */
40
+ read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: string } | undefined;
41
+ }
42
+
43
+ declare module 'deictic' {
44
+ interface ServerApis {
45
+ voice: Clips;
46
+ }
47
+ interface ClientApis {
48
+ voice: Voice;
49
+ }
50
+ }
51
+
52
+ export interface VoiceOptions {
53
+ /** How many clips to keep, the latest: 50 by default. */
54
+ keep?: number;
55
+ /** Where they're kept, from the project's root: `.deictic/voice` by default. */
56
+ dir?: string;
57
+ }
58
+
59
+ const ID = /^[a-z0-9]+-[a-z0-9]+$/;
60
+ /** What one clip may weigh: minutes of speech in Opus are well under a MB. */
61
+ const MAX = 25 * 1024 * 1024;
62
+ /** The audio a browser's `MediaRecorder` makes, by the extension it's kept under. */
63
+ const TYPES: Record<string, string> = { webm: 'audio/webm', ogg: 'audio/ogg', mp4: 'audio/mp4' };
64
+
65
+ export function voice(options: VoiceOptions = {}) {
66
+ const keep = options.keep ?? 50;
67
+ let dir = '';
68
+ let taken = 0;
69
+ const fileOf = (id: string) => (ID.test(id) && existsSync(dir) ? readdirSync(dir).find((f) => f.startsWith(`${id}.`)) : undefined);
70
+ const read: Clips['read'] = (id) => {
71
+ const file = fileOf(id);
72
+ if (file === undefined) return undefined;
73
+ const ext = file.slice(id.length + 1);
74
+ return { data: new Uint8Array(readFileSync(join(dir, file))), name: `voice-${file}`, type: TYPES[ext] ?? 'application/octet-stream' };
75
+ };
76
+ const keepClip = (data: Uint8Array, ext: string) => {
77
+ // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.
78
+ const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;
79
+ mkdirSync(dir, { recursive: true });
80
+ writeFileSync(join(dir, `${id}.${ext}`), data);
81
+ const kept = readdirSync(dir).toSorted();
82
+ for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
83
+ return id;
84
+ };
85
+
86
+ return definePlugin<never, never, never, Clips>({
87
+ name: 'voice',
88
+ client: 'deictic/voice/client',
89
+ setup: ({ root }) => {
90
+ dir = options.dir === undefined ? keptIn(root, 'voice') : resolve(root, options.dir);
91
+ return { read };
92
+ },
93
+ routes: {
94
+ // A take the page recorded, as the audio type its `MediaRecorder` made.
95
+ add: async (req) => {
96
+ const type = (req.headers.get('content-type') ?? '').split(';')[0]!.trim();
97
+ const ext = Object.keys(TYPES).find((e) => TYPES[e] === type);
98
+ if (ext === undefined) return Response.json({ problem: `send the clip as ${Object.values(TYPES).join(', ')}` }, { status: 415 });
99
+ const body = new Uint8Array(await req.arrayBuffer());
100
+ if (body.byteLength === 0) return Response.json({ problem: 'the clip is empty: speak for a moment longer' }, { status: 400 });
101
+ if (body.byteLength > MAX) return Response.json({ problem: `a clip may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
102
+ return Response.json({ id: keepClip(body, ext) });
103
+ },
104
+ // `clip/<id>`: the audio, to play back.
105
+ clip: (req) => {
106
+ const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');
107
+ if (found === undefined) return new Response('no such clip, or not kept any more', { status: 404 });
108
+ return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });
109
+ },
110
+ },
111
+ });
112
+ }
113
+
114
+ export default voice;