@nodii/onboarding 0.0.1 → 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/README.md +75 -2
- package/dist/chunk-7NS7ENJV.js +232 -0
- package/dist/chunk-7NS7ENJV.js.map +1 -0
- package/dist/chunk-AZE3NPSY.js +186 -0
- package/dist/chunk-AZE3NPSY.js.map +1 -0
- package/dist/chunk-BMQINH6O.js +401 -0
- package/dist/chunk-BMQINH6O.js.map +1 -0
- package/dist/chunk-F75ZJERM.js +199 -0
- package/dist/chunk-F75ZJERM.js.map +1 -0
- package/dist/chunk-FIRSA7EH.js +3 -0
- package/dist/chunk-FIRSA7EH.js.map +1 -0
- package/dist/chunk-IPAKPLIF.js +1660 -0
- package/dist/chunk-IPAKPLIF.js.map +1 -0
- package/dist/chunk-JFDQZ3AC.js +3 -0
- package/dist/chunk-JFDQZ3AC.js.map +1 -0
- package/dist/chunk-JFIONONR.js +3 -0
- package/dist/chunk-JFIONONR.js.map +1 -0
- package/dist/chunk-KQTS47FC.js +546 -0
- package/dist/chunk-KQTS47FC.js.map +1 -0
- package/dist/chunk-LVJM4CTG.js +306 -0
- package/dist/chunk-LVJM4CTG.js.map +1 -0
- package/dist/chunk-SEKNVHD3.js +59 -0
- package/dist/chunk-SEKNVHD3.js.map +1 -0
- package/dist/chunk-SIMLMQPT.js +37 -0
- package/dist/chunk-SIMLMQPT.js.map +1 -0
- package/dist/chunk-U56GQITG.js +79 -0
- package/dist/chunk-U56GQITG.js.map +1 -0
- package/dist/chunk-U6AXKGYQ.js +101 -0
- package/dist/chunk-U6AXKGYQ.js.map +1 -0
- package/dist/chunk-VH6FWDWI.js +3 -0
- package/dist/chunk-VH6FWDWI.js.map +1 -0
- package/dist/chunk-XJTJPBJB.js +191 -0
- package/dist/chunk-XJTJPBJB.js.map +1 -0
- package/dist/chunk-Z4PA6C2Z.js +3 -0
- package/dist/chunk-Z4PA6C2Z.js.map +1 -0
- package/dist/client-CqE2dF9A.d.ts +86 -0
- package/dist/consent/index.d.ts +59 -0
- package/dist/consent/index.js +7 -0
- package/dist/consent/index.js.map +1 -0
- package/dist/controller-BQb62D0N.d.ts +177 -0
- package/dist/dynamic/index.d.ts +235 -0
- package/dist/dynamic/index.js +6 -0
- package/dist/dynamic/index.js.map +1 -0
- package/dist/errors-vJkye4a0.d.ts +110 -0
- package/dist/form/index.d.ts +64 -0
- package/dist/form/index.js +5 -0
- package/dist/form/index.js.map +1 -0
- package/dist/index-Dqfa890U.d.ts +83 -0
- package/dist/index.d.ts +16 -2
- package/dist/index.js +18 -2
- package/dist/index.js.map +1 -0
- package/dist/model-ESLSEbi0.d.ts +640 -0
- package/dist/model-mnjAEtKe.d.ts +253 -0
- package/dist/recaptcha/index.d.ts +102 -0
- package/dist/recaptcha/index.js +4 -0
- package/dist/recaptcha/index.js.map +1 -0
- package/dist/render-DC7P2BGQ.js +5 -0
- package/dist/render-DC7P2BGQ.js.map +1 -0
- package/dist/schema-BrXb9gnh.d.ts +267 -0
- package/dist/signup-client-BL5DfarJ.d.ts +392 -0
- package/dist/spec/index.d.ts +17 -0
- package/dist/spec/index.js +5 -0
- package/dist/spec/index.js.map +1 -0
- package/dist/submit/index.d.ts +42 -0
- package/dist/submit/index.js +6 -0
- package/dist/submit/index.js.map +1 -0
- package/dist/viewer/index.d.ts +4 -0
- package/dist/viewer/index.js +5 -0
- package/dist/viewer/index.js.map +1 -0
- package/dist/widget/index.d.ts +262 -0
- package/dist/widget/index.js +12 -0
- package/dist/widget/index.js.map +1 -0
- package/package.json +96 -6
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { fetchDocumentContent } from './chunk-SEKNVHD3.js';
|
|
2
|
+
import createDOMPurify from 'dompurify';
|
|
3
|
+
import { marked } from 'marked';
|
|
4
|
+
|
|
5
|
+
var purifier = null;
|
|
6
|
+
function getPurifier() {
|
|
7
|
+
if (purifier) return purifier;
|
|
8
|
+
const win = globalThis.window ?? globalThis;
|
|
9
|
+
purifier = createDOMPurify(win);
|
|
10
|
+
return purifier;
|
|
11
|
+
}
|
|
12
|
+
var SCROLL_END_EPSILON = 2;
|
|
13
|
+
function clearNode(node) {
|
|
14
|
+
while (node.firstChild) node.removeChild(node.firstChild);
|
|
15
|
+
}
|
|
16
|
+
function boxHasContent(box) {
|
|
17
|
+
if ((box.textContent ?? "").trim().length > 0) return true;
|
|
18
|
+
return box.querySelector("canvas") !== null;
|
|
19
|
+
}
|
|
20
|
+
function makeScrollBox(control, consentKey) {
|
|
21
|
+
const box = document.createElement("div");
|
|
22
|
+
box.className = "nodii-onboarding-consent-scrollbox";
|
|
23
|
+
box.setAttribute("tabindex", "0");
|
|
24
|
+
box.setAttribute("role", "region");
|
|
25
|
+
const report = () => {
|
|
26
|
+
if (!boxHasContent(box)) return;
|
|
27
|
+
if (box.scrollHeight <= 0) return;
|
|
28
|
+
const ratio = box.scrollHeight - box.clientHeight <= 0 ? (
|
|
29
|
+
// Content is present AND genuinely fits without scrolling → "at end".
|
|
30
|
+
1
|
|
31
|
+
) : Math.min(
|
|
32
|
+
1,
|
|
33
|
+
(box.scrollTop + box.clientHeight + SCROLL_END_EPSILON) / box.scrollHeight
|
|
34
|
+
);
|
|
35
|
+
control.reportScrollProgress(consentKey, ratio);
|
|
36
|
+
};
|
|
37
|
+
box.addEventListener("scroll", report);
|
|
38
|
+
return { box, reportScroll: report };
|
|
39
|
+
}
|
|
40
|
+
function isMarkdown(fetched, doc) {
|
|
41
|
+
return fetched.contentType.includes("markdown") || /\.mdx?(\?|#|$)/i.test(doc.downloadUrl);
|
|
42
|
+
}
|
|
43
|
+
var DANGEROUS_TAGS = /* @__PURE__ */ new Set([
|
|
44
|
+
"SCRIPT",
|
|
45
|
+
"IFRAME",
|
|
46
|
+
"OBJECT",
|
|
47
|
+
"EMBED",
|
|
48
|
+
"FORM",
|
|
49
|
+
"STYLE",
|
|
50
|
+
"LINK",
|
|
51
|
+
"META",
|
|
52
|
+
"BASE"
|
|
53
|
+
]);
|
|
54
|
+
function normalizeUrlForSchemeCheck(value) {
|
|
55
|
+
let out = "";
|
|
56
|
+
for (let i = 0; i < value.length; i++) {
|
|
57
|
+
const cp = value.charCodeAt(i);
|
|
58
|
+
if (cp > 32 && cp !== 127) out += value[i];
|
|
59
|
+
}
|
|
60
|
+
return out.toLowerCase();
|
|
61
|
+
}
|
|
62
|
+
var DANGEROUS_URL_SCHEMES = ["javascript:", "vbscript:", "data:text/html"];
|
|
63
|
+
function hardenElement(root) {
|
|
64
|
+
const walker = (node) => {
|
|
65
|
+
const children = Array.from(node.children);
|
|
66
|
+
if (DANGEROUS_TAGS.has(node.tagName)) {
|
|
67
|
+
node.remove();
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
for (const attr of Array.from(node.attributes)) {
|
|
71
|
+
const name = attr.name.toLowerCase();
|
|
72
|
+
const value = normalizeUrlForSchemeCheck(attr.value);
|
|
73
|
+
if (name.startsWith("on")) {
|
|
74
|
+
node.removeAttribute(attr.name);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if ((name === "href" || name === "src" || name === "xlink:href") && DANGEROUS_URL_SCHEMES.some((s) => value.startsWith(s))) {
|
|
78
|
+
node.removeAttribute(attr.name);
|
|
79
|
+
}
|
|
80
|
+
if (name === "srcdoc") node.removeAttribute(attr.name);
|
|
81
|
+
}
|
|
82
|
+
for (const child of children) walker(child);
|
|
83
|
+
};
|
|
84
|
+
for (const child of Array.from(root.children)) walker(child);
|
|
85
|
+
}
|
|
86
|
+
function renderSanitizedHtml(container, control, consentKey, html) {
|
|
87
|
+
clearNode(container);
|
|
88
|
+
const { box, reportScroll } = makeScrollBox(control, consentKey);
|
|
89
|
+
const body = document.createElement("div");
|
|
90
|
+
body.className = "nodii-onboarding-consent-doc-body";
|
|
91
|
+
body.innerHTML = getPurifier().sanitize(html, {
|
|
92
|
+
FORBID_TAGS: ["iframe", "object", "embed", "form"],
|
|
93
|
+
FORBID_ATTR: ["srcdoc"],
|
|
94
|
+
ADD_ATTR: ["target", "rel"]
|
|
95
|
+
});
|
|
96
|
+
hardenElement(body);
|
|
97
|
+
box.appendChild(body);
|
|
98
|
+
container.appendChild(box);
|
|
99
|
+
reportScroll();
|
|
100
|
+
}
|
|
101
|
+
function renderPlainText(container, control, consentKey, text) {
|
|
102
|
+
clearNode(container);
|
|
103
|
+
const { box, reportScroll } = makeScrollBox(control, consentKey);
|
|
104
|
+
const body = document.createElement("div");
|
|
105
|
+
body.className = "nodii-onboarding-consent-doc-body";
|
|
106
|
+
body.textContent = text;
|
|
107
|
+
box.appendChild(body);
|
|
108
|
+
container.appendChild(box);
|
|
109
|
+
reportScroll();
|
|
110
|
+
}
|
|
111
|
+
function renderOpenGateAffordance(container, control, consentKey, doc, note) {
|
|
112
|
+
clearNode(container);
|
|
113
|
+
const link = document.createElement("a");
|
|
114
|
+
link.className = "nodii-onboarding-consent-open";
|
|
115
|
+
link.href = doc.downloadUrl;
|
|
116
|
+
link.target = "_blank";
|
|
117
|
+
link.rel = "noopener noreferrer";
|
|
118
|
+
link.textContent = `Open ${doc.title}`;
|
|
119
|
+
const markOpened = () => control.markOpened(consentKey);
|
|
120
|
+
link.addEventListener("click", markOpened);
|
|
121
|
+
link.addEventListener("keydown", (event) => {
|
|
122
|
+
if (event.key === "Enter") markOpened();
|
|
123
|
+
});
|
|
124
|
+
const row = document.createElement("div");
|
|
125
|
+
row.className = "nodii-onboarding-consent-open-row";
|
|
126
|
+
row.appendChild(link);
|
|
127
|
+
if (note) {
|
|
128
|
+
const noteEl = document.createElement("p");
|
|
129
|
+
noteEl.className = "nodii-onboarding-consent-note";
|
|
130
|
+
noteEl.textContent = note;
|
|
131
|
+
row.appendChild(noteEl);
|
|
132
|
+
}
|
|
133
|
+
container.appendChild(row);
|
|
134
|
+
}
|
|
135
|
+
function renderUnrenderableError(container, doc, onRetry) {
|
|
136
|
+
clearNode(container);
|
|
137
|
+
const wrap = document.createElement("div");
|
|
138
|
+
wrap.className = "nodii-onboarding-consent-unrenderable";
|
|
139
|
+
wrap.setAttribute("role", "alert");
|
|
140
|
+
const msg = document.createElement("p");
|
|
141
|
+
msg.className = "nodii-onboarding-consent-error";
|
|
142
|
+
msg.textContent = `\u201C${doc.title}\u201D could not be loaded, so it cannot be accepted yet. Please retry; if it keeps failing, contact support.`;
|
|
143
|
+
wrap.appendChild(msg);
|
|
144
|
+
const retry = document.createElement("button");
|
|
145
|
+
retry.type = "button";
|
|
146
|
+
retry.className = "nodii-onboarding-consent-retry";
|
|
147
|
+
retry.textContent = "Retry loading document";
|
|
148
|
+
retry.addEventListener("click", onRetry);
|
|
149
|
+
wrap.appendChild(retry);
|
|
150
|
+
const link = document.createElement("a");
|
|
151
|
+
link.className = "nodii-onboarding-consent-open";
|
|
152
|
+
link.href = doc.downloadUrl;
|
|
153
|
+
link.target = "_blank";
|
|
154
|
+
link.rel = "noopener noreferrer";
|
|
155
|
+
link.textContent = `Open ${doc.title} in a new tab`;
|
|
156
|
+
wrap.appendChild(link);
|
|
157
|
+
container.appendChild(wrap);
|
|
158
|
+
}
|
|
159
|
+
async function renderPdf(container, control, consentKey, doc, blob, onRetry) {
|
|
160
|
+
const fail = () => handleRenderFailure(container, control, consentKey, doc, onRetry);
|
|
161
|
+
let pdfjs;
|
|
162
|
+
try {
|
|
163
|
+
pdfjs = await import('pdfjs-dist');
|
|
164
|
+
} catch {
|
|
165
|
+
return fail();
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
configurePdfWorker(pdfjs);
|
|
169
|
+
const data = new Uint8Array(await blob.arrayBuffer());
|
|
170
|
+
const pdf = await pdfjs.getDocument({ data }).promise;
|
|
171
|
+
const body = document.createElement("div");
|
|
172
|
+
body.className = "nodii-onboarding-consent-doc-body nodii-consent-pdf";
|
|
173
|
+
for (let pageNo = 1; pageNo <= pdf.numPages; pageNo++) {
|
|
174
|
+
const page = await pdf.getPage(pageNo);
|
|
175
|
+
const viewport = page.getViewport({ scale: 1.2 });
|
|
176
|
+
const canvas = document.createElement("canvas");
|
|
177
|
+
canvas.className = "nodii-consent-pdf-page";
|
|
178
|
+
canvas.width = Math.ceil(viewport.width);
|
|
179
|
+
canvas.height = Math.ceil(viewport.height);
|
|
180
|
+
const ctx = canvas.getContext("2d");
|
|
181
|
+
if (ctx) {
|
|
182
|
+
await page.render({ canvas, canvasContext: ctx, viewport }).promise;
|
|
183
|
+
}
|
|
184
|
+
body.appendChild(canvas);
|
|
185
|
+
}
|
|
186
|
+
if (typeof container.isConnected === "boolean" && !container.isConnected) {
|
|
187
|
+
return { renderedAs: "unrenderable" };
|
|
188
|
+
}
|
|
189
|
+
if (body.childElementCount === 0) return fail();
|
|
190
|
+
clearNode(container);
|
|
191
|
+
const { box, reportScroll } = makeScrollBox(control, consentKey);
|
|
192
|
+
box.appendChild(body);
|
|
193
|
+
container.appendChild(box);
|
|
194
|
+
reportScroll();
|
|
195
|
+
return { renderedAs: "pdf" };
|
|
196
|
+
} catch {
|
|
197
|
+
return fail();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
var pdfWorkerConfigured = false;
|
|
201
|
+
function resolvePackagedWorkerUrl() {
|
|
202
|
+
const WORKER_SPEC = "pdfjs-dist/build/pdf.worker.min.mjs";
|
|
203
|
+
const meta = import.meta;
|
|
204
|
+
if (typeof meta.resolve === "function") {
|
|
205
|
+
try {
|
|
206
|
+
const resolved = meta.resolve(WORKER_SPEC);
|
|
207
|
+
if (resolved) return resolved;
|
|
208
|
+
} catch {
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
return new URL(WORKER_SPEC, import.meta.url).href;
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function configurePdfWorker(pdfjs) {
|
|
218
|
+
if (pdfWorkerConfigured) return;
|
|
219
|
+
const opts = pdfjs.GlobalWorkerOptions;
|
|
220
|
+
if (opts.workerPort || opts.workerSrc) {
|
|
221
|
+
pdfWorkerConfigured = true;
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const packagedUrl = resolvePackagedWorkerUrl();
|
|
225
|
+
if (packagedUrl) {
|
|
226
|
+
opts.workerSrc = packagedUrl;
|
|
227
|
+
} else {
|
|
228
|
+
const version = pdfjs.version ?? "";
|
|
229
|
+
opts.workerSrc = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${version}/build/pdf.worker.min.mjs`;
|
|
230
|
+
}
|
|
231
|
+
pdfWorkerConfigured = true;
|
|
232
|
+
}
|
|
233
|
+
function handleRenderFailure(container, control, consentKey, doc, onRetry) {
|
|
234
|
+
if (doc.acceptanceLevel === "open_then_accept") {
|
|
235
|
+
renderOpenGateAffordance(
|
|
236
|
+
container,
|
|
237
|
+
control,
|
|
238
|
+
consentKey,
|
|
239
|
+
doc,
|
|
240
|
+
"The inline preview is unavailable. Opening the document in a new tab satisfies this step."
|
|
241
|
+
);
|
|
242
|
+
return { renderedAs: "open-affordance" };
|
|
243
|
+
}
|
|
244
|
+
renderUnrenderableError(container, doc, onRetry);
|
|
245
|
+
return { renderedAs: "unrenderable" };
|
|
246
|
+
}
|
|
247
|
+
async function renderConsentDocument(container, doc, control, options) {
|
|
248
|
+
const { consentKey } = options;
|
|
249
|
+
const onRetry = () => {
|
|
250
|
+
void renderConsentDocument(container, doc, control, options);
|
|
251
|
+
};
|
|
252
|
+
let fetched;
|
|
253
|
+
try {
|
|
254
|
+
fetched = await fetchDocumentContent(doc, {
|
|
255
|
+
fetch: options.fetch,
|
|
256
|
+
timeoutMs: options.timeoutMs
|
|
257
|
+
});
|
|
258
|
+
} catch {
|
|
259
|
+
return handleRenderFailure(container, control, consentKey, doc, onRetry);
|
|
260
|
+
}
|
|
261
|
+
if (typeof container.isConnected === "boolean" && !container.isConnected) {
|
|
262
|
+
return { renderedAs: "unrenderable" };
|
|
263
|
+
}
|
|
264
|
+
if (doc.acceptanceLevel === "open_then_accept") {
|
|
265
|
+
renderOpenGateAffordance(
|
|
266
|
+
container,
|
|
267
|
+
control,
|
|
268
|
+
consentKey,
|
|
269
|
+
doc,
|
|
270
|
+
"Open the document in a new tab to review it \u2014 that satisfies this step."
|
|
271
|
+
);
|
|
272
|
+
return { renderedAs: "open-affordance" };
|
|
273
|
+
}
|
|
274
|
+
if (fetched.kind === "pdf" && fetched.blob) {
|
|
275
|
+
return renderPdf(
|
|
276
|
+
container,
|
|
277
|
+
control,
|
|
278
|
+
consentKey,
|
|
279
|
+
doc,
|
|
280
|
+
fetched.blob,
|
|
281
|
+
onRetry
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
if (fetched.kind === "binary") {
|
|
285
|
+
return handleRenderFailure(container, control, consentKey, doc, onRetry);
|
|
286
|
+
}
|
|
287
|
+
const text = fetched.text ?? "";
|
|
288
|
+
if (isMarkdown(fetched, doc)) {
|
|
289
|
+
const html = await marked.parse(text, { async: true });
|
|
290
|
+
renderSanitizedHtml(container, control, consentKey, html);
|
|
291
|
+
return { renderedAs: "markdown" };
|
|
292
|
+
}
|
|
293
|
+
if (fetched.kind === "html") {
|
|
294
|
+
renderSanitizedHtml(container, control, consentKey, text);
|
|
295
|
+
return { renderedAs: "html" };
|
|
296
|
+
}
|
|
297
|
+
renderPlainText(container, control, consentKey, text);
|
|
298
|
+
return { renderedAs: "text" };
|
|
299
|
+
}
|
|
300
|
+
function _resetPdfWorkerState() {
|
|
301
|
+
pdfWorkerConfigured = false;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export { _resetPdfWorkerState, renderConsentDocument };
|
|
305
|
+
//# sourceMappingURL=chunk-LVJM4CTG.js.map
|
|
306
|
+
//# sourceMappingURL=chunk-LVJM4CTG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/viewer/render.ts"],"names":[],"mappings":";;;;AAgDA,IAAI,QAAA,GAAsD,IAAA;AAC1D,SAAS,WAAA,GAAkD;AACzD,EAAA,IAAI,UAAU,OAAO,QAAA;AACrB,EAAA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O,SAAS,oBAAA,GAA6B;AAC3C,EAAA,mBAAA,GAAsB,KAAA;AACxB","file":"chunk-LVJM4CTG.js","sourcesContent":["/**\n * Default ConsentPack document viewer (D543 §5) — @nodii/onboarding/viewer.\n *\n * A SEPARATE, opt-in module built on STANDARD libraries so the base SDK stays\n * lean: consumers only pay for the viewer if they render our default consent\n * components. The headless controller (@nodii/onboarding/consent) knows nothing\n * about this — it just receives reportScrollProgress / markScrolledToEnd /\n * markOpened from whatever renders the doc.\n *\n * Renderers (per fetched artifact — NO IFRAME anywhere; everything is inline,\n * same-origin, so `scroll_then_accept` scroll tracking is REAL):\n * - text/html → sanitize with DOMPurify, inject into a scroll <div>.\n * - markdown → marked → DOMPurify → inject into a scroll <div>.\n * - text/plain → escaped text (textContent) in a scroll <div>.\n * - application/pdf → PDF.js (pdfjs-dist), rendered to <canvas> + a text\n * layer, page by page, in a scroll <div>. PDF.js is LAZY-loaded via a\n * dynamic import() ONLY when a PDF doc is actually present, so it never\n * bloats the base bundle.\n *\n * The scroll container's scroll-to-end (and the PDF/open fallbacks) drive the\n * consent controller so the gate works for real. A failed fetch/render\n * degrades to an \"open in a new tab\" affordance (marks the doc opened /\n * scrolled) so every doc stays consentable.\n *\n * Bundle discipline: DOMPurify + marked are imported at module top (this is\n * the VIEWER entry, not the base SDK — the base `@nodii/onboarding` never\n * statically imports this file). pdfjs-dist is imported ONLY via dynamic\n * import() inside renderPdf, so even the viewer entry doesn't eagerly load it.\n */\n\nimport createDOMPurify from \"dompurify\";\nimport { marked } from \"marked\";\nimport type { ConsentController } from \"../consent/controller.js\";\nimport type { ConsentDocument } from \"../consent/model.js\";\nimport {\n fetchDocumentContent,\n type FetchedConsentDocument,\n} from \"../consent/document.js\";\n\n/**\n * DOMPurify bound to the current window. The default import is BOTH a\n * pre-bound instance AND a factory `(window) => instance`. Binding it\n * explicitly to `globalThis` (which happy-dom / a real browser populate with\n * `window`) guarantees a working DOM even in environments where DOMPurify's\n * implicit global detection misfires (e.g. bun + happy-dom under test), where\n * an unbound instance silently passes HTML through UN-sanitized. Lazily\n * memoized so we only bind once.\n */\nlet purifier: ReturnType<typeof createDOMPurify> | null = null;\nfunction getPurifier(): ReturnType<typeof createDOMPurify> {\n if (purifier) return purifier;\n const win = (globalThis as { window?: unknown }).window ?? globalThis;\n // createDOMPurify is callable as a factory; when the arg is a window-like\n // object it returns an instance bound to it.\n purifier = (\n createDOMPurify as unknown as (\n w: unknown,\n ) => ReturnType<typeof createDOMPurify>\n )(win);\n return purifier;\n}\n\nexport interface ConsentDocumentViewerOptions {\n /** Injectable fetch for the presigned artifact GET (defaults to global). */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout in ms (default from fetchDocumentContent). */\n timeoutMs?: number;\n /**\n * The `key` the controller identifies this document by (doc_type |\n * custom:<key>). The viewer reports scroll/open evidence under this key.\n */\n consentKey: string;\n}\n\n/** Result of rendering — lets the caller know how the doc was displayed. */\nexport interface ConsentDocumentViewerResult {\n /**\n * How the artifact was rendered.\n *\n * - html | markdown | text | pdf → rendered inline (gate is driven by real\n * scroll/open).\n * - open-affordance → an `open_then_accept` doc that opens in a new tab (the\n * real-open IS its gate; satisfies ONLY `opened`).\n * - unrenderable → a GATED doc (scroll_then_accept) that could NOT be\n * rendered inline. The gate stays UNSATISFIABLE — accept is disabled and a\n * clear error is shown. NO evidence is ever fabricated (COMPLIANCE, D543).\n */\n renderedAs:\n \"html\" | \"markdown\" | \"text\" | \"pdf\" | \"open-affordance\" | \"unrenderable\";\n}\n\nconst SCROLL_END_EPSILON = 2;\n\nfunction clearNode(node: HTMLElement): void {\n while (node.firstChild) node.removeChild(node.firstChild);\n}\n\n/**\n * Does the box hold ACTUAL readable rendered content? A \"content fits without\n * scrolling\" ratio of 1 is only legitimate when there is genuinely something to\n * have read. Content = non-empty text (HTML/markdown/text render) OR at least\n * one rendered PDF page canvas. A bare wrapper `<div>` with empty text is NOT\n * content — so an empty-artifact doc (e.g. a 0-byte or all-whitespace body, or\n * a not-yet-populated box) can NEVER satisfy the gate. This is the P0a\n * by-construction guarantee: the ratio-1 branch depends on rendered-content\n * presence, not on geometry a headless runtime cannot measure — fabrication is\n * impossible in EVERY runtime.\n */\nfunction boxHasContent(box: HTMLElement): boolean {\n if ((box.textContent ?? \"\").trim().length > 0) return true;\n // PDF pages carry no text — a rendered page canvas counts as content.\n return box.querySelector(\"canvas\") !== null;\n}\n\n/**\n * A scroll <div> that reports scroll progress to the controller. Returns the\n * box AND a `reportScroll` fn the caller MUST invoke ONLY AFTER real content is\n * appended — never at creation. `report` refuses to satisfy the \"fits without\n * scrolling\" case unless the box actually holds content, so an empty or\n * pre-render box can never latch scrolled_to_end (P0a — by construction).\n */\nfunction makeScrollBox(\n control: ConsentController,\n consentKey: string,\n): { box: HTMLDivElement; reportScroll: () => void } {\n const box = document.createElement(\"div\");\n box.className = \"nodii-onboarding-consent-scrollbox\";\n box.setAttribute(\"tabindex\", \"0\");\n box.setAttribute(\"role\", \"region\");\n const report = (): void => {\n // COMPLIANCE (P0a): an empty / not-yet-rendered box can NEVER satisfy the\n // gate — there is nothing to have read. This holds in EVERY runtime,\n // independent of scroll geometry (which a headless DOM cannot measure).\n if (!boxHasContent(box)) return;\n // Unmeasured container (no layout yet / happy-dom) → do NOT report a\n // fits-without-scroll: scrollHeight 0 is not evidence the user reached the\n // end. A real scroll event still reports its measured ratio.\n if (box.scrollHeight <= 0) return;\n const ratio =\n box.scrollHeight - box.clientHeight <= 0\n ? // Content is present AND genuinely fits without scrolling → \"at end\".\n 1\n : Math.min(\n 1,\n (box.scrollTop + box.clientHeight + SCROLL_END_EPSILON) /\n box.scrollHeight,\n );\n control.reportScrollProgress(consentKey, ratio);\n };\n box.addEventListener(\"scroll\", report);\n // NOTE: no report is scheduled at creation. The caller invokes reportScroll()\n // AFTER content is appended (short-doc auto-unlock then only fires with\n // content present). This is what makes P0a a construction guarantee.\n return { box, reportScroll: report };\n}\n\n/** Detect markdown by content-type or a .md-looking downloadUrl. */\nfunction isMarkdown(\n fetched: FetchedConsentDocument,\n doc: Pick<ConsentDocument, \"downloadUrl\">,\n): boolean {\n return (\n fetched.contentType.includes(\"markdown\") ||\n /\\.mdx?(\\?|#|$)/i.test(doc.downloadUrl)\n );\n}\n\n/** Tags that must never survive into the rendered consent document. */\nconst DANGEROUS_TAGS = new Set([\n \"SCRIPT\",\n \"IFRAME\",\n \"OBJECT\",\n \"EMBED\",\n \"FORM\",\n \"STYLE\",\n \"LINK\",\n \"META\",\n \"BASE\",\n]);\n\n/**\n * Defense-in-depth pass AFTER DOMPurify: walk the parsed DOM and remove any\n * dangerous element, every on* event-handler attribute, and javascript:/data:\n * URLs. DOMPurify is the primary, audited sanitizer, but this deterministic\n * DOM walk (a) hardens against any DOMPurify config gap and (b) is provably\n * correct in EVERY runtime — including ones where DOMPurify's own DOM-based\n * pass is a no-op (e.g. certain SSR/test DOMs). Belt-and-suspenders, not a\n * hand-rolled replacement for DOMPurify.\n */\n/**\n * Normalize a URL for scheme inspection the way a browser does BEFORE\n * resolving it: strip ALL ASCII whitespace and control characters (code\n * points <= 0x20, plus DEL 0x7F) anywhere in the string, not just the ends.\n * Browsers ignore these inside a URL, so a scheme split by an embedded tab/\n * newline/NUL (e.g. jav<TAB>ascript:) still executes; a mere .trim() leaves\n * the embedded ones and the startsWith('javascript:') check is bypassed.\n * Char-code filtering avoids embedding literal control bytes in a regex.\n */\nfunction normalizeUrlForSchemeCheck(value: string): string {\n let out = \"\";\n for (let i = 0; i < value.length; i++) {\n const cp = value.charCodeAt(i);\n if (cp > 0x20 && cp !== 0x7f) out += value[i];\n }\n return out.toLowerCase();\n}\n\nconst DANGEROUS_URL_SCHEMES = [\"javascript:\", \"vbscript:\", \"data:text/html\"];\n\nfunction hardenElement(root: HTMLElement): void {\n const walker = (node: Element): void => {\n // Copy children first — removal mutates the live list.\n const children = Array.from(node.children);\n if (DANGEROUS_TAGS.has(node.tagName)) {\n node.remove();\n return;\n }\n for (const attr of Array.from(node.attributes)) {\n const name = attr.name.toLowerCase();\n // Whitespace/control-stripped, lower-cased value for scheme inspection.\n const value = normalizeUrlForSchemeCheck(attr.value);\n if (name.startsWith(\"on\")) {\n node.removeAttribute(attr.name);\n continue;\n }\n if (\n (name === \"href\" || name === \"src\" || name === \"xlink:href\") &&\n DANGEROUS_URL_SCHEMES.some((s) => value.startsWith(s))\n ) {\n node.removeAttribute(attr.name);\n }\n if (name === \"srcdoc\") node.removeAttribute(attr.name);\n }\n for (const child of children) walker(child);\n };\n for (const child of Array.from(root.children)) walker(child);\n}\n\n/** Render sanitized HTML inline into a scroll box. */\nfunction renderSanitizedHtml(\n container: HTMLElement,\n control: ConsentController,\n consentKey: string,\n html: string,\n): void {\n clearNode(container);\n const { box, reportScroll } = makeScrollBox(control, consentKey);\n const body = document.createElement(\"div\");\n body.className = \"nodii-onboarding-consent-doc-body\";\n // Primary: DOMPurify (the standard, audited Cure53 sanitizer). FORBID_TAGS\n // on <iframe>/<object>/<embed>/<form> so a doc can't smuggle a frame in.\n body.innerHTML = getPurifier().sanitize(html, {\n FORBID_TAGS: [\"iframe\", \"object\", \"embed\", \"form\"],\n FORBID_ATTR: [\"srcdoc\"],\n ADD_ATTR: [\"target\", \"rel\"],\n });\n // Defense-in-depth: a deterministic DOM walk that removes any residual\n // dangerous node/attr, correct in every runtime (see hardenElement).\n hardenElement(body);\n box.appendChild(body);\n container.appendChild(box);\n // Content is now IN the box → the short-doc auto-unlock may fire (P0a: report\n // ONLY after content is present, never at box creation).\n reportScroll();\n}\n\n/** Render escaped plain text inline into a scroll box. */\nfunction renderPlainText(\n container: HTMLElement,\n control: ConsentController,\n consentKey: string,\n text: string,\n): void {\n clearNode(container);\n const { box, reportScroll } = makeScrollBox(control, consentKey);\n const body = document.createElement(\"div\");\n body.className = \"nodii-onboarding-consent-doc-body\";\n body.textContent = text; // safe-by-construction (no markup interpretation)\n box.appendChild(body);\n container.appendChild(box);\n reportScroll(); // only after content is present (P0a)\n}\n\n/**\n * The LEGITIMATE gate affordance for an `open_then_accept` doc: an open-in-new\n * tab link. Opening the doc in a new tab IS the gate for this level, so a REAL\n * navigation satisfies ONLY `opened` (never `scrolled_to_end`). A native\n * <a target=\"_blank\"> navigates on click AND on Enter (keyboard activation of\n * an anchor) — we mark `opened` on those, which correspond to a real open. We\n * do NOT bind Space (Space does not activate an anchor → no navigation → no\n * open → must not mark opened; binding it would fabricate evidence).\n *\n * This is used both as the primary affordance for open_then_accept and as the\n * failure fallback for open_then_accept when inline preview is unavailable —\n * either way the gate is genuinely the real open.\n */\nfunction renderOpenGateAffordance(\n container: HTMLElement,\n control: ConsentController,\n consentKey: string,\n doc: Pick<ConsentDocument, \"downloadUrl\" | \"title\">,\n note?: string,\n): void {\n clearNode(container);\n const link = document.createElement(\"a\");\n link.className = \"nodii-onboarding-consent-open\";\n link.href = doc.downloadUrl;\n link.target = \"_blank\";\n link.rel = \"noopener noreferrer\";\n link.textContent = `Open ${doc.title}`;\n // Mark opened ONLY on real activation of the anchor (click / Enter). No\n // Space handler — Space does not navigate an <a>, so it is not a real open.\n const markOpened = (): void => control.markOpened(consentKey);\n link.addEventListener(\"click\", markOpened);\n link.addEventListener(\"keydown\", (event) => {\n if ((event as KeyboardEvent).key === \"Enter\") markOpened();\n });\n const row = document.createElement(\"div\");\n row.className = \"nodii-onboarding-consent-open-row\";\n row.appendChild(link);\n if (note) {\n const noteEl = document.createElement(\"p\");\n noteEl.className = \"nodii-onboarding-consent-note\";\n noteEl.textContent = note;\n row.appendChild(noteEl);\n }\n container.appendChild(row);\n}\n\n/**\n * COMPLIANCE-CRITICAL (P0, D543): a GATED doc whose acceptance requires SEEING\n * the content inline (scroll_then_accept) could NOT be rendered inline (fetch\n * failure, expired presigned URL, CORS, octet-stream, PDF.js failure, viewer\n * unavailable). The gate MUST stay UNSATISFIABLE — the SDK NEVER fabricates\n * `scrolled_to_end` on a mere click. Render a clear error + a Retry, and an\n * \"Open in a new tab\" link that is INFORMATIONAL ONLY (it does NOT satisfy the\n * scroll gate — reading in a new tab is not evidence the user scrolled the\n * rendered doc to the end for this level). Accept stays disabled; the operator\n * must fix the artifact/URL for this doc to become acceptable.\n */\nfunction renderUnrenderableError(\n container: HTMLElement,\n doc: Pick<ConsentDocument, \"downloadUrl\" | \"title\">,\n onRetry: () => void,\n): void {\n clearNode(container);\n const wrap = document.createElement(\"div\");\n wrap.className = \"nodii-onboarding-consent-unrenderable\";\n wrap.setAttribute(\"role\", \"alert\");\n\n const msg = document.createElement(\"p\");\n msg.className = \"nodii-onboarding-consent-error\";\n msg.textContent = `“${doc.title}” could not be loaded, so it cannot be accepted yet. Please retry; if it keeps failing, contact support.`;\n wrap.appendChild(msg);\n\n const retry = document.createElement(\"button\");\n retry.type = \"button\";\n retry.className = \"nodii-onboarding-consent-retry\";\n retry.textContent = \"Retry loading document\";\n retry.addEventListener(\"click\", onRetry);\n wrap.appendChild(retry);\n\n // Informational only — opening in a new tab does NOT satisfy the scroll gate.\n const link = document.createElement(\"a\");\n link.className = \"nodii-onboarding-consent-open\";\n link.href = doc.downloadUrl;\n link.target = \"_blank\";\n link.rel = \"noopener noreferrer\";\n link.textContent = `Open ${doc.title} in a new tab`;\n wrap.appendChild(link);\n\n container.appendChild(wrap);\n}\n\n/**\n * Render a PDF via PDF.js into a scroll box (canvas per page). pdfjs-dist is\n * LAZY-loaded here (dynamic import) so it never enters the base bundle. On any\n * failure (import/worker/CSP/parse/zero-page), route through handleRenderFailure\n * — for a scroll_then_accept doc that is UNRENDERABLE (gate stays unsatisfiable,\n * never fabricated); for open_then_accept it is the real-open affordance (P0).\n * The scroll box is only attached (and progress only reported) AFTER pages are\n * rendered, so an empty/pre-render box can never satisfy the gate (P0a).\n */\nasync function renderPdf(\n container: HTMLElement,\n control: ConsentController,\n consentKey: string,\n doc: ConsentDocument,\n blob: Blob,\n onRetry: () => void,\n): Promise<ConsentDocumentViewerResult> {\n const fail = (): ConsentDocumentViewerResult =>\n handleRenderFailure(container, control, consentKey, doc, onRetry);\n\n let pdfjs: typeof import(\"pdfjs-dist\");\n try {\n pdfjs = await import(\"pdfjs-dist\");\n } catch {\n return fail();\n }\n\n try {\n // Configure the worker so getDocument does not reject on\n // \"No GlobalWorkerOptions.workerSrc specified\" (pdfjs-dist v6). Resolve the\n // packaged worker via a bundler-friendly URL; if that fails, fall back to\n // the CDN for the exact installed version (never leaves the worker unset).\n configurePdfWorker(pdfjs);\n const data = new Uint8Array(await blob.arrayBuffer());\n const pdf = await pdfjs.getDocument({ data }).promise;\n\n // Render EVERY page into a DETACHED body FIRST — the scroll box is not put\n // into the container (and reportScroll is not called) until real content is\n // present (P0a: an empty/pre-render box can never satisfy the gate, even in\n // a real browser where an empty 360px box measures scrollHeight==clientH).\n const body = document.createElement(\"div\");\n body.className = \"nodii-onboarding-consent-doc-body nodii-consent-pdf\";\n for (let pageNo = 1; pageNo <= pdf.numPages; pageNo++) {\n const page = await pdf.getPage(pageNo);\n const viewport = page.getViewport({ scale: 1.2 });\n const canvas = document.createElement(\"canvas\");\n canvas.className = \"nodii-consent-pdf-page\";\n canvas.width = Math.ceil(viewport.width);\n canvas.height = Math.ceil(viewport.height);\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n await page.render({ canvas, canvasContext: ctx, viewport }).promise;\n }\n body.appendChild(canvas);\n }\n\n // Lifecycle guard: if the container was detached while we awaited the PDF\n // (stage re-render / unmount / a Retry started a fresh render), abandon —\n // don't mutate an orphaned tree or fight a concurrent render (P2 lifecycle).\n if (typeof container.isConnected === \"boolean\" && !container.isConnected) {\n return { renderedAs: \"unrenderable\" };\n }\n // A zero-page or all-empty PDF has no readable content → treat as a render\n // failure (never satisfy a gate on an empty box).\n if (body.childElementCount === 0) return fail();\n\n clearNode(container);\n const { box, reportScroll } = makeScrollBox(control, consentKey);\n box.appendChild(body);\n container.appendChild(box);\n // Content is now present → the short-PDF auto-unlock may fire (P0a).\n reportScroll();\n return { renderedAs: \"pdf\" };\n } catch {\n return fail();\n }\n}\n\n/** Whether pdfjs already has a worker configured this session. */\nlet pdfWorkerConfigured = false;\n\ninterface WorkerGlobalOptions {\n workerSrc?: string;\n workerPort?: unknown;\n}\n\n/**\n * Resolve the packaged pdf worker module to a LOADABLE URL, robust across\n * runtimes:\n * 1. `import.meta.resolve(...)` — real module resolution (Node/bun ESM);\n * resolves through node_modules to the actual file (the plain\n * `new URL(spec, import.meta.url)` does NOT — it's relative to THIS file,\n * which 404s, the exact P2 dead-fallback bug).\n * 2. `new URL(\"pdfjs-dist/build/pdf.worker.min.mjs\", import.meta.url)` — a\n * bundler (Vite/webpack/tsup) rewrites this to the emitted asset URL.\n * Returns null if neither yields a URL (→ caller falls back to the CDN).\n */\nfunction resolvePackagedWorkerUrl(): string | null {\n const WORKER_SPEC = \"pdfjs-dist/build/pdf.worker.min.mjs\";\n const meta = import.meta as ImportMeta & {\n resolve?: (spec: string) => string;\n };\n if (typeof meta.resolve === \"function\") {\n try {\n const resolved = meta.resolve(WORKER_SPEC);\n if (resolved) return resolved;\n } catch {\n // fall through to the bundler-rewrite form\n }\n }\n try {\n return new URL(WORKER_SPEC, import.meta.url).href;\n } catch {\n return null;\n }\n}\n\n/**\n * Ensure pdfjs has a LOADABLE worker before getDocument (P2). Real pdfjs-dist\n * v6 rejects getDocument without one, and merely SETTING `workerSrc` is not the\n * same as the worker LOADING: the naive `new URL('pdfjs-dist/build/...',\n * import.meta.url)` resolves RELATIVE TO THIS MODULE (not through\n * node_modules), so it points at a path that 404s at load — the dead-fallback\n * bug P2 flags. We resolve the worker to a genuinely-loadable URL instead\n * (`import.meta.resolve` → real module resolution; else the bundler-rewrite\n * `new URL` form; else the version-pinned CDN).\n *\n * We set `workerSrc` (not `workerPort`): a resolved file/asset/CDN URL loads in\n * BOTH a real browser (bundler-served or CDN) AND Node/bun (resolved file\n * path) — proven by the [P2] real-pdfjs test which renders a real PDF with the\n * worker configured here and NO pre-set workerSrc. If the worker still can't\n * load (offline + unresolvable), getDocument rejects and the caller degrades\n * to `unrenderable` — a gated PDF that can't render stays unacceptable, NEVER\n * fabricated (P0). Idempotent per session.\n */\nfunction configurePdfWorker(pdfjs: typeof import(\"pdfjs-dist\")): void {\n if (pdfWorkerConfigured) return;\n const opts = pdfjs.GlobalWorkerOptions as WorkerGlobalOptions;\n // A consumer (or a prior call) already wired a worker → respect it.\n if (opts.workerPort || opts.workerSrc) {\n pdfWorkerConfigured = true;\n return;\n }\n\n const packagedUrl = resolvePackagedWorkerUrl();\n if (packagedUrl) {\n opts.workerSrc = packagedUrl;\n } else {\n // Last resort: version-pinned CDN so a build that can't resolve the asset\n // still gets a real worker rather than silently failing every PDF.\n const version = (pdfjs as { version?: string }).version ?? \"\";\n opts.workerSrc = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${version}/build/pdf.worker.min.mjs`;\n }\n pdfWorkerConfigured = true;\n}\n\n/**\n * COMPLIANCE-CRITICAL failure router (P0): a doc could not be rendered inline.\n * - open_then_accept → the real-open affordance (opening IS its gate; satisfies\n * ONLY `opened`). This is legitimate, not a fabrication.\n * - scroll_then_accept → UNRENDERABLE: the gate stays unsatisfiable, a clear\n * error + Retry is shown, accept is disabled. NEVER fabricate scrolled_to_end.\n * - checkbox → no gate (already satisfiable): show the error + a plain open link\n * for reference; accept remains enabled (the checkbox gate needs no evidence).\n */\nfunction handleRenderFailure(\n container: HTMLElement,\n control: ConsentController,\n consentKey: string,\n doc: ConsentDocument,\n onRetry: () => void,\n): ConsentDocumentViewerResult {\n if (doc.acceptanceLevel === \"open_then_accept\") {\n renderOpenGateAffordance(\n container,\n control,\n consentKey,\n doc,\n \"The inline preview is unavailable. Opening the document in a new tab satisfies this step.\",\n );\n return { renderedAs: \"open-affordance\" };\n }\n // scroll_then_accept (and checkbox — harmless there): show the error. For a\n // scroll gate this leaves it UNSATISFIABLE (accept stays disabled).\n renderUnrenderableError(container, doc, onRetry);\n return { renderedAs: \"unrenderable\" };\n}\n\n/**\n * Fetch + render a consent document INLINE into `container`, wiring its scroll\n * container (or the legitimate open-affordance) to the consent controller so\n * `scroll_then_accept` / `open_then_accept` gates work for real. NO iframe.\n *\n * On ANY inline-render failure for a `scroll_then_accept` doc the gate stays\n * UNSATISFIABLE (never fabricates scrolled_to_end, D543 §5 COMPLIANCE) — the\n * caller's Retry re-invokes this.\n *\n * @returns how the doc was rendered (for the caller's telemetry/UX).\n */\nexport async function renderConsentDocument(\n container: HTMLElement,\n doc: ConsentDocument,\n control: ConsentController,\n options: ConsentDocumentViewerOptions,\n): Promise<ConsentDocumentViewerResult> {\n const { consentKey } = options;\n const onRetry = (): void => {\n void renderConsentDocument(container, doc, control, options);\n };\n\n let fetched: FetchedConsentDocument;\n try {\n fetched = await fetchDocumentContent(doc, {\n fetch: options.fetch,\n timeoutMs: options.timeoutMs,\n });\n } catch {\n return handleRenderFailure(container, control, consentKey, doc, onRetry);\n }\n\n // If the container was detached while we awaited the fetch (the consent stage\n // re-rendered, or the widget unmounted), skip DOM work — a stale render must\n // not mutate an orphaned node or leak an unhandled error.\n if (typeof container.isConnected === \"boolean\" && !container.isConnected) {\n return { renderedAs: \"unrenderable\" };\n }\n\n // open_then_accept: opening the doc in a new tab IS the gate — scrolling an\n // inline render does NOT satisfy it (reportScrollProgress no-ops for this\n // level). So on a SUCCESSFUL fetch we ALSO present the open affordance (which\n // marks `opened` on a real open) so the gate is satisfiable through the\n // default viewer (P1). We do not attempt an inline scroll gate here.\n if (doc.acceptanceLevel === \"open_then_accept\") {\n renderOpenGateAffordance(\n container,\n control,\n consentKey,\n doc,\n \"Open the document in a new tab to review it — that satisfies this step.\",\n );\n return { renderedAs: \"open-affordance\" };\n }\n\n if (fetched.kind === \"pdf\" && fetched.blob) {\n return renderPdf(\n container,\n control,\n consentKey,\n doc,\n fetched.blob,\n onRetry,\n );\n }\n if (fetched.kind === \"binary\") {\n // A binary/octet-stream artifact cannot be previewed inline → same\n // compliance rule: gated docs stay unsatisfiable, never click-to-satisfy.\n return handleRenderFailure(container, control, consentKey, doc, onRetry);\n }\n // text or html\n const text = fetched.text ?? \"\";\n if (isMarkdown(fetched, doc)) {\n const html = await marked.parse(text, { async: true });\n renderSanitizedHtml(container, control, consentKey, html);\n return { renderedAs: \"markdown\" };\n }\n if (fetched.kind === \"html\") {\n renderSanitizedHtml(container, control, consentKey, text);\n return { renderedAs: \"html\" };\n }\n renderPlainText(container, control, consentKey, text);\n return { renderedAs: \"text\" };\n}\n\n/** Reset the module-level pdf-worker latch (tests). */\nexport function _resetPdfWorkerState(): void {\n pdfWorkerConfigured = false;\n}\n"]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { OnboardingError, DEFAULT_REQUEST_TIMEOUT_MS, fetchWithTimeout } from './chunk-XJTJPBJB.js';
|
|
2
|
+
|
|
3
|
+
// src/consent/document.ts
|
|
4
|
+
var OnboardingDocumentFetchError = class extends OnboardingError {
|
|
5
|
+
url;
|
|
6
|
+
constructor(url, detail) {
|
|
7
|
+
super(
|
|
8
|
+
"network_error",
|
|
9
|
+
`Failed to fetch consent document from "${url}": ${detail}`,
|
|
10
|
+
null
|
|
11
|
+
);
|
|
12
|
+
this.name = "OnboardingDocumentFetchError";
|
|
13
|
+
this.url = url;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
function classify(contentType) {
|
|
17
|
+
if (contentType.includes("application/pdf")) return "pdf";
|
|
18
|
+
if (contentType.includes("text/html")) return "html";
|
|
19
|
+
if (contentType.startsWith("text/")) return "text";
|
|
20
|
+
return "binary";
|
|
21
|
+
}
|
|
22
|
+
async function fetchDocumentContent(doc, options = {}) {
|
|
23
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
24
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
25
|
+
const url = doc.downloadUrl;
|
|
26
|
+
let response;
|
|
27
|
+
try {
|
|
28
|
+
response = await fetchWithTimeout(url, {
|
|
29
|
+
method: "GET",
|
|
30
|
+
timeoutMs,
|
|
31
|
+
fetchImpl
|
|
32
|
+
});
|
|
33
|
+
} catch (err) {
|
|
34
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
35
|
+
throw new OnboardingDocumentFetchError(url, detail);
|
|
36
|
+
}
|
|
37
|
+
if (response.status < 200 || response.status >= 300) {
|
|
38
|
+
throw new OnboardingDocumentFetchError(
|
|
39
|
+
url,
|
|
40
|
+
`unexpected status ${response.status}`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
const rawType = response.headers.get("content-type") ?? "";
|
|
44
|
+
const contentType = rawType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
45
|
+
const kind = classify(contentType);
|
|
46
|
+
try {
|
|
47
|
+
if (kind === "html" || kind === "text") {
|
|
48
|
+
return { contentType, kind, text: await response.text() };
|
|
49
|
+
}
|
|
50
|
+
return { contentType, kind, blob: await response.blob() };
|
|
51
|
+
} catch (err) {
|
|
52
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
53
|
+
throw new OnboardingDocumentFetchError(url, `body read failed: ${detail}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export { OnboardingDocumentFetchError, fetchDocumentContent };
|
|
58
|
+
//# sourceMappingURL=chunk-SEKNVHD3.js.map
|
|
59
|
+
//# sourceMappingURL=chunk-SEKNVHD3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/consent/document.ts"],"names":[],"mappings":";;;AAiDO,IAAM,4BAAA,GAAN,cAA2C,eAAA,CAAgB;AAAA,EAChD,GAAA;AAAA,EAEhB,WAAA,CAAY,KAAa,MAAA,EAAgB;AACvC,IAAA,KAAA;AAAA,MACE,eAAA;AAAA,MACA,CAAA,uCAAA,EAA0C,GAAG,CAAA,GAAA,EAAM,MAAM,CAAA,CAAA;AAAA,MACzD;AAAA,KACF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,8BAAA;AACZ,IAAA,IAAA,CAAK,GAAA,GAAM,GAAA;AAAA,EACb;AACF;AAEA,SAAS,SAAS,WAAA,EAA0C;AAC1D,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AA,EAAK,CAAE,WAAA,EAAY,IAAK,EAAA;AACnE,EAAA,MAAM,IAAA,GAAO,SAAS,WAAW,CAAA;AAEjC,EAAA,IAAI;AACF,IAAA,IAAI,IAAA,KAAS,MAAA,IAAU,IAAA,KAAS,MAAA,EAAQ;AACtC,MAAA,OAAO,EAAE,WAAA,EAAa,IAAA,EAAM,MAAM,MAAM,QAAA,CAAS,MAAK,EAAE;AAAA,IAC1D;AACA,IAAA,OAAO,EAAE,WAAA,EAAa,IAAA,EAAM,MAAM,MAAM,QAAA,CAAS,MAAK,EAAE;AAAA,EAC1D,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,SAAS,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC9D,IAAA,MAAM,IAAI,4BAAA,CAA6B,GAAA,EAAK,CAAA,kBAAA,EAAqB,MAAM,CAAA,CAAE,CAAA;AAAA,EAC3E;AACF","file":"chunk-SEKNVHD3.js","sourcesContent":["/**\n * Headless document-content fetch helper (D543 §5).\n *\n * The consent controller is DOM-free; document RENDERING is the consumer's\n * responsibility (TanStack model — you render the row, we own the state). For\n * `scroll_then_accept` gating to work the doc must be rendered SAME-ORIGIN and\n * inline (a cross-origin iframe cannot report scroll position), so consumers\n * fetch the presigned artifact and render its bytes/text themselves.\n *\n * This helper does the fetch + classification so a consumer doesn't wrestle\n * CORS/content-type detection. It returns the artifact's content-type plus the\n * body as text (for HTML/plain) or a Blob (for PDF/binary). It NEVER renders\n * or sanitizes — the consumer (or the default component) decides how to display\n * it (e.g. sanitize+inject HTML, or PDF.js a blob, or degrade to open-in-tab).\n *\n * A short-TTL presigned GET may fail (expired URL, CORS, offline); the caller\n * gets a typed OnboardingDocumentFetchError so a failed preview degrades\n * gracefully (e.g. fall back to an \"open in a new tab\" affordance) without\n * breaking the consent gate.\n */\n\nimport type { ConsentDocument } from \"./model.js\";\nimport {\n DEFAULT_REQUEST_TIMEOUT_MS,\n fetchWithTimeout,\n} from \"../submit/http.js\";\nimport { OnboardingError } from \"../submit/errors.js\";\n\n/** How the fetched artifact should be treated by a renderer. */\nexport type ConsentDocumentKind = \"html\" | \"text\" | \"pdf\" | \"binary\";\n\nexport interface FetchedConsentDocument {\n /** The raw `Content-Type` header (lower-cased, params stripped). */\n contentType: string;\n /** Classification for the renderer. */\n kind: ConsentDocumentKind;\n /** Present for kind \"html\" | \"text\". */\n text?: string;\n /** Present for kind \"pdf\" | \"binary\". */\n blob?: Blob;\n}\n\nexport interface FetchDocumentContentOptions {\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout (default 15s) — a stalled CDN never hangs the UI. */\n timeoutMs?: number;\n}\n\n/** A failed presigned artifact fetch (expired URL, CORS, offline, non-2xx). */\nexport class OnboardingDocumentFetchError extends OnboardingError {\n public readonly url: string;\n\n constructor(url: string, detail: string) {\n super(\n \"network_error\",\n `Failed to fetch consent document from \"${url}\": ${detail}`,\n null,\n );\n this.name = \"OnboardingDocumentFetchError\";\n this.url = url;\n }\n}\n\nfunction classify(contentType: string): ConsentDocumentKind {\n if (contentType.includes(\"application/pdf\")) return \"pdf\";\n if (contentType.includes(\"text/html\")) return \"html\";\n if (contentType.startsWith(\"text/\")) return \"text\";\n return \"binary\";\n}\n\n/**\n * Fetch a consent document's presigned artifact and return its content-type +\n * body (text for HTML/plain, Blob for PDF/binary).\n *\n * @throws {OnboardingDocumentFetchError} on network failure, timeout, CORS,\n * or a non-2xx response — the caller degrades gracefully (open-in-tab).\n */\nexport async function fetchDocumentContent(\n doc: Pick<ConsentDocument, \"downloadUrl\">,\n options: FetchDocumentContentOptions = {},\n): Promise<FetchedConsentDocument> {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const url = doc.downloadUrl;\n\n let response: Response;\n try {\n response = await fetchWithTimeout(url, {\n method: \"GET\",\n timeoutMs,\n fetchImpl,\n });\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n throw new OnboardingDocumentFetchError(url, detail);\n }\n\n if (response.status < 200 || response.status >= 300) {\n throw new OnboardingDocumentFetchError(\n url,\n `unexpected status ${response.status}`,\n );\n }\n\n const rawType = response.headers.get(\"content-type\") ?? \"\";\n const contentType = rawType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n const kind = classify(contentType);\n\n try {\n if (kind === \"html\" || kind === \"text\") {\n return { contentType, kind, text: await response.text() };\n }\n return { contentType, kind, blob: await response.blob() };\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n throw new OnboardingDocumentFetchError(url, `body read failed: ${detail}`);\n }\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from 'zod/v3';
|
|
2
|
+
|
|
3
|
+
// src/form/schema.ts
|
|
4
|
+
var contactFormSchema = z.object({
|
|
5
|
+
name: z.string().max(200).optional(),
|
|
6
|
+
companyName: z.string().min(1, "Company name is required").max(200, "Company name must be 200 characters or fewer"),
|
|
7
|
+
contactName: z.string().min(1, "Contact name is required").max(200, "Contact name must be 200 characters or fewer"),
|
|
8
|
+
email: z.string().email("A valid email address is required"),
|
|
9
|
+
phone: z.string().optional(),
|
|
10
|
+
message: z.string().max(4e3, "Message must be 4000 characters or fewer").optional(),
|
|
11
|
+
interestModules: z.array(z.string().min(1)).max(32).default([]),
|
|
12
|
+
sizeBand: z.string().max(80).optional(),
|
|
13
|
+
attribution: z.object({
|
|
14
|
+
campaignTags: z.record(z.string()).optional(),
|
|
15
|
+
referringSite: z.string().max(2048).optional(),
|
|
16
|
+
landingPage: z.string().max(2048).optional(),
|
|
17
|
+
button: z.string().max(120).optional()
|
|
18
|
+
}).strict().optional(),
|
|
19
|
+
privacyNoticeAcknowledged: z.boolean().refine((value) => value, "Privacy notice acknowledgement is required"),
|
|
20
|
+
marketingOptIn: z.boolean(),
|
|
21
|
+
intakeKind: z.enum(["contact", "enquiry"]),
|
|
22
|
+
// Q46 default: a visually-hidden field. Humans leave it empty.
|
|
23
|
+
website: z.string().max(0).optional()
|
|
24
|
+
});
|
|
25
|
+
var leadsWireSchema = contactFormSchema.extend({
|
|
26
|
+
botToken: z.string().min(1, "botToken is required").optional()
|
|
27
|
+
}).strict();
|
|
28
|
+
function validateContactForm(values) {
|
|
29
|
+
return contactFormSchema.safeParse(values);
|
|
30
|
+
}
|
|
31
|
+
function validateLeadsPayload(payload) {
|
|
32
|
+
return leadsWireSchema.safeParse(payload);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { contactFormSchema, leadsWireSchema, validateContactForm, validateLeadsPayload };
|
|
36
|
+
//# sourceMappingURL=chunk-SIMLMQPT.js.map
|
|
37
|
+
//# sourceMappingURL=chunk-SIMLMQPT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/form/schema.ts"],"names":[],"mappings":";;;AAyBO,IAAM,iBAAA,GAAoB,EAAE,MAAA,CAAO;AAAA,EACxC,MAAM,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,GAAG,EAAE,QAAA,EAAS;AAAA,EACnC,WAAA,EAAa,CAAA,CACV,MAAA,EAAO,CACP,GAAA,CAAI,GAAG,0BAA0B,CAAA,CACjC,GAAA,CAAI,GAAA,EAAK,8CAA8C,CAAA;AAAA,EAC1D,WAAA,EAAa,CAAA,CACV,MAAA,EAAO,CACP,GAAA,CAAI,GAAG,0BAA0B,CAAA,CACjC,GAAA,CAAI,GAAA,EAAK,8CAA8C,CAAA;AAAA,EAC1D,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,MAAM,mCAAmC,CAAA;AAAA,EAC3D,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,OAAA,EAAS,EACN,MAAA,EAAO,CACP,IAAI,GAAA,EAAM,0CAA0C,EACpD,QAAA,EAAS;AAAA,EACZ,eAAA,EAAiB,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,QAAO,CAAE,GA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.js","sourcesContent":["/**\n * Contact-form Zod schema — mirrors the LOCKED hub REST contract exactly:\n * POST /api/v1/public/onboarding/leads\n * Schema: PublicOnboardingLeadsRequest (hub id 8686dd33)\n *\n * Constraints (per hub JSON Schema):\n * name — string, 1-200 chars, required\n * email — email format, required\n * phone — string, optional (no server-side constraint beyond string)\n * message — string, ≤4000 chars, optional\n * botToken — string, required (reCAPTCHA token, D537)\n *\n * additionalProperties: false\n *\n * The schema intentionally does NOT include botToken in the public-facing\n * ContactFormValues type — that field is injected by the submit client right\n * before the POST (the widget/form never exposes it to the user).\n */\n\nimport { z } from \"zod/v3\";\n\n/**\n * The user-visible contact form fields. Validated client-side for UX.\n * Server re-validates authoritatively (D540 §2).\n */\nexport const contactFormSchema = z.object({\n name: z.string().max(200).optional(),\n companyName: z\n .string()\n .min(1, \"Company name is required\")\n .max(200, \"Company name must be 200 characters or fewer\"),\n contactName: z\n .string()\n .min(1, \"Contact name is required\")\n .max(200, \"Contact name must be 200 characters or fewer\"),\n email: z.string().email(\"A valid email address is required\"),\n phone: z.string().optional(),\n message: z\n .string()\n .max(4000, \"Message must be 4000 characters or fewer\")\n .optional(),\n interestModules: z.array(z.string().min(1)).max(32).default([]),\n sizeBand: z.string().max(80).optional(),\n attribution: z\n .object({\n campaignTags: z.record(z.string()).optional(),\n referringSite: z.string().max(2048).optional(),\n landingPage: z.string().max(2048).optional(),\n button: z.string().max(120).optional(),\n })\n .strict()\n .optional(),\n privacyNoticeAcknowledged: z\n .boolean()\n .refine((value) => value, \"Privacy notice acknowledgement is required\"),\n marketingOptIn: z.boolean(),\n intakeKind: z.enum([\"contact\", \"enquiry\"]),\n // Q46 default: a visually-hidden field. Humans leave it empty.\n website: z.string().max(0).optional(),\n});\n\nexport type ContactFormValues = z.infer<typeof contactFormSchema>;\n\n/**\n * The full wire payload — contactFormSchema + botToken.\n *\n * STRICT mode: unknown keys are REJECTED (not stripped), mirroring the\n * server's `additionalProperties: false`. `submitLead` runs every outgoing\n * payload through this schema before the POST — an extra key never reaches\n * the wire; it fails fast client-side with OnboardingValidationError.\n */\nexport const leadsWireSchema = contactFormSchema\n .extend({\n botToken: z.string().min(1, \"botToken is required\").optional(),\n })\n .strict();\n\nexport type LeadsWirePayload = z.infer<typeof leadsWireSchema>;\n\n/**\n * Validate user-visible form values (no botToken required here).\n * Returns a Zod SafeParseReturnType (inferred).\n */\nexport function validateContactForm(values: unknown) {\n return contactFormSchema.safeParse(values);\n}\n\n/**\n * Validate the full wire payload (including botToken) before submission.\n * STRICT: unknown keys are rejected, matching additionalProperties:false.\n * This is the exact validation `submitLead` applies on the wire path.\n * Returns a Zod SafeParseReturnType (inferred).\n */\nexport function validateLeadsPayload(payload: unknown) {\n return leadsWireSchema.safeParse(payload);\n}\n"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { z } from 'zod/v3';
|
|
2
|
+
|
|
3
|
+
// src/consent/model.ts
|
|
4
|
+
var CUSTOM_KEY_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
5
|
+
var ACCEPTANCE_LEVELS = [
|
|
6
|
+
"checkbox",
|
|
7
|
+
"scroll_then_accept",
|
|
8
|
+
"open_then_accept"
|
|
9
|
+
];
|
|
10
|
+
var acceptanceLevelSchema = z.enum(ACCEPTANCE_LEVELS);
|
|
11
|
+
var DOC_TYPES = ["tos", "privacy", "dpa", "custom"];
|
|
12
|
+
var consentDocumentSchema = z.object({
|
|
13
|
+
// Server-side opaque registry id (D543 §3 legal_documents.id). Echoed
|
|
14
|
+
// verbatim on submit as consent.documents[].legalDocumentId (D543 §4);
|
|
15
|
+
// the SDK never synthesizes it. See DRIFT 5e3df7a3 (module doc).
|
|
16
|
+
legalDocumentId: z.string().min(1),
|
|
17
|
+
docType: z.enum(DOC_TYPES),
|
|
18
|
+
// Nullable (NOT omitted): non-custom docs send customKey:null.
|
|
19
|
+
customKey: z.string().min(1).regex(
|
|
20
|
+
CUSTOM_KEY_PATTERN,
|
|
21
|
+
"customKey must contain only letters, digits, underscore, or hyphen"
|
|
22
|
+
).nullable(),
|
|
23
|
+
title: z.string().min(1),
|
|
24
|
+
// Monotonic version of the live document. This is the SUBMIT PIN: it is
|
|
25
|
+
// echoed on submit (consent.documents[].versionNo) and the server matches
|
|
26
|
+
// it against the current live version (mismatch ⇒ 409 consent_stale). Any
|
|
27
|
+
// content change publishes a NEW version, so versionNo is a complete pin.
|
|
28
|
+
versionNo: z.number().int().nonnegative(),
|
|
29
|
+
// sha256 of the live artifact — spec-side integrity metadata (P4). NOT
|
|
30
|
+
// echoed on submit: versionNo is the pin (a content change = new version),
|
|
31
|
+
// so the submit array carries versionNo only, per the canonical wire shape.
|
|
32
|
+
// The SDK exposes contentHash so a consumer can display/verify integrity;
|
|
33
|
+
// the server does NOT require it on the submit array.
|
|
34
|
+
contentHash: z.string().min(1),
|
|
35
|
+
// Short-TTL presigned GET for the artifact bytes (D543 §4 / 04-pii).
|
|
36
|
+
downloadUrl: z.string().min(1),
|
|
37
|
+
acceptanceLevel: acceptanceLevelSchema,
|
|
38
|
+
required: z.boolean()
|
|
39
|
+
}).strict().superRefine((doc, ctx) => {
|
|
40
|
+
if (doc.docType === "custom" && doc.customKey === null) {
|
|
41
|
+
ctx.addIssue({
|
|
42
|
+
code: z.ZodIssueCode.custom,
|
|
43
|
+
path: ["customKey"],
|
|
44
|
+
message: "customKey is required (non-null) when docType is 'custom'"
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (doc.docType !== "custom" && doc.customKey !== null) {
|
|
48
|
+
ctx.addIssue({
|
|
49
|
+
code: z.ZodIssueCode.custom,
|
|
50
|
+
path: ["customKey"],
|
|
51
|
+
message: "customKey must be null when docType is not 'custom'"
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
var consentPackSchema = z.object({
|
|
56
|
+
documents: z.array(consentDocumentSchema)
|
|
57
|
+
}).strict().superRefine((pack, ctx) => {
|
|
58
|
+
const seen = /* @__PURE__ */ new Set();
|
|
59
|
+
for (let i = 0; i < pack.documents.length; i++) {
|
|
60
|
+
const doc = pack.documents[i];
|
|
61
|
+
if (!doc) continue;
|
|
62
|
+
const key = consentDocKey(doc);
|
|
63
|
+
if (seen.has(key)) {
|
|
64
|
+
ctx.addIssue({
|
|
65
|
+
code: z.ZodIssueCode.custom,
|
|
66
|
+
path: ["documents", i],
|
|
67
|
+
message: `duplicate consent document key "${key}"`
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
seen.add(key);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
function consentDocKey(doc) {
|
|
74
|
+
return doc.docType === "custom" ? `custom:${doc.customKey ?? ""}` : doc.docType;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export { ACCEPTANCE_LEVELS, DOC_TYPES, acceptanceLevelSchema, consentDocKey, consentDocumentSchema, consentPackSchema };
|
|
78
|
+
//# sourceMappingURL=chunk-U56GQITG.js.map
|
|
79
|
+
//# sourceMappingURL=chunk-U56GQITG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/consent/model.ts"],"names":[],"mappings":";;;AA2DA,IAAM,kBAAA,GAAqB,kBAAA;AAGpB,IAAM,iBAAA,GAAoB;AAAA,EAC/B,UAAA;AAAA,EACA,oBAAA;AAAA,EACA;AACF;AAIO,IAAM,qBAAA,GAAwB,CAAA,CAAE,IAAA,CAAK,iBAAiB;AAGtD,IAAM,SAAA,GAAY,CAAC,KAAA,EAAO,SAAA,EAAW,OAAO,QAAQ;AAgBpD,IAAM,qBAAA,GAAwB,EAClC,MAAA,CAAO;AAAA;AAAA;AAAA;AAAA,EAIN,eAAA,EAAiB,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EACjC,OAAA,EAAS,CAAA,CAAE,IAAA,CAAK,SAAS,CAAA;AAAA;AAAA,EAEzB,WAAW,CAAA,CACR,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,KAAA;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AM,GAAA,KAAQ;AAC1B,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA,EAAA,EAAK;AAC9C,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,SAAA,CAAU,CAAC,CAAA;AAC5B,IAAA,IAAI,CAAC,GAAA,EAAK;AACV,IAAA,MAAM,GAAA,GAAM,cAAc,GAAG,CAAA;AAC7B,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,GAAG,CAAA,EAAG;AACjB,MAAA,GAAA,CAAI,QAAA,CAAS;AAAA,QACX,IAAA,EAAM,EAAE,YAAA,CAAa,MAAA;AAAA,QACrB,IAAA,EAAM,CAAC,WAAA,EAAa,CAAC,CAAA;AAAA,QACrB,OAAA,EAAS,mCAAmC,GAAG,CAAA,CAAA;AAAA,OAChD,CAAA;AAAA,IACH;AACA,IAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AAAA,EACd;AACF,CAAC;AAcI,SAAS,cAAc,GAAA,EAGnB;AACT,EAAA,OAAO,GAAA,CAAI,YAAY,QAAA,GACnB,CAAA,OAAA,EAAU,IAAI,SAAA,IAAa,EAAE,KAC7B,GAAA,CAAI,OAAA;AACV","file":"chunk-U56GQITG.js","sourcesContent":["/**\n * D543 §4 ConsentPack spec model — the `consentPack` block that GET\n * /api/v1/public/onboarding/spec grows on top of the D540 shape:\n *\n * consentPack: {\n * documents: [\n * { doc_type, custom_key?, title, version_no, content_hash,\n * download_url, acceptance_level, required }\n * ]\n * }\n *\n * The intake projects ONLY `live` versions into this block (D543 §4);\n * `download_url` is a short-TTL presigned GET the SDK renders/opens.\n *\n * `acceptance_level` (D543 §2) is a per-document GATE:\n * - \"checkbox\" — a single accept checkbox (basic clickwrap).\n * - \"scroll_then_accept\" — accept disabled until the doc is scrolled to\n * the end (client asserts evidence.scrolled_to_end).\n * - \"open_then_accept\" — accept disabled until the doc is opened/viewed\n * (client asserts evidence.opened).\n * (E-signature is a deferred future level, D543 §2 — NOT modeled here.)\n *\n * FAIL-CLOSED (R1 + D543 §5 / D540 §1): a malformed consentPack throws\n * OnboardingSpecInvalidError at parse time — never rendered half-parsed\n * (a dropped `required` doc would let a user submit without consent, and a\n * missing `content_hash`/`version_no` would break the server's re-validation\n * match). The SDK refuses to render a consent step it cannot trust.\n *\n * DOM-ID HARDENING: a document's DOM-id token is derived from `doc_type`\n * (a fixed enum — safe) or, for custom docs, from `custom_key` (free-form\n * from the served spec). Custom keys are interpolated into element ids and\n * (historically) selectors by the widget layer, so they are constrained to\n * the SAME strict identifier alphabet as field keys (CUSTOM_KEY_PATTERN,\n * identical to the spec model's FIELD_KEY_PATTERN) and REJECTED at parse time\n * if they carry CSS/selector metacharacters. This is layer 1; the widget also\n * CSS.escapes every id token as defense-in-depth.\n *\n * SUBMIT PIN (P4): the submit array carries {legalDocumentId, versionNo,\n * accepted, evidence} — the server matches on legalDocumentId + versionNo\n * (contentHash is spec-side integrity metadata, NOT echoed on submit; a\n * content change publishes a new versionNo, so versionNo is a complete pin).\n *\n * DRIFT 5e3df7a3 (2026-07-14, consumer-visible) — RESOLVED by the canonical\n * shape: D543 §4 as literally written omitted `legal_document_id` from the\n * spec block, yet the submit array is KEYED on it (the server matches\n * legalDocumentId + versionNo against the live version). The\n * canonical alignment (both tiers, camelCase) INCLUDES `legalDocumentId` in\n * the spec `consentPack.documents[]`, exactly as the drift proposed. This\n * model REQUIRES it (fail-closed OnboardingSpecInvalidError if missing).\n */\n\nimport { z } from \"zod/v3\";\n\n/**\n * DOM-id-safe custom-key alphabet. INTENTIONALLY identical to the spec\n * model's FIELD_KEY_PATTERN (`/^[A-Za-z0-9_-]+$/`), duplicated here rather\n * than imported to avoid a spec↔consent import cycle (spec/model.ts imports\n * consentPackSchema from this file). Any change to one must mirror the other.\n */\nconst CUSTOM_KEY_PATTERN = /^[A-Za-z0-9_-]+$/;\n\n/** D543 §2 acceptance-level enum. Extensible (adding a level is additive). */\nexport const ACCEPTANCE_LEVELS = [\n \"checkbox\",\n \"scroll_then_accept\",\n \"open_then_accept\",\n] as const;\n\nexport type AcceptanceLevel = (typeof ACCEPTANCE_LEVELS)[number];\n\nexport const acceptanceLevelSchema = z.enum(ACCEPTANCE_LEVELS);\n\n/** D543 §3 docType enum. */\nexport const DOC_TYPES = [\"tos\", \"privacy\", \"dpa\", \"custom\"] as const;\nexport type ConsentDocType = (typeof DOC_TYPES)[number];\n\n/**\n * One live legal document projected into the consent step. Mirrors the D543\n * §4 `consentPack.documents[]` element — CANONICAL camelCase wire shape (both\n * tenant + platform tiers aligned to this): { legalDocumentId, docType,\n * customKey (nullable), title, versionNo, contentHash, downloadUrl,\n * acceptanceLevel, required }. The `acceptanceLevel` enum VALUES stay snake\n * (checkbox | scroll_then_accept | open_then_accept).\n *\n * Cross-field invariant (D543 §3): `customKey` is a non-null identifier when\n * `docType === \"custom\"` and MUST be null otherwise (a canonical tos/privacy/\n * dpa doc is keyed by docType; only custom docs carry a key). The custom-key\n * alphabet is DOM-id safe.\n */\nexport const consentDocumentSchema = z\n .object({\n // Server-side opaque registry id (D543 §3 legal_documents.id). Echoed\n // verbatim on submit as consent.documents[].legalDocumentId (D543 §4);\n // the SDK never synthesizes it. See DRIFT 5e3df7a3 (module doc).\n legalDocumentId: z.string().min(1),\n docType: z.enum(DOC_TYPES),\n // Nullable (NOT omitted): non-custom docs send customKey:null.\n customKey: z\n .string()\n .min(1)\n .regex(\n CUSTOM_KEY_PATTERN,\n \"customKey must contain only letters, digits, underscore, or hyphen\",\n )\n .nullable(),\n title: z.string().min(1),\n // Monotonic version of the live document. This is the SUBMIT PIN: it is\n // echoed on submit (consent.documents[].versionNo) and the server matches\n // it against the current live version (mismatch ⇒ 409 consent_stale). Any\n // content change publishes a NEW version, so versionNo is a complete pin.\n versionNo: z.number().int().nonnegative(),\n // sha256 of the live artifact — spec-side integrity metadata (P4). NOT\n // echoed on submit: versionNo is the pin (a content change = new version),\n // so the submit array carries versionNo only, per the canonical wire shape.\n // The SDK exposes contentHash so a consumer can display/verify integrity;\n // the server does NOT require it on the submit array.\n contentHash: z.string().min(1),\n // Short-TTL presigned GET for the artifact bytes (D543 §4 / 04-pii).\n downloadUrl: z.string().min(1),\n acceptanceLevel: acceptanceLevelSchema,\n required: z.boolean(),\n })\n .strict()\n .superRefine((doc, ctx) => {\n if (doc.docType === \"custom\" && doc.customKey === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"customKey\"],\n message: \"customKey is required (non-null) when docType is 'custom'\",\n });\n }\n if (doc.docType !== \"custom\" && doc.customKey !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"customKey\"],\n message: \"customKey must be null when docType is not 'custom'\",\n });\n }\n });\n\nexport type ConsentDocument = z.infer<typeof consentDocumentSchema>;\n\n/**\n * The `consentPack` block. `documents` may be empty (an onboarder with no\n * required legal docs) — the consent stage is then omitted from the flow.\n *\n * Uniqueness: no two documents may share the same STABLE key (docType, or\n * custom:<customKey> for custom docs). A duplicate would collide their DOM\n * ids AND their consent records — fail-closed at parse (the server keys the\n * registry on (scope, docType) / (scope, customKey) per D543 §3, so a\n * duplicate here is a projection bug, not a renderable spec).\n */\nexport const consentPackSchema = z\n .object({\n documents: z.array(consentDocumentSchema),\n })\n .strict()\n .superRefine((pack, ctx) => {\n const seen = new Set<string>();\n for (let i = 0; i < pack.documents.length; i++) {\n const doc = pack.documents[i];\n if (!doc) continue;\n const key = consentDocKey(doc);\n if (seen.has(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"documents\", i],\n message: `duplicate consent document key \"${key}\"`,\n });\n }\n seen.add(key);\n }\n });\n\nexport type ConsentPack = z.infer<typeof consentPackSchema>;\n\n/**\n * Stable, collision-proof identity for a consent document, used as the map\n * key in the controller and the DOM-id token in the widget. `docType` is a\n * fixed enum; `custom:` is prefixed for custom docs so a customKey of\n * \"tos\" can never alias the canonical tos doc.\n *\n * Note: this is NOT the submit key — the submit array keys on the server's\n * opaque `legalDocumentId` (D543 §4), which the SDK does not synthesize.\n * This is a purely CLIENT-side identity for state + DOM.\n */\nexport function consentDocKey(doc: {\n docType: ConsentDocType;\n customKey?: string | null | undefined;\n}): string {\n return doc.docType === \"custom\"\n ? `custom:${doc.customKey ?? \"\"}`\n : doc.docType;\n}\n"]}
|