@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,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
  });
@@ -35,6 +35,29 @@ export async function mediaImagesGet(invocation) {
35
35
  return successResult(VERB_MEDIA_IMAGES_GET, siteId, { image });
36
36
  }
37
37
 
38
+ /**
39
+ * What a refused description write means to its caller (TR01372 shares it with `pages push
40
+ * --describe-missing-images`): a moved revision, an existing default under the condition, or text the server
41
+ * refused, each as its own code. Any other failure is returned as it is.
42
+ */
43
+ export function translateImageDescriptionRefusal(error) {
44
+ if (error instanceof ApiError && error.hasField("ExpectedRevision")) {
45
+ return new SiteAuthoringError("media.image_description_conflict",
46
+ "The description changed. Read it with 'media images get', reconcile the text, and supply that revision.",
47
+ { field: "expectedRevision", status: error.status });
48
+ }
49
+ if (error instanceof ApiError && error.hasField("OnlyIfMissing")) {
50
+ return new SiteAuthoringError("media.image_description_exists", "This image already has a default description; nothing changed.",
51
+ { field: "onlyIfMissing", status: error.status });
52
+ }
53
+ if (error instanceof ApiError && error.hasField("DefaultDescription")) {
54
+ return new SiteAuthoringError("media.image_description_invalid",
55
+ error.descriptionFor("DefaultDescription") ?? "Taproot refused the default description.",
56
+ { field: "defaultDescription", status: error.status });
57
+ }
58
+ return error;
59
+ }
60
+
38
61
  export async function mediaImagesDescribe(invocation) {
39
62
  const imageId = requireImageId(invocation.imageId);
40
63
  const body = imageDescriptionOptions(invocation);
@@ -45,21 +68,7 @@ export async function mediaImagesDescribe(invocation) {
45
68
  try {
46
69
  return await updateSiteImageDescription(client, siteId, imageId, body);
47
70
  } catch (error) {
48
- if (error instanceof ApiError && error.hasField("ExpectedRevision")) {
49
- throw new SiteAuthoringError("media.image_description_conflict",
50
- "The description changed. Read it with 'media images get', reconcile the text, and supply that revision.",
51
- { field: "expectedRevision", status: error.status });
52
- }
53
- if (error instanceof ApiError && error.hasField("OnlyIfMissing")) {
54
- throw new SiteAuthoringError("media.image_description_exists", "This image already has a default description; nothing changed.",
55
- { field: "onlyIfMissing", status: error.status });
56
- }
57
- if (error instanceof ApiError && error.hasField("DefaultDescription")) {
58
- throw new SiteAuthoringError("media.image_description_invalid",
59
- error.descriptionFor("DefaultDescription") ?? "Taproot refused the default description.",
60
- { field: "defaultDescription", status: error.status });
61
- }
62
- throw error;
71
+ throw translateImageDescriptionRefusal(error);
63
72
  }
64
73
  });
65
74
  onProgress(`Saved image ${image.imageId}, description revision ${image.descriptionRevision}. Deploy to update published usages.`);
