@invonetwork/web-sdk 3.29.1 → 3.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +1442 -1397
  2. package/README.md +2954 -2923
  3. package/dist/chunk-3ECVREIM.js +6 -0
  4. package/dist/chunk-7O5JT3LK.js +1590 -0
  5. package/dist/{chunk-VP3OK4J4.js → chunk-TCT2QSVB.js} +515 -3
  6. package/dist/{chunk-YONO4JE5.js → chunk-V2RQYQQD.js} +44 -5
  7. package/dist/game-server.cjs +387 -42
  8. package/dist/game-server.d.cts +42 -6
  9. package/dist/game-server.d.ts +42 -6
  10. package/dist/game-server.js +286 -8
  11. package/dist/game.cjs +2677 -9
  12. package/dist/game.d.cts +78 -4
  13. package/dist/game.d.ts +78 -4
  14. package/dist/game.js +558 -3
  15. package/dist/hosted-approval-DcY4U2RN.d.cts +96 -0
  16. package/dist/hosted-approval-DiKmtjEh.d.ts +96 -0
  17. package/dist/index.d.cts +7 -96
  18. package/dist/index.d.ts +7 -96
  19. package/dist/index.js +2 -1635
  20. package/dist/loyalty-events-CmDw2ZoR.d.cts +40 -0
  21. package/dist/loyalty-events-CmDw2ZoR.d.ts +40 -0
  22. package/dist/{server-Bxo_wgHx.d.cts → server-BAOn3KH3.d.cts} +28 -2
  23. package/dist/{server-BYY6tM6X.d.ts → server-DHmQU1eN.d.ts} +28 -2
  24. package/dist/server.cjs +106 -40
  25. package/dist/server.d.cts +4 -3
  26. package/dist/server.d.ts +4 -3
  27. package/dist/server.js +3 -4
  28. package/dist/{types-_lIm74kd.d.cts → types-BTbZicgj.d.cts} +1 -40
  29. package/dist/{types-_lIm74kd.d.ts → types-BTbZicgj.d.ts} +1 -40
  30. package/dist/{types-CLyJDuXd.d.cts → types-jUxfYjiD.d.cts} +64 -1
  31. package/dist/{types-CLyJDuXd.d.ts → types-jUxfYjiD.d.ts} +64 -1
  32. package/dist/{version-DOaYbHu7.d.cts → version-CR7XECyP.d.cts} +1 -1
  33. package/dist/{version-DOaYbHu7.d.ts → version-CR7XECyP.d.ts} +1 -1
  34. package/package.json +91 -91
  35. package/dist/chunk-6CN236QH.js +0 -473
  36. package/dist/chunk-VOGZZ6QS.js +0 -6
