deictic 0.9.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 +17 -0
- package/dist/bun.d.ts.map +1 -1
- package/dist/bun.js +26 -8
- package/dist/bun.js.map +1 -1
- package/dist/client/index.js +8 -0
- package/dist/client/index.js.map +1 -1
- package/dist/next.d.ts.map +1 -1
- package/dist/next.js +45 -25
- package/dist/next.js.map +1 -1
- 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 +26 -6
- package/dist/shared/endpoints.js.map +1 -1
- package/dist/shared/index.d.ts +10 -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.d.ts +6 -0
- package/dist/shared/integration.d.ts.map +1 -1
- package/dist/shared/integration.js +31 -3
- 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.d.ts +1 -1
- package/dist/shared/vite.d.ts.map +1 -1
- package/dist/shared/vite.js +33 -11
- package/dist/shared/vite.js.map +1 -1
- package/dist/webpack.d.ts +9 -0
- package/dist/webpack.d.ts.map +1 -1
- package/dist/webpack.js +42 -15
- package/dist/webpack.js.map +1 -1
- package/package.json +8 -1
- package/src/bun.ts +32 -8
- package/src/cli/edit.ts +14 -0
- package/src/cli/init.ts +14 -118
- package/src/client/index.ts +4 -0
- package/src/index.ts +10 -0
- package/src/next.ts +34 -15
- package/src/setup.ts +132 -0
- package/src/tools/endpoints.ts +23 -4
- package/src/tools/integration.ts +33 -0
- package/src/tools/plugins.ts +7 -2
- package/src/tools/source.ts +14 -2
- package/src/vite.ts +38 -12
- package/src/webpack.ts +54 -17
package/src/bun.ts
CHANGED
|
@@ -15,13 +15,18 @@
|
|
|
15
15
|
* // server.ts
|
|
16
16
|
* import tools from './deictic.ts';
|
|
17
17
|
* Bun.serve({ routes: { ...tools.routes, '/*': index }, development: true });
|
|
18
|
+
*
|
|
19
|
+
* bunfig may name deictic more than once: the app's, and a package's that adds its own plugin (`defaults`), as
|
|
20
|
+
* prosebook's does. Each made in the process for a root is kept (`made`), the first set up marks the modules, and
|
|
21
|
+
* the client and the endpoints, made when first needed, load all of their options merged (`merge`); any of them
|
|
22
|
+
* has the routes.
|
|
18
23
|
*/
|
|
19
24
|
import { resolve } from 'node:path';
|
|
20
25
|
|
|
21
26
|
import type { BunPlugin } from 'bun';
|
|
22
27
|
|
|
23
28
|
import { endpoints } from './tools/endpoints.ts';
|
|
24
|
-
import { type DeicticOptions, importOf, mark, prepare, writeClient } from './tools/integration.ts';
|
|
29
|
+
import { type DeicticOptions, importOf, mark, merge, prepare, writeClient } from './tools/integration.ts';
|
|
25
30
|
import { JSX } from './tools/locate.ts';
|
|
26
31
|
|
|
27
32
|
export interface DeicticBunOptions extends DeicticOptions {
|
|
@@ -34,15 +39,28 @@ export type DeicticBunPlugin = BunPlugin & {
|
|
|
34
39
|
routes: Record<string, (req: Request) => Promise<Response>>;
|
|
35
40
|
};
|
|
36
41
|
|
|
42
|
+
/** Every deictic made in the process, by its root: what it was given, whether one set up its marking, and its endpoints. */
|
|
43
|
+
interface Made {
|
|
44
|
+
given: DeicticBunOptions[];
|
|
45
|
+
marking: boolean;
|
|
46
|
+
handle?: (req: Request) => Promise<Response | undefined>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const made = new Map<string, Made>();
|
|
50
|
+
|
|
37
51
|
export function deictic(options: DeicticBunOptions = {}): DeicticBunPlugin {
|
|
38
52
|
// Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.
|
|
39
|
-
|
|
53
|
+
prepare(options);
|
|
40
54
|
const root = resolve(options.root ?? process.cwd());
|
|
41
|
-
let
|
|
55
|
+
let all = made.get(root);
|
|
56
|
+
if (all === undefined) made.set(root, (all = { given: [], marking: false }));
|
|
57
|
+
all.given.push(options);
|
|
58
|
+
const shared = all;
|
|
59
|
+
const merged = () => prepare(shared.given.length === 1 ? shared.given[0]! : merge(shared.given));
|
|
42
60
|
const route = async (req: Request) => {
|
|
43
|
-
handle ??= endpoints({
|
|
61
|
+
shared.handle ??= endpoints({
|
|
44
62
|
root,
|
|
45
|
-
plugins,
|
|
63
|
+
plugins: merged().plugins,
|
|
46
64
|
open: (path, { line, column }) => {
|
|
47
65
|
try {
|
|
48
66
|
Bun.openInEditor(path, { line, column });
|
|
@@ -54,7 +72,7 @@ export function deictic(options: DeicticBunOptions = {}): DeicticBunPlugin {
|
|
|
54
72
|
}
|
|
55
73
|
},
|
|
56
74
|
});
|
|
57
|
-
return (await handle(req)) ?? new Response(null, { status: 404 });
|
|
75
|
+
return (await shared.handle(req)) ?? new Response(null, { status: 404 });
|
|
58
76
|
};
|
|
59
77
|
|
|
60
78
|
return {
|
|
@@ -62,14 +80,20 @@ export function deictic(options: DeicticBunOptions = {}): DeicticBunPlugin {
|
|
|
62
80
|
routes: { '/__deictic/*': route },
|
|
63
81
|
setup(build) {
|
|
64
82
|
// A build names its entry points; the dev server's bundler doesn't.
|
|
65
|
-
if ('entrypoints' in build.config) return;
|
|
66
|
-
|
|
83
|
+
if ('entrypoints' in build.config || shared.marking) return;
|
|
84
|
+
shared.marking = true;
|
|
85
|
+
let client: string | undefined;
|
|
67
86
|
// Bun names the side it loads a module for (undocumented, and not in Bun's types); the dev server's is the browser's.
|
|
68
87
|
const forBrowser = (args: object) => !('side' in args) || args.side === 'client';
|
|
69
88
|
build.onLoad({ filter: JSX }, async (args) => {
|
|
70
89
|
// A dependency's is left to Bun, unread.
|
|
71
90
|
if (/[\\/]node_modules[\\/]/.test(args.path)) return undefined;
|
|
72
91
|
const code = await Bun.file(args.path).text();
|
|
92
|
+
// Written as the first module loads, once bunfig's every deictic has been made.
|
|
93
|
+
if (client === undefined) {
|
|
94
|
+
const { plugins, shortcut } = merged();
|
|
95
|
+
client = writeClient(root, plugins, '/', shortcut);
|
|
96
|
+
}
|
|
73
97
|
const marked = mark(code, args.path, root, forBrowser(args) ? importOf(client, args.path) : '');
|
|
74
98
|
if (marked === undefined) return undefined;
|
|
75
99
|
return { contents: marked.code, loader: args.path.endsWith('tsx') ? 'tsx' : 'jsx' };
|
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/client/index.ts
CHANGED
|
@@ -231,6 +231,10 @@ export function start({ base, shortcut: own, plugins: given, server }: StartOpti
|
|
|
231
231
|
use: (other) => apis.get(other) as never,
|
|
232
232
|
request: (route, init) => send(`${base}__deictic/plugins/${name}/${route}`, init),
|
|
233
233
|
report: (problem) => report({ ...problem, plugin: name }),
|
|
234
|
+
edit: async ({ file, line, column }) => {
|
|
235
|
+
const res = await send(`${base}__deictic/open?${new URLSearchParams({ file, line: String(line), column: String(column) })}`);
|
|
236
|
+
if (!res.ok) throw new Error(await res.text());
|
|
237
|
+
},
|
|
234
238
|
// Not from under something unsaved, which a press on the page wouldn't close either: its button shakes.
|
|
235
239
|
open: (plugin, element, at) => panel?.guard() !== true && openAt(plugin, element, at),
|
|
236
240
|
lightbox: (items, options) => openLightbox(root, items, options),
|
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
|
/**
|
|
@@ -282,6 +287,11 @@ export interface ClientContext {
|
|
|
282
287
|
request: (route: string, init?: RequestInit) => Promise<Response>;
|
|
283
288
|
/** Says a problem of the plugin's own to the dev server, as the server half's `report` does: its `plugin` is this one. */
|
|
284
289
|
report: (problem: Problem) => void;
|
|
290
|
+
/**
|
|
291
|
+
* Opens a place in a file under the root in the editor, as the popup's own link opens the element's: through the
|
|
292
|
+
* dev server, or what answers in its place (`Standalone`). Rejects with why it couldn't.
|
|
293
|
+
*/
|
|
294
|
+
edit: (place: Loc) => Promise<void>;
|
|
285
295
|
/**
|
|
286
296
|
* Opens the popup on an element at a plugin's tab, as its shortcut would, or with `at` on a spot in it: the
|
|
287
297
|
* popup is then beside the spot, which is what's lit, and the tab's context has it. An element rendered again
|
package/src/next.ts
CHANGED
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
*
|
|
15
15
|
* Both bundlers' rules are always set, as the config can't tell which will run: Next refuses a Turbopack
|
|
16
16
|
* build whose config has a `webpack` key only where it has no `turbopack` one, and ours always does.
|
|
17
|
+
*
|
|
18
|
+
* A config may be wrapped more than once: by the app, and by a package that adds its own plugin (`defaults`), as
|
|
19
|
+
* `withProsebook` does. The config each returns carries the options it was given (`GIVEN`), so the next one out adds
|
|
20
|
+
* no rules of its own: it writes the client again with all of them merged (`merge`), and the endpoints, made at the
|
|
21
|
+
* first request, load them all.
|
|
17
22
|
*/
|
|
18
23
|
import { createServer } from 'node:http';
|
|
19
24
|
import type { AddressInfo } from 'node:net';
|
|
@@ -22,7 +27,7 @@ import { resolve } from 'node:path';
|
|
|
22
27
|
import type { ServerPlugin } from './index.ts';
|
|
23
28
|
import type { LoaderOptions } from './loader.ts';
|
|
24
29
|
import { endpoints, nodeMiddleware, redirect } from './tools/endpoints.ts';
|
|
25
|
-
import { beside, type DeicticOptions, prepare, writeClient } from './tools/integration.ts';
|
|
30
|
+
import { beside, type DeicticOptions, merge, prepare, writeClient } from './tools/integration.ts';
|
|
26
31
|
import { JSX } from './tools/locate.ts';
|
|
27
32
|
|
|
28
33
|
export interface DeicticNextOptions extends DeicticOptions {
|
|
@@ -45,6 +50,10 @@ const GLOBS = ['*.tsx', '*.jsx', '*.js'];
|
|
|
45
50
|
|
|
46
51
|
// Next loads its config more than once in a process: one endpoints server per project is enough.
|
|
47
52
|
const serving = new Map<string, Promise<number>>();
|
|
53
|
+
// Each project's plugins as its config last merged them, for its endpoints to load at their first request.
|
|
54
|
+
const loaded = new Map<string, ServerPlugin[]>();
|
|
55
|
+
/** On a config a `withDeictic` returned: the options of every one it went through. */
|
|
56
|
+
const GIVEN = Symbol.for('deictic.given');
|
|
48
57
|
|
|
49
58
|
/**
|
|
50
59
|
* Wraps the Next config: `export default withDeictic({ ... }, { plugins: [tailwind()] })`. Takes the
|
|
@@ -55,18 +64,25 @@ export function withDeictic<C extends object>(
|
|
|
55
64
|
options: DeicticNextOptions = {},
|
|
56
65
|
): (phase: string, context: { defaultConfig: C }) => Promise<C> {
|
|
57
66
|
// Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.
|
|
58
|
-
|
|
67
|
+
prepare(options);
|
|
59
68
|
return async (phase, context) => {
|
|
60
69
|
const resolved = typeof next === 'function' ? await next(phase, context) : next;
|
|
61
70
|
if (phase !== DEV) return resolved;
|
|
62
|
-
const
|
|
71
|
+
const before = (resolved as { [GIVEN]?: DeicticNextOptions[] })[GIVEN];
|
|
72
|
+
const given = [...(before ?? []), options];
|
|
73
|
+
const merged = given.length === 1 ? options : merge(given);
|
|
74
|
+
const { plugins, shortcut } = prepare(merged);
|
|
75
|
+
const root = resolve(merged.root ?? process.cwd());
|
|
63
76
|
const base = `${(resolved as { basePath?: string }).basePath ?? ''}/`;
|
|
64
77
|
const client = writeClient(root, plugins, base, shortcut);
|
|
78
|
+
loaded.set(root, plugins);
|
|
79
|
+
// Wrapped already: the rules and the rewrite are there, and only the client and the plugins change.
|
|
80
|
+
if (before !== undefined) return { ...resolved, [GIVEN]: given };
|
|
65
81
|
const rules: [string, Rule][] = GLOBS.flatMap((glob) => [
|
|
66
82
|
[glob, { condition: { all: ['browser', { not: 'foreign' }] }, loaders: [{ loader: loaderPath, options: { root, client } }] }],
|
|
67
83
|
[glob, { condition: { all: [{ not: 'browser' }, { not: 'foreign' }] }, loaders: [{ loader: loaderPath, options: { root } }] }],
|
|
68
84
|
]);
|
|
69
|
-
return withRewrite(withWebpack(withRules(resolved, rules), root, client), await serve(root,
|
|
85
|
+
return { ...withRewrite(withWebpack(withRules(resolved, rules), root, client), await serve(root, base)), [GIVEN]: given };
|
|
70
86
|
};
|
|
71
87
|
}
|
|
72
88
|
|
|
@@ -102,20 +118,23 @@ function withRewrite<C extends object>(resolved: C, port: number): C {
|
|
|
102
118
|
}
|
|
103
119
|
|
|
104
120
|
/** Serves the endpoints on a free local port, for as long as the process lives. */
|
|
105
|
-
function serve(root: string,
|
|
121
|
+
function serve(root: string, base: string): Promise<number> {
|
|
106
122
|
const running = serving.get(root);
|
|
107
123
|
if (running !== undefined) return running;
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
124
|
+
let middleware: ReturnType<typeof nodeMiddleware> | undefined;
|
|
125
|
+
const made = () =>
|
|
126
|
+
(middleware ??= nodeMiddleware(
|
|
127
|
+
endpoints({
|
|
128
|
+
root,
|
|
129
|
+
plugins: loaded.get(root) ?? [],
|
|
130
|
+
// Rewritten from under the base, but served at the root of their own server.
|
|
131
|
+
base: '/',
|
|
132
|
+
open: (path, { line, column }) =>
|
|
133
|
+
redirect(`${base}__nextjs_launch-editor?${new URLSearchParams({ file: path, line1: String(line), column1: String(column) })}`),
|
|
134
|
+
}),
|
|
135
|
+
));
|
|
117
136
|
const server = createServer((req, res) =>
|
|
118
|
-
|
|
137
|
+
made()(req, res, () => {
|
|
119
138
|
res.statusCode = 404;
|
|
120
139
|
res.end();
|
|
121
140
|
}),
|
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
|
+
}
|
package/src/tools/endpoints.ts
CHANGED
|
@@ -46,14 +46,20 @@ const scopeOf = (plugin: string, { file, line, column }: Loc): Scope => ({ plugi
|
|
|
46
46
|
const scopeIn = ({ plugin, target }: Partial<Body>) =>
|
|
47
47
|
plugin === undefined || target === undefined ? undefined : scopeOf(plugin, target.loc);
|
|
48
48
|
|
|
49
|
-
/**
|
|
50
|
-
export
|
|
49
|
+
/** deictic's requests answered, and nothing for any other path; `close` runs what the plugins' setups left to run on close. */
|
|
50
|
+
export interface Endpoints {
|
|
51
|
+
(req: Request): Promise<Response | undefined>;
|
|
52
|
+
close(): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function endpoints({ root, plugins, base = '/', open, history = new History(root, { plugins }) }: EndpointOptions): Endpoints {
|
|
51
56
|
const byName = new Map(plugins.map((p) => [p.name, p]));
|
|
52
57
|
const prefix = `${base}__deictic/`;
|
|
53
58
|
// What goes wrong that nothing in the page caused: said, and handed to the plugins that hear of it once set up.
|
|
54
59
|
const report = reporter(plugins, () => ready);
|
|
55
60
|
// Started now, awaited by every request: a plugin's API is there before anything asks for it.
|
|
56
|
-
const
|
|
61
|
+
const closing: (() => unknown)[] = [];
|
|
62
|
+
const ready = setUp(root, plugins, report, (callback) => void closing.push(callback));
|
|
57
63
|
const gone = missingProblem(root, plugins);
|
|
58
64
|
if (gone !== undefined) report(gone);
|
|
59
65
|
|
|
@@ -104,7 +110,7 @@ export function endpoints({ root, plugins, base = '/', open, history = new Histo
|
|
|
104
110
|
return next;
|
|
105
111
|
};
|
|
106
112
|
|
|
107
|
-
|
|
113
|
+
const handle = async (req: Request): Promise<Response | undefined> => {
|
|
108
114
|
const url = new URL(req.url);
|
|
109
115
|
if (!url.pathname.startsWith(prefix)) return undefined;
|
|
110
116
|
const route = url.pathname.slice(prefix.length);
|
|
@@ -162,6 +168,19 @@ export function endpoints({ root, plugins, base = '/', open, history = new Histo
|
|
|
162
168
|
return Response.json({ problem: e instanceof Error ? (e.stack ?? e.message) : String(e) }, { status: 500 });
|
|
163
169
|
}
|
|
164
170
|
};
|
|
171
|
+
// Once, however many times the dev server says it closes (Vite, once per environment); the last set up, first.
|
|
172
|
+
let closed: Promise<void> | undefined;
|
|
173
|
+
const close = () =>
|
|
174
|
+
(closed ??= ready.then(async () => {
|
|
175
|
+
for (const callback of closing.toReversed()) {
|
|
176
|
+
try {
|
|
177
|
+
await callback();
|
|
178
|
+
} catch (e) {
|
|
179
|
+
console.error(`deictic: a plugin failed as the dev server closed: ${messageOf(e)}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}));
|
|
183
|
+
return Object.assign(handle, { close });
|
|
165
184
|
}
|
|
166
185
|
|
|
167
186
|
/** A redirect within the page's origin, to a launcher the dev server answers itself. */
|
package/src/tools/integration.ts
CHANGED
|
@@ -25,6 +25,39 @@ export interface DeicticOptions {
|
|
|
25
25
|
* `false` for none, leaving only plugins' own shortcuts.
|
|
26
26
|
*/
|
|
27
27
|
shortcut?: Shortcut | false;
|
|
28
|
+
/**
|
|
29
|
+
* For a package that adds its own plugin to the bundler with deictic (prosebook does): these options give way to
|
|
30
|
+
* those of any other deictic in the same build, which merges them in, so the app's own `deictic()` decides the
|
|
31
|
+
* shortcut and its plugin of the same name is the one loaded.
|
|
32
|
+
*/
|
|
33
|
+
defaults?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Every deictic one build was given, as one: the app's and those packages added (`defaults`). The plugins of all of
|
|
38
|
+
* them, each name once, the first given winning, those of an instance with `defaults` after the rest's; any other
|
|
39
|
+
* option from the first that sets it, the same way. Two that aren't `defaults` setting one differently is an error,
|
|
40
|
+
* as neither can be the one meant.
|
|
41
|
+
*/
|
|
42
|
+
export function merge<O extends DeicticOptions>(instances: readonly O[]): O {
|
|
43
|
+
const ordered = [...instances.filter((o) => o.defaults !== true), ...instances.filter((o) => o.defaults === true)];
|
|
44
|
+
const plugins = new Map<string, ServerPlugin>();
|
|
45
|
+
const merged: Record<string, unknown> = {};
|
|
46
|
+
const setBy: Record<string, O> = {};
|
|
47
|
+
for (const options of ordered) {
|
|
48
|
+
for (const plugin of options.plugins ?? []) if (!plugins.has(plugin.name)) plugins.set(plugin.name, plugin);
|
|
49
|
+
for (const [key, value] of Object.entries(options)) {
|
|
50
|
+
if (key === 'plugins' || key === 'defaults' || value === undefined) continue;
|
|
51
|
+
const first = setBy[key];
|
|
52
|
+
if (first === undefined) {
|
|
53
|
+
merged[key] = value;
|
|
54
|
+
setBy[key] = options;
|
|
55
|
+
} else if (first.defaults !== true && options.defaults !== true && JSON.stringify(merged[key]) !== JSON.stringify(value)) {
|
|
56
|
+
throw new Error(`deictic: the build has deictic twice, with ${key} set two ways: set it in one of them only`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { ...merged, plugins: [...plugins.values()] } as O;
|
|
28
61
|
}
|
|
29
62
|
|
|
30
63
|
/** The options with their defaults, checked now, so a wrong set stops the dev server as it starts, not the page. */
|
package/src/tools/plugins.ts
CHANGED
|
@@ -32,9 +32,14 @@ export function checkPlugins(plugins: readonly ServerPlugin[], own?: Shortcut |
|
|
|
32
32
|
* op, never in `setup` itself. One that fails is reported and has no API: the others go on, so one of them
|
|
33
33
|
* can tell of it (tasks, on the board).
|
|
34
34
|
*/
|
|
35
|
-
export async function setUp(
|
|
35
|
+
export async function setUp(
|
|
36
|
+
root: string,
|
|
37
|
+
plugins: readonly ServerPlugin[],
|
|
38
|
+
report: Report,
|
|
39
|
+
onClose: ServerContext['onClose'],
|
|
40
|
+
): Promise<ServerContext> {
|
|
36
41
|
const apis = new Map<string, unknown>();
|
|
37
|
-
const context: ServerContext = { root, use: (name) => apis.get(name) as never, report };
|
|
42
|
+
const context: ServerContext = { root, use: (name) => apis.get(name) as never, report, onClose };
|
|
38
43
|
await Promise.all(
|
|
39
44
|
plugins.map(async (p) => {
|
|
40
45
|
if (p.setup === undefined) return;
|