deictic 0.0.1 → 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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -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 +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 +307 -7
  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
  173. package/index.js +0 -1
@@ -0,0 +1,83 @@
1
+ /**
2
+ * A gesture: the keys held to outline the element under the pointer, and the button that, with them
3
+ * held, opens the popup there. deictic's own (`MASTER` by default) opens the tab used last; a
4
+ * plugin's, which it takes as its `shortcut` option and has none by default, opens its tab. The
5
+ * bundler's plugin checks them all as it starts, so a wrong one, or two alike, fails the dev server,
6
+ * not the page. Both halves import it: it must
7
+ * stay dependency-free.
8
+ */
9
+
10
+ /** A modifier key, as `KeyboardEvent.key` names it. */
11
+ export type Modifier = 'Alt' | 'Control' | 'Meta' | 'Shift';
12
+
13
+ export interface Shortcut {
14
+ /** Held, and no other, to outline elements. */
15
+ modifiers?: Modifier[];
16
+ /** Pressed with them to open the panel. `'left'` unset. */
17
+ button?: 'left' | 'middle' | 'right';
18
+ }
19
+
20
+ const FLAGS = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' } as const;
21
+ const BUTTONS = { left: 0, middle: 1, right: 2 } as const;
22
+
23
+ /** deictic's own shortcut, unless `deictic({ shortcut })` names another or `false`. */
24
+ export const MASTER: Required<Shortcut> = { modifiers: ['Alt'], button: 'left' };
25
+
26
+ /** The name deictic's own shortcut goes by in a problem. */
27
+ export const OWN = 'deictic';
28
+
29
+ /** deictic's own shortcut as given, with its default, before it's checked. */
30
+ export const ownShortcut = (given: Shortcut | false | undefined) => (given === false ? undefined : (given ?? MASTER));
31
+
32
+ /** The shortcut with its button's default and its modifiers in one order, or an error saying what to write instead. */
33
+ export function checkShortcut(plugin: string, shortcut: Shortcut): Required<Shortcut> {
34
+ const { modifiers = [], button = 'left' } = shortcut;
35
+ const named = Object.keys(FLAGS).join("', '");
36
+ if (!Array.isArray(modifiers) || modifiers.length === 0) {
37
+ throw new Error(
38
+ `deictic: ${plugin}'s shortcut.modifiers is empty: hold at least one of '${named}', or every click would open the popup`,
39
+ );
40
+ }
41
+ for (const m of modifiers)
42
+ if (!Object.hasOwn(FLAGS, m)) throw new Error(`deictic: ${plugin}'s shortcut.modifiers has '${m}': name one of '${named}'`);
43
+
44
+ if (!Object.hasOwn(BUTTONS, button))
45
+ throw new Error(`deictic: ${plugin}'s shortcut.button is '${button}': name one of '${Object.keys(BUTTONS).join("', '")}'`);
46
+
47
+ const order = Object.keys(FLAGS);
48
+ return { modifiers: [...new Set(modifiers)].toSorted((a, b) => order.indexOf(a) - order.indexOf(b)), button };
49
+ }
50
+
51
+ /**
52
+ * Each shortcut checked, in order, or nothing where there's none: none may be another's, or only the
53
+ * first would ever open. deictic's own goes first, named `OWN`.
54
+ */
55
+ export function checkShortcuts(plugins: readonly { name: string; shortcut?: Shortcut }[]): (Required<Shortcut> | undefined)[] {
56
+ const taken = new Map<string, string>();
57
+ return plugins.map(({ name, shortcut }) => {
58
+ if (shortcut === undefined) return undefined;
59
+ const checked = checkShortcut(name, shortcut);
60
+ const key = nameOf(checked);
61
+ const other = taken.get(key);
62
+ if (other !== undefined) throw new Error(`deictic: ${name} and ${other} both open on ${key}: give one of them another \`shortcut\``);
63
+ taken.set(key, name);
64
+ return checked;
65
+ });
66
+ }
67
+
68
+ /** How a shortcut reads, for a problem or a label: `Alt+Shift`, `Control+right-click`. */
69
+ export const nameOf = ({ modifiers = [], button = 'left' }: Shortcut) =>
70
+ [...modifiers, ...(button === 'left' ? [] : [`${button}-click`])].join('+');
71
+
72
+ export interface Gesture {
73
+ /** Whether exactly the shortcut's modifiers are down: AltGr, which is Control and Alt, isn't Alt. */
74
+ held: (e: MouseEvent | KeyboardEvent) => boolean;
75
+ /** The shortcut's button, as `MouseEvent.button` numbers it. */
76
+ button: number;
77
+ }
78
+
79
+ export function gestureOf(shortcut: Required<Shortcut>): Gesture {
80
+ const on = new Set<string>(shortcut.modifiers);
81
+ const flags = Object.entries(FLAGS);
82
+ return { held: (e) => flags.every(([key, flag]) => e[flag] === on.has(key)), button: BUTTONS[shortcut.button] };
83
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * `.astro` components. They aren't JSX modules, but Astro 7's own parser reads a template as JSX, into the
3
+ * tree oxc makes (offsets in UTF-16, as ours are), so its host elements are marked as a JSX module's are,
4
+ * before Astro compiles the file. The parser is the project's own Astro's (`@astrojs/compiler-rs`, found
5
+ * through `astro`), so it reads a file exactly as the compiler will; an Astro before 7 has none like it,
6
+ * and its `.astro` files are left unmarked.
7
+ */
8
+ import { createRequire } from 'node:module';
9
+ import { join } from 'node:path';
10
+
11
+ import type { JSXOpeningElement, Program } from 'oxc-parser';
12
+
13
+ import { type Located, marked } from './locate.ts';
14
+
15
+ export const ASTRO = /\.astro$/;
16
+
17
+ /** A file parsed: its module (an `.astro` file's frontmatter), and each opening tag in it, in the file's order. */
18
+ export interface Parsed {
19
+ program: Program;
20
+ elements: JSXOpeningElement[];
21
+ }
22
+
23
+ interface Tree {
24
+ ast: { frontmatter: { program: Program }; body: unknown };
25
+ diagnostics: { severity: string; text: string }[];
26
+ }
27
+ type Parse = (code: string) => Tree;
28
+
29
+ const parsers = new Map<string, Parse | undefined>();
30
+
31
+ /** The parser of the Astro installed for the project at `root`, loaded once; nothing without Astro 7. */
32
+ function parserOf(root: string): Parse | undefined {
33
+ if (!parsers.has(root)) parsers.set(root, load(root));
34
+ return parsers.get(root);
35
+ }
36
+
37
+ function load(root: string): Parse | undefined {
38
+ try {
39
+ // Astro's own dependency, which a strict package manager doesn't put where the project could import it.
40
+ const astro = createRequire(createRequire(join(root, 'package.json')).resolve('astro/package.json'));
41
+ // An ES module, required: every Node that runs Astro 7 can, and reading a source stays synchronous.
42
+ const compiler: { parse?: Parse } = astro('@astrojs/compiler-rs');
43
+ return compiler.parse;
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Astro gives a `<script>` or `<style>` with an attribute it doesn't know to the page as it is, unbundled and
51
+ * unscoped, and a `<slot>` isn't an element at all: none of them can be pointed at, so none is marked.
52
+ */
53
+ const OWN = new Set(['script', 'style', 'slot']);
54
+
55
+ const isOpening = (node: object): node is JSXOpeningElement => 'type' in node && node.type === 'JSXOpeningElement';
56
+
57
+ /** An `.astro` file's text parsed, or the `problem` with it: no parser (an older Astro), or text that doesn't parse. */
58
+ export function parseAstro(root: string, code: string): Parsed | { problem: string } {
59
+ const parse = parserOf(root);
60
+ if (parse === undefined) return { problem: 'reading an .astro file takes Astro 7 or later, so update astro' };
61
+ const { ast, diagnostics } = parse(code);
62
+ const error = diagnostics.find((d) => d.severity === 'error');
63
+ if (error !== undefined) return { problem: `fix it first (${error.text})` };
64
+ const elements: JSXOpeningElement[] = [];
65
+ const walk = (node: unknown): void => {
66
+ if (Array.isArray(node)) return node.forEach(walk);
67
+ if (node === null || typeof node !== 'object') return;
68
+ if (isOpening(node) && !(node.name.type === 'JSXIdentifier' && OWN.has(node.name.name))) elements.push(node);
69
+ Object.values(node).forEach(walk);
70
+ };
71
+ walk(ast.body);
72
+ return { program: ast.frontmatter.program, elements };
73
+ }
74
+
75
+ /** An `.astro` file's text with every host element marked, as `locate` marks a JSX module; nothing where it can't be read. */
76
+ export function locateAstro(code: string, file: string, root: string): Located | undefined {
77
+ // No tag, no parse.
78
+ if (!/<[a-z]/.test(code)) return undefined;
79
+ const parsed = parseAstro(root, code);
80
+ return 'problem' in parsed ? undefined : marked(code, file, parsed.elements);
81
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Opens a place in the editor, for a dev server without a launcher of its own (webpack's, Rspack's):
3
+ * `launch-editor`, which Vite's own launcher uses, finds the editor that's running or the one `EDITOR`
4
+ * names. An optional peer, imported when first asked.
5
+ */
6
+
7
+ import type { Loc } from '#src/index.ts';
8
+
9
+ export async function openInEditor(path: string, { line, column }: Loc): Promise<Response> {
10
+ const launcher = await import('launch-editor').catch(() => undefined);
11
+ if (launcher === undefined)
12
+ return new Response('deictic opens files with launch-editor here: add it to your devDependencies', { status: 501 });
13
+ return new Promise((done) => {
14
+ let failed = false;
15
+ launcher.default(`${path}:${line}:${column}`, (_, message) => {
16
+ failed = true;
17
+ done(new Response(`${message ?? "the editor didn't open"}: set EDITOR to your editor's command`, { status: 500 }));
18
+ });
19
+ // launch-editor reports a failure as it happens, and nothing on success.
20
+ setTimeout(() => failed || done(new Response(null, { status: 204 })), 50);
21
+ });
22
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The dev server's half of deictic, under `/__deictic/`: `read` and `apply` an op through a
3
+ * plugin, `undo`, `redo` and `history`, and `open`, which opens a place in the editor. Written over
4
+ * `Request` and `Response`, so each integration mounts them its own way (Vite as middleware), and
5
+ * served from the page's own origin, so no token travels to the page. `undo`, `redo` and `history` are a
6
+ * plugin's on an element where the request names them (as the popup does: its tab, its element), and
7
+ * the whole history's where it doesn't.
8
+ *
9
+ * Everything but `open` and `history` writes or may, so only the page itself may send it: a POST of
10
+ * JSON from the same origin, which a form or a script on another site can't send without asking first.
11
+ *
12
+ * Each plugin's own `routes` are under `plugins/<name>/`. A `GET` there reaches the plugin as it
13
+ * comes; anything else only from the page's own origin, in whatever type it sends (an image, say).
14
+ * Nothing is answered before every plugin's `setup` has run.
15
+ */
16
+ import type { IncomingMessage, ServerResponse } from 'node:http';
17
+
18
+ import { type Loc, Refusal, type ServerPlugin, type Target } from '#src/index.ts';
19
+
20
+ import { History, type Scope } from './history.ts';
21
+ import { setUp } from './plugins.ts';
22
+ import { applyEdits, resolveFile, sourceAt } from './source.ts';
23
+
24
+ export interface EndpointOptions {
25
+ root: string;
26
+ plugins: ServerPlugin[];
27
+ /** The path the endpoints sit under, ending in `/`: `/` by default. */
28
+ base?: string;
29
+ /** Opens a place in the editor: a redirect to the dev server's own launcher. */
30
+ open: (path: string, loc: Loc) => Response | Promise<Response>;
31
+ history?: History;
32
+ }
33
+
34
+ interface Body {
35
+ plugin: string;
36
+ target: Target;
37
+ op?: unknown;
38
+ }
39
+
40
+ const scopeOf = (plugin: string, { file, line, column }: Loc): Scope => ({ plugin, target: `${file}:${line}:${column}` });
41
+ /** The scope an undo or a redo names, or none for the whole history. */
42
+ const scopeIn = ({ plugin, target }: Partial<Body>) =>
43
+ plugin === undefined || target === undefined ? undefined : scopeOf(plugin, target.loc);
44
+
45
+ /** Answers deictic's requests, and nothing for any other path. */
46
+ export function endpoints({ root, plugins, base = '/', open, history = new History(root, { plugins }) }: EndpointOptions) {
47
+ const byName = new Map(plugins.map((p) => [p.name, p]));
48
+ const prefix = `${base}__deictic/`;
49
+ // Started now, awaited by every request: a plugin's API is there before anything asks for it.
50
+ const ready = setUp(root, plugins);
51
+
52
+ const pluginOf = (name: string) => {
53
+ const plugin = byName.get(name);
54
+ if (plugin === undefined) throw new Refusal(`no plugin "${name}" on the server: is it in the bundler plugin's \`plugins\`?`);
55
+ return plugin;
56
+ };
57
+
58
+ const routes: Record<string, (body: Body) => Promise<unknown>> = {
59
+ read: async ({ plugin, target }) => ({ model: await readOf(pluginOf(plugin), target) }),
60
+ apply: async ({ plugin: name, target, op }) => {
61
+ const plugin = pluginOf(name);
62
+ if (plugin.apply === undefined) throw new Refusal(`${name} changes nothing from its panel: it has no \`apply\``);
63
+ const source = sourceAt(root, target);
64
+ const before = await readOf(plugin, target);
65
+ const { file, line } = target.loc;
66
+ const label = `${name} ${file}:${line}: ${plugin.describe?.(op, before) ?? 'edit'}`;
67
+ const result = await plugin.apply(source, target, op);
68
+ const scope = scopeOf(name, target.loc);
69
+ const change = Array.isArray(result)
70
+ ? history.commit(label, applyEdits(source, result), scope)
71
+ : history.record(label, name, result.done, scope);
72
+ return { model: await readOf(plugin, target), change };
73
+ },
74
+ undo: async (body) => ({ change: await history.undo(scopeIn(body)) }),
75
+ redo: async (body) => ({ change: await history.redo(scopeIn(body)) }),
76
+ };
77
+ // A plugin without `read` has no model, and no need for its element to be where the page says.
78
+ const readOf = (plugin: ServerPlugin, target: Target) => (plugin.read === undefined ? null : plugin.read(sourceAt(root, target), target));
79
+ // One write at a time: a plugin's change may wait on the network, and an undo sent meanwhile must
80
+ // take back that change, not the one before it.
81
+ let queue: Promise<unknown> = Promise.resolve();
82
+ const serially = <T>(run: () => Promise<T>): Promise<T> => {
83
+ const next = queue.then(run, run);
84
+ queue = next.catch(() => {});
85
+ return next;
86
+ };
87
+
88
+ return async (req: Request): Promise<Response | undefined> => {
89
+ const url = new URL(req.url);
90
+ if (!url.pathname.startsWith(prefix)) return undefined;
91
+ const route = url.pathname.slice(prefix.length);
92
+ const origin = req.headers.get('origin');
93
+ const sameOrigin = origin !== null && new URL(origin).host === url.host;
94
+ try {
95
+ const context = await ready;
96
+ if (route.startsWith('plugins/')) {
97
+ const [name = '', first = ''] = route.slice('plugins/'.length).split('/');
98
+ const handle = byName.get(name)?.routes?.[first];
99
+ if (handle === undefined) return new Response(`no endpoint ${url.pathname}`, { status: 404 });
100
+ if (req.method !== 'GET' && req.method !== 'HEAD' && !sameOrigin)
101
+ return Response.json({ problem: `only the page itself may ${req.method} to ${name}` }, { status: 403 });
102
+ return await handle(req, context);
103
+ }
104
+ const loc = {
105
+ file: url.searchParams.get('file') ?? '',
106
+ line: Number(url.searchParams.get('line')),
107
+ column: Number(url.searchParams.get('column')),
108
+ };
109
+ if (route === 'history') {
110
+ const plugin = url.searchParams.get('plugin');
111
+ return Response.json(history.list(plugin === null ? undefined : scopeOf(plugin, loc)));
112
+ }
113
+ if (route === 'open') return await open(resolveFile(root, loc.file), loc);
114
+ const handler = routes[route];
115
+ if (handler === undefined) return new Response(`no endpoint ${url.pathname}`, { status: 404 });
116
+ if (req.method !== 'POST' || !sameOrigin || req.headers.get('content-type')?.startsWith('application/json') !== true)
117
+ return Response.json({ problem: 'edits come from the page, as JSON' }, { status: 403 });
118
+ const body = (await req.json()) as Body;
119
+ return Response.json(await (route === 'read' ? handler(body) : serially(() => handler(body))));
120
+ } catch (e) {
121
+ if (e instanceof Refusal) return Response.json({ problem: e.message }, { status: 422 });
122
+ return Response.json({ problem: e instanceof Error ? (e.stack ?? e.message) : String(e) }, { status: 500 });
123
+ }
124
+ };
125
+ }
126
+
127
+ /** A redirect within the page's origin, to a launcher the dev server answers itself. */
128
+ export const redirect = (path: string) => new Response(null, { status: 307, headers: { Location: path } });
129
+
130
+ /**
131
+ * The endpoints as Node middleware, for Vite's server. The request's host is the one the page was
132
+ * served from: a proxy's `x-forwarded-host` before its own.
133
+ */
134
+ export function nodeMiddleware(
135
+ handle: (req: Request) => Promise<Response | undefined>,
136
+ ): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {
137
+ return (req, res, next) => {
138
+ // Before reading the body, which a request for anything else leaves to whoever answers it.
139
+ if (req.url?.includes('/__deictic/') !== true) return next();
140
+ const forwarded = req.headers['x-forwarded-host'];
141
+ const host = (Array.isArray(forwarded) ? forwarded[0] : forwarded) ?? req.headers.host ?? 'localhost';
142
+ const headers = new Headers();
143
+ for (const [name, value] of Object.entries(req.headers))
144
+ for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(name, v);
145
+
146
+ const chunks: Buffer[] = [];
147
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
148
+ req.on('end', () => {
149
+ const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : Buffer.concat(chunks);
150
+ handle(new Request(`http://${host}${req.url}`, { method: req.method, headers, body }))
151
+ .then(async (response) => {
152
+ if (response === undefined) return next();
153
+ res.statusCode = response.status;
154
+ response.headers.forEach((value, name) => res.setHeader(name, value));
155
+ res.end(Buffer.from(await response.arrayBuffer()));
156
+ })
157
+ .catch((e: unknown) => {
158
+ res.statusCode = 500;
159
+ res.end(e instanceof Error ? e.message : String(e));
160
+ });
161
+ });
162
+ };
163
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Every change deictic made, to undo and redo. A change to files holds each file's whole text
3
+ * before and after: source files are small, and the texts make undo exact without a diff to go stale.
4
+ * A change a plugin made itself (`Done`) holds the plugin's name and its record, and undoing it is the
5
+ * plugin's `undo`.
6
+ *
7
+ * Each change has a scope, the plugin and the element it was made on, and the popup undoes and redoes
8
+ * within its own: the latest change of this tab on this element, not the latest of all. So a change
9
+ * is taken back out of order, with later ones to the same file still in it. Then only the lines the
10
+ * change wrote go back to what they were, where they're still in the file as it wrote them, once.
11
+ *
12
+ * Anything else is refused, not merged: a file whose lines were edited since has the editor's own undo
13
+ * for it; and a redo likewise. A plugin's undo refuses on its own terms. Kept under `.deictic`, so it
14
+ * outlives a restart of the dev server and stays out of git.
15
+ */
16
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
17
+ import { dirname } from 'node:path';
18
+
19
+ import { Refusal, type ServerPlugin } from '#src/index.ts';
20
+
21
+ import { keptIn } from './kept.ts';
22
+ import { resolveFile } from './source.ts';
23
+
24
+ export interface FileChange {
25
+ file: string;
26
+ /** The text before, or nothing for a file the change made. */
27
+ before: string | null;
28
+ after: string;
29
+ }
30
+
31
+ /** Whose a change is: the plugin whose tab made it, and the element it was open on, as `file:line:column`. */
32
+ export interface Scope {
33
+ plugin: string;
34
+ target: string;
35
+ }
36
+
37
+ interface Base {
38
+ id: number;
39
+ at: string;
40
+ label: string;
41
+ /** None on a change made without one, which only an undo of the whole history reaches. */
42
+ scope?: Scope;
43
+ }
44
+
45
+ export type Change = Base & ({ files: FileChange[] } | { plugin: string; record: unknown });
46
+
47
+ /** A change as the page lists it. `files` is empty for one a plugin made itself. */
48
+ export interface Summary {
49
+ id: number;
50
+ at: string;
51
+ label: string;
52
+ files: string[];
53
+ }
54
+
55
+ export interface HistoryOptions {
56
+ /** Whose `undo` and `redo` take back the changes they made themselves. */
57
+ plugins?: ServerPlugin[];
58
+ store?: string;
59
+ }
60
+
61
+ const LIMIT = 200;
62
+
63
+ /** Whether a change is in a scope: any is in none. */
64
+ const within = (scope: Scope | undefined) => (c: Change) =>
65
+ scope === undefined || (c.scope?.plugin === scope.plugin && c.scope.target === scope.target);
66
+
67
+ const summary = (c: Change): Summary => ({ id: c.id, at: c.at, label: c.label, files: 'files' in c ? c.files.map((f) => f.file) : [] });
68
+
69
+ export class History {
70
+ #done: Change[] = [];
71
+ #undone: Change[] = [];
72
+ readonly #root: string;
73
+ readonly #store: string;
74
+ readonly #plugins: Map<string, ServerPlugin>;
75
+
76
+ constructor(root: string, { plugins = [], store = keptIn(root, 'history.json') }: HistoryOptions = {}) {
77
+ this.#root = root;
78
+ this.#store = store;
79
+ this.#plugins = new Map(plugins.map((p) => [p.name, p]));
80
+ if (!existsSync(store)) return;
81
+ try {
82
+ ({ done: this.#done, undone: this.#undone } = JSON.parse(readFileSync(store, 'utf8')) as { done: Change[]; undone: Change[] });
83
+ } catch {
84
+ // A history that doesn't read is one we start over, not one to stop the dev server for.
85
+ }
86
+ }
87
+
88
+ /** Writes each file's new text and records it as one change. A redo after it, in its scope, is gone, as in any editor. */
89
+ commit(label: string, texts: Map<string, string>, scope?: Scope): Summary {
90
+ const files: FileChange[] = [];
91
+ for (const [file, after] of texts) {
92
+ const path = resolveFile(this.#root, file);
93
+ const before = existsSync(path) ? readFileSync(path, 'utf8') : null;
94
+ if (before !== after) files.push({ file, before, after });
95
+ }
96
+ if (files.length === 0) throw new Refusal('nothing to change: the source already says that');
97
+ for (const f of files) write(resolveFile(this.#root, f.file), f.after);
98
+ return this.#push({ label, files }, scope);
99
+ }
100
+
101
+ /** Records a change `plugin` made itself, with what its `undo` needs. */
102
+ record(label: string, plugin: string, record: unknown, scope?: Scope): Summary {
103
+ return this.#push({ label, plugin, record }, scope);
104
+ }
105
+
106
+ /** Takes back the latest change, of a scope where one is given. */
107
+ async undo(scope?: Scope): Promise<Summary> {
108
+ const change = this.#done.findLast(within(scope));
109
+ if (change === undefined) throw new Refusal(scope === undefined ? 'nothing to undo' : 'nothing to undo here');
110
+ if ('files' in change) this.#put(change, 'after', 'before');
111
+ else change.record = (await this.#pluginOf(change, 'undo').undo!(change.record)) ?? change.record;
112
+ this.#done = this.#done.filter((c) => c !== change);
113
+ this.#undone.push(change);
114
+ this.#save();
115
+ return summary(change);
116
+ }
117
+
118
+ /** Makes the change last undone again, of a scope where one is given. */
119
+ async redo(scope?: Scope): Promise<Summary> {
120
+ const change = this.#undone.findLast(within(scope));
121
+ if (change === undefined) throw new Refusal(scope === undefined ? 'nothing to redo' : 'nothing to redo here');
122
+ if ('files' in change) this.#put(change, 'before', 'after');
123
+ else change.record = await this.#pluginOf(change, 'redo').redo!(change.record);
124
+ this.#undone = this.#undone.filter((c) => c !== change);
125
+ this.#done.push(change);
126
+ this.#save();
127
+ return summary(change);
128
+ }
129
+
130
+ list(scope?: Scope): { done: Summary[]; undone: Summary[] } {
131
+ return { done: this.#done.filter(within(scope)).map(summary), undone: this.#undone.filter(within(scope)).map(summary) };
132
+ }
133
+
134
+ #push(change: Omit<Base, 'id' | 'at'> & ({ files: FileChange[] } | { plugin: string; record: unknown }), scope?: Scope): Summary {
135
+ const id = Math.max(0, ...[...this.#done, ...this.#undone].map((c) => c.id)) + 1;
136
+ const made = { id, at: new Date().toISOString(), ...change, ...(scope === undefined ? {} : { scope }) };
137
+ this.#done = [...this.#done, made].slice(-LIMIT);
138
+ // What was undone in this scope can't be redone over the new change; another scope's still can.
139
+ this.#undone = this.#undone.filter((c) => !within(scope)(c));
140
+ this.#save();
141
+ return summary(made);
142
+ }
143
+
144
+ #pluginOf(change: { label: string; plugin: string }, step: 'undo' | 'redo'): ServerPlugin {
145
+ const plugin = this.#plugins.get(change.plugin);
146
+ if (plugin?.[step] === undefined) {
147
+ throw new Refusal(
148
+ `can't ${step} "${change.label}": the ${change.plugin} plugin that made it isn't loaded, so add it back to \`plugins\``,
149
+ );
150
+ }
151
+ return plugin;
152
+ }
153
+
154
+ /**
155
+ * Puts each file's `to` text back, once every one of them still reads as its `from`, or still has the
156
+ * lines that differ as `from` has them: then those lines alone change, and the rest stays as it is now.
157
+ */
158
+ #put(change: Base & { files: FileChange[] }, from: 'before' | 'after', to: 'before' | 'after'): void {
159
+ const paths = change.files.map((f) => resolveFile(this.#root, f.file));
160
+ const texts = change.files.map((f, i) => {
161
+ const now = existsSync(paths[i]!) ? readFileSync(paths[i]!, 'utf8') : null;
162
+ if (now === f[from]) return f[to];
163
+ const text = now === null || f[from] === null || f[to] === null ? undefined : swapped(now, f[from], f[to]);
164
+ if (text === undefined) {
165
+ throw new Refusal(
166
+ `${f.file} changed since "${change.label}" ${from === 'after' ? 'was made' : 'was undone'}: use the editor's undo there`,
167
+ );
168
+ }
169
+ return text;
170
+ });
171
+ texts.forEach((text, i) => {
172
+ if (text === null) rmSync(paths[i]!);
173
+ else write(paths[i]!, text);
174
+ });
175
+ }
176
+
177
+ #save(): void {
178
+ write(this.#store, JSON.stringify({ done: this.#done, undone: this.#undone }));
179
+ }
180
+ }
181
+
182
+ /**
183
+ * `now` with the lines that differ between `from` and `to` put as `to` has them, where `now` has them as
184
+ * `from` does, in one place only. Nothing where it doesn't (they were edited, or there are two of them), or
185
+ * where `from` has no such lines to find (the change only removed some).
186
+ */
187
+ function swapped(now: string, from: string, to: string): string | undefined {
188
+ const [a, b, lines] = [from.split('\n'), to.split('\n'), now.split('\n')];
189
+ let head = 0;
190
+ while (head < a.length && head < b.length && a[head] === b[head]) head++;
191
+ let tail = 0;
192
+ while (tail < a.length - head && tail < b.length - head && a.at(-1 - tail) === b.at(-1 - tail)) tail++;
193
+ const theirs = a.slice(head, a.length - tail);
194
+ if (theirs.length === 0) return undefined;
195
+ const found = lines.flatMap((_, i) => (theirs.every((line, j) => lines[i + j] === line) ? [i] : []));
196
+ if (found.length !== 1) return undefined;
197
+ return [...lines.slice(0, found[0]), ...b.slice(head, b.length - tail), ...lines.slice(found[0]! + theirs.length)].join('\n');
198
+ }
199
+
200
+ function write(path: string, text: string): void {
201
+ mkdirSync(dirname(path), { recursive: true });
202
+ writeFileSync(path, text);
203
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * What every bundler's integration shares: the options, the client module that starts the overlay, and
3
+ * the transform that marks a JSX module. Each integration adds what its bundler does its own way: how a
4
+ * module is transformed (a hook, a loader, `onLoad`), how the page loads the client (a virtual module
5
+ * under Vite, a file in `.deictic/` elsewhere, as webpack, Turbopack and Bun have none), where the
6
+ * endpoints are served, and what opens the editor.
7
+ */
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { dirname, isAbsolute, relative } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ import type { ServerPlugin } from '#src/index.ts';
13
+ import { checkShortcuts, OWN, ownShortcut, type Shortcut } from '#src/shortcut.ts';
14
+
15
+ import { ASTRO, locateAstro } from './astro.ts';
16
+ import { keptIn } from './kept.ts';
17
+ import { JSX, locate, type Located } from './locate.ts';
18
+ import { checkPlugins } from './plugins.ts';
19
+
20
+ export interface DeicticOptions {
21
+ /** The plugins to load, server halves: `tailwind()`, `tasks()`, your own. None by default. */
22
+ plugins?: ServerPlugin[];
23
+ /**
24
+ * What opens the popup on any plugin, at the tab used last: Alt and the left button by default, or
25
+ * `false` for none, leaving only plugins' own shortcuts.
26
+ */
27
+ shortcut?: Shortcut | false;
28
+ }
29
+
30
+ /** The options with their defaults, checked now, so a wrong set stops the dev server as it starts, not the page. */
31
+ export function prepare(options: DeicticOptions): { plugins: ServerPlugin[]; shortcut: Shortcut | false | undefined } {
32
+ const plugins = options.plugins ?? [];
33
+ checkPlugins(plugins, options.shortcut);
34
+ return { plugins, shortcut: options.shortcut };
35
+ }
36
+
37
+ /**
38
+ * The client module: the overlay, started with deictic's own shortcut and each plugin that has a half
39
+ * in the page, with its shortcut, checked.
40
+ */
41
+ export const clientModule = (plugins: ServerPlugin[], base: string, own?: Shortcut | false) => {
42
+ const [shortcut, ...shortcuts] = checkShortcuts([{ name: OWN, shortcut: ownShortcut(own) }, ...plugins]);
43
+ const paged = plugins.flatMap((p, i) =>
44
+ p.client === undefined ? [] : [{ client: p.client, rest: { shortcut: shortcuts[i], options: p.clientOptions } }],
45
+ );
46
+ return [
47
+ `import { start } from 'deictic/client';`,
48
+ ...paged.map((p, i) => `import p${i} from ${JSON.stringify(p.client)};`),
49
+ // Its shortcut and options as JSON, where it has them: `JSON.stringify` leaves out what's undefined.
50
+ `start({ base: ${JSON.stringify(base)}, shortcut: ${JSON.stringify(shortcut) ?? 'undefined'}, plugins: [${paged.map((p, i) => `{ plugin: p${i}, ...${JSON.stringify(p.rest)} }`).join(', ')}] });`,
51
+ ].join('\n');
52
+ };
53
+
54
+ /**
55
+ * Writes the client module to `.deictic/client.js` for a bundler without virtual modules, and answers
56
+ * its path. Its imports are bare (`deictic/client`, each plugin's), found from the project as its own
57
+ * are. Written only when it changed, so a watching bundler doesn't rebuild for nothing.
58
+ */
59
+ export function writeClient(root: string, plugins: ServerPlugin[], base: string, own?: Shortcut | false): string {
60
+ const code = `// Written by deictic as the dev server starts: it starts the overlay in the page.\n${clientModule(plugins, base, own)}\n`;
61
+ // Its own package: an ES module that runs for its effect. An app whose package.json says
62
+ // `"sideEffects": false` would otherwise have webpack drop the import, which is only for its effect.
63
+ const manifest = `${JSON.stringify({ private: true, type: 'module', sideEffects: true }, null, 2)}\n`;
64
+ writeIfChanged(keptIn(root, 'package.json'), manifest);
65
+ return writeIfChanged(keptIn(root, 'client.js'), code);
66
+ }
67
+
68
+ function writeIfChanged(path: string, text: string): string {
69
+ if (!existsSync(path) || readFileSync(path, 'utf8') !== text) writeFileSync(path, text);
70
+ return path;
71
+ }
72
+
73
+ /** A module beside `url`, by its name: `.ts` from the source, `.js` from `dist`, as `url` is. */
74
+ export const beside = (url: string, name: string) =>
75
+ fileURLToPath(new URL(`./${name}${url.endsWith('.ts') ? '.ts' : '.js'}`, url)).replaceAll('\\', '/');
76
+
77
+ /**
78
+ * The import of the written client module in the module at `from`, by a relative path with forward
79
+ * slashes: Turbopack can't import a Windows path, and every bundler takes a relative one.
80
+ */
81
+ export function importOf(path: string, from: string): string {
82
+ const to = relative(dirname(from), path).replaceAll('\\', '/');
83
+ return `\nimport ${JSON.stringify(to.startsWith('.') ? to : `./${to}`)};\n`;
84
+ }
85
+
86
+ /**
87
+ * A module marked, by its absolute path: its host elements, and `append` after it (the client's import,
88
+ * in the browser). Nothing for a file that isn't JSX, is a dependency's, or is outside the project.
89
+ */
90
+ export function mark(code: string, path: string, root: string, append = ''): Located | undefined {
91
+ const file = JSX.test(path) ? fileIn(path, root) : undefined;
92
+ return file === undefined ? undefined : locate(code, file, append);
93
+ }
94
+
95
+ /** An `.astro` component marked, by its absolute path, as `mark` does a module. It's no module of the browser's, so nothing is appended. */
96
+ export function markAstro(code: string, path: string, root: string): Located | undefined {
97
+ const file = ASTRO.test(path) ? fileIn(path, root) : undefined;
98
+ return file === undefined ? undefined : locateAstro(code, file, root);
99
+ }
100
+
101
+ /** A project file's path from the root, as a mark has it; nothing for a dependency's or one outside the project. */
102
+ function fileIn(path: string, root: string): string | undefined {
103
+ if (/[\\/]node_modules[\\/]/.test(path) || !isAbsolute(path)) return undefined;
104
+ const file = relative(root, path).replaceAll('\\', '/');
105
+ return file.startsWith('..') || isAbsolute(file) ? undefined : file;
106
+ }