@bright-logic-digital/site-editor 0.0.0-stage → 1.0.0-rc.1

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +4 -0
  3. package/README.md +318 -2
  4. package/bin/cli.js +92 -0
  5. package/bin/copy-editor.js +211 -0
  6. package/bin/node-version.js +20 -0
  7. package/bin/site-config.js +46 -0
  8. package/bin/site-editor.js +16 -0
  9. package/editor/admin.css +438 -0
  10. package/editor/api.js +138 -0
  11. package/editor/app.js +1178 -0
  12. package/editor/asset-map.js +38 -0
  13. package/editor/boot.js +72 -0
  14. package/editor/copy.js +239 -0
  15. package/editor/drafts.js +67 -0
  16. package/editor/format.js +80 -0
  17. package/editor/forms.js +918 -0
  18. package/editor/images.js +212 -0
  19. package/editor/index.html +27 -0
  20. package/editor/model.js +152 -0
  21. package/editor/pages.js +297 -0
  22. package/editor/photos.js +232 -0
  23. package/editor/publish.js +45 -0
  24. package/editor/shared/rules.js +118 -0
  25. package/editor/shared/site.js +128 -0
  26. package/editor/shared/validate.js +303 -0
  27. package/editor/signin.js +154 -0
  28. package/editor/status.js +90 -0
  29. package/editor/uploads.js +91 -0
  30. package/guide/check.js +233 -0
  31. package/hosts/next.js +19 -0
  32. package/hosts/pages.js +20 -0
  33. package/hosts/shared.js +42 -0
  34. package/package.json +91 -4
  35. package/server/blob-sha.js +10 -0
  36. package/server/changes.js +24 -0
  37. package/server/check-content.js +197 -0
  38. package/server/config.js +97 -0
  39. package/server/dispatch.js +207 -0
  40. package/server/github.js +149 -0
  41. package/server/handlers.js +364 -0
  42. package/server/index.js +153 -0
  43. package/server/local-repo.js +171 -0
  44. package/server/mapped-repo.js +48 -0
  45. package/server/memory-repo.js +104 -0
  46. package/server/path-map.js +26 -0
  47. package/server/signin/access.js +329 -0
  48. package/server/signin/code-store.sql +60 -0
  49. package/server/signin/code.js +192 -0
  50. package/server/signin/codes.js +171 -0
  51. package/server/signin/refusal.js +76 -0
  52. package/server/signin/session.js +90 -0
  53. package/tests/fixtures/image-files.json +14 -0
  54. package/tests/fixtures/slugs.json +202 -0
  55. package/tests/fixtures/validation.json +12734 -0
  56. package/types/bin/cli.d.ts +1 -0
  57. package/types/bin/copy-editor.d.ts +32 -0
  58. package/types/bin/node-version.d.ts +8 -0
  59. package/types/bin/site-config.d.ts +17 -0
  60. package/types/bin/site-editor.d.ts +2 -0
  61. package/types/editor/api.d.ts +37 -0
  62. package/types/editor/copy.d.ts +153 -0
  63. package/types/editor/shared/rules.d.ts +33 -0
  64. package/types/editor/shared/site.d.ts +35 -0
  65. package/types/editor/shared/validate.d.ts +19 -0
  66. package/types/guide/check.d.ts +31 -0
  67. package/types/hosts/next.d.ts +12 -0
  68. package/types/hosts/pages.d.ts +9 -0
  69. package/types/hosts/shared.d.ts +21 -0
  70. package/types/server/blob-sha.d.ts +1 -0
  71. package/types/server/changes.d.ts +2 -0
  72. package/types/server/check-content.d.ts +16 -0
  73. package/types/server/config.d.ts +46 -0
  74. package/types/server/dispatch.d.ts +51 -0
  75. package/types/server/github.d.ts +27 -0
  76. package/types/server/handlers.d.ts +116 -0
  77. package/types/server/index.d.ts +75 -0
  78. package/types/server/local-repo.d.ts +16 -0
  79. package/types/server/mapped-repo.d.ts +10 -0
  80. package/types/server/memory-repo.d.ts +28 -0
  81. package/types/server/path-map.d.ts +3 -0
  82. package/types/server/signin/access.d.ts +68 -0
  83. package/types/server/signin/code.d.ts +44 -0
  84. package/types/server/signin/codes.d.ts +98 -0
  85. package/types/server/signin/refusal.d.ts +122 -0
  86. package/types/server/signin/session.d.ts +29 -0
