@getenginex/sdk-igaming 0.11.0 → 0.12.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.
@@ -30,12 +30,23 @@ var USER_READS = {
30
30
  casino: ["listSessions", "getHistory", "getBiggestWinners"],
31
31
  club: ["getOverview", "listHistory", "listTournaments", "listRelatedTournaments", "getTournament", "getRanking"],
32
32
  bonus: ["listOffers", "getOffer", "listParticipations", "getParticipation", "getOverview", "listPositions"],
33
- missions: ["list", "listMine"],
33
+ missions: ["list", "listMine", "getMine"],
34
34
  loyalty: ["get"],
35
35
  referrals: ["get", "listHistory"],
36
36
  bets: ["list", "get", "getCashoutOffer"]
37
37
  };
38
38
  var LOCALE_KEYED = /* @__PURE__ */ new Set(["club"]);
39
+ var NORMALIZE = {
40
+ "missions.getMine": (input) => {
41
+ if (input === void 0) return void 0;
42
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return input;
43
+ const keys = Object.keys(input);
44
+ const flag = input.includeHistory;
45
+ if (keys.some((key) => key !== "includeHistory")) return input;
46
+ if (flag === void 0 || flag === false) return void 0;
47
+ return flag === true ? { includeHistory: true } : input;
48
+ }
49
+ };
39
50
  function localeOf(igaming) {
40
51
  const read = igaming[LOCALE];
41
52
  return (typeof read === "function" ? read() : void 0) ?? null;
@@ -43,19 +54,25 @@ function localeOf(igaming) {
43
54
  var userKeys = (...prefixes) => (scope) => prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method));
44
55
  var none = () => [];
45
56
  var isConflict = (error) => sdk.isEnginexError(error) && error.status === 409;
57
+ var onConflict = (invalidates) => ({ when: isConflict, invalidates });
58
+ var leavesStateUnknown = (error) => sdk.isEnginexError(error) && (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT" || error.code === "KEY_IN_USE" || error.status >= 500 || error.status >= 200 && error.status < 300 || error.code === "VALIDATION_ERROR" && error.status < 400);
46
59
  var CLUB_WRITE = { idempotent: true, keepsKey: keepsClubIdempotencyKey };
47
60
  var CLUB_MONEY = userKeys(["club", "getOverview"], ["club", "listHistory"], ["bonus"], ["wallet"]);
48
61
  var WRITES = {
49
62
  casino: { launchGame: { invalidates: userKeys(["casino", "listSessions"]), sensitive: true } },
50
63
  club: {
51
- setMembership: { ...CLUB_WRITE, invalidates: userKeys(["club"]), conflict: userKeys(["club", "getOverview"]) },
64
+ setMembership: {
65
+ ...CLUB_WRITE,
66
+ invalidates: userKeys(["club"]),
67
+ onError: onConflict(userKeys(["club", "getOverview"]))
68
+ },
52
69
  // A play or a redemption moves coins, XP, the history and maybe a bonus or the balance; never the tournaments.
53
- play: { ...CLUB_WRITE, invalidates: CLUB_MONEY, conflict: userKeys(["club", "getOverview"]) },
54
- redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, conflict: userKeys(["club", "getOverview"]) },
70
+ play: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(["club", "getOverview"])) },
71
+ redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(["club", "getOverview"])) },
55
72
  registerForTournament: {
56
73
  ...CLUB_WRITE,
57
74
  invalidates: userKeys(["club"]),
58
- conflict: userKeys(["club", "getOverview"], ["club", "listTournaments"], ["club", "getTournament"])
75
+ onError: onConflict(userKeys(["club", "getOverview"], ["club", "listTournaments"], ["club", "getTournament"]))
59
76
  }
60
77
  },
61
78
  bonus: {
@@ -64,7 +81,14 @@ var WRITES = {
64
81
  claim: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true },
65
82
  redeemPromoCode: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true, sensitive: true }
66
83
  },
67
- loyalty: { redeem: { invalidates: userKeys(["loyalty"], ["wallet"]), idempotent: true } },
84
+ loyalty: {
85
+ // An ambiguous failure may have redeemed the points: refetch them and the balance before a retry is offered.
86
+ redeem: {
87
+ invalidates: userKeys(["loyalty"], ["wallet"]),
88
+ idempotent: true,
89
+ onError: { when: leavesStateUnknown, invalidates: userKeys(["loyalty"], ["wallet"]) }
90
+ }
91
+ },
68
92
  sportsbook: { createSession: { invalidates: none, sensitive: true } },
69
93
  bets: { cashout: { invalidates: userKeys(["bets"], ["wallet"]), idempotent: true } }
70
94
  };
@@ -81,7 +105,9 @@ function createIgamingQueries(igaming) {
81
105
  PUBLIC_READS,
82
106
  (namespace, method, input) => scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input)
83
107
  );
