@invonetwork/web-sdk 3.18.0 → 3.20.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/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.20.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1dc07df: Loyalty and rewards. Server: `InvoServer.getPlayerRewards(playerEmail)` reads one player's
8
+ loyalty cards with the game secret (`GET /api/sdk/loyalty/players/rewards`). Browser, with the
9
+ player token: `InvoClient.getMyRewards()` (the player's cards), `getMyVault()`,
10
+ `redeemReward(vaultEntryId)` (the only response with a code; never auto-retried) and
11
+ `getRewardsPageLink()` (INVO's hosted "My rewards" page). Every card step carries `progress`,
12
+ `{ current, target }`, or `null` when unavailable; `state` decides completion. New error
13
+ predicates `isRewardAlreadyRedeemed`, `isRewardNotFound`, `isRewardExpired`,
14
+ `isRewardUnavailable` (`inventory_exhausted` / `conflict`); the server read's
15
+ `PLAYER_NOT_FOUND` and `INVALID_PLAYER_EMAIL` use the existing `isPlayerNotFound` and
16
+ `isInvalidPlayerEmail`. Additive only. README section "Loyalty and rewards".
17
+
18
+ ## 3.19.0
19
+
20
+ ### Minor Changes
21
+
22
+ - 6940139: D-PRICE-012: a subscription card refund, and a lost chargeback not covered by the chargeback guarantee, now cost the partner the whole refunded amount, INVO's card fee included, exactly as a Platform Commerce card refund does. There is no separate payment processor fee on a refund any more: `processingFeeUsd` reads `"0.00"` and `processingFeeBasis` `"none"`.
23
+
24
+ Additive, optional fields:
25
+
26
+ - `RefundResult.cardFeeChargedToPartnerUsd` and `RefundResult.partnerDebitedUsd` on `subscriptions.refund` (the 200 receipt and the 202 `pending_approval` body). `undefined` on a receipt stored before this release.
27
+ - `card_fee_charged_to_partner_usd` and `partner_debited_usd` on the `refund` block of `subscription.refunded` (`SubscriptionRefundDetail`) and on `purchase.disputed` (`PurchaseEventData`, subscription and Platform Commerce losses; `null` where not applicable).
28
+
29
+ README: subscription refund costs, lost chargebacks and the "What did I earn?" answer updated.
30
+
3
31
  ## 3.18.0
4
32
 
5
33
  ### Minor Changes
package/README.md CHANGED
@@ -117,6 +117,7 @@ The right approval method is a property of the **client the player is sitting in
117
117
  - [Passkeys (enroll, approve, link, recover)](#passkeys-enroll-approve-link-recover)
118
118
  - [Web games — approving on INVO's hosted page](#web-games--approving-on-invos-hosted-page)
119
119
  - [Consoles and TVs — approving without a browser (RFC 8628)](#consoles-and-tvs--approving-without-a-browser-rfc-8628)
120
+ - [Loyalty and rewards](#loyalty-and-rewards)
120
121
  - [Webhooks](#webhooks)
121
122
  - [Resilience & observability](#resilience--observability)
122
123
  - [Errors](#errors)
@@ -1134,9 +1135,10 @@ export const POST = createWebhookHandler({
1134
1135
  case "subscription.expired": // the retry budget ran out (or a Steam row was never authorised)
1135
1136
  await revokeAt(event.data.subscription_id, event.data.final_period_end); // NOT ended_at; null if nothing was ever paid
1136
1137
  break; // failure_code "steam_containment" is no longer sent (spending is not restricted by origin)
1137
- case "subscription.refunded": { // your revenue is reversed, plus the processor fee on a card refund
1138
- const r = event.data.refund; // older events carry no partner_total_reversed_usd
1139
- await recordReversal(event.data.subscription_id, r.partner_total_reversed_usd ?? r.partner_revenue_reversed_usd);
1138
+ case "subscription.refunded": { // your revenue is reversed, plus INVO's card fee on a card refund
1139
+ const r = event.data.refund; // older events carry no partner_debited_usd / partner_total_reversed_usd
1140
+ await recordReversal(event.data.subscription_id,
1141
+ r.partner_debited_usd ?? r.partner_total_reversed_usd ?? r.partner_revenue_reversed_usd);
1140
1142
  break; // event.data.subscription_canceled: a full refund cancels (subscription.canceled is sent with it)
1141
1143
  }
1142
1144
  case "subscription.refund_requested": // a refund over your daily limit is waiting for INVO; nothing moved
@@ -1156,7 +1158,7 @@ export const POST = createWebhookHandler({
1156
1158
  |---|---|
1157
1159
  | Has the member paid for the period they are in? | `subscription.renewed` for that period, or `paidThrough` on `get` |
1158
1160
  | Should I revoke access? | only on `subscription.expired` (at `final_period_end`) or `subscription.canceled` (at `access_until`); **never** on `payment_failed`, `past_due` or `authentication_required` |
1159
- | What did I earn? | `split.partner_revenue_usd` on `subscription.renewed`, minus `split.international_card_fee_usd` (the same figure as `split.pass_through_fees_usd`; subtract it once), minus `refund.partner_total_reversed_usd` (revenue reversed plus the card processor fee you bear) on any `subscription.refunded`; on refunds before 2026-09-17, which carry no such field, `refund.partner_revenue_reversed_usd` |
1161
+ | What did I earn? | `split.partner_revenue_usd` on `subscription.renewed`, minus `split.international_card_fee_usd` (the same figure as `split.pass_through_fees_usd`; subtract it once), minus `refund.partner_debited_usd` (revenue reversed plus INVO's card fee: the whole refunded price) on any `subscription.refunded`; on refunds before 2026-09-28, `refund.partner_total_reversed_usd`, and before 2026-09-17, which carry neither, `refund.partner_revenue_reversed_usd`; minus `partner_debited_usd` on a lost chargeback (`purchase.disputed`) |
1160
1162
  | Should I grant anything on a renewal's `purchase.completed`? | **No.** Every paid card renewal also sends `purchase.completed` (`data.metadata.source === "subscription_renewal"`) for the coins its charge minted, and the renewal spends them in the same step. Act on `subscription.renewed`. The two share the mint order id: `order_id` there is `mint_order_id` here |
1161
1163
  | Did a refund end the subscription? | `subscription_canceled` on `subscription.refunded`, and the `subscription.canceled` sent with it (`cancel_cause: "full_refund"`; the two are sent together and may arrive in any order) |
1162
1164
 
@@ -1204,7 +1206,8 @@ if (isRefundPendingApproval(r)) { // narrows r; status =
1204
1206
  // r.status === "refunded". r.isFullRefund, r.fundingShape ("card" for every card period since 2026-09-17),
1205
1207
  // r.cardRefundedUsd (card-only periods: equals the amount, partial included), r.balanceDeltaCoins,
1206
1208
  // r.partnerRevenueReversedUsd (your revenue reversed; INVO's fee is retained),
1207
- // r.processingFeeUsd (the card processor fee you bear), r.partnerTotalReversedUsd (the two together),
1209
+ // r.cardFeeChargedToPartnerUsd (INVO's card fee on the refunded part, charged to you),
1210
+ // r.partnerDebitedUsd (the two together: the whole refunded price), r.processingFeeUsd ("0.00" since 2026-09-28),
1208
1211
  // r.subscriptionCanceled (a full refund cancels the subscription), r.idempotentReplay on a repeat,
1209
1212
  // r.revenueShareAttribution?.netAttributedAmountUsd (the corrected figure to pay your recipient).
1210
1213
  }
@@ -1216,7 +1219,8 @@ for (const w of r.warnings ?? []) log(w.code); // "REASON_RECOMMENDED"
1216
1219
  **What else happens.**
1217
1220
 
1218
1221
  - **A full refund cancels the subscription** immediately (`subscriptionCanceled: true`, `subscriptionStatus: "canceled"`), and you receive `subscription.canceled` (`canceled_by: "partner"`, `cancel_cause: "full_refund"`) together with `subscription.refunded`; the two are sent together and may arrive in any order. A partial refund leaves it live. Before 2026-09-17 a full refund did not cancel.
1219
- - **You bear the card processor fee** on any refund that returns money to a card: `processingFeeUsd` (`processingFeeBasis` `actual` or `estimated`, `processingFeeBorneBy: "partner"`) is deducted from your revenue as its own line. `partnerTotalReversedUsd` is your revenue reversed plus that fee. A coin refund has no fee.
1222
+ - **You bear the whole refunded amount, INVO's card fee included** (since 2026-09-28), on any refund that returns money to a card, exactly as on a Platform Commerce card refund: your revenue is reversed and INVO's card fee on the refunded part is deducted from your revenue as its own line (`cardFeeChargedToPartnerUsd`). Across partial refunds of one charge it adds up to exactly INVO's fee on it. `partnerDebitedUsd` (and `partnerTotalReversedUsd`, the same value) is the two together, which equals the refunded price before tax. There is no separate payment processor fee: `processingFeeUsd` reads `"0.00"` (`processingFeeBasis: "none"`). The 1.5% international card fee is not returned. A coin refund has no fee. Example, Open tier, US card: a $9.99 period refunded in full reverses $9.24 of revenue and charges the $0.75 card fee, a $9.99 debit; a $100 period leaves you at -$4.80 (-$6.30 on a card issued outside the US). A receipt stored before 2026-09-28 (a replay) carries neither new field.
1223
+ - **A lost chargeback costs what a refund does.** Not covered by the chargeback guarantee, it reverses your share and charges INVO's card fee on every charge (`purchase.disputed`: `card_fee_charged_to_partner_usd`, `partner_debited_usd`). A fraud chargeback the guarantee covers costs you nothing; the Open-tier dispute fee pass-through is unchanged.
1220
1224
  - **INVO emails the member** when a refund executes (the amount, where it went, and whether the subscription ended). Your `reason` is not in that email.
1221
1225
  - **Refunds of periods charged through Steam are not supported yet**: `409 STEAM_REFUND_NOT_SUPPORTED` (`err.isSteamRefundNotSupported`); periods of a Steam subscription that the wallet covered entirely are refundable in coins.
1222
1226
 
@@ -2123,6 +2127,90 @@ const done = await server.completeDeviceApproval({
2123
2127
 
2124
2128
  ---
2125
2129
 
2130
+ ## Loyalty and rewards
2131
+
2132
+ Show a player their loyalty programs, how far they are through each step, and the rewards they
2133
+ unlocked. Programs are built in the INVO console; the SDK only reads them and redeems rewards.
2134
+ Currency steps (purchases, transfers, sends, item spends, subscriptions) count on their own.
2135
+
2136
+ **Browser (player token).** The token names the player; no email or id is sent.
2137
+
2138
+ ```ts
2139
+ import { InvoClient } from "@invonetwork/web-sdk";
2140
+
2141
+ const invo = new InvoClient({ token: playerToken, baseUrl: "https://invo.network" });
2142
+
2143
+ const { cards } = await invo.getMyRewards(); // GET /api/sdk/loyalty/me/card
2144
+ for (const card of cards) {
2145
+ console.log(card.title, `${card.stepsComplete} of ${card.stepsRequired} steps`);
2146
+ for (const step of card.steps) {
2147
+ const label =
2148
+ step.state === "complete" ? "Done"
2149
+ : step.state === "locked" ? "Locked"
2150
+ : step.progress ? `${step.progress.current} / ${step.progress.target}` // "3 / 5"
2151
+ : "Open";
2152
+ console.log(step.summary, label);
2153
+ }
2154
+ }
2155
+
2156
+ const { items } = await invo.getMyVault(); // every reward the player holds or held, newest first
2157
+ const redeemed = await invo.redeemReward(items[0].vaultEntryId);
2158
+ showToPlayer(redeemed.code); // the ONLY place a code appears: never log, cache or store it
2159
+
2160
+ const { url } = await invo.getRewardsPageLink(); // INVO's hosted "My rewards" page, short-lived
2161
+ window.open(url);
2162
+ ```
2163
+
2164
+ **Server (game secret).** Read the same cards for any of your players by email, for example to
2165
+ render loyalty UI server-side or send your own "2 matches to go" notification:
2166
+
2167
+ ```ts
2168
+ import { InvoServer } from "@invonetwork/web-sdk/server";
2169
+
2170
+ const server = new InvoServer({ gameSecret: process.env.INVO_GAME_SECRET!, baseUrl: "https://invo.network" });
2171
+ const { cards } = await server.getPlayerRewards("player@example.com");
2172
+ ```
2173
+
2174
+ `getPlayerRewards` takes the game's server secret only. Never ship the secret in a game client;
2175
+ the client uses `getMyRewards()` with the player token instead.
2176
+
2177
+ **Reading a card.**
2178
+
2179
+ - `step.state` is the authority on whether a step is done: `complete`, `open` (the player can
2180
+ work on it now) or `locked` (in an ordered program, a step after the first unfinished one).
2181
+ - `step.progress` is `{ current, target }` on a live card. `target` is the step's count (1
2182
+ unless the program set one), and `current` reaches `target` only when `state` is `complete`.
2183
+ It is `null` in a preview and when the number could not be read this time: render `state`
2184
+ alone then. Do not recompute progress yourself.
2185
+ - `card.status` is `available`, `in_progress`, `completed`, `expired` or `in_review`.
2186
+ - A card never carries a code. A redeemed reward shows `codeMasked` (for example `••••ABCD`).
2187
+ `redeemReward` returns the code; calling it again for a reward the player already redeemed
2188
+ shows the code once more while the card's `canRevealAgain` is true (`revealedAgain: true`).
2189
+ - Mint a fresh rewards page link each time the player opens the page; never share or store it.
2190
+ The page cannot be embedded in an iframe.
2191
+
2192
+ **Errors.**
2193
+
2194
+ | Call | Status | `err.code` | Predicate |
2195
+ |---|---|---|---|
2196
+ | `getPlayerRewards` | 400 | `INVALID_PLAYER_EMAIL` | `err.isInvalidPlayerEmail` |
2197
+ | `getPlayerRewards` | 401 | `INVALID_GAME_SECRET` (missing or wrong key, or a per-channel key: this read takes the server secret only) | |
2198
+ | `getPlayerRewards` | 404 | `PLAYER_NOT_FOUND` (no player with this email in this game) | `err.isPlayerNotFound` |
2199
+ | any | 429 | (do not match on a code) | treat any 429 as retryable after a pause; `err.retryAfter` (reads are retried automatically first) |
2200
+ | `redeemReward` | 409 | `already_redeemed` | `err.isRewardAlreadyRedeemed` |
2201
+ | `redeemReward` | 404 | `vault_entry_not_found` | `err.isRewardNotFound` |
2202
+ | `redeemReward` | 410 | `vault_entry_expired` | `err.isRewardExpired` |
2203
+ | `redeemReward` | 409 | `inventory_exhausted` (no units or codes left for this reward) | `err.isRewardUnavailable` |
2204
+ | `redeemReward` | 409 | `conflict` (the reward is reserved or revoked) | `err.isRewardUnavailable` |
2205
+ | `getPlayerRewards` | 409 | `NO_TENANT` (the game is not set up for loyalty) | |
2206
+ | any | 503 | temporarily unavailable | retry later |
2207
+ | any | 502 / 504 | the loyalty service could not be reached, or timed out | retry later |
2208
+
2209
+ A blank email, or a `vaultEntryId` that is not a reward's id, throws `INVALID_INPUT` (status 0)
2210
+ before the network. `redeemReward` is never auto-retried.
2211
+
2212
+ ---
2213
+
2126
2214
  ## Webhooks
2127
2215
 
2128
2216
  The synchronous responses are for UX; **reconcile and grant value off webhooks.** They're HMAC-signed; **dedupe on the `X-Invo-Idempotency-Key` header** (stable across retries/replays — *not* `X-Invo-Event-Id`, which changes per delivery).
@@ -2177,7 +2265,7 @@ export const POST = createWebhookHandler({
2177
2265
  |---|---|---|
2178
2266
  | `purchase.completed` | every currency-purchase rail, **and every paid card subscription renewal** | grant currency (payload: `transaction_id, order_id, player_email, identity_id, usd_amount, currency_amount, currency_name, new_balance, rail`, `metadata`). `metadata` echoes what you passed to `createCheckout`/`purchaseCurrency` (all rails); `order_id` is also on every webhook as a secondary reconciliation key (`getOrderDetails`). Card purchases also carry `partner_fee_usd` and `international_card_fee_usd`, the card fees charged to you (the player paid the listed price). **Skip it when `metadata.source` is `"subscription_renewal"`**: those coins are spent by the renewal itself; grant on `subscription.renewed`. |
2179
2267
  | `purchase.failed` | `platform` rail only | handle failures |
2180
- | `purchase.disputed` | `platform` rail, and `steam` chargebacks | handle disputes. A lost chargeback takes back up to the purchase's coins from the available balance, never below zero. On a lost Platform Commerce card sale or subscription charge dispute (`order_type`), `guarantee_covered: true` means INVO's chargeback guarantee covers it (a fraud chargeback): your share is not reversed or held and no dispute fee is passed to you. Otherwise a lost dispute costs you what a refund would: the card fee stays charged to you on a Platform Commerce sale, and a subscription charge carries `processing_fee_usd`, the processor fee a refund of that period charges (charges made under the 2026-09 pricing). Coin purchase disputes carry neither key: a lost one takes back the player's coins, not your share. A Steam chargeback carries the same keys as a lost card dispute with `payment_intent_id`, `charge_id` and `dispute_id` `null`, plus `rail: "steam"` and `steam_transid`. **If you revoke on `purchase.refunded`, handle this too:** a Steam chargeback no longer arrives as `purchase.refunded` |
2268
+ | `purchase.disputed` | `platform` rail, and `steam` chargebacks | handle disputes. A lost chargeback takes back up to the purchase's coins from the available balance, never below zero. On a lost Platform Commerce card sale or subscription charge dispute (`order_type`), `guarantee_covered: true` means INVO's chargeback guarantee covers it (a fraud chargeback): your share is not reversed or held and no dispute fee is passed to you. Otherwise a lost dispute costs you what a refund would: your share is reversed and INVO's card fee stays charged to you, on a Platform Commerce sale and on every subscription charge (`card_fee_charged_to_partner_usd`, and `partner_debited_usd` = share reversed plus that fee, since 2026-09-28). A subscription dispute also carries `processing_fee_usd`, which reads `"0.00"`. Coin purchase disputes carry none of these keys: a lost one takes back the player's coins, not your share. A Steam chargeback carries the same keys as a lost card dispute with `payment_intent_id`, `charge_id` and `dispute_id` `null`, plus `rail: "steam"` and `steam_transid`. **If you revoke on `purchase.refunded`, handle this too:** a Steam chargeback no longer arrives as `purchase.refunded` |
2181
2269
  | `purchase.refunded` | `game` / `steam` rails | handle refunds. Only coins the player still has from that purchase are taken back, never below zero. A Steam partial refund carries `fully_refunded: false` |
2182
2270
  | `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`) |
2183
2271
  | `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`) |
@@ -2187,7 +2275,7 @@ export const POST = createWebhookHandler({
2187
2275
  | `subscription.authentication_required` | a card issuer wants the cardholder to authenticate (card rail) | **not a failure** — relay `confirmation_url` before `expires_at` |
2188
2276
  | `subscription.canceled` | a cancel request (yours, or the member's from Steam: `canceled_by`), or a full refund (`cancel_cause: "full_refund"`) | revoke at `access_until` |
2189
2277
  | `subscription.expired` | the retry budget ran out, or a Steam row was never authorised (`steam_authorization_abandoned`). `steam_containment` is **no longer returned**: spending is not restricted by which rail bought the currency | **revoke at `final_period_end`** (not `ended_at`; `null` if nothing was ever paid) |
2190
- | `subscription.refunded` | a period refund | record the reversal (`refund.partner_total_reversed_usd` = revenue reversed plus the card processor fee you bear, `refund.partner_revenue_reversed_usd`, `refund.processing_fee_usd`, `is_full_refund`, `subscription_canceled`, `initiation`, `refund_request_id`, `revenue_share_attribution`) |
2278
+ | `subscription.refunded` | a period refund | record the reversal (`refund.partner_debited_usd` = revenue reversed plus INVO's card fee, the whole refunded price; `refund.card_fee_charged_to_partner_usd`; `refund.partner_total_reversed_usd`, the same value as `partner_debited_usd`; `refund.partner_revenue_reversed_usd`, `refund.processing_fee_usd` (`"0.00"` since 2026-09-28), `is_full_refund`, `subscription_canceled`, `initiation`, `refund_request_id`, `revenue_share_attribution`) |
2191
2279
  | `subscription.refund_requested` / `subscription.refund_approved` / `subscription.refund_rejected` | a refund over the game's daily self-serve limit became a request / INVO approved it (sent together with `subscription.refunded`, and `subscription.canceled` on a full refund, in any order) / INVO rejected it | track the request (`request_id, status, subscription_id, item_id, period_seq, client_request_id, amount_usd, reason, requested_at, daily_cap_usd, executed_today_usd, player_email, identity_id, metadata`; approved adds `decided_at, transaction_id`; rejected adds `decided_at, decision_reason`) |
2192
2280
  | `transfer.received` / `transfer.claim_expired` / `transfer.refunded` | sends & transfers | reconcile claim state — credited to the recipient (by any claim path, the hosted claim page included) / not collected within 24h / returned to the sender |
2193
2281
 
@@ -2340,6 +2428,7 @@ try {
2340
2428
  | `cards.list(playerEmail)` | `{ cards: SavedCard[], raw }` — unexpired cards, newest first; `card.id` is the `playerCardId` |
2341
2429
  | `sandbox.subscriptions.advanceClock(id, intervals?)` / `forceRenewal(id)` / `forceFailure(id, outcome?, { failureCode?, failureMessage? })` / `forceAuthChallenge(id, { failureMessage? })` | `SandboxClockResult` — `{ status, action, subscription, before?, after?, engineStats?, retryScheduleDays?, retriesRemaining?, authChallengesUsed?, …, raw }`; **sandbox only**, posts to `/subscriptions/<id>/...` relative to the sandbox base (not `/api`), needs `sandboxClockKey`; never auto-retried |
2342
2430
  | `getPlayerBalance({ playerEmail })` | `{ player, balances, summary, raw }` — **by email only** (no by-id route; use `InvoClient.getBalance()` client-side) |
2431
+ | `getPlayerRewards(playerEmail)` | `LoyaltyCardsResult`: `{ cardVersion, cards, raw }`, the player's loyalty cards in your game (the same cards as `InvoClient.getMyRewards()`); each step carries `state` and `progress` (`{ current, target }` or `null`); rewards carry `codeMasked` only. Server secret only. `isPlayerNotFound` / `isInvalidPlayerEmail`. See [Loyalty and rewards](#loyalty-and-rewards) |
2343
2432
  | `getInboundPending({ playerEmail? \| playerPhone? })` | `{ inboundPending, raw }` — live unclaimed inbound sends/transfers |
2344
2433
  | `getLinkedIdentities({ playerEmail? \| playerPhone? })` | `{ walletUserId, primaryEmail, primaryPhone, isMinor, emails, notFound, raw }` — **server-only** (returns PII) |
2345
2434
  | ~~`verifySmsTransfer(txnId, smsPin)`~~ / ~~`verifySmsSend(txnId, smsPin)`~~ | **Deprecated (3.1.0), removal at a future major.** `SmsVerifyResult` — completes the SMS-PIN path when `verificationMethod: "sms"`. Prefer passkey enrollment + `approveTransfer`/`approveSend`; keep this only for users who can't enroll. Still fully functional. |
@@ -2373,6 +2462,10 @@ Every method also accepts an optional final `{ signal }` (`AbortSignal`) for can
2373
2462
  | `getPendingCollect()` | `{ pending, raw }` — the player's own pending-to-collect list (player-token) |
2374
2463
  | `getDestinations({ direction? })` | `{ availableGames, sourceGameName, transferMode, … }` — where the player can send/transfer, metadata inline |
2375
2464
  | `getBalance()` | `{ gameId, gameName, balances, totalValue, currencyCount, hasFunds, raw }` — the player's balances for this game |
2465
+ | `getMyRewards()` | `LoyaltyCardsResult`: `{ cardVersion, cards, raw }`, the signed-in player's loyalty cards with per-step `state` and `progress` |
2466
+ | `getMyVault()` | `{ items, raw }`: every reward the player holds or held, newest first, codes masked |
2467
+ | `redeemReward(vaultEntryId)` | `{ vaultEntryId, rewardRef, state, redeemedAt, code, codeMasked, revealedAgain, revealUntil, raw }`: the only response with a code; never auto-retried |
2468
+ | `getRewardsPageLink()` | `{ url, expiresAt, raw }`: a short-lived link to INVO's hosted "My rewards" page |
2376
2469
  | `approveHosted({ transactionId, flow, platformOrigin?, onEnrollment?, renderPrompt?, popupBlocked?, popup?, signal? })` | `{ status: "approved" \| "denied" \| "expired" \| "closed" \| "blocked" \| "redirected", popupBlocked, message?, approval? }` — runs the whole RFC 8628 device-approval grant from the browser on INVO's hosted page (begin `channel:"popup"` → popup → poll → match-code prompt → confirm-enrollment → approve with the `device_code`, which the SDK holds and never exposes); `approval` is the `ApproveResult` / `ConfirmReceiptResult` of the flow's approve endpoint |
2377
2470
  | `checkout.getPurchaseStatus({ sessionId, sessionToken })` | `{ status, terminal, orderId, sessionId, coinsCredited, transactionId, newBalance, reasonCode, message, amountChargedUsd, listedUsd, currencyName, raw }`: what happened to a hosted-checkout purchase. Authenticated by the SESSION token, not the player token |
2378
2471
  | `checkout.waitForPurchase({ sessionId, sessionToken, intervalMs?, timeoutMs?, maxAttempts?, signal?, onUpdate? })` | the same result, polled until INVO's `terminal` is true (never re-derived from `status`); on the cap it returns the last result rather than throwing. Also available standalone: `new CheckoutClient({ baseUrl })` |
@@ -817,6 +817,7 @@ var InvoError = class _InvoError extends Error {
817
817
  * The same code comes back from `cards.beginSetup` and from `mintPlayerToken` for the
818
818
  * same reason; those two never create players, so create the member first (for
819
819
  * example with `createSetupSession` and a `playerName`, or a currency purchase).
820
+ * `getPlayerRewards` answers it when no player has that email in this game.
820
821
  */
821
822
  get isPlayerNotFound() {
822
823
  return this.code === "PLAYER_NOT_FOUND";
@@ -831,7 +832,8 @@ var InvoError = class _InvoError extends Error {
831
832
  }
832
833
  /**
833
834
  * True when `cards.createSetupSession` was refused because `playerEmail` was missing or
834
- * is not an email address (`INVALID_PLAYER_EMAIL`, 400).
835
+ * is not an email address (`INVALID_PLAYER_EMAIL`, 400). `getPlayerRewards` answers it
836
+ * for an email that is not an email address (a blank one never leaves the SDK).
835
837
  */
836
838
  get isInvalidPlayerEmail() {
837
839
  return this.code === "INVALID_PLAYER_EMAIL";
@@ -882,6 +884,26 @@ var InvoError = class _InvoError extends Error {
882
884
  get isIdentityCheckUnavailable() {
883
885
  return this.code === "IDENTITY_CHECK_UNAVAILABLE";
884
886
  }
887
+ // ---- Loyalty rewards (InvoClient.redeemReward) ----
888
+ /** True when a reward was already redeemed and its code can no longer be shown (`already_redeemed`, 409). */
889
+ get isRewardAlreadyRedeemed() {
890
+ return this.code === "already_redeemed";
891
+ }
892
+ /** True when the player has no such reward (`vault_entry_not_found`, 404). */
893
+ get isRewardNotFound() {
894
+ return this.code === "vault_entry_not_found";
895
+ }
896
+ /**
897
+ * True when the reward cannot be redeemed right now (409): `inventory_exhausted` (no units or
898
+ * codes are left for it) or `conflict` (the reward is reserved or revoked).
899
+ */
900
+ get isRewardUnavailable() {
901
+ return this.code === "inventory_exhausted" || this.code === "conflict";
902
+ }
903
+ /** True when the reward expired before it was redeemed (`vault_entry_expired`, 410). */
904
+ get isRewardExpired() {
905
+ return this.code === "vault_entry_expired";
906
+ }
885
907
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
886
908
  get retryAfter() {
887
909
  const v = this.bodyObject()["retry_after"];
@@ -1181,6 +1203,123 @@ function receiptFields(raw) {
1181
1203
  return typeof u === "string" && u !== "" ? { receiptNumber: n, receiptUrl: u } : { receiptNumber: n };
1182
1204
  }
1183
1205
 
1184
- export { Http, InvoError, assertSecureBaseUrl, creditFields, receiptFields, toDestinationsResult };
1185
- //# sourceMappingURL=chunk-YW2PYARQ.js.map
1186
- //# sourceMappingURL=chunk-YW2PYARQ.js.map
1206
+ // src/shared/loyalty.ts
1207
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
1208
+ var rows = (v) => Array.isArray(v) ? v.filter((r) => r && typeof r === "object" && !Array.isArray(r)) : [];
1209
+ var str = (v) => v === void 0 || v === null ? "" : String(v);
1210
+ var strOrNull = (v) => v === void 0 || v === null ? null : String(v);
1211
+ var numOrNull = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
1212
+ var int = (v, fallback = 0) => typeof v === "number" && Number.isFinite(v) ? v : fallback;
1213
+ var passThrough = (v) => v;
1214
+ function toLoyaltyStepProgress(value) {
1215
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1216
+ const v = value;
1217
+ const current = v["current"];
1218
+ const target = v["target"];
1219
+ if (!Number.isInteger(current) || !Number.isInteger(target)) return null;
1220
+ return { current, target };
1221
+ }
1222
+ function toStep(row) {
1223
+ return {
1224
+ stepId: strOrNull(row["step_id"]),
1225
+ index: int(row["index"]),
1226
+ action: str(row["action"]),
1227
+ label: str(row["label"]),
1228
+ summary: str(row["summary"]),
1229
+ windowHours: numOrNull(row["window_hours"]),
1230
+ state: str(row["state"]),
1231
+ progress: toLoyaltyStepProgress(row["progress"]),
1232
+ raw: row
1233
+ };
1234
+ }
1235
+ function toCardReward(row) {
1236
+ return {
1237
+ vaultEntryId: str(row["vault_entry_id"]),
1238
+ rewardId: str(row["reward_id"]),
1239
+ state: str(row["state"]),
1240
+ unlockedAt: str(row["unlocked_at"]),
1241
+ expiresAt: str(row["expires_at"]),
1242
+ redeemedAt: strOrNull(row["redeemed_at"]),
1243
+ codeMasked: strOrNull(row["code_masked"]),
1244
+ canRedeem: row["can_redeem"] === true,
1245
+ canRevealAgain: row["can_reveal_again"] === true,
1246
+ revealUntil: strOrNull(row["reveal_until"]),
1247
+ raw: row
1248
+ };
1249
+ }
1250
+ function toLoyaltyCard(row) {
1251
+ const brand = obj(row["brand"]);
1252
+ const reward = obj(row["reward"]);
1253
+ const steps = rows(row["steps"]).map(toStep);
1254
+ return {
1255
+ cardVersion: passThrough(row["card_version"]),
1256
+ mode: str(row["mode"]),
1257
+ programId: strOrNull(row["program_id"]),
1258
+ questId: strOrNull(row["quest_id"]),
1259
+ questVersion: numOrNull(row["quest_version"]),
1260
+ campaignId: strOrNull(row["campaign_id"]),
1261
+ title: str(row["title"]),
1262
+ description: str(row["description"]),
1263
+ brand: { name: strOrNull(brand["name"]), logoUrl: strOrNull(brand["logo_url"]) },
1264
+ artUrl: strOrNull(row["art_url"]),
1265
+ reward: { rewardId: strOrNull(reward["reward_id"]), name: strOrNull(reward["name"]) },
1266
+ orderMode: str(row["order_mode"]),
1267
+ status: str(row["status"]),
1268
+ startsAt: strOrNull(row["starts_at"]),
1269
+ endsAt: strOrNull(row["ends_at"]),
1270
+ completionHours: numOrNull(row["completion_hours"]),
1271
+ completionNote: strOrNull(row["completion_note"]),
1272
+ windowEndsAt: strOrNull(row["window_ends_at"]),
1273
+ completedAt: strOrNull(row["completed_at"]),
1274
+ stepsRequired: passThrough(row["steps_required"]),
1275
+ stepsComplete: passThrough(row["steps_complete"]),
1276
+ steps,
1277
+ rewards: rows(row["rewards"]).map(toCardReward),
1278
+ raw: row
1279
+ };
1280
+ }
1281
+ function toLoyaltyCardsResult(raw) {
1282
+ return {
1283
+ cardVersion: passThrough(raw["card_version"]),
1284
+ cards: rows(raw["cards"]).map(toLoyaltyCard),
1285
+ raw
1286
+ };
1287
+ }
1288
+ function toVaultEntry(row) {
1289
+ return {
1290
+ vaultEntryId: str(row["vault_entry_id"]),
1291
+ rewardRef: str(row["reward_ref"]),
1292
+ programId: str(row["program_id"]),
1293
+ questId: strOrNull(row["quest_id"]),
1294
+ units: str(row["units"]),
1295
+ state: str(row["state"]),
1296
+ unlockedAt: strOrNull(row["unlocked_at"]),
1297
+ expiresAt: strOrNull(row["expires_at"]),
1298
+ redeemedAt: strOrNull(row["redeemed_at"]),
1299
+ codeMasked: strOrNull(row["code_masked"]),
1300
+ raw: row
1301
+ };
1302
+ }
1303
+ function toLoyaltyVaultResult(raw) {
1304
+ return { items: rows(raw["items"]).map(toVaultEntry), raw };
1305
+ }
1306
+ function toRedeemRewardResult(raw, vaultEntryId) {
1307
+ return {
1308
+ vaultEntryId: str(raw["vault_entry_id"] ?? vaultEntryId),
1309
+ rewardRef: str(raw["reward_ref"]),
1310
+ state: str(raw["state"]),
1311
+ redeemedAt: strOrNull(raw["redeemed_at"]),
1312
+ code: strOrNull(raw["code"]),
1313
+ codeMasked: strOrNull(raw["code_masked"]),
1314
+ revealedAgain: raw["revealed_again"] === true,
1315
+ revealUntil: strOrNull(raw["reveal_until"]),
1316
+ raw
1317
+ };
1318
+ }
1319
+ function toRewardsPageLink(raw) {
1320
+ return { url: str(raw["url"]), expiresAt: str(raw["expires_at"]), raw };
1321
+ }
1322
+
1323
+ export { Http, InvoError, assertSecureBaseUrl, creditFields, receiptFields, toDestinationsResult, toLoyaltyCardsResult, toLoyaltyVaultResult, toRedeemRewardResult, toRewardsPageLink };
1324
+ //# sourceMappingURL=chunk-6IY4473A.js.map
1325
+ //# sourceMappingURL=chunk-6IY4473A.js.map