@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/dist/recipe.js ADDED
@@ -0,0 +1,151 @@
1
+ // The recipe shape (docs/site-planner.md §5): one kind of page Workbench can
2
+ // build and test. A recipe is data: the builder (builder.ts) turns it into a
3
+ // thin page file in the project that calls this package's sections, and its
4
+ // words go into the project's strings catalogue, where the owner's Claude and
5
+ // the Translations page already work.
6
+ import { FRAMES } from "./frames.js";
7
+ import { HERO_ARRANGEMENTS } from "./sections.js";
8
+ /** The section functions a page file calls, by kind. Those in STORE_SECTIONS come from the project's src/pages/enquiry-store.ts, the rest from this package. */
9
+ export const SECTION_FUNCTIONS = { hero: "hero", text: "text", list: "list", call: "callToAction", details: "details", account: "account", "admin-menu": "list", "enquiry-form": "enquirySection", enquiries: "enquiriesSection", "style-guide": "styleGuide", "look-preview": "lookPreview", "design-switch": "designSwitch" };
10
+ /** Sections whose function is in the project's own src/pages/enquiry-store.ts, which the Enquiries recipe writes. */
11
+ export const STORE_SECTIONS = new Set(["enquiry-form", "enquiries"]);
12
+ /** Sections whose function comes from workbench-ui, not this package. */
13
+ export const UI_SECTIONS = new Set(["style-guide", "look-preview"]);
14
+ const AREAS = ["public", "members", "admin", "legal"];
15
+ export const GROUPS = ["every-site", "members", "admin", "business"];
16
+ /** Every word key a section names. */
17
+ function sectionKeys(s) {
18
+ switch (s.kind) {
19
+ case "hero":
20
+ return [s.heading, s.lead, s.action?.label].filter((k) => !!k);
21
+ case "text":
22
+ return [s.heading, s.body].filter((k) => !!k);
23
+ case "list":
24
+ return [s.heading, ...s.items.flatMap((i) => [i.title, i.body])].filter((k) => !!k);
25
+ case "call":
26
+ return [s.heading, s.body, s.action.label].filter((k) => !!k);
27
+ case "details":
28
+ return [s.heading, ...s.rows.flatMap((r) => [r.label, r.value])].filter((k) => !!k);
29
+ case "account":
30
+ return [s.heading, s.signedIn, s.signOut].filter((k) => !!k);
31
+ case "admin-menu":
32
+ return [s.heading].filter((k) => !!k);
33
+ case "enquiry-form":
34
+ return [s.heading, s.intro, s.send, s.sent, s.unavailable].filter((k) => !!k);
35
+ case "enquiries":
36
+ return [s.heading, s.empty, s.unavailable, s.remove].filter((k) => !!k);
37
+ case "style-guide":
38
+ return [s.views, s.light, s.dark, s.admin, s.empty, s.layout];
39
+ case "design-switch":
40
+ return [s.on, s.off, s.turnOn, s.turnOff, s.live];
41
+ case "look-preview":
42
+ return [s.home, s.pages, s.schemes, s.light, s.dark, s.yours, s.inUse, s.open, s.live];
43
+ }
44
+ }
45
+ /** Every word key the recipe's page names, in order. */
46
+ export function recipeKeys(r) {
47
+ const menu = r.menu ? [r.menu.label, r.menu.about].filter((k) => !!k) : [];
48
+ const links = (r.links ?? []).flatMap((l) => [l.label, l.about]);
49
+ return [...new Set([r.pageTitle, ...menu, ...links, ...r.sections.flatMap(sectionKeys)])];
50
+ }
51
+ /** The values a word is given when the page says it. */
52
+ function valuesFor(r, key) {
53
+ return r.sections.some((s) => s.kind === "account" && s.signedIn === key) ? ["email"] : [];
54
+ }
55
+ const ID = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
56
+ /** What's wrong with a recipe in a catalogue: empty when it can be built. */
57
+ export function recipeProblems(r, catalogue) {
58
+ const out = [];
59
+ const ids = new Set(catalogue.map((c) => c.id));
60
+ const p = (m) => out.push(`${r.id}: ${m}`);
61
+ if (!ID.test(r.id))
62
+ p("id must be lower case words joined by hyphens");
63
+ if (!Number.isInteger(r.version) || r.version < 1)
64
+ p("version must be a whole number from 1");
65
+ if (!r.title.trim() || !r.does.trim())
66
+ p("needs a title and what it does");
67
+ if (!GROUPS.includes(r.group))
68
+ p(`group ${r.group} isn't one of ${GROUPS.join(", ")}`);
69
+ if (!AREAS.includes(r.area))
70
+ p(`area ${r.area} isn't one of ${AREAS.join(", ")}`);
71
+ if (r.path !== null && !/^\/([a-z0-9-]+(\/[a-z0-9-]+)*)?$/.test(r.path))
72
+ p(`path ${r.path} must be / or /lower-case-words`);
73
+ if (r.path === null && r.status !== 404)
74
+ p("a page with no path is the Not found page, so its status is 404");
75
+ if (!r.frames.length || r.frames.some((f) => !FRAMES.includes(f)))
76
+ p(`frames must be some of ${FRAMES.join(", ")}`);
77
+ for (const n of r.needs)
78
+ if (!ids.has(n))
79
+ p(`needs ${n}, which isn't in the catalogue`);
80
+ const prefix = `page.${r.id.replace(/-/g, "_")}.`;
81
+ const keys = recipeKeys(r);
82
+ for (const k of keys) {
83
+ if (!k.startsWith(prefix))
84
+ p(`word ${k} must start with ${prefix}`);
85
+ if (!(k in r.words))
86
+ p(`names word ${k}, which it doesn't define`);
87
+ }
88
+ for (const k of Object.keys(r.words)) {
89
+ if (!keys.includes(k))
90
+ p(`defines word ${k}, which no section uses`);
91
+ const w = r.words[k];
92
+ if (!w.trim())
93
+ p(`word ${k} is empty`);
94
+ // ICU placeholders need values: only the account section passes one, {email}.
95
+ const takes = valuesFor(r, k);
96
+ const used = [...w.matchAll(/\{([^}]*)\}/g)].map((m) => m[1]);
97
+ if (/[{}]/.test(w.replace(/\{[a-z]+\}/g, "")) || used.some((v) => !takes.includes(v)))
98
+ p(`word ${k} can't hold braces${takes.length ? ` other than ${takes.map((v) => `{${v}}`).join(", ")}` : ""}`);
99
+ for (const v of takes)
100
+ if (!used.includes(v))
101
+ p(`word ${k} must say {${v}}`);
102
+ }
103
+ const heroes = r.sections.filter((s) => s.kind === "hero");
104
+ if (heroes.length !== 1 || r.sections[0]?.kind !== "hero")
105
+ p("needs exactly one hero, first: it holds the page's only h1");
106
+ for (const s of r.sections) {
107
+ if (s.kind === "hero" && s.arrangement && !HERO_ARRANGEMENTS.includes(s.arrangement))
108
+ p(`hero arrangement ${s.arrangement} isn't known`);
109
+ const to = s.kind === "hero" ? s.action?.to : s.kind === "call" ? s.action.to : undefined;
110
+ if (to !== undefined && !to.startsWith("/") && !ids.has(to))
111
+ p(`a button goes to ${to}, which is neither a path nor a recipe`);
112
+ }
113
+ if (r.menu && r.menu.header === undefined && r.menu.footer === undefined && r.menu.admin === undefined)
114
+ p("menu needs a header, footer or admin place");
115
+ if (r.menu?.admin !== undefined && (r.area !== "admin" || !r.menu.about))
116
+ p("only an admin page goes in the admin menu, with an about line");
117
+ if (r.area === "admin" && (r.path === null || !/^\/admin(\/|$)/.test(r.path)))
118
+ p("an admin page's address starts /admin");
119
+ if (r.area !== "public" && r.path === null)
120
+ p("the Not found page is public");
121
+ for (const s of r.sections) {
122
+ if (s.kind === "account" && r.area !== "members")
123
+ p("the account section is for members pages");
124
+ if (s.kind === "admin-menu" && r.area !== "admin")
125
+ p("the admin menu section is for admin pages");
126
+ if (s.kind === "enquiries" && r.area !== "admin")
127
+ p("the enquiries list is for admin pages");
128
+ if (s.kind === "enquiry-form" && r.area !== "public")
129
+ p("the enquiry form is for public pages");
130
+ if (s.kind === "style-guide" && r.area !== "admin")
131
+ p("the style guide is for admin pages");
132
+ if (s.kind === "look-preview" && r.area !== "admin")
133
+ p("the look previewer is for admin pages");
134
+ if (s.kind === "design-switch" && r.area !== "admin")
135
+ p("design mode's switch is for admin pages");
136
+ }
137
+ for (const l of r.links ?? [])
138
+ if (!/^\/admin(\/|$)/.test(l.href) || r.area !== "admin")
139
+ p(`link ${l.href}: only admin pages add admin menu links, to /admin addresses`);
140
+ if (r.menu && r.path === null)
141
+ p("a page with no path can't be in the menu");
142
+ if (r.migration && !/^workbench_site_[a-z0-9_]+$/.test(r.migration.name))
143
+ p("a migration is named workbench_site_<what>, so Control treats it as a Workbench tool's own");
144
+ for (const [name, v] of Object.entries(r.packages ?? {}))
145
+ if (!/^@mccaskie-labs\/workbench-[a-z]+$/.test(name) || !/^\d+\.\d+\.\d+$/.test(v))
146
+ p(`package ${name}: only a Workbench package, at an exact x.y.z version`);
147
+ for (const f of Object.keys(r.files ?? {}))
148
+ if (!/^(src\/pages|workbench\/forms)\/[a-z0-9-]+\.(ts|json)$/.test(f))
149
+ p(`file ${f}: a recipe writes only into src/pages/ and workbench/forms/`);
150
+ return out;
151
+ }
@@ -0,0 +1,3 @@
1
+ import type { Recipe } from "../recipe.ts";
2
+ /** The "Admin" group, in the order they're offered. */
3
+ export declare const ADMIN: readonly Recipe[];
@@ -0,0 +1,194 @@
1
+ // The "Admin" recipes (docs/site-planner.md §5): pages for the app's admins
2
+ // (the client first, then whoever they invite at /admin/brand). Each tool's
3
+ // own admin list joins the admin menu with its recipe; the template's Brand
4
+ // settings page is in the menu from the start.
5
+ import { ENQUIRY_ANSWERS, ENQUIRY_MIGRATION, ENQUIRY_STORE } from "./enquiries-kit.js";
6
+ const adminHome = {
7
+ id: "admin-home",
8
+ version: 1,
9
+ title: "Admin home",
10
+ does: "One page with a link to everything the business's admins look after.",
11
+ group: "admin",
12
+ area: "admin",
13
+ path: "/admin",
14
+ frames: ["column"],
15
+ tools: ["sign-in"],
16
+ needs: [],
17
+ menu: { label: "page.admin_home.menu", admin: 0, about: "page.admin_home.about" },
18
+ links: [{ label: "page.admin_home.brand.label", about: "page.admin_home.brand.about", href: "/admin/brand", admin: 90 }],
19
+ pageTitle: "page.admin_home.title",
20
+ sections: [
21
+ { kind: "hero", heading: "page.admin_home.hero.heading", lead: "page.admin_home.hero.lead" },
22
+ { kind: "admin-menu", heading: "page.admin_home.pages.heading" },
23
+ ],
24
+ words: {
25
+ "page.admin_home.menu": "Admin",
26
+ "page.admin_home.about": "This page: every admin page in one list.",
27
+ "page.admin_home.title": "Admin",
28
+ "page.admin_home.hero.heading": "Admin",
29
+ "page.admin_home.hero.lead": "Everything you look after on the site. Only the site's admins can see these pages.",
30
+ "page.admin_home.pages.heading": "Your pages",
31
+ "page.admin_home.brand.label": "Brand settings",
32
+ "page.admin_home.brand.about": "Your business's name, colour and logo on emails and PDFs, and who else can manage the site.",
33
+ },
34
+ suggest: { types: [], signals: ["every site"] },
35
+ };
36
+ const enquiries = {
37
+ id: "enquiries",
38
+ version: 1,
39
+ title: "Enquiries",
40
+ does: "Every message sent from the Contact page, newest first, with a way to reply.",
41
+ group: "admin",
42
+ area: "admin",
43
+ path: "/admin/enquiries",
44
+ frames: ["column"],
45
+ tools: ["sign-in", "forms"],
46
+ needs: [],
47
+ menu: { label: "page.enquiries.menu", admin: 10, about: "page.enquiries.about" },
48
+ files: {
49
+ "src/pages/enquiry-store.ts": ENQUIRY_STORE,
50
+ "workbench/forms/enquiry.json": `${JSON.stringify(ENQUIRY_ANSWERS, null, 2)}\n`,
51
+ },
52
+ migration: ENQUIRY_MIGRATION,
53
+ pageTitle: "page.enquiries.title",
54
+ sections: [
55
+ { kind: "hero", heading: "page.enquiries.hero.heading", lead: "page.enquiries.hero.lead" },
56
+ { kind: "enquiries", empty: "page.enquiries.list.empty", unavailable: "page.enquiries.list.unavailable", remove: "page.enquiries.list.remove" },
57
+ ],
58
+ words: {
59
+ "page.enquiries.menu": "Enquiries",
60
+ "page.enquiries.about": "Messages people sent from the Contact page.",
61
+ "page.enquiries.title": "Enquiries",
62
+ "page.enquiries.hero.heading": "Enquiries",
63
+ "page.enquiries.hero.lead": "Messages from the Contact page, newest first. Reply by email or phone, then delete the ones you've dealt with.",
64
+ "page.enquiries.list.empty": "No enquiries yet. They'll show here as soon as someone sends one.",
65
+ "page.enquiries.list.unavailable": "The enquiries can't be read right now. Try again in a minute.",
66
+ "page.enquiries.list.remove": "Delete",
67
+ },
68
+ suggest: { types: [], signals: ["every site"] },
69
+ };
70
+ const styleGuide = {
71
+ id: "style-guide",
72
+ version: 1,
73
+ title: "Style guide",
74
+ does: "Every part of the site on one page, in its look, light and dark, so a change of colours or fonts can be checked at a glance.",
75
+ group: "admin",
76
+ area: "admin",
77
+ path: "/admin/style-guide",
78
+ frames: ["column"],
79
+ tools: ["sign-in", "ui"],
80
+ needs: [],
81
+ // styleGuide, guideView, and the samples module and sheet `npx workbench-ui styles` writes.
82
+ packages: { "@mccaskie-labs/workbench-ui": "0.14.0" },
83
+ menu: { label: "page.style_guide.menu", admin: 80, about: "page.style_guide.about" },
84
+ pageTitle: "page.style_guide.title",
85
+ sections: [
86
+ { kind: "hero", heading: "page.style_guide.hero.heading", lead: "page.style_guide.hero.lead" },
87
+ {
88
+ kind: "style-guide",
89
+ views: "page.style_guide.views",
90
+ light: "page.style_guide.light",
91
+ dark: "page.style_guide.dark",
92
+ admin: "page.style_guide.admin",
93
+ empty: "page.style_guide.empty",
94
+ layout: "page.style_guide.layout",
95
+ },
96
+ ],
97
+ words: {
98
+ "page.style_guide.menu": "Style guide",
99
+ "page.style_guide.about": "Every part of the site in its look, to check a change of colours or fonts.",
100
+ "page.style_guide.title": "Style guide",
101
+ "page.style_guide.hero.heading": "Style guide",
102
+ "page.style_guide.hero.lead": "Every part of the site in your look, with sample words. Nothing here changes anything: the buttons and forms are for show.",
103
+ "page.style_guide.views": "Show",
104
+ "page.style_guide.light": "Light",
105
+ "page.style_guide.dark": "Dark",
106
+ "page.style_guide.admin": "Admin pages",
107
+ "page.style_guide.empty": "None of the site's tools has samples yet.",
108
+ "page.style_guide.layout": "Layout",
109
+ },
110
+ suggest: { types: [], signals: ["every site"] },
111
+ };
112
+ const look = {
113
+ id: "look",
114
+ version: 1,
115
+ title: "Looks",
116
+ does: "The site's own pages in every look it may choose, side by side, light or dark, so an owner can see a new look on their real words and pictures before choosing it.",
117
+ group: "admin",
118
+ area: "admin",
119
+ path: "/admin/look",
120
+ frames: ["column"],
121
+ tools: ["sign-in", "ui"],
122
+ needs: [],
123
+ // lookPreview, and the preview styles (looks.css) and the site helper's ?wb-look= (workbench-ui 0.13.3), and the design script the helper loads (0.14.0).
124
+ packages: { "@mccaskie-labs/workbench-ui": "0.14.0" },
125
+ menu: { label: "page.look.menu", admin: 85, about: "page.look.about" },
126
+ pageTitle: "page.look.title",
127
+ sections: [
128
+ { kind: "hero", heading: "page.look.hero.heading", lead: "page.look.hero.lead" },
129
+ {
130
+ kind: "look-preview",
131
+ home: "page.look.home",
132
+ pages: "page.look.pages",
133
+ schemes: "page.look.schemes",
134
+ light: "page.look.light",
135
+ dark: "page.look.dark",
136
+ yours: "page.look.yours",
137
+ inUse: "page.look.in_use",
138
+ open: "page.look.open",
139
+ live: "page.look.live",
140
+ },
141
+ ],
142
+ words: {
143
+ "page.look.menu": "Looks",
144
+ "page.look.about": "Your own pages in every look you can choose, to compare them.",
145
+ "page.look.title": "Looks",
146
+ "page.look.hero.heading": "Looks",
147
+ "page.look.hero.lead": "Your own pages in each look you can choose, light or dark. Looking changes nothing: your site keeps its look until you choose another.",
148
+ "page.look.home": "Home",
149
+ "page.look.pages": "Page",
150
+ "page.look.schemes": "Show",
151
+ "page.look.light": "Light",
152
+ "page.look.dark": "Dark",
153
+ "page.look.yours": "Your site now",
154
+ "page.look.in_use": "In use",
155
+ "page.look.open": "Open on its own",
156
+ "page.look.live": "The other looks show on your test site.",
157
+ },
158
+ suggest: { types: [], signals: ["every site"] },
159
+ };
160
+ const design = {
161
+ id: "design",
162
+ version: 1,
163
+ title: "Design mode",
164
+ does: "Turns design mode on in this browser, on the test site: a bar on every page to try looks, light or dark and the site layout, and a badge on each tool to try its layouts, on the real pages.",
165
+ group: "admin",
166
+ area: "admin",
167
+ path: "/admin/design",
168
+ frames: ["column"],
169
+ tools: ["sign-in", "ui"],
170
+ needs: [],
171
+ // The design script (public/scripts/design-mode.generated.js) and the site helper that loads it, from workbench-ui 0.14.0.
172
+ packages: { "@mccaskie-labs/workbench-ui": "0.14.0" },
173
+ menu: { label: "page.design.menu", admin: 87, about: "page.design.about" },
174
+ pageTitle: "page.design.title",
175
+ sections: [
176
+ { kind: "hero", heading: "page.design.hero.heading", lead: "page.design.hero.lead" },
177
+ { kind: "design-switch", on: "page.design.on", off: "page.design.off", turnOn: "page.design.turn_on", turnOff: "page.design.turn_off", live: "page.design.live" },
178
+ ],
179
+ words: {
180
+ "page.design.menu": "Design mode",
181
+ "page.design.about": "Try looks and layouts on your own pages before choosing.",
182
+ "page.design.title": "Design mode",
183
+ "page.design.hero.heading": "Design mode",
184
+ "page.design.hero.lead": "Try a look, light or dark, and the layout of each part of your site, on your real pages. A bar across the top has the choices, and each part has a badge with its layouts.",
185
+ "page.design.on": "Design mode is on in this browser. Only you see what you try.",
186
+ "page.design.off": "Nothing you try changes your site until you keep it, and nobody else sees it.",
187
+ "page.design.turn_on": "Turn on design mode",
188
+ "page.design.turn_off": "Turn off design mode",
189
+ "page.design.live": "Design mode is on your test site, so your live site never changes while you try things.",
190
+ },
191
+ suggest: { types: [], signals: ["every site"] },
192
+ };
193
+ /** The "Admin" group, in the order they're offered. */
194
+ export const ADMIN = [adminHome, enquiries, styleGuide, look, design];
@@ -0,0 +1,55 @@
1
+ /** workbench/forms/enquiry.json: the form, as Claude would write it from the forms questions. `npm run forms` builds it. */
2
+ export declare const ENQUIRY_ANSWERS: {
3
+ readonly format: 1;
4
+ readonly status: "done";
5
+ readonly form: "enquiry";
6
+ readonly title: "Contact enquiry form";
7
+ readonly fields: readonly [{
8
+ readonly name: "name";
9
+ readonly label: "Your name";
10
+ readonly kind: "text";
11
+ readonly required: true;
12
+ readonly max: 100;
13
+ readonly width: "l";
14
+ readonly limit_status: "proposed";
15
+ readonly reason: "Workbench default, not yet confirmed";
16
+ readonly column: "site_enquiries.name";
17
+ }, {
18
+ readonly name: "email";
19
+ readonly label: "Your email";
20
+ readonly kind: "email";
21
+ readonly required: true;
22
+ readonly width: "l";
23
+ readonly limit_status: "proposed";
24
+ readonly reason: "Workbench default, not yet confirmed";
25
+ readonly column: "site_enquiries.email";
26
+ }, {
27
+ readonly name: "phone";
28
+ readonly label: "Your phone (if you'd like a call)";
29
+ readonly kind: "phone";
30
+ }, {
31
+ readonly name: "message";
32
+ readonly label: "Your message";
33
+ readonly kind: "long_text";
34
+ readonly required: true;
35
+ readonly max: 2000;
36
+ readonly limit_status: "proposed";
37
+ readonly reason: "Workbench default, not yet confirmed";
38
+ readonly column: "site_enquiries.message";
39
+ }];
40
+ };
41
+ /**
42
+ * The table, as a Workbench tool's own migration (`<stamp>_workbench_site_enquiries`):
43
+ * a new table and its policies only, so Control applies it to staging with no
44
+ * approval. Anyone may add an enquiry (the Worker checks the form and
45
+ * Turnstile first); only the site's admins read or delete them, as
46
+ * themselves, so the project needs no secret key. An enquiry can't be dated
47
+ * by the sender: received_at is the database's own time.
48
+ */
49
+ export declare const ENQUIRY_MIGRATION: {
50
+ name: string;
51
+ up: string;
52
+ down: string;
53
+ };
54
+ /** src/pages/enquiry-store.ts: written once, then the project's. */
55
+ export declare const ENQUIRY_STORE = "// The site's enquiries: Contact's form and the Enquiries admin list. Written by\n// @mccaskie-labs/workbench-site once; it's the project's to change.\n//\n// - The form is workbench/forms/enquiry.json (`npm run forms` builds it); its\n// numbers are in the limits register and match site_enquiries' columns.\n// - The table is site_enquiries (supabase/migrations/*_workbench_site_enquiries.sql).\n// Anyone may add a row and only the site's admins read or delete them, as\n// themselves (RLS), so the project needs no secret key.\n// - The page checks the form and Turnstile before it stores an enquiry. The\n// table also takes rows sent straight to the database with the publishable\n// key, which skip both: each is capped in length, and admins delete what\n// they don't want. To close that, add SUPABASE_SECRET_KEY (two-step), send\n// with the service client, and drop the insert policy.\n\nimport { readForm, validate, type Result } from \"@mccaskie-labs/workbench-forms\";\nimport { FORMS_SCRIPT } from \"@mccaskie-labs/workbench-forms/browser\";\nimport { boundsFor } from \"@mccaskie-labs/workbench-forms/limits\";\nimport { formatDateTime } from \"@mccaskie-labs/workbench-country\";\nimport { enquiryList, formSection, type Enquiry } from \"@mccaskie-labs/workbench-site\";\nimport { sameOrigin } from \"@mccaskie-labs/workbench-supabase\";\nimport { escape, FORM_SCRIPT } from \"@mccaskie-labs/workbench-ui\";\nimport { appConfig } from \"../config.ts\";\nimport { FORMS, formContext } from \"../forms/index.ts\";\nimport { formHtml } from \"../forms/page.ts\";\nimport { READERS } from \"../lib/country.ts\";\nimport { dbAs } from \"../lib/db.ts\";\nimport { TURNSTILE_ACTION, TURNSTILE_ORIGIN, turnstileSetup, verifyTurnstile } from \"../lib/turnstile.ts\";\nimport { LIMITS } from \"../limits.ts\";\nimport type { PageContext, SitePage } from \"./site.ts\";\n\n/** The form's state after a submit that didn't go through. */\nexport interface EnquiryState {\n result?: Result;\n input?: Record<string, unknown>;\n /** It couldn't be sent: the check or the database is down. */\n problem?: boolean;\n}\n\nconst SENT = \"sent\";\n/** At most this many shown, newest first. */\nconst SHOWN = 200;\n\nfunction enquiryForm() {\n const form = FORMS.find((f) => f.name === \"enquiry\");\n if (!form) throw new Error(\"There's no enquiry form: run npm run forms (workbench/forms/enquiry.json)\");\n return form;\n}\n\n/** The table, as the Worker reaches it. Tests replace these. */\nexport const enquiryStore = {\n /** Adds one enquiry as anyone (the publishable key). False when the database didn't take it. */\n async send(env: object, values: { name: string; email: string; phone: string | null; message: string }): Promise<boolean> {\n const c = appConfig(env);\n try {\n const res = await fetch(`${c.SUPABASE_URL}/rest/v1/site_enquiries`, {\n method: \"POST\",\n headers: { apikey: c.SUPABASE_PUBLISHABLE_KEY, \"content-type\": \"application/json\", prefer: \"return=minimal\" },\n body: JSON.stringify(values),\n signal: AbortSignal.timeout(10_000),\n });\n if (!res.ok) console.warn(JSON.stringify({ event: \"site_enquiry_failed\", status: res.status }));\n return res.ok;\n } catch {\n console.warn(JSON.stringify({ event: \"site_enquiry_failed\", status: 0 }));\n return false;\n }\n },\n /** The newest enquiries, as the signed-in admin. Null when they can't be read. */\n async list(env: object, accessToken: string): Promise<{ id: string; name: string; email: string; phone: string | null; message: string; received_at: string }[] | null> {\n const { data, error } = await dbAs(env, accessToken).from(\"site_enquiries\").select(\"id, name, email, phone, message, received_at\").order(\"received_at\", { ascending: false }).limit(SHOWN);\n if (error) {\n console.warn(JSON.stringify({ event: \"site_enquiries_read_failed\" }));\n return null;\n }\n return data;\n },\n /** Deletes one, as the signed-in admin. */\n async remove(env: object, accessToken: string, id: string): Promise<boolean> {\n const { error } = await dbAs(env, accessToken).from(\"site_enquiries\").delete().eq(\"id\", id);\n return !error;\n },\n};\n\nexport interface EnquiryWords {\n heading: string;\n intro?: string;\n /** The submit button's key: renderForm looks it up. */\n send: string;\n /** The thank-you. */\n sent: string;\n /** When the check or the database is down. */\n unavailable: string;\n}\n\n/** Contact's enquiry form, or its thank-you once sent. */\nexport function enquirySection(request: Request, env: object, ctx: PageContext, w: EnquiryWords): string {\n if (new URL(request.url).searchParams.get(SENT) === \"1\") return formSection({ id: \"enquiry\", heading: w.heading, done: w.sent });\n const state = (ctx.form ?? {}) as EnquiryState;\n const path = new URL(request.url).pathname;\n let html = formHtml(enquiryForm(), request, env, { action: `${path}#enquiry`, submit: w.send, ...(state.result ? { result: state.result } : {}), ...(state.input ? { input: state.input } : {}) });\n const bot = turnstileSetup(env);\n if (bot.state === \"on\") {\n // Inside the form, so its token is sent with it; shown only when Cloudflare needs the person to click.\n const widget = `<div class=\"cf-turnstile\" data-sitekey=\"${escape(bot.siteKey)}\" data-action=\"${TURNSTILE_ACTION}\" data-appearance=\"interaction-only\" data-theme=\"auto\"></div>`;\n const at = html.lastIndexOf(\"</form>\");\n if (at !== -1) html = html.slice(0, at) + widget + html.slice(at);\n html += `<script src=\"${TURNSTILE_ORIGIN}/turnstile/v0/api.js\" async defer></script>`;\n }\n html += `<script>${FORMS_SCRIPT}</script><script>${FORM_SCRIPT}</script>`;\n return formSection({ id: \"enquiry\", heading: w.heading, ...(w.intro ? { intro: w.intro } : {}), form: html, ...(state.problem ? { problem: w.unavailable } : {}) });\n}\n\n/** Contact's POST: checks the form and Turnstile, stores it, and sends the person back to the thank-you. */\nexport async function takeEnquiry(request: Request, env: Env, ctx: PageContext, page: SitePage): Promise<Response> {\n if (!sameOrigin(request)) return new Response(\"Forbidden\\n\", { status: 403 });\n const again = async (status: number, form: EnquiryState) => {\n const res = await page.render(request, env, { ...ctx, form });\n return new Response(res.body, { status, headers: res.headers });\n };\n let data: FormData;\n try {\n data = await request.formData();\n } catch {\n return again(400, {});\n }\n const form = enquiryForm();\n const input = readForm(form, data);\n const result = validate(form, input, { ...formContext(), bounds: boundsFor(LIMITS, form) });\n if (!result.ok) return again(422, { result, input });\n const bot = turnstileSetup(env);\n if (bot.state === \"missing\") return again(503, { input, problem: true });\n if (bot.state === \"on\" && !(await verifyTurnstile(bot.secret, data.get(\"cf-turnstile-response\"), request, bot.strict)).ok) return again(400, { input, problem: true });\n const v = result.values as Record<string, unknown>;\n const sent = await enquiryStore.send(env, { name: String(v.name), email: String(v.email), phone: typeof v.phone === \"string\" ? v.phone : null, message: String(v.message) });\n if (!sent) return again(503, { input, problem: true });\n const back = new URL(request.url);\n back.search = `?${SENT}=1`;\n back.hash = \"enquiry\";\n return new Response(null, { status: 303, headers: { location: `${back.pathname}${back.search}${back.hash}` } });\n}\n\n/** The enquiries for the admin list, in the readers' time zone. Null when they can't be read. */\nexport async function listEnquiries(env: object, ctx: PageContext): Promise<Enquiry[] | null> {\n if (!ctx.accessToken) return null;\n const rows = await enquiryStore.list(env, ctx.accessToken);\n return rows && rows.map((r) => ({ id: r.id, name: r.name, email: r.email, phone: r.phone, message: r.message, received: formatDateTime(r.received_at, { pack: READERS }) }));\n}\n\nexport interface EnquiryListWords {\n heading?: string;\n empty: string;\n unavailable: string;\n remove: string;\n}\n\n/** The Enquiries admin list. */\nexport function enquiriesSection(request: Request, enquiries: Enquiry[] | null, w: EnquiryListWords): string {\n return enquiryList({ ...w, enquiries, removeAction: new URL(request.url).pathname });\n}\n\n/** The Enquiries page's POST: deletes one, as the admin, and shows the list again. */\nexport async function removeEnquiry(request: Request, env: object, ctx: PageContext): Promise<Response> {\n let id: unknown = null;\n try {\n id = (await request.formData()).get(\"remove\");\n } catch {\n // Nothing to delete: shown the list again.\n }\n if (ctx.accessToken && typeof id === \"string\" && /^[0-9a-f-]{36}$/.test(id)) await enquiryStore.remove(env, ctx.accessToken, id);\n return new Response(null, { status: 303, headers: { location: new URL(request.url).pathname } });\n}\n";