@getenginex/sdk-igaming 0.10.0 → 0.11.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.
@@ -1,5 +1,21 @@
1
1
  import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
2
2
 
3
+ /**
4
+ * Options of the club mock (`createIgamingRoutes({ club })`).
5
+ * @category Testing
6
+ */
7
+ interface ClubMockOptions {
8
+ /**
9
+ * State of the program:
10
+ * - `active` (default): the player has not joined yet; wheel, chest, store and tournaments;
11
+ * - `paused`: `enabled: false` with the history readable; the overview keeps only the pending chest (`right-1`,
12
+ * with only its right and `rightVersionId: 'club-v0'`), activities and store come empty, tournaments 404;
13
+ * - `disabled`: `enabled: false` without history: the overview omits `rewards`, tournaments 404 and the writes are
14
+ * `ALREADY_EXISTS` (409).
15
+ */
16
+ program?: 'active' | 'paused' | 'disabled';
17
+ }
18
+
3
19
  /**
4
20
  * iGaming mock routes to add to the `createMockFetch` of `@getenginex/sdk/testing`.
5
21
  * @module @getenginex/sdk-igaming/testing
@@ -35,6 +51,19 @@ import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
35
51
  * (80% of the potential return, only for the pending bet) and `POST /bets/:betId/cashout`, which requires
36
52
  * `Idempotency-Key`, moves the bet to `cashed_out` and replays the first response for the same key.
37
53
  *
54
+ * Covers the casino `club` (`/casino/club/*`, answered without the envelope, like the gateway): a program the
55
+ * player has not joined yet (`PUT /casino/club/membership` joins it), a daily wheel (`wheel-daily`, the slice drawn
56
+ * from the `Idempotency-Key`), a mission chest ready to open (`play({ activityId: 'right-1', optionId })`), a coin
57
+ * store (500 coins; `item-spins` costs 200, `item-cash` 5000), the history (receipts newest first, cursor-paginated
58
+ * by `limit`), an own tournament open for registration (`tour-own-1`, with a ranking) and an external one
59
+ * (`ext_tlt_weekly_1`, with one related edition and `CLUB_RANKING_UNAVAILABLE`). Every write requires
60
+ * `Idempotency-Key`: the same key with the same body replays the first answer, with another body (or a stale
61
+ * `versionId`, or before joining) it is `ALREADY_EXISTS` (409).
62
+ * `createIgamingRoutes({ club: { program: 'paused' | 'disabled' } })` switches the program state; a key starting
63
+ * with `inflight-` answers 409 once (a duplicate in flight) and one starting with `lost-` applies the write and
64
+ * answers 503 once (see {@link ClubMockOptions}). The related page has an edition with `title: null` and Go's zero
65
+ * times, as the gateway's `encoding/json` writes them.
66
+ *
38
67
  * Covers the `sportsbook`: `GET /first/session` (requires login) returns a fictitious FIRST URL
39
68
  * (`https://first.mock.local/sportsbook?operatorToken=...`) valid for 24 h.
40
69
  *
@@ -49,6 +78,7 @@ import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
49
78
  * the names already masked, paginated by `page`/`limit` inside `data`, like the gateway).
50
79
  *
51
80
  * All responses match the SDK schemas, even with `validation: 'strict'`.
81
+ * @param options - Mock states, e.g. `{ club: { program: 'paused' } }`. Default: an active club.
52
82
  * @example
53
83
  * import { createMockFetch } from '@getenginex/sdk/testing'
54
84
  * import { createIgamingRoutes } from '@getenginex/sdk-igaming/testing'
@@ -56,13 +86,13 @@ import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
56
86
  * const fetch = createMockFetch({ routes: { ...createIgamingRoutes(), ...myRoutes } })
57
87
  * @category Testing
58
88
  */
59
- declare function createIgamingRoutes(): Record<string, MockHandler>;
89
+ declare function createIgamingRoutes(options?: IgamingRoutesOptions): Record<string, MockHandler>;
60
90
  /**
61
91
  * Adds the iGaming mock routes ({@link createIgamingRoutes}) to the options of `createMockFetch` from
62
92
  * `@getenginex/sdk/testing`. The core routes still apply; the ones in `options.routes` win over the
63
93
  * iGaming ones (to simulate errors). The other options (`twoFactorRequired`, `withdrawalOtp`, `user`)
64
94
  * pass through as they are, and `options` is not changed.
65
- * @param options - The options you would pass to `createMockFetch`.
95
+ * @param options - The options you would pass to `createMockFetch`, plus `club` (see {@link IgamingRoutesOptions}).
66
96
  * @example
67
97
  * import { createEnginexClient } from '@getenginex/sdk'
68
98
  * import { createMockFetch, fail } from '@getenginex/sdk/testing'
@@ -79,6 +109,14 @@ declare function createIgamingRoutes(): Record<string, MockHandler>;
79
109
  * const igaming = createIgaming(enginex)
80
110
  * @category Testing
81
111
  */
