soundings-cli 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,4807 @@
1
+ #!/usr/bin/env node
2
+ /*! Soundings (c) 2026 Dynamo Maritime Ltd. Licensed under FSL-1.1-ALv2, except code from src/pro/,
3
+ * which is under the Soundings Commercial Licence. See LICENSE and LICENSE-COMMERCIAL.md. */
4
+
5
+ // src/cli/index.ts
6
+ import { createInterface } from "readline/promises";
7
+
8
+ // src/cli/main.ts
9
+ import { parseArgs } from "util";
10
+ import { existsSync as existsSync6, readFileSync as readFileSync8, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
11
+ import { relative as relative2, resolve } from "path";
12
+ import pc5 from "picocolors";
13
+
14
+ // src/core/config.ts
15
+ import { existsSync, readFileSync } from "fs";
16
+ import { join } from "path";
17
+ import { z } from "zod";
18
+ var Config = z.object({
19
+ /** Extra .gitignore-style patterns to leave out of the scan. */
20
+ ignore: z.array(z.string()).default([])
21
+ });
22
+ var ConfigError = class extends Error {
23
+ };
24
+ function loadConfig(root, file) {
25
+ const path = file ?? join(root, "soundings.config.json");
26
+ if (!existsSync(path)) {
27
+ if (file) throw new ConfigError(`Config file not found: ${file}`);
28
+ return Config.parse({});
29
+ }
30
+ try {
31
+ return Config.parse(JSON.parse(readFileSync(path, "utf8")));
32
+ } catch (err) {
33
+ throw new ConfigError(`Couldn't read ${path}: ${err instanceof Error ? err.message : String(err)}`);
34
+ }
35
+ }
36
+
37
+ // src/evidence/redact.ts
38
+ import { readdirSync, readFileSync as readFileSync2 } from "fs";
39
+ import { join as join2 } from "path";
40
+ var PLACEHOLDER_PASSWORD = /^(?:pass(?:word)?|pwd|secret|token|changeme|change-me|example|test|dummy|redacted|none|x{3,}|\*+|<[^>]*>|\[[^\]]*\]|\{[^}]*\}|\$\{?[A-Za-z_]\w*\}?|%[A-Za-z_]\w*%|(?:your|my|the)[_-].*|.*[_-](?:here|placeholder))$/i;
41
+ var PATTERNS = [
42
+ { kind: "private-key", re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
43
+ { kind: "aws-access-key", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
44
+ { kind: "github-token", re: /\bgh[pousr]_[A-Za-z0-9]{30,}\b/ },
45
+ { kind: "stripe-key", re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/ },
46
+ { kind: "slack-token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/ },
47
+ { kind: "llm-api-key", re: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/ },
48
+ { kind: "jwt", re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/ },
49
+ {
50
+ kind: "credentialed-url",
51
+ re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:([^\s/@]+)@[^\s/]+/i,
52
+ ignore: (m) => PLACEHOLDER_PASSWORD.test(m[1] ?? "")
53
+ }
54
+ ];
55
+ var PUBLIC_NAME = /^(?:NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|GATSBY_|PUBLIC_)/;
56
+ var ENV_FILE = /^\.env(?:\.[\w.-]+)?$/;
57
+ var ENV_TEMPLATE = /\.(example|sample|template|dist|defaults|schema|vault)$/i;
58
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", ".next", "coverage"]);
59
+ var MIN_VALUE_LENGTH = 8;
60
+ var RedactionError = class extends Error {
61
+ constructor(label, leaks) {
62
+ const kinds = [...new Set(leaks.map((l) => l.kind))].sort().join(", ");
63
+ super(`Possible secret in ${label}: ${leaks.length} match(es) (${kinds})`);
64
+ this.label = label;
65
+ this.leaks = leaks;
66
+ this.name = "RedactionError";
67
+ }
68
+ label;
69
+ leaks;
70
+ };
71
+ function worthGuarding(value) {
72
+ if (value.length < MIN_VALUE_LENGTH) return false;
73
+ if (/^(?:true|false|null|undefined)$/i.test(value)) return false;
74
+ if (/^\d+(?:\.\d+)?$/.test(value)) return false;
75
+ if (/^https?:\/\/[^\s@]+$/i.test(value)) return false;
76
+ if (/^[a-z]+$/.test(value)) return false;
77
+ return true;
78
+ }
79
+ function parseEnvValues(text) {
80
+ const out = [];
81
+ for (const raw of text.split(/\r?\n/)) {
82
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.]*)\s*=\s*(.*?)\s*$/.exec(raw);
83
+ if (!m) continue;
84
+ const [, name, rest] = m;
85
+ let value = rest;
86
+ const q2 = value[0];
87
+ if ((q2 === '"' || q2 === "'" || q2 === "`") && value.lastIndexOf(q2) > 0) value = value.slice(1, value.lastIndexOf(q2));
88
+ else value = value.replace(/\s+#.*$/, "");
89
+ if (PUBLIC_NAME.test(name) || !worthGuarding(value)) continue;
90
+ out.push(value);
91
+ }
92
+ return out;
93
+ }
94
+ function loadEnvValues(root, maxDepth = 3) {
95
+ const values = /* @__PURE__ */ new Set();
96
+ const visit = (dir, depth) => {
97
+ let entries;
98
+ try {
99
+ entries = readdirSync(dir, { withFileTypes: true });
100
+ } catch {
101
+ return;
102
+ }
103
+ for (const e of entries) {
104
+ if (e.isSymbolicLink()) continue;
105
+ if (e.isDirectory()) {
106
+ if (depth < maxDepth && !SKIP_DIRS.has(e.name)) visit(join2(dir, e.name), depth + 1);
107
+ } else if (e.isFile() && ENV_FILE.test(e.name) && !ENV_TEMPLATE.test(e.name)) {
108
+ try {
109
+ for (const v of parseEnvValues(readFileSync2(join2(dir, e.name), "utf8"))) values.add(v);
110
+ } catch {
111
+ }
112
+ }
113
+ }
114
+ };
115
+ visit(root, 0);
116
+ return [...values];
117
+ }
118
+ function createGuard(envValues = []) {
119
+ return { envValues: envValues.filter(worthGuarding) };
120
+ }
121
+ function findLeaks(text, guard = createGuard()) {
122
+ const leaks = [];
123
+ for (const { kind, re, ignore: ignore2 } of PATTERNS) {
124
+ const global = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`);
125
+ for (const m of text.matchAll(global)) {
126
+ if (ignore2?.(m)) continue;
127
+ leaks.push({ kind, index: m.index ?? 0 });
128
+ break;
129
+ }
130
+ }
131
+ for (const v of guard.envValues) {
132
+ const index = text.indexOf(v);
133
+ if (index !== -1) leaks.push({ kind: "env-value", index });
134
+ }
135
+ return leaks.sort((a, b) => a.index - b.index);
136
+ }
137
+ function assertNoLeaks(text, guard, label) {
138
+ const leaks = findLeaks(text, guard);
139
+ if (leaks.length > 0) throw new RedactionError(label, leaks);
140
+ }
141
+
142
+ // src/questions/types.ts
143
+ var CATEGORY_LABELS = {
144
+ ai: "AI use",
145
+ data: "Data handling",
146
+ access: "Access control",
147
+ keys: "Key management",
148
+ logging: "Logging and monitoring",
149
+ suppliers: "Suppliers and subprocessors",
150
+ organisation: "Organisation and incident response"
151
+ };
152
+
153
+ // src/evidence/refs.ts
154
+ var REF_ID = /^(?:EV-[0-9a-f]{6,12}|F-[0-9a-f]{6,12}|KB-[0-9a-f]{6,12}|A-\d{3,})$/;
155
+ function extractRefs(text) {
156
+ const out = [];
157
+ const group = /\[([^\[\]\n]{1,200})\]/g;
158
+ for (let m = group.exec(text); m; m = group.exec(text)) {
159
+ const tokens2 = m[1].split(/[\s,]+/).filter(Boolean);
160
+ if (tokens2.length === 0 || !tokens2.every((t) => REF_ID.test(t))) continue;
161
+ for (const id of tokens2) out.push({ id, kind: id.slice(0, id.indexOf("-")), index: m.index });
162
+ }
163
+ return out;
164
+ }
165
+ function replaceRefGroups(text, fn) {
166
+ return text.replace(/\[([^\[\]\n]{1,200})\]/g, (whole, inner) => {
167
+ const tokens2 = inner.split(/[\s,]+/).filter(Boolean);
168
+ return tokens2.length > 0 && tokens2.every((t) => REF_ID.test(t)) ? fn(tokens2) : whole;
169
+ });
170
+ }
171
+ function documentUse(fact) {
172
+ if (fact.confidence === "low") return "never";
173
+ if (fact.claimType === "not-found" || fact.confidence === "medium") return "qualified";
174
+ return "plain";
175
+ }
176
+
177
+ // src/export/footnotes.ts
178
+ var withFootnoteMarks = (text) => replaceRefGroups(text, (ids) => ids.map((id) => `[^${id}]`).join(""));
179
+ function usedRefs(texts) {
180
+ const seen = /* @__PURE__ */ new Set();
181
+ for (const t of texts) for (const r of extractRefs(t)) seen.add(r.id);
182
+ return [...seen];
183
+ }
184
+ function footnoteLines(refs, evidence, answers, opts) {
185
+ const facts = new Map(evidence.facts.map((f) => [f.id, f]));
186
+ const findings = new Map(evidence.findings.map((f) => [f.id, f]));
187
+ const given = new Map(answers.answers.map((a) => [a.id, a]));
188
+ return refs.map((id) => {
189
+ const f = facts.get(id);
190
+ if (f) {
191
+ const loc = f.locations[0];
192
+ const where2 = opts.locations && loc ? ` (${loc.file}${loc.line ? `:${loc.line}` : ""})` : "";
193
+ const how = f.claimType === "not-found" ? " Not found by the scan's pattern search." : f.confidence === "medium" ? " Inferred from the code." : "";
194
+ return `[^${id}]: Code scan, ${f.subject}${where2}: ${f.claim}${how}`;
195
+ }
196
+ const finding = findings.get(id);
197
+ if (finding) return `[^${id}]: Seaworthy finding ${finding.ruleId} (${finding.severity}).`;
198
+ const a = given.get(id);
199
+ if (a) return `[^${id}]: Answer from the project team, recorded ${a.answeredAt.slice(0, 10)}.`;
200
+ return `[^${id}]: Source not found.`;
201
+ });
202
+ }
203
+
204
+ // src/export/notice.ts
205
+ var DRAFT_NOTICE = "Draft prepared with Soundings from a scan of the project's code and from answers given by the project team. It is not legal advice, and it does not state that anyone is compliant with, or certified to, any law or standard. Every statement about the project points to a numbered source at the end of the document. Please review it before sending.";
206
+ var NEEDS_INPUT = "Needs your input.";
207
+ var TALLY_LINE = /^\d+ of \d+ questions are answered from evidence\. \d+ (?:is|are) partly answered and \d+ needs? input from the project team\.$/;
208
+ var tallyLine = (done, total, partial, open) => `${done} of ${total} questions are answered from evidence. ${partial} ${partial === 1 ? "is" : "are"} partly answered and ${open} ${open === 1 ? "needs" : "need"} input from the project team.`;
209
+ var NOT_YET_PROVIDED = "Not yet provided";
210
+
211
+ // src/export/questionnaire.ts
212
+ var ORDER = ["ai", "data", "access", "keys", "logging", "suppliers", "organisation"];
213
+ function renderQuestionnaireMarkdown(results, evidence, answers, opts) {
214
+ const out = [];
215
+ out.push(`# Security and data handling answers: ${opts.project}`, "", `> ${DRAFT_NOTICE}`, "");
216
+ const done = results.filter((r) => r.status === "answered").length;
217
+ const partial = results.filter((r) => r.status === "partial").length;
218
+ const open = results.length - done - partial;
219
+ out.push(tallyLine(done, results.length, partial, open), "");
220
+ for (const category of ORDER) {
221
+ const inCategory = results.filter((r) => r.category === category);
222
+ if (inCategory.length === 0) continue;
223
+ out.push(`## ${CATEGORY_LABELS[category]}`, "");
224
+ for (const r of inCategory) {
225
+ out.push(`### ${r.question}`, "");
226
+ if (r.answer) out.push(withFootnoteMarks(r.answer), "");
227
+ if (r.status !== "answered") {
228
+ const asks = r.needs.map((n) => n.prompt);
229
+ out.push(`**${NEEDS_INPUT}**${asks.length ? ` ${asks.join(" ")}` : ""}`, "");
230
+ }
231
+ }
232
+ }
233
+ const refs = usedRefs(results.map((r) => r.answer));
234
+ if (refs.length > 0) {
235
+ out.push("## Sources", "", ...footnoteLines(refs, evidence, answers, opts), "");
236
+ }
237
+ return out.join("\n");
238
+ }
239
+
240
+ // src/questions/profile.ts
241
+ var item = (key, prompt, lead) => [key, { key: `profile.${key}`, prompt, lead }];
242
+ var PROFILE = Object.fromEntries([
243
+ item("ai-data-categories", "What categories of data do you send to AI providers (for example support tickets, documents, personal data)?", "Data sent to AI providers"),
244
+ item("ai-human-oversight", "Is a person involved in reviewing AI outputs before they affect users? Describe how.", "Human oversight of AI outputs"),
245
+ item("ai-processing-region", "In which country or region do your AI providers process your data, and is that configurable?", "AI processing location"),
246
+ item("encryption-at-rest", "How is stored data encrypted at rest (for example by the database provider by default)?", "Encryption at rest"),
247
+ item("encryption-in-transit", "How is data encrypted in transit (for example HTTPS/TLS everywhere)?", "Encryption in transit"),
248
+ item("deletion-process", "How can a user or customer have their data deleted, and who carries it out?", "Deletion requests"),
249
+ item("personal-data-categories", "What categories of personal data does the system handle (for example names, emails, payment details)?", "Personal data handled"),
250
+ item("tenant-separation", "How is one customer's data kept separate from another's?", "Customer data separation"),
251
+ item("mfa", "Is multi-factor authentication available or required for users and for administrators?", "Multi-factor authentication"),
252
+ item("admin-access", "Who has administrative access to production systems, and how is it controlled?", "Administrative access"),
253
+ item("access-review", "How often is access reviewed, and what happens when someone leaves?", "Access reviews"),
254
+ item("password-policy", "What password or credential rules apply, and are they enforced by a provider?", "Credential rules"),
255
+ item("secret-storage", "How are secrets and API keys stored and shared with the team?", "Secret storage"),
256
+ item("secret-rotation", "How and how often are keys and secrets rotated, and what happens if one is exposed?", "Secret rotation"),
257
+ item("log-retention", "How long are logs kept, who can read them, and where are they stored?", "Log retention"),
258
+ item("monitoring", "What monitoring or alerting is in place for errors and security events?", "Monitoring and alerting"),
259
+ item("other-suppliers", "Which other suppliers handle your data outside the code (hosting, email, support tools, backups)?", "Other suppliers"),
260
+ item("payments", "How are payments handled, if at all?", "Payments"),
261
+ item("analytics", "Do you use analytics or tracking? If so, which, and what do they collect?", "Analytics"),
262
+ item("email", "How is email sent to users, and by which provider?", "Email"),
263
+ item("incident-response", "Do you have an incident response process? Describe who does what.", "Incident response"),
264
+ item("breach-notification", "How quickly would you notify a customer of a personal data breach, and how?", "Breach notification"),
265
+ item("dpo", "Who is your data protection contact or officer?", "Data protection contact"),
266
+ item("staff-vetting", "What checks are made on staff and contractors with access to client systems or data?", "Staff vetting"),
267
+ item("staff-training", "What security or data protection training do staff receive?", "Staff training"),
268
+ item("backup-recovery", "How is data backed up, and how long would recovery take?", "Backup and recovery"),
269
+ item("vulnerability-process", "How are vulnerabilities in your code and dependencies found and fixed?", "Vulnerability management"),
270
+ item("certifications", "Which security certifications or independent assessments do you hold, if any? Say 'none' if none.", "Certifications and assessments"),
271
+ item("dpia", "Has a data protection impact assessment been carried out for this system?", "Impact assessment"),
272
+ item("supplier-diligence", "How do you check the security of your suppliers?", "Supplier checks"),
273
+ item("organisation-name", "What is the legal name of the organisation responsible for this service?", "Responsible organisation"),
274
+ item("service-description", "In a sentence or two, what does this service do and who uses it?", "About the service"),
275
+ item("lawful-basis", "What is the lawful basis for processing personal data in this service (for example contract, legitimate interests, consent)?", "Lawful basis"),
276
+ item("ai-purpose", "What is AI used for in this service?", "Purpose of AI use"),
277
+ item("dpia-consultation", "Who has been consulted about this processing (for example users, the data protection contact, a security adviser)?", "Consultation"),
278
+ item("dpia-risk-measures", "What measures have been chosen to reduce the risks to individuals that this assessment identifies?", "Measures to reduce risk")
279
+ ]);
280
+ var PROFILE_KEYS = new Set(Object.values(PROFILE).map((p) => p.key));
281
+ var profileByKey = (key) => Object.values(PROFILE).find((p) => p.key === key);
282
+
283
+ // src/questions/helpers.ts
284
+ var draft = () => ({ sentences: [], needs: [] });
285
+ var S = (text, ...refs) => ({ text, refs });
286
+ function list(items) {
287
+ if (items.length <= 1) return items.join("");
288
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
289
+ }
290
+ var stripStop = (s) => s.replace(/\.\s*$/, "");
291
+ function factSentence(f) {
292
+ switch (documentUse(f)) {
293
+ case "never":
294
+ return null;
295
+ case "qualified":
296
+ return f.claimType === "not-found" ? S(f.claim, f.id) : S(`${stripStop(f.claim)} (inferred from the code, not confirmed).`, f.id);
297
+ default:
298
+ return S(f.claim, f.id);
299
+ }
300
+ }
301
+ function addFacts(d, facts) {
302
+ let n = 0;
303
+ for (const f of facts) {
304
+ const s = factSentence(f);
305
+ if (s) {
306
+ d.sentences.push(s);
307
+ n++;
308
+ }
309
+ }
310
+ return n;
311
+ }
312
+ var plainText = (value) => value.replace(/\[/g, "(").replace(/\]/g, ")").replace(/\s+/g, " ").trim();
313
+ var ensureStop = (s) => /[.!?]$/.test(s) ? s : `${s}.`;
314
+ function answerSentence(lead, value, answerId2) {
315
+ return S(ensureStop(`${lead}: ${plainText(value)}`), answerId2);
316
+ }
317
+ function profile(ctx, d, short) {
318
+ const item2 = profileByKey(`profile.${short}`);
319
+ if (!item2) throw new Error(`unknown profile item ${short}`);
320
+ const a = ctx.answer(item2.key);
321
+ if (a) d.sentences.push(answerSentence(item2.lead, a.value, a.id));
322
+ else d.needs.push({ key: item2.key, prompt: item2.prompt });
323
+ }
324
+ function unknownAnswer(ctx, d, u, lead) {
325
+ const a = ctx.answer(u.id);
326
+ if (a) {
327
+ const subjects = u.relatedFacts.map((id) => ctx.factById(id)?.subject).filter((s) => Boolean(s));
328
+ const label = lead ?? `${u.topic}${subjects.length ? ` (${list([...new Set(subjects)])})` : ""}`;
329
+ d.sentences.push(answerSentence(label, a.value, a.id));
330
+ } else {
331
+ d.needs.push({ key: u.id, prompt: u.question });
332
+ }
333
+ }
334
+ function absenceSentence(ctx, detector) {
335
+ const f = ctx.byDetector(detector).find((x) => x.claimType === "not-found");
336
+ return f ? factSentence(f) : null;
337
+ }
338
+ var subjectsOf = (facts) => [...new Set(facts.map((f) => f.subject))];
339
+ var refsOf = (facts) => facts.map((f) => f.id);
340
+ function unanalysed(ctx, d) {
341
+ const u = ctx.evidence.unknowns.find((x) => x.id === "UQ-unanalysed-code");
342
+ if (u) unknownAnswer(ctx, d, u, "Parts of the project the scan did not read");
343
+ }
344
+ function noneFound(ctx, d, detector) {
345
+ const s = absenceSentence(ctx, detector);
346
+ if (s) d.sentences.push(s);
347
+ else unanalysed(ctx, d);
348
+ }
349
+
350
+ // src/questions/bank.ts
351
+ var q = (id, category, text, keywords, build2) => ({
352
+ id,
353
+ category,
354
+ text,
355
+ keywords,
356
+ build: build2
357
+ });
358
+ var services = (ctx, purposes) => ctx.facts("third_party_service").filter((f) => purposes.includes(String(f.attributes.purpose)));
359
+ function fromServices(ctx, d, purposes, fallback) {
360
+ if (addFacts(d, services(ctx, purposes)) === 0) profile(ctx, d, fallback);
361
+ }
362
+ var BANK = [
363
+ // ---- AI use
364
+ q("ai-use", "ai", "Does the system use artificial intelligence or machine-learning services?", ["artificial intelligence", "machine learning", "AI", "LLM", "*generative AI", "generative"], (ctx) => {
365
+ const d = draft();
366
+ const providers = ctx.facts("ai_provider");
367
+ if (providers.length > 0) d.sentences.push(S(`The system uses AI services from ${list(subjectsOf(providers))}.`, ...refsOf(providers)));
368
+ else {
369
+ noneFound(ctx, d, "ai-provider/none-found");
370
+ }
371
+ return d;
372
+ }),
373
+ q("ai-providers", "ai", "Which AI providers and models are used?", ["AI provider", "model", "which AI", "third-party AI", "foundation model", "large language model", "language model", "LLM", "openai", "anthropic"], (ctx) => {
374
+ const d = draft();
375
+ const providers = ctx.facts("ai_provider");
376
+ if (providers.length === 0) {
377
+ noneFound(ctx, d, "ai-provider/none-found");
378
+ return d;
379
+ }
380
+ const parts = providers.map((f) => f.attributes.model ? `${f.subject} (model ${String(f.attributes.model)})` : f.subject);
381
+ d.sentences.push(S(`AI providers in use: ${list([...new Set(parts)])}.`, ...refsOf(providers)));
382
+ return d;
383
+ }),
384
+ q("ai-data-sent", "ai", "What data is sent to AI providers?", ["data sent to AI", "prompt", "prompts", "passed to", "sent to AI", "inputs to the model", "personal data AI"], (ctx) => {
385
+ const d = draft();
386
+ if (ctx.facts("ai_provider").length === 0) {
387
+ noneFound(ctx, d, "ai-provider/none-found");
388
+ return d;
389
+ }
390
+ addFacts(d, ctx.facts("data_flow"));
391
+ profile(ctx, d, "ai-data-categories");
392
+ return d;
393
+ }),
394
+ q("ai-training", "ai", "Is customer data used to train AI models, by you or by your AI providers?", ["train", "training data", "model training", "opt out", "retention at provider"], (ctx) => {
395
+ const d = draft();
396
+ const unknowns = ctx.unknownsWithTopic("AI provider data use");
397
+ if (unknowns.length === 0) {
398
+ noneFound(ctx, d, "ai-provider/none-found");
399
+ return d;
400
+ }
401
+ for (const u of unknowns) unknownAnswer(ctx, d, u);
402
+ return d;
403
+ }),
404
+ q("ai-oversight", "ai", "Is there human oversight of AI outputs?", ["human oversight", "human in the loop", "review of AI output", "automated decision"], (ctx) => {
405
+ const d = draft();
406
+ if (ctx.facts("ai_provider").length === 0) {
407
+ noneFound(ctx, d, "ai-provider/none-found");
408
+ } else profile(ctx, d, "ai-human-oversight");
409
+ return d;
410
+ }),
411
+ q("ai-keys", "ai", "How are AI provider credentials protected?", ["AI keys", "API key protection", "model credentials", "provider keys"], (ctx) => {
412
+ const d = draft();
413
+ if (ctx.facts("ai_provider").length === 0) {
414
+ noneFound(ctx, d, "ai-provider/none-found");
415
+ return d;
416
+ }
417
+ addFacts(d, ctx.byDetector("secrets/env-usage"));
418
+ addFacts(d, ctx.byDetector("client-exposure/public-secret-name"));
419
+ addFacts(d, ctx.byDetector("client-exposure/ai-sdk-in-browser"));
420
+ return d;
421
+ }),
422
+ q("ai-browser", "ai", "Are AI services called directly from users' browsers?", ["browser", "client-side AI", "front end calls", "direct from the client"], (ctx) => {
423
+ const d = draft();
424
+ const providers = ctx.facts("ai_provider");
425
+ if (providers.length === 0) {
426
+ noneFound(ctx, d, "ai-provider/none-found");
427
+ return d;
428
+ }
429
+ const browser = providers.filter((f) => f.attributes.runsOn === "browser");
430
+ const server = providers.filter((f) => f.attributes.runsOn === "server");
431
+ if (browser.length) d.sentences.push(S(`Browser code imports an AI SDK (${list(subjectsOf(browser))}).`, ...refsOf(browser)));
432
+ if (server.length) d.sentences.push(S(`AI SDK use was found in server code (${list(subjectsOf(server))}).`, ...refsOf(server)));
433
+ const unclear = providers.filter((f) => f.attributes.runsOn === "unclear");
434
+ if (unclear.length) d.sentences.push(S(`For some AI SDK use the scan could not tell whether it runs in the browser or on a server (${list(subjectsOf(unclear))}).`, ...refsOf(unclear)));
435
+ return d;
436
+ }),
437
+ q("ai-region", "ai", "Where do AI providers process your data?", ["AI processing location", "AI data residency", "where is AI data processed"], (ctx) => {
438
+ const d = draft();
439
+ if (ctx.facts("ai_provider").length === 0) {
440
+ noneFound(ctx, d, "ai-provider/none-found");
441
+ } else profile(ctx, d, "ai-processing-region");
442
+ return d;
443
+ }),
444
+ // ---- Data handling
445
+ q("data-stores", "data", "Where and in what systems is customer data stored?", ["data stored", "storage", "database", "data repository", "where is data held"], (ctx) => {
446
+ const d = draft();
447
+ if (addFacts(d, ctx.facts("data_store")) === 0) {
448
+ noneFound(ctx, d, "data-store/none-found");
449
+ }
450
+ return d;
451
+ }),
452
+ q("data-region", "data", "In which country or region is data hosted?", ["data residency", "hosting location", "data location", "UK", "EU", "region", "sovereignty"], (ctx) => {
453
+ const d = draft();
454
+ const unknowns = ctx.unknownsWithTopic("Data region", "Database hosting", "Hosting");
455
+ if (unknowns.length === 0) {
456
+ noneFound(ctx, d, "data-store/none-found");
457
+ return d;
458
+ }
459
+ for (const u of unknowns) unknownAnswer(ctx, d, u);
460
+ return d;
461
+ }),
462
+ q("data-encryption-rest", "data", "Is data encrypted at rest?", ["encryption at rest", "encrypted storage", "disk encryption"], (ctx) => {
463
+ const d = draft();
464
+ profile(ctx, d, "encryption-at-rest");
465
+ return d;
466
+ }),
467
+ q("data-encryption-transit", "data", "Is data encrypted in transit?", ["encryption in transit", "*TLS", "*HTTPS", "*SSL", "transport encryption"], (ctx) => {
468
+ const d = draft();
469
+ profile(ctx, d, "encryption-in-transit");
470
+ return d;
471
+ }),
472
+ q("data-retention", "data", "How long is data kept, and what is the retention policy?", ["retention", "how long is data", "data kept", "retention period", "retention policy", "storage limitation"], (ctx) => {
473
+ const d = draft();
474
+ const unknowns = ctx.unknownsWithTopic("Retention");
475
+ if (unknowns.length === 0) {
476
+ noneFound(ctx, d, "data-store/none-found");
477
+ return d;
478
+ }
479
+ for (const u of unknowns) unknownAnswer(ctx, d, u, "Retention and deletion");
480
+ return d;
481
+ }),
482
+ q("data-deletion", "data", "Can customers or users have their data deleted on request?", ["deletion request", "deletion", "*erasure", "right to be forgotten", "delete my data", "delete personal data", "data subject request", "data subject", "request erasure"], (ctx) => {
483
+ const d = draft();
484
+ profile(ctx, d, "deletion-process");
485
+ return d;
486
+ }),
487
+ q("data-recipients", "data", "Which third parties receive customer data?", ["third parties", "data sharing", "recipients", "who receives data", "external services"], (ctx) => {
488
+ const d = draft();
489
+ const recipients = [...ctx.facts("third_party_service"), ...ctx.facts("ai_provider")];
490
+ if (recipients.length > 0) {
491
+ d.sentences.push(S(`The code integrates with these external services: ${list(subjectsOf(recipients))}.`, ...refsOf(recipients)));
492
+ }
493
+ addFacts(d, ctx.facts("data_flow"));
494
+ profile(ctx, d, "other-suppliers");
495
+ return d;
496
+ }),
497
+ q("data-categories", "data", "What categories of personal data are processed?", ["categories of personal data", "personal data categories", "types of personal data", "what personal data", "special category", "PII", "data types"], (ctx) => {
498
+ const d = draft();
499
+ profile(ctx, d, "personal-data-categories");
500
+ return d;
501
+ }),
502
+ q("data-separation", "data", "How is one customer's data separated from another's?", ["tenant", "segregation", "segregated", "separated from", "other customers", "separation", "multi-tenant", "row level security", "isolation"], (ctx) => {
503
+ const d = draft();
504
+ const withRls = ctx.facts("data_store").filter((f) => f.attributes.rowLevelSecurity !== void 0);
505
+ if (withRls.length > 0) addFacts(d, withRls);
506
+ profile(ctx, d, "tenant-separation");
507
+ return d;
508
+ }),
509
+ // ---- Access control
510
+ q("auth-methods", "access", "How do users authenticate?", ["authentication", "login", "sign in", "identity", "SSO", "user accounts"], (ctx) => {
511
+ const d = draft();
512
+ if (addFacts(d, ctx.facts("auth")) === 0) {
513
+ noneFound(ctx, d, "auth/none-found");
514
+ }
515
+ return d;
516
+ }),
517
+ q("auth-mfa", "access", "Is multi-factor authentication supported or required?", ["*MFA", "*2FA", "*two-factor", "*multi-factor", "*second factor"], (ctx) => {
518
+ const d = draft();
519
+ profile(ctx, d, "mfa");
520
+ return d;
521
+ }),
522
+ q("access-admin", "access", "Who has administrative access to production systems, and how is it controlled?", ["administrative access", "privileged access", "admin", "production access", "least privilege"], (ctx) => {
523
+ const d = draft();
524
+ profile(ctx, d, "admin-access");
525
+ return d;
526
+ }),
527
+ q("access-review", "access", "How often is access reviewed, and how is it removed when someone leaves?", ["access review", "joiners movers leavers", "offboarding", "recertification"], (ctx) => {
528
+ const d = draft();
529
+ profile(ctx, d, "access-review");
530
+ return d;
531
+ }),
532
+ q("access-passwords", "access", "What password and credential policies apply?", ["password policy", "password complexity", "credential policy"], (ctx) => {
533
+ const d = draft();
534
+ profile(ctx, d, "password-policy");
535
+ return d;
536
+ }),
537
+ // ---- Key management
538
+ q("keys-storage", "keys", "How are secrets and API keys stored?", ["secrets management", "key management", "how are API keys", "credentials storage", "vault", "environment variables", "secrets stored"], (ctx) => {
539
+ const d = draft();
540
+ if (addFacts(d, ctx.byDetector("secrets/env-usage")) === 0) profile(ctx, d, "secret-storage");
541
+ return d;
542
+ }),
543
+ q("keys-hardcoded", "keys", "Are credentials ever written into source code?", ["hard-coded", "hardcoded", "credentials in code", "secrets in source", "secret scanning"], (ctx) => {
544
+ const d = draft();
545
+ addFacts(d, ctx.byDetector("secrets/hardcoded-patterns"));
546
+ return d;
547
+ }),
548
+ q("keys-rotation", "keys", "How are keys rotated, and what happens if one is exposed?", ["key rotation", "*rotate", "*rotated", "*rotation", "compromised key", "revocation"], (ctx) => {
549
+ const d = draft();
550
+ profile(ctx, d, "secret-rotation");
551
+ return d;
552
+ }),
553
+ q("keys-browser", "keys", "Are any secrets exposed to browsers or client-side code?", ["client-side secrets", "exposed to the browser", "front-end secrets", "public keys"], (ctx) => {
554
+ const d = draft();
555
+ addFacts(d, ctx.byDetector("client-exposure/public-secret-name"));
556
+ addFacts(d, ctx.byDetector("client-exposure/ai-sdk-in-browser"));
557
+ return d;
558
+ }),
559
+ // ---- Logging and monitoring
560
+ q("logging-content", "logging", "What is logged, and does it include user content or personal data?", ["logging", "audit log", "personal data in logs", "what is logged", "log content"], (ctx) => {
561
+ const d = draft();
562
+ if (addFacts(d, ctx.byDetector("logging/request-body")) === 0) unanalysed(ctx, d);
563
+ return d;
564
+ }),
565
+ q("logging-retention", "logging", "How long are logs kept, and who can access them?", ["log retention", "log access", "log storage", "logs retained", "logs kept", "how long are logs", "logs retention"], (ctx) => {
566
+ const d = draft();
567
+ profile(ctx, d, "log-retention");
568
+ return d;
569
+ }),
570
+ q("monitoring", "logging", "What monitoring and alerting is in place?", ["monitoring", "alerting", "SIEM", "error tracking", "observability", "security events"], (ctx) => {
571
+ const d = draft();
572
+ fromServices(ctx, d, ["error tracking"], "monitoring");
573
+ return d;
574
+ }),
575
+ // ---- Suppliers and subprocessors
576
+ q("suppliers-list", "suppliers", "Which subprocessors and suppliers are used to deliver the service?", ["*subprocessor", "*sub-processor", "supplier list", "vendors", "third-party processors", "third-party suppliers", "third-party supplier", "suppliers that process", "who processes"], (ctx) => {
577
+ const d = draft();
578
+ const all = [...ctx.facts("third_party_service"), ...ctx.facts("ai_provider"), ...ctx.facts("data_store")];
579
+ if (all.length > 0) d.sentences.push(S(`The code uses these services: ${list(subjectsOf(all))}.`, ...refsOf(all)));
580
+ profile(ctx, d, "other-suppliers");
581
+ return d;
582
+ }),
583
+ q("suppliers-payments", "suppliers", "How are payments processed?", ["card data", "*PCI", "payment processor", "payment provider", "payments processed", "process payments", "take payments"], (ctx) => {
584
+ const d = draft();
585
+ fromServices(ctx, d, ["payments"], "payments");
586
+ return d;
587
+ }),
588
+ q("suppliers-analytics", "suppliers", "Do you use analytics or tracking tools, and what do they collect?", ["analytics", "tracking", "cookies", "telemetry", "usage data"], (ctx) => {
589
+ const d = draft();
590
+ fromServices(ctx, d, ["analytics"], "analytics");
591
+ return d;
592
+ }),
593
+ q("suppliers-email", "suppliers", "How is email sent to users?", ["email provider", "transactional email", "SMTP", "notifications"], (ctx) => {
594
+ const d = draft();
595
+ fromServices(ctx, d, ["email"], "email");
596
+ return d;
597
+ }),
598
+ q("suppliers-diligence", "suppliers", "How do you assess the security of your suppliers?", ["supplier assurance", "due diligence", "vendor risk", "third-party risk"], (ctx) => {
599
+ const d = draft();
600
+ profile(ctx, d, "supplier-diligence");
601
+ return d;
602
+ }),
603
+ // ---- Organisation and incident response
604
+ q("org-incident", "organisation", "Do you have an incident response process?", ["incident response", "security incident", "incident management", "IR plan"], (ctx) => {
605
+ const d = draft();
606
+ profile(ctx, d, "incident-response");
607
+ return d;
608
+ }),
609
+ q("org-breach", "organisation", "How and how quickly are customers notified of a personal data breach?", ["breach notification", "72 hours", "notify", "data breach"], (ctx) => {
610
+ const d = draft();
611
+ profile(ctx, d, "breach-notification");
612
+ return d;
613
+ }),
614
+ q("org-dpo", "organisation", "Who is responsible for data protection?", ["*DPO", "data protection officer", "privacy contact", "responsible person"], (ctx) => {
615
+ const d = draft();
616
+ profile(ctx, d, "dpo");
617
+ return d;
618
+ }),
619
+ q("org-vetting", "organisation", "What checks are made on staff and contractors?", ["staff vetting", "background checks", "BPSS", "security clearance", "personnel security"], (ctx) => {
620
+ const d = draft();
621
+ profile(ctx, d, "staff-vetting");
622
+ return d;
623
+ }),
624
+ q("org-training", "organisation", "What security and data protection training do staff receive?", ["training", "awareness", "security training"], (ctx) => {
625
+ const d = draft();
626
+ profile(ctx, d, "staff-training");
627
+ return d;
628
+ }),
629
+ q("org-backup", "organisation", "How is data backed up, and how long would recovery take?", ["backup", "disaster recovery", "business continuity", "*RTO", "*RPO", "recovery time", "recovery point", "resilience"], (ctx) => {
630
+ const d = draft();
631
+ profile(ctx, d, "backup-recovery");
632
+ return d;
633
+ }),
634
+ q("org-vulnerabilities", "organisation", "How are vulnerabilities identified and fixed?", ["vulnerability management", "*vulnerability", "*vulnerabilities", "patching", "penetration test", "dependency scanning", "security testing"], (ctx) => {
635
+ const d = draft();
636
+ const findings = ctx.evidence.findings;
637
+ if (findings.length > 0) {
638
+ const high = findings.filter((f) => f.severity === "critical" || f.severity === "high").length;
639
+ d.sentences.push(S(`A Seaworthy scan of the code reported ${findings.length} finding${findings.length === 1 ? "" : "s"}, ${high} of them high or critical.`, ...findings.map((f) => f.id)));
640
+ }
641
+ profile(ctx, d, "vulnerability-process");
642
+ return d;
643
+ }),
644
+ q("org-certifications", "organisation", "Which security certifications or independent assessments do you hold?", ["*ISO 27001", "*SOC 2", "*Cyber Essentials", "certification", "accreditation", "assurance"], (ctx) => {
645
+ const d = draft();
646
+ profile(ctx, d, "certifications");
647
+ return d;
648
+ }),
649
+ q("org-dpia", "organisation", "Has a data protection impact assessment been carried out?", ["*DPIA", "impact assessment", "privacy impact"], (ctx) => {
650
+ const d = draft();
651
+ profile(ctx, d, "dpia");
652
+ return d;
653
+ })
654
+ ];
655
+
656
+ // src/questions/context.ts
657
+ function buildAnswerCtx(evidence, answers) {
658
+ const byQuestion = new Map(answers.answers.map((a) => [a.question, a]));
659
+ const byId = new Map(evidence.facts.map((f) => [f.id, f]));
660
+ return {
661
+ evidence,
662
+ facts: (kind) => evidence.facts.filter((f) => f.kind === kind && f.claimType === "observed"),
663
+ absence: (kind, detector) => evidence.facts.find((f) => f.kind === kind && f.claimType === "not-found" && (!detector || f.detector === detector)),
664
+ byDetector: (detector) => evidence.facts.filter((f) => f.detector === detector),
665
+ answer: (key) => {
666
+ const a = byQuestion.get(key);
667
+ return a ? { id: a.id, value: a.value } : void 0;
668
+ },
669
+ unknownsWithTopic: (...topics) => evidence.unknowns.filter((u) => topics.includes(u.topic)),
670
+ factById: (id) => byId.get(id)
671
+ };
672
+ }
673
+
674
+ // src/questions/engine.ts
675
+ function renderSentence(s) {
676
+ const marker = `[${s.refs.join(", ")}]`;
677
+ const m = /^(.*?)([.!?])$/s.exec(s.text);
678
+ return m ? `${m[1]} ${marker}${m[2]}` : `${s.text} ${marker}`;
679
+ }
680
+ var EngineError = class extends Error {
681
+ };
682
+ function check(sentences2, known, id) {
683
+ for (const s of sentences2) {
684
+ if (s.refs.length === 0) throw new EngineError(`Question ${id} produced a sentence with no reference: "${s.text}"`);
685
+ for (const r of s.refs) if (!known.has(r)) throw new EngineError(`Question ${id} cites ${r}, which isn't in the evidence or answers.`);
686
+ }
687
+ }
688
+ function answerQuestion(q2, evidence, answers) {
689
+ const ctx = buildAnswerCtx(evidence, answers);
690
+ const known = /* @__PURE__ */ new Set([...evidence.facts.map((f) => f.id), ...evidence.findings.map((f) => f.id), ...answers.answers.map((a) => a.id)]);
691
+ const built = q2.build(ctx);
692
+ let { sentences: sentences2 } = built;
693
+ let needs = built.needs;
694
+ let overridden = false;
695
+ const override = ctx.answer(`override.${q2.id}`);
696
+ if (override) {
697
+ overridden = true;
698
+ const scanView = built.sentences.map((s) => s.text.replace(/\.\s*$/, "")).join("; ");
699
+ sentences2 = [answerSentence("Stated by the project team", override.value, override.id)];
700
+ if (scanView) {
701
+ sentences2.push({ text: `For reference, the code scan reported something different: ${scanView}.`, refs: [...new Set(built.sentences.flatMap((s) => s.refs))] });
702
+ }
703
+ needs = [];
704
+ }
705
+ check(sentences2, known, q2.id);
706
+ const refs = [...new Set(sentences2.flatMap((s) => s.refs))];
707
+ const status2 = sentences2.length === 0 ? "needs-input" : needs.length === 0 ? "answered" : "partial";
708
+ return {
709
+ id: q2.id,
710
+ category: q2.category,
711
+ question: q2.text,
712
+ status: status2,
713
+ answer: sentences2.map(renderSentence).join(" "),
714
+ refs,
715
+ needs,
716
+ overridden
717
+ };
718
+ }
719
+ function answerAll(evidence, answers) {
720
+ return BANK.map((q2) => answerQuestion(q2, evidence, answers));
721
+ }
722
+ function pendingNeeds(evidence, results, answers) {
723
+ const answered = new Set(answers.answers.map((a) => a.question));
724
+ const map = /* @__PURE__ */ new Map();
725
+ for (const u of evidence.unknowns) if (!answered.has(u.id)) map.set(u.id, { key: u.id, prompt: u.question, helps: [] });
726
+ for (const r of results) {
727
+ for (const n of r.needs) {
728
+ if (answered.has(n.key)) continue;
729
+ const p = map.get(n.key) ?? { key: n.key, prompt: n.prompt, helps: [] };
730
+ p.helps.push(r.id);
731
+ map.set(n.key, p);
732
+ }
733
+ }
734
+ const unknownFirst = [...map.values()].sort((a, b) => Number(b.key.startsWith("UQ-")) - Number(a.key.startsWith("UQ-")));
735
+ return unknownFirst;
736
+ }
737
+
738
+ // src/documents/templates.ts
739
+ var clean = (s) => s.replace(/\s+/g, " ").trim();
740
+ var TEMPLATES = {
741
+ privacyIntro: "This notice describes how personal data is handled in connection with this service. It was drafted from the project's code and from information supplied by the project team.",
742
+ privacyRights: "People whose personal data is processed have rights under data protection law. They can ask for access to their data, ask for inaccurate data to be corrected, ask for data to be erased in some circumstances, ask for processing to be restricted, object to processing, and ask to receive their data in a portable format. They can also complain to the data protection regulator; in the United Kingdom this is the Information Commissioner's Office.",
743
+ privacyContact: "Questions about this notice, and requests to exercise these rights, can be sent to the contact given above.",
744
+ privacyChanges: "This notice may be updated from time to time. The date at the top shows when it was last prepared.",
745
+ subprocessorsIntro: "This list shows the external services that the project's code integrates with, together with the information the project team has supplied about them.",
746
+ dpiaIntro: "A data protection impact assessment describes a processing activity, considers whether it is necessary and proportionate, identifies risks to individuals and records the measures chosen to reduce them. This draft sets out what the code shows and what the project team has said. The assessment itself must be completed and approved by the people responsible.",
747
+ dpiaSignoff: "Approved by: ____________________ Role: ____________________ Date: ____________________",
748
+ aiIntro: "This statement describes how artificial intelligence services are used. It reflects the project's code and the project team's answers on the date shown.",
749
+ trustIntro: "This page summarises security and data handling practices. Each statement is backed by a numbered source at the end of the page."
750
+ };
751
+ var sentences = (text) => clean(text).split(/(?<=[.!?])\s+(?=[A-Z"'(\[])/).map(clean);
752
+ var TEMPLATE_SENTENCES = new Set(
753
+ Object.values(TEMPLATES).flatMap((t) => [clean(t), ...sentences(t)])
754
+ );
755
+ var isTemplateSentence = (s) => TEMPLATE_SENTENCES.has(clean(s));
756
+
757
+ // src/documents/build.ts
758
+ var DOCUMENTS = [
759
+ { id: "privacy-notice", title: "Privacy notice", about: "what personal data is handled, why, where, for how long, and who receives it" },
760
+ { id: "subprocessors", title: "Subprocessor list", about: "the external services the code integrates with, and what the team has said about each" },
761
+ { id: "dpia", title: "Data protection impact assessment", about: "the processing, what the code shows that bears on risk, and what is left to the people responsible" },
762
+ { id: "ai-use", title: "AI-use statement", about: "which AI providers are used, for what, with what data, and with what oversight" },
763
+ { id: "trust-page", title: "Trust page", about: "a short, client-facing summary of security and data handling" }
764
+ ];
765
+ function fromBank(ctx, ...ids) {
766
+ const out = draft();
767
+ for (const id of ids) {
768
+ const q2 = BANK.find((b) => b.id === id);
769
+ if (!q2) throw new Error(`unknown bank question ${id}`);
770
+ const d = q2.build(ctx);
771
+ out.sentences.push(...d.sentences);
772
+ for (const n of d.needs) if (!out.needs.some((x) => x.key === n.key)) out.needs.push(n);
773
+ }
774
+ return out;
775
+ }
776
+ var Doc = class {
777
+ constructor(title, date) {
778
+ this.title = title;
779
+ this.date = date;
780
+ }
781
+ title;
782
+ date;
783
+ lines = [];
784
+ needs = [];
785
+ heading(text) {
786
+ this.lines.push(`## ${text}`, "");
787
+ }
788
+ text(s) {
789
+ this.lines.push(s, "");
790
+ }
791
+ /** A draft as a paragraph, with its missing items noted underneath. */
792
+ draft(d) {
793
+ if (d.sentences.length) this.lines.push(d.sentences.map(renderSentence).join(" "), "");
794
+ this.noteNeeds(d.needs);
795
+ }
796
+ /** A draft as a bullet list, one bullet per sentence. */
797
+ bullets(d) {
798
+ if (d.sentences.length) this.lines.push(...d.sentences.map((s) => `- ${renderSentence(s)}`), "");
799
+ this.noteNeeds(d.needs);
800
+ }
801
+ noteNeeds(needs) {
802
+ for (const n of needs) {
803
+ this.lines.push(`**Needs your input.** ${n.prompt}`, "");
804
+ if (!this.needs.some((x) => x.key === n.key)) this.needs.push(n);
805
+ }
806
+ }
807
+ render() {
808
+ const head = [`# ${this.title} (draft, ${this.date})`, "", `> ${DRAFT_NOTICE}`, ""];
809
+ const open = this.needs.length ? ["## Open items", "", ...this.needs.map((n) => `- Needs your input: ${n.prompt}`), ""] : [];
810
+ return [...head, ...this.lines, ...open].join("\n");
811
+ }
812
+ };
813
+ var factsBy = (ctx, detector) => ctx.byDetector(detector);
814
+ function serviceRows(ctx) {
815
+ const by = /* @__PURE__ */ new Map();
816
+ for (const kind of ["third_party_service", "ai_provider", "data_store"]) {
817
+ for (const f of ctx.facts(kind)) {
818
+ const key = `${kind}|${f.subject}`;
819
+ const row = by.get(key) ?? { subject: f.subject, kind, facts: [] };
820
+ row.facts.push(f);
821
+ by.set(key, row);
822
+ }
823
+ }
824
+ const NOT_YET = NOT_YET_PROVIDED;
825
+ const rows = [];
826
+ for (const { subject, kind, facts } of by.values()) {
827
+ const ids = refsOf(facts);
828
+ const cite = (text, extra = []) => `${text} [${[...ids, ...extra].join(", ")}]`;
829
+ const purpose = kind === "ai_provider" ? "AI model provider" : kind === "data_store" ? "Data storage" : String(facts[0].attributes.purpose ?? "External service");
830
+ const flows = kind === "ai_provider" ? ctx.facts("data_flow").filter((f) => f.subject === subject) : [];
831
+ const categories = [...new Set(flows.flatMap((f) => Array.isArray(f.attributes.dataCategories) ? f.attributes.dataCategories : []))];
832
+ const data = flows.length ? `${categories.join(", ") || "Content sent in prompts"} [${refsOf(flows).join(", ")}]` : kind === "data_store" ? cite("Application data") : NOT_YET;
833
+ let location = NOT_YET;
834
+ if (kind === "data_store") {
835
+ const u = ctx.unknownsWithTopic("Data region", "Database hosting").find((x) => x.relatedFacts.some((id) => ids.includes(id)));
836
+ const a = u ? ctx.answer(u.id) : void 0;
837
+ if (a) location = `${a.value.replace(/[|\[\]]/g, " ").replace(/\s+/g, " ").trim()} [${a.id}]`;
838
+ } else if (kind === "ai_provider") {
839
+ const a = ctx.answer("profile.ai-processing-region");
840
+ if (a) location = `${a.value.replace(/[|\[\]]/g, " ").replace(/\s+/g, " ").trim()} [${a.id}]`;
841
+ }
842
+ rows.push([cite(subject), cite(purpose), data, location]);
843
+ }
844
+ return rows.sort((a, b) => a[0].localeCompare(b[0]));
845
+ }
846
+ function table(header, rows) {
847
+ return [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`, ...rows.map((r) => `| ${r.join(" | ")} |`), ""];
848
+ }
849
+ function privacyNotice(d, ctx) {
850
+ d.text(TEMPLATES.privacyIntro);
851
+ d.heading("Who is responsible");
852
+ const who = draft();
853
+ profile(ctx, who, "organisation-name");
854
+ profile(ctx, who, "service-description");
855
+ profile(ctx, who, "dpo");
856
+ d.bullets(who);
857
+ d.heading("What personal data is handled");
858
+ const data = fromBank(ctx, "data-categories");
859
+ addFacts(data, ctx.facts("data_flow"));
860
+ d.draft(data);
861
+ d.heading("Why it is used");
862
+ const why = draft();
863
+ profile(ctx, why, "lawful-basis");
864
+ d.draft(why);
865
+ d.heading("Who receives it");
866
+ d.draft(fromBank(ctx, "data-recipients"));
867
+ d.heading("Where it is stored");
868
+ d.draft(fromBank(ctx, "data-stores", "data-region"));
869
+ d.heading("How long it is kept");
870
+ d.draft(fromBank(ctx, "data-retention", "data-deletion"));
871
+ d.heading("How it is protected");
872
+ d.draft(fromBank(ctx, "auth-methods", "data-encryption-rest", "data-encryption-transit", "data-separation", "keys-storage"));
873
+ d.heading("Use of artificial intelligence");
874
+ d.draft(fromBank(ctx, "ai-use", "ai-providers", "ai-training"));
875
+ d.heading("Your rights");
876
+ d.text(TEMPLATES.privacyRights);
877
+ d.text(TEMPLATES.privacyContact);
878
+ d.heading("Changes to this notice");
879
+ d.text(TEMPLATES.privacyChanges);
880
+ }
881
+ function subprocessors(d, ctx) {
882
+ d.text(TEMPLATES.subprocessorsIntro);
883
+ d.heading("External services");
884
+ const rows = serviceRows(ctx);
885
+ if (rows.length) d.lines.push(...table(["Service", "Purpose", "Data", "Location"], rows));
886
+ else {
887
+ const none = draft();
888
+ for (const id of ["ai-provider/none-found", "data-store/none-found"]) {
889
+ const f = factsBy(ctx, id)[0];
890
+ if (f) addFacts(none, [f]);
891
+ }
892
+ if (none.sentences.length === 0) unanalysed(ctx, none);
893
+ d.draft(none);
894
+ }
895
+ d.heading("Other suppliers");
896
+ const other = draft();
897
+ profile(ctx, other, "other-suppliers");
898
+ d.draft(other);
899
+ }
900
+ function dpia(d, ctx) {
901
+ d.text(TEMPLATES.dpiaIntro);
902
+ d.heading("1. Description of the processing");
903
+ const desc = draft();
904
+ profile(ctx, desc, "service-description");
905
+ d.draft(desc);
906
+ d.bullets(fromBank(ctx, "data-categories", "data-stores", "data-recipients", "ai-use"));
907
+ d.heading("2. Necessity and proportionality");
908
+ const basis = draft();
909
+ profile(ctx, basis, "lawful-basis");
910
+ d.draft(basis);
911
+ d.draft(fromBank(ctx, "data-retention", "data-deletion"));
912
+ d.heading("3. What the code shows that bears on risk");
913
+ const obs = draft();
914
+ addFacts(obs, factsBy(ctx, "logging/request-body"));
915
+ addFacts(obs, factsBy(ctx, "secrets/hardcoded-patterns"));
916
+ addFacts(obs, ctx.byDetector("client-exposure/public-secret-name"));
917
+ addFacts(obs, ctx.byDetector("client-exposure/ai-sdk-in-browser"));
918
+ addFacts(obs, ctx.facts("data_store").filter((f) => f.attributes.rowLevelSecurity !== void 0));
919
+ const serious = ctx.evidence.findings.filter((f) => f.severity === "critical" || f.severity === "high");
920
+ for (const f of serious) obs.sentences.push({ text: `A Seaworthy scan reported a ${f.severity}-severity finding (${f.ruleId}).`, refs: [f.id] });
921
+ d.bullets(obs);
922
+ d.bullets(fromBank(ctx, "ai-training"));
923
+ d.heading("4. Measures to reduce risk");
924
+ const measures = draft();
925
+ profile(ctx, measures, "dpia-risk-measures");
926
+ d.draft(measures);
927
+ d.bullets(fromBank(ctx, "auth-mfa", "access-admin", "data-encryption-rest", "data-encryption-transit", "org-incident", "org-breach"));
928
+ d.heading("5. Consultation");
929
+ const consult = draft();
930
+ profile(ctx, consult, "dpia-consultation");
931
+ d.draft(consult);
932
+ d.heading("6. Sign-off");
933
+ d.text(TEMPLATES.dpiaSignoff);
934
+ }
935
+ function aiUse(d, ctx) {
936
+ d.text(TEMPLATES.aiIntro);
937
+ const used = ctx.facts("ai_provider").length > 0;
938
+ d.heading("Whether AI is used");
939
+ d.draft(fromBank(ctx, "ai-use"));
940
+ if (!used) return;
941
+ d.heading("Purpose");
942
+ const purpose = draft();
943
+ profile(ctx, purpose, "ai-purpose");
944
+ d.draft(purpose);
945
+ d.heading("Providers and models");
946
+ d.draft(fromBank(ctx, "ai-providers"));
947
+ d.heading("Data sent to AI providers");
948
+ d.draft(fromBank(ctx, "ai-data-sent"));
949
+ d.heading("How providers may use that data");
950
+ d.draft(fromBank(ctx, "ai-training"));
951
+ d.heading("Human oversight");
952
+ d.draft(fromBank(ctx, "ai-oversight"));
953
+ d.heading("Where processing happens");
954
+ d.draft(fromBank(ctx, "ai-region"));
955
+ d.heading("Access and credentials");
956
+ d.draft(fromBank(ctx, "ai-keys", "ai-browser"));
957
+ }
958
+ function trustPage(d, ctx) {
959
+ d.text(TEMPLATES.trustIntro);
960
+ d.heading("Security at a glance");
961
+ d.bullets(fromBank(ctx, "auth-methods", "data-stores", "data-region", "data-encryption-rest", "data-encryption-transit", "keys-storage", "keys-hardcoded", "keys-browser"));
962
+ d.heading("Use of AI");
963
+ d.bullets(fromBank(ctx, "ai-use", "ai-providers", "ai-training"));
964
+ d.heading("Suppliers");
965
+ const rows = serviceRows(ctx);
966
+ if (rows.length) d.lines.push(...table(["Service", "Purpose", "Data", "Location"], rows));
967
+ d.heading("Contact and incidents");
968
+ d.bullets(fromBank(ctx, "org-dpo", "org-incident", "org-breach"));
969
+ }
970
+ var BUILDERS = {
971
+ "privacy-notice": privacyNotice,
972
+ subprocessors,
973
+ dpia,
974
+ "ai-use": aiUse,
975
+ "trust-page": trustPage
976
+ };
977
+ function isDocumentId(s) {
978
+ return s in BUILDERS;
979
+ }
980
+ function buildDocument(id, evidence, answers, opts) {
981
+ const meta = DOCUMENTS.find((x) => x.id === id);
982
+ const ctx = buildAnswerCtx(evidence, answers);
983
+ const d = new Doc(`${meta.title}: ${evidence.project.name}`, evidence.generatedAt.slice(0, 10));
984
+ BUILDERS[id](d, ctx);
985
+ const body = d.render();
986
+ const refs = usedRefs([body]);
987
+ const sources = refs.length ? ["", "## Sources", "", ...footnoteLines(refs, evidence, answers, opts), ""] : [];
988
+ const markdown = [withFootnoteMarks(body), ...sources].join("\n");
989
+ return { id, title: meta.title, markdown, needs: d.needs };
990
+ }
991
+ function documentNeeds(evidence, answers) {
992
+ const all = /* @__PURE__ */ new Map();
993
+ for (const { id } of DOCUMENTS) for (const n of buildDocument(id, evidence, answers, { locations: false }).needs) all.set(n.key, n);
994
+ return [...all.values()];
995
+ }
996
+
997
+ // src/export/markdown-model.ts
998
+ var FOOTNOTE_DEF = /^\[\^([A-Za-z0-9-]+)\]:\s*(.*)$/;
999
+ var isTableRow = (l) => /^\s*\|.*\|\s*$/.test(l);
1000
+ var isSeparator = (l) => /^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(l) && /-/.test(l);
1001
+ var cells = (l) => l.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim());
1002
+ function parseMarkdown(source) {
1003
+ const blocks = [];
1004
+ const footnotes = /* @__PURE__ */ new Map();
1005
+ const lines = source.split(/\r?\n/);
1006
+ let para2 = [];
1007
+ let bullets = null;
1008
+ let table2 = null;
1009
+ let quote = null;
1010
+ const flush = () => {
1011
+ if (para2.length) blocks.push({ type: "paragraph", text: para2.join(" ") });
1012
+ if (bullets) blocks.push({ type: "bullets", items: bullets });
1013
+ if (table2) blocks.push({ type: "table", rows: table2 });
1014
+ if (quote) blocks.push({ type: "quote", text: quote.join(" ") });
1015
+ para2 = [];
1016
+ bullets = null;
1017
+ table2 = null;
1018
+ quote = null;
1019
+ };
1020
+ for (const line of lines) {
1021
+ const def = FOOTNOTE_DEF.exec(line);
1022
+ if (def) {
1023
+ flush();
1024
+ footnotes.set(def[1], def[2].trim());
1025
+ continue;
1026
+ }
1027
+ const heading = /^(#{1,3})\s+(.*)$/.exec(line);
1028
+ if (heading) {
1029
+ flush();
1030
+ blocks.push({ type: "heading", level: heading[1].length, text: heading[2].trim() });
1031
+ } else if (line.trim() === "") {
1032
+ flush();
1033
+ } else if (isTableRow(line)) {
1034
+ if (!table2) {
1035
+ flush();
1036
+ table2 = [];
1037
+ }
1038
+ if (!isSeparator(line)) table2.push(cells(line));
1039
+ } else if (/^\s*[-*]\s+/.test(line)) {
1040
+ if (!bullets) {
1041
+ flush();
1042
+ bullets = [];
1043
+ }
1044
+ bullets.push(line.replace(/^\s*[-*]\s+/, "").trim());
1045
+ } else if (/^>\s?/.test(line)) {
1046
+ if (!quote) {
1047
+ flush();
1048
+ quote = [];
1049
+ }
1050
+ quote.push(line.replace(/^>\s?/, "").trim());
1051
+ } else {
1052
+ if (bullets || table2 || quote) flush();
1053
+ para2.push(line.trim());
1054
+ }
1055
+ }
1056
+ flush();
1057
+ return { blocks, footnotes };
1058
+ }
1059
+ function inlines(text) {
1060
+ const out = [];
1061
+ const re = /\*\*(.+?)\*\*|\[\^([A-Za-z0-9-]+)\]/g;
1062
+ let last = 0;
1063
+ for (let m = re.exec(text); m; m = re.exec(text)) {
1064
+ if (m.index > last) out.push({ kind: "text", text: text.slice(last, m.index), bold: false });
1065
+ if (m[1] !== void 0) out.push({ kind: "text", text: m[1], bold: true });
1066
+ else out.push({ kind: "note", id: m[2] });
1067
+ last = m.index + m[0].length;
1068
+ }
1069
+ if (last < text.length) out.push({ kind: "text", text: text.slice(last), bold: false });
1070
+ return out;
1071
+ }
1072
+ function noteOrder(doc) {
1073
+ const seen = [];
1074
+ const visit = (text) => {
1075
+ for (const i of inlines(text)) if (i.kind === "note" && !seen.includes(i.id)) seen.push(i.id);
1076
+ };
1077
+ for (const b of doc.blocks) {
1078
+ if (b.type === "paragraph" || b.type === "quote" || b.type === "heading") visit(b.text);
1079
+ else if (b.type === "bullets") b.items.forEach(visit);
1080
+ else if (b.type === "table") b.rows.forEach((r) => r.forEach(visit));
1081
+ }
1082
+ return seen;
1083
+ }
1084
+
1085
+ // src/export/zip.ts
1086
+ var CRC_TABLE = (() => {
1087
+ const t = new Uint32Array(256);
1088
+ for (let n = 0; n < 256; n++) {
1089
+ let c = n;
1090
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
1091
+ t[n] = c >>> 0;
1092
+ }
1093
+ return t;
1094
+ })();
1095
+ function crc32(buf) {
1096
+ let c = 4294967295;
1097
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
1098
+ return (c ^ 4294967295) >>> 0;
1099
+ }
1100
+ var u16 = (n) => Buffer.from([n & 255, n >>> 8 & 255]);
1101
+ var u32 = (n) => Buffer.from([n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255]);
1102
+ var DOS_TIME = 0;
1103
+ var DOS_DATE = 0 << 9 | 1 << 5 | 1;
1104
+ function zip(entries) {
1105
+ const local = [];
1106
+ const central = [];
1107
+ let offset = 0;
1108
+ for (const e of entries) {
1109
+ const name = Buffer.from(e.name, "utf8");
1110
+ const data = typeof e.data === "string" ? Buffer.from(e.data, "utf8") : Buffer.from(e.data);
1111
+ const crc = crc32(data);
1112
+ const header = Buffer.concat([
1113
+ u32(67324752),
1114
+ u16(20),
1115
+ u16(2048),
1116
+ u16(0),
1117
+ u16(DOS_TIME),
1118
+ u16(DOS_DATE),
1119
+ u32(crc),
1120
+ u32(data.length),
1121
+ u32(data.length),
1122
+ u16(name.length),
1123
+ u16(0),
1124
+ name
1125
+ ]);
1126
+ local.push(header, data);
1127
+ central.push(
1128
+ Buffer.concat([
1129
+ u32(33639248),
1130
+ u16(20),
1131
+ u16(20),
1132
+ u16(2048),
1133
+ u16(0),
1134
+ u16(DOS_TIME),
1135
+ u16(DOS_DATE),
1136
+ u32(crc),
1137
+ u32(data.length),
1138
+ u32(data.length),
1139
+ u16(name.length),
1140
+ u16(0),
1141
+ u16(0),
1142
+ u16(0),
1143
+ u16(0),
1144
+ u32(0),
1145
+ u32(offset),
1146
+ name
1147
+ ])
1148
+ );
1149
+ offset += header.length + data.length;
1150
+ }
1151
+ const centralBuf = Buffer.concat(central);
1152
+ const end = Buffer.concat([u32(101010256), u16(0), u16(0), u16(entries.length), u16(entries.length), u32(centralBuf.length), u32(offset), u16(0)]);
1153
+ return Buffer.concat([...local, centralBuf, end]);
1154
+ }
1155
+
1156
+ // src/export/docx.ts
1157
+ var NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
1158
+ var XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
1159
+ var esc = (s) => s.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1160
+ var run = (text, bold = false) => `<w:r>${bold ? "<w:rPr><w:b/></w:rPr>" : ""}<w:t xml:space="preserve">${esc(text)}</w:t></w:r>`;
1161
+ function runs(text, noteId, forceBold = false) {
1162
+ return inlines(text).map(
1163
+ (i) => i.kind === "text" ? run(i.text, i.bold || forceBold) : `<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/></w:rPr><w:footnoteReference w:id="${noteId(i.id)}"/></w:r>`
1164
+ ).join("");
1165
+ }
1166
+ var para = (inner, style, extra = "") => `<w:p><w:pPr>${style ? `<w:pStyle w:val="${style}"/>` : ""}${extra}</w:pPr>${inner}</w:p>`;
1167
+ function blockXml(b, noteId) {
1168
+ switch (b.type) {
1169
+ case "heading":
1170
+ return para(runs(b.text, noteId), `Heading${b.level}`);
1171
+ case "paragraph":
1172
+ return para(runs(b.text, noteId));
1173
+ case "quote":
1174
+ return para(runs(b.text, noteId), "Quote");
1175
+ case "bullets":
1176
+ return b.items.map((i) => para(run("\u2022 ") + runs(i, noteId), "ListParagraph", '<w:ind w:left="567" w:hanging="283"/><w:tabs><w:tab w:val="left" w:pos="567"/></w:tabs>')).join("");
1177
+ case "table": {
1178
+ const cols = Math.max(...b.rows.map((r) => r.length), 1);
1179
+ const width = Math.floor(9e3 / cols);
1180
+ const border = (side) => `<w:${side} w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>`;
1181
+ const rows = b.rows.map((cells2, ri) => {
1182
+ const tcs = Array.from({ length: cols }, (_, ci) => {
1183
+ const text = cells2[ci] ?? "";
1184
+ const shade = ri === 0 ? '<w:shd w:val="clear" w:color="auto" w:fill="EEF2F6"/>' : "";
1185
+ return `<w:tc><w:tcPr><w:tcW w:w="${width}" w:type="dxa"/>${shade}</w:tcPr>${para(runs(text, noteId, ri === 0))}</w:tc>`;
1186
+ }).join("");
1187
+ return `<w:tr>${ri === 0 ? "<w:trPr><w:tblHeader/></w:trPr>" : ""}${tcs}</w:tr>`;
1188
+ }).join("");
1189
+ return `<w:tbl><w:tblPr><w:tblW w:w="${width * cols}" w:type="dxa"/><w:tblBorders>${["top", "left", "bottom", "right", "insideH", "insideV"].map(border).join("")}</w:tblBorders><w:tblLayout w:type="fixed"/></w:tblPr><w:tblGrid>${Array.from({ length: cols }, () => `<w:gridCol w:w="${width}"/>`).join("")}</w:tblGrid>${rows}</w:tbl>` + para("");
1190
+ }
1191
+ }
1192
+ }
1193
+ var STYLES = `${XML}
1194
+ <w:styles ${NS}>
1195
+ <w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:cs="Calibri"/><w:sz w:val="22"/><w:lang w:val="en-GB"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>
1196
+ <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>
1197
+ <w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="160"/><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:b/><w:color w:val="14507A"/><w:sz w:val="36"/></w:rPr></w:style>
1198
+ <w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="320" w:after="100"/><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:b/><w:color w:val="14507A"/><w:sz w:val="28"/></w:rPr></w:style>
1199
+ <w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="200" w:after="80"/><w:outlineLvl w:val="2"/></w:pPr><w:rPr><w:b/><w:sz w:val="24"/></w:rPr></w:style>
1200
+ <w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:after="60"/></w:pPr></w:style>
1201
+ <w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="14507A"/></w:pBdr><w:ind w:left="284"/></w:pPr><w:rPr><w:i/><w:color w:val="595959"/><w:sz w:val="20"/></w:rPr></w:style>
1202
+ <w:style w:type="paragraph" w:styleId="FootnoteText"><w:name w:val="footnote text"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:sz w:val="18"/></w:rPr></w:style>
1203
+ <w:style w:type="character" w:styleId="FootnoteReference"><w:name w:val="footnote reference"/><w:rPr><w:vertAlign w:val="superscript"/></w:rPr></w:style>
1204
+ </w:styles>`;
1205
+ var SETTINGS = `${XML}
1206
+ <w:settings ${NS}><w:footnotePr><w:footnote w:id="-1"/><w:footnote w:id="0"/></w:footnotePr></w:settings>`;
1207
+ var CONTENT_TYPES = `${XML}
1208
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/><Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>`;
1209
+ var ROOT_RELS = `${XML}
1210
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/></Relationships>`;
1211
+ var DOC_RELS = `${XML}
1212
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/></Relationships>`;
1213
+ function renderDocx(markdown, opts) {
1214
+ const doc = parseMarkdown(markdown);
1215
+ const order = noteOrder(doc);
1216
+ const noteId = (id) => order.indexOf(id) + 1;
1217
+ const blocks = doc.blocks.filter((b) => !(b.type === "heading" && b.level === 2 && b.text === "Sources"));
1218
+ const body = blocks.map((b) => blockXml(b, noteId)).join("");
1219
+ const document = `${XML}
1220
+ <w:document ${NS}><w:body>${body}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1304" w:right="1304" w:bottom="1304" w:left="1304" w:header="708" w:footer="708" w:gutter="0"/></w:sectPr></w:body></w:document>`;
1221
+ const notes = order.map(
1222
+ (id, i) => `<w:footnote w:id="${i + 1}"><w:p><w:pPr><w:pStyle w:val="FootnoteText"/></w:pPr><w:r><w:rPr><w:rStyle w:val="FootnoteReference"/></w:rPr><w:footnoteRef/></w:r>${run(` ${doc.footnotes.get(id) ?? "Source not found."}`)}</w:p></w:footnote>`
1223
+ ).join("");
1224
+ const footnotes = `${XML}
1225
+ <w:footnotes ${NS}><w:footnote w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></w:footnote><w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>${notes}</w:footnotes>`;
1226
+ const core = `${XML}
1227
+ <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>${esc(opts.title)}</dc:title><dc:creator>Soundings</dc:creator><dcterms:created xsi:type="dcterms:W3CDTF">${esc(opts.created)}</dcterms:created></cp:coreProperties>`;
1228
+ return zip([
1229
+ { name: "[Content_Types].xml", data: CONTENT_TYPES },
1230
+ { name: "_rels/.rels", data: ROOT_RELS },
1231
+ { name: "word/document.xml", data: document },
1232
+ { name: "word/_rels/document.xml.rels", data: DOC_RELS },
1233
+ { name: "word/styles.xml", data: STYLES },
1234
+ { name: "word/settings.xml", data: SETTINGS },
1235
+ { name: "word/footnotes.xml", data: footnotes },
1236
+ { name: "docProps/core.xml", data: core }
1237
+ ]);
1238
+ }
1239
+
1240
+ // src/export/html.ts
1241
+ var esc2 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1242
+ var CSS = `
1243
+ :root{color-scheme:light dark;--bg:#fff;--fg:#1c2530;--muted:#5b6673;--line:#d6dce3;--accent:#14507a;--quote:#f3f6f9}
1244
+ @media (prefers-color-scheme:dark){:root{--bg:#12171d;--fg:#e6ebf0;--muted:#9aa6b2;--line:#2c3540;--accent:#7cb8e0;--quote:#1a222b}}
1245
+ *{box-sizing:border-box}
1246
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.6 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
1247
+ main{max-width:46rem;margin:0 auto;padding:2rem 1rem 4rem}
1248
+ h1{font-size:1.7rem;line-height:1.25;margin:0 0 1rem}
1249
+ h2{font-size:1.3rem;margin:2.2rem 0 .6rem;padding-top:.4rem;border-top:1px solid var(--line)}
1250
+ h3{font-size:1.05rem;margin:1.4rem 0 .4rem}
1251
+ p,li{margin:.5rem 0}
1252
+ ul{padding-left:1.3rem}
1253
+ blockquote{margin:1rem 0;padding:.7rem 1rem;background:var(--quote);border-left:4px solid var(--accent);color:var(--muted);font-size:.93rem}
1254
+ .table{overflow-x:auto}
1255
+ table{border-collapse:collapse;width:100%;font-size:.93rem}
1256
+ th,td{border:1px solid var(--line);padding:.45rem .6rem;text-align:left;vertical-align:top}
1257
+ th{background:var(--quote)}
1258
+ sup a{color:var(--accent);text-decoration:none;font-size:.78em}
1259
+ a{color:var(--accent)}
1260
+ .sources{font-size:.88rem;color:var(--muted)}
1261
+ .sources li{margin:.3rem 0}
1262
+ @media print{main{max-width:none;padding:0}h2{break-after:avoid}blockquote,table,li{break-inside:avoid}a{color:inherit}}
1263
+ `;
1264
+ function inlineHtml(text, order) {
1265
+ return inlines(text).map((i) => {
1266
+ if (i.kind === "text") return i.bold ? `<strong>${esc2(i.text)}</strong>` : esc2(i.text);
1267
+ const n = order.indexOf(i.id) + 1;
1268
+ return `<sup><a href="#fn-${esc2(i.id)}" id="ref-${esc2(i.id)}" aria-label="Source ${n}">[${n}]</a></sup>`;
1269
+ }).join("");
1270
+ }
1271
+ function blockHtml(b, order) {
1272
+ switch (b.type) {
1273
+ case "heading":
1274
+ return `<h${b.level}>${inlineHtml(b.text, order)}</h${b.level}>`;
1275
+ case "paragraph":
1276
+ return `<p>${inlineHtml(b.text, order)}</p>`;
1277
+ case "quote":
1278
+ return `<blockquote>${inlineHtml(b.text, order)}</blockquote>`;
1279
+ case "bullets":
1280
+ return `<ul>${b.items.map((i) => `<li>${inlineHtml(i, order)}</li>`).join("")}</ul>`;
1281
+ case "table": {
1282
+ const [head, ...body] = b.rows;
1283
+ const row = (cells2, tag2) => `<tr>${cells2.map((c) => `<${tag2}>${inlineHtml(c, order)}</${tag2}>`).join("")}</tr>`;
1284
+ return `<div class="table"><table><thead>${head ? row(head, "th") : ""}</thead><tbody>${body.map((r) => row(r, "td")).join("")}</tbody></table></div>`;
1285
+ }
1286
+ }
1287
+ }
1288
+ function renderHtml(markdown, title) {
1289
+ const doc = parseMarkdown(markdown);
1290
+ const order = noteOrder(doc);
1291
+ const body = doc.blocks.map((b) => blockHtml(b, order)).join("\n");
1292
+ const sources = order.length ? `<h2>Sources</h2>
1293
+ <ol class="sources">${order.map((id) => `<li id="fn-${esc2(id)}">${esc2(doc.footnotes.get(id) ?? "Source not found.")} <a href="#ref-${esc2(id)}" aria-label="Back to text">\u21A9</a></li>`).join("")}</ol>` : "";
1294
+ return `<!doctype html>
1295
+ <html lang="en-GB">
1296
+ <head>
1297
+ <meta charset="utf-8">
1298
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1299
+ <title>${esc2(title)}</title>
1300
+ <style>${CSS}</style>
1301
+ </head>
1302
+ <body>
1303
+ <main>
1304
+ ${body.replace(/<h2>Sources<\/h2>/, "")}
1305
+ ${sources}
1306
+ </main>
1307
+ </body>
1308
+ </html>
1309
+ `;
1310
+ }
1311
+
1312
+ // src/export/render.ts
1313
+ var EXPORT_FORMATS = ["markdown", "html", "docx"];
1314
+ var isExportFormat = (s) => EXPORT_FORMATS.includes(s);
1315
+ function renderExport(markdown, format, meta) {
1316
+ if (format === "markdown") return markdown.endsWith("\n") ? markdown : `${markdown}
1317
+ `;
1318
+ if (format === "html") return renderHtml(markdown, meta.title);
1319
+ return renderDocx(markdown, meta);
1320
+ }
1321
+
1322
+ // src/import/csv.ts
1323
+ function detectDelimiter(text) {
1324
+ const firstLine = text.replace(/^/, "").split(/\r?\n/, 1)[0] ?? "";
1325
+ const counts = [",", ";", " "].map((d) => [d, firstLine.split(d).length - 1]);
1326
+ return counts.sort((a, b) => b[1] - a[1])[0][0];
1327
+ }
1328
+ function parseCsv(input, delimiter = detectDelimiter(input)) {
1329
+ const text = input.replace(/^/, "");
1330
+ const rows = [];
1331
+ let row = [];
1332
+ let cell2 = "";
1333
+ let quoted = false;
1334
+ for (let i = 0; i < text.length; i++) {
1335
+ const c = text[i];
1336
+ if (quoted) {
1337
+ if (c === '"') {
1338
+ if (text[i + 1] === '"') {
1339
+ cell2 += '"';
1340
+ i++;
1341
+ } else quoted = false;
1342
+ } else cell2 += c;
1343
+ } else if (c === '"' && cell2 === "") {
1344
+ quoted = true;
1345
+ } else if (c === delimiter) {
1346
+ row.push(cell2);
1347
+ cell2 = "";
1348
+ } else if (c === "\n" || c === "\r") {
1349
+ if (c === "\r" && text[i + 1] === "\n") i++;
1350
+ row.push(cell2);
1351
+ rows.push(row);
1352
+ row = [];
1353
+ cell2 = "";
1354
+ } else cell2 += c;
1355
+ }
1356
+ if (cell2 !== "" || row.length > 0) {
1357
+ row.push(cell2);
1358
+ rows.push(row);
1359
+ }
1360
+ return rows;
1361
+ }
1362
+ function writeCsv(rows, delimiter = ",") {
1363
+ const esc3 = (v) => v.includes(delimiter) || /["\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
1364
+ return rows.map((r) => r.map(esc3).join(delimiter)).join("\r\n") + "\r\n";
1365
+ }
1366
+
1367
+ // src/import/match.ts
1368
+ var STOP = new Set(
1369
+ "a an the and or of to in on for with by at from as is are be been being do does did you your yours we our us it its this that these those any all each which what how when where who whom whose please describe provide explain state confirm detail details give list whether if there their they them can could would should will shall may must also than then such into over per via etc ie eg".split(" ")
1370
+ );
1371
+ var stem = (w) => w.replace(/(?:ing|ed|es|s)$/, (m, offset) => offset >= 3 ? "" : m);
1372
+ function tokens(text) {
1373
+ return text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/[\s-]+/).filter((w) => w.length > 1 && !STOP.has(w)).map(stem);
1374
+ }
1375
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1376
+ var hasPhrase = (text, phrase) => new RegExp(`(?<![\\w])${escape(phrase.toLowerCase())}(?:e?s)?(?![\\w])`).test(text.toLowerCase());
1377
+ var MIN_SCORE = 0.9;
1378
+ var MIN_MARGIN = 0.15;
1379
+ function score(text, q2) {
1380
+ const rowTokens = new Set(tokens(text));
1381
+ const bankTokens = new Set(tokens(q2.text));
1382
+ if (rowTokens.size === 0 || bankTokens.size === 0) return 0;
1383
+ const shared = [...rowTokens].filter((t) => bankTokens.has(t)).length;
1384
+ const cosine = shared / Math.sqrt(rowTokens.size * bankTokens.size);
1385
+ let phrases = 0;
1386
+ for (const k of q2.keywords) {
1387
+ const strong = k.startsWith("*");
1388
+ const phrase = strong ? k.slice(1) : k;
1389
+ if (hasPhrase(text, phrase)) phrases += strong ? 2 : phrase.trim().includes(" ") ? 1 : 0.6;
1390
+ }
1391
+ return Math.min(phrases, 2) * 0.55 + cosine * 1.4;
1392
+ }
1393
+ function bestMatch(text) {
1394
+ const scored = BANK.map((question) => ({ question, score: score(text, question) })).sort((a, b) => b.score - a.score);
1395
+ const [top, next] = scored;
1396
+ if (!top || top.score < MIN_SCORE) return null;
1397
+ if (next && top.score - next.score < MIN_MARGIN) return null;
1398
+ return top;
1399
+ }
1400
+
1401
+ // src/import/fill.ts
1402
+ var ImportError = class extends Error {
1403
+ };
1404
+ var QUESTION_HEADER = /question|requirement|control|query|statement|description/i;
1405
+ var ANSWER_HEADER = /answer|response|reply|supplier|vendor/i;
1406
+ function pickColumns(header, body) {
1407
+ let question = header.findIndex((h) => QUESTION_HEADER.test(h));
1408
+ if (question < 0) {
1409
+ const avg = header.map((_, c) => body.reduce((sum, r) => sum + (r[c]?.length ?? 0), 0) / Math.max(body.length, 1));
1410
+ question = avg.indexOf(Math.max(...avg));
1411
+ }
1412
+ const answer = header.findIndex((h, c) => c !== question && ANSWER_HEADER.test(h));
1413
+ return { question, answer: answer >= 0 ? answer : null };
1414
+ }
1415
+ function sourceSummary(refs, evidence, answers) {
1416
+ return footnoteLines(refs, evidence, answers, { locations: true }).map((l) => l.replace(/^\[\^([^\]]+)\]:\s*/, "$1: ")).join("; ");
1417
+ }
1418
+ function cell(r) {
1419
+ const asks = r.needs.map((n) => n.prompt).join(" ");
1420
+ if (r.status === "answered") return r.answer;
1421
+ if (r.status === "partial") return `${r.answer} NEEDS YOUR INPUT: ${asks}`;
1422
+ return `NEEDS YOUR INPUT: ${asks}`;
1423
+ }
1424
+ function fillQuestionnaire(text, evidence, answers) {
1425
+ const delimiter = detectDelimiter(text);
1426
+ const rows = parseCsv(text, delimiter);
1427
+ if (rows.length < 2) throw new ImportError("The file needs a header row and at least one question.");
1428
+ const header = rows[0];
1429
+ const body = rows.slice(1);
1430
+ const { question: qCol, answer: foundAnswerCol } = pickColumns(header, body);
1431
+ const addedAnswer = foundAnswerCol === null;
1432
+ const aCol = foundAnswerCol ?? header.length;
1433
+ const width = Math.max(header.length, aCol + 1);
1434
+ const sourcesCol = addedAnswer ? aCol + 1 : width;
1435
+ const matchCol = sourcesCol + 1;
1436
+ const out = [];
1437
+ const pad = (r) => [...r, ...Array(Math.max(0, width - r.length)).fill("")];
1438
+ const headRow = pad(header);
1439
+ if (addedAnswer) headRow[aCol] = "Soundings answer";
1440
+ headRow[sourcesCol] = "Soundings sources";
1441
+ headRow[matchCol] = "Soundings match";
1442
+ out.push(headRow);
1443
+ const outcomes = [];
1444
+ body.forEach((raw, i) => {
1445
+ const r = pad(raw);
1446
+ const question = (r[qCol] ?? "").trim();
1447
+ r[sourcesCol] = "";
1448
+ r[matchCol] = "";
1449
+ const rowNumber = i + 2;
1450
+ if (question === "") {
1451
+ out.push(r);
1452
+ return;
1453
+ }
1454
+ if ((r[aCol] ?? "").trim() !== "") {
1455
+ outcomes.push({ row: rowNumber, question, status: "kept" });
1456
+ r[matchCol] = "kept: already answered";
1457
+ out.push(r);
1458
+ return;
1459
+ }
1460
+ const match = bestMatch(question);
1461
+ if (!match) {
1462
+ r[aCol] = "NEEDS YOUR INPUT: no standard question clearly matches this one, so it has not been answered.";
1463
+ r[matchCol] = "no match";
1464
+ outcomes.push({ row: rowNumber, question, status: "unmatched" });
1465
+ out.push(r);
1466
+ return;
1467
+ }
1468
+ const result = answerQuestion(match.question, evidence, answers);
1469
+ r[aCol] = cell(result);
1470
+ r[sourcesCol] = sourceSummary(result.refs, evidence, answers);
1471
+ r[matchCol] = `${match.question.id} (${match.score.toFixed(2)})`;
1472
+ outcomes.push({ row: rowNumber, question, status: result.status, matched: { id: match.question.id, score: match.score } });
1473
+ out.push(r);
1474
+ });
1475
+ return { csv: writeCsv(out, delimiter), outcomes, questionColumn: qCol, answerColumn: aCol, answerColumnAdded: addedAnswer };
1476
+ }
1477
+
1478
+ // src/core/js.ts
1479
+ import { parse } from "@babel/parser";
1480
+ var JS_FILE_RE = /\.(?:[cm]?[jt]sx?)$/;
1481
+ function pluginsFor(file) {
1482
+ if (/\.[cm]?ts$/.test(file)) return ["typescript"];
1483
+ if (/\.tsx$/.test(file)) return ["typescript", "jsx"];
1484
+ return ["jsx"];
1485
+ }
1486
+ function parseJs(file, text) {
1487
+ try {
1488
+ return parse(text, {
1489
+ sourceType: "unambiguous",
1490
+ plugins: pluginsFor(file),
1491
+ errorRecovery: true,
1492
+ allowReturnOutsideFunction: true,
1493
+ allowImportExportEverywhere: true,
1494
+ allowAwaitOutsideFunction: true
1495
+ }).program;
1496
+ } catch {
1497
+ return null;
1498
+ }
1499
+ }
1500
+ function walkAst(node, visit) {
1501
+ const stack = [[node, null]];
1502
+ while (stack.length > 0) {
1503
+ const [n, parent] = stack.pop();
1504
+ if (visit(n, parent) === false) continue;
1505
+ const children = [];
1506
+ for (const key of Object.keys(n)) {
1507
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments" || key === "innerComments") continue;
1508
+ const v = n[key];
1509
+ if (Array.isArray(v)) {
1510
+ for (const c of v) if (isNode(c)) children.push(c);
1511
+ } else if (isNode(v)) children.push(v);
1512
+ }
1513
+ for (let i = children.length - 1; i >= 0; i--) stack.push([children[i], n]);
1514
+ }
1515
+ }
1516
+ function isEnvObject(obj) {
1517
+ if (obj.type !== "MemberExpression" && obj.type !== "OptionalMemberExpression" || obj.computed) return false;
1518
+ if (obj.property.type !== "Identifier" || obj.property.name !== "env") return false;
1519
+ const o = obj.object;
1520
+ return o.type === "Identifier" && o.name === "process" || o.type === "MetaProperty" && o.meta.name === "import";
1521
+ }
1522
+ function isNode(v) {
1523
+ return typeof v === "object" && v !== null && typeof v.type === "string";
1524
+ }
1525
+ function envReads(ast) {
1526
+ const out = [];
1527
+ walkAst(ast, (n) => {
1528
+ if (n.type === "VariableDeclarator" && n.id.type === "ObjectPattern" && n.init && isEnvObject(n.init)) {
1529
+ for (const prop of n.id.properties) {
1530
+ if (prop.type !== "ObjectProperty") continue;
1531
+ const key = prop.key.type === "Identifier" ? prop.key.name : prop.key.type === "StringLiteral" ? prop.key.value : null;
1532
+ if (key) out.push({ name: key, offset: prop.start ?? 0 });
1533
+ }
1534
+ return;
1535
+ }
1536
+ if (n.type !== "MemberExpression" && n.type !== "OptionalMemberExpression") return;
1537
+ if (!isEnvObject(n.object)) return;
1538
+ const p = n.property;
1539
+ const name = !n.computed && p.type === "Identifier" ? p.name : n.computed && p.type === "StringLiteral" ? p.value : n.computed && p.type === "TemplateLiteral" && p.expressions.length === 0 ? p.quasis[0].value.cooked ?? "" : null;
1540
+ if (name) out.push({ name, offset: n.start ?? 0 });
1541
+ });
1542
+ return out;
1543
+ }
1544
+
1545
+ // src/scanner/ast.ts
1546
+ function chainOf(n) {
1547
+ switch (n.type) {
1548
+ case "Identifier":
1549
+ return [n.name];
1550
+ case "ThisExpression":
1551
+ return ["this"];
1552
+ case "AwaitExpression":
1553
+ return chainOf(n.argument);
1554
+ case "MemberExpression":
1555
+ case "OptionalMemberExpression": {
1556
+ const base = chainOf(n.object);
1557
+ if (!base) return null;
1558
+ if (!n.computed && n.property.type === "Identifier") return [...base, n.property.name];
1559
+ if (n.computed && n.property.type === "StringLiteral") return [...base, n.property.value];
1560
+ return null;
1561
+ }
1562
+ case "CallExpression":
1563
+ case "OptionalCallExpression": {
1564
+ const base = chainOf(n.callee);
1565
+ return base ? [...base, "()"] : null;
1566
+ }
1567
+ default:
1568
+ return null;
1569
+ }
1570
+ }
1571
+ var lineOf = (n) => n.loc?.start.line;
1572
+ function calls(ast) {
1573
+ const out = [];
1574
+ walkAst(ast, (n) => {
1575
+ if (n.type === "CallExpression" || n.type === "OptionalCallExpression") {
1576
+ const line = lineOf(n);
1577
+ out.push({ node: n, chain: chainOf(n.callee), ...line !== void 0 ? { line } : {} });
1578
+ }
1579
+ });
1580
+ return out;
1581
+ }
1582
+ var endsWith = (chain, tail) => chain !== null && chain.length >= tail.length && tail.every((t, i) => chain[chain.length - tail.length + i] === t);
1583
+ function boundNames(p) {
1584
+ if (!p) return [];
1585
+ switch (p.type) {
1586
+ case "Identifier":
1587
+ return [p.name];
1588
+ case "AssignmentPattern":
1589
+ return boundNames(p.left);
1590
+ case "RestElement":
1591
+ return boundNames(p.argument);
1592
+ case "ObjectPattern":
1593
+ return p.properties.flatMap((prop) => prop.type === "RestElement" ? boundNames(prop.argument) : boundNames(prop.value));
1594
+ case "ArrayPattern":
1595
+ return p.elements.flatMap((e) => boundNames(e));
1596
+ case "TSParameterProperty":
1597
+ return boundNames(p.parameter);
1598
+ default:
1599
+ return [];
1600
+ }
1601
+ }
1602
+ function paramNames(ast) {
1603
+ const out = /* @__PURE__ */ new Set();
1604
+ walkAst(ast, (n) => {
1605
+ if (n.type === "FunctionDeclaration" || n.type === "FunctionExpression" || n.type === "ArrowFunctionExpression" || n.type === "ObjectMethod" || n.type === "ClassMethod") {
1606
+ for (const p of n.params) for (const name of boundNames(p)) out.add(name);
1607
+ }
1608
+ });
1609
+ return out;
1610
+ }
1611
+ var REQUEST_ROOTS = /* @__PURE__ */ new Set(["req", "request"]);
1612
+ var REQUEST_ANY = /* @__PURE__ */ new Set(["body", "json", "text", "formData", "query", "params", "searchParams"]);
1613
+ var REQUEST_BODY = /* @__PURE__ */ new Set(["body", "json", "text", "formData"]);
1614
+ function isRequestData(n, parts = REQUEST_ANY) {
1615
+ const chain = chainOf(n);
1616
+ return chain !== null && REQUEST_ROOTS.has(chain[0]) && chain.slice(1).some((c) => parts.has(c));
1617
+ }
1618
+ function requestVariables(ast, parts = REQUEST_ANY) {
1619
+ const out = /* @__PURE__ */ new Set();
1620
+ walkAst(ast, (n) => {
1621
+ if (n.type === "VariableDeclarator" && n.init && isRequestData(n.init, parts)) {
1622
+ for (const name of boundNames(n.id)) out.add(name);
1623
+ }
1624
+ });
1625
+ return out;
1626
+ }
1627
+ function dynamicRoots(n) {
1628
+ const out = /* @__PURE__ */ new Set();
1629
+ walkAst(n, (node) => {
1630
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
1631
+ const chain = chainOf(node);
1632
+ if (chain) {
1633
+ out.add(chain[0]);
1634
+ return false;
1635
+ }
1636
+ }
1637
+ if (node.type === "ObjectProperty" && !node.computed) {
1638
+ for (const r of dynamicRoots(node.value)) out.add(r);
1639
+ return false;
1640
+ }
1641
+ if (node.type === "Identifier") out.add(node.name);
1642
+ return void 0;
1643
+ });
1644
+ return out;
1645
+ }
1646
+ function firstStringProperty(ast, name) {
1647
+ let found;
1648
+ walkAst(ast, (n) => {
1649
+ if (found !== void 0) return false;
1650
+ if (n.type === "ObjectProperty" && !n.computed) {
1651
+ const key = n.key.type === "Identifier" ? n.key.name : n.key.type === "StringLiteral" ? n.key.value : null;
1652
+ if (key === name && n.value.type === "StringLiteral") found = n.value.value;
1653
+ }
1654
+ return void 0;
1655
+ });
1656
+ return found;
1657
+ }
1658
+
1659
+ // src/scanner/python/tokenize.ts
1660
+ var NAME_START = /[A-Za-z_]/;
1661
+ var NAME_PART = /[A-Za-z0-9_]/;
1662
+ var STR_PREFIX = /^(?:[rRbBuUfF]{1,2})$/;
1663
+ function tokenizePython(src) {
1664
+ const lines = [];
1665
+ let cur = [];
1666
+ let curIndent = 0;
1667
+ let curLine = 1;
1668
+ let line = 1;
1669
+ let depth = 0;
1670
+ let atStart = true;
1671
+ let i = 0;
1672
+ const n = src.length;
1673
+ const flush = () => {
1674
+ if (cur.length > 0) lines.push({ indent: curIndent, line: curLine, toks: cur });
1675
+ cur = [];
1676
+ atStart = true;
1677
+ };
1678
+ while (i < n) {
1679
+ const c = src[i];
1680
+ if (atStart && depth === 0) {
1681
+ let w = 0;
1682
+ let j = i;
1683
+ while (j < n && (src[j] === " " || src[j] === " ")) {
1684
+ w += src[j] === " " ? 4 : 1;
1685
+ j++;
1686
+ }
1687
+ if (j >= n) break;
1688
+ if (src[j] === "\n" || src[j] === "\r") {
1689
+ i = j + 1;
1690
+ if (src[j] === "\r" && src[i] === "\n") i++;
1691
+ line++;
1692
+ continue;
1693
+ }
1694
+ if (src[j] === "#") {
1695
+ while (j < n && src[j] !== "\n") j++;
1696
+ i = j;
1697
+ continue;
1698
+ }
1699
+ curIndent = w;
1700
+ curLine = line;
1701
+ i = j;
1702
+ atStart = false;
1703
+ continue;
1704
+ }
1705
+ if (c === "\n" || c === "\r") {
1706
+ if (c === "\r" && src[i + 1] === "\n") i++;
1707
+ i++;
1708
+ line++;
1709
+ if (depth === 0) flush();
1710
+ continue;
1711
+ }
1712
+ if (c === " " || c === " " || c === "\f") {
1713
+ i++;
1714
+ continue;
1715
+ }
1716
+ if (c === "#") {
1717
+ while (i < n && src[i] !== "\n") i++;
1718
+ continue;
1719
+ }
1720
+ if (c === "\\" && (src[i + 1] === "\n" || src[i + 1] === "\r")) {
1721
+ i += src[i + 1] === "\r" && src[i + 2] === "\n" ? 3 : 2;
1722
+ line++;
1723
+ continue;
1724
+ }
1725
+ if (NAME_START.test(c)) {
1726
+ let j = i + 1;
1727
+ while (j < n && NAME_PART.test(src[j])) j++;
1728
+ const word = src.slice(i, j);
1729
+ if ((src[j] === '"' || src[j] === "'") && STR_PREFIX.test(word)) {
1730
+ const end = readString(src, j);
1731
+ cur.push({ t: "str", s: src.slice(i, end), line });
1732
+ line += countNewlines(src, i, end);
1733
+ i = end;
1734
+ continue;
1735
+ }
1736
+ cur.push({ t: "name", s: word, line });
1737
+ i = j;
1738
+ continue;
1739
+ }
1740
+ if (c === '"' || c === "'") {
1741
+ const end = readString(src, i);
1742
+ cur.push({ t: "str", s: src.slice(i, end), line });
1743
+ line += countNewlines(src, i, end);
1744
+ i = end;
1745
+ continue;
1746
+ }
1747
+ if (c >= "0" && c <= "9") {
1748
+ let j = i + 1;
1749
+ while (j < n && /[0-9a-zA-Z_.]/.test(src[j])) j++;
1750
+ cur.push({ t: "num", s: src.slice(i, j), line });
1751
+ i = j;
1752
+ continue;
1753
+ }
1754
+ if (c === "(" || c === "[" || c === "{") depth++;
1755
+ else if (c === ")" || c === "]" || c === "}") depth = Math.max(0, depth - 1);
1756
+ cur.push({ t: "op", s: c, line });
1757
+ i++;
1758
+ }
1759
+ flush();
1760
+ return lines;
1761
+ }
1762
+ function readString(src, start) {
1763
+ const q2 = src[start];
1764
+ const triple = src[start + 1] === q2 && src[start + 2] === q2;
1765
+ let i = start + (triple ? 3 : 1);
1766
+ while (i < src.length) {
1767
+ const c = src[i];
1768
+ if (c === "\\") {
1769
+ i += 2;
1770
+ continue;
1771
+ }
1772
+ if (triple) {
1773
+ if (c === q2 && src[i + 1] === q2 && src[i + 2] === q2) return i + 3;
1774
+ } else {
1775
+ if (c === q2) return i + 1;
1776
+ if (c === "\n") return i;
1777
+ }
1778
+ i++;
1779
+ }
1780
+ return src.length;
1781
+ }
1782
+ function countNewlines(src, from, to) {
1783
+ let n = 0;
1784
+ for (let i = from; i < to; i++) if (src[i] === "\n") n++;
1785
+ return n;
1786
+ }
1787
+ var isFString = (s) => /^[rRbBuU]*[fF][rRbBuU]*["']/.test(s);
1788
+ function stringBody(s) {
1789
+ const m = /^[A-Za-z]*("""|'''|"|')([\s\S]*?)\1$/.exec(s);
1790
+ return m ? m[2] : "";
1791
+ }
1792
+ function fstringNames(s) {
1793
+ if (!isFString(s)) return [];
1794
+ const out = [];
1795
+ for (const m of stringBody(s).matchAll(/\{([^{}]+)\}/g)) {
1796
+ const first = /^\s*([A-Za-z_]\w*)/.exec(m[1]);
1797
+ if (first) out.push(first[1]);
1798
+ }
1799
+ return out;
1800
+ }
1801
+
1802
+ // src/scanner/python/parse.ts
1803
+ var isName = (t, s) => t?.t === "name" && (s === void 0 || t.s === s);
1804
+ var isOp = (t, s) => t?.t === "op" && t.s === s;
1805
+ function importsOf(lines) {
1806
+ const out = [];
1807
+ for (const l of lines) {
1808
+ const t = l.toks;
1809
+ if (isName(t[0], "import")) {
1810
+ let i = 1;
1811
+ while (i < t.length) {
1812
+ const parts = [];
1813
+ while (isName(t[i])) {
1814
+ parts.push(t[i].s);
1815
+ i++;
1816
+ if (isOp(t[i], ".")) i++;
1817
+ else break;
1818
+ }
1819
+ if (parts.length) out.push({ module: parts.join("."), names: [], line: l.line });
1820
+ while (i < t.length && !isOp(t[i], ",")) i++;
1821
+ i++;
1822
+ }
1823
+ } else if (isName(t[0], "from")) {
1824
+ let i = 1;
1825
+ const parts = [];
1826
+ let relative3 = false;
1827
+ while (isOp(t[i], ".")) {
1828
+ relative3 = true;
1829
+ i++;
1830
+ }
1831
+ while (isName(t[i]) && !isName(t[i], "import")) {
1832
+ parts.push(t[i].s);
1833
+ i++;
1834
+ if (isOp(t[i], ".")) i++;
1835
+ else break;
1836
+ }
1837
+ if (!isName(t[i], "import")) continue;
1838
+ const names = [];
1839
+ for (i++; i < t.length; i++) {
1840
+ if (isName(t[i]) && !isName(t[i], "as")) {
1841
+ names.push(t[i].s);
1842
+ if (isName(t[i + 1], "as")) i += 2;
1843
+ }
1844
+ }
1845
+ if (!relative3 || parts.length > 0) out.push({ module: parts.join("."), names, line: l.line });
1846
+ }
1847
+ }
1848
+ return out;
1849
+ }
1850
+ function importCandidates(imp) {
1851
+ return [imp.module, ...imp.names.map((n) => `${imp.module}.${n}`)].filter(Boolean);
1852
+ }
1853
+ var withinModule = (module, name) => module === name || module.startsWith(`${name}.`);
1854
+ var SKIP_PARAMS = /* @__PURE__ */ new Set(["self", "cls"]);
1855
+ function functionsOf(lines) {
1856
+ const out = [];
1857
+ let pending = [];
1858
+ for (const l of lines) {
1859
+ const t = l.toks;
1860
+ if (isOp(t[0], "@")) {
1861
+ pending.push(t.slice(1).map((x) => x.s).join(""));
1862
+ continue;
1863
+ }
1864
+ const start = isName(t[0], "async") && isName(t[1], "def") ? 2 : isName(t[0], "def") ? 1 : -1;
1865
+ if (start < 0 || !isName(t[start])) {
1866
+ pending = [];
1867
+ continue;
1868
+ }
1869
+ const name = t[start].s;
1870
+ const params = [];
1871
+ if (isOp(t[start + 1], "(")) {
1872
+ let depth = 0;
1873
+ let expectName = true;
1874
+ for (let i = start + 1; i < t.length; i++) {
1875
+ const x = t[i];
1876
+ if (x.t === "op" && "([{".includes(x.s)) depth++;
1877
+ else if (x.t === "op" && ")]}".includes(x.s)) {
1878
+ depth--;
1879
+ if (depth === 0) break;
1880
+ } else if (depth === 1 && isOp(x, ",")) expectName = true;
1881
+ else if (depth === 1 && expectName && x.t === "name" && !SKIP_PARAMS.has(x.s)) {
1882
+ params.push(x.s);
1883
+ expectName = false;
1884
+ } else if (depth === 1 && x.t === "op" && (x.s === "*" || x.s === "/")) continue;
1885
+ else if (depth === 1 && expectName) expectName = false;
1886
+ }
1887
+ }
1888
+ out.push({ name, params, decorators: pending, line: l.line });
1889
+ pending = [];
1890
+ }
1891
+ return out;
1892
+ }
1893
+ var ROUTE_DECORATOR = /^\w+(?:\.\w+)*\.(?:get|post|put|patch|delete|route|api_route|websocket)\(/;
1894
+ var isRouteHandler = (f) => f.decorators.some((d) => ROUTE_DECORATOR.test(d));
1895
+ var PLUMBING = /* @__PURE__ */ new Set(["request", "req", "response", "db", "session", "current_user", "user", "background_tasks", "background", "settings", "config", "websocket"]);
1896
+ function handlerInputs(funcs) {
1897
+ const out = /* @__PURE__ */ new Set();
1898
+ for (const f of funcs) if (isRouteHandler(f)) {
1899
+ for (const p of f.params) if (!PLUMBING.has(p)) out.add(p);
1900
+ }
1901
+ return out;
1902
+ }
1903
+ function callsOf(lines) {
1904
+ const out = [];
1905
+ for (const l of lines) {
1906
+ const t = l.toks;
1907
+ for (let i = 0; i < t.length - 1; i++) {
1908
+ if (t[i].t !== "name" || !isOp(t[i + 1], "(")) continue;
1909
+ if (i > 0 && isName(t[i - 1]) && (t[i - 1].s === "def" || t[i - 1].s === "class")) continue;
1910
+ const chain = [t[i].s];
1911
+ let j = i - 1;
1912
+ while (j >= 1 && isOp(t[j], ".") && isName(t[j - 1])) {
1913
+ chain.unshift(t[j - 1].s);
1914
+ j -= 2;
1915
+ }
1916
+ let depth = 0;
1917
+ let end = t.length;
1918
+ for (let k = i + 1; k < t.length; k++) {
1919
+ if (t[k].t === "op" && "([{".includes(t[k].s)) depth++;
1920
+ else if (t[k].t === "op" && ")]}".includes(t[k].s)) {
1921
+ depth--;
1922
+ if (depth === 0) {
1923
+ end = k;
1924
+ break;
1925
+ }
1926
+ }
1927
+ }
1928
+ out.push({ chain, args: t.slice(i + 2, end), line: t[i].line });
1929
+ }
1930
+ }
1931
+ return out;
1932
+ }
1933
+ var callEndsWith = (chain, tail) => chain.length >= tail.length && tail.every((x, i) => chain[chain.length - tail.length + i] === x);
1934
+ var REQUEST_ROOTS2 = /* @__PURE__ */ new Set(["request", "req"]);
1935
+ var BODY_PARTS = /* @__PURE__ */ new Set(["json", "body", "get_json", "data", "form", "POST", "get_data", "stream", "text"]);
1936
+ function dottedAt(t, i) {
1937
+ const chain = [];
1938
+ while (isName(t[i])) {
1939
+ chain.push(t[i].s);
1940
+ if (isOp(t[i + 1], ".") && isName(t[i + 2])) i += 2;
1941
+ else break;
1942
+ }
1943
+ return chain;
1944
+ }
1945
+ var isRequestBodyChain = (c) => c.length >= 2 && REQUEST_ROOTS2.has(c[0]) && c.slice(1).some((p) => BODY_PARTS.has(p));
1946
+ function readsRequestBody(toks) {
1947
+ for (let i = 0; i < toks.length; i++) if (isName(toks[i]) && isRequestBodyChain(dottedAt(toks, i))) return true;
1948
+ return false;
1949
+ }
1950
+ function requestVariables2(lines) {
1951
+ const out = /* @__PURE__ */ new Set();
1952
+ for (const l of lines) {
1953
+ const t = l.toks;
1954
+ if (isName(t[0]) && isOp(t[1], "=") && !isOp(t[2], "=") && readsRequestBody(t.slice(2))) out.add(t[0].s);
1955
+ }
1956
+ return out;
1957
+ }
1958
+ var SECRET_NAME = /KEY|SECRET|TOKEN|PASSWORD|PASSPHRASE|DSN|DATABASE_URL|CONNECTION_STRING/i;
1959
+ var isSecretName = (n) => SECRET_NAME.test(n);
1960
+ function envReadsPy(lines) {
1961
+ const out = [];
1962
+ for (const l of lines) {
1963
+ const t = l.toks;
1964
+ for (let i = 0; i < t.length; i++) {
1965
+ const chain = isName(t[i]) ? dottedAt(t, i) : [];
1966
+ if (chain.length === 0) continue;
1967
+ const tail = chain.join(".");
1968
+ let at = -1;
1969
+ if (/(?:^|\.)(?:os\.)?environ$/.test(tail) && isOp(t[i + chain.length * 2 - 1], "[")) at = i + chain.length * 2;
1970
+ else if (/(?:^|\.)(?:environ\.get|getenv)$/.test(tail) && isOp(t[i + chain.length * 2 - 1], "(")) at = i + chain.length * 2;
1971
+ if (at >= 0 && t[at]?.t === "str") out.push({ name: stringBody(t[at].s), line: l.line });
1972
+ }
1973
+ }
1974
+ return out;
1975
+ }
1976
+ function settingsFields(lines) {
1977
+ const out = [];
1978
+ for (let i = 0; i < lines.length; i++) {
1979
+ const l = lines[i];
1980
+ if (!isName(l.toks[0], "class") || !l.toks.some((t) => isName(t, "BaseSettings"))) continue;
1981
+ for (let j = i + 1; j < lines.length && lines[j].indent > l.indent; j++) {
1982
+ const f = lines[j];
1983
+ if (isName(f.toks[0]) && isOp(f.toks[1], ":")) out.push({ name: f.toks[0].s.toUpperCase(), line: f.line });
1984
+ }
1985
+ }
1986
+ return out;
1987
+ }
1988
+ var KEYWORDS = /* @__PURE__ */ new Set(["True", "False", "None", "and", "or", "not", "if", "else", "for", "in", "is", "lambda", "await", "async", "yield", "from", "import", "as"]);
1989
+ function dependsOn(toks) {
1990
+ const out = /* @__PURE__ */ new Set();
1991
+ for (let i = 0; i < toks.length; i++) {
1992
+ const x = toks[i];
1993
+ if (x.t === "str") {
1994
+ for (const n of fstringNames(x.s)) out.add(n);
1995
+ } else if (x.t === "name" && !KEYWORDS.has(x.s) && !isOp(toks[i - 1], ".") && !isOp(toks[i + 1], "(") && !isOp(toks[i + 1], "=")) {
1996
+ out.add(x.s);
1997
+ }
1998
+ }
1999
+ return out;
2000
+ }
2001
+ function valuesOf(args, keys) {
2002
+ const out = [];
2003
+ for (let i = 0; i < args.length; i++) {
2004
+ const x = args[i];
2005
+ const isKwarg = x.t === "name" && keys.has(x.s) && isOp(args[i + 1], "=") && !isOp(args[i + 2], "=");
2006
+ const isDictKey = x.t === "str" && keys.has(stringBody(x.s)) && isOp(args[i + 1], ":");
2007
+ if (!isKwarg && !isDictKey) continue;
2008
+ const value = [];
2009
+ let depth = 0;
2010
+ for (let k = i + 2; k < args.length; k++) {
2011
+ const y = args[k];
2012
+ if (y.t === "op" && "([{".includes(y.s)) depth++;
2013
+ else if (y.t === "op" && ")]}".includes(y.s)) {
2014
+ if (depth === 0) break;
2015
+ depth--;
2016
+ } else if (depth === 0 && isOp(y, ",")) break;
2017
+ value.push(y);
2018
+ }
2019
+ out.push(value);
2020
+ }
2021
+ return out;
2022
+ }
2023
+ var AI_CALL_TAILS = [
2024
+ ["chat", "completions", "create"],
2025
+ ["chat", "completions", "parse"],
2026
+ ["responses", "create"],
2027
+ ["completions", "create"],
2028
+ ["embeddings", "create"],
2029
+ ["messages", "create"],
2030
+ ["messages", "stream"],
2031
+ ["generate_content"],
2032
+ ["generate_content_async"],
2033
+ ["generate_text"]
2034
+ ];
2035
+ var CONTENT_KEYS = /* @__PURE__ */ new Set(["content", "prompt", "input", "contents", "text", "system", "messages", "query"]);
2036
+ function aiPayload(lines, calls2, funcs) {
2037
+ const params = new Set(funcs.flatMap((f) => f.params));
2038
+ for (const n of handlerInputs(funcs)) params.add(n);
2039
+ const reqVars = requestVariables2(lines);
2040
+ let best = null;
2041
+ for (const c of calls2) {
2042
+ if (!AI_CALL_TAILS.some((t) => callEndsWith(c.chain, t))) continue;
2043
+ const roots = /* @__PURE__ */ new Set();
2044
+ for (const v of valuesOf(c.args, CONTENT_KEYS)) {
2045
+ if (v.length === 1 && v[0].t === "str" && !isFString(v[0].s)) continue;
2046
+ for (const n of dependsOn(v)) roots.add(n);
2047
+ }
2048
+ if (roots.size === 0) continue;
2049
+ const traced = [...roots].some((r) => params.has(r) || reqVars.has(r) || REQUEST_ROOTS2.has(r));
2050
+ const candidate = { confidence: traced ? "high" : "medium", line: c.line };
2051
+ if (!best || candidate.confidence === "high" && best.confidence !== "high") best = candidate;
2052
+ }
2053
+ return best;
2054
+ }
2055
+ var LOG_LEVELS = /* @__PURE__ */ new Set(["debug", "info", "warning", "warn", "error", "exception", "critical", "log"]);
2056
+ function isLogCall(c) {
2057
+ if (c.chain.length === 1) return c.chain[0] === "print";
2058
+ const level = c.chain[c.chain.length - 1];
2059
+ const root = c.chain[0];
2060
+ return LOG_LEVELS.has(level) && (root === "logging" || /^(?:log|logger|\w*_logger|\w*_log|self)$/.test(root) || root.toLowerCase().includes("log"));
2061
+ }
2062
+ function loggedRequestBody(lines, calls2, funcs) {
2063
+ const inputs = handlerInputs(funcs);
2064
+ const reqVars = requestVariables2(lines);
2065
+ for (const c of calls2) {
2066
+ if (!isLogCall(c)) continue;
2067
+ if (readsRequestBody(c.args)) return { line: c.line };
2068
+ const used = dependsOn(c.args);
2069
+ if ([...used].some((n) => reqVars.has(n) || inputs.has(n))) return { line: c.line };
2070
+ }
2071
+ return null;
2072
+ }
2073
+ function firstStringKwarg(lines, name) {
2074
+ for (const l of lines) {
2075
+ const t = l.toks;
2076
+ for (let i = 0; i < t.length - 2; i++) {
2077
+ if (isName(t[i], name) && isOp(t[i + 1], "=") && !isOp(t[i + 2], "=") && t[i + 2].t === "str" && !isFString(t[i + 2].s)) return stringBody(t[i + 2].s);
2078
+ }
2079
+ }
2080
+ return void 0;
2081
+ }
2082
+
2083
+ // src/scanner/coverage.ts
2084
+ var UNSUPPORTED = {
2085
+ go: "Go",
2086
+ java: "Java",
2087
+ kt: "Kotlin",
2088
+ rb: "Ruby",
2089
+ php: "PHP",
2090
+ cs: "C#",
2091
+ rs: "Rust",
2092
+ swift: "Swift",
2093
+ scala: "Scala",
2094
+ ex: "Elixir",
2095
+ exs: "Elixir",
2096
+ dart: "Dart"
2097
+ };
2098
+ var SIGNIFICANT_UNSUPPORTED_FILES = 3;
2099
+ function unsupportedCode(files) {
2100
+ const counts = /* @__PURE__ */ new Map();
2101
+ for (const file of files) {
2102
+ if (!isProductFile(file)) continue;
2103
+ const language = UNSUPPORTED[file.slice(file.lastIndexOf(".") + 1).toLowerCase()];
2104
+ if (language && file.includes(".")) counts.set(language, (counts.get(language) ?? 0) + 1);
2105
+ }
2106
+ return [...counts].map(([language, n]) => ({ language, files: n })).sort((a, b) => b.files - a.files || a.language.localeCompare(b.language));
2107
+ }
2108
+ var totalUnsupported = (u) => u.reduce((n, x) => n + x.files, 0);
2109
+ var isSignificant = (u) => totalUnsupported(u) >= SIGNIFICANT_UNSUPPORTED_FILES;
2110
+ function describeUnsupported(u) {
2111
+ const parts = u.map((x) => `${x.files} ${x.language} file${x.files === 1 ? "" : "s"}`);
2112
+ return parts.length <= 1 ? parts.join("") : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
2113
+ }
2114
+
2115
+ // src/scanner/context.ts
2116
+ var NON_PRODUCT = /(^|\/)(tests?|__tests__|specs?|e2e|fixtures|__mocks__)\/|\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)(test_[^/]*|[^/]*_test|conftest)\.py$/;
2117
+ var isProductFile = (file) => !NON_PRODUCT.test(file);
2118
+ function importsOf2(ast) {
2119
+ const out = [];
2120
+ const add = (source, node) => {
2121
+ const line = node.loc?.start.line;
2122
+ out.push({ source, ...line !== void 0 ? { line } : {} });
2123
+ };
2124
+ walkAst(ast, (n) => {
2125
+ if ((n.type === "ImportDeclaration" || n.type === "ExportNamedDeclaration" || n.type === "ExportAllDeclaration") && n.source) {
2126
+ add(n.source.value, n);
2127
+ } else if (n.type === "CallExpression") {
2128
+ const [arg] = n.arguments;
2129
+ const isRequire = n.callee.type === "Identifier" && n.callee.name === "require";
2130
+ const isDynamicImport = n.callee.type === "Import";
2131
+ if ((isRequire || isDynamicImport) && arg?.type === "StringLiteral") add(arg.value, n);
2132
+ }
2133
+ });
2134
+ return out;
2135
+ }
2136
+ function isClientFile(ast) {
2137
+ return ast.type === "Program" && ast.directives.some((d) => d.value.value === "use client");
2138
+ }
2139
+ function buildContext(project) {
2140
+ const deps = /* @__PURE__ */ new Set();
2141
+ for (const file of project.files) {
2142
+ if (file !== "package.json" && !file.endsWith("/package.json")) continue;
2143
+ const pkg = project.json(file);
2144
+ for (const key of ["dependencies", "devDependencies", "peerDependencies"]) {
2145
+ for (const name of Object.keys(pkg?.[key] ?? {})) deps.add(name);
2146
+ }
2147
+ }
2148
+ const js = [];
2149
+ for (const file of project.files) {
2150
+ if (!JS_FILE_RE.test(file) || !isProductFile(file)) continue;
2151
+ const text = project.read(file);
2152
+ if (text === null) continue;
2153
+ const ast = parseJs(file, text);
2154
+ if (ast) js.push({ file, ast, imports: importsOf2(ast), isClient: isClientFile(ast) });
2155
+ }
2156
+ const py = [];
2157
+ for (const file of project.files) {
2158
+ if (!file.endsWith(".py") || !isProductFile(file)) continue;
2159
+ const text = project.read(file);
2160
+ if (text === null) continue;
2161
+ const lines = tokenizePython(text);
2162
+ py.push({ file, lines, imports: importsOf(lines), calls: callsOf(lines), funcs: functionsOf(lines) });
2163
+ }
2164
+ return {
2165
+ project,
2166
+ deps,
2167
+ js,
2168
+ py,
2169
+ hasPyImport: (...modules) => py.some((f) => importsPy(f, ...modules)),
2170
+ hasDep: (...names) => names.some((n) => deps.has(n)),
2171
+ hasDepPrefix: (prefix) => [...deps].some((d) => d.startsWith(prefix)),
2172
+ hasUnanalysedCode: isSignificant(unsupportedCode(project.files))
2173
+ };
2174
+ }
2175
+ var importsModule = (f, source) => f.imports.find((i) => i.source === source || source.endsWith("/") && i.source.startsWith(source) || i.source.startsWith(`${source}/`));
2176
+ var importsPy = (f, ...modules) => f.imports.find((imp) => importCandidates(imp).some((c) => modules.some((m) => withinModule(c, m))));
2177
+
2178
+ // src/scanner/detectors/ai.ts
2179
+ var AI_PROVIDERS = [
2180
+ { id: "ai-provider/openai-sdk", subject: "OpenAI", packages: ["openai", "@ai-sdk/openai"], pyModules: ["openai", "langchain_openai"] },
2181
+ { id: "ai-provider/anthropic-sdk", subject: "Anthropic", packages: ["@anthropic-ai/sdk", "@ai-sdk/anthropic"], pyModules: ["anthropic", "langchain_anthropic"] },
2182
+ { id: "ai-provider/google-sdk", subject: "Google AI", packages: ["@google/generative-ai", "@google/genai", "@ai-sdk/google"], pyModules: ["google.generativeai", "google.genai", "langchain_google_genai", "vertexai"] },
2183
+ { id: "ai-provider/vercel-ai-sdk", subject: "Vercel AI SDK", packages: ["ai"], pyModules: [] }
2184
+ ];
2185
+ function providersIn(f) {
2186
+ const used = AI_PROVIDERS.filter((p) => p.packages.some((pkg) => importsModule(f, pkg)));
2187
+ const named = used.filter((p) => p.subject !== "Vercel AI SDK");
2188
+ return named.length > 0 ? named : used;
2189
+ }
2190
+ function runsOn(f) {
2191
+ if (f.isClient) return "browser";
2192
+ if (/(^|\/)(api|server|routes?|actions)(\/|\.)|route\.[cm]?[jt]s$/.test(f.file) || !/\.[jt]sx$/.test(f.file)) return "server";
2193
+ return "unclear";
2194
+ }
2195
+ function aiProviderDetector(spec) {
2196
+ return {
2197
+ id: spec.id,
2198
+ skipReason: (ctx) => ctx.hasDep(...spec.packages) || spec.pyModules.length > 0 && ctx.hasPyImport(...spec.pyModules) ? null : `no ${spec.subject} package in dependencies`,
2199
+ run: (ctx) => [
2200
+ ...ctx.py.filter((f) => spec.pyModules.length > 0 && importsPy(f, ...spec.pyModules)).map((f) => {
2201
+ const imp = importsPy(f, ...spec.pyModules);
2202
+ const model = firstStringKwarg(f.lines, "model");
2203
+ return {
2204
+ kind: "ai_provider",
2205
+ subject: spec.subject,
2206
+ claim: `The app uses the ${spec.subject} SDK from server code.`,
2207
+ attributes: { sdk: imp?.module ?? spec.pyModules[0], runsOn: "server", ...model ? { model } : {} },
2208
+ confidence: "high",
2209
+ detector: spec.id,
2210
+ key: f.file,
2211
+ locations: [{ file: f.file, ...imp?.line ? { line: imp.line } : {} }]
2212
+ };
2213
+ }),
2214
+ ...ctx.js.filter((f) => providersIn(f).includes(spec)).map((f) => {
2215
+ const imp = spec.packages.map((p) => importsModule(f, p)).find(Boolean);
2216
+ const model = firstStringProperty(f.ast, "model");
2217
+ const where2 = runsOn(f);
2218
+ return {
2219
+ kind: "ai_provider",
2220
+ subject: spec.subject,
2221
+ claim: where2 === "browser" ? `The browser code imports the ${spec.subject} SDK.` : `The app uses the ${spec.subject} SDK${where2 === "server" ? " from server code" : ""}.`,
2222
+ attributes: { sdk: imp?.source ?? spec.packages[0], runsOn: where2, ...model ? { model } : {} },
2223
+ confidence: "high",
2224
+ detector: spec.id,
2225
+ key: f.file,
2226
+ locations: [{ file: f.file, ...imp?.line ? { line: imp.line } : {} }]
2227
+ };
2228
+ })
2229
+ ]
2230
+ };
2231
+ }
2232
+ var AI_CALL_TAILS2 = [
2233
+ ["chat", "completions", "create"],
2234
+ ["chat", "completions", "stream"],
2235
+ ["responses", "create"],
2236
+ ["completions", "create"],
2237
+ ["embeddings", "create"],
2238
+ ["messages", "create"],
2239
+ ["messages", "stream"],
2240
+ ["generateContent"],
2241
+ ["generateContentStream"]
2242
+ ];
2243
+ var AI_CALL_FUNCTIONS = /* @__PURE__ */ new Set(["generateText", "streamText", "generateObject", "streamObject", "embed", "embedMany"]);
2244
+ var CONTENT_KEYS2 = /* @__PURE__ */ new Set(["content", "prompt", "input", "contents", "text", "system", "messages"]);
2245
+ function payloadIn(f) {
2246
+ const requestVars = requestVariables(f.ast);
2247
+ const params = paramNames(f.ast);
2248
+ let best = null;
2249
+ for (const call of calls(f.ast)) {
2250
+ const isAiCall = call.chain !== null && AI_CALL_TAILS2.some((t) => endsWith(call.chain, t)) || call.chain !== null && call.chain.length === 1 && AI_CALL_FUNCTIONS.has(call.chain[0]);
2251
+ if (!isAiCall || call.node.type !== "CallExpression") continue;
2252
+ const roots = /* @__PURE__ */ new Set();
2253
+ for (const arg of call.node.arguments) {
2254
+ walkAst(arg, (n) => {
2255
+ if (n.type === "ObjectProperty" && !n.computed) {
2256
+ const key = n.key.type === "Identifier" ? n.key.name : n.key.type === "StringLiteral" ? n.key.value : null;
2257
+ if (key && CONTENT_KEYS2.has(key) && n.value.type !== "StringLiteral") for (const r of dynamicRoots(n.value)) roots.add(r);
2258
+ }
2259
+ return void 0;
2260
+ });
2261
+ }
2262
+ const traced = [...roots].some((r) => requestVars.has(r) || params.has(r) || r === "req" || r === "request");
2263
+ if (roots.size === 0) continue;
2264
+ const candidate = { confidence: traced ? "high" : "medium", ...call.line ? { line: call.line } : {} };
2265
+ if (!best || candidate.confidence === "high" && best.confidence !== "high") best = candidate;
2266
+ }
2267
+ return best;
2268
+ }
2269
+ var dataFlowDetector = {
2270
+ id: "data-flow/ai-request-payload",
2271
+ skipReason: (ctx) => AI_PROVIDERS.some((p) => ctx.hasDep(...p.packages) || p.pyModules.length > 0 && ctx.hasPyImport(...p.pyModules)) ? null : "no AI SDK in dependencies",
2272
+ run: (ctx) => {
2273
+ const facts = [];
2274
+ for (const f of ctx.py) {
2275
+ const providers = AI_PROVIDERS.filter((p) => p.pyModules.length > 0 && importsPy(f, ...p.pyModules));
2276
+ if (providers.length === 0) continue;
2277
+ const payload = aiPayload(f.lines, f.calls, f.funcs);
2278
+ if (!payload) continue;
2279
+ for (const p of providers) {
2280
+ facts.push({
2281
+ kind: "data_flow",
2282
+ subject: p.subject,
2283
+ claim: payload.confidence === "high" ? `Text taken from a request or function input is included in prompts sent to ${p.subject}.` : `Variable content is included in prompts sent to ${p.subject}; its source isn't clear from the code.`,
2284
+ attributes: { dataCategories: ["user-supplied content"], destination: p.subject, direction: "outbound" },
2285
+ confidence: payload.confidence,
2286
+ detector: "data-flow/ai-request-payload",
2287
+ key: f.file,
2288
+ locations: [{ file: f.file, line: payload.line }]
2289
+ });
2290
+ }
2291
+ }
2292
+ for (const f of ctx.js) {
2293
+ const providers = providersIn(f);
2294
+ if (providers.length === 0) continue;
2295
+ const payload = payloadIn(f);
2296
+ if (!payload) continue;
2297
+ for (const p of providers) {
2298
+ facts.push({
2299
+ kind: "data_flow",
2300
+ subject: p.subject,
2301
+ claim: payload.confidence === "high" ? `Text taken from a request or function input is included in prompts sent to ${p.subject}.` : `Variable content is included in prompts sent to ${p.subject}; its source isn't clear from the code.`,
2302
+ attributes: { dataCategories: ["user-supplied content"], destination: p.subject, direction: "outbound" },
2303
+ confidence: payload.confidence,
2304
+ detector: "data-flow/ai-request-payload",
2305
+ key: f.file,
2306
+ locations: [{ file: f.file, ...payload.line ? { line: payload.line } : {} }]
2307
+ });
2308
+ }
2309
+ }
2310
+ return facts;
2311
+ }
2312
+ };
2313
+ var aiDetectors = [...AI_PROVIDERS.map(aiProviderDetector), dataFlowDetector];
2314
+
2315
+ // src/scanner/detectors/auth.ts
2316
+ var SUPABASE_METHODS = {
2317
+ signInWithPassword: "email-password",
2318
+ signUp: "email-password",
2319
+ signInWithOtp: "one-time-code",
2320
+ signInWithOAuth: "oauth",
2321
+ signInWithIdToken: "oauth",
2322
+ signInWithSSO: "sso"
2323
+ };
2324
+ var supabaseAuth = {
2325
+ id: "auth/supabase-auth",
2326
+ skipReason: (ctx) => ctx.hasDepPrefix("@supabase/") ? null : "no Supabase package in dependencies",
2327
+ run: (ctx) => {
2328
+ const facts = [];
2329
+ for (const f of ctx.js) {
2330
+ const methods = /* @__PURE__ */ new Set();
2331
+ let line;
2332
+ for (const c of calls(f.ast)) {
2333
+ const i = c.chain?.indexOf("auth") ?? -1;
2334
+ const m = c.chain && i >= 0 ? c.chain[i + 1] : void 0;
2335
+ if (m && SUPABASE_METHODS[m]) {
2336
+ methods.add(SUPABASE_METHODS[m]);
2337
+ line ??= c.line;
2338
+ }
2339
+ }
2340
+ if (methods.size === 0) continue;
2341
+ facts.push({
2342
+ kind: "auth",
2343
+ subject: "Supabase Auth",
2344
+ claim: `Users sign in through Supabase Auth (${[...methods].sort().join(", ")}).`,
2345
+ attributes: { provider: "Supabase Auth", methods: [...methods] },
2346
+ confidence: "high",
2347
+ detector: "auth/supabase-auth",
2348
+ key: f.file,
2349
+ locations: [{ file: f.file, ...line ? { line } : {} }]
2350
+ });
2351
+ }
2352
+ return facts;
2353
+ }
2354
+ };
2355
+ var AUTH_PACKAGES = [
2356
+ { slug: "jwt", subject: "JSON Web Tokens", packages: ["jsonwebtoken", "jose"], pyModules: ["jwt", "jose"], claim: "Requests are authenticated with JSON Web Tokens." },
2357
+ { slug: "authjs", subject: "Auth.js", packages: ["next-auth", "@auth/core"], claim: "Sign-in is handled by Auth.js." },
2358
+ { slug: "clerk", subject: "Clerk", packages: ["@clerk/nextjs", "@clerk/clerk-react", "@clerk/express", "@clerk/backend"], pyModules: ["clerk_backend_api"], claim: "Sign-in is handled by Clerk." },
2359
+ { slug: "auth0", subject: "Auth0", packages: ["@auth0/nextjs-auth0", "@auth0/auth0-react", "auth0"], pyModules: ["auth0"], claim: "Sign-in is handled by Auth0." },
2360
+ { slug: "firebase-auth", subject: "Firebase Auth", packages: ["firebase/auth", "firebase-admin/auth"], pyModules: ["firebase_admin.auth"], claim: "Sign-in is handled by Firebase Auth." },
2361
+ { slug: "entra", subject: "Microsoft Entra ID", packages: ["@azure/msal-browser", "@azure/msal-react", "@azure/msal-node"], pyModules: ["msal"], claim: "Sign-in uses Microsoft Entra ID (MSAL)." },
2362
+ { slug: "fastapi-security", subject: "OAuth2 bearer tokens (FastAPI)", packages: [], pyModules: ["fastapi.security"], claim: "Requests are authenticated with bearer tokens through FastAPI's security helpers." },
2363
+ { slug: "django-auth", subject: "Django authentication", packages: [], pyModules: ["django.contrib.auth"], claim: "Sign-in is handled by Django's authentication system." },
2364
+ { slug: "flask-login", subject: "Flask-Login", packages: [], pyModules: ["flask_login"], claim: "Sign-in is handled with Flask-Login." },
2365
+ { slug: "authlib", subject: "Authlib", packages: [], pyModules: ["authlib"], claim: "Sign-in or token handling uses Authlib." },
2366
+ { slug: "passport", subject: "Passport", packages: ["passport"], claim: "Sign-in is handled with Passport strategies." }
2367
+ ];
2368
+ function authDetector(spec) {
2369
+ const id = `auth/${spec.slug}`;
2370
+ const fact = (file, line) => ({
2371
+ kind: "auth",
2372
+ subject: spec.subject,
2373
+ claim: spec.claim,
2374
+ attributes: { provider: spec.subject },
2375
+ confidence: "high",
2376
+ detector: id,
2377
+ key: file,
2378
+ locations: [{ file, ...line ? { line } : {} }]
2379
+ });
2380
+ return {
2381
+ id,
2382
+ skipReason: (ctx) => {
2383
+ const roots = spec.packages.map((p) => p.startsWith("@") ? p : p.split("/")[0]);
2384
+ if (roots.length > 0 && ctx.hasDep(...roots)) return null;
2385
+ if (spec.pyModules && ctx.hasPyImport(...spec.pyModules)) return null;
2386
+ return `no ${spec.subject} package in dependencies`;
2387
+ },
2388
+ run: (ctx) => [
2389
+ ...ctx.py.flatMap((f) => {
2390
+ const imp = spec.pyModules ? importsPy(f, ...spec.pyModules) : void 0;
2391
+ return imp ? [fact(f.file, imp.line)] : [];
2392
+ }),
2393
+ ...ctx.js.flatMap((f) => {
2394
+ const imp = spec.packages.map((p) => importsModule(f, p)).find(Boolean);
2395
+ return imp ? [fact(f.file, imp.line)] : [];
2396
+ })
2397
+ ]
2398
+ };
2399
+ }
2400
+ var authDetectors = [supabaseAuth, ...AUTH_PACKAGES.map(authDetector)];
2401
+
2402
+ // src/scanner/detectors/services.ts
2403
+ var SERVICES = [
2404
+ {
2405
+ slug: "stripe",
2406
+ subject: "Stripe",
2407
+ purpose: "payments",
2408
+ packages: ["stripe", "@stripe/stripe-js", "@stripe/react-stripe-js"],
2409
+ pyModules: ["stripe"],
2410
+ pyIntegrations: [
2411
+ { contains: "checkout.Session", value: "checkout" },
2412
+ { contains: "PaymentIntent", value: "payment-intents" }
2413
+ ],
2414
+ integrations: [
2415
+ { contains: "checkout.sessions", value: "checkout" },
2416
+ { contains: "paymentIntents", value: "payment-intents" }
2417
+ ]
2418
+ },
2419
+ { slug: "vercel-analytics", subject: "Vercel Analytics", purpose: "analytics", packages: ["@vercel/analytics", "@vercel/speed-insights"] },
2420
+ { slug: "plausible-analytics", subject: "Plausible Analytics", purpose: "analytics", packages: ["next-plausible", "plausible-tracker"], scriptHosts: ["plausible.io"] },
2421
+ {
2422
+ slug: "google-analytics",
2423
+ subject: "Google Analytics",
2424
+ purpose: "analytics",
2425
+ packages: ["@next/third-parties", "react-ga4", "ga-gtag"],
2426
+ scriptHosts: ["googletagmanager.com", "google-analytics.com"]
2427
+ },
2428
+ { slug: "hotjar", subject: "Hotjar", purpose: "analytics", packages: ["@hotjar/browser", "react-hotjar"], scriptHosts: ["static.hotjar.com"] },
2429
+ { slug: "posthog", subject: "PostHog", purpose: "analytics", packages: ["posthog-js", "posthog-node"], pyModules: ["posthog"] },
2430
+ { slug: "mixpanel", subject: "Mixpanel", purpose: "analytics", packages: ["mixpanel", "mixpanel-browser"], pyModules: ["mixpanel"] },
2431
+ { slug: "segment", subject: "Segment", purpose: "analytics", packages: ["@segment/analytics-next", "@segment/analytics-node", "analytics-node"], pyModules: ["segment.analytics"] },
2432
+ { slug: "sentry", subject: "Sentry", purpose: "error tracking", packages: ["@sentry/nextjs", "@sentry/node", "@sentry/react", "@sentry/browser"], pyModules: ["sentry_sdk"] },
2433
+ { slug: "resend", subject: "Resend", purpose: "email", packages: ["resend"], pyModules: ["resend"] },
2434
+ { slug: "sendgrid", subject: "SendGrid", purpose: "email", packages: ["@sendgrid/mail"], pyModules: ["sendgrid"] },
2435
+ { slug: "postmark", subject: "Postmark", purpose: "email", packages: ["postmark"], pyModules: ["postmarker"] },
2436
+ { slug: "twilio", subject: "Twilio", purpose: "SMS and voice", packages: ["twilio"], pyModules: ["twilio"] }
2437
+ ];
2438
+ var HTML_FILE = /\.(?:html?|ejs|hbs|njk|liquid)$/i;
2439
+ var SCRIPT_SRC = /<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi;
2440
+ function serviceDetector(spec) {
2441
+ const id = `third-party/${spec.slug}`;
2442
+ return {
2443
+ id,
2444
+ skipReason: (ctx) => {
2445
+ if (ctx.hasDep(...spec.packages)) return null;
2446
+ if (spec.pyModules && ctx.hasPyImport(...spec.pyModules)) return null;
2447
+ if (spec.scriptHosts) return null;
2448
+ return `no ${spec.subject} package in dependencies`;
2449
+ },
2450
+ run: (ctx) => {
2451
+ const facts = /* @__PURE__ */ new Map();
2452
+ const add = (file, line, extra = {}) => {
2453
+ if (facts.has(file)) return;
2454
+ facts.set(file, {
2455
+ kind: "third_party_service",
2456
+ subject: spec.subject,
2457
+ claim: `${spec.subject} is used for ${spec.purpose}.`,
2458
+ attributes: { purpose: spec.purpose, ...extra },
2459
+ confidence: "high",
2460
+ detector: id,
2461
+ key: file,
2462
+ locations: [{ file, ...line ? { line } : {} }]
2463
+ });
2464
+ };
2465
+ for (const f of ctx.py) {
2466
+ const imp = spec.pyModules ? importsPy(f, ...spec.pyModules) : void 0;
2467
+ if (!imp) continue;
2468
+ const text = ctx.project.read(f.file) ?? "";
2469
+ const integration = spec.pyIntegrations?.find((i) => text.includes(i.contains));
2470
+ add(f.file, imp.line, integration ? { integration: integration.value } : {});
2471
+ }
2472
+ for (const f of ctx.js) {
2473
+ const imp = spec.packages.map((p) => importsModule(f, p)).find(Boolean);
2474
+ if (imp) {
2475
+ const text = ctx.project.read(f.file) ?? "";
2476
+ const integration = spec.integrations?.find((i) => text.includes(i.contains));
2477
+ add(f.file, imp.line, integration ? { integration: integration.value } : {});
2478
+ }
2479
+ if (spec.scriptHosts) {
2480
+ walkAst(f.ast, (n) => {
2481
+ if (n.type === "StringLiteral" && /^https?:\/\//.test(n.value) && spec.scriptHosts.some((h) => new URL(n.value).hostname.endsWith(h))) {
2482
+ add(f.file, n.loc?.start.line);
2483
+ }
2484
+ return void 0;
2485
+ });
2486
+ }
2487
+ }
2488
+ if (spec.scriptHosts) {
2489
+ for (const file of ctx.project.files) {
2490
+ if (!HTML_FILE.test(file)) continue;
2491
+ const text = ctx.project.read(file);
2492
+ if (text === null) continue;
2493
+ for (const m of text.matchAll(SCRIPT_SRC)) {
2494
+ let host = "";
2495
+ try {
2496
+ host = new URL(m[1].startsWith("//") ? `https:${m[1]}` : m[1]).hostname;
2497
+ } catch {
2498
+ continue;
2499
+ }
2500
+ if (spec.scriptHosts.some((h) => host === h || host.endsWith(`.${h}`))) {
2501
+ add(file, ctx.project.position(file, m.index ?? 0).line);
2502
+ break;
2503
+ }
2504
+ }
2505
+ }
2506
+ }
2507
+ return [...facts.values()];
2508
+ }
2509
+ };
2510
+ }
2511
+ var serviceDetectors = SERVICES.map(serviceDetector);
2512
+
2513
+ // src/scanner/detectors/stores.ts
2514
+ var SUPABASE_SQL = /(^|\/)supabase\/(migrations\/.+|schema)\.sql$/;
2515
+ var stripSqlComments = (sql) => sql.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
2516
+ function tableName(raw) {
2517
+ const parts = raw.replace(/"/g, "").split(".");
2518
+ if (parts.length === 2 && parts[0] !== "public") return null;
2519
+ return parts[parts.length - 1].toLowerCase();
2520
+ }
2521
+ var supabase = {
2522
+ id: "data-store/supabase",
2523
+ skipReason: (ctx) => ctx.hasDepPrefix("@supabase/") || ctx.hasPyImport("supabase") || ctx.project.files.some((f) => SUPABASE_SQL.test(f)) ? null : "no Supabase package or migrations found",
2524
+ run: (ctx) => {
2525
+ const sqlFiles = ctx.project.files.filter((f) => SUPABASE_SQL.test(f)).sort();
2526
+ const created = /* @__PURE__ */ new Map();
2527
+ const secured = /* @__PURE__ */ new Set();
2528
+ for (const file of sqlFiles) {
2529
+ const raw = ctx.project.read(file);
2530
+ if (raw === null) continue;
2531
+ const sql = stripSqlComments(raw);
2532
+ for (const m of sql.matchAll(/create\s+table\s+(?:if\s+not\s+exists\s+)?([\w."]+)/gi)) {
2533
+ const name = tableName(m[1]);
2534
+ if (name && !created.has(name)) created.set(name, { file, line: ctx.project.position(file, raw.indexOf(m[0])).line });
2535
+ }
2536
+ for (const m of sql.matchAll(/alter\s+table\s+(?:only\s+)?([\w."]+)\s+enable\s+row\s+level\s+security/gi)) {
2537
+ const name = tableName(m[1]);
2538
+ if (name) secured.add(name);
2539
+ }
2540
+ }
2541
+ if (created.size > 0) {
2542
+ const names = [...created.keys()];
2543
+ const covered = names.filter((n) => secured.has(n)).length;
2544
+ const rls = covered === names.length ? "enabled" : covered === 0 ? "disabled" : "partial";
2545
+ const first = created.values().next().value;
2546
+ const claim = {
2547
+ enabled: "Application data is stored in a Supabase Postgres database, and the migrations enable row-level security on every table they create.",
2548
+ partial: "Application data is stored in a Supabase Postgres database, but the migrations enable row-level security on only some of the tables they create.",
2549
+ disabled: "Application data is stored in a Supabase Postgres database, and the migrations don't enable row-level security on the tables they create."
2550
+ }[rls];
2551
+ return [
2552
+ {
2553
+ kind: "data_store",
2554
+ subject: "Supabase Postgres",
2555
+ claim,
2556
+ attributes: { provider: "Supabase", engine: "postgres", rowLevelSecurity: rls, tables: names.length },
2557
+ confidence: "high",
2558
+ detector: "data-store/supabase",
2559
+ key: sqlFiles[0],
2560
+ locations: [{ file: first.file, line: first.line }]
2561
+ }
2562
+ ];
2563
+ }
2564
+ const pyUser = ctx.py.find((f) => importsPy(f, "supabase"));
2565
+ const user = ctx.js.find((f) => importsModule(f, "@supabase/supabase-js")) ?? pyUser;
2566
+ if (!user) return [];
2567
+ const imp = "imports" in user && pyUser === user ? importsPy(pyUser, "supabase") : importsModule(user, "@supabase/supabase-js");
2568
+ return [
2569
+ {
2570
+ kind: "data_store",
2571
+ subject: "Supabase Postgres",
2572
+ claim: "The app uses Supabase as its database; no migrations were found, so row-level security can't be checked.",
2573
+ attributes: { provider: "Supabase", engine: "postgres", rowLevelSecurity: "unknown" },
2574
+ confidence: "medium",
2575
+ detector: "data-store/supabase",
2576
+ key: user.file,
2577
+ locations: [{ file: user.file, ...imp?.line ? { line: imp.line } : {} }]
2578
+ }
2579
+ ];
2580
+ }
2581
+ };
2582
+ var STORES = [
2583
+ { slug: "postgres", subject: "PostgreSQL", engine: "postgres", packages: ["pg", "postgres", "pg-promise"], pyModules: ["psycopg", "psycopg2", "asyncpg"] },
2584
+ { slug: "mongodb", subject: "MongoDB", engine: "mongodb", packages: ["mongodb", "mongoose"], pyModules: ["pymongo", "motor", "mongoengine", "beanie"] },
2585
+ { slug: "redis", subject: "Redis", engine: "redis", packages: ["redis", "ioredis", "@upstash/redis"], pyModules: ["redis", "aioredis"] },
2586
+ { slug: "firebase", subject: "Firebase (Firestore)", engine: "firestore", packages: ["firebase/firestore", "firebase-admin/firestore", "firebase-admin"], pyModules: ["firebase_admin.firestore", "google.cloud.firestore"] },
2587
+ { slug: "mysql", subject: "MySQL", engine: "mysql", packages: ["mysql", "mysql2"], pyModules: ["pymysql", "mysql.connector", "aiomysql", "MySQLdb"] },
2588
+ { slug: "sqlalchemy", subject: "SQL database (SQLAlchemy)", engine: "sql", packages: [], pyModules: ["sqlalchemy"] },
2589
+ { slug: "azure-blob", subject: "Azure Blob Storage", engine: "object-storage", packages: ["@azure/storage-blob"], pyModules: ["azure.storage.blob"] },
2590
+ { slug: "cosmos", subject: "Azure Cosmos DB", engine: "cosmos", packages: ["@azure/cosmos"], pyModules: ["azure.cosmos"] },
2591
+ { slug: "azure-search", subject: "Azure AI Search", engine: "search-index", packages: ["@azure/search-documents"], pyModules: ["azure.search.documents"] },
2592
+ { slug: "chroma", subject: "Chroma", engine: "vector", packages: ["chromadb"], pyModules: ["chromadb"] },
2593
+ { slug: "qdrant", subject: "Qdrant", engine: "vector", packages: ["@qdrant/js-client-rest"], pyModules: ["qdrant_client"] },
2594
+ { slug: "pinecone", subject: "Pinecone", engine: "vector", packages: ["@pinecone-database/pinecone"], pyModules: ["pinecone"] }
2595
+ ];
2596
+ function storeDetector(spec) {
2597
+ const id = `data-store/${spec.slug}`;
2598
+ const fact = (file, line) => ({
2599
+ kind: "data_store",
2600
+ subject: spec.subject,
2601
+ claim: `The app stores data in ${spec.subject}.`,
2602
+ attributes: { engine: spec.engine },
2603
+ confidence: "high",
2604
+ detector: id,
2605
+ key: file,
2606
+ locations: [{ file, ...line ? { line } : {} }]
2607
+ });
2608
+ return {
2609
+ id,
2610
+ skipReason: (ctx) => {
2611
+ const roots = spec.packages.map((p) => p.startsWith("@") ? p : p.split("/")[0]);
2612
+ if (roots.length > 0 && ctx.hasDep(...roots)) return null;
2613
+ if (spec.pyModules && ctx.hasPyImport(...spec.pyModules)) return null;
2614
+ return `no ${spec.subject} package in dependencies`;
2615
+ },
2616
+ run: (ctx) => [
2617
+ ...ctx.py.flatMap((f) => {
2618
+ const imp = spec.pyModules ? importsPy(f, ...spec.pyModules) : void 0;
2619
+ return imp ? [fact(f.file, imp.line)] : [];
2620
+ }),
2621
+ ...ctx.js.flatMap((f) => {
2622
+ const imp = spec.packages.map((p) => importsModule(f, p)).find(Boolean);
2623
+ return imp ? [fact(f.file, imp.line)] : [];
2624
+ })
2625
+ ]
2626
+ };
2627
+ }
2628
+ var CONNECTION_FILE = /\.(?:py|ya?ml|toml|ini|cfg|json)$|(?:^|\/)\.env(?:\.[\w.-]+)?$/;
2629
+ var CONNECTION_STRING = /\b(postgres(?:ql)?(?:\+\w+)?|mysql(?:\+\w+)?|mongodb(?:\+srv)?|rediss?):\/\//gi;
2630
+ var CONNECTION_SUBJECT = (scheme) => {
2631
+ const s = scheme.toLowerCase();
2632
+ return s.startsWith("postgres") ? "PostgreSQL" : s.startsWith("mysql") ? "MySQL" : s.startsWith("mongodb") ? "MongoDB" : "Redis";
2633
+ };
2634
+ var connectionString = {
2635
+ id: "data-store/connection-string",
2636
+ skipReason: () => null,
2637
+ run: (ctx) => {
2638
+ const facts = [];
2639
+ for (const file of ctx.project.files) {
2640
+ if (!CONNECTION_FILE.test(file) || /(?:^|\/)(?:package-lock\.json|[^/]*\.lock)$/.test(file)) continue;
2641
+ const text = ctx.project.read(file);
2642
+ if (text === null) continue;
2643
+ const seen = /* @__PURE__ */ new Set();
2644
+ for (const m of text.matchAll(CONNECTION_STRING)) {
2645
+ const subject = CONNECTION_SUBJECT(m[1]);
2646
+ if (seen.has(subject)) continue;
2647
+ seen.add(subject);
2648
+ facts.push({
2649
+ kind: "data_store",
2650
+ subject,
2651
+ claim: `A connection string for ${subject} appears in the project's configuration.`,
2652
+ attributes: { engine: subject.toLowerCase() },
2653
+ confidence: "medium",
2654
+ detector: "data-store/connection-string",
2655
+ key: file,
2656
+ locations: [{ file, line: ctx.project.position(file, m.index ?? 0).line }]
2657
+ });
2658
+ }
2659
+ }
2660
+ return facts;
2661
+ }
2662
+ };
2663
+ var storeDetectors = [supabase, ...STORES.map(storeDetector), connectionString];
2664
+
2665
+ // src/verify/entities.ts
2666
+ var EXTRA = [
2667
+ "AWS",
2668
+ "Amazon Web Services",
2669
+ "Azure",
2670
+ "Google Cloud",
2671
+ "GCP",
2672
+ "Cloudflare",
2673
+ "Netlify",
2674
+ "Vercel",
2675
+ "Heroku",
2676
+ "DigitalOcean",
2677
+ "GitHub",
2678
+ "GitLab",
2679
+ "Slack",
2680
+ "Notion",
2681
+ "SharePoint",
2682
+ "Datadog",
2683
+ "Supabase",
2684
+ "Firebase",
2685
+ "Postgres",
2686
+ "Mailchimp",
2687
+ "HubSpot",
2688
+ "Salesforce",
2689
+ "Zendesk",
2690
+ "Intercom"
2691
+ ];
2692
+ var VENDOR_WORDS = ["Vercel", "Supabase", "Firebase", "Google", "Plausible", "Stripe", "OpenAI", "Anthropic", "Sentry", "PostHog", "Mixpanel", "Segment", "Resend", "SendGrid", "Postmark", "Twilio", "Clerk", "Auth0", "Hotjar"];
2693
+ function build() {
2694
+ const names = /* @__PURE__ */ new Set();
2695
+ for (const p of AI_PROVIDERS) names.add(p.subject);
2696
+ for (const s of SERVICES) names.add(s.subject);
2697
+ for (const s of STORES) names.add(s.subject);
2698
+ for (const a of AUTH_PACKAGES) names.add(a.subject);
2699
+ for (const e of EXTRA) names.add(e);
2700
+ for (const w of VENDOR_WORDS) names.add(w);
2701
+ for (const generic of ["JSON Web Tokens", "Auth.js", "Passport"]) names.delete(generic);
2702
+ return [...names].sort((a, b) => b.length - a.length);
2703
+ }
2704
+ var KNOWN_ENTITIES = build();
2705
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2706
+ function entitiesIn(text, extra = []) {
2707
+ const found = /* @__PURE__ */ new Set();
2708
+ let rest = text;
2709
+ for (const name of [.../* @__PURE__ */ new Set([...KNOWN_ENTITIES, ...extra])].sort((a, b) => b.length - a.length)) {
2710
+ const re = new RegExp(`(?<![\\w])${escape2(name)}(?![\\w])`, "i");
2711
+ if (re.test(rest)) {
2712
+ found.add(name.toLowerCase());
2713
+ rest = rest.replace(new RegExp(`(?<![\\w])${escape2(name)}(?![\\w])`, "gi"), " ");
2714
+ }
2715
+ }
2716
+ return [...found];
2717
+ }
2718
+
2719
+ // src/verify/verify.ts
2720
+ var PLACES = /\b(london|ireland|dublin|frankfurt|paris|amsterdam|stockholm|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d|eu-north-\d|uk|united kingdom|eu|europe|usa|united states|asia|australia)\b/gi;
2721
+ var NUMBERS = /(?<![\w.-])\d+(?:[.,]\d+)?(?![\w-])/g;
2722
+ var ABSENCE = /\b(no|not|never|without|none|neither|nor|doesn't|does not|do not|don't|isn't|aren't|cannot|can't|nothing)\b/i;
2723
+ var QUALIFIER = /\b(inferred|appears?|appeared|suggests?|may|might|likely|probably|not confirmed|possibly)\b/i;
2724
+ var OVERCLAIM = /\b(compliant|certified|guarantee[sd]?|guaranteeing|fully secure|100% secure|bank-grade|military-grade|complies with|meets the requirements of)\b/i;
2725
+ var PROJECT_LANGUAGE = /\b(we|our|ours|the (?:app|application|system|service|platform|product|project|code|codebase)|this (?:app|application|system|service|platform|product))\b/i;
2726
+ function sentencesOf(source) {
2727
+ const noticePresent = /not legal advice/i.test(source);
2728
+ const sentences2 = [];
2729
+ const lines = source.split(/\r?\n/);
2730
+ let inCode = false;
2731
+ let inSources = false;
2732
+ lines.forEach((raw, i) => {
2733
+ if (/^\s*```/.test(raw)) {
2734
+ inCode = !inCode;
2735
+ return;
2736
+ }
2737
+ if (inCode) return;
2738
+ if (/^\s{0,3}#{1,6}\s*sources\s*$/i.test(raw)) inSources = true;
2739
+ else if (/^\s{0,3}#{1,6}\s/.test(raw)) inSources = false;
2740
+ if (inSources || /^\s*\[\^[^\]]+\]:/.test(raw)) return;
2741
+ if (/^\s{0,3}#{1,6}\s/.test(raw)) return;
2742
+ if (/^\s*\|?[\s:-]+\|[\s|:-]*$/.test(raw)) return;
2743
+ if (/needs your input/i.test(raw)) return;
2744
+ let line = raw.replace(/^\s*>\s?/, "").replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "");
2745
+ line = line.replace(/\*\*|__|`/g, "");
2746
+ line = line.replace(/(?:\[\^[A-Za-z0-9-]+\])+/g, (m) => `[${[...m.matchAll(/\[\^([A-Za-z0-9-]+)\]/g)].map((x) => x[1]).join(", ")}]`);
2747
+ if (line.includes(DRAFT_NOTICE.slice(0, 40))) return;
2748
+ if (line.trim() === "") return;
2749
+ if (TALLY_LINE.test(line.trim())) return;
2750
+ if (isTemplateSentence(line)) return;
2751
+ for (const s of line.split(/(?<=[.!?])\s+(?=[A-Z"'(\[])/)) {
2752
+ const text = s.trim();
2753
+ if (text.length > 0 && !text.endsWith("?") && !isTemplateSentence(text)) sentences2.push({ line: i + 1, text });
2754
+ }
2755
+ });
2756
+ return { sentences: sentences2, noticePresent };
2757
+ }
2758
+ var lower = (s) => s.toLowerCase();
2759
+ function sourceTexts(evidence, answers) {
2760
+ const m = /* @__PURE__ */ new Map();
2761
+ for (const f of evidence.facts) {
2762
+ const attrs = Object.values(f.attributes).flatMap((v) => Array.isArray(v) ? v : [String(v)]);
2763
+ m.set(f.id, lower([f.subject, f.claim, ...attrs, ...f.locations.map((l) => l.file)].join(" ")));
2764
+ }
2765
+ for (const f of evidence.findings) m.set(f.id, lower(`${f.ruleId} ${f.severity} seaworthy ${f.location?.file ?? ""}`));
2766
+ const leads = new Map(Object.values(PROFILE).map((p) => [p.key, p.lead]));
2767
+ const unknowns = new Map(evidence.unknowns.map((u) => [u.id, u]));
2768
+ const subjectOf = new Map(evidence.facts.map((f) => [f.id, f.subject]));
2769
+ for (const a of answers.answers) {
2770
+ const u = unknowns.get(a.question);
2771
+ const asked = u ? `${u.topic} ${u.question} ${u.relatedFacts.map((id) => subjectOf.get(id) ?? "").join(" ")}` : "";
2772
+ m.set(a.id, lower(`${leads.get(a.question) ?? ""} ${asked} ${a.value} ${a.question}`));
2773
+ }
2774
+ return m;
2775
+ }
2776
+ var stripMarkers = (s) => s.replace(/\[(?:EV|F|KB|A)-[0-9a-f]+(?:\s*,\s*(?:EV|F|KB|A)-[0-9a-f]+)*\]/gi, " ").replace(/\[(?:A-\d+)(?:\s*,\s*[A-Za-z0-9-]+)*\]/g, " ");
2777
+ function verifyText(source, evidence, answers) {
2778
+ const issues = [];
2779
+ const texts = sourceTexts(evidence, answers);
2780
+ const facts = new Map(evidence.facts.map((f) => [f.id, f]));
2781
+ const subjectNames = evidence.facts.filter((f) => f.claimType === "observed").map((f) => f.subject);
2782
+ const { sentences: sentences2, noticePresent } = sentencesOf(source);
2783
+ let withRefs = 0;
2784
+ const add = (severity, code, b, message) => issues.push({ severity, code, line: b.line, sentence: b.text, message });
2785
+ for (const b of sentences2) {
2786
+ const refs = extractRefs(b.text);
2787
+ const body = stripMarkers(b.text);
2788
+ const mentioned = entitiesIn(body, subjectNames);
2789
+ const numbers = [...body.matchAll(NUMBERS)].map((m) => m[0]);
2790
+ const places = [...body.matchAll(PLACES)].map((m) => m[0].toLowerCase());
2791
+ const citesUser = refs.some((r) => r.kind === "A");
2792
+ if (OVERCLAIM.test(body) && !citesUser) {
2793
+ add("error", "overclaim", b, `Wording that implies legal assurance ("${body.match(OVERCLAIM)[0]}"). Soundings documents describe what the code shows and never claim compliance, certification or guarantees.`);
2794
+ }
2795
+ if (refs.length === 0) {
2796
+ if (mentioned.length > 0 || numbers.length > 0 || places.length > 0) {
2797
+ const what = [...mentioned, ...numbers, ...places].slice(0, 3).join(", ");
2798
+ add("error", "missing-reference", b, `States something specific (${what}) with no evidence or answer reference.`);
2799
+ } else if (PROJECT_LANGUAGE.test(body)) {
2800
+ add("warning", "unreferenced-statement", b, "Reads as a statement about the project but cites no source.");
2801
+ }
2802
+ continue;
2803
+ }
2804
+ withRefs++;
2805
+ const missing = refs.filter((r) => !texts.has(r.id));
2806
+ for (const r of missing) add("error", "unknown-reference", b, `${r.id} doesn't exist in the evidence or answers file.`);
2807
+ const cited = refs.filter((r) => texts.has(r.id));
2808
+ if (cited.length === 0) continue;
2809
+ const support = cited.map((r) => texts.get(r.id)).join(" ");
2810
+ for (const e of mentioned) {
2811
+ if (!support.includes(e)) add("error", "entity-not-in-source", b, `Mentions "${e}", but none of the cited sources do.`);
2812
+ }
2813
+ for (const n of numbers) {
2814
+ if (!support.includes(n)) add("error", "number-not-in-source", b, `Uses the number ${n}, which none of the cited sources contain.`);
2815
+ }
2816
+ for (const p of places) {
2817
+ if (!new RegExp(`(?<![\\w])${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w])`, "i").test(support)) {
2818
+ add("error", "place-not-in-source", b, `Names a place ("${p}") that none of the cited sources mention.`);
2819
+ }
2820
+ }
2821
+ const citedFacts = cited.map((r) => facts.get(r.id)).filter((f) => Boolean(f));
2822
+ if (citedFacts.length > 0 && cited.every((r) => r.kind === "EV")) {
2823
+ const bodyForAbsence = body.replace(new RegExp(NOT_YET_PROVIDED, "gi"), " ").replace(/\(inferred[^)]*\)/gi, " ").replace(/\bnot confirmed\b/gi, " ");
2824
+ const saysAbsent = ABSENCE.test(bodyForAbsence);
2825
+ const allObserved = citedFacts.every((f) => f.claimType === "observed" && !ABSENCE.test(f.claim));
2826
+ const allNotFound = citedFacts.every((f) => f.claimType === "not-found");
2827
+ if (saysAbsent && allObserved) add("error", "absence-contradicts-source", b, "Says something is absent or not done, but the cited fact shows it is present.");
2828
+ if (!saysAbsent && allNotFound) add("error", "presence-from-not-found", b, 'States something is present, but the only cited fact is a "not found" result.');
2829
+ }
2830
+ if (citedFacts.some((f) => f.confidence === "low")) {
2831
+ add("error", "low-confidence-fact", b, "Cites a low-confidence fact. Those are for the user to confirm and must stay out of documents.");
2832
+ }
2833
+ const onlyInferred = citedFacts.length > 0 && cited.every((r) => r.kind === "EV") && citedFacts.every((f) => f.claimType === "observed" && f.confidence === "medium");
2834
+ if (onlyInferred && !QUALIFIER.test(body)) {
2835
+ add("error", "unqualified-inference", b, 'Relies only on an inferred (medium-confidence) fact without saying so. Add wording such as "appears to" or "(inferred from the code)".');
2836
+ }
2837
+ }
2838
+ if (!noticePresent) {
2839
+ issues.push({ severity: "warning", code: "missing-notice", line: 1, sentence: "", message: "No draft notice found. Every document should say it is a draft and not legal advice." });
2840
+ }
2841
+ return {
2842
+ issues,
2843
+ sentencesChecked: sentences2.length,
2844
+ sentencesWithReferences: withRefs,
2845
+ noticePresent,
2846
+ ok: !issues.some((i) => i.severity === "error")
2847
+ };
2848
+ }
2849
+
2850
+ // src/reporters/verify.ts
2851
+ import pc from "picocolors";
2852
+ function renderVerify(report, file) {
2853
+ const out = [""];
2854
+ const errors = report.issues.filter((i) => i.severity === "error");
2855
+ const warnings = report.issues.filter((i) => i.severity === "warning");
2856
+ for (const i of report.issues) {
2857
+ const tag2 = i.severity === "error" ? pc.red("error ") : pc.yellow("warning");
2858
+ out.push(` ${tag2} ${file}:${i.line} ${pc.dim(i.code)}`);
2859
+ out.push(` ${i.message}`);
2860
+ if (i.sentence) out.push(` ${pc.dim(`"${i.sentence.length > 140 ? `${i.sentence.slice(0, 137)}...` : i.sentence}"`)}`);
2861
+ out.push("");
2862
+ }
2863
+ const summary = `${report.sentencesChecked} sentences checked, ${report.sentencesWithReferences} with references.`;
2864
+ if (report.ok) {
2865
+ out.push(` ${pc.green("Passed.")} ${summary}${warnings.length ? ` ${warnings.length} warning${warnings.length === 1 ? "" : "s"}.` : ""}`);
2866
+ out.push(` ${pc.dim("Every statement points to a source that exists and mentions what the sentence mentions. That is not proof the source is right.")}`);
2867
+ } else {
2868
+ out.push(` ${pc.red(`Failed: ${errors.length} problem${errors.length === 1 ? "" : "s"}.`)} ${summary}`);
2869
+ }
2870
+ out.push("");
2871
+ return out.join("\n");
2872
+ }
2873
+ function renderFill(result, outPath) {
2874
+ const n = (s) => result.outcomes.filter((o) => o.status === s).length;
2875
+ const out = [""];
2876
+ out.push(` ${pc.bold(`${result.outcomes.length} questions`)}: ${pc.green(`${n("answered")} answered`)}, ${pc.yellow(`${n("partial")} partly answered`)}, ${n("needs-input")} need your input, ${n("unmatched")} not matched, ${n("kept")} left as you had them.`);
2877
+ const unmatched = result.outcomes.filter((o) => o.status === "unmatched");
2878
+ if (unmatched.length > 0) {
2879
+ out.push("", ` ${pc.bold("Not matched (answer these by hand)")}`);
2880
+ for (const o of unmatched) out.push(` row ${o.row} ${o.question}`);
2881
+ }
2882
+ out.push("", ` Saved to ${outPath}.${result.answerColumnAdded ? ' A "Soundings answer" column was added.' : ""}`);
2883
+ out.push(` ${pc.dim('Check the "Soundings match" column: it shows which standard question each row was matched to.')}`, "");
2884
+ return out.join("\n");
2885
+ }
2886
+
2887
+ // src/questions/answers-file.ts
2888
+ import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
2889
+
2890
+ // src/evidence/schema.ts
2891
+ import { z as z2 } from "zod";
2892
+ var SCHEMA_VERSION = "0.2";
2893
+ var factId = z2.string().regex(/^EV-[0-9a-f]{6,12}$/, "fact ids look like EV-3fa9c2d1");
2894
+ var findingId = z2.string().regex(/^F-[0-9a-f]{6,12}$/, "finding ids look like F-3fa9c2d1");
2895
+ var unknownId = z2.string().regex(/^UQ-[a-z0-9]+(?:-[a-z0-9]+)*$/, "unknown ids look like UQ-supabase-region");
2896
+ var answerId = z2.string().regex(/^A-\d{3,}$/, "answer ids look like A-001");
2897
+ var FactKind = z2.enum([
2898
+ "ai_provider",
2899
+ // an AI model provider or SDK is used
2900
+ "third_party_service",
2901
+ // payments, analytics, email, error tracking, hosting...
2902
+ "data_flow",
2903
+ // user or customer data sent to a destination
2904
+ "data_store",
2905
+ // database, storage bucket, cache
2906
+ "auth",
2907
+ // how users or services authenticate
2908
+ "secret_handling",
2909
+ // where and how keys and secrets are kept
2910
+ "logging",
2911
+ // what is logged, and where
2912
+ "region",
2913
+ // where a service or store runs, when determinable
2914
+ "retention",
2915
+ // how long data is kept, when determinable
2916
+ "client_side_exposure"
2917
+ // anything sensitive reachable from browser code
2918
+ ]);
2919
+ var Confidence = z2.enum(["high", "medium", "low"]);
2920
+ var Attribute = z2.union([z2.string(), z2.number(), z2.boolean(), z2.array(z2.string())]);
2921
+ var Location = z2.object({
2922
+ /** Repo-relative path, forward slashes. */
2923
+ file: z2.string().min(1),
2924
+ line: z2.number().int().positive().optional()
2925
+ });
2926
+ var ClaimType = z2.enum(["observed", "not-found"]);
2927
+ var Fact = z2.object({
2928
+ id: factId,
2929
+ kind: FactKind,
2930
+ /** The thing the fact is about, e.g. "OpenAI", "Supabase", "Stripe". */
2931
+ subject: z2.string().min(1),
2932
+ /** One plain-English sentence. No code, no secret values. */
2933
+ claim: z2.string().min(1).max(280),
2934
+ claimType: ClaimType.default("observed"),
2935
+ /**
2936
+ * Structured detail used by templates and the question bank. Conventional keys for the
2937
+ * subprocessor list: `purpose`, `dataCategories`, `region`.
2938
+ */
2939
+ attributes: z2.record(z2.string(), Attribute).default({}),
2940
+ confidence: Confidence,
2941
+ /** Detector that produced it, e.g. "ai-provider/openai-sdk". */
2942
+ detector: z2.string().min(1),
2943
+ /** Stable discriminator the ID is derived from (usually a file path). Not a line number. */
2944
+ key: z2.string().default(""),
2945
+ locations: z2.array(Location).default([])
2946
+ }).superRefine((fact, ctx) => {
2947
+ if (fact.claimType === "not-found" && fact.confidence === "high") {
2948
+ ctx.addIssue({
2949
+ code: "custom",
2950
+ message: `${fact.id}: a "not-found" claim can't be high confidence; absence of a pattern is not proof`
2951
+ });
2952
+ }
2953
+ });
2954
+ var Unknown = z2.object({
2955
+ id: unknownId,
2956
+ topic: z2.string().min(1),
2957
+ question: z2.string().min(1),
2958
+ /** Why the code can't answer it, shown to the user. */
2959
+ why: z2.string().min(1),
2960
+ relatedFacts: z2.array(factId).default([])
2961
+ });
2962
+ var FindingRef = z2.object({
2963
+ id: findingId,
2964
+ ruleId: z2.string().regex(/^SW-[A-Z]\d{2}$/),
2965
+ severity: z2.enum(["critical", "high", "medium", "low"]),
2966
+ location: Location.optional(),
2967
+ /** Facts this finding bears on, so a reader sees when a fact and a finding pull different ways. */
2968
+ relatedFacts: z2.array(factId).default([])
2969
+ });
2970
+ var ScanCoverage = z2.object({
2971
+ filesScanned: z2.number().int().nonnegative(),
2972
+ filesSkipped: z2.number().int().nonnegative(),
2973
+ detectorsRun: z2.array(z2.string()),
2974
+ detectorsSkipped: z2.array(z2.object({ detector: z2.string().min(1), reason: z2.string().min(1) })),
2975
+ /** Source code in languages Soundings doesn't read. What it does is not in this file. */
2976
+ unsupported: z2.array(z2.object({ language: z2.string().min(1), files: z2.number().int().positive() })).default([])
2977
+ });
2978
+ var EvidenceFile = z2.object({
2979
+ schemaVersion: z2.literal(SCHEMA_VERSION),
2980
+ generatedAt: z2.string().datetime(),
2981
+ tool: z2.object({ name: z2.string(), version: z2.string() }),
2982
+ /** Hard privacy guard. A file that sets this to true is invalid. */
2983
+ containsSourceCode: z2.literal(false),
2984
+ project: z2.object({
2985
+ name: z2.string().min(1),
2986
+ languages: z2.array(z2.string()).default([]),
2987
+ frameworks: z2.array(z2.string()).default([])
2988
+ }),
2989
+ scan: ScanCoverage,
2990
+ facts: z2.array(Fact),
2991
+ unknowns: z2.array(Unknown).default([]),
2992
+ findings: z2.array(FindingRef).default([])
2993
+ }).superRefine((file, ctx) => {
2994
+ const ids = /* @__PURE__ */ new Set();
2995
+ for (const item2 of [...file.facts, ...file.unknowns, ...file.findings]) {
2996
+ if (ids.has(item2.id)) ctx.addIssue({ code: "custom", message: `duplicate id ${item2.id}` });
2997
+ ids.add(item2.id);
2998
+ }
2999
+ const factIds = new Set(file.facts.map((f) => f.id));
3000
+ for (const u of file.unknowns) {
3001
+ for (const ref of u.relatedFacts) {
3002
+ if (!factIds.has(ref)) ctx.addIssue({ code: "custom", message: `${u.id} refers to missing fact ${ref}` });
3003
+ }
3004
+ }
3005
+ for (const f of file.findings) {
3006
+ for (const ref of f.relatedFacts) {
3007
+ if (!factIds.has(ref)) ctx.addIssue({ code: "custom", message: `${f.id} refers to missing fact ${ref}` });
3008
+ }
3009
+ }
3010
+ });
3011
+ var Answer = z2.object({
3012
+ id: answerId,
3013
+ /** Either an unknown id (UQ-...) or a profile key such as "profile.industry". */
3014
+ question: z2.string().min(1),
3015
+ value: z2.string().min(1),
3016
+ answeredAt: z2.string().datetime()
3017
+ });
3018
+ var AnswersFile = z2.object({
3019
+ schemaVersion: z2.literal(SCHEMA_VERSION),
3020
+ answers: z2.array(Answer)
3021
+ });
3022
+
3023
+ // src/questions/answers-file.ts
3024
+ var AnswersError = class extends Error {
3025
+ };
3026
+ var emptyAnswers = () => ({ schemaVersion: SCHEMA_VERSION, answers: [] });
3027
+ function loadAnswers(path) {
3028
+ if (!existsSync2(path)) return emptyAnswers();
3029
+ try {
3030
+ return AnswersFile.parse(JSON.parse(readFileSync3(path, "utf8")));
3031
+ } catch (err) {
3032
+ throw new AnswersError(`Couldn't read ${path}: ${err instanceof Error ? err.message : String(err)}`);
3033
+ }
3034
+ }
3035
+ function saveAnswers(path, file) {
3036
+ writeFileSync(path, JSON.stringify(file, null, 2) + "\n");
3037
+ }
3038
+ function setAnswer(file, question, value, now) {
3039
+ const text = value.trim();
3040
+ if (text.length === 0) throw new AnswersError("An answer can't be empty.");
3041
+ if (findLeaks(text).length > 0) {
3042
+ throw new AnswersError("That answer looks like it contains a secret (a key, token or password). Answers go into documents, so describe it instead of pasting it.");
3043
+ }
3044
+ const existing = file.answers.find((a) => a.question === question);
3045
+ if (existing) {
3046
+ return {
3047
+ ...file,
3048
+ answers: file.answers.map((a) => a === existing ? { ...a, value: text, answeredAt: now.toISOString() } : a)
3049
+ };
3050
+ }
3051
+ const next = file.answers.reduce((max, a) => Math.max(max, Number(a.id.slice(2))), 0) + 1;
3052
+ const id = `A-${String(next).padStart(3, "0")}`;
3053
+ return { ...file, answers: [...file.answers, { id, question, value: text, answeredAt: now.toISOString() }] };
3054
+ }
3055
+
3056
+ // src/questions/flow.ts
3057
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
3058
+ var QuestionsError = class extends Error {
3059
+ };
3060
+ function loadEvidence(path) {
3061
+ if (!existsSync3(path)) throw new QuestionsError(`No evidence file at ${path}. Run "soundings scan" first.`);
3062
+ try {
3063
+ return EvidenceFile.parse(JSON.parse(readFileSync4(path, "utf8")));
3064
+ } catch (err) {
3065
+ throw new QuestionsError(`Couldn't read ${path}: ${err instanceof Error ? err.message : String(err)}`);
3066
+ }
3067
+ }
3068
+ function checkKey(key, evidence) {
3069
+ if (key.startsWith("UQ-")) {
3070
+ if (!evidence.unknowns.some((u) => u.id === key)) throw new QuestionsError(`${key} isn't a question in this evidence file. Run "soundings questions --list" to see them.`);
3071
+ } else if (key.startsWith("profile.")) {
3072
+ if (!PROFILE_KEYS.has(key)) throw new QuestionsError(`${key} isn't a known profile question.`);
3073
+ } else if (key.startsWith("override.")) {
3074
+ if (!BANK.some((b) => `override.${b.id}` === key)) throw new QuestionsError(`${key} doesn't match a question in the bank.`);
3075
+ } else {
3076
+ throw new QuestionsError(`"${key}" isn't a valid answer key. Use UQ-\u2026, profile.\u2026 or override.<question-id>.`);
3077
+ }
3078
+ }
3079
+ function stateOf(evidence, answers, includeDocuments = false) {
3080
+ const results = answerAll(evidence, answers);
3081
+ const known = new Set(evidence.unknowns.map((u) => u.id));
3082
+ const stale = answers.answers.filter((a) => a.question.startsWith("UQ-") && !known.has(a.question)).map((a) => a.question);
3083
+ const pending = pendingNeeds(evidence, results, answers);
3084
+ if (includeDocuments) {
3085
+ const answered = new Set(answers.answers.map((a) => a.question));
3086
+ for (const n of documentNeeds(evidence, answers)) {
3087
+ if (answered.has(n.key)) continue;
3088
+ const existing = pending.find((p) => p.key === n.key);
3089
+ if (existing) existing.helps.push("documents");
3090
+ else pending.push({ key: n.key, prompt: n.prompt, helps: ["documents"] });
3091
+ }
3092
+ }
3093
+ return { results, pending, stale };
3094
+ }
3095
+ async function runQuestions(opts) {
3096
+ const evidence = loadEvidence(opts.evidencePath);
3097
+ let answers = loadAnswers(opts.answersPath);
3098
+ const saved = [];
3099
+ const rejected = [];
3100
+ const apply = (key, value) => {
3101
+ checkKey(key, evidence);
3102
+ answers = setAnswer(answers, key, value, opts.now);
3103
+ saveAnswers(opts.answersPath, answers);
3104
+ saved.push(key);
3105
+ };
3106
+ for (const [key, value] of opts.set) apply(key, value);
3107
+ if (opts.ask) {
3108
+ const pending = stateOf(evidence, answers, opts.documents).pending;
3109
+ for (let i = 0; i < pending.length; i++) {
3110
+ const reply = await opts.ask(pending[i], i, pending.length);
3111
+ if (reply === null) break;
3112
+ if (reply.trim() === "") continue;
3113
+ try {
3114
+ apply(pending[i].key, reply);
3115
+ } catch (err) {
3116
+ if (!(err instanceof AnswersError)) throw err;
3117
+ rejected.push({ key: pending[i].key, reason: err.message });
3118
+ }
3119
+ }
3120
+ }
3121
+ return { state: stateOf(evidence, answers, opts.documents), saved, rejected };
3122
+ }
3123
+
3124
+ // src/reporters/questions.ts
3125
+ import pc2 from "picocolors";
3126
+ function renderQuestionsSummary(state, answersPath2, saved) {
3127
+ const { results, pending, stale } = state;
3128
+ const count = (s) => results.filter((r) => r.status === s).length;
3129
+ const out = [""];
3130
+ if (saved.length) out.push(` Saved ${saved.length} answer${saved.length === 1 ? "" : "s"} to ${answersPath2}.`, "");
3131
+ out.push(
3132
+ ` ${pc2.bold(`${results.length} questions`)}: ${pc2.green(`${count("answered")} answered`)}, ${pc2.yellow(`${count("partial")} partly answered`)}, ${count("needs-input")} need your input.`
3133
+ );
3134
+ if (pending.length > 0) {
3135
+ out.push("", ` ${pc2.bold(`Still to answer (${pending.length})`)}`);
3136
+ for (const p of pending) {
3137
+ const helps = p.helps.length ? pc2.dim(` helps with ${p.helps.length} question${p.helps.length === 1 ? "" : "s"}`) : "";
3138
+ out.push(` ${pc2.cyan(p.key)} ${p.prompt}${helps}`);
3139
+ }
3140
+ out.push("", ` ${pc2.dim('Answer with: soundings questions --set <key>="your answer" (or run it in a terminal and answer as asked)')}`);
3141
+ } else {
3142
+ out.push("", " Nothing left to ask.");
3143
+ }
3144
+ if (stale.length > 0) {
3145
+ out.push("", ` ${pc2.dim(`Kept but no longer asked by the scan: ${stale.join(", ")}`)}`);
3146
+ }
3147
+ out.push("", ` ${pc2.dim(`${BANK.length} questions in the bank. Answers live in ${answersPath2} and are reused for every questionnaire.`)}`, "");
3148
+ return out.join("\n");
3149
+ }
3150
+
3151
+ // src/reporters/terminal.ts
3152
+ import pc3 from "picocolors";
3153
+ var SECTIONS = [
3154
+ ["ai_provider", "AI providers"],
3155
+ ["data_flow", "Data sent to other services"],
3156
+ ["third_party_service", "Third-party services"],
3157
+ ["data_store", "Where data is stored"],
3158
+ ["auth", "How users sign in"],
3159
+ ["secret_handling", "Keys and secrets"],
3160
+ ["logging", "Logging"],
3161
+ ["client_side_exposure", "Reachable from the browser"],
3162
+ ["region", "Regions"],
3163
+ ["retention", "Retention"]
3164
+ ];
3165
+ function tag(f) {
3166
+ if (f.claimType === "not-found") return pc3.dim("[not found by the scan]");
3167
+ if (f.confidence === "high") return pc3.green("[stated by the code]");
3168
+ if (f.confidence === "medium") return pc3.yellow("[inferred]");
3169
+ return pc3.red("[unconfirmed, needs your check]");
3170
+ }
3171
+ var where = (f) => {
3172
+ const l = f.locations[0];
3173
+ const more = f.locations.length > 1 ? ` (+${f.locations.length - 1} more)` : "";
3174
+ return l ? pc3.dim(`${l.file}${l.line ? `:${l.line}` : ""}${more}`) : "";
3175
+ };
3176
+ function renderTerminal(e, ms, evidencePath2) {
3177
+ const out = [];
3178
+ const stack = [...e.project.frameworks].join(", ");
3179
+ out.push("");
3180
+ out.push(` ${pc3.bold(`Soundings ${e.tool.version}`)} \xB7 ${e.project.name}${stack ? ` \xB7 ${stack}` : ""}`);
3181
+ out.push(
3182
+ ` ${e.scan.filesScanned} files, ${e.scan.detectorsRun.length} detectors, ${ms} ms. ${pc3.dim("Your code never left this machine.")}`
3183
+ );
3184
+ if (e.scan.unsupported.length > 0) {
3185
+ const n = e.scan.unsupported.map((x) => `${x.files} ${x.language} file${x.files === 1 ? "" : "s"}`).join(", ");
3186
+ out.push("");
3187
+ out.push(` ${pc3.yellow("Not analysed:")} ${n}. Soundings reads JavaScript and TypeScript, so what that code does is not in this report.`);
3188
+ }
3189
+ if (e.facts.length === 0) {
3190
+ out.push("");
3191
+ out.push(" Nothing in the supported list was found. Soundings reads JavaScript and TypeScript projects");
3192
+ out.push(" (Next.js, Node/Express, Supabase, Firebase, Stripe and the main AI SDKs); anything else it");
3193
+ out.push(` reports as "couldn't determine".`);
3194
+ }
3195
+ for (const [kind, title] of SECTIONS) {
3196
+ const facts = e.facts.filter((f) => f.kind === kind);
3197
+ if (facts.length === 0) continue;
3198
+ out.push("");
3199
+ out.push(` ${pc3.bold(title)}`);
3200
+ for (const f of facts) {
3201
+ out.push(` ${pc3.cyan(f.id)} ${f.subject} ${tag(f)}`);
3202
+ out.push(` ${f.claim}`);
3203
+ const loc = where(f);
3204
+ if (loc) out.push(` ${loc}`);
3205
+ }
3206
+ }
3207
+ if (e.findings.length > 0) {
3208
+ out.push("");
3209
+ out.push(` ${pc3.bold("Seaworthy findings")} ${pc3.dim("(from the report you supplied)")}`);
3210
+ for (const f of e.findings) {
3211
+ const loc = f.location ? ` ${pc3.dim(`${f.location.file}${f.location.line ? `:${f.location.line}` : ""}`)}` : "";
3212
+ out.push(` ${pc3.cyan(f.id)} ${f.severity.toUpperCase()} ${f.ruleId}${loc}`);
3213
+ }
3214
+ }
3215
+ if (e.unknowns.length > 0) {
3216
+ out.push("");
3217
+ out.push(` ${pc3.bold(`Only you can answer these (${e.unknowns.length})`)}`);
3218
+ for (const u of e.unknowns) {
3219
+ out.push(` ${pc3.cyan(u.id)} ${u.question}`);
3220
+ out.push(` ${pc3.dim(u.why)}`);
3221
+ }
3222
+ }
3223
+ const skipped = e.scan.detectorsSkipped.length;
3224
+ out.push("");
3225
+ if (evidencePath2) out.push(` Evidence saved to ${evidencePath2}. It holds paths, line numbers and short claims, never code or secrets.`);
3226
+ out.push(` ${pc3.dim(`${skipped} detector${skipped === 1 ? "" : "s"} skipped because their technology isn't in this project.`)}`);
3227
+ out.push(` ${pc3.dim("This is a draft record of what the code shows. It is not an audit or legal advice.")}`);
3228
+ out.push("");
3229
+ return out.join("\n");
3230
+ }
3231
+
3232
+ // src/evidence/build.ts
3233
+ import { createHash } from "crypto";
3234
+ var ID_HEX = 8;
3235
+ var hash = (s, len) => createHash("sha256").update(s).digest("hex").slice(0, len);
3236
+ var cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
3237
+ function allocate(prefix, preimages) {
3238
+ const seen = /* @__PURE__ */ new Map();
3239
+ const taken = /* @__PURE__ */ new Set();
3240
+ return preimages.map((pre) => {
3241
+ const n = seen.get(pre) ?? 0;
3242
+ seen.set(pre, n + 1);
3243
+ const full = n === 0 ? pre : `${pre}#${n}`;
3244
+ for (let len = ID_HEX; len <= 12; len += 2) {
3245
+ const id = `${prefix}-${hash(full, len)}`;
3246
+ if (!taken.has(id)) {
3247
+ taken.add(id);
3248
+ return id;
3249
+ }
3250
+ }
3251
+ throw new Error(`could not allocate a unique id for ${prefix}`);
3252
+ });
3253
+ }
3254
+ function sortedLocations(locs) {
3255
+ const out = [...locs ?? []].sort((a, b) => cmp(a.file, b.file) || (a.line ?? 0) - (b.line ?? 0));
3256
+ return out.filter((l, i) => i === 0 || l.file !== out[i - 1].file || l.line !== out[i - 1].line);
3257
+ }
3258
+ function canonicalAttributes(attrs) {
3259
+ const out = {};
3260
+ for (const k of Object.keys(attrs ?? {}).sort()) {
3261
+ const v = attrs[k];
3262
+ out[k] = Array.isArray(v) ? [...v].sort() : v;
3263
+ }
3264
+ return out;
3265
+ }
3266
+ var factPre = (d) => `${d.kind}|${d.subject}|${d.detector}|${d.key ?? ""}`;
3267
+ function buildEvidence(input) {
3268
+ const facts = input.facts.map((d) => ({ ...d, locations: sortedLocations(d.locations) })).sort(
3269
+ (a, b) => cmp(factPre(a), factPre(b)) || cmp(a.locations[0]?.file ?? "", b.locations[0]?.file ?? "") || (a.locations[0]?.line ?? 0) - (b.locations[0]?.line ?? 0)
3270
+ );
3271
+ const factIds = allocate("EV", facts.map(factPre));
3272
+ const idsFor = (related) => facts.map((f, i) => ({ f, id: factIds[i] })).filter(({ f }) => (related ?? []).some((r) => r.kind === f.kind && r.subject === f.subject)).map(({ id }) => id).sort();
3273
+ const findingsSorted = [...input.findings ?? []].sort(
3274
+ (a, b) => cmp(a.ruleId, b.ruleId) || cmp(a.location?.file ?? "", b.location?.file ?? "") || (a.location?.line ?? 0) - (b.location?.line ?? 0)
3275
+ );
3276
+ const findingIds = allocate(
3277
+ "F",
3278
+ findingsSorted.map((f) => `${f.ruleId}|${f.location?.file ?? ""}`)
3279
+ );
3280
+ const file = {
3281
+ schemaVersion: SCHEMA_VERSION,
3282
+ generatedAt: input.generatedAt,
3283
+ tool: input.tool,
3284
+ containsSourceCode: false,
3285
+ project: {
3286
+ name: input.project.name,
3287
+ languages: [...input.project.languages ?? []].sort(),
3288
+ frameworks: [...input.project.frameworks ?? []].sort()
3289
+ },
3290
+ scan: {
3291
+ ...input.scan,
3292
+ detectorsRun: [...input.scan.detectorsRun].sort(),
3293
+ detectorsSkipped: [...input.scan.detectorsSkipped].sort((a, b) => cmp(a.detector, b.detector)),
3294
+ unsupported: [...input.scan.unsupported ?? []].sort((a, b) => cmp(a.language, b.language))
3295
+ },
3296
+ facts: facts.map((f, i) => ({
3297
+ id: factIds[i],
3298
+ kind: f.kind,
3299
+ subject: f.subject,
3300
+ claim: f.claim,
3301
+ claimType: f.claimType ?? "observed",
3302
+ attributes: canonicalAttributes(f.attributes),
3303
+ confidence: f.confidence,
3304
+ detector: f.detector,
3305
+ key: f.key ?? "",
3306
+ locations: f.locations
3307
+ })),
3308
+ unknowns: [...input.unknowns ?? []].sort((a, b) => cmp(a.key, b.key)).map((u) => ({
3309
+ id: `UQ-${u.key}`,
3310
+ topic: u.topic,
3311
+ question: u.question,
3312
+ why: u.why,
3313
+ relatedFacts: idsFor(u.related)
3314
+ })),
3315
+ findings: findingsSorted.map((f, i) => ({
3316
+ id: findingIds[i],
3317
+ ruleId: f.ruleId,
3318
+ severity: f.severity,
3319
+ ...f.location ? { location: f.location } : {},
3320
+ relatedFacts: idsFor(f.related)
3321
+ }))
3322
+ };
3323
+ return EvidenceFile.parse(file);
3324
+ }
3325
+
3326
+ // src/core/project.ts
3327
+ import { readFileSync as readFileSync5 } from "fs";
3328
+ import { join as join3 } from "path";
3329
+ var ProjectFiles = class {
3330
+ constructor(root, files, isExcluded = () => false) {
3331
+ this.root = root;
3332
+ this.files = files;
3333
+ this.isExcluded = isExcluded;
3334
+ }
3335
+ root;
3336
+ files;
3337
+ isExcluded;
3338
+ text = /* @__PURE__ */ new Map();
3339
+ lineStarts = /* @__PURE__ */ new Map();
3340
+ /** File contents, or null if the file is binary or unreadable. */
3341
+ read(file) {
3342
+ if (this.text.has(file)) return this.text.get(file);
3343
+ let content = null;
3344
+ try {
3345
+ const buf = readFileSync5(join3(this.root, file));
3346
+ content = looksBinary(buf) ? null : buf.toString("utf8");
3347
+ } catch {
3348
+ content = null;
3349
+ }
3350
+ this.text.set(file, content);
3351
+ return content;
3352
+ }
3353
+ json(file) {
3354
+ const t = this.read(file);
3355
+ if (t === null) return null;
3356
+ try {
3357
+ return JSON.parse(t);
3358
+ } catch {
3359
+ return null;
3360
+ }
3361
+ }
3362
+ lines(file) {
3363
+ return (this.read(file) ?? "").split(/\r?\n/);
3364
+ }
3365
+ /** Converts a character offset to a 1-based line and column. */
3366
+ position(file, offset) {
3367
+ let starts = this.lineStarts.get(file);
3368
+ if (!starts) {
3369
+ starts = [0];
3370
+ const t = this.read(file) ?? "";
3371
+ for (let i = 0; i < t.length; i++) if (t.charCodeAt(i) === 10) starts.push(i + 1);
3372
+ this.lineStarts.set(file, starts);
3373
+ }
3374
+ let lo = 0;
3375
+ let hi = starts.length - 1;
3376
+ while (lo < hi) {
3377
+ const mid = lo + hi + 1 >> 1;
3378
+ if (starts[mid] <= offset) lo = mid;
3379
+ else hi = mid - 1;
3380
+ }
3381
+ return { line: lo + 1, column: offset - starts[lo] + 1 };
3382
+ }
3383
+ };
3384
+ function looksBinary(buf) {
3385
+ const n = Math.min(buf.length, 8e3);
3386
+ for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
3387
+ return false;
3388
+ }
3389
+
3390
+ // src/core/walk.ts
3391
+ import { readdirSync as readdirSync2, readFileSync as readFileSync6, statSync, existsSync as existsSync4 } from "fs";
3392
+ import { join as join4, relative, sep } from "path";
3393
+ import ignore from "ignore";
3394
+ var ALWAYS_SKIP = [
3395
+ ".git/",
3396
+ "node_modules/",
3397
+ ".next/",
3398
+ ".vercel/",
3399
+ ".turbo/",
3400
+ ".svelte-kit/",
3401
+ "dist/",
3402
+ "build/",
3403
+ "out/",
3404
+ "coverage/",
3405
+ ".cache/",
3406
+ // Python: virtual environments and tool caches hold other people's code, not the project's.
3407
+ ".venv/",
3408
+ "venv/",
3409
+ "__pycache__/",
3410
+ "site-packages/",
3411
+ ".tox/",
3412
+ ".mypy_cache/",
3413
+ ".pytest_cache/",
3414
+ ".ruff_cache/"
3415
+ ];
3416
+ var MAX_FILE_BYTES = 1e6;
3417
+ var toPosix = (p) => p.split(sep).join("/");
3418
+ function walk(root, extraIgnore = []) {
3419
+ const base = ignore().add(ALWAYS_SKIP).add(extraIgnore);
3420
+ const files = [];
3421
+ const skippedLarge = [];
3422
+ const visit = (dir, matchers) => {
3423
+ const local = readGitignore(dir);
3424
+ const relDir = toPosix(relative(root, dir));
3425
+ const here = local ? [...matchers, { prefix: relDir ? relDir + "/" : "", ig: local }] : matchers;
3426
+ let entries;
3427
+ try {
3428
+ entries = readdirSync2(dir, { withFileTypes: true });
3429
+ } catch {
3430
+ return;
3431
+ }
3432
+ entries.sort((a, b) => a.name.localeCompare(b.name));
3433
+ for (const entry of entries) {
3434
+ if (entry.isSymbolicLink()) continue;
3435
+ const abs = join4(dir, entry.name);
3436
+ const rel = toPosix(relative(root, abs));
3437
+ const test = entry.isDirectory() ? rel + "/" : rel;
3438
+ if (base.ignores(test)) continue;
3439
+ if (here.some(({ prefix, ig }) => test.startsWith(prefix) && ig.ignores(test.slice(prefix.length)))) {
3440
+ continue;
3441
+ }
3442
+ if (entry.isDirectory()) {
3443
+ visit(abs, here);
3444
+ } else if (entry.isFile()) {
3445
+ let size = 0;
3446
+ try {
3447
+ size = statSync(abs).size;
3448
+ } catch {
3449
+ continue;
3450
+ }
3451
+ if (size > MAX_FILE_BYTES) skippedLarge.push(rel);
3452
+ else files.push(rel);
3453
+ }
3454
+ }
3455
+ };
3456
+ visit(root, []);
3457
+ return { files, skippedLarge };
3458
+ }
3459
+ function excluder(extraIgnore = []) {
3460
+ const base = ignore().add(ALWAYS_SKIP).add(extraIgnore);
3461
+ return (rel) => base.ignores(rel);
3462
+ }
3463
+ function readGitignore(dir) {
3464
+ const p = join4(dir, ".gitignore");
3465
+ if (!existsSync4(p)) return null;
3466
+ try {
3467
+ return ignore().add(readFileSync6(p, "utf8"));
3468
+ } catch {
3469
+ return null;
3470
+ }
3471
+ }
3472
+
3473
+ // src/version.ts
3474
+ var VERSION = "0.1.0";
3475
+
3476
+ // src/scanner/detectors/exposure.ts
3477
+ var PUBLIC_PREFIX = /^(?:NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|GATSBY_|PUBLIC_)/;
3478
+ var NEVER_PUBLIC = /SECRET|PRIVATE|SERVICE_ROLE|PASSWORD|OPENAI|ANTHROPIC|CLAUDE|GEMINI|GROQ|MISTRAL|DATABASE_URL/i;
3479
+ var publicSecretNames = {
3480
+ id: "client-exposure/public-secret-name",
3481
+ skipReason: () => null,
3482
+ run: (ctx) => {
3483
+ const facts = [];
3484
+ for (const f of ctx.js) {
3485
+ const seen = /* @__PURE__ */ new Set();
3486
+ for (const r of envReads(f.ast)) {
3487
+ if (!PUBLIC_PREFIX.test(r.name) || !NEVER_PUBLIC.test(r.name) || seen.has(r.name)) continue;
3488
+ seen.add(r.name);
3489
+ facts.push({
3490
+ kind: "client_side_exposure",
3491
+ subject: "Browser-exposed secret name",
3492
+ claim: `A variable named like a secret uses a public prefix, so its value is shipped to browsers (${r.name}).`,
3493
+ attributes: { variable: r.name },
3494
+ confidence: "high",
3495
+ detector: "client-exposure/public-secret-name",
3496
+ key: `${f.file}#${r.name}`,
3497
+ locations: [{ file: f.file, line: ctx.project.position(f.file, r.offset).line }]
3498
+ });
3499
+ }
3500
+ }
3501
+ if (facts.length > 0) return facts;
3502
+ return [
3503
+ {
3504
+ kind: "client_side_exposure",
3505
+ subject: "Browser-exposed secrets",
3506
+ claim: "No secret-named variables with a public prefix were found in the scanned code.",
3507
+ claimType: "not-found",
3508
+ confidence: "medium",
3509
+ detector: "client-exposure/public-secret-name",
3510
+ key: "project"
3511
+ }
3512
+ ];
3513
+ }
3514
+ };
3515
+ var aiSdkInBrowser = {
3516
+ id: "client-exposure/ai-sdk-in-browser",
3517
+ skipReason: (ctx) => AI_PROVIDERS.some((p) => ctx.hasDep(...p.packages)) ? null : "no AI SDK in dependencies",
3518
+ run: (ctx) => ctx.js.flatMap((f) => {
3519
+ if (!f.isClient) return [];
3520
+ const spec = AI_PROVIDERS.find((p) => p.packages.some((pkg) => importsModule(f, pkg)));
3521
+ if (!spec) return [];
3522
+ return [
3523
+ {
3524
+ kind: "client_side_exposure",
3525
+ subject: `${spec.subject} SDK in browser code`,
3526
+ claim: `A browser component imports the ${spec.subject} SDK, which suggests a provider key may reach the browser.`,
3527
+ attributes: { sdk: spec.packages[0] },
3528
+ confidence: "medium",
3529
+ detector: "client-exposure/ai-sdk-in-browser",
3530
+ key: f.file,
3531
+ locations: [{ file: f.file }]
3532
+ }
3533
+ ];
3534
+ })
3535
+ };
3536
+ var exposureDetectors = [publicSecretNames, aiSdkInBrowser];
3537
+
3538
+ // src/scanner/detectors/logging.ts
3539
+ var LEVELS = /* @__PURE__ */ new Set(["log", "info", "debug", "warn", "error", "trace"]);
3540
+ function isLogger(chain) {
3541
+ if (!chain || chain.length < 2) return false;
3542
+ const level = chain[chain.length - 1];
3543
+ const root = chain[0];
3544
+ return LEVELS.has(level) && (root === "console" || /^(?:log|logger|\w*Logger|\w*Log)$/.test(root));
3545
+ }
3546
+ var requestBodyLogging = {
3547
+ id: "logging/request-body",
3548
+ skipReason: () => null,
3549
+ run: (ctx) => {
3550
+ const found = ctx.js.flatMap((f) => {
3551
+ const requestVars = requestVariables(f.ast, REQUEST_BODY);
3552
+ for (const c of calls(f.ast)) {
3553
+ if (!isLogger(c.chain) || c.node.type !== "CallExpression") continue;
3554
+ const logsRequest = c.node.arguments.some(
3555
+ (a) => isRequestData(a, REQUEST_BODY) || [...dynamicRoots(a)].some((r) => requestVars.has(r)) || containsRequestData(a)
3556
+ );
3557
+ if (!logsRequest) continue;
3558
+ return [
3559
+ {
3560
+ kind: "logging",
3561
+ subject: "Server logs",
3562
+ claim: "A request body is written to the logs, so it may include user content.",
3563
+ attributes: { logsUserContent: true },
3564
+ confidence: "medium",
3565
+ detector: "logging/request-body",
3566
+ key: f.file,
3567
+ locations: [{ file: f.file, ...c.line ? { line: c.line } : {} }]
3568
+ }
3569
+ ];
3570
+ }
3571
+ return [];
3572
+ });
3573
+ for (const f of ctx.py) {
3574
+ const hit = loggedRequestBody(f.lines, f.calls, f.funcs);
3575
+ if (!hit) continue;
3576
+ found.push({
3577
+ kind: "logging",
3578
+ subject: "Server logs",
3579
+ claim: "A request body is written to the logs, so it may include user content.",
3580
+ attributes: { logsUserContent: true },
3581
+ confidence: "medium",
3582
+ detector: "logging/request-body",
3583
+ key: f.file,
3584
+ locations: [{ file: f.file, line: hit.line }]
3585
+ });
3586
+ }
3587
+ if (found.length > 0 || ctx.hasUnanalysedCode) return found;
3588
+ return [
3589
+ {
3590
+ kind: "logging",
3591
+ subject: "Request-body logging",
3592
+ claim: "No logging of request bodies was found in the scanned code.",
3593
+ claimType: "not-found",
3594
+ confidence: "medium",
3595
+ detector: "logging/request-body",
3596
+ key: "project"
3597
+ }
3598
+ ];
3599
+ }
3600
+ };
3601
+ function containsRequestData(node) {
3602
+ if (isRequestData(node, REQUEST_BODY)) return true;
3603
+ if (node.type === "ObjectExpression") return node.properties.some((p) => p.type === "ObjectProperty" && containsRequestData(p.value));
3604
+ if (node.type === "ArrayExpression") return node.elements.some((e) => e !== null && containsRequestData(e));
3605
+ if (node.type === "TemplateLiteral") return node.expressions.some((e) => containsRequestData(e));
3606
+ return false;
3607
+ }
3608
+ var loggingDetectors = [requestBodyLogging];
3609
+
3610
+ // src/scanner/detectors/secrets.ts
3611
+ var PUBLIC_PREFIX2 = /^(?:NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|GATSBY_|PUBLIC_)/;
3612
+ var SECRET_NAME2 = /KEY|SECRET|TOKEN|PASSWORD|PASSPHRASE|DSN|DATABASE_URL|CONNECTION_STRING/i;
3613
+ var LOCKFILE = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/;
3614
+ var envUsage = {
3615
+ id: "secrets/env-usage",
3616
+ skipReason: () => null,
3617
+ run: (ctx) => {
3618
+ const names = /* @__PURE__ */ new Set();
3619
+ const locations = [];
3620
+ for (const f of ctx.js) {
3621
+ const text = ctx.project.read(f.file);
3622
+ if (text === null) continue;
3623
+ for (const r of envReads(f.ast)) {
3624
+ if (PUBLIC_PREFIX2.test(r.name) || !SECRET_NAME2.test(r.name)) continue;
3625
+ names.add(r.name);
3626
+ locations.push({ file: f.file, line: ctx.project.position(f.file, r.offset).line });
3627
+ }
3628
+ }
3629
+ for (const f of ctx.py) {
3630
+ for (const r of [...envReadsPy(f.lines), ...settingsFields(f.lines)]) {
3631
+ if (PUBLIC_PREFIX2.test(r.name) || !isSecretName(r.name)) continue;
3632
+ names.add(r.name);
3633
+ locations.push({ file: f.file, line: r.line });
3634
+ }
3635
+ }
3636
+ if (names.size === 0) return [];
3637
+ return [
3638
+ {
3639
+ kind: "secret_handling",
3640
+ subject: "Environment variables",
3641
+ claim: "Keys and secrets are read from environment variables.",
3642
+ attributes: { mechanism: "env", keyNames: [...names] },
3643
+ confidence: "high",
3644
+ detector: "secrets/env-usage",
3645
+ key: "env",
3646
+ locations: locations.slice(0, 5)
3647
+ }
3648
+ ];
3649
+ }
3650
+ };
3651
+ var hardcoded = {
3652
+ id: "secrets/hardcoded-patterns",
3653
+ skipReason: () => null,
3654
+ run: (ctx) => {
3655
+ const facts = [];
3656
+ const guard = createGuard();
3657
+ for (const file of ctx.project.files) {
3658
+ if (LOCKFILE.test(file)) continue;
3659
+ const text = ctx.project.read(file);
3660
+ if (text === null) continue;
3661
+ const leaks = findLeaks(text, guard);
3662
+ if (leaks.length === 0) continue;
3663
+ const kinds = [...new Set(leaks.map((l) => l.kind))].sort();
3664
+ facts.push({
3665
+ kind: "secret_handling",
3666
+ subject: "Hard-coded keys",
3667
+ claim: `A value shaped like a credential (${kinds.join(", ")}) was found in the scanned files. The value is not recorded.`,
3668
+ attributes: { patternKinds: kinds },
3669
+ confidence: "medium",
3670
+ detector: "secrets/hardcoded-patterns",
3671
+ key: file,
3672
+ locations: [{ file, line: ctx.project.position(file, leaks[0].index).line }]
3673
+ });
3674
+ }
3675
+ if (facts.length > 0) return facts;
3676
+ return [
3677
+ {
3678
+ kind: "secret_handling",
3679
+ subject: "Hard-coded keys",
3680
+ claim: "No hard-coded keys matching known credential formats were found in the scanned files.",
3681
+ claimType: "not-found",
3682
+ attributes: { patternsChecked: 8 },
3683
+ confidence: "medium",
3684
+ detector: "secrets/hardcoded-patterns",
3685
+ key: "project"
3686
+ }
3687
+ ];
3688
+ }
3689
+ };
3690
+ var secretDetectors = [envUsage, hardcoded];
3691
+
3692
+ // src/scanner/detectors/index.ts
3693
+ var DETECTORS = [
3694
+ ...aiDetectors,
3695
+ ...serviceDetectors,
3696
+ ...authDetectors,
3697
+ ...storeDetectors,
3698
+ ...secretDetectors,
3699
+ ...loggingDetectors,
3700
+ ...exposureDetectors
3701
+ ];
3702
+
3703
+ // src/scanner/project-info.ts
3704
+ import { basename } from "path";
3705
+ var LANGUAGE_BY_EXT = [
3706
+ [/\.(?:tsx?|mts|cts)$/, "typescript"],
3707
+ [/\.(?:jsx?|mjs|cjs)$/, "javascript"],
3708
+ [/\.html?$/, "html"],
3709
+ [/\.py$/, "python"]
3710
+ ];
3711
+ var FRAMEWORKS = [
3712
+ ["next", "nextjs"],
3713
+ ["react", "react"],
3714
+ ["express", "express"],
3715
+ ["fastify", "fastify"],
3716
+ ["hono", "hono"],
3717
+ ["@supabase/supabase-js", "supabase-js"],
3718
+ ["stripe", "stripe"],
3719
+ ["firebase", "firebase"]
3720
+ ];
3721
+ function projectInfo(ctx, root) {
3722
+ const languages = /* @__PURE__ */ new Set();
3723
+ for (const file of ctx.project.files) {
3724
+ const hit = LANGUAGE_BY_EXT.find(([re]) => re.test(file));
3725
+ if (hit) languages.add(hit[1]);
3726
+ }
3727
+ const frameworks = FRAMEWORKS.filter(([dep]) => ctx.hasDep(dep)).map(([, name2]) => name2);
3728
+ for (const name2 of ["fastapi", "flask", "django"]) {
3729
+ if (ctx.hasPyImport(name2) && !frameworks.includes(name2)) frameworks.push(name2);
3730
+ }
3731
+ const pkg = ctx.project.json("package.json");
3732
+ const name = typeof pkg?.name === "string" && pkg.name.length > 0 ? pkg.name : basename(root) || "project";
3733
+ return { name, languages: [...languages], frameworks };
3734
+ }
3735
+
3736
+ // src/scanner/unknowns.ts
3737
+ var slug = (s) => s.toLowerCase().replace(/\(.*?\)/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
3738
+ function unknownsFor(all, unanalysed2 = false) {
3739
+ const facts = all.filter((f) => f.claimType !== "not-found");
3740
+ const out = /* @__PURE__ */ new Map();
3741
+ const add = (u) => out.set(u.key, u);
3742
+ const providers = [...new Set(facts.filter((f) => f.kind === "ai_provider").map((f) => f.subject))];
3743
+ for (const subject of providers) {
3744
+ add({
3745
+ key: `${slug(subject)}-data-use`,
3746
+ topic: "AI provider data use",
3747
+ question: `Is ${subject}'s data-retention or training opt-out configured on your account?`,
3748
+ why: "This is an account setting at the provider, not something the code shows.",
3749
+ related: [
3750
+ { kind: "ai_provider", subject },
3751
+ { kind: "data_flow", subject }
3752
+ ]
3753
+ });
3754
+ }
3755
+ const stores = [...new Set(facts.filter((f) => f.kind === "data_store").map((f) => f.subject))];
3756
+ for (const subject of stores) {
3757
+ const isSupabase = subject.startsWith("Supabase");
3758
+ const isFirebase = subject.startsWith("Firebase");
3759
+ add({
3760
+ key: isSupabase ? "supabase-region" : isFirebase ? "firebase-region" : `${slug(subject)}-hosting`,
3761
+ topic: isSupabase || isFirebase ? "Data region" : "Database hosting",
3762
+ question: isSupabase ? "In which region is the Supabase project hosted?" : isFirebase ? "In which location is the Firebase project hosted?" : `Where is the ${subject} database hosted, and by whom?`,
3763
+ why: "Hosting is set up outside the code, so a scan can't see it.",
3764
+ related: [{ kind: "data_store", subject }]
3765
+ });
3766
+ }
3767
+ if (stores.length > 0) {
3768
+ add({
3769
+ key: "retention-deletion",
3770
+ topic: "Retention",
3771
+ question: "How long is user data kept, and what happens to it when a user or customer asks for it to be deleted?",
3772
+ why: "No retention or deletion rules can be read from the code alone.",
3773
+ related: stores.map((subject) => ({ kind: "data_store", subject }))
3774
+ });
3775
+ }
3776
+ const hasBackendSignals = facts.some((f) => f.kind === "data_store" || f.kind === "ai_provider" || f.kind === "auth");
3777
+ if (!hasBackendSignals && !unanalysed2) {
3778
+ add({
3779
+ key: "hosting-location",
3780
+ topic: "Hosting",
3781
+ question: "Where is the site hosted, and by whom?",
3782
+ why: "Hosting is configured outside the code, so a scan can't see it."
3783
+ });
3784
+ }
3785
+ return [...out.values()];
3786
+ }
3787
+
3788
+ // src/scanner/seaworthy.ts
3789
+ import { z as z3 } from "zod";
3790
+ var SeaworthyReport = z3.object({
3791
+ findings: z3.array(
3792
+ z3.object({
3793
+ ruleId: z3.string().regex(/^SW-[A-Z]\d{2}$/),
3794
+ severity: z3.enum(["critical", "high", "medium", "low"]),
3795
+ file: z3.string().optional(),
3796
+ line: z3.number().int().positive().optional()
3797
+ })
3798
+ )
3799
+ });
3800
+ var RELATED_KINDS = {
3801
+ D: ["data_store"],
3802
+ S: ["secret_handling", "client_side_exposure"],
3803
+ A: ["auth"],
3804
+ P: ["third_party_service"],
3805
+ L: ["ai_provider", "data_flow"]
3806
+ };
3807
+ function readSeaworthyReport(json, facts) {
3808
+ const report = SeaworthyReport.parse(json);
3809
+ return report.findings.map((f) => {
3810
+ const kinds = RELATED_KINDS[f.ruleId[3]] ?? [];
3811
+ const related = [...new Map(facts.filter((x) => kinds.includes(x.kind)).map((x) => [`${x.kind}|${x.subject}`, { kind: x.kind, subject: x.subject }])).values()];
3812
+ return {
3813
+ ruleId: f.ruleId,
3814
+ severity: f.severity,
3815
+ ...f.file ? { location: { file: f.file, ...f.line ? { line: f.line } : {} } } : {},
3816
+ related
3817
+ };
3818
+ });
3819
+ }
3820
+
3821
+ // src/scanner/scan.ts
3822
+ var ABSENCES = [
3823
+ { kind: "ai_provider", subject: "No AI provider found", detector: "ai-provider/none-found", claim: "No AI provider SDK from the supported list was found in the project's dependencies or code." },
3824
+ { kind: "data_store", subject: "No database found", detector: "data-store/none-found", claim: "No database client or migrations from the supported list were found in the project." },
3825
+ { kind: "auth", subject: "No sign-in found", detector: "auth/none-found", claim: "No sign-in library or provider call from the supported list was found in the project." }
3826
+ ];
3827
+ function absences(found) {
3828
+ return ABSENCES.filter((a) => !found.some((f) => f.kind === a.kind && f.claimType !== "not-found")).map((a) => ({
3829
+ kind: a.kind,
3830
+ subject: a.subject,
3831
+ claim: a.claim,
3832
+ claimType: "not-found",
3833
+ confidence: "medium",
3834
+ detector: a.detector,
3835
+ key: "project"
3836
+ }));
3837
+ }
3838
+ var MAX_LOCATIONS = 10;
3839
+ function mergeFacts(facts) {
3840
+ const groups = /* @__PURE__ */ new Map();
3841
+ for (const f of facts) {
3842
+ const attrs = JSON.stringify(Object.entries(f.attributes ?? {}).sort(([a], [b]) => a.localeCompare(b)));
3843
+ const id = [f.kind, f.subject, f.detector, f.claim, f.claimType ?? "observed", f.confidence, attrs].join("|");
3844
+ groups.set(id, [...groups.get(id) ?? [], f]);
3845
+ }
3846
+ return [...groups.values()].map((group) => {
3847
+ if (group.length === 1) return group[0];
3848
+ const sorted = [...group].sort((a, b) => (a.key ?? "").localeCompare(b.key ?? ""));
3849
+ const locations = sorted.flatMap((f) => f.locations ?? []);
3850
+ return { ...sorted[0], locations: locations.slice(0, MAX_LOCATIONS) };
3851
+ });
3852
+ }
3853
+ function unanalysedQuestion(unsupported) {
3854
+ return {
3855
+ key: "unanalysed-code",
3856
+ topic: "Code not analysed",
3857
+ question: `This project also contains ${describeUnsupported(unsupported)}, which Soundings doesn't read. What AI services, databases, sign-in methods and logging do those parts use?`,
3858
+ why: "Soundings reads JavaScript and TypeScript only, so what the other code does is not in this scan."
3859
+ };
3860
+ }
3861
+ var SPECIFIC_SQL = /* @__PURE__ */ new Set(["PostgreSQL", "MySQL", "Supabase Postgres"]);
3862
+ function dropRedundant(facts) {
3863
+ const stores = facts.filter((f) => f.kind === "data_store");
3864
+ return facts.filter((f) => {
3865
+ if (f.kind !== "data_store") return true;
3866
+ if (f.detector === "data-store/connection-string") return !stores.some((o) => o.subject === f.subject && o.detector !== f.detector);
3867
+ if (f.subject === "SQL database (SQLAlchemy)") return !stores.some((o) => SPECIFIC_SQL.has(o.subject));
3868
+ return true;
3869
+ });
3870
+ }
3871
+ function scan(opts) {
3872
+ const started = Date.now();
3873
+ const { files, skippedLarge } = walk(opts.root, opts.ignore ?? []);
3874
+ const project = new ProjectFiles(opts.root, files, excluder(opts.ignore ?? []));
3875
+ const ctx = buildContext(project);
3876
+ const detectorsRun = [];
3877
+ const detectorsSkipped = [];
3878
+ const facts = [];
3879
+ for (const d of DETECTORS) {
3880
+ const reason = d.skipReason(ctx);
3881
+ if (reason) {
3882
+ detectorsSkipped.push({ detector: d.id, reason });
3883
+ continue;
3884
+ }
3885
+ detectorsRun.push(d.id);
3886
+ facts.push(...d.run(ctx));
3887
+ }
3888
+ const unsupported = unsupportedCode(files);
3889
+ const unanalysed2 = isSignificant(unsupported);
3890
+ if (!unanalysed2) {
3891
+ for (const a of absences(facts)) {
3892
+ detectorsRun.push(a.detector);
3893
+ facts.push(a);
3894
+ }
3895
+ }
3896
+ const merged = dropRedundant(mergeFacts(facts));
3897
+ const findings = opts.seaworthy === void 0 ? [] : readSeaworthyReport(opts.seaworthy, merged);
3898
+ const info = projectInfo(ctx, opts.root);
3899
+ const evidence = buildEvidence({
3900
+ generatedAt: (opts.now ?? /* @__PURE__ */ new Date()).toISOString(),
3901
+ tool: { name: "soundings", version: VERSION },
3902
+ project: info,
3903
+ scan: { filesScanned: files.length, filesSkipped: skippedLarge.length, detectorsRun, detectorsSkipped, unsupported },
3904
+ facts: merged,
3905
+ unknowns: [...unknownsFor(merged, unanalysed2), ...unanalysed2 ? [unanalysedQuestion(unsupported)] : []],
3906
+ findings
3907
+ });
3908
+ assertNoLeaks(JSON.stringify(evidence), createGuard(loadEnvValues(opts.root)), "evidence file");
3909
+ return { evidence, ms: Date.now() - started };
3910
+ }
3911
+
3912
+ // src/licensing/config.ts
3913
+ var PURCHASE_URL = "https://buy.polar.sh/polar_cl_upd3jUUgQJxylkHMhzMvLW9sEFACty8IJ4iV70cfrnM";
3914
+ var PORTAL_URL = "https://polar.sh/dynamo-maritime/portal";
3915
+ var SUPPORT_EMAIL = "support@dynamomaritime.com";
3916
+ var PLACEHOLDER = "00000000-0000-0000-0000-000000000000";
3917
+ var POLAR_SERVERS = {
3918
+ production: {
3919
+ apiBase: "https://api.polar.sh",
3920
+ // The company's Polar organisation, public in the Seaworthy source. No benefit is listed yet,
3921
+ // so licensing stays switched off until a Soundings benefit ID is added.
3922
+ organizationId: "a4a6a28a-20f3-4b1f-9211-7eccab46ff92",
3923
+ benefits: { "ec38b34e-d103-432a-b90d-f1759aeeffe6": "pro" }
3924
+ },
3925
+ sandbox: {
3926
+ apiBase: "https://sandbox-api.polar.sh",
3927
+ organizationId: PLACEHOLDER,
3928
+ benefits: {}
3929
+ }
3930
+ };
3931
+ function polarSettings(env = process.env) {
3932
+ return env.SOUNDINGS_POLAR_SERVER === "sandbox" ? POLAR_SERVERS.sandbox : POLAR_SERVERS.production;
3933
+ }
3934
+ function isConfigured(s) {
3935
+ return s.organizationId !== PLACEHOLDER && Object.keys(s.benefits).length > 0;
3936
+ }
3937
+ var purchasingOpen = (s = polarSettings()) => PURCHASE_URL !== null && isConfigured(s);
3938
+ var renewHint = () => PURCHASE_URL ? `Renew at ${PURCHASE_URL}` : `Contact ${SUPPORT_EMAIL}`;
3939
+ var OFFLINE_GRACE_DAYS = 14;
3940
+ var REVALIDATE_AFTER_HOURS = 24;
3941
+ var LICENCE_TIMEOUT_MS = 8e3;
3942
+
3943
+ // src/licensing/provider.ts
3944
+ var ok = (value) => ({ ok: true, value });
3945
+ var fail = (reason, detail) => ({ ok: false, reason, detail });
3946
+
3947
+ // src/licensing/polar.ts
3948
+ var PolarProvider = class {
3949
+ constructor(settings, fetchImpl = fetch) {
3950
+ this.settings = settings;
3951
+ this.fetchImpl = fetchImpl;
3952
+ }
3953
+ settings;
3954
+ fetchImpl;
3955
+ name = "Polar";
3956
+ async activate(key, machineLabel) {
3957
+ if (!isConfigured(this.settings)) return notConfigured();
3958
+ const res = await this.post("activate", {
3959
+ key,
3960
+ organization_id: this.settings.organizationId,
3961
+ label: machineLabel.slice(0, 200)
3962
+ });
3963
+ if ("error" in res) return res.error;
3964
+ if (res.status === 200 && res.body) {
3965
+ const activationId = str(res.body.id);
3966
+ const lk = res.body.license_key ?? {};
3967
+ if (!activationId) return fail("unreachable", "Polar returned an activation with no ID.");
3968
+ const v = await this.validate(key, activationId);
3969
+ if (!v.ok) {
3970
+ if (v.reason === "not-soundings") await this.deactivate(key, activationId);
3971
+ return v;
3972
+ }
3973
+ return ok({
3974
+ activationId,
3975
+ tier: v.value.tier,
3976
+ displayKey: v.value.displayKey,
3977
+ machineLimit: typeof lk.limit_activations === "number" ? lk.limit_activations : null
3978
+ });
3979
+ }
3980
+ if (res.status === 403) {
3981
+ const detail = detailOf(res.body);
3982
+ return /limit/i.test(detail) ? fail("machine-limit", detail) : fail("revoked", detail || "Polar refused this key: it is revoked, disabled or expired.");
3983
+ }
3984
+ if (res.status === 404 || res.status === 422) return fail("invalid", detailOf(res.body) || "Polar doesn't recognise this key.");
3985
+ return unexpected(res);
3986
+ }
3987
+ async validate(key, activationId) {
3988
+ if (!isConfigured(this.settings)) return notConfigured();
3989
+ const body = { key, organization_id: this.settings.organizationId };
3990
+ if (activationId) body.activation_id = activationId;
3991
+ const res = await this.post("validate", body);
3992
+ if ("error" in res) return res.error;
3993
+ if (res.status === 200 && res.body) {
3994
+ const b = res.body;
3995
+ if (str(b.organization_id) !== this.settings.organizationId) {
3996
+ return fail("not-soundings", "This key belongs to a different Polar organisation.");
3997
+ }
3998
+ const tier = this.settings.benefits[str(b.benefit_id) ?? ""];
3999
+ if (!tier) return fail("not-soundings", "This key is for a product that isn't a Soundings plan.");
4000
+ if (b.status !== void 0 && b.status !== "granted") {
4001
+ return fail("revoked", `Polar reports this key as ${String(b.status)}.`);
4002
+ }
4003
+ const expiresAt = str(b.expires_at);
4004
+ if (expiresAt && Date.parse(expiresAt) < Date.now()) return fail("expired", `This key expired on ${expiresAt.slice(0, 10)}.`);
4005
+ return ok({ tier, displayKey: str(b.display_key) ?? "****", expiresAt });
4006
+ }
4007
+ if (res.status === 404) {
4008
+ if (activationId) {
4009
+ const keyOnly = await this.validate(key, null);
4010
+ if (keyOnly.ok) return fail("activation-removed", "This machine's activation was removed.");
4011
+ if (keyOnly.reason === "unreachable") return keyOnly;
4012
+ }
4013
+ return fail("revoked", "Polar no longer accepts this key: the subscription may have ended, or the key was revoked.");
4014
+ }
4015
+ if (res.status === 422) return fail("invalid", "That doesn't look like a valid licence key.");
4016
+ return unexpected(res);
4017
+ }
4018
+ async deactivate(key, activationId) {
4019
+ if (!isConfigured(this.settings)) return notConfigured();
4020
+ const res = await this.post("deactivate", {
4021
+ key,
4022
+ organization_id: this.settings.organizationId,
4023
+ activation_id: activationId
4024
+ });
4025
+ if ("error" in res) return res.error;
4026
+ if (res.status === 204 || res.status === 200 || res.status === 404) return ok(null);
4027
+ return unexpected(res);
4028
+ }
4029
+ async post(action, body) {
4030
+ const url = `${this.settings.apiBase}/v1/customer-portal/license-keys/${action}`;
4031
+ try {
4032
+ const r = await this.fetchImpl(url, {
4033
+ method: "POST",
4034
+ headers: { "content-type": "application/json", accept: "application/json", "user-agent": `soundings-cli/${VERSION}` },
4035
+ body: JSON.stringify(body),
4036
+ signal: AbortSignal.timeout(LICENCE_TIMEOUT_MS)
4037
+ });
4038
+ let parsed = null;
4039
+ if (r.status !== 204) {
4040
+ try {
4041
+ const j = await r.json();
4042
+ parsed = typeof j === "object" && j !== null ? j : null;
4043
+ } catch {
4044
+ parsed = null;
4045
+ }
4046
+ }
4047
+ return { status: r.status, body: parsed };
4048
+ } catch (err) {
4049
+ const e = err;
4050
+ const why = e.name === "TimeoutError" || e.name === "AbortError" ? "timed out" : "could not be reached";
4051
+ return { error: fail("unreachable", `The licence server ${why}.`) };
4052
+ }
4053
+ }
4054
+ };
4055
+ var str = (v) => typeof v === "string" && v.length > 0 ? v : null;
4056
+ function detailOf(body) {
4057
+ const d = body?.detail;
4058
+ return typeof d === "string" ? d : "";
4059
+ }
4060
+ function notConfigured() {
4061
+ return fail("not-configured", "Licensing isn't set up in this build of Soundings yet.");
4062
+ }
4063
+ function unexpected(res) {
4064
+ return fail("unreachable", `The licence server returned an unexpected response (HTTP ${res.status}).`);
4065
+ }
4066
+
4067
+ // src/licensing/store.ts
4068
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync7, rmSync, writeFileSync as writeFileSync2 } from "fs";
4069
+ import { homedir } from "os";
4070
+ import { join as join5 } from "path";
4071
+ import { createHash as createHash2 } from "crypto";
4072
+ function userConfigDir(env = process.env, platform = process.platform) {
4073
+ if (env.SOUNDINGS_CONFIG_DIR) return env.SOUNDINGS_CONFIG_DIR;
4074
+ if (platform === "win32") return join5(env.APPDATA ?? join5(homedir(), "AppData", "Roaming"), "soundings");
4075
+ if (platform === "darwin") return join5(homedir(), "Library", "Application Support", "soundings");
4076
+ return join5(env.XDG_CONFIG_HOME ?? join5(homedir(), ".config"), "soundings");
4077
+ }
4078
+ var LicenceStore = class {
4079
+ constructor(dir) {
4080
+ this.dir = dir;
4081
+ }
4082
+ dir;
4083
+ get path() {
4084
+ return join5(this.dir, "licence.json");
4085
+ }
4086
+ load() {
4087
+ return readJson(this.path, (r) => r.version === 1 && typeof r.key === "string");
4088
+ }
4089
+ save(record) {
4090
+ writeJson(this.dir, this.path, record);
4091
+ }
4092
+ clear() {
4093
+ rmSync(this.path, { force: true });
4094
+ }
4095
+ /** Validation cache for a key supplied through SOUNDINGS_LICENCE (CI). Keyed by a hash, not the key. */
4096
+ loadEnvCache(key) {
4097
+ const all = readJson(this.envCachePath, () => true) ?? {};
4098
+ const rec = all[hashKey(key)];
4099
+ return rec ? { ...rec, key } : null;
4100
+ }
4101
+ saveEnvCache(record) {
4102
+ const all = readJson(this.envCachePath, () => true) ?? {};
4103
+ all[hashKey(record.key)] = { ...record, key: "" };
4104
+ writeJson(this.dir, this.envCachePath, all);
4105
+ }
4106
+ get envCachePath() {
4107
+ return join5(this.dir, "env-licence-cache.json");
4108
+ }
4109
+ };
4110
+ var hashKey = (key) => createHash2("sha256").update(key).digest("hex").slice(0, 32);
4111
+ function readJson(path, valid) {
4112
+ if (!existsSync5(path)) return null;
4113
+ try {
4114
+ const v = JSON.parse(readFileSync7(path, "utf8"));
4115
+ return v && typeof v === "object" && valid(v) ? v : null;
4116
+ } catch {
4117
+ return null;
4118
+ }
4119
+ }
4120
+ function writeJson(dir, path, value) {
4121
+ mkdirSync(dir, { recursive: true, mode: 448 });
4122
+ writeFileSync2(path, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
4123
+ }
4124
+
4125
+ // src/cli/licence.ts
4126
+ import pc4 from "picocolors";
4127
+
4128
+ // src/core/entitlements.ts
4129
+ var TIER_INFO = {
4130
+ free: { name: "Free", machines: 0, features: [] },
4131
+ pro: { name: "Pro", machines: 3, features: ["answers", "questionnaire-import", "documents", "exports"] }
4132
+ };
4133
+ var FEATURE_LABELS = {
4134
+ answers: "Answering the question bank as a document",
4135
+ "questionnaire-import": "Filling in a client's questionnaire",
4136
+ documents: "Privacy notice, subprocessor list, DPIA draft, AI-use statement and trust page",
4137
+ exports: "Exports to Word and HTML"
4138
+ };
4139
+ var FREE_SUMMARY = "scanning, the report, the questions and verifying any text";
4140
+ function hasFeature(tier, feature) {
4141
+ return TIER_INFO[tier].features.includes(feature);
4142
+ }
4143
+
4144
+ // src/licensing/licence.ts
4145
+ import { hostname } from "os";
4146
+ var DAY = 864e5;
4147
+ var HOUR = 36e5;
4148
+ function defaultMachineLabel() {
4149
+ const platform = { win32: "Windows", darwin: "macOS", linux: "Linux" }[process.platform] ?? process.platform;
4150
+ return `${hostname() || "unknown machine"} (${platform})`;
4151
+ }
4152
+ async function resolveLicence(opts) {
4153
+ const env = opts.env ?? process.env;
4154
+ const now = opts.now ?? /* @__PURE__ */ new Date();
4155
+ const envKey = env.SOUNDINGS_LICENCE?.trim();
4156
+ let source;
4157
+ let record;
4158
+ if (envKey) {
4159
+ source = "env";
4160
+ record = opts.store.loadEnvCache(envKey) ?? {
4161
+ version: 1,
4162
+ key: envKey,
4163
+ activationId: null,
4164
+ machineLabel: "CI",
4165
+ tier: "pro",
4166
+ displayKey: maskKey(envKey),
4167
+ lastValidatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
4168
+ };
4169
+ record.activationId = env.SOUNDINGS_ACTIVATION_ID?.trim() || null;
4170
+ if (record.problem && !opts.forceOnline && !isFresh(record, now)) delete record.problem;
4171
+ } else {
4172
+ source = "file";
4173
+ record = opts.store.load();
4174
+ if (!record) return { tier: "free", licensedTier: "free", state: "none", source: "none", checkedOnline: false };
4175
+ }
4176
+ const base = {
4177
+ licensedTier: record.tier,
4178
+ source,
4179
+ displayKey: record.displayKey,
4180
+ machineLabel: record.machineLabel,
4181
+ lastValidatedAt: validTime(record.lastValidatedAt, now) ? record.lastValidatedAt : void 0
4182
+ };
4183
+ const save = (r) => source === "env" ? opts.store.saveEnvCache(r) : opts.store.save(r);
4184
+ if (record.problem && !opts.forceOnline) {
4185
+ return { ...base, tier: "free", state: "ended", message: problemMessage(record.problem), checkedOnline: false };
4186
+ }
4187
+ if (!opts.forceOnline && isFresh(record, now)) {
4188
+ return { ...base, tier: record.tier, state: "active", checkedOnline: false };
4189
+ }
4190
+ if (opts.offline) return graceOrLapsed(record, base, now, false, "You're offline (--offline).");
4191
+ const v = await opts.provider.validate(record.key, record.activationId);
4192
+ if (v.ok) {
4193
+ const updated = {
4194
+ ...record,
4195
+ tier: v.value.tier,
4196
+ displayKey: v.value.displayKey,
4197
+ lastValidatedAt: now.toISOString()
4198
+ };
4199
+ delete updated.problem;
4200
+ save(updated);
4201
+ return {
4202
+ ...base,
4203
+ licensedTier: updated.tier,
4204
+ displayKey: updated.displayKey,
4205
+ lastValidatedAt: updated.lastValidatedAt,
4206
+ tier: updated.tier,
4207
+ state: "active",
4208
+ checkedOnline: true
4209
+ };
4210
+ }
4211
+ if (v.reason === "unreachable") return graceOrLapsed(record, base, now, true, v.detail);
4212
+ if (v.reason === "not-configured") {
4213
+ return { ...base, tier: "free", state: "not-configured", message: v.detail, checkedOnline: false };
4214
+ }
4215
+ const problem = toProblem(v.reason);
4216
+ save({ ...record, problem });
4217
+ return { ...base, tier: "free", state: "ended", message: problemMessage(problem), checkedOnline: true };
4218
+ }
4219
+ function graceOrLapsed(record, base, now, checkedOnline, why) {
4220
+ const last = validTime(record.lastValidatedAt, now) ? Date.parse(record.lastValidatedAt) : 0;
4221
+ const graceEnds = last + OFFLINE_GRACE_DAYS * DAY;
4222
+ if (last > 0 && now.getTime() <= graceEnds) {
4223
+ const until = new Date(graceEnds).toISOString();
4224
+ return {
4225
+ ...base,
4226
+ tier: record.tier,
4227
+ state: "grace",
4228
+ graceEndsAt: until,
4229
+ message: `${why} Your licence keeps working offline until ${until.slice(0, 10)}.`,
4230
+ checkedOnline
4231
+ };
4232
+ }
4233
+ return {
4234
+ ...base,
4235
+ tier: "free",
4236
+ state: "lapsed",
4237
+ message: last > 0 ? `${why} The licence hasn't been confirmed for over ${OFFLINE_GRACE_DAYS} days, so paid features are paused until Soundings can check it online.` : `${why} Paid features will turn on once Soundings can confirm your licence online.`,
4238
+ checkedOnline
4239
+ };
4240
+ }
4241
+ function isFresh(record, now) {
4242
+ if (!validTime(record.lastValidatedAt, now)) return false;
4243
+ return now.getTime() - Date.parse(record.lastValidatedAt) < REVALIDATE_AFTER_HOURS * HOUR;
4244
+ }
4245
+ function validTime(iso, now) {
4246
+ const t = Date.parse(iso);
4247
+ return Number.isFinite(t) && t > 0 && t <= now.getTime() + 5 * 6e4;
4248
+ }
4249
+ function toProblem(reason) {
4250
+ if (reason === "expired") return "expired";
4251
+ if (reason === "activation-removed") return "activation-removed";
4252
+ if (reason === "not-soundings" || reason === "invalid") return "not-soundings";
4253
+ return "revoked";
4254
+ }
4255
+ function problemMessage(problem) {
4256
+ switch (problem) {
4257
+ case "revoked":
4258
+ return `Your Soundings licence is no longer active; the subscription may have ended. ${renewHint()}, then run soundings login <key>.`;
4259
+ case "expired":
4260
+ return `Your Soundings licence has expired. ${renewHint()}, then run soundings login <key>.`;
4261
+ case "activation-removed":
4262
+ return `This machine was removed from your licence. Run soundings login <key> to add it back (your key: ${PORTAL_URL}).`;
4263
+ case "not-soundings":
4264
+ return "That key isn't a Soundings licence. Check you copied the right one, then run soundings login <key>.";
4265
+ }
4266
+ }
4267
+ function maskKey(key) {
4268
+ return key.length <= 6 ? "****" : `****-${key.slice(-6).toUpperCase()}`;
4269
+ }
4270
+
4271
+ // src/cli/open.ts
4272
+ import { spawn } from "child_process";
4273
+ function openUrl(url, platform = process.platform) {
4274
+ if (!/^https:\/\/[A-Za-z0-9.-]+\/[A-Za-z0-9_\-./?=&%~]*$/.test(url)) return false;
4275
+ const [cmd, args] = platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
4276
+ try {
4277
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
4278
+ child.on("error", () => {
4279
+ });
4280
+ child.unref();
4281
+ return true;
4282
+ } catch {
4283
+ return false;
4284
+ }
4285
+ }
4286
+
4287
+ // src/cli/licence.ts
4288
+ var EXIT_NEEDS_PLAN = 3;
4289
+ function maybeOpen(url, ctx) {
4290
+ if (!ctx.interactive || ctx.noOpen) return false;
4291
+ return (ctx.openUrl ?? openUrl)(url);
4292
+ }
4293
+ async function requireFeature(feature, command, ctx) {
4294
+ const s = await resolveLicence({ provider: ctx.provider, store: ctx.store, env: ctx.env, now: ctx.now(), offline: ctx.offline });
4295
+ if (hasFeature(s.tier, feature)) return null;
4296
+ const lines = ["", ` ${pc4.cyan("\u2726")} ${pc4.bold(`soundings ${command}`)} is part of Soundings Pro: ${FEATURE_LABELS[feature].toLowerCase()}.`];
4297
+ if (s.message) lines.push(` ${s.message}`);
4298
+ if (s.state === "none" || s.state === "not-configured") {
4299
+ lines.push(
4300
+ purchasingOpen() ? ` Buy a plan: ${pc4.cyan(PURCHASE_URL)} then: ${pc4.cyan("soundings login <key>")}` : " Paid plans aren't open for purchase yet."
4301
+ );
4302
+ }
4303
+ lines.push(pc4.dim(` Free, with no licence needed: ${FREE_SUMMARY}.`), "");
4304
+ ctx.err(lines.join("\n"));
4305
+ return EXIT_NEEDS_PLAN;
4306
+ }
4307
+ function buy(ctx) {
4308
+ const out = ["", ` ${pc4.bold("Soundings plans")}`, ""];
4309
+ out.push(` ${pc4.bold("Free".padEnd(8))}${FREE_SUMMARY}`);
4310
+ out.push(` ${pc4.bold("Pro".padEnd(8))}+ ${Object.values(FEATURE_LABELS).map((l) => l[0].toLowerCase() + l.slice(1)).join(", ")}`);
4311
+ out.push("");
4312
+ if (!purchasingOpen()) {
4313
+ out.push(" Paid plans aren't open for purchase yet. Free features work as normal.");
4314
+ out.push(pc4.dim(` Questions: ${SUPPORT_EMAIL}`), "");
4315
+ ctx.out(out.join("\n"));
4316
+ return 0;
4317
+ }
4318
+ const current = ctx.env.SOUNDINGS_LICENCE?.trim() ? null : ctx.store.load();
4319
+ if (current && !current.problem) {
4320
+ out.push(pc4.dim(` You're logged in on this machine with Soundings ${TIER_INFO[current.tier].name} (${current.displayKey}).`), "");
4321
+ }
4322
+ const opened = maybeOpen(PURCHASE_URL, ctx);
4323
+ out.push(
4324
+ opened ? ` ${pc4.green("\u2714")} Opened the checkout in your browser. If it didn't appear: ${pc4.cyan(PURCHASE_URL)}` : ` ${pc4.bold("Buy:")} ${pc4.cyan(PURCHASE_URL)}`
4325
+ );
4326
+ out.push(pc4.dim(" Payment, tax, invoices and cancelling are handled by Polar, our merchant of record."), "");
4327
+ out.push(` ${pc4.bold("After paying")}`);
4328
+ out.push(` 1. Get your key: ${pc4.cyan(PORTAL_URL)}`);
4329
+ out.push(pc4.dim(" Enter the email you bought with; the key is under your plan."));
4330
+ out.push(` 2. ${pc4.cyan("soundings login <key>")}`);
4331
+ out.push(pc4.dim(" In CI, add the key as a secret called SOUNDINGS_LICENCE instead."), "");
4332
+ ctx.out(out.join("\n"));
4333
+ return 0;
4334
+ }
4335
+ async function login(keyArg, ctx) {
4336
+ const key = keyArg?.trim();
4337
+ if (!key || /\s/.test(key) || key.length > 200) {
4338
+ const opened = !key && purchasingOpen() && maybeOpen(PORTAL_URL, ctx);
4339
+ ctx.err(
4340
+ [
4341
+ "",
4342
+ ` ${pc4.bold("Usage:")} soundings login <licence-key>`,
4343
+ "",
4344
+ ` ${pc4.bold("Your key")} is in the customer portal: ${pc4.cyan(PORTAL_URL)}${opened ? pc4.dim(" (opened in your browser)") : ""}`,
4345
+ " Enter the email you bought with, type the code Polar emails you, and copy the key",
4346
+ " shown under your plan. Then run soundings login <key>.",
4347
+ ""
4348
+ ].join("\n")
4349
+ );
4350
+ return 2;
4351
+ }
4352
+ if (ctx.offline) {
4353
+ ctx.err(pc4.red(" Logging in needs one online check. Run it without --offline."));
4354
+ return 2;
4355
+ }
4356
+ const label = (ctx.label?.trim() || defaultMachineLabel()).slice(0, 200);
4357
+ const existing = ctx.store.load();
4358
+ if (existing && existing.key !== key && existing.activationId) await ctx.provider.deactivate(existing.key, existing.activationId);
4359
+ if (existing && existing.key === key && existing.activationId && !existing.problem) {
4360
+ const v = await ctx.provider.validate(key, existing.activationId);
4361
+ if (v.ok) {
4362
+ ctx.store.save({ ...existing, tier: v.value.tier, displayKey: v.value.displayKey, lastValidatedAt: ctx.now().toISOString() });
4363
+ ctx.out(`
4364
+ ${pc4.green("\u2714")} Already logged in: ${pc4.bold(`Soundings ${TIER_INFO[v.value.tier].name}`)} on ${existing.machineLabel}.
4365
+ `);
4366
+ return 0;
4367
+ }
4368
+ }
4369
+ const a = await ctx.provider.activate(key, label);
4370
+ if (!a.ok) {
4371
+ ctx.err(`
4372
+ ${pc4.red("\u2716")} ${loginFailure(a.reason, a.detail)}
4373
+ `);
4374
+ return 1;
4375
+ }
4376
+ ctx.store.save({
4377
+ version: 1,
4378
+ key,
4379
+ activationId: a.value.activationId,
4380
+ machineLabel: label,
4381
+ tier: a.value.tier,
4382
+ displayKey: a.value.displayKey,
4383
+ lastValidatedAt: ctx.now().toISOString()
4384
+ });
4385
+ const info = TIER_INFO[a.value.tier];
4386
+ ctx.out(
4387
+ [
4388
+ "",
4389
+ ` ${pc4.green("\u2714")} Logged in: ${pc4.bold(`Soundings ${info.name}`)} on ${label}.`,
4390
+ ` Unlocked: ${info.features.map((f) => FEATURE_LABELS[f]).join("; ")}.`,
4391
+ pc4.dim(` This key works on up to ${a.value.machineLimit ?? info.machines} machines. Saved in ${ctx.store.path}`),
4392
+ ctx.env.SOUNDINGS_LICENCE ? pc4.yellow(" Note: SOUNDINGS_LICENCE is set in this shell and takes priority over this login.") : "",
4393
+ ""
4394
+ ].filter((l) => l !== "").join("\n") + "\n"
4395
+ );
4396
+ return 0;
4397
+ }
4398
+ function loginFailure(reason, detail) {
4399
+ const renew = PURCHASE_URL ? `Renew at ${PURCHASE_URL}.` : `Contact ${SUPPORT_EMAIL}.`;
4400
+ switch (reason) {
4401
+ case "invalid":
4402
+ return `That key wasn't recognised. Check you copied all of it from the customer portal: ${PORTAL_URL}`;
4403
+ case "revoked":
4404
+ return `That key is no longer active; the subscription may have ended. ${renew}`;
4405
+ case "expired":
4406
+ return `That key has expired. ${renew}`;
4407
+ case "machine-limit":
4408
+ return `That key is already in use on as many machines as your plan allows. Run soundings logout on one you no longer use, or remove it in the customer portal: ${PORTAL_URL}`;
4409
+ case "not-soundings":
4410
+ return "That key isn't a Soundings licence. Check you copied the right one.";
4411
+ case "unreachable":
4412
+ return `${detail} Check your connection and try again. Free features keep working in the meantime.`;
4413
+ case "not-configured":
4414
+ return `${detail} Free features work as normal.`;
4415
+ default:
4416
+ return detail;
4417
+ }
4418
+ }
4419
+ async function logout(ctx) {
4420
+ const existing = ctx.store.load();
4421
+ if (!existing) {
4422
+ ctx.out("\n You're not logged in on this machine. Soundings is running on the Free plan.\n");
4423
+ return 0;
4424
+ }
4425
+ let freed = true;
4426
+ if (existing.activationId && !ctx.offline) freed = (await ctx.provider.deactivate(existing.key, existing.activationId)).ok;
4427
+ else if (existing.activationId) freed = false;
4428
+ ctx.store.clear();
4429
+ ctx.out(
4430
+ `
4431
+ ${pc4.green("\u2714")} Logged out. Soundings is back on the Free plan on this machine.` + (freed ? pc4.dim(`
4432
+ This machine's slot on ${existing.displayKey} is free again.`) : pc4.yellow(`
4433
+ Couldn't reach the licence server to free this machine's slot. Remove "${existing.machineLabel}" in the customer portal if you need it: ${PORTAL_URL}`)) + "\n"
4434
+ );
4435
+ return 0;
4436
+ }
4437
+ async function status(ctx) {
4438
+ const s = await resolveLicence({
4439
+ provider: ctx.provider,
4440
+ store: ctx.store,
4441
+ env: ctx.env,
4442
+ now: ctx.now(),
4443
+ offline: ctx.offline,
4444
+ forceOnline: !ctx.offline
4445
+ });
4446
+ const out = [""];
4447
+ if (s.state === "none") {
4448
+ out.push(` ${pc4.bold("Soundings Free")} ${pc4.dim(`\xB7 ${FREE_SUMMARY}`)}`);
4449
+ out.push(` Pro adds ${Object.values(FEATURE_LABELS).map((l) => l[0].toLowerCase() + l.slice(1)).join(", ")}.`);
4450
+ out.push(purchasingOpen() ? ` ${pc4.cyan("soundings buy")} to open the checkout, then ${pc4.cyan("soundings login <key>")}.` : " Paid plans aren't open for purchase yet.");
4451
+ out.push("");
4452
+ ctx.out(out.join("\n"));
4453
+ return 0;
4454
+ }
4455
+ const stateText = {
4456
+ active: pc4.green("active"),
4457
+ grace: pc4.yellow("offline grace period"),
4458
+ lapsed: pc4.yellow("paused: needs an online check"),
4459
+ ended: pc4.red("not active"),
4460
+ "not-configured": pc4.yellow("licensing not set up in this build")
4461
+ };
4462
+ const lic = s.licensedTier;
4463
+ const confirmed = Boolean(s.lastValidatedAt);
4464
+ const planName = confirmed ? `Soundings ${TIER_INFO[lic].name}` : "Soundings licence (not confirmed yet)";
4465
+ out.push(` ${pc4.bold(planName)} ${pc4.dim("\xB7")} ${stateText[s.state] ?? s.state}`);
4466
+ out.push(` ${pc4.dim("Key".padEnd(10))}${s.displayKey ?? maskKey("")}${s.source === "env" ? pc4.dim(" (from SOUNDINGS_LICENCE)") : ""}`);
4467
+ if (s.source === "file") out.push(` ${pc4.dim("Machine".padEnd(10))}${s.machineLabel}`);
4468
+ if (s.lastValidatedAt) out.push(` ${pc4.dim("Checked".padEnd(10))}${s.lastValidatedAt.slice(0, 16).replace("T", " ")} UTC${s.checkedOnline ? pc4.dim(" (just now)") : ""}`);
4469
+ if (s.graceEndsAt) out.push(` ${pc4.dim("Offline".padEnd(10))}keeps working until ${s.graceEndsAt.slice(0, 10)}`);
4470
+ if (confirmed) out.push(` ${pc4.dim("Plan".padEnd(10))}${TIER_INFO[lic].features.map((f) => FEATURE_LABELS[f]).join("; ")}`);
4471
+ if (confirmed && s.tier !== lic) out.push(` ${pc4.dim("Now".padEnd(10))}running as Free until this is sorted`);
4472
+ if (s.message) out.push("", ` ${s.message}`);
4473
+ out.push("");
4474
+ ctx.out(out.join("\n"));
4475
+ return 0;
4476
+ }
4477
+
4478
+ // src/cli/main.ts
4479
+ var HELP = `
4480
+ ${pc5.bold("soundings")}: evidence-backed answers to security questionnaires, run locally.
4481
+
4482
+ ${pc5.bold("Usage")}
4483
+ soundings [scan] [path] Scan a project (default: current folder) and save its evidence
4484
+ soundings questions Ask only what the code can't answer, and save your answers
4485
+ soundings verify <file> Check any text against the evidence: every statement needs a source
4486
+
4487
+ ${pc5.bold("Pro")}
4488
+ soundings answers Answer the standard question bank from evidence and your answers
4489
+ soundings answer <file.csv> Fill in a client questionnaire from the bank (never guesses)
4490
+ soundings document <type> Privacy notice, subprocessors, dpia, ai-use or trust-page
4491
+ (run with no type to list them)
4492
+
4493
+ ${pc5.bold("Plans")}
4494
+ soundings buy See the plans and open the checkout
4495
+ soundings login <key> Turn on your licence on this machine
4496
+ soundings logout Turn it off and free this machine's slot
4497
+ soundings status Show your plan and licence state
4498
+
4499
+ ${pc5.bold("Options")}
4500
+ --output <file> Where to save the evidence or the answers document
4501
+ (scan: ./soundings-evidence.json; answers: print to screen)
4502
+ --no-write Scan: print the report but don't save the evidence file
4503
+ --format terminal|json Scan report format (default: terminal)
4504
+ --format markdown|html|docx Answers and documents format (default: markdown; html and
4505
+ docx need --output; to make a PDF, print the HTML to PDF).
4506
+ Answers also accept json.
4507
+ --seaworthy <file> Scan: include findings from a Seaworthy JSON report
4508
+ --config <file> Scan: config file (default: <path>/soundings.config.json)
4509
+ --evidence <file> Evidence file (default: ./soundings-evidence.json)
4510
+ --answers <file> Answers file (default: ./soundings-answers.json)
4511
+ --list Questions: show what is left, without asking
4512
+ --documents Questions: also ask what the documents need
4513
+ --set <key>=<value> Questions: record an answer (repeatable). Keys: UQ-\u2026,
4514
+ profile.\u2026 or override.<question-id> to replace what the scan says
4515
+ --no-locations Answers: leave file paths out of the sources
4516
+ --strict Verify: treat warnings as failures
4517
+ --offline Never call the licence server (uses the saved check)
4518
+ --no-open Don't open links in the browser
4519
+ -h, --help -v, --version
4520
+
4521
+ ${pc5.bold("Exit codes")} 0 done \xB7 1 verify found problems \xB7 2 error \xB7 3 needs a paid plan
4522
+ ${pc5.dim("Free commands make no network calls. In CI, set SOUNDINGS_LICENCE to your key instead of logging in.")}
4523
+ ${pc5.dim("Soundings produces drafts, not legal advice.")}
4524
+ `;
4525
+ var COMMANDS = /* @__PURE__ */ new Set(["scan", "questions", "answers", "answer", "document", "verify", "buy", "login", "logout", "status"]);
4526
+ async function run2(argv, deps) {
4527
+ let parsed;
4528
+ try {
4529
+ parsed = parseArgs({
4530
+ args: argv,
4531
+ allowPositionals: true,
4532
+ options: {
4533
+ output: { type: "string" },
4534
+ "no-write": { type: "boolean" },
4535
+ format: { type: "string" },
4536
+ seaworthy: { type: "string" },
4537
+ config: { type: "string" },
4538
+ evidence: { type: "string" },
4539
+ answers: { type: "string" },
4540
+ list: { type: "boolean" },
4541
+ documents: { type: "boolean" },
4542
+ set: { type: "string", multiple: true },
4543
+ "no-locations": { type: "boolean" },
4544
+ strict: { type: "boolean" },
4545
+ offline: { type: "boolean" },
4546
+ "no-open": { type: "boolean" },
4547
+ label: { type: "string" },
4548
+ help: { type: "boolean", short: "h" },
4549
+ version: { type: "boolean", short: "v" }
4550
+ }
4551
+ });
4552
+ } catch (err) {
4553
+ deps.err(`${err.message}
4554
+ ${HELP}`);
4555
+ return 2;
4556
+ }
4557
+ const { values, positionals } = parsed;
4558
+ if (values.version) {
4559
+ deps.out(VERSION);
4560
+ return 0;
4561
+ }
4562
+ if (values.help) {
4563
+ deps.out(HELP);
4564
+ return 0;
4565
+ }
4566
+ const [first, ...rest] = positionals;
4567
+ const command = first !== void 0 && COMMANDS.has(first) ? first : "scan";
4568
+ const target = command === first ? rest[0] : first;
4569
+ try {
4570
+ if (command === "questions") return await runQuestionsCommand(values, deps);
4571
+ if (["buy", "login", "logout", "status", "answers", "answer", "document"].includes(command)) {
4572
+ const lic = licenceCtx(values, deps);
4573
+ if (command === "buy") return buy(lic);
4574
+ if (command === "login") return await login(target, lic);
4575
+ if (command === "logout") return await logout(lic);
4576
+ if (command === "status") return await status(lic);
4577
+ if (command === "document" && !target) return runDocumentList(deps);
4578
+ const feature = command === "answers" ? "answers" : command === "document" ? "documents" : "questionnaire-import";
4579
+ const gate = await requireFeature(feature, command, lic);
4580
+ if (gate !== null) return gate;
4581
+ const fmt = values.format ?? "markdown";
4582
+ if (fmt === "html" || fmt === "docx") {
4583
+ const exportGate = await requireFeature("exports", `${command} --format ${fmt}`, lic);
4584
+ if (exportGate !== null) return exportGate;
4585
+ }
4586
+ if (command === "answers") return runAnswersCommand(values, deps);
4587
+ if (command === "document") return runDocumentCommand(values, target, deps);
4588
+ return runAnswerCommand(values, target, deps);
4589
+ }
4590
+ if (command === "verify") return runVerifyCommand(values, target, deps);
4591
+ return runScanCommand(values, target, deps);
4592
+ } catch (err) {
4593
+ if (err instanceof RedactionError) {
4594
+ deps.err(`Stopped: ${err.message}. Nothing was written.`);
4595
+ } else if (err instanceof ConfigError || err instanceof QuestionsError || err instanceof AnswersError || err instanceof ImportError) {
4596
+ deps.err(err.message);
4597
+ } else {
4598
+ deps.err(`Something went wrong: ${err instanceof Error ? err.message : String(err)}`);
4599
+ }
4600
+ return 2;
4601
+ }
4602
+ }
4603
+ function licenceCtx(values, deps) {
4604
+ return {
4605
+ out: deps.out,
4606
+ err: deps.err,
4607
+ env: deps.env,
4608
+ now: deps.now,
4609
+ provider: deps.provider ?? new PolarProvider(polarSettings(deps.env)),
4610
+ store: new LicenceStore(userConfigDir(deps.env)),
4611
+ offline: Boolean(values.offline),
4612
+ ...values.label ? { label: values.label } : {},
4613
+ noOpen: Boolean(values["no-open"]),
4614
+ interactive: Boolean(deps.interactive),
4615
+ ...deps.openUrl ? { openUrl: deps.openUrl } : {}
4616
+ };
4617
+ }
4618
+ function runScanCommand(values, target, deps) {
4619
+ const format = values.format ?? "terminal";
4620
+ if (format !== "terminal" && format !== "json") {
4621
+ deps.err(`Unknown format "${format}". Use terminal or json.`);
4622
+ return 2;
4623
+ }
4624
+ const root = resolve(deps.cwd, target ?? ".");
4625
+ if (!existsSync6(root) || !statSync2(root).isDirectory()) {
4626
+ deps.err(`Not a folder: ${root}`);
4627
+ return 2;
4628
+ }
4629
+ const config = loadConfig(root, values.config ? resolve(deps.cwd, values.config) : void 0);
4630
+ const seaworthy = values.seaworthy ? JSON.parse(readFileSync8(resolve(deps.cwd, values.seaworthy), "utf8")) : void 0;
4631
+ const { evidence, ms } = scan({ root, ignore: config.ignore, seaworthy, now: deps.now() });
4632
+ let savedTo = null;
4633
+ if (!values["no-write"]) {
4634
+ const path = resolve(deps.cwd, values.output ?? "soundings-evidence.json");
4635
+ writeFileSync3(path, JSON.stringify(evidence, null, 2) + "\n");
4636
+ savedTo = relative2(deps.cwd, path) || path;
4637
+ }
4638
+ deps.out(format === "json" ? JSON.stringify(evidence, null, 2) : renderTerminal(evidence, ms, savedTo));
4639
+ return 0;
4640
+ }
4641
+ var evidencePath = (v, deps) => resolve(deps.cwd, v.evidence ?? "soundings-evidence.json");
4642
+ var answersPath = (v, deps) => resolve(deps.cwd, v.answers ?? "soundings-answers.json");
4643
+ async function runQuestionsCommand(values, deps) {
4644
+ const set = [];
4645
+ for (const item2 of values.set ?? []) {
4646
+ const eq = item2.indexOf("=");
4647
+ if (eq < 1) {
4648
+ deps.err(`--set needs key=value, got "${item2}".`);
4649
+ return 2;
4650
+ }
4651
+ set.push([item2.slice(0, eq).trim(), item2.slice(eq + 1)]);
4652
+ }
4653
+ const aPath = answersPath(values, deps);
4654
+ const outcome = await runQuestions({
4655
+ evidencePath: evidencePath(values, deps),
4656
+ answersPath: aPath,
4657
+ now: deps.now(),
4658
+ set,
4659
+ documents: Boolean(values.documents),
4660
+ ...values.list || !deps.ask ? {} : { ask: deps.ask }
4661
+ });
4662
+ for (const r of outcome.rejected) deps.err(`Skipped ${r.key}: ${r.reason}`);
4663
+ deps.out(renderQuestionsSummary(outcome.state, relative2(deps.cwd, aPath) || aPath, outcome.saved));
4664
+ return 0;
4665
+ }
4666
+ function runAnswersCommand(values, deps) {
4667
+ const format = values.format ?? "markdown";
4668
+ if (format !== "json" && !isExportFormat(format)) {
4669
+ deps.err(`Unknown format "${format}". Use markdown, html, docx or json.`);
4670
+ return 2;
4671
+ }
4672
+ const evidence = loadEvidence(evidencePath(values, deps));
4673
+ const answers = loadAnswers(answersPath(values, deps));
4674
+ const results = answerAll(evidence, answers);
4675
+ const markdown = renderQuestionnaireMarkdown(results, evidence, answers, { project: evidence.project.name, locations: !values["no-locations"] });
4676
+ const output = format === "json" ? JSON.stringify({ project: evidence.project.name, results }, null, 2) : renderExport(markdown, format, { title: `Security and data handling answers: ${evidence.project.name}`, created: evidence.generatedAt });
4677
+ return emit(output, values, deps, "answers document", `Saved ${results.length} answers to`);
4678
+ }
4679
+ function emit(output, values, deps, label, savedPrefix) {
4680
+ if (typeof output === "string") assertNoLeaks(output, createGuard(loadEnvValues(deps.cwd)), label);
4681
+ else assertNoLeaks(output.toString("latin1"), createGuard(loadEnvValues(deps.cwd)), label);
4682
+ if (values.output) {
4683
+ const path = resolve(deps.cwd, values.output);
4684
+ writeFileSync3(path, output);
4685
+ deps.out(`${savedPrefix} ${relative2(deps.cwd, path) || path}.`);
4686
+ return 0;
4687
+ }
4688
+ if (typeof output !== "string") {
4689
+ deps.err("Word files can't be printed to the screen. Add --output <file.docx>.");
4690
+ return 2;
4691
+ }
4692
+ deps.out(output);
4693
+ return 0;
4694
+ }
4695
+ function runDocumentList(deps) {
4696
+ const lines = ["", " Documents (each built only from the scan and your answers):", ""];
4697
+ for (const d of DOCUMENTS) lines.push(` ${d.id.padEnd(15)}${d.title}: ${d.about}`);
4698
+ lines.push("", " soundings document <type> [--format markdown|html|docx] [--output <file>]", "");
4699
+ deps.out(lines.join("\n"));
4700
+ return 0;
4701
+ }
4702
+ function runDocumentCommand(values, type, deps) {
4703
+ const aliases = { privacy: "privacy-notice", subprocessor: "subprocessors", ai: "ai-use", trust: "trust-page" };
4704
+ const id = aliases[type] ?? type;
4705
+ if (!isDocumentId(id)) {
4706
+ deps.err(`Unknown document "${type}". Choose one of: ${DOCUMENTS.map((d) => d.id).join(", ")}.`);
4707
+ return 2;
4708
+ }
4709
+ const format = values.format ?? "markdown";
4710
+ if (!isExportFormat(format)) {
4711
+ deps.err(`Unknown format "${format}". Use ${EXPORT_FORMATS.join(", ")}.`);
4712
+ return 2;
4713
+ }
4714
+ const evidence = loadEvidence(evidencePath(values, deps));
4715
+ const answers = loadAnswers(answersPath(values, deps));
4716
+ const built = buildDocument(id, evidence, answers, { locations: !values["no-locations"] });
4717
+ const output = renderExport(built.markdown, format, { title: `${built.title}: ${evidence.project.name}`, created: evidence.generatedAt });
4718
+ const code = emit(output, values, deps, `${built.title.toLowerCase()}`, `Saved the ${built.title.toLowerCase()} to`);
4719
+ if (code === 0 && built.needs.length > 0 && values.output) {
4720
+ deps.out(`${built.needs.length} item${built.needs.length === 1 ? "" : "s"} still need your input; they are listed under "Open items". Run: soundings questions --documents`);
4721
+ }
4722
+ return code;
4723
+ }
4724
+ function runVerifyCommand(values, file, deps) {
4725
+ if (!file) {
4726
+ deps.err("Which file? Usage: soundings verify <file>");
4727
+ return 2;
4728
+ }
4729
+ const format = values.format ?? "terminal";
4730
+ if (format !== "terminal" && format !== "json") {
4731
+ deps.err(`Unknown format "${format}". Use terminal or json.`);
4732
+ return 2;
4733
+ }
4734
+ const path = resolve(deps.cwd, file);
4735
+ if (!existsSync6(path)) {
4736
+ deps.err(`File not found: ${path}`);
4737
+ return 2;
4738
+ }
4739
+ const evidence = loadEvidence(evidencePath(values, deps));
4740
+ const answers = loadAnswers(answersPath(values, deps));
4741
+ const report = verifyText(readFileSync8(path, "utf8"), evidence, answers);
4742
+ deps.out(format === "json" ? JSON.stringify(report, null, 2) : renderVerify(report, relative2(deps.cwd, path) || file));
4743
+ const failed = !report.ok || Boolean(values.strict) && report.issues.length > 0;
4744
+ return failed ? 1 : 0;
4745
+ }
4746
+ function runAnswerCommand(values, file, deps) {
4747
+ if (!file) {
4748
+ deps.err("Which questionnaire? Usage: soundings answer <file.csv>");
4749
+ return 2;
4750
+ }
4751
+ const path = resolve(deps.cwd, file);
4752
+ if (!existsSync6(path)) {
4753
+ deps.err(`File not found: ${path}`);
4754
+ return 2;
4755
+ }
4756
+ if (/\.xlsx?$/i.test(path)) {
4757
+ deps.err("Excel files aren't supported yet. In Excel, use File > Save As > CSV UTF-8, then run this again on the CSV.");
4758
+ return 2;
4759
+ }
4760
+ const evidence = loadEvidence(evidencePath(values, deps));
4761
+ const answers = loadAnswers(answersPath(values, deps));
4762
+ const result = fillQuestionnaire(readFileSync8(path, "utf8"), evidence, answers);
4763
+ assertNoLeaks(result.csv, createGuard(loadEnvValues(deps.cwd)), "filled questionnaire");
4764
+ const outPath = resolve(deps.cwd, values.output ?? file.replace(/\.csv$/i, "") + ".answered.csv");
4765
+ if (outPath === path) {
4766
+ deps.err("The output file would overwrite the questionnaire. Choose another with --output.");
4767
+ return 2;
4768
+ }
4769
+ writeFileSync3(outPath, result.csv);
4770
+ deps.out(renderFill(result, relative2(deps.cwd, outPath) || outPath));
4771
+ return 0;
4772
+ }
4773
+
4774
+ // src/cli/index.ts
4775
+ function terminalAsker() {
4776
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
4777
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
4778
+ let closed = false;
4779
+ rl.on("close", () => closed = true);
4780
+ return {
4781
+ close: () => rl.close(),
4782
+ ask: async (pending, index, total) => {
4783
+ if (closed) return null;
4784
+ try {
4785
+ return await rl.question(`
4786
+ (${index + 1}/${total}) ${pending.prompt}
4787
+ Press Enter to skip. > `);
4788
+ } catch {
4789
+ return null;
4790
+ }
4791
+ }
4792
+ };
4793
+ }
4794
+ var asker = terminalAsker();
4795
+ try {
4796
+ process.exitCode = await run2(process.argv.slice(2), {
4797
+ out: (s) => console.log(s),
4798
+ err: (s) => console.error(s),
4799
+ env: process.env,
4800
+ cwd: process.cwd(),
4801
+ now: () => /* @__PURE__ */ new Date(),
4802
+ ...asker ? { ask: asker.ask } : {},
4803
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY && !process.env.CI)
4804
+ });
4805
+ } finally {
4806
+ asker?.close();
4807
+ }