@unbase-app/layer 0.0.0-stage → 2.0.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/LICENSE +21 -0
- package/README.md +400 -2
- package/bin/unbase-layer.mjs +28 -0
- package/cli/artifact-style.mjs +89 -0
- package/cli/fetch.mjs +142 -0
- package/cli/lib.mjs +160 -0
- package/cli/live.mjs +35 -0
- package/cli/overview-artifact.mjs +142 -0
- package/cli/plan-artifact.mjs +337 -0
- package/cli/post.mjs +309 -0
- package/cli/redispatch.mjs +99 -0
- package/cli/screenshot.mjs +189 -0
- package/cli/status.mjs +50 -0
- package/cli/store.mjs +143 -0
- package/dist/client/start.d.ts +4 -0
- package/dist/client/start.js +12888 -0
- package/package.json +119 -4
- package/skills/build-comment/SKILL.md +61 -0
- package/skills/get-comments/SKILL.md +127 -0
- package/skills/process-comments/SKILL.md +115 -0
- package/skills/propose-comment/SKILL.md +79 -0
- package/src/astro/component-marker.mjs +161 -0
- package/src/astro/content-map-extra.mjs +192 -0
- package/src/astro/content-map.mjs +584 -0
- package/src/astro/deploy-context.mjs +66 -0
- package/src/astro/index.d.ts +97 -0
- package/src/astro/index.mjs +277 -0
- package/src/astro/pages.mjs +192 -0
- package/src/astro/version.mjs +13 -0
- package/src/edit/index.d.mts +178 -0
- package/src/edit/index.mjs +1002 -0
- package/src/page/index.d.mts +71 -0
- package/src/page/index.mjs +216 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { AstroIntegration } from "astro";
|
|
2
|
+
|
|
3
|
+
/** An inline SVG path for the Operator's avatar (the account that does the
|
|
4
|
+
* processing). Without a logo: a generic icon. */
|
|
5
|
+
export interface Logo {
|
|
6
|
+
viewBox: string;
|
|
7
|
+
path: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Which builds get the data-c markers (1.9.0).
|
|
11
|
+
* - "always" (default): every build, production too. Comments on the live
|
|
12
|
+
* site take a pin's title and source file from them.
|
|
13
|
+
* - "preview": the dev server (also in Unbase's sandbox) and preview builds,
|
|
14
|
+
* not a production build. Production is decided as Unbase's draft-pages
|
|
15
|
+
* kit decides it: UNBASE_DEPLOY_CONTEXT, then a dev server, then the host
|
|
16
|
+
* (VERCEL_ENV, Netlify's CONTEXT), and otherwise production. */
|
|
17
|
+
export type MarkerWhen = "always" | "preview";
|
|
18
|
+
|
|
19
|
+
export interface MarkerOptions {
|
|
20
|
+
/** The folder with the components, relative to the project root (default "src/components"). */
|
|
21
|
+
dir?: string;
|
|
22
|
+
/** Sub-folders (relative to `dir`, with a slash) that are not marked (default ["dev/"]). */
|
|
23
|
+
skip?: string[];
|
|
24
|
+
/** Which builds get the markers (default "always"); see MarkerWhen. */
|
|
25
|
+
when?: MarkerWhen;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Options {
|
|
29
|
+
/** The project in Unbase: its uuid, or for convenience its slug. The layer
|
|
30
|
+
* looks up the uuid when it starts (project_public) and uses it for every
|
|
31
|
+
* row, channel and storage path. */
|
|
32
|
+
project?: string;
|
|
33
|
+
/** @deprecated Use `project`. The old site key (e.g. "avhh") still works:
|
|
34
|
+
* Unbase knows which project it belongs to. Warns once at build. */
|
|
35
|
+
site?: string;
|
|
36
|
+
/** The repository's main branch (default "main"). A Vercel preview of any
|
|
37
|
+
* other branch is that working version: the layer shows its comments only
|
|
38
|
+
* and places new ones on it. Production and local builds are Main. */
|
|
39
|
+
mainBranch?: string;
|
|
40
|
+
/** Language of the interface: "en" (default) or "nl". */
|
|
41
|
+
language?: "en" | "nl";
|
|
42
|
+
/** The Supabase project behind Unbase; by default from PUBLIC_SUPABASE_URL
|
|
43
|
+
* and PUBLIC_SUPABASE_ANON_KEY. */
|
|
44
|
+
supabase?: { url: string; anonKey: string };
|
|
45
|
+
/** Component path ("layout/VibeHero") → title, e.g. from a component registry.
|
|
46
|
+
* Without titles the layer shows the file name. */
|
|
47
|
+
titles?: Record<string, string>;
|
|
48
|
+
/** The site's logo as an SVG path, for the Operator's avatar. */
|
|
49
|
+
logo?: Logo;
|
|
50
|
+
/** Override tokens: { accent: "#0A84FF", font: "…" } → --cm-accent, --cm-font.
|
|
51
|
+
* The names are in src/client/tokens.ts. */
|
|
52
|
+
theme?: Record<string, string>;
|
|
53
|
+
/** The component marker (data-c). false: none (the layer then names a pin
|
|
54
|
+
* after its section's heading). "always" (default) or "preview": which
|
|
55
|
+
* builds get them, see MarkerWhen. An object sets the folder, the
|
|
56
|
+
* sub-folders to skip and `when`. */
|
|
57
|
+
componentMarker?: false | MarkerWhen | MarkerOptions;
|
|
58
|
+
/** Regex (source) on the component path: wrappers that say nothing about what
|
|
59
|
+
* is there, e.g. "^(motion/|layout/(Section|Container)$)". */
|
|
60
|
+
wrappers?: string;
|
|
61
|
+
/** Regex (source) on the component path: atoms that do belong in the chain
|
|
62
|
+
* but are not the name of the spot, e.g. "^ui/(Button|Heading)$". */
|
|
63
|
+
atoms?: string;
|
|
64
|
+
/** Minutes offline after which an unread notification (@-mention, reply)
|
|
65
|
+
* goes out by email. Only set it when Unbase's Edge Function
|
|
66
|
+
* notification-mail runs with the same delay: the layer then promises the
|
|
67
|
+
* email in the notifications panel. */
|
|
68
|
+
emailAfter?: number;
|
|
69
|
+
/** false: no /comment-modus/pages.json and no page tree in the layer.
|
|
70
|
+
* `exclude`: regex (source) on the path of pages to leave out, e.g.
|
|
71
|
+
* "^/componenten/preview/". */
|
|
72
|
+
pages?: false | { exclude?: string };
|
|
73
|
+
/** Edit mode (0.11.0): admins edit text on the page and publish it as one
|
|
74
|
+
* commit. `content` is the folder with the site's JSON content (Astro
|
|
75
|
+
* content collections), relative to the project root; default
|
|
76
|
+
* "src/content". Fields that may carry <em>, <strong> and <a href> are
|
|
77
|
+
* marked in the collection schema with .meta({ "x-inline": true }).
|
|
78
|
+
* `schemas: false` stops copying the collection JSON Schemas to
|
|
79
|
+
* <content>/.schemas/ (Unbase's publish function validates against them). */
|
|
80
|
+
edit?: true | { content?: string; schemas?: boolean };
|
|
81
|
+
/** false: no /version.json route (and no "new version · reload" prompt). */
|
|
82
|
+
versionRoute?: boolean;
|
|
83
|
+
/** Load the layer from this address instead of building it into the site
|
|
84
|
+
* (docs/plan-hosted-layer.md): the page then carries the configuration
|
|
85
|
+
* (window.__COMMENT_MODUS__) and imports the hosted layer, so a new layer
|
|
86
|
+
* needs no deploy of the site. The site's CSP must allow the address in
|
|
87
|
+
* script-src. For now an explicit address, e.g. a local
|
|
88
|
+
* `npm run dev:layer` ("http://localhost:4410/start.js"). */
|
|
89
|
+
layerUrl?: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** "@/components/layout/VibeHero.astro" → "layout/VibeHero" */
|
|
93
|
+
export function keyFromPath(path: string, dir?: string): string;
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
export default function commentModus(options: Options): AstroIntegration;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// ASTRO INTEGRATION — all a site has to do is put this in astro.config:
|
|
3
|
+
//
|
|
4
|
+
// import layer from "@unbase-app/layer";
|
|
5
|
+
// export default defineConfig({ integrations: [layer({ project: "<uuid or slug>" })] });
|
|
6
|
+
//
|
|
7
|
+
// What the integration takes care of:
|
|
8
|
+
// - the virtual module `virtual:comment-modus/config` (project, build,
|
|
9
|
+
// Supabase, component titles, logo, theme) the layer reads from;
|
|
10
|
+
// - a small script on every page that checks whether ?comment is on and only
|
|
11
|
+
// then loads the layer (a dynamic import; normal visitors load nothing):
|
|
12
|
+
// bundled into the site, or with `layerUrl` the hosted layer, with the
|
|
13
|
+
// configuration in the page (docs/plan-hosted-layer.md);
|
|
14
|
+
// - the route /version.json, by which an open tab notices that a new build
|
|
15
|
+
// is live;
|
|
16
|
+
// - /comment-modus/pages.json, the site's pages for the page tree on the
|
|
17
|
+
// left of the layer (pages.mjs). Off with pages: false;
|
|
18
|
+
// - /comment-modus/content-map.json, with the option edit: { content }: every
|
|
19
|
+
// text in the site's JSON content, for the Edit tool (content-map.mjs).
|
|
20
|
+
// Without that option there is no pencil and no Publish;
|
|
21
|
+
// - the component marker (data-c on the root element of every .astro
|
|
22
|
+
// component in src/components/), so a comment knows which component it
|
|
23
|
+
// sits in. Off with componentMarker: false; with "preview" (1.9.0) not in
|
|
24
|
+
// a production build, by the rule of Unbase's draft-pages kit
|
|
25
|
+
// (deploy-context.mjs).
|
|
26
|
+
//
|
|
27
|
+
// The backend is Unbase's: one Supabase project for every site, with
|
|
28
|
+
// everything of the layer in the schema `unbase`. The URL and anon key come
|
|
29
|
+
// from PUBLIC_SUPABASE_URL / PUBLIC_SUPABASE_ANON_KEY (.env or the
|
|
30
|
+
// environment), or from the option `supabase`. They are meant to be public:
|
|
31
|
+
// the rights live in Row Level Security (the migrations in Unbase's repository).
|
|
32
|
+
//
|
|
33
|
+
// This file is JavaScript, not TypeScript: Astro loads the configuration
|
|
34
|
+
// through Node, and Node does not strip types from node_modules. The types are
|
|
35
|
+
// in index.d.ts. The layer itself (src/client/) stays .tsx; that goes through
|
|
36
|
+
// Vite.
|
|
37
|
+
// ============================================================================
|
|
38
|
+
|
|
39
|
+
import { readFileSync } from "node:fs";
|
|
40
|
+
import { loadEnv } from "vite";
|
|
41
|
+
import componentMarker from "./component-marker.mjs";
|
|
42
|
+
import { deployContext, markerSettings, markersInBuild } from "./deploy-context.mjs";
|
|
43
|
+
import { pageList, PAGES_PATH } from "./pages.mjs";
|
|
44
|
+
import { contentMap } from "./content-map.mjs";
|
|
45
|
+
|
|
46
|
+
export { keyFromPath } from "./component-marker.mjs";
|
|
47
|
+
|
|
48
|
+
/** A uuid, a slug or the old site key: lower-case letters, digits and
|
|
49
|
+
* hyphens. */
|
|
50
|
+
const PROJECT_FORMAT = /^[a-z0-9][a-z0-9-]{0,62}$/i;
|
|
51
|
+
const PACKAGE_NAME = "@unbase-app/layer";
|
|
52
|
+
const VIRTUAL_ID = "virtual:comment-modus/config";
|
|
53
|
+
/** This package's version: the hosted layer reads from it what the site
|
|
54
|
+
* brings along (markers, pages.json, content map). */
|
|
55
|
+
const VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
56
|
+
|
|
57
|
+
/** The file behind /version.json, as a file URL and not as
|
|
58
|
+
* "@unbase-app/layer/version": Astro 7 resolves an injected route per
|
|
59
|
+
* Vite environment, and in the prerender environment a package name stays
|
|
60
|
+
* bare when the package is not in the site's package.json (npm install
|
|
61
|
+
* --no-save, or through another package). Astro then computes
|
|
62
|
+
* new URL("file://@unbase-app/…") and the build stops with "Invalid URL" (1.8.1).
|
|
63
|
+
* Astro 5 and later take a URL as entrypoint. */
|
|
64
|
+
const VERSION_ROUTE = new URL("./version.mjs", import.meta.url);
|
|
65
|
+
|
|
66
|
+
/** Which code is live: the commit on Vercel, locally the moment the server
|
|
67
|
+
* started. A redeploy of the same commit does not count as a new version, on
|
|
68
|
+
* purpose: the code did not change. */
|
|
69
|
+
function buildId() {
|
|
70
|
+
return process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 12) || new Date().toISOString();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** This build's working version: the branch of a Vercel preview. Production
|
|
74
|
+
* (also a separate live branch, Unbase's ADR-0010), the main branch and
|
|
75
|
+
* local builds are Main: null. */
|
|
76
|
+
function workingVersion(mainBranch = "main") {
|
|
77
|
+
const ref = process.env.VERCEL_GIT_COMMIT_REF;
|
|
78
|
+
if (!ref || process.env.VERCEL_ENV === "production" || ref === mainBranch) return null;
|
|
79
|
+
return ref.slice(0, 255);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** @param {import("../lib/config").ClientConfig} config @returns {import("vite").Plugin} */
|
|
83
|
+
function configModule(config) {
|
|
84
|
+
const resolved = "\0" + VIRTUAL_ID;
|
|
85
|
+
return {
|
|
86
|
+
name: "comment-modus:config",
|
|
87
|
+
resolveId: (id) => (id === VIRTUAL_ID ? resolved : undefined),
|
|
88
|
+
load: (id) => (id === resolved ? `export default ${JSON.stringify(config)};` : undefined),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The script on every page: a few lines that load nothing, unless ?comment
|
|
93
|
+
* is in the URL or the mode was already on in this session
|
|
94
|
+
* (sessionStorage). × in the toolbar clears that state; an "off" from
|
|
95
|
+
* before 0.2.1 no longer counts as on. */
|
|
96
|
+
const LOADER = `
|
|
97
|
+
const KEY = "comment-modus";
|
|
98
|
+
const asked = new URLSearchParams(location.search).has("comment");
|
|
99
|
+
let on = asked;
|
|
100
|
+
try {
|
|
101
|
+
if (asked) sessionStorage.setItem(KEY, "1");
|
|
102
|
+
on = asked || sessionStorage.getItem(KEY) === "1";
|
|
103
|
+
} catch {
|
|
104
|
+
// No sessionStorage (a private window with storage blocked): then only on
|
|
105
|
+
// the page that has ?comment in its URL.
|
|
106
|
+
}
|
|
107
|
+
if (on) (async () => {
|
|
108
|
+
__PREAMBLE__
|
|
109
|
+
__LOAD__
|
|
110
|
+
m.start();
|
|
111
|
+
})();
|
|
112
|
+
`;
|
|
113
|
+
|
|
114
|
+
/** The layer from the site itself: the import goes through Vite and is in the build. */
|
|
115
|
+
const BUNDLED = `const m = await import(${JSON.stringify(`${PACKAGE_NAME}/start`)});`;
|
|
116
|
+
|
|
117
|
+
/** The hosted layer (layerUrl): first the configuration in the page, which
|
|
118
|
+
* the layer reads there (src/client/page-config.ts), then the layer from its
|
|
119
|
+
* own address. @vite-ignore: Vite must leave that import as it is.
|
|
120
|
+
* @param {string} url @param {import("../lib/config").ClientConfig} config */
|
|
121
|
+
const HOSTED = (url, config) => `window.__COMMENT_MODUS__ = ${JSON.stringify({ config, integration: VERSION })};
|
|
122
|
+
const m = await import(/* @vite-ignore */ ${JSON.stringify(url)});`;
|
|
123
|
+
|
|
124
|
+
/** Inline in the <head>, before the first frame: puts down the still copy of
|
|
125
|
+
* toolbar and page tree that the layer kept on the previous page
|
|
126
|
+
* (src/client/shell.ts), so they stay in place across a page change until
|
|
127
|
+
* the layer itself is there. Only when the mode is on and the copy is fresh
|
|
128
|
+
* (from the page before, not from an hour ago). The current page is marked
|
|
129
|
+
* in the tree, not the previous one.
|
|
130
|
+
* LEGACY-NL: the key and id `comment-modus-schil`, the copy's `stijl`, the
|
|
131
|
+
* row class `cm-pg__rij` and its state `is-hier` keep their Dutch names
|
|
132
|
+
* (shell.ts and Pages.tsx write them; Unbase skips the element by its id). */
|
|
133
|
+
const SHELL = `
|
|
134
|
+
(() => {
|
|
135
|
+
try {
|
|
136
|
+
const on = new URLSearchParams(location.search).has("comment") || sessionStorage.getItem("comment-modus") === "1";
|
|
137
|
+
const saved = on && sessionStorage.getItem("comment-modus-schil");
|
|
138
|
+
if (!saved) return;
|
|
139
|
+
const k = JSON.parse(saved);
|
|
140
|
+
if (!(Date.now() - k.t < 10000)) return;
|
|
141
|
+
const host = document.createElement("div");
|
|
142
|
+
host.id = "comment-modus-schil";
|
|
143
|
+
host.setAttribute("style", k.style ?? k.stijl);
|
|
144
|
+
host.inert = true;
|
|
145
|
+
const r = host.attachShadow({ mode: "open" });
|
|
146
|
+
r.innerHTML = "<style>" + k.css + "</style>" + k.html;
|
|
147
|
+
const norm = (p) => p.replace(/\\/+$/, "") || "/";
|
|
148
|
+
const here = norm(location.pathname);
|
|
149
|
+
for (const a of r.querySelectorAll(".cm-pg__link")) {
|
|
150
|
+
const row = a.closest(".cm-pg__rij");
|
|
151
|
+
const is = a.getAttribute("href") != null && norm(a.getAttribute("href")) === here;
|
|
152
|
+
if (is) a.setAttribute("aria-current", "page"); else a.removeAttribute("aria-current");
|
|
153
|
+
row && row.classList.toggle("is-hier", is);
|
|
154
|
+
}
|
|
155
|
+
document.documentElement.appendChild(host);
|
|
156
|
+
setTimeout(() => host.remove(), 10000);
|
|
157
|
+
} catch {}
|
|
158
|
+
})();
|
|
159
|
+
`;
|
|
160
|
+
|
|
161
|
+
/** Dev only: the fast-refresh preamble of @vitejs/plugin-react. Astro puts
|
|
162
|
+
* it in itself before it hydrates an island, so a page without an island
|
|
163
|
+
* does not have it — and then every .tsx file refuses to load ("can't
|
|
164
|
+
* detect preamble"). Once per page; when it is there already, do
|
|
165
|
+
* nothing. */
|
|
166
|
+
const PREAMBLE_DEV = `
|
|
167
|
+
if (!window.__vite_plugin_react_preamble_installed__) {
|
|
168
|
+
const RefreshRuntime = (await import("/@react-refresh")).default;
|
|
169
|
+
RefreshRuntime.injectIntoGlobalHook(window);
|
|
170
|
+
window.$RefreshReg$ = () => {};
|
|
171
|
+
window.$RefreshSig$ = () => (type) => type;
|
|
172
|
+
window.__vite_plugin_react_preamble_installed__ = true;
|
|
173
|
+
}`;
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* @param {import("./index").Options} options
|
|
177
|
+
* @returns {import("astro").AstroIntegration}
|
|
178
|
+
*/
|
|
179
|
+
export default function commentModus(options) {
|
|
180
|
+
const project = options?.project ?? options?.site;
|
|
181
|
+
if (!PROJECT_FORMAT.test(project ?? "")) {
|
|
182
|
+
throw new Error(`@unbase-app/layer: "project" is the project's uuid or slug, not ${JSON.stringify(project)}`);
|
|
183
|
+
}
|
|
184
|
+
let warnedSite = false;
|
|
185
|
+
const marker = markerSettings(options.componentMarker);
|
|
186
|
+
const pageTree = options.pages === false ? null : pageList(options.pages ?? {});
|
|
187
|
+
const editMap = options.edit ? contentMap(options.edit === true ? {} : options.edit) : null;
|
|
188
|
+
return {
|
|
189
|
+
name: "comment-modus",
|
|
190
|
+
hooks: {
|
|
191
|
+
"astro:config:setup": ({ config, command, updateConfig, injectScript, injectRoute, logger }) => {
|
|
192
|
+
if (!options.project && options.site && !warnedSite) {
|
|
193
|
+
warnedSite = true;
|
|
194
|
+
logger.warn(`The option "site" is deprecated: use project: "<uuid or slug>". "${options.site}" still works for now.`);
|
|
195
|
+
}
|
|
196
|
+
pageTree?.setRoot(config.root);
|
|
197
|
+
editMap?.setRoot(config.root, undefined, config.cacheDir, command === "dev");
|
|
198
|
+
const env = loadEnv(command === "dev" ? "development" : "production", config.root.pathname, "PUBLIC_");
|
|
199
|
+
const url = options.supabase?.url ?? env.PUBLIC_SUPABASE_URL ?? process.env.PUBLIC_SUPABASE_URL;
|
|
200
|
+
const anonKey = options.supabase?.anonKey ?? env.PUBLIC_SUPABASE_ANON_KEY ?? process.env.PUBLIC_SUPABASE_ANON_KEY;
|
|
201
|
+
if (!url || !anonKey) {
|
|
202
|
+
logger.warn("Supabase is not set up (PUBLIC_SUPABASE_URL / PUBLIC_SUPABASE_ANON_KEY): the layer says so in its panel; only ?comment&cm-demo works.");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** @type {import("../lib/config").ClientConfig} */
|
|
206
|
+
const client = {
|
|
207
|
+
project,
|
|
208
|
+
build: buildId(),
|
|
209
|
+
branch: workingVersion(options.mainBranch),
|
|
210
|
+
language: options.language === "nl" ? "nl" : "en",
|
|
211
|
+
supabase: url && anonKey ? { url, anonKey } : null,
|
|
212
|
+
titles: options.titles ?? {},
|
|
213
|
+
logo: options.logo ?? null,
|
|
214
|
+
theme: options.theme ?? {},
|
|
215
|
+
wrappers: options.wrappers ?? "",
|
|
216
|
+
atoms: options.atoms ?? "",
|
|
217
|
+
emailAfter: Number.isFinite(options.emailAfter) && options.emailAfter > 0 ? Math.round(options.emailAfter) : null,
|
|
218
|
+
pages: pageTree ? PAGES_PATH : null,
|
|
219
|
+
edit: editMap ? { map: editMap.path } : null,
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const plugins = [configModule(client)];
|
|
223
|
+
if (marker) {
|
|
224
|
+
// "preview": markers in dev, previews and Unbase's sandbox, not in a
|
|
225
|
+
// production build (Unbase docs/plan-packages.md, Open 5).
|
|
226
|
+
const ctx = deployContext({ env: process.env, command: command === "dev" ? "dev" : "build" });
|
|
227
|
+
if (markersInBuild(marker.when, ctx)) plugins.push(componentMarker(marker));
|
|
228
|
+
else if (command === "build" || command === "dev") logger.info(`no data-c markers: componentMarker "preview" in a production build (${ctx.source})`);
|
|
229
|
+
}
|
|
230
|
+
if (pageTree) plugins.push(pageTree.vitePlugin());
|
|
231
|
+
if (editMap) plugins.push(editMap.vitePlugin());
|
|
232
|
+
|
|
233
|
+
updateConfig({
|
|
234
|
+
vite: {
|
|
235
|
+
plugins,
|
|
236
|
+
// The package is source (tsx), not a bundled dependency: Vite has to
|
|
237
|
+
// process it itself, the virtual module in it too. Pre-bundle
|
|
238
|
+
// everything the layer only loads with ?comment: otherwise Vite
|
|
239
|
+
// discovers it in the middle of the first session, re-bundles, and
|
|
240
|
+
// every open tab gets 504 "Outdated Optimize Dep". One React, also
|
|
241
|
+
// when the package is linked (file:/workspace) and has its own
|
|
242
|
+
// node_modules.
|
|
243
|
+
optimizeDeps: {
|
|
244
|
+
exclude: [PACKAGE_NAME],
|
|
245
|
+
include: ["react", "react-dom", "react-dom/client", "react/jsx-runtime", "react/jsx-dev-runtime", "framer-motion", "lucide-react", "@supabase/supabase-js"],
|
|
246
|
+
},
|
|
247
|
+
resolve: { dedupe: ["react", "react-dom", "framer-motion", "lucide-react", "@supabase/supabase-js"] },
|
|
248
|
+
ssr: { noExternal: [PACKAGE_NAME] },
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
injectScript("head-inline", SHELL);
|
|
253
|
+
const hosted = typeof options.layerUrl === "string" && options.layerUrl.length > 0;
|
|
254
|
+
injectScript(
|
|
255
|
+
"page",
|
|
256
|
+
LOADER.replace("__PREAMBLE__", command === "dev" && !hosted ? PREAMBLE_DEV : "").replace("__LOAD__", hosted ? HOSTED(options.layerUrl, client) : BUNDLED),
|
|
257
|
+
);
|
|
258
|
+
if (options.versionRoute !== false) {
|
|
259
|
+
injectRoute({ pattern: "/version.json", entrypoint: VERSION_ROUTE, prerender: true });
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
"astro:routes:resolved": ({ routes }) => pageTree?.setRoutes(routes),
|
|
263
|
+
// Dev: Astro's refreshContent, for the sync after a new collection (content-map.mjs, update).
|
|
264
|
+
"astro:server:setup": ({ refreshContent }) => editMap?.setRefresh(refreshContent),
|
|
265
|
+
// Dev: the schemas from .astro/collections into the repository (content-map.mjs).
|
|
266
|
+
// A moment after the start, because Astro writes them at its first sync;
|
|
267
|
+
// after that on every new sync (the watcher in content-map.mjs).
|
|
268
|
+
"astro:server:start": ({ logger }) => {
|
|
269
|
+
if (editMap) setTimeout(() => void editMap.copySchemas(logger).catch(() => {}), 3000);
|
|
270
|
+
},
|
|
271
|
+
"astro:build:done": async ({ dir, pages, logger }) => {
|
|
272
|
+
await pageTree?.write({ dir, pages, logger });
|
|
273
|
+
await editMap?.write({ dir, logger });
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// PAGES — which pages the site has, for the page tree in the layer.
|
|
3
|
+
//
|
|
4
|
+
// The layer fetches /comment-modus/pages.json: a list { path, title }.
|
|
5
|
+
//
|
|
6
|
+
// - Build: from astro:build:done, so exactly the pages that were built
|
|
7
|
+
// (every /nieuws/[slug] too), with the <title> from their HTML. The file
|
|
8
|
+
// goes next to the rest of the static output.
|
|
9
|
+
// - Dev: from astro:routes:resolved. A dynamic route is expanded with its
|
|
10
|
+
// own getStaticPaths(); the title is then the slug, made readable
|
|
11
|
+
// (rendering a page to read its <title> is too expensive in dev).
|
|
12
|
+
//
|
|
13
|
+
// Only the project's own pages: no endpoints, redirects or routes another
|
|
14
|
+
// integration injects (such as /studio), and no 404/500. The option
|
|
15
|
+
// `pages.exclude` (a regex source on the path) takes more out.
|
|
16
|
+
// ============================================================================
|
|
17
|
+
|
|
18
|
+
import { readFile, mkdir, writeFile } from "node:fs/promises";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
|
|
21
|
+
export const PAGES_PATH = "/comment-modus/pages.json";
|
|
22
|
+
/** For this long the dev server reuses an expanded list. */
|
|
23
|
+
const DEV_CACHE_MS = 30_000;
|
|
24
|
+
|
|
25
|
+
/** @typedef {{ path: string, title: string }} Page */
|
|
26
|
+
|
|
27
|
+
/** "nieuws/foo/" or "/nieuws/foo/" → "/nieuws/foo"; "" → "/". The same form
|
|
28
|
+
* as currentPath() in the layer. */
|
|
29
|
+
export function normalizePath(path) {
|
|
30
|
+
return `/${path}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "") || "/";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** "de-10-verlangens" → "De 10 verlangens". */
|
|
34
|
+
export function readable(segment) {
|
|
35
|
+
const t = decodeURIComponent(segment).replace(/[-_]+/g, " ").trim();
|
|
36
|
+
return t.charAt(0).toUpperCase() + t.slice(1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The project's own page routes, without 404/500. */
|
|
40
|
+
function projectPages(routes) {
|
|
41
|
+
return routes.filter(
|
|
42
|
+
(r) => r.type === "page" && r.origin === "project" && !/^\/(404|500)\/?$/.test(r.pattern),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Takes the common suffix off the titles ("Team — Agenda voor het Hart" →
|
|
47
|
+
* "Team"): the last part after a separator, when at least half of the pages
|
|
48
|
+
* have it. A title that is only that suffix (usually the home page) stays as
|
|
49
|
+
* it is. */
|
|
50
|
+
export function withoutSuffix(pages) {
|
|
51
|
+
const SEPARATOR = /\s+[—–|·-]\s+/;
|
|
52
|
+
const counts = new Map();
|
|
53
|
+
for (const p of pages) {
|
|
54
|
+
const parts = p.title.split(SEPARATOR);
|
|
55
|
+
if (parts.length > 1) {
|
|
56
|
+
const tail = parts.at(-1);
|
|
57
|
+
counts.set(tail, (counts.get(tail) ?? 0) + 1);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const [tail, count] = [...counts].sort((a, b) => b[1] - a[1])[0] ?? [];
|
|
61
|
+
if (!tail || count < pages.length / 2) return pages;
|
|
62
|
+
return pages.map((p) => {
|
|
63
|
+
const parts = p.title.split(SEPARATOR);
|
|
64
|
+
return parts.length > 1 && parts.at(-1) === tail ? { ...p, title: parts.slice(0, -1).join(" — ") } : p;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function titleFromHtml(html) {
|
|
69
|
+
const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
|
|
70
|
+
if (!m) return "";
|
|
71
|
+
return m[1]
|
|
72
|
+
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
|
73
|
+
.replace(/"/g, '"').replace(/'|'/g, "'").replace(/ /g, " ")
|
|
74
|
+
.replace(/\s+/g, " ").trim();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function sortByPath(pages) {
|
|
78
|
+
return pages.sort((a, b) => a.path.localeCompare(b.path));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A path from the params of getStaticPaths, on the segments of the route. */
|
|
82
|
+
function pathFromParams(segments, params) {
|
|
83
|
+
const parts = [];
|
|
84
|
+
for (const segment of segments) {
|
|
85
|
+
let part = "";
|
|
86
|
+
for (const piece of segment) {
|
|
87
|
+
if (!piece.dynamic) part += piece.content;
|
|
88
|
+
else {
|
|
89
|
+
const name = piece.content.replace(/^\.\.\./, "");
|
|
90
|
+
const value = params?.[name];
|
|
91
|
+
if (value !== undefined && value !== null) part += String(value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (part) parts.push(part);
|
|
95
|
+
}
|
|
96
|
+
return normalizePath(parts.join("/"));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The part of the integration that makes the page list: one object per
|
|
101
|
+
* integration instance, because it remembers the routes between the hooks.
|
|
102
|
+
* @param {{ exclude?: string }} options
|
|
103
|
+
*/
|
|
104
|
+
export function pageList(options = {}) {
|
|
105
|
+
const exclude = options.exclude ? new RegExp(options.exclude) : null;
|
|
106
|
+
/** @type {any[]} */
|
|
107
|
+
let routes = [];
|
|
108
|
+
/** @type {URL | null} */
|
|
109
|
+
let root = null;
|
|
110
|
+
/** @type {{ at: number, list: Promise<Page[]> } | null} */
|
|
111
|
+
let devCache = null;
|
|
112
|
+
|
|
113
|
+
const allowed = (path) => !exclude || !exclude.test(path);
|
|
114
|
+
|
|
115
|
+
/** Dev: static routes as they are, dynamic ones through getStaticPaths. */
|
|
116
|
+
async function devList(server) {
|
|
117
|
+
const pages = [];
|
|
118
|
+
for (const r of projectPages(routes)) {
|
|
119
|
+
if (!r.params?.length) {
|
|
120
|
+
const path = normalizePath(r.pattern);
|
|
121
|
+
if (allowed(path)) pages.push({ path, title: path === "/" ? "" : readable(path.split("/").at(-1)) });
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const mod = await server.ssrLoadModule(fileURLToPath(new URL(r.entrypoint, root)));
|
|
126
|
+
if (typeof mod.getStaticPaths !== "function") continue;
|
|
127
|
+
const result = (await mod.getStaticPaths({ paginate: () => [], routePattern: r.pattern })) ?? [];
|
|
128
|
+
for (const item of result.flat()) {
|
|
129
|
+
const path = pathFromParams(r.segments, item?.params);
|
|
130
|
+
if (allowed(path)) pages.push({ path, title: readable(path.split("/").at(-1) ?? "") });
|
|
131
|
+
}
|
|
132
|
+
} catch (e) {
|
|
133
|
+
server.config.logger.warn(`[comment-modus] pages: ${r.pattern} not expanded (${e?.message ?? e})`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return sortByPath(pages);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
/** astro:config:setup */
|
|
141
|
+
setRoot(r) {
|
|
142
|
+
root = r;
|
|
143
|
+
},
|
|
144
|
+
/** astro:routes:resolved — also on every new or deleted page in dev. */
|
|
145
|
+
setRoutes(r) {
|
|
146
|
+
routes = r;
|
|
147
|
+
devCache = null;
|
|
148
|
+
},
|
|
149
|
+
/** The Vite plugin that serves the list in dev. */
|
|
150
|
+
vitePlugin() {
|
|
151
|
+
return {
|
|
152
|
+
name: "comment-modus:pages",
|
|
153
|
+
apply: "serve",
|
|
154
|
+
configureServer(server) {
|
|
155
|
+
server.middlewares.use(PAGES_PATH, async (_req, res) => {
|
|
156
|
+
if (!devCache || Date.now() - devCache.at > DEV_CACHE_MS) {
|
|
157
|
+
devCache = { at: Date.now(), list: devList(server) };
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const list = await devCache.list;
|
|
161
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
162
|
+
res.setHeader("Cache-Control", "no-store");
|
|
163
|
+
res.end(JSON.stringify(list));
|
|
164
|
+
} catch (e) {
|
|
165
|
+
devCache = null;
|
|
166
|
+
res.statusCode = 500;
|
|
167
|
+
res.end(JSON.stringify({ error: String(e?.message ?? e) }));
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
},
|
|
173
|
+
/** astro:build:done — the built pages, with their <title>. */
|
|
174
|
+
async write({ dir, pages, logger }) {
|
|
175
|
+
const own = projectPages(routes);
|
|
176
|
+
const fromProject = (path) => own.some((r) => r.patternRegex.test(path) || r.patternRegex.test(`${path}/`));
|
|
177
|
+
const paths = [...new Set(pages.map((p) => normalizePath(p.pathname)))].filter((path) => fromProject(path) && allowed(path));
|
|
178
|
+
const found = await Promise.all(
|
|
179
|
+
paths.map(async (path) => {
|
|
180
|
+
const file = new URL(`.${path === "/" ? "" : path}/index.html`, dir);
|
|
181
|
+
const html = await readFile(file, "utf8").catch(() => readFile(new URL(`.${path}.html`, dir), "utf8").catch(() => ""));
|
|
182
|
+
return { path, title: titleFromHtml(html) || (path === "/" ? "" : readable(path.split("/").at(-1))) };
|
|
183
|
+
}),
|
|
184
|
+
);
|
|
185
|
+
const list = sortByPath(withoutSuffix(found));
|
|
186
|
+
const target = new URL(`.${PAGES_PATH}`, dir);
|
|
187
|
+
await mkdir(new URL(".", target), { recursive: true });
|
|
188
|
+
await writeFile(target, JSON.stringify(list));
|
|
189
|
+
logger.info(`${list.length} pages in ${PAGES_PATH}`);
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// /version.json — which build is live. The layer compares it with the build it
|
|
2
|
+
// was loaded with itself (the same virtual module) and asks a tab that still
|
|
3
|
+
// runs old code to reload. Injected by the integration (injectRoute); off with
|
|
4
|
+
// versionRoute: false.
|
|
5
|
+
import CONFIG from "virtual:comment-modus/config";
|
|
6
|
+
|
|
7
|
+
export const prerender = true;
|
|
8
|
+
|
|
9
|
+
/** @type {import("astro").APIRoute} */
|
|
10
|
+
export const GET = () =>
|
|
11
|
+
new Response(JSON.stringify({ build: CONFIG.build }), {
|
|
12
|
+
headers: { "Content-Type": "application/json" },
|
|
13
|
+
});
|