@invonetwork/web-sdk 3.29.1 → 3.30.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +1442 -1397
  2. package/README.md +2954 -2923
  3. package/dist/chunk-3ECVREIM.js +6 -0
  4. package/dist/chunk-7O5JT3LK.js +1590 -0
  5. package/dist/{chunk-VP3OK4J4.js → chunk-TCT2QSVB.js} +515 -3
  6. package/dist/{chunk-YONO4JE5.js → chunk-V2RQYQQD.js} +44 -5
  7. package/dist/game-server.cjs +387 -42
  8. package/dist/game-server.d.cts +42 -6
  9. package/dist/game-server.d.ts +42 -6
  10. package/dist/game-server.js +286 -8
  11. package/dist/game.cjs +2677 -9
  12. package/dist/game.d.cts +78 -4
  13. package/dist/game.d.ts +78 -4
  14. package/dist/game.js +558 -3
  15. package/dist/hosted-approval-DcY4U2RN.d.cts +96 -0
  16. package/dist/hosted-approval-DiKmtjEh.d.ts +96 -0
  17. package/dist/index.d.cts +7 -96
  18. package/dist/index.d.ts +7 -96
  19. package/dist/index.js +2 -1635
  20. package/dist/loyalty-events-CmDw2ZoR.d.cts +40 -0
  21. package/dist/loyalty-events-CmDw2ZoR.d.ts +40 -0
  22. package/dist/{server-Bxo_wgHx.d.cts → server-BAOn3KH3.d.cts} +28 -2
  23. package/dist/{server-BYY6tM6X.d.ts → server-DHmQU1eN.d.ts} +28 -2
  24. package/dist/server.cjs +106 -40
  25. package/dist/server.d.cts +4 -3
  26. package/dist/server.d.ts +4 -3
  27. package/dist/server.js +3 -4
  28. package/dist/{types-_lIm74kd.d.cts → types-BTbZicgj.d.cts} +1 -40
  29. package/dist/{types-_lIm74kd.d.ts → types-BTbZicgj.d.ts} +1 -40
  30. package/dist/{types-CLyJDuXd.d.cts → types-jUxfYjiD.d.cts} +64 -1
  31. package/dist/{types-CLyJDuXd.d.ts → types-jUxfYjiD.d.ts} +64 -1
  32. package/dist/{version-DOaYbHu7.d.cts → version-CR7XECyP.d.cts} +1 -1
  33. package/dist/{version-DOaYbHu7.d.ts → version-CR7XECyP.d.ts} +1 -1
  34. package/package.json +91 -91
  35. package/dist/chunk-6CN236QH.js +0 -473
  36. package/dist/chunk-VOGZZ6QS.js +0 -6
@@ -1478,10 +1478,53 @@ function toDestinationsResult(raw, direction) {
1478
1478
  };
1479
1479
  }
1480
1480
 
1481
+ // src/shared/receipt-fields.ts
1482
+ function creditFields(raw) {
1483
+ const c = raw["credited"];
1484
+ if (c === true) return { credited: true };
1485
+ if (c === false) {
1486
+ const r = raw["reason_code"];
1487
+ return { credited: false, reasonCode: r == null ? null : String(r) };
1488
+ }
1489
+ return {};
1490
+ }
1491
+ function receiptFields(raw) {
1492
+ const n = raw["receipt_number"];
1493
+ if (typeof n !== "string" || n === "") return {};
1494
+ const u = raw["receipt_url"];
1495
+ return typeof u === "string" && u !== "" ? { receiptNumber: n, receiptUrl: u } : { receiptNumber: n };
1496
+ }
1497
+
1498
+ // src/shared/purchase-status.ts
1499
+ function str(v) {
1500
+ return typeof v === "string" ? v : v === null || v === void 0 ? null : String(v);
1501
+ }
1502
+ function toPurchaseStatusResult(raw, sessionId) {
1503
+ return {
1504
+ status: String(raw["status"] ?? ""),
1505
+ // INVO SAYS, AND ONLY AN EXPLICIT `true` SAYS IT. A missing or malformed field reads
1506
+ // false, which keeps a poll running; the alternative, guessing terminality from
1507
+ // `status`, is how an old SDK declares a future status finished.
1508
+ terminal: raw["terminal"] === true,
1509
+ orderId: str(raw["order_id"]),
1510
+ sessionId: String(raw["session_id"] ?? sessionId),
1511
+ coinsCredited: str(raw["coins_credited"]),
1512
+ transactionId: str(raw["transaction_id"]),
1513
+ newBalance: str(raw["new_balance"]),
1514
+ reasonCode: str(raw["reason_code"]),
1515
+ message: str(raw["message"]),
1516
+ amountChargedUsd: str(raw["amount_charged_usd"]),
1517
+ listedUsd: str(raw["listed_usd"]),
1518
+ currencyName: str(raw["currency_name"]),
1519
+ ...receiptFields(raw),
1520
+ raw
1521
+ };
1522
+ }
1523
+
1481
1524
  // src/shared/loyalty.ts
