@taprootio/site-authoring 0.62.0 → 0.64.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.
Files changed (69) hide show
  1. package/README.md +63 -23
  2. package/package.json +2 -2
  3. package/src/api.js +149 -21
  4. package/src/appearance-contract.js +9 -0
  5. package/src/article-end-settings.js +295 -0
  6. package/src/changelog.json +39 -0
  7. package/src/chrome-input.js +1 -1
  8. package/src/cli.js +110 -26
  9. package/src/constants.js +7 -0
  10. package/src/content/components.js +130 -14
  11. package/src/content/cta-decoration-paint.js +321 -0
  12. package/src/content/form-placement-presentation.js +91 -0
  13. package/src/content/form-placement-presentation.json +6 -0
  14. package/src/content/free-form-section-registry.json +19 -1
  15. package/src/content/free-form-sections.js +64 -55
  16. package/src/content/markdown.js +13 -0
  17. package/src/content/tiptap-prosemirror.ts +72 -59
  18. package/src/content/validate-document.js +2 -0
  19. package/src/cta-artwork-warnings.js +164 -0
  20. package/src/errors.js +6 -0
  21. package/src/field-schema.json +6 -2
  22. package/src/field-validation.js +14 -5
  23. package/src/footer-workspace.js +7 -3
  24. package/src/form-references.js +71 -9
  25. package/src/forms-contract.js +3 -5
  26. package/src/heading-outline.js +7 -0
  27. package/src/output.js +2 -0
  28. package/src/page-article-end.js +66 -0
  29. package/src/page-block-catalog.js +54 -0
  30. package/src/page-form-presentation.js +104 -0
  31. package/src/page-structure-checks.js +7 -1
  32. package/src/placed-image-ids.js +15 -18
  33. package/src/presentation-reference.js +30 -52
  34. package/src/reference-help.js +97 -27
  35. package/src/reusable-blocks.js +429 -0
  36. package/src/reusable-placements.js +271 -0
  37. package/src/setting-reference.js +25 -1
  38. package/src/settings-catalog.js +1 -0
  39. package/src/site-check-findings.js +30 -2
  40. package/src/site-check-rules.json +1 -0
  41. package/src/site-checks.js +26 -2
  42. package/src/site-health-findings.js +25 -3
  43. package/src/site-health-image-checks.js +1 -1
  44. package/src/staging-check.js +108 -21
  45. package/src/staging-served.js +5 -49
  46. package/src/status-warning-paints.js +17 -0
  47. package/src/template-token-reach.json +14 -2
  48. package/src/theme-resolve.js +27 -0
  49. package/src/transport.js +41 -5
  50. package/src/typed-page-reference.js +55 -5
  51. package/src/typed-pages.js +27 -4
  52. package/src/verbs/approve.js +2 -1
  53. package/src/verbs/deploy.js +93 -15
  54. package/src/verbs/footer-push.js +4 -2
  55. package/src/verbs/forms-push.js +9 -0
  56. package/src/verbs/health.js +11 -6
  57. package/src/verbs/index.js +3 -0
  58. package/src/verbs/pages-blocks-pull.js +22 -0
  59. package/src/verbs/pages-push.js +89 -34
  60. package/src/verbs/plan.js +34 -5
  61. package/src/verbs/pull.js +213 -124
  62. package/src/verbs/status.js +20 -2
  63. package/src/verbs/theme-push.js +164 -14
  64. package/src/verbs/theme-resolve.js +114 -40
  65. package/src/verbs/validate.js +49 -18
  66. package/src/workspace-check.js +42 -5
  67. package/src/workspace-context-usage.js +54 -1
  68. package/src/workspace.js +37 -7
  69. package/test/fixtures/default-site-theme.json +1 -1
