@reddoorla/maintenance 0.60.1 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/airtable-HHAWHBNM.js +9 -0
  2. package/dist/{announce-Q2DXP5OO.js → announce-54EBITHX.js} +16 -6
  3. package/dist/announce-54EBITHX.js.map +1 -0
  4. package/dist/{bump-deps-RYHQIKW4.js → bump-deps-2U6GIHM5.js} +2 -2
  5. package/dist/{chunk-BWLUNY7L.js → chunk-2T3HZ3DB.js} +24 -14
  6. package/dist/chunk-2T3HZ3DB.js.map +1 -0
  7. package/dist/{chunk-D3LFQNJK.js → chunk-3HM4S422.js} +2 -2
  8. package/dist/{chunk-LMXIZITU.js → chunk-4REUHZAW.js} +40 -4
  9. package/dist/chunk-4REUHZAW.js.map +1 -0
  10. package/dist/chunk-5L3FPQIJ.js +92 -0
  11. package/dist/chunk-5L3FPQIJ.js.map +1 -0
  12. package/dist/{client-JA6QLEDW.js → chunk-6ZKM7OIJ.js} +5 -4
  13. package/dist/{chunk-KC4HU7BC.js → chunk-76VIUWR3.js} +31 -6
  14. package/dist/chunk-76VIUWR3.js.map +1 -0
  15. package/dist/{chunk-L4ULXHIN.js → chunk-BLD6AYJO.js} +15 -1
  16. package/dist/chunk-BLD6AYJO.js.map +1 -0
  17. package/dist/chunk-BMDBOPN3.js +211 -0
  18. package/dist/chunk-BMDBOPN3.js.map +1 -0
  19. package/dist/{chunk-HB7QPECR.js → chunk-KTPPKO2C.js} +6 -6
  20. package/dist/chunk-L5F664ZA.js +45 -0
  21. package/dist/chunk-L5F664ZA.js.map +1 -0
  22. package/dist/{chunk-XB6T4ETK.js → chunk-OSRFDGQM.js} +21 -1
  23. package/dist/chunk-OSRFDGQM.js.map +1 -0
  24. package/dist/{chunk-6CSCLBAA.js → chunk-SAOCVNX7.js} +2 -2
  25. package/dist/{chunk-5PHCZ6L5.js → chunk-SS7BKOIX.js} +89 -2
  26. package/dist/chunk-SS7BKOIX.js.map +1 -0
  27. package/dist/{chunk-TZN2G6FD.js → chunk-TYRCYHRA.js} +3 -3
  28. package/dist/{chunk-HG5DTFNF.js → chunk-XKKTK6WA.js} +17 -1
  29. package/dist/chunk-XKKTK6WA.js.map +1 -0
  30. package/dist/{chunk-JNXCDUYB.js → chunk-XVR7UM6Z.js} +4 -4
  31. package/dist/{chunk-HPSGCDWY.js → chunk-YYUY2OVP.js} +2 -2
  32. package/dist/{chunk-TLZ4V2BE.js → chunk-ZEX2T6JH.js} +3 -2
  33. package/dist/{chunk-TLZ4V2BE.js.map → chunk-ZEX2T6JH.js.map} +1 -1
  34. package/dist/cli/bin.js +16 -15
  35. package/dist/cli/bin.js.map +1 -1
  36. package/dist/cli/commands/audit.d.ts +3 -2
  37. package/dist/cli/commands/audit.js +29 -8
  38. package/dist/cli/commands/audit.js.map +1 -1
  39. package/dist/client-GTMJTXBK.js +11 -0
  40. package/dist/{convert-to-pnpm-KNCXU6FM.js → convert-to-pnpm-JG3767ZQ.js} +2 -2
  41. package/dist/{db-AXKMRTVA.js → db-Y6BVTNH7.js} +3 -3
  42. package/dist/{digest-RVIOHUXR.js → digest-ABJROO4H.js} +13 -197
  43. package/dist/digest-ABJROO4H.js.map +1 -0
  44. package/dist/{github-signals-UL2BBS3Q.js → github-signals-XTJLKOXJ.js} +26 -5
  45. package/dist/github-signals-XTJLKOXJ.js.map +1 -0
  46. package/dist/index.d.ts +62 -5
  47. package/dist/index.js +345 -206
  48. package/dist/index.js.map +1 -1
  49. package/dist/{init-KD56UENX.js → init-DMAIKUQE.js} +8 -8
  50. package/dist/{launch-UWCI3JRM.js → launch-UZPPB4IE.js} +10 -9
  51. package/dist/{launch-UWCI3JRM.js.map → launch-UZPPB4IE.js.map} +1 -1
  52. package/dist/{lighthouse-airtable-N3KCBPVA.js → lighthouse-airtable-HTEW6BBT.js} +3 -3
  53. package/dist/migrate-BFOG2OCP.js +7 -0
  54. package/dist/{onboard-SCZ3UKZ2.js → onboard-TTIC3YZI.js} +2 -2
  55. package/dist/{orchestrate-D72PB6NG.js → orchestrate-5GGOL5EX.js} +7 -4
  56. package/dist/recipes/sync-configs.d.ts +1 -1
  57. package/dist/recipes/sync-configs.js +2 -2
  58. package/dist/{renovate-dispatch-NG5KUQKY.js → renovate-dispatch-QDDMTATD.js} +3 -3
  59. package/dist/{report-CN56TGMK.js → report-SZGZIDDG.js} +6 -6
  60. package/dist/{self-updating-CFHXJSAX.js → self-updating-2RLUP4AA.js} +4 -4
  61. package/dist/{svelte-codemods-HNITLWQM.js → svelte-codemods-BPLKSVIA.js} +2 -2
  62. package/dist/{sync-configs-BZXBYKTI.js → sync-configs-VFRV3TJ4.js} +4 -4
  63. package/dist/{types-QG-QhCYh.d.ts → types-Dg4mHvyf.d.ts} +6 -1
  64. package/dist/{upgrade-6YDUELFA.js → upgrade-WCFD2TRN.js} +2 -2
  65. package/dist/{websites-IYP7IGLU.js → websites-HM2NMZMR.js} +2 -2
  66. package/dist/{write-audits-to-airtable-VDGHCZGQ.js → write-audits-to-airtable-QF26PCAR.js} +5 -4
  67. package/dist/write-audits-to-airtable-QF26PCAR.js.map +1 -0
  68. package/package.json +1 -1
  69. package/dist/airtable-YZ6VMSQZ.js +0 -9
  70. package/dist/announce-Q2DXP5OO.js.map +0 -1
  71. package/dist/chunk-5PHCZ6L5.js.map +0 -1
  72. package/dist/chunk-BWLUNY7L.js.map +0 -1
  73. package/dist/chunk-HG5DTFNF.js.map +0 -1
  74. package/dist/chunk-KC4HU7BC.js.map +0 -1
  75. package/dist/chunk-L4ULXHIN.js.map +0 -1
  76. package/dist/chunk-LMXIZITU.js.map +0 -1
  77. package/dist/chunk-XB6T4ETK.js.map +0 -1
  78. package/dist/digest-RVIOHUXR.js.map +0 -1
  79. package/dist/github-signals-UL2BBS3Q.js.map +0 -1
  80. package/dist/migrate-P2LS4WXI.js +0 -7
  81. /package/dist/{airtable-YZ6VMSQZ.js.map → airtable-HHAWHBNM.js.map} +0 -0
  82. /package/dist/{bump-deps-RYHQIKW4.js.map → bump-deps-2U6GIHM5.js.map} +0 -0
  83. /package/dist/{chunk-D3LFQNJK.js.map → chunk-3HM4S422.js.map} +0 -0
  84. /package/dist/{client-JA6QLEDW.js.map → chunk-6ZKM7OIJ.js.map} +0 -0
  85. /package/dist/{chunk-HB7QPECR.js.map → chunk-KTPPKO2C.js.map} +0 -0
  86. /package/dist/{chunk-6CSCLBAA.js.map → chunk-SAOCVNX7.js.map} +0 -0
  87. /package/dist/{chunk-TZN2G6FD.js.map → chunk-TYRCYHRA.js.map} +0 -0
  88. /package/dist/{chunk-JNXCDUYB.js.map → chunk-XVR7UM6Z.js.map} +0 -0
  89. /package/dist/{chunk-HPSGCDWY.js.map → chunk-YYUY2OVP.js.map} +0 -0
  90. /package/dist/{lighthouse-airtable-N3KCBPVA.js.map → client-GTMJTXBK.js.map} +0 -0
  91. /package/dist/{convert-to-pnpm-KNCXU6FM.js.map → convert-to-pnpm-JG3767ZQ.js.map} +0 -0
  92. /package/dist/{db-AXKMRTVA.js.map → db-Y6BVTNH7.js.map} +0 -0
  93. /package/dist/{init-KD56UENX.js.map → init-DMAIKUQE.js.map} +0 -0
  94. /package/dist/{migrate-P2LS4WXI.js.map → lighthouse-airtable-HTEW6BBT.js.map} +0 -0
  95. /package/dist/{orchestrate-D72PB6NG.js.map → migrate-BFOG2OCP.js.map} +0 -0
  96. /package/dist/{onboard-SCZ3UKZ2.js.map → onboard-TTIC3YZI.js.map} +0 -0
  97. /package/dist/{websites-IYP7IGLU.js.map → orchestrate-5GGOL5EX.js.map} +0 -0
  98. /package/dist/{renovate-dispatch-NG5KUQKY.js.map → renovate-dispatch-QDDMTATD.js.map} +0 -0
  99. /package/dist/{report-CN56TGMK.js.map → report-SZGZIDDG.js.map} +0 -0
  100. /package/dist/{self-updating-CFHXJSAX.js.map → self-updating-2RLUP4AA.js.map} +0 -0
  101. /package/dist/{svelte-codemods-HNITLWQM.js.map → svelte-codemods-BPLKSVIA.js.map} +0 -0
  102. /package/dist/{sync-configs-BZXBYKTI.js.map → sync-configs-VFRV3TJ4.js.map} +0 -0
  103. /package/dist/{upgrade-6YDUELFA.js.map → upgrade-WCFD2TRN.js.map} +0 -0
  104. /package/dist/{write-audits-to-airtable-VDGHCZGQ.js.map → websites-HM2NMZMR.js.map} +0 -0
