@xenia-martech/sdk-js 1.0.0-dev.26 → 1.0.0-dev.28

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.
Files changed (37) hide show
  1. package/CSS_VARIABLES.md +7 -0
  2. package/README.md +71 -2
  3. package/dist/{actions-DFLoSXO_.d.cts → actions-CcBYV--3.d.cts} +242 -6
  4. package/dist/{actions-DFLoSXO_.d.ts → actions-CcBYV--3.d.ts} +242 -6
  5. package/dist/{chunk-3KYKKIIG.cjs → chunk-WYM4CQVG.cjs} +126 -4
  6. package/dist/chunk-WYM4CQVG.cjs.map +1 -0
  7. package/dist/{chunk-D37RD3UC.js → chunk-XXNDHYAS.js} +125 -5
  8. package/dist/chunk-XXNDHYAS.js.map +1 -0
  9. package/dist/client/index.cjs +613 -35
  10. package/dist/client/index.cjs.map +1 -1
  11. package/dist/client/index.d.cts +112 -3
  12. package/dist/client/index.d.ts +112 -3
  13. package/dist/client/index.js +610 -36
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/react/index.cjs +609 -35
  16. package/dist/client/react/index.cjs.map +1 -1
  17. package/dist/client/react/index.d.cts +2 -2
  18. package/dist/client/react/index.d.ts +2 -2
  19. package/dist/client/react/index.js +609 -35
  20. package/dist/client/react/index.js.map +1 -1
  21. package/dist/{cookie-names-LgNDAreS.d.cts → cookie-names-B3b0XNc2.d.cts} +187 -1
  22. package/dist/{cookie-names-LgNDAreS.d.ts → cookie-names-B3b0XNc2.d.ts} +187 -1
  23. package/dist/index.cjs +23 -19
  24. package/dist/index.d.cts +23 -3
  25. package/dist/index.d.ts +23 -3
  26. package/dist/index.js +1 -1
  27. package/dist/server/index.cjs +53 -22
  28. package/dist/server/index.cjs.map +1 -1
  29. package/dist/server/index.d.cts +31 -11
  30. package/dist/server/index.d.ts +31 -11
  31. package/dist/server/index.js +43 -12
  32. package/dist/server/index.js.map +1 -1
  33. package/dist/xenia-sdk.iife.js +37 -3
  34. package/dist/xenia-sdk.iife.js.map +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-3KYKKIIG.cjs.map +0 -1
  37. package/dist/chunk-D37RD3UC.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/event-payload.ts","../../src/server/xenia-server.ts","../../src/server/token.ts","../../src/server/cookies.ts"],"names":[],"mappings":";;;;AAGA,IAAM,QAAA,uBAAe,GAAA,CAAI;AAAA,EACvB,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAAC,CAAA;AAaD,SAAS,QAAQ,GAAA,EAAuE;AACtF,EAAA,MAAM,MAAiC,EAAC;AACxC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACxC,IAAA,IAAI,CAAA,KAAM,MAAA,EAAW,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EAChC;AACA,EAAA,OAAO,GAAA;AACT;AAWO,SAAS,kBAAkB,KAAA,EAAsC;AACtE,EAAA,MAAM,cAAyC,EAAC;AAChD,EAAA,MAAM,WAAsC,EAAC;AAC7C,EAAA,IAAI,MAAM,KAAA,EAAO;AACf,IAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAA,EAAG;AAChD,MAAA,IAAI,MAAM,MAAA,EAAW;AAKrB,MAAA,IAAI,SAAS,GAAA,CAAI,CAAC,CAAA,EAAG,QAAA,CAAS,CAAC,CAAA,GAAI,CAAA;AAAA,WAC9B,WAAA,CAAY,CAAC,CAAA,GAAI,CAAA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CACd,cACA,MAAA,EACe;AACf,EAAA,OAAO,aAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA,IAAK,IAAA;AAClE;AAQO,SAAS,UAAA,CACd,cACA,MAAA,EACc;AACd,EAAA,MAAM,MAAM,YAAA,CAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA;AAChE,EAAA,IAAI,CAAC,KAAK,OAAO,EAAE,WAAW,KAAA,EAAO,SAAA,EAAW,KAAA,EAAO,eAAA,EAAiB,KAAA,EAAM;AAC9E,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA;AAC1D,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,eAAA,EAAiB,MAAA,CAAO,GAAA,CAAI,iBAAiB;AAAA,KAC/C;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { EventContext, EventIdentity, EventPayload, JsonValue } from \"./types\";\n\n/** Reserved keys that map to first-class fields (not passthrough data). */\nconst RESERVED = new Set([\n \"eventId\",\n \"eventType\",\n \"journeyId\",\n \"deviceId\",\n \"visitorId\",\n \"customerId\",\n \"email\",\n \"utmSource\",\n \"utmMedium\",\n \"utmCampaign\",\n \"utmContent\",\n \"utmId\",\n \"url\",\n \"referrer\",\n \"path\",\n \"query\",\n]);\n\nexport interface BuildEventInput {\n eventId: string;\n eventType?: string;\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n /** Arbitrary extra properties merged as passthrough data. */\n props?: Record<string, JsonValue | undefined>;\n}\n\n/** Drop `undefined` values so the JSON body stays clean. */\nfunction compact(obj: Record<string, JsonValue | undefined>): Record<string, JsonValue> {\n const out: Record<string, JsonValue> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Build the request body for the webhook `/flow` call (`XeniaApi.webhook`).\n *\n * Merge order (later wins): passthrough props < context < identity < core.\n * Field names match the backend `EventTriggerRequest` DTO exactly.\n *\n * @internal Used only by the webhook request/response path — the unified event\n * surface (`track()` → `POST /api/events/v1`) builds {@link XeniaEvent} instead.\n */\nexport function buildEventPayload(input: BuildEventInput): EventPayload {\n const passthrough: Record<string, JsonValue> = {};\n const reserved: Record<string, JsonValue> = {};\n if (input.props) {\n for (const [k, v] of Object.entries(input.props)) {\n if (v === undefined) continue;\n // A prop whose key matches a reserved field (e.g. `email`, `customerId`,\n // `utmSource`) is promoted to that first-class field; everything else is\n // custom passthrough data. Previously reserved-named props were dropped\n // outright — so `track(\"sign_up\", { email })` never sent `email` at all.\n if (RESERVED.has(k)) reserved[k] = v;\n else passthrough[k] = v;\n }\n }\n\n const payload = {\n ...passthrough,\n // Reserved-named props fill first-class fields (e.g. `email`, `customerId`)\n // the SDK didn't auto-collect. Auto-collected context/identity still win for\n // what they reliably know (real page url, visitor/device id), so a stray prop\n // can't override the true page context — see merge order below.\n ...reserved,\n ...compact((input.context ?? {}) as Record<string, JsonValue | undefined>),\n ...compact((input.identity ?? {}) as Record<string, JsonValue | undefined>),\n eventId: input.eventId,\n ...(input.eventType ? { eventType: input.eventType } : {}),\n ...(input.journeyId ? { journeyId: input.journeyId } : {}),\n };\n\n return payload as EventPayload;\n}\n","import { XeniaApi } from \"../core/api\";\nimport { buildEventPayload } from \"../core/event-payload\";\nimport { generateUlid, toEventId } from \"../core/id\";\nimport type {\n AnalyticsContext,\n AnalyticsEventName,\n CallerIdentity,\n AnalyticsIngestResponse,\n ConsentState,\n EventContext,\n EventIdentity,\n IdentifyRequest,\n IdentifyResponse,\n JsonValue,\n ResolveBatchItem,\n ResolveBatchResult,\n ResolveOptions,\n ResolveResult,\n WebhookResponse,\n XeniaConfig,\n XeniaEvent,\n} from \"../core/types\";\n\n/**\n * Extra per-call identity/context for server-side webhook calls. There's no\n * ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM\n * params the way the browser client does — pass whatever's known at the call\n * site (e.g. the current request's pathname from Next.js `headers()`/route\n * params) via `context`, and `deviceId`/`visitorId`/etc. via `identity`.\n */\nexport interface ServerWebhookOptions {\n method?: \"GET\" | \"POST\";\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n}\n\n/**\n * Options for a server-side unified event (`POST /api/events/v1`). There's no\n * ambient request context on the server — pass whatever's known at the call\n * site (e.g. pathname/user-agent from the current request, session id from a\n * cookie) via `identity`/`context`.\n */\nexport interface ServerTrackOptions {\n /** When true, also match/advance a journey (never sampled/shed). Default false. */\n trigger?: boolean;\n /** Stable dedup key (e.g. `\"ord-1001\"`) for idempotent conversions. */\n eventId?: string;\n eventVersion?: number;\n occurredAtMs?: number;\n /** Origin tag. Default `\"xenia-server-sdk\"`. */\n source?: string;\n /** Identity fields for this event (except the SDK-owned `xeniaVisitorId`,\n * which comes from `config.visitorId` and can't be set per call). */\n identity?: CallerIdentity;\n context?: AnalyticsContext;\n properties?: Record<string, JsonValue | undefined>;\n consent?: ConsentState;\n}\n\n/**\n * Server-native Xenia client. Same method names as the browser client, but\n * every call is stateless: identity and context are passed explicitly rather\n * than read from the DOM/localStorage. Uses global `fetch` (Node ≥18).\n */\nexport class XeniaServer {\n readonly api: XeniaApi;\n /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */\n private readonly visitorId?: string;\n\n constructor(config: XeniaConfig) {\n this.api = new XeniaApi(config);\n this.visitorId = config.visitorId;\n }\n\n /**\n * Send a unified event server-side (`POST /api/events/v1`) and return the\n * ingest response (including per-result `triggered`). `opts.trigger: true`\n * also matches/advances a journey; pass `opts.eventId` (e.g. `\"ord-1001\"`)\n * as a stable dedup key for idempotent conversions.\n */\n async track(\n eventName: AnalyticsEventName,\n opts: ServerTrackOptions = {},\n ): Promise<AnalyticsIngestResponse> {\n const event: XeniaEvent = {\n eventName,\n eventId: opts.eventId ? toEventId(opts.eventId) : generateUlid(),\n eventVersion: opts.eventVersion ?? 1,\n occurredAtMs: opts.occurredAtMs ?? Date.now(),\n source: opts.source ?? \"xenia-server-sdk\",\n identity: {\n ...opts.identity,\n // SDK-owned, set LAST so it can't be overridden per call. Comes from\n // `config.visitorId` (bind it per request from the `xenia_vid` cookie).\n xeniaVisitorId: this.visitorId,\n },\n context: opts.context,\n properties: opts.properties,\n consent: opts.consent,\n trigger: opts.trigger === true ? true : undefined,\n };\n return this.api.sendEvents([event]);\n }\n\n /**\n * Send a webhook request and await the synchronous response. Merges\n * `opts.identity`/`opts.context` into the payload the same way the browser\n * client's auto-attached fields do (`path`, `query`, `url`, `referrer`,\n * `deviceId`, `visitorId`, etc.) — see `ServerWebhookOptions`.\n */\n async webhook(\n triggerId: string,\n data?: Record<string, JsonValue | undefined>,\n opts: ServerWebhookOptions = {},\n ): Promise<WebhookResponse> {\n const payload = buildEventPayload({\n eventId: triggerId,\n journeyId: opts.journeyId,\n // SDK-owned visitor anchor wins: config.visitorId (bind the `xenia_vid`\n // cookie per request) is attached automatically. Falls back to a\n // per-call visitorId only when none is bound.\n identity: { ...opts.identity, visitorId: this.visitorId ?? opts.identity?.visitorId },\n context: opts.context,\n props: data,\n });\n return this.api.webhook(triggerId, payload as JsonValue, opts.method ?? \"POST\");\n }\n\n /** Bind visitor→user server-side — `POST /api/events/v1/identify`. */\n async identify(body: IdentifyRequest): Promise<IdentifyResponse> {\n return this.api.identify(body);\n }\n\n /**\n * Resolve in-entry content personalization for one content key\n * (`POST /api/personalization/resolve`). Requires a configured SDK token\n * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the\n * returned `content` is server-spliced.\n */\n async resolve(contentKey: string, opts?: ResolveOptions): Promise<ResolveResult> {\n return this.api.resolve(contentKey, this.withVisitor(opts));\n }\n\n /** Resolve several content keys in one round-trip (`POST /api/personalization/resolve-batch`). */\n async resolveBatch(\n items: ResolveBatchItem[],\n opts?: ResolveOptions,\n ): Promise<ResolveBatchResult[]> {\n return this.api.resolveBatch(items, this.withVisitor(opts));\n }\n\n /**\n * Stamp the SDK-owned visitor id (`config.visitorId`) into the resolve `data`\n * under the reserved `_xenia_vid` key so the backend can bucket holdout\n * experiments and record exposure per visitor. Set last so a caller can't\n * override it; a no-op when no `visitorId` was bound on this client.\n */\n private withVisitor(opts?: ResolveOptions): ResolveOptions | undefined {\n if (!this.visitorId) return opts;\n return { ...opts, data: { ...(opts?.data ?? {}), _xenia_vid: this.visitorId } };\n }\n}\n\n/** Create a server-native client. */\nexport function createXeniaServer(config: XeniaConfig): XeniaServer {\n return new XeniaServer(config);\n}\n","import { HttpClient } from \"../core/http-client\";\nimport type { JsonObject } from \"../core/types\";\n\nexport interface RefreshTokenOptions {\n /**\n * Xenia base URL. Defaults to the hosted engine,\n * `https://engine.xeniamartech.com/xenia` — omit unless self-hosting.\n */\n baseUrl?: string;\n /**\n * The personalization SDK token created once in the dashboard (API Tokens →\n * Create token). Stays server-side; the browser never sees it — only the\n * short-lived token this exchanges it for does.\n */\n sdkToken: string;\n /** Lifetime of the returned token, in minutes. Default 15, capped server-side at 60. */\n ttlMinutes?: number;\n timeout?: number;\n}\n\nexport interface RefreshedToken {\n token: string;\n expiresAt?: string;\n}\n\n/**\n * Exchange the long-lived personalization SDK token for a short-lived one with\n * the same tenant/env scope, via `POST /api/personalization/token/refresh`.\n * Self-service — no dashboard credential needed, just the SDK token you\n * already have. Call this from your backend and hand the result to the\n * browser (e.g. from a token route the client SDK calls via `getToken`).\n */\nexport async function refreshSdkToken(opts: RefreshTokenOptions): Promise<RefreshedToken> {\n const http = new HttpClient({ baseUrl: opts.baseUrl, timeout: opts.timeout });\n const { data } = await http.request({\n method: \"POST\",\n path: \"/api/personalization/token/refresh\",\n headers: { Authorization: `Bearer ${opts.sdkToken}` },\n body: { ttlMinutes: opts.ttlMinutes ?? null },\n });\n const obj = (data ?? {}) as JsonObject;\n return {\n token: String(obj.token ?? \"\"),\n expiresAt: typeof obj.expiresAt === \"string\" ? obj.expiresAt : undefined,\n };\n}\n\n/**\n * Build a framework-agnostic request handler that hands the browser SDK a\n * personalization token — mount it at the endpoint `getToken` calls. Needs\n * only the SDK token you already created in the dashboard; mints a fresh\n * short-lived token per request so the long-lived one never reaches the\n * browser.\n *\n * @example\n * ```ts\n * export const GET = createTokenRoute({\n * sdkToken: process.env.XENIA_SDK_TOKEN!,\n * // baseUrl: process.env.XENIA_URL, // only to override the default hosted engine\n * });\n * ```\n */\nexport function createTokenRoute(config: RefreshTokenOptions): (request: Request) => Promise<Response> {\n return async (): Promise<Response> => {\n try {\n const refreshed = await refreshSdkToken(config);\n return new Response(JSON.stringify(refreshed), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"token refresh failed\";\n return new Response(JSON.stringify({ error: message }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n}\n","import {\n CONSENT_COOKIE,\n VISITOR_COOKIE,\n consentCookieName,\n visitorCookieName,\n} from \"../core/cookie-names\";\nimport type { ConsentState } from \"../core/types\";\n\n/**\n * Cookie names the SDK reads server-side (set by the browser SDK / your app).\n *\n * The constants are the DEFAULT-prefix names; the functions build the name for any prefix. If you\n * pass `config.prefix` to the browser client, pass the same prefix here — the browser namespaces\n * the cookie by it, so the default name won't be there to find.\n */\nexport { CONSENT_COOKIE, VISITOR_COOKIE, consentCookieName, visitorCookieName };\n\n/**\n * Parse a raw `Cookie` header into a map. Framework-agnostic so it works with\n * `Request.headers.get(\"cookie\")`, Node `req.headers.cookie`, etc.\n */\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!header) return out;\n for (const part of header.split(\";\")) {\n const idx = part.indexOf(\"=\");\n if (idx === -1) continue;\n const key = part.slice(0, idx).trim();\n const value = part.slice(idx + 1).trim();\n if (key) out[key] = decodeURIComponent(value);\n }\n return out;\n}\n\n/**\n * Read the visitor id the browser SDK wrote, so a server-side event can be bound to the same\n * visitor (`createXeniaServer({ visitorId })`) and attribute to a browser-entered journey.\n *\n * @param prefix Must match the browser client's `config.prefix`. The cookie is namespaced by it, so\n * a mismatch finds nothing and quietly leaves the server with no visitor.\n */\nexport function getVisitorId(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): string | null {\n return parseCookies(cookieHeader)[visitorCookieName(prefix)] ?? null;\n}\n\n/**\n * Read consent from a cookie header. Accepts a JSON blob or a comma-list of\n * granted scopes (e.g. `analytics,personalization`). Absent → all denied.\n *\n * @param prefix Must match the browser client's `config.prefix` — see {@link getVisitorId}.\n */\nexport function getConsent(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): ConsentState {\n const raw = parseCookies(cookieHeader)[consentCookieName(prefix)];\n if (!raw) return { analytics: false, marketing: false, personalization: false };\n try {\n const parsed = JSON.parse(raw) as ConsentState;\n return parsed;\n } catch {\n const scopes = new Set(raw.split(\",\").map((s) => s.trim()));\n return {\n analytics: scopes.has(\"analytics\"),\n marketing: scopes.has(\"marketing\"),\n personalization: scopes.has(\"personalization\"),\n };\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/core/event-payload.ts","../../src/server/xenia-server.ts","../../src/server/token.ts","../../src/server/cookies.ts"],"names":["compact"],"mappings":";;;;AAGA,IAAM,QAAA,uBAAe,GAAA,CAAI;AAAA,EACvB,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA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,KAAA,CAAM,CAAA,EAAG,GAAG,EAAE,IAAA,EAAK;AACpC,IAAA,MAAM,QAAQ,IAAA,CAAK,KAAA,CAAM,GAAA,GAAM,CAAC,EAAE,IAAA,EAAK;AACvC,IAAA,IAAI,GAAA,EAAK,GAAA,CAAI,GAAG,CAAA,GAAI,mBAAmB,KAAK,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,GAAA;AACT;AASO,SAAS,YAAA,CACd,cACA,MAAA,EACe;AACf,EAAA,OAAO,aAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA,IAAK,IAAA;AAClE;AAQO,SAAS,UAAA,CACd,cACA,MAAA,EACc;AACd,EAAA,MAAM,MAAM,YAAA,CAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA;AAChE,EAAA,IAAI,CAAC,KAAK,OAAO,EAAE,WAAW,KAAA,EAAO,SAAA,EAAW,KAAA,EAAO,eAAA,EAAiB,KAAA,EAAM;AAC9E,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA;AAC1D,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,eAAA,EAAiB,MAAA,CAAO,GAAA,CAAI,iBAAiB;AAAA,KAC/C;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { EventContext, EventIdentity, EventPayload, JsonValue } from \"./types\";\n\n/** Reserved keys that map to first-class fields (not passthrough data). */\nconst RESERVED = new Set([\n \"eventId\",\n \"eventType\",\n \"journeyId\",\n \"deviceId\",\n \"visitorId\",\n \"customerId\",\n \"email\",\n \"utmSource\",\n \"utmMedium\",\n \"utmCampaign\",\n \"utmContent\",\n \"utmId\",\n \"url\",\n \"referrer\",\n \"path\",\n \"query\",\n]);\n\nexport interface BuildEventInput {\n eventId: string;\n eventType?: string;\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n /** Arbitrary extra properties merged as passthrough data. */\n props?: Record<string, JsonValue | undefined>;\n}\n\n/** Drop `undefined` values so the JSON body stays clean. */\nfunction compact(obj: Record<string, JsonValue | undefined>): Record<string, JsonValue> {\n const out: Record<string, JsonValue> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Build the request body for the webhook `/flow` call (`XeniaApi.webhook`).\n *\n * Merge order (later wins): passthrough props < context < identity < core.\n * Field names match the backend `EventTriggerRequest` DTO exactly.\n *\n * @internal Used only by the webhook request/response path — the unified event\n * surface (`track()` → `POST /api/events/v1`) builds {@link XeniaEvent} instead.\n */\nexport function buildEventPayload(input: BuildEventInput): EventPayload {\n const passthrough: Record<string, JsonValue> = {};\n const reserved: Record<string, JsonValue> = {};\n if (input.props) {\n for (const [k, v] of Object.entries(input.props)) {\n if (v === undefined) continue;\n // A prop whose key matches a reserved field (e.g. `email`, `customerId`,\n // `utmSource`) is promoted to that first-class field; everything else is\n // custom passthrough data. Previously reserved-named props were dropped\n // outright — so `track(\"sign_up\", { email })` never sent `email` at all.\n if (RESERVED.has(k)) reserved[k] = v;\n else passthrough[k] = v;\n }\n }\n\n const payload = {\n ...passthrough,\n // Reserved-named props fill first-class fields (e.g. `email`, `customerId`)\n // the SDK didn't auto-collect. Auto-collected context/identity still win for\n // what they reliably know (real page url, visitor/device id), so a stray prop\n // can't override the true page context — see merge order below.\n ...reserved,\n ...compact((input.context ?? {}) as Record<string, JsonValue | undefined>),\n ...compact((input.identity ?? {}) as Record<string, JsonValue | undefined>),\n eventId: input.eventId,\n ...(input.eventType ? { eventType: input.eventType } : {}),\n ...(input.journeyId ? { journeyId: input.journeyId } : {}),\n };\n\n return payload as EventPayload;\n}\n","import { compact, XeniaApi } from \"../core/api\";\nimport { buildEventPayload } from \"../core/event-payload\";\nimport { generateUlid, toEventId } from \"../core/id\";\nimport type {\n AnalyticsContext,\n AnalyticsEventName,\n CallerIdentity,\n AnalyticsIngestResponse,\n ConsentState,\n EventContext,\n EventIdentity,\n IdentifyRequest,\n IdentifyResponse,\n JsonValue,\n ResolveBatchItem,\n ResolveBatchResult,\n ResolveOptions,\n ResolveResult,\n WebhookResponse,\n XeniaConfig,\n XeniaEvent,\n} from \"../core/types\";\n\n/**\n * Extra per-call identity/context for server-side webhook calls — an override on top of whatever the\n * client already carries.\n *\n * There's no ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM params the way\n * the browser client does, so bind them ONCE per request via {@link XeniaConfig.context} (see\n * `contextFromUrl`) and every call attaches them automatically. These per-call fields are for the\n * remainder: values known only at this call site, or a deliberate override of the ambient ones.\n */\nexport interface ServerWebhookOptions {\n method?: \"GET\" | \"POST\";\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n}\n\n/**\n * Options for a server-side unified event (`POST /api/events/v1`). There's no\n * ambient request context on the server — pass whatever's known at the call\n * site (e.g. pathname/user-agent from the current request, session id from a\n * cookie) via `identity`/`context`.\n */\nexport interface ServerTrackOptions {\n /** When true, also match/advance a journey (never sampled/shed). Default false. */\n trigger?: boolean;\n /** Stable dedup key (e.g. `\"ord-1001\"`) for idempotent conversions. */\n eventId?: string;\n eventVersion?: number;\n occurredAtMs?: number;\n /** Origin tag. Default `\"xenia-server-sdk\"`. */\n source?: string;\n /** Identity fields for this event (except the SDK-owned `xeniaVisitorId`,\n * which comes from `config.visitorId` and can't be set per call). */\n identity?: CallerIdentity;\n context?: AnalyticsContext;\n properties?: Record<string, JsonValue | undefined>;\n consent?: ConsentState;\n}\n\n/**\n * Server-native Xenia client. Same method names as the browser client, but\n * every call is stateless: identity and context are passed explicitly rather\n * than read from the DOM/localStorage. Uses global `fetch` (Node ≥18).\n */\nexport class XeniaServer {\n readonly api: XeniaApi;\n /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */\n private readonly visitorId?: string;\n /** Ambient request context attached to every call — see {@link XeniaConfig.context}. */\n private readonly context?: EventContext;\n\n constructor(config: XeniaConfig) {\n this.api = new XeniaApi(config);\n this.visitorId = config.visitorId;\n this.context = config.context;\n }\n\n /**\n * Send a unified event server-side (`POST /api/events/v1`) and return the\n * ingest response (including per-result `triggered`). `opts.trigger: true`\n * also matches/advances a journey; pass `opts.eventId` (e.g. `\"ord-1001\"`)\n * as a stable dedup key for idempotent conversions.\n */\n async track(\n eventName: AnalyticsEventName,\n opts: ServerTrackOptions = {},\n ): Promise<AnalyticsIngestResponse> {\n const event: XeniaEvent = {\n eventName,\n eventId: opts.eventId ? toEventId(opts.eventId) : generateUlid(),\n eventVersion: opts.eventVersion ?? 1,\n occurredAtMs: opts.occurredAtMs ?? Date.now(),\n source: opts.source ?? \"xenia-server-sdk\",\n identity: {\n ...opts.identity,\n // SDK-owned, set LAST so it can't be overridden per call. Comes from\n // `config.visitorId` (bind it per request from the `xenia_vid` cookie).\n xeniaVisitorId: this.visitorId,\n },\n context: opts.context,\n properties: opts.properties,\n consent: opts.consent,\n trigger: opts.trigger === true ? true : undefined,\n };\n return this.api.sendEvents([event]);\n }\n\n /**\n * Send a webhook request and await the synchronous response. Merges\n * `opts.identity`/`opts.context` into the payload the same way the browser\n * client's auto-attached fields do (`path`, `query`, `url`, `referrer`,\n * `deviceId`, `visitorId`, etc.) — see `ServerWebhookOptions`.\n */\n async webhook(\n triggerId: string,\n data?: Record<string, JsonValue | undefined>,\n opts: ServerWebhookOptions = {},\n ): Promise<WebhookResponse> {\n const payload = buildEventPayload({\n eventId: triggerId,\n journeyId: opts.journeyId,\n // SDK-owned visitor anchor wins: config.visitorId (bind the `xenia_vid`\n // cookie per request) is attached automatically. Falls back to a\n // per-call visitorId only when none is bound.\n identity: { ...opts.identity, visitorId: this.visitorId ?? opts.identity?.visitorId },\n // Ambient request context (config.context, bound once per request) under a per-call\n // override — same precedence resolve() uses, so both surfaces carry the same fields.\n context: { ...this.context, ...opts.context },\n props: data,\n });\n return this.api.webhook(triggerId, payload as JsonValue, opts.method ?? \"POST\");\n }\n\n /** Bind visitor→user server-side — `POST /api/events/v1/identify`. */\n async identify(body: IdentifyRequest): Promise<IdentifyResponse> {\n return this.api.identify(body);\n }\n\n /**\n * Resolve in-entry content personalization for one content key\n * (`POST /api/personalization/resolve`). Requires a configured SDK token\n * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the\n * returned `content` is server-spliced.\n *\n * Pass `opts.identity`/`opts.context` to attach the same SDK-provided\n * fields (`deviceId`, `customerId`, `email`, `path`, `url`, `referrer`,\n * `utm*`, …) the browser client collects ambiently — there's no ambient\n * `window`/`document` server-side, so a server caller must supply whatever\n * it knows (e.g. from the current request) explicitly. See\n * {@link ResolveOptions}.\n */\n async resolve(contentKey: string, opts?: ResolveOptions): Promise<ResolveResult> {\n return this.api.resolve(contentKey, this.withVisitor(opts));\n }\n\n /** Resolve several content keys in one round-trip (`POST /api/personalization/resolve-batch`). */\n async resolveBatch(\n items: ResolveBatchItem[],\n opts?: ResolveOptions,\n ): Promise<ResolveBatchResult[]> {\n return this.api.resolveBatch(items, this.withVisitor(opts));\n }\n\n /**\n * Merge the ambient `config.context` and `opts.identity`/`opts.context` into\n * the resolve `data`, then stamp the SDK-owned visitor id\n * (`config.visitorId`) under both the reserved `_xenia_vid` key (read by the\n * backend for holdout/exposure bucketing) and the flat `visitorId` field —\n * mirrors `webhook()`'s merge order/precedence exactly: caller `data` <\n * ambient `config.context` < caller `context`/`identity` < SDK-owned\n * `visitorId`/`_xenia_vid`, set LAST so neither can be overridden per call.\n *\n * `config.context` is what makes the SDK-provided fields automatic on the\n * server: bound once per request, every `resolve()` carries `path`/`query`/\n * `url`/`referrer`/UTMs with no per-call wiring, matching what the browser\n * client collects from `window` on its own. A no-op when nothing is bound and\n * nothing was passed — preserving today's behavior for callers using neither.\n */\n private withVisitor(opts?: ResolveOptions): ResolveOptions | undefined {\n const identity = compact({\n ...opts?.identity,\n visitorId: this.visitorId ?? opts?.identity?.visitorId,\n });\n const merged = {\n ...compact((this.context ?? {}) as Record<string, JsonValue | undefined>),\n ...compact((opts?.context ?? {}) as Record<string, JsonValue | undefined>),\n ...identity,\n };\n if (Object.keys(merged).length === 0 && !this.visitorId) return opts;\n if (this.visitorId) merged._xenia_vid = this.visitorId;\n return { ...opts, data: { ...(opts?.data ?? {}), ...merged } };\n }\n}\n\n/** Create a server-native client. */\nexport function createXeniaServer(config: XeniaConfig): XeniaServer {\n return new XeniaServer(config);\n}\n","import { HttpClient } from \"../core/http-client\";\nimport type { JsonObject } from \"../core/types\";\n\nexport interface RefreshTokenOptions {\n /**\n * Xenia base URL. Defaults to the hosted engine,\n * `https://engine.xeniamartech.com/xenia` — omit unless self-hosting.\n */\n baseUrl?: string;\n /**\n * The personalization SDK token created once in the dashboard (API Tokens →\n * Create token). Stays server-side; the browser never sees it — only the\n * short-lived token this exchanges it for does.\n */\n sdkToken: string;\n /** Lifetime of the returned token, in minutes. Default 15, capped server-side at 60. */\n ttlMinutes?: number;\n timeout?: number;\n}\n\nexport interface RefreshedToken {\n token: string;\n expiresAt?: string;\n}\n\n/**\n * Exchange the long-lived personalization SDK token for a short-lived one with\n * the same tenant/env scope, via `POST /api/personalization/token/refresh`.\n * Self-service — no dashboard credential needed, just the SDK token you\n * already have. Call this from your backend and hand the result to the\n * browser (e.g. from a token route the client SDK calls via `getToken`).\n */\nexport async function refreshSdkToken(opts: RefreshTokenOptions): Promise<RefreshedToken> {\n const http = new HttpClient({ baseUrl: opts.baseUrl, timeout: opts.timeout });\n const { data } = await http.request({\n method: \"POST\",\n path: \"/api/personalization/token/refresh\",\n headers: { Authorization: `Bearer ${opts.sdkToken}` },\n body: { ttlMinutes: opts.ttlMinutes ?? null },\n });\n const obj = (data ?? {}) as JsonObject;\n return {\n token: String(obj.token ?? \"\"),\n expiresAt: typeof obj.expiresAt === \"string\" ? obj.expiresAt : undefined,\n };\n}\n\n/**\n * Build a framework-agnostic request handler that hands the browser SDK a\n * personalization token — mount it at the endpoint `getToken` calls. Needs\n * only the SDK token you already created in the dashboard; mints a fresh\n * short-lived token per request so the long-lived one never reaches the\n * browser.\n *\n * @example\n * ```ts\n * export const GET = createTokenRoute({\n * sdkToken: process.env.XENIA_SDK_TOKEN!,\n * // baseUrl: process.env.XENIA_URL, // only to override the default hosted engine\n * });\n * ```\n */\nexport function createTokenRoute(config: RefreshTokenOptions): (request: Request) => Promise<Response> {\n return async (): Promise<Response> => {\n try {\n const refreshed = await refreshSdkToken(config);\n return new Response(JSON.stringify(refreshed), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"token refresh failed\";\n return new Response(JSON.stringify({ error: message }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n}\n","import {\n CONSENT_COOKIE,\n VISITOR_COOKIE,\n consentCookieName,\n visitorCookieName,\n} from \"../core/cookie-names\";\nimport type { ConsentState } from \"../core/types\";\n\n/**\n * Cookie names the SDK reads server-side (set by the browser SDK / your app).\n *\n * The constants are the DEFAULT-prefix names; the functions build the name for any prefix. If you\n * pass `config.prefix` to the browser client, pass the same prefix here — the browser namespaces\n * the cookie by it, so the default name won't be there to find.\n */\nexport { CONSENT_COOKIE, VISITOR_COOKIE, consentCookieName, visitorCookieName };\n\n/**\n * Parse a raw `Cookie` header into a map. Framework-agnostic so it works with\n * `Request.headers.get(\"cookie\")`, Node `req.headers.cookie`, etc.\n */\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!header) return out;\n for (const part of header.split(\";\")) {\n const idx = part.indexOf(\"=\");\n if (idx === -1) continue;\n const key = part.slice(0, idx).trim();\n const value = part.slice(idx + 1).trim();\n if (key) out[key] = decodeURIComponent(value);\n }\n return out;\n}\n\n/**\n * Read the visitor id the browser SDK wrote, so a server-side event can be bound to the same\n * visitor (`createXeniaServer({ visitorId })`) and attribute to a browser-entered journey.\n *\n * @param prefix Must match the browser client's `config.prefix`. The cookie is namespaced by it, so\n * a mismatch finds nothing and quietly leaves the server with no visitor.\n */\nexport function getVisitorId(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): string | null {\n return parseCookies(cookieHeader)[visitorCookieName(prefix)] ?? null;\n}\n\n/**\n * Read consent from a cookie header. Accepts a JSON blob or a comma-list of\n * granted scopes (e.g. `analytics,personalization`). Absent → all denied.\n *\n * @param prefix Must match the browser client's `config.prefix` — see {@link getVisitorId}.\n */\nexport function getConsent(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): ConsentState {\n const raw = parseCookies(cookieHeader)[consentCookieName(prefix)];\n if (!raw) return { analytics: false, marketing: false, personalization: false };\n try {\n const parsed = JSON.parse(raw) as ConsentState;\n return parsed;\n } catch {\n const scopes = new Set(raw.split(\",\").map((s) => s.trim()));\n return {\n analytics: scopes.has(\"analytics\"),\n marketing: scopes.has(\"marketing\"),\n personalization: scopes.has(\"personalization\"),\n };\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- var Xenia=(function(exports){'use strict';var G=new Set(["banner","popup","modal","inline"]),Y=new Set(["top-left","top-right","bottom-left","bottom-right","top","bottom"]),Z=new Set(["swap","hide","show","setContent","redirect",...G]);function V(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n){return typeof n=="string"?n:void 0}function ee(n){return typeof n=="number"?n:void 0}function te(n){if(!V(n))return null;let e=d(n.type);if(!e||!Z.has(e))return null;if(e==="redirect"){let i=d(n.url);return i?{type:e,url:i}:null}if(e==="hide"||e==="show"){let i=d(n.target);return i?{type:e,target:i}:null}if(e==="swap"||e==="setContent"){let i=d(n.target);return i?{type:e,target:i,html:d(n.html),text:d(n.text)}:null}let t=V(n.cta)?{label:d(n.cta.label)??"",url:d(n.cta.url),event:d(n.cta.event)}:void 0;return {type:e,target:d(n.target),title:d(n.title),message:d(n.message),imageUrl:d(n.imageUrl),html:d(n.html),cta:t&&t.label?t:void 0,dismissAfterMs:ee(n.dismissAfterMs),position:ne(n.position)}}function ne(n){let e=d(n);return e&&Y.has(e)?e:void 0}function _(n){let e;if(Array.isArray(n)?e=n:V(n)&&Array.isArray(n.xeniaActions)&&(e=n.xeniaActions),!Array.isArray(e))return [];let t=[];for(let i of e){let s=te(i);s&&t.push(s);}return t}var ie="https://engine.xeniamartech.com/xenia";function x(){return typeof window<"u"&&typeof document<"u"}function se(n,e){if(!e||Object.keys(e).length===0)return n;let t=new URLSearchParams(e),i=n.includes("?")?"&":"?";return `${n}${i}${t.toString()}`}function z(n){return new Promise(e=>setTimeout(e,n))}var m=class extends Error{constructor(t,i,s){super(s??`Request failed with status ${t}`);this.status=t;this.data=i;this.name="HttpError";}status;data},b=class{baseUrl;defaultHeaders;timeout;retry;debug;constructor(e){this.baseUrl=(e.baseUrl??ie).replace(/\/+$/,""),this.defaultHeaders=e.defaultHeaders??{},this.timeout=e.timeout??8e3,this.retry={attempts:e.retry?.attempts??2,baseDelayMs:e.retry?.baseDelayMs??300},this.debug=e.debug??false;}async request(e){let t=se(this.baseUrl+e.path,e.query),i=e.method??"GET",s={"Content-Type":"application/json",...this.defaultHeaders,...e.headers},r=e.body!==void 0?JSON.stringify(e.body):void 0,o=e.timeout??this.timeout,a=e.noRetry?1:(e.retry?.attempts??this.retry.attempts)+1,l=e.retry?.baseDelayMs??this.retry.baseDelayMs,P;for(let h=0;h<a;h++)try{let u=await this.fetchWithTimeout(t,{method:i,headers:s,body:r,...e.keepalive?{keepalive:!0}:{}},o),f=await this.parseBody(u);if(u.ok)return {response:u,data:f};if(this.isRetryableStatus(u.status)&&h<a-1){let D=this.retryAfterMs(u,l,h);this.log(`retrying ${e.path} after ${D}ms (status ${u.status})`),await z(D);continue}throw new m(u.status,f)}catch(u){if(P=u,u instanceof m)throw u;if(h<a-1){let f=l*2**h;this.log(`retrying ${e.path} after ${f}ms (network error)`),await z(f);continue}}throw P instanceof Error?P:new Error("Request failed")}async fetchWithTimeout(e,t,i){let s=new AbortController,r=setTimeout(()=>s.abort(),i);try{return await fetch(e,{...t,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`Request timeout after ${i}ms`,{cause:o}):o}finally{clearTimeout(r);}}async parseBody(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}isRetryableStatus(e){return e===429||e>=500&&e<=599}retryAfterMs(e,t,i){let s=e.headers.get("Retry-After");if(s){let r=Number(s);if(!Number.isNaN(r))return r*1e3}return t*2**i}log(e){this.debug&&console.warn(`[xenia] ${e}`);}};function re(n){try{let e=n.split(".")[1];if(!e)return;let t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}var w=class{config;cached=null;inflight=null;constructor(e){this.config=e;}hasSource(){return !!(this.config.token||this.config.getToken)}getToken=async()=>{if(this.config.token&&!this.config.getToken)return this.config.token;let e=Date.now();if(this.cached&&this.cached.expiresAt>e)return this.cached.token;if(this.inflight)return this.inflight;if(!this.config.getToken)throw new Error("No token source: set config.token or config.getToken.");return this.inflight=Promise.resolve(this.config.getToken()).then(t=>{let i=re(t),s=i?i-3e4:e+5*6e4;return this.cached={token:t,expiresAt:s},t}).finally(()=>{this.inflight=null;}),this.inflight}};function J(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}var k=class{http;tenantId;environmentKey;tokenProvider;constructor(e){this.tenantId=e.tenantId,this.environmentKey=e.environmentKey,this.tokenProvider=new w(e),this.http=new b({baseUrl:e.baseUrl,defaultHeaders:e.headers,timeout:e.timeout,retry:e.retry,debug:e.debug});}tenantHeaders(){return {"X-Tenant-Id":this.tenantId,"X-Environment":this.environmentKey}}async authHeaders(){let e=this.tenantHeaders();if(!this.tokenProvider.hasSource())return e;let t=await this.tokenProvider.getToken();return t&&(e.Authorization=`Bearer ${t}`),e}async webhook(e,t,i="POST"){let{response:s,data:r}=await this.http.request({method:i,path:"/flow",query:{id:e},headers:await this.authHeaders(),body:i==="POST"?t??{}:void 0,noRetry:true});return {status:s.status,body:r,actions:_(r),receivedAt:Date.now()}}async sendEvents(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1",headers:await this.authHeaders(),body:{events:e},keepalive:t?.keepalive});return i}async identify(e){let{data:t}=await this.http.request({method:"POST",path:"/api/events/v1/identify",headers:await this.authHeaders(),body:e});return t}async consent(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1/consent",headers:await this.authHeaders(),body:J({xeniaVisitorId:e,analytics:t.analytics===true,marketing:t.marketing===true,personalization:t.personalization===true,consentSource:t.consentSource,consentVersion:t.consentVersion})});return i}async resolve(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:J({contentKey:e,data:t.data,locale:t.locale})});return i}async resolveBatch(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve-batch",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:J({items:e,data:t.data,locale:t.locale})});return i}};var oe=new Set(["eventId","eventType","journeyId","deviceId","visitorId","customerId","email","utmSource","utmMedium","utmCampaign","utmContent","utmId","url","referrer","path","query"]);function L(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}function j(n){let e={},t={};if(n.props)for(let[s,r]of Object.entries(n.props))r!==void 0&&(oe.has(s)?t[s]=r:e[s]=r);return {...e,...t,...L(n.context??{}),...L(n.identity??{}),eventId:n.eventId,...n.eventType?{eventType:n.eventType}:{},...n.journeyId?{journeyId:n.journeyId}:{}}}var g="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ae(n){let e=new Uint8Array(n);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<n;t++)e[t]=Math.floor(Math.random()*256);return e}function v(n=Date.now()){let e="",t=n;for(let r=9;r>=0;r--)e=g[t%32]+e,t=Math.floor(t/32);let i=ae(16),s="";for(let r=0;r<16;r++)s+=g[i[r]%32];return e+s}var H=26;function B(n){if(n.length<=H)return n;let e="";for(let i of [2166136261,16777619]){let s=i>>>0;for(let r=0;r<n.length;r++)s^=n.charCodeAt(r),s=Math.imul(s,16777619)>>>0,e+=g[s%32];}let t="";for(let i=0;i<H;i++){let s=i+1;for(let r=i;r<e.length;r+=H)s=s*31+g.indexOf(e[r])>>>0;t+=g[s%32];}return t}var I=class{map=new Map;set(e,t){this.map.set(e,t);}get(e){return this.map.get(e)}keys(){return [...this.map.keys()]}clear(){this.map.clear();}},S=class{nsKey;constructor(e="xenia"){this.nsKey=`${e}_responses`;}read(){try{let e=localStorage.getItem(this.nsKey);return e?JSON.parse(e):{}}catch{return {}}}write(e){try{localStorage.setItem(this.nsKey,JSON.stringify(e));}catch{}}set(e,t){let i=this.read();i[e]=t,this.write(i);}get(e){return this.read()[e]}keys(){return Object.keys(this.read())}clear(){try{localStorage.removeItem(this.nsKey);}catch{}}};var C=class{queue=[];send;batchSize;flushIntervalMs;maxQueueSize;debug;timer=null;flushing=false;listenersAttached=false;allowed=false;onPageHide=()=>this.flushOnUnload();onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flushOnUnload();};constructor(e){this.send=e.send,this.batchSize=e.batchSize??20,this.flushIntervalMs=e.flushIntervalMs??3e3,this.maxQueueSize=e.maxQueueSize??200,this.debug=e.debug??false;}start(){this.allowed=true,!(this.timer||typeof window>"u")&&(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=true);}stop(){this.allowed=false,this.timer&&clearInterval(this.timer),this.timer=null,this.listenersAttached&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=false);}enqueue(e){this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(e),this.allowed&&this.queue.length>=this.batchSize&&this.flush();}async sendImmediate(e){try{await this.send([e],{keepalive:!0});}catch(t){this.isPermanentFailure(t)||this.requeue([e]),this.debug&&console.warn("[xenia] immediate send failed",t);}}async flush(){if(!this.allowed||this.flushing||this.queue.length===0)return;this.flushing=true;let e=this.queue.splice(0,this.batchSize);try{await this.send(e);}catch(t){this.isPermanentFailure(t)||this.requeue(e),this.debug&&console.warn("[xenia] analytics flush failed",t);}finally{this.flushing=false;}}isPermanentFailure(e){return e instanceof m&&e.status>=400&&e.status<500}flushOnUnload(){if(!this.allowed||this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length);this.send(e,{keepalive:true}).catch(()=>{});}requeue(e){let t=this.maxQueueSize-this.queue.length;t<=0||this.queue.unshift(...e.slice(0,t));}};var le=new Set(["click","view-port","page-load"]);function U(n){let e=n.indexOf("&");if(e===-1)return null;let t=n.slice(0,e),i=n.slice(e+1);return !t||!le.has(i)?null:{eventId:t,interactionType:i}}function Q(n){let e=n.getAttribute("data-xenia-content-key");if(!e)return null;let t=n.getAttribute("data-xenia-content-entry-id"),i=n.getAttribute("data-xenia-base-entry-id"),s=n.getAttribute("data-xenia-personalized");return {contentKey:e,contentEntryId:t??void 0,baseEntryId:i??void 0,personalized:s==null?void 0:s==="true"}}var E=class{opts;throttleTimers=new Map;observers=new Map;slotObservers=new Map;triggered=new Set;slotImpressed=new Set;clickHandler=null;mutationObserver=null;constructor(e){this.opts=e;}start(){this.setupClicks(),this.scan(document),this.setupMutations();}stop(){this.clickHandler&&document.removeEventListener("click",this.clickHandler),this.clickHandler=null,this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observers.forEach(e=>e.disconnect()),this.observers.clear(),this.slotObservers.forEach(e=>e.disconnect()),this.slotObservers.clear(),this.throttleTimers.clear(),this.triggered.clear(),this.slotImpressed.clear();}attr(){return `data-${this.opts.prefix}`}throttled(e){if(this.opts.throttleMs<=0)return false;let t=Date.now(),i=this.throttleTimers.get(e)??0;return t-i>=this.opts.throttleMs?(this.throttleTimers.set(e,t),false):true}setupClicks(){let e=this.attr();this.clickHandler=t=>{let i=t.target;if(!i)return;let s=i.closest(`[${e}]`);if(s){let r=s.getAttribute(e),o=r?U(r):null;o&&o.interactionType==="click"&&!this.throttled(s)&&this.opts.fire(o.eventId,"click");}if(this.opts.fireSlot){let r=i.closest("[data-xenia-slot]");if(r){let o=Q(r);o&&!this.throttled(r)&&this.opts.fireSlot("click",o);}}},document.addEventListener("click",this.clickHandler);}observeSlot(e){if(!this.opts.fireSlot||this.slotObservers.has(e))return;let t=Q(e);if(!t)return;let i=this.opts.fireSlot,{threshold:s,rootMargin:r}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(this.slotImpressed.has(e)||(this.slotImpressed.add(e),i("impression",t),o.disconnect(),this.slotObservers.delete(e)));},{threshold:s,rootMargin:r});o.observe(e),this.slotObservers.set(e,o);}observeViewport(e,t){if(this.observers.has(e))return;let{threshold:i,rootMargin:s,triggerOnce:r}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(r&&this.triggered.has(e)||this.throttled(e)||(this.opts.fire(t,"view-port"),r&&(this.triggered.add(e),o.disconnect(),this.observers.delete(e))));},{threshold:i,rootMargin:s});o.observe(e),this.observers.set(e,o);}handleElement(e){let t=e.getAttribute(this.attr());if(!t)return;let i=U(t);i&&(i.interactionType==="view-port"?this.observeViewport(e,i.eventId):i.interactionType==="page-load"&&this.opts.fire(i.eventId,"page-load"));}scan(e){e.querySelectorAll(`[${this.attr()}]`).forEach(t=>this.handleElement(t)),this.opts.fireSlot&&e.querySelectorAll("[data-xenia-slot]").forEach(t=>this.observeSlot(t));}setupMutations(){this.mutationObserver=new MutationObserver(e=>{for(let t of e)for(let i of t.addedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;let s=i;this.handleElement(s),this.opts.fireSlot&&s.matches("[data-xenia-slot]")&&this.observeSlot(s),this.scan(s);}}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}};var R="xenia";function q(n=R){return `${n||R}_vid`}var ue=1800*1e3,M=class{prefix;cookie;deviceId=null;journeyId=null;sessionId=null;constructor(e="xenia",t=true){this.prefix=e,this.cookie=ce(t);}key(e){return `${this.prefix}_${e}`}cookieName(){return q(this.prefix)}writeVisitorCookie(e){if(!(!this.cookie||!e))try{if(typeof document>"u")return;let t=[`${this.cookieName()}=${encodeURIComponent(e)}`,"path=/",`max-age=${Math.floor(this.cookie.maxAgeDays*86400)}`,`SameSite=${this.cookie.sameSite}`];this.cookie.domain&&t.push(`domain=${this.cookie.domain}`),this.cookie.secure&&t.push("Secure"),document.cookie=t.join("; ");}catch{}}async resolveDeviceId(){if(this.deviceId)return this.writeVisitorCookie(this.getVisitorId()??this.deviceId),this.deviceId;let e=this.key("device_id");try{let i=localStorage.getItem(e);if(i)return this.deviceId=i,this.writeVisitorCookie(this.getVisitorId()??i),i}catch{}let t=await this.mediaDeviceId();t||(t=await this.fingerprint()),this.deviceId=t;try{localStorage.setItem(e,t);}catch{}return this.writeVisitorCookie(this.getVisitorId()??t),t}getDeviceId(){return this.deviceId}async mediaDeviceId(){try{if(!navigator.mediaDevices?.enumerateDevices)return null;let e=await navigator.mediaDevices.enumerateDevices();return (e.find(i=>i.kind==="videoinput"&&i.deviceId)||e.find(i=>i.kind==="audioinput"&&i.deviceId)||e.find(i=>i.kind==="audiooutput"&&i.deviceId))?.deviceId||null}catch{return null}}async fingerprint(){let e=[navigator.userAgent,navigator.language,screen.width,screen.height,screen.colorDepth,new Date().getTimezoneOffset()].join("|"),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}identify(e){if(e){try{localStorage.setItem(this.key("visitor_id"),e);}catch{}this.writeVisitorCookie(e);}}getVisitorId(){try{return localStorage.getItem(this.key("visitor_id"))}catch{return null}}getSessionId(){let e=this.key("session_id"),t=this.key("session_last_activity"),i=Date.now();try{let s=sessionStorage.getItem(e),r=Number(sessionStorage.getItem(t)),a=s&&Number.isFinite(r)&&i-r<ue?s:v(i);return sessionStorage.setItem(e,a),sessionStorage.setItem(t,String(i)),this.sessionId=a,a}catch{return this.sessionId||(this.sessionId=v(i)),this.sessionId}}setJourneyId(e){this.journeyId=e&&e.trim()?e.trim():null;}getJourneyId(){return this.journeyId||this.utmParam("utm_id")||null}utmParam(e){try{let t=new URLSearchParams(window.location.search).get(e);if(t){try{sessionStorage.setItem(this.key(e),t);}catch{}return t}try{return sessionStorage.getItem(this.key(e))}catch{}}catch{}return null}collectContext(){let e={},t=this.utmParam("utm_source"),i=this.utmParam("utm_medium"),s=this.utmParam("utm_campaign"),r=this.utmParam("utm_content"),o=this.utmParam("utm_id");t&&(e.utmSource=t),i&&(e.utmMedium=i),s&&(e.utmCampaign=s),r&&(e.utmContent=r),o&&(e.utmId=o);try{e.url=window.location.href,e.path=window.location.pathname,e.query=Object.fromEntries(new URLSearchParams(window.location.search)),document.referrer&&(e.referrer=document.referrer);}catch{}let a=this.getVisitorId();return a&&(e.visitorId=a),e}};function ce(n){if(n===false)return null;let e=n===true?{}:n,t=e.sameSite??"Lax",i=t==="None"?true:e.secure??false;return {sameSite:t,secure:i,maxAgeDays:e.maxAgeDays??365,domain:e.domain}}function O(n,e=document){if(!n)return null;let t=e.querySelector(`[data-xenia-slot="${pe(n)}"]`);if(t)return t;try{return e.querySelector(n)}catch{return null}}function pe(n){let e=window;return e.CSS?.escape?e.CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function A(n,e){let t=O(n);return t?(e.html!==void 0?t.innerHTML=e.html:e.text!==void 0&&(t.textContent=e.text),t.removeAttribute("hidden"),true):false}function X(n){let e=O(n);return !e||!(e instanceof HTMLElement)?false:(e.dataset.xeniaHidden="1",e.style.setProperty("display","none","important"),true)}function $(n){let e=O(n);return !e||!(e instanceof HTMLElement)?false:(delete e.dataset.xeniaHidden,e.style.removeProperty("display"),true)}var he=new Set(["banner","popup","modal","inline"]);function me(n){return he.has(n)}var T=class{host=null;shadow=null;onCta;messageTemplate;messageStyles;messageComponent;mounted=new Map;constructor(e,t){this.onCta=e,this.messageTemplate=t?.messageTemplate,this.messageStyles=t?.messageStyles,this.messageComponent=t?.messageComponent;}apply(e){let t=0;for(let i of e)this.applyOne(i)&&t++;return t}applyOne(e){switch(e.type){case "swap":return A(e.target,{html:e.html,text:e.text});case "setContent":return A(e.target,{html:e.html,text:e.text});case "hide":return X(e.target);case "show":return $(e.target);case "redirect":try{return window.location.assign(e.url),!0}catch{return false}default:return me(e.type)?this.renderMessage(e):false}}destroy(){this.mounted.forEach(e=>e()),this.mounted.clear(),this.host?.remove(),this.host=null,this.shadow=null;}ensureShadow(){if(this.shadow)return this.shadow;let e=document.createElement("div");e.setAttribute("data-xenia-ui",""),document.body.appendChild(e);let t=e.attachShadow({mode:"open"});return t.appendChild(this.styleEl()),this.host=e,this.shadow=t,t}styleEl(){let e=document.createElement("style");return e.textContent=this.messageStyles?`${K}