@@ -1,3 +1,13 @@
1
+ import {
2
+ completedWritesForDescribe,
3
+ describedImagesBlock,
4
+ describeMissingImages,
5
+ evaluateImagePrecheck,
6
+ fitPrecheckToBudget,
7
+ placedImageIdsForPages,
8
+ planImageDescriptions,
9
+ readImageRecords,
10
+ } from "../site-health-precheck.js";
1
11
  import {
2
12
  createPage,
3
13
  getPage,
@@ -28,7 +38,7 @@ import { placedFormKeys, readFormIndex, withFormIds } from "../form-references.j
28
38
  import { workspaceFormKeys } from "../forms-workspace.js";
29
39
  import { ApiError } from "../transport.js";
30
40
  import { waitForProcessing } from "./media-upload.js";
31
- import { SiteAuthoringError } from "../errors.js";
41
+ import { outcomeUnknown, SiteAuthoringError } from "../errors.js";
32
42
  import { DESCRIPTION_MAXIMUM_LENGTH, DESCRIPTION_WARN_LENGTH, descriptionWarnings } from "../page-metadata.js";
33
43
  import { stableJson } from "../footer-draft-hash.js";
34
44
  import { CHECK_AREA, collectProblems, planStale, problemsOf, refuseProblems } from "../problems.js";
@@ -145,20 +155,7 @@ import {
145
155
  // of any length.
146
156
  const ITEMS_BYTES = 32 * 1024;
147
157
  const LIST_BYTES = 8 * 1024;
148
- // A send that ended this way may still have written the page.
149
- const OUTCOME_UNKNOWN_CODES = new Set([
150
- "transport.mutation_ambiguous",
151
- "transport.response_read",
152
- "transport.response_too_large",
153
- "transport.invalid_json",
154
- "api.page_contract",
155
- ]);
156
-
157
- export function outcomeUnknown(error) {
158
- // A cancelled retry of a write, and a server error on a write the transport
159
- // does not replay, leave the same question open.
160
- return OUTCOME_UNKNOWN_CODES.has(error.code) || error.ambiguousMutation === true || error.httpStatus >= 500;
161
- }
158
+ export { outcomeUnknown } from "../errors.js";
162
159
 
163
160
  /** The creates this workspace sent without hearing back, by page path. */
164
161
  function pendingCreates(manifest) {
@@ -1603,6 +1600,59 @@ export function plannedPageItem(page) {
1603
1600
  return { file: page.file, path: displayPagePath(page.pagePath), action: page.unchanged ? "unchanged" : page.action };
1604
1601
  }
1605
1602
 
1603
+ /**
1604
+ * The pre-staging image check (TR01371): one read of the site's records for every image the selected pages place,
1605
+ * taken once after the push's problems are refused and before anything is written. A failed read never fails the
1606
+ * push. `apply` already holds the plan, so it carries no check.
1607
+ */
1608
+ async function startImagePrecheck(invocation, client, siteId, planned) {
1609
+ if (invocation.plannedPages !== undefined) return undefined;
1610
+ const pages = placedImageIdsForPages(planned);
1611
+ return { pages, state: await readImageRecords(client, siteId, pages.flatMap((page) => page.imageIds)) };
1612
+ }
1613
+
1614
+ /**
1615
+ * The flagged push's report of what it would set (a dry run) or did set, with the skip reason of every other
1616
+ * candidate, plus the warning that a failed read left images unchecked. Absent without the flag, and under apply.
1617
+ */
1618
+ function describedImagesFor(precheck, plan, outcome, onProgress) {
1619
+ if (outcome === undefined) {
1620
+ outcome = {
1621
+ set: plan.filter((item) => item.description !== undefined).map((item) => ({ imageId: item.imageId, description: item.description })),
1622
+ skipped: plan.filter((item) => item.description === undefined).map((item) => ({ imageId: item.imageId, reason: item.reason })),
1623
+ };
1624
+ }
1625
+ const unread = outcome.skipped.filter((item) => item.reason === "not_read").length;
1626
+ if (precheck.state.reason !== undefined) {
1627
+ onProgress(
1628
+ `Warning: --describe-missing-images could not read every image record (${precheck.state.reason.code}); `
1629
+ + `${unread} image(s) were skipped as not_read.`,
1630
+ );
1631
+ }
1632
+ return describedImagesBlock(outcome, precheck.state);
1633
+ }
1634
+
1635
+ /**
1636
+ * Adds `siteHealthPrecheck` to the result, built from the records as they are now (so a later step that updates
1637
+ * them in place is reflected), printing its progress lines, and fitted to the output bound.
1638
+ */
1639
+ export function withImagePrecheck(result, precheck, onProgress) {
1640
+ if (precheck === undefined) return result;
1641
+ const block = evaluateImagePrecheck(precheck.state, precheck.pages, onProgress);
1642
+ // A block the result already carries (the describe flag's `describedImages`) shrinks with the new one, after it.
1643
+ const { describedImages, ...base } = result;
1644
+ const blocks = { siteHealthPrecheck: block, ...(describedImages === undefined ? {} : { describedImages }) };
1645
+ return {
1646
+ ...base,
1647
+ ...fitPrecheckToBudget(base, blocks, [
1648
+ "siteHealthPrecheck.notInSiteLibrary",
1649
+ "siteHealthPrecheck.imageFindings",
1650
+ "describedImages.set",
1651
+ "describedImages.skipped",
1652
+ ]),
1653
+ };
1654
+ }
1655
+
1606
1656
  export async function pagesPush(invocation) {
1607
1657
  const session = await openSession(invocation);
1608
1658
  const { client, config, siteId, now, onProgress } = session;
@@ -1725,8 +1775,12 @@ export async function pagesPush(invocation) {
1725
1775
  const warnings = { ...autolinkWarnings(sending, onProgress), ...descriptionWarnings(sending, onProgress) };
1726
1776
  if (dryRun) {
1727
1777
  refuseProblems(plan.problems, "pages push --dry-run found problems and sent nothing");
1778
+ const precheck = await startImagePrecheck(invocation, client, siteId, planned);
1779
+ const describedImages = invocation.describeMissingImages === true && precheck !== undefined
1780
+ ? describedImagesFor(precheck, planImageDescriptions(precheck.state, precheck.pages), undefined, onProgress)
1781
+ : undefined;
1728
1782
  onProgress("Dry run: nothing was sent.");
1729
- return successResult(VERB_PAGES_PUSH, siteId, {
1783
+ return withImagePrecheck(successResult(VERB_PAGES_PUSH, siteId, {
1730
1784
  dryRun: true,
1731
1785
  pages: {
1732
1786
  total: planned.length,
@@ -1739,9 +1793,13 @@ export async function pagesPush(invocation) {
1739
1793
  ...reportedList("items", planned.map(plannedPageItem), ITEMS_BYTES),
1740
1794
  },
1741
1795
  ...warnings,
1742
- });
1796
+ ...(describedImages === undefined ? {} : { describedImages }),
1797
+ }), precheck, onProgress);
1743
1798
  }
1744
1799
  refuseProblems(plan.problems, "pages push sent nothing");
1800
+ // Before the video posters are copied, so a poster this push places is outside the check; the stored report
1801
+ // after staging covers it.
1802
+ const precheck = await startImagePrecheck(invocation, client, siteId, planned);
1745
1803
  await copyVideoEmbedPosters(client, siteId, planned, { onProgress, now });
1746
1804
 
1747
1805
  // Phase two: send. The manifest is written back even if a later page fails,
@@ -1899,6 +1957,35 @@ export async function pagesPush(invocation) {
1899
1957
  if (manifestDirty) await writeManifest(config.workspaceDir, manifest);
1900
1958
  }
1901
1959
 
1960
+ // The flag sets missing image defaults only now, after the pages are saved, so a refused push sets nothing. A
1961
+ // failure here fails the command, and the pages saved above stay saved.
1962
+ let describedImages;
1963
+ if (invocation.describeMissingImages === true && precheck !== undefined) {
1964
+ const plan = planImageDescriptions(precheck.state, precheck.pages);
1965
+ let outcome;
1966
+ try {
1967
+ outcome = await describeMissingImages({ client, siteId, state: precheck.state, plan });
1968
+ } catch (error) {
1969
+ if (error?.describeOutcome !== undefined && typeof error.withCompletedWrites === "function") {
1970
+ error.withCompletedWrites(completedWritesForDescribe({
1971
+ outcome: error.describeOutcome,
1972
+ savedPages: applied.map((entry) => `page ${entry.path || "/"}: ${entry.action}`),
1973
+ }));
1974
+ }
1975
+ throw error;
1976
+ }
1977
+ describedImages = describedImagesFor(precheck, plan, outcome, onProgress);
1978
+ if (outcome.set.length > 0) {
1979
+ onProgress(`Set the default description of ${outcome.set.length} image(s). Deploy to update published usages.`);
1980
+ }
1981
+ }
1982
+ // With nothing set the next step is what it always was. After images were set, a page still holding a draft
1983
+ // (sent now, or sent earlier and not approved) is approved first: deploying would stage the older approved content.
1984
+ const imagesSet = describedImages !== undefined && describedImages.set.total > 0;
1985
+ const awaitingApproval = applied.length > 0 || (imagesSet && planned.some((page) =>
1986
+ page.unchanged && livePages.find((live) => live.pageId === page.pageId)?.hasDraft === true));
1987
+ const nextStep = awaitingApproval ? "approve" : imagesSet ? "deploy --staging" : undefined;
1988
+
1902
1989
  // Pages are authorless unless a source names an author, and an owner
1903
1990
  // otherwise finds the missing byline only after publishing (TR01196).
1904
1991
  const authorless = applied.filter((entry) => entry.action === "created" && entry.author === undefined);
@@ -1909,7 +1996,7 @@ export async function pagesPush(invocation) {
1909
1996
  + "<handle or email>', then push again; 'taproot-site authors list' shows who can be named.",
1910
1997
  );
1911
1998
  }
1912
- return successResult(VERB_PAGES_PUSH, siteId, {
1999
+ return withImagePrecheck(successResult(VERB_PAGES_PUSH, siteId, {
1913
2000
  pages: {
1914
2001
  total: planned.length,
1915
2002
  unchanged: planned.filter((page) => page.unchanged).length,
@@ -1935,7 +2022,8 @@ export async function pagesPush(invocation) {
1935
2022
  // `pages push` writes drafts. Nothing reaches an audience until `approve`
1936
2023
  // stages them and `deploy` publishes the site.
1937
2024
  // Nothing to approve when every page was unchanged and nothing was sent.
1938
- ...(applied.length > 0 ? { nextStep: "approve" } : {}),
1939
- });
2025
+ ...(nextStep === undefined ? {} : { nextStep }),
2026
+ ...(describedImages === undefined ? {} : { describedImages }),
2027
+ }), precheck, onProgress);
1940
2028
  });
1941
2029
  }
@@ -23,7 +23,8 @@ import {
23
23
  SURFACE_DOCS_PRESENTATION,
24
24
  VERB_STATUS,
25
25
  } from "../constants.js";
26
- import { boundedList, openSession, successResult } from "../session.js";
26
+ import { boundedByBytes, boundedList, openSession, successResult } from "../session.js";
27
+ import { readFailureCode } from "./health.js";
27
28
 
28
29
  /**
29
30
  * `status` — the platform authoring switch, CLI release, deployments,
@@ -33,6 +34,8 @@ const MAXIMUM_DEPLOYMENTS = 20;
33
34
  const MAXIMUM_FAILED_IMAGES = 50;
34
35
  const MAXIMUM_BLOCKERS = 50;
35
36
  const MAXIMUM_HEALTH_FINDINGS = 100;
37
+ // Each image finding lists its affected pages, so a full report would pass the result bound without this.
38
+ const MAXIMUM_HEALTH_IMAGE_BYTES = 16 * 1024;
36
39
 
37
40
  const PLATFORM_UNKNOWN_NOTE =
38
41
  "Taproot never reported the platform authoring switch on this run: either no sign-in token exchange happened "
@@ -127,6 +130,38 @@ const DOCS_SITE_NOT_COVERED_NOTE =
127
130
  "This is a managed Docs site: its pages come from the Docs artifact, so the image library and site-health "
128
131
  + "reads do not apply and were not made.";
129
132
 
133
+ /**
134
+ * The staged release's report as a summary (TR01363); `health --staging` has the findings and their fixes. A
135
+ * failed read never fails `status`, which still answers from production, so it is reported as unavailable.
136
+ */
137
+ async function summarizeStagedHealth(client, siteId, stagedDeploymentId, onProgress) {
138
+ if (stagedDeploymentId === undefined) {
139
+ return { available: false, reason: "No stored staging report exists yet; deploy --staging creates one." };
140
+ }
141
+ onProgress("Reading the stored staging health report.");
142
+ let staged;
143
+ try {
144
+ staged = await getSiteHealth(client, siteId, { deploymentId: stagedDeploymentId });
145
+ } catch (error) {
146
+ const reason = `The staged Site Health report could not be read (${readFailureCode(error)}).`;
147
+ onProgress(`Warning: ${reason}`);
148
+ return { available: false, reason };
149
+ }
150
+ if (!["complete", "incomplete"].includes(staged.status) || !staged.deploymentId) {
151
+ return { available: false, status: staged.status, reason: "The staged release has no complete supported assessment." };
152
+ }
153
+ return {
154
+ available: true,
155
+ status: staged.status,
156
+ deploymentId: staged.deploymentId,
157
+ checkedAt: staged.checkedAt,
158
+ errors: staged.errorCount,
159
+ warnings: staged.warningCount,
160
+ ...(staged.truncated ? { truncated: true } : {}),
161
+ details: "Run 'taproot-site health --staging' for the findings, the ones new since production, and their fixes.",
162
+ };
163
+ }
164
+
130
165
  export async function status(invocation) {
131
166
  const { client, siteId, surface, platform, release, onProgress } = await openSession(invocation);
132
167
  const presentationOnly = surface === SURFACE_DOCS_PRESENTATION;
@@ -167,6 +202,10 @@ export async function status(invocation) {
167
202
  health = await getSiteHealth(client, siteId);
168
203
  }
169
204
  const reportedFindings = boundedList(health.findings, MAXIMUM_HEALTH_FINDINGS);
205
+ const reportedImageFindings = boundedByBytes(health.images ?? [], MAXIMUM_HEALTH_IMAGE_BYTES);
206
+ const stagedSiteHealth = presentationOnly
207
+ ? { covered: false, reason: DOCS_SITE_NOT_COVERED_NOTE }
208
+ : await summarizeStagedHealth(client, siteId, health.stagedDeploymentId, onProgress);
170
209
 
171
210
  const byState = {};
172
211
  for (const image of images) {
@@ -244,10 +283,12 @@ export async function status(invocation) {
244
283
  warnings: health.warningCount,
245
284
  pages: health.pageCount,
246
285
  findings: reportedFindings.items,
247
- imageFindings: health.images,
286
+ imageFindings: reportedImageFindings.items,
287
+ ...(reportedImageFindings.truncated ? { imageFindingsTruncated: true } : {}),
248
288
  ...(reportedFindings.truncated || health.truncated ? { findingsTruncated: true } : {}),
249
289
  } : { reason: health.status === "not_checked" ? "Not checked yet; deploy the site to create a report." : "A complete supported deployment assessment is unavailable." }),
250
290
  },
291
+ stagedSiteHealth,
251
292
  });
252
293
  });
253
294
  }