@invonetwork/web-sdk 2.5.0 → 3.0.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.d.cts CHANGED
@@ -1,38 +1,26 @@
1
- import { M as MountCardPaymentOptions, C as CardPaymentSession, a as ConfirmCardPaymentOptions, b as CardPaymentResult, c as ClientConfig, d as CallOptions, A as ApproveResult, e as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, f as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, g as EnrollmentVerifyResult, R as RecoveryBeginResult, h as RecoveryCompleteResult } from './types-g1xz5GDk.cjs';
2
- export { i as BalanceRow, j as CardPaymentStatus, k as DestinationGame, I as InvoCardConfirmResponse, l as InvoCardElement, m as InvoCardElements, n as InvoCardProcessor, o as InvoError, p as InvoErrorInfo, q as InvoHooks, r as InvoRequestInfo, s as InvoResponseInfo, t as PendingCollectItem, u as Rail, V as VerificationMethod } from './types-g1xz5GDk.cjs';
1
+ import { M as MountCheckoutOptions, C as CheckoutMountHandle, a as ClientConfig, b as CallOptions, A as ApproveResult, c as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, d as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, e as EnrollmentVerifyResult, R as RecoveryBeginResult, f as RecoveryCompleteResult } from './types-DMNXAGiw.cjs';
2
+ export { g as BalanceRow, h as DestinationGame, I as InvoError, i as InvoErrorInfo, j as InvoHooks, k as InvoRequestInfo, l as InvoResponseInfo, m as PendingCollectItem, n as Rail, V as VerificationMethod } from './types-DMNXAGiw.cjs';
3
3
 
4
- /**
5
- * Platform Commerce card confirmation (browser side). The server (`InvoServer.
6
- * platformCommerce.purchase` with `fundingSource:"card"`) returns a `clientSecret`; this
7
- * mounts the processor's Payment Element (card / Apple Pay / Google Pay) and confirms it.
8
- * The sale is real only on the `platform_commerce.purchased` webhook — treat a "succeeded"
9
- * here as "show processing", never as fulfilled.
10
- */
11
4
  declare class PlatformCommerceClient {
12
- private readonly defaultPublishableKey;
13
- constructor(defaultPublishableKey: () => string | undefined);
14
5
  /**
15
- * Mount the Payment Element and get a session you confirm from your OWN Pay button.
16
- * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
6
+ * Embed INVO's hosted checkout in an iframe and listen for completion.
17
7
  *
18
8
  * ```ts
19
- * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
20
- * mount: "#pay", publishableKey: "pk_live_…",
9
+ * const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
10
+ * onComplete: () => showProcessing(), // then reconcile server-side
21
11
  * });
22
- * // on your Pay button click:
23
- * const r = await session.confirm({ returnUrl: location.href });
24
- * if (r.status === "succeeded") showProcessing();
25
- * session.destroy();
12
+ * // later: handle.destroy();
26
13
  * ```
14
+ *
15
+ * Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
16
+ * the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
17
+ *
18
+ * `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
19
+ * from the checkout URL's own origin (any other window could forge the event). It is a
20
+ * UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
21
+ * on this client event.
27
22
  */
28
- mountCardPayment(clientSecret: string, opts: MountCardPaymentOptions): Promise<CardPaymentSession>;
29
- /**
30
- * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
31
- * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
32
- * button, selector or element) or a minimal button the SDK renders inside `mount`. For
33
- * full control over the button, prefer {@link mountCardPayment}.
34
- */
35
- confirmCardPayment(clientSecret: string, opts: ConfirmCardPaymentOptions): Promise<CardPaymentResult>;
23
+ mountCheckout(el: string | HTMLElement, checkoutUrl: string, opts?: MountCheckoutOptions): CheckoutMountHandle;
36
24
  }