@@ -0,0 +1,92 @@
1
+ // src/audits/fleet-event-detectors.ts
2
+ function ymd(iso) {
3
+ return iso.slice(0, 10);
4
+ }
5
+ function cleanRenovateTitle(title) {
6
+ let t = title.trim();
7
+ t = t.replace(/^[a-z]+(\([^)]*\))?:\s*/i, "");
8
+ t = t.replace(/^update dependency\s+/i, "");
9
+ t = t.replace(/^update\s+/i, "");
10
+ t = t.replace(/^pin dependencies?\s+/i, "");
11
+ t = t.replace(/\s+to\s+v?/i, "\u2192");
12
+ return t.trim();
13
+ }
14
+ function detectAuditEvents(prev, audits, at) {
15
+ const events = [];
16
+ if (audits.security) {
17
+ const prevCH = (prev.securityVulnsCritical ?? 0) + (prev.securityVulnsHigh ?? 0);
18
+ const newCH = audits.security.critical + audits.security.high;
19
+ if (prevCH > 0 && newCH === 0) {
20
+ events.push({
21
+ id: `vuln_cleared:${prev.id}:${ymd(at)}`,
22
+ ts: at,
23
+ type: "vuln_cleared",
24
+ siteId: prev.id,
25
+ siteName: prev.name,
26
+ summary: `cleared ${prevCH} critical/high vuln${prevCH === 1 ? "" : "s"}`,
27
+ data: { from: prevCH }
28
+ });
29
+ }
30
+ }
31
+ if (audits.domain) {
32
+ const prevDays = prev.certDaysRemaining;
33
+ const newDays = audits.domain.certDaysRemaining;
34
+ if (prevDays !== null && prevDays < 30 && newDays !== null && newDays > 60) {
35
+ events.push({
36
+ id: `cert_renewed:${prev.id}:${ymd(at)}`,
37
+ ts: at,
38
+ type: "cert_renewed",
39
+ siteId: prev.id,
40
+ siteName: prev.name,
41
+ summary: `TLS cert renewed (${newDays}d remaining)`,
42
+ data: { days: newDays }
43
+ });
44
+ }
45
+ }
46
+ return events;
47
+ }
48
+ function detectSignalEvents(prev, row, mergedPRs, at) {
49
+ const events = [];
50
+ for (const pr of mergedPRs) {
51
+ events.push({
52
+ id: `pr_automerged:${row.repo}#${pr.number}`,
53
+ ts: pr.mergedAt,
54
+ type: "pr_automerged",
55
+ siteId: prev.id,
56
+ siteName: prev.name,
57
+ summary: `auto-merged ${cleanRenovateTitle(pr.title)}`,
58
+ data: { url: pr.url, repo: row.repo, number: pr.number }
59
+ });
60
+ }
61
+ if (prev.defaultBranchCi === "failing" && row.ciState === "passing") {
62
+ events.push({
63
+ id: `ci_recovered:${prev.id}:${ymd(at)}`,
64
+ ts: at,
65
+ type: "ci_recovered",
66
+ siteId: prev.id,
67
+ siteName: prev.name,
68
+ summary: "CI recovered (default branch green)",
69
+ data: null
70
+ });
71
+ }
72
+ return events;
73
+ }
74
+ function fleetSweptEvent(sweep, count, at) {
75
+ const verb = sweep === "security" ? "security-swept" : sweep === "github-signals" ? "signals-swept" : "re-audited";
76
+ return {
77
+ id: `fleet_swept:${sweep}:${ymd(at)}`,
78
+ ts: at,
79
+ type: "fleet_swept",
80
+ siteId: null,
81
+ siteName: null,
82
+ summary: `${verb} ${count} site${count === 1 ? "" : "s"}`,
83
+ data: { sweep, count }
84
+ };
85
+ }
86
+
87
+ export {
88
+ detectAuditEvents,
89
+ detectSignalEvents,
90
+ fleetSweptEvent
91
+ };
92
+ //# sourceMappingURL=chunk-5L3FPQIJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/audits/fleet-event-detectors.ts"],"sourcesContent":["import type { WebsiteRow, SecurityCounts, DomainResult } from \"../reports/airtable/websites.js\";\nimport type { GitHubSignalsRow } from \"./github-signals.js\";\nimport type { FleetEvent } from \"../db/fleet-events.js\";\n\n/** YYYY-MM-DD slice of an ISO timestamp, for per-site-per-day deterministic ids. */\nfunction ymd(iso: string): string {\n return iso.slice(0, 10);\n}\n\n/** Compact a verbose Renovate PR title to \"<pkg>→<version> [tags]\".\n * \"chore(deps): update dependency vite to v7.3.5 [security]\" → \"vite→7.3.5 [security]\".\n * A grouped/no-version title (\"update all non-major dependencies\") is left readable. */\nexport function cleanRenovateTitle(title: string): string {\n let t = title.trim();\n t = t.replace(/^[a-z]+(\\([^)]*\\))?:\\s*/i, \"\"); // strip \"chore(deps): \"\n t = t.replace(/^update dependency\\s+/i, \"\");\n t = t.replace(/^update\\s+/i, \"\");\n t = t.replace(/^pin dependencies?\\s+/i, \"\");\n t = t.replace(/\\s+to\\s+v?/i, \"→\"); // \" to v7.3.5\" → \"→7.3.5\"\n return t.trim();\n}\n\n/** vuln_cleared (critical+high >0 → 0) and cert_renewed (<30 → >60) from a single\n * site's prior WebsiteRow vs the freshly-audited values. PURE. A null prior count\n * reads as 0 (vuln) or \"not a renewal\" (cert) — both fire only on a real transition. */\nexport function detectAuditEvents(\n prev: WebsiteRow,\n audits: { security?: SecurityCounts; domain?: DomainResult },\n at: string,\n): FleetEvent[] {\n const events: FleetEvent[] = [];\n\n if (audits.security) {\n const prevCH = (prev.securityVulnsCritical ?? 0) + (prev.securityVulnsHigh ?? 0);\n const newCH = audits.security.critical + audits.security.high;\n if (prevCH > 0 && newCH === 0) {\n events.push({\n id: `vuln_cleared:${prev.id}:${ymd(at)}`,\n ts: at,\n type: \"vuln_cleared\",\n siteId: prev.id,\n siteName: prev.name,\n summary: `cleared ${prevCH} critical/high vuln${prevCH === 1 ? \"\" : \"s\"}`,\n data: { from: prevCH },\n });\n }\n }\n\n if (audits.domain) {\n const prevDays = prev.certDaysRemaining;\n const newDays = audits.domain.certDaysRemaining;\n // Null prior = never measured / unresolved → first measurement, not a renewal.\n if (prevDays !== null && prevDays < 30 && newDays !== null && newDays > 60) {\n events.push({\n id: `cert_renewed:${prev.id}:${ymd(at)}`,\n ts: at,\n type: \"cert_renewed\",\n siteId: prev.id,\n siteName: prev.name,\n summary: `TLS cert renewed (${newDays}d remaining)`,\n data: { days: newDays },\n });\n }\n }\n\n return events;\n}\n\n/** pr_automerged (one per merged Renovate PR) + ci_recovered (failing → passing)\n * from a site's prior WebsiteRow, its fresh signals row, and the merged-PR list\n * found since the watermark. PURE. */\nexport function detectSignalEvents(\n prev: WebsiteRow,\n row: GitHubSignalsRow,\n mergedPRs: Array<{ number: number; title: string; url: string; mergedAt: string }>,\n at: string,\n): FleetEvent[] {\n const events: FleetEvent[] = [];\n\n for (const pr of mergedPRs) {\n events.push({\n id: `pr_automerged:${row.repo}#${pr.number}`,\n ts: pr.mergedAt,\n type: \"pr_automerged\",\n siteId: prev.id,\n siteName: prev.name,\n summary: `auto-merged ${cleanRenovateTitle(pr.title)}`,\n data: { url: pr.url, repo: row.repo, number: pr.number },\n });\n }\n\n if (prev.defaultBranchCi === \"failing\" && row.ciState === \"passing\") {\n events.push({\n id: `ci_recovered:${prev.id}:${ymd(at)}`,\n ts: at,\n type: \"ci_recovered\",\n siteId: prev.id,\n siteName: prev.name,\n summary: \"CI recovered (default branch green)\",\n data: null,\n });\n }\n\n return events;\n}\n\n/** A fleet-wide rollup event: one per sweep per day. */\nexport function fleetSweptEvent(\n sweep: \"lighthouse\" | \"security\" | \"github-signals\",\n count: number,\n at: string,\n): FleetEvent {\n const verb =\n sweep === \"security\"\n ? \"security-swept\"\n : sweep === \"github-signals\"\n ? \"signals-swept\"\n : \"re-audited\";\n return {\n id: `fleet_swept:${sweep}:${ymd(at)}`,\n ts: at,\n type: \"fleet_swept\",\n siteId: null,\n siteName: null,\n summary: `${verb} ${count} site${count === 1 ? \"\" : \"s\"}`,\n data: { sweep, count },\n };\n}\n"],"mappings":";AAKA,SAAS,IAAI,KAAqB;AAChC,SAAO,IAAI,MAAM,GAAG,EAAE;AACxB;AAKO,SAAS,mBAAmB,OAAuB;AACxD,MAAI,IAAI,MAAM,KAAK;AACnB,MAAI,EAAE,QAAQ,4BAA4B,EAAE;AAC5C,MAAI,EAAE,QAAQ,0BAA0B,EAAE;AAC1C,MAAI,EAAE,QAAQ,eAAe,EAAE;AAC/B,MAAI,EAAE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AAAA,MACP,MAAM;AAAA,MACN,QAAQ,KAAK;AAAA,MACb,UAAU,KAAK;AAAA,MACf,SAAS,eAAe,mBAAmB,GAAG,KAAK,CAAC;AAAA,MACpD,MAAM,EAAE,KAAK,GAAG,KAAK,MAAM,IAAI,MAAM,QAAQ,GAAG,OAAO;AAAA,IACzD,CAAC;AAAA,EACH;AAEA,MAAI,KAAK,oBAAoB,aAAa,IAAI,YAAY,WAAW;AACnE,WAAO,KAAK;AAAA,MACV,IAAI,gBAAgB,KAAK,EAAE,IAAI,IAAI,EAAE,CAAC;AAAA,MACtC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,QAAQ,KAAK;AAAA,MACb,UAAU,KAAK;AAAA,MACf,SAAS;AAAA,MACT,MAAM;AAAA,IACR,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAGO,SAAS,gBACd,OACA,OACA,IACY;AACZ,QAAM,OACJ,UAAU,aACN,mBACA,UAAU,mBACR,kBACA;AACR,SAAO;AAAA,IACL,IAAI,eAAe,KAAK,IAAI,IAAI,EAAE,CAAC;AAAA,IACnC,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,SAAS,GAAG,IAAI,IAAI,KAAK,QAAQ,UAAU,IAAI,KAAK,GAAG;AAAA,IACvD,MAAM,EAAE,OAAO,MAAM;AAAA,EACvB;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runMigrations
3
- } from "./chunk-HG5DTFNF.js";
3
+ } from "./chunk-XKKTK6WA.js";
4
4
  import {
5
5
  defaultCredentialsPath
6
6
  } from "./chunk-6VAL7XJT.js";
