@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
@@ -0,0 +1,232 @@
1
+ // The new photos of the open page: picked and shown, but not on the site
2
+ // yet. Their files live only in memory, so a draft stores the photo each
3
+ // field had before and names the fields to pick again. No DOM: object URLs
4
+ // are released through the `revoke` passed in.
5
+ import { getAt, isDirty, setAt } from "./model.js";
6
+ import { pathToField } from "./forms.js";
7
+
8
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
9
+
10
+ function walk(fields, obj, path, found) {
11
+ for (const field of fields) {
12
+ const value = Object.hasOwn(obj, field.key) ? obj[field.key] : undefined;
13
+ const here = [...path, field.key];
14
+ if (field.type === "image") {
15
+ if (isObject(value)) found.push({ name: pathToField(here), path: here, image: value });
16
+ } else if (field.type === "object" && isObject(value)) {
17
+ walk(field.fields, value, here, found);
18
+ } else if (field.type === "list" && Array.isArray(value)) {
19
+ value.forEach((item, i) => {
20
+ if (isObject(item)) walk(field.fields, item, [...here, i], found);
21
+ });
22
+ }
23
+ }
24
+ }
25
+
26
+ /** Every image field of doc that holds a photo, in field order:
27
+ * [{name: "photos[2].photo", path: ["photos", 2, "photo"], image}]. */
28
+ export function imageFields(fields, doc) {
29
+ const found = [];
30
+ if (isObject(doc)) walk(fields, doc, [], found);
31
+ return found;
32
+ }
33
+
34
+ /** names with the items of the list listName renumbered: item i becomes
35
+ * item mapIndex(i), or its names go when that is null. */
36
+ export function shiftNames(names, listName, mapIndex) {
37
+ const prefix = `${listName}[`;
38
+ const out = new Set();
39
+ for (const name of names) {
40
+ const m = name.startsWith(prefix) ? /^(\d+)\]/.exec(name.slice(prefix.length)) : null;
41
+ if (!m) {
42
+ out.add(name);
43
+ continue;
44
+ }
45
+ const to = mapIndex(Number(m[1]));
46
+ if (to !== null) out.add(`${prefix}${to}]${name.slice(prefix.length + m[0].length)}`);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /** The path a field name stands for ("photos[2].photo" -> ["photos", 2,
52
+ * "photo"]), or null when the name is not one pathToField writes. */
53
+ export function fieldPath(name) {
54
+ if (typeof name !== "string" || !/^[a-z][a-z0-9_]*(\[\d+\]|\.[a-z][a-z0-9_]*)*$/.test(name)) {
55
+ return null;
56
+ }
57
+ return [...name.matchAll(/([a-z][a-z0-9_]*)|\[(\d+)\]/g)]
58
+ .map((m) => (m[1] !== undefined ? m[1] : Number(m[2])));
59
+ }
60
+
61
+ /** The value at path, and whether its parent holds that key at all. */
62
+ function lookup(doc, path) {
63
+ const parent = getAt(doc, path.slice(0, -1));
64
+ const key = path[path.length - 1];
65
+ const ok = parent !== null && typeof parent === "object" && Object.hasOwn(parent, key);
66
+ return ok ? { value: parent[key] } : null;
67
+ }
68
+
69
+ /** doc with source's values in the named fields, or null when a name does
70
+ * not lead to a field in both (items moved or removed). For comparing only:
71
+ * list positions need not line up. */
72
+ export function withFieldsFrom(doc, names, source) {
73
+ let out = doc;
74
+ for (const name of names) {
75
+ const path = fieldPath(name);
76
+ const from = path && lookup(source, path);
77
+ if (!from || !lookup(out, path)) return null;
78
+ out = setAt(out, path, from.value);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** The names whose field holds the same value in draft and in live: the
84
+ * fields still waiting for a new photo. One whose photo has changed since
85
+ * (a publish landed) or that no longer exists is left out. */
86
+ export function stillWaiting(names, draft, live) {
87
+ return names.filter((name) => {
88
+ const path = fieldPath(name);
89
+ const a = path && lookup(draft, path);
90
+ const b = path && lookup(live, path);
91
+ return Boolean(a && b) && !isDirty(a.value, b.value);
92
+ });
93
+ }
94
+
95
+ /**
96
+ * The open page's new photos.
97
+ * revoke(url): releases an object URL. shown: a Map, kept for the whole
98
+ * session, of base -> preview URL for photos published in it (the site
99
+ * serves them only after its rebuild).
100
+ */
101
+ export function createPagePhotos({ revoke = () => {}, shown = new Map() } = {}) {
102
+ // base -> {base, files, previewUrl, previous, replaces}. `replaces` is a
103
+ // photo that was being sent when this one took its place: if that publish
104
+ // succeeds, the photo it sent becomes what this field had before.
105
+ const pending = new Map();
106
+ const inFlight = new Set(); // records whose files are being sent
107
+ let repick = new Set();
108
+ // True once any list on the page gained, lost or reordered an item.
109
+ let reshaped = false;
110
+
111
+ return {
112
+ /** A photo prepared by prepareImage now fills the field `name`, which
113
+ * held `old`. */
114
+ chosen(name, prepared, old) {
115
+ const earlier = isObject(old) ? pending.get(old.base) : undefined;
116
+ const sending = earlier !== undefined && inFlight.has(earlier);
117
+ if (earlier) {
118
+ pending.delete(earlier.base);
119
+ // A photo being sent keeps its preview until its publish ends.
120
+ if (!sending) revoke(earlier.previewUrl);
121
+ }
122
+ const { base } = prepared.field;
123
+ pending.set(base, {
124
+ base, files: prepared.files, previewUrl: prepared.previewUrl,
125
+ // What the field held before any new photo: what a draft keeps.
126
+ previous: earlier ? earlier.previous : (old ?? null),
127
+ replaces: sending ? earlier : (earlier?.replaces ?? null),
128
+ });
129
+ repick.delete(name);
130
+ },
131
+
132
+ /** A prepared photo that was never used. */
133
+ drop(prepared) {
134
+ revoke(prepared.previewUrl);
135
+ },
136
+
137
+ /** The in-memory address to show for image, or null. */
138
+ previewFor(image) {
139
+ if (!isObject(image)) return null;
140
+ return pending.get(image.base)?.previewUrl ?? shown.get(image.base) ?? null;
141
+ },
142
+
143
+ needsRepick: (name) => repick.has(name),
144
+ /** The fields to pick again, in no particular order. */
145
+ repickNames: () => [...repick],
146
+ restore(names) {
147
+ repick = new Set(names);
148
+ },
149
+ /** The owner keeps the photo the field holds: stop asking for a new one. */
150
+ dropRepick(name) {
151
+ repick.delete(name);
152
+ },
153
+ listChanged(listName, mapIndex) {
154
+ repick = shiftNames(repick, listName, mapIndex);
155
+ reshaped = true;
156
+ },
157
+ /** Whether any list was changed since the page was opened: then its
158
+ * positions no longer line up with another version of the page. */
159
+ listsChanged: () => reshaped,
160
+
161
+ /** {doc, repick}: doc as a draft can keep it, each new photo replaced by
162
+ * what its field held before, and the fields to pick again. */
163
+ forDraft(fields, doc) {
164
+ const names = new Set(repick);
165
+ let out = doc;
166
+ for (const { name, path, image } of imageFields(fields, doc)) {
167
+ const record = pending.get(image.base);
168
+ if (record) {
169
+ out = setAt(out, path, record.previous);
170
+ names.add(name);
171
+ }
172
+ }
173
+ return { doc: out, repick: [...names] };
174
+ },
175
+
176
+ /** The new photos doc holds, once each, in page order. */
177
+ toSend(fields, doc) {
178
+ const out = [];
179
+ for (const { image } of imageFields(fields, doc)) {
180
+ const record = pending.get(image.base);
181
+ if (record && !out.includes(record)) out.push(record);
182
+ }
183
+ return out;
184
+ },
185
+
186
+ /** The field name in doc of the photo with this base, or null. */
187
+ fieldOf(fields, doc, base) {
188
+ return imageFields(fields, doc).find(({ image }) => image.base === base)?.name ?? null;
189
+ },
190
+
191
+ /** These photos' files are being sent. */
192
+ sending(records) {
193
+ for (const record of records) inFlight.add(record);
194
+ },
195
+
196
+ /** These photos are on the site now, as doc (the published document)
197
+ * holds them: no longer new, still previewed. A photo that replaced one
198
+ * of them meanwhile now has it as what its field had before. */
199
+ sent(records, fields, doc) {
200
+ const published = new Map(imageFields(fields, doc).map(({ image }) => [image.base, image]));
201
+ for (const record of records) {
202
+ inFlight.delete(record);
203
+ if (pending.get(record.base) === record) pending.delete(record.base);
204
+ shown.set(record.base, record.previewUrl);
205
+ }
206
+ for (const record of pending.values()) {
207
+ if (record.replaces && records.includes(record.replaces)) {
208
+ record.previous = published.get(record.replaces.base) ?? record.previous;
209
+ record.replaces = null;
210
+ }
211
+ }
212
+ },
213
+
214
+ /** Sending these photos failed. One replaced meanwhile is let go. */
215
+ notSent(records) {
216
+ for (const record of records) {
217
+ inFlight.delete(record);
218
+ if (pending.get(record.base) !== record) revoke(record.previewUrl);
219
+ }
220
+ for (const record of pending.values()) {
221
+ if (record.replaces && records.includes(record.replaces)) record.replaces = null;
222
+ }
223
+ },
224
+
225
+ /** Forget every new photo and every field to pick again. */
226
+ clear() {
227
+ for (const record of pending.values()) revoke(record.previewUrl);
228
+ pending.clear();
229
+ repick = new Set();
230
+ },
231
+ };
232
+ }
@@ -0,0 +1,45 @@
1
+ // Tracks a published commit until the site serves it.
2
+ import { SHA_RE } from "./shared/rules.js";
3
+ import { SITE } from "./shared/site.js";
4
+
5
+ export async function trackPublish({
6
+ commit, getDeployed, contains, sleep, now, onState,
7
+ // The site's longest wait for a build (its config's liveWaitMs).
8
+ intervalMs = 5000, timeoutMs = SITE.liveWaitMs,
9
+ }) {
10
+ const start = now();
11
+ const asked = new Set();
12
+ onState("publishing");
13
+
14
+ async function isLive() {
15
+ let deployed;
16
+ try {
17
+ deployed = await getDeployed();
18
+ } catch {
19
+ return false;
20
+ }
21
+ if (deployed === commit) return true;
22
+ if (typeof deployed !== "string" || !SHA_RE.test(deployed) || asked.has(deployed)) {
23
+ return false;
24
+ }
25
+ try {
26
+ if (await contains(commit, deployed)) return true;
27
+ asked.add(deployed);
28
+ } catch {
29
+ // Not remembered, so it is asked again next round.
30
+ }
31
+ return false;
32
+ }
33
+
34
+ for (;;) {
35
+ if (await isLive()) {
36
+ onState("live");
37
+ return "live";
38
+ }
39
+ if (now() - start >= timeoutMs) {
40
+ onState("timeout");
41
+ return "timeout";
42
+ }
43
+ await sleep(intervalMs);
44
+ }
45
+ }
@@ -0,0 +1,118 @@
1
+ // Slug, path and link rules shared by the editor page and its API.
2
+ // No Node or browser globals: the browser, Workers and Node all load it.
3
+ // A site whose own build checks links too must keep it in step with badLinks.
4
+ import { SITE } from "./site.js";
5
+
6
+ export const ALLOWED_URL_PREFIXES = ["/", "https://", "mailto:", "tel:"];
7
+
8
+ export const DOC_PATH_RE =
9
+ /^content\/(site|pages\/[a-z0-9-]+|custom\/[a-z0-9-]+)\.json$/;
10
+ export const UPLOAD_NAME_RE = /^[a-z0-9-]+-(700|1100|1800)\.(webp|jpg)$/;
11
+ export const SHA_RE = /^[0-9a-f]{40}$/;
12
+
13
+ // The characters Python's \s matches in a str pattern, so the two
14
+ // languages agree on where an address ends.
15
+ const SPACE = "\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029" +
16
+ "\\u202f\\u205f\\u3000";
17
+ // The characters String.prototype.trim removes.
18
+ const BLANK_LABEL = /^[\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/;
19
+ // A typed address longer than this is reported without reading more.
20
+ const MAX_ADDRESS = 200;
21
+
22
+ // A URL may not contain "*", parens or whitespace.
23
+ const LINK = new RegExp(`\\[([^\\[\\]\\n]+)\\]\\(([^()${SPACE}*]+)\\)`, "uy");
24
+ const ATTEMPT = /\[[^\[\]\n]+\]\(/gu;
25
+ const TYPED_ADDRESS = new RegExp(`[^${SPACE}]{0,${MAX_ADDRESS}}`, "uy");
26
+
27
+ function allowed(url) {
28
+ // "https://" alone, or with only "/" after it, has no host; "mailto:" and
29
+ // "tel:" alone have no address.
30
+ if (url.startsWith("https://")) return /[^/]/.test(url.slice(8));
31
+ if (url === "mailto:" || url === "tel:") return false;
32
+ // "//host" and "/\host" are protocol-relative, not site paths.
33
+ return ALLOWED_URL_PREFIXES.some((p) => url.startsWith(p)) &&
34
+ !url.startsWith("//") && !url.startsWith("/\\");
35
+ }
36
+
37
+ /** Addresses of link attempts that would not become a link: a label with
38
+ * nothing visible in it, an address that may not be used, or an attempt that
39
+ * is not a complete link. Reads at most 200 characters past each attempt. */
40
+ export function badLinks(text) {
41
+ const bad = [];
42
+ ATTEMPT.lastIndex = 0;
43
+ let attempt;
44
+ while ((attempt = ATTEMPT.exec(text)) !== null) {
45
+ LINK.lastIndex = attempt.index;
46
+ const m = LINK.exec(text);
47
+ if (m) {
48
+ if (!allowed(m[2]) || BLANK_LABEL.test(m[1])) bad.push(m[2]);
49
+ continue;
50
+ }
51
+ TYPED_ADDRESS.lastIndex = ATTEMPT.lastIndex;
52
+ let addr = TYPED_ADDRESS.exec(text)[0];
53
+ if (addr.endsWith(")")) addr = addr.slice(0, -1);
54
+ bad.push(addr);
55
+ }
56
+ return bad;
57
+ }
58
+
59
+ // ---- Simple pages' addresses: content/custom/<slug>.json is served at
60
+ // /<slug>, or /<slug>/ with the config's trailingSlash. The cases are in
61
+ // tests/fixtures/slugs.json, for a site that repeats these rules elsewhere.
62
+
63
+ /** A whole-string match: "$" without the m flag does not match before a
64
+ * final line break, unlike Python's. */
65
+ export const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
66
+ export const MAX_SLUG = 60;
67
+ /** Addresses every site or its hosting already answers. */
68
+ const BASE_RESERVED = ["admin", "api", "assets", "index", "404"];
69
+ /** Addresses a simple page may not take: the base five and the site's own
70
+ * (its config's `reserved`). */
71
+ export const reservedNames = () => Object.freeze([...BASE_RESERVED, ...SITE.reserved]);
72
+ /** The editor's sign-in covers every path that starts with this, so a page
73
+ * there would be hidden from visitors. */
74
+ export const SIGN_IN_PREFIX = "admin";
75
+ /** The most simple pages the site may hold. */
76
+ export const MAX_CUSTOM_PAGES = 30;
77
+
78
+ /** True when slug can be a new simple page's address. taken: a Set of the
79
+ * addresses other pages already have. */
80
+ export function isUsableSlug(slug, taken) {
81
+ return typeof slug === "string" && slug.length <= MAX_SLUG && SLUG_RE.test(slug) &&
82
+ !reservedNames().includes(slug) && !slug.startsWith(SIGN_IN_PREFIX) && !taken.has(slug);
83
+ }
84
+
85
+ /** An address made from a title: plain a-z0-9 words joined by "-", accents
86
+ * and apostrophes dropped ("Matt's" is "matts"). Empty when nothing in the
87
+ * title can be kept. */
88
+ export function slugify(title) {
89
+ return String(title)
90
+ .normalize("NFKD")
91
+ .toLowerCase()
92
+ .replace(/[\u0300-\u036f]/g, "")
93
+ .replace(/['\u2019\u02bc]/g, "")
94
+ .replace(/[^a-z0-9]+/g, "-")
95
+ .replace(/^-+|-+$/g, "");
96
+ }
97
+
98
+ /** slug cut to at most n characters, without a hyphen at its end. */
99
+ const cut = (slug, n) => slug.slice(0, n).replace(/-+$/, "");
100
+
101
+ /** A usable address for a page with this title: its slug, or that slug with
102
+ * "-2", "-3", ... until it is free; "page" when the title gives nothing,
103
+ * and "page-" in front of one that would start with "admin".
104
+ * Never reserved, taken, empty, under the sign-in or longer than MAX_SLUG.
105
+ * The loop ends: the base is never under the sign-in, so a numbered form of
106
+ * it is never reserved or under the sign-in, and only `taken` can refuse
107
+ * one, which holds finitely many. */
108
+ export function uniqueSlug(title, taken) {
109
+ let base = slugify(title) || "page";
110
+ if (base.startsWith(SIGN_IN_PREFIX)) base = `page-${base}`;
111
+ base = cut(base, MAX_SLUG);
112
+ if (isUsableSlug(base, taken)) return base;
113
+ for (let n = 2; ; n++) {
114
+ const suffix = `-${n}`;
115
+ const slug = cut(base, MAX_SLUG - suffix.length) + suffix;
116
+ if (isUsableSlug(slug, taken)) return slug;
117
+ }
118
+ }
@@ -0,0 +1,128 @@
1
+ // The site config: the few values that differ between the sites using this
2
+ // editor. It is held here, checked here and handed out from here; nothing
3
+ // else decides what a site may set. Modules read SITE when they are used,
4
+ // never when they are loaded, because configureSite runs after the imports.
5
+ // Nothing here needs a DOM or Node: the server loads this module too.
6
+ import { DEFAULT_DEVELOPER, TEXT, configureText } from "../copy.js";
7
+
8
+ export const SITE_DEFAULTS = Object.freeze({
9
+ // The browser tab's title and the name at the top of the page.
10
+ title: "Website editor",
11
+ // How the owner signs in: "code" (an emailed code) or "access" (a sign-in
12
+ // in front of the site, such as Cloudflare Access).
13
+ signIn: "code",
14
+ // True when the site serves its pages at "/<slug>/" rather than "/<slug>".
15
+ trailingSlash: false,
16
+ // How the editor finds a published photo: "key" (by its stored name) or
17
+ // "asset-map" (through the build's map of hashed names).
18
+ photos: "key",
19
+ // Addresses the site answers itself, beyond the five every site reserves.
20
+ reserved: Object.freeze([]),
21
+ // A host serving the site without its sign-in in front, or null. Set
22
+ // only with signIn "access", and together with editorAddress.
23
+ bareHost: null,
24
+ // The editor's own address, to send people to from bareHost, or null.
25
+ editorAddress: null,
26
+ // How long the editor waits for a publish to show on the site.
27
+ liveWaitMs: 360000,
28
+ // Who the owner is told to tell when something needs a person, as the
29
+ // end of "Please let ... know.": a name, or the default.
30
+ developer: DEFAULT_DEVELOPER,
31
+ // The editor's own sentences reworded for this site, by their TEXT key.
32
+ text: Object.freeze({}),
33
+ });
34
+
35
+ /** The keys the browser's config holds; a site's config file holds more. */
36
+ export const BROWSER_KEYS = Object.freeze(Object.keys(SITE_DEFAULTS));
37
+
38
+ export let SITE = SITE_DEFAULTS;
39
+
40
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
41
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
42
+ const oneOf = (...allowed) => (v) => allowed.includes(v);
43
+ // The form rules.js's SLUG_RE gives an address (tests/site.test.js holds the
44
+ // two together); written out here because rules.js imports this module.
45
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
46
+ const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/;
47
+
48
+ function isHttpsAddress(v) {
49
+ if (typeof v !== "string") return false;
50
+ try {
51
+ const url = new URL(v);
52
+ return url.protocol === "https:" && url.href === v;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ const CHECKS = {
59
+ title: isText,
60
+ signIn: oneOf("code", "access"),
61
+ trailingSlash: (v) => typeof v === "boolean",
62
+ photos: oneOf("key", "asset-map"),
63
+ reserved: (v) => Array.isArray(v) && v.every((name) => typeof name === "string" && SLUG.test(name)),
64
+ bareHost: (v) => v === null || (typeof v === "string" && HOST.test(v)),
65
+ editorAddress: (v) => v === null || isHttpsAddress(v),
66
+ liveWaitMs: (v) => Number.isSafeInteger(v) && v > 0,
67
+ developer: (v) => isText(v) && v === v.trim() && v.length <= 60 && !/[\r\n]/.test(v),
68
+ text: isObject,
69
+ // The package's version. Not a key a site sets: site-editor copy writes it
70
+ // into site-config.json, so it has no default and browserConfig leaves it.
71
+ version: isText,
72
+ };
73
+
74
+ /** The names of the keys in values that are unknown or malformed, in the
75
+ * order given: "text.<key>" for a sentence that is not the editor's or is
76
+ * not words. Judges the browser keys only; give it browserConfig(config). */
77
+ export function siteProblems(values) {
78
+ if (!isObject(values)) return ["(not an object)"];
79
+ const problems = [];
80
+ for (const [key, value] of Object.entries(values)) {
81
+ if (!Object.hasOwn(CHECKS, key) || !CHECKS[key](value)) {
82
+ problems.push(key);
83
+ } else if (key === "text") {
84
+ for (const [name, words] of Object.entries(value)) {
85
+ if (!Object.hasOwn(TEXT, name) || !isText(words)) problems.push(`text.${name}`);
86
+ }
87
+ }
88
+ }
89
+ return [...problems, ...pairProblems(values, problems)];
90
+ }
91
+
92
+ /** bareHost and editorAddress go together: the editor sends people from the
93
+ * one to the other. A site with the editor's own sign-in has no bare host,
94
+ * so there both are null. Names the key that is missing, or, with signIn
95
+ * "code", each that is set. Judged only when the three keys are well
96
+ * formed; a malformed one is named already. */
97
+ function pairProblems(values, problems) {
98
+ if (["signIn", "bareHost", "editorAddress"].some((key) => problems.includes(key))) return [];
99
+ const v = { ...SITE_DEFAULTS, ...values };
100
+ const set = ["bareHost", "editorAddress"].filter((key) => v[key] !== null);
101
+ if (v.signIn === "code") return set;
102
+ if (set.length === 1) return [set[0] === "bareHost" ? "editorAddress" : "bareHost"];
103
+ return [];
104
+ }
105
+
106
+ /** A new object holding only the browser keys present in config. */
107
+ export function browserConfig(config) {
108
+ const out = {};
109
+ if (!isObject(config)) return out;
110
+ for (const key of BROWSER_KEYS) {
111
+ if (Object.hasOwn(config, key)) out[key] = config[key];
112
+ }
113
+ return out;
114
+ }
115
+
116
+ /** Make values the site's config, starting again from the defaults. Throws,
117
+ * changing nothing, when siteProblems finds any. */
118
+ export function configureSite(values) {
119
+ const problems = siteProblems(values);
120
+ if (problems.length > 0) throw new Error(`site config: ${problems.join(", ")}`);
121
+ const next = { ...SITE_DEFAULTS, ...values };
122
+ SITE = Object.freeze({
123
+ ...next,
124
+ reserved: Object.freeze([...next.reserved]),
125
+ text: Object.freeze({ ...next.text }),
126
+ });
127
+ configureText(SITE);
128
+ }