82
- declare function withIgamingRoutes(options?: MockFetchOptions): MockFetchOptions;
112
+ declare function withIgamingRoutes(options?: MockFetchOptions & IgamingRoutesOptions): MockFetchOptions;
113
+ /**
114
+ * Options of {@link createIgamingRoutes} (and of {@link withIgamingRoutes}, next to the core's).
115
+ * @category Testing
116
+ */
117
+ interface IgamingRoutesOptions {
118
+ /** State of the club mock (default: an active program the player has not joined). */
119
+ club?: ClubMockOptions;
120
+ }
83
121
 
84
- export { createIgamingRoutes, withIgamingRoutes };
122
+ export { type ClubMockOptions, type IgamingRoutesOptions, createIgamingRoutes, withIgamingRoutes };
@@ -1,5 +1,21 @@
1
1
  import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
2
2
 
3
+ /**
4
+ * Options of the club mock (`createIgamingRoutes({ club })`).
5
+ * @category Testing
6
+ */
7
+ interface ClubMockOptions {
8
+ /**
9
+ * State of the program:
10
+ * - `active` (default): the player has not joined yet; wheel, chest, store and tournaments;
11
+ * - `paused`: `enabled: false` with the history readable; the overview keeps only the pending chest (`right-1`,
12
+ * with only its right and `rightVersionId: 'club-v0'`), activities and store come empty, tournaments 404;
13
+ * - `disabled`: `enabled: false` without history: the overview omits `rewards`, tournaments 404 and the writes are
14
+ * `ALREADY_EXISTS` (409).
15
+ */
16
+ program?: 'active' | 'paused' | 'disabled';
17
+ }
18
+
3
19
  /**
4
20
  * iGaming mock routes to add to the `createMockFetch` of `@getenginex/sdk/testing`.
5
21
  * @module @getenginex/sdk-igaming/testing
@@ -35,6 +51,19 @@ import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
35
51
  * (80% of the potential return, only for the pending bet) and `POST /bets/:betId/cashout`, which requires
36
52
  * `Idempotency-Key`, moves the bet to `cashed_out` and replays the first response for the same key.
37
53
  *
54
+ * Covers the casino `club` (`/casino/club/*`, answered without the envelope, like the gateway): a program the
55
+ * player has not joined yet (`PUT /casino/club/membership` joins it), a daily wheel (`wheel-daily`, the slice drawn
56
+ * from the `Idempotency-Key`), a mission chest ready to open (`play({ activityId: 'right-1', optionId })`), a coin
57
+ * store (500 coins; `item-spins` costs 200, `item-cash` 5000), the history (receipts newest first, cursor-paginated
58
+ * by `limit`), an own tournament open for registration (`tour-own-1`, with a ranking) and an external one
59
+ * (`ext_tlt_weekly_1`, with one related edition and `CLUB_RANKING_UNAVAILABLE`). Every write requires
60
+ * `Idempotency-Key`: the same key with the same body replays the first answer, with another body (or a stale
61
+ * `versionId`, or before joining) it is `ALREADY_EXISTS` (409).
62
+ * `createIgamingRoutes({ club: { program: 'paused' | 'disabled' } })` switches the program state; a key starting
63
+ * with `inflight-` answers 409 once (a duplicate in flight) and one starting with `lost-` applies the write and
64
+ * answers 503 once (see {@link ClubMockOptions}). The related page has an edition with `title: null` and Go's zero
65
+ * times, as the gateway's `encoding/json` writes them.
66
+ *
38
67
  * Covers the `sportsbook`: `GET /first/session` (requires login) returns a fictitious FIRST URL
39
68
  * (`https://first.mock.local/sportsbook?operatorToken=...`) valid for 24 h.
40
69
  *
@@ -49,6 +78,7 @@ import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
49
78
  * the names already masked, paginated by `page`/`limit` inside `data`, like the gateway).
50
79
  *
51
80
  * All responses match the SDK schemas, even with `validation: 'strict'`.
81
+ * @param options - Mock states, e.g. `{ club: { program: 'paused' } }`. Default: an active club.
52
82
  * @example
53
83
  * import { createMockFetch } from '@getenginex/sdk/testing'
54
84
  * import { createIgamingRoutes } from '@getenginex/sdk-igaming/testing'
@@ -56,13 +86,13 @@ import { MockHandler, MockFetchOptions } from '@getenginex/sdk/testing';
56
86
  * const fetch = createMockFetch({ routes: { ...createIgamingRoutes(), ...myRoutes } })
57
87
  * @category Testing
58
88
  */
