@unbase-app/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,629 @@
1
+ // ============================================================================
2
+ // Editing astro.config safely. The config is parsed (Babel, with TypeScript
3
+ // for .ts), the places to change are found in the syntax tree, and the
4
+ // change is a splice at those exact offsets, so the rest of the file keeps
5
+ // its formatting and comments. The result is parsed again and checked before
6
+ // it is written. Anything the tree does not make certain (no
7
+ // `export default`, `integrations` that is not an array literal, a spread
8
+ // that may hold it, a CommonJS config, a name from a package used outside
9
+ // its entry) stops with an error naming the file: never a guess.
10
+ //
11
+ // Since K5 the one entry is unbase({ … }) from @unbase-app/astro, which
12
+ // brings comment mode and the draft-pages kit. A config from before it (the
13
+ // pair: commentModus() and unbasePages()) is moved across: unbase() takes
14
+ // comment mode's call and its options as they are, unbasePages() goes, and
15
+ // an import the site still uses for something else keeps that use.
16
+ //
17
+ // The formatting helpers are exported for the other frameworks' configs
18
+ // (vite-config.mjs, next-config.mjs).
19
+ // ============================================================================
20
+
21
+ import { parse } from "@babel/parser";
22
+ import { CouldNotRun } from "./errors.mjs";
23
+ import { ASTRO, BEFORE, COMMENT_MODUS, LAYER_URL, PAGES, SELF } from "./versions.mjs";
24
+
25
+ /** The modules init imports, and the entries it adds or moves. */
26
+ export const SOURCES = {
27
+ unbase: ASTRO.name,
28
+ comments: COMMENT_MODUS.name,
29
+ pages: `${PAGES.name}/astro`,
30
+ link: "./comment-modus.json",
31
+ sitemap: "@astrojs/sitemap",
32
+ };
33
+ /** The kit's integration, under its name now and before K5, as a site may import it. */
34
+ const PAGES_ALSO = new Set([`${PAGES.name}/astro`, PAGES.name, `${BEFORE.pages}/astro`, BEFORE.pages]);
35
+ const NAMES = { unbase: "unbase", comments: "commentModus", pages: "unbasePages", link: "commentModusConfig" };
36
+ /** The line init writes above unbase({ … }), with comments and without. */
37
+ export const UNBASE_LINE = "// Unbase: comments with ?comment once comment-modus.json names the project, and drafts kept off Live.";
38
+ export const UNBASE_LINE_NO_COMMENTS = "// Unbase: drafts kept off Live; comments on the site left out.";
39
+ /** The lines init wrote above the pair before K5: replaced, or removed with their entry. */
40
+ const LINES_BEFORE = [
41
+ "// Comments on the site with ?comment (Unbase): on once comment-modus.json names the project.",
42
+ "// Keeps Unbase's draft pages out of production builds; after sitemap() and commentModus().",
43
+ ];
44
+
45
+ const unsafe = (file, why) =>
46
+ new CouldNotRun("config_unsafe", `${file} cannot be edited safely: ${why}. Make the change by hand (step 1 of agents/astro.md in ${SELF.name}), then run the command again.`, { file });
47
+
48
+ function parseConfig(code, file) {
49
+ if (/\.cjs$/.test(file)) throw unsafe(file, "it is CommonJS, and the packages are ES modules");
50
+ try {
51
+ return parse(code, {
52
+ sourceType: "module",
53
+ plugins: /\.(m|c)?ts$/.test(file) ? ["typescript"] : [],
54
+ tokens: true,
55
+ errorRecovery: false,
56
+ });
57
+ } catch (e) {
58
+ throw unsafe(file, `it does not parse (${e.message})`);
59
+ }
60
+ }
61
+
62
+ export const unwrap = (n) => {
63
+ while (n && ["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "ParenthesizedExpression", "TSTypeAssertion"].includes(n.type)) n = n.expression;
64
+ return n;
65
+ };
66
+
67
+ /** The object literal `export default defineConfig({ … })` (or `export default { … }`, or through a const) hands Astro. */
68
+ function configObject(ast, file) {
69
+ const body = ast.program.body;
70
+ if (body.some((n) => n.type === "ExpressionStatement" && n.expression.type === "AssignmentExpression" && /module\.exports|exports\./.test(String(n.expression.left?.object?.name ?? "") + "." + String(n.expression.left?.property?.name ?? ""))))
71
+ throw unsafe(file, "it is CommonJS (module.exports)");
72
+ const exp = body.find((n) => n.type === "ExportDefaultDeclaration");
73
+ if (!exp) throw unsafe(file, "it has no `export default`");
74
+ const constNamed = (name) => {
75
+ for (const n of body) {
76
+ const decl = n.type === "ExportNamedDeclaration" ? n.declaration : n;
77
+ if (decl?.type !== "VariableDeclaration" || decl.kind !== "const") continue;
78
+ const d = decl.declarations.find((v) => v.id.type === "Identifier" && v.id.name === name);
79
+ if (d?.init) return d.init;
80
+ }
81
+ return null;
82
+ };
83
+ let node = unwrap(exp.declaration);
84
+ for (let step = 0; step < 3 && node; step++) {
85
+ if (node.type === "ObjectExpression") return node;
86
+ if (node.type === "Identifier") node = unwrap(constNamed(node.name));
87
+ else if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "defineConfig" && node.arguments.length === 1) node = unwrap(node.arguments[0]);
88
+ else break;
89
+ }
90
+ throw unsafe(file, "its `export default` is not `defineConfig({ … })` or an object literal");
91
+ }
92
+
93
+ export const keyName = (p) => (p.key.type === "Identifier" ? p.key.name : p.key.type === "StringLiteral" ? p.key.value : null);
94
+
95
+ /** The imports of the modules init knows: their local names. */
96
+ function importsOf(ast) {
97
+ const found = { unbase: [], comments: [], pages: [], link: [], sitemap: [], nodes: [] };
98
+ for (const n of ast.program.body) {
99
+ if (n.type !== "ImportDeclaration") continue;
100
+ const src = n.source.value;
101
+ const kind = src === SOURCES.unbase ? "unbase" : src === SOURCES.comments ? "comments" : PAGES_ALSO.has(src) ? "pages" : src === SOURCES.link ? "link" : src === SOURCES.sitemap ? "sitemap" : null;
102
+ if (!kind) continue;
103
+ found.nodes.push({ kind, node: n });
104
+ for (const s of n.specifiers) {
105
+ const imported = s.type === "ImportDefaultSpecifier" ? "default" : s.type === "ImportSpecifier" ? (s.imported.name ?? s.imported.value) : "*";
106
+ const isEntry = imported === "default" || (kind === "pages" && imported === "unbasePages") || (kind === "unbase" && imported === "unbase");
107
+ if (isEntry) found[kind].push(s.local.name);
108
+ }
109
+ }
110
+ return found;
111
+ }
112
+
113
+ /** The call an element of `integrations` makes, possibly behind `x ?` or `x &&`; null for anything else. */
114
+ function callOf(el) {
115
+ let e = unwrap(el);
116
+ if (e?.type === "LogicalExpression" && e.operator === "&&") e = unwrap(e.right);
117
+ else if (e?.type === "ConditionalExpression") e = unwrap(e.consequent);
118
+ return e?.type === "CallExpression" && e.callee.type === "Identifier" ? e : null;
119
+ }
120
+
121
+ /** Which of init's entries an element of `integrations` is: a call of an imported name. */
122
+ function entryKind(el, imports) {
123
+ const e = callOf(el);
124
+ if (!e) return null;
125
+ for (const kind of ["unbase", "comments", "pages", "sitemap"]) if (imports[kind].includes(e.callee.name)) return kind;
126
+ return null;
127
+ }
128
+
129
+ const MARKER_WHEN = ["always", "preview"];
130
+ const propNamed = (obj, name) => obj.properties.find((p) => p.type === "ObjectProperty" && !p.computed && keyName(p) === name);
131
+ const spreads = (obj) => obj.properties.some((p) => p.type === "SpreadElement");
132
+
133
+ /**
134
+ * Which builds get comment mode's data-c markers, from commentModus({ componentMarker }) (comment-modus
135
+ * 1.9.0): "always" (also when the option is absent, as before 1.9.0), "preview" (not in a production
136
+ * build), false (none), or null when the config does not say it literally (a variable, a spread).
137
+ */
138
+ function markersOf(call) {
139
+ const opts = unwrap(call.arguments[0]);
140
+ if (opts?.type !== "ObjectExpression") return null;
141
+ const prop = propNamed(opts, "componentMarker");
142
+ if (!prop) return spreads(opts) ? null : "always";
143
+ const v = unwrap(prop.value);
144
+ if (v.type === "BooleanLiteral" && v.value === false) return false;
145
+ if (v.type === "StringLiteral") return MARKER_WHEN.includes(v.value) ? v.value : null;
146
+ if (v.type !== "ObjectExpression") return null;
147
+ const when = propNamed(v, "when");
148
+ if (!when) return spreads(v) ? null : "always";
149
+ const w = unwrap(when.value);
150
+ return w.type === "StringLiteral" && MARKER_WHEN.includes(w.value) ? w.value : null;
151
+ }
152
+
153
+ /** comment mode's own `project` when the config writes it literally (a site that set it up before init), else null (from comment-modus.json, a variable). */
154
+ function projectOf(call) {
155
+ const opts = unwrap(call.arguments[0]);
156
+ if (opts?.type !== "ObjectExpression") return null;
157
+ const prop = propNamed(opts, "project");
158
+ const v = prop ? unwrap(prop.value) : null;
159
+ return v?.type === "StringLiteral" ? v.value : null;
160
+ }
161
+
162
+ /** unbase()'s `comments`: true (absent, or true), false, or null when the config does not say it literally. */
163
+ function commentsIn(call) {
164
+ const opts = unwrap(call?.arguments[0]);
165
+ if (!opts) return true;
166
+ if (opts.type !== "ObjectExpression") return null;
167
+ const prop = propNamed(opts, "comments");
168
+ if (!prop) return spreads(opts) ? null : true;
169
+ const v = unwrap(prop.value);
170
+ return v.type === "BooleanLiteral" ? v.value : null;
171
+ }
172
+
173
+ /**
174
+ * What a config holds of Unbase's packages, read from its tree: for doctor, and for init and
175
+ * uninstall to know what to change.
176
+ */
177
+ export function inspectConfig(code, file) {
178
+ const ast = parseConfig(code, file);
179
+ const obj = configObject(ast, file);
180
+ const imports = importsOf(ast);
181
+ const prop = obj.properties.find((p) => p.type === "ObjectProperty" && !p.computed && keyName(p) === "integrations");
182
+ const spread = obj.properties.some((p) => p.type === "SpreadElement");
183
+ const array = prop ? unwrap(prop.value) : null;
184
+ if (prop && array.type !== "ArrayExpression") throw unsafe(file, "`integrations` is not an array literal");
185
+ const entries = (array?.elements ?? []).map((el, index) => ({ index, kind: el ? entryKind(el, imports) : null, el }));
186
+ const at = (kind) => entries.filter((e) => e.kind === kind).map((e) => e.index);
187
+ const pagesAt = at("pages");
188
+ const before = [...at("comments"), ...at("sitemap")];
189
+ const unbase = entries.find((e) => e.kind === "unbase");
190
+ const unbaseComments = unbase ? commentsIn(callOf(unbase.el)) : null;
191
+ /** The call comment mode's options are in: unbase({ … }) unless it leaves comment mode out, else commentModus({ … }). */
192
+ const comments = unbase && unbaseComments !== false ? unbase : entries.find((e) => e.kind === "comments");
193
+ return {
194
+ ast,
195
+ obj,
196
+ prop,
197
+ array,
198
+ spread,
199
+ imports,
200
+ entries,
201
+ has: {
202
+ /** commentModus() of its own: before K5, or beside unbase({ comments: false }). */
203
+ comments: at("comments").length > 0,
204
+ /** unbasePages() of its own: before K5. */
205
+ pages: pagesAt.length > 0,
206
+ link: imports.link.length > 0,
207
+ /** unbase({ … }) from @unbase-app/astro. */
208
+ unbase: !!unbase,
209
+ /** Comment mode is set up: by unbase() (not with comments: false) or by commentModus(). */
210
+ commentMode: !!comments,
211
+ /** The draft-pages kit is set up: by unbase() or by unbasePages(). */
212
+ kit: !!unbase || pagesAt.length > 0,
213
+ },
214
+ /** unbase()'s `comments`: true, false (comments: false), null when not literal; null without unbase(). */
215
+ unbaseComments,
216
+ /** comment mode's componentMarker: "always", "preview", false; null when unreadable or without comment mode. */
217
+ markers: comments ? markersOf(callOf(comments.el)) : null,
218
+ /** comment mode's own literal project, set in the config itself; null when it comes from comment-modus.json or a variable. */
219
+ project: comments ? projectOf(callOf(comments.el)) : null,
220
+ /** unbasePages() comes after sitemap() and commentModus(): the kit stops the build otherwise. */
221
+ orderOk: !pagesAt.length || before.every((i) => i < Math.min(...pagesAt)),
222
+ /** The entries the pages kit has to follow but does not. */
223
+ pagesBefore: pagesAt.length ? entries.filter((e) => (e.kind === "comments" || e.kind === "sitemap") && e.index > Math.min(...pagesAt)).map((e) => e.kind) : [],
224
+ };
225
+ }
226
+
227
+ // ── Formatting what is added, in the file's own style ───────────────────────
228
+
229
+ export function styleOf(code, ast) {
230
+ const firstImport = ast.program.body.find((n) => n.type === "ImportDeclaration");
231
+ const raw = firstImport ? code.slice(firstImport.source.start, firstImport.source.end) : '"';
232
+ const quote = raw.startsWith("'") ? "'" : '"';
233
+ const semi = firstImport ? code.slice(firstImport.start, firstImport.end).trimEnd().endsWith(";") : true;
234
+ const unit = /^( +|\t)\S/m.exec(code)?.[1] ?? " ";
235
+ return { quote, semi, unit: unit === "\t" ? "\t" : " ".repeat(Math.min(unit.length, 4)) };
236
+ }
237
+
238
+ export const lineStart = (code, i) => code.lastIndexOf("\n", i - 1) + 1;
239
+ export const indentAt = (code, i) => /^[ \t]*/.exec(code.slice(lineStart(code, i)))[0];
240
+ export const multiline = (code, a, b) => code.slice(a, b).includes("\n");
241
+
242
+ /** The token right after offset `end` (skipping comments, which are not tokens). */
243
+ export const tokenAfter = (ast, end) => ast.tokens.find((t) => t.start >= end && t.type !== "CommentLine" && t.type !== "CommentBlock");
244
+ export const isComma = (t) => t && (t.type?.label === "," || t.type === "," || t.value === ",");
245
+
246
+ /** unbase()'s argument as init writes it: comment mode linked through comment-modus.json, or none. */
247
+ function unbaseArgument(comments, style, indent, multi) {
248
+ const q = (x) => `${style.quote}${x}${style.quote}`;
249
+ if (!comments) return "{ comments: false }";
250
+ const opts = [`project: ${NAMES.link}.project`, `layerUrl: ${q(LAYER_URL)}`, "edit: true"];
251
+ return multi ? `{\n${opts.map((o) => `${indent}${style.unit}${o},`).join("\n")}\n${indent}}` : `{ ${opts.join(", ")} }`;
252
+ }
253
+
254
+ /** The entry init adds, with its line above it when the list is multi-line. */
255
+ function unbaseEntry(comments, style, indent, multi) {
256
+ const call = `${NAMES.unbase}(${unbaseArgument(comments, style, indent, multi)})`;
257
+ return multi ? `${comments ? UNBASE_LINE : UNBASE_LINE_NO_COMMENTS}\n${indent}${call}` : call;
258
+ }
259
+
260
+ function importLine(kind, style) {
261
+ const q = (x) => `${style.quote}${x}${style.quote}`;
262
+ return `import ${NAMES[kind]} from ${q(SOURCES[kind])}${style.semi ? ";" : ""}`;
263
+ }
264
+
265
+ export function applySplices(code, splices) {
266
+ let out = code;
267
+ for (const s of [...splices].sort((a, b) => b.start - a.start || b.end - a.end)) out = out.slice(0, s.start) + (s.text ?? "") + out.slice(s.end);
268
+ return out;
269
+ }
270
+
271
+ /** An entry's own comment lines: right above it, after the element before it (a comment on that one's line is not this one's). */
272
+ function leadOf(code, info, e) {
273
+ const els = info.array.elements;
274
+ const prevEnd = e.index > 0 ? els[e.index - 1].end : info.array.start + 1;
275
+ return (e.el.leadingComments ?? []).filter((c) => c.start >= prevEnd && code.slice(prevEnd, c.start).includes("\n"));
276
+ }
277
+
278
+ /** The splice that takes an entry out of `integrations`, with its comment lines and its comma. */
279
+ function entryRemoval(code, info, e) {
280
+ const el = e.el;
281
+ const start = Math.min(el.start, ...leadOf(code, info, e).map((c) => c.start));
282
+ const comma = tokenAfter(info.ast, el.end);
283
+ const end = isComma(comma) ? comma.end : el.end;
284
+ const whole = lineRange(code, start, end);
285
+ if (whole) return whole;
286
+ if (isComma(comma)) return { start, end: /^\s*/.exec(code.slice(end))[0].length + end };
287
+ return { start, end: el.end };
288
+ }
289
+
290
+ /**
291
+ * A text moved to another indent: its lines after the first shifted so that its last line (the
292
+ * closing brace of an object) stands at `indent`. A one-line text stays as it is.
293
+ */
294
+ function reindent(text, indent) {
295
+ const lines = text.split("\n");
296
+ if (lines.length < 2) return text;
297
+ const have = /^[ \t]*/.exec(lines[lines.length - 1])[0];
298
+ const by = have.length - indent.length;
299
+ if (by === 0) return text;
300
+ return [lines[0], ...lines.slice(1).map((l) => (by > 0 ? l.replace(new RegExp(`^[ \\t]{0,${by}}`), "") : `${" ".repeat(-by)}${l}`))].join("\n");
301
+ }
302
+
303
+ /**
304
+ * Splices that take a package's imports out: a declaration whose names all go is removed with its
305
+ * line; one that keeps a name the site uses for itself (`import commentModus, { sleutelVanPad }`)
306
+ * loses only the entry's name. Returns the splices and the first declaration removed whole, where
307
+ * the new import can stand.
308
+ */
309
+ function importRemovals(code, info, kinds, gone) {
310
+ const splices = [];
311
+ let slot = null;
312
+ for (const { kind, node } of info.imports.nodes) {
313
+ if (!kinds.includes(kind)) continue;
314
+ const keep = node.specifiers.filter((sp) => !gone.has(sp.local.name));
315
+ if (!keep.length) {
316
+ const whole = lineRange(code, node.start, node.end) ?? { start: node.start, end: node.end };
317
+ if (!slot) slot = { node, whole };
318
+ else splices.push(whole);
319
+ continue;
320
+ }
321
+ if (keep.length === node.specifiers.length) continue;
322
+ // Only the default import goes, before the braces: `commentModus, { … }` → `{ … }`.
323
+ const def = node.specifiers.find((sp) => sp.type === "ImportDefaultSpecifier" && gone.has(sp.local.name));
324
+ if (!def || node.specifiers.some((sp) => sp !== def && gone.has(sp.local.name))) throw new Error(`cannot take ${[...gone].join(", ")} out of the import of ${node.source.value}`);
325
+ const next = tokenAfter(info.ast, def.end);
326
+ const after = isComma(next) ? info.ast.tokens.find((t) => t.start >= next.end && t.type !== "CommentLine" && t.type !== "CommentBlock") : null;
327
+ if (!after) throw new Error(`cannot read the import of ${node.source.value}`);
328
+ splices.push({ start: def.start, end: after.start });
329
+ }
330
+ return { splices, slot };
331
+ }
332
+
333
+ /**
334
+ * The config with Unbase in it the K5 way, one entry: unbase({ … }) from @unbase-app/astro.
335
+ *
336
+ * - Nothing of Unbase yet: the import, comment-modus.json's import with comments, and the entry
337
+ * at the end of `integrations` (it adds what it brings after every other integration itself).
338
+ * - The pair from before K5: unbase() takes commentModus()'s place and its options as they are
339
+ * (the `commentModusConfig.project ? … : null` init wrote goes: unbase() waits for the project
340
+ * itself), unbasePages() and its import go, and a name the site imports from comment-modus for
341
+ * itself stays imported. Only the kit before: unbase() takes its place.
342
+ * - unbase({ comments: false }) and `comments`: the argument becomes init's linked one.
343
+ *
344
+ * Returns the new code and what changed; the same code when there is nothing to do.
345
+ */
346
+ export function addToConfig(code, file, { comments }) {
347
+ const info = inspectConfig(code, file);
348
+ const style = styleOf(code, info.ast);
349
+ const ours = (kind) => info.entries.filter((e) => e.kind === kind);
350
+ const [unbase, ...moreUnbase] = ours("unbase");
351
+ const [own, ...moreComments] = ours("comments");
352
+ const pages = ours("pages");
353
+ if (moreUnbase.length) throw unsafe(file, "it calls unbase() twice");
354
+ if (moreComments.length) throw unsafe(file, "it calls commentModus() twice");
355
+ const ownWithUnbase = unbase && own && info.unbaseComments !== false;
356
+ if (ownWithUnbase) throw unsafe(file, "it sets comment mode up twice, in unbase() and in commentModus()");
357
+
358
+ const splices = [];
359
+ const changes = [];
360
+ const usesLink = info.imports.link.length > 0;
361
+ const addLink = () => {
362
+ if (usesLink) return null;
363
+ if (usesName(info.ast, NAMES.link)) throw unsafe(file, `it already uses the name ${NAMES.link}`);
364
+ changes.push(`import ${NAMES.link} from "${SOURCES.link}"`);
365
+ return importLine("link", style);
366
+ };
367
+
368
+ if (unbase) {
369
+ // Already the one package: the kit's own entry is one too many; comments switched on if asked.
370
+ for (const e of pages) {
371
+ splices.push(entryRemoval(code, info, e));
372
+ changes.push("removed integrations: unbasePages(): unbase() brings the kit");
373
+ }
374
+ const removed = importRemovals(code, info, pages.length ? ["pages"] : [], new Set(info.imports.pages));
375
+ splices.push(...removed.splices);
376
+ if (removed.slot) splices.push(removed.slot.whole);
377
+ const call = callOf(unbase.el);
378
+ const arg = unwrap(call.arguments[0]);
379
+ if (comments && info.unbaseComments === false && !own) {
380
+ // Only init's own `{ comments: false }`: anything more is the site's, for a person to change.
381
+ if (arg?.type !== "ObjectExpression" || arg.properties.length !== 1) throw unsafe(file, "unbase() leaves comments out with options of its own");
382
+ const multi = multiline(code, info.array.start, info.array.end);
383
+ const indent = indentAt(code, unbase.el.start);
384
+ splices.push({ start: arg.start, end: arg.end, text: unbaseArgument(true, style, indent, multi) });
385
+ for (const c of leadOf(code, info, unbase)) if (code.slice(c.start, c.end) === UNBASE_LINE_NO_COMMENTS) splices.push({ start: c.start, end: c.end, text: UNBASE_LINE });
386
+ const link = addLink();
387
+ if (link) splices.push(importAfter(code, info, [link]));
388
+ changes.push(`integrations: ${NAMES.unbase}({ comments: false }) → ${NAMES.unbase}({ project: ${NAMES.link}.project, … })`);
389
+ }
390
+ if (!splices.length) return { code, changes: [] };
391
+ return finish(code, file, splices, changes, comments);
392
+ }
393
+
394
+ if (usesName(info.ast, NAMES.unbase)) throw unsafe(file, `it already uses the name ${NAMES.unbase}`);
395
+ const multi = info.array ? multiline(code, info.array.start, info.array.end) : true;
396
+ const importUnbase = importLine("unbase", style);
397
+
398
+ if (own || pages.length) {
399
+ // The move: the pair (or the kit alone) becomes the one entry.
400
+ const goneNames = new Set([...info.imports.pages, ...(own ? info.imports.comments : [])]);
401
+ const removed = importRemovals(code, info, own ? ["pages", "comments"] : ["pages"], goneNames);
402
+ splices.push(...removed.splices);
403
+ // Names the entries bring must not be used outside them.
404
+ const going = [own, ...pages].filter(Boolean);
405
+ const inEntries = (n) => going.some((e) => n.start >= e.el.start && n.end <= e.el.end);
406
+ const elsewhere = references(info.ast.program, goneNames).filter((n) => !inEntries(n));
407
+ if (elsewhere.length) throw unsafe(file, `it uses ${elsewhere[0].name} (line ${elsewhere[0].loc.start.line}) outside the integration's entry`);
408
+
409
+ const target = own ?? pages[0];
410
+ const indent = indentAt(code, target.el.start);
411
+ let text;
412
+ if (own) {
413
+ const call = callOf(own.el);
414
+ const el = unwrap(own.el);
415
+ if (el !== call) {
416
+ // Only the condition init wrote: comment-modus.json's project, which unbase() waits for itself.
417
+ const test = unwrap(el.type === "ConditionalExpression" ? el.test : el.left);
418
+ const isLink = test?.type === "MemberExpression" && !test.computed && test.object.type === "Identifier" && info.imports.link.includes(test.object.name) && test.property.name === "project";
419
+ const elseNull = el.type !== "ConditionalExpression" || unwrap(el.alternate)?.type === "NullLiteral";
420
+ if (!isLink || !elseNull) throw unsafe(file, "commentModus() is behind a condition of the site's own; move it into unbase() by hand");
421
+ }
422
+ if (call.arguments.length !== 1) throw unsafe(file, "commentModus() is not called with one argument");
423
+ text = `${NAMES.unbase}(${reindent(code.slice(call.arguments[0].start, call.arguments[0].end), indent)})`;
424
+ changes.push(`integrations: commentModus(…) → ${NAMES.unbase}(…), with the same options`);
425
+ } else {
426
+ text = `${NAMES.unbase}(${unbaseArgument(comments, style, indent, multi)})`;
427
+ changes.push(`integrations: unbasePages() → ${NAMES.unbase}(${comments ? "{ project: … }" : "{ comments: false }"})`);
428
+ if (comments) {
429
+ const link = addLink();
430
+ if (link) splices.push(importAfter(code, info, [link], removed.slot));
431
+ }
432
+ }
433
+ splices.push({ start: target.el.start, end: target.el.end, text });
434
+ // init's own lines above the pair: the one line now; the site's own comments stay.
435
+ let lined = false;
436
+ for (const c of leadOf(code, info, target)) {
437
+ if (!LINES_BEFORE.includes(code.slice(c.start, c.end).trim())) continue;
438
+ splices.push({ start: c.start, end: c.end, text: lined ? "" : own || comments ? UNBASE_LINE : UNBASE_LINE_NO_COMMENTS });
439
+ lined = true;
440
+ }
441
+ for (const e of pages) {
442
+ if (e === target) continue;
443
+ splices.push(entryRemoval(code, info, e));
444
+ changes.push("removed integrations: unbasePages(): unbase() brings the kit");
445
+ }
446
+ // The new import where an old one was removed whole, else after the last import.
447
+ if (removed.slot) splices.push({ start: removed.slot.node.start, end: removed.slot.node.end, text: importUnbase });
448
+ else splices.push(importAfter(code, info, [importUnbase]));
449
+ changes.unshift(`import ${NAMES.unbase} from "${SOURCES.unbase}"`, ...[...info.imports.nodes].filter(({ kind, node }) => (kind === "pages" || (own && kind === "comments")) && node.specifiers.every((sp) => goneNames.has(sp.local.name))).map(({ node }) => `removed import from "${node.source.value}"`));
450
+ return finish(code, file, splices, changes, own ? info.unbaseComments !== false : comments, true);
451
+ }
452
+
453
+ // Nothing of Unbase yet.
454
+ if (!info.prop && info.spread) throw unsafe(file, "its config spreads another object, which may hold `integrations`");
455
+ const link = comments ? addLink() : null;
456
+ splices.push(importAfter(code, info, [importUnbase, ...(link ? [link] : [])]));
457
+ changes.unshift(`import ${NAMES.unbase} from "${SOURCES.unbase}"`);
458
+ const { obj, prop, array } = info;
459
+ if (!prop) {
460
+ // No integrations yet: a new property at the end of the object.
461
+ const props = obj.properties;
462
+ const pIndent = props.length ? indentAt(code, props[0].start) : indentAt(code, obj.start) + style.unit;
463
+ const eIndent = pIndent + style.unit;
464
+ const block = `integrations: [\n${eIndent}${unbaseEntry(comments, style, eIndent, true)},\n${pIndent}]`;
465
+ if (!props.length) splices.push({ start: obj.start, end: obj.end, text: `{\n${pIndent}${block},\n${indentAt(code, obj.start)}}` });
466
+ else {
467
+ const last = props[props.length - 1];
468
+ const comma = tokenAfter(info.ast, last.end);
469
+ const multiObj = multiline(code, obj.start, obj.end);
470
+ if (isComma(comma)) splices.push({ start: comma.end, end: comma.end, text: `\n${pIndent}${block},` });
471
+ else splices.push({ start: last.end, end: last.end, text: `,${multiObj ? `\n${pIndent}` : " "}${block}` });
472
+ }
473
+ } else {
474
+ const els = array.elements;
475
+ const eIndent = els.length && multi ? indentAt(code, els[0].start) : indentAt(code, prop.start) + style.unit;
476
+ if (!els.length) {
477
+ const pIndent = indentAt(code, prop.start);
478
+ splices.push({ start: array.start, end: array.end, text: `[\n${pIndent}${style.unit}${unbaseEntry(comments, style, pIndent + style.unit, true)},\n${pIndent}]` });
479
+ } else {
480
+ const last = els[els.length - 1];
481
+ if (!last) throw unsafe(file, "`integrations` ends with a hole");
482
+ const src = unbaseEntry(comments, style, eIndent, multi);
483
+ const comma = tokenAfter(info.ast, last.end);
484
+ if (multi) {
485
+ if (isComma(comma)) splices.push({ start: comma.end, end: comma.end, text: `\n${eIndent}${src},` });
486
+ else splices.push({ start: last.end, end: last.end, text: `,\n${eIndent}${src}` });
487
+ } else splices.push({ start: last.end, end: last.end, text: `, ${src}` });
488
+ }
489
+ }
490
+ changes.push(`integrations: ${NAMES.unbase}(${comments ? "{ project: commentModusConfig.project, … }" : "{ comments: false }"})`);
491
+ return finish(code, file, splices, changes, comments);
492
+ }
493
+
494
+ /** The file has an identifier (a binding or a use, not a word in a string or a comment) of that name. */
495
+ function usesName(ast, name) {
496
+ let found = false;
497
+ const walk = (node) => {
498
+ if (found || !node || typeof node.type !== "string") return;
499
+ if (node.type === "Identifier" && node.name === name) return void (found = true);
500
+ for (const k of Object.keys(node)) {
501
+ if (k === "leadingComments" || k === "trailingComments" || k === "innerComments" || k === "loc" || k === "extra") continue;
502
+ const v = node[k];
503
+ if (Array.isArray(v)) v.forEach(walk);
504
+ else if (v && typeof v.type === "string") walk(v);
505
+ }
506
+ };
507
+ walk(ast.program);
508
+ return found;
509
+ }
510
+
511
+ /** An import line (or lines) after the file's last import that stays, or at the top. */
512
+ function importAfter(code, info, lines, slot = null) {
513
+ const imports = info.ast.program.body.filter((n) => n.type === "ImportDeclaration" && n !== slot?.node);
514
+ const last = imports.pop();
515
+ if (!last) return { start: 0, end: 0, text: `${lines.join("\n")}\n\n` };
516
+ const nl = code.indexOf("\n", last.end);
517
+ const eol = nl === -1 ? code.length : nl;
518
+ const at = /^[ \t]*(\/\/[^\n]*)?$/.test(code.slice(last.end, eol)) ? eol : last.end;
519
+ return { start: at, end: at, text: `\n${lines.join("\n")}` };
520
+ }
521
+
522
+ /** The edited config, parsed again and checked: one unbase(), no kit of its own, comment mode as asked. */
523
+ function finish(code, file, splices, changes, comments, moved = false) {
524
+ const next = applySplices(code, splices);
525
+ const after = verify(next, file);
526
+ const fine = after.has.unbase && !after.has.pages && (!comments || after.has.commentMode) && after.entries.filter((e) => e.kind === "unbase").length === 1;
527
+ if (!fine) throw unsafe(file, `the edited config did not come out as expected${moved ? " moving it to unbase()" : ""}`);
528
+ return { code: next, changes };
529
+ }
530
+
531
+ function verify(code, file) {
532
+ try {
533
+ return inspectConfig(code, file);
534
+ } catch (e) {
535
+ throw unsafe(file, `the edited config would not parse (${e.message}); nothing was written`);
536
+ }
537
+ }
538
+
539
+ // ── Removing ────────────────────────────────────────────────────────────────
540
+
541
+ /** Every Identifier in a subtree that reads `names` (not a property key, not the import itself). */
542
+ export function references(node, names, out = [], parent = null, key = null) {
543
+ if (!node || typeof node.type !== "string") return out;
544
+ if (node.type === "ImportDeclaration") return out;
545
+ if (node.type === "Identifier" && names.has(node.name)) {
546
+ const isKey = parent && ((parent.type === "ObjectProperty" && key === "key" && !parent.computed) || (parent.type === "MemberExpression" && key === "property" && !parent.computed) || (parent.type === "ObjectMethod" && key === "key"));
547
+ if (!isKey) out.push(node);
548
+ }
549
+ for (const k of Object.keys(node)) {
550
+ if (k === "leadingComments" || k === "trailingComments" || k === "innerComments" || k === "loc" || k === "extra") continue;
551
+ const v = node[k];
552
+ if (Array.isArray(v)) for (const c of v) references(c, names, out, node, k);
553
+ else if (v && typeof v.type === "string") references(v, names, out, node, k);
554
+ }
555
+ return out;
556
+ }
557
+
558
+ /** Whole lines when the range has its lines to itself (a trailing // comment counts as its own). */
559
+ export function lineRange(code, start, end) {
560
+ const ls = lineStart(code, start);
561
+ const nl = code.indexOf("\n", end);
562
+ const le = nl === -1 ? code.length : nl + 1;
563
+ if (/^[ \t]*$/.test(code.slice(ls, start)) && /^[ \t]*(\/\/[^\n]*)?\r?\n?$/.test(code.slice(end, le))) return { start: ls, end: le };
564
+ return null;
565
+ }
566
+
567
+ /**
568
+ * The config without Unbase's packages: their imports (and comment-modus.json's), and their
569
+ * entries in `integrations` with the comment lines above them. Stops when a name they bring is
570
+ * used anywhere else in the file.
571
+ */
572
+ export function removeFromConfig(code, file) {
573
+ const info = inspectConfig(code, file);
574
+ const ours = info.entries.filter((e) => e.kind === "comments" || e.kind === "pages" || e.kind === "unbase");
575
+ const ourImports = info.imports.nodes.filter((n) => n.kind === "comments" || n.kind === "pages" || n.kind === "link" || n.kind === "unbase");
576
+ if (!ours.length && !ourImports.length) return { code, changes: [] };
577
+
578
+ const splices = [];
579
+ const els = info.array?.elements ?? [];
580
+ for (const e of ours) {
581
+ const el = e.el;
582
+ const prevEnd = e.index > 0 ? els[e.index - 1].end : info.array.start + 1;
583
+ // The comment lines right above the entry are its own; a comment on the previous entry's line is not.
584
+ const lead = (el.leadingComments ?? []).filter((c) => c.start >= prevEnd && code.slice(prevEnd, c.start).includes("\n"));
585
+ const start = Math.min(el.start, ...lead.map((c) => c.start));
586
+ const comma = tokenAfter(info.ast, el.end);
587
+ const end = isComma(comma) ? comma.end : el.end;
588
+ const whole = lineRange(code, start, end);
589
+ if (whole) splices.push(whole);
590
+ else if (isComma(comma)) splices.push({ start, end: /^\s*/.exec(code.slice(end))[0].length + end });
591
+ else splices.push({ start, end: el.end });
592
+ }
593
+
594
+ // Names our imports bring must not be used outside the entries being removed.
595
+ const names = new Set(ourImports.flatMap((n) => n.node.specifiers.map((s) => s.local.name)));
596
+ const removed = (n) => splices.some((s) => n.start >= s.start && n.end <= s.end);
597
+ const elsewhere = references(info.ast.program, names).filter((n) => !removed(n));
598
+ if (elsewhere.length) {
599
+ const n = elsewhere[0];
600
+ throw unsafe(file, `it uses ${n.name} (line ${n.loc.start.line}) outside the integration's entry; remove that use by hand`);
601
+ }
602
+ // The last entry going without a comma after it: the entry before it loses the comma init gave it.
603
+ const lastEl = els[els.length - 1];
604
+ const kept = els.filter((el, i) => el && !ours.some((e) => e.index === i));
605
+ if (lastEl && ours.some((e) => e.el === lastEl) && !isComma(tokenAfter(info.ast, lastEl.end)) && kept.length) {
606
+ const comma = tokenAfter(info.ast, kept[kept.length - 1].end);
607
+ const oneLine = !multiline(code, info.array.start, info.array.end);
608
+ if (isComma(comma) && !removed(comma)) splices.push({ start: comma.start, end: oneLine ? comma.end + /^\s*/.exec(code.slice(comma.end))[0].length : comma.end });
609
+ }
610
+ // An array left with nothing but white space in it becomes [].
611
+ if (info.array && !kept.length && ours.length) {
612
+ const inner = { start: info.array.start + 1, end: info.array.end - 1 };
613
+ const left = applySplices(code.slice(0, inner.end), splices.filter((s) => s.start >= inner.start && s.end <= inner.end)).slice(inner.start);
614
+ if (!left.trim()) {
615
+ for (let i = splices.length - 1; i >= 0; i--) if (splices[i].start >= inner.start && splices[i].end <= inner.end) splices.splice(i, 1);
616
+ splices.push({ start: inner.start, end: inner.end });
617
+ }
618
+ }
619
+ for (const { node } of ourImports) splices.push(lineRange(code, node.start, node.end) ?? { start: node.start, end: node.end });
620
+
621
+ const next = applySplices(code, splices);
622
+ const after = verify(next, file);
623
+ if (after.has.comments || after.has.pages || after.has.unbase || after.imports.nodes.some((n) => n.kind !== "sitemap")) throw unsafe(file, "the edited config did not come out as expected");
624
+ const changes = [
625
+ ...ourImports.map(({ node }) => `removed import from "${node.source.value}"`),
626
+ ...ours.map((e) => `removed integrations: ${e.kind === "comments" ? "commentModus(…)" : e.kind === "unbase" ? "unbase(…)" : "unbasePages()"}`),
627
+ ];
628
+ return { code: next, changes };
629
+ }
package/lib/doctor.mjs ADDED
@@ -0,0 +1,37 @@
1
+ // ============================================================================
2
+ // unbase doctor — per feature, what Unbase will say about this site, read
3
+ // with Unbase's own readers on the working tree, and one production build.
4
+ // It never calls Unbase. The features and their checks are the framework's
5
+ // (frameworks/*.mjs `doctor`); their shapes and states are feature.mjs's.
6
+ // A feature that is off fails the run (exit 1).
7
+ // ============================================================================
8
+
9
+ import { buildSite } from "./build.mjs";
10
+ import { FAILED, PASSED } from "./errors.mjs";
11
+ import { openSite, refresh } from "./site.mjs";
12
+
13
+ export async function doctor(flags, io) {
14
+ const site = await openSite(flags.dir ?? process.cwd());
15
+
16
+ // One production build first: the checks read what it wrote (on Astro, comment-modus writes the content schemas while it builds).
17
+ let build = null;
18
+ if (!flags["no-build"]) {
19
+ io.progress("Building the site (production)…");
20
+ build = buildSite(site, { label: "doctor" });
21
+ await refresh(site);
22
+ }
23
+ const features = await site.framework.doctor(site, { build });
24
+
25
+ build?.dispose();
26
+ const failed = features.some((f) => f.state === "off");
27
+ const count = (s) => features.filter((f) => f.state === s).length;
28
+ return {
29
+ command: "doctor",
30
+ ok: !failed,
31
+ exitCode: failed ? FAILED : PASSED,
32
+ site: site.root,
33
+ built: build ? build.ok : null,
34
+ features,
35
+ summary: { on: count("on"), off: count("off"), waiting: count("waiting"), notInstalled: count("not-installed") },
36
+ };
37
+ }