1482
1525
  var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
1483
1526
  var rows = (v) => Array.isArray(v) ? v.filter((r) => r && typeof r === "object" && !Array.isArray(r)) : [];
1484
- var str = (v) => v === void 0 || v === null ? "" : String(v);
1527
+ var str2 = (v) => v === void 0 || v === null ? "" : String(v);
1485
1528
  var strOrNull = (v) => v === void 0 || v === null ? null : String(v);
1486
1529
  var numOrNull = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
1487
1530
  var int = (v, fallback = 0) => typeof v === "number" && Number.isFinite(v) ? v : fallback;
@@ -1498,22 +1541,22 @@ function toStep(row) {
1498
1541
  return {
1499
1542
  stepId: strOrNull(row["step_id"]),
1500
1543
  index: int(row["index"]),
1501
- action: str(row["action"]),
1502
- label: str(row["label"]),
1503
- summary: str(row["summary"]),
1544
+ action: str2(row["action"]),
1545
+ label: str2(row["label"]),
1546
+ summary: str2(row["summary"]),
1504
1547
  windowHours: numOrNull(row["window_hours"]),
1505
- state: str(row["state"]),
1548
+ state: str2(row["state"]),
1506
1549
  progress: toLoyaltyStepProgress(row["progress"]),
1507
1550
  raw: row
1508
1551
  };
1509
1552
  }
