@taprootio/site-authoring 0.36.1 → 0.37.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.
@@ -0,0 +1,49 @@
1
+ // Generated from shared/site-health-image-checks.ts by scripts/sync-field-validation.mjs. Do not edit.
2
+ /**
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.
5
+ *
6
+ * The generator runs this over a frozen deployment and the site-authoring CLI runs it over what a workspace
7
+ * places, so the rule has one owner. Both sides pass pages with an opaque `key` (the generator uses the page id,
8
+ * the CLI the workspace file) and the image records they hold. This file is dependency-free, so
9
+ * `node scripts/sync-field-validation.mjs` writes the generator copy and the CLI's compiled copy; edit only this
10
+ * file and re-run it. Findings carry values, never wording: each surface writes its own words.
11
+ */
12
+ /**
13
+ * Every undescribed image the pages place, one finding per image, in the order of `images`, with no cap (the
14
+ * caller applies its own). Each finding lists its pages in the order of `pages`, once per page even when that page
15
+ * places the image repeatedly. `siteId` is compared only with records that carry one. Image ids match by exact
16
+ * string, so callers pass the lowercase ids the API returns.
17
+ */
18
+ export function evaluateImageDefaultMissing(input) {
19
+ const usedBy = new Map();
20
+ for (const page of input.pages) {
21
+ const reference = { key: page.key, path: page.path, title: page.title };
22
+ for (const imageId of new Set(page.imageIds)) {
23
+ const usages = usedBy.get(imageId);
24
+ if (usages === undefined)
25
+ usedBy.set(imageId, [reference]);
26
+ else
27
+ usages.push(reference);
28
+ }
29
+ }
30
+ const findings = [];
31
+ for (const image of input.images) {
32
+ if (image.isMissing)
33
+ continue;
34
+ if (image.siteId !== undefined && image.siteId !== input.siteId)
35
+ continue;
36
+ if (image.defaultDescription !== undefined)
37
+ continue;
38
+ const affectedPages = usedBy.get(image.imageId);
39
+ if (affectedPages === undefined)
40
+ continue;
41
+ findings.push({
42
+ imageId: image.imageId,
43
+ name: image.name,
44
+ ...(image.previewUrl === undefined ? {} : { previewUrl: image.previewUrl }),
45
+ affectedPages: [...affectedPages],
46
+ });
47
+ }
48
+ return findings;
49
+ }
@@ -0,0 +1,341 @@
1
+ import { listSiteImagesByIds, updateSiteImageDescription } from "./api.js";
2
+ import {
3
+ LIMITS,
4
+ REFUSAL_CAPABILITY_MISSING,
5
+ REFUSAL_CLI_OUTDATED,
6
+ REFUSAL_CREDENTIAL_REJECTED,
7
+ REFUSAL_PLATFORM_PAUSED,
8
+ REFUSAL_THROTTLED,
9
+ } from "./constants.js";
10
+ import { outcomeUnknown, SiteAuthoringError } from "./errors.js";
11
+ import { placedImageIds } from "./placed-image-ids.js";
12
+ import { boundedByBytes } from "./session.js";
13
+ import {
14
+ IMAGE_CHECK_READ_FAILED,
15
+ IMAGE_CHECK_READ_PARTLY_FAILED,
16
+ MAXIMUM_PROGRESS_LINES,
17
+ SITE_CHECK_RULES,
18
+ } from "./site-check-findings.js";
19
+ import { evaluateImageDefaultMissing } from "./site-health-image-checks.js";
20
+ import { altsFromDocument, buildImageFinding, imageFindingLine, mergeAlts, usableDescription } from "./site-health-findings.js";
21
+ import { documentTemplate, PAGE_TEMPLATES, wireTemplate } from "./typed-pages.js";
22
+ import { translateImageDescriptionRefusal } from "./verbs/media-images.js";
23
+ import { displayPagePath } from "./workspace.js";
24
+
25
+ /**
26
+ * Site Health's image description rule, run before staging from what the workspace places (TR01371). `validate
27
+ * --site` and `pages push` share it. It reads the site's own image records once, evaluates the shared rule over the
28
+ * pages the command selected, and reports each undescribed image with the exact fix, as the stored report does
29
+ * after staging. A warning is reported and never refuses.
30
+ */
31
+
32
+ const RULE = SITE_CHECK_RULES.find((rule) => rule.id === "a11y.image_default_missing").id;
33
+ /** The most the findings and the not-in-library ids take of a result, before the result itself is fitted. */
34
+ export const PRECHECK_BUDGETS = Object.freeze({ imageFindings: 12 * 1024, notInSiteLibrary: 2 * 1024 });
35
+
36
+ const STATUS_CHECKED = "checked";
37
+ const STATUS_PARTIAL = "partial";
38
+ const STATUS_NOT_CHECKED = "not_checked";
39
+
40
+ const REASONS = Object.freeze({
41
+ [IMAGE_CHECK_READ_FAILED]: "The site's image records could not be read, so image descriptions were not checked.",
42
+ [IMAGE_CHECK_READ_PARTLY_FAILED]:
43
+ "Some of the site's image records could not be read, so only the images that were read were checked.",
44
+ });
45
+
46
+ /**
47
+ * The pages a command selected, as the evaluator takes them: keyed by workspace file (a new page has no id yet),
48
+ * with each page's placed image ids and its converted document, which the alt text is read from later. A page whose
49
+ * wire form cannot be built contributes no ids, because the conversion already accepted it.
50
+ */
51
+ export function placedImageIdsForPages(pages) {
52
+ return pages.map((page) => {
53
+ let imageIds = [];
54
+ try {
55
+ const template = documentTemplate(page.document);
56
+ imageIds = [...placedImageIds(template, wireTemplate(page.document)[PAGE_TEMPLATES[template].dataKey])];
57
+ // The cover is a field beside the body, so the walk does not see it; the freezer adds it the same way.
58
+ const cover = page.document.coverImageId;
59
+ if (typeof cover === "string" && cover !== "") imageIds.push(cover.toLowerCase());
60
+ } catch {
61
+ imageIds = [];
62
+ }
63
+ return { key: page.file, path: displayPagePath(page.pagePath), title: page.title, imageIds, document: page.document };
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Reads the site's records for every image the pages place, once, in batches of 100. A failed or denied batch never
69
+ * throws: its ids are in `failedIds`, and `status` says whether every batch was read, some, or none. With no
70
+ * placed image it makes no request. `records` is a Map keyed by image id that a later step may update in place.
71
+ */
72
+ export async function readImageRecords(client, siteId, imageIds) {
73
+ const ids = [...new Set(imageIds)].sort();
74
+ if (ids.length === 0) return { siteId, ids, records: new Map(), failedIds: [], status: STATUS_CHECKED };
75
+ const read = await listSiteImagesByIds(client, siteId, ids);
76
+ const status = read.failedIds.length === 0
77
+ ? STATUS_CHECKED
78
+ : read.failedIds.length === ids.length
79
+ ? STATUS_NOT_CHECKED
80
+ : STATUS_PARTIAL;
81
+ const code = status === STATUS_NOT_CHECKED
82
+ ? IMAGE_CHECK_READ_FAILED
83
+ : status === STATUS_PARTIAL
84
+ ? IMAGE_CHECK_READ_PARTLY_FAILED
85
+ : undefined;
86
+ return {
87
+ siteId,
88
+ ids,
89
+ records: new Map(read.images.map((image) => [image.imageId, image])),
90
+ failedIds: read.failedIds,
91
+ status,
92
+ ...(code === undefined ? {} : { reason: { code, message: REASONS[code] } }),
93
+ ...(read.refusalError === undefined ? {} : { refusalError: read.refusalError }),
94
+ };
95
+ }
96
+
97
+ const listOf = (items, budget) => {
98
+ const kept = boundedByBytes(items, budget);
99
+ return { total: items.length, items: kept.items, ...(kept.truncated ? { truncated: true } : {}) };
100
+ };
101
+
102
+ /**
103
+ * Turns the kept state and the selected pages into the block a result reports, and prints its progress lines: one
104
+ * for each finding (at most 20, then a count) and one saying how many images could not be read. It reads nothing,
105
+ * so it runs when the result is built and reports whatever the records then hold.
106
+ *
107
+ * Findings are ordered by image id, so a bounded list keeps the same findings on every run. An id the site did not
108
+ * return (deleted, or owned by another site, a profile or an integration) is `notInSiteLibrary` and no finding; an
109
+ * id in a failed batch is in neither list.
110
+ */
111
+ export function evaluateImagePrecheck(state, pages, onProgress = () => {}) {
112
+ const found = evaluateImageDefaultMissing({
113
+ pages,
114
+ images: [...state.records.values()]
115
+ .sort((left, right) => (left.imageId < right.imageId ? -1 : left.imageId > right.imageId ? 1 : 0))
116
+ .map((image) => ({
117
+ imageId: image.imageId,
118
+ name: image.name,
119
+ ...(image.defaultDescription === undefined ? {} : { defaultDescription: image.defaultDescription }),
120
+ })),
121
+ siteId: state.siteId,
122
+ });
123
+ // Alt text is only needed to suggest a fix, and each page is its own failure: a page that cannot be walked
124
+ // contributes nothing.
125
+ const alts = new Map();
126
+ if (found.length > 0) {
127
+ for (const page of pages) {
128
+ try {
129
+ mergeAlts(alts, altsFromDocument(page.document));
130
+ } catch {
131
+ continue;
132
+ }
133
+ }
134
+ }
135
+ const findings = found.map((finding) =>
136
+ buildImageFinding({
137
+ imageId: finding.imageId,
138
+ name: finding.name,
139
+ descriptionRevision: state.records.get(finding.imageId).descriptionRevision,
140
+ hasDefault: false,
141
+ available: true,
142
+ alts: alts.get(finding.imageId) ?? [],
143
+ affectedPages: finding.affectedPages.map((page) => ({ path: page.path, title: page.title, file: page.key })),
144
+ })
145
+ );
146
+ const failed = new Set(state.failedIds);
147
+ const notInSiteLibrary = state.ids.filter((id) => !state.records.has(id) && !failed.has(id));
148
+
149
+ if (state.failedIds.length > 0) {
150
+ onProgress(
151
+ `Warning: ${state.failedIds.length} image(s) could not be read from the site, so their descriptions were not checked.`,
152
+ );
153
+ }
154
+ for (const finding of findings.slice(0, MAXIMUM_PROGRESS_LINES)) onProgress(imageFindingLine(finding));
155
+ if (findings.length > MAXIMUM_PROGRESS_LINES) {
156
+ onProgress(`Warning: ${findings.length - MAXIMUM_PROGRESS_LINES} more undescribed image(s); see imageFindings.`);
157
+ }
158
+ return {
159
+ status: state.status,
160
+ checkedPages: pages.length,
161
+ imageFindings: listOf(findings, PRECHECK_BUDGETS.imageFindings),
162
+ notInSiteLibrary: listOf(notInSiteLibrary, PRECHECK_BUDGETS.notInSiteLibrary),
163
+ skipped: state.status === STATUS_CHECKED ? [] : [RULE],
164
+ ...(state.reason === undefined ? {} : { reason: state.reason }),
165
+ };
166
+ }
167
+
168
+ const listAt = (value, path) => path.split(".").reduce((node, key) => node?.[key], value);
169
+
170
+ /**
171
+ * Shrinks the new blocks so the result still fits the output bound. `base` is the result without them, `blocks` are
172
+ * the top-level keys to add, and `order` names the `{ total, items, truncated? }` lists to shrink, first to last,
173
+ * each down to empty if needed, as dotted paths into `blocks`. A list that is absent is skipped, so a block a
174
+ * later story adds needs no change here. Every `total` is kept, and a shrunk list is marked `truncated`. It never
175
+ * throws: a base that already fills the bound is returned with empty lists and fails where the result is
176
+ * serialized, as it does today.
177
+ */
178
+ export function fitPrecheckToBudget(base, blocks, order, budget = LIMITS.githubOutputBytes) {
179
+ const fitted = structuredClone(blocks);
180
+ const size = () => Buffer.byteLength(JSON.stringify({ ...base, ...fitted }), "utf8");
181
+ for (const path of order) {
182
+ const list = listAt(fitted, path);
183
+ if (list === undefined || !Array.isArray(list.items)) continue;
184
+ while (size() > budget && list.items.length > 0) {
185
+ list.items.pop();
186
+ list.truncated = true;
187
+ }
188
+ }
189
+ return fitted;
190
+ }
191
+
192
+ // ---------------------------------------------------------------------------
193
+ // --describe-missing-images (TR01372)
194
+ // ---------------------------------------------------------------------------
195
+
196
+ /** What the report of a flagged push carries about the images it set or skipped; `set` and `skipped` are bounded. */
197
+ export const DESCRIBED_IMAGES_BUDGETS = Object.freeze({ set: 3 * 1024, skipped: 1 * 1024 });
198
+
199
+ /**
200
+ * Which placed images the flag would set, and why it leaves the others: ascending by image id, from the kept read
201
+ * state and the selected pages. An image is a candidate when its kept record has no default (so one already
202
+ * described at read time is not listed) or when its id is in a failed read batch, which cannot be set (`not_read`).
203
+ * The text is the one distinct alt the selected placements agree on; none is `no_alt`, two or more `alts_disagree`,
204
+ * and one that cannot be put in a describe command `unusable_alt`. Pure: it reads nothing.
205
+ */
206
+ export function planImageDescriptions(state, pages) {
207
+ const failed = new Set(state.failedIds);
208
+ const candidates = [
209
+ ...[...state.records.values()].filter((record) => record.defaultDescription === undefined).map((record) => record.imageId),
210
+ ...state.failedIds,
211
+ ];
212
+ const alts = new Map();
213
+ if (candidates.length > 0) {
214
+ for (const page of pages) {
215
+ try {
216
+ mergeAlts(alts, altsFromDocument(page.document));
217
+ } catch {
218
+ continue;
219
+ }
220
+ }
221
+ }
222
+ return [...new Set(candidates)].sort().map((imageId) => {
223
+ if (failed.has(imageId)) return { imageId, reason: "not_read" };
224
+ const texts = alts.get(imageId) ?? [];
225
+ if (texts.length === 0) return { imageId, reason: "no_alt" };
226
+ if (texts.length > 1) return { imageId, reason: "alts_disagree" };
227
+ const description = usableDescription(texts[0]);
228
+ return description === undefined
229
+ ? { imageId, reason: "unusable_alt" }
230
+ : { imageId, description, expectedRevision: state.records.get(imageId).descriptionRevision };
231
+ });
232
+ }
233
+
234
+ /** What the command does after a refused or failed description write, by the story's table, in its order. */
235
+ export function classifyDescriptionFailure(error) {
236
+ if (!(error instanceof SiteAuthoringError)) return { action: "fail" };
237
+ if (error.code === "site.cancelled") return { action: "fail" };
238
+ const kind = typeof error.refusalKind === "function" ? error.refusalKind() : undefined;
239
+ if ([REFUSAL_CLI_OUTDATED, REFUSAL_PLATFORM_PAUSED, REFUSAL_CREDENTIAL_REJECTED].includes(kind)) return { action: "fail" };
240
+ if (kind === REFUSAL_THROTTLED) return { action: "stop", reason: "write_failed" };
241
+ if (kind === REFUSAL_CAPABILITY_MISSING || error.httpStatus === 403) return { action: "stop", reason: "write_denied" };
242
+ // The PATCH may have committed when it ended this way, so the image is never reported as failed.
243
+ if (
244
+ outcomeUnknown(error)
245
+ || ["api.image_description_contract", "api.image_contract", "api.image_state"].includes(error.code)
246
+ ) {
247
+ return { action: "unknown", reason: "write_unknown" };
248
+ }
249
+ const refusal = translateImageDescriptionRefusal(error);
250
+ const reason = {
251
+ "media.image_description_conflict": "revision_moved",
252
+ "media.image_description_exists": "already_described",
253
+ "media.image_description_invalid": "invalid_description",
254
+ }[refusal.code];
255
+ return { action: "skip", reason: reason ?? "write_failed" };
256
+ }
257
+
258
+ /** Brings a kept record up to what a successful write returned, so the precheck no longer reports it. */
259
+ function recordWritten(record, written) {
260
+ record.descriptionRevision = written.descriptionRevision;
261
+ if (typeof written.defaultDescription === "string" && written.defaultDescription !== "") {
262
+ record.defaultDescription = written.defaultDescription;
263
+ } else {
264
+ delete record.defaultDescription;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Writes the planned descriptions one at a time, in ascending image id order, each with the revision the read
270
+ * returned and `onlyIfMissing`, so nothing is ever overwritten and a conflict is reported, not retried. A success
271
+ * updates the kept record in place. A cancelled run, an outdated CLI, a paused platform or a rejected credential
272
+ * stops the run and throws with `describeOutcome` (what was set, and which writes may have committed) attached;
273
+ * throttling and a denied write stop further writes and mark the rest skipped; an unknown outcome leaves the record
274
+ * as it was and goes on. Returns the images set and the ones skipped, in order.
275
+ */
276
+ export async function describeMissingImages({ client, siteId, state, plan }) {
277
+ const set = [];
278
+ const skipped = [];
279
+ const unknown = [];
280
+ let stoppedFor;
281
+ for (const item of plan) {
282
+ if (item.description === undefined) {
283
+ skipped.push({ imageId: item.imageId, reason: item.reason });
284
+ continue;
285
+ }
286
+ if (stoppedFor !== undefined) {
287
+ skipped.push({ imageId: item.imageId, reason: stoppedFor });
288
+ continue;
289
+ }
290
+ try {
291
+ const written = await updateSiteImageDescription(client, siteId, item.imageId, {
292
+ defaultDescription: item.description,
293
+ expectedRevision: item.expectedRevision,
294
+ onlyIfMissing: true,
295
+ });
296
+ recordWritten(state.records.get(item.imageId), written);
297
+ set.push({ imageId: item.imageId, description: item.description });
298
+ } catch (error) {
299
+ const outcome = classifyDescriptionFailure(error);
300
+ if (outcome.action === "fail") {
301
+ error.describeOutcome = {
302
+ set: set.map((entry) => entry.imageId),
303
+ unknown: [...unknown],
304
+ failing: error instanceof SiteAuthoringError && outcomeUnknown(error) ? item.imageId : undefined,
305
+ };
306
+ throw error;
307
+ }
308
+ if (outcome.action === "stop") stoppedFor = outcome.reason;
309
+ if (outcome.action === "unknown") unknown.push(item.imageId);
310
+ skipped.push({ imageId: item.imageId, reason: outcome.reason });
311
+ }
312
+ }
313
+ return { set, skipped };
314
+ }
315
+
316
+ /** The report a flagged push adds as `describedImages`, bounded; `reason` is the read's, when it did not complete. */
317
+ export function describedImagesBlock({ set, skipped }, state) {
318
+ return {
319
+ set: listOf(set, DESCRIBED_IMAGES_BUDGETS.set),
320
+ skipped: listOf(skipped, DESCRIBED_IMAGES_BUDGETS.skipped),
321
+ ...(state.reason === undefined ? {} : { reason: state.reason }),
322
+ };
323
+ }
324
+
325
+ /**
326
+ * The operations that committed before an image write failed the command, in the order the 100-entry cap should keep
327
+ * them: the failing image when its outcome is unknown, three count lines, each image set, each earlier unknown
328
+ * image, then each saved page (`savedPages` are labels such as `page about: created`).
329
+ */
330
+ export function completedWritesForDescribe({ outcome, savedPages }) {
331
+ const unknown = [...(outcome.failing === undefined ? [] : [outcome.failing]), ...outcome.unknown];
332
+ return [
333
+ ...(outcome.failing === undefined ? [] : [`image ${outcome.failing}: unknown`]),
334
+ `${outcome.set.length} image(s): set`,
335
+ `${unknown.length} image(s): unknown`,
336
+ `${savedPages.length} page(s): saved`,
337
+ ...outcome.set.map((imageId) => `image ${imageId}: set`),
338
+ ...outcome.unknown.map((imageId) => `image ${imageId}: unknown`),
339
+ ...savedPages,
340
+ ];
341
+ }
@@ -29,6 +29,7 @@ import { HANDOFF_NOT_REQUESTED_PROGRESS, handoffNotRequested, inspectStagingPrev
29
29
  import { confirmStagingServed, readStagingReleaseBefore, unverifiedStagingServed } from "../staging-served.js";
30
30
  import { ApiError } from "../transport.js";
31
31
  import { readManifest, writeManifest } from "../workspace.js";
32
+ import { DEPLOY_HEALTH_BUDGETS, DOCS_SITE_HEALTH_NOT_COVERED, readFailureCode, readSiteHealthReport } from "./health.js";
32
33
  import { STAGING_REVIEW_GUIDANCE } from "./staging-review.js";
33
34
 
34
35
  /**
@@ -227,6 +228,26 @@ async function mintPresentationStagingHandoff(client, siteId, onProgress, now, r
227
228
  }
228
229
  }
229
230
 
231
+ /**
232
+ * The Site Health report of the release just staged (TR01363): the same object `health --staging` returns, under
233
+ * a smaller byte budget. A warning never fails the deploy and a read that fails never reports a completed deploy
234
+ * as failed, so every error but a cancelled run becomes `{ available: false, reason }`.
235
+ */
236
+ async function readStagedSiteHealth({ client, config, siteId, onProgress, deploymentId }) {
237
+ try {
238
+ const report = await readSiteHealthReport({
239
+ client, config, siteId, onProgress, environment: DEPLOY_TARGET_STAGING,
240
+ stagedDeploymentId: deploymentId, budgets: DEPLOY_HEALTH_BUDGETS,
241
+ });
242
+ if (!report.available) onProgress(`Site health (staging): ${report.reason}`);
243
+ return report;
244
+ } catch (error) {
245
+ const reason = `The staged Site Health report could not be read (${readFailureCode(error)}). Run 'taproot-site health --staging' to read it.`;
246
+ onProgress(`Warning: ${reason}`);
247
+ return { available: false, environment: DEPLOY_TARGET_STAGING, unpublishedChangesAssessed: false, reason };
248
+ }
249
+ }
250
+
230
251
  export async function deploy(invocation) {
231
252
  const target = invocation.deployTarget;
232
253
  if (target !== DEPLOY_TARGET_STAGING && target !== DEPLOY_TARGET_PRODUCTION) {
@@ -433,6 +454,10 @@ export async function deploy(invocation) {
433
454
  now,
434
455
  });
435
456
  if (stagingServed.state !== "served") onProgress(`Warning: ${stagingServed.message}`);
457
+ // The report is stored before a release is served, so no waiting is needed (TR01363).
458
+ const siteHealth = presentationOnly
459
+ ? { covered: false, reason: DOCS_SITE_HEALTH_NOT_COVERED }
460
+ : await readStagedSiteHealth({ client, config, siteId, onProgress, deploymentId: completed.id });
436
461
  if (presentationOnly) {
437
462
  // The review URL is a live credential, so it is minted only when asked for (TR01233).
438
463
  if (invocation.handoff !== true) onProgress(HANDOFF_NOT_REQUESTED_PROGRESS);
@@ -452,6 +477,7 @@ export async function deploy(invocation) {
452
477
  outcome: created.outcome,
453
478
  readiness: reportReadiness(readiness),
454
479
  stagingServed,
480
+ siteHealth,
455
481
  stagingPreview,
456
482
  nextStep: stagingPreview.url === "" ? "staging review" : "deploy --production",
457
483
  });
@@ -473,6 +499,7 @@ export async function deploy(invocation) {
473
499
  outcome: created.outcome,
474
500
  readiness: reportReadiness(readiness),
475
501
  stagingServed,
502
+ siteHealth,
476
503
  routeCheck,
477
504
  redirects,
478
505
  stagingPreview,