@mccaskie-labs/workbench-site 0.0.0-stage → 0.9.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/CHANGELOG.md +56 -0
- package/README.md +36 -2
- package/dist/builder.d.ts +73 -0
- package/dist/builder.js +769 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.js +126 -0
- package/dist/frames.d.ts +91 -0
- package/dist/frames.js +63 -0
- package/dist/html.d.ts +6 -0
- package/dist/html.js +24 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +9 -0
- package/dist/recipe.d.ts +204 -0
- package/dist/recipe.js +151 -0
- package/dist/recipes/admin.d.ts +3 -0
- package/dist/recipes/admin.js +194 -0
- package/dist/recipes/enquiries-kit.d.ts +55 -0
- package/dist/recipes/enquiries-kit.js +235 -0
- package/dist/recipes/every-site.d.ts +3 -0
- package/dist/recipes/every-site.js +166 -0
- package/dist/recipes/index.d.ts +2 -0
- package/dist/recipes/index.js +7 -0
- package/dist/recipes/members.d.ts +3 -0
- package/dist/recipes/members.js +37 -0
- package/dist/samples.d.ts +18 -0
- package/dist/samples.js +69 -0
- package/dist/sections.d.ts +142 -0
- package/dist/sections.js +116 -0
- package/dist/styles.d.ts +33 -0
- package/dist/styles.js +153 -0
- package/package.json +52 -4
package/dist/builder.js
ADDED
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
// The builder (docs/site-planner.md §6): turns chosen recipes into thin page
|
|
2
|
+
// files in a project made from Workbench's template. Plain code with no AI in
|
|
3
|
+
// it: the same project and the same recipes give the same files, so
|
|
4
|
+
// Workbench's Checks can prove every recipe builds and passes
|
|
5
|
+
// (scripts/template/site.mjs).
|
|
6
|
+
//
|
|
7
|
+
// It reads the project's files through `read` and returns what to write; the
|
|
8
|
+
// CLI (cli.ts) does the disk. A page already in workbench/site.json is never
|
|
9
|
+
// written again: once built, it is the project's.
|
|
10
|
+
import { recipeKeys, recipeProblems, SECTION_FUNCTIONS, STORE_SECTIONS, UI_SECTIONS } from "./recipe.js";
|
|
11
|
+
import { RECIPES } from "./recipes/index.js";
|
|
12
|
+
export const SITE_FILE = "workbench/site.json";
|
|
13
|
+
const PACKAGE = "@mccaskie-labs/workbench-site";
|
|
14
|
+
/** A page file's export: page + its recipe in camel case (pageHome, pageNotFound), clear of the section functions and the routes. */
|
|
15
|
+
const camel = (id) => `page${id.replace(/(^|-)([a-z0-9])/g, (_, _d, c) => c.toUpperCase())}`;
|
|
16
|
+
const fileOf = (id) => `src/pages/${id}.ts`;
|
|
17
|
+
function readJson(read, path) {
|
|
18
|
+
const text = read(path);
|
|
19
|
+
if (text === undefined)
|
|
20
|
+
return undefined;
|
|
21
|
+
return JSON.parse(text);
|
|
22
|
+
}
|
|
23
|
+
/** Builds the chosen recipes into the project. */
|
|
24
|
+
export function buildSite(o) {
|
|
25
|
+
const catalogue = o.catalogue ?? RECIPES;
|
|
26
|
+
const base = o.base ?? "en-AU";
|
|
27
|
+
const byId = new Map(catalogue.map((r) => [r.id, r]));
|
|
28
|
+
const problems = [];
|
|
29
|
+
const fail = () => ({ writes: {}, added: [], already: [], problems, migrations: [], forms: false });
|
|
30
|
+
for (const r of catalogue)
|
|
31
|
+
problems.push(...recipeProblems(r, catalogue));
|
|
32
|
+
if (problems.length)
|
|
33
|
+
return fail();
|
|
34
|
+
if (o.read("src/index.ts") === undefined || o.read("src/lib/strings.ts") === undefined) {
|
|
35
|
+
problems.push("This doesn't look like a Workbench project: there's no src/index.ts or src/lib/strings.ts. Run it in the project's folder.");
|
|
36
|
+
return fail();
|
|
37
|
+
}
|
|
38
|
+
const pagesIndex = o.read("src/pages/index.ts");
|
|
39
|
+
if (pagesIndex === undefined || !o.read("src/index.ts").includes("sitePages(")) {
|
|
40
|
+
problems.push("src/index.ts doesn't hand over to src/pages/index.ts (sitePages). Update the project to the newest Workbench template first.");
|
|
41
|
+
return fail();
|
|
42
|
+
}
|
|
43
|
+
let site;
|
|
44
|
+
try {
|
|
45
|
+
site = readJson(o.read, SITE_FILE) ?? { format: 1, pages: [] };
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
problems.push(`${SITE_FILE} isn't valid JSON: ${e.message}`);
|
|
49
|
+
return fail();
|
|
50
|
+
}
|
|
51
|
+
const have = new Set(site.pages.map((p) => p.recipe));
|
|
52
|
+
// What to add: the asked-for recipes and what they need, each once.
|
|
53
|
+
const added = [];
|
|
54
|
+
const already = [];
|
|
55
|
+
const visit = (id, asked) => {
|
|
56
|
+
const r = byId.get(id);
|
|
57
|
+
if (!r) {
|
|
58
|
+
problems.push(`There's no page recipe called "${id}". Run \`npx workbench-site list\` to see them.`);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (have.has(id) || added.includes(id)) {
|
|
62
|
+
if (asked && have.has(id) && !already.includes(id))
|
|
63
|
+
already.push(id);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
for (const n of r.needs)
|
|
67
|
+
visit(n, false);
|
|
68
|
+
if (r.area === "legal") {
|
|
69
|
+
problems.push(`${id} is a ${r.area} page, which this version can't build yet.`);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
added.push(id);
|
|
73
|
+
};
|
|
74
|
+
for (const id of o.add)
|
|
75
|
+
visit(id, true);
|
|
76
|
+
if (problems.length)
|
|
77
|
+
return fail();
|
|
78
|
+
const pages = [...site.pages];
|
|
79
|
+
for (const id of added) {
|
|
80
|
+
const r = byId.get(id);
|
|
81
|
+
if (r.path !== null && pages.some((p) => p.path === r.path)) {
|
|
82
|
+
problems.push(`${id} would be at ${r.path}, where ${pages.find((p) => p.path === r.path).recipe} already is.`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (r.path === null && pages.some((p) => p.path === null)) {
|
|
86
|
+
problems.push(`${id} would be the page shown when no other answers, which ${pages.find((p) => p.path === null).recipe} already is.`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (o.read(fileOf(id)) !== undefined) {
|
|
90
|
+
problems.push(`${fileOf(id)} already exists and isn't in ${SITE_FILE}. Move it, or add it to ${SITE_FILE} by hand.`);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
pages.push({ recipe: id, version: r.version, path: r.path, access: r.area === "legal" ? "public" : r.area, frame: r.frames[0], file: fileOf(id), state: "built" });
|
|
94
|
+
}
|
|
95
|
+
if (problems.length)
|
|
96
|
+
return fail();
|
|
97
|
+
const writes = {};
|
|
98
|
+
const pathOf = (id) => pages.find((p) => p.recipe === id)?.path;
|
|
99
|
+
for (const id of added)
|
|
100
|
+
writes[fileOf(id)] = pageFile(byId.get(id), o.version, base, pathOf);
|
|
101
|
+
// The helper is the project's once written, but a copy no one changed takes the newest.
|
|
102
|
+
const helper = o.read("src/pages/site.ts");
|
|
103
|
+
if (helper === undefined || (helper !== SITE_HELPER && PAST_HELPERS.has(fnv(helper))))
|
|
104
|
+
writes["src/pages/site.ts"] = SITE_HELPER;
|
|
105
|
+
writes["src/pages/index.ts"] = indexFile(pages);
|
|
106
|
+
writes["src/pages/nav.ts"] = navFile(pages, byId);
|
|
107
|
+
writes["test/pages.test.ts"] = testFile(base, pages);
|
|
108
|
+
// What the pages need besides their files: each written once, then the project's.
|
|
109
|
+
let forms = false;
|
|
110
|
+
const migrations = [];
|
|
111
|
+
const stamp = (o.now ?? new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
112
|
+
for (const id of added) {
|
|
113
|
+
const r = byId.get(id);
|
|
114
|
+
for (const [path, text] of Object.entries(r.files ?? {})) {
|
|
115
|
+
if (o.read(path) !== undefined || path in writes)
|
|
116
|
+
continue;
|
|
117
|
+
writes[path] = text;
|
|
118
|
+
if (path.startsWith("workbench/forms/"))
|
|
119
|
+
forms = true;
|
|
120
|
+
}
|
|
121
|
+
if (r.migration && !(o.list?.("supabase/migrations") ?? []).some((f) => f.endsWith(`_${r.migration.name}.sql`))) {
|
|
122
|
+
const name = `${stamp}_${r.migration.name}.sql`;
|
|
123
|
+
writes[`supabase/migrations/${name}`] = r.migration.up;
|
|
124
|
+
writes[`supabase/rollback/${name.replace(/\.sql$/, "_down.sql")}`] = `-- Reverses ${name}: drops only what it made.\n${r.migration.down}`;
|
|
125
|
+
migrations.push(`supabase/migrations/${name}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
writes[SITE_FILE] = `${JSON.stringify({ format: 1, pages }, null, 2)}\n`;
|
|
129
|
+
// The words: new keys go at the end; a word the project already has stays as it is.
|
|
130
|
+
const stringsPath = `strings/strings.${base}.json`;
|
|
131
|
+
let strings;
|
|
132
|
+
try {
|
|
133
|
+
strings = readJson(o.read, stringsPath) ?? {};
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
problems.push(`${stringsPath} isn't valid JSON: ${e.message}`);
|
|
137
|
+
return fail();
|
|
138
|
+
}
|
|
139
|
+
const words = { ...strings };
|
|
140
|
+
for (const id of added) {
|
|
141
|
+
const r = byId.get(id);
|
|
142
|
+
for (const k of recipeKeys(r))
|
|
143
|
+
if (!(k in words))
|
|
144
|
+
words[k] = r.words[k];
|
|
145
|
+
}
|
|
146
|
+
writes[stringsPath] = `${JSON.stringify(words, null, 2)}\n`;
|
|
147
|
+
// The dependency the page files import.
|
|
148
|
+
let pkg;
|
|
149
|
+
try {
|
|
150
|
+
pkg = readJson(o.read, "package.json") ?? {};
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
problems.push(`package.json isn't valid JSON: ${e.message}`);
|
|
154
|
+
return fail();
|
|
155
|
+
}
|
|
156
|
+
const scripts = (pkg.scripts ?? {});
|
|
157
|
+
// A page that calls a newer tool than the project has raises it (the site helper needs workbench-ui 0.14.0).
|
|
158
|
+
const raised = {};
|
|
159
|
+
if (older(pkg.dependencies?.[UI] ?? "0.0.0", HELPER_UI))
|
|
160
|
+
raised[UI] = HELPER_UI;
|
|
161
|
+
for (const id of added) {
|
|
162
|
+
for (const [name, least] of Object.entries(byId.get(id).packages ?? {})) {
|
|
163
|
+
const have = pkg.dependencies?.[name];
|
|
164
|
+
if (!have || older(have, raised[name] ?? least))
|
|
165
|
+
raised[name] = raised[name] && !older(raised[name], least) ? raised[name] : least;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (!pkg.dependencies?.[PACKAGE] || !scripts["check:site"] || Object.keys(raised).length) {
|
|
169
|
+
const deps = { ...(pkg.dependencies ?? {}), ...raised, [PACKAGE]: pkg.dependencies?.[PACKAGE] ?? o.version };
|
|
170
|
+
pkg.dependencies = Object.fromEntries(Object.entries(deps).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
171
|
+
pkg.scripts = { ...scripts, "check:site": "workbench-site check" };
|
|
172
|
+
writes["package.json"] = `${JSON.stringify(pkg, null, 2)}\n`;
|
|
173
|
+
}
|
|
174
|
+
// Leave out what wouldn't change, so the CLI reports only real writes.
|
|
175
|
+
for (const [path, text] of Object.entries(writes))
|
|
176
|
+
if (o.read(path) === text)
|
|
177
|
+
delete writes[path];
|
|
178
|
+
return { writes, added, already, problems, migrations, forms };
|
|
179
|
+
}
|
|
180
|
+
/** The code for one section, as the page file calls it. */
|
|
181
|
+
function sectionCode(s, pathOf, self) {
|
|
182
|
+
const w = (k) => `w(${JSON.stringify(k)})`;
|
|
183
|
+
const act = (a) => {
|
|
184
|
+
const href = a.to.startsWith("/") ? a.to : pathOf(a.to);
|
|
185
|
+
return typeof href === "string" ? `{ label: ${w(a.label)}, href: ${JSON.stringify(href)} }` : null;
|
|
186
|
+
};
|
|
187
|
+
const fields = [];
|
|
188
|
+
const add = (name, value) => {
|
|
189
|
+
if (value)
|
|
190
|
+
fields.push(`${name}: ${value}`);
|
|
191
|
+
};
|
|
192
|
+
switch (s.kind) {
|
|
193
|
+
case "hero":
|
|
194
|
+
add("heading", w(s.heading));
|
|
195
|
+
add("lead", s.lead && w(s.lead));
|
|
196
|
+
add("action", s.action && act(s.action));
|
|
197
|
+
if (s.arrangement && s.arrangement !== "plain")
|
|
198
|
+
add("arrangement", JSON.stringify(s.arrangement));
|
|
199
|
+
break;
|
|
200
|
+
case "text":
|
|
201
|
+
add("heading", s.heading && w(s.heading));
|
|
202
|
+
add("body", w(s.body));
|
|
203
|
+
break;
|
|
204
|
+
case "list":
|
|
205
|
+
add("heading", s.heading && w(s.heading));
|
|
206
|
+
add("items", `[\n${s.items.map((i) => ` { title: ${w(i.title)}${i.body ? `, body: ${w(i.body)}` : ""} },`).join("\n")}\n ]`);
|
|
207
|
+
break;
|
|
208
|
+
case "call": {
|
|
209
|
+
const a = act(s.action);
|
|
210
|
+
if (!a)
|
|
211
|
+
return null;
|
|
212
|
+
add("heading", w(s.heading));
|
|
213
|
+
add("body", s.body && w(s.body));
|
|
214
|
+
add("action", a);
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
case "details":
|
|
218
|
+
add("heading", s.heading && w(s.heading));
|
|
219
|
+
add("rows", `[\n${s.rows.map((r) => ` { label: ${w(r.label)}, value: ${w(r.value)} },`).join("\n")}\n ]`);
|
|
220
|
+
break;
|
|
221
|
+
case "account":
|
|
222
|
+
add("heading", s.heading && w(s.heading));
|
|
223
|
+
add("signedIn", `w(${JSON.stringify(s.signedIn)}, { email: ctx.user?.email ?? "" })`);
|
|
224
|
+
add("signOut", w(s.signOut));
|
|
225
|
+
break;
|
|
226
|
+
case "admin-menu":
|
|
227
|
+
add("heading", s.heading && w(s.heading));
|
|
228
|
+
add("items", `ADMIN_MENU.filter(([, href]) => href !== ${JSON.stringify(self)}).map(([label, href, about]) => ({ title: w(label), href, body: w(about) }))`);
|
|
229
|
+
break;
|
|
230
|
+
case "enquiry-form":
|
|
231
|
+
add("heading", w(s.heading));
|
|
232
|
+
add("intro", s.intro && w(s.intro));
|
|
233
|
+
add("send", JSON.stringify(s.send));
|
|
234
|
+
add("sent", w(s.sent));
|
|
235
|
+
add("unavailable", w(s.unavailable));
|
|
236
|
+
return `enquirySection(request, env, ctx, { ${fields.join(", ")} })`;
|
|
237
|
+
case "enquiries":
|
|
238
|
+
add("heading", s.heading && w(s.heading));
|
|
239
|
+
add("empty", w(s.empty));
|
|
240
|
+
add("unavailable", w(s.unavailable));
|
|
241
|
+
add("remove", w(s.remove));
|
|
242
|
+
return `enquiriesSection(request, enquiries, { ${fields.join(", ")} })`;
|
|
243
|
+
case "style-guide":
|
|
244
|
+
for (const k of ["views", "light", "dark", "admin", "empty", "layout"])
|
|
245
|
+
add(k, w(s[k]));
|
|
246
|
+
return `styleGuide(SAMPLES, { view, words: { ${fields.join(", ")} } })`;
|
|
247
|
+
case "design-switch":
|
|
248
|
+
for (const k of ["on", "off", "turnOn", "turnOff", "live"])
|
|
249
|
+
add(k, w(s[k]));
|
|
250
|
+
return `designSwitch({ on: designModeOn(request), live: appConfig(env).WORKBENCH_ENV === "production", words: { ${fields.join(", ")} } })`;
|
|
251
|
+
case "look-preview":
|
|
252
|
+
for (const k of ["pages", "schemes", "light", "dark", "yours", "inUse", "open", "live"])
|
|
253
|
+
add(k, w(s[k]));
|
|
254
|
+
return `lookPreview({ pages: [{ path: "/", label: ${w(s.home)} }, ...MENU.filter(([, href]) => href !== "/").slice(0, 2).map(([label, path]) => ({ path, label: w(label) }))], url: request.url, current: BRAND.look ?? "clean", live: appConfig(env).WORKBENCH_ENV === "production", words: { ${fields.join(", ")} } })`;
|
|
255
|
+
}
|
|
256
|
+
return `${SECTION_FUNCTIONS[s.kind]}({ ${fields.join(", ")} })`;
|
|
257
|
+
}
|
|
258
|
+
/** The site helper reads src/site-layout.generated.ts, which workbench-ui writes from this version. */
|
|
259
|
+
const UI = "@mccaskie-labs/workbench-ui";
|
|
260
|
+
const HELPER_UI = "0.14.0";
|
|
261
|
+
/** True when the version a project asks for (x.y.z, or a ^ or ~ range of one) is older than `least`. */
|
|
262
|
+
function older(have, least) {
|
|
263
|
+
const v = (x) => (/(\d+)\.(\d+)\.(\d+)/.exec(x) ?? [, "0", "0", "0"]).slice(1).map(Number);
|
|
264
|
+
const [a, b] = [v(have), v(least)];
|
|
265
|
+
for (let i = 0; i < 3; i += 1)
|
|
266
|
+
if (a[i] !== b[i])
|
|
267
|
+
return a[i] < b[i];
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
/** The style guide's own sheet, which workbench-ui's styles command writes (both schemes of the project's look). */
|
|
271
|
+
const GUIDE_SHEET = "/styles/style-guide.css";
|
|
272
|
+
function pageFile(r, version, base, pathOf) {
|
|
273
|
+
const sections = r.sections.map((s) => [s, sectionCode(s, pathOf, r.path)]).filter((x) => x[1] !== null);
|
|
274
|
+
const used = [...new Set([...sections.filter(([s]) => !STORE_SECTIONS.has(s.kind) && !UI_SECTIONS.has(s.kind)).map(([s]) => SECTION_FUNCTIONS[s.kind]), ...(sections.some(([s]) => s.kind === "design-switch") ? ["designModeOn", "designModePost"] : [])])].sort();
|
|
275
|
+
const guide = sections.some(([s]) => s.kind === "style-guide");
|
|
276
|
+
const form = sections.some(([s]) => s.kind === "enquiry-form");
|
|
277
|
+
const list = sections.some(([s]) => s.kind === "enquiries");
|
|
278
|
+
const store = [...(form ? ["enquirySection", "takeEnquiry"] : []), ...(list ? ["enquiriesSection", "listEnquiries", "removeEnquiry"] : [])].sort();
|
|
279
|
+
const usesCtx = sections.some(([s]) => s.kind === "account" || s.kind === "enquiry-form") || list;
|
|
280
|
+
const usesMenu = sections.some(([s]) => s.kind === "admin-menu");
|
|
281
|
+
const looks = sections.some(([s]) => s.kind === "look-preview");
|
|
282
|
+
const design = sections.some(([s]) => s.kind === "design-switch");
|
|
283
|
+
const block = list || guide;
|
|
284
|
+
const area = r.area === "members" || r.area === "admin" ? `, area: ${JSON.stringify(r.area)}` : "";
|
|
285
|
+
const prefix = `page.${r.id.replace(/-/g, "_")}.`;
|
|
286
|
+
const frame = r.frames[0];
|
|
287
|
+
const others = r.frames.slice(1);
|
|
288
|
+
const lines = [
|
|
289
|
+
`// ${r.title}: built by Workbench from the "${r.id}" recipe (${PACKAGE} ${version}, recipe version ${r.version}).`,
|
|
290
|
+
`// ${r.does}`,
|
|
291
|
+
"//",
|
|
292
|
+
"// This page is the project's own now: change its sections, their order, its",
|
|
293
|
+
`// frame ("${frame}"${others.length ? `; it also suits ${others.map((f) => `"${f}"`).join(", ")}` : ""}) or its words (${prefix}* in`,
|
|
294
|
+
`// strings/strings.${base}.json). Words in [square brackets] are the owner's to`,
|
|
295
|
+
"// fill in. Once you change this file, set its state in workbench/site.json to",
|
|
296
|
+
'// "changed", and Workbench never writes over it.',
|
|
297
|
+
"",
|
|
298
|
+
`import { ${used.join(", ")} } from "${PACKAGE}";`,
|
|
299
|
+
...(store.length ? [`import { ${store.join(", ")} } from "./enquiry-store.ts";`] : []),
|
|
300
|
+
...(guide ? [`import { guideView, styleGuide } from "@mccaskie-labs/workbench-ui";`, `import { SAMPLES } from "../samples.generated.ts";`] : []),
|
|
301
|
+
...(looks ? [`import { lookPreview } from "@mccaskie-labs/workbench-ui";`] : []),
|
|
302
|
+
...(looks || design ? [`import { appConfig } from "../config.ts";`] : []),
|
|
303
|
+
...(looks ? [`import { BRAND } from "../lib/brand.ts";`] : []),
|
|
304
|
+
...(usesMenu || looks ? [`import { ${[...(usesMenu ? ["ADMIN_MENU"] : []), ...(looks ? ["MENU"] : [])].join(", ")} } from "./nav.ts";`] : []),
|
|
305
|
+
`import { sitePage, type SitePage } from "./site.ts";`,
|
|
306
|
+
"",
|
|
307
|
+
`export const ${camel(r.id)}: SitePage = {`,
|
|
308
|
+
` recipe: ${JSON.stringify(r.id)},`,
|
|
309
|
+
` path: ${JSON.stringify(r.path)},`,
|
|
310
|
+
` access: ${JSON.stringify(r.area === "legal" ? "public" : r.area)},`,
|
|
311
|
+
...(list
|
|
312
|
+
? [" render: async (request, env, ctx) => {", " const enquiries = await listEnquiries(env, ctx);"]
|
|
313
|
+
: guide
|
|
314
|
+
? [" render: (request, env) => {", " // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"]
|
|
315
|
+
: [` render: (request, env${usesCtx ? ", ctx" : ""}) =>`]),
|
|
316
|
+
` ${block ? "return " : ""}sitePage(request, env, { frame: ${JSON.stringify(frame)}, title: ${JSON.stringify(r.pageTitle)}${r.status && r.status !== 200 ? `, status: ${r.status}` : ""}${area}${guide ? `, view, stylesheets: [${JSON.stringify(GUIDE_SHEET)}]` : ""} }, (w) => [`,
|
|
317
|
+
...sections.map(([, code]) => ` ${code},`),
|
|
318
|
+
block ? " ]);\n }," : " ]),",
|
|
319
|
+
...(form ? [` // The form's POST: checked, stored, then back to the thank-you.`, ` post: (request, env, ctx) => takeEnquiry(request, env, ctx, ${camel(r.id)}),`] : []),
|
|
320
|
+
...(design ? [" // The switch's POST: turns design mode on or off in this browser, never on the live site.", ' post: (request, env) => designModePost(request, appConfig(env).WORKBENCH_ENV === "production"),'] : []),
|
|
321
|
+
...(list ? [" // A delete button's POST.", " post: (request, env, ctx) => removeEnquiry(request, env, ctx),"] : []),
|
|
322
|
+
"};",
|
|
323
|
+
"",
|
|
324
|
+
];
|
|
325
|
+
return lines.join("\n");
|
|
326
|
+
}
|
|
327
|
+
function indexFile(pages) {
|
|
328
|
+
const sorted = [...pages].sort((a, b) => (a.recipe < b.recipe ? -1 : a.recipe > b.recipe ? 1 : 0));
|
|
329
|
+
const members = pages.some((p) => p.access !== "public");
|
|
330
|
+
const admin = pages.some((p) => p.access === "admin");
|
|
331
|
+
return [
|
|
332
|
+
`// Generated by ${PACKAGE} from workbench/site.json: \`npx workbench-site add <page>\``,
|
|
333
|
+
"// rewrites it. Each page's own file is the project's. src/index.ts hands",
|
|
334
|
+
"// every request the app's own routes didn't answer to sitePages, and one no",
|
|
335
|
+
"// page answers to notFoundPage. A page's access is checked here, before it",
|
|
336
|
+
"// is drawn: members pages need the app's sign-in, admin pages one of the",
|
|
337
|
+
"// app's admins (the same check as Brand settings).",
|
|
338
|
+
"",
|
|
339
|
+
...(admin ? [`import { brandStore } from "../lib/brand.ts";`] : []),
|
|
340
|
+
...(members ? [`import { requireUser } from "../lib/session.ts";`] : []),
|
|
341
|
+
`import type { SitePage } from "./site.ts";`,
|
|
342
|
+
...sorted.map((p) => `import { ${camel(p.recipe)} } from "./${p.recipe}.ts";`),
|
|
343
|
+
"",
|
|
344
|
+
"/** Every page Workbench built for the site (workbench/site.json). */",
|
|
345
|
+
`export const PAGES: readonly SitePage[] = [${sorted.map((p) => camel(p.recipe)).join(", ")}];`,
|
|
346
|
+
"",
|
|
347
|
+
"/** The page at this address, for GET and HEAD, and POST to a page with a form; null to fall through. */",
|
|
348
|
+
"export async function sitePages(request: Request, env: Env, url: URL): Promise<Response | null> {",
|
|
349
|
+
" const page = PAGES.find((p) => p.path === url.pathname);",
|
|
350
|
+
" if (!page) return null;",
|
|
351
|
+
' if (request.method === "GET" || request.method === "HEAD") return serve(page, request, env);',
|
|
352
|
+
' if (request.method === "POST" && page.post) return serve(page, request, env);',
|
|
353
|
+
" return null;",
|
|
354
|
+
"}",
|
|
355
|
+
"",
|
|
356
|
+
"/** The page shown when no other answers (its status is 404); null when the site has none. */",
|
|
357
|
+
"export async function notFoundPage(request: Request, env: Env, _url: URL): Promise<Response | null> {",
|
|
358
|
+
" const page = PAGES.find((p) => p.path === null);",
|
|
359
|
+
' if (!page || (request.method !== "GET" && request.method !== "HEAD")) return null;',
|
|
360
|
+
" return serve(page, request, env);",
|
|
361
|
+
"}",
|
|
362
|
+
"",
|
|
363
|
+
"/** Checks who may open the page, then draws it, or takes its form's POST. */",
|
|
364
|
+
"async function serve(page: SitePage, request: Request, env: Env): Promise<Response> {",
|
|
365
|
+
' const answer = request.method === "POST" && page.post ? page.post.bind(page) : page.render.bind(page);',
|
|
366
|
+
...(members
|
|
367
|
+
? [
|
|
368
|
+
' if (page.access === "public") return answer(request, env, { user: null });',
|
|
369
|
+
" // Signed out, sent to sign in; a POST from another site, refused.",
|
|
370
|
+
" const s = await requireUser(request, env);",
|
|
371
|
+
" if (s instanceof Response) return s;",
|
|
372
|
+
...(admin
|
|
373
|
+
? [
|
|
374
|
+
' if (page.access === "admin") {',
|
|
375
|
+
" let admin: boolean;",
|
|
376
|
+
" try {",
|
|
377
|
+
" admin = await brandStore.claim(env, s.accessToken, s.user, s.fresh);",
|
|
378
|
+
" } catch (e) {",
|
|
379
|
+
' console.warn(JSON.stringify({ event: "site_admin_check_failed", error: e instanceof Error ? e.message : "read failed" }));',
|
|
380
|
+
' return s.finish(text("This page can\'t be checked right now. Try again in a minute.", 503));',
|
|
381
|
+
" }",
|
|
382
|
+
' if (!admin) return s.finish(text("Only the site\'s admins can open this page.", 403));',
|
|
383
|
+
" }",
|
|
384
|
+
]
|
|
385
|
+
: []),
|
|
386
|
+
" return s.finish(await answer(request, env, { user: s.user, accessToken: s.accessToken }));",
|
|
387
|
+
]
|
|
388
|
+
: [" return answer(request, env, { user: null });"]),
|
|
389
|
+
"}",
|
|
390
|
+
...(admin ? ["", 'const text = (body: string, status: number) => new Response(`${body}\\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } });'] : []),
|
|
391
|
+
"",
|
|
392
|
+
].join("\n");
|
|
393
|
+
}
|
|
394
|
+
function navFile(pages, byId) {
|
|
395
|
+
const entries = (place) => pages
|
|
396
|
+
.map((p) => ({ p, menu: byId.get(p.recipe)?.menu }))
|
|
397
|
+
.filter((x) => x.p.path !== null && x.menu?.[place] !== undefined)
|
|
398
|
+
.sort((a, b) => a.menu[place] - b.menu[place])
|
|
399
|
+
.map(({ p, menu }) => ` [${JSON.stringify(menu.label)}, ${JSON.stringify(p.path)}],`);
|
|
400
|
+
const admin = [
|
|
401
|
+
...pages.flatMap((p) => {
|
|
402
|
+
const m = byId.get(p.recipe)?.menu;
|
|
403
|
+
return p.path !== null && m?.admin !== undefined && m.about ? [{ order: m.admin, label: m.label, href: p.path, about: m.about }] : [];
|
|
404
|
+
}),
|
|
405
|
+
...pages.flatMap((p) => (byId.get(p.recipe)?.links ?? []).map((l) => ({ order: l.admin, label: l.label, href: l.href, about: l.about }))),
|
|
406
|
+
]
|
|
407
|
+
.sort((a, b) => a.order - b.order)
|
|
408
|
+
.map((l) => ` [${JSON.stringify(l.label)}, ${JSON.stringify(l.href)}, ${JSON.stringify(l.about)}],`);
|
|
409
|
+
const list = (lines) => (lines.length ? `[\n${lines.join("\n")}\n]` : "[]");
|
|
410
|
+
return [
|
|
411
|
+
`// Generated by ${PACKAGE} from workbench/site.json and its recipes: \`npx workbench-site add <page>\``,
|
|
412
|
+
"// rewrites it. The site's links, each a word's key and an address.",
|
|
413
|
+
"",
|
|
414
|
+
"/** The header's links, in order. */",
|
|
415
|
+
`export const MENU: readonly (readonly [string, string])[] = ${list(entries("header"))};`,
|
|
416
|
+
"",
|
|
417
|
+
"/** The footer's links, in order. */",
|
|
418
|
+
`export const FOOTER: readonly (readonly [string, string])[] = ${list(entries("footer"))};`,
|
|
419
|
+
"",
|
|
420
|
+
"/** The admin pages' links, in order, each with a line on what it's for. Admin pages show these in their header. */",
|
|
421
|
+
`export const ADMIN_MENU: readonly (readonly [string, string, string])[] = ${list(admin)};`,
|
|
422
|
+
"",
|
|
423
|
+
].join("\n");
|
|
424
|
+
}
|
|
425
|
+
function testFile(base, pages) {
|
|
426
|
+
const enquiries = pages.some((p) => p.recipe === "enquiries");
|
|
427
|
+
const form = pages.find((p) => p.access === "public" && p.path !== null && p.recipe === "contact");
|
|
428
|
+
const guide = pages.find((p) => p.recipe === "style-guide" && p.path !== null);
|
|
429
|
+
return `// Generated by ${PACKAGE}: every page in workbench/site.json answers, in
|
|
430
|
+
// production to whoever its access allows and on staging only to the owner,
|
|
431
|
+
// in the project's look, with each of its words from the catalogue; and
|
|
432
|
+
// workbench/site.json matches the page files (check:site).
|
|
433
|
+
|
|
434
|
+
import { siteProblems } from "${PACKAGE}";
|
|
435
|
+
import { ${enquiries ? "beforeEach, " : ""}describe, expect, it${enquiries ? ", vi" : ""} } from "vitest";
|
|
436
|
+
import worker from "../src/index.ts";
|
|
437
|
+
${enquiries ? 'import { enquiryStore } from "../src/pages/enquiry-store.ts";\n' : ""}import { PAGES } from "../src/pages/index.ts";
|
|
438
|
+
import { SITE_LAYOUT as LAYOUT } from "../src/site-layout.generated.ts";
|
|
439
|
+
import site from "../workbench/site.json";
|
|
440
|
+
import strings from "../strings/strings.${base}.json";
|
|
441
|
+
import { AUD, accessToken, useTestTeam } from "./access-token.ts";
|
|
442
|
+
import { FAKE, testEnv } from "./helpers.ts";
|
|
443
|
+
|
|
444
|
+
const get = (path: string, env: Env, headers: Record<string, string> = {}) =>
|
|
445
|
+
worker.fetch(new Request(\`https://example.com\${path}\`, { headers, redirect: "manual" }) as Parameters<typeof worker.fetch>[0], env);
|
|
446
|
+
const SESSION_SECRET = "s".repeat(43);
|
|
447
|
+
const production = () => testEnv({ WORKBENCH_ENV: "production", WORKBENCH_GATEWAY_KEY: FAKE.prdKey, ACCESS_AUD: AUD, SESSION_SECRET });
|
|
448
|
+
const staging = () => testEnv({ WORKBENCH_ENV: "staging", WORKBENCH_GATEWAY_KEY: FAKE.stgKey, ACCESS_AUD: AUD, SESSION_SECRET });
|
|
449
|
+
const MISSING = "/no-page-is-here-" + "x".repeat(8);
|
|
450
|
+
const files = import.meta.glob<string>("../src/pages/*.ts", { query: "?raw", import: "default", eager: true });
|
|
451
|
+
|
|
452
|
+
describe("site pages", () => {
|
|
453
|
+
${enquiries ? " // The enquiries table isn't reached: each test says what it holds.\n beforeEach(() => void vi.spyOn(enquiryStore, \"list\").mockResolvedValue([]));\n\n" : ""} it("workbench/site.json matches the page files and the strings catalogue (check:site)", () => {
|
|
454
|
+
const byPath = Object.fromEntries(Object.entries(files).map(([path, text]) => [path.replace(/^\\.\\.\\//, ""), text]));
|
|
455
|
+
expect(siteProblems({ site, strings, files: byPath })).toEqual([]);
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
for (const page of PAGES) {
|
|
459
|
+
const path = page.path ?? MISSING;
|
|
460
|
+
it(\`\${page.recipe} draws in the project's look\`, async () => {
|
|
461
|
+
const user = page.access === "public" ? null : { id: "user-1", email: "sam@example.com" };
|
|
462
|
+
const res = await page.render(new Request(\`https://example.com\${path}\`), production(), user ? { user, accessToken: "token" } : { user });
|
|
463
|
+
expect(res.status).toBe(page.path === null ? 404 : 200);
|
|
464
|
+
expect(res.headers.get("content-type")).toContain("text/html");
|
|
465
|
+
const html = await res.text();
|
|
466
|
+
expect(html).toMatch(/<html [^>]*class="wb-site[ "]/);
|
|
467
|
+
// One h1, the page's own (the style guide's samples come after it, and may show one).
|
|
468
|
+
expect(html.split('<div class="wb-ui-guide">')[0]!.match(/<h1[ >]/g)?.length).toBe(1);
|
|
469
|
+
// A word that's missing shows as "undefined" (the scripts a form brings may say it).
|
|
470
|
+
expect(html.replace(/<script[^>]*>[\\s\\S]*?<\\/script>/g, "")).not.toContain("undefined");
|
|
471
|
+
if (page.access !== "public") expect(html).toContain('<meta name="robots" content="noindex">');
|
|
472
|
+
// In the site layout brand.json names (or its look's), as workbench-ui styles wrote it.
|
|
473
|
+
expect(html).toContain(\`data-header="\${LAYOUT.header}"\`);
|
|
474
|
+
expect(html).toContain(\`data-footer="\${LAYOUT.footer}"\`);
|
|
475
|
+
// The style guide opens on the public look; its switch shows the admin one.
|
|
476
|
+
expect(html.includes("wb-ui-admin")).toBe(page.access === "admin" && page.recipe !== "style-guide");
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
it(\`\${page.recipe} answers at \${path} to whoever may open it\`, async () => {
|
|
480
|
+
const res = await get(path, production());
|
|
481
|
+
if (page.access === "public") expect(res.status).toBe(page.path === null ? 404 : 200);
|
|
482
|
+
else {
|
|
483
|
+
// Signed out: sent to sign in, and back here afterwards.
|
|
484
|
+
expect(res.status).toBe(303);
|
|
485
|
+
expect(res.headers.get("location")).toBe(\`/sign-in?next=\${encodeURIComponent(path)}\`);
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
it(\`\${page.recipe} is owner-only on staging\`, async () => {
|
|
490
|
+
useTestTeam();
|
|
491
|
+
expect((await get(path, staging())).status).toBe(403);
|
|
492
|
+
const res = await get(path, staging(), { "Cf-Access-Jwt-Assertion": await accessToken() });
|
|
493
|
+
expect(res.status).toBe(page.access !== "public" ? 303 : page.path === null ? 404 : 200);
|
|
494
|
+
expect(res.headers.get("cache-control")).toBe("private, no-store");
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
${enquiries && form ? enquiryTests(form.path) : ""}${guide ? guideTests(guide.path) : ""}`;
|
|
499
|
+
}
|
|
500
|
+
/** The style guide's own tests, when the site has it. */
|
|
501
|
+
function guideTests(path) {
|
|
502
|
+
return `
|
|
503
|
+
describe("style guide", () => {
|
|
504
|
+
const page = PAGES.find((p) => p.recipe === "style-guide")!;
|
|
505
|
+
const draw = async (query: string) =>
|
|
506
|
+
(await page.render(new Request(\`https://example.com${path}\${query}\`), production(), { user: { id: "user-1", email: "sam@example.com" }, accessToken: "token" })).text();
|
|
507
|
+
|
|
508
|
+
it("shows the public look in light or dark, or the admin look, from its switch", async () => {
|
|
509
|
+
const light = await draw("");
|
|
510
|
+
expect(light).toContain('data-wb-scheme="light"');
|
|
511
|
+
expect(light).toContain('href="${GUIDE_SHEET}"');
|
|
512
|
+
expect(await draw("?view=dark")).toContain('data-wb-scheme="dark"');
|
|
513
|
+
const admin = await draw("?view=admin");
|
|
514
|
+
expect(admin).toContain("wb-ui-admin");
|
|
515
|
+
expect(admin).not.toContain("data-wb-scheme");
|
|
516
|
+
expect(await draw("?view=<script>")).toContain('data-wb-scheme="light"');
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
it("draws every tool's samples, whose forms do nothing", async () => {
|
|
520
|
+
const html = await draw("");
|
|
521
|
+
expect(html).toContain("wb-ui-guide");
|
|
522
|
+
for (const form of html.match(/<form\\b[^>]*>/g) ?? []) {
|
|
523
|
+
if (!form.includes("wb-site-")) expect(form).toMatch(/method="get" action=""/);
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
`;
|
|
528
|
+
}
|
|
529
|
+
/** The enquiry form's and list's own tests, when the site has them. */
|
|
530
|
+
function enquiryTests(path) {
|
|
531
|
+
return `
|
|
532
|
+
describe("enquiries", () => {
|
|
533
|
+
const dev = () => testEnv({ SESSION_SECRET });
|
|
534
|
+
const post = (body: Record<string, string>, origin = "https://example.com") =>
|
|
535
|
+
worker.fetch(new Request(\`https://example.com${path}\`, { method: "POST", body: new URLSearchParams(body), headers: { origin, "content-type": "application/x-www-form-urlencoded" }, redirect: "manual" }) as Parameters<typeof worker.fetch>[0], dev());
|
|
536
|
+
const good = { name: "Sam Lee", email: "sam@example.com", phone: "", message: "Do you open on Sundays?" };
|
|
537
|
+
|
|
538
|
+
it("the contact page has the form", async () => {
|
|
539
|
+
const html = await (await get(${JSON.stringify(path)}, dev())).text();
|
|
540
|
+
expect(html).toContain('id="enquiry"');
|
|
541
|
+
expect(html).toContain('name="message"');
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
it("a sent enquiry is stored, and the person sees the thank-you", async () => {
|
|
545
|
+
const send = vi.spyOn(enquiryStore, "send").mockResolvedValue(true);
|
|
546
|
+
const res = await post(good);
|
|
547
|
+
expect(res.status).toBe(303);
|
|
548
|
+
expect(res.headers.get("location")).toBe(${JSON.stringify(`${path}?sent=1#enquiry`)});
|
|
549
|
+
expect(send).toHaveBeenCalledWith(expect.anything(), { name: "Sam Lee", email: "sam@example.com", phone: null, message: "Do you open on Sundays?" });
|
|
550
|
+
const thanks = await (await get(${JSON.stringify(`${path}?sent=1`)}, dev())).text();
|
|
551
|
+
expect(thanks).toContain("wb-site-done");
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
it("an enquiry with a problem is shown again, not stored", async () => {
|
|
555
|
+
const send = vi.spyOn(enquiryStore, "send").mockResolvedValue(true);
|
|
556
|
+
const res = await post({ ...good, message: "" });
|
|
557
|
+
expect(res.status).toBe(422);
|
|
558
|
+
expect(await res.text()).toContain("Sam Lee");
|
|
559
|
+
expect(send).not.toHaveBeenCalled();
|
|
560
|
+
});
|
|
561
|
+
|
|
562
|
+
it("when the database doesn't take it, the person is told", async () => {
|
|
563
|
+
vi.spyOn(enquiryStore, "send").mockResolvedValue(false);
|
|
564
|
+
const res = await post(good);
|
|
565
|
+
expect(res.status).toBe(503);
|
|
566
|
+
expect(await res.text()).toContain("wb-site-problem");
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
it("a form posted from another site is refused", async () => {
|
|
570
|
+
const send = vi.spyOn(enquiryStore, "send").mockResolvedValue(true);
|
|
571
|
+
expect((await post(good, "https://elsewhere.example")).status).toBe(403);
|
|
572
|
+
expect(send).not.toHaveBeenCalled();
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
it("outside development, an enquiry needs the Turnstile check", async () => {
|
|
576
|
+
const send = vi.spyOn(enquiryStore, "send").mockResolvedValue(true);
|
|
577
|
+
const res = await worker.fetch(new Request(\`https://example.com${path}\`, { method: "POST", body: new URLSearchParams(good), headers: { origin: "https://example.com" }, redirect: "manual" }) as Parameters<typeof worker.fetch>[0], production());
|
|
578
|
+
expect(res.status).toBe(503);
|
|
579
|
+
expect(send).not.toHaveBeenCalled();
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
it("the Enquiries page lists them for the site's admins", async () => {
|
|
583
|
+
vi.spyOn(enquiryStore, "list").mockResolvedValue([{ id: "00000000-0000-4000-8000-000000000001", name: "Sam <Lee>", email: "sam@example.com", phone: "+61400000000", message: "Hello", received_at: "2026-11-24T01:00:00Z" }]);
|
|
584
|
+
const page = PAGES.find((p) => p.recipe === "enquiries")!;
|
|
585
|
+
const html = await (await page.render(new Request("https://example.com/admin/enquiries"), production(), { user: { id: "user-1", email: "a@example.com" }, accessToken: "token" })).text();
|
|
586
|
+
expect(html).toContain("Sam <Lee>");
|
|
587
|
+
expect(html).toContain('href="mailto:sam@example.com"');
|
|
588
|
+
expect(html).toContain('name="remove" value="00000000-0000-4000-8000-000000000001"');
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
it("the Enquiries page says so when they can't be read", async () => {
|
|
592
|
+
vi.spyOn(enquiryStore, "list").mockResolvedValue(null);
|
|
593
|
+
const page = PAGES.find((p) => p.recipe === "enquiries")!;
|
|
594
|
+
const html = await (await page.render(new Request("https://example.com/admin/enquiries"), production(), { user: { id: "user-1", email: "a@example.com" }, accessToken: "token" })).text();
|
|
595
|
+
expect(html).toContain("wb-site-problem");
|
|
596
|
+
});
|
|
597
|
+
});
|
|
598
|
+
`;
|
|
599
|
+
}
|
|
600
|
+
/** src/pages/site.ts: written once, then the project's. */
|
|
601
|
+
/** Each helper an earlier workbench-site wrote, by its FNV-1a hash: a project still holding one unchanged gets the newest. */
|
|
602
|
+
const PAST_HELPERS = new Set(["dcf7ed6a", "ccd7d6a5", "c1d44c4f", "ffc5d608", "ee2ade9e", "9ee82f4f"]);
|
|
603
|
+
/** FNV-1a, 32 bits: enough to know a file is one of a few texts, never a check of who wrote it. */
|
|
604
|
+
function fnv(s) {
|
|
605
|
+
let h = 0x811c9dc5;
|
|
606
|
+
for (let i = 0; i < s.length; i += 1)
|
|
607
|
+
h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0;
|
|
608
|
+
return h.toString(16).padStart(8, "0");
|
|
609
|
+
}
|
|
610
|
+
const SITE_HELPER = `// The parts every site page shares: its words, its frame, its header and
|
|
611
|
+
// footer, and its answer. Written by ${PACKAGE} once; it's the project's to
|
|
612
|
+
// change (the page files and src/pages/index.ts call it).
|
|
613
|
+
|
|
614
|
+
import { designModeOn, frame, type FrameLayout, type FrameName } from "${PACKAGE}";
|
|
615
|
+
import { DESIGN_FILE, previewAttributes, resolveSiteLayout, STYLESHEETS } from "@mccaskie-labs/workbench-ui";
|
|
616
|
+
import { appConfig } from "../config.ts";
|
|
617
|
+
import { beacon } from "../lib/analytics.ts";
|
|
618
|
+
import { BRAND } from "../lib/brand.ts";
|
|
619
|
+
import { stringsFor } from "../lib/strings.ts";
|
|
620
|
+
import { SITE_LAYOUT } from "../site-layout.generated.ts";
|
|
621
|
+
import { ADMIN_MENU, FOOTER, MENU } from "./nav.ts";
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* The site layout's header and footer: brand.json's \`layout\`, else its look's,
|
|
625
|
+
* from workbench-ui's library or workbench/looks/, as \`npx workbench-ui styles\`
|
|
626
|
+
* wrote it (its width and spacing are in workbench.css).
|
|
627
|
+
*/
|
|
628
|
+
const LAYOUT: FrameLayout = { header: SITE_LAYOUT.header, footer: SITE_LAYOUT.footer };
|
|
629
|
+
|
|
630
|
+
/** A previewed look's own header and footer (the look previewer, /admin/look); the site's for a look only the project knows. */
|
|
631
|
+
function previewLayout(look: string): FrameLayout {
|
|
632
|
+
try {
|
|
633
|
+
const l = resolveSiteLayout({ look });
|
|
634
|
+
return { header: l.header, footer: l.footer };
|
|
635
|
+
} catch {
|
|
636
|
+
return LAYOUT;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Who is asking: the signed-in user on a members or admin page, otherwise null. */
|
|
641
|
+
export interface PageContext {
|
|
642
|
+
user: { id: string; email: string } | null;
|
|
643
|
+
/** Theirs, for the database as them (RLS): members and admin pages. */
|
|
644
|
+
accessToken?: string;
|
|
645
|
+
/** A form's state after a submit that didn't go through, for the page to draw again. */
|
|
646
|
+
form?: unknown;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** One page of the site. */
|
|
650
|
+
export interface SitePage {
|
|
651
|
+
/** The recipe it was built from (workbench/site.json). */
|
|
652
|
+
recipe: string;
|
|
653
|
+
/** Its address; null for the page shown when no other answers. */
|
|
654
|
+
path: string | null;
|
|
655
|
+
/** Who may open it, checked by src/pages/index.ts before it is drawn. */
|
|
656
|
+
access: "public" | "members" | "admin";
|
|
657
|
+
render(request: Request, env: Env, ctx: PageContext): Response | Promise<Response>;
|
|
658
|
+
/** Its form's POST, checked for access like the page. */
|
|
659
|
+
post?(request: Request, env: Env, ctx: PageContext): Promise<Response>;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Looks up one of the page's words in the visitor's language, with any values it says. */
|
|
663
|
+
export type Words = (key: string, values?: Record<string, string>) => string;
|
|
664
|
+
|
|
665
|
+
export interface PageOptions {
|
|
666
|
+
frame: FrameName;
|
|
667
|
+
/** The tab title's key. */
|
|
668
|
+
title: string;
|
|
669
|
+
/** Defaults to 200. */
|
|
670
|
+
status?: number;
|
|
671
|
+
/** Members and admin pages stay out of search engines; admin pages show the admin menu. */
|
|
672
|
+
area?: "members" | "admin";
|
|
673
|
+
/** The look to show instead of the page's own: the style guide's switch. Admin pages default to "admin". */
|
|
674
|
+
view?: "light" | "dark" | "admin";
|
|
675
|
+
/** Stylesheets after the site's own, such as the style guide's. */
|
|
676
|
+
stylesheets?: readonly string[];
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** A whole page: its sections, in its frame, with the site's header and footer. */
|
|
680
|
+
export function sitePage(request: Request, env: Env, o: PageOptions, sections: (w: Words) => readonly string[]): Response {
|
|
681
|
+
const config = appConfig(env);
|
|
682
|
+
// The kit's typed keys aren't needed here: each page names its own words.
|
|
683
|
+
const strings = stringsFor(env) as unknown as { detect(request: Request): { locale: string }; t(locale: string, key: string, values?: Record<string, string>): string };
|
|
684
|
+
const { locale } = strings.detect(request);
|
|
685
|
+
const w: Words = (key, values) => strings.t(locale, key, values);
|
|
686
|
+
const link = ([label, href]: readonly [string, string, ...string[]]) => ({ label: w(label), href });
|
|
687
|
+
// ?wb-look= and ?wb-scheme=: a public page in another look, for the look
|
|
688
|
+
// previewer. Never on the live site, and never on a members or admin page.
|
|
689
|
+
const preview = o.area ? null : previewAttributes(request.url, config.WORKBENCH_ENV !== "production");
|
|
690
|
+
// Design mode (/admin/design): on the test site, a public page carries the design script, for the admin who turned it on.
|
|
691
|
+
const design = !o.area && config.WORKBENCH_ENV !== "production" && designModeOn(request);
|
|
692
|
+
const html = frame({
|
|
693
|
+
frame: o.frame,
|
|
694
|
+
title: w(o.title),
|
|
695
|
+
site: BRAND.name,
|
|
696
|
+
sections: sections(w),
|
|
697
|
+
layout: preview ? previewLayout(preview.look) : LAYOUT,
|
|
698
|
+
menu: (o.area === "admin" ? ADMIN_MENU : MENU).map(link),
|
|
699
|
+
footer: FOOTER.map(link),
|
|
700
|
+
current: new URL(request.url).pathname,
|
|
701
|
+
lang: locale,
|
|
702
|
+
stylesheets: [...STYLESHEETS, ...(o.stylesheets ?? [])],
|
|
703
|
+
// Visitor counts only on public pages.
|
|
704
|
+
head: o.area ? "" : beacon(env),
|
|
705
|
+
noindex: o.area !== undefined,
|
|
706
|
+
// The theme's admin look: the project's accent and fonts on light neutrals.
|
|
707
|
+
admin: o.view ? o.view === "admin" : o.area === "admin",
|
|
708
|
+
...(o.view === "light" || o.view === "dark" ? { scheme: o.view } : {}),
|
|
709
|
+
env: config.WORKBENCH_ENV,
|
|
710
|
+
...(preview ? { preview: { look: preview.look, scheme: preview.scheme } } : {}),
|
|
711
|
+
...(design ? { design: { script: DESIGN_FILE.url } } : {}),
|
|
712
|
+
});
|
|
713
|
+
return new Response(html, {
|
|
714
|
+
status: o.status ?? 200,
|
|
715
|
+
headers: {
|
|
716
|
+
"content-type": "text/html; charset=utf-8",
|
|
717
|
+
// Public pages may be framed by the site itself, for the look previewer; members and admin pages by nothing.
|
|
718
|
+
"content-security-policy": o.area ? "frame-ancestors 'none'" : "frame-ancestors 'self'",
|
|
719
|
+
"x-content-type-options": "nosniff",
|
|
720
|
+
// All of staging is owner-only, and members and admin pages are someone's own, so never kept by a cache.
|
|
721
|
+
...(config.WORKBENCH_ENV === "production" && !o.area ? {} : { "cache-control": "private, no-store" }),
|
|
722
|
+
},
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
`;
|
|
726
|
+
/**
|
|
727
|
+
* check:site (docs/site-planner.md §10): every page in workbench/site.json has
|
|
728
|
+
* its file and a known recipe, no two share an address, and a page Workbench
|
|
729
|
+
* built (state built or checked) names only words the catalogue has. With
|
|
730
|
+
* `live`, also no word of a built page still waits for the owner. A page the
|
|
731
|
+
* project changed is its own: only its file is checked.
|
|
732
|
+
*/
|
|
733
|
+
export function siteProblems(i) {
|
|
734
|
+
const out = [];
|
|
735
|
+
const byId = new Map((i.catalogue ?? RECIPES).map((r) => [r.id, r]));
|
|
736
|
+
const record = i.site;
|
|
737
|
+
if (!record || record.format !== 1 || !Array.isArray(record.pages))
|
|
738
|
+
return [`${SITE_FILE} isn't a site record (format 1 with pages)`];
|
|
739
|
+
const seen = new Map();
|
|
740
|
+
for (const p of record.pages) {
|
|
741
|
+
const where = `${SITE_FILE}: ${p.recipe}`;
|
|
742
|
+
if (!(p.file in i.files))
|
|
743
|
+
out.push(`${where}: its file ${p.file} is missing`);
|
|
744
|
+
if (!["built", "checked", "changed"].includes(p.state))
|
|
745
|
+
out.push(`${where}: state ${String(p.state)} isn't built, checked or changed`);
|
|
746
|
+
const key = p.path ?? "(not found)";
|
|
747
|
+
if (seen.has(key))
|
|
748
|
+
out.push(`${where}: ${key} is also ${seen.get(key)}'s address`);
|
|
749
|
+
seen.set(key, p.recipe);
|
|
750
|
+
const r = byId.get(p.recipe);
|
|
751
|
+
if (!r) {
|
|
752
|
+
out.push(`${where}: no recipe called ${p.recipe}`);
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
if (p.state === "changed")
|
|
756
|
+
continue;
|
|
757
|
+
const text = i.files[p.file] ?? "";
|
|
758
|
+
for (const k of recipeKeys(r)) {
|
|
759
|
+
if (!text.includes(JSON.stringify(k)) && !(r.menu && (k === r.menu.label || k === r.menu.about)) && !(r.links ?? []).some((l) => l.label === k || l.about === k))
|
|
760
|
+
continue;
|
|
761
|
+
const word = i.strings[k];
|
|
762
|
+
if (word === undefined)
|
|
763
|
+
out.push(`${where}: the word ${k} isn't in the strings catalogue`);
|
|
764
|
+
else if (i.live && /\[[^\]]+\]/.test(word))
|
|
765
|
+
out.push(`${where}: ${k} still says "${word}": put the owner's words in before going live`);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return out;
|
|
769
|
+
}
|