@@ -0,0 +1,271 @@
1
+ import { getPage, PAGE_STATUS_APPROVED, PAGE_STATUS_PUBLISHED } from "./api.js";
2
+ import { ApiError } from "./transport.js";
3
+ import { placedFormIds } from "./form-references.js";
4
+ import { pageLinkInventory } from "./chrome-input.js";
5
+ import { LIMITS } from "./constants.js";
6
+ import { reusablePlacementKey } from "./content/components.js";
7
+ import { readFormPlacementPresentation } from "./content/form-placement-presentation.js";
8
+ import { SiteAuthoringError } from "./errors.js";
9
+ import { getSitePageBlockCatalog } from "./page-block-catalog.js";
10
+ import { appendAll, CHECK_AREA, problemsOf } from "./problems.js";
11
+ import { reusableCtaForWorkspaceChecks } from "./reusable-blocks.js";
12
+ import { boundedByBytes } from "./session.js";
13
+ import {
14
+ contentDocuments, documentTemplate, parseComponentData, TEMPLATE_ARTICLE, TEMPLATE_FREE_FORM, TEMPLATE_PLACE_REVIEW,
15
+ TEMPLATE_ALBUM, TEMPLATE_GENERATED, TEMPLATE_RECIPE, workspaceDocumentFromPage,
16
+ } from "./typed-pages.js";
17
+
18
+ export const REUSABLE_CATALOG_UNAVAILABLE = "pages.reusable_block_catalog_unavailable";
19
+ const UNKNOWN_KEY = "pages.reusable_block_unknown";
20
+ const WRONG_TYPE = "pages.reusable_block_type_mismatch";
21
+
22
+ function placementNodes(document) {
23
+ const template = documentTemplate(document);
24
+ const placements = [];
25
+ for (const { doc, path } of contentDocuments(document)) {
26
+ const supported = template === TEMPLATE_FREE_FORM || (path === "data.body" && [TEMPLATE_ARTICLE, TEMPLATE_PLACE_REVIEW].includes(template))
27
+ || (path === "data.introductionBody" && [TEMPLATE_ALBUM, TEMPLATE_GENERATED, TEMPLATE_RECIPE].includes(template));
28
+ const pending = [{ node: doc, path }];
29
+ while (pending.length > 0) {
30
+ const { node, path } = pending.pop();
31
+ if (node?.type === "componentBlock" && node.attrs) {
32
+ const attrs = node.attrs;
33
+ const { componentType, componentData } = attrs;
34
+ const data = typeof componentData === "string" ? parseComponentData(componentData) : componentData;
35
+ const key = reusablePlacementKey(componentType, data);
36
+ if (key !== undefined) placements.push({ key, type: componentType, attrs, path, supported });
37
+ }
38
+ const children = Array.isArray(node?.content) ? node.content : [];
39
+ for (let index = children.length - 1; index >= 0; index -= 1) {
40
+ pending.push({ node: children[index], path: `${path}/content/${index}` });
41
+ }
42
+ }
43
+ }
44
+ return placements;
45
+ }
46
+
47
+ export function requireSupportedReusablePlacements(document, file) {
48
+ const refused = placementNodes(document).find(({ supported }) => !supported);
49
+ if (refused !== undefined) throw new SiteAuthoringError("pages.reusable_block_location",
50
+ `'${file}' cannot place reusable ${refused.type} '${refused.key}' at ${refused.path}. Choose a page body or introduction that accepts reusable blocks.`,
51
+ { field: `${file}:${refused.path}` });
52
+ }
53
+
54
+ /** Canonicalize the reference itself while leaving the inline source transport untouched. */
55
+ export function normalizeReusablePlacements(document) {
56
+ if (document === undefined) return document;
57
+ const placements = placementNodes(document);
58
+ if (!placements.some(({ attrs, key }) => attrs.componentData !== JSON.stringify({ reusableKey: key }))) return document;
59
+ const copy = structuredClone(document);
60
+ for (const { attrs, key } of placementNodes(copy)) attrs.componentData = JSON.stringify({ reusableKey: key });
61
+ return copy;
62
+ }
63
+
64
+ function siteError(page, placement, code, message) {
65
+ return problemsOf(new SiteAuthoringError(code, message, {
66
+ field: `${page.file}:${placement.path}/attrs/componentData/reusableKey`,
67
+ }), { area: CHECK_AREA.pages, file: page.file });
68
+ }
69
+
70
+ function selectedReleaseReport() {
71
+ return {
72
+ status: "unavailable",
73
+ reason: "Draft definitions do not identify the settings selected for a release.",
74
+ };
75
+ }
76
+
77
+ function guidance({ file, key, state }) {
78
+ if (state === "workspace") {
79
+ return `'${file}' uses workspace reusable block '${key}'. Save any definition edits before pushing the page. Include publishing preferences if the key exists only in draft.`;
80
+ }
81
+ if (state === "draft_only") {
82
+ return "'" + file + "' uses draft-only reusable block '" + key + "'. Include publishing preferences when staging.";
83
+ }
84
+ if (state === "released_key") return;
85
+ if (state === "catalog_unavailable") {
86
+ return `'${file}' uses reusable block '${key}'. Run 'taproot-site pages blocks pull' to check the site's draft definitions.`;
87
+ }
88
+ return `'${file}' uses reusable block '${key}'. If its definition is only in draft, include publishing preferences in the release.`;
89
+ }
90
+
91
+ /** Build temporary page bodies for workspace checks. The bodies sent and hashed still hold only the keys. */
92
+ export function assessReusablePlacements(planned, {
93
+ catalog, workspaceDefinitions, manifest, online = false, onProgress = () => {},
94
+ } = {}) {
95
+ const pagePlacements = planned.map((page) => [page, placementNodes(page.document)]);
96
+ if (!pagePlacements.some(([, placements]) => placements.length > 0)) {
97
+ return { problems: [], checkedPages: planned, unavailableFiles: [], report: undefined };
98
+ }
99
+ const draft = catalog?.definitions;
100
+ const source = workspaceDefinitions === undefined ? draft : workspaceDefinitions;
101
+ const byKey = Array.isArray(source) ? new Map(source.map((block) => [block.key, block])) : undefined;
102
+ const formRows = workspaceDefinitions === undefined ? catalog?.forms ?? [] : manifest?.reusableBlocks?.forms ?? [];
103
+ const formsById = new Map(formRows.map((form) => [form.formId, form]));
104
+ const formsByKey = new Map(formRows.map((form) => [form.key, form]));
105
+ const plannedPaths = new Map(planned.filter((page) => page.pageId !== undefined)
106
+ .map(({ pageId, pagePath }) => [pageId, pagePath]));
107
+ const knownPaths = pageLinkInventory((manifest?.pages ?? []).map((page) =>
108
+ plannedPaths.has(page.pageId) ? { ...page, path: plannedPaths.get(page.pageId) } : page), false).knownPaths;
109
+ const problems = [];
110
+ const notices = new Map();
111
+ const unavailableFiles = [];
112
+ let total = 0;
113
+ let ctaPlacements = 0;
114
+ let linksPartial = workspaceDefinitions === undefined;
115
+ const checkedPages = pagePlacements.map(([page, placements]) => {
116
+ const replacements = new Map();
117
+ const reusableCtaKeys = new Map();
118
+ const reusableCompactForms = new Map();
119
+ const seen = new Set();
120
+ for (const placement of placements) {
121
+ total += 1;
122
+ const { type, key, path } = placement;
123
+ if (type === "cta") ctaPlacements += 1;
124
+ const label = type === "cta" ? "CTA" : "Form";
125
+ const subject = `'${page.file}' places reusable ${label} '${key}'`;
126
+ if (byKey === undefined) {
127
+ const notice = { file: page.file, key, type, state: "catalog_unavailable" };
128
+ notices.set(`${page.file}:${key}:${type}`, notice);
129
+ if (online && !seen.has(`${type}:${key}`)) {
130
+ appendAll(problems, siteError(page, placement, REUSABLE_CATALOG_UNAVAILABLE,
131
+ `${subject}, but Taproot did not supply a draft catalog. Use a Taproot that serves 'pages blocks pull'.`));
132
+ }
133
+ seen.add(`${type}:${key}`);
134
+ continue;
135
+ }
136
+ const definition = byKey.get(key);
137
+ if (definition?.[type] === undefined) {
138
+ const code = definition === undefined ? UNKNOWN_KEY : WRONG_TYPE;
139
+ if (!seen.has(`${type}:${key}`)) {
140
+ appendAll(problems, siteError(page, placement, code, definition === undefined
141
+ ? `${subject}, which is missing from the draft definitions. Create it in Footer settings or save it with 'taproot-site theme push', then retry.`
142
+ : `${subject}, but the draft definition is a ${type === "cta" ? "Form" : "CTA"}. Choose a key for a ${label} in Footer settings.`));
143
+ }
144
+ seen.add(`${type}:${key}`);
145
+ continue;
146
+ }
147
+ const state = workspaceDefinitions !== undefined ? "workspace" : definition.draftOnly === true
148
+ ? "draft_only" : definition.draftOnly === false ? "released_key" : "draft";
149
+ notices.set(`${page.file}:${key}:${type}`, { file: page.file, key, type, state });
150
+ if (type === "cta") {
151
+ if (definition.cta.pageResourceId !== undefined && !knownPaths.has(definition.cta.pageResourceId)) linksPartial = true;
152
+ const cta = workspaceDefinitions === undefined
153
+ ? definition.cta
154
+ : reusableCtaForWorkspaceChecks(definition.cta, knownPaths);
155
+ replacements.set(path, cta);
156
+ reusableCtaKeys.set(path, key);
157
+ } else {
158
+ const { formId, formKey, layout } = definition.form;
159
+ const row = formId === undefined ? formsByKey.get(formKey) : formsById.get(formId);
160
+ if (!online && page.pageId === undefined && (catalog?.forms !== undefined || manifest?.reusableBlocks?.forms !== undefined)
161
+ && (row === undefined || row.archived)) {
162
+ appendAll(problems, unavailableForm(page, placement, row));
163
+ }
164
+ replacements.set(path, {
165
+ ...(formId === undefined ? {} : { formId }),
166
+ ...(layout === undefined ? {} : { layout }),
167
+ ...readFormPlacementPresentation(definition.form),
168
+ });
169
+ if (layout === "compact") reusableCompactForms.set(key, { key, formKey: formKey ?? row?.key, row });
170
+ }
171
+ }
172
+ if (byKey === undefined && placements.some(({ type }) => type === "cta")) unavailableFiles.push(page.file);
173
+ if (replacements.size === 0) return page;
174
+ const document = structuredClone(page.document);
175
+ for (const { attrs, path } of placementNodes(document)) {
176
+ if (replacements.has(path)) attrs.componentData = JSON.stringify(replacements.get(path));
177
+ }
178
+ return { ...page, document, reusableCtaKeys, reusableCompactForms: [...reusableCompactForms.values()] };
179
+ });
180
+ const items = [...notices.values()];
181
+ const messages = items.map(guidance).filter(Boolean);
182
+ for (const message of messages.slice(0, 20)) onProgress(message);
183
+ if (messages.length > 20) onProgress(`Additional reusable block placements: ${messages.length - 20}.`);
184
+ const report = {
185
+ evidence: workspaceDefinitions !== undefined ? "workspace" : byKey === undefined ? "unavailable" : "draft_catalog",
186
+ total,
187
+ // The Content projection deliberately does not supply CTA button targets.
188
+ ...(ctaPlacements === 0 ? {} : { links: linksPartial ? "partial" : "workspace" }),
189
+ selectedRelease: selectedReleaseReport(),
190
+ ...boundedByBytes(items, 4 * 1024),
191
+ };
192
+ return { problems, checkedPages, unavailableFiles, report };
193
+ }
194
+
195
+ function unavailableForm(page, placement, row) {
196
+ return siteError(page, placement, row === undefined ? "pages.form_unknown" : "pages.form_archived",
197
+ `'${page.file}' places reusable Form '${placement.key}', whose form is ${row === undefined ? "missing" : "archived"}. Restore the form or choose an active form in Footer settings.`);
198
+ }
199
+
200
+ function placementIdentity({ key, type, path }) {
201
+ return JSON.stringify([key, type, path]);
202
+ }
203
+
204
+ function storedFormIds(document, definitions) {
205
+ const ids = placedFormIds(document);
206
+ for (const { type, key } of placementNodes(document)) {
207
+ const id = type === "form" ? definitions.get(key)?.form?.formId : undefined;
208
+ if (id !== undefined) ids.add(id);
209
+ }
210
+ return ids;
211
+ }
212
+
213
+ export async function checkLiveReusablePlacements(client, siteId, planned, onProgress) {
214
+ const sending = planned.filter((page) => !page.unchanged && placementNodes(page.document).length > 0);
215
+ if (sending.length === 0) return { problems: [], report: undefined };
216
+ const catalog = await getSitePageBlockCatalog(client, siteId);
217
+ const checked = assessReusablePlacements(sending, { catalog, online: true, onProgress });
218
+ if (catalog?.definitions === undefined) return checked;
219
+ const definitions = new Map(catalog.definitions.map((row) => [row.key, row]));
220
+ const forms = new Map((catalog.forms ?? []).map((row) => [row.formId, row]));
221
+ for (const page of sending) {
222
+ const placements = placementNodes(page.document);
223
+ const unavailable = placements.filter(({ type, key }) => {
224
+ const form = definitions.get(key)?.form;
225
+ return type === "form" && form !== undefined && forms.get(form.formId)?.archived !== false;
226
+ });
227
+ if (catalog.placementWritesEnabled === true && unavailable.length === 0) continue;
228
+ const read = async (status) => {
229
+ const stored = workspaceDocumentFromPage(await getPage(client, page.pageId, status), page.templateType);
230
+ if (stored === undefined) throw new SiteAuthoringError("api.page_contract",
231
+ `Taproot did not return a readable stored body for '${page.file}'.`, { field: page.file });
232
+ return stored;
233
+ };
234
+ const current = page.pageId === undefined ? undefined : await read(page.storedStatus);
235
+ if (catalog.placementWritesEnabled !== true) {
236
+ const existing = current === undefined ? [] : placementNodes(current);
237
+ if (placements.length !== existing.length || placements.some((item, index) =>
238
+ placementIdentity(item) !== placementIdentity(existing[index]))) {
239
+ appendAll(checked.problems, siteError(page, placements[0], "pages.reusable_block_writes_unavailable",
240
+ `'${page.file}' changes reusable placements. Retry when the site's publishing update finishes.`));
241
+ }
242
+ }
243
+ const held = current === undefined || unavailable.length === 0 ? new Set() : storedFormIds(current, definitions);
244
+ const missing = () => unavailable.filter(({ key }) => !held.has(definitions.get(key).form.formId));
245
+ // Like the page guard, retain forms already held in a draft, approved or published version.
246
+ if (current !== undefined) {
247
+ for (const status of [PAGE_STATUS_APPROVED, PAGE_STATUS_PUBLISHED]) {
248
+ if (status === page.storedStatus || missing().length === 0) continue;
249
+ try {
250
+ for (const id of storedFormIds(await read(status), definitions)) held.add(id);
251
+ } catch (error) {
252
+ if (!(error instanceof ApiError && error.httpStatus === 404)) throw error;
253
+ }
254
+ }
255
+ }
256
+ for (const placement of missing()) {
257
+ appendAll(checked.problems, unavailableForm(page, placement, forms.get(definitions.get(placement.key).form.formId)));
258
+ }
259
+ }
260
+ return checked;
261
+ }
262
+
263
+ export function appendReusablePlacementReport(result, report, onProgress = () => {}) {
264
+ if (report === undefined) return result;
265
+ const room = LIMITS.githubOutputBytes - Buffer.byteLength(JSON.stringify(result), "utf8") - 512;
266
+ if (room < 512) {
267
+ onProgress("The JSON result has no room for the reusable placement summary.");
268
+ return result;
269
+ }
270
+ return { ...result, reusablePlacements: { ...report, ...boundedByBytes(report.items, room - 384) } };
271
+ }
@@ -21,6 +21,7 @@ import {
21
21
  SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES,
22
22
  SETTINGS_TYPE_TAPROOT_STYLES,
23
23
  } from "./settings-catalog.js";
