@invonetwork/web-sdk 3.21.0 → 3.22.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/server.js CHANGED
@@ -1,9 +1,9 @@
1
- import { InvoError, receiptFields, assertSecureBaseUrl, Http, creditFields, toLoyaltyCardsResult, toDestinationsResult } from './chunk-7L4O5Q7K.js';
2
- export { InvoError } from './chunk-7L4O5Q7K.js';
1
+ import { InvoError, assertSecureBaseUrl, Http, toRequestPhoneChangeResult, toPhoneChangeRequest, receiptFields, creditFields, toLoyaltyCardsResult, toDestinationsResult } from './chunk-BOD4WOWO.js';
2
+ export { InvoError } from './chunk-BOD4WOWO.js';
3
3
  import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
5
  // src/version.ts
6
- var SDK_VERSION = "3.21.0";
6
+ var SDK_VERSION = "3.22.0";
7
7
 
8
8
  // src/shared/types.ts
9
9
  function isRefundPendingApproval(r) {
@@ -385,9 +385,65 @@ function toTransactionStatus(raw) {
385
385
  orderId: raw["order_id"],
386
386
  toPhone: raw["to_phone"],
387
387
  toIdentityId: raw["to_identity_id"] ?? null,
388
+ ...typeof raw["expiry_reason"] === "string" && raw["expiry_reason"] ? { expiryReason: raw["expiry_reason"] } : {},
388
389
  raw
389
390
  };
390
391
  }