59
- declare function createIgamingRoutes(): Record<string, MockHandler>;
89
+ declare function createIgamingRoutes(options?: IgamingRoutesOptions): Record<string, MockHandler>;
60
90
  /**
61
91
  * Adds the iGaming mock routes ({@link createIgamingRoutes}) to the options of `createMockFetch` from
62
92
  * `@getenginex/sdk/testing`. The core routes still apply; the ones in `options.routes` win over the
63
93
  * iGaming ones (to simulate errors). The other options (`twoFactorRequired`, `withdrawalOtp`, `user`)
64
94
  * pass through as they are, and `options` is not changed.
65
- * @param options - The options you would pass to `createMockFetch`.
95
+ * @param options - The options you would pass to `createMockFetch`, plus `club` (see {@link IgamingRoutesOptions}).
66
96
  * @example
67
97
  * import { createEnginexClient } from '@getenginex/sdk'
68
98
  * import { createMockFetch, fail } from '@getenginex/sdk/testing'
@@ -79,6 +109,14 @@ declare function createIgamingRoutes(): Record<string, MockHandler>;
79
109
  * const igaming = createIgaming(enginex)
80
110
  * @category Testing
81
111
  */
82
- declare function withIgamingRoutes(options?: MockFetchOptions): MockFetchOptions;
112
+ declare function withIgamingRoutes(options?: MockFetchOptions & IgamingRoutesOptions): MockFetchOptions;
113
+ /**
114
+ * Options of {@link createIgamingRoutes} (and of {@link withIgamingRoutes}, next to the core's).
115
+ * @category Testing
116
+ */
117
+ interface IgamingRoutesOptions {
118
+ /** State of the club mock (default: an active program the player has not joined). */
119
+ club?: ClubMockOptions;
120
+ }
83
121
 
