deictic 0.0.1 → 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 (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -0
  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 +95 -0
  20. package/dist/client/index.d.ts.map +1 -0
  21. package/dist/client/index.js +1333 -0
  22. package/dist/client/index.js.map +1 -0
  23. package/dist/index.d.ts +23 -0
  24. package/dist/index.js +10 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/loader.d.ts +15 -0
  27. package/dist/loader.d.ts.map +1 -0
  28. package/dist/loader.js +17 -0
  29. package/dist/loader.js.map +1 -0
  30. package/dist/next.d.ts +17 -0
  31. package/dist/next.d.ts.map +1 -0
  32. package/dist/next.js +150 -0
  33. package/dist/next.js.map +1 -0
  34. package/dist/recommended/index.d.ts +25 -0
  35. package/dist/recommended/index.d.ts.map +1 -0
  36. package/dist/recommended/index.js +19 -0
  37. package/dist/recommended/index.js.map +1 -0
  38. package/dist/recordings/client.d.ts +4 -0
  39. package/dist/recordings/client.d.ts.map +1 -0
  40. package/dist/recordings/client.js +376 -0
  41. package/dist/recordings/client.js.map +1 -0
  42. package/dist/recordings/index.d.ts +2 -0
  43. package/dist/recordings/index.js +3 -0
  44. package/dist/screenshots/client.d.ts +23 -0
  45. package/dist/screenshots/client.d.ts.map +1 -0
  46. package/dist/screenshots/client.js +76 -0
  47. package/dist/screenshots/client.js.map +1 -0
  48. package/dist/screenshots/dom.d.ts +4 -0
  49. package/dist/screenshots/dom.d.ts.map +1 -0
  50. package/dist/screenshots/dom.js +92 -0
  51. package/dist/screenshots/dom.js.map +1 -0
  52. package/dist/screenshots/index.d.ts +2 -0
  53. package/dist/screenshots/index.js +98 -0
  54. package/dist/screenshots/index.js.map +1 -0
  55. package/dist/screenshots/rrweb.d.ts +9 -0
  56. package/dist/screenshots/rrweb.d.ts.map +1 -0
  57. package/dist/screenshots/rrweb.js +60 -0
  58. package/dist/screenshots/rrweb.js.map +1 -0
  59. package/dist/shared/endpoints.js +354 -0
  60. package/dist/shared/endpoints.js.map +1 -0
  61. package/dist/shared/index.d.ts +226 -0
  62. package/dist/shared/index.d.ts.map +1 -0
  63. package/dist/shared/index2.d.ts +98 -0
  64. package/dist/shared/index2.d.ts.map +1 -0
  65. package/dist/shared/index3.d.ts +86 -0
  66. package/dist/shared/index3.d.ts.map +1 -0
  67. package/dist/shared/index4.d.ts +184 -0
  68. package/dist/shared/index4.d.ts.map +1 -0
  69. package/dist/shared/index5.d.ts +70 -0
  70. package/dist/shared/index5.d.ts.map +1 -0
  71. package/dist/shared/integration.d.ts +20 -0
  72. package/dist/shared/integration.d.ts.map +1 -0
  73. package/dist/shared/integration.js +279 -0
  74. package/dist/shared/integration.js.map +1 -0
  75. package/dist/shared/kept.js +23 -0
  76. package/dist/shared/kept.js.map +1 -0
  77. package/dist/shared/marks.js +14 -0
  78. package/dist/shared/marks.js.map +1 -0
  79. package/dist/shared/playwright.js +105 -0
  80. package/dist/shared/playwright.js.map +1 -0
  81. package/dist/shared/recordings.js +246 -0
  82. package/dist/shared/recordings.js.map +1 -0
  83. package/dist/shared/shortcut.js +63 -0
  84. package/dist/shared/shortcut.js.map +1 -0
  85. package/dist/shared/tasks.js +521 -0
  86. package/dist/shared/tasks.js.map +1 -0
  87. package/dist/shared/waveform.js +93 -0
  88. package/dist/shared/waveform.js.map +1 -0
  89. package/dist/tailwind/client.d.ts +4 -0
  90. package/dist/tailwind/client.d.ts.map +1 -0
  91. package/dist/tailwind/client.js +613 -0
  92. package/dist/tailwind/client.js.map +1 -0
  93. package/dist/tailwind/index.d.ts +2 -0
  94. package/dist/tailwind/index.js +557 -0
  95. package/dist/tailwind/index.js.map +1 -0
  96. package/dist/tasks/client.d.ts +6 -0
  97. package/dist/tasks/client.d.ts.map +1 -0
  98. package/dist/tasks/client.js +642 -0
  99. package/dist/tasks/client.js.map +1 -0
  100. package/dist/tasks/index.d.ts +2 -0
  101. package/dist/tasks/index.js +1 -0
  102. package/dist/vite.d.ts +16 -0
  103. package/dist/vite.d.ts.map +1 -0
  104. package/dist/vite.js +61 -0
  105. package/dist/vite.js.map +1 -0
  106. package/dist/voice/client.d.ts +4 -0
  107. package/dist/voice/client.d.ts.map +1 -0
  108. package/dist/voice/client.js +66 -0
  109. package/dist/voice/client.js.map +1 -0
  110. package/dist/voice/index.d.ts +47 -0
  111. package/dist/voice/index.d.ts.map +1 -0
  112. package/dist/voice/index.js +74 -0
  113. package/dist/voice/index.js.map +1 -0
  114. package/dist/webpack.d.ts +50 -0
  115. package/dist/webpack.d.ts.map +1 -0
  116. package/dist/webpack.js +78 -0
  117. package/dist/webpack.js.map +1 -0
  118. package/package.json +307 -7
  119. package/skills/deictic/SKILL.md +47 -0
  120. package/skills/deictic/references/install.md +96 -0
  121. package/skills/deictic/references/recordings.md +83 -0
  122. package/skills/deictic/references/tasks.md +79 -0
  123. package/skills/deictic/references/watch.md +43 -0
  124. package/skills/deictic/scripts/frame.mjs +62 -0
  125. package/skills/deictic/scripts/lib.mjs +211 -0
  126. package/skills/deictic/scripts/recording.mjs +186 -0
  127. package/skills/deictic/scripts/task.mjs +84 -0
  128. package/skills/deictic/scripts/transcribe.mjs +93 -0
  129. package/skills/deictic/scripts/voice.mjs +50 -0
  130. package/skills/deictic/scripts/watch.mjs +51 -0
  131. package/src/astro.ts +34 -0
  132. package/src/bun.ts +79 -0
  133. package/src/client/index.ts +846 -0
  134. package/src/client/lightbox.ts +256 -0
  135. package/src/client/style.ts +243 -0
  136. package/src/client/tooltip.ts +78 -0
  137. package/src/client/waveform.ts +98 -0
  138. package/src/index.ts +247 -0
  139. package/src/loader.ts +28 -0
  140. package/src/next.ts +133 -0
  141. package/src/plugins/annotations/client.ts +301 -0
  142. package/src/plugins/annotations/draw.ts +169 -0
  143. package/src/plugins/annotations/index.ts +105 -0
  144. package/src/plugins/annotations/svg.ts +61 -0
  145. package/src/plugins/recommended/index.ts +35 -0
  146. package/src/plugins/recordings/client.ts +316 -0
  147. package/src/plugins/recordings/index.ts +175 -0
  148. package/src/plugins/recordings/marks.ts +11 -0
  149. package/src/plugins/recordings/ours.ts +70 -0
  150. package/src/plugins/recordings/replay.ts +165 -0
  151. package/src/plugins/screenshots/client.ts +64 -0
  152. package/src/plugins/screenshots/dom.ts +79 -0
  153. package/src/plugins/screenshots/index.ts +194 -0
  154. package/src/plugins/screenshots/playwright.ts +119 -0
  155. package/src/plugins/screenshots/rrweb.ts +45 -0
  156. package/src/plugins/tailwind/catalog.ts +396 -0
  157. package/src/plugins/tailwind/client.ts +669 -0
  158. package/src/plugins/tailwind/index.ts +267 -0
  159. package/src/plugins/tasks/client.ts +622 -0
  160. package/src/plugins/tasks/index.ts +557 -0
  161. package/src/plugins/tasks/local.ts +170 -0
  162. package/src/plugins/voice/client.ts +58 -0
  163. package/src/plugins/voice/index.ts +114 -0
  164. package/src/shortcut.ts +83 -0
  165. package/src/tools/astro.ts +81 -0
  166. package/src/tools/editor.ts +22 -0
  167. package/src/tools/endpoints.ts +163 -0
  168. package/src/tools/history.ts +203 -0
  169. package/src/tools/integration.ts +108 -0
  170. package/src/tools/kept.ts +21 -0
  171. package/src/tools/locate.ts +94 -0
  172. package/src/tools/plugins.ts +41 -0
  173. package/src/tools/source.ts +72 -0
  174. package/src/vite.ts +81 -0
  175. package/src/webpack.ts +107 -0
  176. package/index.js +0 -1
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ // What was said in voice clips, with when: Whisper on this machine, through transformers.js. For a recording, the
3
+ // times are the recording's, to line up with its timeline. Nothing leaves the machine once the model is downloaded.
4
+ //
5
+ // Usage: transcribe.mjs <task | replay URL | recording ID | file | clip ID> [--model base] [--language en] [--json]
6
+ // transcribe.mjs --setup [--model base] installs it: ask the person first
7
+ //
8
+ // Setup puts @huggingface/transformers and the model in ~/.cache/deictic/transcribe (DEICTIC_CACHE moves it),
9
+ // outside the project. Models: tiny (~40 MB), base (~77 MB, the default), small (~250 MB), large-v3-turbo
10
+ // (~800 MB), or any ONNX Whisper on Hugging Face by its ID. Needs ffmpeg on the PATH.
11
+ import { spawnSync } from 'node:child_process';
12
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
13
+ import { createRequire } from 'node:module';
14
+ import { homedir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { pathToFileURL } from 'node:url';
17
+
18
+ import { clock, fail, ffmpeg, parseArgs, voiceClips } from './lib.mjs';
19
+
20
+ // Pinned, so a setup installs what the script was written against; move it on deliberately.
21
+ const TRANSFORMERS = '@huggingface/transformers@4.3.2';
22
+ const MODELS = { tiny: 'whisper-tiny', base: 'whisper-base', small: 'whisper-small', 'large-v3-turbo': 'whisper-large-v3-turbo' };
23
+
24
+ const { options, rest } = parseArgs(process.argv.slice(2), ['setup', 'json']);
25
+ const size = options.model?.[0] ?? 'base';
26
+ const model = size.includes('/')
27
+ ? size
28
+ : `onnx-community/${MODELS[size] ?? fail(`--model is one of ${Object.keys(MODELS).join(', ')}, or a model ID`)}`;
29
+ const dir = join(process.env.DEICTIC_CACHE ?? join(homedir(), '.cache', 'deictic'), 'transcribe');
30
+ const models = join(dir, 'models');
31
+ const installed = existsSync(join(dir, 'node_modules', '@huggingface', 'transformers', 'package.json'));
32
+ const downloaded = existsSync(join(models, ...model.split('/')));
33
+
34
+ if (options.setup) {
35
+ mkdirSync(dir, { recursive: true });
36
+ if (!existsSync(join(dir, 'package.json'))) writeFileSync(join(dir, 'package.json'), '{ "private": true }\n');
37
+ if (!installed) {
38
+ console.log(`Installing ${TRANSFORMERS} in ${dir}…`);
39
+ const windows = process.platform === 'win32';
40
+ const args = ['install', '--prefix', dir, '--no-audit', '--no-fund', '--save-exact', TRANSFORMERS];
41
+ const run = spawnSync(windows ? `npm ${args.map((a) => `"${a}"`).join(' ')}` : 'npm', windows ? [] : args, {
42
+ stdio: 'inherit',
43
+ shell: windows,
44
+ });
45
+ if (run.status !== 0) fail(`npm install failed (${run.error?.message ?? `exit ${run.status}`}).`);
46
+ }
47
+ } else if (!installed || !downloaded) {
48
+ fail(
49
+ `Local transcription isn't set up${installed ? ` with the ${size} model` : ''}. Ask the person first: it downloads ` +
50
+ `${installed ? '' : `${TRANSFORMERS} (with ONNX Runtime, ~470 MB) and `}Whisper ${size} into ${dir}, outside ` +
51
+ `the project; after that, audio is transcribed on this machine. On yes: node ${process.argv[1]} --setup` +
52
+ (size === 'base' ? '' : ` --model ${size}`),
53
+ );
54
+ }
55
+
56
+ const transformers = await import(pathToFileURL(createRequire(join(dir, 'package.json')).resolve('@huggingface/transformers')).href);
57
+ transformers.env.cacheDir = models;
58
+ // Only setup downloads; a transcription uses what's here.
59
+ transformers.env.allowRemoteModels = Boolean(options.setup);
60
+ if (options.setup) console.log(`Downloading ${model} (quantized) into ${models}…`);
61
+ const asr = await transformers.pipeline('automatic-speech-recognition', model, { dtype: 'q8' });
62
+ if (options.setup) {
63
+ console.log(`Ready: node ${process.argv[1]} <task>${size === 'base' ? '' : ` --model ${size}`}`);
64
+ if (rest[0] === undefined) process.exit(0);
65
+ }
66
+
67
+ const results = [];
68
+ for (const c of await voiceClips(rest[0])) {
69
+ // Whisper takes 16 kHz mono samples; ffmpeg decodes the clip (webm, ogg or mp4) to them.
70
+ const raw = ffmpeg(['-loglevel', 'error', '-i', c.file, '-f', 'f32le', '-ac', '1', '-ar', '16000', '-'], 'buffer').stdout;
71
+ const audio = new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength - (raw.byteLength % 4)));
72
+ const out = await asr(audio, {
73
+ return_timestamps: true,
74
+ chunk_length_s: 30,
75
+ stride_length_s: 5,
76
+ ...(options.language ? { language: options.language[0] } : {}),
77
+ });
78
+ const said = (out.chunks ?? [{ timestamp: [0, audio.length / 16000], text: out.text }]).map(({ timestamp: [from, to], text }) => ({
79
+ from: c.at + from * 1000,
80
+ to: c.at + (to ?? audio.length / 16000) * 1000,
81
+ text: text.trim(),
82
+ }));
83
+ results.push({ ...c, text: out.text.trim(), said });
84
+ }
85
+
86
+ if (options.json) {
87
+ console.log(JSON.stringify(results, null, 2));
88
+ } else {
89
+ for (const r of results) {
90
+ console.log(`clip ${r.id} (${r.recording ? `in recording ${r.recording}, from ${clock(r.at)}` : 'a voice note'}):`);
91
+ for (const s of r.said) console.log(` ${clock(s.from).padStart(6)} – ${clock(s.to).padStart(6)} ${s.text}`);
92
+ }
93
+ }
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // When something was said: the stretches of speech in voice clips, found by ffmpeg's silence detection. For a
3
+ // recording, in the recording's time, to line up with its timeline; for a task, each voice note on it too.
4
+ // Usage: voice.mjs <task | replay URL | recording ID | file | clip ID> [--noise -35] [--gap 0.4] [--wav dir] [--json]
5
+ // --wav writes each clip as 16 kHz mono WAV, what speech-to-text tools take. Needs ffmpeg on the PATH.
6
+ import { mkdirSync } from 'node:fs';
7
+ import { join, resolve } from 'node:path';
8
+
9
+ import { clock, ffmpeg, parseArgs, voiceClips } from './lib.mjs';
10
+
11
+ const { options, rest } = parseArgs(process.argv.slice(2), ['json']);
12
+ const noise = Number(options.noise?.[0] ?? -35);
13
+ const gap = Number(options.gap?.[0] ?? 0.4);
14
+ const clips = await voiceClips(rest[0]);
15
+
16
+ const results = [];
17
+ for (const c of clips) {
18
+ // ffmpeg reports silence; speech is what's between. MediaRecorder's webm has no duration, so it's measured.
19
+ const run = ffmpeg(['-i', c.file, '-af', `silencedetect=noise=${noise}dB:d=${gap}`, '-f', 'null', '-']);
20
+ const log = run.stderr;
21
+ const starts = [...log.matchAll(/silence_start: (-?[\d.]+)/g)].map((m) => Number(m[1]) * 1000);
22
+ const ends = [...log.matchAll(/silence_end: (-?[\d.]+)/g)].map((m) => Number(m[1]) * 1000);
23
+ const times = [...log.matchAll(/time=(\d+):(\d+):([\d.]+)/g)].at(-1);
24
+ const length = times ? (Number(times[1]) * 3600 + Number(times[2]) * 60 + Number(times[3])) * 1000 : Math.max(0, ...ends);
25
+ const speech = [];
26
+ let from = 0;
27
+ for (let i = 0; i < starts.length; i++) {
28
+ if (starts[i] - from > 150) speech.push([from, starts[i]]);
29
+ from = ends[i] ?? length;
30
+ }
31
+ if (length - from > 150) speech.push([from, length]);
32
+ if (options.wav) {
33
+ const dir = resolve(options.wav[0]);
34
+ mkdirSync(dir, { recursive: true });
35
+ ffmpeg(['-y', '-loglevel', 'error', '-i', c.file, '-ar', '16000', '-ac', '1', '-sample_fmt', 's16', join(dir, `${c.id}.wav`)]);
36
+ }
37
+ results.push({ ...c, length, speech: speech.map(([a, b]) => ({ from: c.at + a, to: c.at + b })) });
38
+ }
39
+
40
+ if (options.json) {
41
+ console.log(JSON.stringify(results, null, 2));
42
+ } else {
43
+ for (const r of results) {
44
+ const where = r.recording ? `in recording ${r.recording}, from ${clock(r.at)}` : 'a voice note';
45
+ console.log(`clip ${r.id} (${where}), ${clock(r.length)} long: ${r.file}`);
46
+ if (r.speech.length === 0) console.log(' no speech found: try a lower --noise, like -45');
47
+ for (const s of r.speech) console.log(` ${clock(s.from).padStart(6)} – ${clock(s.to).padStart(6)} speech`);
48
+ if (options.wav) console.log(` wav: ${join(resolve(options.wav[0]), `${r.id}.wav`)}`);
49
+ }
50
+ }
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ // Watches the board for deictic's tasks and prints one line per thing to act on: the tasks ready now as it
3
+ // starts, then each new task, a reply on one, and one canceled (undone in the page, say). Made for an agent's
4
+ // monitor (each line an event); it runs until stopped, and says so if the board goes away.
5
+ // Usage: watch.mjs [channel, default deictic] [--label k=v ...]
6
+ import { spawn } from 'node:child_process';
7
+ import { createInterface } from 'node:readline';
8
+
9
+ import { boardUrl, parseArgs, vb, vbCommand } from './lib.mjs';
10
+
11
+ const { options, rest } = parseArgs(process.argv.slice(2));
12
+ const channel = rest[0] ?? 'deictic';
13
+ const labels = (options.label ?? []).flatMap((l) => ['--label', l]);
14
+ const say = (line) => console.log(line.replace(/\s+/g, ' ').trim());
15
+ const first = (text) => (text.split('\n---')[0] ?? '').trim().slice(0, 160);
16
+
17
+ const ready = vb(['tasks', channel, '--state', 'ready', ...labels]).trim();
18
+ say(`watching ${channel} on ${boardUrl() ?? "the team's board"}`);
19
+ for (const line of ready ? ready.split('\n') : []) if (/^#\d+/.test(line)) say(`ready: ${line}`);
20
+
21
+ // What the board says about each thread: its root's first line and where, to name it when a task is made.
22
+ const roots = new Map();
23
+ const [command, argv, spawnOptions] = vbCommand(['tail', channel, ...labels, '--json']);
24
+ const tail = spawn(command, argv, { ...spawnOptions, stdio: ['ignore', 'pipe', 'inherit'] });
25
+ createInterface({ input: tail.stdout }).on('line', (line) => {
26
+ let e;
27
+ try {
28
+ e = JSON.parse(line);
29
+ } catch {
30
+ return;
31
+ }
32
+ const p = e.payload ?? {};
33
+ if (e.type === 'message.posted' && p.re === null) {
34
+ const at = p.labels?.['deictic.at'];
35
+ roots.set(
36
+ p.thread,
37
+ `"${first(p.text ?? '')}"${at ? ` at ${at}` : ''}${p.labels?.['deictic.page'] ? ` on ${p.labels['deictic.page']}` : ''}${p.labels?.['deictic.project'] ? ` in ${p.labels['deictic.project']}` : ''}`,
38
+ );
39
+ }
40
+ if (e.type === 'task.created') say(`new task #${p.id}: ${roots.get(p.thread) ?? ''}. Read it: vb read ${p.id}`);
41
+
42
+ if (e.type === 'message.posted' && p.re !== null && p.re !== undefined) {
43
+ const by = e.message?.author?.handle ?? p.by?.actor ?? 'someone';
44
+ say(`reply on #${p.re} by ${by}: ${first(p.text ?? '')}`);
45
+ }
46
+ if (e.type === 'task.canceled') say(`task #${p.id} canceled: ${p.reason ?? ''}. Stop work on it.`);
47
+ });
48
+ tail.on('exit', (code) => {
49
+ say(`watch ended (vb tail exited ${code}): start it again`);
50
+ process.exit(1);
51
+ });
package/src/astro.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * `deictic/astro`: the Vite plugin (`vite.ts`) in `astro dev`, and the overlay on every page.
3
+ *
4
+ * Astro renders a page on the server and may send it with no script at all, so nothing in the browser
5
+ * would import the client module, which under Vite comes with the first JSX module. The integration
6
+ * injects it into every page instead. JSX components (React's, Preact's, Solid's) are marked, on the
7
+ * server and in islands, and with Astro 7, whose parser says where their tags are, `.astro` components
8
+ * too (`tools/astro.ts`).
9
+ */
10
+ import { CLIENT, deictic as vitePlugin, type DeicticOptions } from './vite.ts';
11
+
12
+ export type { DeicticOptions as DeicticIntegrationOptions };
13
+
14
+ /** What the integration reads of Astro's setup hook: Astro's own types, as far as they're used here. */
15
+ interface Setup {
16
+ command: 'dev' | 'build' | 'preview' | 'sync';
17
+ updateConfig: (config: { vite: { plugins: unknown[] } }) => void;
18
+ injectScript: (stage: 'page', content: string) => void;
19
+ }
20
+
21
+ export function deictic(options: DeicticOptions = {}) {
22
+ return {
23
+ name: 'deictic',
24
+ hooks: {
25
+ 'astro:config:setup': ({ command, updateConfig, injectScript }: Setup) => {
26
+ if (command !== 'dev') return;
27
+ updateConfig({ vite: { plugins: [vitePlugin(options)] } });
28
+ injectScript('page', `import ${JSON.stringify(CLIENT)};`);
29
+ },
30
+ },
31
+ };
32
+ }
33
+
34
+ export default deictic;
package/src/bun.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `deictic/bun`: deictic in Bun's dev server, the bundler `Bun.serve` runs for HTML imports. Nothing
3
+ * runs in `Bun.build`.
4
+ *
5
+ * Named in bunfig.toml's `[serve.static] plugins`, it marks each JSX module as it loads, and in the
6
+ * browser appends the import of the client module, written to `.deictic/client.js`, as Bun has no
7
+ * virtual modules for it. A bundler plugin can't add routes to the server, so the endpoints are the
8
+ * plugin's `routes`, spread into `Bun.serve`'s; a place opens in the editor `Bun.openInEditor` finds.
9
+ *
10
+ * bunfig names a module whose default export is the plugin, so the plugin lives in a file of its own,
11
+ * which the server imports too, for its routes:
12
+ *
13
+ * // deictic.ts
14
+ * export default deictic({ plugins: [tailwind()] });
15
+ * // server.ts
16
+ * import tools from './deictic.ts';
17
+ * Bun.serve({ routes: { ...tools.routes, '/*': index }, development: true });
18
+ */
19
+ import { resolve } from 'node:path';
20
+
21
+ import type { BunPlugin } from 'bun';
22
+
23
+ import { endpoints } from './tools/endpoints.ts';
24
+ import { type DeicticOptions, importOf, mark, prepare, writeClient } from './tools/integration.ts';
25
+ import { JSX } from './tools/locate.ts';
26
+
27
+ export interface DeicticBunOptions extends DeicticOptions {
28
+ /** The project's root, which marks and edits are from: the working directory by default. */
29
+ root?: string;
30
+ }
31
+
32
+ export type DeicticBunPlugin = BunPlugin & {
33
+ /** The endpoints, as `Bun.serve` routes: `routes: { ...plugin.routes, '/*': index }`. */
34
+ routes: Record<string, (req: Request) => Promise<Response>>;
35
+ };
36
+
37
+ export function deictic(options: DeicticBunOptions = {}): DeicticBunPlugin {
38
+ // Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.
39
+ const { plugins, shortcut } = prepare(options);
40
+ const root = resolve(options.root ?? process.cwd());
41
+ let handle: ((req: Request) => Promise<Response | undefined>) | undefined;
42
+ const route = async (req: Request) => {
43
+ handle ??= endpoints({
44
+ root,
45
+ plugins,
46
+ open: (path, { line, column }) => {
47
+ try {
48
+ Bun.openInEditor(path, { line, column });
49
+ return new Response(null, { status: 204 });
50
+ } catch (e) {
51
+ return new Response(`${e instanceof Error ? e.message : String(e)}: set VISUAL or EDITOR to the editor's command`, {
52
+ status: 500,
53
+ });
54
+ }
55
+ },
56
+ });
57
+ return (await handle(req)) ?? new Response(null, { status: 404 });
58
+ };
59
+
60
+ return {
61
+ name: 'deictic',
62
+ routes: { '/__deictic/*': route },
63
+ setup(build) {
64
+ // A build names its entry points; the dev server's bundler doesn't.
65
+ if ('entrypoints' in build.config) return;
66
+ const client = writeClient(root, plugins, '/', shortcut);
67
+ // Bun names the side it loads a module for (undocumented, and not in Bun's types); the dev server's is the browser's.
68
+ const forBrowser = (args: object) => !('side' in args) || args.side === 'client';
69
+ build.onLoad({ filter: JSX }, async (args) => {
70
+ // A dependency's is left to Bun, unread.
71
+ if (/[\\/]node_modules[\\/]/.test(args.path)) return undefined;
72
+ const code = await Bun.file(args.path).text();
73
+ const marked = mark(code, args.path, root, forBrowser(args) ? importOf(client, args.path) : '');
74
+ if (marked === undefined) return undefined;
75
+ return { contents: marked.code, loader: args.path.endsWith('tsx') ? 'tsx' : 'jsx' };
76
+ });
77
+ },
78
+ };
79
+ }