deictic 0.10.0 → 0.11.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.
- package/API.md +7 -0
- package/dist/setup.d.ts +20 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +1 -0
- package/dist/shared/endpoints.js +12 -3
- package/dist/shared/endpoints.js.map +1 -1
- package/dist/shared/index.d.ts +5 -0
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/init.js +13 -132
- package/dist/shared/init.js.map +1 -1
- package/dist/shared/integration.js +3 -2
- package/dist/shared/integration.js.map +1 -1
- package/dist/shared/package.js +1 -1
- package/dist/shared/setup.js +152 -0
- package/dist/shared/setup.js.map +1 -0
- package/dist/shared/src.js.map +1 -1
- package/dist/shared/vite.js +5 -1
- package/dist/shared/vite.js.map +1 -1
- package/dist/webpack.d.ts +5 -0
- package/dist/webpack.d.ts.map +1 -1
- package/dist/webpack.js +7 -2
- package/dist/webpack.js.map +1 -1
- package/package.json +8 -1
- package/src/cli/edit.ts +14 -0
- package/src/cli/init.ts +14 -118
- package/src/index.ts +5 -0
- package/src/setup.ts +132 -0
- package/src/tools/endpoints.ts +23 -4
- package/src/tools/plugins.ts +7 -2
- package/src/vite.ts +7 -2
- package/src/webpack.ts +14 -9
package/dist/shared/src.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * `deictic`: what a plugin is. Every plugin is optional: deictic itself is the glue (the\n * transform that ties elements to source, the dev server's endpoints, the history, shortcuts and the\n * overlay's panel), and each plugin adds what it does on top.\n *\n * A plugin has two halves, each optional that meet over the dev server's endpoints (`tools/endpoints.ts`). The\n * server half runs beside the bundler and is the only one that reads source: it turns the element\n * under the pointer into a model its panel can show, and an op from that panel into text edits. It\n * never writes files; deictic does, so every plugin's changes land in one history and undo the\n * same way. A change that isn't to a file (a task added to a board) the plugin makes itself and\n * answers with what it did (`Done`): the history keeps that beside the files' changes and hands it\n * back to the plugin's own `undo` and `redo`.\n * The client half is a module the page loads, named by the server half's `client`, which draws the\n * panel and previews an op on the page before it is applied.\n *\n * A plugin may have no panel at all, only an API for others (screenshots, a recording) and routes of\n * its own on the dev server. Each half's `setup` answers its API, and `use(name)` reaches another\n * plugin's, on the same side; `needs` names the plugins it can't do without.\n *\n * Both halves import from here, so the parser is imported for its types only: the browser must not load it.\n */\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport type { Shortcut } from './shortcut.ts';\n\nexport type { Modifier, Shortcut } from './shortcut.ts';\n\n/** A place in the source: the file from the project's root, with `/`, and the line and column, from 1. */\nexport interface Loc {\n file: string;\n line: number;\n column: number;\n}\n\n/** An element the pointer picked: where its opening tag starts, and the tag, which the server checks is still there. */\nexport interface Target {\n loc: Loc;\n tag: string;\n}\n\n/** Text in a file to replace, by UTF-16 offsets. `file` is the target's unless named, from the project's root. */\nexport interface TextEdit {\n file?: string;\n start: number;\n end: number;\n text: string;\n}\n\n/** What a server half reads: the target's file, parsed, and its element. */\nexport interface Source {\n /** The target's file, from the project's root. */\n file: string;\n code: string;\n /** The file's module; for an `.astro` component, its frontmatter's. */\n program: Program;\n /** The target's opening tag. */\n element: JSXOpeningElement;\n /** Another file under the project's root, for plugins whose edits go elsewhere (a locale's messages). */\n read(file: string): string;\n}\n\n/**\n * What answers the overlay's requests in a page with no dev server behind it (`deictic/vite`'s `standalone`): the\n * default export of a module of the page's. A request is one the endpoints would get, under `<base>__deictic/`;\n * the answer is theirs too (`{ model }`, `{ model, change }`, `{ problem }` with a status that isn't ok).\n */\nexport type Standalone = (request: Request) => Response | Promise<Response>;\n\n/** An op a plugin won't make. The message says why and what to do instead; the panel shows it. */\nexport class Refusal extends Error {\n override name = 'Refusal';\n}\n\n/**\n * A change the plugin made itself, not to a file: what its `undo` and `redo` need to take it back and\n * make it again. JSON, since the history keeps it on disk across restarts of the dev server.\n */\nexport interface Done<Record = unknown> {\n done: Record;\n}\n\ntype Maybe<T> = T | Promise<T>;\n\n/**\n * Something of deictic's that went wrong, which nothing a person did in the page caused: a package the project\n * hasn't installed, a plugin that failed. The dev server says it, and hands it to each plugin with a `problem`\n * (tasks posts it to the board, for an agent to fix).\n */\nexport interface Problem {\n /**\n * What tells it apart, and the same problem again from a new one: `packages:rrweb`, `setup:tailwind`. Never a\n * time or an ID, so a problem that comes back is known.\n */\n key: string;\n /**\n * `setup`: the project's to fix, as `message` says (install a package, configure a plugin). `bug`: deictic's own, or\n * a plugin's, to report where it's made, not to patch where it's installed.\n */\n kind: 'setup' | 'bug';\n /** What went wrong, and the fix where there is one, as any problem message says it. */\n message: string;\n /** What more there is to look into: a stack. */\n details?: string;\n /** The plugin it's about, where it's one's: none for deictic's own. */\n plugin?: string;\n}\n\n/**\n * Each plugin's API to the others on the server, by name. A plugin adds its own, so `use` knows its type:\n * `declare module 'deictic' { interface ServerApis { screenshots: Screenshots } }`.\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ServerApis {}\n\n/** The same, in the page: `declare module 'deictic' { interface ClientApis { screenshots: Capture } }`. */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ClientApis {}\n\n/** A plugin's API, by its name: what its package declared, or `unknown` for one that declared none. */\nexport type ApiOf<Apis, Name extends string> = Name extends keyof Apis ? Apis[Name] : unknown;\n\nexport interface ServerContext {\n /** The project's root, as an absolute path. */\n root: string;\n /**\n * Another plugin's API, as its `setup` answered it, or nothing when it isn't loaded (or its `setup` failed,\n * which is reported). One the plugin `needs` always is loaded; any other may not be, so check.\n */\n use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;\n /** Says a problem of the plugin's own, as deictic says its own: in the dev server's output, and to each plugin's `problem`. */\n report: (problem: Problem) => void;\n}\n\n/**\n * A route of the plugin's own, at `/__deictic/plugins/<name>/<route>`, and below it. A `GET` must\n * change nothing: anything else reaches it only from the page itself, which deictic checks.\n */\nexport type Route = (request: Request, context: ServerContext) => Maybe<Response>;\n\nexport interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = unknown> {\n /** Ties the halves together; also the label of its changes in the history, and its routes' path. Lowercase, with `-`. */\n name: string;\n /** The module the page loads for this plugin's half there, which default-exports its `ClientPlugin`. */\n client?: string;\n /** What the page half gets as `context.options`: the user's options it needs there, as JSON. */\n clientOptions?: unknown;\n /** What opens its panel: its own default, which its options let the user change. A plugin with no panel has none. */\n shortcut?: Shortcut;\n /** The plugins it can't do without, by name: the dev server won't start without them. */\n needs?: string[];\n /**\n * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,\n * it says how to install any that's missing, rather than failing when first used.\n */\n packages?: string[];\n /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */\n setup?(context: ServerContext): Maybe<Api>;\n /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */\n routes?: { [route: string]: Route };\n /**\n * The model its panel shows for an element. Without it, the panel gets none. `source` is a `Refusal` where the\n * element isn't to be found in its file (it doesn't parse, or the page runs other code than it has): throw it where\n * the plugin needs the source, or go on without it, as a task does.\n */\n read?(source: Source | Refusal, target: Target): Maybe<Model>;\n /** Text edits for deictic to write, which it refuses without the source, or a change the plugin made itself. */\n apply?(source: Source | Refusal, target: Target, op: Op): Maybe<TextEdit[] | Done<Record>>;\n /**\n * Takes back a change `apply` made itself, or throws a `Refusal` saying why it can't any more. It may\n * answer what the next redo needs, where that differs (what it put back has a new ID).\n */\n undo?(record: Record): Maybe<void | Record>;\n /** Makes it again after an undo, and answers what the next undo needs, which may differ (a new ID). */\n redo?(record: Record): Maybe<Record>;\n /** Says what an op does, for the history: `className: px-2 → px-4`. */\n describe?(op: Op, before: Model): string;\n /**\n * Hears each problem deictic or a plugin reports, on the server or in the page, after every `setup` has run: once\n * per `key` while the dev server runs. Its own failure is only said, never reported again.\n */\n problem?(problem: Problem): Maybe<void>;\n}\n\nexport const definePlugin = <Model, Op, Record = unknown, Api = unknown>(\n plugin: ServerPlugin<Model, Op, Record, Api>,\n): ServerPlugin<Model, Op, Record, Api> => plugin;\n\n/** Where something is in an element, in CSS pixels from its top left. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** A spot on the page: a marked element, and a point in it (or beside it, for the nearest to a point no marked element is under). */\nexport interface Spot {\n element: Element;\n at: Point;\n}\n\n/**\n * The tool panel: a bar docked to an edge of the window, which shows while a shortcut's keys are held and stays\n * while it's in use. A plugin adds its tools to it from its page half's `setup`.\n */\nexport interface ToolPanel {\n /**\n * Adds a plugin's controls, as one group, in the order plugins are loaded. Groups of one `section` sit together,\n * with no line between them, after the groups of none: the screenshots', recordings', voice's and tasks' are\n * `capture`. `last` puts a group at the end of its section, or after all the others for one of none. Each control is a button named by its `title`; its `aria-keyshortcuts`\n * (`B`, `Control+Z`) is the key the panel hears for it, alone or with the keys held to point, and what its tooltip\n * shows.\n */\n add: (group: HTMLElement, options?: { last?: boolean; section?: string }) => void;\n /**\n * Takes the page for a tool that works on it (drawing, picking a point): the tool that had it lets go first, and\n * the panel stays shown. `left` is called when another takes it, or Esc or the pointer tool gives the page back.\n * Answers what lets go of it, for the tool to call when it's done on its own.\n */\n hold: (left: () => void) => () => void;\n /** Keeps the panel shown while something goes on that its controls end (a recording). Answers what ends that. */\n keep: () => () => void;\n /**\n * Takes the page until a point of it is pressed, lighting what's under the pointer as pointing does: answers the\n * spot, the marked element there or the nearest to it, or nothing where the page was given back first.\n */\n pick: () => Promise<Spot | undefined>;\n}\n\n/**\n * The drawer: on the window's side, where what the plugins have for the page lands, a section each. It\n * shows while a shortcut's keys are held and a section has something, and stays while it's in use.\n */\nexport interface Drawer {\n /**\n * Adds a section, in the order added, or before the others with `first`. A section that has nothing to show sets\n * its own `hidden`: the drawer stays away while every one is. Folded away, the drawer counts what the sections\n * have: each says how many things it lists in `data-count`, and how many are unread in `data-unread`.\n */\n add: (section: HTMLElement, options?: { first?: boolean }) => void;\n /**\n * Opens one item in the drawer, in the sections' place, under `title` and a way back. The drawer stays while it's\n * open. `closed` is called when it's left, by the way back, Esc, or another item opening. Answers what closes it.\n */\n show: (view: HTMLElement, options?: { title?: string; closed?: () => void }) => () => void;\n /** Keeps the drawer up while something goes on in it; answers what lets it go. */\n keep: () => () => void;\n}\n\n/** Something a plugin made on the page that nothing has taken yet: a shot, a recording, a voice clip. */\nexport interface TrayItem {\n /** The plugin that made it. */\n plugin: string;\n /** Its ID, as that plugin has it. */\n id: string;\n /** What that plugin says of it, as JSON: the screenshots plugin's `Shot`, a `Recording`, a `Clip`. */\n value: unknown;\n}\n\n/**\n * What plugins made on the page from the tool panel, until something takes it: a task attaches what's there and\n * removes it. Kept for the tab's session, so it's there on the tab's next page too.\n */\nexport interface Tray {\n /** What's kept, oldest first: all of it, or one plugin's. */\n list: (plugin?: string) => TrayItem[];\n add: (plugin: string, id: string, value: unknown) => void;\n /** Takes one out, or all of a plugin's. */\n remove: (plugin: string, id?: string) => void;\n /** Hears every change from now on; answers what stops it. */\n subscribe: (listener: () => void) => () => void;\n}\n\nexport interface ClientContext {\n /** The dev server's base URL, ending in `/`. */\n base: string;\n /** deictic's shadow root, to draw in: neither the page's styles nor the overlay's cross over. */\n root: ShadowRoot;\n /** The server half's `clientOptions`, or nothing. */\n options: unknown;\n /** Another plugin's API in the page, as its `setup` answered it, or nothing when it isn't loaded. */\n use: <Name extends string>(name: Name) => ApiOf<ClientApis, Name> | undefined;\n /** Asks one of this plugin's own routes, from the page: `request('shots', { method: 'POST', body: blob })`. */\n request: (route: string, init?: RequestInit) => Promise<Response>;\n /** Says a problem of the plugin's own to the dev server, as the server half's `report` does: its `plugin` is this one. */\n report: (problem: Problem) => void;\n /**\n * Opens a place in a file under the root in the editor, as the popup's own link opens the element's: through the\n * dev server, or what answers in its place (`Standalone`). Rejects with why it couldn't.\n */\n edit: (place: Loc) => Promise<void>;\n /**\n * Opens the popup on an element at a plugin's tab, as its shortcut would, or with `at` on a spot in it: the\n * popup is then beside the spot, which is what's lit, and the tab's context has it. An element rendered again\n * since stands in for one no longer on the page. False when there's no such tab or no such element any more, and\n * while the open popup holds something unsaved, whose button then shakes. Not as `setup` runs, which is before the\n * popup can open.\n */\n open: (plugin: string, element: Element, at?: Point) => boolean;\n /** The tool panel, to add this plugin's tools to. */\n tools: ToolPanel;\n /** What was made from the tool panel and not taken yet. */\n tray: Tray;\n /** The drawer, to add this plugin's section to. */\n drawer: Drawer;\n /**\n * Lights an element on the page as pointing at it does, for something of the overlay's own that stands for it (a\n * task's row in the drawer, while the pointer is on it); none puts the light back as it was.\n */\n light: (element?: Element) => void;\n /**\n * Shows `items` in the lightbox over everything, at `at` (the first by default), stepping between them with\n * ← and →. With `from`, it grows out of that element (the chip clicked) and shrinks back into it on close.\n */\n lightbox: (items: LightboxItem[], options?: LightboxOptions) => { close: () => void };\n}\n\n/** What the lightbox shows: a picture, a page in a frame (a recording's replay), or a sound with its waveform. */\nexport type LightboxItem = {\n /** Its name, over it. */\n title: string;\n /** Buttons beside the name: each closes the lightbox and runs. */\n actions?: LightboxAction[];\n} & ({ kind: 'image'; url: string } | { kind: 'page'; url: string } | { kind: 'audio'; url: string });\n\nexport interface LightboxAction {\n label: string;\n title?: string;\n run: () => void;\n}\n\nexport interface LightboxOptions {\n /** The item it opens at. */\n at?: number;\n /** The element it grows out of, and goes back into. */\n from?: Element;\n}\n\nexport interface PanelContext<Model, Op> extends ClientContext {\n /**\n * The element clicked: the one the source marked, under the pointer or around what is. Back from `away`\n * it may be off the page (`isConnected` is false), where the page moved on without it: the element as it\n * was left, or after a page load an empty one of its tag and mark. `elements` is then empty.\n */\n element: Element;\n /**\n * What was under the pointer, where it isn't `element` but inside it: markup nothing marked, as a\n * dependency's, or in an open shadow root, as the popup's own on a page that shows it (`popupIn`).\n */\n pointed?: Element;\n /** The spot in `element` the popup was opened on, where it was (the tool panel's task tool), not the element as a whole. */\n at?: Point;\n /** Every element on the page from the same place in the source, the clicked one among them: the rows of a list. */\n elements: Element[];\n target: Target;\n model: Model;\n /**\n * Applies an op on disk, and reads the model again. Rejects with the server's reason, which the panel also shows.\n * On another element with `on`, whose model is then the one answered: for an op that's about that one.\n */\n apply(op: Op, on?: Target): Promise<Model>;\n close: () => void;\n /**\n * Says there's something here that leaving would lose (words typed, a change tried on the page), and the button\n * that keeps it: a click outside the popup then shakes that button, where it would have closed the popup.\n * `undefined` once there's nothing to lose. Forgotten as the panel unmounts.\n */\n unsaved: (action: HTMLElement | undefined) => void;\n /**\n * Leaves the popup to do something on the page, then comes back: closes it, runs `task` (a recording, a\n * pick of another element), and opens it again at this tab on this element. The next mount gets\n * `resumed`: the `state` kept now (what was typed, what's attached), and what `task` answered, or why\n * it failed. The state stays in the page, as it is: no need for JSON. It's also kept for the tab's next\n * page, as a structured clone, where it can be one: after a page load, the plugin's `resume` says whether\n * the task carries on, and the popup comes back there.\n */\n away: <T>(state: unknown, task: () => Promise<T>) => void;\n /** Set when this mount is the panel coming back from `away`. */\n resumed?: Resumed;\n}\n\n/** What a panel coming back from `away` gets: the state it kept, and the task's result or problem. */\nexport interface Resumed {\n state: unknown;\n result?: unknown;\n /** Why the task failed: its error's message. */\n problem?: string;\n}\n\nexport interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {\n /** The server half's `name`. */\n name: string;\n /** Shown over the element while its shortcut's keys are held, and atop the panel. */\n label?: string;\n /**\n * Runs once, as the page starts, before any panel opens (a recording starts here). Answers the\n * plugin's API to the others in the page, at once: one that needs time keeps its promises inside it.\n */\n setup?(context: ClientContext): Api;\n /**\n * Asked as a page starts where the page before it left this plugin's panel `away`: the task it left for,\n * where that carries on in this page (a recording does), or nothing where it ended with the page. When it's\n * done the popup opens at this tab with `resumed`, on the element where this page has it and without where not.\n */\n resume?(context: ClientContext): Promise<unknown> | undefined;\n /**\n * What it shows on the page while a shortcut's keys are held, and the page is dimmed to point on: the tasks\n * plugin pins each task where its element is. Answers what takes it away.\n */\n pointing?(context: ClientContext): () => void;\n /**\n * A shortcut's press on a marked element, before the page hears it and before the popup opens: the page as the\n * person saw it, a tooltip still open under the pointer, a menu still focused. Called as the press goes down, so\n * it must be quick; the screenshots plugin keeps what a shot needs here, and renders it later.\n */\n pressed?(context: ClientContext, element: Element): void;\n /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */\n mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;\n}\n\nexport const defineClientPlugin = <Model, Op, Api = unknown>(plugin: ClientPlugin<Model, Op, Api>): ClientPlugin<Model, Op, Api> => plugin;\n"],"mappings":";;AAqEA,IAAa,UAAb,cAA6B,MAAM;CACxB,OAAO;AAClB;AAgHA,MAAa,gBACX,WACyC;AAyO3C,MAAa,sBAAgD,WAAuE"}
|
|
1
|
+
{"version":3,"file":"src.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * `deictic`: what a plugin is. Every plugin is optional: deictic itself is the glue (the\n * transform that ties elements to source, the dev server's endpoints, the history, shortcuts and the\n * overlay's panel), and each plugin adds what it does on top.\n *\n * A plugin has two halves, each optional that meet over the dev server's endpoints (`tools/endpoints.ts`). The\n * server half runs beside the bundler and is the only one that reads source: it turns the element\n * under the pointer into a model its panel can show, and an op from that panel into text edits. It\n * never writes files; deictic does, so every plugin's changes land in one history and undo the\n * same way. A change that isn't to a file (a task added to a board) the plugin makes itself and\n * answers with what it did (`Done`): the history keeps that beside the files' changes and hands it\n * back to the plugin's own `undo` and `redo`.\n * The client half is a module the page loads, named by the server half's `client`, which draws the\n * panel and previews an op on the page before it is applied.\n *\n * A plugin may have no panel at all, only an API for others (screenshots, a recording) and routes of\n * its own on the dev server. Each half's `setup` answers its API, and `use(name)` reaches another\n * plugin's, on the same side; `needs` names the plugins it can't do without.\n *\n * Both halves import from here, so the parser is imported for its types only: the browser must not load it.\n */\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport type { Shortcut } from './shortcut.ts';\n\nexport type { Modifier, Shortcut } from './shortcut.ts';\n\n/** A place in the source: the file from the project's root, with `/`, and the line and column, from 1. */\nexport interface Loc {\n file: string;\n line: number;\n column: number;\n}\n\n/** An element the pointer picked: where its opening tag starts, and the tag, which the server checks is still there. */\nexport interface Target {\n loc: Loc;\n tag: string;\n}\n\n/** Text in a file to replace, by UTF-16 offsets. `file` is the target's unless named, from the project's root. */\nexport interface TextEdit {\n file?: string;\n start: number;\n end: number;\n text: string;\n}\n\n/** What a server half reads: the target's file, parsed, and its element. */\nexport interface Source {\n /** The target's file, from the project's root. */\n file: string;\n code: string;\n /** The file's module; for an `.astro` component, its frontmatter's. */\n program: Program;\n /** The target's opening tag. */\n element: JSXOpeningElement;\n /** Another file under the project's root, for plugins whose edits go elsewhere (a locale's messages). */\n read(file: string): string;\n}\n\n/**\n * What answers the overlay's requests in a page with no dev server behind it (`deictic/vite`'s `standalone`): the\n * default export of a module of the page's. A request is one the endpoints would get, under `<base>__deictic/`;\n * the answer is theirs too (`{ model }`, `{ model, change }`, `{ problem }` with a status that isn't ok).\n */\nexport type Standalone = (request: Request) => Response | Promise<Response>;\n\n/** An op a plugin won't make. The message says why and what to do instead; the panel shows it. */\nexport class Refusal extends Error {\n override name = 'Refusal';\n}\n\n/**\n * A change the plugin made itself, not to a file: what its `undo` and `redo` need to take it back and\n * make it again. JSON, since the history keeps it on disk across restarts of the dev server.\n */\nexport interface Done<Record = unknown> {\n done: Record;\n}\n\ntype Maybe<T> = T | Promise<T>;\n\n/**\n * Something of deictic's that went wrong, which nothing a person did in the page caused: a package the project\n * hasn't installed, a plugin that failed. The dev server says it, and hands it to each plugin with a `problem`\n * (tasks posts it to the board, for an agent to fix).\n */\nexport interface Problem {\n /**\n * What tells it apart, and the same problem again from a new one: `packages:rrweb`, `setup:tailwind`. Never a\n * time or an ID, so a problem that comes back is known.\n */\n key: string;\n /**\n * `setup`: the project's to fix, as `message` says (install a package, configure a plugin). `bug`: deictic's own, or\n * a plugin's, to report where it's made, not to patch where it's installed.\n */\n kind: 'setup' | 'bug';\n /** What went wrong, and the fix where there is one, as any problem message says it. */\n message: string;\n /** What more there is to look into: a stack. */\n details?: string;\n /** The plugin it's about, where it's one's: none for deictic's own. */\n plugin?: string;\n}\n\n/**\n * Each plugin's API to the others on the server, by name. A plugin adds its own, so `use` knows its type:\n * `declare module 'deictic' { interface ServerApis { screenshots: Screenshots } }`.\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ServerApis {}\n\n/** The same, in the page: `declare module 'deictic' { interface ClientApis { screenshots: Capture } }`. */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ClientApis {}\n\n/** A plugin's API, by its name: what its package declared, or `unknown` for one that declared none. */\nexport type ApiOf<Apis, Name extends string> = Name extends keyof Apis ? Apis[Name] : unknown;\n\nexport interface ServerContext {\n /** The project's root, as an absolute path. */\n root: string;\n /**\n * Another plugin's API, as its `setup` answered it, or nothing when it isn't loaded (or its `setup` failed,\n * which is reported). One the plugin `needs` always is loaded; any other may not be, so check.\n */\n use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;\n /** Says a problem of the plugin's own, as deictic says its own: in the dev server's output, and to each plugin's `problem`. */\n report: (problem: Problem) => void;\n /**\n * Runs `callback` as the dev server closes, to undo what `setup` did beyond the plugin itself: a global it set, a\n * watcher or a server it started. Under Vite and webpack; a dev server that only ends with its process runs none.\n */\n onClose: (callback: () => Maybe<void>) => void;\n}\n\n/**\n * A route of the plugin's own, at `/__deictic/plugins/<name>/<route>`, and below it. A `GET` must\n * change nothing: anything else reaches it only from the page itself, which deictic checks.\n */\nexport type Route = (request: Request, context: ServerContext) => Maybe<Response>;\n\nexport interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = unknown> {\n /** Ties the halves together; also the label of its changes in the history, and its routes' path. Lowercase, with `-`. */\n name: string;\n /** The module the page loads for this plugin's half there, which default-exports its `ClientPlugin`. */\n client?: string;\n /** What the page half gets as `context.options`: the user's options it needs there, as JSON. */\n clientOptions?: unknown;\n /** What opens its panel: its own default, which its options let the user change. A plugin with no panel has none. */\n shortcut?: Shortcut;\n /** The plugins it can't do without, by name: the dev server won't start without them. */\n needs?: string[];\n /**\n * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,\n * it says how to install any that's missing, rather than failing when first used.\n */\n packages?: string[];\n /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */\n setup?(context: ServerContext): Maybe<Api>;\n /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */\n routes?: { [route: string]: Route };\n /**\n * The model its panel shows for an element. Without it, the panel gets none. `source` is a `Refusal` where the\n * element isn't to be found in its file (it doesn't parse, or the page runs other code than it has): throw it where\n * the plugin needs the source, or go on without it, as a task does.\n */\n read?(source: Source | Refusal, target: Target): Maybe<Model>;\n /** Text edits for deictic to write, which it refuses without the source, or a change the plugin made itself. */\n apply?(source: Source | Refusal, target: Target, op: Op): Maybe<TextEdit[] | Done<Record>>;\n /**\n * Takes back a change `apply` made itself, or throws a `Refusal` saying why it can't any more. It may\n * answer what the next redo needs, where that differs (what it put back has a new ID).\n */\n undo?(record: Record): Maybe<void | Record>;\n /** Makes it again after an undo, and answers what the next undo needs, which may differ (a new ID). */\n redo?(record: Record): Maybe<Record>;\n /** Says what an op does, for the history: `className: px-2 → px-4`. */\n describe?(op: Op, before: Model): string;\n /**\n * Hears each problem deictic or a plugin reports, on the server or in the page, after every `setup` has run: once\n * per `key` while the dev server runs. Its own failure is only said, never reported again.\n */\n problem?(problem: Problem): Maybe<void>;\n}\n\nexport const definePlugin = <Model, Op, Record = unknown, Api = unknown>(\n plugin: ServerPlugin<Model, Op, Record, Api>,\n): ServerPlugin<Model, Op, Record, Api> => plugin;\n\n/** Where something is in an element, in CSS pixels from its top left. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** A spot on the page: a marked element, and a point in it (or beside it, for the nearest to a point no marked element is under). */\nexport interface Spot {\n element: Element;\n at: Point;\n}\n\n/**\n * The tool panel: a bar docked to an edge of the window, which shows while a shortcut's keys are held and stays\n * while it's in use. A plugin adds its tools to it from its page half's `setup`.\n */\nexport interface ToolPanel {\n /**\n * Adds a plugin's controls, as one group, in the order plugins are loaded. Groups of one `section` sit together,\n * with no line between them, after the groups of none: the screenshots', recordings', voice's and tasks' are\n * `capture`. `last` puts a group at the end of its section, or after all the others for one of none. Each control is a button named by its `title`; its `aria-keyshortcuts`\n * (`B`, `Control+Z`) is the key the panel hears for it, alone or with the keys held to point, and what its tooltip\n * shows.\n */\n add: (group: HTMLElement, options?: { last?: boolean; section?: string }) => void;\n /**\n * Takes the page for a tool that works on it (drawing, picking a point): the tool that had it lets go first, and\n * the panel stays shown. `left` is called when another takes it, or Esc or the pointer tool gives the page back.\n * Answers what lets go of it, for the tool to call when it's done on its own.\n */\n hold: (left: () => void) => () => void;\n /** Keeps the panel shown while something goes on that its controls end (a recording). Answers what ends that. */\n keep: () => () => void;\n /**\n * Takes the page until a point of it is pressed, lighting what's under the pointer as pointing does: answers the\n * spot, the marked element there or the nearest to it, or nothing where the page was given back first.\n */\n pick: () => Promise<Spot | undefined>;\n}\n\n/**\n * The drawer: on the window's side, where what the plugins have for the page lands, a section each. It\n * shows while a shortcut's keys are held and a section has something, and stays while it's in use.\n */\nexport interface Drawer {\n /**\n * Adds a section, in the order added, or before the others with `first`. A section that has nothing to show sets\n * its own `hidden`: the drawer stays away while every one is. Folded away, the drawer counts what the sections\n * have: each says how many things it lists in `data-count`, and how many are unread in `data-unread`.\n */\n add: (section: HTMLElement, options?: { first?: boolean }) => void;\n /**\n * Opens one item in the drawer, in the sections' place, under `title` and a way back. The drawer stays while it's\n * open. `closed` is called when it's left, by the way back, Esc, or another item opening. Answers what closes it.\n */\n show: (view: HTMLElement, options?: { title?: string; closed?: () => void }) => () => void;\n /** Keeps the drawer up while something goes on in it; answers what lets it go. */\n keep: () => () => void;\n}\n\n/** Something a plugin made on the page that nothing has taken yet: a shot, a recording, a voice clip. */\nexport interface TrayItem {\n /** The plugin that made it. */\n plugin: string;\n /** Its ID, as that plugin has it. */\n id: string;\n /** What that plugin says of it, as JSON: the screenshots plugin's `Shot`, a `Recording`, a `Clip`. */\n value: unknown;\n}\n\n/**\n * What plugins made on the page from the tool panel, until something takes it: a task attaches what's there and\n * removes it. Kept for the tab's session, so it's there on the tab's next page too.\n */\nexport interface Tray {\n /** What's kept, oldest first: all of it, or one plugin's. */\n list: (plugin?: string) => TrayItem[];\n add: (plugin: string, id: string, value: unknown) => void;\n /** Takes one out, or all of a plugin's. */\n remove: (plugin: string, id?: string) => void;\n /** Hears every change from now on; answers what stops it. */\n subscribe: (listener: () => void) => () => void;\n}\n\nexport interface ClientContext {\n /** The dev server's base URL, ending in `/`. */\n base: string;\n /** deictic's shadow root, to draw in: neither the page's styles nor the overlay's cross over. */\n root: ShadowRoot;\n /** The server half's `clientOptions`, or nothing. */\n options: unknown;\n /** Another plugin's API in the page, as its `setup` answered it, or nothing when it isn't loaded. */\n use: <Name extends string>(name: Name) => ApiOf<ClientApis, Name> | undefined;\n /** Asks one of this plugin's own routes, from the page: `request('shots', { method: 'POST', body: blob })`. */\n request: (route: string, init?: RequestInit) => Promise<Response>;\n /** Says a problem of the plugin's own to the dev server, as the server half's `report` does: its `plugin` is this one. */\n report: (problem: Problem) => void;\n /**\n * Opens a place in a file under the root in the editor, as the popup's own link opens the element's: through the\n * dev server, or what answers in its place (`Standalone`). Rejects with why it couldn't.\n */\n edit: (place: Loc) => Promise<void>;\n /**\n * Opens the popup on an element at a plugin's tab, as its shortcut would, or with `at` on a spot in it: the\n * popup is then beside the spot, which is what's lit, and the tab's context has it. An element rendered again\n * since stands in for one no longer on the page. False when there's no such tab or no such element any more, and\n * while the open popup holds something unsaved, whose button then shakes. Not as `setup` runs, which is before the\n * popup can open.\n */\n open: (plugin: string, element: Element, at?: Point) => boolean;\n /** The tool panel, to add this plugin's tools to. */\n tools: ToolPanel;\n /** What was made from the tool panel and not taken yet. */\n tray: Tray;\n /** The drawer, to add this plugin's section to. */\n drawer: Drawer;\n /**\n * Lights an element on the page as pointing at it does, for something of the overlay's own that stands for it (a\n * task's row in the drawer, while the pointer is on it); none puts the light back as it was.\n */\n light: (element?: Element) => void;\n /**\n * Shows `items` in the lightbox over everything, at `at` (the first by default), stepping between them with\n * ← and →. With `from`, it grows out of that element (the chip clicked) and shrinks back into it on close.\n */\n lightbox: (items: LightboxItem[], options?: LightboxOptions) => { close: () => void };\n}\n\n/** What the lightbox shows: a picture, a page in a frame (a recording's replay), or a sound with its waveform. */\nexport type LightboxItem = {\n /** Its name, over it. */\n title: string;\n /** Buttons beside the name: each closes the lightbox and runs. */\n actions?: LightboxAction[];\n} & ({ kind: 'image'; url: string } | { kind: 'page'; url: string } | { kind: 'audio'; url: string });\n\nexport interface LightboxAction {\n label: string;\n title?: string;\n run: () => void;\n}\n\nexport interface LightboxOptions {\n /** The item it opens at. */\n at?: number;\n /** The element it grows out of, and goes back into. */\n from?: Element;\n}\n\nexport interface PanelContext<Model, Op> extends ClientContext {\n /**\n * The element clicked: the one the source marked, under the pointer or around what is. Back from `away`\n * it may be off the page (`isConnected` is false), where the page moved on without it: the element as it\n * was left, or after a page load an empty one of its tag and mark. `elements` is then empty.\n */\n element: Element;\n /**\n * What was under the pointer, where it isn't `element` but inside it: markup nothing marked, as a\n * dependency's, or in an open shadow root, as the popup's own on a page that shows it (`popupIn`).\n */\n pointed?: Element;\n /** The spot in `element` the popup was opened on, where it was (the tool panel's task tool), not the element as a whole. */\n at?: Point;\n /** Every element on the page from the same place in the source, the clicked one among them: the rows of a list. */\n elements: Element[];\n target: Target;\n model: Model;\n /**\n * Applies an op on disk, and reads the model again. Rejects with the server's reason, which the panel also shows.\n * On another element with `on`, whose model is then the one answered: for an op that's about that one.\n */\n apply(op: Op, on?: Target): Promise<Model>;\n close: () => void;\n /**\n * Says there's something here that leaving would lose (words typed, a change tried on the page), and the button\n * that keeps it: a click outside the popup then shakes that button, where it would have closed the popup.\n * `undefined` once there's nothing to lose. Forgotten as the panel unmounts.\n */\n unsaved: (action: HTMLElement | undefined) => void;\n /**\n * Leaves the popup to do something on the page, then comes back: closes it, runs `task` (a recording, a\n * pick of another element), and opens it again at this tab on this element. The next mount gets\n * `resumed`: the `state` kept now (what was typed, what's attached), and what `task` answered, or why\n * it failed. The state stays in the page, as it is: no need for JSON. It's also kept for the tab's next\n * page, as a structured clone, where it can be one: after a page load, the plugin's `resume` says whether\n * the task carries on, and the popup comes back there.\n */\n away: <T>(state: unknown, task: () => Promise<T>) => void;\n /** Set when this mount is the panel coming back from `away`. */\n resumed?: Resumed;\n}\n\n/** What a panel coming back from `away` gets: the state it kept, and the task's result or problem. */\nexport interface Resumed {\n state: unknown;\n result?: unknown;\n /** Why the task failed: its error's message. */\n problem?: string;\n}\n\nexport interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {\n /** The server half's `name`. */\n name: string;\n /** Shown over the element while its shortcut's keys are held, and atop the panel. */\n label?: string;\n /**\n * Runs once, as the page starts, before any panel opens (a recording starts here). Answers the\n * plugin's API to the others in the page, at once: one that needs time keeps its promises inside it.\n */\n setup?(context: ClientContext): Api;\n /**\n * Asked as a page starts where the page before it left this plugin's panel `away`: the task it left for,\n * where that carries on in this page (a recording does), or nothing where it ended with the page. When it's\n * done the popup opens at this tab with `resumed`, on the element where this page has it and without where not.\n */\n resume?(context: ClientContext): Promise<unknown> | undefined;\n /**\n * What it shows on the page while a shortcut's keys are held, and the page is dimmed to point on: the tasks\n * plugin pins each task where its element is. Answers what takes it away.\n */\n pointing?(context: ClientContext): () => void;\n /**\n * A shortcut's press on a marked element, before the page hears it and before the popup opens: the page as the\n * person saw it, a tooltip still open under the pointer, a menu still focused. Called as the press goes down, so\n * it must be quick; the screenshots plugin keeps what a shot needs here, and renders it later.\n */\n pressed?(context: ClientContext, element: Element): void;\n /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */\n mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;\n}\n\nexport const defineClientPlugin = <Model, Op, Api = unknown>(plugin: ClientPlugin<Model, Op, Api>): ClientPlugin<Model, Op, Api> => plugin;\n"],"mappings":";;AAqEA,IAAa,UAAb,cAA6B,MAAM;CACxB,OAAO;AAClB;AAqHA,MAAa,gBACX,WACyC;AAyO3C,MAAa,sBAAgD,WAAuE"}
|
package/dist/shared/vite.js
CHANGED
|
@@ -24,6 +24,7 @@ function deictic(given = {}) {
|
|
|
24
24
|
let options = given;
|
|
25
25
|
let { plugins, shortcut } = prepare(given);
|
|
26
26
|
let leading = true;
|
|
27
|
+
let handle;
|
|
27
28
|
let root = "";
|
|
28
29
|
let base = "/";
|
|
29
30
|
let building = false;
|
|
@@ -48,7 +49,7 @@ function deictic(given = {}) {
|
|
|
48
49
|
},
|
|
49
50
|
configureServer(server) {
|
|
50
51
|
if (!leading) return;
|
|
51
|
-
|
|
52
|
+
handle = endpoints({
|
|
52
53
|
root,
|
|
53
54
|
plugins,
|
|
54
55
|
base,
|
|
@@ -56,6 +57,9 @@ function deictic(given = {}) {
|
|
|
56
57
|
});
|
|
57
58
|
server.middlewares.use(nodeMiddleware(handle));
|
|
58
59
|
},
|
|
60
|
+
async closeBundle() {
|
|
61
|
+
await handle?.close();
|
|
62
|
+
},
|
|
59
63
|
resolveId: (source) => leading && source === "virtual:deictic/client" ? CLIENT_ID : void 0,
|
|
60
64
|
load(module) {
|
|
61
65
|
if (!leading || module !== CLIENT_ID) return void 0;
|
package/dist/shared/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../../src/vite.ts"],"sourcesContent":["/**\n * `deictic/vite`: deictic in Vite's dev server. Nothing runs in a build, unless `standalone` asks for it.\n *\n * Its transform runs `pre`, so each JSX module's host elements are marked with their place in the\n * source as written (`tools/locate.ts`). In the browser each marked module also imports the client\n * module, which starts the overlay with every plugin's panel: imports run first and only once, so no\n * line moves and frameworks that render their own HTML get it too. The endpoints are middleware on\n * Vite's server, and a place opens through Vite's own `/__open-in-editor`, so the editor is whichever\n * Vite already launches. A write reaches the page through Vite's usual update for the file.\n *\n * A build may have deictic more than once: the app's, and one a package added with its own plugin (`defaults`).\n * The first in Vite's list does the work with all of their options merged (`merge`); the others do nothing.\n */\nimport { resolve } from 'node:path';\n\nimport type { Plugin } from 'vite';\n\nimport { endpoints, nodeMiddleware, redirect } from './tools/endpoints.ts';\nimport { clientModule, type DeicticOptions, mark, markAstro, merge, prepare } from './tools/integration.ts';\n\nexport { clientModule, type DeicticOptions };\n\nexport interface ViteOptions extends DeicticOptions {\n /**\n * deictic in a build too, for a page that shows it with no dev server behind it (a deployed demo): a module of\n * the page's, from the root, whose default export answers the overlay's requests there (a `Standalone`, from\n * `deictic`). The build's elements are marked and the overlay is in its bundle. The dev server answers as ever.\n * Without it, the default, nothing of deictic is in a build.\n */\n standalone?: string;\n}\n\n/** The client module's ID, which a page can import itself where nothing it bundles is JSX (Astro's pages). */\nexport const CLIENT = 'virtual:deictic/client';\nconst CLIENT_ID = '\\0deictic/client';\n\n/** What each deictic in Vite's list carries, for the first of them to find the others by. */\ninterface Carried {\n deictic: { options: ViteOptions; id: symbol };\n}\n\nconst carriedBy = (plugin: { api?: unknown }) => (plugin.api as Partial<Carried> | undefined)?.deictic;\n\nexport function deictic(given: ViteOptions = {}): Plugin {\n const id = Symbol('deictic');\n let options = given;\n let { plugins, shortcut } = prepare(given);\n let leading = true;\n let root = '';\n let base = '/';\n let building = false;\n return {\n name: 'deictic',\n enforce: 'pre',\n apply: (_, { command }) => command === 'serve' || given.standalone !== undefined,\n api: { deictic: { options: given, id } } satisfies Carried,\n // The client is the app's to bundle as it changes, not a dependency to prebundle once.\n config: () => ({ optimizeDeps: { exclude: ['deictic'] } }),\n configResolved(config) {\n root = config.root;\n base = config.base;\n building = config.command === 'build';\n const all = config.plugins.flatMap((p) => carriedBy(p) ?? []);\n leading = all[0]?.id === id;\n if (!leading || all.length === 1) return;\n options = merge(all.map((c) => c.options));\n ({ plugins, shortcut } = prepare(options));\n },\n configureServer(server) {\n if (!leading) return;\n
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../../src/vite.ts"],"sourcesContent":["/**\n * `deictic/vite`: deictic in Vite's dev server. Nothing runs in a build, unless `standalone` asks for it.\n *\n * Its transform runs `pre`, so each JSX module's host elements are marked with their place in the\n * source as written (`tools/locate.ts`). In the browser each marked module also imports the client\n * module, which starts the overlay with every plugin's panel: imports run first and only once, so no\n * line moves and frameworks that render their own HTML get it too. The endpoints are middleware on\n * Vite's server, and a place opens through Vite's own `/__open-in-editor`, so the editor is whichever\n * Vite already launches. A write reaches the page through Vite's usual update for the file.\n *\n * A build may have deictic more than once: the app's, and one a package added with its own plugin (`defaults`).\n * The first in Vite's list does the work with all of their options merged (`merge`); the others do nothing.\n */\nimport { resolve } from 'node:path';\n\nimport type { Plugin } from 'vite';\n\nimport { type Endpoints, endpoints, nodeMiddleware, redirect } from './tools/endpoints.ts';\nimport { clientModule, type DeicticOptions, mark, markAstro, merge, prepare } from './tools/integration.ts';\n\nexport { clientModule, type DeicticOptions };\n\nexport interface ViteOptions extends DeicticOptions {\n /**\n * deictic in a build too, for a page that shows it with no dev server behind it (a deployed demo): a module of\n * the page's, from the root, whose default export answers the overlay's requests there (a `Standalone`, from\n * `deictic`). The build's elements are marked and the overlay is in its bundle. The dev server answers as ever.\n * Without it, the default, nothing of deictic is in a build.\n */\n standalone?: string;\n}\n\n/** The client module's ID, which a page can import itself where nothing it bundles is JSX (Astro's pages). */\nexport const CLIENT = 'virtual:deictic/client';\nconst CLIENT_ID = '\\0deictic/client';\n\n/** What each deictic in Vite's list carries, for the first of them to find the others by. */\ninterface Carried {\n deictic: { options: ViteOptions; id: symbol };\n}\n\nconst carriedBy = (plugin: { api?: unknown }) => (plugin.api as Partial<Carried> | undefined)?.deictic;\n\nexport function deictic(given: ViteOptions = {}): Plugin {\n const id = Symbol('deictic');\n let options = given;\n let { plugins, shortcut } = prepare(given);\n let leading = true;\n let handle: Endpoints | undefined;\n let root = '';\n let base = '/';\n let building = false;\n return {\n name: 'deictic',\n enforce: 'pre',\n apply: (_, { command }) => command === 'serve' || given.standalone !== undefined,\n api: { deictic: { options: given, id } } satisfies Carried,\n // The client is the app's to bundle as it changes, not a dependency to prebundle once.\n config: () => ({ optimizeDeps: { exclude: ['deictic'] } }),\n configResolved(config) {\n root = config.root;\n base = config.base;\n building = config.command === 'build';\n const all = config.plugins.flatMap((p) => carriedBy(p) ?? []);\n leading = all[0]?.id === id;\n if (!leading || all.length === 1) return;\n options = merge(all.map((c) => c.options));\n ({ plugins, shortcut } = prepare(options));\n },\n configureServer(server) {\n if (!leading) return;\n handle = endpoints({\n root,\n plugins,\n base,\n open: (path, { line, column }) => redirect(`${base}__open-in-editor?${new URLSearchParams({ file: `${path}:${line}:${column}` })}`),\n });\n server.middlewares.use(nodeMiddleware(handle));\n },\n // Vite's dev server runs it as it closes, once per environment, and a build at its end, with no endpoints.\n async closeBundle() {\n await handle?.close();\n },\n resolveId: (source) => (leading && source === CLIENT ? CLIENT_ID : undefined),\n load(module) {\n if (!leading || module !== CLIENT_ID) return undefined;\n // Only a build's page asks the module: the dev server is there to answer.\n const server = building && options.standalone !== undefined ? resolve(root, options.standalone).replaceAll('\\\\', '/') : undefined;\n return clientModule(plugins, base, shortcut, server);\n },\n transform: {\n // First of all, not only first of the `pre` plugins: the React Compiler (`react({ compiler: true })`) is\n // `pre` too and compiles the JSX away, so after it there'd be no element to mark, wherever deictic is listed.\n order: 'pre',\n handler(code, module) {\n if (!leading) return undefined;\n const [path = ''] = module.split('?');\n // An `.astro` component itself, not the styles and scripts Astro loads from it by a query.\n if (path.endsWith('.astro')) return module === path ? markAstro(code, path, root) : undefined;\n const browser = this.environment.config.consumer === 'client';\n return mark(code, path, root, browser ? `\\nimport ${JSON.stringify(CLIENT)};\\n` : '');\n },\n },\n };\n}\n\nexport default deictic;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,MAAa,SAAS;AACtB,MAAM,YAAY;AAOlB,MAAM,aAAa,WAA+B,OAAO,KAAsC;AAE/F,SAAgB,QAAQ,QAAqB,CAAC,GAAW;CACvD,MAAM,KAAK,OAAO,SAAS;CAC3B,IAAI,UAAU;CACd,IAAI,EAAE,SAAS,aAAa,QAAQ,KAAK;CACzC,IAAI,UAAU;CACd,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,OAAO;CACX,IAAI,WAAW;CACf,OAAO;EACL,MAAM;EACN,SAAS;EACT,QAAQ,GAAG,EAAE,cAAc,YAAY,WAAW,MAAM,eAAe,KAAA;EACvE,KAAK,EAAE,SAAS;GAAE,SAAS;GAAO;EAAG,EAAE;EAEvC,eAAe,EAAE,cAAc,EAAE,SAAS,CAAC,SAAS,EAAE,EAAE;EACxD,eAAe,QAAQ;GACrB,OAAO,OAAO;GACd,OAAO,OAAO;GACd,WAAW,OAAO,YAAY;GAC9B,MAAM,MAAM,OAAO,QAAQ,SAAS,MAAM,UAAU,CAAC,KAAK,CAAC,CAAC;GAC5D,UAAU,IAAI,EAAE,EAAE,OAAO;GACzB,IAAI,CAAC,WAAW,IAAI,WAAW,GAAG;GAClC,UAAU,MAAM,IAAI,KAAK,MAAM,EAAE,OAAO,CAAC;GACzC,CAAC,CAAE,SAAS,YAAa,QAAQ,OAAO;EAC1C;EACA,gBAAgB,QAAQ;GACtB,IAAI,CAAC,SAAS;GACd,SAAS,UAAU;IACjB;IACA;IACA;IACA,OAAO,MAAM,EAAE,MAAM,aAAa,SAAS,GAAG,KAAK,mBAAmB,IAAI,gBAAgB,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,SAAS,CAAC,GAAG;GACpI,CAAC;GACD,OAAO,YAAY,IAAI,eAAe,MAAM,CAAC;EAC/C;EAEA,MAAM,cAAc;GAClB,MAAM,QAAQ,MAAM;EACtB;EACA,YAAY,WAAY,WAAW,WAAA,2BAAoB,YAAY,KAAA;EACnE,KAAK,QAAQ;GACX,IAAI,CAAC,WAAW,WAAW,WAAW,OAAO,KAAA;GAE7C,MAAM,SAAS,YAAY,QAAQ,eAAe,KAAA,IAAY,QAAQ,MAAM,QAAQ,UAAU,CAAC,CAAC,WAAW,MAAM,GAAG,IAAI,KAAA;GACxH,OAAO,aAAa,SAAS,MAAM,UAAU,MAAM;EACrD;EACA,WAAW;GAGT,OAAO;GACP,QAAQ,MAAM,QAAQ;IACpB,IAAI,CAAC,SAAS,OAAO,KAAA;IACrB,MAAM,CAAC,OAAO,MAAM,OAAO,MAAM,GAAG;IAEpC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO,WAAW,OAAO,UAAU,MAAM,MAAM,IAAI,IAAI,KAAA;IACpF,MAAM,UAAU,KAAK,YAAY,OAAO,aAAa;IACrD,OAAO,KAAK,MAAM,MAAM,MAAM,UAAU,YAAY,KAAK,UAAU,MAAM,EAAE,OAAO,EAAE;GACtF;EACF;CACF;AACF"}
|
package/dist/webpack.d.ts
CHANGED
|
@@ -30,6 +30,11 @@ type Middlewares = ({
|
|
|
30
30
|
/** What the plugin reads and sets of a webpack or Rspack compiler. */
|
|
31
31
|
interface Compiler {
|
|
32
32
|
context: string;
|
|
33
|
+
hooks: {
|
|
34
|
+
shutdown: {
|
|
35
|
+
tapPromise: (name: string, run: () => Promise<void>) => void;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
33
38
|
options: {
|
|
34
39
|
mode?: string;
|
|
35
40
|
target?: string | string[] | false;
|
package/dist/webpack.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.d.ts","names":[],"sources":["../src/webpack.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBAwBiB,8BAA8B;;EAE7C;;EAEA;;KAGG,cAAc,KAAK,iBAAiB,KAAK,gBAAgB;KACzD;EAAiB;EAAc,YAAY;IAAe;;UAGrD;EACR;EACA;IACE;IACA;IACA;MAAU;;IACV;MAAc,oBAAoB,aAAa,aAAa,oBAAoB;QAAgB;;;qBAkBvF;;
|
|
1
|
+
{"version":3,"file":"webpack.d.ts","names":[],"sources":["../src/webpack.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBAwBiB,8BAA8B;;EAE7C;;EAEA;;KAGG,cAAc,KAAK,iBAAiB,KAAK,gBAAgB;KACzD;EAAiB;EAAc,YAAY;IAAe;;UAGrD;EACR;EACA;IAAS;MAAY,aAAa,cAAc,WAAW;;;EAC3D;IACE;IACA;IACA;MAAU;;IACV;MAAc,oBAAoB,aAAa,aAAa,oBAAoB;QAAgB;;;qBAkBvF;;EAOX,YAAY,UAAS;;MAajB,cAAc;EAsBlB,MAAM,UAAU;;;qBAuCL,UAAO,UAAa,0BAAqB"}
|
package/dist/webpack.js
CHANGED
|
@@ -22,6 +22,7 @@ var DeicticPlugin = class {
|
|
|
22
22
|
#options;
|
|
23
23
|
#applied;
|
|
24
24
|
#middleware;
|
|
25
|
+
#endpoints;
|
|
25
26
|
#root = "";
|
|
26
27
|
constructor(options = {}) {
|
|
27
28
|
this.#options = options;
|
|
@@ -42,12 +43,13 @@ var DeicticPlugin = class {
|
|
|
42
43
|
return this.#middleware = (req, res, next) => {
|
|
43
44
|
if (handle === void 0) {
|
|
44
45
|
const merged = this.#merged();
|
|
45
|
-
|
|
46
|
+
this.#endpoints = endpoints({
|
|
46
47
|
root: this.#root,
|
|
47
48
|
plugins: prepare(merged).plugins,
|
|
48
49
|
base: merged.base ?? "/",
|
|
49
50
|
open: (path, loc) => openInEditor(path, loc)
|
|
50
|
-
})
|
|
51
|
+
});
|
|
52
|
+
handle = nodeMiddleware(this.#endpoints);
|
|
51
53
|
}
|
|
52
54
|
handle(req, res, next);
|
|
53
55
|
};
|
|
@@ -67,6 +69,9 @@ var DeicticPlugin = class {
|
|
|
67
69
|
const browser = forBrowser(compiler.options.target);
|
|
68
70
|
const client = browser ? writeClient(this.#root, plugins, merged.base ?? "/", shortcut) : void 0;
|
|
69
71
|
if (applied.first !== this) return;
|
|
72
|
+
compiler.hooks.shutdown.tapPromise("deictic", async () => {
|
|
73
|
+
await this.#endpoints?.close();
|
|
74
|
+
});
|
|
70
75
|
const options = {
|
|
71
76
|
root: this.#root,
|
|
72
77
|
...client === void 0 ? {} : { client }
|
package/dist/webpack.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":[],"sources":["../src/tools/editor.ts","../src/webpack.ts"],"sourcesContent":["/**\n * Opens a place in the editor, for a dev server without a launcher of its own (webpack's, Rspack's):\n * `launch-editor`, which Vite's own launcher uses, finds the editor that's running or the one `EDITOR`\n * names. An optional peer, imported when first asked.\n */\n\nimport type { Loc } from '#src/index.ts';\n\nexport async function openInEditor(path: string, { line, column }: Loc): Promise<Response> {\n const launcher = await import('launch-editor').catch(() => undefined);\n if (launcher === undefined)\n return new Response('deictic opens files with launch-editor here: add it to your devDependencies', { status: 501 });\n return new Promise((done) => {\n let failed = false;\n launcher.default(`${path}:${line}:${column}`, (_, message) => {\n failed = true;\n done(new Response(`${message ?? \"the editor didn't open\"}: set EDITOR to your editor's command`, { status: 500 }));\n });\n // launch-editor reports a failure as it happens, and nothing on success.\n setTimeout(() => failed || done(new Response(null, { status: 204 })), 50);\n });\n}\n","/**\n * `deictic/webpack`: deictic in webpack's dev server, or Rspack's (`@rspack/core` takes the same\n * plugin). Nothing runs out of development mode.\n *\n * A loader (`loader.ts`) runs `pre` on the project's JSX modules, marking each host element with its\n * place in the source as written, and in a build for the browser appending the import of the client\n * module, which webpack has no virtual module for, so it's written to `.deictic/client.js`. The\n * endpoints go in front of the dev server's own middleware (`devServer.setupMiddlewares`, which\n * webpack-dev-server and Rspack's both read), and a place opens with `launch-editor`, as webpack has no\n * launcher of its own. Where the dev server is started by hand, or by Rsbuild, `middleware` is the\n * endpoints to mount there.\n *\n * A compiler may be given deictic more than once: the app's, and one a package applied with its own plugin\n * (`defaults`). The first applied adds the rule and the middleware, and every one writes the client again with all\n * of their options merged (`merge`), so the last applied writes it whole before the compiler runs.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport type { LoaderOptions } from './loader.ts';\nimport { openInEditor } from './tools/editor.ts';\nimport { endpoints, nodeMiddleware } from './tools/endpoints.ts';\nimport { beside, type DeicticOptions, merge, prepare, writeClient } from './tools/integration.ts';\nimport { JSX } from './tools/locate.ts';\n\nexport interface DeicticWebpackOptions extends DeicticOptions {\n /** The project's root, which marks and edits are from: the compiler's `context` by default. */\n root?: string;\n /** The path the page is served under, ending in `/`: `/` by default. */\n base?: string;\n}\n\ntype Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;\ntype Middlewares = ({ name: string; middleware: Middleware } | Middleware)[];\n\n/** What the plugin reads and sets of a webpack or Rspack compiler. */\ninterface Compiler {\n context: string;\n options: {\n mode?: string;\n target?: string | string[] | false;\n module: { rules: unknown[] };\n devServer?: { setupMiddlewares?: (middlewares: Middlewares, server: unknown) => Middlewares } & Record<string, unknown>;\n };\n}\n\nconst loaderPath = beside(import.meta.url, 'loader');\n\n/** Whether a target runs in a browser: webpack's default does, as do `web` and `browserslist`; Node's and Electron's main don't. */\nconst forBrowser = (target: Compiler['options']['target']) =>\n target === undefined || [target].flat().some((t) => t !== false && !/^(async-)?node|^electron-main|^electron-preload/.test(t));\n\n/** Every deictic one compiler was given, and the first of them, which serves the endpoints. */\ninterface Applied {\n given: DeicticWebpackOptions[];\n first: DeicticPlugin;\n}\n\nconst appliedTo = new WeakMap<Compiler, Applied>();\n\nexport class DeicticPlugin {\n readonly #options: DeicticWebpackOptions;\n #applied: Applied | undefined;\n #middleware: Middleware | undefined;\n #root = '';\n\n constructor(options: DeicticWebpackOptions = {}) {\n this.#options = options;\n // Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.\n prepare(options);\n }\n\n /** The options of every deictic the compiler was given, merged. */\n #merged(): DeicticWebpackOptions {\n const given = this.#applied?.given ?? [this.#options];\n return given.length === 1 ? given[0]! : merge(given);\n }\n\n /** The endpoints as Node middleware, once the plugin is applied: for a dev server started by hand. */\n get middleware(): Middleware {\n const applied = this.#applied;\n if (applied === undefined) throw new Error('deictic: give the plugin to the compiler before mounting its middleware');\n if (applied.first !== this) return applied.first.middleware;\n if (this.#middleware !== undefined) return this.#middleware;\n let handle: Middleware | undefined;\n // Made at the first request, once every deictic of the compiler has been applied.\n return (this.#middleware = (req, res, next) => {\n if (handle === undefined) {\n const merged = this.#merged();\n handle = nodeMiddleware(\n endpoints({\n root: this.#root,\n plugins: prepare(merged).plugins,\n base: merged.base ?? '/',\n open: (path, loc) => openInEditor(path, loc),\n }),\n );\n }\n handle(req, res, next);\n });\n }\n\n apply(compiler: Compiler): void {\n // Development only: a build without a mode is webpack's production one.\n if (compiler.options.mode !== 'development') return;\n let applied = appliedTo.get(compiler);\n if (applied === undefined) appliedTo.set(compiler, (applied = { given: [], first: this }));\n applied.given.push(this.#options);\n this.#applied = applied;\n const merged = this.#merged();\n const { plugins, shortcut } = prepare(merged);\n this.#root = merged.root ?? compiler.context;\n const browser = forBrowser(compiler.options.target);\n const client = browser ? writeClient(this.#root, plugins, merged.base ?? '/', shortcut) : undefined;\n if (applied.first !== this) return;\n const options: LoaderOptions = { root: this.#root, ...(client === undefined ? {} : { client }) };\n // First, and `pre`, so it sees the source as written whatever the app's own rules do.\n compiler.options.module.rules.unshift({\n test: JSX,\n exclude: /[\\\\/]node_modules[\\\\/]/,\n enforce: 'pre',\n use: [{ loader: loaderPath, options }],\n });\n if (!browser) return;\n\n const devServer = (compiler.options.devServer ??= {});\n const theirs = devServer.setupMiddlewares;\n devServer.setupMiddlewares = (middlewares, server) => {\n const all = theirs === undefined ? middlewares : theirs(middlewares, server);\n // In front of the dev server's own, which would answer `/__deictic/` with the page or a 404.\n all.unshift({ name: 'deictic', middleware: this.middleware });\n return all;\n };\n }\n}\n\n/** The plugin, as a function: `plugins: [deictic({ plugins: [tailwind()] })]`. */\nexport const deictic = (options: DeicticWebpackOptions = {}) => new DeicticPlugin(options);\n\nexport default deictic;\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"webpack.js","names":[],"sources":["../src/tools/editor.ts","../src/webpack.ts"],"sourcesContent":["/**\n * Opens a place in the editor, for a dev server without a launcher of its own (webpack's, Rspack's):\n * `launch-editor`, which Vite's own launcher uses, finds the editor that's running or the one `EDITOR`\n * names. An optional peer, imported when first asked.\n */\n\nimport type { Loc } from '#src/index.ts';\n\nexport async function openInEditor(path: string, { line, column }: Loc): Promise<Response> {\n const launcher = await import('launch-editor').catch(() => undefined);\n if (launcher === undefined)\n return new Response('deictic opens files with launch-editor here: add it to your devDependencies', { status: 501 });\n return new Promise((done) => {\n let failed = false;\n launcher.default(`${path}:${line}:${column}`, (_, message) => {\n failed = true;\n done(new Response(`${message ?? \"the editor didn't open\"}: set EDITOR to your editor's command`, { status: 500 }));\n });\n // launch-editor reports a failure as it happens, and nothing on success.\n setTimeout(() => failed || done(new Response(null, { status: 204 })), 50);\n });\n}\n","/**\n * `deictic/webpack`: deictic in webpack's dev server, or Rspack's (`@rspack/core` takes the same\n * plugin). Nothing runs out of development mode.\n *\n * A loader (`loader.ts`) runs `pre` on the project's JSX modules, marking each host element with its\n * place in the source as written, and in a build for the browser appending the import of the client\n * module, which webpack has no virtual module for, so it's written to `.deictic/client.js`. The\n * endpoints go in front of the dev server's own middleware (`devServer.setupMiddlewares`, which\n * webpack-dev-server and Rspack's both read), and a place opens with `launch-editor`, as webpack has no\n * launcher of its own. Where the dev server is started by hand, or by Rsbuild, `middleware` is the\n * endpoints to mount there.\n *\n * A compiler may be given deictic more than once: the app's, and one a package applied with its own plugin\n * (`defaults`). The first applied adds the rule and the middleware, and every one writes the client again with all\n * of their options merged (`merge`), so the last applied writes it whole before the compiler runs.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport type { LoaderOptions } from './loader.ts';\nimport { openInEditor } from './tools/editor.ts';\nimport { type Endpoints, endpoints, nodeMiddleware } from './tools/endpoints.ts';\nimport { beside, type DeicticOptions, merge, prepare, writeClient } from './tools/integration.ts';\nimport { JSX } from './tools/locate.ts';\n\nexport interface DeicticWebpackOptions extends DeicticOptions {\n /** The project's root, which marks and edits are from: the compiler's `context` by default. */\n root?: string;\n /** The path the page is served under, ending in `/`: `/` by default. */\n base?: string;\n}\n\ntype Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;\ntype Middlewares = ({ name: string; middleware: Middleware } | Middleware)[];\n\n/** What the plugin reads and sets of a webpack or Rspack compiler. */\ninterface Compiler {\n context: string;\n hooks: { shutdown: { tapPromise: (name: string, run: () => Promise<void>) => void } };\n options: {\n mode?: string;\n target?: string | string[] | false;\n module: { rules: unknown[] };\n devServer?: { setupMiddlewares?: (middlewares: Middlewares, server: unknown) => Middlewares } & Record<string, unknown>;\n };\n}\n\nconst loaderPath = beside(import.meta.url, 'loader');\n\n/** Whether a target runs in a browser: webpack's default does, as do `web` and `browserslist`; Node's and Electron's main don't. */\nconst forBrowser = (target: Compiler['options']['target']) =>\n target === undefined || [target].flat().some((t) => t !== false && !/^(async-)?node|^electron-main|^electron-preload/.test(t));\n\n/** Every deictic one compiler was given, and the first of them, which serves the endpoints. */\ninterface Applied {\n given: DeicticWebpackOptions[];\n first: DeicticPlugin;\n}\n\nconst appliedTo = new WeakMap<Compiler, Applied>();\n\nexport class DeicticPlugin {\n readonly #options: DeicticWebpackOptions;\n #applied: Applied | undefined;\n #middleware: Middleware | undefined;\n #endpoints: Endpoints | undefined;\n #root = '';\n\n constructor(options: DeicticWebpackOptions = {}) {\n this.#options = options;\n // Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.\n prepare(options);\n }\n\n /** The options of every deictic the compiler was given, merged. */\n #merged(): DeicticWebpackOptions {\n const given = this.#applied?.given ?? [this.#options];\n return given.length === 1 ? given[0]! : merge(given);\n }\n\n /** The endpoints as Node middleware, once the plugin is applied: for a dev server started by hand. */\n get middleware(): Middleware {\n const applied = this.#applied;\n if (applied === undefined) throw new Error('deictic: give the plugin to the compiler before mounting its middleware');\n if (applied.first !== this) return applied.first.middleware;\n if (this.#middleware !== undefined) return this.#middleware;\n let handle: Middleware | undefined;\n // Made at the first request, once every deictic of the compiler has been applied.\n return (this.#middleware = (req, res, next) => {\n if (handle === undefined) {\n const merged = this.#merged();\n this.#endpoints = endpoints({\n root: this.#root,\n plugins: prepare(merged).plugins,\n base: merged.base ?? '/',\n open: (path, loc) => openInEditor(path, loc),\n });\n handle = nodeMiddleware(this.#endpoints);\n }\n handle(req, res, next);\n });\n }\n\n apply(compiler: Compiler): void {\n // Development only: a build without a mode is webpack's production one.\n if (compiler.options.mode !== 'development') return;\n let applied = appliedTo.get(compiler);\n if (applied === undefined) appliedTo.set(compiler, (applied = { given: [], first: this }));\n applied.given.push(this.#options);\n this.#applied = applied;\n const merged = this.#merged();\n const { plugins, shortcut } = prepare(merged);\n this.#root = merged.root ?? compiler.context;\n const browser = forBrowser(compiler.options.target);\n const client = browser ? writeClient(this.#root, plugins, merged.base ?? '/', shortcut) : undefined;\n if (applied.first !== this) return;\n // webpack's and Rspack's `close()`, which their dev servers call as they stop.\n compiler.hooks.shutdown.tapPromise('deictic', async () => {\n await this.#endpoints?.close();\n });\n const options: LoaderOptions = { root: this.#root, ...(client === undefined ? {} : { client }) };\n // First, and `pre`, so it sees the source as written whatever the app's own rules do.\n compiler.options.module.rules.unshift({\n test: JSX,\n exclude: /[\\\\/]node_modules[\\\\/]/,\n enforce: 'pre',\n use: [{ loader: loaderPath, options }],\n });\n if (!browser) return;\n\n const devServer = (compiler.options.devServer ??= {});\n const theirs = devServer.setupMiddlewares;\n devServer.setupMiddlewares = (middlewares, server) => {\n const all = theirs === undefined ? middlewares : theirs(middlewares, server);\n // In front of the dev server's own, which would answer `/__deictic/` with the page or a 404.\n all.unshift({ name: 'deictic', middleware: this.middleware });\n return all;\n };\n }\n}\n\n/** The plugin, as a function: `plugins: [deictic({ plugins: [tailwind()] })]`. */\nexport const deictic = (options: DeicticWebpackOptions = {}) => new DeicticPlugin(options);\n\nexport default deictic;\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "deictic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Point at an element in your running app and leave a task about it for your agent.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"annotations",
|
|
@@ -218,6 +218,13 @@
|
|
|
218
218
|
"default": "./dist/react/client.js"
|
|
219
219
|
}
|
|
220
220
|
},
|
|
221
|
+
"./setup": {
|
|
222
|
+
"deictic@dev": "./src/setup.ts",
|
|
223
|
+
"default": {
|
|
224
|
+
"types": "./dist/setup.d.ts",
|
|
225
|
+
"default": "./dist/setup.js"
|
|
226
|
+
}
|
|
227
|
+
},
|
|
221
228
|
"./recommended": {
|
|
222
229
|
"deictic@dev": "./src/plugins/recommended/index.ts",
|
|
223
230
|
"default": {
|
package/src/cli/edit.ts
CHANGED
|
@@ -54,3 +54,17 @@ export function addFirst(out: MagicString, code: string, open: number, first: {
|
|
|
54
54
|
const multiline = code.slice(open, first.start).includes('\n');
|
|
55
55
|
out.appendLeft(first.start, multiline ? `${text},${eol}${indentAt(code, first.start)}` : `${text}, `);
|
|
56
56
|
}
|
|
57
|
+
|
|
58
|
+
/** Appends `text` after the array's last element, before its `]` at `close`, as the array is laid out (a trailing comma kept). */
|
|
59
|
+
export function addLast(out: MagicString, code: string, last: { end: number }, close: number, text: string): void {
|
|
60
|
+
const between = code.slice(last.end, close);
|
|
61
|
+
const comma = between.indexOf(',');
|
|
62
|
+
const eol = eolOf(code);
|
|
63
|
+
const indent = indentAt(code, last.end);
|
|
64
|
+
if (!between.includes('\n')) {
|
|
65
|
+
out.appendLeft(last.end, `, ${text}`);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (comma === -1) out.appendLeft(last.end, `,${eol}${indent}${text}`);
|
|
69
|
+
else out.appendLeft(last.end + comma + 1, `${eol}${indent}${text},`);
|
|
70
|
+
}
|
package/src/cli/init.ts
CHANGED
|
@@ -9,16 +9,13 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
9
9
|
import { dirname, join, relative } from 'node:path';
|
|
10
10
|
import { createInterface } from 'node:readline/promises';
|
|
11
11
|
|
|
12
|
-
import MagicString from 'magic-string';
|
|
13
|
-
import { type Expression, type ObjectExpression, parseSync, type Program } from 'oxc-parser';
|
|
14
|
-
|
|
15
12
|
import { deicticRecommended } from '#src/plugins/recommended/index.ts';
|
|
13
|
+
import { addToConfig } from '#src/setup.ts';
|
|
16
14
|
|
|
17
15
|
import { installCommand, installed, packageManager, readJson, runnerOf } from '#src/tools/packages.ts';
|
|
18
16
|
|
|
19
17
|
import { fail } from './board.ts';
|
|
20
18
|
import { addToBunfig, addToServer, BY_HAND, MODULE, PLUGIN, serverOf } from './bun.ts';
|
|
21
|
-
import { addFirst, addImports } from './edit.ts';
|
|
22
19
|
|
|
23
20
|
export type Bundler = 'next' | 'astro' | 'vite' | 'rspack' | 'webpack' | 'bun';
|
|
24
21
|
|
|
@@ -120,122 +117,21 @@ export function packagesFor(bundler: Bundler | undefined, root: string): string[
|
|
|
120
117
|
return ['deictic', ...plugins, ...(bundler === 'webpack' || bundler === 'rspack' ? ['launch-editor'] : [])];
|
|
121
118
|
}
|
|
122
119
|
|
|
123
|
-
type Node = Expression | ObjectExpression;
|
|
124
|
-
|
|
125
120
|
/**
|
|
126
|
-
* The
|
|
127
|
-
*
|
|
128
|
-
*
|
|
121
|
+
* The config with deictic added, or nothing where it can't tell where: first in its list (`plugins`, `integrations`),
|
|
122
|
+
* since a plugin before it that changes a module (both `pre` under Vite) leaves the page's marks pointing at its code,
|
|
123
|
+
* not the file, or the config wrapped (Next's).
|
|
129
124
|
*/
|
|
130
|
-
function
|
|
131
|
-
if (node == null || depth > 8) return undefined;
|
|
132
|
-
const next = (n: Node | null | undefined) => objectOf(n, program, depth + 1);
|
|
133
|
-
if (node.type === 'ObjectExpression') return node;
|
|
134
|
-
if (node.type === 'ParenthesizedExpression' || node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')
|
|
135
|
-
return next(node.expression);
|
|
136
|
-
if (node.type === 'CallExpression') {
|
|
137
|
-
const { callee } = node;
|
|
138
|
-
const named = (callee.type === 'Identifier' ? callee : callee.type === 'MemberExpression' ? callee.property : undefined) as
|
|
139
|
-
{ type: string; name?: string } | undefined;
|
|
140
|
-
const [first] = node.arguments;
|
|
141
|
-
if (named?.name !== 'defineConfig' || first === undefined || first.type === 'SpreadElement') return undefined;
|
|
142
|
-
return next(first);
|
|
143
|
-
}
|
|
144
|
-
if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {
|
|
145
|
-
const body = node.body;
|
|
146
|
-
if (body === null) return undefined;
|
|
147
|
-
if (body.type !== 'BlockStatement') return next(body);
|
|
148
|
-
const returned = body.body.findLast((s) => s.type === 'ReturnStatement');
|
|
149
|
-
return returned?.type === 'ReturnStatement' ? next(returned.argument) : undefined;
|
|
150
|
-
}
|
|
151
|
-
if (node.type !== 'Identifier') return undefined;
|
|
152
|
-
for (const statement of program.body) {
|
|
153
|
-
const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
|
|
154
|
-
if (declaration?.type !== 'VariableDeclaration') continue;
|
|
155
|
-
const found = declaration.declarations.find((d) => d.id.type === 'Identifier' && d.id.name === node.name);
|
|
156
|
-
if (found !== undefined) return next(found.init);
|
|
157
|
-
}
|
|
158
|
-
return undefined;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** The config's exported value: `export default …` or `module.exports = …`, and whether it's CommonJS. */
|
|
162
|
-
function exportedOf(program: Program): { value: Expression; commonjs: boolean } | undefined {
|
|
163
|
-
for (const statement of program.body) {
|
|
164
|
-
if (statement.type === 'ExportDefaultDeclaration') {
|
|
165
|
-
const value = statement.declaration;
|
|
166
|
-
return value.type.endsWith('Declaration') && value.type !== 'FunctionDeclaration'
|
|
167
|
-
? undefined
|
|
168
|
-
: { value: value as Expression, commonjs: false };
|
|
169
|
-
}
|
|
170
|
-
if (statement.type !== 'ExpressionStatement' || statement.expression.type !== 'AssignmentExpression') continue;
|
|
171
|
-
const { left, right } = statement.expression;
|
|
172
|
-
const exports =
|
|
173
|
-
left.type === 'MemberExpression' &&
|
|
174
|
-
left.object.type === 'Identifier' &&
|
|
175
|
-
left.object.name === 'module' &&
|
|
176
|
-
left.property.type === 'Identifier' &&
|
|
177
|
-
left.property.name === 'exports';
|
|
178
|
-
if (exports) return { value: right, commonjs: true };
|
|
179
|
-
}
|
|
180
|
-
return undefined;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* The config with deictic added, or nothing where it can't tell where: deictic's import beside the config's, and its
|
|
185
|
-
* plugin first in the list (`plugins`, `integrations`), as its marks count lines and columns in the code it's given, or the config wrapped (Next's). Written in the config's quotes,
|
|
186
|
-
* semicolons and line endings.
|
|
187
|
-
*/
|
|
188
|
-
export function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {
|
|
125
|
+
export function addDeictic(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {
|
|
189
126
|
const setup = SETUPS[bundler];
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
out.appendRight(exported.value.end, `, ${setup.value})`);
|
|
199
|
-
} else {
|
|
200
|
-
const object = objectOf(exported.value, program);
|
|
201
|
-
if (object === undefined || !addTo(out, code, object, setup.list!, setup.value)) return undefined;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
const lines: [string, string][] = [
|
|
205
|
-
['{ deicticRecommended }', 'deictic/recommended'],
|
|
206
|
-
[`{ ${setup.name} }`, setup.from],
|
|
207
|
-
];
|
|
208
|
-
addImports(out, program, code, lines, exported.commonjs);
|
|
209
|
-
return out.toString();
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Adds `value` first in the object's array `list`, or the list with it, as the object is laid out. False where `list`
|
|
214
|
-
* isn't an array. First, since a plugin before deictic's that changes a module (both `pre` under Vite) leaves the
|
|
215
|
-
* page's marks pointing at its code, not the file.
|
|
216
|
-
*/
|
|
217
|
-
function addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string): boolean {
|
|
218
|
-
const property = object.properties.find(
|
|
219
|
-
(p) =>
|
|
220
|
-
p.type === 'Property' &&
|
|
221
|
-
!p.computed &&
|
|
222
|
-
((p.key.type === 'Identifier' && p.key.name === list) || (p.key.type === 'Literal' && p.key.value === list)),
|
|
223
|
-
);
|
|
224
|
-
if (property !== undefined) {
|
|
225
|
-
if (property.type !== 'Property') return false;
|
|
226
|
-
let array = property.value;
|
|
227
|
-
while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;
|
|
228
|
-
if (array.type !== 'ArrayExpression') return false;
|
|
229
|
-
const first = array.elements.find((e) => e !== null);
|
|
230
|
-
if (first == null) {
|
|
231
|
-
out.appendLeft(array.start + 1, value);
|
|
232
|
-
return true;
|
|
233
|
-
}
|
|
234
|
-
addFirst(out, code, array.start, first, value);
|
|
235
|
-
return true;
|
|
236
|
-
}
|
|
237
|
-
addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);
|
|
238
|
-
return true;
|
|
127
|
+
return addToConfig(file, code, {
|
|
128
|
+
imports: [
|
|
129
|
+
['{ deicticRecommended }', 'deictic/recommended'],
|
|
130
|
+
[`{ ${setup.name} }`, setup.from],
|
|
131
|
+
],
|
|
132
|
+
value: setup.value,
|
|
133
|
+
...(setup.wrap ? { wrap: setup.name } : { list: setup.list! }),
|
|
134
|
+
});
|
|
239
135
|
}
|
|
240
136
|
|
|
241
137
|
export interface InitOptions {
|
|
@@ -314,7 +210,7 @@ function configure(root: string, bundler: Bundler | undefined, dryRun: boolean,
|
|
|
314
210
|
log(`deictic: ${name} has it already`);
|
|
315
211
|
return;
|
|
316
212
|
}
|
|
317
|
-
const added =
|
|
213
|
+
const added = addDeictic(bundler, file, code);
|
|
318
214
|
if (added === undefined) {
|
|
319
215
|
log(`deictic: couldn't tell where it goes in ${name}: add it yourself:\n\n${imports}\n${setup.snippet}\n`);
|
|
320
216
|
return;
|
package/src/index.ts
CHANGED
|
@@ -129,6 +129,11 @@ export interface ServerContext {
|
|
|
129
129
|
use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;
|
|
130
130
|
/** Says a problem of the plugin's own, as deictic says its own: in the dev server's output, and to each plugin's `problem`. */
|
|
131
131
|
report: (problem: Problem) => void;
|
|
132
|
+
/**
|
|
133
|
+
* Runs `callback` as the dev server closes, to undo what `setup` did beyond the plugin itself: a global it set, a
|
|
134
|
+
* watcher or a server it started. Under Vite and webpack; a dev server that only ends with its process runs none.
|
|
135
|
+
*/
|
|
136
|
+
onClose: (callback: () => Maybe<void>) => void;
|
|
132
137
|
}
|
|
133
138
|
|
|
134
139
|
/**
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `deictic/setup`: a bundler's config edited as `deictic init` edits it, for a tool that sets a project up beside
|
|
3
|
+
* deictic. Build-time only, like the CLI.
|
|
4
|
+
*/
|
|
5
|
+
import MagicString from 'magic-string';
|
|
6
|
+
import { type Expression, type ObjectExpression, parseSync, type Program } from 'oxc-parser';
|
|
7
|
+
|
|
8
|
+
import { addFirst, addImports, addLast } from './cli/edit.ts';
|
|
9
|
+
|
|
10
|
+
type Node = Expression | ObjectExpression;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The object an expression comes to: through `defineConfig(…)`, `(…)`, `satisfies`, a function's return and a top-level
|
|
14
|
+
* `const`. Not through another call: in `mergeConfig(base, {…})` or webpack-merge's `merge(common, {…})` the first
|
|
15
|
+
* argument is a base the project may build with too, and the plugin isn't the base's.
|
|
16
|
+
*/
|
|
17
|
+
function objectOf(node: Node | null | undefined, program: Program, depth = 0): ObjectExpression | undefined {
|
|
18
|
+
if (node == null || depth > 8) return undefined;
|
|
19
|
+
const next = (n: Node | null | undefined) => objectOf(n, program, depth + 1);
|
|
20
|
+
if (node.type === 'ObjectExpression') return node;
|
|
21
|
+
if (node.type === 'ParenthesizedExpression' || node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')
|
|
22
|
+
return next(node.expression);
|
|
23
|
+
if (node.type === 'CallExpression') {
|
|
24
|
+
const { callee } = node;
|
|
25
|
+
const named = (callee.type === 'Identifier' ? callee : callee.type === 'MemberExpression' ? callee.property : undefined) as
|
|
26
|
+
{ type: string; name?: string } | undefined;
|
|
27
|
+
const [first] = node.arguments;
|
|
28
|
+
if (named?.name !== 'defineConfig' || first === undefined || first.type === 'SpreadElement') return undefined;
|
|
29
|
+
return next(first);
|
|
30
|
+
}
|
|
31
|
+
if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {
|
|
32
|
+
const body = node.body;
|
|
33
|
+
if (body === null) return undefined;
|
|
34
|
+
if (body.type !== 'BlockStatement') return next(body);
|
|
35
|
+
const returned = body.body.findLast((s) => s.type === 'ReturnStatement');
|
|
36
|
+
return returned?.type === 'ReturnStatement' ? next(returned.argument) : undefined;
|
|
37
|
+
}
|
|
38
|
+
if (node.type !== 'Identifier') return undefined;
|
|
39
|
+
for (const statement of program.body) {
|
|
40
|
+
const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
|
|
41
|
+
if (declaration?.type !== 'VariableDeclaration') continue;
|
|
42
|
+
const found = declaration.declarations.find((d) => d.id.type === 'Identifier' && d.id.name === node.name);
|
|
43
|
+
if (found !== undefined) return next(found.init);
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The config's exported value: `export default …` or `module.exports = …`, and whether it's CommonJS. */
|
|
49
|
+
function exportedOf(program: Program): { value: Expression; commonjs: boolean } | undefined {
|
|
50
|
+
for (const statement of program.body) {
|
|
51
|
+
if (statement.type === 'ExportDefaultDeclaration') {
|
|
52
|
+
const value = statement.declaration;
|
|
53
|
+
return value.type.endsWith('Declaration') && value.type !== 'FunctionDeclaration'
|
|
54
|
+
? undefined
|
|
55
|
+
: { value: value as Expression, commonjs: false };
|
|
56
|
+
}
|
|
57
|
+
if (statement.type !== 'ExpressionStatement' || statement.expression.type !== 'AssignmentExpression') continue;
|
|
58
|
+
const { left, right } = statement.expression;
|
|
59
|
+
const exports =
|
|
60
|
+
left.type === 'MemberExpression' &&
|
|
61
|
+
left.object.type === 'Identifier' &&
|
|
62
|
+
left.object.name === 'module' &&
|
|
63
|
+
left.property.type === 'Identifier' &&
|
|
64
|
+
left.property.name === 'exports';
|
|
65
|
+
if (exports) return { value: right, commonjs: true };
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What a tool adds to a bundler's config: its imports, and a value in one of the config's lists or around it whole. */
|
|
71
|
+
export interface ConfigEntry {
|
|
72
|
+
/** Each import, as `[what, from]`: `['{ deictic }', 'deictic/vite']`. */
|
|
73
|
+
imports: [string, string][];
|
|
74
|
+
/** The value added to `list`, or, with `wrap`, what follows the config in the call: `{ plugins: [] }`, or nothing. */
|
|
75
|
+
value: string;
|
|
76
|
+
/** The exported object's list it goes in: `plugins`, `integrations`. */
|
|
77
|
+
list?: string;
|
|
78
|
+
/** The function the whole of the exported config is passed to instead (Next's `withDeictic`). */
|
|
79
|
+
wrap?: string;
|
|
80
|
+
/** After the list's others, where it goes first by default. */
|
|
81
|
+
last?: boolean;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The config with the entry added, or nothing where it can't tell where: its imports after the config's, and its
|
|
86
|
+
* value in the list or around the whole config, written in the config's quotes, semicolons and line endings. What
|
|
87
|
+
* `deictic init` adds deictic with, for a tool setting a project up beside it (prosebook's `init`).
|
|
88
|
+
*/
|
|
89
|
+
export function addToConfig(file: string, code: string, entry: ConfigEntry): string | undefined {
|
|
90
|
+
const { program, errors } = parseSync(file, code, { preserveParens: false });
|
|
91
|
+
if (errors.length > 0) return undefined;
|
|
92
|
+
const exported = exportedOf(program);
|
|
93
|
+
if (exported === undefined) return undefined;
|
|
94
|
+
const out = new MagicString(code);
|
|
95
|
+
|
|
96
|
+
if (entry.wrap !== undefined) {
|
|
97
|
+
out.appendLeft(exported.value.start, `${entry.wrap}(`);
|
|
98
|
+
out.appendRight(exported.value.end, entry.value === '' ? ')' : `, ${entry.value})`);
|
|
99
|
+
} else {
|
|
100
|
+
const object = objectOf(exported.value, program);
|
|
101
|
+
if (object === undefined || entry.list === undefined || !addTo(out, code, object, entry)) return undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
addImports(out, program, code, entry.imports, exported.commonjs);
|
|
105
|
+
return out.toString();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Adds the entry's value to the object's array `list`, or the list with it, as the object is laid out. False where `list` isn't an array. */
|
|
109
|
+
function addTo(out: MagicString, code: string, object: ObjectExpression, { list, value, last }: ConfigEntry): boolean {
|
|
110
|
+
const property = object.properties.find(
|
|
111
|
+
(p) =>
|
|
112
|
+
p.type === 'Property' &&
|
|
113
|
+
!p.computed &&
|
|
114
|
+
((p.key.type === 'Identifier' && p.key.name === list) || (p.key.type === 'Literal' && p.key.value === list)),
|
|
115
|
+
);
|
|
116
|
+
if (property !== undefined) {
|
|
117
|
+
if (property.type !== 'Property') return false;
|
|
118
|
+
let array = property.value;
|
|
119
|
+
while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;
|
|
120
|
+
if (array.type !== 'ArrayExpression') return false;
|
|
121
|
+
const elements = array.elements.filter((e) => e !== null);
|
|
122
|
+
if (elements.length === 0) {
|
|
123
|
+
out.appendLeft(array.start + 1, value);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
if (last) addLast(out, code, elements.at(-1)!, array.end - 1, value);
|
|
127
|
+
else addFirst(out, code, array.start, elements[0], value);
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);
|
|
131
|
+
return true;
|
|
132
|
+
}
|