@mccaskie-labs/workbench-site 0.11.0 → 0.12.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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # @mccaskie-labs/workbench-site
2
2
 
3
+ ## 0.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Recipes from other tools (`docs/builder-ready.md` B5, `docs/site-planner.md` §5): a tool's own pages are recipes in its own package, exported as `RECIPES` from `"<package>/recipes"`. The CLI finds every Workbench package the project depends on that has the export and gathers its recipes beside the site's own (`recipeSources`, `gatherRecipes`), for `list`, `add` and `check`. A package whose export isn't recipes, that repeats an id, or that has a recipe that can't be built is left out whole and named, so the site's own pages and the other tools' still build. `list` names the package each tool page comes from.
8
+ - A tool can draw a section itself: `{ kind: "tool", from, fn, words }`. The page file imports `fn` from the tool's package (a `ToolSectionFunction`), calls it with (request, env, ctx) before drawing the page, and draws what it gives back with the page's words.
9
+ - `buildSite` takes `from` (recipe id to package), and the generated pages test imports those packages' recipes for `siteProblems`. `main` is now async.
10
+
3
11
  ## 0.11.0
4
12
 
5
13
  ### Minor Changes
package/README.md CHANGED
@@ -40,3 +40,7 @@ import { account, callToAction, details, enquiryList, formSection, frame, hero,
40
40
  ```
41
41
 
42
42
  Each section takes plain words (escaped) and returns HTML with `wb-site-*` classes; `frame` wraps them in a whole page (`landing`, `column` or `two-columns`). Restyle them in the project's `public/styles/project.css`: every class and `--wb-site-*` variable is listed in the generated `public/styles/workbench.css`, and the colour, font, corner and space variables follow the project's theme tokens (`--wb-accent` and the rest).
43
+
44
+ ## A tool's own pages
45
+
46
+ A tool's pages are recipes in its own package (`docs/site-planner.md` §5). Export them as `RECIPES` (a `readonly Recipe[]`, the type from this package) from a `./recipes` subpath in the package's `exports`. `npx workbench-site` gathers them from every Workbench package the project has installed, beside this package's own. Each recipe follows the same rules: ids unique across every package, words under `page.<id>.`, files only in `src/pages/` and `workbench/forms/`, and a `needsYou` count when its admin page has something waiting. A section only the tool can draw (a slot picker) is `{ kind: "tool", from: "<package>", fn: "<export>", words: [<its word keys>] }`: the export is a `ToolSectionFunction`, called with (request, env, ctx) before the page is drawn, which gives back a function that draws the section's HTML with the page's words, in the tool's own `wb-<tool>-*` classes.
package/dist/builder.d.ts CHANGED
@@ -32,6 +32,8 @@ export interface BuildOptions {
32
32
  /** The project's base locale: its words go into strings/strings.<base>.json. Defaults to en-AU. */
33
33
  base?: string;
34
34
  catalogue?: readonly Recipe[];
35
+ /** Which tool package each recipe in `catalogue` came from, by id (gatherRecipes' `from`): the generated test imports their recipes. */
36
+ from?: Readonly<Record<string, string>>;
35
37
  /** Stamps a new migration's file name. Defaults to now. */
36
38
  now?: Date;
37
39
  }
package/dist/builder.js CHANGED
@@ -116,7 +116,7 @@ export function buildSite(o) {
116
116
  const dashboard = pages.some((p) => byId.get(p.recipe)?.sections.some((x) => x.kind === "needs-you"));
117
117
  if (dashboard)
118
118
  writes["src/pages/needs.ts"] = needsFile(pages, byId);
119
- writes["test/pages.test.ts"] = testFile(base, pages, byId);
119
+ writes["test/pages.test.ts"] = testFile(base, pages, byId, o.from ?? {});
120
120
  // What the pages need besides their files: each written once, then the project's.
121
121
  let forms = false;
122
122
  const migrations = [];
@@ -268,6 +268,9 @@ function sectionCode(s, pathOf, self) {
268
268
  for (const k of ["views", "light", "dark", "admin", "empty", "layout"])
269
269
  add(k, w(s[k]));
270
270
  return `styleGuide(SAMPLES, { view, words: { ${fields.join(", ")} } })`;
271
+ case "tool":
272
+ // Drawn from what its function gave back (pageFile).
273
+ return null;
271
274
  case "design-switch":
272
275
  for (const k of ["on", "off", "turnOn", "turnOff", "live"])
273
276
  add(k, w(s[k]));
@@ -294,8 +297,19 @@ function older(have, least) {
294
297
  /** The style guide's own sheet, which workbench-ui's styles command writes (both schemes of the project's look). */
295
298
  const GUIDE_SHEET = "/styles/style-guide.css";
296
299
  function pageFile(r, version, base, pathOf) {
297
- const sections = r.sections.map((s) => [s, sectionCode(s, pathOf, r.path)]).filter((x) => x[1] !== null);
298
- 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();
300
+ // A tool's section is drawn by a function from its own package, called before the page (it may read the database).
301
+ let n = 0;
302
+ const tools = [];
303
+ const sections = r.sections
304
+ .map((s) => {
305
+ if (s.kind !== "tool")
306
+ return [s, sectionCode(s, pathOf, r.path)];
307
+ n += 1;
308
+ tools.push({ name: `tool${n}`, from: s.from, fn: s.fn });
309
+ return [s, `tool${n}(w)`];
310
+ })
311
+ .filter((x) => x[1] !== null);
312
+ const used = [...new Set([...sections.filter(([s]) => !STORE_SECTIONS.has(s.kind) && !UI_SECTIONS.has(s.kind) && s.kind !== "tool").map(([s]) => SECTION_FUNCTIONS[s.kind]), ...(sections.some(([s]) => s.kind === "design-switch") ? ["designModeOn", "designModePost"] : [])])].sort();
299
313
  const guide = sections.some(([s]) => s.kind === "style-guide");
300
314
  const form = sections.some(([s]) => s.kind === "enquiry-form");
301
315
  const list = sections.some(([s]) => s.kind === "enquiries");
@@ -305,7 +319,15 @@ function pageFile(r, version, base, pathOf) {
305
319
  const looks = sections.some(([s]) => s.kind === "look-preview");
306
320
  const design = sections.some(([s]) => s.kind === "design-switch");
307
321
  const needs = sections.some(([s]) => s.kind === "needs-you");
308
- const block = list || guide || needs;
322
+ const pre = [
323
+ ...(list ? [" const enquiries = await listEnquiries(env, ctx);"] : []),
324
+ ...(needs ? [" // Each tool's count, read at once (src/pages/needs.ts).", " const needs = await readNeeds(env, ctx);"] : []),
325
+ ...(guide ? [" // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"] : []),
326
+ ...tools.map((t) => ` const ${t.name} = await ${t.fn}(request, env, ctx);`),
327
+ ];
328
+ const block = pre.length > 0;
329
+ const waits = list || needs || tools.length > 0;
330
+ const toolImports = [...new Set(tools.map((t) => t.from))].sort().map((from) => `import { ${[...new Set(tools.filter((t) => t.from === from).map((t) => t.fn))].sort().join(", ")} } from "${from}";`);
309
331
  const area = r.area === "members" || r.area === "admin" ? `, area: ${JSON.stringify(r.area)}` : "";
310
332
  const prefix = `page.${r.id.replace(/-/g, "_")}.`;
311
333
  const frame = r.frames[0];
@@ -320,7 +342,8 @@ function pageFile(r, version, base, pathOf) {
320
342
  "// fill in. Once you change this file, set its state in workbench/site.json to",
321
343
  '// "changed", and Workbench never writes over it.',
322
344
  "",
323
- `import { ${used.join(", ")} } from "${PACKAGE}";`,
345
+ ...(used.length ? [`import { ${used.join(", ")} } from "${PACKAGE}";`] : []),
346
+ ...toolImports,
324
347
  ...(store.length ? [`import { ${store.join(", ")} } from "./enquiry-store.ts";`] : []),
325
348
  ...(guide ? [`import { guideView, styleGuide } from "@mccaskie-labs/workbench-ui";`, `import { SAMPLES } from "../samples.generated.ts";`] : []),
326
349
  ...(looks ? [`import { lookPreview } from "@mccaskie-labs/workbench-ui";`] : []),
@@ -334,13 +357,7 @@ function pageFile(r, version, base, pathOf) {
334
357
  ` recipe: ${JSON.stringify(r.id)},`,
335
358
  ` path: ${JSON.stringify(r.path)},`,
336
359
  ` access: ${JSON.stringify(r.area === "legal" ? "public" : r.area)},`,
337
- ...(list
338
- ? [" render: async (request, env, ctx) => {", " const enquiries = await listEnquiries(env, ctx);"]
339
- : needs
340
- ? [" render: async (request, env, ctx) => {", " // Each tool's count, read at once (src/pages/needs.ts).", " const needs = await readNeeds(env, ctx);"]
341
- : guide
342
- ? [" render: (request, env) => {", " // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"]
343
- : [` render: (request, env${usesCtx ? ", ctx" : ""}) =>`]),
360
+ ...(block ? [` render: ${waits ? "async " : ""}(request, env${usesCtx || waits ? ", ctx" : ""}) => {`, ...pre] : [` render: (request, env${usesCtx ? ", ctx" : ""}) =>`]),
344
361
  ` ${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) => [`,
345
362
  ...sections.map(([, code]) => ` ${code},`),
346
363
  block ? " ]);\n }," : " ]),",
@@ -508,7 +525,11 @@ function navFile(pages, byId) {
508
525
  "",
509
526
  ].join("\n");
510
527
  }
511
- function testFile(base, pages, byId) {
528
+ /** A package's name as an identifier for its recipes: @mccaskie-labs/workbench-bookings gives bookingsRecipes. */
529
+ const recipesName = (pkg) => `${pkg.replace(/^@[^/]+\//, "").replace(/^workbench-/, "").replace(/[^a-z0-9]+([a-z0-9])/gi, (_, c) => c.toUpperCase())}Recipes`;
530
+ function testFile(base, pages, byId, from) {
531
+ // The tool packages whose pages are on the site: siteProblems needs their recipes too.
532
+ const tools = [...new Set(pages.map((p) => from[p.recipe]).filter((x) => !!x))].sort();
512
533
  const status = Object.fromEntries(pages.filter((p) => p.path === null).map((p) => [p.recipe, byId.get(p.recipe)?.status ?? 404]));
513
534
  const broken = unaddressed(pages, byId, 500);
514
535
  const sample = pages.find((p) => p.access === "public" && p.path !== null);
@@ -521,7 +542,7 @@ function testFile(base, pages, byId) {
521
542
  // in the project's look, with each of its words from the catalogue; and
522
543
  // workbench/site.json matches the page files (check:site).
523
544
 
524
- import { siteProblems } from "${PACKAGE}";
545
+ import { ${tools.length ? "RECIPES, " : ""}siteProblems } from "${PACKAGE}";${tools.map((t) => `\nimport { RECIPES as ${recipesName(t)} } from "${t}/recipes";`).join("")}
525
546
  import { ${enquiries ? "beforeEach, " : ""}describe, expect, it${enquiries || (broken && sample) ? ", vi" : ""} } from "vitest";
526
547
  import worker from "../src/index.ts";
527
548
  ${enquiries ? 'import { enquiryCount } from "../src/pages/enquiry-count.ts";\nimport { enquiryStore } from "../src/pages/enquiry-store.ts";\n' : ""}import { PAGES } from "../src/pages/index.ts";
@@ -544,7 +565,7 @@ const files = import.meta.glob<string>("../src/pages/*.ts", { query: "?raw", imp
544
565
  describe("site pages", () => {
545
566
  ${enquiries ? " // The enquiries table isn't reached: each test says what it holds.\n beforeEach(() => {\n vi.spyOn(enquiryStore, \"list\").mockResolvedValue([]);\n vi.spyOn(enquiryCount, \"count\").mockResolvedValue(0);\n });\n\n" : ""} it("workbench/site.json matches the page files and the strings catalogue (check:site)", () => {
546
567
  const byPath = Object.fromEntries(Object.entries(files).map(([path, text]) => [path.replace(/^\\.\\.\\//, ""), text]));
547
- expect(siteProblems({ site, strings, files: byPath })).toEqual([]);
568
+ expect(siteProblems({ site, strings, files: byPath${tools.length ? `, catalogue: [...RECIPES, ${tools.map((t) => `...${recipesName(t)}`).join(", ")}]` : ""} })).toEqual([]);
548
569
  });
549
570
 
550
571
  for (const page of PAGES) {
package/dist/cli.d.ts CHANGED
@@ -1,8 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { type RecipeSource } from "./gather.ts";
3
+ /**
4
+ * The recipes of every Workbench package the project depends on that exports
5
+ * them (RECIPES from "<package>/recipes"), read from its node_modules. A
6
+ * package without the export has no pages; one that can't be loaded is named.
7
+ */
8
+ export declare function recipeSources(dir: string): Promise<{
9
+ sources: RecipeSource[];
10
+ problems: string[];
11
+ }>;
2
12
  export interface CliDeps {
3
13
  log: (line: string) => void;
4
14
  error: (line: string) => void;
5
15
  /** Runs a command in the project; returns its exit code. */
6
16
  run: (cmd: string, args: readonly string[], cwd: string) => number;
7
17
  }
8
- export declare function main(argv: readonly string[], deps?: CliDeps): number;
18
+ export declare function main(argv: readonly string[], deps?: CliDeps): Promise<number>;
package/dist/cli.js CHANGED
@@ -13,13 +13,21 @@
13
13
  // workbench/site.json against the page files and the strings catalogue
14
14
  // (siteProblems). With --live, before go-live, a built page's word still in
15
15
  // [square brackets] fails too.
16
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
17
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
18
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
19
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
20
+ });
21
+ }
22
+ return path;
23
+ };
16
24
  import { spawnSync } from "node:child_process";
17
25
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
18
26
  import { dirname, join, resolve } from "node:path";
19
- import { fileURLToPath } from "node:url";
27
+ import { fileURLToPath, pathToFileURL } from "node:url";
20
28
  import { buildSite, SITE_FILE, siteProblems } from "./builder.js";
29
+ import { gatherRecipes, RECIPES_EXPORT } from "./gather.js";
21
30
  import { GROUPS } from "./recipe.js";
22
- import { RECIPES } from "./recipes/index.js";
23
31
  const USAGE = ["Usage: workbench-site list", " workbench-site add [<page>...] [--dir <project>] [--no-install]", " workbench-site check [--live] [--dir <project>]"].join("\n");
24
32
  const TIER_NAMES = { always: "always built", ticked: "ask, ticked", offered: "ask, not ticked" };
25
33
  const GROUP_NAMES = { "every-site": "Every site", members: "Members", admin: "Admin", business: "For your business" };
@@ -27,12 +35,49 @@ function version() {
27
35
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
28
36
  return pkg.version;
29
37
  }
38
+ /**
39
+ * The recipes of every Workbench package the project depends on that exports
40
+ * them (RECIPES from "<package>/recipes"), read from its node_modules. A
41
+ * package without the export has no pages; one that can't be loaded is named.
42
+ */
43
+ export async function recipeSources(dir) {
44
+ const sources = [];
45
+ const problems = [];
46
+ let deps = {};
47
+ try {
48
+ deps = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).dependencies ?? {};
49
+ }
50
+ catch {
51
+ return { sources, problems };
52
+ }
53
+ for (const name of Object.keys(deps).filter((d) => /^@mccaskie-labs\/workbench-[a-z]+$/.test(d) && d !== "@mccaskie-labs/workbench-site").sort()) {
54
+ const root = join(dir, "node_modules", ...name.split("/"));
55
+ let target;
56
+ try {
57
+ target = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).exports?.[RECIPES_EXPORT];
58
+ }
59
+ catch {
60
+ continue; // Not installed yet: npm install brings it, and its pages with it.
61
+ }
62
+ const file = typeof target === "string" ? target : target && typeof target === "object" ? (target.import ?? target.default) : undefined;
63
+ if (typeof file !== "string")
64
+ continue;
65
+ try {
66
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(root, file)).href)));
67
+ sources.push({ package: name, recipes: mod.RECIPES });
68
+ }
69
+ catch (e) {
70
+ problems.push(`${name}: its recipes couldn't be loaded (${e.message}), so its pages are left out.`);
71
+ }
72
+ }
73
+ return { sources, problems };
74
+ }
30
75
  const realDeps = {
31
76
  log: (l) => console.log(l),
32
77
  error: (l) => console.error(l),
33
78
  run: (cmd, args, cwd) => spawnSync(cmd, [...args], { cwd, stdio: "inherit", shell: process.platform === "win32" }).status ?? 1,
34
79
  };
35
- export function main(argv, deps = realDeps) {
80
+ export async function main(argv, deps = realDeps) {
36
81
  const args = [...argv];
37
82
  const take = (name) => {
38
83
  const at = args.indexOf(name);
@@ -48,14 +93,20 @@ export function main(argv, deps = realDeps) {
48
93
  const noInstall = flag("--no-install");
49
94
  const live = flag("--live");
50
95
  const [command, ...ids] = args;
96
+ // This package's recipes and those of the tools the project has installed.
97
+ const found = await recipeSources(dir);
98
+ const gathered = gatherRecipes(found.sources);
99
+ for (const p of [...found.problems, ...gathered.problems])
100
+ deps.error(`! ${p}`);
101
+ const { catalogue, from } = gathered;
51
102
  if (command === "list") {
52
103
  for (const g of GROUPS) {
53
- const rs = RECIPES.filter((r) => r.group === g);
104
+ const rs = catalogue.filter((r) => r.group === g);
54
105
  if (!rs.length)
55
106
  continue;
56
107
  deps.log(`${GROUP_NAMES[g]}:`);
57
108
  for (const r of rs)
58
- deps.log(` ${r.id.padEnd(14)} ${(r.path ?? (r.status === 500 ? "(when a page breaks)" : "(any missing address)")).padEnd(20)} ${TIER_NAMES[r.tier].padEnd(16)} ${r.does}`);
109
+ deps.log(` ${r.id.padEnd(14)} ${(r.path ?? (r.status === 500 ? "(when a page breaks)" : "(any missing address)")).padEnd(20)} ${TIER_NAMES[r.tier].padEnd(16)} ${r.does}${from[r.id] ? ` (${from[r.id]})` : ""}`);
59
110
  }
60
111
  return 0;
61
112
  }
@@ -69,7 +120,7 @@ export function main(argv, deps = realDeps) {
69
120
  const files = Object.fromEntries((existsSync(pagesDir) ? readdirSync(pagesDir) : []).filter((f) => f.endsWith(".ts")).map((f) => [`src/pages/${f}`, readFileSync(join(pagesDir, f), "utf8")]));
70
121
  let problems;
71
122
  try {
72
- problems = siteProblems({ site: read(SITE_FILE), strings: read("strings/strings.en-AU.json"), files, live });
123
+ problems = siteProblems({ site: read(SITE_FILE), strings: read("strings/strings.en-AU.json"), files, live, catalogue });
73
124
  }
74
125
  catch (e) {
75
126
  deps.error(`✗ ${e.message}`);
@@ -85,7 +136,7 @@ export function main(argv, deps = realDeps) {
85
136
  deps.error(USAGE);
86
137
  return 2;
87
138
  }
88
- const result = buildSite({ read: (p) => (existsSync(join(dir, p)) ? readFileSync(join(dir, p), "utf8") : undefined), add: ids, version: version(), list: (d) => (existsSync(join(dir, d)) ? readdirSync(join(dir, d)) : undefined) });
139
+ const result = buildSite({ read: (p) => (existsSync(join(dir, p)) ? readFileSync(join(dir, p), "utf8") : undefined), add: ids, catalogue, from, version: version(), list: (d) => (existsSync(join(dir, d)) ? readdirSync(join(dir, d)) : undefined) });
89
140
  if (result.problems.length) {
90
141
  for (const p of result.problems)
91
142
  deps.error(`✗ ${p}`);
@@ -125,4 +176,4 @@ export function main(argv, deps = realDeps) {
125
176
  }
126
177
  const self = fileURLToPath(import.meta.url);
127
178
  if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(self))
128
- process.exit(main(process.argv.slice(2)));
179
+ process.exit(await main(process.argv.slice(2)));
@@ -0,0 +1,20 @@
1
+ import { type Recipe } from "./recipe.ts";
2
+ /** The subpath a tool package exports its recipes from, as `export const RECIPES: readonly Recipe[]`. */
3
+ export declare const RECIPES_EXPORT = "./recipes";
4
+ /** One package's recipes, as it exported them. */
5
+ export interface RecipeSource {
6
+ /** Its npm name, such as @mccaskie-labs/workbench-bookings. */
7
+ package: string;
8
+ /** Its RECIPES export: unknown until checked. */
9
+ recipes: unknown;
10
+ }
11
+ export interface GatheredRecipes {
12
+ /** This package's recipes, then each source's, in the order given. */
13
+ catalogue: Recipe[];
14
+ /** Which package each gathered recipe came from, by recipe id: this package's own are left out. */
15
+ from: Record<string, string>;
16
+ /** A source that isn't a list of recipes, or a recipe id another package already has. Its recipes are left out. */
17
+ problems: string[];
18
+ }
19
+ /** This package's recipes and every source's, each id once. Run recipeProblems (buildSite does) on the result. */
20
+ export declare function gatherRecipes(sources: readonly RecipeSource[], own?: readonly Recipe[]): GatheredRecipes;
package/dist/gather.js ADDED
@@ -0,0 +1,50 @@
1
+ // Recipes from other tools (docs/site-planner.md §5, docs/builder-ready.md B5):
2
+ // a tool's own pages are recipes in that tool's package, exported as RECIPES
3
+ // from "<package>/recipes". The CLI finds the Workbench packages a project has
4
+ // installed and gathers theirs beside this package's own; buildSite and
5
+ // siteProblems take the gathered catalogue. Plain data in, plain data out.
6
+ import { recipeProblems } from "./recipe.js";
7
+ import { RECIPES } from "./recipes/index.js";
8
+ /** The subpath a tool package exports its recipes from, as `export const RECIPES: readonly Recipe[]`. */
9
+ export const RECIPES_EXPORT = "./recipes";
10
+ const looksLikeRecipe = (r) => !!r && typeof r === "object" && typeof r.id === "string" && Array.isArray(r.sections) && typeof r.words === "object";
11
+ /** This package's recipes and every source's, each id once. Run recipeProblems (buildSite does) on the result. */
12
+ export function gatherRecipes(sources, own = RECIPES) {
13
+ const catalogue = [...own];
14
+ const owner = new Map(own.map((r) => [r.id, "@mccaskie-labs/workbench-site"]));
15
+ const from = {};
16
+ const problems = [];
17
+ for (const s of [...sources].sort((a, b) => (a.package < b.package ? -1 : a.package > b.package ? 1 : 0))) {
18
+ if (!Array.isArray(s.recipes) || !s.recipes.every(looksLikeRecipe)) {
19
+ problems.push(`${s.package}: its ${RECIPES_EXPORT} export isn't a list of page recipes, so its pages are left out.`);
20
+ continue;
21
+ }
22
+ const ids = s.recipes.map((r) => r.id);
23
+ const twice = ids.filter((id, i) => ids.indexOf(id) !== i);
24
+ if (twice.length) {
25
+ problems.push(`${s.package}: ${[...new Set(twice)].join(", ")} is in its recipes twice, so its pages are left out.`);
26
+ continue;
27
+ }
28
+ const clash = s.recipes.filter((r) => owner.has(r.id));
29
+ if (clash.length) {
30
+ problems.push(`${s.package}: ${clash.map((r) => `${r.id} is already ${owner.get(r.id)}'s`).join(", ")}, so its pages are left out.`);
31
+ continue;
32
+ }
33
+ for (const r of s.recipes) {
34
+ catalogue.push(r);
35
+ owner.set(r.id, s.package);
36
+ from[r.id] = s.package;
37
+ }
38
+ }
39
+ // A package whose recipe can't be built is left out whole, so the site's own pages and the other tools' still build.
40
+ for (const pkg of [...new Set(Object.values(from))]) {
41
+ const bad = catalogue.filter((r) => from[r.id] === pkg).flatMap((r) => recipeProblems(r, catalogue));
42
+ if (!bad.length)
43
+ continue;
44
+ problems.push(`${pkg}: ${bad.join("; ")}. Its pages are left out.`);
45
+ for (const id of Object.keys(from))
46
+ if (from[id] === pkg)
47
+ delete from[id];
48
+ }
49
+ return { catalogue: catalogue.filter((r) => !owner.has(r.id) || owner.get(r.id) === "@mccaskie-labs/workbench-site" || r.id in from), from, problems };
50
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { frame, FOOTERS, FRAMES, HEADERS, type FooterStyle, type FrameLayout, type FrameName, type FrameOptions, type HeaderStyle, type MenuLink } from "./frames.ts";
2
2
  export { escape } from "./html.ts";
3
3
  export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, needsYou, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, type AccountOptions, type Action, type CallToActionOptions, type DesignSwitchOptions, type DetailRow, type DetailsOptions, type Enquiry, type EnquiryListOptions, type NeedsYouItem, type NeedsYouOptions, type FormSectionOptions, type HeroArrangement, type HeroOptions, type ListItem, type ListOptions, type Picture, type PictureOptions, type TextOptions, } from "./sections.ts";
4
- export { recipeKeys, recipeProblems, TIERS, type ActionSpec, type Area, type Group, type Recipe, type SectionSpec, type Tier } from "./recipe.ts";
4
+ export { recipeKeys, recipeProblems, TIERS, type ActionSpec, type Area, type Group, type PageWords, type Recipe, type SectionSpec, type Tier, type ToolSectionFunction } from "./recipe.ts";
5
5
  export { RECIPES } from "./recipes/index.ts";
6
+ export { gatherRecipes, RECIPES_EXPORT, type GatheredRecipes, type RecipeSource } from "./gather.ts";
6
7
  export { alwaysSet, buildSite, SITE_FILE, siteProblems, type BuildOptions, type BuildResult, type SiteCheckInput, type SitePageRecord, type SiteRecord } from "./builder.ts";
package/dist/index.js CHANGED
@@ -6,4 +6,5 @@ export { escape } from "./html.js";
6
6
  export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, needsYou, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, } from "./sections.js";
7
7
  export { recipeKeys, recipeProblems, TIERS } from "./recipe.js";
8
8
  export { RECIPES } from "./recipes/index.js";
9
+ export { gatherRecipes, RECIPES_EXPORT } from "./gather.js";
9
10
  export { alwaysSet, buildSite, SITE_FILE, siteProblems } from "./builder.js";
package/dist/recipe.d.ts CHANGED
@@ -108,6 +108,18 @@ export type SectionSpec = {
108
108
  turnOn: WordKey;
109
109
  turnOff: WordKey;
110
110
  live: WordKey;
111
+ }
112
+ /**
113
+ * A section a tool draws itself (docs/builder-ready.md B5): `fn`, exported by
114
+ * the tool's package `from`, is a ToolSectionFunction. The page file calls it
115
+ * with (request, env, ctx) before drawing, and draws what it gives back with
116
+ * the page's words. `words` are the keys it says, under the page's own prefix.
117
+ */
118
+ | {
119
+ kind: "tool";
120
+ from: string;
121
+ fn: string;
122
+ words: readonly WordKey[];
111
123
  } | {
112
124
  kind: "look-preview";
113
125
  home: WordKey;
@@ -135,7 +147,24 @@ export declare const SECTION_FUNCTIONS: {
135
147
  readonly "style-guide": "styleGuide";
136
148
  readonly "look-preview": "lookPreview";
137
149
  readonly "design-switch": "designSwitch";
150
+ readonly tool: "";
138
151
  };
152
+ /** Looks up one of the page's words in the visitor's language, with any values it says. */
153
+ export type PageWords = (key: WordKey, values?: Record<string, string>) => string;
154
+ /**
155
+ * What a tool's own section exports (SectionSpec kind "tool"): called with the
156
+ * request, the Worker's env and who is asking before the page is drawn (it may
157
+ * read the database as them, with ctx.accessToken), it gives back a function
158
+ * that draws the section's HTML with the page's words. Every element it draws
159
+ * carries the tool's own wb-<tool>-* classes.
160
+ */
161
+ export type ToolSectionFunction = (request: Request, env: object, ctx: {
162
+ user: {
163
+ id: string;
164
+ email: string;
165
+ } | null;
166
+ accessToken?: string;
167
+ }) => ((w: PageWords) => string) | Promise<(w: PageWords) => string>;
139
168
  /** Sections whose function is in the project's own src/pages/enquiry-store.ts, which the Enquiries recipe writes. */
140
169
  export declare const STORE_SECTIONS: ReadonlySet<SectionSpec["kind"]>;
141
170
  /** Sections whose function comes from workbench-ui, not this package. */
package/dist/recipe.js CHANGED
@@ -6,7 +6,7 @@
6
6
  import { FRAMES } from "./frames.js";
7
7
  import { HERO_ARRANGEMENTS } from "./sections.js";
8
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", "needs-you": "needsYou", "enquiry-form": "enquirySection", enquiries: "enquiriesSection", "style-guide": "styleGuide", "look-preview": "lookPreview", "design-switch": "designSwitch" };
9
+ export const SECTION_FUNCTIONS = { hero: "hero", text: "text", list: "list", call: "callToAction", details: "details", account: "account", "admin-menu": "list", "needs-you": "needsYou", "enquiry-form": "enquirySection", enquiries: "enquiriesSection", "style-guide": "styleGuide", "look-preview": "lookPreview", "design-switch": "designSwitch", tool: "" };
10
10
  /** Sections whose function is in the project's own src/pages/enquiry-store.ts, which the Enquiries recipe writes. */
11
11
  export const STORE_SECTIONS = new Set(["enquiry-form", "enquiries"]);
12
12
  /** Sections whose function comes from workbench-ui, not this package. */
@@ -47,6 +47,8 @@ function sectionKeys(s) {
47
47
  return [s.heading, s.empty, s.unavailable, s.remove].filter((k) => !!k);
48
48
  case "style-guide":
49
49
  return [s.views, s.light, s.dark, s.admin, s.empty, s.layout];
50
+ case "tool":
51
+ return [...s.words];
50
52
  case "design-switch":
51
53
  return [s.on, s.off, s.turnOn, s.turnOff, s.live];
52
54
  case "look-preview":
@@ -152,6 +154,8 @@ export function recipeProblems(r, catalogue) {
152
154
  p("the look previewer is for admin pages");
153
155
  if (s.kind === "design-switch" && r.area !== "admin")
154
156
  p("design mode's switch is for admin pages");
157
+ if (s.kind === "tool" && (!/^@mccaskie-labs\/workbench-[a-z]+$/.test(s.from) || s.from === "@mccaskie-labs/workbench-site" || !/^[a-z][A-Za-z0-9]*$/.test(s.fn)))
158
+ p(`a tool section comes from another Workbench package and names its function (${s.from}, ${s.fn})`);
155
159
  }
156
160
  for (const l of r.links ?? [])
157
161
  if (!/^\/admin(\/|$)/.test(l.href) || r.area !== "admin")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-site",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "A Workbench project's standard pages: page recipes, the builder that turns them into thin page files calling Workbench's tools, and the page frames and sections they are drawn with (wb-site-*, restylable, on the project's theme tokens).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",