24
+ import { REUSABLE_BLOCKS_FILE, REUSABLE_BLOCK_LIMITS } from "./reusable-blocks.js";
24
25
  import { projectPulledTheme } from "./theme-projection.js";
25
26
 
26
27
  /**
@@ -430,6 +431,11 @@ const PREFERENCES_ENTRIES = {
430
431
  + "deployment.",
431
432
  false,
432
433
  ),
434
+ codeCopyEnabled: entry(
435
+ "Settings > Footer > Publishing preferences > Code copy",
436
+ "Whether readers can copy the text of a preformatted code block with one button.",
437
+ "Published pages on Standard sites, including member-only content after unlock. A change applies after deployment.",
438
+ ),
433
439
  albumSeamless: entry(
434
440
  `${FEATURES} > Album layout`,
435
441
  "Whether album images sit edge to edge (seamless) by default. An album can set its own seamless value.",
@@ -699,6 +705,23 @@ export function getSettingsReference() {
699
705
  paths: ["settings.lightTheme", "settings.darkTheme"],
700
706
  })),
701
707
  pageBackgroundVersusCanvas: PAGE_BACKGROUND_VERSUS_CANVAS,
708
+ reusableBlocks: {
709
+ file: REUSABLE_BLOCKS_FILE,
710
+ surface: "standard",
711
+ pull: "pull --settings-only",
712
+ push: "theme push",
713
+ limits: REUSABLE_BLOCK_LIMITS,
714
+ document: {
715
+ blocks: [
716
+ { key: "read-the-guide", name: "Read the guide", type: "cta", data: { heading: "Read the guide", buttonText: "Read it", buttonUrl: "/guide/" } },
717
+ { key: "newsletter", name: "Newsletter", type: "form", data: { formKey: "email-signup", layout: "compact" } },
718
+ ],
719
+ },
720
+ cta: "Use the inline CTA fields from help component cta. Use pageResourceId in place of buttonUrl for an existing page by resource ID.",
721
+ form: "Use formKey from the Design form options. layout is optional; compact requires an eligible newsletter form.",
722
+ presence: "An absent file preserves definitions. A present file replaces the entire list. An empty blocks array requests to clear the list, subject to removal checks.",
723
+ evidence: "theme push --dry-run previews removals. After a complete pull, validate checks workspace placements. The real write also checks saved pages and retained releases. For current page references it reports ReusableBlockDefinitions.<key>.pages. A selected-release check needs the theme and page inventory for that release.",
724
+ },
702
725
  };
703
726
  }
704
727
 
@@ -744,5 +767,6 @@ export function formatSettingsReference(reference) {
744
767
  }`
745
768
  ).join("\n");
746
769
  const contrast = reference.pageBackgroundVersusCanvas;
747
- return `${reference.title}\nUsage: ${reference.usage}\n\nPage background image versus canvas image:\n - ${contrast.pageBackground}\n - ${contrast.canvas}\n - ${contrast.shared}\n\nApp controls stored inside the theme (help theme describes each field):\n${controls}\n\n${groups}\n`;
770
+ const blocks = reference.reusableBlocks;
771
+ return `${reference.title}\nUsage: ${reference.usage}\n\n${blocks.file} (Standard sites)\n Pull with '${blocks.pull}' and send changes with '${blocks.push}'.\n ${blocks.cta}\n ${blocks.form}\n ${blocks.presence}\n ${blocks.evidence}\n\nPage background image versus canvas image:\n - ${contrast.pageBackground}\n - ${contrast.canvas}\n - ${contrast.shared}\n\nApp controls stored inside the theme (help theme describes each field):\n${controls}\n\n${groups}\n`;
748
772
  }
@@ -157,6 +157,7 @@ export const SETTINGS_GROUPS = Object.freeze([
157
157
  ...stringFields("timeZone"),
158
158
  { name: "allowSearch", wireType: "boolean" },
159
159
  { name: "showFollowButton", wireType: "boolean" },
160
+ { name: "codeCopyEnabled", wireType: "boolean" },
160
161
  { name: "albumSeamless", wireType: "boolean" },
161
162
  // Negative sense on the wire (TR00868): an omitted value means the site
162
163
  // shows lightbox comments, which is also what `false` means here, so the
@@ -3,6 +3,7 @@ import { FOOTER_SETTINGS_FILE } from "./footer-workspace.js";
3
3
  import { sanitizeDiagnostic } from "./errors.js";
4
4
  import { boundedByBytes } from "./session.js";
5
5
  import rules from "./site-check-rules.json" with { type: "json" };
6
+ import { placedCompactFormKeys } from "./form-references.js";
6
7
  import { isFormKey } from "./forms-contract.js";
7
8
  import { DESCRIPTION_MINIMUM_LENGTH, DESCRIPTION_WARN_LENGTH, localAuthoringMetadata, METADATA_RULE_IDS, pageStructureFindings, RULE_IMAGE_DEFAULT_MISSING, TITLE_MINIMUM_LENGTH, TITLE_WARN_LENGTH } from "./page-structure-checks.js";
8
9
  import { missingPageLinkFindings, normalizedPathSet } from "./site-checks.js";
@@ -18,6 +19,7 @@ import { displayPagePath } from "./workspace.js";
18
19
  */
