@reddoorla/maintenance 0.55.0 → 0.56.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.
- package/README.md +3 -1
- package/dist/airtable-2BJX4ATJ.js +9 -0
- package/dist/airtable-2BJX4ATJ.js.map +1 -0
- package/dist/announce-JEVCDDKL.js +171 -0
- package/dist/announce-JEVCDDKL.js.map +1 -0
- package/dist/bump-deps-O3SOLQYY.js +57 -0
- package/dist/bump-deps-O3SOLQYY.js.map +1 -0
- package/dist/chunk-2X322ZES.js +99 -0
- package/dist/chunk-2X322ZES.js.map +1 -0
- package/dist/chunk-4NAOR44V.js +153 -0
- package/dist/chunk-4NAOR44V.js.map +1 -0
- package/dist/chunk-4PY4I5OR.js +1167 -0
- package/dist/chunk-4PY4I5OR.js.map +1 -0
- package/dist/chunk-5WL3ET24.js +203 -0
- package/dist/chunk-5WL3ET24.js.map +1 -0
- package/dist/chunk-6LIWDIXU.js +38 -0
- package/dist/chunk-6LIWDIXU.js.map +1 -0
- package/dist/chunk-6VAL7XJT.js +52 -0
- package/dist/chunk-6VAL7XJT.js.map +1 -0
- package/dist/chunk-BWLUNY7L.js +585 -0
- package/dist/chunk-BWLUNY7L.js.map +1 -0
- package/dist/chunk-CASCWQQX.js +161 -0
- package/dist/chunk-CASCWQQX.js.map +1 -0
- package/dist/chunk-CLVTVDOU.js +274 -0
- package/dist/chunk-CLVTVDOU.js.map +1 -0
- package/dist/chunk-D3DQFC32.js +79 -0
- package/dist/chunk-D3DQFC32.js.map +1 -0
- package/dist/chunk-DIVB6ZF7.js +217 -0
- package/dist/chunk-DIVB6ZF7.js.map +1 -0
- package/dist/chunk-EYODPUHV.js +37 -0
- package/dist/chunk-EYODPUHV.js.map +1 -0
- package/dist/chunk-FDIFTIXC.js +70 -0
- package/dist/chunk-FDIFTIXC.js.map +1 -0
- package/dist/chunk-FUD4I2ZW.js +35 -0
- package/dist/chunk-FUD4I2ZW.js.map +1 -0
- package/dist/chunk-HG5DTFNF.js +62 -0
- package/dist/chunk-HG5DTFNF.js.map +1 -0
- package/dist/chunk-HN6I2XWI.js +65 -0
- package/dist/chunk-HN6I2XWI.js.map +1 -0
- package/dist/chunk-HVOOCK6L.js +84 -0
- package/dist/chunk-HVOOCK6L.js.map +1 -0
- package/dist/chunk-IMIR7SC2.js +51 -0
- package/dist/chunk-IMIR7SC2.js.map +1 -0
- package/dist/chunk-J3OPWFZE.js +64 -0
- package/dist/chunk-J3OPWFZE.js.map +1 -0
- package/dist/chunk-JNXCDUYB.js +211 -0
- package/dist/chunk-JNXCDUYB.js.map +1 -0
- package/dist/chunk-JQG222CI.js +49 -0
- package/dist/chunk-JQG222CI.js.map +1 -0
- package/dist/chunk-LKGVSM2O.js +43 -0
- package/dist/chunk-LKGVSM2O.js.map +1 -0
- package/dist/chunk-LYCKN7ZR.js +41 -0
- package/dist/chunk-LYCKN7ZR.js.map +1 -0
- package/dist/chunk-O65I7G7G.js +246 -0
- package/dist/chunk-O65I7G7G.js.map +1 -0
- package/dist/chunk-OCS7SZUZ.js +243 -0
- package/dist/chunk-OCS7SZUZ.js.map +1 -0
- package/dist/chunk-OGGRFBL4.js +14 -0
- package/dist/chunk-OGGRFBL4.js.map +1 -0
- package/dist/chunk-OQPMZ6BM.js +368 -0
- package/dist/chunk-OQPMZ6BM.js.map +1 -0
- package/dist/chunk-OTGB6YQO.js +52 -0
- package/dist/chunk-OTGB6YQO.js.map +1 -0
- package/dist/chunk-PF6BNYGE.js +162 -0
- package/dist/chunk-PF6BNYGE.js.map +1 -0
- package/dist/chunk-QTHKOIFJ.js +13 -0
- package/dist/chunk-QTHKOIFJ.js.map +1 -0
- package/dist/chunk-U5SZ4FOP.js +26 -0
- package/dist/chunk-U5SZ4FOP.js.map +1 -0
- package/dist/chunk-VXSX2FHO.js +269 -0
- package/dist/chunk-VXSX2FHO.js.map +1 -0
- package/dist/chunk-W3G7XFBZ.js +444 -0
- package/dist/chunk-W3G7XFBZ.js.map +1 -0
- package/dist/chunk-WEKL2HYJ.js +31 -0
- package/dist/chunk-WEKL2HYJ.js.map +1 -0
- package/dist/chunk-WVRPOXKH.js +74 -0
- package/dist/chunk-WVRPOXKH.js.map +1 -0
- package/dist/chunk-XKOZUVK2.js +121 -0
- package/dist/chunk-XKOZUVK2.js.map +1 -0
- package/dist/chunk-XO2RUYVM.js +138 -0
- package/dist/chunk-XO2RUYVM.js.map +1 -0
- package/dist/chunk-XTK5VIQB.js +97 -0
- package/dist/chunk-XTK5VIQB.js.map +1 -0
- package/dist/chunk-XXTZBPUY.js +9 -0
- package/dist/chunk-XXTZBPUY.js.map +1 -0
- package/dist/chunk-ZYBOT5PM.js +153 -0
- package/dist/chunk-ZYBOT5PM.js.map +1 -0
- package/dist/cli/bin.js +75 -7785
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.js +37 -2336
- package/dist/cli/commands/audit.js.map +1 -1
- package/dist/client-EPVO3FEH.js +10 -0
- package/dist/client-EPVO3FEH.js.map +1 -0
- package/dist/client-JA6QLEDW.js +48 -0
- package/dist/client-JA6QLEDW.js.map +1 -0
- package/dist/configs/lighthouse.js +4 -31
- package/dist/configs/lighthouse.js.map +1 -1
- package/dist/configs/playwright-a11y.js +6 -33
- package/dist/configs/playwright-a11y.js.map +1 -1
- package/dist/convert-to-pnpm-UR64X3OX.js +51 -0
- package/dist/convert-to-pnpm-UR64X3OX.js.map +1 -0
- package/dist/db-AXKMRTVA.js +23 -0
- package/dist/db-AXKMRTVA.js.map +1 -0
- package/dist/digest-YTO73BEO.js +408 -0
- package/dist/digest-YTO73BEO.js.map +1 -0
- package/dist/forms/index.js +3 -8
- package/dist/forms/index.js.map +1 -1
- package/dist/github-signals-YD64R2AF.js +122 -0
- package/dist/github-signals-YD64R2AF.js.map +1 -0
- package/dist/index.js +102 -4757
- package/dist/index.js.map +1 -1
- package/dist/init-JITQXFVL.js +85 -0
- package/dist/init-JITQXFVL.js.map +1 -0
- package/dist/launch-HXHEL6ID.js +207 -0
- package/dist/launch-HXHEL6ID.js.map +1 -0
- package/dist/lighthouse-airtable-4FKYKFH6.js +12 -0
- package/dist/lighthouse-airtable-4FKYKFH6.js.map +1 -0
- package/dist/migrate-P2LS4WXI.js +7 -0
- package/dist/migrate-P2LS4WXI.js.map +1 -0
- package/dist/onboard-TCQOP2W4.js +69 -0
- package/dist/onboard-TCQOP2W4.js.map +1 -0
- package/dist/orchestrate-RMSBHLQK.js +19 -0
- package/dist/orchestrate-RMSBHLQK.js.map +1 -0
- package/dist/recipes/sync-configs.js +9 -505
- package/dist/recipes/sync-configs.js.map +1 -1
- package/dist/renovate-dispatch-ZGLXNPEK.js +97 -0
- package/dist/renovate-dispatch-ZGLXNPEK.js.map +1 -0
- package/dist/report-SD3CNBOQ.js +240 -0
- package/dist/report-SD3CNBOQ.js.map +1 -0
- package/dist/resend-G2BJMAQV.js +7 -0
- package/dist/resend-G2BJMAQV.js.map +1 -0
- package/dist/self-updating-CIUMOMYI.js +61 -0
- package/dist/self-updating-CIUMOMYI.js.map +1 -0
- package/dist/svelte-codemods-BYRJAU7I.js +51 -0
- package/dist/svelte-codemods-BYRJAU7I.js.map +1 -0
- package/dist/sync-configs-JPRLAW5J.js +109 -0
- package/dist/sync-configs-JPRLAW5J.js.map +1 -0
- package/dist/upgrade-ERA45EVR.js +64 -0
- package/dist/upgrade-ERA45EVR.js.map +1 -0
- package/dist/util/git.js +19 -76
- package/dist/util/git.js.map +1 -1
- package/dist/util/pkg.js +5 -45
- package/dist/util/pkg.js.map +1 -1
- package/dist/websites-X5DLC2PC.js +43 -0
- package/dist/websites-X5DLC2PC.js.map +1 -0
- package/dist/write-audits-to-airtable-CE4POBAF.js +13 -0
- package/dist/write-audits-to-airtable-CE4POBAF.js.map +1 -0
- package/package.json +13 -12
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// src/util/html.ts
|
|
2
|
+
function escapeHtml(s) {
|
|
3
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
4
|
+
}
|
|
5
|
+
function safeUrl(raw) {
|
|
6
|
+
try {
|
|
7
|
+
const u = new URL(raw);
|
|
8
|
+
if (u.protocol === "http:" || u.protocol === "https:") return raw;
|
|
9
|
+
} catch {
|
|
10
|
+
}
|
|
11
|
+
return "#";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/reports/checklist.ts
|
|
15
|
+
var MAINTENANCE_CHECKLIST = [
|
|
16
|
+
{ key: "deploy", label: "Deploy & Function Health", field: "Maint: Deploy & Function Health" },
|
|
17
|
+
{ key: "cms", label: "CMS Checked", field: "Maint: CMS Checked" },
|
|
18
|
+
{ key: "domain", label: "Domain, DNS & SSL", field: "Maint: Domain, DNS & SSL" },
|
|
19
|
+
{ key: "google", label: "Google Indexed", field: "Maint: Google Indexed" },
|
|
20
|
+
{ key: "security", label: "Security Updates", field: "Maint: Security Updates" },
|
|
21
|
+
{ key: "uptime", label: "Uptime Checked", field: "Maint: Uptime Checked" }
|
|
22
|
+
];
|
|
23
|
+
var TESTING_CHECKLIST = [
|
|
24
|
+
{ key: "desktop", label: "Desktop Browsers", field: "Test: Desktop Browsers" },
|
|
25
|
+
{ key: "mobile", label: "Mobile Browsers", field: "Test: Mobile Browsers" },
|
|
26
|
+
{ key: "titles", label: "Page Titles & Meta", field: "Test: Page Titles & Meta" },
|
|
27
|
+
{ key: "links", label: "Links & Navigation", field: "Test: Links & Navigation" },
|
|
28
|
+
{ key: "forms", label: "Form Functionality", field: "Test: Form Functionality" },
|
|
29
|
+
{
|
|
30
|
+
key: "interactions",
|
|
31
|
+
label: "Interactions & Animations",
|
|
32
|
+
field: "Test: Interactions & Animations"
|
|
33
|
+
},
|
|
34
|
+
// `field` keeps its original Airtable column name ("…Verified After Updates") even though
|
|
35
|
+
// the client-facing label is now "Tested After Updates" — the column holds operator data,
|
|
36
|
+
// so renaming the label is display-only and avoids a live-base column migration.
|
|
37
|
+
{ key: "updates", label: "Tested After Updates", field: "Test: Verified After Updates" }
|
|
38
|
+
];
|
|
39
|
+
var ALL_CHECKLIST_FIELDS = [...MAINTENANCE_CHECKLIST, ...TESTING_CHECKLIST].map(
|
|
40
|
+
(i) => i.field
|
|
41
|
+
);
|
|
42
|
+
function checklistFor(type) {
|
|
43
|
+
if (type === "Maintenance") return MAINTENANCE_CHECKLIST;
|
|
44
|
+
if (type === "Testing") return [...MAINTENANCE_CHECKLIST, ...TESTING_CHECKLIST];
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
function isChecklistComplete(report) {
|
|
48
|
+
return checklistFor(report.reportType).every((i) => report.checklist[i.field] === true);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/reports/airtable/reports.ts
|
|
52
|
+
var REPORTS_TABLE = "Reports";
|
|
53
|
+
var REPORT_TYPES = ["Maintenance", "Testing", "Launch", "Announcement"];
|
|
54
|
+
function toReportType(raw) {
|
|
55
|
+
if (raw && REPORT_TYPES.includes(raw)) return raw;
|
|
56
|
+
if (raw)
|
|
57
|
+
console.warn(`[reports] unknown Report type ${JSON.stringify(raw)} \u2014 treating as Maintenance`);
|
|
58
|
+
return "Maintenance";
|
|
59
|
+
}
|
|
60
|
+
function isPendingApproval(r) {
|
|
61
|
+
return r.draftReady && !r.approvedToSend && r.sentAt === null;
|
|
62
|
+
}
|
|
63
|
+
function mapRow(rec) {
|
|
64
|
+
const f = rec.fields;
|
|
65
|
+
const linkSites = f["Site"] ?? [];
|
|
66
|
+
const html = (f["Rendered HTML"] ?? [])[0] ?? null;
|
|
67
|
+
return {
|
|
68
|
+
id: rec.id,
|
|
69
|
+
reportId: String(f["Report ID"] ?? ""),
|
|
70
|
+
siteId: linkSites[0] ?? "",
|
|
71
|
+
reportType: toReportType(f["Report type"]),
|
|
72
|
+
period: f["Period"] ?? null,
|
|
73
|
+
periodStart: f["Period start"] ?? null,
|
|
74
|
+
periodEnd: f["Period end"] ?? null,
|
|
75
|
+
completedOn: f["Completed on"] ?? null,
|
|
76
|
+
lighthouse: lighthouseFromFields(f),
|
|
77
|
+
gaUsersCurrent: f["GA users (period)"] ?? null,
|
|
78
|
+
gaUsersPrevious: f["GA users (prev period)"] ?? null,
|
|
79
|
+
searchFoundPage1: typeof f["Search found page 1"] === "boolean" ? f["Search found page 1"] : null,
|
|
80
|
+
searchPosition: f["Search position"] ?? null,
|
|
81
|
+
lastTestedDate: f["Last tested date"] ?? null,
|
|
82
|
+
commentary: f["Commentary"] ?? null,
|
|
83
|
+
subjectOverride: f["Subject override"] ?? null,
|
|
84
|
+
draftReady: Boolean(f["Draft ready"]),
|
|
85
|
+
approvedToSend: Boolean(f["Approved to send"]),
|
|
86
|
+
sentAt: f["Sent at"] ?? null,
|
|
87
|
+
approvedAt: f["Approved At"] ?? null,
|
|
88
|
+
approvedBy: f["Approved By"] ?? null,
|
|
89
|
+
deliveryStatus: f["Delivery status"] ?? "pending",
|
|
90
|
+
renderedHtmlAttachment: html,
|
|
91
|
+
resendMessageId: f["Resend message ID"] ?? null,
|
|
92
|
+
checklist: Object.fromEntries(ALL_CHECKLIST_FIELDS.map((name) => [name, Boolean(f[name])])),
|
|
93
|
+
autoEvidence: parseAutoEvidence(f["Checklist auto-evidence"])
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function parseAutoEvidence(raw) {
|
|
97
|
+
if (typeof raw !== "string" || !raw.trim()) return null;
|
|
98
|
+
let parsed;
|
|
99
|
+
try {
|
|
100
|
+
parsed = JSON.parse(raw);
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
105
|
+
const out = {};
|
|
106
|
+
for (const [field, v] of Object.entries(parsed)) {
|
|
107
|
+
if (!v || typeof v !== "object") continue;
|
|
108
|
+
const o = v;
|
|
109
|
+
if (o.result !== "pass" && o.result !== "fail" && o.result !== "unknown") continue;
|
|
110
|
+
out[field] = {
|
|
111
|
+
result: o.result,
|
|
112
|
+
checkedAt: typeof o.checkedAt === "string" ? o.checkedAt : null,
|
|
113
|
+
note: typeof o.note === "string" ? o.note : ""
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
117
|
+
}
|
|
118
|
+
function lighthouseFromFields(f) {
|
|
119
|
+
const p = f["Lighthouse \u2014 Performance"];
|
|
120
|
+
const a = f["Lighthouse \u2014 Accessibility"];
|
|
121
|
+
const b = f["Lighthouse \u2014 Best Practices"];
|
|
122
|
+
const s = f["Lighthouse \u2014 SEO"];
|
|
123
|
+
if (typeof p !== "number" || typeof a !== "number" || typeof b !== "number" || typeof s !== "number")
|
|
124
|
+
return null;
|
|
125
|
+
return { performance: p, accessibility: a, bestPractices: b, seo: s };
|
|
126
|
+
}
|
|
127
|
+
function ymd(d) {
|
|
128
|
+
return d.toISOString().slice(0, 10);
|
|
129
|
+
}
|
|
130
|
+
function escapeFormulaString(s) {
|
|
131
|
+
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
132
|
+
}
|
|
133
|
+
async function createDraft(base, input) {
|
|
134
|
+
const fields = {
|
|
135
|
+
"Report ID": input.reportId,
|
|
136
|
+
Site: [input.siteId],
|
|
137
|
+
"Report type": input.reportType,
|
|
138
|
+
"Period start": ymd(input.periodStart),
|
|
139
|
+
"Period end": ymd(input.periodEnd),
|
|
140
|
+
"Completed on": ymd(input.completedOn),
|
|
141
|
+
"Lighthouse \u2014 Performance": input.lighthouse.performance,
|
|
142
|
+
"Lighthouse \u2014 Accessibility": input.lighthouse.accessibility,
|
|
143
|
+
"Lighthouse \u2014 Best Practices": input.lighthouse.bestPractices,
|
|
144
|
+
"Lighthouse \u2014 SEO": input.lighthouse.seo,
|
|
145
|
+
"Delivery status": "pending"
|
|
146
|
+
};
|
|
147
|
+
if (input.lastTestedDate) fields["Last tested date"] = ymd(input.lastTestedDate);
|
|
148
|
+
if (input.gaUsersCurrent !== void 0) fields["GA users (period)"] = input.gaUsersCurrent;
|
|
149
|
+
if (input.gaUsersPrevious !== void 0) fields["GA users (prev period)"] = input.gaUsersPrevious;
|
|
150
|
+
if (input.searchFoundPage1 !== void 0) fields["Search found page 1"] = input.searchFoundPage1;
|
|
151
|
+
if (input.searchPosition !== void 0) fields["Search position"] = input.searchPosition;
|
|
152
|
+
if (input.period !== void 0) fields["Period"] = input.period;
|
|
153
|
+
if (input.subjectOverride !== void 0) fields["Subject override"] = input.subjectOverride;
|
|
154
|
+
for (const field of input.checklistTicks ?? []) fields[field] = true;
|
|
155
|
+
if (input.autoEvidence && Object.keys(input.autoEvidence).length > 0) {
|
|
156
|
+
fields["Checklist auto-evidence"] = JSON.stringify(input.autoEvidence);
|
|
157
|
+
}
|
|
158
|
+
const created = await base(REPORTS_TABLE).create([{ fields }]);
|
|
159
|
+
const rec = created[0];
|
|
160
|
+
if (!rec) throw new Error("Airtable create returned no records");
|
|
161
|
+
return mapRow({ id: rec.id, fields: rec.fields });
|
|
162
|
+
}
|
|
163
|
+
async function setDraftReady(base, recordId, ready) {
|
|
164
|
+
await base(REPORTS_TABLE).update([{ id: recordId, fields: { "Draft ready": ready } }]);
|
|
165
|
+
}
|
|
166
|
+
async function updateReportScores(base, recordId, scores, completedOn, enrichment) {
|
|
167
|
+
const fields = {
|
|
168
|
+
"Lighthouse \u2014 Performance": scores.performance,
|
|
169
|
+
"Lighthouse \u2014 Accessibility": scores.accessibility,
|
|
170
|
+
"Lighthouse \u2014 Best Practices": scores.bestPractices,
|
|
171
|
+
"Lighthouse \u2014 SEO": scores.seo
|
|
172
|
+
};
|
|
173
|
+
if (completedOn) fields["Completed on"] = ymd(completedOn);
|
|
174
|
+
if (enrichment?.gaUsersCurrent !== void 0)
|
|
175
|
+
fields["GA users (period)"] = enrichment.gaUsersCurrent;
|
|
176
|
+
if (enrichment?.gaUsersPrevious !== void 0)
|
|
177
|
+
fields["GA users (prev period)"] = enrichment.gaUsersPrevious;
|
|
178
|
+
if (enrichment?.searchFoundPage1 !== void 0)
|
|
179
|
+
fields["Search found page 1"] = enrichment.searchFoundPage1;
|
|
180
|
+
if (enrichment?.searchPosition !== void 0)
|
|
181
|
+
fields["Search position"] = enrichment.searchPosition;
|
|
182
|
+
await base(REPORTS_TABLE).update([{ id: recordId, fields }]);
|
|
183
|
+
}
|
|
184
|
+
async function listSendableReports(base) {
|
|
185
|
+
const out = [];
|
|
186
|
+
await base(REPORTS_TABLE).select({
|
|
187
|
+
filterByFormula: "AND({Draft ready} = TRUE(), {Approved to send} = TRUE(), {Sent at} = BLANK())",
|
|
188
|
+
pageSize: 100
|
|
189
|
+
}).eachPage((records, fetchNextPage) => {
|
|
190
|
+
for (const rec of records) out.push(mapRow({ id: rec.id, fields: rec.fields }));
|
|
191
|
+
fetchNextPage();
|
|
192
|
+
});
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
async function listAllReports(base) {
|
|
196
|
+
const out = [];
|
|
197
|
+
await base(REPORTS_TABLE).select({ pageSize: 100 }).eachPage((records, fetchNextPage) => {
|
|
198
|
+
for (const rec of records) out.push(mapRow({ id: rec.id, fields: rec.fields }));
|
|
199
|
+
fetchNextPage();
|
|
200
|
+
});
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
async function listReportsForSite(base, siteId) {
|
|
204
|
+
return (await listAllReports(base)).filter((r) => r.siteId === siteId);
|
|
205
|
+
}
|
|
206
|
+
async function stampSent(base, recordId, sentAt, messageId) {
|
|
207
|
+
const fields = { "Sent at": sentAt.toISOString() };
|
|
208
|
+
if (messageId !== null) fields["Resend message ID"] = messageId;
|
|
209
|
+
await base(REPORTS_TABLE).update([
|
|
210
|
+
{
|
|
211
|
+
id: recordId,
|
|
212
|
+
fields
|
|
213
|
+
}
|
|
214
|
+
]);
|
|
215
|
+
}
|
|
216
|
+
async function findReportByPeriod(base, siteId, reportType, period) {
|
|
217
|
+
const safeType = escapeFormulaString(reportType);
|
|
218
|
+
const safePeriod = escapeFormulaString(period);
|
|
219
|
+
const formula = `AND({Report type} = "${safeType}", {Period} = "${safePeriod}")`;
|
|
220
|
+
const rows = [];
|
|
221
|
+
await base(REPORTS_TABLE).select({ filterByFormula: formula, pageSize: 100 }).eachPage((records, fetchNextPage) => {
|
|
222
|
+
for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));
|
|
223
|
+
fetchNextPage();
|
|
224
|
+
});
|
|
225
|
+
return rows.find((r) => r.siteId === siteId) ?? null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export {
|
|
229
|
+
escapeHtml,
|
|
230
|
+
safeUrl,
|
|
231
|
+
checklistFor,
|
|
232
|
+
isChecklistComplete,
|
|
233
|
+
isPendingApproval,
|
|
234
|
+
createDraft,
|
|
235
|
+
setDraftReady,
|
|
236
|
+
updateReportScores,
|
|
237
|
+
listSendableReports,
|
|
238
|
+
listAllReports,
|
|
239
|
+
listReportsForSite,
|
|
240
|
+
stampSent,
|
|
241
|
+
findReportByPeriod
|
|
242
|
+
};
|
|
243
|
+
//# sourceMappingURL=chunk-OCS7SZUZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/util/html.ts","../src/reports/checklist.ts","../src/reports/airtable/reports.ts"],"sourcesContent":["/**\n * Shared HTML/XML escape. One implementation behind the dashboard renderers\n * (`src/dashboard/render.ts`, `fleet-render.ts`), the daily digest\n * (`src/reports/digest.ts`), and the MJML email templates\n * (`src/reports/*-email/template.ts`).\n *\n * The set is the strict-XML set (`& < > \" '`), which is exactly what MJML's\n * `validationLevel: \"strict\"` parser needs and a superset of what plain HTML text\n * interpolation needs — so the SAME function serves both sinks. Site names\n * (e.g. \"Brown & Co\"), URLs, and operator commentary must not break the markup or\n * inject. The MJML templates re-export this as `escapeXml` for their callers.\n */\nexport function escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n/** Allow only http(s) URLs in an href context; everything else collapses to \"#\". */\nexport function safeUrl(raw: string): string {\n try {\n const u = new URL(raw);\n if (u.protocol === \"http:\" || u.protocol === \"https:\") return raw;\n } catch {\n // fall through\n }\n return \"#\";\n}\n","import type { ReportType } from \"./types.js\";\n\n/**\n * One operator checklist item: a stable `key`, its display `label` (which mirrors\n * the client email's checklist line — kept in sync by a test against DEFAULT_COPY),\n * and the exact Airtable checkbox column `field` it reads/writes.\n */\nexport type ChecklistItem = { key: string; label: string; field: string };\n\n/**\n * The 6 Maintenance-report items. `label`s mirror DEFAULT_COPY.maintenanceChecks\n * (same order — \"Google Indexed\" MUST stay at index 3; the email template special-cases\n * that row to inject the live search position).\n */\nexport const MAINTENANCE_CHECKLIST: ChecklistItem[] = [\n { key: \"deploy\", label: \"Deploy & Function Health\", field: \"Maint: Deploy & Function Health\" },\n { key: \"cms\", label: \"CMS Checked\", field: \"Maint: CMS Checked\" },\n { key: \"domain\", label: \"Domain, DNS & SSL\", field: \"Maint: Domain, DNS & SSL\" },\n { key: \"google\", label: \"Google Indexed\", field: \"Maint: Google Indexed\" },\n { key: \"security\", label: \"Security Updates\", field: \"Maint: Security Updates\" },\n { key: \"uptime\", label: \"Uptime Checked\", field: \"Maint: Uptime Checked\" },\n];\n\n/** The 7 Testing-report items. `label`s mirror DEFAULT_COPY.testingChecklist. */\nexport const TESTING_CHECKLIST: ChecklistItem[] = [\n { key: \"desktop\", label: \"Desktop Browsers\", field: \"Test: Desktop Browsers\" },\n { key: \"mobile\", label: \"Mobile Browsers\", field: \"Test: Mobile Browsers\" },\n { key: \"titles\", label: \"Page Titles & Meta\", field: \"Test: Page Titles & Meta\" },\n { key: \"links\", label: \"Links & Navigation\", field: \"Test: Links & Navigation\" },\n { key: \"forms\", label: \"Form Functionality\", field: \"Test: Form Functionality\" },\n {\n key: \"interactions\",\n label: \"Interactions & Animations\",\n field: \"Test: Interactions & Animations\",\n },\n // `field` keeps its original Airtable column name (\"…Verified After Updates\") even though\n // the client-facing label is now \"Tested After Updates\" — the column holds operator data,\n // so renaming the label is display-only and avoids a live-base column migration.\n { key: \"updates\", label: \"Tested After Updates\", field: \"Test: Verified After Updates\" },\n];\n\n/** All 13 Airtable checkbox column names. mapRow reads exactly these into the row's checklist. */\nexport const ALL_CHECKLIST_FIELDS: string[] = [...MAINTENANCE_CHECKLIST, ...TESTING_CHECKLIST].map(\n (i) => i.field,\n);\n\n/**\n * The checklist that gates a report of the given type, in the order the email renders it.\n * Maintenance gates on its 6 items. A Testing pass also performs the maintenance checks —\n * and the Testing email shows BOTH lists — so a Testing report gates on all 13\n * (maintenance first, then testing). Launch/Announcement have no checklist (the gate is\n * vacuously satisfied). PURE.\n */\nexport function checklistFor(type: ReportType): ChecklistItem[] {\n if (type === \"Maintenance\") return MAINTENANCE_CHECKLIST;\n if (type === \"Testing\") return [...MAINTENANCE_CHECKLIST, ...TESTING_CHECKLIST];\n return [];\n}\n\n/**\n * True when every checklist item for the report's type is checked. Launch/Announcement\n * have an empty checklist → vacuously true. A missing or false cell → incomplete. PURE —\n * the single predicate behind both the approve gate and the send gate.\n */\nexport function isChecklistComplete(report: {\n reportType: ReportType;\n checklist: Record<string, boolean>;\n}): boolean {\n return checklistFor(report.reportType).every((i) => report.checklist[i.field] === true);\n}\n","import type { FieldSet, Records } from \"airtable\";\nimport type { AirtableBase } from \"./client.js\";\nimport type { ReportType, LighthouseScores } from \"../types.js\";\nimport { ALL_CHECKLIST_FIELDS } from \"../checklist.js\";\nimport type { EvidenceRecord } from \"../auto-tick.js\";\n\nexport const REPORTS_TABLE = \"Reports\";\n\nconst REPORT_TYPES: readonly ReportType[] = [\"Maintenance\", \"Testing\", \"Launch\", \"Announcement\"];\n\n/** Coerce the Airtable `Report type` (a single-select string) to a known\n * ReportType. A bare `as ReportType` cast is a compile-time lie: if the\n * single-select gains an unexpected option, the bad value flows to render.ts,\n * where `reportType === \"Launch\"` silently falls through to the Maintenance\n * template. Validate at the boundary; warn + default to \"Maintenance\" so an\n * unknown type is VISIBLE in the logs rather than silently mis-templated. */\nexport function toReportType(raw: string | undefined): ReportType {\n if (raw && (REPORT_TYPES as readonly string[]).includes(raw)) return raw as ReportType;\n if (raw)\n console.warn(`[reports] unknown Report type ${JSON.stringify(raw)} — treating as Maintenance`);\n return \"Maintenance\";\n}\n\nexport type DeliveryStatus = \"pending\" | \"delivered\" | \"bounced\" | \"complained\";\n\nexport type ReportRow = {\n id: string;\n reportId: string;\n siteId: string;\n reportType: ReportType;\n /** UTC `YYYY-MM` recurrence key (idempotency for search-before-create). Null on legacy rows. */\n period: string | null;\n periodStart: string | null;\n periodEnd: string | null;\n completedOn: string | null;\n lighthouse: LighthouseScores | null;\n gaUsersCurrent: number | null;\n gaUsersPrevious: number | null;\n searchFoundPage1: boolean | null;\n searchPosition: number | null;\n lastTestedDate: string | null;\n commentary: string | null;\n subjectOverride: string | null;\n draftReady: boolean;\n approvedToSend: boolean;\n sentAt: string | null;\n approvedAt: string | null;\n approvedBy: string | null;\n deliveryStatus: DeliveryStatus;\n renderedHtmlAttachment: { url: string; filename: string } | null;\n /** Read out of the Resend response and stored in a hidden field; needed for webhook reconciliation. */\n resendMessageId: string | null;\n /** The 12 operator-checklist checkboxes, keyed by their Airtable column name (ALL_CHECKLIST_FIELDS);\n * missing/false cells read false. Maintenance/Testing reports gate approve+send on the relevant\n * subset (see src/reports/checklist.ts). */\n checklist: Record<string, boolean>;\n /** Snapshot of the auto-tick evidence at draft time, keyed by checklist field → evidence\n * record. Null when the report predates auto-tick or carried no auto-checked items. Drives the\n * dashboard's green/amber badges; the gate still reads the booleans, not this. */\n autoEvidence: Record<string, EvidenceRecord> | null;\n};\n\n/**\n * The \"Ready for your yes\" gate: Draft ready ∧ ¬Approved to send ∧ Sent at BLANK.\n * The single source of truth for \"pending the operator's approval\" — `listPendingApproval`,\n * `runDigest`'s ready-list, the per-site dashboard, and the fleet cockpit all key off this\n * one predicate so the surfaces can't drift.\n */\nexport function isPendingApproval(r: ReportRow): boolean {\n return r.draftReady && !r.approvedToSend && r.sentAt === null;\n}\n\nfunction mapRow(rec: { id: string; fields: Record<string, unknown> }): ReportRow {\n const f = rec.fields;\n const linkSites = (f[\"Site\"] as string[] | undefined) ?? [];\n const html =\n ((f[\"Rendered HTML\"] as Array<{ url: string; filename: string }> | undefined) ?? [])[0] ?? null;\n return {\n id: rec.id,\n reportId: String(f[\"Report ID\"] ?? \"\"),\n siteId: linkSites[0] ?? \"\",\n reportType: toReportType(f[\"Report type\"] as string | undefined),\n period: (f[\"Period\"] as string | undefined) ?? null,\n periodStart: (f[\"Period start\"] as string | undefined) ?? null,\n periodEnd: (f[\"Period end\"] as string | undefined) ?? null,\n completedOn: (f[\"Completed on\"] as string | undefined) ?? null,\n lighthouse: lighthouseFromFields(f),\n gaUsersCurrent: (f[\"GA users (period)\"] as number | undefined) ?? null,\n gaUsersPrevious: (f[\"GA users (prev period)\"] as number | undefined) ?? null,\n searchFoundPage1:\n typeof f[\"Search found page 1\"] === \"boolean\" ? (f[\"Search found page 1\"] as boolean) : null,\n searchPosition: (f[\"Search position\"] as number | undefined) ?? null,\n lastTestedDate: (f[\"Last tested date\"] as string | undefined) ?? null,\n commentary: (f[\"Commentary\"] as string | undefined) ?? null,\n subjectOverride: (f[\"Subject override\"] as string | undefined) ?? null,\n draftReady: Boolean(f[\"Draft ready\"]),\n approvedToSend: Boolean(f[\"Approved to send\"]),\n sentAt: (f[\"Sent at\"] as string | undefined) ?? null,\n approvedAt: (f[\"Approved At\"] as string | undefined) ?? null,\n approvedBy: (f[\"Approved By\"] as string | undefined) ?? null,\n deliveryStatus: ((f[\"Delivery status\"] as string | undefined) ?? \"pending\") as DeliveryStatus,\n renderedHtmlAttachment: html,\n resendMessageId: (f[\"Resend message ID\"] as string | undefined) ?? null,\n checklist: Object.fromEntries(ALL_CHECKLIST_FIELDS.map((name) => [name, Boolean(f[name])])),\n autoEvidence: parseAutoEvidence(f[\"Checklist auto-evidence\"]),\n };\n}\n\n/**\n * Parse the `Checklist auto-evidence` JSON field → a field→EvidenceRecord map, or null when\n * absent/malformed. Permissive on inner shape (it's display-only — a bad blob just yields null,\n * never throws), mirroring `parseNotifyRouting`.\n */\nexport function parseAutoEvidence(raw: unknown): Record<string, EvidenceRecord> | 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 (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n // Validate each entry's inner shape (it drives display) — drop any record whose `result` isn't\n // one of the three literals, and coerce `note`/`checkedAt` to safe types. A garbage blob yields\n // null rather than a record that would render \"auto: undefined\" on the dashboard.\n const out: Record<string, EvidenceRecord> = {};\n for (const [field, v] of Object.entries(parsed as Record<string, unknown>)) {\n if (!v || typeof v !== \"object\") continue;\n const o = v as Record<string, unknown>;\n if (o.result !== \"pass\" && o.result !== \"fail\" && o.result !== \"unknown\") continue;\n out[field] = {\n result: o.result,\n checkedAt: typeof o.checkedAt === \"string\" ? o.checkedAt : null,\n note: typeof o.note === \"string\" ? o.note : \"\",\n };\n }\n return Object.keys(out).length > 0 ? out : null;\n}\n\nfunction lighthouseFromFields(f: Record<string, unknown>): LighthouseScores | null {\n const p = f[\"Lighthouse — Performance\"];\n const a = f[\"Lighthouse — Accessibility\"];\n const b = f[\"Lighthouse — Best Practices\"];\n const s = f[\"Lighthouse — SEO\"];\n if (\n typeof p !== \"number\" ||\n typeof a !== \"number\" ||\n typeof b !== \"number\" ||\n typeof s !== \"number\"\n )\n return null;\n return { performance: p, accessibility: a, bestPractices: b, seo: s };\n}\n\n/** The GA + Search-presence fields a draft can carry, written to the Reports row.\n * `searchFoundPage1` is written whenever the check ran (true or false — false is the\n * operator-only negative signal); `searchPosition` only when found on page 1. Shared by\n * the create path (DraftInput) and the reuse path (updateReportScores). */\nexport type ReportEnrichment = {\n gaUsersCurrent?: number;\n gaUsersPrevious?: number;\n searchFoundPage1?: boolean;\n searchPosition?: number;\n};\n\nexport type DraftInput = {\n reportId: string;\n siteId: string;\n reportType: ReportType;\n /** UTC `YYYY-MM` recurrence key. Omitted on legacy callers; written only when supplied. */\n period?: string;\n periodStart: Date;\n periodEnd: Date;\n completedOn: Date;\n lighthouse: LighthouseScores;\n lastTestedDate: Date | null;\n /** GA \"Users\" for the period / previous period. Omitted when GA is not configured\n * for the site or the fetch failed — the operator fills the fields manually. */\n gaUsersCurrent?: number;\n gaUsersPrevious?: number;\n /** Search-presence result. `searchFoundPage1` is written whenever the check ran (true or\n * false — false is the operator-only negative signal). `searchPosition` only when found. */\n searchFoundPage1?: boolean;\n searchPosition?: number;\n subjectOverride?: string;\n /** Checklist fields to tick at create time (the auto-tick \"pass\" set). */\n checklistTicks?: string[];\n /** Auto-tick evidence snapshot to persist (keyed by checklist field). */\n autoEvidence?: Record<string, EvidenceRecord>;\n};\n\nfunction ymd(d: Date): string {\n return d.toISOString().slice(0, 10);\n}\n\n/**\n * Escape a string for safe interpolation into an Airtable filterByFormula.\n * Airtable formulas use SQL-like string literals; we escape backslash and\n * double quote. Used wherever an externally-supplied string flows into a\n * formula (e.g. Resend message ids on the webhook path).\n */\nexport function escapeFormulaString(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\nexport async function createDraft(base: AirtableBase, input: DraftInput): Promise<ReportRow> {\n // Set Delivery status to \"pending\" at creation time, NOT at send time. This\n // matters for H4: if stampSent wrote \"pending\" after the webhook had already\n // written \"delivered\" (race), the operator would see a regressed status.\n const fields: FieldSet = {\n \"Report ID\": input.reportId,\n Site: [input.siteId],\n \"Report type\": input.reportType,\n \"Period start\": ymd(input.periodStart),\n \"Period end\": ymd(input.periodEnd),\n \"Completed on\": ymd(input.completedOn),\n \"Lighthouse — Performance\": input.lighthouse.performance,\n \"Lighthouse — Accessibility\": input.lighthouse.accessibility,\n \"Lighthouse — Best Practices\": input.lighthouse.bestPractices,\n \"Lighthouse — SEO\": input.lighthouse.seo,\n \"Delivery status\": \"pending\",\n };\n if (input.lastTestedDate) fields[\"Last tested date\"] = ymd(input.lastTestedDate);\n // GA fields are written only when supplied (GA configured + fetch succeeded). When\n // omitted the row keeps them blank for manual entry — the pre-GA behavior.\n if (input.gaUsersCurrent !== undefined) fields[\"GA users (period)\"] = input.gaUsersCurrent;\n if (input.gaUsersPrevious !== undefined) fields[\"GA users (prev period)\"] = input.gaUsersPrevious;\n if (input.searchFoundPage1 !== undefined) fields[\"Search found page 1\"] = input.searchFoundPage1;\n if (input.searchPosition !== undefined) fields[\"Search position\"] = input.searchPosition;\n if (input.period !== undefined) fields[\"Period\"] = input.period;\n if (input.subjectOverride !== undefined) fields[\"Subject override\"] = input.subjectOverride;\n // Auto-ticked checklist boxes + the evidence snapshot. The booleans are the same columns the\n // operator/dashboard toggle; the JSON drives the dashboard's green/amber badges.\n for (const field of input.checklistTicks ?? []) fields[field] = true;\n if (input.autoEvidence && Object.keys(input.autoEvidence).length > 0) {\n fields[\"Checklist auto-evidence\"] = JSON.stringify(input.autoEvidence);\n }\n const created = (await base(REPORTS_TABLE).create([{ fields }])) as Records<FieldSet>;\n const rec = created[0];\n if (!rec) throw new Error(\"Airtable create returned no records\");\n return mapRow({ id: rec.id, fields: rec.fields });\n}\n\nexport async function setDraftReady(\n base: AirtableBase,\n recordId: string,\n ready: boolean,\n): Promise<void> {\n await base(REPORTS_TABLE).update([{ id: recordId, fields: { \"Draft ready\": ready } }]);\n}\n\n/**\n * Overwrite the four `Lighthouse — *` score cells (and, when supplied, `Completed\n * on`) on an EXISTING Reports row. The launch re-run path uses this: it reuses the\n * already-created Launch row but must refresh its scores to match the freshly-run\n * audit — otherwise the re-rendered preview shows new scores while the row (and the\n * eventually-sent email, which reads the row) keeps the stale ones. The create path\n * already writes fresh scores via `createDraft`; this is its update-side mirror, using\n * the same exact field names so the two stay in lockstep.\n */\nexport async function updateReportScores(\n base: AirtableBase,\n recordId: string,\n scores: LighthouseScores,\n completedOn?: Date,\n enrichment?: ReportEnrichment,\n): Promise<void> {\n const fields: FieldSet = {\n \"Lighthouse — Performance\": scores.performance,\n \"Lighthouse — Accessibility\": scores.accessibility,\n \"Lighthouse — Best Practices\": scores.bestPractices,\n \"Lighthouse — SEO\": scores.seo,\n };\n if (completedOn) fields[\"Completed on\"] = ymd(completedOn);\n if (enrichment?.gaUsersCurrent !== undefined)\n fields[\"GA users (period)\"] = enrichment.gaUsersCurrent;\n if (enrichment?.gaUsersPrevious !== undefined)\n fields[\"GA users (prev period)\"] = enrichment.gaUsersPrevious;\n if (enrichment?.searchFoundPage1 !== undefined)\n fields[\"Search found page 1\"] = enrichment.searchFoundPage1;\n if (enrichment?.searchPosition !== undefined)\n fields[\"Search position\"] = enrichment.searchPosition;\n await base(REPORTS_TABLE).update([{ id: recordId, fields }]);\n}\n\nexport async function listSendableReports(base: AirtableBase): Promise<ReportRow[]> {\n const out: ReportRow[] = [];\n await base(REPORTS_TABLE)\n .select({\n filterByFormula:\n \"AND({Draft ready} = TRUE(), {Approved to send} = TRUE(), {Sent at} = BLANK())\",\n pageSize: 100,\n })\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\n/**\n * Fetch every Reports row, unfiltered. Site-scoped callers filter the result in\n * memory: the `Site` linked-record field CANNOT be formula-filtered by record id\n * (see findReportByPeriod's doc for why), and the fleet's Reports table is small\n * enough that one paged fetch-all beats N broken-or-per-site queries.\n */\nexport async function listAllReports(base: AirtableBase): Promise<ReportRow[]> {\n const out: ReportRow[] = [];\n await base(REPORTS_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 listReportsForSite(base: AirtableBase, siteId: string): Promise<ReportRow[]> {\n // Client-side match on the mapped siteId (mapRow reads the record id from the\n // REST response, where it IS present) — record ids can't appear in formulas.\n return (await listAllReports(base)).filter((r) => r.siteId === siteId);\n}\n\n/**\n * Mark a row as sent: write `Sent at` and (when known) `Resend message ID`.\n * Crucially does NOT touch `Delivery status` — that's set to \"pending\" in\n * createDraft and updated by the webhook from there. If we wrote \"pending\" here\n * we could clobber a \"delivered\" that the webhook raced ahead and wrote first (H4).\n *\n * `messageId` may be `null`: the 409 idempotency-conflict path has no recoverable\n * id (the original send's id was lost when the prior run's stamp failed), so it\n * passes null and we write ONLY `Sent at`. Writing a sentinel string like\n * \"idempotent-conflict\" into the id column would masquerade as a real Resend id\n * and silently orphan `findReportByMessageId` lookups; leaving it null is honest —\n * the row still stops replaying (Sent at is set), delivery tracking for that one\n * report is simply degraded (the id is genuinely unknowable on that path).\n */\nexport async function stampSent(\n base: AirtableBase,\n recordId: string,\n sentAt: Date,\n messageId: string | null,\n): Promise<void> {\n const fields: Record<string, string> = { \"Sent at\": sentAt.toISOString() };\n if (messageId !== null) fields[\"Resend message ID\"] = messageId;\n await base(REPORTS_TABLE).update([\n {\n id: recordId,\n fields,\n },\n ]);\n}\n\nexport async function setDeliveryStatus(\n base: AirtableBase,\n recordId: string,\n status: DeliveryStatus,\n): Promise<void> {\n await base(REPORTS_TABLE).update([{ id: recordId, fields: { \"Delivery status\": status } }]);\n}\n\n/**\n * Stamp the approval on a Reports row: flips `Approved to send` TRUE and records\n * who/when for the audit trail. The caller (approveReport handler) is responsible\n * for idempotency — this is the raw write. Never touches `Sent at`.\n */\nexport async function approveReportRow(\n base: AirtableBase,\n recordId: string,\n approvedAt: Date,\n approvedBy: string,\n): Promise<void> {\n await base(REPORTS_TABLE).update([\n {\n id: recordId,\n fields: {\n \"Approved to send\": true,\n \"Approved At\": approvedAt.toISOString(),\n \"Approved By\": approvedBy,\n },\n },\n ]);\n}\n\n/**\n * Set one operator-checklist checkbox on a Reports row. `field` MUST be one of the\n * 12 known checklist columns (ALL_CHECKLIST_FIELDS) — the caller (setChecklistItem)\n * validates this before calling, so an arbitrary Airtable column can never be written.\n * The raw write mirror of `approveReportRow`; touches only the one checkbox.\n */\nexport async function setReportChecklistItem(\n base: AirtableBase,\n recordId: string,\n field: string,\n value: boolean,\n): Promise<void> {\n await base(REPORTS_TABLE).update([{ id: recordId, fields: { [field]: value } }]);\n}\n\n/**\n * True when an `.find` rejection is a GENUINE not-found, not a transient failure.\n * The Airtable SDK stamps `.statusCode` (404) and/or `.error` (\"NOT_FOUND\") on\n * its errors. Anything else (429 rate-limit, 500 outage, bad-PAT 401, network\n * error) must NOT be masked as a 404 — see getReportById.\n */\nfunction isNotFoundError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as { statusCode?: unknown; error?: unknown; name?: unknown; message?: unknown };\n if (e.statusCode === 404) return true;\n const tag = String(e.error ?? e.name ?? e.message ?? \"\");\n return tag === \"NOT_FOUND\" || /not found/i.test(tag);\n}\n\n/**\n * Fetch one Reports row by its Airtable record id, or null if it doesn't exist.\n * Only a GENUINE not-found (404 / NOT_FOUND) collapses to null; every other\n * failure (outage, 429, bad PAT, network error) is rethrown so the adapter\n * surfaces a 500 instead of a misleading 404. Swallowing all throws previously\n * turned an Airtable outage into a \"no such report\".\n */\nexport async function getReportById(\n base: AirtableBase,\n recordId: string,\n): Promise<ReportRow | null> {\n try {\n const rec = await base(REPORTS_TABLE).find(recordId);\n return mapRow({ id: rec.id, fields: rec.fields as Record<string, unknown> });\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n}\n\nexport async function findReportByMessageId(\n base: AirtableBase,\n messageId: string,\n): Promise<ReportRow | null> {\n const rows: ReportRow[] = [];\n await base(REPORTS_TABLE)\n .select({\n filterByFormula: `{Resend message ID} = \"${escapeFormulaString(messageId)}\"`,\n maxRecords: 1,\n })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n return rows[0] ?? null;\n}\n\n/**\n * Find the Reports row for a `(site, reportType, period)` triple, or null. The\n * idempotency lookup behind search-before-create drafting.\n *\n * The site is matched CLIENT-side, never in the formula: Airtable's formula layer\n * renders linked-record fields ({Site}) as the linked rows' PRIMARY-FIELD NAMES,\n * not record ids, so any formula comparing {Site} or ARRAYJOIN({Site}) against a\n * `recXXX` id matches NOTHING (live-proven against the real base — do not\n * reintroduce that idiom). Record ids exist only in the REST response, where\n * mapRow reads them. So the formula filters on the real scalar fields (Report\n * type + Period — escaped, keeping it injection-safe if their source ever\n * changes), and the first mapped row whose siteId matches wins. The candidate\n * set is at most one row per site for the (type, period), so this stays small.\n */\nexport async function findReportByPeriod(\n base: AirtableBase,\n siteId: string,\n reportType: ReportType,\n period: string,\n): Promise<ReportRow | null> {\n const safeType = escapeFormulaString(reportType);\n const safePeriod = escapeFormulaString(period);\n const formula = `AND({Report type} = \"${safeType}\", {Period} = \"${safePeriod}\")`;\n const rows: ReportRow[] = [];\n await base(REPORTS_TABLE)\n .select({ filterByFormula: formula, pageSize: 100 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n return rows.find((r) => r.siteId === siteId) ?? null;\n}\n"],"mappings":";AAYO,SAAS,WAAW,GAAmB;AAC5C,SAAO,EACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,OAAO;AAC1B;AAGO,SAAS,QAAQ,KAAqB;AAC3C,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAAA,EAChE,QAAQ;AAAA,EAER;AACA,SAAO;AACT;;;AChBO,IAAM,wBAAyC;AAAA,EACpD,EAAE,KAAK,UAAU,OAAO,4BAA4B,OAAO,kCAAkC;AAAA,EAC7F,EAAE,KAAK,OAAO,OAAO,eAAe,OAAO,qBAAqB;AAAA,EAChE,EAA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/reports/send/idempotency.ts
|
|
2
|
+
function isIdempotencyConflict(err) {
|
|
3
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
4
|
+
if (/idempotency key has been used/i.test(message)) return true;
|
|
5
|
+
const e = err;
|
|
6
|
+
if (e.name === "invalid_idempotent_request") return true;
|
|
7
|
+
if (e.statusCode === 409) return true;
|
|
8
|
+
return false;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
isIdempotencyConflict
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=chunk-OGGRFBL4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reports/send/idempotency.ts"],"sourcesContent":["/**\n * True when a thrown send error is Resend's same-key + DIFFERENT-body 409\n * (`invalid_idempotent_request`). The ResendClient (send/resend.ts) discards the\n * status/name and only surfaces the message string, so we match defensively on the\n * stable message substring \"idempotency key has been used\" (case-insensitive); a\n * `name`/`statusCode` of 409/`invalid_idempotent_request` is also accepted if a\n * future client happens to preserve it. A same-key + SAME-body re-send is deduped\n * by Resend (returns the original id) and never reaches here.\n *\n * Shared by both send surfaces that key into Resend's idempotency window:\n * `runDigest` (digest.ts, `digest-<date>` key) and `sendOne` (orchestrate.ts,\n * `report:<id>` key). Both treat a 409 as \"the email already went out under this\n * key on a prior run\" — a no-op for the digest, an already-done success for sendOne.\n */\nexport function isIdempotencyConflict(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n if (/idempotency key has been used/i.test(message)) return true;\n const e = err as { name?: unknown; statusCode?: unknown };\n if (e.name === \"invalid_idempotent_request\") return true;\n if (e.statusCode === 409) return true;\n return false;\n}\n"],"mappings":";AAcO,SAAS,sBAAsB,KAAuB;AAC3D,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,MAAI,iCAAiC,KAAK,OAAO,EAAG,QAAO;AAC3D,QAAM,IAAI;AACV,MAAI,EAAE,SAAS,6BAA8B,QAAO;AACpD,MAAI,EAAE,eAAe,IAAK,QAAO;AACjC,SAAO;AACT;","names":[]}
|