1510
1553
  function toCardReward(row) {
1511
1554
  return {
1512
- vaultEntryId: str(row["vault_entry_id"]),
1513
- rewardId: str(row["reward_id"]),
1514
- state: str(row["state"]),
1515
- unlockedAt: str(row["unlocked_at"]),
1516
- expiresAt: str(row["expires_at"]),
1555
+ vaultEntryId: str2(row["vault_entry_id"]),
1556
+ rewardId: str2(row["reward_id"]),
1557
+ state: str2(row["state"]),
1558
+ unlockedAt: str2(row["unlocked_at"]),
1559
+ expiresAt: str2(row["expires_at"]),
1517
1560
  redeemedAt: strOrNull(row["redeemed_at"]),
1518
1561
  codeMasked: strOrNull(row["code_masked"]),
1519
1562
  canRedeem: row["can_redeem"] === true,
@@ -1528,18 +1571,18 @@ function toLoyaltyCard(row) {
1528
1571
  const steps = rows(row["steps"]).map(toStep);
1529
1572
  return {
1530
1573
  cardVersion: passThrough(row["card_version"]),
1531
- mode: str(row["mode"]),
1574
+ mode: str2(row["mode"]),
1532
1575
  programId: strOrNull(row["program_id"]),
1533
1576
  questId: strOrNull(row["quest_id"]),
1534
1577
  questVersion: numOrNull(row["quest_version"]),
1535
1578
  campaignId: strOrNull(row["campaign_id"]),
1536
- title: str(row["title"]),
1537
- description: str(row["description"]),
1579
+ title: str2(row["title"]),
1580
+ description: str2(row["description"]),
1538
1581
  brand: { name: strOrNull(brand["name"]), logoUrl: strOrNull(brand["logo_url"]) },
1539
1582
  artUrl: strOrNull(row["art_url"]),
1540
1583
  reward: { rewardId: strOrNull(reward["reward_id"]), name: strOrNull(reward["name"]) },
1541
- orderMode: str(row["order_mode"]),
1542
- status: str(row["status"]),
1584
+ orderMode: str2(row["order_mode"]),
1585
+ status: str2(row["status"]),
1543
1586
  startsAt: strOrNull(row["starts_at"]),
1544
1587
  endsAt: strOrNull(row["ends_at"]),
1545
1588
  completionHours: numOrNull(row["completion_hours"]),
@@ -1626,23 +1669,6 @@ function toReportGameEventResult(raw, eventId) {
1626
1669
  };
1627
1670
  }
1628
1671
 
1629
- // src/shared/receipt-fields.ts
1630
- function creditFields(raw) {
1631
- const c = raw["credited"];
1632
- if (c === true) return { credited: true };
1633
- if (c === false) {
1634
- const r = raw["reason_code"];
1635
- return { credited: false, reasonCode: r == null ? null : String(r) };
1636
- }
1637
- return {};
1638
- }
1639
- function receiptFields(raw) {
1640
- const n = raw["receipt_number"];
1641
- if (typeof n !== "string" || n === "") return {};
1642
- const u = raw["receipt_url"];
1643
- return typeof u === "string" && u !== "" ? { receiptNumber: n, receiptUrl: u } : { receiptNumber: n };
1644
- }
1645
-
1646
1672
  // src/shared/phone-change.ts
1647
1673
  function requireField(value, field, raw) {
1648
1674
  const s = value == null ? "" : String(value);
@@ -1656,16 +1682,16 @@ function requireField(value, field, raw) {
1656
1682
  }
1657
1683
  return s;
1658
1684
  }
1659
- var str2 = (v) => v == null ? "" : String(v);
1685
+ var str3 = (v) => v == null ? "" : String(v);
1660
1686
  var strOrNull2 = (v) => typeof v === "string" ? v : v == null ? null : String(v);
1661
1687
  function toRequestPhoneChangeResult(raw) {
1662
1688
  return {
1663
1689
  changeRequestId: requireField(raw["change_request_id"], "change_request_id", raw),
1664
1690
  status: requireField(raw["status"], "status", raw),
1665
- expiresAt: str2(raw["expires_at"]),
1666
- delivery: str2(raw["delivery"]),
1667
- confirmation: str2(raw["confirmation"]),
1668
- message: str2(raw["message"]),
1691
+ expiresAt: str3(raw["expires_at"]),
1692
+ delivery: str3(raw["delivery"]),
1693
+ confirmation: str3(raw["confirmation"]),
1694
+ message: str3(raw["message"]),
1669
1695
  raw
1670
1696
  };
1671
1697
  }
@@ -1673,8 +1699,8 @@ function toPhoneChangeRequest(raw) {
1673
1699
  return {
1674
1700
  changeRequestId: requireField(raw["change_request_id"], "change_request_id", raw),
1675
1701
  status: requireField(raw["status"], "status", raw),
1676
- confirmation: str2(raw["confirmation"]),
1677
- delivery: str2(raw["delivery"]),
1702
+ confirmation: str3(raw["confirmation"]),
1703
+ delivery: str3(raw["delivery"]),
1678
1704
  newPhoneMasked: strOrNull2(raw["new_phone_masked"]),
1679
1705
  createdAt: strOrNull2(raw["created_at"]),
1680
1706
  expiresAt: strOrNull2(raw["expires_at"]),
@@ -1685,7 +1711,7 @@ function toPhoneChangeRequest(raw) {
1685
1711
  }
1686
1712
 
1687
1713
  // src/version.ts
1688
- var SDK_VERSION = "3.29.1";
1714
+ var SDK_VERSION = "3.30.1";
1689
1715
 
1690
1716
  // src/payouts.ts
1691
1717
  var AMOUNT = /^\d+(\.\d{1,2})?$/;
@@ -3753,6 +3779,27 @@ var SandboxSubscriptionsServer = class {
3753
3779
  var SandboxServer = class {
3754
3780
  constructor(http, auth, clockKey) {
3755
3781
  this.subscriptions = new SandboxSubscriptionsServer(http, auth, clockKey);
3782
+ this.http = http;
3783
+ this.auth = auth;
3784
+ }
3785
+ /**
3786
+ * Public demo key only (3.30.0): approve a send or transfer the demo player started, without
3787
+ * a passkey. INVO's demo sandbox answers with the claim code, which the recipient's game
3788
+ * server then uses with `claimCurrency` (a send) or `claimTransfer` (a transfer). Refused on
3789
+ * every other key and in production.
3790
+ */
3791
+ async approveDemoMove(transactionId, kind, opts) {
3792
+ if (typeof transactionId !== "string" || !transactionId.trim()) {
3793
+ throw invalidInput2("transactionId", transactionId, "is required");
3794
+ }
3795
+ const path2 = `/test-auth/${kind === "send" ? "sends" : "transfers"}/${encodeURIComponent(transactionId)}/approve`;
3796
+ const raw = await this.http.post(path2, {}, this.auth, { signal: opts?.signal });
3797
+ return {
3798
+ status: String(raw["status"] ?? ""),
3799
+ claimCode: typeof raw["claim_code"] === "string" ? raw["claim_code"] : null,
3800
+ claimCodeExpiresAt: typeof raw["claim_code_expires_at"] === "string" ? raw["claim_code_expires_at"] : null,
3801
+ raw
3802
+ };
3756
3803
  }
3757
3804
  };
3758
3805
  var InvoServer = class {
@@ -4046,6 +4093,25 @@ var InvoServer = class {
4046
4093
  raw
4047
4094
  };
4048
4095
  }
4096
+ /**
4097
+ * Read a hosted checkout's status from INVO, server-side, with the session token that
4098
+ * {@link createCheckout} returned. Same answer as the browser's
4099
+ * `invo.checkout.getPurchaseStatus`. A game server uses it to confirm a purchase when
4100
+ * the signed webhook cannot reach it (for example a private development preview).
4101
+ * It is INVO's own record, read over TLS with the session credential, never the buyer's word.
4102
+ */
4103
+ async getCheckoutStatus(input, opts) {
4104
+ const sessionId = String(input?.sessionId ?? "").trim();
4105
+ const sessionToken = String(input?.sessionToken ?? "").trim();
4106
+ if (!sessionId) throw invalidInput2("sessionId", input?.sessionId, "is required");
4107
+ if (!sessionToken) throw invalidInput2("sessionToken", "(hidden)", "is required");
4108
+ const raw = await this.http.get(
4109
+ `/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
4110
+ { kind: "bearer", token: sessionToken },
4111
+ { signal: opts?.signal }
4112
+ );
4113
+ return toPurchaseStatusResult(raw, sessionId);
4114
+ }
4049
4115
  /**
4050
4116
  * Direct purchase via the rail selector. Use when you need a specific rail.
4051
4117
  * - rail "platform" (default): standard card. May return status "requires_action"
@@ -5424,6 +5490,19 @@ var GameServerError = class extends Error {
5424
5490
  this.requestId = requestId;
5425
5491
  }
5426
5492
  };
5493
+ function moveDetails(raw) {
5494
+ const d = (raw?.["send_details"] ?? raw?.["transfer_details"] ?? {}) || {};
5495
+ const pick = (...keys) => {
5496
+ for (const k of keys) if (d[k] !== void 0 && d[k] !== null && d[k] !== "") return String(d[k]);
5497
+ return null;
5498
+ };
5499
+ const toId = pick("receiving_game_id", "target_game_id");
5500
+ const fromId = pick("sending_game_id", "source_game_id");
5501
+ const toName = pick("receiving_game", "target_game", "target_game_name");
5502
+ const fromName = pick("sending_game", "source_game", "source_game_name");
5503
+ const sameGame = fromId !== null && toId !== null ? fromId === toId : toName !== null && toName === fromName;
5504
+ return { sameGame, destinationName: toName, currencyName: pick("currency", "currency_name") ?? (typeof raw?.["currency_name"] === "string" ? raw["currency_name"] : null) };
5505
+ }
5427
5506
  function validateEconomy(economy) {
5428
5507
  const problems = [];
5429
5508
  if (!economy?.premium?.name) problems.push("premium.name is required");
@@ -5529,6 +5608,7 @@ function createInvoGameServer(options) {
5529
5608
  maxPerMinute: economy.soft.maxEarnPerMinute ?? 1e4
5530
5609
  };
5531
5610
  const iso = () => now().toISOString();
5611
+ const environmentNow = options.environment ?? (() => options.sandbox ? "sandbox" : "production");
5532
5612
  function toPlayer(p) {
5533
5613
  return { id: p.id, email: p.email, name: p.name, phoneMasked: maskPhone(p.phone) };
5534
5614
  }
@@ -5667,6 +5747,7 @@ function createInvoGameServer(options) {
5667
5747
  playerId: player.id,
5668
5748
  packId: pack.id,
5669
5749
  sessionId: session.sessionId,
5750
+ invoSessionToken: session.sessionToken || void 0,
5670
5751
  status: "pending",
5671
5752
  credited: null,
5672
5753
  orderId: null,
@@ -5680,8 +5761,9 @@ function createInvoGameServer(options) {
5680
5761
  }
5681
5762
  async function purchaseStatus(request, ref) {
5682
5763
  const { player } = await sessionPlayer(request);
5683
- const p = await store.read((s) => s.purchases[ref] ?? null);
5764
+ let p = await store.read((s) => s.purchases[ref] ?? null);
5684
5765
  if (!p || p.playerId !== player.id) throw new GameServerError(404, "PURCHASE_NOT_FOUND", "No such purchase.");
5766
+ if (p.status === "pending") p = await confirmFromInvo(p) ?? p;
5685
5767
  const out = {
5686
5768
  purchaseRef: p.purchaseRef,
5687
5769
  packId: p.packId,
@@ -5692,6 +5774,37 @@ function createInvoGameServer(options) {
5692
5774
  };
5693
5775
  return json(200, out);
5694
5776
  }
5777
+ async function confirmFromInvo(p) {
5778
+ if (!p.sessionId || !p.invoSessionToken) return null;
5779
+ let result;
5780
+ try {
5781
+ result = await invo.getCheckoutStatus({ sessionId: p.sessionId, sessionToken: p.invoSessionToken });
5782
+ } catch (err) {
5783
+ log("warn", "checkout status read failed", { code: err instanceof InvoError ? err.code : "ERROR" });
5784
+ return null;
5785
+ }
5786
+ if (!result.terminal) return null;
5787
+ const at = iso();
5788
+ return store.transact((s) => {
5789
+ const purchase = s.purchases[p.purchaseRef];
5790
+ if (!purchase || purchase.status !== "pending") return purchase ?? null;
5791
+ if (result.status === "credited") {
5792
+ const amount = toNumber(result.coinsCredited) ?? 0;
5793
+ const orderId = result.orderId ?? "";
5794
+ const ref = `order:${orderId}`;
5795
+ if (orderId && !s.ledgerRefs[ref]) {
5796
+ addLedger(s, { playerId: purchase.playerId, currency: "premium", amount, reason: "premium purchase (INVO, confirmed by status)", ref, at });
5797
+ }
5798
+ purchase.status = "credited";
5799
+ purchase.credited = amount;
5800
+ purchase.orderId = orderId || null;
5801
+ } else {
5802
+ purchase.status = "failed";
5803
+ }
5804
+ purchase.updatedAt = at;
5805
+ return purchase;
5806
+ });
5807
+ }
5695
5808
  async function webhook(request) {
5696
5809
  const raw = await readText(request);
5697
5810
  let event;
@@ -5916,6 +6029,223 @@ function createInvoGameServer(options) {
5916
6029
  throw err;
5917
6030
  }
5918
6031
  }
6032
+ function transferStatus() {
6033
+ const demo = !!options.demoProjectId;
6034
+ const environment = environmentNow();
6035
+ const setting = options.transfers ?? "auto";
6036
+ let reason = null;
6037
+ if (setting === false) reason = "off";
6038
+ else if (setting === "auto" && !demo) {
6039
+ if (environment === "resolving") reason = "checking";
6040
+ else if (environment === "sandbox") reason = "sandbox";
6041
+ }
6042
+ return {
6043
+ enabled: reason === null,
6044
+ reason,
6045
+ demo,
6046
+ scope: demo ? "project" : "network",
6047
+ recipientFields: demo ? { email: "required", phone: "hidden" } : { email: "optional", phone: "required" },
6048
+ apiBaseUrl: reason === null ? options.playerApiBaseUrl?.() ?? null : null,
6049
+ approval: demo ? "sandbox" : "passkey"
6050
+ };
6051
+ }
6052
+ function requireTransfers() {
6053
+ const status = transferStatus();
6054
+ if (!status.enabled) {
6055
+ throw new GameServerError(
6056
+ 403,
6057
+ "TRANSFERS_DISABLED",
6058
+ status.reason === "sandbox" ? "Transfers are off on this sandbox key. Set INVO_TRANSFERS=on to try them, or use your production key." : status.reason === "checking" ? "Checking this game's INVO key. Try again in a moment." : "Transfers are switched off for this game."
6059
+ );
6060
+ }
6061
+ return status;
6062
+ }
6063
+ async function transferToken(request) {
6064
+ const status = requireTransfers();
6065
+ const { player } = await sessionPlayer(request);
6066
+ try {
6067
+ const minted = await invo.mintPlayerToken({ playerEmail: player.email });
6068
+ return json(200, { token: minted.token, expiresAt: minted.expiresAt, apiBaseUrl: status.apiBaseUrl }, { "cache-control": "no-store" });
6069
+ } catch (err) {
6070
+ if (err instanceof InvoError) throw fromInvoError(err);
6071
+ throw err;
6072
+ }
6073
+ }
6074
+ async function startTransfer(request) {
6075
+ requireTransfers();
6076
+ const { player } = await sessionPlayer(request);
6077
+ const body = await readJson(request);
6078
+ const kind = body["kind"] === "send" ? "send" : "transfer";
6079
+ const amount = String(body["amount"] ?? "").trim();
6080
+ if (!/^\d{1,9}(\.\d{1,2})?$/.test(amount) || Number(amount) <= 0) {
6081
+ throw new GameServerError(400, "INVALID_AMOUNT", "Enter an amount greater than zero.");
6082
+ }
6083
+ const targetGameId = body["targetGameId"];
6084
+ if ((typeof targetGameId !== "string" || !targetGameId.trim()) && typeof targetGameId !== "number") {
6085
+ throw new GameServerError(400, "INVALID_GAME", "Pick a game to send to.");
6086
+ }
6087
+ const requestId = typeof body["clientRequestId"] === "string" ? body["clientRequestId"] : "";
6088
+ if (requestId && !REQUEST_ID.test(requestId)) {
6089
+ throw new GameServerError(400, "INVALID_REQUEST_ID", "clientRequestId must be 8 to 64 letters, digits, - or _.");
6090
+ }
6091
+ const clientRequestId = requestId || crypto.randomBytes(16).toString("hex");
6092
+ const typedEmail = typeof body["recipientEmail"] === "string" ? body["recipientEmail"].trim().toLowerCase() : "";
6093
+ if (typedEmail && !EMAIL.test(typedEmail)) throw new GameServerError(400, "INVALID_EMAIL", "Check the recipient's email address.");
6094
+ let senderPhone;
6095
+ let recipientEmail;
6096
+ let recipientPhone;
6097
+ const demoPid = options.demoProjectId;
6098
+ if (demoPid) {
6099
+ if (!typedEmail) {
6100
+ throw new GameServerError(400, "RECIPIENT_EMAIL_REQUIRED", "Enter your friend's email: the one they sign in to this game with.");
6101
+ }
6102
+ recipientEmail = toDemoEmail(typedEmail, demoPid);
6103
+ if (recipientEmail === player.email) throw new GameServerError(400, "RECIPIENT_IS_SENDER", "Pick someone other than yourself.");
6104
+ recipientPhone = demoPhoneFor(recipientEmail);
6105
+ senderPhone = demoPhoneFor(player.email);
6106
+ } else {
6107
+ recipientPhone = typeof body["recipientPhone"] === "string" ? body["recipientPhone"].replace(/[\s()-]/g, "") : "";
6108
+ if (!E1642.test(recipientPhone)) {
6109
+ throw new GameServerError(400, "INVALID_PHONE", "Enter the recipient's phone in international format, e.g. +15555550111.");
6110
+ }
6111
+ recipientEmail = typedEmail || void 0;
6112
+ const typedSender = typeof body["senderPhone"] === "string" ? body["senderPhone"].replace(/[\s()-]/g, "") : "";
6113
+ senderPhone = typedSender || player.phone || "";
6114
+ if (!E1642.test(senderPhone)) throw new GameServerError(400, "SENDER_PHONE_REQUIRED", "Add the phone number on your INVO account to send.");
6115
+ }
6116
+ try {
6117
+ const started = kind === "send" ? await invo.initiateSend({
6118
+ clientRequestId,
6119
+ senderPlayerName: player.name,
6120
+ senderPlayerEmail: player.email,
6121
+ senderPlayerPhone: senderPhone,
6122
+ receiverPlayerPhone: recipientPhone,
6123
+ ...recipientEmail ? { receiverPlayerEmail: recipientEmail } : {},
6124
+ receivingGameId: targetGameId,
6125
+ amount
6126
+ }) : await invo.initiateTransfer({
6127
+ clientRequestId,
6128
+ sourcePlayerName: player.name,
6129
+ sourcePlayerEmail: player.email,
6130
+ sourcePlayerPhone: senderPhone,
6131
+ targetPlayerPhone: recipientPhone,
6132
+ ...recipientEmail ? { targetPlayerEmail: recipientEmail } : {},
6133
+ targetGameId,
6134
+ amount
6135
+ });
6136
+ log("info", "transfer started", { kind, playerId: player.id, transactionId: started.transactionId });
6137
+ if (demoPid && recipientEmail) {
6138
+ const details = moveDetails(started.raw);
6139
+ const move = {
6140
+ transactionId: started.transactionId,
6141
+ kind,
6142
+ fromPlayerId: player.id,
6143
+ fromName: player.name,
6144
+ toEmail: recipientEmail,
6145
+ amount,
6146
+ currencyName: details.currencyName ?? economy.premium.name,
6147
+ sameGame: details.sameGame,
6148
+ destinationName: details.destinationName ?? "",
6149
+ status: "started",
6150
+ claimCode: null,
6151
+ claimCodeExpiresAt: null,
6152
+ createdAt: iso()
6153
+ };
6154
+ await store.transact((s) => void ((s.demoMoves ?? (s.demoMoves = {}))[move.transactionId] = move));
6155
+ }
6156
+ const answer = {
6157
+ transactionId: started.transactionId,
6158
+ kind,
6159
+ guardianPending: Boolean(started.guardianApproval),
6160
+ playerToken: started.playerToken ?? null,
6161
+ approval: demoPid ? "sandbox" : "passkey"
6162
+ };
6163
+ return json(200, answer, { "cache-control": "no-store" });
6164
+ } catch (err) {
6165
+ if (err instanceof InvoError) throw fromInvoError(err);
6166
+ throw err;
6167
+ }
6168
+ }
6169
+ function requireDemo() {
6170
+ requireTransfers();
6171
+ if (!options.demoProjectId) {
6172
+ throw new GameServerError(409, "PASSKEY_REQUIRED", "Approve and collect on INVO's page with your passkey.");
6173
+ }
6174
+ return options.demoProjectId;
6175
+ }
6176
+ async function approveMove(request, id) {
6177
+ requireDemo();
6178
+ const { player } = await sessionPlayer(request);
6179
+ const move = await store.read((s) => s.demoMoves?.[id] ?? null);
6180
+ if (!move || move.fromPlayerId !== player.id) throw new GameServerError(404, "TRANSFER_NOT_FOUND", "That transfer isn't yours to approve.");
6181
+ if (move.status !== "started") return json(200, { status: "approved", claimCode: null, replayed: true });
6182
+ try {
6183
+ const approved = await invo.sandbox.approveDemoMove(id, move.kind);
6184
+ await store.transact((s) => {
6185
+ const m = s.demoMoves?.[id];
6186
+ if (m && m.status === "started") {
6187
+ m.status = "approved";
6188
+ m.claimCode = approved.claimCode;
6189
+ m.claimCodeExpiresAt = approved.claimCodeExpiresAt;
6190
+ }
6191
+ });
6192
+ log("info", "demo transfer approved", { kind: move.kind, playerId: player.id, transactionId: id });
6193
+ return json(200, { status: "approved", claimCode: null, replayed: false });
6194
+ } catch (err) {
6195
+ if (err instanceof InvoError) throw fromInvoError(err);
6196
+ throw err;
6197
+ }
6198
+ }
6199
+ async function pendingMoves(request) {
6200
+ requireDemo();
6201
+ const { player } = await sessionPlayer(request);
6202
+ const nowMs = now().getTime();
6203
+ const moves = await store.read((s) => Object.values(s.demoMoves ?? {}));
6204
+ const pending = moves.filter(
6205
+ (m) => m.toEmail === player.email && m.status === "approved" && m.sameGame && (!m.claimCodeExpiresAt || Date.parse(m.claimCodeExpiresAt) > nowMs) || m.fromPlayerId === player.id && m.status === "started"
6206
+ ).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).map((m) => {
6207
+ const incoming = m.toEmail === player.email;
6208
+ return {
6209
+ transferId: m.transactionId,
6210
+ kind: incoming ? "receiving_confirm" : "identity_gate",
6211
+ flow: m.kind,
6212
+ amount: m.amount,
6213
+ currency: m.currencyName,
6214
+ counterpartyGame: incoming ? `${m.fromName}, in this game` : m.destinationName || "another game",
6215
+ expiresAt: m.claimCodeExpiresAt,
6216
+ stepUpRequired: false,
6217
+ held: false,
6218
+ holdReason: null,
6219
+ raw: {}
6220
+ };
6221
+ });
6222
+ return json(200, { pending }, { "cache-control": "no-store" });
6223
+ }
6224
+ async function collectMove(request, id) {
6225
+ requireDemo();
6226
+ const { player } = await sessionPlayer(request);
6227
+ const move = await store.read((s) => s.demoMoves?.[id] ?? null);
6228
+ if (!move || move.toEmail !== player.email) throw new GameServerError(404, "TRANSFER_NOT_FOUND", "There's nothing to collect with that id.");
6229
+ if (move.status === "collected") return json(200, { status: "collected", replayed: true, wallet: await readWallet(player) });
6230
+ if (move.status !== "approved" || !move.claimCode) throw new GameServerError(409, "NOT_APPROVED_YET", "The sender hasn't approved this one yet.");
6231
+ if (!move.sameGame) throw new GameServerError(409, "OTHER_GAME", `This one is waiting in ${move.destinationName || "another game"}; collect it there.`);
6232
+ try {
6233
+ if (move.kind === "send") {
6234
+ await invo.claimCurrency({ claimCode: move.claimCode, receiverPlayerName: player.name, receiverPlayerEmail: player.email, receiverPlayerPhone: demoPhoneFor(player.email) });
6235
+ } else {
6236
+ throw new GameServerError(409, "OTHER_GAME", "Collect this transfer in the game it was sent to.");
6237
+ }
6238
+ } catch (err) {
6239
+ if (err instanceof InvoError) throw fromInvoError(err);
6240
+ throw err;
6241
+ }
6242
+ await store.transact((s) => {
6243
+ const m = s.demoMoves?.[id];
6244
+ if (m) m.status = "collected";
6245
+ });
6246
+ log("info", "demo transfer collected", { kind: move.kind, playerId: player.id, transactionId: id });
6247
+ return json(200, { status: "collected", replayed: false, wallet: await readWallet(player) });
6248
+ }
5919
6249
  async function route(request, sub, method) {
5920
6250
  if (method === "GET" && sub === "/health") return json(200, { ok: true, setupRequired: false, sandbox: options.sandbox, demo: !!options.demoProjectId });
5921
6251
  if (method === "GET" && sub === "/catalog") return catalog();
@@ -5933,6 +6263,15 @@ function createInvoGameServer(options) {
5933
6263
  if (method === "POST" && sub === "/earn") return earn(request);
5934
6264
  if (method === "POST" && sub === "/events") return events(request);
5935
6265
  if (method === "GET" && sub === "/rewards") return rewards(request);
6266
+ if (method === "GET" && sub === "/transfers/status") return json(200, transferStatus());
6267
+ if (method === "POST" && sub === "/transfers/token") return transferToken(request);
6268
+ if (method === "POST" && sub === "/transfers") return startTransfer(request);
6269
+ if (method === "GET" && sub === "/transfers/pending") return pendingMoves(request);
6270
+ const move = /^\/transfers\/([^/]+)\/(approve|collect)$/.exec(sub);
6271
+ if (method === "POST" && move) {
6272
+ const id = decodeURIComponent(move[1]);
6273
+ return move[2] === "approve" ? approveMove(request, id) : collectMove(request, id);
6274
+ }
5936
6275
  return json(404, { error: { code: "NOT_FOUND", message: "No such route." } });
5937
6276
  }
5938
6277
  return {
@@ -6003,7 +6342,13 @@ function invoGameServerFromEnv(options) {
6003
6342
  },
6004
6343
  basePath: options.basePath,
6005
6344
  publicUrl: env["PUBLIC_URL"] || void 0,
6006
- log: options.log
6345
+ log: options.log,
6346
+ transfers: (() => {
6347
+ const t = env["INVO_TRANSFERS"]?.trim().toLowerCase();
6348
+ return t === "on" ? true : t === "off" ? false : "auto";
6349
+ })(),
6350
+ environment: envNow,
6351
+ playerApiBaseUrl: () => explicitBase || (state.environment === "production" ? PRODUCTION_BASE_URL : state.environment === "sandbox" ? SANDBOX_BASE_URL : null)
6007
6352
  };
6008
6353
  const server = createInvoGameServer(serverOptions);
6009
6354
  return { server, missing, sandbox: sandboxNow(), environment: envNow(), demo };
@@ -1,9 +1,10 @@
1
- import { I as InvoServer, a as InvoEnvironment } from './server-Bxo_wgHx.cjs';
2
- export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, b as baseUrlForKey, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-Bxo_wgHx.cjs';
3
- import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-CLyJDuXd.cjs';
4
- export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameWallet } from './types-CLyJDuXd.cjs';
5
- export { I as InvoError } from './types-_lIm74kd.cjs';
6
- export { S as SDK_VERSION } from './version-DOaYbHu7.cjs';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-BAOn3KH3.cjs';
2
+ export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, b as baseUrlForKey, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-BAOn3KH3.cjs';
3
+ import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-jUxfYjiD.cjs';
4
+ export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameTransferInput, n as GameTransferKind, o as GameTransferStart, p as GameTransferStatus, q as GameWallet } from './types-jUxfYjiD.cjs';
5
+ export { I as InvoError } from './types-BTbZicgj.cjs';
6
+ export { S as SDK_VERSION } from './version-CR7XECyP.cjs';
7
+ import './loyalty-events-CmDw2ZoR.cjs';
7
8
 
8
9
  interface StoredPlayer {
9
10
  id: string;
@@ -37,6 +38,8 @@ interface StoredPurchase {
37
38
  playerId: string;
38
39
  packId: string;
39
40
  sessionId: string;
41
+ /** INVO's checkout session token, kept on the server to confirm the purchase if the webhook can't arrive. */
42
+ invoSessionToken?: string;
40
43
  status: GamePurchaseStatus;
41
44
  credited: number | null;
42
45
  orderId: string | null;
@@ -62,6 +65,29 @@ interface GameStoreState {
62
65
  inventory: Record<string, Record<string, number>>;
63
66
  /** Webhook idempotency key → time processed. */
64
67
  webhooks: Record<string, string>;
68
+ /**
69
+ * Public demo key only (3.30.0): sends and transfers between players of this project, by
70
+ * INVO transaction id. The server approves them in INVO's demo sandbox and keeps the claim
71
+ * code so the recipient can collect. Absent in stores written before 3.30.0.
72
+ */
73
+ demoMoves?: Record<string, StoredDemoMove>;
74
+ }
75
+ interface StoredDemoMove {
76
+ transactionId: string;
77
+ kind: "send" | "transfer";
78
+ fromPlayerId: string;
79
+ fromName: string;
80
+ /** The recipient's demo email (already mapped with `toDemoEmail`). */
81
+ toEmail: string;
82
+ amount: string;
83
+ currencyName: string;
84
+ /** True when it lands in this game, so a player of this game can collect it. */
85
+ sameGame: boolean;
86
+ destinationName: string;
87
+ status: "started" | "approved" | "collected";
88
+ claimCode: string | null;
89
+ claimCodeExpiresAt: string | null;
90
+ createdAt: string;
65
91
  }
66
92
  interface GameStore {
67
93
  /** Read a consistent snapshot. Do not mutate it. */
@@ -115,6 +141,16 @@ interface InvoGameServerOptions {
115
141
  * address or number ever reaches INVO. {@link invoGameServerFromEnv} sets it for you.
116
142
  */
117
143
  demoProjectId?: string;
144
+ /**
145
+ * Player-to-player transfers and sends (3.30.0). `"auto"` (the default) turns them on for
146
+ * the public demo key and in production, and off on other sandbox keys; `true` or `false`
147
+ * forces it. {@link invoGameServerFromEnv} reads `INVO_TRANSFERS` (`on`, `off`, `auto`).
148
+ */
149
+ transfers?: boolean | "auto";
150
+ /** Where the key's environment stands, for `transfers: "auto"`. Default: from `sandbox`. */
151
+ environment?: () => InvoEnvironment | "resolving";
152
+ /** INVO's API base for the browser's player-token calls, or null while unknown. */
153
+ playerApiBaseUrl?: () => string | null;
118
154
  }
119
155
  interface InvoGameServer {
120
156
  readonly basePath: string;