392
+ function assertPageLimit(limit) {
393
+ if (limit === void 0) return;
394
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) {
395
+ throw invalidInput("limit", limit, "must be a positive integer (INVO caps it at 100)");
396
+ }
397
+ }
398
+ function assertCursor(cursor) {
399
+ if (cursor === void 0) return;
400
+ if (typeof cursor !== "string" || !cursor.trim()) {
401
+ throw invalidInput("cursor", cursor, "must be the previous page's nextCursor");
402
+ }
403
+ }
404
+ function strOrNull(v) {
405
+ return v == null ? null : String(v);
406
+ }
407
+ function toPlayerActivityEntry(raw) {
408
+ const ccy = raw["currency"] && typeof raw["currency"] === "object" ? raw["currency"] : {};
409
+ const cg = raw["counterparty_game"];
410
+ const cgo = cg && typeof cg === "object" ? cg : null;
411
+ return {
412
+ id: String(raw["id"] ?? ""),
413
+ type: String(raw["type"] ?? ""),
414
+ direction: String(raw["direction"] ?? ""),
415
+ amount: strOrNull(raw["amount"]),
416
+ amountUnit: String(raw["amount_unit"] ?? "currency"),
417
+ currency: {
418
+ currencyId: ccy["currency_id"] ?? null,
419
+ currencyName: strOrNull(ccy["currency_name"])
420
+ },
421
+ status: String(raw["status"] ?? ""),
422
+ statusDetail: strOrNull(raw["status_detail"]),
423
+ expiryReason: strOrNull(raw["expiry_reason"]) || null,
424
+ counterpartyGame: cgo ? { gameId: String(cgo["game_id"] ?? ""), gameName: strOrNull(cgo["game_name"]) } : null,
425
+ createdAt: strOrNull(raw["created_at"]),
426
+ completedAt: strOrNull(raw["completed_at"]),
427
+ orderId: strOrNull(raw["order_id"]),
428
+ raw
429
+ };
430
+ }
431
+ function toPlatformOrderStatus(raw, fallbackOrderId) {
432
+ return {
433
+ orderId: raw["order_id"] ?? fallbackOrderId ?? "",
434
+ status: String(raw["status"] ?? ""),
435
+ gameCurrencyAmount: raw["game_currency_amount"] ?? null,
436
+ usdAmount: raw["usd_amount"] ?? null,
437
+ paymentMethod: raw["payment_method"],
438
+ createdAt: raw["created_at"],
439
+ ...receiptFields(raw),
440
+ raw
441
+ };
442
+ }
443
+ function nextCursorOf(raw) {
444
+ const c = raw["next_cursor"];
445
+ return typeof c === "string" && c ? c : null;
446
+ }
391
447
  function toGuardianApprovalStatus(raw) {
392
448
  const approval = raw["approval"] ?? {};
393
449
  return {
@@ -644,7 +700,9 @@ var PlatformCommerceServer = class {
644
700
  throw new InvoError({
645
701
  message: `Card purchases must be at least $${CARD_MIN_USD.toFixed(2)}.`,
646
702
  code: "BELOW_STRIPE_MINIMUM",
647
- status: 0
703
+ publicCode: "BELOW_CARD_MINIMUM",
704
+ status: 0,
705
+ body: { min_usd: CARD_MIN_USD.toFixed(2) }
648
706
  });
649
707
  }
650
708
  }
@@ -709,17 +767,71 @@ var PlatformCommerceServer = class {
709
767
  this.auth,
710
768
  { signal: opts?.signal }
711
769
  );
770
+ return toPlatformOrderStatus(raw, orderId);
771
+ }
772
+ /**
773
+ * One player's Platform Commerce purchases in your app, newest first, one page at a time
774
+ * (`GET /api/platform-commerce/purchase-history`). Each entry carries exactly the fields
775
+ * `getStatus` returns for that order (including `receiptNumber` / `receiptUrl` on a
776
+ * Merchant of Record card sale once issued). Pass `nextCursor` back as `cursor` for the
777
+ * next page; it is `null` on the last one. `iteratePurchaseHistory` walks every page.
778
+ *
779
+ * Refusals (`InvoError`; this route reports its code in `error_code`, surfaced as
780
+ * `err.code`): a blank `playerEmail` or a bad `limit` / `cursor` throws `INVALID_INPUT`
781
+ * before the network; `400 INVALID_INPUT`, `400 INVALID_CURSOR` (a cursor from another
782
+ * player), `404 PLAYER_NOT_FOUND` (`err.isPlayerNotFound`), `403` for a non-platform
783
+ * tenant (`err.isNotPlatformTenant`), `429` (back off; `err.retryAfter`). A GET, so
784
+ * transient failures are retried automatically.
785
+ */
786
+ async getPurchaseHistory(query, opts) {
787
+ if (typeof query?.playerEmail !== "string" || !query.playerEmail.trim()) {
788
+ throw invalidInput("playerEmail", query?.playerEmail, "is required");
789
+ }
790
+ assertPageLimit(query.limit);
791
+ assertCursor(query.cursor);
792
+ const q = new URLSearchParams();
793
+ q.set("player_email", query.playerEmail.trim());
794
+ if (query.limit !== void 0) q.set("limit", String(query.limit));
795
+ if (query.cursor !== void 0) q.set("cursor", query.cursor);
796
+ const raw = await this.http.get(
797
+ `/api/platform-commerce/purchase-history?${q.toString()}`,
798
+ this.auth,
799
+ { signal: opts?.signal }
800
+ );
801
+ const purchases = Array.isArray(raw["purchases"]) ? raw["purchases"].map((r) => toPlatformOrderStatus(r)) : [];
802
+ const nextCursor = nextCursorOf(raw);
712
803
  return {
713
- orderId: raw["order_id"] ?? orderId,
714
- status: String(raw["status"] ?? ""),
715
- gameCurrencyAmount: raw["game_currency_amount"] ?? null,
716
- usdAmount: raw["usd_amount"] ?? null,
717
- paymentMethod: raw["payment_method"],
718
- createdAt: raw["created_at"],
719
- ...receiptFields(raw),
804
+ playerEmail: String(raw["player_email"] ?? query.playerEmail.trim()),
805
+ gameId: String(raw["game_id"] ?? ""),
806
+ purchases,
807
+ limit: typeof raw["limit"] === "number" ? raw["limit"] : purchases.length,
808
+ hasMore: raw["has_more"] === true && nextCursor !== null,
809
+ nextCursor,
720
810
  raw
721
811
  };
722
812
  }