package/guide/check.js ADDED
@@ -0,0 +1,233 @@
1
+ // @ts-check
2
+ // A site's owner's guide (the page its config names as guide, served at
3
+ // /admin/guide.html) checked against the editor's own words under that
4
+ // site's config, so the two cannot drift apart. Every word of the editor the
5
+ // guide quotes is marked <strong class="ui">. A site's own test is:
6
+ //
7
+ // assert.deepEqual(guideProblems(guideHtml, config, schema), []);
8
+ //
9
+ // What only one site's guide says (its contents' length, the limits of its
10
+ // own schema, what its owner cannot change) stays in that site's tests.
11
+ import { ACTIONS, PHOTO_ERRORS, SIGN_IN_KEYS, STATUS, TEXT, addKindLabel, addLabel, codeSent } from "../editor/copy.js";
12
+ import { MAX_CUSTOM_PAGES } from "../editor/shared/rules.js";
13
+ import { SITE, browserConfig, configureSite, siteProblems } from "../editor/shared/site.js";
14
+ import {
15
+ CODE_DIGITS, CODE_TTL_MS, MAX_ATTEMPTS, MAX_CODES_PER_DAY, MAX_CODES_PER_HOUR,
16
+ } from "../server/signin/codes.js";
17
+ import { SIGN_IN_SENTENCES } from "../server/signin/code.js";
18
+ import { SESSION_MS } from "../server/signin/session.js";
19
+
20
+ /** @typedef {{ label?: string, itemLabel?: string, type?: string, fixed?: boolean,
21
+ * options?: Array<{ label: string }>, fields?: Field[] }} Field */
22
+ /** @typedef {{ documents: Record<string, { label: string, fields: Field[] }> }} Schema */
23
+
24
+ /** @type {Record<string, string>} */
25
+ const ENTITIES = { amp: "&", quot: "\"", apos: "'", lt: "<", gt: ">", "#39": "'" };
26
+ /** @param {string} s */
27
+ const decode = (s) => s.replace(/&(amp|quot|apos|lt|gt|#39);/g, (_, name) => ENTITIES[name]);
28
+
29
+ // Words the owner may not know, anywhere in the guide's text.
30
+ const JARGON = ["deploy", "commit", "schema", "slug", "repository", "api", "draft", "github", "cache",
31
+ "json", "vercel", "supabase", "resend", "token", "branch", "build"];
32
+
33
+ // The sign-in screen's labels the guide must name, with the emailed code.
34
+ const SIGN_IN_LABELS = ["Email me a code", "Sign in", "Send a new code", "Use a different address",
35
+ "Sign out", "Sign in again", "Email address", "Code"];
36
+
37
+ const DAY_MS = 24 * 60 * 60 * 1000;
38
+
39
+ // The fewest editor words a guide quotes: both sites' guides quote far more.
40
+ const MIN_LABELS = 30;
41
+
42
+ /**
43
+ * The text of every <strong class="ui"> in html, entities decoded and white
44
+ * space collapsed.
45
+ * @param {string} html
46
+ */
47
+ function quotedLabels(html) {
48
+ return [...html.matchAll(/<strong class="ui">([\s\S]*?)<\/strong>/g)]
49
+ .map((m) => decode(m[1]).replace(/\s+/g, " ").trim());
50
+ }
51
+
52
+ /**
53
+ * Every label the schema gives the editor: documents, fields, list items,
54
+ * choices, and the buttons made from them ("Add card", "Add a photo").
55
+ * @param {Schema} schema
56
+ */
57
+ function schemaLabels(schema) {
58
+ /** @type {Set<string>} */
59
+ const out = new Set();
60
+ /** @param {Field[]} fields */
61
+ const walk = (fields) => {
62
+ for (const f of fields) {
63
+ if (f.label) out.add(f.label);
64
+ if (f.itemLabel) out.add(f.itemLabel);
65
+ for (const o of f.options ?? []) {
66
+ out.add(o.label);
67
+ if (f.fixed === true) out.add(addKindLabel(o.label));
68
+ }
69
+ if (f.type === "list") {
70
+ const kinds = (f.fields ?? []).some((c) => c.type === "choice" && c.fixed === true);
71
+ if (!kinds) out.add(addLabel(f.itemLabel ?? f.label ?? ""));
72
+ }
73
+ if (f.fields) walk(f.fields);
74
+ }
75
+ };
76
+ for (const doc of Object.values(schema.documents)) {
77
+ out.add(doc.label);
78
+ walk(doc.fields);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /**
84
+ * The problems with a site's guide, one plain sentence each; empty when the
85
+ * guide agrees with the editor. Reads the editor's words under the site's
86
+ * config (its reworded sentences, its sign-in) and leaves the editor's site
87
+ * config (SITE) as it was.
88
+ * @param {string} html the guide's page
89
+ * @param {Record<string, any>} config the site's config file
90
+ * @param {Schema} schema the site's content/schema.json
91
+ * @param {{ minLabels?: number }} [options] minLabels: the fewest editor
92
+ * words the guide must quote, 30 unless a site's guide is short
93
+ * @returns {string[]}
94
+ */
95
+ export function guideProblems(html, config, schema, { minLabels = MIN_LABELS } = {}) {
96
+ const values = browserConfig(config);
97
+ const wrong = siteProblems(values);
98
+ if (wrong.length > 0) {
99
+ return [`The site's config has a problem with: ${wrong.join(", ")}.`];
100
+ }
101
+ const before = SITE;
102
+ configureSite(values);
103
+ try {
104
+ return problemsUnderSite(html, schema, minLabels);
105
+ } finally {
106
+ configureSite({ ...before });
107
+ }
108
+ }
109
+
110
+ /**
111
+ * @param {string} html
112
+ * @param {Schema} schema
113
+ * @param {number} minLabels
114
+ * @returns {string[]}
115
+ */
116
+ function problemsUnderSite(html, schema, minLabels) {
117
+ /** @type {string[]} */
118
+ const problems = [];
119
+ const say = (/** @type {string} */ sentence) => {
120
+ if (!problems.includes(sentence)) problems.push(sentence);
121
+ };
122
+ // Words only the other kind of sign-in shows are not this site's.
123
+ const otherKind = SITE.signIn === "code" ? SIGN_IN_KEYS.access : SIGN_IN_KEYS.code;
124
+ const editorWords = new Set([
125
+ ...Object.entries(TEXT).filter(([key]) => !otherKind.includes(key)).map(([, word]) => word), ...Object.values(STATUS), ...Object.values(ACTIONS),
126
+ ...Object.values(PHOTO_ERRORS), ...schemaLabels(schema),
127
+ ]);
128
+ const quoted = quotedLabels(html);
129
+
130
+ // Every editor word it quotes is one the editor shows.
131
+ // Too few means marks were lost, and with them the check of those words.
132
+ if (quoted.length < minLabels) {
133
+ say(`The guide quotes ${quoted.length} of the editor's words with <strong class="ui">; ` +
134
+ `at least ${minLabels} are expected.`);
135
+ }
136
+ for (const label of quoted) {
137
+ if (!editorWords.has(label)) say(`The guide quotes "${label}", which the editor does not show.`);
138
+ }
139
+
140
+ // It speaks the owner's language.
141
+ const text = decode(html.replace(/<[^>]*>/g, " ")).toLowerCase();
142
+ for (const word of JARGON) {
143
+ if (new RegExp(`\\b${word}`).test(text)) say(`The guide uses the word "${word}", which the owner may not know.`);
144
+ }
145
+
146
+ // It is not indexed, uses the editor's stylesheet and runs nothing.
147
+ for (const [tag, name] of [
148
+ ['<meta name="robots" content="noindex">', "noindex"],
149
+ ['<meta name="viewport" content="width=device-width, initial-scale=1">', "viewport"],
150
+ ['<link rel="stylesheet" href="/admin/admin.css">', "the editor's stylesheet"],
151
+ ]) {
152
+ if (!html.includes(tag)) say(`The guide is missing ${name}: ${tag}`);
153
+ }
154
+ if (/<script\b/.test(html)) say("The guide has a <script>; it must run nothing.");
155
+
156
+ // It sends its reader back by closing its tab, with one link for those
157
+ // who came from elsewhere.
158
+ if (!/This help opened in its own tab\. [^<]*To go back to it, close this tab\./.test(html)) {
159
+ say('The guide does not say "This help opened in its own tab." and "To go back to it, close this tab."');
160
+ }
161
+ const back = [...html.matchAll(/<a class="back" href="\/admin\/">Back to the editor<\/a>/g)];
162
+ if (back.length !== 1) {
163
+ say(`The guide needs one link <a class="back" href="/admin/">Back to the editor</a>; it has ${back.length}.`);
164
+ } else if (!(html.indexOf("If you came here from a link someone sent you") < /** @type {number} */ (back[0].index))) {
165
+ say('The guide\'s Back to the editor link must follow "If you came here from a link someone sent you".');
166
+ }
167
+
168
+ // Every contents link leads to a section.
169
+ for (const [, id] of html.matchAll(/href="#([^"]+)"/g)) {
170
+ if (!html.includes(`id="${id}"`)) say(`The guide links to #${id}, which no section of it is.`);
171
+ }
172
+
173
+ // Plain bold is what the owner types, never an editor word left unchecked.
174
+ for (const [, inner] of html.matchAll(/<strong>([\s\S]*?)<\/strong>/g)) {
175
+ const words = decode(inner).replace(/\s+/g, " ").trim();
176
+ if (editorWords.has(words)) {
177
+ say(`The guide shows "${words}" in plain bold; it is the editor's word, so mark it <strong class="ui">.`);
178
+ }
179
+ }
180
+
181
+ // The number of extra pages the site can hold.
182
+ if (Object.hasOwn(schema.documents, "custom") && !html.includes(`hold ${MAX_CUSTOM_PAGES} extra pages`)) {
183
+ say(`The guide does not say the site can "hold ${MAX_CUSTOM_PAGES} extra pages".`);
184
+ }
185
+
186
+ if (SITE.signIn === "code") codeSignInProblems(html, quoted).forEach(say);
187
+ return problems;
188
+ }
189
+
190
+ /**
191
+ * With the editor's own sign-in (an emailed code): the guide states its
192
+ * rules, quotes its sentences and names its buttons, and mentions no tab
193
+ * but its own.
194
+ * @param {string} html
195
+ * @param {string[]} quoted
196
+ * @returns {string[]}
197
+ */
198
+ function codeSignInProblems(html, quoted) {
199
+ /** @type {string[]} */
200
+ const problems = [];
201
+ const days = Math.round(SESSION_MS / DAY_MS);
202
+ const rules = [
203
+ `code of ${CODE_DIGITS} numbers`,
204
+ `works once, and only for ${CODE_TTL_MS / 60000} minutes`,
205
+ `After ${MAX_ATTEMPTS} wrong tries`,
206
+ `up to ${MAX_CODES_PER_HOUR} codes in an hour and ${MAX_CODES_PER_DAY} in a day`,
207
+ // How long a sign-in lasts: 30 days.
208
+ days === 30 ? "about a month" : `${days} days`,
209
+ ];
210
+ for (const rule of rules) {
211
+ if (!html.includes(rule)) problems.push(`The guide does not say "${rule}", as the sign-in works.`);
212
+ }
213
+ for (const sentence of [TEXT.signedOut, ...Object.values(SIGN_IN_SENTENCES)]) {
214
+ if (!html.includes(sentence)) problems.push(`The guide does not quote the sign-in's sentence "${sentence}"`);
215
+ }
216
+ const sent = /The screen says "([^"]+)"/.exec(html)?.[1];
217
+ if (!sent || !codeSent("x@example.com").startsWith(sent)) {
218
+ problems.push(`The guide does not quote the start of "${codeSent("<address>")}" as: The screen says "..."`);
219
+ }
220
+ for (const label of SIGN_IN_LABELS) {
221
+ if (!quoted.includes(label)) {
222
+ problems.push(`The guide does not name "${label}"; quote it as <strong class="ui">${label}</strong>.`);
223
+ }
224
+ }
225
+ if (/opens in a new tab|another tab/i.test(html)) {
226
+ problems.push("The guide says something opens in another tab; with this sign-in nothing does.");
227
+ }
228
+ // The notice about the guide's own tab is the only mention of a tab.
229
+ if (/\btabs?\b/i.test(html.replace(/<p class="notice">[\s\S]*?<\/p>/, ""))) {
230
+ problems.push("The guide mentions a tab other than in its notice about its own tab.");
231
+ }
232
+ return problems;
233
+ }
package/hosts/next.js ADDED
@@ -0,0 +1,19 @@
1
+ // @ts-check
2
+ // The editor's API as a Next.js route handler. In the site's
3
+ // app/api/admin/[...path]/route.js (Node runtime):
4
+ //
5
+ // export const { GET, HEAD, POST, PUT, PATCH, DELETE } = createNextRoute(options);
6
+ //
7
+ // The settings are process.env. Nothing here imports Next.
8
+ import { lazyApi } from "./shared.js";
9
+
10
+ /**
11
+ * @param {import("./shared.js").HostOptions} options
12
+ * createEditorApi's options, or a function that gives them
13
+ */
14
+ export function createNextRoute(options) {
15
+ const handle = lazyApi(options);
16
+ /** @param {Request} request */
17
+ const route = (request) => handle(request, process.env);
18
+ return { GET: route, HEAD: route, POST: route, PUT: route, PATCH: route, DELETE: route };
19
+ }
package/hosts/pages.js ADDED
@@ -0,0 +1,20 @@
1
+ // @ts-check
2
+ // The editor's API as a Cloudflare Pages Function. In the site's
3
+ // functions/api/admin/[[path]].js:
4
+ //
5
+ // export const onRequest = createPagesFunction(options);
6
+ //
7
+ // The settings arrive with each request (context.env). Nothing this file
8
+ // reaches imports a node: module or anything outside the package
9
+ // (tests/pages-graph.test.js), so Cloudflare's bundler takes it as it is.
10
+ import { lazyApi } from "./shared.js";
11
+
12
+ /**
13
+ * @param {import("./shared.js").HostOptions} options
14
+ * createEditorApi's options, or a function that gives them
15
+ * @returns {(context: { request: Request, env: Record<string, string | undefined> }) => Promise<Response>}
16
+ */
17
+ export function createPagesFunction(options) {
18
+ const handle = lazyApi(options);
19
+ return (context) => handle(context.request, context.env);
20
+ }
@@ -0,0 +1,42 @@
1
+ // @ts-check
2
+ // What both entry points share: the API built on the first request, and
3
+ // the fixed answer when it cannot be built. Runs in Workers and Node.
4
+ import { failure, respond } from "../server/handlers.js";
5
+ import { createEditorApi } from "../server/index.js";
6
+ import { failureLine } from "../server/signin/refusal.js";
7
+
8
+ /** @typedef {import("../server/index.js").EditorApiOptions} EditorApiOptions */
9
+
10
+ /**
11
+ * The options, or a function that gives them (so a site can build its code
12
+ * store or local repository only when the first request arrives).
13
+ * @typedef {EditorApiOptions | (() => EditorApiOptions)} HostOptions
14
+ */
15
+
16
+ /**
17
+ * A handler that builds the API once, on its first request, and then
18
+ * hands it every request. If building throws (a wrong config, say), the
19
+ * answer is the dispatcher's fixed 500 and the log gets the message only;
20
+ * the next request tries again.
21
+ * @param {HostOptions} options
22
+ * @returns {(request: Request, env: Record<string, string | undefined>) => Promise<Response>}
23
+ */
24
+ export function lazyApi(options) {
25
+ /** @type {ReturnType<typeof createEditorApi> | undefined} */
26
+ let api;
27
+ return async (request, env) => {
28
+ if (!api) {
29
+ /** @type {EditorApiOptions | undefined} */
30
+ let given;
31
+ try {
32
+ given = typeof options === "function" ? options() : options;
33
+ api = createEditorApi(given);
34
+ } catch (err) {
35
+ const log = given?.log ?? ((/** @type {string} */ line) => console.error(line));
36
+ log(failureLine("setup", err));
37
+ return respond(failure(500, "server_error", "Something went wrong. Please try again."));
38
+ }
39
+ }
40
+ return api.handle(request, env);
41
+ };
42
+ }
package/package.json CHANGED
@@ -1,6 +1,93 @@
1
1
  {
2
2
  "name": "@bright-logic-digital/site-editor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-rc.1",
4
+ "description": "A website editor for small-business owners: the editor page, its API, and the command that adds them to a site.",
5
+ "license": "UNLICENSED",
6
+ "repository": "github:nicholaspsmith/site-editor",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
11
+ "bin": {
12
+ "site-editor": "bin/site-editor.js"
13
+ },
14
+ "exports": {
15
+ "./server": {
16
+ "types": "./types/server/index.d.ts",
17
+ "default": "./server/index.js"
18
+ },
19
+ "./server/signin/code": {
20
+ "types": "./types/server/signin/code.d.ts",
21
+ "default": "./server/signin/code.js"
22
+ },
23
+ "./server/signin/access": {
24
+ "types": "./types/server/signin/access.d.ts",
25
+ "default": "./server/signin/access.js"
26
+ },
27
+ "./server/local-repo": {
28
+ "types": "./types/server/local-repo.d.ts",
29
+ "default": "./server/local-repo.js"
30
+ },
31
+ "./server/memory-repo": {
32
+ "types": "./types/server/memory-repo.d.ts",
33
+ "default": "./server/memory-repo.js"
34
+ },
35
+ "./server/check-content": {
36
+ "types": "./types/server/check-content.d.ts",
37
+ "default": "./server/check-content.js"
38
+ },
39
+ "./hosts/next": {
40
+ "types": "./types/hosts/next.d.ts",
41
+ "default": "./hosts/next.js"
42
+ },
43
+ "./hosts/pages": {
44
+ "types": "./types/hosts/pages.d.ts",
45
+ "default": "./hosts/pages.js"
46
+ },
47
+ "./shared/rules": {
48
+ "types": "./types/editor/shared/rules.d.ts",
49
+ "default": "./editor/shared/rules.js"
50
+ },
51
+ "./shared/validate": {
52
+ "types": "./types/editor/shared/validate.d.ts",
53
+ "default": "./editor/shared/validate.js"
54
+ },
55
+ "./shared/site": {
56
+ "types": "./types/editor/shared/site.d.ts",
57
+ "default": "./editor/shared/site.js"
58
+ },
59
+ "./guide/check": {
60
+ "types": "./types/guide/check.d.ts",
61
+ "default": "./guide/check.js"
62
+ },
63
+ "./fixtures/validation.json": "./tests/fixtures/validation.json",
64
+ "./fixtures/slugs.json": "./tests/fixtures/slugs.json",
65
+ "./fixtures/image-files.json": "./tests/fixtures/image-files.json"
66
+ },
67
+ "files": [
68
+ "editor/",
69
+ "server/",
70
+ "hosts/",
71
+ "bin/",
72
+ "guide/",
73
+ "types/",
74
+ "CHANGELOG.md",
75
+ "tests/fixtures/validation.json",
76
+ "tests/fixtures/slugs.json",
77
+ "tests/fixtures/image-files.json",
78
+ "!**/*.test.*"
79
+ ],
80
+ "publishConfig": {
81
+ "access": "public"
82
+ },
83
+ "scripts": {
84
+ "test": "vitest run && node --test \"tests/**/*.test.js\"",
85
+ "types": "rm -rf types && tsc -p .",
86
+ "prepack": "rm -rf types && tsc -p ."
87
+ },
88
+ "devDependencies": {
89
+ "@types/node": "^24.19.2",
90
+ "typescript": "^5",
91
+ "vitest": "^4.1.6"
92
+ }
93
+ }
@@ -0,0 +1,10 @@
1
+ // Git blob sha: sha1("blob <byte length>\0" + bytes). Equals `git hash-object`.
2
+ export async function blobSha(input) {
3
+ const body = typeof input === "string" ? new TextEncoder().encode(input) : input;
4
+ const header = new TextEncoder().encode(`blob ${body.length}\0`);
5
+ const all = new Uint8Array(header.length + body.length);
6
+ all.set(header, 0);
7
+ all.set(body, header.length);
8
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-1", all));
9
+ return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
10
+ }
@@ -0,0 +1,24 @@
1
+ // The one check every Repo makes on commit's change list before doing
2
+ // anything: at least one change, each with a path and exactly one of
3
+ // {text}, {sha} or {remove: true}. Runs in Workers and Node.
4
+ const KINDS = {
5
+ text: (v) => typeof v === "string",
6
+ sha: (v) => typeof v === "string",
7
+ remove: (v) => v === true,
8
+ };
9
+
10
+ /** Throws a TypeError naming the first problem with changes. */
11
+ export function checkChanges(changes) {
12
+ if (!Array.isArray(changes) || changes.length === 0) {
13
+ throw new TypeError("commit needs at least one change");
14
+ }
15
+ for (const c of changes) {
16
+ if (typeof c !== "object" || c === null || typeof c.path !== "string" || c.path === "") {
17
+ throw new TypeError("Each change needs a path");
18
+ }
19
+ const kinds = Object.keys(KINDS).filter((k) => c[k] !== undefined);
20
+ if (kinds.length !== 1 || !KINDS[kinds[0]](c[kinds[0]])) {
21
+ throw new TypeError(`The change to ${c.path} needs exactly one of text, sha or remove`);
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,197 @@
1
+ // @ts-check
2
+ // The content check a site runs before its build (site-editor
3
+ // check-content): every document is valid, every photo it names has its
4
+ // files on disk, and every extra page's address is usable. Content and
5
+ // photos are found where the config's paths.local puts the editor's content/
6
+ // and assets/ under the app's folder; problems name the files as they sit
7
+ // there. Node only.
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { SITE, browserConfig, configureSite } from "../editor/shared/site.js";
11
+ import { docTypeForPath, imageFiles, validateDoc } from "../editor/shared/validate.js";
12
+ import { MAX_CUSTOM_PAGES, isUsableSlug } from "../editor/shared/rules.js";
13
+
14
+ /** @typedef {import("./signin/refusal.js").SiteConfig} SiteConfig */
15
+ /** @typedef {{ key: string, type: string, fields?: Field[] }} Field */
16
+
17
+ /**
18
+ * @param {unknown} v
19
+ * @returns {v is Record<string, any>}
20
+ */
21
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
22
+
23
+ /**
24
+ * [fieldPath, image] for every image in doc, in field order.
25
+ * @param {Field[]} fields
26
+ * @param {unknown} obj
27
+ * @param {string} at
28
+ * @param {Array<[string, Record<string, any>]>} out
29
+ */
30
+ function imagesWithPaths(fields, obj, at, out) {
31
+ for (const field of fields) {
32
+ const value = isObject(obj) ? obj[field.key] : undefined;
33
+ const here = at ? `${at}.${field.key}` : field.key;
34
+ if (field.type === "image" && isObject(value)) out.push([here, value]);
35
+ else if (field.type === "object") imagesWithPaths(field.fields ?? [], value, here, out);
36
+ else if (field.type === "list" && Array.isArray(value)) {
37
+ value.forEach((item, i) => imagesWithPaths(field.fields ?? [], item, `${here}[${i}]`, out));
38
+ }
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /**
44
+ * Every file under dir, as a path relative to it with "/" between names, in
45
+ * sorted order. A hidden file or folder (a name starting with ".") is not
46
+ * content: it is skipped, with everything inside it. A symbolic link to a
47
+ * folder is not followed. Walked by hand: readdirSync's recursive option
48
+ * does not exist before Node 20.1 and is ignored there.
49
+ * @param {string} dir
50
+ * @param {string} [prefix]
51
+ * @returns {string[]}
52
+ */
53
+ function filesUnder(dir, prefix = "") {
54
+ /** @type {string[]} */
55
+ const out = [];
56
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
57
+ if (entry.name.startsWith(".")) continue;
58
+ if (entry.isDirectory()) out.push(...filesUnder(path.join(dir, entry.name), `${prefix}${entry.name}/`));
59
+ else out.push(`${prefix}${entry.name}`);
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * Logical paths ("content/pages/about.json") of every JSON file in the
66
+ * content folder but the schema.
67
+ * @param {string} contentDir
68
+ */
69
+ function documentPaths(contentDir) {
70
+ return filesUnder(contentDir)
71
+ .filter((f) => f.endsWith(".json") && f !== "schema.json")
72
+ .sort()
73
+ .map((f) => `content/${f}`);
74
+ }
75
+
76
+ /**
77
+ * The site's folder for a logical path, from paths.local, or null when no
78
+ * folder takes it.
79
+ * @param {Array<[string, string]>} paths
80
+ * @param {string} logical
81
+ */
82
+ function localPath(paths, logical) {
83
+ for (const [name, folder] of paths) {
84
+ if (logical.startsWith(name)) return folder + logical.slice(name.length);
85
+ }
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * Problems with the content under appDir, each naming the file and field.
91
+ * Empty when the content is ready to build. Judges extra pages' addresses
92
+ * by the config's reserved names; leaves the editor's site config (SITE) as
93
+ * it was.
94
+ * @param {string} appDir the folder paths.local is relative to
95
+ * @param {SiteConfig} config the site's config file
96
+ * @returns {string[]}
97
+ */
98
+ export function checkContent(appDir, config) {
99
+ const before = SITE;
100
+ configureSite(browserConfig(config));
101
+ try {
102
+ return contentProblems(appDir, config.paths.local);
103
+ } finally {
104
+ configureSite({ ...before });
105
+ }
106
+ }
107
+
108
+ /**
109
+ * @param {string} appDir
110
+ * @param {Array<[string, string]>} paths
111
+ * @returns {string[]}
112
+ */
113
+ function contentProblems(appDir, paths) {
114
+ // Every logical content path has a folder: paths.local maps content/.
115
+ const local = (/** @type {string} */ logical) => /** @type {string} */ (localPath(paths, logical));
116
+ const contentDir = path.join(appDir, local("content/"));
117
+ /** @type {string[]} */
118
+ const problems = [];
119
+ /** @param {string} logical */
120
+ const read = (logical) => {
121
+ try {
122
+ const bytes = fs.readFileSync(path.join(appDir, local(logical)));
123
+ let text;
124
+ try {
125
+ // ignoreBOM keeps a byte-order mark in the text, so JSON.parse
126
+ // refuses it, as it always has.
127
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
128
+ } catch {
129
+ problems.push(`${local(logical)}: is not saved as UTF-8 text`);
130
+ return null;
131
+ }
132
+ return { value: JSON.parse(text) };
133
+ } catch (err) {
134
+ problems.push(`${local(logical)}: cannot be read (${/** @type {Error} */ (err).message})`);
135
+ return null;
136
+ }
137
+ };
138
+
139
+ const schemaFile = read("content/schema.json");
140
+ if (!schemaFile) return problems;
141
+ const schema = schemaFile.value;
142
+ // Everything below reads schema.documents[kind].fields; a schema without
143
+ // them is one problem, not a JavaScript error.
144
+ if (!isObject(schema) || !isObject(schema.documents)
145
+ || !Object.values(schema.documents).every((spec) => isObject(spec) && Array.isArray(spec.fields))) {
146
+ problems.push(`${local("content/schema.json")}: is not a usable schema (it must be an object whose `
147
+ + '"documents" holds each kind of page, each with its list of fields)');
148
+ return problems;
149
+ }
150
+
151
+ const pagesDir = path.join(contentDir, "pages");
152
+ const pageNames = new Set(
153
+ (fs.existsSync(pagesDir) ? fs.readdirSync(pagesDir) : [])
154
+ .filter((f) => f.endsWith(".json"))
155
+ .map((f) => f.slice(0, -".json".length)),
156
+ );
157
+ let customCount = 0;
158
+
159
+ for (const rel of documentPaths(contentDir)) {
160
+ const docType = docTypeForPath(rel);
161
+ if (docType === null) {
162
+ problems.push(`${local(rel)}: not a content file name (use lower-case letters, digits and -)`);
163
+ continue;
164
+ }
165
+ if (docType === "custom") {
166
+ customCount += 1;
167
+ const slug = rel.slice("content/custom/".length, -".json".length);
168
+ if (!isUsableSlug(slug, pageNames)) {
169
+ problems.push(`${local(rel)}: "${slug}" cannot be a page address: it is reserved or already in use`);
170
+ }
171
+ }
172
+ const file = read(rel);
173
+ if (!file) continue;
174
+ for (const p of validateDoc(schema, docType, file.value)) {
175
+ problems.push(`${local(rel)}: ${p.field || "(document)"}: ${p.message}`);
176
+ }
177
+ const spec = schema.documents[docType];
178
+ if (!spec) continue;
179
+ for (const [field, image] of imagesWithPaths(spec.fields, file.value, "", [])) {
180
+ // A malformed photo is already reported by validateDoc.
181
+ if (typeof image.base !== "string" || !Array.isArray(image.widths)) continue;
182
+ for (const name of imageFiles(image)) {
183
+ // So is one outside assets/, which no folder takes.
184
+ const file = localPath(paths, name);
185
+ if (file !== null && !fs.existsSync(path.join(appDir, file))) {
186
+ problems.push(`${local(rel)}: ${field}: the photo file ${file} is missing`);
187
+ }
188
+ }
189
+ }
190
+ }
191
+
192
+ if (customCount > MAX_CUSTOM_PAGES) {
193
+ problems.push(`${local("content/custom/").slice(0, -1)}: ${customCount} extra pages; ` +
194
+ `the most is ${MAX_CUSTOM_PAGES}`);
195
+ }
196
+ return problems;
197
+ }