84
- export { createIgamingRoutes, withIgamingRoutes };
122
+ export { type ClubMockOptions, type IgamingRoutesOptions, createIgamingRoutes, withIgamingRoutes };
@@ -64,8 +64,8 @@ var SEED = [
64
64
  function pageOf(req, items) {
65
65
  const q = req.url.searchParams;
66
66
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
67
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
68
- const limit = raw >= 1 && raw <= 100 ? raw : 20;
67
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
68
+ const limit = raw2 >= 1 && raw2 <= 100 ? raw2 : 20;
69
69
  return {
70
70
  items: items.slice((page - 1) * limit, page * limit),
71
71
  meta: { page, per_page: limit, total_pages: Math.ceil(items.length / limit), total_items: items.length }
@@ -600,8 +600,8 @@ function json(body, status = 200) {
600
600
  function pageOf2(req, items) {
601
601
  const q = req.url.searchParams;
602
602
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
603
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
604
- const limit = raw >= 1 && raw <= 100 ? raw : 20;
603
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
604
+ const limit = raw2 >= 1 && raw2 <= 100 ? raw2 : 20;
605
605
  return {
606
606
  items: items.slice((page - 1) * limit, page * limit),
607
607
  meta: { page, per_page: limit, total_pages: Math.ceil(items.length / limit), total_items: items.length }
@@ -720,11 +720,447 @@ function createCasinoRoutes() {
720
720
  return ok(items, meta);
721
721
  },
722
722
  "GET /api/v1/games/biggest-winners": (req) => {
723
- const raw = Number.parseInt(req.url.searchParams.get("limit") ?? "", 10);
724
- return ok(WINNERS.slice(0, raw >= 1 ? raw : 10));
723
+ const raw2 = Number.parseInt(req.url.searchParams.get("limit") ?? "", 10);
724
+ return ok(WINNERS.slice(0, raw2 >= 1 ? raw2 : 10));
725
725
  }
726
726
  };
727
727
  }
728
+ function raw(body, status = 200) {
729
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
730
+ }
731
+ var VERSION = "club-v1";
732
+ var TOURNAMENT_VERSION = "tour-v1";
733
+ var OWN = "tour-own-1";
734
+ var EXTERNAL = "ext_tlt_weekly_1";
735
+ var RELATED = "ext_tlt_weekly_2";
736
+ var GO_ZERO = "0001-01-01T00:00:00Z";
737
+ var BRL = (amount) => ({ currency: "BRL", amountMinor: String(amount), decimalPlaces: 2 });
738
+ var pt = (text) => ({ "pt-BR": text });
739
+ var at = (offsetMs) => new Date(Date.UTC(2026, 10, 24, 12) + offsetMs).toISOString().replace(/\.\d{3}Z$/, "Z");
740
+ var reward = (id, kind, quantity, extra = {}) => ({
741
+ id,
742
+ label: pt(id),
743
+ kind,
744
+ quantity: String(quantity),
745
+ ttlSeconds: "0",
746
+ editionId: "",
747
+ ...extra
748
+ });
749
+ var SLICES = [
750
+ { id: "slice-coins", reward: reward("r-coins-50", "coins", 50) },
751
+ { id: "slice-spins", reward: reward("r-spins-10", "free_spins", 10, { campaign: { spins: "10", gameId: "" } }) },
752
+ { id: "slice-bonus", reward: reward("r-bonus-10", "bonus_balance", 1, { money: BRL(1e3) }) }
753
+ ];
754
+ var CHEST = [reward("chest-coins", "coins", 100), reward("chest-spins", "free_spins", 5)];
755
+ var ITEMS = [
756
+ {
757
+ id: "item-spins",
758
+ label: pt("20 giros"),
759
+ terms: {},
760
+ costCoins: "200",
761
+ reward: reward("r-item-spins", "free_spins", 20),
762
+ coverUrl: ""
763
+ },
764
+ {
765
+ id: "item-cash",
766
+ label: pt("R$ 50"),
767
+ terms: {},
768
+ costCoins: "5000",
769
+ reward: reward("r-item-cash", "real_balance", 1, { money: BRL(5e3) }),
770
+ coverUrl: ""
771
+ }
772
+ ];
773
+ function hash(text) {
774
+ let h = 0;
775
+ for (const char of text) h = h * 31 + char.charCodeAt(0) >>> 0;
776
+ return h;
777
+ }
778
+ function createClubRoutes(options = {}) {
779
+ const mode = options.program ?? "active";
780
+ const active = mode === "active";
781
+ const state = {
782
+ joined: mode === "paused",
783
+ xp: 1200,
784
+ coins: 500,
785
+ wheelPlayed: false,
786
+ chestReceipt: null,
787
+ registration: null
788
+ };
789
+ const receipts = [];
790
+ const movements = [
791
+ { id: "mv-1", kind: "coins", units: "500", sourceId: "welcome", occurredAt: at(-864e5) },
792
+ { id: "mv-2", kind: "xp", units: "1200", sourceId: "welcome", occurredAt: at(-864e5) }
793
+ ];
794
+ const replays = /* @__PURE__ */ new Map();
795
+ const seenInFlight = /* @__PURE__ */ new Set();
796
+ const lostOnce = /* @__PURE__ */ new Set();
797
+ let sequence = 0;
798
+ const program = () => mode === "disabled" ? {
799
+ enabled: false,
800
+ joined: false,
801
+ membershipRequired: false,
802
+ canJoin: false,
803
+ historyAvailable: false,
804
+ versionId: "",
805
+ locale: "",
806
+ termsLocale: "",
807
+ timeZone: "",
808
+ currency: "",
809
+ name: {},
810
+ terms: {},
811
+ coinName: {},
812
+ coverUrl: "",
813
+ levels: []
814
+ } : activeProgram();
815
+ const activeProgram = () => ({
816
+ enabled: active,
817
+ joined: state.joined,
818
+ membershipRequired: true,
819
+ canJoin: active && !state.joined,
820
+ historyAvailable: true,
821
+ versionId: VERSION,
822
+ locale: "pt-BR",
823
+ termsLocale: "pt-BR",
824
+ timeZone: "America/Sao_Paulo",
825
+ currency: "BRL",
826
+ name: pt("Clube"),
827
+ terms: pt("Termos do clube"),
828
+ coinName: pt("moedas"),
829
+ coverUrl: "",
830
+ levels: [
831
+ { id: "bronze", name: pt("Bronze"), minXp: "0", benefit: pt("Roleta di\xE1ria") },
832
+ { id: "silver", name: pt("Prata"), minXp: "5000", benefit: pt("Cashback semanal") }
833
+ ]
834
+ });
835
+ const pausedRewards = () => ({
836
+ xp: String(state.xp),
837
+ coins: String(state.coins),
838
+ levelId: "bronze",
839
+ activities: [],
840
+ storeItems: [],
841
+ missions: state.chestReceipt === null ? [
842
+ {
843
+ mission: {
844
+ id: "mission-login",
845
+ title: pt("Entre 3 dias"),
846
+ terms: {},
847
+ recurrence: "",
848
+ countBy: "",
849
+ target: "0",
850
+ coverUrl: ""
851
+ },
852
+ editionId: "",
853
+ progress: "0",
854
+ rightId: "right-1",
855
+ canClaim: false,
856
+ claimExpiresAt: at(6 * 864e5),
857
+ chestOptions: [],
858
+ rightVersionId: "club-v0",
859
+ stampedDays: []
860
+ }
861
+ ] : []
862
+ });
863
+ const rewards = () => {
864
+ if (mode === "paused") return pausedRewards();
865
+ const activity = {
866
+ activity: {
867
+ id: "wheel-daily",
868
+ kind: "wheel",
869
+ name: pt("Roleta di\xE1ria"),
870
+ terms: {},
871
+ coverUrl: "",
872
+ wheelTheme: "emerald",
873
+ playLabel: pt("Girar"),
874
+ slices: SLICES
875
+ },
876
+ canPlay: state.joined && !state.wheelPlayed,
877
+ unavailableReason: ""
878
+ };
879
+ if (state.wheelPlayed) {
880
+ activity.latestReceipt = receipts.find((r) => r.sourceKind === "activity");
881
+ activity.availableAt = at(864e5);
882
+ }
883
+ const chest = {
884
+ mission: {
885
+ id: "mission-login",
886
+ title: pt("Entre 3 dias"),
887
+ terms: {},
888
+ recurrence: "weekly",
889
+ countBy: "day",
890
+ target: "3",
891
+ coverUrl: ""
892
+ },
893
+ editionId: "2026-W48",
894
+ progress: "3",
895
+ rightId: "right-1",
896
+ rightVersionId: VERSION,
897
+ chestOptions: CHEST,
898
+ canClaim: state.joined && state.chestReceipt === null,
899
+ endsAt: at(5 * 864e5),
900
+ claimExpiresAt: at(6 * 864e5),
901
+ stampedDays: ["2026-11-22", "2026-11-23", "2026-11-24"]
902
+ };
903
+ if (state.chestReceipt) chest.receipt = state.chestReceipt;
904
+ return {
905
+ xp: String(state.xp),
906
+ coins: String(state.coins),
907
+ levelId: "bronze",
908
+ activities: [activity],
909
+ missions: [chest],
910
+ storeItems: ITEMS.map((item) => ({
911
+ item,
912
+ canRedeem: state.joined && state.coins >= Number(item.costCoins),
913
+ unavailableReason: state.coins >= Number(item.costCoins) ? "" : "insufficient_coins"
914
+ }))
915
+ };
916
+ };
917
+ const tournaments = () => {
918
+ const own = {
919
+ id: OWN,
920
+ source: "own",
921
+ versionId: TOURNAMENT_VERSION,
922
+ title: pt("Torneio da semana"),
923
+ terms: pt("Maior multiplicador vence"),
924
+ status: "live",
925
+ startsAt: at(-864e5),
926
+ endsAt: at(6 * 864e5),
927
+ updatedAt: at(0),
928
+ scoringRule: "round_multiplier",
929
+ tieBreak: "earliest",
930
+ currency: "BRL",
931
+ timeZone: "America/Sao_Paulo",
932
+ gameIds: [],
933
+ prizes: [
934
+ { fromRank: 1, toRank: 1, reward: reward("prize-1", "real_balance", 1, { money: BRL(5e4) }), terms: {} },
935
+ { fromRank: 2, toRank: 10, reward: reward("prize-2", "free_spins", 50), terms: {} }
936
+ ],
937
+ joinMode: "registration",
938
+ locale: "pt-BR",
939
+ rankingAvailable: true,
940
+ canRegister: state.joined && state.registration === null,
941
+ requiresTicket: false,
942
+ stale: false,
943
+ registrationStartsAt: at(-864e5),
944
+ registrationEndsAt: at(5 * 864e5),
945
+ coverUrl: ""
946
+ };
947
+ if (state.registration) own.registration = state.registration;
948
+ const external = {
949
+ id: EXTERNAL,
950
+ source: "external",
951
+ versionId: "",
952
+ title: pt("Torneio do provedor"),
953
+ terms: {},
954
+ status: "live",
955
+ startsAt: at(-36e5),
956
+ endsAt: at(864e5),
957
+ updatedAt: at(0),
958
+ scoringRule: "",
959
+ tieBreak: "",
960
+ currency: "BRL",
961
+ timeZone: "",
962
+ gameIds: [],
963
+ prizes: [{ fromRank: 1, toRank: 3, announcedAmount: BRL(1e5) }],
964
+ joinMode: "",
965
+ locale: "",
966
+ rankingAvailable: false,
967
+ canRegister: false,
968
+ requiresTicket: false,
969
+ stale: false,
970
+ coverUrl: ""
971
+ };
972
+ return [own, external];
973
+ };
974
+ function keyOf(req) {
975
+ const header = req.headers.get("idempotency-key") ?? "";
976
+ const body = req.body?.idempotencyKey;
977
+ const key = typeof body === "string" && body !== "" ? body : header;
978
+ if (key === "" || key.length > 128 || key !== key.trim() || header !== "" && header !== key) return void 0;
979
+ return key;
980
+ }
981
+ function once(req, scope, run) {
982
+ const key = keyOf(req);
983
+ if (key === void 0) return fail(400, "INVALID_ARGUMENT", "invalid club request");
984
+ if (key.startsWith("inflight-") && !seenInFlight.has(`${scope}:${key}`)) {
985
+ seenInFlight.add(`${scope}:${key}`);
986
+ return fail(
987
+ 409,
988
+ "ALREADY_EXISTS",
989
+ "club action conflicts with the current version, availability, or account state"
990
+ );
991
+ }
992
+ const body = req.body ?? {};
993
+ const { idempotencyKey, ...payload } = body;
994
+ const fingerprint = JSON.stringify([req.url.pathname, payload]);
995
+ const id = `${scope}:${key}`;
996
+ const replay = replays.get(id);
997
+ if (replay) {
998
+ if (replay.fingerprint !== fingerprint)
999
+ return fail(
1000
+ 409,
1001
+ "ALREADY_EXISTS",
1002
+ "club action conflicts with the current version, availability, or account state"
1003
+ );
1004
+ return replay.status < 400 ? raw(replay.body, replay.status) : fail(replay.status, "ALREADY_EXISTS", "club conflict");
1005
+ }
1006
+ const result = run(payload, key);
1007
+ if (result instanceof Response) return result;
1008
+ replays.set(id, { fingerprint, ...result });
1009
+ if (key.startsWith("lost-") && !lostOnce.has(id)) {
1010
+ lostOnce.add(id);
1011
+ return fail(503, "UNAVAILABLE", "club service temporarily unavailable");
1012
+ }
1013
+ return result.status < 400 ? raw(result.body, result.status) : fail(result.status, "ALREADY_EXISTS", "club conflict");
1014
+ }
1015
+ const conflict = { status: 409, body: null };
1016
+ const receipt = (fields) => {
1017
+ sequence += 1;
1018
+ const row = {
1019
+ id: `rcpt-${sequence}`,
1020
+ status: "delivered",
1021
+ costCoins: "0",
1022
+ acceptedAt: at(sequence * 1e3),
1023
+ deliveredAt: at(sequence * 1e3),
1024
+ ticketConsumed: false,
1025
+ ...fields
1026
+ };
1027
+ receipts.unshift(row);
1028
+ return row;
1029
+ };
1030
+ const credit = (kind, units, sourceId) => {
1031
+ if (kind !== "coins") return;
1032
+ state.coins += units;
1033
+ movements.unshift({
1034
+ id: `mv-${movements.length + 1}`,
1035
+ kind: "coins",
1036
+ units: String(units),
1037
+ sourceId,
1038
+ occurredAt: at(0)
1039
+ });
1040
+ };
1041
+ return {
1042
+ // Disabled without history: the gateway writes the program alone (protojson omits the unset `rewards`).
1043
+ "GET /api/v1/casino/club": () => raw(mode === "disabled" ? { program: program() } : { program: program(), rewards: rewards() }),
1044
+ "PUT /api/v1/casino/club/membership": (req) => {
1045
+ const body = req.body ?? {};
1046
+ if (typeof body.joined !== "boolean")
1047
+ return fail(400, "INVALID_ARGUMENT", "club membership requires an explicit joined value");
1048
+ if (body.joined && !body.termsLocale)
1049
+ return fail(400, "INVALID_ARGUMENT", "club membership requires the displayed terms locale");
1050
+ return once(req, "membership", (payload) => {
1051
+ if (!active || payload.versionId !== VERSION) return conflict;
1052
+ state.joined = payload.joined === true;
1053
+ return { status: 200, body: program() };
1054
+ });
1055
+ },
1056
+ "GET /api/v1/casino/club/history": (req) => {
1057
+ const q = req.url.searchParams;
1058
+ const limitText = q.get("limit");
1059
+ const limit = limitText === null ? 20 : Number(limitText);
1060
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
1061
+ return fail(400, "INVALID_ARGUMENT", "invalid club request");
1062
+ const cursor = q.get("cursor") ?? "";
1063
+ const start = cursor === "" ? 0 : Number(cursor.replace(/^c/, ""));
1064
+ if (!Number.isInteger(start) || start < 0) return fail(400, "INVALID_ARGUMENT", "invalid club request");
1065
+ const page = receipts.slice(start, start + limit);
1066
+ const end = start + page.length;
1067
+ return raw({
1068
+ receipts: page,
1069
+ movements: start === 0 ? movements : [],
1070
+ nextCursor: end < receipts.length ? `c${end}` : ""
1071
+ });
1072
+ },
1073
+ "POST /api/v1/casino/club/activities/:activityId/plays": (req) => once(req, "play", (payload, key) => {
1074
+ const activityId = req.params?.activityId;
1075
+ const version = mode === "paused" && activityId === "right-1" ? "club-v0" : VERSION;
1076
+ if (mode === "disabled" || mode === "paused" && activityId !== "right-1") return conflict;
1077
+ if (!state.joined || payload.versionId !== version) return conflict;
1078
+ if (activityId === "wheel-daily") {
1079
+ if (state.wheelPlayed) return conflict;
1080
+ const slice = SLICES[hash(key) % SLICES.length];
1081
+ const won = slice.reward;
1082
+ state.wheelPlayed = true;
1083
+ credit(String(won.kind), Number(won.quantity), "wheel-daily");
1084
+ const row = receipt({ sourceKind: "activity", sourceId: "wheel-daily", sliceId: slice.id, reward: won });
1085
+ return { status: 200, body: { receipt: row, sliceId: slice.id, rewards: rewards() } };
1086
+ }
1087
+ if (activityId === "right-1") {
1088
+ const option = CHEST.find((o) => o.id === payload.optionId);
1089
+ if (state.chestReceipt || !option) return conflict;
1090
+ credit(String(option.kind), Number(option.quantity), "right-1");
1091
+ state.chestReceipt = receipt({ sourceKind: "chest", sourceId: "right-1", reward: option });
1092
+ return { status: 200, body: { receipt: state.chestReceipt, sliceId: "", rewards: rewards() } };
1093
+ }
1094
+ return fail(404, "NOT_FOUND", "club resource not found");
1095
+ }),
1096
+ "POST /api/v1/casino/club/rewards/:rewardId/redemptions": (req) => once(req, "redeem", (payload) => {
1097
+ const item = ITEMS.find((i) => i.id === req.params?.rewardId);
1098
+ if (!item) return fail(404, "NOT_FOUND", "club resource not found");
1099
+ const cost = Number(item.costCoins);
1100
+ if (!active || !state.joined || payload.versionId !== VERSION || state.coins < cost) return conflict;
1101
+ state.coins -= cost;
1102
+ movements.unshift({
1103
+ id: `mv-${movements.length + 1}`,
1104
+ kind: "coins",
1105
+ units: String(-cost),
1106
+ sourceId: item.id,
1107
+ occurredAt: at(0)
1108
+ });
1109
+ const row = receipt({ sourceKind: "store", sourceId: item.id, reward: item.reward, costCoins: item.costCoins });
1110
+ return { status: 200, body: row };
1111
+ }),
1112
+ "GET /api/v1/casino/club/tournaments": (req) => {
1113
+ if (!active) return fail(404, "NOT_FOUND", "club resource not found");
1114
+ const related = req.url.searchParams.get("relatedTo");
1115
+ if (related !== null) {
1116
+ if (related !== EXTERNAL) return fail(404, "NOT_FOUND", "club resource not found");
1117
+ return raw({
1118
+ relatedTo: EXTERNAL,
1119
+ items: [
1120
+ {
1121
+ id: RELATED,
1122
+ title: pt("Torneio do provedor"),
1123
+ status: "upcoming",
1124
+ startsAt: at(864e5),
1125
+ endsAt: at(2 * 864e5)
1126
+ },
1127
+ // A nil title map and zero `time.Time` values, as `encoding/json` writes them.
1128
+ { id: "ext_tlt_weekly_3", title: null, status: "upcoming", startsAt: GO_ZERO, endsAt: GO_ZERO }
1129
+ ],
1130
+ nextCursor: ""
1131
+ });
1132
+ }
1133
+ return raw({ items: tournaments(), externalAvailable: true, externalStale: false, nextCursor: "" });
1134
+ },
1135
+ "GET /api/v1/casino/club/tournaments/:editionId": (req) => {
1136
+ if (!active) return fail(404, "NOT_FOUND", "club resource not found");
1137
+ const tournament = tournaments().find((t) => t.id === req.params?.editionId);
1138
+ return tournament ? raw(tournament) : fail(404, "NOT_FOUND", "club resource not found");
1139
+ },
1140
+ "GET /api/v1/casino/club/tournaments/:editionId/ranking": (req) => {
1141
+ if (!active) return fail(404, "NOT_FOUND", "club resource not found");
1142
+ const editionId = req.params?.editionId;
1143
+ if (editionId === EXTERNAL)
1144
+ return fail(404, "CLUB_RANKING_UNAVAILABLE", "ranking is unavailable for this edition");
1145
+ if (editionId !== OWN) return fail(404, "NOT_FOUND", "club resource not found");
1146
+ const entries = [
1147
+ { position: 1, displayName: "Ma\u2022\u2022\u2022 R.", score: "152.5" },
1148
+ { position: 2, displayName: "Jo\u2022\u2022\u2022 S.", score: "98" },
1149
+ { position: 3, displayName: "An\u2022\u2022\u2022 P.", score: "71.25" }
1150
+ ];
1151
+ const body = { entries, updatedAt: at(0), final: false };
1152
+ if (state.registration) body.personal = { position: 4, displayName: "Voc\xEA", score: "12" };
1153
+ return raw(body);
1154
+ },
1155
+ "POST /api/v1/casino/club/tournaments/:editionId/registrations": (req) => once(req, "register", (payload) => {
1156
+ if (!active) return conflict;
1157
+ if (req.params?.editionId !== OWN) return fail(404, "NOT_FOUND", "club resource not found");
1158
+ if (!state.joined || payload.versionId !== TOURNAMENT_VERSION || state.registration) return conflict;
1159
+ state.registration = { id: "reg-1", editionId: OWN, versionId: TOURNAMENT_VERSION, joinedAt: at(0) };
1160
+ return { status: 200, body: state.registration };
1161
+ })
1162
+ };
1163
+ }
728
1164
  var POINT_VALUE_CENTS = 5;
729
1165
  function createLoyaltyRoutes() {
730
1166
  const state = { total: 5200, current: 1500, redeemed: 3700 };
@@ -835,8 +1271,8 @@ function json2(body) {
835
1271
  function listMissions(req) {
836
1272
  const q = req.url.searchParams;
837
1273
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
838
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
839
- const limit = raw >= 1 && raw <= 100 ? raw : 20;
1274
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
1275
+ const limit = raw2 >= 1 && raw2 <= 100 ? raw2 : 20;
840
1276
  return json2({
841
1277
  success: true,
842
1278
  data: MISSIONS.slice((page - 1) * limit, page * limit),
@@ -891,8 +1327,8 @@ var CODE = "MOCK123";
891
1327
  function listHistory(req) {
892
1328
  const q = req.url.searchParams;
893
1329
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
894
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
895
- const limit = raw >= 1 ? Math.min(raw, 100) : 20;
1330
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
1331
+ const limit = raw2 >= 1 ? Math.min(raw2, 100) : 20;
896
1332
  return ok({
897
1333
  referral_code: CODE,
898
1334
  referrals: REFERRALS.slice((page - 1) * limit, page * limit),
@@ -925,9 +1361,10 @@ function createSportsbookRoutes() {
925
1361
  }
926
1362
 
927
1363
  // src/testing/index.ts
928
- function createIgamingRoutes() {
1364
+ function createIgamingRoutes(options = {}) {
929
1365
  return {
930
1366
  ...createCasinoRoutes(),
1367
+ ...createClubRoutes(options.club),
931
1368
  ...createBonusRoutes(),
932
1369
  ...createSportsbookRoutes(),
933
1370
  ...createMissionsRoutes(),
@@ -937,7 +1374,8 @@ function createIgamingRoutes() {
937
1374
  };
938
1375
  }
939
1376
  function withIgamingRoutes(options = {}) {
940
- return { ...options, routes: { ...createIgamingRoutes(), ...options.routes } };
1377
+ const { club, ...core } = options;
1378
+ return { ...core, routes: { ...createIgamingRoutes({ club }), ...core.routes } };
941
1379
  }
942
1380
 
943
1381
  export { createIgamingRoutes, withIgamingRoutes };