@returningai/widget-sdk 1.2.16 → 1.3.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/README.md CHANGED
@@ -10,12 +10,14 @@ Your access credentials stay on your server. Your server exchanges them for a **
10
10
 
11
11
  **Step 1 — Create an access key pair** (one-time, from your dashboard):
12
12
 
13
- Go to **Community Settings > Integrations > SDK Access** and click **Create SDK Key**. Enter a name and optional allowed origins.
13
+ Go to **Community Settings > Integrations > SDK Access** and click **Create SDK Key**. Enter a name and optional allowed origins (required in production; localhost is auto-allowed in dev).
14
14
 
15
15
  The dashboard will display your `accessId` and `accessKey`. The `accessKey` is shown **once only** — save it securely.
16
16
 
17
17
  Store both values in your server environment variables.
18
18
 
19
+ > **Rotating or revoking keys:** The same dashboard page lists existing keys and lets you revoke or replace them. Revocation takes effect immediately for token issuance, and forces active sessions to re-auth on their next page load.
20
+
19
21
  **Step 2 — Exchange credentials for an embed token on every page load** (Node.js example):
20
22
 
21
23
  ```js
@@ -26,13 +28,22 @@ const response = await fetch('https://YOUR_API_URL/v2/api/widget-access-keys/tok
26
28
  body: JSON.stringify({
27
29
  accessId: process.env.RAI_ACCESS_ID,
28
30
  accessKey: process.env.RAI_ACCESS_KEY,
31
+ // userIdentifiers keys MUST be `data-*` prefixed — they match the
32
+ // `dataAttribute` value of each field configured in your widget's
33
+ // User Identifier Fields (e.g. the dashboard stores "data-email",
34
+ // "data-user-id", not bare "email"/"userId").
35
+ userIdentifiers: {
36
+ 'data-user-id': [YourUserObject].id,
37
+ 'data-email': [YourUserObject].email,
38
+ // ...any other fields configured for this widget
39
+ },
29
40
  }),
30
41
  })
31
42
  const { data } = await response.json()
32
- // data.embedToken expires in 15 minutes
43
+ // data.embedToken expires in 15 minutes and carries signed identity claims
33
44
  ```
34
45
 
35
- **Step 3 — Embed** (only the short-lived token appears in HTML):
46
+ **Step 3 — Embed** (only the short-lived token appears in HTML — no identity attributes):
36
47
 
37
48
  ```html
38
49
  <div id="returning-ai-widget-YOUR_WIDGET_ID" style="width:100%;height:600px"></div>
@@ -40,14 +51,13 @@ const { data } = await response.json()
40
51
  data-widget-id="YOUR_WIDGET_ID"
41
52
  data-widget-type="store"
42
53
  data-theme="dark"
43
- data-email="user@example.com"
44
54
  data-embed-token="eyJ..."
45
55
  api-url="YOUR_API_URL"
46
56
  widget-url="YOUR_WIDGET_URL"
47
57
  ></script>
48
58
  ```
49
59
 
50
- The SDK validates the token on widget load. If the token is expired or invalid, the widget shows an error screen. Tokens expire after 15 minutes — regenerate on each page render.
60
+ The server validates the token and extracts identity from its signed claims. If the token is expired, invalid, or its identifiers don't satisfy the widget's configured User Identifier Fields, the widget shows an error screen. Tokens expire after 15 minutes — regenerate on each page render.
51
61
 
52
62
  ---
53
63
 
@@ -81,6 +91,8 @@ Set the `data-widget-type` attribute to choose which widget to display. The Widg
81
91
  | `referral-conditions` | Referral widget |
82
92
  | `custom` | Custom widget |
83
93
 
