@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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/first-frame/index.ts"],"names":[],"mappings":";;;AA0HA,IAAM,KAAA,mBAAQ,MAAA,CAAO,GAAA,CAAI,kBAAkB,CAAA;AAM3C,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAC7B,IAAA,GAAO,cAAA;AAAA,EAChB,IAAA,GAAO,qBAAA;AAAA,EACP,MAAA,GAAS,CAAA;AAAA,EACT,OAAA,GAAU,MAAA;AAAA,EACnB,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,eAAe,IAAA,EAAM,KAAA,EAAO,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EACpD;AAAA,EAES,QAAA,GAAmB;AAC1B,IAAA,OAAO,CAAA,cAAA,EAAiB,IAAA,CAAK,IAAI,CAAA,GAAA,EAAM,KAAK,OAAO,CAAA,CAAA;AAAA,EACrD;AAAA,EAEA,MAAA,GAAS;AACP,IAAA,OAAO,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,OAAA,EAAS,IAAA,CAAK,OAAA,EAAS,MAAA,EAAQ,IAAA,CAAK,MAAA,EAAO;AAAA,EACxF;AACF,CAAA;AAEA,IAAM,SAAA,GACJ,2GAAA;AAGF,SAAS,SAAS,GAAA,EAA4B;AAC5C,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,GAAG,CAAA;AACvB,IAAA,OAAO,IAAI,QAAA,KAAa,QAAA,IAAY,IAAI,QAAA,KAAa,OAAA,GAAU,IAAI,MAAA,GAAS,IAAA;AAAA,EAC9E,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;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,MAAM,MAAA,GAAS,QAAA,CAAS,MAAA,CAAO,GAAG,CAAA;AAClC,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,MAAM,IAAI,6BAA6B,SAAS,CAAA;AACrE,MAAA,MAAM,SAAS,MAAA,CAAO,aAAA;AACtB,MAAA,IAAI,WAAW,IAAA,EAAM;AACnB,QAAA,MAAM,IAAI,6BAA6B,wEAAwE,CAAA;AAAA,MACjH;AACA,MAAA,MAAA,CAAO,WAAA,CAAY,KAAK,SAAA,CAAU,EAAE,WAAW,SAAA,EAAW,GAAG,MAAM,CAAA;AAAA,IACrE,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,GAAA,CAAI,mBAAA,GAAsB,WAAW,QAAQ,CAAA;AAAA,IAC/C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed bridge with origin checking for the `postMessage` events of the FIRST sportsbook iframe.\n *\n * This entry does not import the core at runtime nor require `lib.dom` in the consumer's types. It is the only\n * entry of the package that touches the DOM, and only through the objects the app passes (the iframe and the window).\n * @module @getenginex/sdk-igaming/first-frame\n */\n\n/**\n * `postMessage` message as the helper reads it: only the fields it uses (a DOM `MessageEvent` is\n * assignable).\n * @category Sportsbook\n */\nexport interface FirstFrameMessageEvent {\n /** Content sent by the iframe: a JSON string or an object. */\n readonly data: unknown\n /** Sender's origin. */\n readonly origin: string\n /** Sender's window. */\n readonly source: unknown\n}\n\n/**\n * Page window, with the minimum the helper uses: a DOM `Window` is assignable. It is the app's window\n * (the one that receives the iframe's messages), not the iframe's.\n * @category Sportsbook\n */\nexport interface FirstFrameWindow {\n /** Registers the `message` listener. */\n addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n /** Removes the `message` listener. */\n removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n}\n\n/**\n * The FIRST iframe, with the minimum the helper uses: an `HTMLIFrameElement` is assignable. The expected\n * origin and the destination of the messages come from `src` (re-read on every message).\n * @category Sportsbook\n */\nexport interface FirstFrameTarget {\n /** URL loaded in the iframe (the session's `launchUrl`). The trusted origin comes from it. */\n readonly src: string\n /** The iframe's window; `null` while it is not in the document. */\n readonly contentWindow: {\n /** Sends a message to the iframe. */\n postMessage(message: string, targetOrigin: string): void\n } | null\n}\n\n/**\n * Argument of `onRedirect`: the fields of `eventData` (if it is an object) plus the top-level `link` of the\n * message. The SDK only guarantees that `link`, when present, is text (a `link` of another type is\n * dropped); the content is not validated and `link` may be missing.\n * @category Sportsbook\n */\nexport interface FirstFrameRedirect {\n /** Destination requested by FIRST; optional and untrusted (validate before opening). */\n link?: string\n /** Other `eventData` fields, as FIRST sent them. */\n [key: string]: unknown\n}\n\n/**\n * Handlers for the iframe events. All optional; a handler that throws (or rejects) is ignored and\n * does not prevent the others.\n * @category Sportsbook\n */\nexport interface FirstFrameHandlers {\n /** `APP_READY`: the sportsbook has loaded and accepts `send`. */\n onReady?(): void\n /** `BET_WAS_PLACED`: a bet was placed (a good moment to re-read the balance). */\n onBetPlaced?(data: unknown): void\n /** `INSUFFICIENT_FUNDS`: insufficient balance for the bet. */\n onInsufficientFunds?(data: unknown): void\n /** `depositClick`: the player asked to deposit. */\n onDepositClick?(data: unknown): void\n /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` or `OPEN_LOGIN_POPUP`: the player needs to log in. */\n onLoginRequired?(data: unknown): void\n /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: new content height (px, positive). */\n onHeightChange?(height: number): void\n /**\n * `BUTTON_REDIRECT`: FIRST asks to open a link. `data.link` comes at the top of the message (or in\n * `eventData`) and **may be missing or not a valid URL**. **Validate before opening**: accept only\n * http(s), without credentials.\n */\n onRedirect?(data: FirstFrameRedirect): void\n /** `SCROLL_TO_TOP`: FIRST asks to scroll the page to the top. */\n onScrollToTop?(): void\n /** Every accepted event, including those that also have a dedicated handler. */\n onEvent?(eventType: string, eventData: unknown): void\n}\n\n/**\n * Connection to the FIRST iframe.\n * @category Sportsbook\n */\nexport interface FirstFrame {\n /**\n * Sends an event to the iframe: `postMessage(JSON.stringify({ eventType, eventData }), origin)`, with the\n * origin of the `src` (never `'*'`). Wait for `onReady` before sending: FIRST only listens after\n * loading. Events FIRST understands: `sportId`, `leagueId`, `eventId` (`{ value: id }`),\n * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`\n * (`{ value: boolean }`), `bscode` (`{ value: code }`) and `shareBetslip` (`{ url }`).\n * @example\n * frame.send('sportId', { value: '66' })\n * @throws {EnginexError} `CONFIGURATION_ERROR` if the `src` has no valid http(s) origin, if the\n * iframe has no `contentWindow` or after `dispose()`.\n */\n send(eventType: string, eventData?: unknown): void\n /** Removes the listener. Idempotent; after that nothing is delivered and `send` throws. */\n dispose(): void\n}\n\n/**\n * Options of {@link connectFirstFrame}.\n * @category Sportsbook\n */\nexport interface ConnectFirstFrameOptions {\n /** Window to listen for `message` on. Default: `globalThis` (the window of the page that contains the iframe). */\n window?: FirstFrameWindow\n}\n\nconst BRAND = Symbol.for('getenginex.error')\n\n// Error compatible with the core's `EnginexError` without importing it: the core cannot enter this entry\n// (importing `@getenginex/sdk`, even only for the error, would leave a runtime `import`). The core\n// recognizes errors by `instanceof Error` + the global mark `Symbol.for('getenginex.error')`, so\n// `isEnginexError(e, 'CONFIGURATION_ERROR')` answers `true` for this error.\nclass FirstFrameConfigurationError extends Error {\n override readonly name = 'EnginexError'\n readonly code = 'CONFIGURATION_ERROR'\n readonly status = 0\n readonly details = undefined\n constructor(message: string) {\n super(message)\n Object.defineProperty(this, BRAND, { value: true })\n }\n\n override toString(): string {\n return `EnginexError [${this.code}]: ${this.message}`\n }\n\n toJSON() {\n return { name: this.name, code: this.code, message: this.message, status: this.status }\n }\n}\n\nconst NO_ORIGIN =\n 'The FIRST iframe src has no valid http(s) origin: set iframe.src to the launchUrl before using the frame.'\n\n/** http(s) origin of `src`, or `null`. It never throws nor includes the `src` (it has a token) in messages. */\nfunction originOf(src: string): string | null {\n try {\n const url = new URL(src)\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : null\n } catch {\n return null\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction parse(data: unknown): Record<string, unknown> | undefined {\n let value = data\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n return isRecord(value) ? value : undefined\n}\n\nfunction call(fn: (() => unknown) | undefined): void {\n if (!fn) return\n try {\n const result = fn()\n // `Promise.resolve` also adopts thenables and promises from another realm (not `instanceof Promise`).\n Promise.resolve(result).catch(() => {})\n } catch {\n // a faulty handler does not take down the listener nor the other handlers\n }\n}\n\nfunction positiveNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined\n}\n\nfunction dispatch(message: Record<string, unknown>, handlers: FirstFrameHandlers): void {\n const rawType = message.eventType || message.type\n if (typeof rawType !== 'string' || rawType === '') return\n const eventType = rawType\n const eventData = message.eventData\n const on = <A extends unknown[]>(handler: ((...args: A) => void) | undefined, ...args: A) =>\n call(handler && (() => handler.apply(handlers, args)))\n\n switch (eventType) {\n case 'APP_READY':\n on(handlers.onReady)\n break\n case 'BET_WAS_PLACED':\n on(handlers.onBetPlaced, eventData)\n break\n case 'INSUFFICIENT_FUNDS':\n on(handlers.onInsufficientFunds, eventData)\n break\n case 'depositClick':\n on(handlers.onDepositClick, eventData)\n break\n case 'PLACE_BET_CLICKED_NOT_LOGGED_IN':\n case 'OPEN_LOGIN_POPUP':\n on(handlers.onLoginRequired, eventData)\n break\n case 'on-page-height-change':\n case 'ON_PAGE_HEIGHT_CHANGE': {\n const height =\n positiveNumber(isRecord(eventData) ? eventData.height : undefined) ?? positiveNumber(message.height)\n if (height !== undefined) on(handlers.onHeightChange, height)\n break\n }\n case 'BUTTON_REDIRECT': {\n // `link` only reaches the handler if it is text (the top-level one in the message takes precedence): the public\n // type promises `link?: string`, and a number or object coming from the iframe would break whoever validates the URL.\n const data: FirstFrameRedirect = { ...(isRecord(eventData) ? eventData : {}) }\n if (typeof message.link === 'string') data.link = message.link\n else if (typeof data.link !== 'string') delete data.link\n on(handlers.onRedirect, data)\n break\n }\n case 'SCROLL_TO_TOP':\n on(handlers.onScrollToTop)\n break\n default:\n break\n }\n on(handlers.onEvent, eventType, eventData)\n}\n\n/**\n * Connects to the FIRST sportsbook iframe: receives FIRST's events in typed handlers and sends\n * commands with `send`. It only delivers messages whose `origin` is the `src` origin of the iframe **and** whose\n * `source` is the iframe's `contentWindow`; invalid JSON or JSON without `eventType` is ignored without throwing.\n * The payload arrives as FIRST sent it (`unknown`): validate before using it.\n * @example\n * import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'\n *\n * const frame = connectFirstFrame(iframe, {\n * onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),\n * onLoginRequired: () => openLogin(),\n * })\n * // when unmounting the iframe:\n * frame.dispose()\n * @throws {EnginexError} `CONFIGURATION_ERROR` if the window (`options.window` or `globalThis`) has no\n * `addEventListener`/`removeEventListener`.\n * @category Sportsbook\n */\nexport function connectFirstFrame(\n iframe: FirstFrameTarget,\n handlers: FirstFrameHandlers,\n options: ConnectFirstFrameOptions = {},\n): FirstFrame {\n const win = options.window ?? (globalThis as unknown as Partial<FirstFrameWindow>)\n if (typeof win.addEventListener !== 'function' || typeof win.removeEventListener !== 'function') {\n throw new FirstFrameConfigurationError(\n 'connectFirstFrame needs a window with addEventListener: outside the browser, pass options.window.',\n )\n }\n let disposed = false\n\n const listener = (event: FirstFrameMessageEvent): void => {\n if (disposed) return\n const target = iframe.contentWindow\n const origin = originOf(iframe.src)\n if (target === null || origin === null || event.source !== target || event.origin !== origin) return\n const message = parse(event.data)\n if (message) dispatch(message, handlers)\n }\n win.addEventListener('message', listener)\n\n return {\n send(eventType, eventData) {\n if (disposed) throw new FirstFrameConfigurationError('The FIRST frame has already been closed (dispose).')\n const origin = originOf(iframe.src)\n if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN)\n const target = iframe.contentWindow\n if (target === null) {\n throw new FirstFrameConfigurationError('The FIRST iframe has no contentWindow yet (it is not in the document).')\n }\n target.postMessage(JSON.stringify({ eventType, eventData }), origin)\n },\n dispose() {\n if (disposed) return\n disposed = true\n win.removeEventListener?.('message', listener)\n },\n }\n}\n"]}
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Typed bridge with origin checking for the `postMessage` events of the FIRST sportsbook iframe.
3
+ *
4
+ * This entry does not import the core at runtime nor require `lib.dom` in the consumer's types. It is the only
5
+ * entry of the package that touches the DOM, and only through the objects the app passes (the iframe and the window).
6
+ * @module @getenginex/sdk-igaming/first-frame
7
+ */
8
+ /**
9
+ * `postMessage` message as the helper reads it: only the fields it uses (a DOM `MessageEvent` is
10
+ * assignable).
11
+ * @category Sportsbook
12
+ */
13
+ interface FirstFrameMessageEvent {
14
+ /** Content sent by the iframe: a JSON string or an object. */
15
+ readonly data: unknown;
16
+ /** Sender's origin. */
17
+ readonly origin: string;
18
+ /** Sender's window. */
19
+ readonly source: unknown;
20
+ }
21
+ /**
22
+ * Page window, with the minimum the helper uses: a DOM `Window` is assignable. It is the app's window
23
+ * (the one that receives the iframe's messages), not the iframe's.
24
+ * @category Sportsbook
25
+ */
26
+ interface FirstFrameWindow {
27
+ /** Registers the `message` listener. */
28
+ addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void;
29
+ /** Removes the `message` listener. */
30
+ removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void;
31
+ }
32
+ /**
33
+ * The FIRST iframe, with the minimum the helper uses: an `HTMLIFrameElement` is assignable. The expected
34
+ * origin and the destination of the messages come from `src` (re-read on every message).
35
+ * @category Sportsbook
36
+ */
37
+ interface FirstFrameTarget {
38
+ /** URL loaded in the iframe (the session's `launchUrl`). The trusted origin comes from it. */
39
+ readonly src: string;
40
+ /** The iframe's window; `null` while it is not in the document. */
41
+ readonly contentWindow: {
42
+ /** Sends a message to the iframe. */
43
+ postMessage(message: string, targetOrigin: string): void;
44
+ } | null;
45
+ }
46
+ /**
47
+ * Argument of `onRedirect`: the fields of `eventData` (if it is an object) plus the top-level `link` of the
48
+ * message. The SDK only guarantees that `link`, when present, is text (a `link` of another type is
49
+ * dropped); the content is not validated and `link` may be missing.
50
+ * @category Sportsbook
51
+ */
52
+ interface FirstFrameRedirect {
53
+ /** Destination requested by FIRST; optional and untrusted (validate before opening). */
54
+ link?: string;
55
+ /** Other `eventData` fields, as FIRST sent them. */
56
+ [key: string]: unknown;
57
+ }
58
+ /**
59
+ * Handlers for the iframe events. All optional; a handler that throws (or rejects) is ignored and
60
+ * does not prevent the others.
61
+ * @category Sportsbook
62
+ */
63
+ interface FirstFrameHandlers {
64
+ /** `APP_READY`: the sportsbook has loaded and accepts `send`. */
65
+ onReady?(): void;
66
+ /** `BET_WAS_PLACED`: a bet was placed (a good moment to re-read the balance). */
67
+ onBetPlaced?(data: unknown): void;
68
+ /** `INSUFFICIENT_FUNDS`: insufficient balance for the bet. */
69
+ onInsufficientFunds?(data: unknown): void;
70
+ /** `depositClick`: the player asked to deposit. */
71
+ onDepositClick?(data: unknown): void;
72
+ /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` or `OPEN_LOGIN_POPUP`: the player needs to log in. */
73
+ onLoginRequired?(data: unknown): void;
74
+ /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: new content height (px, positive). */
75
+ onHeightChange?(height: number): void;
76
+ /**
77
+ * `BUTTON_REDIRECT`: FIRST asks to open a link. `data.link` comes at the top of the message (or in
78
+ * `eventData`) and **may be missing or not a valid URL**. **Validate before opening**: accept only
79
+ * http(s), without credentials.
80
+ */
81
+ onRedirect?(data: FirstFrameRedirect): void;
82
+ /** `SCROLL_TO_TOP`: FIRST asks to scroll the page to the top. */
83
+ onScrollToTop?(): void;
84
+ /** Every accepted event, including those that also have a dedicated handler. */
85
+ onEvent?(eventType: string, eventData: unknown): void;
86
+ }
87
+ /**
88
+ * Connection to the FIRST iframe.
89
+ * @category Sportsbook
90
+ */
91
+ interface FirstFrame {
92
+ /**
93
+ * Sends an event to the iframe: `postMessage(JSON.stringify({ eventType, eventData }), origin)`, with the
94
+ * origin of the `src` (never `'*'`). Wait for `onReady` before sending: FIRST only listens after
95
+ * loading. Events FIRST understands: `sportId`, `leagueId`, `eventId` (`{ value: id }`),
96
+ * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`
97
+ * (`{ value: boolean }`), `bscode` (`{ value: code }`) and `shareBetslip` (`{ url }`).
98
+ * @example
99
+ * frame.send('sportId', { value: '66' })
100
+ * @throws {EnginexError} `CONFIGURATION_ERROR` if the `src` has no valid http(s) origin, if the
101
+ * iframe has no `contentWindow` or after `dispose()`.
102
+ */
103
+ send(eventType: string, eventData?: unknown): void;
104
+ /** Removes the listener. Idempotent; after that nothing is delivered and `send` throws. */
105
+ dispose(): void;
106
+ }
107
+ /**
108
+ * Options of {@link connectFirstFrame}.
109
+ * @category Sportsbook
110
+ */
111
+ interface ConnectFirstFrameOptions {
112
+ /** Window to listen for `message` on. Default: `globalThis` (the window of the page that contains the iframe). */
113
+ window?: FirstFrameWindow;
114
+ }
115
+ /**
116
+ * Connects to the FIRST sportsbook iframe: receives FIRST's events in typed handlers and sends
117
+ * commands with `send`. It only delivers messages whose `origin` is the `src` origin of the iframe **and** whose
118
+ * `source` is the iframe's `contentWindow`; invalid JSON or JSON without `eventType` is ignored without throwing.
119
+ * The payload arrives as FIRST sent it (`unknown`): validate before using it.
120
+ * @example
121
+ * import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'
122
+ *
123
+ * const frame = connectFirstFrame(iframe, {
124
+ * onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),
125
+ * onLoginRequired: () => openLogin(),
126
+ * })
127
+ * // when unmounting the iframe:
128
+ * frame.dispose()
129
+ * @throws {EnginexError} `CONFIGURATION_ERROR` if the window (`options.window` or `globalThis`) has no
130
+ * `addEventListener`/`removeEventListener`.
131
+ * @category Sportsbook
132
+ */
133
+ declare function connectFirstFrame(iframe: FirstFrameTarget, handlers: FirstFrameHandlers, options?: ConnectFirstFrameOptions): FirstFrame;
134
+
135
+ export { type ConnectFirstFrameOptions, type FirstFrame, type FirstFrameHandlers, type FirstFrameMessageEvent, type FirstFrameRedirect, type FirstFrameTarget, type FirstFrameWindow, connectFirstFrame };
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Typed bridge with origin checking for the `postMessage` events of the FIRST sportsbook iframe.
3
+ *
4
+ * This entry does not import the core at runtime nor require `lib.dom` in the consumer's types. It is the only
5
+ * entry of the package that touches the DOM, and only through the objects the app passes (the iframe and the window).
6
+ * @module @getenginex/sdk-igaming/first-frame
7
+ */
8
+ /**
9
+ * `postMessage` message as the helper reads it: only the fields it uses (a DOM `MessageEvent` is
10
+ * assignable).
11
+ * @category Sportsbook
12
+ */
13
+ interface FirstFrameMessageEvent {
14
+ /** Content sent by the iframe: a JSON string or an object. */
15
+ readonly data: unknown;
16
+ /** Sender's origin. */
17
+ readonly origin: string;
18
+ /** Sender's window. */
19
+ readonly source: unknown;
20
+ }
21
+ /**
22
+ * Page window, with the minimum the helper uses: a DOM `Window` is assignable. It is the app's window
23
+ * (the one that receives the iframe's messages), not the iframe's.
24
+ * @category Sportsbook
25
+ */
26
+ interface FirstFrameWindow {
27
+ /** Registers the `message` listener. */
28
+ addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void;
29
+ /** Removes the `message` listener. */
30
+ removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void;
31
+ }
32
+ /**
33
+ * The FIRST iframe, with the minimum the helper uses: an `HTMLIFrameElement` is assignable. The expected
34
+ * origin and the destination of the messages come from `src` (re-read on every message).
35
+ * @category Sportsbook
36
+ */
37
+ interface FirstFrameTarget {
38
+ /** URL loaded in the iframe (the session's `launchUrl`). The trusted origin comes from it. */
39
+ readonly src: string;
40
+ /** The iframe's window; `null` while it is not in the document. */
41
+ readonly contentWindow: {
42
+ /** Sends a message to the iframe. */
43
+ postMessage(message: string, targetOrigin: string): void;
44
+ } | null;
45
+ }
46
+ /**
47
+ * Argument of `onRedirect`: the fields of `eventData` (if it is an object) plus the top-level `link` of the
48
+ * message. The SDK only guarantees that `link`, when present, is text (a `link` of another type is
49
+ * dropped); the content is not validated and `link` may be missing.
50
+ * @category Sportsbook
51
+ */
52
+ interface FirstFrameRedirect {
53
+ /** Destination requested by FIRST; optional and untrusted (validate before opening). */
54
+ link?: string;
55
+ /** Other `eventData` fields, as FIRST sent them. */
56
+ [key: string]: unknown;
57
+ }
58
+ /**
59
+ * Handlers for the iframe events. All optional; a handler that throws (or rejects) is ignored and
60
+ * does not prevent the others.
61
+ * @category Sportsbook
62
+ */
63
+ interface FirstFrameHandlers {
64
+ /** `APP_READY`: the sportsbook has loaded and accepts `send`. */
65
+ onReady?(): void;
66
+ /** `BET_WAS_PLACED`: a bet was placed (a good moment to re-read the balance). */
67
+ onBetPlaced?(data: unknown): void;
68
+ /** `INSUFFICIENT_FUNDS`: insufficient balance for the bet. */
69
+ onInsufficientFunds?(data: unknown): void;
70
+ /** `depositClick`: the player asked to deposit. */
71
+ onDepositClick?(data: unknown): void;
72
+ /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` or `OPEN_LOGIN_POPUP`: the player needs to log in. */
73
+ onLoginRequired?(data: unknown): void;
74
+ /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: new content height (px, positive). */
75
+ onHeightChange?(height: number): void;
76
+ /**
77
+ * `BUTTON_REDIRECT`: FIRST asks to open a link. `data.link` comes at the top of the message (or in
78
+ * `eventData`) and **may be missing or not a valid URL**. **Validate before opening**: accept only
79
+ * http(s), without credentials.
80
+ */
81
+ onRedirect?(data: FirstFrameRedirect): void;
82
+ /** `SCROLL_TO_TOP`: FIRST asks to scroll the page to the top. */
83
+ onScrollToTop?(): void;
84
+ /** Every accepted event, including those that also have a dedicated handler. */
85
+ onEvent?(eventType: string, eventData: unknown): void;
86
+ }
87
+ /**
88
+ * Connection to the FIRST iframe.
89
+ * @category Sportsbook
90
+ */
91
+ interface FirstFrame {
92
+ /**
93
+ * Sends an event to the iframe: `postMessage(JSON.stringify({ eventType, eventData }), origin)`, with the
94
+ * origin of the `src` (never `'*'`). Wait for `onReady` before sending: FIRST only listens after
95
+ * loading. Events FIRST understands: `sportId`, `leagueId`, `eventId` (`{ value: id }`),
96
+ * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`
97
+ * (`{ value: boolean }`), `bscode` (`{ value: code }`) and `shareBetslip` (`{ url }`).
98
+ * @example
99
+ * frame.send('sportId', { value: '66' })
100
+ * @throws {EnginexError} `CONFIGURATION_ERROR` if the `src` has no valid http(s) origin, if the
101
+ * iframe has no `contentWindow` or after `dispose()`.
102
+ */
103
+ send(eventType: string, eventData?: unknown): void;
104
+ /** Removes the listener. Idempotent; after that nothing is delivered and `send` throws. */
105
+ dispose(): void;
106
+ }
107
+ /**
108
+ * Options of {@link connectFirstFrame}.
109
+ * @category Sportsbook
110
+ */
111
+ interface ConnectFirstFrameOptions {
112
+ /** Window to listen for `message` on. Default: `globalThis` (the window of the page that contains the iframe). */
113
+ window?: FirstFrameWindow;
114
+ }
115
+ /**
116
+ * Connects to the FIRST sportsbook iframe: receives FIRST's events in typed handlers and sends
117
+ * commands with `send`. It only delivers messages whose `origin` is the `src` origin of the iframe **and** whose
118
+ * `source` is the iframe's `contentWindow`; invalid JSON or JSON without `eventType` is ignored without throwing.
119
+ * The payload arrives as FIRST sent it (`unknown`): validate before using it.
120
+ * @example
121
+ * import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'
122
+ *
123
+ * const frame = connectFirstFrame(iframe, {
124
+ * onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),
125
+ * onLoginRequired: () => openLogin(),
126
+ * })
127
+ * // when unmounting the iframe:
128
+ * frame.dispose()
129
+ * @throws {EnginexError} `CONFIGURATION_ERROR` if the window (`options.window` or `globalThis`) has no
130
+ * `addEventListener`/`removeEventListener`.
131
+ * @category Sportsbook
132
+ */
133
+ declare function connectFirstFrame(iframe: FirstFrameTarget, handlers: FirstFrameHandlers, options?: ConnectFirstFrameOptions): FirstFrame;
134
+
135
+ export { type ConnectFirstFrameOptions, type FirstFrame, type FirstFrameHandlers, type FirstFrameMessageEvent, type FirstFrameRedirect, type FirstFrameTarget, type FirstFrameWindow, connectFirstFrame };
@@ -0,0 +1,134 @@
1
+ // src/first-frame/index.ts
2
+ var BRAND = /* @__PURE__ */ Symbol.for("getenginex.error");
3
+ var FirstFrameConfigurationError = class extends Error {
4
+ name = "EnginexError";
5
+ code = "CONFIGURATION_ERROR";
6
+ status = 0;
7
+ details = void 0;
8
+ constructor(message) {
9
+ super(message);
10
+ Object.defineProperty(this, BRAND, { value: true });
11
+ }
12
+ toString() {
13
+ return `EnginexError [${this.code}]: ${this.message}`;
14
+ }
15
+ toJSON() {
16
+ return { name: this.name, code: this.code, message: this.message, status: this.status };
17
+ }
18
+ };
19
+ var NO_ORIGIN = "The FIRST iframe src has no valid http(s) origin: set iframe.src to the launchUrl before using the frame.";
20
+ function originOf(src) {
21
+ try {
22
+ const url = new URL(src);
23
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ function isRecord(value) {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
31
+ function parse(data) {
32
+ let value = data;
33
+ if (typeof value === "string") {
34
+ try {
35
+ value = JSON.parse(value);
36
+ } catch {
37
+ return void 0;
38
+ }
39
+ }
40
+ return isRecord(value) ? value : void 0;
41
+ }
42
+ function call(fn) {
43
+ if (!fn) return;
44
+ try {
45
+ const result = fn();
46
+ Promise.resolve(result).catch(() => {
47
+ });
48
+ } catch {
49
+ }
50
+ }
51
+ function positiveNumber(value) {
52
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
53
+ }
54
+ function dispatch(message, handlers) {
55
+ const rawType = message.eventType || message.type;
56
+ if (typeof rawType !== "string" || rawType === "") return;
57
+ const eventType = rawType;
58
+ const eventData = message.eventData;
59
+ const on = (handler, ...args) => call(handler && (() => handler.apply(handlers, args)));
60
+ switch (eventType) {
61
+ case "APP_READY":
62
+ on(handlers.onReady);
63
+ break;
64
+ case "BET_WAS_PLACED":
65
+ on(handlers.onBetPlaced, eventData);
66
+ break;
67
+ case "INSUFFICIENT_FUNDS":
68
+ on(handlers.onInsufficientFunds, eventData);
69
+ break;
70
+ case "depositClick":
71
+ on(handlers.onDepositClick, eventData);
72
+ break;
73
+ case "PLACE_BET_CLICKED_NOT_LOGGED_IN":
74
+ case "OPEN_LOGIN_POPUP":
75
+ on(handlers.onLoginRequired, eventData);
76
+ break;
77
+ case "on-page-height-change":
78
+ case "ON_PAGE_HEIGHT_CHANGE": {
79
+ const height = positiveNumber(isRecord(eventData) ? eventData.height : void 0) ?? positiveNumber(message.height);
80
+ if (height !== void 0) on(handlers.onHeightChange, height);
81
+ break;
82
+ }
83
+ case "BUTTON_REDIRECT": {
84
+ const data = { ...isRecord(eventData) ? eventData : {} };
85
+ if (typeof message.link === "string") data.link = message.link;
86
+ else if (typeof data.link !== "string") delete data.link;
87
+ on(handlers.onRedirect, data);
88
+ break;
89
+ }
90
+ case "SCROLL_TO_TOP":
91
+ on(handlers.onScrollToTop);
92
+ break;
93
+ }
94
+ on(handlers.onEvent, eventType, eventData);
95
+ }
96
+ function connectFirstFrame(iframe, handlers, options = {}) {
97
+ const win = options.window ?? globalThis;
98
+ if (typeof win.addEventListener !== "function" || typeof win.removeEventListener !== "function") {
99
+ throw new FirstFrameConfigurationError(
100
+ "connectFirstFrame needs a window with addEventListener: outside the browser, pass options.window."
101
+ );
102
+ }
103
+ let disposed = false;
104
+ const listener = (event) => {
105
+ if (disposed) return;
106
+ const target = iframe.contentWindow;
107
+ const origin = originOf(iframe.src);
108
+ if (target === null || origin === null || event.source !== target || event.origin !== origin) return;
109
+ const message = parse(event.data);
110
+ if (message) dispatch(message, handlers);
111
+ };
112
+ win.addEventListener("message", listener);
113
+ return {
114
+ send(eventType, eventData) {
115
+ if (disposed) throw new FirstFrameConfigurationError("The FIRST frame has already been closed (dispose).");
116
+ const origin = originOf(iframe.src);
117
+ if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN);
118
+ const target = iframe.contentWindow;
119
+ if (target === null) {
120
+ throw new FirstFrameConfigurationError("The FIRST iframe has no contentWindow yet (it is not in the document).");
121
+ }
122
+ target.postMessage(JSON.stringify({ eventType, eventData }), origin);
123
+ },
124
+ dispose() {
125
+ if (disposed) return;
126
+ disposed = true;
127
+ win.removeEventListener?.("message", listener);
128
+ }
129
+ };
130
+ }
131
+
132
+ export { connectFirstFrame };
133
+ //# sourceMappingURL=index.js.map
134
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/first-frame/index.ts"],"names":[],"mappings":";AA0HA,IAAM,KAAA,mBAAQ,MAAA,CAAO,GAAA,CAAI,kBAAkB,CAAA;AAM3C,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAC7B,IAAA,GAAO,cAAA;AAAA,EAChB,IAAA,GAAO,qBAAA;AAAA,EACP,MAAA,GAAS,CAAA;AAAA,EACT,OAAA,GAAU,MAAA;AAAA,EACnB,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,eAAe,IAAA,EAAM,KAAA,EAAO,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EACpD;AAAA,EAES,QAAA,GAAmB;AAC1B,IAAA,OAAO,CAAA,cAAA,EAAiB,IAAA,CAAK,IAAI,CAAA,GAAA,EAAM,KAAK,OAAO,CAAA,CAAA;AAAA,EACrD;AAAA,EAEA,MAAA,GAAS;AACP,IAAA,OAAO,EAAE,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AAI,MAAA,KAAW,QAAQ,MAAA,KAAW,IAAA,IAAQ,MAAM,MAAA,KAAW,MAAA,IAAU,KAAA,CAAM,MAAA,KAAW,MAAA,EAAQ;AAC9F,IAAA,MAAM,OAAA,GAAU,KAAA,CAAM,KAAA,CAAM,IAAI,CAAA;AAChC,IAAA,IAAI,OAAA,EAAS,QAAA,CAAS,OAAA,EAAS,QAAQ,CAAA;AAAA,EACzC,CAAA;AACA,EAAA,GAAA,CAAI,gBAAA,CAAiB,WAAW,QAAQ,CAAA;AAExC,EAAA,OAAO;AAAA,IACL,IAAA,CAAK,WAAW,SAAA,EAAW;AACzB,MAAA,IAAI,QAAA,EAAU,MAAM,IAAI,4BAAA,CAA6B,oDAAoD,CAAA;AACzG,MAAA,MAAM,MAAA,GAAS,QAAA,CAAS,MAAA,CAAO,GAAG,CAAA;AAClC,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,MAAM,IAAI,6BAA6B,SAAS,CAAA;AACrE,MAAA,MAAM,SAAS,MAAA,CAAO,aAAA;AACtB,MAAA,IAAI,WAAW,IAAA,EAAM;AACnB,QAAA,MAAM,IAAI,6BAA6B,wEAAwE,CAAA;AAAA,MACjH;AACA,MAAA,MAAA,CAAO,WAAA,CAAY,KAAK,SAAA,CAAU,EAAE,WAAW,SAAA,EAAW,GAAG,MAAM,CAAA;AAAA,IACrE,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,GAAA,CAAI,mBAAA,GAAsB,WAAW,QAAQ,CAAA;AAAA,IAC/C;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Typed bridge with origin checking for the `postMessage` events of the FIRST sportsbook iframe.\n *\n * This entry does not import the core at runtime nor require `lib.dom` in the consumer's types. It is the only\n * entry of the package that touches the DOM, and only through the objects the app passes (the iframe and the window).\n * @module @getenginex/sdk-igaming/first-frame\n */\n\n/**\n * `postMessage` message as the helper reads it: only the fields it uses (a DOM `MessageEvent` is\n * assignable).\n * @category Sportsbook\n */\nexport interface FirstFrameMessageEvent {\n /** Content sent by the iframe: a JSON string or an object. */\n readonly data: unknown\n /** Sender's origin. */\n readonly origin: string\n /** Sender's window. */\n readonly source: unknown\n}\n\n/**\n * Page window, with the minimum the helper uses: a DOM `Window` is assignable. It is the app's window\n * (the one that receives the iframe's messages), not the iframe's.\n * @category Sportsbook\n */\nexport interface FirstFrameWindow {\n /** Registers the `message` listener. */\n addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n /** Removes the `message` listener. */\n removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n}\n\n/**\n * The FIRST iframe, with the minimum the helper uses: an `HTMLIFrameElement` is assignable. The expected\n * origin and the destination of the messages come from `src` (re-read on every message).\n * @category Sportsbook\n */\nexport interface FirstFrameTarget {\n /** URL loaded in the iframe (the session's `launchUrl`). The trusted origin comes from it. */\n readonly src: string\n /** The iframe's window; `null` while it is not in the document. */\n readonly contentWindow: {\n /** Sends a message to the iframe. */\n postMessage(message: string, targetOrigin: string): void\n } | null\n}\n\n/**\n * Argument of `onRedirect`: the fields of `eventData` (if it is an object) plus the top-level `link` of the\n * message. The SDK only guarantees that `link`, when present, is text (a `link` of another type is\n * dropped); the content is not validated and `link` may be missing.\n * @category Sportsbook\n */\nexport interface FirstFrameRedirect {\n /** Destination requested by FIRST; optional and untrusted (validate before opening). */\n link?: string\n /** Other `eventData` fields, as FIRST sent them. */\n [key: string]: unknown\n}\n\n/**\n * Handlers for the iframe events. All optional; a handler that throws (or rejects) is ignored and\n * does not prevent the others.\n * @category Sportsbook\n */\nexport interface FirstFrameHandlers {\n /** `APP_READY`: the sportsbook has loaded and accepts `send`. */\n onReady?(): void\n /** `BET_WAS_PLACED`: a bet was placed (a good moment to re-read the balance). */\n onBetPlaced?(data: unknown): void\n /** `INSUFFICIENT_FUNDS`: insufficient balance for the bet. */\n onInsufficientFunds?(data: unknown): void\n /** `depositClick`: the player asked to deposit. */\n onDepositClick?(data: unknown): void\n /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` or `OPEN_LOGIN_POPUP`: the player needs to log in. */\n onLoginRequired?(data: unknown): void\n /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: new content height (px, positive). */\n onHeightChange?(height: number): void\n /**\n * `BUTTON_REDIRECT`: FIRST asks to open a link. `data.link` comes at the top of the message (or in\n * `eventData`) and **may be missing or not a valid URL**. **Validate before opening**: accept only\n * http(s), without credentials.\n */\n onRedirect?(data: FirstFrameRedirect): void\n /** `SCROLL_TO_TOP`: FIRST asks to scroll the page to the top. */\n onScrollToTop?(): void\n /** Every accepted event, including those that also have a dedicated handler. */\n onEvent?(eventType: string, eventData: unknown): void\n}\n\n/**\n * Connection to the FIRST iframe.\n * @category Sportsbook\n */\nexport interface FirstFrame {\n /**\n * Sends an event to the iframe: `postMessage(JSON.stringify({ eventType, eventData }), origin)`, with the\n * origin of the `src` (never `'*'`). Wait for `onReady` before sending: FIRST only listens after\n * loading. Events FIRST understands: `sportId`, `leagueId`, `eventId` (`{ value: id }`),\n * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`\n * (`{ value: boolean }`), `bscode` (`{ value: code }`) and `shareBetslip` (`{ url }`).\n * @example\n * frame.send('sportId', { value: '66' })\n * @throws {EnginexError} `CONFIGURATION_ERROR` if the `src` has no valid http(s) origin, if the\n * iframe has no `contentWindow` or after `dispose()`.\n */\n send(eventType: string, eventData?: unknown): void\n /** Removes the listener. Idempotent; after that nothing is delivered and `send` throws. */\n dispose(): void\n}\n\n/**\n * Options of {@link connectFirstFrame}.\n * @category Sportsbook\n */\nexport interface ConnectFirstFrameOptions {\n /** Window to listen for `message` on. Default: `globalThis` (the window of the page that contains the iframe). */\n window?: FirstFrameWindow\n}\n\nconst BRAND = Symbol.for('getenginex.error')\n\n// Error compatible with the core's `EnginexError` without importing it: the core cannot enter this entry\n// (importing `@getenginex/sdk`, even only for the error, would leave a runtime `import`). The core\n// recognizes errors by `instanceof Error` + the global mark `Symbol.for('getenginex.error')`, so\n// `isEnginexError(e, 'CONFIGURATION_ERROR')` answers `true` for this error.\nclass FirstFrameConfigurationError extends Error {\n override readonly name = 'EnginexError'\n readonly code = 'CONFIGURATION_ERROR'\n readonly status = 0\n readonly details = undefined\n constructor(message: string) {\n super(message)\n Object.defineProperty(this, BRAND, { value: true })\n }\n\n override toString(): string {\n return `EnginexError [${this.code}]: ${this.message}`\n }\n\n toJSON() {\n return { name: this.name, code: this.code, message: this.message, status: this.status }\n }\n}\n\nconst NO_ORIGIN =\n 'The FIRST iframe src has no valid http(s) origin: set iframe.src to the launchUrl before using the frame.'\n\n/** http(s) origin of `src`, or `null`. It never throws nor includes the `src` (it has a token) in messages. */\nfunction originOf(src: string): string | null {\n try {\n const url = new URL(src)\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : null\n } catch {\n return null\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction parse(data: unknown): Record<string, unknown> | undefined {\n let value = data\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n return isRecord(value) ? value : undefined\n}\n\nfunction call(fn: (() => unknown) | undefined): void {\n if (!fn) return\n try {\n const result = fn()\n // `Promise.resolve` also adopts thenables and promises from another realm (not `instanceof Promise`).\n Promise.resolve(result).catch(() => {})\n } catch {\n // a faulty handler does not take down the listener nor the other handlers\n }\n}\n\nfunction positiveNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined\n}\n\nfunction dispatch(message: Record<string, unknown>, handlers: FirstFrameHandlers): void {\n const rawType = message.eventType || message.type\n if (typeof rawType !== 'string' || rawType === '') return\n const eventType = rawType\n const eventData = message.eventData\n const on = <A extends unknown[]>(handler: ((...args: A) => void) | undefined, ...args: A) =>\n call(handler && (() => handler.apply(handlers, args)))\n\n switch (eventType) {\n case 'APP_READY':\n on(handlers.onReady)\n break\n case 'BET_WAS_PLACED':\n on(handlers.onBetPlaced, eventData)\n break\n case 'INSUFFICIENT_FUNDS':\n on(handlers.onInsufficientFunds, eventData)\n break\n case 'depositClick':\n on(handlers.onDepositClick, eventData)\n break\n case 'PLACE_BET_CLICKED_NOT_LOGGED_IN':\n case 'OPEN_LOGIN_POPUP':\n on(handlers.onLoginRequired, eventData)\n break\n case 'on-page-height-change':\n case 'ON_PAGE_HEIGHT_CHANGE': {\n const height =\n positiveNumber(isRecord(eventData) ? eventData.height : undefined) ?? positiveNumber(message.height)\n if (height !== undefined) on(handlers.onHeightChange, height)\n break\n }\n case 'BUTTON_REDIRECT': {\n // `link` only reaches the handler if it is text (the top-level one in the message takes precedence): the public\n // type promises `link?: string`, and a number or object coming from the iframe would break whoever validates the URL.\n const data: FirstFrameRedirect = { ...(isRecord(eventData) ? eventData : {}) }\n if (typeof message.link === 'string') data.link = message.link\n else if (typeof data.link !== 'string') delete data.link\n on(handlers.onRedirect, data)\n break\n }\n case 'SCROLL_TO_TOP':\n on(handlers.onScrollToTop)\n break\n default:\n break\n }\n on(handlers.onEvent, eventType, eventData)\n}\n\n/**\n * Connects to the FIRST sportsbook iframe: receives FIRST's events in typed handlers and sends\n * commands with `send`. It only delivers messages whose `origin` is the `src` origin of the iframe **and** whose\n * `source` is the iframe's `contentWindow`; invalid JSON or JSON without `eventType` is ignored without throwing.\n * The payload arrives as FIRST sent it (`unknown`): validate before using it.\n * @example\n * import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'\n *\n * const frame = connectFirstFrame(iframe, {\n * onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),\n * onLoginRequired: () => openLogin(),\n * })\n * // when unmounting the iframe:\n * frame.dispose()\n * @throws {EnginexError} `CONFIGURATION_ERROR` if the window (`options.window` or `globalThis`) has no\n * `addEventListener`/`removeEventListener`.\n * @category Sportsbook\n */\nexport function connectFirstFrame(\n iframe: FirstFrameTarget,\n handlers: FirstFrameHandlers,\n options: ConnectFirstFrameOptions = {},\n): FirstFrame {\n const win = options.window ?? (globalThis as unknown as Partial<FirstFrameWindow>)\n if (typeof win.addEventListener !== 'function' || typeof win.removeEventListener !== 'function') {\n throw new FirstFrameConfigurationError(\n 'connectFirstFrame needs a window with addEventListener: outside the browser, pass options.window.',\n )\n }\n let disposed = false\n\n const listener = (event: FirstFrameMessageEvent): void => {\n if (disposed) return\n const target = iframe.contentWindow\n const origin = originOf(iframe.src)\n if (target === null || origin === null || event.source !== target || event.origin !== origin) return\n const message = parse(event.data)\n if (message) dispatch(message, handlers)\n }\n win.addEventListener('message', listener)\n\n return {\n send(eventType, eventData) {\n if (disposed) throw new FirstFrameConfigurationError('The FIRST frame has already been closed (dispose).')\n const origin = originOf(iframe.src)\n if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN)\n const target = iframe.contentWindow\n if (target === null) {\n throw new FirstFrameConfigurationError('The FIRST iframe has no contentWindow yet (it is not in the document).')\n }\n target.postMessage(JSON.stringify({ eventType, eventData }), origin)\n },\n dispose() {\n if (disposed) return\n disposed = true\n win.removeEventListener?.('message', listener)\n },\n }\n}\n"]}