37
25
  declare class InvoClient {
38
26
  private readonly http;
@@ -40,11 +28,11 @@ declare class InvoClient {
40
28
  private readonly refreshToken;
41
29
  /** In-flight refresh, shared so concurrent expiries trigger a single re-mint. */
42
30
  private refreshInFlight;
43
- private readonly commercePublishableKey;
44
31
  /**
45
- * Platform Commerce (ecommerce) card confirmation. Use after
32
+ * Platform Commerce (ecommerce) hosted-checkout embed. Use after
46
33
  * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
47
- * `clientSecret`. The passkey/token flows never touch this. See
34
+ * `checkoutUrl` — either redirect the buyer there, or embed it with
35
+ * `mountCheckout`. No card element, no processor dependency. See
48
36
  * {@link PlatformCommerceClient}.
49
37
  */
50
38
  readonly platformCommerce: PlatformCommerceClient;
@@ -170,4 +158,4 @@ declare class InvoClient {
170
158
  private confirmReceipt;
171
159
  }
172
160
 
173
- export { ApproveResult, BalanceResult, CallOptions, CardPaymentResult, CardPaymentSession, ClientConfig, ConfirmCardPaymentOptions, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, MountCardPaymentOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
161
+ export { ApproveResult, BalanceResult, CallOptions, CheckoutMountHandle, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, MountCheckoutOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
package/dist/index.d.ts CHANGED
@@ -1,38 +1,26 @@
1
- import { M as MountCardPaymentOptions, C as CardPaymentSession, a as ConfirmCardPaymentOptions, b as CardPaymentResult, c as ClientConfig, d as CallOptions, A as ApproveResult, e as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, f as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, g as EnrollmentVerifyResult, R as RecoveryBeginResult, h as RecoveryCompleteResult } from './types-g1xz5GDk.js';
2
- export { i as BalanceRow, j as CardPaymentStatus, k as DestinationGame, I as InvoCardConfirmResponse, l as InvoCardElement, m as InvoCardElements, n as InvoCardProcessor, o as InvoError, p as InvoErrorInfo, q as InvoHooks, r as InvoRequestInfo, s as InvoResponseInfo, t as PendingCollectItem, u as Rail, V as VerificationMethod } from './types-g1xz5GDk.js';
1
+ import { M as MountCheckoutOptions, C as CheckoutMountHandle, a as ClientConfig, b as CallOptions, A as ApproveResult, c as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, d as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, e as EnrollmentVerifyResult, R as RecoveryBeginResult, f as RecoveryCompleteResult } from './types-DMNXAGiw.js';
2
+ export { g as BalanceRow, h as DestinationGame, I as InvoError, i as InvoErrorInfo, j as InvoHooks, k as InvoRequestInfo, l as InvoResponseInfo, m as PendingCollectItem, n as Rail, V as VerificationMethod } from './types-DMNXAGiw.js';
3
3
 
4
- /**
5
- * Platform Commerce card confirmation (browser side). The server (`InvoServer.
6
- * platformCommerce.purchase` with `fundingSource:"card"`) returns a `clientSecret`; this
7
- * mounts the processor's Payment Element (card / Apple Pay / Google Pay) and confirms it.
8
- * The sale is real only on the `platform_commerce.purchased` webhook — treat a "succeeded"
9
- * here as "show processing", never as fulfilled.
10
- */
11
4
  declare class PlatformCommerceClient {
12
- private readonly defaultPublishableKey;
13
- constructor(defaultPublishableKey: () => string | undefined);
14
5
  /**
15
- * Mount the Payment Element and get a session you confirm from your OWN Pay button.
16
- * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
6
+ * Embed INVO's hosted checkout in an iframe and listen for completion.
17
7
  *
18
8
  * ```ts
19
- * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
20
- * mount: "#pay", publishableKey: "pk_live_…",
9
+ * const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
10
+ * onComplete: () => showProcessing(), // then reconcile server-side
21
11
  * });
22
- * // on your Pay button click:
23
- * const r = await session.confirm({ returnUrl: location.href });
24
- * if (r.status === "succeeded") showProcessing();
25
- * session.destroy();
12
+ * // later: handle.destroy();
26
13
  * ```
14
+ *
15
+ * Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
16
+ * the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
17
+ *
18
+ * `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
19
+ * from the checkout URL's own origin (any other window could forge the event). It is a
20
+ * UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
21
+ * on this client event.
27
22
  */
28
- mountCardPayment(clientSecret: string, opts: MountCardPaymentOptions): Promise<CardPaymentSession>;
29
- /**
30
- * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
31
- * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
32
- * button, selector or element) or a minimal button the SDK renders inside `mount`. For
33
- * full control over the button, prefer {@link mountCardPayment}.
34
- */
35
- confirmCardPayment(clientSecret: string, opts: ConfirmCardPaymentOptions): Promise<CardPaymentResult>;
23
+ mountCheckout(el: string | HTMLElement, checkoutUrl: string, opts?: MountCheckoutOptions): CheckoutMountHandle;
36
24
  }
37
25
  declare class InvoClient {
38
26
  private readonly http;
@@ -40,11 +28,11 @@ declare class InvoClient {
40
28
  private readonly refreshToken;
41
29
  /** In-flight refresh, shared so concurrent expiries trigger a single re-mint. */
42
30
  private refreshInFlight;
43
- private readonly commercePublishableKey;
44
31
  /**
45
- * Platform Commerce (ecommerce) card confirmation. Use after
32
+ * Platform Commerce (ecommerce) hosted-checkout embed. Use after
46
33
  * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
47
- * `clientSecret`. The passkey/token flows never touch this. See
34
+ * `checkoutUrl` — either redirect the buyer there, or embed it with
35
+ * `mountCheckout`. No card element, no processor dependency. See
48
36
  * {@link PlatformCommerceClient}.
49
37
  */
50
38
  readonly platformCommerce: PlatformCommerceClient;
@@ -170,4 +158,4 @@ declare class InvoClient {
170
158
  private confirmReceipt;
171
159
  }
172
160
 
173
- export { ApproveResult, BalanceResult, CallOptions, CardPaymentResult, CardPaymentSession, ClientConfig, ConfirmCardPaymentOptions, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, MountCardPaymentOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
161
+ export { ApproveResult, BalanceResult, CallOptions, CheckoutMountHandle, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, MountCheckoutOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-ZKYUSYK5.js';
2
- export { InvoError } from './chunk-ZKYUSYK5.js';
1
+ import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-SPTYWJDN.js';
2
+ export { InvoError } from './chunk-SPTYWJDN.js';
3
3
 
4
4
  // src/shared/webauthn.ts
5
5
  function malformedOptions(field) {
@@ -120,184 +120,96 @@ function toBalanceRow(row) {
120
120
  raw: row
121
121
  };
122
122
  }
123
- var PROCESSOR_SRC = "https://js.stripe.com/v3";
124
- var processorScriptLoad;
125
- function loadProcessorScript() {
126
- if (typeof document === "undefined" || typeof window === "undefined") {
127
- return Promise.reject(
128
- new InvoError({
129
- message: "confirmCardPayment requires a browser DOM (window/document).",
130
- code: "DOM_UNAVAILABLE",
131
- status: 0
132
- })
133
- );
134
- }
135
- if (window.Stripe) return Promise.resolve();
136
- if (processorScriptLoad) return processorScriptLoad;
137
- processorScriptLoad = new Promise((resolve, reject) => {
138
- const existing = document.querySelector(
139
- `script[src="${PROCESSOR_SRC}"]`
140
- );
141
- const script = existing ?? document.createElement("script");
142
- if (!existing) {
143
- script.src = PROCESSOR_SRC;
144
- script.async = true;
145
- document.head.appendChild(script);
146
- }
147
- script.addEventListener("load", () => resolve());
148
- script.addEventListener("error", () => {
149
- processorScriptLoad = void 0;
150
- reject(
151
- new InvoError({
152
- message: "Failed to load the card processor script.",
153
- code: "PROCESSOR_LOAD_FAILED",
154
- status: 0
155
- })
156
- );
157
- });
158
- });
159
- return processorScriptLoad;
160
- }
161
- async function defaultLoadProcessor(publishableKey) {
162
- await loadProcessorScript();
163
- const factory = window.Stripe;
164
- if (typeof factory !== "function") {
165
- throw new InvoError({
166
- message: "The card processor was unavailable after loading.",
167
- code: "PROCESSOR_UNAVAILABLE",
168
- status: 0
169
- });
170
- }
171
- return factory(publishableKey);
172
- }
173
- function mapCardConfirm(res) {
174
- const raw = res;
175
- if (res.error) {
176
- return { status: "failed", error: res.error.message ?? "Card payment failed.", raw };
177
- }
178
- const pi = res.paymentIntent;
179
- const s = pi?.status;
180
- let status;
181
- if (s === "succeeded") status = "succeeded";
182
- else if (s === "processing") status = "processing";
183
- else if (s === "requires_action" || s === "requires_confirmation") status = "requires_action";
184
- else status = "failed";
185
- return { status, paymentIntentId: pi?.id, raw };
186
- }
187
- function resolveSubmit(opts) {
188
- if (opts.submit) {
189
- const el = typeof opts.submit === "string" ? typeof document !== "undefined" ? document.querySelector(opts.submit) : null : opts.submit;
190
- if (!el) {
191
- throw new InvoError({
192
- message: `confirmCardPayment could not find the submit element "${String(opts.submit)}".`,
193
- code: "SUBMIT_NOT_FOUND",
194
- status: 0
195
- });
196
- }
197
- return { el, created: false };
198
- }
199
- if (typeof document === "undefined") {
200
- throw new InvoError({
201
- message: "confirmCardPayment needs a submit button: pass `submit`, or use `mountCardPayment(...).confirm()` from your own button.",
202
- code: "SUBMIT_REQUIRED",
203
- status: 0
204
- });
205
- }
206
- const container = typeof opts.mount === "string" ? document.querySelector(opts.mount) : opts.mount;
207
- const btn = document.createElement("button");
208
- btn.type = "button";
209
- btn.textContent = opts.submitLabel ?? "Pay";
210
- (container ?? document.body).appendChild(btn);
211
- return { el: btn, created: true };
212
- }
213
123
  var PlatformCommerceClient = class {
214
- constructor(defaultPublishableKey) {
215
- this.defaultPublishableKey = defaultPublishableKey;
216
- }
217
124
  /**
218
- * Mount the Payment Element and get a session you confirm from your OWN Pay button.
219
- * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
125
+ * Embed INVO's hosted checkout in an iframe and listen for completion.
220
126
  *
221
127
  * ```ts
222
- * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
223
- * mount: "#pay", publishableKey: "pk_live_…",
128
+ * const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
129
+ * onComplete: () => showProcessing(), // then reconcile server-side
224
130
  * });
225
- * // on your Pay button click:
226
- * const r = await session.confirm({ returnUrl: location.href });
227
- * if (r.status === "succeeded") showProcessing();
228
- * session.destroy();
131
+ * // later: handle.destroy();
229
132
  * ```
133
+ *
134
+ * Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
135
+ * the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
136
+ *
137
+ * `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
138
+ * from the checkout URL's own origin (any other window could forge the event). It is a
139
+ * UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
140
+ * on this client event.
230
141
  */
231
- async mountCardPayment(clientSecret, opts) {
232
- if (!clientSecret || !clientSecret.trim()) {
233
- throw new Error("mountCardPayment requires a `clientSecret`.");
142
+ mountCheckout(el, checkoutUrl, opts) {
143
+ if (typeof document === "undefined" || typeof window === "undefined") {
144
+ throw new InvoError({
145
+ message: "mountCheckout requires a browser DOM (window/document).",
146
+ code: "DOM_UNAVAILABLE",
147
+ status: 0
148
+ });
234
149
  }
235
- if (opts?.mount == null || typeof opts.mount === "string" && !opts.mount.trim()) {
236
- throw new Error("mountCardPayment requires a `mount` target (selector or element).");
150
+ if (!checkoutUrl || !checkoutUrl.trim()) {
151
+ throw new Error("mountCheckout requires the server-returned `checkoutUrl`.");
237
152
  }
238
- const pk = opts.publishableKey ?? this.defaultPublishableKey();
239
- if (!pk) {
153
+ let checkoutOrigin;
154
+ try {
155
+ const u = new URL(checkoutUrl);
156
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1";
157
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
158
+ throw new Error("not https");
159
+ }
160
+ checkoutOrigin = u.origin;
161
+ } catch {
240
162
  throw new InvoError({
241
- message: "A card processor publishableKey is required \u2014 pass it in options, or set `commercePublishableKey` on the InvoClient config.",
242
- code: "MISSING_PUBLISHABLE_KEY",
163
+ message: "mountCheckout requires an absolute https checkoutUrl.",
164
+ code: "INVALID_INPUT",
243
165
  status: 0
244
166
  });
245
167
  }
246
- const load = opts.loadProcessor ?? defaultLoadProcessor;
247
- const processor = await load(pk);
248
- const elements = processor.elements({ clientSecret, appearance: opts.appearance });
249
- const element = elements.create("payment");
250
- element.mount(opts.mount);
251
- const confirm = async (confirmOpts) => {
252
- const returnUrl = confirmOpts?.returnUrl ?? opts.returnUrl;
253
- const res = await processor.confirmPayment({
254
- elements,
255
- confirmParams: returnUrl ? { return_url: returnUrl } : void 0,
256
- // Stay in-page unless the bank forces a redirect (then return_url completes it).
257
- redirect: "if_required"
168
+ const container = typeof el === "string" ? document.querySelector(el) : el;
169
+ if (!container) {
170
+ throw new InvoError({
171
+ message: `mountCheckout could not find the container "${String(el)}".`,
172
+ code: "MOUNT_NOT_FOUND",
173
+ status: 0
258
174
  });
259
- return mapCardConfirm(res);
175
+ }
176
+ const iframe = document.createElement("iframe");
177
+ iframe.src = checkoutUrl;
178
+ iframe.title = opts?.title ?? "INVO checkout";
179
+ if (opts?.className) iframe.className = opts.className;
180
+ iframe.style.width = "100%";
181
+ iframe.style.border = "0";
182
+ iframe.allow = "payment";
183
+ const onMessage = (event) => {
184
+ if (event.origin !== checkoutOrigin) return;
185
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
186
+ const msg = event.data;
187
+ if (!msg || msg.type !== "INVO_CHECKOUT_COMPLETE") return;
188
+ opts?.onComplete?.(
189
+ msg.data && typeof msg.data === "object" ? msg.data : {}
190
+ );
260
191
  };
192
+ window.addEventListener("message", onMessage);
193
+ container.appendChild(iframe);
261
194
  return {
262
- element,
263
- confirm,
195
+ iframe,
264
196
  destroy() {
265
- try {
266
- element.unmount?.();
267
- } catch {
268
- }
197
+ window.removeEventListener("message", onMessage);
198
+ iframe.remove();
269
199
  }
270
200
  };
271
201
  }
272
- /**
273
- * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
274
- * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
275
- * button, selector or element) or a minimal button the SDK renders inside `mount`. For
276
- * full control over the button, prefer {@link mountCardPayment}.
277
- */
278
- async confirmCardPayment(clientSecret, opts) {
279
- const session = await this.mountCardPayment(clientSecret, opts);
280
- const trigger = resolveSubmit(opts);
281
- return new Promise((resolve, reject) => {
282
- const finish = (settle) => {
283
- if (trigger.created) trigger.el.remove();
284
- session.destroy();
285
- settle();
286
- };
287
- const onClick = () => {
288
- trigger.el.removeEventListener("click", onClick);
289
- if ("disabled" in trigger.el) trigger.el.disabled = true;
290
- session.confirm().then(
291
- (r) => finish(() => resolve(r)),
292
- (e) => finish(() => reject(e))
293
- );
294
- };
295
- trigger.el.addEventListener("click", onClick);
296
- });
297
- }
298
202
  };
299
203
  var InvoClient = class {
300
204
  constructor(config) {
205
+ /**
206
+ * Platform Commerce (ecommerce) hosted-checkout embed. Use after
207
+ * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
208
+ * `checkoutUrl` — either redirect the buyer there, or embed it with
209
+ * `mountCheckout`. No card element, no processor dependency. See
210
+ * {@link PlatformCommerceClient}.
211
+ */
212
+ this.platformCommerce = new PlatformCommerceClient();
301
213
  if (!config.token) throw new Error("InvoClient requires a player `token`.");
302
214
  if (!config.baseUrl) throw new Error("InvoClient requires a `baseUrl`.");
303
215
  assertSecureBaseUrl(config.baseUrl);
@@ -312,8 +224,6 @@ var InvoClient = class {
312
224
  });
313
225
  this.auth = { kind: "bearer", token: config.token };
314
226
  this.refreshToken = config.refreshToken;
315
- this.commercePublishableKey = config.commercePublishableKey;
316
- this.platformCommerce = new PlatformCommerceClient(() => this.commercePublishableKey);
317
227
  }
318
228
  assertWebAuthn() {
319
229
  if (typeof navigator === "undefined" || !navigator.credentials) {
package/dist/server.cjs CHANGED
@@ -71,7 +71,9 @@ var InvoError = class _InvoError extends Error {
71
71
  get isInsufficientBalance() {
72
72
  if (this.status !== 400) return false;
73
73
  const b = this.bodyObject();
74
- return this.code === "INSUFFICIENT_BALANCE" || "required_amount" in b || /insufficient[_ ]balance/i.test(this.message);
74
+ return this.code === "INSUFFICIENT_BALANCE" || "required_amount" in b || // Zero-balance variant ("Player has no balance in this tenant") carries only
75
+ // `current_balance` — same top-up condition, so classify it the same way.
76
+ "current_balance" in b || /insufficient[_ ]balance/i.test(this.message);
75
77
  }
76
78
  /**
77
79
  * True if the call needs phone-share approval before it can complete (409) — the
@@ -157,6 +159,11 @@ var InvoError = class _InvoError extends Error {
157
159
  get isBelowCardMinimum() {
158
160
  return this.code === "BELOW_STRIPE_MINIMUM";
159
161
  }
162
+ /** True if a Platform Commerce CARD purchase exceeded the hosted checkout's single-charge
163
+ * cap of $999.99 (`ABOVE_CARD_MAXIMUM`, 400) — split the sale or lower the amount. */
164
+ get isAboveCardMaximum() {
165
+ return this.code === "ABOVE_CARD_MAXIMUM";
166
+ }
160
167
  /**
161
168
  * True if a Platform Commerce refund targeted an order that was already refunded
162
169
  * (409). Idempotent outcome — the original refund did happen, so treat this as
@@ -186,10 +193,11 @@ function errorFromResponse(status, body, requestId) {
186
193
  else if (typeof b["error_code"] === "string") code = b["error_code"];
187
194
  if (typeof b["error"] === "string") message = b["error"];
188
195
  else if (typeof b["message"] === "string") message = b["message"];
189
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited)$/.test(
196
+ if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited|service_unavailable)$/.test(
190
197
  b["error"]
191
198
  )) {
192
199
  code = b["error"];
200
+ if (typeof b["message"] === "string" && b["message"]) message = b["message"];
193
201
  }
194
202
  } else if (typeof body === "string" && body.trim()) {
195
203
  message = body;
@@ -605,7 +613,7 @@ async function hmacHexSubtle(secret, message) {
605
613
  }
606
614
 
607
615
  // src/server.ts
608
- var DEFAULT_UA = "invonetwork-web-sdk/2.5.0 (+https://invo.network)";
616
+ var DEFAULT_UA = "invonetwork-web-sdk/3.0.0 (+https://invo.network)";
609
617
  var MAX_USD_AMOUNT = 999.99;
610
618
  var MAX_ITEM_PRICE = 999999.99;
611
619
  function invalidInput(label, value, why) {
@@ -767,35 +775,8 @@ function requireField(value, field, raw) {
767
775
  return s;
768
776
  }
769
777
  var FUNDING_SOURCES = /* @__PURE__ */ new Set(["balance", "card"]);
770
- function assertBillingAddress(addr, label) {
771
- if (!addr || typeof addr !== "object") {
772
- throw invalidInput(label, addr, 'is required for the "card" funding source');
773
- }
774
- const required = [
775
- [`${label}.line1`, addr.line1],
776
- [`${label}.city`, addr.city],
777
- [`${label}.postalCode`, addr.postalCode],
778
- [`${label}.country`, addr.country]
779
- ];
780
- for (const [k, v] of required) {
781
- if (typeof v !== "string" || !v.trim()) throw invalidInput(k, v, "is required");
782
- }
783
- if (!/^[A-Za-z]{2}$/.test(addr.country)) {
784
- throw invalidInput(`${label}.country`, addr.country, "must be a 2-letter ISO country code");
785
- }
786
- }
787
- function toBillingAddressBody(addr) {
788
- const body = {
789
- line1: addr.line1,
790
- city: addr.city,
791
- postal_code: addr.postalCode,
792
- country: addr.country
793
- };
794
- if (addr.name) body["name"] = addr.name;
795
- if (addr.line2) body["line2"] = addr.line2;
796
- if (addr.state) body["state"] = addr.state;
797
- return body;
798
- }
778
+ var CARD_MIN_USD = 0.5;
779
+ var CARD_MAX_USD = 999.99;
799
780
  var PlatformCommerceServer = class {
800
781
  constructor(http, auth) {
801
782
  this.http = http;
@@ -808,13 +789,19 @@ var PlatformCommerceServer = class {
808
789
  *
809
790
  * - `fundingSource: "balance"` → settles synchronously; result `status:"success"` with
810
791
  * `newBalance`/`financialBreakdown`. `totalPrice` is the tenant's network-currency amount.
811
- * - `fundingSource: "card"` → result `status:"requires_payment"` + `clientSecret`; hand
812
- * that to the browser `platformCommerce.confirmCardPayment`. `totalPrice` is USD and a
813
- * `billingAddress` is REQUIRED. The sale is real only on the `platform_commerce.purchased`
814
- * webhook — never on the client confirmation.
792
+ * - `fundingSource: "card"` → result `status:"requires_payment"` + `checkoutUrl`/`sessionId`.
793
+ * Send the buyer to `checkoutUrl` — INVO's hosted page owns the card form, wallets,
794
+ * billing address, and 3-D Secure (there is NO billing address in this request, and no
795
+ * client payment code to write; optionally embed via
796
+ * `InvoClient.platformCommerce.mountCheckout`). `totalPrice` is USD ($0.50–$999.99).
797
+ * The sale is real only on the `platform_commerce.purchased` webhook — never on the
798
+ * client return.
815
799
  *
816
- * Idempotent on `clientRequestId` (a duplicate throws a 409 `err.isDuplicateRequest`).
817
- * A non-platform tenant throws `err.isNotPlatformTenant` (403).
800
+ * Idempotency on `clientRequestId`: the balance leg throws a 409
801
+ * (`err.isDuplicateRequest`) on a duplicate; the card leg REPLAYS the same checkout
802
+ * session (`idempotentReplay: true`) — a lost response is safely recovered by retrying
803
+ * with the SAME `clientRequestId`. A non-platform tenant throws
804
+ * `err.isNotPlatformTenant` (403).
818
805
  */
819
806
  async purchase(input, opts) {
820
807
  const required = [
@@ -845,8 +832,22 @@ var PlatformCommerceServer = class {
845
832
  );
846
833
  }
847
834
  if (input.fundingSource === "card") {
848
- assertBillingAddress(input.billingAddress, "billingAddress");
835
+ if (total < CARD_MIN_USD) {
836
+ throw new InvoError({
837
+ message: `Card purchases must be at least $${CARD_MIN_USD.toFixed(2)}.`,
838
+ code: "BELOW_STRIPE_MINIMUM",
839
+ status: 0
840
+ });
841
+ }
842
+ if (total > CARD_MAX_USD) {
843
+ throw new InvoError({
844
+ message: `Card purchases must be $${CARD_MAX_USD} or less.`,
845
+ code: "ABOVE_CARD_MAXIMUM",
846
+ status: 0
847
+ });
848
+ }
849
849
  }
850
+ if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
850
851
  const body = {
851
852
  client_request_id: input.clientRequestId,
852
853
  funding_source: input.fundingSource,
@@ -861,31 +862,37 @@ var PlatformCommerceServer = class {
861
862
  if (input.playerPhone) body["player_phone"] = input.playerPhone;
862
863
  if (input.itemDescription) body["item_description"] = input.itemDescription;
863
864
  if (input.itemCategory) body["item_category"] = input.itemCategory;
864
- if (input.billingAddress) body["billing_address"] = toBillingAddressBody(input.billingAddress);
865
+ if (input.successUrl) body["success_url"] = input.successUrl;
866
+ if (input.cancelUrl) body["cancel_url"] = input.cancelUrl;
867
+ if (input.metadata) body["metadata"] = input.metadata;
865
868
  const raw = await this.http.post(
866
869
  "/api/platform-commerce/purchase",
867
870
  body,
868
871
  this.auth,
872
+ // Safe to retry: balance dedupes (dup → 409); card REPLAYS the same session.
869
873
  { idempotent: true, signal: opts?.signal }
870
- // client_request_id makes this safe to retry (dup → 409)
871
874
  );
872
- const orderIdRaw = raw["order_id"];
873
- requireField(orderIdRaw, "order_id", raw);
874
875
  const status = String(raw["status"] ?? "");
875
- if (status === "requires_payment" && !raw["client_secret"]) {
876
- requireField(raw["client_secret"], "client_secret", raw);
876
+ if (status === "requires_payment") {
877
+ requireField(raw["checkout_url"], "checkout_url", raw);
878
+ } else {
879
+ requireField(raw["order_id"], "order_id", raw);
877
880
  }
881
+ const expiresAtRaw = raw["expires_at"];
878
882
  return {
879
883
  status,
880
884
  fundingSource: String(raw["funding_source"] ?? input.fundingSource),
881
- orderId: orderIdRaw,
885
+ orderId: raw["order_id"] ?? void 0,
882
886
  transactionId: raw["transaction_id"],
883
887
  newBalance: raw["new_balance"] ?? null,
884
888
  previousBalance: raw["previous_balance"] ?? null,
885
889
  currencyName: raw["currency_name"],
886
890
  financialBreakdown: raw["financial_breakdown"],
887
- clientSecret: raw["client_secret"],
891
+ sessionId: raw["session_id"],
892
+ checkoutUrl: raw["checkout_url"],
893
+ expiresAt: typeof expiresAtRaw === "number" ? expiresAtRaw : void 0,
888
894
  amountUsd: raw["amount_usd"] ?? null,
895
+ idempotentReplay: raw["idempotent_replay"] === true,
889
896
  raw
890
897
  };
891
898
  }
@@ -949,6 +956,9 @@ var PlatformCommerceServer = class {
949
956
  // The refund HTTP response carries no unit; derive it (card → USD). The balance leg's
950
957
  // unit is the tenant's network currency, not present here — left undefined.
951
958
  amountUnit: raw["amount_unit"] ?? (fundingSource === "card" ? "usd" : void 0),
959
+ // Balance leg: the canonical post-refund balance. Card leg: the processor's refund id.
960
+ newBalance: raw["new_balance"] ?? null,
961
+ processorRefundId: raw["stripe_refund_id"],
952
962
  feeRetained: raw["fee_retained"] === true,
953
963
  raw
954
964
  };