@getenginex/sdk-igaming 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +179 -0
- package/LICENSE +202 -0
- package/README.md +110 -2
- package/dist/first-frame/index.cjs +136 -0
- package/dist/first-frame/index.cjs.map +1 -0
- package/dist/first-frame/index.d.cts +135 -0
- package/dist/first-frame/index.d.ts +135 -0
- package/dist/first-frame/index.js +134 -0
- package/dist/first-frame/index.js.map +1 -0
- package/dist/index.cjs +1046 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1588 -0
- package/dist/index.d.ts +1588 -0
- package/dist/index.js +1025 -0
- package/dist/index.js.map +1 -0
- package/dist/query/index.cjs +84 -0
- package/dist/query/index.cjs.map +1 -0
- package/dist/query/index.d.cts +103 -0
- package/dist/query/index.d.ts +103 -0
- package/dist/query/index.js +81 -0
- package/dist/query/index.js.map +1 -0
- package/dist/testing/index.cjs +743 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +75 -0
- package/dist/testing/index.d.ts +75 -0
- package/dist/testing/index.js +740 -0
- package/dist/testing/index.js.map +1 -0
- package/first-frame/package.json +5 -0
- package/package.json +159 -3
- package/query/package.json +5 -0
- package/testing/package.json +5 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# @getenginex/sdk-igaming
|
|
2
|
+
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 8020869: Align the SDK with the gateway contract in production.
|
|
8
|
+
|
|
9
|
+
**Type changes (may need code changes when upgrading):**
|
|
10
|
+
|
|
11
|
+
- `@getenginex/sdk`: `PixDeposit.expiresAt` is now optional (`string | undefined`); code such as `new Date(pix.expiresAt)` must handle a missing expiry. New optional fields: `PixDeposit.redirectUrl`, `Deposit.expiresAt` and `Deposit.redirectUrl`.
|
|
12
|
+
- `@getenginex/sdk-igaming`: `GameLaunch` gains the required `launchTarget` (new exported type `LaunchTarget`: `'iframe' | 'redirect' | 'new_tab'` or a future value) and the optional `providerCode` and `expiresAt`. Hand-written `GameLaunch` objects (e.g. test fixtures) need a `launchTarget`.
|
|
13
|
+
|
|
14
|
+
**Behavior changes:**
|
|
15
|
+
|
|
16
|
+
- `deposits.createPix` no longer throws `VALIDATION_ERROR` after the charge was created when the payment provider reports no expiry.
|
|
17
|
+
- The session is renewed and the request retried only on a 401 that refuses the access token: a 401 without a code (what the gateway's auth middleware answers for a missing, expired or invalid token), `TOKEN_EXPIRED` or `TOKEN_STALE`. A 401 with any other code, such as `INVALID_CREDENTIALS` for a wrong current password in `changePassword` or `disable2fa`, or an explicit `UNAUTHENTICATED`/`TOKEN_INVALID`, is no longer retried and no longer fires `onAccessTokenRejected`. An error body with a top-level `code` (e.g. `TOKEN_STALE`) now keeps that code.
|
|
18
|
+
- `auth.logout` sends the stored refresh token so the gateway revokes it. With an expired access token the gateway refuses the call before revoking, so logout renews once (without storing the new tokens or calling `onSessionExpired`) and revokes the renewed refresh token. The local session is always cleared; if the renewal or the request fails, the refresh token may stay valid on the server until it expires.
|
|
19
|
+
- `casino.launchGame` returns `launchTarget`, so apps can open each game the way its provider requires. A response without it is treated as `iframe`, as before. The testing mock returns `launch_target`, `provider_code` and `expires_at`.
|
|
20
|
+
- `withdrawals.request` docs and the testing mock match the gateway: while an OTP request is pending (until its `expiresAt`, also after its code was confirmed), the same request is replayed and any other request is refused with `FAILED_PRECONDITION` (422) `another withdrawal request is pending`, instead of replacing it. After a confirmed withdrawal, the next one can only be requested once the previous request expires.
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- 7be12eb: Code comments, TSDoc and runtime error messages are now in English. Error `code` values are unchanged; if your UI shows `error.message` to players, it now shows English text — map `code` to your own copy instead.
|
|
25
|
+
- d330035: READMEs and package metadata in English; docs site now in English, Portuguese and Spanish.
|
|
26
|
+
|
|
27
|
+
## 0.5.0
|
|
28
|
+
|
|
29
|
+
### Minor Changes
|
|
30
|
+
|
|
31
|
+
- af441d0: **Breaking (antes do 1.0).** Exige `@getenginex/sdk >=0.6.0 <1.0.0`.
|
|
32
|
+
|
|
33
|
+
- Dinheiro estrito nas respostas: valores monetários (inteiro seguro, em número ou texto), moeda (`/^[A-Z]{3}$/`) e casas decimais (0-8) inválidos rejeitam a resposta inteira com `VALIDATION_ERROR`, também em `validation: 'warn'` (campanhas de bônus, totais do cassino, resgate de fidelidade e indicações). **Como migrar:** nada no app; um gateway fora do contrato passa a aparecer como erro.
|
|
34
|
+
- Indicações (`referrals`): um valor monetário inválido agora rejeita a lista inteira (antes, o item era descartado em silêncio). **Como migrar:** trate o erro da listagem; não há mais itens sumindo.
|
|
35
|
+
- Decisão registrada (desvio do rascunho, que exigia moeda sempre preenchida): a moeda vazia (`''`) é aceita só nos valores de campanha do bônus e no `currency` do resgate de fidelidade, porque o gateway omite a moeda no protojson quando o valor é 0; aceitar o vazio evita derrubar a listagem de campanhas. Em qualquer outro campo, moeda vazia rejeita a resposta. Pontos de fidelidade e progresso de missões não são dinheiro.
|
|
36
|
+
- Idempotência: as mutations (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`) reaproveitam a `Idempotency-Key` só depois de falha ambígua, para a mesma entrada e na mesma mutation; `ABORTED` libera a chave. **Como migrar:** "tentar de novo" com `mutate({ ...mesmos valores })` já reaproveita a chave; para repetir depois de recarregar a página, passe `idempotencyKey`.
|
|
37
|
+
|
|
38
|
+
## 0.4.0
|
|
39
|
+
|
|
40
|
+
### Minor Changes
|
|
41
|
+
|
|
42
|
+
- ddc9d2c: Novo entry `@getenginex/sdk-igaming/query`: `createIgamingQueries(igaming)` e
|
|
43
|
+
`createIgamingMutations(igaming)` devolvem uma fábrica por método de leitura (`{ queryKey, queryFn }`) e
|
|
44
|
+
uma mutation por método de escrita (`{ mutationKey, mutationFn, invalidates }`), com os mesmos nomes e
|
|
45
|
+
entradas dos namespaces (`casino`, `bonus`, `missions`, `loyalty`, `referrals`, `sportsbook`) e as mesmas
|
|
46
|
+
convenções de chave do `@getenginex/sdk/query`, compatíveis com `useQuery`/`useMutation`/`prefetchQuery`
|
|
47
|
+
do TanStack Query v5 sem depender dele. Catálogo do cassino e ofertas públicas de bônus usam chave
|
|
48
|
+
`public`; o resto das leituras usa a chave do usuário (`userId` da sessão, `'anonymous'` e
|
|
49
|
+
`UNAUTHENTICATED` sem request quando não há sessão). `bonus.optIn/claim/redeemPromoCode` e
|
|
50
|
+
`loyalty.redeem` mandam uma `Idempotency-Key` por objeto de entrada (o retry não duplica a operação) e
|
|
51
|
+
aceitam `{ idempotencyKey }` na fábrica; `loyalty.redeem` e `bonus.optIn/claim/redeemPromoCode` invalidam o namespace e o saldo
|
|
52
|
+
do core (`wallet`), `referrals.register` invalida `referrals` e `casino.launchGame`
|
|
53
|
+
`casino.listSessions`. `bonus.resolvePromoCode`, `bonus.redeemPromoCode`, `casino.launchGame` e
|
|
54
|
+
`sportsbook.createSession` trazem `gcTime: 0` (código promocional, URL do jogo e token do sportsbook).
|
|
55
|
+
`createIgaming` passa a registrar o objeto do produto no cliente do core
|
|
56
|
+
(`registerProductClient`, do core 0.5.0), por isso o peer `@getenginex/sdk` sobe de `>=0.2.0 <1.0.0`
|
|
57
|
+
para `>=0.5.0 <1.0.0`.
|
|
58
|
+
|
|
59
|
+
## 0.3.0
|
|
60
|
+
|
|
61
|
+
### Minor Changes
|
|
62
|
+
|
|
63
|
+
- bfd181d: Novo namespace `igaming.missions` (missões): `list({ page?, perPage? })` devolve `Page<Mission>` (envia
|
|
64
|
+
`page` e `limit`; o `Page` sai do `meta` do envelope do gateway) e `listMine()` devolve `UserMission[]`
|
|
65
|
+
(o progresso do jogador, lido de `data.missions`). `Mission` é `{ id, name, description, missionType,
|
|
66
|
+
objectiveType, targetValue, targetGameCategory, targetGames, rewardType, rewardValue, validFrom,
|
|
67
|
+
validTo }`; `UserMission` é `{ id, missionId, missionName, currentProgress, targetValue,
|
|
68
|
+
progressPercentage, status, rewardType, rewardValue, periodEnd, completedAt }`. `targetGames` nulo vira
|
|
69
|
+
`[]`; categoria vazia, data epoch (`1970-01-01T00:00:00Z`) e `period_end`/`completed_at` ausentes viram
|
|
70
|
+
`null`; `targetValue`/`rewardValue` são inteiros e `progressPercentage` é número. `missionType`
|
|
71
|
+
(`daily`, `weekly`, `event`, `permanent`), `objectiveType` (`wager`, `bet_count`, `win_amount`,
|
|
72
|
+
`play_game`, `deposit`), `rewardType` (`bonus`, `free_spins`, `points`, `free_bet`) e `status`
|
|
73
|
+
(`in_progress`, `completed`, `expired`, `claimed`) são uniões abertas em minúsculas: valor desconhecido
|
|
74
|
+
chega cru e vai para `onValidationIssue` em `validation: 'warn'`; em `'strict'`, `VALIDATION_ERROR`.
|
|
75
|
+
`page` que não é inteiro ≥ 1 e `perPage` fora de 1–100 rejeitam com `CONFIGURATION_ERROR` sem request.
|
|
76
|
+
Os dois métodos exigem login. Não há `claim()` (o gateway não tem rota de resgate). `withIgamingRoutes`
|
|
77
|
+
(`@getenginex/sdk-igaming/testing`) responde as duas rotas. Nova página "Missões" nos docs. O peer do core
|
|
78
|
+
continua `>=0.2.0 <1.0.0`.
|
|
79
|
+
|
|
80
|
+
Novo namespace `igaming.loyalty` (fidelidade): `get()` devolve `LoyaltyStatus` (`totalPointsEarned`,
|
|
81
|
+
`currentPoints`, `pointsRedeemed`, `currentTier`, `tierPoints`, `lifetimeWagered`, `lifetimeDeposited`,
|
|
82
|
+
`tierBenefits`, `tierExpiresAt`) e `redeem({ points, redemptionType })` devolve `{ redeemedPoints, value,
|
|
83
|
+
currency, bonusId }`. `tierBenefits` é o `tier_benefits_json` já convertido em objeto: texto vazio ou
|
|
84
|
+
ausente vira `null` sem aviso; JSON inválido ou que não é um objeto vira `null` e vai para
|
|
85
|
+
`onValidationIssue` (sem o texto no issue; em `'strict'`, `VALIDATION_ERROR`). `tierExpiresAt`, `value`,
|
|
86
|
+
`currency`, `bonusId` e `currentTier` vazios ou ausentes viram `null`. `redemptionType` é uma união aberta (`bonus`, `cash`,
|
|
87
|
+
`free_bet`); `points` não inteiro ou ≤ 0 e `redemptionType` vazio rejeitam com `CONFIGURATION_ERROR` sem
|
|
88
|
+
request. `redeem` manda `Idempotency-Key` (gerada, ou a de `options.idempotencyKey`, mantida no retry após
|
|
89
|
+
401), mas o gateway ainda não aplica o middleware de idempotência nesta rota: trave o botão, um duplo
|
|
90
|
+
clique pode resgatar duas vezes. Um 200 sem confirmação (`success` diferente de `true`) rejeita com
|
|
91
|
+
`UNKNOWN` (`status` 200) e a mensagem do gateway quando vem, senão a do SDK: releia `get()` antes de
|
|
92
|
+
tentar de novo. `withIgamingRoutes` responde `GET /loyalty` e `POST /loyalty/redeem`.
|
|
93
|
+
Nova página "Fidelidade" nos docs. O peer do core continua `>=0.2.0 <1.0.0`.
|
|
94
|
+
|
|
95
|
+
Novo namespace `igaming.referrals` (indicações): `get()` devolve `ReferralInfo` (`code`, `link`,
|
|
96
|
+
`totalReferrals`, `completedReferrals`, `pendingReferrals`, `totalEarned`, `bonusPerReferral`,
|
|
97
|
+
`minDeposit`); `listHistory({ page?, perPage? })` devolve `Page<Referral>` mais `completedCount` e
|
|
98
|
+
`totalEarned` (o gateway manda a paginação dentro do `data`: o SDK monta o `Page`, calcula `totalPages` e
|
|
99
|
+
não deixa `totalItems` ficar abaixo dos itens já vistos); `register({ code })` devolve `{ id, code, status,
|
|
100
|
+
refereeBonus, createdAt }` (HTTP 201). O gateway escreve o dinheiro como float na unidade maior; o SDK
|
|
101
|
+
converte para unidades menores com `Math.round(valor * 100)`, metades para longe do zero (`19.99` → `1999`,
|
|
102
|
+
`0.1 + 0.2` → `30`, `1e-7` → `0`, negativos mantêm o sinal), e valor não finito rejeita com
|
|
103
|
+
`VALIDATION_ERROR` em `strict`. `Referral` traz `refereeName` e `refereeEmailMasked`
|
|
104
|
+
(`ana@exemplo.com` → `a**@exemplo.com`; vazio ou inválido vira `null`); o e-mail cru e o `referee_id`
|
|
105
|
+
nunca são expostos (nem no resultado, nem nos issues, nem nos erros), também em `validation: 'warn'`
|
|
106
|
+
quando um item falha inteiro e o core devolve a lista crua: o SDK refaz cada indicação (máscara, status,
|
|
107
|
+
dinheiro em unidades menores) e descarta o que não é objeto ou cujo dinheiro não vira unidades menores.
|
|
108
|
+
Um `total_items` fora do formato em `'warn'` vale 0 (nunca `NaN`). `status` (`pending`, `qualified`,
|
|
109
|
+
`completed`, `expired`) é uma união aberta; `completedAt`, `expiresAt` e `createdAt` ausentes ou epoch
|
|
110
|
+
viram `null`. `page` e `perPage` inválidos e `code` vazio rejeitam com `CONFIGURATION_ERROR` sem request.
|
|
111
|
+
Quem está se cadastrando usa `auth.register({ referralCode })` do core. `withIgamingRoutes` responde as
|
|
112
|
+
três rotas. Nova página "Indicações" nos docs. O peer do core continua `>=0.2.0 <1.0.0`.
|
|
113
|
+
|
|
114
|
+
## 0.2.0
|
|
115
|
+
|
|
116
|
+
### Minor Changes
|
|
117
|
+
|
|
118
|
+
- f91eacb: Novo namespace `igaming.sportsbook` com `createSession(params?, options?)` (`GET /first/session`, exige
|
|
119
|
+
login): devolve `{ launchUrl, expiresInSeconds, expiresAt }` para abrir o sportsbook FIRST num iframe.
|
|
120
|
+
`expiresAt` (ms) é calculado no cliente (relógio na resposta + `expiresInSeconds * 1000`); o
|
|
121
|
+
`operator_token` não entra no tipo público. `launchUrl` carrega o token de operador: a resposta é
|
|
122
|
+
sempre validada em modo estrito (`launch_url` http(s) absoluta e `expires_in_seconds` > 0, senão
|
|
123
|
+
`VALIDATION_ERROR`) e nenhum hook nem `onValidationIssue` a recebe. `createIgamingRoutes` /
|
|
124
|
+
`withIgamingRoutes` ganham a rota mock de `/first/session`. Sem cache no SDK: reutilize a sessão até
|
|
125
|
+
`expiresAt - 30 s` e cheque `enginex.config.getSportsbook()` antes.
|
|
126
|
+
|
|
127
|
+
Novo entry opcional `@getenginex/sdk-igaming/first-frame` com `connectFirstFrame(iframe, handlers,
|
|
128
|
+
options?)`: ponte tipada para os eventos `postMessage` do iframe do FIRST (`onReady`, `onBetPlaced`,
|
|
129
|
+
`onInsufficientFunds`, `onDepositClick`, `onLoginRequired`, `onHeightChange`, `onRedirect`,
|
|
130
|
+
`onScrollToTop` e `onEvent` genérico) e `send(eventType, eventData)` para comandos. Em `onRedirect`,
|
|
131
|
+
`link` só chega se for texto (um `link` de outro tipo é descartado). Só entrega mensagens
|
|
132
|
+
com `event.source === iframe.contentWindow` e `event.origin` igual à origem do `src`; `send` posta
|
|
133
|
+
sempre para essa origem (nunca `'*'`). Não importa o core em runtime nem exige `lib.dom`
|
|
134
|
+
(`FirstFrameTarget`/`FirstFrameWindow` são estruturais); os erros de configuração são
|
|
135
|
+
`CONFIGURATION_ERROR` reconhecidos por `isEnginexError`. Fora do entry principal: quem importa só
|
|
136
|
+
`createIgaming` não o leva no bundle.
|
|
137
|
+
|
|
138
|
+
## 0.1.0
|
|
139
|
+
|
|
140
|
+
### Minor Changes
|
|
141
|
+
|
|
142
|
+
- 7be46cc: Namespace `bonus` em `createIgaming(enginex)`: `listPublicOffers` (vitrine pública, sem mandar a
|
|
143
|
+
sessão), `listOffers`, `getOffer`, `listParticipations` e `getParticipation` (paginação por cursor:
|
|
144
|
+
`CursorPage`/`CursorPageInput` do core), `optIn`, `claim` e `redeemPromoCode` (idempotentes: mandam
|
|
145
|
+
`Idempotency-Key`, a do chamador em `options.idempotencyKey` ou uma gerada, reusada no retry após
|
|
146
|
+
401; respostas validadas sempre em modo estrito) e `resolvePromoCode`. As campanhas chegam do formato
|
|
147
|
+
protojson do gateway em camelCase, com enums sem prefixo e em minúsculas, dinheiro em `number`
|
|
148
|
+
(unidades menores), durações em segundos e o estado da participação em `status` (+ `qualifiedAt`,
|
|
149
|
+
`completedAt`, `expiredAt`). `/testing` ganha as rotas mock de bônus (três campanhas, promo code
|
|
150
|
+
`BEMVINDO`, opt-in/claim/resgate com estado e replay por `Idempotency-Key`).
|
|
151
|
+
- 6397a2f: Namespace `casino` em `createIgaming(enginex)`: `listGames` (filtros por categoria, provedor, busca,
|
|
152
|
+
`ids` e ordenação, paginado), `listCategories`, `listProviders` e `getGame` (públicos, sem mandar a
|
|
153
|
+
sessão), `launchGame` (exige login; devolve `sessionId` e `gameUrl`, com o idioma vindo do `locale` do
|
|
154
|
+
cliente via `Accept-Language`), `listSessions`, `getHistory` (paginados) e `getBiggestWinners`. A URL
|
|
155
|
+
do jogo carrega o token da sessão de jogo: volta só no resultado — nunca nos hooks nem no
|
|
156
|
+
`onValidationIssue` — e a resposta do launch é validada sempre em modo estrito. Valores do histórico e
|
|
157
|
+
do ranking (int64 em texto no fio) chegam como `number` em unidades menores. `/testing` ganha as rotas
|
|
158
|
+
mock do cassino (catálogo fixo, launch com URL fictícia e sessões em memória).
|
|
159
|
+
- eb5d851: Novo pacote `@getenginex/sdk-igaming`: `createIgaming(enginex)` monta os namespaces de iGaming sobre o
|
|
160
|
+
cliente de `@getenginex/sdk` (peer dependency), sem sessão, tenant nem transporte próprios — tudo
|
|
161
|
+
passa pelo contrato `@getenginex/sdk/extension` do core. Um valor que não é um cliente criado por
|
|
162
|
+
`createEnginexClient` é rejeitado com `CONFIGURATION_ERROR`. `@getenginex/sdk-igaming/testing` traz
|
|
163
|
+
`createIgamingRoutes()` e `withIgamingRoutes(options)` para somar as rotas mock de iGaming ao
|
|
164
|
+
`createMockFetch` do core. Cassino e bônus chegam nas próximas versões.
|
|
165
|
+
- eb3921a: O core é declarado como peer `@getenginex/sdk@>=0.2.0 <1.0.0` (a primeira versão com o entry
|
|
166
|
+
`@getenginex/sdk/extension`); em tempo de execução, um cliente de uma cópia do core com contrato de
|
|
167
|
+
transporte incompatível faz `createIgaming` lançar `CONFIGURATION_ERROR`.
|
|
168
|
+
|
|
169
|
+
### Patch Changes
|
|
170
|
+
|
|
171
|
+
- Updated dependencies [ffc0bd1]
|
|
172
|
+
- Updated dependencies [a043c79]
|
|
173
|
+
- Updated dependencies [d4ebcf2]
|
|
174
|
+
- Updated dependencies [cbf1a39]
|
|
175
|
+
- Updated dependencies [826a4d8]
|
|
176
|
+
- Updated dependencies [126ff24]
|
|
177
|
+
- Updated dependencies [eb3921a]
|
|
178
|
+
- Updated dependencies [7144ada]
|
|
179
|
+
- @getenginex/sdk@0.2.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,111 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @getenginex/sdk-igaming
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Casino, bonuses, missions, loyalty, referrals and the FIRST sportsbook for EngineX, built on the `@getenginex/sdk` client.
|
|
4
|
+
|
|
5
|
+
[Docs](https://game-engine-io.github.io/enginex-frontend-sdk/igaming/) · [Português](https://game-engine-io.github.io/enginex-frontend-sdk/pt/igaming/) · [Español](https://game-engine-io.github.io/enginex-frontend-sdk/es/igaming/)
|
|
6
|
+
|
|
7
|
+
Namespaces: `casino` (catalog, launch game, sessions, history, winners ranking), `bonus` (campaigns, opt-in, claim, promo
|
|
8
|
+
codes), `missions`, `loyalty` (points, tier, redeem), `referrals` and `sportsbook` (FIRST session for the iframe).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
Install it next to the core. The core is a peer dependency, so the app has a single copy of it (one session, tenant, hooks and validation for everything):
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm i @getenginex/sdk @getenginex/sdk-igaming
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Peer: `@getenginex/sdk >=0.6.0 <1.0.0`. A client created by a core copy with an incompatible transport contract makes
|
|
19
|
+
`createIgaming` throw `CONFIGURATION_ERROR`. `zod` 4 is shared with the core: keep a single `zod` 4 in the project.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { createEnginexClient } from '@getenginex/sdk'
|
|
25
|
+
import { createIgaming } from '@getenginex/sdk-igaming'
|
|
26
|
+
|
|
27
|
+
export const enginex = createEnginexClient({ locale: 'pt-BR' })
|
|
28
|
+
export const igaming = createIgaming(enginex)
|
|
29
|
+
|
|
30
|
+
const games = await igaming.casino.listGames({ category: 'slots', perPage: 24 })
|
|
31
|
+
const { gameUrl } = await igaming.casino.launchGame({ gameId: games.items[0].id }) // requires login
|
|
32
|
+
|
|
33
|
+
const offers = await igaming.bonus.listOffers() // requires login
|
|
34
|
+
await igaming.bonus.redeemPromoCode({ code: 'WELCOME' }, { idempotencyKey: crypto.randomUUID() })
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`gameUrl` carries the game session token: the SDK returns it only as a result (never in hooks), so do not log it.
|
|
38
|
+
|
|
39
|
+
`createIgaming` creates no session, tenant or transport of its own and makes no request: every method goes through the app's
|
|
40
|
+
client. Create one per client (one per app in the browser; one per request on the server). A value that is not a client
|
|
41
|
+
created by `createEnginexClient` (for example a copy `{ ...enginex }`) is rejected with `CONFIGURATION_ERROR`.
|
|
42
|
+
|
|
43
|
+
## Entry points
|
|
44
|
+
|
|
45
|
+
| Subpath | Purpose |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `@getenginex/sdk-igaming` | `createIgaming` and the casino, bonus, missions, loyalty, referrals and sportsbook namespaces |
|
|
48
|
+
| `@getenginex/sdk-igaming/testing` | Mock routes for iGaming (`withIgamingRoutes`) on top of the core's `createMockFetch` |
|
|
49
|
+
| `@getenginex/sdk-igaming/first-frame` | Origin-checked `postMessage` events and commands for the FIRST sportsbook iframe |
|
|
50
|
+
| `@getenginex/sdk-igaming/query` | Query and mutation factories for TanStack Query v5 |
|
|
51
|
+
|
|
52
|
+
### Queries and mutations
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { createIgamingMutations, createIgamingQueries } from '@getenginex/sdk-igaming/query'
|
|
56
|
+
|
|
57
|
+
const q = createIgamingQueries(igaming)
|
|
58
|
+
const m = createIgamingMutations(igaming)
|
|
59
|
+
|
|
60
|
+
q.casino.listGames({ page: 1 }) // { queryKey: ['enginex', 'public', 'casino', 'listGames', { page: 1 }], queryFn }
|
|
61
|
+
m.loyalty.redeem() // { mutationKey, mutationFn, invalidates }: loyalty and the core wallet
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The casino catalog and public bonus offers use the `public` key; other reads use the user key. `bonus.optIn/claim/redeemPromoCode`
|
|
65
|
+
and `loyalty.redeem` send an `Idempotency-Key` that is reused only after an ambiguous failure, with the same input and in the
|
|
66
|
+
same mutation ([Idempotency](https://game-engine-io.github.io/enginex-frontend-sdk/concepts/idempotency)). The entry requires `@getenginex/sdk >=0.6.0` and is not
|
|
67
|
+
in the bundle of anyone who imports only the main entry.
|
|
68
|
+
|
|
69
|
+
### FIRST iframe events
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'
|
|
73
|
+
|
|
74
|
+
const frame = connectFirstFrame(iframe, {
|
|
75
|
+
onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),
|
|
76
|
+
onLoginRequired: () => openLoginModal(),
|
|
77
|
+
})
|
|
78
|
+
frame.dispose() // on unmount
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Details in [Sportsbook (FIRST)](https://game-engine-io.github.io/enginex-frontend-sdk/igaming/sportsbook).
|
|
82
|
+
|
|
83
|
+
## Testing
|
|
84
|
+
|
|
85
|
+
`withIgamingRoutes` adds the iGaming mock routes to the core's `createMockFetch`:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { createEnginexClient } from '@getenginex/sdk'
|
|
89
|
+
import { createMockFetch } from '@getenginex/sdk/testing'
|
|
90
|
+
import { createIgaming } from '@getenginex/sdk-igaming'
|
|
91
|
+
import { withIgamingRoutes } from '@getenginex/sdk-igaming/testing'
|
|
92
|
+
|
|
93
|
+
const enginex = createEnginexClient({
|
|
94
|
+
baseUrl: 'https://gateway.test', // in Node: absolute baseUrl + tenantHost (optional in the browser)
|
|
95
|
+
tenantHost: 'casino.test',
|
|
96
|
+
fetch: createMockFetch(withIgamingRoutes({ withdrawalOtp: true })),
|
|
97
|
+
})
|
|
98
|
+
const igaming = createIgaming(enginex)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Core routes still apply and `options.routes` win over the iGaming ones. To build the routes object by hand, use
|
|
102
|
+
`createIgamingRoutes()`. See [Testing and mocks](https://game-engine-io.github.io/enginex-frontend-sdk/guide/testing).
|
|
103
|
+
|
|
104
|
+
## Versions
|
|
105
|
+
|
|
106
|
+
While the major version is `0`, minor versions may contain breaking changes and patch versions do not. Pin a tilde range
|
|
107
|
+
(for example `~0.x.0`, with the minor you use) to take only fixes, and read the [upgrade guide](https://game-engine-io.github.io/enginex-frontend-sdk/guide/upgrading) and the [changelog](https://game-engine-io.github.io/enginex-frontend-sdk/changelog) before upgrading.
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
[Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/first-frame/index.ts
|
|
4
|
+
var BRAND = /* @__PURE__ */ Symbol.for("getenginex.error");
|
|
5
|
+
var FirstFrameConfigurationError = class extends Error {
|
|
6
|
+
name = "EnginexError";
|
|
7
|
+
code = "CONFIGURATION_ERROR";
|
|
8
|
+
status = 0;
|
|
9
|
+
details = void 0;
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
Object.defineProperty(this, BRAND, { value: true });
|
|
13
|
+
}
|
|
14
|
+
toString() {
|
|
15
|
+
return `EnginexError [${this.code}]: ${this.message}`;
|
|
16
|
+
}
|
|
17
|
+
toJSON() {
|
|
18
|
+
return { name: this.name, code: this.code, message: this.message, status: this.status };
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var NO_ORIGIN = "The FIRST iframe src has no valid http(s) origin: set iframe.src to the launchUrl before using the frame.";
|
|
22
|
+
function originOf(src) {
|
|
23
|
+
try {
|
|
24
|
+
const url = new URL(src);
|
|
25
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function isRecord(value) {
|
|
31
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
function parse(data) {
|
|
34
|
+
let value = data;
|
|
35
|
+
if (typeof value === "string") {
|
|
36
|
+
try {
|
|
37
|
+
value = JSON.parse(value);
|
|
38
|
+
} catch {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return isRecord(value) ? value : void 0;
|
|
43
|
+
}
|
|
44
|
+
function call(fn) {
|
|
45
|
+
if (!fn) return;
|
|
46
|
+
try {
|
|
47
|
+
const result = fn();
|
|
48
|
+
Promise.resolve(result).catch(() => {
|
|
49
|
+
});
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function positiveNumber(value) {
|
|
54
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
55
|
+
}
|
|
56
|
+
function dispatch(message, handlers) {
|
|
57
|
+
const rawType = message.eventType || message.type;
|
|
58
|
+
if (typeof rawType !== "string" || rawType === "") return;
|
|
59
|
+
const eventType = rawType;
|
|
60
|
+
const eventData = message.eventData;
|
|
61
|
+
const on = (handler, ...args) => call(handler && (() => handler.apply(handlers, args)));
|
|
62
|
+
switch (eventType) {
|
|
63
|
+
case "APP_READY":
|
|
64
|
+
on(handlers.onReady);
|
|
65
|
+
break;
|
|
66
|
+
case "BET_WAS_PLACED":
|
|
67
|
+
on(handlers.onBetPlaced, eventData);
|
|
68
|
+
break;
|
|
69
|
+
case "INSUFFICIENT_FUNDS":
|
|
70
|
+
on(handlers.onInsufficientFunds, eventData);
|
|
71
|
+
break;
|
|
72
|
+
case "depositClick":
|
|
73
|
+
on(handlers.onDepositClick, eventData);
|
|
74
|
+
break;
|
|
75
|
+
case "PLACE_BET_CLICKED_NOT_LOGGED_IN":
|
|
76
|
+
case "OPEN_LOGIN_POPUP":
|
|
77
|
+
on(handlers.onLoginRequired, eventData);
|
|
78
|
+
break;
|
|
79
|
+
case "on-page-height-change":
|
|
80
|
+
case "ON_PAGE_HEIGHT_CHANGE": {
|
|
81
|
+
const height = positiveNumber(isRecord(eventData) ? eventData.height : void 0) ?? positiveNumber(message.height);
|
|
82
|
+
if (height !== void 0) on(handlers.onHeightChange, height);
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
case "BUTTON_REDIRECT": {
|
|
86
|
+
const data = { ...isRecord(eventData) ? eventData : {} };
|
|
87
|
+
if (typeof message.link === "string") data.link = message.link;
|
|
88
|
+
else if (typeof data.link !== "string") delete data.link;
|
|
89
|
+
on(handlers.onRedirect, data);
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
case "SCROLL_TO_TOP":
|
|
93
|
+
on(handlers.onScrollToTop);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
on(handlers.onEvent, eventType, eventData);
|
|
97
|
+
}
|
|
98
|
+
function connectFirstFrame(iframe, handlers, options = {}) {
|
|
99
|
+
const win = options.window ?? globalThis;
|
|
100
|
+
if (typeof win.addEventListener !== "function" || typeof win.removeEventListener !== "function") {
|
|
101
|
+
throw new FirstFrameConfigurationError(
|
|
102
|
+
"connectFirstFrame needs a window with addEventListener: outside the browser, pass options.window."
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
let disposed = false;
|
|
106
|
+
const listener = (event) => {
|
|
107
|
+
if (disposed) return;
|
|
108
|
+
const target = iframe.contentWindow;
|
|
109
|
+
const origin = originOf(iframe.src);
|
|
110
|
+
if (target === null || origin === null || event.source !== target || event.origin !== origin) return;
|
|
111
|
+
const message = parse(event.data);
|
|
112
|
+
if (message) dispatch(message, handlers);
|
|
113
|
+
};
|
|
114
|
+
win.addEventListener("message", listener);
|
|
115
|
+
return {
|
|
116
|
+
send(eventType, eventData) {
|
|
117
|
+
if (disposed) throw new FirstFrameConfigurationError("The FIRST frame has already been closed (dispose).");
|
|
118
|
+
const origin = originOf(iframe.src);
|
|
119
|
+
if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN);
|
|
120
|
+
const target = iframe.contentWindow;
|
|
121
|
+
if (target === null) {
|
|
122
|
+
throw new FirstFrameConfigurationError("The FIRST iframe has no contentWindow yet (it is not in the document).");
|
|
123
|
+
}
|
|
124
|
+
target.postMessage(JSON.stringify({ eventType, eventData }), origin);
|
|
125
|
+
},
|
|
126
|
+
dispose() {
|
|
127
|
+
if (disposed) return;
|
|
128
|
+
disposed = true;
|
|
129
|
+
win.removeEventListener?.("message", listener);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
exports.connectFirstFrame = connectFirstFrame;
|
|
135
|
+
//# sourceMappingURL=index.cjs.map
|
|
136
|
+
//# sourceMappingURL=index.cjs.map
|