2
- ${this.messageStyles}`:K,e}renderMessage(e){let t=e.html===void 0&&!!this.messageComponent;if(e.type==="inline"){if(!e.target)return false;let l=O(e.target);return l?(this.unmount(l),t?(l.innerHTML="",this.mountComponent(l,e,"inline",()=>this.unmount(l))):(l.innerHTML=this.cardHtml(e,"inline"),this.wireCard(l,e)),true):false}let i=this.ensureShadow(),s=document.createElement("div"),r=this.positionClass(e.type,e.position),o=e.html!==void 0?" xenia-custom-bg":"";s.className=`xenia-msg xenia-${e.type}${r?` ${r}`:""}${o}`,i.appendChild(s);let a=()=>{this.unmount(s),s.remove();};return t?this.mountComponent(s,e,e.type,a):(s.innerHTML=this.cardHtml(e,e.type),this.wireCard(s,e,a)),e.dismissAfterMs&&e.dismissAfterMs>0&&setTimeout(a,e.dismissAfterMs),true}mountComponent(e,t,i,s){if(!this.messageComponent)return;let r={action:t,variant:i,close:s,fireCta:()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),s();}},o=this.messageComponent(e,r);o&&this.mounted.set(e,o);}unmount(e){let t=this.mounted.get(e);t&&(t(),this.mounted.delete(e));}positionClass(e,t){return e==="popup"?`xenia-pos-${t==="top-left"||t==="top-right"||t==="bottom-left"?t:"bottom-right"}`:e==="banner"?`xenia-pos-${t==="top"?"top":"bottom"}`:""}cardHtml(e,t){if(e.html!==void 0)return fe(e.html,t);if(this.messageTemplate){let l={action:e,variant:t,escapeHtml:y,escapeAttr:W};return this.messageTemplate(l)}let i=e.imageUrl?`<img class="xenia-img" src="${W(e.imageUrl)}" alt="" />`:"",s=e.title?`<div class="xenia-title">${y(e.title)}</div>`:"",r=e.message?`<div class="xenia-body">${y(e.message)}</div>`:"",o=e.cta?`<button class="xenia-cta" type="button">${y(e.cta.label)}</button>`:"";return `<div class="xenia-card">${t==="inline"?"":'<button class="xenia-close" type="button" aria-label="Close">\xD7</button>'}${i}<div class="xenia-content">${s}${r}${o}</div></div>`}wireCard(e,t,i){i&&e.querySelectorAll(".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]").forEach(o=>{o.removeAttribute("onclick"),o.addEventListener("click",i);}),e.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach(r=>{r instanceof HTMLElement&&r.children.length===0&&!r.textContent?.trim()&&(r.style.opacity="0.5");});let s=e.querySelector(".xenia-cta, [data-xenia-cta]");s&&t.cta&&s.addEventListener("click",()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),i?.();});}};function fe(n,e){return e==="modal"?`<div class="xenia-custom-html">${n}</div>`:`<div class="xenia-custom-html"><style>.xenia-custom-html{position:relative}.xenia-custom-html>*{position:static!important;inset:auto!important;top:auto!important;right:auto!important;bottom:auto!important;left:auto!important}</style>${n}</div>`}function y(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function W(n){return y(n).replace(/"/g,"&quot;")}var K=`
1
+ var Xenia=(function(exports){'use strict';var We=new Set(["banner","popup","modal","inline"]),He=new Set(["top-left","top-right","bottom-left","bottom-right","top","bottom"]),Ve=new Set(["standard","spin-wheel"]),Le=new Set(["swap","hide","show","setContent","redirect",...We]);function S(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function c(n){return typeof n=="string"?n:void 0}function le(n){return typeof n=="number"?n:void 0}function $e(n){if(!S(n))return null;let e=c(n.type);if(!e||!Le.has(e))return null;if(e==="redirect"){let i=c(n.url);return i?{type:e,url:i}:null}if(e==="hide"||e==="show"){let i=c(n.target);return i?{type:e,target:i}:null}if(e==="swap"||e==="setContent"){let i=c(n.target);return i?{type:e,target:i,html:c(n.html),text:c(n.text)}:null}let t=S(n.cta)?{label:c(n.cta.label)??"",url:c(n.cta.url),event:c(n.cta.event)}:void 0;return {type:e,target:c(n.target),title:c(n.title),message:c(n.message),imageUrl:c(n.imageUrl),html:c(n.html),cta:t&&(t.label||t.url)?t:void 0,dismissAfterMs:le(n.dismissAfterMs),position:qe(n.position),widgetType:Je(n.widgetType),segments:De(n.segments),formSubmit:_e(n.formSubmit),style:ze(n.style),spinnerHtml:c(n.spinnerHtml),winHtml:c(n.winHtml),lossHtml:c(n.lossHtml)}}function qe(n){let e=c(n);return e&&He.has(e)?e:void 0}function Je(n){let e=c(n);return e&&Ve.has(e)?e:void 0}function De(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!S(t))continue;let i=c(t.id),r=c(t.label);!i||!r||e.push({id:i,label:r,colorHex:c(t.colorHex),isLoss:t.isLoss===true});}return e.length?e:void 0}function _e(n){if(!S(n))return;let e=c(n.mode);if(e)return {requiresResolve:n.requiresResolve===true,mode:e,flowRef:c(n.flowRef),bindingRef:c(n.bindingRef),successDisplayMs:le(n.successDisplayMs)}}function ze(n){if(!S(n))return;let e={hideCloseButton:n.hideCloseButton===true,hideOverlay:n.hideOverlay===true};return e.hideCloseButton||e.hideOverlay?e:void 0}function j(n){let e;if(Array.isArray(n)?e=n:S(n)&&Array.isArray(n.xeniaActions)&&(e=n.xeniaActions),!Array.isArray(e))return [];let t=[];for(let i of e){let r=$e(i);r&&t.push(r);}return t}var Fe="https://engine.xeniamartech.com/xenia";function W(){return typeof window<"u"&&typeof document<"u"}function Ne(n,e){if(!e||Object.keys(e).length===0)return n;let t=new URLSearchParams(e),i=n.includes("?")?"&":"?";return `${n}${i}${t.toString()}`}function de(n){return new Promise(e=>setTimeout(e,n))}var E=class extends Error{constructor(t,i,r){super(r??`Request failed with status ${t}`);this.status=t;this.data=i;this.name="HttpError";}status;data},O=class{baseUrl;defaultHeaders;timeout;retry;debug;constructor(e){this.baseUrl=(e.baseUrl??Fe).replace(/\/+$/,""),this.defaultHeaders=e.defaultHeaders??{},this.timeout=e.timeout??8e3,this.retry={attempts:e.retry?.attempts??2,baseDelayMs:e.retry?.baseDelayMs??300},this.debug=e.debug??false;}async request(e){let t=Ne(this.baseUrl+e.path,e.query),i=e.method??"GET",r={"Content-Type":"application/json",...this.defaultHeaders,...e.headers},s=e.body!==void 0?JSON.stringify(e.body):void 0,o=e.timeout??this.timeout,a=e.noRetry?1:(e.retry?.attempts??this.retry.attempts)+1,l=e.retry?.baseDelayMs??this.retry.baseDelayMs,u;for(let d=0;d<a;d++)try{let p=await this.fetchWithTimeout(t,{method:i,headers:r,body:s,...e.keepalive?{keepalive:!0}:{}},o),h=await this.parseBody(p);if(p.ok)return {response:p,data:h};if(this.isRetryableStatus(p.status)&&d<a-1){let I=this.retryAfterMs(p,l,d);this.log(`retrying ${e.path} after ${I}ms (status ${p.status})`),await de(I);continue}throw new E(p.status,h)}catch(p){if(u=p,p instanceof E)throw p;if(d<a-1){let h=l*2**d;this.log(`retrying ${e.path} after ${h}ms (network error)`),await de(h);continue}}throw u instanceof Error?u:new Error("Request failed")}async fetchWithTimeout(e,t,i){let r=new AbortController,s=setTimeout(()=>r.abort(),i);try{return await fetch(e,{...t,signal:r.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`Request timeout after ${i}ms`,{cause:o}):o}finally{clearTimeout(s);}}async parseBody(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}isRetryableStatus(e){return e===429||e>=500&&e<=599}retryAfterMs(e,t,i){let r=e.headers.get("Retry-After");if(r){let s=Number(r);if(!Number.isNaN(s))return s*1e3}return t*2**i}log(e){this.debug&&console.warn(`[xenia] ${e}`);}};function Xe(n){try{let e=n.split(".")[1];if(!e)return;let t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}var H=class{config;cached=null;inflight=null;constructor(e){this.config=e;}hasSource(){return !!(this.config.token||this.config.getToken)}getToken=async()=>{if(this.config.token&&!this.config.getToken)return this.config.token;let e=Date.now();if(this.cached&&this.cached.expiresAt>e)return this.cached.token;if(this.inflight)return this.inflight;if(!this.config.getToken)throw new Error("No token source: set config.token or config.getToken.");return this.inflight=Promise.resolve(this.config.getToken()).then(t=>{let i=Xe(t),r=i?i-3e4:e+5*6e4;return this.cached={token:t,expiresAt:r},t}).finally(()=>{this.inflight=null;}),this.inflight}};function ue(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Be(n){return n!==void 0&&ue(n)?n:void 0}function x(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}var V=class{http;tenantId;environmentKey;tokenProvider;constructor(e){this.tenantId=e.tenantId,this.environmentKey=e.environmentKey,this.tokenProvider=new H(e),this.http=new O({baseUrl:e.baseUrl,defaultHeaders:e.headers,timeout:e.timeout,retry:e.retry,debug:e.debug});}tenantHeaders(){return {"X-Tenant-Id":this.tenantId,"X-Environment":this.environmentKey}}async authHeaders(){let e=this.tenantHeaders();if(!this.tokenProvider.hasSource())return e;let t=await this.tokenProvider.getToken();return t&&(e.Authorization=`Bearer ${t}`),e}async webhook(e,t,i="POST"){let{response:r,data:s}=await this.http.request({method:i,path:"/flow",query:{id:e},headers:await this.authHeaders(),body:i==="POST"?t??{}:void 0,noRetry:true});return {status:r.status,body:s,actions:j(s),receivedAt:Date.now()}}async submitWidget(e,t){let{response:i,data:r}=await this.http.request({method:"POST",path:"/widget-submissions",query:{ref:e},headers:await this.authHeaders(),body:t??{},noRetry:true}),s=ue(r)?r:{};return {status:i.status,body:r,actions:j(r),prize:Be(s.prize),alreadyPlayed:s.alreadyPlayed===true,dispatched:s.dispatched===true,dispatchError:typeof s.dispatchError=="string"?s.dispatchError:void 0,widgetType:typeof s.widgetType=="string"?s.widgetType:void 0,receivedAt:Date.now()}}async sendEvents(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1",headers:await this.authHeaders(),body:{events:e},keepalive:t?.keepalive});return i}async identify(e){let{data:t}=await this.http.request({method:"POST",path:"/api/events/v1/identify",headers:await this.authHeaders(),body:e});return t}async consent(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1/consent",headers:await this.authHeaders(),body:x({xeniaVisitorId:e,analytics:t.analytics===true,marketing:t.marketing===true,personalization:t.personalization===true,consentSource:t.consentSource,consentVersion:t.consentVersion})});return i}async resolve(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:x({contentKey:e,data:t.data,locale:t.locale})});return i}async resolveBatch(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve-batch",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:x({items:e,data:t.data,locale:t.locale})});return i}};var je=new Set(["eventId","eventType","journeyId","deviceId","visitorId","customerId","email","utmSource","utmMedium","utmCampaign","utmContent","utmId","url","referrer","path","query"]);function ce(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}function pe(n){let e={},t={};if(n.props)for(let[r,s]of Object.entries(n.props))s!==void 0&&(je.has(r)?t[r]=s:e[r]=s);return {...e,...t,...ce(n.context??{}),...ce(n.identity??{}),eventId:n.eventId,...n.eventType?{eventType:n.eventType}:{},...n.journeyId?{journeyId:n.journeyId}:{}}}var A="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function Ue(n){let e=new Uint8Array(n);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<n;t++)e[t]=Math.floor(Math.random()*256);return e}function g(n=Date.now()){let e="",t=n;for(let s=9;s>=0;s--)e=A[t%32]+e,t=Math.floor(t/32);let i=Ue(16),r="";for(let s=0;s<16;s++)r+=A[i[s]%32];return e+r}var U=26;function me(n){if(n.length<=U)return n;let e="";for(let i of [2166136261,16777619]){let r=i>>>0;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619)>>>0,e+=A[r%32];}let t="";for(let i=0;i<U;i++){let r=i+1;for(let s=i;s<e.length;s+=U)r=r*31+A.indexOf(e[s])>>>0;t+=A[r%32];}return t}var L=class{map=new Map;set(e,t){this.map.set(e,t);}get(e){return this.map.get(e)}keys(){return [...this.map.keys()]}clear(){this.map.clear();}},$=class{nsKey;constructor(e="xenia"){this.nsKey=`${e}_responses`;}read(){try{let e=localStorage.getItem(this.nsKey);return e?JSON.parse(e):{}}catch{return {}}}write(e){try{localStorage.setItem(this.nsKey,JSON.stringify(e));}catch{}}set(e,t){let i=this.read();i[e]=t,this.write(i);}get(e){return this.read()[e]}keys(){return Object.keys(this.read())}clear(){try{localStorage.removeItem(this.nsKey);}catch{}}};var q=class{queue=[];send;batchSize;flushIntervalMs;maxQueueSize;debug;timer=null;flushing=false;listenersAttached=false;allowed=false;onPageHide=()=>this.flushOnUnload();onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flushOnUnload();};constructor(e){this.send=e.send,this.batchSize=e.batchSize??20,this.flushIntervalMs=e.flushIntervalMs??3e3,this.maxQueueSize=e.maxQueueSize??200,this.debug=e.debug??false;}start(){this.allowed=true,!(this.timer||typeof window>"u")&&(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=true);}stop(){this.allowed=false,this.timer&&clearInterval(this.timer),this.timer=null,this.listenersAttached&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=false);}enqueue(e){this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(e),this.allowed&&this.queue.length>=this.batchSize&&this.flush();}async sendImmediate(e){try{await this.send([e],{keepalive:!0});}catch(t){this.isPermanentFailure(t)||this.requeue([e]),this.debug&&console.warn("[xenia] immediate send failed",t);}}async flush(){if(!this.allowed||this.flushing||this.queue.length===0)return;this.flushing=true;let e=this.queue.splice(0,this.batchSize);try{await this.send(e);}catch(t){this.isPermanentFailure(t)||this.requeue(e),this.debug&&console.warn("[xenia] analytics flush failed",t);}finally{this.flushing=false;}}isPermanentFailure(e){return e instanceof E&&e.status>=400&&e.status<500}flushOnUnload(){if(!this.allowed||this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length);this.send(e,{keepalive:true}).catch(()=>{});}requeue(e){let t=this.maxQueueSize-this.queue.length;t<=0||this.queue.unshift(...e.slice(0,t));}};var Ke=new Set(["click","view-port","page-load"]);function he(n){let e=n.indexOf("&");if(e===-1)return null;let t=n.slice(0,e),i=n.slice(e+1);return !t||!Ke.has(i)?null:{eventId:t,interactionType:i}}function fe(n){let e=n.getAttribute("data-xenia-content-key");if(!e)return null;let t=n.getAttribute("data-xenia-content-entry-id"),i=n.getAttribute("data-xenia-base-entry-id"),r=n.getAttribute("data-xenia-personalized");return {contentKey:e,contentEntryId:t??void 0,baseEntryId:i??void 0,personalized:r==null?void 0:r==="true"}}var J=class{opts;throttleTimers=new Map;observers=new Map;slotObservers=new Map;triggered=new Set;slotImpressed=new Set;clickHandler=null;mutationObserver=null;constructor(e){this.opts=e;}start(){this.setupClicks(),this.scan(document),this.setupMutations();}stop(){this.clickHandler&&document.removeEventListener("click",this.clickHandler),this.clickHandler=null,this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observers.forEach(e=>e.disconnect()),this.observers.clear(),this.slotObservers.forEach(e=>e.disconnect()),this.slotObservers.clear(),this.throttleTimers.clear(),this.triggered.clear(),this.slotImpressed.clear();}attr(){return `data-${this.opts.prefix}`}throttled(e){if(this.opts.throttleMs<=0)return false;let t=Date.now(),i=this.throttleTimers.get(e)??0;return t-i>=this.opts.throttleMs?(this.throttleTimers.set(e,t),false):true}setupClicks(){let e=this.attr();this.clickHandler=t=>{let i=t.target;if(!i)return;let r=i.closest(`[${e}]`);if(r){let s=r.getAttribute(e),o=s?he(s):null;o&&o.interactionType==="click"&&!this.throttled(r)&&this.opts.fire(o.eventId,"click");}if(this.opts.fireSlot){let s=i.closest("[data-xenia-slot]");if(s){let o=fe(s);o&&!this.throttled(s)&&this.opts.fireSlot("click",o);}}},document.addEventListener("click",this.clickHandler);}observeSlot(e){if(!this.opts.fireSlot||this.slotObservers.has(e))return;let t=fe(e);if(!t)return;let i=this.opts.fireSlot,{threshold:r,rootMargin:s}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(this.slotImpressed.has(e)||(this.slotImpressed.add(e),i("impression",t),o.disconnect(),this.slotObservers.delete(e)));},{threshold:r,rootMargin:s});o.observe(e),this.slotObservers.set(e,o);}observeViewport(e,t){if(this.observers.has(e))return;let{threshold:i,rootMargin:r,triggerOnce:s}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(s&&this.triggered.has(e)||this.throttled(e)||(this.opts.fire(t,"view-port"),s&&(this.triggered.add(e),o.disconnect(),this.observers.delete(e))));},{threshold:i,rootMargin:r});o.observe(e),this.observers.set(e,o);}handleElement(e){let t=e.getAttribute(this.attr());if(!t)return;let i=he(t);i&&(i.interactionType==="view-port"?this.observeViewport(e,i.eventId):i.interactionType==="page-load"&&this.opts.fire(i.eventId,"page-load"));}scan(e){e.querySelectorAll(`[${this.attr()}]`).forEach(t=>this.handleElement(t)),this.opts.fireSlot&&e.querySelectorAll("[data-xenia-slot]").forEach(t=>this.observeSlot(t));}setupMutations(){this.mutationObserver=new MutationObserver(e=>{for(let t of e)for(let i of t.addedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;let r=i;this.handleElement(r),this.opts.fireSlot&&r.matches("[data-xenia-slot]")&&this.observeSlot(r),this.scan(r);}}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}};var D="xenia";function K(n=D){return `${n||D}_vid`}var Ge=1800*1e3,_=class{prefix;cookie;deviceId=null;journeyId=null;sessionId=null;constructor(e="xenia",t=true){this.prefix=e,this.cookie=Ye(t);}key(e){return `${this.prefix}_${e}`}cookieName(){return K(this.prefix)}writeVisitorCookie(e){if(!(!this.cookie||!e))try{if(typeof document>"u")return;let t=[`${this.cookieName()}=${encodeURIComponent(e)}`,"path=/",`max-age=${Math.floor(this.cookie.maxAgeDays*86400)}`,`SameSite=${this.cookie.sameSite}`];this.cookie.domain&&t.push(`domain=${this.cookie.domain}`),this.cookie.secure&&t.push("Secure"),document.cookie=t.join("; ");}catch{}}async resolveDeviceId(){if(this.deviceId)return this.writeVisitorCookie(this.getVisitorId()??this.deviceId),this.deviceId;let e=this.key("device_id");try{let i=localStorage.getItem(e);if(i)return this.deviceId=i,this.writeVisitorCookie(this.getVisitorId()??i),i}catch{}let t=await this.mediaDeviceId();t||(t=await this.fingerprint()),this.deviceId=t;try{localStorage.setItem(e,t);}catch{}return this.writeVisitorCookie(this.getVisitorId()??t),t}getDeviceId(){return this.deviceId}async mediaDeviceId(){try{if(!navigator.mediaDevices?.enumerateDevices)return null;let e=await navigator.mediaDevices.enumerateDevices();return (e.find(i=>i.kind==="videoinput"&&i.deviceId)||e.find(i=>i.kind==="audioinput"&&i.deviceId)||e.find(i=>i.kind==="audiooutput"&&i.deviceId))?.deviceId||null}catch{return null}}async fingerprint(){let e=[navigator.userAgent,navigator.language,screen.width,screen.height,screen.colorDepth,new Date().getTimezoneOffset()].join("|"),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}identify(e){if(e){try{localStorage.setItem(this.key("visitor_id"),e);}catch{}this.writeVisitorCookie(e);}}getVisitorId(){try{return localStorage.getItem(this.key("visitor_id"))}catch{return null}}setCustomerId(e){try{e?localStorage.setItem(this.key("customer_id"),e):localStorage.removeItem(this.key("customer_id"));}catch{}}getCustomerId(){try{return localStorage.getItem(this.key("customer_id"))}catch{return null}}setEmail(e){try{e?localStorage.setItem(this.key("email"),e):localStorage.removeItem(this.key("email"));}catch{}}getEmail(){try{return localStorage.getItem(this.key("email"))}catch{return null}}getSessionId(){let e=this.key("session_id"),t=this.key("session_last_activity"),i=Date.now();try{let r=sessionStorage.getItem(e),s=Number(sessionStorage.getItem(t)),a=r&&Number.isFinite(s)&&i-s<Ge?r:g(i);return sessionStorage.setItem(e,a),sessionStorage.setItem(t,String(i)),this.sessionId=a,a}catch{return this.sessionId||(this.sessionId=g(i)),this.sessionId}}setJourneyId(e){this.journeyId=e&&e.trim()?e.trim():null;}getJourneyId(){return this.journeyId||this.utmParam("utm_id")||null}utmParam(e){try{let t=new URLSearchParams(window.location.search).get(e);if(t){try{sessionStorage.setItem(this.key(e),t);}catch{}return t}try{return sessionStorage.getItem(this.key(e))}catch{}}catch{}return null}collectContext(){let e={},t=this.utmParam("utm_source"),i=this.utmParam("utm_medium"),r=this.utmParam("utm_campaign"),s=this.utmParam("utm_content"),o=this.utmParam("utm_id");t&&(e.utmSource=t),i&&(e.utmMedium=i),r&&(e.utmCampaign=r),s&&(e.utmContent=s),o&&(e.utmId=o);try{e.url=window.location.href,e.path=window.location.pathname,e.query=Object.fromEntries(new URLSearchParams(window.location.search)),document.referrer&&(e.referrer=document.referrer);}catch{}let a=this.getVisitorId();return a&&(e.visitorId=a),e}};function Ye(n){if(n===false)return null;let e=n===true?{}:n,t=e.sameSite??"Lax",i=t==="None"?true:e.secure??false;return {sameSite:t,secure:i,maxAgeDays:e.maxAgeDays??365,domain:e.domain}}function z(n){let e={};return n.querySelectorAll("[data-xenia-field]").forEach(t=>{let i=t.getAttribute("data-xenia-field");i&&(e[i]=Ze(t));}),e}function Ze(n){return n instanceof HTMLInputElement?n.type==="checkbox"?n.checked?n.value||"on":"":n.type==="radio"?n.checked?n.value:"":n.value:n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?n.value:n.textContent?.trim()??""}function ge(n,e){n&&(n instanceof HTMLButtonElement||n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement||n instanceof HTMLFieldSetElement?n.disabled=e:e?n.setAttribute("aria-disabled","true"):n.removeAttribute("aria-disabled"));}function Q(n,e){let t=n.querySelector("[data-xenia-error]");t&&(t.textContent=e);}var ye="xenia-form-submit-style";function et(n){if(n.querySelector(`#${ye}`))return;let e=document.createElement("style");e.id=ye,e.textContent="@keyframes xenia-submit-spin{to{transform:rotate(360deg)}}[data-xenia-submitting]::after{content:'';display:inline-block;width:0.85em;height:0.85em;margin-left:0.5em;vertical-align:-0.15em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:xenia-submit-spin 0.6s linear infinite}",n.prepend(e);}function G(n,e){n&&(e?n.setAttribute("data-xenia-submitting",""):n.removeAttribute("data-xenia-submitting"));}function tt(n,e){if(!e)return;let t=n instanceof ShadowRoot?n.host:n;t instanceof HTMLElement?(t.style.transition="opacity 220ms ease, transform 220ms ease",t.style.opacity="0",t.style.transform="scale(0.96)",window.setTimeout(e,220)):e();}var nt=900;function it(n,e){let t=n.querySelector("[data-xenia-success]");return t?(t instanceof HTMLElement?t.hidden=false:t.removeAttribute("hidden"),e?e.hidden=true:n.querySelectorAll("[data-xenia-field], [data-xenia-submit]").forEach(i=>{i.hidden=true;}),true):false}function ve(n,e,t){let i=n.querySelector("form"),r=false;et(n);let s=(o,a)=>{if(r)return;if(!e.formSubmit){Q(n,"This form isn't connected yet.");return}r=true,Q(n,""),ge(o,true),G(o,true);let l=Date.now(),u=e.formSubmit.successDisplayMs??nt;t.submitWidgetForm(a).then(()=>{G(o,false),it(n,i);let d=Math.max(0,u-(Date.now()-l));window.setTimeout(()=>tt(n,t.dismiss),d);}).catch(()=>{G(o,false),ge(o,false),Q(n,"Something went wrong. Please try again.");}).finally(()=>{r=false;});};i&&i.addEventListener("submit",o=>{o.preventDefault();let a={};new FormData(i).forEach((u,d)=>{typeof u=="string"&&(a[d]=u);});let l=o.submitter??i.querySelector('[type="submit"], button:not([type])');s(l,{...z(n),...a});}),n.querySelectorAll("[data-xenia-submit]").forEach(o=>{i?.contains(o)||o.addEventListener("click",()=>s(o,z(n)));});}function Y(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function be(n){return Y(n).replace(/"/g,"&quot;")}function F(n,e){e&&n.querySelectorAll(".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]").forEach(i=>{i.removeAttribute("onclick"),i.addEventListener("click",e);}),n.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach(t=>{t instanceof HTMLElement&&t.children.length===0&&!t.textContent?.trim()&&(t.style.opacity="0.5");});}var R=260,T=R/2,C=R/2,xe=["#7c3aed","#2563eb","#059669","#d97706","#dc2626","#0891b2"],rt="transform 3.2s cubic-bezier(0.15, 0.85, 0.25, 1)",st='<div class="xenia-wheel-pointer" aria-hidden="true"></div>',ee=320,we=`opacity ${ee}ms ease, transform ${ee}ms ease`,ot=900,Z=(n,e)=>`perspective(${ot}px) translateZ(${e}px) scale(${n})`;function te(n,e){let t=n*Math.PI/180;return {x:C+e*Math.sin(t),y:C-e*Math.cos(t)}}function at(n,e){let t=te(n,T),i=te(e,T),r=e-n>180?1:0;return `M ${C},${C} L ${t.x},${t.y} A ${T},${T} 0 ${r} 1 ${i.x},${i.y} Z`}function lt(n,e,t=0){if(e<=0)return 0;let i=360/e,s=(360-(n*i+i/2))%360;return t*360+s}function Ee(n,e){let t=n?Array.from(n.children):[],i=e?Array.from(e.children):[];e&&(e.hidden=false),i.forEach(r=>{r instanceof HTMLElement&&(r.style.transition="none",r.style.opacity="0",r.style.transform=Z(.94,-60));}),Re(()=>{t.forEach(r=>{r instanceof HTMLElement&&(r.style.transition=we,r.style.opacity="0",r.style.transform=Z(.94,-60));}),i.forEach(r=>{r instanceof HTMLElement&&(r.style.transition=we,r.style.opacity="1",r.style.transform=Z(1,0));});}),n&&setTimeout(()=>{n.hidden=true;},ee);}function Re(n){typeof requestAnimationFrame=="function"?requestAnimationFrame(n):setTimeout(n,0);}function dt(n){let t=360/(n.length||1),i=n.map((r,s)=>{let o=s*t,a=o+t,l=r.colorHex||xe[s%xe.length],u=o+t/2,d=te(u,T*.62);return `<path d="${at(o,a)}" fill="${be(l)}" stroke="#fff" stroke-width="1"></path><text x="${d.x}" y="${d.y}" fill="#fff" font-size="12" text-anchor="middle" transform="rotate(${u} ${d.x} ${d.y})">${Y(r.label)}</text>`}).join("");return `<svg class="xenia-wheel-svg" viewBox="0 0 ${R} ${R}" width="${R}" height="${R}"><g class="xenia-wheel-dial">${i}</g><circle class="xenia-wheel-hub" cx="${C}" cy="${C}" r="6"></circle></svg>`}var Ce={html(n){return `<div class="xenia-spin-wheel"><div data-xenia-wheel-face>${n.spinnerHtml??""}</div><div class="xenia-widget-result" data-xenia-wheel-result hidden>${n.winHtml??""}</div><div class="xenia-widget-result" data-xenia-wheel-loss hidden>${n.lossHtml??""}</div></div>`},wire(n,e,t){F(n,t.dismiss);let i=e.segments??[],r=n.querySelector("[data-xenia-wheel-face]"),s=n.querySelector("[data-xenia-spin]"),o=n.querySelector("[data-xenia-wheel-result]"),a=n.querySelector("[data-xenia-wheel-loss]"),l=n.querySelector("[data-xenia-error]"),u=n.querySelector("[data-xenia-wheel-slot]");u&&u.insertAdjacentHTML("afterbegin",dt(i)+st);let d=n.querySelector(".xenia-wheel-dial");if(!s||!e.formSubmit)return;n.querySelectorAll("[data-xenia-wheel-cta]").forEach(v=>{v.addEventListener("click",()=>t.fireCta());});let p=(v,f,b)=>{n.querySelectorAll("[data-xenia-wheel-prize]").forEach(w=>{w.textContent=v;});let P=f?a:o,k=f?o:a;k&&(k.hidden=true),Ee(r,P),b||(I=true,n.querySelectorAll("[data-xenia-spin-again]").forEach(w=>{w.hidden=true;}));},h=false,I=false;n.querySelectorAll("[data-xenia-spin-again]").forEach(v=>{v.addEventListener("click",()=>{if(I)return;let f=o&&!o.hidden?o:a&&!a.hidden?a:null;f&&(h=false,s.disabled=false,l&&(l.textContent=""),Ee(f,r));});}),s.addEventListener("click",()=>{if(h)return;h=true,s.disabled=true,l&&(l.textContent="");let v=z(n);t.submitWidgetForm(v).then(f=>{let b=i.findIndex(Oe=>Oe.id===f.prize?.segmentId),P=f.prize?.label??i[b]?.label??"",k=b>=0&&!!i[b]?.isLoss,w=f.alreadyPlayed!==true;if(b<0||!d){p(P,k,w);return}let Te=3+Math.floor(Math.random()*3),Me=lt(b,i.length||1,Te),oe=/rotate\(([-\d.]+)deg\)/.exec(d.style.transform),Pe=oe?parseFloat(oe[1]):0;d.style.transition="none",d.style.transform=`rotate(${Pe%360}deg)`,d.getBoundingClientRect(),d.style.transition=rt;let ae=()=>{d.removeEventListener("transitionend",ae),p(P,k,w);};d.addEventListener("transitionend",ae),Re(()=>{d.style.transform=`rotate(${Me}deg)`;});}).catch(()=>{h=false,s.disabled=false,l&&(l.textContent="Something went wrong. Please try again.");});});}};var ne={"spin-wheel":Ce};function B(n,e=document){if(!n)return null;let t=e.querySelector(`[data-xenia-slot="${ut(n)}"]`);if(t)return t;try{return e.querySelector(n)}catch{return null}}function ut(n){let e=window;return e.CSS?.escape?e.CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function N(n,e){let t=B(n);return t?(e.html!==void 0?t.innerHTML=e.html:e.text!==void 0&&(t.textContent=e.text),t.removeAttribute("hidden"),true):false}function ie(n){let e=B(n);return !e||!(e instanceof HTMLElement)?false:(e.dataset.xeniaHidden="1",e.style.setProperty("display","none","important"),true)}function re(n){let e=B(n);return !e||!(e instanceof HTMLElement)?false:(delete e.dataset.xeniaHidden,e.style.removeProperty("display"),true)}var ct=new Set(["banner","popup","modal","inline"]);function pt(n){return ct.has(n)}var X=class{host=null;shadow=null;onCta;messageTemplate;messageStyles;messageComponent;submitWidgetFormFn;mounted=new Map;constructor(e,t){this.onCta=e,this.messageTemplate=t?.messageTemplate,this.messageStyles=t?.messageStyles,this.messageComponent=t?.messageComponent,this.submitWidgetFormFn=t?.submitWidgetForm;}apply(e){let t=0;for(let i of e)this.applyOne(i)&&t++;return t}applyOne(e){switch(e.type){case "swap":return N(e.target,{html:e.html,text:e.text});case "setContent":return N(e.target,{html:e.html,text:e.text});case "hide":return ie(e.target);case "show":return re(e.target);case "redirect":try{return window.location.assign(e.url),!0}catch{return false}default:return pt(e.type)?this.renderMessage(e):false}}destroy(){this.mounted.forEach(e=>e()),this.mounted.clear(),this.host?.remove(),this.host=null,this.shadow=null;}ensureShadow(){if(this.shadow)return this.shadow;let e=document.createElement("div");e.setAttribute("data-xenia-ui",""),document.body.appendChild(e);let t=e.attachShadow({mode:"open"});return t.appendChild(this.styleEl()),this.host=e,this.shadow=t,t}styleEl(){let e=document.createElement("style");return e.textContent=this.messageStyles?`${ke}
2
+ ${this.messageStyles}`:ke,e}renderMessage(e){let t=e.html===void 0&&!!this.messageComponent;if(e.type==="inline"){if(!e.target)return false;let u=B(e.target);return u?(this.unmount(u),t?(u.innerHTML="",this.mountComponent(u,e,"inline",()=>this.unmount(u))):(u.innerHTML=this.cardHtml(e,"inline"),this.wireCard(u,e)),true):false}let i=this.ensureShadow(),r=document.createElement("div"),s=this.positionClass(e.type,e.position),o=e.html!==void 0?" xenia-custom-bg":"",a=e.style?.hideOverlay?" xenia-no-overlay":"";r.className=`xenia-msg xenia-${e.type}${s?` ${s}`:""}${o}${a}`,i.appendChild(r);let l=()=>{this.unmount(r),r.remove();};if(t?this.mountComponent(r,e,e.type,l):(r.innerHTML=this.cardHtml(e,e.type),this.wireCard(r,e,l)),e.dismissAfterMs&&e.dismissAfterMs>0){let u=setTimeout(l,e.dismissAfterMs),d=()=>clearTimeout(u);r.addEventListener("click",d,{once:true}),r.addEventListener("focusin",d,{once:true});}return true}mountComponent(e,t,i,r){if(!this.messageComponent)return;let s={action:t,variant:i,close:r,fireCta:()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),r();}},o=this.messageComponent(e,s);o&&this.mounted.set(e,o);}unmount(e){let t=this.mounted.get(e);t&&(t(),this.mounted.delete(e));}positionClass(e,t){return e==="popup"?`xenia-pos-${t==="top-left"||t==="top-right"||t==="bottom-left"?t:"bottom-right"}`:e==="banner"?`xenia-pos-${t==="top"?"top":"bottom"}`:""}cardHtml(e,t){let i=e.widgetType?ne[e.widgetType]:void 0;if(i)return i.html(e,t);if(e.html!==void 0)return mt(e.html,t);if(this.messageTemplate){let u={action:e,variant:t,escapeHtml:M,escapeAttr:Ie};return this.messageTemplate(u)}let r=e.imageUrl?`<img class="xenia-img" src="${Ie(e.imageUrl)}" alt="" />`:"",s=e.title?`<div class="xenia-title">${M(e.title)}</div>`:"",o=e.message?`<div class="xenia-body">${M(e.message)}</div>`:"",a=e.cta?`<button class="xenia-cta" type="button">${M(e.cta.label)}</button>`:"";return `<div class="xenia-card">${t==="inline"?"":'<button class="xenia-close" type="button" aria-label="Close">\xD7</button>'}${r}<div class="xenia-content">${s}${o}${a}</div></div>`}wireCard(e,t,i){let r=t.widgetType?ne[t.widgetType]:void 0;if(r){r.wire(e,t,this.buildWidgetCtx(t,i));return}F(e,i);let s=e.querySelector(".xenia-cta, [data-xenia-cta]");s&&t.cta&&s.addEventListener("click",()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),i?.();}),ve(e,t,this.buildWidgetCtx(t,i));}buildWidgetCtx(e,t){let i=g();return {dismiss:t,fireCta:()=>{e.cta?.event&&this.onCta?.(e.cta.event,e.cta),e.cta?.url&&window.location.assign(e.cta.url),t?.();},submitWidgetForm:r=>!e.formSubmit||!this.submitWidgetFormFn?Promise.reject(new Error("xenia: this action has no formSubmit config, or no submitWidgetForm handler is wired (construct the ActionRenderer via XeniaClient to get one)")):this.submitWidgetFormFn(e.formSubmit,r,{idempotencyKey:i})}}};function mt(n,e){return e==="modal"?`<div class="xenia-custom-html">${n}</div>`:`<div class="xenia-custom-html"><style>.xenia-custom-html{position:relative}.xenia-custom-html>*{position:static!important;inset:auto!important;top:auto!important;right:auto!important;bottom:auto!important;left:auto!important}</style>${n}</div>`}function M(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ie(n){return M(n).replace(/"/g,"&quot;")}var ke=`
3
3
  :host { all: initial; }
4
4
  .xenia-msg { position: fixed; z-index: var(--xenia-z-index, 2147483000);
5
5
  font-family: var(--xenia-font-family, system-ui, sans-serif); }
@@ -14,12 +14,14 @@ ${this.messageStyles}`:K,e}renderMessage(e){let t=e.html===void 0&&!!this.messag
14
14
  .xenia-modal { inset: 0; display: flex; align-items: center; justify-content: center;
15
15
  background: var(--xenia-modal-backdrop, rgba(0,0,0,.12)); }
16
16
  .xenia-modal.xenia-custom-bg { background: transparent; }
17
+ .xenia-modal.xenia-no-overlay { background: transparent; }
17
18
  .xenia-card { position: relative; background: var(--xenia-card-bg, #fff); color: var(--xenia-card-color, #111);
18
19
  border-radius: var(--xenia-card-radius, 12px); box-shadow: var(--xenia-card-shadow, 0 10px 40px rgba(0,0,0,.18));
19
20
  padding: var(--xenia-card-padding, 16px 18px); display: flex; gap: var(--xenia-card-gap, 12px);
20
21
  align-items: center; }
21
22
  .xenia-banner .xenia-card { border-radius: var(--xenia-banner-card-radius, 0); justify-content: center; }
22
23
  .xenia-modal .xenia-card { max-width: var(--xenia-modal-max-width, 440px); width: calc(100% - 32px); }
24
+ .xenia-card.xenia-widget { flex-direction: column; align-items: center; text-align: center; }
23
25
  .xenia-img { width: var(--xenia-img-size, 56px); height: var(--xenia-img-size, 56px); object-fit: cover;
24
26
  border-radius: var(--xenia-img-radius, 8px); }
25
27
  .xenia-title { font-weight: var(--xenia-title-weight, 600); font-size: var(--xenia-title-size, 15px);
@@ -31,6 +33,38 @@ ${this.messageStyles}`:K,e}renderMessage(e){let t=e.html===void 0&&!!this.messag
31
33
  font-size: var(--xenia-cta-size, 14px); cursor: pointer; }
32
34
  .xenia-close { position: absolute; top: 6px; right: 8px; background: none; border: 0;
33
35
  font-size: var(--xenia-close-size, 20px); line-height: 1; cursor: pointer; color: var(--xenia-close-color, #999); }
34
- `;var N=class{api;identity;responses;options;renderer;analyticsQueue;tracker=null;ready=false;consentState;listeners=new Map;constructor(e){this.options=e;let t=e.prefix??"xenia";this.identity=new M(t,e.visitorCookie??true),e.visitorId&&this.identity.identify(e.visitorId),this.api=new k(e),this.responses=e.persistResponses===false||!x()?new I:new S(t),this.renderer=new T((i,s)=>this.onCtaEvent(i,s),{messageTemplate:e.messageTemplate,messageStyles:e.messageStyles,messageComponent:e.messageComponent}),this.consentState={...e.consent},this.analyticsQueue=new C({debug:e.debug,send:(i,s)=>this.api.sendEvents(i.map(r=>({...r,consent:this.consentState})),s)});}async init(){this.ready||!x()||(await this.identity.resolveDeviceId(),this.ready=true,this.analyticsAllowed()&&this.analyticsQueue.start(),this.options.autoTrack!==false&&(this.tracker=new E({prefix:this.options.prefix??"xenia",throttleMs:this.options.throttleMs??1e3,viewport:{threshold:this.options.viewport?.threshold??.5,rootMargin:this.options.viewport?.rootMargin,triggerOnce:this.options.viewport?.triggerOnce??true},fire:(e,t)=>this.track(e,{interactionType:t},{trigger:true}),fireSlot:(e,t)=>{this.track("customEvent",{customEventName:e==="impression"?"personalization_impression":"personalization_click",contentKey:t.contentKey,contentEntryId:t.contentEntryId??null,baseEntryId:t.baseEntryId??null},{trigger:false});}}),this.tracker.start()));}destroy(){this.tracker?.stop(),this.tracker=null,this.renderer.destroy(),this.analyticsQueue.stop(),this.ready=false;}identify(e){this.identity.identify(e),this.api.identify({xeniaVisitorId:e}).then(t=>this.emit("identify",t)).catch(t=>this.emitError(t));}setJourneyId(e){this.identity.setJourneyId(e);}track(e,t,i={}){if(!x())return;let s=i.trigger===true;if(!s&&this.dntBlocked())return;let r=this.buildEvent(e,t,i);this.emit("event",{eventName:e,event:r}),s?this.analyticsQueue.sendImmediate(r).catch(o=>this.emitError(o)):(this.analyticsQueue.enqueue(r),this.analyticsAllowed()&&this.analyticsQueue.start());}buildEvent(e,t,i){let s=this.identity.collectContext(),r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return {eventName:e,eventId:i.eventId?B(i.eventId):v(),eventVersion:1,occurredAtMs:Date.now(),source:"xenia-js-sdk",identity:{sessionId:this.identity.getSessionId(),...i.identity,xeniaVisitorId:s.visitorId??this.identity.getDeviceId()??void 0},context:{pagePath:s.path,referrer:s.referrer,userAgent:navigator.userAgent,locale:navigator.language,timezone:r,journeyId:this.identity.getJourneyId()??void 0,utmSource:s.utmSource,utmMedium:s.utmMedium,utmCampaign:s.utmCampaign,utmContent:s.utmContent,...i.context},properties:this.withUtmId(t,s.utmId),trigger:i.trigger===true?true:void 0}}withUtmId(e,t){return !t||e&&(e.utm_id!==void 0||e.utmId!==void 0)?e:{...e,utm_id:t}}async resolve(e,t){return this.api.resolve(e,this.withVisitor(t))}async resolveBatch(e,t){return this.api.resolveBatch(e,this.withVisitor(t))}resolveVisitorId(){return this.identity.getVisitorId()??this.identity.getDeviceId()??void 0}withVisitor(e){let t=this.resolveVisitorId();return t?{...e,data:{...e?.data??{},_xenia_vid:t}}:e}dntBlocked(){if(this.options.respectDnt===false)return false;try{let e=navigator,t=navigator.doNotTrack??window.doNotTrack;if(t==="1"||t==="yes"||e.globalPrivacyControl===!0)return !0}catch{}return false}analyticsAllowed(){return this.consentState.analytics===true}async request(e,t,i){let s=this.identity.collectContext(),r=j({eventId:e,journeyId:this.identity.getJourneyId()??void 0,identity:{deviceId:this.identity.getDeviceId()??void 0,visitorId:this.resolveVisitorId()},context:s,props:t}),o=await this.api.webhook(e,r,i?.method??"POST");return this.responses.set(e,o),this.emit("response",{triggerId:e,response:o}),(i?.apply??this.options.autoApplyActions!==false)&&o.actions.length&&this.applyActions(o.actions),o}getResponse(e){return this.responses.get(e)}swapContent(e,t){return A(e,t)}hideContent(e){return X(e)}showContent(e){return $(e)}applyActions(e){let t=this.renderer.apply(e);return this.emit("actions",{actions:e,applied:t}),t}async consent(e){let t=this.analyticsAllowed();this.consentState={...this.consentState,...e},this.analyticsAllowed()&&!t?(this.analyticsQueue.start(),this.analyticsQueue.flush()):!this.analyticsAllowed()&&t&&this.analyticsQueue.stop();let i=this.identity.getVisitorId()??this.identity.getDeviceId();if(i)try{await this.api.consent(i,e);}catch(s){this.emitError(s);}}on(e,t){let i=this.listeners.get(e)??new Set;return i.add(t),this.listeners.set(e,i),()=>i.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(i=>{try{i(t);}catch{}});}emitError(e){let t=e instanceof Error?e:new Error(String(e));this.options.debug&&console.error("[xenia]",t),this.emit("error",t);}onCtaEvent(e,t){this.track(e,{ctaLabel:t.label,ctaUrl:t.url??null},{trigger:true});}};function F(n){return new N(n)}var p=null;function c(n){if(!p)throw console.warn(`[xenia] ${n}() called before init().`),new Error("Xenia not initialized");return p}var Qe={init(n){p&&p.destroy(),p=F(n),p.init();},destroy(){p?.destroy(),p=null;},track(n,e,t){c("track").track(n,e,t);},identify(n){c("identify").identify(n);},consent(n){return c("consent").consent(n)},resolve(n,e){return c("resolve").resolve(n,e)},resolveBatch(n,e){return c("resolveBatch").resolveBatch(n,e)},setJourneyId(n){c("setJourneyId").setJourneyId(n);},request(n,e){return c("request").request(n,e)},getResponse(n){return c("getResponse").getResponse(n)},swapContent(n,e){return c("swapContent").swapContent(n,e)},hideContent(n){return c("hideContent").hideContent(n)},showContent(n){return c("showContent").showContent(n)}};exports.Xenia=Qe;return exports;})({});
36
+ .xenia-wheel-dial { transform-box: fill-box; transform-origin: center; }
37
+ .xenia-wheel-hub { fill: var(--xenia-wheel-pointer-color, #111); }
38
+ .xenia-wheel-wrap { position: relative; display: inline-block; }
39
+ .xenia-wheel-pointer { position: absolute; top: -6px; left: 50%; transform: translateX(-50%);
40
+ width: 0; height: 0; border-left: 9px solid transparent; border-right: 9px solid transparent;
41
+ border-top: 14px solid var(--xenia-wheel-pointer-color, #111); pointer-events: none; }
42
+ .xenia-wheel-spin { margin-top: 10px; background: var(--xenia-cta-bg, #111); color: var(--xenia-cta-color, #fff);
43
+ border: 0; border-radius: var(--xenia-cta-radius, 8px); padding: var(--xenia-cta-padding, 8px 14px);
44
+ font-size: var(--xenia-cta-size, 14px); font-family: inherit; cursor: pointer; }
45
+ .xenia-wheel-spin:disabled { opacity: 0.6; cursor: default; }
46
+ /* No animation/transform here \u2014 spin-wheel's win/loss screens are ALWAYS full
47
+ custom HTML now (winHtml/lossHtml), never this class's own generated icon/title/prize/cta
48
+ content (those sub-classes below are unreachable dead CSS, kept only for backwards-compat with
49
+ any already-saved artifact that might still reference them). A transform on THIS wrapper
50
+ would make it the CSS containing block for any fixed/absolute-positioned descendant the
51
+ author's own HTML uses (a real, common case \u2014 a "full-screen overlay" win/loss design) \u2014 the
52
+ fixed child would then size/position itself relative to this wrapper's own small, in-flow,
53
+ often off-center box instead of the true browser viewport, visibly popping in from/toward
54
+ whatever corner the wrapper happens to sit at instead of scaling from the real screen center.
55
+ spin-wheel.ts's crossFadeReveal owns the actual reveal transition (applied to the author's own
56
+ top-level element, never this wrapper) \u2014 this class stays a bare, transform-free layout box. */
57
+ .xenia-widget-result { display: flex; flex-direction: column; align-items: center; gap: 4px;
58
+ padding: 8px 4px 2px; text-align: center; }
59
+ .xenia-widget-result[hidden] { display: none; }
60
+ .xenia-widget-result-icon { font-size: 40px; line-height: 1; }
61
+ .xenia-widget-result-title { font-weight: var(--xenia-title-weight, 700); font-size: var(--xenia-title-size, 17px); }
62
+ .xenia-widget-result-prize { font-weight: 600; font-size: 15px; color: var(--xenia-cta-bg, #111);
63
+ background: var(--xenia-result-prize-bg, rgba(0,0,0,.06)); border-radius: var(--xenia-cta-radius, 8px);
64
+ padding: 6px 14px; }
65
+ .xenia-widget-result-cta { margin-top: 8px; background: var(--xenia-cta-bg, #111); color: var(--xenia-cta-color, #fff);
66
+ border: 0; border-radius: var(--xenia-cta-radius, 8px); padding: var(--xenia-cta-padding, 8px 14px);
67
+ font-size: var(--xenia-cta-size, 14px); font-family: inherit; cursor: pointer; }
68
+ `;var se=class{api;identity;responses;options;renderer;analyticsQueue;tracker=null;ready=false;consentState;listeners=new Map;constructor(e){this.options=e;let t=e.prefix??"xenia";this.identity=new _(t,e.visitorCookie??true),e.visitorId&&this.identity.identify(e.visitorId),this.api=new V(e),this.responses=e.persistResponses===false||!W()?new L:new $(t),this.renderer=new X((i,r)=>this.onCtaEvent(i,r),{messageTemplate:e.messageTemplate,messageStyles:e.messageStyles,messageComponent:e.messageComponent,submitWidgetForm:(i,r,s)=>this.submitWidgetForm(i,r,s)}),this.consentState={...e.consent},this.analyticsQueue=new q({debug:e.debug,send:(i,r)=>this.api.sendEvents(i.map(s=>({...s,consent:this.consentState})),r)});}async init(){this.ready||!W()||(await this.identity.resolveDeviceId(),this.ready=true,this.analyticsAllowed()&&this.analyticsQueue.start(),this.options.autoTrack!==false&&(this.tracker=new J({prefix:this.options.prefix??"xenia",throttleMs:this.options.throttleMs??1e3,viewport:{threshold:this.options.viewport?.threshold??.5,rootMargin:this.options.viewport?.rootMargin,triggerOnce:this.options.viewport?.triggerOnce??true},fire:(e,t)=>this.track(e,{interactionType:t},{trigger:true}),fireSlot:(e,t)=>{this.track("customEvent",{customEventName:e==="impression"?"personalization_impression":"personalization_click",contentKey:t.contentKey,contentEntryId:t.contentEntryId??null,baseEntryId:t.baseEntryId??null},{trigger:false});}}),this.tracker.start()));}destroy(){this.tracker?.stop(),this.tracker=null,this.renderer.destroy(),this.analyticsQueue.stop(),this.ready=false;}identify(e,t){this.identity.identify(e),t?.customerId!==void 0&&this.identity.setCustomerId(t.customerId),t?.email!==void 0&&this.identity.setEmail(t.email),this.api.identify({xeniaVisitorId:e,userId:t?.customerId,email:t?.email}).then(i=>this.emit("identify",i)).catch(i=>this.emitError(i));}setJourneyId(e){this.identity.setJourneyId(e);}track(e,t,i={}){if(!W())return;let r=i.trigger===true;if(!r&&this.dntBlocked())return;let s=this.buildEvent(e,t,i);this.emit("event",{eventName:e,event:s}),r?this.analyticsQueue.sendImmediate(s).catch(o=>this.emitError(o)):(this.analyticsQueue.enqueue(s),this.analyticsAllowed()&&this.analyticsQueue.start());}buildEvent(e,t,i){let r=this.identity.collectContext(),s;try{s=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return {eventName:e,eventId:i.eventId?me(i.eventId):g(),eventVersion:1,occurredAtMs:Date.now(),source:"xenia-js-sdk",identity:{sessionId:this.identity.getSessionId(),...i.identity,xeniaVisitorId:r.visitorId??this.identity.getDeviceId()??void 0},context:{pagePath:r.path,referrer:r.referrer,userAgent:navigator.userAgent,locale:navigator.language,timezone:s,journeyId:this.identity.getJourneyId()??void 0,utmSource:r.utmSource,utmMedium:r.utmMedium,utmCampaign:r.utmCampaign,utmContent:r.utmContent,...i.context},properties:this.withUtmId(t,r.utmId),trigger:i.trigger===true?true:void 0}}withUtmId(e,t){return !t||e&&(e.utm_id!==void 0||e.utmId!==void 0)?e:{...e,utm_id:t}}async resolve(e,t){return this.api.resolve(e,this.withVisitor(t))}async resolveBatch(e,t){return this.api.resolveBatch(e,this.withVisitor(t))}resolveVisitorId(){return this.identity.getVisitorId()??this.identity.getDeviceId()??void 0}withVisitor(e){let t=this.identity.collectContext(),i=this.resolveVisitorId(),r=x({path:t.path,query:t.query,deviceId:this.identity.getDeviceId()??void 0,visitorId:i,customerId:this.identity.getCustomerId()??void 0,email:this.identity.getEmail()??void 0,url:t.url,referrer:t.referrer,utmSource:t.utmSource,utmMedium:t.utmMedium,utmCampaign:t.utmCampaign,utmContent:t.utmContent,utmId:t.utmId});return i&&(r._xenia_vid=i),Object.keys(r).length===0?e:{...e,data:{...e?.data??{},...r}}}dntBlocked(){if(this.options.respectDnt===false)return false;try{let e=navigator,t=navigator.doNotTrack??window.doNotTrack;if(t==="1"||t==="yes"||e.globalPrivacyControl===!0)return !0}catch{}return false}analyticsAllowed(){return this.consentState.analytics===true}async request(e,t,i){let r=this.identity.collectContext(),s=pe({eventId:e,journeyId:this.identity.getJourneyId()??void 0,identity:{deviceId:this.identity.getDeviceId()??void 0,visitorId:this.resolveVisitorId()},context:r,props:t}),o=await this.api.webhook(e,s,i?.method??"POST");return this.responses.set(e,o),this.emit("response",{triggerId:e,response:o}),(i?.apply??this.options.autoApplyActions!==false)&&o.actions.length&&this.applyActions(o.actions),o}getResponse(e){return this.responses.get(e)}async submitWidgetForm(e,t,i){let r=this.identity.collectContext(),s=i?.idempotencyKey??g(),o=e.flowRef??e.bindingRef,a={visitorId:this.resolveVisitorId(),deviceId:this.identity.getDeviceId()??void 0,idempotencyKey:s,mode:e.mode,ref:o,url:r.url,referrer:r.referrer,path:r.path,query:r.query,utmSource:r.utmSource,utmMedium:r.utmMedium,utmCampaign:r.utmCampaign,utmContent:r.utmContent,utmId:r.utmId},l=e.flowRef?await this.api.webhook(e.flowRef,x({...a,...t}),"POST"):await this.api.submitWidget(e.bindingRef??"",x({...a,fields:t}));return this.emit("response",{triggerId:o,response:l}),(i?.apply??this.options.autoApplyActions!==false)&&l.actions.length&&this.applyActions(l.actions),l}swapContent(e,t){return N(e,t)}hideContent(e){return ie(e)}showContent(e){return re(e)}applyActions(e){let t=this.renderer.apply(e);return this.emit("actions",{actions:e,applied:t}),t}async consent(e){let t=this.analyticsAllowed();this.consentState={...this.consentState,...e},this.analyticsAllowed()&&!t?(this.analyticsQueue.start(),this.analyticsQueue.flush()):!this.analyticsAllowed()&&t&&this.analyticsQueue.stop();let i=this.identity.getVisitorId()??this.identity.getDeviceId();if(i)try{await this.api.consent(i,e);}catch(r){this.emitError(r);}}on(e,t){let i=this.listeners.get(e)??new Set;return i.add(t),this.listeners.set(e,i),()=>i.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(i=>{try{i(t);}catch{}});}emitError(e){let t=e instanceof Error?e:new Error(String(e));this.options.debug&&console.error("[xenia]",t),this.emit("error",t);}onCtaEvent(e,t){this.track(e,{ctaLabel:t.label,ctaUrl:t.url??null},{trigger:true});}};function Ae(n){return new se(n)}var y=null;function m(n){if(!y)throw console.warn(`[xenia] ${n}() called before init().`),new Error("Xenia not initialized");return y}var nn={init(n){y&&y.destroy(),y=Ae(n),y.init();},destroy(){y?.destroy(),y=null;},track(n,e,t){m("track").track(n,e,t);},identify(n){m("identify").identify(n);},consent(n){return m("consent").consent(n)},resolve(n,e){return m("resolve").resolve(n,e)},resolveBatch(n,e){return m("resolveBatch").resolveBatch(n,e)},setJourneyId(n){m("setJourneyId").setJourneyId(n);},request(n,e){return m("request").request(n,e)},getResponse(n){return m("getResponse").getResponse(n)},swapContent(n,e){return m("swapContent").swapContent(n,e)},hideContent(n){return m("hideContent").hideContent(n)},showContent(n){return m("showContent").showContent(n)}};exports.Xenia=nn;return exports;})({});
35
69
  Xenia=Xenia&&(Xenia.Xenia||Xenia.default)||Xenia;if(typeof window!=='undefined'){window.Xenia=Xenia;}
36
70
  //# sourceMappingURL=xenia-sdk.iife.js.map