@invonetwork/web-sdk 2.4.1 → 2.5.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,73 @@ All notable changes to `@invonetwork/web-sdk` are documented here. This project
4
4
  [Semantic Versioning](https://semver.org/). Releases are managed with
5
5
  [changesets](https://github.com/changesets/changesets).
6
6
 
7
+ ## [2.5.1] — 2026-07-20
8
+
9
+ Hardening patch from a second, independent post-release audit (correctness vs the backend
10
+ blueprint + security red-team) of the 2.5.0 Platform Commerce feature. No API breaks.
11
+
12
+ ### Fixed
13
+ - **Card-confirm script loader could hang forever on retry.** After a transient CDN failure
14
+ (or a pre-existing processor `<script>` tag whose events already fired), the next
15
+ `mountCardPayment`/`confirmCardPayment` attached listeners to a dead tag and never settled —
16
+ checkout silently dead until page reload. The loader now removes failed tags and polls
17
+ (bounded, 10s) when a tag pre-exists.
18
+ - **Orphaned card element on submit-lookup failure.** `confirmCardPayment` now destroys the
19
+ mounted Payment Element before rethrowing when the `submit` selector can't be resolved
20
+ (previously a retry stacked a second live card iframe).
21
+ - **Billing-address validation errors no longer echo the submitted values** (cardholder PII
22
+ could otherwise land in logs/Sentry); optional billing fields (`name`/`line2`/`state`) are
23
+ now type-checked.
24
+ - **`playerPhone` on `platformCommerce.purchase` is now E.164-validated** — this endpoint can
25
+ create the player identity, so a national-format phone must never reach the wire.
26
+ - **`err.isInsufficientBalance` now also classifies the zero-balance 400** ("Player has no
27
+ balance in this tenant", which carries only `current_balance`).
28
+ - **Breaker-open 503 keeps its human message** (`err.code === "service_unavailable"`, message
29
+ no longer collapses to the bare token).
30
+ - **Webhook types:** `platform_commerce.refunded` `player_email` is nullable + `identity_id`
31
+ added; (2.5.0 already made card-leg `total_price` optional on `purchased`).
32
+ - **Refund result surfaces `newBalance`** (balance leg) **and `processorRefundId`** (card leg)
33
+ instead of leaving them `raw`-only.
34
+ - Platform-commerce error tests now assert the REAL backend envelopes
35
+ (`{status,error_code,message}` / bare `{message}`), not idealized shapes.
36
+
37
+ ### Docs
38
+ - Card-leg lost-response caveat on `purchase` (duplicate 409 can strand a `clientSecret`-less
39
+ pending order — reconcile via webhook/`getStatus`, retry with a NEW `clientRequestId`).
40
+ - `confirmCardPayment`: bank-redirect return-leg guidance + remount-after-decline note;
41
+ `CardPaymentResult.raw` log-redaction note.
42
+
43
+ ## [2.5.0] — 2026-07-20
44
+
45
+ **Platform Commerce (ecommerce).** A new flow for **platform** tenants (non-game apps: vertical
46
+ video, creator merch, marketplace) to sell items funded by **INVO balance or a real card**, with
47
+ INVO as merchant of record and full refunds. This is **distinct from item purchase** — that is a
48
+ *game* tenant spending a player's *existing game currency* on an *in-game* item (balance only, no
49
+ card, no refund). Additive; only platform tenants can call it (a game tenant gets `403
50
+ NOT_A_PLATFORM_TENANT`). (Backend handoff: BE-PIP-009 `PLATFORM_COMMERCE_SDK.md`.)
51
+
52
+ - **Server** (`InvoServer.platformCommerce`, mirrored in the Python SDK as
53
+ `server.platform_commerce`):
54
+ - `purchase(input)` — `fundingSource: "balance"` settles synchronously (`status:"success"`);
55
+ `"card"` returns `status:"requires_payment"` + a `clientSecret` and **requires a
56
+ `billingAddress`**. Idempotent on `clientRequestId`.
57
+ - `getStatus(orderId)` — `completed` | `pending_payment` | `refunded`.
58
+ - `refund({ orderId | clientRequestId, reason? })` — INVO retains its fee; a second refund
59
+ throws `409` (`err.isAlreadyRefunded`).
60
+ - **Browser** (`InvoClient.platformCommerce`):
61
+ - `confirmCardPayment(clientSecret, { mount, publishableKey?, returnUrl?, submit? })` — mounts
62
+ the card element and confirms; returns `{ status: "succeeded" | "requires_action" |
63
+ "processing" | "failed" }`. The processor JS is **lazy-loaded from its CDN — no bundled
64
+ dependency**; pass its publishable key (or set `commercePublishableKey` on the client config).
65
+ - `mountCardPayment(clientSecret, opts)` — the primitive: `{ element, confirm(), destroy() }`
66
+ to confirm from your own Pay button.
67
+ - **Webhooks:** new typed `platform_commerce.purchased` / `platform_commerce.refunded` events.
68
+ **Fulfill card orders on `platform_commerce.purchased`, never on the browser confirmation.**
69
+ - **New `InvoError` classifiers:** `isNotPlatformTenant` (403), `isAmountBelowMinimum`,
70
+ `isBelowCardMinimum` (card < $0.50), `isAlreadyRefunded` (409).
71
+ - Docs: README now leads the flow list with an explicit **item purchase vs Platform Commerce**
72
+ contrast; new "Platform Commerce (ecommerce)" section.
73
+
7
74
  ## [2.4.1] — 2026-07-10
8
75
 
9
76
  Docs only, no code change — corrects stale README prose that the 2.4.0 publish still carried:
package/README.md CHANGED
@@ -2,21 +2,26 @@
2
2
 
3
3
  First-party TypeScript SDK for integrating **INVO** into partner **web** platforms (storefronts, web games, dashboards). It wraps INVO's web money flows behind a typed, versioned API — the web analog of the Unity/Unreal plugins.
4
4
 
5
- > **Status:** `v2.4.1` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. Recent highlights: **2.2.0** reconciled with the backend (`mintPlayerToken` is a session mint — `playerPhone` optional; send-by-phone-alone; email-only `getPlayerBalance`); **2.3.0** surfaces the claim-time phone-share `409` on `confirmReceipt*`/`claim*` (+ `err.phoneShareLast4`); **2.4.0** adds Steam transfer-policy handling (`isSteamValueNonTransferable`/`isNonSteamValueIntoSteamBlocked` + `DestinationGame.acceptsSteamOriginValue`). Full history in the [CHANGELOG](CHANGELOG.md).
5
+ > **Status:** `v2.5.1` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. Recent highlights: **2.5.1** hardens 2.5.0 from a second independent audit (card-confirm loader retry fix, PII-free validation errors, E.164 on `platformCommerce` phone, refund `newBalance`/`processorRefundId`); **2.5.0** adds **Platform Commerce** (ecommerce) — a platform tenant selling items funded by balance **or** card, with `invo.platformCommerce.purchase/getStatus/refund` (server), `invo.platformCommerce.confirmCardPayment` (browser), and the `platform_commerce.*` webhooks; **2.4.0** adds Steam transfer-policy handling (`isSteamValueNonTransferable`/`isNonSteamValueIntoSteamBlocked` + `DestinationGame.acceptsSteamOriginValue`); **2.3.0** surfaces the claim-time phone-share `409` on `confirmReceipt*`/`claim*` (+ `err.phoneShareLast4`). Full history in the [CHANGELOG](CHANGELOG.md).
6
6
  > Canonical partner reference: **https://docs.invo.network/docs/currency-purchase** and **https://docs.invo.network/docs/game-developer-integration**.
7
7
 
8
8
  ## What it does
9
9
 
10
- Four money flows plus passkey (WebAuthn) authentication, split across a trusted server entry and an untrusted browser entry:
10
+ Five money flows plus passkey (WebAuthn) authentication, split across a trusted server entry and an untrusted browser entry:
11
11
 
12
12
  | Flow | Direction | Real money? | Passkey? | Where |
13
13
  |---|---|---|---|---|
14
14
  | **Currency purchase** | real money **→** game currency | yes (card/rails) | no | server initiates, browser opens hosted checkout |
15
15
  | **Item purchase** | game currency **→** in-game item | no (balance debit) | no | server only |
16
+ | **Platform Commerce** (ecommerce) | balance **or** card **→** a storefront item | card leg only | no | server creates, browser confirms the card |
16
17
  | **Send** | currency **→** another player (cross-game) | no | yes (sender approves) | server initiates, browser approves/claims |
17
18
  | **Transfer** | currency **→** another player (transfer rail) | no | yes (sender approves) | server initiates, browser approves/claims |
18
19
 
19
- The **game secret stays on your server**; the browser only ever holds a short-lived, game-scoped **player token**.
20
+ > **Item purchase vs Platform Commerce — don't mix them up.** They share a body shape (`itemId`, `unitPrice`, `totalPrice`, `clientRequestId`) but are different products:
21
+ > - **[Item purchase](#item-purchase-spend-game-currency)** — a **game** tenant. A player spends **game currency they already hold** on an **in-game** item (a sword, a skin). Always a balance debit — **never a card, never new money, no refunds**. `server.purchaseItem(...)` → `/api/item-purchases`.
22
+ > - **[Platform Commerce](#platform-commerce-ecommerce)** — a **platform** tenant (a non-game app: vertical video, creator merch, marketplace). A **storefront** sale funded by **INVO balance or a real card** (new money), with **INVO as merchant of record** and **refunds**. `server.platformCommerce.purchase(...)` → `/api/platform-commerce`. A game tenant calling it gets `403 NOT_A_PLATFORM_TENANT`.
23
+
24
+ The **game secret stays on your server**; the browser only ever holds a short-lived, game-scoped **player token** (and, for the card leg, a per-purchase `clientSecret`).
20
25
 
21
26
  ## Contents
22
27
 
@@ -26,6 +31,7 @@ The **game secret stays on your server**; the browser only ever holds a short-li
26
31
  - [Configuration](#configuration)
27
32
  - [Currency purchase (real money in)](#currency-purchase-real-money-in)
28
33
  - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
34
+ - [Platform Commerce (ecommerce)](#platform-commerce-ecommerce)
29
35
  - [Player balance](#player-balance)
30
36
  - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
31
37
  - [Passkeys (enroll, approve, link, recover)](#passkeys-enroll-approve-link-recover)
@@ -303,6 +309,92 @@ const item = await server.purchaseItem({
303
309
 
304
310
  ---
305
311
 
312
+ ## Platform Commerce (ecommerce)
313
+
314
+ > **This is not [item purchase](#item-purchase-spend-game-currency).** Item purchase is a *game* tenant spending a player's *existing game currency* on an *in-game* item — always a balance debit, never a card, no refunds. **Platform Commerce is a _platform_ tenant (a non-game app: vertical video, creator merch, marketplace) running a storefront.** The buyer pays with **INVO balance** *or* a **real card** (new money), INVO is **merchant of record**, and **refunds** exist. Only platform tenants may call it — a game tenant gets `403` (`err.isNotPlatformTenant`).
315
+
316
+ The funding source is resolved **server-side under lock** — the client can *request* `balance` or `card`, but the backend verifies the real balance before any value moves. That's why there's a server call (holds the secret, creates the purchase/refund) **and** a browser call (confirms the card). Reached via the `platformCommerce` namespace on each entry point.
317
+
318
+ ### Balance leg — one server call, settles now
319
+
320
+ ```ts
321
+ const r = await server.platformCommerce.purchase({
322
+ clientRequestId: crypto.randomUUID(), // idempotency key, unique per tenant
323
+ fundingSource: "balance",
324
+ playerEmail: "user@example.com",
325
+ playerName: "Ada",
326
+ itemId: "sticker_pack_01",
327
+ itemName: "Sticker Pack",
328
+ itemQuantity: 1, // integer 1..1000
329
+ unitPrice: "5.00", // BALANCE leg: the tenant's network-currency amount
330
+ totalPrice: "5.00", // must equal unitPrice × itemQuantity (±0.01)
331
+ });
332
+ // r.status === "success" — settled synchronously
333
+ // r.newBalance / r.previousBalance / r.currencyName
334
+ // r.orderId / r.transactionId
335
+ // r.financialBreakdown { total_paid, developer_revenue, platform_fee } // INVO fee: 3.5% flat
336
+ ```
337
+
338
+ ### Card leg — server creates, browser confirms
339
+
340
+ The card leg is the SDK's only browser **payment** step. `totalPrice` is **USD**, and a **`billingAddress`** is required (AVS / fraud / merchant-of-record).
341
+
342
+ ```ts
343
+ // 1) server — returns a clientSecret, NOT yet paid
344
+ const r = await server.platformCommerce.purchase({
345
+ clientRequestId: crypto.randomUUID(),
346
+ fundingSource: "card",
347
+ playerEmail: "user@example.com",
348
+ playerName: "Ada",
349
+ itemId: "sticker_pack_01",
350
+ itemName: "Sticker Pack",
351
+ itemQuantity: 1,
352
+ unitPrice: "5.00", // CARD leg: USD
353
+ totalPrice: "5.00",
354
+ billingAddress: { // REQUIRED on the card leg
355
+ line1: "1 Main St", city: "Austin", postalCode: "78701", country: "US",
356
+ // optional: name, line2, state
357
+ },
358
+ });
359
+ // r.status === "requires_payment"; hand r.clientSecret to the browser
360
+ ```
361
+
362
+ ```ts
363
+ // 2) browser — mount the card element and confirm. The SDK lazy-loads the card
364
+ // processor's JS from its CDN (no bundled dependency); pass its PUBLISHABLE key.
365
+ const result = await invo.platformCommerce.confirmCardPayment(clientSecret, {
366
+ mount: "#pay", // a CSS selector or an HTMLElement
367
+ publishableKey: "pk_live_…", // or set commercePublishableKey on the InvoClient config
368
+ returnUrl: location.href, // where the bank returns after any 3-D Secure step
369
+ // optional: submit (your own Pay button, selector or element), submitLabel, appearance
370
+ });
371
+ // result.status: "succeeded" | "requires_action" | "processing" | "failed"
372
+ ```
373
+
374
+ For full control over your own Pay button, use the primitive: `const session = await invo.platformCommerce.mountCardPayment(clientSecret, { mount, publishableKey })`, then call `await session.confirm({ returnUrl })` from your button and `session.destroy()` when done.
375
+
376
+ > ⚠️ **The card sale is real only on the `platform_commerce.purchased` webhook — never on the browser confirmation** (a client can be tampered with). Treat `"succeeded"` as "show processing" and fulfill on the webhook.
377
+
378
+ ### Status & refunds
379
+
380
+ ```ts
381
+ const s = await server.platformCommerce.getStatus(r.orderId);
382
+ // s.status: "completed" (balance immediately; card after the webhook) | "pending_payment" | "refunded"
383
+
384
+ const ref = await server.platformCommerce.refund({ orderId: r.orderId, reason: "customer request" });
385
+ // or refund({ clientRequestId }). Pass EXACTLY ONE id.
386
+ // INVO retains its fee (ref.feeRetained === true); the customer is made whole minus that fee.
387
+ // A second refund of the same order throws 409 (err.isAlreadyRefunded) — treat as already done.
388
+ ```
389
+
390
+ - **Idempotent** on `clientRequestId` — a duplicate purchase throws `409` (`err.isDuplicateRequest`).
391
+ - **Lost card-purchase response?** If the network drops the card-leg response, you won't have the `clientSecret` or `orderId`, and retrying the same `clientRequestId` returns `409` (the order already exists). Reconcile via your **`platform_commerce.purchased`** webhook — don't retry to recover the `clientSecret`. (The balance leg is fully retry-safe.)
392
+ - INVO fee: **3.5% flat** (balance) · **3.5% + $0.30** (card). Below-minimum amounts throw `err.isAmountBelowMinimum`; a card charge under $0.50 throws `err.isBelowCardMinimum`.
393
+ - Client-side validation (missing fields, bad funding source, quantity outside `1..1000`, total ≠ unit×qty, missing/short billing address on the card leg) throws `INVALID_INPUT` **before** any network call.
394
+ - Fulfill on the **`platform_commerce.purchased`** webhook; handle **`platform_commerce.refunded`** for reversals.
395
+
396
+ ---
397
+
306
398
  ## Player balance
307
399
 
308
400
  Read a player's currency balances (server-side, game-secret) **by email**:
@@ -526,8 +618,10 @@ export const POST = createWebhookHandler({
526
618
  | `purchase.failed` / `purchase.disputed` | `platform` rail only | handle failures/disputes |
527
619
  | `purchase.refunded` | `game` / `steam` rails | handle refunds |
528
620
  | `item.purchased` | every item purchase | **grant the in-game item** (payload includes `transaction_id, order_id, player_email, identity_id, item_id, item_name, item_quantity, unit_price, total_price, currency_name, new_balance, fee_breakdown`) |
621
+ | `platform_commerce.purchased` | every Platform Commerce purchase (balance immediately; **card after payment settles**) | **fulfill the ecommerce order** — never on the browser confirm (payload: `transaction_id, order_id, funding_source, player_email, identity_id, item_id, item_name, item_quantity, total_price`; + `unit_price, currency_name, new_balance` on balance; `total_price_usd` on card; `fee_breakdown`) |
622
+ | `platform_commerce.refunded` | a Platform Commerce refund | handle the reversal (payload: `order_id, funding_source, player_email, refunded_amount, amount_unit, fee_retained`) |
529
623
 
530
- Don't block waiting on `purchase.failed` for the `game`/`steam` rails — they only emit `completed`/`refunded`. Reconcile off `*.completed` + the status endpoints.
624
+ Don't block waiting on `purchase.failed` for the `game`/`steam` rails — they only emit `completed`/`refunded`. Reconcile off `*.completed` + the status endpoints. For Platform Commerce **card** orders, fulfill on `platform_commerce.purchased`, not the browser confirmation.
531
625
 
532
626
  ---
533
627
 
@@ -570,6 +664,9 @@ Helpers:
570
664
  | `.isReceiverNotEnrolled` | recipient has no passkey → switch to claim-code entry |
571
665
  | `.isInsufficientBalance` | item purchase failed (400); `required_amount` + `current_balance` on `.body` |
572
666
  | `.isDuplicateRequest` | idempotency-keyed request was a duplicate (409) |
667
+ | `.isNotPlatformTenant` | Platform Commerce called by a non-platform tenant (403) — use `purchaseItem`/`createCheckout` instead |
668
+ | `.isAmountBelowMinimum` / `.isBelowCardMinimum` | Platform Commerce amount too small for the fee to round up / card charge under $0.50 (400) |
669
+ | `.isAlreadyRefunded` | Platform Commerce refund of an already-refunded order (409) — treat as already done |
573
670
  | `.retryAfter` | seconds to back off on a 429 throttle |
574
671
  | `.isEnrollmentAuthorizationRequired` | first-enrollment needs the OTP grant → `enrollmentBegin`/`enrollmentVerify` |
575
672
  | `.isEnrollmentProofRequired` | another method exists → prove it via `linkDevice` |
@@ -606,9 +703,12 @@ try {
606
703
  | `purchaseCurrency(input)` | `{ status, clientSecret?, paymentIntentId?, paymentUrl?, transactionId?, orderId?, newBalance?, raw }` |
607
704
  | `confirmPayment({ paymentIntentId, orderId? })` | `{ status, transactionId?, newBalance?, raw }` |
608
705
  | `getOrderDetails({ orderId? \| transactionId? })` | `{ order, financialSummary, statusTimeline, raw }` |
609
- | `purchaseItem(input)` | `{ status, transactionId, orderId, newBalance, previousBalance, currencyName, financialBreakdown?, raw }` |
706
+ | `purchaseItem(input)` | `{ status, transactionId, orderId, newBalance, previousBalance, currencyName, financialBreakdown?, raw }` — **game** tenant spending game currency on an in-game item |
610
707
  | `getItemPurchaseHistory({ playerEmail, limit?, offset? })` | `{ history, pagination, raw }` |
611
708
  | `getItemOrderDetails({ orderId? \| transactionId? \| clientRequestId? })` | `{ order, financialSummary, statusTimeline, raw }` |
709
+ | `platformCommerce.purchase(input)` | `{ status, fundingSource, orderId, transactionId?, newBalance?, financialBreakdown?, clientSecret?, amountUsd?, raw }` — **ecommerce** (platform tenant); `balance` settles now, `card` returns a `clientSecret` |
710
+ | `platformCommerce.getStatus(orderId)` | `{ orderId, status, gameCurrencyAmount?, usdAmount?, paymentMethod?, createdAt?, raw }` |
711
+ | `platformCommerce.refund({ orderId? \| clientRequestId?, reason? })` | `{ status, orderId?, fundingSource?, refundedAmount?, amountUnit?, feeRetained?, raw }` — pass **exactly one** id; INVO keeps its fee |
612
712
  | `getPlayerBalance({ playerEmail })` | `{ player, balances, summary, raw }` — **by email only** (no by-id route; use `InvoClient.getBalance()` client-side) |
613
713
  | `getInboundPending({ playerEmail? \| playerPhone? })` | `{ inboundPending, raw }` — live unclaimed inbound sends/transfers |
614
714
  | `getLinkedIdentities({ playerEmail? \| playerPhone? })` | `{ walletUserId, primaryEmail, primaryPhone, isMinor, emails, notFound, raw }` — **server-only** (returns PII) |
@@ -638,8 +738,10 @@ Every method also accepts an optional final `{ signal }` (`AbortSignal`) for can
638
738
  | `getPendingCollect()` | `{ pending, raw }` — the player's own pending-to-collect list (player-token) |
639
739
  | `getDestinations({ direction? })` | `{ availableGames, sourceGameName, transferMode, … }` — where the player can send/transfer, metadata inline |
640
740
  | `getBalance()` | `{ gameId, gameName, balances, totalValue, currencyCount, hasFunds, raw }` — the player's balances for this game |
741
+ | `platformCommerce.confirmCardPayment(clientSecret, { mount, publishableKey?, returnUrl?, submit?, appearance? })` | `{ status: "succeeded" \| "requires_action" \| "processing" \| "failed", paymentIntentId?, error?, raw }` — mount + confirm the Platform Commerce card leg |
742
+ | `platformCommerce.mountCardPayment(clientSecret, { mount, publishableKey? })` | `{ element, confirm({ returnUrl? }), destroy() }` — the primitive: confirm from your own Pay button |
641
743
 
642
- Every method throws `InvoError` on failure and takes an optional final `{ signal }`. Full inline types ship with the package.
744
+ Every method throws `InvoError` on failure and takes an optional final `{ signal }`. Full inline types ship with the package. For the Platform Commerce card leg, set `commercePublishableKey` on the `InvoClient` config (or pass `publishableKey` per call); the processor JS is lazy-loaded from its CDN — nothing to bundle.
643
745
 
644
746
  ---
645
747
 
@@ -67,7 +67,9 @@ var InvoError = class _InvoError extends Error {
67
67
  get isInsufficientBalance() {
68
68
  if (this.status !== 400) return false;
69
69
  const b = this.bodyObject();
70
- return this.code === "INSUFFICIENT_BALANCE" || "required_amount" in b || /insufficient[_ ]balance/i.test(this.message);
70
+ return this.code === "INSUFFICIENT_BALANCE" || "required_amount" in b || // Zero-balance variant ("Player has no balance in this tenant") carries only
71
+ // `current_balance` — same top-up condition, so classify it the same way.
72
+ "current_balance" in b || /insufficient[_ ]balance/i.test(this.message);
71
73
  }
72
74
  /**
73
75
  * True if the call needs phone-share approval before it can complete (409) — the
@@ -130,10 +132,37 @@ var InvoError = class _InvoError extends Error {
130
132
  get isPhoneShareAlreadyApproved() {
131
133
  return this.code === "PHONE_SHARE_ALREADY_APPROVED";
132
134
  }
133
- /** True if an idempotency-keyed request was a duplicate (item purchase → 409). */
135
+ /** True if an idempotency-keyed request was a duplicate (item / platform purchase → 409). */
134
136
  get isDuplicateRequest() {
135
137
  return this.code === "DUPLICATE_REQUEST" || this.status === 409 && /duplicate/i.test(this.message);
136
138
  }
139
+ /**
140
+ * True if a Platform Commerce call was rejected because the tenant isn't a platform
141
+ * tenant (`NOT_A_PLATFORM_TENANT`, 403). Platform Commerce (`invo.platformCommerce.*`)
142
+ * is only for non-game platform tenants — a game tenant should use `purchaseItem`
143
+ * (spend game currency) or `createCheckout`/`purchaseCurrency` (buy currency) instead.
144
+ */
145
+ get isNotPlatformTenant() {
146
+ return this.code === "NOT_A_PLATFORM_TENANT";
147
+ }
148
+ /** True if a Platform Commerce purchase was too small for the fee to round above zero
149
+ * (`AMOUNT_BELOW_MINIMUM`, 400) — raise the amount. */
150
+ get isAmountBelowMinimum() {
151
+ return this.code === "AMOUNT_BELOW_MINIMUM";
152
+ }
153
+ /** True if a Platform Commerce CARD purchase was below the processor's floor of $0.50
154
+ * (backend code `BELOW_STRIPE_MINIMUM`, 400). Neutral name; matches the wire code. */
155
+ get isBelowCardMinimum() {
156
+ return this.code === "BELOW_STRIPE_MINIMUM";
157
+ }
158
+ /**
159
+ * True if a Platform Commerce refund targeted an order that was already refunded
160
+ * (409). Idempotent outcome — the original refund did happen, so treat this as
161
+ * success, not a failure to retry-loop.
162
+ */
163
+ get isAlreadyRefunded() {
164
+ return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
165
+ }
137
166
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
138
167
  get retryAfter() {
139
168
  const v = this.bodyObject()["retry_after"];
@@ -155,10 +184,11 @@ function errorFromResponse(status, body, requestId) {
155
184
  else if (typeof b["error_code"] === "string") code = b["error_code"];
156
185
  if (typeof b["error"] === "string") message = b["error"];
157
186
  else if (typeof b["message"] === "string") message = b["message"];
158
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited)$/.test(
187
+ 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(
159
188
  b["error"]
160
189
  )) {
161
190
  code = b["error"];
191
+ if (typeof b["message"] === "string" && b["message"]) message = b["message"];
162
192
  }
163
193
  } else if (typeof body === "string" && body.trim()) {
164
194
  message = body;
@@ -411,5 +441,5 @@ function toDestinationsResult(raw, direction) {
411
441
  }
412
442
 
413
443
  export { Http, InvoError, assertSecureBaseUrl, toDestinationsResult };
414
- //# sourceMappingURL=chunk-SSTZKXPC.js.map
415
- //# sourceMappingURL=chunk-SSTZKXPC.js.map
444
+ //# sourceMappingURL=chunk-5X3ESHJR.js.map
445
+ //# sourceMappingURL=chunk-5X3ESHJR.js.map
package/dist/index.cjs CHANGED
@@ -69,7 +69,9 @@ var InvoError = class _InvoError extends Error {
69
69
  get isInsufficientBalance() {
70
70
  if (this.status !== 400) return false;
71
71
  const b = this.bodyObject();
72
- return this.code === "INSUFFICIENT_BALANCE" || "required_amount" in b || /insufficient[_ ]balance/i.test(this.message);
72
+ return this.code === "INSUFFICIENT_BALANCE" || "required_amount" in b || // Zero-balance variant ("Player has no balance in this tenant") carries only
73
+ // `current_balance` — same top-up condition, so classify it the same way.
74
+ "current_balance" in b || /insufficient[_ ]balance/i.test(this.message);
73
75
  }
74
76
  /**
75
77
  * True if the call needs phone-share approval before it can complete (409) — the
@@ -132,10 +134,37 @@ var InvoError = class _InvoError extends Error {
132
134
  get isPhoneShareAlreadyApproved() {
133
135
  return this.code === "PHONE_SHARE_ALREADY_APPROVED";
134
136
  }
135
- /** True if an idempotency-keyed request was a duplicate (item purchase → 409). */
137
+ /** True if an idempotency-keyed request was a duplicate (item / platform purchase → 409). */
136
138
  get isDuplicateRequest() {
137
139
  return this.code === "DUPLICATE_REQUEST" || this.status === 409 && /duplicate/i.test(this.message);
138
140
  }
141
+ /**
142
+ * True if a Platform Commerce call was rejected because the tenant isn't a platform
143
+ * tenant (`NOT_A_PLATFORM_TENANT`, 403). Platform Commerce (`invo.platformCommerce.*`)
144
+ * is only for non-game platform tenants — a game tenant should use `purchaseItem`
145
+ * (spend game currency) or `createCheckout`/`purchaseCurrency` (buy currency) instead.
146
+ */
147
+ get isNotPlatformTenant() {
148
+ return this.code === "NOT_A_PLATFORM_TENANT";
149
+ }
150
+ /** True if a Platform Commerce purchase was too small for the fee to round above zero
151
+ * (`AMOUNT_BELOW_MINIMUM`, 400) — raise the amount. */
152
+ get isAmountBelowMinimum() {
153
+ return this.code === "AMOUNT_BELOW_MINIMUM";
154
+ }
155
+ /** True if a Platform Commerce CARD purchase was below the processor's floor of $0.50
156
+ * (backend code `BELOW_STRIPE_MINIMUM`, 400). Neutral name; matches the wire code. */
157
+ get isBelowCardMinimum() {
158
+ return this.code === "BELOW_STRIPE_MINIMUM";
159
+ }
160
+ /**
161
+ * True if a Platform Commerce refund targeted an order that was already refunded
162
+ * (409). Idempotent outcome — the original refund did happen, so treat this as
163
+ * success, not a failure to retry-loop.
164
+ */
165
+ get isAlreadyRefunded() {
166
+ return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
167
+ }
139
168
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
140
169
  get retryAfter() {
141
170
  const v = this.bodyObject()["retry_after"];
@@ -157,10 +186,11 @@ function errorFromResponse(status, body, requestId) {
157
186
  else if (typeof b["error_code"] === "string") code = b["error_code"];
158
187
  if (typeof b["error"] === "string") message = b["error"];
159
188
  else if (typeof b["message"] === "string") message = b["message"];
160
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited)$/.test(
189
+ 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(
161
190
  b["error"]
162
191
  )) {
163
192
  code = b["error"];
193
+ if (typeof b["message"] === "string" && b["message"]) message = b["message"];
164
194
  }
165
195
  } else if (typeof body === "string" && body.trim()) {
166
196
  message = body;
@@ -531,6 +561,214 @@ function toBalanceRow(row) {
531
561
  raw: row
532
562
  };
533
563
  }
564
+ var PROCESSOR_SRC = "https://js.stripe.com/v3";
565
+ var PROCESSOR_LOAD_TIMEOUT_MS = 1e4;
566
+ var processorScriptLoad;
567
+ function loadProcessorScript() {
568
+ if (typeof document === "undefined" || typeof window === "undefined") {
569
+ return Promise.reject(
570
+ new InvoError({
571
+ message: "confirmCardPayment requires a browser DOM (window/document).",
572
+ code: "DOM_UNAVAILABLE",
573
+ status: 0
574
+ })
575
+ );
576
+ }
577
+ if (window.Stripe) return Promise.resolve();
578
+ if (processorScriptLoad) return processorScriptLoad;
579
+ processorScriptLoad = new Promise((resolve, reject) => {
580
+ const fail = () => {
581
+ processorScriptLoad = void 0;
582
+ reject(
583
+ new InvoError({
584
+ message: "Failed to load the card processor script.",
585
+ code: "PROCESSOR_LOAD_FAILED",
586
+ status: 0
587
+ })
588
+ );
589
+ };
590
+ const existing = document.querySelector(
591
+ `script[src="${PROCESSOR_SRC}"]`
592
+ );
593
+ if (existing) {
594
+ const started = Date.now();
595
+ const poll = setInterval(() => {
596
+ if (window.Stripe) {
597
+ clearInterval(poll);
598
+ resolve();
599
+ } else if (Date.now() - started > PROCESSOR_LOAD_TIMEOUT_MS) {
600
+ clearInterval(poll);
601
+ existing.remove();
602
+ fail();
603
+ }
604
+ }, 100);
605
+ return;
606
+ }
607
+ const script = document.createElement("script");
608
+ script.src = PROCESSOR_SRC;
609
+ script.async = true;
610
+ script.addEventListener("load", () => resolve());
611
+ script.addEventListener("error", () => {
612
+ script.remove();
613
+ fail();
614
+ });
615
+ document.head.appendChild(script);
616
+ });
617
+ return processorScriptLoad;
618
+ }
619
+ async function defaultLoadProcessor(publishableKey) {
620
+ await loadProcessorScript();
621
+ const factory = window.Stripe;
622
+ if (typeof factory !== "function") {
623
+ throw new InvoError({
624
+ message: "The card processor was unavailable after loading.",
625
+ code: "PROCESSOR_UNAVAILABLE",
626
+ status: 0
627
+ });
628
+ }
629
+ return factory(publishableKey);
630
+ }
631
+ function mapCardConfirm(res) {
632
+ const raw = res;
633
+ if (res.error) {
634
+ return { status: "failed", error: res.error.message ?? "Card payment failed.", raw };
635
+ }
636
+ const pi = res.paymentIntent;
637
+ const s = pi?.status;
638
+ let status;
639
+ if (s === "succeeded") status = "succeeded";
640
+ else if (s === "processing") status = "processing";
641
+ else if (s === "requires_action" || s === "requires_confirmation") status = "requires_action";
642
+ else status = "failed";
643
+ return { status, paymentIntentId: pi?.id, raw };
644
+ }
645
+ function resolveSubmit(opts) {
646
+ if (opts.submit) {
647
+ const el = typeof opts.submit === "string" ? typeof document !== "undefined" ? document.querySelector(opts.submit) : null : opts.submit;
648
+ if (!el) {
649
+ throw new InvoError({
650
+ message: `confirmCardPayment could not find the submit element "${String(opts.submit)}".`,
651
+ code: "SUBMIT_NOT_FOUND",
652
+ status: 0
653
+ });
654
+ }
655
+ return { el, created: false };
656
+ }
657
+ if (typeof document === "undefined") {
658
+ throw new InvoError({
659
+ message: "confirmCardPayment needs a submit button: pass `submit`, or use `mountCardPayment(...).confirm()` from your own button.",
660
+ code: "SUBMIT_REQUIRED",
661
+ status: 0
662
+ });
663
+ }
664
+ const container = typeof opts.mount === "string" ? document.querySelector(opts.mount) : opts.mount;
665
+ const btn = document.createElement("button");
666
+ btn.type = "button";
667
+ btn.textContent = opts.submitLabel ?? "Pay";
668
+ (container ?? document.body).appendChild(btn);
669
+ return { el: btn, created: true };
670
+ }
671
+ var PlatformCommerceClient = class {
672
+ constructor(defaultPublishableKey) {
673
+ this.defaultPublishableKey = defaultPublishableKey;
674
+ }
675
+ /**
676
+ * Mount the Payment Element and get a session you confirm from your OWN Pay button.
677
+ * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
678
+ *
679
+ * ```ts
680
+ * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
681
+ * mount: "#pay", publishableKey: "pk_live_…",
682
+ * });
683
+ * // on your Pay button click:
684
+ * const r = await session.confirm({ returnUrl: location.href });
685
+ * if (r.status === "succeeded") showProcessing();
686
+ * session.destroy();
687
+ * ```
688
+ */
689
+ async mountCardPayment(clientSecret, opts) {
690
+ if (!clientSecret || !clientSecret.trim()) {
691
+ throw new Error("mountCardPayment requires a `clientSecret`.");
692
+ }
693
+ if (opts?.mount == null || typeof opts.mount === "string" && !opts.mount.trim()) {
694
+ throw new Error("mountCardPayment requires a `mount` target (selector or element).");
695
+ }
696
+ const pk = opts.publishableKey ?? this.defaultPublishableKey();
697
+ if (!pk) {
698
+ throw new InvoError({
699
+ message: "A card processor publishableKey is required \u2014 pass it in options, or set `commercePublishableKey` on the InvoClient config.",
700
+ code: "MISSING_PUBLISHABLE_KEY",
701
+ status: 0
702
+ });
703
+ }
704
+ const load = opts.loadProcessor ?? defaultLoadProcessor;
705
+ const processor = await load(pk);
706
+ const elements = processor.elements({ clientSecret, appearance: opts.appearance });
707
+ const element = elements.create("payment");
708
+ element.mount(opts.mount);
709
+ const confirm = async (confirmOpts) => {
710
+ const returnUrl = confirmOpts?.returnUrl ?? opts.returnUrl;
711
+ const res = await processor.confirmPayment({
712
+ elements,
713
+ confirmParams: returnUrl ? { return_url: returnUrl } : void 0,
714
+ // Stay in-page unless the bank forces a redirect (then return_url completes it).
715
+ redirect: "if_required"
716
+ });
717
+ return mapCardConfirm(res);
718
+ };
719
+ return {
720
+ element,
721
+ confirm,
722
+ destroy() {
723
+ try {
724
+ element.unmount?.();
725
+ } catch {
726
+ }
727
+ }
728
+ };
729
+ }
730
+ /**
731
+ * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
732
+ * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
733
+ * button, selector or element) or a minimal button the SDK renders inside `mount`. For
734
+ * full control over the button, prefer {@link mountCardPayment}.
735
+ *
736
+ * Two flow notes:
737
+ * - **Bank redirect:** with `redirect: "if_required"` most cards confirm in-page, but a
738
+ * bank can force a full redirect — the browser then navigates away (this promise never
739
+ * settles) and returns to `returnUrl`. On that return page, reconcile via your server's
740
+ * `platformCommerce.getStatus(orderId)` / the `platform_commerce.purchased` webhook.
741
+ * - **Decline / "failed":** the element is torn down when this resolves — to let the user
742
+ * retry after a decline, call `confirmCardPayment` (or `mountCardPayment`) again to
743
+ * remount.
744
+ */
745
+ async confirmCardPayment(clientSecret, opts) {
746
+ const session = await this.mountCardPayment(clientSecret, opts);
747
+ let trigger;
748
+ try {
749
+ trigger = resolveSubmit(opts);
750
+ } catch (e) {
751
+ session.destroy();
752
+ throw e;
753
+ }
754
+ return new Promise((resolve, reject) => {
755
+ const finish = (settle) => {
756
+ if (trigger.created) trigger.el.remove();
757
+ session.destroy();
758
+ settle();
759
+ };
760
+ const onClick = () => {
761
+ trigger.el.removeEventListener("click", onClick);
762
+ if ("disabled" in trigger.el) trigger.el.disabled = true;
763
+ session.confirm().then(
764
+ (r) => finish(() => resolve(r)),
765
+ (e) => finish(() => reject(e))
766
+ );
767
+ };
768
+ trigger.el.addEventListener("click", onClick);
769
+ });
770
+ }
771
+ };
534
772
  var InvoClient = class {
535
773
  constructor(config) {
536
774
  if (!config.token) throw new Error("InvoClient requires a player `token`.");
@@ -547,6 +785,8 @@ var InvoClient = class {
547
785
  });
548
786
  this.auth = { kind: "bearer", token: config.token };
549
787
  this.refreshToken = config.refreshToken;
788
+ this.commercePublishableKey = config.commercePublishableKey;
789
+ this.platformCommerce = new PlatformCommerceClient(() => this.commercePublishableKey);
550
790
  }
551
791
  assertWebAuthn() {
552
792
  if (typeof navigator === "undefined" || !navigator.credentials) {
@@ -889,5 +1129,6 @@ var InvoClient = class {
889
1129
 
890
1130
  exports.InvoClient = InvoClient;
891
1131
  exports.InvoError = InvoError;
1132
+ exports.PlatformCommerceClient = PlatformCommerceClient;
892
1133
  //# sourceMappingURL=index.cjs.map
893
1134
  //# sourceMappingURL=index.cjs.map