@@ -0,0 +1,1590 @@
1
+ import { InvoError, assertSecureBaseUrl, Http, toPurchaseStatusResult, toPhoneChangeApprovalsResult, phoneChangeSignalMessage, toApprovePhoneChangeResult, toDestinationsResult, toLoyaltyCardsResult, toLoyaltyVaultResult, toRedeemRewardResult, toRewardsPageLink, buildGameEventBody, toReportGameEventResult } from './chunk-TCT2QSVB.js';
2
+
3
+ // src/shared/webauthn.ts
4
+ function malformedOptions(field) {
5
+ return new InvoError({
6
+ message: `Malformed WebAuthn options from the backend: missing/invalid \`${field}\`.`,
7
+ code: "WEBAUTHN_OPTIONS_MALFORMED",
8
+ status: 0
9
+ });
10
+ }
11
+ function b64urlToBuffer(value) {
12
+ const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
13
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
14
+ const bin = atob(b64);
15
+ const bytes = new Uint8Array(bin.length);
16
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
17
+ return bytes.buffer;
18
+ }
19
+ function bufferToB64url(buf) {
20
+ const bytes = new Uint8Array(buf);
21
+ let bin = "";
22
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
23
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ function descriptorsToBinary(list) {
26
+ return (list ?? []).map((d) => {
27
+ const out = {
28
+ id: b64urlToBuffer(d.id),
29
+ type: d.type
30
+ };
31
+ if (d.transports) out.transports = d.transports;
32
+ return out;
33
+ });
34
+ }
35
+ function toCreationOptions(json) {
36
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
37
+ if (typeof json["user"]?.id !== "string") throw malformedOptions("user.id");
38
+ const opts = {
39
+ ...json,
40
+ challenge: b64urlToBuffer(json["challenge"]),
41
+ user: {
42
+ ...json["user"],
43
+ id: b64urlToBuffer(json["user"].id)
44
+ }
45
+ };
46
+ if (json["excludeCredentials"]) {
47
+ opts.excludeCredentials = descriptorsToBinary(json["excludeCredentials"]);
48
+ }
49
+ return opts;
50
+ }
51
+ function toRequestOptions(json) {
52
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
53
+ const opts = {
54
+ ...json,
55
+ challenge: b64urlToBuffer(json["challenge"])
56
+ };
57
+ if (json["allowCredentials"]) {
58
+ opts.allowCredentials = descriptorsToBinary(json["allowCredentials"]);
59
+ }
60
+ return opts;
61
+ }
62
+ function registrationToJSON(cred) {
63
+ const r = cred.response;
64
+ return {
65
+ id: cred.id,
66
+ rawId: bufferToB64url(cred.rawId),
67
+ type: cred.type,
68
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
69
+ clientExtensionResults: cred.getClientExtensionResults(),
70
+ response: {
71
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
72
+ attestationObject: bufferToB64url(r.attestationObject),
73
+ transports: typeof r.getTransports === "function" ? r.getTransports() : void 0
74
+ }
75
+ };
76
+ }
77
+ function assertionToJSON(cred) {
78
+ const r = cred.response;
79
+ return {
80
+ id: cred.id,
81
+ rawId: bufferToB64url(cred.rawId),
82
+ type: cred.type,
83
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
84
+ clientExtensionResults: cred.getClientExtensionResults(),
85
+ response: {
86
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
87
+ authenticatorData: bufferToB64url(r.authenticatorData),
88
+ signature: bufferToB64url(r.signature),
89
+ userHandle: r.userHandle ? bufferToB64url(r.userHandle) : null
90
+ }
91
+ };
92
+ }
93
+
94
+ // src/shared/hosted-approval.ts
95
+ var HOSTED_FLOWS = [
96
+ "transfer",
97
+ "send",
98
+ "send_receipt",
99
+ "transfer_receipt"
100
+ ];
101
+ var HOSTED_MESSAGE_TYPE = "invo.approval";
102
+ var MAX_EXPIRES_IN_S = 24 * 24 * 60 * 60;
103
+ var CONFIRM_QUIET_CODES = /* @__PURE__ */ new Set([
104
+ "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED",
105
+ "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING"
106
+ ]);
107
+ var MAX_TRANSIENT_POLL_FAILURES = 5;
108
+ function derivePlatformOrigin(verificationUriComplete, explicit) {
109
+ let u;
110
+ try {
111
+ u = new URL(verificationUriComplete);
112
+ } catch {
113
+ throw new InvoError({
114
+ message: "begin returned no absolute verification_uri_complete.",
115
+ code: "UNEXPECTED_RESPONSE",
116
+ status: 0
117
+ });
118
+ }
119
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
120
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
121
+ throw new InvoError({
122
+ message: "The hosted approval page must be https (plaintext would let any page forge the wake-up).",
123
+ code: "INVALID_INPUT",
124
+ status: 0
125
+ });
126
+ }
127
+ if (explicit !== void 0 && u.origin !== explicit) {
128
+ throw new InvoError({
129
+ message: `platformOrigin (${explicit}) does not match the hosted page's origin (${u.origin}).`,
130
+ code: "INVALID_INPUT",
131
+ status: 0
132
+ });
133
+ }
134
+ return u.origin;
135
+ }
136
+ function normalizeEnrollment(input) {
137
+ if (!input || typeof input !== "object") return null;
138
+ const state = typeof input.state === "string" ? input.state : "";
139
+ if (!state) return null;
140
+ const label = input.device_label ?? input.deviceLabel;
141
+ const code = input.match_code ?? input.matchCode;
142
+ const at = input.requested_at ?? input.requestedAt;
143
+ return {
144
+ state,
145
+ deviceLabel: typeof label === "string" && label ? label : "your phone",
146
+ matchCode: typeof code === "string" ? code : "",
147
+ requestedAt: typeof at === "string" ? at : void 0,
148
+ raw: input
149
+ };
150
+ }
151
+ var BRAND = "#4f46e5";
152
+ var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
153
+ var MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
154
+ var PROMPT_IDS = {
155
+ root: "invo-hosted-enrollment",
156
+ title: "invo-hosted-enrollment-title",
157
+ code: "invo-hosted-enrollment-code",
158
+ yes: "invo-hosted-enrollment-yes",
159
+ no: "invo-hosted-enrollment-no",
160
+ stop: "invo-hosted-enrollment-stop",
161
+ error: "invo-hosted-enrollment-error"
162
+ };
163
+ var HostedEnrollmentPrompt = class {
164
+ constructor() {
165
+ this.handlers = { respond: async () => {
166
+ }, renderPrompt: true };
167
+ this.enrollment = null;
168
+ /** The last match code the player answered, so a stale poll can't re-ask it. */
169
+ this.decided = null;
170
+ this.root = null;
171
+ this.previousFocus = null;
172
+ this.keyHandler = null;
173
+ this.busy = false;
174
+ }
175
+ get current() {
176
+ return this.enrollment;
177
+ }
178
+ configure(handlers) {
179
+ this.handlers = handlers;
180
+ this.decided = null;
181
+ if (this.enrollment) this.render();
182
+ }
183
+ update(input) {
184
+ let next = normalizeEnrollment(input);
185
+ if (next && next.state === "awaiting_screen" && this.decided && this.decided.code === next.matchCode) {
186
+ next = this.decided.decision === "approve" ? { ...next, state: "confirmed" } : null;
187
+ }
188
+ const changed = this.enrollment === null !== (next === null) || this.enrollment && next && (this.enrollment.state !== next.state || this.enrollment.matchCode !== next.matchCode || this.enrollment.deviceLabel !== next.deviceLabel);
189
+ this.enrollment = next;
190
+ if (changed) this.handlers.onEnrollment?.(next, this.handlers.respond);
191
+ this.render();
192
+ }
193
+ clear() {
194
+ this.update(null);
195
+ }
196
+ // --- rendering ---
197
+ render() {
198
+ if (typeof document === "undefined") return;
199
+ const e = this.enrollment;
200
+ const visible = this.handlers.renderPrompt && e && (e.state === "awaiting_screen" || e.state === "confirmed");
201
+ if (!visible || !e) {
202
+ this.unmount();
203
+ return;
204
+ }
205
+ this.mount();
206
+ const root = this.root;
207
+ root.innerHTML = "";
208
+ root.appendChild(e.state === "awaiting_screen" ? this.buildPrompt(e) : this.buildFinishing(e));
209
+ this.focusInitial(e.state);
210
+ }
211
+ mount() {
212
+ if (this.root) return;
213
+ this.previousFocus = document.activeElement;
214
+ const overlay = document.createElement("div");
215
+ overlay.id = PROMPT_IDS.root;
216
+ overlay.setAttribute("role", "dialog");
217
+ overlay.setAttribute("aria-modal", "true");
218
+ overlay.setAttribute("aria-labelledby", PROMPT_IDS.title);
219
+ overlay.tabIndex = -1;
220
+ overlay.style.cssText = [
221
+ "position:fixed",
222
+ "inset:0",
223
+ "z-index:2147483000",
224
+ "display:flex",
225
+ "align-items:center",
226
+ "justify-content:center",
227
+ "padding:16px",
228
+ "background:rgba(17,24,39,.55)",
229
+ `font-family:${FONT}`,
230
+ "color:#111827",
231
+ "-webkit-font-smoothing:antialiased",
232
+ "outline:none"
233
+ ].join(";");
234
+ this.keyHandler = (ev) => this.onKeyDown(ev);
235
+ overlay.addEventListener("keydown", this.keyHandler);
236
+ document.body.appendChild(overlay);
237
+ this.root = overlay;
238
+ }
239
+ unmount() {
240
+ if (!this.root) return;
241
+ if (this.keyHandler) this.root.removeEventListener("keydown", this.keyHandler);
242
+ this.root.remove();
243
+ this.root = null;
244
+ this.keyHandler = null;
245
+ this.busy = false;
246
+ const prev = this.previousFocus;
247
+ this.previousFocus = null;
248
+ if (prev && typeof prev.focus === "function") {
249
+ try {
250
+ prev.focus();
251
+ } catch {
252
+ }
253
+ }
254
+ }
255
+ card() {
256
+ const card = document.createElement("div");
257
+ card.style.cssText = [
258
+ "background:#ffffff",
259
+ "border-radius:16px",
260
+ "box-shadow:0 20px 60px rgba(17,24,39,.25)",
261
+ "max-width:420px",
262
+ "width:100%",
263
+ "padding:28px 28px 24px",
264
+ "box-sizing:border-box",
265
+ "text-align:center"
266
+ ].join(";");
267
+ const mark = document.createElement("div");
268
+ mark.textContent = "INVO";
269
+ mark.setAttribute("aria-hidden", "true");
270
+ mark.style.cssText = `font-weight:800;letter-spacing:.18em;font-size:13px;color:${BRAND};margin-bottom:14px`;
271
+ card.appendChild(mark);
272
+ return card;
273
+ }
274
+ button(id, label, primary) {
275
+ const b = document.createElement("button");
276
+ b.type = "button";
277
+ b.id = id;
278
+ b.textContent = label;
279
+ b.style.cssText = [
280
+ "display:block",
281
+ "width:100%",
282
+ "box-sizing:border-box",
283
+ "border-radius:10px",
284
+ "padding:12px 16px",
285
+ "font:inherit",
286
+ "font-size:15px",
287
+ "font-weight:600",
288
+ "cursor:pointer",
289
+ "margin-top:10px",
290
+ primary ? `background:${BRAND};color:#ffffff;border:1px solid ${BRAND}` : "background:#ffffff;color:#374151;border:1px solid #d1d5db"
291
+ ].join(";");
292
+ return b;
293
+ }
294
+ buildPrompt(e) {
295
+ const card = this.card();
296
+ const title = document.createElement("h2");
297
+ title.id = PROMPT_IDS.title;
298
+ title.textContent = `Set up INVO on ${e.deviceLabel}?`;
299
+ title.style.cssText = "margin:0 0 14px;font-size:20px;font-weight:700;line-height:1.3";
300
+ card.appendChild(title);
301
+ const codeLabel = document.createElement("div");
302
+ codeLabel.textContent = "Code";
303
+ codeLabel.style.cssText = "font-size:12px;text-transform:uppercase;letter-spacing:.12em;color:#6b7280";
304
+ card.appendChild(codeLabel);
305
+ const code = document.createElement("div");
306
+ code.id = PROMPT_IDS.code;
307
+ code.textContent = e.matchCode;
308
+ code.setAttribute("aria-label", `Code ${e.matchCode.split("").join(" ")}`);
309
+ code.style.cssText = [
310
+ `font-family:${MONO}`,
311
+ "font-size:40px",
312
+ "font-weight:700",
313
+ "letter-spacing:.3em",
314
+ "text-indent:.3em",
315
+ "line-height:1.2",
316
+ "margin:6px 0 16px",
317
+ "color:#111827",
318
+ "background:#f3f4f6",
319
+ "border-radius:12px",
320
+ "padding:14px 8px"
321
+ ].join(";");
322
+ card.appendChild(code);
323
+ const body = document.createElement("p");
324
+ body.textContent = "Say Yes only if the phone you just scanned/opened shows this code.";
325
+ body.style.cssText = "margin:0 0 6px;font-size:15px;line-height:1.5;color:#374151";
326
+ card.appendChild(body);
327
+ const err = document.createElement("div");
328
+ err.id = PROMPT_IDS.error;
329
+ err.setAttribute("role", "alert");
330
+ err.style.cssText = "min-height:18px;font-size:13px;color:#b91c1c;margin-top:4px";
331
+ card.appendChild(err);
332
+ const yes = this.button(PROMPT_IDS.yes, "Yes, it shows this code", true);
333
+ yes.addEventListener("click", () => void this.decide("approve"));
334
+ card.appendChild(yes);
335
+ const no = this.button(PROMPT_IDS.no, "No, that is not my phone", false);
336
+ no.addEventListener("click", () => void this.decide("deny"));
337
+ card.appendChild(no);
338
+ return card;
339
+ }
340
+ buildFinishing(e) {
341
+ const card = this.card();
342
+ card.style.padding = "18px 22px";
343
+ const row = document.createElement("div");
344
+ row.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap";
345
+ const text = document.createElement("div");
346
+ text.id = PROMPT_IDS.title;
347
+ text.textContent = `Finishing on ${e.deviceLabel}\u2026`;
348
+ text.tabIndex = -1;
349
+ text.setAttribute("aria-live", "polite");
350
+ text.style.cssText = "font-size:15px;color:#374151;outline:none";
351
+ row.appendChild(text);
352
+ const stop = document.createElement("button");
353
+ stop.type = "button";
354
+ stop.id = PROMPT_IDS.stop;
355
+ stop.textContent = "Stop it, wrong code";
356
+ stop.style.cssText = `background:none;border:0;padding:6px 0;font:inherit;font-size:14px;font-weight:600;color:${BRAND};cursor:pointer;text-decoration:underline`;
357
+ stop.addEventListener("click", () => void this.decide("deny"));
358
+ row.appendChild(stop);
359
+ card.appendChild(row);
360
+ return card;
361
+ }
362
+ async decide(decision) {
363
+ if (this.busy || !this.enrollment) return;
364
+ this.busy = true;
365
+ this.root?.focus();
366
+ this.setButtonsDisabled(true);
367
+ try {
368
+ await this.handlers.respond(decision);
369
+ const now = this.enrollment;
370
+ if (!now) return;
371
+ this.decided = { code: now.matchCode, decision };
372
+ if (decision === "deny") {
373
+ this.update(null);
374
+ } else if (now.state === "awaiting_screen") {
375
+ this.update({ ...now.raw, state: "confirmed" });
376
+ }
377
+ } catch (err) {
378
+ const box = this.root?.querySelector(`#${PROMPT_IDS.error}`);
379
+ if (box) {
380
+ box.textContent = err instanceof Error && err.message ? `Couldn't send your answer: ${err.message}` : "Couldn't send your answer. Try again.";
381
+ }
382
+ } finally {
383
+ this.busy = false;
384
+ this.setButtonsDisabled(false);
385
+ if (this.root && this.enrollment?.state === "awaiting_screen") this.focusInitial("awaiting_screen");
386
+ }
387
+ }
388
+ setButtonsDisabled(disabled) {
389
+ this.root?.querySelectorAll("button").forEach((b) => {
390
+ b.disabled = disabled;
391
+ });
392
+ }
393
+ focusables() {
394
+ if (!this.root) return [];
395
+ return Array.from(this.root.querySelectorAll("button:not([disabled])"));
396
+ }
397
+ /** Prompt: first button. Finishing row: the text, NOT "Stop it" — a stray Enter must not deny. */
398
+ focusInitial(state) {
399
+ const target = state === "confirmed" ? this.root?.querySelector(`#${PROMPT_IDS.title}`) : this.focusables()[0];
400
+ try {
401
+ (target ?? this.root)?.focus();
402
+ } catch {
403
+ }
404
+ }
405
+ onKeyDown(ev) {
406
+ if (ev.key === "Escape") {
407
+ ev.preventDefault();
408
+ void this.decide("deny");
409
+ return;
410
+ }
411
+ if (ev.key !== "Tab") return;
412
+ ev.preventDefault();
413
+ const items = this.focusables();
414
+ if (items.length === 0) {
415
+ this.root?.focus();
416
+ return;
417
+ }
418
+ const active = document.activeElement;
419
+ const idx = items.indexOf(active);
420
+ let nextIdx;
421
+ if (idx === -1) nextIdx = ev.shiftKey ? items.length - 1 : 0;
422
+ else nextIdx = (idx + (ev.shiftKey ? -1 : 1) + items.length) % items.length;
423
+ items[nextIdx].focus();
424
+ }
425
+ };
426
+ var COOP_HINT = "The popup was severed from this window as soon as INVO's page loaded. Your page most likely sends `Cross-Origin-Opener-Policy: same-origin`; use `same-origin-allow-popups` so the hosted page can reach window.opener. The grant is still live: the device_approval.approved webhook will tell your server.";
427
+ var BLOCKED_HINT = "The browser blocked the popup. Nothing was started \u2014 call approveHosted() from a click handler.";
428
+ function pollToken(err) {
429
+ if (!(err instanceof InvoError) || err.status === 0 || err.status === 429 || err.status >= 500) return null;
430
+ const body = err.body && typeof err.body === "object" ? err.body : {};
431
+ const token = typeof body["error"] === "string" ? body["error"] : "";
432
+ return { token, body };
433
+ }
434
+ async function runHostedApproval(opts, api, deps = {}) {
435
+ if (typeof window === "undefined") {
436
+ throw new InvoError({
437
+ message: "approveHosted requires a browser window.",
438
+ code: "DOM_UNAVAILABLE",
439
+ status: 0
440
+ });
441
+ }
442
+ if (!opts.transactionId || !String(opts.transactionId).trim()) {
443
+ throw new Error("approveHosted requires a `transactionId`.");
444
+ }
445
+ if (!HOSTED_FLOWS.includes(opts.flow)) {
446
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}" (expected ${HOSTED_FLOWS.join(" | ")}).`);
447
+ }
448
+ if (opts.renderPrompt !== false && typeof document === "undefined") {
449
+ throw new InvoError({
450
+ message: "approveHosted needs a DOM to render the match-code prompt (or pass renderPrompt:false).",
451
+ code: "DOM_UNAVAILABLE",
452
+ status: 0
453
+ });
454
+ }
455
+ const signal = opts.signal;
456
+ if (signal?.aborted) return { status: "closed", popupBlocked: false };
457
+ const open = deps.open ?? ((u, n, f) => window.open(u, n, f));
458
+ const navigate = deps.navigate ?? ((u) => window.location.assign(u));
459
+ const closedPollMs = deps.closedPollMs ?? 500;
460
+ const coopGraceMs = deps.coopGraceMs ?? 1500;
461
+ const createPrompt = deps.createPrompt ?? (() => new HostedEnrollmentPrompt());
462
+ const width = opts.popup?.width ?? 480;
463
+ const height = opts.popup?.height ?? 720;
464
+ const sw = window.screen?.width ?? width;
465
+ const sh = window.screen?.height ?? height;
466
+ const left = Math.max(0, Math.round((sw - width) / 2));
467
+ const top = Math.max(0, Math.round((sh - height) / 2));
468
+ const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
469
+ const name = `invo-approval-${encodeURIComponent(String(opts.transactionId)).replace(/[^A-Za-z0-9-]/g, "")}`;
470
+ let popup;
471
+ try {
472
+ popup = open("about:blank", name, features);
473
+ } catch {
474
+ popup = null;
475
+ }
476
+ const mode = opts.popupBlocked ?? "resolve";
477
+ if (!popup && mode === "resolve") {
478
+ return { status: "blocked", popupBlocked: true, message: BLOCKED_HINT };
479
+ }
480
+ let begin;
481
+ try {
482
+ begin = await api.begin();
483
+ } catch (err) {
484
+ try {
485
+ popup?.close();
486
+ } catch {
487
+ }
488
+ if (signal?.aborted || err instanceof InvoError && err.code === "ABORTED") {
489
+ return { status: "closed", popupBlocked: false };
490
+ }
491
+ throw err;
492
+ }
493
+ const deviceCode = typeof begin["device_code"] === "string" ? begin["device_code"] : "";
494
+ const url = typeof begin["verification_uri_complete"] === "string" ? begin["verification_uri_complete"] : "";
495
+ if (!deviceCode || !url) {
496
+ try {
497
+ popup?.close();
498
+ } catch {
499
+ }
500
+ const { device_code: _dc, ...safeBody } = begin;
501
+ throw new InvoError({
502
+ message: "begin returned no device_code / verification_uri_complete.",
503
+ code: "UNEXPECTED_RESPONSE",
504
+ status: 0,
505
+ body: safeBody
506
+ });
507
+ }
508
+ let origin;
509
+ try {
510
+ origin = derivePlatformOrigin(url, opts.platformOrigin);
511
+ } catch (err) {
512
+ try {
513
+ popup?.close();
514
+ } catch {
515
+ }
516
+ throw err;
517
+ }
518
+ const expiresIn = Math.min(
519
+ MAX_EXPIRES_IN_S,
520
+ Math.max(1, Number(begin["expires_in"]) || 600)
521
+ );
522
+ let interval = Math.max(1, Number(begin["interval"]) || 5);
523
+ if (!popup) {
524
+ try {
525
+ navigate(url);
526
+ return { status: "redirected", popupBlocked: true };
527
+ } catch (err) {
528
+ return {
529
+ status: "blocked",
530
+ popupBlocked: true,
531
+ message: `The browser blocked the popup and the redirect fallback failed${err instanceof Error && err.message ? `: ${err.message}` : "."}`
532
+ };
533
+ }
534
+ }
535
+ const win = popup;
536
+ try {
537
+ const loc = win.location;
538
+ if (loc && typeof loc.replace === "function") loc.replace(url);
539
+ else if (loc) loc.href = url;
540
+ } catch {
541
+ }
542
+ const navigatedAt = Date.now();
543
+ try {
544
+ win.focus?.();
545
+ } catch {
546
+ }
547
+ return new Promise((resolve, reject) => {
548
+ let settled = false;
549
+ let prompt;
550
+ let wake = null;
551
+ let expiryTimer;
552
+ let closedTimer;
553
+ const cleanup = (closePopup) => {
554
+ settled = true;
555
+ window.removeEventListener("message", onMessage);
556
+ signal?.removeEventListener("abort", onAbort);
557
+ if (expiryTimer !== void 0) clearTimeout(expiryTimer);
558
+ if (closedTimer !== void 0) clearInterval(closedTimer);
559
+ prompt?.clear();
560
+ if (closePopup && !win.closed) {
561
+ try {
562
+ win.close();
563
+ } catch {
564
+ }
565
+ }
566
+ wake?.();
567
+ };
568
+ const finish = (result, closePopup) => {
569
+ if (settled) return;
570
+ cleanup(closePopup);
571
+ resolve(result);
572
+ };
573
+ const fail = (err) => {
574
+ if (settled) return;
575
+ cleanup(false);
576
+ reject(err);
577
+ };
578
+ const respond = async (decision) => {
579
+ if (settled) return;
580
+ try {
581
+ await api.confirmEnrollment(deviceCode, decision);
582
+ } catch (err) {
583
+ if (err instanceof InvoError && err.rawCode && CONFIRM_QUIET_CODES.has(err.rawCode)) {
584
+ prompt?.update(null);
585
+ return;
586
+ }
587
+ throw err;
588
+ }
589
+ wake?.();
590
+ };
591
+ const ensurePrompt = () => {
592
+ if (!prompt) {
593
+ prompt = createPrompt();
594
+ prompt.configure({
595
+ respond,
596
+ onEnrollment: opts.onEnrollment,
597
+ renderPrompt: opts.renderPrompt !== false
598
+ });
599
+ }
600
+ return prompt;
601
+ };
602
+ const showEnrollment = (input) => {
603
+ const e = input && typeof input === "object" ? input : null;
604
+ if (e) ensurePrompt().update(e);
605
+ else prompt?.update(null);
606
+ };
607
+ const onMessage = (event) => {
608
+ if (event.origin !== origin) return;
609
+ if (event.source && event.source !== win) return;
610
+ const data = event.data;
611
+ if (!data || typeof data !== "object" || data.type !== HOSTED_MESSAGE_TYPE) return;
612
+ wake?.();
613
+ };
614
+ const onAbort = () => finish({ status: "closed", popupBlocked: false }, true);
615
+ const pause = (ms) => new Promise((r) => {
616
+ const t = setTimeout(() => {
617
+ wake = null;
618
+ r();
619
+ }, ms);
620
+ wake = () => {
621
+ clearTimeout(t);
622
+ wake = null;
623
+ r();
624
+ };
625
+ });
626
+ window.addEventListener("message", onMessage);
627
+ signal?.addEventListener("abort", onAbort, { once: true });
628
+ expiryTimer = setTimeout(() => finish({ status: "expired", popupBlocked: false }, false), expiresIn * 1e3);
629
+ closedTimer = setInterval(() => {
630
+ if (!win.closed) return;
631
+ if (Date.now() - navigatedAt < coopGraceMs) {
632
+ finish({ status: "blocked", popupBlocked: true, message: COOP_HINT }, false);
633
+ } else {
634
+ finish({ status: "closed", popupBlocked: false }, false);
635
+ }
636
+ }, closedPollMs);
637
+ void (async () => {
638
+ let transientFailures = 0;
639
+ while (!settled) {
640
+ await pause(interval * 1e3);
641
+ if (settled) return;
642
+ let raw;
643
+ try {
644
+ raw = await api.poll(deviceCode);
645
+ } catch (err) {
646
+ if (settled) return;
647
+ const p = pollToken(err);
648
+ if (!p) {
649
+ if (++transientFailures >= MAX_TRANSIENT_POLL_FAILURES) return fail(err);
650
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
651
+ if (typeof ra === "number" && ra > interval) interval = Math.min(ra, MAX_EXPIRES_IN_S);
652
+ continue;
653
+ }
654
+ transientFailures = 0;
655
+ const bodyInterval = Number(p.body["interval"]);
656
+ switch (p.token) {
657
+ case "authorization_pending":
658
+ if (bodyInterval > 0) interval = bodyInterval;
659
+ showEnrollment(p.body["enrollment"]);
660
+ continue;
661
+ case "slow_down":
662
+ interval = Math.max(interval + 5, bodyInterval > 0 ? bodyInterval : 0);
663
+ continue;
664
+ case "expired_token":
665
+ return finish({ status: "expired", popupBlocked: false }, false);
666
+ case "access_denied":
667
+ return finish({ status: "denied", popupBlocked: false }, false);
668
+ default:
669
+ return fail(err);
670
+ }
671
+ }
672
+ if (settled) return;
673
+ if (raw["status"] !== "approved") continue;
674
+ try {
675
+ const approval = await api.approve(deviceCode);
676
+ if (settled) return;
677
+ finish({ status: "approved", popupBlocked: false, approval }, true);
678
+ } catch (err) {
679
+ fail(err);
680
+ }
681
+ return;
682
+ }
683
+ })();
684
+ });
685
+ }
686
+
687
+ // src/index.ts
688
+ function clientInvalidInput(message) {
689
+ return new InvoError({ message, code: "INVALID_INPUT", status: 0 });
690
+ }
691
+ function randomNonce() {
692
+ const c = globalThis.crypto;
693
+ if (!c || typeof c.getRandomValues !== "function") {
694
+ throw clientInvalidInput(
695
+ "No secure random source in this environment; pass a deviceSignal you built yourself."
696
+ );
697
+ }
698
+ const bytes = c.getRandomValues(new Uint8Array(16));
699
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
700
+ }
701
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
702
+ function toPendingCollectItem(row) {
703
+ return {
704
+ transferId: String(row["transfer_id"] ?? ""),
705
+ kind: String(row["kind"] ?? ""),
706
+ flow: String(row["flow"] ?? ""),
707
+ amount: row["amount"] ?? null,
708
+ currency: String(row["currency"] ?? ""),
709
+ counterpartyGame: String(row["counterparty_game"] ?? ""),
710
+ expiresAt: row["expires_at"] ?? null,
711
+ stepUpRequired: row["step_up_required"] === true,
712
+ held: row["held"] === true,
713
+ holdReason: row["hold_reason"] ?? null,
714
+ raw: row
715
+ };
716
+ }
717
+ function toBalanceRow(row) {
718
+ return {
719
+ currencyId: row["currency_id"] ?? "",
720
+ currencyName: String(row["currency_name"] ?? ""),
721
+ currencySymbol: row["currency_symbol"] ?? null,
722
+ currencySymbolUrl: row["currency_symbol_url"] ?? null,
723
+ availableBalance: String(row["available_balance"] ?? ""),
724
+ reservedBalance: String(row["reserved_balance"] ?? ""),
725
+ totalBalance: String(row["total_balance"] ?? ""),
726
+ raw: row
727
+ };
728
+ }
729
+ function toApproveResult(raw, transactionId) {
730
+ const holdReason = raw["error_code"] ?? raw["code"];
731
+ return {
732
+ status: String(raw["status"] ?? ""),
733
+ next: String(raw["next"] ?? ""),
734
+ transactionId: String(raw["transaction_id"] ?? transactionId),
735
+ claimCode: raw["claim_code"],
736
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
737
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
738
+ risk: raw["risk"],
739
+ guardianApproval: raw["guardian_approval"] ?? void 0,
740
+ pollEndpoint: raw["poll_endpoint"],
741
+ ...typeof raw["claim_delivery"] === "string" && raw["claim_delivery"] ? { claimDelivery: raw["claim_delivery"] } : {},
742
+ raw
743
+ };
744
+ }
745
+ function toConfirmReceiptResult(raw) {
746
+ const holdReason = raw["error_code"] ?? raw["code"];
747
+ return {
748
+ status: String(raw["status"] ?? ""),
749
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
750
+ raw
751
+ };
752
+ }
753
+ var PlatformCommerceClient = class {
754
+ /**
755
+ * Embed INVO's hosted checkout in an iframe and listen for completion.
756
+ *
757
+ * ```ts
758
+ * const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
759
+ * onComplete: () => showProcessing(), // then reconcile server-side
760
+ * });
761
+ * // later: handle.destroy();
762
+ * ```
763
+ *
764
+ * Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
765
+ * the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
766
+ *
767
+ * `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
768
+ * from the checkout URL's own origin (any other window could forge the event). It is a
769
+ * UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
770
+ * on this client event.
771
+ */
772
+ mountCheckout(el, checkoutUrl, opts) {
773
+ if (typeof document === "undefined" || typeof window === "undefined") {
774
+ throw new InvoError({
775
+ message: "mountCheckout requires a browser DOM (window/document).",
776
+ code: "DOM_UNAVAILABLE",
777
+ status: 0
778
+ });
779
+ }
780
+ if (!checkoutUrl || !checkoutUrl.trim()) {
781
+ throw new Error("mountCheckout requires the server-returned `checkoutUrl`.");
782
+ }
783
+ let checkoutOrigin;
784
+ try {
785
+ const u = new URL(checkoutUrl);
786
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1";
787
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
788
+ throw new Error("not https");
789
+ }
790
+ checkoutOrigin = u.origin;
791
+ } catch {
792
+ throw new InvoError({
793
+ message: "mountCheckout requires an absolute https checkoutUrl.",
794
+ code: "INVALID_INPUT",
795
+ status: 0
796
+ });
797
+ }
798
+ const container = typeof el === "string" ? document.querySelector(el) : el;
799
+ if (!container) {
800
+ throw new InvoError({
801
+ message: `mountCheckout could not find the container "${String(el)}".`,
802
+ code: "MOUNT_NOT_FOUND",
803
+ status: 0
804
+ });
805
+ }
806
+ const iframe = document.createElement("iframe");
807
+ iframe.src = checkoutUrl;
808
+ iframe.title = opts?.title ?? "INVO checkout";
809
+ if (opts?.className) iframe.className = opts.className;
810
+ iframe.style.width = "100%";
811
+ iframe.style.border = "0";
812
+ iframe.allow = "payment";
813
+ const onMessage = (event) => {
814
+ if (event.origin !== checkoutOrigin) return;
815
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
816
+ const msg = event.data;
817
+ if (!msg || msg.type !== "INVO_CHECKOUT_COMPLETE") return;
818
+ opts?.onComplete?.(
819
+ msg.data && typeof msg.data === "object" ? msg.data : {}
820
+ );
821
+ };
822
+ window.addEventListener("message", onMessage);
823
+ container.appendChild(iframe);
824
+ return {
825
+ iframe,
826
+ destroy() {
827
+ window.removeEventListener("message", onMessage);
828
+ iframe.remove();
829
+ }
830
+ };
831
+ }
832
+ };
833
+ var DEFAULT_PURCHASE_POLL_INTERVAL_MS = 1500;
834
+ var DEFAULT_PURCHASE_POLL_TIMEOUT_MS = 18e4;
835
+ function pollSleep(ms, signal) {
836
+ return new Promise((resolve) => {
837
+ if (signal?.aborted) return resolve();
838
+ const timer = setTimeout(done, ms);
839
+ const onAbort = () => done();
840
+ function done() {
841
+ clearTimeout(timer);
842
+ signal?.removeEventListener("abort", onAbort);
843
+ resolve();
844
+ }
845
+ signal?.addEventListener("abort", onAbort, { once: true });
846
+ });
847
+ }
848
+ function isTransientPollFailure(err) {
849
+ if (!(err instanceof InvoError)) return false;
850
+ if (err.code === "ABORTED") return false;
851
+ return err.status === 0 || err.status === 429 || err.status >= 500;
852
+ }
853
+ var CheckoutClient = class _CheckoutClient {
854
+ constructor(config) {
855
+ if (!config?.baseUrl) throw new Error("CheckoutClient requires a `baseUrl`.");
856
+ assertSecureBaseUrl(config.baseUrl);
857
+ this.http = new Http({
858
+ baseUrl: config.baseUrl,
859
+ timeoutMs: config.timeoutMs,
860
+ fetchImpl: config.fetch,
861
+ maxRetries: config.maxRetries,
862
+ retryBaseDelayMs: config.retryBaseDelayMs,
863
+ hooks: config.hooks
864
+ });
865
+ }
866
+ /**
867
+ * Wrap an `Http` the owning client already built, so `invo.checkout` shares that
868
+ * client's baseUrl, timeout, retry budget and observability hooks.
869
+ *
870
+ * @internal Not part of the public API; it takes an internal type and may change.
871
+ */
872
+ static _withHttp(http) {
873
+ const client = Object.create(_CheckoutClient.prototype);
874
+ client.http = http;
875
+ return client;
876
+ }
877
+ /**
878
+ * Read a purchase's status once.
879
+ *
880
+ * Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
881
+ * including "we have your money and your coins are not there". There is no tenant gate
882
+ * on it: a partner suspended after a buyer's card was charged is exactly the case it
883
+ * exists for.
884
+ *
885
+ * Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
886
+ * `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
887
+ * `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
888
+ * expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
889
+ * and a Contact support link).
890
+ *
891
+ * Storefront (in-client) purchases are keyed on the partner's own purchase reference
892
+ * rather than on a checkout session, so a read by session id finds nothing and answers
893
+ * `pending`. Do not conclude from that that such a purchase never happened.
894
+ */
895
+ async getPurchaseStatus(input, opts) {
896
+ const sessionId = String(input?.sessionId ?? "").trim();
897
+ const sessionToken = String(input?.sessionToken ?? "").trim();
898
+ if (!sessionId) {
899
+ throw new InvoError({
900
+ message: "getPurchaseStatus requires `sessionId` (from createCheckout).",
901
+ code: "INVALID_INPUT",
902
+ status: 0
903
+ });
904
+ }
905
+ if (!sessionToken) {
906
+ throw new InvoError({
907
+ message: "getPurchaseStatus requires `sessionToken`. The session token is the credential; the id in the path is not.",
908
+ code: "INVALID_INPUT",
909
+ status: 0
910
+ });
911
+ }
912
+ const raw = await this.http.get(
913
+ `/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
914
+ { kind: "bearer", token: sessionToken },
915
+ { signal: opts?.signal }
916
+ );
917
+ return toPurchaseStatusResult(raw, sessionId);
918
+ }
919
+ /**
920
+ * Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
921
+ * that final result.
922
+ *
923
+ * ```ts
924
+ * const result = await invo.checkout.waitForPurchase({
925
+ * sessionId, sessionToken,
926
+ * intervalMs: 1500,
927
+ * timeoutMs: 300_000,
928
+ * signal: controller.signal,
929
+ * onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
930
+ * });
931
+ * if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
932
+ * else if (result.message) showMessage(result.message, result.orderId); // verbatim
933
+ * ```
934
+ *
935
+ * IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
936
+ * the response; this loop never recomputes it from `status`, so a status a later backend
937
+ * introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
938
+ * not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
939
+ * stalled credit, and telling a buyer they lost money they are about to receive would
940
+ * be a fresh lie in place of the old silence.
941
+ *
942
+ * A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
943
+ * a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
944
+ * read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
945
+ * keeps showing the buyer what INVO last said. If it never got a single answer, the last
946
+ * transport failure is thrown.
947
+ */
948
+ async waitForPurchase(input) {
949
+ const intervalMs = Math.max(0, input?.intervalMs ?? DEFAULT_PURCHASE_POLL_INTERVAL_MS);
950
+ const timeoutMs = Math.max(0, input?.timeoutMs ?? DEFAULT_PURCHASE_POLL_TIMEOUT_MS);
951
+ const maxAttempts = input?.maxAttempts === void 0 ? Number.POSITIVE_INFINITY : Math.max(1, input.maxAttempts);
952
+ const deadline = Date.now() + timeoutMs;
953
+ const signal = input?.signal;
954
+ let last;
955
+ let lastFailure;
956
+ for (let attempts = 0; ; ) {
957
+ if (signal?.aborted) {
958
+ throw new InvoError({
959
+ message: "waitForPurchase was aborted",
960
+ code: "ABORTED",
961
+ status: 0
962
+ });
963
+ }
964
+ attempts += 1;
965
+ try {
966
+ const result = await this.getPurchaseStatus(input, { signal });
967
+ last = result;
968
+ lastFailure = void 0;
969
+ try {
970
+ input?.onUpdate?.(result);
971
+ } catch {
972
+ }
973
+ if (result.terminal) return result;
974
+ } catch (err) {
975
+ if (!isTransientPollFailure(err)) throw err;
976
+ lastFailure = err;
977
+ }
978
+ if (attempts >= maxAttempts) break;
979
+ if (Date.now() + intervalMs >= deadline) break;
980
+ await pollSleep(intervalMs, signal);
981
+ }
982
+ if (last) return last;
983
+ throw lastFailure instanceof Error ? lastFailure : new InvoError({
984
+ message: "waitForPurchase could not read the purchase status before the cap.",
985
+ code: "PURCHASE_STATUS_UNAVAILABLE",
986
+ status: 0
987
+ });
988
+ }
989
+ };
990
+ var InvoClient = class {
991
+ constructor(config) {
992
+ /**
993
+ * Platform Commerce (ecommerce) hosted-checkout embed. Use after
994
+ * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
995
+ * `checkoutUrl` — either redirect the buyer there, or embed it with
996
+ * `mountCheckout`. No card element, no processor dependency. See
997
+ * {@link PlatformCommerceClient}.
998
+ */
999
+ this.platformCommerce = new PlatformCommerceClient();
1000
+ if (!config.token) throw new Error("InvoClient requires a player `token`.");
1001
+ if (!config.baseUrl) throw new Error("InvoClient requires a `baseUrl`.");
1002
+ assertSecureBaseUrl(config.baseUrl);
1003
+ this.http = new Http({
1004
+ baseUrl: config.baseUrl,
1005
+ timeoutMs: config.timeoutMs,
1006
+ fetchImpl: config.fetch,
1007
+ maxRetries: config.maxRetries,
1008
+ retryBaseDelayMs: config.retryBaseDelayMs,
1009
+ hooks: config.hooks
1010
+ // Browser: do NOT set User-Agent (forbidden header); the browser's own UA is fine.
1011
+ });
1012
+ this.auth = { kind: "bearer", token: config.token };
1013
+ this.refreshToken = config.refreshToken;
1014
+ this.checkout = CheckoutClient._withHttp(this.http);
1015
+ }
1016
+ assertWebAuthn() {
1017
+ if (typeof navigator === "undefined" || !navigator.credentials) {
1018
+ throw new Error("WebAuthn is not available in this environment (browser required).");
1019
+ }
1020
+ }
1021
+ /**
1022
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
1023
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
1024
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
1025
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
1026
+ */
1027
+ async enrollPasskey(opts) {
1028
+ this.assertWebAuthn();
1029
+ const signal = opts?.signal;
1030
+ return this.withTokenRetry(async () => {
1031
+ const options = await this.post(
1032
+ "/api/sdk/webauthn/register/begin",
1033
+ void 0,
1034
+ signal
1035
+ );
1036
+ const cred = await navigator.credentials.create({
1037
+ publicKey: toCreationOptions(options),
1038
+ signal
1039
+ });
1040
+ if (!cred) throw new Error("Passkey creation was cancelled or returned no credential.");
1041
+ const raw = await this.post(
1042
+ "/api/sdk/webauthn/register/complete",
1043
+ { credential: registrationToJSON(cred) },
1044
+ signal
1045
+ );
1046
+ return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
1047
+ });
1048
+ }
1049
+ async approveHosted(opts) {
1050
+ const txn = String(opts.transactionId ?? "");
1051
+ const id = encodeURIComponent(txn);
1052
+ const signal = opts.signal;
1053
+ const api = {
1054
+ begin: () => this.withTokenRetry(
1055
+ () => this.post(
1056
+ "/api/sdk/approvals/device/begin",
1057
+ { transaction_id: txn, flow: opts.flow, channel: "popup" },
1058
+ signal
1059
+ )
1060
+ ),
1061
+ poll: (deviceCode) => this.withTokenRetry(
1062
+ () => this.post(
1063
+ "/api/sdk/approvals/device/poll",
1064
+ { device_code: deviceCode },
1065
+ signal
1066
+ )
1067
+ ),
1068
+ confirmEnrollment: (deviceCode, decision) => this.withTokenRetry(
1069
+ () => this.post(
1070
+ "/api/sdk/approvals/device/confirm-enrollment",
1071
+ { device_code: deviceCode, decision },
1072
+ signal
1073
+ )
1074
+ ),
1075
+ approve: (deviceCode) => this.withTokenRetry(async () => {
1076
+ const body = { device_code: deviceCode };
1077
+ switch (opts.flow) {
1078
+ case "transfer":
1079
+ return toApproveResult(
1080
+ await this.post(`/api/sdk/transfers/${id}/approve`, body, signal),
1081
+ txn
1082
+ );
1083
+ case "send":
1084
+ return toApproveResult(
1085
+ await this.post(`/api/sdk/send/${id}/approve`, body, signal),
1086
+ txn
1087
+ );
1088
+ case "send_receipt":
1089
+ return toConfirmReceiptResult(
1090
+ await this.post(`/api/sdk/send/${id}/confirm-receipt`, body, signal)
1091
+ );
1092
+ case "transfer_receipt":
1093
+ return toConfirmReceiptResult(
1094
+ await this.post(`/api/sdk/transfers/${id}/confirm-receipt`, body, signal)
1095
+ );
1096
+ default:
1097
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}".`);
1098
+ }
1099
+ })
1100
+ };
1101
+ return runHostedApproval(opts, api);
1102
+ }
1103
+ /**
1104
+ * Approve a SEND with the player's passkey.
1105
+ *
1106
+ * Throws 403 `err.isPlayerTokenStale` when the player token predates a change to the
1107
+ * sender's identity (their phone was added on the initiate). Not retried automatically,
1108
+ * because this call moves money: re-mint the player token (or use the `playerToken`
1109
+ * your server got back from `initiateSend`) and retry once.
1110
+ */
1111
+ async approveSend(transactionId, opts) {
1112
+ return this.approve("send", transactionId, opts);
1113
+ }
1114
+ /** Approve a TRANSFER with the player's passkey (returns the sender's claim code). Same
1115
+ * `err.isPlayerTokenStale` handling as {@link approveSend}: re-mint and retry once. */
1116
+ async approveTransfer(transactionId, opts) {
1117
+ return this.approve("transfers", transactionId, opts);
1118
+ }
1119
+ /**
1120
+ * Recipient self-claims a SEND with their passkey.
1121
+ *
1122
+ * May throw a 409 with `err.isPhoneShareApprovalRequired` when the receiver phone is
1123
+ * contested (the collecting identity isn't yet authorized for it). NOT a failure — the
1124
+ * money is held and the phone owner is texted to approve. Show `err.message`
1125
+ * (`err.phoneShareLast4` names the phone), then **retry this same call** once approved
1126
+ * (it then succeeds idempotently); on denial/expiry the backend refunds the sender.
1127
+ */
1128
+ async confirmReceiptSend(transactionId, opts) {
1129
+ return this.confirmReceipt("send", transactionId, opts);
1130
+ }
1131
+ /** Recipient self-claims a TRANSFER with their passkey. Can throw the same phone-share
1132
+ * 409 as {@link confirmReceiptSend} (`err.isPhoneShareApprovalRequired`) — handle it the
1133
+ * same way: show `err.message`, retry after the phone owner approves. */
1134
+ async confirmReceiptTransfer(transactionId, opts) {
1135
+ return this.confirmReceipt("transfers", transactionId, opts);
1136
+ }
1137
+ /**
1138
+ * Phone changes waiting for THIS player's enrolled device to approve
1139
+ * (`GET /api/sdk/players/phone/change-approvals`, player token). A row appears after the
1140
+ * player entered the emailed code on INVO's page for a change whose `confirmation` is
1141
+ * `"email_code_and_device"`. Show each one ("Approve changing your number to
1142
+ * ***-***-0123?") and answer it with {@link approvePhoneChange}. Read-only.
1143
+ */
1144
+ async listPhoneChangeApprovals(opts) {
1145
+ return this.withTokenRetry(async () => {
1146
+ const raw = await this.get(
1147
+ "/api/sdk/players/phone/change-approvals",
1148
+ opts?.signal
1149
+ );
1150
+ return toPhoneChangeApprovalsResult(raw);
1151
+ });
1152
+ }
1153
+ /**
1154
+ * Approve (or, with `decision: "deny"`, decline) a phone change from the player's enrolled
1155
+ * device (`POST /api/sdk/players/phone/change-requests/{id}/approve`, player token).
1156
+ *
1157
+ * The device key signs `phone-change|<changeRequestId>|<nonce>|<timestamp>` to approve or
1158
+ * `phone-change-deny|<changeRequestId>|<nonce>|<timestamp>` to decline (`timestamp` in
1159
+ * epoch seconds). Either pass `sign`, and the SDK makes a fresh nonce and timestamp, builds
1160
+ * that message and asks you for the base64 signature; or pass a `deviceSignal` you signed
1161
+ * yourself (build the message with {@link phoneChangeSignalMessage}). This is a device key
1162
+ * registered with INVO, not a passkey.
1163
+ *
1164
+ * `status: "confirmed"` means the change is applied: store `identityId` and use
1165
+ * `playerToken` (tokens minted before the change are stale). `status: "denied"` means
1166
+ * nothing changed. Refusals: 409 `err.isChangeRequestNotReady` (the player has not entered
1167
+ * the code on INVO's page yet), 409 `err.isChangeRequestNotPending` (`err.changeRequestStatus`),
1168
+ * 409 `err.isDeviceEnrolledAfterRequest` (this device was set up after the change was
1169
+ * requested; approve on the earlier device, or the game creates a new request), 409
1170
+ * `err.isPhoneChangeRecoveryCooldown` (a recent sign-in recovery; retry later, declining
1171
+ * still works), 404 `err.isChangeRequestNotFound`, 401 `err.isDeviceSignalRejected`, 403
1172
+ * `DEVICE_REQUIRES_ELEVATION`, or any refusal of the change itself (for example
1173
+ * `err.isPendingTransfersToOldPhone`).
1174
+ */
1175
+ async approvePhoneChange(changeRequestId, input, opts) {
1176
+ if (typeof changeRequestId !== "string" || !changeRequestId.trim()) {
1177
+ throw clientInvalidInput("changeRequestId is required.");
1178
+ }
1179
+ if (!input || typeof input.deviceFingerprint !== "string" || !input.deviceFingerprint.trim()) {
1180
+ throw clientInvalidInput("deviceFingerprint is required.");
1181
+ }
1182
+ const decision = input.decision ?? "approve";
1183
+ if (decision !== "approve" && decision !== "deny") {
1184
+ throw clientInvalidInput('decision must be "approve" or "deny".');
1185
+ }
1186
+ const hasSignal = input.deviceSignal !== void 0;
1187
+ const hasSigner = typeof input.sign === "function";
1188
+ if (hasSignal === hasSigner) {
1189
+ throw clientInvalidInput("Pass exactly one of deviceSignal or sign.");
1190
+ }
1191
+ if (hasSignal) {
1192
+ const sig = input.deviceSignal;
1193
+ if (!sig || typeof sig.nonce !== "string" || !sig.nonce || typeof sig.timestamp !== "number" || !Number.isInteger(sig.timestamp) || typeof sig.signature !== "string" || !sig.signature) {
1194
+ throw clientInvalidInput(
1195
+ "deviceSignal needs a nonce (string), an integer epoch-seconds timestamp and a base64 signature."
1196
+ );
1197
+ }
1198
+ }
1199
+ const id = encodeURIComponent(changeRequestId);
1200
+ const signal = opts?.signal;
1201
+ return this.withTokenRetry(async () => {
1202
+ let deviceSignal;
1203
+ if (hasSignal) {
1204
+ const sig = input.deviceSignal;
1205
+ deviceSignal = {
1206
+ transfer_id: changeRequestId,
1207
+ nonce: sig.nonce,
1208
+ timestamp: sig.timestamp,
1209
+ signature: sig.signature
1210
+ };
1211
+ } else {
1212
+ const nonce = randomNonce();
1213
+ const timestamp = Math.floor(Date.now() / 1e3);
1214
+ const signature = await input.sign(
1215
+ phoneChangeSignalMessage(changeRequestId, nonce, timestamp, decision)
1216
+ );
1217
+ if (typeof signature !== "string" || !signature) {
1218
+ throw clientInvalidInput("sign must return the base64 signature as a non-empty string.");
1219
+ }
1220
+ deviceSignal = { transfer_id: changeRequestId, nonce, timestamp, signature };
1221
+ }
1222
+ const raw = await this.post(
1223
+ `/api/sdk/players/phone/change-requests/${id}/approve`,
1224
+ { device_fingerprint: input.deviceFingerprint, device_signal: deviceSignal, decision },
1225
+ signal
1226
+ );
1227
+ return toApprovePhoneChangeResult(raw, changeRequestId);
1228
+ });
1229
+ }
1230
+ /**
1231
+ * Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
1232
+ * INVO app device key) to authorize adding a new partner passkey. The returned
1233
+ * single-use grant lets a subsequent enrollPasskey() succeed instead of being
1234
+ * blocked with ENROLLMENT_REQUIRES_PROOF.
1235
+ *
1236
+ * begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
1237
+ *
1238
+ * Call it with no arguments: `await invo.linkDevice()`. THE SERVER MINTS THE
1239
+ * LINK ID, so there is nothing for the caller to supply. The parameter is kept
1240
+ * (optional, and sent but ignored by the server) so that code written against
1241
+ * 3.10 and earlier, which had to pass a placeholder, keeps compiling and
1242
+ * working unchanged.
1243
+ */
1244
+ async linkDevice(linkId, opts) {
1245
+ this.assertWebAuthn();
1246
+ const signal = opts?.signal;
1247
+ return this.withTokenRetry(async () => {
1248
+ const begin = await this.post(
1249
+ "/api/sdk/device/link/webauthn/begin",
1250
+ // The server ignores the body and mints its own id; `linkId` travels only
1251
+ // for callers who still pass one.
1252
+ linkId ? { link_id: linkId } : {},
1253
+ signal
1254
+ );
1255
+ const cred = await navigator.credentials.get({
1256
+ publicKey: toRequestOptions(begin.options),
1257
+ signal
1258
+ });
1259
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
1260
+ const raw = await this.post(
1261
+ "/api/sdk/device/link/webauthn/complete",
1262
+ { link_id: begin.link_id, webauthn_assertion: assertionToJSON(cred) },
1263
+ signal
1264
+ );
1265
+ return { status: String(raw["status"] ?? ""), raw };
1266
+ });
1267
+ }
1268
+ /**
1269
+ * List the player's own pending items to collect (browser, player-token). Each row's
1270
+ * `kind` tells you which action to call: `"identity_gate"` → `approve*` (you initiated);
1271
+ * `"receiving_confirm"` → `confirmReceipt*` (a peer sent to you). PII-free — no claim
1272
+ * code or phone (those are only on the server-side `getInboundPending`).
1273
+ */
1274
+ async getPendingCollect(opts) {
1275
+ return this.withTokenRetry(async () => {
1276
+ const raw = await this.get(
1277
+ "/api/sdk/transfers/pending",
1278
+ opts?.signal
1279
+ );
1280
+ const rows = Array.isArray(raw["pending"]) ? raw["pending"] : [];
1281
+ return { pending: rows.map(toPendingCollectItem), raw };
1282
+ });
1283
+ }
1284
+ /**
1285
+ * List the games/tenants this player can send/transfer to, with display metadata
1286
+ * inline (name, icon, currency, min/max limits) — one call, no per-game lookup.
1287
+ * Source game is the token's own game. Player-token (browser).
1288
+ */
1289
+ async getDestinations(query, opts) {
1290
+ const direction = query?.direction ?? "transfer";
1291
+ return this.withTokenRetry(async () => {
1292
+ const raw = await this.get(
1293
+ `/api/sdk/destinations?direction=${encodeURIComponent(direction)}`,
1294
+ opts?.signal
1295
+ );
1296
+ return toDestinationsResult(raw, direction);
1297
+ });
1298
+ }
1299
+ /**
1300
+ * The player's balances for the token's game (browser, player-token). Amounts are
1301
+ * decimal strings. A player who hasn't transacted here yet returns `200` with an empty
1302
+ * `balances` array (show 0.00) — not an error; a `404 GAME_NOT_FOUND` (bad game/token)
1303
+ * throws. Rows include the currency symbol + icon URL (each may be null).
1304
+ */
1305
+ async getBalance(opts) {
1306
+ return this.withTokenRetry(async () => {
1307
+ const raw = await this.get("/api/sdk/balance", opts?.signal);
1308
+ const rows = Array.isArray(raw["balances"]) ? raw["balances"] : [];
1309
+ const summary = raw["summary"] ?? {};
1310
+ return {
1311
+ gameId: raw["game_id"] ?? "",
1312
+ gameName: String(raw["game_name"] ?? ""),
1313
+ balances: rows.map(toBalanceRow),
1314
+ totalValue: String(summary["total_value"] ?? "0"),
1315
+ currencyCount: Number(summary["currency_count"] ?? rows.length),
1316
+ hasFunds: summary["has_funds"] === true,
1317
+ raw
1318
+ };
1319
+ });
1320
+ }
1321
+ // ---- Loyalty and rewards (player token) ----
1322
+ /**
1323
+ * The signed-in player's loyalty cards in this game: one card per program, each step with
1324
+ * its `state` and `progress` (`{ current, target }`, or `null` when the number could not
1325
+ * be read this time: render `state` alone then), and the rewards the player unlocked.
1326
+ * A card never carries a code; a redeemed reward shows its mask. Your server reads the
1327
+ * same cards for any of your players with `InvoServer.getPlayerRewards(playerEmail)`.
1328
+ */
1329
+ async getMyRewards(opts) {
1330
+ return this.withTokenRetry(async () => {
1331
+ const raw = await this.get("/api/sdk/loyalty/me/card", opts?.signal);
1332
+ return toLoyaltyCardsResult(raw);
1333
+ });
1334
+ }
1335
+ /** Every reward the signed-in player holds or held, newest first. Codes are masked. */
1336
+ async getMyVault(opts) {
1337
+ return this.withTokenRetry(async () => {
1338
+ const raw = await this.get("/api/sdk/loyalty/me/vault", opts?.signal);
1339
+ return toLoyaltyVaultResult(raw);
1340
+ });
1341
+ }
1342
+ /**
1343
+ * Redeem one unlocked reward and return its code. This is the only response that
1344
+ * carries a code: show it straight away and never log, cache or store it. Calling again
1345
+ * for a reward this player already redeemed shows the code once more while the card's
1346
+ * `canRevealAgain` is true (`revealedAgain: true`). Never auto-retried.
1347
+ *
1348
+ * Refusals: `409 already_redeemed` (`err.isRewardAlreadyRedeemed`), `404
1349
+ * vault_entry_not_found` (`err.isRewardNotFound`), `410 vault_entry_expired`
1350
+ * (`err.isRewardExpired`), `409 inventory_exhausted` / `409 conflict`
1351
+ * (`err.isRewardUnavailable`: no units or codes left, or the reward is reserved or revoked).
1352
+ */
1353
+ async redeemReward(vaultEntryId, opts) {
1354
+ if (typeof vaultEntryId !== "string" || !UUID_RE.test(vaultEntryId.trim())) {
1355
+ throw new InvoError({
1356
+ message: `vaultEntryId must be a reward's vaultEntryId (got ${JSON.stringify(vaultEntryId)}).`,
1357
+ code: "INVALID_INPUT",
1358
+ status: 0
1359
+ });
1360
+ }
1361
+ const id = vaultEntryId.trim();
1362
+ return this.withTokenRetry(async () => {
1363
+ const raw = await this.post(
1364
+ `/api/sdk/loyalty/me/vault/${encodeURIComponent(id)}/redeem`,
1365
+ void 0,
1366
+ opts?.signal
1367
+ );
1368
+ return toRedeemRewardResult(raw, id);
1369
+ });
1370
+ }
1371
+ /**
1372
+ * A short-lived link to INVO's hosted "My rewards" page for the signed-in player: their
1373
+ * cards, progress and rewards, with a Redeem button. Open `url` in a browser or web view
1374
+ * (it cannot be embedded in an iframe). Ask for a fresh link each time the player opens
1375
+ * the page; never share or store it.
1376
+ */
1377
+ async getRewardsPageLink(opts) {
1378
+ return this.withTokenRetry(async () => {
1379
+ const raw = await this.post(
1380
+ "/api/sdk/loyalty/me/rewards-page",
1381
+ void 0,
1382
+ opts?.signal
1383
+ );
1384
+ return toRewardsPageLink(raw);
1385
+ });
1386
+ }
1387
+ /**
1388
+ * Report a gameplay event for the signed-in player to INVO's loyalty engine
1389
+ * (`POST /api/sdk/loyalty/events`, player token). Use it for sessions, milestones and
1390
+ * registered custom events (see {@link GameEventType}). Events your SERVER reports with
1391
+ * `InvoServer.reportGameEvent` are the ones trusted for rewards; prefer those when a
1392
+ * reward depends on the event.
1393
+ *
1394
+ * Pass your own `eventId` (a UUID) or reuse the returned one if you retry, so INVO counts
1395
+ * the event once. Not auto-retried from the browser.
1396
+ *
1397
+ * Refusals: `INVALID_INPUT` before the network (non-`game.*` type, malformed `eventId`,
1398
+ * `occurredAt` without a timezone, non-object payload); `400 RESERVED_EVENT_TYPE` /
1399
+ * `EVENT_TYPE_NOT_ALLOWED`; `401 SDK_TOKEN_MISSING` / `SDK_TOKEN_WRONG_SCOPE`;
1400
+ * `422 validation_failed`.
1401
+ */
1402
+ async reportGameEvent(input, opts) {
1403
+ const { body, eventId } = buildGameEventBody(input);
1404
+ return this.withTokenRetry(async () => {
1405
+ const raw = await this.post("/api/sdk/loyalty/events", body, opts?.signal);
1406
+ return toReportGameEventResult(raw ?? {}, eventId);
1407
+ });
1408
+ }
1409
+ /**
1410
+ * First-enrollment OTP grant (§4.2). When `enrollPasskey()` throws
1411
+ * `ENROLLMENT_REQUIRES_AUTHORIZATION` (`err.isEnrollmentAuthorizationRequired`), call
1412
+ * this to send a 6-digit code to the player's phone + email on file, collect the code,
1413
+ * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
1414
+ * `register/complete` auto-consumes the server-side grant (30-min TTL). For
1415
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
1416
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
1417
+ * (player lost/deleted their passkey).
1418
+ */
1419
+ async enrollmentBegin(opts) {
1420
+ return this.withTokenRetry(async () => {
1421
+ const raw = await this.post(
1422
+ "/api/sdk/device/enrollment/begin",
1423
+ void 0,
1424
+ opts?.signal
1425
+ );
1426
+ return {
1427
+ status: String(raw["status"] ?? ""),
1428
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
1429
+ raw
1430
+ };
1431
+ });
1432
+ }
1433
+ /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
1434
+ async enrollmentVerify(code, opts) {
1435
+ if (!code || !code.trim()) throw new Error("enrollmentVerify requires the OTP `code`.");
1436
+ return this.withTokenRetry(async () => {
1437
+ const raw = await this.post(
1438
+ "/api/sdk/device/enrollment/verify",
1439
+ { code },
1440
+ opts?.signal
1441
+ );
1442
+ return { status: String(raw["status"] ?? ""), raw };
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
1447
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
1448
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
1449
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
1450
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
1451
+ *
1452
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
1453
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
1454
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
1455
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
1456
+ * expired code — attempt-capped; let the user retry or resend).
1457
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
1458
+ *
1459
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
1460
+ * the intended tamper alert; surface nothing special for it.
1461
+ *
1462
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
1463
+ * funds immediately, but `approveSend`/`approveTransfer` throw
1464
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
1465
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
1466
+ * the timestamp; do not retry-loop it.
1467
+ *
1468
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
1469
+ * passkey"), have the user delete the stale entry in their password manager first
1470
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
1471
+ * Settings → Accounts → Passkeys).
1472
+ */
1473
+ async recoveryBegin(opts) {
1474
+ return this.withTokenRetry(async () => {
1475
+ const raw = await this.post(
1476
+ "/api/sdk/device/recover/begin",
1477
+ void 0,
1478
+ opts?.signal
1479
+ );
1480
+ return {
1481
+ status: String(raw["status"] ?? ""),
1482
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
1483
+ raw
1484
+ };
1485
+ });
1486
+ }
1487
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
1488
+ async recoveryComplete(code, opts) {
1489
+ if (!code || !code.trim()) throw new Error("recoveryComplete requires the one-time `code`.");
1490
+ return this.withTokenRetry(async () => {
1491
+ const raw = await this.post(
1492
+ "/api/sdk/device/recover/complete",
1493
+ { code },
1494
+ opts?.signal
1495
+ );
1496
+ return {
1497
+ status: String(raw["status"] ?? ""),
1498
+ deactivatedCount: Number(raw["deactivated_count"] ?? 0),
1499
+ next: typeof raw["next"] === "string" ? raw["next"] : void 0,
1500
+ raw
1501
+ };
1502
+ });
1503
+ }
1504
+ // --- internals ---
1505
+ /** POST with the current player token. Token-expiry retry is handled one level
1506
+ * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
1507
+ async post(path, body, signal) {
1508
+ return this.http.post(path, body, this.auth, { signal });
1509
+ }
1510
+ async get(path, signal) {
1511
+ return this.http.get(path, this.auth, { signal });
1512
+ }
1513
+ /**
1514
+ * Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
1515
+ * and a `refreshToken` hook is configured. We re-run the entire begin→get→
1516
+ * complete ceremony (not just the failed call) so the retry always uses a fresh,
1517
+ * unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
1518
+ * The refresh is single-flighted so concurrent expiries trigger one re-mint.
1519
+ */
1520
+ async withTokenRetry(run) {
1521
+ try {
1522
+ return await run();
1523
+ } catch (err) {
1524
+ if (err instanceof InvoError && err.isTokenExpired && await this.tryRefresh()) {
1525
+ return await run();
1526
+ }
1527
+ throw err;
1528
+ }
1529
+ }
1530
+ async tryRefresh() {
1531
+ if (!this.refreshToken) return false;
1532
+ if (!this.refreshInFlight) {
1533
+ this.refreshInFlight = Promise.resolve(this.refreshToken()).finally(() => {
1534
+ this.refreshInFlight = void 0;
1535
+ });
1536
+ }
1537
+ const fresh = await this.refreshInFlight;
1538
+ if (!fresh) return false;
1539
+ this.auth = { kind: "bearer", token: fresh };
1540
+ return true;
1541
+ }
1542
+ async runAssertion(beginPath, beginBody, signal) {
1543
+ this.assertWebAuthn();
1544
+ const options = await this.post(beginPath, beginBody, signal);
1545
+ const cred = await navigator.credentials.get({
1546
+ publicKey: toRequestOptions(options),
1547
+ signal
1548
+ });
1549
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
1550
+ return assertionToJSON(cred);
1551
+ }
1552
+ async approve(flow, transactionId, opts) {
1553
+ const id = encodeURIComponent(transactionId);
1554
+ const signal = opts?.signal;
1555
+ return this.withTokenRetry(async () => {
1556
+ const assertion = await this.runAssertion(
1557
+ `/api/sdk/${flow}/${id}/approve/webauthn/begin`,
1558
+ void 0,
1559
+ signal
1560
+ );
1561
+ const raw = await this.post(
1562
+ `/api/sdk/${flow}/${id}/approve`,
1563
+ { webauthn_assertion: assertion },
1564
+ signal
1565
+ );
1566
+ return toApproveResult(raw, transactionId);
1567
+ });
1568
+ }
1569
+ async confirmReceipt(flow, transactionId, opts) {
1570
+ const id = encodeURIComponent(transactionId);
1571
+ const signal = opts?.signal;
1572
+ return this.withTokenRetry(async () => {
1573
+ const assertion = await this.runAssertion(
1574
+ `/api/sdk/${flow}/${id}/confirm-receipt/webauthn/begin`,
1575
+ void 0,
1576
+ signal
1577
+ );
1578
+ const raw = await this.post(
1579
+ `/api/sdk/${flow}/${id}/confirm-receipt`,
1580
+ { webauthn_assertion: assertion },
1581
+ signal
1582
+ );
1583
+ return toConfirmReceiptResult(raw);
1584
+ });
1585
+ }
1586
+ };
1587
+
1588
+ export { CheckoutClient, InvoClient, PlatformCommerceClient };
1589
+ //# sourceMappingURL=chunk-7O5JT3LK.js.map
1590
+ //# sourceMappingURL=chunk-7O5JT3LK.js.map