@invonetwork/web-sdk 3.3.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -248,6 +248,121 @@ var InvoError = class _InvoError extends Error {
248
248
  get isSteamPurchaseLayerRequired() {
249
249
  return this.code === "STEAM_PURCHASE_LAYER_REQUIRED";
250
250
  }
251
+ /**
252
+ * True if the title has no Steam application registered with INVO yet
253
+ * (`STEAM_NOT_CONFIGURED`, 503).
254
+ *
255
+ * Steam pays whoever owns the Steam app, so every INVO title bills through
256
+ * ITS OWN Steam application. The studio adds their Steam app id and publisher
257
+ * Web API key in the INVO dashboard; until then the rail is closed. Earlier
258
+ * SDK versions said purchases ran through an INVO-owned Steam app and there
259
+ * was nothing to register — that is no longer true.
260
+ *
261
+ * Not retryable; the fix is a setup step in the dashboard.
262
+ */
263
+ get isSteamNotConfigured() {
264
+ return this.code === "STEAM_NOT_CONFIGURED";
265
+ }
266
+ /**
267
+ * True if the order was started against a DIFFERENT Steam application than the
268
+ * title is configured for now (`STEAM_APP_CHANGED`, 409).
269
+ *
270
+ * Happens when a studio swaps their Steam app while orders are in flight. The
271
+ * in-flight order cannot be captured under the new app — contact INVO to
272
+ * settle it. New purchases work normally.
273
+ */
274
+ get isSteamAppChanged() {
275
+ return this.code === "STEAM_APP_CHANGED";
276
+ }
277
+ /**
278
+ * True if the studio has not finished INVO billing setup
279
+ * (`PARTNER_BILLING_NOT_SET_UP`, 409).
280
+ *
281
+ * On Steam, Valve pays the STUDIO and INVO issues the player's currency, so
282
+ * INVO settles with the studio afterwards against a payment method they keep
283
+ * on file. No payment method, no sale. Not retryable; it is a dashboard step.
284
+ */
285
+ get isPartnerBillingNotSetUp() {
286
+ return this.code === "PARTNER_BILLING_NOT_SET_UP";
287
+ }
288
+ /**
289
+ * True if the studio's settlement has been suspended (`PARTNER_RAIL_SUSPENDED`,
290
+ * 409) or they are temporarily over their settlement limit
291
+ * (`PARTNER_CREDIT_UNAVAILABLE`, 409).
292
+ *
293
+ * Refused BEFORE the player is charged, which is deliberate — the alternative
294
+ * is taking their money for currency that cannot be issued. Show a neutral
295
+ * "purchases are unavailable right now"; do not surface it as the player's
296
+ * problem, because it is not.
297
+ */
298
+ get isPartnerSettlementUnavailable() {
299
+ return this.code === "PARTNER_RAIL_SUSPENDED" || this.code === "PARTNER_CREDIT_UNAVAILABLE";
300
+ }
301
+ /** True when the studio's settlement float cannot cover this purchase right
302
+ * now (`PARTNER_CREDIT_UNAVAILABLE`, 409) — the structure (billing profile,
303
+ * mandate, payment method) is in place; the MONEY is not. Fixed by the
304
+ * studio topping up (or a settlement sweep clearing), not by the player.
305
+ * Show a plain failure ("try again later"); do NOT hot-poll init — headroom
306
+ * changes on a human action, and each retry briefly re-reserves headroom.
307
+ * A manual retry MUST reuse the same purchaseReference. */
308
+ get isPartnerCreditUnavailable() {
309
+ return this.code === "PARTNER_CREDIT_UNAVAILABLE";
310
+ }
311
+ /** True when the studio's settlement rail is suspended
312
+ * (`PARTNER_RAIL_SUSPENDED`, 409) — collections failed repeatedly or an
313
+ * admin intervened. Terminal from the game's seat: no retry can succeed
314
+ * until the studio resolves it in the INVO console. */
315
+ get isPartnerRailSuspended() {
316
+ return this.code === "PARTNER_RAIL_SUSPENDED";
317
+ }
318
+ /** True when init-purchase was given a `packId` that is not in INVO's Steam
319
+ * catalogue (`UNKNOWN_STEAM_PACK`, 400). The error body's
320
+ * `valid_pack_ids` lists what exists; re-fetch `steamPacks()` — the
321
+ * catalogue is INVO's and can change without a deploy on your side. */
322
+ get isUnknownSteamPack() {
323
+ return this.code === "UNKNOWN_STEAM_PACK";
324
+ }
325
+ /** True when a web-session init was sent without the player's IP
326
+ * (`MISSING_PLAYER_IP`, 400). Always an integration bug: `playerIp` is
327
+ * required for `usersession: "web"` and must be the PLAYER's address as
328
+ * your server sees it — never your server's own. */
329
+ get isMissingPlayerIp() {
330
+ return this.code === "MISSING_PLAYER_IP";
331
+ }
332
+ /** True when finalize was called before the player approved the charge
333
+ * (409, `status: "not_authorized"` with Steam still reporting `Init`, or
334
+ * no status yet). THE NORMAL WAIT STATE — keep polling / wait for the
335
+ * client callback and call finalize again. Contrast
336
+ * {@link isSteamAuthorizationDead}.
337
+ *
338
+ * PENDING IS THE CLOSED SET, deliberately. The first version of this pair
339
+ * enumerated the DEAD statuses and made pending the complement — so a
340
+ * player pressing Cancel in the overlay (the most common non-approval
341
+ * outcome, which Steam reports as a status the list did not name)
342
+ * classified as "keep polling forever": the exact failure these getters
343
+ * exist to prevent, reintroduced by enumerating the author's hazards
344
+ * instead of the backend's vocabulary. Only `Init` (and an absent status)
345
+ * can mean "not yet"; every named status that is not Init is an outcome. */
346
+ get isSteamAuthorizationPending() {
347
+ const b = this.body;
348
+ if (!b || b["status"] !== "not_authorized") return false;
349
+ const st = String(b["steam_status"] ?? "").toLowerCase();
350
+ return st === "init" || st === "";
351
+ }
352
+ /** True when finalize reports the Steam transaction TERMINALLY not-approved:
353
+ * `not_authorized` with any settled status — Failed, Cancelled, Refunded,
354
+ * Chargedback, and every other non-Init outcome. STOP polling: no later
355
+ * call can succeed. (Dead is the open set on purpose: an unrecognised new
356
+ * status stops a poller rather than trapping it, and stopping wrongly costs
357
+ * one support question while polling wrongly runs forever.) A finalize
358
+ * answering `"Order is not finalizable"` with no `not_authorized` status is
359
+ * equally terminal — the reconciler has already settled the order's fate. */
360
+ get isSteamAuthorizationDead() {
361
+ const b = this.body;
362
+ if (!b || b["status"] !== "not_authorized") return false;
363
+ const st = String(b["steam_status"] ?? "").toLowerCase();
364
+ return st !== "init" && st !== "";
365
+ }
251
366
  /** True if a Platform Commerce CARD purchase was below the processor's floor of $0.50
252
367
  * (backend code `BELOW_STRIPE_MINIMUM`, 400). Neutral name; matches the wire code. */
253
368
  get isBelowCardMinimum() {
@@ -636,6 +751,599 @@ function toDestinationsResult(raw, direction) {
636
751
  };
637
752
  }
638
753
 
754
+ // src/shared/hosted-approval.ts
755
+ var HOSTED_FLOWS = [
756
+ "transfer",
757
+ "send",
758
+ "send_receipt",
759
+ "transfer_receipt"
760
+ ];
761
+ var HOSTED_MESSAGE_TYPE = "invo.approval";
762
+ var MAX_EXPIRES_IN_S = 24 * 24 * 60 * 60;
763
+ var CONFIRM_QUIET_CODES = /* @__PURE__ */ new Set([
764
+ "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED",
765
+ "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING"
766
+ ]);
767
+ var MAX_TRANSIENT_POLL_FAILURES = 5;
768
+ function derivePlatformOrigin(verificationUriComplete, explicit) {
769
+ let u;
770
+ try {
771
+ u = new URL(verificationUriComplete);
772
+ } catch {
773
+ throw new InvoError({
774
+ message: "begin returned no absolute verification_uri_complete.",
775
+ code: "UNEXPECTED_RESPONSE",
776
+ status: 0
777
+ });
778
+ }
779
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
780
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
781
+ throw new InvoError({
782
+ message: "The hosted approval page must be https (plaintext would let any page forge the wake-up).",
783
+ code: "INVALID_INPUT",
784
+ status: 0
785
+ });
786
+ }
787
+ if (explicit !== void 0 && u.origin !== explicit) {
788
+ throw new InvoError({
789
+ message: `platformOrigin (${explicit}) does not match the hosted page's origin (${u.origin}).`,
790
+ code: "INVALID_INPUT",
791
+ status: 0
792
+ });
793
+ }
794
+ return u.origin;
795
+ }
796
+ function normalizeEnrollment(input) {
797
+ if (!input || typeof input !== "object") return null;
798
+ const state = typeof input.state === "string" ? input.state : "";
799
+ if (!state) return null;
800
+ const label = input.device_label ?? input.deviceLabel;
801
+ const code = input.match_code ?? input.matchCode;
802
+ const at = input.requested_at ?? input.requestedAt;
803
+ return {
804
+ state,
805
+ deviceLabel: typeof label === "string" && label ? label : "your phone",
806
+ matchCode: typeof code === "string" ? code : "",
807
+ requestedAt: typeof at === "string" ? at : void 0,
808
+ raw: input
809
+ };
810
+ }
811
+ var BRAND = "#4f46e5";
812
+ var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
813
+ var MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
814
+ var PROMPT_IDS = {
815
+ root: "invo-hosted-enrollment",
816
+ title: "invo-hosted-enrollment-title",
817
+ code: "invo-hosted-enrollment-code",
818
+ yes: "invo-hosted-enrollment-yes",
819
+ no: "invo-hosted-enrollment-no",
820
+ stop: "invo-hosted-enrollment-stop",
821
+ error: "invo-hosted-enrollment-error"
822
+ };
823
+ var HostedEnrollmentPrompt = class {
824
+ constructor() {
825
+ this.handlers = { respond: async () => {
826
+ }, renderPrompt: true };
827
+ this.enrollment = null;
828
+ /** The last match code the player answered, so a stale poll can't re-ask it. */
829
+ this.decided = null;
830
+ this.root = null;
831
+ this.previousFocus = null;
832
+ this.keyHandler = null;
833
+ this.busy = false;
834
+ }
835
+ get current() {
836
+ return this.enrollment;
837
+ }
838
+ configure(handlers) {
839
+ this.handlers = handlers;
840
+ this.decided = null;
841
+ if (this.enrollment) this.render();
842
+ }
843
+ update(input) {
844
+ let next = normalizeEnrollment(input);
845
+ if (next && next.state === "awaiting_screen" && this.decided && this.decided.code === next.matchCode) {
846
+ next = this.decided.decision === "approve" ? { ...next, state: "confirmed" } : null;
847
+ }
848
+ 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);
849
+ this.enrollment = next;
850
+ if (changed) this.handlers.onEnrollment?.(next, this.handlers.respond);
851
+ this.render();
852
+ }
853
+ clear() {
854
+ this.update(null);
855
+ }
856
+ // --- rendering ---
857
+ render() {
858
+ if (typeof document === "undefined") return;
859
+ const e = this.enrollment;
860
+ const visible = this.handlers.renderPrompt && e && (e.state === "awaiting_screen" || e.state === "confirmed");
861
+ if (!visible || !e) {
862
+ this.unmount();
863
+ return;
864
+ }
865
+ this.mount();
866
+ const root = this.root;
867
+ root.innerHTML = "";
868
+ root.appendChild(e.state === "awaiting_screen" ? this.buildPrompt(e) : this.buildFinishing(e));
869
+ this.focusInitial(e.state);
870
+ }
871
+ mount() {
872
+ if (this.root) return;
873
+ this.previousFocus = document.activeElement;
874
+ const overlay = document.createElement("div");
875
+ overlay.id = PROMPT_IDS.root;
876
+ overlay.setAttribute("role", "dialog");
877
+ overlay.setAttribute("aria-modal", "true");
878
+ overlay.setAttribute("aria-labelledby", PROMPT_IDS.title);
879
+ overlay.tabIndex = -1;
880
+ overlay.style.cssText = [
881
+ "position:fixed",
882
+ "inset:0",
883
+ "z-index:2147483000",
884
+ "display:flex",
885
+ "align-items:center",
886
+ "justify-content:center",
887
+ "padding:16px",
888
+ "background:rgba(17,24,39,.55)",
889
+ `font-family:${FONT}`,
890
+ "color:#111827",
891
+ "-webkit-font-smoothing:antialiased",
892
+ "outline:none"
893
+ ].join(";");
894
+ this.keyHandler = (ev) => this.onKeyDown(ev);
895
+ overlay.addEventListener("keydown", this.keyHandler);
896
+ document.body.appendChild(overlay);
897
+ this.root = overlay;
898
+ }
899
+ unmount() {
900
+ if (!this.root) return;
901
+ if (this.keyHandler) this.root.removeEventListener("keydown", this.keyHandler);
902
+ this.root.remove();
903
+ this.root = null;
904
+ this.keyHandler = null;
905
+ this.busy = false;
906
+ const prev = this.previousFocus;
907
+ this.previousFocus = null;
908
+ if (prev && typeof prev.focus === "function") {
909
+ try {
910
+ prev.focus();
911
+ } catch {
912
+ }
913
+ }
914
+ }
915
+ card() {
916
+ const card = document.createElement("div");
917
+ card.style.cssText = [
918
+ "background:#ffffff",
919
+ "border-radius:16px",
920
+ "box-shadow:0 20px 60px rgba(17,24,39,.25)",
921
+ "max-width:420px",
922
+ "width:100%",
923
+ "padding:28px 28px 24px",
924
+ "box-sizing:border-box",
925
+ "text-align:center"
926
+ ].join(";");
927
+ const mark = document.createElement("div");
928
+ mark.textContent = "INVO";
929
+ mark.setAttribute("aria-hidden", "true");
930
+ mark.style.cssText = `font-weight:800;letter-spacing:.18em;font-size:13px;color:${BRAND};margin-bottom:14px`;
931
+ card.appendChild(mark);
932
+ return card;
933
+ }
934
+ button(id, label, primary) {
935
+ const b = document.createElement("button");
936
+ b.type = "button";
937
+ b.id = id;
938
+ b.textContent = label;
939
+ b.style.cssText = [
940
+ "display:block",
941
+ "width:100%",
942
+ "box-sizing:border-box",
943
+ "border-radius:10px",
944
+ "padding:12px 16px",
945
+ "font:inherit",
946
+ "font-size:15px",
947
+ "font-weight:600",
948
+ "cursor:pointer",
949
+ "margin-top:10px",
950
+ primary ? `background:${BRAND};color:#ffffff;border:1px solid ${BRAND}` : "background:#ffffff;color:#374151;border:1px solid #d1d5db"
951
+ ].join(";");
952
+ return b;
953
+ }
954
+ buildPrompt(e) {
955
+ const card = this.card();
956
+ const title = document.createElement("h2");
957
+ title.id = PROMPT_IDS.title;
958
+ title.textContent = `Set up INVO on ${e.deviceLabel}?`;
959
+ title.style.cssText = "margin:0 0 14px;font-size:20px;font-weight:700;line-height:1.3";
960
+ card.appendChild(title);
961
+ const codeLabel = document.createElement("div");
962
+ codeLabel.textContent = "Code";
963
+ codeLabel.style.cssText = "font-size:12px;text-transform:uppercase;letter-spacing:.12em;color:#6b7280";
964
+ card.appendChild(codeLabel);
965
+ const code = document.createElement("div");
966
+ code.id = PROMPT_IDS.code;
967
+ code.textContent = e.matchCode;
968
+ code.setAttribute("aria-label", `Code ${e.matchCode.split("").join(" ")}`);
969
+ code.style.cssText = [
970
+ `font-family:${MONO}`,
971
+ "font-size:40px",
972
+ "font-weight:700",
973
+ "letter-spacing:.3em",
974
+ "text-indent:.3em",
975
+ "line-height:1.2",
976
+ "margin:6px 0 16px",
977
+ "color:#111827",
978
+ "background:#f3f4f6",
979
+ "border-radius:12px",
980
+ "padding:14px 8px"
981
+ ].join(";");
982
+ card.appendChild(code);
983
+ const body = document.createElement("p");
984
+ body.textContent = "Say Yes only if the phone you just scanned/opened shows this code.";
985
+ body.style.cssText = "margin:0 0 6px;font-size:15px;line-height:1.5;color:#374151";
986
+ card.appendChild(body);
987
+ const err = document.createElement("div");
988
+ err.id = PROMPT_IDS.error;
989
+ err.setAttribute("role", "alert");
990
+ err.style.cssText = "min-height:18px;font-size:13px;color:#b91c1c;margin-top:4px";
991
+ card.appendChild(err);
992
+ const yes = this.button(PROMPT_IDS.yes, "Yes, it shows this code", true);
993
+ yes.addEventListener("click", () => void this.decide("approve"));
994
+ card.appendChild(yes);
995
+ const no = this.button(PROMPT_IDS.no, "No, that is not my phone", false);
996
+ no.addEventListener("click", () => void this.decide("deny"));
997
+ card.appendChild(no);
998
+ return card;
999
+ }
1000
+ buildFinishing(e) {
1001
+ const card = this.card();
1002
+ card.style.padding = "18px 22px";
1003
+ const row = document.createElement("div");
1004
+ row.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap";
1005
+ const text = document.createElement("div");
1006
+ text.id = PROMPT_IDS.title;
1007
+ text.textContent = `Finishing on ${e.deviceLabel}\u2026`;
1008
+ text.tabIndex = -1;
1009
+ text.setAttribute("aria-live", "polite");
1010
+ text.style.cssText = "font-size:15px;color:#374151;outline:none";
1011
+ row.appendChild(text);
1012
+ const stop = document.createElement("button");
1013
+ stop.type = "button";
1014
+ stop.id = PROMPT_IDS.stop;
1015
+ stop.textContent = "Stop it, wrong code";
1016
+ 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`;
1017
+ stop.addEventListener("click", () => void this.decide("deny"));
1018
+ row.appendChild(stop);
1019
+ card.appendChild(row);
1020
+ return card;
1021
+ }
1022
+ async decide(decision) {
1023
+ if (this.busy || !this.enrollment) return;
1024
+ this.busy = true;
1025
+ this.root?.focus();
1026
+ this.setButtonsDisabled(true);
1027
+ try {
1028
+ await this.handlers.respond(decision);
1029
+ const now = this.enrollment;
1030
+ if (!now) return;
1031
+ this.decided = { code: now.matchCode, decision };
1032
+ if (decision === "deny") {
1033
+ this.update(null);
1034
+ } else if (now.state === "awaiting_screen") {
1035
+ this.update({ ...now.raw, state: "confirmed" });
1036
+ }
1037
+ } catch (err) {
1038
+ const box = this.root?.querySelector(`#${PROMPT_IDS.error}`);
1039
+ if (box) {
1040
+ box.textContent = err instanceof Error && err.message ? `Couldn't send your answer: ${err.message}` : "Couldn't send your answer. Try again.";
1041
+ }
1042
+ } finally {
1043
+ this.busy = false;
1044
+ this.setButtonsDisabled(false);
1045
+ if (this.root && this.enrollment?.state === "awaiting_screen") this.focusInitial("awaiting_screen");
1046
+ }
1047
+ }
1048
+ setButtonsDisabled(disabled) {
1049
+ this.root?.querySelectorAll("button").forEach((b) => {
1050
+ b.disabled = disabled;
1051
+ });
1052
+ }
1053
+ focusables() {
1054
+ if (!this.root) return [];
1055
+ return Array.from(this.root.querySelectorAll("button:not([disabled])"));
1056
+ }
1057
+ /** Prompt: first button. Finishing row: the text, NOT "Stop it" — a stray Enter must not deny. */
1058
+ focusInitial(state) {
1059
+ const target = state === "confirmed" ? this.root?.querySelector(`#${PROMPT_IDS.title}`) : this.focusables()[0];
1060
+ try {
1061
+ (target ?? this.root)?.focus();
1062
+ } catch {
1063
+ }
1064
+ }
1065
+ onKeyDown(ev) {
1066
+ if (ev.key === "Escape") {
1067
+ ev.preventDefault();
1068
+ void this.decide("deny");
1069
+ return;
1070
+ }
1071
+ if (ev.key !== "Tab") return;
1072
+ ev.preventDefault();
1073
+ const items = this.focusables();
1074
+ if (items.length === 0) {
1075
+ this.root?.focus();
1076
+ return;
1077
+ }
1078
+ const active = document.activeElement;
1079
+ const idx = items.indexOf(active);
1080
+ let nextIdx;
1081
+ if (idx === -1) nextIdx = ev.shiftKey ? items.length - 1 : 0;
1082
+ else nextIdx = (idx + (ev.shiftKey ? -1 : 1) + items.length) % items.length;
1083
+ items[nextIdx].focus();
1084
+ }
1085
+ };
1086
+ 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.";
1087
+ var BLOCKED_HINT = "The browser blocked the popup. Nothing was started \u2014 call approveHosted() from a click handler.";
1088
+ function pollToken(err) {
1089
+ if (!(err instanceof InvoError) || err.status === 0 || err.status === 429 || err.status >= 500) return null;
1090
+ const body = err.body && typeof err.body === "object" ? err.body : {};
1091
+ const token = typeof body["error"] === "string" ? body["error"] : "";
1092
+ return { token, body };
1093
+ }
1094
+ async function runHostedApproval(opts, api, deps = {}) {
1095
+ if (typeof window === "undefined") {
1096
+ throw new InvoError({
1097
+ message: "approveHosted requires a browser window.",
1098
+ code: "DOM_UNAVAILABLE",
1099
+ status: 0
1100
+ });
1101
+ }
1102
+ if (!opts.transactionId || !String(opts.transactionId).trim()) {
1103
+ throw new Error("approveHosted requires a `transactionId`.");
1104
+ }
1105
+ if (!HOSTED_FLOWS.includes(opts.flow)) {
1106
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}" (expected ${HOSTED_FLOWS.join(" | ")}).`);
1107
+ }
1108
+ if (opts.renderPrompt !== false && typeof document === "undefined") {
1109
+ throw new InvoError({
1110
+ message: "approveHosted needs a DOM to render the match-code prompt (or pass renderPrompt:false).",
1111
+ code: "DOM_UNAVAILABLE",
1112
+ status: 0
1113
+ });
1114
+ }
1115
+ const signal = opts.signal;
1116
+ if (signal?.aborted) return { status: "closed", popupBlocked: false };
1117
+ const open = deps.open ?? ((u, n, f) => window.open(u, n, f));
1118
+ const navigate = deps.navigate ?? ((u) => window.location.assign(u));
1119
+ const closedPollMs = deps.closedPollMs ?? 500;
1120
+ const coopGraceMs = deps.coopGraceMs ?? 1500;
1121
+ const createPrompt = deps.createPrompt ?? (() => new HostedEnrollmentPrompt());
1122
+ const width = opts.popup?.width ?? 480;
1123
+ const height = opts.popup?.height ?? 720;
1124
+ const sw = window.screen?.width ?? width;
1125
+ const sh = window.screen?.height ?? height;
1126
+ const left = Math.max(0, Math.round((sw - width) / 2));
1127
+ const top = Math.max(0, Math.round((sh - height) / 2));
1128
+ const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
1129
+ const name = `invo-approval-${encodeURIComponent(String(opts.transactionId)).replace(/[^A-Za-z0-9-]/g, "")}`;
1130
+ let popup;
1131
+ try {
1132
+ popup = open("about:blank", name, features);
1133
+ } catch {
1134
+ popup = null;
1135
+ }
1136
+ const mode = opts.popupBlocked ?? "resolve";
1137
+ if (!popup && mode === "resolve") {
1138
+ return { status: "blocked", popupBlocked: true, message: BLOCKED_HINT };
1139
+ }
1140
+ let begin;
1141
+ try {
1142
+ begin = await api.begin();
1143
+ } catch (err) {
1144
+ try {
1145
+ popup?.close();
1146
+ } catch {
1147
+ }
1148
+ if (signal?.aborted || err instanceof InvoError && err.code === "ABORTED") {
1149
+ return { status: "closed", popupBlocked: false };
1150
+ }
1151
+ throw err;
1152
+ }
1153
+ const deviceCode = typeof begin["device_code"] === "string" ? begin["device_code"] : "";
1154
+ const url = typeof begin["verification_uri_complete"] === "string" ? begin["verification_uri_complete"] : "";
1155
+ if (!deviceCode || !url) {
1156
+ try {
1157
+ popup?.close();
1158
+ } catch {
1159
+ }
1160
+ const { device_code: _dc, ...safeBody } = begin;
1161
+ throw new InvoError({
1162
+ message: "begin returned no device_code / verification_uri_complete.",
1163
+ code: "UNEXPECTED_RESPONSE",
1164
+ status: 0,
1165
+ body: safeBody
1166
+ });
1167
+ }
1168
+ let origin;
1169
+ try {
1170
+ origin = derivePlatformOrigin(url, opts.platformOrigin);
1171
+ } catch (err) {
1172
+ try {
1173
+ popup?.close();
1174
+ } catch {
1175
+ }
1176
+ throw err;
1177
+ }
1178
+ const expiresIn = Math.min(
1179
+ MAX_EXPIRES_IN_S,
1180
+ Math.max(1, Number(begin["expires_in"]) || 600)
1181
+ );
1182
+ let interval = Math.max(1, Number(begin["interval"]) || 5);
1183
+ if (!popup) {
1184
+ try {
1185
+ navigate(url);
1186
+ return { status: "redirected", popupBlocked: true };
1187
+ } catch (err) {
1188
+ return {
1189
+ status: "blocked",
1190
+ popupBlocked: true,
1191
+ message: `The browser blocked the popup and the redirect fallback failed${err instanceof Error && err.message ? `: ${err.message}` : "."}`
1192
+ };
1193
+ }
1194
+ }
1195
+ const win = popup;
1196
+ try {
1197
+ const loc = win.location;
1198
+ if (loc && typeof loc.replace === "function") loc.replace(url);
1199
+ else if (loc) loc.href = url;
1200
+ } catch {
1201
+ }
1202
+ const navigatedAt = Date.now();
1203
+ try {
1204
+ win.focus?.();
1205
+ } catch {
1206
+ }
1207
+ return new Promise((resolve, reject) => {
1208
+ let settled = false;
1209
+ let prompt;
1210
+ let wake = null;
1211
+ let expiryTimer;
1212
+ let closedTimer;
1213
+ const cleanup = (closePopup) => {
1214
+ settled = true;
1215
+ window.removeEventListener("message", onMessage);
1216
+ signal?.removeEventListener("abort", onAbort);
1217
+ if (expiryTimer !== void 0) clearTimeout(expiryTimer);
1218
+ if (closedTimer !== void 0) clearInterval(closedTimer);
1219
+ prompt?.clear();
1220
+ if (closePopup && !win.closed) {
1221
+ try {
1222
+ win.close();
1223
+ } catch {
1224
+ }
1225
+ }
1226
+ wake?.();
1227
+ };
1228
+ const finish = (result, closePopup) => {
1229
+ if (settled) return;
1230
+ cleanup(closePopup);
1231
+ resolve(result);
1232
+ };
1233
+ const fail = (err) => {
1234
+ if (settled) return;
1235
+ cleanup(false);
1236
+ reject(err);
1237
+ };
1238
+ const respond = async (decision) => {
1239
+ if (settled) return;
1240
+ try {
1241
+ await api.confirmEnrollment(deviceCode, decision);
1242
+ } catch (err) {
1243
+ if (err instanceof InvoError && err.rawCode && CONFIRM_QUIET_CODES.has(err.rawCode)) {
1244
+ prompt?.update(null);
1245
+ return;
1246
+ }
1247
+ throw err;
1248
+ }
1249
+ wake?.();
1250
+ };
1251
+ const ensurePrompt = () => {
1252
+ if (!prompt) {
1253
+ prompt = createPrompt();
1254
+ prompt.configure({
1255
+ respond,
1256
+ onEnrollment: opts.onEnrollment,
1257
+ renderPrompt: opts.renderPrompt !== false
1258
+ });
1259
+ }
1260
+ return prompt;
1261
+ };
1262
+ const showEnrollment = (input) => {
1263
+ const e = input && typeof input === "object" ? input : null;
1264
+ if (e) ensurePrompt().update(e);
1265
+ else prompt?.update(null);
1266
+ };
1267
+ const onMessage = (event) => {
1268
+ if (event.origin !== origin) return;
1269
+ if (event.source && event.source !== win) return;
1270
+ const data = event.data;
1271
+ if (!data || typeof data !== "object" || data.type !== HOSTED_MESSAGE_TYPE) return;
1272
+ wake?.();
1273
+ };
1274
+ const onAbort = () => finish({ status: "closed", popupBlocked: false }, true);
1275
+ const pause = (ms) => new Promise((r) => {
1276
+ const t = setTimeout(() => {
1277
+ wake = null;
1278
+ r();
1279
+ }, ms);
1280
+ wake = () => {
1281
+ clearTimeout(t);
1282
+ wake = null;
1283
+ r();
1284
+ };
1285
+ });
1286
+ window.addEventListener("message", onMessage);
1287
+ signal?.addEventListener("abort", onAbort, { once: true });
1288
+ expiryTimer = setTimeout(() => finish({ status: "expired", popupBlocked: false }, false), expiresIn * 1e3);
1289
+ closedTimer = setInterval(() => {
1290
+ if (!win.closed) return;
1291
+ if (Date.now() - navigatedAt < coopGraceMs) {
1292
+ finish({ status: "blocked", popupBlocked: true, message: COOP_HINT }, false);
1293
+ } else {
1294
+ finish({ status: "closed", popupBlocked: false }, false);
1295
+ }
1296
+ }, closedPollMs);
1297
+ void (async () => {
1298
+ let transientFailures = 0;
1299
+ while (!settled) {
1300
+ await pause(interval * 1e3);
1301
+ if (settled) return;
1302
+ let raw;
1303
+ try {
1304
+ raw = await api.poll(deviceCode);
1305
+ } catch (err) {
1306
+ if (settled) return;
1307
+ const p = pollToken(err);
1308
+ if (!p) {
1309
+ if (++transientFailures >= MAX_TRANSIENT_POLL_FAILURES) return fail(err);
1310
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
1311
+ if (typeof ra === "number" && ra > interval) interval = Math.min(ra, MAX_EXPIRES_IN_S);
1312
+ continue;
1313
+ }
1314
+ transientFailures = 0;
1315
+ const bodyInterval = Number(p.body["interval"]);
1316
+ switch (p.token) {
1317
+ case "authorization_pending":
1318
+ if (bodyInterval > 0) interval = bodyInterval;
1319
+ showEnrollment(p.body["enrollment"]);
1320
+ continue;
1321
+ case "slow_down":
1322
+ interval = Math.max(interval + 5, bodyInterval > 0 ? bodyInterval : 0);
1323
+ continue;
1324
+ case "expired_token":
1325
+ return finish({ status: "expired", popupBlocked: false }, false);
1326
+ case "access_denied":
1327
+ return finish({ status: "denied", popupBlocked: false }, false);
1328
+ default:
1329
+ return fail(err);
1330
+ }
1331
+ }
1332
+ if (settled) return;
1333
+ if (raw["status"] !== "approved") continue;
1334
+ try {
1335
+ const approval = await api.approve(deviceCode);
1336
+ if (settled) return;
1337
+ finish({ status: "approved", popupBlocked: false, approval }, true);
1338
+ } catch (err) {
1339
+ fail(err);
1340
+ }
1341
+ return;
1342
+ }
1343
+ })();
1344
+ });
1345
+ }
1346
+
639
1347
  // src/index.ts
