@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.
package/lib/errors.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // Exit codes, fixed and documented in the README: 0 passed, 1 failed, 2 could not run.
2
+ export const PASSED = 0;
3
+ export const FAILED = 1;
4
+ export const COULD_NOT_RUN = 2;
5
+
6
+ /** Something that stops a command before it could do its work: a usage error, an unsafe config, no site. */
7
+ export class CouldNotRun extends Error {
8
+ /** @param {string} code @param {string} message @param {{ file?: string, detail?: unknown }} [more] */
9
+ constructor(code, message, more = {}) {
10
+ super(message);
11
+ this.code = code;
12
+ this.file = more.file ?? null;
13
+ this.detail = more.detail ?? null;
14
+ }
15
+ }
@@ -0,0 +1,23 @@
1
+ // ============================================================================
2
+ // doctor's shapes, for every framework's checks (frameworks/*.mjs). A check:
3
+ // its id, its state, what it says, and when it is not ok what is missing, the
4
+ // file, and the agents file's step that fixes it. States:
5
+ // ok works
6
+ // missing the site has to change: fails the run (exit 1)
7
+ // waiting outside this repository (Unbase linking the project, a
8
+ // package release): named, does not fail the run
9
+ // info worth knowing, never fails
10
+ // skipped not checked (no build, or what it needs is missing)
11
+ // A feature is off when a check is missing, waiting when one waits,
12
+ // not-installed when the site chose not to have it, on otherwise.
13
+ // ============================================================================
14
+
15
+ /** @param {string} id @param {"ok"|"missing"|"waiting"|"info"|"skipped"} state @param {string} message @param {{ missing?: string, file?: string, step?: string, detail?: string }} [more] */
16
+ export const check = (id, state, message, more = {}) => ({ id, state, message, ...more });
17
+
18
+ export function featureState(checks, notInstalled = false) {
19
+ if (checks.some((c) => c.state === "missing")) return "off";
20
+ if (checks.some((c) => c.state === "waiting")) return "waiting";
21
+ if (notInstalled) return "not-installed";
22
+ return "on";
23
+ }
@@ -0,0 +1,485 @@
1
+ // ============================================================================
2
+ // Astro: what the CLI does that is Astro's (frameworks/index.mjs has the
3
+ // shape). init adds the one package, @unbase-app/astro, its line in
4
+ // astro.config (config-edit, through the syntax tree) and comment-modus.json;
5
+ // on a site from before K5 it moves the pair (comment-modus and the kit)
6
+ // across to it (`replaced`). uninstall takes either out with
7
+ // unbase.pages.json and the content schemas; doctor reads three features
8
+ // with Unbase's own readers (lib/readers.mjs: detect, read_settings,
9
+ // list_pages and the kit's core) on the working tree and one production
10
+ // build. The steps init leaves: agents/astro.md.
11
+ // ============================================================================
12
+
13
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { tailOf } from "../build.mjs";
16
+ import { hasOurScript } from "../compare.mjs";
17
+ import { addToConfig, inspectConfig, removeFromConfig } from "../config-edit.mjs";
18
+ import { CouldNotRun } from "../errors.mjs";
19
+ import { check, featureState } from "../feature.mjs";
20
+ import { core, readSettings, registryFiles, registryOf } from "../readers.mjs";
21
+ import { depsOf, installedVersion, uncommitted } from "../site.mjs";
22
+ import { ASTRO, BEFORE, COMMENT_MODUS, compareVersions, MARKERS_PREVIEW, PAGES, SELF, UNLISTED_BUILD_FAILURE } from "../versions.mjs";
23
+
24
+ /** The file with the steps init leaves, in this package. */
25
+ const AGENTS = "agents/astro.md";
26
+ /** comment-modus.json: the link to the Unbase project, which Unbase fills in when the site is connected. */
27
+ export const LINK_FILE = "comment-modus.json";
28
+ const SCHEMAS = "src/content/.schemas";
29
+ const STEPS = {
30
+ install: `${AGENTS} step 1: Install`,
31
+ pageSettings: `${AGENTS} step 2: Page settings`,
32
+ siteSettings: `${AGENTS} step 3: Site settings`,
33
+ schemas: `${AGENTS} step 4: Schemas`,
34
+ drafts: `${AGENTS} step 5: Draft pages`,
35
+ };
36
+ const SITE_FIELDS = ["naam", "beschrijving", "taal", "favicon", "faviconDonker", "ogImage", "googleAnalytics"];
37
+ const SOURCE = /^src\/.*\.(astro|ts|tsx|js|jsx|mjs|mts|mdx)$/;
38
+ const CONTENT_CONFIG = /^src\/(content\.config|content\/config)\.(ts|js|mjs|mts)$/;
39
+
40
+ /**
41
+ * Whether comment mode's data-c markers belong in a production build (plan-packages, *The rule*:
42
+ * "Markers in production only for comments on Live", *Open* 5, decided 03-11). Comments on Live
43
+ * need them (a pin's title and source file come from them), so with comment-modus installed they
44
+ * are expected, unless its config keeps them out of production (`componentMarker: "preview"`,
45
+ * comment-modus 1.9.0) or off (`false`). Without comment-modus a production build has none.
46
+ * `when` is the config's componentMarker as config-edit reads it; null (not literal) counts as the
47
+ * default, "always".
48
+ */
49
+ export const markersBelongInProduction = (commentsInstalled, when = "always") => commentsInstalled && when !== "preview" && when !== false;
50
+
51
+ /** The project comment-modus.json names, or null. */
52
+ export function readLink(site) {
53
+ try {
54
+ const data = JSON.parse(readFileSync(join(site.root, LINK_FILE), "utf8"));
55
+ return typeof data?.project === "string" ? data.project : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ // ── init ───────────────────────────────────────────────────────────────────
62
+
63
+ /** init's plan for astro.config and comment-modus.json. */
64
+ function planInit(site, { comments, project }) {
65
+ if (!site.configFile) throw new CouldNotRun("no_config", "No astro.config.(mjs|ts|js|mts) in the site's folder.");
66
+ const configCode = site.text(site.configFile);
67
+ const before = inspectConfig(configCode, site.configFile);
68
+ // A config that sets comment mode up itself keeps its own project. The same project (a site linked
69
+ // before init existed) is linked already; another one is for a person to change there.
70
+ if (project && before.has.commentMode && !before.has.link && before.project !== project)
71
+ throw new CouldNotRun(
72
+ "usage",
73
+ before.project
74
+ ? `${site.configFile} sets comment mode up itself, with project "${before.project}": change it there to "${project}".`
75
+ : `${site.configFile} sets comment mode up itself, with its own project: change the project there.`,
76
+ { file: site.configFile },
77
+ );
78
+ const config = addToConfig(configCode, site.configFile, { comments });
79
+ /** The config reads the project from comment-modus.json (init's way), so the file has to be there. */
80
+ const usesLink = inspectConfig(config.code, site.configFile).has.link;
81
+
82
+ let link = null;
83
+ if (comments) {
84
+ const text = site.text(LINK_FILE);
85
+ if (text === null) {
86
+ if (usesLink) link = { action: "created", data: { project }, indent: " ", changes: [project ? `project: "${project}"` : "project: null (Unbase fills it in when the site is connected)"] };
87
+ } else {
88
+ let data;
89
+ try {
90
+ data = JSON.parse(text);
91
+ } catch {
92
+ throw new CouldNotRun("link_file", `${LINK_FILE} is not valid JSON.`, { file: LINK_FILE });
93
+ }
94
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new CouldNotRun("link_file", `${LINK_FILE} is not a JSON object.`, { file: LINK_FILE });
95
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
96
+ if (project && data.project !== project) link = { action: "changed", data: { ...data, project }, indent, changes: [`project: ${JSON.stringify(data.project ?? null)} → "${project}"`] };
97
+ else if (!("project" in data) && usesLink) link = { action: "changed", data: { project: null, ...data }, indent, changes: ["project: null"] };
98
+ }
99
+ }
100
+ return [
101
+ ...(config.changes.length ? [{ file: site.configFile, action: "changed", changes: config.changes, text: config.code }] : []),
102
+ ...(link ? [{ file: LINK_FILE, action: link.action, changes: link.changes, text: `${JSON.stringify(link.data, null, link.indent)}\n` }] : []),
103
+ ];
104
+ }
105
+
106
+ // ── uninstall ──────────────────────────────────────────────────────────────
107
+
108
+ // ── The move (K5) ──────────────────────────────────────────────────────────
109
+
110
+ /** Files that may name comment-modus for the site's own use: code, scripts and CI, not docs or lockfiles. */
111
+ const OWN_USE = /\.(astro|ts|tsx|js|jsx|mjs|cjs|mts|cts|yml|yaml)$/;
112
+
113
+ /**
114
+ * What init takes out of a site from before K5, once the one package is in: the kit and the CLI
115
+ * under their old names, the kit under its own name (unbase() brings it), and comment-modus unless
116
+ * the site still uses it for itself (a name its config imports, its CLI in a script or a workflow).
117
+ * A comment-modus the site keeps is moved to the version the one package brings, so there is one.
118
+ * `planned`: init's plan for the config, which tells what the config still imports.
119
+ */
120
+ function planReplaced(site, planned) {
121
+ const deps = depsOf(site.pkg);
122
+ const remove = [BEFORE.pages, BEFORE.cli, PAGES.name].filter((n) => deps[n] !== undefined);
123
+ const keep = [];
124
+ if (deps[COMMENT_MODUS.name] !== undefined) {
125
+ const config = planned.find((f) => f.file === site.configFile)?.text ?? site.text(site.configFile) ?? "";
126
+ let imported = false;
127
+ try {
128
+ imported = inspectConfig(config, site.configFile).imports.nodes.some((n) => n.kind === "comments");
129
+ } catch {}
130
+ const scripts = Object.values(site.pkg.scripts ?? {}).some((c) => /\bcomment-modus\b/.test(String(c)));
131
+ const elsewhere = site.appPaths.some((p) => p !== site.configFile && OWN_USE.test(p) && !p.startsWith("node_modules/") && (site.text(p) ?? "").includes(COMMENT_MODUS.name));
132
+ if (imported || scripts || elsewhere) keep.push(COMMENT_MODUS);
133
+ else remove.push(COMMENT_MODUS.name);
134
+ }
135
+ return { remove, keep, by: ASTRO.name };
136
+ }
137
+
138
+ /** What of Unbase the site has now, for init's defaults: null without any of it; else whether comment mode is set up. */
139
+ function currentOf(site) {
140
+ const deps = depsOf(site.pkg);
141
+ if (![ASTRO.name, COMMENT_MODUS.name, PAGES.name, BEFORE.pages].some((n) => deps[n] !== undefined) || !site.configFile) return null;
142
+ try {
143
+ return { comments: inspectConfig(site.text(site.configFile), site.configFile).has.commentMode };
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ /** uninstall's plan: astro.config without the packages' lines, the packages, and the files they wrote. */
150
+ function planUninstall(site) {
151
+ const config = site.configFile ? removeFromConfig(site.text(site.configFile), site.configFile) : { code: null, changes: [] };
152
+ return {
153
+ packages: [ASTRO.name, COMMENT_MODUS.name, PAGES.name, BEFORE.pages, SELF.name, BEFORE.cli],
154
+ files: config.changes.length ? [{ file: site.configFile, action: "changed", changes: config.changes, text: config.code }] : [],
155
+ remove: [LINK_FILE, core.PAGE_FILE, SCHEMAS],
156
+ };
157
+ }
158
+
159
+ // ── doctor ─────────────────────────────────────────────────────────────────
160
+
161
+ /** The collections the committed schemas describe: route files (pad + seo) and site settings (x-instellingen: site). */
162
+ function settingsCollections(site) {
163
+ const dir = join(site.root, SCHEMAS);
164
+ const out = { route: null, site: null, count: 0 };
165
+ if (!existsSync(dir)) return out;
166
+ for (const f of readdirSync(dir).filter((n) => n.endsWith(".schema.json"))) {
167
+ out.count++;
168
+ let s = null;
169
+ try {
170
+ s = JSON.parse(readFileSync(join(dir, f), "utf8"));
171
+ } catch {}
172
+ const name = f.slice(0, -".schema.json".length);
173
+ if (s?.properties?.pad && s?.properties?.seo && !out.route) out.route = name;
174
+ if (s?.["x-instellingen"] === "site" && !out.site) out.site = name;
175
+ }
176
+ return out;
177
+ }
178
+
179
+ /** The files that read a collection: its name as the first argument of Astro's content functions. */
180
+ function readersOf(site, collection) {
181
+ const call = new RegExp(`\\b(getCollection|getEntry|getEntries|getLiveCollection|getLiveEntry)\\s*\\(\\s*(['"\`])${collection.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\2`);
182
+ return site.appPaths.filter((p) => SOURCE.test(p) && !CONTENT_CONFIG.test(p) && call.test(site.text(p) ?? ""));
183
+ }
184
+
185
+ /** Why a build failed, when doctor knows: comment-modus up to 1.8.0 installed but not in package.json. */
186
+ function knownFailure(site, deps, output) {
187
+ const k = UNLISTED_BUILD_FAILURE;
188
+ const have = installedVersion(site, k.package);
189
+ if (have && !deps[k.package] && compareVersions(have, k.upTo) <= 0 && k.output.test(output))
190
+ return `${k.package} ${have} is in node_modules but not listed in package.json, and up to ${k.upTo} it cannot build its /version.json route then. List it in package.json (or use ${k.fixedIn}, which builds either way).`;
191
+ return null;
192
+ }
193
+
194
+ function envHas(site, name) {
195
+ if (process.env[name]) return true;
196
+ return [".env", ".env.production", ".env.local", ".env.production.local"].some((f) => new RegExp(`^\\s*(export\\s+)?${name}\\s*=\\s*\\S`, "m").test(site.text(f) ?? ""));
197
+ }
198
+
199
+ /** doctor's three features on an Astro site, from the production build doctor made (null: --no-build). */
200
+ async function doctorFeatures(site, { build }) {
201
+ const built = !!build?.ok;
202
+
203
+ let config = null;
204
+ let configError = null;
205
+ if (site.configFile) {
206
+ try {
207
+ config = inspectConfig(site.text(site.configFile), site.configFile);
208
+ } catch (e) {
209
+ if (!(e instanceof CouldNotRun)) throw e;
210
+ configError = e.message;
211
+ }
212
+ }
213
+ const deps = depsOf(site.pkg);
214
+ const detection = site.detection;
215
+ const features = [];
216
+ const known = build && !build.ok ? knownFailure(site, deps, build.output) : null;
217
+ /** The one package (K5): comment mode and the kit come inside it, in node_modules without being listed. */
218
+ const one = deps[ASTRO.name] !== undefined;
219
+ /** A package in node_modules (or in the config) that package.json does not list: Unbase reads package.json, and the build may not find it. */
220
+ const unlisted = (p, usedInConfig) =>
221
+ !one && !deps[p.name] && (installedVersion(site, p.name) || usedInConfig)
222
+ ? check("listed", "missing", `${p.name} is ${installedVersion(site, p.name) ? `in node_modules (${installedVersion(site, p.name)})` : "used in the config"} but not listed in package.json.`, {
223
+ missing: `${p.name} in dependencies, pinned`,
224
+ file: "package.json",
225
+ step: STEPS.install,
226
+ })
227
+ : null;
228
+
229
+ // ── Visual editing ────────────────────────────────────────────────────────
230
+ {
231
+ const checks = [check("astro", "ok", `Astro ${installedVersion(site, "astro") ?? detection.framework.version ?? ""}, which Unbase reads with its Astro adapter: texts are edited where they are written, nothing installed.`)];
232
+ if (!build) checks.push(check("build", "skipped", "Not built (--no-build)."));
233
+ else if (built) checks.push(check("build", "ok", `A production build works (${build.html.size} pages).`));
234
+ else if (known) checks.push(check("build", "missing", `The production build fails: ${known}`, { missing: `${COMMENT_MODUS.name} listed in package.json`, file: "package.json", step: STEPS.install, detail: tailOf(build.output, 6) }));
235
+ else checks.push(check("build", "missing", "The production build fails, so Unbase cannot start or check the site.", { missing: "a site that builds", file: site.configFile, detail: tailOf(build.output) }));
236
+ const names = detection.settings.map((s) => s.name);
237
+ if (names.length) checks.push(check("settings", "info", `The code reads ${names.length} setting(s) (${names.slice(0, 6).join(", ")}${names.length > 6 ? ", …" : ""}). If the site needs them to start, give them development values in Unbase.`));
238
+ features.push({ id: "visual-editing", name: "Visual editing", state: featureState(checks), checks });
239
+ }
240
+
241
+ // ── Comments on the site ──────────────────────────────────────────────────
242
+ const commentsInstalled = detection.comment_modus.state === "installed";
243
+ {
244
+ const checks = [];
245
+ const htmlWithMarkers = built ? [...build.html].filter(([, h]) => /\sdata-c="/.test(h)).map(([p]) => p) : [];
246
+ const markersCheck = (linked) => {
247
+ if (!build) return check("markers", "skipped", "Not built (--no-build).");
248
+ if (!built) return check("markers", "skipped", "The build failed.");
249
+ const when = commentsInstalled ? (config?.markers ?? "always") : null;
250
+ if (!markersBelongInProduction(commentsInstalled, when)) {
251
+ const setting = `componentMarker: ${JSON.stringify(when)}`;
252
+ if (!htmlWithMarkers.length)
253
+ return check(
254
+ "markers",
255
+ "ok",
256
+ !commentsInstalled
257
+ ? "No data-c markers in the production build."
258
+ : when === "preview"
259
+ ? `No data-c markers in the production build (${setting}): they are in the dev server and previews only, so a pin on the live site is named after its section.`
260
+ : `No data-c markers in the production build (${setting}).`,
261
+ );
262
+ const have = commentsInstalled ? installedVersion(site, COMMENT_MODUS.name) : null;
263
+ const tooOld = when === "preview" && have && compareVersions(have, MARKERS_PREVIEW.since) < 0;
264
+ const found = `${htmlWithMarkers.length} built page(s) carry data-c markers`;
265
+ const where = `(e.g. ${htmlWithMarkers[0]})`;
266
+ if (tooOld)
267
+ return check("markers", "missing", `${found} ${where}: ${site.configFile} says ${setting}, which ${COMMENT_MODUS.name} ${have} does not know; ${MARKERS_PREVIEW.since} keeps them out of production builds.`, {
268
+ missing: `${COMMENT_MODUS.name} ${MARKERS_PREVIEW.since} or later`,
269
+ file: "package.json",
270
+ step: STEPS.install,
271
+ });
272
+ return check("markers", "missing", `${found} ${commentsInstalled ? `although ${site.configFile} says ${setting}` : "without comment mode installed"} ${where}.`, {
273
+ missing: "no data-c in a production build",
274
+ file: site.configFile,
275
+ });
276
+ }
277
+ if (!linked) return check("markers", "skipped", "Markers come with comment mode, once it is linked.");
278
+ return htmlWithMarkers.length
279
+ ? check("markers", "ok", `${htmlWithMarkers.length} of ${build.html.size} built pages carry comment mode's data-c markers: a pin's title and source file come from them.`)
280
+ : check("markers", "info", "No data-c markers in the build: comment mode marks the components in src/components, and found none on these pages.");
281
+ };
282
+ const notListed = unlisted(COMMENT_MODUS, !!config?.has.comments);
283
+ /** Where comment mode is set up: unbase() (K5), or commentModus() of its own. */
284
+ const call = config?.has.unbase && config.unbaseComments !== false ? "unbase()" : "commentModus()";
285
+ if (!commentsInstalled && notListed) {
286
+ checks.push(notListed);
287
+ features.push({ id: "comments", name: "Comments on the site", state: featureState(checks), checks });
288
+ } else if (!commentsInstalled) {
289
+ checks.push(
290
+ check(
291
+ "package",
292
+ "info",
293
+ one && config?.unbaseComments === false
294
+ ? `Left out: unbase({ comments: false }); \`unbase init --comments\` turns it on. Comments on the canvas in Unbase work without it.`
295
+ : `Not in the code: \`unbase init --comments\` adds it (${ASTRO.name}, with ${COMMENT_MODUS.name}). Comments on the canvas in Unbase work without it.`,
296
+ ),
297
+ );
298
+ checks.push(markersCheck(false));
299
+ features.push({ id: "comments", name: "Comments on the site", state: featureState(checks, true), checks });
300
+ } else {
301
+ checks.push(
302
+ check(
303
+ "package",
304
+ "ok",
305
+ one
306
+ ? `${ASTRO.name} ${installedVersion(site, ASTRO.name) ?? deps[ASTRO.name]} is a dependency, with ${[COMMENT_MODUS.name, installedVersion(site, COMMENT_MODUS.name)].filter(Boolean).join(" ")} in it.`
307
+ : `${COMMENT_MODUS.name} ${installedVersion(site, COMMENT_MODUS.name) ?? deps[COMMENT_MODUS.name]} is a dependency.`,
308
+ ),
309
+ );
310
+ if (configError) checks.push(check("config", "missing", configError, { file: site.configFile, step: STEPS.install }));
311
+ else if (!config?.has.commentMode)
312
+ checks.push(
313
+ check("config", "missing", `${site.configFile ?? "astro.config"} does not set comment mode up: ${one ? "unbase() is not" : "commentModus() is not"} in integrations.`, {
314
+ missing: `${one ? "unbase()" : "commentModus()"} in integrations`,
315
+ file: site.configFile ?? "astro.config.mjs",
316
+ step: STEPS.install,
317
+ }),
318
+ );
319
+ else checks.push(check("config", "ok", `${call} is in integrations.`));
320
+ const project = detection.comment_modus.project ?? (config?.has.link ? readLink(site) : null);
321
+ const linked = !!project || (config?.has.commentMode && !config?.has.link);
322
+ if (project) checks.push(check("link", "ok", `Linked to the Unbase project "${project}".`, { file: config?.has.link ? "comment-modus.json" : site.configFile }));
323
+ else if (config?.has.link)
324
+ checks.push(
325
+ check("link", "waiting", "Not linked to an Unbase project yet, so comment mode stays off. Unbase fills in `project` in comment-modus.json when the site is connected; or run `unbase init --project <id or slug>`.", {
326
+ missing: "project in comment-modus.json",
327
+ file: "comment-modus.json",
328
+ }),
329
+ );
330
+ else checks.push(check("link", "info", `comment mode's project is set in code doctor cannot read; Unbase reads it from comment-modus.json or a literal \`project\` in ${call}.`));
331
+ checks.push(markersCheck(linked));
332
+ if (built && linked) {
333
+ const withLoader = [...build.html].filter(([, h]) => hasOurScript(h, build.file)).length;
334
+ checks.push(
335
+ withLoader
336
+ ? check("loader", "ok", `The ?comment loader is on ${withLoader} of ${build.html.size} built pages; it loads nothing unless someone opens ?comment.`)
337
+ : check("loader", "missing", "The ?comment loader is on no built page.", { missing: "comment mode's loader", file: site.configFile, step: STEPS.install }),
338
+ );
339
+ }
340
+ if (!envHas(site, "PUBLIC_SUPABASE_URL") || !envHas(site, "PUBLIC_SUPABASE_ANON_KEY"))
341
+ checks.push(check("backend", "info", "comment mode finds Unbase's backend through PUBLIC_SUPABASE_URL and PUBLIC_SUPABASE_ANON_KEY where the site is built; they are not set here, and doctor cannot see your host's."));
342
+ features.push({ id: "comments", name: "Comments on the site", state: featureState(checks), checks });
343
+ }
344
+ }
345
+
346
+ // ── Page management: draft pages and page settings ─────────────────────────
347
+ {
348
+ const checks = [];
349
+ const text = (p) => site.text(p);
350
+ const kit = core.kitInstalled({ framework: "astro", text });
351
+ /** The package that brings the kit here: the one package, the kit, or the kit's name before K5. */
352
+ const kitName = core.KITS.astro.find((n) => deps[n] !== undefined) ?? null;
353
+ const pagesUnlisted = unlisted(PAGES, !!config?.has.pages);
354
+ if (pagesUnlisted && !kitName) checks.push(pagesUnlisted);
355
+ else if (kit) checks.push(check("kit", "ok", `${kitName} ${installedVersion(site, kitName) ?? deps[kitName]} is a dependency and in ${site.configFile}${kitName === ASTRO.name ? ", with the draft-pages kit in it" : ""}.`));
356
+ else
357
+ checks.push(
358
+ check("kit", "missing", kitName ? `${site.configFile ?? "astro.config"} does not use ${kitName === ASTRO.name ? "unbase()" : "unbasePages()"}.` : `${ASTRO.name} is not a dependency.`, {
359
+ missing: kitName ? `${kitName === ASTRO.name ? "unbase()" : "unbasePages()"} in integrations` : ASTRO.name,
360
+ file: kitName ? (site.configFile ?? "astro.config.mjs") : "package.json",
361
+ step: STEPS.install,
362
+ }),
363
+ );
364
+ // A site from before K5 works as it is; the one package is where Update goes.
365
+ const before = [COMMENT_MODUS.name, BEFORE.pages].filter((n) => deps[n] !== undefined);
366
+ if (!one && before.includes(BEFORE.pages))
367
+ checks.push(check("moved", "info", `${before.join(" and ")} ${before.length > 1 ? "are" : "is"} one package since 03-11, ${ASTRO.name}: \`npx ${SELF.name} init\` moves the site across (one dependency, one line in ${site.configFile ?? "astro.config"}).`));
368
+ if (config && config.has.pages && !config.orderOk)
369
+ checks.push(check("order", "missing", `unbasePages() comes before ${config.pagesBefore.join(" and ")} in integrations: the kit stops every production build until it comes after them.`, { missing: "unbasePages() last", file: site.configFile, step: STEPS.drafts }));
370
+
371
+ // The drafts unbase.pages.json holds now, as a production build will treat them.
372
+ const files = site.appPaths.filter(registryFiles).map((p) => ({ path: p, text: text(p) ?? "" }));
373
+ const pageFile = core.parsePageFile(text(core.PAGE_FILE));
374
+ if (!pageFile.ok) checks.push(check("drafts", "missing", `${core.PAGE_FILE} is invalid: ${pageFile.error}.`, { missing: `a valid ${core.PAGE_FILE}`, file: core.PAGE_FILE, step: STEPS.drafts }));
375
+ else {
376
+ const paths = files.map((f) => f.path).sort();
377
+ const plan = core.draftPlan({ framework: "astro", paths, text: (p) => files.find((f) => f.path === p)?.text ?? null, pageFile });
378
+ if (plan.failed.length)
379
+ checks.push(
380
+ check("drafts", "missing", `A production build would stop: ${plan.failed.map((f) => `${f.path} (${f.reason}${f.detail ? `: ${f.detail}` : ""})`).join(", ")}.`, {
381
+ missing: "drafts the kit can keep out",
382
+ file: core.PAGE_FILE,
383
+ step: STEPS.drafts,
384
+ }),
385
+ );
386
+ else checks.push(check("drafts", "ok", plan.checks.length ? `${plan.checks.length} draft(s) in ${core.PAGE_FILE}, each kept out of production builds.` : "No drafts now."));
387
+ }
388
+ if (kit && build) {
389
+ if (!built) checks.push(check("fails-closed", "skipped", "The build failed."));
390
+ else if (/production build \(UNBASE_DEPLOY_CONTEXT\)/.test(build.output)) checks.push(check("fails-closed", "ok", "The kit ran in the production build: a draft it cannot keep out stops the build."));
391
+ else checks.push(check("fails-closed", "missing", "The kit did not run in the production build.", { missing: "unbasePages() running in astro build", file: site.configFile, step: STEPS.install }));
392
+ }
393
+ // Which pages can be drafts, as Unbase's page tree will say (staged: Publishing with a Live branch, set in Unbase).
394
+ const registry = registryOf({ files, framework: "astro", appPath: site.appPath, staged: true, truncated: false });
395
+ const pages = registry.pages.filter((p) => p.kind !== "template");
396
+ if (kit) {
397
+ const ok = pages.filter((p) => p.capabilities.draft.ok).length;
398
+ const why = {};
399
+ for (const p of pages) if (!p.capabilities.draft.ok) (why[p.capabilities.draft.reason] ??= []).push(p.path);
400
+ const rest = Object.entries(why).map(([r, list]) => `${r}: ${list.slice(0, 3).join(", ")}${list.length > 3 ? ", …" : ""}`);
401
+ checks.push(check("draftable", "info", `${ok} of ${pages.length} pages can be drafts${rest.length ? ` (not: ${rest.join("; ")})` : ""}. In Unbase, draft pages also need Publishing with a Live branch.`));
402
+ }
403
+
404
+ // Page settings and site settings: read_settings, on the committed schemas.
405
+ const settings = await readSettings(site.repo, site.appPath);
406
+ const named = settingsCollections(site);
407
+ if (!commentsInstalled && !named.count) {
408
+ checks.push(check("schemas", "info", `Page and site settings need the content schemas in ${SCHEMAS}/, which comment-modus writes: \`unbase init --comments\`.`));
409
+ } else if (!named.count) {
410
+ const linked = !!(detection.comment_modus.project ?? readLink(site)) || (config?.has.comments && !config?.has.link);
411
+ if (!linked) checks.push(check("schemas", "waiting", `No content schemas in ${SCHEMAS}/ yet: comment-modus writes them in a build once it is linked to a project.`, { missing: SCHEMAS, file: SCHEMAS, step: STEPS.schemas }));
412
+ else {
413
+ checks.push(check("schemas", "missing", `No content schemas in ${SCHEMAS}/: comment-modus writes them in a build or dev run for collections that have files; add the collections (steps 2 and 3), build, and commit them.`, { missing: SCHEMAS, file: SCHEMAS, step: STEPS.schemas }));
414
+ // Without schemas the collections cannot be read yet; the content config says whether they are there at all.
415
+ const contentConfig = contentConfigFile(site);
416
+ const source = site.text(contentConfig) ?? "";
417
+ if (!/\bpad\s*:/.test(source) || !/\bseo\s*:/.test(source))
418
+ checks.push(check("route-files", "missing", "No collection with `pad` and `seo`: page settings have no place per page.", { missing: "a route-file collection", file: contentConfig, step: STEPS.pageSettings }));
419
+ if (!/x-instellingen/.test(source))
420
+ checks.push(check("site-settings", "missing", 'No collection marked `"x-instellingen": "site"`: site settings have no place.', { missing: "a site-settings collection", file: contentConfig, step: STEPS.siteSettings }));
421
+ }
422
+ } else {
423
+ const dirty = uncommitted(site, SCHEMAS);
424
+ checks.push(check("schemas", "ok", `${named.count} content schema(s) in ${SCHEMAS}/.${dirty.length ? ` ${dirty.length} file(s) there are not committed yet: Unbase reads them from the repository.` : ""}`));
425
+ }
426
+ if (named.count || commentsInstalled) {
427
+ if (settings?.routes && named.route) {
428
+ const own = pages.filter((p) => settings.pages[p.path]).length;
429
+ const strays = Object.keys(settings.pages).filter((r) => !pages.some((p) => p.path === r));
430
+ if (!settings.routes.fields.length)
431
+ checks.push(check("route-files", "missing", `The route files' seo object allows none of titel, beschrijving, ogImage, noindex, zoeken.`, { missing: "seo fields", file: contentConfigFile(site), step: STEPS.pageSettings }));
432
+ else
433
+ checks.push(
434
+ check("route-files", "ok", `Page settings in ${settings.routes.dir}/ (collection ${named.route}): ${own} of ${pages.length} pages have a route file${own < pages.length ? "; the others get one when their settings are first published" : ""}.${strays.length ? ` No page for: ${strays.slice(0, 3).join(", ")}.` : ""}`),
435
+ );
436
+ const by = readersOf(site, named.route);
437
+ checks.push(
438
+ by.length
439
+ ? check("route-files-read", "ok", `Read by ${by.slice(0, 3).join(", ")}.`)
440
+ : check("route-files-read", "missing", `Nothing reads the collection ${named.route}: the layout has to use a page's route file before its own title and description.`, { missing: `getCollection("${named.route}") in the layout`, file: "src/layouts", step: STEPS.pageSettings }),
441
+ );
442
+ } else if (named.count) {
443
+ checks.push(check("route-files", "missing", "No collection with `pad` and `seo`: page settings have no place per page.", { missing: "a route-file collection", file: contentConfigFile(site), step: STEPS.pageSettings }));
444
+ }
445
+ if (settings?.site && named.site) {
446
+ const settable = Object.keys(settings.site).length;
447
+ checks.push(check("site-settings", "ok", `Site settings in ${Object.values(settings.site)[0]?.file ?? `collection ${named.site}`}: ${settable} of ${SITE_FIELDS.length} settable.`));
448
+ const by = readersOf(site, named.site);
449
+ checks.push(
450
+ by.length
451
+ ? check("site-settings-read", "ok", `Read by ${by.slice(0, 3).join(", ")}.`)
452
+ : check("site-settings-read", "missing", `Nothing reads the collection ${named.site}: the layout has to use it before its own defaults.`, { missing: `getEntry("${named.site}", …) in the layout`, file: "src/layouts", step: STEPS.siteSettings }),
453
+ );
454
+ } else if (named.count) {
455
+ checks.push(check("site-settings", "missing", 'No collection marked `"x-instellingen": "site"`: site settings have no place.', { missing: "a site-settings collection", file: contentConfigFile(site), step: STEPS.siteSettings }));
456
+ }
457
+ }
458
+ features.push({ id: "page-management", name: "Page management", state: featureState(checks), checks });
459
+ }
460
+ return features;
461
+ }
462
+
463
+ function contentConfigFile(site) {
464
+ return ["src/content.config.ts", "src/content.config.mjs", "src/content.config.js", "src/content/config.ts"].find((f) => site.exists(f)) ?? "src/content.config.ts";
465
+ }
466
+
467
+ /** Where Astro's adapters put the static pages when they move the output (Vercel, Netlify). */
468
+ const ADAPTER_OUTPUT = [".vercel/output/static", "dist/client", ".netlify/static"];
469
+
470
+ export default {
471
+ id: "astro",
472
+ name: "Astro",
473
+ /** In the order the kit looks for them (kitFiles). */
474
+ configFiles: core.kitFiles("astro").filter((f) => f !== "package.json"),
475
+ agents: AGENTS,
476
+ comments: true,
477
+ build: { bin: "astro", args: (outDir) => ["build", "--outDir", outDir], env: { ASTRO_TELEMETRY_DISABLED: "1" }, output: ADAPTER_OUTPUT },
478
+ packages: () => [ASTRO, SELF],
479
+ init: planInit,
480
+ replaced: planReplaced,
481
+ current: currentOf,
482
+ linked: readLink,
483
+ uninstall: planUninstall,
484
+ doctor: doctorFeatures,
485
+ };
@@ -0,0 +1,50 @@
1
+ // ============================================================================
2
+ // The frameworks the CLI has a package for (docs/plan-packages.md, K5: one
3
+ // package per framework). What differs per framework is in its module; init,
4
+ // doctor and uninstall do the rest the same way for each. A site whose
5
+ // framework has no module here does not open (site.mjs: openSite, code
6
+ // `framework_unsupported`, exit 2).
7
+ //
8
+ // A framework module's default export:
9
+ //
10
+ // id detection's id for it (detect.ts FRAMEWORKS): "astro"
11
+ // name as people say it: "Astro"
12
+ // configFiles its config files, relative to the site, in the order they
13
+ // are looked for: `site.configFile` is the first one there
14
+ // agents the file in this package with the steps init leaves,
15
+ // relative to the package ("agents/astro.md"); AGENTS.md
16
+ // points to it, init names it, doctor's steps cite it
17
+ // comments whether init offers comments on the live site (--comments)
18
+ // build the production build doctor and uninstall make (build.mjs):
19
+ // { bin, args(outDir), env, output }, `output` the folders a
20
+ // build may write its pages to instead of outDir
21
+ // packages({ comments })
22
+ // what init installs, pinned (versions.mjs), in its order
23
+ // init(site, { comments, project })
24
+ // init's plan for the files besides package.json: an array of
25
+ // { file, action: "created" | "changed", changes, text }, or a
26
+ // CouldNotRun. Writes nothing; init writes them, in order
27
+ // linked(site) the Unbase project the site's code is linked to, or null
28
+ // uninstall(site)
29
+ // uninstall's plan: { packages: names, files: [{ file, action,
30
+ // changes, text }], remove: paths }. Writes nothing
31
+ // doctor(site, { build })
32
+ // the features, each { id, name, state, checks } (feature.mjs)
33
+ // normalise optional: a built page as uninstall compares it, before the
34
+ // shared normalising (compare.mjs), for what differs between
35
+ // two builds of this framework (Next.js: its scripts and hashes)
36
+ //
37
+ // Adding a framework: its module in this folder, one line in FRAMEWORKS, and
38
+ // its agents file (shipped: package.json `files` has agents/). Unbase reads
39
+ // the same list from supabase/functions/_shared/framework-packages.ts, held
40
+ // equal to this one by test/frameworks.test.mjs.
41
+ // ============================================================================
42
+
43
+ import astro from "./astro.mjs";
44
+ import viteReact from "./vite-react.mjs";
45
+ import next from "./next.mjs";
46
+
47
+ export const FRAMEWORKS = [astro, viteReact, next];
48
+
49
+ /** The module for detection's framework id, or null. */
50
+ export const frameworkOf = (id) => FRAMEWORKS.find((f) => f.id === id) ?? null;