94
+ All examples below use **Access Key Embed** (recommended) — identity is signed into `data-embed-token` server-side per the [Quick Start](#quick-start). Swap `data-embed-token="eyJ..."` for `data-*` identifier attributes if you want [Public Embed](#user-identifier-attributes) instead.
95
+
84
96
  ### Store widget
85
97
 
86
98
  ```html
@@ -89,7 +101,7 @@ Set the `data-widget-type` attribute to choose which widget to display. The Widg
89
101
  data-widget-id="YOUR_WIDGET_ID"
90
102
  data-widget-type="store"
91
103
  data-theme="dark"
92
- data-email="user@example.com"
104
+ data-embed-token="eyJ..."
93
105
  api-url="YOUR_API_URL"
94
106
  widget-url="YOUR_WIDGET_URL"
95
107
  ></script>
@@ -103,7 +115,7 @@ Set the `data-widget-type` attribute to choose which widget to display. The Widg
103
115
  data-widget-id="YOUR_WIDGET_ID"
104
116
  data-widget-type="channel"
105
117
  data-theme="dark"
106
- data-email="user@example.com"
118
+ data-embed-token="eyJ..."
107
119
  api-url="YOUR_API_URL"
108
120
  widget-url="YOUR_WIDGET_URL"
109
121
  ></script>
@@ -119,7 +131,7 @@ Set the `data-widget-type` attribute to choose which widget to display. The Widg
119
131
  data-widget-id="YOUR_WIDGET_ID"
120
132
  data-widget-type="social"
121
133
  data-theme="dark"
122
- data-email="user@example.com"
134
+ data-embed-token="eyJ..."
123
135
  api-url="YOUR_API_URL"
124
136
  widget-url="YOUR_WIDGET_URL"
125
137
  ></script>
@@ -133,7 +145,7 @@ Set the `data-widget-type` attribute to choose which widget to display. The Widg
133
145
  data-widget-id="YOUR_WIDGET_ID"
134
146
  data-widget-type="milestone"
135
147
  data-theme="dark"
136
- data-email="user@example.com"
148
+ data-embed-token="eyJ..."
137
149
  api-url="YOUR_API_URL"
138
150
  widget-url="YOUR_WIDGET_URL"
139
151
  ></script>
@@ -147,12 +159,14 @@ Set the `data-widget-type` attribute to choose which widget to display. The Widg
147
159
  data-widget-id="YOUR_WIDGET_ID"
148
160
  data-widget-type="custom"
149
161
  data-theme="dark"
150
- data-email="user@example.com"
162
+ data-embed-token="eyJ..."
151
163
  api-url="YOUR_API_URL"
152
164
  widget-url="YOUR_WIDGET_URL"
153
165
  ></script>
154
166
  ```
155
167
 
168
+ > **Custom widgets:** `YOUR_WIDGET_ID` is the base64-encoded `_id` of the CustomWidget record (not the community ID). The custom element variant `<rai-custom-widget widget-id="...">` uses this same base64 value — it's the one widget type where raw ObjectIds are not accepted.
169
+
156
170
  ---
157
171
 
158
172
  ## Attributes
@@ -175,13 +189,15 @@ All attributes can be provided with or without the `data-` prefix — both work.
175
189
  | `data-bundle-url` | No | — | URL to the widget IIFE bundle — triggers [bundle mode](#bundle-mode) (non-iframe) |
176
190
  | `data-domain-key` | Bundle mode | — | Environment key: `SGTR`, `STG`, or `PROD`. Required for bundle mode on external sites |
177
191
  | `data-theme` | No | `light` | `light` or `dark` |
178
- | `data-email` | Recommended | — | User's email for identification |
179
- | `data-embed-token` | Access Key only | — | Short-lived token from your server |
192
+ | `data-email` | Public Embed only | — | User's email for identification. **Access Key Embed:** omit — identity is signed into `data-embed-token` |
193
+ | `data-embed-token` | Access Key Embed only | — | Short-lived JWT from your server. Carries signed user identifiers — no `data-*` identifier attributes needed |
180
194
  | `data-locale` | No | — | BCP 47 locale tag (e.g. `fr-FR`) |
181
- | `data-eager` | No | — | Load immediately instead of waiting until visible |
195
+ | `data-eager` | No | — | Load immediately instead of waiting until visible (presence-based boolean) |
182
196
  | `data-auto-refresh` | No | `true` | Auto-refresh access token before expiry |
183
197
  | `data-debug` | No | `false` | Verbose console logging |
184
198
  | `data-custom-data` | No | — | JSON object forwarded to the widget |
199
+ | `data-retry-label` | No | `Retry` | Label text for the retry button on the error screen |
200
+ | `data-v2-api-url` | Reserved | — | Reserved for future deployments where V2 API endpoints live on a different host than `api-url`. Currently unused — safe to omit |
185
201
 
186
202
  ### Custom element attributes
187
203
 
@@ -194,15 +210,17 @@ All attributes can be provided with or without the `data-` prefix — both work.
194
210
  | `bundle-url` | No | — | URL to the widget IIFE bundle — triggers [bundle mode](#bundle-mode) (non-iframe) |
195
211
  | `domain-key` | Bundle mode | — | Environment key: `SGTR`, `STG`, or `PROD`. Required for bundle mode on external sites |
196
212
  | `theme` | No | `light` | `light` or `dark` |
197
- | `data-email` | Recommended | — | User's email for identification |
198
- | `embed-token` | Access Key only | — | Short-lived token from your server |
213
+ | `data-email` | Public Embed only | — | User's email for identification. **Access Key Embed:** omit — identity is signed into `embed-token` |
214
+ | `embed-token` | Access Key Embed only | — | Short-lived JWT from your server. Carries signed user identifiers — no `data-*` identifier attributes needed |
199
215
  | `width` | No | `100%` | CSS width |
200
216
  | `height` | No | `600px` | CSS height |
201
217
  | `locale` | No | — | BCP 47 locale tag (e.g. `fr-FR`) |
202
- | `eager` | No | — | Load immediately instead of waiting until visible |
218
+ | `eager` | No | — | Load immediately instead of waiting until visible (presence-based boolean) |
203
219
  | `auto-refresh` | No | `true` | Auto-refresh access token before expiry |
204
220
  | `debug` | No | `false` | Verbose console logging |
205
221
  | `custom-data` | No | — | JSON object forwarded to the widget |
222
+ | `retry-label` | No | `Retry` | Label text for the retry button on the error screen |
223
+ | `v2-api-url` | Reserved | — | Reserved for future deployments where V2 API endpoints live on a different host than `api-url`. Currently unused — safe to omit |
206
224
 
207
225
  > **`widget-id` vs `community-id`:** The script-tag method uses `data-widget-id` which is a pre-encoded identifier (base64). The custom element method uses raw ObjectIds — `community-id` for most widget types, plus `channel-id` for channel widgets. The SDK handles the encoding internally.
208
226
 
@@ -218,9 +236,12 @@ Custom elements don't need a container div — they size themselves using `width
218
236
 
219
237
  ### User Identifier Attributes
220
238
 
221
- Pass any `data-*` attribute to identify the current user. Which identifiers are available is configured per community in your dashboard.
239
+ > **Access Key Embed:** Do **not** put identifiers in HTML. Pass them inside the `userIdentifiers` object when exchanging your access credentials for an embed token (Step 2). Identity is cryptographically signed into the token so it cannot be tampered with from the browser.
240
+ >
241
+ > **Public Embed:** Pass any `data-*` attribute to identify the current user. Which identifiers are available is configured per community in your dashboard.
222
242
 
223
243
  ```html
244
+ <!-- Public Embed — identifiers in HTML -->
224
245
  <script src="https://unpkg.com/@returningai/widget-sdk/dist/rai-widget.iife.js"
225
246
  data-widget-id="YOUR_WIDGET_ID"
226
247
  data-widget-type="store"
@@ -232,7 +253,7 @@ Pass any `data-*` attribute to identify the current user. Which identifiers are
232
253
  ></script>
233
254
  ```
234
255
 
235
- Any `data-*` attribute not reserved by the SDK is forwarded to the auth API as a user identifier.
256
+ In Public Embed mode, any `data-*` attribute not reserved by the SDK is forwarded to the auth API as a user identifier.
236
257
 
237
258
  ---
238
259
 
@@ -240,7 +261,11 @@ Any `data-*` attribute not reserved by the SDK is forwarded to the auth API as a
240
261
 
241
262
  When you set the `bundle-url` attribute, the widget renders directly in the page DOM instead of inside an iframe. This gives full CSS cascade — `html[data-theme]` and Tailwind classes apply to the widget content naturally.
242
263
 
243
- `widget-url` is not needed in bundle mode. `domain-key` is required so the widget resolves the correct environment URLs.
264
+ - `widget-url` is **not** needed in bundle mode (the widget is loaded directly from `bundle-url`).
265
+ - `api-url` **is still required** — it's where the SDK sends the auth request (`/auth/serverless`).
266
+ - `domain-key` is required so the widget IIFE resolves the correct environment URLs.
267
+
268
+ Both examples below use Access Key Embed:
244
269
 
245
270
  ```html
246
271
  <!-- Script-tag approach -->
@@ -249,7 +274,7 @@ When you set the `bundle-url` attribute, the widget renders directly in the page
249
274
  data-widget-id="YOUR_WIDGET_ID"
250
275
  data-widget-type="store"
251
276
  data-theme="dark"
252
- data-email="user@example.com"
277
+ data-embed-token="eyJ..."
253
278
  data-bundle-url="YOUR_BUNDLE_URL"
254
279
  data-domain-key="YOUR_DOMAIN_KEY"
255
280
  api-url="YOUR_API_URL"
@@ -262,7 +287,7 @@ When you set the `bundle-url` attribute, the widget renders directly in the page
262
287
  api-url="YOUR_API_URL"
263
288
  bundle-url="YOUR_BUNDLE_URL"
264
289
  domain-key="YOUR_DOMAIN_KEY"
265
- data-email="user@example.com"
290
+ embed-token="eyJ..."
266
291
  theme="dark"
267
292
  width="100%"
268
293
  height="100vh"
@@ -288,7 +313,9 @@ The bundle must export a `mount(container, config)` function on its global (e.g.
288
313
 
289
314
  ## Framework Usage (Custom Elements)
290
315
 
291
- When using a frontend framework (React, Vue, Angular), you can use custom HTML element tags instead of the script-tag method. Custom elements use raw IDs (`community-id`, `channel-id`) instead of the pre-encoded `data-widget-id`.
316
+ When using a frontend framework (React, Vue, Angular), you can use custom HTML element tags instead of the script-tag method. Custom elements use raw ObjectIds (`community-id`, `channel-id`) instead of the pre-encoded `data-widget-id` — the SDK handles the encoding internally. (Exception: `<rai-custom-widget>` uses `widget-id` with a base64-encoded value — see the [attributes table](#custom-element-attributes).)
317
+
318
+ All examples below use **Access Key Embed** — pass the short-lived token your server minted into `embed-token`. For [Public Embed](#user-identifier-attributes), replace `embed-token` with `data-*` identifier attributes.
292
319
 
293
320
  ### Plain HTML
294
321
 
@@ -299,7 +326,7 @@ When using a frontend framework (React, Vue, Angular), you can use custom HTML e
299
326
  <rai-store-widget
300
327
  community-id="YOUR_COMMUNITY_ID"
301
328
  theme="dark"
302
- data-email="user@example.com"
329
+ embed-token="eyJ..."
303
330
  api-url="YOUR_API_URL"
304
331
  widget-url="YOUR_WIDGET_URL"
305
332
  ></rai-store-widget>
@@ -309,7 +336,7 @@ When using a frontend framework (React, Vue, Angular), you can use custom HTML e
309
336
  community-id="YOUR_COMMUNITY_ID"
310
337
  channel-id="YOUR_CHANNEL_ID"
311
338
  theme="dark"
312
- data-email="user@example.com"
339
+ embed-token="eyJ..."
313
340
  api-url="YOUR_API_URL"
314
341
  widget-url="YOUR_WIDGET_URL"
315
342
  ></rai-channel-widget>
@@ -322,25 +349,25 @@ Types are included — no manual JSX declarations needed.
322
349
  ```tsx
323
350
  import '@returningai/widget-sdk'
324
351
 
325
- export function StoreEmbed({ email }: { email: string }) {
352
+ export function StoreEmbed({ embedToken }: { embedToken: string }) {
326
353
  return (
327
354
  <rai-store-widget
328
355
  community-id="YOUR_COMMUNITY_ID"
329
356
  theme="dark"
330
- data-email={email}
357
+ embed-token={embedToken}
331
358
  api-url="YOUR_API_URL"
332
359
  widget-url="YOUR_WIDGET_URL"
333
360
  />
334
361
  )
335
362
  }
336
363
 
337
- export function ChannelEmbed({ email }: { email: string }) {
364
+ export function ChannelEmbed({ embedToken }: { embedToken: string }) {
338
365
  return (
339
366
  <rai-channel-widget
340
367
  community-id="YOUR_COMMUNITY_ID"
341
368
  channel-id="YOUR_CHANNEL_ID"
342
369
  theme="dark"
343
- data-email={email}
370
+ embed-token={embedToken}
344
371
  api-url="YOUR_API_URL"
345
372
  widget-url="YOUR_WIDGET_URL"
346
373
  />
@@ -353,6 +380,7 @@ export function ChannelEmbed({ email }: { email: string }) {
353
380
  ```vue
354
381
  <script setup>
355
382
  import '@returningai/widget-sdk'
383
+ defineProps({ embedToken: String })
356
384
  </script>
357
385
 
358
386
  <template>
@@ -360,7 +388,7 @@ import '@returningai/widget-sdk'
360
388
  <rai-store-widget
361
389
  community-id="YOUR_COMMUNITY_ID"
362
390
  theme="dark"
363
- :data-email="user.email"
391
+ :embed-token="embedToken"
364
392
  api-url="YOUR_API_URL"
365
393
  widget-url="YOUR_WIDGET_URL"
366
394
  />
@@ -370,7 +398,7 @@ import '@returningai/widget-sdk'
370
398
  community-id="YOUR_COMMUNITY_ID"
371
399
  channel-id="YOUR_CHANNEL_ID"
372
400
  theme="dark"
373
- :data-email="user.email"
401
+ :embed-token="embedToken"
374
402
  api-url="YOUR_API_URL"
375
403
  widget-url="YOUR_WIDGET_URL"
376
404
  />
@@ -392,7 +420,7 @@ import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'
392
420
  <rai-store-widget
393
421
  community-id="YOUR_COMMUNITY_ID"
394
422
  theme="dark"
395
- [attr.data-email]="user.email"
423
+ [attr.embed-token]="embedToken"
396
424
  api-url="YOUR_API_URL"
397
425
  widget-url="YOUR_WIDGET_URL"
398
426
  ></rai-store-widget>
@@ -402,7 +430,7 @@ import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'
402
430
  community-id="YOUR_COMMUNITY_ID"
403
431
  channel-id="YOUR_CHANNEL_ID"
404
432
  theme="dark"
405
- [attr.data-email]="user.email"
433
+ [attr.embed-token]="embedToken"
406
434
  api-url="YOUR_API_URL"
407
435
  widget-url="YOUR_WIDGET_URL"
408
436
  ></rai-channel-widget>
@@ -431,7 +459,7 @@ Listen for widget lifecycle events:
431
459
  | `rai-authenticated` | `{}` | Auth succeeded, before widget mounts |
432
460
  | `rai-ready` | `{}` | `WIDGET_READY` received, loader hidden (iframe mode) |
433
461
  | `rai-mounted` | `{}` | Widget bundle mounted successfully (bundle mode) |
434
- | `rai-error` | `{ message }` | Auth failed after all retries |
462
+ | `rai-error` | `{ message, hint?, status? }` | Auth failed after all retries. `message` is the backend error text (e.g. `"Invalid or expired embed token"`), `hint` is the optional human-readable suggestion, `status` is the HTTP status code of the failing response. |
435
463
  | `rai-logout` | `{}` | Widget logged out |
436
464
  | `rai-height-change` | `{ height }` | iframe resized (after debounce) |
437
465
 
@@ -445,7 +473,7 @@ const widget = document.querySelector('rai-store-widget')
445
473
  widget.addEventListener('rai-authenticated', () => { /* auth succeeded */ })
446
474
  widget.addEventListener('rai-ready', () => { /* widget loaded and visible (iframe mode) */ })
447
475
  widget.addEventListener('rai-mounted', () => { /* widget mounted (bundle mode) */ })
448
- widget.addEventListener('rai-error', (e) => console.error(e.detail.message))
476
+ widget.addEventListener('rai-error', (e) => console.error(e.detail.status, e.detail.message, e.detail.hint))
449
477
  widget.addEventListener('rai-logout', () => { /* user logged out */ })
450
478
  widget.addEventListener('rai-height-change', (e) => console.log(e.detail.height))
451
479
  ```
@@ -1 +1 @@
1
- var RaiWidget=function(e){"use strict";var t=Object.defineProperty,r=(e,r,i)=>((e,r,i)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i)(e,"symbol"!=typeof r?r+"":r,i);function i(e){return`${e.storagePrefix}-${e.widgetId}-auth`}function a(e){return`${e.storagePrefix}-${e.widgetId}-error-settings`}function n(e){try{localStorage.removeItem(i(e))}catch{}}function o(e){return!e||Date.now()>=e-6e4}function s(e,t,r,a){t.accessToken=r.accessToken,t.refreshToken=r.refreshToken,t.tokenFamily=r.tokenFamily??null;const n=Date.now();t.accessTokenExpiry=n+1e3*r.accessTokenTTL,t.refreshTokenExpiry=n+1e3*r.refreshTokenTTL,function(e,t){try{const r={refreshToken:t.refreshToken,tokenFamily:t.tokenFamily,refreshTokenExpiry:t.refreshTokenExpiry};localStorage.setItem(i(e),JSON.stringify(r))}catch{}}(e,t),e.autoRefresh&&a&&a()}async function l(e,t,r){const i=crypto.randomUUID(),a=Date.now(),n=e.maxRetries??3,o=e.retryDelay??500;for(let l=0;l<=n;l++){l>0&&await new Promise(e=>setTimeout(e,o*(1<<l-1)));let c=!1;try{const n=await fetch(`${e.apiUrl}/${e.widgetId}/auth/serverless`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nonce:i,timestamp:a,widgetType:e.widgetType,userIdentifiers:e.userIdentifiers}),credentials:"include"});if(!n.ok){c=n.status>=400&&n.status<500;const e=await n.json().catch(()=>({error:"Authentication failed"}));throw new Error(e.error||`HTTP ${n.status}`)}const o=await n.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid authentication response");return s(e,t,o,r),t.isAuthenticated=!0,!0}catch{if(c||l===n)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function c(e,t,r){const i=e.maxRetries??3,a=e.retryDelay??500;for(let n=0;n<=i;n++){n>0&&await new Promise(e=>setTimeout(e,a*(1<<n-1)));let o=!1;try{const i=await fetch(e.authUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(!i.ok)throw o=i.status>=400&&i.status<500,new Error(`HTTP ${i.status}`);const a=await i.json();if(!a.token)throw new Error("Invalid proxy auth response");const n=a.expiresIn??300;return t.accessToken=a.token,t.refreshToken=null,t.tokenFamily=null,t.accessTokenExpiry=Date.now()+1e3*n,t.refreshTokenExpiry=null,t.isAuthenticated=!0,e.autoRefresh&&r&&r(),!0}catch{if(o||n===i)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function d(e,t,r,i){return t.isRefreshing?t.refreshPromise:!!t.refreshToken&&(t.isRefreshing=!0,t.refreshPromise=(async()=>{try{const a=await fetch(`${e.apiUrl}/${e.widgetId}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.refreshToken}`},body:JSON.stringify({widgetType:e.widgetType})});if(!a.ok){if(401===a.status||403===a.status)return u(t),n(e),l(e,t,r);const i=await a.json().catch(()=>({error:"Token refresh failed"}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid refresh response");return s(e,t,o,r),i&&i(),!0}catch{return u(t),n(e),l(e,t,r)}finally{t.isRefreshing=!1,t.refreshPromise=null}})(),t.refreshPromise)}async function h(e,t){const r=function(e){try{const t=localStorage.getItem(a(e));if(!t)return null;const r=JSON.parse(t);return r.cachedAt&&Date.now()-r.cachedAt<36e5?r:(localStorage.removeItem(a(e)),null)}catch{return null}}(e);if(r)return r.configured&&(t.errorSettings={errorMessage:r.errorMessage,modalColor:r.modalColor,backgroundImage:r.backgroundImage}),r.loadingAnimation&&(t.loadingAnimation=r.loadingAnimation),t.errorSettings;try{const r=await fetch(`${e.apiUrl}/${e.widgetId}/auth/error-settings?widgetType=${e.widgetType}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!r.ok)return null;const i=await r.json();return function(e,t){try{localStorage.setItem(a(e),JSON.stringify({...t,cachedAt:Date.now()}))}catch{}}(e,i),i.configured&&(t.errorSettings={errorMessage:i.errorMessage,modalColor:i.modalColor,backgroundImage:i.backgroundImage}),i.loadingAnimation&&(t.loadingAnimation=i.loadingAnimation),t.errorSettings}catch{return null}}function u(e){e.accessToken=null,e.refreshToken=null,e.tokenFamily=null,e.accessTokenExpiry=null,e.refreshTokenExpiry=null,e.isAuthenticated=!1,e.isRefreshing=!1,e.refreshPromise=null,e.refreshTimer&&(clearTimeout(e.refreshTimer),e.refreshTimer=null),e.syncTimer&&(clearInterval(e.syncTimer),e.syncTimer=null)}function m(e,t,r){var i;if(t.accessToken)try{null==(i=r.contentWindow)||i.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{widgetId:e.widgetId,token:t.accessToken,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}}function g(e,t,r,i,a,n,s,h){const u=function(e,t){let r=null;return{call(i){r&&clearTimeout(r),r=setTimeout(()=>{e(i),r=null},t)},cancel(){r&&(clearTimeout(r),r=null)}}}(e=>{i.style.height=`${e}px`,null==h||h("rai-height-change",{height:e})},e.heightDebounce??100),m=async r=>{var m;if(r.origin!==e.widgetDomain)return;if(!r.data||"string"!=typeof r.data.type)return;const{type:g,containerId:f,widgetId:p,payload:w}=r.data;switch(g){case"RETURNINGAI_WIDGET_REQUEST_TOKEN":try{const r=await async function(e,t,r){if(t.accessToken&&!o(t.accessTokenExpiry))return t.accessToken;if(e.authUrl){if(await c(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}if(await d(e,t,r)&&t.accessToken)return t.accessToken;if(await l(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}(e,t,a);null==(m=i.contentWindow)||m.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{token:r,widgetId:e.widgetId,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}break;case"WIDGET_HEIGHT_UPDATE":{const e=Number(null==w?void 0:w.height);Number.isFinite(e)&&e>0&&u.call(e);break}case"WIDGET_READY":if(void 0!==p&&p!==e.widgetId)break;if(void 0!==f&&f!==e.container)break;i.classList.add("loaded"),s&&s(),null==h||h("rai-ready");break;case"WIDGET_ERROR":s&&s();break;case"WIDGET_LOGOUT":n&&await n()}};return window.addEventListener("message",m),()=>{window.removeEventListener("message",m),u.cancel()}}const f=new Set(["community-id","channel-id","widget-id","widget-type","theme","container","width","height","api-url","widget-url","auto-refresh","debug","storage-prefix","max-retries","retry-delay","height-debounce","locale","custom-data","retry-label","auth-url","bundle-url","embed-token","v2-api-url","domain-key"]),p={store:"RaiStoreWidget",channel:"RaiChannelWidget",social:"RaiSocialWidget",milestone:"RaiMilestoneWidget","currency-view":"RaiCurrencyWidget","referral-conditions":"RaiReferralWidget",custom:"RaiCustomWidget"},w={"RAI-STORE-WIDGET":"store","RAI-CHANNEL-WIDGET":"channel","RAI-MILESTONE-WIDGET":"milestone","RAI-SOCIAL-WIDGET":"social","RAI-CURRENCY-WIDGET":"currency-view","RAI-REFERRAL-WIDGET":"referral-conditions","RAI-CUSTOM-WIDGET":"custom","RAI-WIDGET":"store"};class y extends HTMLElement{constructor(){super(),r(this,"shadow"),r(this,"config"),r(this,"state",{accessToken:null,refreshToken:null,tokenFamily:null,accessTokenExpiry:null,refreshTokenExpiry:null,refreshTimer:null,syncTimer:null,iframe:null,isAuthenticated:!1,isRefreshing:!1,refreshPromise:null,errorSettings:null,loadingAnimation:null}),r(this,"loaderEl",null),r(this,"errorEl",null),r(this,"msgEl",null),r(this,"cleanupListener"),r(this,"intersectionObserver"),r(this,"themeObserver"),this.shadow=this.attachShadow({mode:"closed"})}connectedCallback(){this.config=function(e,t){const r=t=>e.getAttribute(t)??e.getAttribute(`data-${t}`)??"",i=(e,t)=>{const i=parseInt(r(e),10);return Number.isFinite(i)&&i>=0?i:t},a=!!r("community-id"),n=r("community-id")||r("widget-id")||t||"";if(n&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(n))throw new Error(`[rai-widget] Invalid community-id: "${n}"`);const o=r("channel-id")||void 0;if(o&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(o))throw new Error(`[rai-widget] Invalid channel-id: "${o}"`);const s=r("widget-type")||w[e.tagName]||"store";let l;l=a?"store"===s?n:"channel"===s?o?btoa(o):n:n?btoa(n):n:n;let c,d=r("widget-url")||"https://widget.returningai.com";d.endsWith("store-widget")&&(d=`${d}/${n}/open-widget`);try{c=new URL(d).origin}catch{c=d}if(d.includes("store-widget")){const e=new URL(d);e.searchParams.set("color",r("theme")||"light"),d=e.toString()}const h=r("container")||r("data-container")||`returning-ai-widget-${l}`,u={};Array.from(e.attributes).forEach(e=>{const t=e.name.toLowerCase();if(!t.startsWith("data-"))return;const r=t.slice(5);f.has(r)||(u[t]=e.value)});const m=(()=>{const e=r("custom-data");if(e)try{return JSON.parse(e)}catch{return}})();return{communityId:n,channelId:o,widgetId:l,widgetType:s,theme:r("theme")||"light",container:h,width:r("width")||"100%",height:r("height")||"600px",apiUrl:r("api-url")||"https://sgtr-eks-widgets.genesiv.org",widgetUrl:d,widgetDomain:c,autoRefresh:"false"!==r("auto-refresh"),debug:"true"===r("debug"),storagePrefix:r("storage-prefix")||"returning-ai-widget",userIdentifiers:u,maxRetries:i("max-retries",3),retryDelay:i("retry-delay",500),heightDebounce:i("height-debounce",100),locale:r("locale")||void 0,customData:m,authUrl:r("auth-url")||void 0,bundleUrl:r("bundle-url")||void 0,embedToken:r("embed-token")||void 0,v2ApiUrl:r("v2-api-url")||void 0,domainKey:r("domain-key")||void 0}}(this,void 0);const e=document.createElement("style");e.textContent=':host{display:block;position:relative;width:100%;height:100%}.rai-loader{position:absolute;top:0;left:0;display:flex;align-items:center;justify-content:center;width:100%;height:100%;background:var(--rai-loader-bg, #ffffff);border-radius:8px;z-index:10;transition:opacity .3s ease-out}.rai-loader.fade-out{opacity:0;pointer-events:none}.rai-error{display:none;position:absolute;top:0;left:0;width:100%;height:100%;align-items:center;justify-content:center;flex-direction:column;gap:12px;background:var(--rai-error-bg, #1a1a1a);border-radius:8px;padding:24px;box-sizing:border-box;text-align:center;color:var(--rai-error-text, #9ca3af);font-family:system-ui,-apple-system,sans-serif;z-index:10}.rai-error.visible{display:flex}iframe{display:block;border:none;opacity:0;transition:opacity .3s ease-in}iframe.loaded{opacity:1}.rai-lottie-loader{width:100px;height:100px}.rai-lottie-loader svg{width:100%!important;height:100%!important}.rai-lottie-spinner{width:32px;height:32px;margin:34px auto;border:3px solid var(--rai-text4, #6b7280);border-top-color:var(--rai-accent, #000000);border-radius:50%;animation:rai-spin .7s linear infinite}@keyframes rai-spin{to{transform:rotate(360deg)}}.rai-sdk-loader{position:relative;width:75px;height:100px}.rai-sdk-loader__bar{position:absolute;bottom:0;width:10px;height:50%;background:var(--rai-accent, #000000);transform-origin:center bottom;box-shadow:1px 1px #0003}.rai-sdk-loader__bar:nth-child(1){left:0;transform:scaleY(.2);animation:rai-sdk-barUp1 4s infinite}.rai-sdk-loader__bar:nth-child(2){left:15px;transform:scaleY(.4);animation:rai-sdk-barUp2 4s infinite}.rai-sdk-loader__bar:nth-child(3){left:30px;transform:scaleY(.6);animation:rai-sdk-barUp3 4s infinite}.rai-sdk-loader__bar:nth-child(4){left:45px;transform:scaleY(.8);animation:rai-sdk-barUp4 4s infinite}.rai-sdk-loader__bar:nth-child(5){left:60px;transform:scale(1);animation:rai-sdk-barUp5 4s infinite}.rai-sdk-loader__ball{position:absolute;bottom:10px;left:0;width:10px;height:10px;background:var(--rai-accent, #000000);border-radius:50%;animation:rai-sdk-ball 4s infinite}@keyframes rai-sdk-ball{0%{transform:translate(0)}5%{transform:translate(8px,-14px)}10%{transform:translate(15px,-10px)}17%{transform:translate(23px,-24px)}20%{transform:translate(30px,-20px)}27%{transform:translate(38px,-34px)}30%{transform:translate(45px,-30px)}37%{transform:translate(53px,-44px)}40%{transform:translate(60px,-40px)}50%{transform:translate(60px)}57%{transform:translate(53px,-14px)}60%{transform:translate(45px,-10px)}67%{transform:translate(37px,-24px)}70%{transform:translate(30px,-20px)}77%{transform:translate(22px,-34px)}80%{transform:translate(15px,-30px)}87%{transform:translate(7px,-44px)}90%{transform:translateY(-40px)}to{transform:translate(0)}}@keyframes rai-sdk-barUp1{0%{transform:scaleY(.2)}40%{transform:scaleY(.2)}50%{transform:scale(1)}90%{transform:scale(1)}to{transform:scaleY(.2)}}@keyframes rai-sdk-barUp2{0%{transform:scaleY(.4)}40%{transform:scaleY(.4)}50%{transform:scaleY(.8)}90%{transform:scaleY(.8)}to{transform:scaleY(.4)}}@keyframes rai-sdk-barUp3{0%{transform:scaleY(.6)}to{transform:scaleY(.6)}}@keyframes rai-sdk-barUp4{0%{transform:scaleY(.8)}40%{transform:scaleY(.8)}50%{transform:scaleY(.4)}90%{transform:scaleY(.4)}to{transform:scaleY(.8)}}@keyframes rai-sdk-barUp5{0%{transform:scale(1)}40%{transform:scale(1)}50%{transform:scaleY(.2)}90%{transform:scaleY(.2)}to{transform:scale(1)}}#loading-square{width:75px;aspect-ratio:1;display:flex;color:var(--rai-accent, #000000);background:linear-gradient(currentColor 0 0) right / 51% 100%,linear-gradient(currentColor 0 0) bottom / 100% 51%;background-repeat:no-repeat;animation:l16-0 2s infinite linear .25s}#loading-square>div{width:50%;height:50%;background:currentColor;animation:l16-1 .5s infinite linear}@keyframes l16-0{0%,12.49%{transform:rotate(0)}12.5%,37.49%{transform:rotate(90deg)}37.5%,62.49%{transform:rotate(180deg)}62.5%,87.49%{transform:rotate(270deg)}87.5%,to{transform:rotate(360deg)}}@keyframes l16-1{0%{transform:perspective(80px) rotate3d(-1,-1,0,0)}80%,to{transform:perspective(80px) rotate3d(-1,-1,0,-180deg)}}#loading-circle{width:75px;aspect-ratio:1;display:grid;grid:50%/50%;color:var(--rai-accent, #000000);border-radius:50%;--_g: no-repeat linear-gradient(currentColor 0 0);background:var(--_g),var(--_g),var(--_g);background-size:50.1% 50.1%;animation:l9-0 1.5s infinite steps(1) alternate,l9-0-0 3s infinite steps(1) alternate}#loading-circle>div{background:var(--rai-text4, #6b7280);border-top-left-radius:100px;transform:perspective(150px) rotateY(0) rotateX(0);transform-origin:bottom right;animation:l9-1 1.5s infinite linear alternate}@keyframes l9-0{0%{background-position:0 100%,100% 100%,100% 0}33%{background-position:100% 100%,100% 100%,100% 0}66%{background-position:100% 0,100% 0,100% 0}}@keyframes l9-0-0{0%{transform:scaleX(1) rotate(0)}50%{transform:scaleX(-1) rotate(-90deg)}}@keyframes l9-1{16.5%{transform:perspective(150px) rotateX(-90deg) rotateY(0) rotateX(0);filter:grayscale(.8)}33%{transform:perspective(150px) rotateX(-180deg) rotateY(0) rotateX(0)}66%{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(0)}to{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(-180deg);filter:grayscale(.8)}}.rai-custom-error{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10}.tiptap strong.tw-font-bold,.tiptap b.tw-font-bold{font-weight:700}.tiptap em.tw-font-italic,.tiptap i.tw-font-italic{font-style:italic}.tiptap a.tiptap-rich-text-link{color:#3b82f6;text-decoration:underline;position:relative;display:inline-block;width:fit-content}.tiptap a.tiptap-rich-text-link:hover{color:#3b82f6cc;text-decoration:none}.tiptap a.tiptap-rich-text-link:not([title=""]):before{content:attr(title);position:absolute;top:-2rem;left:50%;transform:translate(-50%);white-space:nowrap;border-radius:.25rem;background-color:#000;padding:.25rem .5rem;color:#fff;opacity:0;transition:opacity .2s;pointer-events:none}.tiptap a.tiptap-rich-text-link:not([title=""]):hover:before{opacity:1}.tiptap p[style*="text-align: left"]{text-align:left}.tiptap p[style*="text-align: center"]{text-align:center}.tiptap p[style*="text-align: right"]{text-align:right}.tiptap p[style*="text-align: justify"]{text-align:justify}.tiptap u{text-decoration:underline}.tiptap.ProseMirror{background-color:transparent;height:fit-content!important;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0;padding:0;width:100%;overflow-y:auto}.tiptap{line-height:1.6;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}.tiptap p{margin:.5em 0}.tiptap p:first-child{margin-top:0}.tiptap p:last-child{margin-bottom:0}.tiptap img{max-width:100%;height:auto;display:block}.tiptap p[style*="text-align: left"] img{margin-left:0;margin-right:auto}.tiptap p[style*="text-align: center"] img{margin-left:auto;margin-right:auto}.tiptap p[style*="text-align: right"] img{margin-left:auto;margin-right:0}.rai-retry-btn{padding:8px 20px;border:none;border-radius:6px;background:var(--rai-accent, #000000);color:var(--rai-error-bg, #ffffff);font-size:14px;font-family:system-ui,-apple-system,sans-serif;cursor:pointer}.rai-retry-btn:hover{opacity:.85}',this.shadow.appendChild(e);const t=this.config.theme,r="dark"===t?"#ffffff":"#000000",i="dark"===t?"#9ca3af":"#6b7280",a="dark"===t?"#1a1a1a":"#ffffff";this.style.width=this.config.width,this.style.height=this.config.height,this.style.setProperty("--rai-accent",r),this.style.setProperty("--rai-text4",i),this.style.setProperty("--rai-loader-bg",a),this.style.setProperty("--rai-error-bg",a),this.renderShell(),this.hasAttribute("eager")?this.init():(this.intersectionObserver=new IntersectionObserver(e=>{e[0].isIntersecting&&(this.intersectionObserver.disconnect(),this.intersectionObserver=void 0,this.init())}),this.intersectionObserver.observe(this))}disconnectedCallback(){var e,t;null==(e=this.intersectionObserver)||e.disconnect(),null==(t=this.themeObserver)||t.disconnect(),this.cleanupListener&&this.cleanupListener(),u(this.state)}emit(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t??{}}))}renderShell(){this.loaderEl=document.createElement("div"),this.loaderEl.className="rai-loader",this.shadow.appendChild(this.loaderEl),this.fetchAndRenderLoader(),this.errorEl=document.createElement("div"),this.errorEl.className="rai-error",this.msgEl=document.createElement("span"),this.msgEl.className="rai-error-msg",this.msgEl.textContent="Authentication failed. Please try again later.",this.errorEl.appendChild(this.msgEl);const e=this.getAttribute("retry-label")||this.getAttribute("data-retry-label")||"Retry",t=document.createElement("button");t.className="rai-retry-btn",t.textContent=e,t.addEventListener("click",()=>this.reload()),this.errorEl.appendChild(t),this.shadow.appendChild(this.errorEl)}async fetchAndRenderLoader(){var e;null==(e=this.loaderEl)||e.appendChild(this.createDefaultLoader());try{await h(this.config,this.state)}catch{}if(!this.loaderEl)return;this.loaderEl.innerHTML="";const t=this.state.loadingAnimation,r="dark"===this.config.theme?"dark":"light";if("custom"===(null==t?void 0:t.type)&&t.custom){const e=t.custom[r]||t.custom.light||t.custom.dark;if(e){if("lottie"===e.type&&e.lottieData)return void this.renderLottieLoader(e.lottieData);if("custom"===e.type&&e.html){const t=document.createElement("div");return t.innerHTML=e.html,void this.loaderEl.appendChild(t)}}}"preset"===(null==t?void 0:t.type)&&t.preset?this.loaderEl.appendChild(this.createPresetLoader(t.preset)):this.loaderEl.appendChild(this.createDefaultLoader())}renderLottieLoader(e){const t=document.createElement("div");t.className="rai-lottie-loader",this.loaderEl.appendChild(t);const r=window;if(void 0!==r.lottie)r.lottie.loadAnimation({container:t,renderer:"svg",loop:!0,autoplay:!0,animationData:e});else{const r=document.createElement("script");r.src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js",r.onload=()=>{window.lottie.loadAnimation({container:t,renderer:"svg",loop:!0,autoplay:!0,animationData:e})},document.head.appendChild(r)}}createDefaultLoader(){const e=document.createElement("div");e.className="rai-sdk-loader";for(let r=0;r<5;r++){const t=document.createElement("div");t.className="rai-sdk-loader__bar",e.appendChild(t)}const t=document.createElement("div");return t.className="rai-sdk-loader__ball",e.appendChild(t),e}createPresetLoader(e){if("square"===e){const e=document.createElement("div");e.id="loading-square";const t=document.createElement("div");return e.appendChild(t),e}if("circle"===e){const e=document.createElement("div");e.id="loading-circle";const t=document.createElement("div");return e.appendChild(t),e}return this.createDefaultLoader()}hideLoader(){this.loaderEl&&(this.loaderEl.classList.add("fade-out"),setTimeout(()=>{var e;return null==(e=this.loaderEl)?void 0:e.remove()},300),this.loaderEl=null)}showError(){this.hideLoader();const e=this.state.errorSettings;(null==e?void 0:e.errorMessage)?this.renderCustomError(e):this.errorEl&&this.errorEl.classList.add("visible"),this.emit("rai-error",{message:(null==e?void 0:e.errorMessage)??"Authentication failed"})}renderCustomError(e){var t,r;null==(t=this.errorEl)||t.remove(),this.errorEl=null;const i=(null==(r=e.backgroundImage)?void 0:r.trim())?`background-image: url('${e.backgroundImage}'); background-size: cover; background-position: center; background-repeat: no-repeat;`:"",a=document.createElement("div");a.className="rai-custom-error",a.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n overflow: auto;\n width: 100%;\n height: 100%;\n ${i}\n `;const n=document.createElement("div");n.className="rai-rich-text",n.style.cssText=`\n min-width: 50%;\n min-height: 50%;\n margin: 0 auto;\n padding: 20px;\n width: auto;\n height: auto;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 6px;\n background-color: ${e.modalColor||"transparent"};\n `;const o=document.createElement("div");o.className="tiptap ProseMirror",o.innerHTML=e.errorMessage||"",n.appendChild(o),a.appendChild(n),this.shadow.appendChild(a)}async init(){if(!this.config.communityId)return void this.showError();if(await h(this.config,this.state),this.config.embedToken){if(!(await async function(e){try{const t=e.v2ApiUrl||e.apiUrl;return(await fetch(`${t}/v2/api/widget-access-keys/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:e.embedToken})})).ok}catch{return!1}}(this.config)))return void this.showError()}const e=()=>{this.config.bundleUrl?this.mountWidget():this.createIframe()};if(this.config.authUrl){return void(await c(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError())}if(function(e,t){try{const r=localStorage.getItem(i(e));if(!r)return!1;const a=JSON.parse(r);return a.refreshToken&&!o(a.refreshTokenExpiry)?(t.refreshToken=a.refreshToken,t.tokenFamily=a.tokenFamily,t.refreshTokenExpiry=a.refreshTokenExpiry,!0):(n(e),!1)}catch{return!1}}(this.config,this.state)){return await d(this.config,this.state,()=>this.scheduleRefresh())?(this.state.isAuthenticated=!0,this.emit("rai-authenticated"),void e()):void this.showError()}await l(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError()}createIframe(){const e=document.createElement("iframe");e.src=this.buildWidgetUrl(this.config),e.allow="clipboard-write",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),e.frameBorder="0",e.scrolling="no",e.style.width=this.config.width,e.style.height=this.config.height,e.style.border="none",e.style.display="block",e.onload=()=>{m(this.config,this.state,e),this.schedulePeriodicSync(e)},e.onerror=()=>{this.showError()},this.state.iframe=e,this.shadow.appendChild(e),this.cleanupListener=g(this.config,this.state,this.shadow,e,()=>this.scheduleRefresh(),()=>this.logoutAndClear(),()=>this.hideLoader(),(e,t)=>this.emit(e,t))}async mountWidget(){try{const t=window;!t.DomainKey&&this.config.domainKey&&(t.DomainKey="PROD"===this.config.domainKey?"GEN":this.config.domainKey),window.__IS_WIDGET__=!0,window.guest_token=this.state.accessToken,await(e=this.config.bundleUrl,new Promise((t,r)=>{const i=document.createElement("script");i.src=e,i.onload=()=>t(),i.onerror=()=>r(new Error(`Failed to load ${e}`)),document.head.appendChild(i)}));const r=p[this.config.widgetType],i=window[r];if(!(null==i?void 0:i.mount))throw new Error(`window.${r}.mount not found after loading bundle`);const a=document.createElement("div");if(a.style.cssText="position: relative; width: 100%; height: 100%;",this.appendChild(a),!this.shadow.querySelector("slot")){const e=document.createElement("slot");this.shadow.appendChild(e)}this.loaderEl&&(this.loaderEl.remove(),this.loaderEl=null),i.mount(a,{widgetType:this.config.widgetType,communityId:this.config.communityId,channelId:this.config.channelId,widgetId:this.config.communityId,apiUrl:this.config.apiUrl,token:this.state.accessToken,basePath:"/",isPreview:!1,isOpenWidget:!0,defaultColorSchema:"dark"===this.config.theme?"dark":"light"}),this.emit("rai-mounted")}catch(t){console.error("[rai-widget] Bundle mount failed:",t),this.showError()}var e}scheduleRefresh(){if(this.state.refreshTimer&&clearTimeout(this.state.refreshTimer),!this.state.accessTokenExpiry)return;const e=this.state.accessTokenExpiry-Date.now()-6e4,t=()=>{this.state.iframe&&m(this.config,this.state,this.state.iframe),this.config.bundleUrl&&this.state.accessToken&&(window.guest_token=this.state.accessToken)},r=async()=>{if(this.config.authUrl){await c(this.config,this.state,()=>this.scheduleRefresh())&&t()}else await d(this.config,this.state,()=>this.scheduleRefresh(),t)};e>0?this.state.refreshTimer=setTimeout(r,e):r()}schedulePeriodicSync(e){this.state.syncTimer&&clearInterval(this.state.syncTimer),this.state.syncTimer=setInterval(()=>{this.state.accessToken&&m(this.config,this.state,e)},12e4)}async logoutAndClear(){await async function(e,t){if(t.accessToken)try{await fetch(`${e.apiUrl}/${e.widgetId}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({refreshToken:t.refreshToken})})}catch{}u(t),n(e)}(this.config,this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),this.emit("rai-logout")}async reload(){u(this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),await this.init()}async logoutPublic(){await this.logoutAndClear()}isAuthenticated(){return this.state.isAuthenticated&&null!==this.state.accessToken}getTokenInfo(){return{hasAccessToken:!!this.state.accessToken,hasRefreshToken:!!this.state.refreshToken,accessTokenExpiry:this.state.accessTokenExpiry?new Date(this.state.accessTokenExpiry):null,refreshTokenExpiry:this.state.refreshTokenExpiry?new Date(this.state.refreshTokenExpiry):null,isAccessTokenValid:!!this.state.accessToken&&!o(this.state.accessTokenExpiry),isRefreshTokenValid:!!this.state.refreshToken&&!o(this.state.refreshTokenExpiry)}}}class b extends y{buildWidgetUrl(e){const t=new URL(e.widgetUrl);return t.searchParams.set("color",e.theme),t.searchParams.set("containerId",e.container),t.searchParams.set("connectType","simple"),t.searchParams.set("mode","private"),e.locale&&t.searchParams.set("locale",e.locale),t.toString()}}class k extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("channel-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class T extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("milestone-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class v extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("social-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class x extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("currency-overview-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class E extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("referral-conditions-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class I extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("custom-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}console.log("[rai-widget] v1.2.16");const U=[["rai-store-widget",b],["rai-channel-widget",k],["rai-milestone-widget",T],["rai-social-widget",v],["rai-currency-widget",x],["rai-referral-widget",E],["rai-custom-widget",I],["rai-widget",class extends b{}]];for(const[$,D]of U)customElements.get($)||customElements.define($,D);const A={store:b,channel:k,milestone:T,social:v,"currency-view":x,"referral-conditions":E,custom:I},R=U.map(([e])=>e).join(", ");function C(){var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return;const i=r.getAttribute("data-community-id")||r.getAttribute("data-widget-id");if(!i)return;const a=r.getAttribute("data-container")||`returning-ai-widget-${i}`,n=document.getElementById(a);if(!n)return;"static"===getComputedStyle(n).position&&(n.style.position="relative");const o=r.getAttribute("data-widget-type")??"store",s=new(A[o]??b);Array.from(r.attributes).forEach(e=>{s.setAttribute(e.name,e.value)}),n.appendChild(s)}function S(){const e=(()=>{var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return null;const i=r.getAttribute("data-container")||`returning-ai-widget-${r.getAttribute("data-community-id")||r.getAttribute("data-widget-id")}`;return document.getElementById(i)})(),t=null==e?void 0:e.querySelector(R);window.ReturningAIWidget={version:"1.2.16",reload:()=>(null==t?void 0:t.reload())??Promise.resolve(),logout:()=>(null==t?void 0:t.logoutPublic())??Promise.resolve(),isAuthenticated:()=>(null==t?void 0:t.isAuthenticated())??!1,getTokenInfo:()=>(null==t?void 0:t.getTokenInfo())??{}}}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",C):C(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",S):S(),e.ChannelWidget=k,e.CurrencyWidget=x,e.CustomWidget=I,e.MilestoneWidget=T,e.ReferralWidget=E,e.SocialWidget=v,e.StoreWidget=b,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
1
+ var RaiWidget=function(e){"use strict";var t=Object.defineProperty,r=(e,r,i)=>((e,r,i)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i)(e,"symbol"!=typeof r?r+"":r,i);function i(e){return`${e.storagePrefix}-${e.widgetId}-auth`}function a(e){return`${e.storagePrefix}-${e.widgetId}-error-settings`}function n(e){try{localStorage.removeItem(i(e))}catch{}}function o(e){try{const t=localStorage.getItem(a(e));if(!t)return null;const r=JSON.parse(t);return r.cachedAt&&Date.now()-r.cachedAt<36e5?r:(localStorage.removeItem(a(e)),null)}catch{return null}}function s(e){return!e||Date.now()>=e-6e4}function l(e,t,r,a){t.accessToken=r.accessToken,t.refreshToken=r.refreshToken,t.tokenFamily=r.tokenFamily??null;const n=Date.now();t.accessTokenExpiry=n+1e3*r.accessTokenTTL,t.refreshTokenExpiry=n+1e3*r.refreshTokenTTL,function(e,t){try{const r={refreshToken:t.refreshToken,tokenFamily:t.tokenFamily,refreshTokenExpiry:t.refreshTokenExpiry};localStorage.setItem(i(e),JSON.stringify(r))}catch{}}(e,t),e.autoRefresh&&a&&a()}async function c(e,t,r){const i=crypto.randomUUID(),a=Date.now(),n=e.maxRetries??3,o=e.retryDelay??500;for(let s=0;s<=n;s++){s>0&&await new Promise(e=>setTimeout(e,o*(1<<s-1)));let c=!1;try{const n={nonce:i,timestamp:a,widgetType:e.widgetType};e.embedToken&&(n.embedToken=e.embedToken),e.userIdentifiers&&Object.keys(e.userIdentifiers).length>0&&(n.userIdentifiers=e.userIdentifiers);const o=await fetch(`${e.apiUrl}/${e.widgetId}/auth/serverless`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"include"});if(!o.ok){c=o.status>=400&&o.status<500;const e=await o.json().catch(()=>({error:"Authentication failed"}));throw c&&(t.lastAuthError={status:o.status,error:null==e?void 0:e.error,hint:null==e?void 0:e.hint},console.error(`[rai-widget] /auth/serverless ${o.status}:`,(null==e?void 0:e.error)||"Authentication failed",(null==e?void 0:e.hint)?`— ${e.hint}`:"")),new Error((null==e?void 0:e.error)||`HTTP ${o.status}`)}t.lastAuthError=null;const s=await o.json();if(!s.accessToken||!s.refreshToken)throw new Error("Invalid authentication response");return l(e,t,s,r),t.isAuthenticated=!0,!0}catch{if(c||s===n)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function d(e,t,r){const i=e.maxRetries??3,a=e.retryDelay??500;for(let n=0;n<=i;n++){n>0&&await new Promise(e=>setTimeout(e,a*(1<<n-1)));let o=!1;try{const i=await fetch(e.authUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(!i.ok)throw o=i.status>=400&&i.status<500,new Error(`HTTP ${i.status}`);const a=await i.json();if(!a.token)throw new Error("Invalid proxy auth response");const n=a.expiresIn??300;return t.accessToken=a.token,t.refreshToken=null,t.tokenFamily=null,t.accessTokenExpiry=Date.now()+1e3*n,t.refreshTokenExpiry=null,t.isAuthenticated=!0,e.autoRefresh&&r&&r(),!0}catch{if(o||n===i)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function h(e,t,r,i){return t.isRefreshing?t.refreshPromise:!!t.refreshToken&&(t.isRefreshing=!0,t.refreshPromise=(async()=>{try{const a=await fetch(`${e.apiUrl}/${e.widgetId}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.refreshToken}`},body:JSON.stringify({widgetType:e.widgetType})});if(!a.ok){if(401===a.status||403===a.status)return g(t),n(e),c(e,t,r);const i=await a.json().catch(()=>({error:"Token refresh failed"}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid refresh response");return l(e,t,o,r),i&&i(),!0}catch{return g(t),n(e),c(e,t,r)}finally{t.isRefreshing=!1,t.refreshPromise=null}})(),t.refreshPromise)}const u=new Map;function m(e,t){t.configured&&(e.errorSettings={errorMessage:t.errorMessage,modalColor:t.modalColor,backgroundImage:t.backgroundImage}),t.loadingAnimation&&(e.loadingAnimation=t.loadingAnimation),t.themePalette&&(e.themePalette=t.themePalette),"string"==typeof t.font&&t.font&&(e.font=t.font),"light"!==t.defaultColorSchema&&"dark"!==t.defaultColorSchema||(e.defaultColorSchema=t.defaultColorSchema)}async function f(e,t,r={}){if(!r.skipCache){const r=o(e);if(r)return m(t,r),t.errorSettings}const i=`${e.apiUrl}/${e.widgetId}/auth/error-settings?widgetType=${e.widgetType}`;let n=u.get(i);n||(n=(async()=>{try{const t=await fetch(i,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)return null;const r=await t.json();return function(e,t){try{localStorage.setItem(a(e),JSON.stringify({...t,cachedAt:Date.now()}))}catch{}}(e,r),r}catch{return null}finally{u.delete(i)}})(),u.set(i,n));const s=await n;return s?(m(t,s),t.errorSettings):null}function g(e){e.accessToken=null,e.refreshToken=null,e.tokenFamily=null,e.accessTokenExpiry=null,e.refreshTokenExpiry=null,e.isAuthenticated=!1,e.isRefreshing=!1,e.refreshPromise=null,e.lastAuthError=null,e.refreshTimer&&(clearTimeout(e.refreshTimer),e.refreshTimer=null),e.syncTimer&&(clearInterval(e.syncTimer),e.syncTimer=null)}function p(e,t,r){var i;if(t.accessToken)try{null==(i=r.contentWindow)||i.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{widgetId:e.widgetId,token:t.accessToken,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}}function y(e,t,r,i,a,n,o,l){const u=function(e,t){let r=null;return{call(i){r&&clearTimeout(r),r=setTimeout(()=>{e(i),r=null},t)},cancel(){r&&(clearTimeout(r),r=null)}}}(e=>{i.style.height=`${e}px`,null==l||l("rai-height-change",{height:e})},e.heightDebounce??100),m=async r=>{var m;if(r.origin!==e.widgetDomain)return;if(!r.data||"string"!=typeof r.data.type)return;const{type:f,containerId:g,widgetId:p,payload:y}=r.data;switch(f){case"RETURNINGAI_WIDGET_REQUEST_TOKEN":try{const r=await async function(e,t,r){if(t.accessToken&&!s(t.accessTokenExpiry))return t.accessToken;if(e.authUrl){if(await d(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}if(await h(e,t,r)&&t.accessToken)return t.accessToken;if(await c(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}(e,t,a);null==(m=i.contentWindow)||m.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{token:r,widgetId:e.widgetId,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}break;case"WIDGET_HEIGHT_UPDATE":{const e=Number(null==y?void 0:y.height);Number.isFinite(e)&&e>0&&u.call(e);break}case"WIDGET_READY":if(void 0!==p&&p!==e.widgetId)break;if(void 0!==g&&g!==e.container)break;i.classList.add("loaded"),o&&o(),null==l||l("rai-ready");break;case"WIDGET_ERROR":o&&o();break;case"WIDGET_LOGOUT":n&&await n()}};return window.addEventListener("message",m),()=>{window.removeEventListener("message",m),u.cancel()}}const w=new Set(["community-id","channel-id","widget-id","widget-type","theme","container","width","height","api-url","widget-url","auto-refresh","debug","storage-prefix","max-retries","retry-delay","height-debounce","locale","custom-data","retry-label","auth-url","bundle-url","embed-token","v2-api-url","domain-key","loading-text","bg","text","accent","font"]),b={store:"RaiStoreWidget",channel:"RaiChannelWidget",social:"RaiSocialWidget",milestone:"RaiMilestoneWidget","currency-view":"RaiCurrencyWidget","referral-conditions":"RaiReferralWidget",custom:"RaiCustomWidget"},k={"RAI-STORE-WIDGET":"store","RAI-CHANNEL-WIDGET":"channel","RAI-MILESTONE-WIDGET":"milestone","RAI-SOCIAL-WIDGET":"social","RAI-CURRENCY-WIDGET":"currency-view","RAI-REFERRAL-WIDGET":"referral-conditions","RAI-CUSTOM-WIDGET":"custom","RAI-WIDGET":"store"};const v=new Set;const x=["script","iframe","object","embed"],T=["src","href","xlink:href"];class E extends HTMLElement{constructor(){super(),r(this,"shadow"),r(this,"config"),r(this,"state",{accessToken:null,refreshToken:null,tokenFamily:null,accessTokenExpiry:null,refreshTokenExpiry:null,refreshTimer:null,syncTimer:null,iframe:null,isAuthenticated:!1,isRefreshing:!1,refreshPromise:null,errorSettings:null,loadingAnimation:null,themePalette:null,font:null,defaultColorSchema:null,lastAuthError:null}),r(this,"loaderEl",null),r(this,"errorEl",null),r(this,"msgEl",null),r(this,"cleanupListener"),r(this,"intersectionObserver"),r(this,"themeObserver"),this.shadow=this.attachShadow({mode:"closed"})}connectedCallback(){this.config=function(e,t){const r=t=>e.getAttribute(t)??e.getAttribute(`data-${t}`)??"",i=(e,t)=>{const i=parseInt(r(e),10);return Number.isFinite(i)&&i>=0?i:t},a=!!r("community-id"),n=r("community-id")||r("widget-id")||t||"";if(n&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(n))throw new Error(`[rai-widget] Invalid community-id: "${n}"`);const o=r("channel-id")||void 0;if(o&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(o))throw new Error(`[rai-widget] Invalid channel-id: "${o}"`);const s=r("widget-type")||k[e.tagName]||"store";let l;l=a?"store"===s?n:"channel"===s?o?btoa(o):n:n?btoa(n):n:n;let c,d=r("widget-url")||"https://widget.returningai.com";d.endsWith("store-widget")&&(d=`${d}/${n}/open-widget`);try{c=new URL(d).origin}catch{c=d}if(d.includes("store-widget")){const e=new URL(d);e.searchParams.set("color",r("theme")||"light"),d=e.toString()}const h=r("container")||r("data-container")||`returning-ai-widget-${l}`,u={};Array.from(e.attributes).forEach(e=>{const t=e.name.toLowerCase();if(!t.startsWith("data-"))return;const r=t.slice(5);w.has(r)||(u[t]=e.value)});const m=(()=>{const e=r("custom-data");if(e)try{return JSON.parse(e)}catch{return}})();return{communityId:n,channelId:o,widgetId:l,widgetType:s,theme:r("theme")||"light",themeExplicit:!!r("theme"),container:h,width:r("width")||"100%",height:r("height")||"600px",apiUrl:r("api-url")||"https://sgtr-eks-widgets.genesiv.org",widgetUrl:d,widgetDomain:c,autoRefresh:"false"!==r("auto-refresh"),debug:"true"===r("debug"),storagePrefix:r("storage-prefix")||"returning-ai-widget",userIdentifiers:u,maxRetries:i("max-retries",3),retryDelay:i("retry-delay",500),heightDebounce:i("height-debounce",100),locale:r("locale")||void 0,customData:m,authUrl:r("auth-url")||void 0,bundleUrl:r("bundle-url")||void 0,embedToken:r("embed-token")||void 0,v2ApiUrl:r("v2-api-url")||void 0,domainKey:r("domain-key")||void 0,loadingText:r("loading-text")||"Loading ...",firstPaintColors:(()=>{const e=r("bg")||void 0,t=r("text")||void 0,i=r("accent")||void 0;return e||t||i?{bg:e,text:t,accent:i}:void 0})(),firstPaintFont:r("font")||void 0}}(this,void 0);const e=document.createElement("style");e.textContent=':host{display:block;position:relative;width:100%;height:100%}.rai-loader{position:absolute;top:0;left:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.75rem;width:100%;height:100%;background:var(--background-5, var(--rai-loader-bg, #ffffff));border-radius:8px;z-index:10;transition:opacity .3s ease-out;font-family:var(--rai-loader-font, "Roboto", system-ui, -apple-system, sans-serif)}.rai-loader.fade-out{opacity:0;pointer-events:none}.rai-loader-text{margin:.5rem 0 0;font-size:1.125rem;line-height:1.75rem;font-weight:400;letter-spacing:normal;color:var(--accent-1, var(--rai-accent, #000000));text-align:center}@media (min-width: 768px){.rai-loader-text{font-size:1.5rem;line-height:2rem}}.rai-error{display:none;position:absolute;top:0;left:0;width:100%;height:100%;align-items:center;justify-content:center;flex-direction:column;gap:12px;background:var(--rai-error-bg, #1a1a1a);border-radius:8px;padding:24px;box-sizing:border-box;text-align:center;color:var(--rai-error-text, #9ca3af);font-family:system-ui,-apple-system,sans-serif;z-index:10}.rai-error.visible{display:flex}iframe{display:block;border:none;opacity:0;transition:opacity .3s ease-in}iframe.loaded{opacity:1}.rai-lottie-loader{width:100px;height:100px}.rai-lottie-loader svg{width:100%!important;height:100%!important}.rai-lottie-spinner{width:32px;height:32px;margin:34px auto;border:3px solid var(--rai-text4, #6b7280);border-top-color:var(--rai-accent, #000000);border-radius:50%;animation:rai-spin .7s linear infinite}@keyframes rai-spin{to{transform:rotate(360deg)}}.rai-sdk-loader{position:relative;width:75px;height:100px}.rai-sdk-loader__bar{position:absolute;bottom:0;width:10px;height:50%;background:var(--rai-accent, #000000);transform-origin:center bottom;box-shadow:1px 1px #0003}.rai-sdk-loader__bar:nth-child(1){left:0;transform:scaleY(.2);animation:rai-sdk-barUp1 4s infinite}.rai-sdk-loader__bar:nth-child(2){left:15px;transform:scaleY(.4);animation:rai-sdk-barUp2 4s infinite}.rai-sdk-loader__bar:nth-child(3){left:30px;transform:scaleY(.6);animation:rai-sdk-barUp3 4s infinite}.rai-sdk-loader__bar:nth-child(4){left:45px;transform:scaleY(.8);animation:rai-sdk-barUp4 4s infinite}.rai-sdk-loader__bar:nth-child(5){left:60px;transform:scale(1);animation:rai-sdk-barUp5 4s infinite}.rai-sdk-loader__ball{position:absolute;bottom:10px;left:0;width:10px;height:10px;background:var(--rai-accent, #000000);border-radius:50%;animation:rai-sdk-ball 4s infinite}@keyframes rai-sdk-ball{0%{transform:translate(0)}5%{transform:translate(8px,-14px)}10%{transform:translate(15px,-10px)}17%{transform:translate(23px,-24px)}20%{transform:translate(30px,-20px)}27%{transform:translate(38px,-34px)}30%{transform:translate(45px,-30px)}37%{transform:translate(53px,-44px)}40%{transform:translate(60px,-40px)}50%{transform:translate(60px)}57%{transform:translate(53px,-14px)}60%{transform:translate(45px,-10px)}67%{transform:translate(37px,-24px)}70%{transform:translate(30px,-20px)}77%{transform:translate(22px,-34px)}80%{transform:translate(15px,-30px)}87%{transform:translate(7px,-44px)}90%{transform:translateY(-40px)}to{transform:translate(0)}}@keyframes rai-sdk-barUp1{0%{transform:scaleY(.2)}40%{transform:scaleY(.2)}50%{transform:scale(1)}90%{transform:scale(1)}to{transform:scaleY(.2)}}@keyframes rai-sdk-barUp2{0%{transform:scaleY(.4)}40%{transform:scaleY(.4)}50%{transform:scaleY(.8)}90%{transform:scaleY(.8)}to{transform:scaleY(.4)}}@keyframes rai-sdk-barUp3{0%{transform:scaleY(.6)}to{transform:scaleY(.6)}}@keyframes rai-sdk-barUp4{0%{transform:scaleY(.8)}40%{transform:scaleY(.8)}50%{transform:scaleY(.4)}90%{transform:scaleY(.4)}to{transform:scaleY(.8)}}@keyframes rai-sdk-barUp5{0%{transform:scale(1)}40%{transform:scale(1)}50%{transform:scaleY(.2)}90%{transform:scaleY(.2)}to{transform:scale(1)}}#loading-square{width:75px;aspect-ratio:1;display:flex;color:var(--rai-accent, #000000);background:linear-gradient(currentColor 0 0) right / 51% 100%,linear-gradient(currentColor 0 0) bottom / 100% 51%;background-repeat:no-repeat;animation:l16-0 2s infinite linear .25s}#loading-square>div{width:50%;height:50%;background:currentColor;animation:l16-1 .5s infinite linear}@keyframes l16-0{0%,12.49%{transform:rotate(0)}12.5%,37.49%{transform:rotate(90deg)}37.5%,62.49%{transform:rotate(180deg)}62.5%,87.49%{transform:rotate(270deg)}87.5%,to{transform:rotate(360deg)}}@keyframes l16-1{0%{transform:perspective(80px) rotate3d(-1,-1,0,0)}80%,to{transform:perspective(80px) rotate3d(-1,-1,0,-180deg)}}#loading-circle{width:75px;aspect-ratio:1;display:grid;grid:50%/50%;color:var(--rai-accent, #000000);border-radius:50%;--_g: no-repeat linear-gradient(currentColor 0 0);background:var(--_g),var(--_g),var(--_g);background-size:50.1% 50.1%;animation:l9-0 1.5s infinite steps(1) alternate,l9-0-0 3s infinite steps(1) alternate}#loading-circle>div{background:var(--rai-text4, #6b7280);border-top-left-radius:100px;transform:perspective(150px) rotateY(0) rotateX(0);transform-origin:bottom right;animation:l9-1 1.5s infinite linear alternate}@keyframes l9-0{0%{background-position:0 100%,100% 100%,100% 0}33%{background-position:100% 100%,100% 100%,100% 0}66%{background-position:100% 0,100% 0,100% 0}}@keyframes l9-0-0{0%{transform:scaleX(1) rotate(0)}50%{transform:scaleX(-1) rotate(-90deg)}}@keyframes l9-1{16.5%{transform:perspective(150px) rotateX(-90deg) rotateY(0) rotateX(0);filter:grayscale(.8)}33%{transform:perspective(150px) rotateX(-180deg) rotateY(0) rotateX(0)}66%{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(0)}to{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(-180deg);filter:grayscale(.8)}}.rai-custom-error{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10}.tiptap strong.tw-font-bold,.tiptap b.tw-font-bold{font-weight:700}.tiptap em.tw-font-italic,.tiptap i.tw-font-italic{font-style:italic}.tiptap a.tiptap-rich-text-link{color:#3b82f6;text-decoration:underline;position:relative;display:inline-block;width:fit-content}.tiptap a.tiptap-rich-text-link:hover{color:#3b82f6cc;text-decoration:none}.tiptap a.tiptap-rich-text-link:not([title=""]):before{content:attr(title);position:absolute;top:-2rem;left:50%;transform:translate(-50%);white-space:nowrap;border-radius:.25rem;background-color:#000;padding:.25rem .5rem;color:#fff;opacity:0;transition:opacity .2s;pointer-events:none}.tiptap a.tiptap-rich-text-link:not([title=""]):hover:before{opacity:1}.tiptap p[style*="text-align: left"]{text-align:left}.tiptap p[style*="text-align: center"]{text-align:center}.tiptap p[style*="text-align: right"]{text-align:right}.tiptap p[style*="text-align: justify"]{text-align:justify}.tiptap u{text-decoration:underline}.tiptap.ProseMirror{background-color:transparent;height:fit-content!important;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0;padding:0;width:100%;overflow-y:auto}.tiptap{line-height:1.6;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}.tiptap p{margin:.5em 0}.tiptap p:first-child{margin-top:0}.tiptap p:last-child{margin-bottom:0}.tiptap img{max-width:100%;height:auto;display:block}.tiptap p[style*="text-align: left"] img{margin-left:0;margin-right:auto}.tiptap p[style*="text-align: center"] img{margin-left:auto;margin-right:auto}.tiptap p[style*="text-align: right"] img{margin-left:auto;margin-right:0}.rai-retry-btn{padding:8px 20px;border:none;border-radius:6px;background:var(--rai-accent, #000000);color:var(--rai-error-bg, #ffffff);font-size:14px;font-family:system-ui,-apple-system,sans-serif;cursor:pointer}.rai-retry-btn:hover{opacity:.85}',this.shadow.appendChild(e);const t=this.config.theme,r="dark"===t?"#ffffff":"#000000",i="dark"===t?"#9ca3af":"#6b7280",a="dark"===t?"#1a1a1a":"#ffffff";this.style.width=this.config.width,this.style.height=this.config.height,this.style.setProperty("--rai-accent",r),this.style.setProperty("--rai-text4",i),this.style.setProperty("--rai-loader-bg",a),this.style.setProperty("--rai-error-bg",a),this.applyFirstPaintColors(),this.renderShell(),this.hasAttribute("eager")?this.init():(this.intersectionObserver=new IntersectionObserver(e=>{e[0].isIntersecting&&(this.intersectionObserver.disconnect(),this.intersectionObserver=void 0,this.init())}),this.intersectionObserver.observe(this))}disconnectedCallback(){var e,t;null==(e=this.intersectionObserver)||e.disconnect(),null==(t=this.themeObserver)||t.disconnect(),this.cleanupListener&&this.cleanupListener(),g(this.state)}emit(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t??{}}))}applyFirstPaintColors(){var e;const t=o(this.config);if(!this.config.themeExplicit){const e=null==t?void 0:t.defaultColorSchema;"light"!==e&&"dark"!==e||(this.config.theme=e)}const r="dark"===this.config.theme?"dark":"light",i=null==(e=null==t?void 0:t.themePalette)?void 0:e[r];i&&this.applyPalette(i);const a=("string"==typeof(null==t?void 0:t.font)?t.font:void 0)||this.config.firstPaintFont;if(a&&this.applyFont(a),i)return;const n=this.config.firstPaintColors;(null==n?void 0:n.bg)&&this.style.setProperty("--background-5",n.bg),(null==n?void 0:n.text)&&this.style.setProperty("--text-1",n.text),(null==n?void 0:n.accent)&&this.style.setProperty("--accent-1",n.accent)}applyFont(e){this.style.setProperty("--rai-loader-font",`'${e}', system-ui, -apple-system, sans-serif`),function(e){if(!e||v.has(e))return;v.add(e);const t=`rai-font-${e.toLowerCase().replace(/\s+/g,"-")}`;if(document.getElementById(t))return;const r=document.createElement("link");r.id=t,r.rel="stylesheet",r.href=`https://fonts.googleapis.com/css2?family=${encodeURIComponent(e)}&display=swap`,document.head.appendChild(r)}(e)}applyPalette(e){Object.entries(e).forEach(([e,t])=>{e.startsWith("--")&&t&&this.style.setProperty(e,t)})}renderShell(){this.loaderEl=document.createElement("div"),this.loaderEl.className="rai-loader";const e=document.createElement("h1");e.className="rai-loader-text",e.textContent=this.config.loadingText,this.loaderEl.appendChild(e),this.shadow.appendChild(this.loaderEl),this.fetchAndRenderLoader(),this.errorEl=document.createElement("div"),this.errorEl.className="rai-error",this.msgEl=document.createElement("span"),this.msgEl.className="rai-error-msg",this.msgEl.textContent="Authentication failed. Please try again later.",this.errorEl.appendChild(this.msgEl);const t=this.getAttribute("retry-label")||this.getAttribute("data-retry-label")||"Retry",r=document.createElement("button");r.className="rai-retry-btn",r.textContent=t,r.addEventListener("click",()=>this.reload()),this.errorEl.appendChild(r),this.shadow.appendChild(this.errorEl)}async fetchAndRenderLoader(){var e;const t=o(this.config);if(t)return m(this.state,t),this.renderLoaderAnimation(),void f(this.config,this.state,{skipCache:!0}).catch(()=>{});try{await f(this.config,this.state)}catch{}if(!this.loaderEl)return;this.config.themeExplicit||"light"!==this.state.defaultColorSchema&&"dark"!==this.state.defaultColorSchema||this.state.defaultColorSchema===this.config.theme||(this.config.theme=this.state.defaultColorSchema);const r="dark"===this.config.theme?"dark":"light",i=null==(e=this.state.themePalette)?void 0:e[r];i&&this.applyPalette(i),this.state.font&&this.applyFont(this.state.font),this.renderLoaderAnimation()}renderLoaderAnimation(){if(!this.loaderEl)return;const e=this.loaderEl.querySelector(".rai-loader-anim");e&&e.remove();const t=document.createElement("div");t.className="rai-loader-anim";const r=this.state.loadingAnimation,i="dark"===this.config.theme?"dark":"light";if("custom"===(null==r?void 0:r.type)&&r.custom){const e=r.custom[i]||r.custom.light||r.custom.dark;if(e){if("lottie"===e.type&&e.lottieData)return this.renderLottieInto(t,e.lottieData),void this.loaderEl.insertBefore(t,this.loaderEl.firstChild);if("html"===e.type&&e.html)return t.innerHTML=function(e){const t=(new DOMParser).parseFromString(e,"text/html");return t.body.querySelectorAll(x.join(",")).forEach(e=>e.remove()),t.body.querySelectorAll("*").forEach(e=>{Array.from(e.attributes).forEach(t=>{const r=t.name.toLowerCase();(r.startsWith("on")||T.includes(r)&&t.value.trim().toLowerCase().startsWith("javascript:"))&&e.removeAttribute(t.name)})}),t.body.innerHTML}(e.html),void this.loaderEl.insertBefore(t,this.loaderEl.firstChild)}}if("preset"===(null==r?void 0:r.type)&&r.preset)return t.appendChild(this.createPresetLoader(r.preset)),void this.loaderEl.insertBefore(t,this.loaderEl.firstChild);t.appendChild(this.createDefaultLoader()),this.loaderEl.insertBefore(t,this.loaderEl.firstChild)}renderLottieInto(e,t){const r=document.createElement("div");r.className="rai-lottie-loader",e.appendChild(r);const i=window;if(void 0!==i.lottie)i.lottie.loadAnimation({container:r,renderer:"svg",loop:!0,autoplay:!0,animationData:t});else{const i=document.createElement("script");i.src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js",i.onload=()=>{window.lottie.loadAnimation({container:r,renderer:"svg",loop:!0,autoplay:!0,animationData:t})},i.onerror=()=>{r.remove(),e.appendChild(this.createDefaultLoader())},document.head.appendChild(i)}}createDefaultLoader(){const e=document.createElement("div");e.className="rai-sdk-loader";for(let r=0;r<5;r++){const t=document.createElement("div");t.className="rai-sdk-loader__bar",e.appendChild(t)}const t=document.createElement("div");return t.className="rai-sdk-loader__ball",e.appendChild(t),e}createPresetLoader(e){if("square"===e){const e=document.createElement("div");e.id="loading-square";const t=document.createElement("div");return e.appendChild(t),e}if("circle"===e){const e=document.createElement("div");e.id="loading-circle";const t=document.createElement("div");return e.appendChild(t),e}return this.createDefaultLoader()}hideLoader(){this.loaderEl&&(this.loaderEl.classList.add("fade-out"),setTimeout(()=>{var e;return null==(e=this.loaderEl)?void 0:e.remove()},300),this.loaderEl=null)}deferLoaderRemovalUntilReactPaints(e){if(!this.loaderEl)return;let t=!1;const r=()=>{t||(t=!0,this.hideLoader())},i=new MutationObserver(()=>{e.children.length>0&&(i.disconnect(),requestAnimationFrame(r))});i.observe(e,{childList:!0}),setTimeout(()=>{i.disconnect(),r()},2e3)}showError(){this.hideLoader();const e=this.state.errorSettings,t=this.state.lastAuthError,r="User not found"===(null==t?void 0:t.error)||"Missing required user identifier fields"===(null==t?void 0:t.error)||"Missing user identifier fields"===(null==t?void 0:t.error),i=!!(null==e?void 0:e.errorMessage)&&(r||!t);i?this.renderCustomError(e):this.errorEl&&((null==t?void 0:t.error)&&this.msgEl&&(this.msgEl.textContent=t.hint?`${t.error}: ${t.hint}`:t.error),this.errorEl.classList.add("visible"));const a=i?e.errorMessage:(null==t?void 0:t.error)||"Authentication failed";this.emit("rai-error",{message:a,hint:null==t?void 0:t.hint,status:null==t?void 0:t.status})}renderCustomError(e){var t,r;null==(t=this.errorEl)||t.remove(),this.errorEl=null;const i=(null==(r=e.backgroundImage)?void 0:r.trim())?`background-image: url('${e.backgroundImage}'); background-size: cover; background-position: center; background-repeat: no-repeat;`:"",a=document.createElement("div");a.className="rai-custom-error",a.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n overflow: auto;\n width: 100%;\n height: 100%;\n ${i}\n `;const n=document.createElement("div");n.className="rai-rich-text",n.style.cssText=`\n min-width: 50%;\n min-height: 50%;\n margin: 0 auto;\n padding: 20px;\n width: auto;\n height: auto;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 6px;\n background-color: ${e.modalColor||"transparent"};\n `;const o=document.createElement("div");o.className="tiptap ProseMirror",o.innerHTML=e.errorMessage||"",n.appendChild(o),a.appendChild(n),this.shadow.appendChild(a)}async init(){if(!this.config.communityId)return void this.showError();await f(this.config,this.state);const e=()=>{this.config.bundleUrl?this.mountWidget():this.createIframe()};if(this.config.authUrl){return void(await d(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError())}if(this.config.embedToken){g(this.state),n(this.config);return void(await c(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError())}if(function(e,t){try{const r=localStorage.getItem(i(e));if(!r)return!1;const a=JSON.parse(r);return a.refreshToken&&!s(a.refreshTokenExpiry)?(t.refreshToken=a.refreshToken,t.tokenFamily=a.tokenFamily,t.refreshTokenExpiry=a.refreshTokenExpiry,!0):(n(e),!1)}catch{return!1}}(this.config,this.state)){return await h(this.config,this.state,()=>this.scheduleRefresh())?(this.state.isAuthenticated=!0,this.emit("rai-authenticated"),void e()):void this.showError()}await c(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError()}createIframe(){const e=document.createElement("iframe");e.src=this.buildWidgetUrl(this.config),e.allow="clipboard-write",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),e.frameBorder="0",e.scrolling="no",e.style.width=this.config.width,e.style.height=this.config.height,e.style.border="none",e.style.display="block",e.onload=()=>{p(this.config,this.state,e),this.schedulePeriodicSync(e)},e.onerror=()=>{this.showError()},this.state.iframe=e,this.shadow.appendChild(e),this.cleanupListener=y(this.config,this.state,this.shadow,e,()=>this.scheduleRefresh(),()=>this.logoutAndClear(),()=>this.hideLoader(),(e,t)=>this.emit(e,t))}async mountWidget(){try{const t=this.config.v2ApiUrl||this.config.apiUrl,r=window;!r.DomainKey&&this.config.domainKey&&(r.DomainKey="PROD"===this.config.domainKey?"GEN":this.config.domainKey);const i=["api_url","base_url","auth_api","socket_path_v2","socket_path","channel_api"];for(const e of i)r[e]||(r[e]=t);window.__IS_WIDGET__=!0,window.guest_token=this.state.accessToken;const a="dark"===this.config.theme?"dark":"light",n="dark"===a?"dark-knight":"white-smoke";document.documentElement.setAttribute("data-theme",n),window.currentTheme=a,window.__FORCE_COLOR_MODE__=a,window.__WIDGET_STORAGE_KEY__=`color-schema-${this.config.widgetType}-${this.config.widgetId}`,this.state.loadingAnimation&&(window.loadingAnimation=this.state.loadingAnimation),await(e=this.config.bundleUrl,new Promise((t,r)=>{const i=document.createElement("script");i.src=e,i.onload=()=>t(),i.onerror=()=>r(new Error(`Failed to load ${e}`)),document.head.appendChild(i)}));const o=b[this.config.widgetType],s=window[o];if(!(null==s?void 0:s.mount))throw new Error(`window.${o}.mount not found after loading bundle`);const l=document.createElement("div");if(l.className="rai-widget-root",l.style.cssText=["position: relative","width: 100%","height: 100%","color: var(--text-1)","background: var(--background-1)","font-family: var(--rai-loader-font, 'Roboto', system-ui, -apple-system, sans-serif)"].join("; "),this.appendChild(l),!this.shadow.querySelector("slot")){const e=document.createElement("slot");this.shadow.appendChild(e)}this.deferLoaderRemovalUntilReactPaints(l),s.mount(l,{widgetType:this.config.widgetType,communityId:this.config.communityId,channelId:this.config.channelId,widgetId:this.config.communityId,apiUrl:t,token:this.state.accessToken,basePath:"/",isPreview:!1,isOpenWidget:!this.state.accessToken,defaultColorSchema:"dark"===this.config.theme?"dark":"light"}),this.emit("rai-mounted")}catch(t){console.error("[rai-widget] Bundle mount failed:",t),this.showError()}var e}scheduleRefresh(){if(this.state.refreshTimer&&clearTimeout(this.state.refreshTimer),!this.state.accessTokenExpiry)return;const e=this.state.accessTokenExpiry-Date.now()-6e4,t=()=>{this.state.iframe&&p(this.config,this.state,this.state.iframe),this.config.bundleUrl&&this.state.accessToken&&(window.guest_token=this.state.accessToken)},r=async()=>{if(this.config.authUrl){await d(this.config,this.state,()=>this.scheduleRefresh())&&t()}else await h(this.config,this.state,()=>this.scheduleRefresh(),t)};e>0?this.state.refreshTimer=setTimeout(r,e):r()}schedulePeriodicSync(e){this.state.syncTimer&&clearInterval(this.state.syncTimer),this.state.syncTimer=setInterval(()=>{this.state.accessToken&&p(this.config,this.state,e)},12e4)}async logoutAndClear(){await async function(e,t){if(t.accessToken)try{await fetch(`${e.apiUrl}/${e.widgetId}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({refreshToken:t.refreshToken})})}catch{}g(t),n(e)}(this.config,this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),this.emit("rai-logout")}async reload(){g(this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),await this.init()}async logoutPublic(){await this.logoutAndClear()}isAuthenticated(){return this.state.isAuthenticated&&null!==this.state.accessToken}getTokenInfo(){return{hasAccessToken:!!this.state.accessToken,hasRefreshToken:!!this.state.refreshToken,accessTokenExpiry:this.state.accessTokenExpiry?new Date(this.state.accessTokenExpiry):null,refreshTokenExpiry:this.state.refreshTokenExpiry?new Date(this.state.refreshTokenExpiry):null,isAccessTokenValid:!!this.state.accessToken&&!s(this.state.accessTokenExpiry),isRefreshTokenValid:!!this.state.refreshToken&&!s(this.state.refreshTokenExpiry)}}}class I extends E{buildWidgetUrl(e){const t=new URL(e.widgetUrl);return t.searchParams.set("color",e.theme),t.searchParams.set("containerId",e.container),t.searchParams.set("connectType","simple"),t.searchParams.set("mode","private"),e.locale&&t.searchParams.set("locale",e.locale),t.toString()}}class A extends E{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("channel-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;try{const r=new URL(t);return r.searchParams.set("color",e.theme),e.locale&&r.searchParams.set("locale",e.locale),r.toString()}catch{const r=[`color=${e.theme}`];return e.locale&&r.push(`locale=${encodeURIComponent(e.locale)}`),`${t}?${r.join("&")}`}}}class C extends E{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("milestone-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;try{const r=new URL(t);return r.searchParams.set("color",e.theme),e.locale&&r.searchParams.set("locale",e.locale),r.toString()}catch{const r=[`color=${e.theme}`];return e.locale&&r.push(`locale=${encodeURIComponent(e.locale)}`),`${t}?${r.join("&")}`}}}class U extends E{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("social-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;try{const r=new URL(t);return r.searchParams.set("color",e.theme),e.locale&&r.searchParams.set("locale",e.locale),r.toString()}catch{const r=[`color=${e.theme}`];return e.locale&&r.push(`locale=${encodeURIComponent(e.locale)}`),`${t}?${r.join("&")}`}}}class R extends E{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("currency-overview-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;try{const r=new URL(t);return r.searchParams.set("color",e.theme),e.locale&&r.searchParams.set("locale",e.locale),r.toString()}catch{const r=[`color=${e.theme}`];return e.locale&&r.push(`locale=${encodeURIComponent(e.locale)}`),`${t}?${r.join("&")}`}}}class S extends E{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("referral-conditions-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;try{const r=new URL(t);return r.searchParams.set("color",e.theme),e.locale&&r.searchParams.set("locale",e.locale),r.toString()}catch{const r=[`color=${e.theme}`];return e.locale&&r.push(`locale=${encodeURIComponent(e.locale)}`),`${t}?${r.join("&")}`}}}class P extends E{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("custom-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;try{const r=new URL(t);return r.searchParams.set("color",e.theme),e.locale&&r.searchParams.set("locale",e.locale),r.toString()}catch{const r=[`color=${e.theme}`];return e.locale&&r.push(`locale=${encodeURIComponent(e.locale)}`),`${t}?${r.join("&")}`}}}console.log("[rai-widget] v1.3.0");const $=[["rai-store-widget",I],["rai-channel-widget",A],["rai-milestone-widget",C],["rai-social-widget",U],["rai-currency-widget",R],["rai-referral-widget",S],["rai-custom-widget",P],["rai-widget",class extends I{}]];for(const[O,N]of $)customElements.get(O)||customElements.define(O,N);const _={store:I,channel:A,milestone:C,social:U,"currency-view":R,"referral-conditions":S,custom:P},D=$.map(([e])=>e).join(", ");function L(){var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return;const i=r.getAttribute("data-community-id")||r.getAttribute("data-widget-id");if(!i)return;const a=r.getAttribute("data-container")||`returning-ai-widget-${i}`,n=document.getElementById(a);if(!n)return;"static"===getComputedStyle(n).position&&(n.style.position="relative");const o=r.getAttribute("data-widget-type")??"store",s=new(_[o]??I);Array.from(r.attributes).forEach(e=>{s.setAttribute(e.name,e.value)}),n.appendChild(s)}function W(){const e=(()=>{var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return null;const i=r.getAttribute("data-container")||`returning-ai-widget-${r.getAttribute("data-community-id")||r.getAttribute("data-widget-id")}`;return document.getElementById(i)})(),t=null==e?void 0:e.querySelector(D);window.ReturningAIWidget={version:"1.3.0",reload:()=>(null==t?void 0:t.reload())??Promise.resolve(),logout:()=>(null==t?void 0:t.logoutPublic())??Promise.resolve(),isAuthenticated:()=>(null==t?void 0:t.isAuthenticated())??!1,getTokenInfo:()=>(null==t?void 0:t.getTokenInfo())??{}}}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",L):L(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",W):W(),e.ChannelWidget=A,e.CurrencyWidget=R,e.CustomWidget=P,e.MilestoneWidget=C,e.ReferralWidget=S,e.SocialWidget=U,e.StoreWidget=I,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});