@taprootio/site-authoring 0.36.2 → 0.37.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.
@@ -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,
@@ -0,0 +1,266 @@
1
+ import { getSiteHealth, listSiteImagesByIds, withRefusalGuidance } from "../api.js";
2
+ import {
3
+ CLI_BINARY_NAME,
4
+ DEPLOY_TARGET_PRODUCTION,
5
+ DEPLOY_TARGET_STAGING,
6
+ SURFACE_DOCS_PRESENTATION,
7
+ VERB_HEALTH,
8
+ } from "../constants.js";
9
+ import { SiteAuthoringError } from "../errors.js";
10
+ import { boundedByBytes, openSession, successResult } from "../session.js";
11
+ import {
12
+ altsFromDocument,
13
+ buildImageFinding,
14
+ buildPageFindings,
15
+ filesByPageId,
16
+ mergeAlts,
17
+ productionKeys,
18
+ reportHealthProgress,
19
+ resolveAffectedPages,
20
+ } from "../site-health-findings.js";
21
+ import { readManifest, readMediaManifest } from "../workspace.js";
22
+ import { convertWorkspacePageSource, readWorkspacePageSource, requireCompletePageMetadata } from "./pages-push.js";
23
+
24
+ /**
25
+ * `health --staging | --production` — the stored Site Health report of one release (TR01363).
26
+ *
27
+ * Site Health is compiled when a release is generated, so this reads what the release stored and never
28
+ * recomputes it. It marks the findings that are new since production, and gives each an exact fix. Read-only.
29
+ */
30
+
31
+ /** About the findings a `health` result carries; a full 200 and 200 report still fits the 64 KiB result bound. */
32
+ export const HEALTH_BUDGETS = Object.freeze({ findings: 32 * 1024, imageFindings: 16 * 1024 });
33
+ /** `deploy --staging` also carries readiness, redirects and the staging preview, so its share is smaller. */
34
+ export const DEPLOY_HEALTH_BUDGETS = Object.freeze({ findings: 12 * 1024, imageFindings: 8 * 1024 });
35
+
36
+ export const DOCS_SITE_HEALTH_NOT_COVERED =
37
+ "This is a managed Docs site: its pages come from the Docs artifact, so Site Health does not apply and no "
38
+ + "report was read.";
39
+
40
+ /**
41
+ * Why a health read failed, as a short code for a warning: `deploy` and `status` never fail a command on a read
42
+ * that comes after the work they report, so every error but a cancelled run is reduced to this. An error that is
43
+ * not the CLI's own is named only as unexpected, because its text is not ours to print.
44
+ */
45
+ export function readFailureCode(error) {
46
+ if (error instanceof SiteAuthoringError && error.code === "site.cancelled") throw error;
47
+ return error instanceof SiteAuthoringError ? error.code : "unexpected";
48
+ }
49
+
50
+ const INCOMPLETE_NOTE = "Coverage is incomplete, so this report is not a pass; the findings below are all it holds.";
51
+
52
+ const UNAVAILABLE_REASONS = Object.freeze({
53
+ not_checked: {
54
+ [DEPLOY_TARGET_PRODUCTION]: "Production has no stored report yet. A report is created when a release is generated.",
55
+ [DEPLOY_TARGET_STAGING]:
56
+ "No stored report exists for the staged release. If one was just staged, run "
57
+ + `'${CLI_BINARY_NAME} health --staging' again shortly (nothing here waits); otherwise run '${CLI_BINARY_NAME} deploy --staging'.`,
58
+ },
59
+ unsupported: "Site Health does not support this site type, so there is no report.",
60
+ incomplete: "The stored report could not be read as a complete report, so it has no deployment identity to show.",
61
+ unknown: "Taproot returned a report with a status this CLI does not know.",
62
+ });
63
+
64
+ function unavailable(status, environment) {
65
+ const reason = status === "not_checked"
66
+ ? UNAVAILABLE_REASONS.not_checked[environment]
67
+ : UNAVAILABLE_REASONS[status] ?? UNAVAILABLE_REASONS.unknown;
68
+ return { available: false, status, environment, unpublishedChangesAssessed: false, reason };
69
+ }
70
+
71
+ /**
72
+ * The alt text the workspace places for each image, read offline with the conversion `validate` uses.
73
+ *
74
+ * A page that cannot be read, converted or walked contributes nothing, so this never fails a verb. `files` are the
75
+ * page sources to read, tracked or not; the default is every tracked source. Returns a Map from lowercase image id
76
+ * to its distinct trimmed non-empty alts, in file order (see `altsFromDocument` for what counts).
77
+ */
78
+ export async function collectPlacementAlts({ workspaceDir, manifest, mediaManifest, files, content }) {
79
+ const entryByFile = new Map();
80
+ for (const entry of manifest?.pages ?? []) {
81
+ if (typeof entry?.file === "string") entryByFile.set(entry.file, entry);
82
+ }
83
+ const alts = new Map();
84
+ for (const file of files ?? [...entryByFile.keys()]) {
85
+ let found;
86
+ try {
87
+ const source = requireCompletePageMetadata(
88
+ await readWorkspacePageSource({ workspaceDir, file, manifestEntry: entryByFile.get(file) }),
89
+ );
90
+ found = altsFromDocument(await convertWorkspacePageSource({ source, mediaManifest, content }));
91
+ } catch {
92
+ continue;
93
+ }
94
+ mergeAlts(alts, found);
95
+ }
96
+ return alts;
97
+ }
98
+
99
+ /** A media manifest that cannot be read only costs alt suggestions; it never fails a health read. */
100
+ async function readMediaManifestOrEmpty(workspaceDir, siteId, onProgress) {
101
+ try {
102
+ return await readMediaManifest(workspaceDir, siteId);
103
+ } catch {
104
+ onProgress("Warning: the workspace's media manifest could not be read, so no alt text is suggested for images.");
105
+ return { media: {}, videos: {} };
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Reads one release's stored report and shapes it for a result. Shared by `health` and `deploy --staging`, so
111
+ * both return the same object. Production is read first, for the comparison and for the staged release's id;
112
+ * `deploy` passes the id of the deployment it just staged, so its read never depends on what production names.
113
+ */
114
+ export async function readSiteHealthReport({
115
+ client,
116
+ config,
117
+ siteId,
118
+ onProgress,
119
+ environment,
120
+ stagedDeploymentId,
121
+ budgets,
122
+ }) {
123
+ const production = await getSiteHealth(client, siteId);
124
+ let report = production;
125
+ if (environment === DEPLOY_TARGET_STAGING) {
126
+ const releaseId = stagedDeploymentId ?? production.stagedDeploymentId;
127
+ if (releaseId === undefined) return unavailable("not_checked", environment);
128
+ report = await getSiteHealth(client, siteId, { deploymentId: releaseId });
129
+ }
130
+ const available = ["complete", "incomplete"].includes(report.status) && Boolean(report.deploymentId);
131
+ if (!available) return unavailable(report.status, environment);
132
+
133
+ const manifest = await readManifest(config.workspaceDir, siteId, { required: false });
134
+ const fileByPageId = filesByPageId(manifest);
135
+ const staging = environment === DEPLOY_TARGET_STAGING;
136
+ const keys = staging ? productionKeys(production) : undefined;
137
+ const findings = buildPageFindings(report, { fileByPageId, keys, environment });
138
+
139
+ // Image reads and page sources are only needed when there is an image finding to fix.
140
+ let imageFindings = [];
141
+ if (report.images.length > 0) {
142
+ const read = await listSiteImagesByIds(client, siteId, report.images.map((image) => image.imageId));
143
+ if (read.failedIds.length > 0) {
144
+ onProgress(
145
+ `Warning: ${read.failedIds.length} image(s) could not be read, so their fixes lack the description revision; `
146
+ + `run '${CLI_BINARY_NAME} media images get <image-id>' for it.`,
147
+ );
148
+ }
149
+ const records = new Map(read.images.map((image) => [image.imageId, image]));
150
+ const failed = new Set(read.failedIds);
151
+ // In manifest order, so the first usable alt for an image is the same whichever finding names a page first.
152
+ const affected = new Set(
153
+ report.images.flatMap((image) => image.affectedPages.map((page) => fileByPageId.get(page.pageId))),
154
+ );
155
+ const affectedFiles = (manifest?.pages ?? []).map((entry) => entry?.file)
156
+ .filter((file) => typeof file === "string" && affected.has(file));
157
+ const alts = affectedFiles.length === 0
158
+ ? new Map()
159
+ : await collectPlacementAlts({
160
+ workspaceDir: config.workspaceDir,
161
+ manifest,
162
+ mediaManifest: await readMediaManifestOrEmpty(config.workspaceDir, siteId, onProgress),
163
+ files: affectedFiles,
164
+ });
165
+ imageFindings = report.images.map((stored) => {
166
+ const record = records.get(stored.imageId);
167
+ const isFailed = failed.has(stored.imageId);
168
+ return {
169
+ ...buildImageFinding({
170
+ imageId: stored.imageId,
171
+ name: stored.name || record?.name || "",
172
+ descriptionRevision: isFailed ? undefined : record?.descriptionRevision,
173
+ hasDefault: record !== undefined && record.defaultDescription !== undefined,
174
+ available: isFailed || record !== undefined,
175
+ alts: alts.get(stored.imageId) ?? [],
176
+ affectedPages: resolveAffectedPages(stored.affectedPages, fileByPageId),
177
+ environment,
178
+ }),
179
+ ...(keys === undefined ? {} : { newSinceProduction: !keys.images.has(stored.imageId) }),
180
+ };
181
+ });
182
+ }
183
+
184
+ const compared = keys !== undefined;
185
+ reportHealthProgress(onProgress, {
186
+ environment,
187
+ checkedAt: report.checkedAt,
188
+ status: report.status,
189
+ findings,
190
+ imageFindings,
191
+ compared: staging ? compared : undefined,
192
+ });
193
+ const keptFindings = boundedByBytes(findings, budgets.findings);
194
+ const keptImages = boundedByBytes(imageFindings, budgets.imageFindings);
195
+ return {
196
+ available: true,
197
+ status: report.status,
198
+ environment,
199
+ deploymentId: report.deploymentId,
200
+ outputReleaseId: report.outputReleaseId,
201
+ checkedAt: report.checkedAt,
202
+ ruleVersion: report.ruleVersion,
203
+ coverage: report.coverage,
204
+ assessedPageCount: report.assessedPageCount,
205
+ errorCount: report.errorCount,
206
+ warningCount: report.warningCount,
207
+ truncated: report.truncated,
208
+ // The report covers the named release only; drafts and approvals made after it are outside it.
209
+ unpublishedChangesAssessed: false,
210
+ ...(report.status === "incomplete" ? { note: INCOMPLETE_NOTE } : {}),
211
+ ...(staging
212
+ ? {
213
+ comparison: compared
214
+ ? {
215
+ comparedTo: "production",
216
+ compared: true,
217
+ newFindings: findings.filter((item) => item.newSinceProduction).length,
218
+ newImageFindings: imageFindings.filter((item) => item.newSinceProduction).length,
219
+ }
220
+ : {
221
+ comparedTo: "production",
222
+ compared: false,
223
+ reason: "Production has no complete, untruncated report to compare with, so every finding is listed as not compared.",
224
+ },
225
+ }
226
+ : {}),
227
+ findingsTotal: findings.length,
228
+ imageFindingsTotal: imageFindings.length,
229
+ findings: keptFindings.items,
230
+ imageFindings: keptImages.items,
231
+ ...(keptFindings.truncated ? { findingsTruncated: true } : {}),
232
+ ...(keptImages.truncated ? { imageFindingsTruncated: true } : {}),
233
+ };
234
+ }
235
+
236
+ export async function health(invocation) {
237
+ const target = invocation.deployTarget;
238
+ if (target !== DEPLOY_TARGET_STAGING && target !== DEPLOY_TARGET_PRODUCTION) {
239
+ throw new SiteAuthoringError("health.target_missing", "health requires exactly one of --staging or --production.", {
240
+ field: "deployTarget",
241
+ exitCode: 2,
242
+ });
243
+ }
244
+ const { client, config, siteId, surface, onProgress } = await openSession(invocation);
245
+ return await withRefusalGuidance(onProgress, "health", async () => {
246
+ if (surface === SURFACE_DOCS_PRESENTATION) {
247
+ onProgress(DOCS_SITE_HEALTH_NOT_COVERED);
248
+ return successResult(VERB_HEALTH, siteId, {
249
+ environment: target,
250
+ covered: false,
251
+ reason: DOCS_SITE_HEALTH_NOT_COVERED,
252
+ });
253
+ }
254
+ onProgress(`Reading the stored ${target} Site Health report.`);
255
+ const report = await readSiteHealthReport({
256
+ client,
257
+ config,
258
+ siteId,
259
+ onProgress,
260
+ environment: target,
261
+ budgets: HEALTH_BUDGETS,
262
+ });
263
+ if (!report.available) onProgress(`Site health (${target}): ${report.reason}`);
264
+ return successResult(VERB_HEALTH, siteId, report);
265
+ });
266
+ }
@@ -11,6 +11,7 @@ import {
11
11
  VERB_FORMS_PULL,
12
12
  VERB_FORMS_PUSH,
13
13
  VERB_FORMS_VALIDATE,
14
+ VERB_HEALTH,
14
15
  VERB_LINK_BUILD,
15
16
  VERB_LOGIN,
16
17
  VERB_LOGOUT,
@@ -55,6 +56,7 @@ import { footerPush } from "./footer-push.js";
55
56
  import { formsPull } from "./forms-pull.js";
56
57
  import { formsPush } from "./forms-push.js";
57
58
  import { formsValidate } from "./forms-validate.js";
59
+ import { health } from "./health.js";
58
60
  import { linkBuild } from "./link-build.js";
59
61
  import { login } from "./login.js";
60
62
  import { logout } from "./logout.js";
@@ -209,4 +211,5 @@ export const VERB_HANDLERS = Object.freeze({
209
211
  [VERB_STATUS]: status,
210
212
  [VERB_DELIVERY_CHECK]: deliveryCheck,
211
213
  [VERB_STAGING_REVIEW]: stagingReview,
214
+ [VERB_HEALTH]: health,
212
215
  });