@unbase-app/cli 0.2.0 → 0.3.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.
@@ -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. */
package/lib/readers.mjs CHANGED
@@ -7,6 +7,7 @@
7
7
  // readSettings supabase/functions/unbase-projects/settings.ts (read_settings)
8
8
  // registryOf supabase/functions/unbase-projects/pages.ts (list_pages)
9
9
  // core supabase/functions/_shared/pages-core.mjs (= kit/pages/core.mjs)
10
+ // csp supabase/functions/_shared/csp.ts (analytics' collector in a CSP)
10
11
  // ============================================================================
11
12
  var __defProp = Object.defineProperty;
12
13
  var __export = (target, all) => {
@@ -184,6 +185,7 @@ var frameworkPackage = (id) => FRAMEWORK_PACKAGES.find((f) => f.id === id) ?? nu
184
185
 
185
186
  // supabase/functions/unbase-projects/detect.ts
186
187
  var ADAPTERS = [astro];
188
+ var HTML = { id: "html", name: "HTML", version: null, major: null };
187
189
  var FRAMEWORKS = [
188
190
  { id: "astro", name: "Astro", dep: "astro", public: "PUBLIC_" },
189
191
  { id: "next", name: "Next.js", dep: "next", public: "NEXT_PUBLIC_" },
@@ -256,8 +258,8 @@ function packageManager(repo, appPath, root) {
256
258
  const found = LOCKFILES.find(([file]) => repo.paths.includes(join(folder, file)));
257
259
  if (found) return found[1];
258
260
  }
259
- const field = root?.pkg.packageManager;
260
- return typeof field === "string" ? field.split("@")[0] || null : null;
261
+ const field2 = root?.pkg.packageManager;
262
+ return typeof field2 === "string" ? field2.split("@")[0] || null : null;
261
263
  }
262
264
  function cmsOf(repo, app, root) {
263
265
  const deps = { ...root?.deps ?? {}, ...app.deps };
@@ -393,7 +395,7 @@ async function detect(repo, branch, truncated, appPath) {
393
395
  } else {
394
396
  return empty;
395
397
  }
396
- if (!chosen) return { ...empty, app_path: "" };
398
+ if (!chosen) return { ...empty, app_path: "", framework: !all.length && repo.paths.includes("index.html") ? HTML : null };
397
399
  const fw = frameworkOf(chosen.deps);
398
400
  const adapter = fw ? ADAPTERS.find((a) => a.framework === fw.id) ?? null : null;
399
401
  const found = adapter ? await adapter.detect(repo, chosen) : { text: null, site: null, project: null };
@@ -419,7 +421,7 @@ async function detect(repo, branch, truncated, appPath) {
419
421
  }
420
422
 
421
423
  // supabase/functions/_shared/html-head.ts
422
- var headPointer = (field) => `/head/${field}`;
424
+ var headPointer = (field2) => `/head/${field2}`;
423
425
  var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
424
426
  function decodeValue(raw) {
425
427
  return raw.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&([a-z]+);/gi, (m, n) => ENTITIES[n.toLowerCase()] ?? m).replace(/\s+/g, " ").trim();
@@ -525,10 +527,10 @@ function readHead(html) {
525
527
  if (image) out.image = image;
526
528
  const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
527
529
  const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
528
- for (const [field, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
530
+ for (const [field2, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
529
531
  const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
530
532
  const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
531
- if (href && href.value.trim() && plain(href.value)) out[field] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
533
+ if (href && href.value.trim() && plain(href.value)) out[field2] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
532
534
  }
533
535
  return out;
534
536
  }
@@ -1694,12 +1696,12 @@ function valueOf(v, kind) {
1694
1696
  }
1695
1697
  function fieldsOf(names, data, allowed, file, base) {
1696
1698
  const fields = {};
1697
- for (const [field, { name, kind }] of Object.entries(names)) {
1699
+ for (const [field2, { name, kind }] of Object.entries(names)) {
1698
1700
  const value = valueOf(data?.[name], kind);
1699
1701
  const there = data?.[name] !== void 0;
1700
1702
  if (there && value === null) continue;
1701
1703
  if (!there && !allowed[name]) continue;
1702
- fields[field] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
1704
+ fields[field2] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
1703
1705
  }
1704
1706
  return fields;
1705
1707
  }
@@ -1717,9 +1719,9 @@ async function viteSettings(repo, appPath) {
1717
1719
  if (text === null) return null;
1718
1720
  const head = readHead(text);
1719
1721
  const site = {};
1720
- for (const [field, at2, kind] of HEAD_SETTINGS) {
1722
+ for (const [field2, at2, kind] of HEAD_SETTINGS) {
1721
1723
  const found = head[at2];
1722
- if (found) site[field] = { file: VITE_DOCUMENT, pointer: headPointer(at2), kind, exists: true, value: found.value };
1724
+ if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at2), kind, exists: true, value: found.value };
1723
1725
  }
1724
1726
  return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
1725
1727
  }
@@ -1755,7 +1757,7 @@ async function readSettings(repo, appPath, framework = null) {
1755
1757
  pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
1756
1758
  });
1757
1759
  const dir = files[0] ? files[0].slice(appPath ? appPath.length + 1 : 0).replace(/\/[^/]+$/, "") : `${CONTENT}/${collection}`;
1758
- const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field, { name, kind }]) => ({ field, pointer: `/seo/${name}`, kind }));
1760
+ const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
1759
1761
  routes = { dir, fields };
1760
1762
  }
