@unbase-app/cli 0.2.0 → 0.4.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/args.mjs CHANGED
@@ -2,7 +2,8 @@
2
2
  // Flags. Every choice is a flag (`--comments` / `--no-comments`, `--yes`):
3
3
  // without a terminal a missing one is an error, never a question. Unknown
4
4
  // flags are an error too, so a typo in a script fails instead of being
5
- // ignored.
5
+ // ignored. Only `unbase page` takes arguments besides its flags: what to do
6
+ // and the addresses (`unbase page rename /about /about-us`).
6
7
  // ============================================================================
7
8
 
8
9
  import { CouldNotRun } from "./errors.mjs";
@@ -12,20 +13,30 @@ export const FLAGS = {
12
13
  init: { comments: "bool", "no-comments": "bool", project: "value", pointer: "optional-value", "no-pointer": "bool", "no-install": "bool", tarballs: "value", yes: "bool", json: "bool", dir: "value" },
13
14
  doctor: { json: "bool", "no-build": "bool", dir: "value" },
14
15
  uninstall: { yes: "bool", json: "bool", "no-build": "bool", "no-install": "bool", dir: "value" },
16
+ page: { name: "value", "not-live": "bool", redirect: "value", "not-found": "bool", "dry-run": "bool", json: "bool", dir: "value" },
15
17
  };
16
18
 
