@consent-kit/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/index.js ADDED
@@ -0,0 +1,877 @@
1
+ import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { resolve, join, dirname } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { compile, guardManifest, contentSecurityPolicy, receiptManifest, policySnapshot, releasedPolicy, describeCspDeviations, consentScriptTag } from '@consent-kit/compiler';
5
+ export { consentEmbed, consentScriptTag, contentSecurityPolicy, describeCspDeviations, guardManifest } from '@consent-kit/compiler';
6
+ import { describePresets, parseRegistry } from '@consent-kit/presets';
7
+ export { parseRegistry } from '@consent-kit/presets';
8
+ import { createHash } from 'node:crypto';
9
+ import { subjectRequestOutputs, generateDocuments } from '@consent-kit/documents';
10
+ import { renderInlineGuard } from '@consent-kit/guard';
11
+ export { renderInlineGuard } from '@consent-kit/guard';
12
+ import { renderStorageModule } from '@consent-kit/storage';
13
+ import { diffRegistry, nextRevision } from '@consent-kit/schema';
14
+
15
+ // src/cli.ts
16
+ var GUARD_MODES = ["throw", "record", "report", "enforce"];
17
+ var DEFAULT_GUARD_MODE = "enforce";
18
+ var DEFAULT_OUT_DIR = "src/consent.gen";
19
+ var INLINE_GUARD_FILE = "guard.inline.js";
20
+ var HEADERS_FILE = "_headers";
21
+ var STORAGE_MODULE_FILE = "storage.gen.ts";
22
+ var RECEIPTS_MANIFEST_FILE = "receipts.manifest.gen.json";
23
+ var SUBJECT_REQUESTS_MANIFEST_FILE = "subject-requests.manifest.gen.json";
24
+ function buildOutputs(registry, options) {
25
+ const compiled = compile(registry, { revision: options.revision });
26
+ const guard = renderInlineGuard({
27
+ manifest: guardManifest(registry),
28
+ mode: options.guardMode,
29
+ reportUrl: options.reportUrl
30
+ });
31
+ const guardFile = `${guard}
32
+ `;
33
+ const csp = contentSecurityPolicy(registry, {
34
+ inlineScriptHashes: [createHash("sha256").update(guardFile, "utf8").digest("base64")]
35
+ });
36
+ const files = {
37
+ ...compiled,
38
+ "csp.json": `${JSON.stringify(csp, null, 2)}
39
+ `,
40
+ [INLINE_GUARD_FILE]: guardFile,
41
+ [STORAGE_MODULE_FILE]: renderStorageModule(registry),
42
+ [HEADERS_FILE]: headersFile(csp)
43
+ };
44
+ const manifest = receiptManifest(registry, { revision: options.revision, history: options.history });
45
+ if (manifest !== void 0) files[RECEIPTS_MANIFEST_FILE] = `${JSON.stringify(manifest, null, 2)}
46
+ `;
47
+ const requests = subjectRequestOutputs(registry, { policyHash: policySnapshot(registry).hash, phraseOverrides: options.phraseOverrides });
48
+ if (requests !== void 0) {
49
+ Object.assign(files, requests.files);
50
+ files[SUBJECT_REQUESTS_MANIFEST_FILE] = `${JSON.stringify(requests.manifest, null, 2)}
51
+ `;
52
+ }
53
+ return Object.fromEntries(Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
54
+ }
55
+ function headersFile(csp) {
56
+ const policy = typeof csp === "string" ? { headerName: "Content-Security-Policy", header: csp, reportingEndpoints: void 0 } : csp;
57
+ const lines = [` ${policy.headerName}: ${policy.header}`];
58
+ if (policy.reportingEndpoints !== void 0) lines.push(` Reporting-Endpoints: ${policy.reportingEndpoints}`);
59
+ return `/*
60
+ ${lines.join("\n")}
61
+ `;
62
+ }
63
+ function planWrites(outputs, existing) {
64
+ return Object.entries(outputs).map(([name, contents]) => {
65
+ const current = existing(name);
66
+ return { name, status: current === null ? "created" : current === contents ? "unchanged" : "updated" };
67
+ });
68
+ }
69
+ var EMPTY_REVIEW = { overrides: {}, acknowledged: [] };
70
+ var INITIAL_REVISION = 0;
71
+ function analyse(input) {
72
+ const { lock, review } = input;
73
+ const report = {
74
+ reportVersion: 1,
75
+ ok: false,
76
+ registry: input.registryPath,
77
+ lock: {
78
+ path: input.lockPath,
79
+ exists: lock !== null,
80
+ revision: lock?.revision ?? null,
81
+ policyHash: lock?.policyHash ?? null,
82
+ releasedAt: lock?.releasedAt ?? null
83
+ },
84
+ firstRelease: lock === null,
85
+ policyHash: null,
86
+ unreleasedChanges: false,
87
+ revision: { released: lock?.revision ?? null, pending: null },
88
+ reconsentRequired: false,
89
+ validationErrors: [],
90
+ changes: [],
91
+ purposesNeedingBump: [],
92
+ missingVersionBumps: [],
93
+ unnecessaryBumps: [],
94
+ versionIssues: [],
95
+ rejectedOverrides: [],
96
+ errors: [],
97
+ warnings: [],
98
+ presets: { applied: [], overrides: [] },
99
+ csp: null,
100
+ receipts: null,
101
+ consentPurposes: []
102
+ };
103
+ if (!input.parsed.ok) {
104
+ report.validationErrors = input.parsed.errors;
105
+ return { report };
106
+ }
107
+ const registry = input.parsed.registry;
108
+ const { policy, hash } = policySnapshot(registry);
109
+ report.policyHash = hash;
110
+ const { level, deviations } = contentSecurityPolicy(registry);
111
+ report.csp = { level, deviations };
112
+ report.receipts = registry.receipts ?? null;
113
+ report.consentPurposes = registry.purposes.filter((purpose) => purpose.basis === "consent").map((purpose) => purpose.id);
114
+ if (registry.receipts !== void 0 && "optOut" in registry.receipts) {
115
+ report.warnings.push({
116
+ code: "receipts/opted-out",
117
+ message: `No consent receipts are kept: the registry opts out, so nothing proves what a visitor decided beyond the consent cookie in their own browser. Reason given: ${registry.receipts.optOut.reason} Declare "receipts: { endpoint: <path or https URL> }" once the site can store them.`
118
+ });
119
+ }
120
+ if (input.parsed.presets) {
121
+ const { applied, overrides, warnings } = input.parsed.presets;
122
+ report.presets = { applied, overrides };
123
+ for (const warning of warnings) report.warnings.push({ code: warning.code, message: warning.message });
124
+ }
125
+ if (lock === null) {
126
+ report.unreleasedChanges = true;
127
+ report.reconsentRequired = true;
128
+ report.revision.pending = INITIAL_REVISION + 1;
129
+ report.ok = true;
130
+ return { report, registry, policy, diff: null };
131
+ }
132
+ const diff2 = diffRegistry(lock.registry, registry, review.overrides);
133
+ const acknowledged = new Set(review.acknowledged);
134
+ report.unreleasedChanges = hash !== lock.policyHash;
135
+ report.revision.pending = nextRevision(lock.revision, diff2);
136
+ report.reconsentRequired = diff2.reconsentRequired;
137
+ report.changes = diff2.changes.map((change) => ({
138
+ ...change,
139
+ acknowledgement: acknowledgementOf(change, acknowledged)
140
+ }));
141
+ report.purposesNeedingBump = diff2.purposesNeedingBump;
142
+ report.missingVersionBumps = diff2.missingVersionBumps;
143
+ report.unnecessaryBumps = diff2.unnecessaryBumps;
144
+ report.versionIssues = diff2.versionIssues;
145
+ report.rejectedOverrides = diff2.rejectedOverrides;
146
+ for (const issue of diff2.versionIssues) {
147
+ const finding = { code: `version/${issue.code}`, message: issue.message, purposeId: issue.purposeId };
148
+ (issue.severity === "error" ? report.errors : report.warnings).push(finding);
149
+ }
150
+ for (const change of report.changes) {
151
+ if (change.acknowledgement !== "missing") continue;
152
+ report.errors.push(
153
+ change.classification === "needs_review" ? {
154
+ code: "review/unacknowledged",
155
+ key: change.key,
156
+ message: `"${change.key}" needs a human review and blocks the build. Once reviewed, add its key to "acknowledged" in privacy.review.json.`
157
+ } : {
158
+ code: "confirmation/unacknowledged",
159
+ key: change.key,
160
+ message: `"${change.key}" is presumed not material but nobody confirmed it. Add its key to "acknowledged" in privacy.review.json, or escalate it under "overrides".`
161
+ }
162
+ );
163
+ }
164
+ for (const rejected of diff2.rejectedOverrides) {
165
+ report.warnings.push({ code: `override/${rejected.reason}`, key: rejected.key, message: rejectedOverrideMessage(rejected) });
166
+ }
167
+ const changeKeys = new Set(diff2.changes.map((change) => change.key));
168
+ for (const key of [...acknowledged].sort()) {
169
+ if (changeKeys.has(key)) continue;
170
+ report.warnings.push({
171
+ code: "acknowledgement/unknown_change",
172
+ key,
173
+ message: `"${key}" is acknowledged in privacy.review.json but no such change exists; remove it.`
174
+ });
175
+ }
176
+ if (policySnapshot(lock.registry).hash !== lock.policyHash) {
177
+ report.warnings.push({
178
+ code: "lock/hash_mismatch",
179
+ message: `The registry stored in ${input.lockPath} does not match its policyHash. The lock file is written by "consent-kit release" and should not be edited by hand.`
180
+ });
181
+ }
182
+ report.ok = report.errors.length === 0;
183
+ return { report, registry, policy, diff: diff2 };
184
+ }
185
+ function acknowledgementOf(change, acknowledged) {
186
+ if (change.classification !== "needs_review" && change.classification !== "needs_confirmation") return "not_required";
187
+ return acknowledged.has(change.key) ? "acknowledged" : "missing";
188
+ }
189
+ function rejectedOverrideMessage(rejected) {
190
+ const requested = JSON.stringify(rejected.requested);
191
+ switch (rejected.reason) {
192
+ case "downgrade":
193
+ return `Override ignored: "${rejected.key}" is ${rejected.current} and cannot be lowered to ${requested}. Overrides only escalate.`;
194
+ case "unknown_change":
195
+ return `Override ignored: no change has the key "${rejected.key}".`;
196
+ case "invalid_classification":
197
+ return `Override ignored: ${requested} (for "${rejected.key}") is not a classification.`;
198
+ }
199
+ }
200
+ function makeLock(policy, policyHash, revision, releasedAt, previous = null) {
201
+ const release2 = { revision, policyHash, releasedAt: releasedAt.toISOString() };
202
+ return {
203
+ lockVersion: 2,
204
+ ...release2,
205
+ history: [...previous?.history ?? [], releasedPolicy(policy, release2)],
206
+ registry: policy
207
+ };
208
+ }
209
+
210
+ // src/files.ts
211
+ var DEFAULT_REGISTRY_FILE = "privacy.registry.yaml";
212
+ var LOCK_FILE = "privacy.lock.json";
213
+ var REVIEW_FILE = "privacy.review.json";
214
+ var InputError = class extends Error {
215
+ };
216
+ function readIfExists(path) {
217
+ try {
218
+ return readFileSync(path, "utf8");
219
+ } catch (error) {
220
+ if (error.code === "ENOENT") return null;
221
+ throw new InputError(`cannot read ${path}: ${error.message}`);
222
+ }
223
+ }
224
+ function writeFile(path, contents) {
225
+ mkdirSync(dirname(path), { recursive: true });
226
+ writeFileSync(path, contents);
227
+ }
228
+ function formatJsonFile(value) {
229
+ return `${JSON.stringify(value, null, 2)}
230
+ `;
231
+ }
232
+ function parseJson(text, path) {
233
+ try {
234
+ return JSON.parse(text);
235
+ } catch (error) {
236
+ throw new InputError(`${path} is not valid JSON: ${error.message}`);
237
+ }
238
+ }
239
+ function isRecord(value) {
240
+ return typeof value === "object" && value !== null && !Array.isArray(value);
241
+ }
242
+ function parseLock(text, path) {
243
+ const value = parseJson(text, path);
244
+ if (!isRecord(value)) throw new InputError(`${path} must contain a JSON object`);
245
+ if (value.lockVersion !== 1 && value.lockVersion !== 2) {
246
+ throw new InputError(`${path} has lockVersion ${JSON.stringify(value.lockVersion)}; this consent-kit reads lockVersion 1 and 2`);
247
+ }
248
+ const { revision, policyHash, releasedAt, registry } = value;
249
+ if (!isCount(revision)) throw new InputError(`${path}: "revision" must be a non-negative integer`);
250
+ if (typeof policyHash !== "string") throw new InputError(`${path}: "policyHash" must be a string`);
251
+ if (typeof releasedAt !== "string") throw new InputError(`${path}: "releasedAt" must be a string`);
252
+ if (!isRecord(registry) || !Array.isArray(registry.purposes)) {
253
+ throw new InputError(`${path}: "registry" must be the released registry`);
254
+ }
255
+ const released = registry;
256
+ const history = value.lockVersion === 1 ? [releasedPolicy(released, { policyHash, revision, releasedAt })] : parseHistory(value.history, path);
257
+ const last = history[history.length - 1];
258
+ if (last === void 0 || last.policyHash !== policyHash || last.revision !== revision || last.releasedAt !== releasedAt) {
259
+ throw new InputError(`${path}: the last entry of "history" must be the release the lock records (revision ${revision}, released ${releasedAt})`);
260
+ }
261
+ return { lockVersion: 2, revision, policyHash, releasedAt, history, registry: released };
262
+ }
263
+ function parseHistory(value, path) {
264
+ if (!Array.isArray(value)) throw new InputError(`${path}: "history" must be an array of releases`);
265
+ return value.map((entry, index) => {
266
+ const fail = (problem) => {
267
+ throw new InputError(`${path}: history[${index}] ${problem}`);
268
+ };
269
+ if (!isRecord(entry)) return fail("must be an object");
270
+ const { revision, policyHash, releasedAt, consentPurposes, otherPurposes, sendsReceipts } = entry;
271
+ if (!isCount(revision)) return fail('"revision" must be a non-negative integer');
272
+ if (typeof policyHash !== "string") return fail('"policyHash" must be a string');
273
+ if (typeof releasedAt !== "string") return fail('"releasedAt" must be a string');
274
+ if (!isRecord(consentPurposes) || !Object.values(consentPurposes).every((version2) => isCount(version2) && version2 >= 1)) {
275
+ return fail('"consentPurposes" must map purpose ids to versions');
276
+ }
277
+ if (!Array.isArray(otherPurposes) || !otherPurposes.every((id) => typeof id === "string")) return fail('"otherPurposes" must be an array of ids');
278
+ if (typeof sendsReceipts !== "boolean") return fail('"sendsReceipts" must be true or false');
279
+ return {
280
+ revision,
281
+ policyHash,
282
+ releasedAt,
283
+ consentPurposes,
284
+ otherPurposes,
285
+ sendsReceipts
286
+ };
287
+ });
288
+ }
289
+ function isCount(value) {
290
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
291
+ }
292
+ function parseReview(text, path) {
293
+ const value = parseJson(text, path);
294
+ if (!isRecord(value)) throw new InputError(`${path} must contain a JSON object`);
295
+ const overrides = value.overrides ?? {};
296
+ const acknowledged = value.acknowledged ?? [];
297
+ if (!isRecord(overrides)) throw new InputError(`${path}: "overrides" must be an object of change key to classification`);
298
+ if (!Array.isArray(acknowledged) || !acknowledged.every((key) => typeof key === "string")) {
299
+ throw new InputError(`${path}: "acknowledged" must be an array of change keys`);
300
+ }
301
+ return { overrides, acknowledged };
302
+ }
303
+ function loadLock(path) {
304
+ const text = readIfExists(path);
305
+ return text === null ? null : parseLock(text, path);
306
+ }
307
+ function loadReview(path) {
308
+ const text = readIfExists(path);
309
+ return text === null ? EMPTY_REVIEW : parseReview(text, path);
310
+ }
311
+ function consumedReview(text, path) {
312
+ const review = parseReview(text, path);
313
+ if (Object.keys(review.overrides).length === 0 && review.acknowledged.length === 0) return null;
314
+ return formatJsonFile({ ...parseJson(text, path), overrides: {}, acknowledged: [] });
315
+ }
316
+ var identity = (text) => text;
317
+ var plain = { bold: identity, dim: identity, red: identity, yellow: identity, green: identity };
318
+ var ansi = (open, close) => (text) => `\x1B[${open}m${text}\x1B[${close}m`;
319
+ var coloured = {
320
+ bold: ansi(1, 22),
321
+ dim: ansi(2, 22),
322
+ red: ansi(31, 39),
323
+ yellow: ansi(33, 39),
324
+ green: ansi(32, 39)
325
+ };
326
+ var GROUPS = [
327
+ { classification: "needs_review", heading: "Needs review (blocks the build until a person acknowledges it)" },
328
+ { classification: "material", heading: "Material (purpose version bump required)" },
329
+ { classification: "needs_confirmation", heading: "Needs confirmation (presumed not material)" },
330
+ { classification: "not_material", heading: "Not material" }
331
+ ];
332
+ var CONSEQUENCES = {
333
+ human_review: "human review",
334
+ reconsent: "re-consent",
335
+ notice_update: "notice update",
336
+ confirmation: "confirmation",
337
+ changelog: "changelog only"
338
+ };
339
+ var VALUE_WIDTH = 100;
340
+ function renderValidationErrors(report, paint = plain) {
341
+ return report.validationErrors.map((error) => {
342
+ let location = report.registry;
343
+ if (error.line !== void 0) location += `:${error.line}:${error.column ?? 1}`;
344
+ return `${location} ${paint.red(error.rule)} ${error.message}`;
345
+ });
346
+ }
347
+ function renderDiff(report, paint = plain) {
348
+ if (report.firstRelease) {
349
+ return [
350
+ `No ${report.lock.path}: nothing has been released yet.`,
351
+ report.consentPurposes.length === 0 ? `The first release will be revision ${report.revision.pending}. No purpose asks for consent, so no visitor is asked anything.` : `The first release will be revision ${report.revision.pending}; every visitor is asked for the first time.`
352
+ ];
353
+ }
354
+ const since = `revision ${report.lock.revision} (released ${report.lock.releasedAt})`;
355
+ if (report.changes.length === 0) {
356
+ return [
357
+ report.unreleasedChanges ? `No classified changes since ${since}; only purpose versions or unclassified details differ.` : `No changes since ${since}.`
358
+ ];
359
+ }
360
+ const lines = [`Changes since ${since}:`];
361
+ for (const group of GROUPS) {
362
+ const changes = report.changes.filter((change) => change.classification === group.classification);
363
+ if (changes.length === 0) continue;
364
+ lines.push("", paint.bold(`${group.heading}: ${changes.length}`));
365
+ for (const change of changes) lines.push(...renderChange(change, paint));
366
+ }
367
+ lines.push("", revisionSentence(report));
368
+ return lines;
369
+ }
370
+ function renderChange(change, paint) {
371
+ const flags = [];
372
+ if (change.escalated) flags.push(`escalated from ${change.defaultClassification}`);
373
+ if (change.acknowledgement === "acknowledged") flags.push(paint.green("acknowledged"));
374
+ if (change.acknowledgement === "missing") flags.push(paint.red("not acknowledged"));
375
+ const lines = [` ${change.key}${flags.length > 0 ? ` [${flags.join(", ")}]` : ""}`];
376
+ lines.push(paint.dim(` ${formatValue(change.before)} -> ${formatValue(change.after)}`));
377
+ if (change.note !== void 0) lines.push(paint.dim(` note: ${change.note}`));
378
+ if (change.affectedPurposes.length === 0) lines.push(" affects no purpose");
379
+ for (const purpose of change.affectedPurposes) {
380
+ lines.push(` ${purpose.id} (${purpose.basis}): ${CONSEQUENCES[purpose.consequence]}`);
381
+ }
382
+ return lines;
383
+ }
384
+ function formatValue(value) {
385
+ if (value === void 0) return "(none)";
386
+ const text = JSON.stringify(value) ?? String(value);
387
+ return text.length > VALUE_WIDTH ? `${text.slice(0, VALUE_WIDTH - 3)}...` : text;
388
+ }
389
+ function revisionSentence(report) {
390
+ const { released, pending } = report.revision;
391
+ if (report.consentPurposes.length === 0) return `Revision ${pending}: no purpose asks for consent, so no visitor is asked anything.`;
392
+ if (report.firstRelease) return `Revision ${pending}: every visitor is asked for the first time.`;
393
+ return report.reconsentRequired ? `Visitors will be asked to consent again: revision ${released} -> ${pending}.` : `Visitors will not be asked again: revision stays at ${pending}.`;
394
+ }
395
+ function renderFindings(report, paint = plain) {
396
+ const line = (label, finding) => `${label} ${finding.code} ${finding.message}`;
397
+ return [
398
+ ...report.errors.map((finding) => line(paint.red("error"), finding)),
399
+ ...report.warnings.map((finding) => line(paint.yellow("warning"), finding))
400
+ ];
401
+ }
402
+ function renderCheck(report, paint = plain) {
403
+ if (report.validationErrors.length > 0) {
404
+ const count = report.validationErrors.length;
405
+ return [
406
+ ...renderValidationErrors(report, paint),
407
+ "",
408
+ paint.red(`check failed: ${plural(count, "validation error")} in ${report.registry}`)
409
+ ];
410
+ }
411
+ const lines = [...renderDiff(report, paint)];
412
+ const presets = describePresets({ ...report.presets, warnings: [] });
413
+ if (presets.length > 0) lines.push("", ...presets);
414
+ const deviations = describeCspDeviations(report.csp?.deviations ?? []);
415
+ if (deviations.length > 0) {
416
+ lines.push("", `Content-Security-Policy: ${plural(deviations.length, "deviation")} from strict`, ...deviations.map((line) => ` ${line}`));
417
+ }
418
+ const findings = renderFindings(report, paint);
419
+ if (findings.length > 0) lines.push("", ...findings);
420
+ lines.push("", verdict(report, paint));
421
+ return lines;
422
+ }
423
+ function verdict(report, paint) {
424
+ const warnings = report.warnings.length > 0 ? `, ${plural(report.warnings.length, "warning")}` : "";
425
+ return report.ok ? paint.green(`check passed${warnings}`) : paint.red(`check failed: ${plural(report.errors.length, "error")}${warnings}`);
426
+ }
427
+ function renderChangelogEntry(report, releasedAt, paint = plain) {
428
+ const lines = [paint.bold(`Released revision ${report.revision.pending} on ${releasedAt}`), `Policy hash: ${report.policyHash}`, ""];
429
+ if (report.firstRelease) {
430
+ lines.push("First release. Every visitor is asked for the first time.");
431
+ return lines;
432
+ }
433
+ const changes = renderDiff(report, paint);
434
+ lines.push(...changes);
435
+ if (report.changes.length === 0) lines.push(revisionSentence(report));
436
+ return lines;
437
+ }
438
+ function plural(count, noun) {
439
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
440
+ }
441
+
442
+ // src/docs.ts
443
+ var DEFAULT_DOCS_DIR = "privacy-docs";
444
+ var DOCUMENTS_FILE = "privacy.documents.json";
445
+ function isRecord2(value) {
446
+ return typeof value === "object" && value !== null && !Array.isArray(value);
447
+ }
448
+ function parseDocumentsFile(text, path) {
449
+ let value;
450
+ try {
451
+ value = JSON.parse(text);
452
+ } catch (error) {
453
+ throw new InputError(`${path} is not valid JSON: ${error.message}`);
454
+ }
455
+ if (!isRecord2(value)) throw new InputError(`${path} must contain a JSON object`);
456
+ const known = ["slots", "phrases", "cookieTableLinks", "subjectRequestFormLinks", "generatedAt"];
457
+ if ("labels" in value) {
458
+ throw new InputError(
459
+ `${path}: "labels" is no longer read. Move "labels.dataCategories" to the registry's top-level "dataCategories" (id: { title: { <locale>: <name> } }) and "labels.retentionEvents" to "retentionEvents" (id: { <locale>: <text> }), then remove "labels" from this file.`
460
+ );
461
+ }
462
+ for (const key of Object.keys(value)) {
463
+ if (!known.includes(key)) throw new InputError(`${path}: unknown key "${key}" (expected: ${known.join(", ")})`);
464
+ }
465
+ const { slots = {}, phrases = {}, cookieTableLinks = {}, subjectRequestFormLinks = {}, generatedAt } = value;
466
+ if (!isRecord2(slots) || !Object.values(slots).every((slot) => slot === false || isRecord2(slot) && Object.values(slot).every((text2) => typeof text2 === "string"))) {
467
+ throw new InputError(`${path}: "slots" must map a slot id to { "<locale>": "text" } or false`);
468
+ }
469
+ if (!isRecord2(phrases) || !Object.values(phrases).every(isRecord2)) {
470
+ throw new InputError(`${path}: "phrases" must map a phrase id to { "<locale>": "text" }`);
471
+ }
472
+ if (!isRecord2(cookieTableLinks) || !Object.values(cookieTableLinks).every((link) => typeof link === "string")) {
473
+ throw new InputError(`${path}: "cookieTableLinks" must map a locale to a URL`);
474
+ }
475
+ if (!isRecord2(subjectRequestFormLinks) || !Object.values(subjectRequestFormLinks).every((link) => typeof link === "string")) {
476
+ throw new InputError(`${path}: "subjectRequestFormLinks" must map a locale to a URL`);
477
+ }
478
+ if (generatedAt !== void 0 && typeof generatedAt !== "string") throw new InputError(`${path}: "generatedAt" must be a string`);
479
+ return {
480
+ slots,
481
+ phraseOverrides: phrases,
482
+ cookieTableLinks,
483
+ subjectRequestFormLinks,
484
+ generatedAt
485
+ };
486
+ }
487
+ function renderDocumentsReport(report, paint) {
488
+ const lines = [];
489
+ const label = (text, colour) => colour(text.padEnd(10));
490
+ for (const error of report.errors) lines.push(`${label("error", paint.red)} ${error.code} ${error.message}`);
491
+ for (const locale of report.skippedLocales) lines.push(`${label("skipped", paint.yellow)} locale "${locale}": the phrase library has no texts for it`);
492
+ if (report.unreviewedPhrases.length > 0) {
493
+ const perLocale = /* @__PURE__ */ new Map();
494
+ for (const phrase of report.unreviewedPhrases) perLocale.set(phrase.locale, (perLocale.get(phrase.locale) ?? 0) + 1);
495
+ const breakdown = [...perLocale].map(([locale, count]) => `${count} ${locale}`).join(", ");
496
+ lines.push(
497
+ `${label("unreviewed", paint.yellow)} ${plural(report.unreviewedPhrases.length, "phrase text")} in use ${report.unreviewedPhrases.length === 1 ? "has" : "have"} not been legally reviewed (${breakdown}). The documents are stamped as unreviewed drafts. List them with --json.`
498
+ );
499
+ } else {
500
+ lines.push(`${label("reviewed", paint.green)} every phrase in use has a legal review on record`);
501
+ }
502
+ for (const override of report.overrides) {
503
+ lines.push(
504
+ `${label("override", paint.yellow)} ${override.id} (${override.locale}, ${override.status === "reviewed" ? "reviewed by the project" : "unreviewed"}): ${JSON.stringify(override.text)} replaces ${JSON.stringify(override.libraryText)}`
505
+ );
506
+ }
507
+ for (const gap of report.gaps) {
508
+ lines.push(`${gap.severity === "required" ? label("required", paint.red) : label("advisory", paint.dim)} ${gap.subject} ${gap.message} (${gap.locales.join(", ")})`);
509
+ }
510
+ const required = report.gaps.filter((gap) => gap.severity === "required").length;
511
+ lines.push(
512
+ "",
513
+ `${plural(report.unreviewedPhrases.length, "unreviewed phrase text")}, ${plural(report.overrides.length, "override")}, ${plural(required, "required gap")}, ${plural(report.gaps.length - required, "advisory gap")}. Generated text is not legal advice.`
514
+ );
515
+ return lines;
516
+ }
517
+ function docs(ctx, flags, loaded) {
518
+ const { report, registry } = loaded;
519
+ if (!report.ok || registry === void 0 || report.policyHash === null || report.revision.pending === null) {
520
+ ctx.out(renderCheck(report, ctx.paint));
521
+ ctx.err("docs refused: the check failed");
522
+ return 1;
523
+ }
524
+ const outDir = flags.out ?? DEFAULT_DOCS_DIR;
525
+ const documentsPath = join(dirname(flags.registry ?? DEFAULT_REGISTRY_FILE), DOCUMENTS_FILE);
526
+ const documentsText = readIfExists(resolve(ctx.cwd, documentsPath));
527
+ const inputs = documentsText === null ? {} : parseDocumentsFile(documentsText, documentsPath);
528
+ const diff2 = loaded.diff ?? null;
529
+ const generated = generateDocuments(registry, {
530
+ ...inputs,
531
+ policyHash: report.policyHash,
532
+ revision: report.revision.pending,
533
+ requireReviewed: flags["require-reviewed"] === true,
534
+ changelog: diff2 !== null && diff2.changes.length > 0 ? { diff: diff2, previousPolicyHash: report.lock.policyHash ?? void 0 } : void 0
535
+ });
536
+ const summary = flags.json ? [JSON.stringify(generated.report, null, 2)] : renderDocumentsReport(generated.report, ctx.paint);
537
+ if (!generated.report.ok) {
538
+ ctx.out(summary);
539
+ const unreviewed = generated.report.errors.every((error) => error.code === "unreviewed_phrases");
540
+ ctx.err(unreviewed ? "docs refused: --require-reviewed is set and unreviewed phrase texts are in use" : `docs refused: ${generated.report.errors[0]?.message}`);
541
+ return 1;
542
+ }
543
+ const target = (name) => resolve(ctx.cwd, outDir, name);
544
+ const plan = planWrites(generated.files, (name) => readIfExists(target(name)));
545
+ const stale = plan.filter((file) => file.status !== "unchanged");
546
+ if (flags.check) {
547
+ if (stale.length === 0) {
548
+ ctx.out(flags.json ? summary : [...summary, `${plural(plan.length, "document")} in ${outDir} ${plan.length === 1 ? "is" : "are"} up to date (revision ${report.revision.pending}).`]);
549
+ return 0;
550
+ }
551
+ ctx.out(flags.json ? summary : [...stale.map((file) => `${file.status === "created" ? "missing" : "stale"} ${join(outDir, file.name)}`), "", ...summary]);
552
+ ctx.err(`${plural(stale.length, "document")} out of date; run "consent-kit docs"`);
553
+ return 1;
554
+ }
555
+ for (const file of stale) writeFile(target(file.name), generated.files[file.name]);
556
+ if (flags.json) {
557
+ ctx.out(summary);
558
+ return 0;
559
+ }
560
+ const width = Math.max(...plan.map((file) => file.status.length));
561
+ ctx.out([
562
+ ...plan.map((file) => `${file.status.padEnd(width)} ${join(outDir, file.name)}`),
563
+ "",
564
+ ...summary,
565
+ `Wrote the documents of revision ${report.revision.pending} (policy ${report.policyHash.slice(0, 12)}): ${stale.length} written, ${plan.length - stale.length} unchanged.`
566
+ ]);
567
+ return 0;
568
+ }
569
+
570
+ // src/cli.ts
571
+ var EXIT_OK = 0;
572
+ var EXIT_FAILED = 1;
573
+ var EXIT_USAGE = 2;
574
+ var AUDIT_PACKAGE = "@consent-kit/audit";
575
+ function loadAuditPackage() {
576
+ const specifier = AUDIT_PACKAGE;
577
+ return import(specifier);
578
+ }
579
+ var AUDIT_INSTALL_HINT = `"consent-kit audit" needs the optional package ${AUDIT_PACKAGE} (and its browser, Playwright's Chromium), which is not installed.
580
+ Install it next to @consent-kit/cli, then run the command again:
581
+
582
+ npm install --save-dev ${AUDIT_PACKAGE}
583
+ npx playwright install chromium
584
+ `;
585
+ var HELP = `consent-kit: compile privacy.registry.yaml into consent config, policy and guard files
586
+
587
+ Usage: consent-kit <command> [options]
588
+
589
+ Commands:
590
+ check Validate the registry and classify its changes since the last release
591
+ diff Print the changes since the last release (always exits 0 for a valid registry)
592
+ build Run check, then write the generated files
593
+ docs Run check, then write the privacy documents (policy, cookie table, Art. 30 record,
594
+ processor list, field notices, changelog entry). Drafts, not legal advice
595
+ release Run check, then record the registry as released in privacy.lock.json
596
+ script-tag <artefact-id>
597
+ Print the consent-gated <script> tag for a script artefact
598
+ audit <url>
599
+ Check a running site against the registry in a real browser.
600
+ Needs the optional package ${AUDIT_PACKAGE}; see "consent-kit audit --help"
601
+
602
+ Options (all commands):
603
+ --registry <path> Registry file (default: ${DEFAULT_REGISTRY_FILE})
604
+ -h, --help Show this help
605
+ -v, --version Show the version
606
+
607
+ Options (check, diff):
608
+ --json Print a machine-readable report
609
+
610
+ Options (audit): --page <path>, --check <id>, --exercise <file>, --json, --strict, --headed
611
+
612
+ Options (build):
613
+ --out <dir> Output directory (default: ${DEFAULT_OUT_DIR})
614
+ --guard-mode <mode> ${GUARD_MODES.join(" | ")} (default: ${DEFAULT_GUARD_MODE})
615
+ --report-url <url> Where the inline guard sends violation reports
616
+ --check Write nothing; exit 1 if the generated files are stale
617
+
618
+ Options (docs):
619
+ --out <dir> Output directory (default: ${DEFAULT_DOCS_DIR})
620
+ --check Write nothing; exit 1 if the documents are stale
621
+ --require-reviewed Exit 1 if any phrase text in use has no legal review on record
622
+ --json Print the documents report (unreviewed phrases, overrides, gaps) as JSON
623
+
624
+ Files next to the registry:
625
+ ${LOCK_FILE} Last released state. Written by "release"; commit it.
626
+ ${REVIEW_FILE} Optional. { "overrides": { "<change key>": "<classification>" },
627
+ "acknowledged": ["<change key>"] }
628
+ ${DOCUMENTS_FILE} Optional, for "docs". { "slots": { "<slot>": { "<locale>": "text" } | false },
629
+ "phrases": { "<phrase id>": { "<locale>": "text" } }, "labels": {\u2026} }
630
+
631
+ Exit codes: 0 ok, 1 check failed or files stale, 2 usage or unreadable input.
632
+ `;
633
+ var COMMON_OPTIONS = {
634
+ registry: { type: "string" },
635
+ help: { type: "boolean", short: "h" },
636
+ version: { type: "boolean", short: "v" }
637
+ };
638
+ var REPORT_OPTIONS = { ...COMMON_OPTIONS, json: { type: "boolean" } };
639
+ var COMMAND_OPTIONS = {
640
+ check: REPORT_OPTIONS,
641
+ diff: REPORT_OPTIONS,
642
+ build: {
643
+ ...COMMON_OPTIONS,
644
+ out: { type: "string" },
645
+ "guard-mode": { type: "string" },
646
+ "report-url": { type: "string" },
647
+ check: { type: "boolean" }
648
+ },
649
+ docs: { ...REPORT_OPTIONS, out: { type: "string" }, check: { type: "boolean" }, "require-reviewed": { type: "boolean" } },
650
+ release: COMMON_OPTIONS,
651
+ "script-tag": COMMON_OPTIONS
652
+ };
653
+ var POSITIONALS = {
654
+ "script-tag": { count: 1, expected: "script-tag expects one artefact id" }
655
+ };
656
+ var UsageError = class extends Error {
657
+ };
658
+ function run(argv, options = {}) {
659
+ const stdout = options.stdout ?? process.stdout;
660
+ const stderr = options.stderr ?? process.stderr;
661
+ const env = options.env ?? process.env;
662
+ const noColor = env.NO_COLOR !== void 0 && env.NO_COLOR !== "";
663
+ const ctx = {
664
+ cwd: options.cwd ?? process.cwd(),
665
+ out: (lines) => {
666
+ if (lines.length > 0) stdout.write(`${lines.join("\n")}
667
+ `);
668
+ },
669
+ err: (line) => {
670
+ stderr.write(`consent-kit: ${line}
671
+ `);
672
+ },
673
+ paint: stdout.isTTY === true && !noColor ? coloured : plain,
674
+ now: options.now ?? (() => /* @__PURE__ */ new Date())
675
+ };
676
+ try {
677
+ const first = argv[0];
678
+ if (first === void 0) {
679
+ stderr.write(HELP);
680
+ return EXIT_USAGE;
681
+ }
682
+ if (first === "--help" || first === "-h" || first === "help") {
683
+ stdout.write(HELP);
684
+ return EXIT_OK;
685
+ }
686
+ if (first === "--version" || first === "-v") {
687
+ stdout.write(`${version()}
688
+ `);
689
+ return EXIT_OK;
690
+ }
691
+ if (first === "audit") {
692
+ return audit(argv.slice(1), options.loadAudit ?? loadAuditPackage, { cwd: ctx.cwd, stdout, stderr });
693
+ }
694
+ if (!Object.hasOwn(COMMAND_OPTIONS, first)) {
695
+ throw new UsageError(first.startsWith("-") ? `expected a command before "${first}"` : `unknown command "${first}"`);
696
+ }
697
+ const command = first;
698
+ const { values: parsed, positionals } = parse(argv.slice(1), COMMAND_OPTIONS[command], POSITIONALS[command]);
699
+ if (parsed.help) {
700
+ stdout.write(HELP);
701
+ return EXIT_OK;
702
+ }
703
+ if (parsed.version) {
704
+ stdout.write(`${version()}
705
+ `);
706
+ return EXIT_OK;
707
+ }
708
+ switch (command) {
709
+ case "check":
710
+ return check(ctx, parsed);
711
+ case "diff":
712
+ return diff(ctx, parsed);
713
+ case "build":
714
+ return build(ctx, parsed);
715
+ case "docs":
716
+ return docs(ctx, parsed, load(ctx, parsed));
717
+ case "release":
718
+ return release(ctx, parsed);
719
+ case "script-tag":
720
+ return scriptTag(ctx, parsed, positionals[0]);
721
+ }
722
+ } catch (error) {
723
+ if (error instanceof UsageError) {
724
+ ctx.err(`${error.message}. Run "consent-kit --help" for usage.`);
725
+ return EXIT_USAGE;
726
+ }
727
+ if (error instanceof InputError) {
728
+ ctx.err(error.message);
729
+ return EXIT_USAGE;
730
+ }
731
+ throw error;
732
+ }
733
+ }
734
+ function parse(args, options, positional) {
735
+ let parsed;
736
+ try {
737
+ parsed = parseArgs({ args: [...args], options, strict: true, allowPositionals: positional !== void 0 });
738
+ } catch (error) {
739
+ throw new UsageError(error.message.replace(/\.$/, ""));
740
+ }
741
+ const { values, positionals } = parsed;
742
+ if (positional && positionals.length !== positional.count && !values.help && !values.version) throw new UsageError(positional.expected);
743
+ return { values, positionals };
744
+ }
745
+ function version() {
746
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
747
+ return manifest.version;
748
+ }
749
+ function load(ctx, flags) {
750
+ const registryPath = flags.registry ?? DEFAULT_REGISTRY_FILE;
751
+ const yaml = readIfExists(resolve(ctx.cwd, registryPath));
752
+ if (yaml === null) throw new InputError(`registry not found: ${registryPath}`);
753
+ const lockPath = join(dirname(registryPath), LOCK_FILE);
754
+ const reviewPath = join(dirname(registryPath), REVIEW_FILE);
755
+ const lockFile = resolve(ctx.cwd, lockPath);
756
+ const reviewFile = resolve(ctx.cwd, reviewPath);
757
+ const lock = loadLock(lockFile);
758
+ const analysis = analyse({
759
+ registryPath,
760
+ lockPath,
761
+ parsed: parseRegistry(yaml),
762
+ lock,
763
+ review: loadReview(reviewFile)
764
+ });
765
+ return { ...analysis, lock, lockFile, reviewFile };
766
+ }
767
+ function check(ctx, flags) {
768
+ const { report } = load(ctx, flags);
769
+ ctx.out(flags.json ? [JSON.stringify(report, null, 2)] : renderCheck(report, ctx.paint));
770
+ return report.ok ? EXIT_OK : EXIT_FAILED;
771
+ }
772
+ function diff(ctx, flags) {
773
+ const { report, registry } = load(ctx, flags);
774
+ if (flags.json) {
775
+ ctx.out([JSON.stringify(report, null, 2)]);
776
+ } else if (registry === void 0) {
777
+ ctx.out(renderValidationErrors(report, ctx.paint));
778
+ } else {
779
+ ctx.out(renderDiff(report, ctx.paint));
780
+ }
781
+ return registry === void 0 ? EXIT_FAILED : EXIT_OK;
782
+ }
783
+ function build(ctx, flags) {
784
+ const guardMode = flags["guard-mode"] ?? DEFAULT_GUARD_MODE;
785
+ if (!GUARD_MODES.includes(guardMode)) {
786
+ throw new UsageError(`--guard-mode must be one of ${GUARD_MODES.join(", ")}; got "${guardMode}"`);
787
+ }
788
+ const outDir = flags.out ?? DEFAULT_OUT_DIR;
789
+ const { report, registry, lock } = load(ctx, flags);
790
+ if (!report.ok || registry === void 0 || report.revision.pending === null) {
791
+ ctx.out(renderCheck(report, ctx.paint));
792
+ ctx.err("build refused: the check failed");
793
+ return EXIT_FAILED;
794
+ }
795
+ const documentsPath = join(dirname(flags.registry ?? DEFAULT_REGISTRY_FILE), DOCUMENTS_FILE);
796
+ const documentsText = registry.subjectRequests === void 0 ? null : readIfExists(resolve(ctx.cwd, documentsPath));
797
+ const outputs = buildOutputs(registry, {
798
+ revision: report.revision.pending,
799
+ guardMode,
800
+ reportUrl: flags["report-url"],
801
+ history: lock?.history,
802
+ phraseOverrides: documentsText === null ? void 0 : parseDocumentsFile(documentsText, documentsPath).phraseOverrides
803
+ });
804
+ const target = (name) => resolve(ctx.cwd, outDir, name);
805
+ const plan = planWrites(outputs, (name) => readIfExists(target(name)));
806
+ const stale = plan.filter((file) => file.status !== "unchanged");
807
+ const warnings = report.warnings.map((finding) => `${ctx.paint.yellow("warning")} ${finding.code} ${finding.message}`);
808
+ if (flags.check) {
809
+ ctx.out(warnings);
810
+ if (stale.length === 0) {
811
+ ctx.out([`${plural(plan.length, "generated file")} in ${outDir} ${plan.length === 1 ? "is" : "are"} up to date (revision ${report.revision.pending}).`]);
812
+ return EXIT_OK;
813
+ }
814
+ ctx.out(stale.map((file) => `${file.status === "created" ? "missing" : "stale"} ${join(outDir, file.name)}`));
815
+ ctx.err(`${plural(stale.length, "generated file")} out of date; run "consent-kit build"`);
816
+ return EXIT_FAILED;
817
+ }
818
+ for (const file of stale) writeFile(target(file.name), outputs[file.name]);
819
+ const width = Math.max(...plan.map((file) => file.status.length));
820
+ ctx.out([
821
+ ...warnings,
822
+ ...plan.map((file) => `${file.status.padEnd(width)} ${join(outDir, file.name)}`),
823
+ "",
824
+ `Built revision ${report.revision.pending} with guard mode "${guardMode}": ${stale.length} written, ${plan.length - stale.length} unchanged.`,
825
+ revisionSentence(report)
826
+ ]);
827
+ return EXIT_OK;
828
+ }
829
+ function scriptTag(ctx, flags, artefactId) {
830
+ const { report, registry } = load(ctx, flags);
831
+ if (registry === void 0) {
832
+ ctx.out(renderValidationErrors(report, ctx.paint));
833
+ return EXIT_FAILED;
834
+ }
835
+ let tag;
836
+ try {
837
+ tag = consentScriptTag(registry, artefactId);
838
+ } catch (error) {
839
+ throw new UsageError(error.message.replace(/^consent-kit: /, "").replace(/\.$/, ""));
840
+ }
841
+ ctx.out([tag]);
842
+ return EXIT_OK;
843
+ }
844
+ async function audit(argv, loadAudit, io) {
845
+ let module;
846
+ try {
847
+ module = await loadAudit();
848
+ } catch (error) {
849
+ if (error.code !== "ERR_MODULE_NOT_FOUND") throw error;
850
+ io.stderr.write(`consent-kit: ${AUDIT_INSTALL_HINT}`);
851
+ return EXIT_USAGE;
852
+ }
853
+ return module.run(argv, { ...io, programName: "consent-kit audit", defaultRegistry: DEFAULT_REGISTRY_FILE });
854
+ }
855
+ function release(ctx, flags) {
856
+ const loaded = load(ctx, flags);
857
+ const { report, policy } = loaded;
858
+ if (!report.ok || policy === void 0 || report.policyHash === null || report.revision.pending === null) {
859
+ ctx.out(renderCheck(report, ctx.paint));
860
+ ctx.err("release refused: the check failed");
861
+ return EXIT_FAILED;
862
+ }
863
+ if (!report.unreleasedChanges) {
864
+ ctx.out([`Nothing to release: the registry is identical to revision ${report.lock.revision} (released ${report.lock.releasedAt}).`]);
865
+ return EXIT_OK;
866
+ }
867
+ const lock = makeLock(policy, report.policyHash, report.revision.pending, ctx.now(), loaded.lock);
868
+ writeFile(loaded.lockFile, formatJsonFile(lock));
869
+ const reviewText = readIfExists(loaded.reviewFile);
870
+ const cleared = reviewText === null ? null : consumedReview(reviewText, loaded.reviewFile);
871
+ if (cleared !== null) writeFile(loaded.reviewFile, cleared);
872
+ ctx.out(renderChangelogEntry(report, lock.releasedAt, ctx.paint));
873
+ ctx.out(["", `Wrote ${report.lock.path}.${cleared !== null ? ` Cleared the overrides and acknowledgements in ${REVIEW_FILE}.` : ""}`]);
874
+ return EXIT_OK;
875
+ }
876
+
877
+ export { DEFAULT_GUARD_MODE, DEFAULT_OUT_DIR, DEFAULT_REGISTRY_FILE, EXIT_FAILED, EXIT_OK, EXIT_USAGE, GUARD_MODES, INITIAL_REVISION, LOCK_FILE, RECEIPTS_MANIFEST_FILE, REVIEW_FILE, analyse, buildOutputs, headersFile, makeLock, planWrites, renderChangelogEntry, renderCheck, renderDiff, renderValidationErrors, run };