640
1348
  function toPendingCollectItem(row) {
641
1349
  return {
@@ -664,6 +1372,29 @@ function toBalanceRow(row) {
664
1372
  raw: row
665
1373
  };
666
1374
  }
1375
+ function toApproveResult(raw, transactionId) {
1376
+ const holdReason = raw["error_code"] ?? raw["code"];
1377
+ return {
1378
+ status: String(raw["status"] ?? ""),
1379
+ next: String(raw["next"] ?? ""),
1380
+ transactionId: String(raw["transaction_id"] ?? transactionId),
1381
+ claimCode: raw["claim_code"],
1382
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
1383
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
1384
+ risk: raw["risk"],
1385
+ guardianApproval: raw["guardian_approval"] ?? void 0,
1386
+ pollEndpoint: raw["poll_endpoint"],
1387
+ raw
1388
+ };
1389
+ }
1390
+ function toConfirmReceiptResult(raw) {
1391
+ const holdReason = raw["error_code"] ?? raw["code"];
1392
+ return {
1393
+ status: String(raw["status"] ?? ""),
1394
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
1395
+ raw
1396
+ };
1397
+ }
667
1398
  var PlatformCommerceClient = class {
668
1399
  /**
669
1400
  * Embed INVO's hosted checkout in an iframe and listen for completion.
@@ -802,6 +1533,60 @@ var InvoClient = class {
802
1533
  return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
803
1534
  });
804
1535
  }
1536
+ async approveHosted(opts) {
1537
+ const txn = String(opts.transactionId ?? "");
1538
+ const id = encodeURIComponent(txn);
1539
+ const signal = opts.signal;
1540
+ const api = {
1541
+ begin: () => this.withTokenRetry(
1542
+ () => this.post(
1543
+ "/api/sdk/approvals/device/begin",
1544
+ { transaction_id: txn, flow: opts.flow, channel: "popup" },
1545
+ signal
1546
+ )
1547
+ ),
1548
+ poll: (deviceCode) => this.withTokenRetry(
1549
+ () => this.post(
1550
+ "/api/sdk/approvals/device/poll",
1551
+ { device_code: deviceCode },
1552
+ signal
1553
+ )
1554
+ ),
1555
+ confirmEnrollment: (deviceCode, decision) => this.withTokenRetry(
1556
+ () => this.post(
1557
+ "/api/sdk/approvals/device/confirm-enrollment",
1558
+ { device_code: deviceCode, decision },
1559
+ signal
1560
+ )
1561
+ ),
1562
+ approve: (deviceCode) => this.withTokenRetry(async () => {
1563
+ const body = { device_code: deviceCode };
1564
+ switch (opts.flow) {
1565
+ case "transfer":
1566
+ return toApproveResult(
1567
+ await this.post(`/api/sdk/transfers/${id}/approve`, body, signal),
1568
+ txn
1569
+ );
1570
+ case "send":
1571
+ return toApproveResult(
1572
+ await this.post(`/api/sdk/send/${id}/approve`, body, signal),
1573
+ txn
1574
+ );
1575
+ case "send_receipt":
1576
+ return toConfirmReceiptResult(
1577
+ await this.post(`/api/sdk/send/${id}/confirm-receipt`, body, signal)
1578
+ );
1579
+ case "transfer_receipt":
1580
+ return toConfirmReceiptResult(
1581
+ await this.post(`/api/sdk/transfers/${id}/confirm-receipt`, body, signal)
1582
+ );
1583
+ default:
1584
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}".`);
1585
+ }
1586
+ })
1587
+ };
1588
+ return runHostedApproval(opts, api);
1589
+ }
805
1590
  /** Approve a SEND with the player's passkey. */
806
1591
  async approveSend(transactionId, opts) {
807
1592
  return this.approve("send", transactionId, opts);
@@ -1069,19 +1854,7 @@ var InvoClient = class {
1069
1854
  { webauthn_assertion: assertion },
1070
1855
  signal
1071
1856
  );
1072
- const holdReason = raw["error_code"] ?? raw["code"];
1073
- return {
1074
- status: String(raw["status"] ?? ""),
1075
- next: String(raw["next"] ?? ""),
1076
- transactionId: String(raw["transaction_id"] ?? transactionId),
1077
- claimCode: raw["claim_code"],
1078
- claimCodeExpiresAt: raw["claim_code_expires_at"],
1079
- holdReason: typeof holdReason === "string" ? holdReason : void 0,
1080
- risk: raw["risk"],
1081
- guardianApproval: raw["guardian_approval"] ?? void 0,
1082
- pollEndpoint: raw["poll_endpoint"],
1083
- raw
1084
- };
1857
+ return toApproveResult(raw, transactionId);
1085
1858
  });
1086
1859
  }
1087
1860
  async confirmReceipt(flow, transactionId, opts) {
@@ -1098,12 +1871,7 @@ var InvoClient = class {
1098
1871
  { webauthn_assertion: assertion },
1099
1872
  signal
1100
1873
  );
1101
- const holdReason = raw["error_code"] ?? raw["code"];
1102
- return {
1103
- status: String(raw["status"] ?? ""),
1104
- holdReason: typeof holdReason === "string" ? holdReason : void 0,
1105
- raw
1106
- };
1874
+ return toConfirmReceiptResult(raw);
1107
1875
  });
1108
1876
  }
1109
1877
  };