19
20
  export const SITE_CHECK_RULES = Object.freeze(rules.rules);
20
21
  export const SITE_FINDINGS_MAX_BYTES = 8 * 1024;
22
+ const RULE_FORM_COMPACT_UNAVAILABLE = "form.compact_unavailable";
21
23
 
22
24
  /** Why `validate` did not run the image description rule, which needs the site's image records (TR01371). */
23
25
  export const IMAGE_CHECK_NOT_REQUESTED = "not_requested";
@@ -50,6 +52,9 @@ export const SITE_CHECK_WORDING = Object.freeze({
50
52
  isFormKey(finding.subject)
51
53
  ? `places the form '${finding.subject}', but the workspace has no forms/${finding.subject}.json (add that form file, run 'forms pull' if the site has it, or fix the key)`
52
54
  : `places the form '${finding.subject}', which is not a form key (lowercase letters, digits and single hyphens)`,
55
+ [RULE_FORM_COMPACT_UNAVAILABLE]: (finding) =>
56
+ `uses Compact layout for '${finding.subject}', but the ${finding.detail === "workspace" ? "workspace definition" : "recorded form version"} `
57
+ + "needs exactly a required contact email and one consent checkbox. The selected release’s form version determines its layout",
53
58
  "form.not_supported_on_site_type": () => "places a form, but forms are available on standard sites only",
54
59
  "form.after_submit_page_unpublished": (finding) =>
55
60
  `the form '${finding.detail}' sends visitors to ${finding.subject || "a page that no longer exists"}, which the release does not publish`,
@@ -224,6 +229,7 @@ export function evaluateOfflineSiteChecks({
224
229
  pagePaths,
225
230
  pagesComplete = true,
226
231
  formKeysChecked = true,
232
+ formEvidence,
227
233
  footerInput,
228
234
  footerOnly = false,
229
235
  // Whether `validate --site` ran the image description rule (TR01371), or why it did not.
@@ -235,11 +241,28 @@ export function evaluateOfflineSiteChecks({
235
241
  const hiddenFooter = footer.total - footer.findings.length;
236
242
 
237
243
  const found = [];
244
+ let compactEvaluated = false;
245
+ let compactEvidenceMissing = false;
238
246
  for (const page of footerOnly ? [] : planned ?? []) {
239
247
  if (page.document === null || typeof page.document !== "object") continue;
240
248
  // The link rule needs every page path; the structure rules read only the page itself.
241
249
  const linkFindings = pagesComplete ? missingPageLinkFindings(page.document, page.pagePath ?? "", known) : [];
242
250
  for (const finding of [...linkFindings, ...structureFindingsFor(page)]) found.push({ page, finding });
251
+ const compactForms = [
252
+ ...placedCompactFormKeys(page.document).map((key) => ({ key, formKey: key })),
253
+ ...(page.reusableCompactForms ?? []),
254
+ ];
255
+ for (const { key, formKey, row } of compactForms) {
256
+ const evidence = formKey === undefined ? undefined : formEvidence?.(formKey, row);
257
+ if (evidence === undefined) {
258
+ compactEvidenceMissing = true;
259
+ continue;
260
+ }
261
+ compactEvaluated = true;
262
+ if (!evidence.eligible) found.push({ page, finding: {
263
+ ruleId: RULE_FORM_COMPACT_UNAVAILABLE, severity: "warning", subject: key, detail: evidence.source,
264
+ } });
265
+ }
243
266
  }
244
267
  for (const finding of footer.findings) found.push({ finding });
245
268
  // Keep severity and catalogue order in the byte-capped JSON list.
@@ -287,7 +310,7 @@ export function evaluateOfflineSiteChecks({
287
310
  ranOffline: footerInput === undefined ? [] : ["footer.word_breaks"],
288
311
  ...(footerSkipped.length === 0 ? {} : { skipped: footerSkipped }),
289
312
  } : {
290
- ranOffline: rulesRunningAt("validate"),
313
+ ranOffline: rulesRunningAt("validate").filter((id) => id !== RULE_FORM_COMPACT_UNAVAILABLE || compactEvaluated),
291
314
  // Local values are checked above; only a deployment knows every effective fallback.
292
315
  deferredToDeployment: [...METADATA_RULE_IDS],
293
316
  // Rules that need the site's own records; `taproot-site status` shows what the site finds.
@@ -304,16 +327,21 @@ export function evaluateOfflineSiteChecks({
304
327
  ).map((rule) => rule.id),
305
328
  // A rule that had nothing to read: a truncated page manifest, no site read for the images, or a workspace
306
329
  // with no form files, or a disabled footer. In catalogue order.
307
- ...(pagesComplete && formKeysChecked && imageCheck.ran && footerSkipped.length === 0
330
+ ...(pagesComplete && formKeysChecked && imageCheck.ran && !compactEvidenceMissing && footerSkipped.length === 0
308
331
  ? {}
309
332
  : {
310
333
  skipped: [
311
334
  ...(pagesComplete ? [] : ["link.page_missing"]),
312
335
  ...(imageCheck.ran ? [] : [RULE_IMAGE_DEFAULT_MISSING]),
313
336
  ...(formKeysChecked ? [] : ["form.key_unknown"]),
337
+ ...(compactEvidenceMissing ? [RULE_FORM_COMPACT_UNAVAILABLE] : []),
314
338
  ...footerSkipped,
315
339
  ],
316
340
  }),
341
+ ...(compactEvidenceMissing ? { formCompactCheckReason: {
342
+ code: "form_definition_unavailable",
343
+ message: "Some compact placements have no local form definition or version-matched catalog evidence.",
344
+ } } : {}),
317
345
  ...(imageCheck.ran
318
346
  ? {}
319
347
  : { imageCheckReason: { code: imageCheck.code, ...(imageCheck.message === undefined ? {} : { message: imageCheck.message }) } }),
@@ -14,6 +14,7 @@
14
14
  { "id": "form.after_submit_page_unpublished", "severity": "error", "scope": "site", "runsAt": ["deploy"], "subject": "page_path", "detail": "form_name" },
15
15
  { "id": "form.after_submit_page_not_allowed", "severity": "error", "scope": "site", "runsAt": ["deploy"], "subject": "page_path", "detail": "form_name" },
16
16
  { "id": "form.key_unknown", "severity": "error", "scope": "site", "runsAt": ["validate"], "subject": "form_key", "detail": "none" },
17
+ { "id": "form.compact_unavailable", "severity": "warning", "scope": "page", "runsAt": ["validate", "edit"], "subject": "form_key", "detail": "evidence_source" },
17
18
  { "id": "redirect.source_invalid", "severity": "error", "scope": "site", "runsAt": ["save", "validate"], "subject": "redirect_source", "detail": "none" },
18
19
  { "id": "redirect.source_index_html", "severity": "error", "scope": "site", "runsAt": ["save", "validate"], "subject": "redirect_source", "detail": "first_segment" },
19
20
  { "id": "redirect.source_integration_data", "severity": "error", "scope": "site", "runsAt": ["save", "validate"], "subject": "redirect_source", "detail": "first_segment" },
@@ -9,11 +9,12 @@
9
9
  * `shared/site-check-corpus.json`. Results carry rule ids and values, never
10
10
  * wording: each surface writes its own words.
11
11
  *
12
- * It is dependency-free so the published site-authoring package can carry a
13
- * compiled copy. The package cannot import this file, so
12
+ * The published site-authoring package carries a compiled copy. It cannot
13
+ * import this file, so
14
14
  * `node scripts/sync-field-validation.mjs` writes that copy; edit only this file
15
15
  * and re-run it.
16
16
  */
17
+ import { readFormPlacementPresentation } from "./content/form-placement-presentation.js";
17
18
  export const RULE_LINK_PAGE_MISSING = "link.page_missing";
18
19
  export const RULE_FORM_KEY_UNKNOWN = "form.key_unknown";
19
20
  export const RULE_REDIRECT_SOURCE_INVALID = "redirect.source_invalid";
@@ -176,6 +177,25 @@ function addEncodedComponentLinks(links, value, currentPagePath) {
176
177
  }
177
178
  addLinks(links, parsed, currentPagePath);
178
179
  }
180
+ function addFormLink(links, value, currentPagePath) {
181
+ let data = value;
182
+ if (typeof value === "string") {
183
+ try {
184
+ data = JSON.parse(value);
185
+ }
186
+ catch {
187
+ try {
188
+ data = JSON.parse(htmlDecodeRepeatedly(value));
189
+ }
190
+ catch {
191
+ return;
192
+ }
193
+ }
194
+ }
195
+ const link = readFormPlacementPresentation(data).finePrint?.linkUrl;
196
+ if (link !== undefined)
197
+ addCandidate(links, link, currentPagePath);
198
+ }
179
199
  function addLinks(links, element, currentPagePath) {
180
200
  if (Array.isArray(element)) {
181
201
  for (const item of element)
@@ -185,6 +205,10 @@ function addLinks(links, element, currentPagePath) {
185
205
  if (element === null || typeof element !== "object")
186
206
  return;
187
207
  for (const [name, value] of Object.entries(element)) {
208
+ if (name === "componentData" && "componentType" in element && element.componentType === "form") {
209
+ addFormLink(links, value, currentPagePath);
210
+ continue;
211
+ }
188
212
  if (typeof value === "string") {
189
213
  if (isUrlProperty(name))
190
214
  addCandidate(links, value, currentPagePath);
@@ -121,10 +121,27 @@ export function productionKeys(production) {
121
121
  if (production?.status !== "complete" || production.truncated === true || !production.deploymentId) return undefined;
122
122
  return {
123
123
  pages: new Set(production.findingKeys),
124
- images: new Set(production.images.map((image) => image.imageId)),
124
+ images: new Map(production.images.map(({ imageId, affectedPages }) => [
125
+ imageId,
126
+ {
127
+ resourceIds: new Set(affectedPages.flatMap(({ resourceId }) => resourceId === undefined ? [] : [resourceId])),
128
+ complete: affectedPages.every(({ resourceId }) => resourceId !== undefined),
129
+ },
130
+ ])),
125
131
  };
126
132
  }
127
133
 
134
+ /** Undefined means missing identity evidence prevents deciding whether the group is new. */
135
+ export function imageFindingNewSinceProduction({ imageId, affectedPages }, productionImages) {
136
+ const previous = productionImages?.get(imageId);
137
+ if (previous === undefined) return productionImages === undefined ? undefined : true;
138
+ if (previous.complete && affectedPages.some(({ resourceId }) =>
139
+ resourceId !== undefined && !previous.resourceIds.has(resourceId)
140
+ )) return true;
141
+ if (affectedPages.every(({ resourceId }) => previous.resourceIds.has(resourceId))) return false;
142
+ return undefined;
143
+ }
144
+
128
145
  /** The stored page findings as the CLI reports them. `keys` is `productionKeys`, or undefined for "not compared". */
129
146
  export function buildPageFindings(report, { fileByPageId, keys, environment }) {
130
147
  return report.findings.map((finding, index) => {
@@ -221,7 +238,10 @@ export function imageFindingLine(item) {
221
238
  * One summary line and a line for each warning that is new since production (each warning when production was not
222
239
  * compared), at most `MAXIMUM_PROGRESS_LINES`, each naming its fix.
223
240
  */
224
- export function reportHealthProgress(onProgress, { environment, checkedAt, status, findings, imageFindings, compared }) {
241
+ export function reportHealthProgress(
242
+ onProgress,
243
+ { environment, checkedAt, status, findings, imageFindings, compared, imageIdentityComplete },
244
+ ) {
225
245
  const incomplete = status === "incomplete"
226
246
  ? " Coverage is incomplete, so this report is not a pass."
227
247
  : "";
@@ -229,13 +249,15 @@ export function reportHealthProgress(onProgress, { environment, checkedAt, statu
229
249
  // Every value here ends up on a terminal, and some come from the manifest or the server unchecked, so each is
230
250
  // cleaned for display. The JSON result keeps the original values.
231
251
  const safe = (value, fallback = "") => sanitizeDiagnostic(value, fallback);
232
- const newFindings = [...findings, ...imageFindings].filter((item) => item.newSinceProduction !== false);
252
+ const allFindings = [...findings, ...imageFindings];
253
+ const newFindings = compared === true ? allFindings.filter((item) => item.newSinceProduction === true) : allFindings;
233
254
  const scope = environment === "staging" && compared === false
234
255
  ? "not compared with production, so every warning is listed"
235
256
  : environment === "staging"
236
257
  ? `${newFindings.length} new since production`
237
258
  : "production";
238
259
  onProgress(`Site health (${environment}, checked ${checkedAt}): ${total} finding(s), ${scope}.${incomplete}`);
260
+ if (imageIdentityComplete === false) onProgress("Some image uses could not be compared with production.");
239
261
  for (const item of siteFindingsForProgress(newFindings)) {
240
262
  if ("imageId" in item) {
241
263
  onProgress(imageFindingLine(item));
@@ -1,7 +1,7 @@
1
1
  // Generated from shared/site-health-image-checks.ts by scripts/sync-field-validation.mjs. Do not edit.
2
2
  /**
3
3
  * Site Health's `a11y.image_default_missing` rule (TR01364): an image the site owns, that some page places, and
4
- * whose default description is undefined. A page that places an image only as a section decoration does not count.
4
+ * whose default description is undefined. A page that places an image only as decoration does not count.
5
5
  *
6
6
  * The generator runs this over a frozen deployment and the site-authoring CLI runs it over what a workspace
7
7
  * places, so the rule has one owner. Both sides pass pages with an opaque `key` (the generator uses the page id,