@reddoorla/maintenance 0.61.0 → 0.62.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.
- package/dist/airtable-HHAWHBNM.js +9 -0
- package/dist/{announce-Q2DXP5OO.js → announce-N6VWO5QZ.js} +16 -6
- package/dist/announce-N6VWO5QZ.js.map +1 -0
- package/dist/{bump-deps-RYHQIKW4.js → bump-deps-2U6GIHM5.js} +2 -2
- package/dist/{chunk-D3LFQNJK.js → chunk-3HM4S422.js} +2 -2
- package/dist/{chunk-LMXIZITU.js → chunk-4REUHZAW.js} +40 -4
- package/dist/chunk-4REUHZAW.js.map +1 -0
- package/dist/chunk-5L3FPQIJ.js +92 -0
- package/dist/chunk-5L3FPQIJ.js.map +1 -0
- package/dist/{client-JA6QLEDW.js → chunk-6ZKM7OIJ.js} +5 -4
- package/dist/{chunk-L4ULXHIN.js → chunk-BLD6AYJO.js} +15 -1
- package/dist/chunk-BLD6AYJO.js.map +1 -0
- package/dist/{chunk-VDBENQUA.js → chunk-BMDBOPN3.js} +2 -2
- package/dist/{chunk-KC4HU7BC.js → chunk-DXRKWALS.js} +31 -6
- package/dist/chunk-DXRKWALS.js.map +1 -0
- package/dist/{chunk-HB7QPECR.js → chunk-KTPPKO2C.js} +6 -6
- package/dist/chunk-L5F664ZA.js +45 -0
- package/dist/chunk-L5F664ZA.js.map +1 -0
- package/dist/{chunk-TZN2G6FD.js → chunk-NPJFHBAX.js} +3 -3
- package/dist/{chunk-XB6T4ETK.js → chunk-OSRFDGQM.js} +21 -1
- package/dist/chunk-OSRFDGQM.js.map +1 -0
- package/dist/{chunk-6CSCLBAA.js → chunk-SAOCVNX7.js} +2 -2
- package/dist/{chunk-5PHCZ6L5.js → chunk-SS7BKOIX.js} +89 -2
- package/dist/chunk-SS7BKOIX.js.map +1 -0
- package/dist/{chunk-BWLUNY7L.js → chunk-U3MF6RCS.js} +40 -21
- package/dist/chunk-U3MF6RCS.js.map +1 -0
- package/dist/{chunk-HG5DTFNF.js → chunk-XKKTK6WA.js} +17 -1
- package/dist/chunk-XKKTK6WA.js.map +1 -0
- package/dist/{chunk-JNXCDUYB.js → chunk-XVR7UM6Z.js} +4 -4
- package/dist/{chunk-HPSGCDWY.js → chunk-YYUY2OVP.js} +2 -2
- package/dist/{chunk-TLZ4V2BE.js → chunk-ZEX2T6JH.js} +3 -2
- package/dist/{chunk-TLZ4V2BE.js.map → chunk-ZEX2T6JH.js.map} +1 -1
- package/dist/cli/bin.js +16 -15
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.d.ts +3 -2
- package/dist/cli/commands/audit.js +29 -8
- package/dist/cli/commands/audit.js.map +1 -1
- package/dist/client-GTMJTXBK.js +11 -0
- package/dist/{convert-to-pnpm-KNCXU6FM.js → convert-to-pnpm-JG3767ZQ.js} +2 -2
- package/dist/{db-AXKMRTVA.js → db-Y6BVTNH7.js} +3 -3
- package/dist/{digest-WAS3EJNC.js → digest-ABJROO4H.js} +3 -3
- package/dist/{github-signals-UL2BBS3Q.js → github-signals-XTJLKOXJ.js} +26 -5
- package/dist/github-signals-XTJLKOXJ.js.map +1 -0
- package/dist/index.d.ts +60 -3
- package/dist/index.js +86 -21
- package/dist/index.js.map +1 -1
- package/dist/{init-KD56UENX.js → init-DMAIKUQE.js} +8 -8
- package/dist/{launch-UWCI3JRM.js → launch-IBP23PNY.js} +10 -9
- package/dist/{launch-UWCI3JRM.js.map → launch-IBP23PNY.js.map} +1 -1
- package/dist/{lighthouse-airtable-N3KCBPVA.js → lighthouse-airtable-HTEW6BBT.js} +3 -3
- package/dist/migrate-BFOG2OCP.js +7 -0
- package/dist/{onboard-SCZ3UKZ2.js → onboard-TTIC3YZI.js} +2 -2
- package/dist/{orchestrate-D72PB6NG.js → orchestrate-I3KAJGFB.js} +7 -4
- package/dist/recipes/sync-configs.d.ts +1 -1
- package/dist/recipes/sync-configs.js +2 -2
- package/dist/{renovate-dispatch-NG5KUQKY.js → renovate-dispatch-QDDMTATD.js} +3 -3
- package/dist/{report-EPHXV2T2.js → report-PY6O3YMX.js} +6 -6
- package/dist/{self-updating-CFHXJSAX.js → self-updating-2RLUP4AA.js} +4 -4
- package/dist/{svelte-codemods-HNITLWQM.js → svelte-codemods-BPLKSVIA.js} +2 -2
- package/dist/{sync-configs-BZXBYKTI.js → sync-configs-VFRV3TJ4.js} +4 -4
- package/dist/{types-QG-QhCYh.d.ts → types-Dg4mHvyf.d.ts} +6 -1
- package/dist/{upgrade-6YDUELFA.js → upgrade-WCFD2TRN.js} +2 -2
- package/dist/{websites-IYP7IGLU.js → websites-HM2NMZMR.js} +2 -2
- package/dist/{write-audits-to-airtable-VDGHCZGQ.js → write-audits-to-airtable-QF26PCAR.js} +5 -4
- package/dist/write-audits-to-airtable-QF26PCAR.js.map +1 -0
- package/package.json +1 -1
- package/dist/airtable-YZ6VMSQZ.js +0 -9
- package/dist/announce-Q2DXP5OO.js.map +0 -1
- package/dist/chunk-5PHCZ6L5.js.map +0 -1
- package/dist/chunk-BWLUNY7L.js.map +0 -1
- package/dist/chunk-HG5DTFNF.js.map +0 -1
- package/dist/chunk-KC4HU7BC.js.map +0 -1
- package/dist/chunk-L4ULXHIN.js.map +0 -1
- package/dist/chunk-LMXIZITU.js.map +0 -1
- package/dist/chunk-XB6T4ETK.js.map +0 -1
- package/dist/github-signals-UL2BBS3Q.js.map +0 -1
- package/dist/migrate-P2LS4WXI.js +0 -7
- /package/dist/{airtable-YZ6VMSQZ.js.map → airtable-HHAWHBNM.js.map} +0 -0
- /package/dist/{bump-deps-RYHQIKW4.js.map → bump-deps-2U6GIHM5.js.map} +0 -0
- /package/dist/{chunk-D3LFQNJK.js.map → chunk-3HM4S422.js.map} +0 -0
- /package/dist/{client-JA6QLEDW.js.map → chunk-6ZKM7OIJ.js.map} +0 -0
- /package/dist/{chunk-VDBENQUA.js.map → chunk-BMDBOPN3.js.map} +0 -0
- /package/dist/{chunk-HB7QPECR.js.map → chunk-KTPPKO2C.js.map} +0 -0
- /package/dist/{chunk-TZN2G6FD.js.map → chunk-NPJFHBAX.js.map} +0 -0
- /package/dist/{chunk-6CSCLBAA.js.map → chunk-SAOCVNX7.js.map} +0 -0
- /package/dist/{chunk-JNXCDUYB.js.map → chunk-XVR7UM6Z.js.map} +0 -0
- /package/dist/{chunk-HPSGCDWY.js.map → chunk-YYUY2OVP.js.map} +0 -0
- /package/dist/{lighthouse-airtable-N3KCBPVA.js.map → client-GTMJTXBK.js.map} +0 -0
- /package/dist/{convert-to-pnpm-KNCXU6FM.js.map → convert-to-pnpm-JG3767ZQ.js.map} +0 -0
- /package/dist/{db-AXKMRTVA.js.map → db-Y6BVTNH7.js.map} +0 -0
- /package/dist/{digest-WAS3EJNC.js.map → digest-ABJROO4H.js.map} +0 -0
- /package/dist/{init-KD56UENX.js.map → init-DMAIKUQE.js.map} +0 -0
- /package/dist/{migrate-P2LS4WXI.js.map → lighthouse-airtable-HTEW6BBT.js.map} +0 -0
- /package/dist/{orchestrate-D72PB6NG.js.map → migrate-BFOG2OCP.js.map} +0 -0
- /package/dist/{onboard-SCZ3UKZ2.js.map → onboard-TTIC3YZI.js.map} +0 -0
- /package/dist/{websites-IYP7IGLU.js.map → orchestrate-I3KAJGFB.js.map} +0 -0
- /package/dist/{renovate-dispatch-NG5KUQKY.js.map → renovate-dispatch-QDDMTATD.js.map} +0 -0
- /package/dist/{report-EPHXV2T2.js.map → report-PY6O3YMX.js.map} +0 -0
- /package/dist/{self-updating-CFHXJSAX.js.map → self-updating-2RLUP4AA.js.map} +0 -0
- /package/dist/{svelte-codemods-HNITLWQM.js.map → svelte-codemods-BPLKSVIA.js.map} +0 -0
- /package/dist/{sync-configs-BZXBYKTI.js.map → sync-configs-VFRV3TJ4.js.map} +0 -0
- /package/dist/{upgrade-6YDUELFA.js.map → upgrade-WCFD2TRN.js.map} +0 -0
- /package/dist/{write-audits-to-airtable-VDGHCZGQ.js.map → websites-HM2NMZMR.js.map} +0 -0
|
@@ -1,24 +1,27 @@
|
|
|
1
|
-
import {
|
|
2
|
-
isIdempotencyConflict
|
|
3
|
-
} from "./chunk-OGGRFBL4.js";
|
|
4
1
|
import {
|
|
5
2
|
announcementSiteExtras,
|
|
6
3
|
fetchAttachmentBytes,
|
|
7
4
|
loadBundledImages,
|
|
8
5
|
renderReportHtml,
|
|
9
6
|
resolveCopy
|
|
10
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-U3MF6RCS.js";
|
|
8
|
+
import {
|
|
9
|
+
isIdempotencyConflict
|
|
10
|
+
} from "./chunk-OGGRFBL4.js";
|
|
11
11
|
import {
|
|
12
12
|
checklistFor,
|
|
13
13
|
isChecklistComplete,
|
|
14
14
|
listSendableReports,
|
|
15
15
|
stampSent
|
|
16
16
|
} from "./chunk-OCS7SZUZ.js";
|
|
17
|
+
import {
|
|
18
|
+
recordFleetEventsBestEffort
|
|
19
|
+
} from "./chunk-L5F664ZA.js";
|
|
17
20
|
import {
|
|
18
21
|
listWebsites,
|
|
19
22
|
siteSlug,
|
|
20
23
|
updateLaunched
|
|
21
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-BLD6AYJO.js";
|
|
22
25
|
import {
|
|
23
26
|
openBase,
|
|
24
27
|
readAirtableConfig
|
|
@@ -86,6 +89,12 @@ var MONTHS = [
|
|
|
86
89
|
function monthYear(d) {
|
|
87
90
|
return `${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
|
|
88
91
|
}
|
|
92
|
+
function windowDays(start, end) {
|
|
93
|
+
if (!start || !end) return void 0;
|
|
94
|
+
const ms = new Date(end).getTime() - new Date(start).getTime();
|
|
95
|
+
if (!Number.isFinite(ms) || ms <= 0) return void 0;
|
|
96
|
+
return Math.round(ms / (24 * 60 * 60 * 1e3));
|
|
97
|
+
}
|
|
89
98
|
function toInlineAttachment(a) {
|
|
90
99
|
return {
|
|
91
100
|
filename: a.filename,
|
|
@@ -117,6 +126,20 @@ async function sendApprovedReports(options = {}) {
|
|
|
117
126
|
try {
|
|
118
127
|
await updateLaunched(base, site.id, (/* @__PURE__ */ new Date()).toISOString());
|
|
119
128
|
lines.push(` \u21B3 launched: ${site.name} flipped to maintenance`);
|
|
129
|
+
await recordFleetEventsBestEffort(
|
|
130
|
+
[
|
|
131
|
+
{
|
|
132
|
+
id: `site_launched:${site.id}`,
|
|
133
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
134
|
+
type: "site_launched",
|
|
135
|
+
siteId: site.id,
|
|
136
|
+
siteName: site.name,
|
|
137
|
+
summary: "launched \u2014 now in maintenance",
|
|
138
|
+
data: null
|
|
139
|
+
}
|
|
140
|
+
],
|
|
141
|
+
/* @__PURE__ */ new Date()
|
|
142
|
+
);
|
|
120
143
|
} catch (e) {
|
|
121
144
|
lines.push(` \u26A0 launch flip failed for ${site.name}: ${e.message}`);
|
|
122
145
|
}
|
|
@@ -174,6 +197,7 @@ async function sendOne(client, base, site, report) {
|
|
|
174
197
|
const bundled = await loadBundledImages();
|
|
175
198
|
const slug = siteSlug(site.name);
|
|
176
199
|
const cidName = `${slug}-header`;
|
|
200
|
+
const gaPeriodDays = report.reportType === "Announcement" ? 30 : windowDays(report.periodStart, report.periodEnd);
|
|
177
201
|
const { html } = await renderReportHtml({
|
|
178
202
|
siteName: site.name,
|
|
179
203
|
siteUrl: site.url,
|
|
@@ -182,6 +206,7 @@ async function sendOne(client, base, site, report) {
|
|
|
182
206
|
lighthouse: report.lighthouse,
|
|
183
207
|
gaUsersCurrent: report.gaUsersCurrent ?? void 0,
|
|
184
208
|
gaUsersPrevious: report.gaUsersPrevious ?? void 0,
|
|
209
|
+
gaPeriodDays,
|
|
185
210
|
searchPosition: report.searchFoundPage1 && report.searchPosition !== null ? report.searchPosition : void 0,
|
|
186
211
|
lastTestedDate: report.lastTestedDate ? new Date(report.lastTestedDate) : null,
|
|
187
212
|
commentary: report.commentary,
|
|
@@ -276,4 +301,4 @@ export {
|
|
|
276
301
|
parseAddresses,
|
|
277
302
|
isProbablyEmail
|
|
278
303
|
};
|
|
279
|
-
//# sourceMappingURL=chunk-
|
|
304
|
+
//# sourceMappingURL=chunk-DXRKWALS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reports/maintenance-email/header-image.ts","../src/reports/send/orchestrate.ts"],"sourcesContent":["import sharp from \"sharp\";\n\nexport type PreparedHeaderImage = {\n /** Resized JPEG bytes to attach inline (CID) in place of the Airtable original. */\n bytes: Uint8Array;\n /** Always \"image/jpeg\" — we re-encode for predictable size and a flat white background. */\n contentType: string;\n /** CSS display width in px (≤ requested, never wider than the source has pixels for). */\n displayWidth: number;\n /** CSS display height in px, source aspect ratio preserved (no distortion). */\n displayHeight: number;\n /** Dominant-color hex (e.g. \"#cfc3a8\"), used as the loading/blocked placeholder box. */\n placeholderColor: string;\n};\n\nexport type PrepareHeaderImageOptions = {\n /** Intended CSS display width. The email body is 600px, so that's the default. */\n displayWidth?: number;\n};\n\nconst DEFAULT_DISPLAY_WIDTH = 600;\n/** Encode the source at 2× display width so it stays crisp on retina screens. */\nconst RETINA_SCALE = 2;\n/** Quality is for *resized* pixels — at 1200px the texture/text read as sharp; bytes are tiny. */\nconst JPEG_QUALITY = 82;\n\nfunction channelToHex(value: number): string {\n return Math.max(0, Math.min(255, Math.round(value)))\n .toString(16)\n .padStart(2, \"0\");\n}\n\n/**\n * Downscale an oversized header image for email: 2× the display width (retina) at most,\n * never upscaled, re-encoded as JPEG on a flat white background. Also reports the display\n * dimensions (so the template can reserve the box and stop reflow) and a dominant color\n * (so the reserved box shows a matched placeholder while the image loads).\n *\n * Root cause this addresses: Airtable headers can be multi-MB / 2400px+ while the email\n * renders them at ~600px — shipping ~16× more pixels than the display can use.\n */\nexport async function prepareHeaderImage(\n bytes: Uint8Array,\n options: PrepareHeaderImageOptions = {},\n): Promise<PreparedHeaderImage> {\n const requestedDisplayWidth = options.displayWidth ?? DEFAULT_DISPLAY_WIDTH;\n const input = Buffer.from(bytes);\n\n const meta = await sharp(input).metadata();\n const origWidth = meta.width;\n const origHeight = meta.height;\n if (!origWidth || !origHeight) {\n throw new Error(\"prepareHeaderImage: could not read source image dimensions\");\n }\n\n // Never claim a wider display than the source can fill at 1×.\n const displayWidth = Math.min(requestedDisplayWidth, origWidth);\n const displayHeight = Math.round((displayWidth * origHeight) / origWidth);\n\n // Encode at 2× display for retina, but never enlarge a smaller original.\n const targetSourceWidth = Math.min(origWidth, displayWidth * RETINA_SCALE);\n\n const out = await sharp(input)\n .resize({ width: targetSourceWidth, withoutEnlargement: true })\n .flatten({ background: \"#ffffff\" })\n .jpeg({ quality: JPEG_QUALITY })\n .toBuffer();\n\n const { dominant } = await sharp(out).stats();\n const placeholderColor = `#${channelToHex(dominant.r)}${channelToHex(dominant.g)}${channelToHex(dominant.b)}`;\n\n return {\n bytes: new Uint8Array(out),\n contentType: \"image/jpeg\",\n displayWidth,\n displayHeight,\n placeholderColor,\n };\n}\n","import { openBase, readAirtableConfig } from \"../airtable/client.js\";\nimport { listSendableReports, stampSent } from \"../airtable/reports.js\";\nimport { listWebsites, siteSlug, updateLaunched } from \"../airtable/websites.js\";\nimport type { WebsiteRow } from \"../airtable/websites.js\";\nimport type { ReportRow } from \"../airtable/reports.js\";\nimport { fetchAttachmentBytes } from \"../airtable/attachments.js\";\nimport { renderReportHtml } from \"../render.js\";\nimport { resolveCopy } from \"../copy.js\";\nimport { announcementSiteExtras } from \"../announcement-email/template.js\";\nimport { loadBundledImages } from \"../maintenance-email/assets/index.js\";\nimport { prepareHeaderImage } from \"../maintenance-email/header-image.js\";\nimport { defaultResendClient, type ResendClient, type ResendSendInput } from \"./resend.js\";\nimport { isIdempotencyConflict } from \"./idempotency.js\";\nimport { checklistFor, isChecklistComplete } from \"../checklist.js\";\nimport { recordFleetEventsBestEffort } from \"../../audits/fleet-events-writer.js\";\n\nconst FROM_ADDRESS = \"Reddoor Reports <reports@reddoorla.com>\";\nconst REPLY_TO = \"info@reddoorla.com\";\n\n/** Operations inbox CC'd on every outgoing report so there's always an internal\n * copy on file alongside the client recipients. */\nexport const GLOBAL_REPORT_CC = \"info@reddoorla.com\";\n\n/**\n * Append {@link GLOBAL_REPORT_CC} to a site's per-site CC list. The per-site CC is\n * passed through unchanged (preserving prior behavior); the global address is added\n * only when it isn't already present in the CC or To lists (case-insensitive), so a\n * report is never double-addressed to the ops inbox. Returns the final CC list (may\n * be empty if the global address is already the sole To recipient — the caller omits\n * an empty CC).\n */\nexport function withGlobalCc(perSiteCc: string[] | null, to: string[]): string[] {\n const cc = [...(perSiteCc ?? [])];\n const present = new Set([...cc, ...to].map((a) => a.toLowerCase()));\n if (!present.has(GLOBAL_REPORT_CC.toLowerCase())) cc.push(GLOBAL_REPORT_CC);\n return cc;\n}\n\nconst MONTHS = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\n/** \"May 2026\" — UTC month/year, consistent with the rest of the reports pipeline's dates. */\nfunction monthYear(d: Date): string {\n return `${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;\n}\n\n/** Whole days spanned by an ISO period window, or undefined when either bound is missing or the\n * span isn't positive. Drives the analytics trend's \"vs the previous N days\" label. */\nfunction windowDays(start: string | null, end: string | null): number | undefined {\n if (!start || !end) return undefined;\n const ms = new Date(end).getTime() - new Date(start).getTime();\n if (!Number.isFinite(ms) || ms <= 0) return undefined;\n return Math.round(ms / (24 * 60 * 60 * 1000));\n}\n\ntype InlineAttachment = NonNullable<ResendSendInput[\"attachments\"]>[number];\n\n/** Build a Resend inline (CID-referenced) attachment from raw bytes — the header\n * image and both bundled images share this exact shape. */\nfunction toInlineAttachment(a: {\n bytes: Uint8Array;\n filename: string;\n contentType: string;\n cid: string;\n}): InlineAttachment {\n return {\n filename: a.filename,\n content: Buffer.from(a.bytes).toString(\"base64\"),\n contentType: a.contentType,\n inlineContentId: a.cid,\n };\n}\n\nexport type OrchestrateOptions = {\n resend?: ResendClient;\n};\n\nexport async function sendApprovedReports(\n options: OrchestrateOptions = {},\n): Promise<{ output: string; code: number }> {\n const base = openBase(readAirtableConfig());\n const client = options.resend ?? defaultResendClient();\n\n const sendable = await listSendableReports(base);\n if (sendable.length === 0) return { output: \"No reports ready to send.\", code: 0 };\n\n const websites = await listWebsites(base);\n const sites = new Map(websites.map((w) => [w.id, w]));\n\n const lines: string[] = [];\n let anyFailed = false;\n for (const report of sendable) {\n const site = sites.get(report.siteId);\n if (!site) {\n lines.push(`✗ ${report.reportId} — Site row not found for id=${report.siteId}`);\n anyFailed = true;\n continue;\n }\n try {\n const messageId = await sendOne(client, base, site, report);\n lines.push(`✓ sent: ${report.reportId} (${messageId})`);\n if (report.reportType === \"Launch\") {\n try {\n await updateLaunched(base, site.id, new Date().toISOString());\n lines.push(` ↳ launched: ${site.name} flipped to maintenance`);\n await recordFleetEventsBestEffort(\n [\n {\n id: `site_launched:${site.id}`,\n ts: new Date().toISOString(),\n type: \"site_launched\",\n siteId: site.id,\n siteName: site.name,\n summary: \"launched — now in maintenance\",\n data: null,\n },\n ],\n new Date(),\n );\n } catch (e) {\n lines.push(` ⚠ launch flip failed for ${site.name}: ${(e as Error).message}`);\n }\n }\n } catch (e) {\n lines.push(`✗ ${report.reportId} — ${(e as Error).message}`);\n anyFailed = true;\n }\n }\n return { output: lines.join(\"\\n\"), code: anyFailed ? 1 : 0 };\n}\n\nasync function sendOne(\n client: ResendClient,\n base: ReturnType<typeof openBase>,\n site: WebsiteRow,\n report: ReportRow,\n): Promise<string> {\n // Hard checklist gate: a Maintenance/Testing report whose operator checklist isn't\n // fully checked must never go out — even if \"Approved to send\" was ticked directly in\n // Airtable, bypassing the dashboard's approve gate. Throw so the report is skipped and\n // `Sent at` stays null (at-least-once retry preserved), exactly like the other sendOne\n // guards. Launch/Announcement have an empty checklist → vacuously complete, never gated.\n if (!isChecklistComplete(report)) {\n const items = checklistFor(report.reportType);\n const done = items.filter((i) => report.checklist[i.field] === true).length;\n throw new Error(\n `Report ${report.reportId} checklist incomplete — ${done}/${items.length} items checked`,\n );\n }\n if (!site.headerImage) {\n throw new Error(`Site '${site.name}' has no Header image set on the Websites row`);\n }\n if (!report.lighthouse) {\n throw new Error(\n `Report ${report.reportId} has no Lighthouse scores — all four cells ` +\n `(Lighthouse — Performance / Accessibility / Best Practices / SEO) must be numeric ` +\n `on the Reports row; one non-numeric or blank cell nulls all four`,\n );\n }\n\n // Resolve + validate recipients BEFORE the expensive work (header fetch + sharp\n // downscale + full MJML render). A misconfigured-recipients site is a guaranteed\n // failure, so fail fast here rather than after burning that work. Same checks +\n // messages as before — only the position moved.\n const explicitTo = parseAddresses(site.reportRecipientsTo);\n // Run pointOfContact through the parser too — operators sometimes paste\n // \"a@x, b@y\" into that single-line field.\n const fallbackTo = parseAddresses(site.pointOfContact);\n const to = explicitTo ?? fallbackTo ?? [];\n if (to.length === 0) {\n throw new Error(\n `Site '${site.name}' has no recipients (Report recipients (To) AND point of contact are both empty)`,\n );\n }\n for (const addr of to) {\n if (!isProbablyEmail(addr)) {\n throw new Error(\n `Site '${site.name}' recipient is malformed: ${addr} — use a bare address only ` +\n `(no \\`Name <addr>\\` display-name syntax); fix Report recipients (To) or point of contact in Airtable`,\n );\n }\n }\n const cc = parseAddresses(site.reportRecipientsCc);\n if (cc) {\n for (const addr of cc) {\n if (!isProbablyEmail(addr)) {\n throw new Error(\n `Site '${site.name}' CC is malformed: ${addr} — fix Report recipients (CC) in Airtable`,\n );\n }\n }\n }\n\n const original = await fetchAttachmentBytes(site.headerImage.url);\n // Downscale the (often multi-MB / 2400px+) Airtable header to email display size, and get\n // back display dims + a placeholder color so the template can reserve the box.\n const header = await prepareHeaderImage(original.bytes);\n const bundled = await loadBundledImages();\n\n const slug = siteSlug(site.name);\n const cidName = `${slug}-header`;\n // GA window length (days) for the analytics trend's \"vs the previous N days\" label.\n // Announcements report on a fixed 30-day window — the announce recipe collapses the stored\n // period to `now`, so it can't be derived from the row; every other report derives it from\n // the stored period window.\n const gaPeriodDays =\n report.reportType === \"Announcement\" ? 30 : windowDays(report.periodStart, report.periodEnd);\n const { html } = await renderReportHtml({\n siteName: site.name,\n siteUrl: site.url,\n reportType: report.reportType,\n completedOn: report.completedOn ? new Date(report.completedOn) : new Date(),\n lighthouse: report.lighthouse,\n gaUsersCurrent: report.gaUsersCurrent ?? undefined,\n gaUsersPrevious: report.gaUsersPrevious ?? undefined,\n gaPeriodDays,\n searchPosition:\n report.searchFoundPage1 && report.searchPosition !== null ? report.searchPosition : undefined,\n lastTestedDate: report.lastTestedDate ? new Date(report.lastTestedDate) : null,\n commentary: report.commentary,\n copy: resolveCopy(site),\n headerImageCid: cidName,\n headerWidth: header.displayWidth,\n headerHeight: header.displayHeight,\n headerBgColor: header.placeholderColor,\n // Announcement-only: re-derive cadence + improvements from the site row so the SENT email\n // keeps its cadence copy + improvement callouts. Without this the send-time re-render drops\n // them entirely (they're not stored on the Reports row). Ignored by the other templates.\n ...(report.reportType === \"Announcement\" ? announcementSiteExtras(site) : {}),\n });\n\n const reportDate = report.completedOn ? new Date(report.completedOn) : new Date();\n const subject =\n report.subjectOverride ?? `${site.name} — ${monthYear(reportDate)} ${report.reportType} Report`;\n\n // Inline attachments: the per-site header (every template renders it) plus only the bundled\n // images the rendered HTML actually references. The green check (cid:rd-check-png) appears in\n // every report's checklist/score rows EXCEPT Launch; the blurred-tests image\n // (cid:rd-blurred-tests-jpg) appears ONLY in the Maintenance email. Attaching a bundled image\n // the template doesn't reference leaves a dangling inline part that some mail clients surface as\n // a stray downloadable attachment — so gate each on its cid actually appearing in `html`. This\n // self-corrects if a template's image usage changes; there's no per-report-type list to keep in\n // sync. Self-contained inline (no external CDN, no image-blocked broken icons in webmail).\n const attachments: InlineAttachment[] = [\n toInlineAttachment({\n bytes: header.bytes,\n filename: `${cidName}.jpg`,\n contentType: header.contentType,\n cid: cidName,\n }),\n ];\n for (const img of [bundled.check, bundled.blurred]) {\n if (html.includes(`cid:${img.cid}`)) {\n attachments.push(\n toInlineAttachment({\n bytes: img.bytes,\n filename: img.filename,\n contentType: img.contentType,\n cid: img.cid,\n }),\n );\n }\n }\n\n const payload: Parameters<ResendClient[\"send\"]>[0] = {\n from: FROM_ADDRESS,\n to,\n replyTo: REPLY_TO,\n subject,\n html,\n attachments,\n // Stable across retries of the same row — if Airtable stamping fails after a\n // successful Resend, the next --send-ready replays with the same key and\n // Resend returns the original message id rather than sending a duplicate.\n idempotencyKey: `report:${report.id}`,\n };\n // Always CC the ops inbox (info@reddoorla.com), in addition to any per-site CC.\n const finalCc = withGlobalCc(cc, to);\n if (finalCc.length > 0) payload.cc = finalCc;\n\n let result: Awaited<ReturnType<ResendClient[\"send\"]>>;\n try {\n result = await client.send(payload);\n } catch (err) {\n // The send path is at-least-once: client.send succeeds → stampSent writes\n // `Sent at` (the ONLY thing that removes the row from listSendableReports). If\n // stampSent threw on a PRIOR run (an Airtable blip), `Sent at` stayed null and\n // the row replays here. By replay time the rendered body has usually changed\n // (operator Commentary edit, `report --due` rewrote scores, or the header\n // re-encodes non-deterministically), so Resend rejects the same-key\n // (`report:<id>`) / different-body re-send with a 409 (`invalid_idempotent_request`).\n //\n // That 409 means the email ALREADY WENT OUT under this key on the prior run.\n // Do NOT re-throw and do NOT re-send (re-throwing leaves the row unstamped, and\n // after the 24h key TTL a SECOND real email would go out). Instead stamp the row\n // so it stops replaying, then return success so the caller runs the Launch flip —\n // which self-heals a launch that sent-but-never-flipped on the prior run.\n //\n // Any OTHER error (real network/Resend failure) re-throws, exactly as before, so\n // a genuine failure still fails loudly and the row replays next run.\n if (isIdempotencyConflict(err)) {\n // Stamp `Sent at` ONLY — the original send's messageId is unrecoverable on\n // the 409 path, so we leave `Resend message ID` null rather than writing a\n // sentinel that would masquerade as a real id and orphan webhook lookups.\n // Still return the sentinel string so the caller logs the already-sent path\n // and runs the Launch flip.\n await stampSent(base, report.id, new Date(), null);\n console.log(`↻ already sent (idempotency conflict), stamped: ${report.reportId}`);\n return \"idempotent-conflict\";\n }\n throw err;\n }\n await stampSent(base, report.id, new Date(), result.messageId);\n return result.messageId;\n}\n\n/**\n * Split a comma/newline-separated address field into a clean array.\n * Lowercases (case-insensitive dedupe) and removes empty entries. Returns\n * null if nothing survives. Does NOT understand `Display Name <email>` —\n * operators should put a bare address in the Airtable field, or use multiple\n * lines if needing multiple recipients.\n */\nexport function parseAddresses(field: string | null): string[] | null {\n if (!field) return null;\n const seen = new Set<string>();\n const list: string[] = [];\n for (const raw of field.split(/[,\\n]/)) {\n const trimmed = raw.trim().toLowerCase();\n if (!trimmed) continue;\n if (seen.has(trimmed)) continue;\n seen.add(trimmed);\n list.push(trimmed);\n }\n return list.length > 0 ? list : null;\n}\n\n/**\n * Cheap email shape check — must contain exactly one @, with non-empty\n * local and domain parts and at least one dot in the domain. We're not\n * trying to be a full RFC validator; we're trying to catch operator\n * mistakes like \"ops at acme dot com\" or a missing @ before they 422\n * at Resend.\n */\nexport function isProbablyEmail(s: string): boolean {\n const at = s.indexOf(\"@\");\n if (at < 1 || at !== s.lastIndexOf(\"@\")) return false;\n const local = s.slice(0, at);\n const domain = s.slice(at + 1);\n if (!local || !domain) return false;\n if (!domain.includes(\".\")) return false;\n if (/\\s/.test(s)) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,WAAW;AAoBlB,IAAM,wBAAwB;AAE9B,IAAM,eAAe;AAErB,IAAM,eAAe;AAErB,SAAS,aAAa,OAAuB;AAC3C,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,EAChD,SAAS,EAAE,EACX,SAAS,GAAG,GAAG;AACpB;AAWA,eAAsB,mBACpB,OACA,UAAqC,CAAC,GACR;AAC9B,QAAM,wBAAwB,QAAQ,gBAAgB;AACtD,QAAM,QAAQ,OAAO,KAAK,KAAK;AAE/B,QAAM,OAAO,MAAM,MAAM,KAAK,EAAE,SAAS;AACzC,QAAM,Y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
|
svelteCodemods
|
|
3
6
|
} from "./chunk-FUD4I2ZW.js";
|
|
4
7
|
import {
|
|
5
8
|
onboard
|
|
6
9
|
} from "./chunk-ZYBOT5PM.js";
|
|
7
|
-
import {
|
|
8
|
-
convertToPnpm
|
|
9
|
-
} from "./chunk-2X322ZES.js";
|
|
10
10
|
import {
|
|
11
11
|
syncConfigs
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-XVR7UM6Z.js";
|
|
13
13
|
import {
|
|
14
14
|
withRecipe
|
|
15
15
|
} from "./chunk-XKOZUVK2.js";
|
|
16
16
|
import {
|
|
17
17
|
runAudits
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-SS7BKOIX.js";
|
|
19
19
|
import {
|
|
20
20
|
siteLabel
|
|
21
21
|
} from "./chunk-XXTZBPUY.js";
|
|
@@ -135,4 +135,4 @@ export {
|
|
|
135
135
|
DEFAULT_INIT_STEPS,
|
|
136
136
|
init
|
|
137
137
|
};
|
|
138
|
-
//# sourceMappingURL=chunk-
|
|
138
|
+
//# sourceMappingURL=chunk-KTPPKO2C.js.map
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
openDb,
|
|
3
|
+
readDbConfig
|
|
4
|
+
} from "./chunk-6ZKM7OIJ.js";
|
|
5
|
+
|
|
6
|
+
// src/db/fleet-events.ts
|
|
7
|
+
async function recordFleetEvent(db, e) {
|
|
8
|
+
await db.insertInto("fleet_events").values({
|
|
9
|
+
id: e.id,
|
|
10
|
+
ts: e.ts,
|
|
11
|
+
type: e.type,
|
|
12
|
+
site_id: e.siteId,
|
|
13
|
+
site_name: e.siteName,
|
|
14
|
+
summary: e.summary,
|
|
15
|
+
data: e.data == null ? null : JSON.stringify(e.data),
|
|
16
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
17
|
+
}).onConflict((oc) => oc.column("id").doNothing()).execute();
|
|
18
|
+
}
|
|
19
|
+
async function pruneFleetEvents(db, beforeIso) {
|
|
20
|
+
await db.deleteFrom("fleet_events").where("ts", "<", beforeIso).execute();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/audits/fleet-events-writer.ts
|
|
24
|
+
var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
25
|
+
async function recordFleetEventsBestEffort(events, now, open = () => openDb(readDbConfig())) {
|
|
26
|
+
if (events.length === 0) return;
|
|
27
|
+
let db;
|
|
28
|
+
try {
|
|
29
|
+
db = await open();
|
|
30
|
+
} catch (e) {
|
|
31
|
+
console.error(`[fleet-events] skipped ${events.length} event(s): no libSQL (${String(e)})`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
for (const e of events) await recordFleetEvent(db, e);
|
|
36
|
+
await pruneFleetEvents(db, new Date(now.getTime() - RETENTION_MS).toISOString());
|
|
37
|
+
} catch (e) {
|
|
38
|
+
console.error(`[fleet-events] write failed: ${String(e)}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export {
|
|
43
|
+
recordFleetEventsBestEffort
|
|
44
|
+
};
|
|
45
|
+
//# sourceMappingURL=chunk-L5F664ZA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db/fleet-events.ts","../src/audits/fleet-events-writer.ts"],"sourcesContent":["import type { Selectable } from \"kysely\";\nimport type { Db } from \"./client.js\";\nimport type { FleetEventsTable } from \"./schema.js\";\n\nexport type FleetEventType =\n | \"pr_automerged\"\n | \"vuln_cleared\"\n | \"ci_recovered\"\n | \"site_launched\"\n | \"fleet_swept\"\n | \"cert_renewed\";\n\n/** One recorded fleet activity event. `id` is deterministic (see the detectors)\n * so re-runs INSERT OR IGNORE without duplicating. `siteId`/`siteName` are null\n * for fleet-wide rollups; `data` is optional structured detail (e.g. the PR url). */\nexport type FleetEvent = {\n id: string;\n ts: string;\n type: FleetEventType;\n siteId: string | null;\n siteName: string | null;\n summary: string;\n data: unknown | null;\n};\n\n/** Tolerant JSON parse for the stored `data` column — a malformed value (should\n * never happen, we wrote it) degrades to null rather than throwing the read. */\nfunction parseData(raw: string | null): unknown | null {\n if (raw === null) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction rowToEvent(r: Selectable<FleetEventsTable>): FleetEvent {\n return {\n id: r.id,\n ts: r.ts,\n type: r.type as FleetEventType,\n siteId: r.site_id,\n siteName: r.site_name,\n summary: r.summary,\n data: parseData(r.data),\n };\n}\n\n/** Idempotent append: INSERT OR IGNORE on the deterministic primary key, so an\n * overlapping/re-run sweep never duplicates an event. The first write wins. */\nexport async function recordFleetEvent(db: Db, e: FleetEvent): Promise<void> {\n await db\n .insertInto(\"fleet_events\")\n .values({\n id: e.id,\n ts: e.ts,\n type: e.type,\n site_id: e.siteId,\n site_name: e.siteName,\n summary: e.summary,\n data: e.data == null ? null : JSON.stringify(e.data),\n created_at: new Date().toISOString(),\n })\n .onConflict((oc) => oc.column(\"id\").doNothing())\n .execute();\n}\n\n/** Recent events at/after `sinceIso`, newest-first, capped at `limit`. */\nexport async function listFleetEvents(\n db: Db,\n opts: { sinceIso: string; limit: number },\n): Promise<FleetEvent[]> {\n const rows = await db\n .selectFrom(\"fleet_events\")\n .selectAll()\n .where(\"ts\", \">=\", opts.sinceIso)\n .orderBy(\"ts\", \"desc\")\n .limit(opts.limit)\n .execute();\n return rows.map(rowToEvent);\n}\n\n/** Retention prune: delete events strictly older than `beforeIso`. */\nexport async function pruneFleetEvents(db: Db, beforeIso: string): Promise<void> {\n await db.deleteFrom(\"fleet_events\").where(\"ts\", \"<\", beforeIso).execute();\n}\n","import { openDb, readDbConfig, type Db } from \"../db/client.js\";\nimport { recordFleetEvent, pruneFleetEvents, type FleetEvent } from \"../db/fleet-events.js\";\n\nconst RETENTION_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Persist a batch of fleet events + prune the 30-day window — best-effort.\n * Opens its OWN libSQL connection (the producers carry only Airtable creds today).\n * A missing TURSO_* (creds not yet added to the workflow) or any write error is\n * swallowed with a console.error: recording fleet activity must NEVER fail the\n * sweep that produced it. The feed ships dark until the creds are present.\n * `open` is injectable for tests. */\nexport async function recordFleetEventsBestEffort(\n events: FleetEvent[],\n now: Date,\n open: () => Promise<Db> = () => openDb(readDbConfig()),\n): Promise<void> {\n if (events.length === 0) return;\n let db: Db;\n try {\n db = await open();\n } catch (e) {\n console.error(`[fleet-events] skipped ${events.length} event(s): no libSQL (${String(e)})`);\n return;\n }\n try {\n for (const e of events) await recordFleetEvent(db, e);\n await pruneFleetEvents(db, new Date(now.getTime() - RETENTION_MS).toISOString());\n } catch (e) {\n console.error(`[fleet-events] write failed: ${String(e)}`);\n }\n}\n"],"mappings":";;;;;;AAkDA,eAAsB,iBAAiB,IAAQ,GAA8B;AAC3E,QAAM,GACH,WAAW,cAAc,EACzB,OAAO;AAAA,IACN,IAAI,EAAE;AAAA,IACN,IAAI,EAAE;AAAA,IACN,MAAM,EAAE;AAAA,IACR,SAAS,EAAE;AAAA,IACX,WAAW,EAAE;AAAA,IACb,SAAS,EAAE;AAAA,IACX,MAAM,EAAE,QAAQ,OAAO,OAAO,KAAK,UAAU,EAAE,IAAI;AAAA,IACnD,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,EACrC,CAAC,EACA,WAAW,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,UAAU,CAAC,EAC9C,QAAQ;AACb;AAkBA,eAAsB,iBAAiB,IAAQ,WAAkC;AAC/E,QAAM,GAAG,WAAW,cAAc,EAAE,MAAM,MAAM,KAAK,SAAS,EAAE,QAAQ;AAC1E;;;AClFA,IAAM,eAAe,KAAK,KAAK,KAAK,KAAK;AAQzC,eAAsB,4BACpB,QACA,KACA,OAA0B,MAAM,OAAO,aAAa,CAAC,GACtC;AACf,MAAI,OAAO,WAAW,EAAG;AACzB,MAAI;AACJ,MAAI;AACF,SAAK,MAAM,KAAK;AAAA,EAClB,SAAS,GAAG;AACV,YAAQ,MAAM,0BAA0B,OAAO,MAAM,yBAAyB,OAAO,CAAC,CAAC,GAAG;AAC1F;AAAA,EACF;AACA,MAAI;AACF,eAAW,KAAK,OAAQ,OAAM,iBAAiB,IAAI,CAAC;AACpD,UAAM,iBAAiB,IAAI,IAAI,KAAK,IAAI,QAAQ,IAAI,YAAY,EAAE,YAAY,CAAC;AAAA,EACjF,SAAS,GAAG;AACV,YAAQ,MAAM,gCAAgC,OAAO,CAAC,CAAC,EAAE;AAAA,EAC3D;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
renderReportHtml,
|
|
6
6
|
resolveCopy,
|
|
7
7
|
uploadAttachment
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-U3MF6RCS.js";
|
|
9
9
|
import {
|
|
10
10
|
checklistFor,
|
|
11
11
|
createDraft,
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
import {
|
|
18
18
|
siteSlug,
|
|
19
19
|
updateAnalyticsHealth
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-BLD6AYJO.js";
|
|
21
21
|
import {
|
|
22
22
|
defaultCredentialsPath
|
|
23
23
|
} from "./chunk-6VAL7XJT.js";
|
|
@@ -441,4 +441,4 @@ export {
|
|
|
441
441
|
fetchGaUsers,
|
|
442
442
|
fetchSearch
|
|
443
443
|
};
|
|
444
|
-
//# sourceMappingURL=chunk-
|
|
444
|
+
//# sourceMappingURL=chunk-NPJFHBAX.js.map
|
|
@@ -194,6 +194,26 @@ function makeGitHub(deps) {
|
|
|
194
194
|
lastCommitAt: target?.committedDate ?? null
|
|
195
195
|
};
|
|
196
196
|
},
|
|
197
|
+
async mergedRenovatePullRequests(repo, sinceIso) {
|
|
198
|
+
const [owner, name, ...rest] = repo.split("/");
|
|
199
|
+
if (!owner || !name || rest.length > 0) {
|
|
200
|
+
throw new Error(`mergedRenovatePullRequests: expected "owner/repo", got "${repo}"`);
|
|
201
|
+
}
|
|
202
|
+
const out = await gh([
|
|
203
|
+
"api",
|
|
204
|
+
`repos/${owner}/${name}/pulls?state=closed&sort=updated&direction=desc&per_page=50`
|
|
205
|
+
]);
|
|
206
|
+
const arr = JSON.parse(out);
|
|
207
|
+
return arr.filter(
|
|
208
|
+
(p) => p.merged_at !== null && p.merged_at >= sinceIso && // ISO8601 UTC strings sort lexicographically
|
|
209
|
+
(p.head?.ref ?? "").startsWith("renovate/")
|
|
210
|
+
).map((p) => ({
|
|
211
|
+
number: p.number,
|
|
212
|
+
title: p.title,
|
|
213
|
+
url: p.html_url,
|
|
214
|
+
mergedAt: p.merged_at
|
|
215
|
+
}));
|
|
216
|
+
},
|
|
197
217
|
async dispatchWorkflow(repo, workflow, ref) {
|
|
198
218
|
const [owner, name, ...rest] = repo.split("/");
|
|
199
219
|
if (!owner || !name || rest.length > 0) {
|
|
@@ -218,4 +238,4 @@ function makeGitHub(deps) {
|
|
|
218
238
|
export {
|
|
219
239
|
makeGitHub
|
|
220
240
|
};
|
|
221
|
-
//# sourceMappingURL=chunk-
|
|
241
|
+
//# sourceMappingURL=chunk-OSRFDGQM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/github/gh.ts"],"sourcesContent":["import { defaultSpawn, type SpawnFn } from \"../audits/util/spawn.js\";\n\n/** Aggregate CI state of a PR's head commit, normalized from GitHub's rollup. */\nexport type CiState = \"passing\" | \"failing\" | \"pending\" | \"none\";\n\n/** GitHub's computed mergeability of a PR. `UNKNOWN` is transient — GitHub is\n * still computing it (e.g. right after a push) — so it should be read as \"not\n * known to conflict\", never as conflicting. */\nexport type PrMergeable = \"MERGEABLE\" | \"CONFLICTING\" | \"UNKNOWN\";\n\n/** A minimal open-PR summary with its head-commit CI rollup state + mergeability. */\nexport type PullRequestSummary = {\n number: number;\n title: string;\n url: string;\n headRef: string;\n ciState: CiState;\n mergeable: PrMergeable;\n};\n\n/**\n * Reject a value before it's interpolated into a `gh api` URL path. The\n * `owner/repo` split methods already validate shape; this is the defense-in-depth\n * guard for the `branch` and file-`path` segments. An unexpected value (`..`, a\n * leading `/`, whitespace, or a URL-structural char like `?#%` or a backslash)\n * could otherwise retarget the endpoint (escape the intended path, smuggle a\n * query string, or traverse). Conservative by design — legit branch names like\n * `maint/self-updating-x` and paths like `.github/workflows/ci.yml` pass.\n *\n * Both branch refs (`maint/self-updating-x`) and file paths\n * (`.github/workflows/ci.yml`) legitimately contain `/`, so a single slash is\n * allowed; what's rejected is `..`, a leading `/`, whitespace, or a\n * URL-structural char (`?`, `#`, `%`, backslash) that could escape or retarget\n * the endpoint.\n */\nexport function assertUrlSegment(kind: \"branch\" | \"path\", value: string): void {\n const structural = /[\\s?#%\\\\]|\\.\\./;\n if (value.length === 0 || value.startsWith(\"/\") || structural.test(value)) {\n throw new Error(\n `unsafe ${kind} for gh api path (illegal characters or traversal): ${JSON.stringify(value)}`,\n );\n }\n}\n\n/** Map GitHub's `statusCheckRollup.state` enum to our normalized CiState. */\nfunction mapRollupState(state: string | null | undefined): CiState {\n switch (state) {\n case \"SUCCESS\":\n return \"passing\";\n case \"FAILURE\":\n case \"ERROR\":\n return \"failing\";\n case \"PENDING\":\n case \"EXPECTED\":\n return \"pending\";\n default:\n return \"none\"; // null/undefined = no checks reported\n }\n}\n\n/** Coerce GitHub's `mergeable` enum to our PrMergeable. Anything unexpected\n * (including the literal `UNKNOWN` GitHub returns while still computing) maps to\n * `UNKNOWN` — i.e. \"not known to conflict\". Only an explicit `CONFLICTING` is. */\nfunction mapMergeable(state: string | null | undefined): PrMergeable {\n return state === \"MERGEABLE\" || state === \"CONFLICTING\" ? state : \"UNKNOWN\";\n}\n\nexport type GitHub = {\n openPullRequest: (\n repo: string,\n pr: { head: string; base: string; title: string; body: string },\n ) => Promise<{ url: string }>;\n enableRepoAutoMerge: (repo: string) => Promise<void>;\n protectBranch: (repo: string, branch: string, requiredChecks: string[]) => Promise<void>;\n setRepoSecret: (repo: string, name: string, value: string) => Promise<void>;\n repoExists: (repo: string) => Promise<boolean>;\n defaultBranch: (repo: string) => Promise<string>;\n filesOnBranch: (repo: string, branch: string, paths: string[]) => Promise<string[]>;\n branchProtectionContexts: (repo: string, branch: string) => Promise<string[]>;\n secretExists: (repo: string, name: string) => Promise<boolean>;\n autoMergeEnabled: (repo: string) => Promise<boolean>;\n findOpenSelfUpdatingPR: (repo: string) => Promise<string | null>;\n /** All open PRs on a repo with each head commit's normalized CI rollup state. */\n openPullRequests: (repo: string) => Promise<PullRequestSummary[]>;\n /** The default branch's latest-commit date + normalized CI rollup, one query. */\n defaultBranchStatus: (repo: string) => Promise<{ ciState: CiState; lastCommitAt: string | null }>;\n /** Renovate PRs (head `renovate/*`) merged at/after `sinceIso`. Used to record\n * `pr_automerged` fleet events. gh-shell (Actions only). */\n mergedRenovatePullRequests: (\n repo: string,\n sinceIso: string,\n ) => Promise<Array<{ number: number; title: string; url: string; mergedAt: string }>>;\n /** Fire a `workflow_dispatch` for `<workflow>` (a filename like `renovate.yml`)\n * on `ref`. Requires the token's `actions:write` scope; a 404 (no such\n * workflow) or 403 (missing scope) surfaces as a thrown error. */\n dispatchWorkflow: (repo: string, workflow: string, ref: string) => Promise<void>;\n};\n\nexport function makeGitHub(deps: { token: string; spawn?: SpawnFn }): GitHub {\n const spawn = deps.spawn ?? defaultSpawn;\n const env = { ...process.env, GH_TOKEN: deps.token };\n\n async function gh(args: string[]): Promise<string> {\n const r = await spawn(\"gh\", args, { env, timeoutMs: 60_000 });\n if (r.code !== 0) throw new Error(`gh ${args[0]} failed (code ${r.code}): ${r.stderr.trim()}`);\n return r.stdout;\n }\n\n return {\n async openPullRequest(repo, pr) {\n const out = await gh([\n \"pr\",\n \"create\",\n \"--repo\",\n repo,\n \"--head\",\n pr.head,\n \"--base\",\n pr.base,\n \"--title\",\n pr.title,\n \"--body\",\n pr.body,\n ]);\n return { url: out.trim() };\n },\n async enableRepoAutoMerge(repo) {\n await gh([\"api\", \"-X\", \"PATCH\", `repos/${repo}`, \"-F\", \"allow_auto_merge=true\"]);\n },\n async protectBranch(repo, branch, requiredChecks) {\n assertUrlSegment(\"branch\", branch);\n const args = [\n \"api\",\n \"-X\",\n \"PUT\",\n `repos/${repo}/branches/${branch}/protection`,\n \"-H\",\n \"Accept: application/vnd.github+json\",\n \"-F\",\n \"required_status_checks[strict]=true\",\n ...requiredChecks.flatMap((c) => [\"-f\", `required_status_checks[contexts][]=${c}`]),\n \"-F\",\n \"enforce_admins=true\",\n \"-F\",\n \"required_pull_request_reviews=null\",\n \"-F\",\n \"restrictions=null\",\n ];\n await gh(args);\n },\n async setRepoSecret(repo, name, value) {\n await gh([\"secret\", \"set\", name, \"--repo\", repo, \"--body\", value]);\n },\n async repoExists(repo) {\n const r = await spawn(\"gh\", [\"api\", `repos/${repo}`], { env, timeoutMs: 60_000 });\n return r.code === 0;\n },\n async defaultBranch(repo) {\n const out = await gh([\"api\", `repos/${repo}`, \"--jq\", \".default_branch\"]);\n return out.trim();\n },\n // filesOnBranch and branchProtectionContexts call `spawn` directly (not the\n // throwing `gh()` helper) because a 404 is an expected, meaningful answer —\n // \"file/protection absent\" — not an error. The remaining readers use `gh()`\n // since a non-200 there is a genuine failure (e.g. missing token scope).\n async filesOnBranch(repo, branch, paths) {\n assertUrlSegment(\"branch\", branch);\n const present: string[] = [];\n for (const p of paths) {\n assertUrlSegment(\"path\", p);\n const r = await spawn(\"gh\", [`api`, `repos/${repo}/contents/${p}?ref=${branch}`], {\n env,\n timeoutMs: 60_000,\n });\n if (r.code === 0) present.push(p);\n }\n return present;\n },\n async branchProtectionContexts(repo, branch) {\n assertUrlSegment(\"branch\", branch);\n const r = await spawn(\n \"gh\",\n [\n \"api\",\n `repos/${repo}/branches/${branch}/protection`,\n \"--jq\",\n \".required_status_checks.contexts[]?\",\n ],\n { env, timeoutMs: 60_000 },\n );\n if (r.code !== 0) return []; // 404 = no protection configured\n return r.stdout\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.length > 0);\n },\n async secretExists(repo, name) {\n // per_page=100: the REST default of 30 would false-negative on a repo with >30 secrets,\n // wrongly reporting an existing secret absent (→ a needless overwrite).\n const out = await gh([\n \"api\",\n `repos/${repo}/actions/secrets?per_page=100`,\n \"--jq\",\n \".secrets[].name\",\n ]);\n return out\n .split(\"\\n\")\n .map((l) => l.trim())\n .includes(name);\n },\n async autoMergeEnabled(repo) {\n const out = await gh([\"api\", `repos/${repo}`, \"--jq\", \".allow_auto_merge\"]);\n return out.trim() === \"true\";\n },\n async findOpenSelfUpdatingPR(repo) {\n // per_page=100: with the REST default of 30, a repo with >30 open PRs (plausible under\n // Renovate) could page past the existing self-updating PR and open a duplicate.\n const out = await gh([\n \"api\",\n `repos/${repo}/pulls?state=open&per_page=100`,\n \"--jq\",\n '.[] | select(.head.ref | startswith(\"maint/self-updating-\")) | .html_url',\n ]);\n const first = out\n .split(\"\\n\")\n .map((l) => l.trim())\n .find((l) => l.length > 0);\n return first ?? null;\n },\n async openPullRequests(repo) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`openPullRequests: expected \"owner/repo\", got \"${repo}\"`);\n }\n const query =\n \"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){\" +\n \"pullRequests(states:OPEN,first:100,orderBy:{field:CREATED_AT,direction:DESC}){nodes{number title url headRefName mergeable \" +\n \"commits(last:1){nodes{commit{statusCheckRollup{state}}}}}}}}\";\n const out = await gh([\n \"api\",\n \"graphql\",\n \"-f\",\n `query=${query}`,\n \"-F\",\n `owner=${owner}`,\n \"-F\",\n `name=${name}`,\n ]);\n const parsed = JSON.parse(out) as {\n data?: {\n repository?: {\n pullRequests?: {\n nodes?: Array<{\n number: number;\n title: string;\n url: string;\n headRefName: string;\n mergeable?: string;\n commits?: {\n nodes?: Array<{ commit?: { statusCheckRollup?: { state?: string } } }>;\n };\n }>;\n };\n };\n };\n };\n const nodes = parsed.data?.repository?.pullRequests?.nodes ?? [];\n return nodes.map((n) => ({\n number: n.number,\n title: n.title,\n url: n.url,\n headRef: n.headRefName,\n ciState: mapRollupState(n.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),\n mergeable: mapMergeable(n.mergeable),\n }));\n },\n async defaultBranchStatus(repo) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`defaultBranchStatus: expected \"owner/repo\", got \"${repo}\"`);\n }\n const query =\n \"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){\" +\n \"defaultBranchRef{target{... on Commit{committedDate statusCheckRollup{state}}}}}}\";\n const out = await gh([\n \"api\",\n \"graphql\",\n \"-f\",\n `query=${query}`,\n \"-F\",\n `owner=${owner}`,\n \"-F\",\n `name=${name}`,\n ]);\n const parsed = JSON.parse(out) as {\n data?: {\n repository?: {\n defaultBranchRef?: {\n target?: { committedDate?: string; statusCheckRollup?: { state?: string } | null };\n } | null;\n };\n };\n };\n const target = parsed.data?.repository?.defaultBranchRef?.target;\n return {\n ciState: mapRollupState(target?.statusCheckRollup?.state),\n lastCommitAt: target?.committedDate ?? null,\n };\n },\n async mergedRenovatePullRequests(repo, sinceIso) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`mergedRenovatePullRequests: expected \"owner/repo\", got \"${repo}\"`);\n }\n // per_page=50: comfortably covers a week of Renovate merges on one repo. The\n // list endpoint returns merged_at + head.ref, so the filter is local.\n const out = await gh([\n \"api\",\n `repos/${owner}/${name}/pulls?state=closed&sort=updated&direction=desc&per_page=50`,\n ]);\n const arr = JSON.parse(out) as Array<{\n number: number;\n title: string;\n html_url: string;\n merged_at: string | null;\n head?: { ref?: string };\n }>;\n return arr\n .filter(\n (p) =>\n p.merged_at !== null &&\n p.merged_at >= sinceIso && // ISO8601 UTC strings sort lexicographically\n (p.head?.ref ?? \"\").startsWith(\"renovate/\"),\n )\n .map((p) => ({\n number: p.number,\n title: p.title,\n url: p.html_url,\n mergedAt: p.merged_at as string,\n }));\n },\n async dispatchWorkflow(repo, workflow, ref) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`dispatchWorkflow: expected \"owner/repo\", got \"${repo}\"`);\n }\n // Every segment interpolates into the API path, so guard them all like the\n // other write methods do (defense in depth). `owner`/`name` are the most\n // operator-controlled (typed into Airtable's \"Git repo\"); `workflow` is a\n // constant today; `ref` is repo-sourced. A junk value like `repo?x=1` would\n // otherwise smuggle a query string past the bare two-part shape check.\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n assertUrlSegment(\"path\", workflow);\n assertUrlSegment(\"branch\", ref);\n await gh([\n \"api\",\n \"-X\",\n \"POST\",\n `repos/${owner}/${name}/actions/workflows/${workflow}/dispatches`,\n \"-f\",\n `ref=${ref}`,\n ]);\n },\n };\n}\n"],"mappings":";;;;;AAmCO,SAAS,iBAAiB,MAAyB,OAAqB;AAC7E,QAAM,aAAa;AACnB,MAAI,MAAM,WAAW,KAAK,MAAM,WAAW,GAAG,KAAK,WAAW,KAAK,KAAK,GAAG;AACzE,UAAM,IAAI;AAAA,MACR,UAAU,IAAI,uDAAuD,KAAK,UAAU,KAAK,CAAC;AAAA,IAC5F;AAAA,EACF;AACF;AAGA,SAAS,eAAe,OAA2C;AACjE,UAAQ,OAAO;AAAA,IACb,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAKA,SAAS,aAAa,OAA+C;AACnE,SAAO,UAAU,eAAe,UAAU,gBAAgB,QAAQ;AACpE;AAiCO,SAAS,WAAW,MAAkD;AAC3E,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,MAAM,EAAE,GAAG,QAAQ,KAAK,UAAU,KAAK,MAAM;AAEnD,iBAAe,GAAG,MAAiC;AACjD,UAAM,IAAI,MAAM,MAAM,MAAM,MAAM,E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,IACN;AAAA,IACA,MAAM,iBAAiB,MAAM,UAAU,KAAK;AAC1C,YAAM,CAAC,OAAO,MAAM,GAAG,IAAI,IAAI,KAAK,MAAM,GAAG;AAC7C,UAAI,CAAC,SAAS,CAAC,QAAQ,KAAK,SAAS,GAAG;AACtC,cAAM,IAAI,MAAM,iDAAiD,IAAI,GAAG;AAAA,MAC1E;AAMA,uBAAiB,QAAQ,KAAK;AAC9B,uBAAiB,QAAQ,IAAI;AAC7B,uBAAiB,QAAQ,QAAQ;AACjC,uBAAiB,UAAU,GAAG;AAC9B,YAAM,GAAG;AAAA,QACP;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS,KAAK,IAAI,IAAI,sBAAsB,QAAQ;AAAA,QACpD;AAAA,QACA,OAAO,GAAG;AAAA,MACZ,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -30,7 +30,7 @@ async function resolveSites(input) {
|
|
|
30
30
|
}
|
|
31
31
|
if (input.fleet === "airtable") {
|
|
32
32
|
const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
|
|
33
|
-
const { fromAirtableBase } = await import("./airtable-
|
|
33
|
+
const { fromAirtableBase } = await import("./airtable-HHAWHBNM.js");
|
|
34
34
|
const base = openBase(readAirtableConfig());
|
|
35
35
|
const provider = fromAirtableBase(base, input.workdir ? { workdir: input.workdir } : {});
|
|
36
36
|
return provider();
|
|
@@ -61,4 +61,4 @@ async function resolveSites(input) {
|
|
|
61
61
|
export {
|
|
62
62
|
resolveSites
|
|
63
63
|
};
|
|
64
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
//# sourceMappingURL=chunk-SAOCVNX7.js.map
|
|
@@ -1120,6 +1120,92 @@ async function defaultBrowserRunner() {
|
|
|
1120
1120
|
};
|
|
1121
1121
|
}
|
|
1122
1122
|
|
|
1123
|
+
// src/audits/netlify-deploy.ts
|
|
1124
|
+
var READY_STATES = /* @__PURE__ */ new Set(["ready"]);
|
|
1125
|
+
var FAILED_STATES = /* @__PURE__ */ new Set(["error", "failed", "rejected"]);
|
|
1126
|
+
function isReadyState(state) {
|
|
1127
|
+
return state !== null && READY_STATES.has(state);
|
|
1128
|
+
}
|
|
1129
|
+
function isFailedState(state) {
|
|
1130
|
+
return state !== null && FAILED_STATES.has(state);
|
|
1131
|
+
}
|
|
1132
|
+
async function checkNetlifyDeploy(siteId, deps) {
|
|
1133
|
+
const fetched = await deps.fetchLatestProductionDeploy(siteId).catch(() => null);
|
|
1134
|
+
if (!fetched) {
|
|
1135
|
+
return { state: null, deployedAt: null, logUrl: null, errorMessage: null };
|
|
1136
|
+
}
|
|
1137
|
+
return fetched;
|
|
1138
|
+
}
|
|
1139
|
+
function str(raw) {
|
|
1140
|
+
if (typeof raw !== "string") return null;
|
|
1141
|
+
const trimmed = raw.trim();
|
|
1142
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
1143
|
+
}
|
|
1144
|
+
function defaultNetlifyDeployDeps(token, now, fetchImpl = fetch) {
|
|
1145
|
+
return {
|
|
1146
|
+
now,
|
|
1147
|
+
fetchLatestProductionDeploy: async (siteId) => {
|
|
1148
|
+
const url = `https://api.netlify.com/api/v1/sites/${encodeURIComponent(siteId)}/deploys?per_page=1&production=true`;
|
|
1149
|
+
let res;
|
|
1150
|
+
try {
|
|
1151
|
+
res = await fetchImpl(url, {
|
|
1152
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
1153
|
+
});
|
|
1154
|
+
} catch {
|
|
1155
|
+
return null;
|
|
1156
|
+
}
|
|
1157
|
+
if (!res.ok) return null;
|
|
1158
|
+
let body;
|
|
1159
|
+
try {
|
|
1160
|
+
body = await res.json();
|
|
1161
|
+
} catch {
|
|
1162
|
+
return null;
|
|
1163
|
+
}
|
|
1164
|
+
if (!Array.isArray(body) || body.length === 0) return null;
|
|
1165
|
+
const d = body[0];
|
|
1166
|
+
const state = str(d["state"]);
|
|
1167
|
+
const deployedAt = str(d["published_at"]) ?? str(d["created_at"]);
|
|
1168
|
+
const logUrl = str(d["deploy_ssl_url"]) ?? str(d["admin_url"]) ?? str(d["deploy_url"]);
|
|
1169
|
+
const errorMessage = str(d["error_message"]);
|
|
1170
|
+
return {
|
|
1171
|
+
state: state ? state.toLowerCase() : null,
|
|
1172
|
+
deployedAt,
|
|
1173
|
+
logUrl,
|
|
1174
|
+
errorMessage
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
async function netlifyDeployAudit(ctx) {
|
|
1180
|
+
const { site } = ctx;
|
|
1181
|
+
const label = siteLabel(site);
|
|
1182
|
+
if (!site.netlifyId) {
|
|
1183
|
+
return { audit: "netlify-deploy", site: label, status: "skip", summary: "no netlify id" };
|
|
1184
|
+
}
|
|
1185
|
+
const token = process.env.NETLIFY_PAT;
|
|
1186
|
+
if (!token) {
|
|
1187
|
+
return { audit: "netlify-deploy", site: label, status: "skip", summary: "no NETLIFY_PAT" };
|
|
1188
|
+
}
|
|
1189
|
+
const now = ctx.now ?? /* @__PURE__ */ new Date();
|
|
1190
|
+
const deps = ctx.netlifyDeployDeps ?? defaultNetlifyDeployDeps(token, now);
|
|
1191
|
+
const check = await checkNetlifyDeploy(site.netlifyId, deps);
|
|
1192
|
+
const checkedAt = now.toISOString();
|
|
1193
|
+
const status = isReadyState(check.state) ? "pass" : isFailedState(check.state) ? "fail" : "warn";
|
|
1194
|
+
const summary = check.state === null ? "no deploy found" : isFailedState(check.state) ? `deploy ${check.state}${check.errorMessage ? ` \u2014 ${check.errorMessage}` : ""}` : `deploy ${check.state}`;
|
|
1195
|
+
return {
|
|
1196
|
+
audit: "netlify-deploy",
|
|
1197
|
+
site: label,
|
|
1198
|
+
status,
|
|
1199
|
+
summary,
|
|
1200
|
+
details: {
|
|
1201
|
+
state: check.state,
|
|
1202
|
+
deployedAt: check.deployedAt,
|
|
1203
|
+
logUrl: check.logUrl,
|
|
1204
|
+
checkedAt
|
|
1205
|
+
}
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1123
1209
|
// src/audits/index.ts
|
|
1124
1210
|
var REGISTRY = {
|
|
1125
1211
|
deps: depsAudit,
|
|
@@ -1128,7 +1214,8 @@ var REGISTRY = {
|
|
|
1128
1214
|
lighthouse: lighthouseAudit,
|
|
1129
1215
|
a11y: a11yAudit,
|
|
1130
1216
|
domain: domainAudit,
|
|
1131
|
-
browser: browserAudit
|
|
1217
|
+
browser: browserAudit,
|
|
1218
|
+
"netlify-deploy": netlifyDeployAudit
|
|
1132
1219
|
};
|
|
1133
1220
|
var ALL_AUDIT_NAMES = Object.keys(REGISTRY);
|
|
1134
1221
|
var DEFAULT_AUDIT_TIMEOUT_MS = 3e4;
|
|
@@ -1173,4 +1260,4 @@ export {
|
|
|
1173
1260
|
runAudits,
|
|
1174
1261
|
runAuditsAcross
|
|
1175
1262
|
};
|
|
1176
|
-
//# sourceMappingURL=chunk-
|
|
1263
|
+
//# sourceMappingURL=chunk-SS7BKOIX.js.map
|