@@ -41,8 +41,9 @@ async function openDb(cfg) {
41
41
  await ensureMigrated(cfg.url, client);
42
42
  return new Kysely({ dialect: new LibsqlDialect({ client }) });
43
43
  }
44
+
44
45
  export {
45
- openDb,
46
- readDbConfig
46
+ readDbConfig,
47
+ openDb
47
48
  };
48
- //# sourceMappingURL=client-JA6QLEDW.js.map
49
+ //# sourceMappingURL=chunk-6ZKM7OIJ.js.map
@@ -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-BWLUNY7L.js";
7
+ } from "./chunk-2T3HZ3DB.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-L4ULXHIN.js";
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-KC4HU7BC.js.map
304
+ //# sourceMappingURL=chunk-76VIUWR3.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,YAAY,KAAK;AACvB,QAAM,aAAa,KAAK;AACxB,MAAI,CAAC,aAAa,CAAC,YAAY;AAC7B,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AAGA,QAAM,eAAe,KAAK,IAAI,uBAAuB,SAAS;AAC9D,QAAM,gBAAgB,KAAK,MAAO,eAAe,aAAc,SAAS;AAGxE,QAAM,oBAAoB,KAAK,IAAI,WAAW,eAAe,YAAY;AAEzE,QAAM,MAAM,MAAM,MAAM,KAAK,EAC1B,OAAO,EAAE,OAAO,mBAAmB,oBAAoB,KAAK,CAAC,EAC7D,QAAQ,EAAE,YAAY,UAAU,CAAC,EACjC,KAAK,EAAE,SAAS,aAAa,CAAC,EAC9B,SAAS;AAEZ,QAAM,EAAE,SAAS,IAAI,MAAM,MAAM,GAAG,EAAE,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aAAW,OAAO,MAAM,MAAM,OAAO,GAAG;AACtC,UAAM,UAAU,IAAI,KAAK,EAAE,YAAY;AACvC,QAAI,CAAC,QAAS;AACd,QAAI,KAAK,IAAI,OAAO,EAAG;AACvB,SAAK,IAAI,OAAO;AAChB,SAAK,KAAK,OAAO;AAAA,EACnB;AACA,SAAO,KAAK,SAAS,IAAI,OAAO;AAClC;AASO,SAAS,gBAAgB,GAAoB;AAClD,QAAM,KAAK,EAAE,QAAQ,GAAG;AACxB,MAAI,KAAK,KAAK,OAAO,EAAE,YAAY,GAAG,EAAG,QAAO;AAChD,QAAM,QAAQ,EAAE,MAAM,GAAG,EAAE;AAC3B,QAAM,SAAS,EAAE,MAAM,KAAK,CAAC;AAC7B,MAAI,CAAC,SAAS,CAAC,OAAQ,QAAO;AAC9B,MAAI,CAAC,OAAO,SAAS,GAAG,EAAG,QAAO;AAClC,MAAI,KAAK,KAAK,CAAC,EAAG,QAAO;AACzB,SAAO;AACT;","names":[]}
@@ -81,6 +81,10 @@ function mapRow(rec) {
81
81
  securityAdvisories: parseSecurityAdvisories(f["Security advisories"]),
82
82
  certDaysRemaining: f["Cert days remaining"] ?? null,
83
83
  domainCheckedAt: f["Domain checked at"] ?? null,
84
+ netlifyId: trimToNull(f["Netlify ID"]),
85
+ deployStatus: f["Deploy status"] ?? null,
86
+ lastDeployAt: f["Last deploy at"] ?? null,
87
+ deployLogUrl: f["Deploy log URL"] ?? null,
84
88
  crossbrowserOk: typeof f["Crossbrowser OK"] === "boolean" ? f["Crossbrowser OK"] : null,
85
89
  mobileOk: typeof f["Mobile OK"] === "boolean" ? f["Mobile OK"] : null,
86
90
  linksOk: typeof f["Links OK"] === "boolean" ? f["Links OK"] : null,
@@ -198,6 +202,15 @@ function domainFields(result) {
198
202
  fields["Cert days remaining"] = result.certDaysRemaining;
199
203
  return fields;
200
204
  }
205
+ function netlifyDeployFields(result) {
206
+ const fields = {
207
+ "Deploy status": result.state,
208
+ "Last deploy at": result.deployedAt,
209
+ "Deploy log URL": result.logUrl,
210
+ "Deploy checked at": result.checkedAt
211
+ };
212
+ return fields;
213
+ }
201
214
  function browserFields(r) {
202
215
  return {
203
216
  "Crossbrowser OK": r.desktopOk,
@@ -241,6 +254,7 @@ async function updateAuditFields(base, recordId, audits) {
241
254
  Object.assign(fields, securityAdvisoryFields(audits.securityAdvisories));
242
255
  if (audits.domain) Object.assign(fields, domainFields(audits.domain));
243
256
  if (audits.browser) Object.assign(fields, browserFields(audits.browser));
257
+ if (audits.netlifyDeploy) Object.assign(fields, netlifyDeployFields(audits.netlifyDeploy));
244
258
  await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);
245
259
  return fields;
246
260
  }
@@ -283,4 +297,4 @@ export {
283
297
  updateGitHubSignals,
284
298
  updateLaunched
285
299
  };
286
- //# sourceMappingURL=chunk-L4ULXHIN.js.map
300
+ //# sourceMappingURL=chunk-BLD6AYJO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/reports/airtable/websites.ts"],"sourcesContent":["import type { FieldSet } from \"airtable\";\nimport type { AirtableBase } from \"./client.js\";\nimport type { LighthouseScores, LighthouseScoreWriteback } from \"../types.js\";\n\nexport const WEBSITES_TABLE = \"Websites\";\n\nexport type Frequency = \"None\" | \"Monthly\" | \"Quarterly\" | \"Yearly\";\n\nexport type Status =\n | \"in development\"\n | \"launch period\"\n | \"maintenance\"\n | \"hosting\"\n | \"probably not our problem\"\n | \"deprecated\";\n\n/**\n * Per-site notification routing. When present on a `maintenance` site, the form\n * notification is addressed by the value of a submission field (`field`, read from\n * `extraFields`) — e.g. route a contact form's `interest` to a different recipient\n * per option, always CC-ing a shared address. Absent (`null`) → the site keeps the\n * default single-POC behavior. Recipients live HERE (server-side Airtable config),\n * never supplied by the submitting site, so the ingest can't be turned into an open\n * relay.\n */\nexport type NotifyRouting = {\n /** The `extraFields` key whose value selects a route, e.g. \"interest\". */\n field: string;\n /** Field-value → recipient address(es). */\n routes: Record<string, string | string[]>;\n /** Recipient(s) when the value matches no route. */\n default?: string | string[];\n /** Address(es) CC'd on every routed (maintenance) send. */\n cc?: string[];\n};\n\nexport type WebsiteRow = {\n id: string;\n name: string;\n url: string;\n status: Status | null;\n pointOfContact: string | null;\n maintenanceFreq: Frequency;\n testingFreq: Frequency;\n /** Last manually-recorded maintenance day (used as fallback when no Reports row exists). */\n maintenanceDay: string | null;\n testingDay: string | null;\n ga4PropertyId: string | null;\n /** Operator-supplied query for the Google search-presence check (e.g. the business name).\n * Null = no query set → the check is skipped for this site. */\n searchQuery: string | null;\n /** Explicit Search Console property for this site (`sc-domain:...` or `https://.../`).\n * Null = auto-resolve from the SA's visible properties by host. */\n searchConsoleProperty: string | null;\n /** ISO timestamp of the last draft run where THIS site's GA/Search enrichment\n * ERRORED (vs a legitimate \"not configured\" skip). Set by drafting on a soft-fail,\n * cleared (null) on a clean enrichment, so the per-site analytics-failure signal\n * self-heals. Null when the operator-added `Analytics soft-fail at` column is absent. */\n analyticsSoftFailAt: string | null;\n /** GitHub repo identity as `owner/repo`. Null = no git wiring → self-update ops skip\n * (or, for local runs, fall back to the checkout's origin remote). */\n gitRepo: string | null;\n reportRecipientsTo: string | null;\n reportRecipientsCc: string | null;\n /** First attachment in the Header image field (Airtable's signed URL — fetch before expiry). */\n headerImage: { url: string; filename: string; type: string } | null;\n /** Lighthouse \"current state\" snapshot, kept fresh by `audit lighthouse --write-airtable`. */\n pScore: number | null;\n rScore: number | null;\n bpScore: number | null;\n seoScore: number | null;\n /** ISO timestamp set by `audit lighthouse --write-airtable` when scores were last refreshed. */\n lastLighthouseAuditAt: string | null;\n /** Last-known counts from non-lighthouse audits, written by\n * `audit --write-airtable`. `null` = never audited (or this audit\n * type was skipped on the last run). 0 = audited, clean. */\n a11yViolations: number | null;\n /** Declared-range drift vs the Reddoor baseline (what package.json asks for). */\n depsDrifted: number | null;\n depsMajorBehind: number | null;\n /** Real installed-version drift: deps behind the registry's latest, from the\n * committed lockfile (`pnpm outdated`). Null = not determined this run. */\n depsOutdated: number | null;\n securityVulnsCritical: number | null;\n securityVulnsHigh: number | null;\n securityVulnsModerate: number | null;\n securityVulnsLow: number | null;\n /** Count of consecutive nightly Renovate auto-fix dispatches for the CURRENT\n * critical/high vuln episode that have NOT yet cleared it. Owned by\n * `renovate-dispatch`: +1 per real dispatch, reset to 0 when vulns clear.\n * Null = field absent / never dispatched → reads as 0. At/above\n * AUTO_FIX_EXHAUSTED_CYCLES the vuln renders as \"auto-fix failed\". */\n securityAutoFixAttempts: number | null;\n /** ISO timestamp the security audit last ran — gates freshness of the Security Updates auto-tick\n * (clean counts only auto-tick when recent). */\n lastSecurityAuditAt: string | null;\n /** The known advisories behind the counts (severity-sorted, capped), so the dashboard can show\n * WHICH packages are vulnerable, not just the totals. null = never audited / unparseable;\n * empty array = audited clean. Written alongside the counts by the security audit. */\n securityAdvisories: SecurityAdvisory[] | null;\n /** Domain/DNS/SSL probe (the `domain` audit). `certDaysRemaining` is days until the TLS cert\n * expires (null = unresolved or no usable cert); `domainCheckedAt` is when it last ran. */\n certDaysRemaining: number | null;\n domainCheckedAt: string | null;\n /** Netlify site id — the IDENTITY the `netlify-deploy` audit needs to query the\n * Netlify API. Read-only input (operator-set in Airtable); null = not on Netlify\n * (or not wired) → that audit skips. Never derived from the URL. */\n netlifyId: string | null;\n /** Latest PRODUCTION deploy health (the `netlify-deploy` audit). `deployStatus` is\n * Netlify's deploy state lower-cased (`ready`/`error`/`building`/…), null = none / not\n * checked; `lastDeployAt` is when it deployed; `deployLogUrl` links to the deploy/log. */\n deployStatus: string | null;\n lastDeployAt: string | null;\n deployLogUrl: string | null;\n /** Deployed-URL browser probe (the `browser` audit): cross-engine render OK, mobile render OK,\n * internal-links OK + broken count, and when it last ran (one timestamp gates all three). */\n crossbrowserOk: boolean | null;\n mobileOk: boolean | null;\n linksOk: boolean | null;\n brokenLinks: number | null;\n browserCheckedAt: string | null;\n /** Per-site copy overrides (M6a). Blank → null → the DEFAULT_COPY value. */\n copyIntro: string | null;\n copyContact: string | null;\n copyFooter: string | null;\n /** Go-live timestamp, stamped when a Launch report sends (M6b). Null = not yet launched. */\n launchedAt: string | null;\n /** Optional per-site webhook (e.g. Zapier Catch Hook). When set, the ingest\n * POSTs newsletter-formType submissions here (best-effort). Blank → null. */\n newsletterWebhook: string | null;\n /** Per-site Mailchimp (newsletter). Both must be set for the direct add;\n * blank → skipped. The API key is `key-dc` format; dc is derived from it. */\n mailchimpApiKey: string | null;\n mailchimpAudienceId: string | null;\n /** GitHub-signals sweep (slice 2a), written nightly by `github-signals --fleet`. */\n renovateFailingCis: number | null;\n defaultBranchCi: string | null; // \"passing\" | \"failing\" | \"pending\" | \"none\"\n lastCommitAt: string | null;\n githubSignalsAt: string | null;\n notifyRouting: NotifyRouting | null;\n};\n\nexport function siteSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** Blank-trim-to-null: a non-string or whitespace-only value becomes null,\n * otherwise the trimmed string. */\nfunction trimToNull(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Parse the Websites `Notify Routing` JSON into a NotifyRouting, defensively: a\n * non-string, blank, malformed-JSON, or wrong-shape value yields null (the site\n * then keeps default single-POC routing) — never throws. Mirrors the pipeline's\n * \"a bad Airtable string degrades quietly\" rule.\n */\nexport function parseNotifyRouting(raw: unknown): NotifyRouting | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (!trimmed) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const o = parsed as Record<string, unknown>;\n if (typeof o.field !== \"string\" || !o.field.trim()) return null;\n if (!o.routes || typeof o.routes !== \"object\" || Array.isArray(o.routes)) return null;\n const routing: NotifyRouting = {\n field: o.field,\n routes: o.routes as Record<string, string | string[]>,\n };\n if (o.default !== undefined) routing.default = o.default as string | string[];\n if (Array.isArray(o.cc)) routing.cc = o.cc.filter((x): x is string => typeof x === \"string\");\n return routing;\n}\n\n/**\n * Active sites: actively-maintained or pre-launch. Single source of truth for\n * \"is this a live site\" — the operator cockpit shows these, and the fleet\n * audit/report path runs against these. A `null` status (not-yet-active) is\n * deliberately excluded.\n */\nexport const ACTIVE_STATUSES: ReadonlySet<Status> = new Set<Status>([\n \"maintenance\",\n \"launch period\",\n]);\n\nexport function isDashboardVisible(site: WebsiteRow): boolean {\n return site.status !== null && ACTIVE_STATUSES.has(site.status);\n}\n\nconst FREQUENCIES: readonly Frequency[] = [\"None\", \"Monthly\", \"Quarterly\", \"Yearly\"];\n\n/** Coerce an Airtable single-select value to a known Frequency. An unrecognized value — a\n * renamed / typo'd / whitespace option — falls back to \"None\" (its section is simply omitted)\n * rather than flowing a bogus string downstream, which the announcement would otherwise render\n * as \"We do this undefined.\" into a client email. */\nfunction toFrequency(raw: unknown): Frequency {\n return typeof raw === \"string\" && (FREQUENCIES as readonly string[]).includes(raw)\n ? (raw as Frequency)\n : \"None\";\n}\n\n// NOTE: every `f[\"...\"]` key below is a load-bearing magic string that must match\n// the live Airtable \"Websites\" column name EXACTLY — including the legacy\n// misspelling `\"maintenence freq\"`, the mixed-case `\"GA4 property ID\"`, and the\n// lowercase `\"url\"` / `\"point of contact\"`. A column rename in Airtable silently\n// returns undefined here (→ null), which degrades quietly (GA skipped, recipients\n// empty) with no error. If you rename a column, change it here too.\nexport function mapRow(rec: { id: string; fields: Record<string, unknown> }): WebsiteRow {\n const f = rec.fields;\n const attachments =\n (f[\"Header image\"] as Array<{ url: string; filename: string; type: string }> | undefined) ?? [];\n const header = attachments[0] ?? null;\n return {\n id: rec.id,\n name: String(f[\"Name\"] ?? \"\"),\n url: String(f[\"url\"] ?? \"\"),\n status: (f[\"Status\"] as Status | undefined) ?? null,\n pointOfContact: (f[\"point of contact\"] as string | undefined) ?? null,\n maintenanceFreq: toFrequency(f[\"maintenence freq\"]),\n testingFreq: toFrequency(f[\"testing freq\"]),\n maintenanceDay: (f[\"maintenance day\"] as string | undefined) ?? null,\n testingDay: (f[\"testing day\"] as string | undefined) ?? null,\n ga4PropertyId: (f[\"GA4 property ID\"] as string | undefined) ?? null,\n searchQuery: (f[\"Search query\"] as string | undefined) ?? null,\n searchConsoleProperty: (f[\"Search Console property\"] as string | undefined) ?? null,\n analyticsSoftFailAt: (f[\"Analytics soft-fail at\"] as string | undefined) ?? null,\n gitRepo: (f[\"Git repo\"] as string | undefined) ?? null,\n reportRecipientsTo: (f[\"Report recipients (To)\"] as string | undefined) ?? null,\n reportRecipientsCc: (f[\"Report recipients (CC)\"] as string | undefined) ?? null,\n headerImage: header,\n pScore: (f[\"pScore\"] as number | undefined) ?? null,\n rScore: (f[\"rScore\"] as number | undefined) ?? null,\n bpScore: (f[\"bpScore\"] as number | undefined) ?? null,\n seoScore: (f[\"seoScore\"] as number | undefined) ?? null,\n lastLighthouseAuditAt: (f[\"Last lighthouse audit at\"] as string | undefined) ?? null,\n a11yViolations: (f[\"A11y Violations\"] as number | undefined) ?? null,\n depsDrifted: (f[\"Deps Drifted\"] as number | undefined) ?? null,\n depsMajorBehind: (f[\"Deps Major Behind\"] as number | undefined) ?? null,\n depsOutdated: (f[\"Deps Outdated\"] as number | undefined) ?? null,\n securityVulnsCritical: (f[\"Security Vulns Critical\"] as number | undefined) ?? null,\n securityVulnsHigh: (f[\"Security Vulns High\"] as number | undefined) ?? null,\n securityVulnsModerate: (f[\"Security Vulns Moderate\"] as number | undefined) ?? null,\n securityVulnsLow: (f[\"Security Vulns Low\"] as number | undefined) ?? null,\n securityAutoFixAttempts: (f[\"Security Auto-Fix Attempts\"] as number | undefined) ?? null,\n lastSecurityAuditAt: (f[\"Last security audit at\"] as string | undefined) ?? null,\n securityAdvisories: parseSecurityAdvisories(f[\"Security advisories\"]),\n certDaysRemaining: (f[\"Cert days remaining\"] as number | undefined) ?? null,\n domainCheckedAt: (f[\"Domain checked at\"] as string | undefined) ?? null,\n netlifyId: trimToNull(f[\"Netlify ID\"]),\n deployStatus: (f[\"Deploy status\"] as string | undefined) ?? null,\n lastDeployAt: (f[\"Last deploy at\"] as string | undefined) ?? null,\n deployLogUrl: (f[\"Deploy log URL\"] as string | undefined) ?? null,\n crossbrowserOk:\n typeof f[\"Crossbrowser OK\"] === \"boolean\" ? (f[\"Crossbrowser OK\"] as boolean) : null,\n mobileOk: typeof f[\"Mobile OK\"] === \"boolean\" ? (f[\"Mobile OK\"] as boolean) : null,\n linksOk: typeof f[\"Links OK\"] === \"boolean\" ? (f[\"Links OK\"] as boolean) : null,\n brokenLinks: typeof f[\"Broken links\"] === \"number\" ? (f[\"Broken links\"] as number) : null,\n browserCheckedAt: (f[\"Browser checked at\"] as string | undefined) ?? null,\n copyIntro: trimToNull(f[\"Copy — Intro\"]),\n copyContact: trimToNull(f[\"Copy — Contact\"]),\n copyFooter: trimToNull(f[\"Copy — Footer\"]),\n launchedAt: (f[\"Launched at\"] as string | undefined) ?? null,\n newsletterWebhook: trimToNull(f[\"Newsletter Webhook\"]),\n notifyRouting: parseNotifyRouting(f[\"Notify Routing\"]),\n mailchimpApiKey: trimToNull(f[\"Mailchimp API Key\"]),\n mailchimpAudienceId: trimToNull(f[\"Mailchimp Audience ID\"]),\n renovateFailingCis: (f[\"Renovate Failing CIs\"] as number | undefined) ?? null,\n defaultBranchCi: (f[\"Default Branch CI\"] as string | undefined) ?? null,\n lastCommitAt: (f[\"Last Commit At\"] as string | undefined) ?? null,\n githubSignalsAt: (f[\"GitHub Signals At\"] as string | undefined) ?? null,\n };\n}\n\nexport async function listWebsites(base: AirtableBase): Promise<WebsiteRow[]> {\n const out: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ pageSize: 100 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) out.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n return out;\n}\n\nexport async function getWebsiteBySlug(\n base: AirtableBase,\n slug: string,\n): Promise<WebsiteRow | null> {\n // Slugs are siteSlug() output: [a-z0-9] segments joined by single hyphens.\n // Reject anything else — it can't match a real row, and it keeps URL-supplied\n // input out of the filter formula below (formula-injection guard).\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return null;\n\n // Narrow the fetch to the slug-matching row server-side instead of paging the\n // whole table per request (MEDIUM-H). The formula replicates siteSlug() on\n // {Name} — lowercase → non-alnum runs to \"-\" → strip leading/trailing \"-\" —\n // verified against the live base. maxRecords caps it (slug collisions keep the\n // prior first-match-wins behavior).\n const formula = `REGEX_REPLACE(REGEX_REPLACE(LOWER({Name}),\"[^a-z0-9]+\",\"-\"),\"^-|-$\",\"\")=${JSON.stringify(\n slug,\n )}`;\n const rows: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ filterByFormula: formula, maxRecords: 1 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n // Confirm the match in JS too: keeps the function correct if the formula and\n // siteSlug() ever drift, and under test fakes that don't evaluate the formula.\n return rows.find((w) => siteSlug(w.name) === slug) ?? null;\n}\n\n// ── audit-field builders ─────────────────────────────────────────────────────\n// One source of truth for the column-name → value mappings of each audit type.\n// The per-audit `updateXxxCounts` writers delegate to these (for their other\n// callers), and `updateAuditFields` merges whichever are present into ONE write —\n// so the field-name magic strings live in exactly one place.\n\nexport type A11yCounts = { violations: number };\nexport type DepsCounts = { drifted: number; majorBehind: number; outdated: number | null };\nexport type SecurityCounts = { critical: number; high: number; moderate: number; low: number };\nexport type Severity = \"low\" | \"moderate\" | \"high\" | \"critical\";\n/** One known vulnerability behind the security counts, as persisted/rendered. */\nexport type SecurityAdvisory = {\n module: string;\n severity: Severity;\n title: string;\n cves: string[];\n url: string | null;\n};\nexport type DomainResult = { certDaysRemaining: number | null; checkedAt: string };\nexport type NetlifyDeployResult = {\n /** Netlify deploy state lower-cased (`ready`/`error`/`building`/…), null = none. */\n state: string | null;\n /** When the latest production deploy was published/created (ISO), null = unknown. */\n deployedAt: string | null;\n /** Link to the deploy / its build log, null = unknown. */\n logUrl: string | null;\n /** When the audit last ran. */\n checkedAt: string;\n};\nexport type BrowserAuditFields = {\n desktopOk: boolean;\n mobileOk: boolean;\n linksOk: boolean;\n brokenLinks: number;\n checkedAt: string;\n};\n\nfunction scoreFields(scores: LighthouseScoreWriteback): FieldSet {\n // A null score CLEARS the cell (→ dashboard \"—\"), distinguishing a metric that\n // errored this run (e.g. NO_LCP → null performance) from a real low score. This\n // intentionally overwrites a prior value: a run that couldn't measure the metric\n // shouldn't keep showing a stale number. Writing null to clear mirrors\n // updateAnalyticsHealth; the `as FieldSet` cast is needed because airtable's\n // FieldSet type omits null.\n const fields: Record<string, number | string | null> = {\n pScore: scores.performance,\n rScore: scores.accessibility,\n bpScore: scores.bestPractices,\n seoScore: scores.seo,\n \"Last lighthouse audit at\": new Date().toISOString(),\n };\n return fields as FieldSet;\n}\n\nfunction a11yFields(counts: A11yCounts): FieldSet {\n return { \"A11y Violations\": counts.violations };\n}\n\nfunction depsFields(counts: DepsCounts): FieldSet {\n const fields: FieldSet = {\n \"Deps Drifted\": counts.drifted,\n \"Deps Major Behind\": counts.majorBehind,\n };\n // Only write the outdated count when it was determined — a null (no/stale\n // lockfile this run) must not clobber a previously-good value.\n if (counts.outdated !== null) {\n fields[\"Deps Outdated\"] = counts.outdated;\n }\n return fields;\n}\n\n/** Critical first → low last; the persist cap and the dashboard list both lean on this. */\nexport const SEVERITY_RANK: Record<Severity, number> = {\n critical: 0,\n high: 1,\n moderate: 2,\n low: 3,\n};\n/** Cap persisted advisories so the JSON field can't blow up on a badly-neglected site. */\nconst MAX_PERSISTED_ADVISORIES = 25;\n\n/** Coerce one untrusted value into a SecurityAdvisory, or null if it isn't shaped like one.\n * Shared by the read path (`parseSecurityAdvisories`) and the write path so both validate\n * identically. A missing module or unrecognized severity drops the entry entirely. */\nexport function normalizeSecurityAdvisory(raw: unknown): SecurityAdvisory | null {\n if (!raw || typeof raw !== \"object\") return null;\n const e = raw as Record<string, unknown>;\n const module = typeof e[\"module\"] === \"string\" ? (e[\"module\"] as string) : null;\n const severity = e[\"severity\"];\n if (module === null) return null;\n if (\n severity !== \"low\" &&\n severity !== \"moderate\" &&\n severity !== \"high\" &&\n severity !== \"critical\"\n )\n return null;\n const cves = Array.isArray(e[\"cves\"])\n ? (e[\"cves\"] as unknown[]).filter((c): c is string => typeof c === \"string\")\n : [];\n return {\n module,\n severity,\n title: typeof e[\"title\"] === \"string\" ? (e[\"title\"] as string) : \"\",\n cves,\n url: typeof e[\"url\"] === \"string\" ? (e[\"url\"] as string) : null,\n };\n}\n\n/** Parse the `Security advisories` JSON cell. null when absent/blank/unparseable/not-an-array\n * (treated as \"never audited\"); a valid array (possibly empty = audited clean) otherwise. */\nexport function parseSecurityAdvisories(raw: unknown): SecurityAdvisory[] | null {\n if (typeof raw !== \"string\" || raw.trim() === \"\") return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!Array.isArray(parsed)) return null;\n return parsed.map(normalizeSecurityAdvisory).filter((a): a is SecurityAdvisory => a !== null);\n}\n\nfunction securityAdvisoryFields(advisories: SecurityAdvisory[]): FieldSet {\n const capped = [...advisories]\n .sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n .slice(0, MAX_PERSISTED_ADVISORIES);\n // Always write — an empty array (\"[]\") clears a stale list when a once-vulnerable site goes clean.\n return { \"Security advisories\": JSON.stringify(capped) };\n}\n\nfunction securityFields(counts: SecurityCounts): FieldSet {\n return {\n \"Security Vulns Critical\": counts.critical,\n \"Security Vulns High\": counts.high,\n \"Security Vulns Moderate\": counts.moderate,\n \"Security Vulns Low\": counts.low,\n // Stamp freshness alongside the counts so the Security Updates auto-tick can require a recent\n // audit (a clean count from months ago must not silently keep ticking the box).\n \"Last security audit at\": new Date().toISOString(),\n };\n}\n\nfunction domainFields(result: DomainResult): FieldSet {\n const fields: FieldSet = { \"Domain checked at\": result.checkedAt };\n // Write the cert days UNCONDITIONALLY: a null (unresolved / no usable cert) must CLEAR any\n // previously-good value. Leaving a stale number in place — next to a freshly-stamped \"Domain\n // checked at\" — false-passes the Domain/DNS/SSL auto-tick (domainEvidence reads the stale\n // non-null value as a current pass) for a site that's actually down. null clears the cell in\n // Airtable; FieldSet's type doesn't model null, hence the cast through a widened record.\n (fields as Record<string, number | null>)[\"Cert days remaining\"] = result.certDaysRemaining;\n return fields;\n}\n\nfunction netlifyDeployFields(result: NetlifyDeployResult): FieldSet {\n // Write all three deploy fields UNCONDITIONALLY (null clears the cell): a null state /\n // deployedAt / logUrl this run means \"couldn't read it\" and must not leave a STALE value\n // sitting next to a fresh \"Deploy checked at\" — the dashboard would otherwise render a green\n // \"ready\" badge for a site whose latest deploy actually errored. FieldSet's type doesn't model\n // null, hence the cast through a widened record (same approach as domainFields).\n const fields: Record<string, string | null> = {\n \"Deploy status\": result.state,\n \"Last deploy at\": result.deployedAt,\n \"Deploy log URL\": result.logUrl,\n \"Deploy checked at\": result.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction browserFields(r: BrowserAuditFields): FieldSet {\n return {\n \"Crossbrowser OK\": r.desktopOk,\n \"Mobile OK\": r.mobileOk,\n \"Links OK\": r.linksOk,\n \"Broken links\": r.brokenLinks,\n \"Browser checked at\": r.checkedAt,\n };\n}\n\n/**\n * Write the four Lighthouse scores + a refreshed-at timestamp onto a Websites row.\n * Called by `audit lighthouse --write-airtable` after a successful audit run, so\n * the operator never has to paste numbers manually before drafting a report.\n */\nexport async function updateScores(\n base: AirtableBase,\n recordId: string,\n scores: LighthouseScores,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: scoreFields(scores) }]);\n}\n\n/**\n * Record (or clear) the per-site GA/Search enrichment health on the `Analytics\n * soft-fail at` column. `at` is an ISO timestamp when the site's last draft had a\n * GA/Search soft-failure, or `null` to clear it after a clean enrichment. The\n * caller (drafting) swallows errors: this column is operator-added, so until it\n * exists Airtable throws UNKNOWN_FIELD_NAME — which must not break a draft.\n */\nexport async function updateAnalyticsHealth(\n base: AirtableBase,\n recordId: string,\n at: string | null,\n): Promise<void> {\n const fields: Record<string, string | null> = { \"Analytics soft-fail at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n}\n\n/** Persist a11y violation count. */\nexport async function updateA11yCounts(\n base: AirtableBase,\n recordId: string,\n counts: A11yCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: a11yFields(counts) }]);\n}\n\n/** Persist deps drift counts (declared-range drift + real outdated installs). */\nexport async function updateDepsCounts(\n base: AirtableBase,\n recordId: string,\n counts: DepsCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: depsFields(counts) }]);\n}\n\n/** Persist security vulnerability counts by severity. */\nexport async function updateSecurityCounts(\n base: AirtableBase,\n recordId: string,\n counts: SecurityCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: securityFields(counts) }]);\n}\n\n/** Persist a site's auto-fix attempt counter. Its own one-field writer so the\n * nightly Renovate dispatch can update it without touching the audit's counts. */\nexport async function updateAutoFixAttempts(\n base: AirtableBase,\n recordId: string,\n attempts: number,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([\n { id: recordId, fields: { \"Security Auto-Fix Attempts\": attempts } },\n ]);\n}\n\n/** Generic single-field writer for the dashboard site-details editor. The caller\n * (setSiteDetail) restricts `column` to the EDITABLE_SITE_FIELDS allowlist, so this\n * never writes an arbitrary column from request input. */\nexport async function updateSiteField(\n base: AirtableBase,\n recordId: string,\n column: string,\n value: string,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: { [column]: value } }]);\n}\n\n/**\n * Persist all of a single audit run's results to one Websites row in ONE atomic\n * `update()` — instead of up to four sequential updates on the same id (which left\n * a row half-written on a mid-sequence failure and quadrupled the request volume).\n * Pass only the audit slices that produced real values; each present slice is merged\n * via the SAME field mappings the per-audit writers use. Omit a slice (or pass\n * undefined) to leave those columns untouched. Returns the merged FieldSet so the\n * caller can enumerate what was written.\n */\nexport async function updateAuditFields(\n base: AirtableBase,\n recordId: string,\n audits: {\n scores?: LighthouseScoreWriteback;\n a11y?: A11yCounts;\n deps?: DepsCounts;\n security?: SecurityCounts;\n securityAdvisories?: SecurityAdvisory[];\n domain?: DomainResult;\n browser?: BrowserAuditFields;\n netlifyDeploy?: NetlifyDeployResult;\n },\n): Promise<FieldSet> {\n const fields: FieldSet = {};\n if (audits.scores) Object.assign(fields, scoreFields(audits.scores));\n if (audits.a11y) Object.assign(fields, a11yFields(audits.a11y));\n if (audits.deps) Object.assign(fields, depsFields(audits.deps));\n if (audits.security) Object.assign(fields, securityFields(audits.security));\n // Separate slice (not folded into `security`) so the advisory list and the counts can be\n // written independently, but in practice the security audit supplies both together.\n if (audits.securityAdvisories)\n Object.assign(fields, securityAdvisoryFields(audits.securityAdvisories));\n if (audits.domain) Object.assign(fields, domainFields(audits.domain));\n if (audits.browser) Object.assign(fields, browserFields(audits.browser));\n if (audits.netlifyDeploy) Object.assign(fields, netlifyDeployFields(audits.netlifyDeploy));\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n return fields;\n}\n\n/** Persist the GitHub-signals sweep onto a Websites row (slice 2a). A null\n * `lastCommitAt` is OMITTED so a not-determined-this-run value never clobbers a\n * previously-good timestamp (mirrors updateDepsCounts' outdated handling). */\nexport async function updateGitHubSignals(\n base: AirtableBase,\n recordId: string,\n signals: {\n renovateFailingCis: number;\n ciState: string;\n lastCommitAt: string | null;\n sweptAt: string;\n },\n): Promise<void> {\n const fields: FieldSet = {\n \"Renovate Failing CIs\": signals.renovateFailingCis,\n \"Default Branch CI\": signals.ciState,\n \"GitHub Signals At\": signals.sweptAt,\n };\n if (signals.lastCommitAt !== null) {\n fields[\"Last Commit At\"] = signals.lastCommitAt;\n }\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n}\n\n/** Mark a site launched: flip Status → maintenance + stamp Launched at (M6b).\n * The first code that writes Status. Called after a Launch report sends. */\nexport async function updateLaunched(\n base: AirtableBase,\n recordId: string,\n at: string,\n): Promise<void> {\n const fields: FieldSet = { Status: \"maintenance\", \"Launched at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n}\n"],"mappings":";AAIO,IAAM,iBAAiB;AA0IvB,SAAS,SAAS,MAAsB;AAC7C,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AACzB;AAIA,SAAS,WAAW,KAA6B;AAC/C,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAQO,SAAS,mBAAmB,KAAoC;AACrE,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,OAAO;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,EAAG,QAAO;AAC3E,QAAM,IAAI;AACV,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,EAAE,MAAM,KAAK,EAAG,QAAO;AAC3D,MAAI,CAAC,EAAE,UAAU,OAAO,EAAE,WAAW,YAAY,MAAM,QAAQ,EAAE,MAAM,EAAG,QAAO;AACjF,QAAM,UAAyB;AAAA,IAC7B,OAAO,EAAE;AAAA,IACT,QAAQ,EAAE;AAAA,EACZ;AACA,MAAI,EAAE,YAAY,OAAW,SAAQ,UAAU,EAAE;AACjD,MAAI,MAAM,QAAQ,EAAE,EAAE,EAAG,SAAQ,KAAK,EAAE,GAAG,OA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W,OAAO,IAAI,CAAC;AAC9D,MAAI,OAAO,KAAM,QAAO,OAAO,QAAQ,WAAW,OAAO,IAAI,CAAC;AAC9D,MAAI,OAAO,SAAU,QAAO,OAAO,QAAQ,eAAe,OAAO,QAAQ,CAAC;AAG1E,MAAI,OAAO;AACT,WAAO,OAAO,QAAQ,uBAAuB,OAAO,kBAAkB,CAAC;AACzE,MAAI,OAAO,OAAQ,QAAO,OAAO,QAAQ,aAAa,OAAO,MAAM,CAAC;AACpE,MAAI,OAAO,QAAS,QAAO,OAAO,QAAQ,cAAc,OAAO,OAAO,CAAC;AACvE,MAAI,OAAO,cAAe,QAAO,OAAO,QAAQ,oBAAoB,OAAO,aAAa,CAAC;AACzF,QAAM,KAAK,cAAc,EAAE,OAAO,CAAC,EAAE,IAAI,UAAU,OAAO,CAAC,CAAC;AAC5D,SAAO;AACT;AAKA,eAAsB,oBACpB,MACA,UACA,SAMe;AACf,QAAM,SAAmB;AAAA,IACvB,wBAAwB,QAAQ;AAAA,IAChC,qBAAqB,QAAQ;AAAA,IAC7B,qBAAqB,QAAQ;AAAA,EAC/B;AACA,MAAI,QAAQ,iBAAiB,MAAM;AACjC,WAAO,gBAAgB,IAAI,QAAQ;AAAA,EACrC;AACA,QAAM,KAAK,cAAc,EAAE,OAAO,CAAC,EAAE,IAAI,UAAU,OAAO,CAAC,CAAC;AAC9D;AAIA,eAAsB,eACpB,MACA,UACA,IACe;AACf,QAAM,SAAmB,EAAE,QAAQ,eAAe,eAAe,GAAG;AACpE,QAAM,KAAK,cAAc,EAAE,OAAO,CAAC,EAAE,IAAI,UAAU,OAAO,CAAC,CAAC;AAC9D;","names":[]}
@@ -0,0 +1,211 @@
1
+ import {
2
+ siteSlug
3
+ } from "./chunk-BLD6AYJO.js";
4
+
5
+ // src/alerts/digest-collectors.ts
6
+ function dashboardUrl(baseUrl, siteName) {
7
+ return `${baseUrl.replace(/\/$/, "")}/s/${siteSlug(siteName)}`;
8
+ }
9
+ var GITHUB_SIGNALS_STALE_DAYS = 3;
10
+ var MS_PER_DAY = 24 * 60 * 60 * 1e3;
11
+ function gitHubSignalsStale(swept, now) {
12
+ if (swept === null) return true;
13
+ const ageMs = now.getTime() - Date.parse(swept);
14
+ if (!Number.isFinite(ageMs)) return true;
15
+ return ageMs > GITHUB_SIGNALS_STALE_DAYS * MS_PER_DAY;
16
+ }
17
+ var AUTO_FIX_EXHAUSTED_CYCLES = 3;
18
+ function collectVulnAlerts(sites, baseUrl) {
19
+ const items = [];
20
+ for (const s of sites) {
21
+ const critical = s.securityVulnsCritical ?? 0;
22
+ const high = s.securityVulnsHigh ?? 0;
23
+ const metric = critical + high;
24
+ if (metric <= 0) continue;
25
+ const attempts = s.securityAutoFixAttempts ?? 0;
26
+ const exhausted = attempts >= AUTO_FIX_EXHAUSTED_CYCLES;
27
+ const noun = metric === 1 ? "vuln" : "vulns";
28
+ items.push({
29
+ key: `vuln:${s.id}`,
30
+ kind: "vuln",
31
+ siteName: s.name,
32
+ title: exhausted ? `${metric} critical/high ${noun} \u2014 auto-fix failed (${attempts}\xD7)` : `${metric} critical/high ${noun}`,
33
+ url: dashboardUrl(baseUrl, s.name),
34
+ severity: exhausted || critical > 0 ? "critical" : "warning",
35
+ metric,
36
+ ...exhausted ? { autoFixExhausted: true } : {}
37
+ });
38
+ }
39
+ return items;
40
+ }
41
+ var LIGHTHOUSE_FLOOR = 75;
42
+ var LIGHTHOUSE_CATEGORIES = [
43
+ { field: "pScore", slug: "performance", label: "Performance" },
44
+ { field: "rScore", slug: "accessibility", label: "Accessibility" },
45
+ { field: "bpScore", slug: "best-practices", label: "Best Practices" },
46
+ { field: "seoScore", slug: "seo", label: "SEO" }
47
+ ];
48
+ function collectLighthouseAlerts(sites, baseUrl) {
49
+ const items = [];
50
+ for (const s of sites) {
51
+ for (const cat of LIGHTHOUSE_CATEGORIES) {
52
+ const score = s[cat.field];
53
+ if (score === null || score >= LIGHTHOUSE_FLOOR) continue;
54
+ items.push({
55
+ key: `lighthouse:${s.id}:${cat.slug}`,
56
+ kind: "lighthouse",
57
+ siteName: s.name,
58
+ title: `Lighthouse ${cat.label} ${score} (below ${LIGHTHOUSE_FLOOR})`,
59
+ url: dashboardUrl(baseUrl, s.name),
60
+ severity: "warning",
61
+ metric: 100 - score
62
+ });
63
+ }
64
+ }
65
+ return items;
66
+ }
67
+ function collectDeliveryFailures(reports, sitesById, baseUrl) {
68
+ const items = [];
69
+ for (const r of reports) {
70
+ if (r.deliveryStatus !== "bounced" && r.deliveryStatus !== "complained") continue;
71
+ const site = sitesById.get(r.siteId);
72
+ if (!site) continue;
73
+ const complained = r.deliveryStatus === "complained";
74
+ items.push({
75
+ key: `delivery:${r.id}`,
76
+ kind: "delivery",
77
+ siteName: site.name,
78
+ title: complained ? "Spam complaint on a sent report" : "A sent report bounced",
79
+ url: dashboardUrl(baseUrl, site.name),
80
+ severity: complained ? "critical" : "warning",
81
+ metric: 1
82
+ });
83
+ }
84
+ return items;
85
+ }
86
+ function collectRenovateAlerts(sites, baseUrl, now = /* @__PURE__ */ new Date()) {
87
+ const items = [];
88
+ for (const s of sites) {
89
+ if (gitHubSignalsStale(s.githubSignalsAt, now)) continue;
90
+ const n = s.renovateFailingCis ?? 0;
91
+ if (n <= 0) continue;
92
+ items.push({
93
+ key: `renovate:${s.id}`,
94
+ kind: "renovate",
95
+ siteName: s.name,
96
+ title: `${n} Renovate ${n === 1 ? "PR" : "PRs"} failing CI`,
97
+ url: dashboardUrl(baseUrl, s.name),
98
+ severity: "warning",
99
+ metric: n
100
+ });
101
+ }
102
+ return items;
103
+ }
104
+ function collectCiAlerts(sites, baseUrl, now = /* @__PURE__ */ new Date()) {
105
+ const items = [];
106
+ for (const s of sites) {
107
+ if (gitHubSignalsStale(s.githubSignalsAt, now)) continue;
108
+ if (s.defaultBranchCi !== "failing") continue;
109
+ items.push({
110
+ key: `ci:${s.id}`,
111
+ kind: "ci",
112
+ siteName: s.name,
113
+ title: "Default-branch CI failing",
114
+ url: dashboardUrl(baseUrl, s.name),
115
+ severity: "warning",
116
+ metric: 1
117
+ });
118
+ }
119
+ return items;
120
+ }
121
+ var ANALYTICS_SOFT_FAIL_STALE_DAYS = 45;
122
+ function collectAnalyticsFailures(sites, baseUrl, now = /* @__PURE__ */ new Date()) {
123
+ const items = [];
124
+ for (const s of sites) {
125
+ const at = s.analyticsSoftFailAt;
126
+ if (at === null) continue;
127
+ const ageMs = now.getTime() - Date.parse(at);
128
+ if (Number.isFinite(ageMs) && ageMs > ANALYTICS_SOFT_FAIL_STALE_DAYS * MS_PER_DAY) continue;
129
+ items.push({
130
+ key: `analytics:${s.id}`,
131
+ kind: "analytics",
132
+ siteName: s.name,
133
+ title: "GA/Search enrichment failing (analytics blank)",
134
+ url: dashboardUrl(baseUrl, s.name),
135
+ severity: "warning",
136
+ metric: 1
137
+ });
138
+ }
139
+ return items;
140
+ }
141
+
142
+ // src/alerts/digest-state.ts
143
+ function diffAttention(items, prior, today) {
144
+ const tagged = [];
145
+ const next = {};
146
+ for (const it of items) {
147
+ const was = prior[it.key];
148
+ let status;
149
+ let firstFlaggedAt;
150
+ if (!was) {
151
+ status = "new";
152
+ firstFlaggedAt = today;
153
+ } else if (it.metric > was.metric) {
154
+ status = "worse";
155
+ firstFlaggedAt = was.firstFlaggedAt;
156
+ } else {
157
+ status = "standing";
158
+ firstFlaggedAt = was.firstFlaggedAt;
159
+ }
160
+ tagged.push({ ...it, status });
161
+ next[it.key] = { metric: it.metric, firstFlaggedAt };
162
+ }
163
+ return { tagged, next };
164
+ }
165
+ var DIGEST_STATE_TABLE = "Digest State";
166
+ async function readDigestState(base) {
167
+ const rows = [];
168
+ await base(DIGEST_STATE_TABLE).select({ maxRecords: 1, pageSize: 1 }).eachPage((records, fetchNextPage) => {
169
+ for (const rec of records) rows.push({ id: rec.id, fields: rec.fields });
170
+ fetchNextPage();
171
+ });
172
+ const first = rows[0];
173
+ if (!first) return {};
174
+ const raw = first.fields["Snapshot"];
175
+ if (typeof raw !== "string") return {};
176
+ try {
177
+ return JSON.parse(raw);
178
+ } catch {
179
+ return {};
180
+ }
181
+ }
182
+ async function writeDigestState(base, snap, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
183
+ const rows = [];
184
+ await base(DIGEST_STATE_TABLE).select({ maxRecords: 1, pageSize: 1 }).eachPage((records, fetchNextPage) => {
185
+ for (const rec of records) rows.push({ id: rec.id });
186
+ fetchNextPage();
187
+ });
188
+ const fields = {
189
+ Snapshot: JSON.stringify(snap),
190
+ "Updated At": updatedAt
191
+ };
192
+ const existing = rows[0];
193
+ if (existing) {
194
+ await base(DIGEST_STATE_TABLE).update([{ id: existing.id, fields }]);
195
+ } else {
196
+ await base(DIGEST_STATE_TABLE).create([{ fields }]);
197
+ }
198
+ }
199
+
200
+ export {
201
+ collectVulnAlerts,
202
+ collectLighthouseAlerts,
203
+ collectDeliveryFailures,
204
+ collectRenovateAlerts,
205
+ collectCiAlerts,
206
+ collectAnalyticsFailures,
207
+ diffAttention,
208
+ readDigestState,
209
+ writeDigestState
210
+ };
211
+ //# sourceMappingURL=chunk-BMDBOPN3.js.map