1761
1763
  const siteCollection = [...schemas].find(([, s]) => s["x-instellingen"] === "site");
@@ -1909,8 +1911,226 @@ function registryOf(input) {
1909
1911
  truncated
1910
1912
  };
1911
1913
  }
1914
+
1915
+ // supabase/functions/_shared/csp.ts
1916
+ var csp_exports = {};
1917
+ __export(csp_exports, {
1918
+ COLLECTOR: () => COLLECTOR,
1919
+ COLLECTOR_ORIGIN: () => COLLECTOR_ORIGIN,
1920
+ CSP_FILES: () => CSP_FILES,
1921
+ blockingIn: () => blockingIn,
1922
+ cspElsewhere: () => cspElsewhere,
1923
+ directivesOf: () => directivesOf,
1924
+ onlyCollectorChanged: () => onlyCollectorChanged,
1925
+ policiesIn: () => policiesIn,
1926
+ policyAllows: () => policyAllows,
1927
+ withCollector: () => withCollector,
1928
+ withCollectorIn: () => withCollectorIn,
1929
+ withoutCollector: () => withoutCollector,
1930
+ withoutCollectorIn: () => withoutCollectorIn
1931
+ });
1932
+ var COLLECTOR = "https://unbase.app/e";
1933
+ var COLLECTOR_ORIGIN = new URL(COLLECTOR).origin;
1934
+ var CSP_FILES = ["vercel.json", "public/_headers"];
1935
+ var HEADER = /^content-security-policy$/i;
1936
+ function directivesOf(policy) {
1937
+ const out = [];
1938
+ let at2 = 0;
1939
+ for (const part of policy.split(";")) {
1940
+ const lead = part.length - part.trimStart().length;
1941
+ const text = part.trim();
1942
+ if (text) {
1943
+ const [name, ...sources] = text.split(/\s+/);
1944
+ out.push({ name: name.toLowerCase(), sources, start: at2 + lead, end: at2 + lead + text.length });
1945
+ }
1946
+ at2 += part.length + 1;
1947
+ }
1948
+ return out;
1949
+ }
1950
+ var governing = (ds) => ds.find((d) => d.name === "connect-src") ?? ds.find((d) => d.name === "default-src") ?? null;
1951
+ function sourceAllows(source, endpoint) {
1952
+ const s = source.toLowerCase();
1953
+ const url = new URL(endpoint);
1954
+ if (s === "*" || s === "https:") return true;
1955
+ if (s.startsWith("'")) return false;
1956
+ const m = /^(?:(https?):\/\/)?([^/:]+)(?::(\d+|\*))?(\/.*)?$/.exec(s);
1957
+ if (!m) return false;
1958
+ const [, scheme, host, port, path] = m;
1959
+ if (scheme && scheme !== "https" && scheme !== "http") return false;
1960
+ const hostOk = host === url.hostname || host.startsWith("*.") && url.hostname.endsWith(host.slice(1));
1961
+ if (!hostOk) return false;
1962
+ if (port && port !== "*" && port !== "443") return false;
1963
+ if (!path) return true;
1964
+ return path.endsWith("/") ? url.pathname.startsWith(path) : url.pathname === path;
1965
+ }
1966
+ function policyAllows(policy, endpoint = COLLECTOR) {
1967
+ const d = governing(directivesOf(policy));
1968
+ return !d || d.sources.some((s) => sourceAllows(s, endpoint));
1969
+ }
1970
+ function withCollector(policy, origin = COLLECTOR_ORIGIN) {
1971
+ if (policyAllows(policy, `${origin}${new URL(COLLECTOR).pathname}`)) return policy;
1972
+ const ds = directivesOf(policy);
1973
+ const connect = ds.find((d) => d.name === "connect-src");
1974
+ if (connect) {
1975
+ const rest = connect.sources.filter((s) => s.toLowerCase() !== "'none'");
1976
+ return `${policy.slice(0, connect.start)}${["connect-src", ...rest, origin].join(" ")}${policy.slice(connect.end)}`;
1977
+ }
1978
+ const fallback = ds.find((d) => d.name === "default-src");
1979
+ const sources = fallback.sources.filter((s) => s.toLowerCase() !== "'none'");
1980
+ const body = policy.replace(/[\s;]*$/, "");
1981
+ return `${body}; ${["connect-src", ...sources, origin].join(" ")}${policy.slice(body.length)}`;
1982
+ }
1983
+ function withoutCollector(policy, origin = COLLECTOR_ORIGIN) {
1984
+ const ds = directivesOf(policy);
1985
+ const connect = ds.find((d) => d.name === "connect-src");
1986
+ const own = (s) => s.toLowerCase().replace(/\/+$/, "") === origin.toLowerCase();
1987
+ if (!connect || !connect.sources.some(own)) return policy;
1988
+ const rest = connect.sources.filter((s) => !own(s));
1989
+ const fallback = ds.find((d) => d.name === "default-src");
1990
+ const plain2 = (list) => list.filter((s) => s.toLowerCase() !== "'none'").join(" ");
1991
+ if (fallback && plain2(rest) === plain2(fallback.sources)) {
1992
+ const before = policy.slice(0, connect.start);
1993
+ const cut = before.lastIndexOf(";");
1994
+ if (cut >= 0) return `${policy.slice(0, cut)}${policy.slice(connect.end)}`;
1995
+ return policy.slice(connect.end).replace(/^\s*;\s*/, "");
1996
+ }
1997
+ return `${policy.slice(0, connect.start)}${["connect-src", ...rest.length ? rest : ["'none'"]].join(" ")}${policy.slice(connect.end)}`;
1998
+ }
1999
+ var plainPolicy = (policy) => {
2000
+ const ds = directivesOf(withoutCollector(policy));
2001
+ return ds.map((d) => [d.name, ...d.sources].join(" ")).join("; ");
2002
+ };
2003
+ function jsonTree(text) {
2004
+ JSON.parse(text);
2005
+ let i = 0;
2006
+ const ws = () => {
2007
+ while (i < text.length && /\s/.test(text[i])) i++;
2008
+ };
2009
+ const value = () => {
2010
+ ws();
2011
+ const start = i;
2012
+ const c = text[i];
2013
+ if (c === "{" || c === "[") {
2014
+ const close = c === "{" ? "}" : "]";
2015
+ i++;
2016
+ const entries = [];
2017
+ const items = [];
2018
+ ws();
2019
+ while (text[i] !== close) {
2020
+ if (c === "{") {
2021
+ const key = value();
2022
+ ws();
2023
+ i++;
2024
+ entries.push({ key: key.value, value: value() });
2025
+ } else items.push(value());
2026
+ ws();
2027
+ if (text[i] === ",") i++;
2028
+ ws();
2029
+ }
2030
+ i++;
2031
+ return c === "{" ? { type: "object", start, end: i, entries } : { type: "array", start, end: i, items };
2032
+ }
2033
+ if (c === '"') {
2034
+ i++;
2035
+ while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
2036
+ i++;
2037
+ return { type: "string", start, end: i, value: JSON.parse(text.slice(start, i)) };
2038
+ }
2039
+ while (i < text.length && /[^\s,\]}]/.test(text[i])) i++;
2040
+ return { type: "literal", start, end: i };
2041
+ };
2042
+ return value();
2043
+ }
2044
+ var field = (node, key) => node?.type === "object" ? node.entries.find((e) => e.key === key)?.value : void 0;
2045
+ function vercelPolicies(text) {
2046
+ const out = [];
2047
+ const rules = field(jsonTree(text), "headers");
2048
+ if (rules?.type !== "array") return out;
2049
+ for (const rule of rules.items) {
2050
+ const source = field(rule, "source");
2051
+ const headers = field(rule, "headers");
2052
+ if (headers?.type !== "array") continue;
2053
+ for (const h of headers.items) {
2054
+ const key = field(h, "key");
2055
+ const value = field(h, "value");
2056
+ if (key?.type === "string" && HEADER.test(key.value) && value?.type === "string")
2057
+ out.push({ file: "vercel.json", source: source?.type === "string" ? source.value : "", value: value.value, start: value.start, end: value.end });
2058
+ }
2059
+ }
2060
+ return out;
2061
+ }
2062
+ var HEADERS_LINE = /^([ \t]+)(content-security-policy)([ \t]*:[ \t]*)(.*?)([ \t]*)$/i;
2063
+ function headersPolicies(text) {
2064
+ const out = [];
2065
+ let path = "";
2066
+ let at2 = 0;
2067
+ text.split("\n").forEach((line, n) => {
2068
+ const plain2 = line.replace(/\r$/, "");
2069
+ if (/^\S/.test(plain2) && !plain2.startsWith("#")) path = plain2.trim();
2070
+ const m = HEADERS_LINE.exec(plain2);
2071
+ if (m) {
2072
+ const start = at2 + m[1].length + m[2].length + m[3].length;
2073
+ out.push({ file: "public/_headers", source: path, value: m[4], start, end: start + m[4].length, line: n + 1 });
2074
+ }
2075
+ at2 += line.length + 1;
2076
+ });
2077
+ return out;
2078
+ }
2079
+ function policiesIn(file, text) {
2080
+ if (text === null) return { policies: [], invalid: false };
2081
+ try {
2082
+ if (file.endsWith("vercel.json")) return { policies: vercelPolicies(text), invalid: false };
2083
+ if (file.endsWith("_headers")) return { policies: headersPolicies(text), invalid: false };
2084
+ } catch {
2085
+ return { policies: [], invalid: true };
2086
+ }
2087
+ return { policies: [], invalid: false };
2088
+ }
2089
+ var blockingIn = (file, text, endpoint = COLLECTOR) => policiesIn(file, text).policies.filter((p) => !policyAllows(p.value, endpoint));
2090
+ function edited(file, text, change) {
2091
+ const { policies } = policiesIn(file, text);
2092
+ let out = text;
2093
+ for (const p of [...policies].sort((a, b) => b.start - a.start)) {
2094
+ const next = change(p.value);
2095
+ if (next === p.value) continue;
2096
+ const literal = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
2097
+ out = `${out.slice(0, p.start)}${literal}${out.slice(p.end)}`;
2098
+ }
2099
+ return out;
2100
+ }
2101
+ var withCollectorIn = (file, text, origin = COLLECTOR_ORIGIN) => edited(file, text, (p) => withCollector(p, origin));
2102
+ var withoutCollectorIn = (file, text, origin = COLLECTOR_ORIGIN) => edited(file, text, (p) => withoutCollector(p, origin));
2103
+ function onlyCollectorChanged(file, before, after) {
2104
+ if (before === null || after === null) return false;
2105
+ const a = policiesIn(file, before);
2106
+ const b = policiesIn(file, after);
2107
+ if (a.invalid || b.invalid) return false;
2108
+ const plain2 = (text) => edited(file, text, plainPolicy);
2109
+ if (file.endsWith("vercel.json")) {
2110
+ try {
2111
+ return JSON.stringify(JSON.parse(plain2(before))) === JSON.stringify(JSON.parse(plain2(after)));
2112
+ } catch {
2113
+ return false;
2114
+ }
2115
+ }
2116
+ return plain2(before) === plain2(after);
2117
+ }
2118
+ var CODE2 = /\.(m?[jt]sx?|c[jt]s|astro|html?|vue|svelte|toml|ya?ml)$/;
2119
+ function cspElsewhere(path, text) {
2120
+ if (!text || CSP_FILES.includes(path) || path.includes("node_modules/") || !CODE2.test(path)) return null;
2121
+ if (/http-?equiv\s*=\s*\{?\s*["'`]content-security-policy/i.test(text)) return "a <meta http-equiv> tag";
2122
+ if (/content-security-policy/i.test(text)) {
2123
+ if (/(^|\/)next\.config\.[mc]?[jt]s$/.test(path)) return "next.config's headers()";
2124
+ if (/(^|\/)netlify\.toml$/.test(path)) return "netlify.toml's headers";
2125
+ if (/(^|\/)middleware\.[mc]?[jt]s$/.test(path)) return "a middleware";
2126
+ return "a Content-Security-Policy header";
2127
+ }
2128
+ if (/(^|\/)astro\.config\.[mc]?[jt]s$/.test(path) && /\bcsp\s*:/.test(text)) return "Astro's own CSP (its `csp` option)";
2129
+ return null;
2130
+ }
1912
2131
  export {
1913
2132
  pages_core_exports as core,
2133
+ csp_exports as csp,
1914
2134
  detect,
1915
2135
  readSettings,
1916
2136
  registryFiles,
package/lib/uninstall.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // draft (without the kit a draft is built and goes live). Then removes the
4
4
  // packages, what the framework's module names (on Astro: their lines in
5
5
  // astro.config, comment-modus.json, unbase.pages.json,
6
- // src/content/.schemas/) and the pointer line init may have written, and
6
+ // src/content/.schemas/), the analytics collector init allowed in the CSP of
7
+ // vercel.json and public/_headers, and the pointer line init may have written, and
7
8
  // compares every built page's HTML before and after: the packages may change
8
9
  // how a site is edited and built, never how it renders.
9
10
  // ============================================================================
@@ -13,6 +14,7 @@ import { join } from "node:path";
13
14
  import { buildSite, tailOf } from "./build.mjs";
14
15
  import { comparePages } from "./compare.mjs";
15
16
  import { CouldNotRun, FAILED, PASSED } from "./errors.mjs";
17
+ import { planCsp } from "./analytics.mjs";
16
18
  import { POINTER_BEFORE, POINTER_FILES, POINTER_LINE } from "./init.mjs";
17
19
  import { dropDependencies, lockfileOf, packageManagerOf, removePackages } from "./pm.mjs";
18
20
  import { core } from "./readers.mjs";
@@ -43,7 +45,9 @@ export async function uninstall(flags, io) {
43
45
  }
44
46
 
45
47
  // Plan everything before changing anything: a config that cannot be edited stops here.
46
- const plan = site.framework.uninstall(site);
48
+ const own = site.framework.uninstall(site);
49
+ // The collector init allowed in the site's CSP goes with the package.
50
+ const plan = { ...own, files: [...own.files, ...planCsp(site, { add: false }).files] };
47
51
  const deps = depsOf(site.pkg);
48
52
  const packages = plan.packages.filter((n) => deps[n]);
49
53
  const pm = packages.length && !flags["no-install"] ? packageManagerOf(site) : null;