17
- /** @returns {{ command: string | null, flags: Record<string, string | true> }} */
19
+ /** Commands that take arguments besides their flags. */
20
+ const ARGUMENTS = new Set(["page"]);
21
+
22
+ /** @returns {{ command: string | null, flags: Record<string, string | true>, args: string[] }} */
18
23
  export function parseArgs(argv) {
19
24
  const [command, ...rest] = argv;
20
- if (!command || command === "--help" || command === "-h" || command === "help") return { command: "help", flags: {} };
21
- if (command === "--version" || command === "-v") return { command: "version", flags: {} };
25
+ if (!command || command === "--help" || command === "-h" || command === "help") return { command: "help", flags: {}, args: [] };
26
+ if (command === "--version" || command === "-v") return { command: "version", flags: {}, args: [] };
22
27
  const known = FLAGS[command];
23
- if (!known) throw new CouldNotRun("usage", `Unknown command "${command}". Commands: init, doctor, uninstall.`);
28
+ if (!known) throw new CouldNotRun("usage", `Unknown command "${command}". Commands: ${Object.keys(FLAGS).join(", ")}.`);
24
29
  /** @type {Record<string, string | true>} */
25
30
  const flags = {};
31
+ /** @type {string[]} */
32
+ const args = [];
26
33
  for (let i = 0; i < rest.length; i++) {
27
34
  const arg = rest[i];
28
- if (!arg.startsWith("--")) throw new CouldNotRun("usage", `Unexpected argument "${arg}" for ${command}.`);
35
+ if (!arg.startsWith("--")) {
36
+ if (!ARGUMENTS.has(command)) throw new CouldNotRun("usage", `Unexpected argument "${arg}" for ${command}.`);
37
+ args.push(arg);
38
+ continue;
39
+ }
29
40
  const [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
30
41
  const kind = known[name];
31
42
  if (!kind) throw new CouldNotRun("usage", `Unknown flag --${name} for ${command}. Flags: ${Object.keys(known).map((f) => `--${f}`).join(", ")}.`);
@@ -45,5 +56,6 @@ export function parseArgs(argv) {
45
56
  }
46
57
  if (flags.comments && flags["no-comments"]) throw new CouldNotRun("usage", "Use --comments or --no-comments, not both.");
47
58
  if (flags.pointer && flags["no-pointer"]) throw new CouldNotRun("usage", "Use --pointer or --no-pointer, not both.");
48
- return { command, flags };
59
+ if (flags.redirect !== undefined && flags["not-found"]) throw new CouldNotRun("usage", "Use --redirect or --not-found, not both.");
60
+ return { command, flags, args };
49
61
  }
package/lib/compare.mjs CHANGED
@@ -1,24 +1,28 @@
1
1
  // ============================================================================
2
2
  // Two builds' pages, compared: what a visitor gets, before and after
3
3
  // uninstall. What only the packages put in a page is taken out first (comment
4
- // mode's markers and its loader scripts), and what differs between any two
5
- // builds (asset hashes, Astro's scope and island ids, white space, comments).
6
- // Anything else that differs is a difference.
4
+ // mode's markers and its loader scripts, and the analytics beacon), and what
5
+ // differs between any two builds (asset hashes, Astro's scope and island ids,
6
+ // white space, comments). Anything else that differs is a difference.
7
7
  // ============================================================================
8
8
 
9
9
  /** comment-modus's loader and the head script that keeps its toolbar across pages carry its name. */
10
- const OURS = /comment-modus/;
10
+ const COMMENTS = /comment-modus/;
11
+ /** The analytics beacon (@unbase-app/analytics) carries the flag it sets on the window. */
12
+ const BEACON = /__unbaseAnalytics/;
13
+ /** Every script of ours. */
14
+ const OURS = /comment-modus|__unbaseAnalytics/;
11
15
 
12
16
  /**
13
- * The page without comment mode's scripts: inline ones that carry its name always; a script file
14
- * that carries it only with `files` (Astro may bundle the loader with the site's own page scripts
15
- * into one file, which then stays after uninstall).
17
+ * The page without our scripts (`ours`: by default all of them): inline ones that carry the mark
18
+ * always; a script file that carries it only with `files` (Astro may bundle the loader and the
19
+ * beacon with the site's own page scripts into one file, which then stays after uninstall).
16
20
  */
17
- function withoutOurScripts(html, file, files = true) {
21
+ function withoutOurScripts(html, file, files = true, ours = OURS) {
18
22
  return html.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g, (whole, attrs, body) => {
19
- if (OURS.test(body)) return "";
23
+ if (ours.test(body)) return "";
20
24
  const src = /\bsrc=["']?([^"'\s>]+)/.exec(attrs)?.[1];
21
- if (files && src && src.startsWith("/") && OURS.test(file(src.replace(/^\/+/, "").replace(/[?#].*$/, "")) ?? "")) return "";
25
+ if (files && src && src.startsWith("/") && ours.test(file(src.replace(/^\/+/, "").replace(/[?#].*$/, "")) ?? "")) return "";
22
26
  return whole;
23
27
  });
24
28
  }
@@ -93,4 +97,7 @@ export function comparePages(before, after, again = null, pre = (html) => html)
93
97
  }
94
98
 
95
99
  /** Whether a page carries comment mode's loader (inline, or in a script file it loads). */
96
- export const hasOurScript = (html, file = () => null) => withoutOurScripts(html, file) !== html;
100
+ export const hasOurScript = (html, file = () => null) => withoutOurScripts(html, file, true, COMMENTS) !== html;
101
+
102
+ /** Whether a page carries the analytics beacon (inline, or in a script file it loads). */
103
+ export const hasBeacon = (html, file = () => null) => withoutOurScripts(html, file, true, BEACON) !== html;
@@ -159,16 +159,17 @@ function projectOf(call) {
159
159
  return v?.type === "StringLiteral" ? v.value : null;
160
160
  }
161
161
 
162
- /** unbase()'s `comments`: true (absent, or true), false, or null when the config does not say it literally. */
163
- function commentsIn(call) {
162
+ /** unbase()'s boolean option `name` (`comments`, `analytics`): true (absent, or true), false, or null when the config does not say it literally. */
163
+ function booleanIn(call, name = "comments") {
164
164
  const opts = unwrap(call?.arguments[0]);
165
165
  if (!opts) return true;
166
166
  if (opts.type !== "ObjectExpression") return null;
167
- const prop = propNamed(opts, "comments");
167
+ const prop = propNamed(opts, name);
168
168
  if (!prop) return spreads(opts) ? null : true;
169
169
  const v = unwrap(prop.value);
170
170
  return v.type === "BooleanLiteral" ? v.value : null;
171
171
  }
172
+ const commentsIn = (call) => booleanIn(call, "comments");
172
173
 
173
174
  /**
174
175
  * What a config holds of Unbase's packages, read from its tree: for doctor, and for init and
@@ -213,6 +214,10 @@ export function inspectConfig(code, file) {
213
214
  },
214
215
  /** unbase()'s `comments`: true, false (comments: false), null when not literal; null without unbase(). */
215
216
  unbaseComments,
217
+ /** unbase()'s `analytics`: true, false (analytics: false), null when not literal; null without unbase(). */
218
+ unbaseAnalytics: unbase ? booleanIn(callOf(unbase.el), "analytics") : null,
219
+ /** A literal `project` in unbase(), with or without comment mode; null otherwise. */
220
+ unbaseProject: unbase ? projectOf(callOf(unbase.el)) : null,
216
221
  /** comment mode's componentMarker: "always", "preview", false; null when unreadable or without comment mode. */
217
222
  markers: comments ? markersOf(callOf(comments.el)) : null,
218
223
  /** comment mode's own literal project, set in the config itself; null when it comes from comment-modus.json or a variable. */
@@ -4,14 +4,15 @@
4
4
  // astro.config (config-edit, through the syntax tree) and comment-modus.json;
5
5
  // on a site from before K5 it moves the pair (comment-modus and the kit)
6
6
  // across to it (`replaced`). uninstall takes either out with
7
- // unbase.pages.json and the content schemas; doctor reads three features
7
+ // unbase.pages.json and the content schemas; doctor reads four features
8
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.
9
+ // list_pages, the kit's core and the CSP reader) on the working tree and one
10
+ // production build. The steps init leaves: agents/astro.md.
11
11
  // ============================================================================
12
12
 
13
13
  import { existsSync, readdirSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
+ import { analyticsFeature } from "../analytics.mjs";
15
16
  import { tailOf } from "../build.mjs";
16
17
  import { hasOurScript } from "../compare.mjs";
17
18
  import { addToConfig, inspectConfig, removeFromConfig } from "../config-edit.mjs";
@@ -32,6 +33,7 @@ const STEPS = {
32
33
  siteSettings: `${AGENTS} step 3: Site settings`,
33
34
  schemas: `${AGENTS} step 4: Schemas`,
34
35
  drafts: `${AGENTS} step 5: Draft pages`,
36
+ analytics: `${AGENTS} step 6: Analytics`,
35
37
  };
36
38
  const SITE_FIELDS = ["naam", "beschrijving", "taal", "favicon", "faviconDonker", "ogImage", "googleAnalytics"];
37
39
  const SOURCE = /^src\/.*\.(astro|ts|tsx|js|jsx|mjs|mts|mdx)$/;
@@ -60,8 +62,8 @@ export function readLink(site) {
60
62
 
61
63
  // ── init ───────────────────────────────────────────────────────────────────
62
64
 
63
- /** init's plan for astro.config and comment-modus.json. */
64
- function planInit(site, { comments, project }) {
65
+ /** init's plan for astro.config and comment-modus.json (for comment mode, or for analytics alone with --no-comments). */
66
+ function planInit(site, { comments, project, analytics = true }) {
65
67
  if (!site.configFile) throw new CouldNotRun("no_config", "No astro.config.(mjs|ts|js|mts) in the site's folder.");
66
68
  const configCode = site.text(site.configFile);
67
69
  const before = inspectConfig(configCode, site.configFile);
@@ -96,6 +98,9 @@ function planInit(site, { comments, project }) {
96
98
  if (project && data.project !== project) link = { action: "changed", data: { ...data, project }, indent, changes: [`project: ${JSON.stringify(data.project ?? null)} → "${project}"`] };
97
99
  else if (!("project" in data) && usesLink) link = { action: "changed", data: { project: null, ...data }, indent, changes: ["project: null"] };
98
100
  }
101
+ } else if (analytics) {
102
+ // Without comment mode the link is analytics': unbase() reads comment-modus.json itself.
103
+ link = linkFor(site, project);
99
104
  }
100
105
  return [
101
106
  ...(config.changes.length ? [{ file: site.configFile, action: "changed", changes: config.changes, text: config.code }] : []),
@@ -103,6 +108,33 @@ function planInit(site, { comments, project }) {
103
108
  ];
104
109
  }
105
110
 
111
+ /** comment-modus.json for analytics alone: made with the project (or null), the project changed, else nothing. */
112
+ function linkFor(site, project) {
113
+ const text = site.text(LINK_FILE);
114
+ if (text === null) return { action: "created", data: { project }, indent: " ", changes: [project ? `project: "${project}"` : "project: null (Unbase fills it in when the site is connected)"] };
115
+ let data;
116
+ try {
117
+ data = JSON.parse(text);
118
+ } catch {
119
+ throw new CouldNotRun("link_file", `${LINK_FILE} is not valid JSON.`, { file: LINK_FILE });
120
+ }
121
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new CouldNotRun("link_file", `${LINK_FILE} is not a JSON object.`, { file: LINK_FILE });
122
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
123
+ if (project && data.project !== project) return { action: "changed", data: { ...data, project }, indent, changes: [`project: ${JSON.stringify(data.project ?? null)} → "${project}"`] };
124
+ if (!("project" in data)) return { action: "changed", data: { project: null, ...data }, indent, changes: ["project: null"] };
125
+ return null;
126
+ }
127
+
128
+ /** unbase()'s `analytics` in the config as it is: false only when it says so literally. */
129
+ function analyticsOption(site) {
130
+ if (!site.configFile) return true;
131
+ try {
132
+ return inspectConfig(site.text(site.configFile), site.configFile).unbaseAnalytics !== false;
133
+ } catch {
134
+ return true;
135
+ }
136
+ }
137
+
106
138
  // ── uninstall ──────────────────────────────────────────────────────────────
107
139
 
108
140
  // ── The move (K5) ──────────────────────────────────────────────────────────
@@ -457,6 +489,21 @@ async function doctorFeatures(site, { build }) {
457
489
  }
458
490
  features.push({ id: "page-management", name: "Page management", state: featureState(checks), checks });
459
491
  }
492
+
493
+ // ── Analytics ─────────────────────────────────────────────────────────────
494
+ features.push(
495
+ analyticsFeature(site, {
496
+ umbrella: ASTRO,
497
+ version: one ? (installedVersion(site, ASTRO.name) ?? deps[ASTRO.name]) : null,
498
+ configured: !!config?.has.unbase,
499
+ option: config ? config.unbaseAnalytics : null,
500
+ project: readLink(site) ?? config?.unbaseProject ?? null,
501
+ before: !one && [COMMENT_MODUS.name, BEFORE.pages].some((n) => deps[n] !== undefined),
502
+ step: STEPS.analytics,
503
+ install: STEPS.install,
504
+ config: site.configFile ?? "astro.config.mjs",
505
+ }),
506
+ );
460
507
  return features;
461
508
  }
462
509
 
@@ -474,6 +521,9 @@ export default {
474
521
  configFiles: core.kitFiles("astro").filter((f) => f !== "package.json"),
475
522
  agents: AGENTS,
476
523
  comments: true,
524
+ /** comment-modus.json links analytics without comment mode too: unbase() reads it itself. */
525
+ analyticsLink: true,
526
+ analyticsOption,
477
527
  build: { bin: "astro", args: (outDir) => ["build", "--outDir", outDir], env: { ASTRO_TELEMETRY_DISABLED: "1" }, output: ADAPTER_OUTPUT },
478
528
  packages: () => [ASTRO, SELF],
479
529
  init: planInit,
@@ -15,6 +15,13 @@
15
15
  // relative to the package ("agents/astro.md"); AGENTS.md
16
16
  // points to it, init names it, doctor's steps cite it
17
17
  // comments whether init offers comments on the live site (--comments)
18
+ // analyticsLink
19
+ // whether comment-modus.json links analytics without comment
20
+ // mode (the package reads the file itself): init writes it
21
+ // with --no-comments too, and takes --project then
22
+ // analyticsOption(site)
23
+ // the config's `analytics` option as it is: false only when it
24
+ // says so literally; init leaves the CSP alone then
18
25
  // build the production build doctor and uninstall make (build.mjs):
19
26
  // { bin, args(outDir), env, output }, `output` the folders a
20
27
  // build may write its pages to instead of outDir
@@ -4,14 +4,17 @@
4
4
  // (next-config.mjs, through the syntax tree), writes comment-modus.json, and
5
5
  // on a Next.js before 16.3 imports the comments' loader in
6
6
  // instrumentation-client; uninstall takes them out with unbase.pages.json;
7
- // doctor reads three features with Unbase's own readers (lib/readers.mjs:
8
- // detect, read_settings on the pages' metadata, list_pages and the kit's
9
- // core) on the working tree and one production build (`next build`, into the
10
- // site's own .next). The steps init leaves: agents/next.md.
7
+ // doctor reads four features with Unbase's own readers (lib/readers.mjs:
8
+ // detect, read_settings on the pages' metadata, list_pages, the kit's core
9
+ // and the CSP reader) on the working tree and one production build (`next
10
+ // build`, into the site's own .next). The steps init leaves: agents/next.md.
11
+ // Analytics comes with the comments' client module, so it needs the same
12
+ // link: on Next.js, --no-comments leaves both out.
11
13
  // ============================================================================
12
14
 
13
15
  import { existsSync, readdirSync, readFileSync } from "node:fs";
14
16
  import { join } from "node:path";
17
+ import { analyticsFeature } from "../analytics.mjs";
15
18
  import { tailOf } from "../build.mjs";
16
19
  import { CouldNotRun } from "../errors.mjs";
17
20
  import { check, featureState } from "../feature.mjs";
@@ -29,6 +32,7 @@ const STEPS = {
29
32
  comments: `${AGENTS} step 2: Comments on the site`,
30
33
  pageSettings: `${AGENTS} step 3: Page settings`,
31
34
  drafts: `${AGENTS} step 4: Draft pages`,
35
+ analytics: `${AGENTS} step 5: Analytics`,
32
36
  };
33
37
  /** Next.js injects a package's client module from this version on (instrumentationClientInject); before, instrumentation-client imports it. */
34
38
  const INJECTS_FROM = "16.3.0";
@@ -99,6 +103,16 @@ function planInit(site, { comments, project }) {
99
103
  return plan;
100
104
  }
101
105
 
106
+ /** withUnbase's `analytics` in next.config as it is: false only when it says so literally. */
107
+ function analyticsOption(site) {
108
+ if (!site.configFile) return true;
109
+ try {
110
+ return inspectNextConfig(site.text(site.configFile), site.configFile).analytics !== false;
111
+ } catch {
112
+ return true;
113
+ }
114
+ }
115
+
102
116
  // ── uninstall ──────────────────────────────────────────────────────────────
103
117
 
104
118
  /** uninstall's plan: next.config unwrapped, the loader's import out of instrumentation-client, the package and its files. */
@@ -289,6 +303,26 @@ async function doctorFeatures(site, { build }) {
289
303
  }
290
304
  features.push({ id: "page-management", name: "Page management", state: featureState(checks), checks });
291
305
  }
306
+
307
+ // ── Analytics: with the comments' client module, so on the same link and loader ──
308
+ {
309
+ const injects = version && compareVersions(version, INJECTS_FROM) >= 0;
310
+ const old = version && compareVersions(version, INSTRUMENTATION_FROM) >= 0 && !injects;
311
+ features.push(
312
+ analyticsFeature(site, {
313
+ umbrella: NEXT,
314
+ version: listed ? (have ?? deps[NEXT.name]) : null,
315
+ configured: wrapped,
316
+ option: wrapped ? config.analytics : null,
317
+ project: readLink(site) || null,
318
+ before: false,
319
+ step: STEPS.analytics,
320
+ install: STEPS.install,
321
+ config: site.configFile ?? "next.config.ts",
322
+ loader: old ? importsLoader(text(instrumentationFile(site))) : null,
323
+ }),
324
+ );
325
+ }
292
326
  return features;
293
327
  }
294
328
 
@@ -310,6 +344,9 @@ export default {
310
344
  configFiles: core.kitFiles("next").filter((f) => f !== "package.json"),
311
345
  agents: AGENTS,
312
346
  comments: true,
347
+ /** Analytics comes with the comments' client module: comment-modus.json links both, or neither. */
348
+ analyticsLink: false,
349
+ analyticsOption,
313
350
  // next build has no output folder of its own: it writes the site's .next, where its pages are read.
314
351
  build: { bin: "next", args: () => ["build"], env: { NEXT_TELEMETRY_DISABLED: "1" }, output: [`${DIST}/server/app`, `${DIST}/server/pages`] },
315
352
  packages: () => [NEXT, SELF],
@@ -4,10 +4,10 @@
4
4
  // package, @unbase-app/vite (kit/vite): the draft-pages kit and comment
5
5
  // mode's loader in one plugin. init adds it, its line in vite.config
6
6
  // (vite-config.mjs, through the syntax tree) and comment-modus.json;
7
- // uninstall takes them out with unbase.pages.json; doctor reads three
7
+ // uninstall takes them out with unbase.pages.json; doctor reads four
8
8
  // features 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/vite-react.md.
9
+ // list_pages, the kit's core and the CSP reader) on the working tree and one
10
+ // production build. The steps init leaves: agents/vite-react.md.
11
11
  //
12
12
  // React Router's framework mode (@react-router/dev, detection's
13
13
  // "react-router") is not this: it renders its own document and reads its
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { readFileSync } from "node:fs";
18
18
  import { join } from "node:path";
19
+ import { analyticsFeature } from "../analytics.mjs";
19
20
  import { tailOf } from "../build.mjs";
20
21
  import { hasOurScript } from "../compare.mjs";
21
22
  import { CouldNotRun } from "../errors.mjs";
@@ -32,6 +33,7 @@ const STEPS = {
32
33
  settings: `${AGENTS} step 2: Site settings`,
33
34
  drafts: `${AGENTS} step 3: Draft pages`,
34
35
  comments: `${AGENTS} step 4: Comments on the site`,
36
+ analytics: `${AGENTS} step 5: Analytics`,
35
37
  };
36
38
  /** The settings index.html can hold, as read_settings names them. */
37
39
  const SITE_SETTINGS = { name: "<title>", description: "meta description", language: "<html lang>", faviconLight: "icon", faviconDark: "dark icon", socialImage: "og:image" };
@@ -51,12 +53,12 @@ export function readLink(site) {
51
53
 
52
54
  // ── init ───────────────────────────────────────────────────────────────────
53
55
 
54
- /** init's plan for vite.config and comment-modus.json. */
55
- function planInit(site, { comments, project }) {
56
+ /** init's plan for vite.config and comment-modus.json (which links comment mode and analytics alike). */
57
+ function planInit(site, { comments, project, analytics = true }) {
56
58
  if (!site.configFile) throw new CouldNotRun("no_config", "No vite.config.(ts|js|mjs|mts) in the site's folder.");
57
59
  const config = addToViteConfig(site.text(site.configFile), site.configFile, { comments });
58
60
  let link = null;
59
- if (comments) {
61
+ if (comments || analytics) {
60
62
  const text = site.text(LINK_FILE);
61
63
  if (text === null) link = { action: "created", data: { project }, indent: " ", changes: [project ? `project: "${project}"` : "project: null (Unbase fills it in when the site is connected)"] };
62
64
  else {
@@ -93,6 +95,16 @@ function planReplaced(site, planned) {
93
95
  return { remove, keep: [], by: VITE.name };
94
96
  }
95
97
 
98
+ /** unbase()'s `analytics` in the config as it is: false only when it says so literally. */
99
+ function analyticsOption(site) {
100
+ if (!site.configFile) return true;
101
+ try {
102
+ return inspectViteConfig(site.text(site.configFile), site.configFile).options?.analytics !== false;
103
+ } catch {
104
+ return true;
105
+ }
106
+ }
107
+
96
108
  /** What of Unbase the site has now, for init's defaults: null without any of it; else whether comment mode is on. */
97
109
  function currentOf(site) {
98
110
  const deps = depsOf(site.pkg);
@@ -278,6 +290,21 @@ async function doctorFeatures(site, { build }) {
278
290
  checks.push(check("page-settings", "info", "No page settings: every route of a single-page app is index.html, so a route has no <head> of its own to set."));
279
291
  features.push({ id: "page-management", name: "Page management", state: featureState(checks), checks });
280
292
  }
293
+
294
+ // ── Analytics ─────────────────────────────────────────────────────────────
295
+ features.push(
296
+ analyticsFeature(site, {
297
+ umbrella: VITE,
298
+ version: listed ? version : null,
299
+ configured: !!config?.has.unbase,
300
+ option: config?.has.unbase ? (config.options ? config.options.analytics : null) : null,
301
+ project: readLink(site),
302
+ before: !listed && [PAGES.name, BEFORE.pages].some((n) => deps[n] !== undefined),
303
+ step: STEPS.analytics,
304
+ install: STEPS.install,
305
+ config: file,
306
+ }),
307
+ );
281
308
  return features;
282
309
  }
283
310
 
@@ -288,6 +315,9 @@ export default {
288
315
  configFiles: core.kitFiles("vite-react").filter((f) => f !== "package.json"),
289
316
  agents: AGENTS,
290
317
  comments: true,
318
+ /** comment-modus.json links analytics without comment mode too: the plugin reads it itself. */
319
+ analyticsLink: true,
320
+ analyticsOption,
291
321
  build: { bin: "vite", args: (outDir) => ["build", "--outDir", outDir, "--emptyOutDir"], env: {}, output: [] },
292
322
  packages: () => [VITE, SELF],
293
323
  init: planInit,
package/lib/init.mjs CHANGED
@@ -11,10 +11,17 @@
11
11
  // once the new one is in, and the pointer line moves to the CLI's new name.
12
12
  // Running init again is also how a site updates; with --yes a site that has
13
13
  // Unbase keeps its choice of comments.
14
+ //
15
+ // Analytics comes with the framework's package, on unless its config says
16
+ // `analytics: false`: init adds nothing for it but the collector's origin in
17
+ // the site's CSP, where it can edit it safely (lib/analytics.mjs: vercel.json,
18
+ // public/_headers), and names the CSPs it cannot edit. On Astro and Vite
19
+ // comment-modus.json links analytics too, so --no-comments still writes it.
14
20
  // ============================================================================
15
21
 
16
22
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
17
23
  import { join } from "node:path";
24
+ import { COLLECTOR_ORIGIN, cspElsewhereIn, elsewhereSteps, planCsp } from "./analytics.mjs";
18
25
  import { CouldNotRun, PASSED } from "./errors.mjs";
19
26
  import { addPackages, dropDependencies, installAsListed, lockfileOf, packageManagerOf, tarballFor, writeDependencies } from "./pm.mjs";
20
27
  import { installedVersion, openSite } from "./site.mjs";
@@ -68,7 +75,12 @@ export async function init(flags, io) {
68
75
  // --yes: a site that has Unbase keeps what it chose; a new one gets comments.
69
76
  const now = fw.current?.(site) ?? null;
70
77
  const comments = fw.comments && (await choose(io, flags, { yes: "comments", no: "no-comments", question: "Add comments on the live site (?comment, comment-modus)?", fallback: now ? now.comments : true }));
71
- if (!comments && project) throw new CouldNotRun("usage", "--project links comments; it cannot go with --no-comments.");
78
+ // Analytics: on unless the site's config already says analytics: false (init never writes it).
79
+ const analytics = fw.analyticsOption ? fw.analyticsOption(site) : true;
80
+ /** comment-modus.json links what is on: comment mode, or on Astro and Vite analytics alone. */
81
+ const links = comments || (analytics && !!fw.analyticsLink);
82
+ if (!links && project)
83
+ throw new CouldNotRun("usage", fw.analyticsLink ? "--project links comments and analytics; with --no-comments and analytics: false there is nothing to link." : `--project links comments; it cannot go with --no-comments (on ${fw.name}, analytics comes with comments).`);
72
84
  const pointerWanted = await choose(io, flags, { yes: "pointer", no: "no-pointer", question: "Add a line to AGENTS.md or CLAUDE.md pointing your coding agent at Unbase's conventions?", fallback: false });
73
85
  let pointerFile = null;
74
86
  if (pointerWanted) {
@@ -78,7 +90,10 @@ export async function init(flags, io) {
78
90
 
79
91
  // ── Plan ──────────────────────────────────────────────────────────────────
80
92
  // The framework's own files (on Astro: astro.config, comment-modus.json), planned: nothing is written yet.
81
- const own = fw.init(site, { comments, project });
93
+ const own = fw.init(site, { comments, project, analytics });
94
+ // The collector's origin in the site's CSP, where the CLI can edit it; the other places named.
95
+ const csp = analytics ? planCsp(site, { add: true }) : { files: [], invalid: [] };
96
+ const elsewhere = analytics ? cspElsewhereIn(site) : [];
82
97
  // What the framework's package replaced (K5): out once it is in; what the site keeps, moved to the version it brings.
83
98
  const replaced = fw.replaced?.(site, own) ?? { remove: [], keep: [], by: null };
84
99
  const packages = [...fw.packages({ comments }), ...replaced.keep].map((p) => planPackage(site, p));
@@ -127,7 +142,7 @@ export async function init(flags, io) {
127
142
  files.push({ file: lockfileOf(site, pm), action: "changed", changes: [`${pm} installed ${toAdd.length} package(s)`] });
128
143
  }
129
144
  }
130
- for (const f of own) {
145
+ for (const f of [...own, ...csp.files]) {
131
146
  writeFileSync(join(site.root, f.file), f.text);
132
147
  files.push({ file: f.file, action: f.action, changes: f.changes });
133
148
  }
@@ -136,7 +151,7 @@ export async function init(flags, io) {
136
151
  files.push({ file: p.file, action: p.action, changes: p.changes });
137
152
  }
138
153
 
139
- const linked = comments ? fw.linked(site) : null;
154
+ const linked = links ? fw.linked(site) : null;
140
155
  const agents = `node_modules/${SELF.name}/${fw.agents}`;
141
156
  return {
142
157
  command: "init",
@@ -149,7 +164,11 @@ export async function init(flags, io) {
149
164
  packageManager: pm,
150
165
  installed: !flags["no-install"],
151
166
  comments,
167
+ /** Analytics comes with the package, on unless the config says analytics: false. */
168
+ analytics,
152
169
  project: linked,
170
+ /** The CSP files init allowed the collector in, the ones it could not read, and the other places that may set a CSP. */
171
+ csp: { files: csp.files.map((f) => f.file), invalid: csp.invalid, elsewhere },
153
172
  changed: files.length > 0,
154
173
  packages: [
155
174
  ...packages.map(({ name, version, dev, action, have, from, to, note }) => ({ name, version, dev, action, ...(from ? { from, to } : {}), ...(have ? { have } : {}), ...(note ? { note } : {}) })),
@@ -158,6 +177,8 @@ export async function init(flags, io) {
158
177
  files,
159
178
  next: [
160
179
  ...(flags["no-install"] && toAdd.length ? [`Install the packages: ${pm} install`] : []),
180
+ ...elsewhereSteps(elsewhere),
181
+ ...csp.invalid.map((f) => `${f} cannot be read, so the CLI did not edit it: allow ${COLLECTOR_ORIGIN} in its Content-Security-Policy's connect-src.`),
161
182
  `Do the steps in ${agents} that this site still needs.`,
162
183
  "Run npx @unbase-app/cli doctor until it passes; then commit on a new branch.",
163
184
  ],
@@ -68,7 +68,18 @@ export function inspectNextConfig(code, file) {
68
68
  if (value.type === "ClassDeclaration") throw unsafe(file, "its `export default` is a class");
69
69
  const call = unwrap(value);
70
70
  const wrapped = call?.type === "CallExpression" && call.callee.type === "Identifier" && names.has(call.callee.name);
71
- return { ast, cjs: !exp, value, wrapped, call: wrapped ? call : null, imports, required, names };
71
+ return { ast, cjs: !exp, value, wrapped, call: wrapped ? call : null, imports, required, names, analytics: wrapped ? analyticsOf(call) : null };
72
+ }
73
+
74
+ /** withUnbase(config, { analytics })'s `analytics`: true (absent, or true), false, or null when not literal. */
75
+ function analyticsOf(call) {
76
+ const opts = unwrap(call.arguments[1]);
77
+ if (!opts) return true;
78
+ if (opts.type !== "ObjectExpression") return null;
79
+ const prop = opts.properties.find((p) => p.type === "ObjectProperty" && !p.computed && (p.key.name ?? p.key.value) === "analytics");
80
+ if (!prop) return opts.properties.some((p) => p.type === "SpreadElement") ? null : true;
81
+ const v = unwrap(prop.value);
82
+ return v.type === "BooleanLiteral" ? v.value : null;
72
83
  }
73
84
 
74
85
  /** Where a new import (or require) goes: after the last one at the top, else at the start. */