@characterxyz/widget 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cx.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/iife.ts","../src/config.ts","../../web/src/audio/player.ts","../../web/src/audio/mic.ts","../../web/src/emitter.ts","../../web/src/errors.ts","../../web/src/http.ts","../../web/src/protocol.ts","../../web/src/call.ts","../../web/src/chat.ts","../../web/src/session.ts","../../web/src/client.ts","../../web/src/index.ts","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/constants.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/util.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/options.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/create-element.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/component.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/props.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/create-context.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/children.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/index.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/render.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/clone-element.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/catch-error.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/hooks/src/index.js","../src/format.ts","../src/framing.ts","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/jsx-runtime/src/utils.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/constants.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/jsx-runtime/src/index.js","../src/icons.tsx","../src/face-frame.tsx","../src/portrait.tsx","../src/app.tsx","../src/styles.ts","../src/element.tsx"],"sourcesContent":["/**\n * `cx.js` — the script-tag build. Everything in one file; reads its settings\n * from its own `data-*` attributes and mounts itself:\n *\n * ```html\n * <script src=\"https://unpkg.com/@characterxyz/widget@0/dist/cx.js\"\n * data-key=\"cxyz_pk_live_…\" data-accent=\"#e11d48\" async></script>\n * ```\n *\n * `window.CharacterXYZ` is then `{ mount, open, close, widget }` for pages\n * that want to drive it (`CharacterXYZ.open('call')`).\n */\nimport { applyLayer, DEFAULTS, fromAttributes } from './config.js';\nimport { mount, type MountOptions, type WidgetHandle } from './element.js';\n\nexport { mount };\n\nconst script = document.currentScript as HTMLScriptElement | null;\nlet widget: WidgetHandle | null = null;\n\nfunction start() {\n if (!script) return;\n const attrs = fromAttributes(Array.from(script.attributes).filter((a) => a.name.startsWith('data-')));\n // An empty attribute is \"not set\" (a template that left it blank), never \"\".\n const given = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);\n const key = given(attrs.key) ?? given(attrs.publishableKey);\n if (!key) return; // no key on the tag: the page will call CharacterXYZ.mount() itself\n // Only the presentational settings pass through the config filter; the\n // connection settings are read directly.\n const config = applyLayer(DEFAULTS, attrs);\n const changed = Object.fromEntries(Object.entries(config).filter(([k, v]) => k in attrs && v !== (DEFAULTS as unknown as Record<string, unknown>)[k]));\n const opts: MountOptions = {\n ...changed,\n publishableKey: key,\n agentId: given(attrs.agent),\n apiUrl: given(attrs.apiUrl),\n };\n widget = mount(opts);\n}\n\nif (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });\nelse start();\n\nconst api = {\n mount: (o: MountOptions) => (widget = mount(o)),\n open: (v?: 'chat' | 'call') => widget?.open(v),\n close: () => widget?.close(),\n get widget() {\n return widget;\n },\n};\n(window as unknown as { CharacterXYZ: typeof api }).CharacterXYZ = api;\n","/**\n * Everything a brand can set, from three places, later wins:\n * 1. the key's `appearance` (the Embed designer in Character XYZ),\n * 2. the element's attributes / `data-*` on the script tag,\n * 3. options passed to `mount()`.\n */\n\nexport type Position = 'bottom-right' | 'bottom-left';\nexport type ColorMode = 'light' | 'dark' | 'auto';\n/** `bubble`: just her portrait (opens the chat; calls are inside). `actions`: chat and call buttons beside it. */\nexport type LauncherStyle = 'bubble' | 'actions';\n/** How she is shown while closed: a round `bubble`, a `half` body cut-out, or her `full` body standing in the corner. */\nexport type Display = 'bubble' | 'half' | 'full';\n\nexport interface WidgetConfig {\n position: Position;\n mode: ColorMode;\n launcher: LauncherStyle;\n display: Display;\n /** Any CSS colour. */\n accent: string;\n /** Corner radius of the panel, px. */\n radius: number;\n /** A CSS font-family; defaults to the system UI font. */\n font: string;\n /** The line under her name; defaults to the agent's tagline. */\n subtitle: string | null;\n /** Shown once per visitor above the launcher. Empty = none. */\n greeting: string;\n /** Seconds before the greeting appears. */\n greetingDelay: number;\n /** Suggested first messages in an empty chat. */\n suggestions: string[];\n /** Placeholder in the message box. */\n placeholder: string;\n showChat: boolean;\n showCall: boolean;\n /** The \"Powered by Character XYZ\" line. */\n branding: boolean;\n /** px from the corner. */\n offsetX: number;\n offsetY: number;\n zIndex: number;\n /** Open the panel on load. */\n open: boolean;\n /**\n * Draw the agent's face in calls with Character XYZ's own renderer (lip\n * sync, her own teeth and eyes), framed from `faceUrl`. Off = the portrait clips.\n */\n face: boolean;\n faceUrl: string;\n}\n\nexport const DEFAULTS: WidgetConfig = {\n position: 'bottom-right',\n mode: 'auto',\n launcher: 'bubble',\n display: 'bubble',\n accent: '#7c5cff',\n radius: 24,\n font: '',\n subtitle: null,\n greeting: '',\n greetingDelay: 3,\n suggestions: [],\n placeholder: 'Message',\n showChat: true,\n showCall: true,\n branding: true,\n offsetX: 20,\n offsetY: 20,\n zIndex: 2147483000,\n open: false,\n face: true,\n faceUrl: 'https://www.character.xyz/embed/face',\n};\n\nconst num = (v: unknown, lo: number, hi: number): number | undefined => {\n const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;\n return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : undefined;\n};\n\nconst bool = (v: unknown): boolean | undefined => {\n if (typeof v === 'boolean') return v;\n if (v === 'true' || v === '' || v === '1') return true;\n if (v === 'false' || v === '0') return false;\n return undefined;\n};\n\nconst str = (v: unknown, max = 200): string | undefined => (typeof v === 'string' ? v.slice(0, max) : undefined);\n\n/** A colour the page can use safely in CSS: hex, rgb()/hsl()/oklch() or a name. Anything else is ignored. */\nexport function safeColor(v: unknown): string | undefined {\n if (typeof v !== 'string') return undefined;\n const s = v.trim();\n if (/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s)) return s;\n if (/^(rgb|rgba|hsl|hsla|oklch|oklab)\\([0-9.,%\\s/+-]+\\)$/i.test(s)) return s;\n if (/^[a-z]{3,20}$/i.test(s)) return s;\n return undefined;\n}\n\n/** A font-family list without anything that could escape the declaration. */\nexport function safeFont(v: unknown): string | undefined {\n if (typeof v !== 'string') return undefined;\n const s = v.trim();\n return /^[\\w\\s,\"'-]{1,120}$/.test(s) ? s : undefined;\n}\n\n/** Merge one layer of untrusted settings onto a config. Unknown or invalid values are dropped. */\nexport function applyLayer(base: WidgetConfig, raw: Record<string, unknown> | null | undefined): WidgetConfig {\n if (!raw || typeof raw !== 'object') return base;\n const c = { ...base };\n if (raw.position === 'bottom-left' || raw.position === 'bottom-right') c.position = raw.position;\n if (raw.mode === 'light' || raw.mode === 'dark' || raw.mode === 'auto') c.mode = raw.mode;\n if (raw.launcher === 'bubble' || raw.launcher === 'actions') c.launcher = raw.launcher;\n if (raw.display === 'bubble' || raw.display === 'half' || raw.display === 'full') c.display = raw.display;\n c.accent = safeColor(raw.accent) ?? c.accent;\n c.radius = num(raw.radius, 0, 40) ?? c.radius;\n c.font = safeFont(raw.font) ?? c.font;\n if (raw.subtitle === null) c.subtitle = null;\n else c.subtitle = str(raw.subtitle, 80) ?? c.subtitle;\n c.greeting = str(raw.greeting, 160) ?? c.greeting;\n c.greetingDelay = num(raw.greetingDelay, 0, 120) ?? c.greetingDelay;\n if (Array.isArray(raw.suggestions)) {\n c.suggestions = raw.suggestions.filter((s): s is string => typeof s === 'string' && s.trim() !== '').map((s) => s.slice(0, 80)).slice(0, 4);\n } else if (typeof raw.suggestions === 'string') {\n c.suggestions = raw.suggestions.split('|').map((s) => s.trim()).filter(Boolean).slice(0, 4);\n }\n c.placeholder = str(raw.placeholder, 60) ?? c.placeholder;\n c.showChat = bool(raw.showChat) ?? c.showChat;\n c.showCall = bool(raw.showCall) ?? c.showCall;\n c.branding = bool(raw.branding) ?? c.branding;\n c.offsetX = num(raw.offsetX, 0, 200) ?? c.offsetX;\n c.offsetY = num(raw.offsetY, 0, 200) ?? c.offsetY;\n c.zIndex = num(raw.zIndex, 0, 2147483647) ?? c.zIndex;\n c.open = bool(raw.open) ?? c.open;\n c.face = bool(raw.face) ?? c.face;\n if (typeof raw.faceUrl === 'string' && /^https?:\\/\\/[^\\s\"'<>]+$/.test(raw.faceUrl.trim())) c.faceUrl = raw.faceUrl.trim();\n return c;\n}\n\n/** `data-show-call=\"false\"` → `{ showCall: 'false' }`: kebab attributes to camel keys. */\nexport function fromAttributes(attrs: Iterable<{ name: string; value: string }>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const { name, value } of attrs) {\n const key = name.replace(/^data-/, '').replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase());\n out[key] = value;\n }\n return out;\n}\n","/**\n * Plays the agent's streamed voice (PCM16 chunks) gaplessly, and reports how\n * loud it is right now so a UI can draw a ring that follows the voice.\n *\n * Each chunk becomes an AudioBuffer scheduled right after the last one; the\n * first waits a short pre-roll so a slow second chunk does not open a gap.\n */\n\nexport interface PlayerOptions {\n sampleRate?: number;\n onStart?: () => void;\n onEnd?: () => void;\n volume?: number;\n}\n\nconst PREROLL_S = 0.12;\n\nlet shared: AudioContext | null = null;\n\n/** One output context for the page, created on first use (after a gesture). */\nexport function audioContext(): AudioContext {\n if (!shared || shared.state === 'closed') shared = new AudioContext({ latencyHint: 'interactive' });\n if (shared.state === 'suspended') void shared.resume().catch(() => {});\n return shared;\n}\n\nexport class PcmPlayer {\n private readonly ctx: AudioContext;\n private readonly gain: GainNode;\n private readonly analyser: AnalyserNode;\n private readonly data: Uint8Array<ArrayBuffer>;\n private nextAt = 0;\n private started = false;\n private ended = false;\n private finishing = false;\n private sources = new Set<AudioBufferSourceNode>();\n private startedAt = 0;\n readonly sampleRate: number;\n\n constructor(private readonly opts: PlayerOptions = {}) {\n this.ctx = audioContext();\n this.sampleRate = opts.sampleRate ?? 16_000;\n this.gain = this.ctx.createGain();\n this.gain.gain.value = opts.volume ?? 1;\n this.analyser = this.ctx.createAnalyser();\n this.analyser.fftSize = 512;\n this.data = new Uint8Array(new ArrayBuffer(this.analyser.fftSize));\n this.gain.connect(this.analyser).connect(this.ctx.destination);\n }\n\n /** Queue PCM16 little-endian mono bytes. */\n enqueue(bytes: Uint8Array): void {\n if (this.ended || bytes.byteLength < 2) return;\n const count = Math.floor(bytes.byteLength / 2);\n const view = new DataView(bytes.buffer, bytes.byteOffset, count * 2);\n const buf = this.ctx.createBuffer(1, count, this.sampleRate);\n const ch = buf.getChannelData(0);\n for (let i = 0; i < count; i++) ch[i] = view.getInt16(i * 2, true) / 32768;\n const src = this.ctx.createBufferSource();\n src.buffer = buf;\n src.connect(this.gain);\n const now = this.ctx.currentTime;\n if (this.nextAt < now) this.nextAt = now + (this.started ? 0.02 : PREROLL_S);\n src.start(this.nextAt);\n if (!this.started) {\n this.started = true;\n const delayMs = Math.max(0, (this.nextAt - now) * 1000);\n this.startedAt = performance.now() + delayMs;\n setTimeout(() => this.opts.onStart?.(), delayMs);\n }\n this.nextAt += buf.duration;\n this.sources.add(src);\n src.onended = () => {\n this.sources.delete(src);\n if (this.finishing && this.sources.size === 0) this.finish();\n };\n }\n\n /** No more chunks: report the end once the queue has played out. */\n end(): void {\n this.finishing = true;\n if (this.sources.size === 0) this.finish();\n }\n\n /** Silence now (an interruption). Does not call `onEnd`. */\n stop(): void {\n this.ended = true;\n for (const s of this.sources) {\n try {\n s.stop();\n } catch {\n /* not started */\n }\n }\n this.sources.clear();\n this.gain.disconnect();\n }\n\n /** Milliseconds of audio actually heard so far. */\n playedMs(): number {\n return this.started ? Math.max(0, performance.now() - this.startedAt) : 0;\n }\n\n /** Loudness now, 0..1. */\n level(): number {\n this.analyser.getByteTimeDomainData(this.data);\n let sum = 0;\n for (let i = 0; i < this.data.length; i++) {\n const v = (this.data[i]! - 128) / 128;\n sum += v * v;\n }\n return Math.min(1, Math.sqrt(sum / this.data.length) * 3);\n }\n\n private finish() {\n if (this.ended) return;\n this.ended = true;\n this.gain.disconnect();\n this.opts.onEnd?.();\n }\n}\n","/**\n * The microphone as the agent socket wants it: 16 kHz mono PCM16, 30 ms\n * (480-sample) frames, sent continuously.\n *\n * Resampled in an AudioWorklet from whatever rate the device runs at. A\n * context forced to 16 kHz would be simpler and is refused by Firefox for a\n * MediaStream source at another rate, so the worklet does it.\n */\n\nexport const TARGET_RATE = 16_000;\nexport const FRAME_SAMPLES = 480;\n\nconst WORKLET = `\nclass CxyzMic extends AudioWorkletProcessor {\n constructor(o) {\n super();\n this.ratio = sampleRate / ${TARGET_RATE};\n this.pos = 0;\n this.lp = 0;\n this.alpha = Math.min(1, 2 * Math.PI * 7000 / sampleRate / (1 + 2 * Math.PI * 7000 / sampleRate));\n this.out = new Int16Array(${FRAME_SAMPLES});\n this.n = 0;\n }\n process(inputs) {\n const ch = inputs[0] && inputs[0][0];\n if (!ch) return true;\n for (let i = 0; i < ch.length; i++) {\n this.lp += this.alpha * (ch[i] - this.lp);\n this.pos += 1;\n if (this.pos >= this.ratio) {\n this.pos -= this.ratio;\n const s = Math.max(-1, Math.min(1, this.lp));\n this.out[this.n++] = s < 0 ? s * 0x8000 : s * 0x7fff;\n if (this.n === ${FRAME_SAMPLES}) {\n this.port.postMessage(this.out.buffer, [this.out.buffer]);\n this.out = new Int16Array(${FRAME_SAMPLES});\n this.n = 0;\n }\n }\n }\n return true;\n }\n}\nregisterProcessor('cxyz-mic', CxyzMic);\n`;\n\nexport interface MicOptions {\n onFrame: (pcm: ArrayBuffer, level: number) => void;\n deviceId?: string;\n}\n\nexport interface Mic {\n stop(): void;\n setMuted(m: boolean): void;\n readonly muted: boolean;\n}\n\n/** RMS of a PCM16 frame, 0..1. */\nexport function levelOf(pcm: ArrayBuffer): number {\n const s = new Int16Array(pcm);\n if (!s.length) return 0;\n let sum = 0;\n for (let i = 0; i < s.length; i++) {\n const v = s[i]! / 32768;\n sum += v * v;\n }\n return Math.sqrt(sum / s.length);\n}\n\nexport async function openMic(opts: MicOptions): Promise<Mic> {\n if (!navigator.mediaDevices?.getUserMedia) throw new Error('This browser cannot use a microphone here.');\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: {\n deviceId: opts.deviceId ? { exact: opts.deviceId } : undefined,\n channelCount: 1,\n // The agent's voice comes out of the speakers; without cancellation it\n // would hear itself and answer.\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true,\n },\n });\n const ctx = new AudioContext({ latencyHint: 'interactive' });\n const source = ctx.createMediaStreamSource(stream);\n let muted = false;\n const deliver = (buf: ArrayBuffer) => {\n if (muted) {\n // Silence, not nothing: the server keeps a pre-roll of the last frames\n // and splices it onto the next utterance.\n opts.onFrame(new ArrayBuffer(buf.byteLength), 0);\n return;\n }\n opts.onFrame(buf, levelOf(buf));\n };\n\n let node: AudioNode;\n let teardown: () => void;\n try {\n const url = URL.createObjectURL(new Blob([WORKLET], { type: 'application/javascript' }));\n try {\n await ctx.audioWorklet.addModule(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n const w = new AudioWorkletNode(ctx, 'cxyz-mic');\n w.port.onmessage = (e) => deliver(e.data as ArrayBuffer);\n node = w;\n teardown = () => {\n w.port.onmessage = null;\n };\n } catch {\n // A strict Content-Security-Policy can refuse a blob: worklet. The old\n // ScriptProcessor path is deprecated but universal.\n const sp = ctx.createScriptProcessor(4096, 1, 1);\n const ratio = ctx.sampleRate / TARGET_RATE;\n let pos = 0;\n let out = new Int16Array(FRAME_SAMPLES);\n let n = 0;\n sp.onaudioprocess = (e) => {\n const ch = e.inputBuffer.getChannelData(0);\n for (let i = 0; i < ch.length; i++) {\n pos += 1;\n if (pos >= ratio) {\n pos -= ratio;\n const s = Math.max(-1, Math.min(1, ch[i]!));\n out[n++] = s < 0 ? s * 0x8000 : s * 0x7fff;\n if (n === FRAME_SAMPLES) {\n deliver(out.buffer);\n out = new Int16Array(FRAME_SAMPLES);\n n = 0;\n }\n }\n }\n };\n node = sp;\n teardown = () => {\n sp.onaudioprocess = null;\n };\n }\n source.connect(node);\n // A worklet/processor only runs while connected to the destination; a gain\n // of zero keeps the room from hearing itself.\n const sink = ctx.createGain();\n sink.gain.value = 0;\n node.connect(sink).connect(ctx.destination);\n if (ctx.state === 'suspended') await ctx.resume().catch(() => {});\n\n return {\n get muted() {\n return muted;\n },\n setMuted(m: boolean) {\n muted = m;\n for (const t of stream.getAudioTracks()) t.enabled = !m;\n },\n stop() {\n teardown();\n try {\n source.disconnect();\n node.disconnect();\n } catch {\n /* already disconnected */\n }\n for (const t of stream.getTracks()) t.stop();\n void ctx.close().catch(() => {});\n },\n };\n}\n","/** A tiny typed event emitter. `on` returns the unsubscribe. */\nexport class Emitter<Events extends Record<string, unknown>> {\n private handlers: { [K in keyof Events]?: Set<(payload: Events[K]) => void> } = {};\n\n on<K extends keyof Events>(event: K, fn: (payload: Events[K]) => void): () => void {\n (this.handlers[event] ??= new Set()).add(fn);\n return () => this.handlers[event]?.delete(fn);\n }\n\n emit<K extends keyof Events>(event: K, payload: Events[K]): void {\n for (const fn of this.handlers[event] ?? []) {\n try {\n fn(payload);\n } catch (e) {\n // A listener's bug must never break the SDK's own state machine.\n console.error('[characterxyz] listener threw', e);\n }\n }\n }\n\n clear(): void {\n this.handlers = {};\n }\n}\n","export type CxErrorCode =\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'invalid'\n | 'rate_limited'\n | 'payment_required'\n | 'unavailable'\n | 'network'\n | 'unknown';\n\n/** Every failure the SDK reports, with a message fit to show a visitor. */\nexport class CxError extends Error {\n readonly code: CxErrorCode;\n readonly status: number;\n\n constructor(code: CxErrorCode, message: string, status = 0) {\n super(message);\n this.name = 'CxError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport function codeForStatus(status: number): CxErrorCode {\n switch (status) {\n case 401:\n return 'unauthorized';\n case 403:\n return 'forbidden';\n case 404:\n return 'not_found';\n case 402:\n return 'payment_required';\n case 422:\n return 'invalid';\n case 429:\n return 'rate_limited';\n case 503:\n return 'unavailable';\n default:\n return 'unknown';\n }\n}\n","import { CxError, codeForStatus } from './errors.js';\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n token?: string;\n signal?: AbortSignal;\n}\n\nasync function errorFrom(res: Response): Promise<CxError> {\n let message = '';\n try {\n const j = (await res.json()) as { message?: unknown };\n if (typeof j?.message === 'string') message = j.message;\n } catch {\n // not JSON: the status says enough\n }\n return new CxError(codeForStatus(res.status), message || `Request failed (${res.status})`, res.status);\n}\n\nexport async function send(apiUrl: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n const headers: Record<string, string> = {};\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json';\n if (opts.token) headers.Authorization = `Bearer ${opts.token}`;\n let res: Response;\n try {\n res = await fetch(apiUrl + path, {\n method: opts.method ?? (opts.body === undefined ? 'GET' : 'POST'),\n headers,\n body: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: opts.signal,\n // No cookies, ever: the SDK authenticates with its own bearer token, and\n // a credentialed request would carry the brand page's cookies to us.\n credentials: 'omit',\n cache: 'no-store',\n });\n } catch (e) {\n if ((e as Error)?.name === 'AbortError') throw e;\n throw new CxError('network', 'Could not reach Character XYZ. Check your connection.');\n }\n if (!res.ok) throw await errorFrom(res);\n return res;\n}\n\n/** JSON request; unwraps the API's `{message, data}` envelope. */\nexport async function request<T>(apiUrl: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await send(apiUrl, path, opts);\n const j = (await res.json()) as { data?: T };\n return j.data as T;\n}\n\nexport interface ServerEvent {\n event: string;\n data: unknown;\n}\n\n/**\n * Read a `text/event-stream` body, calling `onEvent` per event, until the\n * stream ends or `signal` aborts. Fetch-based on purpose: `EventSource` cannot\n * send an Authorization header, so it would need the token in the URL.\n */\nexport async function readEvents(res: Response, onEvent: (e: ServerEvent) => void, signal?: AbortSignal): Promise<void> {\n const body = res.body;\n if (!body) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = '';\n const onAbort = () => void reader.cancel().catch(() => {});\n signal?.addEventListener('abort', onAbort);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n buf = drain(buf, onEvent);\n }\n buf += decoder.decode();\n drain(buf + '\\n\\n', onEvent);\n } finally {\n signal?.removeEventListener('abort', onAbort);\n }\n}\n\n/** Dispatch every complete event in `buf`; return what is left over. */\nexport function drain(buf: string, onEvent: (e: ServerEvent) => void): string {\n const normalised = buf.replace(/\\r\\n/g, '\\n');\n let rest = normalised;\n let idx: number;\n while ((idx = rest.indexOf('\\n\\n')) !== -1) {\n const block = rest.slice(0, idx);\n rest = rest.slice(idx + 2);\n let event = 'message';\n const data: string[] = [];\n for (const line of block.split('\\n')) {\n if (!line || line.startsWith(':')) continue;\n const colon = line.indexOf(':');\n const field = colon === -1 ? line : line.slice(0, colon);\n const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '');\n if (field === 'event') event = value;\n else if (field === 'data') data.push(value);\n }\n if (!data.length) continue;\n const raw = data.join('\\n');\n let parsed: unknown = raw;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // plain text data\n }\n onEvent({ event, data: parsed });\n }\n return rest;\n}\n","/**\n * The agent socket's binary packet (the same one the Stage reads):\n *\n * \"CXYZ\" | version u8 (1) | kind u8 | flags u8 (bit 0 = final)\n * | corrLen u16 | corr utf8 | seq u32 | timestamp u64 | duration u32\n * | payloadLen u32 | payload\n *\n * All little-endian. Kind 1 is voice (PCM16), kind 2/3 are face data, which\n * this SDK does not draw yet.\n */\nexport interface Packet {\n kind: number;\n final: boolean;\n corr: string;\n payload: Uint8Array;\n}\n\nexport function parsePacket(buf: ArrayBuffer): Packet | null {\n if (buf.byteLength < 25) return null;\n const v = new DataView(buf);\n if (v.getUint8(0) !== 0x43 || v.getUint8(1) !== 0x58 || v.getUint8(2) !== 0x59 || v.getUint8(3) !== 0x5a) return null;\n if (v.getUint8(4) !== 1) return null;\n const kind = v.getUint8(5);\n const final = (v.getUint8(6) & 1) !== 0;\n let o = 7;\n const corrLen = v.getUint16(o, true);\n o += 2;\n if (o + corrLen + 20 > buf.byteLength) return null;\n const corr = new TextDecoder().decode(new Uint8Array(buf, o, corrLen));\n o += corrLen + 4 + 8 + 4;\n const len = v.getUint32(o, true);\n o += 4;\n if (o + len > buf.byteLength) return null;\n return { kind, final, corr, payload: new Uint8Array(buf, o, len) };\n}\n\n/** Build one (for tests and tools). */\nexport function buildPacket(p: { kind: number; final: boolean; corr: string; payload: Uint8Array }): ArrayBuffer {\n const corr = new TextEncoder().encode(p.corr);\n const head = 7 + 2 + corr.length + 4 + 8 + 4 + 4;\n const buf = new ArrayBuffer(head + p.payload.byteLength);\n const v = new DataView(buf);\n const bytes = new Uint8Array(buf);\n bytes.set([0x43, 0x58, 0x59, 0x5a], 0);\n v.setUint8(4, 1);\n v.setUint8(5, p.kind);\n v.setUint8(6, p.final ? 1 : 0);\n let o = 7;\n v.setUint16(o, corr.length, true);\n o += 2;\n bytes.set(corr, o);\n o += corr.length + 4 + 8 + 4;\n v.setUint32(o, p.payload.byteLength, true);\n o += 4;\n bytes.set(p.payload, o);\n return buf;\n}\n","import { audioContext, PcmPlayer } from './audio/player.js';\nimport { openMic, type Mic } from './audio/mic.js';\nimport { Emitter } from './emitter.js';\nimport { CxError } from './errors.js';\nimport { readEvents, request, send } from './http.js';\nimport { parsePacket } from './protocol.js';\nimport type { SessionManager } from './session.js';\nimport type { CallEndReason, CallState, Caption } from './types.js';\n\nexport interface CallEvents extends Record<string, unknown> {\n state: CallState;\n /** The visitor's words and the agent's reply, as they are recognised. */\n caption: Caption;\n /** A caption the server withdrew (the visitor was not finished). */\n captionRemoved: string;\n /** The turn is ready: accept() within `holdSeconds`. */\n ready: { holdSeconds: number };\n /** One streamed face batch (kind-3 msgpack payload) for line `corr` — only with `face`. */\n face: { corr: string; payload: Uint8Array };\n /** A line of the agent's voice became audible, or ended (naturally or interrupted). */\n line: { corr: string; event: 'audible' | 'end' };\n error: CxError;\n}\n\nexport interface CallOptions {\n /** Join the moment it is this visitor's turn (default true). */\n autoAccept?: boolean;\n deviceId?: string;\n /**\n * Ask for the agent's face streamed with the voice (Neural Lip Sync), for a\n * UI that draws it. `emotion()` is read when the call connects: the face's\n * mood as the face service takes it (`joy:0.3`), or null for neutral.\n */\n face?: { emotion?: () => string | null };\n}\n\n/** Talking over the agent this loud, this long, stops her. */\nconst BARGE_IN_LEVEL = 0.09;\nconst BARGE_IN_MS = 350;\nconst HEARTBEAT_MS = 25_000;\n\nconst initial = (): CallState => ({\n phase: 'idle',\n callId: null,\n position: null,\n etaSeconds: null,\n holdSeconds: null,\n maxSeconds: null,\n startedAt: null,\n endReason: null,\n muted: false,\n speaking: false,\n agentState: 'idle',\n error: null,\n});\n\n/**\n * One voice call: join the line, wait (chatting is fine meanwhile), accept,\n * talk, hang up. A call is single-use; start another for the next one.\n */\nexport class Call extends Emitter<CallEvents> {\n private s: CallState = initial();\n private ticket: string | null = null;\n private eventsAbort: AbortController | null = null;\n private ws: WebSocket | null = null;\n private mic: Mic | null = null;\n private players = new Map<string, PcmPlayer>();\n private sampleRates = new Map<string, number>();\n private cancelled = new Set<string>();\n private speakingCorr: string | null = null;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private loudSince: number | null = null;\n\n constructor(\n private readonly apiUrl: string,\n private readonly session: SessionManager,\n private readonly agentId: string,\n private readonly opts: CallOptions = {},\n ) {\n super();\n }\n\n get state(): CallState {\n return this.s;\n }\n\n /** The line being voiced now, and how much of it has been heard (ms). */\n audible(): { corr: string; ms: number } | null {\n const corr = this.speakingCorr;\n const p = corr ? this.players.get(corr) : undefined;\n return corr && p ? { corr, ms: p.playedMs() } : null;\n }\n\n /** Loudness of the agent's voice right now, 0..1. */\n voiceLevel(): number {\n const p = this.speakingCorr ? this.players.get(this.speakingCorr) : undefined;\n return p ? p.level() : 0;\n }\n\n private set(patch: Partial<CallState>) {\n this.s = { ...this.s, ...patch };\n this.emit('state', this.s);\n }\n\n /**\n * Call from a click: it unlocks audio, asks for the microphone, then joins\n * the line (or goes straight through when a slot is free).\n */\n async start(): Promise<void> {\n if (this.s.phase !== 'idle') return;\n this.set({ phase: 'joining' });\n // Created inside the gesture, or the browser keeps it suspended.\n audioContext();\n try {\n this.mic = await openMic({ deviceId: this.opts.deviceId, onFrame: (pcm, level) => this.onMicFrame(pcm, level) });\n } catch {\n this.finish('mic-denied', 'Allow the microphone to talk, or chat instead.');\n return;\n }\n try {\n const token = await this.session.token();\n const r = await request<{ callId: string; state: string; position?: number; etaSeconds?: number }>(this.apiUrl, '/sdk/v1/calls', {\n method: 'POST',\n body: {},\n token,\n });\n this.set({ callId: r.callId, phase: r.state === 'ready' ? 'joining' : 'queued', position: r.position ?? null, etaSeconds: r.etaSeconds ?? null });\n void this.follow();\n } catch (e) {\n const err = e instanceof CxError ? e : new CxError('unknown', 'Could not start the call.');\n const reason: CallEndReason = err.code === 'rate_limited' ? 'busy' : 'unavailable';\n this.finish(reason, err.message);\n this.emit('error', err);\n }\n }\n\n /** Follow the call's server-side state, reconnecting the stream if it drops. */\n private async follow(): Promise<void> {\n let failures = 0;\n while (this.s.callId && this.s.phase !== 'ended' && this.s.phase !== 'idle') {\n this.eventsAbort = new AbortController();\n try {\n const token = await this.session.token();\n const res = await send(this.apiUrl, `/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`, { token, signal: this.eventsAbort.signal });\n failures = 0;\n await readEvents(res, (e) => this.onServerEvent(e.event, e.data as Record<string, unknown>), this.eventsAbort.signal);\n } catch (e) {\n if ((e as Error)?.name === 'AbortError') return;\n if (e instanceof CxError && e.code === 'not_found') {\n this.finish('failed', 'The call ended.');\n return;\n }\n failures += 1;\n if (failures > 5) {\n this.finish('failed', 'Lost the connection to the call.');\n return;\n }\n }\n if (this.ended()) return;\n await new Promise((r) => setTimeout(r, Math.min(4000, 500 * 2 ** failures)));\n }\n }\n\n private onServerEvent(event: string, d: Record<string, unknown>) {\n switch (event) {\n case 'queued':\n if (this.s.phase === 'joining' || this.s.phase === 'queued') {\n this.set({ phase: 'queued', position: Number(d.position) || 1, etaSeconds: Number(d.etaSeconds) || null });\n }\n break;\n case 'ready': {\n if (typeof d.ticket === 'string' && d.ticket) this.ticket = d.ticket;\n const hold = Number(d.holdSeconds) || 0;\n if (this.s.phase !== 'ready' && this.s.phase !== 'connecting' && this.s.phase !== 'live') {\n this.set({ phase: 'ready', holdSeconds: hold, position: null, etaSeconds: null });\n this.emit('ready', { holdSeconds: hold });\n if (this.opts.autoAccept !== false) this.accept();\n } else if (this.s.phase === 'ready') {\n this.set({ holdSeconds: hold });\n }\n break;\n }\n case 'live':\n this.set({ phase: 'live', maxSeconds: Number(d.maxSeconds) || null, startedAt: this.s.startedAt ?? Date.now() - (Number(d.elapsedSeconds) || 0) * 1000 });\n break;\n case 'ended':\n this.finish((String(d.reason || 'hangup') as CallEndReason) || 'hangup', null);\n break;\n }\n }\n\n // A method, not an inline comparison: the phase changes across an await,\n // which TypeScript's narrowing cannot see.\n private ended(): boolean {\n return this.s.phase === 'ended';\n }\n\n /** Take the call now that it is this visitor's turn. */\n accept(): void {\n if (this.s.phase !== 'ready' || !this.ticket || this.ws) return;\n this.set({ phase: 'connecting' });\n const url = this.apiUrl.replace(/^http/, 'ws') + '/sdk/v1/calls/socket';\n const ws = new WebSocket(url, [`cxyz-ticket.${this.ticket}`]);\n this.ticket = null;\n ws.binaryType = 'arraybuffer';\n this.ws = ws;\n ws.onopen = () => {\n const face = this.opts.face;\n const emotion = face?.emotion?.() ?? null;\n ws.send(\n JSON.stringify({\n type: 'agent_identity',\n agent_id: this.agentId,\n skin_index: 0,\n blendshapes: !!face,\n ...(face ? { blendshape_stream: true } : {}),\n ...(face && emotion ? { face_emotion: emotion } : {}),\n }),\n );\n // This page does not gate the microphone: the server's own voice\n // detection judges every frame.\n ws.send(JSON.stringify({ type: 'mic_state', silero: 'off', denoise: false }));\n this.heartbeat = setInterval(() => this.sendJson({ type: 'heartbeat' }), HEARTBEAT_MS);\n this.set({ phase: 'live', startedAt: this.s.startedAt ?? Date.now() });\n };\n ws.onmessage = (e) => this.onSocket(e.data);\n ws.onclose = () => {\n this.ws = null;\n // The event stream says why; give it a moment before calling it ourselves.\n setTimeout(() => {\n if (this.s.phase === 'live' || this.s.phase === 'connecting') this.finish('hangup', null);\n }, 1500);\n };\n }\n\n private sendJson(o: unknown) {\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(o));\n }\n\n private onMicFrame(pcm: ArrayBuffer, level: number) {\n const ws = this.ws;\n if (!ws || ws.readyState !== WebSocket.OPEN) return;\n if (this.speakingCorr) {\n // The agent must not hear itself: while she talks the frames go up as\n // silence, unless the visitor is clearly talking over her.\n const now = performance.now();\n if (level > BARGE_IN_LEVEL) {\n this.loudSince ??= now;\n if (now - this.loudSince >= BARGE_IN_MS) {\n this.loudSince = null;\n this.interrupt();\n ws.send(pcm);\n return;\n }\n } else {\n this.loudSince = null;\n }\n ws.send(new ArrayBuffer(pcm.byteLength));\n return;\n }\n ws.send(pcm);\n }\n\n private onSocket(data: unknown) {\n if (data instanceof ArrayBuffer) {\n const p = parsePacket(data);\n if (!p || this.cancelled.has(p.corr)) return;\n if (p.kind === 3) {\n // A copy, so the receiver may keep or transfer it.\n if (this.opts.face) this.emit('face', { corr: p.corr, payload: p.payload.slice() });\n return;\n }\n if (p.kind !== 1) return;\n let player = this.players.get(p.corr);\n if (!player) {\n // A new line: whatever was playing is over.\n for (const [c, old] of this.players) {\n old.stop();\n this.players.delete(c);\n }\n const corr = p.corr;\n player = new PcmPlayer({\n sampleRate: this.sampleRates.get(corr) ?? 16_000,\n onStart: () => {\n this.speakingCorr = corr;\n this.set({ speaking: true });\n this.emit('line', { corr, event: 'audible' });\n this.sendJson({ type: 'playback_started', correlationId: corr, timestampMs: Date.now() });\n },\n onEnd: () => {\n this.players.delete(corr);\n if (this.speakingCorr === corr) this.speakingCorr = null;\n this.set({ speaking: false });\n this.emit('line', { corr, event: 'end' });\n this.sendJson({ type: 'playback_ended', correlationId: corr, timestampMs: Date.now(), reason: 'natural' });\n this.sendJson({ type: 'speech_ended' });\n },\n });\n this.players.set(corr, player);\n }\n player.enqueue(p.payload);\n if (p.final) player.end();\n return;\n }\n if (typeof data !== 'string') return;\n let o: Record<string, unknown>;\n try {\n o = JSON.parse(data);\n } catch {\n return;\n }\n if ('AgentSpeechMeta' in o) {\n const m = o.AgentSpeechMeta as { correlation_id?: string; sample_rate?: number };\n if (m?.correlation_id && m.sample_rate) this.sampleRates.set(m.correlation_id, m.sample_rate);\n return;\n }\n if ('InteractorTranscript' in o) {\n const t = o.InteractorTranscript as { correlation_id: string; text: string };\n if (t?.text) this.emit('caption', { id: `v:${t.correlation_id}`, role: 'visitor', text: t.text });\n return;\n }\n if ('AgentReplyTranscript' in o) {\n const t = o.AgentReplyTranscript as { correlation_id: string; text: string };\n if (t?.text && !this.cancelled.has(t.correlation_id)) this.emit('caption', { id: `a:${t.correlation_id}`, role: 'agent', text: t.text });\n return;\n }\n if (o.type === 'turn_cancelled' && typeof o.correlationId === 'string') {\n const cid = o.correlationId;\n this.cancelled.add(cid);\n this.players.get(cid)?.stop();\n this.players.delete(cid);\n this.emit('line', { corr: cid, event: 'end' });\n if (this.speakingCorr === cid) {\n this.speakingCorr = null;\n this.set({ speaking: false });\n }\n this.emit('captionRemoved', `a:${cid}`);\n return;\n }\n if (o.kind === 'agent_status' && typeof o.state === 'string') {\n this.set({ agentState: o.state.toLowerCase() });\n }\n }\n\n /** Stop the agent mid-sentence (the visitor wants to speak). */\n interrupt(): void {\n const corr = this.speakingCorr;\n if (!corr) return;\n const p = this.players.get(corr);\n const heardMs = Math.round(p?.playedMs() ?? 0);\n p?.stop();\n this.players.delete(corr);\n this.cancelled.add(corr);\n this.speakingCorr = null;\n this.set({ speaking: false });\n this.emit('line', { corr, event: 'end' });\n this.sendJson({ type: 'playback_ended', correlationId: corr, timestampMs: Date.now(), reason: 'interrupted' });\n this.sendJson({ type: 'interrupt', correlationId: corr, heardMs, timestampMs: Date.now() });\n }\n\n setMuted(muted: boolean): void {\n this.mic?.setMuted(muted);\n this.set({ muted });\n }\n\n /** Leave the line, or hang up. */\n async hangUp(): Promise<void> {\n const id = this.s.callId;\n const was = this.s.phase;\n this.finish(was === 'live' ? 'hangup' : 'left', null);\n if (!id) return;\n try {\n const token = await this.session.token();\n await send(this.apiUrl, `/sdk/v1/calls/${encodeURIComponent(id)}`, { method: 'DELETE', token });\n } catch {\n // The server notices a closed socket / abandoned line on its own.\n }\n }\n\n private finish(reason: CallEndReason, error: string | null) {\n if (this.s.phase === 'ended') return;\n this.eventsAbort?.abort();\n this.eventsAbort = null;\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.heartbeat = null;\n for (const p of this.players.values()) p.stop();\n this.players.clear();\n this.speakingCorr = null;\n this.mic?.stop();\n this.mic = null;\n const ws = this.ws;\n this.ws = null;\n if (ws && ws.readyState <= WebSocket.OPEN) ws.close(1000);\n this.ticket = null;\n this.set({ phase: 'ended', endReason: reason, speaking: false, holdSeconds: null, error });\n }\n}\n","import { Emitter } from './emitter.js';\nimport { CxError } from './errors.js';\nimport { readEvents, request, send } from './http.js';\nimport type { SessionManager } from './session.js';\nimport type { ChatMessage } from './types.js';\n\nexport interface ChatEvents extends Record<string, unknown> {\n /** The whole list, after any change. */\n messages: ChatMessage[];\n /** True from send until the reply is complete. */\n busy: boolean;\n error: CxError;\n}\n\nlet localSeq = 0;\nconst localId = (p: string) => `${p}_${Date.now().toString(36)}_${(localSeq++).toString(36)}`;\n\n/**\n * Text chat with the agent. History lives on the server, so it follows the\n * visitor across page loads (and, for an identified visitor, devices).\n */\nexport class Chat extends Emitter<ChatEvents> {\n private list: ChatMessage[] = [];\n private loaded = false;\n private busy = false;\n private abort: AbortController | null = null;\n\n constructor(\n private readonly apiUrl: string,\n private readonly session: SessionManager,\n ) {\n super();\n }\n\n get messages(): readonly ChatMessage[] {\n return this.list;\n }\n\n get isBusy(): boolean {\n return this.busy;\n }\n\n private publish() {\n this.list = [...this.list];\n this.emit('messages', this.list);\n }\n\n /** Load earlier messages (once; later calls return what is held). */\n async load(): Promise<readonly ChatMessage[]> {\n if (this.loaded) return this.list;\n const token = await this.session.token();\n const res = await request<{ messages: ChatMessage[] }>(this.apiUrl, '/sdk/v1/chat/messages?limit=50', { token });\n // Anything sent while the history was loading stays after it.\n const pending = this.list;\n this.list = [...(res?.messages ?? []), ...pending];\n this.loaded = true;\n this.publish();\n return this.list;\n }\n\n /**\n * Send a message; the reply streams into `messages` as it is written.\n * Resolves with the finished reply.\n */\n async send(text: string): Promise<ChatMessage> {\n const t = text.trim();\n if (!t) throw new CxError('invalid', 'Say something first.');\n if (this.busy) throw new CxError('rate_limited', 'Wait for the reply first.');\n this.setBusy(true);\n const mine: ChatMessage = { id: localId('local'), role: 'visitor', text: t, createdAt: new Date().toISOString() };\n const reply: ChatMessage = { id: localId('reply'), role: 'agent', text: '', createdAt: new Date().toISOString(), streaming: true };\n this.list.push(mine, reply);\n this.publish();\n\n this.abort = new AbortController();\n try {\n const token = await this.session.token();\n const res = await send(this.apiUrl, '/sdk/v1/chat/messages', { method: 'POST', body: { text: t }, token, signal: this.abort.signal });\n let finished: ChatMessage | null = null;\n let failure: string | null = null;\n await readEvents(\n res,\n ({ event, data }) => {\n const d = data as Record<string, unknown>;\n if (event === 'delta' && typeof d?.text === 'string') {\n reply.text += d.text;\n this.publish();\n } else if (event === 'done') {\n finished = { id: String(d.id), role: 'agent', text: String(d.text ?? reply.text), createdAt: String(d.createdAt ?? reply.createdAt) };\n } else if (event === 'error') {\n failure = typeof d?.message === 'string' ? d.message : 'Something went wrong.';\n }\n },\n this.abort.signal,\n );\n if (failure || !finished) throw new CxError('unknown', failure ?? 'The reply was cut off. Try again.');\n const done: ChatMessage = finished;\n this.replace(reply.id, done);\n return done;\n } catch (e) {\n const err = e instanceof CxError ? e : new CxError('network', 'The reply was cut off. Try again.');\n this.list = this.list.filter((m) => m.id !== reply.id);\n const idx = this.list.findIndex((m) => m.id === mine.id);\n // A refusal the server explained (a daily limit, a slow-down) is shown as\n // it was said; anything else is the generic \"not sent\".\n if (idx !== -1) this.list[idx] = { ...mine, failed: true, ...(err.status === 429 ? { error: err.message } : {}) };\n this.publish();\n if ((e as Error)?.name !== 'AbortError') this.emit('error', err);\n throw err;\n } finally {\n this.abort = null;\n this.setBusy(false);\n }\n }\n\n /** Send a failed message again. */\n retry(id: string): Promise<ChatMessage> {\n const m = this.list.find((x) => x.id === id && x.failed);\n if (!m) throw new CxError('not_found', 'Nothing to retry.');\n this.list = this.list.filter((x) => x.id !== id);\n this.publish();\n return this.send(m.text);\n }\n\n /** Stop listening to a reply in progress (the server still finishes it). */\n stop(): void {\n this.abort?.abort();\n }\n\n private replace(id: string, next: ChatMessage) {\n const i = this.list.findIndex((m) => m.id === id);\n if (i !== -1) this.list[i] = next;\n this.publish();\n }\n\n private setBusy(b: boolean) {\n this.busy = b;\n this.emit('busy', b);\n }\n}\n","import { CxError } from './errors.js';\nimport { request } from './http.js';\nimport type { SessionInfo } from './types.js';\n\n/** Where the SDK may remember this browser's anonymous visitor id. */\nexport interface VisitorStore {\n get(key: string): string | null;\n set(key: string, value: string): void;\n}\n\nexport const memoryStore = (): VisitorStore => {\n const m = new Map<string, string>();\n return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v) };\n};\n\nexport const localStore = (): VisitorStore => ({\n get(k) {\n try {\n return globalThis.localStorage?.getItem(k) ?? null;\n } catch {\n return null;\n }\n },\n set(k, v) {\n try {\n globalThis.localStorage?.setItem(k, v);\n } catch {\n // private mode / blocked storage: the visitor is simply new each time\n }\n },\n});\n\nexport interface SessionSource {\n apiUrl: string;\n agentId?: string;\n /** Browser path: a publishable key, exchanged from this page's origin. */\n publishableKey?: string;\n /**\n * Server path: your backend mints the session with a secret key (an\n * identified visitor) and hands the token to the page. Called again when\n * the session is about to run out.\n */\n getSessionToken?: () => Promise<string | SessionInfo>;\n store: VisitorStore;\n}\n\n/** Renew this long before expiry. */\nconst RENEW_EARLY_S = 60;\n\n/**\n * Holds the current session, renews it before it runs out, and never runs\n * two renewals at once.\n */\nexport class SessionManager {\n private current: SessionInfo | null = null;\n private inflight: Promise<SessionInfo> | null = null;\n\n constructor(private readonly src: SessionSource) {\n if (!src.publishableKey && !src.getSessionToken) {\n throw new CxError('invalid', 'Pass a publishableKey, or getSessionToken for sessions your server mints.');\n }\n }\n\n private visitorKey(): string {\n // Per key, so two brands on one domain never share a visitor.\n const k = this.src.publishableKey ?? 'server';\n return `cxyz:visitor:${k.slice(-12)}`;\n }\n\n get info(): SessionInfo | null {\n return this.current;\n }\n\n /** A token valid for at least the next minute. */\n async token(): Promise<string> {\n const now = Date.now() / 1000;\n if (this.current && this.current.expiresAt - RENEW_EARLY_S > now) return this.current.token;\n return (await this.refresh()).token;\n }\n\n refresh(): Promise<SessionInfo> {\n this.inflight ??= this.mint().finally(() => {\n this.inflight = null;\n });\n return this.inflight;\n }\n\n private async mint(): Promise<SessionInfo> {\n let info: SessionInfo;\n if (this.src.getSessionToken) {\n const got = await this.src.getSessionToken();\n if (typeof got === 'string') {\n // A bare token: ask the server what it unlocks.\n info = await this.describe(got);\n } else {\n info = got;\n }\n } else {\n const visitorId = this.src.store.get(this.visitorKey()) ?? undefined;\n info = await request<SessionInfo>(this.src.apiUrl, '/sdk/v1/sessions', {\n method: 'POST',\n body: { publishableKey: this.src.publishableKey, agentId: this.src.agentId, visitorId },\n });\n this.src.store.set(this.visitorKey(), info.visitorId);\n }\n this.current = info;\n return info;\n }\n\n /** The session behind a token minted elsewhere (`getSessionToken` returned a string). */\n private async describe(token: string): Promise<SessionInfo> {\n const info = await request<SessionInfo>(this.src.apiUrl, '/sdk/v1/session', { token });\n return { ...info, token };\n }\n}\n","import { Call, type CallOptions } from './call.js';\nimport { Chat } from './chat.js';\nimport { Emitter } from './emitter.js';\nimport { CxError } from './errors.js';\nimport { request } from './http.js';\nimport { localStore, memoryStore, SessionManager, type VisitorStore } from './session.js';\nimport type { AgentCard, Features, SessionInfo } from './types.js';\n\nexport const DEFAULT_API_URL = 'https://api.character.xyz';\n\nexport interface InitOptions {\n /** `cxyz_pk_live_…` — safe in the page; works only from the key's allowed sites. */\n publishableKey?: string;\n /**\n * For signed-in visitors: return a session your server minted with its\n * secret key (see `@characterxyz/server`). Called again before expiry.\n */\n getSessionToken?: () => Promise<string | SessionInfo>;\n /** Which of the key's agents to talk to. Defaults to the key's first. */\n agentId?: string;\n /** Override the API (staging, local development). */\n apiUrl?: string;\n /** Remember the anonymous visitor across visits (default) or not at all. */\n storage?: 'local' | 'memory' | VisitorStore;\n}\n\nexport interface ClientEvents extends Record<string, unknown> {\n /** A call started or ended; the widget swaps its view on this. */\n call: Call | null;\n error: CxError;\n}\n\n/**\n * The headless SDK. `await CharacterXYZ.init({ publishableKey })`, then use\n * `chat` and `startCall()`. Everything the widget does goes through here, so\n * a brand can build its own UI on the same calls.\n */\nexport class CharacterXYZ extends Emitter<ClientEvents> {\n readonly chat: Chat;\n private currentCall: Call | null = null;\n private destroyed = false;\n\n private constructor(\n readonly apiUrl: string,\n private readonly session: SessionManager,\n private info: SessionInfo,\n ) {\n super();\n this.chat = new Chat(apiUrl, session);\n }\n\n static async init(opts: InitOptions): Promise<CharacterXYZ> {\n const apiUrl = (opts.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, '');\n if (opts.publishableKey && /^cxyz_sk_/.test(opts.publishableKey)) {\n // A secret key in a page is a leak. Refuse loudly, before it is sent anywhere.\n throw new CxError('invalid', 'That is a SECRET key. Never put it in a web page: use a publishable key (cxyz_pk_…). Revoke the secret key now.');\n }\n const store = opts.storage === 'memory' ? memoryStore() : opts.storage && typeof opts.storage === 'object' ? opts.storage : localStore();\n const session = new SessionManager({ apiUrl, agentId: opts.agentId, publishableKey: opts.publishableKey, getSessionToken: opts.getSessionToken, store });\n const info = await session.refresh();\n return new CharacterXYZ(apiUrl, session, info);\n }\n\n get agent(): AgentCard {\n return (this.session.info ?? this.info).agent;\n }\n\n get features(): Features {\n return (this.session.info ?? this.info).features;\n }\n\n get appearance(): Record<string, unknown> {\n return (this.session.info ?? this.info).appearance ?? {};\n }\n\n get visitorId(): string {\n return (this.session.info ?? this.info).visitorId;\n }\n\n get mode(): 'live' | 'test' {\n return (this.session.info ?? this.info).mode;\n }\n\n /** The call in progress (queued, ready or live), if any. */\n get call(): Call | null {\n return this.currentCall && this.currentCall.state.phase !== 'ended' ? this.currentCall : null;\n }\n\n /**\n * The worn video character's full render data (the public projection the\n * app's Stage reads), for a UI that draws the face — the widget hands it to\n * the app's renderer. Null when the agent wears none.\n */\n async videoAvatar(): Promise<Record<string, unknown> | null> {\n const token = await this.session.token();\n return request<Record<string, unknown> | null>(this.apiUrl, '/sdk/v1/agent/video-avatar', { token });\n }\n\n /** Start a voice call. Call from a click: it needs the microphone and audio unlocked. */\n async startCall(opts: CallOptions = {}): Promise<Call> {\n if (this.destroyed) throw new CxError('invalid', 'This client was destroyed.');\n if (!this.features.call) throw new CxError('forbidden', 'Calls are not available on this site.');\n if (this.call) return this.call;\n const call = new Call(this.apiUrl, this.session, this.agent.id, opts);\n this.currentCall = call;\n call.on('state', (s) => {\n if (s.phase === 'ended' && this.currentCall === call) this.emit('call', null);\n });\n call.on('error', (e) => this.emit('error', e));\n this.emit('call', call);\n await call.start();\n return call;\n }\n\n destroy(): void {\n this.destroyed = true;\n void this.currentCall?.hangUp();\n this.chat.stop();\n this.chat.clear();\n this.clear();\n }\n}\n","/**\n * `@characterxyz/web` — Character XYZ on any web page, headless.\n *\n * ```ts\n * import { CharacterXYZ } from '@characterxyz/web';\n *\n * const cx = await CharacterXYZ.init({ publishableKey: 'cxyz_pk_live_…' });\n * cx.chat.on('messages', render);\n * await cx.chat.send('Hi!');\n *\n * button.onclick = async () => {\n * const call = await cx.startCall();\n * call.on('state', (s) => show(s.phase, s.position));\n * };\n * ```\n *\n * The ready-made widget is `@characterxyz/widget`; this package is what it\n * is built on, for brands who want their own UI.\n */\nexport { CharacterXYZ, DEFAULT_API_URL, type InitOptions, type ClientEvents } from './client.js';\nexport { Chat, type ChatEvents } from './chat.js';\nexport { Call, type CallEvents, type CallOptions } from './call.js';\nexport { CxError, type CxErrorCode } from './errors.js';\nexport { Emitter } from './emitter.js';\nexport type { VisitorStore } from './session.js';\nexport type {\n AgentCard,\n CallEndReason,\n CallPhase,\n CallState,\n Caption,\n ChatMessage,\n Features,\n SessionInfo,\n VideoCharacter,\n VideoClip,\n} from './types.js';\nexport const VERSION = '0.1.0';\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {import('./index').ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tif (node && node.parentNode) node.parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n","import { slice } from './util';\nimport options from './options';\nimport { NULL, UNDEFINED } from './constants';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array<import('.').ComponentChildren>} [children] The children of the\n * virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != NULL) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === UNDEFINED) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, NULL);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {import('./internal').VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: NULL,\n\t\t_parent: NULL,\n\t\t_depth: 0,\n\t\t_dom: NULL,\n\t\t_component: NULL,\n\t\tconstructor: UNDEFINED,\n\t\t_original: original == NULL ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == NULL && options.vnode != NULL) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: NULL };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != NULL && vnode.constructor === UNDEFINED;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE, NULL } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != NULL && this._nextState != this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == NULL) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == NULL) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: NULL;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != NULL && sibling._dom != NULL) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tif (component._parentDom && component._dirty) {\n\t\tlet oldVNode = component._vnode,\n\t\t\toldDom = oldVNode._dom,\n\t\t\tcommitQueue = [],\n\t\t\trefQueue = [],\n\t\t\tnewVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL,\n\t\t\tcommitQueue,\n\t\t\toldDom == NULL ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\t\toldVNode._dom = oldVNode._parent = null;\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != NULL && vnode._component != NULL) {\n\t\tvnode._dom = vnode._component.base = NULL;\n\t\tvnode._children.some(child => {\n\t\t\tif (child != NULL && child._dom != NULL) {\n\t\t\t\treturn (vnode._dom = vnode._component.base = child._dom);\n\t\t\t}\n\t\t});\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array<import('./internal').Component>}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce != options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\ttry {\n\t\tlet c,\n\t\t\tl = 1;\n\n\t\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t\t// process() calls from getting scheduled while `queue` is still being consumed.\n\t\twhile (rerenderQueue.length) {\n\t\t\t// Keep the rerender queue sorted by (depth, insertion order). The queue\n\t\t\t// will initially be sorted on the first iteration only if it has more than 1 item.\n\t\t\t//\n\t\t\t// New items can be added to the queue e.g. when rerendering a provider, so we want to\n\t\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t\t// single pass\n\t\t\tif (rerenderQueue.length > l) {\n\t\t\t\trerenderQueue.sort(depthSort);\n\t\t\t}\n\n\t\t\tc = rerenderQueue.shift();\n\t\t\tl = rerenderQueue.length;\n\n\t\t\trenderComponent(c);\n\t\t}\n\t} finally {\n\t\trerenderQueue.length = process._rerenderCount = 0;\n\t}\n}\n\nprocess._rerenderCount = 0;\n","import { IS_NON_DIMENSIONAL, NULL, SVG_NAMESPACE } from '../constants';\nimport options from '../options';\n\n// Per-instance unique key for event clock stamps. Each Preact copy on the page\n// gets its own random suffix so that `_dispatched` / `_attached` properties on\n// shared event objects and handler functions cannot collide across instances.\n// ~1 in 60M collision odds - if you have that many praect versions on the page,\n// you deserve some weird bugs.\n// In 11 we can replace this with a\n// Symbol\nlet _id = Math.random().toString(8),\n\tEVENT_DISPATCHED = '__d' + _id,\n\tEVENT_ATTACHED = '__a' + _id;\n\nfunction setStyle(style, key, value) {\n\tif (key[0] == '-') {\n\t\tstyle.setProperty(key, value == NULL ? '' : value);\n\t} else if (value == NULL) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\nconst CAPTURE_REGEX = /(PointerCapture)$|Capture$/i;\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name == 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] != oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] == 'o' && name[1] == 'n') {\n\t\tuseCapture = name != (name = name.replace(CAPTURE_REGEX, '$1'));\n\t\tconst lowerCaseName = name.toLowerCase();\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (lowerCaseName in dom || name == 'onFocusOut' || name == 'onFocusIn')\n\t\t\tname = lowerCaseName.slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue[EVENT_ATTACHED] = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue[EVENT_ATTACHED] = oldValue[EVENT_ATTACHED];\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == SVG_NAMESPACE) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == NULL ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != NULL && (value !== false || name[4] == '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {import('../internal').PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e[EVENT_DISPATCHED] == NULL) {\n\t\t\t\te[EVENT_DISPATCHED] = eventClock++;\n\n\t\t\t\t// When `e[EVENT_DISPATCHED]` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e[EVENT_DISPATCHED] < eventHandler[EVENT_ATTACHED]) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n","import { enqueueRender } from './component';\nimport { NULL } from './constants';\n\nexport let i = 0;\n\nexport function createContext(defaultValue) {\n\tfunction Context(props) {\n\t\tif (!this.getChildContext) {\n\t\t\t/** @type {Set<import('./internal').Component> | null} */\n\t\t\tlet subs = new Set();\n\t\t\tlet ctx = {};\n\t\t\tctx[Context._id] = this;\n\n\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\tsubs = NULL;\n\t\t\t};\n\n\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t// @ts-expect-error even\n\t\t\t\tif (this.props.value != _props.value) {\n\t\t\t\t\tsubs.forEach(c => {\n\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.sub = c => {\n\t\t\t\tsubs.add(c);\n\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\tif (subs) {\n\t\t\t\t\t\tsubs.delete(c);\n\t\t\t\t\t}\n\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn props.children;\n\t}\n\n\tContext._id = '__cC' + i++;\n\tContext._defaultValue = defaultValue;\n\n\t/** @type {import('./internal').FunctionComponent} */\n\tContext.Consumer = (props, contextValue) => {\n\t\treturn props.children(contextValue);\n\t};\n\n\t// we could also get rid of _contextRef entirely\n\tContext.Provider =\n\t\tContext._contextRef =\n\t\tContext.Consumer.contextType =\n\t\t\tContext;\n\n\treturn Context;\n}\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport {\n\tEMPTY_OBJ,\n\tEMPTY_ARR,\n\tINSERT_VNODE,\n\tMATCHED,\n\tUNDEFINED,\n\tNULL\n} from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\toldDom = constructNewChildrenArray(\n\t\tnewParentVNode,\n\t\trenderResult,\n\t\toldChildren,\n\t\toldDom,\n\t\tnewChildrenLength\n\t);\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (childVNode == NULL) continue;\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\toldVNode =\n\t\t\t(childVNode._index != -1 && oldChildren[childVNode._index]) || EMPTY_OBJ;\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tlet result = diff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, NULL, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == NULL && newDom != NULL) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tif (childVNode._flags & INSERT_VNODE) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom);\n\n\t\t\t// When a matched VNode is physically moved via INSERT_VNODE, its old\n\t\t\t// _dom pointer becomes a stale positional reference. Clear it so that\n\t\t\t// getDomSibling (called from nested diffs) won't return this stale\n\t\t\t// reference and mis-place subsequent DOM nodes. See #5065.\n\t\t\tif (oldVNode._dom) {\n\t\t\t\toldVNode._dom = NULL;\n\t\t\t}\n\t\t} else if (typeof childVNode.type == 'function' && result !== UNDEFINED) {\n\t\t\toldDom = result;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(\n\tnewParentVNode,\n\trenderResult,\n\toldChildren,\n\toldDom,\n\tnewChildrenLength\n) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = new Array(newChildrenLength);\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == NULL ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tnewParentVNode._children[i] = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t// If this newVNode is being reused (e.g. <div>{reuse}{reuse}</div>) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tNULL,\n\t\t\t\tchildVNode,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse = <div />\n\t\t\t// <div>{reuse}<span />{reuse}</div>\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : NULL,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tnewParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tconst matchingIndex = (childVNode._index = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t));\n\n\t\toldVNode = NULL;\n\t\tif (matchingIndex != -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original == null\n\t\tconst isMounting = oldVNode == NULL || oldVNode._original == NULL;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\t// When the array of children is growing we need to decrease the skew\n\t\t\t\t// as we are adding a new element to the array.\n\t\t\t\t// Example:\n\t\t\t\t// [1, 2, 3] --> [0, 1, 2, 3]\n\t\t\t\t// oldChildren newChildren\n\t\t\t\t//\n\t\t\t\t// The new element is at index 0, so our skew is 0,\n\t\t\t\t// we need to decrease the skew as we are adding a new element.\n\t\t\t\t// The decrease will cause us to compare the element at position 1\n\t\t\t\t// with value 1 with the element at position 0 with value 0.\n\t\t\t\t//\n\t\t\t\t// A linear concept is applied when the array is shrinking,\n\t\t\t\t// if the length is unchanged we can assume that no skew\n\t\t\t\t// changes are needed.\n\t\t\t\tif (newChildrenLength > oldChildrenLength) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else if (newChildrenLength < oldChildrenLength) {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex != skewedIndex) {\n\t\t\t// When we move elements around i.e. [0, 1, 2] --> [1, 0, 2]\n\t\t\t// --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0\n\t\t\t// we set the skew to 1 as we found an offset.\n\t\t\t// --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1\n\t\t\t// this makes us increase the skew again.\n\t\t\t// --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2\n\t\t\t//\n\t\t\t// this becomes an optimization question where currently we see a 1 element offset as an insertion\n\t\t\t// or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2]\n\t\t\t// while a more than 1 offset we see as a swap.\n\t\t\t// We could probably build heuristics for having an optimized course of action here as well, but\n\t\t\t// might go at the cost of some bytes.\n\t\t\t//\n\t\t\t// If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have\n\t\t\t// only the first item be a re-scouting and all the others fall in their skewed counter-part.\n\t\t\t// We could also further optimize for swaps\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else {\n\t\t\t\tif (matchingIndex > skewedIndex) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\n\t\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t\t// match the new skew index (i + new skew)\n\t\t\t\t// In the former two branches we know that it matches after skewing\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) {\n\t\t\t\tif (oldVNode._dom == oldDom) {\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (oldDom && parentVNode.type && !oldDom.parentNode) {\n\t\t\toldDom = getDomSibling(parentVNode);\n\t\t}\n\t\toldDom = parentDom.insertBefore(parentVNode._dom, oldDom || NULL);\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != NULL && oldDom.nodeType == 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == NULL || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet oldVNode = oldChildren[skewedIndex];\n\tconst matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0;\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\t//\n\t// If there is an unkeyed functional VNode, that isn't a built-in like our Fragment,\n\t// we should not search as we risk re-using state of an unrelated VNode. (reverted for now)\n\tlet shouldSearch =\n\t\t// (typeof type != 'function' || type === Fragment || key) &&\n\t\tremainingOldChildren > (matched ? 1 : 0);\n\n\tif (\n\t\t(oldVNode === NULL && key == null) ||\n\t\t(matched && key == oldVNode.key && type == oldVNode.type)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\tlet x = skewedIndex - 1;\n\t\tlet y = skewedIndex + 1;\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tconst childIndex = x >= 0 ? x-- : y++;\n\t\t\toldVNode = oldChildren[childIndex];\n\t\t\tif (\n\t\t\t\toldVNode != NULL &&\n\t\t\t\t(oldVNode._flags & MATCHED) == 0 &&\n\t\t\t\tkey == oldVNode.key &&\n\t\t\t\ttype == oldVNode.type\n\t\t\t) {\n\t\t\t\treturn childIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n","import {\n\tEMPTY_ARR,\n\tEMPTY_OBJ,\n\tMATH_NAMESPACE,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tNULL,\n\tRESET_MODE,\n\tSVG_NAMESPACE,\n\tUNDEFINED,\n\tXHTML_NAMESPACE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * @template {any} T\n * @typedef {import('../internal').Ref<T>} Ref<T>\n */\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== UNDEFINED) return NULL;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\tlet oldCommitQueueLength = commitQueue.length;\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent = newType.prototype && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == NULL) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != NULL) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tc.componentWillMount != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tnewVNode._original == oldVNode._original ||\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != NULL &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original != oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.some(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tEMPTY_ARR.push.apply(c._renderCallbacks, c._stateCallbacks);\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Skip over the retained subtree without traversing it; the\n\t\t\t\t\t// `result` branch in diffChildren picks this up as the next\n\t\t\t\t\t// oldDom.\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != NULL) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tEMPTY_ARR.push.apply(c._renderCallbacks, c._stateCallbacks);\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != NULL) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet renderResult =\n\t\t\t\ttmp != NULL && tmp.type === Fragment && tmp.key == NULL\n\t\t\t\t\t? cloneNode(tmp.props.children)\n\t\t\t\t\t: tmp;\n\n\t\t\toldDom = diffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = NULL;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// We remove any componentDidMount, ...\n\t\t\t// that have been invalidated by us\n\t\t\t// intercepting the error.\n\t\t\tcommitQueue.length = oldCommitQueueLength;\n\t\t\tnewVNode._original = NULL;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != NULL) {\n\t\t\t\tif (e.then) {\n\t\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t\t: MODE_SUSPENDED;\n\n\t\t\t\t\twhile (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) {\n\t\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\t} else if (excessDomChildren != NULL) {\n\t\t\t\t\tfor (let i = excessDomChildren.length; i--; ) {\n\t\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t}\n\n\t\t\tif (newVNode._children == NULL) {\n\t\t\t\tnewVNode._children = oldVNode._children || [];\n\t\t\t}\n\n\t\t\tif (!e.then) markAsForce(newVNode);\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == NULL &&\n\t\tnewVNode._original == oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\toldDom = newVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n\n\treturn newVNode._flags & MODE_SUSPENDED ? undefined : oldDom;\n}\n\nfunction markAsForce(vnode) {\n\tif (vnode) {\n\t\tif (vnode._component) vnode._component._force = true;\n\t\tif (vnode._children) vnode._children.some(markAsForce);\n\t}\n}\n\n/**\n * @param {Array<Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\nfunction cloneNode(node) {\n\tif (typeof node != 'object' || node == NULL || node._depth > 0) {\n\t\treturn node;\n\t}\n\n\tif (isArray(node)) {\n\t\treturn node.map(cloneNode);\n\t}\n\n\tif (node.constructor !== UNDEFINED) return null;\n\n\treturn assign({}, node);\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props || EMPTY_OBJ;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType == 'svg') namespace = SVG_NAMESPACE;\n\telse if (nodeType == 'math') namespace = MATH_NAMESPACE;\n\telse if (!namespace) namespace = XHTML_NAMESPACE;\n\n\tif (excessDomChildren != NULL) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value == !!nodeType &&\n\t\t\t\t(nodeType ? value.localName == nodeType : value.nodeType == 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == NULL) {\n\t\tif (nodeType == NULL) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tif (isHydrating) {\n\t\t\tif (options._hydrationMismatch)\n\t\t\t\toptions._hydrationMismatch(newVNode, excessDomChildren);\n\t\t\tisHydrating = false;\n\t\t}\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = NULL;\n\t}\n\n\tif (nodeType == NULL) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data != newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren =\n\t\t\tnodeType == 'textarea' && newProps.defaultValue != NULL\n\t\t\t\t? NULL\n\t\t\t\t: excessDomChildren && slice.call(dom.childNodes);\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != NULL) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (\n\t\t\t\ti != 'children' &&\n\t\t\t\t!(i in newProps) &&\n\t\t\t\t!(i == 'value' && 'defaultValue' in newProps) &&\n\t\t\t\t!(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, NULL, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnewVNode.type == 'template' ? dom.content : dom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating || nodeType == 'textarea') {\n\t\t\ti = 'value';\n\t\t\tif (nodeType == 'progress' && inputValue == NULL) {\n\t\t\t\tdom.removeAttribute('value');\n\t\t\t} else if (\n\t\t\t\tinputValue != UNDEFINED &&\n\t\t\t\t// #2756 For the <progress>-element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType == 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix <select> value not being updated.\n\t\t\t\t\t// To avoid a stale select value we need to set the option.value\n\t\t\t\t\t// again, which triggers IE11 to re-evaluate the select value\n\t\t\t\t\t(nodeType == 'option' && inputValue != oldProps[i]))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, inputValue, oldProps[i], namespace);\n\t\t\t}\n\n\t\t\ti = 'checked';\n\t\t\tif (checked != UNDEFINED && checked != dom[i]) {\n\t\t\t\tsetProperty(dom, i, checked, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {Ref<any> & { _unmount?: unknown }} ref\n * @param {any} value\n * @param {VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') {\n\t\t\tlet hasRefUnmount = typeof ref._unmount == 'function';\n\t\t\tif (hasRefUnmount) {\n\t\t\t\t// @ts-ignore TS doesn't like moving narrowing checks into variables\n\t\t\t\tref._unmount();\n\t\t\t}\n\n\t\t\tif (!hasRefUnmount || value != NULL) {\n\t\t\t\t// Store the cleanup function on the function\n\t\t\t\t// instance object itself to avoid shape\n\t\t\t\t// transitioning vnode\n\t\t\t\tref._unmount = ref(value);\n\t\t\t}\n\t\t} else ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {VNode} vnode The virtual node to unmount\n * @param {VNode} parentVNode The parent of the VNode that initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current == vnode._dom) {\n\t\t\tapplyRef(r, NULL, parentVNode);\n\t\t}\n\t}\n\n\tif ((r = vnode._component) != NULL) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = r._globalContext = NULL;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) {\n\t\t\t\tunmount(\n\t\t\t\t\tr[i],\n\t\t\t\t\tparentVNode,\n\t\t\t\t\tskipRemove || typeof vnode.type != 'function'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!skipRemove) {\n\t\tremoveNode(vnode._dom);\n\t}\n\n\tvnode._component = vnode._parent = vnode._dom = UNDEFINED;\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, NULL } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\nimport { slice } from './util';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\t// https://github.com/preactjs/preact/issues/3794\n\tif (parentDom == document) {\n\t\tparentDom = document.documentElement;\n\t}\n\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode == 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? NULL\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = ((!isHydrating && replaceNode) || parentDom)._children =\n\t\tcreateElement(Fragment, NULL, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [],\n\t\trefQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.namespaceURI,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t\t? NULL\n\t\t\t\t: parentDom.firstChild\n\t\t\t\t\t? slice.call(parentDom.childNodes)\n\t\t\t\t\t: NULL,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t\t? oldVNode._dom\n\t\t\t\t: parentDom.firstChild,\n\t\tisHydrating,\n\t\trefQueue\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode, refQueue);\n\n\t// The live children are tracked on _children after diffing.\n\tvnode.props.children = NULL;\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","import { assign, slice } from './util';\nimport { createVNode } from './create-element';\nimport { NULL, UNDEFINED } from './constants';\n\n/**\n * Clones the given VNode, optionally adding attributes/props and replacing its\n * children.\n * @param {import('./internal').VNode} vnode The virtual DOM element to clone\n * @param {object} props Attributes/props to add when cloning\n * @param {Array<import('./internal').ComponentChildren>} rest Any additional arguments will be used\n * as replacement children.\n * @returns {import('./internal').VNode}\n */\nexport function cloneElement(vnode, props, children) {\n\tlet normalizedProps = assign({}, vnode.props),\n\t\tkey,\n\t\tref,\n\t\ti;\n\n\tlet defaultProps;\n\n\tif (vnode.type && vnode.type.defaultProps) {\n\t\tdefaultProps = vnode.type.defaultProps;\n\t}\n\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse if (props[i] === UNDEFINED && defaultProps != UNDEFINED) {\n\t\t\tnormalizedProps[i] = defaultProps[i];\n\t\t} else {\n\t\t\tnormalizedProps[i] = props[i];\n\t\t}\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\treturn createVNode(\n\t\tvnode.type,\n\t\tnormalizedProps,\n\t\tkey || vnode.key,\n\t\tref || vnode.ref,\n\t\tNULL\n\t);\n}\n","import { NULL } from '../constants';\n\n/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except\n * for unmounting when this parameter is the highest parent that was being\n * unmounted)\n * @param {import('../internal').VNode} [oldVNode]\n * @param {import('../internal').ErrorInfo} [errorInfo]\n */\nexport function _catchError(error, vnode, oldVNode, errorInfo) {\n\t/** @type {import('../internal').Component} */\n\tlet component,\n\t\t/** @type {import('../internal').ComponentType} */\n\t\tctor,\n\t\t/** @type {boolean} */\n\t\thandled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != NULL) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != NULL) {\n\t\t\t\t\tcomponent.componentDidCatch(error, errorInfo || {});\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { options as _options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n\n/** @type {import('./internal').Component} */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array<import('./internal').Component>} */\nlet afterPaintEffects = [];\n\n// Cast to use internal Options type\nconst options = /** @type {import('./internal').Options} */ (_options);\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\nlet oldRoot = options._root;\n\n// We take the minimum timeout for requestAnimationFrame to ensure that\n// the callback is invoked after the next frame. 35ms is based on a 30hz\n// refresh rate, which is the minimum rate for a smooth user experience.\nconst RAF_TIMEOUT = 35;\nlet prevRaf;\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._root = (vnode, parentDom) => {\n\tif (vnode && parentDom._children && parentDom._children._mask) {\n\t\tvnode._mask = parentDom._children._mask;\n\t}\n\n\tif (oldRoot) oldRoot(vnode, parentDom);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\tif (previousComponent === currentComponent) {\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentComponent._renderCallbacks = [];\n\t\t\thooks._list.some(hookItem => {\n\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t}\n\t\t\t\thookItem._pendingArgs = hookItem._nextValue = undefined;\n\t\t\t});\n\t\t} else {\n\t\t\thooks._pendingEffects.some(invokeCleanup);\n\t\t\thooks._pendingEffects.some(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentIndex = 0;\n\t\t}\n\t}\n\tpreviousComponent = currentComponent;\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tif (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));\n\t\tc.__hooks._list.some(hookItem => {\n\t\t\tif (hookItem._pendingArgs) {\n\t\t\t\thookItem._args = hookItem._pendingArgs;\n\t\t\t\thookItem._pendingArgs = undefined;\n\t\t\t}\n\t\t});\n\t}\n\tpreviousComponent = currentComponent = null;\n};\n\n// TODO: Improve typing of commitQueue parameter\n/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.some(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tlet hasErrored;\n\t\tc.__hooks._list.some(s => {\n\t\t\ttry {\n\t\t\t\tinvokeCleanup(s);\n\t\t\t} catch (e) {\n\t\t\t\thasErrored = e;\n\t\t\t}\n\t\t});\n\t\tc.__hooks = undefined;\n\t\tif (hasErrored) options._catchError(hasErrored, c._vnode);\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\n\treturn hooks._list[index];\n}\n\n/**\n * @template {unknown} S\n * @param {import('./index').Dispatch<import('./index').StateUpdater<S>>} [initialState]\n * @returns {[S, (state: S) => void]}\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @template {unknown} S\n * @template {unknown} A\n * @param {import('./index').Reducer<S, A>} reducer\n * @param {import('./index').Dispatch<import('./index').StateUpdater<S>>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ S, (state: S) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst currentValue = hookState._nextValue\n\t\t\t\t\t? hookState._nextValue[0]\n\t\t\t\t\t: hookState._value[0];\n\t\t\t\tconst nextValue = hookState._reducer(currentValue, action);\n\n\t\t\t\tif (currentValue !== nextValue) {\n\t\t\t\t\thookState._nextValue = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\n\t\tif (!currentComponent._hasScuFromHooks) {\n\t\t\tcurrentComponent._hasScuFromHooks = true;\n\t\t\tlet prevScu = currentComponent.shouldComponentUpdate;\n\t\t\tconst prevCWU = currentComponent.componentWillUpdate;\n\n\t\t\t// If we're dealing with a forced update `shouldComponentUpdate` will\n\t\t\t// not be called. But we use that to update the hook values, so we\n\t\t\t// need to call it.\n\t\t\tcurrentComponent.componentWillUpdate = function (p, s, c) {\n\t\t\t\tif (this._force) {\n\t\t\t\t\tlet tmp = prevScu;\n\t\t\t\t\t// Clear to avoid other sCU hooks from being called\n\t\t\t\t\tprevScu = undefined;\n\t\t\t\t\tupdateHookState(p, s, c);\n\t\t\t\t\tprevScu = tmp;\n\t\t\t\t}\n\n\t\t\t\tif (prevCWU) prevCWU.call(this, p, s, c);\n\t\t\t};\n\n\t\t\t// This SCU has the purpose of bailing out after repeated updates\n\t\t\t// to stateful hooks.\n\t\t\t// we store the next value in _nextValue[0] and keep doing that for all\n\t\t\t// state setters, if we have next states and\n\t\t\t// all next states within a component end up being equal to their original state\n\t\t\t// we are safe to bail out for this specific component.\n\t\t\t/**\n\t\t\t *\n\t\t\t * @type {import('./internal').Component[\"shouldComponentUpdate\"]}\n\t\t\t */\n\t\t\t// @ts-ignore - We don't use TS to downtranspile\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction updateHookState(p, s, c) {\n\t\t\t\tif (!hookState._component.__hooks) return true;\n\n\t\t\t\t// We check whether we have components with a nextValue set that\n\t\t\t\t// have values that aren't equal to one another this pushes\n\t\t\t\t// us to update further down the tree\n\t\t\t\tlet updatedHook = false;\n\t\t\t\tlet shouldUpdate = hookState._component.props !== p;\n\t\t\t\thookState._component.__hooks._list.some(hookItem => {\n\t\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\t\tupdatedHook = true;\n\t\t\t\t\t\tconst currentValue = hookItem._value[0];\n\t\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t\t\thookItem._nextValue = undefined;\n\t\t\t\t\t\tif (currentValue !== hookItem._value[0]) shouldUpdate = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (prevScu) {\n\t\t\t\t\tconst result = prevScu.call(this, p, s, c);\n\t\t\t\t\treturn updatedHook ? result || shouldUpdate : result;\n\t\t\t\t}\n\n\t\t\t\treturn !updatedHook || shouldUpdate;\n\t\t\t}\n\n\t\t\tcurrentComponent.shouldComponentUpdate = updateHookState;\n\t\t}\n\t}\n\n\treturn hookState._nextValue || hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\n/** @type {(initialValue: unknown) => unknown} */\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') {\n\t\t\t\tconst result = ref(createHandle());\n\t\t\t\treturn () => {\n\t\t\t\t\tref(null);\n\t\t\t\t\tif (result && typeof result == 'function') result();\n\t\t\t\t};\n\t\t\t} else if (ref) {\n\t\t\t\tref.current = createHandle();\n\t\t\t\treturn () => (ref.current = null);\n\t\t\t}\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @template {unknown} T\n * @param {() => T} factory\n * @param {unknown[]} args\n * @returns {T}\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState<T>} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {unknown[]} args\n * @returns {() => void}\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {<T>(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(\n\t\t\tformatter ? formatter(value) : /** @type {any}*/ (value)\n\t\t);\n\t}\n}\n\n/**\n * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb\n * @returns {[unknown, () => void]}\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = (err, errorInfo) => {\n\t\t\tif (state._value) state._value(err, errorInfo);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/** @type {() => string} */\nexport function useId() {\n\t/** @type {import('./internal').IdHookState} */\n\tconst state = getHookState(currentIndex++, 11);\n\tif (!state._value) {\n\t\t// Grab either the root node or the nearest async boundary node.\n\t\t/** @type {import('./internal').VNode} */\n\t\tlet root = currentComponent._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\tlet mask = root._mask || (root._mask = [0, 0]);\n\t\tstate._value = 'P' + mask[0] + '-' + mask[1]++;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tlet component;\n\twhile ((component = afterPaintEffects.shift())) {\n\t\tconst hooks = component.__hooks;\n\t\tif (!component._parentDom || !hooks) continue;\n\t\ttry {\n\t\t\thooks._pendingEffects.some(invokeCleanup);\n\t\t\thooks._pendingEffects.some(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t} catch (e) {\n\t\t\thooks._pendingEffects = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t}\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n * @returns {void}\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').HookState} hook\n * @returns {void}\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tlet cleanup = hook._cleanup;\n\tif (typeof cleanup == 'function') {\n\t\thook._cleanup = undefined;\n\t\tcleanup();\n\t}\n\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n * @returns {void}\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {unknown[]} oldArgs\n * @param {unknown[]} newArgs\n * @returns {boolean}\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\n/**\n * @template Arg\n * @param {Arg} arg\n * @param {(arg: Arg) => any} f\n * @returns {any}\n */\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n","/** \"1st\", \"2nd\", \"3rd\", \"11th\". */\nexport function ordinal(n: number): string {\n const v = n % 100;\n if (v >= 11 && v <= 13) return `${n}th`;\n switch (n % 10) {\n case 1:\n return `${n}st`;\n case 2:\n return `${n}nd`;\n case 3:\n return `${n}rd`;\n default:\n return `${n}th`;\n }\n}\n\n/** \"less than a minute\", \"about 1 min\", \"about 4 min\", \"about 1 hr\". */\nexport function eta(seconds: number | null): string {\n if (seconds == null) return '';\n if (seconds < 60) return 'less than a minute';\n const m = Math.round(seconds / 60);\n if (m < 60) return `about ${m} min`;\n return `about ${Math.round(m / 60)} hr`;\n}\n\n/** 0:07, 3:12, 1:02:03 */\nexport function clock(totalSeconds: number): string {\n const s = Math.max(0, Math.floor(totalSeconds));\n const h = Math.floor(s / 3600);\n const m = Math.floor((s % 3600) / 60);\n const ss = String(s % 60).padStart(2, '0');\n return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`;\n}\n\n/** What a visitor is told when a call could not happen or ended. */\nexport function endCopy(reason: string | null, name: string): { title: string; body: string } {\n switch (reason) {\n case 'hangup':\n return { title: 'Call ended', body: `Thanks for talking with ${name}.` };\n case 'left':\n return { title: 'You left the line', body: 'You can call again whenever you like.' };\n case 'missed':\n return { title: 'You missed your turn', body: `${name} was ready, but the call wasn't joined in time.` };\n case 'timeout':\n return { title: 'Still busy', body: `Sorry for the wait. ${name} is still on other calls. Chat is open meanwhile.` };\n case 'limit':\n return { title: 'Time is up', body: 'This call reached its time limit.' };\n case 'busy':\n return { title: 'All lines are busy', body: 'Try again in a few minutes, or keep chatting.' };\n case 'mic-denied':\n return { title: 'Microphone needed', body: 'Allow the microphone in your browser to talk, or keep chatting.' };\n case 'silence':\n return { title: 'Call ended', body: `The line was quiet for a minute, so ${name} hung up. Call again any time.` };\n case 'daily_limit':\n return { title: 'Calls are resting', body: 'Calls are done for today. Chat is open.' };\n case 'credits':\n case 'unavailable':\n return { title: 'Calls are unavailable', body: 'Calls are not available right now. Chat is open.' };\n default:\n return { title: 'The call dropped', body: 'Something interrupted the call. Try again.' };\n }\n}\n\n/**\n * Light markdown for replies: **bold**, *italic*, `code`, links, line breaks\n * and \"- \" lists. Returns tokens, never HTML, so nothing a model writes can\n * become markup.\n */\nexport type Inline = { t: 'text' | 'b' | 'i' | 'code'; v: string } | { t: 'link'; v: string; href: string };\nexport type Block = { t: 'p'; parts: Inline[] } | { t: 'ul'; items: Inline[][] };\n\nexport function inline(s: string): Inline[] {\n const out: Inline[] = [];\n const re = /(\\*\\*[^*]+\\*\\*|`[^`]+`|\\[[^\\]]+\\]\\((https?:\\/\\/[^)\\s]+)\\)|https?:\\/\\/[^\\s<>()]+[^\\s<>().,;:!?'\"]|\\*[^*\\s][^*]*\\*)/g;\n let last = 0;\n let m: RegExpExecArray | null;\n while ((m = re.exec(s))) {\n if (m.index > last) out.push({ t: 'text', v: s.slice(last, m.index) });\n const tok = m[0];\n if (tok.startsWith('**')) out.push({ t: 'b', v: tok.slice(2, -2) });\n else if (tok.startsWith('`')) out.push({ t: 'code', v: tok.slice(1, -1) });\n else if (tok.startsWith('[')) out.push({ t: 'link', v: tok.slice(1, tok.indexOf(']')), href: m[2]! });\n else if (tok.startsWith('http')) out.push({ t: 'link', v: tok, href: tok });\n else out.push({ t: 'i', v: tok.slice(1, -1) });\n last = m.index + tok.length;\n }\n if (last < s.length) out.push({ t: 'text', v: s.slice(last) });\n return out;\n}\n\nexport function blocks(text: string): Block[] {\n const out: Block[] = [];\n for (const para of text.split(/\\n{2,}/)) {\n const lines = para.split('\\n');\n if (lines.length && lines.every((l) => /^\\s*[-*•]\\s+/.test(l))) {\n out.push({ t: 'ul', items: lines.map((l) => inline(l.replace(/^\\s*[-*•]\\s+/, ''))) });\n } else {\n out.push({ t: 'p', parts: inline(para) });\n }\n }\n return out;\n}\n","import type { VideoCharacter } from '@characterxyz/web';\n\n/**\n * Where to put a full-body character so her face sits where a portrait wants\n * it. All in the media's own normalised coordinates (0..1), read from the\n * anchor still's eyes and chin.\n */\nexport interface Face {\n /** Centre of the face. */\n cx: number;\n cy: number;\n /** Eyes-to-chin, as a fraction of the media's height. */\n span: number;\n}\n\n/** Ananya-shaped default: a standing figure whose head is near the top. */\nconst FALLBACK: Face = { cx: 0.5, cy: 0.12, span: 0.06 };\n\nexport function faceOf(video: VideoCharacter | null, anchorW: number, anchorH: number): Face {\n const eyes = video?.face?.eyes;\n const chin = video?.face?.chin;\n if (!eyes || !chin || !anchorW || !anchorH) return FALLBACK;\n const ex = (eyes.left.x + eyes.right.x) / 2;\n const ey = (eyes.left.y + eyes.right.y) / 2;\n const span = (chin.y - ey) / anchorH;\n if (!(span > 0.005 && span < 0.5)) return FALLBACK;\n return { cx: ex / anchorW, cy: (ey + chin.y) / 2 / anchorH, span };\n}\n\nexport type Shot =\n | {\n /** Eyes-to-chin as a fraction of the box height. */\n faceFraction: number;\n /** Where the face centre lands in the box, 0..1. */\n at: { x: number; y: number };\n }\n /** The whole clip, its height filling the box, centred on her face — standing. */\n | { fit: 'height' };\n\n/** The corner portrait: a close-up. */\nexport const CLOSE_UP = { faceFraction: 0.26, at: { x: 0.5, y: 0.5 } } satisfies Shot;\n/** The call card: head and shoulders with room above. */\nexport const MEDIUM = { faceFraction: 0.14, at: { x: 0.5, y: 0.34 } } satisfies Shot;\n/** The launcher's half body: head to waist, her face high in the frame. */\nexport const HALF_BODY = { faceFraction: 0.16, at: { x: 0.5, y: 0.22 } } satisfies Shot;\n/** The launcher's full body: the whole figure, standing on the box's bottom edge. */\nexport const FULL_BODY = { fit: 'height' } satisfies Shot;\n\nexport interface Placement {\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\n/** Pixel placement of the media inside a `boxW`×`boxH` box. */\nexport function place(face: Face, mediaAspect: number, boxW: number, boxH: number, shot: Shot): Placement {\n if ('fit' in shot) {\n const width = boxH * mediaAspect;\n return { width, height: boxH, left: boxW / 2 - face.cx * width, top: 0 };\n }\n const height = (boxH * shot.faceFraction) / face.span;\n const width = height * mediaAspect;\n return {\n width,\n height,\n left: boxW * shot.at.x - face.cx * width,\n top: boxH * shot.at.y - face.cy * height,\n };\n}\n","const ENCODED_ENTITIES = /[\"&<]/;\n\n/** @param {string} str */\nexport function encodeEntities(str) {\n\t// Skip all work for strings with no entities needing encoding:\n\tif (str.length === 0 || ENCODED_ENTITIES.test(str) === false) return str;\n\n\tlet last = 0,\n\t\ti = 0,\n\t\tout = '',\n\t\tch = '';\n\n\t// Seek forward in str until the next entity char:\n\tfor (; i < str.length; i++) {\n\t\tswitch (str.charCodeAt(i)) {\n\t\t\tcase 34:\n\t\t\t\tch = '&quot;';\n\t\t\t\tbreak;\n\t\t\tcase 38:\n\t\t\t\tch = '&amp;';\n\t\t\t\tbreak;\n\t\t\tcase 60:\n\t\t\t\tch = '&lt;';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t}\n\t\t// Append skipped/buffered characters and the encoded entity:\n\t\tif (i !== last) out += str.slice(last, i);\n\t\tout += ch;\n\t\t// Start the next seek/buffer after the entity's offset:\n\t\tlast = i + 1;\n\t}\n\tif (i !== last) out += str.slice(last, i);\n\treturn out;\n}\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { options, Fragment } from 'preact';\nimport { encodeEntities } from './utils';\nimport { IS_NON_DIMENSIONAL } from '../../src/constants';\n\nlet vnodeId = 0;\n\nconst isArray = Array.isArray;\n\n/**\n * @fileoverview\n * This file exports various methods that implement Babel's \"automatic\" JSX runtime API:\n * - jsx(type, props, key)\n * - jsxs(type, props, key)\n * - jsxDEV(type, props, key, __source, __self)\n *\n * The implementation of createVNode here is optimized for performance.\n * Benchmarks: https://esbench.com/bench/5f6b54a0b4632100a7dcd2b3\n */\n\n/**\n * JSX.Element factory used by Babel's {runtime:\"automatic\"} JSX transform\n * @param {VNode['type']} type\n * @param {VNode['props']} props\n * @param {VNode['key']} [key]\n * @param {unknown} [isStaticChildren]\n * @param {unknown} [__source]\n * @param {unknown} [__self]\n */\nfunction createVNode(type, props, key, isStaticChildren, __source, __self) {\n\tif (!props) props = {};\n\t// We'll want to preserve `ref` in props to get rid of the need for\n\t// forwardRef components in the future, but that should happen via\n\t// a separate PR.\n\tlet normalizedProps = props,\n\t\tref,\n\t\ti;\n\n\tif ('ref' in normalizedProps) {\n\t\tnormalizedProps = {};\n\t\tfor (i in props) {\n\t\t\tif (i == 'ref') {\n\t\t\t\tref = props[i];\n\t\t\t} else {\n\t\t\t\tnormalizedProps[i] = props[i];\n\t\t\t}\n\t\t}\n\t}\n\n\t/** @type {VNode & { __source: any; __self: any }} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops: normalizedProps,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t_component: null,\n\t\tconstructor: undefined,\n\t\t_original: --vnodeId,\n\t\t_index: -1,\n\t\t_flags: 0,\n\t\t__source,\n\t\t__self\n\t};\n\n\t// If a Component VNode, check for and apply defaultProps.\n\t// Note: `type` is often a String, and can be `undefined` in development.\n\tif (typeof type === 'function' && (ref = type.defaultProps)) {\n\t\tfor (i in ref)\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = ref[i];\n\t\t\t}\n\t}\n\n\tif (options.vnode) options.vnode(vnode);\n\treturn vnode;\n}\n\n/**\n * Create a template vnode. This function is not expected to be\n * used directly, but rather through a precompile JSX transform\n * @param {string[]} templates\n * @param {Array<string | null | VNode>} exprs\n * @returns {VNode}\n */\nfunction jsxTemplate(templates, ...exprs) {\n\tconst vnode = createVNode(Fragment, { tpl: templates, exprs });\n\t// Bypass render to string top level Fragment optimization\n\tvnode.key = vnode._vnode;\n\treturn vnode;\n}\n\nconst JS_TO_CSS = {};\nconst CSS_REGEX = /[A-Z]/g;\n\n/**\n * Unwrap potential signals.\n * @param {*} value\n * @returns {*}\n */\nfunction normalizeAttrValue(value) {\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.valueOf === 'function'\n\t\t? value.valueOf()\n\t\t: value;\n}\n\n/**\n * Serialize an HTML attribute to a string. This function is not\n * expected to be used directly, but rather through a precompile\n * JSX transform\n * @param {string} name The attribute name\n * @param {*} value The attribute value\n * @returns {string}\n */\nfunction jsxAttr(name, value) {\n\tif (options.attr) {\n\t\tconst result = options.attr(name, value);\n\t\tif (typeof result === 'string') return result;\n\t}\n\n\tvalue = normalizeAttrValue(value);\n\n\tif (name === 'ref' || name === 'key') return '';\n\tif (name === 'style' && typeof value === 'object') {\n\t\tlet str = '';\n\t\tfor (let prop in value) {\n\t\t\tlet val = value[prop];\n\t\t\tif (val != null && val !== '') {\n\t\t\t\tconst name =\n\t\t\t\t\tprop[0] == '-'\n\t\t\t\t\t\t? prop\n\t\t\t\t\t\t: JS_TO_CSS[prop] ||\n\t\t\t\t\t\t\t(JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());\n\n\t\t\t\tlet suffix = ';';\n\t\t\t\tif (\n\t\t\t\t\ttypeof val === 'number' &&\n\t\t\t\t\t// Exclude custom-attributes\n\t\t\t\t\t!name.startsWith('--') &&\n\t\t\t\t\t!IS_NON_DIMENSIONAL.test(name)\n\t\t\t\t) {\n\t\t\t\t\tsuffix = 'px;';\n\t\t\t\t}\n\t\t\t\tstr = str + name + ':' + val + suffix;\n\t\t\t}\n\t\t}\n\t\treturn name + '=\"' + encodeEntities(str) + '\"';\n\t}\n\n\tif (\n\t\tvalue == null ||\n\t\tvalue === false ||\n\t\ttypeof value === 'function' ||\n\t\ttypeof value === 'object'\n\t) {\n\t\treturn '';\n\t} else if (value === true) return name;\n\n\treturn name + '=\"' + encodeEntities('' + value) + '\"';\n}\n\n/**\n * Escape a dynamic child passed to `jsxTemplate`. This function\n * is not expected to be used directly, but rather through a\n * precompile JSX transform\n * @param {*} value\n * @returns {string | null | VNode | Array<string | null | VNode>}\n */\nfunction jsxEscape(value) {\n\tif (\n\t\tvalue == null ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'function'\n\t) {\n\t\treturn null;\n\t}\n\n\tif (typeof value === 'object') {\n\t\t// Check for VNode\n\t\tif (value.constructor === undefined) return value;\n\n\t\tif (isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\tvalue[i] = jsxEscape(value[i]);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t}\n\n\treturn encodeEntities('' + value);\n}\n\nexport {\n\tcreateVNode as jsx,\n\tcreateVNode as jsxs,\n\tcreateVNode as jsxDEV,\n\tFragment,\n\t// precompiled JSX transform\n\tjsxTemplate,\n\tjsxAttr,\n\tjsxEscape\n};\n","/** Inline icons (24×24, stroke = currentColor), so the widget loads no assets. */\nimport type { ComponentChildren } from 'preact';\n\ntype P = { size?: number };\n\nconst svg = (size: number, children: ComponentChildren) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.9\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {children}\n </svg>\n);\n\nexport const ChatIcon = ({ size = 20 }: P) => svg(size, <path d=\"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6a.5.5 0 0 1-.8-.4V16h0A2.5 2.5 0 0 1 4 13.5z\" />);\nexport const PhoneIcon = ({ size = 20 }: P) =>\n svg(size, <path d=\"M5.2 3.5h3l1.6 4.2-2 1.4a12 12 0 0 0 7.1 7.1l1.4-2 4.2 1.6v3a1.7 1.7 0 0 1-1.8 1.7A16.6 16.6 0 0 1 3.5 5.3 1.7 1.7 0 0 1 5.2 3.5z\" />);\nexport const HangUpIcon = ({ size = 22 }: P) =>\n svg(size, <path d=\"M3 13.6c5-4.4 13-4.4 18 0l-1.7 2.6-3.6-1.3v-2.6a11 11 0 0 0-7.4 0v2.6l-3.6 1.3z\" />);\nexport const MicIcon = ({ size = 20 }: P) =>\n svg(\n size,\n <>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\" />\n </>,\n );\nexport const MicOffIcon = ({ size = 20 }: P) =>\n svg(\n size,\n <>\n <path d=\"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 10.6 5M18.4 12.5a6.5 6.5 0 0 0 .1-1.5M12 17.5V21M3 3l18 18\" />\n </>,\n );\nexport const CloseIcon = ({ size = 18 }: P) => svg(size, <path d=\"M6 6l12 12M18 6L6 18\" />);\nexport const SendIcon = ({ size = 18 }: P) => svg(size, <path d=\"M12 19V5M5.5 11.5L12 5l6.5 6.5\" />);\nexport const BackIcon = ({ size = 18 }: P) => svg(size, <path d=\"M15 5l-7 7 7 7\" />);\nexport const SparkIcon = ({ size = 14 }: P) => svg(size, <path d=\"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z\" />);\nexport const RetryIcon = ({ size = 14 }: P) => svg(size, <path d=\"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4\" />);\n","import type { Call, CallState, CharacterXYZ } from '@characterxyz/web';\nimport { useEffect, useRef, useState } from 'preact/hooks';\n\n/**\n * The agent's face, drawn by Character XYZ's own renderer in a frame\n * (`<faceUrl>` = the app's `/embed/face`), so the widget shows her exactly as\n * the app does — her clips, the Neural Lip Sync mouth, her own teeth and eyes —\n * without carrying the renderer itself (canon/docs/sdk-design.md, lip sync).\n *\n * The frame holds no session: this side fetches the face data with the\n * widget's session and posts it in, then forwards the call's streamed face and\n * the voice's audible clock. Until the frame says it is ready, the caller keeps\n * showing the portrait underneath.\n */\n\nexport type FaceStatus = 'loading' | 'ready' | 'unavailable';\n\n/** What the frame wants the face's mood to be (read when the call connects). */\nexport const faceEmotion = { current: null as string | null };\n\nfunction cameoState(s: CallState | null): string {\n if (!s) return 'idle';\n if (s.speaking) return 'speaking';\n if (s.agentState === 'thinking') return 'reasoning';\n if (s.agentState === 'listening' || s.phase === 'live') return 'listening';\n return 'idle';\n}\n\nexport function FaceFrame({\n client,\n call,\n state,\n src,\n onStatus,\n}: {\n client: CharacterXYZ;\n call: Call | null;\n state: CallState | null;\n src: string;\n onStatus: (s: FaceStatus) => void;\n}) {\n const frame = useRef<HTMLIFrameElement>(null);\n const [loaded, setLoaded] = useState(false);\n const loadedRef = useRef(false);\n const origin = (() => {\n try {\n return new URL(src).origin;\n } catch {\n return null;\n }\n })();\n\n const post = (msg: Record<string, unknown>, transfer?: Transferable[]) => {\n const w = frame.current?.contentWindow;\n if (w && origin) w.postMessage({ cx: 'face', ...msg }, origin, transfer ?? []);\n };\n\n // The frame's own messages: loaded → send the skin; ready / unavailable → report.\n useEffect(() => {\n if (!origin) {\n onStatus('unavailable');\n return;\n }\n let cancelled = false;\n const onMessage = (e: MessageEvent) => {\n if (e.source !== frame.current?.contentWindow || e.origin !== origin) return;\n const d = e.data as { cx?: string; type?: string; faceEmotion?: string | null };\n if (d?.cx !== 'face') return;\n if (d.type === 'loaded') {\n loadedRef.current = true;\n setLoaded(true);\n client\n .videoAvatar()\n .then((avatar) => {\n if (cancelled) return;\n if (!avatar) onStatus('unavailable');\n else post({ type: 'init', avatar });\n })\n .catch(() => !cancelled && onStatus('unavailable'));\n } else if (d.type === 'ready') {\n faceEmotion.current = typeof d.faceEmotion === 'string' ? d.faceEmotion : null;\n onStatus('ready');\n } else if (d.type === 'unavailable') {\n onStatus('unavailable');\n }\n };\n window.addEventListener('message', onMessage);\n // A frame that never answers (blocked, offline) leaves the portrait in place.\n const timeout = setTimeout(() => !cancelled && !loadedRef.current && onStatus('unavailable'), 15_000);\n return () => {\n cancelled = true;\n clearTimeout(timeout);\n window.removeEventListener('message', onMessage);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, origin]);\n\n // The agent's state, as the app's renderer names it.\n const cameo = cameoState(state);\n useEffect(() => {\n if (loaded) post({ type: 'state', state: cameo });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [cameo, loaded]);\n\n // The streamed face, the lines' starts and ends, and the voice's clock.\n useEffect(() => {\n if (!call || !loaded) return;\n const offs = [\n call.on('face', ({ corr, payload }) => post({ type: 'batch', corr, payload }, [payload.buffer as ArrayBuffer])),\n call.on('line', ({ corr, event }) => {\n if (event === 'audible') post({ type: 'audible', corr, ms: call.audible()?.ms ?? 0 });\n else post({ type: 'end', corr });\n }),\n ];\n let raf = 0;\n const tick = () => {\n const a = call.audible();\n if (a) post({ type: 'clock', corr: a.corr, ms: a.ms });\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => {\n offs.forEach((f) => f());\n cancelAnimationFrame(raf);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [call, loaded]);\n\n if (!origin) return null;\n return (\n <iframe\n ref={frame}\n class=\"face-frame\"\n src={src}\n title=\"\"\n aria-hidden=\"true\"\n tabIndex={-1}\n allow=\"autoplay\"\n sandbox=\"allow-scripts allow-same-origin\"\n referrerpolicy=\"strict-origin\"\n />\n );\n}\n","import type { AgentCard } from '@characterxyz/web';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\n\nimport { faceOf, place, type Shot } from './framing.js';\n\n/**\n * WebM with alpha plays in Chromium and Firefox. Safari ignores the alpha and\n * would draw the clip's green screen, so it gets the cut-out still instead.\n */\nfunction alphaVideoWorks(): boolean {\n if (typeof document === 'undefined') return false;\n const ua = navigator.userAgent;\n const safari = /Safari\\//.test(ua) && !/(Chrome|Chromium|Edg|OPR|Firefox)\\//.test(ua);\n if (safari) return false;\n const v = document.createElement('video');\n return v.canPlayType('video/webm; codecs=\"vp9\"') !== '';\n}\n\nconst reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nexport interface PortraitProps {\n agent: AgentCard;\n shot: Shot;\n /** Play the talking clip instead of idle. */\n talking?: boolean;\n /** Freeze on the still (closed launcher on a slow page, reduced motion). */\n still?: boolean;\n class?: string;\n}\n\n/**\n * The character, framed on her face. Two looping clips (idle, talking)\n * crossfade; the anchor still shows until the first frame and wherever clips\n * cannot play. A character without a video shows her initial.\n */\nexport function Portrait({ agent, shot, talking = false, still = false, class: cls }: PortraitProps) {\n const box = useRef<HTMLDivElement>(null);\n const [size, setSize] = useState({ w: 0, h: 0 });\n const [anchorDims, setAnchorDims] = useState<{ w: number; h: number } | null>(null);\n const [ready, setReady] = useState<Record<string, boolean>>({});\n const video = agent.video;\n const anchorUrl = video?.anchor?.alphaUrl ?? video?.anchor?.url ?? null;\n const canPlay = !still && !reducedMotion() && alphaVideoWorks();\n const idle = video?.clips.idle?.alphaUrl ?? null;\n const talk = video?.clips.talking?.alphaUrl ?? idle;\n\n useLayoutEffect(() => {\n const el = box.current;\n if (!el) return;\n const update = () => setSize({ w: el.clientWidth, h: el.clientHeight });\n update();\n if (typeof ResizeObserver === 'undefined') return;\n const ro = new ResizeObserver(update);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n if (!video || !anchorUrl) {\n return (\n <div ref={box} class={`portrait portrait--initial ${cls ?? ''}`} aria-hidden=\"true\">\n <span>{(agent.name || '?').slice(0, 1).toUpperCase()}</span>\n </div>\n );\n }\n\n const aspect = anchorDims ? anchorDims.w / anchorDims.h : 0.75;\n const face = faceOf(video, anchorDims?.w ?? 0, anchorDims?.h ?? 0);\n const p = size.w && size.h ? place(face, aspect, size.w, size.h, shot) : null;\n const style: Record<string, string | number> = p ? { width: `${p.width}px`, height: `${p.height}px`, left: `${p.left}px`, top: `${p.top}px` } : { opacity: 0 };\n const showIdle = canPlay && !!idle && !!ready.idle;\n const showTalk = canPlay && !!talk && talk !== idle && !!ready.talk && talking;\n\n return (\n <div ref={box} class={`portrait ${cls ?? ''}`} aria-hidden=\"true\">\n <img\n class=\"portrait__media\"\n src={anchorUrl}\n alt=\"\"\n draggable={false}\n style={{ ...style, opacity: p ? (showIdle ? 0 : 1) : 0 }}\n onLoad={(e) => {\n const img = e.currentTarget as HTMLImageElement;\n setAnchorDims({ w: img.naturalWidth, h: img.naturalHeight });\n }}\n />\n {canPlay && idle ? <Clip src={idle} style={style} visible={showIdle && !showTalk} onReady={() => setReady((r) => ({ ...r, idle: true }))} /> : null}\n {canPlay && talk && talk !== idle ? <Clip src={talk} style={style} visible={showTalk} onReady={() => setReady((r) => ({ ...r, talk: true }))} /> : null}\n </div>\n );\n}\n\nfunction Clip({ src, style, visible, onReady }: { src: string; style: Record<string, string | number>; visible: boolean; onReady: () => void }) {\n const ref = useRef<HTMLVideoElement>(null);\n useEffect(() => {\n const v = ref.current;\n if (!v) return;\n // Only the clip on screen plays; a hidden one costs nothing.\n if (visible) void v.play().catch(() => {});\n else v.pause();\n }, [visible]);\n return (\n <video\n ref={ref}\n class=\"portrait__media portrait__clip\"\n src={src}\n muted\n loop\n playsInline\n preload=\"auto\"\n style={{ ...style, opacity: visible ? 1 : 0 }}\n onLoadedData={onReady}\n />\n );\n}\n","import type { Call, CallState, Caption, CharacterXYZ, ChatMessage } from '@characterxyz/web';\nimport { Fragment } from 'preact';\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\n\nimport type { WidgetConfig } from './config.js';\nimport { blocks, clock, endCopy, eta, ordinal, type Inline } from './format.js';\nimport { CLOSE_UP, FULL_BODY, HALF_BODY, MEDIUM } from './framing.js';\nimport { BackIcon, ChatIcon, CloseIcon, HangUpIcon, MicIcon, MicOffIcon, PhoneIcon, RetryIcon, SendIcon, SparkIcon } from './icons.js';\nimport { faceEmotion, FaceFrame, type FaceStatus } from './face-frame.js';\nimport { Portrait } from './portrait.js';\n\nexport type View = 'closed' | 'chat' | 'call';\n\nexport interface AppApi {\n open(view?: Exclude<View, 'closed'>): void;\n close(): void;\n}\n\nexport interface AppProps {\n client: CharacterXYZ;\n config: WidgetConfig;\n /** Lets the element drive the app (`open()`, `close()`). */\n bind: (api: AppApi) => void;\n onView: (v: View) => void;\n}\n\nconst GREETED_KEY = 'cxyz:greeted';\n/** Set once the launcher has shown its words; after that it is icons only. */\nconst INTRODUCED_KEY = 'cxyz:introduced';\n\nfunction storage(key: string, value?: string): string | null {\n try {\n if (value !== undefined) localStorage.setItem(key, value);\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** A short two-note chime: \"your turn\". */\nfunction chime() {\n try {\n const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;\n const ctx = new Ctx();\n const now = ctx.currentTime;\n [660, 880].forEach((f, i) => {\n const o = ctx.createOscillator();\n const g = ctx.createGain();\n o.type = 'sine';\n o.frequency.value = f;\n g.gain.setValueAtTime(0, now + i * 0.16);\n g.gain.linearRampToValueAtTime(0.18, now + i * 0.16 + 0.02);\n g.gain.exponentialRampToValueAtTime(0.0001, now + i * 0.16 + 0.5);\n o.connect(g).connect(ctx.destination);\n o.start(now + i * 0.16);\n o.stop(now + i * 0.16 + 0.55);\n });\n setTimeout(() => void ctx.close(), 1200);\n } catch {\n // no audio: the banner still says it\n }\n}\n\nfunction useChat(client: CharacterXYZ) {\n const [messages, setMessages] = useState<readonly ChatMessage[]>(client.chat.messages);\n const [busy, setBusy] = useState(client.chat.isBusy);\n useEffect(() => {\n const a = client.chat.on('messages', setMessages);\n const b = client.chat.on('busy', setBusy);\n return () => {\n a();\n b();\n };\n }, [client]);\n return { messages, busy };\n}\n\nfunction useCall(client: CharacterXYZ) {\n const [call, setCall] = useState<Call | null>(client.call);\n const [state, setState] = useState<CallState | null>(client.call?.state ?? null);\n const [captions, setCaptions] = useState<Caption[]>([]);\n useEffect(() => client.on('call', (c) => c && setCall(c)), [client]);\n useEffect(() => {\n if (!call) return;\n setState(call.state);\n setCaptions([]);\n const offs = [\n call.on('state', setState),\n call.on('caption', (c) => setCaptions((prev) => [...prev.filter((x) => x.id !== c.id), c].slice(-4))),\n call.on('captionRemoved', (id) => setCaptions((prev) => prev.filter((x) => x.id !== id))),\n ];\n return () => offs.forEach((f) => f());\n }, [call]);\n return { call, state, captions, reset: () => setCall(null) };\n}\n\n/** Seconds since `startedAt`, ticking. */\nfunction useElapsed(startedAt: number | null, running: boolean) {\n const [now, setNow] = useState(Date.now());\n useEffect(() => {\n if (!running) return;\n const t = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(t);\n }, [running]);\n return startedAt ? Math.max(0, (now - startedAt) / 1000) : 0;\n}\n\n/** Feed `--cx-lvl` from the agent's voice on every frame, without re-rendering. */\nfunction useVoiceLevel(call: Call | null, el: { current: HTMLElement | null }, active: boolean) {\n useEffect(() => {\n if (!call || !active) return;\n let raf = 0;\n let smooth = 0;\n const tick = () => {\n const lvl = call.voiceLevel();\n smooth = smooth * 0.7 + lvl * 0.3;\n el.current?.style.setProperty('--cx-lvl', smooth.toFixed(3));\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(raf);\n }, [call, active, el]);\n}\n\nfunction Text({ parts }: { parts: Inline[] }) {\n return (\n <Fragment>\n {parts.map((p, i) =>\n p.t === 'b' ? (\n <strong key={i}>{p.v}</strong>\n ) : p.t === 'i' ? (\n <em key={i}>{p.v}</em>\n ) : p.t === 'code' ? (\n <code key={i}>{p.v}</code>\n ) : p.t === 'link' ? (\n <a key={i} href={p.href} target=\"_blank\" rel=\"noopener noreferrer nofollow\">\n {p.v}\n </a>\n ) : (\n p.v.split('\\n').map((line, j, arr) => (\n <Fragment key={`${i}.${j}`}>\n {line}\n {j < arr.length - 1 ? <br /> : null}\n </Fragment>\n ))\n ),\n )}\n </Fragment>\n );\n}\n\nfunction Rich({ text }: { text: string }) {\n return (\n <Fragment>\n {blocks(text).map((b, i) =>\n b.t === 'ul' ? (\n <ul key={i}>\n {b.items.map((it, j) => (\n <li key={j}>\n <Text parts={it} />\n </li>\n ))}\n </ul>\n ) : (\n <p key={i}>\n <Text parts={b.parts} />\n </p>\n ),\n )}\n </Fragment>\n );\n}\n\nexport function App({ client, config, bind, onView }: AppProps) {\n const agent = client.agent;\n const features = client.features;\n const canChat = config.showChat && features.chat;\n const canCall = config.showCall && features.call;\n const [view, setViewRaw] = useState<View>(config.open ? (canChat ? 'chat' : 'call') : 'closed');\n const [closing, setClosing] = useState(false);\n const [greeting, setGreeting] = useState(false);\n const { messages, busy } = useChat(client);\n const { call, state, captions, reset } = useCall(client);\n const [draft, setDraft] = useState('');\n const log = useRef<HTMLDivElement>(null);\n const input = useRef<HTMLTextAreaElement>(null);\n const stage = useRef<HTMLDivElement>(null);\n const subtitle = config.subtitle ?? agent.tagline;\n const name = agent.name || 'Assistant';\n\n const setView = useCallback(\n (v: View) => {\n setViewRaw(v);\n onView(v);\n },\n [onView],\n );\n\n const close = useCallback(() => {\n setClosing(true);\n setTimeout(() => {\n setClosing(false);\n setView('closed');\n }, 200);\n }, [setView]);\n\n const open = useCallback(\n (v: Exclude<View, 'closed'> = canChat ? 'chat' : 'call') => {\n setGreeting(false);\n storage(GREETED_KEY, '1');\n setView(v);\n if (v === 'chat') void client.chat.load().catch(() => {});\n },\n [canChat, client, setView],\n );\n\n useEffect(() => bind({ open, close }), [bind, open, close]);\n\n useEffect(() => {\n if (config.open && canChat) void client.chat.load().catch(() => {});\n }, [client, config.open, canChat]);\n\n // The greeting: once per visitor, after a beat, never over an open panel.\n useEffect(() => {\n if (!config.greeting || storage(GREETED_KEY)) return;\n const t = setTimeout(() => setGreeting(true), config.greetingDelay * 1000);\n return () => clearTimeout(t);\n }, [config.greeting, config.greetingDelay]);\n\n // The launcher's buttons say what they are once, on a visitor's first visit,\n // then fold to icons. Hover and keyboard focus unfold them again (CSS).\n const [labelled, setLabelled] = useState(() => !storage(INTRODUCED_KEY));\n useEffect(() => {\n if (!labelled) return;\n const t = setTimeout(() => {\n setLabelled(false);\n storage(INTRODUCED_KEY, '1');\n }, 5000);\n return () => clearTimeout(t);\n }, [labelled]);\n\n // Esc closes.\n useEffect(() => {\n if (view === 'closed') return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') close();\n };\n window.addEventListener('keydown', onKey);\n return () => window.removeEventListener('keydown', onKey);\n }, [view, close]);\n\n // Keep the newest message in view.\n useEffect(() => {\n const el = log.current;\n if (el) el.scrollTop = el.scrollHeight;\n }, [messages, view, state?.phase]);\n\n useEffect(() => {\n if (view === 'chat') setTimeout(() => input.current?.focus({ preventScroll: true }), 60);\n }, [view]);\n\n // The face frame (the app's own renderer) is wanted for a video character.\n const wantsFace = config.face && !!agent.video;\n const [faceStatus, setFaceStatus] = useState<FaceStatus>('loading');\n\n // Your turn: a chime, and the tab title if the visitor is elsewhere.\n const phase = state?.phase ?? 'idle';\n useEffect(() => {\n if (phase !== 'ready' || !call) return;\n chime();\n if (view === 'call') {\n // Join once the face frame has said who she is (her mood goes in the\n // call's opening message), or after 3 s whatever it says: the hold is 30.\n if (!wantsFace || faceStatus !== 'loading') {\n call.accept();\n return;\n }\n const t = setTimeout(() => call.accept(), 3000);\n return () => clearTimeout(t);\n }\n if (typeof document !== 'undefined' && document.hidden) {\n const title = document.title;\n document.title = `● ${name} is ready for you`;\n const restore = () => {\n document.title = title;\n document.removeEventListener('visibilitychange', restore);\n };\n document.addEventListener('visibilitychange', restore);\n }\n }, [phase, call, view, name, wantsFace, faceStatus]);\n\n const live = phase === 'live' || phase === 'connecting';\n useVoiceLevel(call, stage, live && view === 'call');\n const elapsed = useElapsed(state?.startedAt ?? null, phase === 'live');\n // Every hook above the early returns: Preact keys hooks by call order.\n const startPos = useMemoStart(call, state?.position ?? 1);\n\n const startCall = async () => {\n setView('call');\n try {\n await client.startCall({ autoAccept: false, ...(wantsFace ? { face: { emotion: () => faceEmotion.current } } : {}) });\n } catch {\n // the call's own state carries the reason\n }\n };\n\n const sendText = async (text: string) => {\n const t = text.trim();\n if (!t || busy) return;\n setDraft('');\n if (input.current) input.current.style.height = '';\n try {\n await client.chat.send(t);\n } catch {\n // the message shows as failed with a retry\n }\n };\n\n const lastAgentStreaming = messages.length > 0 && messages[messages.length - 1]!.role === 'agent' && messages[messages.length - 1]!.streaming;\n\n // ---------------------------------------------------------------- closed\n if (view === 'closed') {\n const inLine = phase === 'queued' || phase === 'ready' || phase === 'live' || phase === 'connecting';\n return (\n <div class={`dock dock--${config.display}`} part=\"launcher\">\n {greeting ? (\n <div class=\"greeting\" part=\"greeting\" role=\"status\" onClick={() => open()}>\n {config.greeting}\n <button\n class=\"greeting__close\"\n aria-label=\"Dismiss\"\n onClick={(e) => {\n e.stopPropagation();\n setGreeting(false);\n storage(GREETED_KEY, '1');\n }}\n >\n <CloseIcon size={14} />\n </button>\n </div>\n ) : null}\n <button\n class={`presence presence--${config.display} ${inLine ? 'presence--live' : ''}`}\n part=\"presence\"\n aria-label={\n inLine\n ? phase === 'queued'\n ? `You are ${ordinal(state?.position ?? 1)} in line to call ${name}. Open`\n : `Back to your call with ${name}`\n : canChat\n ? `Chat with ${name}`\n : `Call ${name}`\n }\n onClick={() => open(inLine || !canChat ? 'call' : 'chat')}\n >\n {config.display === 'bubble' ? <span class=\"presence__ring\" /> : null}\n <span class=\"presence__face\">\n <Portrait agent={agent} shot={config.display === 'full' ? FULL_BODY : config.display === 'half' ? HALF_BODY : CLOSE_UP} />\n </span>\n <span class=\"presence__dot\" />\n {client.mode === 'test' ? (\n <span class=\"testmode\" title=\"Test mode: this key only works on development sites\">\n TEST\n </span>\n ) : null}\n {phase === 'queued' ? (\n <span class=\"presence__badge\" aria-hidden=\"true\">\n {state?.position ?? 1}\n </span>\n ) : null}\n {config.launcher === 'bubble' && !greeting ? (\n <span class=\"presence__label\" aria-hidden=\"true\">\n {inLine ? (phase === 'queued' ? `${ordinal(state?.position ?? 1)} in line` : 'Back to your call') : canChat ? `Chat with ${name}` : `Call ${name}`}\n </span>\n ) : null}\n </button>\n {config.launcher === 'bubble' ? null : (\n <div class={`acts ${labelled ? 'acts--labelled' : ''}`} part=\"actions\">\n {canChat ? (\n <button class=\"act\" aria-label={`Chat with ${name}`} onClick={() => open('chat')}>\n <ChatIcon size={20} />\n <span class=\"act__label\" aria-hidden=\"true\">\n Chat\n </span>\n </button>\n ) : null}\n {canCall ? (\n <button\n class={`act act--call ${inLine ? 'act--live' : ''}`}\n aria-label={inLine ? (phase === 'queued' ? `You are ${ordinal(state?.position ?? 1)} in line. Open your call` : 'Back to your call') : `Call ${name}`}\n onClick={() => (inLine ? open('call') : void startCall())}\n >\n <PhoneIcon size={20} />\n <span class=\"act__label\" aria-hidden=\"true\">\n {inLine ? (phase === 'queued' ? `${ordinal(state?.position ?? 1)} in line` : 'On call') : 'Call'}\n </span>\n {phase === 'queued' ? (\n <span class=\"act__badge\" aria-hidden=\"true\">\n {state?.position ?? 1}\n </span>\n ) : null}\n </button>\n ) : null}\n </div>\n )}\n </div>\n );\n }\n\n // ---------------------------------------------------------------- chat\n const head = (\n <div class=\"head\" part=\"header\">\n <div class=\"head__face\">\n <Portrait agent={agent} shot={CLOSE_UP} talking={!!lastAgentStreaming} />\n </div>\n <div class=\"head__who\">\n <div class=\"head__name\">{name}</div>\n <div class=\"head__sub\">\n <i />\n {busy ? 'Typing…' : subtitle || 'Online'}\n </div>\n </div>\n {canCall && view === 'chat' ? (\n <button class=\"icon-btn icon-btn--accent\" aria-label={`Call ${name}`} title={`Call ${name}`} onClick={() => (call && phase !== 'ended' ? setView('call') : void startCall())}>\n <PhoneIcon size={18} />\n </button>\n ) : null}\n <button class=\"icon-btn\" aria-label=\"Close\" onClick={close}>\n <CloseIcon />\n </button>\n </div>\n );\n\n if (view === 'chat') {\n return (\n <div class={`panel ${closing ? 'is-closing' : ''}`} part=\"panel\" role=\"dialog\" aria-label={`Chat with ${name}`}>\n {head}\n {call && (phase === 'queued' || phase === 'ready') ? (\n <div class=\"banner\" part=\"banner\" role=\"status\">\n <div class=\"banner__text\">\n {phase === 'queued' ? (\n <Fragment>\n You're <b>{ordinal(state?.position ?? 1)}</b> in line for a call · {eta(state?.etaSeconds ?? null)}\n </Fragment>\n ) : (\n <Fragment>\n <b>{name} is ready for you</b> · {state?.holdSeconds ?? 30}s to join\n </Fragment>\n )}\n </div>\n {phase === 'ready' ? (\n <button\n class=\"btn btn--accent btn--glow\"\n onClick={() => {\n call.accept();\n setView('call');\n }}\n >\n Join\n </button>\n ) : (\n <button class=\"btn\" onClick={() => setView('call')}>\n View\n </button>\n )}\n </div>\n ) : null}\n <div class=\"log\" ref={log} role=\"log\" aria-live=\"polite\" aria-relevant=\"additions\">\n {messages.length === 0 ? (\n <div class=\"empty\">\n <div class=\"empty__face\">\n <Portrait agent={agent} shot={CLOSE_UP} />\n </div>\n <div class=\"empty__title\">Hi, I'm {name}</div>\n <div class=\"empty__body\">{subtitle ? `${subtitle}. ` : ''}Ask me anything{canCall ? ', or call me to talk' : ''}.</div>\n {canCall ? (\n <button class=\"btn btn--accent empty__call\" onClick={() => (call && phase !== 'ended' ? setView('call') : void startCall())}>\n <PhoneIcon size={17} /> Call {name}\n </button>\n ) : null}\n {config.suggestions.length ? (\n <div class=\"chips\">\n {config.suggestions.map((s) => (\n <button class=\"chip\" key={s} onClick={() => void sendText(s)}>\n <SparkIcon />\n {s}\n </button>\n ))}\n </div>\n ) : null}\n </div>\n ) : null}\n {messages.map((m) =>\n m.role === 'agent' && m.streaming && !m.text ? (\n <div class=\"msg msg--agent typing\" key={m.id} aria-label={`${name} is typing`}>\n <i />\n <i />\n <i />\n </div>\n ) : (\n <Fragment key={m.id}>\n <div class={`msg msg--${m.role} ${m.failed ? 'msg--failed' : ''} ${m.streaming ? 'caret' : ''}`} part={`message message-${m.role}`}>\n {m.role === 'agent' ? <Rich text={m.text} /> : m.text}\n </div>\n {m.failed && m.error ? (\n <div class=\"msg__why\" role=\"status\">\n {m.error}\n </div>\n ) : m.failed ? (\n <button class=\"msg__retry\" onClick={() => void client.chat.retry(m.id).catch(() => {})}>\n <RetryIcon /> Not sent · Retry\n </button>\n ) : null}\n </Fragment>\n ),\n )}\n </div>\n <form\n class=\"compose\"\n part=\"composer\"\n onSubmit={(e) => {\n e.preventDefault();\n void sendText(draft);\n }}\n >\n <div class=\"compose__box\">\n <textarea\n ref={input}\n rows={1}\n value={draft}\n maxLength={2000}\n placeholder={config.placeholder}\n aria-label=\"Message\"\n onInput={(e) => {\n const t = e.currentTarget;\n setDraft(t.value);\n t.style.height = 'auto';\n t.style.height = `${Math.min(120, t.scrollHeight)}px`;\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {\n e.preventDefault();\n void sendText(draft);\n }\n }}\n />\n <button class=\"send\" type=\"submit\" aria-label=\"Send\" disabled={!draft.trim() || busy}>\n <SendIcon />\n </button>\n </div>\n </form>\n {config.branding ? (\n <div class=\"foot\">\n Powered by{' '}\n <a href=\"https://character.xyz\" target=\"_blank\" rel=\"noopener noreferrer\">\n Character XYZ\n </a>\n </div>\n ) : null}\n </div>\n );\n }\n\n // ---------------------------------------------------------------- call\n const s = state;\n const position = s?.position ?? 1;\n const progress = startPos > 1 ? (startPos - position) / (startPos - 1) : 0;\n const R = 74;\n const C = 2 * Math.PI * R;\n const remaining = s?.maxSeconds ? s.maxSeconds - elapsed : null;\n const agentState = s?.agentState ?? 'idle';\n const status = s?.speaking ? 'Speaking' : agentState === 'thinking' ? 'Thinking…' : 'Listening';\n const ended = !s || phase === 'ended' || phase === 'idle';\n const copy = endCopy(s?.endReason ?? null, name);\n\n return (\n <div class={`panel ${closing ? 'is-closing' : ''}`} part=\"panel\" role=\"dialog\" aria-label={`Call with ${name}`}>\n <div class={`stage ${wantsFace && faceStatus === 'ready' ? 'stage--face' : ''}`} ref={stage}>\n <div class=\"stage__figure\" style={{ opacity: phase === 'queued' ? 0.35 : 1, transition: 'opacity .6s' }}>\n <Portrait agent={agent} shot={MEDIUM} talking={!!s?.speaking} />\n {wantsFace ? (\n <div class={`stage__face ${faceStatus === 'ready' ? 'is-ready' : ''}`}>\n <FaceFrame client={client} call={call} state={s} src={config.faceUrl} onStatus={setFaceStatus} />\n </div>\n ) : null}\n </div>\n {live ? <div class=\"voice\" /> : null}\n <div class=\"stage__veil\" />\n <div class=\"stage__top\">\n {phase === 'live' ? (\n <span class={`badge ${remaining != null && remaining <= 60 ? 'badge--warn' : ''}`} role=\"timer\" aria-label=\"Call time\">\n <i />\n {remaining != null && remaining <= 60 ? `${clock(remaining)} left` : clock(elapsed)}\n </span>\n ) : (\n <span />\n )}\n <div style={{ display: 'flex', gap: '6px' }}>\n {canChat ? (\n <button class=\"icon-btn\" aria-label=\"Chat\" title=\"Chat\" onClick={() => open('chat')}>\n <ChatIcon size={18} />\n </button>\n ) : null}\n <button class=\"icon-btn\" aria-label=\"Minimise\" onClick={close}>\n <CloseIcon />\n </button>\n </div>\n </div>\n\n <div class=\"stage__bottom\" aria-live=\"polite\">\n {phase === 'joining' || phase === 'connecting' ? (\n <Fragment>\n <div class=\"stage__name\">{name}</div>\n <div class=\"stage__status\">\n <span class=\"spinner\" /> {phase === 'joining' ? 'Connecting…' : 'Joining…'}\n </div>\n </Fragment>\n ) : null}\n\n {phase === 'queued' ? (\n <Fragment>\n <div class=\"line\" role=\"status\" aria-label={`You are ${ordinal(position)} in line, ${eta(s?.etaSeconds ?? null)}`}>\n <svg width=\"168\" height=\"168\" viewBox=\"0 0 168 168\">\n <circle class=\"line__track\" cx=\"84\" cy=\"84\" r={R} fill=\"none\" stroke-width=\"7\" />\n <circle class=\"line__fill\" cx=\"84\" cy=\"84\" r={R} fill=\"none\" stroke-width=\"7\" stroke-linecap=\"round\" stroke-dasharray={C} stroke-dashoffset={C * (1 - Math.max(0.06, progress))} />\n </svg>\n <div>\n <div class=\"line__num\">{ordinal(position)}</div>\n <div class=\"line__lbl\">in line</div>\n </div>\n </div>\n <div class=\"title\">{name} is on other calls</div>\n <div class=\"note\">\n Your turn in {eta(s?.etaSeconds ?? null)}. We'll chime when it's time{canChat ? ', so feel free to keep chatting.' : '.'}\n </div>\n <div class=\"btn-row\">\n {canChat ? (\n <button class=\"btn btn--accent\" onClick={() => open('chat')}>\n <ChatIcon size={18} /> Keep chatting\n </button>\n ) : null}\n <button\n class=\"btn\"\n onClick={() => {\n void call?.hangUp();\n }}\n >\n Leave line\n </button>\n </div>\n </Fragment>\n ) : null}\n\n {phase === 'ready' ? (\n <Fragment>\n <div class=\"title\">{name} is ready for you</div>\n <div class=\"note\">Join within {s?.holdSeconds ?? 30} seconds.</div>\n <button class=\"btn btn--accent btn--glow\" onClick={() => call?.accept()}>\n <PhoneIcon size={18} /> Join call\n </button>\n </Fragment>\n ) : null}\n\n {phase === 'live' ? (\n <Fragment>\n <div class=\"stage__name\">{name}</div>\n <div class=\"stage__status\">\n {s?.speaking ? (\n <span class=\"wave\" aria-hidden=\"true\">\n {[0.6, 1, 0.75, 1, 0.55].map((k, i) => (\n <i key={i} style={{ '--k': k } as Record<string, number>} />\n ))}\n </span>\n ) : null}\n {s?.muted ? 'You are muted' : status}\n </div>\n <div class=\"captions\">\n {captions.slice(-2).map((c, i, arr) => (\n <div key={c.id} class={`captions__line ${i === arr.length - 1 ? 'captions__line--now' : ''}`}>\n {c.role === 'visitor' ? `You: ${c.text}` : c.text}\n </div>\n ))}\n </div>\n <div class=\"controls\">\n <div class=\"ctl\">\n <button class={`round ${s?.muted ? 'round--on' : ''}`} aria-pressed={s?.muted} aria-label={s?.muted ? 'Unmute' : 'Mute'} onClick={() => call?.setMuted(!s?.muted)}>\n {s?.muted ? <MicOffIcon size={22} /> : <MicIcon size={22} />}\n </button>\n <span class=\"round__label\">{s?.muted ? 'Unmute' : 'Mute'}</span>\n </div>\n <div class=\"ctl\">\n <button class=\"round round--end\" aria-label=\"End call\" onClick={() => void call?.hangUp()}>\n <HangUpIcon size={26} />\n </button>\n <span class=\"round__label\">End</span>\n </div>\n {s?.speaking ? (\n <div class=\"ctl\">\n <button class=\"round\" aria-label={`Interrupt ${name}`} onClick={() => call?.interrupt()}>\n <BackIcon size={22} />\n </button>\n <span class=\"round__label\">Interrupt</span>\n </div>\n ) : null}\n </div>\n </Fragment>\n ) : null}\n\n {ended ? (\n <Fragment>\n <div class=\"title\">{s ? copy.title : `Call ${name}`}</div>\n <div class=\"note\">{s ? (s.endReason === 'hangup' && elapsed ? `${clock(elapsed)} · ${copy.body}` : s.error ?? copy.body) : `Talk with ${name} in real time.`}</div>\n <div class=\"btn-row\">\n {canCall && s?.endReason !== 'credits' && s?.endReason !== 'unavailable' && s?.endReason !== 'daily_limit' ? (\n <button\n class=\"btn btn--accent\"\n onClick={() => {\n reset();\n void startCall();\n }}\n >\n <PhoneIcon size={18} /> {s ? 'Call again' : 'Start call'}\n </button>\n ) : null}\n {canChat ? (\n <button class=\"btn\" onClick={() => open('chat')}>\n <ChatIcon size={18} /> Chat\n </button>\n ) : null}\n </div>\n </Fragment>\n ) : null}\n </div>\n </div>\n </div>\n );\n}\n\n/** The place a visitor joined the line at, for the ring's progress. */\nfunction useMemoStart(call: Call | null, position: number): number {\n const ref = useRef<{ call: Call | null; start: number }>({ call: null, start: position });\n if (ref.current.call !== call) ref.current = { call, start: position };\n if (position > ref.current.start) ref.current.start = position;\n return ref.current.start;\n}\n\n","/**\n * The widget's whole stylesheet. It lives in the Shadow DOM: nothing here\n * reaches the brand's page and nothing of theirs reaches in, except the\n * `::part()` names documented in the README.\n *\n * Tokens are custom properties on :host, set from the config at mount\n * (`--cx-accent`, `--cx-radius`, `--cx-font`) — a brand overrides any of\n * them from outside with `character-xyz { --cx-accent: … }`.\n */\nexport const CSS = /* css */ `\n:host {\n --cx-accent: #7c5cff;\n --cx-accent-ink: #fff;\n --cx-radius: 24px;\n --cx-font: ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n --cx-bg: rgba(255, 255, 255, 0.82);\n --cx-solid: #ffffff;\n --cx-ink: #14121a;\n --cx-ink-2: #5b5866;\n --cx-ink-3: #8d8a98;\n --cx-line: rgba(20, 18, 26, 0.08);\n --cx-bubble: rgba(20, 18, 26, 0.05);\n --cx-shadow: 0 24px 64px -12px rgba(23, 16, 52, 0.28), 0 4px 16px -4px rgba(23, 16, 52, 0.12);\n --cx-danger: #ef4444;\n --cx-ok: #22c55e;\n --cx-ease: cubic-bezier(0.22, 1, 0.36, 1);\n --cx-spring: cubic-bezier(0.34, 1.4, 0.64, 1);\n all: initial;\n position: fixed;\n z-index: var(--cx-z, 2147483000);\n bottom: var(--cx-oy, 20px);\n font-family: var(--cx-font);\n color: var(--cx-ink);\n -webkit-font-smoothing: antialiased;\n line-height: 1.45;\n}\n:host([data-side=\"right\"]) { right: var(--cx-ox, 20px); }\n:host([data-side=\"left\"]) { left: var(--cx-ox, 20px); }\n:host([data-theme=\"dark\"]) {\n --cx-bg: rgba(22, 20, 30, 0.78);\n --cx-solid: #16141e;\n --cx-ink: #f4f2fa;\n --cx-ink-2: #b7b3c6;\n --cx-ink-3: #85819a;\n --cx-line: rgba(255, 255, 255, 0.09);\n --cx-bubble: rgba(255, 255, 255, 0.07);\n --cx-shadow: 0 24px 64px -12px rgba(0, 0, 0, 0.6), 0 4px 16px -4px rgba(0, 0, 0, 0.4);\n}\n*, *::before, *::after { box-sizing: border-box; }\nbutton { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }\nbutton:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px solid var(--cx-accent); outline-offset: 2px; }\n.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n\n/* ------------------------------------------------------------ launcher */\n.dock { display: flex; align-items: flex-end; gap: 10px; }\n/* She sits in the corner and never moves; the buttons grow away from her. */\n:host([data-side=\"right\"]) .dock { flex-direction: row-reverse; }\n.presence {\n position: relative; width: 60px; height: 60px; border-radius: 50%; flex: none;\n transition: transform .5s var(--cx-spring);\n}\n.presence:hover { transform: translateY(-2px) scale(1.05); }\n/* ---- display: half body — her cut-out from the waist up, no frame, fading out at the waist */\n.presence--half { width: 128px; height: 170px; border-radius: 0; filter: drop-shadow(0 10px 18px rgba(15, 10, 30, 0.28)); }\n.presence--half .presence__face { border-radius: 0; background: none; box-shadow: none;\n -webkit-mask-image: linear-gradient(to bottom, #000 70%, transparent 98%); mask-image: linear-gradient(to bottom, #000 70%, transparent 98%); }\n/* ---- display: full body — she stands in the corner, feet on the edge, a soft shadow under her */\n.presence--full { width: 132px; height: 300px; border-radius: 0; filter: drop-shadow(0 6px 14px rgba(15, 10, 30, 0.22)); }\n.presence--full .presence__face { border-radius: 0; background: none; box-shadow: none; }\n.presence--full::before { content: \"\"; position: absolute; left: 22%; right: 22%; bottom: -4px; height: 10px; border-radius: 50%;\n background: radial-gradient(closest-side, rgba(15, 10, 30, 0.35), transparent); }\n.presence--half:hover, .presence--full:hover { transform: translateY(-3px); }\n.presence--half .presence__dot { top: 10px; bottom: auto; right: 26px; }\n.presence--full .presence__dot { top: 6px; bottom: auto; right: 34px; }\n.presence--half .testmode, .presence--full .testmode { top: -6px; bottom: auto; }\n.presence--full .presence__label { top: 22%; }\n.presence--half .presence__badge, .presence--full .presence__badge { top: 0; right: 4px; }\n.presence--half.presence--live::after, .presence--full.presence--live::after { display: none; }\n.presence--half.presence--live, .presence--full.presence--live { animation: cx-figure-glow 1.8s ease-in-out infinite; }\n.dock--half .greeting { bottom: 186px; }\n.dock--full .greeting { bottom: 316px; }\n\n/* What a tap does, on hover and keyboard focus. */\n.presence__label {\n position: absolute; top: 50%; transform: translate(6px, -50%); opacity: 0; pointer-events: none; white-space: nowrap;\n padding: 7px 12px; border-radius: 999px; font-size: 13px; font-weight: 600; letter-spacing: -0.005em;\n color: var(--cx-ink); background: var(--cx-solid); border: 1px solid var(--cx-line); box-shadow: var(--cx-shadow);\n transition: opacity .2s, transform .3s var(--cx-ease);\n}\n:host([data-side=\"right\"]) .presence__label { right: calc(100% + 10px); }\n:host([data-side=\"left\"]) .presence__label { left: calc(100% + 10px); transform: translate(-6px, -50%); }\n.presence:hover .presence__label, .presence:focus-visible .presence__label { opacity: 1; transform: translate(0, -50%); }\n/* Waiting in line: the place, on her. */\n.presence__badge {\n position: absolute; top: -4px; right: -4px; min-width: 22px; height: 22px; padding: 0 6px; border-radius: 11px;\n display: grid; place-items: center; font-size: 12px; font-weight: 800; font-variant-numeric: tabular-nums;\n background: var(--cx-accent); color: var(--cx-accent-ink); box-shadow: 0 0 0 2px var(--cx-solid);\n}\n/* A call is open (or waiting): she breathes, so the way back is obvious. */\n.presence--live::after { content: \"\"; position: absolute; inset: -5px; border-radius: 50%; border: 2px solid var(--cx-accent); animation: cx-glow-ring 1.8s ease-out infinite; }\n.empty__call { margin-top: 4px; height: 40px; }\n.presence__ring {\n position: absolute; inset: -3px; border-radius: 50%;\n background: conic-gradient(from var(--cx-angle, 0deg), var(--cx-accent), color-mix(in oklab, var(--cx-accent) 30%, #fff), var(--cx-accent));\n animation: cx-spin 6s linear infinite;\n}\n.presence__face {\n position: absolute; inset: 0; border-radius: 50%; overflow: hidden;\n background: radial-gradient(120% 90% at 50% 10%, color-mix(in oklab, var(--cx-accent) 22%, var(--cx-solid)), var(--cx-solid));\n box-shadow: inset 0 0 0 3px var(--cx-solid);\n}\n.presence__dot {\n position: absolute; right: 3px; bottom: 3px; width: 14px; height: 14px; border-radius: 50%;\n background: var(--cx-ok); box-shadow: 0 0 0 3px var(--cx-solid);\n}\n.acts { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }\n/* Call, the primary action, sits next to her on either side. */\n:host([data-side=\"left\"]) .acts { flex-direction: row-reverse; }\n.act {\n position: relative; display: inline-flex; align-items: center; justify-content: center;\n height: 44px; min-width: 44px; padding: 0 12px; border-radius: 999px;\n color: var(--cx-ink); background: var(--cx-bg);\n backdrop-filter: blur(18px) saturate(1.6); -webkit-backdrop-filter: blur(18px) saturate(1.6);\n border: 1px solid var(--cx-line); box-shadow: var(--cx-shadow);\n animation: cx-rise .6s var(--cx-ease) both;\n transition: transform .35s var(--cx-spring), background .2s, box-shadow .2s;\n}\n.act + .act { animation-delay: .06s; }\n.act:hover { transform: translateY(-2px); }\n.act:active { transform: scale(.94); }\n.act--call { background: var(--cx-accent); color: var(--cx-accent-ink); border-color: transparent; }\n.act--call:hover { background: color-mix(in oklab, var(--cx-accent) 88%, #000); }\n/* The word folds away to an icon; hover, keyboard focus and a first visit unfold it. */\n.act__label {\n max-width: 0; opacity: 0; overflow: hidden; white-space: nowrap;\n font-size: 14px; font-weight: 600; letter-spacing: -0.005em;\n transition: max-width .35s var(--cx-ease), opacity .2s, margin .35s var(--cx-ease);\n}\n.act:hover .act__label, .act:focus-visible .act__label, .acts--labelled .act__label { max-width: 120px; opacity: 1; margin-left: 7px; }\n/* Waiting in line: the place, on the button. */\n.act__badge {\n position: absolute; top: -5px; right: -5px; min-width: 20px; height: 20px; padding: 0 5px; border-radius: 10px;\n display: grid; place-items: center; font-size: 11px; font-weight: 800; font-variant-numeric: tabular-nums;\n background: var(--cx-solid); color: var(--cx-ink); box-shadow: 0 0 0 2px var(--cx-accent);\n}\n/* On a call (or ready): the button breathes so the way back is obvious. */\n.act--live::after { content: \"\"; position: absolute; inset: -4px; border-radius: inherit; border: 2px solid var(--cx-accent); opacity: .5; animation: cx-glow-ring 1.8s ease-out infinite; }\n.greeting {\n position: absolute; bottom: 76px; max-width: 260px; padding: 12px 34px 12px 14px; border-radius: 18px;\n background: var(--cx-solid); box-shadow: var(--cx-shadow); border: 1px solid var(--cx-line);\n font-size: 14px; color: var(--cx-ink); animation: cx-pop .55s var(--cx-spring) both; cursor: pointer;\n}\n:host([data-side=\"right\"]) .greeting { right: 0; border-bottom-right-radius: 6px; }\n:host([data-side=\"left\"]) .greeting { left: 0; border-bottom-left-radius: 6px; }\n.greeting__close { position: absolute; top: 6px; right: 6px; width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; color: var(--cx-ink-3); }\n.greeting__close:hover { background: var(--cx-bubble); color: var(--cx-ink); }\n\n/* ------------------------------------------------------------ panel */\n.panel {\n position: absolute; bottom: 0; width: 392px; height: min(640px, calc(100vh - 40px));\n display: flex; flex-direction: column; overflow: hidden;\n border-radius: var(--cx-radius); background: var(--cx-bg); border: 1px solid var(--cx-line);\n backdrop-filter: blur(24px) saturate(1.7); -webkit-backdrop-filter: blur(24px) saturate(1.7);\n box-shadow: var(--cx-shadow);\n transform-origin: bottom right;\n animation: cx-open .5s var(--cx-ease) both;\n}\n:host([data-side=\"right\"]) .panel { right: 0; }\n:host([data-side=\"left\"]) .panel { left: 0; transform-origin: bottom left; }\n.panel.is-closing { animation: cx-close .22s ease-in both; }\n\n.head { display: flex; align-items: center; gap: 12px; padding: 14px 14px 12px 16px; border-bottom: 1px solid var(--cx-line); }\n.head__face { position: relative; width: 42px; height: 42px; border-radius: 50%; overflow: hidden; flex: none;\n background: radial-gradient(120% 90% at 50% 10%, color-mix(in oklab, var(--cx-accent) 22%, var(--cx-solid)), var(--cx-solid)); }\n.head__who { flex: 1; min-width: 0; }\n.head__name { font-size: 15px; font-weight: 650; letter-spacing: -0.01em; }\n.head__sub { font-size: 12.5px; color: var(--cx-ink-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; gap: 6px; }\n.head__sub i { width: 7px; height: 7px; border-radius: 50%; background: var(--cx-ok); flex: none; }\n.icon-btn { width: 38px; height: 38px; border-radius: 12px; display: grid; place-items: center; color: var(--cx-ink-2); transition: background .2s, color .2s; }\n.icon-btn:hover { background: var(--cx-bubble); color: var(--cx-ink); }\n.icon-btn--accent { background: var(--cx-accent); color: var(--cx-accent-ink); }\n.icon-btn--accent:hover { background: color-mix(in oklab, var(--cx-accent) 88%, #000); color: var(--cx-accent-ink); }\n\n/* ------------------------------------------------------------ chat */\n.log { flex: 1; overflow-y: auto; padding: 18px 16px 8px; display: flex; flex-direction: column; gap: 6px; scroll-behavior: smooth; overscroll-behavior: contain; }\n.log::-webkit-scrollbar { width: 8px; } .log::-webkit-scrollbar-thumb { background: var(--cx-line); border-radius: 8px; }\n.msg { max-width: 84%; padding: 9px 13px; border-radius: 18px; font-size: 14.5px; word-wrap: break-word; animation: cx-msg .35s var(--cx-ease) both; }\n.msg p { margin: 0; } .msg p + p, .msg p + ul, .msg ul + p { margin-top: 8px; }\n.msg ul { margin: 0; padding-left: 18px; }\n.msg code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .9em; padding: 1px 5px; border-radius: 6px; background: var(--cx-bubble); }\n.msg a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }\n.msg--agent { align-self: flex-start; background: var(--cx-bubble); border-bottom-left-radius: 6px; }\n.msg--visitor { align-self: flex-end; background: var(--cx-accent); color: var(--cx-accent-ink); border-bottom-right-radius: 6px; }\n.msg--visitor + .msg--visitor, .msg--agent + .msg--agent { margin-top: -2px; }\n.msg--failed { opacity: .65; }\n.msg__retry { display: inline-flex; align-items: center; gap: 4px; margin-top: 4px; font-size: 12px; color: var(--cx-danger); align-self: flex-end; }\n.msg__why { margin-top: 4px; font-size: 12px; color: var(--cx-ink-2); align-self: flex-end; text-align: right; max-width: 85%; }\n.caret::after { content: \"\"; display: inline-block; width: 7px; height: 1.05em; margin-left: 2px; vertical-align: -2px; border-radius: 2px; background: currentColor; opacity: .55; animation: cx-blink 1s steps(2) infinite; }\n.typing { display: inline-flex; gap: 4px; padding: 13px 14px; }\n.typing i { width: 7px; height: 7px; border-radius: 50%; background: var(--cx-ink-3); animation: cx-bounce 1.2s var(--cx-ease) infinite; }\n.typing i:nth-child(2) { animation-delay: .15s; } .typing i:nth-child(3) { animation-delay: .3s; }\n.empty { margin: auto 0 8px; display: flex; flex-direction: column; align-items: center; text-align: center; gap: 10px; padding: 10px 8px 4px; }\n.empty__face { width: 96px; height: 96px; border-radius: 50%; overflow: hidden; position: relative; box-shadow: 0 0 0 4px var(--cx-solid), 0 0 0 6px color-mix(in oklab, var(--cx-accent) 45%, transparent);\n background: radial-gradient(120% 90% at 50% 10%, color-mix(in oklab, var(--cx-accent) 22%, var(--cx-solid)), var(--cx-solid)); }\n.empty__title { font-size: 17px; font-weight: 650; letter-spacing: -0.015em; }\n.empty__body { font-size: 13.5px; color: var(--cx-ink-2); max-width: 280px; }\n.chips { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-top: 4px; }\n.chip { display: inline-flex; align-items: center; gap: 6px; padding: 7px 12px; border-radius: 999px; font-size: 13px; border: 1px solid var(--cx-line); background: var(--cx-solid); transition: border-color .2s, transform .3s var(--cx-spring); }\n.chip:hover { border-color: color-mix(in oklab, var(--cx-accent) 55%, transparent); transform: translateY(-1px); }\n.chip svg { color: var(--cx-accent); }\n\n.compose { padding: 10px 12px 12px; }\n.compose__box { display: flex; align-items: flex-end; gap: 8px; padding: 6px 6px 6px 14px; border-radius: 20px; background: var(--cx-solid); border: 1px solid var(--cx-line); transition: border-color .2s, box-shadow .2s; }\n.compose__box:focus-within { border-color: color-mix(in oklab, var(--cx-accent) 60%, transparent); box-shadow: 0 0 0 4px color-mix(in oklab, var(--cx-accent) 14%, transparent); }\n.compose textarea { flex: 1; resize: none; border: 0; outline: 0; background: transparent; font: inherit; font-size: 14.5px; color: var(--cx-ink); max-height: 120px; padding: 7px 0; line-height: 1.4; }\n.compose textarea::placeholder { color: var(--cx-ink-3); }\n.send { width: 34px; height: 34px; border-radius: 50%; display: grid; place-items: center; background: var(--cx-accent); color: var(--cx-accent-ink); flex: none; transition: transform .3s var(--cx-spring), opacity .2s; }\n.send:disabled { opacity: .35; cursor: default; }\n.send:not(:disabled):active { transform: scale(.9); }\n.foot { text-align: center; font-size: 11px; color: var(--cx-ink-3); padding: 0 0 10px; }\n.foot a { color: inherit; text-decoration: none; font-weight: 600; }\n\n/* ------------------------------------------------------------ banners (queue / ready while chatting) */\n.banner { margin: 10px 12px 0; padding: 10px 10px 10px 14px; border-radius: 16px; display: flex; align-items: center; gap: 10px; font-size: 13px;\n background: color-mix(in oklab, var(--cx-accent) 12%, var(--cx-solid)); border: 1px solid color-mix(in oklab, var(--cx-accent) 25%, transparent); animation: cx-rise .4s var(--cx-ease) both; }\n.banner__text { flex: 1; min-width: 0; } .banner__text b { font-weight: 650; }\n.banner .btn { height: 32px; padding: 0 12px; font-size: 13px; }\n\n/* ------------------------------------------------------------ call */\n.stage { flex: 1; position: relative; display: flex; flex-direction: column; overflow: hidden;\n background: radial-gradient(120% 70% at 50% 18%, color-mix(in oklab, var(--cx-accent) 26%, var(--cx-solid)) 0%, var(--cx-solid) 70%); }\n.stage__figure { position: absolute; inset: 0; }\n.stage__figure .portrait { position: absolute; inset: 0; }\n/* The app's own face renderer, faded in over the portrait once it is drawing. */\n.stage__face { position: absolute; inset: 0; opacity: 0; transition: opacity .5s ease; pointer-events: none; }\n.stage__face.is-ready { opacity: 1; }\n/* Over the skin's own (usually dark) backdrop the top controls go light. */\n.stage--face .stage__top .icon-btn { color: rgba(255, 255, 255, 0.85); }\n.stage--face .stage__top .icon-btn:hover { color: #fff; background: rgba(255, 255, 255, 0.14); }\n.stage--face .badge { background: rgba(10, 8, 16, 0.45); color: #fff; border-color: rgba(255, 255, 255, 0.12); }\n.face-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: transparent; color-scheme: normal; }\n.stage__veil { position: absolute; left: 0; right: 0; bottom: 0; height: 58%; background: linear-gradient(to top, var(--cx-solid) 18%, color-mix(in oklab, var(--cx-solid) 0%, transparent)); pointer-events: none; }\n.stage__top { position: relative; display: flex; justify-content: space-between; align-items: center; padding: 14px 14px 0 16px; }\n.badge { display: inline-flex; align-items: center; gap: 7px; height: 28px; padding: 0 11px; border-radius: 999px; font-size: 12.5px; font-weight: 600; background: var(--cx-bg); backdrop-filter: blur(12px); border: 1px solid var(--cx-line); font-variant-numeric: tabular-nums; }\n.badge i { width: 7px; height: 7px; border-radius: 50%; background: var(--cx-danger); animation: cx-pulse 1.6s ease-in-out infinite; }\n.badge--warn { color: var(--cx-danger); }\n.stage__bottom { position: relative; margin-top: auto; padding: 0 18px 18px; display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center; }\n.stage__name { font-size: 21px; font-weight: 700; letter-spacing: -0.02em; }\n.stage__status { font-size: 13.5px; color: var(--cx-ink-2); min-height: 20px; display: inline-flex; align-items: center; gap: 8px; }\n.wave { display: inline-flex; align-items: center; gap: 3px; height: 16px; }\n.wave i { width: 3px; border-radius: 3px; background: var(--cx-accent); height: calc(4px + var(--cx-lvl, 0) * 12px * var(--k, 1)); transition: height .08s linear; }\n.captions { width: 100%; min-height: 44px; font-size: 14.5px; color: var(--cx-ink); display: flex; flex-direction: column; gap: 2px; }\n.captions__line { opacity: .55; font-size: 13px; } .captions__line--now { opacity: 1; font-size: 15px; font-weight: 500; }\n.controls { display: flex; gap: 14px; align-items: center; justify-content: center; margin-top: 4px; }\n.round { width: 56px; height: 56px; border-radius: 50%; display: grid; place-items: center; background: var(--cx-bg); border: 1px solid var(--cx-line); backdrop-filter: blur(12px); transition: transform .3s var(--cx-spring), background .2s; }\n.round:hover { transform: translateY(-2px); }\n.round:active { transform: scale(.94); }\n.round--on { background: var(--cx-ink); color: var(--cx-solid); }\n.round--end { background: var(--cx-danger); color: #fff; border-color: transparent; width: 64px; height: 64px; }\n.round__label { font-size: 11.5px; color: var(--cx-ink-2); margin-top: 6px; }\n.ctl { display: flex; flex-direction: column; align-items: center; }\n\n.voice { position: absolute; left: 50%; top: 34%; width: 240px; height: 240px; margin: -120px 0 0 -120px; border-radius: 50%; pointer-events: none;\n background: radial-gradient(closest-side, color-mix(in oklab, var(--cx-accent) 30%, transparent), transparent);\n transform: scale(calc(0.85 + var(--cx-lvl, 0) * 0.5)); opacity: calc(0.25 + var(--cx-lvl, 0) * 0.75); transition: transform .1s linear, opacity .1s linear; }\n\n/* queue */\n.line { position: relative; width: 168px; height: 168px; display: grid; place-items: center; margin: 4px auto 0; }\n.line svg { position: absolute; inset: 0; transform: rotate(-90deg); }\n.line__track { stroke: var(--cx-line); }\n.line__fill { stroke: var(--cx-accent); transition: stroke-dashoffset .8s var(--cx-ease); }\n.line__num { font-size: 46px; font-weight: 750; letter-spacing: -0.04em; line-height: 1; font-variant-numeric: tabular-nums; }\n.line__lbl { font-size: 12px; color: var(--cx-ink-2); text-transform: uppercase; letter-spacing: .08em; margin-top: 4px; }\n.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 44px; padding: 0 18px; border-radius: 999px; font-size: 14.5px; font-weight: 600; background: var(--cx-bubble); transition: transform .3s var(--cx-spring), background .2s; }\n.btn:hover { background: color-mix(in oklab, var(--cx-ink) 10%, transparent); }\n.btn:active { transform: scale(.97); }\n.btn--accent { background: var(--cx-accent); color: var(--cx-accent-ink); }\n.btn--accent:hover { background: color-mix(in oklab, var(--cx-accent) 88%, #000); }\n.btn--glow { box-shadow: 0 0 0 0 color-mix(in oklab, var(--cx-accent) 55%, transparent); animation: cx-glow 1.6s ease-out infinite; }\n.btn-row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }\n.note { font-size: 13.5px; color: var(--cx-ink-2); max-width: 300px; }\n.title { font-size: 19px; font-weight: 700; letter-spacing: -0.02em; }\n.spinner { width: 22px; height: 22px; border-radius: 50%; border: 2.5px solid var(--cx-line); border-top-color: var(--cx-accent); animation: cx-spin 0.8s linear infinite; }\n\n/* ------------------------------------------------------------ portrait */\n.portrait { position: relative; width: 100%; height: 100%; overflow: hidden; }\n.portrait__media { position: absolute; max-width: none; transition: opacity .35s ease; user-select: none; -webkit-user-drag: none; }\n.portrait--initial { display: grid; place-items: center; font-size: 26px; font-weight: 700; color: var(--cx-accent); }\n\n/* ------------------------------------------------------------ test-mode ribbon */\n.dock { position: relative; }\n/* A small tag on the portrait's lower edge: present, never in the way. */\n.testmode { position: absolute; left: 50%; bottom: -7px; transform: translateX(-50%); font-size: 8.5px; font-weight: 800; letter-spacing: .08em; line-height: 1; padding: 3px 5px; border-radius: 5px; background: #f59e0b; color: #1c1206; box-shadow: 0 0 0 2px var(--cx-solid); pointer-events: none; }\n\n/* ------------------------------------------------------------ phones: a bottom sheet */\n@media (max-width: 520px) {\n :host([data-open]) { left: 0 !important; right: 0 !important; bottom: 0 !important; }\n .panel { position: fixed; left: 0; right: 0; bottom: 0; width: 100%; height: min(92dvh, 760px); border-radius: var(--cx-radius) var(--cx-radius) 0 0; padding-bottom: env(safe-area-inset-bottom); animation-name: cx-sheet; }\n .presence { width: 56px; height: 56px; }\n .presence--half { width: 104px; height: 138px; }\n .presence--full { width: 100px; height: 228px; }\n .dock--half .greeting { bottom: 152px; }\n .dock--full .greeting { bottom: 242px; }\n}\n\n@keyframes cx-spin { to { transform: rotate(360deg); } }\n@keyframes cx-rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }\n@keyframes cx-pop { from { opacity: 0; transform: translateY(8px) scale(.92); } to { opacity: 1; transform: none; } }\n@keyframes cx-open { from { opacity: 0; transform: translateY(14px) scale(.94); filter: blur(4px); } to { opacity: 1; transform: none; filter: none; } }\n@keyframes cx-close { to { opacity: 0; transform: translateY(10px) scale(.96); } }\n@keyframes cx-sheet { from { transform: translateY(100%); } to { transform: none; } }\n@keyframes cx-msg { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }\n@keyframes cx-blink { 50% { opacity: 0; } }\n@keyframes cx-bounce { 0%, 60%, 100% { transform: translateY(0); opacity: .45; } 30% { transform: translateY(-4px); opacity: 1; } }\n@keyframes cx-pulse { 50% { opacity: .35; } }\n@keyframes cx-figure-glow { 0%, 100% { filter: drop-shadow(0 0 0 transparent); } 50% { filter: drop-shadow(0 0 12px var(--cx-accent)); } }\n@keyframes cx-glow-ring { 0% { transform: scale(1); opacity: .55; } 100% { transform: scale(1.35); opacity: 0; } }\n@keyframes cx-glow { 0% { box-shadow: 0 0 0 0 color-mix(in oklab, var(--cx-accent) 50%, transparent); } 100% { box-shadow: 0 0 0 16px transparent; } }\n\n@media (prefers-reduced-motion: reduce) {\n *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }\n .presence__ring { animation: none; }\n}\n`;\n","import { CharacterXYZ, CxError, type InitOptions } from '@characterxyz/web';\nimport { render } from 'preact';\n\nimport { App, type AppApi, type View } from './app.js';\nimport { applyLayer, DEFAULTS, fromAttributes, type WidgetConfig } from './config.js';\nimport { CSS } from './styles.js';\n\nexport const TAG = 'character-xyz';\n\nexport interface MountOptions extends InitOptions, Partial<WidgetConfig> {\n /** Where the element goes. Default `document.body`. */\n container?: HTMLElement;\n}\n\n/** Ink that reads on the accent: white on dark accents, near-black on light ones. */\nexport function inkFor(color: string): string {\n const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim());\n if (!m) return '#ffffff';\n const hex = m[1]!.length === 3 ? m[1]!.replace(/./g, (c) => c + c) : m[1]!;\n const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)) as [number, number, number];\n const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n return lum > 0.45 ? '#14121a' : '#ffffff';\n}\n\n/** Relative luminance of a CSS rgb()/rgba() colour, or null when transparent / unreadable. */\nexport function luminanceOf(color: string): number | null {\n const m = /rgba?\\(\\s*([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)(?:[,\\s/]+([\\d.]+%?))?\\s*\\)/.exec(color);\n if (!m) return null;\n const alpha = m[4] === undefined ? 1 : m[4].endsWith('%') ? parseFloat(m[4]) / 100 : parseFloat(m[4]);\n if (alpha < 0.5) return null;\n const [r, g, b] = [m[1], m[2], m[3]].map((v) => Number(v) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)) as [number, number, number];\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\n/**\n * `auto` means \"look like you belong on THIS page\": a dark site gets the dark\n * widget whatever the visitor's system says. The page's own background\n * decides; only a transparent one falls back to the system preference.\n */\nfunction pageIsDark(mq: MediaQueryList | null): boolean {\n for (const el of [document.body, document.documentElement]) {\n if (!el) continue;\n const lum = luminanceOf(getComputedStyle(el).backgroundColor);\n if (lum !== null) return lum < 0.22;\n }\n return !!mq?.matches;\n}\n\nconst ATTRS = ['publishable-key', 'agent', 'api-url', 'position', 'mode', 'accent', 'greeting', 'open'];\n\n/**\n * `<character-xyz publishable-key=\"cxyz_pk_live_…\"></character-xyz>`\n *\n * Events (bubbling, composed): `cx-ready` {agent}, `cx-open` {view},\n * `cx-close`, `cx-call` {phase}, `cx-error` {code, message}.\n * Methods: `open('chat' | 'call')`, `close()`; property `client` once ready.\n */\nexport class CharacterXYZElement extends HTMLElement {\n static get observedAttributes() {\n return ATTRS;\n }\n\n /** Set before the element connects (what `mount()` does). */\n options: MountOptions | null = null;\n client: CharacterXYZ | null = null;\n private api: AppApi | null = null;\n private pendingOpen: View | null = null;\n private booted = false;\n private mq: MediaQueryList | null = null;\n private stage: HTMLDivElement | null = null;\n\n connectedCallback() {\n if (this.booted) return;\n this.booted = true;\n const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });\n const style = document.createElement('style');\n style.textContent = CSS;\n this.stage = document.createElement('div');\n root.replaceChildren(style, this.stage);\n // Out of the page's way until there is something to show.\n this.style.display = 'none';\n // The page's own work first: start once the browser is idle.\n const idle = (window as unknown as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number }).requestIdleCallback;\n if (idle) idle(() => void this.boot(), { timeout: 2000 });\n else setTimeout(() => void this.boot(), 200);\n }\n\n disconnectedCallback() {\n if (this.stage) render(null, this.stage);\n this.client?.destroy();\n this.client = null;\n this.mq?.removeEventListener('change', this.onSchemeChange);\n this.booted = false;\n }\n\n open(view: 'chat' | 'call' = 'chat') {\n if (this.api) this.api.open(view);\n else this.pendingOpen = view;\n }\n\n close() {\n this.api?.close();\n }\n\n private fire(name: string, detail?: unknown) {\n this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));\n }\n\n private onSchemeChange = () => requestAnimationFrame(this.onScheme);\n\n private onScheme = () => {\n if (this.dataset.mode === 'auto') this.dataset.theme = pageIsDark(this.mq) ? 'dark' : 'light';\n };\n\n private async boot() {\n const opts: MountOptions = { ...(this.options ?? {}) };\n const attrs = fromAttributes(Array.from(this.attributes));\n const publishableKey = opts.publishableKey ?? (attrs.publishableKey as string | undefined);\n try {\n this.client = await CharacterXYZ.init({\n publishableKey,\n getSessionToken: opts.getSessionToken,\n agentId: opts.agentId ?? (attrs.agent as string | undefined),\n apiUrl: opts.apiUrl ?? (attrs.apiUrl as string | undefined),\n storage: opts.storage,\n });\n } catch (e) {\n const err = e instanceof CxError ? e : new CxError('unknown', String((e as Error)?.message ?? e));\n // The widget stays hidden: a broken embed must never put an error box\n // on the brand's page. The console and the event say why.\n console.warn(`[characterxyz] widget not shown: ${err.message}`);\n this.fire('cx-error', { code: err.code, message: err.message });\n return;\n }\n if (!this.isConnected) {\n this.client.destroy();\n return;\n }\n const client = this.client;\n // Designer appearance, then attributes, then mount() options.\n let config = applyLayer(DEFAULTS, client.appearance as Record<string, unknown>);\n config = applyLayer(config, attrs);\n config = applyLayer(config, opts as unknown as Record<string, unknown>);\n if (!(config.showChat && client.features.chat) && !(config.showCall && client.features.call)) {\n console.warn('[characterxyz] widget not shown: neither chat nor calls are enabled for this site');\n return;\n }\n this.applyTokens(config);\n client.on('call', (c) => {\n if (!c) return;\n c.on('state', (s) => this.fire('cx-call', { phase: s.phase, position: s.position, endReason: s.endReason }));\n });\n client.on('error', (e) => this.fire('cx-error', { code: e.code, message: e.message }));\n this.style.display = '';\n render(\n <App\n client={client}\n config={config}\n bind={(api) => {\n this.api = api;\n if (this.pendingOpen && this.pendingOpen !== 'closed') {\n api.open(this.pendingOpen);\n this.pendingOpen = null;\n }\n }}\n onView={(v) => {\n if (v === 'closed') {\n this.removeAttribute('data-open');\n this.fire('cx-close');\n } else {\n this.setAttribute('data-open', '');\n this.fire('cx-open', { view: v });\n }\n }}\n />,\n this.stage!,\n );\n if (config.open) this.setAttribute('data-open', '');\n this.fire('cx-ready', { agent: { id: client.agent.id, name: client.agent.name }, features: client.features });\n }\n\n private applyTokens(c: WidgetConfig) {\n this.dataset.side = c.position === 'bottom-left' ? 'left' : 'right';\n this.dataset.mode = c.mode;\n if (c.mode === 'auto') {\n this.mq = matchMedia('(prefers-color-scheme: dark)');\n // A site's own dark mode usually follows the system, so re-read the page then.\n this.mq.addEventListener('change', this.onSchemeChange);\n this.dataset.theme = pageIsDark(this.mq) ? 'dark' : 'light';\n } else {\n this.dataset.theme = c.mode;\n }\n const set = (k: string, v: string) => this.style.setProperty(k, v);\n set('--cx-accent', c.accent);\n set('--cx-accent-ink', inkFor(c.accent));\n set('--cx-radius', `${c.radius}px`);\n if (c.font) set('--cx-font', c.font);\n set('--cx-ox', `${c.offsetX}px`);\n set('--cx-oy', `${c.offsetY}px`);\n set('--cx-z', String(c.zIndex));\n }\n}\n\nexport function define() {\n if (typeof customElements !== 'undefined' && !customElements.get(TAG)) customElements.define(TAG, CharacterXYZElement);\n}\n\nexport interface WidgetHandle {\n element: CharacterXYZElement;\n open(view?: 'chat' | 'call'): void;\n close(): void;\n destroy(): void;\n}\n\n/** Put the widget on the page. One per page is the norm; a second replaces nothing. */\nexport function mount(options: MountOptions): WidgetHandle {\n define();\n const el = document.createElement(TAG) as CharacterXYZElement;\n el.options = options;\n (options.container ?? document.body).appendChild(el);\n return {\n element: el,\n open: (v) => el.open(v),\n close: () => el.close(),\n destroy: () => el.remove(),\n };\n}\n"],"mappings":"+lBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,WAAAE,KCqDO,IAAMC,GAAyB,CACpC,SAAU,eACV,KAAM,OACN,SAAU,SACV,QAAS,SACT,OAAQ,UACR,OAAQ,GACR,KAAM,GACN,SAAU,KACV,SAAU,GACV,cAAe,EACf,YAAa,CAAC,EACd,YAAa,UACb,SAAU,GACV,SAAU,GACV,SAAU,GACV,QAAS,GACT,QAAS,GACT,OAAQ,UACR,KAAM,GACN,KAAM,GACN,QAAS,sCACX,EAEMC,GAAM,CAACC,EAAYC,EAAYC,IAAmC,CACtE,IAAMC,EAAI,OAA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","names":["iife_exports","__export","mount","DEFAULTS","num","v","lo","hi","n","bool","str","max","safeColor","s","safeFont","applyLayer","base","raw","c","fromAttributes","attrs","out","name","value","key","_","ch","shared","audioContext","PcmPlayer","opts","__publicField","bytes","count","view","buf","ch","i","src","now","delayMs","s","sum","v","WORKLET","levelOf","pcm","openMic","stream","ctx","source","muted","deliver","node","teardown","url","w","e","sp","ratio","pos","out","n","sink","m","t","Emitter","event","fn","_a","payload","CxError","code","message","status","codeForStatus","errorFrom","res","j","send","apiUrl","path","headers","request","readEvents","onEvent","signal","body","reader","decoder","onAbort","value","done","drain","rest","idx","block","data","line","colon","field","raw","parsed","parsePacket","kind","final","o","corrLen","corr","len","BARGE_IN_LEVEL","BARGE_IN_MS","HEARTBEAT_MS","initial","Call","session","agentId","p","patch","level","token","r","err","reason","failures","d","hold","ws","face","emotion","player","c","old","cid","heardMs","id","was","error","localSeq","localId","Chat","pending","text","mine","reply","finished","failure","x","next","b","memoryStore","k","localStore","RENEW_EARLY_S","SessionManager","info","got","visitorId","DEFAULT_API_URL","CharacterXYZ","_CharacterXYZ","store","call","slice","options","vnodeId","isValidElement","rerenderQueue","prevDebounce","defer","depthSort","_id","EVENT_DISPATCHED","EVENT_ATTACHED","CAPTURE_REGEX","eventClock","eventProxy","eventProxyCapture","i","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","isArray","Array","assign","obj","props","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","call","defaultProps","createVNode","original","vnode","__k","__","__b","__e","__c","constructor","__v","__i","__u","Fragment","props","children","BaseComponent","context","this","getDomSibling","vnode","childIndex","__","__i","sibling","__k","length","__e","type","renderComponent","component","__P","__d","oldVNode","__v","oldDom","commitQueue","refQueue","newVNode","assign","options","diff","__n","namespaceURI","__u","commitRoot","updateParentDomPointers","__c","base","some","child","enqueueRender","c","rerenderQueue","push","process","__r","prevDebounce","debounceRendering","defer","l","sort","depthSort","shift","diffChildren","parentDom","renderResult","newParentVNode","oldParentVNode","globalContext","namespace","excessDomChildren","isHydrating","i","childVNode","newDom","firstChildDom","result","oldChildren","EMPTY_ARR","newChildrenLength","constructNewChildrenArray","EMPTY_OBJ","ref","applyRef","insert","nextSibling","skewedIndex","matchingIndex","oldChildrenLength","remainingOldChildren","skew","Array","constructor","String","createVNode","isArray","__b","key","findMatchingIndex","unmount","parentVNode","parentNode","insertBefore","nodeType","findMatchingIndex","childVNode","oldChildren","skewedIndex","remainingOldChildren","x","y","childIndex","key","type","oldVNode","matched","__u","length","setStyle","style","value","setProperty","IS_NON_DIMENSIONAL","test","dom","name","oldValue","namespace","useCapture","lowerCaseName","o","cssText","replace","CAPTURE_REGEX","toLowerCase","slice","l","EVENT_ATTACHED","eventClock","addEventListener","eventProxyCapture","eventProxy","removeEventListener","e","removeAttribute","setAttribute","createEventProxy","this","eventHandler","EVENT_DISPATCHED","options","event","diff","parentDom","newVNode","globalContext","excessDomChildren","commitQueue","oldDom","isHydrating","refQueue","tmp","oldCommitQueueLength","c","isNew","oldProps","oldState","snapshot","clearProcessingException","newProps","isClassComponent","provider","componentContext","renderHook","count","renderResult","i","newType","constructor","__e","__b","outer","props","prototype","render","contextType","__c","__","__E","BaseComponent","doRender","sub","state","__n","__d","__h","_sb","__s","getDerivedStateFromProps","assign","__v","componentWillMount","componentDidMount","push","componentWillReceiveProps","shouldComponentUpdate","__k","some","vnode","EMPTY_ARR","apply","getDomSibling","componentWillUpdate","componentDidUpdate","context","__P","__r","getChildContext","getSnapshotBeforeUpdate","Fragment","cloneNode","children","diffChildren","isArray","base","then","MODE_HYDRATE","nodeType","nextSibling","indexOf","removeNode","markAsForce","diffElementNodes","diffed","commitRoot","root","applyRef","cb","call","node","map","newHtml","oldHtml","newChildren","inputValue","checked","EMPTY_OBJ","localName","document","createTextNode","createElementNS","is","__m","data","defaultValue","childNodes","attributes","__html","innerHTML","content","undefined","ref","hasRefUnmount","current","unmount","parentVNode","skipRemove","r","componentWillUnmount","replaceNode","documentElement","createElement","namespaceURI","firstChild","slice","EMPTY_ARR","options","__e","error","vnode","oldVNode","errorInfo","component","ctor","handled","__","__c","constructor","getDerivedStateFromError","setState","__d","componentDidCatch","__E","e","vnodeId","isValidElement","BaseComponent","prototype","update","callback","s","this","__s","state","assign","props","__v","_sb","push","enqueueRender","forceUpdate","__h","render","Fragment","rerenderQueue","defer","Promise","then","bind","resolve","setTimeout","depthSort","a","b","__b","process","__r","_id","Math","random","toString","EVENT_DISPATCHED","EVENT_ATTACHED","CAPTURE_REGEX","eventClock","eventProxy","createEventProxy","eventProxyCapture","i","currentIndex","currentComponent","previousComponent","prevRaf","currentHook","afterPaintEffects","options","_options","oldBeforeDiff","__b","oldBeforeRender","__r","oldAfterDiff","diffed","oldCommit","__c","oldBeforeUnmount","unmount","oldRoot","__","getHookState","index","type","__h","hooks","__H","length","push","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","action","currentValue","__N","nextValue","setState","__f","updateHookState","p","s","c","updatedHook","shouldUpdate","props","some","hookItem","prevScu","result","call","this","shouldComponentUpdate","prevCWU","componentWillUpdate","__e","tmp","useEffect","callback","args","state","__s","argsChanged","_pendingArgs","useLayoutEffect","useRef","initialValue","useMemo","current","useMemo","factory","args","state","getHookState","currentIndex","argsChanged","__H","__","__h","useCallback","callback","currentHook","flushAfterPaintEffects","component","afterPaintEffects","shift","hooks","__H","__P","__h","some","invokeCleanup","invokeEffect","e","options","__e","__v","__b","vnode","currentComponent","oldBeforeDiff","__","parentDom","__k","__m","oldRoot","__r","oldBeforeRender","currentIndex","__c","previousComponent","hookItem","__N","_pendingArgs","diffed","oldAfterDiff","c","length","push","prevRaf","requestAnimationFrame","afterNextFrame","commitQueue","filter","cb","oldCommit","unmount","oldBeforeUnmount","hasErrored","s","HAS_RAF","callback","raf","done","clearTimeout","timeout","cancelAnimationFrame","setTimeout","hook","comp","cleanup","argsChanged","oldArgs","newArgs","arg","index","invokeOrReturn","f","ordinal","n","v","eta","seconds","m","clock","totalSeconds","s","h","ss","endCopy","reason","name","inline","out","re","last","tok","blocks","text","para","lines","l","FALLBACK","faceOf","video","anchorW","anchorH","eyes","chin","ex","ey","span","CLOSE_UP","MEDIUM","HALF_BODY","FULL_BODY","place","face","mediaAspect","boxW","boxH","shot","width","height","vnodeId","createVNode","type","props","key","isStaticChildren","__source","__self","ref","i","normalizedProps","vnode","__k","__","__b","__e","__c","constructor","__v","vnodeId","__i","__u","defaultProps","options","svg","size","children","u","ChatIcon","PhoneIcon","HangUpIcon","MicIcon","S","MicOffIcon","CloseIcon","SendIcon","BackIcon","SparkIcon","RetryIcon","faceEmotion","cameoState","s","FaceFrame","client","call","state","src","onStatus","frame","A","loaded","setLoaded","d","loadedRef","origin","post","msg","transfer","w","h","cancelled","onMessage","e","avatar","timeout","cameo","offs","corr","payload","event","raf","tick","a","f","u","alphaVideoWorks","ua","reducedMotion","Portrait","agent","shot","talking","still","cls","box","A","size","setSize","d","anchorDims","setAnchorDims","ready","setReady","video","anchorUrl","canPlay","idle","talk","_","el","update","ro","u","aspect","face","faceOf","p","place","style","showIdle","showTalk","e","img","Clip","r","src","visible","onReady","ref","h","v","GREETED_KEY","INTRODUCED_KEY","storage","key","value","chime","Ctx","ctx","now","f","i","o","g","useChat","client","messages","setMessages","d","busy","setBusy","h","a","b","useCall","call","setCall","state","setState","captions","setCaptions","c","offs","prev","x","id","useElapsed","startedAt","running","setNow","t","useVoiceLevel","el","active","raf","smooth","tick","lvl","Text","parts","u","S","p","line","j","arr","Rich","text","blocks","it","App","config","bind","onView","agent","features","canChat","canCall","view","setViewRaw","closing","setClosing","greeting","setGreeting","reset","draft","setDraft","log","A","input","stage","subtitle","name","setView","q","v","close","open","labelled","setLabelled","onKey","e","wantsFace","faceStatus","setFaceStatus","phase","title","restore","live","elapsed","startPos","useMemoStart","startCall","faceEmotion","sendText","lastAgentStreaming","inLine","CloseIcon","ordinal","Portrait","FULL_BODY","HALF_BODY","CLOSE_UP","ChatIcon","PhoneIcon","head","eta","s","SparkIcon","m","RetryIcon","SendIcon","position","progress","R","C","remaining","agentState","status","ended","copy","endCopy","MEDIUM","FaceFrame","clock","k","MicOffIcon","MicIcon","HangUpIcon","BackIcon","ref","CSS","TAG","inkFor","color","m","hex","c","r","g","b","i","luminanceOf","v","pageIsDark","mq","el","lum","ATTRS","CharacterXYZElement","__publicField","root","style","CSS","idle","R","view","name","detail","opts","attrs","fromAttributes","publishableKey","e","err","d","client","config","applyLayer","DEFAULTS","s","u","App","api","set","k","define","mount","options","script","widget","start","attrs","fromAttributes","a","given","v","key","config","applyLayer","DEFAULTS","opts","k","mount","api","o"]}
1
+ {"version":3,"sources":["../src/iife.ts","../src/config.ts","../../web/src/audio/player.ts","../../web/src/audio/mic.ts","../../web/src/emitter.ts","../../web/src/errors.ts","../../web/src/http.ts","../../web/src/protocol.ts","../../web/src/call.ts","../../web/src/chat.ts","../../web/src/session.ts","../../web/src/client.ts","../../web/src/index.ts","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/constants.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/util.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/options.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/create-element.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/component.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/props.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/create-context.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/children.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/index.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/render.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/clone-element.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/diff/catch-error.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/hooks/src/index.js","../src/format.ts","../src/framing.ts","../src/contact.ts","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/jsx-runtime/src/utils.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/src/constants.js","../../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/jsx-runtime/src/index.js","../src/icons.tsx","../src/face-frame.tsx","../src/portrait.tsx","../src/app.tsx","../src/styles.ts","../src/element.tsx"],"sourcesContent":["/**\n * `cx.js` — the script-tag build. Everything in one file; reads its settings\n * from its own `data-*` attributes and mounts itself:\n *\n * ```html\n * <script src=\"https://unpkg.com/@characterxyz/widget@0/dist/cx.js\"\n * data-key=\"cxyz_pk_live_…\" data-accent=\"#e11d48\" async></script>\n * ```\n *\n * `window.CharacterXYZ` is then `{ mount, open, close, widget }` for pages\n * that want to drive it (`CharacterXYZ.open('call')`).\n */\nimport { applyLayer, DEFAULTS, fromAttributes } from './config.js';\nimport { mount, type MountOptions, type WidgetHandle } from './element.js';\n\nexport { mount };\n\nconst script = document.currentScript as HTMLScriptElement | null;\nlet widget: WidgetHandle | null = null;\n\nfunction start() {\n if (!script) return;\n const attrs = fromAttributes(Array.from(script.attributes).filter((a) => a.name.startsWith('data-')));\n // An empty attribute is \"not set\" (a template that left it blank), never \"\".\n const given = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);\n const key = given(attrs.key) ?? given(attrs.publishableKey);\n if (!key) return; // no key on the tag: the page will call CharacterXYZ.mount() itself\n // Only the presentational settings pass through the config filter; the\n // connection settings are read directly.\n const config = applyLayer(DEFAULTS, attrs);\n const changed = Object.fromEntries(Object.entries(config).filter(([k, v]) => k in attrs && v !== (DEFAULTS as unknown as Record<string, unknown>)[k]));\n const opts: MountOptions = {\n ...changed,\n publishableKey: key,\n agentId: given(attrs.agent),\n apiUrl: given(attrs.apiUrl),\n };\n widget = mount(opts);\n}\n\nif (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });\nelse start();\n\nconst api = {\n mount: (o: MountOptions) => (widget = mount(o)),\n open: (v?: 'chat' | 'call') => widget?.open(v),\n close: () => widget?.close(),\n get widget() {\n return widget;\n },\n};\n(window as unknown as { CharacterXYZ: typeof api }).CharacterXYZ = api;\n","/**\n * Everything a brand can set, from three places, later wins:\n * 1. the key's `appearance` (the Embed designer in Character XYZ),\n * 2. the element's attributes / `data-*` on the script tag,\n * 3. options passed to `mount()`.\n */\n\nexport type Position = 'bottom-right' | 'bottom-left';\nexport type ColorMode = 'light' | 'dark' | 'auto';\n/** `bubble`: just her portrait (opens the chat; calls are inside). `actions`: chat and call buttons beside it. */\nexport type LauncherStyle = 'bubble' | 'actions';\n/** How she is shown while closed: a round `bubble`, a `half` body cut-out, or her `full` body standing in the corner. */\nexport type Display = 'bubble' | 'half' | 'full';\n\nexport interface WidgetConfig {\n position: Position;\n mode: ColorMode;\n launcher: LauncherStyle;\n display: Display;\n /** Any CSS colour. */\n accent: string;\n /** Corner radius of the panel, px. */\n radius: number;\n /** A CSS font-family; defaults to the system UI font. */\n font: string;\n /** The line under her name; defaults to the agent's tagline. */\n subtitle: string | null;\n /** Shown once per visitor above the launcher. Empty = none. */\n greeting: string;\n /** Seconds before the greeting appears. */\n greetingDelay: number;\n /** Suggested first messages in an empty chat. */\n suggestions: string[];\n /** Placeholder in the message box. */\n placeholder: string;\n showChat: boolean;\n showCall: boolean;\n /** The \"Powered by Character XYZ\" line. */\n branding: boolean;\n /** px from the corner. */\n offsetX: number;\n offsetY: number;\n zIndex: number;\n /** Open the panel on load. */\n open: boolean;\n /**\n * Draw the agent's face in calls with Character XYZ's own renderer (lip\n * sync, her own teeth and eyes), framed from `faceUrl`. Off = the portrait clips.\n */\n face: boolean;\n faceUrl: string;\n}\n\nexport const DEFAULTS: WidgetConfig = {\n position: 'bottom-right',\n mode: 'auto',\n launcher: 'bubble',\n display: 'bubble',\n accent: '#7c5cff',\n radius: 24,\n font: '',\n subtitle: null,\n greeting: '',\n greetingDelay: 3,\n suggestions: [],\n placeholder: 'Message',\n showChat: true,\n showCall: true,\n branding: true,\n offsetX: 20,\n offsetY: 20,\n zIndex: 2147483000,\n open: false,\n face: true,\n faceUrl: 'https://www.character.xyz/embed/face',\n};\n\nconst num = (v: unknown, lo: number, hi: number): number | undefined => {\n const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;\n return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : undefined;\n};\n\nconst bool = (v: unknown): boolean | undefined => {\n if (typeof v === 'boolean') return v;\n if (v === 'true' || v === '' || v === '1') return true;\n if (v === 'false' || v === '0') return false;\n return undefined;\n};\n\nconst str = (v: unknown, max = 200): string | undefined => (typeof v === 'string' ? v.slice(0, max) : undefined);\n\n/** A colour the page can use safely in CSS: hex, rgb()/hsl()/oklch() or a name. Anything else is ignored. */\nexport function safeColor(v: unknown): string | undefined {\n if (typeof v !== 'string') return undefined;\n const s = v.trim();\n if (/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s)) return s;\n if (/^(rgb|rgba|hsl|hsla|oklch|oklab)\\([0-9.,%\\s/+-]+\\)$/i.test(s)) return s;\n if (/^[a-z]{3,20}$/i.test(s)) return s;\n return undefined;\n}\n\n/** A font-family list without anything that could escape the declaration. */\nexport function safeFont(v: unknown): string | undefined {\n if (typeof v !== 'string') return undefined;\n const s = v.trim();\n return /^[\\w\\s,\"'-]{1,120}$/.test(s) ? s : undefined;\n}\n\n/** Merge one layer of untrusted settings onto a config. Unknown or invalid values are dropped. */\nexport function applyLayer(base: WidgetConfig, raw: Record<string, unknown> | null | undefined): WidgetConfig {\n if (!raw || typeof raw !== 'object') return base;\n const c = { ...base };\n if (raw.position === 'bottom-left' || raw.position === 'bottom-right') c.position = raw.position;\n if (raw.mode === 'light' || raw.mode === 'dark' || raw.mode === 'auto') c.mode = raw.mode;\n if (raw.launcher === 'bubble' || raw.launcher === 'actions') c.launcher = raw.launcher;\n if (raw.display === 'bubble' || raw.display === 'half' || raw.display === 'full') c.display = raw.display;\n c.accent = safeColor(raw.accent) ?? c.accent;\n c.radius = num(raw.radius, 0, 40) ?? c.radius;\n c.font = safeFont(raw.font) ?? c.font;\n if (raw.subtitle === null) c.subtitle = null;\n else c.subtitle = str(raw.subtitle, 80) ?? c.subtitle;\n c.greeting = str(raw.greeting, 160) ?? c.greeting;\n c.greetingDelay = num(raw.greetingDelay, 0, 120) ?? c.greetingDelay;\n if (Array.isArray(raw.suggestions)) {\n c.suggestions = raw.suggestions.filter((s): s is string => typeof s === 'string' && s.trim() !== '').map((s) => s.slice(0, 80)).slice(0, 4);\n } else if (typeof raw.suggestions === 'string') {\n c.suggestions = raw.suggestions.split('|').map((s) => s.trim()).filter(Boolean).slice(0, 4);\n }\n c.placeholder = str(raw.placeholder, 60) ?? c.placeholder;\n c.showChat = bool(raw.showChat) ?? c.showChat;\n c.showCall = bool(raw.showCall) ?? c.showCall;\n c.branding = bool(raw.branding) ?? c.branding;\n c.offsetX = num(raw.offsetX, 0, 200) ?? c.offsetX;\n c.offsetY = num(raw.offsetY, 0, 200) ?? c.offsetY;\n c.zIndex = num(raw.zIndex, 0, 2147483647) ?? c.zIndex;\n c.open = bool(raw.open) ?? c.open;\n c.face = bool(raw.face) ?? c.face;\n if (typeof raw.faceUrl === 'string' && /^https?:\\/\\/[^\\s\"'<>]+$/.test(raw.faceUrl.trim())) c.faceUrl = raw.faceUrl.trim();\n return c;\n}\n\n/** `data-show-call=\"false\"` → `{ showCall: 'false' }`: kebab attributes to camel keys. */\nexport function fromAttributes(attrs: Iterable<{ name: string; value: string }>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const { name, value } of attrs) {\n const key = name.replace(/^data-/, '').replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase());\n out[key] = value;\n }\n return out;\n}\n","/**\n * Plays the agent's streamed voice (PCM16 chunks) gaplessly, and reports how\n * loud it is right now so a UI can draw a ring that follows the voice.\n *\n * Each chunk becomes an AudioBuffer scheduled right after the last one; the\n * first waits a short pre-roll so a slow second chunk does not open a gap.\n */\n\nexport interface PlayerOptions {\n sampleRate?: number;\n onStart?: () => void;\n onEnd?: () => void;\n volume?: number;\n}\n\nconst PREROLL_S = 0.12;\n\nlet shared: AudioContext | null = null;\n\n/** One output context for the page, created on first use (after a gesture). */\nexport function audioContext(): AudioContext {\n if (!shared || shared.state === 'closed') shared = new AudioContext({ latencyHint: 'interactive' });\n if (shared.state === 'suspended') void shared.resume().catch(() => {});\n return shared;\n}\n\nexport class PcmPlayer {\n private readonly ctx: AudioContext;\n private readonly gain: GainNode;\n private readonly analyser: AnalyserNode;\n private readonly data: Uint8Array<ArrayBuffer>;\n private nextAt = 0;\n private started = false;\n private ended = false;\n private finishing = false;\n private sources = new Set<AudioBufferSourceNode>();\n private startedAt = 0;\n readonly sampleRate: number;\n\n constructor(private readonly opts: PlayerOptions = {}) {\n this.ctx = audioContext();\n this.sampleRate = opts.sampleRate ?? 16_000;\n this.gain = this.ctx.createGain();\n this.gain.gain.value = opts.volume ?? 1;\n this.analyser = this.ctx.createAnalyser();\n this.analyser.fftSize = 512;\n this.data = new Uint8Array(new ArrayBuffer(this.analyser.fftSize));\n this.gain.connect(this.analyser).connect(this.ctx.destination);\n }\n\n /** Queue PCM16 little-endian mono bytes. */\n enqueue(bytes: Uint8Array): void {\n if (this.ended || bytes.byteLength < 2) return;\n const count = Math.floor(bytes.byteLength / 2);\n const view = new DataView(bytes.buffer, bytes.byteOffset, count * 2);\n const buf = this.ctx.createBuffer(1, count, this.sampleRate);\n const ch = buf.getChannelData(0);\n for (let i = 0; i < count; i++) ch[i] = view.getInt16(i * 2, true) / 32768;\n const src = this.ctx.createBufferSource();\n src.buffer = buf;\n src.connect(this.gain);\n const now = this.ctx.currentTime;\n if (this.nextAt < now) this.nextAt = now + (this.started ? 0.02 : PREROLL_S);\n src.start(this.nextAt);\n if (!this.started) {\n this.started = true;\n const delayMs = Math.max(0, (this.nextAt - now) * 1000);\n this.startedAt = performance.now() + delayMs;\n setTimeout(() => this.opts.onStart?.(), delayMs);\n }\n this.nextAt += buf.duration;\n this.sources.add(src);\n src.onended = () => {\n this.sources.delete(src);\n if (this.finishing && this.sources.size === 0) this.finish();\n };\n }\n\n /** No more chunks: report the end once the queue has played out. */\n end(): void {\n this.finishing = true;\n if (this.sources.size === 0) this.finish();\n }\n\n /** Silence now (an interruption). Does not call `onEnd`. */\n stop(): void {\n this.ended = true;\n for (const s of this.sources) {\n try {\n s.stop();\n } catch {\n /* not started */\n }\n }\n this.sources.clear();\n this.gain.disconnect();\n }\n\n /** Milliseconds of audio actually heard so far. */\n playedMs(): number {\n return this.started ? Math.max(0, performance.now() - this.startedAt) : 0;\n }\n\n /** Loudness now, 0..1. */\n level(): number {\n this.analyser.getByteTimeDomainData(this.data);\n let sum = 0;\n for (let i = 0; i < this.data.length; i++) {\n const v = (this.data[i]! - 128) / 128;\n sum += v * v;\n }\n return Math.min(1, Math.sqrt(sum / this.data.length) * 3);\n }\n\n private finish() {\n if (this.ended) return;\n this.ended = true;\n this.gain.disconnect();\n this.opts.onEnd?.();\n }\n}\n","/**\n * The microphone as the agent socket wants it: 16 kHz mono PCM16, 30 ms\n * (480-sample) frames, sent continuously.\n *\n * Resampled in an AudioWorklet from whatever rate the device runs at. A\n * context forced to 16 kHz would be simpler and is refused by Firefox for a\n * MediaStream source at another rate, so the worklet does it.\n */\n\nexport const TARGET_RATE = 16_000;\nexport const FRAME_SAMPLES = 480;\n\nconst WORKLET = `\nclass CxyzMic extends AudioWorkletProcessor {\n constructor(o) {\n super();\n this.ratio = sampleRate / ${TARGET_RATE};\n this.pos = 0;\n this.lp = 0;\n this.alpha = Math.min(1, 2 * Math.PI * 7000 / sampleRate / (1 + 2 * Math.PI * 7000 / sampleRate));\n this.out = new Int16Array(${FRAME_SAMPLES});\n this.n = 0;\n }\n process(inputs) {\n const ch = inputs[0] && inputs[0][0];\n if (!ch) return true;\n for (let i = 0; i < ch.length; i++) {\n this.lp += this.alpha * (ch[i] - this.lp);\n this.pos += 1;\n if (this.pos >= this.ratio) {\n this.pos -= this.ratio;\n const s = Math.max(-1, Math.min(1, this.lp));\n this.out[this.n++] = s < 0 ? s * 0x8000 : s * 0x7fff;\n if (this.n === ${FRAME_SAMPLES}) {\n this.port.postMessage(this.out.buffer, [this.out.buffer]);\n this.out = new Int16Array(${FRAME_SAMPLES});\n this.n = 0;\n }\n }\n }\n return true;\n }\n}\nregisterProcessor('cxyz-mic', CxyzMic);\n`;\n\nexport interface MicOptions {\n onFrame: (pcm: ArrayBuffer, level: number) => void;\n deviceId?: string;\n}\n\nexport interface Mic {\n stop(): void;\n setMuted(m: boolean): void;\n readonly muted: boolean;\n}\n\n/** RMS of a PCM16 frame, 0..1. */\nexport function levelOf(pcm: ArrayBuffer): number {\n const s = new Int16Array(pcm);\n if (!s.length) return 0;\n let sum = 0;\n for (let i = 0; i < s.length; i++) {\n const v = s[i]! / 32768;\n sum += v * v;\n }\n return Math.sqrt(sum / s.length);\n}\n\nexport async function openMic(opts: MicOptions): Promise<Mic> {\n if (!navigator.mediaDevices?.getUserMedia) throw new Error('This browser cannot use a microphone here.');\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: {\n deviceId: opts.deviceId ? { exact: opts.deviceId } : undefined,\n channelCount: 1,\n // The agent's voice comes out of the speakers; without cancellation it\n // would hear itself and answer.\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true,\n },\n });\n const ctx = new AudioContext({ latencyHint: 'interactive' });\n const source = ctx.createMediaStreamSource(stream);\n let muted = false;\n const deliver = (buf: ArrayBuffer) => {\n if (muted) {\n // Silence, not nothing: the server keeps a pre-roll of the last frames\n // and splices it onto the next utterance.\n opts.onFrame(new ArrayBuffer(buf.byteLength), 0);\n return;\n }\n opts.onFrame(buf, levelOf(buf));\n };\n\n let node: AudioNode;\n let teardown: () => void;\n try {\n const url = URL.createObjectURL(new Blob([WORKLET], { type: 'application/javascript' }));\n try {\n await ctx.audioWorklet.addModule(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n const w = new AudioWorkletNode(ctx, 'cxyz-mic');\n w.port.onmessage = (e) => deliver(e.data as ArrayBuffer);\n node = w;\n teardown = () => {\n w.port.onmessage = null;\n };\n } catch {\n // A strict Content-Security-Policy can refuse a blob: worklet. The old\n // ScriptProcessor path is deprecated but universal.\n const sp = ctx.createScriptProcessor(4096, 1, 1);\n const ratio = ctx.sampleRate / TARGET_RATE;\n let pos = 0;\n let out = new Int16Array(FRAME_SAMPLES);\n let n = 0;\n sp.onaudioprocess = (e) => {\n const ch = e.inputBuffer.getChannelData(0);\n for (let i = 0; i < ch.length; i++) {\n pos += 1;\n if (pos >= ratio) {\n pos -= ratio;\n const s = Math.max(-1, Math.min(1, ch[i]!));\n out[n++] = s < 0 ? s * 0x8000 : s * 0x7fff;\n if (n === FRAME_SAMPLES) {\n deliver(out.buffer);\n out = new Int16Array(FRAME_SAMPLES);\n n = 0;\n }\n }\n }\n };\n node = sp;\n teardown = () => {\n sp.onaudioprocess = null;\n };\n }\n source.connect(node);\n // A worklet/processor only runs while connected to the destination; a gain\n // of zero keeps the room from hearing itself.\n const sink = ctx.createGain();\n sink.gain.value = 0;\n node.connect(sink).connect(ctx.destination);\n if (ctx.state === 'suspended') await ctx.resume().catch(() => {});\n\n return {\n get muted() {\n return muted;\n },\n setMuted(m: boolean) {\n muted = m;\n for (const t of stream.getAudioTracks()) t.enabled = !m;\n },\n stop() {\n teardown();\n try {\n source.disconnect();\n node.disconnect();\n } catch {\n /* already disconnected */\n }\n for (const t of stream.getTracks()) t.stop();\n void ctx.close().catch(() => {});\n },\n };\n}\n","/** A tiny typed event emitter. `on` returns the unsubscribe. */\nexport class Emitter<Events extends Record<string, unknown>> {\n private handlers: { [K in keyof Events]?: Set<(payload: Events[K]) => void> } = {};\n\n on<K extends keyof Events>(event: K, fn: (payload: Events[K]) => void): () => void {\n (this.handlers[event] ??= new Set()).add(fn);\n return () => this.handlers[event]?.delete(fn);\n }\n\n emit<K extends keyof Events>(event: K, payload: Events[K]): void {\n for (const fn of this.handlers[event] ?? []) {\n try {\n fn(payload);\n } catch (e) {\n // A listener's bug must never break the SDK's own state machine.\n console.error('[characterxyz] listener threw', e);\n }\n }\n }\n\n clear(): void {\n this.handlers = {};\n }\n}\n","export type CxErrorCode =\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'invalid'\n | 'rate_limited'\n | 'payment_required'\n | 'unavailable'\n | 'network'\n | 'unknown';\n\n/** Every failure the SDK reports, with a message fit to show a visitor. */\nexport class CxError extends Error {\n readonly code: CxErrorCode;\n readonly status: number;\n /** On `invalid`: what is wrong with each field, by its name (`email`, `name`…). */\n readonly fields: Record<string, string>;\n\n constructor(code: CxErrorCode, message: string, status = 0, fields: Record<string, string> = {}) {\n super(message);\n this.name = 'CxError';\n this.code = code;\n this.status = status;\n this.fields = fields;\n }\n}\n\nexport function codeForStatus(status: number): CxErrorCode {\n switch (status) {\n case 401:\n return 'unauthorized';\n case 403:\n return 'forbidden';\n case 404:\n return 'not_found';\n case 402:\n return 'payment_required';\n case 422:\n return 'invalid';\n case 429:\n return 'rate_limited';\n case 503:\n return 'unavailable';\n default:\n return 'unknown';\n }\n}\n","import { CxError, codeForStatus } from './errors.js';\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n token?: string;\n signal?: AbortSignal;\n}\n\nasync function errorFrom(res: Response): Promise<CxError> {\n let message = '';\n const fields: Record<string, string> = {};\n try {\n const j = (await res.json()) as { message?: unknown; errors?: { path?: unknown; message?: unknown }[] };\n if (typeof j?.message === 'string') message = j.message;\n for (const e of Array.isArray(j?.errors) ? j.errors : []) {\n if (typeof e?.path === 'string' && typeof e?.message === 'string') fields[e.path] = e.message;\n }\n } catch {\n // not JSON: the status says enough\n }\n return new CxError(codeForStatus(res.status), message || `Request failed (${res.status})`, res.status, fields);\n}\n\nexport async function send(apiUrl: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n const headers: Record<string, string> = {};\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json';\n if (opts.token) headers.Authorization = `Bearer ${opts.token}`;\n let res: Response;\n try {\n res = await fetch(apiUrl + path, {\n method: opts.method ?? (opts.body === undefined ? 'GET' : 'POST'),\n headers,\n body: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: opts.signal,\n // No cookies, ever: the SDK authenticates with its own bearer token, and\n // a credentialed request would carry the brand page's cookies to us.\n credentials: 'omit',\n cache: 'no-store',\n });\n } catch (e) {\n if ((e as Error)?.name === 'AbortError') throw e;\n throw new CxError('network', 'Could not reach Character XYZ. Check your connection.');\n }\n if (!res.ok) throw await errorFrom(res);\n return res;\n}\n\n/** JSON request; unwraps the API's `{message, data}` envelope. */\nexport async function request<T>(apiUrl: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await send(apiUrl, path, opts);\n const j = (await res.json()) as { data?: T };\n return j.data as T;\n}\n\nexport interface ServerEvent {\n event: string;\n data: unknown;\n}\n\n/**\n * Read a `text/event-stream` body, calling `onEvent` per event, until the\n * stream ends or `signal` aborts. Fetch-based on purpose: `EventSource` cannot\n * send an Authorization header, so it would need the token in the URL.\n */\nexport async function readEvents(res: Response, onEvent: (e: ServerEvent) => void, signal?: AbortSignal): Promise<void> {\n const body = res.body;\n if (!body) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = '';\n const onAbort = () => void reader.cancel().catch(() => {});\n signal?.addEventListener('abort', onAbort);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n buf = drain(buf, onEvent);\n }\n buf += decoder.decode();\n drain(buf + '\\n\\n', onEvent);\n } finally {\n signal?.removeEventListener('abort', onAbort);\n }\n}\n\n/** Dispatch every complete event in `buf`; return what is left over. */\nexport function drain(buf: string, onEvent: (e: ServerEvent) => void): string {\n const normalised = buf.replace(/\\r\\n/g, '\\n');\n let rest = normalised;\n let idx: number;\n while ((idx = rest.indexOf('\\n\\n')) !== -1) {\n const block = rest.slice(0, idx);\n rest = rest.slice(idx + 2);\n let event = 'message';\n const data: string[] = [];\n for (const line of block.split('\\n')) {\n if (!line || line.startsWith(':')) continue;\n const colon = line.indexOf(':');\n const field = colon === -1 ? line : line.slice(0, colon);\n const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '');\n if (field === 'event') event = value;\n else if (field === 'data') data.push(value);\n }\n if (!data.length) continue;\n const raw = data.join('\\n');\n let parsed: unknown = raw;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // plain text data\n }\n onEvent({ event, data: parsed });\n }\n return rest;\n}\n","/**\n * The agent socket's binary packet (the same one the Stage reads):\n *\n * \"CXYZ\" | version u8 (1) | kind u8 | flags u8 (bit 0 = final)\n * | corrLen u16 | corr utf8 | seq u32 | timestamp u64 | duration u32\n * | payloadLen u32 | payload\n *\n * All little-endian. Kind 1 is voice (PCM16), kind 2/3 are face data, which\n * this SDK does not draw yet.\n */\nexport interface Packet {\n kind: number;\n final: boolean;\n corr: string;\n payload: Uint8Array;\n}\n\nexport function parsePacket(buf: ArrayBuffer): Packet | null {\n if (buf.byteLength < 25) return null;\n const v = new DataView(buf);\n if (v.getUint8(0) !== 0x43 || v.getUint8(1) !== 0x58 || v.getUint8(2) !== 0x59 || v.getUint8(3) !== 0x5a) return null;\n if (v.getUint8(4) !== 1) return null;\n const kind = v.getUint8(5);\n const final = (v.getUint8(6) & 1) !== 0;\n let o = 7;\n const corrLen = v.getUint16(o, true);\n o += 2;\n if (o + corrLen + 20 > buf.byteLength) return null;\n const corr = new TextDecoder().decode(new Uint8Array(buf, o, corrLen));\n o += corrLen + 4 + 8 + 4;\n const len = v.getUint32(o, true);\n o += 4;\n if (o + len > buf.byteLength) return null;\n return { kind, final, corr, payload: new Uint8Array(buf, o, len) };\n}\n\n/** Build one (for tests and tools). */\nexport function buildPacket(p: { kind: number; final: boolean; corr: string; payload: Uint8Array }): ArrayBuffer {\n const corr = new TextEncoder().encode(p.corr);\n const head = 7 + 2 + corr.length + 4 + 8 + 4 + 4;\n const buf = new ArrayBuffer(head + p.payload.byteLength);\n const v = new DataView(buf);\n const bytes = new Uint8Array(buf);\n bytes.set([0x43, 0x58, 0x59, 0x5a], 0);\n v.setUint8(4, 1);\n v.setUint8(5, p.kind);\n v.setUint8(6, p.final ? 1 : 0);\n let o = 7;\n v.setUint16(o, corr.length, true);\n o += 2;\n bytes.set(corr, o);\n o += corr.length + 4 + 8 + 4;\n v.setUint32(o, p.payload.byteLength, true);\n o += 4;\n bytes.set(p.payload, o);\n return buf;\n}\n","import { audioContext, PcmPlayer } from './audio/player.js';\nimport { openMic, type Mic } from './audio/mic.js';\nimport { Emitter } from './emitter.js';\nimport { CxError } from './errors.js';\nimport { readEvents, request, send } from './http.js';\nimport { parsePacket } from './protocol.js';\nimport type { SessionManager } from './session.js';\nimport type { CallEndReason, CallState, Caption } from './types.js';\n\nexport interface CallEvents extends Record<string, unknown> {\n state: CallState;\n /** The visitor's words and the agent's reply, as they are recognised. */\n caption: Caption;\n /** A caption the server withdrew (the visitor was not finished). */\n captionRemoved: string;\n /** The turn is ready: accept() within `holdSeconds`. */\n ready: { holdSeconds: number };\n /** One streamed face batch (kind-3 msgpack payload) for line `corr` — only with `face`. */\n face: { corr: string; payload: Uint8Array };\n /** A line of the agent's voice became audible, or ended (naturally or interrupted). */\n line: { corr: string; event: 'audible' | 'end' };\n error: CxError;\n}\n\nexport interface CallOptions {\n /** Join the moment it is this visitor's turn (default true). */\n autoAccept?: boolean;\n deviceId?: string;\n /**\n * Ask for the agent's face streamed with the voice (Neural Lip Sync), for a\n * UI that draws it. `emotion()` is read when the call connects: the face's\n * mood as the face service takes it (`joy:0.3`), or null for neutral.\n */\n face?: { emotion?: () => string | null };\n}\n\n/** Talking over the agent this loud, this long, stops her. */\nconst BARGE_IN_LEVEL = 0.09;\nconst BARGE_IN_MS = 350;\nconst HEARTBEAT_MS = 25_000;\n\nconst initial = (): CallState => ({\n phase: 'idle',\n callId: null,\n position: null,\n etaSeconds: null,\n holdSeconds: null,\n maxSeconds: null,\n startedAt: null,\n endReason: null,\n muted: false,\n speaking: false,\n agentState: 'idle',\n error: null,\n});\n\n/**\n * One voice call: join the line, wait (chatting is fine meanwhile), accept,\n * talk, hang up. A call is single-use; start another for the next one.\n */\nexport class Call extends Emitter<CallEvents> {\n private s: CallState = initial();\n private ticket: string | null = null;\n private eventsAbort: AbortController | null = null;\n private ws: WebSocket | null = null;\n private mic: Mic | null = null;\n private players = new Map<string, PcmPlayer>();\n private sampleRates = new Map<string, number>();\n private cancelled = new Set<string>();\n private speakingCorr: string | null = null;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private loudSince: number | null = null;\n\n constructor(\n private readonly apiUrl: string,\n private readonly session: SessionManager,\n private readonly agentId: string,\n private readonly opts: CallOptions = {},\n ) {\n super();\n }\n\n get state(): CallState {\n return this.s;\n }\n\n /** The line being voiced now, and how much of it has been heard (ms). */\n audible(): { corr: string; ms: number } | null {\n const corr = this.speakingCorr;\n const p = corr ? this.players.get(corr) : undefined;\n return corr && p ? { corr, ms: p.playedMs() } : null;\n }\n\n /** Loudness of the agent's voice right now, 0..1. */\n voiceLevel(): number {\n const p = this.speakingCorr ? this.players.get(this.speakingCorr) : undefined;\n return p ? p.level() : 0;\n }\n\n private set(patch: Partial<CallState>) {\n this.s = { ...this.s, ...patch };\n this.emit('state', this.s);\n }\n\n /**\n * Call from a click: it unlocks audio, asks for the microphone, then joins\n * the line (or goes straight through when a slot is free).\n */\n async start(): Promise<void> {\n if (this.s.phase !== 'idle') return;\n this.set({ phase: 'joining' });\n // Created inside the gesture, or the browser keeps it suspended.\n audioContext();\n try {\n this.mic = await openMic({ deviceId: this.opts.deviceId, onFrame: (pcm, level) => this.onMicFrame(pcm, level) });\n } catch {\n this.finish('mic-denied', 'Allow the microphone to talk, or chat instead.');\n return;\n }\n try {\n const token = await this.session.token();\n const r = await request<{ callId: string; state: string; position?: number; etaSeconds?: number }>(this.apiUrl, '/sdk/v1/calls', {\n method: 'POST',\n body: {},\n token,\n });\n this.set({ callId: r.callId, phase: r.state === 'ready' ? 'joining' : 'queued', position: r.position ?? null, etaSeconds: r.etaSeconds ?? null });\n void this.follow();\n } catch (e) {\n const err = e instanceof CxError ? e : new CxError('unknown', 'Could not start the call.');\n const reason: CallEndReason = err.code === 'rate_limited' ? 'busy' : 'unavailable';\n this.finish(reason, err.message);\n this.emit('error', err);\n }\n }\n\n /** Follow the call's server-side state, reconnecting the stream if it drops. */\n private async follow(): Promise<void> {\n let failures = 0;\n while (this.s.callId && this.s.phase !== 'ended' && this.s.phase !== 'idle') {\n this.eventsAbort = new AbortController();\n try {\n const token = await this.session.token();\n const res = await send(this.apiUrl, `/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`, { token, signal: this.eventsAbort.signal });\n failures = 0;\n await readEvents(res, (e) => this.onServerEvent(e.event, e.data as Record<string, unknown>), this.eventsAbort.signal);\n } catch (e) {\n if ((e as Error)?.name === 'AbortError') return;\n if (e instanceof CxError && e.code === 'not_found') {\n this.finish('failed', 'The call ended.');\n return;\n }\n failures += 1;\n if (failures > 5) {\n this.finish('failed', 'Lost the connection to the call.');\n return;\n }\n }\n if (this.ended()) return;\n await new Promise((r) => setTimeout(r, Math.min(4000, 500 * 2 ** failures)));\n }\n }\n\n private onServerEvent(event: string, d: Record<string, unknown>) {\n switch (event) {\n case 'queued':\n if (this.s.phase === 'joining' || this.s.phase === 'queued') {\n this.set({ phase: 'queued', position: Number(d.position) || 1, etaSeconds: Number(d.etaSeconds) || null });\n }\n break;\n case 'ready': {\n if (typeof d.ticket === 'string' && d.ticket) this.ticket = d.ticket;\n const hold = Number(d.holdSeconds) || 0;\n if (this.s.phase !== 'ready' && this.s.phase !== 'connecting' && this.s.phase !== 'live') {\n this.set({ phase: 'ready', holdSeconds: hold, position: null, etaSeconds: null });\n this.emit('ready', { holdSeconds: hold });\n if (this.opts.autoAccept !== false) this.accept();\n } else if (this.s.phase === 'ready') {\n this.set({ holdSeconds: hold });\n }\n break;\n }\n case 'live':\n this.set({ phase: 'live', maxSeconds: Number(d.maxSeconds) || null, startedAt: this.s.startedAt ?? Date.now() - (Number(d.elapsedSeconds) || 0) * 1000 });\n break;\n case 'ended':\n this.finish((String(d.reason || 'hangup') as CallEndReason) || 'hangup', null);\n break;\n }\n }\n\n // A method, not an inline comparison: the phase changes across an await,\n // which TypeScript's narrowing cannot see.\n private ended(): boolean {\n return this.s.phase === 'ended';\n }\n\n /** Take the call now that it is this visitor's turn. */\n accept(): void {\n if (this.s.phase !== 'ready' || !this.ticket || this.ws) return;\n this.set({ phase: 'connecting' });\n const url = this.apiUrl.replace(/^http/, 'ws') + '/sdk/v1/calls/socket';\n const ws = new WebSocket(url, [`cxyz-ticket.${this.ticket}`]);\n this.ticket = null;\n ws.binaryType = 'arraybuffer';\n this.ws = ws;\n ws.onopen = () => {\n const face = this.opts.face;\n const emotion = face?.emotion?.() ?? null;\n ws.send(\n JSON.stringify({\n type: 'agent_identity',\n agent_id: this.agentId,\n skin_index: 0,\n blendshapes: !!face,\n ...(face ? { blendshape_stream: true } : {}),\n ...(face && emotion ? { face_emotion: emotion } : {}),\n }),\n );\n // This page does not gate the microphone: the server's own voice\n // detection judges every frame.\n ws.send(JSON.stringify({ type: 'mic_state', silero: 'off', denoise: false }));\n this.heartbeat = setInterval(() => this.sendJson({ type: 'heartbeat' }), HEARTBEAT_MS);\n this.set({ phase: 'live', startedAt: this.s.startedAt ?? Date.now() });\n };\n ws.onmessage = (e) => this.onSocket(e.data);\n ws.onclose = () => {\n this.ws = null;\n // The event stream says why; give it a moment before calling it ourselves.\n setTimeout(() => {\n if (this.s.phase === 'live' || this.s.phase === 'connecting') this.finish('hangup', null);\n }, 1500);\n };\n }\n\n private sendJson(o: unknown) {\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(o));\n }\n\n private onMicFrame(pcm: ArrayBuffer, level: number) {\n const ws = this.ws;\n if (!ws || ws.readyState !== WebSocket.OPEN) return;\n if (this.speakingCorr) {\n // The agent must not hear itself: while she talks the frames go up as\n // silence, unless the visitor is clearly talking over her.\n const now = performance.now();\n if (level > BARGE_IN_LEVEL) {\n this.loudSince ??= now;\n if (now - this.loudSince >= BARGE_IN_MS) {\n this.loudSince = null;\n this.interrupt();\n ws.send(pcm);\n return;\n }\n } else {\n this.loudSince = null;\n }\n ws.send(new ArrayBuffer(pcm.byteLength));\n return;\n }\n ws.send(pcm);\n }\n\n private onSocket(data: unknown) {\n if (data instanceof ArrayBuffer) {\n const p = parsePacket(data);\n if (!p || this.cancelled.has(p.corr)) return;\n if (p.kind === 3) {\n // A copy, so the receiver may keep or transfer it.\n if (this.opts.face) this.emit('face', { corr: p.corr, payload: p.payload.slice() });\n return;\n }\n if (p.kind !== 1) return;\n let player = this.players.get(p.corr);\n if (!player) {\n // A new line: whatever was playing is over.\n for (const [c, old] of this.players) {\n old.stop();\n this.players.delete(c);\n }\n const corr = p.corr;\n player = new PcmPlayer({\n sampleRate: this.sampleRates.get(corr) ?? 16_000,\n onStart: () => {\n this.speakingCorr = corr;\n this.set({ speaking: true });\n this.emit('line', { corr, event: 'audible' });\n this.sendJson({ type: 'playback_started', correlationId: corr, timestampMs: Date.now() });\n },\n onEnd: () => {\n this.players.delete(corr);\n if (this.speakingCorr === corr) this.speakingCorr = null;\n this.set({ speaking: false });\n this.emit('line', { corr, event: 'end' });\n this.sendJson({ type: 'playback_ended', correlationId: corr, timestampMs: Date.now(), reason: 'natural' });\n this.sendJson({ type: 'speech_ended' });\n },\n });\n this.players.set(corr, player);\n }\n player.enqueue(p.payload);\n if (p.final) player.end();\n return;\n }\n if (typeof data !== 'string') return;\n let o: Record<string, unknown>;\n try {\n o = JSON.parse(data);\n } catch {\n return;\n }\n if ('AgentSpeechMeta' in o) {\n const m = o.AgentSpeechMeta as { correlation_id?: string; sample_rate?: number };\n if (m?.correlation_id && m.sample_rate) this.sampleRates.set(m.correlation_id, m.sample_rate);\n return;\n }\n if ('InteractorTranscript' in o) {\n const t = o.InteractorTranscript as { correlation_id: string; text: string };\n if (t?.text) this.emit('caption', { id: `v:${t.correlation_id}`, role: 'visitor', text: t.text });\n return;\n }\n if ('AgentReplyTranscript' in o) {\n const t = o.AgentReplyTranscript as { correlation_id: string; text: string };\n if (t?.text && !this.cancelled.has(t.correlation_id)) this.emit('caption', { id: `a:${t.correlation_id}`, role: 'agent', text: t.text });\n return;\n }\n if (o.type === 'turn_cancelled' && typeof o.correlationId === 'string') {\n const cid = o.correlationId;\n this.cancelled.add(cid);\n this.players.get(cid)?.stop();\n this.players.delete(cid);\n this.emit('line', { corr: cid, event: 'end' });\n if (this.speakingCorr === cid) {\n this.speakingCorr = null;\n this.set({ speaking: false });\n }\n this.emit('captionRemoved', `a:${cid}`);\n return;\n }\n if (o.kind === 'agent_status' && typeof o.state === 'string') {\n this.set({ agentState: o.state.toLowerCase() });\n }\n }\n\n /** Stop the agent mid-sentence (the visitor wants to speak). */\n interrupt(): void {\n const corr = this.speakingCorr;\n if (!corr) return;\n const p = this.players.get(corr);\n const heardMs = Math.round(p?.playedMs() ?? 0);\n p?.stop();\n this.players.delete(corr);\n this.cancelled.add(corr);\n this.speakingCorr = null;\n this.set({ speaking: false });\n this.emit('line', { corr, event: 'end' });\n this.sendJson({ type: 'playback_ended', correlationId: corr, timestampMs: Date.now(), reason: 'interrupted' });\n this.sendJson({ type: 'interrupt', correlationId: corr, heardMs, timestampMs: Date.now() });\n }\n\n setMuted(muted: boolean): void {\n this.mic?.setMuted(muted);\n this.set({ muted });\n }\n\n /** Leave the line, or hang up. */\n async hangUp(): Promise<void> {\n const id = this.s.callId;\n const was = this.s.phase;\n this.finish(was === 'live' ? 'hangup' : 'left', null);\n if (!id) return;\n try {\n const token = await this.session.token();\n await send(this.apiUrl, `/sdk/v1/calls/${encodeURIComponent(id)}`, { method: 'DELETE', token });\n } catch {\n // The server notices a closed socket / abandoned line on its own.\n }\n }\n\n private finish(reason: CallEndReason, error: string | null) {\n if (this.s.phase === 'ended') return;\n this.eventsAbort?.abort();\n this.eventsAbort = null;\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.heartbeat = null;\n for (const p of this.players.values()) p.stop();\n this.players.clear();\n this.speakingCorr = null;\n this.mic?.stop();\n this.mic = null;\n const ws = this.ws;\n this.ws = null;\n if (ws && ws.readyState <= WebSocket.OPEN) ws.close(1000);\n this.ticket = null;\n this.set({ phase: 'ended', endReason: reason, speaking: false, holdSeconds: null, error });\n }\n}\n","import { Emitter } from './emitter.js';\nimport { CxError } from './errors.js';\nimport { readEvents, request, send } from './http.js';\nimport type { SessionManager } from './session.js';\nimport type { ChatMessage } from './types.js';\n\nexport interface ChatEvents extends Record<string, unknown> {\n /** The whole list, after any change. */\n messages: ChatMessage[];\n /** True from send until the reply is complete. */\n busy: boolean;\n error: CxError;\n}\n\nlet localSeq = 0;\nconst localId = (p: string) => `${p}_${Date.now().toString(36)}_${(localSeq++).toString(36)}`;\n\n/**\n * Text chat with the agent. History lives on the server, so it follows the\n * visitor across page loads (and, for an identified visitor, devices).\n */\nexport class Chat extends Emitter<ChatEvents> {\n private list: ChatMessage[] = [];\n private loaded = false;\n private busy = false;\n private abort: AbortController | null = null;\n\n constructor(\n private readonly apiUrl: string,\n private readonly session: SessionManager,\n ) {\n super();\n }\n\n get messages(): readonly ChatMessage[] {\n return this.list;\n }\n\n get isBusy(): boolean {\n return this.busy;\n }\n\n private publish() {\n this.list = [...this.list];\n this.emit('messages', this.list);\n }\n\n /** Load earlier messages (once; later calls return what is held). */\n async load(): Promise<readonly ChatMessage[]> {\n if (this.loaded) return this.list;\n const token = await this.session.token();\n const res = await request<{ messages: ChatMessage[] }>(this.apiUrl, '/sdk/v1/chat/messages?limit=50', { token });\n // Anything sent while the history was loading stays after it.\n const pending = this.list;\n this.list = [...(res?.messages ?? []), ...pending];\n this.loaded = true;\n this.publish();\n return this.list;\n }\n\n /**\n * Send a message; the reply streams into `messages` as it is written.\n * Resolves with the finished reply.\n */\n async send(text: string): Promise<ChatMessage> {\n const t = text.trim();\n if (!t) throw new CxError('invalid', 'Say something first.');\n if (this.busy) throw new CxError('rate_limited', 'Wait for the reply first.');\n this.setBusy(true);\n const mine: ChatMessage = { id: localId('local'), role: 'visitor', text: t, createdAt: new Date().toISOString() };\n const reply: ChatMessage = { id: localId('reply'), role: 'agent', text: '', createdAt: new Date().toISOString(), streaming: true };\n this.list.push(mine, reply);\n this.publish();\n\n this.abort = new AbortController();\n try {\n const token = await this.session.token();\n const res = await send(this.apiUrl, '/sdk/v1/chat/messages', { method: 'POST', body: { text: t }, token, signal: this.abort.signal });\n let finished: ChatMessage | null = null;\n let failure: string | null = null;\n await readEvents(\n res,\n ({ event, data }) => {\n const d = data as Record<string, unknown>;\n if (event === 'delta' && typeof d?.text === 'string') {\n reply.text += d.text;\n this.publish();\n } else if (event === 'done') {\n const next = Array.isArray(d.suggestions) ? d.suggestions.filter((q): q is string => typeof q === 'string' && q.trim() !== '') : [];\n finished = {\n id: String(d.id),\n role: 'agent',\n text: String(d.text ?? reply.text),\n createdAt: String(d.createdAt ?? reply.createdAt),\n ...(next.length ? { suggestions: next } : {}),\n ...(d.askDetails && typeof d.askDetails === 'object' ? { askDetails: d.askDetails as ChatMessage['askDetails'] } : {}),\n ...(d.detailsForm && typeof d.detailsForm === 'object' ? { detailsForm: d.detailsForm as ChatMessage['detailsForm'] } : {}),\n };\n } else if (event === 'error') {\n failure = typeof d?.message === 'string' ? d.message : 'Something went wrong.';\n }\n },\n this.abort.signal,\n );\n if (failure || !finished) throw new CxError('unknown', failure ?? 'The reply was cut off. Try again.');\n const done: ChatMessage = finished;\n this.replace(reply.id, done);\n return done;\n } catch (e) {\n const err = e instanceof CxError ? e : new CxError('network', 'The reply was cut off. Try again.');\n this.list = this.list.filter((m) => m.id !== reply.id);\n const idx = this.list.findIndex((m) => m.id === mine.id);\n // A refusal the server explained (a daily limit, a slow-down) is shown as\n // it was said; anything else is the generic \"not sent\".\n if (idx !== -1) this.list[idx] = { ...mine, failed: true, ...(err.status === 429 ? { error: err.message } : {}) };\n this.publish();\n if ((e as Error)?.name !== 'AbortError') this.emit('error', err);\n throw err;\n } finally {\n this.abort = null;\n this.setBusy(false);\n }\n }\n\n /**\n * Start a new conversation. The old one is archived by the server, not\n * deleted; the visitor simply starts fresh.\n */\n async reset(): Promise<void> {\n this.stop();\n const token = await this.session.token();\n await send(this.apiUrl, '/sdk/v1/chat/messages', { method: 'DELETE', token });\n this.list = [];\n this.loaded = true;\n this.publish();\n }\n\n /** Send a failed message again. */\n retry(id: string): Promise<ChatMessage> {\n const m = this.list.find((x) => x.id === id && x.failed);\n if (!m) throw new CxError('not_found', 'Nothing to retry.');\n this.list = this.list.filter((x) => x.id !== id);\n this.publish();\n return this.send(m.text);\n }\n\n /** Stop listening to a reply in progress (the server still finishes it). */\n stop(): void {\n this.abort?.abort();\n }\n\n private replace(id: string, next: ChatMessage) {\n const i = this.list.findIndex((m) => m.id === id);\n if (i !== -1) this.list[i] = next;\n this.publish();\n }\n\n private setBusy(b: boolean) {\n this.busy = b;\n this.emit('busy', b);\n }\n}\n","import { CxError } from './errors.js';\nimport { request } from './http.js';\nimport type { SessionInfo } from './types.js';\n\n/** Where the SDK may remember this browser's anonymous visitor id. */\nexport interface VisitorStore {\n get(key: string): string | null;\n set(key: string, value: string): void;\n}\n\nexport const memoryStore = (): VisitorStore => {\n const m = new Map<string, string>();\n return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v) };\n};\n\nexport const localStore = (): VisitorStore => ({\n get(k) {\n try {\n return globalThis.localStorage?.getItem(k) ?? null;\n } catch {\n return null;\n }\n },\n set(k, v) {\n try {\n globalThis.localStorage?.setItem(k, v);\n } catch {\n // private mode / blocked storage: the visitor is simply new each time\n }\n },\n});\n\nexport interface SessionSource {\n apiUrl: string;\n agentId?: string;\n /** Browser path: a publishable key, exchanged from this page's origin. */\n publishableKey?: string;\n /**\n * Server path: your backend mints the session with a secret key (an\n * identified visitor) and hands the token to the page. Called again when\n * the session is about to run out.\n */\n getSessionToken?: () => Promise<string | SessionInfo>;\n store: VisitorStore;\n}\n\n/** Renew this long before expiry. */\nconst RENEW_EARLY_S = 60;\n\n/**\n * Holds the current session, renews it before it runs out, and never runs\n * two renewals at once.\n */\nexport class SessionManager {\n private current: SessionInfo | null = null;\n private inflight: Promise<SessionInfo> | null = null;\n\n constructor(private readonly src: SessionSource) {\n if (!src.publishableKey && !src.getSessionToken) {\n throw new CxError('invalid', 'Pass a publishableKey, or getSessionToken for sessions your server mints.');\n }\n }\n\n private visitorKey(): string {\n // Per key, so two brands on one domain never share a visitor.\n const k = this.src.publishableKey ?? 'server';\n return `cxyz:visitor:${k.slice(-12)}`;\n }\n\n get info(): SessionInfo | null {\n return this.current;\n }\n\n /** A token valid for at least the next minute. */\n async token(): Promise<string> {\n const now = Date.now() / 1000;\n if (this.current && this.current.expiresAt - RENEW_EARLY_S > now) return this.current.token;\n return (await this.refresh()).token;\n }\n\n refresh(): Promise<SessionInfo> {\n this.inflight ??= this.mint().finally(() => {\n this.inflight = null;\n });\n return this.inflight;\n }\n\n private async mint(): Promise<SessionInfo> {\n let info: SessionInfo;\n if (this.src.getSessionToken) {\n const got = await this.src.getSessionToken();\n if (typeof got === 'string') {\n // A bare token: ask the server what it unlocks.\n info = await this.describe(got);\n } else {\n info = got;\n }\n } else {\n const visitorId = this.src.store.get(this.visitorKey()) ?? undefined;\n info = await request<SessionInfo>(this.src.apiUrl, '/sdk/v1/sessions', {\n method: 'POST',\n body: { publishableKey: this.src.publishableKey, agentId: this.src.agentId, visitorId },\n });\n this.src.store.set(this.visitorKey(), info.visitorId);\n }\n this.current = info;\n return info;\n }\n\n /** The session behind a token minted elsewhere (`getSessionToken` returned a string). */\n private async describe(token: string): Promise<SessionInfo> {\n const info = await request<SessionInfo>(this.src.apiUrl, '/sdk/v1/session', { token });\n return { ...info, token };\n }\n}\n","import { Call, type CallOptions } from './call.js';\nimport { Chat } from './chat.js';\nimport { Emitter } from './emitter.js';\nimport { CxError } from './errors.js';\nimport { request } from './http.js';\nimport { localStore, memoryStore, SessionManager, type VisitorStore } from './session.js';\nimport type { AgentCard, ContactDetails, Features, Opening, SessionInfo } from './types.js';\n\nexport const DEFAULT_API_URL = 'https://api.character.xyz';\n\nexport interface InitOptions {\n /** `cxyz_pk_live_…` — safe in the page; works only from the key's allowed sites. */\n publishableKey?: string;\n /**\n * For signed-in visitors: return a session your server minted with its\n * secret key (see `@characterxyz/server`). Called again before expiry.\n */\n getSessionToken?: () => Promise<string | SessionInfo>;\n /** Which of the key's agents to talk to. Defaults to the key's first. */\n agentId?: string;\n /** Override the API (staging, local development). */\n apiUrl?: string;\n /** Remember the anonymous visitor across visits (default) or not at all. */\n storage?: 'local' | 'memory' | VisitorStore;\n}\n\nexport interface ClientEvents extends Record<string, unknown> {\n /** A call started or ended; the widget swaps its view on this. */\n call: Call | null;\n error: CxError;\n}\n\n/**\n * The headless SDK. `await CharacterXYZ.init({ publishableKey })`, then use\n * `chat` and `startCall()`. Everything the widget does goes through here, so\n * a brand can build its own UI on the same calls.\n */\nexport class CharacterXYZ extends Emitter<ClientEvents> {\n readonly chat: Chat;\n private currentCall: Call | null = null;\n private destroyed = false;\n\n private constructor(\n readonly apiUrl: string,\n private readonly session: SessionManager,\n private info: SessionInfo,\n ) {\n super();\n this.chat = new Chat(apiUrl, session);\n }\n\n static async init(opts: InitOptions): Promise<CharacterXYZ> {\n const apiUrl = (opts.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, '');\n if (opts.publishableKey && /^cxyz_sk_/.test(opts.publishableKey)) {\n // A secret key in a page is a leak. Refuse loudly, before it is sent anywhere.\n throw new CxError('invalid', 'That is a SECRET key. Never put it in a web page: use a publishable key (cxyz_pk_…). Revoke the secret key now.');\n }\n const store = opts.storage === 'memory' ? memoryStore() : opts.storage && typeof opts.storage === 'object' ? opts.storage : localStore();\n const session = new SessionManager({ apiUrl, agentId: opts.agentId, publishableKey: opts.publishableKey, getSessionToken: opts.getSessionToken, store });\n const info = await session.refresh();\n return new CharacterXYZ(apiUrl, session, info);\n }\n\n get agent(): AgentCard {\n return (this.session.info ?? this.info).agent;\n }\n\n get features(): Features {\n return (this.session.info ?? this.info).features;\n }\n\n get appearance(): Record<string, unknown> {\n return (this.session.info ?? this.info).appearance ?? {};\n }\n\n get visitorId(): string {\n return (this.session.info ?? this.info).visitorId;\n }\n\n get mode(): 'live' | 'test' {\n return (this.session.info ?? this.info).mode;\n }\n\n /** The call in progress (queued, ready or live), if any. */\n get call(): Call | null {\n return this.currentCall && this.currentCall.state.phase !== 'ended' ? this.currentCall : null;\n }\n\n /**\n * The worn video character's full render data (the public projection the\n * app's Stage reads), for a UI that draws the face — the widget hands it to\n * the app's renderer. Null when the agent wears none.\n */\n async videoAvatar(): Promise<Record<string, unknown> | null> {\n const token = await this.session.token();\n return request<Record<string, unknown> | null>(this.apiUrl, '/sdk/v1/agent/video-avatar', { token });\n }\n\n private openingP: Promise<Opening | null> | null = null;\n\n /**\n * How the agent opens the conversation here — her greeting, a welcome-back\n * line, a teaser and likely first questions — written by her and cached by\n * the server. Fetched once per page; null if it could not be had.\n */\n opening(refresh = false): Promise<Opening | null> {\n if (refresh) this.openingP = null;\n this.openingP ??= this.session\n .token()\n .then((token) => request<Opening>(this.apiUrl, '/sdk/v1/agent/opening', { token }))\n .catch(() => null);\n return this.openingP;\n }\n\n /**\n * Leave the visitor's details for the brand's team. Sending is the consent\n * (the card says so). Fails `invalid` with `fields` naming each problem.\n */\n async sendDetails(details: ContactDetails): Promise<void> {\n const token = await this.session.token();\n const page = typeof location !== 'undefined' ? location.href : undefined;\n await request(this.apiUrl, '/sdk/v1/lead', { token, body: { ...details, consent: true, ...(page ? { page } : {}) } });\n }\n\n /** \"Not now\" on the details card: she will not ask again in this conversation. */\n async declineDetails(): Promise<void> {\n const token = await this.session.token();\n await request(this.apiUrl, '/sdk/v1/lead/decline', { token, method: 'POST', body: {} });\n }\n\n /** Start a voice call. Call from a click: it needs the microphone and audio unlocked. */\n async startCall(opts: CallOptions = {}): Promise<Call> {\n if (this.destroyed) throw new CxError('invalid', 'This client was destroyed.');\n if (!this.features.call) throw new CxError('forbidden', 'Calls are not available on this site.');\n if (this.call) return this.call;\n const call = new Call(this.apiUrl, this.session, this.agent.id, opts);\n this.currentCall = call;\n call.on('state', (s) => {\n if (s.phase === 'ended' && this.currentCall === call) this.emit('call', null);\n });\n call.on('error', (e) => this.emit('error', e));\n this.emit('call', call);\n await call.start();\n return call;\n }\n\n destroy(): void {\n this.destroyed = true;\n void this.currentCall?.hangUp();\n this.chat.stop();\n this.chat.clear();\n this.clear();\n }\n}\n","/**\n * `@characterxyz/web` — Character XYZ on any web page, headless.\n *\n * ```ts\n * import { CharacterXYZ } from '@characterxyz/web';\n *\n * const cx = await CharacterXYZ.init({ publishableKey: 'cxyz_pk_live_…' });\n * cx.chat.on('messages', render);\n * await cx.chat.send('Hi!');\n *\n * button.onclick = async () => {\n * const call = await cx.startCall();\n * call.on('state', (s) => show(s.phase, s.position));\n * };\n * ```\n *\n * The ready-made widget is `@characterxyz/widget`; this package is what it\n * is built on, for brands who want their own UI.\n */\nexport { CharacterXYZ, DEFAULT_API_URL, type InitOptions, type ClientEvents } from './client.js';\nexport { Chat, type ChatEvents } from './chat.js';\nexport { Call, type CallEvents, type CallOptions } from './call.js';\nexport { CxError, type CxErrorCode } from './errors.js';\nexport { Emitter } from './emitter.js';\nexport type { VisitorStore } from './session.js';\nexport type {\n AgentCard,\n CallEndReason,\n CallPhase,\n CallState,\n Caption,\n ChatMessage,\n ContactDetails,\n DetailsForm,\n Features,\n Opening,\n SessionInfo,\n VideoCharacter,\n VideoClip,\n} from './types.js';\nexport const VERSION = '0.3.0';\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {import('./index').ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tif (node && node.parentNode) node.parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n","import { slice } from './util';\nimport options from './options';\nimport { NULL, UNDEFINED } from './constants';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array<import('.').ComponentChildren>} [children] The children of the\n * virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != NULL) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === UNDEFINED) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, NULL);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {import('./internal').VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: NULL,\n\t\t_parent: NULL,\n\t\t_depth: 0,\n\t\t_dom: NULL,\n\t\t_component: NULL,\n\t\tconstructor: UNDEFINED,\n\t\t_original: original == NULL ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == NULL && options.vnode != NULL) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: NULL };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != NULL && vnode.constructor === UNDEFINED;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE, NULL } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != NULL && this._nextState != this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == NULL) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == NULL) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: NULL;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != NULL && sibling._dom != NULL) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tif (component._parentDom && component._dirty) {\n\t\tlet oldVNode = component._vnode,\n\t\t\toldDom = oldVNode._dom,\n\t\t\tcommitQueue = [],\n\t\t\trefQueue = [],\n\t\t\tnewVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL,\n\t\t\tcommitQueue,\n\t\t\toldDom == NULL ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\t\toldVNode._dom = oldVNode._parent = null;\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != NULL && vnode._component != NULL) {\n\t\tvnode._dom = vnode._component.base = NULL;\n\t\tvnode._children.some(child => {\n\t\t\tif (child != NULL && child._dom != NULL) {\n\t\t\t\treturn (vnode._dom = vnode._component.base = child._dom);\n\t\t\t}\n\t\t});\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array<import('./internal').Component>}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce != options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\ttry {\n\t\tlet c,\n\t\t\tl = 1;\n\n\t\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t\t// process() calls from getting scheduled while `queue` is still being consumed.\n\t\twhile (rerenderQueue.length) {\n\t\t\t// Keep the rerender queue sorted by (depth, insertion order). The queue\n\t\t\t// will initially be sorted on the first iteration only if it has more than 1 item.\n\t\t\t//\n\t\t\t// New items can be added to the queue e.g. when rerendering a provider, so we want to\n\t\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t\t// single pass\n\t\t\tif (rerenderQueue.length > l) {\n\t\t\t\trerenderQueue.sort(depthSort);\n\t\t\t}\n\n\t\t\tc = rerenderQueue.shift();\n\t\t\tl = rerenderQueue.length;\n\n\t\t\trenderComponent(c);\n\t\t}\n\t} finally {\n\t\trerenderQueue.length = process._rerenderCount = 0;\n\t}\n}\n\nprocess._rerenderCount = 0;\n","import { IS_NON_DIMENSIONAL, NULL, SVG_NAMESPACE } from '../constants';\nimport options from '../options';\n\n// Per-instance unique key for event clock stamps. Each Preact copy on the page\n// gets its own random suffix so that `_dispatched` / `_attached` properties on\n// shared event objects and handler functions cannot collide across instances.\n// ~1 in 60M collision odds - if you have that many praect versions on the page,\n// you deserve some weird bugs.\n// In 11 we can replace this with a\n// Symbol\nlet _id = Math.random().toString(8),\n\tEVENT_DISPATCHED = '__d' + _id,\n\tEVENT_ATTACHED = '__a' + _id;\n\nfunction setStyle(style, key, value) {\n\tif (key[0] == '-') {\n\t\tstyle.setProperty(key, value == NULL ? '' : value);\n\t} else if (value == NULL) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\nconst CAPTURE_REGEX = /(PointerCapture)$|Capture$/i;\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name == 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] != oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] == 'o' && name[1] == 'n') {\n\t\tuseCapture = name != (name = name.replace(CAPTURE_REGEX, '$1'));\n\t\tconst lowerCaseName = name.toLowerCase();\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (lowerCaseName in dom || name == 'onFocusOut' || name == 'onFocusIn')\n\t\t\tname = lowerCaseName.slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue[EVENT_ATTACHED] = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue[EVENT_ATTACHED] = oldValue[EVENT_ATTACHED];\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == SVG_NAMESPACE) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == NULL ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != NULL && (value !== false || name[4] == '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {import('../internal').PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e[EVENT_DISPATCHED] == NULL) {\n\t\t\t\te[EVENT_DISPATCHED] = eventClock++;\n\n\t\t\t\t// When `e[EVENT_DISPATCHED]` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e[EVENT_DISPATCHED] < eventHandler[EVENT_ATTACHED]) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n","import { enqueueRender } from './component';\nimport { NULL } from './constants';\n\nexport let i = 0;\n\nexport function createContext(defaultValue) {\n\tfunction Context(props) {\n\t\tif (!this.getChildContext) {\n\t\t\t/** @type {Set<import('./internal').Component> | null} */\n\t\t\tlet subs = new Set();\n\t\t\tlet ctx = {};\n\t\t\tctx[Context._id] = this;\n\n\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\tsubs = NULL;\n\t\t\t};\n\n\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t// @ts-expect-error even\n\t\t\t\tif (this.props.value != _props.value) {\n\t\t\t\t\tsubs.forEach(c => {\n\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.sub = c => {\n\t\t\t\tsubs.add(c);\n\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\tif (subs) {\n\t\t\t\t\t\tsubs.delete(c);\n\t\t\t\t\t}\n\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn props.children;\n\t}\n\n\tContext._id = '__cC' + i++;\n\tContext._defaultValue = defaultValue;\n\n\t/** @type {import('./internal').FunctionComponent} */\n\tContext.Consumer = (props, contextValue) => {\n\t\treturn props.children(contextValue);\n\t};\n\n\t// we could also get rid of _contextRef entirely\n\tContext.Provider =\n\t\tContext._contextRef =\n\t\tContext.Consumer.contextType =\n\t\t\tContext;\n\n\treturn Context;\n}\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport {\n\tEMPTY_OBJ,\n\tEMPTY_ARR,\n\tINSERT_VNODE,\n\tMATCHED,\n\tUNDEFINED,\n\tNULL\n} from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\toldDom = constructNewChildrenArray(\n\t\tnewParentVNode,\n\t\trenderResult,\n\t\toldChildren,\n\t\toldDom,\n\t\tnewChildrenLength\n\t);\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (childVNode == NULL) continue;\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\toldVNode =\n\t\t\t(childVNode._index != -1 && oldChildren[childVNode._index]) || EMPTY_OBJ;\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tlet result = diff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, NULL, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == NULL && newDom != NULL) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tif (childVNode._flags & INSERT_VNODE) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom);\n\n\t\t\t// When a matched VNode is physically moved via INSERT_VNODE, its old\n\t\t\t// _dom pointer becomes a stale positional reference. Clear it so that\n\t\t\t// getDomSibling (called from nested diffs) won't return this stale\n\t\t\t// reference and mis-place subsequent DOM nodes. See #5065.\n\t\t\tif (oldVNode._dom) {\n\t\t\t\toldVNode._dom = NULL;\n\t\t\t}\n\t\t} else if (typeof childVNode.type == 'function' && result !== UNDEFINED) {\n\t\t\toldDom = result;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(\n\tnewParentVNode,\n\trenderResult,\n\toldChildren,\n\toldDom,\n\tnewChildrenLength\n) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = new Array(newChildrenLength);\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == NULL ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tnewParentVNode._children[i] = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t// If this newVNode is being reused (e.g. <div>{reuse}{reuse}</div>) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tNULL,\n\t\t\t\tchildVNode,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse = <div />\n\t\t\t// <div>{reuse}<span />{reuse}</div>\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : NULL,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tnewParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tconst matchingIndex = (childVNode._index = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t));\n\n\t\toldVNode = NULL;\n\t\tif (matchingIndex != -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original == null\n\t\tconst isMounting = oldVNode == NULL || oldVNode._original == NULL;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\t// When the array of children is growing we need to decrease the skew\n\t\t\t\t// as we are adding a new element to the array.\n\t\t\t\t// Example:\n\t\t\t\t// [1, 2, 3] --> [0, 1, 2, 3]\n\t\t\t\t// oldChildren newChildren\n\t\t\t\t//\n\t\t\t\t// The new element is at index 0, so our skew is 0,\n\t\t\t\t// we need to decrease the skew as we are adding a new element.\n\t\t\t\t// The decrease will cause us to compare the element at position 1\n\t\t\t\t// with value 1 with the element at position 0 with value 0.\n\t\t\t\t//\n\t\t\t\t// A linear concept is applied when the array is shrinking,\n\t\t\t\t// if the length is unchanged we can assume that no skew\n\t\t\t\t// changes are needed.\n\t\t\t\tif (newChildrenLength > oldChildrenLength) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else if (newChildrenLength < oldChildrenLength) {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex != skewedIndex) {\n\t\t\t// When we move elements around i.e. [0, 1, 2] --> [1, 0, 2]\n\t\t\t// --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0\n\t\t\t// we set the skew to 1 as we found an offset.\n\t\t\t// --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1\n\t\t\t// this makes us increase the skew again.\n\t\t\t// --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2\n\t\t\t//\n\t\t\t// this becomes an optimization question where currently we see a 1 element offset as an insertion\n\t\t\t// or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2]\n\t\t\t// while a more than 1 offset we see as a swap.\n\t\t\t// We could probably build heuristics for having an optimized course of action here as well, but\n\t\t\t// might go at the cost of some bytes.\n\t\t\t//\n\t\t\t// If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have\n\t\t\t// only the first item be a re-scouting and all the others fall in their skewed counter-part.\n\t\t\t// We could also further optimize for swaps\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else {\n\t\t\t\tif (matchingIndex > skewedIndex) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\n\t\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t\t// match the new skew index (i + new skew)\n\t\t\t\t// In the former two branches we know that it matches after skewing\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) {\n\t\t\t\tif (oldVNode._dom == oldDom) {\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (oldDom && parentVNode.type && !oldDom.parentNode) {\n\t\t\toldDom = getDomSibling(parentVNode);\n\t\t}\n\t\toldDom = parentDom.insertBefore(parentVNode._dom, oldDom || NULL);\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != NULL && oldDom.nodeType == 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == NULL || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet oldVNode = oldChildren[skewedIndex];\n\tconst matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0;\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\t//\n\t// If there is an unkeyed functional VNode, that isn't a built-in like our Fragment,\n\t// we should not search as we risk re-using state of an unrelated VNode. (reverted for now)\n\tlet shouldSearch =\n\t\t// (typeof type != 'function' || type === Fragment || key) &&\n\t\tremainingOldChildren > (matched ? 1 : 0);\n\n\tif (\n\t\t(oldVNode === NULL && key == null) ||\n\t\t(matched && key == oldVNode.key && type == oldVNode.type)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\tlet x = skewedIndex - 1;\n\t\tlet y = skewedIndex + 1;\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tconst childIndex = x >= 0 ? x-- : y++;\n\t\t\toldVNode = oldChildren[childIndex];\n\t\t\tif (\n\t\t\t\toldVNode != NULL &&\n\t\t\t\t(oldVNode._flags & MATCHED) == 0 &&\n\t\t\t\tkey == oldVNode.key &&\n\t\t\t\ttype == oldVNode.type\n\t\t\t) {\n\t\t\t\treturn childIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n","import {\n\tEMPTY_ARR,\n\tEMPTY_OBJ,\n\tMATH_NAMESPACE,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tNULL,\n\tRESET_MODE,\n\tSVG_NAMESPACE,\n\tUNDEFINED,\n\tXHTML_NAMESPACE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * @template {any} T\n * @typedef {import('../internal').Ref<T>} Ref<T>\n */\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== UNDEFINED) return NULL;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\tlet oldCommitQueueLength = commitQueue.length;\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent = newType.prototype && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == NULL) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != NULL) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tc.componentWillMount != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tnewVNode._original == oldVNode._original ||\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != NULL &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original != oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.some(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tEMPTY_ARR.push.apply(c._renderCallbacks, c._stateCallbacks);\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Skip over the retained subtree without traversing it; the\n\t\t\t\t\t// `result` branch in diffChildren picks this up as the next\n\t\t\t\t\t// oldDom.\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != NULL) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tEMPTY_ARR.push.apply(c._renderCallbacks, c._stateCallbacks);\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != NULL) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet renderResult =\n\t\t\t\ttmp != NULL && tmp.type === Fragment && tmp.key == NULL\n\t\t\t\t\t? cloneNode(tmp.props.children)\n\t\t\t\t\t: tmp;\n\n\t\t\toldDom = diffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = NULL;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// We remove any componentDidMount, ...\n\t\t\t// that have been invalidated by us\n\t\t\t// intercepting the error.\n\t\t\tcommitQueue.length = oldCommitQueueLength;\n\t\t\tnewVNode._original = NULL;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != NULL) {\n\t\t\t\tif (e.then) {\n\t\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t\t: MODE_SUSPENDED;\n\n\t\t\t\t\twhile (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) {\n\t\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\t} else if (excessDomChildren != NULL) {\n\t\t\t\t\tfor (let i = excessDomChildren.length; i--; ) {\n\t\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t}\n\n\t\t\tif (newVNode._children == NULL) {\n\t\t\t\tnewVNode._children = oldVNode._children || [];\n\t\t\t}\n\n\t\t\tif (!e.then) markAsForce(newVNode);\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == NULL &&\n\t\tnewVNode._original == oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\toldDom = newVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n\n\treturn newVNode._flags & MODE_SUSPENDED ? undefined : oldDom;\n}\n\nfunction markAsForce(vnode) {\n\tif (vnode) {\n\t\tif (vnode._component) vnode._component._force = true;\n\t\tif (vnode._children) vnode._children.some(markAsForce);\n\t}\n}\n\n/**\n * @param {Array<Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\nfunction cloneNode(node) {\n\tif (typeof node != 'object' || node == NULL || node._depth > 0) {\n\t\treturn node;\n\t}\n\n\tif (isArray(node)) {\n\t\treturn node.map(cloneNode);\n\t}\n\n\tif (node.constructor !== UNDEFINED) return null;\n\n\treturn assign({}, node);\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props || EMPTY_OBJ;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType == 'svg') namespace = SVG_NAMESPACE;\n\telse if (nodeType == 'math') namespace = MATH_NAMESPACE;\n\telse if (!namespace) namespace = XHTML_NAMESPACE;\n\n\tif (excessDomChildren != NULL) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value == !!nodeType &&\n\t\t\t\t(nodeType ? value.localName == nodeType : value.nodeType == 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == NULL) {\n\t\tif (nodeType == NULL) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tif (isHydrating) {\n\t\t\tif (options._hydrationMismatch)\n\t\t\t\toptions._hydrationMismatch(newVNode, excessDomChildren);\n\t\t\tisHydrating = false;\n\t\t}\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = NULL;\n\t}\n\n\tif (nodeType == NULL) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data != newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren =\n\t\t\tnodeType == 'textarea' && newProps.defaultValue != NULL\n\t\t\t\t? NULL\n\t\t\t\t: excessDomChildren && slice.call(dom.childNodes);\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != NULL) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (\n\t\t\t\ti != 'children' &&\n\t\t\t\t!(i in newProps) &&\n\t\t\t\t!(i == 'value' && 'defaultValue' in newProps) &&\n\t\t\t\t!(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, NULL, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnewVNode.type == 'template' ? dom.content : dom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating || nodeType == 'textarea') {\n\t\t\ti = 'value';\n\t\t\tif (nodeType == 'progress' && inputValue == NULL) {\n\t\t\t\tdom.removeAttribute('value');\n\t\t\t} else if (\n\t\t\t\tinputValue != UNDEFINED &&\n\t\t\t\t// #2756 For the <progress>-element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType == 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix <select> value not being updated.\n\t\t\t\t\t// To avoid a stale select value we need to set the option.value\n\t\t\t\t\t// again, which triggers IE11 to re-evaluate the select value\n\t\t\t\t\t(nodeType == 'option' && inputValue != oldProps[i]))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, inputValue, oldProps[i], namespace);\n\t\t\t}\n\n\t\t\ti = 'checked';\n\t\t\tif (checked != UNDEFINED && checked != dom[i]) {\n\t\t\t\tsetProperty(dom, i, checked, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {Ref<any> & { _unmount?: unknown }} ref\n * @param {any} value\n * @param {VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') {\n\t\t\tlet hasRefUnmount = typeof ref._unmount == 'function';\n\t\t\tif (hasRefUnmount) {\n\t\t\t\t// @ts-ignore TS doesn't like moving narrowing checks into variables\n\t\t\t\tref._unmount();\n\t\t\t}\n\n\t\t\tif (!hasRefUnmount || value != NULL) {\n\t\t\t\t// Store the cleanup function on the function\n\t\t\t\t// instance object itself to avoid shape\n\t\t\t\t// transitioning vnode\n\t\t\t\tref._unmount = ref(value);\n\t\t\t}\n\t\t} else ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {VNode} vnode The virtual node to unmount\n * @param {VNode} parentVNode The parent of the VNode that initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current == vnode._dom) {\n\t\t\tapplyRef(r, NULL, parentVNode);\n\t\t}\n\t}\n\n\tif ((r = vnode._component) != NULL) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = r._globalContext = NULL;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) {\n\t\t\t\tunmount(\n\t\t\t\t\tr[i],\n\t\t\t\t\tparentVNode,\n\t\t\t\t\tskipRemove || typeof vnode.type != 'function'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!skipRemove) {\n\t\tremoveNode(vnode._dom);\n\t}\n\n\tvnode._component = vnode._parent = vnode._dom = UNDEFINED;\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, NULL } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\nimport { slice } from './util';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\t// https://github.com/preactjs/preact/issues/3794\n\tif (parentDom == document) {\n\t\tparentDom = document.documentElement;\n\t}\n\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode == 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? NULL\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = ((!isHydrating && replaceNode) || parentDom)._children =\n\t\tcreateElement(Fragment, NULL, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [],\n\t\trefQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.namespaceURI,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t\t? NULL\n\t\t\t\t: parentDom.firstChild\n\t\t\t\t\t? slice.call(parentDom.childNodes)\n\t\t\t\t\t: NULL,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t\t? oldVNode._dom\n\t\t\t\t: parentDom.firstChild,\n\t\tisHydrating,\n\t\trefQueue\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode, refQueue);\n\n\t// The live children are tracked on _children after diffing.\n\tvnode.props.children = NULL;\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","import { assign, slice } from './util';\nimport { createVNode } from './create-element';\nimport { NULL, UNDEFINED } from './constants';\n\n/**\n * Clones the given VNode, optionally adding attributes/props and replacing its\n * children.\n * @param {import('./internal').VNode} vnode The virtual DOM element to clone\n * @param {object} props Attributes/props to add when cloning\n * @param {Array<import('./internal').ComponentChildren>} rest Any additional arguments will be used\n * as replacement children.\n * @returns {import('./internal').VNode}\n */\nexport function cloneElement(vnode, props, children) {\n\tlet normalizedProps = assign({}, vnode.props),\n\t\tkey,\n\t\tref,\n\t\ti;\n\n\tlet defaultProps;\n\n\tif (vnode.type && vnode.type.defaultProps) {\n\t\tdefaultProps = vnode.type.defaultProps;\n\t}\n\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse if (props[i] === UNDEFINED && defaultProps != UNDEFINED) {\n\t\t\tnormalizedProps[i] = defaultProps[i];\n\t\t} else {\n\t\t\tnormalizedProps[i] = props[i];\n\t\t}\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\treturn createVNode(\n\t\tvnode.type,\n\t\tnormalizedProps,\n\t\tkey || vnode.key,\n\t\tref || vnode.ref,\n\t\tNULL\n\t);\n}\n","import { NULL } from '../constants';\n\n/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except\n * for unmounting when this parameter is the highest parent that was being\n * unmounted)\n * @param {import('../internal').VNode} [oldVNode]\n * @param {import('../internal').ErrorInfo} [errorInfo]\n */\nexport function _catchError(error, vnode, oldVNode, errorInfo) {\n\t/** @type {import('../internal').Component} */\n\tlet component,\n\t\t/** @type {import('../internal').ComponentType} */\n\t\tctor,\n\t\t/** @type {boolean} */\n\t\thandled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != NULL) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != NULL) {\n\t\t\t\t\tcomponent.componentDidCatch(error, errorInfo || {});\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { options as _options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n\n/** @type {import('./internal').Component} */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array<import('./internal').Component>} */\nlet afterPaintEffects = [];\n\n// Cast to use internal Options type\nconst options = /** @type {import('./internal').Options} */ (_options);\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\nlet oldRoot = options._root;\n\n// We take the minimum timeout for requestAnimationFrame to ensure that\n// the callback is invoked after the next frame. 35ms is based on a 30hz\n// refresh rate, which is the minimum rate for a smooth user experience.\nconst RAF_TIMEOUT = 35;\nlet prevRaf;\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._root = (vnode, parentDom) => {\n\tif (vnode && parentDom._children && parentDom._children._mask) {\n\t\tvnode._mask = parentDom._children._mask;\n\t}\n\n\tif (oldRoot) oldRoot(vnode, parentDom);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\tif (previousComponent === currentComponent) {\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentComponent._renderCallbacks = [];\n\t\t\thooks._list.some(hookItem => {\n\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t}\n\t\t\t\thookItem._pendingArgs = hookItem._nextValue = undefined;\n\t\t\t});\n\t\t} else {\n\t\t\thooks._pendingEffects.some(invokeCleanup);\n\t\t\thooks._pendingEffects.some(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentIndex = 0;\n\t\t}\n\t}\n\tpreviousComponent = currentComponent;\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tif (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));\n\t\tc.__hooks._list.some(hookItem => {\n\t\t\tif (hookItem._pendingArgs) {\n\t\t\t\thookItem._args = hookItem._pendingArgs;\n\t\t\t\thookItem._pendingArgs = undefined;\n\t\t\t}\n\t\t});\n\t}\n\tpreviousComponent = currentComponent = null;\n};\n\n// TODO: Improve typing of commitQueue parameter\n/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.some(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tlet hasErrored;\n\t\tc.__hooks._list.some(s => {\n\t\t\ttry {\n\t\t\t\tinvokeCleanup(s);\n\t\t\t} catch (e) {\n\t\t\t\thasErrored = e;\n\t\t\t}\n\t\t});\n\t\tc.__hooks = undefined;\n\t\tif (hasErrored) options._catchError(hasErrored, c._vnode);\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\n\treturn hooks._list[index];\n}\n\n/**\n * @template {unknown} S\n * @param {import('./index').Dispatch<import('./index').StateUpdater<S>>} [initialState]\n * @returns {[S, (state: S) => void]}\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @template {unknown} S\n * @template {unknown} A\n * @param {import('./index').Reducer<S, A>} reducer\n * @param {import('./index').Dispatch<import('./index').StateUpdater<S>>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ S, (state: S) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst currentValue = hookState._nextValue\n\t\t\t\t\t? hookState._nextValue[0]\n\t\t\t\t\t: hookState._value[0];\n\t\t\t\tconst nextValue = hookState._reducer(currentValue, action);\n\n\t\t\t\tif (currentValue !== nextValue) {\n\t\t\t\t\thookState._nextValue = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\n\t\tif (!currentComponent._hasScuFromHooks) {\n\t\t\tcurrentComponent._hasScuFromHooks = true;\n\t\t\tlet prevScu = currentComponent.shouldComponentUpdate;\n\t\t\tconst prevCWU = currentComponent.componentWillUpdate;\n\n\t\t\t// If we're dealing with a forced update `shouldComponentUpdate` will\n\t\t\t// not be called. But we use that to update the hook values, so we\n\t\t\t// need to call it.\n\t\t\tcurrentComponent.componentWillUpdate = function (p, s, c) {\n\t\t\t\tif (this._force) {\n\t\t\t\t\tlet tmp = prevScu;\n\t\t\t\t\t// Clear to avoid other sCU hooks from being called\n\t\t\t\t\tprevScu = undefined;\n\t\t\t\t\tupdateHookState(p, s, c);\n\t\t\t\t\tprevScu = tmp;\n\t\t\t\t}\n\n\t\t\t\tif (prevCWU) prevCWU.call(this, p, s, c);\n\t\t\t};\n\n\t\t\t// This SCU has the purpose of bailing out after repeated updates\n\t\t\t// to stateful hooks.\n\t\t\t// we store the next value in _nextValue[0] and keep doing that for all\n\t\t\t// state setters, if we have next states and\n\t\t\t// all next states within a component end up being equal to their original state\n\t\t\t// we are safe to bail out for this specific component.\n\t\t\t/**\n\t\t\t *\n\t\t\t * @type {import('./internal').Component[\"shouldComponentUpdate\"]}\n\t\t\t */\n\t\t\t// @ts-ignore - We don't use TS to downtranspile\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction updateHookState(p, s, c) {\n\t\t\t\tif (!hookState._component.__hooks) return true;\n\n\t\t\t\t// We check whether we have components with a nextValue set that\n\t\t\t\t// have values that aren't equal to one another this pushes\n\t\t\t\t// us to update further down the tree\n\t\t\t\tlet updatedHook = false;\n\t\t\t\tlet shouldUpdate = hookState._component.props !== p;\n\t\t\t\thookState._component.__hooks._list.some(hookItem => {\n\t\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\t\tupdatedHook = true;\n\t\t\t\t\t\tconst currentValue = hookItem._value[0];\n\t\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t\t\thookItem._nextValue = undefined;\n\t\t\t\t\t\tif (currentValue !== hookItem._value[0]) shouldUpdate = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (prevScu) {\n\t\t\t\t\tconst result = prevScu.call(this, p, s, c);\n\t\t\t\t\treturn updatedHook ? result || shouldUpdate : result;\n\t\t\t\t}\n\n\t\t\t\treturn !updatedHook || shouldUpdate;\n\t\t\t}\n\n\t\t\tcurrentComponent.shouldComponentUpdate = updateHookState;\n\t\t}\n\t}\n\n\treturn hookState._nextValue || hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\n/** @type {(initialValue: unknown) => unknown} */\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') {\n\t\t\t\tconst result = ref(createHandle());\n\t\t\t\treturn () => {\n\t\t\t\t\tref(null);\n\t\t\t\t\tif (result && typeof result == 'function') result();\n\t\t\t\t};\n\t\t\t} else if (ref) {\n\t\t\t\tref.current = createHandle();\n\t\t\t\treturn () => (ref.current = null);\n\t\t\t}\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @template {unknown} T\n * @param {() => T} factory\n * @param {unknown[]} args\n * @returns {T}\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState<T>} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {unknown[]} args\n * @returns {() => void}\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {<T>(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(\n\t\t\tformatter ? formatter(value) : /** @type {any}*/ (value)\n\t\t);\n\t}\n}\n\n/**\n * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb\n * @returns {[unknown, () => void]}\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = (err, errorInfo) => {\n\t\t\tif (state._value) state._value(err, errorInfo);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/** @type {() => string} */\nexport function useId() {\n\t/** @type {import('./internal').IdHookState} */\n\tconst state = getHookState(currentIndex++, 11);\n\tif (!state._value) {\n\t\t// Grab either the root node or the nearest async boundary node.\n\t\t/** @type {import('./internal').VNode} */\n\t\tlet root = currentComponent._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\tlet mask = root._mask || (root._mask = [0, 0]);\n\t\tstate._value = 'P' + mask[0] + '-' + mask[1]++;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tlet component;\n\twhile ((component = afterPaintEffects.shift())) {\n\t\tconst hooks = component.__hooks;\n\t\tif (!component._parentDom || !hooks) continue;\n\t\ttry {\n\t\t\thooks._pendingEffects.some(invokeCleanup);\n\t\t\thooks._pendingEffects.some(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t} catch (e) {\n\t\t\thooks._pendingEffects = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t}\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n * @returns {void}\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').HookState} hook\n * @returns {void}\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tlet cleanup = hook._cleanup;\n\tif (typeof cleanup == 'function') {\n\t\thook._cleanup = undefined;\n\t\tcleanup();\n\t}\n\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n * @returns {void}\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {unknown[]} oldArgs\n * @param {unknown[]} newArgs\n * @returns {boolean}\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\n/**\n * @template Arg\n * @param {Arg} arg\n * @param {(arg: Arg) => any} f\n * @returns {any}\n */\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n","/** \"1st\", \"2nd\", \"3rd\", \"11th\". */\nexport function ordinal(n: number): string {\n const v = n % 100;\n if (v >= 11 && v <= 13) return `${n}th`;\n switch (n % 10) {\n case 1:\n return `${n}st`;\n case 2:\n return `${n}nd`;\n case 3:\n return `${n}rd`;\n default:\n return `${n}th`;\n }\n}\n\n/** \"less than a minute\", \"about 1 min\", \"about 4 min\", \"about 1 hr\". */\nexport function eta(seconds: number | null): string {\n if (seconds == null) return '';\n if (seconds < 60) return 'less than a minute';\n const m = Math.round(seconds / 60);\n if (m < 60) return `about ${m} min`;\n return `about ${Math.round(m / 60)} hr`;\n}\n\n/** 0:07, 3:12, 1:02:03 */\nexport function clock(totalSeconds: number): string {\n const s = Math.max(0, Math.floor(totalSeconds));\n const h = Math.floor(s / 3600);\n const m = Math.floor((s % 3600) / 60);\n const ss = String(s % 60).padStart(2, '0');\n return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`;\n}\n\n/** What a visitor is told when a call could not happen or ended. */\nexport function endCopy(reason: string | null, name: string): { title: string; body: string } {\n switch (reason) {\n case 'hangup':\n return { title: 'Call ended', body: `Thanks for talking with ${name}.` };\n case 'left':\n return { title: 'You left the line', body: 'You can call again whenever you like.' };\n case 'missed':\n return { title: 'You missed your turn', body: `${name} was ready, but the call wasn't joined in time.` };\n case 'timeout':\n return { title: 'Still busy', body: `Sorry for the wait. ${name} is still on other calls. Chat is open meanwhile.` };\n case 'limit':\n return { title: 'Time is up', body: 'This call reached its time limit.' };\n case 'busy':\n return { title: 'All lines are busy', body: 'Try again in a few minutes, or keep chatting.' };\n case 'mic-denied':\n return { title: 'Microphone needed', body: 'Allow the microphone in your browser to talk, or keep chatting.' };\n case 'silence':\n return { title: 'Call ended', body: `The line was quiet for a minute, so ${name} hung up. Call again any time.` };\n case 'daily_limit':\n return { title: 'Calls are resting', body: 'Calls are done for today. Chat is open.' };\n case 'credits':\n case 'unavailable':\n return { title: 'Calls are unavailable', body: 'Calls are not available right now. Chat is open.' };\n default:\n return { title: 'The call dropped', body: 'Something interrupted the call. Try again.' };\n }\n}\n\n/**\n * Light markdown for replies: **bold**, *italic*, `code`, links, line breaks\n * and \"- \" lists. Returns tokens, never HTML, so nothing a model writes can\n * become markup.\n */\nexport type Inline = { t: 'text' | 'b' | 'i' | 'code'; v: string } | { t: 'link'; v: string; href: string };\nexport type Block = { t: 'p'; parts: Inline[] } | { t: 'ul'; items: Inline[][] };\n\nexport function inline(s: string): Inline[] {\n const out: Inline[] = [];\n const re = /(\\*\\*[^*]+\\*\\*|`[^`]+`|\\[[^\\]]+\\]\\((https?:\\/\\/[^)\\s]+)\\)|https?:\\/\\/[^\\s<>()]+[^\\s<>().,;:!?'\"]|\\*[^*\\s][^*]*\\*)/g;\n let last = 0;\n let m: RegExpExecArray | null;\n while ((m = re.exec(s))) {\n if (m.index > last) out.push({ t: 'text', v: s.slice(last, m.index) });\n const tok = m[0];\n if (tok.startsWith('**')) out.push({ t: 'b', v: tok.slice(2, -2) });\n else if (tok.startsWith('`')) out.push({ t: 'code', v: tok.slice(1, -1) });\n else if (tok.startsWith('[')) out.push({ t: 'link', v: tok.slice(1, tok.indexOf(']')), href: m[2]! });\n else if (tok.startsWith('http')) out.push({ t: 'link', v: tok, href: tok });\n else out.push({ t: 'i', v: tok.slice(1, -1) });\n last = m.index + tok.length;\n }\n if (last < s.length) out.push({ t: 'text', v: s.slice(last) });\n return out;\n}\n\nexport function blocks(text: string): Block[] {\n const out: Block[] = [];\n for (const para of text.split(/\\n{2,}/)) {\n const lines = para.split('\\n');\n if (lines.length && lines.every((l) => /^\\s*[-*•]\\s+/.test(l))) {\n out.push({ t: 'ul', items: lines.map((l) => inline(l.replace(/^\\s*[-*•]\\s+/, ''))) });\n } else {\n out.push({ t: 'p', parts: inline(para) });\n }\n }\n return out;\n}\n","import type { VideoCharacter } from '@characterxyz/web';\n\n/**\n * Where to put a full-body character so her face sits where a portrait wants\n * it. All in the media's own normalised coordinates (0..1), read from the\n * anchor still's eyes and chin.\n */\nexport interface Face {\n /** Centre of the face. */\n cx: number;\n cy: number;\n /** Eyes-to-chin, as a fraction of the media's height. */\n span: number;\n}\n\n/** Ananya-shaped default: a standing figure whose head is near the top. */\nconst FALLBACK: Face = { cx: 0.5, cy: 0.12, span: 0.06 };\n\nexport function faceOf(video: VideoCharacter | null, anchorW: number, anchorH: number): Face {\n const eyes = video?.face?.eyes;\n const chin = video?.face?.chin;\n if (!eyes || !chin || !anchorW || !anchorH) return FALLBACK;\n const ex = (eyes.left.x + eyes.right.x) / 2;\n const ey = (eyes.left.y + eyes.right.y) / 2;\n const span = (chin.y - ey) / anchorH;\n if (!(span > 0.005 && span < 0.5)) return FALLBACK;\n return { cx: ex / anchorW, cy: (ey + chin.y) / 2 / anchorH, span };\n}\n\nexport type Shot =\n | {\n /** Eyes-to-chin as a fraction of the box height. */\n faceFraction: number;\n /** Where the face centre lands in the box, 0..1. */\n at: { x: number; y: number };\n }\n /** The whole clip, its height filling the box, centred on her face — standing. */\n | { fit: 'height' };\n\n/** The corner portrait: a close-up. */\nexport const CLOSE_UP = { faceFraction: 0.26, at: { x: 0.5, y: 0.5 } } satisfies Shot;\n/** The call card: head and shoulders with room above. */\nexport const MEDIUM = { faceFraction: 0.14, at: { x: 0.5, y: 0.34 } } satisfies Shot;\n/** The launcher's half body: head to waist, her face high in the frame. */\nexport const HALF_BODY = { faceFraction: 0.16, at: { x: 0.5, y: 0.22 } } satisfies Shot;\n/** The launcher's full body: the whole figure, standing on the box's bottom edge. */\nexport const FULL_BODY = { fit: 'height' } satisfies Shot;\n\nexport interface Placement {\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\n/** Pixel placement of the media inside a `boxW`×`boxH` box. */\nexport function place(face: Face, mediaAspect: number, boxW: number, boxH: number, shot: Shot): Placement {\n if ('fit' in shot) {\n const width = boxH * mediaAspect;\n return { width, height: boxH, left: boxW / 2 - face.cx * width, top: 0 };\n }\n const height = (boxH * shot.faceFraction) / face.span;\n const width = height * mediaAspect;\n return {\n width,\n height,\n left: boxW * shot.at.x - face.cx * width,\n top: boxH * shot.at.y - face.cy * height,\n };\n}\n","/**\n * Contact details a visitor TYPED into the chat (\"sure, I'm Ginger,\n * ginger@alpha.com, 72005 80713\"), so the details card can open already filled\n * in. Nothing here sends anything: the card is still the one confirmation, with\n * the consent line on it.\n *\n * Deliberately conservative. A missed name costs the visitor one field; a wrong\n * one (\"Interested\") is worse, so a name is taken only from an explicit\n * \"I'm / my name is / this is\" and only when it looks like a name.\n */\n\nexport interface TypedContact {\n name?: string;\n email?: string;\n phone?: string;\n}\n\nconst EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/;\nconst PHONE = /\\+?\\d[\\d\\s().-]{5,}\\d/g;\nconst NAME = /\\b(?:my name is|i am|i'm|im|this is|name\\s*[:-])\\s+([A-Za-z][A-Za-z'’-]+(?:\\s+[A-Za-z][A-Za-z'’-]+)?)/i;\n// Words that follow \"I'm\" without being a name.\nconst NOT_NAMES = new Set(['interested', 'looking', 'from', 'with', 'here', 'trying', 'not', 'a', 'an', 'the', 'just', 'also', 'happy', 'keen', 'curious', 'calling', 'sure', 'fine', 'good', 'okay', 'ok']);\n\n/** What looks like contact details in `text`, or null when there is no email and no phone. */\nexport function extractContact(text: string): TypedContact | null {\n const out: TypedContact = {};\n const email = text.match(EMAIL)?.[0];\n if (email) out.email = email.replace(/[.,;:]+$/, '');\n // The first run of digits that is a plausible phone number (7–15 digits).\n for (const m of text.replace(EMAIL, ' ').matchAll(PHONE)) {\n const digits = m[0].replace(/\\D/g, '');\n if (digits.length >= 7 && digits.length <= 15) {\n out.phone = m[0].trim();\n break;\n }\n }\n if (!out.email && !out.phone) return null;\n const n = text.match(NAME)?.[1];\n if (n) {\n const words = n.split(/\\s+/).filter((w) => !NOT_NAMES.has(w.toLowerCase()));\n // Stop at the first word that is clearly not part of a name (\"Ginger and\", \"Priya here\").\n const kept: string[] = [];\n for (const w of words) {\n if (['and', 'here', 'at', 'from'].includes(w.toLowerCase())) break;\n kept.push(w);\n }\n if (kept.length && kept[0]!.length > 1) out.name = kept.map((w) => w[0]!.toUpperCase() + w.slice(1)).join(' ');\n }\n return out;\n}\n","const ENCODED_ENTITIES = /[\"&<]/;\n\n/** @param {string} str */\nexport function encodeEntities(str) {\n\t// Skip all work for strings with no entities needing encoding:\n\tif (str.length === 0 || ENCODED_ENTITIES.test(str) === false) return str;\n\n\tlet last = 0,\n\t\ti = 0,\n\t\tout = '',\n\t\tch = '';\n\n\t// Seek forward in str until the next entity char:\n\tfor (; i < str.length; i++) {\n\t\tswitch (str.charCodeAt(i)) {\n\t\t\tcase 34:\n\t\t\t\tch = '&quot;';\n\t\t\t\tbreak;\n\t\t\tcase 38:\n\t\t\t\tch = '&amp;';\n\t\t\t\tbreak;\n\t\t\tcase 60:\n\t\t\t\tch = '&lt;';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t}\n\t\t// Append skipped/buffered characters and the encoded entity:\n\t\tif (i !== last) out += str.slice(last, i);\n\t\tout += ch;\n\t\t// Start the next seek/buffer after the entity's offset:\n\t\tlast = i + 1;\n\t}\n\tif (i !== last) out += str.slice(last, i);\n\treturn out;\n}\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { options, Fragment } from 'preact';\nimport { encodeEntities } from './utils';\nimport { IS_NON_DIMENSIONAL } from '../../src/constants';\n\nlet vnodeId = 0;\n\nconst isArray = Array.isArray;\n\n/**\n * @fileoverview\n * This file exports various methods that implement Babel's \"automatic\" JSX runtime API:\n * - jsx(type, props, key)\n * - jsxs(type, props, key)\n * - jsxDEV(type, props, key, __source, __self)\n *\n * The implementation of createVNode here is optimized for performance.\n * Benchmarks: https://esbench.com/bench/5f6b54a0b4632100a7dcd2b3\n */\n\n/**\n * JSX.Element factory used by Babel's {runtime:\"automatic\"} JSX transform\n * @param {VNode['type']} type\n * @param {VNode['props']} props\n * @param {VNode['key']} [key]\n * @param {unknown} [isStaticChildren]\n * @param {unknown} [__source]\n * @param {unknown} [__self]\n */\nfunction createVNode(type, props, key, isStaticChildren, __source, __self) {\n\tif (!props) props = {};\n\t// We'll want to preserve `ref` in props to get rid of the need for\n\t// forwardRef components in the future, but that should happen via\n\t// a separate PR.\n\tlet normalizedProps = props,\n\t\tref,\n\t\ti;\n\n\tif ('ref' in normalizedProps) {\n\t\tnormalizedProps = {};\n\t\tfor (i in props) {\n\t\t\tif (i == 'ref') {\n\t\t\t\tref = props[i];\n\t\t\t} else {\n\t\t\t\tnormalizedProps[i] = props[i];\n\t\t\t}\n\t\t}\n\t}\n\n\t/** @type {VNode & { __source: any; __self: any }} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops: normalizedProps,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t_component: null,\n\t\tconstructor: undefined,\n\t\t_original: --vnodeId,\n\t\t_index: -1,\n\t\t_flags: 0,\n\t\t__source,\n\t\t__self\n\t};\n\n\t// If a Component VNode, check for and apply defaultProps.\n\t// Note: `type` is often a String, and can be `undefined` in development.\n\tif (typeof type === 'function' && (ref = type.defaultProps)) {\n\t\tfor (i in ref)\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = ref[i];\n\t\t\t}\n\t}\n\n\tif (options.vnode) options.vnode(vnode);\n\treturn vnode;\n}\n\n/**\n * Create a template vnode. This function is not expected to be\n * used directly, but rather through a precompile JSX transform\n * @param {string[]} templates\n * @param {Array<string | null | VNode>} exprs\n * @returns {VNode}\n */\nfunction jsxTemplate(templates, ...exprs) {\n\tconst vnode = createVNode(Fragment, { tpl: templates, exprs });\n\t// Bypass render to string top level Fragment optimization\n\tvnode.key = vnode._vnode;\n\treturn vnode;\n}\n\nconst JS_TO_CSS = {};\nconst CSS_REGEX = /[A-Z]/g;\n\n/**\n * Unwrap potential signals.\n * @param {*} value\n * @returns {*}\n */\nfunction normalizeAttrValue(value) {\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.valueOf === 'function'\n\t\t? value.valueOf()\n\t\t: value;\n}\n\n/**\n * Serialize an HTML attribute to a string. This function is not\n * expected to be used directly, but rather through a precompile\n * JSX transform\n * @param {string} name The attribute name\n * @param {*} value The attribute value\n * @returns {string}\n */\nfunction jsxAttr(name, value) {\n\tif (options.attr) {\n\t\tconst result = options.attr(name, value);\n\t\tif (typeof result === 'string') return result;\n\t}\n\n\tvalue = normalizeAttrValue(value);\n\n\tif (name === 'ref' || name === 'key') return '';\n\tif (name === 'style' && typeof value === 'object') {\n\t\tlet str = '';\n\t\tfor (let prop in value) {\n\t\t\tlet val = value[prop];\n\t\t\tif (val != null && val !== '') {\n\t\t\t\tconst name =\n\t\t\t\t\tprop[0] == '-'\n\t\t\t\t\t\t? prop\n\t\t\t\t\t\t: JS_TO_CSS[prop] ||\n\t\t\t\t\t\t\t(JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());\n\n\t\t\t\tlet suffix = ';';\n\t\t\t\tif (\n\t\t\t\t\ttypeof val === 'number' &&\n\t\t\t\t\t// Exclude custom-attributes\n\t\t\t\t\t!name.startsWith('--') &&\n\t\t\t\t\t!IS_NON_DIMENSIONAL.test(name)\n\t\t\t\t) {\n\t\t\t\t\tsuffix = 'px;';\n\t\t\t\t}\n\t\t\t\tstr = str + name + ':' + val + suffix;\n\t\t\t}\n\t\t}\n\t\treturn name + '=\"' + encodeEntities(str) + '\"';\n\t}\n\n\tif (\n\t\tvalue == null ||\n\t\tvalue === false ||\n\t\ttypeof value === 'function' ||\n\t\ttypeof value === 'object'\n\t) {\n\t\treturn '';\n\t} else if (value === true) return name;\n\n\treturn name + '=\"' + encodeEntities('' + value) + '\"';\n}\n\n/**\n * Escape a dynamic child passed to `jsxTemplate`. This function\n * is not expected to be used directly, but rather through a\n * precompile JSX transform\n * @param {*} value\n * @returns {string | null | VNode | Array<string | null | VNode>}\n */\nfunction jsxEscape(value) {\n\tif (\n\t\tvalue == null ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'function'\n\t) {\n\t\treturn null;\n\t}\n\n\tif (typeof value === 'object') {\n\t\t// Check for VNode\n\t\tif (value.constructor === undefined) return value;\n\n\t\tif (isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\tvalue[i] = jsxEscape(value[i]);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t}\n\n\treturn encodeEntities('' + value);\n}\n\nexport {\n\tcreateVNode as jsx,\n\tcreateVNode as jsxs,\n\tcreateVNode as jsxDEV,\n\tFragment,\n\t// precompiled JSX transform\n\tjsxTemplate,\n\tjsxAttr,\n\tjsxEscape\n};\n","/** Inline icons (24×24, stroke = currentColor), so the widget loads no assets. */\nimport type { ComponentChildren } from 'preact';\n\ntype P = { size?: number };\n\nconst svg = (size: number, children: ComponentChildren) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.9\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {children}\n </svg>\n);\n\nexport const ChatIcon = ({ size = 20 }: P) => svg(size, <path d=\"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6a.5.5 0 0 1-.8-.4V16h0A2.5 2.5 0 0 1 4 13.5z\" />);\nexport const PhoneIcon = ({ size = 20 }: P) =>\n svg(size, <path d=\"M5.2 3.5h3l1.6 4.2-2 1.4a12 12 0 0 0 7.1 7.1l1.4-2 4.2 1.6v3a1.7 1.7 0 0 1-1.8 1.7A16.6 16.6 0 0 1 3.5 5.3 1.7 1.7 0 0 1 5.2 3.5z\" />);\nexport const HangUpIcon = ({ size = 22 }: P) =>\n svg(size, <path d=\"M3 13.6c5-4.4 13-4.4 18 0l-1.7 2.6-3.6-1.3v-2.6a11 11 0 0 0-7.4 0v2.6l-3.6 1.3z\" />);\nexport const MicIcon = ({ size = 20 }: P) =>\n svg(\n size,\n <>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\" />\n </>,\n );\nexport const MicOffIcon = ({ size = 20 }: P) =>\n svg(\n size,\n <>\n <path d=\"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 10.6 5M18.4 12.5a6.5 6.5 0 0 0 .1-1.5M12 17.5V21M3 3l18 18\" />\n </>,\n );\nexport const CloseIcon = ({ size = 18 }: P) => svg(size, <path d=\"M6 6l12 12M18 6L6 18\" />);\nexport const SendIcon = ({ size = 18 }: P) => svg(size, <path d=\"M12 19V5M5.5 11.5L12 5l6.5 6.5\" />);\nexport const BackIcon = ({ size = 18 }: P) => svg(size, <path d=\"M15 5l-7 7 7 7\" />);\nexport const SparkIcon = ({ size = 14 }: P) => svg(size, <path d=\"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z\" />);\nexport const NewChatIcon = ({ size = 18 }: P) => svg(size, <path d=\"M12 4H6.5A2.5 2.5 0 0 0 4 6.5v11A2.5 2.5 0 0 0 6.5 20h11a2.5 2.5 0 0 0 2.5-2.5V12M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z\" />);\nexport const CheckIcon = ({ size = 14 }: P) => svg(size, <path d=\"M5 12.5l4.2 4.2L19 7\" />);\nexport const RetryIcon = ({ size = 14 }: P) => svg(size, <path d=\"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4\" />);\n","import type { Call, CallState, CharacterXYZ } from '@characterxyz/web';\nimport { useEffect, useRef, useState } from 'preact/hooks';\n\n/**\n * The agent's face, drawn by Character XYZ's own renderer in a frame\n * (`<faceUrl>` = the app's `/embed/face`), so the widget shows her exactly as\n * the app does — her clips, the Neural Lip Sync mouth, her own teeth and eyes —\n * without carrying the renderer itself (canon/docs/sdk-design.md, lip sync).\n *\n * The frame holds no session: this side fetches the face data with the\n * widget's session and posts it in, then forwards the call's streamed face and\n * the voice's audible clock. Until the frame says it is ready, the caller keeps\n * showing the portrait underneath.\n */\n\nexport type FaceStatus = 'loading' | 'ready' | 'unavailable';\n\n/** What the frame wants the face's mood to be (read when the call connects). */\nexport const faceEmotion = { current: null as string | null };\n\nfunction cameoState(s: CallState | null): string {\n if (!s) return 'idle';\n if (s.speaking) return 'speaking';\n if (s.agentState === 'thinking') return 'reasoning';\n if (s.agentState === 'listening' || s.phase === 'live') return 'listening';\n return 'idle';\n}\n\nexport function FaceFrame({\n client,\n call,\n state,\n src,\n onStatus,\n}: {\n client: CharacterXYZ;\n call: Call | null;\n state: CallState | null;\n src: string;\n onStatus: (s: FaceStatus) => void;\n}) {\n const frame = useRef<HTMLIFrameElement>(null);\n const [loaded, setLoaded] = useState(false);\n const loadedRef = useRef(false);\n const origin = (() => {\n try {\n return new URL(src).origin;\n } catch {\n return null;\n }\n })();\n\n const post = (msg: Record<string, unknown>, transfer?: Transferable[]) => {\n const w = frame.current?.contentWindow;\n if (w && origin) w.postMessage({ cx: 'face', ...msg }, origin, transfer ?? []);\n };\n\n // The frame's own messages: loaded → send the skin; ready / unavailable → report.\n useEffect(() => {\n if (!origin) {\n onStatus('unavailable');\n return;\n }\n let cancelled = false;\n const onMessage = (e: MessageEvent) => {\n if (e.source !== frame.current?.contentWindow || e.origin !== origin) return;\n const d = e.data as { cx?: string; type?: string; faceEmotion?: string | null };\n if (d?.cx !== 'face') return;\n if (d.type === 'loaded') {\n loadedRef.current = true;\n setLoaded(true);\n client\n .videoAvatar()\n .then((avatar) => {\n if (cancelled) return;\n if (!avatar) onStatus('unavailable');\n else post({ type: 'init', avatar });\n })\n .catch(() => !cancelled && onStatus('unavailable'));\n } else if (d.type === 'ready') {\n faceEmotion.current = typeof d.faceEmotion === 'string' ? d.faceEmotion : null;\n onStatus('ready');\n } else if (d.type === 'unavailable') {\n onStatus('unavailable');\n }\n };\n window.addEventListener('message', onMessage);\n // A frame that never answers (blocked, offline) leaves the portrait in place.\n const timeout = setTimeout(() => !cancelled && !loadedRef.current && onStatus('unavailable'), 15_000);\n return () => {\n cancelled = true;\n clearTimeout(timeout);\n window.removeEventListener('message', onMessage);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, origin]);\n\n // The agent's state, as the app's renderer names it.\n const cameo = cameoState(state);\n useEffect(() => {\n if (loaded) post({ type: 'state', state: cameo });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [cameo, loaded]);\n\n // The streamed face, the lines' starts and ends, and the voice's clock.\n useEffect(() => {\n if (!call || !loaded) return;\n const offs = [\n call.on('face', ({ corr, payload }) => post({ type: 'batch', corr, payload }, [payload.buffer as ArrayBuffer])),\n call.on('line', ({ corr, event }) => {\n if (event === 'audible') post({ type: 'audible', corr, ms: call.audible()?.ms ?? 0 });\n else post({ type: 'end', corr });\n }),\n ];\n let raf = 0;\n const tick = () => {\n const a = call.audible();\n if (a) post({ type: 'clock', corr: a.corr, ms: a.ms });\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => {\n offs.forEach((f) => f());\n cancelAnimationFrame(raf);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [call, loaded]);\n\n if (!origin) return null;\n return (\n <iframe\n ref={frame}\n class=\"face-frame\"\n src={src}\n title=\"\"\n aria-hidden=\"true\"\n tabIndex={-1}\n allow=\"autoplay\"\n sandbox=\"allow-scripts allow-same-origin\"\n referrerpolicy=\"strict-origin\"\n />\n );\n}\n","import type { AgentCard } from '@characterxyz/web';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\n\nimport { faceOf, place, type Shot } from './framing.js';\n\n/**\n * WebM with alpha plays in Chromium and Firefox. Safari ignores the alpha and\n * would draw the clip's green screen, so it gets the cut-out still instead.\n */\nfunction alphaVideoWorks(): boolean {\n if (typeof document === 'undefined') return false;\n const ua = navigator.userAgent;\n const safari = /Safari\\//.test(ua) && !/(Chrome|Chromium|Edg|OPR|Firefox)\\//.test(ua);\n if (safari) return false;\n const v = document.createElement('video');\n return v.canPlayType('video/webm; codecs=\"vp9\"') !== '';\n}\n\nconst reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nexport interface PortraitProps {\n agent: AgentCard;\n shot: Shot;\n /** Play the talking clip instead of idle. */\n talking?: boolean;\n /** Freeze on the still (closed launcher on a slow page, reduced motion). */\n still?: boolean;\n class?: string;\n}\n\n/**\n * The character, framed on her face. Two looping clips (idle, talking)\n * crossfade; the anchor still shows until the first frame and wherever clips\n * cannot play. A character without a video shows her initial.\n */\nexport function Portrait({ agent, shot, talking = false, still = false, class: cls }: PortraitProps) {\n const box = useRef<HTMLDivElement>(null);\n const [size, setSize] = useState({ w: 0, h: 0 });\n const [anchorDims, setAnchorDims] = useState<{ w: number; h: number } | null>(null);\n const [ready, setReady] = useState<Record<string, boolean>>({});\n const video = agent.video;\n const anchorUrl = video?.anchor?.alphaUrl ?? video?.anchor?.url ?? null;\n const canPlay = !still && !reducedMotion() && alphaVideoWorks();\n const idle = video?.clips.idle?.alphaUrl ?? null;\n const talk = video?.clips.talking?.alphaUrl ?? idle;\n\n useLayoutEffect(() => {\n const el = box.current;\n if (!el) return;\n const update = () => setSize({ w: el.clientWidth, h: el.clientHeight });\n update();\n if (typeof ResizeObserver === 'undefined') return;\n const ro = new ResizeObserver(update);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n if (!video || !anchorUrl) {\n return (\n <div ref={box} class={`portrait portrait--initial ${cls ?? ''}`} aria-hidden=\"true\">\n <span>{(agent.name || '?').slice(0, 1).toUpperCase()}</span>\n </div>\n );\n }\n\n const aspect = anchorDims ? anchorDims.w / anchorDims.h : 0.75;\n const face = faceOf(video, anchorDims?.w ?? 0, anchorDims?.h ?? 0);\n const p = size.w && size.h ? place(face, aspect, size.w, size.h, shot) : null;\n const style: Record<string, string | number> = p ? { width: `${p.width}px`, height: `${p.height}px`, left: `${p.left}px`, top: `${p.top}px` } : { opacity: 0 };\n const showIdle = canPlay && !!idle && !!ready.idle;\n const showTalk = canPlay && !!talk && talk !== idle && !!ready.talk && talking;\n\n return (\n <div ref={box} class={`portrait ${cls ?? ''}`} aria-hidden=\"true\">\n <img\n class=\"portrait__media\"\n src={anchorUrl}\n alt=\"\"\n draggable={false}\n style={{ ...style, opacity: p ? (showIdle ? 0 : 1) : 0 }}\n onLoad={(e) => {\n const img = e.currentTarget as HTMLImageElement;\n setAnchorDims({ w: img.naturalWidth, h: img.naturalHeight });\n }}\n />\n {canPlay && idle ? <Clip src={idle} style={style} visible={showIdle && !showTalk} onReady={() => setReady((r) => ({ ...r, idle: true }))} /> : null}\n {canPlay && talk && talk !== idle ? <Clip src={talk} style={style} visible={showTalk} onReady={() => setReady((r) => ({ ...r, talk: true }))} /> : null}\n </div>\n );\n}\n\nfunction Clip({ src, style, visible, onReady }: { src: string; style: Record<string, string | number>; visible: boolean; onReady: () => void }) {\n const ref = useRef<HTMLVideoElement>(null);\n useEffect(() => {\n const v = ref.current;\n if (!v) return;\n // Only the clip on screen plays; a hidden one costs nothing.\n if (visible) void v.play().catch(() => {});\n else v.pause();\n }, [visible]);\n return (\n <video\n ref={ref}\n class=\"portrait__media portrait__clip\"\n src={src}\n muted\n loop\n playsInline\n preload=\"auto\"\n style={{ ...style, opacity: visible ? 1 : 0 }}\n onLoadedData={onReady}\n />\n );\n}\n","import type { Call, CallState, Caption, CharacterXYZ, ChatMessage, ContactDetails, DetailsForm, Opening } from '@characterxyz/web';\nimport { Fragment, type ComponentChildren } from 'preact';\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\n\nimport type { WidgetConfig } from './config.js';\nimport { blocks, clock, endCopy, eta, ordinal, type Inline } from './format.js';\nimport { CLOSE_UP, FULL_BODY, HALF_BODY, MEDIUM } from './framing.js';\nimport { extractContact, type TypedContact } from './contact.js';\nimport { BackIcon, ChatIcon, CheckIcon, CloseIcon, HangUpIcon, MicIcon, MicOffIcon, NewChatIcon, PhoneIcon, RetryIcon, SendIcon } from './icons.js';\nimport { faceEmotion, FaceFrame, type FaceStatus } from './face-frame.js';\nimport { Portrait } from './portrait.js';\n\nexport type View = 'closed' | 'chat' | 'call';\n\nexport interface AppApi {\n open(view?: Exclude<View, 'closed'>): void;\n close(): void;\n}\n\nexport interface AppProps {\n client: CharacterXYZ;\n config: WidgetConfig;\n /** Lets the element drive the app (`open()`, `close()`). */\n bind: (api: AppApi) => void;\n onView: (v: View) => void;\n}\n\nconst GREETED_KEY = 'cxyz:greeted';\n/** Set once the launcher has shown its words; after that it is icons only. */\nconst INTRODUCED_KEY = 'cxyz:introduced';\n\nfunction storage(key: string, value?: string): string | null {\n try {\n if (value !== undefined) localStorage.setItem(key, value);\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** A short two-note chime: \"your turn\". */\nfunction chime() {\n try {\n const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;\n const ctx = new Ctx();\n const now = ctx.currentTime;\n [660, 880].forEach((f, i) => {\n const o = ctx.createOscillator();\n const g = ctx.createGain();\n o.type = 'sine';\n o.frequency.value = f;\n g.gain.setValueAtTime(0, now + i * 0.16);\n g.gain.linearRampToValueAtTime(0.18, now + i * 0.16 + 0.02);\n g.gain.exponentialRampToValueAtTime(0.0001, now + i * 0.16 + 0.5);\n o.connect(g).connect(ctx.destination);\n o.start(now + i * 0.16);\n o.stop(now + i * 0.16 + 0.55);\n });\n setTimeout(() => void ctx.close(), 1200);\n } catch {\n // no audio: the banner still says it\n }\n}\n\nfunction useChat(client: CharacterXYZ) {\n const [messages, setMessages] = useState<readonly ChatMessage[]>(client.chat.messages);\n const [busy, setBusy] = useState(client.chat.isBusy);\n useEffect(() => {\n const a = client.chat.on('messages', setMessages);\n const b = client.chat.on('busy', setBusy);\n return () => {\n a();\n b();\n };\n }, [client]);\n return { messages, busy };\n}\n\nfunction useCall(client: CharacterXYZ) {\n const [call, setCall] = useState<Call | null>(client.call);\n const [state, setState] = useState<CallState | null>(client.call?.state ?? null);\n const [captions, setCaptions] = useState<Caption[]>([]);\n useEffect(() => client.on('call', (c) => c && setCall(c)), [client]);\n useEffect(() => {\n if (!call) return;\n setState(call.state);\n setCaptions([]);\n const offs = [\n call.on('state', setState),\n call.on('caption', (c) => setCaptions((prev) => [...prev.filter((x) => x.id !== c.id), c].slice(-4))),\n call.on('captionRemoved', (id) => setCaptions((prev) => prev.filter((x) => x.id !== id))),\n ];\n return () => offs.forEach((f) => f());\n }, [call]);\n return { call, state, captions, reset: () => setCall(null) };\n}\n\n/** Seconds since `startedAt`, ticking. */\nfunction useElapsed(startedAt: number | null, running: boolean) {\n const [now, setNow] = useState(Date.now());\n useEffect(() => {\n if (!running) return;\n const t = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(t);\n }, [running]);\n return startedAt ? Math.max(0, (now - startedAt) / 1000) : 0;\n}\n\n/** Feed `--cx-lvl` from the agent's voice on every frame, without re-rendering. */\nfunction useVoiceLevel(call: Call | null, el: { current: HTMLElement | null }, active: boolean) {\n useEffect(() => {\n if (!call || !active) return;\n let raf = 0;\n let smooth = 0;\n const tick = () => {\n const lvl = call.voiceLevel();\n smooth = smooth * 0.7 + lvl * 0.3;\n el.current?.style.setProperty('--cx-lvl', smooth.toFixed(3));\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(raf);\n }, [call, active, el]);\n}\n\nfunction Text({ parts }: { parts: Inline[] }) {\n return (\n <Fragment>\n {parts.map((p, i) =>\n p.t === 'b' ? (\n <strong key={i}>{p.v}</strong>\n ) : p.t === 'i' ? (\n <em key={i}>{p.v}</em>\n ) : p.t === 'code' ? (\n <code key={i}>{p.v}</code>\n ) : p.t === 'link' ? (\n <a key={i} href={p.href} target=\"_blank\" rel=\"noopener noreferrer nofollow\">\n {p.v}\n </a>\n ) : (\n p.v.split('\\n').map((line, j, arr) => (\n <Fragment key={`${i}.${j}`}>\n {line}\n {j < arr.length - 1 ? <br /> : null}\n </Fragment>\n ))\n ),\n )}\n </Fragment>\n );\n}\n\nconst LABELS: Record<string, { label: string; type: string; auto: string }> = {\n name: { label: 'Name', type: 'text', auto: 'name' },\n email: { label: 'Email', type: 'email', auto: 'email' },\n phone: { label: 'Phone', type: 'tel', auto: 'tel' },\n company: { label: 'Company', type: 'text', auto: 'organization' },\n};\n\n/** The contact card: a few fields in the chat, skippable, sending is the consent. */\nfunction DetailsCard({\n form,\n title,\n note,\n onSend,\n onSkip,\n skipLabel,\n initial,\n}: {\n form: DetailsForm;\n initial?: TypedContact;\n title: string;\n note: string | null;\n onSend: (d: ContactDetails) => Promise<void>;\n onSkip: () => void;\n skipLabel: string;\n}) {\n const [values, setValues] = useState<Record<string, string>>(() => ({ ...(initial ?? {}) }) as Record<string, string>);\n const [errors, setErrors] = useState<Record<string, string>>({});\n const [failed, setFailed] = useState<string | null>(null);\n const [sending, setSending] = useState(false);\n const first = useRef<HTMLInputElement>(null);\n useEffect(() => {\n setTimeout(() => first.current?.focus({ preventScroll: true }), 80);\n }, []);\n return (\n <form\n class=\"card\"\n part=\"details\"\n onSubmit={async (e) => {\n e.preventDefault();\n setSending(true);\n setErrors({});\n setFailed(null);\n try {\n await onSend({\n name: values.name ?? '',\n email: values.email ?? '',\n ...(values.phone ? { phone: values.phone } : {}),\n ...(values.company ? { company: values.company } : {}),\n });\n } catch (err) {\n const fields = (err as { fields?: Record<string, string> }).fields ?? {};\n if (Object.keys(fields).length) setErrors(fields);\n else setFailed((err as Error).message || 'Could not send. Try again.');\n } finally {\n setSending(false);\n }\n }}\n >\n <div class=\"card__title\">{title}</div>\n {note ? <div class=\"card__note\">{note}</div> : null}\n {form.fields.map((f, i) => {\n const spec = LABELS[f]!;\n return (\n <label class=\"card__field\" key={f}>\n <span>\n {spec.label}\n {f === 'phone' || f === 'company' ? <i> · optional</i> : null}\n </span>\n <input\n ref={i === 0 ? first : undefined}\n type={spec.type}\n autocomplete={spec.auto}\n required={f === 'name' || f === 'email'}\n maxLength={f === 'email' ? 254 : 120}\n value={values[f] ?? ''}\n aria-invalid={errors[f] ? 'true' : undefined}\n onInput={(e) => setValues((v) => ({ ...v, [f]: e.currentTarget.value }))}\n />\n {errors[f] ? <em>{errors[f]}</em> : null}\n </label>\n );\n })}\n <div class=\"card__consent\">\n {form.consent}\n {form.privacyUrl ? (\n <Fragment>\n {' '}\n <a href={form.privacyUrl} target=\"_blank\" rel=\"noopener noreferrer\">\n Privacy policy\n </a>\n </Fragment>\n ) : null}\n </div>\n {failed ? <div class=\"card__failed\">{failed}</div> : null}\n <div class=\"card__actions\">\n <button type=\"submit\" class=\"btn btn--accent btn--sm\" disabled={sending}>\n {sending ? 'Sending…' : 'Send'}\n </button>\n <button type=\"button\" class=\"btn btn--ghost btn--sm\" onClick={onSkip} disabled={sending}>\n {skipLabel}\n </button>\n </div>\n </form>\n );\n}\n\n/** Tappable questions under her message: what to ask first, or next. */\nfunction QuickReplies({ items, onPick, children }: { items: readonly string[]; onPick: (q: string) => void; children?: ComponentChildren }) {\n if (!items.length && !children) return null;\n return (\n <div class=\"chips chips--start\" part=\"suggestions\">\n {items.map((q) => (\n <button class=\"chip\" key={q} onClick={() => onPick(q)}>\n {q}\n </button>\n ))}\n {children}\n </div>\n );\n}\n\nfunction Rich({ text }: { text: string }) {\n return (\n <Fragment>\n {blocks(text).map((b, i) =>\n b.t === 'ul' ? (\n <ul key={i}>\n {b.items.map((it, j) => (\n <li key={j}>\n <Text parts={it} />\n </li>\n ))}\n </ul>\n ) : (\n <p key={i}>\n <Text parts={b.parts} />\n </p>\n ),\n )}\n </Fragment>\n );\n}\n\nexport function App({ client, config, bind, onView }: AppProps) {\n const agent = client.agent;\n const features = client.features;\n const canChat = config.showChat && features.chat;\n const canCall = config.showCall && features.call;\n const [view, setViewRaw] = useState<View>(config.open ? (canChat ? 'chat' : 'call') : 'closed');\n const [closing, setClosing] = useState(false);\n const [greeting, setGreeting] = useState(false);\n const { messages, busy } = useChat(client);\n const { call, state, captions, reset } = useCall(client);\n const [draft, setDraft] = useState('');\n const log = useRef<HTMLDivElement>(null);\n const input = useRef<HTMLTextAreaElement>(null);\n const stage = useRef<HTMLDivElement>(null);\n const subtitle = config.subtitle ?? agent.tagline;\n const name = agent.name || 'Assistant';\n\n // HOW SHE OPENS is hers: written by the agent from her persona and the\n // key's product knowledge (server-cached), fetched once per page so the\n // teaser and her first message are ready before anyone clicks. A brand's own\n // `greeting` / `suggestions` still win.\n const [opening, setOpening] = useState<Opening | null>(null);\n useEffect(() => {\n if (!canChat) return;\n let live = true;\n void client.opening().then((o) => live && setOpening(o));\n return () => {\n live = false;\n };\n }, [client, canChat]);\n const teaser = config.greeting || opening?.teaser || '';\n const starters = config.suggestions.length ? config.suggestions : (opening?.suggestions ?? []);\n const firstLine = opening?.greeting || `Hi, I'm ${name}. How can I help you today?`;\n\n // Her first message waits for the history (a returning visitor has one) and\n // then for a short typing beat, so it arrives like a message, not a label.\n const [history, setHistory] = useState<'loading' | 'empty' | number>('loading');\n const [greeted, setGreeted] = useState(false);\n\n // HER DETAILS CARD, asked at a moment of intent, never before the chat: under\n // the reply where she invited the visitor (`askDetails`), or once before a\n // call when the key has somewhere to send it (`opening.details`). Sending or\n // \"Not now\" settles it for this conversation.\n const [detailsDone, setDetailsDone] = useState<'sent' | 'skipped' | null>(null);\n const [sentName, setSentName] = useState('');\n const [callCard, setCallCard] = useState<DetailsForm | null>(null);\n // Details the visitor TYPED into the chat: the card opens already filled in,\n // after her reply, and sending it is still the one confirmation.\n const [typed, setTyped] = useState<{ form: DetailsForm; values: TypedContact } | null>(null);\n\n const setView = useCallback(\n (v: View) => {\n setViewRaw(v);\n onView(v);\n },\n [onView],\n );\n\n const close = useCallback(() => {\n setClosing(true);\n setTimeout(() => {\n setClosing(false);\n setView('closed');\n }, 200);\n }, [setView]);\n\n const loadHistory = useCallback(async () => {\n try {\n const list = await client.chat.load();\n setHistory((h) => (h === 'loading' ? (list.length ? list.length : 'empty') : h));\n } catch {\n setHistory((h) => (h === 'loading' ? 'empty' : h));\n }\n }, [client]);\n\n const open = useCallback(\n (v: Exclude<View, 'closed'> = canChat ? 'chat' : 'call') => {\n setGreeting(false);\n storage(GREETED_KEY, '1');\n setView(v);\n if (v === 'chat') void loadHistory();\n },\n [canChat, setView, loadHistory],\n );\n\n\n useEffect(() => bind({ open, close }), [bind, open, close]);\n\n useEffect(() => {\n if (config.open && canChat) void loadHistory();\n }, [loadHistory, config.open, canChat]);\n\n // The teaser: once per visitor, after a beat, never over an open panel.\n useEffect(() => {\n if (!teaser || storage(GREETED_KEY)) return;\n const t = setTimeout(() => setGreeting(true), config.greetingDelay * 1000);\n return () => clearTimeout(t);\n }, [teaser, config.greetingDelay]);\n\n useEffect(() => {\n if (view !== 'chat' || greeted || history === 'loading') return;\n const t = setTimeout(() => setGreeted(true), 700);\n return () => clearTimeout(t);\n }, [view, greeted, history]);\n\n // The launcher's buttons say what they are once, on a visitor's first visit,\n // then fold to icons. Hover and keyboard focus unfold them again (CSS).\n const [labelled, setLabelled] = useState(() => !storage(INTRODUCED_KEY));\n useEffect(() => {\n if (!labelled) return;\n const t = setTimeout(() => {\n setLabelled(false);\n storage(INTRODUCED_KEY, '1');\n }, 5000);\n return () => clearTimeout(t);\n }, [labelled]);\n\n // Esc closes.\n useEffect(() => {\n if (view === 'closed') return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') close();\n };\n window.addEventListener('keydown', onKey);\n return () => window.removeEventListener('keydown', onKey);\n }, [view, close]);\n\n // Keep the newest message in view.\n useEffect(() => {\n const el = log.current;\n if (el) el.scrollTop = el.scrollHeight;\n }, [messages, view, state?.phase]);\n\n useEffect(() => {\n if (view === 'chat') setTimeout(() => input.current?.focus({ preventScroll: true }), 60);\n }, [view]);\n\n // The face frame (the app's own renderer) is wanted for a video character.\n const wantsFace = config.face && !!agent.video;\n const [faceStatus, setFaceStatus] = useState<FaceStatus>('loading');\n\n // Your turn: a chime, and the tab title if the visitor is elsewhere.\n const phase = state?.phase ?? 'idle';\n useEffect(() => {\n if (phase !== 'ready' || !call) return;\n chime();\n if (view === 'call') {\n // Join once the face frame has said who she is (her mood goes in the\n // call's opening message), or after 3 s whatever it says: the hold is 30.\n if (!wantsFace || faceStatus !== 'loading') {\n call.accept();\n return;\n }\n const t = setTimeout(() => call.accept(), 3000);\n return () => clearTimeout(t);\n }\n if (typeof document !== 'undefined' && document.hidden) {\n const title = document.title;\n document.title = `● ${name} is ready for you`;\n const restore = () => {\n document.title = title;\n document.removeEventListener('visibilitychange', restore);\n };\n document.addEventListener('visibilitychange', restore);\n }\n }, [phase, call, view, name, wantsFace, faceStatus]);\n\n const live = phase === 'live' || phase === 'connecting';\n useVoiceLevel(call, stage, live && view === 'call');\n const elapsed = useElapsed(state?.startedAt ?? null, phase === 'live');\n // Every hook above the early returns: Preact keys hooks by call order.\n const startPos = useMemoStart(call, state?.position ?? 1);\n\n /** A call, after the details card when there is one to offer first. */\n const beginCall = () => {\n const form = opening?.details;\n if (form && !detailsDone && canChat) {\n setCallCard(form);\n setView('chat');\n void loadHistory();\n return;\n }\n void startCall();\n };\n\n const settleDetails = (how: 'sent' | 'skipped', firstName = '') => {\n setDetailsDone(how);\n setSentName(firstName);\n setTyped(null);\n const thenCall = !!callCard;\n setCallCard(null);\n if (thenCall) void startCall();\n };\n\n const sendDetails = async (d: ContactDetails) => {\n await client.sendDetails(d);\n settleDetails('sent', d.name.trim().split(/\\s+/)[0] ?? '');\n };\n\n const skipDetails = () => {\n void client.declineDetails().catch(() => {});\n settleDetails('skipped');\n };\n\n const startOver = async () => {\n try {\n await client.chat.reset();\n } catch {\n return;\n }\n setHistory('empty');\n setGreeted(false);\n setDetailsDone(null);\n setCallCard(null);\n setTyped(null);\n setDraft('');\n setOpening(await client.opening(true));\n };\n\n const startCall = async () => {\n setView('call');\n try {\n await client.startCall({ autoAccept: false, ...(wantsFace ? { face: { emotion: () => faceEmotion.current } } : {}) });\n } catch {\n // the call's own state carries the reason\n }\n };\n\n // The card's settings while details may still be left: the latest a reply\n // carried, else the opening's (it is null once this conversation was asked).\n const knownForm: DetailsForm | null =\n [...messages].reverse().find((m) => m.detailsForm || m.askDetails)?.detailsForm ??\n [...messages].reverse().find((m) => m.askDetails)?.askDetails ??\n opening?.details ??\n null;\n\n const sendText = async (text: string) => {\n const t = text.trim();\n if (!t || busy) return;\n // ⚠ A \"NOT NOW\" DOES NOT CLOSE THIS DOOR: someone who typed their email has\n // changed their mind. Only an already-sent card does.\n const found = knownForm && detailsDone !== 'sent' ? extractContact(t) : null;\n if (found && knownForm) setTyped({ form: knownForm, values: found });\n setDraft('');\n if (input.current) input.current.style.height = '';\n try {\n await client.chat.send(t);\n } catch {\n // the message shows as failed with a retry\n }\n };\n\n const lastAgentStreaming = messages.length > 0 && messages[messages.length - 1]!.role === 'agent' && messages[messages.length - 1]!.streaming;\n\n // Which details card is open, if any — one at a time, and while one is open\n // it is the only thing asking (the suggestion chips step aside).\n const lastMsg = messages[messages.length - 1];\n const invited = lastMsg?.role === 'agent' && !lastMsg.streaming ? lastMsg.askDetails : undefined;\n const card: { form: DetailsForm; kind: 'call' | 'typed' | 'invited'; initial?: TypedContact } | null = callCard\n ? { form: callCard, kind: 'call' }\n : typed && detailsDone !== 'sent' && !busy\n ? { form: typed.form, kind: 'typed', initial: typed.values }\n : invited && !detailsDone\n ? { form: invited, kind: 'invited' }\n : null;\n\n // ---------------------------------------------------------------- closed\n if (view === 'closed') {\n const inLine = phase === 'queued' || phase === 'ready' || phase === 'live' || phase === 'connecting';\n return (\n <div class={`dock dock--${config.display}`} part=\"launcher\">\n {greeting ? (\n <div class=\"greeting\" part=\"greeting\" role=\"status\" onClick={() => open()}>\n {teaser}\n <button\n class=\"greeting__close\"\n aria-label=\"Dismiss\"\n onClick={(e) => {\n e.stopPropagation();\n setGreeting(false);\n storage(GREETED_KEY, '1');\n }}\n >\n <CloseIcon size={14} />\n </button>\n </div>\n ) : null}\n <button\n class={`presence presence--${config.display} ${inLine ? 'presence--live' : ''}`}\n part=\"presence\"\n aria-label={\n inLine\n ? phase === 'queued'\n ? `You are ${ordinal(state?.position ?? 1)} in line to call ${name}. Open`\n : `Back to your call with ${name}`\n : canChat\n ? `Chat with ${name}`\n : `Call ${name}`\n }\n onClick={() => open(inLine || !canChat ? 'call' : 'chat')}\n >\n {config.display === 'bubble' ? <span class=\"presence__ring\" /> : null}\n <span class=\"presence__face\">\n <Portrait agent={agent} shot={config.display === 'full' ? FULL_BODY : config.display === 'half' ? HALF_BODY : CLOSE_UP} />\n </span>\n <span class=\"presence__dot\" />\n {client.mode === 'test' ? (\n <span class=\"testmode\" title=\"Test mode: this key only works on development sites\">\n TEST\n </span>\n ) : null}\n {phase === 'queued' ? (\n <span class=\"presence__badge\" aria-hidden=\"true\">\n {state?.position ?? 1}\n </span>\n ) : null}\n {config.launcher === 'bubble' && !greeting ? (\n <span class=\"presence__label\" aria-hidden=\"true\">\n {inLine ? (phase === 'queued' ? `${ordinal(state?.position ?? 1)} in line` : 'Back to your call') : canChat ? `Chat with ${name}` : `Call ${name}`}\n </span>\n ) : null}\n </button>\n {config.launcher === 'bubble' ? null : (\n <div class={`acts ${labelled ? 'acts--labelled' : ''}`} part=\"actions\">\n {canChat ? (\n <button class=\"act\" aria-label={`Chat with ${name}`} onClick={() => open('chat')}>\n <ChatIcon size={20} />\n <span class=\"act__label\" aria-hidden=\"true\">\n Chat\n </span>\n </button>\n ) : null}\n {canCall ? (\n <button\n class={`act act--call ${inLine ? 'act--live' : ''}`}\n aria-label={inLine ? (phase === 'queued' ? `You are ${ordinal(state?.position ?? 1)} in line. Open your call` : 'Back to your call') : `Call ${name}`}\n onClick={() => (inLine ? open('call') : beginCall())}\n >\n <PhoneIcon size={20} />\n <span class=\"act__label\" aria-hidden=\"true\">\n {inLine ? (phase === 'queued' ? `${ordinal(state?.position ?? 1)} in line` : 'On call') : 'Call'}\n </span>\n {phase === 'queued' ? (\n <span class=\"act__badge\" aria-hidden=\"true\">\n {state?.position ?? 1}\n </span>\n ) : null}\n </button>\n ) : null}\n </div>\n )}\n </div>\n );\n }\n\n // ---------------------------------------------------------------- chat\n const head = (\n <div class=\"head\" part=\"header\">\n <div class=\"head__face\">\n <Portrait agent={agent} shot={CLOSE_UP} talking={!!lastAgentStreaming} />\n </div>\n <div class=\"head__who\">\n <div class=\"head__name\">{name}</div>\n <div class=\"head__sub\">\n <i />\n {busy ? 'Typing…' : subtitle || 'Online'}\n </div>\n </div>\n {view === 'chat' && messages.length > 0 && !busy ? (\n <button class=\"icon-btn\" aria-label=\"Start a new conversation\" title=\"Start a new conversation\" onClick={() => void startOver()}>\n <NewChatIcon />\n </button>\n ) : null}\n {canCall && view === 'chat' ? (\n <button class=\"icon-btn icon-btn--accent\" aria-label={`Call ${name}`} title={`Call ${name}`} onClick={() => (call && phase !== 'ended' ? setView('call') : beginCall())}>\n <PhoneIcon size={18} />\n </button>\n ) : null}\n <button class=\"icon-btn\" aria-label=\"Close\" onClick={close}>\n <CloseIcon />\n </button>\n </div>\n );\n\n if (view === 'chat') {\n return (\n <div class={`panel ${closing ? 'is-closing' : ''}`} part=\"panel\" role=\"dialog\" aria-label={`Chat with ${name}`}>\n {head}\n {call && (phase === 'queued' || phase === 'ready') ? (\n <div class=\"banner\" part=\"banner\" role=\"status\">\n <div class=\"banner__text\">\n {phase === 'queued' ? (\n <Fragment>\n You're <b>{ordinal(state?.position ?? 1)}</b> in line for a call · {eta(state?.etaSeconds ?? null)}\n </Fragment>\n ) : (\n <Fragment>\n <b>{name} is ready for you</b> · {state?.holdSeconds ?? 30}s to join\n </Fragment>\n )}\n </div>\n {phase === 'ready' ? (\n <button\n class=\"btn btn--accent btn--glow\"\n onClick={() => {\n call.accept();\n setView('call');\n }}\n >\n Join\n </button>\n ) : (\n <button class=\"btn\" onClick={() => setView('call')}>\n View\n </button>\n )}\n </div>\n ) : null}\n <div class=\"log\" ref={log} role=\"log\" aria-live=\"polite\" aria-relevant=\"additions\">\n {messages.length === 0 ? (\n <Fragment>\n <div class=\"empty\">\n <div class=\"empty__face\">\n <Portrait agent={agent} shot={CLOSE_UP} />\n </div>\n <div class=\"empty__title\">{name}</div>\n {subtitle ? <div class=\"empty__body\">{subtitle}</div> : null}\n </div>\n {history === 'loading' ? null : !greeted ? (\n <div class=\"msg msg--agent typing\" aria-label={`${name} is typing`}>\n <i />\n <i />\n <i />\n </div>\n ) : (\n <Fragment>\n <div class=\"msg msg--agent\" part=\"message message-agent\">\n <Rich text={firstLine} />\n </div>\n {card ? null : (\n <QuickReplies items={starters} onPick={(q) => void sendText(q)}>\n {canCall ? (\n <button class=\"chip chip--call\" onClick={() => (call && phase !== 'ended' ? setView('call') : beginCall())}>\n <PhoneIcon size={14} /> Call {name}\n </button>\n ) : null}\n </QuickReplies>\n )}\n </Fragment>\n )}\n </Fragment>\n ) : null}\n {messages.map((m) =>\n m.role === 'agent' && m.streaming && !m.text ? (\n <div class=\"msg msg--agent typing\" key={m.id} aria-label={`${name} is typing`}>\n <i />\n <i />\n <i />\n </div>\n ) : (\n <Fragment key={m.id}>\n <div class={`msg msg--${m.role} ${m.failed ? 'msg--failed' : ''} ${m.streaming ? 'caret' : ''}`} part={`message message-${m.role}`}>\n {m.role === 'agent' ? <Rich text={m.text} /> : m.text}\n </div>\n {m === messages[messages.length - 1] && m.role === 'agent' && !m.streaming && !busy && !card && m.suggestions?.length ? (\n <QuickReplies items={m.suggestions} onPick={(q) => void sendText(q)} />\n ) : null}\n {m.failed && m.error ? (\n <div class=\"msg__why\" role=\"status\">\n {m.error}\n </div>\n ) : m.failed ? (\n <button class=\"msg__retry\" onClick={() => void client.chat.retry(m.id).catch(() => {})}>\n <RetryIcon /> Not sent · Retry\n </button>\n ) : null}\n </Fragment>\n ),\n )}\n {/* A visitor back to an earlier conversation: a word from her, and\n where to start — until they say something. */}\n {typeof history === 'number' && messages.length === history && opening?.welcomeBack ? (\n <Fragment>\n <div class=\"msg msg--agent\" part=\"message message-agent\">\n {opening.welcomeBack}\n </div>\n {card ? null : <QuickReplies items={starters} onPick={(q) => void sendText(q)} />}\n </Fragment>\n ) : null}\n {(() => {\n if (card) {\n return (\n <DetailsCard\n key={card.kind === 'invited' ? lastMsg?.id : card.kind}\n form={card.form}\n initial={card.initial}\n title={card.kind === 'call' ? `Before you call ${name}` : card.kind === 'typed' ? 'Confirm your details' : 'Leave your details'}\n note={card.kind === 'call' ? 'So the team can follow up, even if the line drops.' : card.kind === 'typed' ? 'From what you typed. Check them and send.' : null}\n onSend={sendDetails}\n onSkip={skipDetails}\n skipLabel={card.kind === 'call' ? 'Skip and call' : 'Not now'}\n />\n );\n }\n return detailsDone === 'sent' ? (\n <div class=\"notice\" role=\"status\">\n <CheckIcon /> {sentName ? `Thanks, ${sentName}. ` : 'Thanks. '}The team will be in touch.\n </div>\n ) : null;\n })()}\n </div>\n <form\n class=\"compose\"\n part=\"composer\"\n onSubmit={(e) => {\n e.preventDefault();\n void sendText(draft);\n }}\n >\n <div class=\"compose__box\">\n <textarea\n ref={input}\n rows={1}\n value={draft}\n maxLength={2000}\n placeholder={config.placeholder}\n aria-label=\"Message\"\n onInput={(e) => {\n const t = e.currentTarget;\n setDraft(t.value);\n t.style.height = 'auto';\n t.style.height = `${Math.min(120, t.scrollHeight)}px`;\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {\n e.preventDefault();\n void sendText(draft);\n }\n }}\n />\n <button class=\"send\" type=\"submit\" aria-label=\"Send\" disabled={!draft.trim() || busy}>\n <SendIcon />\n </button>\n </div>\n </form>\n {config.branding ? (\n <div class=\"foot\">\n Powered by{' '}\n <a href=\"https://character.xyz\" target=\"_blank\" rel=\"noopener noreferrer\">\n Character XYZ\n </a>\n </div>\n ) : null}\n </div>\n );\n }\n\n // ---------------------------------------------------------------- call\n const s = state;\n const position = s?.position ?? 1;\n const progress = startPos > 1 ? (startPos - position) / (startPos - 1) : 0;\n const R = 74;\n const C = 2 * Math.PI * R;\n const remaining = s?.maxSeconds ? s.maxSeconds - elapsed : null;\n const agentState = s?.agentState ?? 'idle';\n const status = s?.speaking ? 'Speaking' : agentState === 'thinking' ? 'Thinking…' : 'Listening';\n const ended = !s || phase === 'ended' || phase === 'idle';\n const copy = endCopy(s?.endReason ?? null, name);\n\n return (\n <div class={`panel ${closing ? 'is-closing' : ''}`} part=\"panel\" role=\"dialog\" aria-label={`Call with ${name}`}>\n <div class={`stage ${wantsFace && faceStatus === 'ready' ? 'stage--face' : ''}`} ref={stage}>\n <div class=\"stage__figure\" style={{ opacity: phase === 'queued' ? 0.35 : 1, transition: 'opacity .6s' }}>\n <Portrait agent={agent} shot={MEDIUM} talking={!!s?.speaking} />\n {wantsFace ? (\n <div class={`stage__face ${faceStatus === 'ready' ? 'is-ready' : ''}`}>\n <FaceFrame client={client} call={call} state={s} src={config.faceUrl} onStatus={setFaceStatus} />\n </div>\n ) : null}\n </div>\n {live ? <div class=\"voice\" /> : null}\n <div class=\"stage__veil\" />\n <div class=\"stage__top\">\n {phase === 'live' ? (\n <span class={`badge ${remaining != null && remaining <= 60 ? 'badge--warn' : ''}`} role=\"timer\" aria-label=\"Call time\">\n <i />\n {remaining != null && remaining <= 60 ? `${clock(remaining)} left` : clock(elapsed)}\n </span>\n ) : (\n <span />\n )}\n <div style={{ display: 'flex', gap: '6px' }}>\n {canChat ? (\n <button class=\"icon-btn\" aria-label=\"Chat\" title=\"Chat\" onClick={() => open('chat')}>\n <ChatIcon size={18} />\n </button>\n ) : null}\n <button class=\"icon-btn\" aria-label=\"Minimise\" onClick={close}>\n <CloseIcon />\n </button>\n </div>\n </div>\n\n <div class=\"stage__bottom\" aria-live=\"polite\">\n {phase === 'joining' || phase === 'connecting' ? (\n <Fragment>\n <div class=\"stage__name\">{name}</div>\n <div class=\"stage__status\">\n <span class=\"spinner\" /> {phase === 'joining' ? 'Connecting…' : 'Joining…'}\n </div>\n </Fragment>\n ) : null}\n\n {phase === 'queued' ? (\n <Fragment>\n <div class=\"line\" role=\"status\" aria-label={`You are ${ordinal(position)} in line, ${eta(s?.etaSeconds ?? null)}`}>\n <svg width=\"168\" height=\"168\" viewBox=\"0 0 168 168\">\n <circle class=\"line__track\" cx=\"84\" cy=\"84\" r={R} fill=\"none\" stroke-width=\"7\" />\n <circle class=\"line__fill\" cx=\"84\" cy=\"84\" r={R} fill=\"none\" stroke-width=\"7\" stroke-linecap=\"round\" stroke-dasharray={C} stroke-dashoffset={C * (1 - Math.max(0.06, progress))} />\n </svg>\n <div>\n <div class=\"line__num\">{ordinal(position)}</div>\n <div class=\"line__lbl\">in line</div>\n </div>\n </div>\n <div class=\"title\">{name} is on other calls</div>\n <div class=\"note\">\n Your turn in {eta(s?.etaSeconds ?? null)}. We'll chime when it's time{canChat ? ', so feel free to keep chatting.' : '.'}\n </div>\n <div class=\"btn-row\">\n {canChat ? (\n <button class=\"btn btn--accent\" onClick={() => open('chat')}>\n <ChatIcon size={18} /> Keep chatting\n </button>\n ) : null}\n <button\n class=\"btn\"\n onClick={() => {\n void call?.hangUp();\n }}\n >\n Leave line\n </button>\n </div>\n </Fragment>\n ) : null}\n\n {phase === 'ready' ? (\n <Fragment>\n <div class=\"title\">{name} is ready for you</div>\n <div class=\"note\">Join within {s?.holdSeconds ?? 30} seconds.</div>\n <button class=\"btn btn--accent btn--glow\" onClick={() => call?.accept()}>\n <PhoneIcon size={18} /> Join call\n </button>\n </Fragment>\n ) : null}\n\n {phase === 'live' ? (\n <Fragment>\n <div class=\"stage__name\">{name}</div>\n <div class=\"stage__status\">\n {s?.speaking ? (\n <span class=\"wave\" aria-hidden=\"true\">\n {[0.6, 1, 0.75, 1, 0.55].map((k, i) => (\n <i key={i} style={{ '--k': k } as Record<string, number>} />\n ))}\n </span>\n ) : null}\n {s?.muted ? 'You are muted' : status}\n </div>\n <div class=\"captions\">\n {captions.slice(-2).map((c, i, arr) => (\n <div key={c.id} class={`captions__line ${i === arr.length - 1 ? 'captions__line--now' : ''}`}>\n {c.role === 'visitor' ? `You: ${c.text}` : c.text}\n </div>\n ))}\n </div>\n <div class=\"controls\">\n <div class=\"ctl\">\n <button class={`round ${s?.muted ? 'round--on' : ''}`} aria-pressed={s?.muted} aria-label={s?.muted ? 'Unmute' : 'Mute'} onClick={() => call?.setMuted(!s?.muted)}>\n {s?.muted ? <MicOffIcon size={22} /> : <MicIcon size={22} />}\n </button>\n <span class=\"round__label\">{s?.muted ? 'Unmute' : 'Mute'}</span>\n </div>\n <div class=\"ctl\">\n <button class=\"round round--end\" aria-label=\"End call\" onClick={() => void call?.hangUp()}>\n <HangUpIcon size={26} />\n </button>\n <span class=\"round__label\">End</span>\n </div>\n {s?.speaking ? (\n <div class=\"ctl\">\n <button class=\"round\" aria-label={`Interrupt ${name}`} onClick={() => call?.interrupt()}>\n <BackIcon size={22} />\n </button>\n <span class=\"round__label\">Interrupt</span>\n </div>\n ) : null}\n </div>\n </Fragment>\n ) : null}\n\n {ended ? (\n <Fragment>\n <div class=\"title\">{s ? copy.title : `Call ${name}`}</div>\n <div class=\"note\">{s ? (s.endReason === 'hangup' && elapsed ? `${clock(elapsed)} · ${copy.body}` : s.error ?? copy.body) : `Talk with ${name} in real time.`}</div>\n <div class=\"btn-row\">\n {canCall && s?.endReason !== 'credits' && s?.endReason !== 'unavailable' && s?.endReason !== 'daily_limit' ? (\n <button\n class=\"btn btn--accent\"\n onClick={() => {\n reset();\n void startCall();\n }}\n >\n <PhoneIcon size={18} /> {s ? 'Call again' : 'Start call'}\n </button>\n ) : null}\n {canChat ? (\n <button class=\"btn\" onClick={() => open('chat')}>\n <ChatIcon size={18} /> Chat\n </button>\n ) : null}\n </div>\n </Fragment>\n ) : null}\n </div>\n </div>\n </div>\n );\n}\n\n/** The place a visitor joined the line at, for the ring's progress. */\nfunction useMemoStart(call: Call | null, position: number): number {\n const ref = useRef<{ call: Call | null; start: number }>({ call: null, start: position });\n if (ref.current.call !== call) ref.current = { call, start: position };\n if (position > ref.current.start) ref.current.start = position;\n return ref.current.start;\n}\n\n","/**\n * The widget's whole stylesheet. It lives in the Shadow DOM: nothing here\n * reaches the brand's page and nothing of theirs reaches in, except the\n * `::part()` names documented in the README.\n *\n * Tokens are custom properties on :host, set from the config at mount\n * (`--cx-accent`, `--cx-radius`, `--cx-font`) — a brand overrides any of\n * them from outside with `character-xyz { --cx-accent: … }`.\n */\nexport const CSS = /* css */ `\n:host {\n --cx-accent: #7c5cff;\n --cx-accent-ink: #fff;\n --cx-radius: 24px;\n --cx-font: ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n --cx-bg: rgba(255, 255, 255, 0.82);\n --cx-solid: #ffffff;\n --cx-ink: #14121a;\n --cx-ink-2: #5b5866;\n --cx-ink-3: #8d8a98;\n --cx-line: rgba(20, 18, 26, 0.08);\n --cx-bubble: rgba(20, 18, 26, 0.05);\n --cx-shadow: 0 24px 64px -12px rgba(23, 16, 52, 0.28), 0 4px 16px -4px rgba(23, 16, 52, 0.12);\n --cx-danger: #ef4444;\n --cx-ok: #22c55e;\n --cx-ease: cubic-bezier(0.22, 1, 0.36, 1);\n --cx-spring: cubic-bezier(0.34, 1.4, 0.64, 1);\n all: initial;\n position: fixed;\n z-index: var(--cx-z, 2147483000);\n bottom: var(--cx-oy, 20px);\n font-family: var(--cx-font);\n color: var(--cx-ink);\n -webkit-font-smoothing: antialiased;\n line-height: 1.45;\n}\n:host([data-side=\"right\"]) { right: var(--cx-ox, 20px); }\n:host([data-side=\"left\"]) { left: var(--cx-ox, 20px); }\n:host([data-theme=\"dark\"]) {\n --cx-bg: rgba(22, 20, 30, 0.78);\n --cx-solid: #16141e;\n --cx-ink: #f4f2fa;\n --cx-ink-2: #b7b3c6;\n --cx-ink-3: #85819a;\n --cx-line: rgba(255, 255, 255, 0.09);\n --cx-bubble: rgba(255, 255, 255, 0.07);\n --cx-shadow: 0 24px 64px -12px rgba(0, 0, 0, 0.6), 0 4px 16px -4px rgba(0, 0, 0, 0.4);\n}\n*, *::before, *::after { box-sizing: border-box; }\nbutton { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }\nbutton:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px solid var(--cx-accent); outline-offset: 2px; }\n.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n\n/* ------------------------------------------------------------ launcher */\n.dock { display: flex; align-items: flex-end; gap: 10px; }\n/* She sits in the corner and never moves; the buttons grow away from her. */\n:host([data-side=\"right\"]) .dock { flex-direction: row-reverse; }\n.presence {\n position: relative; width: 60px; height: 60px; border-radius: 50%; flex: none;\n transition: transform .5s var(--cx-spring);\n}\n.presence:hover { transform: translateY(-2px) scale(1.05); }\n/* ---- display: half body — her cut-out from the waist up, no frame, fading out at the waist */\n.presence--half { width: 128px; height: 170px; border-radius: 0; filter: drop-shadow(0 10px 18px rgba(15, 10, 30, 0.28)); }\n.presence--half .presence__face { border-radius: 0; background: none; box-shadow: none;\n -webkit-mask-image: linear-gradient(to bottom, #000 70%, transparent 98%); mask-image: linear-gradient(to bottom, #000 70%, transparent 98%); }\n/* ---- display: full body — she stands in the corner, feet on the edge, a soft shadow under her */\n.presence--full { width: 132px; height: 300px; border-radius: 0; filter: drop-shadow(0 6px 14px rgba(15, 10, 30, 0.22)); }\n.presence--full .presence__face { border-radius: 0; background: none; box-shadow: none; }\n.presence--full::before { content: \"\"; position: absolute; left: 22%; right: 22%; bottom: -4px; height: 10px; border-radius: 50%;\n background: radial-gradient(closest-side, rgba(15, 10, 30, 0.35), transparent); }\n.presence--half:hover, .presence--full:hover { transform: translateY(-3px); }\n.presence--half .presence__dot { top: 10px; bottom: auto; right: 26px; }\n.presence--full .presence__dot { top: 6px; bottom: auto; right: 34px; }\n.presence--half .testmode, .presence--full .testmode { top: -6px; bottom: auto; }\n.presence--full .presence__label { top: 22%; }\n.presence--half .presence__badge, .presence--full .presence__badge { top: 0; right: 4px; }\n.presence--half.presence--live::after, .presence--full.presence--live::after { display: none; }\n.presence--half.presence--live, .presence--full.presence--live { animation: cx-figure-glow 1.8s ease-in-out infinite; }\n.dock--half .greeting { bottom: 186px; }\n.dock--full .greeting { bottom: 316px; }\n\n/* What a tap does, on hover and keyboard focus. */\n.presence__label {\n position: absolute; top: 50%; transform: translate(6px, -50%); opacity: 0; pointer-events: none; white-space: nowrap;\n padding: 7px 12px; border-radius: 999px; font-size: 13px; font-weight: 600; letter-spacing: -0.005em;\n color: var(--cx-ink); background: var(--cx-solid); border: 1px solid var(--cx-line); box-shadow: var(--cx-shadow);\n transition: opacity .2s, transform .3s var(--cx-ease);\n}\n:host([data-side=\"right\"]) .presence__label { right: calc(100% + 10px); }\n:host([data-side=\"left\"]) .presence__label { left: calc(100% + 10px); transform: translate(-6px, -50%); }\n.presence:hover .presence__label, .presence:focus-visible .presence__label { opacity: 1; transform: translate(0, -50%); }\n/* Waiting in line: the place, on her. */\n.presence__badge {\n position: absolute; top: -4px; right: -4px; min-width: 22px; height: 22px; padding: 0 6px; border-radius: 11px;\n display: grid; place-items: center; font-size: 12px; font-weight: 800; font-variant-numeric: tabular-nums;\n background: var(--cx-accent); color: var(--cx-accent-ink); box-shadow: 0 0 0 2px var(--cx-solid);\n}\n/* A call is open (or waiting): she breathes, so the way back is obvious. */\n.presence--live::after { content: \"\"; position: absolute; inset: -5px; border-radius: 50%; border: 2px solid var(--cx-accent); animation: cx-glow-ring 1.8s ease-out infinite; }\n.empty__call { margin-top: 4px; height: 40px; }\n.presence__ring {\n position: absolute; inset: -3px; border-radius: 50%;\n background: conic-gradient(from var(--cx-angle, 0deg), var(--cx-accent), color-mix(in oklab, var(--cx-accent) 30%, #fff), var(--cx-accent));\n animation: cx-spin 6s linear infinite;\n}\n.presence__face {\n position: absolute; inset: 0; border-radius: 50%; overflow: hidden;\n background: radial-gradient(120% 90% at 50% 10%, color-mix(in oklab, var(--cx-accent) 22%, var(--cx-solid)), var(--cx-solid));\n box-shadow: inset 0 0 0 3px var(--cx-solid);\n}\n.presence__dot {\n position: absolute; right: 3px; bottom: 3px; width: 14px; height: 14px; border-radius: 50%;\n background: var(--cx-ok); box-shadow: 0 0 0 3px var(--cx-solid);\n}\n.acts { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }\n/* Call, the primary action, sits next to her on either side. */\n:host([data-side=\"left\"]) .acts { flex-direction: row-reverse; }\n.act {\n position: relative; display: inline-flex; align-items: center; justify-content: center;\n height: 44px; min-width: 44px; padding: 0 12px; border-radius: 999px;\n color: var(--cx-ink); background: var(--cx-bg);\n backdrop-filter: blur(18px) saturate(1.6); -webkit-backdrop-filter: blur(18px) saturate(1.6);\n border: 1px solid var(--cx-line); box-shadow: var(--cx-shadow);\n animation: cx-rise .6s var(--cx-ease) both;\n transition: transform .35s var(--cx-spring), background .2s, box-shadow .2s;\n}\n.act + .act { animation-delay: .06s; }\n.act:hover { transform: translateY(-2px); }\n.act:active { transform: scale(.94); }\n.act--call { background: var(--cx-accent); color: var(--cx-accent-ink); border-color: transparent; }\n.act--call:hover { background: color-mix(in oklab, var(--cx-accent) 88%, #000); }\n/* The word folds away to an icon; hover, keyboard focus and a first visit unfold it. */\n.act__label {\n max-width: 0; opacity: 0; overflow: hidden; white-space: nowrap;\n font-size: 14px; font-weight: 600; letter-spacing: -0.005em;\n transition: max-width .35s var(--cx-ease), opacity .2s, margin .35s var(--cx-ease);\n}\n.act:hover .act__label, .act:focus-visible .act__label, .acts--labelled .act__label { max-width: 120px; opacity: 1; margin-left: 7px; }\n/* Waiting in line: the place, on the button. */\n.act__badge {\n position: absolute; top: -5px; right: -5px; min-width: 20px; height: 20px; padding: 0 5px; border-radius: 10px;\n display: grid; place-items: center; font-size: 11px; font-weight: 800; font-variant-numeric: tabular-nums;\n background: var(--cx-solid); color: var(--cx-ink); box-shadow: 0 0 0 2px var(--cx-accent);\n}\n/* On a call (or ready): the button breathes so the way back is obvious. */\n.act--live::after { content: \"\"; position: absolute; inset: -4px; border-radius: inherit; border: 2px solid var(--cx-accent); opacity: .5; animation: cx-glow-ring 1.8s ease-out infinite; }\n.greeting {\n position: absolute; bottom: 76px; width: max-content; max-width: 260px; padding: 12px 34px 12px 14px; border-radius: 18px;\n background: var(--cx-solid); box-shadow: var(--cx-shadow); border: 1px solid var(--cx-line);\n font-size: 14px; color: var(--cx-ink); animation: cx-pop .55s var(--cx-spring) both; cursor: pointer;\n}\n:host([data-side=\"right\"]) .greeting { right: 0; border-bottom-right-radius: 6px; }\n:host([data-side=\"left\"]) .greeting { left: 0; border-bottom-left-radius: 6px; }\n.greeting__close { position: absolute; top: 6px; right: 6px; width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; color: var(--cx-ink-3); }\n.greeting__close:hover { background: var(--cx-bubble); color: var(--cx-ink); }\n\n/* ------------------------------------------------------------ panel */\n.panel {\n position: absolute; bottom: 0; width: 392px; height: min(640px, calc(100vh - 40px));\n display: flex; flex-direction: column; overflow: hidden;\n border-radius: var(--cx-radius); background: var(--cx-bg); border: 1px solid var(--cx-line);\n backdrop-filter: blur(24px) saturate(1.7); -webkit-backdrop-filter: blur(24px) saturate(1.7);\n box-shadow: var(--cx-shadow);\n transform-origin: bottom right;\n animation: cx-open .5s var(--cx-ease) both;\n}\n:host([data-side=\"right\"]) .panel { right: 0; }\n:host([data-side=\"left\"]) .panel { left: 0; transform-origin: bottom left; }\n.panel.is-closing { animation: cx-close .22s ease-in both; }\n\n.head { display: flex; align-items: center; gap: 12px; padding: 14px 14px 12px 16px; border-bottom: 1px solid var(--cx-line); }\n.head__face { position: relative; width: 42px; height: 42px; border-radius: 50%; overflow: hidden; flex: none;\n background: radial-gradient(120% 90% at 50% 10%, color-mix(in oklab, var(--cx-accent) 22%, var(--cx-solid)), var(--cx-solid)); }\n.head__who { flex: 1; min-width: 0; }\n.head__name { font-size: 15px; font-weight: 650; letter-spacing: -0.01em; }\n.head__sub { font-size: 12.5px; color: var(--cx-ink-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; gap: 6px; }\n.head__sub i { width: 7px; height: 7px; border-radius: 50%; background: var(--cx-ok); flex: none; }\n.icon-btn { width: 38px; height: 38px; border-radius: 12px; display: grid; place-items: center; color: var(--cx-ink-2); transition: background .2s, color .2s; }\n.icon-btn:hover { background: var(--cx-bubble); color: var(--cx-ink); }\n.icon-btn--accent { background: var(--cx-accent); color: var(--cx-accent-ink); }\n.icon-btn--accent:hover { background: color-mix(in oklab, var(--cx-accent) 88%, #000); color: var(--cx-accent-ink); }\n\n/* ------------------------------------------------------------ chat */\n.log { flex: 1; overflow-y: auto; padding: 18px 16px 8px; display: flex; flex-direction: column; gap: 6px; scroll-behavior: smooth; overscroll-behavior: contain; }\n.log::-webkit-scrollbar { width: 8px; } .log::-webkit-scrollbar-thumb { background: var(--cx-line); border-radius: 8px; }\n.msg { max-width: 84%; padding: 9px 13px; border-radius: 18px; font-size: 14.5px; word-wrap: break-word; animation: cx-msg .35s var(--cx-ease) both; }\n.msg p { margin: 0; } .msg p + p, .msg p + ul, .msg ul + p { margin-top: 8px; }\n.msg ul { margin: 0; padding-left: 18px; }\n.msg code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .9em; padding: 1px 5px; border-radius: 6px; background: var(--cx-bubble); }\n.msg a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }\n.msg--agent { align-self: flex-start; background: var(--cx-bubble); border-bottom-left-radius: 6px; }\n.msg--visitor { align-self: flex-end; background: var(--cx-accent); color: var(--cx-accent-ink); border-bottom-right-radius: 6px; }\n.msg--visitor + .msg--visitor, .msg--agent + .msg--agent { margin-top: -2px; }\n.msg--failed { opacity: .65; }\n.msg__retry { display: inline-flex; align-items: center; gap: 4px; margin-top: 4px; font-size: 12px; color: var(--cx-danger); align-self: flex-end; }\n.msg__why { margin-top: 4px; font-size: 12px; color: var(--cx-ink-2); align-self: flex-end; text-align: right; max-width: 85%; }\n.caret::after { content: \"\"; display: inline-block; width: 7px; height: 1.05em; margin-left: 2px; vertical-align: -2px; border-radius: 2px; background: currentColor; opacity: .55; animation: cx-blink 1s steps(2) infinite; }\n.typing { display: inline-flex; gap: 4px; padding: 13px 14px; }\n.typing i { width: 7px; height: 7px; border-radius: 50%; background: var(--cx-ink-3); animation: cx-bounce 1.2s var(--cx-ease) infinite; }\n.typing i:nth-child(2) { animation-delay: .15s; } .typing i:nth-child(3) { animation-delay: .3s; }\n.empty { margin: auto 0 8px; display: flex; flex-direction: column; align-items: center; text-align: center; gap: 10px; padding: 10px 8px 4px; }\n.empty__face { width: 96px; height: 96px; border-radius: 50%; overflow: hidden; position: relative; box-shadow: 0 0 0 4px var(--cx-solid), 0 0 0 6px color-mix(in oklab, var(--cx-accent) 45%, transparent);\n background: radial-gradient(120% 90% at 50% 10%, color-mix(in oklab, var(--cx-accent) 22%, var(--cx-solid)), var(--cx-solid)); }\n.empty__title { font-size: 17px; font-weight: 650; letter-spacing: -0.015em; }\n.empty__body { font-size: 13.5px; color: var(--cx-ink-2); max-width: 280px; }\n.chips { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-top: 4px; }\n.chip { display: inline-flex; align-items: center; gap: 6px; padding: 7px 12px; border-radius: 999px; font-size: 13px; border: 1px solid var(--cx-line); background: var(--cx-solid); transition: border-color .2s, transform .3s var(--cx-spring); }\n.chip:hover { border-color: color-mix(in oklab, var(--cx-accent) 55%, transparent); transform: translateY(-1px); }\n.chip svg { color: var(--cx-accent); }\n/* Quick replies sit under her message, on her side, and arrive just after it. */\n.chips--start { justify-content: flex-start; margin: 2px 0 4px; animation: cx-rise .4s var(--cx-ease) .12s both; }\n/* The details card: in the conversation, on her side, never a gate. */\n.card { align-self: stretch; margin: 2px 0 6px; padding: 14px; border-radius: 16px; background: var(--cx-solid); border: 1px solid var(--cx-line); display: flex; flex-direction: column; gap: 10px; animation: cx-rise .35s var(--cx-ease) both; }\n.card__title { font-size: 14.5px; font-weight: 650; letter-spacing: -0.01em; }\n.card__note { font-size: 12.5px; color: var(--cx-ink-2); margin-top: -6px; }\n.card__field { display: flex; flex-direction: column; gap: 5px; font-size: 12px; font-weight: 600; color: var(--cx-ink-2); }\n.card__field i { font-style: normal; font-weight: 400; color: var(--cx-ink-3); }\n.card__field input { height: 40px; padding: 0 12px; border-radius: 10px; border: 1px solid var(--cx-line); background: var(--cx-bubble); color: var(--cx-ink); font: inherit; font-size: 14px; font-weight: 400; outline: none; transition: border-color .2s; }\n.card__field input:focus { border-color: var(--cx-accent); }\n.card__field input[aria-invalid=\"true\"] { border-color: #e5484d; }\n.card__field em { font-style: normal; font-weight: 400; color: #e5484d; }\n.card__consent { font-size: 11.5px; line-height: 1.45; color: var(--cx-ink-3); }\n.card__consent a { color: var(--cx-ink-2); text-decoration: underline; }\n.card__failed { font-size: 12.5px; color: #e5484d; }\n.card__actions { display: flex; gap: 8px; }\n.btn--sm { height: 36px; padding: 0 16px; font-size: 13.5px; }\n.btn--ghost { background: transparent; color: var(--cx-ink-2); }\n.btn--ghost:hover { background: var(--cx-bubble); }\n.notice { align-self: flex-start; display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--cx-ink-2); padding: 2px 4px 6px; animation: cx-rise .35s var(--cx-ease) both; }\n.notice svg { color: var(--cx-ok); }\n.chip--call { color: var(--cx-accent); border-color: color-mix(in oklab, var(--cx-accent) 45%, transparent); font-weight: 600; }\n\n.compose { padding: 10px 12px 12px; }\n.compose__box { display: flex; align-items: flex-end; gap: 8px; padding: 6px 6px 6px 14px; border-radius: 20px; background: var(--cx-solid); border: 1px solid var(--cx-line); transition: border-color .2s, box-shadow .2s; }\n.compose__box:focus-within { border-color: color-mix(in oklab, var(--cx-accent) 60%, transparent); box-shadow: 0 0 0 4px color-mix(in oklab, var(--cx-accent) 14%, transparent); }\n.compose textarea { flex: 1; resize: none; border: 0; outline: 0; background: transparent; font: inherit; font-size: 14.5px; color: var(--cx-ink); max-height: 120px; padding: 7px 0; line-height: 1.4; }\n.compose textarea::placeholder { color: var(--cx-ink-3); }\n.send { width: 34px; height: 34px; border-radius: 50%; display: grid; place-items: center; background: var(--cx-accent); color: var(--cx-accent-ink); flex: none; transition: transform .3s var(--cx-spring), opacity .2s; }\n.send:disabled { opacity: .35; cursor: default; }\n.send:not(:disabled):active { transform: scale(.9); }\n.foot { text-align: center; font-size: 11px; color: var(--cx-ink-3); padding: 0 0 10px; }\n.foot a { color: inherit; text-decoration: none; font-weight: 600; }\n\n/* ------------------------------------------------------------ banners (queue / ready while chatting) */\n.banner { margin: 10px 12px 0; padding: 10px 10px 10px 14px; border-radius: 16px; display: flex; align-items: center; gap: 10px; font-size: 13px;\n background: color-mix(in oklab, var(--cx-accent) 12%, var(--cx-solid)); border: 1px solid color-mix(in oklab, var(--cx-accent) 25%, transparent); animation: cx-rise .4s var(--cx-ease) both; }\n.banner__text { flex: 1; min-width: 0; } .banner__text b { font-weight: 650; }\n.banner .btn { height: 32px; padding: 0 12px; font-size: 13px; }\n\n/* ------------------------------------------------------------ call */\n.stage { flex: 1; position: relative; display: flex; flex-direction: column; overflow: hidden;\n background: radial-gradient(120% 70% at 50% 18%, color-mix(in oklab, var(--cx-accent) 26%, var(--cx-solid)) 0%, var(--cx-solid) 70%); }\n.stage__figure { position: absolute; inset: 0; }\n.stage__figure .portrait { position: absolute; inset: 0; }\n/* The app's own face renderer, faded in over the portrait once it is drawing. */\n.stage__face { position: absolute; inset: 0; opacity: 0; transition: opacity .5s ease; pointer-events: none; }\n.stage__face.is-ready { opacity: 1; }\n/* Over the skin's own (usually dark) backdrop the top controls go light. */\n.stage--face .stage__top .icon-btn { color: rgba(255, 255, 255, 0.85); }\n.stage--face .stage__top .icon-btn:hover { color: #fff; background: rgba(255, 255, 255, 0.14); }\n.stage--face .badge { background: rgba(10, 8, 16, 0.45); color: #fff; border-color: rgba(255, 255, 255, 0.12); }\n.face-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: transparent; color-scheme: normal; }\n.stage__veil { position: absolute; left: 0; right: 0; bottom: 0; height: 58%; background: linear-gradient(to top, var(--cx-solid) 18%, color-mix(in oklab, var(--cx-solid) 0%, transparent)); pointer-events: none; }\n.stage__top { position: relative; display: flex; justify-content: space-between; align-items: center; padding: 14px 14px 0 16px; }\n.badge { display: inline-flex; align-items: center; gap: 7px; height: 28px; padding: 0 11px; border-radius: 999px; font-size: 12.5px; font-weight: 600; background: var(--cx-bg); backdrop-filter: blur(12px); border: 1px solid var(--cx-line); font-variant-numeric: tabular-nums; }\n.badge i { width: 7px; height: 7px; border-radius: 50%; background: var(--cx-danger); animation: cx-pulse 1.6s ease-in-out infinite; }\n.badge--warn { color: var(--cx-danger); }\n.stage__bottom { position: relative; margin-top: auto; padding: 0 18px 18px; display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center; }\n.stage__name { font-size: 21px; font-weight: 700; letter-spacing: -0.02em; }\n.stage__status { font-size: 13.5px; color: var(--cx-ink-2); min-height: 20px; display: inline-flex; align-items: center; gap: 8px; }\n.wave { display: inline-flex; align-items: center; gap: 3px; height: 16px; }\n.wave i { width: 3px; border-radius: 3px; background: var(--cx-accent); height: calc(4px + var(--cx-lvl, 0) * 12px * var(--k, 1)); transition: height .08s linear; }\n.captions { width: 100%; min-height: 44px; font-size: 14.5px; color: var(--cx-ink); display: flex; flex-direction: column; gap: 2px; }\n.captions__line { opacity: .55; font-size: 13px; } .captions__line--now { opacity: 1; font-size: 15px; font-weight: 500; }\n.controls { display: flex; gap: 14px; align-items: center; justify-content: center; margin-top: 4px; }\n.round { width: 56px; height: 56px; border-radius: 50%; display: grid; place-items: center; background: var(--cx-bg); border: 1px solid var(--cx-line); backdrop-filter: blur(12px); transition: transform .3s var(--cx-spring), background .2s; }\n.round:hover { transform: translateY(-2px); }\n.round:active { transform: scale(.94); }\n.round--on { background: var(--cx-ink); color: var(--cx-solid); }\n.round--end { background: var(--cx-danger); color: #fff; border-color: transparent; width: 64px; height: 64px; }\n.round__label { font-size: 11.5px; color: var(--cx-ink-2); margin-top: 6px; }\n.ctl { display: flex; flex-direction: column; align-items: center; }\n\n.voice { position: absolute; left: 50%; top: 34%; width: 240px; height: 240px; margin: -120px 0 0 -120px; border-radius: 50%; pointer-events: none;\n background: radial-gradient(closest-side, color-mix(in oklab, var(--cx-accent) 30%, transparent), transparent);\n transform: scale(calc(0.85 + var(--cx-lvl, 0) * 0.5)); opacity: calc(0.25 + var(--cx-lvl, 0) * 0.75); transition: transform .1s linear, opacity .1s linear; }\n\n/* queue */\n.line { position: relative; width: 168px; height: 168px; display: grid; place-items: center; margin: 4px auto 0; }\n.line svg { position: absolute; inset: 0; transform: rotate(-90deg); }\n.line__track { stroke: var(--cx-line); }\n.line__fill { stroke: var(--cx-accent); transition: stroke-dashoffset .8s var(--cx-ease); }\n.line__num { font-size: 46px; font-weight: 750; letter-spacing: -0.04em; line-height: 1; font-variant-numeric: tabular-nums; }\n.line__lbl { font-size: 12px; color: var(--cx-ink-2); text-transform: uppercase; letter-spacing: .08em; margin-top: 4px; }\n.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 44px; padding: 0 18px; border-radius: 999px; font-size: 14.5px; font-weight: 600; background: var(--cx-bubble); transition: transform .3s var(--cx-spring), background .2s; }\n.btn:hover { background: color-mix(in oklab, var(--cx-ink) 10%, transparent); }\n.btn:active { transform: scale(.97); }\n.btn--accent { background: var(--cx-accent); color: var(--cx-accent-ink); }\n.btn--accent:hover { background: color-mix(in oklab, var(--cx-accent) 88%, #000); }\n.btn--glow { box-shadow: 0 0 0 0 color-mix(in oklab, var(--cx-accent) 55%, transparent); animation: cx-glow 1.6s ease-out infinite; }\n.btn-row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }\n.note { font-size: 13.5px; color: var(--cx-ink-2); max-width: 300px; }\n.title { font-size: 19px; font-weight: 700; letter-spacing: -0.02em; }\n.spinner { width: 22px; height: 22px; border-radius: 50%; border: 2.5px solid var(--cx-line); border-top-color: var(--cx-accent); animation: cx-spin 0.8s linear infinite; }\n\n/* ------------------------------------------------------------ portrait */\n.portrait { position: relative; width: 100%; height: 100%; overflow: hidden; }\n.portrait__media { position: absolute; max-width: none; transition: opacity .35s ease; user-select: none; -webkit-user-drag: none; }\n.portrait--initial { display: grid; place-items: center; font-size: 26px; font-weight: 700; color: var(--cx-accent); }\n\n/* ------------------------------------------------------------ test-mode ribbon */\n.dock { position: relative; }\n/* A small tag on the portrait's lower edge: present, never in the way. */\n.testmode { position: absolute; left: 50%; bottom: -7px; transform: translateX(-50%); font-size: 8.5px; font-weight: 800; letter-spacing: .08em; line-height: 1; padding: 3px 5px; border-radius: 5px; background: #f59e0b; color: #1c1206; box-shadow: 0 0 0 2px var(--cx-solid); pointer-events: none; }\n\n/* ------------------------------------------------------------ phones: a bottom sheet */\n@media (max-width: 520px) {\n :host([data-open]) { left: 0 !important; right: 0 !important; bottom: 0 !important; }\n .panel { position: fixed; left: 0; right: 0; bottom: 0; width: 100%; height: min(92dvh, 760px); border-radius: var(--cx-radius) var(--cx-radius) 0 0; padding-bottom: env(safe-area-inset-bottom); animation-name: cx-sheet; }\n .presence { width: 56px; height: 56px; }\n .presence--half { width: 104px; height: 138px; }\n .presence--full { width: 100px; height: 228px; }\n .dock--half .greeting { bottom: 152px; }\n .dock--full .greeting { bottom: 242px; }\n}\n\n@keyframes cx-spin { to { transform: rotate(360deg); } }\n@keyframes cx-rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }\n@keyframes cx-pop { from { opacity: 0; transform: translateY(8px) scale(.92); } to { opacity: 1; transform: none; } }\n@keyframes cx-open { from { opacity: 0; transform: translateY(14px) scale(.94); filter: blur(4px); } to { opacity: 1; transform: none; filter: none; } }\n@keyframes cx-close { to { opacity: 0; transform: translateY(10px) scale(.96); } }\n@keyframes cx-sheet { from { transform: translateY(100%); } to { transform: none; } }\n@keyframes cx-msg { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }\n@keyframes cx-blink { 50% { opacity: 0; } }\n@keyframes cx-bounce { 0%, 60%, 100% { transform: translateY(0); opacity: .45; } 30% { transform: translateY(-4px); opacity: 1; } }\n@keyframes cx-pulse { 50% { opacity: .35; } }\n@keyframes cx-figure-glow { 0%, 100% { filter: drop-shadow(0 0 0 transparent); } 50% { filter: drop-shadow(0 0 12px var(--cx-accent)); } }\n@keyframes cx-glow-ring { 0% { transform: scale(1); opacity: .55; } 100% { transform: scale(1.35); opacity: 0; } }\n@keyframes cx-glow { 0% { box-shadow: 0 0 0 0 color-mix(in oklab, var(--cx-accent) 50%, transparent); } 100% { box-shadow: 0 0 0 16px transparent; } }\n\n@media (prefers-reduced-motion: reduce) {\n *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }\n .presence__ring { animation: none; }\n}\n`;\n","import { CharacterXYZ, CxError, type InitOptions } from '@characterxyz/web';\nimport { render } from 'preact';\n\nimport { App, type AppApi, type View } from './app.js';\nimport { applyLayer, DEFAULTS, fromAttributes, type WidgetConfig } from './config.js';\nimport { CSS } from './styles.js';\n\nexport const TAG = 'character-xyz';\n\nexport interface MountOptions extends InitOptions, Partial<WidgetConfig> {\n /** Where the element goes. Default `document.body`. */\n container?: HTMLElement;\n}\n\n/** Ink that reads on the accent: white on dark accents, near-black on light ones. */\nexport function inkFor(color: string): string {\n const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim());\n if (!m) return '#ffffff';\n const hex = m[1]!.length === 3 ? m[1]!.replace(/./g, (c) => c + c) : m[1]!;\n const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)) as [number, number, number];\n const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n return lum > 0.45 ? '#14121a' : '#ffffff';\n}\n\n/** Relative luminance of a CSS rgb()/rgba() colour, or null when transparent / unreadable. */\nexport function luminanceOf(color: string): number | null {\n const m = /rgba?\\(\\s*([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)(?:[,\\s/]+([\\d.]+%?))?\\s*\\)/.exec(color);\n if (!m) return null;\n const alpha = m[4] === undefined ? 1 : m[4].endsWith('%') ? parseFloat(m[4]) / 100 : parseFloat(m[4]);\n if (alpha < 0.5) return null;\n const [r, g, b] = [m[1], m[2], m[3]].map((v) => Number(v) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)) as [number, number, number];\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\n/**\n * `auto` means \"look like you belong on THIS page\": a dark site gets the dark\n * widget whatever the visitor's system says. The page's own background\n * decides; only a transparent one falls back to the system preference.\n */\nfunction pageIsDark(mq: MediaQueryList | null): boolean {\n for (const el of [document.body, document.documentElement]) {\n if (!el) continue;\n const lum = luminanceOf(getComputedStyle(el).backgroundColor);\n if (lum !== null) return lum < 0.22;\n }\n return !!mq?.matches;\n}\n\nconst ATTRS = ['publishable-key', 'agent', 'api-url', 'position', 'mode', 'accent', 'greeting', 'open'];\n\n/**\n * `<character-xyz publishable-key=\"cxyz_pk_live_…\"></character-xyz>`\n *\n * Events (bubbling, composed): `cx-ready` {agent}, `cx-open` {view},\n * `cx-close`, `cx-call` {phase}, `cx-error` {code, message}.\n * Methods: `open('chat' | 'call')`, `close()`; property `client` once ready.\n */\nexport class CharacterXYZElement extends HTMLElement {\n static get observedAttributes() {\n return ATTRS;\n }\n\n /** Set before the element connects (what `mount()` does). */\n options: MountOptions | null = null;\n client: CharacterXYZ | null = null;\n private api: AppApi | null = null;\n private pendingOpen: View | null = null;\n private booted = false;\n private mq: MediaQueryList | null = null;\n private stage: HTMLDivElement | null = null;\n\n connectedCallback() {\n if (this.booted) return;\n this.booted = true;\n const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });\n const style = document.createElement('style');\n style.textContent = CSS;\n this.stage = document.createElement('div');\n root.replaceChildren(style, this.stage);\n // Out of the page's way until there is something to show.\n this.style.display = 'none';\n // The page's own work first: start once the browser is idle.\n const idle = (window as unknown as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number }).requestIdleCallback;\n if (idle) idle(() => void this.boot(), { timeout: 2000 });\n else setTimeout(() => void this.boot(), 200);\n }\n\n disconnectedCallback() {\n if (this.stage) render(null, this.stage);\n this.client?.destroy();\n this.client = null;\n this.mq?.removeEventListener('change', this.onSchemeChange);\n this.booted = false;\n }\n\n open(view: 'chat' | 'call' = 'chat') {\n if (this.api) this.api.open(view);\n else this.pendingOpen = view;\n }\n\n close() {\n this.api?.close();\n }\n\n private fire(name: string, detail?: unknown) {\n this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));\n }\n\n private onSchemeChange = () => requestAnimationFrame(this.onScheme);\n\n private onScheme = () => {\n if (this.dataset.mode === 'auto') this.dataset.theme = pageIsDark(this.mq) ? 'dark' : 'light';\n };\n\n private async boot() {\n const opts: MountOptions = { ...(this.options ?? {}) };\n const attrs = fromAttributes(Array.from(this.attributes));\n const publishableKey = opts.publishableKey ?? (attrs.publishableKey as string | undefined);\n try {\n this.client = await CharacterXYZ.init({\n publishableKey,\n getSessionToken: opts.getSessionToken,\n agentId: opts.agentId ?? (attrs.agent as string | undefined),\n apiUrl: opts.apiUrl ?? (attrs.apiUrl as string | undefined),\n storage: opts.storage,\n });\n } catch (e) {\n const err = e instanceof CxError ? e : new CxError('unknown', String((e as Error)?.message ?? e));\n // The widget stays hidden: a broken embed must never put an error box\n // on the brand's page. The console and the event say why.\n console.warn(`[characterxyz] widget not shown: ${err.message}`);\n this.fire('cx-error', { code: err.code, message: err.message });\n return;\n }\n if (!this.isConnected) {\n this.client.destroy();\n return;\n }\n const client = this.client;\n // Designer appearance, then attributes, then mount() options.\n let config = applyLayer(DEFAULTS, client.appearance as Record<string, unknown>);\n config = applyLayer(config, attrs);\n config = applyLayer(config, opts as unknown as Record<string, unknown>);\n if (!(config.showChat && client.features.chat) && !(config.showCall && client.features.call)) {\n console.warn('[characterxyz] widget not shown: neither chat nor calls are enabled for this site');\n return;\n }\n this.applyTokens(config);\n client.on('call', (c) => {\n if (!c) return;\n c.on('state', (s) => this.fire('cx-call', { phase: s.phase, position: s.position, endReason: s.endReason }));\n });\n client.on('error', (e) => this.fire('cx-error', { code: e.code, message: e.message }));\n this.style.display = '';\n render(\n <App\n client={client}\n config={config}\n bind={(api) => {\n this.api = api;\n if (this.pendingOpen && this.pendingOpen !== 'closed') {\n api.open(this.pendingOpen);\n this.pendingOpen = null;\n }\n }}\n onView={(v) => {\n if (v === 'closed') {\n this.removeAttribute('data-open');\n this.fire('cx-close');\n } else {\n this.setAttribute('data-open', '');\n this.fire('cx-open', { view: v });\n }\n }}\n />,\n this.stage!,\n );\n if (config.open) this.setAttribute('data-open', '');\n this.fire('cx-ready', { agent: { id: client.agent.id, name: client.agent.name }, features: client.features });\n }\n\n private applyTokens(c: WidgetConfig) {\n this.dataset.side = c.position === 'bottom-left' ? 'left' : 'right';\n this.dataset.mode = c.mode;\n if (c.mode === 'auto') {\n this.mq = matchMedia('(prefers-color-scheme: dark)');\n // A site's own dark mode usually follows the system, so re-read the page then.\n this.mq.addEventListener('change', this.onSchemeChange);\n this.dataset.theme = pageIsDark(this.mq) ? 'dark' : 'light';\n } else {\n this.dataset.theme = c.mode;\n }\n const set = (k: string, v: string) => this.style.setProperty(k, v);\n set('--cx-accent', c.accent);\n set('--cx-accent-ink', inkFor(c.accent));\n set('--cx-radius', `${c.radius}px`);\n if (c.font) set('--cx-font', c.font);\n set('--cx-ox', `${c.offsetX}px`);\n set('--cx-oy', `${c.offsetY}px`);\n set('--cx-z', String(c.zIndex));\n }\n}\n\nexport function define() {\n if (typeof customElements !== 'undefined' && !customElements.get(TAG)) customElements.define(TAG, CharacterXYZElement);\n}\n\nexport interface WidgetHandle {\n element: CharacterXYZElement;\n open(view?: 'chat' | 'call'): void;\n close(): void;\n destroy(): void;\n}\n\n/** Put the widget on the page. One per page is the norm; a second replaces nothing. */\nexport function mount(options: MountOptions): WidgetHandle {\n define();\n const el = document.createElement(TAG) as CharacterXYZElement;\n el.options = options;\n (options.container ?? document.body).appendChild(el);\n return {\n element: el,\n open: (v) => el.open(v),\n close: () => el.close(),\n destroy: () => el.remove(),\n };\n}\n"],"mappings":"+lBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,WAAAE,KCqDO,IAAMC,GAAyB,CACpC,SAAU,eACV,KAAM,OACN,SAAU,SACV,QAAS,SACT,OAAQ,UACR,OAAQ,GACR,KAAM,GACN,SAAU,KACV,SAAU,GACV,cAAe,EACf,YAAa,CAAC,EACd,YAAa,UACb,SAAU,GACV,SAAU,GACV,SAAU,GACV,QAAS,GACT,QAAS,GACT,OAAQ,UACR,KAAM,GACN,KAAM,GACN,QAAS,sCACX,EAEMC,GAAM,CAACC,EAAYC,EAAYC,IAAmC,CACtE,IAAMC,EAAI,OAAOH,GAAM,SAAWA,EAAI,OAAOA,GAAM,UAAYA,EAAE,KAAK,IAAM,GAAK,OAAOA,CAAC,EAAI,IAC7F,OAAO,OAAO,SAASG,CAAC,EAAI,KAAK,IAAID,EAAI,KAAK,IAAID,EAAIE,CAAC,CAAC,EAAI,MAC9D,EAEMC,GAAQJ,GAAoC,CAChD,GAAI,OAAOA,GAAM,UAAW,OAAOA,EACnC,GAAIA,IAAM,QAAUA,IAAM,IAAMA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C,GAAS,SAAS,cACpBC,GAA8B,KAElC,SAASC,IAAQ,CACf,GAAI,CAACF,GAAQ,OACb,IAAMG,EAAQC,GAAe,MAAM,KAAKJ,GAAO,UAAU,EAAE,OAAQK,GAAMA,EAAE,KAAK,WAAW,OAAO,CAAC,CAAC,EAE9FC,EAASC,GAAgB,OAAOA,GAAM,UAAYA,EAAE,KAAK,EAAIA,EAAE,KAAK,EAAI,OACxEC,EAAMF,EAAMH,EAAM,GAAG,GAAKG,EAAMH,EAAM,cAAc,EAC1D,GAAI,CAACK,EAAK,OAGV,IAAMC,EAASC,GAAWC,GAAUR,CAAK,EAEnCS,EAAqB,CACzB,GAFc,OAAO,YAAY,OAAO,QAAQH,CAAM,EAAE,OAAO,CAAC,CAACI,EAAGN,CAAC,IAAMM,KAAKV,GAASI,IAAOI,GAAgDE,CAAC,CAAC,CAAC,EAGnJ,eAAgBL,EAChB,QAASF,EAAMH,EAAM,KAAK,EAC1B,OAAQG,EAAMH,EAAM,MAAM,CAC5B,EACAF,GAASa,GAAMF,CAAI,CACrB,CAEI,SAAS,aAAe,UAAW,SAAS,iBAAiB,mBAAoBV,GAAO,CAAE,KAAM,EAAK,CAAC,EACrGA,GAAM,EAEX,IAAMa,GAAM,CACV,MAAQC,GAAqBf,GAASa,GAAME,CAAC,EAC7C,KAAOT,GAAwBN,IAAQ,KAAKM,CAAC,EAC7C,MAAO,IAAMN,IAAQ,MAAM,EAC3B,IAAI,QAAS,CACX,OAAOA,EACT,CACF,EACC,OAAmD,aAAec","names":["iife_exports","__export","mount","DEFAULTS","num","v","lo","hi","n","bool","str","max","safeColor","s","safeFont","applyLayer","base","raw","c","fromAttributes","attrs","out","name","value","key","_","ch","shared","audioContext","PcmPlayer","opts","__publicField","bytes","count","view","buf","ch","i","src","now","delayMs","s","sum","v","WORKLET","levelOf","pcm","openMic","stream","ctx","source","muted","deliver","node","teardown","url","w","e","sp","ratio","pos","out","n","sink","m","t","Emitter","event","fn","_a","payload","CxError","code","message","status","fields","codeForStatus","errorFrom","res","j","send","apiUrl","path","headers","request","readEvents","onEvent","signal","body","reader","decoder","onAbort","value","done","drain","rest","idx","block","data","line","colon","field","raw","parsed","parsePacket","kind","final","o","corrLen","corr","len","BARGE_IN_LEVEL","BARGE_IN_MS","HEARTBEAT_MS","initial","Call","session","agentId","p","patch","level","token","r","err","reason","failures","d","hold","ws","face","emotion","player","c","old","cid","heardMs","id","was","error","localSeq","localId","Chat","pending","text","mine","reply","finished","failure","next","q","x","b","memoryStore","k","localStore","RENEW_EARLY_S","SessionManager","info","got","visitorId","DEFAULT_API_URL","CharacterXYZ","_CharacterXYZ","store","refresh","details","page","call","slice","options","vnodeId","isValidElement","rerenderQueue","prevDebounce","defer","depthSort","_id","EVENT_DISPATCHED","EVENT_ATTACHED","CAPTURE_REGEX","eventClock","eventProxy","eventProxyCapture","i","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","isArray","Array","assign","obj","props","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","call","defaultProps","createVNode","original","vnode","__k","__","__b","__e","__c","constructor","__v","__i","__u","Fragment","props","children","BaseComponent","context","this","getDomSibling","vnode","childIndex","__","__i","sibling","__k","length","__e","type","renderComponent","component","__P","__d","oldVNode","__v","oldDom","commitQueue","refQueue","newVNode","assign","options","diff","__n","namespaceURI","__u","commitRoot","updateParentDomPointers","__c","base","some","child","enqueueRender","c","rerenderQueue","push","process","__r","prevDebounce","debounceRendering","defer","l","sort","depthSort","shift","diffChildren","parentDom","renderResult","newParentVNode","oldParentVNode","globalContext","namespace","excessDomChildren","isHydrating","i","childVNode","newDom","firstChildDom","result","oldChildren","EMPTY_ARR","newChildrenLength","constructNewChildrenArray","EMPTY_OBJ","ref","applyRef","insert","nextSibling","skewedIndex","matchingIndex","oldChildrenLength","remainingOldChildren","skew","Array","constructor","String","createVNode","isArray","__b","key","findMatchingIndex","unmount","parentVNode","parentNode","insertBefore","nodeType","findMatchingIndex","childVNode","oldChildren","skewedIndex","remainingOldChildren","x","y","childIndex","key","type","oldVNode","matched","__u","length","setStyle","style","value","setProperty","IS_NON_DIMENSIONAL","test","dom","name","oldValue","namespace","useCapture","lowerCaseName","o","cssText","replace","CAPTURE_REGEX","toLowerCase","slice","l","EVENT_ATTACHED","eventClock","addEventListener","eventProxyCapture","eventProxy","removeEventListener","e","removeAttribute","setAttribute","createEventProxy","this","eventHandler","EVENT_DISPATCHED","options","event","diff","parentDom","newVNode","globalContext","excessDomChildren","commitQueue","oldDom","isHydrating","refQueue","tmp","oldCommitQueueLength","c","isNew","oldProps","oldState","snapshot","clearProcessingException","newProps","isClassComponent","provider","componentContext","renderHook","count","renderResult","i","newType","constructor","__e","__b","outer","props","prototype","render","contextType","__c","__","__E","BaseComponent","doRender","sub","state","__n","__d","__h","_sb","__s","getDerivedStateFromProps","assign","__v","componentWillMount","componentDidMount","push","componentWillReceiveProps","shouldComponentUpdate","__k","some","vnode","EMPTY_ARR","apply","getDomSibling","componentWillUpdate","componentDidUpdate","context","__P","__r","getChildContext","getSnapshotBeforeUpdate","Fragment","cloneNode","children","diffChildren","isArray","base","then","MODE_HYDRATE","nodeType","nextSibling","indexOf","removeNode","markAsForce","diffElementNodes","diffed","commitRoot","root","applyRef","cb","call","node","map","newHtml","oldHtml","newChildren","inputValue","checked","EMPTY_OBJ","localName","document","createTextNode","createElementNS","is","__m","data","defaultValue","childNodes","attributes","__html","innerHTML","content","undefined","ref","hasRefUnmount","current","unmount","parentVNode","skipRemove","r","componentWillUnmount","replaceNode","documentElement","createElement","namespaceURI","firstChild","slice","EMPTY_ARR","options","__e","error","vnode","oldVNode","errorInfo","component","ctor","handled","__","__c","constructor","getDerivedStateFromError","setState","__d","componentDidCatch","__E","e","vnodeId","isValidElement","BaseComponent","prototype","update","callback","s","this","__s","state","assign","props","__v","_sb","push","enqueueRender","forceUpdate","__h","render","Fragment","rerenderQueue","defer","Promise","then","bind","resolve","setTimeout","depthSort","a","b","__b","process","__r","_id","Math","random","toString","EVENT_DISPATCHED","EVENT_ATTACHED","CAPTURE_REGEX","eventClock","eventProxy","createEventProxy","eventProxyCapture","i","currentIndex","currentComponent","previousComponent","prevRaf","currentHook","afterPaintEffects","options","_options","oldBeforeDiff","__b","oldBeforeRender","__r","oldAfterDiff","diffed","oldCommit","__c","oldBeforeUnmount","unmount","oldRoot","__","getHookState","index","type","__h","hooks","__H","length","push","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","action","currentValue","__N","nextValue","setState","__f","updateHookState","p","s","c","updatedHook","shouldUpdate","props","some","hookItem","prevScu","result","call","this","shouldComponentUpdate","prevCWU","componentWillUpdate","__e","tmp","useEffect","callback","args","state","__s","argsChanged","_pendingArgs","useLayoutEffect","useRef","initialValue","useMemo","current","useMemo","factory","args","state","getHookState","currentIndex","argsChanged","__H","__","__h","useCallback","callback","currentHook","flushAfterPaintEffects","component","afterPaintEffects","shift","hooks","__H","__P","__h","some","invokeCleanup","invokeEffect","e","options","__e","__v","__b","vnode","currentComponent","oldBeforeDiff","__","parentDom","__k","__m","oldRoot","__r","oldBeforeRender","currentIndex","__c","previousComponent","hookItem","__N","_pendingArgs","diffed","oldAfterDiff","c","length","push","prevRaf","requestAnimationFrame","afterNextFrame","commitQueue","filter","cb","oldCommit","unmount","oldBeforeUnmount","hasErrored","s","HAS_RAF","callback","raf","done","clearTimeout","timeout","cancelAnimationFrame","setTimeout","hook","comp","cleanup","argsChanged","oldArgs","newArgs","arg","index","invokeOrReturn","f","ordinal","n","v","eta","seconds","m","clock","totalSeconds","s","h","ss","endCopy","reason","name","inline","out","re","last","tok","blocks","text","para","lines","l","FALLBACK","faceOf","video","anchorW","anchorH","eyes","chin","ex","ey","span","CLOSE_UP","MEDIUM","HALF_BODY","FULL_BODY","place","face","mediaAspect","boxW","boxH","shot","width","height","EMAIL","PHONE","NAME","NOT_NAMES","extractContact","text","out","email","m","digits","n","words","w","kept","vnodeId","createVNode","type","props","key","isStaticChildren","__source","__self","ref","i","normalizedProps","vnode","__k","__","__b","__e","__c","constructor","__v","vnodeId","__i","__u","defaultProps","options","svg","size","children","u","ChatIcon","PhoneIcon","HangUpIcon","MicIcon","S","MicOffIcon","CloseIcon","SendIcon","BackIcon","NewChatIcon","size","svg","u","CheckIcon","RetryIcon","faceEmotion","cameoState","s","FaceFrame","client","call","state","src","onStatus","frame","A","loaded","setLoaded","d","loadedRef","origin","post","msg","transfer","w","h","cancelled","onMessage","e","avatar","timeout","cameo","offs","corr","payload","event","raf","tick","a","f","u","alphaVideoWorks","ua","reducedMotion","Portrait","agent","shot","talking","still","cls","box","A","size","setSize","d","anchorDims","setAnchorDims","ready","setReady","video","anchorUrl","canPlay","idle","talk","_","el","update","ro","u","aspect","face","faceOf","p","place","style","showIdle","showTalk","e","img","Clip","r","src","visible","onReady","ref","h","v","GREETED_KEY","INTRODUCED_KEY","storage","key","value","chime","Ctx","ctx","now","f","i","o","g","useChat","client","messages","setMessages","d","busy","setBusy","h","a","b","useCall","call","setCall","state","setState","captions","setCaptions","c","offs","prev","x","id","useElapsed","startedAt","running","setNow","t","useVoiceLevel","el","active","raf","smooth","tick","lvl","Text","parts","u","S","p","line","j","arr","LABELS","DetailsCard","form","title","note","onSend","onSkip","skipLabel","initial","values","setValues","errors","setErrors","failed","setFailed","sending","setSending","first","A","e","err","fields","spec","v","QuickReplies","items","onPick","children","q","Rich","text","blocks","it","App","config","bind","onView","agent","features","canChat","canCall","view","setViewRaw","closing","setClosing","greeting","setGreeting","reset","draft","setDraft","log","input","stage","subtitle","name","opening","setOpening","live","teaser","starters","firstLine","history","setHistory","greeted","setGreeted","detailsDone","setDetailsDone","sentName","setSentName","callCard","setCallCard","typed","setTyped","setView","close","loadHistory","list","open","labelled","setLabelled","onKey","wantsFace","faceStatus","setFaceStatus","phase","restore","elapsed","startPos","useMemoStart","beginCall","startCall","settleDetails","how","firstName","thenCall","sendDetails","skipDetails","startOver","faceEmotion","knownForm","m","sendText","found","extractContact","lastAgentStreaming","lastMsg","invited","card","inLine","CloseIcon","ordinal","Portrait","FULL_BODY","HALF_BODY","CLOSE_UP","ChatIcon","PhoneIcon","head","NewChatIcon","eta","RetryIcon","CheckIcon","SendIcon","s","position","progress","R","C","remaining","agentState","status","ended","copy","endCopy","MEDIUM","FaceFrame","clock","k","MicOffIcon","MicIcon","HangUpIcon","BackIcon","ref","CSS","TAG","inkFor","color","m","hex","c","r","g","b","i","luminanceOf","v","pageIsDark","mq","el","lum","ATTRS","CharacterXYZElement","__publicField","root","style","CSS","idle","R","view","name","detail","opts","attrs","fromAttributes","publishableKey","P","e","err","d","client","config","applyLayer","DEFAULTS","s","u","App","api","set","k","define","mount","options","script","widget","start","attrs","fromAttributes","a","given","v","key","config","applyLayer","DEFAULTS","opts","k","mount","api","o"]}