84
- add(USER_READS, (namespace, method, input) => {
108
+ add(USER_READS, (namespace, method, raw) => {
109
+ const normalize = NORMALIZE[`${namespace}.${method}`];
110
+ const input = normalize ? normalize(raw) : raw;
85
111
  const options = scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input);
86
112
  if (!LOCALE_KEYED.has(namespace)) return options;
87
113
  return { ...options, queryKey: [...options.queryKey, { locale: localeOf(igaming) }] };
@@ -109,8 +135,9 @@ function createIgamingMutations(igaming) {
109
135
  () => write.invalidates(scope),
110
136
  scoped
111
137
  );
112
- const conflict = write.conflict;
113
- if (conflict) mutation.invalidatesOnError = (_input, error) => isConflict(error) ? conflict(scope) : [];
138
+ const refresh = write.onError;
139
+ if (refresh)
140
+ mutation.invalidatesOnError = (_input, error) => refresh.when(error) ? refresh.invalidates(scope) : [];
114
141
  return mutation;
115
142
  };
116
143
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/internal/input.ts","../../src/modules/club.ts","../../src/query/index.ts"],"names":["isEnginexError","isAmbiguousFailure","queryScope"],"mappings":";;;;;;;;;;AA0CO,IAAM,MAAA,mBAAwC,MAAA,CAAO,GAAA,CAAI,gCAAgC,CAAA;ACuwBzF,SAAS,wBAAwB,KAAA,EAAyB;AAC/D,EAAA,IAAI,CAACA,kBAAA,CAAe,KAAK,CAAA,EAAG,OAAO,KAAA;AACnC,EAAA,IAAIC,4BAAA,CAAmB,KAAK,CAAA,EAAG,OAAO,IAAA;AACtC,EAAA,OAAO,MAAM,MAAA,IAAU,GAAA,IAAO,CAAC,sBAAA,CAAu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;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["import type { ExtensionTransport } from '@getenginex/sdk/extension'\n\n/** Route of a call, to report the input error to `onError`. @internal */\nexport interface Route {\n /** HTTP method. */\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n /** Path after `/api/v1`. */\n path: string\n}\n\n/**\n * Rejects with `CONFIGURATION_ERROR` (without a request) notifying `onError`, like the core does with invalid\n * input. `message` never carries the received value. The error comes out of `reportError`, which normalizes it into\n * `EnginexError` (the core does not export the constructor to product packages). @internal\n */\nexport function rejectInput(transport: ExtensionTransport, message: string, route: Route): Promise<never> {\n return Promise.reject(\n transport.reportError({ code: 'CONFIGURATION_ERROR', message, status: 0 }, { ...route, attempt: 0 }),\n )\n}\n\n/**\n * Checks `{ page, perPage }` of a listing: `page` an integer ≥ 1, `perPage` an integer from 1 to 100.\n * Returns the problem message or `undefined` if everything is fine. @internal\n */\nexport function pageInputProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${name}: input must be an object.`\n const { page, perPage } = input as { page?: unknown; perPage?: unknown }\n if (page !== undefined && (typeof page !== 'number' || !Number.isSafeInteger(page) || page < 1))\n return `${name}: page must be an integer ≥ 1.`\n if (\n perPage !== undefined &&\n (typeof perPage !== 'number' || !Number.isInteger(perPage) || perPage < 1 || perPage > 100)\n )\n return `${name}: perPage must be an integer from 1 to 100.`\n return undefined\n}\n/**\n * Symbol (non-enumerable) of the client's current locale getter on the iGaming object. `Symbol.for`: `/query` may be\n * another copy of this package's code (CommonJS entries are separate files). @internal\n */\nexport const LOCALE: unique symbol = /* @__PURE__ */ Symbol.for('@getenginex/sdk-igaming/locale') as never\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport { isEnginexError, type CallOptions, type NoParams } from '@getenginex/sdk'\nimport {\n currencyCode,\n decimalPlaces,\n isAmbiguousFailure,\n lazy,\n mapOf,\n wire,\n type ExtensionTransport,\n} from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalText } from '../internal/optional-values'\nimport { currencyOrEmpty, integerText, nonNegativeMinorUnits, protoEnum } from '../internal/schemas'\n\n// Wire format: every `/casino/club` route answers WITHOUT the `{ success, data }` envelope. All of them but one are\n// protojson written by `writeClubResponse` with `EmitDefaultValues: true`: scalars, lists and maps are always\n// present (an empty list as `[]`, int64 as text), while an unset message or an unset proto3 `optional` is omitted.\n// The exception is `GET /casino/club/tournaments?relatedTo=`, written by `encoding/json` (`httputil.JSON`): a nil\n// map comes out as `null` and a zero `time.Time` as `\"0001-01-01T00:00:00Z\"`. The SDK reads both shapes the same\n// way: an omitted or `null` list is `[]`, an omitted or `null` message is `null`, an empty text that means \"none\" is\n// `null`, and an absent date (omitted, `null`, `\"\"`, the epoch or Go's zero time) is `null`.\n\n// ─── Types ─────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Text per locale, as the operator wrote it (`{ \"pt-BR\": \"...\", \"en\": \"...\" }`). `{}` when the gateway sends none.\n * @category Club\n */\nexport type ClubLocalized = Record<string, string>\n\n/**\n * Money of the club, in minor units of `currency`.\n * @category Club\n */\nexport interface ClubMoney {\n /** Value in minor units of `currency` (the gateway sends it as int64 text; the SDK converts). Never negative. */\n amount: number\n /** ISO 4217 currency code, e.g. `BRL`. */\n currency: string\n /**\n * Decimal places of `amount` as the gateway resolved them (the currency's ISO exponent; for a free-spin\n * denomination, the provider's scale); `null` when the gateway omits them.\n */\n decimalPlaces: number | null\n}\n\n/**\n * Kind of a club reward, in lowercase. A kind the SDK does not know yet arrives as the gateway sent it, in\n * lowercase: handle the default case.\n * @category Club\n */\nexport type ClubRewardKind =\n | 'coins'\n | 'digital'\n | 'cashback'\n | 'bonus_balance'\n | 'free_spins'\n | 'tournament_ticket'\n | 'real_balance'\n | 'manual'\n | 'unspecified'\n | (string & {})\n\n/**\n * Coin award published in place of a reward in a given situation (e.g. the player already holds the ticket).\n * @category Club\n */\nexport interface ClubAlternateReward {\n /** Kind of the alternate, `coins` today. */\n kind: ClubRewardKind\n /** Label per locale. */\n label: ClubLocalized\n /** Quantity (integer). */\n quantity: number\n}\n\n/**\n * Cashback terms of a `cashback` reward.\n * @category Club\n */\nexport interface ClubCashbackTerms {\n /** Percentage in basis points (`1000` = 10%). */\n percentageBps: number\n /** `edition`, `daily`, `weekly` or another period; `null` when absent. */\n period: 'edition' | 'daily' | 'weekly' | (string & {}) | null\n /** `net_loss` or another basis; `null` when absent. */\n basis: 'net_loss' | (string & {}) | null\n /** Where the cashback is credited: `real`, `restricted` or another; `null` when absent. */\n destination: 'real' | 'restricted' | (string & {}) | null\n /** Start of the frozen basis window (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End of the frozen basis window (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Catalogue game ids eligible for the basis. */\n gameIds: string[]\n /** Coin award when the basis is zero; `null` when none. */\n zeroBasisAlternate: ClubAlternateReward | null\n /** Coin award when the basis was already rewarded; `null` when none. */\n priorAwardAlternate: ClubAlternateReward | null\n}\n\n/**\n * A club reward: of a wheel slice, a mission chest, a store item or a tournament prize.\n * @category Club\n */\nexport interface ClubReward {\n /** Reward id (`''` when the gateway sends none, e.g. in a projected tournament prize). */\n id: string\n /** Label per locale. */\n label: ClubLocalized\n /** Kind of the reward (see {@link ClubRewardKind}). */\n kind: ClubRewardKind\n /** Quantity (integer: coins, spins, items). */\n quantity: number\n /** Money of the reward; `null` when it has none. */\n money: ClubMoney | null\n /** Free-spin campaign: spins and the catalogue game; `null` when not a campaign. */\n campaign: { spins: number; gameId: string | null } | null\n /** Cashback terms; `null` when not a cashback. */\n cashback: ClubCashbackTerms | null\n /** Manual delivery (`physical` or `experience`) with the instructions; `null` when not manual. */\n manual: { deliveryType: 'physical' | 'experience' | (string & {}) | null; instructions: ClubLocalized } | null\n /** Validity in seconds after delivery (integer; `0` without one). */\n ttlSeconds: number\n /** Tournament edition of a `tournament_ticket`; `null` otherwise. */\n editionId: string | null\n /** Coin award when the player already holds the ticket or entry; `null` when none. */\n ticketOwnedAlternate: ClubAlternateReward | null\n}\n\n/**\n * Status of a receipt, in lowercase: `pending`, `delivered`, `failed`, `no_value` (a confirmed zero cashback) or a\n * status the SDK does not know yet.\n * @category Club\n */\nexport type ClubReceiptStatus = 'pending' | 'delivered' | 'failed' | 'no_value' | 'unspecified' | (string & {})\n\n/**\n * Receipt of a play, a redemption, a mission chest or a tournament award.\n * @category Club\n */\nexport interface ClubReceipt {\n /** Receipt id. */\n id: string\n /** Status (see {@link ClubReceiptStatus}). */\n status: ClubReceiptStatus\n /** What produced it, in lowercase: `activity` (a wheel, scratch card or gift), `chest` (a mission chest), `store` or `tournament`. */\n sourceKind: 'activity' | 'chest' | 'store' | 'tournament' | 'unspecified' | (string & {})\n /** Id of the source (activity, mission right, item, edition); `null` when absent. */\n sourceId: string | null\n /** Wheel slice that was drawn; `null` when not a draw. */\n sliceId: string | null\n /** The reward; `null` when absent. */\n reward: ClubReward | null\n /** Money actually settled; `null` when absent. */\n settlement: ClubMoney | null\n /** Coins spent (integer; `0` when free). */\n costCoins: number\n /** When it was accepted (ISO 8601); `null` when absent. */\n acceptedAt: string | null\n /** When the delivery was confirmed (ISO 8601); `null` while not delivered. */\n deliveredAt: string | null\n /** When the reward expires (ISO 8601); `null` without expiry. */\n expiresAt: string | null\n /** Frozen final rank of a tournament award; `null` otherwise. */\n tournamentRank: number | null\n /** Whether a tournament ticket was consumed. */\n ticketConsumed: boolean\n}\n\n/**\n * A level of the program.\n * @category Club\n */\nexport interface ClubLevel {\n /** Level id. */\n id: string\n /** Name per locale. */\n name: ClubLocalized\n /** XP needed to reach it (integer). */\n minXp: number\n /** Benefit per locale. */\n benefit: ClubLocalized\n}\n\n/**\n * The club program as the player sees it (part of {@link ClubOverview}; also the result of\n * {@link ClubApi.setMembership}).\n * @category Club\n */\nexport interface ClubProgram {\n /** Whether the program is active for the operator. */\n enabled: boolean\n /** Whether the player joined. */\n joined: boolean\n /** Whether joining is required before playing. */\n membershipRequired: boolean\n /** Whether the player can join now. */\n canJoin: boolean\n /** Whether the history can be read (also when the program is paused). */\n historyAvailable: boolean\n /** Published version: pass it back as `versionId` in every write; `null` without a published version. */\n versionId: string | null\n /** Locale the gateway resolved from `Accept-Language` (the client's locale); `null` when absent. */\n locale: string | null\n /** Key of the membership terms shown for that locale: pass it as `termsLocale` when joining. */\n termsLocale: string | null\n /** Program time zone (IANA); `null` when absent. */\n timeZone: string | null\n /** The player's wallet currency the program uses; `null` while not confirmed. */\n currency: string | null\n /** Name per locale. */\n name: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Name of the coin per locale. */\n coinName: ClubLocalized\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n /** Levels, in the order the operator published them (a repeated id keeps the first). */\n levels: ClubLevel[]\n}\n\n/**\n * Kind of an activity: `wheel`, `scratch`, `gift` or a kind the SDK does not know yet.\n * @category Club\n */\nexport type ClubActivityKind = 'wheel' | 'scratch' | 'gift' | 'unspecified' | (string & {})\n\n/**\n * An activity (wheel, scratch card, gift) and the player's state in it.\n * @category Club\n */\nexport interface ClubActivityState {\n /** The activity. */\n activity: {\n /** Activity id: pass it to {@link ClubApi.play}. */\n id: string\n /** Kind (see {@link ClubActivityKind}). */\n kind: ClubActivityKind\n /** Name per locale. */\n name: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n /** Wheel theme: `emerald`, `midnight`, `berry` or another; `null` when absent. */\n wheelTheme: 'emerald' | 'midnight' | 'berry' | (string & {}) | null\n /** Label of the play button per locale. */\n playLabel: ClubLocalized\n /** Slices, without the draw weights (a repeated id keeps the first). */\n slices: { id: string; reward: ClubReward | null }[]\n }\n /** Whether the player can play now. */\n canPlay: boolean\n /** Why the player cannot play (e.g. `daily_budget_exhausted`); `null` when absent. */\n unavailableReason: 'daily_budget_exhausted' | (string & {}) | null\n /** The player's last receipt in this activity; `null` when none. */\n latestReceipt: ClubReceipt | null\n /** When the player can play again (ISO 8601); `null` when absent. */\n availableAt: string | null\n}\n\n/**\n * A mission and the player's progress and chest right.\n * @category Club\n */\nexport interface ClubMissionState {\n /** The mission. */\n mission: {\n /** Mission id. */\n id: string\n /** Title per locale. */\n title: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** `daily`, `weekly`, `edition` or another, in lowercase. */\n recurrence: string\n /** `fact`, `day`, `edition` or another, in lowercase. */\n countBy: string\n /** Target (integer). */\n target: number\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n }\n /** Edition (period) of the mission; `null` when absent. */\n editionId: string | null\n /** Progress (integer). */\n progress: number\n /** Chest right: pass it as `activityId` to {@link ClubApi.play} to open the chest; `null` without a right. */\n rightId: string | null\n /**\n * Version of the right. The gateway sends it on the pending chests of a paused program; `null` when absent.\n */\n rightVersionId: string | null\n /** Chest options: pass the chosen `id` as `optionId` to {@link ClubApi.play}. */\n chestOptions: ClubReward[]\n /** Whether the chest can be opened now. */\n canClaim: boolean\n /** Receipt of the opened chest; `null` while not opened. */\n receipt: ClubReceipt | null\n /** End of the edition (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Deadline to open the chest (ISO 8601); `null` when absent. */\n claimExpiresAt: string | null\n /** Days already stamped (`YYYY-MM-DD`). */\n stampedDays: string[]\n}\n\n/**\n * An item of the coin store and whether the player can redeem it.\n * @category Club\n */\nexport interface ClubStoreItemState {\n /** The item. */\n item: {\n /** Item id: pass it as `rewardId` to {@link ClubApi.redeem}. */\n id: string\n /** Label per locale. */\n label: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Price in coins (integer). */\n costCoins: number\n /** The reward; `null` when absent. */\n reward: ClubReward | null\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n }\n /** Whether the player can redeem it now. */\n canRedeem: boolean\n /** Why it cannot be redeemed, in lowercase; `null` when absent. */\n unavailableReason: string | null\n}\n\n/**\n * The player's balances, activities, missions and store.\n * @category Club\n */\nexport interface ClubRewards {\n /** XP (integer). */\n xp: number\n /** Coin balance (integer). */\n coins: number\n /** Current level id; `null` when none. */\n levelId: string | null\n /** Activities (a repeated activity id keeps the first). Empty while the program is paused. */\n activities: ClubActivityState[]\n /** Missions (a repeated mission right keeps the first). While paused, only the pending chests. */\n missions: ClubMissionState[]\n /** Store items (a repeated item id keeps the first). Empty while the program is paused. */\n storeItems: ClubStoreItemState[]\n}\n\n/**\n * The club overview (`GET /casino/club`).\n * @category Club\n */\nexport interface ClubOverview {\n /** The program. */\n program: ClubProgram\n /** The player's state; `null` when the program is disabled and has no history. */\n rewards: ClubRewards | null\n}\n\n/**\n * A balance movement of the history.\n * @category Club\n */\nexport interface ClubMovement {\n /** Movement id. */\n id: string\n /** `xp`, `coins` or another kind, in lowercase. */\n kind: string\n /** Units moved (integer; negative for a debit). */\n units: number\n /** Id of the source; `null` when absent. */\n sourceId: string | null\n /** When it happened (ISO 8601); `null` when absent. */\n occurredAt: string | null\n}\n\n/**\n * A page of the club history.\n * @category Club\n */\nexport interface ClubHistory {\n /** Receipts on this page (a repeated id keeps the first). */\n receipts: ClubReceipt[]\n /** Movements on this page (a repeated id keeps the first). */\n movements: ClubMovement[]\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * Status of a tournament, in lowercase.\n * @category Club\n */\nexport type ClubTournamentStatus =\n | 'draft'\n | 'upcoming'\n | 'live'\n | 'awaiting_confirmation'\n | 'completed'\n | 'cancelled'\n | 'unspecified'\n | (string & {})\n\n/**\n * The player's registration in a tournament.\n * @category Club\n */\nexport interface ClubTournamentRegistration {\n /** Registration id. */\n id: string\n /** Edition id. */\n editionId: string\n /** Version registered; `null` when absent. */\n versionId: string | null\n /** When the player registered (ISO 8601); `null` when absent. */\n joinedAt: string | null\n}\n\n/**\n * A prize range of a tournament.\n * @category Club\n */\nexport interface ClubTournamentPrize {\n /** First rank of the range (integer). */\n fromRank: number\n /** Last rank of the range (integer). */\n toRank: number\n /** The reward; `null` when absent (e.g. an external listing). */\n reward: ClubReward | null\n /** Announced amount (external listings); `null` when absent. Under `'warn'` a prize with an invalid one is dropped. */\n announcedAmount: ClubMoney | null\n /** Prize terms per locale (`{}` when none). */\n terms: ClubLocalized\n /** Frozen offer conditions of a `bonus_balance`/`free_spins` prize; `null` when none. */\n offerTerms: {\n /** Value of each free spin, in the provider's scale; `null` when unconfirmed. */\n spinDenomination: ClubMoney | null\n /** Exact decimal wagering multiplier (`\"0\"` = no wagering); `null` when unconfirmed. */\n wageringMultiplier: string | null\n /** Validity in seconds; `null` when unconfirmed. */\n validForSeconds: number | null\n /** Expiry of the offer (ISO 8601); `null` when absent. */\n expiresAt: string | null\n /** End of the grant window (ISO 8601); `null` when absent. */\n grantEndsAt: string | null\n } | null\n}\n\n/**\n * A club tournament (own or external).\n * @category Club\n */\nexport interface ClubTournament {\n /** Edition id (external ones start with `ext_`). */\n id: string\n /** `own`, `external` or another source, in lowercase. */\n source: string\n /** Published version: pass it as `versionId` to {@link ClubApi.registerForTournament}; `null` when absent. */\n versionId: string | null\n /** Title per locale. */\n title: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Status (see {@link ClubTournamentStatus}). */\n status: ClubTournamentStatus\n /** Start (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Last update (ISO 8601); `null` when absent. */\n updatedAt: string | null\n /** Scoring rule, in lowercase; `null` when absent. */\n scoringRule: string | null\n /** Tie-break rule, in lowercase; `null` when absent. */\n tieBreak: string | null\n /** Currency of the edition (ISO 4217); `null` when absent. */\n currency: string | null\n /** Time zone (IANA); `null` when absent. */\n timeZone: string | null\n /** Catalogue games of the edition (a repeated id keeps the first). */\n gameIds: string[]\n /** Prize ranges. */\n prizes: ClubTournamentPrize[]\n /** `registration`, `in_game` or another; `null` when no action is confirmed. */\n joinMode: 'registration' | 'in_game' | (string & {}) | null\n /** Locale of the terms shown; `null` when absent. */\n locale: string | null\n /** Whether {@link ClubApi.getRanking} can be read. */\n rankingAvailable: boolean\n /** Whether the player can register now. */\n canRegister: boolean\n /** Whether registering consumes a ticket. */\n requiresTicket: boolean\n /** The player's registration; `null` when not registered. */\n registration: ClubTournamentRegistration | null\n /** The player's award from the frozen result (detail only); `null` when none. */\n personalAward: ClubReceipt | null\n /** Whether the source data is stale. */\n stale: boolean\n /** Registration opening (ISO 8601); `null` when absent. */\n registrationStartsAt: string | null\n /** Registration closing (ISO 8601); `null` when absent. */\n registrationEndsAt: string | null\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n}\n\n/**\n * A page of club tournaments.\n * @category Club\n */\nexport interface ClubTournamentPage {\n /** Tournaments on this page (a repeated id keeps the first). */\n items: ClubTournament[]\n /** Whether external tournaments are on the page. */\n externalAvailable: boolean\n /** Whether an external tournament on the page is stale. */\n externalStale: boolean\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * Another edition of the same external schedule.\n * @category Club\n */\nexport interface ClubRelatedTournament {\n /** Edition id (`ext_...`). */\n id: string\n /** Title per locale. */\n title: ClubLocalized\n /** Status (see {@link ClubTournamentStatus}). */\n status: ClubTournamentStatus\n /** Start (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End (ISO 8601); `null` when absent. */\n endsAt: string | null\n}\n\n/**\n * A page of related editions.\n * @category Club\n */\nexport interface ClubRelatedTournamentPage {\n /** Related editions (a repeated id keeps the first). */\n items: ClubRelatedTournament[]\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * A row of a tournament ranking.\n * @category Club\n */\nexport interface ClubRank {\n /** Position (integer ≥ 1). */\n position: number\n /** Display name, already masked by the source. */\n displayName: string\n /** Score as decimal text (display only). */\n score: string\n}\n\n/**\n * A tournament ranking.\n * @category Club\n */\nexport interface ClubRanking {\n /** Top rows. */\n entries: ClubRank[]\n /** The player's row; `null` when not ranked. */\n personal: ClubRank | null\n /** Last update (ISO 8601); `null` when absent. */\n updatedAt: string | null\n /** Whether the ranking is final. */\n final: boolean\n}\n\n/**\n * Result of {@link ClubApi.play}.\n * @category Club\n */\nexport interface ClubPlayResult {\n /** The receipt. */\n receipt: ClubReceipt\n /** Slice drawn; `null` when not a draw (e.g. a mission chest). */\n sliceId: string | null\n /** The player's state after the play; `null` when absent. */\n rewards: ClubRewards | null\n}\n\n/**\n * Cursor pagination of the club listings.\n * @category Club\n */\nexport interface ClubCursorInput {\n /** The previous page's `nextCursor`. Omitted: the first page. */\n cursor?: string\n /** Items per page: an integer from 1 to 100. Omitted: the gateway default. */\n limit?: number\n}\n\n/**\n * Input of {@link ClubApi.listRelatedTournaments}.\n * @category Club\n */\nexport interface ListRelatedClubTournamentsInput extends ClubCursorInput {\n /** External edition (`ext_` followed by letters, digits, `_` or `-`). */\n editionId: string\n}\n\n/**\n * Input of {@link ClubApi.getRanking}.\n * @category Club\n */\nexport interface GetClubRankingInput {\n /** Edition id. */\n editionId: string\n /** Rows: an integer from 1 to 100. Omitted: the gateway default. */\n limit?: number\n}\n\n/**\n * Input of {@link ClubApi.setMembership}: join (with the terms locale shown) or leave.\n * @category Club\n */\nexport type SetClubMembershipInput =\n | {\n /** {@link ClubProgram.versionId}. */\n versionId: string\n /** Join. */\n joined: true\n /** {@link ClubProgram.termsLocale}: the key of the terms the player saw. */\n termsLocale: string\n }\n | {\n /** {@link ClubProgram.versionId}. */\n versionId: string\n /** Leave. */\n joined: false\n }\n\n/**\n * Input of {@link ClubApi.play}.\n * @category Club\n */\nexport interface PlayClubActivityInput {\n /** An activity id, or a mission's `rightId` to open its chest. */\n activityId: string\n /** {@link ClubProgram.versionId} (or the mission's `rightVersionId`). */\n versionId: string\n /** Chosen chest option (`chestOptions[i].id`). */\n optionId?: string\n}\n\n/**\n * Input of {@link ClubApi.redeem}.\n * @category Club\n */\nexport interface RedeemClubRewardInput {\n /** Store item id. */\n rewardId: string\n /** {@link ClubProgram.versionId}. */\n versionId: string\n}\n\n/**\n * Input of {@link ClubApi.registerForTournament}.\n * @category Club\n */\nexport interface RegisterClubTournamentInput {\n /** Edition id. */\n editionId: string\n /** {@link ClubTournament.versionId}. */\n versionId: string\n /** Ticket to consume, when the tournament requires one. */\n ticketId?: string\n}\n\n/**\n * The casino club: program, activities (wheel, scratch, gift), missions with chests, coin store, history and\n * tournaments. Every method requires login. The gateway resolves the texts from the client's locale\n * (`Accept-Language`): change it with the core's `setLocale`.\n *\n * Writes are **idempotent**: each sends an `Idempotency-Key` (the one in `options.idempotencyKey` or one generated per\n * call; printable ASCII up to 128 characters, without surrounding spaces) that the club service stores. To retry a write whose\n * outcome is unknown, call again with the **same** key: the service answers the first result. The club answers a\n * duplicate still in flight with a plain 409 (`ALREADY_EXISTS`, never `KEY_IN_USE`), so a 409 is not a definitive\n * refusal: keep the key after anything but a 400, 403, 404 or 422 ({@link keepsClubIdempotencyKey} tells which).\n * Through `createIgamingMutations` the club writes follow that rule for you; an app that persists the key (e.g. per\n * action in `sessionStorage`, to survive a reload) uses the same helper to decide when to drop it.\n *\n * Errors to expect (identify by `error.code`): `NOT_FOUND` (404, also when the club is not active),\n * `PERMISSION_DENIED` (403), `ALREADY_EXISTS` (409, a conflict with the version, the availability or the account\n * state), `CLUB_WALLET_UNAVAILABLE` (503, or 409 when the wallet currency is not confirmed), `CLUB_RATE_LIMITED`\n * (429), `INVALID_ARGUMENT` (400), `UNAVAILABLE` (503).\n * @category Club\n */\nexport interface ClubApi {\n /**\n * The program, the player's balances, activities, missions and store.\n * @example\n * const { program, rewards } = await igaming.club.getOverview()\n * if (program.enabled && !program.joined && program.canJoin) showJoin(program.terms, program.termsLocale)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n getOverview(params?: NoParams, options?: CallOptions): Promise<ClubOverview>\n /**\n * The player's receipts and balance movements, newest first, cursor-paginated.\n * @example\n * const page = await igaming.club.listHistory({ limit: 30 })\n * const next = page.nextCursor && (await igaming.club.listHistory({ cursor: page.nextCursor, limit: 30 }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `cursor` that is not text or a `limit` outside\n * 1–100; `UNAUTHENTICATED` without a session.\n */\n listHistory(input?: ClubCursorInput, options?: CallOptions): Promise<ClubHistory>\n /**\n * Own and external tournaments, merged and cursor-paginated (gateway default: 50 per page).\n * @example\n * const { items, nextCursor } = await igaming.club.listTournaments()\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a bad `cursor` or `limit`; `NOT_FOUND` when the\n * club is not active.\n */\n listTournaments(input?: ClubCursorInput, options?: CallOptions): Promise<ClubTournamentPage>\n /**\n * Other editions of the same external schedule as `editionId` (the gateway caps the page at 20). A page that\n * answers for another edition is read as empty.\n * @example\n * const { items } = await igaming.club.listRelatedTournaments({ editionId: 'ext_tlt_123', limit: 10 })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an `editionId` that is not an external edition id,\n * or a bad `cursor`/`limit`; `NOT_FOUND` for an unknown edition.\n */\n listRelatedTournaments(\n input: ListRelatedClubTournamentsInput,\n options?: CallOptions,\n ): Promise<ClubRelatedTournamentPage>\n /**\n * A tournament's detail, with the player's registration and award.\n * @example\n * const tournament = await igaming.club.getTournament({ editionId })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `editionId` or one over 128 UTF-8 bytes;\n * `NOT_FOUND` for an unknown edition.\n */\n getTournament(input: { editionId: string }, options?: CallOptions): Promise<ClubTournament>\n /**\n * A tournament's ranking.\n * @example\n * const ranking = await igaming.club.getRanking({ editionId, limit: 20 })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a bad `editionId` or `limit`;\n * `CLUB_RANKING_UNAVAILABLE` (404) when the source cannot disclose it.\n */\n getRanking(input: GetClubRankingInput, options?: CallOptions): Promise<ClubRanking>\n /**\n * Joins the club (accepting the terms shown in `termsLocale`) or leaves it. Idempotent (see {@link ClubApi}).\n * @example\n * const program = await igaming.club.setMembership({ versionId, joined: true, termsLocale })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `versionId`, a `joined` that is not a\n * boolean, an empty `termsLocale` when joining or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) for a stale\n * version.\n */\n setMembership(input: SetClubMembershipInput, options?: CallOptions): Promise<ClubProgram>\n /**\n * Plays an activity, or opens a mission chest (`activityId` = `rightId`, `optionId` = the chosen option).\n * Idempotent (see {@link ClubApi}).\n * @example\n * const { receipt, sliceId } = await igaming.club.play({ activityId, versionId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `activityId`/`versionId`, a non-text\n * `optionId` or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) when it cannot be played now.\n */\n play(input: PlayClubActivityInput, options?: CallOptions): Promise<ClubPlayResult>\n /**\n * Redeems a store item with coins. Idempotent (see {@link ClubApi}).\n * @example\n * const receipt = await igaming.club.redeem({ rewardId: item.id, versionId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `rewardId`/`versionId` or a bad\n * `idempotencyKey`; `ALREADY_EXISTS` (409) without enough coins or stock.\n */\n redeem(input: RedeemClubRewardInput, options?: CallOptions): Promise<ClubReceipt>\n /**\n * Registers the player in an own tournament. Idempotent (see {@link ClubApi}).\n * @example\n * const registration = await igaming.club.registerForTournament({ editionId, versionId: t.versionId })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `editionId`/`versionId`, a non-text\n * `ticketId` or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) when registration is closed.\n */\n registerForTournament(input: RegisterClubTournamentInput, options?: CallOptions): Promise<ClubTournamentRegistration>\n}\n\n/**\n * Whether a failed club write must keep its `Idempotency-Key` for the retry. The club service stores the key and\n * answers a duplicate that is still being processed with a plain 409, the same answer as a stale version: releasing\n * the key after it would let the next tap pay twice. So the key is kept after everything except a definitive\n * refusal (400, 403, 404, 422) or an error that never reached the club (`CONFIGURATION_ERROR`, `ABORTED`): network\n * errors, timeouts, 5xx, 401, 409, 429 and a 2xx outside the format all keep it. `createIgamingMutations` applies it\n * to the `club` writes; use it where the app keeps its own key (e.g. one per action, persisted across a reload).\n * @param error - What the write rejected with.\n * @example\n * try {\n * await igaming.club.redeem({ rewardId, versionId }, { idempotencyKey: pendingKey })\n * forget(pendingKey)\n * } catch (error) {\n * if (!keepsClubIdempotencyKey(error)) forget(pendingKey)\n * throw error\n * }\n * @throws Never throws: anything that is not an `EnginexError` returns `false`.\n * @category Club\n */\nexport function keepsClubIdempotencyKey(error: unknown): boolean {\n if (!isEnginexError(error)) return false\n if (isAmbiguousFailure(error)) return true\n return error.status >= 400 && !DEFINITIVE_CLUB_STATUS.has(error.status)\n}\n\nconst DEFINITIVE_CLUB_STATUS: ReadonlySet<number> = /* @__PURE__ */ new Set([400, 403, 404, 422])\n\n// ─── Schemas ───────────────────────────────────────────────────────────────────────────────────\n\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/\nconst ISO_DAY = /^\\d{4}-\\d{2}-\\d{2}$/\nconst DECIMAL = /^(?:0|[1-9]\\d{0,19})(?:\\.\\d{1,20})?$/\nconst EXTERNAL_EDITION = /^ext_[A-Za-z0-9_-]+$/\nconst GO_ZERO_TIME = /^0001-01-01T00:00:00(?:\\.0+)?(?:Z|[+-]00:00)$/\n\n/**\n * Optional ISO 8601 date-time: absent, `null`, `\"\"`, the epoch (protojson's zero `Timestamp` as `AsTime()`) and\n * Go's zero `time.Time` (`encoding/json`) become `null`. Anything else that is not an RFC 3339 date-time fails.\n */\nconst time = () =>\n z.pipe(\n z.nullish(\n z\n .string()\n .check(\n z.refine(\n (value) => value === '' || (ISO_DATE_TIME.test(value) && !Number.isNaN(Date.parse(value))),\n 'Expected an ISO 8601 date-time',\n ),\n ),\n ),\n z.transform((value): string | null =>\n value == null || value === '' || Date.parse(value) === 0 || GO_ZERO_TIME.test(value) ? null : value,\n ),\n )\n\nconst flag = () => z._default(z.boolean(), false)\nconst textOrEmpty = () => z._default(z.string(), '')\nconst id = () => z.string().check(z.minLength(1, 'Expected a non-empty id'))\nconst localized = () => mapOf(z.string())\n// int64 counters that are not money (coins, XP, quantities): int64 text or a number, safe integers, normal `'warn'`\n// rule (the divergent field arrives raw and is reported).\nconst units = () => z._default(integerText(), 0)\nconst int32 = () =>\n z._default(z.number().check(z.refine((value) => Number.isSafeInteger(value), 'Expected an integer')), 0)\nconst rank = () =>\n z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 1, 'Expected an integer ≥ 1'))\n// Free-text codes the gateway writes in lowercase: lowercased, `''`/absent as `unspecified`, a new value passes.\nconst code = () =>\n z.pipe(\n protoEnum(''),\n z.transform((value) => (value === '' ? 'unspecified' : value)),\n )\n// An optional code: `''`/absent/`null` as `null`, otherwise lowercased.\nconst optionalCode = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((value): string | null => (value ? value.toLowerCase() : null)),\n )\nconst nullable = <T extends z.ZodMiniType>(schema: T) =>\n z.pipe(\n z.nullish(schema),\n z.transform((value): z.output<T> | null => value ?? null),\n )\n\n/** A list (omitted/`null` as `[]`) whose repeated keys keep the first occurrence. */\nfunction uniqueList<T extends z.ZodMiniType>(item: T, key: (value: z.output<T>) => string | undefined) {\n return z.pipe(\n nullableList(item),\n z.transform((items): z.output<T>[] => {\n const seen = new Set<string>()\n return items.filter((value) => {\n // In `'warn'` an item whose identity came in raw (e.g. the `activity` of an activity state as text) has no\n // key: it is dropped, so the app never reads a field of a text where it expects an object.\n const k = typeof value === 'object' && value !== null ? safeKey(() => key(value)) : String(value)\n if (k === undefined || seen.has(k)) return false\n seen.add(k)\n return true\n })\n }),\n )\n}\n\nfunction safeKey(read: () => string | undefined): string | undefined {\n try {\n const value = read()\n return typeof value === 'string' && value !== '' ? value : undefined\n } catch {\n return undefined\n }\n}\n\n// `ClubMoney` (and `ClubSpinDenomination`, same shape): strict even in `'warn'`, like the other money of the SDK.\nconst moneySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubMoney> =>\n z.pipe(\n wire({\n currency: currencyCode(),\n amountMinor: nonNegativeMinorUnits(),\n decimalPlaces: z.optional(decimalPlaces()),\n }),\n z.transform(\n (m): ClubMoney => ({ amount: m.amountMinor, currency: m.currency, decimalPlaces: m.decimalPlaces ?? null }),\n ),\n ),\n)\n\nconst alternateSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubAlternateReward> => wire({ kind: code(), label: localized(), quantity: units() }),\n)\n\nconst rewardSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubReward> =>\n wire({\n id: textOrEmpty(),\n label: localized(),\n kind: code(),\n quantity: units(),\n money: nullable(moneySchema()),\n campaign: nullable(wire({ spins: units(), gameId: optionalText() })),\n cashback: nullable(\n wire({\n percentageBps: int32(),\n period: optionalCode(),\n basis: optionalCode(),\n destination: optionalCode(),\n startsAt: time(),\n endsAt: time(),\n gameIds: uniqueList(z.string(), String),\n zeroBasisAlternate: nullable(alternateSchema()),\n priorAwardAlternate: nullable(alternateSchema()),\n }),\n ),\n manual: nullable(wire({ deliveryType: optionalCode(), instructions: localized() })),\n ttlSeconds: units(),\n editionId: optionalText(),\n ticketOwnedAlternate: nullable(alternateSchema()),\n }),\n)\n\nconst receiptSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubReceipt> =>\n wire({\n id: id(),\n status: code(),\n sourceKind: code(),\n sourceId: optionalText(),\n sliceId: optionalText(),\n reward: nullable(rewardSchema()),\n settlement: nullable(moneySchema()),\n costCoins: units(),\n acceptedAt: time(),\n deliveredAt: time(),\n expiresAt: time(),\n tournamentRank: nullable(rank()),\n ticketConsumed: flag(),\n }),\n)\n\nconst levelSchema = () => wire({ id: id(), name: localized(), minXp: units(), benefit: localized() })\n\nconst programSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubProgram> =>\n wire({\n enabled: flag(),\n joined: flag(),\n membershipRequired: flag(),\n canJoin: flag(),\n historyAvailable: flag(),\n versionId: optionalText(),\n locale: optionalText(),\n termsLocale: optionalText(),\n timeZone: optionalText(),\n currency: z.pipe(\n z._default(currencyOrEmpty(), ''),\n z.transform((value): string | null => value || null),\n ),\n name: localized(),\n terms: localized(),\n coinName: localized(),\n coverUrl: optionalText(),\n levels: uniqueList(levelSchema(), (level) => level.id),\n }),\n)\n\nconst activitySchema = () =>\n wire({\n activity: wire({\n id: id(),\n kind: code(),\n name: localized(),\n terms: localized(),\n coverUrl: optionalText(),\n wheelTheme: optionalCode(),\n playLabel: localized(),\n slices: uniqueList(wire({ id: id(), reward: nullable(rewardSchema()) }), (slice) => slice.id),\n }),\n canPlay: flag(),\n unavailableReason: optionalCode(),\n latestReceipt: nullable(receiptSchema()),\n availableAt: time(),\n })\n\nconst missionSchema = () =>\n wire({\n mission: wire({\n id: id(),\n title: localized(),\n terms: localized(),\n recurrence: code(),\n countBy: code(),\n target: units(),\n coverUrl: optionalText(),\n }),\n editionId: optionalText(),\n progress: units(),\n rightId: optionalText(),\n rightVersionId: optionalText(),\n chestOptions: nullableList(rewardSchema()),\n canClaim: flag(),\n receipt: nullable(receiptSchema()),\n endsAt: time(),\n claimExpiresAt: time(),\n stampedDays: uniqueList(\n z\n .string()\n .check(\n z.refine((value) => ISO_DAY.test(value) && !Number.isNaN(Date.parse(value)), 'Expected a YYYY-MM-DD day'),\n ),\n String,\n ),\n })\n\nconst storeItemSchema = () =>\n wire({\n item: wire({\n id: id(),\n label: localized(),\n terms: localized(),\n costCoins: units(),\n reward: nullable(rewardSchema()),\n coverUrl: optionalText(),\n }),\n canRedeem: flag(),\n unavailableReason: optionalCode(),\n })\n\nconst rewardsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubRewards> =>\n wire({\n xp: units(),\n coins: units(),\n levelId: optionalText(),\n activities: uniqueList(activitySchema(), (state) => state.activity.id),\n // The same mission may hold several rights (one per period): a repeat is the same mission, right and period.\n missions: uniqueList(missionSchema(), (state) =>\n typeof state.mission.id === 'string'\n ? JSON.stringify([state.mission.id, state.rightId ?? state.editionId, state.endsAt])\n : undefined,\n ),\n storeItems: uniqueList(storeItemSchema(), (state) => state.item.id),\n }),\n)\n\nconst overviewSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubOverview> => wire({ program: programSchema(), rewards: nullable(rewardsSchema()) }),\n)\n\nconst nextCursor = () =>\n z.pipe(\n optionalText(),\n z.transform((value) => value ?? undefined),\n )\n\n/** Drops an `undefined` `nextCursor`, so the last page has no such key. */\nfunction compactCursor<T extends { nextCursor?: string | undefined }>(page: T): T {\n if (page.nextCursor === undefined) delete page.nextCursor\n return page\n}\n\nconst historySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubHistory> =>\n z.pipe(\n wire({\n receipts: uniqueList(receiptSchema(), (receipt) => receipt.id),\n movements: uniqueList(\n wire({ id: id(), kind: code(), units: units(), sourceId: optionalText(), occurredAt: time() }),\n (movement) => movement.id,\n ),\n nextCursor: nextCursor(),\n }),\n z.transform(compactCursor),\n ),\n)\n\nconst registrationSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournamentRegistration> =>\n wire({ id: id(), editionId: id(), versionId: optionalText(), joinedAt: time() }),\n)\n\nconst isMinorUnits = (v: unknown): boolean =>\n (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) ||\n (typeof v === 'string' && /^\\d+$/.test(v) && Number.isSafeInteger(Number(v)))\n\n// Not strict: a value outside the format is a normal issue (reported, the field arriving raw in `'warn'`), never\n// rounded (≥ 2^53 as text fails like any other malformed amount).\nconst announcedMoney = () =>\n z.pipe(\n wire({\n currency: z.string().check(z.regex(/^[A-Z]{3}$/, 'Expected a currency code, e.g. BRL')),\n amountMinor: z.union([z.string(), z.number()]).check(z.refine(isMinorUnits, 'Expected non-negative minor units')),\n decimalPlaces: z.optional(\n z.number().check(z.refine((v) => Number.isInteger(v) && v >= 0 && v <= 8, 'Expected decimal places 0 to 8')),\n ),\n }),\n // In `'warn'` the amount may come in raw: only an exact non-negative integer becomes `amount`; anything else stays\n // as it came, so `hasValidAnnouncedAmount` drops the prize (never `Number('1e3')`, never a rounded value).\n z.transform(\n (m): ClubMoney => ({\n amount: isMinorUnits(m.amountMinor) ? Number(m.amountMinor) || 0 : (m.amountMinor as unknown as number),\n currency: m.currency,\n decimalPlaces: m.decimalPlaces ?? null,\n }),\n ),\n )\n\nconst prizeSchema = () =>\n wire({\n fromRank: int32(),\n toRank: int32(),\n reward: nullable(rewardSchema()),\n announcedAmount: nullable(announcedMoney()),\n terms: localized(),\n offerTerms: nullable(\n wire({\n spinDenomination: nullable(moneySchema()),\n wageringMultiplier: nullable(z.string().check(z.regex(DECIMAL, 'Expected an exact decimal'))),\n validForSeconds: nullable(integerText()),\n expiresAt: time(),\n grantEndsAt: time(),\n }),\n ),\n })\n\n/** `false` for a prize whose announced amount came in raw (recovered in `'warn'`): it is dropped, already reported. */\nfunction hasValidAnnouncedAmount(prize: { announcedAmount: unknown }): boolean {\n const amount = prize.announcedAmount\n if (amount === null) return true\n if (typeof amount !== 'object') return false\n const { amount: value, currency } = amount as Record<string, unknown>\n return (\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value >= 0 &&\n typeof currency === 'string' &&\n /^[A-Z]{3}$/.test(currency)\n )\n}\n\nconst tournamentSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournament> =>\n wire({\n id: id(),\n source: code(),\n versionId: optionalText(),\n title: localized(),\n terms: localized(),\n status: code(),\n startsAt: time(),\n endsAt: time(),\n updatedAt: time(),\n scoringRule: optionalCode(),\n tieBreak: optionalCode(),\n currency: z.pipe(\n z._default(currencyOrEmpty(), ''),\n z.transform((value): string | null => value || null),\n ),\n timeZone: optionalText(),\n gameIds: uniqueList(z.string(), String),\n // An announced amount (an external listing) is display data, not a prize the player wins: one outside the\n // format (negative, a fraction, ≥ 2^53, a bad currency) fails without the strict mark, so `'warn'` reports it\n // and drops that prize instead of failing the whole page. Strict mode still rejects it.\n prizes: z.pipe(\n nullableList(prizeSchema()),\n z.transform((prizes) => prizes.filter(hasValidAnnouncedAmount)),\n ),\n joinMode: optionalCode(),\n locale: optionalText(),\n rankingAvailable: flag(),\n canRegister: flag(),\n requiresTicket: flag(),\n registration: nullable(registrationSchema()),\n personalAward: nullable(receiptSchema()),\n stale: flag(),\n registrationStartsAt: time(),\n registrationEndsAt: time(),\n coverUrl: optionalText(),\n }),\n)\n\nconst tournamentPageSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournamentPage> =>\n z.pipe(\n wire({\n items: uniqueList(tournamentSchema(), (tournament) => tournament.id),\n externalAvailable: flag(),\n externalStale: flag(),\n nextCursor: nextCursor(),\n }),\n z.transform(compactCursor),\n ),\n)\n\nconst relatedPageSchema = /* @__PURE__ */ lazy(() =>\n wire({\n relatedTo: textOrEmpty(),\n items: uniqueList(\n wire({\n id: z.string().check(z.regex(EXTERNAL_EDITION, 'Expected an external edition id')),\n title: localized(),\n status: code(),\n startsAt: time(),\n endsAt: time(),\n }),\n (item) => item.id,\n ),\n nextCursor: nextCursor(),\n }),\n)\n\nconst rankSchema = () => wire({ position: rank(), displayName: textOrEmpty(), score: textOrEmpty() })\n\nconst rankingSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubRanking> =>\n wire({ entries: nullableList(rankSchema()), personal: nullable(rankSchema()), updatedAt: time(), final: flag() }),\n)\n\nconst playSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubPlayResult> =>\n wire({ receipt: receiptSchema(), sliceId: optionalText(), rewards: nullable(rewardsSchema()) }),\n)\n\n// ─── Input checks ──────────────────────────────────────────────────────────────────────────────\n\nconst BASE = '/casino/club'\n// The gateway's `clubSetPathID` and `clubMutationKey` refuse anything above 128 bytes (Go `len`).\nconst MAX_ID = 128\nconst MAX_IDEMPOTENCY_KEY = 128\n\nconst ROUTES = {\n overview: { method: 'GET', path: BASE },\n history: { method: 'GET', path: `${BASE}/history` },\n tournaments: { method: 'GET', path: `${BASE}/tournaments` },\n tournament: { method: 'GET', path: `${BASE}/tournaments/{editionId}` },\n ranking: { method: 'GET', path: `${BASE}/tournaments/{editionId}/ranking` },\n membership: { method: 'PUT', path: `${BASE}/membership` },\n play: { method: 'POST', path: `${BASE}/activities/{activityId}/plays` },\n redeem: { method: 'POST', path: `${BASE}/rewards/{rewardId}/redemptions` },\n register: { method: 'POST', path: `${BASE}/tournaments/{editionId}/registrations` },\n} satisfies Record<string, Route>\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Length in UTF-8 bytes: the gateway's `len()` in Go, not JavaScript's UTF-16 units. */\nfunction utf8Length(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\nfunction idProblem(name: string, field: string, value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' && utf8Length(value) <= MAX_ID\n ? undefined\n : `${name}: ${field} must be non-empty text up to ${MAX_ID} UTF-8 bytes.`\n}\n\nfunction optionalTextProblem(name: string, field: string, value: unknown): string | undefined {\n return value === undefined || typeof value === 'string' ? undefined : `${name}: ${field} must be text.`\n}\n\nfunction limitProblem(name: string, value: unknown): string | undefined {\n return value === undefined || (typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 100)\n ? undefined\n : `${name}: limit must be an integer from 1 to 100.`\n}\n\nfunction cursorProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (!isObject(input)) return `${name}: input must be an object.`\n return optionalTextProblem(name, 'cursor', input.cursor) ?? limitProblem(name, input.limit)\n}\n\nfunction keyProblem(name: string, options: CallOptions | undefined): string | undefined {\n const key = options?.idempotencyKey\n if (key === undefined || key === '') return undefined\n // A header value is a byte string: only printable ASCII travels as itself (an emoji makes `fetch` throw, a Latin-1\n // letter reaches the gateway as other bytes), so one ASCII character is one of the gateway's bytes.\n return typeof key === 'string' &&\n key === key.trim() &&\n /^[\\x20-\\x7E]+$/.test(key) &&\n key.length <= MAX_IDEMPOTENCY_KEY\n ? undefined\n : `${name}: idempotencyKey must be printable ASCII without surrounding spaces, up to ${MAX_IDEMPOTENCY_KEY} characters.`\n}\n\nfunction membershipProblem(input: unknown): string | undefined {\n const name = 'club.setMembership'\n if (!isObject(input)) return `${name}: input must be { versionId, joined, termsLocale? }.`\n if (typeof input.joined !== 'boolean') return `${name}: joined must be true or false.`\n const versionProblem = idProblem(name, 'versionId', input.versionId)\n if (versionProblem) return versionProblem\n if (input.joined && (typeof input.termsLocale !== 'string' || input.termsLocale.trim() === ''))\n return `${name}: termsLocale must be non-empty text when joining.`\n return undefined\n}\n\nconst segment = (value: string) => encodeURIComponent(value)\n\n/**\n * In `'warn'` a required message of the wrong type (text, a number) arrives raw. The overview without its program and\n * a play without its receipt mean nothing: they reject with `VALIDATION_ERROR` (status 200, so an idempotent retry\n * keeps the key and replays the result) instead of handing the app a text where it reads an object.\n */\nfunction requireObject<T extends object>(transport: ExtensionTransport, route: Route, field: keyof T & string) {\n return (value: T): T => {\n if (isObject(value[field])) return value\n throw transport.reportError(\n {\n code: 'VALIDATION_ERROR',\n message: `Unexpected gateway response on ${route.method} ${route.path}: ${field}`,\n status: 200,\n },\n route,\n )\n }\n}\n\n/** Creates the `club` namespace. @internal */\nexport function createClubApi(transport: ExtensionTransport): ClubApi {\n const get = <T>(\n path: string,\n query: Record<string, string | number | undefined>,\n schema: z.ZodMiniType<T>,\n options?: CallOptions,\n ) => transport.request({ method: 'GET', path, query, auth: 'required', schema, options })\n\n const write = <T>(\n method: 'POST' | 'PUT',\n path: string,\n body: Record<string, unknown>,\n schema: z.ZodMiniType<T>,\n options: CallOptions | undefined,\n ) =>\n // The key goes only in the `Idempotency-Key` header: the gateway reads it from there when the body has none\n // (a body key that differed from the header would be refused).\n transport.request({ method, path, body, auth: 'required', idempotent: true, schema, options })\n\n return {\n getOverview: (_params, options) =>\n get(BASE, {}, overviewSchema(), options).then(requireObject<ClubOverview>(transport, ROUTES.overview, 'program')),\n\n listHistory: (input, options) => {\n const problem = cursorProblem('club.listHistory', input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.history)\n return get(\n ROUTES.history.path,\n { cursor: input?.cursor || undefined, limit: input?.limit },\n historySchema(),\n options,\n )\n },\n\n listTournaments: (input, options) => {\n const problem = cursorProblem('club.listTournaments', input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournaments)\n return get(\n ROUTES.tournaments.path,\n { cursor: input?.cursor || undefined, limit: input?.limit },\n tournamentPageSchema(),\n options,\n )\n },\n\n listRelatedTournaments: (input, options) => {\n const name = 'club.listRelatedTournaments'\n const problem = !isObject(input)\n ? `${name}: input must be { editionId }.`\n : typeof input.editionId !== 'string' ||\n utf8Length(input.editionId) > MAX_ID ||\n !EXTERNAL_EDITION.test(input.editionId)\n ? `${name}: editionId must be an external edition id (ext_...), up to ${MAX_ID} characters.`\n : cursorProblem(name, input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournaments)\n return get(\n ROUTES.tournaments.path,\n { relatedTo: input.editionId, cursor: input.cursor || undefined, limit: input.limit },\n relatedPageSchema(),\n options,\n ).then(({ relatedTo, items, nextCursor: cursor }): ClubRelatedTournamentPage => {\n // A page about another edition is not about this one: read as empty, never mixed in.\n if (relatedTo !== input.editionId) return { items: [] }\n return cursor === undefined ? { items } : { items, nextCursor: cursor }\n })\n },\n\n getTournament: (input, options) => {\n const problem = idProblem('club.getTournament', 'editionId', isObject(input) ? input.editionId : undefined)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournament)\n return get(`${BASE}/tournaments/${segment(input.editionId)}`, {}, tournamentSchema(), options)\n },\n\n getRanking: (input, options) => {\n const name = 'club.getRanking'\n const problem = isObject(input)\n ? (idProblem(name, 'editionId', input.editionId) ?? limitProblem(name, input.limit))\n : `${name}: input must be { editionId }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.ranking)\n return get(\n `${BASE}/tournaments/${segment(input.editionId)}/ranking`,\n { limit: input.limit },\n rankingSchema(),\n options,\n )\n },\n\n setMembership: (input, options) => {\n const problem = membershipProblem(input) ?? keyProblem('club.setMembership', options)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.membership)\n const body = input.joined\n ? { versionId: input.versionId, joined: true, termsLocale: input.termsLocale }\n : { versionId: input.versionId, joined: false }\n return write('PUT', ROUTES.membership.path, body, programSchema(), options)\n },\n\n play: (input, options) => {\n const name = 'club.play'\n const problem = isObject(input)\n ? (idProblem(name, 'activityId', input.activityId) ??\n idProblem(name, 'versionId', input.versionId) ??\n optionalTextProblem(name, 'optionId', input.optionId) ??\n keyProblem(name, options))\n : `${name}: input must be { activityId, versionId, optionId? }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.play)\n const body: Record<string, unknown> = { versionId: input.versionId }\n if (input.optionId) body.optionId = input.optionId\n return write('POST', `${BASE}/activities/${segment(input.activityId)}/plays`, body, playSchema(), options).then(\n requireObject<ClubPlayResult>(transport, ROUTES.play, 'receipt'),\n )\n },\n\n redeem: (input, options) => {\n const name = 'club.redeem'\n const problem = isObject(input)\n ? (idProblem(name, 'rewardId', input.rewardId) ??\n idProblem(name, 'versionId', input.versionId) ??\n keyProblem(name, options))\n : `${name}: input must be { rewardId, versionId }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.redeem)\n return write(\n 'POST',\n `${BASE}/rewards/${segment(input.rewardId)}/redemptions`,\n { versionId: input.versionId },\n receiptSchema(),\n options,\n )\n },\n\n registerForTournament: (input, options) => {\n const name = 'club.registerForTournament'\n const problem = isObject(input)\n ? (idProblem(name, 'editionId', input.editionId) ??\n idProblem(name, 'versionId', input.versionId) ??\n optionalTextProblem(name, 'ticketId', input.ticketId) ??\n keyProblem(name, options))\n : `${name}: input must be { editionId, versionId, ticketId? }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.register)\n const body: Record<string, unknown> = { versionId: input.versionId }\n if (input.ticketId) body.ticketId = input.ticketId\n return write(\n 'POST',\n `${BASE}/tournaments/${segment(input.editionId)}/registrations`,\n body,\n registrationSchema(),\n options,\n )\n },\n }\n}\n","/**\n * iGaming query and mutation factories, compatible with TanStack Query v5 (`useQuery`,\n * `useMutation`, `prefetchQuery`), without depending on it. Same key conventions as\n * `@getenginex/sdk/query`.\n * @module @getenginex/sdk-igaming/query\n */\n\nimport { isEnginexError, type CallOptions } from '@getenginex/sdk'\nimport {\n queryScope,\n type IdempotentMutationsOf,\n type MutationsOf,\n type QueriesOf,\n type QueryScope,\n} from '@getenginex/sdk/query'\nimport type { IgamingClient } from '../client'\nimport { LOCALE } from '../internal/input'\nimport type { BetsApi } from '../modules/bets'\nimport type { BonusApi } from '../modules/bonus'\nimport type { CasinoApi } from '../modules/casino'\nimport { keepsClubIdempotencyKey, type ClubApi } from '../modules/club'\nimport type { LoyaltyApi } from '../modules/loyalty'\nimport type { MissionsApi } from '../modules/missions'\nimport type { ReferralsApi } from '../modules/referrals'\nimport type { SportsbookApi } from '../modules/sportsbook'\n\n/**\n * iGaming query factories, one per read method: `q.<namespace>.<method>(input)` returns\n * `{ queryKey, queryFn }`. Obtained with {@link createIgamingQueries}.\n * @category Queries\n */\nexport interface IgamingQueries {\n /** Catalog and lobby jackpots (public) and, with login, sessions, history and biggest winners. */\n readonly casino: QueriesOf<\n CasinoApi,\n | 'listGames'\n | 'listCategories'\n | 'listProviders'\n | 'getGame'\n | 'listJackpots'\n | 'listJackpotGames'\n | 'listSessions'\n | 'getHistory'\n | 'getBiggestWinners'\n >\n /** Casino club: overview, history, tournaments, related editions, a tournament and its ranking. */\n readonly club: QueriesOf<\n ClubApi,\n 'getOverview' | 'listHistory' | 'listTournaments' | 'listRelatedTournaments' | 'getTournament' | 'getRanking'\n >\n /** Public offers (no login) and, with login, offers, participations, bonus overview and positions. */\n readonly bonus: QueriesOf<\n BonusApi,\n | 'listPublicOffers'\n | 'listOffers'\n | 'getOffer'\n | 'listParticipations'\n | 'getParticipation'\n | 'getOverview'\n | 'listPositions'\n >\n /** Operator missions and the player's own. */\n readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>\n /** Points balance, tier and benefits. */\n readonly loyalty: QueriesOf<LoyaltyApi, 'get'>\n /** Referral code, program rules, totals and history. */\n readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>\n /** The player's bets, a bet's details and its cash-out offer. */\n readonly bets: QueriesOf<BetsApi, 'list' | 'get' | 'getCashoutOffer'>\n}\n\n/**\n * iGaming mutations, one per write method: `m.<namespace>.<method>()` returns\n * `{ mutationKey, mutationFn, invalidates }`. Obtained with {@link createIgamingMutations}.\n * @category Queries\n */\nexport interface IgamingMutations {\n /** Game launch (`launchGame`, with `gcTime: 0`: the game URL carries credentials). */\n readonly casino: MutationsOf<CasinoApi, 'launchGame'>\n /** Club membership, plays, redemptions and tournament registration (idempotent: they accept `{ idempotencyKey }`). */\n readonly club: IdempotentMutationsOf<ClubApi, 'setMembership' | 'play' | 'redeem' | 'registerForTournament'>\n /** Opt-in, redemption (idempotent: they accept `{ idempotencyKey }`) and promo code check. */\n readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> &\n MutationsOf<BonusApi, 'resolvePromoCode'>\n /** Points redemption (idempotent: it accepts `{ idempotencyKey }`). */\n readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>\n /** Sportsbook session (`gcTime: 0`: the URL carries the operator token). */\n readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>\n /** Bet cash-out (idempotent: it accepts `{ idempotencyKey }`). */\n readonly bets: IdempotentMutationsOf<BetsApi, 'cashout'>\n}\n\ntype Method = (input: unknown, options?: CallOptions) => Promise<unknown>\n\n// Calls `igaming[namespace][method]` at request time (not at creation), keeping `this`.\nconst methodOf = (igaming: object, namespace: string, method: string) => (input: unknown, options: CallOptions) =>\n ((igaming as Record<string, Record<string, Method>>)[namespace]![method] as Method).call(\n (igaming as Record<string, unknown>)[namespace],\n input,\n options,\n )\n\n// Reads without a session (the method sends no token): `public` key, no `staleTime`.\nconst PUBLIC_READS = {\n casino: ['listGames', 'listCategories', 'listProviders', 'getGame', 'listJackpots', 'listJackpotGames'],\n bonus: ['listPublicOffers'],\n} as const\n\n// Player reads: `user` key with the session's `userId`.\nconst USER_READS = {\n casino: ['listSessions', 'getHistory', 'getBiggestWinners'],\n club: ['getOverview', 'listHistory', 'listTournaments', 'listRelatedTournaments', 'getTournament', 'getRanking'],\n bonus: ['listOffers', 'getOffer', 'listParticipations', 'getParticipation', 'getOverview', 'listPositions'],\n missions: ['list', 'listMine'],\n loyalty: ['get'],\n referrals: ['get', 'listHistory'],\n bets: ['list', 'get', 'getCashoutOffer'],\n} as const\n\n// Namespaces whose responses depend on the client's locale: their keys end with `{ locale }`.\nconst LOCALE_KEYED: ReadonlySet<string> = /* @__PURE__ */ new Set(['club'])\n\n/** The client's locale right now (`null` without one, or with a core older than 0.12.0). */\nfunction localeOf(igaming: object): string | null {\n const read = (igaming as Record<symbol, (() => string | undefined) | undefined>)[LOCALE]\n return (typeof read === 'function' ? read() : undefined) ?? null\n}\n\ntype Invalidation = (scope: QueryScope) => readonly (readonly unknown[])[]\nconst userKeys =\n (...prefixes: [namespace: string, method?: string][]): Invalidation =>\n (scope) =>\n prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method))\nconst none: Invalidation = () => []\n\ninterface Write {\n /** What the write leaves stale. The core's prefixes (`wallet`) come from `scope.userPrefix`. */\n invalidates: Invalidation\n /** Sends `Idempotency-Key` (accepts `{ idempotencyKey }`). */\n idempotent?: boolean\n /** Entry or result with a credential: `gcTime: 0`. */\n sensitive?: boolean\n /** Extra failures that keep the key (core `>=0.12.0`; older cores ignore it). */\n keepsKey?: (error: unknown) => boolean\n /** What a 409 leaves stale (`invalidatesOnError`). */\n conflict?: Invalidation\n}\n\nconst isConflict = (error: unknown) => isEnginexError(error) && error.status === 409\n\n// The club writes keep the key after a 409 (an in-flight duplicate looks like any conflict) and, on a 409 (a stale\n// `versionId`, a wallet not confirmed), refresh what the retry must read again.\nconst CLUB_WRITE = { idempotent: true, keepsKey: keepsClubIdempotencyKey } as const\nconst CLUB_MONEY = userKeys(['club', 'getOverview'], ['club', 'listHistory'], ['bonus'], ['wallet'])\n\nconst WRITES: Record<string, Record<string, Write>> = {\n casino: { launchGame: { invalidates: userKeys(['casino', 'listSessions']), sensitive: true } },\n club: {\n setMembership: { ...CLUB_WRITE, invalidates: userKeys(['club']), conflict: userKeys(['club', 'getOverview']) },\n // A play or a redemption moves coins, XP, the history and maybe a bonus or the balance; never the tournaments.\n play: { ...CLUB_WRITE, invalidates: CLUB_MONEY, conflict: userKeys(['club', 'getOverview']) },\n redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, conflict: userKeys(['club', 'getOverview']) },\n registerForTournament: {\n ...CLUB_WRITE,\n invalidates: userKeys(['club']),\n conflict: userKeys(['club', 'getOverview'], ['club', 'listTournaments'], ['club', 'getTournament']),\n },\n },\n bonus: {\n resolvePromoCode: { invalidates: none, sensitive: true },\n optIn: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n claim: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n redeemPromoCode: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true, sensitive: true },\n },\n loyalty: { redeem: { invalidates: userKeys(['loyalty'], ['wallet']), idempotent: true } },\n sportsbook: { createSession: { invalidates: none, sensitive: true } },\n bets: { cashout: { invalidates: userKeys(['bets'], ['wallet']), idempotent: true } },\n}\n\n/**\n * Creates the iGaming query factories: one per read method, with the same name and the same input\n * as the method (`q.casino.listGames({ page })`). Each call returns `{ queryKey, queryFn }`, compatible\n * with TanStack Query v5's `useQuery`/`prefetchQuery`/`fetchQuery`. It makes no request.\n *\n * - Reads without a session (`casino.listGames/listCategories/listProviders/getGame/listJackpots/listJackpotGames`,\n * `bonus.listPublicOffers`): key `['enginex', 'public', namespace, method, input?]`.\n * - The `club` reads also end with `{ locale }` (the client's locale, `null` without one): the club answers in that\n * locale, so after `setLocale` a factory called again returns a new key and the program (with its\n * `termsLocale`) is fetched again instead of a join recording consent under the old terms. Prefix invalidation\n * (`['enginex', 'user', userId, 'club']`) still matches every locale. Needs core `>=0.12.0` (older: `null`).\n * - Player reads (the others): key `['enginex', 'user', userId, namespace, method, input?]`,\n * with the session's `userId` when the factory is called; without a session, `'anonymous'` and the `queryFn`\n * rejects with `UNAUTHENTICATED` without a request (the same if the session switches user before the `fetch`).\n * - `queryFn` forwards the context's `signal`: canceling the query aborts the `fetch`.\n * - None carries `staleTime`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useQuery } from '@tanstack/react-query'\n * import { createIgamingQueries } from '@getenginex/sdk-igaming/query'\n *\n * const q = createIgamingQueries(igaming)\n * const games = useQuery(q.casino.listGames({ category: 'slots' }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming` (e.g. a\n * `{ ...igaming }` copy). Identify with `isEnginexError(error, 'CONFIGURATION_ERROR')`.\n * @category Queries\n */\nexport function createIgamingQueries(igaming: IgamingClient): IgamingQueries {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (input?: unknown) => unknown>> = {}\n const add = (\n table: Record<string, readonly string[]>,\n build: (namespace: string, method: string, input: unknown) => unknown,\n ) => {\n for (const [namespace, methods] of Object.entries(table)) {\n const factories = (out[namespace] ??= {})\n for (const method of methods) factories[method] = (input) => build(namespace, method, input)\n }\n }\n add(PUBLIC_READS, (namespace, method, input) =>\n scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input),\n )\n add(USER_READS, (namespace, method, input) => {\n const options = scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input)\n if (!LOCALE_KEYED.has(namespace)) return options\n // The club answers in the client's locale (texts, `termsLocale`): a `setLocale` must not reuse the cached\n // program, or a join would record consent under the terms of the old language.\n return { ...options, queryKey: [...options.queryKey, { locale: localeOf(igaming) }] }\n })\n return out as unknown as IgamingQueries\n}\n\n/**\n * Creates the iGaming mutations: one per write method, with the same name as the method\n * (`m.loyalty.redeem()`). Each call returns `{ mutationKey, mutationFn, invalidates }`, compatible\n * with TanStack Query v5's `useMutation`; `invalidates(input, result)` lists the prefixes the write\n * leaves stale (with the session's `userId` at call time; call it only after success):\n *\n * - `bonus.optIn/claim/redeemPromoCode` → `bonus` and `wallet` (the core's balance);\n * - `loyalty.redeem` → `loyalty` and `wallet`;\n * - `bets.cashout` → `bets` and `wallet`;\n * - `club.play/redeem` → `club.getOverview`, `club.listHistory`, `bonus` and `wallet` (a reward may credit a bonus or\n * the balance; the tournaments and rankings are not refetched); `club.setMembership/registerForTournament` →\n * `club`. The club writes also carry `invalidatesOnError`: on a 409 (a stale `versionId`) they refresh\n * `club.getOverview` (and, for `registerForTournament`, the tournaments), like the player did on settle;\n * `useEnginexMutation` runs it in `onError`, plain TanStack calls it in its own `onError`;\n * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` and\n * `sportsbook.createSession` → nothing.\n *\n * `mutationKey` is `['enginex', namespace, method]`, without the input. The ones that send `Idempotency-Key`\n * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`, `bets.cashout`, the four `club` writes) reuse the key only after an ambiguous\n * failure (network, timeout, 5xx, `KEY_IN_USE` or `VALIDATION_ERROR` after a 2xx) with the same input,\n * on this options object (see the core's `createMutations`), and accept `{ idempotencyKey }` on the factory. The\n * `club` writes also keep it after a 409 or 429 and release it only on 400/403/404/422 (see\n * `keepsClubIdempotencyKey`; needs core `>=0.12.0`). The\n * ones that carry credentials in the input or the result (promo code, game URL, sportsbook\n * session) have `gcTime: 0`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useMutation } from '@tanstack/react-query'\n * import { createIgamingMutations } from '@getenginex/sdk-igaming/query'\n *\n * const m = createIgamingMutations(igaming)\n * const redeem = m.loyalty.redeem()\n * const result = await redeem.mutationFn({ points: 500, redemptionType: 'bonus' })\n * for (const queryKey of redeem.invalidates({ points: 500, redemptionType: 'bonus' }, result)) {\n * await queryClient.invalidateQueries({ queryKey })\n * }\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming`.\n * @category Queries\n */\nexport function createIgamingMutations(igaming: IgamingClient): IgamingMutations {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (options?: { idempotencyKey?: string }) => unknown>> = {}\n for (const [namespace, methods] of Object.entries(WRITES)) {\n const factories = (out[namespace] ??= {})\n for (const [method, write] of Object.entries(methods)) {\n factories[method] = (options) => {\n const scoped: {\n idempotent?: boolean\n idempotencyKey?: string\n gcTime?: number\n keepsKey?: (error: unknown) => boolean\n } = {}\n if (write.idempotent === true) {\n scoped.idempotent = true\n if (write.keepsKey) scoped.keepsKey = write.keepsKey\n if (options?.idempotencyKey !== undefined) scoped.idempotencyKey = options.idempotencyKey\n }\n if (write.sensitive === true) scoped.gcTime = 0\n const mutation = scope.mutation(\n namespace,\n method,\n methodOf(igaming, namespace, method),\n () => write.invalidates(scope),\n scoped,\n )\n const conflict = write.conflict\n // Set here (not through the scope) so it holds with any core; the adapters run it in `onError`.\n if (conflict) mutation.invalidatesOnError = (_input, error) => (isConflict(error) ? conflict(scope) : [])\n return mutation\n }\n }\n }\n return out as unknown as IgamingMutations\n}\n"]}
1
+ {"version":3,"sources":["../../src/internal/input.ts","../../src/modules/club.ts","../../src/query/index.ts"],"names":["isEnginexError","isAmbiguousFailure","queryScope"],"mappings":";;;;;;;;;;AA0CO,IAAM,MAAA,mBAAwC,MAAA,CAAO,GAAA,CAAI,gCAAgC,CAAA;ACuwBzF,SAAS,wBAAwB,KAAA,EAAyB;AAC/D,EAAA,IAAI,CAACA,kBAAA,CAAe,KAAK,CAAA,EAAG,OAAO,KAAA;AACnC,EAAA,IAAIC,4BAAA,CAAmB,KAAK,CAAA,EA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MAAM,CAAA;AAAA,UACnC,MAAM,KAAA,CAAM,WAAA,CAAY,KAAK,CAAA;AAAA,UAC7B;AAAA,SACF;AACA,QAAA,MAAM,UAAU,KAAA,CAAM,OAAA;AAEtB,QAAA,IAAI,OAAA;AACF,UAAA,QAAA,CAAS,kBAAA,GAAqB,CAAC,MAAA,EAAQ,KAAA,KAAW,OAAA,CAAQ,IAAA,CAAK,KAAK,CAAA,GAAI,OAAA,CAAQ,WAAA,CAAY,KAAK,CAAA,GAAI,EAAC;AACxG,QAAA,OAAO,QAAA;AAAA,MACT,CAAA;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["import type { ExtensionTransport } from '@getenginex/sdk/extension'\n\n/** Route of a call, to report the input error to `onError`. @internal */\nexport interface Route {\n /** HTTP method. */\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n /** Path after `/api/v1`. */\n path: string\n}\n\n/**\n * Rejects with `CONFIGURATION_ERROR` (without a request) notifying `onError`, like the core does with invalid\n * input. `message` never carries the received value. The error comes out of `reportError`, which normalizes it into\n * `EnginexError` (the core does not export the constructor to product packages). @internal\n */\nexport function rejectInput(transport: ExtensionTransport, message: string, route: Route): Promise<never> {\n return Promise.reject(\n transport.reportError({ code: 'CONFIGURATION_ERROR', message, status: 0 }, { ...route, attempt: 0 }),\n )\n}\n\n/**\n * Checks `{ page, perPage }` of a listing: `page` an integer ≥ 1, `perPage` an integer from 1 to 100.\n * Returns the problem message or `undefined` if everything is fine. @internal\n */\nexport function pageInputProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${name}: input must be an object.`\n const { page, perPage } = input as { page?: unknown; perPage?: unknown }\n if (page !== undefined && (typeof page !== 'number' || !Number.isSafeInteger(page) || page < 1))\n return `${name}: page must be an integer ≥ 1.`\n if (\n perPage !== undefined &&\n (typeof perPage !== 'number' || !Number.isInteger(perPage) || perPage < 1 || perPage > 100)\n )\n return `${name}: perPage must be an integer from 1 to 100.`\n return undefined\n}\n/**\n * Symbol (non-enumerable) of the client's current locale getter on the iGaming object. `Symbol.for`: `/query` may be\n * another copy of this package's code (CommonJS entries are separate files). @internal\n */\nexport const LOCALE: unique symbol = /* @__PURE__ */ Symbol.for('@getenginex/sdk-igaming/locale') as never\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport { isEnginexError, type CallOptions, type NoParams } from '@getenginex/sdk'\nimport {\n currencyCode,\n decimalPlaces,\n isAmbiguousFailure,\n lazy,\n mapOf,\n wire,\n type ExtensionTransport,\n} from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalText } from '../internal/optional-values'\nimport { currencyOrEmpty, integerText, nonNegativeMinorUnits, protoEnum } from '../internal/schemas'\n\n// Wire format: every `/casino/club` route answers WITHOUT the `{ success, data }` envelope. All of them but one are\n// protojson written by `writeClubResponse` with `EmitDefaultValues: true`: scalars, lists and maps are always\n// present (an empty list as `[]`, int64 as text), while an unset message or an unset proto3 `optional` is omitted.\n// The exception is `GET /casino/club/tournaments?relatedTo=`, written by `encoding/json` (`httputil.JSON`): a nil\n// map comes out as `null` and a zero `time.Time` as `\"0001-01-01T00:00:00Z\"`. The SDK reads both shapes the same\n// way: an omitted or `null` list is `[]`, an omitted or `null` message is `null`, an empty text that means \"none\" is\n// `null`, and an absent date (omitted, `null`, `\"\"`, the epoch or Go's zero time) is `null`.\n\n// ─── Types ─────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Text per locale, as the operator wrote it (`{ \"pt-BR\": \"...\", \"en\": \"...\" }`). `{}` when the gateway sends none.\n * @category Club\n */\nexport type ClubLocalized = Record<string, string>\n\n/**\n * Money of the club, in minor units of `currency`.\n * @category Club\n */\nexport interface ClubMoney {\n /** Value in minor units of `currency` (the gateway sends it as int64 text; the SDK converts). Never negative. */\n amount: number\n /** ISO 4217 currency code, e.g. `BRL`. */\n currency: string\n /**\n * Decimal places of `amount` as the gateway resolved them (the currency's ISO exponent; for a free-spin\n * denomination, the provider's scale); `null` when the gateway omits them.\n */\n decimalPlaces: number | null\n}\n\n/**\n * Kind of a club reward, in lowercase. A kind the SDK does not know yet arrives as the gateway sent it, in\n * lowercase: handle the default case.\n * @category Club\n */\nexport type ClubRewardKind =\n | 'coins'\n | 'digital'\n | 'cashback'\n | 'bonus_balance'\n | 'free_spins'\n | 'tournament_ticket'\n | 'real_balance'\n | 'manual'\n | 'unspecified'\n | (string & {})\n\n/**\n * Coin award published in place of a reward in a given situation (e.g. the player already holds the ticket).\n * @category Club\n */\nexport interface ClubAlternateReward {\n /** Kind of the alternate, `coins` today. */\n kind: ClubRewardKind\n /** Label per locale. */\n label: ClubLocalized\n /** Quantity (integer). */\n quantity: number\n}\n\n/**\n * Cashback terms of a `cashback` reward.\n * @category Club\n */\nexport interface ClubCashbackTerms {\n /** Percentage in basis points (`1000` = 10%). */\n percentageBps: number\n /** `edition`, `daily`, `weekly` or another period; `null` when absent. */\n period: 'edition' | 'daily' | 'weekly' | (string & {}) | null\n /** `net_loss` or another basis; `null` when absent. */\n basis: 'net_loss' | (string & {}) | null\n /** Where the cashback is credited: `real`, `restricted` or another; `null` when absent. */\n destination: 'real' | 'restricted' | (string & {}) | null\n /** Start of the frozen basis window (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End of the frozen basis window (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Catalogue game ids eligible for the basis. */\n gameIds: string[]\n /** Coin award when the basis is zero; `null` when none. */\n zeroBasisAlternate: ClubAlternateReward | null\n /** Coin award when the basis was already rewarded; `null` when none. */\n priorAwardAlternate: ClubAlternateReward | null\n}\n\n/**\n * A club reward: of a wheel slice, a mission chest, a store item or a tournament prize.\n * @category Club\n */\nexport interface ClubReward {\n /** Reward id (`''` when the gateway sends none, e.g. in a projected tournament prize). */\n id: string\n /** Label per locale. */\n label: ClubLocalized\n /** Kind of the reward (see {@link ClubRewardKind}). */\n kind: ClubRewardKind\n /** Quantity (integer: coins, spins, items). */\n quantity: number\n /** Money of the reward; `null` when it has none. */\n money: ClubMoney | null\n /** Free-spin campaign: spins and the catalogue game; `null` when not a campaign. */\n campaign: { spins: number; gameId: string | null } | null\n /** Cashback terms; `null` when not a cashback. */\n cashback: ClubCashbackTerms | null\n /** Manual delivery (`physical` or `experience`) with the instructions; `null` when not manual. */\n manual: { deliveryType: 'physical' | 'experience' | (string & {}) | null; instructions: ClubLocalized } | null\n /** Validity in seconds after delivery (integer; `0` without one). */\n ttlSeconds: number\n /** Tournament edition of a `tournament_ticket`; `null` otherwise. */\n editionId: string | null\n /** Coin award when the player already holds the ticket or entry; `null` when none. */\n ticketOwnedAlternate: ClubAlternateReward | null\n}\n\n/**\n * Status of a receipt, in lowercase: `pending`, `delivered`, `failed`, `no_value` (a confirmed zero cashback) or a\n * status the SDK does not know yet.\n * @category Club\n */\nexport type ClubReceiptStatus = 'pending' | 'delivered' | 'failed' | 'no_value' | 'unspecified' | (string & {})\n\n/**\n * Receipt of a play, a redemption, a mission chest or a tournament award.\n * @category Club\n */\nexport interface ClubReceipt {\n /** Receipt id. */\n id: string\n /** Status (see {@link ClubReceiptStatus}). */\n status: ClubReceiptStatus\n /** What produced it, in lowercase: `activity` (a wheel, scratch card or gift), `chest` (a mission chest), `store` or `tournament`. */\n sourceKind: 'activity' | 'chest' | 'store' | 'tournament' | 'unspecified' | (string & {})\n /** Id of the source (activity, mission right, item, edition); `null` when absent. */\n sourceId: string | null\n /** Wheel slice that was drawn; `null` when not a draw. */\n sliceId: string | null\n /** The reward; `null` when absent. */\n reward: ClubReward | null\n /** Money actually settled; `null` when absent. */\n settlement: ClubMoney | null\n /** Coins spent (integer; `0` when free). */\n costCoins: number\n /** When it was accepted (ISO 8601); `null` when absent. */\n acceptedAt: string | null\n /** When the delivery was confirmed (ISO 8601); `null` while not delivered. */\n deliveredAt: string | null\n /** When the reward expires (ISO 8601); `null` without expiry. */\n expiresAt: string | null\n /** Frozen final rank of a tournament award; `null` otherwise. */\n tournamentRank: number | null\n /** Whether a tournament ticket was consumed. */\n ticketConsumed: boolean\n}\n\n/**\n * A level of the program.\n * @category Club\n */\nexport interface ClubLevel {\n /** Level id. */\n id: string\n /** Name per locale. */\n name: ClubLocalized\n /** XP needed to reach it (integer). */\n minXp: number\n /** Benefit per locale. */\n benefit: ClubLocalized\n}\n\n/**\n * The club program as the player sees it (part of {@link ClubOverview}; also the result of\n * {@link ClubApi.setMembership}).\n * @category Club\n */\nexport interface ClubProgram {\n /** Whether the program is active for the operator. */\n enabled: boolean\n /** Whether the player joined. */\n joined: boolean\n /** Whether joining is required before playing. */\n membershipRequired: boolean\n /** Whether the player can join now. */\n canJoin: boolean\n /** Whether the history can be read (also when the program is paused). */\n historyAvailable: boolean\n /** Published version: pass it back as `versionId` in every write; `null` without a published version. */\n versionId: string | null\n /** Locale the gateway resolved from `Accept-Language` (the client's locale); `null` when absent. */\n locale: string | null\n /** Key of the membership terms shown for that locale: pass it as `termsLocale` when joining. */\n termsLocale: string | null\n /** Program time zone (IANA); `null` when absent. */\n timeZone: string | null\n /** The player's wallet currency the program uses; `null` while not confirmed. */\n currency: string | null\n /** Name per locale. */\n name: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Name of the coin per locale. */\n coinName: ClubLocalized\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n /** Levels, in the order the operator published them (a repeated id keeps the first). */\n levels: ClubLevel[]\n}\n\n/**\n * Kind of an activity: `wheel`, `scratch`, `gift` or a kind the SDK does not know yet.\n * @category Club\n */\nexport type ClubActivityKind = 'wheel' | 'scratch' | 'gift' | 'unspecified' | (string & {})\n\n/**\n * An activity (wheel, scratch card, gift) and the player's state in it.\n * @category Club\n */\nexport interface ClubActivityState {\n /** The activity. */\n activity: {\n /** Activity id: pass it to {@link ClubApi.play}. */\n id: string\n /** Kind (see {@link ClubActivityKind}). */\n kind: ClubActivityKind\n /** Name per locale. */\n name: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n /** Wheel theme: `emerald`, `midnight`, `berry` or another; `null` when absent. */\n wheelTheme: 'emerald' | 'midnight' | 'berry' | (string & {}) | null\n /** Label of the play button per locale. */\n playLabel: ClubLocalized\n /** Slices, without the draw weights (a repeated id keeps the first). */\n slices: { id: string; reward: ClubReward | null }[]\n }\n /** Whether the player can play now. */\n canPlay: boolean\n /** Why the player cannot play (e.g. `daily_budget_exhausted`); `null` when absent. */\n unavailableReason: 'daily_budget_exhausted' | (string & {}) | null\n /** The player's last receipt in this activity; `null` when none. */\n latestReceipt: ClubReceipt | null\n /** When the player can play again (ISO 8601); `null` when absent. */\n availableAt: string | null\n}\n\n/**\n * A mission and the player's progress and chest right.\n * @category Club\n */\nexport interface ClubMissionState {\n /** The mission. */\n mission: {\n /** Mission id. */\n id: string\n /** Title per locale. */\n title: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** `daily`, `weekly`, `edition` or another, in lowercase. */\n recurrence: string\n /** `fact`, `day`, `edition` or another, in lowercase. */\n countBy: string\n /** Target (integer). */\n target: number\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n }\n /** Edition (period) of the mission; `null` when absent. */\n editionId: string | null\n /** Progress (integer). */\n progress: number\n /** Chest right: pass it as `activityId` to {@link ClubApi.play} to open the chest; `null` without a right. */\n rightId: string | null\n /**\n * Version of the right. The gateway sends it on the pending chests of a paused program; `null` when absent.\n */\n rightVersionId: string | null\n /** Chest options: pass the chosen `id` as `optionId` to {@link ClubApi.play}. */\n chestOptions: ClubReward[]\n /** Whether the chest can be opened now. */\n canClaim: boolean\n /** Receipt of the opened chest; `null` while not opened. */\n receipt: ClubReceipt | null\n /** End of the edition (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Deadline to open the chest (ISO 8601); `null` when absent. */\n claimExpiresAt: string | null\n /** Days already stamped (`YYYY-MM-DD`). */\n stampedDays: string[]\n}\n\n/**\n * An item of the coin store and whether the player can redeem it.\n * @category Club\n */\nexport interface ClubStoreItemState {\n /** The item. */\n item: {\n /** Item id: pass it as `rewardId` to {@link ClubApi.redeem}. */\n id: string\n /** Label per locale. */\n label: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Price in coins (integer). */\n costCoins: number\n /** The reward; `null` when absent. */\n reward: ClubReward | null\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n }\n /** Whether the player can redeem it now. */\n canRedeem: boolean\n /** Why it cannot be redeemed, in lowercase; `null` when absent. */\n unavailableReason: string | null\n}\n\n/**\n * The player's balances, activities, missions and store.\n * @category Club\n */\nexport interface ClubRewards {\n /** XP (integer). */\n xp: number\n /** Coin balance (integer). */\n coins: number\n /** Current level id; `null` when none. */\n levelId: string | null\n /** Activities (a repeated activity id keeps the first). Empty while the program is paused. */\n activities: ClubActivityState[]\n /** Missions (a repeated mission right keeps the first). While paused, only the pending chests. */\n missions: ClubMissionState[]\n /** Store items (a repeated item id keeps the first). Empty while the program is paused. */\n storeItems: ClubStoreItemState[]\n}\n\n/**\n * The club overview (`GET /casino/club`).\n * @category Club\n */\nexport interface ClubOverview {\n /** The program. */\n program: ClubProgram\n /** The player's state; `null` when the program is disabled and has no history. */\n rewards: ClubRewards | null\n}\n\n/**\n * A balance movement of the history.\n * @category Club\n */\nexport interface ClubMovement {\n /** Movement id. */\n id: string\n /** `xp`, `coins` or another kind, in lowercase. */\n kind: string\n /** Units moved (integer; negative for a debit). */\n units: number\n /** Id of the source; `null` when absent. */\n sourceId: string | null\n /** When it happened (ISO 8601); `null` when absent. */\n occurredAt: string | null\n}\n\n/**\n * A page of the club history.\n * @category Club\n */\nexport interface ClubHistory {\n /** Receipts on this page (a repeated id keeps the first). */\n receipts: ClubReceipt[]\n /** Movements on this page (a repeated id keeps the first). */\n movements: ClubMovement[]\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * Status of a tournament, in lowercase.\n * @category Club\n */\nexport type ClubTournamentStatus =\n | 'draft'\n | 'upcoming'\n | 'live'\n | 'awaiting_confirmation'\n | 'completed'\n | 'cancelled'\n | 'unspecified'\n | (string & {})\n\n/**\n * The player's registration in a tournament.\n * @category Club\n */\nexport interface ClubTournamentRegistration {\n /** Registration id. */\n id: string\n /** Edition id. */\n editionId: string\n /** Version registered; `null` when absent. */\n versionId: string | null\n /** When the player registered (ISO 8601); `null` when absent. */\n joinedAt: string | null\n}\n\n/**\n * A prize range of a tournament.\n * @category Club\n */\nexport interface ClubTournamentPrize {\n /** First rank of the range (integer). */\n fromRank: number\n /** Last rank of the range (integer). */\n toRank: number\n /** The reward; `null` when absent (e.g. an external listing). */\n reward: ClubReward | null\n /** Announced amount (external listings); `null` when absent. Under `'warn'` a prize with an invalid one is dropped. */\n announcedAmount: ClubMoney | null\n /** Prize terms per locale (`{}` when none). */\n terms: ClubLocalized\n /** Frozen offer conditions of a `bonus_balance`/`free_spins` prize; `null` when none. */\n offerTerms: {\n /** Value of each free spin, in the provider's scale; `null` when unconfirmed. */\n spinDenomination: ClubMoney | null\n /** Exact decimal wagering multiplier (`\"0\"` = no wagering); `null` when unconfirmed. */\n wageringMultiplier: string | null\n /** Validity in seconds; `null` when unconfirmed. */\n validForSeconds: number | null\n /** Expiry of the offer (ISO 8601); `null` when absent. */\n expiresAt: string | null\n /** End of the grant window (ISO 8601); `null` when absent. */\n grantEndsAt: string | null\n } | null\n}\n\n/**\n * A club tournament (own or external).\n * @category Club\n */\nexport interface ClubTournament {\n /** Edition id (external ones start with `ext_`). */\n id: string\n /** `own`, `external` or another source, in lowercase. */\n source: string\n /** Published version: pass it as `versionId` to {@link ClubApi.registerForTournament}; `null` when absent. */\n versionId: string | null\n /** Title per locale. */\n title: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Status (see {@link ClubTournamentStatus}). */\n status: ClubTournamentStatus\n /** Start (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Last update (ISO 8601); `null` when absent. */\n updatedAt: string | null\n /** Scoring rule, in lowercase; `null` when absent. */\n scoringRule: string | null\n /** Tie-break rule, in lowercase; `null` when absent. */\n tieBreak: string | null\n /** Currency of the edition (ISO 4217); `null` when absent. */\n currency: string | null\n /** Time zone (IANA); `null` when absent. */\n timeZone: string | null\n /** Catalogue games of the edition (a repeated id keeps the first). */\n gameIds: string[]\n /** Prize ranges. */\n prizes: ClubTournamentPrize[]\n /** `registration`, `in_game` or another; `null` when no action is confirmed. */\n joinMode: 'registration' | 'in_game' | (string & {}) | null\n /** Locale of the terms shown; `null` when absent. */\n locale: string | null\n /** Whether {@link ClubApi.getRanking} can be read. */\n rankingAvailable: boolean\n /** Whether the player can register now. */\n canRegister: boolean\n /** Whether registering consumes a ticket. */\n requiresTicket: boolean\n /** The player's registration; `null` when not registered. */\n registration: ClubTournamentRegistration | null\n /** The player's award from the frozen result (detail only); `null` when none. */\n personalAward: ClubReceipt | null\n /** Whether the source data is stale. */\n stale: boolean\n /** Registration opening (ISO 8601); `null` when absent. */\n registrationStartsAt: string | null\n /** Registration closing (ISO 8601); `null` when absent. */\n registrationEndsAt: string | null\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n}\n\n/**\n * A page of club tournaments.\n * @category Club\n */\nexport interface ClubTournamentPage {\n /** Tournaments on this page (a repeated id keeps the first). */\n items: ClubTournament[]\n /** Whether external tournaments are on the page. */\n externalAvailable: boolean\n /** Whether an external tournament on the page is stale. */\n externalStale: boolean\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * Another edition of the same external schedule.\n * @category Club\n */\nexport interface ClubRelatedTournament {\n /** Edition id (`ext_...`). */\n id: string\n /** Title per locale. */\n title: ClubLocalized\n /** Status (see {@link ClubTournamentStatus}). */\n status: ClubTournamentStatus\n /** Start (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End (ISO 8601); `null` when absent. */\n endsAt: string | null\n}\n\n/**\n * A page of related editions.\n * @category Club\n */\nexport interface ClubRelatedTournamentPage {\n /** Related editions (a repeated id keeps the first). */\n items: ClubRelatedTournament[]\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * A row of a tournament ranking.\n * @category Club\n */\nexport interface ClubRank {\n /** Position (integer ≥ 1). */\n position: number\n /** Display name, already masked by the source. */\n displayName: string\n /** Score as decimal text (display only). */\n score: string\n}\n\n/**\n * A tournament ranking.\n * @category Club\n */\nexport interface ClubRanking {\n /** Top rows. */\n entries: ClubRank[]\n /** The player's row; `null` when not ranked. */\n personal: ClubRank | null\n /** Last update (ISO 8601); `null` when absent. */\n updatedAt: string | null\n /** Whether the ranking is final. */\n final: boolean\n}\n\n/**\n * Result of {@link ClubApi.play}.\n * @category Club\n */\nexport interface ClubPlayResult {\n /** The receipt. */\n receipt: ClubReceipt\n /** Slice drawn; `null` when not a draw (e.g. a mission chest). */\n sliceId: string | null\n /** The player's state after the play; `null` when absent. */\n rewards: ClubRewards | null\n}\n\n/**\n * Cursor pagination of the club listings.\n * @category Club\n */\nexport interface ClubCursorInput {\n /** The previous page's `nextCursor`. Omitted: the first page. */\n cursor?: string\n /** Items per page: an integer from 1 to 100. Omitted: the gateway default. */\n limit?: number\n}\n\n/**\n * Input of {@link ClubApi.listRelatedTournaments}.\n * @category Club\n */\nexport interface ListRelatedClubTournamentsInput extends ClubCursorInput {\n /** External edition (`ext_` followed by letters, digits, `_` or `-`). */\n editionId: string\n}\n\n/**\n * Input of {@link ClubApi.getRanking}.\n * @category Club\n */\nexport interface GetClubRankingInput {\n /** Edition id. */\n editionId: string\n /** Rows: an integer from 1 to 100. Omitted: the gateway default. */\n limit?: number\n}\n\n/**\n * Input of {@link ClubApi.setMembership}: join (with the terms locale shown) or leave.\n * @category Club\n */\nexport type SetClubMembershipInput =\n | {\n /** {@link ClubProgram.versionId}. */\n versionId: string\n /** Join. */\n joined: true\n /** {@link ClubProgram.termsLocale}: the key of the terms the player saw. */\n termsLocale: string\n }\n | {\n /** {@link ClubProgram.versionId}. */\n versionId: string\n /** Leave. */\n joined: false\n }\n\n/**\n * Input of {@link ClubApi.play}.\n * @category Club\n */\nexport interface PlayClubActivityInput {\n /** An activity id, or a mission's `rightId` to open its chest. */\n activityId: string\n /** {@link ClubProgram.versionId} (or the mission's `rightVersionId`). */\n versionId: string\n /** Chosen chest option (`chestOptions[i].id`). */\n optionId?: string\n}\n\n/**\n * Input of {@link ClubApi.redeem}.\n * @category Club\n */\nexport interface RedeemClubRewardInput {\n /** Store item id. */\n rewardId: string\n /** {@link ClubProgram.versionId}. */\n versionId: string\n}\n\n/**\n * Input of {@link ClubApi.registerForTournament}.\n * @category Club\n */\nexport interface RegisterClubTournamentInput {\n /** Edition id. */\n editionId: string\n /** {@link ClubTournament.versionId}. */\n versionId: string\n /** Ticket to consume, when the tournament requires one. */\n ticketId?: string\n}\n\n/**\n * The casino club: program, activities (wheel, scratch, gift), missions with chests, coin store, history and\n * tournaments. Every method requires login. The gateway resolves the texts from the client's locale\n * (`Accept-Language`): change it with the core's `setLocale`.\n *\n * Writes are **idempotent**: each sends an `Idempotency-Key` (the one in `options.idempotencyKey` or one generated per\n * call; printable ASCII up to 128 characters, without surrounding spaces) that the club service stores. To retry a write whose\n * outcome is unknown, call again with the **same** key: the service answers the first result. The club answers a\n * duplicate still in flight with a plain 409 (`ALREADY_EXISTS`, never `KEY_IN_USE`), so a 409 is not a definitive\n * refusal: keep the key after anything but a 400, 403, 404 or 422 ({@link keepsClubIdempotencyKey} tells which).\n * Through `createIgamingMutations` the club writes follow that rule for you; an app that persists the key (e.g. per\n * action in `sessionStorage`, to survive a reload) uses the same helper to decide when to drop it.\n *\n * Errors to expect (identify by `error.code`): `NOT_FOUND` (404, also when the club is not active),\n * `PERMISSION_DENIED` (403), `ALREADY_EXISTS` (409, a conflict with the version, the availability or the account\n * state), `CLUB_WALLET_UNAVAILABLE` (503, or 409 when the wallet currency is not confirmed), `CLUB_RATE_LIMITED`\n * (429), `INVALID_ARGUMENT` (400), `UNAVAILABLE` (503).\n * @category Club\n */\nexport interface ClubApi {\n /**\n * The program, the player's balances, activities, missions and store.\n * @example\n * const { program, rewards } = await igaming.club.getOverview()\n * if (program.enabled && !program.joined && program.canJoin) showJoin(program.terms, program.termsLocale)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n getOverview(params?: NoParams, options?: CallOptions): Promise<ClubOverview>\n /**\n * The player's receipts and balance movements, newest first, cursor-paginated.\n * @example\n * const page = await igaming.club.listHistory({ limit: 30 })\n * const next = page.nextCursor && (await igaming.club.listHistory({ cursor: page.nextCursor, limit: 30 }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `cursor` that is not text or a `limit` outside\n * 1–100; `UNAUTHENTICATED` without a session.\n */\n listHistory(input?: ClubCursorInput, options?: CallOptions): Promise<ClubHistory>\n /**\n * Own and external tournaments, merged and cursor-paginated (gateway default: 50 per page).\n * @example\n * const { items, nextCursor } = await igaming.club.listTournaments()\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a bad `cursor` or `limit`; `NOT_FOUND` when the\n * club is not active.\n */\n listTournaments(input?: ClubCursorInput, options?: CallOptions): Promise<ClubTournamentPage>\n /**\n * Other editions of the same external schedule as `editionId` (the gateway caps the page at 20). A page that\n * answers for another edition is read as empty.\n * @example\n * const { items } = await igaming.club.listRelatedTournaments({ editionId: 'ext_tlt_123', limit: 10 })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an `editionId` that is not an external edition id,\n * or a bad `cursor`/`limit`; `NOT_FOUND` for an unknown edition.\n */\n listRelatedTournaments(\n input: ListRelatedClubTournamentsInput,\n options?: CallOptions,\n ): Promise<ClubRelatedTournamentPage>\n /**\n * A tournament's detail, with the player's registration and award.\n * @example\n * const tournament = await igaming.club.getTournament({ editionId })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `editionId` or one over 128 UTF-8 bytes;\n * `NOT_FOUND` for an unknown edition.\n */\n getTournament(input: { editionId: string }, options?: CallOptions): Promise<ClubTournament>\n /**\n * A tournament's ranking.\n * @example\n * const ranking = await igaming.club.getRanking({ editionId, limit: 20 })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a bad `editionId` or `limit`;\n * `CLUB_RANKING_UNAVAILABLE` (404) when the source cannot disclose it.\n */\n getRanking(input: GetClubRankingInput, options?: CallOptions): Promise<ClubRanking>\n /**\n * Joins the club (accepting the terms shown in `termsLocale`) or leaves it. Idempotent (see {@link ClubApi}).\n * @example\n * const program = await igaming.club.setMembership({ versionId, joined: true, termsLocale })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `versionId`, a `joined` that is not a\n * boolean, an empty `termsLocale` when joining or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) for a stale\n * version.\n */\n setMembership(input: SetClubMembershipInput, options?: CallOptions): Promise<ClubProgram>\n /**\n * Plays an activity, or opens a mission chest (`activityId` = `rightId`, `optionId` = the chosen option).\n * Idempotent (see {@link ClubApi}).\n * @example\n * const { receipt, sliceId } = await igaming.club.play({ activityId, versionId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `activityId`/`versionId`, a non-text\n * `optionId` or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) when it cannot be played now.\n */\n play(input: PlayClubActivityInput, options?: CallOptions): Promise<ClubPlayResult>\n /**\n * Redeems a store item with coins. Idempotent (see {@link ClubApi}).\n * @example\n * const receipt = await igaming.club.redeem({ rewardId: item.id, versionId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `rewardId`/`versionId` or a bad\n * `idempotencyKey`; `ALREADY_EXISTS` (409) without enough coins or stock.\n */\n redeem(input: RedeemClubRewardInput, options?: CallOptions): Promise<ClubReceipt>\n /**\n * Registers the player in an own tournament. Idempotent (see {@link ClubApi}).\n * @example\n * const registration = await igaming.club.registerForTournament({ editionId, versionId: t.versionId })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `editionId`/`versionId`, a non-text\n * `ticketId` or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) when registration is closed.\n */\n registerForTournament(input: RegisterClubTournamentInput, options?: CallOptions): Promise<ClubTournamentRegistration>\n}\n\n/**\n * Whether a failed club write must keep its `Idempotency-Key` for the retry. The club service stores the key and\n * answers a duplicate that is still being processed with a plain 409, the same answer as a stale version: releasing\n * the key after it would let the next tap pay twice. So the key is kept after everything except a definitive\n * refusal (400, 403, 404, 422) or an error that never reached the club (`CONFIGURATION_ERROR`, `ABORTED`): network\n * errors, timeouts, 5xx, 401, 409, 429 and a 2xx outside the format all keep it. `createIgamingMutations` applies it\n * to the `club` writes; use it where the app keeps its own key (e.g. one per action, persisted across a reload).\n * @param error - What the write rejected with.\n * @example\n * try {\n * await igaming.club.redeem({ rewardId, versionId }, { idempotencyKey: pendingKey })\n * forget(pendingKey)\n * } catch (error) {\n * if (!keepsClubIdempotencyKey(error)) forget(pendingKey)\n * throw error\n * }\n * @throws Never throws: anything that is not an `EnginexError` returns `false`.\n * @category Club\n */\nexport function keepsClubIdempotencyKey(error: unknown): boolean {\n if (!isEnginexError(error)) return false\n if (isAmbiguousFailure(error)) return true\n return error.status >= 400 && !DEFINITIVE_CLUB_STATUS.has(error.status)\n}\n\nconst DEFINITIVE_CLUB_STATUS: ReadonlySet<number> = /* @__PURE__ */ new Set([400, 403, 404, 422])\n\n// ─── Schemas ───────────────────────────────────────────────────────────────────────────────────\n\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/\nconst ISO_DAY = /^\\d{4}-\\d{2}-\\d{2}$/\nconst DECIMAL = /^(?:0|[1-9]\\d{0,19})(?:\\.\\d{1,20})?$/\nconst EXTERNAL_EDITION = /^ext_[A-Za-z0-9_-]+$/\nconst GO_ZERO_TIME = /^0001-01-01T00:00:00(?:\\.0+)?(?:Z|[+-]00:00)$/\n\n/**\n * Optional ISO 8601 date-time: absent, `null`, `\"\"`, the epoch (protojson's zero `Timestamp` as `AsTime()`) and\n * Go's zero `time.Time` (`encoding/json`) become `null`. Anything else that is not an RFC 3339 date-time fails.\n */\nconst time = () =>\n z.pipe(\n z.nullish(\n z\n .string()\n .check(\n z.refine(\n (value) => value === '' || (ISO_DATE_TIME.test(value) && !Number.isNaN(Date.parse(value))),\n 'Expected an ISO 8601 date-time',\n ),\n ),\n ),\n z.transform((value): string | null =>\n value == null || value === '' || Date.parse(value) === 0 || GO_ZERO_TIME.test(value) ? null : value,\n ),\n )\n\nconst flag = () => z._default(z.boolean(), false)\nconst textOrEmpty = () => z._default(z.string(), '')\nconst id = () => z.string().check(z.minLength(1, 'Expected a non-empty id'))\nconst localized = () => mapOf(z.string())\n// int64 counters that are not money (coins, XP, quantities): int64 text or a number, safe integers, normal `'warn'`\n// rule (the divergent field arrives raw and is reported).\nconst units = () => z._default(integerText(), 0)\nconst int32 = () =>\n z._default(z.number().check(z.refine((value) => Number.isSafeInteger(value), 'Expected an integer')), 0)\nconst rank = () =>\n z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 1, 'Expected an integer ≥ 1'))\n// Free-text codes the gateway writes in lowercase: lowercased, `''`/absent as `unspecified`, a new value passes.\nconst code = () =>\n z.pipe(\n protoEnum(''),\n z.transform((value) => (value === '' ? 'unspecified' : value)),\n )\n// An optional code: `''`/absent/`null` as `null`, otherwise lowercased.\nconst optionalCode = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((value): string | null => (value ? value.toLowerCase() : null)),\n )\nconst nullable = <T extends z.ZodMiniType>(schema: T) =>\n z.pipe(\n z.nullish(schema),\n z.transform((value): z.output<T> | null => value ?? null),\n )\n\n/** A list (omitted/`null` as `[]`) whose repeated keys keep the first occurrence. */\nfunction uniqueList<T extends z.ZodMiniType>(item: T, key: (value: z.output<T>) => string | undefined) {\n return z.pipe(\n nullableList(item),\n z.transform((items): z.output<T>[] => {\n const seen = new Set<string>()\n return items.filter((value) => {\n // In `'warn'` an item whose identity came in raw (e.g. the `activity` of an activity state as text) has no\n // key: it is dropped, so the app never reads a field of a text where it expects an object.\n const k = typeof value === 'object' && value !== null ? safeKey(() => key(value)) : String(value)\n if (k === undefined || seen.has(k)) return false\n seen.add(k)\n return true\n })\n }),\n )\n}\n\nfunction safeKey(read: () => string | undefined): string | undefined {\n try {\n const value = read()\n return typeof value === 'string' && value !== '' ? value : undefined\n } catch {\n return undefined\n }\n}\n\n// `ClubMoney` (and `ClubSpinDenomination`, same shape): strict even in `'warn'`, like the other money of the SDK.\nconst moneySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubMoney> =>\n z.pipe(\n wire({\n currency: currencyCode(),\n amountMinor: nonNegativeMinorUnits(),\n decimalPlaces: z.optional(decimalPlaces()),\n }),\n z.transform(\n (m): ClubMoney => ({ amount: m.amountMinor, currency: m.currency, decimalPlaces: m.decimalPlaces ?? null }),\n ),\n ),\n)\n\nconst alternateSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubAlternateReward> => wire({ kind: code(), label: localized(), quantity: units() }),\n)\n\nconst rewardSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubReward> =>\n wire({\n id: textOrEmpty(),\n label: localized(),\n kind: code(),\n quantity: units(),\n money: nullable(moneySchema()),\n campaign: nullable(wire({ spins: units(), gameId: optionalText() })),\n cashback: nullable(\n wire({\n percentageBps: int32(),\n period: optionalCode(),\n basis: optionalCode(),\n destination: optionalCode(),\n startsAt: time(),\n endsAt: time(),\n gameIds: uniqueList(z.string(), String),\n zeroBasisAlternate: nullable(alternateSchema()),\n priorAwardAlternate: nullable(alternateSchema()),\n }),\n ),\n manual: nullable(wire({ deliveryType: optionalCode(), instructions: localized() })),\n ttlSeconds: units(),\n editionId: optionalText(),\n ticketOwnedAlternate: nullable(alternateSchema()),\n }),\n)\n\nconst receiptSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubReceipt> =>\n wire({\n id: id(),\n status: code(),\n sourceKind: code(),\n sourceId: optionalText(),\n sliceId: optionalText(),\n reward: nullable(rewardSchema()),\n settlement: nullable(moneySchema()),\n costCoins: units(),\n acceptedAt: time(),\n deliveredAt: time(),\n expiresAt: time(),\n tournamentRank: nullable(rank()),\n ticketConsumed: flag(),\n }),\n)\n\nconst levelSchema = () => wire({ id: id(), name: localized(), minXp: units(), benefit: localized() })\n\nconst programSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubProgram> =>\n wire({\n enabled: flag(),\n joined: flag(),\n membershipRequired: flag(),\n canJoin: flag(),\n historyAvailable: flag(),\n versionId: optionalText(),\n locale: optionalText(),\n termsLocale: optionalText(),\n timeZone: optionalText(),\n currency: z.pipe(\n z._default(currencyOrEmpty(), ''),\n z.transform((value): string | null => value || null),\n ),\n name: localized(),\n terms: localized(),\n coinName: localized(),\n coverUrl: optionalText(),\n levels: uniqueList(levelSchema(), (level) => level.id),\n }),\n)\n\nconst activitySchema = () =>\n wire({\n activity: wire({\n id: id(),\n kind: code(),\n name: localized(),\n terms: localized(),\n coverUrl: optionalText(),\n wheelTheme: optionalCode(),\n playLabel: localized(),\n slices: uniqueList(wire({ id: id(), reward: nullable(rewardSchema()) }), (slice) => slice.id),\n }),\n canPlay: flag(),\n unavailableReason: optionalCode(),\n latestReceipt: nullable(receiptSchema()),\n availableAt: time(),\n })\n\nconst missionSchema = () =>\n wire({\n mission: wire({\n id: id(),\n title: localized(),\n terms: localized(),\n recurrence: code(),\n countBy: code(),\n target: units(),\n coverUrl: optionalText(),\n }),\n editionId: optionalText(),\n progress: units(),\n rightId: optionalText(),\n rightVersionId: optionalText(),\n chestOptions: nullableList(rewardSchema()),\n canClaim: flag(),\n receipt: nullable(receiptSchema()),\n endsAt: time(),\n claimExpiresAt: time(),\n stampedDays: uniqueList(\n z\n .string()\n .check(\n z.refine((value) => ISO_DAY.test(value) && !Number.isNaN(Date.parse(value)), 'Expected a YYYY-MM-DD day'),\n ),\n String,\n ),\n })\n\nconst storeItemSchema = () =>\n wire({\n item: wire({\n id: id(),\n label: localized(),\n terms: localized(),\n costCoins: units(),\n reward: nullable(rewardSchema()),\n coverUrl: optionalText(),\n }),\n canRedeem: flag(),\n unavailableReason: optionalCode(),\n })\n\nconst rewardsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubRewards> =>\n wire({\n xp: units(),\n coins: units(),\n levelId: optionalText(),\n activities: uniqueList(activitySchema(), (state) => state.activity.id),\n // The same mission may hold several rights (one per period): a repeat is the same mission, right and period.\n missions: uniqueList(missionSchema(), (state) =>\n typeof state.mission.id === 'string'\n ? JSON.stringify([state.mission.id, state.rightId ?? state.editionId, state.endsAt])\n : undefined,\n ),\n storeItems: uniqueList(storeItemSchema(), (state) => state.item.id),\n }),\n)\n\nconst overviewSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubOverview> => wire({ program: programSchema(), rewards: nullable(rewardsSchema()) }),\n)\n\nconst nextCursor = () =>\n z.pipe(\n optionalText(),\n z.transform((value) => value ?? undefined),\n )\n\n/** Drops an `undefined` `nextCursor`, so the last page has no such key. */\nfunction compactCursor<T extends { nextCursor?: string | undefined }>(page: T): T {\n if (page.nextCursor === undefined) delete page.nextCursor\n return page\n}\n\nconst historySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubHistory> =>\n z.pipe(\n wire({\n receipts: uniqueList(receiptSchema(), (receipt) => receipt.id),\n movements: uniqueList(\n wire({ id: id(), kind: code(), units: units(), sourceId: optionalText(), occurredAt: time() }),\n (movement) => movement.id,\n ),\n nextCursor: nextCursor(),\n }),\n z.transform(compactCursor),\n ),\n)\n\nconst registrationSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournamentRegistration> =>\n wire({ id: id(), editionId: id(), versionId: optionalText(), joinedAt: time() }),\n)\n\nconst isMinorUnits = (v: unknown): boolean =>\n (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) ||\n (typeof v === 'string' && /^\\d+$/.test(v) && Number.isSafeInteger(Number(v)))\n\n// Not strict: a value outside the format is a normal issue (reported, the field arriving raw in `'warn'`), never\n// rounded (≥ 2^53 as text fails like any other malformed amount).\nconst announcedMoney = () =>\n z.pipe(\n wire({\n currency: z.string().check(z.regex(/^[A-Z]{3}$/, 'Expected a currency code, e.g. BRL')),\n amountMinor: z.union([z.string(), z.number()]).check(z.refine(isMinorUnits, 'Expected non-negative minor units')),\n decimalPlaces: z.optional(\n z.number().check(z.refine((v) => Number.isInteger(v) && v >= 0 && v <= 8, 'Expected decimal places 0 to 8')),\n ),\n }),\n // In `'warn'` the amount may come in raw: only an exact non-negative integer becomes `amount`; anything else stays\n // as it came, so `hasValidAnnouncedAmount` drops the prize (never `Number('1e3')`, never a rounded value).\n z.transform(\n (m): ClubMoney => ({\n amount: isMinorUnits(m.amountMinor) ? Number(m.amountMinor) || 0 : (m.amountMinor as unknown as number),\n currency: m.currency,\n decimalPlaces: m.decimalPlaces ?? null,\n }),\n ),\n )\n\nconst prizeSchema = () =>\n wire({\n fromRank: int32(),\n toRank: int32(),\n reward: nullable(rewardSchema()),\n announcedAmount: nullable(announcedMoney()),\n terms: localized(),\n offerTerms: nullable(\n wire({\n spinDenomination: nullable(moneySchema()),\n wageringMultiplier: nullable(z.string().check(z.regex(DECIMAL, 'Expected an exact decimal'))),\n validForSeconds: nullable(integerText()),\n expiresAt: time(),\n grantEndsAt: time(),\n }),\n ),\n })\n\n/** `false` for a prize whose announced amount came in raw (recovered in `'warn'`): it is dropped, already reported. */\nfunction hasValidAnnouncedAmount(prize: { announcedAmount: unknown }): boolean {\n const amount = prize.announcedAmount\n if (amount === null) return true\n if (typeof amount !== 'object') return false\n const { amount: value, currency } = amount as Record<string, unknown>\n return (\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value >= 0 &&\n typeof currency === 'string' &&\n /^[A-Z]{3}$/.test(currency)\n )\n}\n\nconst tournamentSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournament> =>\n wire({\n id: id(),\n source: code(),\n versionId: optionalText(),\n title: localized(),\n terms: localized(),\n status: code(),\n startsAt: time(),\n endsAt: time(),\n updatedAt: time(),\n scoringRule: optionalCode(),\n tieBreak: optionalCode(),\n currency: z.pipe(\n z._default(currencyOrEmpty(), ''),\n z.transform((value): string | null => value || null),\n ),\n timeZone: optionalText(),\n gameIds: uniqueList(z.string(), String),\n // An announced amount (an external listing) is display data, not a prize the player wins: one outside the\n // format (negative, a fraction, ≥ 2^53, a bad currency) fails without the strict mark, so `'warn'` reports it\n // and drops that prize instead of failing the whole page. Strict mode still rejects it.\n prizes: z.pipe(\n nullableList(prizeSchema()),\n z.transform((prizes) => prizes.filter(hasValidAnnouncedAmount)),\n ),\n joinMode: optionalCode(),\n locale: optionalText(),\n rankingAvailable: flag(),\n canRegister: flag(),\n requiresTicket: flag(),\n registration: nullable(registrationSchema()),\n personalAward: nullable(receiptSchema()),\n stale: flag(),\n registrationStartsAt: time(),\n registrationEndsAt: time(),\n coverUrl: optionalText(),\n }),\n)\n\nconst tournamentPageSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournamentPage> =>\n z.pipe(\n wire({\n items: uniqueList(tournamentSchema(), (tournament) => tournament.id),\n externalAvailable: flag(),\n externalStale: flag(),\n nextCursor: nextCursor(),\n }),\n z.transform(compactCursor),\n ),\n)\n\nconst relatedPageSchema = /* @__PURE__ */ lazy(() =>\n wire({\n relatedTo: textOrEmpty(),\n items: uniqueList(\n wire({\n id: z.string().check(z.regex(EXTERNAL_EDITION, 'Expected an external edition id')),\n title: localized(),\n status: code(),\n startsAt: time(),\n endsAt: time(),\n }),\n (item) => item.id,\n ),\n nextCursor: nextCursor(),\n }),\n)\n\nconst rankSchema = () => wire({ position: rank(), displayName: textOrEmpty(), score: textOrEmpty() })\n\nconst rankingSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubRanking> =>\n wire({ entries: nullableList(rankSchema()), personal: nullable(rankSchema()), updatedAt: time(), final: flag() }),\n)\n\nconst playSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubPlayResult> =>\n wire({ receipt: receiptSchema(), sliceId: optionalText(), rewards: nullable(rewardsSchema()) }),\n)\n\n// ─── Input checks ──────────────────────────────────────────────────────────────────────────────\n\nconst BASE = '/casino/club'\n// The gateway's `clubSetPathID` and `clubMutationKey` refuse anything above 128 bytes (Go `len`).\nconst MAX_ID = 128\nconst MAX_IDEMPOTENCY_KEY = 128\n\nconst ROUTES = {\n overview: { method: 'GET', path: BASE },\n history: { method: 'GET', path: `${BASE}/history` },\n tournaments: { method: 'GET', path: `${BASE}/tournaments` },\n tournament: { method: 'GET', path: `${BASE}/tournaments/{editionId}` },\n ranking: { method: 'GET', path: `${BASE}/tournaments/{editionId}/ranking` },\n membership: { method: 'PUT', path: `${BASE}/membership` },\n play: { method: 'POST', path: `${BASE}/activities/{activityId}/plays` },\n redeem: { method: 'POST', path: `${BASE}/rewards/{rewardId}/redemptions` },\n register: { method: 'POST', path: `${BASE}/tournaments/{editionId}/registrations` },\n} satisfies Record<string, Route>\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Length in UTF-8 bytes: the gateway's `len()` in Go, not JavaScript's UTF-16 units. */\nfunction utf8Length(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\nfunction idProblem(name: string, field: string, value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' && utf8Length(value) <= MAX_ID\n ? undefined\n : `${name}: ${field} must be non-empty text up to ${MAX_ID} UTF-8 bytes.`\n}\n\nfunction optionalTextProblem(name: string, field: string, value: unknown): string | undefined {\n return value === undefined || typeof value === 'string' ? undefined : `${name}: ${field} must be text.`\n}\n\nfunction limitProblem(name: string, value: unknown): string | undefined {\n return value === undefined || (typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 100)\n ? undefined\n : `${name}: limit must be an integer from 1 to 100.`\n}\n\nfunction cursorProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (!isObject(input)) return `${name}: input must be an object.`\n return optionalTextProblem(name, 'cursor', input.cursor) ?? limitProblem(name, input.limit)\n}\n\nfunction keyProblem(name: string, options: CallOptions | undefined): string | undefined {\n const key = options?.idempotencyKey\n if (key === undefined || key === '') return undefined\n // A header value is a byte string: only printable ASCII travels as itself (an emoji makes `fetch` throw, a Latin-1\n // letter reaches the gateway as other bytes), so one ASCII character is one of the gateway's bytes.\n return typeof key === 'string' &&\n key === key.trim() &&\n /^[\\x20-\\x7E]+$/.test(key) &&\n key.length <= MAX_IDEMPOTENCY_KEY\n ? undefined\n : `${name}: idempotencyKey must be printable ASCII without surrounding spaces, up to ${MAX_IDEMPOTENCY_KEY} characters.`\n}\n\nfunction membershipProblem(input: unknown): string | undefined {\n const name = 'club.setMembership'\n if (!isObject(input)) return `${name}: input must be { versionId, joined, termsLocale? }.`\n if (typeof input.joined !== 'boolean') return `${name}: joined must be true or false.`\n const versionProblem = idProblem(name, 'versionId', input.versionId)\n if (versionProblem) return versionProblem\n if (input.joined && (typeof input.termsLocale !== 'string' || input.termsLocale.trim() === ''))\n return `${name}: termsLocale must be non-empty text when joining.`\n return undefined\n}\n\nconst segment = (value: string) => encodeURIComponent(value)\n\n/**\n * In `'warn'` a required message of the wrong type (text, a number) arrives raw. The overview without its program and\n * a play without its receipt mean nothing: they reject with `VALIDATION_ERROR` (status 200, so an idempotent retry\n * keeps the key and replays the result) instead of handing the app a text where it reads an object.\n */\nfunction requireObject<T extends object>(transport: ExtensionTransport, route: Route, field: keyof T & string) {\n return (value: T): T => {\n if (isObject(value[field])) return value\n throw transport.reportError(\n {\n code: 'VALIDATION_ERROR',\n message: `Unexpected gateway response on ${route.method} ${route.path}: ${field}`,\n status: 200,\n },\n route,\n )\n }\n}\n\n/** Creates the `club` namespace. @internal */\nexport function createClubApi(transport: ExtensionTransport): ClubApi {\n const get = <T>(\n path: string,\n query: Record<string, string | number | undefined>,\n schema: z.ZodMiniType<T>,\n options?: CallOptions,\n ) => transport.request({ method: 'GET', path, query, auth: 'required', schema, options })\n\n const write = <T>(\n method: 'POST' | 'PUT',\n path: string,\n body: Record<string, unknown>,\n schema: z.ZodMiniType<T>,\n options: CallOptions | undefined,\n ) =>\n // The key goes only in the `Idempotency-Key` header: the gateway reads it from there when the body has none\n // (a body key that differed from the header would be refused).\n transport.request({ method, path, body, auth: 'required', idempotent: true, schema, options })\n\n return {\n getOverview: (_params, options) =>\n get(BASE, {}, overviewSchema(), options).then(requireObject<ClubOverview>(transport, ROUTES.overview, 'program')),\n\n listHistory: (input, options) => {\n const problem = cursorProblem('club.listHistory', input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.history)\n return get(\n ROUTES.history.path,\n { cursor: input?.cursor || undefined, limit: input?.limit },\n historySchema(),\n options,\n )\n },\n\n listTournaments: (input, options) => {\n const problem = cursorProblem('club.listTournaments', input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournaments)\n return get(\n ROUTES.tournaments.path,\n { cursor: input?.cursor || undefined, limit: input?.limit },\n tournamentPageSchema(),\n options,\n )\n },\n\n listRelatedTournaments: (input, options) => {\n const name = 'club.listRelatedTournaments'\n const problem = !isObject(input)\n ? `${name}: input must be { editionId }.`\n : typeof input.editionId !== 'string' ||\n utf8Length(input.editionId) > MAX_ID ||\n !EXTERNAL_EDITION.test(input.editionId)\n ? `${name}: editionId must be an external edition id (ext_...), up to ${MAX_ID} characters.`\n : cursorProblem(name, input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournaments)\n return get(\n ROUTES.tournaments.path,\n { relatedTo: input.editionId, cursor: input.cursor || undefined, limit: input.limit },\n relatedPageSchema(),\n options,\n ).then(({ relatedTo, items, nextCursor: cursor }): ClubRelatedTournamentPage => {\n // A page about another edition is not about this one: read as empty, never mixed in.\n if (relatedTo !== input.editionId) return { items: [] }\n return cursor === undefined ? { items } : { items, nextCursor: cursor }\n })\n },\n\n getTournament: (input, options) => {\n const problem = idProblem('club.getTournament', 'editionId', isObject(input) ? input.editionId : undefined)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournament)\n return get(`${BASE}/tournaments/${segment(input.editionId)}`, {}, tournamentSchema(), options)\n },\n\n getRanking: (input, options) => {\n const name = 'club.getRanking'\n const problem = isObject(input)\n ? (idProblem(name, 'editionId', input.editionId) ?? limitProblem(name, input.limit))\n : `${name}: input must be { editionId }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.ranking)\n return get(\n `${BASE}/tournaments/${segment(input.editionId)}/ranking`,\n { limit: input.limit },\n rankingSchema(),\n options,\n )\n },\n\n setMembership: (input, options) => {\n const problem = membershipProblem(input) ?? keyProblem('club.setMembership', options)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.membership)\n const body = input.joined\n ? { versionId: input.versionId, joined: true, termsLocale: input.termsLocale }\n : { versionId: input.versionId, joined: false }\n return write('PUT', ROUTES.membership.path, body, programSchema(), options)\n },\n\n play: (input, options) => {\n const name = 'club.play'\n const problem = isObject(input)\n ? (idProblem(name, 'activityId', input.activityId) ??\n idProblem(name, 'versionId', input.versionId) ??\n optionalTextProblem(name, 'optionId', input.optionId) ??\n keyProblem(name, options))\n : `${name}: input must be { activityId, versionId, optionId? }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.play)\n const body: Record<string, unknown> = { versionId: input.versionId }\n if (input.optionId) body.optionId = input.optionId\n return write('POST', `${BASE}/activities/${segment(input.activityId)}/plays`, body, playSchema(), options).then(\n requireObject<ClubPlayResult>(transport, ROUTES.play, 'receipt'),\n )\n },\n\n redeem: (input, options) => {\n const name = 'club.redeem'\n const problem = isObject(input)\n ? (idProblem(name, 'rewardId', input.rewardId) ??\n idProblem(name, 'versionId', input.versionId) ??\n keyProblem(name, options))\n : `${name}: input must be { rewardId, versionId }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.redeem)\n return write(\n 'POST',\n `${BASE}/rewards/${segment(input.rewardId)}/redemptions`,\n { versionId: input.versionId },\n receiptSchema(),\n options,\n )\n },\n\n registerForTournament: (input, options) => {\n const name = 'club.registerForTournament'\n const problem = isObject(input)\n ? (idProblem(name, 'editionId', input.editionId) ??\n idProblem(name, 'versionId', input.versionId) ??\n optionalTextProblem(name, 'ticketId', input.ticketId) ??\n keyProblem(name, options))\n : `${name}: input must be { editionId, versionId, ticketId? }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.register)\n const body: Record<string, unknown> = { versionId: input.versionId }\n if (input.ticketId) body.ticketId = input.ticketId\n return write(\n 'POST',\n `${BASE}/tournaments/${segment(input.editionId)}/registrations`,\n body,\n registrationSchema(),\n options,\n )\n },\n }\n}\n","/**\n * iGaming query and mutation factories, compatible with TanStack Query v5 (`useQuery`,\n * `useMutation`, `prefetchQuery`), without depending on it. Same key conventions as\n * `@getenginex/sdk/query`.\n * @module @getenginex/sdk-igaming/query\n */\n\nimport { isEnginexError, type CallOptions } from '@getenginex/sdk'\nimport {\n queryScope,\n type IdempotentMutationsOf,\n type MutationsOf,\n type QueriesOf,\n type QueryScope,\n} from '@getenginex/sdk/query'\nimport type { IgamingClient } from '../client'\nimport { LOCALE } from '../internal/input'\nimport type { BetsApi } from '../modules/bets'\nimport type { BonusApi } from '../modules/bonus'\nimport type { CasinoApi } from '../modules/casino'\nimport { keepsClubIdempotencyKey, type ClubApi } from '../modules/club'\nimport type { LoyaltyApi } from '../modules/loyalty'\nimport type { MissionsApi } from '../modules/missions'\nimport type { ReferralsApi } from '../modules/referrals'\nimport type { SportsbookApi } from '../modules/sportsbook'\n\n/**\n * iGaming query factories, one per read method: `q.<namespace>.<method>(input)` returns\n * `{ queryKey, queryFn }`. Obtained with {@link createIgamingQueries}.\n * @category Queries\n */\nexport interface IgamingQueries {\n /** Catalog and lobby jackpots (public) and, with login, sessions, history and biggest winners. */\n readonly casino: QueriesOf<\n CasinoApi,\n | 'listGames'\n | 'listCategories'\n | 'listProviders'\n | 'getGame'\n | 'listJackpots'\n | 'listJackpotGames'\n | 'listSessions'\n | 'getHistory'\n | 'getBiggestWinners'\n >\n /** Casino club: overview, history, tournaments, related editions, a tournament and its ranking. */\n readonly club: QueriesOf<\n ClubApi,\n 'getOverview' | 'listHistory' | 'listTournaments' | 'listRelatedTournaments' | 'getTournament' | 'getRanking'\n >\n /** Public offers (no login) and, with login, offers, participations, bonus overview and positions. */\n readonly bonus: QueriesOf<\n BonusApi,\n | 'listPublicOffers'\n | 'listOffers'\n | 'getOffer'\n | 'listParticipations'\n | 'getParticipation'\n | 'getOverview'\n | 'listPositions'\n >\n /** Operator missions and the player's own (with or without history). */\n readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine' | 'getMine'>\n /** Points balance, tier and benefits. */\n readonly loyalty: QueriesOf<LoyaltyApi, 'get'>\n /** Referral code, program rules, totals and history. */\n readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>\n /** The player's bets, a bet's details and its cash-out offer. */\n readonly bets: QueriesOf<BetsApi, 'list' | 'get' | 'getCashoutOffer'>\n}\n\n/**\n * iGaming mutations, one per write method: `m.<namespace>.<method>()` returns\n * `{ mutationKey, mutationFn, invalidates }`. Obtained with {@link createIgamingMutations}.\n * @category Queries\n */\nexport interface IgamingMutations {\n /** Game launch (`launchGame`, with `gcTime: 0`: the game URL carries credentials). */\n readonly casino: MutationsOf<CasinoApi, 'launchGame'>\n /** Club membership, plays, redemptions and tournament registration (idempotent: they accept `{ idempotencyKey }`). */\n readonly club: IdempotentMutationsOf<ClubApi, 'setMembership' | 'play' | 'redeem' | 'registerForTournament'>\n /** Opt-in, redemption (idempotent: they accept `{ idempotencyKey }`) and promo code check. */\n readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> &\n MutationsOf<BonusApi, 'resolvePromoCode'>\n /** Points redemption (idempotent: it accepts `{ idempotencyKey }`). */\n readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>\n /** Sportsbook session (`gcTime: 0`: the URL carries the operator token). */\n readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>\n /** Bet cash-out (idempotent: it accepts `{ idempotencyKey }`). */\n readonly bets: IdempotentMutationsOf<BetsApi, 'cashout'>\n}\n\ntype Method = (input: unknown, options?: CallOptions) => Promise<unknown>\n\n// Calls `igaming[namespace][method]` at request time (not at creation), keeping `this`.\nconst methodOf = (igaming: object, namespace: string, method: string) => (input: unknown, options: CallOptions) =>\n ((igaming as Record<string, Record<string, Method>>)[namespace]![method] as Method).call(\n (igaming as Record<string, unknown>)[namespace],\n input,\n options,\n )\n\n// Reads without a session (the method sends no token): `public` key, no `staleTime`.\nconst PUBLIC_READS = {\n casino: ['listGames', 'listCategories', 'listProviders', 'getGame', 'listJackpots', 'listJackpotGames'],\n bonus: ['listPublicOffers'],\n} as const\n\n// Player reads: `user` key with the session's `userId`.\nconst USER_READS = {\n casino: ['listSessions', 'getHistory', 'getBiggestWinners'],\n club: ['getOverview', 'listHistory', 'listTournaments', 'listRelatedTournaments', 'getTournament', 'getRanking'],\n bonus: ['listOffers', 'getOffer', 'listParticipations', 'getParticipation', 'getOverview', 'listPositions'],\n missions: ['list', 'listMine', 'getMine'],\n loyalty: ['get'],\n referrals: ['get', 'listHistory'],\n bets: ['list', 'get', 'getCashoutOffer'],\n} as const\n\n// Namespaces whose responses depend on the client's locale: their keys end with `{ locale }`.\nconst LOCALE_KEYED: ReadonlySet<string> = /* @__PURE__ */ new Set(['club'])\n\n// Inputs that mean the same request share one cache entry: `getMine()`, `getMine({})` and\n// `getMine({ includeHistory: false })` all send no query string. Anything else (an invalid input included, so the\n// method still rejects it) is kept as it came.\nconst NORMALIZE: Record<string, (input: unknown) => unknown> = {\n 'missions.getMine': (input) => {\n if (input === undefined) return undefined\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return input\n const keys = Object.keys(input)\n const flag = (input as { includeHistory?: unknown }).includeHistory\n if (keys.some((key) => key !== 'includeHistory')) return input\n if (flag === undefined || flag === false) return undefined\n return flag === true ? { includeHistory: true } : input\n },\n}\n\n/** The client's locale right now (`null` without one, or with a core older than 0.12.0). */\nfunction localeOf(igaming: object): string | null {\n const read = (igaming as Record<symbol, (() => string | undefined) | undefined>)[LOCALE]\n return (typeof read === 'function' ? read() : undefined) ?? null\n}\n\ntype Invalidation = (scope: QueryScope) => readonly (readonly unknown[])[]\nconst userKeys =\n (...prefixes: [namespace: string, method?: string][]): Invalidation =>\n (scope) =>\n prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method))\nconst none: Invalidation = () => []\n\ninterface Write {\n /** What the write leaves stale. The core's prefixes (`wallet`) come from `scope.userPrefix`. */\n invalidates: Invalidation\n /** Sends `Idempotency-Key` (accepts `{ idempotencyKey }`). */\n idempotent?: boolean\n /** Entry or result with a credential: `gcTime: 0`. */\n sensitive?: boolean\n /** Extra failures that keep the key (core `>=0.12.0`; older cores ignore it). */\n keepsKey?: (error: unknown) => boolean\n /** What a failure leaves stale (`invalidatesOnError`): `invalidates` when `when(error)` holds. */\n onError?: { when: (error: unknown) => boolean; invalidates: Invalidation }\n}\n\nconst isConflict = (error: unknown) => isEnginexError(error) && error.status === 409\nconst onConflict = (invalidates: Invalidation) => ({ when: isConflict, invalidates })\n\n// A failure after which the write may have happened: network, timeout, 5xx, `KEY_IN_USE`, or a 2xx the SDK could not\n// confirm (`UNKNOWN` with a 2xx status, `VALIDATION_ERROR` of a malformed answer). The same classes the core's\n// `isAmbiguousFailure` keeps the key for, plus the unconfirmed 2xx; written here so it holds with any core.\nconst leavesStateUnknown = (error: unknown) =>\n isEnginexError(error) &&\n (error.code === 'NETWORK_ERROR' ||\n error.code === 'TIMEOUT' ||\n error.code === 'KEY_IN_USE' ||\n error.status >= 500 ||\n (error.status >= 200 && error.status < 300) ||\n (error.code === 'VALIDATION_ERROR' && error.status < 400))\n\n// The club writes keep the key after a 409 (an in-flight duplicate looks like any conflict) and, on a 409 (a stale\n// `versionId`, a wallet not confirmed), refresh what the retry must read again.\nconst CLUB_WRITE = { idempotent: true, keepsKey: keepsClubIdempotencyKey } as const\nconst CLUB_MONEY = userKeys(['club', 'getOverview'], ['club', 'listHistory'], ['bonus'], ['wallet'])\n\nconst WRITES: Record<string, Record<string, Write>> = {\n casino: { launchGame: { invalidates: userKeys(['casino', 'listSessions']), sensitive: true } },\n club: {\n setMembership: {\n ...CLUB_WRITE,\n invalidates: userKeys(['club']),\n onError: onConflict(userKeys(['club', 'getOverview'])),\n },\n // A play or a redemption moves coins, XP, the history and maybe a bonus or the balance; never the tournaments.\n play: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(['club', 'getOverview'])) },\n redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(['club', 'getOverview'])) },\n registerForTournament: {\n ...CLUB_WRITE,\n invalidates: userKeys(['club']),\n onError: onConflict(userKeys(['club', 'getOverview'], ['club', 'listTournaments'], ['club', 'getTournament'])),\n },\n },\n bonus: {\n resolvePromoCode: { invalidates: none, sensitive: true },\n optIn: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n claim: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n redeemPromoCode: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true, sensitive: true },\n },\n loyalty: {\n // An ambiguous failure may have redeemed the points: refetch them and the balance before a retry is offered.\n redeem: {\n invalidates: userKeys(['loyalty'], ['wallet']),\n idempotent: true,\n onError: { when: leavesStateUnknown, invalidates: userKeys(['loyalty'], ['wallet']) },\n },\n },\n sportsbook: { createSession: { invalidates: none, sensitive: true } },\n bets: { cashout: { invalidates: userKeys(['bets'], ['wallet']), idempotent: true } },\n}\n\n/**\n * Creates the iGaming query factories: one per read method, with the same name and the same input\n * as the method (`q.casino.listGames({ page })`). Each call returns `{ queryKey, queryFn }`, compatible\n * with TanStack Query v5's `useQuery`/`prefetchQuery`/`fetchQuery`. It makes no request.\n *\n * - Reads without a session (`casino.listGames/listCategories/listProviders/getGame/listJackpots/listJackpotGames`,\n * `bonus.listPublicOffers`): key `['enginex', 'public', namespace, method, input?]`.\n * - The `club` reads also end with `{ locale }` (the client's locale, `null` without one): the club answers in that\n * locale, so after `setLocale` a factory called again returns a new key and the program (with its\n * `termsLocale`) is fetched again instead of a join recording consent under the old terms. Prefix invalidation\n * (`['enginex', 'user', userId, 'club']`) still matches every locale. Needs core `>=0.12.0` (older: `null`).\n * - Player reads (the others): key `['enginex', 'user', userId, namespace, method, input?]`,\n * with the session's `userId` when the factory is called; without a session, `'anonymous'` and the `queryFn`\n * rejects with `UNAUTHENTICATED` without a request (the same if the session switches user before the `fetch`).\n * - `missions.getMine()`, `getMine({})` and `getMine({ includeHistory: false })` share one key (they send the same\n * request); `getMine({ includeHistory: true })` has its own.\n * - `queryFn` forwards the context's `signal`: canceling the query aborts the `fetch`.\n * - None carries `staleTime`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useQuery } from '@tanstack/react-query'\n * import { createIgamingQueries } from '@getenginex/sdk-igaming/query'\n *\n * const q = createIgamingQueries(igaming)\n * const games = useQuery(q.casino.listGames({ category: 'slots' }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming` (e.g. a\n * `{ ...igaming }` copy). Identify with `isEnginexError(error, 'CONFIGURATION_ERROR')`.\n * @category Queries\n */\nexport function createIgamingQueries(igaming: IgamingClient): IgamingQueries {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (input?: unknown) => unknown>> = {}\n const add = (\n table: Record<string, readonly string[]>,\n build: (namespace: string, method: string, input: unknown) => unknown,\n ) => {\n for (const [namespace, methods] of Object.entries(table)) {\n const factories = (out[namespace] ??= {})\n for (const method of methods) factories[method] = (input) => build(namespace, method, input)\n }\n }\n add(PUBLIC_READS, (namespace, method, input) =>\n scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input),\n )\n add(USER_READS, (namespace, method, raw) => {\n const normalize = NORMALIZE[`${namespace}.${method}`]\n const input = normalize ? normalize(raw) : raw\n const options = scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input)\n if (!LOCALE_KEYED.has(namespace)) return options\n // The club answers in the client's locale (texts, `termsLocale`): a `setLocale` must not reuse the cached\n // program, or a join would record consent under the terms of the old language.\n return { ...options, queryKey: [...options.queryKey, { locale: localeOf(igaming) }] }\n })\n return out as unknown as IgamingQueries\n}\n\n/**\n * Creates the iGaming mutations: one per write method, with the same name as the method\n * (`m.loyalty.redeem()`). Each call returns `{ mutationKey, mutationFn, invalidates }`, compatible\n * with TanStack Query v5's `useMutation`; `invalidates(input, result)` lists the prefixes the write\n * leaves stale (with the session's `userId` at call time; call it only after success):\n *\n * - `bonus.optIn/claim/redeemPromoCode` → `bonus` and `wallet` (the core's balance);\n * - `loyalty.redeem` → `loyalty` and `wallet`, also through `invalidatesOnError` after an ambiguous failure (network,\n * timeout, 5xx, `KEY_IN_USE`, or a 2xx it could not confirm: `UNKNOWN`/`VALIDATION_ERROR`), when the points may\n * have been redeemed;\n * - `bets.cashout` → `bets` and `wallet`;\n * - `club.play/redeem` → `club.getOverview`, `club.listHistory`, `bonus` and `wallet` (a reward may credit a bonus or\n * the balance; the tournaments and rankings are not refetched); `club.setMembership/registerForTournament` →\n * `club`. The club writes also carry `invalidatesOnError`: on a 409 (a stale `versionId`) they refresh\n * `club.getOverview` (and, for `registerForTournament`, the tournaments), like the player did on settle;\n * `useEnginexMutation` runs it in `onError`, plain TanStack calls it in its own `onError`;\n * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` and\n * `sportsbook.createSession` → nothing.\n *\n * `mutationKey` is `['enginex', namespace, method]`, without the input. The ones that send `Idempotency-Key`\n * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`, `bets.cashout`, the four `club` writes) reuse the key only after an ambiguous\n * failure (network, timeout, 5xx, `KEY_IN_USE` or `VALIDATION_ERROR` after a 2xx) with the same input,\n * on this options object (see the core's `createMutations`), and accept `{ idempotencyKey }` on the factory. The\n * `club` writes also keep it after a 409 or 429 and release it only on 400/403/404/422 (see\n * `keepsClubIdempotencyKey`; needs core `>=0.12.0`). The\n * ones that carry credentials in the input or the result (promo code, game URL, sportsbook\n * session) have `gcTime: 0`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useMutation } from '@tanstack/react-query'\n * import { createIgamingMutations } from '@getenginex/sdk-igaming/query'\n *\n * const m = createIgamingMutations(igaming)\n * const redeem = m.loyalty.redeem()\n * const result = await redeem.mutationFn({ points: 500, redemptionType: 'bonus' })\n * for (const queryKey of redeem.invalidates({ points: 500, redemptionType: 'bonus' }, result)) {\n * await queryClient.invalidateQueries({ queryKey })\n * }\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming`.\n * @category Queries\n */\nexport function createIgamingMutations(igaming: IgamingClient): IgamingMutations {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (options?: { idempotencyKey?: string }) => unknown>> = {}\n for (const [namespace, methods] of Object.entries(WRITES)) {\n const factories = (out[namespace] ??= {})\n for (const [method, write] of Object.entries(methods)) {\n factories[method] = (options) => {\n const scoped: {\n idempotent?: boolean\n idempotencyKey?: string\n gcTime?: number\n keepsKey?: (error: unknown) => boolean\n } = {}\n if (write.idempotent === true) {\n scoped.idempotent = true\n if (write.keepsKey) scoped.keepsKey = write.keepsKey\n if (options?.idempotencyKey !== undefined) scoped.idempotencyKey = options.idempotencyKey\n }\n if (write.sensitive === true) scoped.gcTime = 0\n const mutation = scope.mutation(\n namespace,\n method,\n methodOf(igaming, namespace, method),\n () => write.invalidates(scope),\n scoped,\n )\n const refresh = write.onError\n // Set here (not through the scope) so it holds with any core; the adapters run it in `onError`.\n if (refresh)\n mutation.invalidatesOnError = (_input, error) => (refresh.when(error) ? refresh.invalidates(scope) : [])\n return mutation\n }\n }\n }\n return out as unknown as IgamingMutations\n}\n"]}
@@ -21,8 +21,8 @@ interface IgamingQueries {
21
21
  readonly club: QueriesOf<ClubApi, 'getOverview' | 'listHistory' | 'listTournaments' | 'listRelatedTournaments' | 'getTournament' | 'getRanking'>;
22
22
  /** Public offers (no login) and, with login, offers, participations, bonus overview and positions. */
23
23
  readonly bonus: QueriesOf<BonusApi, 'listPublicOffers' | 'listOffers' | 'getOffer' | 'listParticipations' | 'getParticipation' | 'getOverview' | 'listPositions'>;
24
- /** Operator missions and the player's own. */
25
- readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>;
24
+ /** Operator missions and the player's own (with or without history). */
25
+ readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine' | 'getMine'>;
26
26
  /** Points balance, tier and benefits. */
27
27
  readonly loyalty: QueriesOf<LoyaltyApi, 'get'>;
28
28
  /** Referral code, program rules, totals and history. */
@@ -63,6 +63,8 @@ interface IgamingMutations {
63
63
  * - Player reads (the others): key `['enginex', 'user', userId, namespace, method, input?]`,
64
64
  * with the session's `userId` when the factory is called; without a session, `'anonymous'` and the `queryFn`
65
65
  * rejects with `UNAUTHENTICATED` without a request (the same if the session switches user before the `fetch`).
66
+ * - `missions.getMine()`, `getMine({})` and `getMine({ includeHistory: false })` share one key (they send the same
67
+ * request); `getMine({ includeHistory: true })` has its own.
66
68
  * - `queryFn` forwards the context's `signal`: canceling the query aborts the `fetch`.
67
69
  * - None carries `staleTime`.
68
70
  * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).
@@ -84,7 +86,9 @@ declare function createIgamingQueries(igaming: IgamingClient): IgamingQueries;
84
86
  * leaves stale (with the session's `userId` at call time; call it only after success):
85
87
  *
86
88
  * - `bonus.optIn/claim/redeemPromoCode` → `bonus` and `wallet` (the core's balance);
87
- * - `loyalty.redeem` → `loyalty` and `wallet`;
89
+ * - `loyalty.redeem` → `loyalty` and `wallet`, also through `invalidatesOnError` after an ambiguous failure (network,
90
+ * timeout, 5xx, `KEY_IN_USE`, or a 2xx it could not confirm: `UNKNOWN`/`VALIDATION_ERROR`), when the points may
91
+ * have been redeemed;
88
92
  * - `bets.cashout` → `bets` and `wallet`;
89
93
  * - `club.play/redeem` → `club.getOverview`, `club.listHistory`, `bonus` and `wallet` (a reward may credit a bonus or
90
94
  * the balance; the tournaments and rankings are not refetched); `club.setMembership/registerForTournament` →
@@ -21,8 +21,8 @@ interface IgamingQueries {
21
21
  readonly club: QueriesOf<ClubApi, 'getOverview' | 'listHistory' | 'listTournaments' | 'listRelatedTournaments' | 'getTournament' | 'getRanking'>;
22
22
  /** Public offers (no login) and, with login, offers, participations, bonus overview and positions. */
23
23
  readonly bonus: QueriesOf<BonusApi, 'listPublicOffers' | 'listOffers' | 'getOffer' | 'listParticipations' | 'getParticipation' | 'getOverview' | 'listPositions'>;
24
- /** Operator missions and the player's own. */
25
- readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>;
24
+ /** Operator missions and the player's own (with or without history). */
25
+ readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine' | 'getMine'>;
26
26
  /** Points balance, tier and benefits. */
27
27
  readonly loyalty: QueriesOf<LoyaltyApi, 'get'>;
28
28
  /** Referral code, program rules, totals and history. */
@@ -63,6 +63,8 @@ interface IgamingMutations {
63
63
  * - Player reads (the others): key `['enginex', 'user', userId, namespace, method, input?]`,
64
64
  * with the session's `userId` when the factory is called; without a session, `'anonymous'` and the `queryFn`
65
65
  * rejects with `UNAUTHENTICATED` without a request (the same if the session switches user before the `fetch`).
66
+ * - `missions.getMine()`, `getMine({})` and `getMine({ includeHistory: false })` share one key (they send the same
67
+ * request); `getMine({ includeHistory: true })` has its own.
66
68
  * - `queryFn` forwards the context's `signal`: canceling the query aborts the `fetch`.
67
69
  * - None carries `staleTime`.
68
70
  * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).
@@ -84,7 +86,9 @@ declare function createIgamingQueries(igaming: IgamingClient): IgamingQueries;
84
86
  * leaves stale (with the session's `userId` at call time; call it only after success):
85
87
  *
86
88
  * - `bonus.optIn/claim/redeemPromoCode` → `bonus` and `wallet` (the core's balance);
87
- * - `loyalty.redeem` → `loyalty` and `wallet`;
89
+ * - `loyalty.redeem` → `loyalty` and `wallet`, also through `invalidatesOnError` after an ambiguous failure (network,
90
+ * timeout, 5xx, `KEY_IN_USE`, or a 2xx it could not confirm: `UNKNOWN`/`VALIDATION_ERROR`), when the points may
91
+ * have been redeemed;
88
92
  * - `bets.cashout` → `bets` and `wallet`;
89
93
  * - `club.play/redeem` → `club.getOverview`, `club.listHistory`, `bonus` and `wallet` (a reward may credit a bonus or
90
94
  * the balance; the tournaments and rankings are not refetched); `club.setMembership/registerForTournament` →