813
+ /**
814
+ * Async iterator over ALL of a player's Platform Commerce purchases, newest first: pages
815
+ * through `getPurchaseHistory` by `nextCursor`, yielding one order at a time.
816
+ *
817
+ * ```ts
818
+ * for await (const order of invo.platformCommerce.iteratePurchaseHistory({ playerEmail })) { … }
819
+ * ```
820
+ */
821
+ async *iteratePurchaseHistory(query, opts) {
822
+ let cursor;
823
+ const seen = /* @__PURE__ */ new Set();
824
+ for (; ; ) {
825
+ const page = await this.getPurchaseHistory(
826
+ { playerEmail: query.playerEmail, limit: query.pageSize, cursor },
827
+ opts
828
+ );
829
+ for (const row of page.purchases) yield row;
830
+ if (!page.hasMore || page.nextCursor === null || seen.has(page.nextCursor)) return;
831
+ seen.add(page.nextCursor);
832
+ cursor = page.nextCursor;
833
+ }
834
+ }
723
835
  /**
724
836
  * Refund a completed purchase. Provide EXACTLY ONE of `orderId` or `clientRequestId`.
725
837
  * INVO retains its fee — the customer is made whole (balance re-credit or card refund)
@@ -1958,9 +2070,11 @@ var InvoServer = class {
1958
2070
  * of date).
1959
2071
  *
1960
2072
  * Refusals: 409 `err.isPhoneChangeRequiresVerification` (the player has secured this
1961
- * account, so the change needs the player's own confirmation; contact INVO support
1962
- * meanwhile), 409 `err.isPhoneShareRefused` (the number belongs to another email),
1963
- * 404 `err.isPlayerNotFound`, 400 `INVALID_INPUT` / `INVALID_PHONE`, 429
2073
+ * account, so the change needs the player's own confirmation: call `requestPhoneChange`;
2074
+ * `err.changeRequestEndpoint` names the route), 409 `err.isPhoneShareRefused` (the
2075
+ * number belongs to another email), 409 `err.isPendingTransfersToOldPhone` /
2076
+ * `err.isPendingTransfersToNewPhone` (transfers to the current or the new number are still
2077
+ * waiting to be collected), 404 `err.isPlayerNotFound`, 400 `INVALID_INPUT` / `INVALID_PHONE`, 429
1964
2078
  * (`err.retryAfter`), 503 (could not be checked right now; try again shortly).
1965
2079
  *
1966
2080
  * Never auto-retried: a retry after a change that landed would answer `"unchanged"` and
@@ -1986,6 +2100,61 @@ var InvoServer = class {
1986
2100
  raw
1987
2101
  };
1988
2102
  }
2103
+ /**
2104
+ * Ask the player to confirm a new phone number
2105
+ * (`POST /api/sdk/players/phone/change-requests`, HTTP 202). Use it when `updatePlayerPhone`
2106
+ * answers 409 `err.isPhoneChangeRequiresVerification`.
2107
+ *
2108
+ * Nothing about the player changes here. INVO emails the player a code and a link to a
2109
+ * page on INVO's site, and the player confirms there (plus their passkey on that page, or
2110
+ * an approval on their enrolled device, when they have one: see `confirmation`). Your game
2111
+ * never collects the code and never receives the link: do not ask the player for it.
2112
+ * Follow up with `getPhoneChange`, or wait for the `player.phone_changed` webhook.
2113
+ *
2114
+ * Refusals carry `err.code`, for example 409 `PHONE_SAME`, `PHONE_IN_USE_BY_ANOTHER_PLAYER`,
2115
+ * `PENDING_TRANSFERS_TO_NEW_PHONE` (`err.isPendingTransfersToNewPhone`),
2116
+ * `PENDING_TRANSFERS_TO_OLD_PHONE` (`err.isPendingTransfersToOldPhone`),
2117
+ * `CHANGE_REQUEST_IN_PROGRESS` (`err.isChangeRequestInProgress`), `PHONE_CHANGE_LOCKED`
2118
+ * (`err.isPhoneChangeLocked`), `PHONE_CHANGE_RECOVERY_COOLDOWN`
2119
+ * (`err.isPhoneChangeRecoveryCooldown`), `STEP_UP_UNAVAILABLE`, `WALLET_SECURED`,
2120
+ * `PHONE_NOT_SET`;
2121
+ * 429 `err.isTooManyChangeRequests`; 404 `err.isPlayerNotFound`; 503
2122
+ * `err.isPhoneChangeUnavailable`.
2123
+ *
2124
+ * Never auto-retried: a new request replaces your earlier pending one and sends the player
2125
+ * another email.
2126
+ */
2127
+ async requestPhoneChange(input, opts) {
2128
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2129
+ throw invalidInput("playerEmail", input.playerEmail, "is required");
2130
+ }
2131
+ assertE164(input.newPhone, "newPhone");
2132
+ const raw = await this.http.post(
2133
+ "/api/sdk/players/phone/change-requests",
2134
+ { player_email: input.playerEmail, new_phone: input.newPhone },
2135
+ this.auth,
2136
+ { signal: opts?.signal }
2137
+ );
2138
+ return toRequestPhoneChangeResult(raw);
2139
+ }
2140
+ /**
2141
+ * Read a change request your game created
2142
+ * (`GET /api/sdk/players/phone/change-requests/{changeRequestId}`). `status` is `pending`,
2143
+ * `confirmed`, `expired`, `cancelled`, `refused` or `denied`. A request another game
2144
+ * created, or an unknown id, is 404 `err.isChangeRequestNotFound`. Poll sparingly, or wait
2145
+ * for the `player.phone_changed` webhook.
2146
+ */
2147
+ async getPhoneChange(changeRequestId, opts) {
2148
+ if (typeof changeRequestId !== "string" || !changeRequestId.trim()) {
2149
+ throw invalidInput("changeRequestId", changeRequestId, "is required");
2150
+ }
2151
+ const raw = await this.http.get(
2152
+ `/api/sdk/players/phone/change-requests/${encodeURIComponent(changeRequestId)}`,
2153
+ this.auth,
2154
+ { signal: opts?.signal }
2155
+ );
2156
+ return toPhoneChangeRequest(raw);
2157
+ }
1989
2158
  /**
1990
2159
  * Initiate a cross-game currency SEND. Inspect result.verificationMethod.
1991
2160
  *
@@ -2081,7 +2250,7 @@ var InvoServer = class {
2081
2250
  * - rail "game": returns status "pending_payment" + paymentUrl (redirect the browser).
2082
2251
  * - rail "steam": NOT a browser flow — the backend returns WRONG_RAIL_ENDPOINT.
2083
2252
  *
2084
- * INVO's card fee (4.5% + $0.30 on Open, 5.5% + $0.50 on Merchant of Record, plus 1.5% of
2253
+ * INVO's card fee (3.5% + $0.30 on Open, 5.5% + $0.50 on Merchant of Record, plus 1.5% of
2085
2254
  * the listed price (before tax) on a card issued outside the US) is charged to you, the partner. The player
2086
2255
  * pays the listed price (plus any tax) and receives the listed coins. Card purchases only;
2087
2256
  * purchases through a third-party storefront or payment rail are unaffected. Two shapes,
@@ -2170,9 +2339,9 @@ var InvoServer = class {
2170
2339
  *
2171
2340
  * The player pays the listed price plus any tax (when you pass `country`) and receives the
2172
2341
  * listed coins: `totalUsd` carries no card fee, and `processingFeeUsd` is `"0.00"`. INVO's
2173
- * card fee (4.5% + $0.30 on Open, 5.5% + $0.50 on Merchant of Record) is charged to you;
2342
+ * card fee (3.5% + $0.30 on Open, 5.5% + $0.50 on Merchant of Record) is charged to you;
2174
2343
  * `partnerFeeUsd` carries it when INVO sends it. $10.00 quotes a $10.00 total, 100.00 coins
2175
- * at the default 10 per USD, and a $0.75 partner fee on Open. Show the player `totalUsd`,
2344
+ * at the default 10 per USD, and a $0.65 partner fee on Open. Show the player `totalUsd`,
2176
2345
  * then send the same figure back as `acknowledgedTotalUsd` on {@link purchaseCurrency}; the
2177
2346
  * card is never charged more than that. `ifUnacknowledged` shows the purchase without the
2178
2347
  * acknowledgement (the card charged exactly `usdAmount`), or `null` when INVO sends none.
@@ -2523,6 +2692,86 @@ var InvoServer = class {
2523
2692
  if (Number.isFinite(total) && yielded >= total) return;
2524
2693
  }
2525
2694
  }
2695
+ /**
2696
+ * One merged, newest-first list of a player's money activity in your game, one page at a
2697
+ * time (`GET /api/sdk/players/activity`): currency purchases, item purchases, Platform
2698
+ * Commerce purchases, sends and transfers, in both directions. Only rows where your game
2699
+ * is a party through this player are listed; the other side of a cross-game send or
2700
+ * transfer is named by game only (`counterpartyGame`).
2701
+ *
2702
+ * An inbound (`direction: "in"`) send or transfer is listed as soon as it names this
2703
+ * player, in ANY status (awaiting collection, completed, expired, refunded): read `status`
2704
+ * and `statusDetail` before treating it as credited. `direction` is `"in"` / `"out"` /
2705
+ * `"self"`, not the `"incoming"` / `"outgoing"` of the per-type history reads.
2706
+ *
2707
+ * Pass `nextCursor` back as `cursor` (with the same `types`) for the next page; it is
2708
+ * `null` on the last one. `iteratePlayerActivity` walks every page.
2709
+ *
2710
+ * Refusals (`InvoError`): a blank `playerEmail` or a bad `limit` / `cursor` / `types`
2711
+ * throws `INVALID_INPUT` before the network; `400 INVALID_INPUT` (for example an unknown
2712
+ * kind in `types`), `400 INVALID_CURSOR` (a cursor from another player or other `types`),
2713
+ * `401 INVALID_GAME_SECRET`, `404 PLAYER_NOT_FOUND` (`err.isPlayerNotFound`),
2714
+ * `500 PLAYER_ACTIVITY_FAILED` (retry later), `429` (back off; `err.retryAfter`). A GET, so
2715
+ * transient failures are retried automatically.
2716
+ */
2717
+ async getPlayerActivity(query, opts) {
2718
+ if (typeof query?.playerEmail !== "string" || !query.playerEmail.trim()) {
2719
+ throw invalidInput("playerEmail", query?.playerEmail, "is required");
2720
+ }
2721
+ assertPageLimit(query.limit);
2722
+ assertCursor(query.cursor);
2723
+ if (query.types !== void 0) {
2724
+ if (!Array.isArray(query.types) || query.types.some((t) => typeof t !== "string" || !t.trim() || t.includes(","))) {
2725
+ throw invalidInput("types", query.types, "must be an array of activity kinds");
2726
+ }
2727
+ }
2728
+ const q = new URLSearchParams();
2729
+ q.set("player_email", query.playerEmail.trim());
2730
+ if (query.limit !== void 0) q.set("limit", String(query.limit));
2731
+ if (query.cursor !== void 0) q.set("cursor", query.cursor);
2732
+ if (query.types && query.types.length > 0) {
2733
+ q.set("types", query.types.map((t) => t.trim()).join(","));
2734
+ }
2735
+ const raw = await this.http.get(
2736
+ `/api/sdk/players/activity?${q.toString()}`,
2737
+ this.auth,
2738
+ { signal: opts?.signal }
2739
+ );
2740
+ const activity = Array.isArray(raw["activity"]) ? raw["activity"].map(toPlayerActivityEntry) : [];
2741
+ const nextCursor = nextCursorOf(raw);
2742
+ return {
2743
+ playerEmail: String(raw["player_email"] ?? query.playerEmail.trim()),
2744
+ gameId: String(raw["game_id"] ?? ""),
2745
+ types: Array.isArray(raw["types"]) ? raw["types"].map(String) : [],
2746
+ activity,
2747
+ limit: typeof raw["limit"] === "number" ? raw["limit"] : activity.length,
2748
+ hasMore: raw["has_more"] === true && nextCursor !== null,
2749
+ nextCursor,
2750
+ raw
2751
+ };
2752
+ }
2753
+ /**
2754
+ * Async iterator over a player's ENTIRE activity, newest first: pages through
2755
+ * `getPlayerActivity` by `nextCursor`, yielding one row at a time.
2756
+ *
2757
+ * ```ts
2758
+ * for await (const row of invo.iteratePlayerActivity({ playerEmail, types: ["send", "transfer"] })) { … }
2759
+ * ```
2760
+ */
2761
+ async *iteratePlayerActivity(query, opts) {
2762
+ let cursor;
2763
+ const seen = /* @__PURE__ */ new Set();
2764
+ for (; ; ) {
2765
+ const page = await this.getPlayerActivity(
2766
+ { playerEmail: query.playerEmail, types: query.types, limit: query.pageSize, cursor },
2767
+ opts
2768
+ );
2769
+ for (const row of page.activity) yield row;
2770
+ if (!page.hasMore || page.nextCursor === null || seen.has(page.nextCursor)) return;
2771
+ seen.add(page.nextCursor);
2772
+ cursor = page.nextCursor;
2773
+ }
2774
+ }
2526
2775
  /**
2527
2776
  * Read a player's currency balances by email (server-side, game-secret).
2528
2777
  *