@wysdym/agent 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +228 -0
- package/dist/ChatWidget.d.ts +58 -0
- package/dist/index.cjs.js +1824 -0
- package/dist/index.css +1 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.es.js +35567 -0
- package/dist/sdk/WysdymWidget.d.ts +108 -0
- package/dist/types/agent.d.ts +32 -0
- package/dist/types/analytics.d.ts +75 -0
- package/dist/types/api.d.ts +21 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/session.d.ts +55 -0
- package/dist/types/voice.d.ts +33 -0
- package/dist/vite.svg +1 -0
- package/package.json +99 -0
|
@@ -0,0 +1,1824 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const jsxRuntime=require("react/jsx-runtime"),React=require("react"),client=require("react-dom/client");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;const ELEMENT_NAME="wysdym-widget",TRIGGER_ICON_SVG={Phone:'<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>',Home:'<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M9 22V12h6v10"/>',Mic:'<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>',MessageCircle:'<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>',MessageSquare:'<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',Video:'<path d="m22 8-6 4 6 4V8Z"/><rect width="14" height="12" x="2" y="6" rx="2" ry="2"/>',User:'<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',Users:'<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',Headphones:'<path d="M3 14v3a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3"/><path d="M21 14v3a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3"/><path d="M12 2a5 5 0 0 0-5 5v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V7a5 5 0 0 0-5-5Z"/>',HelpCircle:'<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>',Mail:'<rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>',Send:'<path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>',Settings:'<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',Search:'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',Heart:'<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',Star:'<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',ThumbsUp:'<path d="M7 11v8a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1Z"/><path d="M20.38 8.57A1 1 0 0 0 19 9V7a1 1 0 0 0-1-1h-.65a1 1 0 0 0-.9.63l-.58 1.19B15.65 10 15 11 15 12v4a1 1 0 0 0 1 1 1 1 0 0 0 1-1v-4h.83a1 1 0 0 0 .8-.38Z"/><path d="M16 8a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1 1 1 0 0 0 1-1V9a1 1 0 0 0-1-1Z"/>',ThumbsDown:'<path d="M17 13V5a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1V6h4"/><path d="M20 16v1a1 1 0 0 1-1 1h-1.5a1 1 0 0 1-.8-.38l-2.5-3.33A1 1 0 0 1 14 14v-4"/><path d="M14 10v4"/>',Check:'<path d="M20 6 9 17l-5-5"/>',X:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',Plus:'<path d="M5 12h14"/><path d="M12 5v14"/>',Minus:'<path d="M5 12h14"/>',ArrowLeft:'<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>',ArrowRight:'<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',ArrowUp:'<path d="m18 15-6-6-6 6"/><path d="M12 21V9"/>',ArrowDown:'<path d="m6 9 6 6 6-6"/><path d="M12 3v18"/>',ChevronLeft:'<path d="m15 18-6-6 6-6"/>',ChevronRight:'<path d="m9 18 6-6-6-6"/>',ChevronUp:'<path d="m18 15-6-6-6 6"/>',ChevronDown:'<path d="m6 9 6 6 6-6"/>',Menu:'<line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/>',MoreHorizontal:'<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',MoreVertical:'<circle cx="12" cy="12" r="1"/><circle cx="12" cy="5" r="1"/><circle cx="12" cy="19" r="1"/>',Edit:'<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>',Trash2:'<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',Copy:'<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',Download:'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',Upload:'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>',Link:'<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',ExternalLink:'<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" x2="21" y1="14" y2="3"/>',Lock:'<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',Unlock:'<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 5-5 5 5 0 0 1 5 5"/>',Eye:'<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',EyeOff:'<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/>',Calendar:'<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>',Clock:'<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',MapPin:'<path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/>',PhoneCall:'<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>',FileText:'<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><line x1="10" x2="8" y1="9" y2="9"/>',Image:'<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.3-3.3"/><path d="m17 10 3.3-3.3"/>',Music:'<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',Play:'<polygon points="5 3 19 12 5 21 5 3"/>',Pause:'<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>',SkipBack:'<polygon points="19 20 9 12 19 4 19 20"/><line x1="5" x2="5" y1="19" y2="5"/>',SkipForward:'<polygon points="5 4 15 12 5 20 5 4"/><line x1="19" x2="19" y1="5" y2="19"/>',Volume:'<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>',Volume2:'<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>',VolumeX:'<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" x2="16" y1="9" y2="15"/><line x1="16" x2="22" y1="9" y2="15"/>',Wifi:'<path d="M5 13a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><line x1="12" x2="12.01" y1="20" y2="20"/>',Bluetooth:'<path d="m17 11 2-2-2-2"/><path d="m7 11 10 10 2-6-2-6"/><path d="M22 12h-4v-2"/>',Battery:'<rect width="16" height="10" x="2" y="7" rx="2" ry="2"/><line x1="22" x2="22" y1="11" y2="13"/>',Zap:'<path d="M4 14l6 6 2-4 8-2-6-6-2 4-8 2z"/>',Sun:'<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>',Moon:'<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',Cloud:'<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/>',Wind:'<path d="M17.7 19.2c.8.4 1.8-.2 1.8-1.1v-1.2c0-.9-.9-1.4-1.6-1.1"/><path d="M14.5 11a2.5 2.5 0 1 1 0-5h4.3c.6 0 1.2.5 1.2 1.2v.1"/><path d="M9 15v-1.2c0-.9-.9-1.4-1.6-1.1"/>',Leaf:'<path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z"/>',Wrench:'<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>'};function getTriggerIconSvg(T){if(!T||typeof T!="string")return TRIGGER_ICON_SVG.Phone;const n=TRIGGER_ICON_SVG[T];if(n)return n;const P=T.trim().toLowerCase(),R=Object.keys(TRIGGER_ICON_SVG).find(A=>A.toLowerCase()===P);return R?TRIGGER_ICON_SVG[R]:TRIGGER_ICON_SVG.Phone}function escapeHtml(T){const n=document.createElement("div");return n.textContent=T,n.innerHTML}const TRIGGER_STYLES=`
|
|
2
|
+
:host {
|
|
3
|
+
display: block;
|
|
4
|
+
position: relative;
|
|
5
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
@keyframes rainbow-spin {
|
|
9
|
+
0% { --angle: 0deg; }
|
|
10
|
+
100% { --angle: 360deg; }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
@property --angle {
|
|
14
|
+
syntax: '<angle>';
|
|
15
|
+
initial-value: 0deg;
|
|
16
|
+
inherits: false;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
.wysdym-trigger {
|
|
20
|
+
position: fixed;
|
|
21
|
+
bottom: 20px;
|
|
22
|
+
right: 20px;
|
|
23
|
+
z-index: 2147483647;
|
|
24
|
+
display: flex;
|
|
25
|
+
align-items: center;
|
|
26
|
+
justify-content: center;
|
|
27
|
+
gap: 8px;
|
|
28
|
+
padding: 12px 20px;
|
|
29
|
+
border-radius: 50px;
|
|
30
|
+
border: 2px solid transparent;
|
|
31
|
+
cursor: pointer;
|
|
32
|
+
background:
|
|
33
|
+
linear-gradient(white, white) padding-box,
|
|
34
|
+
conic-gradient(from var(--angle, 0deg), #f472b6, #a855f7, #6366f1, #38bdf8, #34d399, #facc15, #f472b6) border-box;
|
|
35
|
+
color: var(--wysdym-primary, #BA6296);
|
|
36
|
+
font-size: 14px;
|
|
37
|
+
font-weight: 600;
|
|
38
|
+
white-space: nowrap;
|
|
39
|
+
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
|
|
40
|
+
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
|
41
|
+
animation: rainbow-spin 3s linear infinite;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
.wysdym-trigger:hover {
|
|
45
|
+
transform: scale(1.05);
|
|
46
|
+
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.18);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
.wysdym-trigger:active {
|
|
50
|
+
transform: scale(0.95);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
.wysdym-trigger--left {
|
|
54
|
+
right: auto;
|
|
55
|
+
left: 20px;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
.wysdym-trigger svg {
|
|
59
|
+
width: 18px;
|
|
60
|
+
height: 18px;
|
|
61
|
+
fill: none;
|
|
62
|
+
stroke: currentColor;
|
|
63
|
+
stroke-width: 2;
|
|
64
|
+
stroke-linecap: round;
|
|
65
|
+
stroke-linejoin: round;
|
|
66
|
+
}
|
|
67
|
+
`;function defineWidget(){if(typeof HTMLElement>"u")return;class T extends HTMLElement{static observedAttributes=["agent-id","mode","position","theme","expandable","data-defer-init","data-trigger-text","data-button-text","data-button-icon"];abortController=null;configUpdatedHandler=null;initialized=!1;mounted=!1;triggerButton=null;connectedCallback(){this.abortController=new AbortController;const P=document.getElementById("wysdym-floating-widget");P&&P.remove();const R=this.attachShadow({mode:"open"}),A=document.createElement("style");if(A.textContent=TRIGGER_STYLES,R.appendChild(A),this.renderTrigger(R),this.hasPreviewOverrides())this.applyPreviewOverrides();else{const L=this.getAttribute("agent-id");if(L){const O=typeof window<"u"?window.__WYSDYM_BACKEND_URL__:void 0;Promise.resolve().then(()=>agentConfig).then(({fetchAgentConfig:N})=>N(L,O)).then(N=>{if(N&&this.triggerButton){const V=N.widget_trigger_button_text??"Start a call",j=N.widget_trigger_button_icon??"Phone",B=N.widget_trigger_text??"Need help?";this.updateTriggerContent(V,j,B)}}).catch(()=>{})}}window.addEventListener("wysdym-widget-collapsed",()=>{this.mounted=!1,this.triggerButton&&(this.triggerButton.style.display="");const L=document.getElementById("wysdym-floating-widget");L&&L.remove()}),this.configUpdatedHandler=L=>{L.detail?.agentId===this.getAttribute("agent-id")&&this.refreshTriggerFromApi()},window.addEventListener("wysdym-agent-config-updated",this.configUpdatedHandler),this.isDeferredInit()||this.initialize()}disconnectedCallback(){if(this.configUpdatedHandler&&(window.removeEventListener("wysdym-agent-config-updated",this.configUpdatedHandler),this.configUpdatedHandler=null),this.abortController&&(this.abortController.abort(),this.abortController=null),this.mounted){const P=document.getElementById("wysdym-floating-widget");P&&P.remove()}this.initialized=!1,this.mounted=!1,this.triggerButton=null}attributeChangedCallback(P,R,A){(P==="data-trigger-text"||P==="data-button-text"||P==="data-button-icon")&&this.hasPreviewOverrides()&&this.applyPreviewOverrides()}hasPreviewOverrides(){return this.getAttribute("data-trigger-text")!==null||this.getAttribute("data-button-text")!==null||this.getAttribute("data-button-icon")!==null}applyPreviewOverrides(){if(!this.triggerButton)return;const P=this.getAttribute("data-trigger-text")??"Need help?",R=this.getAttribute("data-button-text")??"Start a call",A=this.getAttribute("data-button-icon")??"Phone";this.updateTriggerContent(R,A,P)}init(){this.initialized||this.initialize()}isDeferredInit(){return this.getAttribute("data-defer-init")==="true"}getPosition(){return this.getAttribute("position")==="bottom-left"?"bottom-left":"bottom-right"}initialize(){this.initialized=!0}handleTriggerClick(){if(this.mounted)return;const P=this.getAttribute("agent-id");if(!P)return;const R=this.getPosition(),A=this.getAttribute("mode")||"floating";this.triggerButton&&(this.triggerButton.style.display="none");const L={agentId:P,mode:A,position:R,startExpanded:!0},O=window.WysdymWidget||window.ChatWidget;if(O?.mount){this.mounted=!0,O.mount(L);return}Promise.resolve().then(()=>main).then(()=>{this.mounted=!0,(window.WysdymWidget||window.ChatWidget)?.mount?.(L)}).catch(()=>{this.triggerButton&&(this.triggerButton.style.display="")})}refreshTriggerFromApi(){const P=this.getAttribute("agent-id");if(!P||!this.triggerButton)return;const R=typeof window<"u"?window.__WYSDYM_BACKEND_URL__:void 0;Promise.resolve().then(()=>agentConfig).then(({fetchAgentConfig:A})=>A(P,R)).then(A=>{if(A&&this.triggerButton){const L=A.widget_trigger_button_text??"Start a call",O=A.widget_trigger_button_icon??"Phone",N=A.widget_trigger_text??"Need help?";this.updateTriggerContent(L,O,N)}}).catch(()=>{})}updateTriggerContent(P,R,A){if(!this.triggerButton)return;const L=getTriggerIconSvg(R);this.triggerButton.title=A,this.triggerButton.setAttribute("aria-label",A||"Open chat widget"),P.trim()?this.triggerButton.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${L}</svg><span>${escapeHtml(P)}</span>`:this.triggerButton.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${L}</svg>`}renderTrigger(P){const R=document.createElement("button");R.className="wysdym-trigger",R.setAttribute("data-testid","widget-trigger"),R.setAttribute("aria-label","Open chat widget"),R.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${TRIGGER_ICON_SVG.Phone}</svg><span>Start a call</span>`,this.getPosition()==="bottom-left"&&R.classList.add("wysdym-trigger--left"),R.addEventListener("click",()=>this.handleTriggerClick()),this.triggerButton=R,P.appendChild(R)}}return typeof customElements<"u"&&!customElements.get(ELEMENT_NAME)&&customElements.define(ELEMENT_NAME,T),T}defineWidget();function WysdymWidget({agentId:T,mode:n="floating",position:P="bottom-right",theme:R,primaryColor:A,expandable:L,deferInit:O,backendUrl:N,previewTriggerText:V,previewButtonText:j,previewButtonIcon:B}){const z=React.useRef(null);return React.useEffect(()=>(N&&(window.__WYSDYM_BACKEND_URL__=N),()=>{N&&delete window.__WYSDYM_BACKEND_URL__}),[N]),React.useEffect(()=>{const W=z.current;W&&(W.setAttribute("agent-id",T),W.setAttribute("mode",n),W.setAttribute("position",P),R&&W.setAttribute("theme",R),A&&W.style.setProperty("--wysdym-primary",A),L!=null&&W.setAttribute("expandable",String(L)),O&&W.setAttribute("data-defer-init","true"),V!==void 0?W.setAttribute("data-trigger-text",V):W.removeAttribute("data-trigger-text"),j!==void 0?W.setAttribute("data-button-text",j):W.removeAttribute("data-button-text"),B!==void 0?W.setAttribute("data-button-icon",B):W.removeAttribute("data-button-icon"))},[T,n,P,R,A,L,O,V,j,B]),jsxRuntime.jsx("wysdym-widget",{ref:z})}const WIDGET_CDN_URL="https://storage.googleapis.com/wysdym-widget-cdn-production";function getEmbedCode(T,n={}){const{companyToken:P,mode:R="floating",position:A="bottom-right",containerId:L}=n,O=P?`
|
|
68
|
+
data-company-token="${P}"`:"";return R==="inline"&&L?`<script src="${WIDGET_CDN_URL}/widget-loader.js"
|
|
69
|
+
data-auto-load="true"${O}
|
|
70
|
+
data-agent-id="${T}"
|
|
71
|
+
data-mode="inline"
|
|
72
|
+
data-container="#${L}"
|
|
73
|
+
async><\/script>`:`<script src="${WIDGET_CDN_URL}/widget-loader.js"
|
|
74
|
+
data-auto-load="true"${O}
|
|
75
|
+
data-agent-id="${T}"
|
|
76
|
+
data-mode="${R}"
|
|
77
|
+
data-position="${A}"
|
|
78
|
+
async><\/script>`}const createStoreImpl=T=>{let n;const P=new Set,R=(j,B)=>{const z=typeof j=="function"?j(n):j;if(!Object.is(z,n)){const W=n;n=B??(typeof z!="object"||z===null)?z:Object.assign({},n,z),P.forEach(q=>q(n,W))}},A=()=>n,N={setState:R,getState:A,getInitialState:()=>V,subscribe:j=>(P.add(j),()=>P.delete(j))},V=n=T(R,A,N);return N},createStore=(T=>createStoreImpl),identity=T=>T;function useStore(T,n=identity){const P=React.useSyncExternalStore(T.subscribe,React.useCallback(()=>n(T.getState()),[T,n]),React.useCallback(()=>n(T.getInitialState()),[T,n]));return React.useDebugValue(P),P}/**
|
|
79
|
+
* @license lucide-react v0.539.0 - ISC
|
|
80
|
+
*
|
|
81
|
+
* This source code is licensed under the ISC license.
|
|
82
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
83
|
+
*/const toKebabCase=T=>T.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),toCamelCase=T=>T.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,P,R)=>R?R.toUpperCase():P.toLowerCase()),toPascalCase=T=>{const n=toCamelCase(T);return n.charAt(0).toUpperCase()+n.slice(1)},mergeClasses=(...T)=>T.filter((n,P,R)=>!!n&&n.trim()!==""&&R.indexOf(n)===P).join(" ").trim(),hasA11yProp=T=>{for(const n in T)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**
|
|
84
|
+
* @license lucide-react v0.539.0 - ISC
|
|
85
|
+
*
|
|
86
|
+
* This source code is licensed under the ISC license.
|
|
87
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
88
|
+
*/var defaultAttributes={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
89
|
+
* @license lucide-react v0.539.0 - ISC
|
|
90
|
+
*
|
|
91
|
+
* This source code is licensed under the ISC license.
|
|
92
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
93
|
+
*/const Icon=React.forwardRef(({color:T="currentColor",size:n=24,strokeWidth:P=2,absoluteStrokeWidth:R,className:A="",children:L,iconNode:O,...N},V)=>React.createElement("svg",{ref:V,...defaultAttributes,width:n,height:n,stroke:T,strokeWidth:R?Number(P)*24/Number(n):P,className:mergeClasses("lucide",A),...!L&&!hasA11yProp(N)&&{"aria-hidden":"true"},...N},[...O.map(([j,B])=>React.createElement(j,B)),...Array.isArray(L)?L:[L]]));/**
|
|
94
|
+
* @license lucide-react v0.539.0 - ISC
|
|
95
|
+
*
|
|
96
|
+
* This source code is licensed under the ISC license.
|
|
97
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
98
|
+
*/const createLucideIcon=(T,n)=>{const P=React.forwardRef(({className:R,...A},L)=>React.createElement(Icon,{ref:L,iconNode:n,className:mergeClasses(`lucide-${toKebabCase(toPascalCase(T))}`,`lucide-${T}`,R),...A}));return P.displayName=toPascalCase(T),P};/**
|
|
99
|
+
* @license lucide-react v0.539.0 - ISC
|
|
100
|
+
*
|
|
101
|
+
* This source code is licensed under the ISC license.
|
|
102
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
103
|
+
*/const __iconNode$1a=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],ArrowDown=createLucideIcon("arrow-down",__iconNode$1a);/**
|
|
104
|
+
* @license lucide-react v0.539.0 - ISC
|
|
105
|
+
*
|
|
106
|
+
* This source code is licensed under the ISC license.
|
|
107
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
108
|
+
*/const __iconNode$19=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ArrowLeft=createLucideIcon("arrow-left",__iconNode$19);/**
|
|
109
|
+
* @license lucide-react v0.539.0 - ISC
|
|
110
|
+
*
|
|
111
|
+
* This source code is licensed under the ISC license.
|
|
112
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
113
|
+
*/const __iconNode$18=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],ArrowRight=createLucideIcon("arrow-right",__iconNode$18);/**
|
|
114
|
+
* @license lucide-react v0.539.0 - ISC
|
|
115
|
+
*
|
|
116
|
+
* This source code is licensed under the ISC license.
|
|
117
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
118
|
+
*/const __iconNode$17=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ArrowUp=createLucideIcon("arrow-up",__iconNode$17);/**
|
|
119
|
+
* @license lucide-react v0.539.0 - ISC
|
|
120
|
+
*
|
|
121
|
+
* This source code is licensed under the ISC license.
|
|
122
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
123
|
+
*/const __iconNode$16=[["path",{d:"M 22 14 L 22 10",key:"nqc4tb"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]],Battery=createLucideIcon("battery",__iconNode$16);/**
|
|
124
|
+
* @license lucide-react v0.539.0 - ISC
|
|
125
|
+
*
|
|
126
|
+
* This source code is licensed under the ISC license.
|
|
127
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
128
|
+
*/const __iconNode$15=[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}]],Bluetooth=createLucideIcon("bluetooth",__iconNode$15);/**
|
|
129
|
+
* @license lucide-react v0.539.0 - ISC
|
|
130
|
+
*
|
|
131
|
+
* This source code is licensed under the ISC license.
|
|
132
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
133
|
+
*/const __iconNode$14=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],Calendar=createLucideIcon("calendar",__iconNode$14);/**
|
|
134
|
+
* @license lucide-react v0.539.0 - ISC
|
|
135
|
+
*
|
|
136
|
+
* This source code is licensed under the ISC license.
|
|
137
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
138
|
+
*/const __iconNode$13=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Check=createLucideIcon("check",__iconNode$13);/**
|
|
139
|
+
* @license lucide-react v0.539.0 - ISC
|
|
140
|
+
*
|
|
141
|
+
* This source code is licensed under the ISC license.
|
|
142
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
143
|
+
*/const __iconNode$12=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ChevronDown=createLucideIcon("chevron-down",__iconNode$12);/**
|
|
144
|
+
* @license lucide-react v0.539.0 - ISC
|
|
145
|
+
*
|
|
146
|
+
* This source code is licensed under the ISC license.
|
|
147
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
148
|
+
*/const __iconNode$11=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],ChevronLeft=createLucideIcon("chevron-left",__iconNode$11);/**
|
|
149
|
+
* @license lucide-react v0.539.0 - ISC
|
|
150
|
+
*
|
|
151
|
+
* This source code is licensed under the ISC license.
|
|
152
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
153
|
+
*/const __iconNode$10=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ChevronRight=createLucideIcon("chevron-right",__iconNode$10);/**
|
|
154
|
+
* @license lucide-react v0.539.0 - ISC
|
|
155
|
+
*
|
|
156
|
+
* This source code is licensed under the ISC license.
|
|
157
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
158
|
+
*/const __iconNode$$=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ChevronUp=createLucideIcon("chevron-up",__iconNode$$);/**
|
|
159
|
+
* @license lucide-react v0.539.0 - ISC
|
|
160
|
+
*
|
|
161
|
+
* This source code is licensed under the ISC license.
|
|
162
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
163
|
+
*/const __iconNode$_=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],CircleAlert=createLucideIcon("circle-alert",__iconNode$_);/**
|
|
164
|
+
* @license lucide-react v0.539.0 - ISC
|
|
165
|
+
*
|
|
166
|
+
* This source code is licensed under the ISC license.
|
|
167
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
168
|
+
*/const __iconNode$Z=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],CircleCheckBig=createLucideIcon("circle-check-big",__iconNode$Z);/**
|
|
169
|
+
* @license lucide-react v0.539.0 - ISC
|
|
170
|
+
*
|
|
171
|
+
* This source code is licensed under the ISC license.
|
|
172
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
173
|
+
*/const __iconNode$Y=[["path",{d:"M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",key:"kmsa83"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],CirclePlay=createLucideIcon("circle-play",__iconNode$Y);/**
|
|
174
|
+
* @license lucide-react v0.539.0 - ISC
|
|
175
|
+
*
|
|
176
|
+
* This source code is licensed under the ISC license.
|
|
177
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
178
|
+
*/const __iconNode$X=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],CircleQuestionMark=createLucideIcon("circle-question-mark",__iconNode$X);/**
|
|
179
|
+
* @license lucide-react v0.539.0 - ISC
|
|
180
|
+
*
|
|
181
|
+
* This source code is licensed under the ISC license.
|
|
182
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
183
|
+
*/const __iconNode$W=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],CircleX=createLucideIcon("circle-x",__iconNode$W);/**
|
|
184
|
+
* @license lucide-react v0.539.0 - ISC
|
|
185
|
+
*
|
|
186
|
+
* This source code is licensed under the ISC license.
|
|
187
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
188
|
+
*/const __iconNode$V=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Clock=createLucideIcon("clock",__iconNode$V);/**
|
|
189
|
+
* @license lucide-react v0.539.0 - ISC
|
|
190
|
+
*
|
|
191
|
+
* This source code is licensed under the ISC license.
|
|
192
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
193
|
+
*/const __iconNode$U=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Cloud=createLucideIcon("cloud",__iconNode$U);/**
|
|
194
|
+
* @license lucide-react v0.539.0 - ISC
|
|
195
|
+
*
|
|
196
|
+
* This source code is licensed under the ISC license.
|
|
197
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
198
|
+
*/const __iconNode$T=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Copy=createLucideIcon("copy",__iconNode$T);/**
|
|
199
|
+
* @license lucide-react v0.539.0 - ISC
|
|
200
|
+
*
|
|
201
|
+
* This source code is licensed under the ISC license.
|
|
202
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
203
|
+
*/const __iconNode$S=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Download=createLucideIcon("download",__iconNode$S);/**
|
|
204
|
+
* @license lucide-react v0.539.0 - ISC
|
|
205
|
+
*
|
|
206
|
+
* This source code is licensed under the ISC license.
|
|
207
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
208
|
+
*/const __iconNode$R=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],EllipsisVertical=createLucideIcon("ellipsis-vertical",__iconNode$R);/**
|
|
209
|
+
* @license lucide-react v0.539.0 - ISC
|
|
210
|
+
*
|
|
211
|
+
* This source code is licensed under the ISC license.
|
|
212
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
213
|
+
*/const __iconNode$Q=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Ellipsis=createLucideIcon("ellipsis",__iconNode$Q);/**
|
|
214
|
+
* @license lucide-react v0.539.0 - ISC
|
|
215
|
+
*
|
|
216
|
+
* This source code is licensed under the ISC license.
|
|
217
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
218
|
+
*/const __iconNode$P=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],ExternalLink=createLucideIcon("external-link",__iconNode$P);/**
|
|
219
|
+
* @license lucide-react v0.539.0 - ISC
|
|
220
|
+
*
|
|
221
|
+
* This source code is licensed under the ISC license.
|
|
222
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
223
|
+
*/const __iconNode$O=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],EyeOff=createLucideIcon("eye-off",__iconNode$O);/**
|
|
224
|
+
* @license lucide-react v0.539.0 - ISC
|
|
225
|
+
*
|
|
226
|
+
* This source code is licensed under the ISC license.
|
|
227
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
228
|
+
*/const __iconNode$N=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Eye=createLucideIcon("eye",__iconNode$N);/**
|
|
229
|
+
* @license lucide-react v0.539.0 - ISC
|
|
230
|
+
*
|
|
231
|
+
* This source code is licensed under the ISC license.
|
|
232
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
233
|
+
*/const __iconNode$M=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],FileText=createLucideIcon("file-text",__iconNode$M);/**
|
|
234
|
+
* @license lucide-react v0.539.0 - ISC
|
|
235
|
+
*
|
|
236
|
+
* This source code is licensed under the ISC license.
|
|
237
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
238
|
+
*/const __iconNode$L=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]],Headphones=createLucideIcon("headphones",__iconNode$L);/**
|
|
239
|
+
* @license lucide-react v0.539.0 - ISC
|
|
240
|
+
*
|
|
241
|
+
* This source code is licensed under the ISC license.
|
|
242
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
243
|
+
*/const __iconNode$K=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],Heart=createLucideIcon("heart",__iconNode$K);/**
|
|
244
|
+
* @license lucide-react v0.539.0 - ISC
|
|
245
|
+
*
|
|
246
|
+
* This source code is licensed under the ISC license.
|
|
247
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
248
|
+
*/const __iconNode$J=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]],House=createLucideIcon("house",__iconNode$J);/**
|
|
249
|
+
* @license lucide-react v0.539.0 - ISC
|
|
250
|
+
*
|
|
251
|
+
* This source code is licensed under the ISC license.
|
|
252
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
253
|
+
*/const __iconNode$I=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Image$1=createLucideIcon("image",__iconNode$I);/**
|
|
254
|
+
* @license lucide-react v0.539.0 - ISC
|
|
255
|
+
*
|
|
256
|
+
* This source code is licensed under the ISC license.
|
|
257
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
258
|
+
*/const __iconNode$H=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Info=createLucideIcon("info",__iconNode$H);/**
|
|
259
|
+
* @license lucide-react v0.539.0 - ISC
|
|
260
|
+
*
|
|
261
|
+
* This source code is licensed under the ISC license.
|
|
262
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
263
|
+
*/const __iconNode$G=[["path",{d:"M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z",key:"nnexq3"}],["path",{d:"M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12",key:"mt58a7"}]],Leaf=createLucideIcon("leaf",__iconNode$G);/**
|
|
264
|
+
* @license lucide-react v0.539.0 - ISC
|
|
265
|
+
*
|
|
266
|
+
* This source code is licensed under the ISC license.
|
|
267
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
268
|
+
*/const __iconNode$F=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],Link=createLucideIcon("link",__iconNode$F);/**
|
|
269
|
+
* @license lucide-react v0.539.0 - ISC
|
|
270
|
+
*
|
|
271
|
+
* This source code is licensed under the ISC license.
|
|
272
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
273
|
+
*/const __iconNode$E=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]],LockOpen=createLucideIcon("lock-open",__iconNode$E);/**
|
|
274
|
+
* @license lucide-react v0.539.0 - ISC
|
|
275
|
+
*
|
|
276
|
+
* This source code is licensed under the ISC license.
|
|
277
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
278
|
+
*/const __iconNode$D=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Lock=createLucideIcon("lock",__iconNode$D);/**
|
|
279
|
+
* @license lucide-react v0.539.0 - ISC
|
|
280
|
+
*
|
|
281
|
+
* This source code is licensed under the ISC license.
|
|
282
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
283
|
+
*/const __iconNode$C=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],Mail=createLucideIcon("mail",__iconNode$C);/**
|
|
284
|
+
* @license lucide-react v0.539.0 - ISC
|
|
285
|
+
*
|
|
286
|
+
* This source code is licensed under the ISC license.
|
|
287
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
288
|
+
*/const __iconNode$B=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]],MapPin=createLucideIcon("map-pin",__iconNode$B);/**
|
|
289
|
+
* @license lucide-react v0.539.0 - ISC
|
|
290
|
+
*
|
|
291
|
+
* This source code is licensed under the ISC license.
|
|
292
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
293
|
+
*/const __iconNode$A=[["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 18h16",key:"19g7jn"}],["path",{d:"M4 6h16",key:"1o0s65"}]],Menu=createLucideIcon("menu",__iconNode$A);/**
|
|
294
|
+
* @license lucide-react v0.539.0 - ISC
|
|
295
|
+
*
|
|
296
|
+
* This source code is licensed under the ISC license.
|
|
297
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
298
|
+
*/const __iconNode$z=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],MessageCircle=createLucideIcon("message-circle",__iconNode$z);/**
|
|
299
|
+
* @license lucide-react v0.539.0 - ISC
|
|
300
|
+
*
|
|
301
|
+
* This source code is licensed under the ISC license.
|
|
302
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
303
|
+
*/const __iconNode$y=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],MessageSquare=createLucideIcon("message-square",__iconNode$y);/**
|
|
304
|
+
* @license lucide-react v0.539.0 - ISC
|
|
305
|
+
*
|
|
306
|
+
* This source code is licensed under the ISC license.
|
|
307
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
308
|
+
*/const __iconNode$x=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],Mic=createLucideIcon("mic",__iconNode$x);/**
|
|
309
|
+
* @license lucide-react v0.539.0 - ISC
|
|
310
|
+
*
|
|
311
|
+
* This source code is licensed under the ISC license.
|
|
312
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
313
|
+
*/const __iconNode$w=[["path",{d:"M5 12h14",key:"1ays0h"}]],Minus=createLucideIcon("minus",__iconNode$w);/**
|
|
314
|
+
* @license lucide-react v0.539.0 - ISC
|
|
315
|
+
*
|
|
316
|
+
* This source code is licensed under the ISC license.
|
|
317
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
318
|
+
*/const __iconNode$v=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],Moon=createLucideIcon("moon",__iconNode$v);/**
|
|
319
|
+
* @license lucide-react v0.539.0 - ISC
|
|
320
|
+
*
|
|
321
|
+
* This source code is licensed under the ISC license.
|
|
322
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
323
|
+
*/const __iconNode$u=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],Music=createLucideIcon("music",__iconNode$u);/**
|
|
324
|
+
* @license lucide-react v0.539.0 - ISC
|
|
325
|
+
*
|
|
326
|
+
* This source code is licensed under the ISC license.
|
|
327
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
328
|
+
*/const __iconNode$t=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],Pause=createLucideIcon("pause",__iconNode$t);/**
|
|
329
|
+
* @license lucide-react v0.539.0 - ISC
|
|
330
|
+
*
|
|
331
|
+
* This source code is licensed under the ISC license.
|
|
332
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
333
|
+
*/const __iconNode$s=[["path",{d:"M13 2a9 9 0 0 1 9 9",key:"1itnx2"}],["path",{d:"M13 6a5 5 0 0 1 5 5",key:"11nki7"}],["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]],PhoneCall=createLucideIcon("phone-call",__iconNode$s);/**
|
|
334
|
+
* @license lucide-react v0.539.0 - ISC
|
|
335
|
+
*
|
|
336
|
+
* This source code is licensed under the ISC license.
|
|
337
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
338
|
+
*/const __iconNode$r=[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]],PhoneOff=createLucideIcon("phone-off",__iconNode$r);/**
|
|
339
|
+
* @license lucide-react v0.539.0 - ISC
|
|
340
|
+
*
|
|
341
|
+
* This source code is licensed under the ISC license.
|
|
342
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
343
|
+
*/const __iconNode$q=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]],Phone=createLucideIcon("phone",__iconNode$q);/**
|
|
344
|
+
* @license lucide-react v0.539.0 - ISC
|
|
345
|
+
*
|
|
346
|
+
* This source code is licensed under the ISC license.
|
|
347
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
348
|
+
*/const __iconNode$p=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Play=createLucideIcon("play",__iconNode$p);/**
|
|
349
|
+
* @license lucide-react v0.539.0 - ISC
|
|
350
|
+
*
|
|
351
|
+
* This source code is licensed under the ISC license.
|
|
352
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
353
|
+
*/const __iconNode$o=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Plus=createLucideIcon("plus",__iconNode$o);/**
|
|
354
|
+
* @license lucide-react v0.539.0 - ISC
|
|
355
|
+
*
|
|
356
|
+
* This source code is licensed under the ISC license.
|
|
357
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
358
|
+
*/const __iconNode$n=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],RotateCcw=createLucideIcon("rotate-ccw",__iconNode$n);/**
|
|
359
|
+
* @license lucide-react v0.539.0 - ISC
|
|
360
|
+
*
|
|
361
|
+
* This source code is licensed under the ISC license.
|
|
362
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
363
|
+
*/const __iconNode$m=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Search=createLucideIcon("search",__iconNode$m);/**
|
|
364
|
+
* @license lucide-react v0.539.0 - ISC
|
|
365
|
+
*
|
|
366
|
+
* This source code is licensed under the ISC license.
|
|
367
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
368
|
+
*/const __iconNode$l=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Send=createLucideIcon("send",__iconNode$l);/**
|
|
369
|
+
* @license lucide-react v0.539.0 - ISC
|
|
370
|
+
*
|
|
371
|
+
* This source code is licensed under the ISC license.
|
|
372
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
373
|
+
*/const __iconNode$k=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Settings=createLucideIcon("settings",__iconNode$k);/**
|
|
374
|
+
* @license lucide-react v0.539.0 - ISC
|
|
375
|
+
*
|
|
376
|
+
* This source code is licensed under the ISC license.
|
|
377
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
378
|
+
*/const __iconNode$j=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],ShoppingCart=createLucideIcon("shopping-cart",__iconNode$j);/**
|
|
379
|
+
* @license lucide-react v0.539.0 - ISC
|
|
380
|
+
*
|
|
381
|
+
* This source code is licensed under the ISC license.
|
|
382
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
383
|
+
*/const __iconNode$i=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],SkipBack=createLucideIcon("skip-back",__iconNode$i);/**
|
|
384
|
+
* @license lucide-react v0.539.0 - ISC
|
|
385
|
+
*
|
|
386
|
+
* This source code is licensed under the ISC license.
|
|
387
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
388
|
+
*/const __iconNode$h=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],SkipForward=createLucideIcon("skip-forward",__iconNode$h);/**
|
|
389
|
+
* @license lucide-react v0.539.0 - ISC
|
|
390
|
+
*
|
|
391
|
+
* This source code is licensed under the ISC license.
|
|
392
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
393
|
+
*/const __iconNode$g=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],SquarePen=createLucideIcon("square-pen",__iconNode$g);/**
|
|
394
|
+
* @license lucide-react v0.539.0 - ISC
|
|
395
|
+
*
|
|
396
|
+
* This source code is licensed under the ISC license.
|
|
397
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
398
|
+
*/const __iconNode$f=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],Star=createLucideIcon("star",__iconNode$f);/**
|
|
399
|
+
* @license lucide-react v0.539.0 - ISC
|
|
400
|
+
*
|
|
401
|
+
* This source code is licensed under the ISC license.
|
|
402
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
403
|
+
*/const __iconNode$e=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],Sun=createLucideIcon("sun",__iconNode$e);/**
|
|
404
|
+
* @license lucide-react v0.539.0 - ISC
|
|
405
|
+
*
|
|
406
|
+
* This source code is licensed under the ISC license.
|
|
407
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
408
|
+
*/const __iconNode$d=[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]],ThumbsDown=createLucideIcon("thumbs-down",__iconNode$d);/**
|
|
409
|
+
* @license lucide-react v0.539.0 - ISC
|
|
410
|
+
*
|
|
411
|
+
* This source code is licensed under the ISC license.
|
|
412
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
413
|
+
*/const __iconNode$c=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],ThumbsUp=createLucideIcon("thumbs-up",__iconNode$c);/**
|
|
414
|
+
* @license lucide-react v0.539.0 - ISC
|
|
415
|
+
*
|
|
416
|
+
* This source code is licensed under the ISC license.
|
|
417
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
418
|
+
*/const __iconNode$b=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Trash2=createLucideIcon("trash-2",__iconNode$b);/**
|
|
419
|
+
* @license lucide-react v0.539.0 - ISC
|
|
420
|
+
*
|
|
421
|
+
* This source code is licensed under the ISC license.
|
|
422
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
423
|
+
*/const __iconNode$a=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Upload=createLucideIcon("upload",__iconNode$a);/**
|
|
424
|
+
* @license lucide-react v0.539.0 - ISC
|
|
425
|
+
*
|
|
426
|
+
* This source code is licensed under the ISC license.
|
|
427
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
428
|
+
*/const __iconNode$9=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],User=createLucideIcon("user",__iconNode$9);/**
|
|
429
|
+
* @license lucide-react v0.539.0 - ISC
|
|
430
|
+
*
|
|
431
|
+
* This source code is licensed under the ISC license.
|
|
432
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
433
|
+
*/const __iconNode$8=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Users=createLucideIcon("users",__iconNode$8);/**
|
|
434
|
+
* @license lucide-react v0.539.0 - ISC
|
|
435
|
+
*
|
|
436
|
+
* This source code is licensed under the ISC license.
|
|
437
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
438
|
+
*/const __iconNode$7=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Video=createLucideIcon("video",__iconNode$7);/**
|
|
439
|
+
* @license lucide-react v0.539.0 - ISC
|
|
440
|
+
*
|
|
441
|
+
* This source code is licensed under the ISC license.
|
|
442
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
443
|
+
*/const __iconNode$6=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],Volume2=createLucideIcon("volume-2",__iconNode$6);/**
|
|
444
|
+
* @license lucide-react v0.539.0 - ISC
|
|
445
|
+
*
|
|
446
|
+
* This source code is licensed under the ISC license.
|
|
447
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
448
|
+
*/const __iconNode$5=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],VolumeX=createLucideIcon("volume-x",__iconNode$5);/**
|
|
449
|
+
* @license lucide-react v0.539.0 - ISC
|
|
450
|
+
*
|
|
451
|
+
* This source code is licensed under the ISC license.
|
|
452
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
453
|
+
*/const __iconNode$4=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}]],Volume=createLucideIcon("volume",__iconNode$4);/**
|
|
454
|
+
* @license lucide-react v0.539.0 - ISC
|
|
455
|
+
*
|
|
456
|
+
* This source code is licensed under the ISC license.
|
|
457
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
458
|
+
*/const __iconNode$3=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]],Wifi=createLucideIcon("wifi",__iconNode$3);/**
|
|
459
|
+
* @license lucide-react v0.539.0 - ISC
|
|
460
|
+
*
|
|
461
|
+
* This source code is licensed under the ISC license.
|
|
462
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
463
|
+
*/const __iconNode$2=[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]],Wind=createLucideIcon("wind",__iconNode$2);/**
|
|
464
|
+
* @license lucide-react v0.539.0 - ISC
|
|
465
|
+
*
|
|
466
|
+
* This source code is licensed under the ISC license.
|
|
467
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
468
|
+
*/const __iconNode$1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],X=createLucideIcon("x",__iconNode$1);/**
|
|
469
|
+
* @license lucide-react v0.539.0 - ISC
|
|
470
|
+
*
|
|
471
|
+
* This source code is licensed under the ISC license.
|
|
472
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
473
|
+
*/const __iconNode=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Zap=createLucideIcon("zap",__iconNode),useSettingsStore=createStore()(T=>({isOpen:!1,trackingOptOut:!1,language:"en",toggle:()=>T(n=>({isOpen:!n.isOpen})),open:()=>T({isOpen:!0}),close:()=>T({isOpen:!1}),setTrackingOptOut:n=>T({trackingOptOut:n}),setLanguage:n=>T({language:n})})),DEFAULT_PRIMARY="#BA6296",DEFAULT_SECONDARY="#A0527A",useAgentConfigStore=createStore()(T=>({config:null,isLoaded:!1,primaryColor:DEFAULT_PRIMARY,secondaryColor:DEFAULT_SECONDARY,hasVoice:!1,setConfig:n=>T({config:n,isLoaded:!0,primaryColor:n.primary_color??DEFAULT_PRIMARY,secondaryColor:n.secondary_color??DEFAULT_SECONDARY,hasVoice:n.elevenlabs_agent_id!=null}),clearConfig:()=>T({config:null,isLoaded:!1,primaryColor:DEFAULT_PRIMARY,secondaryColor:DEFAULT_SECONDARY,hasVoice:!1})})),SettingsCog=({reportIssueUrl:T})=>{const n=React.useRef(null),P=React.useRef(null),{isOpen:R,trackingOptOut:A,toggle:L,close:O,setTrackingOptOut:N}=useSettingsStore.getState(),V=useAgentConfigStore.getState().primaryColor,[j,B]=React.useState({isOpen:R,trackingOptOut:A,primaryColor:V});React.useEffect(()=>{const W=useSettingsStore.subscribe(H=>B($=>({...$,isOpen:H.isOpen,trackingOptOut:H.trackingOptOut}))),q=useAgentConfigStore.subscribe(H=>B($=>({...$,primaryColor:H.primaryColor})));return()=>{W(),q()}},[]);const z=React.useCallback(W=>{const q=W.composedPath();n.current&&!q.includes(n.current)&&P.current&&!q.includes(P.current)&&O()},[O]);return React.useEffect(()=>(j.isOpen&&document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)),[j.isOpen,z]),jsxRuntime.jsxs("div",{className:"relative",style:{zIndex:50},children:[jsxRuntime.jsx("button",{ref:P,onClick:L,"aria-label":"Settings","aria-expanded":j.isOpen,className:"w-8 h-8 flex items-center justify-center rounded-full transition-colors hover:bg-white/20",style:{color:"white"},children:jsxRuntime.jsx(Settings,{className:"w-4 h-4"})}),j.isOpen&&jsxRuntime.jsxs("div",{ref:n,role:"dialog","aria-label":"Settings panel",className:"absolute right-0 top-full mt-2 w-72 bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden",children:[jsxRuntime.jsx("div",{className:"px-4 py-3 border-b border-gray-100",children:jsxRuntime.jsx("span",{className:"text-sm font-semibold text-gray-900",children:"Settings"})}),jsxRuntime.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex-1 min-w-0 mr-3",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium text-gray-900 block",children:"Opt out of tracking"}),jsxRuntime.jsx("span",{className:"text-xs text-gray-500 block mt-0.5",children:"Disable anonymous session tracking"})]}),jsxRuntime.jsx("button",{role:"switch","aria-checked":j.trackingOptOut,onClick:()=>N(!j.trackingOptOut),className:"relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:j.trackingOptOut?j.primaryColor:"#d1d5db"},children:jsxRuntime.jsx("span",{className:"pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out",style:{marginTop:"2px",transform:j.trackingOptOut?"translateX(18px)":"translateX(2px)"}})})]}),T&&jsxRuntime.jsx("div",{className:"px-4 py-3",children:jsxRuntime.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:[jsxRuntime.jsx(CircleAlert,{className:"w-4 h-4"}),"Report an issue"]})})]})]})},RINGS=[{size:100,opacity:.2,delay:0},{size:76,opacity:.28,delay:.3},{size:52,opacity:.35,delay:.6}],WidgetHeader=({primaryColor:T,secondaryColor:n,onClose:P})=>jsxRuntime.jsxs("div",{className:"text-white rounded-t-2xl relative flex-shrink-0",style:{background:`linear-gradient(135deg, ${T} 0%, ${n} 100%)`,height:140},children:[jsxRuntime.jsxs("div",{className:"absolute top-0 right-0 flex items-center gap-0.5 px-3 pt-3 z-10",children:[jsxRuntime.jsx(SettingsCog,{}),jsxRuntime.jsx("button",{onClick:P,"aria-label":"Close widget",className:"w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors",children:jsxRuntime.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),jsxRuntime.jsxs("div",{className:"absolute inset-0 flex items-center justify-center overflow-hidden rounded-t-2xl",children:[RINGS.map(({size:R,opacity:A,delay:L})=>jsxRuntime.jsx("div",{className:"absolute rounded-full",style:{width:R,height:R,border:`2px solid rgba(255,255,255,${A})`,animation:`wysdym-ring-pulse 2.5s ease-in-out ${L}s infinite`}},R)),jsxRuntime.jsx("div",{className:"relative w-10 h-10 rounded-full",style:{backgroundColor:"rgba(255,255,255,0.9)",boxShadow:"0 0 20px rgba(255,255,255,0.3)",animation:"wysdym-orb-breathe 2s ease-in-out infinite"}})]}),jsxRuntime.jsx("style",{children:`
|
|
474
|
+
@keyframes wysdym-ring-pulse {
|
|
475
|
+
0%, 100% { transform: scale(1); opacity: 1; }
|
|
476
|
+
50% { transform: scale(1.08); opacity: 0.5; }
|
|
477
|
+
}
|
|
478
|
+
@keyframes wysdym-orb-breathe {
|
|
479
|
+
0%, 100% { transform: scale(1); }
|
|
480
|
+
50% { transform: scale(1.08); }
|
|
481
|
+
}
|
|
482
|
+
`})]});function getDefaultExportFromCjs$1(T){return T&&T.__esModule&&Object.prototype.hasOwnProperty.call(T,"default")?T.default:T}var lottie$2={exports:{}},lottie$1=lottie$2.exports,hasRequiredLottie;function requireLottie(){return hasRequiredLottie||(hasRequiredLottie=1,(function(module,exports){typeof document<"u"&&typeof navigator<"u"&&(function(T,n){module.exports=n()})(lottie$1,(function(){var svgNS="http://www.w3.org/2000/svg",locationHref="",_useWebWorker=!1,initialDefaultFrame=-999999,setWebWorker=function(n){_useWebWorker=!!n},getWebWorker=function(){return _useWebWorker},setLocationHref=function(n){locationHref=n},getLocationHref=function(){return locationHref};function createTag(T){return document.createElement(T)}function extendPrototype(T,n){var P,R=T.length,A;for(P=0;P<R;P+=1){A=T[P].prototype;for(var L in A)Object.prototype.hasOwnProperty.call(A,L)&&(n.prototype[L]=A[L])}}function getDescriptor(T,n){return Object.getOwnPropertyDescriptor(T,n)}function createProxyFunction(T){function n(){}return n.prototype=T,n}var audioControllerFactory=(function(){function T(n){this.audios=[],this.audioFactory=n,this._volume=1,this._isMuted=!1}return T.prototype={addAudio:function(P){this.audios.push(P)},pause:function(){var P,R=this.audios.length;for(P=0;P<R;P+=1)this.audios[P].pause()},resume:function(){var P,R=this.audios.length;for(P=0;P<R;P+=1)this.audios[P].resume()},setRate:function(P){var R,A=this.audios.length;for(R=0;R<A;R+=1)this.audios[R].setRate(P)},createAudio:function(P){return this.audioFactory?this.audioFactory(P):window.Howl?new window.Howl({src:[P]}):{isPlaying:!1,play:function(){this.isPlaying=!0},seek:function(){this.isPlaying=!1},playing:function(){},rate:function(){},setVolume:function(){}}},setAudioFactory:function(P){this.audioFactory=P},setVolume:function(P){this._volume=P,this._updateVolume()},mute:function(){this._isMuted=!0,this._updateVolume()},unmute:function(){this._isMuted=!1,this._updateVolume()},getVolume:function(){return this._volume},_updateVolume:function(){var P,R=this.audios.length;for(P=0;P<R;P+=1)this.audios[P].volume(this._volume*(this._isMuted?0:1))}},function(){return new T}})(),createTypedArray=(function(){function T(P,R){var A=0,L=[],O;switch(P){case"int16":case"uint8c":O=1;break;default:O=1.1;break}for(A=0;A<R;A+=1)L.push(O);return L}function n(P,R){return P==="float32"?new Float32Array(R):P==="int16"?new Int16Array(R):P==="uint8c"?new Uint8ClampedArray(R):T(P,R)}return typeof Uint8ClampedArray=="function"&&typeof Float32Array=="function"?n:T})();function createSizedArray(T){return Array.apply(null,{length:T})}function _typeof$6(T){"@babel/helpers - typeof";return _typeof$6=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof$6(T)}var subframeEnabled=!0,expressionsPlugin=null,expressionsInterfaces=null,idPrefix$1="",isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),bmPow=Math.pow,bmSqrt=Math.sqrt,bmFloor=Math.floor,bmMax=Math.max,bmMin=Math.min,BMMath={};(function(){var T=["abs","acos","acosh","asin","asinh","atan","atanh","atan2","ceil","cbrt","expm1","clz32","cos","cosh","exp","floor","fround","hypot","imul","log","log1p","log2","log10","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc","E","LN10","LN2","LOG10E","LOG2E","PI","SQRT1_2","SQRT2"],n,P=T.length;for(n=0;n<P;n+=1)BMMath[T[n]]=Math[T[n]]})(),BMMath.random=Math.random,BMMath.abs=function(T){var n=_typeof$6(T);if(n==="object"&&T.length){var P=createSizedArray(T.length),R,A=T.length;for(R=0;R<A;R+=1)P[R]=Math.abs(T[R]);return P}return Math.abs(T)};var defaultCurveSegments=150,degToRads=Math.PI/180,roundCorner=.5519;function styleDiv(T){T.style.position="absolute",T.style.top=0,T.style.left=0,T.style.display="block",T.style.transformOrigin="0 0",T.style.webkitTransformOrigin="0 0",T.style.backfaceVisibility="visible",T.style.webkitBackfaceVisibility="visible",T.style.transformStyle="preserve-3d",T.style.webkitTransformStyle="preserve-3d",T.style.mozTransformStyle="preserve-3d"}function BMEnterFrameEvent(T,n,P,R){this.type=T,this.currentTime=n,this.totalTime=P,this.direction=R<0?-1:1}function BMCompleteEvent(T,n){this.type=T,this.direction=n<0?-1:1}function BMCompleteLoopEvent(T,n,P,R){this.type=T,this.currentLoop=P,this.totalLoops=n,this.direction=R<0?-1:1}function BMSegmentStartEvent(T,n,P){this.type=T,this.firstFrame=n,this.totalFrames=P}function BMDestroyEvent(T,n){this.type=T,this.target=n}function BMRenderFrameErrorEvent(T,n){this.type="renderFrameError",this.nativeError=T,this.currentTime=n}function BMConfigErrorEvent(T){this.type="configError",this.nativeError=T}var createElementID=(function(){var T=0;return function(){return T+=1,idPrefix$1+"__lottie_element_"+T}})();function HSVtoRGB(T,n,P){var R,A,L,O,N,V,j,B;switch(O=Math.floor(T*6),N=T*6-O,V=P*(1-n),j=P*(1-N*n),B=P*(1-(1-N)*n),O%6){case 0:R=P,A=B,L=V;break;case 1:R=j,A=P,L=V;break;case 2:R=V,A=P,L=B;break;case 3:R=V,A=j,L=P;break;case 4:R=B,A=V,L=P;break;case 5:R=P,A=V,L=j;break}return[R,A,L]}function RGBtoHSV(T,n,P){var R=Math.max(T,n,P),A=Math.min(T,n,P),L=R-A,O,N=R===0?0:L/R,V=R/255;switch(R){case A:O=0;break;case T:O=n-P+L*(n<P?6:0),O/=6*L;break;case n:O=P-T+L*2,O/=6*L;break;case P:O=T-n+L*4,O/=6*L;break}return[O,N,V]}function addSaturationToRGB(T,n){var P=RGBtoHSV(T[0]*255,T[1]*255,T[2]*255);return P[1]+=n,P[1]>1?P[1]=1:P[1]<=0&&(P[1]=0),HSVtoRGB(P[0],P[1],P[2])}function addBrightnessToRGB(T,n){var P=RGBtoHSV(T[0]*255,T[1]*255,T[2]*255);return P[2]+=n,P[2]>1?P[2]=1:P[2]<0&&(P[2]=0),HSVtoRGB(P[0],P[1],P[2])}function addHueToRGB(T,n){var P=RGBtoHSV(T[0]*255,T[1]*255,T[2]*255);return P[0]+=n/360,P[0]>1?P[0]-=1:P[0]<0&&(P[0]+=1),HSVtoRGB(P[0],P[1],P[2])}var rgbToHex=(function(){var T=[],n,P;for(n=0;n<256;n+=1)P=n.toString(16),T[n]=P.length===1?"0"+P:P;return function(R,A,L){return R<0&&(R=0),A<0&&(A=0),L<0&&(L=0),"#"+T[R]+T[A]+T[L]}})(),setSubframeEnabled=function(n){subframeEnabled=!!n},getSubframeEnabled=function(){return subframeEnabled},setExpressionsPlugin=function(n){expressionsPlugin=n},getExpressionsPlugin=function(){return expressionsPlugin},setExpressionInterfaces=function(n){expressionsInterfaces=n},getExpressionInterfaces=function(){return expressionsInterfaces},setDefaultCurveSegments=function(n){defaultCurveSegments=n},getDefaultCurveSegments=function(){return defaultCurveSegments},setIdPrefix=function(n){idPrefix$1=n};function createNS(T){return document.createElementNS(svgNS,T)}function _typeof$5(T){"@babel/helpers - typeof";return _typeof$5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof$5(T)}var dataManager=(function(){var T=1,n=[],P,R,A={onmessage:function(){},postMessage:function(q){P({data:q})}},L={postMessage:function(q){A.onmessage({data:q})}};function O(W){if(window.Worker&&window.Blob&&getWebWorker()){var q=new Blob(["var _workerSelf = self; self.onmessage = ",W.toString()],{type:"text/javascript"}),H=URL.createObjectURL(q);return new Worker(H)}return P=W,A}function N(){R||(R=O(function(q){function H(){function Q(fe,ne){var ce,ee,te=fe.length,oe,ae,de,ge;for(ee=0;ee<te;ee+=1)if(ce=fe[ee],"ks"in ce&&!ce.completed){if(ce.completed=!0,ce.hasMask){var ye=ce.masksProperties;for(ae=ye.length,oe=0;oe<ae;oe+=1)if(ye[oe].pt.k.i)Y(ye[oe].pt.k);else for(ge=ye[oe].pt.k.length,de=0;de<ge;de+=1)ye[oe].pt.k[de].s&&Y(ye[oe].pt.k[de].s[0]),ye[oe].pt.k[de].e&&Y(ye[oe].pt.k[de].e[0])}ce.ty===0?(ce.layers=G(ce.refId,ne),Q(ce.layers,ne)):ce.ty===4?K(ce.shapes):ce.ty===5&&ve(ce)}}function U(fe,ne){if(fe){var ce=0,ee=fe.length;for(ce=0;ce<ee;ce+=1)fe[ce].t===1&&(fe[ce].data.layers=G(fe[ce].data.refId,ne),Q(fe[ce].data.layers,ne))}}function J(fe,ne){for(var ce=0,ee=ne.length;ce<ee;){if(ne[ce].id===fe)return ne[ce];ce+=1}return null}function G(fe,ne){var ce=J(fe,ne);return ce?ce.layers.__used?JSON.parse(JSON.stringify(ce.layers)):(ce.layers.__used=!0,ce.layers):null}function K(fe){var ne,ce=fe.length,ee,te;for(ne=ce-1;ne>=0;ne-=1)if(fe[ne].ty==="sh")if(fe[ne].ks.k.i)Y(fe[ne].ks.k);else for(te=fe[ne].ks.k.length,ee=0;ee<te;ee+=1)fe[ne].ks.k[ee].s&&Y(fe[ne].ks.k[ee].s[0]),fe[ne].ks.k[ee].e&&Y(fe[ne].ks.k[ee].e[0]);else fe[ne].ty==="gr"&&K(fe[ne].it)}function Y(fe){var ne,ce=fe.i.length;for(ne=0;ne<ce;ne+=1)fe.i[ne][0]+=fe.v[ne][0],fe.i[ne][1]+=fe.v[ne][1],fe.o[ne][0]+=fe.v[ne][0],fe.o[ne][1]+=fe.v[ne][1]}function Z(fe,ne){var ce=ne?ne.split("."):[100,100,100];return fe[0]>ce[0]?!0:ce[0]>fe[0]?!1:fe[1]>ce[1]?!0:ce[1]>fe[1]?!1:fe[2]>ce[2]?!0:ce[2]>fe[2]?!1:null}var ie=(function(){var fe=[4,4,14];function ne(ee){var te=ee.t.d;ee.t.d={k:[{s:te,t:0}]}}function ce(ee){var te,oe=ee.length;for(te=0;te<oe;te+=1)ee[te].ty===5&&ne(ee[te])}return function(ee){if(Z(fe,ee.v)&&(ce(ee.layers),ee.assets)){var te,oe=ee.assets.length;for(te=0;te<oe;te+=1)ee.assets[te].layers&&ce(ee.assets[te].layers)}}})(),se=(function(){var fe=[4,7,99];return function(ne){if(ne.chars&&!Z(fe,ne.v)){var ce,ee=ne.chars.length;for(ce=0;ce<ee;ce+=1){var te=ne.chars[ce];te.data&&te.data.shapes&&(K(te.data.shapes),te.data.ip=0,te.data.op=99999,te.data.st=0,te.data.sr=1,te.data.ks={p:{k:[0,0],a:0},s:{k:[100,100],a:0},a:{k:[0,0],a:0},r:{k:0,a:0},o:{k:100,a:0}},ne.chars[ce].t||(te.data.shapes.push({ty:"no"}),te.data.shapes[0].it.push({p:{k:[0,0],a:0},s:{k:[100,100],a:0},a:{k:[0,0],a:0},r:{k:0,a:0},o:{k:100,a:0},sk:{k:0,a:0},sa:{k:0,a:0},ty:"tr"})))}}}})(),le=(function(){var fe=[5,7,15];function ne(ee){var te=ee.t.p;typeof te.a=="number"&&(te.a={a:0,k:te.a}),typeof te.p=="number"&&(te.p={a:0,k:te.p}),typeof te.r=="number"&&(te.r={a:0,k:te.r})}function ce(ee){var te,oe=ee.length;for(te=0;te<oe;te+=1)ee[te].ty===5&&ne(ee[te])}return function(ee){if(Z(fe,ee.v)&&(ce(ee.layers),ee.assets)){var te,oe=ee.assets.length;for(te=0;te<oe;te+=1)ee.assets[te].layers&&ce(ee.assets[te].layers)}}})(),pe=(function(){var fe=[4,1,9];function ne(ee){var te,oe=ee.length,ae,de;for(te=0;te<oe;te+=1)if(ee[te].ty==="gr")ne(ee[te].it);else if(ee[te].ty==="fl"||ee[te].ty==="st")if(ee[te].c.k&&ee[te].c.k[0].i)for(de=ee[te].c.k.length,ae=0;ae<de;ae+=1)ee[te].c.k[ae].s&&(ee[te].c.k[ae].s[0]/=255,ee[te].c.k[ae].s[1]/=255,ee[te].c.k[ae].s[2]/=255,ee[te].c.k[ae].s[3]/=255),ee[te].c.k[ae].e&&(ee[te].c.k[ae].e[0]/=255,ee[te].c.k[ae].e[1]/=255,ee[te].c.k[ae].e[2]/=255,ee[te].c.k[ae].e[3]/=255);else ee[te].c.k[0]/=255,ee[te].c.k[1]/=255,ee[te].c.k[2]/=255,ee[te].c.k[3]/=255}function ce(ee){var te,oe=ee.length;for(te=0;te<oe;te+=1)ee[te].ty===4&&ne(ee[te].shapes)}return function(ee){if(Z(fe,ee.v)&&(ce(ee.layers),ee.assets)){var te,oe=ee.assets.length;for(te=0;te<oe;te+=1)ee.assets[te].layers&&ce(ee.assets[te].layers)}}})(),ue=(function(){var fe=[4,4,18];function ne(ee){var te,oe=ee.length,ae,de;for(te=oe-1;te>=0;te-=1)if(ee[te].ty==="sh")if(ee[te].ks.k.i)ee[te].ks.k.c=ee[te].closed;else for(de=ee[te].ks.k.length,ae=0;ae<de;ae+=1)ee[te].ks.k[ae].s&&(ee[te].ks.k[ae].s[0].c=ee[te].closed),ee[te].ks.k[ae].e&&(ee[te].ks.k[ae].e[0].c=ee[te].closed);else ee[te].ty==="gr"&&ne(ee[te].it)}function ce(ee){var te,oe,ae=ee.length,de,ge,ye,Ee;for(oe=0;oe<ae;oe+=1){if(te=ee[oe],te.hasMask){var Pe=te.masksProperties;for(ge=Pe.length,de=0;de<ge;de+=1)if(Pe[de].pt.k.i)Pe[de].pt.k.c=Pe[de].cl;else for(Ee=Pe[de].pt.k.length,ye=0;ye<Ee;ye+=1)Pe[de].pt.k[ye].s&&(Pe[de].pt.k[ye].s[0].c=Pe[de].cl),Pe[de].pt.k[ye].e&&(Pe[de].pt.k[ye].e[0].c=Pe[de].cl)}te.ty===4&&ne(te.shapes)}}return function(ee){if(Z(fe,ee.v)&&(ce(ee.layers),ee.assets)){var te,oe=ee.assets.length;for(te=0;te<oe;te+=1)ee.assets[te].layers&&ce(ee.assets[te].layers)}}})();function he(fe){fe.__complete||(pe(fe),ie(fe),se(fe),le(fe),ue(fe),Q(fe.layers,fe.assets),U(fe.chars,fe.assets),fe.__complete=!0)}function ve(fe){fe.t.a.length===0&&"m"in fe.t.p}var be={};return be.completeData=he,be.checkColors=pe,be.checkChars=se,be.checkPathProperties=le,be.checkShapes=ue,be.completeLayers=Q,be}if(L.dataManager||(L.dataManager=H()),L.assetLoader||(L.assetLoader=(function(){function Q(J){var G=J.getResponseHeader("content-type");return G&&J.responseType==="json"&&G.indexOf("json")!==-1||J.response&&_typeof$5(J.response)==="object"?J.response:J.response&&typeof J.response=="string"?JSON.parse(J.response):J.responseText?JSON.parse(J.responseText):null}function U(J,G,K,Y){var Z,ie=new XMLHttpRequest;try{ie.responseType="json"}catch{}ie.onreadystatechange=function(){if(ie.readyState===4)if(ie.status===200)Z=Q(ie),K(Z);else try{Z=Q(ie),K(Z)}catch(se){Y&&Y(se)}};try{ie.open(["G","E","T"].join(""),J,!0)}catch{ie.open(["G","E","T"].join(""),G+"/"+J,!0)}ie.send()}return{load:U}})()),q.data.type==="loadAnimation")L.assetLoader.load(q.data.path,q.data.fullPath,function(Q){L.dataManager.completeData(Q),L.postMessage({id:q.data.id,payload:Q,status:"success"})},function(){L.postMessage({id:q.data.id,status:"error"})});else if(q.data.type==="complete"){var $=q.data.animation;L.dataManager.completeData($),L.postMessage({id:q.data.id,payload:$,status:"success"})}else q.data.type==="loadData"&&L.assetLoader.load(q.data.path,q.data.fullPath,function(Q){L.postMessage({id:q.data.id,payload:Q,status:"success"})},function(){L.postMessage({id:q.data.id,status:"error"})})}),R.onmessage=function(W){var q=W.data,H=q.id,$=n[H];n[H]=null,q.status==="success"?$.onComplete(q.payload):$.onError&&$.onError()})}function V(W,q){T+=1;var H="processId_"+T;return n[H]={onComplete:W,onError:q},H}function j(W,q,H){N();var $=V(q,H);R.postMessage({type:"loadAnimation",path:W,fullPath:window.location.origin+window.location.pathname,id:$})}function B(W,q,H){N();var $=V(q,H);R.postMessage({type:"loadData",path:W,fullPath:window.location.origin+window.location.pathname,id:$})}function z(W,q,H){N();var $=V(q,H);R.postMessage({type:"complete",animation:W,id:$})}return{loadAnimation:j,loadData:B,completeAnimation:z}})(),ImagePreloader=(function(){var T=(function(){var U=createTag("canvas");U.width=1,U.height=1;var J=U.getContext("2d");return J.fillStyle="rgba(0,0,0,0)",J.fillRect(0,0,1,1),U})();function n(){this.loadedAssets+=1,this.loadedAssets===this.totalImages&&this.loadedFootagesCount===this.totalFootages&&this.imagesLoadedCb&&this.imagesLoadedCb(null)}function P(){this.loadedFootagesCount+=1,this.loadedAssets===this.totalImages&&this.loadedFootagesCount===this.totalFootages&&this.imagesLoadedCb&&this.imagesLoadedCb(null)}function R(U,J,G){var K="";if(U.e)K=U.p;else if(J){var Y=U.p;Y.indexOf("images/")!==-1&&(Y=Y.split("/")[1]),K=J+Y}else K=G,K+=U.u?U.u:"",K+=U.p;return K}function A(U){var J=0,G=setInterval((function(){var K=U.getBBox();(K.width||J>500)&&(this._imageLoaded(),clearInterval(G)),J+=1}).bind(this),50)}function L(U){var J=R(U,this.assetsPath,this.path),G=createNS("image");isSafari?this.testImageLoaded(G):G.addEventListener("load",this._imageLoaded,!1),G.addEventListener("error",(function(){K.img=T,this._imageLoaded()}).bind(this),!1),G.setAttributeNS("http://www.w3.org/1999/xlink","href",J),this._elementHelper.append?this._elementHelper.append(G):this._elementHelper.appendChild(G);var K={img:G,assetData:U};return K}function O(U){var J=R(U,this.assetsPath,this.path),G=createTag("img");G.crossOrigin="anonymous",G.addEventListener("load",this._imageLoaded,!1),G.addEventListener("error",(function(){K.img=T,this._imageLoaded()}).bind(this),!1),G.src=J;var K={img:G,assetData:U};return K}function N(U){var J={assetData:U},G=R(U,this.assetsPath,this.path);return dataManager.loadData(G,(function(K){J.img=K,this._footageLoaded()}).bind(this),(function(){J.img={},this._footageLoaded()}).bind(this)),J}function V(U,J){this.imagesLoadedCb=J;var G,K=U.length;for(G=0;G<K;G+=1)U[G].layers||(!U[G].t||U[G].t==="seq"?(this.totalImages+=1,this.images.push(this._createImageData(U[G]))):U[G].t===3&&(this.totalFootages+=1,this.images.push(this.createFootageData(U[G]))))}function j(U){this.path=U||""}function B(U){this.assetsPath=U||""}function z(U){for(var J=0,G=this.images.length;J<G;){if(this.images[J].assetData===U)return this.images[J].img;J+=1}return null}function W(){this.imagesLoadedCb=null,this.images.length=0}function q(){return this.totalImages===this.loadedAssets}function H(){return this.totalFootages===this.loadedFootagesCount}function $(U,J){U==="svg"?(this._elementHelper=J,this._createImageData=this.createImageData.bind(this)):this._createImageData=this.createImgData.bind(this)}function Q(){this._imageLoaded=n.bind(this),this._footageLoaded=P.bind(this),this.testImageLoaded=A.bind(this),this.createFootageData=N.bind(this),this.assetsPath="",this.path="",this.totalImages=0,this.totalFootages=0,this.loadedAssets=0,this.loadedFootagesCount=0,this.imagesLoadedCb=null,this.images=[]}return Q.prototype={loadAssets:V,setAssetsPath:B,setPath:j,loadedImages:q,loadedFootages:H,destroy:W,getAsset:z,createImgData:O,createImageData:L,imageLoaded:n,footageLoaded:P,setCacheType:$},Q})();function BaseEvent(){}BaseEvent.prototype={triggerEvent:function(n,P){if(this._cbs[n])for(var R=this._cbs[n],A=0;A<R.length;A+=1)R[A](P)},addEventListener:function(n,P){return this._cbs[n]||(this._cbs[n]=[]),this._cbs[n].push(P),(function(){this.removeEventListener(n,P)}).bind(this)},removeEventListener:function(n,P){if(!P)this._cbs[n]=null;else if(this._cbs[n]){for(var R=0,A=this._cbs[n].length;R<A;)this._cbs[n][R]===P&&(this._cbs[n].splice(R,1),R-=1,A-=1),R+=1;this._cbs[n].length||(this._cbs[n]=null)}}};var markerParser=(function(){function T(n){for(var P=n.split(`\r
|
|
483
|
+
`),R={},A,L=0,O=0;O<P.length;O+=1)A=P[O].split(":"),A.length===2&&(R[A[0]]=A[1].trim(),L+=1);if(L===0)throw new Error;return R}return function(n){for(var P=[],R=0;R<n.length;R+=1){var A=n[R],L={time:A.tm,duration:A.dr};try{L.payload=JSON.parse(n[R].cm)}catch{try{L.payload=T(n[R].cm)}catch{L.payload={name:n[R].cm}}}P.push(L)}return P}})(),ProjectInterface=(function(){function T(n){this.compositions.push(n)}return function(){function n(P){for(var R=0,A=this.compositions.length;R<A;){if(this.compositions[R].data&&this.compositions[R].data.nm===P)return this.compositions[R].prepareFrame&&this.compositions[R].data.xt&&this.compositions[R].prepareFrame(this.currentFrame),this.compositions[R].compInterface;R+=1}return null}return n.compositions=[],n.currentFrame=0,n.registerComposition=T,n}})(),renderers={},registerRenderer=function(n,P){renderers[n]=P};function getRenderer(T){return renderers[T]}function getRegisteredRenderer(){if(renderers.canvas)return"canvas";for(var T in renderers)if(renderers[T])return T;return""}function _typeof$4(T){"@babel/helpers - typeof";return _typeof$4=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof$4(T)}var AnimationItem=function(){this._cbs=[],this.name="",this.path="",this.isLoaded=!1,this.currentFrame=0,this.currentRawFrame=0,this.firstFrame=0,this.totalFrames=0,this.frameRate=0,this.frameMult=0,this.playSpeed=1,this.playDirection=1,this.playCount=0,this.animationData={},this.assets=[],this.isPaused=!0,this.autoplay=!1,this.loop=!0,this.renderer=null,this.animationID=createElementID(),this.assetsPath="",this.timeCompleted=0,this.segmentPos=0,this.isSubframeEnabled=getSubframeEnabled(),this.segments=[],this._idle=!0,this._completedLoop=!1,this.projectInterface=ProjectInterface(),this.imagePreloader=new ImagePreloader,this.audioController=audioControllerFactory(),this.markers=[],this.configAnimation=this.configAnimation.bind(this),this.onSetupError=this.onSetupError.bind(this),this.onSegmentComplete=this.onSegmentComplete.bind(this),this.drawnFrameEvent=new BMEnterFrameEvent("drawnFrame",0,0,0),this.expressionsPlugin=getExpressionsPlugin()};extendPrototype([BaseEvent],AnimationItem),AnimationItem.prototype.setParams=function(T){(T.wrapper||T.container)&&(this.wrapper=T.wrapper||T.container);var n="svg";T.animType?n=T.animType:T.renderer&&(n=T.renderer);var P=getRenderer(n);this.renderer=new P(this,T.rendererSettings),this.imagePreloader.setCacheType(n,this.renderer.globalData.defs),this.renderer.setProjectInterface(this.projectInterface),this.animType=n,T.loop===""||T.loop===null||T.loop===void 0||T.loop===!0?this.loop=!0:T.loop===!1?this.loop=!1:this.loop=parseInt(T.loop,10),this.autoplay="autoplay"in T?T.autoplay:!0,this.name=T.name?T.name:"",this.autoloadSegments=Object.prototype.hasOwnProperty.call(T,"autoloadSegments")?T.autoloadSegments:!0,this.assetsPath=T.assetsPath,this.initialSegment=T.initialSegment,T.audioFactory&&this.audioController.setAudioFactory(T.audioFactory),T.animationData?this.setupAnimation(T.animationData):T.path&&(T.path.lastIndexOf("\\")!==-1?this.path=T.path.substr(0,T.path.lastIndexOf("\\")+1):this.path=T.path.substr(0,T.path.lastIndexOf("/")+1),this.fileName=T.path.substr(T.path.lastIndexOf("/")+1),this.fileName=this.fileName.substr(0,this.fileName.lastIndexOf(".json")),dataManager.loadAnimation(T.path,this.configAnimation,this.onSetupError))},AnimationItem.prototype.onSetupError=function(){this.trigger("data_failed")},AnimationItem.prototype.setupAnimation=function(T){dataManager.completeAnimation(T,this.configAnimation)},AnimationItem.prototype.setData=function(T,n){n&&_typeof$4(n)!=="object"&&(n=JSON.parse(n));var P={wrapper:T,animationData:n},R=T.attributes;P.path=R.getNamedItem("data-animation-path")?R.getNamedItem("data-animation-path").value:R.getNamedItem("data-bm-path")?R.getNamedItem("data-bm-path").value:R.getNamedItem("bm-path")?R.getNamedItem("bm-path").value:"",P.animType=R.getNamedItem("data-anim-type")?R.getNamedItem("data-anim-type").value:R.getNamedItem("data-bm-type")?R.getNamedItem("data-bm-type").value:R.getNamedItem("bm-type")?R.getNamedItem("bm-type").value:R.getNamedItem("data-bm-renderer")?R.getNamedItem("data-bm-renderer").value:R.getNamedItem("bm-renderer")?R.getNamedItem("bm-renderer").value:getRegisteredRenderer()||"canvas";var A=R.getNamedItem("data-anim-loop")?R.getNamedItem("data-anim-loop").value:R.getNamedItem("data-bm-loop")?R.getNamedItem("data-bm-loop").value:R.getNamedItem("bm-loop")?R.getNamedItem("bm-loop").value:"";A==="false"?P.loop=!1:A==="true"?P.loop=!0:A!==""&&(P.loop=parseInt(A,10));var L=R.getNamedItem("data-anim-autoplay")?R.getNamedItem("data-anim-autoplay").value:R.getNamedItem("data-bm-autoplay")?R.getNamedItem("data-bm-autoplay").value:R.getNamedItem("bm-autoplay")?R.getNamedItem("bm-autoplay").value:!0;P.autoplay=L!=="false",P.name=R.getNamedItem("data-name")?R.getNamedItem("data-name").value:R.getNamedItem("data-bm-name")?R.getNamedItem("data-bm-name").value:R.getNamedItem("bm-name")?R.getNamedItem("bm-name").value:"";var O=R.getNamedItem("data-anim-prerender")?R.getNamedItem("data-anim-prerender").value:R.getNamedItem("data-bm-prerender")?R.getNamedItem("data-bm-prerender").value:R.getNamedItem("bm-prerender")?R.getNamedItem("bm-prerender").value:"";O==="false"&&(P.prerender=!1),P.path?this.setParams(P):this.trigger("destroy")},AnimationItem.prototype.includeLayers=function(T){T.op>this.animationData.op&&(this.animationData.op=T.op,this.totalFrames=Math.floor(T.op-this.animationData.ip));var n=this.animationData.layers,P,R=n.length,A=T.layers,L,O=A.length;for(L=0;L<O;L+=1)for(P=0;P<R;){if(n[P].id===A[L].id){n[P]=A[L];break}P+=1}if((T.chars||T.fonts)&&(this.renderer.globalData.fontManager.addChars(T.chars),this.renderer.globalData.fontManager.addFonts(T.fonts,this.renderer.globalData.defs)),T.assets)for(R=T.assets.length,P=0;P<R;P+=1)this.animationData.assets.push(T.assets[P]);this.animationData.__complete=!1,dataManager.completeAnimation(this.animationData,this.onSegmentComplete)},AnimationItem.prototype.onSegmentComplete=function(T){this.animationData=T;var n=getExpressionsPlugin();n&&n.initExpressions(this),this.loadNextSegment()},AnimationItem.prototype.loadNextSegment=function(){var T=this.animationData.segments;if(!T||T.length===0||!this.autoloadSegments){this.trigger("data_ready"),this.timeCompleted=this.totalFrames;return}var n=T.shift();this.timeCompleted=n.time*this.frameRate;var P=this.path+this.fileName+"_"+this.segmentPos+".json";this.segmentPos+=1,dataManager.loadData(P,this.includeLayers.bind(this),(function(){this.trigger("data_failed")}).bind(this))},AnimationItem.prototype.loadSegments=function(){var T=this.animationData.segments;T||(this.timeCompleted=this.totalFrames),this.loadNextSegment()},AnimationItem.prototype.imagesLoaded=function(){this.trigger("loaded_images"),this.checkLoaded()},AnimationItem.prototype.preloadImages=function(){this.imagePreloader.setAssetsPath(this.assetsPath),this.imagePreloader.setPath(this.path),this.imagePreloader.loadAssets(this.animationData.assets,this.imagesLoaded.bind(this))},AnimationItem.prototype.configAnimation=function(T){if(this.renderer)try{this.animationData=T,this.initialSegment?(this.totalFrames=Math.floor(this.initialSegment[1]-this.initialSegment[0]),this.firstFrame=Math.round(this.initialSegment[0])):(this.totalFrames=Math.floor(this.animationData.op-this.animationData.ip),this.firstFrame=Math.round(this.animationData.ip)),this.renderer.configAnimation(T),T.assets||(T.assets=[]),this.assets=this.animationData.assets,this.frameRate=this.animationData.fr,this.frameMult=this.animationData.fr/1e3,this.renderer.searchExtraCompositions(T.assets),this.markers=markerParser(T.markers||[]),this.trigger("config_ready"),this.preloadImages(),this.loadSegments(),this.updaFrameModifier(),this.waitForFontsLoaded(),this.isPaused&&this.audioController.pause()}catch(n){this.triggerConfigError(n)}},AnimationItem.prototype.waitForFontsLoaded=function(){this.renderer&&(this.renderer.globalData.fontManager.isLoaded?this.checkLoaded():setTimeout(this.waitForFontsLoaded.bind(this),20))},AnimationItem.prototype.checkLoaded=function(){if(!this.isLoaded&&this.renderer.globalData.fontManager.isLoaded&&(this.imagePreloader.loadedImages()||this.renderer.rendererType!=="canvas")&&this.imagePreloader.loadedFootages()){this.isLoaded=!0;var T=getExpressionsPlugin();T&&T.initExpressions(this),this.renderer.initItems(),setTimeout((function(){this.trigger("DOMLoaded")}).bind(this),0),this.gotoFrame(),this.autoplay&&this.play()}},AnimationItem.prototype.resize=function(T,n){var P=typeof T=="number"?T:void 0,R=typeof n=="number"?n:void 0;this.renderer.updateContainerSize(P,R)},AnimationItem.prototype.setSubframe=function(T){this.isSubframeEnabled=!!T},AnimationItem.prototype.gotoFrame=function(){this.currentFrame=this.isSubframeEnabled?this.currentRawFrame:~~this.currentRawFrame,this.timeCompleted!==this.totalFrames&&this.currentFrame>this.timeCompleted&&(this.currentFrame=this.timeCompleted),this.trigger("enterFrame"),this.renderFrame(),this.trigger("drawnFrame")},AnimationItem.prototype.renderFrame=function(){if(!(this.isLoaded===!1||!this.renderer))try{this.expressionsPlugin&&this.expressionsPlugin.resetFrame(),this.renderer.renderFrame(this.currentFrame+this.firstFrame)}catch(T){this.triggerRenderFrameError(T)}},AnimationItem.prototype.play=function(T){T&&this.name!==T||this.isPaused===!0&&(this.isPaused=!1,this.trigger("_play"),this.audioController.resume(),this._idle&&(this._idle=!1,this.trigger("_active")))},AnimationItem.prototype.pause=function(T){T&&this.name!==T||this.isPaused===!1&&(this.isPaused=!0,this.trigger("_pause"),this._idle=!0,this.trigger("_idle"),this.audioController.pause())},AnimationItem.prototype.togglePause=function(T){T&&this.name!==T||(this.isPaused===!0?this.play():this.pause())},AnimationItem.prototype.stop=function(T){T&&this.name!==T||(this.pause(),this.playCount=0,this._completedLoop=!1,this.setCurrentRawFrameValue(0))},AnimationItem.prototype.getMarkerData=function(T){for(var n,P=0;P<this.markers.length;P+=1)if(n=this.markers[P],n.payload&&n.payload.name===T)return n;return null},AnimationItem.prototype.goToAndStop=function(T,n,P){if(!(P&&this.name!==P)){var R=Number(T);if(isNaN(R)){var A=this.getMarkerData(T);A&&this.goToAndStop(A.time,!0)}else n?this.setCurrentRawFrameValue(T):this.setCurrentRawFrameValue(T*this.frameModifier);this.pause()}},AnimationItem.prototype.goToAndPlay=function(T,n,P){if(!(P&&this.name!==P)){var R=Number(T);if(isNaN(R)){var A=this.getMarkerData(T);A&&(A.duration?this.playSegments([A.time,A.time+A.duration],!0):this.goToAndStop(A.time,!0))}else this.goToAndStop(R,n,P);this.play()}},AnimationItem.prototype.advanceTime=function(T){if(!(this.isPaused===!0||this.isLoaded===!1)){var n=this.currentRawFrame+T*this.frameModifier,P=!1;n>=this.totalFrames-1&&this.frameModifier>0?!this.loop||this.playCount===this.loop?this.checkSegments(n>this.totalFrames?n%this.totalFrames:0)||(P=!0,n=this.totalFrames-1):n>=this.totalFrames?(this.playCount+=1,this.checkSegments(n%this.totalFrames)||(this.setCurrentRawFrameValue(n%this.totalFrames),this._completedLoop=!0,this.trigger("loopComplete"))):this.setCurrentRawFrameValue(n):n<0?this.checkSegments(n%this.totalFrames)||(this.loop&&!(this.playCount--<=0&&this.loop!==!0)?(this.setCurrentRawFrameValue(this.totalFrames+n%this.totalFrames),this._completedLoop?this.trigger("loopComplete"):this._completedLoop=!0):(P=!0,n=0)):this.setCurrentRawFrameValue(n),P&&(this.setCurrentRawFrameValue(n),this.pause(),this.trigger("complete"))}},AnimationItem.prototype.adjustSegment=function(T,n){this.playCount=0,T[1]<T[0]?(this.frameModifier>0&&(this.playSpeed<0?this.setSpeed(-this.playSpeed):this.setDirection(-1)),this.totalFrames=T[0]-T[1],this.timeCompleted=this.totalFrames,this.firstFrame=T[1],this.setCurrentRawFrameValue(this.totalFrames-.001-n)):T[1]>T[0]&&(this.frameModifier<0&&(this.playSpeed<0?this.setSpeed(-this.playSpeed):this.setDirection(1)),this.totalFrames=T[1]-T[0],this.timeCompleted=this.totalFrames,this.firstFrame=T[0],this.setCurrentRawFrameValue(.001+n)),this.trigger("segmentStart")},AnimationItem.prototype.setSegment=function(T,n){var P=-1;this.isPaused&&(this.currentRawFrame+this.firstFrame<T?P=T:this.currentRawFrame+this.firstFrame>n&&(P=n-T)),this.firstFrame=T,this.totalFrames=n-T,this.timeCompleted=this.totalFrames,P!==-1&&this.goToAndStop(P,!0)},AnimationItem.prototype.playSegments=function(T,n){if(n&&(this.segments.length=0),_typeof$4(T[0])==="object"){var P,R=T.length;for(P=0;P<R;P+=1)this.segments.push(T[P])}else this.segments.push(T);this.segments.length&&n&&this.adjustSegment(this.segments.shift(),0),this.isPaused&&this.play()},AnimationItem.prototype.resetSegments=function(T){this.segments.length=0,this.segments.push([this.animationData.ip,this.animationData.op]),T&&this.checkSegments(0)},AnimationItem.prototype.checkSegments=function(T){return this.segments.length?(this.adjustSegment(this.segments.shift(),T),!0):!1},AnimationItem.prototype.destroy=function(T){T&&this.name!==T||!this.renderer||(this.renderer.destroy(),this.imagePreloader.destroy(),this.trigger("destroy"),this._cbs=null,this.onEnterFrame=null,this.onLoopComplete=null,this.onComplete=null,this.onSegmentStart=null,this.onDestroy=null,this.renderer=null,this.expressionsPlugin=null,this.imagePreloader=null,this.projectInterface=null)},AnimationItem.prototype.setCurrentRawFrameValue=function(T){this.currentRawFrame=T,this.gotoFrame()},AnimationItem.prototype.setSpeed=function(T){this.playSpeed=T,this.updaFrameModifier()},AnimationItem.prototype.setDirection=function(T){this.playDirection=T<0?-1:1,this.updaFrameModifier()},AnimationItem.prototype.setLoop=function(T){this.loop=T},AnimationItem.prototype.setVolume=function(T,n){n&&this.name!==n||this.audioController.setVolume(T)},AnimationItem.prototype.getVolume=function(){return this.audioController.getVolume()},AnimationItem.prototype.mute=function(T){T&&this.name!==T||this.audioController.mute()},AnimationItem.prototype.unmute=function(T){T&&this.name!==T||this.audioController.unmute()},AnimationItem.prototype.updaFrameModifier=function(){this.frameModifier=this.frameMult*this.playSpeed*this.playDirection,this.audioController.setRate(this.playSpeed*this.playDirection)},AnimationItem.prototype.getPath=function(){return this.path},AnimationItem.prototype.getAssetsPath=function(T){var n="";if(T.e)n=T.p;else if(this.assetsPath){var P=T.p;P.indexOf("images/")!==-1&&(P=P.split("/")[1]),n=this.assetsPath+P}else n=this.path,n+=T.u?T.u:"",n+=T.p;return n},AnimationItem.prototype.getAssetData=function(T){for(var n=0,P=this.assets.length;n<P;){if(T===this.assets[n].id)return this.assets[n];n+=1}return null},AnimationItem.prototype.hide=function(){this.renderer.hide()},AnimationItem.prototype.show=function(){this.renderer.show()},AnimationItem.prototype.getDuration=function(T){return T?this.totalFrames:this.totalFrames/this.frameRate},AnimationItem.prototype.updateDocumentData=function(T,n,P){try{var R=this.renderer.getElementByPath(T);R.updateDocumentData(n,P)}catch{}},AnimationItem.prototype.trigger=function(T){if(this._cbs&&this._cbs[T])switch(T){case"enterFrame":this.triggerEvent(T,new BMEnterFrameEvent(T,this.currentFrame,this.totalFrames,this.frameModifier));break;case"drawnFrame":this.drawnFrameEvent.currentTime=this.currentFrame,this.drawnFrameEvent.totalTime=this.totalFrames,this.drawnFrameEvent.direction=this.frameModifier,this.triggerEvent(T,this.drawnFrameEvent);break;case"loopComplete":this.triggerEvent(T,new BMCompleteLoopEvent(T,this.loop,this.playCount,this.frameMult));break;case"complete":this.triggerEvent(T,new BMCompleteEvent(T,this.frameMult));break;case"segmentStart":this.triggerEvent(T,new BMSegmentStartEvent(T,this.firstFrame,this.totalFrames));break;case"destroy":this.triggerEvent(T,new BMDestroyEvent(T,this));break;default:this.triggerEvent(T)}T==="enterFrame"&&this.onEnterFrame&&this.onEnterFrame.call(this,new BMEnterFrameEvent(T,this.currentFrame,this.totalFrames,this.frameMult)),T==="loopComplete"&&this.onLoopComplete&&this.onLoopComplete.call(this,new BMCompleteLoopEvent(T,this.loop,this.playCount,this.frameMult)),T==="complete"&&this.onComplete&&this.onComplete.call(this,new BMCompleteEvent(T,this.frameMult)),T==="segmentStart"&&this.onSegmentStart&&this.onSegmentStart.call(this,new BMSegmentStartEvent(T,this.firstFrame,this.totalFrames)),T==="destroy"&&this.onDestroy&&this.onDestroy.call(this,new BMDestroyEvent(T,this))},AnimationItem.prototype.triggerRenderFrameError=function(T){var n=new BMRenderFrameErrorEvent(T,this.currentFrame);this.triggerEvent("error",n),this.onError&&this.onError.call(this,n)},AnimationItem.prototype.triggerConfigError=function(T){var n=new BMConfigErrorEvent(T,this.currentFrame);this.triggerEvent("error",n),this.onError&&this.onError.call(this,n)};var animationManager=(function(){var T={},n=[],P=0,R=0,A=0,L=!0,O=!1;function N(ne){for(var ce=0,ee=ne.target;ce<R;)n[ce].animation===ee&&(n.splice(ce,1),ce-=1,R-=1,ee.isPaused||z()),ce+=1}function V(ne,ce){if(!ne)return null;for(var ee=0;ee<R;){if(n[ee].elem===ne&&n[ee].elem!==null)return n[ee].animation;ee+=1}var te=new AnimationItem;return W(te,ne),te.setData(ne,ce),te}function j(){var ne,ce=n.length,ee=[];for(ne=0;ne<ce;ne+=1)ee.push(n[ne].animation);return ee}function B(){A+=1,pe()}function z(){A-=1}function W(ne,ce){ne.addEventListener("destroy",N),ne.addEventListener("_active",B),ne.addEventListener("_idle",z),n.push({elem:ce,animation:ne}),R+=1}function q(ne){var ce=new AnimationItem;return W(ce,null),ce.setParams(ne),ce}function H(ne,ce){var ee;for(ee=0;ee<R;ee+=1)n[ee].animation.setSpeed(ne,ce)}function $(ne,ce){var ee;for(ee=0;ee<R;ee+=1)n[ee].animation.setDirection(ne,ce)}function Q(ne){var ce;for(ce=0;ce<R;ce+=1)n[ce].animation.play(ne)}function U(ne){var ce=ne-P,ee;for(ee=0;ee<R;ee+=1)n[ee].animation.advanceTime(ce);P=ne,A&&!O?window.requestAnimationFrame(U):L=!0}function J(ne){P=ne,window.requestAnimationFrame(U)}function G(ne){var ce;for(ce=0;ce<R;ce+=1)n[ce].animation.pause(ne)}function K(ne,ce,ee){var te;for(te=0;te<R;te+=1)n[te].animation.goToAndStop(ne,ce,ee)}function Y(ne){var ce;for(ce=0;ce<R;ce+=1)n[ce].animation.stop(ne)}function Z(ne){var ce;for(ce=0;ce<R;ce+=1)n[ce].animation.togglePause(ne)}function ie(ne){var ce;for(ce=R-1;ce>=0;ce-=1)n[ce].animation.destroy(ne)}function se(ne,ce,ee){var te=[].concat([].slice.call(document.getElementsByClassName("lottie")),[].slice.call(document.getElementsByClassName("bodymovin"))),oe,ae=te.length;for(oe=0;oe<ae;oe+=1)ee&&te[oe].setAttribute("data-bm-type",ee),V(te[oe],ne);if(ce&&ae===0){ee||(ee="svg");var de=document.getElementsByTagName("body")[0];de.innerText="";var ge=createTag("div");ge.style.width="100%",ge.style.height="100%",ge.setAttribute("data-bm-type",ee),de.appendChild(ge),V(ge,ne)}}function le(){var ne;for(ne=0;ne<R;ne+=1)n[ne].animation.resize()}function pe(){!O&&A&&L&&(window.requestAnimationFrame(J),L=!1)}function ue(){O=!0}function he(){O=!1,pe()}function ve(ne,ce){var ee;for(ee=0;ee<R;ee+=1)n[ee].animation.setVolume(ne,ce)}function be(ne){var ce;for(ce=0;ce<R;ce+=1)n[ce].animation.mute(ne)}function fe(ne){var ce;for(ce=0;ce<R;ce+=1)n[ce].animation.unmute(ne)}return T.registerAnimation=V,T.loadAnimation=q,T.setSpeed=H,T.setDirection=$,T.play=Q,T.pause=G,T.stop=Y,T.togglePause=Z,T.searchAnimations=se,T.resize=le,T.goToAndStop=K,T.destroy=ie,T.freeze=ue,T.unfreeze=he,T.setVolume=ve,T.mute=be,T.unmute=fe,T.getRegisteredAnimations=j,T})(),BezierFactory=(function(){var T={};T.getBezierEasing=P;var n={};function P(J,G,K,Y,Z){var ie=Z||("bez_"+J+"_"+G+"_"+K+"_"+Y).replace(/\./g,"p");if(n[ie])return n[ie];var se=new U([J,G,K,Y]);return n[ie]=se,se}var R=4,A=.001,L=1e-7,O=10,N=11,V=1/(N-1),j=typeof Float32Array=="function";function B(J,G){return 1-3*G+3*J}function z(J,G){return 3*G-6*J}function W(J){return 3*J}function q(J,G,K){return((B(G,K)*J+z(G,K))*J+W(G))*J}function H(J,G,K){return 3*B(G,K)*J*J+2*z(G,K)*J+W(G)}function $(J,G,K,Y,Z){var ie,se,le=0;do se=G+(K-G)/2,ie=q(se,Y,Z)-J,ie>0?K=se:G=se;while(Math.abs(ie)>L&&++le<O);return se}function Q(J,G,K,Y){for(var Z=0;Z<R;++Z){var ie=H(G,K,Y);if(ie===0)return G;var se=q(G,K,Y)-J;G-=se/ie}return G}function U(J){this._p=J,this._mSampleValues=j?new Float32Array(N):new Array(N),this._precomputed=!1,this.get=this.get.bind(this)}return U.prototype={get:function(G){var K=this._p[0],Y=this._p[1],Z=this._p[2],ie=this._p[3];return this._precomputed||this._precompute(),K===Y&&Z===ie?G:G===0?0:G===1?1:q(this._getTForX(G),Y,ie)},_precompute:function(){var G=this._p[0],K=this._p[1],Y=this._p[2],Z=this._p[3];this._precomputed=!0,(G!==K||Y!==Z)&&this._calcSampleValues()},_calcSampleValues:function(){for(var G=this._p[0],K=this._p[2],Y=0;Y<N;++Y)this._mSampleValues[Y]=q(Y*V,G,K)},_getTForX:function(G){for(var K=this._p[0],Y=this._p[2],Z=this._mSampleValues,ie=0,se=1,le=N-1;se!==le&&Z[se]<=G;++se)ie+=V;--se;var pe=(G-Z[se])/(Z[se+1]-Z[se]),ue=ie+pe*V,he=H(ue,K,Y);return he>=A?Q(G,ue,K,Y):he===0?ue:$(G,ie,ie+V,K,Y)}},T})(),pooling=(function(){function T(n){return n.concat(createSizedArray(n.length))}return{double:T}})(),poolFactory=(function(){return function(T,n,P){var R=0,A=T,L=createSizedArray(A),O={newElement:N,release:V};function N(){var j;return R?(R-=1,j=L[R]):j=n(),j}function V(j){R===A&&(L=pooling.double(L),A*=2),P&&P(j),L[R]=j,R+=1}return O}})(),bezierLengthPool=(function(){function T(){return{addedLength:0,percents:createTypedArray("float32",getDefaultCurveSegments()),lengths:createTypedArray("float32",getDefaultCurveSegments())}}return poolFactory(8,T)})(),segmentsLengthPool=(function(){function T(){return{lengths:[],totalLength:0}}function n(P){var R,A=P.lengths.length;for(R=0;R<A;R+=1)bezierLengthPool.release(P.lengths[R]);P.lengths.length=0}return poolFactory(8,T,n)})();function bezFunction(){var T=Math;function n(W,q,H,$,Q,U){var J=W*$+q*Q+H*U-Q*$-U*W-H*q;return J>-.001&&J<.001}function P(W,q,H,$,Q,U,J,G,K){if(H===0&&U===0&&K===0)return n(W,q,$,Q,J,G);var Y=T.sqrt(T.pow($-W,2)+T.pow(Q-q,2)+T.pow(U-H,2)),Z=T.sqrt(T.pow(J-W,2)+T.pow(G-q,2)+T.pow(K-H,2)),ie=T.sqrt(T.pow(J-$,2)+T.pow(G-Q,2)+T.pow(K-U,2)),se;return Y>Z?Y>ie?se=Y-Z-ie:se=ie-Z-Y:ie>Z?se=ie-Z-Y:se=Z-Y-ie,se>-1e-4&&se<1e-4}var R=(function(){return function(W,q,H,$){var Q=getDefaultCurveSegments(),U,J,G,K,Y,Z=0,ie,se=[],le=[],pe=bezierLengthPool.newElement();for(G=H.length,U=0;U<Q;U+=1){for(Y=U/(Q-1),ie=0,J=0;J<G;J+=1)K=bmPow(1-Y,3)*W[J]+3*bmPow(1-Y,2)*Y*H[J]+3*(1-Y)*bmPow(Y,2)*$[J]+bmPow(Y,3)*q[J],se[J]=K,le[J]!==null&&(ie+=bmPow(se[J]-le[J],2)),le[J]=se[J];ie&&(ie=bmSqrt(ie),Z+=ie),pe.percents[U]=Y,pe.lengths[U]=Z}return pe.addedLength=Z,pe}})();function A(W){var q=segmentsLengthPool.newElement(),H=W.c,$=W.v,Q=W.o,U=W.i,J,G=W._length,K=q.lengths,Y=0;for(J=0;J<G-1;J+=1)K[J]=R($[J],$[J+1],Q[J],U[J+1]),Y+=K[J].addedLength;return H&&G&&(K[J]=R($[J],$[0],Q[J],U[0]),Y+=K[J].addedLength),q.totalLength=Y,q}function L(W){this.segmentLength=0,this.points=new Array(W)}function O(W,q){this.partialLength=W,this.point=q}var N=(function(){var W={};return function(q,H,$,Q){var U=(q[0]+"_"+q[1]+"_"+H[0]+"_"+H[1]+"_"+$[0]+"_"+$[1]+"_"+Q[0]+"_"+Q[1]).replace(/\./g,"p");if(!W[U]){var J=getDefaultCurveSegments(),G,K,Y,Z,ie,se=0,le,pe,ue=null;q.length===2&&(q[0]!==H[0]||q[1]!==H[1])&&n(q[0],q[1],H[0],H[1],q[0]+$[0],q[1]+$[1])&&n(q[0],q[1],H[0],H[1],H[0]+Q[0],H[1]+Q[1])&&(J=2);var he=new L(J);for(Y=$.length,G=0;G<J;G+=1){for(pe=createSizedArray(Y),ie=G/(J-1),le=0,K=0;K<Y;K+=1)Z=bmPow(1-ie,3)*q[K]+3*bmPow(1-ie,2)*ie*(q[K]+$[K])+3*(1-ie)*bmPow(ie,2)*(H[K]+Q[K])+bmPow(ie,3)*H[K],pe[K]=Z,ue!==null&&(le+=bmPow(pe[K]-ue[K],2));le=bmSqrt(le),se+=le,he.points[G]=new O(le,pe),ue=pe}he.segmentLength=se,W[U]=he}return W[U]}})();function V(W,q){var H=q.percents,$=q.lengths,Q=H.length,U=bmFloor((Q-1)*W),J=W*q.addedLength,G=0;if(U===Q-1||U===0||J===$[U])return H[U];for(var K=$[U]>J?-1:1,Y=!0;Y;)if($[U]<=J&&$[U+1]>J?(G=(J-$[U])/($[U+1]-$[U]),Y=!1):U+=K,U<0||U>=Q-1){if(U===Q-1)return H[U];Y=!1}return H[U]+(H[U+1]-H[U])*G}function j(W,q,H,$,Q,U){var J=V(Q,U),G=1-J,K=T.round((G*G*G*W[0]+(J*G*G+G*J*G+G*G*J)*H[0]+(J*J*G+G*J*J+J*G*J)*$[0]+J*J*J*q[0])*1e3)/1e3,Y=T.round((G*G*G*W[1]+(J*G*G+G*J*G+G*G*J)*H[1]+(J*J*G+G*J*J+J*G*J)*$[1]+J*J*J*q[1])*1e3)/1e3;return[K,Y]}var B=createTypedArray("float32",8);function z(W,q,H,$,Q,U,J){Q<0?Q=0:Q>1&&(Q=1);var G=V(Q,J);U=U>1?1:U;var K=V(U,J),Y,Z=W.length,ie=1-G,se=1-K,le=ie*ie*ie,pe=G*ie*ie*3,ue=G*G*ie*3,he=G*G*G,ve=ie*ie*se,be=G*ie*se+ie*G*se+ie*ie*K,fe=G*G*se+ie*G*K+G*ie*K,ne=G*G*K,ce=ie*se*se,ee=G*se*se+ie*K*se+ie*se*K,te=G*K*se+ie*K*K+G*se*K,oe=G*K*K,ae=se*se*se,de=K*se*se+se*K*se+se*se*K,ge=K*K*se+se*K*K+K*se*K,ye=K*K*K;for(Y=0;Y<Z;Y+=1)B[Y*4]=T.round((le*W[Y]+pe*H[Y]+ue*$[Y]+he*q[Y])*1e3)/1e3,B[Y*4+1]=T.round((ve*W[Y]+be*H[Y]+fe*$[Y]+ne*q[Y])*1e3)/1e3,B[Y*4+2]=T.round((ce*W[Y]+ee*H[Y]+te*$[Y]+oe*q[Y])*1e3)/1e3,B[Y*4+3]=T.round((ae*W[Y]+de*H[Y]+ge*$[Y]+ye*q[Y])*1e3)/1e3;return B}return{getSegmentsLength:A,getNewSegment:z,getPointInSegment:j,buildBezierData:N,pointOnLine2D:n,pointOnLine3D:P}}var bez=bezFunction(),initFrame=initialDefaultFrame,mathAbs=Math.abs;function interpolateValue(T,n){var P=this.offsetTime,R;this.propType==="multidimensional"&&(R=createTypedArray("float32",this.pv.length));for(var A=n.lastIndex,L=A,O=this.keyframes.length-1,N=!0,V,j,B;N;){if(V=this.keyframes[L],j=this.keyframes[L+1],L===O-1&&T>=j.t-P){V.h&&(V=j),A=0;break}if(j.t-P>T){A=L;break}L<O-1?L+=1:(A=0,N=!1)}B=this.keyframesMetadata[L]||{};var z,W,q,H,$,Q,U=j.t-P,J=V.t-P,G;if(V.to){B.bezierData||(B.bezierData=bez.buildBezierData(V.s,j.s||V.e,V.to,V.ti));var K=B.bezierData;if(T>=U||T<J){var Y=T>=U?K.points.length-1:0;for(W=K.points[Y].point.length,z=0;z<W;z+=1)R[z]=K.points[Y].point[z]}else{B.__fnct?Q=B.__fnct:(Q=BezierFactory.getBezierEasing(V.o.x,V.o.y,V.i.x,V.i.y,V.n).get,B.__fnct=Q),q=Q((T-J)/(U-J));var Z=K.segmentLength*q,ie,se=n.lastFrame<T&&n._lastKeyframeIndex===L?n._lastAddedLength:0;for($=n.lastFrame<T&&n._lastKeyframeIndex===L?n._lastPoint:0,N=!0,H=K.points.length;N;){if(se+=K.points[$].partialLength,Z===0||q===0||$===K.points.length-1){for(W=K.points[$].point.length,z=0;z<W;z+=1)R[z]=K.points[$].point[z];break}else if(Z>=se&&Z<se+K.points[$+1].partialLength){for(ie=(Z-se)/K.points[$+1].partialLength,W=K.points[$].point.length,z=0;z<W;z+=1)R[z]=K.points[$].point[z]+(K.points[$+1].point[z]-K.points[$].point[z])*ie;break}$<H-1?$+=1:N=!1}n._lastPoint=$,n._lastAddedLength=se-K.points[$].partialLength,n._lastKeyframeIndex=L}}else{var le,pe,ue,he,ve;if(O=V.s.length,G=j.s||V.e,this.sh&&V.h!==1)if(T>=U)R[0]=G[0],R[1]=G[1],R[2]=G[2];else if(T<=J)R[0]=V.s[0],R[1]=V.s[1],R[2]=V.s[2];else{var be=createQuaternion(V.s),fe=createQuaternion(G),ne=(T-J)/(U-J);quaternionToEuler(R,slerp(be,fe,ne))}else for(L=0;L<O;L+=1)V.h!==1&&(T>=U?q=1:T<J?q=0:(V.o.x.constructor===Array?(B.__fnct||(B.__fnct=[]),B.__fnct[L]?Q=B.__fnct[L]:(le=V.o.x[L]===void 0?V.o.x[0]:V.o.x[L],pe=V.o.y[L]===void 0?V.o.y[0]:V.o.y[L],ue=V.i.x[L]===void 0?V.i.x[0]:V.i.x[L],he=V.i.y[L]===void 0?V.i.y[0]:V.i.y[L],Q=BezierFactory.getBezierEasing(le,pe,ue,he).get,B.__fnct[L]=Q)):B.__fnct?Q=B.__fnct:(le=V.o.x,pe=V.o.y,ue=V.i.x,he=V.i.y,Q=BezierFactory.getBezierEasing(le,pe,ue,he).get,V.keyframeMetadata=Q),q=Q((T-J)/(U-J)))),G=j.s||V.e,ve=V.h===1?V.s[L]:V.s[L]+(G[L]-V.s[L])*q,this.propType==="multidimensional"?R[L]=ve:R=ve}return n.lastIndex=A,R}function slerp(T,n,P){var R=[],A=T[0],L=T[1],O=T[2],N=T[3],V=n[0],j=n[1],B=n[2],z=n[3],W,q,H,$,Q;return q=A*V+L*j+O*B+N*z,q<0&&(q=-q,V=-V,j=-j,B=-B,z=-z),1-q>1e-6?(W=Math.acos(q),H=Math.sin(W),$=Math.sin((1-P)*W)/H,Q=Math.sin(P*W)/H):($=1-P,Q=P),R[0]=$*A+Q*V,R[1]=$*L+Q*j,R[2]=$*O+Q*B,R[3]=$*N+Q*z,R}function quaternionToEuler(T,n){var P=n[0],R=n[1],A=n[2],L=n[3],O=Math.atan2(2*R*L-2*P*A,1-2*R*R-2*A*A),N=Math.asin(2*P*R+2*A*L),V=Math.atan2(2*P*L-2*R*A,1-2*P*P-2*A*A);T[0]=O/degToRads,T[1]=N/degToRads,T[2]=V/degToRads}function createQuaternion(T){var n=T[0]*degToRads,P=T[1]*degToRads,R=T[2]*degToRads,A=Math.cos(n/2),L=Math.cos(P/2),O=Math.cos(R/2),N=Math.sin(n/2),V=Math.sin(P/2),j=Math.sin(R/2),B=A*L*O-N*V*j,z=N*V*O+A*L*j,W=N*L*O+A*V*j,q=A*V*O-N*L*j;return[z,W,q,B]}function getValueAtCurrentTime(){var T=this.comp.renderedFrame-this.offsetTime,n=this.keyframes[0].t-this.offsetTime,P=this.keyframes[this.keyframes.length-1].t-this.offsetTime;if(!(T===this._caching.lastFrame||this._caching.lastFrame!==initFrame&&(this._caching.lastFrame>=P&&T>=P||this._caching.lastFrame<n&&T<n))){this._caching.lastFrame>=T&&(this._caching._lastKeyframeIndex=-1,this._caching.lastIndex=0);var R=this.interpolateValue(T,this._caching);this.pv=R}return this._caching.lastFrame=T,this.pv}function setVValue(T){var n;if(this.propType==="unidimensional")n=T*this.mult,mathAbs(this.v-n)>1e-5&&(this.v=n,this._mdf=!0);else for(var P=0,R=this.v.length;P<R;)n=T[P]*this.mult,mathAbs(this.v[P]-n)>1e-5&&(this.v[P]=n,this._mdf=!0),P+=1}function processEffectsSequence(){if(!(this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)){if(this.lock){this.setVValue(this.pv);return}this.lock=!0,this._mdf=this._isFirstFrame;var T,n=this.effectsSequence.length,P=this.kf?this.pv:this.data.k;for(T=0;T<n;T+=1)P=this.effectsSequence[T](P);this.setVValue(P),this._isFirstFrame=!1,this.lock=!1,this.frameId=this.elem.globalData.frameId}}function addEffect(T){this.effectsSequence.push(T),this.container.addDynamicProperty(this)}function ValueProperty(T,n,P,R){this.propType="unidimensional",this.mult=P||1,this.data=n,this.v=P?n.k*P:n.k,this.pv=n.k,this._mdf=!1,this.elem=T,this.container=R,this.comp=T.comp,this.k=!1,this.kf=!1,this.vel=0,this.effectsSequence=[],this._isFirstFrame=!0,this.getValue=processEffectsSequence,this.setVValue=setVValue,this.addEffect=addEffect}function MultiDimensionalProperty(T,n,P,R){this.propType="multidimensional",this.mult=P||1,this.data=n,this._mdf=!1,this.elem=T,this.container=R,this.comp=T.comp,this.k=!1,this.kf=!1,this.frameId=-1;var A,L=n.k.length;for(this.v=createTypedArray("float32",L),this.pv=createTypedArray("float32",L),this.vel=createTypedArray("float32",L),A=0;A<L;A+=1)this.v[A]=n.k[A]*this.mult,this.pv[A]=n.k[A];this._isFirstFrame=!0,this.effectsSequence=[],this.getValue=processEffectsSequence,this.setVValue=setVValue,this.addEffect=addEffect}function KeyframedValueProperty(T,n,P,R){this.propType="unidimensional",this.keyframes=n.k,this.keyframesMetadata=[],this.offsetTime=T.data.st,this.frameId=-1,this._caching={lastFrame:initFrame,lastIndex:0,value:0,_lastKeyframeIndex:-1},this.k=!0,this.kf=!0,this.data=n,this.mult=P||1,this.elem=T,this.container=R,this.comp=T.comp,this.v=initFrame,this.pv=initFrame,this._isFirstFrame=!0,this.getValue=processEffectsSequence,this.setVValue=setVValue,this.interpolateValue=interpolateValue,this.effectsSequence=[getValueAtCurrentTime.bind(this)],this.addEffect=addEffect}function KeyframedMultidimensionalProperty(T,n,P,R){this.propType="multidimensional";var A,L=n.k.length,O,N,V,j;for(A=0;A<L-1;A+=1)n.k[A].to&&n.k[A].s&&n.k[A+1]&&n.k[A+1].s&&(O=n.k[A].s,N=n.k[A+1].s,V=n.k[A].to,j=n.k[A].ti,(O.length===2&&!(O[0]===N[0]&&O[1]===N[1])&&bez.pointOnLine2D(O[0],O[1],N[0],N[1],O[0]+V[0],O[1]+V[1])&&bez.pointOnLine2D(O[0],O[1],N[0],N[1],N[0]+j[0],N[1]+j[1])||O.length===3&&!(O[0]===N[0]&&O[1]===N[1]&&O[2]===N[2])&&bez.pointOnLine3D(O[0],O[1],O[2],N[0],N[1],N[2],O[0]+V[0],O[1]+V[1],O[2]+V[2])&&bez.pointOnLine3D(O[0],O[1],O[2],N[0],N[1],N[2],N[0]+j[0],N[1]+j[1],N[2]+j[2]))&&(n.k[A].to=null,n.k[A].ti=null),O[0]===N[0]&&O[1]===N[1]&&V[0]===0&&V[1]===0&&j[0]===0&&j[1]===0&&(O.length===2||O[2]===N[2]&&V[2]===0&&j[2]===0)&&(n.k[A].to=null,n.k[A].ti=null));this.effectsSequence=[getValueAtCurrentTime.bind(this)],this.data=n,this.keyframes=n.k,this.keyframesMetadata=[],this.offsetTime=T.data.st,this.k=!0,this.kf=!0,this._isFirstFrame=!0,this.mult=P||1,this.elem=T,this.container=R,this.comp=T.comp,this.getValue=processEffectsSequence,this.setVValue=setVValue,this.interpolateValue=interpolateValue,this.frameId=-1;var B=n.k[0].s.length;for(this.v=createTypedArray("float32",B),this.pv=createTypedArray("float32",B),A=0;A<B;A+=1)this.v[A]=initFrame,this.pv[A]=initFrame;this._caching={lastFrame:initFrame,lastIndex:0,value:createTypedArray("float32",B)},this.addEffect=addEffect}var PropertyFactory=(function(){function T(P,R,A,L,O){R.sid&&(R=P.globalData.slotManager.getProp(R));var N;if(!R.k.length)N=new ValueProperty(P,R,L,O);else if(typeof R.k[0]=="number")N=new MultiDimensionalProperty(P,R,L,O);else switch(A){case 0:N=new KeyframedValueProperty(P,R,L,O);break;case 1:N=new KeyframedMultidimensionalProperty(P,R,L,O);break}return N.effectsSequence.length&&O.addDynamicProperty(N),N}var n={getProp:T};return n})();function DynamicPropertyContainer(){}DynamicPropertyContainer.prototype={addDynamicProperty:function(n){this.dynamicProperties.indexOf(n)===-1&&(this.dynamicProperties.push(n),this.container.addDynamicProperty(this),this._isAnimated=!0)},iterateDynamicProperties:function(){this._mdf=!1;var n,P=this.dynamicProperties.length;for(n=0;n<P;n+=1)this.dynamicProperties[n].getValue(),this.dynamicProperties[n]._mdf&&(this._mdf=!0)},initDynamicPropertyContainer:function(n){this.container=n,this.dynamicProperties=[],this._mdf=!1,this._isAnimated=!1}};var pointPool=(function(){function T(){return createTypedArray("float32",2)}return poolFactory(8,T)})();function ShapePath(){this.c=!1,this._length=0,this._maxLength=8,this.v=createSizedArray(this._maxLength),this.o=createSizedArray(this._maxLength),this.i=createSizedArray(this._maxLength)}ShapePath.prototype.setPathData=function(T,n){this.c=T,this.setLength(n);for(var P=0;P<n;)this.v[P]=pointPool.newElement(),this.o[P]=pointPool.newElement(),this.i[P]=pointPool.newElement(),P+=1},ShapePath.prototype.setLength=function(T){for(;this._maxLength<T;)this.doubleArrayLength();this._length=T},ShapePath.prototype.doubleArrayLength=function(){this.v=this.v.concat(createSizedArray(this._maxLength)),this.i=this.i.concat(createSizedArray(this._maxLength)),this.o=this.o.concat(createSizedArray(this._maxLength)),this._maxLength*=2},ShapePath.prototype.setXYAt=function(T,n,P,R,A){var L;switch(this._length=Math.max(this._length,R+1),this._length>=this._maxLength&&this.doubleArrayLength(),P){case"v":L=this.v;break;case"i":L=this.i;break;case"o":L=this.o;break;default:L=[];break}(!L[R]||L[R]&&!A)&&(L[R]=pointPool.newElement()),L[R][0]=T,L[R][1]=n},ShapePath.prototype.setTripleAt=function(T,n,P,R,A,L,O,N){this.setXYAt(T,n,"v",O,N),this.setXYAt(P,R,"o",O,N),this.setXYAt(A,L,"i",O,N)},ShapePath.prototype.reverse=function(){var T=new ShapePath;T.setPathData(this.c,this._length);var n=this.v,P=this.o,R=this.i,A=0;this.c&&(T.setTripleAt(n[0][0],n[0][1],R[0][0],R[0][1],P[0][0],P[0][1],0,!1),A=1);var L=this._length-1,O=this._length,N;for(N=A;N<O;N+=1)T.setTripleAt(n[L][0],n[L][1],R[L][0],R[L][1],P[L][0],P[L][1],N,!1),L-=1;return T},ShapePath.prototype.length=function(){return this._length};var shapePool=(function(){function T(){return new ShapePath}function n(A){var L=A._length,O;for(O=0;O<L;O+=1)pointPool.release(A.v[O]),pointPool.release(A.i[O]),pointPool.release(A.o[O]),A.v[O]=null,A.i[O]=null,A.o[O]=null;A._length=0,A.c=!1}function P(A){var L=R.newElement(),O,N=A._length===void 0?A.v.length:A._length;for(L.setLength(N),L.c=A.c,O=0;O<N;O+=1)L.setTripleAt(A.v[O][0],A.v[O][1],A.o[O][0],A.o[O][1],A.i[O][0],A.i[O][1],O);return L}var R=poolFactory(4,T,n);return R.clone=P,R})();function ShapeCollection(){this._length=0,this._maxLength=4,this.shapes=createSizedArray(this._maxLength)}ShapeCollection.prototype.addShape=function(T){this._length===this._maxLength&&(this.shapes=this.shapes.concat(createSizedArray(this._maxLength)),this._maxLength*=2),this.shapes[this._length]=T,this._length+=1},ShapeCollection.prototype.releaseShapes=function(){var T;for(T=0;T<this._length;T+=1)shapePool.release(this.shapes[T]);this._length=0};var shapeCollectionPool=(function(){var T={newShapeCollection:A,release:L},n=0,P=4,R=createSizedArray(P);function A(){var O;return n?(n-=1,O=R[n]):O=new ShapeCollection,O}function L(O){var N,V=O._length;for(N=0;N<V;N+=1)shapePool.release(O.shapes[N]);O._length=0,n===P&&(R=pooling.double(R),P*=2),R[n]=O,n+=1}return T})(),ShapePropertyFactory=(function(){var T=-999999;function n(U,J,G){var K=G.lastIndex,Y,Z,ie,se,le,pe,ue,he,ve,be=this.keyframes;if(U<be[0].t-this.offsetTime)Y=be[0].s[0],ie=!0,K=0;else if(U>=be[be.length-1].t-this.offsetTime)Y=be[be.length-1].s?be[be.length-1].s[0]:be[be.length-2].e[0],ie=!0;else{for(var fe=K,ne=be.length-1,ce=!0,ee,te,oe;ce&&(ee=be[fe],te=be[fe+1],!(te.t-this.offsetTime>U));)fe<ne-1?fe+=1:ce=!1;if(oe=this.keyframesMetadata[fe]||{},ie=ee.h===1,K=fe,!ie){if(U>=te.t-this.offsetTime)he=1;else if(U<ee.t-this.offsetTime)he=0;else{var ae;oe.__fnct?ae=oe.__fnct:(ae=BezierFactory.getBezierEasing(ee.o.x,ee.o.y,ee.i.x,ee.i.y).get,oe.__fnct=ae),he=ae((U-(ee.t-this.offsetTime))/(te.t-this.offsetTime-(ee.t-this.offsetTime)))}Z=te.s?te.s[0]:ee.e[0]}Y=ee.s[0]}for(pe=J._length,ue=Y.i[0].length,G.lastIndex=K,se=0;se<pe;se+=1)for(le=0;le<ue;le+=1)ve=ie?Y.i[se][le]:Y.i[se][le]+(Z.i[se][le]-Y.i[se][le])*he,J.i[se][le]=ve,ve=ie?Y.o[se][le]:Y.o[se][le]+(Z.o[se][le]-Y.o[se][le])*he,J.o[se][le]=ve,ve=ie?Y.v[se][le]:Y.v[se][le]+(Z.v[se][le]-Y.v[se][le])*he,J.v[se][le]=ve}function P(){var U=this.comp.renderedFrame-this.offsetTime,J=this.keyframes[0].t-this.offsetTime,G=this.keyframes[this.keyframes.length-1].t-this.offsetTime,K=this._caching.lastFrame;return K!==T&&(K<J&&U<J||K>G&&U>G)||(this._caching.lastIndex=K<U?this._caching.lastIndex:0,this.interpolateShape(U,this.pv,this._caching)),this._caching.lastFrame=U,this.pv}function R(){this.paths=this.localShapeCollection}function A(U,J){if(U._length!==J._length||U.c!==J.c)return!1;var G,K=U._length;for(G=0;G<K;G+=1)if(U.v[G][0]!==J.v[G][0]||U.v[G][1]!==J.v[G][1]||U.o[G][0]!==J.o[G][0]||U.o[G][1]!==J.o[G][1]||U.i[G][0]!==J.i[G][0]||U.i[G][1]!==J.i[G][1])return!1;return!0}function L(U){A(this.v,U)||(this.v=shapePool.clone(U),this.localShapeCollection.releaseShapes(),this.localShapeCollection.addShape(this.v),this._mdf=!0,this.paths=this.localShapeCollection)}function O(){if(this.elem.globalData.frameId!==this.frameId){if(!this.effectsSequence.length){this._mdf=!1;return}if(this.lock){this.setVValue(this.pv);return}this.lock=!0,this._mdf=!1;var U;this.kf?U=this.pv:this.data.ks?U=this.data.ks.k:U=this.data.pt.k;var J,G=this.effectsSequence.length;for(J=0;J<G;J+=1)U=this.effectsSequence[J](U);this.setVValue(U),this.lock=!1,this.frameId=this.elem.globalData.frameId}}function N(U,J,G){this.propType="shape",this.comp=U.comp,this.container=U,this.elem=U,this.data=J,this.k=!1,this.kf=!1,this._mdf=!1;var K=G===3?J.pt.k:J.ks.k;this.v=shapePool.clone(K),this.pv=shapePool.clone(this.v),this.localShapeCollection=shapeCollectionPool.newShapeCollection(),this.paths=this.localShapeCollection,this.paths.addShape(this.v),this.reset=R,this.effectsSequence=[]}function V(U){this.effectsSequence.push(U),this.container.addDynamicProperty(this)}N.prototype.interpolateShape=n,N.prototype.getValue=O,N.prototype.setVValue=L,N.prototype.addEffect=V;function j(U,J,G){this.propType="shape",this.comp=U.comp,this.elem=U,this.container=U,this.offsetTime=U.data.st,this.keyframes=G===3?J.pt.k:J.ks.k,this.keyframesMetadata=[],this.k=!0,this.kf=!0;var K=this.keyframes[0].s[0].i.length;this.v=shapePool.newElement(),this.v.setPathData(this.keyframes[0].s[0].c,K),this.pv=shapePool.clone(this.v),this.localShapeCollection=shapeCollectionPool.newShapeCollection(),this.paths=this.localShapeCollection,this.paths.addShape(this.v),this.lastFrame=T,this.reset=R,this._caching={lastFrame:T,lastIndex:0},this.effectsSequence=[P.bind(this)]}j.prototype.getValue=O,j.prototype.interpolateShape=n,j.prototype.setVValue=L,j.prototype.addEffect=V;var B=(function(){var U=roundCorner;function J(G,K){this.v=shapePool.newElement(),this.v.setPathData(!0,4),this.localShapeCollection=shapeCollectionPool.newShapeCollection(),this.paths=this.localShapeCollection,this.localShapeCollection.addShape(this.v),this.d=K.d,this.elem=G,this.comp=G.comp,this.frameId=-1,this.initDynamicPropertyContainer(G),this.p=PropertyFactory.getProp(G,K.p,1,0,this),this.s=PropertyFactory.getProp(G,K.s,1,0,this),this.dynamicProperties.length?this.k=!0:(this.k=!1,this.convertEllToPath())}return J.prototype={reset:R,getValue:function(){this.elem.globalData.frameId!==this.frameId&&(this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties(),this._mdf&&this.convertEllToPath())},convertEllToPath:function(){var K=this.p.v[0],Y=this.p.v[1],Z=this.s.v[0]/2,ie=this.s.v[1]/2,se=this.d!==3,le=this.v;le.v[0][0]=K,le.v[0][1]=Y-ie,le.v[1][0]=se?K+Z:K-Z,le.v[1][1]=Y,le.v[2][0]=K,le.v[2][1]=Y+ie,le.v[3][0]=se?K-Z:K+Z,le.v[3][1]=Y,le.i[0][0]=se?K-Z*U:K+Z*U,le.i[0][1]=Y-ie,le.i[1][0]=se?K+Z:K-Z,le.i[1][1]=Y-ie*U,le.i[2][0]=se?K+Z*U:K-Z*U,le.i[2][1]=Y+ie,le.i[3][0]=se?K-Z:K+Z,le.i[3][1]=Y+ie*U,le.o[0][0]=se?K+Z*U:K-Z*U,le.o[0][1]=Y-ie,le.o[1][0]=se?K+Z:K-Z,le.o[1][1]=Y+ie*U,le.o[2][0]=se?K-Z*U:K+Z*U,le.o[2][1]=Y+ie,le.o[3][0]=se?K-Z:K+Z,le.o[3][1]=Y-ie*U}},extendPrototype([DynamicPropertyContainer],J),J})(),z=(function(){function U(J,G){this.v=shapePool.newElement(),this.v.setPathData(!0,0),this.elem=J,this.comp=J.comp,this.data=G,this.frameId=-1,this.d=G.d,this.initDynamicPropertyContainer(J),G.sy===1?(this.ir=PropertyFactory.getProp(J,G.ir,0,0,this),this.is=PropertyFactory.getProp(J,G.is,0,.01,this),this.convertToPath=this.convertStarToPath):this.convertToPath=this.convertPolygonToPath,this.pt=PropertyFactory.getProp(J,G.pt,0,0,this),this.p=PropertyFactory.getProp(J,G.p,1,0,this),this.r=PropertyFactory.getProp(J,G.r,0,degToRads,this),this.or=PropertyFactory.getProp(J,G.or,0,0,this),this.os=PropertyFactory.getProp(J,G.os,0,.01,this),this.localShapeCollection=shapeCollectionPool.newShapeCollection(),this.localShapeCollection.addShape(this.v),this.paths=this.localShapeCollection,this.dynamicProperties.length?this.k=!0:(this.k=!1,this.convertToPath())}return U.prototype={reset:R,getValue:function(){this.elem.globalData.frameId!==this.frameId&&(this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties(),this._mdf&&this.convertToPath())},convertStarToPath:function(){var G=Math.floor(this.pt.v)*2,K=Math.PI*2/G,Y=!0,Z=this.or.v,ie=this.ir.v,se=this.os.v,le=this.is.v,pe=2*Math.PI*Z/(G*2),ue=2*Math.PI*ie/(G*2),he,ve,be,fe,ne=-Math.PI/2;ne+=this.r.v;var ce=this.data.d===3?-1:1;for(this.v._length=0,he=0;he<G;he+=1){ve=Y?Z:ie,be=Y?se:le,fe=Y?pe:ue;var ee=ve*Math.cos(ne),te=ve*Math.sin(ne),oe=ee===0&&te===0?0:te/Math.sqrt(ee*ee+te*te),ae=ee===0&&te===0?0:-ee/Math.sqrt(ee*ee+te*te);ee+=+this.p.v[0],te+=+this.p.v[1],this.v.setTripleAt(ee,te,ee-oe*fe*be*ce,te-ae*fe*be*ce,ee+oe*fe*be*ce,te+ae*fe*be*ce,he,!0),Y=!Y,ne+=K*ce}},convertPolygonToPath:function(){var G=Math.floor(this.pt.v),K=Math.PI*2/G,Y=this.or.v,Z=this.os.v,ie=2*Math.PI*Y/(G*4),se,le=-Math.PI*.5,pe=this.data.d===3?-1:1;for(le+=this.r.v,this.v._length=0,se=0;se<G;se+=1){var ue=Y*Math.cos(le),he=Y*Math.sin(le),ve=ue===0&&he===0?0:he/Math.sqrt(ue*ue+he*he),be=ue===0&&he===0?0:-ue/Math.sqrt(ue*ue+he*he);ue+=+this.p.v[0],he+=+this.p.v[1],this.v.setTripleAt(ue,he,ue-ve*ie*Z*pe,he-be*ie*Z*pe,ue+ve*ie*Z*pe,he+be*ie*Z*pe,se,!0),le+=K*pe}this.paths.length=0,this.paths[0]=this.v}},extendPrototype([DynamicPropertyContainer],U),U})(),W=(function(){function U(J,G){this.v=shapePool.newElement(),this.v.c=!0,this.localShapeCollection=shapeCollectionPool.newShapeCollection(),this.localShapeCollection.addShape(this.v),this.paths=this.localShapeCollection,this.elem=J,this.comp=J.comp,this.frameId=-1,this.d=G.d,this.initDynamicPropertyContainer(J),this.p=PropertyFactory.getProp(J,G.p,1,0,this),this.s=PropertyFactory.getProp(J,G.s,1,0,this),this.r=PropertyFactory.getProp(J,G.r,0,0,this),this.dynamicProperties.length?this.k=!0:(this.k=!1,this.convertRectToPath())}return U.prototype={convertRectToPath:function(){var G=this.p.v[0],K=this.p.v[1],Y=this.s.v[0]/2,Z=this.s.v[1]/2,ie=bmMin(Y,Z,this.r.v),se=ie*(1-roundCorner);this.v._length=0,this.d===2||this.d===1?(this.v.setTripleAt(G+Y,K-Z+ie,G+Y,K-Z+ie,G+Y,K-Z+se,0,!0),this.v.setTripleAt(G+Y,K+Z-ie,G+Y,K+Z-se,G+Y,K+Z-ie,1,!0),ie!==0?(this.v.setTripleAt(G+Y-ie,K+Z,G+Y-ie,K+Z,G+Y-se,K+Z,2,!0),this.v.setTripleAt(G-Y+ie,K+Z,G-Y+se,K+Z,G-Y+ie,K+Z,3,!0),this.v.setTripleAt(G-Y,K+Z-ie,G-Y,K+Z-ie,G-Y,K+Z-se,4,!0),this.v.setTripleAt(G-Y,K-Z+ie,G-Y,K-Z+se,G-Y,K-Z+ie,5,!0),this.v.setTripleAt(G-Y+ie,K-Z,G-Y+ie,K-Z,G-Y+se,K-Z,6,!0),this.v.setTripleAt(G+Y-ie,K-Z,G+Y-se,K-Z,G+Y-ie,K-Z,7,!0)):(this.v.setTripleAt(G-Y,K+Z,G-Y+se,K+Z,G-Y,K+Z,2),this.v.setTripleAt(G-Y,K-Z,G-Y,K-Z+se,G-Y,K-Z,3))):(this.v.setTripleAt(G+Y,K-Z+ie,G+Y,K-Z+se,G+Y,K-Z+ie,0,!0),ie!==0?(this.v.setTripleAt(G+Y-ie,K-Z,G+Y-ie,K-Z,G+Y-se,K-Z,1,!0),this.v.setTripleAt(G-Y+ie,K-Z,G-Y+se,K-Z,G-Y+ie,K-Z,2,!0),this.v.setTripleAt(G-Y,K-Z+ie,G-Y,K-Z+ie,G-Y,K-Z+se,3,!0),this.v.setTripleAt(G-Y,K+Z-ie,G-Y,K+Z-se,G-Y,K+Z-ie,4,!0),this.v.setTripleAt(G-Y+ie,K+Z,G-Y+ie,K+Z,G-Y+se,K+Z,5,!0),this.v.setTripleAt(G+Y-ie,K+Z,G+Y-se,K+Z,G+Y-ie,K+Z,6,!0),this.v.setTripleAt(G+Y,K+Z-ie,G+Y,K+Z-ie,G+Y,K+Z-se,7,!0)):(this.v.setTripleAt(G-Y,K-Z,G-Y+se,K-Z,G-Y,K-Z,1,!0),this.v.setTripleAt(G-Y,K+Z,G-Y,K+Z-se,G-Y,K+Z,2,!0),this.v.setTripleAt(G+Y,K+Z,G+Y-se,K+Z,G+Y,K+Z,3,!0)))},getValue:function(){this.elem.globalData.frameId!==this.frameId&&(this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties(),this._mdf&&this.convertRectToPath())},reset:R},extendPrototype([DynamicPropertyContainer],U),U})();function q(U,J,G){var K;if(G===3||G===4){var Y=G===3?J.pt:J.ks,Z=Y.k;Z.length?K=new j(U,J,G):K=new N(U,J,G)}else G===5?K=new W(U,J):G===6?K=new B(U,J):G===7&&(K=new z(U,J));return K.k&&U.addDynamicProperty(K),K}function H(){return N}function $(){return j}var Q={};return Q.getShapeProp=q,Q.getConstructorFunction=H,Q.getKeyframedConstructorFunction=$,Q})();/*!
|
|
484
|
+
Transformation Matrix v2.0
|
|
485
|
+
(c) Epistemex 2014-2015
|
|
486
|
+
www.epistemex.com
|
|
487
|
+
By Ken Fyrstenberg
|
|
488
|
+
Contributions by leeoniya.
|
|
489
|
+
License: MIT, header required.
|
|
490
|
+
*/var Matrix=(function(){var T=Math.cos,n=Math.sin,P=Math.tan,R=Math.round;function A(){return this.props[0]=1,this.props[1]=0,this.props[2]=0,this.props[3]=0,this.props[4]=0,this.props[5]=1,this.props[6]=0,this.props[7]=0,this.props[8]=0,this.props[9]=0,this.props[10]=1,this.props[11]=0,this.props[12]=0,this.props[13]=0,this.props[14]=0,this.props[15]=1,this}function L(ee){if(ee===0)return this;var te=T(ee),oe=n(ee);return this._t(te,-oe,0,0,oe,te,0,0,0,0,1,0,0,0,0,1)}function O(ee){if(ee===0)return this;var te=T(ee),oe=n(ee);return this._t(1,0,0,0,0,te,-oe,0,0,oe,te,0,0,0,0,1)}function N(ee){if(ee===0)return this;var te=T(ee),oe=n(ee);return this._t(te,0,oe,0,0,1,0,0,-oe,0,te,0,0,0,0,1)}function V(ee){if(ee===0)return this;var te=T(ee),oe=n(ee);return this._t(te,-oe,0,0,oe,te,0,0,0,0,1,0,0,0,0,1)}function j(ee,te){return this._t(1,te,ee,1,0,0)}function B(ee,te){return this.shear(P(ee),P(te))}function z(ee,te){var oe=T(te),ae=n(te);return this._t(oe,ae,0,0,-ae,oe,0,0,0,0,1,0,0,0,0,1)._t(1,0,0,0,P(ee),1,0,0,0,0,1,0,0,0,0,1)._t(oe,-ae,0,0,ae,oe,0,0,0,0,1,0,0,0,0,1)}function W(ee,te,oe){return!oe&&oe!==0&&(oe=1),ee===1&&te===1&&oe===1?this:this._t(ee,0,0,0,0,te,0,0,0,0,oe,0,0,0,0,1)}function q(ee,te,oe,ae,de,ge,ye,Ee,Pe,Ie,Ae,Le,Me,ke,Ce,xe){return this.props[0]=ee,this.props[1]=te,this.props[2]=oe,this.props[3]=ae,this.props[4]=de,this.props[5]=ge,this.props[6]=ye,this.props[7]=Ee,this.props[8]=Pe,this.props[9]=Ie,this.props[10]=Ae,this.props[11]=Le,this.props[12]=Me,this.props[13]=ke,this.props[14]=Ce,this.props[15]=xe,this}function H(ee,te,oe){return oe=oe||0,ee!==0||te!==0||oe!==0?this._t(1,0,0,0,0,1,0,0,0,0,1,0,ee,te,oe,1):this}function $(ee,te,oe,ae,de,ge,ye,Ee,Pe,Ie,Ae,Le,Me,ke,Ce,xe){var we=this.props;if(ee===1&&te===0&&oe===0&&ae===0&&de===0&&ge===1&&ye===0&&Ee===0&&Pe===0&&Ie===0&&Ae===1&&Le===0)return we[12]=we[12]*ee+we[15]*Me,we[13]=we[13]*ge+we[15]*ke,we[14]=we[14]*Ae+we[15]*Ce,we[15]*=xe,this._identityCalculated=!1,this;var Oe=we[0],De=we[1],We=we[2],Fe=we[3],qe=we[4],Ne=we[5],je=we[6],Ye=we[7],Xe=we[8],ze=we[9],Qe=we[10],Ge=we[11],et=we[12],nt=we[13],Ze=we[14],tt=we[15];return we[0]=Oe*ee+De*de+We*Pe+Fe*Me,we[1]=Oe*te+De*ge+We*Ie+Fe*ke,we[2]=Oe*oe+De*ye+We*Ae+Fe*Ce,we[3]=Oe*ae+De*Ee+We*Le+Fe*xe,we[4]=qe*ee+Ne*de+je*Pe+Ye*Me,we[5]=qe*te+Ne*ge+je*Ie+Ye*ke,we[6]=qe*oe+Ne*ye+je*Ae+Ye*Ce,we[7]=qe*ae+Ne*Ee+je*Le+Ye*xe,we[8]=Xe*ee+ze*de+Qe*Pe+Ge*Me,we[9]=Xe*te+ze*ge+Qe*Ie+Ge*ke,we[10]=Xe*oe+ze*ye+Qe*Ae+Ge*Ce,we[11]=Xe*ae+ze*Ee+Qe*Le+Ge*xe,we[12]=et*ee+nt*de+Ze*Pe+tt*Me,we[13]=et*te+nt*ge+Ze*Ie+tt*ke,we[14]=et*oe+nt*ye+Ze*Ae+tt*Ce,we[15]=et*ae+nt*Ee+Ze*Le+tt*xe,this._identityCalculated=!1,this}function Q(ee){var te=ee.props;return this.transform(te[0],te[1],te[2],te[3],te[4],te[5],te[6],te[7],te[8],te[9],te[10],te[11],te[12],te[13],te[14],te[15])}function U(){return this._identityCalculated||(this._identity=!(this.props[0]!==1||this.props[1]!==0||this.props[2]!==0||this.props[3]!==0||this.props[4]!==0||this.props[5]!==1||this.props[6]!==0||this.props[7]!==0||this.props[8]!==0||this.props[9]!==0||this.props[10]!==1||this.props[11]!==0||this.props[12]!==0||this.props[13]!==0||this.props[14]!==0||this.props[15]!==1),this._identityCalculated=!0),this._identity}function J(ee){for(var te=0;te<16;){if(ee.props[te]!==this.props[te])return!1;te+=1}return!0}function G(ee){var te;for(te=0;te<16;te+=1)ee.props[te]=this.props[te];return ee}function K(ee){var te;for(te=0;te<16;te+=1)this.props[te]=ee[te]}function Y(ee,te,oe){return{x:ee*this.props[0]+te*this.props[4]+oe*this.props[8]+this.props[12],y:ee*this.props[1]+te*this.props[5]+oe*this.props[9]+this.props[13],z:ee*this.props[2]+te*this.props[6]+oe*this.props[10]+this.props[14]}}function Z(ee,te,oe){return ee*this.props[0]+te*this.props[4]+oe*this.props[8]+this.props[12]}function ie(ee,te,oe){return ee*this.props[1]+te*this.props[5]+oe*this.props[9]+this.props[13]}function se(ee,te,oe){return ee*this.props[2]+te*this.props[6]+oe*this.props[10]+this.props[14]}function le(){var ee=this.props[0]*this.props[5]-this.props[1]*this.props[4],te=this.props[5]/ee,oe=-this.props[1]/ee,ae=-this.props[4]/ee,de=this.props[0]/ee,ge=(this.props[4]*this.props[13]-this.props[5]*this.props[12])/ee,ye=-(this.props[0]*this.props[13]-this.props[1]*this.props[12])/ee,Ee=new Matrix;return Ee.props[0]=te,Ee.props[1]=oe,Ee.props[4]=ae,Ee.props[5]=de,Ee.props[12]=ge,Ee.props[13]=ye,Ee}function pe(ee){var te=this.getInverseMatrix();return te.applyToPointArray(ee[0],ee[1],ee[2]||0)}function ue(ee){var te,oe=ee.length,ae=[];for(te=0;te<oe;te+=1)ae[te]=pe(ee[te]);return ae}function he(ee,te,oe){var ae=createTypedArray("float32",6);if(this.isIdentity())ae[0]=ee[0],ae[1]=ee[1],ae[2]=te[0],ae[3]=te[1],ae[4]=oe[0],ae[5]=oe[1];else{var de=this.props[0],ge=this.props[1],ye=this.props[4],Ee=this.props[5],Pe=this.props[12],Ie=this.props[13];ae[0]=ee[0]*de+ee[1]*ye+Pe,ae[1]=ee[0]*ge+ee[1]*Ee+Ie,ae[2]=te[0]*de+te[1]*ye+Pe,ae[3]=te[0]*ge+te[1]*Ee+Ie,ae[4]=oe[0]*de+oe[1]*ye+Pe,ae[5]=oe[0]*ge+oe[1]*Ee+Ie}return ae}function ve(ee,te,oe){var ae;return this.isIdentity()?ae=[ee,te,oe]:ae=[ee*this.props[0]+te*this.props[4]+oe*this.props[8]+this.props[12],ee*this.props[1]+te*this.props[5]+oe*this.props[9]+this.props[13],ee*this.props[2]+te*this.props[6]+oe*this.props[10]+this.props[14]],ae}function be(ee,te){if(this.isIdentity())return ee+","+te;var oe=this.props;return Math.round((ee*oe[0]+te*oe[4]+oe[12])*100)/100+","+Math.round((ee*oe[1]+te*oe[5]+oe[13])*100)/100}function fe(){for(var ee=0,te=this.props,oe="matrix3d(",ae=1e4;ee<16;)oe+=R(te[ee]*ae)/ae,oe+=ee===15?")":",",ee+=1;return oe}function ne(ee){var te=1e4;return ee<1e-6&&ee>0||ee>-1e-6&&ee<0?R(ee*te)/te:ee}function ce(){var ee=this.props,te=ne(ee[0]),oe=ne(ee[1]),ae=ne(ee[4]),de=ne(ee[5]),ge=ne(ee[12]),ye=ne(ee[13]);return"matrix("+te+","+oe+","+ae+","+de+","+ge+","+ye+")"}return function(){this.reset=A,this.rotate=L,this.rotateX=O,this.rotateY=N,this.rotateZ=V,this.skew=B,this.skewFromAxis=z,this.shear=j,this.scale=W,this.setTransform=q,this.translate=H,this.transform=$,this.multiply=Q,this.applyToPoint=Y,this.applyToX=Z,this.applyToY=ie,this.applyToZ=se,this.applyToPointArray=ve,this.applyToTriplePoints=he,this.applyToPointStringified=be,this.toCSS=fe,this.to2dCSS=ce,this.clone=G,this.cloneFromProps=K,this.equals=J,this.inversePoints=ue,this.inversePoint=pe,this.getInverseMatrix=le,this._t=this.transform,this.isIdentity=U,this._identity=!0,this._identityCalculated=!1,this.props=createTypedArray("float32",16),this.reset()}})();function _typeof$3(T){"@babel/helpers - typeof";return _typeof$3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof$3(T)}var lottie={};function setLocation(T){setLocationHref(T)}function searchAnimations(){animationManager.searchAnimations()}function setSubframeRendering(T){setSubframeEnabled(T)}function setPrefix(T){setIdPrefix(T)}function loadAnimation(T){return animationManager.loadAnimation(T)}function setQuality(T){if(typeof T=="string")switch(T){case"high":setDefaultCurveSegments(200);break;default:case"medium":setDefaultCurveSegments(50);break;case"low":setDefaultCurveSegments(10);break}else!isNaN(T)&&T>1&&setDefaultCurveSegments(T)}function inBrowser(){return typeof navigator<"u"}function installPlugin(T,n){T==="expressions"&&setExpressionsPlugin(n)}function getFactory(T){switch(T){case"propertyFactory":return PropertyFactory;case"shapePropertyFactory":return ShapePropertyFactory;case"matrix":return Matrix;default:return null}}lottie.play=animationManager.play,lottie.pause=animationManager.pause,lottie.setLocationHref=setLocation,lottie.togglePause=animationManager.togglePause,lottie.setSpeed=animationManager.setSpeed,lottie.setDirection=animationManager.setDirection,lottie.stop=animationManager.stop,lottie.searchAnimations=searchAnimations,lottie.registerAnimation=animationManager.registerAnimation,lottie.loadAnimation=loadAnimation,lottie.setSubframeRendering=setSubframeRendering,lottie.resize=animationManager.resize,lottie.goToAndStop=animationManager.goToAndStop,lottie.destroy=animationManager.destroy,lottie.setQuality=setQuality,lottie.inBrowser=inBrowser,lottie.installPlugin=installPlugin,lottie.freeze=animationManager.freeze,lottie.unfreeze=animationManager.unfreeze,lottie.setVolume=animationManager.setVolume,lottie.mute=animationManager.mute,lottie.unmute=animationManager.unmute,lottie.getRegisteredAnimations=animationManager.getRegisteredAnimations,lottie.useWebWorker=setWebWorker,lottie.setIDPrefix=setPrefix,lottie.__getFactory=getFactory,lottie.version="5.13.0";function checkReady(){document.readyState==="complete"&&(clearInterval(readyStateCheckInterval),searchAnimations())}function getQueryVariable(T){for(var n=queryString.split("&"),P=0;P<n.length;P+=1){var R=n[P].split("=");if(decodeURIComponent(R[0])==T)return decodeURIComponent(R[1])}return null}var queryString="";{var scripts=document.getElementsByTagName("script"),index=scripts.length-1,myScript=scripts[index]||{src:""};queryString=myScript.src?myScript.src.replace(/^[^\?]+\??/,""):"",getQueryVariable("renderer")}var readyStateCheckInterval=setInterval(checkReady,100);try{_typeof$3(exports)!=="object"&&(window.bodymovin=lottie)}catch(T){}var ShapeModifiers=(function(){var T={},n={};T.registerModifier=P,T.getModifier=R;function P(A,L){n[A]||(n[A]=L)}function R(A,L,O){return new n[A](L,O)}return T})();function ShapeModifier(){}ShapeModifier.prototype.initModifierProperties=function(){},ShapeModifier.prototype.addShapeToModifier=function(){},ShapeModifier.prototype.addShape=function(T){if(!this.closed){T.sh.container.addDynamicProperty(T.sh);var n={shape:T.sh,data:T,localShapeCollection:shapeCollectionPool.newShapeCollection()};this.shapes.push(n),this.addShapeToModifier(n),this._isAnimated&&T.setAsAnimated()}},ShapeModifier.prototype.init=function(T,n){this.shapes=[],this.elem=T,this.initDynamicPropertyContainer(T),this.initModifierProperties(T,n),this.frameId=initialDefaultFrame,this.closed=!1,this.k=!1,this.dynamicProperties.length?this.k=!0:this.getValue(!0)},ShapeModifier.prototype.processKeys=function(){this.elem.globalData.frameId!==this.frameId&&(this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties())},extendPrototype([DynamicPropertyContainer],ShapeModifier);function TrimModifier(){}extendPrototype([ShapeModifier],TrimModifier),TrimModifier.prototype.initModifierProperties=function(T,n){this.s=PropertyFactory.getProp(T,n.s,0,.01,this),this.e=PropertyFactory.getProp(T,n.e,0,.01,this),this.o=PropertyFactory.getProp(T,n.o,0,0,this),this.sValue=0,this.eValue=0,this.getValue=this.processKeys,this.m=n.m,this._isAnimated=!!this.s.effectsSequence.length||!!this.e.effectsSequence.length||!!this.o.effectsSequence.length},TrimModifier.prototype.addShapeToModifier=function(T){T.pathsData=[]},TrimModifier.prototype.calculateShapeEdges=function(T,n,P,R,A){var L=[];n<=1?L.push({s:T,e:n}):T>=1?L.push({s:T-1,e:n-1}):(L.push({s:T,e:1}),L.push({s:0,e:n-1}));var O=[],N,V=L.length,j;for(N=0;N<V;N+=1)if(j=L[N],!(j.e*A<R||j.s*A>R+P)){var B,z;j.s*A<=R?B=0:B=(j.s*A-R)/P,j.e*A>=R+P?z=1:z=(j.e*A-R)/P,O.push([B,z])}return O.length||O.push([0,0]),O},TrimModifier.prototype.releasePathsData=function(T){var n,P=T.length;for(n=0;n<P;n+=1)segmentsLengthPool.release(T[n]);return T.length=0,T},TrimModifier.prototype.processShapes=function(T){var n,P;if(this._mdf||T){var R=this.o.v%360/360;if(R<0&&(R+=1),this.s.v>1?n=1+R:this.s.v<0?n=0+R:n=this.s.v+R,this.e.v>1?P=1+R:this.e.v<0?P=0+R:P=this.e.v+R,n>P){var A=n;n=P,P=A}n=Math.round(n*1e4)*1e-4,P=Math.round(P*1e4)*1e-4,this.sValue=n,this.eValue=P}else n=this.sValue,P=this.eValue;var L,O,N=this.shapes.length,V,j,B,z,W,q=0;if(P===n)for(O=0;O<N;O+=1)this.shapes[O].localShapeCollection.releaseShapes(),this.shapes[O].shape._mdf=!0,this.shapes[O].shape.paths=this.shapes[O].localShapeCollection,this._mdf&&(this.shapes[O].pathsData.length=0);else if(P===1&&n===0||P===0&&n===1){if(this._mdf)for(O=0;O<N;O+=1)this.shapes[O].pathsData.length=0,this.shapes[O].shape._mdf=!0}else{var H=[],$,Q;for(O=0;O<N;O+=1)if($=this.shapes[O],!$.shape._mdf&&!this._mdf&&!T&&this.m!==2)$.shape.paths=$.localShapeCollection;else{if(L=$.shape.paths,j=L._length,W=0,!$.shape._mdf&&$.pathsData.length)W=$.totalShapeLength;else{for(B=this.releasePathsData($.pathsData),V=0;V<j;V+=1)z=bez.getSegmentsLength(L.shapes[V]),B.push(z),W+=z.totalLength;$.totalShapeLength=W,$.pathsData=B}q+=W,$.shape._mdf=!0}var U=n,J=P,G=0,K;for(O=N-1;O>=0;O-=1)if($=this.shapes[O],$.shape._mdf){for(Q=$.localShapeCollection,Q.releaseShapes(),this.m===2&&N>1?(K=this.calculateShapeEdges(n,P,$.totalShapeLength,G,q),G+=$.totalShapeLength):K=[[U,J]],j=K.length,V=0;V<j;V+=1){U=K[V][0],J=K[V][1],H.length=0,J<=1?H.push({s:$.totalShapeLength*U,e:$.totalShapeLength*J}):U>=1?H.push({s:$.totalShapeLength*(U-1),e:$.totalShapeLength*(J-1)}):(H.push({s:$.totalShapeLength*U,e:$.totalShapeLength}),H.push({s:0,e:$.totalShapeLength*(J-1)}));var Y=this.addShapes($,H[0]);if(H[0].s!==H[0].e){if(H.length>1){var Z=$.shape.paths.shapes[$.shape.paths._length-1];if(Z.c){var ie=Y.pop();this.addPaths(Y,Q),Y=this.addShapes($,H[1],ie)}else this.addPaths(Y,Q),Y=this.addShapes($,H[1])}this.addPaths(Y,Q)}}$.shape.paths=Q}}},TrimModifier.prototype.addPaths=function(T,n){var P,R=T.length;for(P=0;P<R;P+=1)n.addShape(T[P])},TrimModifier.prototype.addSegment=function(T,n,P,R,A,L,O){A.setXYAt(n[0],n[1],"o",L),A.setXYAt(P[0],P[1],"i",L+1),O&&A.setXYAt(T[0],T[1],"v",L),A.setXYAt(R[0],R[1],"v",L+1)},TrimModifier.prototype.addSegmentFromArray=function(T,n,P,R){n.setXYAt(T[1],T[5],"o",P),n.setXYAt(T[2],T[6],"i",P+1),R&&n.setXYAt(T[0],T[4],"v",P),n.setXYAt(T[3],T[7],"v",P+1)},TrimModifier.prototype.addShapes=function(T,n,P){var R=T.pathsData,A=T.shape.paths.shapes,L,O=T.shape.paths._length,N,V,j=0,B,z,W,q,H=[],$,Q=!0;for(P?(z=P._length,$=P._length):(P=shapePool.newElement(),z=0,$=0),H.push(P),L=0;L<O;L+=1){for(W=R[L].lengths,P.c=A[L].c,V=A[L].c?W.length:W.length+1,N=1;N<V;N+=1)if(B=W[N-1],j+B.addedLength<n.s)j+=B.addedLength,P.c=!1;else if(j>n.e){P.c=!1;break}else n.s<=j&&n.e>=j+B.addedLength?(this.addSegment(A[L].v[N-1],A[L].o[N-1],A[L].i[N],A[L].v[N],P,z,Q),Q=!1):(q=bez.getNewSegment(A[L].v[N-1],A[L].v[N],A[L].o[N-1],A[L].i[N],(n.s-j)/B.addedLength,(n.e-j)/B.addedLength,W[N-1]),this.addSegmentFromArray(q,P,z,Q),Q=!1,P.c=!1),j+=B.addedLength,z+=1;if(A[L].c&&W.length){if(B=W[N-1],j<=n.e){var U=W[N-1].addedLength;n.s<=j&&n.e>=j+U?(this.addSegment(A[L].v[N-1],A[L].o[N-1],A[L].i[0],A[L].v[0],P,z,Q),Q=!1):(q=bez.getNewSegment(A[L].v[N-1],A[L].v[0],A[L].o[N-1],A[L].i[0],(n.s-j)/U,(n.e-j)/U,W[N-1]),this.addSegmentFromArray(q,P,z,Q),Q=!1,P.c=!1)}else P.c=!1;j+=B.addedLength,z+=1}if(P._length&&(P.setXYAt(P.v[$][0],P.v[$][1],"i",$),P.setXYAt(P.v[P._length-1][0],P.v[P._length-1][1],"o",P._length-1)),j>n.e)break;L<O-1&&(P=shapePool.newElement(),Q=!0,H.push(P),z=0)}return H};function PuckerAndBloatModifier(){}extendPrototype([ShapeModifier],PuckerAndBloatModifier),PuckerAndBloatModifier.prototype.initModifierProperties=function(T,n){this.getValue=this.processKeys,this.amount=PropertyFactory.getProp(T,n.a,0,null,this),this._isAnimated=!!this.amount.effectsSequence.length},PuckerAndBloatModifier.prototype.processPath=function(T,n){var P=n/100,R=[0,0],A=T._length,L=0;for(L=0;L<A;L+=1)R[0]+=T.v[L][0],R[1]+=T.v[L][1];R[0]/=A,R[1]/=A;var O=shapePool.newElement();O.c=T.c;var N,V,j,B,z,W;for(L=0;L<A;L+=1)N=T.v[L][0]+(R[0]-T.v[L][0])*P,V=T.v[L][1]+(R[1]-T.v[L][1])*P,j=T.o[L][0]+(R[0]-T.o[L][0])*-P,B=T.o[L][1]+(R[1]-T.o[L][1])*-P,z=T.i[L][0]+(R[0]-T.i[L][0])*-P,W=T.i[L][1]+(R[1]-T.i[L][1])*-P,O.setTripleAt(N,V,j,B,z,W,L);return O},PuckerAndBloatModifier.prototype.processShapes=function(T){var n,P,R=this.shapes.length,A,L,O=this.amount.v;if(O!==0){var N,V;for(P=0;P<R;P+=1){if(N=this.shapes[P],V=N.localShapeCollection,!(!N.shape._mdf&&!this._mdf&&!T))for(V.releaseShapes(),N.shape._mdf=!0,n=N.shape.paths.shapes,L=N.shape.paths._length,A=0;A<L;A+=1)V.addShape(this.processPath(n[A],O));N.shape.paths=N.localShapeCollection}}this.dynamicProperties.length||(this._mdf=!1)};var TransformPropertyFactory=(function(){var T=[0,0];function n(V){var j=this._mdf;this.iterateDynamicProperties(),this._mdf=this._mdf||j,this.a&&V.translate(-this.a.v[0],-this.a.v[1],this.a.v[2]),this.s&&V.scale(this.s.v[0],this.s.v[1],this.s.v[2]),this.sk&&V.skewFromAxis(-this.sk.v,this.sa.v),this.r?V.rotate(-this.r.v):V.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]),this.data.p.s?this.data.p.z?V.translate(this.px.v,this.py.v,-this.pz.v):V.translate(this.px.v,this.py.v,0):V.translate(this.p.v[0],this.p.v[1],-this.p.v[2])}function P(V){if(this.elem.globalData.frameId!==this.frameId){if(this._isDirty&&(this.precalculateMatrix(),this._isDirty=!1),this.iterateDynamicProperties(),this._mdf||V){var j;if(this.v.cloneFromProps(this.pre.props),this.appliedTransformations<1&&this.v.translate(-this.a.v[0],-this.a.v[1],this.a.v[2]),this.appliedTransformations<2&&this.v.scale(this.s.v[0],this.s.v[1],this.s.v[2]),this.sk&&this.appliedTransformations<3&&this.v.skewFromAxis(-this.sk.v,this.sa.v),this.r&&this.appliedTransformations<4?this.v.rotate(-this.r.v):!this.r&&this.appliedTransformations<4&&this.v.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]),this.autoOriented){var B,z;if(j=this.elem.globalData.frameRate,this.p&&this.p.keyframes&&this.p.getValueAtTime)this.p._caching.lastFrame+this.p.offsetTime<=this.p.keyframes[0].t?(B=this.p.getValueAtTime((this.p.keyframes[0].t+.01)/j,0),z=this.p.getValueAtTime(this.p.keyframes[0].t/j,0)):this.p._caching.lastFrame+this.p.offsetTime>=this.p.keyframes[this.p.keyframes.length-1].t?(B=this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length-1].t/j,0),z=this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length-1].t-.05)/j,0)):(B=this.p.pv,z=this.p.getValueAtTime((this.p._caching.lastFrame+this.p.offsetTime-.01)/j,this.p.offsetTime));else if(this.px&&this.px.keyframes&&this.py.keyframes&&this.px.getValueAtTime&&this.py.getValueAtTime){B=[],z=[];var W=this.px,q=this.py;W._caching.lastFrame+W.offsetTime<=W.keyframes[0].t?(B[0]=W.getValueAtTime((W.keyframes[0].t+.01)/j,0),B[1]=q.getValueAtTime((q.keyframes[0].t+.01)/j,0),z[0]=W.getValueAtTime(W.keyframes[0].t/j,0),z[1]=q.getValueAtTime(q.keyframes[0].t/j,0)):W._caching.lastFrame+W.offsetTime>=W.keyframes[W.keyframes.length-1].t?(B[0]=W.getValueAtTime(W.keyframes[W.keyframes.length-1].t/j,0),B[1]=q.getValueAtTime(q.keyframes[q.keyframes.length-1].t/j,0),z[0]=W.getValueAtTime((W.keyframes[W.keyframes.length-1].t-.01)/j,0),z[1]=q.getValueAtTime((q.keyframes[q.keyframes.length-1].t-.01)/j,0)):(B=[W.pv,q.pv],z[0]=W.getValueAtTime((W._caching.lastFrame+W.offsetTime-.01)/j,W.offsetTime),z[1]=q.getValueAtTime((q._caching.lastFrame+q.offsetTime-.01)/j,q.offsetTime))}else z=T,B=z;this.v.rotate(-Math.atan2(B[1]-z[1],B[0]-z[0]))}this.data.p&&this.data.p.s?this.data.p.z?this.v.translate(this.px.v,this.py.v,-this.pz.v):this.v.translate(this.px.v,this.py.v,0):this.v.translate(this.p.v[0],this.p.v[1],-this.p.v[2])}this.frameId=this.elem.globalData.frameId}}function R(){if(this.appliedTransformations=0,this.pre.reset(),!this.a.effectsSequence.length)this.pre.translate(-this.a.v[0],-this.a.v[1],this.a.v[2]),this.appliedTransformations=1;else return;if(!this.s.effectsSequence.length)this.pre.scale(this.s.v[0],this.s.v[1],this.s.v[2]),this.appliedTransformations=2;else return;if(this.sk)if(!this.sk.effectsSequence.length&&!this.sa.effectsSequence.length)this.pre.skewFromAxis(-this.sk.v,this.sa.v),this.appliedTransformations=3;else return;this.r?this.r.effectsSequence.length||(this.pre.rotate(-this.r.v),this.appliedTransformations=4):!this.rz.effectsSequence.length&&!this.ry.effectsSequence.length&&!this.rx.effectsSequence.length&&!this.or.effectsSequence.length&&(this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]),this.appliedTransformations=4)}function A(){}function L(V){this._addDynamicProperty(V),this.elem.addDynamicProperty(V),this._isDirty=!0}function O(V,j,B){if(this.elem=V,this.frameId=-1,this.propType="transform",this.data=j,this.v=new Matrix,this.pre=new Matrix,this.appliedTransformations=0,this.initDynamicPropertyContainer(B||V),j.p&&j.p.s?(this.px=PropertyFactory.getProp(V,j.p.x,0,0,this),this.py=PropertyFactory.getProp(V,j.p.y,0,0,this),j.p.z&&(this.pz=PropertyFactory.getProp(V,j.p.z,0,0,this))):this.p=PropertyFactory.getProp(V,j.p||{k:[0,0,0]},1,0,this),j.rx){if(this.rx=PropertyFactory.getProp(V,j.rx,0,degToRads,this),this.ry=PropertyFactory.getProp(V,j.ry,0,degToRads,this),this.rz=PropertyFactory.getProp(V,j.rz,0,degToRads,this),j.or.k[0].ti){var z,W=j.or.k.length;for(z=0;z<W;z+=1)j.or.k[z].to=null,j.or.k[z].ti=null}this.or=PropertyFactory.getProp(V,j.or,1,degToRads,this),this.or.sh=!0}else this.r=PropertyFactory.getProp(V,j.r||{k:0},0,degToRads,this);j.sk&&(this.sk=PropertyFactory.getProp(V,j.sk,0,degToRads,this),this.sa=PropertyFactory.getProp(V,j.sa,0,degToRads,this)),this.a=PropertyFactory.getProp(V,j.a||{k:[0,0,0]},1,0,this),this.s=PropertyFactory.getProp(V,j.s||{k:[100,100,100]},1,.01,this),j.o?this.o=PropertyFactory.getProp(V,j.o,0,.01,V):this.o={_mdf:!1,v:1},this._isDirty=!0,this.dynamicProperties.length||this.getValue(!0)}O.prototype={applyToMatrix:n,getValue:P,precalculateMatrix:R,autoOrient:A},extendPrototype([DynamicPropertyContainer],O),O.prototype.addDynamicProperty=L,O.prototype._addDynamicProperty=DynamicPropertyContainer.prototype.addDynamicProperty;function N(V,j,B){return new O(V,j,B)}return{getTransformProperty:N}})();function RepeaterModifier(){}extendPrototype([ShapeModifier],RepeaterModifier),RepeaterModifier.prototype.initModifierProperties=function(T,n){this.getValue=this.processKeys,this.c=PropertyFactory.getProp(T,n.c,0,null,this),this.o=PropertyFactory.getProp(T,n.o,0,null,this),this.tr=TransformPropertyFactory.getTransformProperty(T,n.tr,this),this.so=PropertyFactory.getProp(T,n.tr.so,0,.01,this),this.eo=PropertyFactory.getProp(T,n.tr.eo,0,.01,this),this.data=n,this.dynamicProperties.length||this.getValue(!0),this._isAnimated=!!this.dynamicProperties.length,this.pMatrix=new Matrix,this.rMatrix=new Matrix,this.sMatrix=new Matrix,this.tMatrix=new Matrix,this.matrix=new Matrix},RepeaterModifier.prototype.applyTransforms=function(T,n,P,R,A,L){var O=L?-1:1,N=R.s.v[0]+(1-R.s.v[0])*(1-A),V=R.s.v[1]+(1-R.s.v[1])*(1-A);T.translate(R.p.v[0]*O*A,R.p.v[1]*O*A,R.p.v[2]),n.translate(-R.a.v[0],-R.a.v[1],R.a.v[2]),n.rotate(-R.r.v*O*A),n.translate(R.a.v[0],R.a.v[1],R.a.v[2]),P.translate(-R.a.v[0],-R.a.v[1],R.a.v[2]),P.scale(L?1/N:N,L?1/V:V),P.translate(R.a.v[0],R.a.v[1],R.a.v[2])},RepeaterModifier.prototype.init=function(T,n,P,R){for(this.elem=T,this.arr=n,this.pos=P,this.elemsData=R,this._currentCopies=0,this._elements=[],this._groups=[],this.frameId=-1,this.initDynamicPropertyContainer(T),this.initModifierProperties(T,n[P]);P>0;)P-=1,this._elements.unshift(n[P]);this.dynamicProperties.length?this.k=!0:this.getValue(!0)},RepeaterModifier.prototype.resetElements=function(T){var n,P=T.length;for(n=0;n<P;n+=1)T[n]._processed=!1,T[n].ty==="gr"&&this.resetElements(T[n].it)},RepeaterModifier.prototype.cloneElements=function(T){var n=JSON.parse(JSON.stringify(T));return this.resetElements(n),n},RepeaterModifier.prototype.changeGroupRender=function(T,n){var P,R=T.length;for(P=0;P<R;P+=1)T[P]._render=n,T[P].ty==="gr"&&this.changeGroupRender(T[P].it,n)},RepeaterModifier.prototype.processShapes=function(T){var n,P,R,A,L,O=!1;if(this._mdf||T){var N=Math.ceil(this.c.v);if(this._groups.length<N){for(;this._groups.length<N;){var V={it:this.cloneElements(this._elements),ty:"gr"};V.it.push({a:{a:0,ix:1,k:[0,0]},nm:"Transform",o:{a:0,ix:7,k:100},p:{a:0,ix:2,k:[0,0]},r:{a:1,ix:6,k:[{s:0,e:0,t:0},{s:0,e:0,t:1}]},s:{a:0,ix:3,k:[100,100]},sa:{a:0,ix:5,k:0},sk:{a:0,ix:4,k:0},ty:"tr"}),this.arr.splice(0,0,V),this._groups.splice(0,0,V),this._currentCopies+=1}this.elem.reloadShapes(),O=!0}L=0;var j;for(R=0;R<=this._groups.length-1;R+=1){if(j=L<N,this._groups[R]._render=j,this.changeGroupRender(this._groups[R].it,j),!j){var B=this.elemsData[R].it,z=B[B.length-1];z.transform.op.v!==0?(z.transform.op._mdf=!0,z.transform.op.v=0):z.transform.op._mdf=!1}L+=1}this._currentCopies=N;var W=this.o.v,q=W%1,H=W>0?Math.floor(W):Math.ceil(W),$=this.pMatrix.props,Q=this.rMatrix.props,U=this.sMatrix.props;this.pMatrix.reset(),this.rMatrix.reset(),this.sMatrix.reset(),this.tMatrix.reset(),this.matrix.reset();var J=0;if(W>0){for(;J<H;)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1),J+=1;q&&(this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,q,!1),J+=q)}else if(W<0){for(;J>H;)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!0),J-=1;q&&(this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,-q,!0),J-=q)}R=this.data.m===1?0:this._currentCopies-1,A=this.data.m===1?1:-1,L=this._currentCopies;for(var G,K;L;){if(n=this.elemsData[R].it,P=n[n.length-1].transform.mProps.v.props,K=P.length,n[n.length-1].transform.mProps._mdf=!0,n[n.length-1].transform.op._mdf=!0,n[n.length-1].transform.op.v=this._currentCopies===1?this.so.v:this.so.v+(this.eo.v-this.so.v)*(R/(this._currentCopies-1)),J!==0){for((R!==0&&A===1||R!==this._currentCopies-1&&A===-1)&&this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1),this.matrix.transform(Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],Q[8],Q[9],Q[10],Q[11],Q[12],Q[13],Q[14],Q[15]),this.matrix.transform(U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7],U[8],U[9],U[10],U[11],U[12],U[13],U[14],U[15]),this.matrix.transform($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15]),G=0;G<K;G+=1)P[G]=this.matrix.props[G];this.matrix.reset()}else for(this.matrix.reset(),G=0;G<K;G+=1)P[G]=this.matrix.props[G];J+=1,L-=1,R+=A}}else for(L=this._currentCopies,R=0,A=1;L;)n=this.elemsData[R].it,P=n[n.length-1].transform.mProps.v.props,n[n.length-1].transform.mProps._mdf=!1,n[n.length-1].transform.op._mdf=!1,L-=1,R+=A;return O},RepeaterModifier.prototype.addShape=function(){};function RoundCornersModifier(){}extendPrototype([ShapeModifier],RoundCornersModifier),RoundCornersModifier.prototype.initModifierProperties=function(T,n){this.getValue=this.processKeys,this.rd=PropertyFactory.getProp(T,n.r,0,null,this),this._isAnimated=!!this.rd.effectsSequence.length},RoundCornersModifier.prototype.processPath=function(T,n){var P=shapePool.newElement();P.c=T.c;var R,A=T._length,L,O,N,V,j,B,z=0,W,q,H,$,Q,U;for(R=0;R<A;R+=1)L=T.v[R],N=T.o[R],O=T.i[R],L[0]===N[0]&&L[1]===N[1]&&L[0]===O[0]&&L[1]===O[1]?(R===0||R===A-1)&&!T.c?(P.setTripleAt(L[0],L[1],N[0],N[1],O[0],O[1],z),z+=1):(R===0?V=T.v[A-1]:V=T.v[R-1],j=Math.sqrt(Math.pow(L[0]-V[0],2)+Math.pow(L[1]-V[1],2)),B=j?Math.min(j/2,n)/j:0,Q=L[0]+(V[0]-L[0])*B,W=Q,U=L[1]-(L[1]-V[1])*B,q=U,H=W-(W-L[0])*roundCorner,$=q-(q-L[1])*roundCorner,P.setTripleAt(W,q,H,$,Q,U,z),z+=1,R===A-1?V=T.v[0]:V=T.v[R+1],j=Math.sqrt(Math.pow(L[0]-V[0],2)+Math.pow(L[1]-V[1],2)),B=j?Math.min(j/2,n)/j:0,H=L[0]+(V[0]-L[0])*B,W=H,$=L[1]+(V[1]-L[1])*B,q=$,Q=W-(W-L[0])*roundCorner,U=q-(q-L[1])*roundCorner,P.setTripleAt(W,q,H,$,Q,U,z),z+=1):(P.setTripleAt(T.v[R][0],T.v[R][1],T.o[R][0],T.o[R][1],T.i[R][0],T.i[R][1],z),z+=1);return P},RoundCornersModifier.prototype.processShapes=function(T){var n,P,R=this.shapes.length,A,L,O=this.rd.v;if(O!==0){var N,V;for(P=0;P<R;P+=1){if(N=this.shapes[P],V=N.localShapeCollection,!(!N.shape._mdf&&!this._mdf&&!T))for(V.releaseShapes(),N.shape._mdf=!0,n=N.shape.paths.shapes,L=N.shape.paths._length,A=0;A<L;A+=1)V.addShape(this.processPath(n[A],O));N.shape.paths=N.localShapeCollection}}this.dynamicProperties.length||(this._mdf=!1)};function floatEqual(T,n){return Math.abs(T-n)*1e5<=Math.min(Math.abs(T),Math.abs(n))}function floatZero(T){return Math.abs(T)<=1e-5}function lerp(T,n,P){return T*(1-P)+n*P}function lerpPoint(T,n,P){return[lerp(T[0],n[0],P),lerp(T[1],n[1],P)]}function quadRoots(T,n,P){if(T===0)return[];var R=n*n-4*T*P;if(R<0)return[];var A=-n/(2*T);if(R===0)return[A];var L=Math.sqrt(R)/(2*T);return[A-L,A+L]}function polynomialCoefficients(T,n,P,R){return[-T+3*n-3*P+R,3*T-6*n+3*P,-3*T+3*n,T]}function singlePoint(T){return new PolynomialBezier(T,T,T,T,!1)}function PolynomialBezier(T,n,P,R,A){A&&pointEqual(T,n)&&(n=lerpPoint(T,R,1/3)),A&&pointEqual(P,R)&&(P=lerpPoint(T,R,2/3));var L=polynomialCoefficients(T[0],n[0],P[0],R[0]),O=polynomialCoefficients(T[1],n[1],P[1],R[1]);this.a=[L[0],O[0]],this.b=[L[1],O[1]],this.c=[L[2],O[2]],this.d=[L[3],O[3]],this.points=[T,n,P,R]}PolynomialBezier.prototype.point=function(T){return[((this.a[0]*T+this.b[0])*T+this.c[0])*T+this.d[0],((this.a[1]*T+this.b[1])*T+this.c[1])*T+this.d[1]]},PolynomialBezier.prototype.derivative=function(T){return[(3*T*this.a[0]+2*this.b[0])*T+this.c[0],(3*T*this.a[1]+2*this.b[1])*T+this.c[1]]},PolynomialBezier.prototype.tangentAngle=function(T){var n=this.derivative(T);return Math.atan2(n[1],n[0])},PolynomialBezier.prototype.normalAngle=function(T){var n=this.derivative(T);return Math.atan2(n[0],n[1])},PolynomialBezier.prototype.inflectionPoints=function(){var T=this.a[1]*this.b[0]-this.a[0]*this.b[1];if(floatZero(T))return[];var n=-.5*(this.a[1]*this.c[0]-this.a[0]*this.c[1])/T,P=n*n-1/3*(this.b[1]*this.c[0]-this.b[0]*this.c[1])/T;if(P<0)return[];var R=Math.sqrt(P);return floatZero(R)?R>0&&R<1?[n]:[]:[n-R,n+R].filter(function(A){return A>0&&A<1})},PolynomialBezier.prototype.split=function(T){if(T<=0)return[singlePoint(this.points[0]),this];if(T>=1)return[this,singlePoint(this.points[this.points.length-1])];var n=lerpPoint(this.points[0],this.points[1],T),P=lerpPoint(this.points[1],this.points[2],T),R=lerpPoint(this.points[2],this.points[3],T),A=lerpPoint(n,P,T),L=lerpPoint(P,R,T),O=lerpPoint(A,L,T);return[new PolynomialBezier(this.points[0],n,A,O,!0),new PolynomialBezier(O,L,R,this.points[3],!0)]};function extrema(T,n){var P=T.points[0][n],R=T.points[T.points.length-1][n];if(P>R){var A=R;R=P,P=A}for(var L=quadRoots(3*T.a[n],2*T.b[n],T.c[n]),O=0;O<L.length;O+=1)if(L[O]>0&&L[O]<1){var N=T.point(L[O])[n];N<P?P=N:N>R&&(R=N)}return{min:P,max:R}}PolynomialBezier.prototype.bounds=function(){return{x:extrema(this,0),y:extrema(this,1)}},PolynomialBezier.prototype.boundingBox=function(){var T=this.bounds();return{left:T.x.min,right:T.x.max,top:T.y.min,bottom:T.y.max,width:T.x.max-T.x.min,height:T.y.max-T.y.min,cx:(T.x.max+T.x.min)/2,cy:(T.y.max+T.y.min)/2}};function intersectData(T,n,P){var R=T.boundingBox();return{cx:R.cx,cy:R.cy,width:R.width,height:R.height,bez:T,t:(n+P)/2,t1:n,t2:P}}function splitData(T){var n=T.bez.split(.5);return[intersectData(n[0],T.t1,T.t),intersectData(n[1],T.t,T.t2)]}function boxIntersect(T,n){return Math.abs(T.cx-n.cx)*2<T.width+n.width&&Math.abs(T.cy-n.cy)*2<T.height+n.height}function intersectsImpl(T,n,P,R,A,L){if(boxIntersect(T,n)){if(P>=L||T.width<=R&&T.height<=R&&n.width<=R&&n.height<=R){A.push([T.t,n.t]);return}var O=splitData(T),N=splitData(n);intersectsImpl(O[0],N[0],P+1,R,A,L),intersectsImpl(O[0],N[1],P+1,R,A,L),intersectsImpl(O[1],N[0],P+1,R,A,L),intersectsImpl(O[1],N[1],P+1,R,A,L)}}PolynomialBezier.prototype.intersections=function(T,n,P){n===void 0&&(n=2),P===void 0&&(P=7);var R=[];return intersectsImpl(intersectData(this,0,1),intersectData(T,0,1),0,n,R,P),R},PolynomialBezier.shapeSegment=function(T,n){var P=(n+1)%T.length();return new PolynomialBezier(T.v[n],T.o[n],T.i[P],T.v[P],!0)},PolynomialBezier.shapeSegmentInverted=function(T,n){var P=(n+1)%T.length();return new PolynomialBezier(T.v[P],T.i[P],T.o[n],T.v[n],!0)};function crossProduct(T,n){return[T[1]*n[2]-T[2]*n[1],T[2]*n[0]-T[0]*n[2],T[0]*n[1]-T[1]*n[0]]}function lineIntersection(T,n,P,R){var A=[T[0],T[1],1],L=[n[0],n[1],1],O=[P[0],P[1],1],N=[R[0],R[1],1],V=crossProduct(crossProduct(A,L),crossProduct(O,N));return floatZero(V[2])?null:[V[0]/V[2],V[1]/V[2]]}function polarOffset(T,n,P){return[T[0]+Math.cos(n)*P,T[1]-Math.sin(n)*P]}function pointDistance(T,n){return Math.hypot(T[0]-n[0],T[1]-n[1])}function pointEqual(T,n){return floatEqual(T[0],n[0])&&floatEqual(T[1],n[1])}function ZigZagModifier(){}extendPrototype([ShapeModifier],ZigZagModifier),ZigZagModifier.prototype.initModifierProperties=function(T,n){this.getValue=this.processKeys,this.amplitude=PropertyFactory.getProp(T,n.s,0,null,this),this.frequency=PropertyFactory.getProp(T,n.r,0,null,this),this.pointsType=PropertyFactory.getProp(T,n.pt,0,null,this),this._isAnimated=this.amplitude.effectsSequence.length!==0||this.frequency.effectsSequence.length!==0||this.pointsType.effectsSequence.length!==0};function setPoint(T,n,P,R,A,L,O){var N=P-Math.PI/2,V=P+Math.PI/2,j=n[0]+Math.cos(P)*R*A,B=n[1]-Math.sin(P)*R*A;T.setTripleAt(j,B,j+Math.cos(N)*L,B-Math.sin(N)*L,j+Math.cos(V)*O,B-Math.sin(V)*O,T.length())}function getPerpendicularVector(T,n){var P=[n[0]-T[0],n[1]-T[1]],R=-Math.PI*.5,A=[Math.cos(R)*P[0]-Math.sin(R)*P[1],Math.sin(R)*P[0]+Math.cos(R)*P[1]];return A}function getProjectingAngle(T,n){var P=n===0?T.length()-1:n-1,R=(n+1)%T.length(),A=T.v[P],L=T.v[R],O=getPerpendicularVector(A,L);return Math.atan2(0,1)-Math.atan2(O[1],O[0])}function zigZagCorner(T,n,P,R,A,L,O){var N=getProjectingAngle(n,P),V=n.v[P%n._length],j=n.v[P===0?n._length-1:P-1],B=n.v[(P+1)%n._length],z=L===2?Math.sqrt(Math.pow(V[0]-j[0],2)+Math.pow(V[1]-j[1],2)):0,W=L===2?Math.sqrt(Math.pow(V[0]-B[0],2)+Math.pow(V[1]-B[1],2)):0;setPoint(T,n.v[P%n._length],N,O,R,W/((A+1)*2),z/((A+1)*2))}function zigZagSegment(T,n,P,R,A,L){for(var O=0;O<R;O+=1){var N=(O+1)/(R+1),V=A===2?Math.sqrt(Math.pow(n.points[3][0]-n.points[0][0],2)+Math.pow(n.points[3][1]-n.points[0][1],2)):0,j=n.normalAngle(N),B=n.point(N);setPoint(T,B,j,L,P,V/((R+1)*2),V/((R+1)*2)),L=-L}return L}ZigZagModifier.prototype.processPath=function(T,n,P,R){var A=T._length,L=shapePool.newElement();if(L.c=T.c,T.c||(A-=1),A===0)return L;var O=-1,N=PolynomialBezier.shapeSegment(T,0);zigZagCorner(L,T,0,n,P,R,O);for(var V=0;V<A;V+=1)O=zigZagSegment(L,N,n,P,R,-O),V===A-1&&!T.c?N=null:N=PolynomialBezier.shapeSegment(T,(V+1)%A),zigZagCorner(L,T,V+1,n,P,R,O);return L},ZigZagModifier.prototype.processShapes=function(T){var n,P,R=this.shapes.length,A,L,O=this.amplitude.v,N=Math.max(0,Math.round(this.frequency.v)),V=this.pointsType.v;if(O!==0){var j,B;for(P=0;P<R;P+=1){if(j=this.shapes[P],B=j.localShapeCollection,!(!j.shape._mdf&&!this._mdf&&!T))for(B.releaseShapes(),j.shape._mdf=!0,n=j.shape.paths.shapes,L=j.shape.paths._length,A=0;A<L;A+=1)B.addShape(this.processPath(n[A],O,N,V));j.shape.paths=j.localShapeCollection}}this.dynamicProperties.length||(this._mdf=!1)};function linearOffset(T,n,P){var R=Math.atan2(n[0]-T[0],n[1]-T[1]);return[polarOffset(T,R,P),polarOffset(n,R,P)]}function offsetSegment(T,n){var P,R,A,L,O,N,V;V=linearOffset(T.points[0],T.points[1],n),P=V[0],R=V[1],V=linearOffset(T.points[1],T.points[2],n),A=V[0],L=V[1],V=linearOffset(T.points[2],T.points[3],n),O=V[0],N=V[1];var j=lineIntersection(P,R,A,L);j===null&&(j=R);var B=lineIntersection(O,N,A,L);return B===null&&(B=O),new PolynomialBezier(P,j,B,N)}function joinLines(T,n,P,R,A){var L=n.points[3],O=P.points[0];if(R===3||pointEqual(L,O))return L;if(R===2){var N=-n.tangentAngle(1),V=-P.tangentAngle(0)+Math.PI,j=lineIntersection(L,polarOffset(L,N+Math.PI/2,100),O,polarOffset(O,N+Math.PI/2,100)),B=j?pointDistance(j,L):pointDistance(L,O)/2,z=polarOffset(L,N,2*B*roundCorner);return T.setXYAt(z[0],z[1],"o",T.length()-1),z=polarOffset(O,V,2*B*roundCorner),T.setTripleAt(O[0],O[1],O[0],O[1],z[0],z[1],T.length()),O}var W=pointEqual(L,n.points[2])?n.points[0]:n.points[2],q=pointEqual(O,P.points[1])?P.points[3]:P.points[1],H=lineIntersection(W,L,O,q);return H&&pointDistance(H,L)<A?(T.setTripleAt(H[0],H[1],H[0],H[1],H[0],H[1],T.length()),H):L}function getIntersection(T,n){var P=T.intersections(n);return P.length&&floatEqual(P[0][0],1)&&P.shift(),P.length?P[0]:null}function pruneSegmentIntersection(T,n){var P=T.slice(),R=n.slice(),A=getIntersection(T[T.length-1],n[0]);return A&&(P[T.length-1]=T[T.length-1].split(A[0])[0],R[0]=n[0].split(A[1])[1]),T.length>1&&n.length>1&&(A=getIntersection(T[0],n[n.length-1]),A)?[[T[0].split(A[0])[0]],[n[n.length-1].split(A[1])[1]]]:[P,R]}function pruneIntersections(T){for(var n,P=1;P<T.length;P+=1)n=pruneSegmentIntersection(T[P-1],T[P]),T[P-1]=n[0],T[P]=n[1];return T.length>1&&(n=pruneSegmentIntersection(T[T.length-1],T[0]),T[T.length-1]=n[0],T[0]=n[1]),T}function offsetSegmentSplit(T,n){var P=T.inflectionPoints(),R,A,L,O;if(P.length===0)return[offsetSegment(T,n)];if(P.length===1||floatEqual(P[1],1))return L=T.split(P[0]),R=L[0],A=L[1],[offsetSegment(R,n),offsetSegment(A,n)];L=T.split(P[0]),R=L[0];var N=(P[1]-P[0])/(1-P[0]);return L=L[1].split(N),O=L[0],A=L[1],[offsetSegment(R,n),offsetSegment(O,n),offsetSegment(A,n)]}function OffsetPathModifier(){}extendPrototype([ShapeModifier],OffsetPathModifier),OffsetPathModifier.prototype.initModifierProperties=function(T,n){this.getValue=this.processKeys,this.amount=PropertyFactory.getProp(T,n.a,0,null,this),this.miterLimit=PropertyFactory.getProp(T,n.ml,0,null,this),this.lineJoin=n.lj,this._isAnimated=this.amount.effectsSequence.length!==0},OffsetPathModifier.prototype.processPath=function(T,n,P,R){var A=shapePool.newElement();A.c=T.c;var L=T.length();T.c||(L-=1);var O,N,V,j=[];for(O=0;O<L;O+=1)V=PolynomialBezier.shapeSegment(T,O),j.push(offsetSegmentSplit(V,n));if(!T.c)for(O=L-1;O>=0;O-=1)V=PolynomialBezier.shapeSegmentInverted(T,O),j.push(offsetSegmentSplit(V,n));j=pruneIntersections(j);var B=null,z=null;for(O=0;O<j.length;O+=1){var W=j[O];for(z&&(B=joinLines(A,z,W[0],P,R)),z=W[W.length-1],N=0;N<W.length;N+=1)V=W[N],B&&pointEqual(V.points[0],B)?A.setXYAt(V.points[1][0],V.points[1][1],"o",A.length()-1):A.setTripleAt(V.points[0][0],V.points[0][1],V.points[1][0],V.points[1][1],V.points[0][0],V.points[0][1],A.length()),A.setTripleAt(V.points[3][0],V.points[3][1],V.points[3][0],V.points[3][1],V.points[2][0],V.points[2][1],A.length()),B=V.points[3]}return j.length&&joinLines(A,z,j[0][0],P,R),A},OffsetPathModifier.prototype.processShapes=function(T){var n,P,R=this.shapes.length,A,L,O=this.amount.v,N=this.miterLimit.v,V=this.lineJoin;if(O!==0){var j,B;for(P=0;P<R;P+=1){if(j=this.shapes[P],B=j.localShapeCollection,!(!j.shape._mdf&&!this._mdf&&!T))for(B.releaseShapes(),j.shape._mdf=!0,n=j.shape.paths.shapes,L=j.shape.paths._length,A=0;A<L;A+=1)B.addShape(this.processPath(n[A],O,V,N));j.shape.paths=j.localShapeCollection}}this.dynamicProperties.length||(this._mdf=!1)};function getFontProperties(T){for(var n=T.fStyle?T.fStyle.split(" "):[],P="normal",R="normal",A=n.length,L,O=0;O<A;O+=1)switch(L=n[O].toLowerCase(),L){case"italic":R="italic";break;case"bold":P="700";break;case"black":P="900";break;case"medium":P="500";break;case"regular":case"normal":P="400";break;case"light":case"thin":P="200";break}return{style:R,weight:T.fWeight||P}}var FontManager=(function(){var T=5e3,n={w:0,size:0,shapes:[],data:{shapes:[]}},P=[];P=P.concat([2304,2305,2306,2307,2362,2363,2364,2364,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2387,2388,2389,2390,2391,2402,2403]);var R=127988,A=917631,L=917601,O=917626,N=65039,V=8205,j=127462,B=127487,z=["d83cdffb","d83cdffc","d83cdffd","d83cdffe","d83cdfff"];function W(ne){var ce=ne.split(","),ee,te=ce.length,oe=[];for(ee=0;ee<te;ee+=1)ce[ee]!=="sans-serif"&&ce[ee]!=="monospace"&&oe.push(ce[ee]);return oe.join(",")}function q(ne,ce){var ee=createTag("span");ee.setAttribute("aria-hidden",!0),ee.style.fontFamily=ce;var te=createTag("span");te.innerText="giItT1WQy@!-/#",ee.style.position="absolute",ee.style.left="-10000px",ee.style.top="-10000px",ee.style.fontSize="300px",ee.style.fontVariant="normal",ee.style.fontStyle="normal",ee.style.fontWeight="normal",ee.style.letterSpacing="0",ee.appendChild(te),document.body.appendChild(ee);var oe=te.offsetWidth;return te.style.fontFamily=W(ne)+", "+ce,{node:te,w:oe,parent:ee}}function H(){var ne,ce=this.fonts.length,ee,te,oe=ce;for(ne=0;ne<ce;ne+=1)this.fonts[ne].loaded?oe-=1:this.fonts[ne].fOrigin==="n"||this.fonts[ne].origin===0?this.fonts[ne].loaded=!0:(ee=this.fonts[ne].monoCase.node,te=this.fonts[ne].monoCase.w,ee.offsetWidth!==te?(oe-=1,this.fonts[ne].loaded=!0):(ee=this.fonts[ne].sansCase.node,te=this.fonts[ne].sansCase.w,ee.offsetWidth!==te&&(oe-=1,this.fonts[ne].loaded=!0)),this.fonts[ne].loaded&&(this.fonts[ne].sansCase.parent.parentNode.removeChild(this.fonts[ne].sansCase.parent),this.fonts[ne].monoCase.parent.parentNode.removeChild(this.fonts[ne].monoCase.parent)));oe!==0&&Date.now()-this.initTime<T?setTimeout(this.checkLoadedFontsBinded,20):setTimeout(this.setIsLoadedBinded,10)}function $(ne,ce){var ee=document.body&&ce?"svg":"canvas",te,oe=getFontProperties(ne);if(ee==="svg"){var ae=createNS("text");ae.style.fontSize="100px",ae.setAttribute("font-family",ne.fFamily),ae.setAttribute("font-style",oe.style),ae.setAttribute("font-weight",oe.weight),ae.textContent="1",ne.fClass?(ae.style.fontFamily="inherit",ae.setAttribute("class",ne.fClass)):ae.style.fontFamily=ne.fFamily,ce.appendChild(ae),te=ae}else{var de=new OffscreenCanvas(500,500).getContext("2d");de.font=oe.style+" "+oe.weight+" 100px "+ne.fFamily,te=de}function ge(ye){return ee==="svg"?(te.textContent=ye,te.getComputedTextLength()):te.measureText(ye).width}return{measureText:ge}}function Q(ne,ce){if(!ne){this.isLoaded=!0;return}if(this.chars){this.isLoaded=!0,this.fonts=ne.list;return}if(!document.body){this.isLoaded=!0,ne.list.forEach(function(Ae){Ae.helper=$(Ae),Ae.cache={}}),this.fonts=ne.list;return}var ee=ne.list,te,oe=ee.length,ae=oe;for(te=0;te<oe;te+=1){var de=!0,ge,ye;if(ee[te].loaded=!1,ee[te].monoCase=q(ee[te].fFamily,"monospace"),ee[te].sansCase=q(ee[te].fFamily,"sans-serif"),!ee[te].fPath)ee[te].loaded=!0,ae-=1;else if(ee[te].fOrigin==="p"||ee[te].origin===3){if(ge=document.querySelectorAll('style[f-forigin="p"][f-family="'+ee[te].fFamily+'"], style[f-origin="3"][f-family="'+ee[te].fFamily+'"]'),ge.length>0&&(de=!1),de){var Ee=createTag("style");Ee.setAttribute("f-forigin",ee[te].fOrigin),Ee.setAttribute("f-origin",ee[te].origin),Ee.setAttribute("f-family",ee[te].fFamily),Ee.type="text/css",Ee.innerText="@font-face {font-family: "+ee[te].fFamily+"; font-style: normal; src: url('"+ee[te].fPath+"');}",ce.appendChild(Ee)}}else if(ee[te].fOrigin==="g"||ee[te].origin===1){for(ge=document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'),ye=0;ye<ge.length;ye+=1)ge[ye].href.indexOf(ee[te].fPath)!==-1&&(de=!1);if(de){var Pe=createTag("link");Pe.setAttribute("f-forigin",ee[te].fOrigin),Pe.setAttribute("f-origin",ee[te].origin),Pe.type="text/css",Pe.rel="stylesheet",Pe.href=ee[te].fPath,document.body.appendChild(Pe)}}else if(ee[te].fOrigin==="t"||ee[te].origin===2){for(ge=document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]'),ye=0;ye<ge.length;ye+=1)ee[te].fPath===ge[ye].src&&(de=!1);if(de){var Ie=createTag("link");Ie.setAttribute("f-forigin",ee[te].fOrigin),Ie.setAttribute("f-origin",ee[te].origin),Ie.setAttribute("rel","stylesheet"),Ie.setAttribute("href",ee[te].fPath),ce.appendChild(Ie)}}ee[te].helper=$(ee[te],ce),ee[te].cache={},this.fonts.push(ee[te])}ae===0?this.isLoaded=!0:setTimeout(this.checkLoadedFonts.bind(this),100)}function U(ne){if(ne){this.chars||(this.chars=[]);var ce,ee=ne.length,te,oe=this.chars.length,ae;for(ce=0;ce<ee;ce+=1){for(te=0,ae=!1;te<oe;)this.chars[te].style===ne[ce].style&&this.chars[te].fFamily===ne[ce].fFamily&&this.chars[te].ch===ne[ce].ch&&(ae=!0),te+=1;ae||(this.chars.push(ne[ce]),oe+=1)}}}function J(ne,ce,ee){for(var te=0,oe=this.chars.length;te<oe;){if(this.chars[te].ch===ne&&this.chars[te].style===ce&&this.chars[te].fFamily===ee)return this.chars[te];te+=1}return(typeof ne=="string"&&ne.charCodeAt(0)!==13||!ne)&&console&&console.warn&&!this._warned&&(this._warned=!0,console.warn("Missing character from exported characters list: ",ne,ce,ee)),n}function G(ne,ce,ee){var te=this.getFontByName(ce),oe=ne;if(!te.cache[oe]){var ae=te.helper;if(ne===" "){var de=ae.measureText("|"+ne+"|"),ge=ae.measureText("||");te.cache[oe]=(de-ge)/100}else te.cache[oe]=ae.measureText(ne)/100}return te.cache[oe]*ee}function K(ne){for(var ce=0,ee=this.fonts.length;ce<ee;){if(this.fonts[ce].fName===ne)return this.fonts[ce];ce+=1}return this.fonts[0]}function Y(ne){var ce=0,ee=ne.charCodeAt(0);if(ee>=55296&&ee<=56319){var te=ne.charCodeAt(1);te>=56320&&te<=57343&&(ce=(ee-55296)*1024+te-56320+65536)}return ce}function Z(ne,ce){var ee=ne.toString(16)+ce.toString(16);return z.indexOf(ee)!==-1}function ie(ne){return ne===V}function se(ne){return ne===N}function le(ne){var ce=Y(ne);return ce>=j&&ce<=B}function pe(ne){return le(ne.substr(0,2))&&le(ne.substr(2,2))}function ue(ne){return P.indexOf(ne)!==-1}function he(ne,ce){var ee=Y(ne.substr(ce,2));if(ee!==R)return!1;var te=0;for(ce+=2;te<5;){if(ee=Y(ne.substr(ce,2)),ee<L||ee>O)return!1;te+=1,ce+=2}return Y(ne.substr(ce,2))===A}function ve(){this.isLoaded=!0}var be=function(){this.fonts=[],this.chars=null,this.typekitLoaded=0,this.isLoaded=!1,this._warned=!1,this.initTime=Date.now(),this.setIsLoadedBinded=this.setIsLoaded.bind(this),this.checkLoadedFontsBinded=this.checkLoadedFonts.bind(this)};be.isModifier=Z,be.isZeroWidthJoiner=ie,be.isFlagEmoji=pe,be.isRegionalCode=le,be.isCombinedCharacter=ue,be.isRegionalFlag=he,be.isVariationSelector=se,be.BLACK_FLAG_CODE_POINT=R;var fe={addChars:U,addFonts:Q,getCharData:J,getFontByName:K,measureText:G,checkLoadedFonts:H,setIsLoaded:ve};return be.prototype=fe,be})();function SlotManager(T){this.animationData=T}SlotManager.prototype.getProp=function(T){return this.animationData.slots&&this.animationData.slots[T.sid]?Object.assign(T,this.animationData.slots[T.sid].p):T};function slotFactory(T){return new SlotManager(T)}function RenderableElement(){}RenderableElement.prototype={initRenderable:function(){this.isInRange=!1,this.hidden=!1,this.isTransparent=!1,this.renderableComponents=[]},addRenderableComponent:function(n){this.renderableComponents.indexOf(n)===-1&&this.renderableComponents.push(n)},removeRenderableComponent:function(n){this.renderableComponents.indexOf(n)!==-1&&this.renderableComponents.splice(this.renderableComponents.indexOf(n),1)},prepareRenderableFrame:function(n){this.checkLayerLimits(n)},checkTransparency:function(){this.finalTransform.mProp.o.v<=0?!this.isTransparent&&this.globalData.renderConfig.hideOnTransparent&&(this.isTransparent=!0,this.hide()):this.isTransparent&&(this.isTransparent=!1,this.show())},checkLayerLimits:function(n){this.data.ip-this.data.st<=n&&this.data.op-this.data.st>n?this.isInRange!==!0&&(this.globalData._mdf=!0,this._mdf=!0,this.isInRange=!0,this.show()):this.isInRange!==!1&&(this.globalData._mdf=!0,this.isInRange=!1,this.hide())},renderRenderable:function(){var n,P=this.renderableComponents.length;for(n=0;n<P;n+=1)this.renderableComponents[n].renderFrame(this._isFirstFrame)},sourceRectAtTime:function(){return{top:0,left:0,width:100,height:100}},getLayerSize:function(){return this.data.ty===5?{w:this.data.textData.width,h:this.data.textData.height}:{w:this.data.width,h:this.data.height}}};var getBlendMode=(function(){var T={0:"source-over",1:"multiply",2:"screen",3:"overlay",4:"darken",5:"lighten",6:"color-dodge",7:"color-burn",8:"hard-light",9:"soft-light",10:"difference",11:"exclusion",12:"hue",13:"saturation",14:"color",15:"luminosity"};return function(n){return T[n]||""}})();function SliderEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,0,0,P)}function AngleEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,0,0,P)}function ColorEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,1,0,P)}function PointEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,1,0,P)}function LayerIndexEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,0,0,P)}function MaskIndexEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,0,0,P)}function CheckboxEffect(T,n,P){this.p=PropertyFactory.getProp(n,T.v,0,0,P)}function NoValueEffect(){this.p={}}function EffectsManager(T,n){var P=T.ef||[];this.effectElements=[];var R,A=P.length,L;for(R=0;R<A;R+=1)L=new GroupEffect(P[R],n),this.effectElements.push(L)}function GroupEffect(T,n){this.init(T,n)}extendPrototype([DynamicPropertyContainer],GroupEffect),GroupEffect.prototype.getValue=GroupEffect.prototype.iterateDynamicProperties,GroupEffect.prototype.init=function(T,n){this.data=T,this.effectElements=[],this.initDynamicPropertyContainer(n);var P,R=this.data.ef.length,A,L=this.data.ef;for(P=0;P<R;P+=1){switch(A=null,L[P].ty){case 0:A=new SliderEffect(L[P],n,this);break;case 1:A=new AngleEffect(L[P],n,this);break;case 2:A=new ColorEffect(L[P],n,this);break;case 3:A=new PointEffect(L[P],n,this);break;case 4:case 7:A=new CheckboxEffect(L[P],n,this);break;case 10:A=new LayerIndexEffect(L[P],n,this);break;case 11:A=new MaskIndexEffect(L[P],n,this);break;case 5:A=new EffectsManager(L[P],n);break;default:A=new NoValueEffect(L[P]);break}A&&this.effectElements.push(A)}};function BaseElement(){}BaseElement.prototype={checkMasks:function(){if(!this.data.hasMask)return!1;for(var n=0,P=this.data.masksProperties.length;n<P;){if(this.data.masksProperties[n].mode!=="n"&&this.data.masksProperties[n].cl!==!1)return!0;n+=1}return!1},initExpressions:function(){var n=getExpressionInterfaces();if(n){var P=n("layer"),R=n("effects"),A=n("shape"),L=n("text"),O=n("comp");this.layerInterface=P(this),this.data.hasMask&&this.maskManager&&this.layerInterface.registerMaskInterface(this.maskManager);var N=R.createEffectsInterface(this,this.layerInterface);this.layerInterface.registerEffectsInterface(N),this.data.ty===0||this.data.xt?this.compInterface=O(this):this.data.ty===4?(this.layerInterface.shapeInterface=A(this.shapesData,this.itemsData,this.layerInterface),this.layerInterface.content=this.layerInterface.shapeInterface):this.data.ty===5&&(this.layerInterface.textInterface=L(this),this.layerInterface.text=this.layerInterface.textInterface)}},setBlendMode:function(){var n=getBlendMode(this.data.bm),P=this.baseElement||this.layerElement;P.style["mix-blend-mode"]=n},initBaseData:function(n,P,R){this.globalData=P,this.comp=R,this.data=n,this.layerId=createElementID(),this.data.sr||(this.data.sr=1),this.effectsManager=new EffectsManager(this.data,this,this.dynamicProperties)},getType:function(){return this.type},sourceRectAtTime:function(){}};function FrameElement(){}FrameElement.prototype={initFrame:function(){this._isFirstFrame=!1,this.dynamicProperties=[],this._mdf=!1},prepareProperties:function(n,P){var R,A=this.dynamicProperties.length;for(R=0;R<A;R+=1)(P||this._isParent&&this.dynamicProperties[R].propType==="transform")&&(this.dynamicProperties[R].getValue(),this.dynamicProperties[R]._mdf&&(this.globalData._mdf=!0,this._mdf=!0))},addDynamicProperty:function(n){this.dynamicProperties.indexOf(n)===-1&&this.dynamicProperties.push(n)}};function FootageElement(T,n,P){this.initFrame(),this.initRenderable(),this.assetData=n.getAssetData(T.refId),this.footageData=n.imageLoader.getAsset(this.assetData),this.initBaseData(T,n,P)}FootageElement.prototype.prepareFrame=function(){},extendPrototype([RenderableElement,BaseElement,FrameElement],FootageElement),FootageElement.prototype.getBaseElement=function(){return null},FootageElement.prototype.renderFrame=function(){},FootageElement.prototype.destroy=function(){},FootageElement.prototype.initExpressions=function(){var T=getExpressionInterfaces();if(T){var n=T("footage");this.layerInterface=n(this)}},FootageElement.prototype.getFootageData=function(){return this.footageData};function AudioElement(T,n,P){this.initFrame(),this.initRenderable(),this.assetData=n.getAssetData(T.refId),this.initBaseData(T,n,P),this._isPlaying=!1,this._canPlay=!1;var R=this.globalData.getAssetsPath(this.assetData);this.audio=this.globalData.audioController.createAudio(R),this._currentTime=0,this.globalData.audioController.addAudio(this),this._volumeMultiplier=1,this._volume=1,this._previousVolume=null,this.tm=T.tm?PropertyFactory.getProp(this,T.tm,0,n.frameRate,this):{_placeholder:!0},this.lv=PropertyFactory.getProp(this,T.au&&T.au.lv?T.au.lv:{k:[100]},1,.01,this)}AudioElement.prototype.prepareFrame=function(T){if(this.prepareRenderableFrame(T,!0),this.prepareProperties(T,!0),this.tm._placeholder)this._currentTime=T/this.data.sr;else{var n=this.tm.v;this._currentTime=n}this._volume=this.lv.v[0];var P=this._volume*this._volumeMultiplier;this._previousVolume!==P&&(this._previousVolume=P,this.audio.volume(P))},extendPrototype([RenderableElement,BaseElement,FrameElement],AudioElement),AudioElement.prototype.renderFrame=function(){this.isInRange&&this._canPlay&&(this._isPlaying?(!this.audio.playing()||Math.abs(this._currentTime/this.globalData.frameRate-this.audio.seek())>.1)&&this.audio.seek(this._currentTime/this.globalData.frameRate):(this.audio.play(),this.audio.seek(this._currentTime/this.globalData.frameRate),this._isPlaying=!0))},AudioElement.prototype.show=function(){},AudioElement.prototype.hide=function(){this.audio.pause(),this._isPlaying=!1},AudioElement.prototype.pause=function(){this.audio.pause(),this._isPlaying=!1,this._canPlay=!1},AudioElement.prototype.resume=function(){this._canPlay=!0},AudioElement.prototype.setRate=function(T){this.audio.rate(T)},AudioElement.prototype.volume=function(T){this._volumeMultiplier=T,this._previousVolume=T*this._volume,this.audio.volume(this._previousVolume)},AudioElement.prototype.getBaseElement=function(){return null},AudioElement.prototype.destroy=function(){},AudioElement.prototype.sourceRectAtTime=function(){},AudioElement.prototype.initExpressions=function(){};function BaseRenderer(){}BaseRenderer.prototype.checkLayers=function(T){var n,P=this.layers.length,R;for(this.completeLayers=!0,n=P-1;n>=0;n-=1)this.elements[n]||(R=this.layers[n],R.ip-R.st<=T-this.layers[n].st&&R.op-R.st>T-this.layers[n].st&&this.buildItem(n)),this.completeLayers=this.elements[n]?this.completeLayers:!1;this.checkPendingElements()},BaseRenderer.prototype.createItem=function(T){switch(T.ty){case 2:return this.createImage(T);case 0:return this.createComp(T);case 1:return this.createSolid(T);case 3:return this.createNull(T);case 4:return this.createShape(T);case 5:return this.createText(T);case 6:return this.createAudio(T);case 13:return this.createCamera(T);case 15:return this.createFootage(T);default:return this.createNull(T)}},BaseRenderer.prototype.createCamera=function(){throw new Error("You're using a 3d camera. Try the html renderer.")},BaseRenderer.prototype.createAudio=function(T){return new AudioElement(T,this.globalData,this)},BaseRenderer.prototype.createFootage=function(T){return new FootageElement(T,this.globalData,this)},BaseRenderer.prototype.buildAllItems=function(){var T,n=this.layers.length;for(T=0;T<n;T+=1)this.buildItem(T);this.checkPendingElements()},BaseRenderer.prototype.includeLayers=function(T){this.completeLayers=!1;var n,P=T.length,R,A=this.layers.length;for(n=0;n<P;n+=1)for(R=0;R<A;){if(this.layers[R].id===T[n].id){this.layers[R]=T[n];break}R+=1}},BaseRenderer.prototype.setProjectInterface=function(T){this.globalData.projectInterface=T},BaseRenderer.prototype.initItems=function(){this.globalData.progressiveLoad||this.buildAllItems()},BaseRenderer.prototype.buildElementParenting=function(T,n,P){for(var R=this.elements,A=this.layers,L=0,O=A.length;L<O;)A[L].ind==n&&(!R[L]||R[L]===!0?(this.buildItem(L),this.addPendingElement(T)):(P.push(R[L]),R[L].setAsParent(),A[L].parent!==void 0?this.buildElementParenting(T,A[L].parent,P):T.setHierarchy(P))),L+=1},BaseRenderer.prototype.addPendingElement=function(T){this.pendingElements.push(T)},BaseRenderer.prototype.searchExtraCompositions=function(T){var n,P=T.length;for(n=0;n<P;n+=1)if(T[n].xt){var R=this.createComp(T[n]);R.initExpressions(),this.globalData.projectInterface.registerComposition(R)}},BaseRenderer.prototype.getElementById=function(T){var n,P=this.elements.length;for(n=0;n<P;n+=1)if(this.elements[n].data.ind===T)return this.elements[n];return null},BaseRenderer.prototype.getElementByPath=function(T){var n=T.shift(),P;if(typeof n=="number")P=this.elements[n];else{var R,A=this.elements.length;for(R=0;R<A;R+=1)if(this.elements[R].data.nm===n){P=this.elements[R];break}}return T.length===0?P:P.getElementByPath(T)},BaseRenderer.prototype.setupGlobalData=function(T,n){this.globalData.fontManager=new FontManager,this.globalData.slotManager=slotFactory(T),this.globalData.fontManager.addChars(T.chars),this.globalData.fontManager.addFonts(T.fonts,n),this.globalData.getAssetData=this.animationItem.getAssetData.bind(this.animationItem),this.globalData.getAssetsPath=this.animationItem.getAssetsPath.bind(this.animationItem),this.globalData.imageLoader=this.animationItem.imagePreloader,this.globalData.audioController=this.animationItem.audioController,this.globalData.frameId=0,this.globalData.frameRate=T.fr,this.globalData.nm=T.nm,this.globalData.compSize={w:T.w,h:T.h}};var effectTypes={TRANSFORM_EFFECT:"transformEFfect"};function TransformElement(){}TransformElement.prototype={initTransform:function(){var n=new Matrix;this.finalTransform={mProp:this.data.ks?TransformPropertyFactory.getTransformProperty(this,this.data.ks,this):{o:0},_matMdf:!1,_localMatMdf:!1,_opMdf:!1,mat:n,localMat:n,localOpacity:1},this.data.ao&&(this.finalTransform.mProp.autoOriented=!0),this.data.ty},renderTransform:function(){if(this.finalTransform._opMdf=this.finalTransform.mProp.o._mdf||this._isFirstFrame,this.finalTransform._matMdf=this.finalTransform.mProp._mdf||this._isFirstFrame,this.hierarchy){var n,P=this.finalTransform.mat,R=0,A=this.hierarchy.length;if(!this.finalTransform._matMdf)for(;R<A;){if(this.hierarchy[R].finalTransform.mProp._mdf){this.finalTransform._matMdf=!0;break}R+=1}if(this.finalTransform._matMdf)for(n=this.finalTransform.mProp.v.props,P.cloneFromProps(n),R=0;R<A;R+=1)P.multiply(this.hierarchy[R].finalTransform.mProp.v)}(!this.localTransforms||this.finalTransform._matMdf)&&(this.finalTransform._localMatMdf=this.finalTransform._matMdf),this.finalTransform._opMdf&&(this.finalTransform.localOpacity=this.finalTransform.mProp.o.v)},renderLocalTransform:function(){if(this.localTransforms){var n=0,P=this.localTransforms.length;if(this.finalTransform._localMatMdf=this.finalTransform._matMdf,!this.finalTransform._localMatMdf||!this.finalTransform._opMdf)for(;n<P;)this.localTransforms[n]._mdf&&(this.finalTransform._localMatMdf=!0),this.localTransforms[n]._opMdf&&!this.finalTransform._opMdf&&(this.finalTransform.localOpacity=this.finalTransform.mProp.o.v,this.finalTransform._opMdf=!0),n+=1;if(this.finalTransform._localMatMdf){var R=this.finalTransform.localMat;for(this.localTransforms[0].matrix.clone(R),n=1;n<P;n+=1){var A=this.localTransforms[n].matrix;R.multiply(A)}R.multiply(this.finalTransform.mat)}if(this.finalTransform._opMdf){var L=this.finalTransform.localOpacity;for(n=0;n<P;n+=1)L*=this.localTransforms[n].opacity*.01;this.finalTransform.localOpacity=L}}},searchEffectTransforms:function(){if(this.renderableEffectsManager){var n=this.renderableEffectsManager.getEffects(effectTypes.TRANSFORM_EFFECT);if(n.length){this.localTransforms=[],this.finalTransform.localMat=new Matrix;var P=0,R=n.length;for(P=0;P<R;P+=1)this.localTransforms.push(n[P])}}},globalToLocal:function(n){var P=[];P.push(this.finalTransform);for(var R=!0,A=this.comp;R;)A.finalTransform?(A.data.hasMask&&P.splice(0,0,A.finalTransform),A=A.comp):R=!1;var L,O=P.length,N;for(L=0;L<O;L+=1)N=P[L].mat.applyToPointArray(0,0,0),n=[n[0]-N[0],n[1]-N[1],0];return n},mHelper:new Matrix};function MaskElement(T,n,P){this.data=T,this.element=n,this.globalData=P,this.storedData=[],this.masksProperties=this.data.masksProperties||[],this.maskElement=null;var R=this.globalData.defs,A,L=this.masksProperties?this.masksProperties.length:0;this.viewData=createSizedArray(L),this.solidPath="";var O,N=this.masksProperties,V=0,j=[],B,z,W=createElementID(),q,H,$,Q,U="clipPath",J="clip-path";for(A=0;A<L;A+=1)if((N[A].mode!=="a"&&N[A].mode!=="n"||N[A].inv||N[A].o.k!==100||N[A].o.x)&&(U="mask",J="mask"),(N[A].mode==="s"||N[A].mode==="i")&&V===0?(q=createNS("rect"),q.setAttribute("fill","#ffffff"),q.setAttribute("width",this.element.comp.data.w||0),q.setAttribute("height",this.element.comp.data.h||0),j.push(q)):q=null,O=createNS("path"),N[A].mode==="n")this.viewData[A]={op:PropertyFactory.getProp(this.element,N[A].o,0,.01,this.element),prop:ShapePropertyFactory.getShapeProp(this.element,N[A],3),elem:O,lastPath:""},R.appendChild(O);else{V+=1,O.setAttribute("fill",N[A].mode==="s"?"#000000":"#ffffff"),O.setAttribute("clip-rule","nonzero");var G;if(N[A].x.k!==0?(U="mask",J="mask",Q=PropertyFactory.getProp(this.element,N[A].x,0,null,this.element),G=createElementID(),H=createNS("filter"),H.setAttribute("id",G),$=createNS("feMorphology"),$.setAttribute("operator","erode"),$.setAttribute("in","SourceGraphic"),$.setAttribute("radius","0"),H.appendChild($),R.appendChild(H),O.setAttribute("stroke",N[A].mode==="s"?"#000000":"#ffffff")):($=null,Q=null),this.storedData[A]={elem:O,x:Q,expan:$,lastPath:"",lastOperator:"",filterId:G,lastRadius:0},N[A].mode==="i"){z=j.length;var K=createNS("g");for(B=0;B<z;B+=1)K.appendChild(j[B]);var Y=createNS("mask");Y.setAttribute("mask-type","alpha"),Y.setAttribute("id",W+"_"+V),Y.appendChild(O),R.appendChild(Y),K.setAttribute("mask","url("+getLocationHref()+"#"+W+"_"+V+")"),j.length=0,j.push(K)}else j.push(O);N[A].inv&&!this.solidPath&&(this.solidPath=this.createLayerSolidPath()),this.viewData[A]={elem:O,lastPath:"",op:PropertyFactory.getProp(this.element,N[A].o,0,.01,this.element),prop:ShapePropertyFactory.getShapeProp(this.element,N[A],3),invRect:q},this.viewData[A].prop.k||this.drawPath(N[A],this.viewData[A].prop.v,this.viewData[A])}for(this.maskElement=createNS(U),L=j.length,A=0;A<L;A+=1)this.maskElement.appendChild(j[A]);V>0&&(this.maskElement.setAttribute("id",W),this.element.maskedElement.setAttribute(J,"url("+getLocationHref()+"#"+W+")"),R.appendChild(this.maskElement)),this.viewData.length&&this.element.addRenderableComponent(this)}MaskElement.prototype.getMaskProperty=function(T){return this.viewData[T].prop},MaskElement.prototype.renderFrame=function(T){var n=this.element.finalTransform.mat,P,R=this.masksProperties.length;for(P=0;P<R;P+=1)if((this.viewData[P].prop._mdf||T)&&this.drawPath(this.masksProperties[P],this.viewData[P].prop.v,this.viewData[P]),(this.viewData[P].op._mdf||T)&&this.viewData[P].elem.setAttribute("fill-opacity",this.viewData[P].op.v),this.masksProperties[P].mode!=="n"&&(this.viewData[P].invRect&&(this.element.finalTransform.mProp._mdf||T)&&this.viewData[P].invRect.setAttribute("transform",n.getInverseMatrix().to2dCSS()),this.storedData[P].x&&(this.storedData[P].x._mdf||T))){var A=this.storedData[P].expan;this.storedData[P].x.v<0?(this.storedData[P].lastOperator!=="erode"&&(this.storedData[P].lastOperator="erode",this.storedData[P].elem.setAttribute("filter","url("+getLocationHref()+"#"+this.storedData[P].filterId+")")),A.setAttribute("radius",-this.storedData[P].x.v)):(this.storedData[P].lastOperator!=="dilate"&&(this.storedData[P].lastOperator="dilate",this.storedData[P].elem.setAttribute("filter",null)),this.storedData[P].elem.setAttribute("stroke-width",this.storedData[P].x.v*2))}},MaskElement.prototype.getMaskelement=function(){return this.maskElement},MaskElement.prototype.createLayerSolidPath=function(){var T="M0,0 ";return T+=" h"+this.globalData.compSize.w,T+=" v"+this.globalData.compSize.h,T+=" h-"+this.globalData.compSize.w,T+=" v-"+this.globalData.compSize.h+" ",T},MaskElement.prototype.drawPath=function(T,n,P){var R=" M"+n.v[0][0]+","+n.v[0][1],A,L;for(L=n._length,A=1;A<L;A+=1)R+=" C"+n.o[A-1][0]+","+n.o[A-1][1]+" "+n.i[A][0]+","+n.i[A][1]+" "+n.v[A][0]+","+n.v[A][1];if(n.c&&L>1&&(R+=" C"+n.o[A-1][0]+","+n.o[A-1][1]+" "+n.i[0][0]+","+n.i[0][1]+" "+n.v[0][0]+","+n.v[0][1]),P.lastPath!==R){var O="";P.elem&&(n.c&&(O=T.inv?this.solidPath+R:R),P.elem.setAttribute("d",O)),P.lastPath=R}},MaskElement.prototype.destroy=function(){this.element=null,this.globalData=null,this.maskElement=null,this.data=null,this.masksProperties=null};var filtersFactory=(function(){var T={};T.createFilter=n,T.createAlphaToLuminanceFilter=P;function n(R,A){var L=createNS("filter");return L.setAttribute("id",R),A!==!0&&(L.setAttribute("filterUnits","objectBoundingBox"),L.setAttribute("x","0%"),L.setAttribute("y","0%"),L.setAttribute("width","100%"),L.setAttribute("height","100%")),L}function P(){var R=createNS("feColorMatrix");return R.setAttribute("type","matrix"),R.setAttribute("color-interpolation-filters","sRGB"),R.setAttribute("values","0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"),R}return T})(),featureSupport=(function(){var T={maskType:!0,svgLumaHidden:!0,offscreenCanvas:typeof OffscreenCanvas<"u"};return(/MSIE 10/i.test(navigator.userAgent)||/MSIE 9/i.test(navigator.userAgent)||/rv:11.0/i.test(navigator.userAgent)||/Edge\/\d./i.test(navigator.userAgent))&&(T.maskType=!1),/firefox/i.test(navigator.userAgent)&&(T.svgLumaHidden=!1),T})(),registeredEffects$1={},idPrefix="filter_result_";function SVGEffects(T){var n,P="SourceGraphic",R=T.data.ef?T.data.ef.length:0,A=createElementID(),L=filtersFactory.createFilter(A,!0),O=0;this.filters=[];var N;for(n=0;n<R;n+=1){N=null;var V=T.data.ef[n].ty;if(registeredEffects$1[V]){var j=registeredEffects$1[V].effect;N=new j(L,T.effectsManager.effectElements[n],T,idPrefix+O,P),P=idPrefix+O,registeredEffects$1[V].countsAsEffect&&(O+=1)}N&&this.filters.push(N)}O&&(T.globalData.defs.appendChild(L),T.layerElement.setAttribute("filter","url("+getLocationHref()+"#"+A+")")),this.filters.length&&T.addRenderableComponent(this)}SVGEffects.prototype.renderFrame=function(T){var n,P=this.filters.length;for(n=0;n<P;n+=1)this.filters[n].renderFrame(T)},SVGEffects.prototype.getEffects=function(T){var n,P=this.filters.length,R=[];for(n=0;n<P;n+=1)this.filters[n].type===T&&R.push(this.filters[n]);return R};function registerEffect$1(T,n,P){registeredEffects$1[T]={effect:n,countsAsEffect:P}}function SVGBaseElement(){}SVGBaseElement.prototype={initRendererElement:function(){this.layerElement=createNS("g")},createContainerElements:function(){this.matteElement=createNS("g"),this.transformedElement=this.layerElement,this.maskedElement=this.layerElement,this._sizeChanged=!1;var n=null;if(this.data.td){this.matteMasks={};var P=createNS("g");P.setAttribute("id",this.layerId),P.appendChild(this.layerElement),n=P,this.globalData.defs.appendChild(P)}else this.data.tt?(this.matteElement.appendChild(this.layerElement),n=this.matteElement,this.baseElement=this.matteElement):this.baseElement=this.layerElement;if(this.data.ln&&this.layerElement.setAttribute("id",this.data.ln),this.data.cl&&this.layerElement.setAttribute("class",this.data.cl),this.data.ty===0&&!this.data.hd){var R=createNS("clipPath"),A=createNS("path");A.setAttribute("d","M0,0 L"+this.data.w+",0 L"+this.data.w+","+this.data.h+" L0,"+this.data.h+"z");var L=createElementID();if(R.setAttribute("id",L),R.appendChild(A),this.globalData.defs.appendChild(R),this.checkMasks()){var O=createNS("g");O.setAttribute("clip-path","url("+getLocationHref()+"#"+L+")"),O.appendChild(this.layerElement),this.transformedElement=O,n?n.appendChild(this.transformedElement):this.baseElement=this.transformedElement}else this.layerElement.setAttribute("clip-path","url("+getLocationHref()+"#"+L+")")}this.data.bm!==0&&this.setBlendMode()},renderElement:function(){this.finalTransform._localMatMdf&&this.transformedElement.setAttribute("transform",this.finalTransform.localMat.to2dCSS()),this.finalTransform._opMdf&&this.transformedElement.setAttribute("opacity",this.finalTransform.localOpacity)},destroyBaseElement:function(){this.layerElement=null,this.matteElement=null,this.maskManager.destroy()},getBaseElement:function(){return this.data.hd?null:this.baseElement},createRenderableComponents:function(){this.maskManager=new MaskElement(this.data,this,this.globalData),this.renderableEffectsManager=new SVGEffects(this),this.searchEffectTransforms()},getMatte:function(n){if(this.matteMasks||(this.matteMasks={}),!this.matteMasks[n]){var P=this.layerId+"_"+n,R,A,L,O;if(n===1||n===3){var N=createNS("mask");N.setAttribute("id",P),N.setAttribute("mask-type",n===3?"luminance":"alpha"),L=createNS("use"),L.setAttributeNS("http://www.w3.org/1999/xlink","href","#"+this.layerId),N.appendChild(L),this.globalData.defs.appendChild(N),!featureSupport.maskType&&n===1&&(N.setAttribute("mask-type","luminance"),R=createElementID(),A=filtersFactory.createFilter(R),this.globalData.defs.appendChild(A),A.appendChild(filtersFactory.createAlphaToLuminanceFilter()),O=createNS("g"),O.appendChild(L),N.appendChild(O),O.setAttribute("filter","url("+getLocationHref()+"#"+R+")"))}else if(n===2){var V=createNS("mask");V.setAttribute("id",P),V.setAttribute("mask-type","alpha");var j=createNS("g");V.appendChild(j),R=createElementID(),A=filtersFactory.createFilter(R);var B=createNS("feComponentTransfer");B.setAttribute("in","SourceGraphic"),A.appendChild(B);var z=createNS("feFuncA");z.setAttribute("type","table"),z.setAttribute("tableValues","1.0 0.0"),B.appendChild(z),this.globalData.defs.appendChild(A);var W=createNS("rect");W.setAttribute("width",this.comp.data.w),W.setAttribute("height",this.comp.data.h),W.setAttribute("x","0"),W.setAttribute("y","0"),W.setAttribute("fill","#ffffff"),W.setAttribute("opacity","0"),j.setAttribute("filter","url("+getLocationHref()+"#"+R+")"),j.appendChild(W),L=createNS("use"),L.setAttributeNS("http://www.w3.org/1999/xlink","href","#"+this.layerId),j.appendChild(L),featureSupport.maskType||(V.setAttribute("mask-type","luminance"),A.appendChild(filtersFactory.createAlphaToLuminanceFilter()),O=createNS("g"),j.appendChild(W),O.appendChild(this.layerElement),j.appendChild(O)),this.globalData.defs.appendChild(V)}this.matteMasks[n]=P}return this.matteMasks[n]},setMatte:function(n){this.matteElement&&this.matteElement.setAttribute("mask","url("+getLocationHref()+"#"+n+")")}};function HierarchyElement(){}HierarchyElement.prototype={initHierarchy:function(){this.hierarchy=[],this._isParent=!1,this.checkParenting()},setHierarchy:function(n){this.hierarchy=n},setAsParent:function(){this._isParent=!0},checkParenting:function(){this.data.parent!==void 0&&this.comp.buildElementParenting(this,this.data.parent,[])}};function RenderableDOMElement(){}(function(){var T={initElement:function(P,R,A){this.initFrame(),this.initBaseData(P,R,A),this.initTransform(P,R,A),this.initHierarchy(),this.initRenderable(),this.initRendererElement(),this.createContainerElements(),this.createRenderableComponents(),this.createContent(),this.hide()},hide:function(){if(!this.hidden&&(!this.isInRange||this.isTransparent)){var P=this.baseElement||this.layerElement;P.style.display="none",this.hidden=!0}},show:function(){if(this.isInRange&&!this.isTransparent){if(!this.data.hd){var P=this.baseElement||this.layerElement;P.style.display="block"}this.hidden=!1,this._isFirstFrame=!0}},renderFrame:function(){this.data.hd||this.hidden||(this.renderTransform(),this.renderRenderable(),this.renderLocalTransform(),this.renderElement(),this.renderInnerContent(),this._isFirstFrame&&(this._isFirstFrame=!1))},renderInnerContent:function(){},prepareFrame:function(P){this._mdf=!1,this.prepareRenderableFrame(P),this.prepareProperties(P,this.isInRange),this.checkTransparency()},destroy:function(){this.innerElem=null,this.destroyBaseElement()}};extendPrototype([RenderableElement,createProxyFunction(T)],RenderableDOMElement)})();function IImageElement(T,n,P){this.assetData=n.getAssetData(T.refId),this.assetData&&this.assetData.sid&&(this.assetData=n.slotManager.getProp(this.assetData)),this.initElement(T,n,P),this.sourceRect={top:0,left:0,width:this.assetData.w,height:this.assetData.h}}extendPrototype([BaseElement,TransformElement,SVGBaseElement,HierarchyElement,FrameElement,RenderableDOMElement],IImageElement),IImageElement.prototype.createContent=function(){var T=this.globalData.getAssetsPath(this.assetData);this.innerElem=createNS("image"),this.innerElem.setAttribute("width",this.assetData.w+"px"),this.innerElem.setAttribute("height",this.assetData.h+"px"),this.innerElem.setAttribute("preserveAspectRatio",this.assetData.pr||this.globalData.renderConfig.imagePreserveAspectRatio),this.innerElem.setAttributeNS("http://www.w3.org/1999/xlink","href",T),this.layerElement.appendChild(this.innerElem)},IImageElement.prototype.sourceRectAtTime=function(){return this.sourceRect};function ProcessedElement(T,n){this.elem=T,this.pos=n}function IShapeElement(){}IShapeElement.prototype={addShapeToModifiers:function(n){var P,R=this.shapeModifiers.length;for(P=0;P<R;P+=1)this.shapeModifiers[P].addShape(n)},isShapeInAnimatedModifiers:function(n){for(var P=0,R=this.shapeModifiers.length;P<R;)if(this.shapeModifiers[P].isAnimatedWithShape(n))return!0;return!1},renderModifiers:function(){if(this.shapeModifiers.length){var n,P=this.shapes.length;for(n=0;n<P;n+=1)this.shapes[n].sh.reset();P=this.shapeModifiers.length;var R;for(n=P-1;n>=0&&(R=this.shapeModifiers[n].processShapes(this._isFirstFrame),!R);n-=1);}},searchProcessedElement:function(n){for(var P=this.processedElements,R=0,A=P.length;R<A;){if(P[R].elem===n)return P[R].pos;R+=1}return 0},addProcessedElement:function(n,P){for(var R=this.processedElements,A=R.length;A;)if(A-=1,R[A].elem===n){R[A].pos=P;return}R.push(new ProcessedElement(n,P))},prepareFrame:function(n){this.prepareRenderableFrame(n),this.prepareProperties(n,this.isInRange)}};var lineCapEnum={1:"butt",2:"round",3:"square"},lineJoinEnum={1:"miter",2:"round",3:"bevel"};function SVGShapeData(T,n,P){this.caches=[],this.styles=[],this.transformers=T,this.lStr="",this.sh=P,this.lvl=n,this._isAnimated=!!P.k;for(var R=0,A=T.length;R<A;){if(T[R].mProps.dynamicProperties.length){this._isAnimated=!0;break}R+=1}}SVGShapeData.prototype.setAsAnimated=function(){this._isAnimated=!0};function SVGStyleData(T,n){this.data=T,this.type=T.ty,this.d="",this.lvl=n,this._mdf=!1,this.closed=T.hd===!0,this.pElem=createNS("path"),this.msElem=null}SVGStyleData.prototype.reset=function(){this.d="",this._mdf=!1};function DashProperty(T,n,P,R){this.elem=T,this.frameId=-1,this.dataProps=createSizedArray(n.length),this.renderer=P,this.k=!1,this.dashStr="",this.dashArray=createTypedArray("float32",n.length?n.length-1:0),this.dashoffset=createTypedArray("float32",1),this.initDynamicPropertyContainer(R);var A,L=n.length||0,O;for(A=0;A<L;A+=1)O=PropertyFactory.getProp(T,n[A].v,0,0,this),this.k=O.k||this.k,this.dataProps[A]={n:n[A].n,p:O};this.k||this.getValue(!0),this._isAnimated=this.k}DashProperty.prototype.getValue=function(T){if(!(this.elem.globalData.frameId===this.frameId&&!T)&&(this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties(),this._mdf=this._mdf||T,this._mdf)){var n=0,P=this.dataProps.length;for(this.renderer==="svg"&&(this.dashStr=""),n=0;n<P;n+=1)this.dataProps[n].n!=="o"?this.renderer==="svg"?this.dashStr+=" "+this.dataProps[n].p.v:this.dashArray[n]=this.dataProps[n].p.v:this.dashoffset[0]=this.dataProps[n].p.v}},extendPrototype([DynamicPropertyContainer],DashProperty);function SVGStrokeStyleData(T,n,P){this.initDynamicPropertyContainer(T),this.getValue=this.iterateDynamicProperties,this.o=PropertyFactory.getProp(T,n.o,0,.01,this),this.w=PropertyFactory.getProp(T,n.w,0,null,this),this.d=new DashProperty(T,n.d||{},"svg",this),this.c=PropertyFactory.getProp(T,n.c,1,255,this),this.style=P,this._isAnimated=!!this._isAnimated}extendPrototype([DynamicPropertyContainer],SVGStrokeStyleData);function SVGFillStyleData(T,n,P){this.initDynamicPropertyContainer(T),this.getValue=this.iterateDynamicProperties,this.o=PropertyFactory.getProp(T,n.o,0,.01,this),this.c=PropertyFactory.getProp(T,n.c,1,255,this),this.style=P}extendPrototype([DynamicPropertyContainer],SVGFillStyleData);function SVGNoStyleData(T,n,P){this.initDynamicPropertyContainer(T),this.getValue=this.iterateDynamicProperties,this.style=P}extendPrototype([DynamicPropertyContainer],SVGNoStyleData);function GradientProperty(T,n,P){this.data=n,this.c=createTypedArray("uint8c",n.p*4);var R=n.k.k[0].s?n.k.k[0].s.length-n.p*4:n.k.k.length-n.p*4;this.o=createTypedArray("float32",R),this._cmdf=!1,this._omdf=!1,this._collapsable=this.checkCollapsable(),this._hasOpacity=R,this.initDynamicPropertyContainer(P),this.prop=PropertyFactory.getProp(T,n.k,1,null,this),this.k=this.prop.k,this.getValue(!0)}GradientProperty.prototype.comparePoints=function(T,n){for(var P=0,R=this.o.length/2,A;P<R;){if(A=Math.abs(T[P*4]-T[n*4+P*2]),A>.01)return!1;P+=1}return!0},GradientProperty.prototype.checkCollapsable=function(){if(this.o.length/2!==this.c.length/4)return!1;if(this.data.k.k[0].s)for(var T=0,n=this.data.k.k.length;T<n;){if(!this.comparePoints(this.data.k.k[T].s,this.data.p))return!1;T+=1}else if(!this.comparePoints(this.data.k.k,this.data.p))return!1;return!0},GradientProperty.prototype.getValue=function(T){if(this.prop.getValue(),this._mdf=!1,this._cmdf=!1,this._omdf=!1,this.prop._mdf||T){var n,P=this.data.p*4,R,A;for(n=0;n<P;n+=1)R=n%4===0?100:255,A=Math.round(this.prop.v[n]*R),this.c[n]!==A&&(this.c[n]=A,this._cmdf=!T);if(this.o.length)for(P=this.prop.v.length,n=this.data.p*4;n<P;n+=1)R=n%2===0?100:1,A=n%2===0?Math.round(this.prop.v[n]*100):this.prop.v[n],this.o[n-this.data.p*4]!==A&&(this.o[n-this.data.p*4]=A,this._omdf=!T);this._mdf=!T}},extendPrototype([DynamicPropertyContainer],GradientProperty);function SVGGradientFillStyleData(T,n,P){this.initDynamicPropertyContainer(T),this.getValue=this.iterateDynamicProperties,this.initGradientData(T,n,P)}SVGGradientFillStyleData.prototype.initGradientData=function(T,n,P){this.o=PropertyFactory.getProp(T,n.o,0,.01,this),this.s=PropertyFactory.getProp(T,n.s,1,null,this),this.e=PropertyFactory.getProp(T,n.e,1,null,this),this.h=PropertyFactory.getProp(T,n.h||{k:0},0,.01,this),this.a=PropertyFactory.getProp(T,n.a||{k:0},0,degToRads,this),this.g=new GradientProperty(T,n.g,this),this.style=P,this.stops=[],this.setGradientData(P.pElem,n),this.setGradientOpacity(n,P),this._isAnimated=!!this._isAnimated},SVGGradientFillStyleData.prototype.setGradientData=function(T,n){var P=createElementID(),R=createNS(n.t===1?"linearGradient":"radialGradient");R.setAttribute("id",P),R.setAttribute("spreadMethod","pad"),R.setAttribute("gradientUnits","userSpaceOnUse");var A=[],L,O,N;for(N=n.g.p*4,O=0;O<N;O+=4)L=createNS("stop"),R.appendChild(L),A.push(L);T.setAttribute(n.ty==="gf"?"fill":"stroke","url("+getLocationHref()+"#"+P+")"),this.gf=R,this.cst=A},SVGGradientFillStyleData.prototype.setGradientOpacity=function(T,n){if(this.g._hasOpacity&&!this.g._collapsable){var P,R,A,L=createNS("mask"),O=createNS("path");L.appendChild(O);var N=createElementID(),V=createElementID();L.setAttribute("id",V);var j=createNS(T.t===1?"linearGradient":"radialGradient");j.setAttribute("id",N),j.setAttribute("spreadMethod","pad"),j.setAttribute("gradientUnits","userSpaceOnUse"),A=T.g.k.k[0].s?T.g.k.k[0].s.length:T.g.k.k.length;var B=this.stops;for(R=T.g.p*4;R<A;R+=2)P=createNS("stop"),P.setAttribute("stop-color","rgb(255,255,255)"),j.appendChild(P),B.push(P);O.setAttribute(T.ty==="gf"?"fill":"stroke","url("+getLocationHref()+"#"+N+")"),T.ty==="gs"&&(O.setAttribute("stroke-linecap",lineCapEnum[T.lc||2]),O.setAttribute("stroke-linejoin",lineJoinEnum[T.lj||2]),T.lj===1&&O.setAttribute("stroke-miterlimit",T.ml)),this.of=j,this.ms=L,this.ost=B,this.maskId=V,n.msElem=O}},extendPrototype([DynamicPropertyContainer],SVGGradientFillStyleData);function SVGGradientStrokeStyleData(T,n,P){this.initDynamicPropertyContainer(T),this.getValue=this.iterateDynamicProperties,this.w=PropertyFactory.getProp(T,n.w,0,null,this),this.d=new DashProperty(T,n.d||{},"svg",this),this.initGradientData(T,n,P),this._isAnimated=!!this._isAnimated}extendPrototype([SVGGradientFillStyleData,DynamicPropertyContainer],SVGGradientStrokeStyleData);function ShapeGroupData(){this.it=[],this.prevViewData=[],this.gr=createNS("g")}function SVGTransformData(T,n,P){this.transform={mProps:T,op:n,container:P},this.elements=[],this._isAnimated=this.transform.mProps.dynamicProperties.length||this.transform.op.effectsSequence.length}var buildShapeString=function(n,P,R,A){if(P===0)return"";var L=n.o,O=n.i,N=n.v,V,j=" M"+A.applyToPointStringified(N[0][0],N[0][1]);for(V=1;V<P;V+=1)j+=" C"+A.applyToPointStringified(L[V-1][0],L[V-1][1])+" "+A.applyToPointStringified(O[V][0],O[V][1])+" "+A.applyToPointStringified(N[V][0],N[V][1]);return R&&P&&(j+=" C"+A.applyToPointStringified(L[V-1][0],L[V-1][1])+" "+A.applyToPointStringified(O[0][0],O[0][1])+" "+A.applyToPointStringified(N[0][0],N[0][1]),j+="z"),j},SVGElementsRenderer=(function(){var T=new Matrix,n=new Matrix,P={createRenderFunction:R};function R(z){switch(z.ty){case"fl":return N;case"gf":return j;case"gs":return V;case"st":return B;case"sh":case"el":case"rc":case"sr":return O;case"tr":return A;case"no":return L;default:return null}}function A(z,W,q){(q||W.transform.op._mdf)&&W.transform.container.setAttribute("opacity",W.transform.op.v),(q||W.transform.mProps._mdf)&&W.transform.container.setAttribute("transform",W.transform.mProps.v.to2dCSS())}function L(){}function O(z,W,q){var H,$,Q,U,J,G,K=W.styles.length,Y=W.lvl,Z,ie,se,le;for(G=0;G<K;G+=1){if(U=W.sh._mdf||q,W.styles[G].lvl<Y){for(ie=n.reset(),se=Y-W.styles[G].lvl,le=W.transformers.length-1;!U&&se>0;)U=W.transformers[le].mProps._mdf||U,se-=1,le-=1;if(U)for(se=Y-W.styles[G].lvl,le=W.transformers.length-1;se>0;)ie.multiply(W.transformers[le].mProps.v),se-=1,le-=1}else ie=T;if(Z=W.sh.paths,$=Z._length,U){for(Q="",H=0;H<$;H+=1)J=Z.shapes[H],J&&J._length&&(Q+=buildShapeString(J,J._length,J.c,ie));W.caches[G]=Q}else Q=W.caches[G];W.styles[G].d+=z.hd===!0?"":Q,W.styles[G]._mdf=U||W.styles[G]._mdf}}function N(z,W,q){var H=W.style;(W.c._mdf||q)&&H.pElem.setAttribute("fill","rgb("+bmFloor(W.c.v[0])+","+bmFloor(W.c.v[1])+","+bmFloor(W.c.v[2])+")"),(W.o._mdf||q)&&H.pElem.setAttribute("fill-opacity",W.o.v)}function V(z,W,q){j(z,W,q),B(z,W,q)}function j(z,W,q){var H=W.gf,$=W.g._hasOpacity,Q=W.s.v,U=W.e.v;if(W.o._mdf||q){var J=z.ty==="gf"?"fill-opacity":"stroke-opacity";W.style.pElem.setAttribute(J,W.o.v)}if(W.s._mdf||q){var G=z.t===1?"x1":"cx",K=G==="x1"?"y1":"cy";H.setAttribute(G,Q[0]),H.setAttribute(K,Q[1]),$&&!W.g._collapsable&&(W.of.setAttribute(G,Q[0]),W.of.setAttribute(K,Q[1]))}var Y,Z,ie,se;if(W.g._cmdf||q){Y=W.cst;var le=W.g.c;for(ie=Y.length,Z=0;Z<ie;Z+=1)se=Y[Z],se.setAttribute("offset",le[Z*4]+"%"),se.setAttribute("stop-color","rgb("+le[Z*4+1]+","+le[Z*4+2]+","+le[Z*4+3]+")")}if($&&(W.g._omdf||q)){var pe=W.g.o;for(W.g._collapsable?Y=W.cst:Y=W.ost,ie=Y.length,Z=0;Z<ie;Z+=1)se=Y[Z],W.g._collapsable||se.setAttribute("offset",pe[Z*2]+"%"),se.setAttribute("stop-opacity",pe[Z*2+1])}if(z.t===1)(W.e._mdf||q)&&(H.setAttribute("x2",U[0]),H.setAttribute("y2",U[1]),$&&!W.g._collapsable&&(W.of.setAttribute("x2",U[0]),W.of.setAttribute("y2",U[1])));else{var ue;if((W.s._mdf||W.e._mdf||q)&&(ue=Math.sqrt(Math.pow(Q[0]-U[0],2)+Math.pow(Q[1]-U[1],2)),H.setAttribute("r",ue),$&&!W.g._collapsable&&W.of.setAttribute("r",ue)),W.s._mdf||W.e._mdf||W.h._mdf||W.a._mdf||q){ue||(ue=Math.sqrt(Math.pow(Q[0]-U[0],2)+Math.pow(Q[1]-U[1],2)));var he=Math.atan2(U[1]-Q[1],U[0]-Q[0]),ve=W.h.v;ve>=1?ve=.99:ve<=-1&&(ve=-.99);var be=ue*ve,fe=Math.cos(he+W.a.v)*be+Q[0],ne=Math.sin(he+W.a.v)*be+Q[1];H.setAttribute("fx",fe),H.setAttribute("fy",ne),$&&!W.g._collapsable&&(W.of.setAttribute("fx",fe),W.of.setAttribute("fy",ne))}}}function B(z,W,q){var H=W.style,$=W.d;$&&($._mdf||q)&&$.dashStr&&(H.pElem.setAttribute("stroke-dasharray",$.dashStr),H.pElem.setAttribute("stroke-dashoffset",$.dashoffset[0])),W.c&&(W.c._mdf||q)&&H.pElem.setAttribute("stroke","rgb("+bmFloor(W.c.v[0])+","+bmFloor(W.c.v[1])+","+bmFloor(W.c.v[2])+")"),(W.o._mdf||q)&&H.pElem.setAttribute("stroke-opacity",W.o.v),(W.w._mdf||q)&&(H.pElem.setAttribute("stroke-width",W.w.v),H.msElem&&H.msElem.setAttribute("stroke-width",W.w.v))}return P})();function SVGShapeElement(T,n,P){this.shapes=[],this.shapesData=T.shapes,this.stylesList=[],this.shapeModifiers=[],this.itemsData=[],this.processedElements=[],this.animatedContents=[],this.initElement(T,n,P),this.prevViewData=[]}extendPrototype([BaseElement,TransformElement,SVGBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableDOMElement],SVGShapeElement),SVGShapeElement.prototype.initSecondaryElement=function(){},SVGShapeElement.prototype.identityMatrix=new Matrix,SVGShapeElement.prototype.buildExpressionInterface=function(){},SVGShapeElement.prototype.createContent=function(){this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement,0,[],!0),this.filterUniqueShapes()},SVGShapeElement.prototype.filterUniqueShapes=function(){var T,n=this.shapes.length,P,R,A=this.stylesList.length,L,O=[],N=!1;for(R=0;R<A;R+=1){for(L=this.stylesList[R],N=!1,O.length=0,T=0;T<n;T+=1)P=this.shapes[T],P.styles.indexOf(L)!==-1&&(O.push(P),N=P._isAnimated||N);O.length>1&&N&&this.setShapesAsAnimated(O)}},SVGShapeElement.prototype.setShapesAsAnimated=function(T){var n,P=T.length;for(n=0;n<P;n+=1)T[n].setAsAnimated()},SVGShapeElement.prototype.createStyleElement=function(T,n){var P,R=new SVGStyleData(T,n),A=R.pElem;if(T.ty==="st")P=new SVGStrokeStyleData(this,T,R);else if(T.ty==="fl")P=new SVGFillStyleData(this,T,R);else if(T.ty==="gf"||T.ty==="gs"){var L=T.ty==="gf"?SVGGradientFillStyleData:SVGGradientStrokeStyleData;P=new L(this,T,R),this.globalData.defs.appendChild(P.gf),P.maskId&&(this.globalData.defs.appendChild(P.ms),this.globalData.defs.appendChild(P.of),A.setAttribute("mask","url("+getLocationHref()+"#"+P.maskId+")"))}else T.ty==="no"&&(P=new SVGNoStyleData(this,T,R));return(T.ty==="st"||T.ty==="gs")&&(A.setAttribute("stroke-linecap",lineCapEnum[T.lc||2]),A.setAttribute("stroke-linejoin",lineJoinEnum[T.lj||2]),A.setAttribute("fill-opacity","0"),T.lj===1&&A.setAttribute("stroke-miterlimit",T.ml)),T.r===2&&A.setAttribute("fill-rule","evenodd"),T.ln&&A.setAttribute("id",T.ln),T.cl&&A.setAttribute("class",T.cl),T.bm&&(A.style["mix-blend-mode"]=getBlendMode(T.bm)),this.stylesList.push(R),this.addToAnimatedContents(T,P),P},SVGShapeElement.prototype.createGroupElement=function(T){var n=new ShapeGroupData;return T.ln&&n.gr.setAttribute("id",T.ln),T.cl&&n.gr.setAttribute("class",T.cl),T.bm&&(n.gr.style["mix-blend-mode"]=getBlendMode(T.bm)),n},SVGShapeElement.prototype.createTransformElement=function(T,n){var P=TransformPropertyFactory.getTransformProperty(this,T,this),R=new SVGTransformData(P,P.o,n);return this.addToAnimatedContents(T,R),R},SVGShapeElement.prototype.createShapeElement=function(T,n,P){var R=4;T.ty==="rc"?R=5:T.ty==="el"?R=6:T.ty==="sr"&&(R=7);var A=ShapePropertyFactory.getShapeProp(this,T,R,this),L=new SVGShapeData(n,P,A);return this.shapes.push(L),this.addShapeToModifiers(L),this.addToAnimatedContents(T,L),L},SVGShapeElement.prototype.addToAnimatedContents=function(T,n){for(var P=0,R=this.animatedContents.length;P<R;){if(this.animatedContents[P].element===n)return;P+=1}this.animatedContents.push({fn:SVGElementsRenderer.createRenderFunction(T),element:n,data:T})},SVGShapeElement.prototype.setElementStyles=function(T){var n=T.styles,P,R=this.stylesList.length;for(P=0;P<R;P+=1)n.indexOf(this.stylesList[P])===-1&&!this.stylesList[P].closed&&n.push(this.stylesList[P])},SVGShapeElement.prototype.reloadShapes=function(){this._isFirstFrame=!0;var T,n=this.itemsData.length;for(T=0;T<n;T+=1)this.prevViewData[T]=this.itemsData[T];for(this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement,0,[],!0),this.filterUniqueShapes(),n=this.dynamicProperties.length,T=0;T<n;T+=1)this.dynamicProperties[T].getValue();this.renderModifiers()},SVGShapeElement.prototype.searchShapes=function(T,n,P,R,A,L,O){var N=[].concat(L),V,j=T.length-1,B,z,W=[],q=[],H,$,Q;for(V=j;V>=0;V-=1){if(Q=this.searchProcessedElement(T[V]),Q?n[V]=P[Q-1]:T[V]._render=O,T[V].ty==="fl"||T[V].ty==="st"||T[V].ty==="gf"||T[V].ty==="gs"||T[V].ty==="no")Q?n[V].style.closed=T[V].hd:n[V]=this.createStyleElement(T[V],A),T[V]._render&&n[V].style.pElem.parentNode!==R&&R.appendChild(n[V].style.pElem),W.push(n[V].style);else if(T[V].ty==="gr"){if(!Q)n[V]=this.createGroupElement(T[V]);else for(z=n[V].it.length,B=0;B<z;B+=1)n[V].prevViewData[B]=n[V].it[B];this.searchShapes(T[V].it,n[V].it,n[V].prevViewData,n[V].gr,A+1,N,O),T[V]._render&&n[V].gr.parentNode!==R&&R.appendChild(n[V].gr)}else T[V].ty==="tr"?(Q||(n[V]=this.createTransformElement(T[V],R)),H=n[V].transform,N.push(H)):T[V].ty==="sh"||T[V].ty==="rc"||T[V].ty==="el"||T[V].ty==="sr"?(Q||(n[V]=this.createShapeElement(T[V],N,A)),this.setElementStyles(n[V])):T[V].ty==="tm"||T[V].ty==="rd"||T[V].ty==="ms"||T[V].ty==="pb"||T[V].ty==="zz"||T[V].ty==="op"?(Q?($=n[V],$.closed=!1):($=ShapeModifiers.getModifier(T[V].ty),$.init(this,T[V]),n[V]=$,this.shapeModifiers.push($)),q.push($)):T[V].ty==="rp"&&(Q?($=n[V],$.closed=!0):($=ShapeModifiers.getModifier(T[V].ty),n[V]=$,$.init(this,T,V,n),this.shapeModifiers.push($),O=!1),q.push($));this.addProcessedElement(T[V],V+1)}for(j=W.length,V=0;V<j;V+=1)W[V].closed=!0;for(j=q.length,V=0;V<j;V+=1)q[V].closed=!0},SVGShapeElement.prototype.renderInnerContent=function(){this.renderModifiers();var T,n=this.stylesList.length;for(T=0;T<n;T+=1)this.stylesList[T].reset();for(this.renderShape(),T=0;T<n;T+=1)(this.stylesList[T]._mdf||this._isFirstFrame)&&(this.stylesList[T].msElem&&(this.stylesList[T].msElem.setAttribute("d",this.stylesList[T].d),this.stylesList[T].d="M0 0"+this.stylesList[T].d),this.stylesList[T].pElem.setAttribute("d",this.stylesList[T].d||"M0 0"))},SVGShapeElement.prototype.renderShape=function(){var T,n=this.animatedContents.length,P;for(T=0;T<n;T+=1)P=this.animatedContents[T],(this._isFirstFrame||P.element._isAnimated)&&P.data!==!0&&P.fn(P.data,P.element,this._isFirstFrame)},SVGShapeElement.prototype.destroy=function(){this.destroyBaseElement(),this.shapesData=null,this.itemsData=null};function LetterProps(T,n,P,R,A,L){this.o=T,this.sw=n,this.sc=P,this.fc=R,this.m=A,this.p=L,this._mdf={o:!0,sw:!!n,sc:!!P,fc:!!R,m:!0,p:!0}}LetterProps.prototype.update=function(T,n,P,R,A,L){this._mdf.o=!1,this._mdf.sw=!1,this._mdf.sc=!1,this._mdf.fc=!1,this._mdf.m=!1,this._mdf.p=!1;var O=!1;return this.o!==T&&(this.o=T,this._mdf.o=!0,O=!0),this.sw!==n&&(this.sw=n,this._mdf.sw=!0,O=!0),this.sc!==P&&(this.sc=P,this._mdf.sc=!0,O=!0),this.fc!==R&&(this.fc=R,this._mdf.fc=!0,O=!0),this.m!==A&&(this.m=A,this._mdf.m=!0,O=!0),L.length&&(this.p[0]!==L[0]||this.p[1]!==L[1]||this.p[4]!==L[4]||this.p[5]!==L[5]||this.p[12]!==L[12]||this.p[13]!==L[13])&&(this.p=L,this._mdf.p=!0,O=!0),O};function TextProperty(T,n){this._frameId=initialDefaultFrame,this.pv="",this.v="",this.kf=!1,this._isFirstFrame=!0,this._mdf=!1,n.d&&n.d.sid&&(n.d=T.globalData.slotManager.getProp(n.d)),this.data=n,this.elem=T,this.comp=this.elem.comp,this.keysIndex=0,this.canResize=!1,this.minimumFontSize=1,this.effectsSequence=[],this.currentData={ascent:0,boxWidth:this.defaultBoxWidth,f:"",fStyle:"",fWeight:"",fc:"",j:"",justifyOffset:"",l:[],lh:0,lineWidths:[],ls:"",of:"",s:"",sc:"",sw:0,t:0,tr:0,sz:0,ps:null,fillColorAnim:!1,strokeColorAnim:!1,strokeWidthAnim:!1,yOffset:0,finalSize:0,finalText:[],finalLineHeight:0,__complete:!1},this.copyData(this.currentData,this.data.d.k[0].s),this.searchProperty()||this.completeTextData(this.currentData)}TextProperty.prototype.defaultBoxWidth=[0,0],TextProperty.prototype.copyData=function(T,n){for(var P in n)Object.prototype.hasOwnProperty.call(n,P)&&(T[P]=n[P]);return T},TextProperty.prototype.setCurrentData=function(T){T.__complete||this.completeTextData(T),this.currentData=T,this.currentData.boxWidth=this.currentData.boxWidth||this.defaultBoxWidth,this._mdf=!0},TextProperty.prototype.searchProperty=function(){return this.searchKeyframes()},TextProperty.prototype.searchKeyframes=function(){return this.kf=this.data.d.k.length>1,this.kf&&this.addEffect(this.getKeyframeValue.bind(this)),this.kf},TextProperty.prototype.addEffect=function(T){this.effectsSequence.push(T),this.elem.addDynamicProperty(this)},TextProperty.prototype.getValue=function(T){if(!((this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)&&!T)){this.currentData.t=this.data.d.k[this.keysIndex].s.t;var n=this.currentData,P=this.keysIndex;if(this.lock){this.setCurrentData(this.currentData);return}this.lock=!0,this._mdf=!1;var R,A=this.effectsSequence.length,L=T||this.data.d.k[this.keysIndex].s;for(R=0;R<A;R+=1)P!==this.keysIndex?L=this.effectsSequence[R](L,L.t):L=this.effectsSequence[R](this.currentData,L.t);n!==L&&this.setCurrentData(L),this.v=this.currentData,this.pv=this.v,this.lock=!1,this.frameId=this.elem.globalData.frameId}},TextProperty.prototype.getKeyframeValue=function(){for(var T=this.data.d.k,n=this.elem.comp.renderedFrame,P=0,R=T.length;P<=R-1&&!(P===R-1||T[P+1].t>n);)P+=1;return this.keysIndex!==P&&(this.keysIndex=P),this.data.d.k[this.keysIndex].s},TextProperty.prototype.buildFinalText=function(T){for(var n=[],P=0,R=T.length,A,L,O=!1,N=!1,V="";P<R;)O=N,N=!1,A=T.charCodeAt(P),V=T.charAt(P),FontManager.isCombinedCharacter(A)?O=!0:A>=55296&&A<=56319?FontManager.isRegionalFlag(T,P)?V=T.substr(P,14):(L=T.charCodeAt(P+1),L>=56320&&L<=57343&&(FontManager.isModifier(A,L)?(V=T.substr(P,2),O=!0):FontManager.isFlagEmoji(T.substr(P,4))?V=T.substr(P,4):V=T.substr(P,2))):A>56319?(L=T.charCodeAt(P+1),FontManager.isVariationSelector(A)&&(O=!0)):FontManager.isZeroWidthJoiner(A)&&(O=!0,N=!0),O?(n[n.length-1]+=V,O=!1):n.push(V),P+=V.length;return n},TextProperty.prototype.completeTextData=function(T){T.__complete=!0;var n=this.elem.globalData.fontManager,P=this.data,R=[],A,L,O,N=0,V,j=P.m.g,B=0,z=0,W=0,q=[],H=0,$=0,Q,U,J=n.getFontByName(T.f),G,K=0,Y=getFontProperties(J);T.fWeight=Y.weight,T.fStyle=Y.style,T.finalSize=T.s,T.finalText=this.buildFinalText(T.t),L=T.finalText.length,T.finalLineHeight=T.lh;var Z=T.tr/1e3*T.finalSize,ie;if(T.sz)for(var se=!0,le=T.sz[0],pe=T.sz[1],ue,he;se;){he=this.buildFinalText(T.t),ue=0,H=0,L=he.length,Z=T.tr/1e3*T.finalSize;var ve=-1;for(A=0;A<L;A+=1)ie=he[A].charCodeAt(0),O=!1,he[A]===" "?ve=A:(ie===13||ie===3)&&(H=0,O=!0,ue+=T.finalLineHeight||T.finalSize*1.2),n.chars?(G=n.getCharData(he[A],J.fStyle,J.fFamily),K=O?0:G.w*T.finalSize/100):K=n.measureText(he[A],T.f,T.finalSize),H+K>le&&he[A]!==" "?(ve===-1?L+=1:A=ve,ue+=T.finalLineHeight||T.finalSize*1.2,he.splice(A,ve===A?1:0,"\r"),ve=-1,H=0):(H+=K,H+=Z);ue+=J.ascent*T.finalSize/100,this.canResize&&T.finalSize>this.minimumFontSize&&pe<ue?(T.finalSize-=1,T.finalLineHeight=T.finalSize*T.lh/T.s):(T.finalText=he,L=T.finalText.length,se=!1)}H=-Z,K=0;var be=0,fe;for(A=0;A<L;A+=1)if(O=!1,fe=T.finalText[A],ie=fe.charCodeAt(0),ie===13||ie===3?(be=0,q.push(H),$=H>$?H:$,H=-2*Z,V="",O=!0,W+=1):V=fe,n.chars?(G=n.getCharData(fe,J.fStyle,n.getFontByName(T.f).fFamily),K=O?0:G.w*T.finalSize/100):K=n.measureText(V,T.f,T.finalSize),fe===" "?be+=K+Z:(H+=K+Z+be,be=0),R.push({l:K,an:K,add:B,n:O,anIndexes:[],val:V,line:W,animatorJustifyOffset:0}),j==2){if(B+=K,V===""||V===" "||A===L-1){for((V===""||V===" ")&&(B-=K);z<=A;)R[z].an=B,R[z].ind=N,R[z].extra=K,z+=1;N+=1,B=0}}else if(j==3){if(B+=K,V===""||A===L-1){for(V===""&&(B-=K);z<=A;)R[z].an=B,R[z].ind=N,R[z].extra=K,z+=1;B=0,N+=1}}else R[N].ind=N,R[N].extra=0,N+=1;if(T.l=R,$=H>$?H:$,q.push(H),T.sz)T.boxWidth=T.sz[0],T.justifyOffset=0;else switch(T.boxWidth=$,T.j){case 1:T.justifyOffset=-T.boxWidth;break;case 2:T.justifyOffset=-T.boxWidth/2;break;default:T.justifyOffset=0}T.lineWidths=q;var ne=P.a,ce,ee;U=ne.length;var te,oe,ae=[];for(Q=0;Q<U;Q+=1){for(ce=ne[Q],ce.a.sc&&(T.strokeColorAnim=!0),ce.a.sw&&(T.strokeWidthAnim=!0),(ce.a.fc||ce.a.fh||ce.a.fs||ce.a.fb)&&(T.fillColorAnim=!0),oe=0,te=ce.s.b,A=0;A<L;A+=1)ee=R[A],ee.anIndexes[Q]=oe,(te==1&&ee.val!==""||te==2&&ee.val!==""&&ee.val!==" "||te==3&&(ee.n||ee.val==" "||A==L-1)||te==4&&(ee.n||A==L-1))&&(ce.s.rn===1&&ae.push(oe),oe+=1);P.a[Q].s.totalChars=oe;var de=-1,ge;if(ce.s.rn===1)for(A=0;A<L;A+=1)ee=R[A],de!=ee.anIndexes[Q]&&(de=ee.anIndexes[Q],ge=ae.splice(Math.floor(Math.random()*ae.length),1)[0]),ee.anIndexes[Q]=ge}T.yOffset=T.finalLineHeight||T.finalSize*1.2,T.ls=T.ls||0,T.ascent=J.ascent*T.finalSize/100},TextProperty.prototype.updateDocumentData=function(T,n){n=n===void 0?this.keysIndex:n;var P=this.copyData({},this.data.d.k[n].s);P=this.copyData(P,T),this.data.d.k[n].s=P,this.recalculate(n),this.setCurrentData(P),this.elem.addDynamicProperty(this)},TextProperty.prototype.recalculate=function(T){var n=this.data.d.k[T].s;n.__complete=!1,this.keysIndex=0,this._isFirstFrame=!0,this.getValue(n)},TextProperty.prototype.canResizeFont=function(T){this.canResize=T,this.recalculate(this.keysIndex),this.elem.addDynamicProperty(this)},TextProperty.prototype.setMinimumFontSize=function(T){this.minimumFontSize=Math.floor(T)||1,this.recalculate(this.keysIndex),this.elem.addDynamicProperty(this)};var TextSelectorProp=(function(){var T=Math.max,n=Math.min,P=Math.floor;function R(L,O){this._currentTextLength=-1,this.k=!1,this.data=O,this.elem=L,this.comp=L.comp,this.finalS=0,this.finalE=0,this.initDynamicPropertyContainer(L),this.s=PropertyFactory.getProp(L,O.s||{k:0},0,0,this),"e"in O?this.e=PropertyFactory.getProp(L,O.e,0,0,this):this.e={v:100},this.o=PropertyFactory.getProp(L,O.o||{k:0},0,0,this),this.xe=PropertyFactory.getProp(L,O.xe||{k:0},0,0,this),this.ne=PropertyFactory.getProp(L,O.ne||{k:0},0,0,this),this.sm=PropertyFactory.getProp(L,O.sm||{k:100},0,0,this),this.a=PropertyFactory.getProp(L,O.a,0,.01,this),this.dynamicProperties.length||this.getValue()}R.prototype={getMult:function(O){this._currentTextLength!==this.elem.textProperty.currentData.l.length&&this.getValue();var N=0,V=0,j=1,B=1;this.ne.v>0?N=this.ne.v/100:V=-this.ne.v/100,this.xe.v>0?j=1-this.xe.v/100:B=1+this.xe.v/100;var z=BezierFactory.getBezierEasing(N,V,j,B).get,W=0,q=this.finalS,H=this.finalE,$=this.data.sh;if($===2)H===q?W=O>=H?1:0:W=T(0,n(.5/(H-q)+(O-q)/(H-q),1)),W=z(W);else if($===3)H===q?W=O>=H?0:1:W=1-T(0,n(.5/(H-q)+(O-q)/(H-q),1)),W=z(W);else if($===4)H===q?W=0:(W=T(0,n(.5/(H-q)+(O-q)/(H-q),1)),W<.5?W*=2:W=1-2*(W-.5)),W=z(W);else if($===5){if(H===q)W=0;else{var Q=H-q;O=n(T(0,O+.5-q),H-q);var U=-Q/2+O,J=Q/2;W=Math.sqrt(1-U*U/(J*J))}W=z(W)}else $===6?(H===q?W=0:(O=n(T(0,O+.5-q),H-q),W=(1+Math.cos(Math.PI+Math.PI*2*O/(H-q)))/2),W=z(W)):(O>=P(q)&&(O-q<0?W=T(0,n(n(H,1)-(q-O),1)):W=T(0,n(H-O,1))),W=z(W));if(this.sm.v!==100){var G=this.sm.v*.01;G===0&&(G=1e-8);var K=.5-G*.5;W<K?W=0:(W=(W-K)/G,W>1&&(W=1))}return W*this.a.v},getValue:function(O){this.iterateDynamicProperties(),this._mdf=O||this._mdf,this._currentTextLength=this.elem.textProperty.currentData.l.length||0,O&&this.data.r===2&&(this.e.v=this._currentTextLength);var N=this.data.r===2?1:100/this.data.totalChars,V=this.o.v/N,j=this.s.v/N+V,B=this.e.v/N+V;if(j>B){var z=j;j=B,B=z}this.finalS=j,this.finalE=B}},extendPrototype([DynamicPropertyContainer],R);function A(L,O,N){return new R(L,O)}return{getTextSelectorProp:A}})();function TextAnimatorDataProperty(T,n,P){var R={propType:!1},A=PropertyFactory.getProp,L=n.a;this.a={r:L.r?A(T,L.r,0,degToRads,P):R,rx:L.rx?A(T,L.rx,0,degToRads,P):R,ry:L.ry?A(T,L.ry,0,degToRads,P):R,sk:L.sk?A(T,L.sk,0,degToRads,P):R,sa:L.sa?A(T,L.sa,0,degToRads,P):R,s:L.s?A(T,L.s,1,.01,P):R,a:L.a?A(T,L.a,1,0,P):R,o:L.o?A(T,L.o,0,.01,P):R,p:L.p?A(T,L.p,1,0,P):R,sw:L.sw?A(T,L.sw,0,0,P):R,sc:L.sc?A(T,L.sc,1,0,P):R,fc:L.fc?A(T,L.fc,1,0,P):R,fh:L.fh?A(T,L.fh,0,0,P):R,fs:L.fs?A(T,L.fs,0,.01,P):R,fb:L.fb?A(T,L.fb,0,.01,P):R,t:L.t?A(T,L.t,0,0,P):R},this.s=TextSelectorProp.getTextSelectorProp(T,n.s,P),this.s.t=n.s.t}function TextAnimatorProperty(T,n,P){this._isFirstFrame=!0,this._hasMaskedPath=!1,this._frameId=-1,this._textData=T,this._renderType=n,this._elem=P,this._animatorsData=createSizedArray(this._textData.a.length),this._pathData={},this._moreOptions={alignment:{}},this.renderedLetters=[],this.lettersChangedFlag=!1,this.initDynamicPropertyContainer(P)}TextAnimatorProperty.prototype.searchProperties=function(){var T,n=this._textData.a.length,P,R=PropertyFactory.getProp;for(T=0;T<n;T+=1)P=this._textData.a[T],this._animatorsData[T]=new TextAnimatorDataProperty(this._elem,P,this);this._textData.p&&"m"in this._textData.p?(this._pathData={a:R(this._elem,this._textData.p.a,0,0,this),f:R(this._elem,this._textData.p.f,0,0,this),l:R(this._elem,this._textData.p.l,0,0,this),r:R(this._elem,this._textData.p.r,0,0,this),p:R(this._elem,this._textData.p.p,0,0,this),m:this._elem.maskManager.getMaskProperty(this._textData.p.m)},this._hasMaskedPath=!0):this._hasMaskedPath=!1,this._moreOptions.alignment=R(this._elem,this._textData.m.a,1,0,this)},TextAnimatorProperty.prototype.getMeasures=function(T,n){if(this.lettersChangedFlag=n,!(!this._mdf&&!this._isFirstFrame&&!n&&(!this._hasMaskedPath||!this._pathData.m._mdf))){this._isFirstFrame=!1;var P=this._moreOptions.alignment.v,R=this._animatorsData,A=this._textData,L=this.mHelper,O=this._renderType,N=this.renderedLetters.length,V,j,B,z,W=T.l,q,H,$,Q,U,J,G,K,Y,Z,ie,se,le,pe,ue;if(this._hasMaskedPath){if(ue=this._pathData.m,!this._pathData.n||this._pathData._mdf){var he=ue.v;this._pathData.r.v&&(he=he.reverse()),q={tLength:0,segments:[]},z=he._length-1;var ve;for(se=0,B=0;B<z;B+=1)ve=bez.buildBezierData(he.v[B],he.v[B+1],[he.o[B][0]-he.v[B][0],he.o[B][1]-he.v[B][1]],[he.i[B+1][0]-he.v[B+1][0],he.i[B+1][1]-he.v[B+1][1]]),q.tLength+=ve.segmentLength,q.segments.push(ve),se+=ve.segmentLength;B=z,ue.v.c&&(ve=bez.buildBezierData(he.v[B],he.v[0],[he.o[B][0]-he.v[B][0],he.o[B][1]-he.v[B][1]],[he.i[0][0]-he.v[0][0],he.i[0][1]-he.v[0][1]]),q.tLength+=ve.segmentLength,q.segments.push(ve),se+=ve.segmentLength),this._pathData.pi=q}if(q=this._pathData.pi,H=this._pathData.f.v,G=0,J=1,Q=0,U=!0,Z=q.segments,H<0&&ue.v.c)for(q.tLength<Math.abs(H)&&(H=-Math.abs(H)%q.tLength),G=Z.length-1,Y=Z[G].points,J=Y.length-1;H<0;)H+=Y[J].partialLength,J-=1,J<0&&(G-=1,Y=Z[G].points,J=Y.length-1);Y=Z[G].points,K=Y[J-1],$=Y[J],ie=$.partialLength}z=W.length,V=0,j=0;var be=T.finalSize*1.2*.714,fe=!0,ne,ce,ee,te,oe;te=R.length;var ae,de=-1,ge,ye,Ee,Pe=H,Ie=G,Ae=J,Le=-1,Me,ke,Ce,xe,we,Oe,De,We,Fe="",qe=this.defaultPropsArray,Ne;if(T.j===2||T.j===1){var je=0,Ye=0,Xe=T.j===2?-.5:-1,ze=0,Qe=!0;for(B=0;B<z;B+=1)if(W[B].n){for(je&&(je+=Ye);ze<B;)W[ze].animatorJustifyOffset=je,ze+=1;je=0,Qe=!0}else{for(ee=0;ee<te;ee+=1)ne=R[ee].a,ne.t.propType&&(Qe&&T.j===2&&(Ye+=ne.t.v*Xe),ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),ae.length?je+=ne.t.v*ae[0]*Xe:je+=ne.t.v*ae*Xe);Qe=!1}for(je&&(je+=Ye);ze<B;)W[ze].animatorJustifyOffset=je,ze+=1}for(B=0;B<z;B+=1){if(L.reset(),Me=1,W[B].n)V=0,j+=T.yOffset,j+=fe?1:0,H=Pe,fe=!1,this._hasMaskedPath&&(G=Ie,J=Ae,Y=Z[G].points,K=Y[J-1],$=Y[J],ie=$.partialLength,Q=0),Fe="",We="",Oe="",Ne="",qe=this.defaultPropsArray;else{if(this._hasMaskedPath){if(Le!==W[B].line){switch(T.j){case 1:H+=se-T.lineWidths[W[B].line];break;case 2:H+=(se-T.lineWidths[W[B].line])/2;break}Le=W[B].line}de!==W[B].ind&&(W[de]&&(H+=W[de].extra),H+=W[B].an/2,de=W[B].ind),H+=P[0]*W[B].an*.005;var Ge=0;for(ee=0;ee<te;ee+=1)ne=R[ee].a,ne.p.propType&&(ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),ae.length?Ge+=ne.p.v[0]*ae[0]:Ge+=ne.p.v[0]*ae),ne.a.propType&&(ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),ae.length?Ge+=ne.a.v[0]*ae[0]:Ge+=ne.a.v[0]*ae);for(U=!0,this._pathData.a.v&&(H=W[0].an*.5+(se-this._pathData.f.v-W[0].an*.5-W[W.length-1].an*.5)*de/(z-1),H+=this._pathData.f.v);U;)Q+ie>=H+Ge||!Y?(le=(H+Ge-Q)/$.partialLength,ye=K.point[0]+($.point[0]-K.point[0])*le,Ee=K.point[1]+($.point[1]-K.point[1])*le,L.translate(-P[0]*W[B].an*.005,-(P[1]*be)*.01),U=!1):Y&&(Q+=$.partialLength,J+=1,J>=Y.length&&(J=0,G+=1,Z[G]?Y=Z[G].points:ue.v.c?(J=0,G=0,Y=Z[G].points):(Q-=$.partialLength,Y=null)),Y&&(K=$,$=Y[J],ie=$.partialLength));ge=W[B].an/2-W[B].add,L.translate(-ge,0,0)}else ge=W[B].an/2-W[B].add,L.translate(-ge,0,0),L.translate(-P[0]*W[B].an*.005,-P[1]*be*.01,0);for(ee=0;ee<te;ee+=1)ne=R[ee].a,ne.t.propType&&(ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),(V!==0||T.j!==0)&&(this._hasMaskedPath?ae.length?H+=ne.t.v*ae[0]:H+=ne.t.v*ae:ae.length?V+=ne.t.v*ae[0]:V+=ne.t.v*ae));for(T.strokeWidthAnim&&(Ce=T.sw||0),T.strokeColorAnim&&(T.sc?ke=[T.sc[0],T.sc[1],T.sc[2]]:ke=[0,0,0]),T.fillColorAnim&&T.fc&&(xe=[T.fc[0],T.fc[1],T.fc[2]]),ee=0;ee<te;ee+=1)ne=R[ee].a,ne.a.propType&&(ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),ae.length?L.translate(-ne.a.v[0]*ae[0],-ne.a.v[1]*ae[1],ne.a.v[2]*ae[2]):L.translate(-ne.a.v[0]*ae,-ne.a.v[1]*ae,ne.a.v[2]*ae));for(ee=0;ee<te;ee+=1)ne=R[ee].a,ne.s.propType&&(ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),ae.length?L.scale(1+(ne.s.v[0]-1)*ae[0],1+(ne.s.v[1]-1)*ae[1],1):L.scale(1+(ne.s.v[0]-1)*ae,1+(ne.s.v[1]-1)*ae,1));for(ee=0;ee<te;ee+=1){if(ne=R[ee].a,ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),ne.sk.propType&&(ae.length?L.skewFromAxis(-ne.sk.v*ae[0],ne.sa.v*ae[1]):L.skewFromAxis(-ne.sk.v*ae,ne.sa.v*ae)),ne.r.propType&&(ae.length?L.rotateZ(-ne.r.v*ae[2]):L.rotateZ(-ne.r.v*ae)),ne.ry.propType&&(ae.length?L.rotateY(ne.ry.v*ae[1]):L.rotateY(ne.ry.v*ae)),ne.rx.propType&&(ae.length?L.rotateX(ne.rx.v*ae[0]):L.rotateX(ne.rx.v*ae)),ne.o.propType&&(ae.length?Me+=(ne.o.v*ae[0]-Me)*ae[0]:Me+=(ne.o.v*ae-Me)*ae),T.strokeWidthAnim&&ne.sw.propType&&(ae.length?Ce+=ne.sw.v*ae[0]:Ce+=ne.sw.v*ae),T.strokeColorAnim&&ne.sc.propType)for(we=0;we<3;we+=1)ae.length?ke[we]+=(ne.sc.v[we]-ke[we])*ae[0]:ke[we]+=(ne.sc.v[we]-ke[we])*ae;if(T.fillColorAnim&&T.fc){if(ne.fc.propType)for(we=0;we<3;we+=1)ae.length?xe[we]+=(ne.fc.v[we]-xe[we])*ae[0]:xe[we]+=(ne.fc.v[we]-xe[we])*ae;ne.fh.propType&&(ae.length?xe=addHueToRGB(xe,ne.fh.v*ae[0]):xe=addHueToRGB(xe,ne.fh.v*ae)),ne.fs.propType&&(ae.length?xe=addSaturationToRGB(xe,ne.fs.v*ae[0]):xe=addSaturationToRGB(xe,ne.fs.v*ae)),ne.fb.propType&&(ae.length?xe=addBrightnessToRGB(xe,ne.fb.v*ae[0]):xe=addBrightnessToRGB(xe,ne.fb.v*ae))}}for(ee=0;ee<te;ee+=1)ne=R[ee].a,ne.p.propType&&(ce=R[ee].s,ae=ce.getMult(W[B].anIndexes[ee],A.a[ee].s.totalChars),this._hasMaskedPath?ae.length?L.translate(0,ne.p.v[1]*ae[0],-ne.p.v[2]*ae[1]):L.translate(0,ne.p.v[1]*ae,-ne.p.v[2]*ae):ae.length?L.translate(ne.p.v[0]*ae[0],ne.p.v[1]*ae[1],-ne.p.v[2]*ae[2]):L.translate(ne.p.v[0]*ae,ne.p.v[1]*ae,-ne.p.v[2]*ae));if(T.strokeWidthAnim&&(Oe=Ce<0?0:Ce),T.strokeColorAnim&&(De="rgb("+Math.round(ke[0]*255)+","+Math.round(ke[1]*255)+","+Math.round(ke[2]*255)+")"),T.fillColorAnim&&T.fc&&(We="rgb("+Math.round(xe[0]*255)+","+Math.round(xe[1]*255)+","+Math.round(xe[2]*255)+")"),this._hasMaskedPath){if(L.translate(0,-T.ls),L.translate(0,P[1]*be*.01+j,0),this._pathData.p.v){pe=($.point[1]-K.point[1])/($.point[0]-K.point[0]);var et=Math.atan(pe)*180/Math.PI;$.point[0]<K.point[0]&&(et+=180),L.rotate(-et*Math.PI/180)}L.translate(ye,Ee,0),H-=P[0]*W[B].an*.005,W[B+1]&&de!==W[B+1].ind&&(H+=W[B].an/2,H+=T.tr*.001*T.finalSize)}else{switch(L.translate(V,j,0),T.ps&&L.translate(T.ps[0],T.ps[1]+T.ascent,0),T.j){case 1:L.translate(W[B].animatorJustifyOffset+T.justifyOffset+(T.boxWidth-T.lineWidths[W[B].line]),0,0);break;case 2:L.translate(W[B].animatorJustifyOffset+T.justifyOffset+(T.boxWidth-T.lineWidths[W[B].line])/2,0,0);break}L.translate(0,-T.ls),L.translate(ge,0,0),L.translate(P[0]*W[B].an*.005,P[1]*be*.01,0),V+=W[B].l+T.tr*.001*T.finalSize}O==="html"?Fe=L.toCSS():O==="svg"?Fe=L.to2dCSS():qe=[L.props[0],L.props[1],L.props[2],L.props[3],L.props[4],L.props[5],L.props[6],L.props[7],L.props[8],L.props[9],L.props[10],L.props[11],L.props[12],L.props[13],L.props[14],L.props[15]],Ne=Me}N<=B?(oe=new LetterProps(Ne,Oe,De,We,Fe,qe),this.renderedLetters.push(oe),N+=1,this.lettersChangedFlag=!0):(oe=this.renderedLetters[B],this.lettersChangedFlag=oe.update(Ne,Oe,De,We,Fe,qe)||this.lettersChangedFlag)}}},TextAnimatorProperty.prototype.getValue=function(){this._elem.globalData.frameId!==this._frameId&&(this._frameId=this._elem.globalData.frameId,this.iterateDynamicProperties())},TextAnimatorProperty.prototype.mHelper=new Matrix,TextAnimatorProperty.prototype.defaultPropsArray=[],extendPrototype([DynamicPropertyContainer],TextAnimatorProperty);function ITextElement(){}ITextElement.prototype.initElement=function(T,n,P){this.lettersChangedFlag=!0,this.initFrame(),this.initBaseData(T,n,P),this.textProperty=new TextProperty(this,T.t,this.dynamicProperties),this.textAnimator=new TextAnimatorProperty(T.t,this.renderType,this),this.initTransform(T,n,P),this.initHierarchy(),this.initRenderable(),this.initRendererElement(),this.createContainerElements(),this.createRenderableComponents(),this.createContent(),this.hide(),this.textAnimator.searchProperties(this.dynamicProperties)},ITextElement.prototype.prepareFrame=function(T){this._mdf=!1,this.prepareRenderableFrame(T),this.prepareProperties(T,this.isInRange)},ITextElement.prototype.createPathShape=function(T,n){var P,R=n.length,A,L="";for(P=0;P<R;P+=1)n[P].ty==="sh"&&(A=n[P].ks.k,L+=buildShapeString(A,A.i.length,!0,T));return L},ITextElement.prototype.updateDocumentData=function(T,n){this.textProperty.updateDocumentData(T,n)},ITextElement.prototype.canResizeFont=function(T){this.textProperty.canResizeFont(T)},ITextElement.prototype.setMinimumFontSize=function(T){this.textProperty.setMinimumFontSize(T)},ITextElement.prototype.applyTextPropertiesToMatrix=function(T,n,P,R,A){switch(T.ps&&n.translate(T.ps[0],T.ps[1]+T.ascent,0),n.translate(0,-T.ls,0),T.j){case 1:n.translate(T.justifyOffset+(T.boxWidth-T.lineWidths[P]),0,0);break;case 2:n.translate(T.justifyOffset+(T.boxWidth-T.lineWidths[P])/2,0,0);break}n.translate(R,A,0)},ITextElement.prototype.buildColor=function(T){return"rgb("+Math.round(T[0]*255)+","+Math.round(T[1]*255)+","+Math.round(T[2]*255)+")"},ITextElement.prototype.emptyProp=new LetterProps,ITextElement.prototype.destroy=function(){},ITextElement.prototype.validateText=function(){(this.textProperty._mdf||this.textProperty._isFirstFrame)&&(this.buildNewText(),this.textProperty._isFirstFrame=!1,this.textProperty._mdf=!1)};var emptyShapeData={shapes:[]};function SVGTextLottieElement(T,n,P){this.textSpans=[],this.renderType="svg",this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,SVGBaseElement,HierarchyElement,FrameElement,RenderableDOMElement,ITextElement],SVGTextLottieElement),SVGTextLottieElement.prototype.createContent=function(){this.data.singleShape&&!this.globalData.fontManager.chars&&(this.textContainer=createNS("text"))},SVGTextLottieElement.prototype.buildTextContents=function(T){for(var n=0,P=T.length,R=[],A="";n<P;)T[n]==="\r"||T[n]===""?(R.push(A),A=""):A+=T[n],n+=1;return R.push(A),R},SVGTextLottieElement.prototype.buildShapeData=function(T,n){if(T.shapes&&T.shapes.length){var P=T.shapes[0];if(P.it){var R=P.it[P.it.length-1];R.s&&(R.s.k[0]=n,R.s.k[1]=n)}}return T},SVGTextLottieElement.prototype.buildNewText=function(){this.addDynamicProperty(this);var T,n,P=this.textProperty.currentData;this.renderedLetters=createSizedArray(P?P.l.length:0),P.fc?this.layerElement.setAttribute("fill",this.buildColor(P.fc)):this.layerElement.setAttribute("fill","rgba(0,0,0,0)"),P.sc&&(this.layerElement.setAttribute("stroke",this.buildColor(P.sc)),this.layerElement.setAttribute("stroke-width",P.sw)),this.layerElement.setAttribute("font-size",P.finalSize);var R=this.globalData.fontManager.getFontByName(P.f);if(R.fClass)this.layerElement.setAttribute("class",R.fClass);else{this.layerElement.setAttribute("font-family",R.fFamily);var A=P.fWeight,L=P.fStyle;this.layerElement.setAttribute("font-style",L),this.layerElement.setAttribute("font-weight",A)}this.layerElement.setAttribute("aria-label",P.t);var O=P.l||[],N=!!this.globalData.fontManager.chars;n=O.length;var V,j=this.mHelper,B="",z=this.data.singleShape,W=0,q=0,H=!0,$=P.tr*.001*P.finalSize;if(z&&!N&&!P.sz){var Q=this.textContainer,U="start";switch(P.j){case 1:U="end";break;case 2:U="middle";break;default:U="start";break}Q.setAttribute("text-anchor",U),Q.setAttribute("letter-spacing",$);var J=this.buildTextContents(P.finalText);for(n=J.length,q=P.ps?P.ps[1]+P.ascent:0,T=0;T<n;T+=1)V=this.textSpans[T].span||createNS("tspan"),V.textContent=J[T],V.setAttribute("x",0),V.setAttribute("y",q),V.style.display="inherit",Q.appendChild(V),this.textSpans[T]||(this.textSpans[T]={span:null,glyph:null}),this.textSpans[T].span=V,q+=P.finalLineHeight;this.layerElement.appendChild(Q)}else{var G=this.textSpans.length,K;for(T=0;T<n;T+=1){if(this.textSpans[T]||(this.textSpans[T]={span:null,childSpan:null,glyph:null}),!N||!z||T===0){if(V=G>T?this.textSpans[T].span:createNS(N?"g":"text"),G<=T){if(V.setAttribute("stroke-linecap","butt"),V.setAttribute("stroke-linejoin","round"),V.setAttribute("stroke-miterlimit","4"),this.textSpans[T].span=V,N){var Y=createNS("g");V.appendChild(Y),this.textSpans[T].childSpan=Y}this.textSpans[T].span=V,this.layerElement.appendChild(V)}V.style.display="inherit"}if(j.reset(),z&&(O[T].n&&(W=-$,q+=P.yOffset,q+=H?1:0,H=!1),this.applyTextPropertiesToMatrix(P,j,O[T].line,W,q),W+=O[T].l||0,W+=$),N){K=this.globalData.fontManager.getCharData(P.finalText[T],R.fStyle,this.globalData.fontManager.getFontByName(P.f).fFamily);var Z;if(K.t===1)Z=new SVGCompElement(K.data,this.globalData,this);else{var ie=emptyShapeData;K.data&&K.data.shapes&&(ie=this.buildShapeData(K.data,P.finalSize)),Z=new SVGShapeElement(ie,this.globalData,this)}if(this.textSpans[T].glyph){var se=this.textSpans[T].glyph;this.textSpans[T].childSpan.removeChild(se.layerElement),se.destroy()}this.textSpans[T].glyph=Z,Z._debug=!0,Z.prepareFrame(0),Z.renderFrame(),this.textSpans[T].childSpan.appendChild(Z.layerElement),K.t===1&&this.textSpans[T].childSpan.setAttribute("transform","scale("+P.finalSize/100+","+P.finalSize/100+")")}else z&&V.setAttribute("transform","translate("+j.props[12]+","+j.props[13]+")"),V.textContent=O[T].val,V.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve")}z&&V&&V.setAttribute("d",B)}for(;T<this.textSpans.length;)this.textSpans[T].span.style.display="none",T+=1;this._sizeChanged=!0},SVGTextLottieElement.prototype.sourceRectAtTime=function(){if(this.prepareFrame(this.comp.renderedFrame-this.data.st),this.renderInnerContent(),this._sizeChanged){this._sizeChanged=!1;var T=this.layerElement.getBBox();this.bbox={top:T.y,left:T.x,width:T.width,height:T.height}}return this.bbox},SVGTextLottieElement.prototype.getValue=function(){var T,n=this.textSpans.length,P;for(this.renderedFrame=this.comp.renderedFrame,T=0;T<n;T+=1)P=this.textSpans[T].glyph,P&&(P.prepareFrame(this.comp.renderedFrame-this.data.st),P._mdf&&(this._mdf=!0))},SVGTextLottieElement.prototype.renderInnerContent=function(){if(this.validateText(),(!this.data.singleShape||this._mdf)&&(this.textAnimator.getMeasures(this.textProperty.currentData,this.lettersChangedFlag),this.lettersChangedFlag||this.textAnimator.lettersChangedFlag)){this._sizeChanged=!0;var T,n,P=this.textAnimator.renderedLetters,R=this.textProperty.currentData.l;n=R.length;var A,L,O;for(T=0;T<n;T+=1)R[T].n||(A=P[T],L=this.textSpans[T].span,O=this.textSpans[T].glyph,O&&O.renderFrame(),A._mdf.m&&L.setAttribute("transform",A.m),A._mdf.o&&L.setAttribute("opacity",A.o),A._mdf.sw&&L.setAttribute("stroke-width",A.sw),A._mdf.sc&&L.setAttribute("stroke",A.sc),A._mdf.fc&&L.setAttribute("fill",A.fc))}};function ISolidElement(T,n,P){this.initElement(T,n,P)}extendPrototype([IImageElement],ISolidElement),ISolidElement.prototype.createContent=function(){var T=createNS("rect");T.setAttribute("width",this.data.sw),T.setAttribute("height",this.data.sh),T.setAttribute("fill",this.data.sc),this.layerElement.appendChild(T)};function NullElement(T,n,P){this.initFrame(),this.initBaseData(T,n,P),this.initFrame(),this.initTransform(T,n,P),this.initHierarchy()}NullElement.prototype.prepareFrame=function(T){this.prepareProperties(T,!0)},NullElement.prototype.renderFrame=function(){},NullElement.prototype.getBaseElement=function(){return null},NullElement.prototype.destroy=function(){},NullElement.prototype.sourceRectAtTime=function(){},NullElement.prototype.hide=function(){},extendPrototype([BaseElement,TransformElement,HierarchyElement,FrameElement],NullElement);function SVGRendererBase(){}extendPrototype([BaseRenderer],SVGRendererBase),SVGRendererBase.prototype.createNull=function(T){return new NullElement(T,this.globalData,this)},SVGRendererBase.prototype.createShape=function(T){return new SVGShapeElement(T,this.globalData,this)},SVGRendererBase.prototype.createText=function(T){return new SVGTextLottieElement(T,this.globalData,this)},SVGRendererBase.prototype.createImage=function(T){return new IImageElement(T,this.globalData,this)},SVGRendererBase.prototype.createSolid=function(T){return new ISolidElement(T,this.globalData,this)},SVGRendererBase.prototype.configAnimation=function(T){this.svgElement.setAttribute("xmlns","http://www.w3.org/2000/svg"),this.svgElement.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),this.renderConfig.viewBoxSize?this.svgElement.setAttribute("viewBox",this.renderConfig.viewBoxSize):this.svgElement.setAttribute("viewBox","0 0 "+T.w+" "+T.h),this.renderConfig.viewBoxOnly||(this.svgElement.setAttribute("width",T.w),this.svgElement.setAttribute("height",T.h),this.svgElement.style.width="100%",this.svgElement.style.height="100%",this.svgElement.style.transform="translate3d(0,0,0)",this.svgElement.style.contentVisibility=this.renderConfig.contentVisibility),this.renderConfig.width&&this.svgElement.setAttribute("width",this.renderConfig.width),this.renderConfig.height&&this.svgElement.setAttribute("height",this.renderConfig.height),this.renderConfig.className&&this.svgElement.setAttribute("class",this.renderConfig.className),this.renderConfig.id&&this.svgElement.setAttribute("id",this.renderConfig.id),this.renderConfig.focusable!==void 0&&this.svgElement.setAttribute("focusable",this.renderConfig.focusable),this.svgElement.setAttribute("preserveAspectRatio",this.renderConfig.preserveAspectRatio),this.animationItem.wrapper.appendChild(this.svgElement);var n=this.globalData.defs;this.setupGlobalData(T,n),this.globalData.progressiveLoad=this.renderConfig.progressiveLoad,this.data=T;var P=createNS("clipPath"),R=createNS("rect");R.setAttribute("width",T.w),R.setAttribute("height",T.h),R.setAttribute("x",0),R.setAttribute("y",0);var A=createElementID();P.setAttribute("id",A),P.appendChild(R),this.layerElement.setAttribute("clip-path","url("+getLocationHref()+"#"+A+")"),n.appendChild(P),this.layers=T.layers,this.elements=createSizedArray(T.layers.length)},SVGRendererBase.prototype.destroy=function(){this.animationItem.wrapper&&(this.animationItem.wrapper.innerText=""),this.layerElement=null,this.globalData.defs=null;var T,n=this.layers?this.layers.length:0;for(T=0;T<n;T+=1)this.elements[T]&&this.elements[T].destroy&&this.elements[T].destroy();this.elements.length=0,this.destroyed=!0,this.animationItem=null},SVGRendererBase.prototype.updateContainerSize=function(){},SVGRendererBase.prototype.findIndexByInd=function(T){var n=0,P=this.layers.length;for(n=0;n<P;n+=1)if(this.layers[n].ind===T)return n;return-1},SVGRendererBase.prototype.buildItem=function(T){var n=this.elements;if(!(n[T]||this.layers[T].ty===99)){n[T]=!0;var P=this.createItem(this.layers[T]);if(n[T]=P,getExpressionsPlugin()&&(this.layers[T].ty===0&&this.globalData.projectInterface.registerComposition(P),P.initExpressions()),this.appendElementInPos(P,T),this.layers[T].tt){var R="tp"in this.layers[T]?this.findIndexByInd(this.layers[T].tp):T-1;if(R===-1)return;if(!this.elements[R]||this.elements[R]===!0)this.buildItem(R),this.addPendingElement(P);else{var A=n[R],L=A.getMatte(this.layers[T].tt);P.setMatte(L)}}}},SVGRendererBase.prototype.checkPendingElements=function(){for(;this.pendingElements.length;){var T=this.pendingElements.pop();if(T.checkParenting(),T.data.tt)for(var n=0,P=this.elements.length;n<P;){if(this.elements[n]===T){var R="tp"in T.data?this.findIndexByInd(T.data.tp):n-1,A=this.elements[R],L=A.getMatte(this.layers[n].tt);T.setMatte(L);break}n+=1}}},SVGRendererBase.prototype.renderFrame=function(T){if(!(this.renderedFrame===T||this.destroyed)){T===null?T=this.renderedFrame:this.renderedFrame=T,this.globalData.frameNum=T,this.globalData.frameId+=1,this.globalData.projectInterface.currentFrame=T,this.globalData._mdf=!1;var n,P=this.layers.length;for(this.completeLayers||this.checkLayers(T),n=P-1;n>=0;n-=1)(this.completeLayers||this.elements[n])&&this.elements[n].prepareFrame(T-this.layers[n].st);if(this.globalData._mdf)for(n=0;n<P;n+=1)(this.completeLayers||this.elements[n])&&this.elements[n].renderFrame()}},SVGRendererBase.prototype.appendElementInPos=function(T,n){var P=T.getBaseElement();if(P){for(var R=0,A;R<n;)this.elements[R]&&this.elements[R]!==!0&&this.elements[R].getBaseElement()&&(A=this.elements[R].getBaseElement()),R+=1;A?this.layerElement.insertBefore(P,A):this.layerElement.appendChild(P)}},SVGRendererBase.prototype.hide=function(){this.layerElement.style.display="none"},SVGRendererBase.prototype.show=function(){this.layerElement.style.display="block"};function ICompElement(){}extendPrototype([BaseElement,TransformElement,HierarchyElement,FrameElement,RenderableDOMElement],ICompElement),ICompElement.prototype.initElement=function(T,n,P){this.initFrame(),this.initBaseData(T,n,P),this.initTransform(T,n,P),this.initRenderable(),this.initHierarchy(),this.initRendererElement(),this.createContainerElements(),this.createRenderableComponents(),(this.data.xt||!n.progressiveLoad)&&this.buildAllItems(),this.hide()},ICompElement.prototype.prepareFrame=function(T){if(this._mdf=!1,this.prepareRenderableFrame(T),this.prepareProperties(T,this.isInRange),!(!this.isInRange&&!this.data.xt)){if(this.tm._placeholder)this.renderedFrame=T/this.data.sr;else{var n=this.tm.v;n===this.data.op&&(n=this.data.op-1),this.renderedFrame=n}var P,R=this.elements.length;for(this.completeLayers||this.checkLayers(this.renderedFrame),P=R-1;P>=0;P-=1)(this.completeLayers||this.elements[P])&&(this.elements[P].prepareFrame(this.renderedFrame-this.layers[P].st),this.elements[P]._mdf&&(this._mdf=!0))}},ICompElement.prototype.renderInnerContent=function(){var T,n=this.layers.length;for(T=0;T<n;T+=1)(this.completeLayers||this.elements[T])&&this.elements[T].renderFrame()},ICompElement.prototype.setElements=function(T){this.elements=T},ICompElement.prototype.getElements=function(){return this.elements},ICompElement.prototype.destroyElements=function(){var T,n=this.layers.length;for(T=0;T<n;T+=1)this.elements[T]&&this.elements[T].destroy()},ICompElement.prototype.destroy=function(){this.destroyElements(),this.destroyBaseElement()};function SVGCompElement(T,n,P){this.layers=T.layers,this.supports3d=!0,this.completeLayers=!1,this.pendingElements=[],this.elements=this.layers?createSizedArray(this.layers.length):[],this.initElement(T,n,P),this.tm=T.tm?PropertyFactory.getProp(this,T.tm,0,n.frameRate,this):{_placeholder:!0}}extendPrototype([SVGRendererBase,ICompElement,SVGBaseElement],SVGCompElement),SVGCompElement.prototype.createComp=function(T){return new SVGCompElement(T,this.globalData,this)};function SVGRenderer(T,n){this.animationItem=T,this.layers=null,this.renderedFrame=-1,this.svgElement=createNS("svg");var P="";if(n&&n.title){var R=createNS("title"),A=createElementID();R.setAttribute("id",A),R.textContent=n.title,this.svgElement.appendChild(R),P+=A}if(n&&n.description){var L=createNS("desc"),O=createElementID();L.setAttribute("id",O),L.textContent=n.description,this.svgElement.appendChild(L),P+=" "+O}P&&this.svgElement.setAttribute("aria-labelledby",P);var N=createNS("defs");this.svgElement.appendChild(N);var V=createNS("g");this.svgElement.appendChild(V),this.layerElement=V,this.renderConfig={preserveAspectRatio:n&&n.preserveAspectRatio||"xMidYMid meet",imagePreserveAspectRatio:n&&n.imagePreserveAspectRatio||"xMidYMid slice",contentVisibility:n&&n.contentVisibility||"visible",progressiveLoad:n&&n.progressiveLoad||!1,hideOnTransparent:!(n&&n.hideOnTransparent===!1),viewBoxOnly:n&&n.viewBoxOnly||!1,viewBoxSize:n&&n.viewBoxSize||!1,className:n&&n.className||"",id:n&&n.id||"",focusable:n&&n.focusable,filterSize:{width:n&&n.filterSize&&n.filterSize.width||"100%",height:n&&n.filterSize&&n.filterSize.height||"100%",x:n&&n.filterSize&&n.filterSize.x||"0%",y:n&&n.filterSize&&n.filterSize.y||"0%"},width:n&&n.width,height:n&&n.height,runExpressions:!n||n.runExpressions===void 0||n.runExpressions},this.globalData={_mdf:!1,frameNum:-1,defs:N,renderConfig:this.renderConfig},this.elements=[],this.pendingElements=[],this.destroyed=!1,this.rendererType="svg"}extendPrototype([SVGRendererBase],SVGRenderer),SVGRenderer.prototype.createComp=function(T){return new SVGCompElement(T,this.globalData,this)};function ShapeTransformManager(){this.sequences={},this.sequenceList=[],this.transform_key_count=0}ShapeTransformManager.prototype={addTransformSequence:function(n){var P,R=n.length,A="_";for(P=0;P<R;P+=1)A+=n[P].transform.key+"_";var L=this.sequences[A];return L||(L={transforms:[].concat(n),finalTransform:new Matrix,_mdf:!1},this.sequences[A]=L,this.sequenceList.push(L)),L},processSequence:function(n,P){for(var R=0,A=n.transforms.length,L=P;R<A&&!P;){if(n.transforms[R].transform.mProps._mdf){L=!0;break}R+=1}if(L)for(n.finalTransform.reset(),R=A-1;R>=0;R-=1)n.finalTransform.multiply(n.transforms[R].transform.mProps.v);n._mdf=L},processSequences:function(n){var P,R=this.sequenceList.length;for(P=0;P<R;P+=1)this.processSequence(this.sequenceList[P],n)},getNewKey:function(){return this.transform_key_count+=1,"_"+this.transform_key_count}};var lumaLoader=function(){var n="__lottie_element_luma_buffer",P=null,R=null,A=null;function L(){var V=createNS("svg"),j=createNS("filter"),B=createNS("feColorMatrix");return j.setAttribute("id",n),B.setAttribute("type","matrix"),B.setAttribute("color-interpolation-filters","sRGB"),B.setAttribute("values","0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0"),j.appendChild(B),V.appendChild(j),V.setAttribute("id",n+"_svg"),featureSupport.svgLumaHidden&&(V.style.display="none"),V}function O(){P||(A=L(),document.body.appendChild(A),P=createTag("canvas"),R=P.getContext("2d"),R.filter="url(#"+n+")",R.fillStyle="rgba(0,0,0,0)",R.fillRect(0,0,1,1))}function N(V){return P||O(),P.width=V.width,P.height=V.height,R.filter="url(#"+n+")",P}return{load:O,get:N}};function createCanvas(T,n){if(featureSupport.offscreenCanvas)return new OffscreenCanvas(T,n);var P=createTag("canvas");return P.width=T,P.height=n,P}var assetLoader=(function(){return{loadLumaCanvas:lumaLoader.load,getLumaCanvas:lumaLoader.get,createCanvas}})(),registeredEffects={};function CVEffects(T){var n,P=T.data.ef?T.data.ef.length:0;this.filters=[];var R;for(n=0;n<P;n+=1){R=null;var A=T.data.ef[n].ty;if(registeredEffects[A]){var L=registeredEffects[A].effect;R=new L(T.effectsManager.effectElements[n],T)}R&&this.filters.push(R)}this.filters.length&&T.addRenderableComponent(this)}CVEffects.prototype.renderFrame=function(T){var n,P=this.filters.length;for(n=0;n<P;n+=1)this.filters[n].renderFrame(T)},CVEffects.prototype.getEffects=function(T){var n,P=this.filters.length,R=[];for(n=0;n<P;n+=1)this.filters[n].type===T&&R.push(this.filters[n]);return R};function registerEffect(T,n){registeredEffects[T]={effect:n}}function CVMaskElement(T,n){this.data=T,this.element=n,this.masksProperties=this.data.masksProperties||[],this.viewData=createSizedArray(this.masksProperties.length);var P,R=this.masksProperties.length,A=!1;for(P=0;P<R;P+=1)this.masksProperties[P].mode!=="n"&&(A=!0),this.viewData[P]=ShapePropertyFactory.getShapeProp(this.element,this.masksProperties[P],3);this.hasMasks=A,A&&this.element.addRenderableComponent(this)}CVMaskElement.prototype.renderFrame=function(){if(this.hasMasks){var T=this.element.finalTransform.mat,n=this.element.canvasContext,P,R=this.masksProperties.length,A,L,O;for(n.beginPath(),P=0;P<R;P+=1)if(this.masksProperties[P].mode!=="n"){this.masksProperties[P].inv&&(n.moveTo(0,0),n.lineTo(this.element.globalData.compSize.w,0),n.lineTo(this.element.globalData.compSize.w,this.element.globalData.compSize.h),n.lineTo(0,this.element.globalData.compSize.h),n.lineTo(0,0)),O=this.viewData[P].v,A=T.applyToPointArray(O.v[0][0],O.v[0][1],0),n.moveTo(A[0],A[1]);var N,V=O._length;for(N=1;N<V;N+=1)L=T.applyToTriplePoints(O.o[N-1],O.i[N],O.v[N]),n.bezierCurveTo(L[0],L[1],L[2],L[3],L[4],L[5]);L=T.applyToTriplePoints(O.o[N-1],O.i[0],O.v[0]),n.bezierCurveTo(L[0],L[1],L[2],L[3],L[4],L[5])}this.element.globalData.renderer.save(!0),n.clip()}},CVMaskElement.prototype.getMaskProperty=MaskElement.prototype.getMaskProperty,CVMaskElement.prototype.destroy=function(){this.element=null};function CVBaseElement(){}var operationsMap={1:"source-in",2:"source-out",3:"source-in",4:"source-out"};CVBaseElement.prototype={createElements:function(){},initRendererElement:function(){},createContainerElements:function(){if(this.data.tt>=1){this.buffers=[];var n=this.globalData.canvasContext,P=assetLoader.createCanvas(n.canvas.width,n.canvas.height);this.buffers.push(P);var R=assetLoader.createCanvas(n.canvas.width,n.canvas.height);this.buffers.push(R),this.data.tt>=3&&!document._isProxy&&assetLoader.loadLumaCanvas()}this.canvasContext=this.globalData.canvasContext,this.transformCanvas=this.globalData.transformCanvas,this.renderableEffectsManager=new CVEffects(this),this.searchEffectTransforms()},createContent:function(){},setBlendMode:function(){var n=this.globalData;if(n.blendMode!==this.data.bm){n.blendMode=this.data.bm;var P=getBlendMode(this.data.bm);n.canvasContext.globalCompositeOperation=P}},createRenderableComponents:function(){this.maskManager=new CVMaskElement(this.data,this),this.transformEffects=this.renderableEffectsManager.getEffects(effectTypes.TRANSFORM_EFFECT)},hideElement:function(){!this.hidden&&(!this.isInRange||this.isTransparent)&&(this.hidden=!0)},showElement:function(){this.isInRange&&!this.isTransparent&&(this.hidden=!1,this._isFirstFrame=!0,this.maskManager._isFirstFrame=!0)},clearCanvas:function(n){n.clearRect(this.transformCanvas.tx,this.transformCanvas.ty,this.transformCanvas.w*this.transformCanvas.sx,this.transformCanvas.h*this.transformCanvas.sy)},prepareLayer:function(){if(this.data.tt>=1){var n=this.buffers[0],P=n.getContext("2d");this.clearCanvas(P),P.drawImage(this.canvasContext.canvas,0,0),this.currentTransform=this.canvasContext.getTransform(),this.canvasContext.setTransform(1,0,0,1,0,0),this.clearCanvas(this.canvasContext),this.canvasContext.setTransform(this.currentTransform)}},exitLayer:function(){if(this.data.tt>=1){var n=this.buffers[1],P=n.getContext("2d");this.clearCanvas(P),P.drawImage(this.canvasContext.canvas,0,0),this.canvasContext.setTransform(1,0,0,1,0,0),this.clearCanvas(this.canvasContext),this.canvasContext.setTransform(this.currentTransform);var R=this.comp.getElementById("tp"in this.data?this.data.tp:this.data.ind-1);if(R.renderFrame(!0),this.canvasContext.setTransform(1,0,0,1,0,0),this.data.tt>=3&&!document._isProxy){var A=assetLoader.getLumaCanvas(this.canvasContext.canvas),L=A.getContext("2d");L.drawImage(this.canvasContext.canvas,0,0),this.clearCanvas(this.canvasContext),this.canvasContext.drawImage(A,0,0)}this.canvasContext.globalCompositeOperation=operationsMap[this.data.tt],this.canvasContext.drawImage(n,0,0),this.canvasContext.globalCompositeOperation="destination-over",this.canvasContext.drawImage(this.buffers[0],0,0),this.canvasContext.setTransform(this.currentTransform),this.canvasContext.globalCompositeOperation="source-over"}},renderFrame:function(n){if(!(this.hidden||this.data.hd)&&!(this.data.td===1&&!n)){this.renderTransform(),this.renderRenderable(),this.renderLocalTransform(),this.setBlendMode();var P=this.data.ty===0;this.prepareLayer(),this.globalData.renderer.save(P),this.globalData.renderer.ctxTransform(this.finalTransform.localMat.props),this.globalData.renderer.ctxOpacity(this.finalTransform.localOpacity),this.renderInnerContent(),this.globalData.renderer.restore(P),this.exitLayer(),this.maskManager.hasMasks&&this.globalData.renderer.restore(!0),this._isFirstFrame&&(this._isFirstFrame=!1)}},destroy:function(){this.canvasContext=null,this.data=null,this.globalData=null,this.maskManager.destroy()},mHelper:new Matrix},CVBaseElement.prototype.hide=CVBaseElement.prototype.hideElement,CVBaseElement.prototype.show=CVBaseElement.prototype.showElement;function CVShapeData(T,n,P,R){this.styledShapes=[],this.tr=[0,0,0,0,0,0];var A=4;n.ty==="rc"?A=5:n.ty==="el"?A=6:n.ty==="sr"&&(A=7),this.sh=ShapePropertyFactory.getShapeProp(T,n,A,T);var L,O=P.length,N;for(L=0;L<O;L+=1)P[L].closed||(N={transforms:R.addTransformSequence(P[L].transforms),trNodes:[]},this.styledShapes.push(N),P[L].elements.push(N))}CVShapeData.prototype.setAsAnimated=SVGShapeData.prototype.setAsAnimated;function CVShapeElement(T,n,P){this.shapes=[],this.shapesData=T.shapes,this.stylesList=[],this.itemsData=[],this.prevViewData=[],this.shapeModifiers=[],this.processedElements=[],this.transformsManager=new ShapeTransformManager,this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,CVBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableElement],CVShapeElement),CVShapeElement.prototype.initElement=RenderableDOMElement.prototype.initElement,CVShapeElement.prototype.transformHelper={opacity:1,_opMdf:!1},CVShapeElement.prototype.dashResetter=[],CVShapeElement.prototype.createContent=function(){this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,!0,[])},CVShapeElement.prototype.createStyleElement=function(T,n){var P={data:T,type:T.ty,preTransforms:this.transformsManager.addTransformSequence(n),transforms:[],elements:[],closed:T.hd===!0},R={};if(T.ty==="fl"||T.ty==="st"?(R.c=PropertyFactory.getProp(this,T.c,1,255,this),R.c.k||(P.co="rgb("+bmFloor(R.c.v[0])+","+bmFloor(R.c.v[1])+","+bmFloor(R.c.v[2])+")")):(T.ty==="gf"||T.ty==="gs")&&(R.s=PropertyFactory.getProp(this,T.s,1,null,this),R.e=PropertyFactory.getProp(this,T.e,1,null,this),R.h=PropertyFactory.getProp(this,T.h||{k:0},0,.01,this),R.a=PropertyFactory.getProp(this,T.a||{k:0},0,degToRads,this),R.g=new GradientProperty(this,T.g,this)),R.o=PropertyFactory.getProp(this,T.o,0,.01,this),T.ty==="st"||T.ty==="gs"){if(P.lc=lineCapEnum[T.lc||2],P.lj=lineJoinEnum[T.lj||2],T.lj==1&&(P.ml=T.ml),R.w=PropertyFactory.getProp(this,T.w,0,null,this),R.w.k||(P.wi=R.w.v),T.d){var A=new DashProperty(this,T.d,"canvas",this);R.d=A,R.d.k||(P.da=R.d.dashArray,P.do=R.d.dashoffset[0])}}else P.r=T.r===2?"evenodd":"nonzero";return this.stylesList.push(P),R.style=P,R},CVShapeElement.prototype.createGroupElement=function(){var T={it:[],prevViewData:[]};return T},CVShapeElement.prototype.createTransformElement=function(T){var n={transform:{opacity:1,_opMdf:!1,key:this.transformsManager.getNewKey(),op:PropertyFactory.getProp(this,T.o,0,.01,this),mProps:TransformPropertyFactory.getTransformProperty(this,T,this)}};return n},CVShapeElement.prototype.createShapeElement=function(T){var n=new CVShapeData(this,T,this.stylesList,this.transformsManager);return this.shapes.push(n),this.addShapeToModifiers(n),n},CVShapeElement.prototype.reloadShapes=function(){this._isFirstFrame=!0;var T,n=this.itemsData.length;for(T=0;T<n;T+=1)this.prevViewData[T]=this.itemsData[T];for(this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,!0,[]),n=this.dynamicProperties.length,T=0;T<n;T+=1)this.dynamicProperties[T].getValue();this.renderModifiers(),this.transformsManager.processSequences(this._isFirstFrame)},CVShapeElement.prototype.addTransformToStyleList=function(T){var n,P=this.stylesList.length;for(n=0;n<P;n+=1)this.stylesList[n].closed||this.stylesList[n].transforms.push(T)},CVShapeElement.prototype.removeTransformFromStyleList=function(){var T,n=this.stylesList.length;for(T=0;T<n;T+=1)this.stylesList[T].closed||this.stylesList[T].transforms.pop()},CVShapeElement.prototype.closeStyles=function(T){var n,P=T.length;for(n=0;n<P;n+=1)T[n].closed=!0},CVShapeElement.prototype.searchShapes=function(T,n,P,R,A){var L,O=T.length-1,N,V,j=[],B=[],z,W,q,H=[].concat(A);for(L=O;L>=0;L-=1){if(z=this.searchProcessedElement(T[L]),z?n[L]=P[z-1]:T[L]._shouldRender=R,T[L].ty==="fl"||T[L].ty==="st"||T[L].ty==="gf"||T[L].ty==="gs")z?n[L].style.closed=!1:n[L]=this.createStyleElement(T[L],H),j.push(n[L].style);else if(T[L].ty==="gr"){if(!z)n[L]=this.createGroupElement(T[L]);else for(V=n[L].it.length,N=0;N<V;N+=1)n[L].prevViewData[N]=n[L].it[N];this.searchShapes(T[L].it,n[L].it,n[L].prevViewData,R,H)}else T[L].ty==="tr"?(z||(q=this.createTransformElement(T[L]),n[L]=q),H.push(n[L]),this.addTransformToStyleList(n[L])):T[L].ty==="sh"||T[L].ty==="rc"||T[L].ty==="el"||T[L].ty==="sr"?z||(n[L]=this.createShapeElement(T[L])):T[L].ty==="tm"||T[L].ty==="rd"||T[L].ty==="pb"||T[L].ty==="zz"||T[L].ty==="op"?(z?(W=n[L],W.closed=!1):(W=ShapeModifiers.getModifier(T[L].ty),W.init(this,T[L]),n[L]=W,this.shapeModifiers.push(W)),B.push(W)):T[L].ty==="rp"&&(z?(W=n[L],W.closed=!0):(W=ShapeModifiers.getModifier(T[L].ty),n[L]=W,W.init(this,T,L,n),this.shapeModifiers.push(W),R=!1),B.push(W));this.addProcessedElement(T[L],L+1)}for(this.removeTransformFromStyleList(),this.closeStyles(j),O=B.length,L=0;L<O;L+=1)B[L].closed=!0},CVShapeElement.prototype.renderInnerContent=function(){this.transformHelper.opacity=1,this.transformHelper._opMdf=!1,this.renderModifiers(),this.transformsManager.processSequences(this._isFirstFrame),this.renderShape(this.transformHelper,this.shapesData,this.itemsData,!0)},CVShapeElement.prototype.renderShapeTransform=function(T,n){(T._opMdf||n.op._mdf||this._isFirstFrame)&&(n.opacity=T.opacity,n.opacity*=n.op.v,n._opMdf=!0)},CVShapeElement.prototype.drawLayer=function(){var T,n=this.stylesList.length,P,R,A,L,O,N,V=this.globalData.renderer,j=this.globalData.canvasContext,B,z;for(T=0;T<n;T+=1)if(z=this.stylesList[T],B=z.type,!((B==="st"||B==="gs")&&z.wi===0||!z.data._shouldRender||z.coOp===0||this.globalData.currentGlobalAlpha===0)){for(V.save(),O=z.elements,B==="st"||B==="gs"?(V.ctxStrokeStyle(B==="st"?z.co:z.grd),V.ctxLineWidth(z.wi),V.ctxLineCap(z.lc),V.ctxLineJoin(z.lj),V.ctxMiterLimit(z.ml||0)):V.ctxFillStyle(B==="fl"?z.co:z.grd),V.ctxOpacity(z.coOp),B!=="st"&&B!=="gs"&&j.beginPath(),V.ctxTransform(z.preTransforms.finalTransform.props),R=O.length,P=0;P<R;P+=1){for((B==="st"||B==="gs")&&(j.beginPath(),z.da&&(j.setLineDash(z.da),j.lineDashOffset=z.do)),N=O[P].trNodes,L=N.length,A=0;A<L;A+=1)N[A].t==="m"?j.moveTo(N[A].p[0],N[A].p[1]):N[A].t==="c"?j.bezierCurveTo(N[A].pts[0],N[A].pts[1],N[A].pts[2],N[A].pts[3],N[A].pts[4],N[A].pts[5]):j.closePath();(B==="st"||B==="gs")&&(V.ctxStroke(),z.da&&j.setLineDash(this.dashResetter))}B!=="st"&&B!=="gs"&&this.globalData.renderer.ctxFill(z.r),V.restore()}},CVShapeElement.prototype.renderShape=function(T,n,P,R){var A,L=n.length-1,O;for(O=T,A=L;A>=0;A-=1)n[A].ty==="tr"?(O=P[A].transform,this.renderShapeTransform(T,O)):n[A].ty==="sh"||n[A].ty==="el"||n[A].ty==="rc"||n[A].ty==="sr"?this.renderPath(n[A],P[A]):n[A].ty==="fl"?this.renderFill(n[A],P[A],O):n[A].ty==="st"?this.renderStroke(n[A],P[A],O):n[A].ty==="gf"||n[A].ty==="gs"?this.renderGradientFill(n[A],P[A],O):n[A].ty==="gr"?this.renderShape(O,n[A].it,P[A].it):n[A].ty;R&&this.drawLayer()},CVShapeElement.prototype.renderStyledShape=function(T,n){if(this._isFirstFrame||n._mdf||T.transforms._mdf){var P=T.trNodes,R=n.paths,A,L,O,N=R._length;P.length=0;var V=T.transforms.finalTransform;for(O=0;O<N;O+=1){var j=R.shapes[O];if(j&&j.v){for(L=j._length,A=1;A<L;A+=1)A===1&&P.push({t:"m",p:V.applyToPointArray(j.v[0][0],j.v[0][1],0)}),P.push({t:"c",pts:V.applyToTriplePoints(j.o[A-1],j.i[A],j.v[A])});L===1&&P.push({t:"m",p:V.applyToPointArray(j.v[0][0],j.v[0][1],0)}),j.c&&L&&(P.push({t:"c",pts:V.applyToTriplePoints(j.o[A-1],j.i[0],j.v[0])}),P.push({t:"z"}))}}T.trNodes=P}},CVShapeElement.prototype.renderPath=function(T,n){if(T.hd!==!0&&T._shouldRender){var P,R=n.styledShapes.length;for(P=0;P<R;P+=1)this.renderStyledShape(n.styledShapes[P],n.sh)}},CVShapeElement.prototype.renderFill=function(T,n,P){var R=n.style;(n.c._mdf||this._isFirstFrame)&&(R.co="rgb("+bmFloor(n.c.v[0])+","+bmFloor(n.c.v[1])+","+bmFloor(n.c.v[2])+")"),(n.o._mdf||P._opMdf||this._isFirstFrame)&&(R.coOp=n.o.v*P.opacity)},CVShapeElement.prototype.renderGradientFill=function(T,n,P){var R=n.style,A;if(!R.grd||n.g._mdf||n.s._mdf||n.e._mdf||T.t!==1&&(n.h._mdf||n.a._mdf)){var L=this.globalData.canvasContext,O=n.s.v,N=n.e.v;if(T.t===1)A=L.createLinearGradient(O[0],O[1],N[0],N[1]);else{var V=Math.sqrt(Math.pow(O[0]-N[0],2)+Math.pow(O[1]-N[1],2)),j=Math.atan2(N[1]-O[1],N[0]-O[0]),B=n.h.v;B>=1?B=.99:B<=-1&&(B=-.99);var z=V*B,W=Math.cos(j+n.a.v)*z+O[0],q=Math.sin(j+n.a.v)*z+O[1];A=L.createRadialGradient(W,q,0,O[0],O[1],V)}var H,$=T.g.p,Q=n.g.c,U=1;for(H=0;H<$;H+=1)n.g._hasOpacity&&n.g._collapsable&&(U=n.g.o[H*2+1]),A.addColorStop(Q[H*4]/100,"rgba("+Q[H*4+1]+","+Q[H*4+2]+","+Q[H*4+3]+","+U+")");R.grd=A}R.coOp=n.o.v*P.opacity},CVShapeElement.prototype.renderStroke=function(T,n,P){var R=n.style,A=n.d;A&&(A._mdf||this._isFirstFrame)&&(R.da=A.dashArray,R.do=A.dashoffset[0]),(n.c._mdf||this._isFirstFrame)&&(R.co="rgb("+bmFloor(n.c.v[0])+","+bmFloor(n.c.v[1])+","+bmFloor(n.c.v[2])+")"),(n.o._mdf||P._opMdf||this._isFirstFrame)&&(R.coOp=n.o.v*P.opacity),(n.w._mdf||this._isFirstFrame)&&(R.wi=n.w.v)},CVShapeElement.prototype.destroy=function(){this.shapesData=null,this.globalData=null,this.canvasContext=null,this.stylesList.length=0,this.itemsData.length=0};function CVTextElement(T,n,P){this.textSpans=[],this.yOffset=0,this.fillColorAnim=!1,this.strokeColorAnim=!1,this.strokeWidthAnim=!1,this.stroke=!1,this.fill=!1,this.justifyOffset=0,this.currentRender=null,this.renderType="canvas",this.values={fill:"rgba(0,0,0,0)",stroke:"rgba(0,0,0,0)",sWidth:0,fValue:""},this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,CVBaseElement,HierarchyElement,FrameElement,RenderableElement,ITextElement],CVTextElement),CVTextElement.prototype.tHelper=createTag("canvas").getContext("2d"),CVTextElement.prototype.buildNewText=function(){var T=this.textProperty.currentData;this.renderedLetters=createSizedArray(T.l?T.l.length:0);var n=!1;T.fc?(n=!0,this.values.fill=this.buildColor(T.fc)):this.values.fill="rgba(0,0,0,0)",this.fill=n;var P=!1;T.sc&&(P=!0,this.values.stroke=this.buildColor(T.sc),this.values.sWidth=T.sw);var R=this.globalData.fontManager.getFontByName(T.f),A,L,O=T.l,N=this.mHelper;this.stroke=P,this.values.fValue=T.finalSize+"px "+this.globalData.fontManager.getFontByName(T.f).fFamily,L=T.finalText.length;var V,j,B,z,W,q,H,$,Q,U,J=this.data.singleShape,G=T.tr*.001*T.finalSize,K=0,Y=0,Z=!0,ie=0;for(A=0;A<L;A+=1){V=this.globalData.fontManager.getCharData(T.finalText[A],R.fStyle,this.globalData.fontManager.getFontByName(T.f).fFamily),j=V&&V.data||{},N.reset(),J&&O[A].n&&(K=-G,Y+=T.yOffset,Y+=Z?1:0,Z=!1),W=j.shapes?j.shapes[0].it:[],H=W.length,N.scale(T.finalSize/100,T.finalSize/100),J&&this.applyTextPropertiesToMatrix(T,N,O[A].line,K,Y),Q=createSizedArray(H-1);var se=0;for(q=0;q<H;q+=1)if(W[q].ty==="sh"){for(z=W[q].ks.k.i.length,$=W[q].ks.k,U=[],B=1;B<z;B+=1)B===1&&U.push(N.applyToX($.v[0][0],$.v[0][1],0),N.applyToY($.v[0][0],$.v[0][1],0)),U.push(N.applyToX($.o[B-1][0],$.o[B-1][1],0),N.applyToY($.o[B-1][0],$.o[B-1][1],0),N.applyToX($.i[B][0],$.i[B][1],0),N.applyToY($.i[B][0],$.i[B][1],0),N.applyToX($.v[B][0],$.v[B][1],0),N.applyToY($.v[B][0],$.v[B][1],0));U.push(N.applyToX($.o[B-1][0],$.o[B-1][1],0),N.applyToY($.o[B-1][0],$.o[B-1][1],0),N.applyToX($.i[0][0],$.i[0][1],0),N.applyToY($.i[0][0],$.i[0][1],0),N.applyToX($.v[0][0],$.v[0][1],0),N.applyToY($.v[0][0],$.v[0][1],0)),Q[se]=U,se+=1}J&&(K+=O[A].l,K+=G),this.textSpans[ie]?this.textSpans[ie].elem=Q:this.textSpans[ie]={elem:Q},ie+=1}},CVTextElement.prototype.renderInnerContent=function(){this.validateText();var T=this.canvasContext;T.font=this.values.fValue,this.globalData.renderer.ctxLineCap("butt"),this.globalData.renderer.ctxLineJoin("miter"),this.globalData.renderer.ctxMiterLimit(4),this.data.singleShape||this.textAnimator.getMeasures(this.textProperty.currentData,this.lettersChangedFlag);var n,P,R,A,L,O,N=this.textAnimator.renderedLetters,V=this.textProperty.currentData.l;P=V.length;var j,B=null,z=null,W=null,q,H,$=this.globalData.renderer;for(n=0;n<P;n+=1)if(!V[n].n){if(j=N[n],j&&($.save(),$.ctxTransform(j.p),$.ctxOpacity(j.o)),this.fill){for(j&&j.fc?B!==j.fc&&($.ctxFillStyle(j.fc),B=j.fc):B!==this.values.fill&&(B=this.values.fill,$.ctxFillStyle(this.values.fill)),q=this.textSpans[n].elem,A=q.length,this.globalData.canvasContext.beginPath(),R=0;R<A;R+=1)for(H=q[R],O=H.length,this.globalData.canvasContext.moveTo(H[0],H[1]),L=2;L<O;L+=6)this.globalData.canvasContext.bezierCurveTo(H[L],H[L+1],H[L+2],H[L+3],H[L+4],H[L+5]);this.globalData.canvasContext.closePath(),$.ctxFill()}if(this.stroke){for(j&&j.sw?W!==j.sw&&(W=j.sw,$.ctxLineWidth(j.sw)):W!==this.values.sWidth&&(W=this.values.sWidth,$.ctxLineWidth(this.values.sWidth)),j&&j.sc?z!==j.sc&&(z=j.sc,$.ctxStrokeStyle(j.sc)):z!==this.values.stroke&&(z=this.values.stroke,$.ctxStrokeStyle(this.values.stroke)),q=this.textSpans[n].elem,A=q.length,this.globalData.canvasContext.beginPath(),R=0;R<A;R+=1)for(H=q[R],O=H.length,this.globalData.canvasContext.moveTo(H[0],H[1]),L=2;L<O;L+=6)this.globalData.canvasContext.bezierCurveTo(H[L],H[L+1],H[L+2],H[L+3],H[L+4],H[L+5]);this.globalData.canvasContext.closePath(),$.ctxStroke()}j&&this.globalData.renderer.restore()}};function CVImageElement(T,n,P){this.assetData=n.getAssetData(T.refId),this.img=n.imageLoader.getAsset(this.assetData),this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,CVBaseElement,HierarchyElement,FrameElement,RenderableElement],CVImageElement),CVImageElement.prototype.initElement=SVGShapeElement.prototype.initElement,CVImageElement.prototype.prepareFrame=IImageElement.prototype.prepareFrame,CVImageElement.prototype.createContent=function(){if(this.img.width&&(this.assetData.w!==this.img.width||this.assetData.h!==this.img.height)){var T=createTag("canvas");T.width=this.assetData.w,T.height=this.assetData.h;var n=T.getContext("2d"),P=this.img.width,R=this.img.height,A=P/R,L=this.assetData.w/this.assetData.h,O,N,V=this.assetData.pr||this.globalData.renderConfig.imagePreserveAspectRatio;A>L&&V==="xMidYMid slice"||A<L&&V!=="xMidYMid slice"?(N=R,O=N*L):(O=P,N=O/L),n.drawImage(this.img,(P-O)/2,(R-N)/2,O,N,0,0,this.assetData.w,this.assetData.h),this.img=T}},CVImageElement.prototype.renderInnerContent=function(){this.canvasContext.drawImage(this.img,0,0)},CVImageElement.prototype.destroy=function(){this.img=null};function CVSolidElement(T,n,P){this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,CVBaseElement,HierarchyElement,FrameElement,RenderableElement],CVSolidElement),CVSolidElement.prototype.initElement=SVGShapeElement.prototype.initElement,CVSolidElement.prototype.prepareFrame=IImageElement.prototype.prepareFrame,CVSolidElement.prototype.renderInnerContent=function(){this.globalData.renderer.ctxFillStyle(this.data.sc),this.globalData.renderer.ctxFillRect(0,0,this.data.sw,this.data.sh)};function CanvasRendererBase(){}extendPrototype([BaseRenderer],CanvasRendererBase),CanvasRendererBase.prototype.createShape=function(T){return new CVShapeElement(T,this.globalData,this)},CanvasRendererBase.prototype.createText=function(T){return new CVTextElement(T,this.globalData,this)},CanvasRendererBase.prototype.createImage=function(T){return new CVImageElement(T,this.globalData,this)},CanvasRendererBase.prototype.createSolid=function(T){return new CVSolidElement(T,this.globalData,this)},CanvasRendererBase.prototype.createNull=SVGRenderer.prototype.createNull,CanvasRendererBase.prototype.ctxTransform=function(T){T[0]===1&&T[1]===0&&T[4]===0&&T[5]===1&&T[12]===0&&T[13]===0||this.canvasContext.transform(T[0],T[1],T[4],T[5],T[12],T[13])},CanvasRendererBase.prototype.ctxOpacity=function(T){this.canvasContext.globalAlpha*=T<0?0:T},CanvasRendererBase.prototype.ctxFillStyle=function(T){this.canvasContext.fillStyle=T},CanvasRendererBase.prototype.ctxStrokeStyle=function(T){this.canvasContext.strokeStyle=T},CanvasRendererBase.prototype.ctxLineWidth=function(T){this.canvasContext.lineWidth=T},CanvasRendererBase.prototype.ctxLineCap=function(T){this.canvasContext.lineCap=T},CanvasRendererBase.prototype.ctxLineJoin=function(T){this.canvasContext.lineJoin=T},CanvasRendererBase.prototype.ctxMiterLimit=function(T){this.canvasContext.miterLimit=T},CanvasRendererBase.prototype.ctxFill=function(T){this.canvasContext.fill(T)},CanvasRendererBase.prototype.ctxFillRect=function(T,n,P,R){this.canvasContext.fillRect(T,n,P,R)},CanvasRendererBase.prototype.ctxStroke=function(){this.canvasContext.stroke()},CanvasRendererBase.prototype.reset=function(){if(!this.renderConfig.clearCanvas){this.canvasContext.restore();return}this.contextData.reset()},CanvasRendererBase.prototype.save=function(){this.canvasContext.save()},CanvasRendererBase.prototype.restore=function(T){if(!this.renderConfig.clearCanvas){this.canvasContext.restore();return}T&&(this.globalData.blendMode="source-over"),this.contextData.restore(T)},CanvasRendererBase.prototype.configAnimation=function(T){if(this.animationItem.wrapper){this.animationItem.container=createTag("canvas");var n=this.animationItem.container.style;n.width="100%",n.height="100%";var P="0px 0px 0px";n.transformOrigin=P,n.mozTransformOrigin=P,n.webkitTransformOrigin=P,n["-webkit-transform"]=P,n.contentVisibility=this.renderConfig.contentVisibility,this.animationItem.wrapper.appendChild(this.animationItem.container),this.canvasContext=this.animationItem.container.getContext("2d"),this.renderConfig.className&&this.animationItem.container.setAttribute("class",this.renderConfig.className),this.renderConfig.id&&this.animationItem.container.setAttribute("id",this.renderConfig.id)}else this.canvasContext=this.renderConfig.context;this.contextData.setContext(this.canvasContext),this.data=T,this.layers=T.layers,this.transformCanvas={w:T.w,h:T.h,sx:0,sy:0,tx:0,ty:0},this.setupGlobalData(T,document.body),this.globalData.canvasContext=this.canvasContext,this.globalData.renderer=this,this.globalData.isDashed=!1,this.globalData.progressiveLoad=this.renderConfig.progressiveLoad,this.globalData.transformCanvas=this.transformCanvas,this.elements=createSizedArray(T.layers.length),this.updateContainerSize()},CanvasRendererBase.prototype.updateContainerSize=function(T,n){this.reset();var P,R;T?(P=T,R=n,this.canvasContext.canvas.width=P,this.canvasContext.canvas.height=R):(this.animationItem.wrapper&&this.animationItem.container?(P=this.animationItem.wrapper.offsetWidth,R=this.animationItem.wrapper.offsetHeight):(P=this.canvasContext.canvas.width,R=this.canvasContext.canvas.height),this.canvasContext.canvas.width=P*this.renderConfig.dpr,this.canvasContext.canvas.height=R*this.renderConfig.dpr);var A,L;if(this.renderConfig.preserveAspectRatio.indexOf("meet")!==-1||this.renderConfig.preserveAspectRatio.indexOf("slice")!==-1){var O=this.renderConfig.preserveAspectRatio.split(" "),N=O[1]||"meet",V=O[0]||"xMidYMid",j=V.substr(0,4),B=V.substr(4);A=P/R,L=this.transformCanvas.w/this.transformCanvas.h,L>A&&N==="meet"||L<A&&N==="slice"?(this.transformCanvas.sx=P/(this.transformCanvas.w/this.renderConfig.dpr),this.transformCanvas.sy=P/(this.transformCanvas.w/this.renderConfig.dpr)):(this.transformCanvas.sx=R/(this.transformCanvas.h/this.renderConfig.dpr),this.transformCanvas.sy=R/(this.transformCanvas.h/this.renderConfig.dpr)),j==="xMid"&&(L<A&&N==="meet"||L>A&&N==="slice")?this.transformCanvas.tx=(P-this.transformCanvas.w*(R/this.transformCanvas.h))/2*this.renderConfig.dpr:j==="xMax"&&(L<A&&N==="meet"||L>A&&N==="slice")?this.transformCanvas.tx=(P-this.transformCanvas.w*(R/this.transformCanvas.h))*this.renderConfig.dpr:this.transformCanvas.tx=0,B==="YMid"&&(L>A&&N==="meet"||L<A&&N==="slice")?this.transformCanvas.ty=(R-this.transformCanvas.h*(P/this.transformCanvas.w))/2*this.renderConfig.dpr:B==="YMax"&&(L>A&&N==="meet"||L<A&&N==="slice")?this.transformCanvas.ty=(R-this.transformCanvas.h*(P/this.transformCanvas.w))*this.renderConfig.dpr:this.transformCanvas.ty=0}else this.renderConfig.preserveAspectRatio==="none"?(this.transformCanvas.sx=P/(this.transformCanvas.w/this.renderConfig.dpr),this.transformCanvas.sy=R/(this.transformCanvas.h/this.renderConfig.dpr),this.transformCanvas.tx=0,this.transformCanvas.ty=0):(this.transformCanvas.sx=this.renderConfig.dpr,this.transformCanvas.sy=this.renderConfig.dpr,this.transformCanvas.tx=0,this.transformCanvas.ty=0);this.transformCanvas.props=[this.transformCanvas.sx,0,0,0,0,this.transformCanvas.sy,0,0,0,0,1,0,this.transformCanvas.tx,this.transformCanvas.ty,0,1],this.ctxTransform(this.transformCanvas.props),this.canvasContext.beginPath(),this.canvasContext.rect(0,0,this.transformCanvas.w,this.transformCanvas.h),this.canvasContext.closePath(),this.canvasContext.clip(),this.renderFrame(this.renderedFrame,!0)},CanvasRendererBase.prototype.destroy=function(){this.renderConfig.clearCanvas&&this.animationItem.wrapper&&(this.animationItem.wrapper.innerText="");var T,n=this.layers?this.layers.length:0;for(T=n-1;T>=0;T-=1)this.elements[T]&&this.elements[T].destroy&&this.elements[T].destroy();this.elements.length=0,this.globalData.canvasContext=null,this.animationItem.container=null,this.destroyed=!0},CanvasRendererBase.prototype.renderFrame=function(T,n){if(!(this.renderedFrame===T&&this.renderConfig.clearCanvas===!0&&!n||this.destroyed||T===-1)){this.renderedFrame=T,this.globalData.frameNum=T-this.animationItem._isFirstFrame,this.globalData.frameId+=1,this.globalData._mdf=!this.renderConfig.clearCanvas||n,this.globalData.projectInterface.currentFrame=T;var P,R=this.layers.length;for(this.completeLayers||this.checkLayers(T),P=R-1;P>=0;P-=1)(this.completeLayers||this.elements[P])&&this.elements[P].prepareFrame(T-this.layers[P].st);if(this.globalData._mdf){for(this.renderConfig.clearCanvas===!0?this.canvasContext.clearRect(0,0,this.transformCanvas.w,this.transformCanvas.h):this.save(),P=R-1;P>=0;P-=1)(this.completeLayers||this.elements[P])&&this.elements[P].renderFrame();this.renderConfig.clearCanvas!==!0&&this.restore()}}},CanvasRendererBase.prototype.buildItem=function(T){var n=this.elements;if(!(n[T]||this.layers[T].ty===99)){var P=this.createItem(this.layers[T],this,this.globalData);n[T]=P,P.initExpressions()}},CanvasRendererBase.prototype.checkPendingElements=function(){for(;this.pendingElements.length;){var T=this.pendingElements.pop();T.checkParenting()}},CanvasRendererBase.prototype.hide=function(){this.animationItem.container.style.display="none"},CanvasRendererBase.prototype.show=function(){this.animationItem.container.style.display="block"};function CanvasContext(){this.opacity=-1,this.transform=createTypedArray("float32",16),this.fillStyle="",this.strokeStyle="",this.lineWidth="",this.lineCap="",this.lineJoin="",this.miterLimit="",this.id=Math.random()}function CVContextData(){this.stack=[],this.cArrPos=0,this.cTr=new Matrix;var T,n=15;for(T=0;T<n;T+=1){var P=new CanvasContext;this.stack[T]=P}this._length=n,this.nativeContext=null,this.transformMat=new Matrix,this.currentOpacity=1,this.currentFillStyle="",this.appliedFillStyle="",this.currentStrokeStyle="",this.appliedStrokeStyle="",this.currentLineWidth="",this.appliedLineWidth="",this.currentLineCap="",this.appliedLineCap="",this.currentLineJoin="",this.appliedLineJoin="",this.appliedMiterLimit="",this.currentMiterLimit=""}CVContextData.prototype.duplicate=function(){var T=this._length*2,n=0;for(n=this._length;n<T;n+=1)this.stack[n]=new CanvasContext;this._length=T},CVContextData.prototype.reset=function(){this.cArrPos=0,this.cTr.reset(),this.stack[this.cArrPos].opacity=1},CVContextData.prototype.restore=function(T){this.cArrPos-=1;var n=this.stack[this.cArrPos],P=n.transform,R,A=this.cTr.props;for(R=0;R<16;R+=1)A[R]=P[R];if(T){this.nativeContext.restore();var L=this.stack[this.cArrPos+1];this.appliedFillStyle=L.fillStyle,this.appliedStrokeStyle=L.strokeStyle,this.appliedLineWidth=L.lineWidth,this.appliedLineCap=L.lineCap,this.appliedLineJoin=L.lineJoin,this.appliedMiterLimit=L.miterLimit}this.nativeContext.setTransform(P[0],P[1],P[4],P[5],P[12],P[13]),(T||n.opacity!==-1&&this.currentOpacity!==n.opacity)&&(this.nativeContext.globalAlpha=n.opacity,this.currentOpacity=n.opacity),this.currentFillStyle=n.fillStyle,this.currentStrokeStyle=n.strokeStyle,this.currentLineWidth=n.lineWidth,this.currentLineCap=n.lineCap,this.currentLineJoin=n.lineJoin,this.currentMiterLimit=n.miterLimit},CVContextData.prototype.save=function(T){T&&this.nativeContext.save();var n=this.cTr.props;this._length<=this.cArrPos&&this.duplicate();var P=this.stack[this.cArrPos],R;for(R=0;R<16;R+=1)P.transform[R]=n[R];this.cArrPos+=1;var A=this.stack[this.cArrPos];A.opacity=P.opacity,A.fillStyle=P.fillStyle,A.strokeStyle=P.strokeStyle,A.lineWidth=P.lineWidth,A.lineCap=P.lineCap,A.lineJoin=P.lineJoin,A.miterLimit=P.miterLimit},CVContextData.prototype.setOpacity=function(T){this.stack[this.cArrPos].opacity=T},CVContextData.prototype.setContext=function(T){this.nativeContext=T},CVContextData.prototype.fillStyle=function(T){this.stack[this.cArrPos].fillStyle!==T&&(this.currentFillStyle=T,this.stack[this.cArrPos].fillStyle=T)},CVContextData.prototype.strokeStyle=function(T){this.stack[this.cArrPos].strokeStyle!==T&&(this.currentStrokeStyle=T,this.stack[this.cArrPos].strokeStyle=T)},CVContextData.prototype.lineWidth=function(T){this.stack[this.cArrPos].lineWidth!==T&&(this.currentLineWidth=T,this.stack[this.cArrPos].lineWidth=T)},CVContextData.prototype.lineCap=function(T){this.stack[this.cArrPos].lineCap!==T&&(this.currentLineCap=T,this.stack[this.cArrPos].lineCap=T)},CVContextData.prototype.lineJoin=function(T){this.stack[this.cArrPos].lineJoin!==T&&(this.currentLineJoin=T,this.stack[this.cArrPos].lineJoin=T)},CVContextData.prototype.miterLimit=function(T){this.stack[this.cArrPos].miterLimit!==T&&(this.currentMiterLimit=T,this.stack[this.cArrPos].miterLimit=T)},CVContextData.prototype.transform=function(T){this.transformMat.cloneFromProps(T);var n=this.cTr;this.transformMat.multiply(n),n.cloneFromProps(this.transformMat.props);var P=n.props;this.nativeContext.setTransform(P[0],P[1],P[4],P[5],P[12],P[13])},CVContextData.prototype.opacity=function(T){var n=this.stack[this.cArrPos].opacity;n*=T<0?0:T,this.stack[this.cArrPos].opacity!==n&&(this.currentOpacity!==T&&(this.nativeContext.globalAlpha=T,this.currentOpacity=T),this.stack[this.cArrPos].opacity=n)},CVContextData.prototype.fill=function(T){this.appliedFillStyle!==this.currentFillStyle&&(this.appliedFillStyle=this.currentFillStyle,this.nativeContext.fillStyle=this.appliedFillStyle),this.nativeContext.fill(T)},CVContextData.prototype.fillRect=function(T,n,P,R){this.appliedFillStyle!==this.currentFillStyle&&(this.appliedFillStyle=this.currentFillStyle,this.nativeContext.fillStyle=this.appliedFillStyle),this.nativeContext.fillRect(T,n,P,R)},CVContextData.prototype.stroke=function(){this.appliedStrokeStyle!==this.currentStrokeStyle&&(this.appliedStrokeStyle=this.currentStrokeStyle,this.nativeContext.strokeStyle=this.appliedStrokeStyle),this.appliedLineWidth!==this.currentLineWidth&&(this.appliedLineWidth=this.currentLineWidth,this.nativeContext.lineWidth=this.appliedLineWidth),this.appliedLineCap!==this.currentLineCap&&(this.appliedLineCap=this.currentLineCap,this.nativeContext.lineCap=this.appliedLineCap),this.appliedLineJoin!==this.currentLineJoin&&(this.appliedLineJoin=this.currentLineJoin,this.nativeContext.lineJoin=this.appliedLineJoin),this.appliedMiterLimit!==this.currentMiterLimit&&(this.appliedMiterLimit=this.currentMiterLimit,this.nativeContext.miterLimit=this.appliedMiterLimit),this.nativeContext.stroke()};function CVCompElement(T,n,P){this.completeLayers=!1,this.layers=T.layers,this.pendingElements=[],this.elements=createSizedArray(this.layers.length),this.initElement(T,n,P),this.tm=T.tm?PropertyFactory.getProp(this,T.tm,0,n.frameRate,this):{_placeholder:!0}}extendPrototype([CanvasRendererBase,ICompElement,CVBaseElement],CVCompElement),CVCompElement.prototype.renderInnerContent=function(){var T=this.canvasContext;T.beginPath(),T.moveTo(0,0),T.lineTo(this.data.w,0),T.lineTo(this.data.w,this.data.h),T.lineTo(0,this.data.h),T.lineTo(0,0),T.clip();var n,P=this.layers.length;for(n=P-1;n>=0;n-=1)(this.completeLayers||this.elements[n])&&this.elements[n].renderFrame()},CVCompElement.prototype.destroy=function(){var T,n=this.layers.length;for(T=n-1;T>=0;T-=1)this.elements[T]&&this.elements[T].destroy();this.layers=null,this.elements=null},CVCompElement.prototype.createComp=function(T){return new CVCompElement(T,this.globalData,this)};function CanvasRenderer(T,n){this.animationItem=T,this.renderConfig={clearCanvas:n&&n.clearCanvas!==void 0?n.clearCanvas:!0,context:n&&n.context||null,progressiveLoad:n&&n.progressiveLoad||!1,preserveAspectRatio:n&&n.preserveAspectRatio||"xMidYMid meet",imagePreserveAspectRatio:n&&n.imagePreserveAspectRatio||"xMidYMid slice",contentVisibility:n&&n.contentVisibility||"visible",className:n&&n.className||"",id:n&&n.id||"",runExpressions:!n||n.runExpressions===void 0||n.runExpressions},this.renderConfig.dpr=n&&n.dpr||1,this.animationItem.wrapper&&(this.renderConfig.dpr=n&&n.dpr||window.devicePixelRatio||1),this.renderedFrame=-1,this.globalData={frameNum:-1,_mdf:!1,renderConfig:this.renderConfig,currentGlobalAlpha:-1},this.contextData=new CVContextData,this.elements=[],this.pendingElements=[],this.transformMat=new Matrix,this.completeLayers=!1,this.rendererType="canvas",this.renderConfig.clearCanvas&&(this.ctxTransform=this.contextData.transform.bind(this.contextData),this.ctxOpacity=this.contextData.opacity.bind(this.contextData),this.ctxFillStyle=this.contextData.fillStyle.bind(this.contextData),this.ctxStrokeStyle=this.contextData.strokeStyle.bind(this.contextData),this.ctxLineWidth=this.contextData.lineWidth.bind(this.contextData),this.ctxLineCap=this.contextData.lineCap.bind(this.contextData),this.ctxLineJoin=this.contextData.lineJoin.bind(this.contextData),this.ctxMiterLimit=this.contextData.miterLimit.bind(this.contextData),this.ctxFill=this.contextData.fill.bind(this.contextData),this.ctxFillRect=this.contextData.fillRect.bind(this.contextData),this.ctxStroke=this.contextData.stroke.bind(this.contextData),this.save=this.contextData.save.bind(this.contextData))}extendPrototype([CanvasRendererBase],CanvasRenderer),CanvasRenderer.prototype.createComp=function(T){return new CVCompElement(T,this.globalData,this)};function HBaseElement(){}HBaseElement.prototype={checkBlendMode:function(){},initRendererElement:function(){this.baseElement=createTag(this.data.tg||"div"),this.data.hasMask?(this.svgElement=createNS("svg"),this.layerElement=createNS("g"),this.maskedElement=this.layerElement,this.svgElement.appendChild(this.layerElement),this.baseElement.appendChild(this.svgElement)):this.layerElement=this.baseElement,styleDiv(this.baseElement)},createContainerElements:function(){this.renderableEffectsManager=new CVEffects(this),this.transformedElement=this.baseElement,this.maskedElement=this.layerElement,this.data.ln&&this.layerElement.setAttribute("id",this.data.ln),this.data.cl&&this.layerElement.setAttribute("class",this.data.cl),this.data.bm!==0&&this.setBlendMode()},renderElement:function(){var n=this.transformedElement?this.transformedElement.style:{};if(this.finalTransform._matMdf){var P=this.finalTransform.mat.toCSS();n.transform=P,n.webkitTransform=P}this.finalTransform._opMdf&&(n.opacity=this.finalTransform.mProp.o.v)},renderFrame:function(){this.data.hd||this.hidden||(this.renderTransform(),this.renderRenderable(),this.renderElement(),this.renderInnerContent(),this._isFirstFrame&&(this._isFirstFrame=!1))},destroy:function(){this.layerElement=null,this.transformedElement=null,this.matteElement&&(this.matteElement=null),this.maskManager&&(this.maskManager.destroy(),this.maskManager=null)},createRenderableComponents:function(){this.maskManager=new MaskElement(this.data,this,this.globalData)},addEffects:function(){},setMatte:function(){}},HBaseElement.prototype.getBaseElement=SVGBaseElement.prototype.getBaseElement,HBaseElement.prototype.destroyBaseElement=HBaseElement.prototype.destroy,HBaseElement.prototype.buildElementParenting=BaseRenderer.prototype.buildElementParenting;function HSolidElement(T,n,P){this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,HBaseElement,HierarchyElement,FrameElement,RenderableDOMElement],HSolidElement),HSolidElement.prototype.createContent=function(){var T;this.data.hasMask?(T=createNS("rect"),T.setAttribute("width",this.data.sw),T.setAttribute("height",this.data.sh),T.setAttribute("fill",this.data.sc),this.svgElement.setAttribute("width",this.data.sw),this.svgElement.setAttribute("height",this.data.sh)):(T=createTag("div"),T.style.width=this.data.sw+"px",T.style.height=this.data.sh+"px",T.style.backgroundColor=this.data.sc),this.layerElement.appendChild(T)};function HShapeElement(T,n,P){this.shapes=[],this.shapesData=T.shapes,this.stylesList=[],this.shapeModifiers=[],this.itemsData=[],this.processedElements=[],this.animatedContents=[],this.shapesContainer=createNS("g"),this.initElement(T,n,P),this.prevViewData=[],this.currentBBox={x:999999,y:-999999,h:0,w:0}}extendPrototype([BaseElement,TransformElement,HSolidElement,SVGShapeElement,HBaseElement,HierarchyElement,FrameElement,RenderableElement],HShapeElement),HShapeElement.prototype._renderShapeFrame=HShapeElement.prototype.renderInnerContent,HShapeElement.prototype.createContent=function(){var T;if(this.baseElement.style.fontSize=0,this.data.hasMask)this.layerElement.appendChild(this.shapesContainer),T=this.svgElement;else{T=createNS("svg");var n=this.comp.data?this.comp.data:this.globalData.compSize;T.setAttribute("width",n.w),T.setAttribute("height",n.h),T.appendChild(this.shapesContainer),this.layerElement.appendChild(T)}this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.shapesContainer,0,[],!0),this.filterUniqueShapes(),this.shapeCont=T},HShapeElement.prototype.getTransformedPoint=function(T,n){var P,R=T.length;for(P=0;P<R;P+=1)n=T[P].mProps.v.applyToPointArray(n[0],n[1],0);return n},HShapeElement.prototype.calculateShapeBoundingBox=function(T,n){var P=T.sh.v,R=T.transformers,A,L=P._length,O,N,V,j;if(!(L<=1)){for(A=0;A<L-1;A+=1)O=this.getTransformedPoint(R,P.v[A]),N=this.getTransformedPoint(R,P.o[A]),V=this.getTransformedPoint(R,P.i[A+1]),j=this.getTransformedPoint(R,P.v[A+1]),this.checkBounds(O,N,V,j,n);P.c&&(O=this.getTransformedPoint(R,P.v[A]),N=this.getTransformedPoint(R,P.o[A]),V=this.getTransformedPoint(R,P.i[0]),j=this.getTransformedPoint(R,P.v[0]),this.checkBounds(O,N,V,j,n))}},HShapeElement.prototype.checkBounds=function(T,n,P,R,A){this.getBoundsOfCurve(T,n,P,R);var L=this.shapeBoundingBox;A.x=bmMin(L.left,A.x),A.xMax=bmMax(L.right,A.xMax),A.y=bmMin(L.top,A.y),A.yMax=bmMax(L.bottom,A.yMax)},HShapeElement.prototype.shapeBoundingBox={left:0,right:0,top:0,bottom:0},HShapeElement.prototype.tempBoundingBox={x:0,xMax:0,y:0,yMax:0,width:0,height:0},HShapeElement.prototype.getBoundsOfCurve=function(T,n,P,R){for(var A=[[T[0],R[0]],[T[1],R[1]]],L,O,N,V,j,B,z,W=0;W<2;++W)O=6*T[W]-12*n[W]+6*P[W],L=-3*T[W]+9*n[W]-9*P[W]+3*R[W],N=3*n[W]-3*T[W],O|=0,L|=0,N|=0,L===0&&O===0||(L===0?(V=-N/O,V>0&&V<1&&A[W].push(this.calculateF(V,T,n,P,R,W))):(j=O*O-4*N*L,j>=0&&(B=(-O+bmSqrt(j))/(2*L),B>0&&B<1&&A[W].push(this.calculateF(B,T,n,P,R,W)),z=(-O-bmSqrt(j))/(2*L),z>0&&z<1&&A[W].push(this.calculateF(z,T,n,P,R,W)))));this.shapeBoundingBox.left=bmMin.apply(null,A[0]),this.shapeBoundingBox.top=bmMin.apply(null,A[1]),this.shapeBoundingBox.right=bmMax.apply(null,A[0]),this.shapeBoundingBox.bottom=bmMax.apply(null,A[1])},HShapeElement.prototype.calculateF=function(T,n,P,R,A,L){return bmPow(1-T,3)*n[L]+3*bmPow(1-T,2)*T*P[L]+3*(1-T)*bmPow(T,2)*R[L]+bmPow(T,3)*A[L]},HShapeElement.prototype.calculateBoundingBox=function(T,n){var P,R=T.length;for(P=0;P<R;P+=1)T[P]&&T[P].sh?this.calculateShapeBoundingBox(T[P],n):T[P]&&T[P].it?this.calculateBoundingBox(T[P].it,n):T[P]&&T[P].style&&T[P].w&&this.expandStrokeBoundingBox(T[P].w,n)},HShapeElement.prototype.expandStrokeBoundingBox=function(T,n){var P=0;if(T.keyframes){for(var R=0;R<T.keyframes.length;R+=1){var A=T.keyframes[R].s;A>P&&(P=A)}P*=T.mult}else P=T.v*T.mult;n.x-=P,n.xMax+=P,n.y-=P,n.yMax+=P},HShapeElement.prototype.currentBoxContains=function(T){return this.currentBBox.x<=T.x&&this.currentBBox.y<=T.y&&this.currentBBox.width+this.currentBBox.x>=T.x+T.width&&this.currentBBox.height+this.currentBBox.y>=T.y+T.height},HShapeElement.prototype.renderInnerContent=function(){if(this._renderShapeFrame(),!this.hidden&&(this._isFirstFrame||this._mdf)){var T=this.tempBoundingBox,n=999999;if(T.x=n,T.xMax=-n,T.y=n,T.yMax=-n,this.calculateBoundingBox(this.itemsData,T),T.width=T.xMax<T.x?0:T.xMax-T.x,T.height=T.yMax<T.y?0:T.yMax-T.y,this.currentBoxContains(T))return;var P=!1;if(this.currentBBox.w!==T.width&&(this.currentBBox.w=T.width,this.shapeCont.setAttribute("width",T.width),P=!0),this.currentBBox.h!==T.height&&(this.currentBBox.h=T.height,this.shapeCont.setAttribute("height",T.height),P=!0),P||this.currentBBox.x!==T.x||this.currentBBox.y!==T.y){this.currentBBox.w=T.width,this.currentBBox.h=T.height,this.currentBBox.x=T.x,this.currentBBox.y=T.y,this.shapeCont.setAttribute("viewBox",this.currentBBox.x+" "+this.currentBBox.y+" "+this.currentBBox.w+" "+this.currentBBox.h);var R=this.shapeCont.style,A="translate("+this.currentBBox.x+"px,"+this.currentBBox.y+"px)";R.transform=A,R.webkitTransform=A}}};function HTextElement(T,n,P){this.textSpans=[],this.textPaths=[],this.currentBBox={x:999999,y:-999999,h:0,w:0},this.renderType="svg",this.isMasked=!1,this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,HBaseElement,HierarchyElement,FrameElement,RenderableDOMElement,ITextElement],HTextElement),HTextElement.prototype.createContent=function(){if(this.isMasked=this.checkMasks(),this.isMasked){this.renderType="svg",this.compW=this.comp.data.w,this.compH=this.comp.data.h,this.svgElement.setAttribute("width",this.compW),this.svgElement.setAttribute("height",this.compH);var T=createNS("g");this.maskedElement.appendChild(T),this.innerElem=T}else this.renderType="html",this.innerElem=this.layerElement;this.checkParenting()},HTextElement.prototype.buildNewText=function(){var T=this.textProperty.currentData;this.renderedLetters=createSizedArray(T.l?T.l.length:0);var n=this.innerElem.style,P=T.fc?this.buildColor(T.fc):"rgba(0,0,0,0)";n.fill=P,n.color=P,T.sc&&(n.stroke=this.buildColor(T.sc),n.strokeWidth=T.sw+"px");var R=this.globalData.fontManager.getFontByName(T.f);if(!this.globalData.fontManager.chars)if(n.fontSize=T.finalSize+"px",n.lineHeight=T.finalSize+"px",R.fClass)this.innerElem.className=R.fClass;else{n.fontFamily=R.fFamily;var A=T.fWeight,L=T.fStyle;n.fontStyle=L,n.fontWeight=A}var O,N,V=T.l;N=V.length;var j,B,z,W=this.mHelper,q,H="",$=0;for(O=0;O<N;O+=1){if(this.globalData.fontManager.chars?(this.textPaths[$]?j=this.textPaths[$]:(j=createNS("path"),j.setAttribute("stroke-linecap",lineCapEnum[1]),j.setAttribute("stroke-linejoin",lineJoinEnum[2]),j.setAttribute("stroke-miterlimit","4")),this.isMasked||(this.textSpans[$]?(B=this.textSpans[$],z=B.children[0]):(B=createTag("div"),B.style.lineHeight=0,z=createNS("svg"),z.appendChild(j),styleDiv(B)))):this.isMasked?j=this.textPaths[$]?this.textPaths[$]:createNS("text"):this.textSpans[$]?(B=this.textSpans[$],j=this.textPaths[$]):(B=createTag("span"),styleDiv(B),j=createTag("span"),styleDiv(j),B.appendChild(j)),this.globalData.fontManager.chars){var Q=this.globalData.fontManager.getCharData(T.finalText[O],R.fStyle,this.globalData.fontManager.getFontByName(T.f).fFamily),U;if(Q?U=Q.data:U=null,W.reset(),U&&U.shapes&&U.shapes.length&&(q=U.shapes[0].it,W.scale(T.finalSize/100,T.finalSize/100),H=this.createPathShape(W,q),j.setAttribute("d",H)),this.isMasked)this.innerElem.appendChild(j);else{if(this.innerElem.appendChild(B),U&&U.shapes){document.body.appendChild(z);var J=z.getBBox();z.setAttribute("width",J.width+2),z.setAttribute("height",J.height+2),z.setAttribute("viewBox",J.x-1+" "+(J.y-1)+" "+(J.width+2)+" "+(J.height+2));var G=z.style,K="translate("+(J.x-1)+"px,"+(J.y-1)+"px)";G.transform=K,G.webkitTransform=K,V[O].yOffset=J.y-1}else z.setAttribute("width",1),z.setAttribute("height",1);B.appendChild(z)}}else if(j.textContent=V[O].val,j.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),this.isMasked)this.innerElem.appendChild(j);else{this.innerElem.appendChild(B);var Y=j.style,Z="translate3d(0,"+-T.finalSize/1.2+"px,0)";Y.transform=Z,Y.webkitTransform=Z}this.isMasked?this.textSpans[$]=j:this.textSpans[$]=B,this.textSpans[$].style.display="block",this.textPaths[$]=j,$+=1}for(;$<this.textSpans.length;)this.textSpans[$].style.display="none",$+=1},HTextElement.prototype.renderInnerContent=function(){this.validateText();var T;if(this.data.singleShape){if(!this._isFirstFrame&&!this.lettersChangedFlag)return;if(this.isMasked&&this.finalTransform._matMdf){this.svgElement.setAttribute("viewBox",-this.finalTransform.mProp.p.v[0]+" "+-this.finalTransform.mProp.p.v[1]+" "+this.compW+" "+this.compH),T=this.svgElement.style;var n="translate("+-this.finalTransform.mProp.p.v[0]+"px,"+-this.finalTransform.mProp.p.v[1]+"px)";T.transform=n,T.webkitTransform=n}}if(this.textAnimator.getMeasures(this.textProperty.currentData,this.lettersChangedFlag),!(!this.lettersChangedFlag&&!this.textAnimator.lettersChangedFlag)){var P,R,A=0,L=this.textAnimator.renderedLetters,O=this.textProperty.currentData.l;R=O.length;var N,V,j;for(P=0;P<R;P+=1)O[P].n?A+=1:(V=this.textSpans[P],j=this.textPaths[P],N=L[A],A+=1,N._mdf.m&&(this.isMasked?V.setAttribute("transform",N.m):(V.style.webkitTransform=N.m,V.style.transform=N.m)),V.style.opacity=N.o,N.sw&&N._mdf.sw&&j.setAttribute("stroke-width",N.sw),N.sc&&N._mdf.sc&&j.setAttribute("stroke",N.sc),N.fc&&N._mdf.fc&&(j.setAttribute("fill",N.fc),j.style.color=N.fc));if(this.innerElem.getBBox&&!this.hidden&&(this._isFirstFrame||this._mdf)){var B=this.innerElem.getBBox();this.currentBBox.w!==B.width&&(this.currentBBox.w=B.width,this.svgElement.setAttribute("width",B.width)),this.currentBBox.h!==B.height&&(this.currentBBox.h=B.height,this.svgElement.setAttribute("height",B.height));var z=1;if(this.currentBBox.w!==B.width+z*2||this.currentBBox.h!==B.height+z*2||this.currentBBox.x!==B.x-z||this.currentBBox.y!==B.y-z){this.currentBBox.w=B.width+z*2,this.currentBBox.h=B.height+z*2,this.currentBBox.x=B.x-z,this.currentBBox.y=B.y-z,this.svgElement.setAttribute("viewBox",this.currentBBox.x+" "+this.currentBBox.y+" "+this.currentBBox.w+" "+this.currentBBox.h),T=this.svgElement.style;var W="translate("+this.currentBBox.x+"px,"+this.currentBBox.y+"px)";T.transform=W,T.webkitTransform=W}}}};function HCameraElement(T,n,P){this.initFrame(),this.initBaseData(T,n,P),this.initHierarchy();var R=PropertyFactory.getProp;if(this.pe=R(this,T.pe,0,0,this),T.ks.p.s?(this.px=R(this,T.ks.p.x,1,0,this),this.py=R(this,T.ks.p.y,1,0,this),this.pz=R(this,T.ks.p.z,1,0,this)):this.p=R(this,T.ks.p,1,0,this),T.ks.a&&(this.a=R(this,T.ks.a,1,0,this)),T.ks.or.k.length&&T.ks.or.k[0].to){var A,L=T.ks.or.k.length;for(A=0;A<L;A+=1)T.ks.or.k[A].to=null,T.ks.or.k[A].ti=null}this.or=R(this,T.ks.or,1,degToRads,this),this.or.sh=!0,this.rx=R(this,T.ks.rx,0,degToRads,this),this.ry=R(this,T.ks.ry,0,degToRads,this),this.rz=R(this,T.ks.rz,0,degToRads,this),this.mat=new Matrix,this._prevMat=new Matrix,this._isFirstFrame=!0,this.finalTransform={mProp:this}}extendPrototype([BaseElement,FrameElement,HierarchyElement],HCameraElement),HCameraElement.prototype.setup=function(){var T,n=this.comp.threeDElements.length,P,R,A;for(T=0;T<n;T+=1)if(P=this.comp.threeDElements[T],P.type==="3d"){R=P.perspectiveElem.style,A=P.container.style;var L=this.pe.v+"px",O="0px 0px 0px",N="matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)";R.perspective=L,R.webkitPerspective=L,A.transformOrigin=O,A.mozTransformOrigin=O,A.webkitTransformOrigin=O,R.transform=N,R.webkitTransform=N}},HCameraElement.prototype.createElements=function(){},HCameraElement.prototype.hide=function(){},HCameraElement.prototype.renderFrame=function(){var T=this._isFirstFrame,n,P;if(this.hierarchy)for(P=this.hierarchy.length,n=0;n<P;n+=1)T=this.hierarchy[n].finalTransform.mProp._mdf||T;if(T||this.pe._mdf||this.p&&this.p._mdf||this.px&&(this.px._mdf||this.py._mdf||this.pz._mdf)||this.rx._mdf||this.ry._mdf||this.rz._mdf||this.or._mdf||this.a&&this.a._mdf){if(this.mat.reset(),this.hierarchy)for(P=this.hierarchy.length-1,n=P;n>=0;n-=1){var R=this.hierarchy[n].finalTransform.mProp;this.mat.translate(-R.p.v[0],-R.p.v[1],R.p.v[2]),this.mat.rotateX(-R.or.v[0]).rotateY(-R.or.v[1]).rotateZ(R.or.v[2]),this.mat.rotateX(-R.rx.v).rotateY(-R.ry.v).rotateZ(R.rz.v),this.mat.scale(1/R.s.v[0],1/R.s.v[1],1/R.s.v[2]),this.mat.translate(R.a.v[0],R.a.v[1],R.a.v[2])}if(this.p?this.mat.translate(-this.p.v[0],-this.p.v[1],this.p.v[2]):this.mat.translate(-this.px.v,-this.py.v,this.pz.v),this.a){var A;this.p?A=[this.p.v[0]-this.a.v[0],this.p.v[1]-this.a.v[1],this.p.v[2]-this.a.v[2]]:A=[this.px.v-this.a.v[0],this.py.v-this.a.v[1],this.pz.v-this.a.v[2]];var L=Math.sqrt(Math.pow(A[0],2)+Math.pow(A[1],2)+Math.pow(A[2],2)),O=[A[0]/L,A[1]/L,A[2]/L],N=Math.sqrt(O[2]*O[2]+O[0]*O[0]),V=Math.atan2(O[1],N),j=Math.atan2(O[0],-O[2]);this.mat.rotateY(j).rotateX(-V)}this.mat.rotateX(-this.rx.v).rotateY(-this.ry.v).rotateZ(this.rz.v),this.mat.rotateX(-this.or.v[0]).rotateY(-this.or.v[1]).rotateZ(this.or.v[2]),this.mat.translate(this.globalData.compSize.w/2,this.globalData.compSize.h/2,0),this.mat.translate(0,0,this.pe.v);var B=!this._prevMat.equals(this.mat);if((B||this.pe._mdf)&&this.comp.threeDElements){P=this.comp.threeDElements.length;var z,W,q;for(n=0;n<P;n+=1)if(z=this.comp.threeDElements[n],z.type==="3d"){if(B){var H=this.mat.toCSS();q=z.container.style,q.transform=H,q.webkitTransform=H}this.pe._mdf&&(W=z.perspectiveElem.style,W.perspective=this.pe.v+"px",W.webkitPerspective=this.pe.v+"px")}this.mat.clone(this._prevMat)}}this._isFirstFrame=!1},HCameraElement.prototype.prepareFrame=function(T){this.prepareProperties(T,!0)},HCameraElement.prototype.destroy=function(){},HCameraElement.prototype.getBaseElement=function(){return null};function HImageElement(T,n,P){this.assetData=n.getAssetData(T.refId),this.initElement(T,n,P)}extendPrototype([BaseElement,TransformElement,HBaseElement,HSolidElement,HierarchyElement,FrameElement,RenderableElement],HImageElement),HImageElement.prototype.createContent=function(){var T=this.globalData.getAssetsPath(this.assetData),n=new Image;this.data.hasMask?(this.imageElem=createNS("image"),this.imageElem.setAttribute("width",this.assetData.w+"px"),this.imageElem.setAttribute("height",this.assetData.h+"px"),this.imageElem.setAttributeNS("http://www.w3.org/1999/xlink","href",T),this.layerElement.appendChild(this.imageElem),this.baseElement.setAttribute("width",this.assetData.w),this.baseElement.setAttribute("height",this.assetData.h)):this.layerElement.appendChild(n),n.crossOrigin="anonymous",n.src=T,this.data.ln&&this.baseElement.setAttribute("id",this.data.ln)};function HybridRendererBase(T,n){this.animationItem=T,this.layers=null,this.renderedFrame=-1,this.renderConfig={className:n&&n.className||"",imagePreserveAspectRatio:n&&n.imagePreserveAspectRatio||"xMidYMid slice",hideOnTransparent:!(n&&n.hideOnTransparent===!1),filterSize:{width:n&&n.filterSize&&n.filterSize.width||"400%",height:n&&n.filterSize&&n.filterSize.height||"400%",x:n&&n.filterSize&&n.filterSize.x||"-100%",y:n&&n.filterSize&&n.filterSize.y||"-100%"}},this.globalData={_mdf:!1,frameNum:-1,renderConfig:this.renderConfig},this.pendingElements=[],this.elements=[],this.threeDElements=[],this.destroyed=!1,this.camera=null,this.supports3d=!0,this.rendererType="html"}extendPrototype([BaseRenderer],HybridRendererBase),HybridRendererBase.prototype.buildItem=SVGRenderer.prototype.buildItem,HybridRendererBase.prototype.checkPendingElements=function(){for(;this.pendingElements.length;){var T=this.pendingElements.pop();T.checkParenting()}},HybridRendererBase.prototype.appendElementInPos=function(T,n){var P=T.getBaseElement();if(P){var R=this.layers[n];if(!R.ddd||!this.supports3d)if(this.threeDElements)this.addTo3dContainer(P,n);else{for(var A=0,L,O,N;A<n;)this.elements[A]&&this.elements[A]!==!0&&this.elements[A].getBaseElement&&(O=this.elements[A],N=this.layers[A].ddd?this.getThreeDContainerByPos(A):O.getBaseElement(),L=N||L),A+=1;L?(!R.ddd||!this.supports3d)&&this.layerElement.insertBefore(P,L):(!R.ddd||!this.supports3d)&&this.layerElement.appendChild(P)}else this.addTo3dContainer(P,n)}},HybridRendererBase.prototype.createShape=function(T){return this.supports3d?new HShapeElement(T,this.globalData,this):new SVGShapeElement(T,this.globalData,this)},HybridRendererBase.prototype.createText=function(T){return this.supports3d?new HTextElement(T,this.globalData,this):new SVGTextLottieElement(T,this.globalData,this)},HybridRendererBase.prototype.createCamera=function(T){return this.camera=new HCameraElement(T,this.globalData,this),this.camera},HybridRendererBase.prototype.createImage=function(T){return this.supports3d?new HImageElement(T,this.globalData,this):new IImageElement(T,this.globalData,this)},HybridRendererBase.prototype.createSolid=function(T){return this.supports3d?new HSolidElement(T,this.globalData,this):new ISolidElement(T,this.globalData,this)},HybridRendererBase.prototype.createNull=SVGRenderer.prototype.createNull,HybridRendererBase.prototype.getThreeDContainerByPos=function(T){for(var n=0,P=this.threeDElements.length;n<P;){if(this.threeDElements[n].startPos<=T&&this.threeDElements[n].endPos>=T)return this.threeDElements[n].perspectiveElem;n+=1}return null},HybridRendererBase.prototype.createThreeDContainer=function(T,n){var P=createTag("div"),R,A;styleDiv(P);var L=createTag("div");if(styleDiv(L),n==="3d"){R=P.style,R.width=this.globalData.compSize.w+"px",R.height=this.globalData.compSize.h+"px";var O="50% 50%";R.webkitTransformOrigin=O,R.mozTransformOrigin=O,R.transformOrigin=O,A=L.style;var N="matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)";A.transform=N,A.webkitTransform=N}P.appendChild(L);var V={container:L,perspectiveElem:P,startPos:T,endPos:T,type:n};return this.threeDElements.push(V),V},HybridRendererBase.prototype.build3dContainers=function(){var T,n=this.layers.length,P,R="";for(T=0;T<n;T+=1)this.layers[T].ddd&&this.layers[T].ty!==3?(R!=="3d"&&(R="3d",P=this.createThreeDContainer(T,"3d")),P.endPos=Math.max(P.endPos,T)):(R!=="2d"&&(R="2d",P=this.createThreeDContainer(T,"2d")),P.endPos=Math.max(P.endPos,T));for(n=this.threeDElements.length,T=n-1;T>=0;T-=1)this.resizerElem.appendChild(this.threeDElements[T].perspectiveElem)},HybridRendererBase.prototype.addTo3dContainer=function(T,n){for(var P=0,R=this.threeDElements.length;P<R;){if(n<=this.threeDElements[P].endPos){for(var A=this.threeDElements[P].startPos,L;A<n;)this.elements[A]&&this.elements[A].getBaseElement&&(L=this.elements[A].getBaseElement()),A+=1;L?this.threeDElements[P].container.insertBefore(T,L):this.threeDElements[P].container.appendChild(T);break}P+=1}},HybridRendererBase.prototype.configAnimation=function(T){var n=createTag("div"),P=this.animationItem.wrapper,R=n.style;R.width=T.w+"px",R.height=T.h+"px",this.resizerElem=n,styleDiv(n),R.transformStyle="flat",R.mozTransformStyle="flat",R.webkitTransformStyle="flat",this.renderConfig.className&&n.setAttribute("class",this.renderConfig.className),P.appendChild(n),R.overflow="hidden";var A=createNS("svg");A.setAttribute("width","1"),A.setAttribute("height","1"),styleDiv(A),this.resizerElem.appendChild(A);var L=createNS("defs");A.appendChild(L),this.data=T,this.setupGlobalData(T,A),this.globalData.defs=L,this.layers=T.layers,this.layerElement=this.resizerElem,this.build3dContainers(),this.updateContainerSize()},HybridRendererBase.prototype.destroy=function(){this.animationItem.wrapper&&(this.animationItem.wrapper.innerText=""),this.animationItem.container=null,this.globalData.defs=null;var T,n=this.layers?this.layers.length:0;for(T=0;T<n;T+=1)this.elements[T]&&this.elements[T].destroy&&this.elements[T].destroy();this.elements.length=0,this.destroyed=!0,this.animationItem=null},HybridRendererBase.prototype.updateContainerSize=function(){var T=this.animationItem.wrapper.offsetWidth,n=this.animationItem.wrapper.offsetHeight,P=T/n,R=this.globalData.compSize.w/this.globalData.compSize.h,A,L,O,N;R>P?(A=T/this.globalData.compSize.w,L=T/this.globalData.compSize.w,O=0,N=(n-this.globalData.compSize.h*(T/this.globalData.compSize.w))/2):(A=n/this.globalData.compSize.h,L=n/this.globalData.compSize.h,O=(T-this.globalData.compSize.w*(n/this.globalData.compSize.h))/2,N=0);var V=this.resizerElem.style;V.webkitTransform="matrix3d("+A+",0,0,0,0,"+L+",0,0,0,0,1,0,"+O+","+N+",0,1)",V.transform=V.webkitTransform},HybridRendererBase.prototype.renderFrame=SVGRenderer.prototype.renderFrame,HybridRendererBase.prototype.hide=function(){this.resizerElem.style.display="none"},HybridRendererBase.prototype.show=function(){this.resizerElem.style.display="block"},HybridRendererBase.prototype.initItems=function(){if(this.buildAllItems(),this.camera)this.camera.setup();else{var T=this.globalData.compSize.w,n=this.globalData.compSize.h,P,R=this.threeDElements.length;for(P=0;P<R;P+=1){var A=this.threeDElements[P].perspectiveElem.style;A.webkitPerspective=Math.sqrt(Math.pow(T,2)+Math.pow(n,2))+"px",A.perspective=A.webkitPerspective}}},HybridRendererBase.prototype.searchExtraCompositions=function(T){var n,P=T.length,R=createTag("div");for(n=0;n<P;n+=1)if(T[n].xt){var A=this.createComp(T[n],R,this.globalData.comp,null);A.initExpressions(),this.globalData.projectInterface.registerComposition(A)}};function HCompElement(T,n,P){this.layers=T.layers,this.supports3d=!T.hasMask,this.completeLayers=!1,this.pendingElements=[],this.elements=this.layers?createSizedArray(this.layers.length):[],this.initElement(T,n,P),this.tm=T.tm?PropertyFactory.getProp(this,T.tm,0,n.frameRate,this):{_placeholder:!0}}extendPrototype([HybridRendererBase,ICompElement,HBaseElement],HCompElement),HCompElement.prototype._createBaseContainerElements=HCompElement.prototype.createContainerElements,HCompElement.prototype.createContainerElements=function(){this._createBaseContainerElements(),this.data.hasMask?(this.svgElement.setAttribute("width",this.data.w),this.svgElement.setAttribute("height",this.data.h),this.transformedElement=this.baseElement):this.transformedElement=this.layerElement},HCompElement.prototype.addTo3dContainer=function(T,n){for(var P=0,R;P<n;)this.elements[P]&&this.elements[P].getBaseElement&&(R=this.elements[P].getBaseElement()),P+=1;R?this.layerElement.insertBefore(T,R):this.layerElement.appendChild(T)},HCompElement.prototype.createComp=function(T){return this.supports3d?new HCompElement(T,this.globalData,this):new SVGCompElement(T,this.globalData,this)};function HybridRenderer(T,n){this.animationItem=T,this.layers=null,this.renderedFrame=-1,this.renderConfig={className:n&&n.className||"",imagePreserveAspectRatio:n&&n.imagePreserveAspectRatio||"xMidYMid slice",hideOnTransparent:!(n&&n.hideOnTransparent===!1),filterSize:{width:n&&n.filterSize&&n.filterSize.width||"400%",height:n&&n.filterSize&&n.filterSize.height||"400%",x:n&&n.filterSize&&n.filterSize.x||"-100%",y:n&&n.filterSize&&n.filterSize.y||"-100%"},runExpressions:!n||n.runExpressions===void 0||n.runExpressions},this.globalData={_mdf:!1,frameNum:-1,renderConfig:this.renderConfig},this.pendingElements=[],this.elements=[],this.threeDElements=[],this.destroyed=!1,this.camera=null,this.supports3d=!0,this.rendererType="html"}extendPrototype([HybridRendererBase],HybridRenderer),HybridRenderer.prototype.createComp=function(T){return this.supports3d?new HCompElement(T,this.globalData,this):new SVGCompElement(T,this.globalData,this)};var CompExpressionInterface=(function(){return function(T){function n(P){for(var R=0,A=T.layers.length;R<A;){if(T.layers[R].nm===P||T.layers[R].ind===P)return T.elements[R].layerInterface;R+=1}return null}return Object.defineProperty(n,"_name",{value:T.data.nm}),n.layer=n,n.pixelAspect=1,n.height=T.data.h||T.globalData.compSize.h,n.width=T.data.w||T.globalData.compSize.w,n.pixelAspect=1,n.frameDuration=1/T.globalData.frameRate,n.displayStartTime=0,n.numLayers=T.layers.length,n}})();function _typeof$2(T){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof$2(T)}function seedRandom(T,n){var P=this,R=256,A=6,L=52,O="random",N=n.pow(R,A),V=n.pow(2,L),j=V*2,B=R-1,z;function W(G,K,Y){var Z=[];K=K===!0?{entropy:!0}:K||{};var ie=Q($(K.entropy?[G,J(T)]:G===null?U():G,3),Z),se=new q(Z),le=function(){for(var ue=se.g(A),he=N,ve=0;ue<V;)ue=(ue+ve)*R,he*=R,ve=se.g(1);for(;ue>=j;)ue/=2,he/=2,ve>>>=1;return(ue+ve)/he};return le.int32=function(){return se.g(4)|0},le.quick=function(){return se.g(4)/4294967296},le.double=le,Q(J(se.S),T),(K.pass||Y||function(pe,ue,he,ve){return ve&&(ve.S&&H(ve,se),pe.state=function(){return H(se,{})}),he?(n[O]=pe,ue):pe})(le,ie,"global"in K?K.global:this==n,K.state)}n["seed"+O]=W;function q(G){var K,Y=G.length,Z=this,ie=0,se=Z.i=Z.j=0,le=Z.S=[];for(Y||(G=[Y++]);ie<R;)le[ie]=ie++;for(ie=0;ie<R;ie++)le[ie]=le[se=B&se+G[ie%Y]+(K=le[ie])],le[se]=K;Z.g=function(pe){for(var ue,he=0,ve=Z.i,be=Z.j,fe=Z.S;pe--;)ue=fe[ve=B&ve+1],he=he*R+fe[B&(fe[ve]=fe[be=B&be+ue])+(fe[be]=ue)];return Z.i=ve,Z.j=be,he}}function H(G,K){return K.i=G.i,K.j=G.j,K.S=G.S.slice(),K}function $(G,K){var Y=[],Z=_typeof$2(G),ie;if(K&&Z=="object")for(ie in G)try{Y.push($(G[ie],K-1))}catch{}return Y.length?Y:Z=="string"?G:G+"\0"}function Q(G,K){for(var Y=G+"",Z,ie=0;ie<Y.length;)K[B&ie]=B&(Z^=K[B&ie]*19)+Y.charCodeAt(ie++);return J(K)}function U(){try{var G=new Uint8Array(R);return(P.crypto||P.msCrypto).getRandomValues(G),J(G)}catch{var K=P.navigator,Y=K&&K.plugins;return[+new Date,P,Y,P.screen,J(T)]}}function J(G){return String.fromCharCode.apply(0,G)}Q(n.random(),T)}function initialize$2(T){seedRandom([],T)}var propTypes={SHAPE:"shape"};function _typeof$1(T){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof$1(T)}var ExpressionManager=(function(){var ob={},Math=BMMath,window=null,document=null,XMLHttpRequest=null,fetch=null,frames=null,_lottieGlobal={};initialize$2(BMMath);function resetFrame(){_lottieGlobal={}}function $bm_isInstanceOfArray(T){return T.constructor===Array||T.constructor===Float32Array}function isNumerable(T,n){return T==="number"||n instanceof Number||T==="boolean"||T==="string"}function $bm_neg(T){var n=_typeof$1(T);if(n==="number"||T instanceof Number||n==="boolean")return-T;if($bm_isInstanceOfArray(T)){var P,R=T.length,A=[];for(P=0;P<R;P+=1)A[P]=-T[P];return A}return T.propType?T.v:-T}var easeInBez=BezierFactory.getBezierEasing(.333,0,.833,.833,"easeIn").get,easeOutBez=BezierFactory.getBezierEasing(.167,.167,.667,1,"easeOut").get,easeInOutBez=BezierFactory.getBezierEasing(.33,0,.667,1,"easeInOut").get;function sum(T,n){var P=_typeof$1(T),R=_typeof$1(n);if(isNumerable(P,T)&&isNumerable(R,n)||P==="string"||R==="string")return T+n;if($bm_isInstanceOfArray(T)&&isNumerable(R,n))return T=T.slice(0),T[0]+=n,T;if(isNumerable(P,T)&&$bm_isInstanceOfArray(n))return n=n.slice(0),n[0]=T+n[0],n;if($bm_isInstanceOfArray(T)&&$bm_isInstanceOfArray(n)){for(var A=0,L=T.length,O=n.length,N=[];A<L||A<O;)(typeof T[A]=="number"||T[A]instanceof Number)&&(typeof n[A]=="number"||n[A]instanceof Number)?N[A]=T[A]+n[A]:N[A]=n[A]===void 0?T[A]:T[A]||n[A],A+=1;return N}return 0}var add=sum;function sub(T,n){var P=_typeof$1(T),R=_typeof$1(n);if(isNumerable(P,T)&&isNumerable(R,n))return P==="string"&&(T=parseInt(T,10)),R==="string"&&(n=parseInt(n,10)),T-n;if($bm_isInstanceOfArray(T)&&isNumerable(R,n))return T=T.slice(0),T[0]-=n,T;if(isNumerable(P,T)&&$bm_isInstanceOfArray(n))return n=n.slice(0),n[0]=T-n[0],n;if($bm_isInstanceOfArray(T)&&$bm_isInstanceOfArray(n)){for(var A=0,L=T.length,O=n.length,N=[];A<L||A<O;)(typeof T[A]=="number"||T[A]instanceof Number)&&(typeof n[A]=="number"||n[A]instanceof Number)?N[A]=T[A]-n[A]:N[A]=n[A]===void 0?T[A]:T[A]||n[A],A+=1;return N}return 0}function mul(T,n){var P=_typeof$1(T),R=_typeof$1(n),A;if(isNumerable(P,T)&&isNumerable(R,n))return T*n;var L,O;if($bm_isInstanceOfArray(T)&&isNumerable(R,n)){for(O=T.length,A=createTypedArray("float32",O),L=0;L<O;L+=1)A[L]=T[L]*n;return A}if(isNumerable(P,T)&&$bm_isInstanceOfArray(n)){for(O=n.length,A=createTypedArray("float32",O),L=0;L<O;L+=1)A[L]=T*n[L];return A}return 0}function div(T,n){var P=_typeof$1(T),R=_typeof$1(n),A;if(isNumerable(P,T)&&isNumerable(R,n))return T/n;var L,O;if($bm_isInstanceOfArray(T)&&isNumerable(R,n)){for(O=T.length,A=createTypedArray("float32",O),L=0;L<O;L+=1)A[L]=T[L]/n;return A}if(isNumerable(P,T)&&$bm_isInstanceOfArray(n)){for(O=n.length,A=createTypedArray("float32",O),L=0;L<O;L+=1)A[L]=T/n[L];return A}return 0}function mod(T,n){return typeof T=="string"&&(T=parseInt(T,10)),typeof n=="string"&&(n=parseInt(n,10)),T%n}var $bm_sum=sum,$bm_sub=sub,$bm_mul=mul,$bm_div=div,$bm_mod=mod;function clamp(T,n,P){if(n>P){var R=P;P=n,n=R}return Math.min(Math.max(T,n),P)}function radiansToDegrees(T){return T/degToRads}var radians_to_degrees=radiansToDegrees;function degreesToRadians(T){return T*degToRads}var degrees_to_radians=radiansToDegrees,helperLengthArray=[0,0,0,0,0,0];function length(T,n){if(typeof T=="number"||T instanceof Number)return n=n||0,Math.abs(T-n);n||(n=helperLengthArray);var P,R=Math.min(T.length,n.length),A=0;for(P=0;P<R;P+=1)A+=Math.pow(n[P]-T[P],2);return Math.sqrt(A)}function normalize(T){return div(T,length(T))}function rgbToHsl(T){var n=T[0],P=T[1],R=T[2],A=Math.max(n,P,R),L=Math.min(n,P,R),O,N,V=(A+L)/2;if(A===L)O=0,N=0;else{var j=A-L;switch(N=V>.5?j/(2-A-L):j/(A+L),A){case n:O=(P-R)/j+(P<R?6:0);break;case P:O=(R-n)/j+2;break;case R:O=(n-P)/j+4;break}O/=6}return[O,N,V,T[3]]}function hue2rgb(T,n,P){return P<0&&(P+=1),P>1&&(P-=1),P<1/6?T+(n-T)*6*P:P<1/2?n:P<2/3?T+(n-T)*(2/3-P)*6:T}function hslToRgb(T){var n=T[0],P=T[1],R=T[2],A,L,O;if(P===0)A=R,O=R,L=R;else{var N=R<.5?R*(1+P):R+P-R*P,V=2*R-N;A=hue2rgb(V,N,n+1/3),L=hue2rgb(V,N,n),O=hue2rgb(V,N,n-1/3)}return[A,L,O,T[3]]}function linear(T,n,P,R,A){if((R===void 0||A===void 0)&&(R=n,A=P,n=0,P=1),P<n){var L=P;P=n,n=L}if(T<=n)return R;if(T>=P)return A;var O=P===n?0:(T-n)/(P-n);if(!R.length)return R+(A-R)*O;var N,V=R.length,j=createTypedArray("float32",V);for(N=0;N<V;N+=1)j[N]=R[N]+(A[N]-R[N])*O;return j}function random(T,n){if(n===void 0&&(T===void 0?(T=0,n=1):(n=T,T=void 0)),n.length){var P,R=n.length;T||(T=createTypedArray("float32",R));var A=createTypedArray("float32",R),L=BMMath.random();for(P=0;P<R;P+=1)A[P]=T[P]+L*(n[P]-T[P]);return A}T===void 0&&(T=0);var O=BMMath.random();return T+O*(n-T)}function createPath(T,n,P,R){var A,L=T.length,O=shapePool.newElement();O.setPathData(!!R,L);var N=[0,0],V,j;for(A=0;A<L;A+=1)V=n&&n[A]?n[A]:N,j=P&&P[A]?P[A]:N,O.setTripleAt(T[A][0],T[A][1],j[0]+T[A][0],j[1]+T[A][1],V[0]+T[A][0],V[1]+T[A][1],A,!0);return O}function initiateExpression(elem,data,property){function noOp(T){return T}if(!elem.globalData.renderConfig.runExpressions)return noOp;var val=data.x,needsVelocity=/velocity(?![\w\d])/.test(val),_needsRandom=val.indexOf("random")!==-1,elemType=elem.data.ty,transform,$bm_transform,content,effect,thisProperty=property;thisProperty._name=elem.data.nm,thisProperty.valueAtTime=thisProperty.getValueAtTime,Object.defineProperty(thisProperty,"value",{get:function(){return thisProperty.v}}),elem.comp.frameDuration=1/elem.comp.globalData.frameRate,elem.comp.displayStartTime=0;var inPoint=elem.data.ip/elem.comp.globalData.frameRate,outPoint=elem.data.op/elem.comp.globalData.frameRate,width=elem.data.sw?elem.data.sw:0,height=elem.data.sh?elem.data.sh:0,name=elem.data.nm,loopIn,loop_in,loopOut,loop_out,smooth,toWorld,fromWorld,fromComp,toComp,fromCompToSurface,position,rotation,anchorPoint,scale,thisLayer,thisComp,mask,valueAtTime,velocityAtTime,scoped_bm_rt,expression_function=eval("[function _expression_function(){"+val+";scoped_bm_rt=$bm_rt}]")[0],numKeys=property.kf?data.k.length:0,active=!this.data||this.data.hd!==!0,wiggle=(function T(n,P){var R,A,L=this.pv.length?this.pv.length:1,O=createTypedArray("float32",L);n=5;var N=Math.floor(time*n);for(R=0,A=0;R<N;){for(A=0;A<L;A+=1)O[A]+=-P+P*2*BMMath.random();R+=1}var V=time*n,j=V-Math.floor(V),B=createTypedArray("float32",L);if(L>1){for(A=0;A<L;A+=1)B[A]=this.pv[A]+O[A]+(-P+P*2*BMMath.random())*j;return B}return this.pv+O[0]+(-P+P*2*BMMath.random())*j}).bind(this);thisProperty.loopIn&&(loopIn=thisProperty.loopIn.bind(thisProperty),loop_in=loopIn),thisProperty.loopOut&&(loopOut=thisProperty.loopOut.bind(thisProperty),loop_out=loopOut),thisProperty.smooth&&(smooth=thisProperty.smooth.bind(thisProperty));function loopInDuration(T,n){return loopIn(T,n,!0)}function loopOutDuration(T,n){return loopOut(T,n,!0)}this.getValueAtTime&&(valueAtTime=this.getValueAtTime.bind(this)),this.getVelocityAtTime&&(velocityAtTime=this.getVelocityAtTime.bind(this));var comp=elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface);function lookAt(T,n){var P=[n[0]-T[0],n[1]-T[1],n[2]-T[2]],R=Math.atan2(P[0],Math.sqrt(P[1]*P[1]+P[2]*P[2]))/degToRads,A=-Math.atan2(P[1],P[2])/degToRads;return[A,R,0]}function easeOut(T,n,P,R,A){return applyEase(easeOutBez,T,n,P,R,A)}function easeIn(T,n,P,R,A){return applyEase(easeInBez,T,n,P,R,A)}function ease(T,n,P,R,A){return applyEase(easeInOutBez,T,n,P,R,A)}function applyEase(T,n,P,R,A,L){A===void 0?(A=P,L=R):n=(n-P)/(R-P),n>1?n=1:n<0&&(n=0);var O=T(n);if($bm_isInstanceOfArray(A)){var N,V=A.length,j=createTypedArray("float32",V);for(N=0;N<V;N+=1)j[N]=(L[N]-A[N])*O+A[N];return j}return(L-A)*O+A}function nearestKey(T){var n,P=data.k.length,R,A;if(!data.k.length||typeof data.k[0]=="number")R=0,A=0;else if(R=-1,T*=elem.comp.globalData.frameRate,T<data.k[0].t)R=1,A=data.k[0].t;else{for(n=0;n<P-1;n+=1)if(T===data.k[n].t){R=n+1,A=data.k[n].t;break}else if(T>data.k[n].t&&T<data.k[n+1].t){T-data.k[n].t>data.k[n+1].t-T?(R=n+2,A=data.k[n+1].t):(R=n+1,A=data.k[n].t);break}R===-1&&(R=n+1,A=data.k[n].t)}var L={};return L.index=R,L.time=A/elem.comp.globalData.frameRate,L}function key(T){var n,P,R;if(!data.k.length||typeof data.k[0]=="number")throw new Error("The property has no keyframe at index "+T);T-=1,n={time:data.k[T].t/elem.comp.globalData.frameRate,value:[]};var A=Object.prototype.hasOwnProperty.call(data.k[T],"s")?data.k[T].s:data.k[T-1].e;for(R=A.length,P=0;P<R;P+=1)n[P]=A[P],n.value[P]=A[P];return n}function framesToTime(T,n){return n||(n=elem.comp.globalData.frameRate),T/n}function timeToFrames(T,n){return!T&&T!==0&&(T=time),n||(n=elem.comp.globalData.frameRate),T*n}function seedRandom(T){BMMath.seedrandom(randSeed+T)}function sourceRectAtTime(){return elem.sourceRectAtTime()}function substring(T,n){return typeof value=="string"?n===void 0?value.substring(T):value.substring(T,n):""}function substr(T,n){return typeof value=="string"?n===void 0?value.substr(T):value.substr(T,n):""}function posterizeTime(T){time=T===0?0:Math.floor(time*T)/T,value=valueAtTime(time)}var time,velocity,value,text,textIndex,textTotal,selectorValue,index=elem.data.ind,hasParent=!!(elem.hierarchy&&elem.hierarchy.length),parent,randSeed=Math.floor(Math.random()*1e6),globalData=elem.globalData;function executeExpression(T){return value=T,this.frameExpressionId===elem.globalData.frameId&&this.propType!=="textSelector"?value:(this.propType==="textSelector"&&(textIndex=this.textIndex,textTotal=this.textTotal,selectorValue=this.selectorValue),thisLayer||(text=elem.layerInterface.text,thisLayer=elem.layerInterface,thisComp=elem.comp.compInterface,toWorld=thisLayer.toWorld.bind(thisLayer),fromWorld=thisLayer.fromWorld.bind(thisLayer),fromComp=thisLayer.fromComp.bind(thisLayer),toComp=thisLayer.toComp.bind(thisLayer),mask=thisLayer.mask?thisLayer.mask.bind(thisLayer):null,fromCompToSurface=fromComp),transform||(transform=elem.layerInterface("ADBE Transform Group"),$bm_transform=transform,transform&&(anchorPoint=transform.anchorPoint)),elemType===4&&!content&&(content=thisLayer("ADBE Root Vectors Group")),effect||(effect=thisLayer(4)),hasParent=!!(elem.hierarchy&&elem.hierarchy.length),hasParent&&!parent&&(parent=elem.hierarchy[0].layerInterface),time=this.comp.renderedFrame/this.comp.globalData.frameRate,_needsRandom&&seedRandom(randSeed+time),needsVelocity&&(velocity=velocityAtTime(time)),expression_function(),this.frameExpressionId=elem.globalData.frameId,scoped_bm_rt=scoped_bm_rt.propType===propTypes.SHAPE?scoped_bm_rt.v:scoped_bm_rt,scoped_bm_rt)}return executeExpression.__preventDeadCodeRemoval=[$bm_transform,anchorPoint,time,velocity,inPoint,outPoint,width,height,name,loop_in,loop_out,smooth,toComp,fromCompToSurface,toWorld,fromWorld,mask,position,rotation,scale,thisComp,numKeys,active,wiggle,loopInDuration,loopOutDuration,comp,lookAt,easeOut,easeIn,ease,nearestKey,key,text,textIndex,textTotal,selectorValue,framesToTime,timeToFrames,sourceRectAtTime,substring,substr,posterizeTime,index,globalData],executeExpression}return ob.initiateExpression=initiateExpression,ob.__preventDeadCodeRemoval=[window,document,XMLHttpRequest,fetch,frames,$bm_neg,add,$bm_sum,$bm_sub,$bm_mul,$bm_div,$bm_mod,clamp,radians_to_degrees,degreesToRadians,degrees_to_radians,normalize,rgbToHsl,hslToRgb,linear,random,createPath,_lottieGlobal],ob.resetFrame=resetFrame,ob})(),Expressions=(function(){var T={};T.initExpressions=n,T.resetFrame=ExpressionManager.resetFrame;function n(P){var R=0,A=[];function L(){R+=1}function O(){R-=1,R===0&&V()}function N(j){A.indexOf(j)===-1&&A.push(j)}function V(){var j,B=A.length;for(j=0;j<B;j+=1)A[j].release();A.length=0}P.renderer.compInterface=CompExpressionInterface(P.renderer),P.renderer.globalData.projectInterface.registerComposition(P.renderer),P.renderer.globalData.pushExpression=L,P.renderer.globalData.popExpression=O,P.renderer.globalData.registerExpressionProperty=N}return T})(),MaskManagerInterface=(function(){function T(P,R){this._mask=P,this._data=R}Object.defineProperty(T.prototype,"maskPath",{get:function(){return this._mask.prop.k&&this._mask.prop.getValue(),this._mask.prop}}),Object.defineProperty(T.prototype,"maskOpacity",{get:function(){return this._mask.op.k&&this._mask.op.getValue(),this._mask.op.v*100}});var n=function(R){var A=createSizedArray(R.viewData.length),L,O=R.viewData.length;for(L=0;L<O;L+=1)A[L]=new T(R.viewData[L],R.masksProperties[L]);var N=function(j){for(L=0;L<O;){if(R.masksProperties[L].nm===j)return A[L];L+=1}return null};return N};return n})(),ExpressionPropertyInterface=(function(){var T={pv:0,v:0,mult:1},n={pv:[0,0,0],v:[0,0,0],mult:1};function P(O,N,V){Object.defineProperty(O,"velocity",{get:function(){return N.getVelocityAtTime(N.comp.currentFrame)}}),O.numKeys=N.keyframes?N.keyframes.length:0,O.key=function(j){if(!O.numKeys)return 0;var B="";"s"in N.keyframes[j-1]?B=N.keyframes[j-1].s:"e"in N.keyframes[j-2]?B=N.keyframes[j-2].e:B=N.keyframes[j-2].s;var z=V==="unidimensional"?new Number(B):Object.assign({},B);return z.time=N.keyframes[j-1].t/N.elem.comp.globalData.frameRate,z.value=V==="unidimensional"?B[0]:B,z},O.valueAtTime=N.getValueAtTime,O.speedAtTime=N.getSpeedAtTime,O.velocityAtTime=N.getVelocityAtTime,O.propertyGroup=N.propertyGroup}function R(O){(!O||!("pv"in O))&&(O=T);var N=1/O.mult,V=O.pv*N,j=new Number(V);return j.value=V,P(j,O,"unidimensional"),function(){return O.k&&O.getValue(),V=O.v*N,j.value!==V&&(j=new Number(V),j.value=V,j[0]=V,P(j,O,"unidimensional")),j}}function A(O){(!O||!("pv"in O))&&(O=n);var N=1/O.mult,V=O.data&&O.data.l||O.pv.length,j=createTypedArray("float32",V),B=createTypedArray("float32",V);return j.value=B,P(j,O,"multidimensional"),function(){O.k&&O.getValue();for(var z=0;z<V;z+=1)B[z]=O.v[z]*N,j[z]=B[z];return j}}function L(){return T}return function(O){return O?O.propType==="unidimensional"?R(O):A(O):L}})(),TransformExpressionInterface=(function(){return function(T){function n(O){switch(O){case"scale":case"Scale":case"ADBE Scale":case 6:return n.scale;case"rotation":case"Rotation":case"ADBE Rotation":case"ADBE Rotate Z":case 10:return n.rotation;case"ADBE Rotate X":return n.xRotation;case"ADBE Rotate Y":return n.yRotation;case"position":case"Position":case"ADBE Position":case 2:return n.position;case"ADBE Position_0":return n.xPosition;case"ADBE Position_1":return n.yPosition;case"ADBE Position_2":return n.zPosition;case"anchorPoint":case"AnchorPoint":case"Anchor Point":case"ADBE AnchorPoint":case 1:return n.anchorPoint;case"opacity":case"Opacity":case 11:return n.opacity;default:return null}}Object.defineProperty(n,"rotation",{get:ExpressionPropertyInterface(T.r||T.rz)}),Object.defineProperty(n,"zRotation",{get:ExpressionPropertyInterface(T.rz||T.r)}),Object.defineProperty(n,"xRotation",{get:ExpressionPropertyInterface(T.rx)}),Object.defineProperty(n,"yRotation",{get:ExpressionPropertyInterface(T.ry)}),Object.defineProperty(n,"scale",{get:ExpressionPropertyInterface(T.s)});var P,R,A,L;return T.p?L=ExpressionPropertyInterface(T.p):(P=ExpressionPropertyInterface(T.px),R=ExpressionPropertyInterface(T.py),T.pz&&(A=ExpressionPropertyInterface(T.pz))),Object.defineProperty(n,"position",{get:function(){return T.p?L():[P(),R(),A?A():0]}}),Object.defineProperty(n,"xPosition",{get:ExpressionPropertyInterface(T.px)}),Object.defineProperty(n,"yPosition",{get:ExpressionPropertyInterface(T.py)}),Object.defineProperty(n,"zPosition",{get:ExpressionPropertyInterface(T.pz)}),Object.defineProperty(n,"anchorPoint",{get:ExpressionPropertyInterface(T.a)}),Object.defineProperty(n,"opacity",{get:ExpressionPropertyInterface(T.o)}),Object.defineProperty(n,"skew",{get:ExpressionPropertyInterface(T.sk)}),Object.defineProperty(n,"skewAxis",{get:ExpressionPropertyInterface(T.sa)}),Object.defineProperty(n,"orientation",{get:ExpressionPropertyInterface(T.or)}),n}})(),LayerExpressionInterface=(function(){function T(j){var B=new Matrix;if(j!==void 0){var z=this._elem.finalTransform.mProp.getValueAtTime(j);z.clone(B)}else{var W=this._elem.finalTransform.mProp;W.applyToMatrix(B)}return B}function n(j,B){var z=this.getMatrix(B);return z.props[12]=0,z.props[13]=0,z.props[14]=0,this.applyPoint(z,j)}function P(j,B){var z=this.getMatrix(B);return this.applyPoint(z,j)}function R(j,B){var z=this.getMatrix(B);return z.props[12]=0,z.props[13]=0,z.props[14]=0,this.invertPoint(z,j)}function A(j,B){var z=this.getMatrix(B);return this.invertPoint(z,j)}function L(j,B){if(this._elem.hierarchy&&this._elem.hierarchy.length){var z,W=this._elem.hierarchy.length;for(z=0;z<W;z+=1)this._elem.hierarchy[z].finalTransform.mProp.applyToMatrix(j)}return j.applyToPointArray(B[0],B[1],B[2]||0)}function O(j,B){if(this._elem.hierarchy&&this._elem.hierarchy.length){var z,W=this._elem.hierarchy.length;for(z=0;z<W;z+=1)this._elem.hierarchy[z].finalTransform.mProp.applyToMatrix(j)}return j.inversePoint(B)}function N(j){var B=new Matrix;if(B.reset(),this._elem.finalTransform.mProp.applyToMatrix(B),this._elem.hierarchy&&this._elem.hierarchy.length){var z,W=this._elem.hierarchy.length;for(z=0;z<W;z+=1)this._elem.hierarchy[z].finalTransform.mProp.applyToMatrix(B);return B.inversePoint(j)}return B.inversePoint(j)}function V(){return[1,1,1,1]}return function(j){var B;function z($){q.mask=new MaskManagerInterface($,j)}function W($){q.effect=$}function q($){switch($){case"ADBE Root Vectors Group":case"Contents":case 2:return q.shapeInterface;case 1:case 6:case"Transform":case"transform":case"ADBE Transform Group":return B;case 4:case"ADBE Effect Parade":case"effects":case"Effects":return q.effect;case"ADBE Text Properties":return q.textInterface;default:return null}}q.getMatrix=T,q.invertPoint=O,q.applyPoint=L,q.toWorld=P,q.toWorldVec=n,q.fromWorld=A,q.fromWorldVec=R,q.toComp=P,q.fromComp=N,q.sampleImage=V,q.sourceRectAtTime=j.sourceRectAtTime.bind(j),q._elem=j,B=TransformExpressionInterface(j.finalTransform.mProp);var H=getDescriptor(B,"anchorPoint");return Object.defineProperties(q,{hasParent:{get:function(){return j.hierarchy.length}},parent:{get:function(){return j.hierarchy[0].layerInterface}},rotation:getDescriptor(B,"rotation"),scale:getDescriptor(B,"scale"),position:getDescriptor(B,"position"),opacity:getDescriptor(B,"opacity"),anchorPoint:H,anchor_point:H,transform:{get:function(){return B}},active:{get:function(){return j.isInRange}}}),q.startTime=j.data.st,q.index=j.data.ind,q.source=j.data.refId,q.height=j.data.ty===0?j.data.h:100,q.width=j.data.ty===0?j.data.w:100,q.inPoint=j.data.ip/j.comp.globalData.frameRate,q.outPoint=j.data.op/j.comp.globalData.frameRate,q._name=j.data.nm,q.registerMaskInterface=z,q.registerEffectsInterface=W,q}})(),propertyGroupFactory=(function(){return function(T,n){return function(P){return P=P===void 0?1:P,P<=0?T:n(P-1)}}})(),PropertyInterface=(function(){return function(T,n){var P={_name:T};function R(A){return A=A===void 0?1:A,A<=0?P:n(A-1)}return R}})(),EffectsExpressionInterface=(function(){var T={createEffectsInterface:n};function n(A,L){if(A.effectsManager){var O=[],N=A.data.ef,V,j=A.effectsManager.effectElements.length;for(V=0;V<j;V+=1)O.push(P(N[V],A.effectsManager.effectElements[V],L,A));var B=A.data.ef||[],z=function(q){for(V=0,j=B.length;V<j;){if(q===B[V].nm||q===B[V].mn||q===B[V].ix)return O[V];V+=1}return null};return Object.defineProperty(z,"numProperties",{get:function(){return B.length}}),z}return null}function P(A,L,O,N){function V(q){for(var H=A.ef,$=0,Q=H.length;$<Q;){if(q===H[$].nm||q===H[$].mn||q===H[$].ix)return H[$].ty===5?B[$]:B[$]();$+=1}throw new Error}var j=propertyGroupFactory(V,O),B=[],z,W=A.ef.length;for(z=0;z<W;z+=1)A.ef[z].ty===5?B.push(P(A.ef[z],L.effectElements[z],L.effectElements[z].propertyGroup,N)):B.push(R(L.effectElements[z],A.ef[z].ty,N,j));return A.mn==="ADBE Color Control"&&Object.defineProperty(V,"color",{get:function(){return B[0]()}}),Object.defineProperties(V,{numProperties:{get:function(){return A.np}},_name:{value:A.nm},propertyGroup:{value:j}}),V.enabled=A.en!==0,V.active=V.enabled,V}function R(A,L,O,N){var V=ExpressionPropertyInterface(A.p);function j(){return L===10?O.comp.compInterface(A.p.v):V()}return A.p.setGroupProperty&&A.p.setGroupProperty(PropertyInterface("",N)),j}return T})(),ShapePathInterface=(function(){return function(n,P,R){var A=P.sh;function L(N){return N==="Shape"||N==="shape"||N==="Path"||N==="path"||N==="ADBE Vector Shape"||N===2?L.path:null}var O=propertyGroupFactory(L,R);return A.setGroupProperty(PropertyInterface("Path",O)),Object.defineProperties(L,{path:{get:function(){return A.k&&A.getValue(),A}},shape:{get:function(){return A.k&&A.getValue(),A}},_name:{value:n.nm},ix:{value:n.ix},propertyIndex:{value:n.ix},mn:{value:n.mn},propertyGroup:{value:R}}),L}})(),ShapeExpressionInterface=(function(){function T(H,$,Q){var U=[],J,G=H?H.length:0;for(J=0;J<G;J+=1)H[J].ty==="gr"?U.push(P(H[J],$[J],Q)):H[J].ty==="fl"?U.push(R(H[J],$[J],Q)):H[J].ty==="st"?U.push(O(H[J],$[J],Q)):H[J].ty==="tm"?U.push(N(H[J],$[J],Q)):H[J].ty==="tr"||(H[J].ty==="el"?U.push(j(H[J],$[J],Q)):H[J].ty==="sr"?U.push(B(H[J],$[J],Q)):H[J].ty==="sh"?U.push(ShapePathInterface(H[J],$[J],Q)):H[J].ty==="rc"?U.push(z(H[J],$[J],Q)):H[J].ty==="rd"?U.push(W(H[J],$[J],Q)):H[J].ty==="rp"?U.push(q(H[J],$[J],Q)):H[J].ty==="gf"?U.push(A(H[J],$[J],Q)):U.push(L(H[J],$[J])));return U}function n(H,$,Q){var U,J=function(Y){for(var Z=0,ie=U.length;Z<ie;){if(U[Z]._name===Y||U[Z].mn===Y||U[Z].propertyIndex===Y||U[Z].ix===Y||U[Z].ind===Y)return U[Z];Z+=1}return typeof Y=="number"?U[Y-1]:null};J.propertyGroup=propertyGroupFactory(J,Q),U=T(H.it,$.it,J.propertyGroup),J.numProperties=U.length;var G=V(H.it[H.it.length-1],$.it[$.it.length-1],J.propertyGroup);return J.transform=G,J.propertyIndex=H.cix,J._name=H.nm,J}function P(H,$,Q){var U=function(Y){switch(Y){case"ADBE Vectors Group":case"Contents":case 2:return U.content;default:return U.transform}};U.propertyGroup=propertyGroupFactory(U,Q);var J=n(H,$,U.propertyGroup),G=V(H.it[H.it.length-1],$.it[$.it.length-1],U.propertyGroup);return U.content=J,U.transform=G,Object.defineProperty(U,"_name",{get:function(){return H.nm}}),U.numProperties=H.np,U.propertyIndex=H.ix,U.nm=H.nm,U.mn=H.mn,U}function R(H,$,Q){function U(J){return J==="Color"||J==="color"?U.color:J==="Opacity"||J==="opacity"?U.opacity:null}return Object.defineProperties(U,{color:{get:ExpressionPropertyInterface($.c)},opacity:{get:ExpressionPropertyInterface($.o)},_name:{value:H.nm},mn:{value:H.mn}}),$.c.setGroupProperty(PropertyInterface("Color",Q)),$.o.setGroupProperty(PropertyInterface("Opacity",Q)),U}function A(H,$,Q){function U(J){return J==="Start Point"||J==="start point"?U.startPoint:J==="End Point"||J==="end point"?U.endPoint:J==="Opacity"||J==="opacity"?U.opacity:null}return Object.defineProperties(U,{startPoint:{get:ExpressionPropertyInterface($.s)},endPoint:{get:ExpressionPropertyInterface($.e)},opacity:{get:ExpressionPropertyInterface($.o)},type:{get:function(){return"a"}},_name:{value:H.nm},mn:{value:H.mn}}),$.s.setGroupProperty(PropertyInterface("Start Point",Q)),$.e.setGroupProperty(PropertyInterface("End Point",Q)),$.o.setGroupProperty(PropertyInterface("Opacity",Q)),U}function L(){function H(){return null}return H}function O(H,$,Q){var U=propertyGroupFactory(ie,Q),J=propertyGroupFactory(Z,U);function G(se){Object.defineProperty(Z,H.d[se].nm,{get:ExpressionPropertyInterface($.d.dataProps[se].p)})}var K,Y=H.d?H.d.length:0,Z={};for(K=0;K<Y;K+=1)G(K),$.d.dataProps[K].p.setGroupProperty(J);function ie(se){return se==="Color"||se==="color"?ie.color:se==="Opacity"||se==="opacity"?ie.opacity:se==="Stroke Width"||se==="stroke width"?ie.strokeWidth:null}return Object.defineProperties(ie,{color:{get:ExpressionPropertyInterface($.c)},opacity:{get:ExpressionPropertyInterface($.o)},strokeWidth:{get:ExpressionPropertyInterface($.w)},dash:{get:function(){return Z}},_name:{value:H.nm},mn:{value:H.mn}}),$.c.setGroupProperty(PropertyInterface("Color",U)),$.o.setGroupProperty(PropertyInterface("Opacity",U)),$.w.setGroupProperty(PropertyInterface("Stroke Width",U)),ie}function N(H,$,Q){function U(G){return G===H.e.ix||G==="End"||G==="end"?U.end:G===H.s.ix?U.start:G===H.o.ix?U.offset:null}var J=propertyGroupFactory(U,Q);return U.propertyIndex=H.ix,$.s.setGroupProperty(PropertyInterface("Start",J)),$.e.setGroupProperty(PropertyInterface("End",J)),$.o.setGroupProperty(PropertyInterface("Offset",J)),U.propertyIndex=H.ix,U.propertyGroup=Q,Object.defineProperties(U,{start:{get:ExpressionPropertyInterface($.s)},end:{get:ExpressionPropertyInterface($.e)},offset:{get:ExpressionPropertyInterface($.o)},_name:{value:H.nm}}),U.mn=H.mn,U}function V(H,$,Q){function U(G){return H.a.ix===G||G==="Anchor Point"?U.anchorPoint:H.o.ix===G||G==="Opacity"?U.opacity:H.p.ix===G||G==="Position"?U.position:H.r.ix===G||G==="Rotation"||G==="ADBE Vector Rotation"?U.rotation:H.s.ix===G||G==="Scale"?U.scale:H.sk&&H.sk.ix===G||G==="Skew"?U.skew:H.sa&&H.sa.ix===G||G==="Skew Axis"?U.skewAxis:null}var J=propertyGroupFactory(U,Q);return $.transform.mProps.o.setGroupProperty(PropertyInterface("Opacity",J)),$.transform.mProps.p.setGroupProperty(PropertyInterface("Position",J)),$.transform.mProps.a.setGroupProperty(PropertyInterface("Anchor Point",J)),$.transform.mProps.s.setGroupProperty(PropertyInterface("Scale",J)),$.transform.mProps.r.setGroupProperty(PropertyInterface("Rotation",J)),$.transform.mProps.sk&&($.transform.mProps.sk.setGroupProperty(PropertyInterface("Skew",J)),$.transform.mProps.sa.setGroupProperty(PropertyInterface("Skew Angle",J))),$.transform.op.setGroupProperty(PropertyInterface("Opacity",J)),Object.defineProperties(U,{opacity:{get:ExpressionPropertyInterface($.transform.mProps.o)},position:{get:ExpressionPropertyInterface($.transform.mProps.p)},anchorPoint:{get:ExpressionPropertyInterface($.transform.mProps.a)},scale:{get:ExpressionPropertyInterface($.transform.mProps.s)},rotation:{get:ExpressionPropertyInterface($.transform.mProps.r)},skew:{get:ExpressionPropertyInterface($.transform.mProps.sk)},skewAxis:{get:ExpressionPropertyInterface($.transform.mProps.sa)},_name:{value:H.nm}}),U.ty="tr",U.mn=H.mn,U.propertyGroup=Q,U}function j(H,$,Q){function U(K){return H.p.ix===K?U.position:H.s.ix===K?U.size:null}var J=propertyGroupFactory(U,Q);U.propertyIndex=H.ix;var G=$.sh.ty==="tm"?$.sh.prop:$.sh;return G.s.setGroupProperty(PropertyInterface("Size",J)),G.p.setGroupProperty(PropertyInterface("Position",J)),Object.defineProperties(U,{size:{get:ExpressionPropertyInterface(G.s)},position:{get:ExpressionPropertyInterface(G.p)},_name:{value:H.nm}}),U.mn=H.mn,U}function B(H,$,Q){function U(K){return H.p.ix===K?U.position:H.r.ix===K?U.rotation:H.pt.ix===K?U.points:H.or.ix===K||K==="ADBE Vector Star Outer Radius"?U.outerRadius:H.os.ix===K?U.outerRoundness:H.ir&&(H.ir.ix===K||K==="ADBE Vector Star Inner Radius")?U.innerRadius:H.is&&H.is.ix===K?U.innerRoundness:null}var J=propertyGroupFactory(U,Q),G=$.sh.ty==="tm"?$.sh.prop:$.sh;return U.propertyIndex=H.ix,G.or.setGroupProperty(PropertyInterface("Outer Radius",J)),G.os.setGroupProperty(PropertyInterface("Outer Roundness",J)),G.pt.setGroupProperty(PropertyInterface("Points",J)),G.p.setGroupProperty(PropertyInterface("Position",J)),G.r.setGroupProperty(PropertyInterface("Rotation",J)),H.ir&&(G.ir.setGroupProperty(PropertyInterface("Inner Radius",J)),G.is.setGroupProperty(PropertyInterface("Inner Roundness",J))),Object.defineProperties(U,{position:{get:ExpressionPropertyInterface(G.p)},rotation:{get:ExpressionPropertyInterface(G.r)},points:{get:ExpressionPropertyInterface(G.pt)},outerRadius:{get:ExpressionPropertyInterface(G.or)},outerRoundness:{get:ExpressionPropertyInterface(G.os)},innerRadius:{get:ExpressionPropertyInterface(G.ir)},innerRoundness:{get:ExpressionPropertyInterface(G.is)},_name:{value:H.nm}}),U.mn=H.mn,U}function z(H,$,Q){function U(K){return H.p.ix===K?U.position:H.r.ix===K?U.roundness:H.s.ix===K||K==="Size"||K==="ADBE Vector Rect Size"?U.size:null}var J=propertyGroupFactory(U,Q),G=$.sh.ty==="tm"?$.sh.prop:$.sh;return U.propertyIndex=H.ix,G.p.setGroupProperty(PropertyInterface("Position",J)),G.s.setGroupProperty(PropertyInterface("Size",J)),G.r.setGroupProperty(PropertyInterface("Rotation",J)),Object.defineProperties(U,{position:{get:ExpressionPropertyInterface(G.p)},roundness:{get:ExpressionPropertyInterface(G.r)},size:{get:ExpressionPropertyInterface(G.s)},_name:{value:H.nm}}),U.mn=H.mn,U}function W(H,$,Q){function U(K){return H.r.ix===K||K==="Round Corners 1"?U.radius:null}var J=propertyGroupFactory(U,Q),G=$;return U.propertyIndex=H.ix,G.rd.setGroupProperty(PropertyInterface("Radius",J)),Object.defineProperties(U,{radius:{get:ExpressionPropertyInterface(G.rd)},_name:{value:H.nm}}),U.mn=H.mn,U}function q(H,$,Q){function U(K){return H.c.ix===K||K==="Copies"?U.copies:H.o.ix===K||K==="Offset"?U.offset:null}var J=propertyGroupFactory(U,Q),G=$;return U.propertyIndex=H.ix,G.c.setGroupProperty(PropertyInterface("Copies",J)),G.o.setGroupProperty(PropertyInterface("Offset",J)),Object.defineProperties(U,{copies:{get:ExpressionPropertyInterface(G.c)},offset:{get:ExpressionPropertyInterface(G.o)},_name:{value:H.nm}}),U.mn=H.mn,U}return function(H,$,Q){var U;function J(K){if(typeof K=="number")return K=K===void 0?1:K,K===0?Q:U[K-1];for(var Y=0,Z=U.length;Y<Z;){if(U[Y]._name===K)return U[Y];Y+=1}return null}function G(){return Q}return J.propertyGroup=propertyGroupFactory(J,G),U=T(H,$,J.propertyGroup),J.numProperties=U.length,J._name="Contents",J}})(),TextExpressionInterface=(function(){return function(T){var n;function P(R){switch(R){case"ADBE Text Document":return P.sourceText;default:return null}}return Object.defineProperty(P,"sourceText",{get:function(){T.textProperty.getValue();var A=T.textProperty.currentData.t;return(!n||A!==n.value)&&(n=new String(A),n.value=A||new String(A),Object.defineProperty(n,"style",{get:function(){return{fillColor:T.textProperty.currentData.fc}}})),n}}),P}})();function _typeof(T){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof(T)}var FootageInterface=(function(){var T=function(R){var A="",L=R.getFootageData();function O(){return A="",L=R.getFootageData(),N}function N(V){if(L[V])return A=V,L=L[V],_typeof(L)==="object"?N:L;var j=V.indexOf(A);if(j!==-1){var B=parseInt(V.substr(j+A.length),10);return L=L[B],_typeof(L)==="object"?N:L}return""}return O},n=function(R){function A(L){return L==="Outline"?A.outlineInterface():null}return A._name="Outline",A.outlineInterface=T(R),A};return function(P){function R(A){return A==="Data"?R.dataInterface:null}return R._name="Data",R.dataInterface=n(P),R}})(),interfaces={layer:LayerExpressionInterface,effects:EffectsExpressionInterface,comp:CompExpressionInterface,shape:ShapeExpressionInterface,text:TextExpressionInterface,footage:FootageInterface};function getInterface(T){return interfaces[T]||null}var expressionHelpers=(function(){function T(O,N,V){N.x&&(V.k=!0,V.x=!0,V.initiateExpression=ExpressionManager.initiateExpression,V.effectsSequence.push(V.initiateExpression(O,N,V).bind(V)))}function n(O){return O*=this.elem.globalData.frameRate,O-=this.offsetTime,O!==this._cachingAtTime.lastFrame&&(this._cachingAtTime.lastIndex=this._cachingAtTime.lastFrame<O?this._cachingAtTime.lastIndex:0,this._cachingAtTime.value=this.interpolateValue(O,this._cachingAtTime),this._cachingAtTime.lastFrame=O),this._cachingAtTime.value}function P(O){var N=-.01,V=this.getValueAtTime(O),j=this.getValueAtTime(O+N),B=0;if(V.length){var z;for(z=0;z<V.length;z+=1)B+=Math.pow(j[z]-V[z],2);B=Math.sqrt(B)*100}else B=0;return B}function R(O){if(this.vel!==void 0)return this.vel;var N=-.001,V=this.getValueAtTime(O),j=this.getValueAtTime(O+N),B;if(V.length){B=createTypedArray("float32",V.length);var z;for(z=0;z<V.length;z+=1)B[z]=(j[z]-V[z])/N}else B=(j-V)/N;return B}function A(){return this.pv}function L(O){this.propertyGroup=O}return{searchExpressions:T,getSpeedAtTime:P,getVelocityAtTime:R,getValueAtTime:n,getStaticValueAtTime:A,setGroupProperty:L}})();function addPropertyDecorator(){function T(W,q,H){if(!this.k||!this.keyframes)return this.pv;W=W?W.toLowerCase():"";var $=this.comp.renderedFrame,Q=this.keyframes,U=Q[Q.length-1].t;if($<=U)return this.pv;var J,G;H?(q?J=Math.abs(U-this.elem.comp.globalData.frameRate*q):J=Math.max(0,U-this.elem.data.ip),G=U-J):((!q||q>Q.length-1)&&(q=Q.length-1),G=Q[Q.length-1-q].t,J=U-G);var K,Y,Z;if(W==="pingpong"){var ie=Math.floor(($-G)/J);if(ie%2!==0)return this.getValueAtTime((J-($-G)%J+G)/this.comp.globalData.frameRate,0)}else if(W==="offset"){var se=this.getValueAtTime(G/this.comp.globalData.frameRate,0),le=this.getValueAtTime(U/this.comp.globalData.frameRate,0),pe=this.getValueAtTime((($-G)%J+G)/this.comp.globalData.frameRate,0),ue=Math.floor(($-G)/J);if(this.pv.length){for(Z=new Array(se.length),Y=Z.length,K=0;K<Y;K+=1)Z[K]=(le[K]-se[K])*ue+pe[K];return Z}return(le-se)*ue+pe}else if(W==="continue"){var he=this.getValueAtTime(U/this.comp.globalData.frameRate,0),ve=this.getValueAtTime((U-.001)/this.comp.globalData.frameRate,0);if(this.pv.length){for(Z=new Array(he.length),Y=Z.length,K=0;K<Y;K+=1)Z[K]=he[K]+(he[K]-ve[K])*(($-U)/this.comp.globalData.frameRate)/5e-4;return Z}return he+(he-ve)*(($-U)/.001)}return this.getValueAtTime((($-G)%J+G)/this.comp.globalData.frameRate,0)}function n(W,q,H){if(!this.k)return this.pv;W=W?W.toLowerCase():"";var $=this.comp.renderedFrame,Q=this.keyframes,U=Q[0].t;if($>=U)return this.pv;var J,G;H?(q?J=Math.abs(this.elem.comp.globalData.frameRate*q):J=Math.max(0,this.elem.data.op-U),G=U+J):((!q||q>Q.length-1)&&(q=Q.length-1),G=Q[q].t,J=G-U);var K,Y,Z;if(W==="pingpong"){var ie=Math.floor((U-$)/J);if(ie%2===0)return this.getValueAtTime(((U-$)%J+U)/this.comp.globalData.frameRate,0)}else if(W==="offset"){var se=this.getValueAtTime(U/this.comp.globalData.frameRate,0),le=this.getValueAtTime(G/this.comp.globalData.frameRate,0),pe=this.getValueAtTime((J-(U-$)%J+U)/this.comp.globalData.frameRate,0),ue=Math.floor((U-$)/J)+1;if(this.pv.length){for(Z=new Array(se.length),Y=Z.length,K=0;K<Y;K+=1)Z[K]=pe[K]-(le[K]-se[K])*ue;return Z}return pe-(le-se)*ue}else if(W==="continue"){var he=this.getValueAtTime(U/this.comp.globalData.frameRate,0),ve=this.getValueAtTime((U+.001)/this.comp.globalData.frameRate,0);if(this.pv.length){for(Z=new Array(he.length),Y=Z.length,K=0;K<Y;K+=1)Z[K]=he[K]+(he[K]-ve[K])*(U-$)/.001;return Z}return he+(he-ve)*(U-$)/.001}return this.getValueAtTime((J-((U-$)%J+U))/this.comp.globalData.frameRate,0)}function P(W,q){if(!this.k)return this.pv;if(W=(W||.4)*.5,q=Math.floor(q||5),q<=1)return this.pv;var H=this.comp.renderedFrame/this.comp.globalData.frameRate,$=H-W,Q=H+W,U=q>1?(Q-$)/(q-1):1,J=0,G=0,K;this.pv.length?K=createTypedArray("float32",this.pv.length):K=0;for(var Y;J<q;){if(Y=this.getValueAtTime($+J*U),this.pv.length)for(G=0;G<this.pv.length;G+=1)K[G]+=Y[G];else K+=Y;J+=1}if(this.pv.length)for(G=0;G<this.pv.length;G+=1)K[G]/=q;else K/=q;return K}function R(W){this._transformCachingAtTime||(this._transformCachingAtTime={v:new Matrix});var q=this._transformCachingAtTime.v;if(q.cloneFromProps(this.pre.props),this.appliedTransformations<1){var H=this.a.getValueAtTime(W);q.translate(-H[0]*this.a.mult,-H[1]*this.a.mult,H[2]*this.a.mult)}if(this.appliedTransformations<2){var $=this.s.getValueAtTime(W);q.scale($[0]*this.s.mult,$[1]*this.s.mult,$[2]*this.s.mult)}if(this.sk&&this.appliedTransformations<3){var Q=this.sk.getValueAtTime(W),U=this.sa.getValueAtTime(W);q.skewFromAxis(-Q*this.sk.mult,U*this.sa.mult)}if(this.r&&this.appliedTransformations<4){var J=this.r.getValueAtTime(W);q.rotate(-J*this.r.mult)}else if(!this.r&&this.appliedTransformations<4){var G=this.rz.getValueAtTime(W),K=this.ry.getValueAtTime(W),Y=this.rx.getValueAtTime(W),Z=this.or.getValueAtTime(W);q.rotateZ(-G*this.rz.mult).rotateY(K*this.ry.mult).rotateX(Y*this.rx.mult).rotateZ(-Z[2]*this.or.mult).rotateY(Z[1]*this.or.mult).rotateX(Z[0]*this.or.mult)}if(this.data.p&&this.data.p.s){var ie=this.px.getValueAtTime(W),se=this.py.getValueAtTime(W);if(this.data.p.z){var le=this.pz.getValueAtTime(W);q.translate(ie*this.px.mult,se*this.py.mult,-le*this.pz.mult)}else q.translate(ie*this.px.mult,se*this.py.mult,0)}else{var pe=this.p.getValueAtTime(W);q.translate(pe[0]*this.p.mult,pe[1]*this.p.mult,-pe[2]*this.p.mult)}return q}function A(){return this.v.clone(new Matrix)}var L=TransformPropertyFactory.getTransformProperty;TransformPropertyFactory.getTransformProperty=function(W,q,H){var $=L(W,q,H);return $.dynamicProperties.length?$.getValueAtTime=R.bind($):$.getValueAtTime=A.bind($),$.setGroupProperty=expressionHelpers.setGroupProperty,$};var O=PropertyFactory.getProp;PropertyFactory.getProp=function(W,q,H,$,Q){var U=O(W,q,H,$,Q);U.kf?U.getValueAtTime=expressionHelpers.getValueAtTime.bind(U):U.getValueAtTime=expressionHelpers.getStaticValueAtTime.bind(U),U.setGroupProperty=expressionHelpers.setGroupProperty,U.loopOut=T,U.loopIn=n,U.smooth=P,U.getVelocityAtTime=expressionHelpers.getVelocityAtTime.bind(U),U.getSpeedAtTime=expressionHelpers.getSpeedAtTime.bind(U),U.numKeys=q.a===1?q.k.length:0,U.propertyIndex=q.ix;var J=0;return H!==0&&(J=createTypedArray("float32",q.a===1?q.k[0].s.length:q.k.length)),U._cachingAtTime={lastFrame:initialDefaultFrame,lastIndex:0,value:J},expressionHelpers.searchExpressions(W,q,U),U.k&&Q.addDynamicProperty(U),U};function N(W){return this._cachingAtTime||(this._cachingAtTime={shapeValue:shapePool.clone(this.pv),lastIndex:0,lastTime:initialDefaultFrame}),W*=this.elem.globalData.frameRate,W-=this.offsetTime,W!==this._cachingAtTime.lastTime&&(this._cachingAtTime.lastIndex=this._cachingAtTime.lastTime<W?this._caching.lastIndex:0,this._cachingAtTime.lastTime=W,this.interpolateShape(W,this._cachingAtTime.shapeValue,this._cachingAtTime)),this._cachingAtTime.shapeValue}var V=ShapePropertyFactory.getConstructorFunction(),j=ShapePropertyFactory.getKeyframedConstructorFunction();function B(){}B.prototype={vertices:function(q,H){this.k&&this.getValue();var $=this.v;H!==void 0&&($=this.getValueAtTime(H,0));var Q,U=$._length,J=$[q],G=$.v,K=createSizedArray(U);for(Q=0;Q<U;Q+=1)q==="i"||q==="o"?K[Q]=[J[Q][0]-G[Q][0],J[Q][1]-G[Q][1]]:K[Q]=[J[Q][0],J[Q][1]];return K},points:function(q){return this.vertices("v",q)},inTangents:function(q){return this.vertices("i",q)},outTangents:function(q){return this.vertices("o",q)},isClosed:function(){return this.v.c},pointOnPath:function(q,H){var $=this.v;H!==void 0&&($=this.getValueAtTime(H,0)),this._segmentsLength||(this._segmentsLength=bez.getSegmentsLength($));for(var Q=this._segmentsLength,U=Q.lengths,J=Q.totalLength*q,G=0,K=U.length,Y=0,Z;G<K;){if(Y+U[G].addedLength>J){var ie=G,se=$.c&&G===K-1?0:G+1,le=(J-Y)/U[G].addedLength;Z=bez.getPointInSegment($.v[ie],$.v[se],$.o[ie],$.i[se],le,U[G]);break}else Y+=U[G].addedLength;G+=1}return Z||(Z=$.c?[$.v[0][0],$.v[0][1]]:[$.v[$._length-1][0],$.v[$._length-1][1]]),Z},vectorOnPath:function(q,H,$){q==1?q=this.v.c:q==0&&(q=.999);var Q=this.pointOnPath(q,H),U=this.pointOnPath(q+.001,H),J=U[0]-Q[0],G=U[1]-Q[1],K=Math.sqrt(Math.pow(J,2)+Math.pow(G,2));if(K===0)return[0,0];var Y=$==="tangent"?[J/K,G/K]:[-G/K,J/K];return Y},tangentOnPath:function(q,H){return this.vectorOnPath(q,H,"tangent")},normalOnPath:function(q,H){return this.vectorOnPath(q,H,"normal")},setGroupProperty:expressionHelpers.setGroupProperty,getValueAtTime:expressionHelpers.getStaticValueAtTime},extendPrototype([B],V),extendPrototype([B],j),j.prototype.getValueAtTime=N,j.prototype.initiateExpression=ExpressionManager.initiateExpression;var z=ShapePropertyFactory.getShapeProp;ShapePropertyFactory.getShapeProp=function(W,q,H,$,Q){var U=z(W,q,H,$,Q);return U.propertyIndex=q.ix,U.lock=!1,H===3?expressionHelpers.searchExpressions(W,q.pt,U):H===4&&expressionHelpers.searchExpressions(W,q.ks,U),U.k&&W.addDynamicProperty(U),U}}function initialize$1(){addPropertyDecorator()}function addDecorator(){function T(){return this.data.d.x?(this.calculateExpression=ExpressionManager.initiateExpression.bind(this)(this.elem,this.data.d,this),this.addEffect(this.getExpressionValue.bind(this)),!0):null}TextProperty.prototype.getExpressionValue=function(n,P){var R=this.calculateExpression(P);if(n.t!==R){var A={};return this.copyData(A,n),A.t=R.toString(),A.__complete=!1,A}return n},TextProperty.prototype.searchProperty=function(){var n=this.searchKeyframes(),P=this.searchExpressions();return this.kf=n||P,this.kf},TextProperty.prototype.searchExpressions=T}function initialize(){addDecorator()}function SVGComposableEffect(){}SVGComposableEffect.prototype={createMergeNode:function T(n,P){var R=createNS("feMerge");R.setAttribute("result",n);var A,L;for(L=0;L<P.length;L+=1)A=createNS("feMergeNode"),A.setAttribute("in",P[L]),R.appendChild(A),R.appendChild(A);return R}};var linearFilterValue="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0";function SVGTintFilter(T,n,P,R,A){this.filterManager=n;var L=createNS("feColorMatrix");L.setAttribute("type","matrix"),L.setAttribute("color-interpolation-filters","linearRGB"),L.setAttribute("values",linearFilterValue+" 1 0"),this.linearFilter=L,L.setAttribute("result",R+"_tint_1"),T.appendChild(L),L=createNS("feColorMatrix"),L.setAttribute("type","matrix"),L.setAttribute("color-interpolation-filters","sRGB"),L.setAttribute("values","1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0"),L.setAttribute("result",R+"_tint_2"),T.appendChild(L),this.matrixFilter=L;var O=this.createMergeNode(R,[A,R+"_tint_1",R+"_tint_2"]);T.appendChild(O)}extendPrototype([SVGComposableEffect],SVGTintFilter),SVGTintFilter.prototype.renderFrame=function(T){if(T||this.filterManager._mdf){var n=this.filterManager.effectElements[0].p.v,P=this.filterManager.effectElements[1].p.v,R=this.filterManager.effectElements[2].p.v/100;this.linearFilter.setAttribute("values",linearFilterValue+" "+R+" 0"),this.matrixFilter.setAttribute("values",P[0]-n[0]+" 0 0 0 "+n[0]+" "+(P[1]-n[1])+" 0 0 0 "+n[1]+" "+(P[2]-n[2])+" 0 0 0 "+n[2]+" 0 0 0 1 0")}};function SVGFillFilter(T,n,P,R){this.filterManager=n;var A=createNS("feColorMatrix");A.setAttribute("type","matrix"),A.setAttribute("color-interpolation-filters","sRGB"),A.setAttribute("values","1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0"),A.setAttribute("result",R),T.appendChild(A),this.matrixFilter=A}SVGFillFilter.prototype.renderFrame=function(T){if(T||this.filterManager._mdf){var n=this.filterManager.effectElements[2].p.v,P=this.filterManager.effectElements[6].p.v;this.matrixFilter.setAttribute("values","0 0 0 0 "+n[0]+" 0 0 0 0 "+n[1]+" 0 0 0 0 "+n[2]+" 0 0 0 "+P+" 0")}};function SVGStrokeEffect(T,n,P){this.initialized=!1,this.filterManager=n,this.elem=P,this.paths=[]}SVGStrokeEffect.prototype.initialize=function(){var T=this.elem.layerElement.children||this.elem.layerElement.childNodes,n,P,R,A;for(this.filterManager.effectElements[1].p.v===1?(A=this.elem.maskManager.masksProperties.length,R=0):(R=this.filterManager.effectElements[0].p.v-1,A=R+1),P=createNS("g"),P.setAttribute("fill","none"),P.setAttribute("stroke-linecap","round"),P.setAttribute("stroke-dashoffset",1),R;R<A;R+=1)n=createNS("path"),P.appendChild(n),this.paths.push({p:n,m:R});if(this.filterManager.effectElements[10].p.v===3){var L=createNS("mask"),O=createElementID();L.setAttribute("id",O),L.setAttribute("mask-type","alpha"),L.appendChild(P),this.elem.globalData.defs.appendChild(L);var N=createNS("g");for(N.setAttribute("mask","url("+getLocationHref()+"#"+O+")");T[0];)N.appendChild(T[0]);this.elem.layerElement.appendChild(N),this.masker=L,P.setAttribute("stroke","#fff")}else if(this.filterManager.effectElements[10].p.v===1||this.filterManager.effectElements[10].p.v===2){if(this.filterManager.effectElements[10].p.v===2)for(T=this.elem.layerElement.children||this.elem.layerElement.childNodes;T.length;)this.elem.layerElement.removeChild(T[0]);this.elem.layerElement.appendChild(P),this.elem.layerElement.removeAttribute("mask"),P.setAttribute("stroke","#fff")}this.initialized=!0,this.pathMasker=P},SVGStrokeEffect.prototype.renderFrame=function(T){this.initialized||this.initialize();var n,P=this.paths.length,R,A;for(n=0;n<P;n+=1)if(this.paths[n].m!==-1&&(R=this.elem.maskManager.viewData[this.paths[n].m],A=this.paths[n].p,(T||this.filterManager._mdf||R.prop._mdf)&&A.setAttribute("d",R.lastPath),T||this.filterManager.effectElements[9].p._mdf||this.filterManager.effectElements[4].p._mdf||this.filterManager.effectElements[7].p._mdf||this.filterManager.effectElements[8].p._mdf||R.prop._mdf)){var L;if(this.filterManager.effectElements[7].p.v!==0||this.filterManager.effectElements[8].p.v!==100){var O=Math.min(this.filterManager.effectElements[7].p.v,this.filterManager.effectElements[8].p.v)*.01,N=Math.max(this.filterManager.effectElements[7].p.v,this.filterManager.effectElements[8].p.v)*.01,V=A.getTotalLength();L="0 0 0 "+V*O+" ";var j=V*(N-O),B=1+this.filterManager.effectElements[4].p.v*2*this.filterManager.effectElements[9].p.v*.01,z=Math.floor(j/B),W;for(W=0;W<z;W+=1)L+="1 "+this.filterManager.effectElements[4].p.v*2*this.filterManager.effectElements[9].p.v*.01+" ";L+="0 "+V*10+" 0 0"}else L="1 "+this.filterManager.effectElements[4].p.v*2*this.filterManager.effectElements[9].p.v*.01;A.setAttribute("stroke-dasharray",L)}if((T||this.filterManager.effectElements[4].p._mdf)&&this.pathMasker.setAttribute("stroke-width",this.filterManager.effectElements[4].p.v*2),(T||this.filterManager.effectElements[6].p._mdf)&&this.pathMasker.setAttribute("opacity",this.filterManager.effectElements[6].p.v),(this.filterManager.effectElements[10].p.v===1||this.filterManager.effectElements[10].p.v===2)&&(T||this.filterManager.effectElements[3].p._mdf)){var q=this.filterManager.effectElements[3].p.v;this.pathMasker.setAttribute("stroke","rgb("+bmFloor(q[0]*255)+","+bmFloor(q[1]*255)+","+bmFloor(q[2]*255)+")")}};function SVGTritoneFilter(T,n,P,R){this.filterManager=n;var A=createNS("feColorMatrix");A.setAttribute("type","matrix"),A.setAttribute("color-interpolation-filters","linearRGB"),A.setAttribute("values","0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"),T.appendChild(A);var L=createNS("feComponentTransfer");L.setAttribute("color-interpolation-filters","sRGB"),L.setAttribute("result",R),this.matrixFilter=L;var O=createNS("feFuncR");O.setAttribute("type","table"),L.appendChild(O),this.feFuncR=O;var N=createNS("feFuncG");N.setAttribute("type","table"),L.appendChild(N),this.feFuncG=N;var V=createNS("feFuncB");V.setAttribute("type","table"),L.appendChild(V),this.feFuncB=V,T.appendChild(L)}SVGTritoneFilter.prototype.renderFrame=function(T){if(T||this.filterManager._mdf){var n=this.filterManager.effectElements[0].p.v,P=this.filterManager.effectElements[1].p.v,R=this.filterManager.effectElements[2].p.v,A=R[0]+" "+P[0]+" "+n[0],L=R[1]+" "+P[1]+" "+n[1],O=R[2]+" "+P[2]+" "+n[2];this.feFuncR.setAttribute("tableValues",A),this.feFuncG.setAttribute("tableValues",L),this.feFuncB.setAttribute("tableValues",O)}};function SVGProLevelsFilter(T,n,P,R){this.filterManager=n;var A=this.filterManager.effectElements,L=createNS("feComponentTransfer");(A[10].p.k||A[10].p.v!==0||A[11].p.k||A[11].p.v!==1||A[12].p.k||A[12].p.v!==1||A[13].p.k||A[13].p.v!==0||A[14].p.k||A[14].p.v!==1)&&(this.feFuncR=this.createFeFunc("feFuncR",L)),(A[17].p.k||A[17].p.v!==0||A[18].p.k||A[18].p.v!==1||A[19].p.k||A[19].p.v!==1||A[20].p.k||A[20].p.v!==0||A[21].p.k||A[21].p.v!==1)&&(this.feFuncG=this.createFeFunc("feFuncG",L)),(A[24].p.k||A[24].p.v!==0||A[25].p.k||A[25].p.v!==1||A[26].p.k||A[26].p.v!==1||A[27].p.k||A[27].p.v!==0||A[28].p.k||A[28].p.v!==1)&&(this.feFuncB=this.createFeFunc("feFuncB",L)),(A[31].p.k||A[31].p.v!==0||A[32].p.k||A[32].p.v!==1||A[33].p.k||A[33].p.v!==1||A[34].p.k||A[34].p.v!==0||A[35].p.k||A[35].p.v!==1)&&(this.feFuncA=this.createFeFunc("feFuncA",L)),(this.feFuncR||this.feFuncG||this.feFuncB||this.feFuncA)&&(L.setAttribute("color-interpolation-filters","sRGB"),T.appendChild(L)),(A[3].p.k||A[3].p.v!==0||A[4].p.k||A[4].p.v!==1||A[5].p.k||A[5].p.v!==1||A[6].p.k||A[6].p.v!==0||A[7].p.k||A[7].p.v!==1)&&(L=createNS("feComponentTransfer"),L.setAttribute("color-interpolation-filters","sRGB"),L.setAttribute("result",R),T.appendChild(L),this.feFuncRComposed=this.createFeFunc("feFuncR",L),this.feFuncGComposed=this.createFeFunc("feFuncG",L),this.feFuncBComposed=this.createFeFunc("feFuncB",L))}SVGProLevelsFilter.prototype.createFeFunc=function(T,n){var P=createNS(T);return P.setAttribute("type","table"),n.appendChild(P),P},SVGProLevelsFilter.prototype.getTableValue=function(T,n,P,R,A){for(var L=0,O=256,N,V=Math.min(T,n),j=Math.max(T,n),B=Array.call(null,{length:O}),z,W=0,q=A-R,H=n-T;L<=256;)N=L/256,N<=V?z=H<0?A:R:N>=j?z=H<0?R:A:z=R+q*Math.pow((N-T)/H,1/P),B[W]=z,W+=1,L+=256/(O-1);return B.join(" ")},SVGProLevelsFilter.prototype.renderFrame=function(T){if(T||this.filterManager._mdf){var n,P=this.filterManager.effectElements;this.feFuncRComposed&&(T||P[3].p._mdf||P[4].p._mdf||P[5].p._mdf||P[6].p._mdf||P[7].p._mdf)&&(n=this.getTableValue(P[3].p.v,P[4].p.v,P[5].p.v,P[6].p.v,P[7].p.v),this.feFuncRComposed.setAttribute("tableValues",n),this.feFuncGComposed.setAttribute("tableValues",n),this.feFuncBComposed.setAttribute("tableValues",n)),this.feFuncR&&(T||P[10].p._mdf||P[11].p._mdf||P[12].p._mdf||P[13].p._mdf||P[14].p._mdf)&&(n=this.getTableValue(P[10].p.v,P[11].p.v,P[12].p.v,P[13].p.v,P[14].p.v),this.feFuncR.setAttribute("tableValues",n)),this.feFuncG&&(T||P[17].p._mdf||P[18].p._mdf||P[19].p._mdf||P[20].p._mdf||P[21].p._mdf)&&(n=this.getTableValue(P[17].p.v,P[18].p.v,P[19].p.v,P[20].p.v,P[21].p.v),this.feFuncG.setAttribute("tableValues",n)),this.feFuncB&&(T||P[24].p._mdf||P[25].p._mdf||P[26].p._mdf||P[27].p._mdf||P[28].p._mdf)&&(n=this.getTableValue(P[24].p.v,P[25].p.v,P[26].p.v,P[27].p.v,P[28].p.v),this.feFuncB.setAttribute("tableValues",n)),this.feFuncA&&(T||P[31].p._mdf||P[32].p._mdf||P[33].p._mdf||P[34].p._mdf||P[35].p._mdf)&&(n=this.getTableValue(P[31].p.v,P[32].p.v,P[33].p.v,P[34].p.v,P[35].p.v),this.feFuncA.setAttribute("tableValues",n))}};function SVGDropShadowEffect(T,n,P,R,A){var L=n.container.globalData.renderConfig.filterSize,O=n.data.fs||L;T.setAttribute("x",O.x||L.x),T.setAttribute("y",O.y||L.y),T.setAttribute("width",O.width||L.width),T.setAttribute("height",O.height||L.height),this.filterManager=n;var N=createNS("feGaussianBlur");N.setAttribute("in","SourceAlpha"),N.setAttribute("result",R+"_drop_shadow_1"),N.setAttribute("stdDeviation","0"),this.feGaussianBlur=N,T.appendChild(N);var V=createNS("feOffset");V.setAttribute("dx","25"),V.setAttribute("dy","0"),V.setAttribute("in",R+"_drop_shadow_1"),V.setAttribute("result",R+"_drop_shadow_2"),this.feOffset=V,T.appendChild(V);var j=createNS("feFlood");j.setAttribute("flood-color","#00ff00"),j.setAttribute("flood-opacity","1"),j.setAttribute("result",R+"_drop_shadow_3"),this.feFlood=j,T.appendChild(j);var B=createNS("feComposite");B.setAttribute("in",R+"_drop_shadow_3"),B.setAttribute("in2",R+"_drop_shadow_2"),B.setAttribute("operator","in"),B.setAttribute("result",R+"_drop_shadow_4"),T.appendChild(B);var z=this.createMergeNode(R,[R+"_drop_shadow_4",A]);T.appendChild(z)}extendPrototype([SVGComposableEffect],SVGDropShadowEffect),SVGDropShadowEffect.prototype.renderFrame=function(T){if(T||this.filterManager._mdf){if((T||this.filterManager.effectElements[4].p._mdf)&&this.feGaussianBlur.setAttribute("stdDeviation",this.filterManager.effectElements[4].p.v/4),T||this.filterManager.effectElements[0].p._mdf){var n=this.filterManager.effectElements[0].p.v;this.feFlood.setAttribute("flood-color",rgbToHex(Math.round(n[0]*255),Math.round(n[1]*255),Math.round(n[2]*255)))}if((T||this.filterManager.effectElements[1].p._mdf)&&this.feFlood.setAttribute("flood-opacity",this.filterManager.effectElements[1].p.v/255),T||this.filterManager.effectElements[2].p._mdf||this.filterManager.effectElements[3].p._mdf){var P=this.filterManager.effectElements[3].p.v,R=(this.filterManager.effectElements[2].p.v-90)*degToRads,A=P*Math.cos(R),L=P*Math.sin(R);this.feOffset.setAttribute("dx",A),this.feOffset.setAttribute("dy",L)}}};var _svgMatteSymbols=[];function SVGMatte3Effect(T,n,P){this.initialized=!1,this.filterManager=n,this.filterElem=T,this.elem=P,P.matteElement=createNS("g"),P.matteElement.appendChild(P.layerElement),P.matteElement.appendChild(P.transformedElement),P.baseElement=P.matteElement}SVGMatte3Effect.prototype.findSymbol=function(T){for(var n=0,P=_svgMatteSymbols.length;n<P;){if(_svgMatteSymbols[n]===T)return _svgMatteSymbols[n];n+=1}return null},SVGMatte3Effect.prototype.replaceInParent=function(T,n){var P=T.layerElement.parentNode;if(P){for(var R=P.children,A=0,L=R.length;A<L&&R[A]!==T.layerElement;)A+=1;var O;A<=L-2&&(O=R[A+1]);var N=createNS("use");N.setAttribute("href","#"+n),O?P.insertBefore(N,O):P.appendChild(N)}},SVGMatte3Effect.prototype.setElementAsMask=function(T,n){if(!this.findSymbol(n)){var P=createElementID(),R=createNS("mask");R.setAttribute("id",n.layerId),R.setAttribute("mask-type","alpha"),_svgMatteSymbols.push(n);var A=T.globalData.defs;A.appendChild(R);var L=createNS("symbol");L.setAttribute("id",P),this.replaceInParent(n,P),L.appendChild(n.layerElement),A.appendChild(L);var O=createNS("use");O.setAttribute("href","#"+P),R.appendChild(O),n.data.hd=!1,n.show()}T.setMatte(n.layerId)},SVGMatte3Effect.prototype.initialize=function(){for(var T=this.filterManager.effectElements[0].p.v,n=this.elem.comp.elements,P=0,R=n.length;P<R;)n[P]&&n[P].data.ind===T&&this.setElementAsMask(this.elem,n[P]),P+=1;this.initialized=!0},SVGMatte3Effect.prototype.renderFrame=function(){this.initialized||this.initialize()};function SVGGaussianBlurEffect(T,n,P,R){T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%"),this.filterManager=n;var A=createNS("feGaussianBlur");A.setAttribute("result",R),T.appendChild(A),this.feGaussianBlur=A}SVGGaussianBlurEffect.prototype.renderFrame=function(T){if(T||this.filterManager._mdf){var n=.3,P=this.filterManager.effectElements[0].p.v*n,R=this.filterManager.effectElements[1].p.v,A=R==3?0:P,L=R==2?0:P;this.feGaussianBlur.setAttribute("stdDeviation",A+" "+L);var O=this.filterManager.effectElements[2].p.v==1?"wrap":"duplicate";this.feGaussianBlur.setAttribute("edgeMode",O)}};function TransformEffect(){}TransformEffect.prototype.init=function(T){this.effectsManager=T,this.type=effectTypes.TRANSFORM_EFFECT,this.matrix=new Matrix,this.opacity=-1,this._mdf=!1,this._opMdf=!1},TransformEffect.prototype.renderFrame=function(T){if(this._opMdf=!1,this._mdf=!1,T||this.effectsManager._mdf){var n=this.effectsManager.effectElements,P=n[0].p.v,R=n[1].p.v,A=n[2].p.v===1,L=n[3].p.v,O=A?L:n[4].p.v,N=n[5].p.v,V=n[6].p.v,j=n[7].p.v;this.matrix.reset(),this.matrix.translate(-P[0],-P[1],P[2]),this.matrix.scale(O*.01,L*.01,1),this.matrix.rotate(-j*degToRads),this.matrix.skewFromAxis(-N*degToRads,(V+90)*degToRads),this.matrix.translate(R[0],R[1],0),this._mdf=!0,this.opacity!==n[8].p.v&&(this.opacity=n[8].p.v,this._opMdf=!0)}};function SVGTransformEffect(T,n){this.init(n)}extendPrototype([TransformEffect],SVGTransformEffect);function CVTransformEffect(T){this.init(T)}return extendPrototype([TransformEffect],CVTransformEffect),registerRenderer("canvas",CanvasRenderer),registerRenderer("html",HybridRenderer),registerRenderer("svg",SVGRenderer),ShapeModifiers.registerModifier("tm",TrimModifier),ShapeModifiers.registerModifier("pb",PuckerAndBloatModifier),ShapeModifiers.registerModifier("rp",RepeaterModifier),ShapeModifiers.registerModifier("rd",RoundCornersModifier),ShapeModifiers.registerModifier("zz",ZigZagModifier),ShapeModifiers.registerModifier("op",OffsetPathModifier),setExpressionsPlugin(Expressions),setExpressionInterfaces(getInterface),initialize$1(),initialize(),registerEffect$1(20,SVGTintFilter,!0),registerEffect$1(21,SVGFillFilter,!0),registerEffect$1(22,SVGStrokeEffect,!1),registerEffect$1(23,SVGTritoneFilter,!0),registerEffect$1(24,SVGProLevelsFilter,!0),registerEffect$1(25,SVGDropShadowEffect,!0),registerEffect$1(28,SVGMatte3Effect,!1),registerEffect$1(29,SVGGaussianBlurEffect,!0),registerEffect$1(35,SVGTransformEffect,!1),registerEffect(35,CVTransformEffect),lottie}))})(lottie$2,lottie$2.exports)),lottie$2.exports}var lottieExports=requireLottie();const lottie=getDefaultExportFromCjs$1(lottieExports);function _arrayLikeToArray(T,n){(n==null||n>T.length)&&(n=T.length);for(var P=0,R=Array(n);P<n;P++)R[P]=T[P];return R}function _arrayWithHoles(T){if(Array.isArray(T))return T}function _defineProperty(T,n,P){return(n=_toPropertyKey(n))in T?Object.defineProperty(T,n,{value:P,enumerable:!0,configurable:!0,writable:!0}):T[n]=P,T}function _iterableToArrayLimit(T,n){var P=T==null?null:typeof Symbol<"u"&&T[Symbol.iterator]||T["@@iterator"];if(P!=null){var R,A,L,O,N=[],V=!0,j=!1;try{if(L=(P=P.call(T)).next,n!==0)for(;!(V=(R=L.call(P)).done)&&(N.push(R.value),N.length!==n);V=!0);}catch(B){j=!0,A=B}finally{try{if(!V&&P.return!=null&&(O=P.return(),Object(O)!==O))return}finally{if(j)throw A}}return N}}function _nonIterableRest(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
491
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ownKeys(T,n){var P=Object.keys(T);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(T);n&&(R=R.filter(function(A){return Object.getOwnPropertyDescriptor(T,A).enumerable})),P.push.apply(P,R)}return P}function _objectSpread2(T){for(var n=1;n<arguments.length;n++){var P=arguments[n]!=null?arguments[n]:{};n%2?ownKeys(Object(P),!0).forEach(function(R){_defineProperty(T,R,P[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(T,Object.getOwnPropertyDescriptors(P)):ownKeys(Object(P)).forEach(function(R){Object.defineProperty(T,R,Object.getOwnPropertyDescriptor(P,R))})}return T}function _objectWithoutProperties(T,n){if(T==null)return{};var P,R,A=_objectWithoutPropertiesLoose(T,n);if(Object.getOwnPropertySymbols){var L=Object.getOwnPropertySymbols(T);for(R=0;R<L.length;R++)P=L[R],n.includes(P)||{}.propertyIsEnumerable.call(T,P)&&(A[P]=T[P])}return A}function _objectWithoutPropertiesLoose(T,n){if(T==null)return{};var P={};for(var R in T)if({}.hasOwnProperty.call(T,R)){if(n.includes(R))continue;P[R]=T[R]}return P}function _slicedToArray(T,n){return _arrayWithHoles(T)||_iterableToArrayLimit(T,n)||_unsupportedIterableToArray(T,n)||_nonIterableRest()}function _toPrimitive(T,n){if(typeof T!="object"||!T)return T;var P=T[Symbol.toPrimitive];if(P!==void 0){var R=P.call(T,n);if(typeof R!="object")return R;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(T)}function _toPropertyKey(T){var n=_toPrimitive(T,"string");return typeof n=="symbol"?n:n+""}function _unsupportedIterableToArray(T,n){if(T){if(typeof T=="string")return _arrayLikeToArray(T,n);var P={}.toString.call(T).slice(8,-1);return P==="Object"&&T.constructor&&(P=T.constructor.name),P==="Map"||P==="Set"?Array.from(T):P==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(P)?_arrayLikeToArray(T,n):void 0}}var _excluded$1=["animationData","loop","autoplay","initialSegment","onComplete","onLoopComplete","onEnterFrame","onSegmentStart","onConfigReady","onDataReady","onDataFailed","onLoadedImages","onDOMLoaded","onDestroy","lottieRef","renderer","name","assetsPath","rendererSettings"],useLottie=function T(n,P){var R=n.animationData,A=n.loop,L=n.autoplay,O=n.initialSegment,N=n.onComplete,V=n.onLoopComplete,j=n.onEnterFrame,B=n.onSegmentStart,z=n.onConfigReady,W=n.onDataReady,q=n.onDataFailed,H=n.onLoadedImages,$=n.onDOMLoaded,Q=n.onDestroy;n.lottieRef,n.renderer,n.name,n.assetsPath,n.rendererSettings;var U=_objectWithoutProperties(n,_excluded$1),J=React.useState(!1),G=_slicedToArray(J,2),K=G[0],Y=G[1],Z=React.useRef(),ie=React.useRef(null),se=function(){var de;(de=Z.current)===null||de===void 0||de.play()},le=function(){var de;(de=Z.current)===null||de===void 0||de.stop()},pe=function(){var de;(de=Z.current)===null||de===void 0||de.pause()},ue=function(de){var ge;(ge=Z.current)===null||ge===void 0||ge.setSpeed(de)},he=function(de,ge){var ye;(ye=Z.current)===null||ye===void 0||ye.goToAndPlay(de,ge)},ve=function(de,ge){var ye;(ye=Z.current)===null||ye===void 0||ye.goToAndStop(de,ge)},be=function(de){var ge;(ge=Z.current)===null||ge===void 0||ge.setDirection(de)},fe=function(de,ge){var ye;(ye=Z.current)===null||ye===void 0||ye.playSegments(de,ge)},ne=function(de){var ge;(ge=Z.current)===null||ge===void 0||ge.setSubframe(de)},ce=function(de){var ge;return(ge=Z.current)===null||ge===void 0?void 0:ge.getDuration(de)},ee=function(){var de;(de=Z.current)===null||de===void 0||de.destroy(),Z.current=void 0},te=function(){var de=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ge;if(ie.current){(ge=Z.current)===null||ge===void 0||ge.destroy();var ye=_objectSpread2(_objectSpread2(_objectSpread2({},n),de),{},{container:ie.current});return Z.current=lottie.loadAnimation(ye),Y(!!Z.current),function(){var Ee;(Ee=Z.current)===null||Ee===void 0||Ee.destroy(),Z.current=void 0}}};React.useEffect(function(){var ae=te();return function(){return ae?.()}},[R,A]),React.useEffect(function(){Z.current&&(Z.current.autoplay=!!L)},[L]),React.useEffect(function(){if(Z.current){if(!O){Z.current.resetSegments(!0);return}!Array.isArray(O)||!O.length||((Z.current.currentRawFrame<O[0]||Z.current.currentRawFrame>O[1])&&(Z.current.currentRawFrame=O[0]),Z.current.setSegment(O[0],O[1]))}},[O]),React.useEffect(function(){var ae=[{name:"complete",handler:N},{name:"loopComplete",handler:V},{name:"enterFrame",handler:j},{name:"segmentStart",handler:B},{name:"config_ready",handler:z},{name:"data_ready",handler:W},{name:"data_failed",handler:q},{name:"loaded_images",handler:H},{name:"DOMLoaded",handler:$},{name:"destroy",handler:Q}],de=ae.filter(function(ye){return ye.handler!=null});if(de.length){var ge=de.map(function(ye){var Ee;return(Ee=Z.current)===null||Ee===void 0||Ee.addEventListener(ye.name,ye.handler),function(){var Pe;(Pe=Z.current)===null||Pe===void 0||Pe.removeEventListener(ye.name,ye.handler)}});return function(){ge.forEach(function(ye){return ye()})}}},[N,V,j,B,z,W,q,H,$,Q]);var oe=React.createElement("div",_objectSpread2({style:P,ref:ie},U));return{View:oe,play:se,stop:le,pause:pe,setSpeed:ue,goToAndStop:ve,goToAndPlay:he,setDirection:be,playSegments:fe,setSubframe:ne,getDuration:ce,destroy:ee,animationContainerRef:ie,animationLoaded:K,animationItem:Z.current}};function getContainerVisibility(T){var n=T.getBoundingClientRect(),P=n.top,R=n.height,A=window.innerHeight-P,L=window.innerHeight+R;return A/L}function getContainerCursorPosition(T,n,P){var R=T.getBoundingClientRect(),A=R.top,L=R.left,O=R.width,N=R.height,V=(n-L)/O,j=(P-A)/N;return{x:V,y:j}}var useInitInteractivity=function T(n){var P=n.wrapperRef,R=n.animationItem,A=n.mode,L=n.actions;React.useEffect(function(){var O=P.current;if(!(!O||!R||!L.length)){R.stop();var N=function(){var B=null,z=function(){var q=getContainerVisibility(O),H=L.find(function(Q){var U=Q.visibility;return U&&q>=U[0]&&q<=U[1]});if(H){if(H.type==="seek"&&H.visibility&&H.frames.length===2){var $=H.frames[0]+Math.ceil((q-H.visibility[0])/(H.visibility[1]-H.visibility[0])*H.frames[1]);//! goToAndStop must be relative to the start of the current segment
|
|
492
|
+
R.goToAndStop($-R.firstFrame-1,!0)}H.type==="loop"&&(B===null||B!==H.frames||R.isPaused)&&(R.playSegments(H.frames,!0),B=H.frames),H.type==="play"&&R.isPaused&&(R.resetSegments(!0),R.play()),H.type==="stop"&&R.goToAndStop(H.frames[0]-R.firstFrame-1,!0)}};return document.addEventListener("scroll",z),function(){document.removeEventListener("scroll",z)}},V=function(){var B=function(H,$){var Q=H,U=$;if(Q!==-1&&U!==-1){var J=getContainerCursorPosition(O,Q,U);Q=J.x,U=J.y}var G=L.find(function(Z){var ie=Z.position;return ie&&Array.isArray(ie.x)&&Array.isArray(ie.y)?Q>=ie.x[0]&&Q<=ie.x[1]&&U>=ie.y[0]&&U<=ie.y[1]:ie&&!Number.isNaN(ie.x)&&!Number.isNaN(ie.y)?Q===ie.x&&U===ie.y:!1});if(G){if(G.type==="seek"&&G.position&&Array.isArray(G.position.x)&&Array.isArray(G.position.y)&&G.frames.length===2){var K=(Q-G.position.x[0])/(G.position.x[1]-G.position.x[0]),Y=(U-G.position.y[0])/(G.position.y[1]-G.position.y[0]);R.playSegments(G.frames,!0),R.goToAndStop(Math.ceil((K+Y)/2*(G.frames[1]-G.frames[0])),!0)}G.type==="loop"&&R.playSegments(G.frames,!0),G.type==="play"&&(R.isPaused&&R.resetSegments(!1),R.playSegments(G.frames)),G.type==="stop"&&R.goToAndStop(G.frames[0],!0)}},z=function(H){B(H.clientX,H.clientY)},W=function(){B(-1,-1)};return O.addEventListener("mousemove",z),O.addEventListener("mouseout",W),function(){O.removeEventListener("mousemove",z),O.removeEventListener("mouseout",W)}};switch(A){case"scroll":return N();case"cursor":return V()}}},[A,R])},useLottieInteractivity=function T(n){var P=n.actions,R=n.mode,A=n.lottieObj,L=A.animationItem,O=A.View,N=A.animationContainerRef;return useInitInteractivity({actions:P,animationItem:L,mode:R,wrapperRef:N}),O},_excluded=["style","interactivity"],Lottie=function T(n){var P,R,A,L=n.style,O=n.interactivity,N=_objectWithoutProperties(n,_excluded),V=useLottie(N,L),j=V.View,B=V.play,z=V.stop,W=V.pause,q=V.setSpeed,H=V.goToAndStop,$=V.goToAndPlay,Q=V.setDirection,U=V.playSegments,J=V.setSubframe,G=V.getDuration,K=V.destroy,Y=V.animationContainerRef,Z=V.animationLoaded,ie=V.animationItem;return React.useEffect(function(){n.lottieRef&&(n.lottieRef.current={play:B,stop:z,pause:W,setSpeed:q,goToAndPlay:$,goToAndStop:H,setDirection:Q,playSegments:U,setSubframe:J,getDuration:G,destroy:K,animationContainerRef:Y,animationLoaded:Z,animationItem:ie})},[(P=n.lottieRef)===null||P===void 0?void 0:P.current]),useLottieInteractivity({lottieObj:{View:j,play:B,stop:z,pause:W,setSpeed:q,goToAndStop:H,goToAndPlay:$,setDirection:Q,playSegments:U,setSubframe:J,getDuration:G,destroy:K,animationContainerRef:Y,animationLoaded:Z,animationItem:ie},actions:(R=O?.actions)!==null&&R!==void 0?R:[],mode:(A=O?.mode)!==null&&A!==void 0?A:"scroll"})};const nm="Comp 1",ddd=0,h$2=700,w$1=700,meta={g:"@lottiefiles/toolkit-js 0.22.1"},layers=[{ty:0,nm:"Pre-comp 3",sr:1,st:141.000005743048,op:231.000009408823,ip:141.000005743048,hd:!1,ddd:0,bm:0,hasMask:!1,ao:0,ks:{a:{a:0,k:[350,350,0],ix:1},s:{a:0,k:[100,100,100],ix:6},sk:{a:0,k:0},p:{a:0,k:[350,350,0],ix:2},r:{a:0,k:0,ix:10},sa:{a:0,k:0},o:{a:0,k:100,ix:11}},ef:[],w:700,h:700,refId:"comp_0",ind:1},{ty:0,nm:"Pre-comp 3",sr:1,st:71.0000028918893,op:161.000006557664,ip:71.0000028918893,hd:!1,ddd:0,bm:0,hasMask:!1,ao:0,ks:{a:{a:0,k:[350,350,0],ix:1},s:{a:0,k:[100,100,100],ix:6},sk:{a:0,k:0},p:{a:0,k:[350,350,0],ix:2},r:{a:0,k:0,ix:10},sa:{a:0,k:0},o:{a:0,k:100,ix:11}},ef:[],w:700,h:700,refId:"comp_0",ind:2},{ty:0,nm:"Pre-comp 3",sr:1,st:0,op:90.0000036657751,ip:0,hd:!1,ddd:0,bm:0,hasMask:!1,ao:0,ks:{a:{a:0,k:[350,350,0],ix:1},s:{a:0,k:[100,100,100],ix:6},sk:{a:0,k:0},p:{a:0,k:[350,350,0],ix:2},r:{a:0,k:0,ix:10},sa:{a:0,k:0},o:{a:0,k:100,ix:11}},ef:[],w:700,h:700,refId:"comp_0",ind:3},{ty:0,nm:"bubble",sr:1,st:0,op:600.000024438501,ip:0,hd:!1,ddd:0,bm:0,hasMask:!1,ao:0,ks:{a:{a:0,k:[350,350,0],ix:1},s:{a:0,k:[91,91,100],ix:6},sk:{a:0,k:0},p:{a:0,k:[350,350,0],ix:2},r:{a:0,k:43,ix:10},sa:{a:0,k:0},o:{a:0,k:70,ix:11}},ef:[{ty:0,mn:"ADBE Gaussian Blur 2",nm:"Gaussian Blur",ix:1,en:1,ef:[{ty:0,mn:"ADBE Gaussian Blur 2-0001",nm:"Blurriness",ix:1,v:{a:0,k:40.5,ix:1}},{ty:7,mn:"ADBE Gaussian Blur 2-0002",nm:"Blur Dimensions",ix:2,v:{a:0,k:1,ix:2}},{ty:7,mn:"ADBE Gaussian Blur 2-0003",nm:"Repeat Edge Pixels",ix:3,v:{a:0,k:0,ix:3}}]}],w:700,h:700,refId:"comp_4",ind:4},{ty:0,nm:"bubble",sr:1,st:0,op:600.000024438501,ip:0,hd:!1,ddd:0,bm:0,hasMask:!1,ao:0,ks:{a:{a:0,k:[350,350,0],ix:1},s:{a:0,k:[100,100,100],ix:6},sk:{a:0,k:0},p:{a:0,k:[350,350,0],ix:2},r:{a:0,k:226,ix:10},sa:{a:0,k:0},o:{a:0,k:48,ix:11}},ef:[{ty:0,mn:"ADBE Tint",nm:"Tint",ix:1,en:1,ef:[{ty:2,mn:"ADBE Tint-0001",nm:"Map Black To",ix:1,v:{a:0,k:[0,0,0,0],ix:1}},{ty:2,mn:"ADBE Tint-0002",nm:"Map White To",ix:2,v:{a:0,k:[1,0,.7765],ix:2}},{ty:0,mn:"ADBE Tint-0003",nm:"Amount to Tint",ix:3,v:{a:0,k:100,ix:3}},{ty:6,mn:"ADBE Tint-0004",nm:"",ix:4,v:0}]}],w:700,h:700,refId:"comp_4",ind:5},{ty:0,nm:"bubble",sr:1,st:0,op:600.000024438501,ip:0,hd:!1,ddd:0,bm:0,hasMask:!1,ao:0,ks:{a:{a:0,k:[350,350,0],ix:1},s:{a:0,k:[100,100,100],ix:6},sk:{a:0,k:0},p:{a:0,k:[350,350,0],ix:2},r:{a:0,k:0,ix:10},sa:{a:0,k:0},o:{a:0,k:100,ix:11}},ef:[],w:700,h:700,refId:"comp_4",ind:6}],v$1="5.5.5",fr=29.9700012207031,op=231.000009408823,ip=0,assets=JSON.parse('[{"nm":"","id":"comp_0","layers":[{"ty":0,"nm":"Pre-comp 2","sr":1,"st":13.0000005295009,"op":90.0000036657751,"ip":13.0000005295009,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":42,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":55,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_1","ind":1},{"ty":0,"nm":"Pre-comp 2","sr":1,"st":0,"op":77.0000031362743,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_1","ind":2}]},{"nm":"","id":"comp_1","layers":[{"ty":0,"nm":"Pre-comp 1","sr":1,"st":9.00000036657752,"op":77.0000031362743,"ip":9.00000036657752,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":69,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[{"ty":0,"mn":"ADBE Tint","nm":"Tint","ix":1,"en":1,"ef":[{"ty":2,"mn":"ADBE Tint-0001","nm":"Map Black To","ix":1,"v":{"a":0,"k":[0,0,0,0],"ix":1}},{"ty":2,"mn":"ADBE Tint-0002","nm":"Map White To","ix":2,"v":{"a":0,"k":[1,0.4078,0.6588],"ix":2}},{"ty":0,"mn":"ADBE Tint-0003","nm":"Amount to Tint","ix":3,"v":{"a":0,"k":100,"ix":3}},{"ty":6,"mn":"ADBE Tint-0004","nm":"","ix":4,"v":0}]}],"w":700,"h":700,"refId":"comp_2","ind":1},{"ty":0,"nm":"Pre-comp 1","sr":1,"st":0,"op":68.0000027696968,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_2","ind":2}]},{"nm":"","id":"comp_2","layers":[{"ty":0,"nm":"Shape Layer 1 Comp 1","sr":1,"st":0,"op":47.0000019143492,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":275,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_3","ind":1},{"ty":0,"nm":"Shape Layer 1 Comp 1","sr":1,"st":12.00000048877,"op":59.0000024031193,"ip":12.00000048877,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":227,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_3","ind":2},{"ty":0,"nm":"Shape Layer 1 Comp 1","sr":1,"st":5.00000020365417,"op":52.0000021180034,"ip":5.00000020365417,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":140,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_3","ind":3},{"ty":0,"nm":"Shape Layer 1 Comp 1","sr":1,"st":21.0000008553475,"op":68.0000027696968,"ip":21.0000008553475,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":48,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_3","ind":4},{"ty":0,"nm":"Shape Layer 1 Comp 1","sr":1,"st":14.0000005702317,"op":61.0000024845809,"ip":14.0000005702317,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[350,350,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"w":700,"h":700,"refId":"comp_3","ind":5}]},{"nm":"","id":"comp_3","layers":[{"ty":4,"nm":"Shape Layer 1","sr":1,"st":0,"op":47.0000019143492,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[-261,141,0],"ix":1},"s":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[0,0,100],"t":0},{"s":[100,100,100],"t":48.0000019550801}],"ix":6},"sk":{"a":0,"k":0},"p":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[349,350,0],"t":0,"ti":[19.167,-15.333,0],"to":[-19.167,15.333,0]},{"s":[234,442,0],"t":48.0000019550801}],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[100],"t":26},{"s":[0],"t":46.0000018736184}],"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[12,12],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"fl","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Fill","nm":"Fill 1","c":{"a":0,"k":[1,0.9529,0.9725],"ix":4},"r":1,"o":{"a":0,"k":100,"ix":5}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[-261,141],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":1}]},{"nm":"","id":"comp_4","layers":[{"ty":4,"nm":"Shape Layer 1","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[0],"t":0},{"s":[720],"t":231.000009408823}],"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[400,400],"ix":2}},{"ty":"gs","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Stroke","nm":"Gradient Stroke 1","e":{"a":0,"k":[-761.875,495.96],"ix":5},"g":{"p":3,"k":{"a":0,"k":[0,1,1,1,0.496,0.9882352941176471,0.39215686274509803,0.17647058823529413,0.993,1,0.35294117647058826,0.37254901960784315,0,0,0.496,1,0.993,1],"ix":8}},"t":2,"a":{"a":0,"k":0,"ix":7},"h":{"a":0,"k":0,"ix":6},"s":{"a":0,"k":[154.435,-126.834],"ix":4},"lc":1,"lj":1,"ml":4,"o":{"a":0,"k":100,"ix":9},"w":{"a":0,"k":1,"ix":10}},{"ty":"fl","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Fill","nm":"Fill 1","c":{"a":0,"k":[1,0.9529,0.9725],"ix":4},"r":1,"o":{"a":0,"k":0,"ix":5}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[1,-1],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":1},{"ty":4,"nm":"Shape Layer 10","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[59.113,-37.893,0],"ix":1},"s":{"a":0,"k":[131.951,131.951,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[351,351,0],"ix":2},"r":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[382],"t":0},{"s":[742],"t":231.000009408823}],"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Shape 1","ix":1,"cix":2,"np":3,"it":[{"ty":"sh","bm":0,"hd":false,"mn":"ADBE Vector Shape - Group","nm":"Path 1","ix":1,"d":1,"ks":{"a":0,"k":{"c":true,"i":[[0,75.084],[-2.326,11.481],[8.484,-20.679],[0,-18.258],[-75.111,0],[-2.638,0.152]],"o":[[0,-12.43],[4.439,-21.907],[-6.526,15.906],[0,75.111],[2.677,0],[-56.982,-4.209]],"v":[[-30.208,-36.759],[-26.642,-72.724],[-61.861,-83.451],[-71.985,-31.87],[64.015,104.13],[71.985,103.892]]},"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[100,0],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0,1,0.9529411764705882,0.9725490196078431,0.487,1,0.9529411764705882,0.9725490196078431,0.998,0.5176470588235295,0,1,0,1,0.487,1,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[0,0],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[0,0],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":2},{"ty":4,"nm":"Shape Layer 4","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[-128,0,0],"ix":1},"s":{"a":0,"k":[65.625,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[222,350,0],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":54,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[16,16],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[100,0],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0.002,1,1,1,0.488,1,1,1,0.998,1,1,1,0.002,1,0.488,0.5,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[0,0],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[-128,0],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":3},{"ty":4,"nm":"Shape Layer 8","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"td":1,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[0],"t":0},{"s":[360],"t":59.0000024031193}],"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[400,400],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[202.396,-0.369],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0,1,1,1,0.487,1,1,1,0.998,1,1,1,0,0.44,0.487,0.22,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[0,0],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[1,-1],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":4},{"ty":4,"nm":"Shape Layer 7","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"tt":1,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[-118,46,0],"ix":1},"s":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[33.333,100,100],"t":0},{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[100,100,100],"t":29},{"s":[33.333,100,100],"t":59.0000024031193}],"ix":6},"sk":{"a":0,"k":0},"p":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[106,342,0],"t":0,"ti":[-81.667,0,0],"to":[81.667,0,0]},{"s":[596,342,0],"t":59.0000024031193}],"ix":2},"r":{"a":0,"k":38,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":39,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Rectangle 1","ix":1,"cix":2,"np":3,"it":[{"ty":"rc","bm":0,"hd":false,"mn":"ADBE Vector Shape - Rect","nm":"Rectangle Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"r":{"a":0,"k":0,"ix":4},"s":{"a":0,"k":[72,596],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[-2.662,190],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0,1,1,1,0.487,1,1,1,0.998,1,1,1,0,0.44,0.487,0.22,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[1.369,-19],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[-118,46],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":5},{"ty":4,"nm":"Shape Layer 6","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[146.132,146.132,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[142,142],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[60.839,0],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0,0.8549019607843137,0.8549019607843137,0.8549019607843137,0.487,0.9254901960784314,0.9254901960784314,0.9254901960784314,0.998,1,1,1,0,0.44,0.487,0.22,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[0,0],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[181.304,181.304],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[0,-3],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":6},{"ty":4,"nm":"Shape Layer 5","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[124.841,124.841,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,458,0],"ix":2},"r":{"a":0,"k":180,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":10,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Shape 2","ix":1,"cix":2,"np":3,"it":[{"ty":"sh","bm":0,"hd":false,"mn":"ADBE Vector Shape - Group","nm":"Path 1","ix":1,"d":1,"ks":{"a":0,"k":{"c":true,"i":[[0,0],[-36.43,1.19],[0,0],[24.53,-18.36]],"o":[[25.85,-22.17],[0,0],[-32.74,1.05],[0,0]],"v":[[-100.64,-30.635],[-5.11,-67.775],[-5.11,37.125],[-92.55,67.775]]},"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[0,105.643],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0,1,1,1,0.487,1,1,1,0.998,1,1,1,0,1,0.487,0.5,0.998,0],"ix":9}},"t":1,"a":{"a":0,"k":0},"h":{"a":0,"k":0},"s":{"a":0,"k":[-1,-118.622],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[0,0],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]},{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Shape 1","ix":2,"cix":2,"np":3,"it":[{"ty":"sh","bm":0,"hd":false,"mn":"ADBE Vector Shape - Group","nm":"Path 1","ix":1,"d":1,"ks":{"a":0,"k":{"c":true,"i":[[-25.85,-22.17],[0,0],[32.74,1.05],[0,0]],"o":[[0,0],[-24.53,-18.36],[0,0],[36.43,1.19]],"v":[[100.64,-30.635],[92.55,67.775],[5.11,37.125],[5.11,-67.775]]},"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[0,105.643],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0,1,1,1,0.487,1,1,1,0.998,1,1,1,0,1,0.487,0.5,0.998,0],"ix":9}},"t":1,"a":{"a":0,"k":0},"h":{"a":0,"k":0},"s":{"a":0,"k":[-1,-118.622],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[0,0],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":7},{"ty":4,"nm":"Shape Layer 3","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[343,317,0],"ix":2},"r":{"a":0,"k":0,"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[177,116],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[100,0],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0.002,0.9529411764705882,0.9529411764705882,0.9529411764705882,0.488,0.9764705882352941,0.9764705882352941,0.9764705882352941,0.998,1,1,1,0.002,1,0.488,0.5,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[-10,-146],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[7.5,-104],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":8},{"ty":4,"nm":"Shape Layer 9","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[190],"t":0},{"s":[550],"t":230.000009368092}],"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[400,400],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[29.602,-44.441],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0.002,0.5450980392156862,0.9882352941176471,0.9725490196078431,0.488,0.5686274509803921,0.7294117647058823,0.7176470588235294,0.998,1,0,0,0.002,1,0.488,0.5,0.998,0],"ix":9}},"t":2,"a":{"a":0,"k":0,"ix":8},"h":{"a":0,"k":0,"ix":7},"s":{"a":0,"k":[-131.837,65.407],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[1,-1],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":9},{"ty":4,"nm":"Shape Layer 2","sr":1,"st":0,"op":600.000024438501,"ip":0,"hd":false,"ddd":0,"bm":0,"hasMask":false,"ao":0,"ks":{"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6},"sk":{"a":0,"k":0},"p":{"a":0,"k":[350,350,0],"ix":2},"r":{"a":1,"k":[{"o":{"x":0.167,"y":0.167},"i":{"x":0.833,"y":0.833},"s":[190],"t":0},{"s":[1270],"t":230.000009368092}],"ix":10},"sa":{"a":0,"k":0},"o":{"a":0,"k":100,"ix":11}},"ef":[],"shapes":[{"ty":"gr","bm":0,"hd":false,"mn":"ADBE Vector Group","nm":"Ellipse 1","ix":1,"cix":2,"np":3,"it":[{"ty":"el","bm":0,"hd":false,"mn":"ADBE Vector Shape - Ellipse","nm":"Ellipse Path 1","d":1,"p":{"a":0,"k":[0,0],"ix":3},"s":{"a":0,"k":[400,400],"ix":2}},{"ty":"st","bm":0,"hd":false,"mn":"ADBE Vector Graphic - Stroke","nm":"Stroke 1","lc":1,"lj":1,"ml":4,"o":{"a":0,"k":0,"ix":4},"w":{"a":0,"k":3,"ix":5},"c":{"a":0,"k":[0.9529,0.9608,0.9686],"ix":3}},{"ty":"gf","bm":0,"hd":false,"mn":"ADBE Vector Graphic - G-Fill","nm":"Gradient Fill 1","e":{"a":0,"k":[-48.365,-83.495],"ix":6},"g":{"p":3,"k":{"a":0,"k":[0.002,0.9882352941176471,0.7333333333333333,0.984313725490196,0.488,0.5254901960784314,0.9686274509803922,0.9294117647058824,0.998,1,0,0.8470588235294118,0.002,1,0.488,1,0.998,0],"ix":9}},"t":1,"a":{"a":0,"k":0},"h":{"a":0,"k":0},"s":{"a":0,"k":[-134.449,-317.964],"ix":5},"r":1,"o":{"a":0,"k":100,"ix":10}},{"ty":"tr","a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"sk":{"a":0,"k":0,"ix":4},"p":{"a":0,"k":[1,-1],"ix":2},"r":{"a":0,"k":0,"ix":6},"sa":{"a":0,"k":0,"ix":5},"o":{"a":0,"k":100,"ix":7}}]}],"ind":10}]}]'),newAgentVoiceAnimation={nm,ddd,h:h$2,w:w$1,meta,layers,v:v$1,fr,op,ip,assets},LoadingState=({primaryColor:T})=>jsxRuntime.jsx("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center min-h-0",children:jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center space-y-6",children:[jsxRuntime.jsx("div",{className:"w-48 h-48 flex items-center justify-center bg-transparent p-8",style:{overflow:"visible"},children:jsxRuntime.jsx("div",{style:{width:"120%",height:"120%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible"},children:jsxRuntime.jsx(Lottie,{animationData:newAgentVoiceAnimation,loop:!0,autoplay:!0,rendererSettings:{preserveAspectRatio:"xMidYMid meet",progressiveLoad:!0,filterSize:{width:"400%",height:"400%",x:"-150%",y:"-150%"},renderer:"svg",clearCanvas:!0,context:null,scaleMode:"noScale",imagePreserveAspectRatio:"xMidYMid meet"},style:{width:"100%",height:"100%",background:"transparent",overflow:"visible",WebkitTransform:"translateZ(0)",transform:"translateZ(0)",willChange:"transform",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden"}})})}),jsxRuntime.jsx("div",{className:"text-sm font-medium text-gray-600",children:"Loading..."})]})}),ErrorState=()=>jsxRuntime.jsx("div",{className:"wysdym-widget-container fixed bottom-4 right-4 z-50",children:jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center shadow-lg bg-red-500",children:jsxRuntime.jsx("svg",{className:"w-6 h-6 text-white",fill:"currentColor",viewBox:"0 0 20 20",children:jsxRuntime.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})})})}),ICON_MAP={Phone,ArrowRight,ArrowLeft,ArrowUp,ArrowDown,Mail,Send,MessageSquare,MessageCircle,Calendar,ExternalLink,Play,Pause,SkipBack,SkipForward,Mic,Video,Settings,HelpCircle:CircleQuestionMark,Star,Heart,CheckCircle:CircleCheckBig,XCircle:CircleX,AlertCircle:CircleAlert,Info,Search,ShoppingCart,Headphones,User,Users,FileText,Image:Image$1,Music,Home:House,ThumbsUp,ThumbsDown,Check,X,Plus,Minus,ChevronRight,ChevronLeft,ChevronUp,ChevronDown,Menu,MoreHorizontal:Ellipsis,MoreVertical:EllipsisVertical,Edit:SquarePen,Trash2,Copy,Download,Upload,Link,Lock,Unlock:LockOpen,Eye,EyeOff,Clock,MapPin,PhoneCall,Volume,Volume2,VolumeX,Wifi,Bluetooth,Battery,Zap,Sun,Moon,Cloud,Wind,Leaf};function resolveIcon(T,n=Phone){if(!T||typeof T!="string")return n;const P=ICON_MAP[T];if(P)return P;const R=T.trim(),A=Object.keys(ICON_MAP).find(L=>L.toLowerCase()===R.toLowerCase());return A?ICON_MAP[A]:n}const CallControls=({isConnected:T,isEnding:n,callDuration:P,formatCallDuration:R,onEndCall:A})=>jsxRuntime.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 border-t border-gray-200 w-full",children:[jsxRuntime.jsxs("div",{className:"flex items-center space-x-2 text-sm text-gray-600",children:[jsxRuntime.jsx(Clock,{className:"w-4 h-4"}),jsxRuntime.jsx("span",{className:"font-mono",children:R(P)})]}),jsxRuntime.jsx("div",{className:"flex items-center space-x-2",children:jsxRuntime.jsx("button",{onClick:A,disabled:n,className:"p-2 rounded-full bg-red-100 text-red-700 hover:bg-red-200 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer border border-red-300",title:"End Call",children:jsxRuntime.jsx(PhoneOff,{className:"w-4 h-4"})})})]}),CustomCTA=({primaryColor:T,buttonText:n,href:P,onClick:R})=>{const[A,L]=React.useState(!1),O=A?`${T}dd`:T,N=V=>{R?R():window.open(P,"_blank","noopener,noreferrer")};return jsxRuntime.jsx("div",{className:"bg-gray-50 p-4",children:jsxRuntime.jsxs("button",{onClick:N,className:"w-full flex items-center justify-center space-x-2 px-4 py-3 rounded-xl text-sm font-medium transition-all duration-200 cursor-pointer",style:{backgroundColor:O,boxShadow:`0 4px 14px 0 ${T}40`,border:"none",color:"white"},onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),children:[jsxRuntime.jsx("span",{children:n}),jsxRuntime.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})},FloatingWidgetButton=({primaryColor:T,secondaryColor:n,triggerText:P,buttonText:R,buttonIcon:A,onExpand:L,hasActiveSession:O=!1,audioData:N=[],isAgentSpeaking:V=!1,customCta:j=null,onCtaClick:B,isConnected:z=!1,callDuration:W=0,onEndCall:q,mode:H="floating"})=>{const $=resolveIcon(A),[Q,U]=React.useState(!1),J=Q?`${T}dd`:T,G=React.useMemo(()=>{if(!V||N.length===0)return 1;const K=N.slice(-5),Y=K[K.length-1]||0;let Z;if(Y<1.5?Z=1:Y<3?Z=1.04:Y<5?Z=1.06:Y<7?Z=1.12:Y<9?Z=1.18:Z=1.24,K.length>1&&Math.abs(Y-(K[K.length-2]||Y))>1){const se=(Math.random()-.5)*.03;Z=Math.max(.98,Math.min(1.3,Z+se))}return Z},[N,V]);return H==="inline"?jsxRuntime.jsx("div",{className:"w-full h-full",children:jsxRuntime.jsxs("div",{className:"bg-white rounded-xl shadow-lg border border-gray-200 w-80 max-w-[calc(100vw-2rem)] overflow-hidden transition-all duration-[3000ms] ease-in-out",children:[jsxRuntime.jsxs("div",{className:"p-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center space-x-3 mb-3",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center bg-transparent p-2",style:{overflow:"visible"},children:jsxRuntime.jsx("div",{style:{width:"120%",height:"120%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible"},children:jsxRuntime.jsx(Lottie,{animationData:newAgentVoiceAnimation,loop:!0,autoplay:!0,rendererSettings:{preserveAspectRatio:"xMidYMid meet",progressiveLoad:!0,filterSize:{width:"400%",height:"400%",x:"-150%",y:"-150%"},renderer:"svg",clearCanvas:!0,context:null,scaleMode:"noScale",imagePreserveAspectRatio:"xMidYMid meet"},style:{width:"100%",height:"100%",background:"transparent",overflow:"visible",transform:`scale(${G}) translateZ(0)`,transition:"transform 0.15s ease-out",WebkitTransform:`scale(${G}) translateZ(0)`,willChange:"transform",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden"}})})}),jsxRuntime.jsx("div",{className:"flex-1",children:jsxRuntime.jsx("div",{className:"text-gray-900 font-medium",children:P})})]}),j&&j.is_active&&jsxRuntime.jsx("div",{className:`border-t border-gray-100 transition-all duration-[3000ms] ease-in-out overflow-hidden ${O?"h-auto opacity-100 translate-y-0":"h-0 opacity-0 -translate-y-2 pointer-events-none border-t-0"}`,children:jsxRuntime.jsx(CustomCTA,{primaryColor:T,buttonText:j.button_text,href:j.href,onClick:()=>B?.(j)})}),!O&&jsxRuntime.jsxs("button",{onClick:L,className:"w-full py-2 px-4 rounded-lg font-medium transition-all duration-200 flex items-center justify-center space-x-2",style:{backgroundColor:J,boxShadow:`0 4px 14px 0 ${T}40`,border:"none",cursor:"pointer"},onMouseEnter:()=>U(!0),onMouseLeave:()=>U(!1),children:[jsxRuntime.jsx($,{className:"w-5 h-5 text-white"}),jsxRuntime.jsx("span",{className:"font-medium text-white",children:R})]})]}),jsxRuntime.jsx("div",{className:`transition-all duration-[3000ms] ease-in-out overflow-hidden ${O&&q?"h-16 opacity-100":"h-0 opacity-0"}`,children:jsxRuntime.jsx(CallControls,{isConnected:z,isEnding:!1,callDuration:W,formatCallDuration:K=>`${Math.floor(K/60)}:${(K%60).toString().padStart(2,"0")}`,onEndCall:q||(()=>{}),primaryColor:T,secondaryColor:n})})]})}):jsxRuntime.jsx("div",{className:"w-full h-full",children:jsxRuntime.jsxs("div",{className:"bg-white rounded-xl shadow-lg border border-gray-200 p-4 w-80 max-w-[calc(100vw-2rem)]",children:[jsxRuntime.jsxs("div",{className:"flex items-center space-x-3 mb-3",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center bg-transparent p-2",style:{overflow:"visible"},children:jsxRuntime.jsx("div",{style:{width:"120%",height:"120%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible"},children:jsxRuntime.jsx(Lottie,{animationData:newAgentVoiceAnimation,loop:!0,autoplay:!0,rendererSettings:{preserveAspectRatio:"xMidYMid meet",progressiveLoad:!0,filterSize:{width:"400%",height:"400%",x:"-150%",y:"-150%"},renderer:"svg",clearCanvas:!0,context:null,scaleMode:"noScale",imagePreserveAspectRatio:"xMidYMid meet"},style:{width:"100%",height:"100%",background:"transparent",overflow:"visible",transform:`scale(${G}) translateZ(0)`,transition:"transform 0.15s ease-out",WebkitTransform:`scale(${G}) translateZ(0)`,willChange:"transform",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden"}})})}),jsxRuntime.jsx("div",{className:"flex-1",children:jsxRuntime.jsx("div",{className:"text-gray-900 font-medium",children:P})})]}),jsxRuntime.jsxs("button",{onClick:L,className:"w-full py-2 px-4 rounded-lg font-medium transition-all duration-200 flex items-center justify-center space-x-2",style:{backgroundColor:J,boxShadow:`0 4px 14px 0 ${T}40`,border:"none",cursor:"pointer"},onMouseEnter:()=>U(!0),onMouseLeave:()=>U(!1),children:[jsxRuntime.jsx($,{className:"w-5 h-5 text-white"}),jsxRuntime.jsx("span",{className:"font-medium text-white",children:R})]}),O&&j&&j.is_active&&jsxRuntime.jsx("div",{className:"mt-3 border-t border-gray-100",children:jsxRuntime.jsx(CustomCTA,{primaryColor:T,buttonText:j.button_text,href:j.href,onClick:()=>B?.(j)})})]})})},SessionResumePrompt=({primaryColor:T,messageCount:n=0,lastMessage:P,onResume:R,onStartNew:A,isLoading:L=!1})=>{const O=React.useRef(null),[N,V]=React.useState(null),[j,B]=React.useState(null);React.useEffect(()=>{const H=setTimeout(()=>{O.current&&O.current.focus()},100);return()=>clearTimeout(H)},[]);const z=async()=>{V("resume"),B(null);try{await R()||(B("Failed to resume session. Please try starting a new conversation."),V(null))}catch(H){console.error("[SessionResumePrompt] Error resuming session:",H),B("Failed to resume session. Please try starting a new conversation."),V(null)}},W=async()=>{V("new"),B(null);try{await A()}catch(H){console.error("[SessionResumePrompt] Error starting new session:",H),B("Failed to start new session. Please try again."),V(null)}},q=P&&P.length>50?`${P.substring(0,50)}...`:P;return jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center py-8 px-6",role:"dialog","aria-labelledby":"resume-prompt-title","aria-describedby":"resume-prompt-description",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 mb-4 rounded-full flex items-center justify-center",style:{backgroundColor:`${T}15`},"aria-hidden":"true",children:jsxRuntime.jsx(RotateCcw,{className:"w-8 h-8",style:{color:T}})}),jsxRuntime.jsx("h3",{id:"resume-prompt-title",className:"text-lg font-semibold text-gray-900 mb-2 text-center",children:"Welcome back!"}),jsxRuntime.jsxs("div",{id:"resume-prompt-description",className:"text-center mb-6 space-y-2",children:[jsxRuntime.jsxs("p",{className:"text-sm text-gray-600",children:["You have a paused conversation",n>0&&jsxRuntime.jsxs("span",{className:"font-medium text-gray-700",children:[" ","with ",n," message",n!==1?"s":""]}),"."]}),q&&jsxRuntime.jsxs("div",{className:"mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[jsxRuntime.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Last message:"}),jsxRuntime.jsxs("p",{className:"text-sm text-gray-700 italic",children:['"',q,'"']})]})]}),j&&jsxRuntime.jsx("div",{className:"w-full mb-4 p-3 bg-red-50 border border-red-200 rounded-lg",role:"alert","aria-live":"polite",children:jsxRuntime.jsxs("div",{className:"flex items-start space-x-2",children:[jsxRuntime.jsx(CircleAlert,{className:"w-4 h-4 text-red-600 flex-shrink-0 mt-0.5"}),jsxRuntime.jsx("p",{className:"text-sm text-red-700",children:j})]})}),jsxRuntime.jsxs("div",{className:"flex flex-col w-full space-y-3",children:[jsxRuntime.jsx("button",{ref:O,onClick:z,disabled:L||N!==null,className:`w-full py-3 px-4 rounded-xl text-white font-semibold transition-all duration-200 flex items-center justify-center space-x-2 ${L||N!==null?"bg-gray-400 cursor-not-allowed opacity-60":"hover:brightness-110 focus:outline-none focus:ring-2 focus:ring-offset-2"}`,style:L||N!==null?{}:{backgroundColor:T,"--tw-ring-color":T},"aria-label":`Resume conversation with ${n} message${n!==1?"s":""}`,"aria-busy":N==="resume",children:N==="resume"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-white",role:"status","aria-label":"Resuming session"}),jsxRuntime.jsx("span",{children:"Resuming..."})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(CirclePlay,{className:"w-5 h-5","aria-hidden":"true"}),jsxRuntime.jsx("span",{children:"Resume Conversation"})]})}),jsxRuntime.jsx("button",{onClick:W,disabled:L||N!==null,className:`w-full py-3 px-4 rounded-xl font-semibold transition-all duration-200 flex items-center justify-center space-x-2 border-2 ${L||N!==null?"bg-gray-100 border-gray-300 text-gray-400 cursor-not-allowed opacity-60":"bg-white border-gray-300 text-gray-700 hover:bg-gray-50 hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-400"}`,"aria-label":"Start a new conversation","aria-busy":N==="new",children:N==="new"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-gray-700",role:"status","aria-label":"Starting new session"}),jsxRuntime.jsx("span",{children:"Starting New..."})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Plus,{className:"w-5 h-5","aria-hidden":"true"}),jsxRuntime.jsx("span",{children:"Start New Conversation"})]})})]}),jsxRuntime.jsx("p",{className:"mt-4 text-xs text-gray-500 text-center",children:"Choose to continue where you left off or start fresh"})]})},PHONE_ICON=jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v0z"})}),REFRESH_ICON=jsxRuntime.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("polyline",{points:"23 4 23 10 17 10"}),jsxRuntime.jsx("polyline",{points:"1 20 1 14 7 14"}),jsxRuntime.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]});function getMessage(T){switch(T){case"form_active":return{title:"Voice paused",subtitle:"Complete the form or tap to resume"};case"timeout":return{title:"Connection timed out",subtitle:"Tap below to reconnect and continue"};case"error":return{title:"Connection lost",subtitle:"Something went wrong — tap to try again"};default:return{title:"Voice paused",subtitle:"Tap to resume the conversation"}}}function VoiceReconnectionPrompt({onReconnect:T,isReconnecting:n,primaryColor:P="#BA6296",reason:R="form_active"}){const{title:A,subtitle:L}=getMessage(R),O=R==="timeout"||R==="error";return jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",padding:"32px 24px",gap:"16px"},children:[jsxRuntime.jsx("div",{style:{position:"relative"},children:jsxRuntime.jsx("div",{style:{width:"56px",height:"56px",borderRadius:"50%",background:`${P}15`,display:"flex",alignItems:"center",justifyContent:"center",color:P},children:O?REFRESH_ICON:PHONE_ICON})}),jsxRuntime.jsxs("div",{style:{textAlign:"center"},children:[jsxRuntime.jsx("div",{style:{fontSize:"16px",fontWeight:600,color:"#1a1a1a",marginBottom:"4px"},children:A}),jsxRuntime.jsx("div",{style:{fontSize:"13px",color:"#6b7280",maxWidth:"240px"},children:L})]}),jsxRuntime.jsxs("button",{onClick:T,disabled:n,style:{display:"inline-flex",alignItems:"center",gap:"8px",padding:"10px 24px",borderRadius:"50px",border:"none",background:P,color:"#fff",fontSize:"14px",fontWeight:500,cursor:n?"wait":"pointer",opacity:n?.6:1,transition:"opacity 0.15s ease"},children:[jsxRuntime.jsx("span",{style:{display:"flex",animation:n?"spin 1s linear infinite":"none"},children:O?REFRESH_ICON:PHONE_ICON}),n?"Reconnecting...":"Resume Voice"]}),R==="form_active"&&jsxRuntime.jsx("div",{style:{fontSize:"11px",color:"#9ca3af",textAlign:"center"},children:"Voice resumes automatically after form submission"})]})}const __vite_import_meta_env__={},STAGING_API_URL=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs.js",document.baseURI).href}<"u"&&__vite_import_meta_env__?.VITE_STAGING_API_BASE_URL||"https://sales-demo-agent-staging-984571195996.us-central1.run.app",PRODUCTION_API_URL=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs.js",document.baseURI).href}<"u"&&__vite_import_meta_env__?.VITE_PROD_API_BASE_URL||"https://api.wysdym.ai";function getBackendUrl(){if(typeof window<"u"&&window.__WYSDYM_BACKEND_URL__)return window.__WYSDYM_BACKEND_URL__;if(typeof window<"u"){const T=window.location.hostname;if(T==="localhost"||T==="127.0.0.1")return"http://localhost:8000";const n=T.toLowerCase();if(n.includes("staging")||n.includes("wysdym-widget-cdn-staging")||n.includes("sales-demo-ui-staging")||n.includes("sales-demo-agent-staging")||n.includes("984571195996"))return STAGING_API_URL}return PRODUCTION_API_URL}const getCurrentBackendUrl=()=>getBackendUrl(),getCurrentApiUrl=()=>getBackendUrl(),buildApiUrl=T=>{const n=T.startsWith("/")?T.slice(1):T;return`${getBackendUrl()}/${n}`};var define_process_default={},define_process_env_default={};function _mergeNamespaces$1(T,n){return n.forEach(function(P){P&&typeof P!="string"&&!Array.isArray(P)&&Object.keys(P).forEach(function(R){if(R!=="default"&&!(R in T)){var A=Object.getOwnPropertyDescriptor(P,R);Object.defineProperty(T,R,A.get?A:{enumerable:!0,get:function(){return P[R]}})}})}),Object.freeze(T)}var e=Object.defineProperty,h$1=(T,n,P)=>n in T?e(T,n,{enumerable:!0,configurable:!0,writable:!0,value:P}):T[n]=P,o$1=(T,n,P)=>h$1(T,typeof n!="symbol"?n+"":n,P);let _$1=class{constructor(){o$1(this,"_locking"),o$1(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let n;const P=new Promise(A=>n=()=>{this._locks-=1,A()}),R=this._locking.then(()=>n);return this._locking=this._locking.then(()=>P),R}};function assert(T,n){if(!T)throw new Error(n)}const FLOAT32_MAX=34028234663852886e22,FLOAT32_MIN=-34028234663852886e22,UINT32_MAX=4294967295,INT32_MAX=2147483647,INT32_MIN=-2147483648;function assertInt32(T){if(typeof T!="number")throw new Error("invalid int 32: "+typeof T);if(!Number.isInteger(T)||T>INT32_MAX||T<INT32_MIN)throw new Error("invalid int 32: "+T)}function assertUInt32(T){if(typeof T!="number")throw new Error("invalid uint 32: "+typeof T);if(!Number.isInteger(T)||T>UINT32_MAX||T<0)throw new Error("invalid uint 32: "+T)}function assertFloat32(T){if(typeof T!="number")throw new Error("invalid float 32: "+typeof T);if(Number.isFinite(T)&&(T>FLOAT32_MAX||T<FLOAT32_MIN))throw new Error("invalid float 32: "+T)}const enumTypeSymbol=Symbol("@bufbuild/protobuf/enum-type");function getEnumType(T){const n=T[enumTypeSymbol];return assert(n,"missing enum type on enum object"),n}function setEnumType(T,n,P,R){T[enumTypeSymbol]=makeEnumType(n,P.map(A=>({no:A.no,name:A.name,localName:T[A.no]})))}function makeEnumType(T,n,P){const R=Object.create(null),A=Object.create(null),L=[];for(const O of n){const N=normalizeEnumValue(O);L.push(N),R[O.name]=N,A[O.no]=N}return{typeName:T,values:L,findName(O){return R[O]},findNumber(O){return A[O]}}}function makeEnum(T,n,P){const R={};for(const A of n){const L=normalizeEnumValue(A);R[L.localName]=L.no,R[L.no]=L.localName}return setEnumType(R,T,n),R}function normalizeEnumValue(T){return"localName"in T?T:Object.assign(Object.assign({},T),{localName:T.name})}class Message{equals(n){return this.getType().runtime.util.equals(this.getType(),this,n)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(n,P){const R=this.getType(),A=R.runtime.bin,L=A.makeReadOptions(P);return A.readMessage(this,L.readerFactory(n),n.byteLength,L),this}fromJson(n,P){const R=this.getType(),A=R.runtime.json,L=A.makeReadOptions(P);return A.readMessage(R,n,L,this),this}fromJsonString(n,P){let R;try{R=JSON.parse(n)}catch(A){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(A instanceof Error?A.message:String(A)))}return this.fromJson(R,P)}toBinary(n){const P=this.getType(),R=P.runtime.bin,A=R.makeWriteOptions(n),L=A.writerFactory();return R.writeMessage(this,L,A),L.finish()}toJson(n){const P=this.getType(),R=P.runtime.json,A=R.makeWriteOptions(n);return R.writeMessage(this,A)}toJsonString(n){var P;const R=this.toJson(n);return JSON.stringify(R,null,(P=n?.prettySpaces)!==null&&P!==void 0?P:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function makeMessageType(T,n,P,R){var A;const L=(A=R?.localName)!==null&&A!==void 0?A:n.substring(n.lastIndexOf(".")+1),O={[L]:function(N){T.util.initFields(this),T.util.initPartial(N,this)}}[L];return Object.setPrototypeOf(O.prototype,new Message),Object.assign(O,{runtime:T,typeName:n,fields:T.util.newFieldList(P),fromBinary(N,V){return new O().fromBinary(N,V)},fromJson(N,V){return new O().fromJson(N,V)},fromJsonString(N,V){return new O().fromJsonString(N,V)},equals(N,V){return T.util.equals(O,N,V)}}),O}function varint64read(){let T=0,n=0;for(let R=0;R<28;R+=7){let A=this.buf[this.pos++];if(T|=(A&127)<<R,(A&128)==0)return this.assertBounds(),[T,n]}let P=this.buf[this.pos++];if(T|=(P&15)<<28,n=(P&112)>>4,(P&128)==0)return this.assertBounds(),[T,n];for(let R=3;R<=31;R+=7){let A=this.buf[this.pos++];if(n|=(A&127)<<R,(A&128)==0)return this.assertBounds(),[T,n]}throw new Error("invalid varint")}function varint64write(T,n,P){for(let L=0;L<28;L=L+7){const O=T>>>L,N=!(!(O>>>7)&&n==0),V=(N?O|128:O)&255;if(P.push(V),!N)return}const R=T>>>28&15|(n&7)<<4,A=n>>3!=0;if(P.push((A?R|128:R)&255),!!A){for(let L=3;L<31;L=L+7){const O=n>>>L,N=!!(O>>>7),V=(N?O|128:O)&255;if(P.push(V),!N)return}P.push(n>>>31&1)}}const TWO_PWR_32_DBL=4294967296;function int64FromString(T){const n=T[0]==="-";n&&(T=T.slice(1));const P=1e6;let R=0,A=0;function L(O,N){const V=Number(T.slice(O,N));A*=P,R=R*P+V,R>=TWO_PWR_32_DBL&&(A=A+(R/TWO_PWR_32_DBL|0),R=R%TWO_PWR_32_DBL)}return L(-24,-18),L(-18,-12),L(-12,-6),L(-6),n?negate(R,A):newBits(R,A)}function int64ToString(T,n){let P=newBits(T,n);const R=P.hi&2147483648;R&&(P=negate(P.lo,P.hi));const A=uInt64ToString(P.lo,P.hi);return R?"-"+A:A}function uInt64ToString(T,n){if({lo:T,hi:n}=toUnsigned(T,n),n<=2097151)return String(TWO_PWR_32_DBL*n+T);const P=T&16777215,R=(T>>>24|n<<8)&16777215,A=n>>16&65535;let L=P+R*6777216+A*6710656,O=R+A*8147497,N=A*2;const V=1e7;return L>=V&&(O+=Math.floor(L/V),L%=V),O>=V&&(N+=Math.floor(O/V),O%=V),N.toString()+decimalFrom1e7WithLeadingZeros(O)+decimalFrom1e7WithLeadingZeros(L)}function toUnsigned(T,n){return{lo:T>>>0,hi:n>>>0}}function newBits(T,n){return{lo:T|0,hi:n|0}}function negate(T,n){return n=~n,T?T=~T+1:n+=1,newBits(T,n)}const decimalFrom1e7WithLeadingZeros=T=>{const n=String(T);return"0000000".slice(n.length)+n};function varint32write(T,n){if(T>=0){for(;T>127;)n.push(T&127|128),T=T>>>7;n.push(T)}else{for(let P=0;P<9;P++)n.push(T&127|128),T=T>>7;n.push(1)}}function varint32read(){let T=this.buf[this.pos++],n=T&127;if((T&128)==0)return this.assertBounds(),n;if(T=this.buf[this.pos++],n|=(T&127)<<7,(T&128)==0)return this.assertBounds(),n;if(T=this.buf[this.pos++],n|=(T&127)<<14,(T&128)==0)return this.assertBounds(),n;if(T=this.buf[this.pos++],n|=(T&127)<<21,(T&128)==0)return this.assertBounds(),n;T=this.buf[this.pos++],n|=(T&15)<<28;for(let P=5;(T&128)!==0&&P<10;P++)T=this.buf[this.pos++];if((T&128)!=0)throw new Error("invalid varint");return this.assertBounds(),n>>>0}function makeInt64Support(){const T=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof T.getBigInt64=="function"&&typeof T.getBigUint64=="function"&&typeof T.setBigInt64=="function"&&typeof T.setBigUint64=="function"&&(typeof define_process_default!="object"||typeof define_process_env_default!="object"||define_process_env_default.BUF_BIGINT_DISABLE!=="1")){const A=BigInt("-9223372036854775808"),L=BigInt("9223372036854775807"),O=BigInt("0"),N=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(V){const j=typeof V=="bigint"?V:BigInt(V);if(j>L||j<A)throw new Error("int64 invalid: ".concat(V));return j},uParse(V){const j=typeof V=="bigint"?V:BigInt(V);if(j>N||j<O)throw new Error("uint64 invalid: ".concat(V));return j},enc(V){return T.setBigInt64(0,this.parse(V),!0),{lo:T.getInt32(0,!0),hi:T.getInt32(4,!0)}},uEnc(V){return T.setBigInt64(0,this.uParse(V),!0),{lo:T.getInt32(0,!0),hi:T.getInt32(4,!0)}},dec(V,j){return T.setInt32(0,V,!0),T.setInt32(4,j,!0),T.getBigInt64(0,!0)},uDec(V,j){return T.setInt32(0,V,!0),T.setInt32(4,j,!0),T.getBigUint64(0,!0)}}}const P=A=>assert(/^-?[0-9]+$/.test(A),"int64 invalid: ".concat(A)),R=A=>assert(/^[0-9]+$/.test(A),"uint64 invalid: ".concat(A));return{zero:"0",supported:!1,parse(A){return typeof A!="string"&&(A=A.toString()),P(A),A},uParse(A){return typeof A!="string"&&(A=A.toString()),R(A),A},enc(A){return typeof A!="string"&&(A=A.toString()),P(A),int64FromString(A)},uEnc(A){return typeof A!="string"&&(A=A.toString()),R(A),int64FromString(A)},dec(A,L){return int64ToString(A,L)},uDec(A,L){return uInt64ToString(A,L)}}}const protoInt64=makeInt64Support();var ScalarType;(function(T){T[T.DOUBLE=1]="DOUBLE",T[T.FLOAT=2]="FLOAT",T[T.INT64=3]="INT64",T[T.UINT64=4]="UINT64",T[T.INT32=5]="INT32",T[T.FIXED64=6]="FIXED64",T[T.FIXED32=7]="FIXED32",T[T.BOOL=8]="BOOL",T[T.STRING=9]="STRING",T[T.BYTES=12]="BYTES",T[T.UINT32=13]="UINT32",T[T.SFIXED32=15]="SFIXED32",T[T.SFIXED64=16]="SFIXED64",T[T.SINT32=17]="SINT32",T[T.SINT64=18]="SINT64"})(ScalarType||(ScalarType={}));var LongType;(function(T){T[T.BIGINT=0]="BIGINT",T[T.STRING=1]="STRING"})(LongType||(LongType={}));function scalarEquals(T,n,P){if(n===P)return!0;if(T==ScalarType.BYTES){if(!(n instanceof Uint8Array)||!(P instanceof Uint8Array)||n.length!==P.length)return!1;for(let R=0;R<n.length;R++)if(n[R]!==P[R])return!1;return!0}switch(T){case ScalarType.UINT64:case ScalarType.FIXED64:case ScalarType.INT64:case ScalarType.SFIXED64:case ScalarType.SINT64:return n==P}return!1}function scalarZeroValue(T,n){switch(T){case ScalarType.BOOL:return!1;case ScalarType.UINT64:case ScalarType.FIXED64:case ScalarType.INT64:case ScalarType.SFIXED64:case ScalarType.SINT64:return n==0?protoInt64.zero:"0";case ScalarType.DOUBLE:case ScalarType.FLOAT:return 0;case ScalarType.BYTES:return new Uint8Array(0);case ScalarType.STRING:return"";default:return 0}}function isScalarZeroValue(T,n){switch(T){case ScalarType.BOOL:return n===!1;case ScalarType.STRING:return n==="";case ScalarType.BYTES:return n instanceof Uint8Array&&!n.byteLength;default:return n==0}}var WireType;(function(T){T[T.Varint=0]="Varint",T[T.Bit64=1]="Bit64",T[T.LengthDelimited=2]="LengthDelimited",T[T.StartGroup=3]="StartGroup",T[T.EndGroup=4]="EndGroup",T[T.Bit32=5]="Bit32"})(WireType||(WireType={}));class BinaryWriter{constructor(n){this.stack=[],this.textEncoder=n??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let n=0;for(let A=0;A<this.chunks.length;A++)n+=this.chunks[A].length;let P=new Uint8Array(n),R=0;for(let A=0;A<this.chunks.length;A++)P.set(this.chunks[A],R),R+=this.chunks[A].length;return this.chunks=[],P}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let n=this.finish(),P=this.stack.pop();if(!P)throw new Error("invalid state, fork stack empty");return this.chunks=P.chunks,this.buf=P.buf,this.uint32(n.byteLength),this.raw(n)}tag(n,P){return this.uint32((n<<3|P)>>>0)}raw(n){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(n),this}uint32(n){for(assertUInt32(n);n>127;)this.buf.push(n&127|128),n=n>>>7;return this.buf.push(n),this}int32(n){return assertInt32(n),varint32write(n,this.buf),this}bool(n){return this.buf.push(n?1:0),this}bytes(n){return this.uint32(n.byteLength),this.raw(n)}string(n){let P=this.textEncoder.encode(n);return this.uint32(P.byteLength),this.raw(P)}float(n){assertFloat32(n);let P=new Uint8Array(4);return new DataView(P.buffer).setFloat32(0,n,!0),this.raw(P)}double(n){let P=new Uint8Array(8);return new DataView(P.buffer).setFloat64(0,n,!0),this.raw(P)}fixed32(n){assertUInt32(n);let P=new Uint8Array(4);return new DataView(P.buffer).setUint32(0,n,!0),this.raw(P)}sfixed32(n){assertInt32(n);let P=new Uint8Array(4);return new DataView(P.buffer).setInt32(0,n,!0),this.raw(P)}sint32(n){return assertInt32(n),n=(n<<1^n>>31)>>>0,varint32write(n,this.buf),this}sfixed64(n){let P=new Uint8Array(8),R=new DataView(P.buffer),A=protoInt64.enc(n);return R.setInt32(0,A.lo,!0),R.setInt32(4,A.hi,!0),this.raw(P)}fixed64(n){let P=new Uint8Array(8),R=new DataView(P.buffer),A=protoInt64.uEnc(n);return R.setInt32(0,A.lo,!0),R.setInt32(4,A.hi,!0),this.raw(P)}int64(n){let P=protoInt64.enc(n);return varint64write(P.lo,P.hi,this.buf),this}sint64(n){let P=protoInt64.enc(n),R=P.hi>>31,A=P.lo<<1^R,L=(P.hi<<1|P.lo>>>31)^R;return varint64write(A,L,this.buf),this}uint64(n){let P=protoInt64.uEnc(n);return varint64write(P.lo,P.hi,this.buf),this}}class BinaryReader{constructor(n,P){this.varint64=varint64read,this.uint32=varint32read,this.buf=n,this.len=n.length,this.pos=0,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.textDecoder=P??new TextDecoder}tag(){let n=this.uint32(),P=n>>>3,R=n&7;if(P<=0||R<0||R>5)throw new Error("illegal tag: field no "+P+" wire type "+R);return[P,R]}skip(n,P){let R=this.pos;switch(n){case WireType.Varint:for(;this.buf[this.pos++]&128;);break;case WireType.Bit64:this.pos+=4;case WireType.Bit32:this.pos+=4;break;case WireType.LengthDelimited:let A=this.uint32();this.pos+=A;break;case WireType.StartGroup:for(;;){const[L,O]=this.tag();if(O===WireType.EndGroup){if(P!==void 0&&L!==P)throw new Error("invalid end group tag");break}this.skip(O,L)}break;default:throw new Error("cant skip wire type "+n)}return this.assertBounds(),this.buf.subarray(R,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let n=this.uint32();return n>>>1^-(n&1)}int64(){return protoInt64.dec(...this.varint64())}uint64(){return protoInt64.uDec(...this.varint64())}sint64(){let[n,P]=this.varint64(),R=-(n&1);return n=(n>>>1|(P&1)<<31)^R,P=P>>>1^R,protoInt64.dec(n,P)}bool(){let[n,P]=this.varint64();return n!==0||P!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return protoInt64.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return protoInt64.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let n=this.uint32(),P=this.pos;return this.pos+=n,this.assertBounds(),this.buf.subarray(P,P+n)}string(){return this.textDecoder.decode(this.bytes())}}function makeExtension(T,n,P,R){let A;return{typeName:n,extendee:P,get field(){if(!A){const L=typeof R=="function"?R():R;L.name=n.split(".").pop(),L.jsonName="[".concat(n,"]"),A=T.util.newFieldList([L]).list()[0]}return A},runtime:T}}function createExtensionContainer(T){const n=T.field.localName,P=Object.create(null);return P[n]=initExtensionField(T),[P,()=>P[n]]}function initExtensionField(T){const n=T.field;if(n.repeated)return[];if(n.default!==void 0)return n.default;switch(n.kind){case"enum":return n.T.values[0].no;case"scalar":return scalarZeroValue(n.T,n.L);case"message":const P=n.T,R=new P;return P.fieldWrapper?P.fieldWrapper.unwrapField(R):R;case"map":throw"map fields are not allowed to be extensions"}}function filterUnknownFields(T,n){if(!n.repeated&&(n.kind=="enum"||n.kind=="scalar")){for(let P=T.length-1;P>=0;--P)if(T[P].no==n.no)return[T[P]];return[]}return T.filter(P=>P.no===n.no)}let encTable="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),decTable=[];for(let T=0;T<encTable.length;T++)decTable[encTable[T].charCodeAt(0)]=T;decTable[45]=encTable.indexOf("+");decTable[95]=encTable.indexOf("/");const protoBase64={dec(T){let n=T.length*3/4;T[T.length-2]=="="?n-=2:T[T.length-1]=="="&&(n-=1);let P=new Uint8Array(n),R=0,A=0,L,O=0;for(let N=0;N<T.length;N++){if(L=decTable[T.charCodeAt(N)],L===void 0)switch(T[N]){case"=":A=0;case`
|
|
493
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(A){case 0:O=L,A=1;break;case 1:P[R++]=O<<2|(L&48)>>4,O=L,A=2;break;case 2:P[R++]=(O&15)<<4|(L&60)>>2,O=L,A=3;break;case 3:P[R++]=(O&3)<<6|L,A=0;break}}if(A==1)throw Error("invalid base64 string.");return P.subarray(0,R)},enc(T){let n="",P=0,R,A=0;for(let L=0;L<T.length;L++)switch(R=T[L],P){case 0:n+=encTable[R>>2],A=(R&3)<<4,P=1;break;case 1:n+=encTable[A|R>>4],A=(R&15)<<2,P=2;break;case 2:n+=encTable[A|R>>6],n+=encTable[R&63],P=0;break}return P&&(n+=encTable[A],n+="=",P==1&&(n+="=")),n}};function getExtension(T,n,P){assertExtendee(n,T);const R=n.runtime.bin.makeReadOptions(P),A=filterUnknownFields(T.getType().runtime.bin.listUnknownFields(T),n.field),[L,O]=createExtensionContainer(n);for(const N of A)n.runtime.bin.readField(L,R.readerFactory(N.data),n.field,N.wireType,R);return O()}function setExtension(T,n,P,R){assertExtendee(n,T);const A=n.runtime.bin.makeReadOptions(R),L=n.runtime.bin.makeWriteOptions(R);if(hasExtension(T,n)){const j=T.getType().runtime.bin.listUnknownFields(T).filter(B=>B.no!=n.field.no);T.getType().runtime.bin.discardUnknownFields(T);for(const B of j)T.getType().runtime.bin.onUnknownField(T,B.no,B.wireType,B.data)}const O=L.writerFactory();let N=n.field;!N.opt&&!N.repeated&&(N.kind=="enum"||N.kind=="scalar")&&(N=Object.assign(Object.assign({},n.field),{opt:!0})),n.runtime.bin.writeField(N,P,O,L);const V=A.readerFactory(O.finish());for(;V.pos<V.len;){const[j,B]=V.tag(),z=V.skip(B,j);T.getType().runtime.bin.onUnknownField(T,j,B,z)}}function hasExtension(T,n){const P=T.getType();return n.extendee.typeName===P.typeName&&!!P.runtime.bin.listUnknownFields(T).find(R=>R.no==n.field.no)}function assertExtendee(T,n){assert(T.extendee.typeName==n.getType().typeName,"extension ".concat(T.typeName," can only be applied to message ").concat(T.extendee.typeName))}function isFieldSet(T,n){const P=T.localName;if(T.repeated)return n[P].length>0;if(T.oneof)return n[T.oneof.localName].case===P;switch(T.kind){case"enum":case"scalar":return T.opt||T.req?n[P]!==void 0:T.kind=="enum"?n[P]!==T.T.values[0].no:!isScalarZeroValue(T.T,n[P]);case"message":return n[P]!==void 0;case"map":return Object.keys(n[P]).length>0}}function clearField(T,n){const P=T.localName,R=!T.opt&&!T.req;if(T.repeated)n[P]=[];else if(T.oneof)n[T.oneof.localName]={case:void 0};else switch(T.kind){case"map":n[P]={};break;case"enum":n[P]=R?T.T.values[0].no:void 0;break;case"scalar":n[P]=R?scalarZeroValue(T.T,T.L):void 0;break;case"message":n[P]=void 0;break}}function isMessage(T,n){if(T===null||typeof T!="object"||!Object.getOwnPropertyNames(Message.prototype).every(R=>R in T&&typeof T[R]=="function"))return!1;const P=T.getType();return P===null||typeof P!="function"||!("typeName"in P)||typeof P.typeName!="string"?!1:n===void 0?!0:P.typeName==n.typeName}function wrapField(T,n){return isMessage(n)||!T.fieldWrapper?n:T.fieldWrapper.wrapField(n)}ScalarType.DOUBLE,ScalarType.FLOAT,ScalarType.INT64,ScalarType.UINT64,ScalarType.INT32,ScalarType.UINT32,ScalarType.BOOL,ScalarType.STRING,ScalarType.BYTES;const jsonReadDefaults={ignoreUnknownFields:!1},jsonWriteDefaults={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function makeReadOptions$1(T){return T?Object.assign(Object.assign({},jsonReadDefaults),T):jsonReadDefaults}function makeWriteOptions$1(T){return T?Object.assign(Object.assign({},jsonWriteDefaults),T):jsonWriteDefaults}const tokenNull=Symbol(),tokenIgnoredUnknownEnum=Symbol();function makeJsonFormat(){return{makeReadOptions:makeReadOptions$1,makeWriteOptions:makeWriteOptions$1,readMessage(T,n,P,R){if(n==null||Array.isArray(n)||typeof n!="object")throw new Error("cannot decode message ".concat(T.typeName," from JSON: ").concat(debugJsonValue(n)));R=R??new T;const A=new Map,L=P.typeRegistry;for(const[O,N]of Object.entries(n)){const V=T.fields.findJsonName(O);if(V){if(V.oneof){if(N===null&&V.kind=="scalar")continue;const j=A.get(V.oneof);if(j!==void 0)throw new Error("cannot decode message ".concat(T.typeName,' from JSON: multiple keys for oneof "').concat(V.oneof.name,'" present: "').concat(j,'", "').concat(O,'"'));A.set(V.oneof,O)}readField$1(R,N,V,P,T)}else{let j=!1;if(L?.findExtension&&O.startsWith("[")&&O.endsWith("]")){const B=L.findExtension(O.substring(1,O.length-1));if(B&&B.extendee.typeName==T.typeName){j=!0;const[z,W]=createExtensionContainer(B);readField$1(z,N,B.field,P,B),setExtension(R,B,W(),P)}}if(!j&&!P.ignoreUnknownFields)throw new Error("cannot decode message ".concat(T.typeName,' from JSON: key "').concat(O,'" is unknown'))}}return R},writeMessage(T,n){const P=T.getType(),R={};let A;try{for(A of P.fields.byNumber()){if(!isFieldSet(A,T)){if(A.req)throw"required field not set";if(!n.emitDefaultValues||!canEmitFieldDefaultValue(A))continue}const O=A.oneof?T[A.oneof.localName].value:T[A.localName],N=writeField$1(A,O,n);N!==void 0&&(R[n.useProtoFieldName?A.name:A.jsonName]=N)}const L=n.typeRegistry;if(L?.findExtensionFor)for(const O of P.runtime.bin.listUnknownFields(T)){const N=L.findExtensionFor(P.typeName,O.no);if(N&&hasExtension(T,N)){const V=getExtension(T,N,n),j=writeField$1(N.field,V,n);j!==void 0&&(R[N.field.jsonName]=j)}}}catch(L){const O=A?"cannot encode field ".concat(P.typeName,".").concat(A.name," to JSON"):"cannot encode message ".concat(P.typeName," to JSON"),N=L instanceof Error?L.message:String(L);throw new Error(O+(N.length>0?": ".concat(N):""))}return R},readScalar(T,n,P){return readScalar$1(T,n,P??LongType.BIGINT,!0)},writeScalar(T,n,P){if(n!==void 0&&(P||isScalarZeroValue(T,n)))return writeScalar$1(T,n)},debug:debugJsonValue}}function debugJsonValue(T){if(T===null)return"null";switch(typeof T){case"object":return Array.isArray(T)?"array":"object";case"string":return T.length>100?"string":'"'.concat(T.split('"').join('\\"'),'"');default:return String(T)}}function readField$1(T,n,P,R,A){let L=P.localName;if(P.repeated){if(assert(P.kind!="map"),n===null)return;if(!Array.isArray(n))throw new Error("cannot decode field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(n)));const O=T[L];for(const N of n){if(N===null)throw new Error("cannot decode field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(N)));switch(P.kind){case"message":O.push(P.T.fromJson(N,R));break;case"enum":const V=readEnum(P.T,N,R.ignoreUnknownFields,!0);V!==tokenIgnoredUnknownEnum&&O.push(V);break;case"scalar":try{O.push(readScalar$1(P.T,N,P.L,!0))}catch(j){let B="cannot decode field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(N));throw j instanceof Error&&j.message.length>0&&(B+=": ".concat(j.message)),new Error(B)}break}}}else if(P.kind=="map"){if(n===null)return;if(typeof n!="object"||Array.isArray(n))throw new Error("cannot decode field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(n)));const O=T[L];for(const[N,V]of Object.entries(n)){if(V===null)throw new Error("cannot decode field ".concat(A.typeName,".").concat(P.name," from JSON: map value null"));let j;try{j=readMapKey(P.K,N)}catch(B){let z="cannot decode map key for field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(n));throw B instanceof Error&&B.message.length>0&&(z+=": ".concat(B.message)),new Error(z)}switch(P.V.kind){case"message":O[j]=P.V.T.fromJson(V,R);break;case"enum":const B=readEnum(P.V.T,V,R.ignoreUnknownFields,!0);B!==tokenIgnoredUnknownEnum&&(O[j]=B);break;case"scalar":try{O[j]=readScalar$1(P.V.T,V,LongType.BIGINT,!0)}catch(z){let W="cannot decode map value for field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(n));throw z instanceof Error&&z.message.length>0&&(W+=": ".concat(z.message)),new Error(W)}break}}}else switch(P.oneof&&(T=T[P.oneof.localName]={case:L},L="value"),P.kind){case"message":const O=P.T;if(n===null&&O.typeName!="google.protobuf.Value")return;let N=T[L];isMessage(N)?N.fromJson(n,R):(T[L]=N=O.fromJson(n,R),O.fieldWrapper&&!P.oneof&&(T[L]=O.fieldWrapper.unwrapField(N)));break;case"enum":const V=readEnum(P.T,n,R.ignoreUnknownFields,!1);switch(V){case tokenNull:clearField(P,T);break;case tokenIgnoredUnknownEnum:break;default:T[L]=V;break}break;case"scalar":try{const j=readScalar$1(P.T,n,P.L,!1);switch(j){case tokenNull:clearField(P,T);break;default:T[L]=j;break}}catch(j){let B="cannot decode field ".concat(A.typeName,".").concat(P.name," from JSON: ").concat(debugJsonValue(n));throw j instanceof Error&&j.message.length>0&&(B+=": ".concat(j.message)),new Error(B)}break}}function readMapKey(T,n){if(T===ScalarType.BOOL)switch(n){case"true":n=!0;break;case"false":n=!1;break}return readScalar$1(T,n,LongType.BIGINT,!0).toString()}function readScalar$1(T,n,P,R){if(n===null)return R?scalarZeroValue(T,P):tokenNull;switch(T){case ScalarType.DOUBLE:case ScalarType.FLOAT:if(n==="NaN")return Number.NaN;if(n==="Infinity")return Number.POSITIVE_INFINITY;if(n==="-Infinity")return Number.NEGATIVE_INFINITY;if(n===""||typeof n=="string"&&n.trim().length!==n.length||typeof n!="string"&&typeof n!="number")break;const A=Number(n);if(Number.isNaN(A)||!Number.isFinite(A))break;return T==ScalarType.FLOAT&&assertFloat32(A),A;case ScalarType.INT32:case ScalarType.FIXED32:case ScalarType.SFIXED32:case ScalarType.SINT32:case ScalarType.UINT32:let L;if(typeof n=="number"?L=n:typeof n=="string"&&n.length>0&&n.trim().length===n.length&&(L=Number(n)),L===void 0)break;return T==ScalarType.UINT32||T==ScalarType.FIXED32?assertUInt32(L):assertInt32(L),L;case ScalarType.INT64:case ScalarType.SFIXED64:case ScalarType.SINT64:if(typeof n!="number"&&typeof n!="string")break;const O=protoInt64.parse(n);return P?O.toString():O;case ScalarType.FIXED64:case ScalarType.UINT64:if(typeof n!="number"&&typeof n!="string")break;const N=protoInt64.uParse(n);return P?N.toString():N;case ScalarType.BOOL:if(typeof n!="boolean")break;return n;case ScalarType.STRING:if(typeof n!="string")break;try{encodeURIComponent(n)}catch{throw new Error("invalid UTF8")}return n;case ScalarType.BYTES:if(n==="")return new Uint8Array(0);if(typeof n!="string")break;return protoBase64.dec(n)}throw new Error}function readEnum(T,n,P,R){if(n===null)return T.typeName=="google.protobuf.NullValue"?0:R?T.values[0].no:tokenNull;switch(typeof n){case"number":if(Number.isInteger(n))return n;break;case"string":const A=T.findName(n);if(A!==void 0)return A.no;if(P)return tokenIgnoredUnknownEnum;break}throw new Error("cannot decode enum ".concat(T.typeName," from JSON: ").concat(debugJsonValue(n)))}function canEmitFieldDefaultValue(T){return T.repeated||T.kind=="map"?!0:!(T.oneof||T.kind=="message"||T.opt||T.req)}function writeField$1(T,n,P){if(T.kind=="map"){assert(typeof n=="object"&&n!=null);const R={},A=Object.entries(n);switch(T.V.kind){case"scalar":for(const[O,N]of A)R[O.toString()]=writeScalar$1(T.V.T,N);break;case"message":for(const[O,N]of A)R[O.toString()]=N.toJson(P);break;case"enum":const L=T.V.T;for(const[O,N]of A)R[O.toString()]=writeEnum(L,N,P.enumAsInteger);break}return P.emitDefaultValues||A.length>0?R:void 0}if(T.repeated){assert(Array.isArray(n));const R=[];switch(T.kind){case"scalar":for(let A=0;A<n.length;A++)R.push(writeScalar$1(T.T,n[A]));break;case"enum":for(let A=0;A<n.length;A++)R.push(writeEnum(T.T,n[A],P.enumAsInteger));break;case"message":for(let A=0;A<n.length;A++)R.push(n[A].toJson(P));break}return P.emitDefaultValues||R.length>0?R:void 0}switch(T.kind){case"scalar":return writeScalar$1(T.T,n);case"enum":return writeEnum(T.T,n,P.enumAsInteger);case"message":return wrapField(T.T,n).toJson(P)}}function writeEnum(T,n,P){var R;if(assert(typeof n=="number"),T.typeName=="google.protobuf.NullValue")return null;if(P)return n;const A=T.findNumber(n);return(R=A?.name)!==null&&R!==void 0?R:n}function writeScalar$1(T,n){switch(T){case ScalarType.INT32:case ScalarType.SFIXED32:case ScalarType.SINT32:case ScalarType.FIXED32:case ScalarType.UINT32:return assert(typeof n=="number"),n;case ScalarType.FLOAT:case ScalarType.DOUBLE:return assert(typeof n=="number"),Number.isNaN(n)?"NaN":n===Number.POSITIVE_INFINITY?"Infinity":n===Number.NEGATIVE_INFINITY?"-Infinity":n;case ScalarType.STRING:return assert(typeof n=="string"),n;case ScalarType.BOOL:return assert(typeof n=="boolean"),n;case ScalarType.UINT64:case ScalarType.FIXED64:case ScalarType.INT64:case ScalarType.SFIXED64:case ScalarType.SINT64:return assert(typeof n=="bigint"||typeof n=="string"||typeof n=="number"),n.toString();case ScalarType.BYTES:return assert(n instanceof Uint8Array),protoBase64.enc(n)}}const unknownFieldsSymbol=Symbol("@bufbuild/protobuf/unknown-fields"),readDefaults={readUnknownFields:!0,readerFactory:T=>new BinaryReader(T)},writeDefaults={writeUnknownFields:!0,writerFactory:()=>new BinaryWriter};function makeReadOptions(T){return T?Object.assign(Object.assign({},readDefaults),T):readDefaults}function makeWriteOptions(T){return T?Object.assign(Object.assign({},writeDefaults),T):writeDefaults}function makeBinaryFormat(){return{makeReadOptions,makeWriteOptions,listUnknownFields(T){var n;return(n=T[unknownFieldsSymbol])!==null&&n!==void 0?n:[]},discardUnknownFields(T){delete T[unknownFieldsSymbol]},writeUnknownFields(T,n){const R=T[unknownFieldsSymbol];if(R)for(const A of R)n.tag(A.no,A.wireType).raw(A.data)},onUnknownField(T,n,P,R){const A=T;Array.isArray(A[unknownFieldsSymbol])||(A[unknownFieldsSymbol]=[]),A[unknownFieldsSymbol].push({no:n,wireType:P,data:R})},readMessage(T,n,P,R,A){const L=T.getType(),O=A?n.len:n.pos+P;let N,V;for(;n.pos<O&&([N,V]=n.tag(),!(A===!0&&V==WireType.EndGroup));){const j=L.fields.find(N);if(!j){const B=n.skip(V,N);R.readUnknownFields&&this.onUnknownField(T,N,V,B);continue}readField(T,n,j,V,R)}if(A&&(V!=WireType.EndGroup||N!==P))throw new Error("invalid end group tag")},readField,writeMessage(T,n,P){const R=T.getType();for(const A of R.fields.byNumber()){if(!isFieldSet(A,T)){if(A.req)throw new Error("cannot encode field ".concat(R.typeName,".").concat(A.name," to binary: required field not set"));continue}const L=A.oneof?T[A.oneof.localName].value:T[A.localName];writeField(A,L,n,P)}return P.writeUnknownFields&&this.writeUnknownFields(T,n),n},writeField(T,n,P,R){n!==void 0&&writeField(T,n,P,R)}}}function readField(T,n,P,R,A){let{repeated:L,localName:O}=P;switch(P.oneof&&(T=T[P.oneof.localName],T.case!=O&&delete T.value,T.case=O,O="value"),P.kind){case"scalar":case"enum":const N=P.kind=="enum"?ScalarType.INT32:P.T;let V=readScalar;if(P.kind=="scalar"&&P.L>0&&(V=readScalarLTString),L){let W=T[O];if(R==WireType.LengthDelimited&&N!=ScalarType.STRING&&N!=ScalarType.BYTES){let H=n.uint32()+n.pos;for(;n.pos<H;)W.push(V(n,N))}else W.push(V(n,N))}else T[O]=V(n,N);break;case"message":const j=P.T;L?T[O].push(readMessageField(n,new j,A,P)):isMessage(T[O])?readMessageField(n,T[O],A,P):(T[O]=readMessageField(n,new j,A,P),j.fieldWrapper&&!P.oneof&&!P.repeated&&(T[O]=j.fieldWrapper.unwrapField(T[O])));break;case"map":let[B,z]=readMapEntry(P,n,A);T[O][B]=z;break}}function readMessageField(T,n,P,R){const A=n.getType().runtime.bin,L=R?.delimited;return A.readMessage(n,T,L?R.no:T.uint32(),P,L),n}function readMapEntry(T,n,P){const R=n.uint32(),A=n.pos+R;let L,O;for(;n.pos<A;){const[N]=n.tag();switch(N){case 1:L=readScalar(n,T.K);break;case 2:switch(T.V.kind){case"scalar":O=readScalar(n,T.V.T);break;case"enum":O=n.int32();break;case"message":O=readMessageField(n,new T.V.T,P,void 0);break}break}}if(L===void 0&&(L=scalarZeroValue(T.K,LongType.BIGINT)),typeof L!="string"&&typeof L!="number"&&(L=L.toString()),O===void 0)switch(T.V.kind){case"scalar":O=scalarZeroValue(T.V.T,LongType.BIGINT);break;case"enum":O=T.V.T.values[0].no;break;case"message":O=new T.V.T;break}return[L,O]}function readScalarLTString(T,n){const P=readScalar(T,n);return typeof P=="bigint"?P.toString():P}function readScalar(T,n){switch(n){case ScalarType.STRING:return T.string();case ScalarType.BOOL:return T.bool();case ScalarType.DOUBLE:return T.double();case ScalarType.FLOAT:return T.float();case ScalarType.INT32:return T.int32();case ScalarType.INT64:return T.int64();case ScalarType.UINT64:return T.uint64();case ScalarType.FIXED64:return T.fixed64();case ScalarType.BYTES:return T.bytes();case ScalarType.FIXED32:return T.fixed32();case ScalarType.SFIXED32:return T.sfixed32();case ScalarType.SFIXED64:return T.sfixed64();case ScalarType.SINT64:return T.sint64();case ScalarType.UINT32:return T.uint32();case ScalarType.SINT32:return T.sint32()}}function writeField(T,n,P,R){assert(n!==void 0);const A=T.repeated;switch(T.kind){case"scalar":case"enum":let L=T.kind=="enum"?ScalarType.INT32:T.T;if(A)if(assert(Array.isArray(n)),T.packed)writePacked(P,L,T.no,n);else for(const O of n)writeScalar(P,L,T.no,O);else writeScalar(P,L,T.no,n);break;case"message":if(A){assert(Array.isArray(n));for(const O of n)writeMessageField(P,R,T,O)}else writeMessageField(P,R,T,n);break;case"map":assert(typeof n=="object"&&n!=null);for(const[O,N]of Object.entries(n))writeMapEntry(P,R,T,O,N);break}}function writeMapEntry(T,n,P,R,A){T.tag(P.no,WireType.LengthDelimited),T.fork();let L=R;switch(P.K){case ScalarType.INT32:case ScalarType.FIXED32:case ScalarType.UINT32:case ScalarType.SFIXED32:case ScalarType.SINT32:L=Number.parseInt(R);break;case ScalarType.BOOL:assert(R=="true"||R=="false"),L=R=="true";break}switch(writeScalar(T,P.K,1,L),P.V.kind){case"scalar":writeScalar(T,P.V.T,2,A);break;case"enum":writeScalar(T,ScalarType.INT32,2,A);break;case"message":assert(A!==void 0),T.tag(2,WireType.LengthDelimited).bytes(A.toBinary(n));break}T.join()}function writeMessageField(T,n,P,R){const A=wrapField(P.T,R);P.delimited?T.tag(P.no,WireType.StartGroup).raw(A.toBinary(n)).tag(P.no,WireType.EndGroup):T.tag(P.no,WireType.LengthDelimited).bytes(A.toBinary(n))}function writeScalar(T,n,P,R){assert(R!==void 0);let[A,L]=scalarTypeInfo(n);T.tag(P,A)[L](R)}function writePacked(T,n,P,R){if(!R.length)return;T.tag(P,WireType.LengthDelimited).fork();let[,A]=scalarTypeInfo(n);for(let L=0;L<R.length;L++)T[A](R[L]);T.join()}function scalarTypeInfo(T){let n=WireType.Varint;switch(T){case ScalarType.BYTES:case ScalarType.STRING:n=WireType.LengthDelimited;break;case ScalarType.DOUBLE:case ScalarType.FIXED64:case ScalarType.SFIXED64:n=WireType.Bit64;break;case ScalarType.FIXED32:case ScalarType.SFIXED32:case ScalarType.FLOAT:n=WireType.Bit32;break}const P=ScalarType[T].toLowerCase();return[n,P]}function makeUtilCommon(){return{setEnumType,initPartial(T,n){if(T===void 0)return;const P=n.getType();for(const R of P.fields.byMember()){const A=R.localName,L=n,O=T;if(O[A]!=null)switch(R.kind){case"oneof":const N=O[A].case;if(N===void 0)continue;const V=R.findField(N);let j=O[A].value;V&&V.kind=="message"&&!isMessage(j,V.T)?j=new V.T(j):V&&V.kind==="scalar"&&V.T===ScalarType.BYTES&&(j=toU8Arr(j)),L[A]={case:N,value:j};break;case"scalar":case"enum":let B=O[A];R.T===ScalarType.BYTES&&(B=R.repeated?B.map(toU8Arr):toU8Arr(B)),L[A]=B;break;case"map":switch(R.V.kind){case"scalar":case"enum":if(R.V.T===ScalarType.BYTES)for(const[q,H]of Object.entries(O[A]))L[A][q]=toU8Arr(H);else Object.assign(L[A],O[A]);break;case"message":const W=R.V.T;for(const q of Object.keys(O[A])){let H=O[A][q];W.fieldWrapper||(H=new W(H)),L[A][q]=H}break}break;case"message":const z=R.T;if(R.repeated)L[A]=O[A].map(W=>isMessage(W,z)?W:new z(W));else{const W=O[A];z.fieldWrapper?z.typeName==="google.protobuf.BytesValue"?L[A]=toU8Arr(W):L[A]=W:L[A]=isMessage(W,z)?W:new z(W)}break}}},equals(T,n,P){return n===P?!0:!n||!P?!1:T.fields.byMember().every(R=>{const A=n[R.localName],L=P[R.localName];if(R.repeated){if(A.length!==L.length)return!1;switch(R.kind){case"message":return A.every((O,N)=>R.T.equals(O,L[N]));case"scalar":return A.every((O,N)=>scalarEquals(R.T,O,L[N]));case"enum":return A.every((O,N)=>scalarEquals(ScalarType.INT32,O,L[N]))}throw new Error("repeated cannot contain ".concat(R.kind))}switch(R.kind){case"message":let O=A,N=L;return R.T.fieldWrapper&&(O!==void 0&&!isMessage(O)&&(O=R.T.fieldWrapper.wrapField(O)),N!==void 0&&!isMessage(N)&&(N=R.T.fieldWrapper.wrapField(N))),R.T.equals(O,N);case"enum":return scalarEquals(ScalarType.INT32,A,L);case"scalar":return scalarEquals(R.T,A,L);case"oneof":if(A.case!==L.case)return!1;const V=R.findField(A.case);if(V===void 0)return!0;switch(V.kind){case"message":return V.T.equals(A.value,L.value);case"enum":return scalarEquals(ScalarType.INT32,A.value,L.value);case"scalar":return scalarEquals(V.T,A.value,L.value)}throw new Error("oneof cannot contain ".concat(V.kind));case"map":const j=Object.keys(A).concat(Object.keys(L));switch(R.V.kind){case"message":const B=R.V.T;return j.every(W=>B.equals(A[W],L[W]));case"enum":return j.every(W=>scalarEquals(ScalarType.INT32,A[W],L[W]));case"scalar":const z=R.V.T;return j.every(W=>scalarEquals(z,A[W],L[W]))}break}})},clone(T){const n=T.getType(),P=new n,R=P;for(const A of n.fields.byMember()){const L=T[A.localName];let O;if(A.repeated)O=L.map(cloneSingularField);else if(A.kind=="map"){O=R[A.localName];for(const[N,V]of Object.entries(L))O[N]=cloneSingularField(V)}else A.kind=="oneof"?O=A.findField(L.case)?{case:L.case,value:cloneSingularField(L.value)}:{case:void 0}:O=cloneSingularField(L);R[A.localName]=O}for(const A of n.runtime.bin.listUnknownFields(T))n.runtime.bin.onUnknownField(R,A.no,A.wireType,A.data);return P}}}function cloneSingularField(T){if(T===void 0)return T;if(isMessage(T))return T.clone();if(T instanceof Uint8Array){const n=new Uint8Array(T.byteLength);return n.set(T),n}return T}function toU8Arr(T){return T instanceof Uint8Array?T:new Uint8Array(T)}function makeProtoRuntime(T,n,P){return{syntax:T,json:makeJsonFormat(),bin:makeBinaryFormat(),util:Object.assign(Object.assign({},makeUtilCommon()),{newFieldList:n,initFields:P}),makeMessageType(R,A,L){return makeMessageType(this,R,A,L)},makeEnum,makeEnumType,getEnumType,makeExtension(R,A,L){return makeExtension(this,R,A,L)}}}class InternalFieldList{constructor(n,P){this._fields=n,this._normalizer=P}findJsonName(n){if(!this.jsonNames){const P={};for(const R of this.list())P[R.jsonName]=P[R.name]=R;this.jsonNames=P}return this.jsonNames[n]}find(n){if(!this.numbers){const P={};for(const R of this.list())P[R.no]=R;this.numbers=P}return this.numbers[n]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((n,P)=>n.no-P.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const n=this.members;let P;for(const R of this.list())R.oneof?R.oneof!==P&&(P=R.oneof,n.push(P)):n.push(R)}return this.members}}function localFieldName(T,n){const P=protoCamelCase(T);return n?P:safeObjectProperty(safeMessageProperty(P))}function localOneofName(T){return localFieldName(T,!1)}const fieldJsonName=protoCamelCase;function protoCamelCase(T){let n=!1;const P=[];for(let R=0;R<T.length;R++){let A=T.charAt(R);switch(A){case"_":n=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":P.push(A),n=!1;break;default:n&&(n=!1,A=A.toUpperCase()),P.push(A);break}}return P.join("")}const reservedObjectProperties=new Set(["constructor","toString","toJSON","valueOf"]),reservedMessageProperties=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),fallback=T=>"".concat(T,"$"),safeMessageProperty=T=>reservedMessageProperties.has(T)?fallback(T):T,safeObjectProperty=T=>reservedObjectProperties.has(T)?fallback(T):T;class InternalOneofInfo{constructor(n){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=n,this.localName=localOneofName(n)}addField(n){assert(n.oneof===this,"field ".concat(n.name," not one of ").concat(this.name)),this.fields.push(n)}findField(n){if(!this._lookup){this._lookup=Object.create(null);for(let P=0;P<this.fields.length;P++)this._lookup[this.fields[P].localName]=this.fields[P]}return this._lookup[n]}}function normalizeFieldInfos(T,n){var P,R,A,L,O,N;const V=[];let j;for(const B of typeof T=="function"?T():T){const z=B;if(z.localName=localFieldName(B.name,B.oneof!==void 0),z.jsonName=(P=B.jsonName)!==null&&P!==void 0?P:fieldJsonName(B.name),z.repeated=(R=B.repeated)!==null&&R!==void 0?R:!1,B.kind=="scalar"&&(z.L=(A=B.L)!==null&&A!==void 0?A:LongType.BIGINT),z.delimited=(L=B.delimited)!==null&&L!==void 0?L:!1,z.req=(O=B.req)!==null&&O!==void 0?O:!1,z.opt=(N=B.opt)!==null&&N!==void 0?N:!1,B.packed===void 0&&(z.packed=B.kind=="enum"||B.kind=="scalar"&&B.T!=ScalarType.BYTES&&B.T!=ScalarType.STRING),B.oneof!==void 0){const W=typeof B.oneof=="string"?B.oneof:B.oneof.name;(!j||j.name!=W)&&(j=new InternalOneofInfo(W)),z.oneof=j,j.addField(z)}V.push(z)}return V}const proto3=makeProtoRuntime("proto3",T=>new InternalFieldList(T,n=>normalizeFieldInfos(n)),T=>{for(const n of T.getType().fields.byMember()){if(n.opt)continue;const P=n.localName,R=T;if(n.repeated){R[P]=[];continue}switch(n.kind){case"oneof":R[P]={case:void 0};break;case"enum":R[P]=0;break;case"map":R[P]={};break;case"scalar":R[P]=scalarZeroValue(n.T,n.L);break}}});class Timestamp extends Message{constructor(n){super(),this.seconds=protoInt64.zero,this.nanos=0,proto3.util.initPartial(n,this)}fromJson(n,P){if(typeof n!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(proto3.json.debug(n)));const R=n.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!R)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const A=Date.parse(R[1]+"-"+R[2]+"-"+R[3]+"T"+R[4]+":"+R[5]+":"+R[6]+(R[8]?R[8]:"Z"));if(Number.isNaN(A))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(A<Date.parse("0001-01-01T00:00:00Z")||A>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=protoInt64.parse(A/1e3),this.nanos=0,R[7]&&(this.nanos=parseInt("1"+R[7]+"0".repeat(9-R[7].length))-1e9),this}toJson(n){const P=Number(this.seconds)*1e3;if(P<Date.parse("0001-01-01T00:00:00Z")||P>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let R="Z";if(this.nanos>0){const A=(this.nanos+1e9).toString().substring(1);A.substring(3)==="000000"?R="."+A.substring(0,3)+"Z":A.substring(6)==="000"?R="."+A.substring(0,6)+"Z":R="."+A+"Z"}return new Date(P).toISOString().replace(".000Z",R)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Timestamp.fromDate(new Date)}static fromDate(n){const P=n.getTime();return new Timestamp({seconds:protoInt64.parse(Math.floor(P/1e3)),nanos:P%1e3*1e6})}static fromBinary(n,P){return new Timestamp().fromBinary(n,P)}static fromJson(n,P){return new Timestamp().fromJson(n,P)}static fromJsonString(n,P){return new Timestamp().fromJsonString(n,P)}static equals(n,P){return proto3.util.equals(Timestamp,n,P)}}Timestamp.runtime=proto3;Timestamp.typeName="google.protobuf.Timestamp";Timestamp.fields=proto3.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const MetricsBatch=proto3.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Timestamp},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:TimeSeriesMetric,repeated:!0},{no:5,name:"events",kind:"message",T:EventMetric,repeated:!0}]),TimeSeriesMetric=proto3.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:MetricSample,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),MetricSample=proto3.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Timestamp},{no:3,name:"value",kind:"scalar",T:2}]),EventMetric=proto3.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Timestamp},{no:7,name:"normalized_end_timestamp",kind:"message",T:Timestamp,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),BackupCodecPolicy$1=proto3.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),TrackType=proto3.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),TrackSource=proto3.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),VideoQuality$1=proto3.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ConnectionQuality$1=proto3.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ClientConfigSetting=proto3.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),DisconnectReason=proto3.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),ReconnectReason=proto3.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),SubscriptionError=proto3.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),AudioTrackFeature=proto3.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),Room$1=proto3.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Codec,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:TimedVersion}]),Codec=proto3.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),ParticipantPermission=proto3.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:proto3.getEnumType(TrackSource),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),ParticipantInfo=proto3.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:proto3.getEnumType(ParticipantInfo_State)},{no:4,name:"tracks",kind:"message",T:TrackInfo,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:ParticipantPermission},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:proto3.getEnumType(ParticipantInfo_Kind)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:proto3.getEnumType(DisconnectReason)},{no:18,name:"kind_details",kind:"enum",T:proto3.getEnumType(ParticipantInfo_KindDetail),repeated:!0}]),ParticipantInfo_State=proto3.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ParticipantInfo_Kind=proto3.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),ParticipantInfo_KindDetail=proto3.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Encryption_Type=proto3.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),SimulcastCodecInfo=proto3.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:VideoLayer,repeated:!0}]),TrackInfo=proto3.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:proto3.getEnumType(TrackType)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:proto3.getEnumType(TrackSource)},{no:10,name:"layers",kind:"message",T:VideoLayer,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:SimulcastCodecInfo,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:proto3.getEnumType(Encryption_Type)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:TimedVersion},{no:19,name:"audio_features",kind:"enum",T:proto3.getEnumType(AudioTrackFeature),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:proto3.getEnumType(BackupCodecPolicy$1)}]),VideoLayer=proto3.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:proto3.getEnumType(VideoQuality$1)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),DataPacket=proto3.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:proto3.getEnumType(DataPacket_Kind)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:UserPacket,oneof:"value"},{no:3,name:"speaker",kind:"message",T:ActiveSpeakerUpdate,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:SipDTMF,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Transcription,oneof:"value"},{no:8,name:"metrics",kind:"message",T:MetricsBatch,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ChatMessage,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:RpcRequest,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:RpcAck,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:RpcResponse,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:DataStream_Header,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:DataStream_Chunk,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:DataStream_Trailer,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),DataPacket_Kind=proto3.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),ActiveSpeakerUpdate=proto3.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:SpeakerInfo,repeated:!0}]),SpeakerInfo=proto3.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),UserPacket=proto3.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),SipDTMF=proto3.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Transcription=proto3.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:TranscriptionSegment,repeated:!0}]),TranscriptionSegment=proto3.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),ChatMessage=proto3.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),RpcRequest=proto3.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),RpcAck=proto3.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),RpcResponse=proto3.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:RpcError$1,oneof:"value"}]),RpcError$1=proto3.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),ParticipantTracks=proto3.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),ServerInfo=proto3.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:proto3.getEnumType(ServerInfo_Edition)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),ServerInfo_Edition=proto3.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),ClientInfo=proto3.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:proto3.getEnumType(ClientInfo_SDK)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),ClientInfo_SDK=proto3.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),ClientConfiguration=proto3.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:VideoConfiguration},{no:2,name:"screen",kind:"message",T:VideoConfiguration},{no:3,name:"resume_connection",kind:"enum",T:proto3.getEnumType(ClientConfigSetting)},{no:4,name:"disabled_codecs",kind:"message",T:DisabledCodecs},{no:5,name:"force_relay",kind:"enum",T:proto3.getEnumType(ClientConfigSetting)}]),VideoConfiguration=proto3.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:proto3.getEnumType(ClientConfigSetting)}]),DisabledCodecs=proto3.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Codec,repeated:!0},{no:2,name:"publish",kind:"message",T:Codec,repeated:!0}]),TimedVersion=proto3.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),DataStream_OperationType=proto3.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),DataStream_TextHeader=proto3.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:proto3.getEnumType(DataStream_OperationType)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),DataStream_ByteHeader=proto3.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),DataStream_Header=proto3.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:proto3.getEnumType(Encryption_Type)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:DataStream_TextHeader,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:DataStream_ByteHeader,oneof:"content_header"}],{localName:"DataStream_Header"}),DataStream_Chunk=proto3.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),DataStream_Trailer=proto3.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),SignalTarget=proto3.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),StreamState=proto3.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),CandidateProtocol=proto3.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),SignalRequest=proto3.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:SessionDescription,oneof:"message"},{no:2,name:"answer",kind:"message",T:SessionDescription,oneof:"message"},{no:3,name:"trickle",kind:"message",T:TrickleRequest,oneof:"message"},{no:4,name:"add_track",kind:"message",T:AddTrackRequest,oneof:"message"},{no:5,name:"mute",kind:"message",T:MuteTrackRequest,oneof:"message"},{no:6,name:"subscription",kind:"message",T:UpdateSubscription,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:UpdateTrackSettings,oneof:"message"},{no:8,name:"leave",kind:"message",T:LeaveRequest,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:UpdateVideoLayers,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:SubscriptionPermission,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:SyncState,oneof:"message"},{no:13,name:"simulate",kind:"message",T:SimulateScenario,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:UpdateParticipantMetadata,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ping,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:UpdateLocalAudioTrack,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:UpdateLocalVideoTrack,oneof:"message"}]),SignalResponse=proto3.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:JoinResponse,oneof:"message"},{no:2,name:"answer",kind:"message",T:SessionDescription,oneof:"message"},{no:3,name:"offer",kind:"message",T:SessionDescription,oneof:"message"},{no:4,name:"trickle",kind:"message",T:TrickleRequest,oneof:"message"},{no:5,name:"update",kind:"message",T:ParticipantUpdate,oneof:"message"},{no:6,name:"track_published",kind:"message",T:TrackPublishedResponse,oneof:"message"},{no:8,name:"leave",kind:"message",T:LeaveRequest,oneof:"message"},{no:9,name:"mute",kind:"message",T:MuteTrackRequest,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:SpeakersChanged,oneof:"message"},{no:11,name:"room_update",kind:"message",T:RoomUpdate,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:ConnectionQualityUpdate,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:StreamStateUpdate,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:SubscribedQualityUpdate,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:SubscriptionPermissionUpdate,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:TrackUnpublishedResponse,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:ReconnectResponse,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Pong,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:SubscriptionResponse,oneof:"message"},{no:22,name:"request_response",kind:"message",T:RequestResponse,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:TrackSubscribed,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:RoomMovedResponse,oneof:"message"}]),SimulcastCodec=proto3.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),AddTrackRequest=proto3.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:proto3.getEnumType(TrackType)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:proto3.getEnumType(TrackSource)},{no:9,name:"layers",kind:"message",T:VideoLayer,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:SimulcastCodec,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:proto3.getEnumType(Encryption_Type)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:proto3.getEnumType(BackupCodecPolicy$1)},{no:17,name:"audio_features",kind:"enum",T:proto3.getEnumType(AudioTrackFeature),repeated:!0}]),TrickleRequest=proto3.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:proto3.getEnumType(SignalTarget)},{no:3,name:"final",kind:"scalar",T:8}]),MuteTrackRequest=proto3.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),JoinResponse=proto3.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Room$1},{no:2,name:"participant",kind:"message",T:ParticipantInfo},{no:3,name:"other_participants",kind:"message",T:ParticipantInfo,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ICEServer,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:ClientConfiguration},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:ServerInfo},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Codec,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),ReconnectResponse=proto3.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ICEServer,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ClientConfiguration},{no:3,name:"server_info",kind:"message",T:ServerInfo},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),TrackPublishedResponse=proto3.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:TrackInfo}]),TrackUnpublishedResponse=proto3.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),SessionDescription=proto3.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),ParticipantUpdate=proto3.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ParticipantInfo,repeated:!0}]),UpdateSubscription=proto3.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:ParticipantTracks,repeated:!0}]),UpdateTrackSettings=proto3.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:proto3.getEnumType(VideoQuality$1)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),UpdateLocalAudioTrack=proto3.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:proto3.getEnumType(AudioTrackFeature),repeated:!0}]),UpdateLocalVideoTrack=proto3.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),LeaveRequest=proto3.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:proto3.getEnumType(DisconnectReason)},{no:3,name:"action",kind:"enum",T:proto3.getEnumType(LeaveRequest_Action)},{no:4,name:"regions",kind:"message",T:RegionSettings}]),LeaveRequest_Action=proto3.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),UpdateVideoLayers=proto3.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:VideoLayer,repeated:!0}]),UpdateParticipantMetadata=proto3.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),ICEServer=proto3.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),SpeakersChanged=proto3.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:SpeakerInfo,repeated:!0}]),RoomUpdate=proto3.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Room$1}]),ConnectionQualityInfo=proto3.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:proto3.getEnumType(ConnectionQuality$1)},{no:3,name:"score",kind:"scalar",T:2}]),ConnectionQualityUpdate=proto3.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:ConnectionQualityInfo,repeated:!0}]),StreamStateInfo=proto3.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:proto3.getEnumType(StreamState)}]),StreamStateUpdate=proto3.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:StreamStateInfo,repeated:!0}]),SubscribedQuality=proto3.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:proto3.getEnumType(VideoQuality$1)},{no:2,name:"enabled",kind:"scalar",T:8}]),SubscribedCodec=proto3.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:SubscribedQuality,repeated:!0}]),SubscribedQualityUpdate=proto3.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:SubscribedQuality,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:SubscribedCodec,repeated:!0}]),TrackPermission=proto3.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),SubscriptionPermission=proto3.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:TrackPermission,repeated:!0}]),SubscriptionPermissionUpdate=proto3.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),RoomMovedResponse=proto3.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Room$1},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ParticipantInfo},{no:4,name:"other_participants",kind:"message",T:ParticipantInfo,repeated:!0}]),SyncState=proto3.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:SessionDescription},{no:2,name:"subscription",kind:"message",T:UpdateSubscription},{no:3,name:"publish_tracks",kind:"message",T:TrackPublishedResponse,repeated:!0},{no:4,name:"data_channels",kind:"message",T:DataChannelInfo,repeated:!0},{no:5,name:"offer",kind:"message",T:SessionDescription},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:DataChannelReceiveState,repeated:!0}]),DataChannelReceiveState=proto3.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),DataChannelInfo=proto3.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:proto3.getEnumType(SignalTarget)}]),SimulateScenario=proto3.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:proto3.getEnumType(CandidateProtocol),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Ping=proto3.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Pong=proto3.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),RegionSettings=proto3.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:RegionInfo,repeated:!0}]),RegionInfo=proto3.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),SubscriptionResponse=proto3.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:proto3.getEnumType(SubscriptionError)}]),RequestResponse=proto3.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:proto3.getEnumType(RequestResponse_Reason)},{no:3,name:"message",kind:"scalar",T:9}]),RequestResponse_Reason=proto3.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),TrackSubscribed=proto3.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function getDefaultExportFromCjs(T){return T&&T.__esModule&&Object.prototype.hasOwnProperty.call(T,"default")?T.default:T}var loglevel$1={exports:{}},loglevel=loglevel$1.exports,hasRequiredLoglevel;function requireLoglevel(){return hasRequiredLoglevel||(hasRequiredLoglevel=1,(function(T){(function(n,P){T.exports?T.exports=P():n.log=P()})(loglevel,function(){var n=function(){},P="undefined",R=typeof window!==P&&typeof window.navigator!==P&&/Trident\/|MSIE /.test(window.navigator.userAgent),A=["trace","debug","info","warn","error"],L={},O=null;function N($,Q){var U=$[Q];if(typeof U.bind=="function")return U.bind($);try{return Function.prototype.bind.call(U,$)}catch{return function(){return Function.prototype.apply.apply(U,[$,arguments])}}}function V(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function j($){return $==="debug"&&($="log"),typeof console===P?!1:$==="trace"&&R?V:console[$]!==void 0?N(console,$):console.log!==void 0?N(console,"log"):n}function B(){for(var $=this.getLevel(),Q=0;Q<A.length;Q++){var U=A[Q];this[U]=Q<$?n:this.methodFactory(U,$,this.name)}if(this.log=this.debug,typeof console===P&&$<this.levels.SILENT)return"No console available for logging"}function z($){return function(){typeof console!==P&&(B.call(this),this[$].apply(this,arguments))}}function W($,Q,U){return j($)||z.apply(this,arguments)}function q($,Q){var U=this,J,G,K,Y="loglevel";typeof $=="string"?Y+=":"+$:typeof $=="symbol"&&(Y=void 0);function Z(ue){var he=(A[ue]||"silent").toUpperCase();if(!(typeof window===P||!Y)){try{window.localStorage[Y]=he;return}catch{}try{window.document.cookie=encodeURIComponent(Y)+"="+he+";"}catch{}}}function ie(){var ue;if(!(typeof window===P||!Y)){try{ue=window.localStorage[Y]}catch{}if(typeof ue===P)try{var he=window.document.cookie,ve=encodeURIComponent(Y),be=he.indexOf(ve+"=");be!==-1&&(ue=/^([^;]+)/.exec(he.slice(be+ve.length+1))[1])}catch{}return U.levels[ue]===void 0&&(ue=void 0),ue}}function se(){if(!(typeof window===P||!Y)){try{window.localStorage.removeItem(Y)}catch{}try{window.document.cookie=encodeURIComponent(Y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function le(ue){var he=ue;if(typeof he=="string"&&U.levels[he.toUpperCase()]!==void 0&&(he=U.levels[he.toUpperCase()]),typeof he=="number"&&he>=0&&he<=U.levels.SILENT)return he;throw new TypeError("log.setLevel() called with invalid level: "+ue)}U.name=$,U.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},U.methodFactory=Q||W,U.getLevel=function(){return K??G??J},U.setLevel=function(ue,he){return K=le(ue),he!==!1&&Z(K),B.call(U)},U.setDefaultLevel=function(ue){G=le(ue),ie()||U.setLevel(ue,!1)},U.resetLevel=function(){K=null,se(),B.call(U)},U.enableAll=function(ue){U.setLevel(U.levels.TRACE,ue)},U.disableAll=function(ue){U.setLevel(U.levels.SILENT,ue)},U.rebuild=function(){if(O!==U&&(J=le(O.getLevel())),B.call(U),O===U)for(var ue in L)L[ue].rebuild()},J=le(O?O.getLevel():"WARN");var pe=ie();pe!=null&&(K=le(pe)),B.call(U)}O=new q,O.getLogger=function(Q){if(typeof Q!="symbol"&&typeof Q!="string"||Q==="")throw new TypeError("You must supply a name when creating a logger.");var U=L[Q];return U||(U=L[Q]=new q(Q,O.methodFactory)),U};var H=typeof window!==P?window.log:void 0;return O.noConflict=function(){return typeof window!==P&&window.log===O&&(window.log=H),O},O.getLoggers=function(){return L},O.default=O,O})})(loglevel$1)),loglevel$1.exports}var loglevelExports=requireLoglevel(),LogLevel;(function(T){T[T.trace=0]="trace",T[T.debug=1]="debug",T[T.info=2]="info",T[T.warn=3]="warn",T[T.error=4]="error",T[T.silent=5]="silent"})(LogLevel||(LogLevel={}));var LoggerNames;(function(T){T.Default="livekit",T.Room="livekit-room",T.Participant="livekit-participant",T.Track="livekit-track",T.Publication="livekit-track-publication",T.Engine="livekit-engine",T.Signal="livekit-signal",T.PCManager="livekit-pc-manager",T.PCTransport="livekit-pc-transport",T.E2EE="lk-e2ee"})(LoggerNames||(LoggerNames={}));let livekitLogger=loglevelExports.getLogger("livekit");Object.values(LoggerNames).map(T=>loglevelExports.getLogger(T));livekitLogger.setDefaultLevel(LogLevel.info);function getLogger(T){const n=loglevelExports.getLogger(T);return n.setDefaultLevel(livekitLogger.getLevel()),n}const workerLogger=loglevelExports.getLogger("lk-e2ee"),maxRetryDelay=7e3,DEFAULT_RETRY_DELAYS_IN_MS=[0,300,4*300,9*300,16*300,maxRetryDelay,maxRetryDelay,maxRetryDelay,maxRetryDelay,maxRetryDelay];class DefaultReconnectPolicy{constructor(n){this._retryDelays=n!==void 0?[...n]:DEFAULT_RETRY_DELAYS_IN_MS}nextRetryDelayInMs(n){if(n.retryCount>=this._retryDelays.length)return null;const P=this._retryDelays[n.retryCount];return n.retryCount<=1?P:P+Math.random()*1e3}}function __rest(T,n){var P={};for(var R in T)Object.prototype.hasOwnProperty.call(T,R)&&n.indexOf(R)<0&&(P[R]=T[R]);if(T!=null&&typeof Object.getOwnPropertySymbols=="function")for(var A=0,R=Object.getOwnPropertySymbols(T);A<R.length;A++)n.indexOf(R[A])<0&&Object.prototype.propertyIsEnumerable.call(T,R[A])&&(P[R[A]]=T[R[A]]);return P}function __awaiter(T,n,P,R){function A(L){return L instanceof P?L:new P(function(O){O(L)})}return new(P||(P=Promise))(function(L,O){function N(B){try{j(R.next(B))}catch(z){O(z)}}function V(B){try{j(R.throw(B))}catch(z){O(z)}}function j(B){B.done?L(B.value):A(B.value).then(N,V)}j((R=R.apply(T,n||[])).next())})}function __values(T){var n=typeof Symbol=="function"&&Symbol.iterator,P=n&&T[n],R=0;if(P)return P.call(T);if(T&&typeof T.length=="number")return{next:function(){return T&&R>=T.length&&(T=void 0),{value:T&&T[R++],done:!T}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function __asyncValues(T){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=T[Symbol.asyncIterator],P;return n?n.call(T):(T=typeof __values=="function"?__values(T):T[Symbol.iterator](),P={},R("next"),R("throw"),R("return"),P[Symbol.asyncIterator]=function(){return this},P);function R(L){P[L]=T[L]&&function(O){return new Promise(function(N,V){O=T[L](O),A(N,V,O.done,O.value)})}}function A(L,O,N,V){Promise.resolve(V).then(function(j){L({value:j,done:N})},O)}}typeof SuppressedError=="function"&&SuppressedError;var events={exports:{}},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events.exports;hasRequiredEvents=1;var T=typeof Reflect=="object"?Reflect:null,n=T&&typeof T.apply=="function"?T.apply:function(Y,Z,ie){return Function.prototype.apply.call(Y,Z,ie)},P;T&&typeof T.ownKeys=="function"?P=T.ownKeys:Object.getOwnPropertySymbols?P=function(Y){return Object.getOwnPropertyNames(Y).concat(Object.getOwnPropertySymbols(Y))}:P=function(Y){return Object.getOwnPropertyNames(Y)};function R(K){console&&console.warn&&console.warn(K)}var A=Number.isNaN||function(Y){return Y!==Y};function L(){L.init.call(this)}events.exports=L,events.exports.once=U,L.EventEmitter=L,L.prototype._events=void 0,L.prototype._eventsCount=0,L.prototype._maxListeners=void 0;var O=10;function N(K){if(typeof K!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof K)}Object.defineProperty(L,"defaultMaxListeners",{enumerable:!0,get:function(){return O},set:function(K){if(typeof K!="number"||K<0||A(K))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+K+".");O=K}}),L.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},L.prototype.setMaxListeners=function(Y){if(typeof Y!="number"||Y<0||A(Y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+Y+".");return this._maxListeners=Y,this};function V(K){return K._maxListeners===void 0?L.defaultMaxListeners:K._maxListeners}L.prototype.getMaxListeners=function(){return V(this)},L.prototype.emit=function(Y){for(var Z=[],ie=1;ie<arguments.length;ie++)Z.push(arguments[ie]);var se=Y==="error",le=this._events;if(le!==void 0)se=se&&le.error===void 0;else if(!se)return!1;if(se){var pe;if(Z.length>0&&(pe=Z[0]),pe instanceof Error)throw pe;var ue=new Error("Unhandled error."+(pe?" ("+pe.message+")":""));throw ue.context=pe,ue}var he=le[Y];if(he===void 0)return!1;if(typeof he=="function")n(he,this,Z);else for(var ve=he.length,be=H(he,ve),ie=0;ie<ve;++ie)n(be[ie],this,Z);return!0};function j(K,Y,Z,ie){var se,le,pe;if(N(Z),le=K._events,le===void 0?(le=K._events=Object.create(null),K._eventsCount=0):(le.newListener!==void 0&&(K.emit("newListener",Y,Z.listener?Z.listener:Z),le=K._events),pe=le[Y]),pe===void 0)pe=le[Y]=Z,++K._eventsCount;else if(typeof pe=="function"?pe=le[Y]=ie?[Z,pe]:[pe,Z]:ie?pe.unshift(Z):pe.push(Z),se=V(K),se>0&&pe.length>se&&!pe.warned){pe.warned=!0;var ue=new Error("Possible EventEmitter memory leak detected. "+pe.length+" "+String(Y)+" listeners added. Use emitter.setMaxListeners() to increase limit");ue.name="MaxListenersExceededWarning",ue.emitter=K,ue.type=Y,ue.count=pe.length,R(ue)}return K}L.prototype.addListener=function(Y,Z){return j(this,Y,Z,!1)},L.prototype.on=L.prototype.addListener,L.prototype.prependListener=function(Y,Z){return j(this,Y,Z,!0)};function B(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function z(K,Y,Z){var ie={fired:!1,wrapFn:void 0,target:K,type:Y,listener:Z},se=B.bind(ie);return se.listener=Z,ie.wrapFn=se,se}L.prototype.once=function(Y,Z){return N(Z),this.on(Y,z(this,Y,Z)),this},L.prototype.prependOnceListener=function(Y,Z){return N(Z),this.prependListener(Y,z(this,Y,Z)),this},L.prototype.removeListener=function(Y,Z){var ie,se,le,pe,ue;if(N(Z),se=this._events,se===void 0)return this;if(ie=se[Y],ie===void 0)return this;if(ie===Z||ie.listener===Z)--this._eventsCount===0?this._events=Object.create(null):(delete se[Y],se.removeListener&&this.emit("removeListener",Y,ie.listener||Z));else if(typeof ie!="function"){for(le=-1,pe=ie.length-1;pe>=0;pe--)if(ie[pe]===Z||ie[pe].listener===Z){ue=ie[pe].listener,le=pe;break}if(le<0)return this;le===0?ie.shift():$(ie,le),ie.length===1&&(se[Y]=ie[0]),se.removeListener!==void 0&&this.emit("removeListener",Y,ue||Z)}return this},L.prototype.off=L.prototype.removeListener,L.prototype.removeAllListeners=function(Y){var Z,ie,se;if(ie=this._events,ie===void 0)return this;if(ie.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):ie[Y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete ie[Y]),this;if(arguments.length===0){var le=Object.keys(ie),pe;for(se=0;se<le.length;++se)pe=le[se],pe!=="removeListener"&&this.removeAllListeners(pe);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(Z=ie[Y],typeof Z=="function")this.removeListener(Y,Z);else if(Z!==void 0)for(se=Z.length-1;se>=0;se--)this.removeListener(Y,Z[se]);return this};function W(K,Y,Z){var ie=K._events;if(ie===void 0)return[];var se=ie[Y];return se===void 0?[]:typeof se=="function"?Z?[se.listener||se]:[se]:Z?Q(se):H(se,se.length)}L.prototype.listeners=function(Y){return W(this,Y,!0)},L.prototype.rawListeners=function(Y){return W(this,Y,!1)},L.listenerCount=function(K,Y){return typeof K.listenerCount=="function"?K.listenerCount(Y):q.call(K,Y)},L.prototype.listenerCount=q;function q(K){var Y=this._events;if(Y!==void 0){var Z=Y[K];if(typeof Z=="function")return 1;if(Z!==void 0)return Z.length}return 0}L.prototype.eventNames=function(){return this._eventsCount>0?P(this._events):[]};function H(K,Y){for(var Z=new Array(Y),ie=0;ie<Y;++ie)Z[ie]=K[ie];return Z}function $(K,Y){for(;Y+1<K.length;Y++)K[Y]=K[Y+1];K.pop()}function Q(K){for(var Y=new Array(K.length),Z=0;Z<Y.length;++Z)Y[Z]=K[Z].listener||K[Z];return Y}function U(K,Y){return new Promise(function(Z,ie){function se(pe){K.removeListener(Y,le),ie(pe)}function le(){typeof K.removeListener=="function"&&K.removeListener("error",se),Z([].slice.call(arguments))}G(K,Y,le,{once:!0}),Y!=="error"&&J(K,se,{once:!0})})}function J(K,Y,Z){typeof K.on=="function"&&G(K,"error",Y,Z)}function G(K,Y,Z,ie){if(typeof K.on=="function")ie.once?K.once(Y,Z):K.on(Y,Z);else if(typeof K.addEventListener=="function")K.addEventListener(Y,function se(le){ie.once&&K.removeEventListener(Y,se),Z(le)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof K)}return events.exports}var eventsExports=requireEvents();let logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(T,n,P){const R=T.match(n);return R&&R.length>=P&&parseFloat(R[P],10)}function wrapPeerConnectionEvent(T,n,P){if(!T.RTCPeerConnection)return;const R=T.RTCPeerConnection.prototype,A=R.addEventListener;R.addEventListener=function(O,N){if(O!==n)return A.apply(this,arguments);const V=j=>{const B=P(j);B&&(N.handleEvent?N.handleEvent(B):N(B))};return this._eventMap=this._eventMap||{},this._eventMap[n]||(this._eventMap[n]=new Map),this._eventMap[n].set(N,V),A.apply(this,[O,V])};const L=R.removeEventListener;R.removeEventListener=function(O,N){if(O!==n||!this._eventMap||!this._eventMap[n])return L.apply(this,arguments);if(!this._eventMap[n].has(N))return L.apply(this,arguments);const V=this._eventMap[n].get(N);return this._eventMap[n].delete(N),this._eventMap[n].size===0&&delete this._eventMap[n],Object.keys(this._eventMap).length===0&&delete this._eventMap,L.apply(this,[O,V])},Object.defineProperty(R,"on"+n,{get(){return this["_on"+n]},set(O){this["_on"+n]&&(this.removeEventListener(n,this["_on"+n]),delete this["_on"+n]),O&&this.addEventListener(n,this["_on"+n]=O)},enumerable:!0,configurable:!0})}function disableLog(T){return typeof T!="boolean"?new Error("Argument type: "+typeof T+". Please use a boolean."):(logDisabled_=T,T?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(T){return typeof T!="boolean"?new Error("Argument type: "+typeof T+". Please use a boolean."):(deprecationWarnings_=!T,"adapter.js deprecation warnings "+(T?"disabled":"enabled"))}function log(){if(typeof window=="object"){if(logDisabled_)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function deprecated(T,n){deprecationWarnings_&&console.warn(T+" is deprecated, please use "+n+" instead.")}function detectBrowser(T){const n={browser:null,version:null};if(typeof T>"u"||!T.navigator||!T.navigator.userAgent)return n.browser="Not a browser.",n;const{navigator:P}=T;if(P.userAgentData&&P.userAgentData.brands){const R=P.userAgentData.brands.find(A=>A.brand==="Chromium");if(R)return{browser:"chrome",version:parseInt(R.version,10)}}if(P.mozGetUserMedia)n.browser="firefox",n.version=parseInt(extractVersion(P.userAgent,/Firefox\/(\d+)\./,1));else if(P.webkitGetUserMedia||T.isSecureContext===!1&&T.webkitRTCPeerConnection)n.browser="chrome",n.version=parseInt(extractVersion(P.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(T.RTCPeerConnection&&P.userAgent.match(/AppleWebKit\/(\d+)\./))n.browser="safari",n.version=parseInt(extractVersion(P.userAgent,/AppleWebKit\/(\d+)\./,1)),n.supportsUnifiedPlan=T.RTCRtpTransceiver&&"currentDirection"in T.RTCRtpTransceiver.prototype,n._safariVersion=extractVersion(P.userAgent,/Version\/(\d+(\.?\d+))/,1);else return n.browser="Not a supported browser.",n;return n}function isObject$1(T){return Object.prototype.toString.call(T)==="[object Object]"}function compactObject(T){return isObject$1(T)?Object.keys(T).reduce(function(n,P){const R=isObject$1(T[P]),A=R?compactObject(T[P]):T[P],L=R&&!Object.keys(A).length;return A===void 0||L?n:Object.assign(n,{[P]:A})},{}):T}function walkStats(T,n,P){!n||P.has(n.id)||(P.set(n.id,n),Object.keys(n).forEach(R=>{R.endsWith("Id")?walkStats(T,T.get(n[R]),P):R.endsWith("Ids")&&n[R].forEach(A=>{walkStats(T,T.get(A),P)})}))}function filterStats(T,n,P){const R=P?"outbound-rtp":"inbound-rtp",A=new Map;if(n===null)return A;const L=[];return T.forEach(O=>{O.type==="track"&&O.trackIdentifier===n.id&&L.push(O)}),L.forEach(O=>{T.forEach(N=>{N.type===R&&N.trackId===O.id&&walkStats(T,N,A)})}),A}const logging=log;function shimGetUserMedia$2(T,n){const P=T&&T.navigator;if(!P.mediaDevices)return;const R=function(N){if(typeof N!="object"||N.mandatory||N.optional)return N;const V={};return Object.keys(N).forEach(j=>{if(j==="require"||j==="advanced"||j==="mediaSource")return;const B=typeof N[j]=="object"?N[j]:{ideal:N[j]};B.exact!==void 0&&typeof B.exact=="number"&&(B.min=B.max=B.exact);const z=function(W,q){return W?W+q.charAt(0).toUpperCase()+q.slice(1):q==="deviceId"?"sourceId":q};if(B.ideal!==void 0){V.optional=V.optional||[];let W={};typeof B.ideal=="number"?(W[z("min",j)]=B.ideal,V.optional.push(W),W={},W[z("max",j)]=B.ideal,V.optional.push(W)):(W[z("",j)]=B.ideal,V.optional.push(W))}B.exact!==void 0&&typeof B.exact!="number"?(V.mandatory=V.mandatory||{},V.mandatory[z("",j)]=B.exact):["min","max"].forEach(W=>{B[W]!==void 0&&(V.mandatory=V.mandatory||{},V.mandatory[z(W,j)]=B[W])})}),N.advanced&&(V.optional=(V.optional||[]).concat(N.advanced)),V},A=function(N,V){if(n.version>=61)return V(N);if(N=JSON.parse(JSON.stringify(N)),N&&typeof N.audio=="object"){const j=function(B,z,W){z in B&&!(W in B)&&(B[W]=B[z],delete B[z])};N=JSON.parse(JSON.stringify(N)),j(N.audio,"autoGainControl","googAutoGainControl"),j(N.audio,"noiseSuppression","googNoiseSuppression"),N.audio=R(N.audio)}if(N&&typeof N.video=="object"){let j=N.video.facingMode;j=j&&(typeof j=="object"?j:{ideal:j});const B=n.version<66;if(j&&(j.exact==="user"||j.exact==="environment"||j.ideal==="user"||j.ideal==="environment")&&!(P.mediaDevices.getSupportedConstraints&&P.mediaDevices.getSupportedConstraints().facingMode&&!B)){delete N.video.facingMode;let z;if(j.exact==="environment"||j.ideal==="environment"?z=["back","rear"]:(j.exact==="user"||j.ideal==="user")&&(z=["front"]),z)return P.mediaDevices.enumerateDevices().then(W=>{W=W.filter(H=>H.kind==="videoinput");let q=W.find(H=>z.some($=>H.label.toLowerCase().includes($)));return!q&&W.length&&z.includes("back")&&(q=W[W.length-1]),q&&(N.video.deviceId=j.exact?{exact:q.deviceId}:{ideal:q.deviceId}),N.video=R(N.video),logging("chrome: "+JSON.stringify(N)),V(N)})}N.video=R(N.video)}return logging("chrome: "+JSON.stringify(N)),V(N)},L=function(N){return n.version>=64?N:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[N.name]||N.name,message:N.message,constraint:N.constraint||N.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},O=function(N,V,j){A(N,B=>{P.webkitGetUserMedia(B,V,z=>{j&&j(L(z))})})};if(P.getUserMedia=O.bind(P),P.mediaDevices.getUserMedia){const N=P.mediaDevices.getUserMedia.bind(P.mediaDevices);P.mediaDevices.getUserMedia=function(V){return A(V,j=>N(j).then(B=>{if(j.audio&&!B.getAudioTracks().length||j.video&&!B.getVideoTracks().length)throw B.getTracks().forEach(z=>{z.stop()}),new DOMException("","NotFoundError");return B},B=>Promise.reject(L(B))))}}}function shimMediaStream(T){T.MediaStream=T.MediaStream||T.webkitMediaStream}function shimOnTrack$1(T){if(typeof T=="object"&&T.RTCPeerConnection&&!("ontrack"in T.RTCPeerConnection.prototype)){Object.defineProperty(T.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(P){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=P)},enumerable:!0,configurable:!0});const n=T.RTCPeerConnection.prototype.setRemoteDescription;T.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=R=>{R.stream.addEventListener("addtrack",A=>{let L;T.RTCPeerConnection.prototype.getReceivers?L=this.getReceivers().find(N=>N.track&&N.track.id===A.track.id):L={track:A.track};const O=new Event("track");O.track=A.track,O.receiver=L,O.transceiver={receiver:L},O.streams=[R.stream],this.dispatchEvent(O)}),R.stream.getTracks().forEach(A=>{let L;T.RTCPeerConnection.prototype.getReceivers?L=this.getReceivers().find(N=>N.track&&N.track.id===A.id):L={track:A};const O=new Event("track");O.track=A,O.receiver=L,O.transceiver={receiver:L},O.streams=[R.stream],this.dispatchEvent(O)})},this.addEventListener("addstream",this._ontrackpoly)),n.apply(this,arguments)}}else wrapPeerConnectionEvent(T,"track",n=>(n.transceiver||Object.defineProperty(n,"transceiver",{value:{receiver:n.receiver}}),n))}function shimGetSendersWithDtmf(T){if(typeof T=="object"&&T.RTCPeerConnection&&!("getSenders"in T.RTCPeerConnection.prototype)&&"createDTMFSender"in T.RTCPeerConnection.prototype){const n=function(A,L){return{track:L,get dtmf(){return this._dtmf===void 0&&(L.kind==="audio"?this._dtmf=A.createDTMFSender(L):this._dtmf=null),this._dtmf},_pc:A}};if(!T.RTCPeerConnection.prototype.getSenders){T.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const A=T.RTCPeerConnection.prototype.addTrack;T.RTCPeerConnection.prototype.addTrack=function(N,V){let j=A.apply(this,arguments);return j||(j=n(this,N),this._senders.push(j)),j};const L=T.RTCPeerConnection.prototype.removeTrack;T.RTCPeerConnection.prototype.removeTrack=function(N){L.apply(this,arguments);const V=this._senders.indexOf(N);V!==-1&&this._senders.splice(V,1)}}const P=T.RTCPeerConnection.prototype.addStream;T.RTCPeerConnection.prototype.addStream=function(L){this._senders=this._senders||[],P.apply(this,[L]),L.getTracks().forEach(O=>{this._senders.push(n(this,O))})};const R=T.RTCPeerConnection.prototype.removeStream;T.RTCPeerConnection.prototype.removeStream=function(L){this._senders=this._senders||[],R.apply(this,[L]),L.getTracks().forEach(O=>{const N=this._senders.find(V=>V.track===O);N&&this._senders.splice(this._senders.indexOf(N),1)})}}else if(typeof T=="object"&&T.RTCPeerConnection&&"getSenders"in T.RTCPeerConnection.prototype&&"createDTMFSender"in T.RTCPeerConnection.prototype&&T.RTCRtpSender&&!("dtmf"in T.RTCRtpSender.prototype)){const n=T.RTCPeerConnection.prototype.getSenders;T.RTCPeerConnection.prototype.getSenders=function(){const R=n.apply(this,[]);return R.forEach(A=>A._pc=this),R},Object.defineProperty(T.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimSenderReceiverGetStats(T){if(!(typeof T=="object"&&T.RTCPeerConnection&&T.RTCRtpSender&&T.RTCRtpReceiver))return;if(!("getStats"in T.RTCRtpSender.prototype)){const P=T.RTCPeerConnection.prototype.getSenders;P&&(T.RTCPeerConnection.prototype.getSenders=function(){const L=P.apply(this,[]);return L.forEach(O=>O._pc=this),L});const R=T.RTCPeerConnection.prototype.addTrack;R&&(T.RTCPeerConnection.prototype.addTrack=function(){const L=R.apply(this,arguments);return L._pc=this,L}),T.RTCRtpSender.prototype.getStats=function(){const L=this;return this._pc.getStats().then(O=>filterStats(O,L.track,!0))}}if(!("getStats"in T.RTCRtpReceiver.prototype)){const P=T.RTCPeerConnection.prototype.getReceivers;P&&(T.RTCPeerConnection.prototype.getReceivers=function(){const A=P.apply(this,[]);return A.forEach(L=>L._pc=this),A}),wrapPeerConnectionEvent(T,"track",R=>(R.receiver._pc=R.srcElement,R)),T.RTCRtpReceiver.prototype.getStats=function(){const A=this;return this._pc.getStats().then(L=>filterStats(L,A.track,!1))}}if(!("getStats"in T.RTCRtpSender.prototype&&"getStats"in T.RTCRtpReceiver.prototype))return;const n=T.RTCPeerConnection.prototype.getStats;T.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof T.MediaStreamTrack){const R=arguments[0];let A,L,O;return this.getSenders().forEach(N=>{N.track===R&&(A?O=!0:A=N)}),this.getReceivers().forEach(N=>(N.track===R&&(L?O=!0:L=N),N.track===R)),O||A&&L?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):A?A.getStats():L?L.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}function shimAddTrackRemoveTrackWithNative(T){T.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(O=>this._shimmedLocalStreams[O][0])};const n=T.RTCPeerConnection.prototype.addTrack;T.RTCPeerConnection.prototype.addTrack=function(O,N){if(!N)return n.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const V=n.apply(this,arguments);return this._shimmedLocalStreams[N.id]?this._shimmedLocalStreams[N.id].indexOf(V)===-1&&this._shimmedLocalStreams[N.id].push(V):this._shimmedLocalStreams[N.id]=[N,V],V};const P=T.RTCPeerConnection.prototype.addStream;T.RTCPeerConnection.prototype.addStream=function(O){this._shimmedLocalStreams=this._shimmedLocalStreams||{},O.getTracks().forEach(j=>{if(this.getSenders().find(z=>z.track===j))throw new DOMException("Track already exists.","InvalidAccessError")});const N=this.getSenders();P.apply(this,arguments);const V=this.getSenders().filter(j=>N.indexOf(j)===-1);this._shimmedLocalStreams[O.id]=[O].concat(V)};const R=T.RTCPeerConnection.prototype.removeStream;T.RTCPeerConnection.prototype.removeStream=function(O){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[O.id],R.apply(this,arguments)};const A=T.RTCPeerConnection.prototype.removeTrack;T.RTCPeerConnection.prototype.removeTrack=function(O){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},O&&Object.keys(this._shimmedLocalStreams).forEach(N=>{const V=this._shimmedLocalStreams[N].indexOf(O);V!==-1&&this._shimmedLocalStreams[N].splice(V,1),this._shimmedLocalStreams[N].length===1&&delete this._shimmedLocalStreams[N]}),A.apply(this,arguments)}}function shimAddTrackRemoveTrack(T,n){if(!T.RTCPeerConnection)return;if(T.RTCPeerConnection.prototype.addTrack&&n.version>=65)return shimAddTrackRemoveTrackWithNative(T);const P=T.RTCPeerConnection.prototype.getLocalStreams;T.RTCPeerConnection.prototype.getLocalStreams=function(){const B=P.apply(this);return this._reverseStreams=this._reverseStreams||{},B.map(z=>this._reverseStreams[z.id])};const R=T.RTCPeerConnection.prototype.addStream;T.RTCPeerConnection.prototype.addStream=function(B){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},B.getTracks().forEach(z=>{if(this.getSenders().find(q=>q.track===z))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[B.id]){const z=new T.MediaStream(B.getTracks());this._streams[B.id]=z,this._reverseStreams[z.id]=B,B=z}R.apply(this,[B])};const A=T.RTCPeerConnection.prototype.removeStream;T.RTCPeerConnection.prototype.removeStream=function(B){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},A.apply(this,[this._streams[B.id]||B]),delete this._reverseStreams[this._streams[B.id]?this._streams[B.id].id:B.id],delete this._streams[B.id]},T.RTCPeerConnection.prototype.addTrack=function(B,z){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const W=[].slice.call(arguments,1);if(W.length!==1||!W[0].getTracks().find($=>$===B))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find($=>$.track===B))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const H=this._streams[z.id];if(H)H.addTrack(B),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const $=new T.MediaStream([B]);this._streams[z.id]=$,this._reverseStreams[$.id]=z,this.addStream($)}return this.getSenders().find($=>$.track===B)};function L(j,B){let z=B.sdp;return Object.keys(j._reverseStreams||[]).forEach(W=>{const q=j._reverseStreams[W],H=j._streams[q.id];z=z.replace(new RegExp(H.id,"g"),q.id)}),new RTCSessionDescription({type:B.type,sdp:z})}function O(j,B){let z=B.sdp;return Object.keys(j._reverseStreams||[]).forEach(W=>{const q=j._reverseStreams[W],H=j._streams[q.id];z=z.replace(new RegExp(q.id,"g"),H.id)}),new RTCSessionDescription({type:B.type,sdp:z})}["createOffer","createAnswer"].forEach(function(j){const B=T.RTCPeerConnection.prototype[j],z={[j](){const W=arguments;return arguments.length&&typeof arguments[0]=="function"?B.apply(this,[H=>{const $=L(this,H);W[0].apply(null,[$])},H=>{W[1]&&W[1].apply(null,H)},arguments[2]]):B.apply(this,arguments).then(H=>L(this,H))}};T.RTCPeerConnection.prototype[j]=z[j]});const N=T.RTCPeerConnection.prototype.setLocalDescription;T.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?N.apply(this,arguments):(arguments[0]=O(this,arguments[0]),N.apply(this,arguments))};const V=Object.getOwnPropertyDescriptor(T.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(T.RTCPeerConnection.prototype,"localDescription",{get(){const j=V.get.apply(this);return j.type===""?j:L(this,j)}}),T.RTCPeerConnection.prototype.removeTrack=function(B){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!B._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(B._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let W;Object.keys(this._streams).forEach(q=>{this._streams[q].getTracks().find($=>B.track===$)&&(W=this._streams[q])}),W&&(W.getTracks().length===1?this.removeStream(this._reverseStreams[W.id]):W.removeTrack(B.track),this.dispatchEvent(new Event("negotiationneeded")))}}function shimPeerConnection$1(T,n){!T.RTCPeerConnection&&T.webkitRTCPeerConnection&&(T.RTCPeerConnection=T.webkitRTCPeerConnection),T.RTCPeerConnection&&n.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(P){const R=T.RTCPeerConnection.prototype[P],A={[P](){return arguments[0]=new(P==="addIceCandidate"?T.RTCIceCandidate:T.RTCSessionDescription)(arguments[0]),R.apply(this,arguments)}};T.RTCPeerConnection.prototype[P]=A[P]})}function fixNegotiationNeeded(T,n){wrapPeerConnectionEvent(T,"negotiationneeded",P=>{const R=P.target;if(!((n.version<72||R.getConfiguration&&R.getConfiguration().sdpSemantics==="plan-b")&&R.signalingState!=="stable"))return P})}var chromeShim=Object.freeze({__proto__:null,fixNegotiationNeeded,shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative,shimGetSendersWithDtmf,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats});function shimGetUserMedia$1(T,n){const P=T&&T.navigator,R=T&&T.MediaStreamTrack;if(P.getUserMedia=function(A,L,O){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),P.mediaDevices.getUserMedia(A).then(L,O)},!(n.version>55&&"autoGainControl"in P.mediaDevices.getSupportedConstraints())){const A=function(O,N,V){N in O&&!(V in O)&&(O[V]=O[N],delete O[N])},L=P.mediaDevices.getUserMedia.bind(P.mediaDevices);if(P.mediaDevices.getUserMedia=function(O){return typeof O=="object"&&typeof O.audio=="object"&&(O=JSON.parse(JSON.stringify(O)),A(O.audio,"autoGainControl","mozAutoGainControl"),A(O.audio,"noiseSuppression","mozNoiseSuppression")),L(O)},R&&R.prototype.getSettings){const O=R.prototype.getSettings;R.prototype.getSettings=function(){const N=O.apply(this,arguments);return A(N,"mozAutoGainControl","autoGainControl"),A(N,"mozNoiseSuppression","noiseSuppression"),N}}if(R&&R.prototype.applyConstraints){const O=R.prototype.applyConstraints;R.prototype.applyConstraints=function(N){return this.kind==="audio"&&typeof N=="object"&&(N=JSON.parse(JSON.stringify(N)),A(N,"autoGainControl","mozAutoGainControl"),A(N,"noiseSuppression","mozNoiseSuppression")),O.apply(this,[N])}}}}function shimGetDisplayMedia(T,n){T.navigator.mediaDevices&&"getDisplayMedia"in T.navigator.mediaDevices||T.navigator.mediaDevices&&(T.navigator.mediaDevices.getDisplayMedia=function(R){if(!(R&&R.video)){const A=new DOMException("getDisplayMedia without video constraints is undefined");return A.name="NotFoundError",A.code=8,Promise.reject(A)}return R.video===!0?R.video={mediaSource:n}:R.video.mediaSource=n,T.navigator.mediaDevices.getUserMedia(R)})}function shimOnTrack(T){typeof T=="object"&&T.RTCTrackEvent&&"receiver"in T.RTCTrackEvent.prototype&&!("transceiver"in T.RTCTrackEvent.prototype)&&Object.defineProperty(T.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimPeerConnection(T,n){if(typeof T!="object"||!(T.RTCPeerConnection||T.mozRTCPeerConnection))return;!T.RTCPeerConnection&&T.mozRTCPeerConnection&&(T.RTCPeerConnection=T.mozRTCPeerConnection),n.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(A){const L=T.RTCPeerConnection.prototype[A],O={[A](){return arguments[0]=new(A==="addIceCandidate"?T.RTCIceCandidate:T.RTCSessionDescription)(arguments[0]),L.apply(this,arguments)}};T.RTCPeerConnection.prototype[A]=O[A]});const P={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},R=T.RTCPeerConnection.prototype.getStats;T.RTCPeerConnection.prototype.getStats=function(){const[L,O,N]=arguments;return R.apply(this,[L||null]).then(V=>{if(n.version<53&&!O)try{V.forEach(j=>{j.type=P[j.type]||j.type})}catch(j){if(j.name!=="TypeError")throw j;V.forEach((B,z)=>{V.set(z,Object.assign({},B,{type:P[B.type]||B.type}))})}return V}).then(O,N)}}function shimSenderGetStats(T){if(!(typeof T=="object"&&T.RTCPeerConnection&&T.RTCRtpSender)||T.RTCRtpSender&&"getStats"in T.RTCRtpSender.prototype)return;const n=T.RTCPeerConnection.prototype.getSenders;n&&(T.RTCPeerConnection.prototype.getSenders=function(){const A=n.apply(this,[]);return A.forEach(L=>L._pc=this),A});const P=T.RTCPeerConnection.prototype.addTrack;P&&(T.RTCPeerConnection.prototype.addTrack=function(){const A=P.apply(this,arguments);return A._pc=this,A}),T.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function shimReceiverGetStats(T){if(!(typeof T=="object"&&T.RTCPeerConnection&&T.RTCRtpSender)||T.RTCRtpSender&&"getStats"in T.RTCRtpReceiver.prototype)return;const n=T.RTCPeerConnection.prototype.getReceivers;n&&(T.RTCPeerConnection.prototype.getReceivers=function(){const R=n.apply(this,[]);return R.forEach(A=>A._pc=this),R}),wrapPeerConnectionEvent(T,"track",P=>(P.receiver._pc=P.srcElement,P)),T.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function shimRemoveStream(T){!T.RTCPeerConnection||"removeStream"in T.RTCPeerConnection.prototype||(T.RTCPeerConnection.prototype.removeStream=function(P){deprecated("removeStream","removeTrack"),this.getSenders().forEach(R=>{R.track&&P.getTracks().includes(R.track)&&this.removeTrack(R)})})}function shimRTCDataChannel(T){T.DataChannel&&!T.RTCDataChannel&&(T.RTCDataChannel=T.DataChannel)}function shimAddTransceiver(T){if(!(typeof T=="object"&&T.RTCPeerConnection))return;const n=T.RTCPeerConnection.prototype.addTransceiver;n&&(T.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let R=arguments[1]&&arguments[1].sendEncodings;R===void 0&&(R=[]),R=[...R];const A=R.length>0;A&&R.forEach(O=>{if("rid"in O&&!/^[a-z0-9]{0,16}$/i.test(O.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in O&&!(parseFloat(O.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in O&&!(parseFloat(O.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const L=n.apply(this,arguments);if(A){const{sender:O}=L,N=O.getParameters();(!("encodings"in N)||N.encodings.length===1&&Object.keys(N.encodings[0]).length===0)&&(N.encodings=R,O.sendEncodings=R,this.setParametersPromises.push(O.setParameters(N).then(()=>{delete O.sendEncodings}).catch(()=>{delete O.sendEncodings})))}return L})}function shimGetParameters(T){if(!(typeof T=="object"&&T.RTCRtpSender))return;const n=T.RTCRtpSender.prototype.getParameters;n&&(T.RTCRtpSender.prototype.getParameters=function(){const R=n.apply(this,arguments);return"encodings"in R||(R.encodings=[].concat(this.sendEncodings||[{}])),R})}function shimCreateOffer(T){if(!(typeof T=="object"&&T.RTCPeerConnection))return;const n=T.RTCPeerConnection.prototype.createOffer;T.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function shimCreateAnswer(T){if(!(typeof T=="object"&&T.RTCPeerConnection))return;const n=T.RTCPeerConnection.prototype.createAnswer;T.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}var firefoxShim=Object.freeze({__proto__:null,shimAddTransceiver,shimCreateAnswer,shimCreateOffer,shimGetDisplayMedia,shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack,shimPeerConnection,shimRTCDataChannel,shimReceiverGetStats,shimRemoveStream,shimSenderGetStats});function shimLocalStreamsAPI(T){if(!(typeof T!="object"||!T.RTCPeerConnection)){if("getLocalStreams"in T.RTCPeerConnection.prototype||(T.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in T.RTCPeerConnection.prototype)){const n=T.RTCPeerConnection.prototype.addTrack;T.RTCPeerConnection.prototype.addStream=function(R){this._localStreams||(this._localStreams=[]),this._localStreams.includes(R)||this._localStreams.push(R),R.getAudioTracks().forEach(A=>n.call(this,A,R)),R.getVideoTracks().forEach(A=>n.call(this,A,R))},T.RTCPeerConnection.prototype.addTrack=function(R){for(var A=arguments.length,L=new Array(A>1?A-1:0),O=1;O<A;O++)L[O-1]=arguments[O];return L&&L.forEach(N=>{this._localStreams?this._localStreams.includes(N)||this._localStreams.push(N):this._localStreams=[N]}),n.apply(this,arguments)}}"removeStream"in T.RTCPeerConnection.prototype||(T.RTCPeerConnection.prototype.removeStream=function(P){this._localStreams||(this._localStreams=[]);const R=this._localStreams.indexOf(P);if(R===-1)return;this._localStreams.splice(R,1);const A=P.getTracks();this.getSenders().forEach(L=>{A.includes(L.track)&&this.removeTrack(L)})})}}function shimRemoteStreamsAPI(T){if(!(typeof T!="object"||!T.RTCPeerConnection)&&("getRemoteStreams"in T.RTCPeerConnection.prototype||(T.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in T.RTCPeerConnection.prototype))){Object.defineProperty(T.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(P){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=P),this.addEventListener("track",this._onaddstreampoly=R=>{R.streams.forEach(A=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(A))return;this._remoteStreams.push(A);const L=new Event("addstream");L.stream=A,this.dispatchEvent(L)})})}});const n=T.RTCPeerConnection.prototype.setRemoteDescription;T.RTCPeerConnection.prototype.setRemoteDescription=function(){const R=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(A){A.streams.forEach(L=>{if(R._remoteStreams||(R._remoteStreams=[]),R._remoteStreams.indexOf(L)>=0)return;R._remoteStreams.push(L);const O=new Event("addstream");O.stream=L,R.dispatchEvent(O)})}),n.apply(R,arguments)}}}function shimCallbacksAPI(T){if(typeof T!="object"||!T.RTCPeerConnection)return;const n=T.RTCPeerConnection.prototype,P=n.createOffer,R=n.createAnswer,A=n.setLocalDescription,L=n.setRemoteDescription,O=n.addIceCandidate;n.createOffer=function(j,B){const z=arguments.length>=2?arguments[2]:arguments[0],W=P.apply(this,[z]);return B?(W.then(j,B),Promise.resolve()):W},n.createAnswer=function(j,B){const z=arguments.length>=2?arguments[2]:arguments[0],W=R.apply(this,[z]);return B?(W.then(j,B),Promise.resolve()):W};let N=function(V,j,B){const z=A.apply(this,[V]);return B?(z.then(j,B),Promise.resolve()):z};n.setLocalDescription=N,N=function(V,j,B){const z=L.apply(this,[V]);return B?(z.then(j,B),Promise.resolve()):z},n.setRemoteDescription=N,N=function(V,j,B){const z=O.apply(this,[V]);return B?(z.then(j,B),Promise.resolve()):z},n.addIceCandidate=N}function shimGetUserMedia(T){const n=T&&T.navigator;if(n.mediaDevices&&n.mediaDevices.getUserMedia){const P=n.mediaDevices,R=P.getUserMedia.bind(P);n.mediaDevices.getUserMedia=A=>R(shimConstraints(A))}!n.getUserMedia&&n.mediaDevices&&n.mediaDevices.getUserMedia&&(n.getUserMedia=(function(R,A,L){n.mediaDevices.getUserMedia(R).then(A,L)}).bind(n))}function shimConstraints(T){return T&&T.video!==void 0?Object.assign({},T,{video:compactObject(T.video)}):T}function shimRTCIceServerUrls(T){if(!T.RTCPeerConnection)return;const n=T.RTCPeerConnection;T.RTCPeerConnection=function(R,A){if(R&&R.iceServers){const L=[];for(let O=0;O<R.iceServers.length;O++){let N=R.iceServers[O];N.urls===void 0&&N.url?(deprecated("RTCIceServer.url","RTCIceServer.urls"),N=JSON.parse(JSON.stringify(N)),N.urls=N.url,delete N.url,L.push(N)):L.push(R.iceServers[O])}R.iceServers=L}return new n(R,A)},T.RTCPeerConnection.prototype=n.prototype,"generateCertificate"in n&&Object.defineProperty(T.RTCPeerConnection,"generateCertificate",{get(){return n.generateCertificate}})}function shimTrackEventTransceiver(T){typeof T=="object"&&T.RTCTrackEvent&&"receiver"in T.RTCTrackEvent.prototype&&!("transceiver"in T.RTCTrackEvent.prototype)&&Object.defineProperty(T.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(T){const n=T.RTCPeerConnection.prototype.createOffer;T.RTCPeerConnection.prototype.createOffer=function(R){if(R){typeof R.offerToReceiveAudio<"u"&&(R.offerToReceiveAudio=!!R.offerToReceiveAudio);const A=this.getTransceivers().find(O=>O.receiver.track.kind==="audio");R.offerToReceiveAudio===!1&&A?A.direction==="sendrecv"?A.setDirection?A.setDirection("sendonly"):A.direction="sendonly":A.direction==="recvonly"&&(A.setDirection?A.setDirection("inactive"):A.direction="inactive"):R.offerToReceiveAudio===!0&&!A&&this.addTransceiver("audio",{direction:"recvonly"}),typeof R.offerToReceiveVideo<"u"&&(R.offerToReceiveVideo=!!R.offerToReceiveVideo);const L=this.getTransceivers().find(O=>O.receiver.track.kind==="video");R.offerToReceiveVideo===!1&&L?L.direction==="sendrecv"?L.setDirection?L.setDirection("sendonly"):L.direction="sendonly":L.direction==="recvonly"&&(L.setDirection?L.setDirection("inactive"):L.direction="inactive"):R.offerToReceiveVideo===!0&&!L&&this.addTransceiver("video",{direction:"recvonly"})}return n.apply(this,arguments)}}function shimAudioContext(T){typeof T!="object"||T.AudioContext||(T.AudioContext=T.webkitAudioContext)}var safariShim=Object.freeze({__proto__:null,shimAudioContext,shimCallbacksAPI,shimConstraints,shimCreateOfferLegacy,shimGetUserMedia,shimLocalStreamsAPI,shimRTCIceServerUrls,shimRemoteStreamsAPI,shimTrackEventTransceiver}),sdp$1={exports:{}},hasRequiredSdp;function requireSdp(){return hasRequiredSdp||(hasRequiredSdp=1,(function(T){const n={};n.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},n.localCName=n.generateIdentifier(),n.splitLines=function(P){return P.trim().split(`
|
|
494
|
+
`).map(R=>R.trim())},n.splitSections=function(P){return P.split(`
|
|
495
|
+
m=`).map((A,L)=>(L>0?"m="+A:A).trim()+`\r
|
|
496
|
+
`)},n.getDescription=function(P){const R=n.splitSections(P);return R&&R[0]},n.getMediaSections=function(P){const R=n.splitSections(P);return R.shift(),R},n.matchPrefix=function(P,R){return n.splitLines(P).filter(A=>A.indexOf(R)===0)},n.parseCandidate=function(P){let R;P.indexOf("a=candidate:")===0?R=P.substring(12).split(" "):R=P.substring(10).split(" ");const A={foundation:R[0],component:{1:"rtp",2:"rtcp"}[R[1]]||R[1],protocol:R[2].toLowerCase(),priority:parseInt(R[3],10),ip:R[4],address:R[4],port:parseInt(R[5],10),type:R[7]};for(let L=8;L<R.length;L+=2)switch(R[L]){case"raddr":A.relatedAddress=R[L+1];break;case"rport":A.relatedPort=parseInt(R[L+1],10);break;case"tcptype":A.tcpType=R[L+1];break;case"ufrag":A.ufrag=R[L+1],A.usernameFragment=R[L+1];break;default:A[R[L]]===void 0&&(A[R[L]]=R[L+1]);break}return A},n.writeCandidate=function(P){const R=[];R.push(P.foundation);const A=P.component;A==="rtp"?R.push(1):A==="rtcp"?R.push(2):R.push(A),R.push(P.protocol.toUpperCase()),R.push(P.priority),R.push(P.address||P.ip),R.push(P.port);const L=P.type;return R.push("typ"),R.push(L),L!=="host"&&P.relatedAddress&&P.relatedPort&&(R.push("raddr"),R.push(P.relatedAddress),R.push("rport"),R.push(P.relatedPort)),P.tcpType&&P.protocol.toLowerCase()==="tcp"&&(R.push("tcptype"),R.push(P.tcpType)),(P.usernameFragment||P.ufrag)&&(R.push("ufrag"),R.push(P.usernameFragment||P.ufrag)),"candidate:"+R.join(" ")},n.parseIceOptions=function(P){return P.substring(14).split(" ")},n.parseRtpMap=function(P){let R=P.substring(9).split(" ");const A={payloadType:parseInt(R.shift(),10)};return R=R[0].split("/"),A.name=R[0],A.clockRate=parseInt(R[1],10),A.channels=R.length===3?parseInt(R[2],10):1,A.numChannels=A.channels,A},n.writeRtpMap=function(P){let R=P.payloadType;P.preferredPayloadType!==void 0&&(R=P.preferredPayloadType);const A=P.channels||P.numChannels||1;return"a=rtpmap:"+R+" "+P.name+"/"+P.clockRate+(A!==1?"/"+A:"")+`\r
|
|
497
|
+
`},n.parseExtmap=function(P){const R=P.substring(9).split(" ");return{id:parseInt(R[0],10),direction:R[0].indexOf("/")>0?R[0].split("/")[1]:"sendrecv",uri:R[1],attributes:R.slice(2).join(" ")}},n.writeExtmap=function(P){return"a=extmap:"+(P.id||P.preferredId)+(P.direction&&P.direction!=="sendrecv"?"/"+P.direction:"")+" "+P.uri+(P.attributes?" "+P.attributes:"")+`\r
|
|
498
|
+
`},n.parseFmtp=function(P){const R={};let A;const L=P.substring(P.indexOf(" ")+1).split(";");for(let O=0;O<L.length;O++)A=L[O].trim().split("="),R[A[0].trim()]=A[1];return R},n.writeFmtp=function(P){let R="",A=P.payloadType;if(P.preferredPayloadType!==void 0&&(A=P.preferredPayloadType),P.parameters&&Object.keys(P.parameters).length){const L=[];Object.keys(P.parameters).forEach(O=>{P.parameters[O]!==void 0?L.push(O+"="+P.parameters[O]):L.push(O)}),R+="a=fmtp:"+A+" "+L.join(";")+`\r
|
|
499
|
+
`}return R},n.parseRtcpFb=function(P){const R=P.substring(P.indexOf(" ")+1).split(" ");return{type:R.shift(),parameter:R.join(" ")}},n.writeRtcpFb=function(P){let R="",A=P.payloadType;return P.preferredPayloadType!==void 0&&(A=P.preferredPayloadType),P.rtcpFeedback&&P.rtcpFeedback.length&&P.rtcpFeedback.forEach(L=>{R+="a=rtcp-fb:"+A+" "+L.type+(L.parameter&&L.parameter.length?" "+L.parameter:"")+`\r
|
|
500
|
+
`}),R},n.parseSsrcMedia=function(P){const R=P.indexOf(" "),A={ssrc:parseInt(P.substring(7,R),10)},L=P.indexOf(":",R);return L>-1?(A.attribute=P.substring(R+1,L),A.value=P.substring(L+1)):A.attribute=P.substring(R+1),A},n.parseSsrcGroup=function(P){const R=P.substring(13).split(" ");return{semantics:R.shift(),ssrcs:R.map(A=>parseInt(A,10))}},n.getMid=function(P){const R=n.matchPrefix(P,"a=mid:")[0];if(R)return R.substring(6)},n.parseFingerprint=function(P){const R=P.substring(14).split(" ");return{algorithm:R[0].toLowerCase(),value:R[1].toUpperCase()}},n.getDtlsParameters=function(P,R){return{role:"auto",fingerprints:n.matchPrefix(P+R,"a=fingerprint:").map(n.parseFingerprint)}},n.writeDtlsParameters=function(P,R){let A="a=setup:"+R+`\r
|
|
501
|
+
`;return P.fingerprints.forEach(L=>{A+="a=fingerprint:"+L.algorithm+" "+L.value+`\r
|
|
502
|
+
`}),A},n.parseCryptoLine=function(P){const R=P.substring(9).split(" ");return{tag:parseInt(R[0],10),cryptoSuite:R[1],keyParams:R[2],sessionParams:R.slice(3)}},n.writeCryptoLine=function(P){return"a=crypto:"+P.tag+" "+P.cryptoSuite+" "+(typeof P.keyParams=="object"?n.writeCryptoKeyParams(P.keyParams):P.keyParams)+(P.sessionParams?" "+P.sessionParams.join(" "):"")+`\r
|
|
503
|
+
`},n.parseCryptoKeyParams=function(P){if(P.indexOf("inline:")!==0)return null;const R=P.substring(7).split("|");return{keyMethod:"inline",keySalt:R[0],lifeTime:R[1],mkiValue:R[2]?R[2].split(":")[0]:void 0,mkiLength:R[2]?R[2].split(":")[1]:void 0}},n.writeCryptoKeyParams=function(P){return P.keyMethod+":"+P.keySalt+(P.lifeTime?"|"+P.lifeTime:"")+(P.mkiValue&&P.mkiLength?"|"+P.mkiValue+":"+P.mkiLength:"")},n.getCryptoParameters=function(P,R){return n.matchPrefix(P+R,"a=crypto:").map(n.parseCryptoLine)},n.getIceParameters=function(P,R){const A=n.matchPrefix(P+R,"a=ice-ufrag:")[0],L=n.matchPrefix(P+R,"a=ice-pwd:")[0];return A&&L?{usernameFragment:A.substring(12),password:L.substring(10)}:null},n.writeIceParameters=function(P){let R="a=ice-ufrag:"+P.usernameFragment+`\r
|
|
504
|
+
a=ice-pwd:`+P.password+`\r
|
|
505
|
+
`;return P.iceLite&&(R+=`a=ice-lite\r
|
|
506
|
+
`),R},n.parseRtpParameters=function(P){const R={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},L=n.splitLines(P)[0].split(" ");R.profile=L[2];for(let N=3;N<L.length;N++){const V=L[N],j=n.matchPrefix(P,"a=rtpmap:"+V+" ")[0];if(j){const B=n.parseRtpMap(j),z=n.matchPrefix(P,"a=fmtp:"+V+" ");switch(B.parameters=z.length?n.parseFmtp(z[0]):{},B.rtcpFeedback=n.matchPrefix(P,"a=rtcp-fb:"+V+" ").map(n.parseRtcpFb),R.codecs.push(B),B.name.toUpperCase()){case"RED":case"ULPFEC":R.fecMechanisms.push(B.name.toUpperCase());break}}}n.matchPrefix(P,"a=extmap:").forEach(N=>{R.headerExtensions.push(n.parseExtmap(N))});const O=n.matchPrefix(P,"a=rtcp-fb:* ").map(n.parseRtcpFb);return R.codecs.forEach(N=>{O.forEach(V=>{N.rtcpFeedback.find(B=>B.type===V.type&&B.parameter===V.parameter)||N.rtcpFeedback.push(V)})}),R},n.writeRtpDescription=function(P,R){let A="";A+="m="+P+" ",A+=R.codecs.length>0?"9":"0",A+=" "+(R.profile||"UDP/TLS/RTP/SAVPF")+" ",A+=R.codecs.map(O=>O.preferredPayloadType!==void 0?O.preferredPayloadType:O.payloadType).join(" ")+`\r
|
|
507
|
+
`,A+=`c=IN IP4 0.0.0.0\r
|
|
508
|
+
`,A+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
509
|
+
`,R.codecs.forEach(O=>{A+=n.writeRtpMap(O),A+=n.writeFmtp(O),A+=n.writeRtcpFb(O)});let L=0;return R.codecs.forEach(O=>{O.maxptime>L&&(L=O.maxptime)}),L>0&&(A+="a=maxptime:"+L+`\r
|
|
510
|
+
`),R.headerExtensions&&R.headerExtensions.forEach(O=>{A+=n.writeExtmap(O)}),A},n.parseRtpEncodingParameters=function(P){const R=[],A=n.parseRtpParameters(P),L=A.fecMechanisms.indexOf("RED")!==-1,O=A.fecMechanisms.indexOf("ULPFEC")!==-1,N=n.matchPrefix(P,"a=ssrc:").map(W=>n.parseSsrcMedia(W)).filter(W=>W.attribute==="cname"),V=N.length>0&&N[0].ssrc;let j;const B=n.matchPrefix(P,"a=ssrc-group:FID").map(W=>W.substring(17).split(" ").map(H=>parseInt(H,10)));B.length>0&&B[0].length>1&&B[0][0]===V&&(j=B[0][1]),A.codecs.forEach(W=>{if(W.name.toUpperCase()==="RTX"&&W.parameters.apt){let q={ssrc:V,codecPayloadType:parseInt(W.parameters.apt,10)};V&&j&&(q.rtx={ssrc:j}),R.push(q),L&&(q=JSON.parse(JSON.stringify(q)),q.fec={ssrc:V,mechanism:O?"red+ulpfec":"red"},R.push(q))}}),R.length===0&&V&&R.push({ssrc:V});let z=n.matchPrefix(P,"b=");return z.length&&(z[0].indexOf("b=TIAS:")===0?z=parseInt(z[0].substring(7),10):z[0].indexOf("b=AS:")===0?z=parseInt(z[0].substring(5),10)*1e3*.95-2e3*8:z=void 0,R.forEach(W=>{W.maxBitrate=z})),R},n.parseRtcpParameters=function(P){const R={},A=n.matchPrefix(P,"a=ssrc:").map(N=>n.parseSsrcMedia(N)).filter(N=>N.attribute==="cname")[0];A&&(R.cname=A.value,R.ssrc=A.ssrc);const L=n.matchPrefix(P,"a=rtcp-rsize");R.reducedSize=L.length>0,R.compound=L.length===0;const O=n.matchPrefix(P,"a=rtcp-mux");return R.mux=O.length>0,R},n.writeRtcpParameters=function(P){let R="";return P.reducedSize&&(R+=`a=rtcp-rsize\r
|
|
511
|
+
`),P.mux&&(R+=`a=rtcp-mux\r
|
|
512
|
+
`),P.ssrc!==void 0&&P.cname&&(R+="a=ssrc:"+P.ssrc+" cname:"+P.cname+`\r
|
|
513
|
+
`),R},n.parseMsid=function(P){let R;const A=n.matchPrefix(P,"a=msid:");if(A.length===1)return R=A[0].substring(7).split(" "),{stream:R[0],track:R[1]};const L=n.matchPrefix(P,"a=ssrc:").map(O=>n.parseSsrcMedia(O)).filter(O=>O.attribute==="msid");if(L.length>0)return R=L[0].value.split(" "),{stream:R[0],track:R[1]}},n.parseSctpDescription=function(P){const R=n.parseMLine(P),A=n.matchPrefix(P,"a=max-message-size:");let L;A.length>0&&(L=parseInt(A[0].substring(19),10)),isNaN(L)&&(L=65536);const O=n.matchPrefix(P,"a=sctp-port:");if(O.length>0)return{port:parseInt(O[0].substring(12),10),protocol:R.fmt,maxMessageSize:L};const N=n.matchPrefix(P,"a=sctpmap:");if(N.length>0){const V=N[0].substring(10).split(" ");return{port:parseInt(V[0],10),protocol:V[1],maxMessageSize:L}}},n.writeSctpDescription=function(P,R){let A=[];return P.protocol!=="DTLS/SCTP"?A=["m="+P.kind+" 9 "+P.protocol+" "+R.protocol+`\r
|
|
514
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
515
|
+
`,"a=sctp-port:"+R.port+`\r
|
|
516
|
+
`]:A=["m="+P.kind+" 9 "+P.protocol+" "+R.port+`\r
|
|
517
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
518
|
+
`,"a=sctpmap:"+R.port+" "+R.protocol+` 65535\r
|
|
519
|
+
`],R.maxMessageSize!==void 0&&A.push("a=max-message-size:"+R.maxMessageSize+`\r
|
|
520
|
+
`),A.join("")},n.generateSessionId=function(){return Math.random().toString().substr(2,22)},n.writeSessionBoilerplate=function(P,R,A){let L;const O=R!==void 0?R:2;return P?L=P:L=n.generateSessionId(),`v=0\r
|
|
521
|
+
o=`+(A||"thisisadapterortc")+" "+L+" "+O+` IN IP4 127.0.0.1\r
|
|
522
|
+
s=-\r
|
|
523
|
+
t=0 0\r
|
|
524
|
+
`},n.getDirection=function(P,R){const A=n.splitLines(P);for(let L=0;L<A.length;L++)switch(A[L]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return A[L].substring(2)}return R?n.getDirection(R):"sendrecv"},n.getKind=function(P){return n.splitLines(P)[0].split(" ")[0].substring(2)},n.isRejected=function(P){return P.split(" ",2)[1]==="0"},n.parseMLine=function(P){const A=n.splitLines(P)[0].substring(2).split(" ");return{kind:A[0],port:parseInt(A[1],10),protocol:A[2],fmt:A.slice(3).join(" ")}},n.parseOLine=function(P){const A=n.matchPrefix(P,"o=")[0].substring(2).split(" ");return{username:A[0],sessionId:A[1],sessionVersion:parseInt(A[2],10),netType:A[3],addressType:A[4],address:A[5]}},n.isValidSDP=function(P){if(typeof P!="string"||P.length===0)return!1;const R=n.splitLines(P);for(let A=0;A<R.length;A++)if(R[A].length<2||R[A].charAt(1)!=="=")return!1;return!0},T.exports=n})(sdp$1)),sdp$1.exports}var sdpExports=requireSdp(),SDPUtils=getDefaultExportFromCjs(sdpExports),sdp=_mergeNamespaces$1({__proto__:null,default:SDPUtils},[sdpExports]);function shimRTCIceCandidate(T){if(!T.RTCIceCandidate||T.RTCIceCandidate&&"foundation"in T.RTCIceCandidate.prototype)return;const n=T.RTCIceCandidate;T.RTCIceCandidate=function(R){if(typeof R=="object"&&R.candidate&&R.candidate.indexOf("a=")===0&&(R=JSON.parse(JSON.stringify(R)),R.candidate=R.candidate.substring(2)),R.candidate&&R.candidate.length){const A=new n(R),L=SDPUtils.parseCandidate(R.candidate);for(const O in L)O in A||Object.defineProperty(A,O,{value:L[O]});return A.toJSON=function(){return{candidate:A.candidate,sdpMid:A.sdpMid,sdpMLineIndex:A.sdpMLineIndex,usernameFragment:A.usernameFragment}},A}return new n(R)},T.RTCIceCandidate.prototype=n.prototype,wrapPeerConnectionEvent(T,"icecandidate",P=>(P.candidate&&Object.defineProperty(P,"candidate",{value:new T.RTCIceCandidate(P.candidate),writable:"false"}),P))}function shimRTCIceCandidateRelayProtocol(T){!T.RTCIceCandidate||T.RTCIceCandidate&&"relayProtocol"in T.RTCIceCandidate.prototype||wrapPeerConnectionEvent(T,"icecandidate",n=>{if(n.candidate){const P=SDPUtils.parseCandidate(n.candidate.candidate);P.type==="relay"&&(n.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[P.priority>>24])}return n})}function shimMaxMessageSize(T,n){if(!T.RTCPeerConnection)return;"sctp"in T.RTCPeerConnection.prototype||Object.defineProperty(T.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const P=function(N){if(!N||!N.sdp)return!1;const V=SDPUtils.splitSections(N.sdp);return V.shift(),V.some(j=>{const B=SDPUtils.parseMLine(j);return B&&B.kind==="application"&&B.protocol.indexOf("SCTP")!==-1})},R=function(N){const V=N.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(V===null||V.length<2)return-1;const j=parseInt(V[1],10);return j!==j?-1:j},A=function(N){let V=65536;return n.browser==="firefox"&&(n.version<57?N===-1?V=16384:V=2147483637:n.version<60?V=n.version===57?65535:65536:V=2147483637),V},L=function(N,V){let j=65536;n.browser==="firefox"&&n.version===57&&(j=65535);const B=SDPUtils.matchPrefix(N.sdp,"a=max-message-size:");return B.length>0?j=parseInt(B[0].substring(19),10):n.browser==="firefox"&&V!==-1&&(j=2147483637),j},O=T.RTCPeerConnection.prototype.setRemoteDescription;T.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,n.browser==="chrome"&&n.version>=76){const{sdpSemantics:V}=this.getConfiguration();V==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(P(arguments[0])){const V=R(arguments[0]),j=A(V),B=L(arguments[0],V);let z;j===0&&B===0?z=Number.POSITIVE_INFINITY:j===0||B===0?z=Math.max(j,B):z=Math.min(j,B);const W={};Object.defineProperty(W,"maxMessageSize",{get(){return z}}),this._sctp=W}return O.apply(this,arguments)}}function shimSendThrowTypeError(T){if(!(T.RTCPeerConnection&&"createDataChannel"in T.RTCPeerConnection.prototype))return;function n(R,A){const L=R.send;R.send=function(){const N=arguments[0],V=N.length||N.size||N.byteLength;if(R.readyState==="open"&&A.sctp&&V>A.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+A.sctp.maxMessageSize+" bytes)");return L.apply(R,arguments)}}const P=T.RTCPeerConnection.prototype.createDataChannel;T.RTCPeerConnection.prototype.createDataChannel=function(){const A=P.apply(this,arguments);return n(A,this),A},wrapPeerConnectionEvent(T,"datachannel",R=>(n(R.channel,R.target),R))}function shimConnectionState(T){if(!T.RTCPeerConnection||"connectionState"in T.RTCPeerConnection.prototype)return;const n=T.RTCPeerConnection.prototype;Object.defineProperty(n,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(n,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(P){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),P&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=P)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(P=>{const R=n[P];n[P]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=A=>{const L=A.target;if(L._lastConnectionState!==L.connectionState){L._lastConnectionState=L.connectionState;const O=new Event("connectionstatechange",A);L.dispatchEvent(O)}return A},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),R.apply(this,arguments)}})}function removeExtmapAllowMixed(T,n){if(!T.RTCPeerConnection||n.browser==="chrome"&&n.version>=71||n.browser==="safari"&&n._safariVersion>=13.1)return;const P=T.RTCPeerConnection.prototype.setRemoteDescription;T.RTCPeerConnection.prototype.setRemoteDescription=function(A){if(A&&A.sdp&&A.sdp.indexOf(`
|
|
525
|
+
a=extmap-allow-mixed`)!==-1){const L=A.sdp.split(`
|
|
526
|
+
`).filter(O=>O.trim()!=="a=extmap-allow-mixed").join(`
|
|
527
|
+
`);T.RTCSessionDescription&&A instanceof T.RTCSessionDescription?arguments[0]=new T.RTCSessionDescription({type:A.type,sdp:L}):A.sdp=L}return P.apply(this,arguments)}}function shimAddIceCandidateNullOrEmpty(T,n){if(!(T.RTCPeerConnection&&T.RTCPeerConnection.prototype))return;const P=T.RTCPeerConnection.prototype.addIceCandidate;!P||P.length===0||(T.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(n.browser==="chrome"&&n.version<78||n.browser==="firefox"&&n.version<68||n.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():P.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function shimParameterlessSetLocalDescription(T,n){if(!(T.RTCPeerConnection&&T.RTCPeerConnection.prototype))return;const P=T.RTCPeerConnection.prototype.setLocalDescription;!P||P.length===0||(T.RTCPeerConnection.prototype.setLocalDescription=function(){let A=arguments[0]||{};if(typeof A!="object"||A.type&&A.sdp)return P.apply(this,arguments);if(A={type:A.type,sdp:A.sdp},!A.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":A.type="offer";break;default:A.type="answer";break}return A.sdp||A.type!=="offer"&&A.type!=="answer"?P.apply(this,[A]):(A.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(O=>P.apply(this,[O]))})}var commonShim=Object.freeze({__proto__:null,removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty,shimConnectionState,shimMaxMessageSize,shimParameterlessSetLocalDescription,shimRTCIceCandidate,shimRTCIceCandidateRelayProtocol,shimSendThrowTypeError});function adapterFactory(){let{window:T}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const P=log,R=detectBrowser(T),A={browserDetails:R,commonShim,extractVersion,disableLog,disableWarnings,sdp};switch(R.browser){case"chrome":if(!chromeShim||!shimPeerConnection$1||!n.shimChrome)return P("Chrome shim is not included in this adapter release."),A;if(R.version===null)return P("Chrome shim can not determine version, not shimming."),A;P("adapter.js shimming chrome."),A.browserShim=chromeShim,shimAddIceCandidateNullOrEmpty(T,R),shimParameterlessSetLocalDescription(T),shimGetUserMedia$2(T,R),shimMediaStream(T),shimPeerConnection$1(T,R),shimOnTrack$1(T),shimAddTrackRemoveTrack(T,R),shimGetSendersWithDtmf(T),shimSenderReceiverGetStats(T),fixNegotiationNeeded(T,R),shimRTCIceCandidate(T),shimRTCIceCandidateRelayProtocol(T),shimConnectionState(T),shimMaxMessageSize(T,R),shimSendThrowTypeError(T),removeExtmapAllowMixed(T,R);break;case"firefox":if(!firefoxShim||!shimPeerConnection||!n.shimFirefox)return P("Firefox shim is not included in this adapter release."),A;P("adapter.js shimming firefox."),A.browserShim=firefoxShim,shimAddIceCandidateNullOrEmpty(T,R),shimParameterlessSetLocalDescription(T),shimGetUserMedia$1(T,R),shimPeerConnection(T,R),shimOnTrack(T),shimRemoveStream(T),shimSenderGetStats(T),shimReceiverGetStats(T),shimRTCDataChannel(T),shimAddTransceiver(T),shimGetParameters(T),shimCreateOffer(T),shimCreateAnswer(T),shimRTCIceCandidate(T),shimConnectionState(T),shimMaxMessageSize(T,R),shimSendThrowTypeError(T);break;case"safari":if(!safariShim||!n.shimSafari)return P("Safari shim is not included in this adapter release."),A;P("adapter.js shimming safari."),A.browserShim=safariShim,shimAddIceCandidateNullOrEmpty(T,R),shimParameterlessSetLocalDescription(T),shimRTCIceServerUrls(T),shimCreateOfferLegacy(T),shimCallbacksAPI(T),shimLocalStreamsAPI(T),shimRemoteStreamsAPI(T),shimTrackEventTransceiver(T),shimGetUserMedia(T),shimAudioContext(T),shimRTCIceCandidate(T),shimRTCIceCandidateRelayProtocol(T),shimMaxMessageSize(T,R),shimSendThrowTypeError(T),removeExtmapAllowMixed(T,R);break;default:P("Unsupported browser!");break}return A}adapterFactory({window:typeof window>"u"?void 0:window});const DECRYPTION_FAILURE_TOLERANCE=10,E2EE_FLAG="lk_e2ee",SALT="LKFrameEncryptionKey",KEY_PROVIDER_DEFAULTS={sharedKey:!1,ratchetSalt:SALT,ratchetWindowSize:8,failureTolerance:DECRYPTION_FAILURE_TOLERANCE,keyringSize:16};var KeyProviderEvent;(function(T){T.SetKey="setKey",T.RatchetRequest="ratchetRequest",T.KeyRatcheted="keyRatcheted"})(KeyProviderEvent||(KeyProviderEvent={}));var KeyHandlerEvent;(function(T){T.KeyRatcheted="keyRatcheted"})(KeyHandlerEvent||(KeyHandlerEvent={}));var EncryptionEvent;(function(T){T.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",T.EncryptionError="encryptionError"})(EncryptionEvent||(EncryptionEvent={}));var CryptorEvent;(function(T){T.Error="cryptorError"})(CryptorEvent||(CryptorEvent={}));function isE2EESupported(){return isInsertableStreamSupported()||isScriptTransformSupported()}function isScriptTransformSupported(){return typeof window.RTCRtpScriptTransform<"u"}function isInsertableStreamSupported(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class BaseKeyProvider extends eventsExports.EventEmitter{constructor(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(P,R,A)=>{livekitLogger.debug("key ratcheted event received",{ratchetResult:P,participantId:R,keyIndex:A})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},KEY_PROVIDER_DEFAULTS),n),this.on(KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(n,P,R){const A={key:n,participantIdentity:P,keyIndex:R};if(!this.options.sharedKey&&!P)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(P??"shared","-").concat(R??0),A),this.emit(KeyProviderEvent.SetKey,A)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(n,P){this.emit(KeyProviderEvent.RatchetRequest,n,P)}}class LivekitError extends Error{constructor(n,P){super(P||"an error has occured"),this.name="LiveKitError",this.code=n}}var ConnectionErrorReason;(function(T){T[T.NotAllowed=0]="NotAllowed",T[T.ServerUnreachable=1]="ServerUnreachable",T[T.InternalError=2]="InternalError",T[T.Cancelled=3]="Cancelled",T[T.LeaveRequest=4]="LeaveRequest",T[T.Timeout=5]="Timeout"})(ConnectionErrorReason||(ConnectionErrorReason={}));class ConnectionError extends LivekitError{constructor(n,P,R,A){super(1,n),this.name="ConnectionError",this.status=R,this.reason=P,this.context=A,this.reasonName=ConnectionErrorReason[P]}}class DeviceUnsupportedError extends LivekitError{constructor(n){super(21,n??"device is unsupported"),this.name="DeviceUnsupportedError"}}class TrackInvalidError extends LivekitError{constructor(n){super(20,n??"track is invalid"),this.name="TrackInvalidError"}}class UnsupportedServer extends LivekitError{constructor(n){super(10,n??"unsupported server"),this.name="UnsupportedServer"}}class UnexpectedConnectionState extends LivekitError{constructor(n){super(12,n??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class NegotiationError extends LivekitError{constructor(n){super(13,n??"unable to negotiate"),this.name="NegotiationError"}}class PublishTrackError extends LivekitError{constructor(n,P){super(15,n),this.name="PublishTrackError",this.status=P}}class SignalRequestError extends LivekitError{constructor(n,P){super(15,n),this.reason=P,this.reasonName=typeof P=="string"?P:RequestResponse_Reason[P]}}var DataStreamErrorReason;(function(T){T[T.AlreadyOpened=0]="AlreadyOpened",T[T.AbnormalEnd=1]="AbnormalEnd",T[T.DecodeFailed=2]="DecodeFailed",T[T.LengthExceeded=3]="LengthExceeded",T[T.Incomplete=4]="Incomplete",T[T.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"})(DataStreamErrorReason||(DataStreamErrorReason={}));class DataStreamError extends LivekitError{constructor(n,P){super(16,n),this.name="DataStreamError",this.reason=P,this.reasonName=DataStreamErrorReason[P]}}var MediaDeviceFailure;(function(T){T.PermissionDenied="PermissionDenied",T.NotFound="NotFound",T.DeviceInUse="DeviceInUse",T.Other="Other"})(MediaDeviceFailure||(MediaDeviceFailure={}));(function(T){function n(P){if(P&&"name"in P)return P.name==="NotFoundError"||P.name==="DevicesNotFoundError"?T.NotFound:P.name==="NotAllowedError"||P.name==="PermissionDeniedError"?T.PermissionDenied:P.name==="NotReadableError"||P.name==="TrackStartError"?T.DeviceInUse:T.Other}T.getFailure=n})(MediaDeviceFailure||(MediaDeviceFailure={}));var CryptorErrorReason;(function(T){T[T.InvalidKey=0]="InvalidKey",T[T.MissingKey=1]="MissingKey",T[T.InternalError=2]="InternalError"})(CryptorErrorReason||(CryptorErrorReason={}));var RoomEvent;(function(T){T.Connected="connected",T.Reconnecting="reconnecting",T.SignalReconnecting="signalReconnecting",T.Reconnected="reconnected",T.Disconnected="disconnected",T.ConnectionStateChanged="connectionStateChanged",T.Moved="moved",T.MediaDevicesChanged="mediaDevicesChanged",T.ParticipantConnected="participantConnected",T.ParticipantDisconnected="participantDisconnected",T.TrackPublished="trackPublished",T.TrackSubscribed="trackSubscribed",T.TrackSubscriptionFailed="trackSubscriptionFailed",T.TrackUnpublished="trackUnpublished",T.TrackUnsubscribed="trackUnsubscribed",T.TrackMuted="trackMuted",T.TrackUnmuted="trackUnmuted",T.LocalTrackPublished="localTrackPublished",T.LocalTrackUnpublished="localTrackUnpublished",T.LocalAudioSilenceDetected="localAudioSilenceDetected",T.ActiveSpeakersChanged="activeSpeakersChanged",T.ParticipantMetadataChanged="participantMetadataChanged",T.ParticipantNameChanged="participantNameChanged",T.ParticipantAttributesChanged="participantAttributesChanged",T.ParticipantActive="participantActive",T.RoomMetadataChanged="roomMetadataChanged",T.DataReceived="dataReceived",T.SipDTMFReceived="sipDTMFReceived",T.TranscriptionReceived="transcriptionReceived",T.ConnectionQualityChanged="connectionQualityChanged",T.TrackStreamStateChanged="trackStreamStateChanged",T.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",T.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",T.AudioPlaybackStatusChanged="audioPlaybackChanged",T.VideoPlaybackStatusChanged="videoPlaybackChanged",T.MediaDevicesError="mediaDevicesError",T.ParticipantPermissionsChanged="participantPermissionsChanged",T.SignalConnected="signalConnected",T.RecordingStatusChanged="recordingStatusChanged",T.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",T.EncryptionError="encryptionError",T.DCBufferStatusChanged="dcBufferStatusChanged",T.ActiveDeviceChanged="activeDeviceChanged",T.ChatMessage="chatMessage",T.LocalTrackSubscribed="localTrackSubscribed",T.MetricsReceived="metricsReceived"})(RoomEvent||(RoomEvent={}));var ParticipantEvent;(function(T){T.TrackPublished="trackPublished",T.TrackSubscribed="trackSubscribed",T.TrackSubscriptionFailed="trackSubscriptionFailed",T.TrackUnpublished="trackUnpublished",T.TrackUnsubscribed="trackUnsubscribed",T.TrackMuted="trackMuted",T.TrackUnmuted="trackUnmuted",T.LocalTrackPublished="localTrackPublished",T.LocalTrackUnpublished="localTrackUnpublished",T.LocalTrackCpuConstrained="localTrackCpuConstrained",T.LocalSenderCreated="localSenderCreated",T.ParticipantMetadataChanged="participantMetadataChanged",T.ParticipantNameChanged="participantNameChanged",T.DataReceived="dataReceived",T.SipDTMFReceived="sipDTMFReceived",T.TranscriptionReceived="transcriptionReceived",T.IsSpeakingChanged="isSpeakingChanged",T.ConnectionQualityChanged="connectionQualityChanged",T.TrackStreamStateChanged="trackStreamStateChanged",T.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",T.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",T.TrackCpuConstrained="trackCpuConstrained",T.MediaDevicesError="mediaDevicesError",T.AudioStreamAcquired="audioStreamAcquired",T.ParticipantPermissionsChanged="participantPermissionsChanged",T.PCTrackAdded="pcTrackAdded",T.AttributesChanged="attributesChanged",T.LocalTrackSubscribed="localTrackSubscribed",T.ChatMessage="chatMessage",T.Active="active"})(ParticipantEvent||(ParticipantEvent={}));var EngineEvent;(function(T){T.TransportsCreated="transportsCreated",T.Connected="connected",T.Disconnected="disconnected",T.Resuming="resuming",T.Resumed="resumed",T.Restarting="restarting",T.Restarted="restarted",T.SignalResumed="signalResumed",T.SignalRestarted="signalRestarted",T.Closing="closing",T.MediaTrackAdded="mediaTrackAdded",T.ActiveSpeakersUpdate="activeSpeakersUpdate",T.DataPacketReceived="dataPacketReceived",T.RTPVideoMapUpdate="rtpVideoMapUpdate",T.DCBufferStatusChanged="dcBufferStatusChanged",T.ParticipantUpdate="participantUpdate",T.RoomUpdate="roomUpdate",T.SpeakersChanged="speakersChanged",T.StreamStateChanged="streamStateChanged",T.ConnectionQualityUpdate="connectionQualityUpdate",T.SubscriptionError="subscriptionError",T.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",T.RemoteMute="remoteMute",T.SubscribedQualityUpdate="subscribedQualityUpdate",T.LocalTrackUnpublished="localTrackUnpublished",T.LocalTrackSubscribed="localTrackSubscribed",T.Offline="offline",T.SignalRequestResponse="signalRequestResponse",T.SignalConnected="signalConnected",T.RoomMoved="roomMoved"})(EngineEvent||(EngineEvent={}));var TrackEvent;(function(T){T.Message="message",T.Muted="muted",T.Unmuted="unmuted",T.Restarted="restarted",T.Ended="ended",T.Subscribed="subscribed",T.Unsubscribed="unsubscribed",T.CpuConstrained="cpuConstrained",T.UpdateSettings="updateSettings",T.UpdateSubscription="updateSubscription",T.AudioPlaybackStarted="audioPlaybackStarted",T.AudioPlaybackFailed="audioPlaybackFailed",T.AudioSilenceDetected="audioSilenceDetected",T.VisibilityChanged="visibilityChanged",T.VideoDimensionsChanged="videoDimensionsChanged",T.VideoPlaybackStarted="videoPlaybackStarted",T.VideoPlaybackFailed="videoPlaybackFailed",T.ElementAttached="elementAttached",T.ElementDetached="elementDetached",T.UpstreamPaused="upstreamPaused",T.UpstreamResumed="upstreamResumed",T.SubscriptionPermissionChanged="subscriptionPermissionChanged",T.SubscriptionStatusChanged="subscriptionStatusChanged",T.SubscriptionFailed="subscriptionFailed",T.TrackProcessorUpdate="trackProcessorUpdate",T.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",T.TranscriptionReceived="transcriptionReceived",T.TimeSyncUpdate="timeSyncUpdate",T.PreConnectBufferFlushed="preConnectBufferFlushed"})(TrackEvent||(TrackEvent={}));function cloneDeep(T){return typeof T>"u"?T:typeof structuredClone=="function"?typeof T=="object"&&T!==null?structuredClone(Object.assign({},T)):structuredClone(T):JSON.parse(JSON.stringify(T))}const commonVersionIdentifier=/version\/(\d+(\.?_?\d+)+)/i;let browserDetails;function getBrowser(T){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const P=navigator.userAgent.toLowerCase();if(browserDetails===void 0||n){const R=browsersList.find(A=>{let{test:L}=A;return L.test(P)});browserDetails=R?.describe(P)}return browserDetails}const browsersList=[{test:/firefox|iceweasel|fxios/i,describe(T){return{name:"Firefox",version:getMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,T),os:T.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:getOSVersion(T)}}},{test:/chrom|crios|crmo/i,describe(T){return{name:"Chrome",version:getMatch(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,T),os:T.toLowerCase().includes("crios")?"iOS":void 0,osVersion:getOSVersion(T)}}},{test:/safari|applewebkit/i,describe(T){return{name:"Safari",version:getMatch(commonVersionIdentifier,T),os:T.includes("mobile/")?"iOS":"macOS",osVersion:getOSVersion(T)}}}];function getMatch(T,n){let P=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const R=n.match(T);return R&&R.length>=P&&R[P]||""}function getOSVersion(T){return T.includes("mac os")?getMatch(/\(.+?(\d+_\d+(:?_\d+)?)/,T,1).replace(/_/g,"."):void 0}var version$1="2.15.7";const version=version$1,protocolVersion=16;class CriticalTimers{}CriticalTimers.setTimeout=function(){return setTimeout(...arguments)};CriticalTimers.setInterval=function(){return setInterval(...arguments)};CriticalTimers.clearTimeout=function(){return clearTimeout(...arguments)};CriticalTimers.clearInterval=function(){return clearInterval(...arguments)};const BACKGROUND_REACTION_DELAY=5e3,recycledElements=[];var VideoQuality;(function(T){T[T.LOW=0]="LOW",T[T.MEDIUM=1]="MEDIUM",T[T.HIGH=2]="HIGH"})(VideoQuality||(VideoQuality={}));class Track extends eventsExports.EventEmitter{get streamState(){return this._streamState}setStreamState(n){this._streamState=n}constructor(n,P){let R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var A;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Track.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=livekitLogger,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),BACKGROUND_REACTION_DELAY):this.handleAppVisibilityChanged()},this.log=getLogger((A=R.loggerName)!==null&&A!==void 0?A:LoggerNames.Track),this.loggerContextCb=R.loggerContextCb,this.setMaxListeners(100),this.kind=P,this._mediaStreamTrack=n,this._mediaStreamID=n.id,this.source=Track.Source.Unknown}get logContext(){var n;return Object.assign(Object.assign({},(n=this.loggerContextCb)===null||n===void 0?void 0:n.call(this)),getLogContextFromTrack(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(n){let P="audio";this.kind===Track.Kind.Video&&(P="video"),this.attachedElements.length===0&&this.kind===Track.Kind.Video&&this.addAppVisibilityListener(),n||(P==="audio"&&(recycledElements.forEach(L=>{L.parentElement===null&&!n&&(n=L)}),n&&recycledElements.splice(recycledElements.indexOf(n),1)),n||(n=document.createElement(P))),this.attachedElements.includes(n)||this.attachedElements.push(n),attachToElement(this.mediaStreamTrack,n);const R=n.srcObject.getTracks(),A=R.some(L=>L.kind==="audio");return n.play().then(()=>{this.emit(A?TrackEvent.AudioPlaybackStarted:TrackEvent.VideoPlaybackStarted)}).catch(L=>{L.name==="NotAllowedError"?this.emit(A?TrackEvent.AudioPlaybackFailed:TrackEvent.VideoPlaybackFailed,L):L.name==="AbortError"?livekitLogger.debug("".concat(A?"audio":"video"," playback aborted, likely due to new play request")):livekitLogger.warn("could not playback ".concat(A?"audio":"video"),L),A&&n&&R.some(O=>O.kind==="video")&&L.name==="NotAllowedError"&&(n.muted=!0,n.play().catch(()=>{}))}),this.emit(TrackEvent.ElementAttached,n),n}detach(n){try{if(n){detachTrack(this.mediaStreamTrack,n);const R=this.attachedElements.indexOf(n);return R>=0&&(this.attachedElements.splice(R,1),this.recycleElement(n),this.emit(TrackEvent.ElementDetached,n)),n}const P=[];return this.attachedElements.forEach(R=>{detachTrack(this.mediaStreamTrack,R),P.push(R),this.recycleElement(R),this.emit(TrackEvent.ElementDetached,R)}),this.attachedElements=[],P}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(n){n.loggerName&&(this.log=getLogger(n.loggerName)),n.loggerContextCb&&(this.loggerContextCb=n.loggerContextCb)}recycleElement(n){if(n instanceof HTMLAudioElement){let P=!0;n.pause(),recycledElements.forEach(R=>{R.parentElement||(P=!1)}),P&&recycledElements.push(n)}}handleAppVisibilityChanged(){return __awaiter(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Track.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(n=>n.play().catch(()=>{})),0)})}addAppVisibilityListener(){isWeb()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){isWeb()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function attachToElement(T,n){let P;n.srcObject instanceof MediaStream?P=n.srcObject:P=new MediaStream;let R;T.kind==="audio"?R=P.getAudioTracks():R=P.getVideoTracks(),R.includes(T)||(R.forEach(A=>{P.removeTrack(A)}),P.addTrack(T)),(!isSafari()||!(n instanceof HTMLVideoElement))&&(n.autoplay=!0),n.muted=P.getAudioTracks().length===0,n instanceof HTMLVideoElement&&(n.playsInline=!0),n.srcObject!==P&&(n.srcObject=P,(isSafari()||isFireFox())&&n instanceof HTMLVideoElement&&setTimeout(()=>{n.srcObject=P,n.play().catch(()=>{})},0))}function detachTrack(T,n){if(n.srcObject instanceof MediaStream){const P=n.srcObject;P.removeTrack(T),P.getTracks().length>0?n.srcObject=P:n.srcObject=null}}(function(T){let n;(function(j){j.Audio="audio",j.Video="video",j.Unknown="unknown"})(n=T.Kind||(T.Kind={}));let P;(function(j){j.Camera="camera",j.Microphone="microphone",j.ScreenShare="screen_share",j.ScreenShareAudio="screen_share_audio",j.Unknown="unknown"})(P=T.Source||(T.Source={}));let R;(function(j){j.Active="active",j.Paused="paused",j.Unknown="unknown"})(R=T.StreamState||(T.StreamState={}));function A(j){switch(j){case n.Audio:return TrackType.AUDIO;case n.Video:return TrackType.VIDEO;default:return TrackType.DATA}}T.kindToProto=A;function L(j){switch(j){case TrackType.AUDIO:return n.Audio;case TrackType.VIDEO:return n.Video;default:return n.Unknown}}T.kindFromProto=L;function O(j){switch(j){case P.Camera:return TrackSource.CAMERA;case P.Microphone:return TrackSource.MICROPHONE;case P.ScreenShare:return TrackSource.SCREEN_SHARE;case P.ScreenShareAudio:return TrackSource.SCREEN_SHARE_AUDIO;default:return TrackSource.UNKNOWN}}T.sourceToProto=O;function N(j){switch(j){case TrackSource.CAMERA:return P.Camera;case TrackSource.MICROPHONE:return P.Microphone;case TrackSource.SCREEN_SHARE:return P.ScreenShare;case TrackSource.SCREEN_SHARE_AUDIO:return P.ScreenShareAudio;default:return P.Unknown}}T.sourceFromProto=N;function V(j){switch(j){case StreamState.ACTIVE:return R.Active;case StreamState.PAUSED:return R.Paused;default:return R.Unknown}}T.streamStateFromProto=V})(Track||(Track={}));class VideoPreset{constructor(n,P,R,A,L){if(typeof n=="object")this.width=n.width,this.height=n.height,this.aspectRatio=n.aspectRatio,this.encoding={maxBitrate:n.maxBitrate,maxFramerate:n.maxFramerate,priority:n.priority};else if(P!==void 0&&R!==void 0)this.width=n,this.height=P,this.aspectRatio=n/P,this.encoding={maxBitrate:R,maxFramerate:A,priority:L};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const backupCodecs=["vp8","h264"],videoCodecs=["vp8","h264","vp9","av1","h265"];function isBackupCodec(T){return!!backupCodecs.find(n=>n===T)}var BackupCodecPolicy;(function(T){T[T.PREFER_REGRESSION=0]="PREFER_REGRESSION",T[T.SIMULCAST=1]="SIMULCAST",T[T.REGRESSION=2]="REGRESSION"})(BackupCodecPolicy||(BackupCodecPolicy={}));var AudioPresets;(function(T){T.telephone={maxBitrate:12e3},T.speech={maxBitrate:24e3},T.music={maxBitrate:48e3},T.musicStereo={maxBitrate:64e3},T.musicHighQuality={maxBitrate:96e3},T.musicHighQualityStereo={maxBitrate:128e3}})(AudioPresets||(AudioPresets={}));const VideoPresets={h90:new VideoPreset(160,90,9e4,20),h180:new VideoPreset(320,180,16e4,20),h216:new VideoPreset(384,216,18e4,20),h360:new VideoPreset(640,360,45e4,20),h540:new VideoPreset(960,540,8e5,25),h720:new VideoPreset(1280,720,17e5,30),h1080:new VideoPreset(1920,1080,3e6,30),h1440:new VideoPreset(2560,1440,5e6,30),h2160:new VideoPreset(3840,2160,8e6,30)},VideoPresets43={h120:new VideoPreset(160,120,7e4,20),h180:new VideoPreset(240,180,125e3,20),h240:new VideoPreset(320,240,14e4,20),h360:new VideoPreset(480,360,33e4,20),h480:new VideoPreset(640,480,5e5,20),h540:new VideoPreset(720,540,6e5,25),h720:new VideoPreset(960,720,13e5,30),h1080:new VideoPreset(1440,1080,23e5,30),h1440:new VideoPreset(1920,1440,38e5,30)},ScreenSharePresets={h360fps3:new VideoPreset(640,360,2e5,3,"medium"),h360fps15:new VideoPreset(640,360,4e5,15,"medium"),h720fps5:new VideoPreset(1280,720,8e5,5,"medium"),h720fps15:new VideoPreset(1280,720,15e5,15,"medium"),h720fps30:new VideoPreset(1280,720,2e6,30,"medium"),h1080fps15:new VideoPreset(1920,1080,25e5,15,"medium"),h1080fps30:new VideoPreset(1920,1080,5e6,30,"medium"),original:new VideoPreset(0,0,7e6,30,"medium")},separator="|",ddExtensionURI="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function unpackStreamId(T){const n=T.split(separator);return n.length>1?[n[0],T.substr(n[0].length+1)]:[T,""]}function sleep(T){return __awaiter(this,void 0,void 0,function*(){return new Promise(n=>CriticalTimers.setTimeout(n,T))})}function supportsTransceiver(){return"addTransceiver"in RTCPeerConnection.prototype}function supportsAddTrack(){return"addTrack"in RTCPeerConnection.prototype}function supportsAV1(){if(!("getCapabilities"in RTCRtpSender)||isSafari()||isFireFox())return!1;const T=RTCRtpSender.getCapabilities("video");let n=!1;if(T){for(const P of T.codecs)if(P.mimeType==="video/AV1"){n=!0;break}}return n}function supportsVP9(){if(!("getCapabilities"in RTCRtpSender)||isFireFox())return!1;if(isSafari()){const P=getBrowser();if(P?.version&&compareVersions(P.version,"16")<0||P?.os==="iOS"&&P?.osVersion&&compareVersions(P.osVersion,"16")<0)return!1}const T=RTCRtpSender.getCapabilities("video");let n=!1;if(T){for(const P of T.codecs)if(P.mimeType==="video/VP9"){n=!0;break}}return n}function isSVCCodec(T){return T==="av1"||T==="vp9"}function supportsSetSinkId(T){return!document||isSafariBased()?!1:(T||(T=document.createElement("audio")),"setSinkId"in T)}function isBrowserSupported(){return typeof RTCPeerConnection>"u"?!1:supportsTransceiver()||supportsAddTrack()}function isFireFox(){var T;return((T=getBrowser())===null||T===void 0?void 0:T.name)==="Firefox"}function isSafari(){var T;return((T=getBrowser())===null||T===void 0?void 0:T.name)==="Safari"}function isSafariBased(){const T=getBrowser();return T?.name==="Safari"||T?.os==="iOS"}function isSafari17Based(){const T=getBrowser();return T?.name==="Safari"&&T.version.startsWith("17.")||T?.os==="iOS"&&!!T?.osVersion&&compareVersions(T.osVersion,"17")>=0}function isSafariSvcApi(T){return T||(T=getBrowser()),T?.name==="Safari"&&compareVersions(T.version,"18.3")>0||T?.os==="iOS"&&!!T?.osVersion&&compareVersions(T.osVersion,"18.3")>0}function isMobile(){var T,n;return isWeb()?(n=(T=navigator.userAgentData)===null||T===void 0?void 0:T.mobile)!==null&&n!==void 0?n:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function isE2EESimulcastSupported(){const T=getBrowser(),n="17.2";if(T)return T.name!=="Safari"&&T.os!=="iOS"||T.os==="iOS"&&T.osVersion&&compareVersions(T.osVersion,n)>=0?!0:T.name==="Safari"&&compareVersions(T.version,n)>=0}function isWeb(){return typeof document<"u"}function isReactNative$1(){return navigator.product=="ReactNative"}function isCloud(T){return T.hostname.endsWith(".livekit.cloud")||T.hostname.endsWith(".livekit.run")}function getLKReactNativeInfo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function getReactNativeOs(){if(!isReactNative$1())return;let T=getLKReactNativeInfo();if(T)return T.platform}function getDevicePixelRatio(){if(isWeb())return window.devicePixelRatio;if(isReactNative$1()){let T=getLKReactNativeInfo();if(T)return T.devicePixelRatio}return 1}function compareVersions(T,n){const P=T.split("."),R=n.split("."),A=Math.min(P.length,R.length);for(let L=0;L<A;++L){const O=parseInt(P[L],10),N=parseInt(R[L],10);if(O>N)return 1;if(O<N)return-1;if(L===A-1&&O===N)return 0}return T===""&&n!==""?-1:n===""?1:P.length==R.length?0:P.length<R.length?-1:1}function roDispatchCallback(T){for(const n of T)n.target.handleResize(n)}function ioDispatchCallback(T){for(const n of T)n.target.handleVisibilityChanged(n)}let resizeObserver=null;const getResizeObserver=()=>(resizeObserver||(resizeObserver=new ResizeObserver(roDispatchCallback)),resizeObserver);let intersectionObserver=null;const getIntersectionObserver=()=>(intersectionObserver||(intersectionObserver=new IntersectionObserver(ioDispatchCallback,{root:null,rootMargin:"0px"})),intersectionObserver);function getClientInfo(){var T;const n=new ClientInfo({sdk:ClientInfo_SDK.JS,protocol:protocolVersion,version});return isReactNative$1()&&(n.os=(T=getReactNativeOs())!==null&&T!==void 0?T:""),n}function createDummyVideoStreamTrack(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,P=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,R=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const A=document.createElement("canvas");A.width=T,A.height=n;const L=A.getContext("2d");L?.fillRect(0,0,A.width,A.height),R&&L&&(L.beginPath(),L.arc(T/2,n/2,50,0,Math.PI*2,!0),L.closePath(),L.fillStyle="grey",L.fill());const O=A.captureStream(),[N]=O.getTracks();if(!N)throw Error("Could not get empty media stream video track");return N.enabled=P,N}let emptyAudioStreamTrack;function getEmptyAudioStreamTrack(){if(!emptyAudioStreamTrack){const T=new AudioContext,n=T.createOscillator(),P=T.createGain();P.gain.setValueAtTime(0,0);const R=T.createMediaStreamDestination();if(n.connect(P),P.connect(R),n.start(),[emptyAudioStreamTrack]=R.stream.getAudioTracks(),!emptyAudioStreamTrack)throw Error("Could not get empty media stream audio track");emptyAudioStreamTrack.enabled=!1}return emptyAudioStreamTrack.clone()}class Future{get isResolved(){return this._isResolved}constructor(n,P){this._isResolved=!1,this.onFinally=P,this.promise=new Promise((R,A)=>__awaiter(this,void 0,void 0,function*(){this.resolve=R,this.reject=A,n&&(yield n(R,A))})).finally(()=>{var R;this._isResolved=!0,(R=this.onFinally)===null||R===void 0||R.call(this)})}}function isVideoCodec(T){return videoCodecs.includes(T)}function unwrapConstraint(T){if(typeof T=="string"||typeof T=="number")return T;if(Array.isArray(T))return T[0];if(T.exact!==void 0)return Array.isArray(T.exact)?T.exact[0]:T.exact;if(T.ideal!==void 0)return Array.isArray(T.ideal)?T.ideal[0]:T.ideal;throw Error("could not unwrap constraint")}function toWebsocketUrl(T){return T.startsWith("http")?T.replace(/^(http)/,"ws"):T}function toHttpUrl(T){return T.startsWith("ws")?T.replace(/^(ws)/,"http"):T}function extractTranscriptionSegments(T,n){return T.segments.map(P=>{let{id:R,text:A,language:L,startTime:O,endTime:N,final:V}=P;var j;const B=(j=n.get(R))!==null&&j!==void 0?j:Date.now(),z=Date.now();return V?n.delete(R):n.set(R,B),{id:R,text:A,startTime:Number.parseInt(O.toString()),endTime:Number.parseInt(N.toString()),final:V,language:L,firstReceivedTime:B,lastReceivedTime:z}})}function extractChatMessage(T){const{id:n,timestamp:P,message:R,editTimestamp:A}=T;return{id:n,timestamp:Number.parseInt(P.toString()),editTimestamp:A?Number.parseInt(A.toString()):void 0,message:R}}function getDisconnectReasonFromConnectionError(T){switch(T.reason){case ConnectionErrorReason.LeaveRequest:return T.context;case ConnectionErrorReason.Cancelled:return DisconnectReason.CLIENT_INITIATED;case ConnectionErrorReason.NotAllowed:return DisconnectReason.USER_REJECTED;case ConnectionErrorReason.ServerUnreachable:return DisconnectReason.JOIN_FAILURE;default:return DisconnectReason.UNKNOWN_REASON}}function bigIntToNumber(T){return T!==void 0?Number(T):void 0}function numberToBigInt(T){return T!==void 0?BigInt(T):void 0}function isLocalTrack(T){return!!T&&!(T instanceof MediaStreamTrack)&&T.isLocal}function isAudioTrack(T){return!!T&&T.kind==Track.Kind.Audio}function isVideoTrack(T){return!!T&&T.kind==Track.Kind.Video}function isLocalVideoTrack(T){return isLocalTrack(T)&&isVideoTrack(T)}function isLocalAudioTrack(T){return isLocalTrack(T)&&isAudioTrack(T)}function isRemoteTrack(T){return!!T&&!T.isLocal}function isRemotePub(T){return!!T&&!T.isLocal}function isRemoteVideoTrack(T){return isRemoteTrack(T)&&isVideoTrack(T)}function isLocalParticipant(T){return T.isLocal}function splitUtf8(T,n){const P=[];let R=new TextEncoder().encode(T);for(;R.length>n;){let A=n;for(;A>0;){const L=R[A];if(L!==void 0&&(L&192)!==128)break;A--}P.push(R.slice(0,A)),R=R.slice(A)}return R.length>0&&P.push(R),P}function mergeDefaultOptions(T,n,P){var R,A,L,O;const{optionsWithoutProcessor:N,audioProcessor:V,videoProcessor:j}=extractProcessorsFromOptions(T??{}),B=n?.processor,z=P?.processor,W=N??{};return W.audio===!0&&(W.audio={}),W.video===!0&&(W.video={}),W.audio&&(mergeObjectWithoutOverwriting(W.audio,n),(R=(L=W.audio).deviceId)!==null&&R!==void 0||(L.deviceId={ideal:"default"}),(V||B)&&(W.audio.processor=V??B)),W.video&&(mergeObjectWithoutOverwriting(W.video,P),(A=(O=W.video).deviceId)!==null&&A!==void 0||(O.deviceId={ideal:"default"}),(j||z)&&(W.video.processor=j??z)),W}function mergeObjectWithoutOverwriting(T,n){return Object.keys(n).forEach(P=>{T[P]===void 0&&(T[P]=n[P])}),T}function constraintsForOptions(T){var n,P,R,A;const L={};if(T.video)if(typeof T.video=="object"){const O={},N=O,V=T.video;Object.keys(V).forEach(j=>{switch(j){case"resolution":mergeObjectWithoutOverwriting(N,V.resolution);break;default:N[j]=V[j]}}),L.video=O,(n=(R=L.video).deviceId)!==null&&n!==void 0||(R.deviceId={ideal:"default"})}else L.video=T.video?{deviceId:{ideal:"default"}}:!1;else L.video=!1;return T.audio?typeof T.audio=="object"?(L.audio=T.audio,(P=(A=L.audio).deviceId)!==null&&P!==void 0||(A.deviceId={ideal:"default"})):L.audio={deviceId:{ideal:"default"}}:L.audio=!1,L}function detectSilence(T){return __awaiter(this,arguments,void 0,function(n){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const R=getNewAudioContext();if(R){const A=R.createAnalyser();A.fftSize=2048;const L=A.frequencyBinCount,O=new Uint8Array(L);R.createMediaStreamSource(new MediaStream([n.mediaStreamTrack])).connect(A),yield sleep(P),A.getByteTimeDomainData(O);const V=O.some(j=>j!==128&&j!==0);return R.close(),!V}return!1})()})}function getNewAudioContext(){var T;const n=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(n){const P=new n({latencyHint:"interactive"});if(P.state==="suspended"&&typeof window<"u"&&(!((T=window.document)===null||T===void 0)&&T.body)){const R=()=>__awaiter(this,void 0,void 0,function*(){var A;try{P.state==="suspended"&&(yield P.resume())}catch(L){console.warn("Error trying to auto-resume audio context",L)}(A=window.document.body)===null||A===void 0||A.removeEventListener("click",R)});window.document.body.addEventListener("click",R)}return P}}function kindToSource(T){return T==="audioinput"?Track.Source.Microphone:T==="videoinput"?Track.Source.Camera:Track.Source.Unknown}function sourceToKind(T){return T===Track.Source.Microphone?"audioinput":T===Track.Source.Camera?"videoinput":void 0}function screenCaptureToDisplayMediaStreamOptions(T){var n,P;let R=(n=T.video)!==null&&n!==void 0?n:!0;return T.resolution&&T.resolution.width>0&&T.resolution.height>0&&(R=typeof R=="boolean"?{}:R,isSafari()?R=Object.assign(Object.assign({},R),{width:{max:T.resolution.width},height:{max:T.resolution.height},frameRate:T.resolution.frameRate}):R=Object.assign(Object.assign({},R),{width:{ideal:T.resolution.width},height:{ideal:T.resolution.height},frameRate:T.resolution.frameRate})),{audio:(P=T.audio)!==null&&P!==void 0?P:!1,video:R,controller:T.controller,selfBrowserSurface:T.selfBrowserSurface,surfaceSwitching:T.surfaceSwitching,systemAudio:T.systemAudio,preferCurrentTab:T.preferCurrentTab}}function mimeTypeToVideoCodecString(T){return T.split("/")[1].toLowerCase()}function getTrackPublicationInfo(T){const n=[];return T.forEach(P=>{P.track!==void 0&&n.push(new TrackPublishedResponse({cid:P.track.mediaStreamID,track:P.trackInfo}))}),n}function getLogContextFromTrack(T){return"mediaStreamTrack"in T?{trackID:T.sid,source:T.source,muted:T.isMuted,enabled:T.mediaStreamTrack.enabled,kind:T.kind,streamID:T.mediaStreamID,streamTrackID:T.mediaStreamTrack.id}:{trackID:T.trackSid,enabled:T.isEnabled,muted:T.isMuted,trackInfo:Object.assign({mimeType:T.mimeType,name:T.trackName,encrypted:T.isEncrypted,kind:T.kind,source:T.source},T.track?getLogContextFromTrack(T.track):{})}}function supportsSynchronizationSources(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function diffAttributes(T,n){var P;T===void 0&&(T={}),n===void 0&&(n={});const R=[...Object.keys(n),...Object.keys(T)],A={};for(const L of R)T[L]!==n[L]&&(A[L]=(P=n[L])!==null&&P!==void 0?P:"");return A}function extractProcessorsFromOptions(T){const n=Object.assign({},T);let P,R;return typeof n.audio=="object"&&n.audio.processor&&(P=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),typeof n.video=="object"&&n.video.processor&&(R=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:P,videoProcessor:R,optionsWithoutProcessor:cloneDeep(n)}}function getTrackSourceFromProto(T){switch(T){case TrackSource.CAMERA:return Track.Source.Camera;case TrackSource.MICROPHONE:return Track.Source.Microphone;case TrackSource.SCREEN_SHARE:return Track.Source.ScreenShare;case TrackSource.SCREEN_SHARE_AUDIO:return Track.Source.ScreenShareAudio;default:return Track.Source.Unknown}}function areDimensionsSmaller(T,n){return T.width*T.height<n.width*n.height}function layerDimensionsFor(T,n){var P;return(P=T.layers)===null||P===void 0?void 0:P.find(R=>R.quality===n)}class E2EEManager extends eventsExports.EventEmitter{constructor(n){super(),this.onWorkerMessage=P=>{var R,A;const{kind:L,data:O}=P.data;switch(L){case"error":livekitLogger.error(O.error.message),this.emit(EncryptionEvent.EncryptionError,O.error);break;case"initAck":O.enabled&&this.keyProvider.getKeys().forEach(N=>{this.postKey(N)});break;case"enable":if(O.enabled&&this.keyProvider.getKeys().forEach(N=>{this.postKey(N)}),this.encryptionEnabled!==O.enabled&&O.participantIdentity===((R=this.room)===null||R===void 0?void 0:R.localParticipant.identity))this.emit(EncryptionEvent.ParticipantEncryptionStatusChanged,O.enabled,this.room.localParticipant),this.encryptionEnabled=O.enabled;else if(O.participantIdentity){const N=(A=this.room)===null||A===void 0?void 0:A.getParticipantByIdentity(O.participantIdentity);if(!N)throw TypeError("couldn't set encryption status, participant not found".concat(O.participantIdentity));this.emit(EncryptionEvent.ParticipantEncryptionStatusChanged,O.enabled,N)}break;case"ratchetKey":this.keyProvider.emit(KeyProviderEvent.KeyRatcheted,O.ratchetResult,O.participantIdentity,O.keyIndex);break}},this.onWorkerError=P=>{livekitLogger.error("e2ee worker encountered an error:",{error:P.error}),this.emit(EncryptionEvent.EncryptionError,P.error)},this.keyProvider=n.keyProvider,this.worker=n.worker,this.encryptionEnabled=!1}setup(n){if(!isE2EESupported())throw new DeviceUnsupportedError("tried to setup end-to-end encryption on an unsupported browser");if(livekitLogger.info("setting up e2ee"),n!==this.room){this.room=n,this.setupEventListeners(n,this.keyProvider);const P={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:workerLogger.getLevel()}};this.worker&&(livekitLogger.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(P))}}setParticipantCryptorEnabled(n,P){livekitLogger.debug("set e2ee to ".concat(n," for participant ").concat(P)),this.postEnable(n,P)}setSifTrailer(n){!n||n.length===0?livekitLogger.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(n)}setupEngine(n){n.on(EngineEvent.RTPVideoMapUpdate,P=>{this.postRTPMap(P)})}setupEventListeners(n,P){n.on(RoomEvent.TrackPublished,(R,A)=>this.setParticipantCryptorEnabled(R.trackInfo.encryption!==Encryption_Type.NONE,A.identity)),n.on(RoomEvent.ConnectionStateChanged,R=>{R===ConnectionState.Connected&&n.remoteParticipants.forEach(A=>{A.trackPublications.forEach(L=>{this.setParticipantCryptorEnabled(L.trackInfo.encryption!==Encryption_Type.NONE,A.identity)})})}).on(RoomEvent.TrackUnsubscribed,(R,A,L)=>{var O;const N={kind:"removeTransform",data:{participantIdentity:L.identity,trackId:R.mediaStreamID}};(O=this.worker)===null||O===void 0||O.postMessage(N)}).on(RoomEvent.TrackSubscribed,(R,A,L)=>{this.setupE2EEReceiver(R,L.identity,A.trackInfo)}).on(RoomEvent.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");P.getKeys().forEach(R=>{this.postKey(R)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),n.localParticipant.on(ParticipantEvent.LocalSenderCreated,(R,A)=>__awaiter(this,void 0,void 0,function*(){this.setupE2EESender(A,R)})),n.localParticipant.on(ParticipantEvent.LocalTrackPublished,R=>{if(!isVideoTrack(R.track)||!isSafariBased())return;const A={kind:"updateCodec",data:{trackId:R.track.mediaStreamID,codec:mimeTypeToVideoCodecString(R.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(A)}),P.on(KeyProviderEvent.SetKey,R=>this.postKey(R)).on(KeyProviderEvent.RatchetRequest,(R,A)=>this.postRatchetRequest(R,A))}postRatchetRequest(n,P){if(!this.worker)throw Error("could not ratchet key, worker is missing");const R={kind:"ratchetRequest",data:{participantIdentity:n,keyIndex:P}};this.worker.postMessage(R)}postKey(n){let{key:P,participantIdentity:R,keyIndex:A}=n;var L;if(!this.worker)throw Error("could not set key, worker is missing");const O={kind:"setKey",data:{participantIdentity:R,isPublisher:R===((L=this.room)===null||L===void 0?void 0:L.localParticipant.identity),key:P,keyIndex:A}};this.worker.postMessage(O)}postEnable(n,P){if(this.worker){const R={kind:"enable",data:{enabled:n,participantIdentity:P}};this.worker.postMessage(R)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(n){var P;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((P=this.room)===null||P===void 0)&&P.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const R={kind:"setRTPMap",data:{map:n,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(R)}postSifTrailer(n){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const P={kind:"setSifTrailer",data:{trailer:n}};this.worker.postMessage(P)}setupE2EEReceiver(n,P,R){if(n.receiver){if(!R?.mimeType||R.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(n.receiver,n.mediaStreamID,P,n.kind==="video"?mimeTypeToVideoCodecString(R.mimeType):void 0)}}setupE2EESender(n,P){if(!isLocalTrack(n)||!P){P||livekitLogger.warn("early return because sender is not ready");return}this.handleSender(P,n.mediaStreamID,void 0)}handleReceiver(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){if(this.worker){if(isScriptTransformSupported()){const L={kind:"decode",participantIdentity:R,trackId:P,codec:A};n.transform=new RTCRtpScriptTransform(this.worker,L)}else{if(E2EE_FLAG in n&&A){const V={kind:"updateCodec",data:{trackId:P,codec:A,participantIdentity:R}};this.worker.postMessage(V);return}let L=n.writableStream,O=n.readableStream;if(!L||!O){const V=n.createEncodedStreams();n.writableStream=V.writable,L=V.writable,n.readableStream=V.readable,O=V.readable}const N={kind:"decode",data:{readableStream:O,writableStream:L,trackId:P,codec:A,participantIdentity:R,isReuse:E2EE_FLAG in n}};this.worker.postMessage(N,[O,L])}n[E2EE_FLAG]=!0}})}handleSender(n,P,R){var A;if(!(E2EE_FLAG in n||!this.worker)){if(!(!((A=this.room)===null||A===void 0)&&A.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(isScriptTransformSupported()){livekitLogger.info("initialize script transform");const L={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:P,codec:R};n.transform=new RTCRtpScriptTransform(this.worker,L)}else{livekitLogger.info("initialize encoded streams");const L=n.createEncodedStreams(),O={kind:"encode",data:{readableStream:L.readable,writableStream:L.writable,codec:R,trackId:P,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(O,[L.readable,L.writable])}n[E2EE_FLAG]=!0}}}const defaultId="default";class DeviceManager{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new DeviceManager),this.instance}get previousDevices(){return this._previousDevices}getDevices(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var L;if(((L=DeviceManager.userMediaPromiseMap)===null||L===void 0?void 0:L.size)>0){livekitLogger.debug("awaiting getUserMedia promise");try{P?yield DeviceManager.userMediaPromiseMap.get(P):yield Promise.all(DeviceManager.userMediaPromiseMap.values())}catch{livekitLogger.warn("error waiting for media permissons")}}let O=yield navigator.mediaDevices.enumerateDevices();if(A&&!(isSafari()&&R.hasDeviceInUse(P))&&(O.filter(V=>V.kind===P).length===0||O.some(V=>{const j=V.label==="",B=P?V.kind===P:!0;return j&&B}))){const V={video:P!=="audioinput"&&P!=="audiooutput",audio:P!=="videoinput"&&{deviceId:{ideal:"default"}}},j=yield navigator.mediaDevices.getUserMedia(V);O=yield navigator.mediaDevices.enumerateDevices(),j.getTracks().forEach(B=>{B.stop()})}return R._previousDevices=O,P&&(O=O.filter(N=>N.kind===P)),O})()})}normalizeDeviceId(n,P,R){return __awaiter(this,void 0,void 0,function*(){if(P!==defaultId)return P;const A=yield this.getDevices(n),L=A.find(N=>N.deviceId===defaultId);if(!L){livekitLogger.warn("could not reliably determine default device");return}const O=A.find(N=>N.deviceId!==defaultId&&N.groupId===(R??L.groupId));if(!O){livekitLogger.warn("could not reliably determine default device");return}return O?.deviceId})}hasDeviceInUse(n){return n?DeviceManager.userMediaPromiseMap.has(n):DeviceManager.userMediaPromiseMap.size>0}}DeviceManager.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];DeviceManager.userMediaPromiseMap=new Map;var QueueTaskStatus;(function(T){T[T.WAITING=0]="WAITING",T[T.RUNNING=1]="RUNNING",T[T.COMPLETED=2]="COMPLETED"})(QueueTaskStatus||(QueueTaskStatus={}));class AsyncQueue{constructor(){this.pendingTasks=new Map,this.taskMutex=new _$1,this.nextTaskIndex=0}run(n){return __awaiter(this,void 0,void 0,function*(){const P={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:QueueTaskStatus.WAITING};this.pendingTasks.set(P.id,P);const R=yield this.taskMutex.lock();try{return P.executedAt=Date.now(),P.status=QueueTaskStatus.RUNNING,yield n()}finally{P.status=QueueTaskStatus.COMPLETED,this.pendingTasks.delete(P.id),R()}})}flush(){return __awaiter(this,void 0,void 0,function*(){return this.run(()=>__awaiter(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function createRtcUrl(T,n){const P=new URL(toWebsocketUrl(T));return n.forEach((R,A)=>{P.searchParams.set(A,R)}),appendUrlPath(P,"rtc")}function createValidateUrl(T){const n=new URL(toHttpUrl(T));return appendUrlPath(n,"validate")}function ensureTrailingSlash(T){return T.endsWith("/")?T:"".concat(T,"/")}function appendUrlPath(T,n){return T.pathname="".concat(ensureTrailingSlash(T.pathname)).concat(n),T.toString()}const passThroughQueueSignals=["syncState","trickle","offer","answer","simulate","leave"];function canPassThroughQueue(T){const n=passThroughQueueSignals.indexOf(T.case)>=0;return livekitLogger.trace("request allowed to bypass queue:",{canPass:n,req:T}),n}var SignalConnectionState;(function(T){T[T.CONNECTING=0]="CONNECTING",T[T.CONNECTED=1]="CONNECTED",T[T.RECONNECTING=2]="RECONNECTING",T[T.DISCONNECTING=3]="DISCONNECTING",T[T.DISCONNECTED=4]="DISCONNECTED"})(SignalConnectionState||(SignalConnectionState={}));class SignalClient{get currentState(){return this.state}get isDisconnected(){return this.state===SignalConnectionState.DISCONNECTING||this.state===SignalConnectionState.DISCONNECTED}get isEstablishingConnection(){return this.state===SignalConnectionState.CONNECTING||this.state===SignalConnectionState.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var R;this.rtt=0,this.state=SignalConnectionState.DISCONNECTED,this.log=livekitLogger,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=getLogger((R=P.loggerName)!==null&&R!==void 0?R:LoggerNames.Signal),this.loggerContextCb=P.loggerContextCb,this.useJSON=n,this.requestQueue=new AsyncQueue,this.queuedRequests=[],this.closingLock=new _$1,this.connectionLock=new _$1,this.state=SignalConnectionState.DISCONNECTED}get logContext(){var n,P;return(P=(n=this.loggerContextCb)===null||n===void 0?void 0:n.call(this))!==null&&P!==void 0?P:{}}join(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){return this.state=SignalConnectionState.CONNECTING,this.options=R,yield this.connect(n,P,R,A)})}reconnect(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=SignalConnectionState.RECONNECTING,this.clearPingInterval(),yield this.connect(n,P,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:R,reconnectReason:A}))})}connect(n,P,R,A){this.connectOptions=R;const L=getClientInfo(),O=createConnectionParams(P,L,R),N=createRtcUrl(n,O),V=createValidateUrl(N);return new Promise((j,B)=>__awaiter(this,void 0,void 0,function*(){const z=yield this.connectionLock.lock();try{const W=()=>__awaiter(this,void 0,void 0,function*(){this.close(),clearTimeout(q),B(new ConnectionError("room connection has been cancelled (signal)",ConnectionErrorReason.Cancelled))}),q=setTimeout(()=>{this.close(),B(new ConnectionError("room connection has timed out (signal)",ConnectionErrorReason.ServerUnreachable))},R.websocketTimeout);A?.aborted&&W(),A?.addEventListener("abort",W);const H=new URL(N);H.searchParams.has("access_token")&&H.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(H),Object.assign({reconnect:R.reconnect,reconnectReason:R.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(N),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(q)},this.ws.onerror=$=>__awaiter(this,void 0,void 0,function*(){if(this.state!==SignalConnectionState.CONNECTED){this.state=SignalConnectionState.DISCONNECTED,clearTimeout(q);try{const Q=yield fetch(V);if(Q.status.toFixed(0).startsWith("4")){const U=yield Q.text();B(new ConnectionError(U,ConnectionErrorReason.NotAllowed,Q.status))}else B(new ConnectionError("Encountered unknown websocket error during connection: ".concat($.toString()),ConnectionErrorReason.InternalError,Q.status))}catch(Q){B(new ConnectionError(Q instanceof Error?Q.message:"server was not reachable",ConnectionErrorReason.ServerUnreachable))}return}this.handleWSError($)}),this.ws.onmessage=$=>__awaiter(this,void 0,void 0,function*(){var Q,U,J;let G;if(typeof $.data=="string"){const K=JSON.parse($.data);G=SignalResponse.fromJson(K,{ignoreUnknownFields:!0})}else if($.data instanceof ArrayBuffer)G=SignalResponse.fromBinary(new Uint8Array($.data));else{this.log.error("could not decode websocket message: ".concat(typeof $.data),this.logContext);return}if(this.state!==SignalConnectionState.CONNECTED){let K=!1;if(((Q=G.message)===null||Q===void 0?void 0:Q.case)==="join"?(this.state=SignalConnectionState.CONNECTED,A?.removeEventListener("abort",W),this.pingTimeoutDuration=G.message.value.pingTimeout,this.pingIntervalDuration=G.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),j(G.message.value)):this.state===SignalConnectionState.RECONNECTING&&G.message.case!=="leave"?(this.state=SignalConnectionState.CONNECTED,A?.removeEventListener("abort",W),this.startPingInterval(),((U=G.message)===null||U===void 0?void 0:U.case)==="reconnect"?j(G.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),j(void 0),K=!0)):this.isEstablishingConnection&&G.message.case==="leave"?B(new ConnectionError("Received leave request while trying to (re)connect",ConnectionErrorReason.LeaveRequest,void 0,G.message.value.reason)):R.reconnect||B(new ConnectionError("did not receive join response, got ".concat((J=G.message)===null||J===void 0?void 0:J.case," instead"),ConnectionErrorReason.InternalError)),!K)return}this.signalLatency&&(yield sleep(this.signalLatency)),this.handleSignalResponse(G)}),this.ws.onclose=$=>{this.isEstablishingConnection&&B(new ConnectionError("Websocket got closed during a (re)connection attempt",ConnectionErrorReason.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:$.reason,code:$.code,wasClean:$.wasClean,state:this.state})),this.handleOnClose($.reason)}}finally{z()}}))}close(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const R=yield n.closingLock.lock();try{if(n.clearPingInterval(),P&&(n.state=SignalConnectionState.DISCONNECTING),n.ws){n.ws.onmessage=null,n.ws.onopen=null,n.ws.onclose=null;const A=new Promise(L=>{n.ws?n.ws.onclose=()=>{L()}:L()});n.ws.readyState<n.ws.CLOSING&&(n.ws.close(),yield Promise.race([A,sleep(250)])),n.ws=void 0}}finally{P&&(n.state=SignalConnectionState.DISCONNECTED),R()}})()})}sendOffer(n,P){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:n.sdp})),this.sendRequest({case:"offer",value:toProtoSessionDescription(n,P)})}sendAnswer(n,P){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:n.sdp})),this.sendRequest({case:"answer",value:toProtoSessionDescription(n,P)})}sendIceCandidate(n,P){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:n})),this.sendRequest({case:"trickle",value:new TrickleRequest({candidateInit:JSON.stringify(n),target:P})})}sendMuteTrack(n,P){return this.sendRequest({case:"mute",value:new MuteTrackRequest({sid:n,muted:P})})}sendAddTrack(n){return this.sendRequest({case:"addTrack",value:n})}sendUpdateLocalMetadata(n,P){return __awaiter(this,arguments,void 0,function(R,A){var L=this;let O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const N=L.getNextRequestId();return yield L.sendRequest({case:"updateMetadata",value:new UpdateParticipantMetadata({requestId:N,metadata:R,name:A,attributes:O})}),N})()})}sendUpdateTrackSettings(n){this.sendRequest({case:"trackSetting",value:n})}sendUpdateSubscription(n){return this.sendRequest({case:"subscription",value:n})}sendSyncState(n){return this.sendRequest({case:"syncState",value:n})}sendUpdateVideoLayers(n,P){return this.sendRequest({case:"updateLayers",value:new UpdateVideoLayers({trackSid:n,layers:P})})}sendUpdateSubscriptionPermissions(n,P){return this.sendRequest({case:"subscriptionPermission",value:new SubscriptionPermission({allParticipants:n,trackPermissions:P})})}sendSimulateScenario(n){return this.sendRequest({case:"simulate",value:n})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:protoInt64.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ping({timestamp:protoInt64.parse(Date.now()),rtt:protoInt64.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(n,P){return this.sendRequest({case:"updateAudioTrack",value:new UpdateLocalAudioTrack({trackSid:n,features:P})})}sendLeave(){return this.sendRequest({case:"leave",value:new LeaveRequest({reason:DisconnectReason.CLIENT_INITIATED,action:LeaveRequest_Action.DISCONNECT})})}sendRequest(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!A&&!canPassThroughQueue(P)&&R.state===SignalConnectionState.RECONNECTING){R.queuedRequests.push(()=>__awaiter(R,void 0,void 0,function*(){yield this.sendRequest(P,!0)}));return}if(A||(yield R.requestQueue.flush()),R.signalLatency&&(yield sleep(R.signalLatency)),R.isDisconnected){R.log.debug("skipping signal request (type: ".concat(P.case,") - SignalClient disconnected"));return}if(!R.ws||R.ws.readyState!==R.ws.OPEN){R.log.error("cannot send signal request before connected, type: ".concat(P?.case),R.logContext);return}const O=new SignalRequest({message:P});try{R.useJSON?R.ws.send(O.toJsonString()):R.ws.send(O.toBinary())}catch(N){R.log.error("error sending signal message",Object.assign(Object.assign({},R.logContext),{error:N}))}})()})}handleSignalResponse(n){var P,R;const A=n.message;if(A==null){this.log.debug("received unsupported message",this.logContext);return}let L=!1;if(A.case==="answer"){const O=fromProtoSessionDescription(A.value);this.onAnswer&&this.onAnswer(O,A.value.id)}else if(A.case==="offer"){const O=fromProtoSessionDescription(A.value);this.onOffer&&this.onOffer(O,A.value.id)}else if(A.case==="trickle"){const O=JSON.parse(A.value.candidateInit);this.onTrickle&&this.onTrickle(O,A.value.target)}else A.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((P=A.value.participants)!==null&&P!==void 0?P:[]):A.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(A.value):A.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((R=A.value.speakers)!==null&&R!==void 0?R:[]):A.case==="leave"?this.onLeave&&this.onLeave(A.value):A.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(A.value.sid,A.value.muted):A.case==="roomUpdate"?this.onRoomUpdate&&A.value.room&&this.onRoomUpdate(A.value.room):A.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(A.value):A.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(A.value):A.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(A.value):A.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(A.value):A.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(A.value):A.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(A.value):A.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(A.value):A.case==="pong"||(A.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(A.value.lastPingTimestamp.toString()),this.resetPingTimeout(),L=!0):A.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(A.value):A.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(A.value.trackSid):A.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(A.value.token),this.onRoomMoved&&this.onRoomMoved(A.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:A.case})));L||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const n=this.queuedRequests.shift();n&&this.requestQueue.run(n)}}handleOnClose(n){return __awaiter(this,void 0,void 0,function*(){if(this.state===SignalConnectionState.DISCONNECTED)return;const P=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(n),Object.assign(Object.assign({},this.logContext),{reason:n})),P&&P(n)})}handleWSError(n){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:n}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=CriticalTimers.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&CriticalTimers.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=CriticalTimers.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&CriticalTimers.clearInterval(this.pingInterval)}}function fromProtoSessionDescription(T){const n={type:"offer",sdp:T.sdp};switch(T.type){case"answer":case"offer":case"pranswer":case"rollback":n.type=T.type;break}return n}function toProtoSessionDescription(T,n){return new SessionDescription({sdp:T.sdp,type:T.type,id:n})}function createConnectionParams(T,n,P){var R;const A=new URLSearchParams;return A.set("access_token",T),P.reconnect&&(A.set("reconnect","1"),P.sid&&A.set("sid",P.sid)),A.set("auto_subscribe",P.autoSubscribe?"1":"0"),A.set("sdk",isReactNative$1()?"reactnative":"js"),A.set("version",n.version),A.set("protocol",n.protocol.toString()),n.deviceModel&&A.set("device_model",n.deviceModel),n.os&&A.set("os",n.os),n.osVersion&&A.set("os_version",n.osVersion),n.browser&&A.set("browser",n.browser),n.browserVersion&&A.set("browser_version",n.browserVersion),P.adaptiveStream&&A.set("adaptive_stream","1"),P.reconnectReason&&A.set("reconnect_reason",P.reconnectReason.toString()),!((R=navigator.connection)===null||R===void 0)&&R.type&&A.set("network",navigator.connection.type),A}class DataPacketBuffer{constructor(){this.buffer=[],this._totalSize=0}push(n){this.buffer.push(n),this._totalSize+=n.data.byteLength}pop(){const n=this.buffer.shift();return n&&(this._totalSize-=n.data.byteLength),n}getAll(){return this.buffer.slice()}popToSequence(n){for(;this.buffer.length>0&&this.buffer[0].sequence<=n;)this.pop()}alignBufferedAmount(n){for(;this.buffer.length>0;){const P=this.buffer[0];if(this._totalSize-P.data.byteLength<=n)break;this.pop()}}get length(){return this.buffer.length}}class TTLMap{constructor(n){this._map=new Map,this._lastCleanup=0,this.ttl=n}set(n,P){const R=Date.now();R-this._lastCleanup>this.ttl/2&&this.cleanup();const A=R+this.ttl;return this._map.set(n,{value:P,expiresAt:A}),this}get(n){const P=this._map.get(n);if(P){if(P.expiresAt<Date.now()){this._map.delete(n);return}return P.value}}has(n){const P=this._map.get(n);return P?P.expiresAt<Date.now()?(this._map.delete(n),!1):!0:!1}delete(n){return this._map.delete(n)}clear(){this._map.clear()}cleanup(){const n=Date.now();for(const[P,R]of this._map.entries())R.expiresAt<n&&this._map.delete(P);this._lastCleanup=n}get size(){return this.cleanup(),this._map.size}forEach(n){this.cleanup();for(const[P,R]of this._map.entries())R.expiresAt>=Date.now()&&n(R.value,P,this.asValueMap())}map(n){this.cleanup();const P=[],R=this.asValueMap();for(const[A,L]of R.entries())P.push(n(L,A,R));return P}asValueMap(){const n=new Map;for(const[P,R]of this._map.entries())R.expiresAt>=Date.now()&&n.set(P,R.value);return n}}var lib={},parser$1={},grammar={exports:{}},hasRequiredGrammar;function requireGrammar(){if(hasRequiredGrammar)return grammar.exports;hasRequiredGrammar=1;var T=grammar.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(n){return n.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(n){return n.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(n){var P="candidate:%s %d %s %d %s %d typ %s";return P+=n.raddr!=null?" raddr %s rport %d":"%v%v",P+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(P+=" generation %d"),P+=n["network-id"]!=null?" network-id %d":"%v",P+=n["network-cost"]!=null?" network-cost %d":"%v",P}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(n){var P="ssrc:%d";return n.attribute!=null&&(P+=" %s",n.value!=null&&(P+=":%s")),P}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(n){return n.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(n){return n.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(n){return"imageattr:%s %s %s"+(n.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(n){return"simulcast:%s %s"+(n.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var P="mediaclk:";return P+=n.id!=null?"id=%s %s":"%v%s",P+=n.mediaClockValue!=null?"=%s":"",P+=n.rateNumerator!=null?" rate=%s":"",P+=n.rateDenominator!=null?"/%s":"",P}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(T).forEach(function(n){var P=T[n];P.forEach(function(R){R.reg||(R.reg=/(.*)/),R.format||(R.format="%s")})}),grammar.exports}var hasRequiredParser;function requireParser(){return hasRequiredParser||(hasRequiredParser=1,(function(T){var n=function(N){return String(Number(N))===N?Number(N):N},P=function(N,V,j,B){if(B&&!j)V[B]=n(N[1]);else for(var z=0;z<j.length;z+=1)N[z+1]!=null&&(V[j[z]]=n(N[z+1]))},R=function(N,V,j){var B=N.name&&N.names;N.push&&!V[N.push]?V[N.push]=[]:B&&!V[N.name]&&(V[N.name]={});var z=N.push?{}:B?V[N.name]:V;P(j.match(N.reg),z,N.names,N.name),N.push&&V[N.push].push(z)},A=requireGrammar(),L=RegExp.prototype.test.bind(/^([a-z])=(.*)/);T.parse=function(N){var V={},j=[],B=V;return N.split(/(\r\n|\r|\n)/).filter(L).forEach(function(z){var W=z[0],q=z.slice(2);W==="m"&&(j.push({rtp:[],fmtp:[]}),B=j[j.length-1]);for(var H=0;H<(A[W]||[]).length;H+=1){var $=A[W][H];if($.reg.test(q))return R($,B,q)}}),V.media=j,V};var O=function(N,V){var j=V.split(/=(.+)/,2);return j.length===2?N[j[0]]=n(j[1]):j.length===1&&V.length>1&&(N[j[0]]=void 0),N};T.parseParams=function(N){return N.split(/;\s?/).reduce(O,{})},T.parseFmtpConfig=T.parseParams,T.parsePayloads=function(N){return N.toString().split(" ").map(Number)},T.parseRemoteCandidates=function(N){for(var V=[],j=N.split(" ").map(n),B=0;B<j.length;B+=3)V.push({component:j[B],ip:j[B+1],port:j[B+2]});return V},T.parseImageAttributes=function(N){return N.split(" ").map(function(V){return V.substring(1,V.length-1).split(",").reduce(O,{})})},T.parseSimulcastStreamList=function(N){return N.split(";").map(function(V){return V.split(",").map(function(j){var B,z=!1;return j[0]!=="~"?B=n(j):(B=n(j.substring(1,j.length)),z=!0),{scid:B,paused:z}})})}})(parser$1)),parser$1}var writer,hasRequiredWriter;function requireWriter(){if(hasRequiredWriter)return writer;hasRequiredWriter=1;var T=requireGrammar(),n=/%[sdv%]/g,P=function(O){var N=1,V=arguments,j=V.length;return O.replace(n,function(B){if(N>=j)return B;var z=V[N];switch(N+=1,B){case"%%":return"%";case"%s":return String(z);case"%d":return Number(z);case"%v":return""}})},R=function(O,N,V){var j=N.format instanceof Function?N.format(N.push?V:V[N.name]):N.format,B=[O+"="+j];if(N.names)for(var z=0;z<N.names.length;z+=1){var W=N.names[z];N.name?B.push(V[N.name][W]):B.push(V[N.names[z]])}else B.push(V[N.name]);return P.apply(null,B)},A=["v","o","s","i","u","e","p","c","b","t","r","z","a"],L=["i","c","b","a"];return writer=function(O,N){N=N||{},O.version==null&&(O.version=0),O.name==null&&(O.name=" "),O.media.forEach(function(z){z.payloads==null&&(z.payloads="")});var V=N.outerOrder||A,j=N.innerOrder||L,B=[];return V.forEach(function(z){T[z].forEach(function(W){W.name in O&&O[W.name]!=null?B.push(R(z,W,O)):W.push in O&&O[W.push]!=null&&O[W.push].forEach(function(q){B.push(R(z,W,q))})})}),O.media.forEach(function(z){B.push(R("m",T.m[0],z)),j.forEach(function(W){T[W].forEach(function(q){q.name in z&&z[q.name]!=null?B.push(R(W,q,z)):q.push in z&&z[q.push]!=null&&z[q.push].forEach(function(H){B.push(R(W,q,H))})})})}),B.join(`\r
|
|
528
|
+
`)+`\r
|
|
529
|
+
`},writer}var hasRequiredLib;function requireLib(){if(hasRequiredLib)return lib;hasRequiredLib=1;var T=requireParser(),n=requireWriter(),P=requireGrammar();return lib.grammar=P,lib.write=n,lib.parse=T.parse,lib.parseParams=T.parseParams,lib.parseFmtpConfig=T.parseFmtpConfig,lib.parsePayloads=T.parsePayloads,lib.parseRemoteCandidates=T.parseRemoteCandidates,lib.parseImageAttributes=T.parseImageAttributes,lib.parseSimulcastStreamList=T.parseSimulcastStreamList,lib}var libExports=requireLib();function r$1(T,n,P){var R,A,L;n===void 0&&(n=50),P===void 0&&(P={});var O=(R=P.isImmediate)!=null&&R,N=(A=P.callback)!=null&&A,V=P.maxWait,j=Date.now(),B=[];function z(){if(V!==void 0){var q=Date.now()-j;if(q+n>=V)return V-q}return n}var W=function(){var q=[].slice.call(arguments),H=this;return new Promise(function($,Q){var U=O&&L===void 0;if(L!==void 0&&clearTimeout(L),L=setTimeout(function(){if(L=void 0,j=Date.now(),!O){var G=T.apply(H,q);N&&N(G),B.forEach(function(K){return(0,K.resolve)(G)}),B=[]}},z()),U){var J=T.apply(H,q);return N&&N(J),$(J)}B.push({resolve:$,reject:Q})})};return W.cancel=function(q){L!==void 0&&clearTimeout(L),B.forEach(function(H){return(0,H.reject)(q)}),B=[]},W}const startBitrateForSVC=.7,debounceInterval=20,PCEvents={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class PCTransport extends eventsExports.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(n){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var R;super(),this.log=livekitLogger,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=r$1(A=>__awaiter(this,void 0,void 0,function*(){this.emit(PCEvents.NegotiationStarted);try{yield this.createAndSendOffer()}catch(L){if(A)A(L);else throw L}}),debounceInterval),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=getLogger((R=P.loggerName)!==null&&R!==void 0?R:LoggerNames.PCTransport),this.loggerOptions=P,this.config=n,this._pc=this.createPC(),this.offerLock=new _$1}createPC(){const n=new RTCPeerConnection(this.config);return n.onicecandidate=P=>{var R;P.candidate&&((R=this.onIceCandidate)===null||R===void 0||R.call(this,P.candidate))},n.onicecandidateerror=P=>{var R;(R=this.onIceCandidateError)===null||R===void 0||R.call(this,P)},n.oniceconnectionstatechange=()=>{var P;(P=this.onIceConnectionStateChange)===null||P===void 0||P.call(this,n.iceConnectionState)},n.onsignalingstatechange=()=>{var P;(P=this.onSignalingStatechange)===null||P===void 0||P.call(this,n.signalingState)},n.onconnectionstatechange=()=>{var P;(P=this.onConnectionStateChange)===null||P===void 0||P.call(this,n.connectionState)},n.ondatachannel=P=>{var R;(R=this.onDataChannel)===null||R===void 0||R.call(this,P)},n.ontrack=P=>{var R;(R=this.onTrack)===null||R===void 0||R.call(this,P)},n}get logContext(){var n,P;return Object.assign({},(P=(n=this.loggerOptions).loggerContextCb)===null||P===void 0?void 0:P.call(n))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(n){return __awaiter(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(n);this.pendingCandidates.push(n)})}setRemoteDescription(n,P){return __awaiter(this,void 0,void 0,function*(){var R;if(n.type==="answer"&&this.latestOfferId>0&&P>0&&P!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:P,latestOfferId:this.latestOfferId})),!1;let A;if(n.type==="offer"){let{stereoMids:L,nackMids:O}=extractStereoAndNackAudioFromOffer(n);this.remoteStereoMids=L,this.remoteNackMids=O}else if(n.type==="answer"){const L=libExports.parse((R=n.sdp)!==null&&R!==void 0?R:"");L.media.forEach(O=>{const N=getMidString(O.mid);O.type==="audio"&&this.trackBitrates.some(V=>{if(!V.transceiver||N!=V.transceiver.mid)return!1;let j=0;if(O.rtp.some(z=>z.codec.toUpperCase()===V.codec.toUpperCase()?(j=z.payload,!0):!1),j===0)return!0;let B=!1;for(const z of O.fmtp)if(z.payload===j){z.config=z.config.split(";").filter(W=>!W.includes("maxaveragebitrate")).join(";"),V.maxbr>0&&(z.config+=";maxaveragebitrate=".concat(V.maxbr*1e3)),B=!0;break}return B||V.maxbr>0&&O.fmtp.push({payload:j,config:"maxaveragebitrate=".concat(V.maxbr*1e3)}),!0})}),A=libExports.write(L)}return yield this.setMungedSDP(n,A,!0),this.pendingCandidates.forEach(L=>{this.pc.addIceCandidate(L)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):n.type==="answer"&&(this.emit(PCEvents.NegotiationComplete),n.sdp&&libExports.parse(n.sdp).media.forEach(O=>{O.type==="video"&&this.emit(PCEvents.RTPVideoPayloadTypes,O.rtp)})),!0})}createAndSendOffer(n){return __awaiter(this,void 0,void 0,function*(){var P;const R=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(n?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const N=this._pc.remoteDescription;if(n?.iceRestart&&N)yield this._pc.setRemoteDescription(N);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const A=this.latestOfferId+1;this.latestOfferId=A;const L=yield this.pc.createOffer(n);this.log.debug("original offer",Object.assign({sdp:L.sdp},this.logContext));const O=libExports.parse((P=L.sdp)!==null&&P!==void 0?P:"");if(O.media.forEach(N=>{ensureIPAddrMatchVersion(N),N.type==="audio"?ensureAudioNackAndStereo(N,[],[]):N.type==="video"&&this.trackBitrates.some(V=>{if(!N.msid||!V.cid||!N.msid.includes(V.cid))return!1;let j=0;if(N.rtp.some(z=>z.codec.toUpperCase()===V.codec.toUpperCase()?(j=z.payload,!0):!1),j===0||(isSVCCodec(V.codec)&&!isSafari()&&this.ensureVideoDDExtensionForSVC(N,O),V.codec!=="av1"))return!0;const B=Math.round(V.maxbr*startBitrateForSVC);for(const z of N.fmtp)if(z.payload===j){z.config.includes("x-google-start-bitrate")||(z.config+=";x-google-start-bitrate=".concat(B));break}return!0})}),this.latestOfferId>A){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:A}));return}yield this.setMungedSDP(L,libExports.write(O)),this.onOffer(L,this.latestOfferId)}finally{R()}})}createAndSetAnswer(){return __awaiter(this,void 0,void 0,function*(){var n;const P=yield this.pc.createAnswer(),R=libExports.parse((n=P.sdp)!==null&&n!==void 0?n:"");return R.media.forEach(A=>{ensureIPAddrMatchVersion(A),A.type==="audio"&&ensureAudioNackAndStereo(A,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(P,libExports.write(R)),P})}createDataChannel(n,P){return this.pc.createDataChannel(n,P)}addTransceiver(n,P){return this.pc.addTransceiver(n,P)}addTrack(n){if(!this._pc)throw new UnexpectedConnectionState("PC closed, cannot add track");return this._pc.addTrack(n)}setTrackCodecBitrate(n){this.trackBitrates.push(n)}setConfiguration(n){var P;if(!this._pc)throw new UnexpectedConnectionState("PC closed, cannot configure");return(P=this._pc)===null||P===void 0?void 0:P.setConfiguration(n)}canRemoveTrack(){var n;return!!(!((n=this._pc)===null||n===void 0)&&n.removeTrack)}removeTrack(n){var P;return(P=this._pc)===null||P===void 0?void 0:P.removeTrack(n)}getConnectionState(){var n,P;return(P=(n=this._pc)===null||n===void 0?void 0:n.connectionState)!==null&&P!==void 0?P:"closed"}getICEConnectionState(){var n,P;return(P=(n=this._pc)===null||n===void 0?void 0:n.iceConnectionState)!==null&&P!==void 0?P:"closed"}getSignallingState(){var n,P;return(P=(n=this._pc)===null||n===void 0?void 0:n.signalingState)!==null&&P!==void 0?P:"closed"}getTransceivers(){var n,P;return(P=(n=this._pc)===null||n===void 0?void 0:n.getTransceivers())!==null&&P!==void 0?P:[]}getSenders(){var n,P;return(P=(n=this._pc)===null||n===void 0?void 0:n.getSenders())!==null&&P!==void 0?P:[]}getLocalDescription(){var n;return(n=this._pc)===null||n===void 0?void 0:n.localDescription}getRemoteDescription(){var n;return(n=this.pc)===null||n===void 0?void 0:n.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return __awaiter(this,void 0,void 0,function*(){var n;if(!this._pc)return;let P="";const R=new Map,A=new Map;if((yield this._pc.getStats()).forEach(N=>{switch(N.type){case"transport":P=N.selectedCandidatePairId;break;case"candidate-pair":P===""&&N.selected&&(P=N.id),R.set(N.id,N);break;case"remote-candidate":A.set(N.id,"".concat(N.address,":").concat(N.port));break}}),P==="")return;const O=(n=R.get(P))===null||n===void 0?void 0:n.remoteCandidateId;if(O!==void 0)return A.get(O)})}setMungedSDP(n,P,R){return __awaiter(this,void 0,void 0,function*(){if(P){const A=n.sdp;n.sdp=P;try{this.log.debug("setting munged ".concat(R?"remote":"local"," description"),this.logContext),R?yield this.pc.setRemoteDescription(n):yield this.pc.setLocalDescription(n);return}catch(L){this.log.warn("not able to set ".concat(n.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:L,sdp:P})),n.sdp=A}}try{R?yield this.pc.setRemoteDescription(n):yield this.pc.setLocalDescription(n)}catch(A){let L="unknown error";A instanceof Error?L=A.message:typeof A=="string"&&(L=A);const O={error:L,sdp:n.sdp};throw!R&&this.pc.remoteDescription&&(O.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(n.type),Object.assign(Object.assign({},this.logContext),{fields:O})),new NegotiationError(L)}})}ensureVideoDDExtensionForSVC(n,P){var R,A;if(!((R=n.ext)===null||R===void 0?void 0:R.some(O=>O.uri===ddExtensionURI))){if(this.ddExtID===0){let O=0;P.media.forEach(N=>{var V;N.type==="video"&&((V=N.ext)===null||V===void 0||V.forEach(j=>{j.value>O&&(O=j.value)}))}),this.ddExtID=O+1}(A=n.ext)===null||A===void 0||A.push({value:this.ddExtID,uri:ddExtensionURI})}}}function ensureAudioNackAndStereo(T,n,P){const R=getMidString(T.mid);let A=0;T.rtp.some(L=>L.codec==="opus"?(A=L.payload,!0):!1),A>0&&(T.rtcpFb||(T.rtcpFb=[]),P.includes(R)&&!T.rtcpFb.some(L=>L.payload===A&&L.type==="nack")&&T.rtcpFb.push({payload:A,type:"nack"}),n.includes(R)&&T.fmtp.some(L=>L.payload===A?(L.config.includes("stereo=1")||(L.config+=";stereo=1"),!0):!1))}function extractStereoAndNackAudioFromOffer(T){var n;const P=[],R=[],A=libExports.parse((n=T.sdp)!==null&&n!==void 0?n:"");let L=0;return A.media.forEach(O=>{var N;const V=getMidString(O.mid);O.type==="audio"&&(O.rtp.some(j=>j.codec==="opus"?(L=j.payload,!0):!1),!((N=O.rtcpFb)===null||N===void 0)&&N.some(j=>j.payload===L&&j.type==="nack")&&R.push(V),O.fmtp.some(j=>j.payload===L?(j.config.includes("sprop-stereo=1")&&P.push(V),!0):!1))}),{stereoMids:P,nackMids:R}}function ensureIPAddrMatchVersion(T){if(T.connection){const n=T.connection.ip.indexOf(":")>=0;(T.connection.version===4&&n||T.connection.version===6&&!n)&&(T.connection.ip="0.0.0.0",T.connection.version=4)}}function getMidString(T){return typeof T=="number"?T.toFixed(0):T}const defaultVideoCodec="vp8",publishDefaults={audioPreset:AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ScreenSharePresets.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:defaultVideoCodec,backupCodec:!0,preConnectBuffer:!1},audioDefaults={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},videoDefaults={deviceId:{ideal:"default"},resolution:VideoPresets.h720.resolution},roomOptionDefaults={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new DefaultReconnectPolicy,disconnectOnPageLeave:!0,webAudioMix:!1},roomConnectOptionDefaults={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var PCTransportState;(function(T){T[T.NEW=0]="NEW",T[T.CONNECTING=1]="CONNECTING",T[T.CONNECTED=2]="CONNECTED",T[T.FAILED=3]="FAILED",T[T.CLOSING=4]="CLOSING",T[T.CLOSED=5]="CLOSED"})(PCTransportState||(PCTransportState={}));class PCTransportManager{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(n,P,R){var A;this.peerConnectionTimeout=roomConnectOptionDefaults.peerConnectionTimeout,this.log=livekitLogger,this.updateState=()=>{var L;const O=this.state,N=this.requiredTransports.map(V=>V.getConnectionState());N.every(V=>V==="connected")?this.state=PCTransportState.CONNECTED:N.some(V=>V==="failed")?this.state=PCTransportState.FAILED:N.some(V=>V==="connecting")?this.state=PCTransportState.CONNECTING:N.every(V=>V==="closed")?this.state=PCTransportState.CLOSED:N.some(V=>V==="closed")?this.state=PCTransportState.CLOSING:N.every(V=>V==="new")&&(this.state=PCTransportState.NEW),O!==this.state&&(this.log.debug("pc state change: from ".concat(PCTransportState[O]," to ").concat(PCTransportState[this.state]),this.logContext),(L=this.onStateChange)===null||L===void 0||L.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=getLogger((A=R.loggerName)!==null&&A!==void 0?A:LoggerNames.PCManager),this.loggerOptions=R,this.isPublisherConnectionRequired=!P,this.isSubscriberConnectionRequired=P,this.publisher=new PCTransport(n,R),this.subscriber=new PCTransport(n,R),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=L=>{var O;(O=this.onIceCandidate)===null||O===void 0||O.call(this,L,SignalTarget.PUBLISHER)},this.subscriber.onIceCandidate=L=>{var O;(O=this.onIceCandidate)===null||O===void 0||O.call(this,L,SignalTarget.SUBSCRIBER)},this.subscriber.onDataChannel=L=>{var O;(O=this.onDataChannel)===null||O===void 0||O.call(this,L)},this.subscriber.onTrack=L=>{var O;(O=this.onTrack)===null||O===void 0||O.call(this,L)},this.publisher.onOffer=(L,O)=>{var N;(N=this.onPublisherOffer)===null||N===void 0||N.call(this,L,O)},this.state=PCTransportState.NEW,this.connectionLock=new _$1,this.remoteOfferLock=new _$1}get logContext(){var n,P;return Object.assign({},(P=(n=this.loggerOptions).loggerContextCb)===null||P===void 0?void 0:P.call(n))}requirePublisher(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=n,this.updateState()}requireSubscriber(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=n,this.updateState()}createAndSendPublisherOffer(n){return this.publisher.createAndSendOffer(n)}setPublisherAnswer(n,P){return this.publisher.setRemoteDescription(n,P)}removeTrack(n){return this.publisher.removeTrack(n)}close(){return __awaiter(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const n=this.publisher;for(const P of n.getSenders())try{n.canRemoveTrack()&&n.removeTrack(P)}catch(R){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:R}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return __awaiter(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(n,P){return __awaiter(this,void 0,void 0,function*(){P===SignalTarget.PUBLISHER?yield this.publisher.addIceCandidate(n):yield this.subscriber.addIceCandidate(n)})}createSubscriberAnswerFromOffer(n,P){return __awaiter(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:n.type,sdp:n.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const R=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(n,P))?yield this.subscriber.createAndSetAnswer():void 0}finally{R()}})}updateConfiguration(n,P){this.publisher.setConfiguration(n),this.subscriber.setConfiguration(n),P&&this.triggerIceRestart()}ensurePCTransportConnection(n,P){return __awaiter(this,void 0,void 0,function*(){var R;const A=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((R=this.requiredTransports)===null||R===void 0?void 0:R.map(L=>this.ensureTransportConnected(L,n,P)))}finally{A()}})}negotiate(n){return __awaiter(this,void 0,void 0,function*(){return new Promise((P,R)=>__awaiter(this,void 0,void 0,function*(){const A=setTimeout(()=>{R("negotiation timed out")},this.peerConnectionTimeout),L=()=>{clearTimeout(A),R("negotiation aborted")};n.signal.addEventListener("abort",L),this.publisher.once(PCEvents.NegotiationStarted,()=>{n.signal.aborted||this.publisher.once(PCEvents.NegotiationComplete,()=>{clearTimeout(A),P()})}),yield this.publisher.negotiate(O=>{clearTimeout(A),R(O)})}))})}addPublisherTransceiver(n,P){return this.publisher.addTransceiver(n,P)}addPublisherTrack(n){return this.publisher.addTrack(n)}createPublisherDataChannel(n,P){return this.publisher.createDataChannel(n,P)}getConnectedAddress(n){return n===SignalTarget.PUBLISHER?this.publisher.getConnectedAddress():n===SignalTarget.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const n=[];return this.isPublisherConnectionRequired&&n.push(this.publisher),this.isSubscriberConnectionRequired&&n.push(this.subscriber),n}ensureTransportConnected(n,P){return __awaiter(this,arguments,void 0,function(R,A){var L=this;let O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(R.getConnectionState()!=="connected")return new Promise((V,j)=>__awaiter(L,void 0,void 0,function*(){const B=()=>{this.log.warn("abort transport connection",this.logContext),CriticalTimers.clearTimeout(z),j(new ConnectionError("room connection has been cancelled",ConnectionErrorReason.Cancelled))};A?.signal.aborted&&B(),A?.signal.addEventListener("abort",B);const z=CriticalTimers.setTimeout(()=>{A?.signal.removeEventListener("abort",B),j(new ConnectionError("could not establish pc connection",ConnectionErrorReason.InternalError))},O);for(;this.state!==PCTransportState.CONNECTED;)if(yield sleep(50),A?.signal.aborted){j(new ConnectionError("room connection has been cancelled",ConnectionErrorReason.Cancelled));return}CriticalTimers.clearTimeout(z),A?.signal.removeEventListener("abort",B),V()}))})()})}}class RpcError extends Error{constructor(n,P,R){super(P),this.code=n,this.message=truncateBytes(P,RpcError.MAX_MESSAGE_BYTES),this.data=R?truncateBytes(R,RpcError.MAX_DATA_BYTES):void 0}static fromProto(n){return new RpcError(n.code,n.message,n.data)}toProto(){return new RpcError$1({code:this.code,message:this.message,data:this.data})}static builtIn(n,P){return new RpcError(RpcError.ErrorCode[n],RpcError.ErrorMessage[n],P)}}RpcError.MAX_MESSAGE_BYTES=256;RpcError.MAX_DATA_BYTES=15360;RpcError.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};RpcError.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const MAX_PAYLOAD_BYTES=15360;function byteLength$1(T){return new TextEncoder().encode(T).length}function truncateBytes(T,n){if(byteLength$1(T)<=n)return T;let P=0,R=T.length;const A=new TextEncoder;for(;P<R;){const L=Math.floor((P+R+1)/2);A.encode(T.slice(0,L)).length<=n?P=L:R=L-1}return T.slice(0,P)}const monitorFrequency=2e3;function computeBitrate(T,n){if(!n)return 0;let P,R;return"bytesReceived"in T?(P=T.bytesReceived,R=n.bytesReceived):"bytesSent"in T&&(P=T.bytesSent,R=n.bytesSent),P===void 0||R===void 0||T.timestamp===void 0||n.timestamp===void 0?0:(P-R)*8*1e3/(T.timestamp-n.timestamp)}const isMediaRecorderAvailable=typeof MediaRecorder<"u";class FallbackRecorder{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const RecorderBase=isMediaRecorderAvailable?MediaRecorder:FallbackRecorder;class LocalTrackRecorder extends RecorderBase{constructor(n,P){if(!isMediaRecorderAvailable)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([n.mediaStreamTrack]),P);let R,A;const L=()=>A===void 0,O=()=>{this.removeEventListener("dataavailable",R),this.removeEventListener("stop",O),this.removeEventListener("error",N),A?.close(),A=void 0},N=V=>{A?.error(V),this.removeEventListener("dataavailable",R),this.removeEventListener("stop",O),this.removeEventListener("error",N),A=void 0};this.byteStream=new ReadableStream({start:V=>{A=V,R=j=>__awaiter(this,void 0,void 0,function*(){let B;if(j.data.arrayBuffer){const z=yield j.data.arrayBuffer();B=new Uint8Array(z)}else if(j.data.byteArray)B=j.data.byteArray;else throw new Error("no data available!");L()||V.enqueue(B)}),this.addEventListener("dataavailable",R)},cancel:()=>{O()}}),this.addEventListener("stop",O),this.addEventListener("error",N)}}function isRecordingSupported(){return isMediaRecorderAvailable}const DEFAULT_DIMENSIONS_TIMEOUT=1e3,PRE_CONNECT_BUFFER_TIMEOUT=1e4;class LocalTrack extends Track{get sender(){return this._sender}set sender(n){this._sender=n}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(n,P,R){let A=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,L=arguments.length>4?arguments[4]:void 0;super(n,P,L),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=r$1(()=>__awaiter(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>__awaiter(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=A,this.muteLock=new _$1,this.pauseUpstreamLock=new _$1,this.trackChangeLock=new _$1,this.trackChangeLock.lock().then(O=>__awaiter(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(n,!0)}finally{O()}})),this._constraints=n.getConstraints(),R&&(this._constraints=R)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Track.Kind.Video)return;const{width:n,height:P}=this._mediaStreamTrack.getSettings();if(n&&P)return{width:n,height:P}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var n,P;return(P=(n=this.processor)===null||n===void 0?void 0:n.processedTrack)!==null&&P!==void 0?P:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(n,P){return __awaiter(this,void 0,void 0,function*(){var R;if(n===this._mediaStreamTrack&&!P)return;this._mediaStreamTrack&&(this.attachedElements.forEach(L=>{detachTrack(this._mediaStreamTrack,L)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([n]),n&&(n.addEventListener("ended",this.handleEnded),n.addEventListener("mute",this.handleTrackMuteEvent),n.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=n.getConstraints());let A;if(this.processor&&n){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(attachToElement(n,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:n,kind:this.kind,element:this.processorElement}),A=this.processor.processedTrack}this.sender&&((R=this.sender.transport)===null||R===void 0?void 0:R.state)!=="closed"&&(yield this.sender.replaceTrack(A??n)),!this.providedByUser&&this._mediaStreamTrack!==n&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=n,n&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(L=>{attachToElement(A??n,L)}))})}waitForDimensions(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:DEFAULT_DIMENSIONS_TIMEOUT;return(function*(){var R;if(n.kind===Track.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((R=getBrowser())===null||R===void 0?void 0:R.os)==="iOS"&&(yield sleep(10));const A=Date.now();for(;Date.now()-A<P;){const L=n.dimensions;if(L)return L;yield sleep(50)}throw new TrackInvalidError("unable to get track dimensions after timeout")})()})}setDeviceId(n){return __awaiter(this,void 0,void 0,function*(){return this._constraints.deviceId===n&&this._mediaStreamTrack.getSettings().deviceId===unwrapConstraint(n)||(this._constraints.deviceId=n,this.isMuted)?!0:(yield this.restartTrack(),unwrapConstraint(n)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(n.source===Track.Source.ScreenShare)return;const{deviceId:R,groupId:A}=n._mediaStreamTrack.getSettings(),L=n.kind===Track.Kind.Audio?"audioinput":"videoinput";return P?DeviceManager.getInstance().normalizeDeviceId(L,R,A):R})()})}mute(){return __awaiter(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return __awaiter(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(n,P){return __awaiter(this,void 0,void 0,function*(){const R=yield this.trackChangeLock.lock();try{if(!this.sender)throw new TrackInvalidError("unable to replace an unpublished track");let A,L;return typeof P=="boolean"?A=P:P!==void 0&&(A=P.userProvidedTrack,L=P.stopProcessor),this.providedByUser=A??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(n),L&&this.processor&&(yield this.internalStopProcessor()),this}finally{R()}})}restart(n){return __awaiter(this,void 0,void 0,function*(){this.manuallyStopped=!1;const P=yield this.trackChangeLock.lock();try{n||(n=this._constraints);const{deviceId:R,facingMode:A}=n,L=__rest(n,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:n}));const O={audio:!1,video:!1};this.kind===Track.Kind.Video?O.video=R||A?{deviceId:R,facingMode:A}:!0:O.audio=R?Object.assign({deviceId:R},L):!0,this.attachedElements.forEach(j=>{detachTrack(this.mediaStreamTrack,j)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const V=(yield navigator.mediaDevices.getUserMedia(O)).getTracks()[0];return this.kind===Track.Kind.Video&&(yield V.applyConstraints(L)),V.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(V),this._constraints=n,this.emit(TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{P()}})}setTrackMuted(n){this.log.debug("setting ".concat(this.kind," track ").concat(n?"muted":"unmuted"),this.logContext),!(this.isMuted===n&&this._mediaStreamTrack.enabled!==n)&&(this.isMuted=n,this._mediaStreamTrack.enabled=!n,this.emit(n?TrackEvent.Muted:TrackEvent.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const n=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return __awaiter(this,void 0,void 0,function*(){yield n.handleAppVisibilityChanged.call(this),isMobile()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var n;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(n=this.processor)===null||n===void 0||n.destroy(),this.processor=void 0}pauseUpstream(){return __awaiter(this,void 0,void 0,function*(){var n;const P=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(TrackEvent.UpstreamPaused,this);const R=getBrowser();if(R?.name==="Safari"&&compareVersions(R.version,"12.0")<0)throw new DeviceUnsupportedError("pauseUpstream is not supported on Safari < 12.");((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{P()}})}resumeUpstream(){return __awaiter(this,void 0,void 0,function*(){var n;const P=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(TrackEvent.UpstreamResumed,this),((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{P()}})}getRTCStatsReport(){return __awaiter(this,void 0,void 0,function*(){var n;return!((n=this.sender)===null||n===void 0)&&n.getStats?yield this.sender.getStats():void 0})}setProcessor(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var L;const O=yield R.trackChangeLock.lock();try{R.log.debug("setting up processor",R.logContext);const N=document.createElement(R.kind),V={kind:R.kind,track:R._mediaStreamTrack,element:N,audioContext:R.audioContext};if(yield P.init(V),R.log.debug("processor initialized",R.logContext),R.processor&&(yield R.internalStopProcessor()),R.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(attachToElement(R._mediaStreamTrack,N),N.muted=!0,N.play().catch(j=>{j instanceof DOMException&&j.name==="AbortError"?(R.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},R.logContext),{error:j})),setTimeout(()=>{N.play().catch(B=>{R.log.error("failed to play processor element",Object.assign(Object.assign({},R.logContext),{err:B}))})},100)):R.log.error("failed to play processor element",Object.assign(Object.assign({},R.logContext),{error:j}))}),R.processor=P,R.processorElement=N,R.processor.processedTrack){for(const j of R.attachedElements)j!==R.processorElement&&A&&(detachTrack(R._mediaStreamTrack,j),attachToElement(R.processor.processedTrack,j));yield(L=R.sender)===null||L===void 0?void 0:L.replaceTrack(R.processor.processedTrack)}R.emit(TrackEvent.TrackProcessorUpdate,R.processor)}finally{O()}})()})}getProcessor(){return this.processor}stopProcessor(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const R=yield n.trackChangeLock.lock();try{yield n.internalStopProcessor(P)}finally{R()}})()})}internalStopProcessor(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var R,A;n.processor&&(n.log.debug("stopping processor",n.logContext),(R=n.processor.processedTrack)===null||R===void 0||R.stop(),yield n.processor.destroy(),n.processor=void 0,P||((A=n.processorElement)===null||A===void 0||A.remove(),n.processorElement=void 0),yield n._mediaStreamTrack.applyConstraints(n._constraints),yield n.setMediaStreamTrack(n._mediaStreamTrack,!0),n.emit(TrackEvent.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!isRecordingSupported()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let P="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(P)||(P="video/mp4"),this.localTrackRecorder=new LocalTrackRecorder(this,{mimeType:P})}this.localTrackRecorder.start(n),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},PRE_CONNECT_BUFFER_TIMEOUT)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var n;return(n=this.localTrackRecorder)===null||n===void 0?void 0:n.byteStream}getPreConnectBufferMimeType(){var n;return(n=this.localTrackRecorder)===null||n===void 0?void 0:n.mimeType}}class LocalAudioTrack extends LocalTrack{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(n,P){let R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,A=arguments.length>3?arguments[3]:void 0,L=arguments.length>4?arguments[4]:void 0;super(n,Track.Kind.Audio,P,R,L),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>__awaiter(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let O;try{O=yield this.getSenderStats()}catch(N){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:N}));return}O&&this.prevStats&&(this._currentBitrate=computeBitrate(O,this.prevStats)),this.prevStats=O}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(TrackEvent.AudioTrackFeatureUpdate,this,AudioTrackFeature.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(TrackEvent.AudioTrackFeatureUpdate,this,AudioTrackFeature.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=A,this.checkForSilence()}mute(){const n=Object.create(null,{mute:{get:()=>super.mute}});return __awaiter(this,void 0,void 0,function*(){const P=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Track.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield n.mute.call(this),this)}finally{P()}})}unmute(){const n=Object.create(null,{unmute:{get:()=>super.unmute}});return __awaiter(this,void 0,void 0,function*(){const P=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const R=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==unwrapConstraint(this._constraints.deviceId);return this.source===Track.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||R)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield n.unmute.call(this),this}finally{P()}})}restartTrack(n){return __awaiter(this,void 0,void 0,function*(){let P;if(n){const R=constraintsForOptions({audio:n});typeof R.audio!="boolean"&&(P=R.audio)}yield this.restart(P)})}restart(n){const P=Object.create(null,{restart:{get:()=>super.restart}});return __awaiter(this,void 0,void 0,function*(){const R=yield P.restart.call(this,n);return this.checkForSilence(),R})}startMonitor(){isWeb()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},monitorFrequency)))}setProcessor(n){return __awaiter(this,void 0,void 0,function*(){var P;const R=yield this.trackChangeLock.lock();try{if(!isReactNative$1()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const A={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(n.name),this.logContext),yield n.init(A),this.processor=n,this.processor.processedTrack&&(yield(P=this.sender)===null||P===void 0?void 0:P.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(TrackEvent.TrackProcessorUpdate,this.processor)}finally{R()}})}setAudioContext(n){this.audioContext=n}getSenderStats(){return __awaiter(this,void 0,void 0,function*(){var n;if(!(!((n=this.sender)===null||n===void 0)&&n.getStats))return;const P=yield this.sender.getStats();let R;return P.forEach(A=>{A.type==="outbound-rtp"&&(R={type:"audio",streamId:A.id,packetsSent:A.packetsSent,packetsLost:A.packetsLost,bytesSent:A.bytesSent,timestamp:A.timestamp,roundTripTime:A.roundTripTime,jitter:A.jitter})}),R})}checkForSilence(){return __awaiter(this,void 0,void 0,function*(){const n=yield detectSilence(this);return n&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(TrackEvent.AudioSilenceDetected)),n})}}function mediaTrackToLocalTrack(T,n,P){switch(T.kind){case"audio":return new LocalAudioTrack(T,n,!1,void 0,P);case"video":return new LocalVideoTrack(T,n,!1,P);default:throw new TrackInvalidError("unsupported track type: ".concat(T.kind))}}const presets169=Object.values(VideoPresets),presets43=Object.values(VideoPresets43),presetsScreenShare=Object.values(ScreenSharePresets),defaultSimulcastPresets169=[VideoPresets.h180,VideoPresets.h360],defaultSimulcastPresets43=[VideoPresets43.h180,VideoPresets43.h360],computeDefaultScreenShareSimulcastPresets=T=>[{scaleResolutionDownBy:2,fps:T.encoding.maxFramerate}].map(P=>{var R,A;return new VideoPreset(Math.floor(T.width/P.scaleResolutionDownBy),Math.floor(T.height/P.scaleResolutionDownBy),Math.max(15e4,Math.floor(T.encoding.maxBitrate/(Math.pow(P.scaleResolutionDownBy,2)*(((R=T.encoding.maxFramerate)!==null&&R!==void 0?R:30)/((A=P.fps)!==null&&A!==void 0?A:30))))),P.fps,T.encoding.priority)}),videoRids=["q","h","f"];function computeVideoEncodings(T,n,P,R){var A,L;let O=R?.videoEncoding;T&&(O=R?.screenShareEncoding);const N=R?.simulcast,V=R?.scalabilityMode,j=R?.videoCodec;if(!O&&!N&&!V||!n||!P)return[{}];O||(O=determineAppropriateEncoding(T,n,P,j),livekitLogger.debug("using video encoding",O));const B=O.maxFramerate,z=new VideoPreset(n,P,O.maxBitrate,O.maxFramerate,O.priority);if(V&&isSVCCodec(j)){const H=new ScalabilityMode(V),$=[];if(H.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(V));const Q=getBrowser();if(isSafariBased()||isReactNative$1()||Q?.name==="Chrome"&&compareVersions(Q?.version,"113")<0){const U=H.suffix=="h"?2:3,J=isSafariSvcApi(Q);for(let G=0;G<H.spatial;G+=1)$.push({rid:videoRids[2-G],maxBitrate:O.maxBitrate/Math.pow(U,G),maxFramerate:z.encoding.maxFramerate,scaleResolutionDownBy:J?Math.pow(2,G):void 0});$[0].scalabilityMode=V}else $.push({maxBitrate:O.maxBitrate,maxFramerate:z.encoding.maxFramerate,scalabilityMode:V});return z.encoding.priority&&($[0].priority=z.encoding.priority,$[0].networkPriority=z.encoding.priority),livekitLogger.debug("using svc encoding",{encodings:$}),$}if(!N)return[O];let W=[];T?W=(A=sortPresets(R?.screenShareSimulcastLayers))!==null&&A!==void 0?A:defaultSimulcastLayers(T,z):W=(L=sortPresets(R?.videoSimulcastLayers))!==null&&L!==void 0?L:defaultSimulcastLayers(T,z);let q;if(W.length>0){const H=W[0];W.length>1&&([,q]=W);const $=Math.max(n,P);if($>=960&&q)return encodingsFromPresets(n,P,[H,q,z],B);if($>=480)return encodingsFromPresets(n,P,[H,z],B)}return encodingsFromPresets(n,P,[z])}function computeTrackBackupEncodings(T,n,P){var R,A,L,O;if(!P.backupCodec||P.backupCodec===!0||P.backupCodec.codec===P.videoCodec)return;n!==P.backupCodec.codec&&livekitLogger.warn("requested a different codec than specified as backup",{serverRequested:n,backup:P.backupCodec.codec}),P.videoCodec=n,P.videoEncoding=P.backupCodec.encoding;const N=T.mediaStreamTrack.getSettings(),V=(R=N.width)!==null&&R!==void 0?R:(A=T.dimensions)===null||A===void 0?void 0:A.width,j=(L=N.height)!==null&&L!==void 0?L:(O=T.dimensions)===null||O===void 0?void 0:O.height;return T.source===Track.Source.ScreenShare&&P.simulcast&&(P.simulcast=!1),computeVideoEncodings(T.source===Track.Source.ScreenShare,V,j,P)}function determineAppropriateEncoding(T,n,P,R){const A=presetsForResolution(T,n,P);let{encoding:L}=A[0];const O=Math.max(n,P);for(let N=0;N<A.length;N+=1){const V=A[N];if(L=V.encoding,V.width>=O)break}if(R)switch(R){case"av1":case"h265":L=Object.assign({},L),L.maxBitrate=L.maxBitrate*.7;break;case"vp9":L=Object.assign({},L),L.maxBitrate=L.maxBitrate*.85;break}return L}function presetsForResolution(T,n,P){if(T)return presetsScreenShare;const R=n>P?n/P:P/n;return Math.abs(R-16/9)<Math.abs(R-4/3)?presets169:presets43}function defaultSimulcastLayers(T,n){if(T)return computeDefaultScreenShareSimulcastPresets(n);const{width:P,height:R}=n,A=P>R?P/R:R/P;return Math.abs(A-16/9)<Math.abs(A-4/3)?defaultSimulcastPresets169:defaultSimulcastPresets43}function encodingsFromPresets(T,n,P,R){const A=[];if(P.forEach((L,O)=>{if(O>=videoRids.length)return;const N=Math.min(T,n),j={rid:videoRids[O],scaleResolutionDownBy:Math.max(1,N/Math.min(L.width,L.height)),maxBitrate:L.encoding.maxBitrate},B=R&&L.encoding.maxFramerate?Math.min(R,L.encoding.maxFramerate):L.encoding.maxFramerate;B&&(j.maxFramerate=B);const z=isFireFox()||O===0;L.encoding.priority&&z&&(j.priority=L.encoding.priority,j.networkPriority=L.encoding.priority),A.push(j)}),isReactNative$1()&&getReactNativeOs()==="ios"){let L;A.forEach(N=>{L?N.maxFramerate&&N.maxFramerate>L&&(L=N.maxFramerate):L=N.maxFramerate});let O=!0;A.forEach(N=>{var V;N.maxFramerate!=L&&(O&&(O=!1,livekitLogger.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),livekitLogger.info('Setting framerate of encoding "'.concat((V=N.rid)!==null&&V!==void 0?V:"",'" to ').concat(L)),N.maxFramerate=L)})}return A}function sortPresets(T){if(T)return T.sort((n,P)=>{const{encoding:R}=n,{encoding:A}=P;return R.maxBitrate>A.maxBitrate?1:R.maxBitrate<A.maxBitrate?-1:R.maxBitrate===A.maxBitrate&&R.maxFramerate&&A.maxFramerate?R.maxFramerate>A.maxFramerate?1:-1:0})}class ScalabilityMode{constructor(n){const P=n.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!P)throw new Error("invalid scalability mode");if(this.spatial=parseInt(P[1]),this.temporal=parseInt(P[2]),P.length>3)switch(P[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=P[3]}}toString(){var n;return"L".concat(this.spatial,"T").concat(this.temporal).concat((n=this.suffix)!==null&&n!==void 0?n:"")}}function getDefaultDegradationPreference(T){return T.source===Track.Source.ScreenShare||T.constraints.height&&unwrapConstraint(T.constraints.height)>=1080?"maintain-resolution":"balanced"}const refreshSubscribedCodecAfterNewCodec=5e3;class LocalVideoTrack extends LocalTrack{get sender(){return this._sender}set sender(n){this._sender=n,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(n,P){let R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,A=arguments.length>3?arguments[3]:void 0;super(n,Track.Kind.Video,P,R,A),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>__awaiter(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let L;try{L=yield this.getSenderStats()}catch(V){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:V}));return}const O=new Map(L.map(V=>[V.rid,V])),N=L.some(V=>V.qualityLimitationReason==="cpu");if(N!==this.isCpuConstrained&&(this.isCpuConstrained=N,this.isCpuConstrained&&this.emit(TrackEvent.CpuConstrained)),this.prevStats){let V=0;O.forEach((j,B)=>{var z;const W=(z=this.prevStats)===null||z===void 0?void 0:z.get(B);V+=computeBitrate(j,W)}),this._currentBitrate=V}this.prevStats=O}),this.senderLock=new _$1}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(n){var P;if(this.signalClient=n,!isWeb())return;const R=(P=this.sender)===null||P===void 0?void 0:P.getParameters();R&&(this.encodings=R.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},monitorFrequency))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(n=>{n.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const n=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return __awaiter(this,void 0,void 0,function*(){var P,R,A,L,O;yield n.pauseUpstream.call(this);try{for(var N=!0,V=__asyncValues(this.simulcastCodecs.values()),j;j=yield V.next(),P=j.done,!P;N=!0)L=j.value,N=!1,yield(O=L.sender)===null||O===void 0?void 0:O.replaceTrack(null)}catch(B){R={error:B}}finally{try{!N&&!P&&(A=V.return)&&(yield A.call(V))}finally{if(R)throw R.error}}})}resumeUpstream(){const n=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return __awaiter(this,void 0,void 0,function*(){var P,R,A,L,O;yield n.resumeUpstream.call(this);try{for(var N=!0,V=__asyncValues(this.simulcastCodecs.values()),j;j=yield V.next(),P=j.done,!P;N=!0){L=j.value,N=!1;const B=L;yield(O=B.sender)===null||O===void 0?void 0:O.replaceTrack(B.mediaStreamTrack)}}catch(B){R={error:B}}finally{try{!N&&!P&&(A=V.return)&&(yield A.call(V))}finally{if(R)throw R.error}}})}mute(){const n=Object.create(null,{mute:{get:()=>super.mute}});return __awaiter(this,void 0,void 0,function*(){const P=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Track.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield n.mute.call(this),this)}finally{P()}})}unmute(){const n=Object.create(null,{unmute:{get:()=>super.unmute}});return __awaiter(this,void 0,void 0,function*(){const P=yield this.muteLock.lock();try{return this.isMuted?(this.source===Track.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield n.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{P()}})}setTrackMuted(n){super.setTrackMuted(n);for(const P of this.simulcastCodecs.values())P.mediaStreamTrack.enabled=!n}getSenderStats(){return __awaiter(this,void 0,void 0,function*(){var n;if(!(!((n=this.sender)===null||n===void 0)&&n.getStats))return[];const P=[],R=yield this.sender.getStats();return R.forEach(A=>{var L;if(A.type==="outbound-rtp"){const O={type:"video",streamId:A.id,frameHeight:A.frameHeight,frameWidth:A.frameWidth,framesPerSecond:A.framesPerSecond,framesSent:A.framesSent,firCount:A.firCount,pliCount:A.pliCount,nackCount:A.nackCount,packetsSent:A.packetsSent,bytesSent:A.bytesSent,qualityLimitationReason:A.qualityLimitationReason,qualityLimitationDurations:A.qualityLimitationDurations,qualityLimitationResolutionChanges:A.qualityLimitationResolutionChanges,rid:(L=A.rid)!==null&&L!==void 0?L:A.id,retransmittedPacketsSent:A.retransmittedPacketsSent,targetBitrate:A.targetBitrate,timestamp:A.timestamp},N=R.get(A.remoteId);N&&(O.jitter=N.jitter,O.packetsLost=N.packetsLost,O.roundTripTime=N.roundTripTime),P.push(O)}}),P.sort((A,L)=>{var O,N;return((O=L.frameWidth)!==null&&O!==void 0?O:0)-((N=A.frameWidth)!==null&&N!==void 0?N:0)}),P})}setPublishingQuality(n){const P=[];for(let R=VideoQuality.LOW;R<=VideoQuality.HIGH;R+=1)P.push(new SubscribedQuality({quality:R,enabled:R<=n}));this.log.debug("setting publishing quality. max quality ".concat(n),this.logContext),this.setPublishingLayers(isSVCCodec(this.codec),P)}restartTrack(n){return __awaiter(this,void 0,void 0,function*(){var P,R,A,L,O;let N;if(n){const z=constraintsForOptions({video:n});typeof z.video!="boolean"&&(N=z.video)}yield this.restart(N),this.isCpuConstrained=!1;try{for(var V=!0,j=__asyncValues(this.simulcastCodecs.values()),B;B=yield j.next(),P=B.done,!P;V=!0){L=B.value,V=!1;const z=L;z.sender&&((O=z.sender.transport)===null||O===void 0?void 0:O.state)!=="closed"&&(z.mediaStreamTrack=this.mediaStreamTrack.clone(),yield z.sender.replaceTrack(z.mediaStreamTrack))}}catch(z){R={error:z}}finally{try{!V&&!P&&(A=j.return)&&(yield A.call(j))}finally{if(R)throw R.error}}})}setProcessor(n){const P=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return __awaiter(this,arguments,void 0,function(R){var A=this;let L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var O,N,V,j,B,z;if(yield P.setProcessor.call(A,R,L),!((B=A.processor)===null||B===void 0)&&B.processedTrack)try{for(var W=!0,q=__asyncValues(A.simulcastCodecs.values()),H;H=yield q.next(),O=H.done,!O;W=!0)j=H.value,W=!1,yield(z=j.sender)===null||z===void 0?void 0:z.replaceTrack(A.processor.processedTrack)}catch($){N={error:$}}finally{try{!W&&!O&&(V=q.return)&&(yield V.call(q))}finally{if(N)throw N.error}}})()})}setDegradationPreference(n){return __awaiter(this,void 0,void 0,function*(){if(this.degradationPreference=n,this.sender)try{this.log.debug("setting degradationPreference to ".concat(n),this.logContext);const P=this.sender.getParameters();P.degradationPreference=n,this.sender.setParameters(P)}catch(P){this.log.warn("failed to set degradationPreference",Object.assign({error:P},this.logContext))}})}addSimulcastTrack(n,P){if(this.simulcastCodecs.has(n)){this.log.error("".concat(n," already added, skipping adding simulcast codec"),this.logContext);return}const R={codec:n,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:P};return this.simulcastCodecs.set(n,R),R}setSimulcastTrackSender(n,P){const R=this.simulcastCodecs.get(n);R&&(R.sender=P,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},refreshSubscribedCodecAfterNewCodec))}setPublishingCodecs(n){return __awaiter(this,void 0,void 0,function*(){var P,R,A,L,O,N,V;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:n,currentCodec:this.codec})),!this.codec&&n.length>0)return yield this.setPublishingLayers(isSVCCodec(n[0].codec),n[0].qualities),[];this.subscribedCodecs=n;const j=[];try{for(P=!0,R=__asyncValues(n);A=yield R.next(),L=A.done,!L;P=!0){V=A.value,P=!1;const B=V;if(!this.codec||this.codec===B.codec)yield this.setPublishingLayers(isSVCCodec(B.codec),B.qualities);else{const z=this.simulcastCodecs.get(B.codec);if(this.log.debug("try setPublishingCodec for ".concat(B.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:z})),!z||!z.sender){for(const W of B.qualities)if(W.enabled){j.push(B.codec);break}}else z.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(B.codec),this.logContext),yield setPublishingLayersForSender(z.sender,z.encodings,B.qualities,this.senderLock,isSVCCodec(B.codec),this.log,this.logContext))}}}catch(B){O={error:B}}finally{try{!P&&!L&&(N=R.return)&&(yield N.call(R))}finally{if(O)throw O.error}}return j})}setPublishingLayers(n,P){return __awaiter(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:P}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:P})),!(!this.sender||!this.encodings)&&(yield setPublishingLayersForSender(this.sender,this.encodings,P,this.senderLock,n,this.log,this.logContext))})}prioritizePerformance(){return __awaiter(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const n=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const P=this.sender.getParameters();P.encodings=P.encodings.map((R,A)=>{var L;return Object.assign(Object.assign({},R),{active:A===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((L=this.mediaStreamTrack.getSettings().height)!==null&&L!==void 0?L:360)/360)),scalabilityMode:A===0&&isSVCCodec(this.codec)?"L1T3":void 0,maxFramerate:A===0?15:0,maxBitrate:A===0?R.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:P.encodings})),this.encodings=P.encodings,yield this.sender.setParameters(P)}catch(P){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:P})),this.optimizeForPerformance=!1}finally{n()}})}handleAppVisibilityChanged(){const n=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return __awaiter(this,void 0,void 0,function*(){yield n.handleAppVisibilityChanged.call(this),isMobile()&&this.isInBackground&&this.source===Track.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function setPublishingLayersForSender(T,n,P,R,A,L,O){return __awaiter(this,void 0,void 0,function*(){const N=yield R.lock();L.debug("setPublishingLayersForSender",Object.assign(Object.assign({},O),{sender:T,qualities:P,senderEncodings:n}));try{const V=T.getParameters(),{encodings:j}=V;if(!j)return;if(j.length!==n.length){L.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},O),{encodings:j,senderEncodings:n}));return}let B=!1;!1&&j[0].scalabilityMode||(A&&P.some(q=>q.enabled)&&P.forEach(q=>q.enabled=!0),j.forEach((W,q)=>{var H;let $=(H=W.rid)!==null&&H!==void 0?H:"";$===""&&($="q");const Q=videoQualityForRid($),U=P.find(J=>J.quality===Q);U&&W.active!==U.enabled&&(B=!0,W.active=U.enabled,L.debug("setting layer ".concat(U.quality," to ").concat(W.active?"enabled":"disabled"),O),isFireFox()&&(U.enabled?(W.scaleResolutionDownBy=n[q].scaleResolutionDownBy,W.maxBitrate=n[q].maxBitrate,W.maxFrameRate=n[q].maxFrameRate):(W.scaleResolutionDownBy=4,W.maxBitrate=10,W.maxFrameRate=2)))})),B&&(V.encodings=j,L.debug("setting encodings",Object.assign(Object.assign({},O),{encodings:V.encodings})),yield T.setParameters(V))}finally{N()}})}function videoQualityForRid(T){switch(T){case"f":return VideoQuality.HIGH;case"h":return VideoQuality.MEDIUM;case"q":return VideoQuality.LOW;default:return VideoQuality.HIGH}}function videoLayersFromEncodings(T,n,P,R){if(!P)return[new VideoLayer({quality:VideoQuality.HIGH,width:T,height:n,bitrate:0,ssrc:0})];if(R){const A=P[0].scalabilityMode,L=new ScalabilityMode(A),O=[],N=L.suffix=="h"?1.5:2,V=L.suffix=="h"?2:3;for(let j=0;j<L.spatial;j+=1)O.push(new VideoLayer({quality:Math.min(VideoQuality.HIGH,L.spatial-1)-j,width:Math.ceil(T/Math.pow(N,j)),height:Math.ceil(n/Math.pow(N,j)),bitrate:P[0].maxBitrate?Math.ceil(P[0].maxBitrate/Math.pow(V,j)):0,ssrc:0}));return O}return P.map(A=>{var L,O,N;const V=(L=A.scaleResolutionDownBy)!==null&&L!==void 0?L:1;let j=videoQualityForRid((O=A.rid)!==null&&O!==void 0?O:"");return new VideoLayer({quality:j,width:Math.ceil(T/V),height:Math.ceil(n/V),bitrate:(N=A.maxBitrate)!==null&&N!==void 0?N:0,ssrc:0})})}const lossyDataChannel="_lossy",reliableDataChannel="_reliable",minReconnectWait=2*1e3,leaveReconnect="leave-reconnect",reliabeReceiveStateTTL=3e4;var PCState;(function(T){T[T.New=0]="New",T[T.Connected=1]="Connected",T[T.Disconnected=2]="Disconnected",T[T.Reconnecting=3]="Reconnecting",T[T.Closed=4]="Closed"})(PCState||(PCState={}));class RTCEngine extends eventsExports.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(n){var P;super(),this.options=n,this.rtcConfig={},this.peerConnectionTimeout=roomConnectOptionDefaults.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=PCState.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=livekitLogger,this.reliableDataSequence=1,this.reliableMessageBuffer=new DataPacketBuffer,this.reliableReceivedState=new TTLMap(reliabeReceiveStateTTL),this.handleDataChannel=R=>__awaiter(this,[R],void 0,function(A){var L=this;let{channel:O}=A;return(function*(){if(O){if(O.label===reliableDataChannel)L.reliableDCSub=O;else if(O.label===lossyDataChannel)L.lossyDCSub=O;else return;L.log.debug("on data channel ".concat(O.id,", ").concat(O.label),L.logContext),O.onmessage=L.handleDataMessage}})()}),this.handleDataMessage=R=>__awaiter(this,void 0,void 0,function*(){var A,L;const O=yield this.dataProcessLock.lock();try{let N;if(R.data instanceof ArrayBuffer)N=R.data;else if(R.data instanceof Blob)N=yield R.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:R.data}));return}const V=DataPacket.fromBinary(new Uint8Array(N));if(V.sequence>0&&V.participantSid!==""){const j=this.reliableReceivedState.get(V.participantSid);if(j&&V.sequence<=j)return;this.reliableReceivedState.set(V.participantSid,V.sequence)}((A=V.value)===null||A===void 0?void 0:A.case)==="speaker"?this.emit(EngineEvent.ActiveSpeakersUpdate,V.value.value.speakers):(((L=V.value)===null||L===void 0?void 0:L.case)==="user"&&applyUserDataCompat(V,V.value.value),this.emit(EngineEvent.DataPacketReceived,V))}finally{O()}}),this.handleDataError=R=>{const L=R.currentTarget.maxRetransmits===0?"lossy":"reliable";if(R instanceof ErrorEvent&&R.error){const{error:O}=R.error;this.log.error("DataChannel error on ".concat(L,": ").concat(R.message),Object.assign(Object.assign({},this.logContext),{error:O}))}else this.log.error("Unknown DataChannel error on ".concat(L),Object.assign(Object.assign({},this.logContext),{event:R}))},this.handleBufferedAmountLow=R=>{const L=R.currentTarget.maxRetransmits===0?DataPacket_Kind.LOSSY:DataPacket_Kind.RELIABLE;this.updateAndEmitDCBufferStatus(L)},this.handleDisconnect=(R,A)=>{if(this._isClosed)return;this.log.warn("".concat(R," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const L=V=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(V,"ms. giving up"),this.logContext),this.emit(EngineEvent.Disconnected),this.close()},O=Date.now()-this.reconnectStart;let N=this.getNextRetryDelay({elapsedMs:O,retryCount:this.reconnectAttempts});if(N===null){L(O);return}R===leaveReconnect&&(N=0),this.log.debug("reconnecting in ".concat(N,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=CriticalTimers.setTimeout(()=>this.attemptReconnect(A).finally(()=>this.reconnectTimeout=void 0),N)},this.waitForRestarted=()=>new Promise((R,A)=>{this.pcState===PCState.Connected&&R();const L=()=>{this.off(EngineEvent.Disconnected,O),R()},O=()=>{this.off(EngineEvent.Restarted,L),A()};this.once(EngineEvent.Restarted,L),this.once(EngineEvent.Disconnected,O)}),this.updateAndEmitDCBufferStatus=R=>{const A=this.isBufferStatusLow(R);typeof A<"u"&&A!==this.dcBufferStatus.get(R)&&(this.dcBufferStatus.set(R,A),this.emit(EngineEvent.DCBufferStatusChanged,A,R))},this.isBufferStatusLow=R=>{const A=this.dataChannelForKind(R);if(A)return R===DataPacket_Kind.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(A.bufferedAmount),A.bufferedAmount<=A.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===SignalConnectionState.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ReconnectReason.RR_SIGNAL_DISCONNECTED))},this.log=getLogger((P=n.loggerName)!==null&&P!==void 0?P:LoggerNames.Engine),this.loggerOptions={loggerName:n.loggerName,loggerContextCb:()=>this.logContext},this.client=new SignalClient(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new _$1,this.dataProcessLock=new _$1,this.dcBufferStatus=new Map([[DataPacket_Kind.LOSSY,!0],[DataPacket_Kind.RELIABLE,!0]]),this.client.onParticipantUpdate=R=>this.emit(EngineEvent.ParticipantUpdate,R),this.client.onConnectionQuality=R=>this.emit(EngineEvent.ConnectionQualityUpdate,R),this.client.onRoomUpdate=R=>this.emit(EngineEvent.RoomUpdate,R),this.client.onSubscriptionError=R=>this.emit(EngineEvent.SubscriptionError,R),this.client.onSubscriptionPermissionUpdate=R=>this.emit(EngineEvent.SubscriptionPermissionUpdate,R),this.client.onSpeakersChanged=R=>this.emit(EngineEvent.SpeakersChanged,R),this.client.onStreamStateUpdate=R=>this.emit(EngineEvent.StreamStateChanged,R),this.client.onRequestResponse=R=>this.emit(EngineEvent.SignalRequestResponse,R)}get logContext(){var n,P,R,A,L,O;return{room:(P=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||P===void 0?void 0:P.name,roomID:(A=(R=this.latestJoinResponse)===null||R===void 0?void 0:R.room)===null||A===void 0?void 0:A.sid,participant:(O=(L=this.latestJoinResponse)===null||L===void 0?void 0:L.participant)===null||O===void 0?void 0:O.identity,pID:this.participantSid}}join(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){this.url=n,this.token=P,this.signalOpts=R,this.maxJoinAttempts=R.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const L=yield this.client.join(n,P,R,A);return this._isClosed=!1,this.latestJoinResponse=L,this.subscriberPrimary=L.subscriberPrimary,this.pcManager||(yield this.configure(L)),(!this.subscriberPrimary||L.fastPublish)&&this.negotiate(),this.clientConfiguration=L.clientConfiguration,this.emit(EngineEvent.SignalConnected,L),L}catch(L){if(L instanceof ConnectionError&&L.reason===ConnectionErrorReason.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(n,P,R,A);throw L}})}close(){return __awaiter(this,void 0,void 0,function*(){const n=yield this.closingLock.lock();if(this.isClosed){n();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{n()}})}cleanupPeerConnections(){return __awaiter(this,void 0,void 0,function*(){var n;yield(n=this.pcManager)===null||n===void 0?void 0:n.close(),this.pcManager=void 0;const P=R=>{R&&(R.close(),R.onbufferedamountlow=null,R.onclose=null,R.onclosing=null,R.onerror=null,R.onmessage=null,R.onopen=null)};P(this.lossyDC),P(this.lossyDCSub),P(this.reliableDC),P(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new DataPacketBuffer,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return __awaiter(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(n){if(this.pendingTrackResolvers[n.cid])throw new TrackInvalidError("a track with the same ID has already been published");return new Promise((P,R)=>{const A=setTimeout(()=>{delete this.pendingTrackResolvers[n.cid],R(new ConnectionError("publication of local track timed out, no response from server",ConnectionErrorReason.Timeout))},1e4);this.pendingTrackResolvers[n.cid]={resolve:L=>{clearTimeout(A),P(L)},reject:()=>{clearTimeout(A),R(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(n)})}removeTrack(n){if(n.track&&this.pendingTrackResolvers[n.track.id]){const{reject:P}=this.pendingTrackResolvers[n.track.id];P&&P(),delete this.pendingTrackResolvers[n.track.id]}try{return this.pcManager.removeTrack(n),!0}catch(P){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:P}))}return!1}updateMuteStatus(n,P){this.client.sendMuteTrack(n,P)}get dataSubscriberReadyState(){var n;return(n=this.reliableDCSub)===null||n===void 0?void 0:n.readyState}getConnectedServerAddress(){return __awaiter(this,void 0,void 0,function*(){var n;return(n=this.pcManager)===null||n===void 0?void 0:n.getConnectedAddress()})}setRegionUrlProvider(n){this.regionUrlProvider=n}configure(n){return __awaiter(this,void 0,void 0,function*(){var P,R;if(this.pcManager&&this.pcManager.currentState!==PCTransportState.NEW)return;this.participantSid=(P=n.participant)===null||P===void 0?void 0:P.sid;const A=this.makeRTCConfiguration(n);this.pcManager=new PCTransportManager(A,n.subscriberPrimary,this.loggerOptions),this.emit(EngineEvent.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(L,O)=>{this.client.sendIceCandidate(L,O)},this.pcManager.onPublisherOffer=(L,O)=>{this.client.sendOffer(L,O)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(L,O,N)=>__awaiter(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(L),this.logContext),["closed","disconnected","failed"].includes(O)&&(this.publisherConnectionPromise=void 0),L===PCTransportState.CONNECTED){const B=this.pcState===PCState.New;this.pcState=PCState.Connected,B&&this.emit(EngineEvent.Connected,n)}else L===PCTransportState.FAILED&&this.pcState===PCState.Connected&&(this.pcState=PCState.Disconnected,this.handleDisconnect("peerconnection failed",N==="failed"?ReconnectReason.RR_SUBSCRIBER_FAILED:ReconnectReason.RR_PUBLISHER_FAILED));const V=this.client.isDisconnected||this.client.currentState===SignalConnectionState.RECONNECTING,j=[PCTransportState.FAILED,PCTransportState.CLOSING,PCTransportState.CLOSED].includes(L);V&&j&&!this._isClosed&&this.emit(EngineEvent.Offline)}),this.pcManager.onTrack=L=>{this.emit(EngineEvent.MediaTrackAdded,L.track,L.streams[0],L.receiver)},supportOptionalDatachannel((R=n.serverInfo)===null||R===void 0?void 0:R.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(n,P)=>__awaiter(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:n.type})),yield this.pcManager.setPublisherAnswer(n,P))}),this.client.onTrickle=(n,P)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:n,target:P})),this.pcManager.addIceCandidate(n,P))},this.client.onOffer=(n,P)=>__awaiter(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=P,!this.pcManager)return;const R=yield this.pcManager.createSubscriberAnswerFromOffer(n,P);R&&this.client.sendAnswer(R,P)}),this.client.onLocalTrackPublished=n=>{var P;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:n.cid,track:(P=n.track)===null||P===void 0?void 0:P.sid})),!this.pendingTrackResolvers[n.cid]){this.log.error("missing track resolver for ".concat(n.cid),Object.assign(Object.assign({},this.logContext),{cid:n.cid}));return}const{resolve:R}=this.pendingTrackResolvers[n.cid];delete this.pendingTrackResolvers[n.cid],R(n.track)},this.client.onLocalTrackUnpublished=n=>{this.emit(EngineEvent.LocalTrackUnpublished,n)},this.client.onLocalTrackSubscribed=n=>{this.emit(EngineEvent.LocalTrackSubscribed,n)},this.client.onTokenRefresh=n=>{this.token=n},this.client.onRemoteMuteChanged=(n,P)=>{this.emit(EngineEvent.RemoteMute,n,P)},this.client.onSubscribedQualityUpdate=n=>{this.emit(EngineEvent.SubscribedQualityUpdate,n)},this.client.onRoomMoved=n=>{var P;this.participantSid=(P=n.participant)===null||P===void 0?void 0:P.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=n.room),this.emit(EngineEvent.RoomMoved,n)},this.client.onClose=()=>{this.handleDisconnect("signal",ReconnectReason.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=n=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:n?.reason})),n.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(n.regions)),n.action){case LeaveRequest_Action.DISCONNECT:this.emit(EngineEvent.Disconnected,n?.reason),this.close();break;case LeaveRequest_Action.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(leaveReconnect);break;case LeaveRequest_Action.RESUME:this.handleDisconnect(leaveReconnect)}}}makeRTCConfiguration(n){var P;const R=Object.assign({},this.rtcConfig);if(!((P=this.signalOpts)===null||P===void 0)&&P.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),R.encodedInsertableStreams=!0),n.iceServers&&!R.iceServers){const A=[];n.iceServers.forEach(L=>{const O={urls:L.urls};L.username&&(O.username=L.username),L.credential&&(O.credential=L.credential),A.push(O)}),R.iceServers=A}return n.clientConfiguration&&n.clientConfiguration.forceRelay===ClientConfigSetting.ENABLED&&(R.iceTransportPolicy="relay"),R.sdpSemantics="unified-plan",R.continualGatheringPolicy="gather_continually",R}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(lossyDataChannel,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(reliableDataChannel,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(n,P,R){return __awaiter(this,void 0,void 0,function*(){if(supportsTransceiver())return yield this.createTransceiverRTCRtpSender(n,P,R);if(supportsAddTrack())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(n.mediaStreamTrack);throw new UnexpectedConnectionState("Required webRTC APIs not supported on this device")})}createSimulcastSender(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){if(supportsTransceiver())return this.createSimulcastTransceiverSender(n,P,R,A);if(supportsAddTrack())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(n.mediaStreamTrack);throw new UnexpectedConnectionState("Cannot stream on this device")})}createTransceiverRTCRtpSender(n,P,R){return __awaiter(this,void 0,void 0,function*(){if(!this.pcManager)throw new UnexpectedConnectionState("publisher is closed");const A=[];n.mediaStream&&A.push(n.mediaStream),isVideoTrack(n)&&(n.codec=P.videoCodec);const L={direction:"sendonly",streams:A};return R&&(L.sendEncodings=R),(yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,L)).sender})}createSimulcastTransceiverSender(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){if(!this.pcManager)throw new UnexpectedConnectionState("publisher is closed");const L={direction:"sendonly"};A&&(L.sendEncodings=A);const O=yield this.pcManager.addPublisherTransceiver(P.mediaStreamTrack,L);if(R.videoCodec)return n.setSimulcastTrackSender(R.videoCodec,O.sender),O.sender})}createRTCRtpSender(n){return __awaiter(this,void 0,void 0,function*(){if(!this.pcManager)throw new UnexpectedConnectionState("publisher is closed");return this.pcManager.addPublisherTrack(n)})}attemptReconnect(n){return __awaiter(this,void 0,void 0,function*(){var P,R,A;if(!this._isClosed){if(this.attemptingReconnect){livekitLogger.warn("already attempting reconnect, returning early",this.logContext);return}(((P=this.clientConfiguration)===null||P===void 0?void 0:P.resumeConnection)===ClientConfigSetting.DISABLED||((A=(R=this.pcManager)===null||R===void 0?void 0:R.currentState)!==null&&A!==void 0?A:PCTransportState.NEW)===PCTransportState.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(n),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(L){this.reconnectAttempts+=1;let O=!0;L instanceof UnexpectedConnectionState?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:L})),O=!1):L instanceof SignalReconnectError||(this.fullReconnectOnNext=!0),O?this.handleDisconnect("reconnect",ReconnectReason.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(n){try{return this.reconnectPolicy.nextRetryDelayInMs(n)}catch(P){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:P}))}return null}restartConnection(n){return __awaiter(this,void 0,void 0,function*(){var P,R,A;try{if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let L;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new SignalReconnectError;L=yield this.join(n??this.url,this.token,this.signalOpts)}catch(O){throw O instanceof ConnectionError&&O.reason===ConnectionErrorReason.NotAllowed?new UnexpectedConnectionState("could not reconnect, token might be expired"):new SignalReconnectError}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(EngineEvent.SignalRestarted,L),yield this.waitForPCReconnected(),this.client.currentState!==SignalConnectionState.CONNECTED)throw new SignalReconnectError("Signal connection got severed during reconnect");(P=this.regionUrlProvider)===null||P===void 0||P.resetAttempts(),this.emit(EngineEvent.Restarted)}catch(L){const O=yield(R=this.regionUrlProvider)===null||R===void 0?void 0:R.getNextBestRegionUrl();if(O){yield this.restartConnection(O);return}else throw(A=this.regionUrlProvider)===null||A===void 0||A.resetAttempts(),L}})}resumeConnection(n){return __awaiter(this,void 0,void 0,function*(){var P;if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");if(!this.pcManager)throw new UnexpectedConnectionState("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(EngineEvent.Resuming);let R;try{this.setupSignalClientCallbacks(),R=yield this.client.reconnect(this.url,this.token,this.participantSid,n)}catch(A){let L="";throw A instanceof Error&&(L=A.message,this.log.error(A.message,Object.assign(Object.assign({},this.logContext),{error:A}))),A instanceof ConnectionError&&A.reason===ConnectionErrorReason.NotAllowed?new UnexpectedConnectionState("could not reconnect, token might be expired"):A instanceof ConnectionError&&A.reason===ConnectionErrorReason.LeaveRequest?A:new SignalReconnectError(L)}if(this.emit(EngineEvent.SignalResumed),R){const A=this.makeRTCConfiguration(R);this.pcManager.updateConfiguration(A),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=R.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==SignalConnectionState.CONNECTED)throw new SignalReconnectError("Signal connection got severed during reconnect");this.client.setReconnected(),((P=this.reliableDC)===null||P===void 0?void 0:P.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),R?.lastMessageSeq&&this.resendReliableMessagesForResume(R.lastMessageSeq),this.emit(EngineEvent.Resumed)})}waitForPCInitialConnection(n,P){return __awaiter(this,void 0,void 0,function*(){if(!this.pcManager)throw new UnexpectedConnectionState("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(P,n)})}waitForPCReconnected(){return __awaiter(this,void 0,void 0,function*(){this.pcState=PCState.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield sleep(minReconnectWait),!this.pcManager)throw new UnexpectedConnectionState("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=PCState.Connected}catch(n){throw this.pcState=PCState.Disconnected,new ConnectionError("could not establish PC connection, ".concat(n.message),ConnectionErrorReason.InternalError)}})}publishRpcResponse(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){const L=new DataPacket({destinationIdentities:[n],kind:DataPacket_Kind.RELIABLE,value:{case:"rpcResponse",value:new RpcResponse({requestId:P,value:A?{case:"error",value:A.toProto()}:{case:"payload",value:R??""}})}});yield this.sendDataPacket(L,DataPacket_Kind.RELIABLE)})}publishRpcAck(n,P){return __awaiter(this,void 0,void 0,function*(){const R=new DataPacket({destinationIdentities:[n],kind:DataPacket_Kind.RELIABLE,value:{case:"rpcAck",value:new RpcAck({requestId:P})}});yield this.sendDataPacket(R,DataPacket_Kind.RELIABLE)})}sendDataPacket(n,P){return __awaiter(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(P),P===DataPacket_Kind.RELIABLE&&(n.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const R=n.toBinary(),A=this.dataChannelForKind(P);if(A){if(P===DataPacket_Kind.RELIABLE&&this.reliableMessageBuffer.push({data:R,sequence:n.sequence}),this.attemptingReconnect)return;A.send(R)}this.updateAndEmitDCBufferStatus(P)})}resendReliableMessagesForResume(n){return __awaiter(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(DataPacket_Kind.RELIABLE);const P=this.dataChannelForKind(DataPacket_Kind.RELIABLE);P&&(this.reliableMessageBuffer.popToSequence(n),this.reliableMessageBuffer.getAll().forEach(R=>{P.send(R.data)})),this.updateAndEmitDCBufferStatus(DataPacket_Kind.RELIABLE)})}waitForBufferStatusLow(n){return new Promise((P,R)=>__awaiter(this,void 0,void 0,function*(){if(this.isBufferStatusLow(n))P();else{const A=()=>R("Engine closed");for(this.once(EngineEvent.Closing,A);!this.dcBufferStatus.get(n);)yield sleep(10);this.off(EngineEvent.Closing,A),P()}}))}ensureDataTransportConnected(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var L;if(!R.pcManager)throw new UnexpectedConnectionState("PC manager is closed");const O=A?R.pcManager.subscriber:R.pcManager.publisher,N=A?"Subscriber":"Publisher";if(!O)throw new ConnectionError("".concat(N," connection not set"),ConnectionErrorReason.InternalError);let V=!1;!A&&!R.dataChannelForKind(P,A)&&(R.createDataChannels(),V=!0),!V&&!A&&!R.pcManager.publisher.isICEConnected&&R.pcManager.publisher.getICEConnectionState()!=="checking"&&(V=!0),V&&R.negotiate();const j=R.dataChannelForKind(P,A);if(j?.readyState==="open")return;const B=new Date().getTime()+R.peerConnectionTimeout;for(;new Date().getTime()<B;){if(O.isICEConnected&&((L=R.dataChannelForKind(P,A))===null||L===void 0?void 0:L.readyState)==="open")return;yield sleep(50)}throw new ConnectionError("could not establish ".concat(N," connection, state: ").concat(O.getICEConnectionState()),ConnectionErrorReason.InternalError)})()})}ensurePublisherConnected(n){return __awaiter(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(n,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==PCTransportState.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return __awaiter(this,void 0,void 0,function*(){return new Promise((n,P)=>__awaiter(this,void 0,void 0,function*(){if(!this.pcManager){P(new NegotiationError("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const R=new AbortController,A=()=>{R.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),n()};this.isClosed&&P("cannot negotiate on closed engine"),this.on(EngineEvent.Closing,A),this.pcManager.publisher.once(PCEvents.RTPVideoPayloadTypes,L=>{const O=new Map;L.forEach(N=>{const V=N.codec.toLowerCase();isVideoCodec(V)&&O.set(N.payload,V)}),this.emit(EngineEvent.RTPVideoMapUpdate,O)});try{yield this.pcManager.negotiate(R),n()}catch(L){L instanceof NegotiationError&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ReconnectReason.RR_UNKNOWN),P(L)}finally{this.off(EngineEvent.Closing,A)}}))})}dataChannelForKind(n,P){if(P){if(n===DataPacket_Kind.LOSSY)return this.lossyDCSub;if(n===DataPacket_Kind.RELIABLE)return this.reliableDCSub}else{if(n===DataPacket_Kind.LOSSY)return this.lossyDC;if(n===DataPacket_Kind.RELIABLE)return this.reliableDC}}sendSyncState(n,P){var R,A;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const L=this.pcManager.subscriber.getLocalDescription(),O=this.pcManager.subscriber.getRemoteDescription(),N=(A=(R=this.signalOpts)===null||R===void 0?void 0:R.autoSubscribe)!==null&&A!==void 0?A:!0,V=new Array,j=new Array;n.forEach(B=>{B.isDesired!==N&&V.push(B.trackSid),B.isEnabled||j.push(B.trackSid)}),this.client.sendSyncState(new SyncState({answer:L?toProtoSessionDescription({sdp:L.sdp,type:L.type}):void 0,offer:O?toProtoSessionDescription({sdp:O.sdp,type:O.type}):void 0,subscription:new UpdateSubscription({trackSids:V,subscribe:!N,participantTracks:[]}),publishTracks:getTrackPublicationInfo(P),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:j,datachannelReceiveStates:this.reliableReceivedState.map((B,z)=>new DataChannelReceiveState({publisherSid:z,lastSeq:B}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const n=[],P=(R,A)=>{R?.id!==void 0&&R.id!==null&&n.push(new DataChannelInfo({label:R.label,id:R.id,target:A}))};return P(this.dataChannelForKind(DataPacket_Kind.LOSSY),SignalTarget.PUBLISHER),P(this.dataChannelForKind(DataPacket_Kind.RELIABLE),SignalTarget.PUBLISHER),P(this.dataChannelForKind(DataPacket_Kind.LOSSY,!0),SignalTarget.SUBSCRIBER),P(this.dataChannelForKind(DataPacket_Kind.RELIABLE,!0),SignalTarget.SUBSCRIBER),n}clearReconnectTimeout(){this.reconnectTimeout&&CriticalTimers.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){isWeb()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){isWeb()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class SignalReconnectError extends Error{}function supportOptionalDatachannel(T){return T!==void 0&&T>13}function applyUserDataCompat(T,n){const P=T.participantIdentity?T.participantIdentity:n.participantIdentity;T.participantIdentity=P,n.participantIdentity=P;const R=T.destinationIdentities.length!==0?T.destinationIdentities:n.destinationIdentities;T.destinationIdentities=R,n.destinationIdentities=R}class RegionUrlProvider{constructor(n,P){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(n),this.token=P}updateToken(n){this.token=n}isCloud(){return isCloud(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(n){return __awaiter(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(n));const P=this.regionSettings.regions.filter(R=>!this.attemptedRegions.find(A=>A.url===R.url));if(P.length>0){const R=P[0];return this.attemptedRegions.push(R),livekitLogger.debug("next region: ".concat(R.region)),R.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(n){return __awaiter(this,void 0,void 0,function*(){const P=yield fetch("".concat(getCloudConfigUrl(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:n});if(P.ok){const R=yield P.json();return this.lastUpdateAt=Date.now(),R}else throw new ConnectionError("Could not fetch region settings: ".concat(P.statusText),P.status===401?ConnectionErrorReason.NotAllowed:ConnectionErrorReason.InternalError,P.status)})}setServerReportedRegions(n){this.regionSettings=n,this.lastUpdateAt=Date.now()}}function getCloudConfigUrl(T){return"".concat(T.protocol.replace("ws","http"),"//").concat(T.host,"/settings")}class BaseStreamReader{get info(){return this._info}validateBytesReceived(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(n&&this.bytesReceived<this.totalByteSize)throw new DataStreamError("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),DataStreamErrorReason.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new DataStreamError("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),DataStreamErrorReason.LengthExceeded)}}constructor(n,P,R,A){this.reader=P,this.totalByteSize=R,this._info=n,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=A}}class ByteStreamReader extends BaseStreamReader{handleChunkReceived(n){var P;this.bytesReceived+=n.content.byteLength,this.validateBytesReceived();const R=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(P=this.onProgress)===null||P===void 0||P.call(this,R)}[Symbol.asyncIterator](){const n=this.reader.getReader();let P=new Future,R=null,A=null;if(this.signal){const O=this.signal;A=()=>{var N;(N=P.reject)===null||N===void 0||N.call(P,O.reason)},O.addEventListener("abort",A),R=O}const L=()=>{n.releaseLock(),R&&A&&R.removeEventListener("abort",A),this.signal=void 0};return{next:()=>__awaiter(this,void 0,void 0,function*(){var O,N;try{const{done:V,value:j}=yield Promise.race([n.read(),P.promise,(N=(O=this.outOfBandFailureRejectingFuture)===null||O===void 0?void 0:O.promise)!==null&&N!==void 0?N:new Promise(()=>{})]);return V?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(j),{done:!1,value:j.content})}catch(V){throw L(),V}}),return(){return __awaiter(this,void 0,void 0,function*(){return L(),{done:!0,value:void 0}})}}}withAbortSignal(n){return this.signal=n,this}readAll(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var R,A,L,O;let N=new Set;const V=P.signal?n.withAbortSignal(P.signal):n;try{for(var j=!0,B=__asyncValues(V),z;z=yield B.next(),R=z.done,!R;j=!0){O=z.value,j=!1;const W=O;N.add(W)}}catch(W){A={error:W}}finally{try{!j&&!R&&(L=B.return)&&(yield L.call(B))}finally{if(A)throw A.error}}return Array.from(N)})()})}}class TextStreamReader extends BaseStreamReader{constructor(n,P,R,A){super(n,P,R,A),this.receivedChunks=new Map}handleChunkReceived(n){var P;const R=bigIntToNumber(n.chunkIndex),A=this.receivedChunks.get(R);if(A&&A.version>n.version)return;this.receivedChunks.set(R,n),this.bytesReceived+=n.content.byteLength,this.validateBytesReceived();const L=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(P=this.onProgress)===null||P===void 0||P.call(this,L)}[Symbol.asyncIterator](){const n=this.reader.getReader(),P=new TextDecoder("utf-8",{fatal:!0});let R=new Future,A=null,L=null;if(this.signal){const N=this.signal;L=()=>{var V;(V=R.reject)===null||V===void 0||V.call(R,N.reason)},N.addEventListener("abort",L),A=N}const O=()=>{n.releaseLock(),A&&L&&A.removeEventListener("abort",L),this.signal=void 0};return{next:()=>__awaiter(this,void 0,void 0,function*(){var N,V;try{const{done:j,value:B}=yield Promise.race([n.read(),R.promise,(V=(N=this.outOfBandFailureRejectingFuture)===null||N===void 0?void 0:N.promise)!==null&&V!==void 0?V:new Promise(()=>{})]);if(j)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(B);let z;try{z=P.decode(B.content)}catch(W){throw new DataStreamError("Cannot decode datastream chunk ".concat(B.chunkIndex," as text: ").concat(W),DataStreamErrorReason.DecodeFailed)}return{done:!1,value:z}}}catch(j){throw O(),j}}),return(){return __awaiter(this,void 0,void 0,function*(){return O(),{done:!0,value:void 0}})}}}withAbortSignal(n){return this.signal=n,this}readAll(){return __awaiter(this,arguments,void 0,function(){var n=this;let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var R,A,L,O;let N="";const V=P.signal?n.withAbortSignal(P.signal):n;try{for(var j=!0,B=__asyncValues(V),z;z=yield B.next(),R=z.done,!R;j=!0)O=z.value,j=!1,N+=O}catch(W){A={error:W}}finally{try{!j&&!R&&(L=B.return)&&(yield L.call(B))}finally{if(A)throw A.error}}return N})()})}}class IncomingDataStreamManager{constructor(){this.log=livekitLogger,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(n,P){if(this.textStreamHandlers.has(n))throw new DataStreamError('A text stream handler for topic "'.concat(n,'" has already been set.'),DataStreamErrorReason.HandlerAlreadyRegistered);this.textStreamHandlers.set(n,P)}unregisterTextStreamHandler(n){this.textStreamHandlers.delete(n)}registerByteStreamHandler(n,P){if(this.byteStreamHandlers.has(n))throw new DataStreamError('A byte stream handler for topic "'.concat(n,'" has already been set.'),DataStreamErrorReason.HandlerAlreadyRegistered);this.byteStreamHandlers.set(n,P)}unregisterByteStreamHandler(n){this.byteStreamHandlers.delete(n)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(n){var P,R,A,L;const O=Array.from(this.textStreamControllers.entries()).filter(V=>V[1].sendingParticipantIdentity===n),N=Array.from(this.byteStreamControllers.entries()).filter(V=>V[1].sendingParticipantIdentity===n);if(O.length>0||N.length>0){const V=new DataStreamError("Participant ".concat(n," unexpectedly disconnected in the middle of sending data"),DataStreamErrorReason.AbnormalEnd);for(const[j,B]of N)(R=(P=B.outOfBandFailureRejectingFuture).reject)===null||R===void 0||R.call(P,V),this.byteStreamControllers.delete(j);for(const[j,B]of O)(L=(A=B.outOfBandFailureRejectingFuture).reject)===null||L===void 0||L.call(A,V),this.textStreamControllers.delete(j)}}handleDataStreamPacket(n){return __awaiter(this,void 0,void 0,function*(){switch(n.value.case){case"streamHeader":return this.handleStreamHeader(n.value.value,n.participantIdentity);case"streamChunk":return this.handleStreamChunk(n.value.value);case"streamTrailer":return this.handleStreamTrailer(n.value.value);default:throw new Error('DataPacket of value "'.concat(n.value.case,'" is not data stream related!'))}})}handleStreamHeader(n,P){return __awaiter(this,void 0,void 0,function*(){var R;if(n.contentHeader.case==="byteHeader"){const A=this.byteStreamHandlers.get(n.topic);if(!A){this.log.debug("ignoring incoming byte stream due to no handler for topic",n.topic);return}let L;const O=new Future,N={id:n.streamId,name:(R=n.contentHeader.value.name)!==null&&R!==void 0?R:"unknown",mimeType:n.mimeType,size:n.totalLength?Number(n.totalLength):void 0,topic:n.topic,timestamp:bigIntToNumber(n.timestamp),attributes:n.attributes},V=new ReadableStream({start:j=>{if(L=j,this.textStreamControllers.has(n.streamId))throw new DataStreamError("A data stream read is already in progress for a stream with id ".concat(n.streamId,"."),DataStreamErrorReason.AlreadyOpened);this.byteStreamControllers.set(n.streamId,{info:N,controller:L,startTime:Date.now(),sendingParticipantIdentity:P,outOfBandFailureRejectingFuture:O})}});A(new ByteStreamReader(N,V,bigIntToNumber(n.totalLength),O),{identity:P})}else if(n.contentHeader.case==="textHeader"){const A=this.textStreamHandlers.get(n.topic);if(!A){this.log.debug("ignoring incoming text stream due to no handler for topic",n.topic);return}let L;const O=new Future,N={id:n.streamId,mimeType:n.mimeType,size:n.totalLength?Number(n.totalLength):void 0,topic:n.topic,timestamp:Number(n.timestamp),attributes:n.attributes},V=new ReadableStream({start:j=>{if(L=j,this.textStreamControllers.has(n.streamId))throw new DataStreamError("A data stream read is already in progress for a stream with id ".concat(n.streamId,"."),DataStreamErrorReason.AlreadyOpened);this.textStreamControllers.set(n.streamId,{info:N,controller:L,startTime:Date.now(),sendingParticipantIdentity:P,outOfBandFailureRejectingFuture:O})}});A(new TextStreamReader(N,V,bigIntToNumber(n.totalLength),O),{identity:P})}})}handleStreamChunk(n){const P=this.byteStreamControllers.get(n.streamId);P&&n.content.length>0&&P.controller.enqueue(n);const R=this.textStreamControllers.get(n.streamId);R&&n.content.length>0&&R.controller.enqueue(n)}handleStreamTrailer(n){const P=this.textStreamControllers.get(n.streamId);P&&(P.info.attributes=Object.assign(Object.assign({},P.info.attributes),n.attributes),P.controller.close(),this.textStreamControllers.delete(n.streamId));const R=this.byteStreamControllers.get(n.streamId);R&&(R.info.attributes=Object.assign(Object.assign({},R.info.attributes),n.attributes),R.controller.close(),this.byteStreamControllers.delete(n.streamId))}}class BaseStreamWriter{constructor(n,P,R){this.writableStream=n,this.defaultWriter=n.getWriter(),this.onClose=R,this.info=P}write(n){return this.defaultWriter.write(n)}close(){return __awaiter(this,void 0,void 0,function*(){var n;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(n=this.onClose)===null||n===void 0||n.call(this)})}}class TextStreamWriter extends BaseStreamWriter{}class ByteStreamWriter extends BaseStreamWriter{}const STREAM_CHUNK_SIZE=15e3;class OutgoingDataStreamManager{constructor(n,P){this.engine=n,this.log=P}setupEngine(n){this.engine=n}sendText(n,P){return __awaiter(this,void 0,void 0,function*(){var R;const A=crypto.randomUUID(),O=new TextEncoder().encode(n).byteLength,N=(R=P?.attachments)===null||R===void 0?void 0:R.map(()=>crypto.randomUUID()),V=new Array(N?N.length+1:1).fill(0),j=(z,W)=>{var q;V[W]=z;const H=V.reduce(($,Q)=>$+Q,0);(q=P?.onProgress)===null||q===void 0||q.call(P,H)},B=yield this.streamText({streamId:A,totalSize:O,destinationIdentities:P?.destinationIdentities,topic:P?.topic,attachedStreamIds:N,attributes:P?.attributes});return yield B.write(n),j(1,0),yield B.close(),P?.attachments&&N&&(yield Promise.all(P.attachments.map((z,W)=>__awaiter(this,void 0,void 0,function*(){return this._sendFile(N[W],z,{topic:P.topic,mimeType:z.type,onProgress:q=>{j(q,W+1)}})})))),B.info})}streamText(n){return __awaiter(this,void 0,void 0,function*(){var P,R;const A=(P=n?.streamId)!==null&&P!==void 0?P:crypto.randomUUID(),L={id:A,mimeType:"text/plain",timestamp:Date.now(),topic:(R=n?.topic)!==null&&R!==void 0?R:"",size:n?.totalSize,attributes:n?.attributes},O=new DataStream_Header({streamId:A,mimeType:L.mimeType,topic:L.topic,timestamp:numberToBigInt(L.timestamp),totalLength:numberToBigInt(n?.totalSize),attributes:L.attributes,contentHeader:{case:"textHeader",value:new DataStream_TextHeader({version:n?.version,attachedStreamIds:n?.attachedStreamIds,replyToStreamId:n?.replyToStreamId,operationType:n?.type==="update"?DataStream_OperationType.UPDATE:DataStream_OperationType.CREATE})}}),N=n?.destinationIdentities,V=new DataPacket({destinationIdentities:N,value:{case:"streamHeader",value:O}});yield this.engine.sendDataPacket(V,DataPacket_Kind.RELIABLE);let j=0;const B=this.engine,z=new WritableStream({write(H){return __awaiter(this,void 0,void 0,function*(){for(const $ of splitUtf8(H,STREAM_CHUNK_SIZE)){yield B.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);const Q=new DataStream_Chunk({content:$,streamId:A,chunkIndex:numberToBigInt(j)}),U=new DataPacket({destinationIdentities:N,value:{case:"streamChunk",value:Q}});yield B.sendDataPacket(U,DataPacket_Kind.RELIABLE),j+=1}})},close(){return __awaiter(this,void 0,void 0,function*(){const H=new DataStream_Trailer({streamId:A}),$=new DataPacket({destinationIdentities:N,value:{case:"streamTrailer",value:H}});yield B.sendDataPacket($,DataPacket_Kind.RELIABLE)})},abort(H){console.log("Sink error:",H)}});let W=()=>__awaiter(this,void 0,void 0,function*(){yield q.close()});B.once(EngineEvent.Closing,W);const q=new TextStreamWriter(z,L,()=>this.engine.off(EngineEvent.Closing,W));return q})}sendFile(n,P){return __awaiter(this,void 0,void 0,function*(){const R=crypto.randomUUID();return yield this._sendFile(R,n,P),{id:R}})}_sendFile(n,P,R){return __awaiter(this,void 0,void 0,function*(){var A;const L=yield this.streamBytes({streamId:n,totalSize:P.size,name:P.name,mimeType:(A=R?.mimeType)!==null&&A!==void 0?A:P.type,topic:R?.topic,destinationIdentities:R?.destinationIdentities}),O=P.stream().getReader();for(;;){const{done:N,value:V}=yield O.read();if(N)break;yield L.write(V)}return yield L.close(),L.info})}streamBytes(n){return __awaiter(this,void 0,void 0,function*(){var P,R,A,L,O;const N=(P=n?.streamId)!==null&&P!==void 0?P:crypto.randomUUID(),V=n?.destinationIdentities,j={id:N,mimeType:(R=n?.mimeType)!==null&&R!==void 0?R:"application/octet-stream",topic:(A=n?.topic)!==null&&A!==void 0?A:"",timestamp:Date.now(),attributes:n?.attributes,size:n?.totalSize,name:(L=n?.name)!==null&&L!==void 0?L:"unknown"},B=new DataStream_Header({totalLength:numberToBigInt((O=j.size)!==null&&O!==void 0?O:0),mimeType:j.mimeType,streamId:N,topic:j.topic,timestamp:numberToBigInt(Date.now()),attributes:j.attributes,contentHeader:{case:"byteHeader",value:new DataStream_ByteHeader({name:j.name})}}),z=new DataPacket({destinationIdentities:V,value:{case:"streamHeader",value:B}});yield this.engine.sendDataPacket(z,DataPacket_Kind.RELIABLE);let W=0;const q=new _$1,H=this.engine,$=this.log,Q=new WritableStream({write(J){return __awaiter(this,void 0,void 0,function*(){const G=yield q.lock();let K=0;try{for(;K<J.byteLength;){const Y=J.slice(K,K+STREAM_CHUNK_SIZE);yield H.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);const Z=new DataPacket({destinationIdentities:V,value:{case:"streamChunk",value:new DataStream_Chunk({content:Y,streamId:N,chunkIndex:numberToBigInt(W)})}});yield H.sendDataPacket(Z,DataPacket_Kind.RELIABLE),W+=1,K+=Y.byteLength}}finally{G()}})},close(){return __awaiter(this,void 0,void 0,function*(){const J=new DataStream_Trailer({streamId:N}),G=new DataPacket({destinationIdentities:V,value:{case:"streamTrailer",value:J}});yield H.sendDataPacket(G,DataPacket_Kind.RELIABLE)})},abort(J){$.error("Sink error:",J)}});return new ByteStreamWriter(Q,j)})}}class RemoteTrack extends Track{constructor(n,P,R,A,L){super(n,R,L),this.sid=P,this.receiver=A}get isLocal(){return!1}setMuted(n){this.isMuted!==n&&(this.isMuted=n,this._mediaStreamTrack.enabled=!n,this.emit(n?TrackEvent.Muted:TrackEvent.Unmuted,this))}setMediaStream(n){this.mediaStream=n;const P=R=>{R.track===this._mediaStreamTrack&&(n.removeEventListener("removetrack",P),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(TrackEvent.Ended,this))};n.addEventListener("removetrack",P)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return __awaiter(this,void 0,void 0,function*(){var n;return!((n=this.receiver)===null||n===void 0)&&n.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(n){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=n:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),monitorFrequency)),supportsSynchronizationSources()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const n=()=>{var P;this.timeSyncHandle=requestAnimationFrame(()=>n());const R=(P=this.receiver)===null||P===void 0?void 0:P.getSynchronizationSources()[0];if(R){const{timestamp:A,rtpTimestamp:L}=R;L&&this.rtpTimestamp!==L&&(this.emit(TrackEvent.TimeSyncUpdate,{timestamp:A,rtpTimestamp:L}),this.rtpTimestamp=L)}};n()}}class RemoteAudioTrack extends RemoteTrack{constructor(n,P,R,A,L,O){super(n,P,Track.Kind.Audio,R,O),this.monitorReceiver=()=>__awaiter(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const N=yield this.getReceiverStats();N&&this.prevStats&&this.receiver&&(this._currentBitrate=computeBitrate(N,this.prevStats)),this.prevStats=N}),this.audioContext=A,this.webAudioPluginNodes=[],L&&(this.sinkId=L.deviceId)}setVolume(n){var P;for(const R of this.attachedElements)this.audioContext?(P=this.gainNode)===null||P===void 0||P.gain.setTargetAtTime(n,0,.1):R.volume=n;isReactNative$1()&&this._mediaStreamTrack._setVolume(n),this.elementVolume=n}getVolume(){if(this.elementVolume)return this.elementVolume;if(isReactNative$1())return 1;let n=0;return this.attachedElements.forEach(P=>{P.volume>n&&(n=P.volume)}),n}setSinkId(n){return __awaiter(this,void 0,void 0,function*(){this.sinkId=n,yield Promise.all(this.attachedElements.map(P=>{if(supportsSetSinkId(P))return P.setSinkId(n)}))})}attach(n){const P=this.attachedElements.length===0;return n?super.attach(n):n=super.attach(),this.sinkId&&supportsSetSinkId(n)&&n.setSinkId(this.sinkId).catch(R=>{this.log.error("Failed to set sink id on remote audio track",R,this.logContext)}),this.audioContext&&P&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,n),n.volume=0,n.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),n}detach(n){let P;return n?(P=super.detach(n),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(P=super.detach(),this.disconnectWebAudio()),P}setAudioContext(n){this.audioContext=n,n&&this.attachedElements.length>0?this.connectWebAudio(n,this.attachedElements[0]):n||this.disconnectWebAudio()}setWebAudioPlugins(n){this.webAudioPluginNodes=n,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(n,P){this.disconnectWebAudio(),this.sourceNode=n.createMediaStreamSource(P.srcObject);let R=this.sourceNode;this.webAudioPluginNodes.forEach(A=>{R.connect(A),R=A}),this.gainNode=n.createGain(),R.connect(this.gainNode),this.gainNode.connect(n.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),n.state!=="running"&&n.resume().then(()=>{n.state!=="running"&&this.emit(TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(A=>{this.emit(TrackEvent.AudioPlaybackFailed,A)})}disconnectWebAudio(){var n,P;(n=this.gainNode)===null||n===void 0||n.disconnect(),(P=this.sourceNode)===null||P===void 0||P.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return __awaiter(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const n=yield this.receiver.getStats();let P;return n.forEach(R=>{R.type==="inbound-rtp"&&(P={type:"audio",streamId:R.id,timestamp:R.timestamp,jitter:R.jitter,bytesReceived:R.bytesReceived,concealedSamples:R.concealedSamples,concealmentEvents:R.concealmentEvents,silentConcealedSamples:R.silentConcealedSamples,silentConcealmentEvents:R.silentConcealmentEvents,totalAudioEnergy:R.totalAudioEnergy,totalSamplesDuration:R.totalSamplesDuration})}),P})}}const REACTION_DELAY=100;class RemoteVideoTrack extends RemoteTrack{constructor(n,P,R,A,L){super(n,P,Track.Kind.Video,R,L),this.elementInfos=[],this.monitorReceiver=()=>__awaiter(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const O=yield this.getReceiverStats();O&&this.prevStats&&this.receiver&&(this._currentBitrate=computeBitrate(O,this.prevStats)),this.prevStats=O}),this.debouncedHandleResize=r$1(()=>{this.updateDimensions()},REACTION_DELAY),this.adaptiveStreamSettings=A}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(n){super.setStreamState(n),console.log("setStreamState",n),n===Track.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(n){super.setMuted(n),this.attachedElements.forEach(P=>{n?detachTrack(this._mediaStreamTrack,P):attachToElement(this._mediaStreamTrack,P)})}attach(n){if(n?super.attach(n):n=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(P=>P.element===n)===void 0){const P=new HTMLElementInfo(n);this.observeElementInfo(P)}return n}observeElementInfo(n){this.adaptiveStreamSettings&&this.elementInfos.find(P=>P===n)===void 0?(n.handleResize=()=>{this.debouncedHandleResize()},n.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(n),n.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(n){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const P=this.elementInfos.filter(R=>R===n);for(const R of P)R.stopObserving();this.elementInfos=this.elementInfos.filter(R=>R!==n),this.updateVisibility(),this.debouncedHandleResize()}detach(n){let P=[];if(n)return this.stopObservingElement(n),super.detach(n);P=super.detach();for(const R of P)this.stopObservingElement(R);return P}getDecoderImplementation(){var n;return(n=this.prevStats)===null||n===void 0?void 0:n.decoderImplementation}getReceiverStats(){return __awaiter(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const n=yield this.receiver.getStats();let P,R="",A=new Map;return n.forEach(L=>{L.type==="inbound-rtp"?(R=L.codecId,P={type:"video",streamId:L.id,framesDecoded:L.framesDecoded,framesDropped:L.framesDropped,framesReceived:L.framesReceived,packetsReceived:L.packetsReceived,packetsLost:L.packetsLost,frameWidth:L.frameWidth,frameHeight:L.frameHeight,pliCount:L.pliCount,firCount:L.firCount,nackCount:L.nackCount,jitter:L.jitter,timestamp:L.timestamp,bytesReceived:L.bytesReceived,decoderImplementation:L.decoderImplementation}):L.type==="codec"&&A.set(L.id,L)}),P&&R!==""&&A.get(R)&&(P.mimeType=A.get(R).mimeType),P})}stopObservingElement(n){const P=this.elementInfos.filter(R=>R.element===n);for(const R of P)this.stopObservingElementInfo(R)}handleAppVisibilityChanged(){const n=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return __awaiter(this,void 0,void 0,function*(){yield n.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(n){var P,R;const A=this.elementInfos.reduce((V,j)=>Math.max(V,j.visibilityChangedAt||0),0),L=!((R=(P=this.adaptiveStreamSettings)===null||P===void 0?void 0:P.pauseVideoInBackground)!==null&&R!==void 0)||R?this.isInBackground:!1,O=this.elementInfos.some(V=>V.pictureInPicture),N=this.elementInfos.some(V=>V.visible)&&!L||O;if(!(this.lastVisible===N&&!n)){if(!N&&Date.now()-A<REACTION_DELAY){CriticalTimers.setTimeout(()=>{this.updateVisibility()},REACTION_DELAY);return}this.lastVisible=N,this.emit(TrackEvent.VisibilityChanged,N,this)}}updateDimensions(){var n,P;let R=0,A=0;const L=this.getPixelDensity();for(const O of this.elementInfos){const N=O.width()*L,V=O.height()*L;N+V>R+A&&(R=N,A=V)}((n=this.lastDimensions)===null||n===void 0?void 0:n.width)===R&&((P=this.lastDimensions)===null||P===void 0?void 0:P.height)===A||(this.lastDimensions={width:R,height:A},this.emit(TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var n;const P=(n=this.adaptiveStreamSettings)===null||n===void 0?void 0:n.pixelDensity;return P==="screen"?getDevicePixelRatio():P||(getDevicePixelRatio()>2?2:1)}}class HTMLElementInfo{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(n,P){this.onVisibilityChanged=R=>{var A;const{target:L,isIntersecting:O}=R;L===this.element&&(this.isIntersecting=O,this.isPiP=isElementInPiP(this.element),this.visibilityChangedAt=Date.now(),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this))},this.onEnterPiP=()=>{var R,A,L;(A=(R=window.documentPictureInPicture)===null||R===void 0?void 0:R.window)===null||A===void 0||A.addEventListener("pagehide",this.onLeavePiP),this.isPiP=isElementInPiP(this.element),(L=this.handleVisibilityChanged)===null||L===void 0||L.call(this)},this.onLeavePiP=()=>{var R;this.isPiP=isElementInPiP(this.element),(R=this.handleVisibilityChanged)===null||R===void 0||R.call(this)},this.element=n,this.isIntersecting=P??isElementInViewport(n),this.isPiP=isWeb()&&isElementInPiP(n),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var n,P,R;this.isIntersecting=isElementInViewport(this.element),this.isPiP=isElementInPiP(this.element),this.element.handleResize=()=>{var A;(A=this.handleResize)===null||A===void 0||A.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,getIntersectionObserver().observe(this.element),getResizeObserver().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.addEventListener("enter",this.onEnterPiP),(R=(P=window.documentPictureInPicture)===null||P===void 0?void 0:P.window)===null||R===void 0||R.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var n,P,R,A,L;(n=getIntersectionObserver())===null||n===void 0||n.unobserve(this.element),(P=getResizeObserver())===null||P===void 0||P.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(R=window.documentPictureInPicture)===null||R===void 0||R.removeEventListener("enter",this.onEnterPiP),(L=(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window)===null||L===void 0||L.removeEventListener("pagehide",this.onLeavePiP)}}function isElementInPiP(T){var n,P;return document.pictureInPictureElement===T?!0:!((n=window.documentPictureInPicture)===null||n===void 0)&&n.window?isElementInViewport(T,(P=window.documentPictureInPicture)===null||P===void 0?void 0:P.window):!1}function isElementInViewport(T,n){const P=n||window;let R=T.offsetTop,A=T.offsetLeft;const L=T.offsetWidth,O=T.offsetHeight,{hidden:N}=T,{display:V}=getComputedStyle(T);for(;T.offsetParent;)T=T.offsetParent,R+=T.offsetTop,A+=T.offsetLeft;return R<P.pageYOffset+P.innerHeight&&A<P.pageXOffset+P.innerWidth&&R+O>P.pageYOffset&&A+L>P.pageXOffset&&!N&&V!=="none"}class TrackPublication extends eventsExports.EventEmitter{constructor(n,P,R,A){var L;super(),this.metadataMuted=!1,this.encryption=Encryption_Type.NONE,this.log=livekitLogger,this.handleMuted=()=>{this.emit(TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(TrackEvent.Unmuted)},this.log=getLogger((L=A?.loggerName)!==null&&L!==void 0?L:LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=n,this.trackSid=P,this.trackName=R,this.source=Track.Source.Unknown}setTrack(n){this.track&&(this.track.off(TrackEvent.Muted,this.handleMuted),this.track.off(TrackEvent.Unmuted,this.handleUnmuted)),this.track=n,n&&(n.on(TrackEvent.Muted,this.handleMuted),n.on(TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var n;return Object.assign(Object.assign({},(n=this.loggerContextCb)===null||n===void 0?void 0:n.call(this)),getLogContextFromTrack(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Encryption_Type.NONE}get audioTrack(){if(isAudioTrack(this.track))return this.track}get videoTrack(){if(isVideoTrack(this.track))return this.track}updateInfo(n){this.trackSid=n.sid,this.trackName=n.name,this.source=Track.sourceFromProto(n.source),this.mimeType=n.mimeType,this.kind===Track.Kind.Video&&n.width>0&&(this.dimensions={width:n.width,height:n.height},this.simulcasted=n.simulcast),this.encryption=n.encryption,this.trackInfo=n,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:n}))}}(function(T){(function(n){n.Desired="desired",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed"})(T.SubscriptionStatus||(T.SubscriptionStatus={})),(function(n){n.Allowed="allowed",n.NotAllowed="not_allowed"})(T.PermissionStatus||(T.PermissionStatus={}))})(TrackPublication||(TrackPublication={}));class LocalTrackPublication extends TrackPublication{get isUpstreamPaused(){var n;return(n=this.track)===null||n===void 0?void 0:n.isUpstreamPaused}constructor(n,P,R,A){super(n,P.sid,P.name,A),this.track=void 0,this.handleTrackEnded=()=>{this.emit(TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&isVideoTrack(this.track)&&this.emit(TrackEvent.CpuConstrained,this.track)},this.updateInfo(P),this.setTrack(R)}setTrack(n){this.track&&(this.track.off(TrackEvent.Ended,this.handleTrackEnded),this.track.off(TrackEvent.CpuConstrained,this.handleCpuConstrained)),super.setTrack(n),n&&(n.on(TrackEvent.Ended,this.handleTrackEnded),n.on(TrackEvent.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return __awaiter(this,void 0,void 0,function*(){var n;return(n=this.track)===null||n===void 0?void 0:n.mute()})}unmute(){return __awaiter(this,void 0,void 0,function*(){var n;return(n=this.track)===null||n===void 0?void 0:n.unmute()})}pauseUpstream(){return __awaiter(this,void 0,void 0,function*(){var n;yield(n=this.track)===null||n===void 0?void 0:n.pauseUpstream()})}resumeUpstream(){return __awaiter(this,void 0,void 0,function*(){var n;yield(n=this.track)===null||n===void 0?void 0:n.resumeUpstream()})}getTrackFeatures(){var n;if(isAudioTrack(this.track)){const P=this.track.getSourceTrackSettings(),R=new Set;return P.autoGainControl&&R.add(AudioTrackFeature.TF_AUTO_GAIN_CONTROL),P.echoCancellation&&R.add(AudioTrackFeature.TF_ECHO_CANCELLATION),P.noiseSuppression&&R.add(AudioTrackFeature.TF_NOISE_SUPPRESSION),P.channelCount&&P.channelCount>1&&R.add(AudioTrackFeature.TF_STEREO),!((n=this.options)===null||n===void 0)&&n.dtx||R.add(AudioTrackFeature.TF_NO_DTX),this.track.enhancedNoiseCancellation&&R.add(AudioTrackFeature.TF_ENHANCED_NOISE_CANCELLATION),Array.from(R.values())}else return[]}}function createLocalTracks(T,n){return __awaiter(this,void 0,void 0,function*(){T??(T={});let P=!1;const{audioProcessor:R,videoProcessor:A,optionsWithoutProcessor:L}=extractProcessorsFromOptions(T);let O=L.audio,N=L.video;if(R&&typeof L.audio=="object"&&(L.audio.processor=R),A&&typeof L.video=="object"&&(L.video.processor=A),T.audio&&typeof L.audio=="object"&&typeof L.audio.deviceId=="string"){const z=L.audio.deviceId;L.audio.deviceId={exact:z},P=!0,O=Object.assign(Object.assign({},L.audio),{deviceId:{ideal:z}})}if(L.video&&typeof L.video=="object"&&typeof L.video.deviceId=="string"){const z=L.video.deviceId;L.video.deviceId={exact:z},P=!0,N=Object.assign(Object.assign({},L.video),{deviceId:{ideal:z}})}(L.audio===!0||typeof L.audio=="object"&&!L.audio.deviceId)&&(L.audio={deviceId:"default"}),L.video===!0?L.video={deviceId:"default"}:typeof L.video=="object"&&!L.video.deviceId&&(L.video.deviceId="default");const V=mergeDefaultOptions(L,audioDefaults,videoDefaults),j=constraintsForOptions(V),B=navigator.mediaDevices.getUserMedia(j);L.audio&&(DeviceManager.userMediaPromiseMap.set("audioinput",B),B.catch(()=>DeviceManager.userMediaPromiseMap.delete("audioinput"))),L.video&&(DeviceManager.userMediaPromiseMap.set("videoinput",B),B.catch(()=>DeviceManager.userMediaPromiseMap.delete("videoinput")));try{const z=yield B;return yield Promise.all(z.getTracks().map(W=>__awaiter(this,void 0,void 0,function*(){const q=W.kind==="audio";let H=q?V.audio:V.video;(typeof H=="boolean"||!H)&&(H={});let $;const Q=q?j.audio:j.video;typeof Q!="boolean"&&($=Q);const U=W.getSettings().deviceId;$?.deviceId&&unwrapConstraint($.deviceId)!==U?$.deviceId=U:$||($={deviceId:U});const J=mediaTrackToLocalTrack(W,$,n);return J.kind===Track.Kind.Video?J.source=Track.Source.Camera:J.kind===Track.Kind.Audio&&(J.source=Track.Source.Microphone),J.mediaStream=z,isAudioTrack(J)&&R?yield J.setProcessor(R):isVideoTrack(J)&&A&&(yield J.setProcessor(A)),J})))}catch(z){if(!P)throw z;return createLocalTracks(Object.assign(Object.assign({},T),{audio:O,video:N}),n)}})}function createLocalVideoTrack(T){return __awaiter(this,void 0,void 0,function*(){return(yield createLocalTracks({audio:!1,video:!0}))[0]})}function createLocalAudioTrack(T){return __awaiter(this,void 0,void 0,function*(){return(yield createLocalTracks({audio:T??!0,video:!1}))[0]})}var ConnectionQuality;(function(T){T.Excellent="excellent",T.Good="good",T.Poor="poor",T.Lost="lost",T.Unknown="unknown"})(ConnectionQuality||(ConnectionQuality={}));function qualityFromProto(T){switch(T){case ConnectionQuality$1.EXCELLENT:return ConnectionQuality.Excellent;case ConnectionQuality$1.GOOD:return ConnectionQuality.Good;case ConnectionQuality$1.POOR:return ConnectionQuality.Poor;case ConnectionQuality$1.LOST:return ConnectionQuality.Lost;default:return ConnectionQuality.Unknown}}class Participant extends eventsExports.EventEmitter{get logContext(){var n,P;return Object.assign({},(P=(n=this.loggerOptions)===null||n===void 0?void 0:n.loggerContextCb)===null||P===void 0?void 0:P.call(n))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(n=>n.isEncrypted)}get isAgent(){var n;return((n=this.permissions)===null||n===void 0?void 0:n.agent)||this.kind===ParticipantInfo_Kind.AGENT}get isActive(){var n;return((n=this.participantInfo)===null||n===void 0?void 0:n.state)===ParticipantInfo_State.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(n,P,R,A,L,O){let N=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ParticipantInfo_Kind.STANDARD;var V;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ConnectionQuality.Unknown,this.log=livekitLogger,this.log=getLogger((V=O?.loggerName)!==null&&V!==void 0?V:LoggerNames.Participant),this.loggerOptions=O,this.setMaxListeners(100),this.sid=n,this.identity=P,this.name=R,this.metadata=A,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=N,this._attributes=L??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(n){for(const[,P]of this.trackPublications)if(P.source===n)return P}getTrackPublicationByName(n){for(const[,P]of this.trackPublications)if(P.trackName===n)return P}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Future,this.once(ParticipantEvent.Active,()=>{var n,P;(P=(n=this.activeFuture)===null||n===void 0?void 0:n.resolve)===null||P===void 0||P.call(n),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var n;const P=this.getTrackPublication(Track.Source.Camera);return!(!((n=P?.isMuted)!==null&&n!==void 0)||n)}get isMicrophoneEnabled(){var n;const P=this.getTrackPublication(Track.Source.Microphone);return!(!((n=P?.isMuted)!==null&&n!==void 0)||n)}get isScreenShareEnabled(){return!!this.getTrackPublication(Track.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(n){var P;return this.participantInfo&&this.participantInfo.sid===n.sid&&this.participantInfo.version>n.version?!1:(this.identity=n.identity,this.sid=n.sid,this._setName(n.name),this._setMetadata(n.metadata),this._setAttributes(n.attributes),n.state===ParticipantInfo_State.ACTIVE&&((P=this.participantInfo)===null||P===void 0?void 0:P.state)!==ParticipantInfo_State.ACTIVE&&this.emit(ParticipantEvent.Active),n.permission&&this.setPermissions(n.permission),this.participantInfo=n,!0)}_setMetadata(n){const P=this.metadata!==n,R=this.metadata;this.metadata=n,P&&this.emit(ParticipantEvent.ParticipantMetadataChanged,R)}_setName(n){const P=this.name!==n;this.name=n,P&&this.emit(ParticipantEvent.ParticipantNameChanged,n)}_setAttributes(n){const P=diffAttributes(this.attributes,n);this._attributes=n,Object.keys(P).length>0&&this.emit(ParticipantEvent.AttributesChanged,P)}setPermissions(n){var P,R,A,L,O,N;const V=this.permissions,j=n.canPublish!==((P=this.permissions)===null||P===void 0?void 0:P.canPublish)||n.canSubscribe!==((R=this.permissions)===null||R===void 0?void 0:R.canSubscribe)||n.canPublishData!==((A=this.permissions)===null||A===void 0?void 0:A.canPublishData)||n.hidden!==((L=this.permissions)===null||L===void 0?void 0:L.hidden)||n.recorder!==((O=this.permissions)===null||O===void 0?void 0:O.recorder)||n.canPublishSources.length!==this.permissions.canPublishSources.length||n.canPublishSources.some((B,z)=>{var W;return B!==((W=this.permissions)===null||W===void 0?void 0:W.canPublishSources[z])})||n.canSubscribeMetrics!==((N=this.permissions)===null||N===void 0?void 0:N.canSubscribeMetrics);return this.permissions=n,j&&this.emit(ParticipantEvent.ParticipantPermissionsChanged,V),j}setIsSpeaking(n){n!==this.isSpeaking&&(this.isSpeaking=n,n&&(this.lastSpokeAt=new Date),this.emit(ParticipantEvent.IsSpeakingChanged,n))}setConnectionQuality(n){const P=this._connectionQuality;this._connectionQuality=qualityFromProto(n),P!==this._connectionQuality&&this.emit(ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var n,P;this.activeFuture&&((P=(n=this.activeFuture).reject)===null||P===void 0||P.call(n,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(n){this.audioContext=n,this.audioTrackPublications.forEach(P=>isAudioTrack(P.track)&&P.track.setAudioContext(n))}addTrackPublication(n){n.on(TrackEvent.Muted,()=>{this.emit(ParticipantEvent.TrackMuted,n)}),n.on(TrackEvent.Unmuted,()=>{this.emit(ParticipantEvent.TrackUnmuted,n)});const P=n;switch(P.track&&(P.track.sid=n.trackSid),this.trackPublications.set(n.trackSid,n),n.kind){case Track.Kind.Audio:this.audioTrackPublications.set(n.trackSid,n);break;case Track.Kind.Video:this.videoTrackPublications.set(n.trackSid,n);break}}}function trackPermissionToProto(T){var n,P,R;if(!T.participantSid&&!T.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new TrackPermission({participantIdentity:(n=T.participantIdentity)!==null&&n!==void 0?n:"",participantSid:(P=T.participantSid)!==null&&P!==void 0?P:"",allTracks:(R=T.allowAll)!==null&&R!==void 0?R:!1,trackSids:T.allowedTrackSids||[]})}class LocalParticipant extends Participant{constructor(n,P,R,A,L,O){super(n,P,void 0,void 0,void 0,{loggerName:A.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Encryption_Type.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Future)},this.handleReconnected=()=>{var N,V;(V=(N=this.reconnectFuture)===null||N===void 0?void 0:N.resolve)===null||V===void 0||V.call(N),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var N,V,j,B,z,W;this.reconnectFuture&&(this.reconnectFuture.promise.catch(q=>this.log.warn(q.message,this.logContext)),(V=(N=this.reconnectFuture)===null||N===void 0?void 0:N.reject)===null||V===void 0||V.call(N,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((B=(j=this.signalConnectedFuture).reject)===null||B===void 0||B.call(j,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(W=(z=this.activeAgentFuture)===null||z===void 0?void 0:z.reject)===null||W===void 0||W.call(z,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=N=>{var V,j;N.participant&&this.updateInfo(N.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Future),(j=(V=this.signalConnectedFuture).resolve)===null||j===void 0||j.call(V)},this.handleSignalRequestResponse=N=>{const{requestId:V,reason:j,message:B}=N,z=this.pendingSignalRequests.get(V);z&&(j!==RequestResponse_Reason.OK&&z.reject(new SignalRequestError(B,j)),this.pendingSignalRequests.delete(V))},this.handleDataPacket=N=>{switch(N.value.case){case"rpcResponse":let V=N.value.value,j=null,B=null;V.value.case==="payload"?j=V.value.value:V.value.case==="error"&&(B=RpcError.fromProto(V.value.value)),this.handleIncomingRpcResponse(V.requestId,j,B);break;case"rpcAck":let z=N.value.value;this.handleIncomingRpcAck(z.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(N=>trackPermissionToProto(N)))},this.onTrackUnmuted=N=>{this.onTrackMuted(N,N.isUpstreamPaused)},this.onTrackMuted=(N,V)=>{if(V===void 0&&(V=!0),!N.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N)));return}this.engine.updateMuteStatus(N.sid,V)},this.onTrackUpstreamPaused=N=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),this.onTrackMuted(N,!0)},this.onTrackUpstreamResumed=N=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),this.onTrackMuted(N,N.isMuted)},this.onTrackFeatureUpdate=N=>{const V=this.audioTrackPublications.get(N.sid);if(!V){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(N.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(V.trackSid,V.getTrackFeatures())},this.onTrackCpuConstrained=(N,V)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(V))),this.emit(ParticipantEvent.LocalTrackCpuConstrained,N,V)},this.handleSubscribedQualityUpdate=N=>__awaiter(this,void 0,void 0,function*(){var V,j,B,z,W;if(!(!((W=this.roomOptions)===null||W===void 0)&&W.dynacast))return;const q=this.videoTrackPublications.get(N.trackSid);if(!q){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:N.trackSid}));return}if(!q.videoTrack)return;const H=yield q.videoTrack.setPublishingCodecs(N.subscribedCodecs);try{for(var $=!0,Q=__asyncValues(H),U;U=yield Q.next(),V=U.done,!V;$=!0){z=U.value,$=!1;const J=z;isBackupCodec(J)&&(this.log.debug("publish ".concat(J," for ").concat(q.videoTrack.sid),Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(q))),yield this.publishAdditionalCodecForTrack(q.videoTrack,J,q.options))}}catch(J){j={error:J}}finally{try{!$&&!V&&(B=Q.return)&&(yield B.call(Q))}finally{if(j)throw j.error}}}),this.handleLocalTrackUnpublished=N=>{const V=this.trackPublications.get(N.trackSid);if(!V){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:N.trackSid}));return}this.unpublishTrack(V.track)},this.handleTrackEnded=N=>__awaiter(this,void 0,void 0,function*(){if(N.source===Track.Source.ScreenShare||N.source===Track.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),this.unpublishTrack(N);else if(N.isUserProvided)yield N.mute();else if(isLocalAudioTrack(N)||isLocalVideoTrack(N))try{if(isWeb())try{const V=yield navigator?.permissions.query({name:N.source===Track.Source.Camera?"camera":"microphone"});if(V&&V.state==="denied")throw this.log.warn("user has revoked access to ".concat(N.source),Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),V.onchange=()=>{V.state!=="denied"&&(N.isMuted||N.restartTrack(),V.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}N.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),isLocalAudioTrack(N)?yield N.restartTrack({deviceId:"default"}):yield N.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),yield N.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=R,this.roomOptions=A,this.setupEngine(R),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=L,this.roomOutgoingDataStreamManager=O}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Encryption_Type.NONE}getTrackPublication(n){const P=super.getTrackPublication(n);if(P)return P}getTrackPublicationByName(n){const P=super.getTrackPublicationByName(n);if(P)return P}setupEngine(n){var P;this.engine=n,this.engine.on(EngineEvent.RemoteMute,(R,A)=>{const L=this.trackPublications.get(R);!L||!L.track||(A?L.mute():L.unmute())}),!((P=this.signalConnectedFuture)===null||P===void 0)&&P.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(EngineEvent.Connected,this.handleReconnected).on(EngineEvent.SignalConnected,this.handleSignalConnected).on(EngineEvent.SignalRestarted,this.handleReconnected).on(EngineEvent.SignalResumed,this.handleReconnected).on(EngineEvent.Restarting,this.handleReconnecting).on(EngineEvent.Resuming,this.handleReconnecting).on(EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(EngineEvent.Closing,this.handleClosing).on(EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse).on(EngineEvent.DataPacketReceived,this.handleDataPacket)}setMetadata(n){return __awaiter(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:n})})}setName(n){return __awaiter(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:n})})}setAttributes(n){return __awaiter(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:n})})}requestMetadataUpdate(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let{metadata:A,name:L,attributes:O}=P;return(function*(){return new Promise((N,V)=>__awaiter(R,void 0,void 0,function*(){var j,B;try{let z=!1;const W=yield this.engine.client.sendUpdateLocalMetadata((j=A??this.metadata)!==null&&j!==void 0?j:"",(B=L??this.name)!==null&&B!==void 0?B:"",O),q=performance.now();for(this.pendingSignalRequests.set(W,{resolve:N,reject:H=>{V(H),z=!0},values:{name:L,metadata:A,attributes:O}});performance.now()-q<5e3&&!z;){if((!L||this.name===L)&&(!A||this.metadata===A)&&(!O||Object.entries(O).every(H=>{let[$,Q]=H;return this.attributes[$]===Q||Q===""&&!this.attributes[$]}))){this.pendingSignalRequests.delete(W),N();return}yield sleep(50)}V(new SignalRequestError("Request to update local metadata timed out","TimeoutError"))}catch(z){z instanceof Error&&V(z)}}))})()})}setCameraEnabled(n,P,R){return this.setTrackEnabled(Track.Source.Camera,n,P,R)}setMicrophoneEnabled(n,P,R){return this.setTrackEnabled(Track.Source.Microphone,n,P,R)}setScreenShareEnabled(n,P,R){return this.setTrackEnabled(Track.Source.ScreenShare,n,P,R)}setE2EEEnabled(n){return __awaiter(this,void 0,void 0,function*(){this.encryptionType=n?Encryption_Type.GCM:Encryption_Type.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(n,P,R,A){return __awaiter(this,void 0,void 0,function*(){var L,O;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:n,enabled:P})),this.republishPromise&&(yield this.republishPromise);let N=this.getTrackPublication(n);if(P)if(N)yield N.unmute();else{let V;if(this.pendingPublishing.has(n)){const j=yield this.waitForPendingPublicationOfSource(n);return j||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:n})),yield j?.unmute(),j}this.pendingPublishing.add(n);try{switch(n){case Track.Source.Camera:V=yield this.createTracks({video:(L=R)!==null&&L!==void 0?L:!0});break;case Track.Source.Microphone:V=yield this.createTracks({audio:(O=R)!==null&&O!==void 0?O:!0});break;case Track.Source.ScreenShare:V=yield this.createScreenTracks(Object.assign({},R));break;default:throw new TrackInvalidError(n)}}catch(j){throw V?.forEach(B=>{B.stop()}),j instanceof Error&&this.emit(ParticipantEvent.MediaDevicesError,j,sourceToKind(n)),this.pendingPublishing.delete(n),j}for(const j of V){const B=Object.assign(Object.assign({},this.roomOptions.publishDefaults),R);n===Track.Source.Microphone&&isAudioTrack(j)&&B.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),j.startPreConnectBuffer())}try{const j=[];for(const z of V)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(z))),j.push(this.publishTrack(z,A));[N]=yield Promise.all(j)}catch(j){throw V?.forEach(B=>{B.stop()}),j}finally{this.pendingPublishing.delete(n)}}else if(!N?.track&&this.pendingPublishing.has(n)&&(N=yield this.waitForPendingPublicationOfSource(n),N||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:n}))),N&&N.track)if(n===Track.Source.ScreenShare){N=yield this.unpublishTrack(N.track);const V=this.getTrackPublication(Track.Source.ScreenShareAudio);V&&V.track&&this.unpublishTrack(V.track)}else yield N.mute();return N})}enableCameraAndMicrophone(){return __awaiter(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(Track.Source.Camera)||this.pendingPublishing.has(Track.Source.Microphone))){this.pendingPublishing.add(Track.Source.Camera),this.pendingPublishing.add(Track.Source.Microphone);try{const n=yield this.createTracks({audio:!0,video:!0});yield Promise.all(n.map(P=>this.publishTrack(P)))}finally{this.pendingPublishing.delete(Track.Source.Camera),this.pendingPublishing.delete(Track.Source.Microphone)}}})}createTracks(n){return __awaiter(this,void 0,void 0,function*(){var P,R;n??(n={});const A=mergeDefaultOptions(n,(P=this.roomOptions)===null||P===void 0?void 0:P.audioCaptureDefaults,(R=this.roomOptions)===null||R===void 0?void 0:R.videoCaptureDefaults);try{return(yield createLocalTracks(A,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(N=>(isAudioTrack(N)&&(this.microphoneError=void 0,N.setAudioContext(this.audioContext),N.source=Track.Source.Microphone,this.emit(ParticipantEvent.AudioStreamAcquired)),isVideoTrack(N)&&(this.cameraError=void 0,N.source=Track.Source.Camera),N))}catch(L){throw L instanceof Error&&(n.audio&&(this.microphoneError=L),n.video&&(this.cameraError=L)),L}})}createScreenTracks(n){return __awaiter(this,void 0,void 0,function*(){if(n===void 0&&(n={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new DeviceUnsupportedError("getDisplayMedia not supported");n.resolution===void 0&&!isSafari17Based()&&(n.resolution=ScreenSharePresets.h1080fps30.resolution);const P=screenCaptureToDisplayMediaStreamOptions(n),R=yield navigator.mediaDevices.getDisplayMedia(P),A=R.getVideoTracks();if(A.length===0)throw new TrackInvalidError("no video track found");const L=new LocalVideoTrack(A[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});L.source=Track.Source.ScreenShare,n.contentHint&&(L.mediaStreamTrack.contentHint=n.contentHint);const O=[L];if(R.getAudioTracks().length>0){this.emit(ParticipantEvent.AudioStreamAcquired);const N=new LocalAudioTrack(R.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});N.source=Track.Source.ScreenShareAudio,O.push(N)}return O})}publishTrack(n,P){return __awaiter(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(n,P)})}publishOrRepublishTrack(n,P){return __awaiter(this,arguments,void 0,function(R,A){var L=this;let O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var N,V,j,B;isLocalAudioTrack(R)&&R.setAudioContext(L.audioContext),yield(N=L.reconnectFuture)===null||N===void 0?void 0:N.promise,L.republishPromise&&!O&&(yield L.republishPromise),isLocalTrack(R)&&L.pendingPublishPromises.has(R)&&(yield L.pendingPublishPromises.get(R));let z;if(R instanceof MediaStreamTrack)z=R.getConstraints();else{z=R.constraints;let U;switch(R.source){case Track.Source.Microphone:U="audioinput";break;case Track.Source.Camera:U="videoinput"}U&&L.activeDeviceMap.has(U)&&(z=Object.assign(Object.assign({},z),{deviceId:L.activeDeviceMap.get(U)}))}if(R instanceof MediaStreamTrack)switch(R.kind){case"audio":R=new LocalAudioTrack(R,z,!0,L.audioContext,{loggerName:L.roomOptions.loggerName,loggerContextCb:()=>L.logContext});break;case"video":R=new LocalVideoTrack(R,z,!0,{loggerName:L.roomOptions.loggerName,loggerContextCb:()=>L.logContext});break;default:throw new TrackInvalidError("unsupported MediaStreamTrack kind ".concat(R.kind))}else R.updateLoggerOptions({loggerName:L.roomOptions.loggerName,loggerContextCb:()=>L.logContext});let W;if(L.trackPublications.forEach(U=>{U.track&&U.track===R&&(W=U)}),W)return L.log.warn("track has already been published, skipping",Object.assign(Object.assign({},L.logContext),getLogContextFromTrack(W))),W;const q=Object.assign(Object.assign({},L.roomOptions.publishDefaults),A),H="channelCount"in R.mediaStreamTrack.getSettings()&&R.mediaStreamTrack.getSettings().channelCount===2||R.mediaStreamTrack.getConstraints().channelCount===2,$=(V=q.forceStereo)!==null&&V!==void 0?V:H;$&&(q.dtx===void 0&&L.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},L.logContext),getLogContextFromTrack(R))),q.red===void 0&&L.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(j=q.dtx)!==null&&j!==void 0||(q.dtx=!1),(B=q.red)!==null&&B!==void 0||(q.red=!1)),!isE2EESimulcastSupported()&&L.roomOptions.e2ee&&(L.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},L.logContext)),q.simulcast=!1),q.source&&(R.source=q.source);const Q=new Promise((U,J)=>__awaiter(L,void 0,void 0,function*(){try{if(this.engine.client.currentState!==SignalConnectionState.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:getLogContextFromTrack(R)}));const G=setTimeout(()=>{J(new PublishTrackError("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(G);const K=yield this.publish(R,q,$);U(K)}else try{const G=yield this.publish(R,q,$);U(G)}catch(G){J(G)}}catch(G){J(G)}}));L.pendingPublishPromises.set(R,Q);try{return yield Q}catch(U){throw U}finally{L.pendingPublishPromises.delete(R)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Future),this.signalConnectedFuture.promise}hasPermissionsToPublish(n){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n))),!1;const{canPublish:P,canPublishSources:R}=this.permissions;return P&&(R.length===0||R.map(A=>getTrackSourceFromProto(A)).includes(n.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n))),!1)}publish(n,P,R){return __awaiter(this,void 0,void 0,function*(){var A,L,O,N,V,j,B,z,W,q;if(!this.hasPermissionsToPublish(n))throw new PublishTrackError("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(le=>isLocalTrack(n)&&le.source===n.source)&&n.source!==Track.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(n.source),Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n))),P.stopMicTrackOnMute&&isAudioTrack(n)&&(n.stopOnMute=!0),n.source===Track.Source.ScreenShare&&isFireFox()&&(P.simulcast=!1),P.videoCodec==="av1"&&!supportsAV1()&&(P.videoCodec=void 0),P.videoCodec==="vp9"&&!supportsVP9()&&(P.videoCodec=void 0),P.videoCodec===void 0&&(P.videoCodec=defaultVideoCodec),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(le=>P.videoCodec===mimeTypeToVideoCodecString(le.mime))||(P.videoCodec=mimeTypeToVideoCodecString(this.enabledPublishVideoCodecs[0].mime)));const $=P.videoCodec;n.on(TrackEvent.Muted,this.onTrackMuted),n.on(TrackEvent.Unmuted,this.onTrackUnmuted),n.on(TrackEvent.Ended,this.handleTrackEnded),n.on(TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),n.on(TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),n.on(TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const Q=[],U=!(!((A=P.dtx)!==null&&A!==void 0)||A),J=n.getSourceTrackSettings();J.autoGainControl&&Q.push(AudioTrackFeature.TF_AUTO_GAIN_CONTROL),J.echoCancellation&&Q.push(AudioTrackFeature.TF_ECHO_CANCELLATION),J.noiseSuppression&&Q.push(AudioTrackFeature.TF_NOISE_SUPPRESSION),J.channelCount&&J.channelCount>1&&Q.push(AudioTrackFeature.TF_STEREO),U&&Q.push(AudioTrackFeature.TF_NO_DTX),isLocalAudioTrack(n)&&n.hasPreConnectBuffer&&Q.push(AudioTrackFeature.TF_PRECONNECT_BUFFER);const G=new AddTrackRequest({cid:n.mediaStreamTrack.id,name:P.name,type:Track.kindToProto(n.kind),muted:n.isMuted,source:Track.sourceToProto(n.source),disableDtx:U,encryption:this.encryptionType,stereo:R,disableRed:this.isE2EEEnabled||!(!((L=P.red)!==null&&L!==void 0)||L),stream:P?.stream,backupCodecPolicy:P?.backupCodecPolicy,audioFeatures:Q});let K;if(n.kind===Track.Kind.Video){let le={width:0,height:0};try{le=yield n.waitForDimensions()}catch{const ue=(N=(O=this.roomOptions.videoCaptureDefaults)===null||O===void 0?void 0:O.resolution)!==null&&N!==void 0?N:VideoPresets.h720.resolution;le={width:ue.width,height:ue.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)),{dims:le}))}G.width=le.width,G.height=le.height,isLocalVideoTrack(n)&&(isSVCCodec($)&&(n.source===Track.Source.ScreenShare&&(P.scalabilityMode="L1T3","contentHint"in n.mediaStreamTrack&&(n.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n))))),P.scalabilityMode=(V=P.scalabilityMode)!==null&&V!==void 0?V:"L3T3_KEY"),G.simulcastCodecs=[new SimulcastCodec({codec:$,cid:n.mediaStreamTrack.id})],P.backupCodec===!0&&(P.backupCodec={codec:defaultVideoCodec}),P.backupCodec&&$!==P.backupCodec.codec&&G.encryption===Encryption_Type.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),G.simulcastCodecs.push(new SimulcastCodec({codec:P.backupCodec.codec,cid:""})))),K=computeVideoEncodings(n.source===Track.Source.ScreenShare,G.width,G.height,P),G.layers=videoLayersFromEncodings(G.width,G.height,K,isSVCCodec(P.videoCodec))}else n.kind===Track.Kind.Audio&&(K=[{maxBitrate:(j=P.audioPreset)===null||j===void 0?void 0:j.maxBitrate,priority:(z=(B=P.audioPreset)===null||B===void 0?void 0:B.priority)!==null&&z!==void 0?z:"high",networkPriority:(q=(W=P.audioPreset)===null||W===void 0?void 0:W.priority)!==null&&q!==void 0?q:"high"}]);if(!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const Y=()=>__awaiter(this,void 0,void 0,function*(){var le,pe,ue;if(!this.engine.pcManager)throw new UnexpectedConnectionState("pcManager is not ready");if(n.sender=yield this.engine.createSender(n,P,K),this.emit(ParticipantEvent.LocalSenderCreated,n.sender,n),isLocalVideoTrack(n)&&((le=P.degradationPreference)!==null&&le!==void 0||(P.degradationPreference=getDefaultDegradationPreference(n)),n.setDegradationPreference(P.degradationPreference)),K)if(isFireFox()&&n.kind===Track.Kind.Audio){let he;for(const ve of this.engine.pcManager.publisher.getTransceivers())if(ve.sender===n.sender){he=ve;break}he&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:he,codec:"opus",maxbr:!((pe=K[0])===null||pe===void 0)&&pe.maxBitrate?K[0].maxBitrate/1e3:0})}else n.codec&&isSVCCodec(n.codec)&&(!((ue=K[0])===null||ue===void 0)&&ue.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:G.cid,codec:n.codec,maxbr:K[0].maxBitrate/1e3});yield this.engine.negotiate()});let Z;const ie=new Promise((le,pe)=>__awaiter(this,void 0,void 0,function*(){var ue;try{Z=yield this.engine.addTrack(G),le(Z)}catch(he){n.sender&&(!((ue=this.engine.pcManager)===null||ue===void 0)&&ue.publisher)&&(this.engine.pcManager.publisher.removeTrack(n.sender),yield this.engine.negotiate().catch(ve=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)),{error:ve}))})),pe(he)}}));if(this.enabledPublishVideoCodecs.length>0)Z=(yield Promise.all([ie,Y()]))[0];else{Z=yield ie;let le;if(Z.codecs.forEach(pe=>{le===void 0&&(le=pe.mimeType)}),le&&n.kind===Track.Kind.Video){const pe=mimeTypeToVideoCodecString(le);pe!==$&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)),{codec:pe})),P.videoCodec=pe,K=computeVideoEncodings(n.source===Track.Source.ScreenShare,G.width,G.height,P))}yield Y()}const se=new LocalTrackPublication(n.kind,Z,n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(se.on(TrackEvent.CpuConstrained,le=>this.onTrackCpuConstrained(le,se)),se.options=P,n.sid=Z.sid,this.log.debug("publishing ".concat(n.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:K,trackInfo:Z})),isLocalVideoTrack(n)?n.startMonitor(this.engine.client):isLocalAudioTrack(n)&&n.startMonitor(),this.addTrackPublication(se),this.emit(ParticipantEvent.LocalTrackPublished,se),isLocalAudioTrack(n)&&Z.audioFeatures.includes(AudioTrackFeature.TF_PRECONNECT_BUFFER)){const le=n.getPreConnectBuffer(),pe=n.getPreConnectBufferMimeType();this.on(ParticipantEvent.LocalTrackSubscribed,ue=>{if(ue.trackSid===Z.sid){if(!n.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n))),n.stopPreConnectBuffer()}}),le&&new Promise((he,ve)=>__awaiter(this,void 0,void 0,function*(){var be,fe,ne,ce,ee,te;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)));const ge=setTimeout(()=>{ve(new Error("agent not active within 10 seconds"))},1e4),ye=yield this.waitUntilActiveAgentPresent();clearTimeout(ge),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)));const Ee=yield this.streamBytes({name:"preconnect-buffer",mimeType:pe,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ye.identity],attributes:{trackId:se.trackSid,sampleRate:String((ee=J.sampleRate)!==null&&ee!==void 0?ee:"48000"),channels:String((te=J.channelCount)!==null&&te!==void 0?te:"1")}});try{for(var oe=!0,ae=__asyncValues(le),de;de=yield ae.next(),be=de.done,!be;oe=!0){ce=de.value,oe=!1;const Pe=ce;yield Ee.write(Pe)}}catch(Pe){fe={error:Pe}}finally{try{!oe&&!be&&(ne=ae.return)&&(yield ne.call(ae))}finally{if(fe)throw fe.error}}yield Ee.close(),he()}catch(ge){ve(ge)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)))}).catch(he=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)),{error:he}))})}return se})}get isLocal(){return!0}publishAdditionalCodecForTrack(n,P,R){return __awaiter(this,void 0,void 0,function*(){var A;if(this.encryptionType!==Encryption_Type.NONE)return;let L;if(this.trackPublications.forEach(q=>{q.track&&q.track===n&&(L=q)}),!L)throw new TrackInvalidError("track is not published");if(!isLocalVideoTrack(n))throw new TrackInvalidError("track is not a video track");const O=Object.assign(Object.assign({},(A=this.roomOptions)===null||A===void 0?void 0:A.publishDefaults),R),N=computeTrackBackupEncodings(n,P,O);if(!N){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)));return}const V=n.addSimulcastTrack(P,N);if(!V)return;const j=new AddTrackRequest({cid:V.mediaStreamTrack.id,type:Track.kindToProto(n.kind),muted:n.isMuted,source:Track.sourceToProto(n.source),sid:n.sid,simulcastCodecs:[{codec:O.videoCodec,cid:V.mediaStreamTrack.id}]});if(j.layers=videoLayersFromEncodings(j.width,j.height,N),!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const B=()=>__awaiter(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(n,V,O,N),yield this.engine.negotiate()}),W=(yield Promise.all([this.engine.addTrack(j),B()]))[0];this.log.debug("published ".concat(P," for track ").concat(n.sid),Object.assign(Object.assign({},this.logContext),{encodings:N,trackInfo:W}))})}unpublishTrack(n,P){return __awaiter(this,void 0,void 0,function*(){var R,A;if(isLocalTrack(n)){const j=this.pendingPublishPromises.get(n);j&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n))),yield j)}const L=this.getPublicationForTrack(n),O=L?getLogContextFromTrack(L):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),O)),!L||!L.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),O));return}n=L.track,n.off(TrackEvent.Muted,this.onTrackMuted),n.off(TrackEvent.Unmuted,this.onTrackUnmuted),n.off(TrackEvent.Ended,this.handleTrackEnded),n.off(TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),n.off(TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),n.off(TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),P===void 0&&(P=(A=(R=this.roomOptions)===null||R===void 0?void 0:R.stopLocalTrackOnUnpublish)!==null&&A!==void 0?A:!0),P?n.stop():n.stopMonitor();let N=!1;const V=n.sender;if(n.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<PCTransportState.FAILED&&V)try{for(const j of this.engine.pcManager.publisher.getTransceivers())j.sender===V&&(j.direction="inactive",N=!0);if(this.engine.removeTrack(V)&&(N=!0),isLocalVideoTrack(n)){for(const[,j]of n.simulcastCodecs)j.sender&&(this.engine.removeTrack(j.sender)&&(N=!0),j.sender=void 0);n.simulcastCodecs.clear()}}catch(j){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),O),{error:j}))}switch(this.trackPublications.delete(L.trackSid),L.kind){case Track.Kind.Audio:this.audioTrackPublications.delete(L.trackSid);break;case Track.Kind.Video:this.videoTrackPublications.delete(L.trackSid);break}return this.emit(ParticipantEvent.LocalTrackUnpublished,L),L.setTrack(void 0),N&&(yield this.engine.negotiate()),L})}unpublishTracks(n){return __awaiter(this,void 0,void 0,function*(){return(yield Promise.all(n.map(R=>this.unpublishTrack(R)))).filter(R=>!!R)})}republishAllTracks(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){R.republishPromise&&(yield R.republishPromise),R.republishPromise=new Promise((L,O)=>__awaiter(R,void 0,void 0,function*(){try{const N=[];this.trackPublications.forEach(V=>{V.track&&(P&&(V.options=Object.assign(Object.assign({},V.options),P)),N.push(V))}),yield Promise.all(N.map(V=>__awaiter(this,void 0,void 0,function*(){const j=V.track;yield this.unpublishTrack(j,!1),A&&!j.isMuted&&j.source!==Track.Source.ScreenShare&&j.source!==Track.Source.ScreenShareAudio&&(isLocalAudioTrack(j)||isLocalVideoTrack(j))&&!j.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:V.trackSid})),yield j.restartTrack()),yield this.publishOrRepublishTrack(j,V.options,!0)}))),L()}catch(N){O(N)}finally{this.republishPromise=void 0}})),yield R.republishPromise})()})}publishData(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const L=A.reliable?DataPacket_Kind.RELIABLE:DataPacket_Kind.LOSSY,O=A.destinationIdentities,N=A.topic,V=new DataPacket({kind:L,value:{case:"user",value:new UserPacket({participantIdentity:R.identity,payload:P,destinationIdentities:O,topic:N})}});yield R.engine.sendDataPacket(V,L)})()})}publishDtmf(n,P){return __awaiter(this,void 0,void 0,function*(){const R=new DataPacket({kind:DataPacket_Kind.RELIABLE,value:{case:"sipDtmf",value:new SipDTMF({code:n,digit:P})}});yield this.engine.sendDataPacket(R,DataPacket_Kind.RELIABLE)})}sendChatMessage(n,P){return __awaiter(this,void 0,void 0,function*(){const R={id:crypto.randomUUID(),message:n,timestamp:Date.now(),attachedFiles:P?.attachments},A=new DataPacket({value:{case:"chatMessage",value:new ChatMessage(Object.assign(Object.assign({},R),{timestamp:protoInt64.parse(R.timestamp)}))}});return yield this.engine.sendDataPacket(A,DataPacket_Kind.RELIABLE),this.emit(ParticipantEvent.ChatMessage,R),R})}editChatMessage(n,P){return __awaiter(this,void 0,void 0,function*(){const R=Object.assign(Object.assign({},P),{message:n,editTimestamp:Date.now()}),A=new DataPacket({value:{case:"chatMessage",value:new ChatMessage(Object.assign(Object.assign({},R),{timestamp:protoInt64.parse(R.timestamp),editTimestamp:protoInt64.parse(R.editTimestamp)}))}});return yield this.engine.sendDataPacket(A,DataPacket_Kind.RELIABLE),this.emit(ParticipantEvent.ChatMessage,R),R})}sendText(n,P){return __awaiter(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(n,P)})}streamText(n){return __awaiter(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(n)})}sendFile(n,P){return __awaiter(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(n,P)})}streamBytes(n){return __awaiter(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(n)})}performRpc(n){return __awaiter(this,arguments,void 0,function(P){var R=this;let{destinationIdentity:A,method:L,payload:O,responseTimeout:N=1e4}=P;return(function*(){return new Promise((j,B)=>__awaiter(R,void 0,void 0,function*(){var z,W,q,H;if(byteLength$1(O)>MAX_PAYLOAD_BYTES){B(RpcError.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((W=(z=this.engine.latestJoinResponse)===null||z===void 0?void 0:z.serverInfo)===null||W===void 0)&&W.version&&compareVersions((H=(q=this.engine.latestJoinResponse)===null||q===void 0?void 0:q.serverInfo)===null||H===void 0?void 0:H.version,"1.8.0")<0){B(RpcError.builtIn("UNSUPPORTED_SERVER"));return}const $=crypto.randomUUID();yield this.publishRpcRequest(A,$,L,O,N-2e3);const Q=setTimeout(()=>{this.pendingAcks.delete($),B(RpcError.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete($),clearTimeout(U)},2e3);this.pendingAcks.set($,{resolve:()=>{clearTimeout(Q)},participantIdentity:A});const U=setTimeout(()=>{this.pendingResponses.delete($),B(RpcError.builtIn("RESPONSE_TIMEOUT"))},N);this.pendingResponses.set($,{resolve:(J,G)=>{clearTimeout(U),this.pendingAcks.has($)&&(console.warn("RPC response received before ack",$),this.pendingAcks.delete($),clearTimeout(Q)),G?B(G):j(J??"")},participantIdentity:A})}))})()})}registerRpcMethod(n,P){this.rpcHandlers.has(n)&&this.log.warn("you're overriding the RPC handler for method ".concat(n,", in the future this will throw an error")),this.rpcHandlers.set(n,P)}unregisterRpcMethod(n){this.rpcHandlers.delete(n)}setTrackSubscriptionPermissions(n){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=P,this.allParticipantsAllowedToSubscribe=n,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(n){const P=this.pendingAcks.get(n);P?(P.resolve(),this.pendingAcks.delete(n)):console.error("Ack received for unexpected RPC request",n)}handleIncomingRpcResponse(n,P,R){const A=this.pendingResponses.get(n);A?(A.resolve(P,R),this.pendingResponses.delete(n)):console.error("Response received for unexpected RPC request",n)}publishRpcRequest(n,P,R,A,L){return __awaiter(this,void 0,void 0,function*(){const O=new DataPacket({destinationIdentities:[n],kind:DataPacket_Kind.RELIABLE,value:{case:"rpcRequest",value:new RpcRequest({id:P,method:R,payload:A,responseTimeoutMs:L,version:1})}});yield this.engine.sendDataPacket(O,DataPacket_Kind.RELIABLE)})}handleParticipantDisconnected(n){for(const[P,{participantIdentity:R}]of this.pendingAcks)R===n&&this.pendingAcks.delete(P);for(const[P,{participantIdentity:R,resolve:A}]of this.pendingResponses)R===n&&(A(null,RpcError.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(P))}setEnabledPublishCodecs(n){this.enabledPublishVideoCodecs=n.filter(P=>P.mime.split("/")[0].toLowerCase()==="video")}updateInfo(n){return super.updateInfo(n)?(n.tracks.forEach(P=>{var R,A;const L=this.trackPublications.get(P.sid);if(L){const O=L.isMuted||((A=(R=L.track)===null||R===void 0?void 0:R.isUpstreamPaused)!==null&&A!==void 0?A:!1);O!==P.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(L)),{mutedOnServer:O})),this.engine.client.sendMuteTrack(P.sid,O))}}),!0):!1}setActiveAgent(n){var P,R,A,L;this.firstActiveAgent=n,n&&!this.firstActiveAgent&&(this.firstActiveAgent=n),n?(R=(P=this.activeAgentFuture)===null||P===void 0?void 0:P.resolve)===null||R===void 0||R.call(P,n):(L=(A=this.activeAgentFuture)===null||A===void 0?void 0:A.reject)===null||L===void 0||L.call(A,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Future),this.activeAgentFuture.promise)}getPublicationForTrack(n){let P;return this.trackPublications.forEach(R=>{const A=R.track;A&&(n instanceof MediaStreamTrack?(isLocalAudioTrack(A)||isLocalVideoTrack(A))&&A.mediaStreamTrack===n&&(P=R):n===A&&(P=R))}),P}waitForPendingPublicationOfSource(n){return __awaiter(this,void 0,void 0,function*(){const R=Date.now();for(;Date.now()<R+1e4;){const A=Array.from(this.pendingPublishPromises.entries()).find(L=>{let[O]=L;return O.source===n});if(A)return A[1];yield sleep(20)}})}}class RemoteTrackPublication extends TrackPublication{constructor(n,P,R,A){super(n,P.sid,P.name,A),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=L=>{this.setTrack(void 0),this.emit(TrackEvent.Ended,L)},this.handleVisibilityChange=L=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(L),this.logContext),this.visible=L,this.emitTrackUpdate()},this.handleVideoDimensionsChange=L=>{this.log.debug("adaptivestream video dimensions ".concat(L.width,"x").concat(L.height),this.logContext),this.videoDimensionsAdaptiveStream=L,this.emitTrackUpdate()},this.subscribed=R,this.updateInfo(P)}setSubscribed(n){const P=this.subscriptionStatus,R=this.permissionStatus;this.subscribed=n,n&&(this.allowed=!0);const A=new UpdateSubscription({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ParticipantTracks({participantSid:"",trackSids:[this.trackSid]})]});this.emit(TrackEvent.UpdateSubscription,A),this.emitSubscriptionUpdateIfChanged(P),this.emitPermissionUpdateIfChanged(R)}get subscriptionStatus(){return this.subscribed===!1?TrackPublication.SubscriptionStatus.Unsubscribed:super.isSubscribed?TrackPublication.SubscriptionStatus.Subscribed:TrackPublication.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?TrackPublication.PermissionStatus.Allowed:TrackPublication.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(n){!this.isManualOperationAllowed()||this.requestedDisabled===!n||(this.requestedDisabled=!n,this.emitTrackUpdate())}setVideoQuality(n){!this.isManualOperationAllowed()||this.requestedMaxQuality===n||(this.requestedMaxQuality=n,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(n){var P,R;this.isManualOperationAllowed()&&(((P=this.requestedVideoDimensions)===null||P===void 0?void 0:P.width)===n.width&&((R=this.requestedVideoDimensions)===null||R===void 0?void 0:R.height)===n.height||(isRemoteVideoTrack(this.track)&&(this.requestedVideoDimensions=n),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(n){this.isManualOperationAllowed()&&isRemoteVideoTrack(this.track)&&this.fps!==n&&(this.fps=n,this.emitTrackUpdate())}get videoQuality(){var n;return(n=this.requestedMaxQuality)!==null&&n!==void 0?n:VideoQuality.HIGH}setTrack(n){const P=this.subscriptionStatus,R=this.permissionStatus,A=this.track;A!==n&&(A&&(A.off(TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),A.off(TrackEvent.VisibilityChanged,this.handleVisibilityChange),A.off(TrackEvent.Ended,this.handleEnded),A.detach(),A.stopMonitor(),this.emit(TrackEvent.Unsubscribed,A)),super.setTrack(n),n&&(n.sid=this.trackSid,n.on(TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.on(TrackEvent.VisibilityChanged,this.handleVisibilityChange),n.on(TrackEvent.Ended,this.handleEnded),this.emit(TrackEvent.Subscribed,n)),this.emitPermissionUpdateIfChanged(R),this.emitSubscriptionUpdateIfChanged(P))}setAllowed(n){const P=this.subscriptionStatus,R=this.permissionStatus;this.allowed=n,this.emitPermissionUpdateIfChanged(R),this.emitSubscriptionUpdateIfChanged(P)}setSubscriptionError(n){this.emit(TrackEvent.SubscriptionFailed,n)}updateInfo(n){super.updateInfo(n);const P=this.metadataMuted;this.metadataMuted=n.muted,this.track?this.track.setMuted(n.muted):P!==n.muted&&this.emit(n.muted?TrackEvent.Muted:TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(n){const P=this.subscriptionStatus;n!==P&&this.emit(TrackEvent.SubscriptionStatusChanged,P,n)}emitPermissionUpdateIfChanged(n){this.permissionStatus!==n&&this.emit(TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,n)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return isRemoteVideoTrack(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const n=new UpdateTrackSettings({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Track.Kind.Video){let P=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(P)areDimensionsSmaller(this.videoDimensionsAdaptiveStream,P)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),P=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const R=layerDimensionsFor(this.trackInfo,this.requestedMaxQuality);R&&areDimensionsSmaller(this.videoDimensionsAdaptiveStream,R)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),P=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),P=this.videoDimensionsAdaptiveStream;P?(n.width=Math.ceil(P.width),n.height=Math.ceil(P.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),n.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:VideoQuality.HIGH})),n.quality=VideoQuality.HIGH)}this.emit(TrackEvent.UpdateSettings,n)}}class RemoteParticipant extends Participant{static fromParticipantInfo(n,P,R){return new RemoteParticipant(n,P.sid,P.identity,P.name,P.metadata,P.attributes,R,P.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(n,P,R,A,L,O,N){let V=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ParticipantInfo_Kind.STANDARD;super(P,R||"",A,L,O,N,V),this.signalClient=n,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(n){super.addTrackPublication(n),n.on(TrackEvent.UpdateSettings,P=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(n)),{settings:P})),this.signalClient.sendUpdateTrackSettings(P)}),n.on(TrackEvent.UpdateSubscription,P=>{P.participantTracks.forEach(R=>{R.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(P)}),n.on(TrackEvent.SubscriptionPermissionChanged,P=>{this.emit(ParticipantEvent.TrackSubscriptionPermissionChanged,n,P)}),n.on(TrackEvent.SubscriptionStatusChanged,P=>{this.emit(ParticipantEvent.TrackSubscriptionStatusChanged,n,P)}),n.on(TrackEvent.Subscribed,P=>{this.emit(ParticipantEvent.TrackSubscribed,P,n)}),n.on(TrackEvent.Unsubscribed,P=>{this.emit(ParticipantEvent.TrackUnsubscribed,P,n)}),n.on(TrackEvent.SubscriptionFailed,P=>{this.emit(ParticipantEvent.TrackSubscriptionFailed,n.trackSid,P)})}getTrackPublication(n){const P=super.getTrackPublication(n);if(P)return P}getTrackPublicationByName(n){const P=super.getTrackPublicationByName(n);if(P)return P}setVolume(n){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Track.Source.Microphone;this.volumeMap.set(P,n);const R=this.getTrackPublication(P);R&&R.track&&R.track.setVolume(n)}getVolume(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Track.Source.Microphone;const P=this.getTrackPublication(n);return P&&P.track?P.track.getVolume():this.volumeMap.get(n)}addSubscribedMediaTrack(n,P,R,A,L,O){let N=this.getTrackPublicationBySid(P);if(N||P.startsWith("TR")||this.trackPublications.forEach(B=>{!N&&n.kind===B.kind.toString()&&(N=B)}),!N){if(O===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:P})),this.emit(ParticipantEvent.TrackSubscriptionFailed,P);return}O===void 0&&(O=20),setTimeout(()=>{this.addSubscribedMediaTrack(n,P,R,A,L,O-1)},150);return}if(n.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(N))),this.emit(ParticipantEvent.TrackSubscriptionFailed,P);return}const V=n.kind==="video";let j;return V?j=new RemoteVideoTrack(n,P,A,L):j=new RemoteAudioTrack(n,P,A,this.audioContext,this.audioOutput),j.source=N.source,j.isMuted=N.isMuted,j.setMediaStream(R),j.start(),N.setTrack(j),this.volumeMap.has(N.source)&&isRemoteTrack(j)&&isAudioTrack(j)&&j.setVolume(this.volumeMap.get(N.source)),N}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(n){return this.trackPublications.get(n)}updateInfo(n){if(!super.updateInfo(n))return!1;const P=new Map,R=new Map;return n.tracks.forEach(A=>{var L,O;let N=this.getTrackPublicationBySid(A.sid);if(N)N.updateInfo(A);else{const V=Track.kindFromProto(A.type);if(!V)return;N=new RemoteTrackPublication(V,A,(L=this.signalClient.connectOptions)===null||L===void 0?void 0:L.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(O=this.loggerOptions)===null||O===void 0?void 0:O.loggerName}),N.updateInfo(A),R.set(A.sid,N);const j=Array.from(this.trackPublications.values()).find(B=>B.source===N?.source);j&&N.source!==Track.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(N.source),Object.assign(Object.assign({},this.logContext),{oldTrack:getLogContextFromTrack(j),newTrack:getLogContextFromTrack(N)})),this.addTrackPublication(N)}P.set(A.sid,N)}),this.trackPublications.forEach(A=>{P.has(A.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),getLogContextFromTrack(A))),this.unpublishTrack(A.trackSid,!0))}),R.forEach(A=>{this.emit(ParticipantEvent.TrackPublished,A)}),!0}unpublishTrack(n,P){const R=this.trackPublications.get(n);if(!R)return;const{track:A}=R;switch(A&&(A.stop(),R.setTrack(void 0)),this.trackPublications.delete(n),R.kind){case Track.Kind.Audio:this.audioTrackPublications.delete(n);break;case Track.Kind.Video:this.videoTrackPublications.delete(n);break}P&&this.emit(ParticipantEvent.TrackUnpublished,R)}setAudioOutput(n){return __awaiter(this,void 0,void 0,function*(){this.audioOutput=n;const P=[];this.audioTrackPublications.forEach(R=>{var A;isAudioTrack(R.track)&&isRemoteTrack(R.track)&&P.push(R.track.setSinkId((A=n.deviceId)!==null&&A!==void 0?A:"default"))}),yield Promise.all(P)})}emit(n){for(var P=arguments.length,R=new Array(P>1?P-1:0),A=1;A<P;A++)R[A-1]=arguments[A];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:n,args:R})),super.emit(n,...R)}}var ConnectionState;(function(T){T.Disconnected="disconnected",T.Connecting="connecting",T.Connected="connected",T.Reconnecting="reconnecting",T.SignalReconnecting="signalReconnecting"})(ConnectionState||(ConnectionState={}));const connectionReconcileFrequency=4*1e3;class Room extends eventsExports.EventEmitter{constructor(n){var P,R,A,L;if(super(),P=this,this.state=ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=livekitLogger,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(O,N,V)=>__awaiter(this,void 0,void 0,function*(){var j;if(!isBrowserSupported())throw isReactNative$1()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const B=yield this.disconnectLock.lock();if(this.state===ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),B(),Promise.resolve();if(this.connectFuture)return B(),this.connectFuture.promise;this.setAndEmitConnectionState(ConnectionState.Connecting),((j=this.regionUrlProvider)===null||j===void 0?void 0:j.getServerUrl().toString())!==O&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),isCloud(new URL(O))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new RegionUrlProvider(O,N):this.regionUrlProvider.updateToken(N),this.regionUrlProvider.fetchRegionSettings().then(q=>{var H;(H=this.regionUrlProvider)===null||H===void 0||H.setServerReportedRegions(q)}).catch(q=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:q}))}));const z=(q,H,$)=>__awaiter(this,void 0,void 0,function*(){var Q,U;this.abortController&&this.abortController.abort();const J=new AbortController;this.abortController=J,B?.();try{yield this.attemptConnection($??O,N,V,J),this.abortController=void 0,q()}catch(G){if(this.regionUrlProvider&&G instanceof ConnectionError&&G.reason!==ConnectionErrorReason.Cancelled&&G.reason!==ConnectionErrorReason.NotAllowed){let K=null;try{K=yield this.regionUrlProvider.getNextBestRegionUrl((Q=this.abortController)===null||Q===void 0?void 0:Q.signal)}catch(Y){if(Y instanceof ConnectionError&&(Y.status===401||Y.reason===ConnectionErrorReason.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),H(Y);return}}K&&!(!((U=this.abortController)===null||U===void 0)&&U.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(G.message,". Retrying with another region: ").concat(K),this.logContext),this.recreateEngine(),yield z(q,H,K)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,getDisconnectReasonFromConnectionError(G)),H(G))}else{let K=DisconnectReason.UNKNOWN_REASON;G instanceof ConnectionError&&(K=getDisconnectReasonFromConnectionError(G)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,K),H(G)}}}),W=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Future((q,H)=>{z(q,H,W)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(O,N,V,j,B,z)=>__awaiter(this,void 0,void 0,function*(){var W,q,H;const $=yield V.join(O,N,{autoSubscribe:j.autoSubscribe,adaptiveStream:typeof B.adaptiveStream=="object"?!0:B.adaptiveStream,maxRetries:j.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:j.websocketTimeout},z.signal);let Q=$.serverInfo;if(Q||(Q={version:$.serverVersion,region:$.serverRegion}),this.serverInfo=Q,this.log.debug("connected to Livekit Server ".concat(Object.entries(Q).map(U=>{let[J,G]=U;return"".concat(J,": ").concat(G)}).join(", ")),{room:(W=$.room)===null||W===void 0?void 0:W.name,roomSid:(q=$.room)===null||q===void 0?void 0:q.sid,identity:(H=$.participant)===null||H===void 0?void 0:H.identity}),!Q.version)throw new UnsupportedServer("unknown server version");return Q.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),B.dynacast=!1),$}),this.applyJoinResponse=O=>{const N=O.participant;if(this.localParticipant.sid=N.sid,this.localParticipant.identity=N.identity,this.localParticipant.setEnabledPublishCodecs(O.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(O.sifTrailer)}catch(V){this.log.error(V instanceof Error?V.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:V}))}this.handleParticipantUpdates([N,...O.otherParticipants]),O.room&&this.handleRoomUpdate(O.room)},this.attemptConnection=(O,N,V,j)=>__awaiter(this,void 0,void 0,function*(){var B,z;this.state===ConnectionState.Reconnecting||this.isResuming||!((B=this.engine)===null||B===void 0)&&B.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((z=this.regionUrlProvider)===null||z===void 0)&&z.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},roomConnectOptionDefaults),V),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const W=yield this.connectSignal(O,N,this.engine,this.connOptions,this.options,j);this.applyJoinResponse(W),this.setupLocalParticipantEvents(),this.emit(RoomEvent.SignalConnected)}catch(W){yield this.engine.close(),this.recreateEngine();const q=new ConnectionError("could not establish signal connection",ConnectionErrorReason.ServerUnreachable);throw W instanceof Error&&(q.message="".concat(q.message,": ").concat(W.message)),W instanceof ConnectionError&&(q.reason=W.reason,q.status=W.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:W})),q}if(j.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ConnectionError("Connection attempt aborted",ConnectionErrorReason.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,j)}catch(W){throw yield this.engine.close(),this.recreateEngine(),W}isWeb()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),isWeb()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ConnectionState.Connected),this.emit(RoomEvent.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var O=arguments.length,N=new Array(O),V=0;V<O;V++)N[V]=arguments[V];return __awaiter(P,[...N],void 0,function(){var j=this;let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var z,W,q,H;const $=yield j.disconnectLock.lock();try{if(j.state===ConnectionState.Disconnected){j.log.debug("already disconnected",j.logContext);return}j.log.info("disconnect from room",Object.assign({},j.logContext)),(j.state===ConnectionState.Connecting||j.state===ConnectionState.Reconnecting||j.isResuming)&&(j.log.warn("abort connection attempt",j.logContext),(z=j.abortController)===null||z===void 0||z.abort(),(q=(W=j.connectFuture)===null||W===void 0?void 0:W.reject)===null||q===void 0||q.call(W,new ConnectionError("Client initiated disconnect",ConnectionErrorReason.Cancelled)),j.connectFuture=void 0),!((H=j.engine)===null||H===void 0)&&H.client.isDisconnected||(yield j.engine.client.sendLeave()),j.engine&&(yield j.engine.close()),j.handleDisconnect(B,DisconnectReason.CLIENT_INITIATED),j.engine=void 0}finally{$()}})()})},this.onPageLeave=()=>__awaiter(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>__awaiter(this,void 0,void 0,function*(){const O=[],N=getBrowser();if(N&&N.os==="iOS"){const V="livekit-dummy-audio-el";let j=document.getElementById(V);if(!j){j=document.createElement("audio"),j.id=V,j.autoplay=!0,j.hidden=!0;const B=getEmptyAudioStreamTrack();B.enabled=!0;const z=new MediaStream([B]);j.srcObject=z,document.addEventListener("visibilitychange",()=>{j&&(j.srcObject=document.hidden?null:z,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(j),this.once(RoomEvent.Disconnected,()=>{j?.remove(),j=null})}O.push(j)}this.remoteParticipants.forEach(V=>{V.audioTrackPublications.forEach(j=>{j.track&&j.track.attachedElements.forEach(B=>{O.push(B)})})});try{yield Promise.all([this.acquireAudioContext(),...O.map(V=>(V.muted=!1,V.play()))]),this.handleAudioPlaybackStarted()}catch(V){throw this.handleAudioPlaybackFailed(V),V}}),this.startVideo=()=>__awaiter(this,void 0,void 0,function*(){const O=[];for(const N of this.remoteParticipants.values())N.videoTrackPublications.forEach(V=>{var j;(j=V.track)===null||j===void 0||j.attachedElements.forEach(B=>{O.includes(B)||O.push(B)})});yield Promise.all(O.map(N=>N.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(N=>{N.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const O of this.remoteParticipants.values())this.handleParticipantDisconnected(O.identity,O);this.setAndEmitConnectionState(ConnectionState.Reconnecting)&&this.emit(RoomEvent.Reconnecting)},this.handleSignalRestarted=O=>__awaiter(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(O.serverRegion),Object.assign(Object.assign({},this.logContext),{region:O.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(O);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(N){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:N}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:O.serverRegion}))}catch{return}this.setAndEmitConnectionState(ConnectionState.Connected),this.emit(RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=O=>{O.forEach(N=>{var V;if(N.identity===this.localParticipant.identity){this.localParticipant.updateInfo(N);return}N.identity===""&&(N.identity=(V=this.sidToIdentity.get(N.sid))!==null&&V!==void 0?V:"");let j=this.remoteParticipants.get(N.identity);N.state===ParticipantInfo_State.DISCONNECTED?this.handleParticipantDisconnected(N.identity,j):j=this.getOrCreateParticipant(N.identity,N)})},this.handleActiveSpeakersUpdate=O=>{const N=[],V={};O.forEach(j=>{if(V[j.sid]=!0,j.sid===this.localParticipant.sid)this.localParticipant.audioLevel=j.level,this.localParticipant.setIsSpeaking(!0),N.push(this.localParticipant);else{const B=this.getRemoteParticipantBySid(j.sid);B&&(B.audioLevel=j.level,B.setIsSpeaking(!0),N.push(B))}}),V[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(j=>{V[j.sid]||(j.audioLevel=0,j.setIsSpeaking(!1))}),this.activeSpeakers=N,this.emitWhenConnected(RoomEvent.ActiveSpeakersChanged,N)},this.handleSpeakersChanged=O=>{const N=new Map;this.activeSpeakers.forEach(j=>{const B=this.remoteParticipants.get(j.identity);B&&B.sid!==j.sid||N.set(j.sid,j)}),O.forEach(j=>{let B=this.getRemoteParticipantBySid(j.sid);j.sid===this.localParticipant.sid&&(B=this.localParticipant),B&&(B.audioLevel=j.level,B.setIsSpeaking(j.active),j.active?N.set(j.sid,B):N.delete(j.sid))});const V=Array.from(N.values());V.sort((j,B)=>B.audioLevel-j.audioLevel),this.activeSpeakers=V,this.emitWhenConnected(RoomEvent.ActiveSpeakersChanged,V)},this.handleStreamStateUpdate=O=>{O.streamStates.forEach(N=>{const V=this.getRemoteParticipantBySid(N.participantSid);if(!V)return;const j=V.getTrackPublicationBySid(N.trackSid);if(!j||!j.track)return;const B=Track.streamStateFromProto(N.state);j.track.setStreamState(B),B!==j.track.streamState&&(V.emit(ParticipantEvent.TrackStreamStateChanged,j,j.track.streamState),this.emitWhenConnected(RoomEvent.TrackStreamStateChanged,j,j.track.streamState,V))})},this.handleSubscriptionPermissionUpdate=O=>{const N=this.getRemoteParticipantBySid(O.participantSid);if(!N)return;const V=N.getTrackPublicationBySid(O.trackSid);V&&V.setAllowed(O.allowed)},this.handleSubscriptionError=O=>{const N=Array.from(this.remoteParticipants.values()).find(j=>j.trackPublications.has(O.trackSid));if(!N)return;const V=N.getTrackPublicationBySid(O.trackSid);V&&V.setSubscriptionError(O.err)},this.handleDataPacket=O=>{const N=this.remoteParticipants.get(O.participantIdentity);if(O.value.case==="user")this.handleUserPacket(N,O.value.value,O.kind);else if(O.value.case==="transcription")this.handleTranscription(N,O.value.value);else if(O.value.case==="sipDtmf")this.handleSipDtmf(N,O.value.value);else if(O.value.case==="chatMessage")this.handleChatMessage(N,O.value.value);else if(O.value.case==="metrics")this.handleMetrics(O.value.value,N);else if(O.value.case==="streamHeader"||O.value.case==="streamChunk"||O.value.case==="streamTrailer")this.handleDataStream(O);else if(O.value.case==="rpcRequest"){const V=O.value.value;this.handleIncomingRpcRequest(O.participantIdentity,V.id,V.method,V.payload,V.responseTimeoutMs,V.version)}},this.handleUserPacket=(O,N,V)=>{this.emit(RoomEvent.DataReceived,N.payload,O,V,N.topic),O?.emit(ParticipantEvent.DataReceived,N.payload,V)},this.handleSipDtmf=(O,N)=>{this.emit(RoomEvent.SipDTMFReceived,N,O),O?.emit(ParticipantEvent.SipDTMFReceived,N)},this.handleTranscription=(O,N)=>{const V=N.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(N.transcribedParticipantIdentity),j=V?.trackPublications.get(N.trackId),B=extractTranscriptionSegments(N,this.transcriptionReceivedTimes);j?.emit(TrackEvent.TranscriptionReceived,B),V?.emit(ParticipantEvent.TranscriptionReceived,B,j),this.emit(RoomEvent.TranscriptionReceived,B,V,j)},this.handleChatMessage=(O,N)=>{const V=extractChatMessage(N);this.emit(RoomEvent.ChatMessage,V,O)},this.handleMetrics=(O,N)=>{this.emit(RoomEvent.MetricsReceived,O,N)},this.handleDataStream=O=>{this.incomingDataStreamManager.handleDataStreamPacket(O)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=O=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:O})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>__awaiter(this,void 0,void 0,function*(){var O;((O=getBrowser())===null||O===void 0?void 0:O.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(RoomEvent.MediaDevicesChanged)}),this.handleRoomUpdate=O=>{const N=this.roomInfo;this.roomInfo=O,N&&N.metadata!==O.metadata&&this.emitWhenConnected(RoomEvent.RoomMetadataChanged,O.metadata),N?.activeRecording!==O.activeRecording&&this.emitWhenConnected(RoomEvent.RecordingStatusChanged,O.activeRecording)},this.handleConnectionQualityUpdate=O=>{O.updates.forEach(N=>{if(N.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(N.quality);return}const V=this.getRemoteParticipantBySid(N.participantSid);V&&V.setConnectionQuality(N.quality)})},this.onLocalParticipantMetadataChanged=O=>{this.emit(RoomEvent.ParticipantMetadataChanged,O,this.localParticipant)},this.onLocalParticipantNameChanged=O=>{this.emit(RoomEvent.ParticipantNameChanged,O,this.localParticipant)},this.onLocalAttributesChanged=O=>{this.emit(RoomEvent.ParticipantAttributesChanged,O,this.localParticipant)},this.onLocalTrackMuted=O=>{this.emit(RoomEvent.TrackMuted,O,this.localParticipant)},this.onLocalTrackUnmuted=O=>{this.emit(RoomEvent.TrackUnmuted,O,this.localParticipant)},this.onTrackProcessorUpdate=O=>{var N;(N=O?.onPublish)===null||N===void 0||N.call(O,this)},this.onLocalTrackPublished=O=>__awaiter(this,void 0,void 0,function*(){var N,V,j,B,z,W;(N=O.track)===null||N===void 0||N.on(TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),(V=O.track)===null||V===void 0||V.on(TrackEvent.Restarted,this.onLocalTrackRestarted),(z=(B=(j=O.track)===null||j===void 0?void 0:j.getProcessor())===null||B===void 0?void 0:B.onPublish)===null||z===void 0||z.call(B,this),this.emit(RoomEvent.LocalTrackPublished,O,this.localParticipant),isLocalAudioTrack(O.track)&&(yield O.track.checkForSilence())&&this.emit(RoomEvent.LocalAudioSilenceDetected,O);const q=yield(W=O.track)===null||W===void 0?void 0:W.getDeviceId(!1),H=sourceToKind(O.source);H&&q&&q!==this.localParticipant.activeDeviceMap.get(H)&&(this.localParticipant.activeDeviceMap.set(H,q),this.emit(RoomEvent.ActiveDeviceChanged,H,q))}),this.onLocalTrackUnpublished=O=>{var N,V;(N=O.track)===null||N===void 0||N.off(TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),(V=O.track)===null||V===void 0||V.off(TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(RoomEvent.LocalTrackUnpublished,O,this.localParticipant)},this.onLocalTrackRestarted=O=>__awaiter(this,void 0,void 0,function*(){const N=yield O.getDeviceId(!1),V=sourceToKind(O.source);V&&N&&N!==this.localParticipant.activeDeviceMap.get(V)&&(this.log.debug("local track restarted, setting ".concat(V," ").concat(N," active"),this.logContext),this.localParticipant.activeDeviceMap.set(V,N),this.emit(RoomEvent.ActiveDeviceChanged,V,N))}),this.onLocalConnectionQualityChanged=O=>{this.emit(RoomEvent.ConnectionQualityChanged,O,this.localParticipant)},this.onMediaDevicesError=(O,N)=>{this.emit(RoomEvent.MediaDevicesError,O,N)},this.onLocalParticipantPermissionsChanged=O=>{this.emit(RoomEvent.ParticipantPermissionsChanged,O,this.localParticipant)},this.onLocalChatMessageSent=O=>{this.emit(RoomEvent.ChatMessage,O,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},roomOptionDefaults),n),this.log=getLogger((R=this.options.loggerName)!==null&&R!==void 0?R:LoggerNames.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},audioDefaults),n?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},videoDefaults),n?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},publishDefaults),n?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new IncomingDataStreamManager,this.outgoingDataStreamManager=new OutgoingDataStreamManager(this.engine,this.log),this.disconnectLock=new _$1,this.localParticipant=new LocalParticipant("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",unwrapConstraint(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",unwrapConstraint(this.options.audioCaptureDefaults.deviceId)),!((A=this.options.audioOutput)===null||A===void 0)&&A.deviceId&&this.switchActiveDevice("audiooutput",unwrapConstraint(this.options.audioOutput.deviceId)).catch(O=>this.log.warn("Could not set audio output: ".concat(O.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),isWeb()){const O=new AbortController;(L=navigator.mediaDevices)===null||L===void 0||L.addEventListener("devicechange",this.handleDeviceChange,{signal:O.signal}),Room.cleanupRegistry&&Room.cleanupRegistry.register(this,()=>{O.abort()})}}registerTextStreamHandler(n,P){return this.incomingDataStreamManager.registerTextStreamHandler(n,P)}unregisterTextStreamHandler(n){return this.incomingDataStreamManager.unregisterTextStreamHandler(n)}registerByteStreamHandler(n,P){return this.incomingDataStreamManager.registerByteStreamHandler(n,P)}unregisterByteStreamHandler(n){return this.incomingDataStreamManager.unregisterByteStreamHandler(n)}registerRpcMethod(n,P){if(this.rpcHandlers.has(n))throw Error("RPC handler already registered for method ".concat(n,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(n,P)}unregisterRpcMethod(n){this.rpcHandlers.delete(n)}setE2EEEnabled(n){return __awaiter(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(n)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(n,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var n;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new E2EEManager(this.options.e2ee),this.e2eeManager.on(EncryptionEvent.ParticipantEncryptionStatusChanged,(P,R)=>{isLocalParticipant(R)&&(this.isE2EEEnabled=P),this.emit(RoomEvent.ParticipantEncryptionStatusChanged,P,R)}),this.e2eeManager.on(EncryptionEvent.EncryptionError,P=>this.emit(RoomEvent.EncryptionError,P)),(n=this.e2eeManager)===null||n===void 0||n.setup(this))}get logContext(){var n;return{room:this.name,roomID:(n=this.roomInfo)===null||n===void 0?void 0:n.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var n,P;return(P=(n=this.roomInfo)===null||n===void 0?void 0:n.activeRecording)!==null&&P!==void 0?P:!1}getSid(){return __awaiter(this,void 0,void 0,function*(){return this.state===ConnectionState.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((n,P)=>{const R=A=>{A.sid!==""&&(this.engine.off(EngineEvent.RoomUpdate,R),n(A.sid))};this.engine.on(EngineEvent.RoomUpdate,R),this.once(RoomEvent.Disconnected,()=>{this.engine.off(EngineEvent.RoomUpdate,R),P("Room disconnected before room server id was available")})})})}get name(){var n,P;return(P=(n=this.roomInfo)===null||n===void 0?void 0:n.name)!==null&&P!==void 0?P:""}get metadata(){var n;return(n=this.roomInfo)===null||n===void 0?void 0:n.metadata}get numParticipants(){var n,P;return(P=(n=this.roomInfo)===null||n===void 0?void 0:n.numParticipants)!==null&&P!==void 0?P:0}get numPublishers(){var n,P;return(P=(n=this.roomInfo)===null||n===void 0?void 0:n.numPublishers)!==null&&P!==void 0?P:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new RTCEngine(this.options),this.engine.on(EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(EngineEvent.RoomUpdate,this.handleRoomUpdate).on(EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(EngineEvent.SubscriptionError,this.handleSubscriptionError).on(EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(EngineEvent.MediaTrackAdded,(n,P,R)=>{this.onTrackAdded(n,P,R)}).on(EngineEvent.Disconnected,n=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,n)}).on(EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(EngineEvent.DataPacketReceived,this.handleDataPacket).on(EngineEvent.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ConnectionState.SignalReconnecting)&&this.emit(RoomEvent.SignalReconnecting)}).on(EngineEvent.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ConnectionState.Connected)&&this.emit(RoomEvent.Reconnected)}).on(EngineEvent.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(EngineEvent.Restarting,this.handleRestarting).on(EngineEvent.SignalRestarted,this.handleSignalRestarted).on(EngineEvent.Offline,()=>{this.setAndEmitConnectionState(ConnectionState.Reconnecting)&&this.emit(RoomEvent.Reconnecting)}).on(EngineEvent.DCBufferStatusChanged,(n,P)=>{this.emit(RoomEvent.DCBufferStatusChanged,n,P)}).on(EngineEvent.LocalTrackSubscribed,n=>{const P=this.localParticipant.getTrackPublications().find(R=>{let{trackSid:A}=R;return A===n});if(!P){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(ParticipantEvent.LocalTrackSubscribed,P),this.emitWhenConnected(RoomEvent.LocalTrackSubscribed,P,this.localParticipant)}).on(EngineEvent.RoomMoved,n=>{this.log.debug("room moved",n),n.room&&this.handleRoomUpdate(n.room),this.remoteParticipants.forEach((P,R)=>{this.handleParticipantDisconnected(R,P)}),this.emit(RoomEvent.Moved,n.room.name),n.participant?this.handleParticipantUpdates([n.participant,...n.otherParticipants]):this.handleParticipantUpdates(n.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(n){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return DeviceManager.getInstance().getDevices(n,P)}prepareConnection(n,P){return __awaiter(this,void 0,void 0,function*(){if(this.state===ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(n),this.logContext);try{if(isCloud(new URL(n))&&P){this.regionUrlProvider=new RegionUrlProvider(n,P);const R=yield this.regionUrlProvider.getNextBestRegionUrl();R&&this.state===ConnectionState.Disconnected&&(this.regionUrl=R,yield fetch(toHttpUrl(R),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(R),this.logContext))}else yield fetch(toHttpUrl(n),{method:"HEAD"})}catch(R){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:R}))}}})}getParticipantByIdentity(n){return this.localParticipant.identity===n?this.localParticipant:this.remoteParticipants.get(n)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(n,P){return __awaiter(this,void 0,void 0,function*(){let R=()=>__awaiter(this,void 0,void 0,function*(){}),A;switch(n){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":A=new SimulateScenario({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":A=new SimulateScenario({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":A=new SimulateScenario({scenario:{case:"serverLeave",value:!0}});break;case"migration":A=new SimulateScenario({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":R=()=>__awaiter(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),A=new SimulateScenario({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":R=()=>__awaiter(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),A=new SimulateScenario({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":A=new SimulateScenario({scenario:{case:"switchCandidateProtocol",value:n==="force-tls"?2:1}}),R=()=>__awaiter(this,void 0,void 0,function*(){const L=this.engine.client.onLeave;L&&L(new LeaveRequest({reason:DisconnectReason.CLIENT_INITIATED,action:LeaveRequest_Action.RECONNECT}))});break;case"subscriber-bandwidth":if(P===void 0||typeof P!="number")throw new Error("subscriber-bandwidth requires a number as argument");A=new SimulateScenario({scenario:{case:"subscriberBandwidth",value:numberToBigInt(P)}});break;case"leave-full-reconnect":A=new SimulateScenario({scenario:{case:"leaveRequestFullReconnect",value:!0}})}A&&(yield this.engine.client.sendSimulateScenario(A),yield R())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(n){return this.localParticipant.activeDeviceMap.get(n)}switchActiveDevice(n,P){return __awaiter(this,arguments,void 0,function(R,A){var L=this;let O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var N,V,j,B,z,W,q;let H=!0,$=!1;const Q=O?{exact:A}:A;if(R==="audioinput"){$=L.localParticipant.audioTrackPublications.size===0;const U=(N=L.getActiveDevice(R))!==null&&N!==void 0?N:L.options.audioCaptureDefaults.deviceId;L.options.audioCaptureDefaults.deviceId=Q;const J=Array.from(L.localParticipant.audioTrackPublications.values()).filter(K=>K.source===Track.Source.Microphone);try{H=(yield Promise.all(J.map(K=>{var Y;return(Y=K.audioTrack)===null||Y===void 0?void 0:Y.setDeviceId(Q)}))).every(K=>K===!0)}catch(K){throw L.options.audioCaptureDefaults.deviceId=U,K}const G=J.some(K=>{var Y,Z;return(Z=(Y=K.track)===null||Y===void 0?void 0:Y.isMuted)!==null&&Z!==void 0?Z:!1});H&&G&&($=!0)}else if(R==="videoinput"){$=L.localParticipant.videoTrackPublications.size===0;const U=(V=L.getActiveDevice(R))!==null&&V!==void 0?V:L.options.videoCaptureDefaults.deviceId;L.options.videoCaptureDefaults.deviceId=Q;const J=Array.from(L.localParticipant.videoTrackPublications.values()).filter(K=>K.source===Track.Source.Camera);try{H=(yield Promise.all(J.map(K=>{var Y;return(Y=K.videoTrack)===null||Y===void 0?void 0:Y.setDeviceId(Q)}))).every(K=>K===!0)}catch(K){throw L.options.videoCaptureDefaults.deviceId=U,K}const G=J.some(K=>{var Y,Z;return(Z=(Y=K.track)===null||Y===void 0?void 0:Y.isMuted)!==null&&Z!==void 0?Z:!1});H&&G&&($=!0)}else if(R==="audiooutput"){if($=!0,!supportsSetSinkId()&&!L.options.webAudioMix||L.options.webAudioMix&&L.audioContext&&!("setSinkId"in L.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");L.options.webAudioMix&&(A=(j=yield DeviceManager.getInstance().normalizeDeviceId("audiooutput",A))!==null&&j!==void 0?j:""),(B=(q=L.options).audioOutput)!==null&&B!==void 0||(q.audioOutput={});const U=(z=L.getActiveDevice(R))!==null&&z!==void 0?z:L.options.audioOutput.deviceId;L.options.audioOutput.deviceId=A;try{L.options.webAudioMix&&((W=L.audioContext)===null||W===void 0||W.setSinkId(A)),yield Promise.all(Array.from(L.remoteParticipants.values()).map(J=>J.setAudioOutput({deviceId:A})))}catch(J){throw L.options.audioOutput.deviceId=U,J}}return $&&(L.localParticipant.activeDeviceMap.set(R,A),L.emit(RoomEvent.ActiveDeviceChanged,R,A)),H})()})}setupLocalParticipantEvents(){this.localParticipant.on(ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).on(ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(ParticipantEvent.AudioStreamAcquired,this.startAudio).on(ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).on(ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var n;(n=this.engine)===null||n===void 0||n.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(n,P,R){if(this.state===ConnectionState.Connecting||this.state===ConnectionState.Reconnecting){const z=()=>{this.onTrackAdded(n,P,R),W()},W=()=>{this.off(RoomEvent.Reconnected,z),this.off(RoomEvent.Connected,z),this.off(RoomEvent.Disconnected,W)};this.once(RoomEvent.Reconnected,z),this.once(RoomEvent.Connected,z),this.once(RoomEvent.Disconnected,W);return}if(this.state===ConnectionState.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(n.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const A=unpackStreamId(P.id),L=A[0];let O=A[1],N=n.id;if(O&&O.startsWith("TR")&&(N=O),L===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const V=Array.from(this.remoteParticipants.values()).find(z=>z.sid===L);if(!V){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(L),this.logContext);return}let j;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?j=this.options.adaptiveStream:j={});const B=V.addSubscribedMediaTrack(n,N,P,R,j);B?.isEncrypted&&!this.e2eeManager&&this.emit(RoomEvent.EncryptionError,new Error("Encrypted ".concat(B.source," track received from participant ").concat(V.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,P=arguments.length>1?arguments[1]:void 0;var R;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ConnectionState.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(A=>{A.trackPublications.forEach(L=>{A.unpublishTrack(L.trackSid)})}),this.localParticipant.trackPublications.forEach(A=>{var L,O,N;A.track&&this.localParticipant.unpublishTrack(A.track,n),n?((L=A.track)===null||L===void 0||L.detach(),(O=A.track)===null||O===void 0||O.stop()):(N=A.track)===null||N===void 0||N.stopMonitor()}),this.localParticipant.off(ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).off(ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(ParticipantEvent.AudioStreamAcquired,this.startAudio).off(ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).off(ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),isWeb()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(R=navigator.mediaDevices)===null||R===void 0||R.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ConnectionState.Disconnected),this.emit(RoomEvent.Disconnected,P)}}}handleParticipantDisconnected(n,P){var R;this.remoteParticipants.delete(n),P&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(n),P.trackPublications.forEach(A=>{P.unpublishTrack(A.trackSid,!0)}),this.emit(RoomEvent.ParticipantDisconnected,P),P.setDisconnected(),(R=this.localParticipant)===null||R===void 0||R.handleParticipantDisconnected(P.identity))}handleIncomingRpcRequest(n,P,R,A,L,O){return __awaiter(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(n,P),O!==1){yield this.engine.publishRpcResponse(n,P,null,RpcError.builtIn("UNSUPPORTED_VERSION"));return}const N=this.rpcHandlers.get(R);if(!N){yield this.engine.publishRpcResponse(n,P,null,RpcError.builtIn("UNSUPPORTED_METHOD"));return}let V=null,j=null;try{const B=yield N({requestId:P,callerIdentity:n,payload:A,responseTimeout:L});byteLength$1(B)>MAX_PAYLOAD_BYTES?(V=RpcError.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(R))):j=B}catch(B){B instanceof RpcError?V=B:(console.warn("Uncaught error returned by RPC handler for ".concat(R,". Returning APPLICATION_ERROR instead."),B),V=RpcError.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(n,P,j,V)})}selectDefaultDevices(){return __awaiter(this,void 0,void 0,function*(){var n,P,R;const A=DeviceManager.getInstance().previousDevices,L=yield DeviceManager.getInstance().getDevices(void 0,!1),O=getBrowser();if(O?.name==="Chrome"&&O.os!=="iOS")for(let V of L){const j=A.find(B=>B.deviceId===V.deviceId);j&&j.label!==""&&j.kind===V.kind&&j.label!==V.label&&this.getActiveDevice(V.kind)==="default"&&this.emit(RoomEvent.ActiveDeviceChanged,V.kind,V.deviceId)}const N=["audiooutput","audioinput","videoinput"];for(let V of N){const j=kindToSource(V),B=this.localParticipant.getTrackPublication(j);if(B&&(!((n=B.track)===null||n===void 0)&&n.isUserProvided))continue;const z=L.filter(q=>q.kind===V),W=this.getActiveDevice(V);if(W===((P=A.filter(q=>q.kind===V)[0])===null||P===void 0?void 0:P.deviceId)&&z.length>0&&((R=z[0])===null||R===void 0?void 0:R.deviceId)!==W){yield this.switchActiveDevice(V,z[0].deviceId);continue}V==="audioinput"&&!isSafariBased()||V==="videoinput"||z.length>0&&!z.find(q=>q.deviceId===this.getActiveDevice(V))&&(V!=="audiooutput"||!isSafariBased())&&(yield this.switchActiveDevice(V,z[0].deviceId))}})}acquireAudioContext(){return __awaiter(this,void 0,void 0,function*(){var n,P;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(n=getNewAudioContext())!==null&&n!==void 0?n:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(A=>A.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),sleep(200)])}catch(A){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:A}))}const R=((P=this.audioContext)===null||P===void 0?void 0:P.state)==="running";R!==this.canPlaybackAudio&&(this.audioEnabled=R,this.emit(RoomEvent.AudioPlaybackStatusChanged,R))})}createParticipant(n,P){var R;let A;return P?A=RemoteParticipant.fromParticipantInfo(this.engine.client,P,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):A=new RemoteParticipant(this.engine.client,"",n,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&A.setAudioContext(this.audioContext),!((R=this.options.audioOutput)===null||R===void 0)&&R.deviceId&&A.setAudioOutput(this.options.audioOutput).catch(L=>this.log.warn("Could not set audio output: ".concat(L.message),this.logContext)),A}getOrCreateParticipant(n,P){if(this.remoteParticipants.has(n)){const A=this.remoteParticipants.get(n);return P&&A.updateInfo(P)&&this.sidToIdentity.set(P.sid,P.identity),A}const R=this.createParticipant(n,P);return this.remoteParticipants.set(n,R),this.sidToIdentity.set(P.sid,P.identity),this.emitWhenConnected(RoomEvent.ParticipantConnected,R),R.on(ParticipantEvent.TrackPublished,A=>{this.emitWhenConnected(RoomEvent.TrackPublished,A,R)}).on(ParticipantEvent.TrackSubscribed,(A,L)=>{A.kind===Track.Kind.Audio?(A.on(TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),A.on(TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):A.kind===Track.Kind.Video&&(A.on(TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),A.on(TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(RoomEvent.TrackSubscribed,A,L,R)}).on(ParticipantEvent.TrackUnpublished,A=>{this.emit(RoomEvent.TrackUnpublished,A,R)}).on(ParticipantEvent.TrackUnsubscribed,(A,L)=>{this.emit(RoomEvent.TrackUnsubscribed,A,L,R)}).on(ParticipantEvent.TrackMuted,A=>{this.emitWhenConnected(RoomEvent.TrackMuted,A,R)}).on(ParticipantEvent.TrackUnmuted,A=>{this.emitWhenConnected(RoomEvent.TrackUnmuted,A,R)}).on(ParticipantEvent.ParticipantMetadataChanged,A=>{this.emitWhenConnected(RoomEvent.ParticipantMetadataChanged,A,R)}).on(ParticipantEvent.ParticipantNameChanged,A=>{this.emitWhenConnected(RoomEvent.ParticipantNameChanged,A,R)}).on(ParticipantEvent.AttributesChanged,A=>{this.emitWhenConnected(RoomEvent.ParticipantAttributesChanged,A,R)}).on(ParticipantEvent.ConnectionQualityChanged,A=>{this.emitWhenConnected(RoomEvent.ConnectionQualityChanged,A,R)}).on(ParticipantEvent.ParticipantPermissionsChanged,A=>{this.emitWhenConnected(RoomEvent.ParticipantPermissionsChanged,A,R)}).on(ParticipantEvent.TrackSubscriptionStatusChanged,(A,L)=>{this.emitWhenConnected(RoomEvent.TrackSubscriptionStatusChanged,A,L,R)}).on(ParticipantEvent.TrackSubscriptionFailed,(A,L)=>{this.emit(RoomEvent.TrackSubscriptionFailed,A,R,L)}).on(ParticipantEvent.TrackSubscriptionPermissionChanged,(A,L)=>{this.emitWhenConnected(RoomEvent.TrackSubscriptionPermissionChanged,A,L,R)}).on(ParticipantEvent.Active,()=>{this.emitWhenConnected(RoomEvent.ParticipantActive,R),R.kind===ParticipantInfo_Kind.AGENT&&this.localParticipant.setActiveAgent(R)}),P&&R.updateInfo(P),R}sendSyncState(){const n=Array.from(this.remoteParticipants.values()).reduce((R,A)=>(R.push(...A.getTrackPublications()),R),[]),P=this.localParticipant.getTrackPublications();this.engine.sendSyncState(n,P)}updateSubscriptions(){for(const n of this.remoteParticipants.values())for(const P of n.videoTrackPublications.values())P.isSubscribed&&isRemotePub(P)&&P.emitTrackUpdate()}getRemoteParticipantBySid(n){const P=this.sidToIdentity.get(n);if(P)return this.remoteParticipants.get(P)}registerConnectionReconcile(){this.clearConnectionReconcile();let n=0;this.connectionReconcileInterval=CriticalTimers.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(n++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:n,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),n>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,DisconnectReason.STATE_MISMATCH))):n=0},connectionReconcileFrequency)}clearConnectionReconcile(){this.connectionReconcileInterval&&CriticalTimers.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(n){return n===this.state?!1:(this.state=n,this.emit(RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(n=>{let[P,R]=n;this.emit(P,...R)}),this.bufferedEvents=[]}emitWhenConnected(n){for(var P=arguments.length,R=new Array(P>1?P-1:0),A=1;A<P;A++)R[A-1]=arguments[A];if(this.state===ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([n,R]);else if(this.state===ConnectionState.Connected)return this.emit(n,...R);return!1}simulateParticipants(n){return __awaiter(this,void 0,void 0,function*(){var P,R;const A=Object.assign({audio:!0,video:!0,useRealTracks:!1},n.publish),L=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},n.participants);if(this.handleDisconnect(),this.roomInfo=new Room$1({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:protoInt64.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ParticipantInfo({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(RoomEvent.SignalConnected),this.emit(RoomEvent.Connected),this.setAndEmitConnectionState(ConnectionState.Connected),A.video){const O=new LocalTrackPublication(Track.Kind.Video,new TrackInfo({source:TrackSource.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:TrackType.AUDIO,name:"video-dummy"}),new LocalVideoTrack(A.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:createDummyVideoStreamTrack(160*((P=L.aspectRatios[0])!==null&&P!==void 0?P:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(O),this.localParticipant.emit(ParticipantEvent.LocalTrackPublished,O)}if(A.audio){const O=new LocalTrackPublication(Track.Kind.Audio,new TrackInfo({source:TrackSource.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:TrackType.AUDIO}),new LocalAudioTrack(A.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:getEmptyAudioStreamTrack(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(O),this.localParticipant.emit(ParticipantEvent.LocalTrackPublished,O)}for(let O=0;O<L.count-1;O+=1){let N=new ParticipantInfo({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(O),state:ParticipantInfo_State.ACTIVE,tracks:[],joinedAt:protoInt64.parse(Date.now())});const V=this.getOrCreateParticipant(N.identity,N);if(L.video){const j=createDummyVideoStreamTrack(160*((R=L.aspectRatios[O%L.aspectRatios.length])!==null&&R!==void 0?R:1),160,!1,!0),B=new TrackInfo({source:TrackSource.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:TrackType.AUDIO});V.addSubscribedMediaTrack(j,B.sid,new MediaStream([j]),new RTCRtpReceiver),N.tracks=[...N.tracks,B]}if(L.audio){const j=getEmptyAudioStreamTrack(),B=new TrackInfo({source:TrackSource.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:TrackType.AUDIO});V.addSubscribedMediaTrack(j,B.sid,new MediaStream([j]),new RTCRtpReceiver),N.tracks=[...N.tracks,B]}V.updateInfo(N)}})}emit(n){for(var P=arguments.length,R=new Array(P>1?P-1:0),A=1;A<P;A++)R[A-1]=arguments[A];if(n!==RoomEvent.ActiveSpeakersChanged&&n!==RoomEvent.TranscriptionReceived){const L=mapArgs(R).filter(O=>O!==void 0);this.log.debug("room event ".concat(n),Object.assign(Object.assign({},this.logContext),{event:n,args:L}))}return super.emit(n,...R)}}Room.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(T=>{T()});function mapArgs(T){return T.map(n=>{if(n)return Array.isArray(n)?mapArgs(n):typeof n=="object"?"logContext"in n?n.logContext:void 0:n})}var CheckStatus;(function(T){T[T.IDLE=0]="IDLE",T[T.RUNNING=1]="RUNNING",T[T.SKIPPED=2]="SKIPPED",T[T.SUCCESS=3]="SUCCESS",T[T.FAILED=4]="FAILED"})(CheckStatus||(CheckStatus={}));class Checker extends eventsExports.EventEmitter{constructor(n,P){let R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=CheckStatus.IDLE,this.logs=[],this.options={},this.url=n,this.token=P,this.name=this.constructor.name,this.room=new Room(R.roomOptions),this.connectOptions=R.connectOptions,this.options=R}run(n){return __awaiter(this,void 0,void 0,function*(){if(this.status!==CheckStatus.IDLE)throw Error("check is running already");this.setStatus(CheckStatus.RUNNING);try{yield this.perform()}catch(P){P instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(P.message):this.appendError(P.message))}return yield this.disconnect(),yield new Promise(P=>setTimeout(P,500)),this.status!==CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?CheckStatus.SUCCESS:CheckStatus.FAILED),n&&n(),this.getInfo()})}isSuccess(){return!this.logs.some(n=>n.level==="error")}connect(n){return __awaiter(this,void 0,void 0,function*(){return this.room.state===ConnectionState.Connected?this.room:(n||(n=this.url),yield this.room.connect(n,this.token,this.connectOptions),this.room)})}disconnect(){return __awaiter(this,void 0,void 0,function*(){this.room&&this.room.state!==ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise(n=>setTimeout(n,500)))})}skip(){this.setStatus(CheckStatus.SKIPPED)}switchProtocol(n){return __awaiter(this,void 0,void 0,function*(){let P=!1,R=!1;if(this.room.on(RoomEvent.Reconnecting,()=>{P=!0}),this.room.once(RoomEvent.Reconnected,()=>{R=!0}),this.room.simulateScenario("force-".concat(n)),yield new Promise(L=>setTimeout(L,1e3)),!P)return;const A=Date.now()+1e4;for(;Date.now()<A;){if(R)return;yield sleep(100)}throw new Error("Could not reconnect using ".concat(n," protocol after 10 seconds"))})}appendMessage(n){this.logs.push({level:"info",message:n}),this.emit("update",this.getInfo())}appendWarning(n){this.logs.push({level:"warning",message:n}),this.emit("update",this.getInfo())}appendError(n){this.logs.push({level:"error",message:n}),this.emit("update",this.getInfo())}setStatus(n){this.status=n,this.emit("update",this.getInfo())}get engine(){var n;return(n=this.room)===null||n===void 0?void 0:n.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class CloudRegionCheck extends Checker{get description(){return"Cloud regions"}perform(){return __awaiter(this,void 0,void 0,function*(){const n=new RegionUrlProvider(this.url,this.token);if(!n.isCloud()){this.skip();return}const P=[],R=new Set;for(let L=0;L<3;L++){const O=yield n.getNextBestRegionUrl();if(!O)break;if(R.has(O))continue;R.add(O);const N=yield this.checkCloudRegion(O);this.appendMessage("".concat(N.region," RTT: ").concat(N.rtt,"ms, duration: ").concat(N.duration,"ms")),P.push(N)}P.sort((L,O)=>(L.duration-O.duration)*.5+(L.rtt-O.rtt)*.5);const A=P[0];this.bestStats=A,this.appendMessage("best Cloud region: ".concat(A.region))})}getInfo(){const n=super.getInfo();return n.data=this.bestStats,n}checkCloudRegion(n){return __awaiter(this,void 0,void 0,function*(){var P,R;yield this.connect(n),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const A=(P=this.room.serverInfo)===null||P===void 0?void 0:P.region;if(!A)throw new Error("Region not found");const L=yield this.room.localParticipant.streamText({topic:"test"}),O=1e3,V=1e6/O,j="A".repeat(O),B=Date.now();for(let H=0;H<V;H++)yield L.write(j);yield L.close();const z=Date.now(),W=yield(R=this.room.engine.pcManager)===null||R===void 0?void 0:R.publisher.getStats(),q={region:A,rtt:1e4,duration:z-B};return W?.forEach(H=>{H.type==="candidate-pair"&&H.nominated&&(q.rtt=H.currentRoundTripTime*1e3)}),yield this.disconnect(),q})}}const TEST_DURATION=1e4;class ConnectionProtocolCheck extends Checker{get description(){return"Connection via UDP vs TCP"}perform(){return __awaiter(this,void 0,void 0,function*(){const n=yield this.checkConnectionProtocol("udp"),P=yield this.checkConnectionProtocol("tcp");this.bestStats=n,n.qualityLimitationDurations.bandwidth-P.qualityLimitationDurations.bandwidth>.5||(n.packetsLost-P.packetsLost)/n.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=P):this.appendMessage("best connection quality via udp");const R=this.bestStats;this.appendMessage("upstream bitrate: ".concat((R.bitrateTotal/R.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((R.rttTotal/R.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((R.jitterTotal/R.count*1e3).toFixed(2)," ms")),R.packetsLost>0&&this.appendWarning("packets lost: ".concat((R.packetsLost/R.packetsSent*100).toFixed(2),"%")),R.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((R.qualityLimitationDurations.bandwidth/(TEST_DURATION/1e3)*100).toFixed(2),"%")),R.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((R.qualityLimitationDurations.cpu/(TEST_DURATION/1e3)*100).toFixed(2),"%"))})}getInfo(){const n=super.getInfo();return n.data=this.bestStats,n}checkConnectionProtocol(n){return __awaiter(this,void 0,void 0,function*(){yield this.connect(),n==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const P=document.createElement("canvas");P.width=1280,P.height=720;const R=P.getContext("2d");if(!R)throw new Error("Could not get canvas context");let A=0;const L=()=>{A=(A+1)%360,R.fillStyle="hsl(".concat(A,", 100%, 50%)"),R.fillRect(0,0,P.width,P.height),requestAnimationFrame(L)};L();const N=P.captureStream(30).getVideoTracks()[0],j=(yield this.room.localParticipant.publishTrack(N,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,B={protocol:n,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},z=setInterval(()=>__awaiter(this,void 0,void 0,function*(){const W=yield j.getRTCStatsReport();W?.forEach(q=>{q.type==="outbound-rtp"?(B.packetsSent=q.packetsSent,B.qualityLimitationDurations=q.qualityLimitationDurations,B.bitrateTotal+=q.targetBitrate,B.count++):q.type==="remote-inbound-rtp"&&(B.packetsLost=q.packetsLost,B.rttTotal+=q.roundTripTime,B.jitterTotal+=q.jitter)})}),1e3);return yield new Promise(W=>setTimeout(W,TEST_DURATION)),clearInterval(z),N.stop(),P.remove(),yield this.disconnect(),B})}}class PublishAudioCheck extends Checker{get description(){return"Can publish audio"}perform(){return __awaiter(this,void 0,void 0,function*(){var n;const P=yield this.connect(),R=yield createLocalAudioTrack();if(yield detectSilence(R,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),P.localParticipant.publishTrack(R),yield new Promise(N=>setTimeout(N,3e3));const L=yield(n=R.sender)===null||n===void 0?void 0:n.getStats();if(!L)throw new Error("Could not get RTCStats");let O=0;if(L.forEach(N=>{N.type==="outbound-rtp"&&(N.kind==="audio"||!N.kind&&N.mediaType==="audio")&&(O=N.packetsSent)}),O===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(O," audio packets"))})}}class PublishVideoCheck extends Checker{get description(){return"Can publish video"}perform(){return __awaiter(this,void 0,void 0,function*(){var n;const P=yield this.connect(),R=yield createLocalVideoTrack();yield this.checkForVideo(R.mediaStreamTrack),P.localParticipant.publishTrack(R),yield new Promise(O=>setTimeout(O,5e3));const A=yield(n=R.sender)===null||n===void 0?void 0:n.getStats();if(!A)throw new Error("Could not get RTCStats");let L=0;if(A.forEach(O=>{O.type==="outbound-rtp"&&(O.kind==="video"||!O.kind&&O.mediaType==="video")&&(L+=O.packetsSent)}),L===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(L," video packets"))})}checkForVideo(n){return __awaiter(this,void 0,void 0,function*(){const P=new MediaStream;P.addTrack(n.clone());const R=document.createElement("video");R.srcObject=P,R.muted=!0,yield new Promise(A=>{R.onplay=()=>{setTimeout(()=>{var L,O,N,V;const j=document.createElement("canvas"),B=n.getSettings(),z=(O=(L=B.width)!==null&&L!==void 0?L:R.videoWidth)!==null&&O!==void 0?O:1280,W=(V=(N=B.height)!==null&&N!==void 0?N:R.videoHeight)!==null&&V!==void 0?V:720;j.width=z,j.height=W;const q=j.getContext("2d");q.drawImage(R,0,0);const $=q.getImageData(0,0,j.width,j.height).data;let Q=!0;for(let U=0;U<$.length;U+=4)if($[U]!==0||$[U+1]!==0||$[U+2]!==0){Q=!1;break}Q?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),A()},1e3)},R.play()}),P.getTracks().forEach(A=>A.stop()),R.remove()})}}class ReconnectCheck extends Checker{get description(){return"Resuming connection after interruption"}perform(){return __awaiter(this,void 0,void 0,function*(){var n;const P=yield this.connect();let R=!1,A=!1,L;const O=new Promise(j=>{setTimeout(j,5e3),L=j}),N=()=>{R=!0};P.on(RoomEvent.SignalReconnecting,N).on(RoomEvent.Reconnecting,N).on(RoomEvent.Reconnected,()=>{A=!0,L(!0)}),(n=P.engine.client.ws)===null||n===void 0||n.close();const V=P.engine.client.onClose;if(V&&V(""),yield O,R){if(!A||P.state!==ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class TURNCheck extends Checker{get description(){return"Can connect via TURN"}perform(){return __awaiter(this,void 0,void 0,function*(){var n,P;const R=new SignalClient,A=yield R.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let L=!1,O=!1,N=!1;for(let V of A.iceServers)for(let j of V.urls)j.startsWith("turn:")?(O=!0,N=!0):j.startsWith("turns:")&&(O=!0,N=!0,L=!0),j.startsWith("stun:")&&(N=!0);N?O&&!L&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield R.close(),!((P=(n=this.connectOptions)===null||n===void 0?void 0:n.rtcConfig)===null||P===void 0)&&P.iceServers||O?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(V=>setTimeout(V,0)))})}}class WebRTCCheck extends Checker{get description(){return"Establishing WebRTC connection"}perform(){return __awaiter(this,void 0,void 0,function*(){let n=!1,P=!1;this.room.on(RoomEvent.SignalConnected,()=>{const R=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(A,L)=>{if(A.candidate){const O=new RTCIceCandidate(A);let N="".concat(O.protocol," ").concat(O.address,":").concat(O.port," ").concat(O.type);O.address&&(isIPPrivate(O.address)?N+=" (private)":O.protocol==="tcp"&&O.tcpType==="passive"?(n=!0,N+=" (passive)"):O.protocol==="udp"&&(P=!0)),this.appendMessage(N)}R&&R(A,L)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=A=>{A instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(A.errorCode," ").concat(A.errorText," ").concat(A.url))})});try{yield this.connect(),livekitLogger.info("now the room is connected")}catch(R){throw this.appendWarning("ports need to be open on firewall in order to connect."),R}n||this.appendWarning("Server is not configured for ICE/TCP"),P||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function isIPPrivate(T){const n=T.split(".");if(n.length===4){if(n[0]==="10")return!0;if(n[0]==="192"&&n[1]==="168")return!0;if(n[0]==="172"){const P=parseInt(n[1],10);if(P>=16&&P<=31)return!0}}return!1}class WebSocketCheck extends Checker{get description(){return"Connecting to signal connection via WebSocket"}perform(){return __awaiter(this,void 0,void 0,function*(){var n,P,R;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let A=new SignalClient;const L=yield A.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(L.serverVersion,".")),((n=L.serverInfo)===null||n===void 0?void 0:n.edition)===ServerInfo_Edition.Cloud&&(!((P=L.serverInfo)===null||P===void 0)&&P.region)&&this.appendMessage("LiveKit Cloud: ".concat((R=L.serverInfo)===null||R===void 0?void 0:R.region)),yield A.close()})}}class ConnectionCheck extends eventsExports.EventEmitter{constructor(n,P){let R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=n,this.token=P,this.options=R}getNextCheckId(){const n=this.checkResults.size;return this.checkResults.set(n,{logs:[],status:CheckStatus.IDLE,name:"",description:""}),n}updateCheck(n,P){this.checkResults.set(n,P),this.emit("checkUpdate",n,P)}isSuccess(){return Array.from(this.checkResults.values()).every(n=>n.status!==CheckStatus.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(n){return __awaiter(this,void 0,void 0,function*(){const P=this.getNextCheckId(),R=new n(this.url,this.token,this.options),A=O=>{this.updateCheck(P,O)};R.on("update",A);const L=yield R.run();return R.off("update",A),L})}checkWebsocket(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(WebSocketCheck)})}checkWebRTC(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(WebRTCCheck)})}checkTURN(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(TURNCheck)})}checkReconnect(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(ReconnectCheck)})}checkPublishAudio(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(PublishAudioCheck)})}checkPublishVideo(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(PublishVideoCheck)})}checkConnectionProtocol(){return __awaiter(this,void 0,void 0,function*(){const n=yield this.createAndRunCheck(ConnectionProtocolCheck);if(n.data&&"protocol"in n.data){const P=n.data;this.options.protocol=P.protocol}return n})}checkCloudRegion(){return __awaiter(this,void 0,void 0,function*(){return this.createAndRunCheck(CloudRegionCheck)})}}function s(){return s=Object.assign?Object.assign.bind():function(T){for(var n=1;n<arguments.length;n++){var P=arguments[n];for(var R in P)({}).hasOwnProperty.call(P,R)&&(T[R]=P[R])}return T},s.apply(null,arguments)}const i$1=new Uint8Array(0);class r{static getFullOptions(n){return s({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{}},n)}constructor(n,P){var R=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(A){R.status!=="connected"&&R.status!=="connecting"||(R.updateStatus("disconnecting"),await R.handleEndSession(),R.updateStatus("disconnected"),R.options.onDisconnect&&R.options.onDisconnect(A))},this.onMessage=async function(A){switch(A.type){case"interruption":return void R.handleInterruption(A);case"agent_response":return void R.handleAgentResponse(A);case"user_transcript":return void R.handleUserTranscript(A);case"internal_tentative_agent_response":return void R.handleTentativeAgentResponse(A);case"client_tool_call":try{await R.handleClientToolCall(A)}catch(L){R.onError(`Unexpected error in client tool call handling: ${L instanceof Error?L.message:String(L)}`,{clientToolName:A.client_tool_call.tool_name,toolCallId:A.client_tool_call.tool_call_id})}return;case"audio":return void R.handleAudio(A);case"vad_score":return void R.handleVadScore(A);case"ping":return void R.connection.sendMessage({type:"pong",event_id:A.ping_event.event_id});default:return void(R.options.onDebug&&R.options.onDebug(A))}},this.setVolume=({volume:A})=>{this.volume=A},this.options=n,this.connection=P,this.options.onConnect&&this.options.onConnect({conversationId:P.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(A=>this.updateMode(A)),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(n){n!==this.mode&&(this.mode=n,this.options.onModeChange&&this.options.onModeChange({mode:n}))}updateStatus(n){n!==this.status&&(this.status=n,this.options.onStatusChange&&this.options.onStatusChange({status:n}))}updateCanSendFeedback(){const n=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==n&&(this.canSendFeedback=n,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:n}))}handleInterruption(n){n.interruption_event&&(this.lastInterruptTimestamp=n.interruption_event.event_id)}handleAgentResponse(n){this.options.onMessage&&this.options.onMessage({source:"ai",message:n.agent_response_event.agent_response})}handleUserTranscript(n){this.options.onMessage&&this.options.onMessage({source:"user",message:n.user_transcription_event.user_transcript})}handleTentativeAgentResponse(n){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:n.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(n){this.options.onVadScore&&this.options.onVadScore({vadScore:n.vad_score_event.vad_score})}async handleClientToolCall(n){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,n.client_tool_call.tool_name))try{var P;const R=(P=await this.options.clientTools[n.client_tool_call.tool_name](n.client_tool_call.parameters))!=null?P:"Client tool execution successful.",A=typeof R=="object"?JSON.stringify(R):String(R);this.connection.sendMessage({type:"client_tool_result",tool_call_id:n.client_tool_call.tool_call_id,result:A,is_error:!1})}catch(R){this.onError(`Client tool execution failed with following error: ${R?.message}`,{clientToolName:n.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:n.client_tool_call.tool_call_id,result:`Client tool execution failed: ${R?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(n.client_tool_call);this.onError(`Client tool with name ${n.client_tool_call.tool_name} is not defined on client`,{clientToolName:n.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:n.client_tool_call.tool_call_id,result:`Client tool with name ${n.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(n){}onError(n,P){console.error(n,P),this.options.onError&&this.options.onError(n,P)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}setMicMuted(n){this.connection.setMicMuted(n)}getInputByteFrequencyData(){return i$1}getOutputByteFrequencyData(){return i$1}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(n){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:n?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(n){this.connection.sendMessage({type:"contextual_update",text:n})}sendUserMessage(n){this.connection.sendMessage({type:"user_message",text:n})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(n,P){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:n,is_approved:P})}}class c{constructor(n={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=n.onDebug}debug(n){this.onDebug&&this.onDebug(n)}onMessage(n){this.onMessageCallback=n;const P=this.queue;this.queue=[],P.length>0&&queueMicrotask(()=>{P.forEach(n)})}onDisconnect(n){this.onDisconnectCallback=n;const P=this.disconnectionDetails;P&&queueMicrotask(()=>{n(P)})}onModeChange(n){this.onModeChangeCallback=n}updateMode(n){var P;(P=this.onModeChangeCallback)==null||P.call(this,n)}disconnect(n){var P;this.disconnectionDetails||(this.disconnectionDetails=n,(P=this.onDisconnectCallback)==null||P.call(this,n))}handleMessage(n){this.onMessageCallback?this.onMessageCallback(n):this.queue.push(n)}}function l(T){const[n,P]=T.split("_");if(!["pcm","ulaw"].includes(n))throw new Error(`Invalid format: ${T}`);const R=Number.parseInt(P);if(Number.isNaN(R))throw new Error(`Invalid sample rate: ${P}`);return{format:n,sampleRate:R}}const u$1="0.6.2";function d(T){return!!T.type}const h="conversation_initiation_client_data";function p(T){var n;const P={type:h};var R,A,L,O,N;return T.overrides&&(P.conversation_config_override={agent:{prompt:(R=T.overrides.agent)==null?void 0:R.prompt,first_message:(A=T.overrides.agent)==null?void 0:A.firstMessage,language:(L=T.overrides.agent)==null?void 0:L.language},tts:{voice_id:(O=T.overrides.tts)==null?void 0:O.voiceId},conversation:{text_only:(N=T.overrides.conversation)==null?void 0:N.textOnly}}),T.customLlmExtraBody&&(P.custom_llm_extra_body=T.customLlmExtraBody),T.dynamicVariables&&(P.dynamic_variables=T.dynamicVariables),T.userId&&(P.user_id=T.userId),(n=T.overrides)!=null&&n.client&&(P.source_info={source:T.overrides.client.source,version:T.overrides.client.version}),P}class m extends c{constructor(n,P,R,A){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=n,this.conversationId=P,this.inputFormat=R,this.outputFormat=A,this.socket.addEventListener("error",L=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:L}),0)}),this.socket.addEventListener("close",L=>{this.disconnect(L.code===1e3?{reason:"agent",context:L}:{reason:"error",message:L.reason||"The connection was closed by the server.",context:L})}),this.socket.addEventListener("message",L=>{try{const O=JSON.parse(L.data);if(!d(O))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:L.data});this.handleMessage(O)}catch(O){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:O instanceof Error?O.message:String(O),data:L.data})}})}static async create(n){let P=null;try{var R,A,L;const N=(R=n.origin)!=null?R:"wss://api.elevenlabs.io";let V;const j=((A=n.overrides)==null||(A=A.client)==null?void 0:A.version)||u$1,B=((L=n.overrides)==null||(L=L.client)==null?void 0:L.source)||"js_sdk";if(n.signedUrl){const J=n.signedUrl.includes("?")?"&":"?";V=`${n.signedUrl}${J}source=${B}&version=${j}`}else V=`${N}/v1/convai/conversation?agent_id=${n.agentId}&source=${B}&version=${j}`;const z=["convai"];n.authorization&&z.push(`bearer.${n.authorization}`),P=new WebSocket(V,z);const W=await new Promise((J,G)=>{P.addEventListener("open",()=>{var K;const Y=p(n);(K=P)==null||K.send(JSON.stringify(Y))},{once:!0}),P.addEventListener("error",K=>{setTimeout(()=>G(K),0)}),P.addEventListener("close",G),P.addEventListener("message",K=>{const Y=JSON.parse(K.data);d(Y)&&(Y.type==="conversation_initiation_metadata"?J(Y.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:q,agent_output_audio_format:H,user_input_audio_format:$}=W,Q=l($??"pcm_16000"),U=l(H);return new m(P,q,Q,U)}catch(N){var O;throw(O=P)==null||O.close(),N}}close(){this.socket.close()}sendMessage(n){this.socket.send(JSON.stringify(n))}async setMicMuted(n){console.warn(`WebSocket connection setMicMuted called with ${n}, but this is handled by VoiceConversation`)}}function v(T){const n=new Uint8Array(T);return window.btoa(String.fromCharCode(...n))}function g(T){const n=window.atob(T),P=n.length,R=new Uint8Array(P);for(let A=0;A<P;A++)R[A]=n.charCodeAt(A);return R.buffer}const f=new Map;function w(T,n){return async P=>{const R=f.get(T);if(R)return P.addModule(R);const A=new Blob([n],{type:"application/javascript"}),L=URL.createObjectURL(A);try{return await P.addModule(L),void f.set(T,L)}catch{URL.revokeObjectURL(L)}try{const O=`data:application/javascript;base64,${btoa(n)}`;await P.addModule(O),f.set(T,O)}catch{throw new Error(`Failed to load the ${T} worklet module. Make sure the browser supports AudioWorklets.`)}}}const y=w("raw-audio-processor",`
|
|
530
|
+
const BIAS = 0x84;
|
|
531
|
+
const CLIP = 32635;
|
|
532
|
+
const encodeTable = [
|
|
533
|
+
0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
|
|
534
|
+
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
|
|
535
|
+
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
|
|
536
|
+
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
|
|
537
|
+
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
|
|
538
|
+
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
|
|
539
|
+
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
|
|
540
|
+
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
|
|
541
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
542
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
543
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
544
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
545
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
546
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
547
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
|
548
|
+
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
|
|
549
|
+
];
|
|
550
|
+
|
|
551
|
+
function encodeSample(sample) {
|
|
552
|
+
let sign;
|
|
553
|
+
let exponent;
|
|
554
|
+
let mantissa;
|
|
555
|
+
let muLawSample;
|
|
556
|
+
sign = (sample >> 8) & 0x80;
|
|
557
|
+
if (sign !== 0) sample = -sample;
|
|
558
|
+
sample = sample + BIAS;
|
|
559
|
+
if (sample > CLIP) sample = CLIP;
|
|
560
|
+
exponent = encodeTable[(sample>>7) & 0xFF];
|
|
561
|
+
mantissa = (sample >> (exponent+3)) & 0x0F;
|
|
562
|
+
muLawSample = ~(sign | (exponent << 4) | mantissa);
|
|
563
|
+
|
|
564
|
+
return muLawSample;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
class RawAudioProcessor extends AudioWorkletProcessor {
|
|
568
|
+
constructor() {
|
|
569
|
+
super();
|
|
570
|
+
|
|
571
|
+
this.port.onmessage = ({ data }) => {
|
|
572
|
+
switch (data.type) {
|
|
573
|
+
case "setFormat":
|
|
574
|
+
this.isMuted = false;
|
|
575
|
+
this.buffer = []; // Initialize an empty buffer
|
|
576
|
+
this.bufferSize = data.sampleRate / 4;
|
|
577
|
+
this.format = data.format;
|
|
578
|
+
|
|
579
|
+
if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {
|
|
580
|
+
globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => {
|
|
581
|
+
this.resampler = resampler;
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
break;
|
|
585
|
+
case "setMuted":
|
|
586
|
+
this.isMuted = data.isMuted;
|
|
587
|
+
break;
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
process(inputs) {
|
|
592
|
+
if (!this.buffer) {
|
|
593
|
+
return true;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const input = inputs[0]; // Get the first input node
|
|
597
|
+
if (input.length > 0) {
|
|
598
|
+
let channelData = input[0]; // Get the first channel's data
|
|
599
|
+
|
|
600
|
+
// Resample the audio if necessary
|
|
601
|
+
if (this.resampler) {
|
|
602
|
+
channelData = this.resampler.full(channelData);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// Add channel data to the buffer
|
|
606
|
+
this.buffer.push(...channelData);
|
|
607
|
+
// Get max volume
|
|
608
|
+
let sum = 0.0;
|
|
609
|
+
for (let i = 0; i < channelData.length; i++) {
|
|
610
|
+
sum += channelData[i] * channelData[i];
|
|
611
|
+
}
|
|
612
|
+
const maxVolume = Math.sqrt(sum / channelData.length);
|
|
613
|
+
// Check if buffer size has reached or exceeded the threshold
|
|
614
|
+
if (this.buffer.length >= this.bufferSize) {
|
|
615
|
+
const float32Array = this.isMuted
|
|
616
|
+
? new Float32Array(this.buffer.length)
|
|
617
|
+
: new Float32Array(this.buffer);
|
|
618
|
+
|
|
619
|
+
let encodedArray = this.format === "ulaw"
|
|
620
|
+
? new Uint8Array(float32Array.length)
|
|
621
|
+
: new Int16Array(float32Array.length);
|
|
622
|
+
|
|
623
|
+
// Iterate through the Float32Array and convert each sample to PCM16
|
|
624
|
+
for (let i = 0; i < float32Array.length; i++) {
|
|
625
|
+
// Clamp the value to the range [-1, 1]
|
|
626
|
+
let sample = Math.max(-1, Math.min(1, float32Array[i]));
|
|
627
|
+
|
|
628
|
+
// Scale the sample to the range [-32768, 32767]
|
|
629
|
+
let value = sample < 0 ? sample * 32768 : sample * 32767;
|
|
630
|
+
if (this.format === "ulaw") {
|
|
631
|
+
value = encodeSample(Math.round(value));
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
encodedArray[i] = value;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// Send the buffered data to the main script
|
|
638
|
+
this.port.postMessage([encodedArray, maxVolume]);
|
|
639
|
+
|
|
640
|
+
// Clear the buffer after sending
|
|
641
|
+
this.buffer = [];
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return true; // Continue processing
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
registerProcessor("raw-audio-processor", RawAudioProcessor);
|
|
648
|
+
`);class k extends c{constructor(n,P,R,A,L={}){super(L),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=n,this.conversationId=P,this.inputFormat=R,this.outputFormat=A,this.setupRoomEventListeners()}static async create(n){let P;if("conversationToken"in n&&n.conversationToken)P=n.conversationToken;else{if(!("agentId"in n)||!n.agentId)throw new Error("Either conversationToken or agentId is required for WebRTC connection");try{var R,A,L;const j=((R=n.overrides)==null||(R=R.client)==null?void 0:R.version)||u$1,B=((A=n.overrides)==null||(A=A.client)==null?void 0:A.source)||"js_sdk",z=`${O=(L=n.origin)!=null?L:"https://api.elevenlabs.io",O.replace(/^wss:\/\//,"https://")}/v1/convai/conversation/token?agent_id=${n.agentId}&source=${B}&version=${j}`,W=await fetch(z);if(!W.ok)throw new Error(`ElevenLabs API returned ${W.status} ${W.statusText}`);if(P=(await W.json()).token,!P)throw new Error("No conversation token received from API")}catch(j){let B=j instanceof Error?j.message:String(j);throw j instanceof Error&&j.message.includes("401")&&(B="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${n.agentId}: ${B}`)}}var O;const N=new Room;try{const j=`room_${Date.now()}`,B=l("pcm_48000"),z=l("pcm_48000"),W=new k(N,j,B,z,n),q=n.livekitUrl||"wss://livekit.rtc.elevenlabs.io";var V;await N.connect(q,P),await new Promise($=>{if(W.isConnected)$();else{const Q=()=>{N.off(RoomEvent.Connected,Q),$()};N.on(RoomEvent.Connected,Q)}}),N.name&&(W.conversationId=((V=N.name.match(/(conv_[a-zA-Z0-9]+)/))==null?void 0:V[0])||N.name),await N.localParticipant.setMicrophoneEnabled(!0);const H=p(n);return W.debug({type:h,message:H}),await W.sendMessage(H),W}catch(j){throw await N.disconnect(),j}}setupRoomEventListeners(){var n=this;this.room.on(RoomEvent.Connected,async function(){n.isConnected=!0,console.info("WebRTC room connected")}),this.room.on(RoomEvent.Disconnected,P=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:P?.toString()})})}),this.room.on(RoomEvent.ConnectionStateChanged,P=>{P===ConnectionState.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${P}`,context:new Event("connection_state_changed")}))}),this.room.on(RoomEvent.DataReceived,(P,R)=>{try{const A=JSON.parse(new TextDecoder().decode(P));if(A.type==="audio")return;d(A)?this.handleMessage(A):console.warn("Invalid socket event received:",A)}catch(A){console.warn("Failed to parse incoming data message:",A),console.warn("Raw payload:",new TextDecoder().decode(P))}}),this.room.on(RoomEvent.TrackSubscribed,async function(P,R,A){if(P.kind===Track.Kind.Audio&&A.identity.includes("agent")){const L=P,O=L.attach();if(O.autoplay=!0,O.controls=!1,n.outputDeviceId&&O.setSinkId)try{await O.setSinkId(n.outputDeviceId)}catch(N){console.warn("Failed to set output device for new audio element:",N)}O.style.display="none",document.body.appendChild(O),n.audioElements.push(O),n.audioElements.length===1&&(n.onDebug==null||n.onDebug({type:"audio_element_ready"})),await n.setupAudioCapture(L)}}),this.room.on(RoomEvent.ActiveSpeakersChanged,async function(P){n.updateMode(P.length>0&&P[0].identity.startsWith("agent")?"speaking":"listening")})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(n=>{n.track&&n.track.stop()})}catch(n){console.warn("Error stopping local tracks:",n)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch(n=>{console.warn("Error closing audio capture context:",n)}),this.audioCaptureContext=null),this.audioElements.forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(n){if(this.isConnected&&this.room.localParticipant){if(!("user_audio_chunk"in n))try{const P=new TextEncoder().encode(JSON.stringify(n));await this.room.localParticipant.publishData(P,{reliable:!0})}catch(P){this.debug({type:"send_message_error",message:{message:n,error:P}}),console.error("Failed to send message via WebRTC:",P)}}else console.warn("Cannot send message: room not connected or no local participant")}getRoom(){return this.room}async setMicMuted(n){if(!this.isConnected||!this.room.localParticipant)return void console.warn("Cannot set microphone muted: room not connected or no local participant");const P=this.room.localParticipant.getTrackPublication(Track.Source.Microphone);if(P!=null&&P.track)try{n?await P.track.mute():await P.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!n)}else await this.room.localParticipant.setMicrophoneEnabled(!n)}async setupAudioCapture(n){try{const P=new AudioContext;this.audioCaptureContext=P,this.outputAnalyser=P.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;const R=new MediaStream([n.mediaStreamTrack]),A=P.createMediaStreamSource(R);A.connect(this.outputAnalyser),await y(P.audioWorklet);const L=new AudioWorkletNode(P,"raw-audio-processor");this.outputAnalyser.connect(L),L.port.postMessage({type:"setFormat",format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),L.port.onmessage=O=>{const[N,V]=O.data;if(V>.01){const j=v(N.buffer),B=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:j,event_id:B}})}},A.connect(L)}catch(P){console.warn("Failed to set up audio capture:",P)}}setAudioVolume(n){this.audioElements.forEach(P=>{P.volume=n})}async setAudioOutputDevice(n){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");const P=this.audioElements.map(async function(R){try{await R.setSinkId(n)}catch(A){throw console.error("Failed to set sink ID for audio element:",A),A}});await Promise.all(P),this.outputDeviceId=n}async setAudioInputDevice(n){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");try{const P=this.room.localParticipant.getTrackPublication(Track.Source.Microphone);P!=null&&P.track&&(await P.track.stop(),await this.room.localParticipant.unpublishTrack(P.track));const R={deviceId:{exact:n},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},A=await createLocalAudioTrack(R);await this.room.localParticipant.publishTrack(A,{name:"microphone",source:Track.Source.Microphone})}catch(P){console.error("Failed to change input device:",P);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(R){console.error("Failed to recover microphone after device switch error:",R)}throw P}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}}async function b(T){const n=(function(P){return P.connectionType?P.connectionType:"conversationToken"in P&&P.conversationToken?"webrtc":"websocket"})(T);switch(n){case"websocket":return m.create(T);case"webrtc":return k.create(T);default:throw new Error(`Unknown connection type: ${n}`)}}function _(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function C(T={default:0,android:3e3}){let n=T.default;var P;if(/android/i.test(navigator.userAgent))n=(P=T.android)!=null?P:n;else if(_()){var R;n=(R=T.ios)!=null?R:n}n>0&&await new Promise(A=>setTimeout(A,n))}class S extends r{static async startSession(n){const P=r.getFullOptions(n);P.onStatusChange&&P.onStatusChange({status:"connecting"}),P.onCanSendFeedbackChange&&P.onCanSendFeedbackChange({canSendFeedback:!1}),P.onModeChange&&P.onModeChange({mode:"listening"}),P.onCanSendFeedbackChange&&P.onCanSendFeedbackChange({canSendFeedback:!1});let R=null;try{return await C(P.connectionDelay),R=await b(n),new S(P,R)}catch(L){var A;throw P.onStatusChange&&P.onStatusChange({status:"disconnected"}),(A=R)==null||A.close(),L}}}const M={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class I{static async create({sampleRate:n,format:P,preferHeadphonesForIosDevices:R,inputDeviceId:A}){let L=null,O=null;try{const j=s({sampleRate:{ideal:n}},M);if(_()&&R){const $=(await window.navigator.mediaDevices.enumerateDevices()).find(Q=>Q.kind==="audioinput"&&["airpod","headphone","earphone"].find(U=>Q.label.toLowerCase().includes(U)));$&&(j.deviceId={ideal:$.deviceId})}A&&(j.deviceId={exact:A});const B=navigator.mediaDevices.getSupportedConstraints().sampleRate;L=new window.AudioContext(B?{sampleRate:n}:{});const z=L.createAnalyser();B||await L.audioWorklet.addModule("https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js"),await y(L.audioWorklet);const W=s({voiceIsolation:!0},j);O=await navigator.mediaDevices.getUserMedia({audio:W});const q=L.createMediaStreamSource(O),H=new AudioWorkletNode(L,"raw-audio-processor");return H.port.postMessage({type:"setFormat",format:P,sampleRate:n}),q.connect(z),z.connect(H),await L.resume(),new I(L,z,H,O,q)}catch(j){var N,V;throw(N=O)==null||N.getTracks().forEach(B=>{B.stop()}),(V=L)==null||V.close(),j}}constructor(n,P,R,A,L){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=n,this.analyser=P,this.worklet=R,this.inputStream=A,this.mediaStreamSource=L}async close(){this.inputStream.getTracks().forEach(n=>{n.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(n){this.worklet.port.postMessage({type:"setMuted",isMuted:n})}async setInputDevice(n){if(!n)throw new Error("Input device ID is required");try{const P=s({deviceId:{exact:n}},M),R=s({voiceIsolation:!0},P),A=await navigator.mediaDevices.getUserMedia({audio:R});this.inputStream.getTracks().forEach(L=>{L.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=A,this.mediaStreamSource=this.context.createMediaStreamSource(A),this.mediaStreamSource.connect(this.analyser)}catch(P){throw console.error("Failed to switch input device:",P),P}}}const D=w("audio-concat-processor",`
|
|
649
|
+
const decodeTable = [0,132,396,924,1980,4092,8316,16764];
|
|
650
|
+
|
|
651
|
+
export function decodeSample(muLawSample) {
|
|
652
|
+
let sign;
|
|
653
|
+
let exponent;
|
|
654
|
+
let mantissa;
|
|
655
|
+
let sample;
|
|
656
|
+
muLawSample = ~muLawSample;
|
|
657
|
+
sign = (muLawSample & 0x80);
|
|
658
|
+
exponent = (muLawSample >> 4) & 0x07;
|
|
659
|
+
mantissa = muLawSample & 0x0F;
|
|
660
|
+
sample = decodeTable[exponent] + (mantissa << (exponent+3));
|
|
661
|
+
if (sign !== 0) sample = -sample;
|
|
662
|
+
|
|
663
|
+
return sample;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
class AudioConcatProcessor extends AudioWorkletProcessor {
|
|
667
|
+
constructor() {
|
|
668
|
+
super();
|
|
669
|
+
this.buffers = []; // Initialize an empty buffer
|
|
670
|
+
this.cursor = 0;
|
|
671
|
+
this.currentBuffer = null;
|
|
672
|
+
this.wasInterrupted = false;
|
|
673
|
+
this.finished = false;
|
|
674
|
+
|
|
675
|
+
this.port.onmessage = ({ data }) => {
|
|
676
|
+
switch (data.type) {
|
|
677
|
+
case "setFormat":
|
|
678
|
+
this.format = data.format;
|
|
679
|
+
break;
|
|
680
|
+
case "buffer":
|
|
681
|
+
this.wasInterrupted = false;
|
|
682
|
+
this.buffers.push(
|
|
683
|
+
this.format === "ulaw"
|
|
684
|
+
? new Uint8Array(data.buffer)
|
|
685
|
+
: new Int16Array(data.buffer)
|
|
686
|
+
);
|
|
687
|
+
break;
|
|
688
|
+
case "interrupt":
|
|
689
|
+
this.wasInterrupted = true;
|
|
690
|
+
break;
|
|
691
|
+
case "clearInterrupted":
|
|
692
|
+
if (this.wasInterrupted) {
|
|
693
|
+
this.wasInterrupted = false;
|
|
694
|
+
this.buffers = [];
|
|
695
|
+
this.currentBuffer = null;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
process(_, outputs) {
|
|
701
|
+
let finished = false;
|
|
702
|
+
const output = outputs[0][0];
|
|
703
|
+
for (let i = 0; i < output.length; i++) {
|
|
704
|
+
if (!this.currentBuffer) {
|
|
705
|
+
if (this.buffers.length === 0) {
|
|
706
|
+
finished = true;
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
709
|
+
this.currentBuffer = this.buffers.shift();
|
|
710
|
+
this.cursor = 0;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
let value = this.currentBuffer[this.cursor];
|
|
714
|
+
if (this.format === "ulaw") {
|
|
715
|
+
value = decodeSample(value);
|
|
716
|
+
}
|
|
717
|
+
output[i] = value / 32768;
|
|
718
|
+
this.cursor++;
|
|
719
|
+
|
|
720
|
+
if (this.cursor >= this.currentBuffer.length) {
|
|
721
|
+
this.currentBuffer = null;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (this.finished !== finished) {
|
|
726
|
+
this.finished = finished;
|
|
727
|
+
this.port.postMessage({ type: "process", finished });
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
return true; // Continue processing
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
registerProcessor("audio-concat-processor", AudioConcatProcessor);
|
|
735
|
+
`);class F{static async create({sampleRate:n,format:P,outputDeviceId:R}){let A=null,L=null;try{A=new AudioContext({sampleRate:n});const V=A.createAnalyser(),j=A.createGain();L=new Audio,L.src="",L.load(),L.autoplay=!0,L.style.display="none",document.body.appendChild(L);const B=A.createMediaStreamDestination();L.srcObject=B.stream,j.connect(V),V.connect(B),await D(A.audioWorklet);const z=new AudioWorkletNode(A,"audio-concat-processor");return z.port.postMessage({type:"setFormat",format:P}),z.connect(j),await A.resume(),R&&L.setSinkId&&await L.setSinkId(R),new F(A,V,j,z,L)}catch(V){var O,N;throw(O=L)!=null&&O.parentNode&&L.parentNode.removeChild(L),(N=L)==null||N.pause(),A&&A.state!=="closed"&&await A.close(),V}}constructor(n,P,R,A,L){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=n,this.analyser=P,this.gain=R,this.worklet=A,this.audioElement=L}async setOutputDevice(n){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(n)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class E extends r{static async startSession(n){var P;const R=r.getFullOptions(n);R.onStatusChange&&R.onStatusChange({status:"connecting"}),R.onCanSendFeedbackChange&&R.onCanSendFeedbackChange({canSendFeedback:!1});let A=null,L=null,O=null,N=null,V=null;if((P=n.useWakeLock)==null||P)try{V=await navigator.wakeLock.request("screen")}catch{}try{var j;return N=await navigator.mediaDevices.getUserMedia({audio:!0}),await C(R.connectionDelay),L=await b(n),[A,O]=await Promise.all([I.create(s({},L.inputFormat,{preferHeadphonesForIosDevices:n.preferHeadphonesForIosDevices,inputDeviceId:n.inputDeviceId})),F.create(s({},L.outputFormat,{outputDeviceId:n.outputDeviceId}))]),(j=N)==null||j.getTracks().forEach($=>{$.stop()}),N=null,new E(R,L,A,O,V)}catch($){var B,z,W,q;R.onStatusChange&&R.onStatusChange({status:"disconnected"}),(B=N)==null||B.getTracks().forEach(Q=>{Q.stop()}),(z=L)==null||z.close(),await((W=A)==null?void 0:W.close()),await((q=O)==null?void 0:q.close());try{var H;await((H=V)==null?void 0:H.release()),V=null}catch{}throw $}}constructor(n,P,R,A,L){super(n,P),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=O=>{this.status==="connected"&&this.connection.sendMessage({user_audio_chunk:v(O.data[0].buffer)})},this.onOutputWorkletMessage=({data:O})=>{O.type==="process"&&this.updateMode(O.finished?"listening":"speaking")},this.addAudioBase64Chunk=O=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:g(O)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},this.calculateVolume=O=>{if(O.length===0)return 0;let N=0;for(let V=0;V<O.length;V++)N+=O[V]/255;return N/=O.length,N<0?0:N>1?1:N},this.setVolume=({volume:O})=>{const N=Number.isFinite(O)?Math.min(1,Math.max(0,O)):1;this.volume=N,this.connection instanceof k?this.connection.setAudioVolume(N):this.output.gain.gain.value=N},this.input=R,this.output=A,this.wakeLock=L,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{var n;await((n=this.wakeLock)==null?void 0:n.release()),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(n){super.handleInterruption(n),this.fadeOutAudio()}handleAudio(n){var P,R;this.lastInterruptTimestamp<=n.audio_event.event_id&&((P=(R=this.options).onAudio)==null||P.call(R,n.audio_event.audio_base_64),this.connection instanceof k||this.addAudioBase64Chunk(n.audio_event.audio_base_64),this.currentEventId=n.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(n){this.connection instanceof k?this.connection.setMicMuted(n):this.input.setMuted(n)}getInputByteFrequencyData(){return this.inputFrequencyData!=null||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof k?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:n,format:P,preferHeadphonesForIosDevices:R,inputDeviceId:A}){try{if(this.connection instanceof m&&A)try{return await this.input.setInputDevice(A),this.input}catch(O){console.warn("Failed to change device on existing input, recreating:",O)}this.connection instanceof k&&A&&await this.connection.setAudioInputDevice(A),await this.input.close();const L=await I.create({sampleRate:n,format:P,preferHeadphonesForIosDevices:R,inputDeviceId:A});return this.input=L,this.input}catch(L){throw console.error("Error changing input device",L),L}}async changeOutputDevice({sampleRate:n,format:P,outputDeviceId:R}){try{if(this.connection instanceof m&&R)try{return await this.output.setOutputDevice(R),this.output}catch(L){console.warn("Failed to change device on existing output, recreating:",L)}this.connection instanceof k&&R&&await this.connection.setAudioOutputDevice(R),await this.output.close();const A=await F.create({sampleRate:n,format:P,outputDeviceId:R});return this.output=A,this.output}catch(A){throw console.error("Error changing output device",A),A}}}class x extends r{static startSession(n){return n.textOnly?S.startSession(n):E.startSession(n)}}function u(){return u=Object.assign?Object.assign.bind():function(T){for(var n=1;n<arguments.length;n++){var P=arguments[n];for(var R in P)({}).hasOwnProperty.call(P,R)&&(T[R]=P[R])}return T},u.apply(null,arguments)}const o=["micMuted","volume","serverLocation"];function t(T="us"){switch(T){case"eu-residency":case"in-residency":case"us":case"global":return T;default:return console.warn(`[ConversationalAI] Invalid server-location: ${T}. Defaulting to "us"`),"us"}}function i(T){return{us:"wss://api.elevenlabs.io","eu-residency":"wss://api.eu.residency.elevenlabs.io","in-residency":"wss://api.in.residency.elevenlabs.io",global:"wss://api.elevenlabs.io"}[T]}function a(T={}){const{micMuted:n,volume:P,serverLocation:R}=T,A=(function(q,H){if(q==null)return{};var $={};for(var Q in q)if({}.hasOwnProperty.call(q,Q)){if(H.indexOf(Q)!==-1)continue;$[Q]=q[Q]}return $})(T,o),L=React.useRef(null),O=React.useRef(null),[N,V]=React.useState("disconnected"),[j,B]=React.useState(!1),[z,W]=React.useState("listening");return React.useEffect(()=>{var q;n!==void 0&&(L==null||(q=L.current)==null||q.setMicMuted(n))},[n]),React.useEffect(()=>{var q;P!==void 0&&(L==null||(q=L.current)==null||q.setVolume({volume:P}))},[P]),React.useEffect(()=>()=>{var q;(q=L.current)==null||q.endSession()},[]),{startSession:async q=>{var H;if((H=L.current)!=null&&H.isOpen())return L.current.getId();if(O.current)return(await O.current).getId();try{var $,Q,U,J,G,K,Y,Z,ie,se;const le=i(t(q?.serverLocation||R));return O.current=x.startSession(u({},A??{},q??{},{origin:le,overrides:u({},($=A?.overrides)!=null?$:{},(Q=q?.overrides)!=null?Q:{},{client:u({},(U=A==null||(J=A.overrides)==null?void 0:J.client)!=null?U:{},(G=q==null||(K=q.overrides)==null?void 0:K.client)!=null?G:{},{source:(q==null||(Y=q.overrides)==null||(Y=Y.client)==null?void 0:Y.source)||(A==null||(Z=A.overrides)==null||(Z=Z.client)==null?void 0:Z.source)||"react_sdk",version:(q==null||(ie=q.overrides)==null||(ie=ie.client)==null?void 0:ie.version)||(A==null||(se=A.overrides)==null||(se=se.client)==null?void 0:se.version)||"0.6.2"})}),onConnect:q?.onConnect||A?.onConnect,onDisconnect:q?.onDisconnect||A?.onDisconnect,onError:q?.onError||A?.onError,onMessage:q?.onMessage||A?.onMessage,onAudio:q?.onAudio||A?.onAudio,onDebug:q?.onDebug||A?.onDebug,onUnhandledClientToolCall:q?.onUnhandledClientToolCall||A?.onUnhandledClientToolCall,onVadScore:q?.onVadScore||A?.onVadScore,onModeChange:({mode:pe})=>{var ue;W(pe),(ue=q?.onModeChange||A?.onModeChange)==null||ue({mode:pe})},onStatusChange:({status:pe})=>{var ue;V(pe),(ue=q?.onStatusChange||A?.onStatusChange)==null||ue({status:pe})},onCanSendFeedbackChange:({canSendFeedback:pe})=>{var ue;B(pe),(ue=q?.onCanSendFeedbackChange||A?.onCanSendFeedbackChange)==null||ue({canSendFeedback:pe})}})),L.current=await O.current,n!==void 0&&L.current.setMicMuted(n),P!==void 0&&L.current.setVolume({volume:P}),L.current.getId()}finally{O.current=null}},endSession:async()=>{const q=L.current;L.current=null,await q?.endSession()},setVolume:({volume:q})=>{var H;(H=L.current)==null||H.setVolume({volume:q})},getInputByteFrequencyData:()=>{var q;return(q=L.current)==null?void 0:q.getInputByteFrequencyData()},getOutputByteFrequencyData:()=>{var q;return(q=L.current)==null?void 0:q.getOutputByteFrequencyData()},getInputVolume:()=>{var q,H;return(q=(H=L.current)==null?void 0:H.getInputVolume())!=null?q:0},getOutputVolume:()=>{var q,H;return(q=(H=L.current)==null?void 0:H.getOutputVolume())!=null?q:0},sendFeedback:q=>{var H;(H=L.current)==null||H.sendFeedback(q)},getId:()=>{var q;return(q=L.current)==null?void 0:q.getId()},sendContextualUpdate:q=>{var H;(H=L.current)==null||H.sendContextualUpdate(q)},sendUserMessage:q=>{var H;(H=L.current)==null||H.sendUserMessage(q)},sendUserActivity:()=>{var q;(q=L.current)==null||q.sendUserActivity()},sendMCPToolApprovalResult:(q,H)=>{var $;($=L.current)==null||$.sendMCPToolApprovalResult(q,H)},changeInputDevice:async q=>{if(L.current&&"changeInputDevice"in L.current)return await L.current.changeInputDevice(q);throw new Error("Device switching is only available for voice conversations")},changeOutputDevice:async q=>{if(L.current&&"changeOutputDevice"in L.current)return await L.current.changeOutputDevice(q);throw new Error("Device switching is only available for voice conversations")},status:N,canSendFeedback:j,micMuted:n,isSpeaking:z==="speaking"}}class ElevenLabsErrorLogger{logs=[];maxLogs=100;isEnabled=!0;initialized=!1;constructor(){}ensureInitialized(){this.initialized||typeof window>"u"||(this.initialized=!0,this.loadLogs(),this.setupGlobalErrorHandler(),this.setupPerformanceMonitoring())}generateId(){return`error_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getBrowserInfo(){return typeof navigator>"u"?null:{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,connection:navigator.connection?{effectiveType:navigator.connection.effectiveType,downlink:navigator.connection.downlink,rtt:navigator.connection.rtt,saveData:navigator.connection.saveData}:null,hardwareConcurrency:navigator.hardwareConcurrency,maxTouchPoints:navigator.maxTouchPoints,vendor:navigator.vendor}}getNetworkInfo(){return typeof window>"u"?null:{timestamp:new Date().toISOString(),url:window.location.href,referrer:document.referrer,online:navigator.onLine,connection:navigator.connection?{effectiveType:navigator.connection.effectiveType,downlink:navigator.connection.downlink,rtt:navigator.connection.rtt}:null}}getViewportInfo(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio,orientation:screen.orientation?screen.orientation.type:"unknown"}}getMemoryInfo(){if(performance.memory)return{usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}}getPerformanceInfo(){if(performance&&performance.timing){const n=performance.timing;return{navigationStart:n.navigationStart,loadEventEnd:n.loadEventEnd,domContentLoadedEventEnd:n.domContentLoadedEventEnd,domComplete:n.domComplete,loadComplete:n.loadComplete}}}setupGlobalErrorHandler(){typeof window>"u"||(window.addEventListener("unhandledrejection",n=>{this.logError("unhandled_promise_rejection",n.reason,{connectionState:"unknown",sessionInfo:{hasActiveSession:!1}})}),window.addEventListener("error",n=>{this.logError("global_error",n.error||n.message,{connectionState:"unknown",sessionInfo:{hasActiveSession:!1}})}))}setupPerformanceMonitoring(){if(!(typeof window>"u")&&"PerformanceObserver"in window)try{new PerformanceObserver(P=>{for(const R of P.getEntries())if(R.entryType==="navigation"){const A=R;A.loadEventEnd-A.navigationStart>1e4&&console.warn("[ElevenLabsErrorLogger] ⚠️ Slow page load detected, might affect WebSocket stability")}}).observe({entryTypes:["navigation"]})}catch(n){console.warn("[ElevenLabsErrorLogger] Performance monitoring not available:",n)}}logError(n,P,R){if(!(!this.isEnabled||typeof window>"u")){this.ensureInitialized();try{const A={id:this.generateId(),timestamp:new Date().toISOString(),errorType:n,errorMessage:P instanceof Error?P.message:String(P),connectionState:R.connectionState,sessionInfo:R.sessionInfo,browserInfo:this.getBrowserInfo(),networkInfo:this.getNetworkInfo(),elevenLabsError:P,stackTrace:P instanceof Error?P.stack:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:"unknown",url:typeof window<"u"?window.location.href:"unknown",viewport:this.getViewportInfo(),memory:this.getMemoryInfo(),performance:this.getPerformanceInfo()};this.logs.unshift(A),this.logs.length>this.maxLogs&&(this.logs=this.logs.slice(0,this.maxLogs)),this.saveLogs(),console.error("[ElevenLabsErrorLogger] 🔍 Error logged:",{type:n,message:A.errorMessage,timestamp:A.timestamp,connectionState:A.connectionState}),this.sendToAnalytics(A)}catch(A){console.error("[ElevenLabsErrorLogger] ❌ Failed to log error:",A)}}}sendToAnalytics(n){try{typeof gtag<"u"&>ag("event","elevenlabs_error",{error_type:n.errorType,error_message:n.errorMessage,connection_state:n.connectionState,browser:n.browserInfo.userAgent.split(" ")[0],timestamp:n.timestamp})}catch{}}saveLogs(){if(!(typeof localStorage>"u"))try{localStorage.setItem("elevenlabs_error_logs",JSON.stringify(this.logs))}catch(n){console.warn("[ElevenLabsErrorLogger] Failed to save logs to localStorage:",n)}}loadLogs(){if(!(typeof localStorage>"u"))try{const n=localStorage.getItem("elevenlabs_error_logs");n&&(this.logs=JSON.parse(n))}catch(n){console.warn("[ElevenLabsErrorLogger] Failed to load logs from localStorage:",n)}}getLogs(){return[...this.logs]}getLogsByType(n){return this.logs.filter(P=>P.errorType===n)}getLogsByTimeRange(n,P){return this.logs.filter(R=>{const A=new Date(R.timestamp);return A>=n&&A<=P})}getRecentLogs(n=10){return this.logs.slice(0,n)}clearLogs(){this.logs=[],this.saveLogs()}exportLogs(){const n={exportTimestamp:new Date().toISOString(),totalErrors:this.logs.length,logs:this.logs};return JSON.stringify(n,null,2)}downloadLogs(n){if(typeof document>"u")return;const P=this.exportLogs(),R=new Blob([P],{type:"application/json"}),A=URL.createObjectURL(R),L=document.createElement("a");L.href=A,L.download=n||`elevenlabs-error-logs-${new Date().toISOString().slice(0,19).replace(/:/g,"-")}.json`,L.click(),URL.revokeObjectURL(A)}getErrorSummary(){const n={totalErrors:this.logs.length,errorTypes:{},connectionStates:{},timeDistribution:{lastHour:0,lastDay:0,lastWeek:0}},P=new Date,R=new Date(P.getTime()-3600*1e3),A=new Date(P.getTime()-1440*60*1e3),L=new Date(P.getTime()-10080*60*1e3);return this.logs.forEach(O=>{n.errorTypes[O.errorType]=(n.errorTypes[O.errorType]||0)+1,n.connectionStates[O.connectionState]=(n.connectionStates[O.connectionState]||0)+1;const N=new Date(O.timestamp);N>=R&&n.timeDistribution.lastHour++,N>=A&&n.timeDistribution.lastDay++,N>=L&&n.timeDistribution.lastWeek++}),n}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}isLoggingEnabled(){return this.isEnabled}}const elevenLabsErrorLogger=new ElevenLabsErrorLogger,useElevenLabsManager=({onConnect:T,onDisconnect:n,onError:P,onMessage:R,onAudioData:A,onStatusChange:L})=>{const O=a({onConnect:()=>{console.log("[ElevenLabsManager] ✅ Connected"),console.log("[ElevenLabsManager] 🔍 Stack trace for connect:",new Error().stack),V("connected"),B(null),T?.()},onDisconnect:()=>{console.log("[ElevenLabsManager] 🔌 Disconnected"),console.log("[ElevenLabsManager] 🔍 Stack trace for disconnect:",new Error().stack),V("disconnected"),n?.()},onError:oe=>{console.error("[ElevenLabsManager] ❌ Error:",oe),V("disconnected");const ae=Z(oe,"elevenlabs_error");W(de=>[...de,ae]),elevenLabsErrorLogger.logError("elevenlabs_error",oe,{connectionState:N,sessionInfo:{hasActiveSession:!!O,conversationStatus:O?.status,conversationId:O?.conversationId||O?.id}}),P?.(oe)},onMessage:oe=>{be(),console.log("[ElevenLabsManager] 📨 Message received:",JSON.stringify(oe).substring(0,300)),R?.(oe)}}),[N,V]=React.useState("disconnected"),[j,B]=React.useState(null),[z,W]=React.useState([]),q=React.useRef(null);React.useEffect(()=>{if(!O)return;const oe=O?.id||O?.conversationId||"unknown";q.current&&q.current!==oe?(console.error("[ElevenLabsManager] ⚠️⚠️⚠️ CONVERSATION OBJECT RECREATED! Old:",q.current,"New:",oe),console.error("[ElevenLabsManager] 🔍 Stack trace:",new Error().stack)):q.current||console.log("[ElevenLabsManager] 🆕 Initial conversation object created:",oe),q.current=oe},[O]),React.useEffect(()=>{if(!O)return;let oe=null;const ae={getOutputByteFrequencyData:"getOutputByteFrequencyData"in O,getInputByteFrequencyData:"getInputByteFrequencyData"in O};return ae.getOutputByteFrequencyData?oe=setInterval(()=>{try{const de=O.getOutputByteFrequencyData();if(de&&(Array.isArray(de)||de instanceof Uint8Array)&&de.length>0){const ge=Array.isArray(de)?de:Array.from(de),ye=ge.reduce((Ee,Pe)=>Ee+Pe,0)/ge.length;if(A)try{A({data:ge,averageLevel:ye,timestamp:Date.now()})}catch(Ee){console.error("[ElevenLabsManager] ❌ Error in onAudioData callback:",Ee)}}}catch(de){console.warn("[ElevenLabsManager] ⚠️ Audio data collection error:",de)}},100):ae.getInputByteFrequencyData?(console.warn("[ElevenLabsManager] ⚠️ getOutputByteFrequencyData not available, falling back to getInputByteFrequencyData (user voice)"),oe=setInterval(()=>{try{const de=O.getInputByteFrequencyData();if(de&&(Array.isArray(de)||de instanceof Uint8Array)&&de.length>0){const ge=Array.isArray(de)?de:Array.from(de),ye=ge.reduce((Ee,Pe)=>Ee+Pe,0)/ge.length;A&&A({data:ge,averageLevel:ye,timestamp:Date.now()})}}catch(de){console.warn("[ElevenLabsManager] ⚠️ Fallback audio data collection error:",de)}},100)):console.warn("[ElevenLabsManager] ⚠️ No audio data methods available on conversation object"),()=>{oe&&clearInterval(oe)}},[O,A]);const H=React.useRef(null),$=React.useRef(!1),Q=React.useRef(null),U=React.useRef(null),J=React.useRef(null),G=React.useRef(null),K=React.useRef([]),Y=React.useRef(null),Z=React.useCallback((oe,ae)=>{const de=new Date().toISOString();return{message:oe instanceof Error?oe.message:String(oe),type:ae,timestamp:de,connectionState:N,sessionInfo:{hasActiveSession:!!O,conversationStatus:O?.status,conversationId:O?.conversationId||O?.id},browserInfo:{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine},networkInfo:{connectionType:navigator.connection?.type||"unknown",effectiveType:navigator.connection?.effectiveType||"unknown",downlink:navigator.connection?.downlink||"unknown",rtt:navigator.connection?.rtt||"unknown"},elevenLabsError:{error:oe,errorType:typeof oe,errorKeys:oe&&typeof oe=="object"?Object.keys(oe):"N/A",stack:oe instanceof Error?oe.stack:"N/A"}}},[N,O]),ie=React.useCallback(()=>{J.current&&clearInterval(J.current),J.current=setInterval(()=>{if(N==="connected"&&O){const oe=Date.now(),ae=U.current?oe-U.current:0,de=Q.current?oe-Q.current:0;console.log("[ElevenLabsManager] 📊 Connection Health:",{connectionDuration:`${Math.round(de/1e3)}s`,timeSinceLastActivity:`${Math.round(ae/1e3)}s`,conversationStatus:O.status}),ae>6e4&&console.warn("[ElevenLabsManager] ⚠️ No activity for over 1 minute")}},1e4)},[N,O]),se=React.useCallback(()=>{J.current&&(clearInterval(J.current),J.current=null)},[]),le=React.useCallback(async oe=>{(N==="connecting"||N==="connected")&&(console.log("[ElevenLabsManager] ⚠️ Session already active, ending first..."),await pe()),console.log("[ElevenLabsManager] ⏳ Pre-session buffer (1 second) to ensure clean state..."),await new Promise(ae=>setTimeout(ae,1e3)),console.log("[ElevenLabsManager] 🔧 Warming up AudioContext before session start...");try{const ae=window.AudioContext||window.webkitAudioContext;if(ae){const de=new ae;de.state==="suspended"&&(await de.resume(),console.log("[ElevenLabsManager] ✅ AudioContext resumed")),await new Promise(ge=>setTimeout(ge,200)),await de.close(),console.log("[ElevenLabsManager] ✅ AudioContext warmed up and closed")}}catch(ae){console.warn("[ElevenLabsManager] ⚠️ AudioContext warmup failed (non-critical):",ae)}try{console.log("[ElevenLabsManager] 🚀 Starting new session..."),V("connecting"),B(null),Q.current=Date.now(),U.current=Date.now(),K.current=[],Y.current||(Y.current=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices));const ae=Y.current;navigator.mediaDevices.getUserMedia=async function(Ie){const Ae=await ae(Ie);return Ie?.audio&&K.current.push(Ae),Ae};const de={signedUrl:oe.signedUrl,overrides:{agent:{prompt:{prompt:oe.agent.prompt},language:oe.agent.language,...oe.agent.firstMessage&&{firstMessage:oe.agent.firstMessage}},tts:oe.tts?{...oe.tts,stability:.7,similarity_boost:.5,style:0,use_speaker_boost:!0,speed:1}:void 0,conversation:{textOnly:!1}},customLlmExtraBody:oe.customLlmExtraBody};console.log("[ElevenLabsManager] 📋 Session config:",de),ie(),console.log("[ElevenLabsManager] 📋 Registering client tools: show_asset, close_asset, update_user_profile, custom_cta, show_email_form, load_skill");const ge={show_asset:async Ie=>{console.log("[ElevenLabsManager] 🎨 show_asset tool called:",Ie),L?.("calling_tool");try{const Ae=getCurrentBackendUrl(),Le=await fetch(`${Ae}/api/show-me/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe.customLlmExtraBody.jwt||""}`},body:JSON.stringify({query:Ie.query,context:Ie.context,session_id:oe.customLlmExtraBody.session_id,company_id:oe.customLlmExtraBody.company_id})});if(!Le.ok)throw new Error(`Asset search failed: ${Le.statusText}`);const Me=await Le.json();if(console.log("[ElevenLabsManager] ✅ Asset search result:",Me),Me.success&&Me.asset){console.log("[ElevenLabsManager] 📤 Dispatching show_asset event to window");const ke=new CustomEvent("show_asset",{detail:{asset:Me.asset,offer_message:Me.offer_message}});window.dispatchEvent(ke),console.log("[ElevenLabsManager] ✅ Event dispatched successfully")}return L?.("speaking"),Me}catch(Ae){return console.error("[ElevenLabsManager] ❌ show_asset error:",Ae),L?.("speaking"),{success:!1,error:String(Ae)}}},close_asset:async()=>{console.log("[ElevenLabsManager] 🚪 close_asset tool called"),L?.("calling_tool");try{const Ie=new CustomEvent("close_asset");return window.dispatchEvent(Ie),console.log("[ElevenLabsManager] ✅ Close asset event dispatched"),L?.("speaking"),{success:!0}}catch(Ie){return console.error("[ElevenLabsManager] ❌ close_asset error:",Ie),L?.("speaking"),{success:!1,error:String(Ie)}}},update_user_profile:async Ie=>{console.log("[ElevenLabsManager] 👤 update_user_profile tool called:",Ie),L?.("calling_tool");try{const Ae=getCurrentBackendUrl(),Le=await fetch(`${Ae}/api/prospects/update-profile`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe.customLlmExtraBody.jwt||""}`},body:JSON.stringify({session_id:oe.customLlmExtraBody.session_id,company_id:oe.customLlmExtraBody.company_id,profile_data:Ie})});if(!Le.ok)throw new Error(`Profile update failed: ${Le.statusText}`);const Me=await Le.json();return console.log("[ElevenLabsManager] ✅ Profile updated:",Me),L?.("speaking"),"Saved"}catch(Ae){return console.error("[ElevenLabsManager] ❌ update_user_profile error:",Ae),L?.("speaking"),"Error saving"}},custom_cta:async Ie=>{console.log("[ElevenLabsManager] 🔗 custom_cta tool called:",Ie),L?.("calling_tool");const Ae=oe.customLlmExtraBody?.customCta,Le=oe.customLlmExtraBody?.session_id,Me=oe.customLlmExtraBody?.jwt,ke=oe.customLlmExtraBody?.agent_id,Ce=oe.customLlmExtraBody?.companyToken||"",xe=Ie.url||Ae?.href;if(!xe)return console.error("[ElevenLabsManager] ❌ custom_cta: No URL provided and no CTA configured"),L?.("speaking"),{success:!1,error:"No URL to redirect to"};let we=null;if(Ae?.id&&Le&&Me)try{const De=await fetch(`${getCurrentBackendUrl()}/api/widget/custom-cta/click`,{method:"POST",headers:{Authorization:`Bearer ${Me}`,"Content-Type":"application/json"},body:JSON.stringify({custom_cta_id:Ae.id,widget_session_id:Le})});De.ok&&(we=(await De.json()).id)}catch(De){console.warn("[ElevenLabsManager] ⚠️ custom_cta: Failed to track click:",De)}if(sessionStorage.setItem("lastCtaClickId",we||"agent-redirect"),Ae?.open_in_new_tab!==!1)window.open(xe,"_blank","noopener,noreferrer");else{const{saveSession:De,CTA_SAME_TAB_REDIRECT_KEY:We}=await Promise.resolve().then(()=>sessionPersistence);try{const Fe=getCurrentBackendUrl();await fetch(`${Fe}/api/widget/session/${Le}/pause`,{method:"POST",headers:{Authorization:`Bearer ${Me}`,"X-Client-Token":Ce,"Content-Type":"application/json"}})}catch(Fe){console.warn("[ElevenLabsManager] ⚠️ custom_cta: Failed to pause before same-tab redirect:",Fe)}De({sessionId:Le,widgetJwt:Me,agentId:ke||"",companyToken:Ce,status:"paused",lastActivityAt:Date.now(),pageUrl:window.location.href,conversationState:{messageCount:0,lastMessage:void 0}}),sessionStorage.setItem(We,"1"),window.location.href=xe}return L?.("speaking"),{success:!0}},show_email_form:async Ie=>{console.log("[ElevenLabsManager] 📧 show_email_form tool called:",Ie),L?.("calling_tool");try{const Ae=new CustomEvent("show_email_form",{detail:{prompt:Ie?.prompt,force_display:Ie?.force_display??!1}});return window.dispatchEvent(Ae),console.log("[ElevenLabsManager] ✅ show_email_form event dispatched"),L?.("speaking"),{success:!0}}catch(Ae){return console.error("[ElevenLabsManager] ❌ show_email_form error:",Ae),L?.("speaking"),{success:!1,error:String(Ae)}}},load_skill:async Ie=>{console.log("[ElevenLabsManager] 📚 load_skill tool called:",Ie),L?.("calling_tool");try{const Ae=getCurrentBackendUrl(),Le=oe.customLlmExtraBody?.agent_id;let Me=`${Ae}/api/skills/${Ie.skill_name}/content`;Le&&(Me+=`?agent_id=${Le}`);const ke=await fetch(Me,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe.customLlmExtraBody.jwt||""}`}});if(!ke.ok)throw new Error(`Skill content fetch failed: ${ke.statusText}`);const Ce=await ke.json();return console.log("[ElevenLabsManager] ✅ Skill content loaded:",Ce.name),L?.("speaking"),Ce}catch(Ae){return console.error("[ElevenLabsManager] ❌ load_skill error:",Ae),L?.("speaking"),{success:!1,error:String(Ae)}}},get_user_profile:async()=>(console.warn("[ElevenLabsManager] ⚠️ get_user_profile called but is deprecated - returning empty profile"),console.warn("[ElevenLabsManager] ⚠️ Please disable get_user_profile in ElevenLabs agent configuration"),L?.("speaking"),"Profile data already available")};await O.startSession({...de,clientTools:ge});let ye=0;const Ee=3e3,Pe=100;for(;ye<Ee;){if(O?.status==="connected"){console.log(`[ElevenLabsManager] ✅ Connection established after ${ye}ms`);break}await new Promise(Ae=>setTimeout(Ae,Pe)),ye+=Pe}return console.log("[ElevenLabsManager] ✅ Session ready - ElevenLabs will handle audio buffering"),Y.current&&(navigator.mediaDevices.getUserMedia=Y.current),console.log("[ElevenLabsManager] ✅ Session started successfully"),!0}catch(ae){console.error("[ElevenLabsManager] ❌ Failed to start session:",ae),V("disconnected"),Y.current&&(navigator.mediaDevices.getUserMedia=Y.current);const de=Z(ae,"session_start_failed");return W(ge=>[...ge,de]),elevenLabsErrorLogger.logError("session_start_failed",ae,{connectionState:N,sessionInfo:{hasActiveSession:!!O,conversationStatus:O?.status}}),!1}},[O,N,ie,Z]),pe=React.useCallback(async()=>{if(N!=="disconnected")try{console.log("[ElevenLabsManager] 🔚 Ending session..."),V("disconnected"),se(),G.current&&(clearTimeout(G.current),G.current=null),O&&typeof O.endSession=="function"&&(await O.endSession(),console.log("[ElevenLabsManager] ⏳ Starting background cleanup (5 seconds)..."),setTimeout(()=>{console.log("[ElevenLabsManager] ✅ Background cleanup completed (5 seconds)")},5e3)),console.log("[ElevenLabsManager] ✅ Session ended successfully (UI updated immediately)")}catch(oe){console.error("[ElevenLabsManager] ❌ Error ending session:",oe),V("disconnected");const ae=Z(oe,"session_end_failed");W(de=>[...de,ae]),elevenLabsErrorLogger.logError("session_end_failed",oe,{connectionState:N,sessionInfo:{hasActiveSession:!!O,conversationStatus:O?.status}})}},[O,N,se,Z]),ue=React.useCallback(()=>{if($.current){console.log("[ElevenLabsManager] ⚠️ Session renewal already started");return}console.log("[ElevenLabsManager] 🔄 Starting proactive session renewal (every 4.5 minutes)"),$.current=!0,H.current=setInterval(async()=>{try{console.log("[ElevenLabsManager] 🔄 Proactive session renewal triggered"),N==="connected"&&O&&(await O.endSession(),await new Promise(oe=>setTimeout(oe,100)),console.log("[ElevenLabsManager] 🔄 Session renewal completed"))}catch(oe){console.error("[ElevenLabsManager] ❌ Session renewal failed:",oe)}},27e4)},[N,O]),he=React.useCallback(()=>{H.current&&(clearInterval(H.current),H.current=null,$.current=!1,console.log("[ElevenLabsManager] 🛑 Session renewal stopped"))},[]),ve=React.useCallback(()=>{B(null)},[]),be=React.useCallback(()=>{U.current=Date.now()},[]),fe=React.useCallback(async(oe,ae=3)=>{if(N==="connecting"||N==="reconnecting")return console.log("[ElevenLabsManager] ⚠️ Already attempting to connect"),!1;console.log("[ElevenLabsManager] 🔄 Manual reconnection initiated"),V("reconnecting");for(let de=1;de<=ae;de++)try{if(console.log(`[ElevenLabsManager] 🔄 Reconnection attempt ${de}/${ae}`),de>1){const ye=Math.min(1e3*Math.pow(2,de-1),1e4);console.log(`[ElevenLabsManager] ⏳ Waiting ${ye}ms before retry...`),await new Promise(Ee=>setTimeout(Ee,ye))}if(await le(oe))return console.log("[ElevenLabsManager] ✅ Manual reconnection successful"),!0}catch(ge){if(console.error(`[ElevenLabsManager] ❌ Reconnection attempt ${de} failed:`,ge),de===ae)return console.error("[ElevenLabsManager] ❌ All reconnection attempts failed"),V("disconnected"),!1}return V("disconnected"),!1},[N,le]),ne=React.useCallback(()=>{const oe=Date.now(),ae=Q.current?oe-Q.current:0,de=U.current?oe-U.current:0;return{connectionState:N,connectionDuration:Math.round(ae/1e3),timeSinceLastActivity:Math.round(de/1e3),conversationStatus:O?.status,conversationId:O?.conversationId||O?.id,errorCount:z.length,lastError:z[z.length-1]||null}},[N,O,z]);React.useEffect(()=>()=>{se(),he(),G.current&&clearTimeout(G.current)},[se,he]);const ce=React.useCallback(()=>{if(!O){console.warn("[ElevenLabsManager] ⚠️ Cannot send keep-alive: no conversation");return}if(N!=="connected"){console.warn("[ElevenLabsManager] ⚠️ Cannot send keep-alive: not connected");return}try{O.sendUserInput?.(" "),console.log("[ElevenLabsManager] 🔄 Keep-alive sent (space character)")}catch(oe){console.error("[ElevenLabsManager] ❌ Failed to send keep-alive:",oe)}},[O,N]),ee=React.useCallback(oe=>{K.current.forEach(ae=>{ae.getAudioTracks().forEach(de=>{de.enabled=!oe})})},[]),te=React.useCallback(oe=>{const ae=oe?0:1;try{O?.setVolume?.({volume:ae}),console.log(`[ElevenLabsManager] 🔇 Agent audio ${oe?"muted":"unmuted"} via SDK (volume=${ae})`)}catch(de){console.warn("[ElevenLabsManager] setVolume failed, falling back to DOM muting:",de)}document.querySelectorAll("audio").forEach(de=>{de.muted=oe,de.volume=ae}),document.querySelectorAll("video").forEach(de=>{de.muted=oe,de.volume=ae})},[O]);return{conversation:O,connectionState:N,isConnected:N==="connected",isConnecting:N==="connecting",isReconnecting:N==="reconnecting",isAgentSpeaking:O?.isSpeaking||!1,isListening:N==="disconnected"?!1:!O?.isSpeaking,error:j,detailedErrors:z,startSession:le,endSession:pe,startSessionRenewal:ue,stopSessionRenewal:he,clearError:ve,updateActivity:be,manualReconnect:fe,sendKeepAlive:ce,muteMicrophone:ee,muteAgentAudio:te,startDiagnostics:ie,stopDiagnostics:se,getDiagnostics:ne}},useAudioVisualization=({inputMode:T})=>{const[n,P]=React.useState([]),[R,A]=React.useState(!1),[L,O]=React.useState(0),N=React.useRef(null),V=React.useRef(null),j=React.useRef(null),B=React.useRef(null),z=React.useRef(null),W=React.useRef(!1),q=React.useCallback(()=>{try{if(!N.current){N.current=new(window.AudioContext||window.webkitAudioContext),V.current=N.current.createAnalyser(),V.current.fftSize=256,V.current.smoothingTimeConstant=.8,V.current.minDecibels=-90,V.current.maxDecibels=-10;const G=V.current.frequencyBinCount;B.current=new Uint8Array(G),console.log("[useAudioVisualization] Audio analysis initialized for visualization")}}catch(G){console.error("[useAudioVisualization] Error initializing audio analysis:",G)}},[]),H=React.useCallback(G=>{if((!V.current||!B.current)&&(q(),!V.current||!B.current))return;try{if(N.current&&G){j.current&&(j.current.disconnect(),j.current=null);const ie=N.current.createMediaStreamSource(G);j.current=ie,ie.connect(V.current),console.log("[useAudioVisualization] 🎤 Microphone stream connected to audio analyzer (copy)")}}catch(ie){console.error("[useAudioVisualization] Error connecting microphone to analyzer:",ie)}let K=0;const Y=50,Z=()=>{const ie=Date.now();if(ie-K>=Y){if(V.current&&B.current&&V.current&&B.current){V.current.getByteFrequencyData(B.current);const se=B.current;let le=0;for(let pe=0;pe<se.length;pe++)le+=se[pe];O(le/(se.length*255))}K=ie}z.current=requestAnimationFrame(Z)};Z(),console.log("[useAudioVisualization] 🎵 Microphone audio processing started (not for agent Lottie)")},[T,q]),$=React.useCallback(()=>{if(z.current&&(cancelAnimationFrame(z.current),z.current=null),O(0),j.current)try{j.current.disconnect(),j.current=null}catch(G){console.warn("[useAudioVisualization] Warning: Error disconnecting media stream source:",G)}},[]),Q=React.useCallback(G=>{console.log("[useAudioVisualization] 🎤 setAgentSpeaking called:",{isSpeaking:G,previousState:W.current,hasAudioData:n.length>0}),W.current=G,A(G)},[]),U=React.useCallback(G=>{G&&Array.isArray(G)&&G.length>0?P(G):console.warn("[useAudioVisualization] ⚠️ Invalid real audio data received:",G)},[]);React.useEffect(()=>()=>{$(),N.current&&(N.current.close(),N.current=null)},[$]);const J=React.useCallback(()=>{if(V.current)try{V.current.disconnect(),console.log("[useAudioVisualization] 🎤 Audio analyzer fully disconnected")}catch(G){console.warn("[useAudioVisualization] Warning: Error disconnecting audio analyzer:",G)}if(N.current)try{N.current.close(),N.current=null,console.log("[useAudioVisualization] 🎤 Audio context closed")}catch(G){console.warn("[useAudioVisualization] Warning: Error closing audio context:",G)}},[]);return React.useMemo(()=>({audioData:n,isAgentSpeaking:R,micLevel:L,startAudioVisualization:H,stopAudioVisualization:$,setAgentSpeaking:Q,setRealAudioData:U,cleanupAudioContext:J}),[n,R,L,H,$,Q,U,J])},useVoiceSessionV2=({agent:T,agentId:n,sessionId:P,jwt:R,messages:A,setMessages:L,onError:O,customCta:N,companyToken:V})=>{const j=React.useRef(null),B=React.useRef(!1),z=React.useRef(R);z.current=R;const W=React.useRef(P);W.current=P;const q=useAudioVisualization({inputMode:"voice"});React.useRef(null),React.useRef(null);const H=React.useCallback(()=>{console.log("[useVoiceSessionV2] ✅ ElevenLabs connected")},[]),$=React.useCallback(()=>{console.log("[useVoiceSessionV2] 🔌 ElevenLabs disconnected")},[]),Q=React.useCallback(Z=>{console.error("[useVoiceSessionV2] ❌ ElevenLabs error:",Z),O(`Voice error: ${Z instanceof Error?Z.message:"Unknown error"}`)},[O]),U=React.useCallback(Z=>{if(B.current&&!(!Z||typeof Z!="object")&&"source"in Z&&"message"in Z){const ie={role:Z.source==="ai"?"assistant":"user",content:Z.message};L(pe=>[...pe,ie]);const se=W.current,le=z.current;se&&le&&fetch(buildApiUrl("api/widget/session/log-message"),{method:"POST",headers:{Authorization:`Bearer ${le}`,"Content-Type":"application/json"},body:JSON.stringify({session_id:se,role:ie.role,message:ie.content})}).then(pe=>{pe.ok||console.error("[useVoiceSessionV2] ⚠️ log-message failed:",pe.status,pe.statusText)}).catch(pe=>{console.error("[useVoiceSessionV2] ⚠️ Failed to log message to backend:",pe)}),Z.source==="ai"?q.setAgentSpeaking?.(!0):q.setAgentSpeaking?.(!1)}},[L,q]),J=React.useCallback(Z=>{q.setRealAudioData&&q.setRealAudioData(Z.data)},[q]),G=useElevenLabsManager({onConnect:H,onDisconnect:$,onError:Q,onMessage:U,onAudioData:J}),K=React.useCallback(async(Z=!1,ie="",se="")=>{if(console.log("[useVoiceSessionV2] 🚀 Starting voice session..."),console.log("[useVoiceSessionV2] 📊 Required data check:",{agent:!!T,sessionId:!!P,jwt:!!R,agentId:!!n,isResuming:Z,hasLastUserMsg:!!ie,hasLastAssistantMsg:!!se}),!T||!P||!R)return console.error("[useVoiceSessionV2] ❌ Missing required data for voice session"),!1;console.log("[useVoiceSessionV2] ✅ All required data present, proceeding...");try{const le=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});j.current=le,q.startAudioVisualization(le);const pe=await fetch(buildApiUrl("api/widget/session/signed-url"),{method:"POST",headers:{Authorization:`Bearer ${R}`,"Content-Type":"application/json"},body:JSON.stringify({agent_id:n,session_id:P})});if(!pe.ok)throw new Error(`Failed to get signed URL: ${pe.statusText}`);const{signed_url:ue}=await pe.json();console.log("[useVoiceSessionV2] ✅ Got signed URL from backend");let he;try{const fe=await fetch(buildApiUrl(`api/widget/session/${P}/personalized-prompt`),{headers:{Authorization:`Bearer ${R}`}});if(fe.ok){const{prompt:ne}=await fe.json();he=(ne||"").replace(/^assistant:\s*/i,"").trim(),console.log("[useVoiceSessionV2] ✅ Using personalized prompt from backend")}else throw new Error("Prompt fetch failed")}catch(fe){console.warn("[useVoiceSessionV2] ⚠️ Could not fetch personalized prompt, using agent instructions:",fe),he=(T.agent_instructions||"").replace(/^assistant:\s*/i,"").trim()}if(!he){const fe="Agent instructions are missing. The agent may not have been configured correctly.";return console.error("[useVoiceSessionV2] ❌",fe),O(fe),!1}console.log("[useVoiceSessionV2] 🎯 Starting ElevenLabs session..."),console.log("[useVoiceSessionV2] 📊 ElevenLabs manager state:",{conversation:!!G.conversation,connectionState:G.connectionState,isConnected:G.isConnected,isResuming:Z});let ve="";if(Z&&(ie||se)?(ve=`${ie?`Welcome back! We were just discussing: "${ie.substring(0,100)}${ie.length>100?"...":""}"`:se?`Welcome back! I was just saying: "${se.substring(0,100)}${se.length>100?"...":""}"`:"Welcome back! How can I continue helping you?"}. How can I help you continue?`,console.log("[useVoiceSessionV2] 🔄 Using resume-specific first message:",ve)):T.agent_first_message&&A.length===0&&(ve=T.agent_first_message,console.log("[useVoiceSessionV2] 👋 Using standard welcome message:",ve)),ve){const fe={role:"assistant",content:ve};console.log("[useVoiceSessionV2] 🎯 Adding first message to store:",fe),L([fe]),console.log("[useVoiceSessionV2] 🎤 Setting agent as speaking for initial message"),q.setAgentSpeaking&&q.setAgentSpeaking(!0)}const be=setTimeout(()=>{throw console.error("[useVoiceSessionV2] ⏰ Session start timeout - taking too long"),new Error("Session start timeout - taking too long")},3e4);try{const fe=(T.agent_first_message||"").replace(/^assistant:\s*/i,"").trim(),ne=ve||fe||"Hello! How can I help you today?",ce=await G.startSession({signedUrl:ue,agent:{prompt:he,language:"en",...ne&&(Z||A.length===0)&&{firstMessage:ne}},tts:T.elevenlabs_voice_id?{voiceId:T.elevenlabs_voice_id,stability:.7,similarity_boost:.5,style:0,use_speaker_boost:!0,speed:1}:void 0,customLlmExtraBody:{session_id:P,agent_id:n,company_id:T.company_id||null,namespace:`${T.company_id||"__default__"}-global`,vad_enabled:!0,jwt:R,customCta:N||null,companyToken:V||""}});if(clearTimeout(be),console.log("[useVoiceSessionV2] 📊 ElevenLabs session result:",ce),ce)return G.startSessionRenewal(),B.current=!0,console.log("[useVoiceSessionV2] 🎯 Session started - ElevenLabs will manage speaking/listening states"),console.log("[useVoiceSessionV2] ✅ Voice session started successfully"),!0;throw new Error("Failed to start ElevenLabs session")}catch(fe){throw clearTimeout(be),fe}}catch(le){return console.error("[useVoiceSessionV2] ❌ Failed to start voice session:",le),j.current&&(j.current.getTracks().forEach(pe=>pe.stop()),j.current=null),le instanceof Error&&le.name==="NotAllowedError"?O("Microphone access denied. Please allow microphone access to use voice mode."):O(`Failed to start voice mode: ${le instanceof Error?le.message:"Unknown error"}`),!1}finally{}},[T,n,P,R,A,G,q,O]),Y=React.useCallback(async()=>{try{console.log("[useVoiceSessionV2] 🔚 Ending voice session..."),B.current=!1,await G.endSession(),G.stopSessionRenewal(),q.stopAudioVisualization(),q.cleanupAudioContext&&(q.cleanupAudioContext(),console.log("[useVoiceSessionV2] ✅ AudioContext explicitly cleaned up")),j.current&&(j.current.getTracks().forEach(Z=>Z.stop()),j.current=null),console.log("[useVoiceSessionV2] ✅ Voice session ended successfully")}catch(Z){console.error("[useVoiceSessionV2] ❌ Error ending voice session:",Z),j.current&&(j.current.getTracks().forEach(ie=>ie.stop()),j.current=null)}},[G,q]);return{conversation:G.conversation,connectionState:G.connectionState,isConnected:G.isConnected,isConnecting:G.isConnecting,isAgentSpeaking:G.isAgentSpeaking,isListening:G.isListening,error:G.error,audioData:q.audioData,startVoiceSession:K,endVoiceSession:Y,sendKeepAlive:G.sendKeepAlive,mediaStreamRef:j,clearError:G.clearError,muteMicrophone:G.muteMicrophone,muteAgentAudio:G.muteAgentAudio,setAgentSpeaking:q.setAgentSpeaking,micLevel:q.micLevel}},useTextSessionV2=({agent:T,agentId:n,sessionId:P,jwt:R,messages:A,setMessages:L,onError:O})=>{const[N,V]=React.useState(""),[j,B]=React.useState(!1),z=React.useRef(R);z.current=R;const W=React.useRef(P);W.current=P;const q=useElevenLabsManager({onConnect:()=>{console.log("[useTextSessionV2] ✅ ElevenLabs connected for text mode")},onDisconnect:()=>{console.log("[useTextSessionV2] 🔌 ElevenLabs disconnected from text mode")},onError:J=>{console.error("[useTextSessionV2] ❌ ElevenLabs error:",J),O(`Text chat error: ${J instanceof Error?J.message:"Unknown error"}`)},onMessage:J=>{if(console.log("[useTextSessionV2] 📨 Text message received:",J),J&&typeof J=="object"&&"message"in J){const G=J.source==="ai"?"assistant":"user",K=J.message;console.log("[useTextSessionV2] Processing text message:",{role:G,content:K}),L(ie=>[...ie,{role:G,content:K}]);const Y=W.current,Z=z.current;Y&&Z&&fetch(buildApiUrl("api/widget/session/log-message"),{method:"POST",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json"},body:JSON.stringify({session_id:Y,role:G,message:K})}).catch(ie=>{console.error("[useTextSessionV2] ⚠️ Failed to log message to backend:",ie)}),G==="assistant"&&(q.setIsAgentSpeaking(!0),setTimeout(()=>{q.setIsAgentSpeaking(!1)},1e3))}}}),H=React.useCallback(async()=>{if(!T||!P||!R)return console.error("[useTextSessionV2] ❌ Missing required data for text session"),!1;try{console.log("[useTextSessionV2] 📝 Starting text session...");const J=await fetch(buildApiUrl("api/widget/session/signed-url"),{method:"POST",headers:{Authorization:`Bearer ${R}`,"Content-Type":"application/json"},body:JSON.stringify({agent_id:n,session_id:P})});if(!J.ok)throw new Error(`Failed to get signed URL: ${J.statusText}`);const{signed_url:G}=await J.json();console.log("[useTextSessionV2] ✅ Got signed URL for text session");let K;try{const Z=await fetch(buildApiUrl(`api/widget/session/${P}/personalized-prompt`),{headers:{Authorization:`Bearer ${R}`}});if(Z.ok){const{prompt:ie}=await Z.json();K=(ie||"").replace(/^assistant:\s*/i,"").trim(),console.log("[useTextSessionV2] ✅ Using personalized prompt from backend")}else throw new Error("Prompt fetch failed")}catch(Z){console.warn("[useTextSessionV2] ⚠️ Could not fetch personalized prompt, using agent instructions:",Z),K=(T.agent_instructions||"").replace(/^assistant:\s*/i,"").trim()}if(await q.startSession({signedUrl:G,agent:{prompt:K||"",language:"en",...A.length===0&&{firstMessage:T.agent_first_message||""}},tts:T.elevenlabs_voice_id?{voiceId:T.elevenlabs_voice_id}:void 0,customLlmExtraBody:{session_id:P,company_id:T.company_id||null,namespace:`${T.company_id||"__default__"}-global`,vad_enabled:!1,require_email:T.require_email||!1,jwt:R}}))return console.log("[useTextSessionV2] ✅ Text session started successfully"),!0;throw new Error("Failed to start ElevenLabs text session")}catch(J){return console.error("[useTextSessionV2] ❌ Failed to start text session:",J),O(`Failed to start text mode: ${J instanceof Error?J.message:"Unknown error"}`),!1}},[T,n,P,R,A,q,O]),$=React.useCallback(async J=>{if(J.preventDefault(),!N.trim()||j)return;const G=N.trim();console.log("[useTextSessionV2] 📝 Sending text message:",G),L(K=>[...K,{role:"user",content:G}]),V(""),B(!0);try{q.isConnected&&q.conversation?(console.log("[useTextSessionV2] 📤 Sending text via ElevenLabs session"),await q.conversation.sendUserMessage(G),console.log("[useTextSessionV2] ✅ Text sent via ElevenLabs")):(console.log("[useTextSessionV2] 📤 No ElevenLabs session, using backend fallback"),await Q(G))}catch(K){console.error("[useTextSessionV2] ❌ Failed to send text via ElevenLabs, falling back to backend:",K);try{await Q(G)}catch(Y){console.error("[useTextSessionV2] ❌ Backend fallback also failed:",Y),O("Failed to send message. Please try again.")}}finally{B(!1)}},[N,j,q,L,O]),Q=React.useCallback(async J=>{try{const G=await fetch(`${getCurrentBackendUrl()}/api/chat/respond`,{method:"POST",headers:{Authorization:`Bearer ${R}`,"Content-Type":"application/json"},body:JSON.stringify({message:J,session_id:P})});if(!G.ok)throw new Error(`Backend API error: ${G.statusText}`);const K=await G.json();console.log("[useTextSessionV2] ✅ Text sent via backend:",K),K.response&&L(Y=>[...Y,{role:"assistant",content:K.response}])}catch(G){throw console.error("[useTextSessionV2] ❌ Backend text message failed:",G),G}},[R,P,L]),U=React.useCallback(async()=>{try{console.log("[useTextSessionV2] 🔚 Ending text session..."),await q.endSession(),console.log("[useTextSessionV2] ✅ Text session ended successfully")}catch(J){console.error("[useTextSessionV2] ❌ Error ending text session:",J)}},[q]);return{textInput:N,setTextInput:V,isSendingText:j,conversation:q.conversation,connectionState:q.connectionState,isConnected:q.isConnected,isConnecting:q.isConnecting,error:q.error,startTextSession:H,endTextSession:U,handleTextSubmit:$,clearError:q.clearError}},STORAGE_KEY="wysdym_widget_session",CTA_SAME_TAB_REDIRECT_KEY="wysdym_cta_same_tab_redirect",EXPIRATION_MS=864e5,MAX_PAYLOAD_SIZE=5120;function sanitizeString(T,n=1e3){return typeof T!="string"?"":T.replace(/[<>]/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").substring(0,n)}function sanitizeSession(T){const n={};return T.sessionId&&(n.sessionId=sanitizeString(T.sessionId,100)),T.widgetJwt&&(n.widgetJwt=sanitizeString(T.widgetJwt,2e3)),T.agentId&&(n.agentId=sanitizeString(T.agentId,100)),T.companyToken&&(n.companyToken=sanitizeString(T.companyToken,200)),T.status&&(n.status=T.status),T.lastActivityAt&&(n.lastActivityAt=Number(T.lastActivityAt)),T.pageUrl&&(n.pageUrl=sanitizeString(T.pageUrl,500)),T.expiresAt&&(n.expiresAt=Number(T.expiresAt)),T.conversationState&&(n.conversationState={messageCount:Number(T.conversationState.messageCount)||0,lastMessage:T.conversationState.lastMessage?sanitizeString(T.conversationState.lastMessage,200):void 0}),n}function getStorage(T){try{return T==="localStorage"?window.localStorage:window.sessionStorage}catch(n){return console.warn(`[SessionPersistence] ${T} not available:`,n),null}}function writeToStorage(T,n){try{const P=getStorage("localStorage");if(P)return P.setItem(T,n),!0}catch(P){if(P?.name==="QuotaExceededError"||P?.code===22){console.warn("[SessionPersistence] localStorage quota exceeded, falling back to sessionStorage");try{const R=getStorage("sessionStorage");if(R)return R.setItem(T,n),!0}catch(R){console.error("[SessionPersistence] sessionStorage fallback failed:",R)}}else console.error("[SessionPersistence] Failed to write to localStorage:",P)}return!1}function readFromStorage(T){try{const n=getStorage("localStorage");if(n){const P=n.getItem(T);if(P!==null)return P}}catch(n){console.error("[SessionPersistence] Failed to read from localStorage:",n)}try{const n=getStorage("sessionStorage");if(n)return n.getItem(T)}catch(n){console.error("[SessionPersistence] Failed to read from sessionStorage:",n)}return null}function removeFromStorage(T){try{getStorage("localStorage")?.removeItem(T)}catch(n){console.error("[SessionPersistence] Failed to remove from localStorage:",n)}try{getStorage("sessionStorage")?.removeItem(T)}catch(n){console.error("[SessionPersistence] Failed to remove from sessionStorage:",n)}}function isExpired(T){return Date.now()>=T.expiresAt}function validatePayloadSize(T){const n=new Blob([T]).size;return n>MAX_PAYLOAD_SIZE?(console.warn(`[SessionPersistence] Payload size ${n} bytes exceeds maximum ${MAX_PAYLOAD_SIZE} bytes`),!1):!0}function saveSession(T){try{const P={...sanitizeSession(T),expiresAt:Date.now()+EXPIRATION_MS},R=JSON.stringify(P);if(!validatePayloadSize(R))return console.error("[SessionPersistence] Session payload too large, cannot save"),!1;const A=writeToStorage(STORAGE_KEY,R);return A&&console.log("[SessionPersistence] Session saved successfully"),A}catch(n){return console.error("[SessionPersistence] Error saving session:",n),!1}}function loadSession(){try{const T=readFromStorage(STORAGE_KEY);if(!T)return console.log("[SessionPersistence] No session found in storage"),null;let n;try{n=JSON.parse(T)}catch(A){return console.error("[SessionPersistence] Failed to parse session JSON:",A),clearSession(),null}if(!n||typeof n!="object")return console.error("[SessionPersistence] Invalid session structure"),clearSession(),null;const P=["sessionId","widgetJwt","agentId","companyToken","status","lastActivityAt","pageUrl","conversationState","expiresAt"];for(const A of P)if(!(A in n))return console.error(`[SessionPersistence] Missing required field: ${A}`),clearSession(),null;const R=n;return isExpired(R)?(console.log("[SessionPersistence] Session expired, clearing"),clearSession(),null):(console.log("[SessionPersistence] Session loaded successfully"),R)}catch(T){return console.error("[SessionPersistence] Error loading session:",T),null}}function updateStatus(T){try{const n=loadSession();if(!n)return console.warn("[SessionPersistence] Cannot update status: no session found"),!1;n.status=T,n.lastActivityAt=Date.now();const{expiresAt:P,...R}=n;return saveSession(R)}catch(n){return console.error("[SessionPersistence] Error updating status:",n),!1}}function clearSession(){try{removeFromStorage(STORAGE_KEY),console.log("[SessionPersistence] Session cleared")}catch(T){console.error("[SessionPersistence] Error clearing session:",T)}}function hasValidSession(){try{return loadSession()!==null}catch(T){return console.error("[SessionPersistence] Error checking session validity:",T),!1}}const sessionPersistence=Object.freeze(Object.defineProperty({__proto__:null,CTA_SAME_TAB_REDIRECT_KEY,clearSession,hasValidSession,loadSession,saveSession,updateStatus},Symbol.toStringTag,{value:"Module"})),PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0";PACKET_TYPES.close="1";PACKET_TYPES.ping="2";PACKET_TYPES.pong="3";PACKET_TYPES.message="4";PACKET_TYPES.upgrade="5";PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(T=>{PACKET_TYPES_REVERSE[PACKET_TYPES[T]]=T});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",withNativeArrayBuffer$2=typeof ArrayBuffer=="function",isView$1=T=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(T):T&&T.buffer instanceof ArrayBuffer,encodePacket=({type:T,data:n},P,R)=>withNativeBlob$1&&n instanceof Blob?P?R(n):encodeBlobAsBase64(n,R):withNativeArrayBuffer$2&&(n instanceof ArrayBuffer||isView$1(n))?P?R(n):encodeBlobAsBase64(new Blob([n]),R):R(PACKET_TYPES[T]+(n||"")),encodeBlobAsBase64=(T,n)=>{const P=new FileReader;return P.onload=function(){const R=P.result.split(",")[1];n("b"+(R||""))},P.readAsDataURL(T)};function toArray(T){return T instanceof Uint8Array?T:T instanceof ArrayBuffer?new Uint8Array(T):new Uint8Array(T.buffer,T.byteOffset,T.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(T,n){if(withNativeBlob$1&&T.data instanceof Blob)return T.data.arrayBuffer().then(toArray).then(n);if(withNativeArrayBuffer$2&&(T.data instanceof ArrayBuffer||isView$1(T.data)))return n(toArray(T.data));encodePacket(T,!1,P=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),n(TEXT_ENCODER.encode(P))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let T=0;T<chars.length;T++)lookup$1[chars.charCodeAt(T)]=T;const decode$1=T=>{let n=T.length*.75,P=T.length,R,A=0,L,O,N,V;T[T.length-1]==="="&&(n--,T[T.length-2]==="="&&n--);const j=new ArrayBuffer(n),B=new Uint8Array(j);for(R=0;R<P;R+=4)L=lookup$1[T.charCodeAt(R)],O=lookup$1[T.charCodeAt(R+1)],N=lookup$1[T.charCodeAt(R+2)],V=lookup$1[T.charCodeAt(R+3)],B[A++]=L<<2|O>>4,B[A++]=(O&15)<<4|N>>2,B[A++]=(N&3)<<6|V&63;return j},withNativeArrayBuffer$1=typeof ArrayBuffer=="function",decodePacket=(T,n)=>{if(typeof T!="string")return{type:"message",data:mapBinary(T,n)};const P=T.charAt(0);return P==="b"?{type:"message",data:decodeBase64Packet(T.substring(1),n)}:PACKET_TYPES_REVERSE[P]?T.length>1?{type:PACKET_TYPES_REVERSE[P],data:T.substring(1)}:{type:PACKET_TYPES_REVERSE[P]}:ERROR_PACKET},decodeBase64Packet=(T,n)=>{if(withNativeArrayBuffer$1){const P=decode$1(T);return mapBinary(P,n)}else return{base64:!0,data:T}},mapBinary=(T,n)=>{switch(n){case"blob":return T instanceof Blob?T:new Blob([T]);case"arraybuffer":default:return T instanceof ArrayBuffer?T:T.buffer}},SEPARATOR="",encodePayload=(T,n)=>{const P=T.length,R=new Array(P);let A=0;T.forEach((L,O)=>{encodePacket(L,!1,N=>{R[O]=N,++A===P&&n(R.join(SEPARATOR))})})},decodePayload=(T,n)=>{const P=T.split(SEPARATOR),R=[];for(let A=0;A<P.length;A++){const L=decodePacket(P[A],n);if(R.push(L),L.type==="error")break}return R};function createPacketEncoderStream(){return new TransformStream({transform(T,n){encodePacketToBinary(T,P=>{const R=P.length;let A;if(R<126)A=new Uint8Array(1),new DataView(A.buffer).setUint8(0,R);else if(R<65536){A=new Uint8Array(3);const L=new DataView(A.buffer);L.setUint8(0,126),L.setUint16(1,R)}else{A=new Uint8Array(9);const L=new DataView(A.buffer);L.setUint8(0,127),L.setBigUint64(1,BigInt(R))}T.data&&typeof T.data!="string"&&(A[0]|=128),n.enqueue(A),n.enqueue(P)})}})}let TEXT_DECODER;function totalLength(T){return T.reduce((n,P)=>n+P.length,0)}function concatChunks(T,n){if(T[0].length===n)return T.shift();const P=new Uint8Array(n);let R=0;for(let A=0;A<n;A++)P[A]=T[0][R++],R===T[0].length&&(T.shift(),R=0);return T.length&&R<T[0].length&&(T[0]=T[0].slice(R)),P}function createPacketDecoderStream(T,n){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const P=[];let R=0,A=-1,L=!1;return new TransformStream({transform(O,N){for(P.push(O);;){if(R===0){if(totalLength(P)<1)break;const V=concatChunks(P,1);L=(V[0]&128)===128,A=V[0]&127,A<126?R=3:A===126?R=1:R=2}else if(R===1){if(totalLength(P)<2)break;const V=concatChunks(P,2);A=new DataView(V.buffer,V.byteOffset,V.length).getUint16(0),R=3}else if(R===2){if(totalLength(P)<8)break;const V=concatChunks(P,8),j=new DataView(V.buffer,V.byteOffset,V.length),B=j.getUint32(0);if(B>Math.pow(2,21)-1){N.enqueue(ERROR_PACKET);break}A=B*Math.pow(2,32)+j.getUint32(4),R=3}else{if(totalLength(P)<A)break;const V=concatChunks(P,A);N.enqueue(decodePacket(L?V:TEXT_DECODER.decode(V),n)),R=0}if(A===0||A>T){N.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(T){if(T)return mixin(T)}function mixin(T){for(var n in Emitter.prototype)T[n]=Emitter.prototype[n];return T}Emitter.prototype.on=Emitter.prototype.addEventListener=function(T,n){return this._callbacks=this._callbacks||{},(this._callbacks["$"+T]=this._callbacks["$"+T]||[]).push(n),this};Emitter.prototype.once=function(T,n){function P(){this.off(T,P),n.apply(this,arguments)}return P.fn=n,this.on(T,P),this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(T,n){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var P=this._callbacks["$"+T];if(!P)return this;if(arguments.length==1)return delete this._callbacks["$"+T],this;for(var R,A=0;A<P.length;A++)if(R=P[A],R===n||R.fn===n){P.splice(A,1);break}return P.length===0&&delete this._callbacks["$"+T],this};Emitter.prototype.emit=function(T){this._callbacks=this._callbacks||{};for(var n=new Array(arguments.length-1),P=this._callbacks["$"+T],R=1;R<arguments.length;R++)n[R-1]=arguments[R];if(P){P=P.slice(0);for(var R=0,A=P.length;R<A;++R)P[R].apply(this,n)}return this};Emitter.prototype.emitReserved=Emitter.prototype.emit;Emitter.prototype.listeners=function(T){return this._callbacks=this._callbacks||{},this._callbacks["$"+T]||[]};Emitter.prototype.hasListeners=function(T){return!!this.listeners(T).length};const nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?n=>Promise.resolve().then(n):(n,P)=>P(n,0),globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),defaultBinaryType="arraybuffer";function createCookieJar(){}function pick(T,...n){return n.reduce((P,R)=>(T.hasOwnProperty(R)&&(P[R]=T[R]),P),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(T,n){n.useNativeTimers?(T.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),T.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(T.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),T.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(T){return typeof T=="string"?utf8Length(T):Math.ceil((T.byteLength||T.size)*BASE64_OVERHEAD)}function utf8Length(T){let n=0,P=0;for(let R=0,A=T.length;R<A;R++)n=T.charCodeAt(R),n<128?P+=1:n<2048?P+=2:n<55296||n>=57344?P+=3:(R++,P+=4);return P}function randomString(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function encode(T){let n="";for(let P in T)T.hasOwnProperty(P)&&(n.length&&(n+="&"),n+=encodeURIComponent(P)+"="+encodeURIComponent(T[P]));return n}function decode(T){let n={},P=T.split("&");for(let R=0,A=P.length;R<A;R++){let L=P[R].split("=");n[decodeURIComponent(L[0])]=decodeURIComponent(L[1])}return n}class TransportError extends Error{constructor(n,P,R){super(n),this.description=P,this.context=R,this.type="TransportError"}}class Transport extends Emitter{constructor(n){super(),this.writable=!1,installTimerFunctions(this,n),this.opts=n,this.query=n.query,this.socket=n.socket,this.supportsBinary=!n.forceBase64}onError(n,P,R){return super.emitReserved("error",new TransportError(n,P,R)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(n){this.readyState==="open"&&this.write(n)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(n){const P=decodePacket(n,this.socket.binaryType);this.onPacket(P)}onPacket(n){super.emitReserved("packet",n)}onClose(n){this.readyState="closed",super.emitReserved("close",n)}pause(n){}createUri(n,P={}){return n+"://"+this._hostname()+this._port()+this.opts.path+this._query(P)}_hostname(){const n=this.opts.hostname;return n.indexOf(":")===-1?n:"["+n+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(n){const P=encode(n);return P.length?"?"+P:""}}class Polling extends Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(n){this.readyState="pausing";const P=()=>{this.readyState="paused",n()};if(this._polling||!this.writable){let R=0;this._polling&&(R++,this.once("pollComplete",function(){--R||P()})),this.writable||(R++,this.once("drain",function(){--R||P()}))}else P()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(n){const P=R=>{if(this.readyState==="opening"&&R.type==="open"&&this.onOpen(),R.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(R)};decodePayload(n,this.socket.binaryType).forEach(P),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const n=()=>{this.write([{type:"close"}])};this.readyState==="open"?n():this.once("open",n)}write(n){this.writable=!1,encodePayload(n,P=>{this.doWrite(P,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const n=this.opts.secure?"https":"http",P=this.query||{};return this.opts.timestampRequests!==!1&&(P[this.opts.timestampParam]=randomString()),!this.supportsBinary&&!P.sid&&(P.b64=1),this.createUri(n,P)}}let value=!1;try{value=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch(T){}const hasCORS=value;function empty(){}class BaseXHR extends Polling{constructor(n){if(super(n),typeof location<"u"){const P=location.protocol==="https:";let R=location.port;R||(R=P?"443":"80"),this.xd=typeof location<"u"&&n.hostname!==location.hostname||R!==n.port}}doWrite(n,P){const R=this.request({method:"POST",data:n});R.on("success",P),R.on("error",(A,L)=>{this.onError("xhr post error",A,L)})}doPoll(){const n=this.request();n.on("data",this.onData.bind(this)),n.on("error",(P,R)=>{this.onError("xhr poll error",P,R)}),this.pollXhr=n}}class Request extends Emitter{constructor(n,P,R){super(),this.createRequest=n,installTimerFunctions(this,R),this._opts=R,this._method=R.method||"GET",this._uri=P,this._data=R.data!==void 0?R.data:null,this._create()}_create(){var n;const P=pick(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");P.xdomain=!!this._opts.xd;const R=this._xhr=this.createRequest(P);try{R.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){R.setDisableHeaderCheck&&R.setDisableHeaderCheck(!0);for(let A in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(A)&&R.setRequestHeader(A,this._opts.extraHeaders[A])}}catch{}if(this._method==="POST")try{R.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{R.setRequestHeader("Accept","*/*")}catch{}(n=this._opts.cookieJar)===null||n===void 0||n.addCookies(R),"withCredentials"in R&&(R.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(R.timeout=this._opts.requestTimeout),R.onreadystatechange=()=>{var A;R.readyState===3&&((A=this._opts.cookieJar)===null||A===void 0||A.parseCookies(R.getResponseHeader("set-cookie"))),R.readyState===4&&(R.status===200||R.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof R.status=="number"?R.status:0)},0))},R.send(this._data)}catch(A){this.setTimeoutFn(()=>{this._onError(A)},0);return}typeof document<"u"&&(this._index=Request.requestsCount++,Request.requests[this._index]=this)}_onError(n){this.emitReserved("error",n,this._xhr),this._cleanup(!0)}_cleanup(n){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=empty,n)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Request.requests[this._index],this._xhr=null}}_onLoad(){const n=this._xhr.responseText;n!==null&&(this.emitReserved("data",n),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Request.requestsCount=0;Request.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",unloadHandler);else if(typeof addEventListener=="function"){const T="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(T,unloadHandler,!1)}}function unloadHandler(){for(let T in Request.requests)Request.requests.hasOwnProperty(T)&&Request.requests[T].abort()}const hasXHR2=(function(){const T=newRequest({xdomain:!1});return T&&T.responseType!==null})();class XHR extends BaseXHR{constructor(n){super(n);const P=n&&n.forceBase64;this.supportsBinary=hasXHR2&&!P}request(n={}){return Object.assign(n,{xd:this.xd},this.opts),new Request(newRequest,this.uri(),n)}}function newRequest(T){const n=T.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!n||hasCORS))return new XMLHttpRequest}catch{}if(!n)try{return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const isReactNative=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class BaseWS extends Transport{get name(){return"websocket"}doOpen(){const n=this.uri(),P=this.opts.protocols,R=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(R.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(n,P,R)}catch(A){return this.emitReserved("error",A)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=n=>this.onClose({description:"websocket connection closed",context:n}),this.ws.onmessage=n=>this.onData(n.data),this.ws.onerror=n=>this.onError("websocket error",n)}write(n){this.writable=!1;for(let P=0;P<n.length;P++){const R=n[P],A=P===n.length-1;encodePacket(R,this.supportsBinary,L=>{try{this.doWrite(R,L)}catch{}A&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const n=this.opts.secure?"wss":"ws",P=this.query||{};return this.opts.timestampRequests&&(P[this.opts.timestampParam]=randomString()),this.supportsBinary||(P.b64=1),this.createUri(n,P)}}const WebSocketCtor=globalThisShim.WebSocket||globalThisShim.MozWebSocket;class WS extends BaseWS{createSocket(n,P,R){return isReactNative?new WebSocketCtor(n,P,R):P?new WebSocketCtor(n,P):new WebSocketCtor(n)}doWrite(n,P){this.ws.send(P)}}class WT extends Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(n){return this.emitReserved("error",n)}this._transport.closed.then(()=>{this.onClose()}).catch(n=>{this.onError("webtransport error",n)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(n=>{const P=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),R=n.readable.pipeThrough(P).getReader(),A=createPacketEncoderStream();A.readable.pipeTo(n.writable),this._writer=A.writable.getWriter();const L=()=>{R.read().then(({done:N,value:V})=>{N||(this.onPacket(V),L())}).catch(N=>{})};L();const O={type:"open"};this.query.sid&&(O.data=`{"sid":"${this.query.sid}"}`),this._writer.write(O).then(()=>this.onOpen())})})}write(n){this.writable=!1;for(let P=0;P<n.length;P++){const R=n[P],A=P===n.length-1;this._writer.write(R).then(()=>{A&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var n;(n=this._transport)===null||n===void 0||n.close()}}const transports={websocket:WS,webtransport:WT,polling:XHR},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse(T){if(T.length>8e3)throw"URI too long";const n=T,P=T.indexOf("["),R=T.indexOf("]");P!=-1&&R!=-1&&(T=T.substring(0,P)+T.substring(P,R).replace(/:/g,";")+T.substring(R,T.length));let A=re.exec(T||""),L={},O=14;for(;O--;)L[parts[O]]=A[O]||"";return P!=-1&&R!=-1&&(L.source=n,L.host=L.host.substring(1,L.host.length-1).replace(/;/g,":"),L.authority=L.authority.replace("[","").replace("]","").replace(/;/g,":"),L.ipv6uri=!0),L.pathNames=pathNames(L,L.path),L.queryKey=queryKey(L,L.query),L}function pathNames(T,n){const P=/\/{2,9}/g,R=n.replace(P,"/").split("/");return(n.slice(0,1)=="/"||n.length===0)&&R.splice(0,1),n.slice(-1)=="/"&&R.splice(R.length-1,1),R}function queryKey(T,n){const P={};return n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(R,A,L){A&&(P[A]=L)}),P}const withEventListeners=typeof addEventListener=="function"&&typeof removeEventListener=="function",OFFLINE_EVENT_LISTENERS=[];withEventListeners&&addEventListener("offline",()=>{OFFLINE_EVENT_LISTENERS.forEach(T=>T())},!1);class SocketWithoutUpgrade extends Emitter{constructor(n,P){if(super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,n&&typeof n=="object"&&(P=n,n=null),n){const R=parse(n);P.hostname=R.host,P.secure=R.protocol==="https"||R.protocol==="wss",P.port=R.port,R.query&&(P.query=R.query)}else P.host&&(P.hostname=parse(P.host).host);installTimerFunctions(this,P),this.secure=P.secure!=null?P.secure:typeof location<"u"&&location.protocol==="https:",P.hostname&&!P.port&&(P.port=this.secure?"443":"80"),this.hostname=P.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=P.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},P.transports.forEach(R=>{const A=R.prototype.name;this.transports.push(A),this._transportsByName[A]=R}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},P),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=decode(this.opts.query)),withEventListeners&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(n){const P=Object.assign({},this.opts.query);P.EIO=protocol$1,P.transport=n,this.id&&(P.sid=this.id);const R=Object.assign({},this.opts,{query:P,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[n]);return new this._transportsByName[n](R)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const n=this.opts.rememberUpgrade&&SocketWithoutUpgrade.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const P=this.createTransport(n);P.open(),this.setTransport(P)}setTransport(n){this.transport&&this.transport.removeAllListeners(),this.transport=n,n.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",P=>this._onClose("transport close",P))}onOpen(){this.readyState="open",SocketWithoutUpgrade.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",n),this.emitReserved("heartbeat"),n.type){case"open":this.onHandshake(JSON.parse(n.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const P=new Error("server error");P.code=n.data,this._onError(P);break;case"message":this.emitReserved("data",n.data),this.emitReserved("message",n.data);break}}onHandshake(n){this.emitReserved("handshake",n),this.id=n.sid,this.transport.query.sid=n.sid,this._pingInterval=n.pingInterval,this._pingTimeout=n.pingTimeout,this._maxPayload=n.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const n=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+n,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},n),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const n=this._getWritablePackets();this.transport.send(n),this._prevBufferLen=n.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let P=1;for(let R=0;R<this.writeBuffer.length;R++){const A=this.writeBuffer[R].data;if(A&&(P+=byteLength(A)),R>0&&P>this._maxPayload)return this.writeBuffer.slice(0,R);P+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const n=Date.now()>this._pingTimeoutTime;return n&&(this._pingTimeoutTime=0,nextTick(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),n}write(n,P,R){return this._sendPacket("message",n,P,R),this}send(n,P,R){return this._sendPacket("message",n,P,R),this}_sendPacket(n,P,R,A){if(typeof P=="function"&&(A=P,P=void 0),typeof R=="function"&&(A=R,R=null),this.readyState==="closing"||this.readyState==="closed")return;R=R||{},R.compress=R.compress!==!1;const L={type:n,data:P,options:R};this.emitReserved("packetCreate",L),this.writeBuffer.push(L),A&&this.once("flush",A),this.flush()}close(){const n=()=>{this._onClose("forced close"),this.transport.close()},P=()=>{this.off("upgrade",P),this.off("upgradeError",P),n()},R=()=>{this.once("upgrade",P),this.once("upgradeError",P)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?R():n()}):this.upgrading?R():n()),this}_onError(n){if(SocketWithoutUpgrade.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",n),this._onClose("transport error",n)}_onClose(n,P){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),withEventListeners&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const R=OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);R!==-1&&OFFLINE_EVENT_LISTENERS.splice(R,1)}this.readyState="closed",this.id=null,this.emitReserved("close",n,P),this.writeBuffer=[],this._prevBufferLen=0}}}SocketWithoutUpgrade.protocol=protocol$1;class SocketWithUpgrade extends SocketWithoutUpgrade{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let n=0;n<this._upgrades.length;n++)this._probe(this._upgrades[n])}_probe(n){let P=this.createTransport(n),R=!1;SocketWithoutUpgrade.priorWebsocketSuccess=!1;const A=()=>{R||(P.send([{type:"ping",data:"probe"}]),P.once("packet",z=>{if(!R)if(z.type==="pong"&&z.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",P),!P)return;SocketWithoutUpgrade.priorWebsocketSuccess=P.name==="websocket",this.transport.pause(()=>{R||this.readyState!=="closed"&&(B(),this.setTransport(P),P.send([{type:"upgrade"}]),this.emitReserved("upgrade",P),P=null,this.upgrading=!1,this.flush())})}else{const W=new Error("probe error");W.transport=P.name,this.emitReserved("upgradeError",W)}}))};function L(){R||(R=!0,B(),P.close(),P=null)}const O=z=>{const W=new Error("probe error: "+z);W.transport=P.name,L(),this.emitReserved("upgradeError",W)};function N(){O("transport closed")}function V(){O("socket closed")}function j(z){P&&z.name!==P.name&&L()}const B=()=>{P.removeListener("open",A),P.removeListener("error",O),P.removeListener("close",N),this.off("close",V),this.off("upgrading",j)};P.once("open",A),P.once("error",O),P.once("close",N),this.once("close",V),this.once("upgrading",j),this._upgrades.indexOf("webtransport")!==-1&&n!=="webtransport"?this.setTimeoutFn(()=>{R||P.open()},200):P.open()}onHandshake(n){this._upgrades=this._filterUpgrades(n.upgrades),super.onHandshake(n)}_filterUpgrades(n){const P=[];for(let R=0;R<n.length;R++)~this.transports.indexOf(n[R])&&P.push(n[R]);return P}}let Socket$1=class extends SocketWithUpgrade{constructor(n,P={}){const R=typeof n=="object"?n:P;(!R.transports||R.transports&&typeof R.transports[0]=="string")&&(R.transports=(R.transports||["polling","websocket","webtransport"]).map(A=>transports[A]).filter(A=>!!A)),super(n,R)}};function url(T,n="",P){let R=T;P=P||typeof location<"u"&&location,T==null&&(T=P.protocol+"//"+P.host),typeof T=="string"&&(T.charAt(0)==="/"&&(T.charAt(1)==="/"?T=P.protocol+T:T=P.host+T),/^(https?|wss?):\/\//.test(T)||(typeof P<"u"?T=P.protocol+"//"+T:T="https://"+T),R=parse(T)),R.port||(/^(http|ws)$/.test(R.protocol)?R.port="80":/^(http|ws)s$/.test(R.protocol)&&(R.port="443")),R.path=R.path||"/";const L=R.host.indexOf(":")!==-1?"["+R.host+"]":R.host;return R.id=R.protocol+"://"+L+":"+R.port+n,R.href=R.protocol+"://"+L+(P&&P.port===R.port?"":":"+R.port),R}const withNativeArrayBuffer=typeof ArrayBuffer=="function",isView=T=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(T):T.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob=typeof Blob=="function"||typeof Blob<"u"&&toString.call(Blob)==="[object BlobConstructor]",withNativeFile=typeof File=="function"||typeof File<"u"&&toString.call(File)==="[object FileConstructor]";function isBinary(T){return withNativeArrayBuffer&&(T instanceof ArrayBuffer||isView(T))||withNativeBlob&&T instanceof Blob||withNativeFile&&T instanceof File}function hasBinary(T,n){if(!T||typeof T!="object")return!1;if(Array.isArray(T)){for(let P=0,R=T.length;P<R;P++)if(hasBinary(T[P]))return!0;return!1}if(isBinary(T))return!0;if(T.toJSON&&typeof T.toJSON=="function"&&arguments.length===1)return hasBinary(T.toJSON(),!0);for(const P in T)if(Object.prototype.hasOwnProperty.call(T,P)&&hasBinary(T[P]))return!0;return!1}function deconstructPacket(T){const n=[],P=T.data,R=T;return R.data=_deconstructPacket(P,n),R.attachments=n.length,{packet:R,buffers:n}}function _deconstructPacket(T,n){if(!T)return T;if(isBinary(T)){const P={_placeholder:!0,num:n.length};return n.push(T),P}else if(Array.isArray(T)){const P=new Array(T.length);for(let R=0;R<T.length;R++)P[R]=_deconstructPacket(T[R],n);return P}else if(typeof T=="object"&&!(T instanceof Date)){const P={};for(const R in T)Object.prototype.hasOwnProperty.call(T,R)&&(P[R]=_deconstructPacket(T[R],n));return P}return T}function reconstructPacket(T,n){return T.data=_reconstructPacket(T.data,n),delete T.attachments,T}function _reconstructPacket(T,n){if(!T)return T;if(T&&T._placeholder===!0){if(typeof T.num=="number"&&T.num>=0&&T.num<n.length)return n[T.num];throw new Error("illegal attachments")}else if(Array.isArray(T))for(let P=0;P<T.length;P++)T[P]=_reconstructPacket(T[P],n);else if(typeof T=="object")for(const P in T)Object.prototype.hasOwnProperty.call(T,P)&&(T[P]=_reconstructPacket(T[P],n));return T}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;(function(T){T[T.CONNECT=0]="CONNECT",T[T.DISCONNECT=1]="DISCONNECT",T[T.EVENT=2]="EVENT",T[T.ACK=3]="ACK",T[T.CONNECT_ERROR=4]="CONNECT_ERROR",T[T.BINARY_EVENT=5]="BINARY_EVENT",T[T.BINARY_ACK=6]="BINARY_ACK"})(PacketType||(PacketType={}));class Encoder{constructor(n){this.replacer=n}encode(n){return(n.type===PacketType.EVENT||n.type===PacketType.ACK)&&hasBinary(n)?this.encodeAsBinary({type:n.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id}):[this.encodeAsString(n)]}encodeAsString(n){let P=""+n.type;return(n.type===PacketType.BINARY_EVENT||n.type===PacketType.BINARY_ACK)&&(P+=n.attachments+"-"),n.nsp&&n.nsp!=="/"&&(P+=n.nsp+","),n.id!=null&&(P+=n.id),n.data!=null&&(P+=JSON.stringify(n.data,this.replacer)),P}encodeAsBinary(n){const P=deconstructPacket(n),R=this.encodeAsString(P.packet),A=P.buffers;return A.unshift(R),A}}function isObject(T){return Object.prototype.toString.call(T)==="[object Object]"}class Decoder extends Emitter{constructor(n){super(),this.reviver=n}add(n){let P;if(typeof n=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");P=this.decodeString(n);const R=P.type===PacketType.BINARY_EVENT;R||P.type===PacketType.BINARY_ACK?(P.type=R?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(P),P.attachments===0&&super.emitReserved("decoded",P)):super.emitReserved("decoded",P)}else if(isBinary(n)||n.base64)if(this.reconstructor)P=this.reconstructor.takeBinaryData(n),P&&(this.reconstructor=null,super.emitReserved("decoded",P));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+n)}decodeString(n){let P=0;const R={type:Number(n.charAt(0))};if(PacketType[R.type]===void 0)throw new Error("unknown packet type "+R.type);if(R.type===PacketType.BINARY_EVENT||R.type===PacketType.BINARY_ACK){const L=P+1;for(;n.charAt(++P)!=="-"&&P!=n.length;);const O=n.substring(L,P);if(O!=Number(O)||n.charAt(P)!=="-")throw new Error("Illegal attachments");R.attachments=Number(O)}if(n.charAt(P+1)==="/"){const L=P+1;for(;++P&&!(n.charAt(P)===","||P===n.length););R.nsp=n.substring(L,P)}else R.nsp="/";const A=n.charAt(P+1);if(A!==""&&Number(A)==A){const L=P+1;for(;++P;){const O=n.charAt(P);if(O==null||Number(O)!=O){--P;break}if(P===n.length)break}R.id=Number(n.substring(L,P+1))}if(n.charAt(++P)){const L=this.tryParse(n.substr(P));if(Decoder.isPayloadValid(R.type,L))R.data=L;else throw new Error("invalid payload")}return R}tryParse(n){try{return JSON.parse(n,this.reviver)}catch{return!1}}static isPayloadValid(n,P){switch(n){case PacketType.CONNECT:return isObject(P);case PacketType.DISCONNECT:return P===void 0;case PacketType.CONNECT_ERROR:return typeof P=="string"||isObject(P);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(P)&&(typeof P[0]=="number"||typeof P[0]=="string"&&RESERVED_EVENTS$1.indexOf(P[0])===-1);case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(P)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(n){this.packet=n,this.buffers=[],this.reconPack=n}takeBinaryData(n){if(this.buffers.push(n),this.buffers.length===this.reconPack.attachments){const P=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),P}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const parser=Object.freeze(Object.defineProperty({__proto__:null,Decoder,Encoder,get PacketType(){return PacketType},protocol},Symbol.toStringTag,{value:"Module"}));function on(T,n,P){return T.on(n,P),function(){T.off(n,P)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(n,P,R){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=n,this.nsp=P,R&&R.auth&&(this.auth=R.auth),this._opts=Object.assign({},R),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const n=this.io;this.subs=[on(n,"open",this.onopen.bind(this)),on(n,"packet",this.onpacket.bind(this)),on(n,"error",this.onerror.bind(this)),on(n,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...n){return n.unshift("message"),this.emit.apply(this,n),this}emit(n,...P){var R,A,L;if(RESERVED_EVENTS.hasOwnProperty(n))throw new Error('"'+n.toString()+'" is a reserved event name');if(P.unshift(n),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(P),this;const O={type:PacketType.EVENT,data:P};if(O.options={},O.options.compress=this.flags.compress!==!1,typeof P[P.length-1]=="function"){const B=this.ids++,z=P.pop();this._registerAckCallback(B,z),O.id=B}const N=(A=(R=this.io.engine)===null||R===void 0?void 0:R.transport)===null||A===void 0?void 0:A.writable,V=this.connected&&!(!((L=this.io.engine)===null||L===void 0)&&L._hasPingExpired());return this.flags.volatile&&!N||(V?(this.notifyOutgoingListeners(O),this.packet(O)):this.sendBuffer.push(O)),this.flags={},this}_registerAckCallback(n,P){var R;const A=(R=this.flags.timeout)!==null&&R!==void 0?R:this._opts.ackTimeout;if(A===void 0){this.acks[n]=P;return}const L=this.io.setTimeoutFn(()=>{delete this.acks[n];for(let N=0;N<this.sendBuffer.length;N++)this.sendBuffer[N].id===n&&this.sendBuffer.splice(N,1);P.call(this,new Error("operation has timed out"))},A),O=(...N)=>{this.io.clearTimeoutFn(L),P.apply(this,N)};O.withError=!0,this.acks[n]=O}emitWithAck(n,...P){return new Promise((R,A)=>{const L=(O,N)=>O?A(O):R(N);L.withError=!0,P.push(L),this.emit(n,...P)})}_addToQueue(n){let P;typeof n[n.length-1]=="function"&&(P=n.pop());const R={id:this._queueSeq++,tryCount:0,pending:!1,args:n,flags:Object.assign({fromQueue:!0},this.flags)};n.push((A,...L)=>R!==this._queue[0]?void 0:(A!==null?R.tryCount>this._opts.retries&&(this._queue.shift(),P&&P(A)):(this._queue.shift(),P&&P(null,...L)),R.pending=!1,this._drainQueue())),this._queue.push(R),this._drainQueue()}_drainQueue(n=!1){if(!this.connected||this._queue.length===0)return;const P=this._queue[0];P.pending&&!n||(P.pending=!0,P.tryCount++,this.flags=P.flags,this.emit.apply(this,P.args))}packet(n){n.nsp=this.nsp,this.io._packet(n)}onopen(){typeof this.auth=="function"?this.auth(n=>{this._sendConnectPacket(n)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(n){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},n):n})}onerror(n){this.connected||this.emitReserved("connect_error",n)}onclose(n,P){this.connected=!1,delete this.id,this.emitReserved("disconnect",n,P),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(n=>{if(!this.sendBuffer.some(R=>String(R.id)===n)){const R=this.acks[n];delete this.acks[n],R.withError&&R.call(this,new Error("socket has been disconnected"))}})}onpacket(n){if(n.nsp===this.nsp)switch(n.type){case PacketType.CONNECT:n.data&&n.data.sid?this.onconnect(n.data.sid,n.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(n);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(n);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const R=new Error(n.data.message);R.data=n.data.data,this.emitReserved("connect_error",R);break}}onevent(n){const P=n.data||[];n.id!=null&&P.push(this.ack(n.id)),this.connected?this.emitEvent(P):this.receiveBuffer.push(Object.freeze(P))}emitEvent(n){if(this._anyListeners&&this._anyListeners.length){const P=this._anyListeners.slice();for(const R of P)R.apply(this,n)}super.emit.apply(this,n),this._pid&&n.length&&typeof n[n.length-1]=="string"&&(this._lastOffset=n[n.length-1])}ack(n){const P=this;let R=!1;return function(...A){R||(R=!0,P.packet({type:PacketType.ACK,id:n,data:A}))}}onack(n){const P=this.acks[n.id];typeof P=="function"&&(delete this.acks[n.id],P.withError&&n.data.unshift(null),P.apply(this,n.data))}onconnect(n,P){this.id=n,this.recovered=P&&this._pid===P,this._pid=P,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(n=>this.emitEvent(n)),this.receiveBuffer=[],this.sendBuffer.forEach(n=>{this.notifyOutgoingListeners(n),this.packet(n)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(n=>n()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(n){return this.flags.compress=n,this}get volatile(){return this.flags.volatile=!0,this}timeout(n){return this.flags.timeout=n,this}onAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(n),this}prependAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(n),this}offAny(n){if(!this._anyListeners)return this;if(n){const P=this._anyListeners;for(let R=0;R<P.length;R++)if(n===P[R])return P.splice(R,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(n),this}prependAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(n),this}offAnyOutgoing(n){if(!this._anyOutgoingListeners)return this;if(n){const P=this._anyOutgoingListeners;for(let R=0;R<P.length;R++)if(n===P[R])return P.splice(R,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(n){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const P=this._anyOutgoingListeners.slice();for(const R of P)R.apply(this,n.data)}}}function Backoff(T){T=T||{},this.ms=T.min||100,this.max=T.max||1e4,this.factor=T.factor||2,this.jitter=T.jitter>0&&T.jitter<=1?T.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var T=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var n=Math.random(),P=Math.floor(n*this.jitter*T);T=(Math.floor(n*10)&1)==0?T-P:T+P}return Math.min(T,this.max)|0};Backoff.prototype.reset=function(){this.attempts=0};Backoff.prototype.setMin=function(T){this.ms=T};Backoff.prototype.setMax=function(T){this.max=T};Backoff.prototype.setJitter=function(T){this.jitter=T};class Manager extends Emitter{constructor(n,P){var R;super(),this.nsps={},this.subs=[],n&&typeof n=="object"&&(P=n,n=void 0),P=P||{},P.path=P.path||"/socket.io",this.opts=P,installTimerFunctions(this,P),this.reconnection(P.reconnection!==!1),this.reconnectionAttempts(P.reconnectionAttempts||1/0),this.reconnectionDelay(P.reconnectionDelay||1e3),this.reconnectionDelayMax(P.reconnectionDelayMax||5e3),this.randomizationFactor((R=P.randomizationFactor)!==null&&R!==void 0?R:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(P.timeout==null?2e4:P.timeout),this._readyState="closed",this.uri=n;const A=P.parser||parser;this.encoder=new A.Encoder,this.decoder=new A.Decoder,this._autoConnect=P.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(n){return arguments.length?(this._reconnection=!!n,n||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(n){return n===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=n,this)}reconnectionDelay(n){var P;return n===void 0?this._reconnectionDelay:(this._reconnectionDelay=n,(P=this.backoff)===null||P===void 0||P.setMin(n),this)}randomizationFactor(n){var P;return n===void 0?this._randomizationFactor:(this._randomizationFactor=n,(P=this.backoff)===null||P===void 0||P.setJitter(n),this)}reconnectionDelayMax(n){var P;return n===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=n,(P=this.backoff)===null||P===void 0||P.setMax(n),this)}timeout(n){return arguments.length?(this._timeout=n,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(n){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const P=this.engine,R=this;this._readyState="opening",this.skipReconnect=!1;const A=on(P,"open",function(){R.onopen(),n&&n()}),L=N=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",N),n?n(N):this.maybeReconnectOnOpen()},O=on(P,"error",L);if(this._timeout!==!1){const N=this._timeout,V=this.setTimeoutFn(()=>{A(),L(new Error("timeout")),P.close()},N);this.opts.autoUnref&&V.unref(),this.subs.push(()=>{this.clearTimeoutFn(V)})}return this.subs.push(A),this.subs.push(O),this}connect(n){return this.open(n)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const n=this.engine;this.subs.push(on(n,"ping",this.onping.bind(this)),on(n,"data",this.ondata.bind(this)),on(n,"error",this.onerror.bind(this)),on(n,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(n){try{this.decoder.add(n)}catch(P){this.onclose("parse error",P)}}ondecoded(n){nextTick(()=>{this.emitReserved("packet",n)},this.setTimeoutFn)}onerror(n){this.emitReserved("error",n)}socket(n,P){let R=this.nsps[n];return R?this._autoConnect&&!R.active&&R.connect():(R=new Socket(this,n,P),this.nsps[n]=R),R}_destroy(n){const P=Object.keys(this.nsps);for(const R of P)if(this.nsps[R].active)return;this._close()}_packet(n){const P=this.encoder.encode(n);for(let R=0;R<P.length;R++)this.engine.write(P[R],n.options)}cleanup(){this.subs.forEach(n=>n()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(n,P){var R;this.cleanup(),(R=this.engine)===null||R===void 0||R.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",n,P),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const n=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const P=this.backoff.duration();this._reconnecting=!0;const R=this.setTimeoutFn(()=>{n.skipReconnect||(this.emitReserved("reconnect_attempt",n.backoff.attempts),!n.skipReconnect&&n.open(A=>{A?(n._reconnecting=!1,n.reconnect(),this.emitReserved("reconnect_error",A)):n.onreconnect()}))},P);this.opts.autoUnref&&R.unref(),this.subs.push(()=>{this.clearTimeoutFn(R)})}}onreconnect(){const n=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",n)}}const cache={};function lookup(T,n){typeof T=="object"&&(n=T,T=void 0),n=n||{};const P=url(T,n.path||"/socket.io"),R=P.source,A=P.id,L=P.path,O=cache[A]&&L in cache[A].nsps,N=n.forceNew||n["force new connection"]||n.multiplex===!1||O;let V;return N?V=new Manager(R,n):(cache[A]||(cache[A]=new Manager(R,n)),V=cache[A]),P.query&&!n.query&&(n.query=P.queryKey),V.socket(P.path,n)}Object.assign(lookup,{Manager,Socket,io:lookup,connect:lookup});let socket=null,authToken=null,currentSessionId=null,reconnectAttempts=0;const MAX_RECONNECT_ATTEMPTS=10,BASE_RECONNECT_DELAY=1e3,initializeSocket=(T,n)=>{if(socket&&socket.connected)return console.log("[SocketService] Socket already connected"),socket;currentSessionId=T,authToken=n;const P=getCurrentBackendUrl();return socket=lookup(P,{path:"/socket.io/",transports:["websocket","polling"],reconnection:!0,reconnectionDelay:BASE_RECONNECT_DELAY,reconnectionDelayMax:1e4,reconnectionAttempts:MAX_RECONNECT_ATTEMPTS,timeout:2e4,autoConnect:!0,upgrade:!0}),socket.on("connect",()=>{console.log("[SocketService] Connected to server"),reconnectAttempts=0,authenticateSocket()}),socket.on("authenticated",R=>{console.log("[SocketService] Authenticated successfully",R),currentSessionId?(console.log("[SocketService] Emitting join_session for:",currentSessionId),socket?.emit("join_session",{session_id:currentSessionId}),console.log("[SocketService] join_session emitted")):console.warn("[SocketService] No currentSessionId, cannot join session room")}),socket.on("auth_error",R=>{console.error("[SocketService] Authentication failed:",R)}),socket.on("auth_required",R=>{console.warn("[SocketService] Authentication required:",R),authenticateSocket()}),socket.on("joined",R=>{console.log("[SocketService] Joined session room:",R.session_id)}),socket.on("disconnect",R=>{console.log("[SocketService] Disconnected:",R),R==="io server disconnect"&&socket?.connect()}),socket.on("connect_error",R=>{reconnectAttempts++;const A=Math.min(BASE_RECONNECT_DELAY*Math.pow(2,reconnectAttempts),1e4);console.error(`[SocketService] Connection error (attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS}):`,R.message),console.log(`[SocketService] Retrying in ${A}ms...`),reconnectAttempts>=MAX_RECONNECT_ATTEMPTS&&console.error("[SocketService] Max reconnection attempts reached")}),socket.on("reconnect_attempt",R=>{console.log(`[SocketService] Reconnection attempt ${R}`)}),socket.on("reconnect",R=>{console.log(`[SocketService] Reconnected after ${R} attempts`),reconnectAttempts=0,authenticateSocket()}),socket.on("reconnect_failed",()=>{console.error("[SocketService] Reconnection failed after all attempts")}),socket.on("pong",()=>{console.debug("[SocketService] Pong received")}),socket.on("agent_message",R=>{console.log("[SocketService] Agent message received:",R);const A=new CustomEvent("agent_message",{detail:R});window.dispatchEvent(A)}),socket.on("agent_response",R=>{console.log("[SocketService] Agent response received:",R);const A=new CustomEvent("agent_response",{detail:R});window.dispatchEvent(A)}),socket},authenticateSocket=()=>{if(!socket||!authToken){console.warn("[SocketService] Cannot authenticate: missing socket or token");return}console.log("[SocketService] Authenticating..."),socket.emit("authenticate",{token:authToken})},getSocket=()=>socket,useWidgetStore=({companyToken:T,agentId:n,analyticsService:P,mode:R="floating",initialExpanded:A=!1})=>{const[L,O]=React.useState(A),[N,V]=React.useState(!1),[j,B]=React.useState(!1),[z,W]=React.useState(null),[q,H]=React.useState(null),[$,Q]=React.useState(null),[U,J]=React.useState(null),[G,K]=React.useState(!1),[Y,Z]=React.useState(!1),[ie,se]=React.useState("voice"),[le,pe]=React.useState(0),[ue,he]=React.useState([]),[ve,be]=React.useState(""),[fe,ne]=React.useState(!1),[ce,ee]=React.useState(null),[te,oe]=React.useState(null),[ae,de]=React.useState(null),[ge,ye]=React.useState(!1),[Ee,Pe]=React.useState(!1),[Ie,Ae]=React.useState(!1),[Le,Me]=React.useState(!1),[ke,Ce]=React.useState(!1),[xe,we]=React.useState("active"),[Oe,De]=React.useState(!1),[We,Fe]=React.useState("idle"),[qe,Ne]=React.useState(void 0),[je,Ye]=React.useState(!1),[Xe,ze]=React.useState(!1),[Qe,Ge]=React.useState("form_active"),[et,nt]=React.useState(!1);React.useEffect(()=>{console.log("[WidgetStoreV2] 📋 hasActiveForm changed to:",je)},[je]),React.useEffect(()=>{const me=Se=>{const _e=(Se?.detail??{}).force_display??!1;console.log("[WidgetStoreV2] 📧 show_email_form event received from agent",{force_display:_e}),Me(!0),Ce(_e)};return window.addEventListener("show_email_form",me),()=>window.removeEventListener("show_email_form",me)},[]);const Ze=React.useRef(null),tt=React.useRef(null),st=React.useRef(!1),ht=React.useRef(!1),pt=React.useRef(!1),ot=React.useRef(null),kt=React.useRef(0),Rt=1e3,ft=React.useRef(!1),At=React.useCallback(()=>{W(null)},[]),ut=React.useCallback(me=>{W(me)},[]),at=React.useCallback(me=>{J(me),me&&P?.setJwt(me)},[P]),mt=React.useCallback(me=>{he(Se=>[...Se,me])},[]),St=React.useCallback(async()=>{if(n){B(!0),W(null);try{const me=await fetch(buildApiUrl(`api/widget/bootstrap?agent_id=${n}`),{method:"GET",headers:{"Content-Type":"application/json"}});if(!me.ok)throw new Error("Failed to get bootstrap JWT");const{access_token:Se}=await me.json();at(Se);const Re=await fetch(buildApiUrl(`api/widget/session/agent-config/${n}`),{method:"GET",headers:{Authorization:`Bearer ${Se}`,"Content-Type":"application/json"}});if(!Re.ok)throw new Error(`Failed to load agent: ${Re.statusText}`);const _e=await Re.json();oe(_e),console.log("[WidgetStoreV2] ✅ Agent loaded:",_e.name),console.log("[WidgetStoreV2] 🔍 Agent data details:",{id:_e.id,name:_e.name,agent_instructions:_e.agent_instructions,agent_first_message:_e.agent_first_message,require_email:_e.require_email,company_id:_e.company_id,allKeys:Object.keys(_e)}),console.log("[WidgetStoreV2] 📧 EMAIL CAPTURE DEBUG:",{require_email_value:_e.require_email,require_email_type:typeof _e.require_email,require_email_stringify:JSON.stringify(_e.require_email),is_truthy:!!_e.require_email,is_exactly_true:_e.require_email===!0,is_exactly_false:_e.require_email===!1,is_null_or_undefined:_e.require_email==null,all_agent_keys:Object.keys(_e),timestamp:new Date().toISOString()})}catch(me){console.error("[WidgetStoreV2] ❌ Failed to load agent:",me);const Se=me instanceof Error?me.message:"Unknown error";console.error("[WidgetStoreV2] ❌ Error details:",{message:Se,error:me,companyToken:T,agentId:n}),W(`Failed to load agent: ${Se}`)}finally{B(!1)}}},[T,n]),ct=React.useCallback(async()=>{if(n)try{if(console.log("[WidgetStoreV2] 🎨 Loading custom CTA..."),console.log("[WidgetStoreV2] 🎨 CTA request details:",{url:buildApiUrl(`api/widget/custom-cta/${n}`),companyToken:T?"present":"missing",agentId:n,hasJwt:!!(U||$)}),!U&&!$){console.warn("[WidgetStoreV2] ⚠️ No JWT token available for CTA authentication, skipping...");return}const me=new AbortController,Se=setTimeout(()=>me.abort(),5e3),Re=await fetch(buildApiUrl(`api/widget/custom-cta/${n}`),{method:"GET",headers:{Authorization:`Bearer ${U||$}`,"Content-Type":"application/json"},signal:me.signal});if(clearTimeout(Se),console.log("[WidgetStoreV2] 🎨 CTA response status:",Re.status,Re.statusText),console.log("[WidgetStoreV2] 🎨 CTA response headers:",Object.fromEntries(Re.headers.entries())),Re.ok){const _e=await Re.json(),Be=_e.has_cta&&_e.cta?_e.cta:null;de(Be),console.log("[WidgetStoreV2] ✅ Custom CTA loaded:",Be?.button_text??"none")}else{console.warn("[WidgetStoreV2] ⚠️ Custom CTA endpoint returned status:",Re.status,Re.statusText);try{const _e=await Re.text();console.warn("[WidgetStoreV2] ⚠️ CTA error response body:",_e)}catch{console.warn("[WidgetStoreV2] ⚠️ Could not read CTA error response body")}}}catch(me){me instanceof Error&&me.name==="AbortError"?console.warn("[WidgetStoreV2] ⚠️ Custom CTA request timed out (non-blocking)"):console.warn("[WidgetStoreV2] ⚠️ Failed to load custom CTA (non-blocking):",me)}},[T,n,U,$]),wt=React.useCallback(async()=>{if(!n)return;let me=U||$;if(!me)try{const Se=await fetch(buildApiUrl(`api/widget/bootstrap?agent_id=${n}`),{method:"GET",headers:{"Content-Type":"application/json"}});if(!Se.ok)return;me=(await Se.json()).access_token,at(me)}catch{return}try{const Se=await fetch(buildApiUrl(`api/widget/session/agent-config/${n}`),{method:"GET",headers:{Authorization:`Bearer ${me}`,"Content-Type":"application/json"}});if(!Se.ok)return;const Re=await Se.json();oe(Re),Re.require_email===!1&&(Me(!1),Ce(!1)),console.log("[WidgetStoreV2] ✅ Agent config refreshed (real-time):",{require_email:Re.require_email})}catch(Se){console.warn("[WidgetStoreV2] ⚠️ Failed to refresh agent config:",Se)}},[T,n,U,$]);React.useEffect(()=>{const me=Se=>{(Se?.detail??{}).agentId===n&&(wt(),ct())};return window.addEventListener("wysdym-agent-config-updated",me),()=>window.removeEventListener("wysdym-agent-config-updated",me)},[n,wt,ct]);const _t=$||U||"",Te=useVoiceSessionV2({agent:te,agentId:n,sessionId:q||"",jwt:_t,messages:ue,setMessages:he,onError:ut,customCta:ae,companyToken:T}),rt=useTextSessionV2({agent:te,agentId:n,sessionId:q||"",jwt:_t,messages:ue,setMessages:he,onError:ut}),gt=React.useCallback(async()=>{if(console.log("[WidgetStoreV2] 🚀 startDirectSession called with:",{companyToken:T,agentId:n}),!n){console.error("[WidgetStoreV2] ❌ Missing required agentId");return}console.log("[WidgetStoreV2] ⏳ Starting direct session..."),B(!0);try{console.log("[WidgetStoreV2] 📡 Fetching bootstrap JWT...");const me=await fetch(buildApiUrl(`api/widget/bootstrap?agent_id=${n}`),{method:"GET",headers:{"Content-Type":"application/json"}});if(!me.ok)throw console.error("[WidgetStoreV2] ❌ Bootstrap response failed:",me.status,me.statusText),new Error("Failed to get bootstrap JWT");const{access_token:Se}=await me.json();console.log("[WidgetStoreV2] ✅ Got bootstrap JWT"),at(Se);try{const $e=await fetch(buildApiUrl(`api/widget/session/agent-config/${n}`),{method:"GET",headers:{Authorization:`Bearer ${Se}`,"Content-Type":"application/json"}});if($e.ok){const Ke=await $e.json();oe(Ke),console.log("[WidgetStoreV2] ✅ Agent config refreshed for session:",{require_email:Ke.require_email})}}catch($e){console.warn("[WidgetStoreV2] ⚠️ Failed to refresh agent config, using cached:",$e)}const Re=P?await P.getAnonymousUserId():typeof localStorage<"u"?localStorage.getItem(`wysdym_anonymous_user_${T}`):null;console.log("[WidgetStoreV2] 📡 Creating session via intake...",{anonymousUserId:Re?`${Re.slice(0,8)}...`:null});const _e=await fetch(buildApiUrl("api/widget/session/intake"),{method:"POST",headers:{Authorization:`Bearer ${Se}`,"Content-Type":"application/json"},body:JSON.stringify({company_token:T,agent_id:n,email:null,anonymous_user_id:Re||void 0})});if(!_e.ok)throw console.error("[WidgetStoreV2] ❌ Intake response failed:",_e.status,_e.statusText),new Error(`Failed to create session: ${_e.statusText}`);const Be=await _e.json(),{session_id:Ve,widget_jwt:Ue,has_email:Je}=Be;console.log("[WidgetStoreV2] ✅ Got session data:",{session_id:Ve,hasJwt:!!Ue,has_email:Je}),H(Ve),Q(Ue),Z(!0),K(!1),Ae(!!Je),console.log("[WidgetStoreV2] 🔌 Initializing socket for session:",Ve),initializeSocket(Ve,Ue),console.log("[WidgetStoreV2] ✅ Direct session started:",Ve),console.log("[WidgetStoreV2] ⏳ Voice session will start automatically...")}catch(me){console.error("[WidgetStoreV2] ❌ Failed to start direct session:",me),W(`Failed to start session: ${me instanceof Error?me.message:"Unknown error"}`),B(!1)}},[T,n,R,P]),It=React.useCallback(async me=>{const Se=$||U,Re=q&&$;if(console.log("[WidgetStoreV2] 🔍 Email submit attempt:",{email:me,sessionId:q,hasActiveSession:Re,hasJwt:!!Se}),!Se){console.error("[WidgetStoreV2] ❌ Missing JWT for email submission");return}ne(!0),ee(null);try{if(Re){const _e=P?await P.getAnonymousUserId():typeof localStorage<"u"?localStorage.getItem(`wysdym_anonymous_user_${T}`):null;console.log("[WidgetStoreV2] 📧 Update-email with anonymous_user_id:",_e?`${_e.slice(0,8)}...`:null);const Be=await fetch(buildApiUrl(`api/widget/session/update-email/${q}`),{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"},body:JSON.stringify({email:me.trim(),anonymous_user_id:_e||void 0})});if(!Be.ok){const Ue=await Be.text();throw new Error(`Failed to update email: ${Be.statusText} ${Ue}`)}const Ve=await Be.json();console.log("[WidgetStoreV2] 🔍 Update email response:",Ve),Pe(!0),Ae(!0),Me(!1),Ce(!1),console.log("[WidgetStoreV2] ✅ Email updated successfully")}else{const _e=P?await P.getAnonymousUserId():typeof localStorage<"u"?localStorage.getItem(`wysdym_anonymous_user_${T}`):null,Be=await fetch(buildApiUrl("api/widget/session/intake"),{method:"POST",headers:{Authorization:`Bearer ${U}`,"Content-Type":"application/json"},body:JSON.stringify({email:me.trim(),role:"Widget User",company:"Widget Demo",needs:[],challenges:[],agent_id:n,anonymous_user_id:_e||void 0})});if(!Be.ok)throw new Error(`Failed to submit email: ${Be.statusText}`);const Ve=await Be.json();console.log("[WidgetStoreV2] 🔍 Intake response data:",Ve);const{session_id:Ue,widget_jwt:Je}=Ve;if(!Ue||!Je)throw new Error("Invalid response from intake endpoint");H(Ue),Q(Je),K(!1),Z(!0),Pe(!0),Ae(!0),Me(!1),Ce(!1),console.log("[WidgetStoreV2] 🔌 Initializing socket for session:",Ue),initializeSocket(Ue,Je),console.log("[WidgetStoreV2] ✅ Email submitted successfully")}}catch(_e){console.error("[WidgetStoreV2] ❌ Failed to submit email:",_e),ee(`Failed to submit email: ${_e instanceof Error?_e.message:"Unknown error"}`)}finally{ne(!1)}},[q,U,$,n,T,P]),Mt=React.useCallback(async me=>{se(me),console.log(me==="voice"?"[WidgetStoreV2] 🎤 Voice mode selected":"[WidgetStoreV2] 📝 Text mode selected")},[]),Dt=React.useCallback(async()=>{if(!q||!(U||$))return console.error("[WidgetStoreV2] ❌ Cannot reconnect: missing session data"),!1;try{if(console.log("[WidgetStoreV2] 🔄 Manual reconnection initiated by user..."),nt(!0),ie==="voice"){const me=ue.filter(_e=>_e.role==="user").slice(-1)[0]?.content||"",Se=ue.filter(_e=>_e.role==="assistant").slice(-1)[0]?.content||"";return await Te.startVoiceSession(!0,me,Se)?(console.log("[WidgetStoreV2] ✅ Voice session reconnected successfully"),ze(!1),!0):(W("Failed to reconnect voice. Please try again."),!1)}else return await rt.startTextSession()?(console.log("[WidgetStoreV2] ✅ Text session reconnected successfully"),!0):(W("Failed to reconnect. Please try again."),!1)}catch(me){return console.error("[WidgetStoreV2] ❌ Manual reconnection failed:",me),W("Reconnection failed. Please try starting a new conversation."),!1}finally{nt(!1)}},[q,U,$,ie,ue,Te,rt]),Lt=React.useCallback(()=>{R==="floating"&&O(!0)},[R]),vt=React.useCallback(()=>{O(!1)},[]),Tt=React.useCallback(()=>{Ze.current=Date.now(),tt.current=setInterval(()=>{if(Ze.current){const me=Math.floor((Date.now()-Ze.current)/1e3);pe(me)}},1e3)},[]),Ct=React.useCallback(()=>{tt.current&&(clearInterval(tt.current),tt.current=null),Ze.current=null},[]);React.useEffect(()=>{Te.isConnected&&!Ze.current&&Tt()},[Te.isConnected,Tt]),React.useEffect(()=>{},[]),React.useEffect(()=>{R==="floating"&&L&&!te&&!N&&!ht.current&&(ht.current=!0,console.log("[WidgetStoreV2] 🚀 Widget expanded, auto-loading agent..."),St())},[R,L,te,N,St]),React.useEffect(()=>{R==="floating"&&L&&te&&!Y&&!N&&!pt.current&&(pt.current=!0,console.log("[WidgetStoreV2] 🎯 Agent loaded, auto-starting session..."),gt())},[R,L,te,Y,N,gt]),React.useEffect(()=>{te&&!ae&&(console.log("[WidgetStoreV2] 🎨 Loading custom CTA in background..."),ct())},[te,ae,ct]),React.useEffect(()=>{if(console.log("[WidgetStoreV2] 🎤 Voice session init effect triggered:",{demoStarted:Y,hasAgent:!!te,agentName:te?.name,isConnected:Te.isConnected,isConnecting:Te.isConnecting,alreadyInitialized:st.current,mode:R,sessionId:q||"none",hasJwt:!!(U||$)}),Y&&te&&!Te.isConnected&&!Te.isConnecting&&!st.current){const me=te&&(q||!te.require_email),Se=U||$;console.log("[WidgetStoreV2] 🎤 Voice session init check:",{hasRequiredData:me,hasJwt:Se,sessionId:q||"none"}),me&&Se?(st.current=!0,console.log("[WidgetStoreV2] 🎤 Starting voice session for",R,"mode..."),(async()=>{try{if(console.log("[WidgetStoreV2] 🎤 About to call startVoiceSession..."),!q||!(U||$)||!te){console.error("[WidgetStoreV2] ❌ Missing data for voice session:",{sessionId:!!q,hasJwt:!!(U||$),agent:!!te}),B(!1);return}const _e=await Te.startVoiceSession();console.log("[WidgetStoreV2] 🎤 Voice session startVoiceSession called, result:",_e),_e?(console.log("[WidgetStoreV2] ✅ Voice session started successfully"),B(!1)):(console.warn("[WidgetStoreV2] ⚠️ Voice session failed to start"),st.current=!1,B(!1))}catch(_e){console.error("[WidgetStoreV2] ❌ Voice session error:",_e),st.current=!1,B(!1)}})()):console.log("[WidgetStoreV2] ⏳ Waiting for voice session data...")}else console.log("[WidgetStoreV2] ⏳ Voice session init conditions not met:",{demoStarted:Y,hasAgent:!!te,isConnected:Te.isConnected,isConnecting:Te.isConnecting,alreadyInitialized:st.current,reason:Y?te?Te.isConnected?"already connected":Te.isConnecting?"already connecting":"already initialized":"no agent":"demo not started"})},[Y,te,q,U,$,Te.isConnected,Te.isConnecting,B,R]);const Ot=React.useCallback(async()=>{if(n){V(!0),W(null);try{const me=await fetch(buildApiUrl(`api/widget/bootstrap?agent_id=${n}`),{method:"GET",headers:{"Content-Type":"application/json"}});if(!me.ok)throw new Error("Failed to get bootstrap JWT");const{access_token:Se}=await me.json();at(Se);const Re=await fetch(buildApiUrl(`api/widget/session/agent-config/${n}`),{method:"GET",headers:{Authorization:`Bearer ${Se}`,"Content-Type":"application/json"}});if(!Re.ok)throw new Error(`Failed to load agent: ${Re.statusText}`);const _e=await Re.json();oe(_e),console.log("[WidgetStoreV2] ✅ Agent loaded:",_e.name)}catch(me){console.error("[WidgetStoreV2] ❌ Failed to load agent:",me)}finally{V(!1)}}},[T,n]);React.useEffect(()=>()=>{Ct()},[Ct]),React.useEffect(()=>{},[L]);const yt=React.useCallback(async()=>{if(ft.current){console.warn("[WidgetStoreV2] ⚠️ endCall already in progress, ignoring duplicate call");return}ft.current=!0;try{if(q&&$)try{const me=buildApiUrl(`api/widget/session/${q}/end`),Se=await fetch(me,{method:"POST",headers:{Authorization:`Bearer ${$}`,"X-Client-Token":T,"Content-Type":"application/json"}});if(Se.ok)console.log("[WidgetStoreV2] ✅ Session ended on backend successfully");else{const Re=await Se.text();console.warn("[WidgetStoreV2] ⚠️ Failed to end session on backend:",Se.status,Re)}}catch(me){console.error("[WidgetStoreV2] ⚠️ Error calling end endpoint:",me)}else console.warn("[WidgetStoreV2] ⚠️ No sessionId or widgetJwt available for backend session end");Te.isConnected&&await Te.endVoiceSession(),rt.isConnected&&await rt.endTextSession(),Z(!1),ye(!0),st.current=!1,ht.current=!1,pt.current=!1,R==="inline"&&(H(null),Q(null),at(null),he([]),W(null),B(!1)),R==="floating"&&vt()}catch(me){console.error("[WidgetStoreV2] ❌ Error ending call:",me),ut(`Failed to end call: ${me instanceof Error?me.message:"Unknown error"}`)}finally{ft.current=!1}},[Te,rt,vt,R,q,$,T]),lt=React.useCallback(async()=>{console.log("[WidgetStoreV2] Pausing session...");try{if(Te.isConnected)try{await Te.endVoiceSession(),console.log("[WidgetStoreV2] Voice session ended due to pause")}catch(me){console.error("[WidgetStoreV2] Error ending voice session on pause:",me)}if(q&&$)try{const me=await fetch(buildApiUrl(`api/widget/session/${q}/pause`),{method:"POST",headers:{Authorization:`Bearer ${$}`,"X-Client-Token":T,"Content-Type":"application/json"}});if(me.ok){const Se=await me.json();console.log("[WidgetStoreV2] Session paused successfully:",Se),we("paused"),updateStatus("paused")}else me.status===401||me.status===403?(console.warn("[WidgetStoreV2] JWT expired during pause, will need to re-bootstrap on resume"),we("paused")):console.error("[WidgetStoreV2] Failed to pause session:",me.statusText)}catch(me){console.error("[WidgetStoreV2] Error calling pause endpoint:",me),we("paused")}if(P)try{P.trackEvent("session_paused","Session Paused",{reason:"user_action",sessionId:q})}catch(me){console.error("[WidgetStoreV2] Error tracking pause event:",me)}}catch(me){console.error("[WidgetStoreV2] Error in pauseSession:",me)}},[q,$,T,Te,P]),Ft=React.useCallback(async me=>{if(!(!$||!q)){P&&P.trackCTAClick(me.id,me.button_text);try{const Se=await fetch(buildApiUrl("api/widget/custom-cta/click"),{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"},body:JSON.stringify({custom_cta_id:me.id,widget_session_id:q})});if(Se.ok){const _e=await Se.json();sessionStorage.setItem("lastCtaClickId",_e.id)}if(me.open_in_new_tab!==!1)window.open(me.href,"_blank","noopener,noreferrer");else{console.log("[WidgetStoreV2] Same-tab CTA redirect - pausing session for continuity");try{await lt(),saveSession({sessionId:q,widgetJwt:$,agentId:n,companyToken:T,status:"paused",lastActivityAt:Date.now(),pageUrl:window.location.href,conversationState:{messageCount:ue.length,lastMessage:ue.length>0?ue[ue.length-1].content:void 0}}),sessionStorage.setItem(CTA_SAME_TAB_REDIRECT_KEY,"1")}catch(_e){console.warn("[WidgetStoreV2] Failed to pause before same-tab redirect:",_e),saveSession({sessionId:q,widgetJwt:$,agentId:n,companyToken:T,status:"paused",lastActivityAt:Date.now(),pageUrl:window.location.href,conversationState:{messageCount:ue.length,lastMessage:void 0}}),sessionStorage.setItem(CTA_SAME_TAB_REDIRECT_KEY,"1")}window.location.href=me.href}}catch(Se){console.error("[WidgetStoreV2] Error handling CTA click:",Se);const Re=me.open_in_new_tab!==!1?"_blank":"_self";window.open(me.href,Re,me.open_in_new_tab!==!1?"noopener,noreferrer":void 0)}}},[$,q,n,T,P,lt,ue]);React.useEffect(()=>{Te.setAgentSpeaking&&Te.setAgentSpeaking(Te.isAgentSpeaking)},[Te.isAgentSpeaking,Te.setAgentSpeaking]);const Nt=React.useCallback(me=>{Q(me)},[]),bt=React.useCallback(async(me,Se)=>{console.log("[WidgetStoreV2] Resuming session...");const Re=me??q,_e=Se??$;if(!Re||!_e)return console.error("[WidgetStoreV2] Cannot resume: missing session ID or JWT"),!1;try{const Be=await fetch(buildApiUrl(`api/widget/session/${Re}/resume`),{method:"POST",headers:{Authorization:`Bearer ${_e}`,"X-Client-Token":T,"Content-Type":"application/json"}});if(Be.ok){const Ve=await Be.json();console.log("[WidgetStoreV2] Session resumed successfully:",Ve),H(Re),Q(_e),we("active"),De(!1),updateStatus("active");let Ue="",Je="";try{const $e=await fetch(buildApiUrl(`api/widget/session/${Re}/history`),{method:"GET",headers:{Authorization:`Bearer ${_e}`,"X-Client-Token":T,"Content-Type":"application/json"}});if($e.ok){const Ke=await $e.json();if(console.log("[WidgetStoreV2] Loaded message history:",Ke),Ae(!!Ke.has_email),Ke.messages&&Array.isArray(Ke.messages)){const it=Ke.messages.map(He=>({role:He.role,content:He.message||He.content||""}));he(it),console.log("[WidgetStoreV2] Hydrated",it.length,"messages");for(let He=it.length-1;He>=0&&(!Ue&&it[He].role==="user"&&(Ue=it[He].content),!Je&&it[He].role==="assistant"&&(Je=it[He].content),!(Ue&&Je));He--);}}else console.warn("[WidgetStoreV2] Failed to load history:",$e.statusText)}catch($e){console.error("[WidgetStoreV2] Error loading history:",$e)}return ie==="voice"&&await Te.startVoiceSession(!0,Ue,Je),P&&P.trackEvent("session_resumed","Session Resumed",{sessionId:Re}),!0}else if(Be.status===401||Be.status===403){console.warn("[WidgetStoreV2] JWT expired during resume, re-bootstrapping...");try{const Ve=await fetch(buildApiUrl(`api/widget/bootstrap?agent_id=${n}`),{method:"GET",headers:{"Content-Type":"application/json"}});if(Ve.ok){const{access_token:Ue}=await Ve.json();if(at(Ue),Q(Ue),(await fetch(buildApiUrl(`api/widget/session/${Re}/resume`),{method:"POST",headers:{Authorization:`Bearer ${Ue}`,"X-Client-Token":T,"Content-Type":"application/json"}})).ok){console.log("[WidgetStoreV2] Session resumed after re-bootstrap"),we("active"),De(!1),updateStatus("active");try{const $e=await fetch(buildApiUrl(`api/widget/session/${Re}/history`),{method:"GET",headers:{Authorization:`Bearer ${Ue}`,"X-Client-Token":T,"Content-Type":"application/json"}});if($e.ok){const Ke=await $e.json();if(Ae(!!Ke.has_email),Ke.messages&&Array.isArray(Ke.messages)){const it=Ke.messages.map(He=>({role:He.role,content:He.message||He.content||""}));he(it)}}}catch($e){console.error("[WidgetStoreV2] Error loading history after re-bootstrap:",$e)}return!0}}}catch(Ve){console.error("[WidgetStoreV2] Re-bootstrap failed:",Ve)}return clearSession(),De(!1),W("Session expired. Please start a new conversation."),!1}else return console.error("[WidgetStoreV2] Failed to resume session:",Be.statusText),!1}catch(Be){return console.error("[WidgetStoreV2] Error resuming session:",Be),!1}},[q,$,T,n,ie,Te,P]),Vt=React.useCallback(async()=>{console.log("[WidgetStoreV2] Ending session with persistence cleanup...");try{if(q&&$)try{const me=await fetch(buildApiUrl(`api/widget/session/${q}/end`),{method:"POST",headers:{Authorization:`Bearer ${$}`,"X-Client-Token":T,"Content-Type":"application/json"}});me.ok?console.log("[WidgetStoreV2] Session ended on server"):console.warn("[WidgetStoreV2] Failed to end session on server:",me.statusText)}catch(me){console.warn("[WidgetStoreV2] Error calling end endpoint:",me)}await yt(),clearSession(),we("active"),De(!1),Ae(!1),Me(!1),console.log("[WidgetStoreV2] Session ended and persistence cleared")}catch(me){console.error("[WidgetStoreV2] Error ending session:",me)}},[yt,q,$,T]),Et=React.useCallback(async()=>{console.log("[WidgetStoreV2] Tab hidden - pausing session"),await lt()},[lt]),xt=React.useCallback(async()=>{console.log("[WidgetStoreV2] Tab visible - checking for resumable session");try{const me=sessionStorage.getItem("lastCtaClickId"),Se=hasValidSession()?loadSession():null,Re=Se?.widgetJwt||$;if(me&&Re&&me!=="agent-redirect")try{await fetch(buildApiUrl(`api/widget/custom-cta/return/${me}`),{method:"POST",headers:{Authorization:`Bearer ${Re}`}})}catch(_e){console.error("[WidgetStoreV2] Error tracking CTA return:",_e)}if(me&&sessionStorage.removeItem("lastCtaClickId"),hasValidSession()&&Se&&Se&&Se.status==="paused"){if(me){console.log("[WidgetStoreV2] Returning from CTA - auto-resuming session");try{await bt(Se.sessionId,Se.widgetJwt)}catch(_e){console.error("[WidgetStoreV2] Auto-resume failed:",_e),H(Se.sessionId),Q(Se.widgetJwt),we("resumable"),De(!0)}return}if(console.log("[WidgetStoreV2] Found paused session, marking as resumable"),H(Se.sessionId),Q(Se.widgetJwt),we("resumable"),De(!0),Se.conversationState&&console.log("[WidgetStoreV2] Restoring conversation state:",Se.conversationState),P)try{P.trackEvent("session_resumable","Session Resumable",{sessionId:Se.sessionId,messageCount:Se.conversationState?.messageCount||0})}catch(_e){console.error("[WidgetStoreV2] Error tracking resumable event:",_e)}}}catch(me){console.error("[WidgetStoreV2] Error in handleTabVisible:",me)}},[q,$,P,bt]),Pt=React.useCallback(async()=>{if(!sessionStorage.getItem(CTA_SAME_TAB_REDIRECT_KEY))return;sessionStorage.removeItem(CTA_SAME_TAB_REDIRECT_KEY);const Se=hasValidSession()?loadSession():null;!Se||Se.status!=="paused"||Se.agentId!==n||Se.companyToken!==T||(console.log("[WidgetStoreV2] Same-tab CTA redirect detected - restoring session for resume"),H(Se.sessionId),Q(Se.widgetJwt),we("resumable"),De(!0))},[n,T]);React.useEffect(()=>{Pt()},[Pt]),React.useEffect(()=>{const me=()=>{const Se=Date.now();if(Se-kt.current<Rt){console.log("[WidgetStoreV2] Visibility change debounced");return}kt.current=Se,ot.current&&clearTimeout(ot.current),ot.current=setTimeout(()=>{document.visibilityState==="hidden"?Et():document.visibilityState==="visible"&&xt()},0)};return document.addEventListener("visibilitychange",me),()=>{document.removeEventListener("visibilitychange",me),ot.current&&clearTimeout(ot.current)}},[Et,xt]),React.useEffect(()=>{const me=()=>{if(!(!q||!$)&&!sessionStorage.getItem(CTA_SAME_TAB_REDIRECT_KEY))try{const Se=buildApiUrl(`api/widget/session/${q}/end`),Re=JSON.stringify({reason:"beforeunload"});fetch(Se,{method:"POST",headers:{Authorization:`Bearer ${$}`,"X-Client-Token":T,"Content-Type":"application/json"},body:Re,keepalive:!0}).catch(_e=>{console.warn("[WidgetStoreV2] End session keepalive failed:",_e)})}catch(Se){console.warn("[WidgetStoreV2] Failed to send endSession beacon on unload:",Se)}};return window.addEventListener("beforeunload",me),()=>window.removeEventListener("beforeunload",me)},[q,$,T]),React.useEffect(()=>{q&&$&&xe==="active"&&saveSession({sessionId:q,widgetJwt:$,agentId:n,companyToken:T,status:"active",lastActivityAt:Date.now(),pageUrl:window.location.href,conversationState:{messageCount:ue.length,lastMessage:ue.length>0?ue[ue.length-1].content:void 0}})},[q,$,n,T,xe,ue]),React.useEffect(()=>{if(!q||!$)return;const me=getSocket();if(!me)return;const Se=Ve=>{console.log("[WidgetStoreV2] Tool call event:",Ve),Fe("calling_tool"),Ne(Ve.tool_name),setTimeout(()=>{Fe("idle"),Ne(void 0)},5e3)},Re=()=>{Fe("speaking"),Ne(void 0)},_e=()=>{Fe("idle"),Ne(void 0)},Be=Ve=>{if(console.log("[WidgetStoreV2] Agent message event:",Ve),Ve.message&&Te.conversation?.sendUserMessage){console.log("[WidgetStoreV2] Sending message to ElevenLabs:",Ve.message);try{Te.conversation.sendUserMessage(Ve.message)}catch(Ue){console.error("[WidgetStoreV2] Failed to send message to ElevenLabs:",Ue)}}};return me.on("tool_call",Se),me.on("agent_speaking",Re),me.on("agent_idle",_e),me.on("agent_message",Be),()=>{me.off("tool_call",Se),me.off("agent_speaking",Re),me.off("agent_idle",_e),me.off("agent_message",Be)}},[q,$,Te,se]),React.useEffect(()=>{Te.isAgentSpeaking?(Fe("speaking"),Ne(void 0)):Te.isListening&&(Fe("idle"),Ne(void 0))},[Te.isAgentSpeaking,Te.isListening]);const dt=React.useRef(!1);React.useEffect(()=>{Te.isConnected&&(dt.current=!0),!Te.isConnected&&dt.current&&console.log("[WidgetStoreV2] 🔍 Disconnection detected, checking conditions:",{wasConnected:dt.current,isConnected:Te.isConnected,isConnecting:Te.isConnecting,inputMode:ie,demoStarted:Y,userEndedCall:ge,hasActiveForm:je,shouldShowPrompt:dt.current&&!Te.isConnected&&!Te.isConnecting&&ie==="voice"&&Y&&!ge}),dt.current&&!Te.isConnected&&!Te.isConnecting&&ie==="voice"&&Y&&!ge&&(console.log("[WidgetStoreV2] 🔌 Voice disconnected - showing reconnection prompt"),je?Ge("form_active"):Te.error?Ge("error"):Ge("timeout"),ze(!0)),Te.isConnected&&(ze(!1),nt(!1))},[Te.isConnected,Te.isConnecting,Te.error,ie,Y,je,ge]);const jt=React.useCallback(async me=>{if(me.trim()&&(mt({role:"user",content:me,source:"text"}),Te.isConnected&&Te.conversation))try{await Te.conversation.sendUserMessage(me)}catch(Se){console.error("[WidgetStoreV2] Failed to send text via voice session:",Se)}},[Te.isConnected,Te.conversation,mt]),Bt=React.useCallback(()=>{if(!(!Te.isConnected||!Te.conversation))try{Te.conversation.sendUserActivity?.()}catch(me){console.warn("[WidgetStoreV2] sendUserActivity failed:",me)}},[Te.isConnected,Te.conversation]);return{isExpanded:L,isLoading:N,isInitializing:j,error:z,sessionId:q,widgetJwt:$,bootstrapJwt:U,showEmailForm:G,demoStarted:Y,inputMode:ie,callDuration:le,messages:ue,textInput:ve,isSubmittingEmail:fe,emailError:ce,agent:te,customCta:ae,userEndedCall:ge,emailSubmitted:Ee,sessionHasEmail:Ie,showEmailFormRequestedByAgent:Le,forceDisplayEmailForm:ke,sessionStatus:xe,canResumeSession:Oe,aiStatus:We,currentToolName:qe,hasActiveForm:je,setHasActiveForm:Ye,showReconnectionPrompt:Xe,disconnectionReason:Qe,isReconnecting:et,isConnected:Te.isConnected,isConnecting:Te.isConnecting,connectionState:Te.connectionState,isAgentSpeaking:Te.isAgentSpeaking,isListening:Te.isListening,audioData:Te.audioData,micLevel:Te.micLevel,expandWidget:Lt,closeWidget:vt,setInputModeAndStart:Mt,startDirectSession:gt,handleEmailSubmit:It,endCall:yt,manualReconnect:Dt,loadAgent:Ot,loadCustomCta:ct,handleCtaClick:Ft,updateWidgetJwt:Nt,resumeSession:bt,pauseSession:lt,endSession:Vt,startVoiceSession:Te.startVoiceSession,endVoiceSession:Te.endVoiceSession,startTextSession:rt.startTextSession,endTextSession:rt.endTextSession,handleTextSubmit:rt.handleTextSubmit,setTextInput:be,setError:ut,clearError:At,mediaStreamRef:Te.mediaStreamRef,muteMicrophone:Te.muteMicrophone,muteAgentAudio:Te.muteAgentAudio,addMessage:mt,sendTextDuringVoice:jt,sendUserActivity:Bt}};var EventType=(T=>(T.WIDGET_OPEN="widget_open",T.WIDGET_CLOSE="widget_close",T.WIDGET_EXPAND="widget_expand",T.WIDGET_COLLAPSE="widget_collapse",T.SESSION_START="session_start",T.SESSION_END="session_end",T.SESSION_ABANDON="session_abandon",T.WIDGET_SESSION_CREATED="widget_session_created",T.WIDGET_SESSION_PAUSED="widget_session_paused",T.WIDGET_SESSION_RESUMED="widget_session_resumed",T.WIDGET_SESSION_ENDED="widget_session_ended",T.WIDGET_SESSION_ABANDONED="widget_session_abandoned",T.WIDGET_PAGE_NAVIGATION="widget_page_navigation",T.WIDGET_SESSION_TIMEOUT="widget_session_timeout",T.WIDGET_RESUME_PROMPT_SHOWN="widget_resume_prompt_shown",T.WIDGET_RESUME_PROMPT_ACCEPTED="widget_resume_prompt_accepted",T.WIDGET_RESUME_PROMPT_DECLINED="widget_resume_prompt_declined",T.INPUT_MODE_SWITCH="input_mode_switch",T.VOICE_MODE_START="voice_mode_start",T.VOICE_MODE_END="voice_mode_end",T.TEXT_MODE_START="text_mode_start",T.MESSAGE_SENT="message_sent",T.MESSAGE_RECEIVED="message_received",T.VOICE_START_LISTENING="voice_start_listening",T.VOICE_STOP_LISTENING="voice_stop_listening",T.MICROPHONE_REQUEST="microphone_request",T.MICROPHONE_GRANTED="microphone_granted",T.MICROPHONE_DENIED="microphone_denied",T.CALL_START="call_start",T.CALL_END="call_end",T.CALL_MUTE="call_mute",T.CALL_UNMUTE="call_unmute",T.CALL_HOLD="call_hold",T.CALL_RESUME="call_resume",T.CONNECTION_ERROR="connection_error",T.API_ERROR="api_error",T.AUDIO_QUALITY_ISSUE="audio_quality_issue",T.NETWORK_TIMEOUT="network_timeout",T.RESPONSE_LATENCY="response_latency",T.PAGE_VISIBLE="page_visible",T.PAGE_HIDDEN="page_hidden",T.TAB_SWITCH="tab_switch",T.WINDOW_FOCUS="window_focus",T.WINDOW_BLUR="window_blur",T.CTA_DISPLAY="cta_display",T.CTA_CLICK="cta_click",T.CTA_RETURN="cta_return",T.EMAIL_FORM_SHOW="email_form_show",T.EMAIL_SUBMIT="email_submit",T.EMAIL_SUBMIT_SUCCESS="email_submit_success",T.EMAIL_SUBMIT_ERROR="email_submit_error",T.AGENT_LOAD_START="agent_load_start",T.AGENT_LOAD_SUCCESS="agent_load_success",T.AGENT_LOAD_ERROR="agent_load_error",T.AGENT_SPEAKING_START="agent_speaking_start",T.AGENT_SPEAKING_END="agent_speaking_end",T))(EventType||{});class EventDeduplicator{static instance;trackedEvents=new Set;eventWindowMs=5e3;cleanupInterval=null;static getInstance(){return EventDeduplicator.instance||(EventDeduplicator.instance=new EventDeduplicator,EventDeduplicator.instance.cleanupInterval=setInterval(()=>{EventDeduplicator.instance.cleanupOldEvents()},1e4)),EventDeduplicator.instance}generateEventKey(n){const P=Math.floor(Date.now()/this.eventWindowMs);return`${n.event_type}_${n.event_name}_${n.widget_session_id||"no_session"}_${P}`}shouldTrackEvent(n){const P=this.generateEventKey(n);return this.trackedEvents.has(P)?(console.log("[EventDeduplicator] Duplicate event detected, skipping:",P),!1):(this.trackedEvents.add(P),console.log("[EventDeduplicator] Event added to tracking:",P),!0)}cleanupOldEvents(){const n=Date.now(),P=Math.floor(n/this.eventWindowMs);for(const R of this.trackedEvents){const A=R.split("_");parseInt(A[A.length-1])<P-2&&this.trackedEvents.delete(R)}console.log("[EventDeduplicator] Cleaned up old events, current count:",this.trackedEvents.size)}clearEvents(){this.trackedEvents.clear(),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}}class AnalyticsService{config;jwtToken=null;anonymousUserId=null;anonymousUserIdReady=null;eventQueue=[];isProcessing=!1;retryCount=0;maxRetries=3;deduplicator;circuitBreakerOpen=!1;circuitBreakerOpenTime=0;circuitBreakerTimeout=3e4;consecutiveFailures=0;maxConsecutiveFailures=5;constructor(n){this.config=n,this.deduplicator=EventDeduplicator.getInstance(),this.anonymousUserIdReady=this.loadAnonymousUserId()}setJwt(n){this.jwtToken=n}async getAnonymousUserId(){return this.anonymousUserIdReady&&await this.anonymousUserIdReady,this.anonymousUserId}async loadAnonymousUserId(){try{const n=localStorage.getItem(`wysdym_anonymous_user_${this.config.companyToken}`);if(n){this.anonymousUserId=n;return}this.anonymousUserId=this.generateAnonymousUserId(),localStorage.setItem(`wysdym_anonymous_user_${this.config.companyToken}`,this.anonymousUserId)}catch(n){console.warn("[AnalyticsService] Failed to load anonymous user ID:",n)}}generateAnonymousUserId(){const n=this.getBrowserFingerprint(),P=JSON.stringify(n,Object.keys(n).sort());let R=0;for(let A=0;A<P.length;A++){const L=P.charCodeAt(A);R=(R<<5)-R+L,R=R&R}return Math.abs(R).toString(36).substring(0,16)}getBrowserFingerprint(){return{userAgent:navigator.userAgent,language:navigator.language,platform:navigator.platform,cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}async trackEvent(n){if(!this.deduplicator.shouldTrackEvent(n)){console.log("[AnalyticsService] Event already tracked, skipping:",n.event_type,n.event_name);return}console.log("[AnalyticsService] Tracking event:",n.event_type,n.event_name,new Date().toISOString());try{if(!this.jwtToken)return;const P=await fetch(`${this.config.baseUrl}/api/widget/analytics/track`,{method:"POST",headers:{Authorization:`Bearer ${this.jwtToken}`,"Content-Type":"application/json"},body:JSON.stringify({...n,registered_agent_id:n.registered_agent_id||this.config.agentId,widget_session_id:n.widget_session_id||this.config.sessionId})});if(!P.ok)throw new Error(`Analytics tracking failed: ${P.statusText}`);const R=await P.json();R.anonymous_user_id&&!this.anonymousUserId&&(this.anonymousUserId=R.anonymous_user_id,localStorage.setItem(`wysdym_anonymous_user_${this.config.companyToken}`,this.anonymousUserId)),console.log("[AnalyticsService] Event tracked successfully:",n.event_type,n.event_name),this.retryCount=0}catch(P){console.error("[AnalyticsService] Failed to track event:",P),this.queueEvent(n)}}queueEvent(n){if(this.isCircuitBreakerOpen()){console.warn("[AnalyticsService] Circuit breaker open, dropping event:",n.event_type,n.event_name);return}if(this.eventQueue.length>=50){console.warn("[AnalyticsService] Queue full, dropping event:",n.event_type,n.event_name);return}const P=`${n.event_type}_${n.event_name}_${n.widget_session_id||"no_session"}`;if(this.eventQueue.some(A=>`${A.event_type}_${A.event_name}_${A.widget_session_id||"no_session"}`===P)){console.log("[AnalyticsService] Duplicate event in queue, skipping:",n.event_type,n.event_name);return}this.isProcessing?this.eventQueue.push(n):(this.eventQueue.push(n),this.processQueue())}async processQueue(){if(!(this.isProcessing||this.eventQueue.length===0)){for(this.isProcessing=!0;this.eventQueue.length>0&&this.retryCount<this.maxRetries;){const n=this.eventQueue.shift();if(n)try{await this.trackEvent(n),this.retryCount=0,this.consecutiveFailures=0,this.circuitBreakerOpen&&(console.log("[AnalyticsService] Circuit breaker closed after successful event"),this.circuitBreakerOpen=!1)}catch(P){if(console.error("[AnalyticsService] Failed to process queued event:",P),this.retryCount++,this.consecutiveFailures++,this.consecutiveFailures>=this.maxConsecutiveFailures){this.openCircuitBreaker();break}if(this.retryCount<this.maxRetries){this.eventQueue.push(n),await new Promise(R=>setTimeout(R,1e3*this.retryCount));break}else console.warn("[AnalyticsService] Max retries reached, dropping event:",n.event_type,n.event_name)}}this.isProcessing=!1,this.retryCount=0}}openCircuitBreaker(){this.circuitBreakerOpen=!0,this.circuitBreakerOpenTime=Date.now(),console.warn("[AnalyticsService] Circuit breaker opened due to consecutive failures"),setTimeout(()=>{this.circuitBreakerOpen&&(console.log("[AnalyticsService] Circuit breaker timeout reached, attempting to close"),this.circuitBreakerOpen=!1,this.consecutiveFailures=0,this.eventQueue.length>0&&!this.isProcessing&&this.processQueue())},this.circuitBreakerTimeout)}isCircuitBreakerOpen(){return this.circuitBreakerOpen&&Date.now()-this.circuitBreakerOpenTime>this.circuitBreakerTimeout&&(this.circuitBreakerOpen=!1,this.consecutiveFailures=0,console.log("[AnalyticsService] Circuit breaker auto-closed after timeout")),this.circuitBreakerOpen}clearQueue(){this.eventQueue=[],this.isProcessing=!1,this.retryCount=0,this.consecutiveFailures=0,console.log("[AnalyticsService] Event queue cleared")}clearDeduplicator(){this.deduplicator.clearEvents()}updateSessionId(n){this.config.sessionId=n}async trackWidgetOpen(){await this.trackEvent({event_type:"widget_open",event_name:"Widget Opened",event_data:{timestamp:Date.now(),page_url:window.location.href,referrer:document.referrer}})}async trackWidgetClose(){await this.trackEvent({event_type:"widget_close",event_name:"Widget Closed",event_data:{timestamp:Date.now(),session_duration:this.config.sessionId?Date.now():void 0}})}async trackSessionStart(){this.config.sessionId&&await this.trackEvent({event_type:"session_start",event_name:"Session Started",widget_session_id:this.config.sessionId,event_data:{timestamp:Date.now(),page_url:window.location.href}})}async trackSessionEnd(){this.config.sessionId&&await this.trackEvent({event_type:"session_end",event_name:"Session Ended",widget_session_id:this.config.sessionId,event_data:{timestamp:Date.now(),session_duration:Date.now()}})}async trackInputModeSwitch(n,P){await this.trackEvent({event_type:"input_mode_switch",event_name:`Input Mode Switched: ${n} → ${P}`,event_data:{from_mode:n,to_mode:P,timestamp:Date.now()}})}async trackMessageSent(n,P){await this.trackEvent({event_type:"message_sent",event_name:"Message Sent",event_data:{message_length:n,input_mode:P,timestamp:Date.now()}})}async trackError(n,P,R){await this.trackEvent({event_type:"api_error",event_name:`Error: ${n}`,error_code:P,error_message:R,event_data:{error_type:n,timestamp:Date.now(),page_url:window.location.href}})}async trackPerformance(n,P,R="ms"){await this.trackEvent({event_type:"response_latency",event_name:`Performance: ${n}`,event_data:{metric_name:n,value:P,unit:R,timestamp:Date.now()}})}async trackVoiceModeStart(){await this.trackEvent({event_type:"voice_mode_start",event_name:"Voice Mode Started",event_data:{timestamp:Date.now()}})}async trackVoiceModeEnd(){await this.trackEvent({event_type:"voice_mode_end",event_name:"Voice Mode Ended",event_data:{timestamp:Date.now()}})}async trackMicrophoneRequest(){await this.trackEvent({event_type:"microphone_request",event_name:"Microphone Requested",event_data:{timestamp:Date.now()}})}async trackMicrophoneGranted(){await this.trackEvent({event_type:"microphone_granted",event_name:"Microphone Granted",event_data:{timestamp:Date.now()}})}async trackMicrophoneDenied(){await this.trackEvent({event_type:"microphone_denied",event_name:"Microphone Denied",event_data:{timestamp:Date.now()}})}async trackPageVisibilityChange(n){await this.trackEvent({event_type:n?"page_visible":"page_hidden",event_name:n?"Page Visible":"Page Hidden",event_data:{timestamp:Date.now(),page_url:window.location.href}})}async trackCTADisplay(){await this.trackEvent({event_type:"cta_display",event_name:"CTA Displayed",event_data:{timestamp:Date.now()}})}async trackCTAClick(n,P){await this.trackEvent({event_type:"cta_click",event_name:"CTA Clicked",event_data:{cta_id:n,cta_text:P,timestamp:Date.now()}})}async trackEmailFormShow(){await this.trackEvent({event_type:"email_form_show",event_name:"Email Form Shown",event_data:{timestamp:Date.now()}})}async trackEmailSubmit(n,P){await this.trackEvent({event_type:n?"email_submit_success":"email_submit_error",event_name:n?"Email Submitted Successfully":"Email Submit Failed",error_message:P,event_data:{success:n,timestamp:Date.now()}})}async trackAgentLoadStart(){await this.trackEvent({event_type:"agent_load_start",event_name:"Agent Load Started",event_data:{timestamp:Date.now()}})}async trackAgentLoadSuccess(){await this.trackEvent({event_type:"agent_load_success",event_name:"Agent Loaded Successfully",event_data:{timestamp:Date.now()}})}async trackAgentLoadError(n){await this.trackEvent({event_type:"agent_load_error",event_name:"Agent Load Failed",error_message:n,event_data:{timestamp:Date.now()}})}async trackAgentSpeakingStart(){await this.trackEvent({event_type:"agent_speaking_start",event_name:"Agent Started Speaking",event_data:{timestamp:Date.now()}})}async trackAgentSpeakingEnd(){await this.trackEvent({event_type:"agent_speaking_end",event_name:"Agent Stopped Speaking",event_data:{timestamp:Date.now()}})}async trackCallStart(){await this.trackEvent({event_type:"call_start",event_name:"Call Started",event_data:{timestamp:Date.now()}})}async trackCallEnd(){await this.trackEvent({event_type:"call_end",event_name:"Call Ended",event_data:{timestamp:Date.now()}})}async trackVoiceStartListening(){await this.trackEvent({event_type:"voice_start_listening",event_name:"Voice Listening Started",event_data:{timestamp:Date.now()}})}async trackVoiceStopListening(){await this.trackEvent({event_type:"voice_stop_listening",event_name:"Voice Listening Stopped",event_data:{timestamp:Date.now()}})}async trackWidgetSessionCreated(n){await this.trackEvent({event_type:EventType.WIDGET_SESSION_CREATED,event_name:"Widget Session Created",event_data:{timestamp:Date.now(),page_url:n?.pageUrl||window.location.href,message_count:n?.messageCount||0}})}async trackWidgetSessionPaused(n){await this.trackEvent({event_type:EventType.WIDGET_SESSION_PAUSED,event_name:"Widget Session Paused",event_data:{timestamp:Date.now(),reason:n?.reason||"user_action",message_count:n?.messageCount,session_duration_ms:n?.sessionDuration,page_url:window.location.href}})}async trackWidgetSessionResumed(n){await this.trackEvent({event_type:EventType.WIDGET_SESSION_RESUMED,event_name:"Widget Session Resumed",event_data:{timestamp:Date.now(),message_count:n?.messageCount,pause_duration_ms:n?.pauseDuration,page_url:window.location.href}})}async trackWidgetSessionEnded(n){await this.trackEvent({event_type:EventType.WIDGET_SESSION_ENDED,event_name:"Widget Session Ended",event_data:{timestamp:Date.now(),reason:n?.reason||"user_action",message_count:n?.messageCount,session_duration_ms:n?.sessionDuration,completed_successfully:n?.completedSuccessfully??!0,page_url:window.location.href}})}async trackWidgetSessionAbandoned(n){await this.trackEvent({event_type:EventType.WIDGET_SESSION_ABANDONED,event_name:"Widget Session Abandoned",event_data:{timestamp:Date.now(),reason:n?.reason||"timeout",message_count:n?.messageCount,session_duration_ms:n?.sessionDuration,last_activity_at:n?.lastActivityAt,page_url:window.location.href}})}async trackWidgetPageNavigation(n){await this.trackEvent({event_type:EventType.WIDGET_PAGE_NAVIGATION,event_name:"Widget Page Navigation",event_data:{timestamp:Date.now(),from_url:n.fromUrl,to_url:n.toUrl,session_age_ms:n.sessionAge,message_count:n.messageCount}})}async trackWidgetSessionTimeout(n){await this.trackEvent({event_type:EventType.WIDGET_SESSION_TIMEOUT,event_name:"Widget Session Timeout",event_data:{timestamp:Date.now(),message_count:n?.messageCount,session_duration_ms:n?.sessionDuration,last_activity_at:n?.lastActivityAt,page_url:window.location.href}})}async trackResumePromptShown(n){await this.trackEvent({event_type:EventType.WIDGET_RESUME_PROMPT_SHOWN,event_name:"Widget Resume Prompt Shown",event_data:{timestamp:Date.now(),message_count:n?.messageCount,session_age_ms:n?.sessionAge,pause_duration_ms:n?.pauseDuration,page_url:window.location.href}})}async trackResumePromptAccepted(n){await this.trackEvent({event_type:EventType.WIDGET_RESUME_PROMPT_ACCEPTED,event_name:"Widget Resume Prompt Accepted",event_data:{timestamp:Date.now(),message_count:n?.messageCount,session_age_ms:n?.sessionAge,pause_duration_ms:n?.pauseDuration,page_url:window.location.href}})}async trackResumePromptDeclined(n){await this.trackEvent({event_type:EventType.WIDGET_RESUME_PROMPT_DECLINED,event_name:"Widget Resume Prompt Declined",event_data:{timestamp:Date.now(),message_count:n?.messageCount,session_age_ms:n?.sessionAge,pause_duration_ms:n?.pauseDuration,page_url:window.location.href}})}}class UIActionService{socket=null;handlers=new Map;isListening=!1;initialize(n){if(this.socket===n){console.log("[UIActionService] Already initialized with same socket");return}this.socket&&(console.warn("[UIActionService] Re-initializing with different socket, cleaning up old listeners"),this.isListening=!1),this.socket=n,this.setupListeners(),console.log("[UIActionService] Initialized")}setupListeners(){!this.socket||this.isListening||(this.socket.on("ui_action",n=>{console.log("[UIActionService] Received UI action:",n),this.handleUIAction(n.action)}),this.isListening=!0,console.log("[UIActionService] Listening for ui_action events"))}handleUIAction(n){const{action:P,component:R}=n;(this.handlers.get(R)||[]).forEach(O=>{try{O(n)}catch(N){console.error(`[UIActionService] Error in handler for ${R}:`,N)}}),(this.handlers.get("*")||[]).forEach(O=>{try{O(n)}catch(N){console.error("[UIActionService] Error in wildcard handler:",N)}})}on(n,P){this.handlers.has(n)||this.handlers.set(n,[]);const R=this.handlers.get(n);return R.push(P),console.log(`[UIActionService] Registered handler for '${n}'`),()=>{const A=R.indexOf(P);A>-1&&R.splice(A,1)}}off(n,P){const R=this.handlers.get(n);if(!R)return;const A=R.indexOf(P);A>-1&&R.splice(A,1)}removeAllHandlers(n){n?this.handlers.delete(n):this.handlers.clear()}cleanup(){this.socket&&(this.socket.off("ui_action"),this.socket=null),this.handlers.clear(),this.isListening=!1,console.log("[UIActionService] Cleaned up")}}const uiActionService=new UIActionService,DynamicInputForm=({formId:T,title:n,fields:P,submitText:R="Submit",onSubmit:A,onCancel:L})=>{const[O,N]=React.useState({}),[V,j]=React.useState({}),B=(q,H)=>{N($=>({...$,[q]:H})),V[q]&&j($=>{const Q={...$};return delete Q[q],Q})},z=()=>{const q={};return P.forEach(H=>{H.required&&!O[H.name]?.trim()&&(q[H.name]=`${H.label} is required`),H.type==="email"&&O[H.name]&&(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(O[H.name])||(q[H.name]="Please enter a valid email address"))}),j(q),Object.keys(q).length===0},W=q=>{q.preventDefault(),z()&&A(T,O)};return jsxRuntime.jsxs("div",{className:"dynamic-input-form bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl shadow-lg border-2 border-blue-200 overflow-hidden animate-slide-up",children:[jsxRuntime.jsxs("div",{className:"bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-3 flex items-center space-x-2",children:[jsxRuntime.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),n?jsxRuntime.jsx("h3",{className:"text-base font-semibold text-white",children:n}):jsxRuntime.jsx("h3",{className:"text-base font-semibold text-white",children:"Please type your information"})]}),jsxRuntime.jsxs("form",{onSubmit:W,className:"p-4 space-y-3",children:[P.map(q=>jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsxs("label",{htmlFor:`${T}-${q.name}`,className:"block text-xs font-semibold text-gray-700 uppercase tracking-wide",children:[q.label,q.required&&jsxRuntime.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),jsxRuntime.jsx("input",{id:`${T}-${q.name}`,type:q.type,placeholder:q.placeholder||`Enter your ${q.label.toLowerCase()}`,value:O[q.name]||"",onChange:H=>B(q.name,H.target.value),className:`w-full px-3 py-2.5 text-sm border-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${V[q.name]?"border-red-400 bg-red-50":"border-gray-200 bg-white hover:border-blue-300"}`,required:q.required,autoComplete:q.type==="email"?"email":q.name}),V[q.name]&&jsxRuntime.jsxs("p",{className:"text-xs text-red-600 font-medium flex items-center mt-1",children:[jsxRuntime.jsx("svg",{className:"w-3 h-3 mr-1",fill:"currentColor",viewBox:"0 0 20 20",children:jsxRuntime.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})}),V[q.name]]})]},q.name)),jsxRuntime.jsxs("div",{className:"flex gap-2 pt-3",children:[jsxRuntime.jsxs("button",{type:"submit",className:"flex-1 px-4 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 rounded-lg font-semibold transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-md hover:shadow-lg flex items-center justify-center space-x-2",style:{color:"#ffffff !important"},children:[jsxRuntime.jsx("span",{style:{color:"#ffffff !important"},children:R}),jsxRuntime.jsx("svg",{className:"w-4 h-4",style:{color:"#ffffff !important"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})]}),L&&jsxRuntime.jsx("button",{type:"button",onClick:L,className:"px-4 py-2.5 border-2 border-gray-300 hover:border-gray-400 hover:bg-gray-50 text-gray-700 rounded-lg font-semibold transition-all",children:"Cancel"})]}),jsxRuntime.jsxs("p",{className:"text-xs text-gray-600 text-center pt-2 flex items-center justify-center space-x-1",children:[jsxRuntime.jsx("svg",{className:"w-3 h-3",fill:"currentColor",viewBox:"0 0 20 20",children:jsxRuntime.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z",clipRule:"evenodd"})}),jsxRuntime.jsx("span",{children:"Please type for accurate spelling"})]})]})]})},DynamicUIRenderer=({sessionId:T,token:n,onFormStateChange:P,onFormSubmit:R})=>{const[A,L]=React.useState(new Map),[O,N]=React.useState(new Set),V=React.useCallback(Q=>{console.log("[DynamicUIRenderer] Received action:",Q.action,Q.component);const{action:U,component:J,data:G,animation:K}=Q,Y=`${U}-${J}-${G?.form_id||G?.id||Date.now()}`;if(U==="render"&&O.has(Y)){console.log(`[DynamicUIRenderer] ⚠️ Duplicate action detected, skipping: ${Y}`);return}switch(U){case"render":N(Z=>new Set(Z).add(Y)),j(J,G,K);break;case"update":B(J,G);break;case"remove":z(J,G);break;case"highlight":W(J,G);break;default:console.warn(`[DynamicUIRenderer] Unknown action type: ${U}`)}},[O]),j=(Q,U,J)=>{const G=U?.form_id||U?.id||`${Q}-${Date.now()}`;console.log(`[DynamicUIRenderer] 🎨 Rendering ${Q} (ID: ${G})`),console.log(`[DynamicUIRenderer] Is form? ${Q==="input_form"}, Has callback? ${!!P}`),L(K=>{const Y=new Map(K);if(Y.has(G)){console.log(`[DynamicUIRenderer] ⚠️ Component ${G} already exists, updating instead`);const Z=Y.get(G);Y.set(G,{...Z,data:{...Z.data,...U},animation:J})}else console.log(`[DynamicUIRenderer] ✨ Creating new component ${G}`),Y.set(G,{id:G,type:Q,data:U||{},animation:J});return console.log(`[DynamicUIRenderer] 📊 Active components count: ${Y.size}`),Y}),Q==="input_form"&&P&&(console.log("[DynamicUIRenderer] 🔄 Deferring onFormStateChange(true)"),setTimeout(()=>P(!0),0)),console.log(`[DynamicUIRenderer] ✅ Rendered ${Q} (ID: ${G})`)},B=(Q,U)=>{const J=U?.form_id||U?.id;if(!J){console.warn("[DynamicUIRenderer] Cannot update without component ID");return}L(G=>{const K=new Map(G),Y=K.get(J);return Y&&K.set(J,{...Y,data:{...Y.data,...U}}),K}),console.log(`[DynamicUIRenderer] Updated ${Q} with ID ${J}`)},z=(Q,U)=>{const J=U?.form_id||U?.id;if(!J){console.warn("[DynamicUIRenderer] Cannot remove without component ID");return}console.log(`[DynamicUIRenderer] 🗑️ Removing ${Q} with ID ${J}`),L(G=>{const K=new Map(G),Y=K.get(J);if(!Y)return console.warn(`[DynamicUIRenderer] ⚠️ Component ${J} not found for removal`),G;K.delete(J);const Z=Array.from(K.values()).some(ie=>ie.type==="input_form");return console.log(`[DynamicUIRenderer] 📊 After removal: ${K.size} components, ${Z?"has":"no"} forms`),Y.type==="input_form"&&!Z&&P&&(console.log("[DynamicUIRenderer] 🔄 Calling onFormStateChange(false)"),P(!1)),K}),console.log(`[DynamicUIRenderer] ✅ Removed ${Q} with ID ${J}`)},W=(Q,U)=>{console.log(`[DynamicUIRenderer] Highlight ${Q}`,U)},q=React.useCallback((Q,U)=>{console.log("[DynamicUIRenderer] Form submitted:",Q,U);const J=getSocket();J&&J.emit("form_submission",{session_id:T,form_id:Q,data:U}),J&&J.emit("tool_call",{session_id:T,tool_name:"collect_contact_info",args:{...U,form_id:Q}}),R&&R(Q,U),L(G=>{const K=new Map(G);return K.delete(Q),!Array.from(K.values()).some(Z=>Z.type==="input_form")&&P&&setTimeout(()=>P(!1),0),K})},[T,P]),H=React.useCallback(Q=>{console.log("[DynamicUIRenderer] Form cancelled:",Q),L(U=>{const J=new Map(U);return J.delete(Q),!Array.from(J.values()).some(K=>K.type==="input_form")&&P&&setTimeout(()=>P(!1),0),J})},[P]);React.useEffect(()=>{if(!n||!T){console.log("[DynamicUIRenderer] Waiting for token and session...");return}console.log("[DynamicUIRenderer] Initializing with session:",T),console.log("[DynamicUIRenderer] Token:",n.substring(0,20)+"...");let Q,U=null;const J=()=>{const G=getSocket();return G?(console.log("[DynamicUIRenderer] Socket found!"),console.log("[DynamicUIRenderer] Socket connected:",G.connected),console.log("[DynamicUIRenderer] Socket ID:",G.id),uiActionService.initialize(G),console.log("[DynamicUIRenderer] ✅ UI action service initialized"),U=uiActionService.on("*",V),console.log("[DynamicUIRenderer] Subscribed to UI actions"),!0):(console.log("[DynamicUIRenderer] Waiting for socket to be created..."),!1)};return J()||(Q=setInterval(()=>{J()&&clearInterval(Q)},100)),()=>{Q&&clearInterval(Q),U&&U()}},[T,n,V]);const $=Q=>{switch(Q.type){case"input_form":return jsxRuntime.jsx(DynamicInputForm,{formId:Q.id,title:Q.data.title,fields:Q.data.fields||[],submitText:Q.data.submit_text,onSubmit:q,onCancel:()=>H(Q.id)},Q.id);default:return console.warn(`[DynamicUIRenderer] Unknown component type: ${Q.type}`),null}};return jsxRuntime.jsx("div",{className:"dynamic-ui-renderer w-full max-w-md mx-auto px-6",children:Array.from(A.values()).map(Q=>jsxRuntime.jsx("div",{className:"dynamic-component",children:$(Q)},Q.id))})},MIC_THRESHOLD=.04;function formatToolName(T){return T.split("_").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}const MicLevelBars=({level:T})=>{const n=T>MIC_THRESHOLD,P=Math.min(T*4,1),R="var(--wysdym-primary, #BA6296)",A=(L,O)=>n?L+O*P*10:L;return jsxRuntime.jsx("div",{className:"flex items-center space-x-0.5",style:{height:16},children:[{base:6,scale:.7,delay:0},{base:8,scale:1,delay:80},{base:10,scale:.9,delay:40},{base:8,scale:1,delay:120},{base:6,scale:.7,delay:60}].map((L,O)=>jsxRuntime.jsx("div",{style:{width:3,height:A(L.base,L.scale),borderRadius:2,backgroundColor:R,opacity:n?.7+P*.3:.5,transition:"height 80ms ease-out, opacity 80ms ease-out"}},O))})},AIStatusIndicator=({status:T,toolName:n,micLevel:P=0})=>{if(T==="idle")return null;const R=T==="listening"&&P>MIC_THRESHOLD,L=(()=>{switch(T){case"listening":return{icon:jsxRuntime.jsx(MicLevelBars,{level:P}),text:R?"Hearing you...":"Listening...",bg:"rgba(186, 98, 150, 0.08)",color:"var(--wysdym-primary, #BA6296)",border:"rgba(186, 98, 150, 0.2)"};case"thinking":return{icon:jsxRuntime.jsx("svg",{className:"w-3.5 h-3.5 animate-spin",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),text:"Thinking...",bg:"#eff6ff",color:"#1d4ed8",border:"#bfdbfe"};case"calling_tool":return{icon:jsxRuntime.jsxs("svg",{className:"w-3.5 h-3.5 animate-pulse",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),text:n?`Using ${formatToolName(n)}...`:"Using a tool...",bg:"#faf5ff",color:"#7c3aed",border:"#ddd6fe"};case"speaking":return{icon:jsxRuntime.jsxs("div",{className:"flex space-x-0.5",children:[jsxRuntime.jsx("div",{className:"w-1 h-3 bg-green-600 rounded-full animate-pulse",style:{animationDelay:"0ms"}}),jsxRuntime.jsx("div",{className:"w-1 h-3 bg-green-600 rounded-full animate-pulse",style:{animationDelay:"150ms"}}),jsxRuntime.jsx("div",{className:"w-1 h-3 bg-green-600 rounded-full animate-pulse",style:{animationDelay:"300ms"}})]}),text:"Speaking...",bg:"#f0fdf4",color:"#15803d",border:"#bbf7d0"};default:return null}})();return L?jsxRuntime.jsxs("div",{className:"flex items-center space-x-2 px-3 py-1.5 rounded-lg shadow-sm",style:{backgroundColor:L.bg,borderWidth:"1px",borderStyle:"solid",borderColor:L.border,color:L.color,animation:"fadeIn 0.2s ease-in"},children:[L.icon,jsxRuntime.jsx("span",{className:"text-xs font-medium",children:L.text})]}):null},useConversationStore=createStore()((T,n)=>({messages:[],messageCount:0,lastMessage:null,addMessage:P=>{const R=[...n().messages,P];T({messages:R,messageCount:R.length,lastMessage:P})},updateLastMessage:(P,R)=>{const{messages:A}=n();if(A.length===0)return;const L=A[A.length-1];if(L.role!==P)return;const O=[...A];O[O.length-1]={...L,text:R},T({messages:O,lastMessage:O[O.length-1]})},setMessages:P=>T({messages:P,messageCount:P.length,lastMessage:P.length>0?P[P.length-1]:null}),clearMessages:()=>T({messages:[],messageCount:0,lastMessage:null})})),CHARS_PER_TICK=1,TICK_MS=30,MIC_ICON=jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),jsxRuntime.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsxRuntime.jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"})]}),KEYBOARD_ICON=jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),jsxRuntime.jsx("path",{d:"M6 8h.001M10 8h.001M14 8h.001M18 8h.001M8 12h.001M12 12h.001M16 12h.001M7 16h10"})]});function formatRelativeTime(T){const n=Math.max(0,Date.now()-T),P=Math.floor(n/1e3);if(P<5)return"just now";if(P<60)return`${P}s ago`;const R=Math.floor(P/60);return R<60?`${R}m ago`:`${Math.floor(R/60)}h ago`}const TranscriptMessage=({entry:T})=>{const n=T.role==="user",P=!n&&T.source==="voice"&&T.isFinal,[R,A]=React.useState(()=>P?0:T.text.length),L=React.useRef(T.text);React.useEffect(()=>{if(L.current=T.text,!P){A(T.text.length);return}if(R>=T.text.length)return;const N=setInterval(()=>{A(V=>{const j=V+CHARS_PER_TICK;return j>=L.current.length?(clearInterval(N),L.current.length):j})},TICK_MS);return()=>clearInterval(N)},[T.text,P]);const O=P?T.text.slice(0,R):T.text;return jsxRuntime.jsxs("div",{"data-testid":"transcript-message","data-role":T.role,"data-source":T.source,style:{display:"flex",flexDirection:"column",alignItems:n?"flex-end":"flex-start",marginBottom:"8px",maxWidth:"100%"},children:[jsxRuntime.jsx("div",{style:{maxWidth:"80%",padding:"8px 12px",borderRadius:n?"12px 12px 2px 12px":"12px 12px 12px 2px",backgroundColor:n?"var(--wysdym-primary, #BA6296)":"#f0f0f0",color:n?"#fff":"#1a1a1a",fontSize:"14px",lineHeight:"1.4"},children:O}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginTop:"2px",fontSize:"11px",color:"#999"},children:[jsxRuntime.jsx("span",{style:{display:"flex",alignItems:"center"},children:T.source==="voice"?MIC_ICON:KEYBOARD_ICON}),jsxRuntime.jsx("span",{"data-testid":"message-timestamp",children:formatRelativeTime(T.timestamp)})]})]})},SCROLL_THRESHOLD=60,Transcript=()=>{const T=useStore(useConversationStore,L=>L.messages),n=React.useRef(null),P=React.useRef(!0),R=React.useCallback(()=>{const L=n.current;if(!L)return;const O=L.scrollHeight-L.clientHeight-L.scrollTop<=SCROLL_THRESHOLD;P.current=O},[]);React.useEffect(()=>{P.current&&n.current&&(n.current.scrollTop=n.current.scrollHeight)},[T]);const A=React.useRef(null);return React.useEffect(()=>{const L=A.current,O=n.current;if(!L||!O)return;const N=new ResizeObserver(()=>{P.current&&(O.scrollTop=O.scrollHeight)});return N.observe(L),()=>N.disconnect()},[]),jsxRuntime.jsx("div",{"data-testid":"transcript-scroll",ref:n,onScroll:R,style:{flex:1,overflowY:"auto",padding:"12px"},children:jsxRuntime.jsx("div",{ref:A,children:T.length===0?jsxRuntime.jsx("div",{"data-testid":"transcript-empty",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#999",fontSize:"14px",fontStyle:"italic"},children:"Start a conversation..."}):T.map((L,O)=>jsxRuntime.jsx(TranscriptMessage,{entry:L},`${L.timestamp}-${O}`))})})},MIC_ON_ICON=jsxRuntime.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),jsxRuntime.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsxRuntime.jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"})]}),MIC_OFF_ICON=jsxRuntime.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"}),jsxRuntime.jsx("path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2"}),jsxRuntime.jsx("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),jsxRuntime.jsx("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),jsxRuntime.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),jsxRuntime.jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"})]}),SPEAKER_ON_ICON=jsxRuntime.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),jsxRuntime.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),jsxRuntime.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}),SPEAKER_OFF_ICON=jsxRuntime.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),jsxRuntime.jsx("line",{x1:"22",x2:"16",y1:"9",y2:"15"}),jsxRuntime.jsx("line",{x1:"16",x2:"22",y1:"9",y2:"15"})]}),SEND_ICON=jsxRuntime.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"22",x2:"11",y1:"2",y2:"13"}),jsxRuntime.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),END_CALL_ICON=jsxRuntime.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91"}),jsxRuntime.jsx("line",{x1:"22",x2:"2",y1:"2",y2:"22"})]}),TextInput=({onSend:T,isMicMuted:n=!1,isAgentMuted:P=!1,onToggleMic:R,onToggleAgentAudio:A,isConnected:L=!1,onEndCall:O,cta:N,onTypingChange:V,placeholder:j="Or type a message..."})=>{const[B,z]=React.useState(""),W=React.useRef(null),q=React.useRef(!1),H=React.useCallback(G=>{q.current!==G&&(q.current=G,V?.(G))},[V]),$=React.useCallback(G=>{z(G.target.value),H(!0),W.current&&clearTimeout(W.current),W.current=setTimeout(()=>H(!1),1500)},[H]);React.useEffect(()=>()=>{W.current&&clearTimeout(W.current)},[]);const Q=React.useCallback(()=>{const G=B.trim();G&&(T?.(G),z(""),H(!1),W.current&&clearTimeout(W.current))},[B,T,H]),U=React.useCallback(G=>{G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),Q())},[Q]),J="flex items-center justify-center w-9 h-9 rounded-full flex-shrink-0 transition-opacity hover:opacity-90";return jsxRuntime.jsxs("div",{"data-testid":"unified-bottom-bar",className:"flex items-center gap-2 px-3 py-2.5 border-t border-gray-200 bg-gray-50",style:{borderBottomLeftRadius:"16px",borderBottomRightRadius:"16px"},children:[L&&R&&jsxRuntime.jsx("button",{"data-testid":"mic-toggle",type:"button",onClick:R,"aria-label":n?"Unmute microphone":"Mute microphone",className:J,style:{background:n?"#fee2e2":"var(--wysdym-primary-light, #f3e8ef)",color:n?"#dc2626":"var(--wysdym-primary, #BA6296)"},children:n?MIC_OFF_ICON:MIC_ON_ICON}),jsxRuntime.jsxs("div",{className:"flex-1 flex items-center min-w-0 h-9 bg-white rounded-full border border-gray-200 px-3 gap-2",children:[jsxRuntime.jsx("input",{"data-testid":"text-input-field",type:"text",value:B,onChange:$,onKeyDown:U,placeholder:j,className:"flex-1 min-w-0 py-0 bg-transparent outline-none text-sm text-gray-900 placeholder-gray-400"}),B.trim()&&jsxRuntime.jsx("button",{"data-testid":"text-send-button",onClick:Q,"aria-label":"Send message",className:"flex items-center justify-center w-7 h-7 rounded-full flex-shrink-0 transition-opacity hover:opacity-90",style:{background:"var(--wysdym-primary, #BA6296)",color:"#fff"},children:SEND_ICON})]}),L&&A&&jsxRuntime.jsx("button",{"data-testid":"speaker-toggle",type:"button",onClick:A,"aria-label":P?"Unmute agent":"Mute agent",className:J,style:{background:P?"#fee2e2":"var(--wysdym-primary-light, #f3e8ef)",color:P?"#dc2626":"var(--wysdym-primary, #BA6296)"},children:P?SPEAKER_OFF_ICON:SPEAKER_ON_ICON}),N&&jsxRuntime.jsxs("button",{"data-testid":"bottom-bar-cta",type:"button",onClick:N.onClick,className:"flex items-center justify-center gap-2 flex-shrink-0 whitespace-nowrap text-sm font-medium transition-opacity hover:opacity-90 rounded-full",style:{padding:"8px 16px",background:"var(--wysdym-primary, #BA6296)",color:"#fff"},children:[jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),jsxRuntime.jsx("span",{className:"truncate max-w-[120px]",children:N.label})]}),L&&O&&jsxRuntime.jsx("button",{"data-testid":"end-call-button",type:"button",onClick:O,"aria-label":"End call",className:J,style:{background:"#dc2626",color:"#fff"},children:END_CALL_ICON})]})},DEFAULT_MAX=4,NudgeTokens=({suggestions:T,maxVisible:n=DEFAULT_MAX,onSelect:P})=>{const R=T.slice(0,n),A=React.useCallback(L=>{P?.(L)},[P]);return R.length===0?null:jsxRuntime.jsx("div",{"data-testid":"nudge-tokens",role:"group","aria-label":"Suggested responses",style:{display:"flex",flexWrap:"wrap",gap:"6px",padding:"6px 12px",flexShrink:0},children:R.map(L=>jsxRuntime.jsx("button",{"data-testid":"nudge-chip",type:"button",onClick:()=>A(L),style:{padding:"4px 12px",borderRadius:"9999px",fontSize:"12px",border:"1px solid var(--wysdym-primary, #BA6296)",color:"var(--wysdym-primary, #BA6296)",background:"transparent",cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},children:L},L))})},EXPAND_ICON=jsxRuntime.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("polyline",{points:"15 3 21 3 21 9"}),jsxRuntime.jsx("polyline",{points:"9 21 3 21 3 15"}),jsxRuntime.jsx("line",{x1:"21",x2:"14",y1:"3",y2:"10"}),jsxRuntime.jsx("line",{x1:"3",x2:"10",y1:"21",y2:"14"})]}),DOWNLOAD_ICON=jsxRuntime.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsxRuntime.jsx("polyline",{points:"7 10 12 15 17 10"}),jsxRuntime.jsx("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),CLOSE_ICON=jsxRuntime.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"18",x2:"6",y1:"6",y2:"18"}),jsxRuntime.jsx("line",{x1:"6",x2:"18",y1:"6",y2:"18"})]}),TOOLBAR_BTN_STYLE={display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",borderRadius:"50%",border:"none",background:"rgba(255,255,255,0.25)",backdropFilter:"blur(8px)",cursor:"pointer",padding:0,color:"#fff",transition:"background 0.15s ease"};function renderMastheadContent(T,n){const P={width:"100%",height:"100%",objectFit:"contain",display:"block"},R={width:"100%",height:"100%",border:"none",borderRadius:n?"0":"16px 16px 0 0"};switch(T.type){case"image":return jsxRuntime.jsx("img",{"data-testid":"showme-content",src:T.url,alt:T.alt??"",style:P});case"pdf":case"url":return jsxRuntime.jsx("iframe",{"data-testid":"showme-content",src:T.url,title:T.type==="pdf"?T.title??"Document":T.title??"Page",style:R});case"html":return jsxRuntime.jsx("div",{"data-testid":"showme-content",dangerouslySetInnerHTML:{__html:T.html},style:{padding:"16px",height:"100%",overflow:"auto"}})}}const ShowMePanel=({content:T,primaryColor:n="#BA6296",secondaryColor:P="#A0527A",isFullScreen:R=!1,onClose:A,onExpand:L,onDownload:O})=>{if(!T)return null;const N=()=>{if(O){O();return}(T.type==="image"||T.type==="pdf"||T.type==="url")&&window.open(T.url,"_blank")};return R?jsxRuntime.jsxs("div",{"data-testid":"showme-panel-fullscreen",role:"region","aria-label":"Visual content - expanded",className:"flex-shrink-0",style:{position:"relative",background:`linear-gradient(135deg, ${n} 0%, ${P} 100%)`,borderRadius:"16px 16px 0 0",overflow:"hidden"},children:[jsxRuntime.jsxs("div",{style:{position:"absolute",top:"10px",right:"10px",display:"flex",gap:"6px",zIndex:2},children:[jsxRuntime.jsx("button",{"data-testid":"showme-download",type:"button",onClick:N,"aria-label":"Download",style:TOOLBAR_BTN_STYLE,children:DOWNLOAD_ICON}),jsxRuntime.jsx("button",{"data-testid":"showme-close",type:"button",onClick:A,"aria-label":"Close visual content",style:TOOLBAR_BTN_STYLE,children:CLOSE_ICON})]}),jsxRuntime.jsx("div",{style:{maxHeight:"50vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"8px",overflow:"hidden"},children:renderMastheadContent(T,!0)})]}):jsxRuntime.jsxs("div",{"data-testid":"showme-panel",role:"region","aria-label":"Visual content",className:"flex-shrink-0",style:{position:"relative",background:`linear-gradient(135deg, ${n} 0%, ${P} 100%)`,borderRadius:"16px 16px 0 0",overflow:"hidden"},children:[jsxRuntime.jsxs("div",{style:{position:"absolute",top:"10px",right:"10px",display:"flex",gap:"6px",zIndex:2},children:[L&&jsxRuntime.jsx("button",{"data-testid":"showme-expand",type:"button",onClick:L,"aria-label":"Expand visual content",style:TOOLBAR_BTN_STYLE,children:EXPAND_ICON}),jsxRuntime.jsx("button",{"data-testid":"showme-download",type:"button",onClick:N,"aria-label":"Download",style:TOOLBAR_BTN_STYLE,children:DOWNLOAD_ICON}),jsxRuntime.jsx("button",{"data-testid":"showme-close",type:"button",onClick:A,"aria-label":"Close visual content",style:TOOLBAR_BTN_STYLE,children:CLOSE_ICON})]}),jsxRuntime.jsx("div",{style:{maxHeight:"35vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"8px",overflow:"hidden"},children:renderMastheadContent(T,!1)})]})},ProactiveTooltip=({text:T,primaryColor:n,onClose:P})=>jsxRuntime.jsxs("div",{role:"tooltip",className:"wysdym-proactive-tooltip",style:{position:"absolute",bottom:"100%",marginBottom:"12px",right:0,maxWidth:"220px",borderRadius:"12px",padding:"12px 16px",boxShadow:`0 4px 20px ${n}40`,backgroundColor:n,color:"#fff",fontSize:"12px",lineHeight:1.5},children:[T,jsxRuntime.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),P()},"aria-label":"Dismiss",style:{position:"absolute",top:"4px",right:"4px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"rgba(255,255,255,0.3)",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:R=>{R.currentTarget.style.backgroundColor="rgba(255,255,255,0.5)"},onMouseLeave:R=>{R.currentTarget.style.backgroundColor="rgba(255,255,255,0.3)"},children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntime.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"-6px",right:"20px",width:"12px",height:"12px",backgroundColor:n,transform:"rotate(45deg)"}})]}),SHOW_DELAY_MS=4e3,AUTO_DISMISS_MS=9e3,CollapsedFloatingTrigger=({primaryColor:T,triggerText:n,buttonIcon:P,buttonText:R,onExpand:A,greetingTooltipEnabled:L=!0,greetingTooltipText:O,agentFirstMessage:N,agentName:V="your assistant"})=>{const[j,B]=React.useState(!1),z=React.useRef(null),W=React.useRef(null),q=resolveIcon(P);React.useEffect(()=>{if(!L){B(!1);return}return z.current=setTimeout(()=>B(!0),SHOW_DELAY_MS),W.current=setTimeout(()=>B(!1),AUTO_DISMISS_MS),()=>{z.current&&clearTimeout(z.current),W.current&&clearTimeout(W.current)}},[L]);const H=O?.trim()||n?.trim()||N?.trim()||`Hi! I'm ${V}. How can I help?`,$=R?.trim()||n?.trim()||"Open chat",Q=!!R?.trim(),U={height:"56px",borderRadius:Q?28:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:8,paddingLeft:Q?16:0,paddingRight:Q?20:0,width:Q?"auto":56,minWidth:Q?void 0:56,backgroundColor:T,boxShadow:`0 0 20px ${T}55, 0 0 40px ${T}30, 0 4px 14px rgba(0,0,0,0.25)`,transition:"transform 0.2s ease, box-shadow 0.2s ease"};return jsxRuntime.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:0},children:[j&&L&&jsxRuntime.jsx(ProactiveTooltip,{text:H,primaryColor:T,onClose:()=>B(!1)}),jsxRuntime.jsxs("button",{type:"button",onClick:A,"aria-label":$,style:U,onMouseEnter:J=>{J.currentTarget.style.transform="scale(1.05)",J.currentTarget.style.boxShadow=`0 0 24px ${T}66, 0 0 48px ${T}40, 0 6px 18px rgba(0,0,0,0.28)`},onMouseLeave:J=>{J.currentTarget.style.transform="scale(1)",J.currentTarget.style.boxShadow=`0 0 20px ${T}55, 0 0 40px ${T}30, 0 4px 14px rgba(0,0,0,0.25)`},children:[jsxRuntime.jsx(q,{style:{width:24,height:24,color:"#fff",flexShrink:0}}),Q&&jsxRuntime.jsx("span",{style:{color:"#fff",fontWeight:600,fontSize:15,whiteSpace:"nowrap"},children:R.trim()})]})]})},INITIAL_HEALTH={isConnected:!1,latencyMs:null,lastHeartbeat:null},useVoiceStore=createStore()((T,n)=>({connectionState:"disconnected",isMicMuted:!1,isAgentMuted:!1,agentStatus:"idle",audioData:null,connectionHealth:{...INITIAL_HEALTH},setConnectionState:P=>T({connectionState:P}),toggleMic:()=>T({isMicMuted:!n().isMicMuted}),toggleAgentAudio:()=>T({isAgentMuted:!n().isAgentMuted}),setAgentStatus:P=>T({agentStatus:P}),setAudioData:P=>T({audioData:P}),setConnectionHealth:P=>T({connectionHealth:P}),reset:()=>T({connectionState:"disconnected",isMicMuted:!1,isAgentMuted:!1,agentStatus:"idle",audioData:null,connectionHealth:{...INITIAL_HEALTH}})})),ChatWidget=({companyToken:T,agentId:n,primaryColor:P="#BA6296",secondaryColor:R="#A0527A",widgetTriggerText:A="Need help?",widgetTriggerButtonText:L="Start a call",widgetTriggerButtonIcon:O="Phone",isExpanded:N=!1,onExpandChange:V,backendUrl:j,mode:B="floating",greetingTooltipEnabled:z=!0,greetingTooltipText:W,initialAgentName:q,initialAgentFirstMessage:H})=>{const $=React.useRef(null);if(!$.current){const ke=j||getCurrentApiUrl();$.current=new AnalyticsService({baseUrl:ke,companyToken:T,agentId:n,sessionId:void 0})}const Q=$.current,U=useWidgetStore({companyToken:T,agentId:n,analyticsService:Q,mode:B,initialExpanded:N}),J=React.useRef(!1),G=U.agent?.widget_trigger_text??A,K=U.agent?.widget_trigger_button_text??L,Y=U.agent?.widget_trigger_button_icon??O,Z=ke=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ke.trim()),ie=(U.showEmailFormRequestedByAgent||!!U.agent?.require_email)&&!U.emailSubmitted&&(!U.sessionHasEmail||U.forceDisplayEmailForm||!!U.agent?.force_display_email),[se,le]=React.useState(null),[pe,ue]=React.useState(!1);React.useEffect(()=>{const ke=xe=>{const Oe=xe.detail?.asset;if(!Oe)return;const De=Ne=>{if(!Ne||Ne.startsWith("http://")||Ne.startsWith("https://"))return Ne;const je=getCurrentBackendUrl();return Ne.startsWith("/")?`${je}${Ne}`:`${je}/${Ne.replace(/^\//,"")}`},We=Oe.storage_url?De(Oe.storage_url):void 0,Fe=Oe.external_url?De(Oe.external_url):void 0;let qe=null;Oe.asset_type==="image"&&We?qe={type:"image",url:We,alt:Oe.asset_name}:Oe.asset_type==="video"&&Fe?qe={type:"url",url:Fe,title:Oe.asset_name}:Fe?qe={type:"url",url:Fe,title:Oe.asset_name}:We&&(qe={type:"url",url:We,title:Oe.asset_name}),qe&&(le(qe),ue(!1))},Ce=()=>{le(null),ue(!1)};return window.addEventListener("show_asset",ke),window.addEventListener("close_asset",Ce),()=>{window.removeEventListener("show_asset",ke),window.removeEventListener("close_asset",Ce)}},[]);const he=React.useRef([]);React.useEffect(()=>{const ke=he.current,Ce=U.messages.map((xe,we)=>({role:xe.role==="assistant"?"agent":"user",text:xe.content,source:xe.source||"voice",timestamp:we<ke.length?ke[we]:Date.now(),isFinal:!0}));he.current=Ce.map(xe=>xe.timestamp),useConversationStore.getState().setMessages(Ce)},[U.messages]),React.useEffect(()=>{const ke=useVoiceStore.getState();ke.setConnectionState(U.connectionState);let Ce;U.aiStatus==="calling_tool"?Ce="calling_tool":U.aiStatus==="thinking"?Ce="thinking":U.isAgentSpeaking?Ce="speaking":U.isListening?Ce="listening":Ce="idle",ke.setAgentStatus(Ce),U.audioData&&ke.setAudioData(U.audioData)},[U.connectionState,U.aiStatus,U.isAgentSpeaking,U.isListening,U.audioData]),React.useEffect(()=>{U.agent&&useAgentConfigStore.getState().setConfig({id:U.agent.id,company_id:U.agent.company_id,name:U.agent.name,description:null,agent_first_message:U.agent.agent_first_message,agent_instructions:U.agent.agent_instructions||null,elevenlabs_agent_id:null,elevenlabs_voice_id:U.agent.elevenlabs_voice_id||null,require_email:U.agent.require_email,product:null,template_id:null,primary_color:P,secondary_color:R,widget_trigger_text:null,widget_trigger_button_text:null,widget_trigger_button_icon:null,email_collection_button_text:null,email_collection_button_icon:null,force_display_email:!1})},[U.agent,P,R]),React.useEffect(()=>{if(U.isExpanded)J.current=!0,Q.trackWidgetOpen();else if(J.current){Q.trackWidgetClose();const ke=U.widgetJwt||U.bootstrapJwt;U.sessionId&&ke&&fetch(`${getCurrentApiUrl()}/api/widget/session/${U.sessionId}/end`,{method:"POST",headers:{Authorization:`Bearer ${ke}`,"Content-Type":"application/json"},keepalive:!0}).catch(()=>{}),window.dispatchEvent(new CustomEvent("wysdym-widget-collapsed"))}},[U.isExpanded]),React.useEffect(()=>{U.demoStarted&&U.sessionId&&(Q.updateSessionId(U.sessionId),Q.trackSessionStart())},[U.demoStarted,U.sessionId]),React.useEffect(()=>{U.isLoading&&!U.agent?Q.trackAgentLoadStart():U.agent&&!U.isLoading&&Q.trackAgentLoadSuccess()},[U.isLoading,U.agent]),React.useEffect(()=>{U.error&&Q.trackError("Widget Error","WIDGET_ERROR",U.error)},[U.error]),React.useEffect(()=>{const ke=()=>{Q?.trackPageVisibilityChange(document.visibilityState==="visible")};return document.addEventListener("visibilitychange",ke),()=>document.removeEventListener("visibilitychange",ke)},[]),React.useEffect(()=>{N&&!U.isExpanded&&U.expandWidget()},[]),React.useEffect(()=>{U.isExpanded!==N&&V&&V(U.isExpanded)},[U.isExpanded,N,V]),React.useEffect(()=>{const ke=Ce=>{const xe=Ce.detail;xe.session_id===U.sessionId&&xe.message&&setTimeout(()=>{U.addMessage({role:"assistant",content:xe.message})},0)};return window.addEventListener("agent_response",ke),()=>window.removeEventListener("agent_response",ke)},[U.sessionId,U.addMessage]),React.useEffect(()=>{let ke;const Ce=()=>{ke=setInterval(async()=>{if(U.bootstrapJwt&&U.sessionId)try{const xe=await fetch(`${getCurrentApiUrl()}/api/widget/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${U.bootstrapJwt}`,"Content-Type":"application/json"},body:JSON.stringify({session_id:U.sessionId})});if(xe.ok){const{widget_jwt:we}=await xe.json();U.updateWidgetJwt(we)}}catch(xe){console.error("[ChatWidget] JWT refresh error:",xe)}},24e4)};return U.bootstrapJwt&&U.sessionId&&Ce(),()=>{ke&&clearInterval(ke)}},[U.bootstrapJwt,U.sessionId]);const ve=React.useCallback(ke=>{const Ce=ke.trim();if(!Ce)return;if((U.showEmailFormRequestedByAgent||!!U.agent?.require_email)&&!U.emailSubmitted&&(!U.sessionHasEmail||U.forceDisplayEmailForm||!!U.agent?.force_display_email)&&Z(Ce)){U.handleEmailSubmit(Ce);return}U.sendTextDuringVoice(Ce)},[U.sendTextDuringVoice,U.handleEmailSubmit,U.showEmailFormRequestedByAgent,U.agent?.require_email,U.emailSubmitted,U.sessionHasEmail,U.forceDisplayEmailForm,U.agent?.force_display_email]),be=React.useCallback(()=>{const ke=useVoiceStore.getState(),Ce=!ke.isMicMuted;ke.toggleMic(),U.muteMicrophone(Ce)},[U.muteMicrophone]),fe=React.useCallback(()=>{const ke=useVoiceStore.getState(),Ce=!ke.isAgentMuted;ke.toggleAgentAudio(),U.muteAgentAudio(Ce)},[U.muteAgentAudio]),ne=React.useCallback(ke=>{U.sendTextDuringVoice(ke)},[U.sendTextDuringVoice]),ce=React.useRef(!1),ee=React.useRef(null),te=React.useRef(null);te.current=U.sessionId&&U.widgetJwt?{sessionId:U.sessionId,widgetJwt:U.widgetJwt}:null;const oe=React.useCallback(ke=>{const Ce=te.current;Ce&&fetch(buildApiUrl(`api/widget/session/${Ce.sessionId}/typing`),{method:"POST",headers:{Authorization:`Bearer ${Ce.widgetJwt}`,"Content-Type":"application/json"},body:JSON.stringify({is_typing:ke})}).catch(()=>{})},[]),ae=React.useCallback(ke=>{const Ce=useVoiceStore.getState();ke&&!Ce.isAgentMuted?(ce.current=!1,Ce.toggleAgentAudio(),U.muteAgentAudio(!0)):!ke&&!ce.current&&Ce.isAgentMuted&&(Ce.toggleAgentAudio(),U.muteAgentAudio(!1)),ke&&U.sendUserActivity&&U.sendUserActivity(),oe(ke),ee.current&&(clearInterval(ee.current),ee.current=null),ke&&(ee.current=setInterval(()=>{U.sendUserActivity&&U.sendUserActivity(),oe(!0)},2e3))},[U.muteAgentAudio,U.sendUserActivity,oe]);React.useEffect(()=>()=>{ee.current&&clearInterval(ee.current)},[]);const de=React.useMemo(()=>!U.customCta||!U.customCta.is_active?null:{type:"link",label:U.customCta.button_text,url:U.customCta.href},[U.customCta]),ge=React.useSyncExternalStore(useVoiceStore.subscribe,()=>useVoiceStore.getState().isMicMuted),ye=React.useSyncExternalStore(useVoiceStore.subscribe,()=>useVoiceStore.getState().isAgentMuted),Ee=React.useMemo(()=>U.aiStatus==="calling_tool"?"calling_tool":U.aiStatus==="thinking"?"thinking":U.isAgentSpeaking?"speaking":U.isListening?"listening":"idle",[U.aiStatus,U.isAgentSpeaking,U.isListening]),Pe=useStore(useConversationStore,ke=>ke.messages),[Ie,Ae]=React.useState([]),Le=React.useRef(0),Me=React.useRef(0);if(React.useEffect(()=>{if(!U.agent){Ae([]);return}const ke=Pe.length;if(ke===Me.current&&Ie.length>0||ke>0&&ke-Me.current<2&&Me.current>0)return;Me.current=ke;const Ce=++Le.current,xe=U.widgetJwt||U.bootstrapJwt;if(!xe)return;const we=j||getCurrentApiUrl(),Oe={agent_name:U.agent.name||void 0,agent_description:U.agent.description||void 0,messages:Pe.map(De=>({role:De.role==="agent"?"assistant":"user",content:De.text}))};fetch(`${we}/api/widget/nudges/suggestions`,{method:"POST",headers:{Authorization:`Bearer ${xe}`,"Content-Type":"application/json"},body:JSON.stringify(Oe)}).then(De=>De.ok?De.json():Promise.reject(De.status)).then(De=>{Ce===Le.current&&Array.isArray(De.suggestions)&&Ae(De.suggestions.slice(0,4))}).catch(De=>{console.warn("[ChatWidget] Nudge fetch failed:",De)})},[U.agent,Pe,U.widgetJwt,U.bootstrapJwt,j]),U.isLoading)return jsxRuntime.jsx(LoadingState,{primaryColor:P});if(U.error)return jsxRuntime.jsx(ErrorState,{});if(B==="inline")return jsxRuntime.jsx(FloatingWidgetButton,{primaryColor:P,secondaryColor:R,triggerText:G,buttonText:U.demoStarted?"End Call":K,buttonIcon:Y,onExpand:()=>{U.demoStarted?U.endCall():U.startDirectSession()},hasActiveSession:U.demoStarted,audioData:U.audioData,isAgentSpeaking:U.isAgentSpeaking,customCta:U.customCta,onCtaClick:U.handleCtaClick,isConnected:U.isConnected,callDuration:U.callDuration,onEndCall:U.endCall,mode:"inline"});if(U.isExpanded){const ke=!!se;return jsxRuntime.jsxs("div",{className:"wysdym-widget-expanded-mobile sm:wysdym-widget-expanded",style:{"--wysdym-primary":P,"--wysdym-primary-light":`${P}18`,display:"flex",flexDirection:"column",maxHeight:"95vh",width:"100%"},"data-wysdym-widget":!0,children:[ke&&jsxRuntime.jsx(ShowMePanel,{content:se,primaryColor:P,secondaryColor:R,isFullScreen:pe,onClose:()=>le(null),onExpand:()=>ue(!0)}),jsxRuntime.jsxs("div",{style:{height:"650px",maxHeight:ke?"55vh":"85vh",overflow:"hidden",display:"flex",flexDirection:"column",background:"#fff",borderRadius:ke?"0 0 16px 16px":"16px",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",border:"1px solid #e5e7eb"},children:[!ke&&jsxRuntime.jsx(WidgetHeader,{primaryColor:P,secondaryColor:R,onClose:U.closeWidget}),U.demoStarted&&Ee!=="idle"&&jsxRuntime.jsx("div",{className:"px-4 py-2 flex-shrink-0",children:jsxRuntime.jsx(AIStatusIndicator,{status:Ee,toolName:U.currentToolName,micLevel:U.micLevel})}),jsxRuntime.jsx("div",{className:"flex-1 flex flex-col overflow-hidden min-h-0",children:U.canResumeSession?(()=>{const Ce=loadSession();return jsxRuntime.jsx(SessionResumePrompt,{primaryColor:P,messageCount:Ce?.conversationState?.messageCount||0,lastMessage:Ce?.conversationState?.lastMessage,onResume:U.resumeSession,onStartNew:U.endSession,isLoading:U.isLoading})})():U.demoStarted?jsxRuntime.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[U.showReconnectionPrompt&&jsxRuntime.jsx(VoiceReconnectionPrompt,{onReconnect:U.manualReconnect,isReconnecting:U.isReconnecting,primaryColor:P,reason:U.disconnectionReason}),U.sessionId&&U.widgetJwt&&U.hasActiveForm&&jsxRuntime.jsx("div",{className:"flex-1 flex items-center justify-center",children:jsxRuntime.jsx(DynamicUIRenderer,{sessionId:U.sessionId,token:U.widgetJwt,onFormStateChange:U.setHasActiveForm,onFormSubmit:()=>{U.showReconnectionPrompt&&setTimeout(()=>U.manualReconnect(),1e3)}})}),U.sessionId&&U.widgetJwt&&!U.hasActiveForm&&jsxRuntime.jsx("div",{className:"hidden",children:jsxRuntime.jsx(DynamicUIRenderer,{sessionId:U.sessionId,token:U.widgetJwt,onFormStateChange:U.setHasActiveForm,onFormSubmit:()=>{}})}),!U.showReconnectionPrompt&&!U.hasActiveForm&&jsxRuntime.jsx("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:jsxRuntime.jsx(Transcript,{})})]}):!U.agent&&!U.isInitializing?jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Failed to load agent"}),jsxRuntime.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"There was an issue loading the agent. Please try again."}),jsxRuntime.jsx("button",{onClick:()=>U.loadAgent(),className:"px-6 py-3 text-white rounded-lg font-medium hover:opacity-90 transition-opacity",style:{backgroundColor:P},children:"Retry"})]}):jsxRuntime.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center py-8",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Starting conversation..."}),jsxRuntime.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Please wait while we connect you to our AI agent."}),jsxRuntime.jsx("div",{className:"w-8 h-8 border-2 border-gray-300 rounded-full animate-spin",style:{borderTopColor:P}})]})}),U.demoStarted&&!U.showReconnectionPrompt&&!U.hasActiveForm&&jsxRuntime.jsxs("div",{className:"flex-shrink-0",children:[ie&&jsxRuntime.jsxs("div",{className:"px-4 py-2 border-t border-gray-100 bg-blue-50/80",children:[jsxRuntime.jsx("p",{className:"text-sm text-blue-800",children:"Please type your email address in the box below so we can follow up."}),U.emailError&&jsxRuntime.jsx("p",{className:"mt-1 text-xs text-red-600",children:U.emailError})]}),jsxRuntime.jsx(NudgeTokens,{suggestions:Ie,onSelect:ne}),jsxRuntime.jsx(TextInput,{onSend:ve,isMicMuted:ge,isAgentMuted:ye,onToggleMic:be,onToggleAgentAudio:fe,isConnected:U.isConnected,onEndCall:U.endCall,cta:de?{label:de.label,onClick:()=>U.customCta&&U.handleCtaClick?.(U.customCta)}:null,onTypingChange:ae,placeholder:ie?"Enter your email address":void 0})]})]})]})}return jsxRuntime.jsx(CollapsedFloatingTrigger,{primaryColor:P,triggerText:G,buttonIcon:Y,buttonText:K,onExpand:()=>U.expandWidget(),greetingTooltipEnabled:z,greetingTooltipText:W,agentFirstMessage:U.agent?.agent_first_message??H,agentName:U.agent?.name??q})};async function fetchAgentConfig(T,n){const P=n??getCurrentApiUrl();try{const R=await fetch(`${P}/api/widget/bootstrap?agent_id=${encodeURIComponent(T)}`);if(!R.ok)return null;const{access_token:A}=await R.json();if(!A)return null;const L=await fetch(`${P}/api/widget/session/agent-config/${T}`,{headers:{Authorization:`Bearer ${A}`}});return L.ok?await L.json():null}catch{return null}}const agentConfig=Object.freeze(Object.defineProperty({__proto__:null,fetchAgentConfig},Symbol.toStringTag,{value:"Module"})),combinedCSS=`/* Shadow DOM provides CSS isolation — minimal reset replaces full Preflight. */
|
|
736
|
+
.container {
|
|
737
|
+
width: 100%;
|
|
738
|
+
}
|
|
739
|
+
@media (min-width: 640px) {
|
|
740
|
+
.container {
|
|
741
|
+
max-width: 640px;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
@media (min-width: 768px) {
|
|
745
|
+
.container {
|
|
746
|
+
max-width: 768px;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
@media (min-width: 1024px) {
|
|
750
|
+
.container {
|
|
751
|
+
max-width: 1024px;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
@media (min-width: 1280px) {
|
|
755
|
+
.container {
|
|
756
|
+
max-width: 1280px;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
@media (min-width: 1536px) {
|
|
760
|
+
.container {
|
|
761
|
+
max-width: 1536px;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
.wysdym-widget-container .pointer-events-none {
|
|
765
|
+
pointer-events: none;
|
|
766
|
+
}
|
|
767
|
+
.wysdym-widget-container .visible {
|
|
768
|
+
visibility: visible;
|
|
769
|
+
}
|
|
770
|
+
.wysdym-widget-container .collapse {
|
|
771
|
+
visibility: collapse;
|
|
772
|
+
}
|
|
773
|
+
.wysdym-widget-container .static {
|
|
774
|
+
position: static;
|
|
775
|
+
}
|
|
776
|
+
.wysdym-widget-container .fixed {
|
|
777
|
+
position: fixed;
|
|
778
|
+
}
|
|
779
|
+
.wysdym-widget-container .absolute {
|
|
780
|
+
position: absolute;
|
|
781
|
+
}
|
|
782
|
+
.wysdym-widget-container .relative {
|
|
783
|
+
position: relative;
|
|
784
|
+
}
|
|
785
|
+
.wysdym-widget-container .inset-0 {
|
|
786
|
+
inset: 0px;
|
|
787
|
+
}
|
|
788
|
+
.wysdym-widget-container .bottom-4 {
|
|
789
|
+
bottom: 1rem;
|
|
790
|
+
}
|
|
791
|
+
.wysdym-widget-container .right-0 {
|
|
792
|
+
right: 0px;
|
|
793
|
+
}
|
|
794
|
+
.wysdym-widget-container .right-4 {
|
|
795
|
+
right: 1rem;
|
|
796
|
+
}
|
|
797
|
+
.wysdym-widget-container .top-0 {
|
|
798
|
+
top: 0px;
|
|
799
|
+
}
|
|
800
|
+
.wysdym-widget-container .top-full {
|
|
801
|
+
top: 100%;
|
|
802
|
+
}
|
|
803
|
+
.wysdym-widget-container .z-10 {
|
|
804
|
+
z-index: 10;
|
|
805
|
+
}
|
|
806
|
+
.wysdym-widget-container .z-50 {
|
|
807
|
+
z-index: 50;
|
|
808
|
+
}
|
|
809
|
+
.wysdym-widget-container .mx-1 {
|
|
810
|
+
margin-left: 0.25rem;
|
|
811
|
+
margin-right: 0.25rem;
|
|
812
|
+
}
|
|
813
|
+
.wysdym-widget-container .mx-auto {
|
|
814
|
+
margin-left: auto;
|
|
815
|
+
margin-right: auto;
|
|
816
|
+
}
|
|
817
|
+
.wysdym-widget-container .mb-1 {
|
|
818
|
+
margin-bottom: 0.25rem;
|
|
819
|
+
}
|
|
820
|
+
.wysdym-widget-container .mb-12 {
|
|
821
|
+
margin-bottom: 3rem;
|
|
822
|
+
}
|
|
823
|
+
.wysdym-widget-container .mb-2 {
|
|
824
|
+
margin-bottom: 0.5rem;
|
|
825
|
+
}
|
|
826
|
+
.wysdym-widget-container .mb-3 {
|
|
827
|
+
margin-bottom: 0.75rem;
|
|
828
|
+
}
|
|
829
|
+
.wysdym-widget-container .mb-4 {
|
|
830
|
+
margin-bottom: 1rem;
|
|
831
|
+
}
|
|
832
|
+
.wysdym-widget-container .mb-6 {
|
|
833
|
+
margin-bottom: 1.5rem;
|
|
834
|
+
}
|
|
835
|
+
.wysdym-widget-container .mb-8 {
|
|
836
|
+
margin-bottom: 2rem;
|
|
837
|
+
}
|
|
838
|
+
.wysdym-widget-container .ml-1 {
|
|
839
|
+
margin-left: 0.25rem;
|
|
840
|
+
}
|
|
841
|
+
.wysdym-widget-container .mr-1 {
|
|
842
|
+
margin-right: 0.25rem;
|
|
843
|
+
}
|
|
844
|
+
.wysdym-widget-container .mr-3 {
|
|
845
|
+
margin-right: 0.75rem;
|
|
846
|
+
}
|
|
847
|
+
.wysdym-widget-container .mt-0\\.5 {
|
|
848
|
+
margin-top: 0.125rem;
|
|
849
|
+
}
|
|
850
|
+
.wysdym-widget-container .mt-1 {
|
|
851
|
+
margin-top: 0.25rem;
|
|
852
|
+
}
|
|
853
|
+
.wysdym-widget-container .mt-2 {
|
|
854
|
+
margin-top: 0.5rem;
|
|
855
|
+
}
|
|
856
|
+
.wysdym-widget-container .mt-3 {
|
|
857
|
+
margin-top: 0.75rem;
|
|
858
|
+
}
|
|
859
|
+
.wysdym-widget-container .mt-4 {
|
|
860
|
+
margin-top: 1rem;
|
|
861
|
+
}
|
|
862
|
+
.wysdym-widget-container .mt-6 {
|
|
863
|
+
margin-top: 1.5rem;
|
|
864
|
+
}
|
|
865
|
+
.wysdym-widget-container .mt-8 {
|
|
866
|
+
margin-top: 2rem;
|
|
867
|
+
}
|
|
868
|
+
.wysdym-widget-container .block {
|
|
869
|
+
display: block;
|
|
870
|
+
}
|
|
871
|
+
.wysdym-widget-container .inline-block {
|
|
872
|
+
display: inline-block;
|
|
873
|
+
}
|
|
874
|
+
.wysdym-widget-container .inline {
|
|
875
|
+
display: inline;
|
|
876
|
+
}
|
|
877
|
+
.wysdym-widget-container .flex {
|
|
878
|
+
display: flex;
|
|
879
|
+
}
|
|
880
|
+
.wysdym-widget-container .inline-flex {
|
|
881
|
+
display: inline-flex;
|
|
882
|
+
}
|
|
883
|
+
.wysdym-widget-container .grid {
|
|
884
|
+
display: grid;
|
|
885
|
+
}
|
|
886
|
+
.wysdym-widget-container .hidden {
|
|
887
|
+
display: none;
|
|
888
|
+
}
|
|
889
|
+
.wysdym-widget-container .h-0 {
|
|
890
|
+
height: 0px;
|
|
891
|
+
}
|
|
892
|
+
.wysdym-widget-container .h-10 {
|
|
893
|
+
height: 2.5rem;
|
|
894
|
+
}
|
|
895
|
+
.wysdym-widget-container .h-16 {
|
|
896
|
+
height: 4rem;
|
|
897
|
+
}
|
|
898
|
+
.wysdym-widget-container .h-3 {
|
|
899
|
+
height: 0.75rem;
|
|
900
|
+
}
|
|
901
|
+
.wysdym-widget-container .h-3\\.5 {
|
|
902
|
+
height: 0.875rem;
|
|
903
|
+
}
|
|
904
|
+
.wysdym-widget-container .h-4 {
|
|
905
|
+
height: 1rem;
|
|
906
|
+
}
|
|
907
|
+
.wysdym-widget-container .h-48 {
|
|
908
|
+
height: 12rem;
|
|
909
|
+
}
|
|
910
|
+
.wysdym-widget-container .h-5 {
|
|
911
|
+
height: 1.25rem;
|
|
912
|
+
}
|
|
913
|
+
.wysdym-widget-container .h-6 {
|
|
914
|
+
height: 1.5rem;
|
|
915
|
+
}
|
|
916
|
+
.wysdym-widget-container .h-7 {
|
|
917
|
+
height: 1.75rem;
|
|
918
|
+
}
|
|
919
|
+
.wysdym-widget-container .h-8 {
|
|
920
|
+
height: 2rem;
|
|
921
|
+
}
|
|
922
|
+
.wysdym-widget-container .h-9 {
|
|
923
|
+
height: 2.25rem;
|
|
924
|
+
}
|
|
925
|
+
.wysdym-widget-container .h-96 {
|
|
926
|
+
height: 24rem;
|
|
927
|
+
}
|
|
928
|
+
.wysdym-widget-container .h-auto {
|
|
929
|
+
height: auto;
|
|
930
|
+
}
|
|
931
|
+
.wysdym-widget-container .h-full {
|
|
932
|
+
height: 100%;
|
|
933
|
+
}
|
|
934
|
+
.wysdym-widget-container .min-h-0 {
|
|
935
|
+
min-height: 0px;
|
|
936
|
+
}
|
|
937
|
+
.wysdym-widget-container .min-h-screen {
|
|
938
|
+
min-height: 100vh;
|
|
939
|
+
}
|
|
940
|
+
.wysdym-widget-container .w-1 {
|
|
941
|
+
width: 0.25rem;
|
|
942
|
+
}
|
|
943
|
+
.wysdym-widget-container .w-10 {
|
|
944
|
+
width: 2.5rem;
|
|
945
|
+
}
|
|
946
|
+
.wysdym-widget-container .w-16 {
|
|
947
|
+
width: 4rem;
|
|
948
|
+
}
|
|
949
|
+
.wysdym-widget-container .w-3 {
|
|
950
|
+
width: 0.75rem;
|
|
951
|
+
}
|
|
952
|
+
.wysdym-widget-container .w-3\\.5 {
|
|
953
|
+
width: 0.875rem;
|
|
954
|
+
}
|
|
955
|
+
.wysdym-widget-container .w-4 {
|
|
956
|
+
width: 1rem;
|
|
957
|
+
}
|
|
958
|
+
.wysdym-widget-container .w-48 {
|
|
959
|
+
width: 12rem;
|
|
960
|
+
}
|
|
961
|
+
.wysdym-widget-container .w-5 {
|
|
962
|
+
width: 1.25rem;
|
|
963
|
+
}
|
|
964
|
+
.wysdym-widget-container .w-6 {
|
|
965
|
+
width: 1.5rem;
|
|
966
|
+
}
|
|
967
|
+
.wysdym-widget-container .w-7 {
|
|
968
|
+
width: 1.75rem;
|
|
969
|
+
}
|
|
970
|
+
.wysdym-widget-container .w-72 {
|
|
971
|
+
width: 18rem;
|
|
972
|
+
}
|
|
973
|
+
.wysdym-widget-container .w-8 {
|
|
974
|
+
width: 2rem;
|
|
975
|
+
}
|
|
976
|
+
.wysdym-widget-container .w-80 {
|
|
977
|
+
width: 20rem;
|
|
978
|
+
}
|
|
979
|
+
.wysdym-widget-container .w-9 {
|
|
980
|
+
width: 2.25rem;
|
|
981
|
+
}
|
|
982
|
+
.wysdym-widget-container .w-full {
|
|
983
|
+
width: 100%;
|
|
984
|
+
}
|
|
985
|
+
.wysdym-widget-container .w-px {
|
|
986
|
+
width: 1px;
|
|
987
|
+
}
|
|
988
|
+
.wysdym-widget-container .min-w-0 {
|
|
989
|
+
min-width: 0px;
|
|
990
|
+
}
|
|
991
|
+
.wysdym-widget-container .min-w-\\[60px\\] {
|
|
992
|
+
min-width: 60px;
|
|
993
|
+
}
|
|
994
|
+
.wysdym-widget-container .max-w-6xl {
|
|
995
|
+
max-width: 72rem;
|
|
996
|
+
}
|
|
997
|
+
.wysdym-widget-container .max-w-\\[120px\\] {
|
|
998
|
+
max-width: 120px;
|
|
999
|
+
}
|
|
1000
|
+
.wysdym-widget-container .max-w-\\[calc\\(100vw-2rem\\)\\] {
|
|
1001
|
+
max-width: calc(100vw - 2rem);
|
|
1002
|
+
}
|
|
1003
|
+
.wysdym-widget-container .max-w-full {
|
|
1004
|
+
max-width: 100%;
|
|
1005
|
+
}
|
|
1006
|
+
.wysdym-widget-container .max-w-md {
|
|
1007
|
+
max-width: 28rem;
|
|
1008
|
+
}
|
|
1009
|
+
.wysdym-widget-container .flex-1 {
|
|
1010
|
+
flex: 1 1 0%;
|
|
1011
|
+
}
|
|
1012
|
+
.wysdym-widget-container .flex-shrink-0 {
|
|
1013
|
+
flex-shrink: 0;
|
|
1014
|
+
}
|
|
1015
|
+
.wysdym-widget-container .grow {
|
|
1016
|
+
flex-grow: 1;
|
|
1017
|
+
}
|
|
1018
|
+
.wysdym-widget-container .-translate-y-2 {
|
|
1019
|
+
--tw-translate-y: -0.5rem;
|
|
1020
|
+
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
|
|
1021
|
+
}
|
|
1022
|
+
.wysdym-widget-container .translate-y-0 {
|
|
1023
|
+
--tw-translate-y: 0px;
|
|
1024
|
+
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
|
|
1025
|
+
}
|
|
1026
|
+
.wysdym-widget-container .transform {
|
|
1027
|
+
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
|
|
1028
|
+
}
|
|
1029
|
+
@keyframes pulse {
|
|
1030
|
+
50% {
|
|
1031
|
+
opacity: .5;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
.wysdym-widget-container .animate-pulse {
|
|
1035
|
+
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
|
1036
|
+
}
|
|
1037
|
+
@keyframes spin {
|
|
1038
|
+
to {
|
|
1039
|
+
transform: rotate(360deg);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
.wysdym-widget-container .animate-spin {
|
|
1043
|
+
animation: spin 1s linear infinite;
|
|
1044
|
+
}
|
|
1045
|
+
.wysdym-widget-container .cursor-not-allowed {
|
|
1046
|
+
cursor: not-allowed;
|
|
1047
|
+
}
|
|
1048
|
+
.wysdym-widget-container .cursor-pointer {
|
|
1049
|
+
cursor: pointer;
|
|
1050
|
+
}
|
|
1051
|
+
.wysdym-widget-container .grid-cols-1 {
|
|
1052
|
+
grid-template-columns: repeat(1, minmax(0, 1fr));
|
|
1053
|
+
}
|
|
1054
|
+
.wysdym-widget-container .flex-col {
|
|
1055
|
+
flex-direction: column;
|
|
1056
|
+
}
|
|
1057
|
+
.wysdym-widget-container .flex-wrap {
|
|
1058
|
+
flex-wrap: wrap;
|
|
1059
|
+
}
|
|
1060
|
+
.wysdym-widget-container .items-start {
|
|
1061
|
+
align-items: flex-start;
|
|
1062
|
+
}
|
|
1063
|
+
.wysdym-widget-container .items-center {
|
|
1064
|
+
align-items: center;
|
|
1065
|
+
}
|
|
1066
|
+
.wysdym-widget-container .justify-center {
|
|
1067
|
+
justify-content: center;
|
|
1068
|
+
}
|
|
1069
|
+
.wysdym-widget-container .justify-between {
|
|
1070
|
+
justify-content: space-between;
|
|
1071
|
+
}
|
|
1072
|
+
.wysdym-widget-container .gap-0\\.5 {
|
|
1073
|
+
gap: 0.125rem;
|
|
1074
|
+
}
|
|
1075
|
+
.wysdym-widget-container .gap-2 {
|
|
1076
|
+
gap: 0.5rem;
|
|
1077
|
+
}
|
|
1078
|
+
.wysdym-widget-container .gap-4 {
|
|
1079
|
+
gap: 1rem;
|
|
1080
|
+
}
|
|
1081
|
+
.wysdym-widget-container .gap-6 {
|
|
1082
|
+
gap: 1.5rem;
|
|
1083
|
+
}
|
|
1084
|
+
.wysdym-widget-container .gap-8 {
|
|
1085
|
+
gap: 2rem;
|
|
1086
|
+
}
|
|
1087
|
+
.wysdym-widget-container :is(.space-x-0\\.5 > :not([hidden]) ~ :not([hidden])) {
|
|
1088
|
+
--tw-space-x-reverse: 0;
|
|
1089
|
+
margin-right: calc(0.125rem * var(--tw-space-x-reverse));
|
|
1090
|
+
margin-left: calc(0.125rem * calc(1 - var(--tw-space-x-reverse)));
|
|
1091
|
+
}
|
|
1092
|
+
.wysdym-widget-container :is(.space-x-1 > :not([hidden]) ~ :not([hidden])) {
|
|
1093
|
+
--tw-space-x-reverse: 0;
|
|
1094
|
+
margin-right: calc(0.25rem * var(--tw-space-x-reverse));
|
|
1095
|
+
margin-left: calc(0.25rem * calc(1 - var(--tw-space-x-reverse)));
|
|
1096
|
+
}
|
|
1097
|
+
.wysdym-widget-container :is(.space-x-2 > :not([hidden]) ~ :not([hidden])) {
|
|
1098
|
+
--tw-space-x-reverse: 0;
|
|
1099
|
+
margin-right: calc(0.5rem * var(--tw-space-x-reverse));
|
|
1100
|
+
margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse)));
|
|
1101
|
+
}
|
|
1102
|
+
.wysdym-widget-container :is(.space-x-3 > :not([hidden]) ~ :not([hidden])) {
|
|
1103
|
+
--tw-space-x-reverse: 0;
|
|
1104
|
+
margin-right: calc(0.75rem * var(--tw-space-x-reverse));
|
|
1105
|
+
margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse)));
|
|
1106
|
+
}
|
|
1107
|
+
.wysdym-widget-container :is(.space-y-1 > :not([hidden]) ~ :not([hidden])) {
|
|
1108
|
+
--tw-space-y-reverse: 0;
|
|
1109
|
+
margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse)));
|
|
1110
|
+
margin-bottom: calc(0.25rem * var(--tw-space-y-reverse));
|
|
1111
|
+
}
|
|
1112
|
+
.wysdym-widget-container :is(.space-y-2 > :not([hidden]) ~ :not([hidden])) {
|
|
1113
|
+
--tw-space-y-reverse: 0;
|
|
1114
|
+
margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse)));
|
|
1115
|
+
margin-bottom: calc(0.5rem * var(--tw-space-y-reverse));
|
|
1116
|
+
}
|
|
1117
|
+
.wysdym-widget-container :is(.space-y-3 > :not([hidden]) ~ :not([hidden])) {
|
|
1118
|
+
--tw-space-y-reverse: 0;
|
|
1119
|
+
margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse)));
|
|
1120
|
+
margin-bottom: calc(0.75rem * var(--tw-space-y-reverse));
|
|
1121
|
+
}
|
|
1122
|
+
.wysdym-widget-container :is(.space-y-6 > :not([hidden]) ~ :not([hidden])) {
|
|
1123
|
+
--tw-space-y-reverse: 0;
|
|
1124
|
+
margin-top: calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));
|
|
1125
|
+
margin-bottom: calc(1.5rem * var(--tw-space-y-reverse));
|
|
1126
|
+
}
|
|
1127
|
+
.wysdym-widget-container .overflow-auto {
|
|
1128
|
+
overflow: auto;
|
|
1129
|
+
}
|
|
1130
|
+
.wysdym-widget-container .overflow-hidden {
|
|
1131
|
+
overflow: hidden;
|
|
1132
|
+
}
|
|
1133
|
+
.wysdym-widget-container .truncate {
|
|
1134
|
+
overflow: hidden;
|
|
1135
|
+
text-overflow: ellipsis;
|
|
1136
|
+
white-space: nowrap;
|
|
1137
|
+
}
|
|
1138
|
+
.wysdym-widget-container .whitespace-nowrap {
|
|
1139
|
+
white-space: nowrap;
|
|
1140
|
+
}
|
|
1141
|
+
.wysdym-widget-container .rounded {
|
|
1142
|
+
border-radius: 0.25rem;
|
|
1143
|
+
}
|
|
1144
|
+
.wysdym-widget-container .rounded-2xl {
|
|
1145
|
+
border-radius: 1rem;
|
|
1146
|
+
}
|
|
1147
|
+
.wysdym-widget-container .rounded-full {
|
|
1148
|
+
border-radius: 9999px;
|
|
1149
|
+
}
|
|
1150
|
+
.wysdym-widget-container .rounded-lg {
|
|
1151
|
+
border-radius: 0.5rem;
|
|
1152
|
+
}
|
|
1153
|
+
.wysdym-widget-container .rounded-xl {
|
|
1154
|
+
border-radius: 0.75rem;
|
|
1155
|
+
}
|
|
1156
|
+
.wysdym-widget-container .rounded-t-2xl {
|
|
1157
|
+
border-top-left-radius: 1rem;
|
|
1158
|
+
border-top-right-radius: 1rem;
|
|
1159
|
+
}
|
|
1160
|
+
.wysdym-widget-container .border {
|
|
1161
|
+
border-width: 1px;
|
|
1162
|
+
}
|
|
1163
|
+
.wysdym-widget-container .border-0 {
|
|
1164
|
+
border-width: 0px;
|
|
1165
|
+
}
|
|
1166
|
+
.wysdym-widget-container .border-2 {
|
|
1167
|
+
border-width: 2px;
|
|
1168
|
+
}
|
|
1169
|
+
.wysdym-widget-container .border-b {
|
|
1170
|
+
border-bottom-width: 1px;
|
|
1171
|
+
}
|
|
1172
|
+
.wysdym-widget-container .border-b-2 {
|
|
1173
|
+
border-bottom-width: 2px;
|
|
1174
|
+
}
|
|
1175
|
+
.wysdym-widget-container .border-t {
|
|
1176
|
+
border-top-width: 1px;
|
|
1177
|
+
}
|
|
1178
|
+
.wysdym-widget-container .border-t-0 {
|
|
1179
|
+
border-top-width: 0px;
|
|
1180
|
+
}
|
|
1181
|
+
.wysdym-widget-container .border-dashed {
|
|
1182
|
+
border-style: dashed;
|
|
1183
|
+
}
|
|
1184
|
+
.wysdym-widget-container .border-blue-200 {
|
|
1185
|
+
--tw-border-opacity: 1;
|
|
1186
|
+
border-color: rgb(191 219 254 / var(--tw-border-opacity, 1));
|
|
1187
|
+
}
|
|
1188
|
+
.wysdym-widget-container .border-gray-100 {
|
|
1189
|
+
--tw-border-opacity: 1;
|
|
1190
|
+
border-color: rgb(243 244 246 / var(--tw-border-opacity, 1));
|
|
1191
|
+
}
|
|
1192
|
+
.wysdym-widget-container .border-gray-200 {
|
|
1193
|
+
--tw-border-opacity: 1;
|
|
1194
|
+
border-color: rgb(229 231 235 / var(--tw-border-opacity, 1));
|
|
1195
|
+
}
|
|
1196
|
+
.wysdym-widget-container .border-gray-300 {
|
|
1197
|
+
--tw-border-opacity: 1;
|
|
1198
|
+
border-color: rgb(209 213 219 / var(--tw-border-opacity, 1));
|
|
1199
|
+
}
|
|
1200
|
+
.wysdym-widget-container .border-gray-700 {
|
|
1201
|
+
--tw-border-opacity: 1;
|
|
1202
|
+
border-color: rgb(55 65 81 / var(--tw-border-opacity, 1));
|
|
1203
|
+
}
|
|
1204
|
+
.wysdym-widget-container .border-red-200 {
|
|
1205
|
+
--tw-border-opacity: 1;
|
|
1206
|
+
border-color: rgb(254 202 202 / var(--tw-border-opacity, 1));
|
|
1207
|
+
}
|
|
1208
|
+
.wysdym-widget-container .border-red-300 {
|
|
1209
|
+
--tw-border-opacity: 1;
|
|
1210
|
+
border-color: rgb(252 165 165 / var(--tw-border-opacity, 1));
|
|
1211
|
+
}
|
|
1212
|
+
.wysdym-widget-container .border-red-400 {
|
|
1213
|
+
--tw-border-opacity: 1;
|
|
1214
|
+
border-color: rgb(248 113 113 / var(--tw-border-opacity, 1));
|
|
1215
|
+
}
|
|
1216
|
+
.wysdym-widget-container .border-white {
|
|
1217
|
+
--tw-border-opacity: 1;
|
|
1218
|
+
border-color: rgb(255 255 255 / var(--tw-border-opacity, 1));
|
|
1219
|
+
}
|
|
1220
|
+
.wysdym-widget-container .bg-black {
|
|
1221
|
+
--tw-bg-opacity: 1;
|
|
1222
|
+
background-color: rgb(0 0 0 / var(--tw-bg-opacity, 1));
|
|
1223
|
+
}
|
|
1224
|
+
.wysdym-widget-container .bg-blue-50\\/80 {
|
|
1225
|
+
background-color: rgb(239 246 255 / 0.8);
|
|
1226
|
+
}
|
|
1227
|
+
.wysdym-widget-container .bg-blue-600 {
|
|
1228
|
+
--tw-bg-opacity: 1;
|
|
1229
|
+
background-color: rgb(37 99 235 / var(--tw-bg-opacity, 1));
|
|
1230
|
+
}
|
|
1231
|
+
.wysdym-widget-container .bg-gray-100 {
|
|
1232
|
+
--tw-bg-opacity: 1;
|
|
1233
|
+
background-color: rgb(243 244 246 / var(--tw-bg-opacity, 1));
|
|
1234
|
+
}
|
|
1235
|
+
.wysdym-widget-container .bg-gray-400 {
|
|
1236
|
+
--tw-bg-opacity: 1;
|
|
1237
|
+
background-color: rgb(156 163 175 / var(--tw-bg-opacity, 1));
|
|
1238
|
+
}
|
|
1239
|
+
.wysdym-widget-container .bg-gray-50 {
|
|
1240
|
+
--tw-bg-opacity: 1;
|
|
1241
|
+
background-color: rgb(249 250 251 / var(--tw-bg-opacity, 1));
|
|
1242
|
+
}
|
|
1243
|
+
.wysdym-widget-container .bg-gray-600 {
|
|
1244
|
+
--tw-bg-opacity: 1;
|
|
1245
|
+
background-color: rgb(75 85 99 / var(--tw-bg-opacity, 1));
|
|
1246
|
+
}
|
|
1247
|
+
.wysdym-widget-container .bg-gray-800 {
|
|
1248
|
+
--tw-bg-opacity: 1;
|
|
1249
|
+
background-color: rgb(31 41 55 / var(--tw-bg-opacity, 1));
|
|
1250
|
+
}
|
|
1251
|
+
.wysdym-widget-container .bg-gray-900 {
|
|
1252
|
+
--tw-bg-opacity: 1;
|
|
1253
|
+
background-color: rgb(17 24 39 / var(--tw-bg-opacity, 1));
|
|
1254
|
+
}
|
|
1255
|
+
.wysdym-widget-container .bg-green-600 {
|
|
1256
|
+
--tw-bg-opacity: 1;
|
|
1257
|
+
background-color: rgb(22 163 74 / var(--tw-bg-opacity, 1));
|
|
1258
|
+
}
|
|
1259
|
+
.wysdym-widget-container .bg-red-100 {
|
|
1260
|
+
--tw-bg-opacity: 1;
|
|
1261
|
+
background-color: rgb(254 226 226 / var(--tw-bg-opacity, 1));
|
|
1262
|
+
}
|
|
1263
|
+
.wysdym-widget-container .bg-red-50 {
|
|
1264
|
+
--tw-bg-opacity: 1;
|
|
1265
|
+
background-color: rgb(254 242 242 / var(--tw-bg-opacity, 1));
|
|
1266
|
+
}
|
|
1267
|
+
.wysdym-widget-container .bg-red-500 {
|
|
1268
|
+
--tw-bg-opacity: 1;
|
|
1269
|
+
background-color: rgb(239 68 68 / var(--tw-bg-opacity, 1));
|
|
1270
|
+
}
|
|
1271
|
+
.wysdym-widget-container .bg-red-600 {
|
|
1272
|
+
--tw-bg-opacity: 1;
|
|
1273
|
+
background-color: rgb(220 38 38 / var(--tw-bg-opacity, 1));
|
|
1274
|
+
}
|
|
1275
|
+
.wysdym-widget-container .bg-transparent {
|
|
1276
|
+
background-color: transparent;
|
|
1277
|
+
}
|
|
1278
|
+
.wysdym-widget-container .bg-white {
|
|
1279
|
+
--tw-bg-opacity: 1;
|
|
1280
|
+
background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1));
|
|
1281
|
+
}
|
|
1282
|
+
.wysdym-widget-container .bg-gradient-to-br {
|
|
1283
|
+
background-image: linear-gradient(to bottom right, var(--tw-gradient-stops));
|
|
1284
|
+
}
|
|
1285
|
+
.wysdym-widget-container .bg-gradient-to-r {
|
|
1286
|
+
background-image: linear-gradient(to right, var(--tw-gradient-stops));
|
|
1287
|
+
}
|
|
1288
|
+
.wysdym-widget-container .from-blue-50 {
|
|
1289
|
+
--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);
|
|
1290
|
+
--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);
|
|
1291
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
|
|
1292
|
+
}
|
|
1293
|
+
.wysdym-widget-container .from-blue-600 {
|
|
1294
|
+
--tw-gradient-from: #2563eb var(--tw-gradient-from-position);
|
|
1295
|
+
--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);
|
|
1296
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
|
|
1297
|
+
}
|
|
1298
|
+
.wysdym-widget-container .to-indigo-100 {
|
|
1299
|
+
--tw-gradient-to: #e0e7ff var(--tw-gradient-to-position);
|
|
1300
|
+
}
|
|
1301
|
+
.wysdym-widget-container .to-indigo-50 {
|
|
1302
|
+
--tw-gradient-to: #eef2ff var(--tw-gradient-to-position);
|
|
1303
|
+
}
|
|
1304
|
+
.wysdym-widget-container .to-indigo-600 {
|
|
1305
|
+
--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position);
|
|
1306
|
+
}
|
|
1307
|
+
.wysdym-widget-container .p-2 {
|
|
1308
|
+
padding: 0.5rem;
|
|
1309
|
+
}
|
|
1310
|
+
.wysdym-widget-container .p-3 {
|
|
1311
|
+
padding: 0.75rem;
|
|
1312
|
+
}
|
|
1313
|
+
.wysdym-widget-container .p-4 {
|
|
1314
|
+
padding: 1rem;
|
|
1315
|
+
}
|
|
1316
|
+
.wysdym-widget-container .p-6 {
|
|
1317
|
+
padding: 1.5rem;
|
|
1318
|
+
}
|
|
1319
|
+
.wysdym-widget-container .p-8 {
|
|
1320
|
+
padding: 2rem;
|
|
1321
|
+
}
|
|
1322
|
+
.wysdym-widget-container .px-3 {
|
|
1323
|
+
padding-left: 0.75rem;
|
|
1324
|
+
padding-right: 0.75rem;
|
|
1325
|
+
}
|
|
1326
|
+
.wysdym-widget-container .px-4 {
|
|
1327
|
+
padding-left: 1rem;
|
|
1328
|
+
padding-right: 1rem;
|
|
1329
|
+
}
|
|
1330
|
+
.wysdym-widget-container .px-6 {
|
|
1331
|
+
padding-left: 1.5rem;
|
|
1332
|
+
padding-right: 1.5rem;
|
|
1333
|
+
}
|
|
1334
|
+
.wysdym-widget-container .py-0 {
|
|
1335
|
+
padding-top: 0px;
|
|
1336
|
+
padding-bottom: 0px;
|
|
1337
|
+
}
|
|
1338
|
+
.wysdym-widget-container .py-1\\.5 {
|
|
1339
|
+
padding-top: 0.375rem;
|
|
1340
|
+
padding-bottom: 0.375rem;
|
|
1341
|
+
}
|
|
1342
|
+
.wysdym-widget-container .py-2 {
|
|
1343
|
+
padding-top: 0.5rem;
|
|
1344
|
+
padding-bottom: 0.5rem;
|
|
1345
|
+
}
|
|
1346
|
+
.wysdym-widget-container .py-2\\.5 {
|
|
1347
|
+
padding-top: 0.625rem;
|
|
1348
|
+
padding-bottom: 0.625rem;
|
|
1349
|
+
}
|
|
1350
|
+
.wysdym-widget-container .py-3 {
|
|
1351
|
+
padding-top: 0.75rem;
|
|
1352
|
+
padding-bottom: 0.75rem;
|
|
1353
|
+
}
|
|
1354
|
+
.wysdym-widget-container .py-8 {
|
|
1355
|
+
padding-top: 2rem;
|
|
1356
|
+
padding-bottom: 2rem;
|
|
1357
|
+
}
|
|
1358
|
+
.wysdym-widget-container .pt-2 {
|
|
1359
|
+
padding-top: 0.5rem;
|
|
1360
|
+
}
|
|
1361
|
+
.wysdym-widget-container .pt-3 {
|
|
1362
|
+
padding-top: 0.75rem;
|
|
1363
|
+
}
|
|
1364
|
+
.wysdym-widget-container .text-center {
|
|
1365
|
+
text-align: center;
|
|
1366
|
+
}
|
|
1367
|
+
.wysdym-widget-container .font-mono {
|
|
1368
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
1369
|
+
}
|
|
1370
|
+
.wysdym-widget-container .text-2xl {
|
|
1371
|
+
font-size: 1.5rem;
|
|
1372
|
+
line-height: 2rem;
|
|
1373
|
+
}
|
|
1374
|
+
.wysdym-widget-container .text-4xl {
|
|
1375
|
+
font-size: 2.25rem;
|
|
1376
|
+
line-height: 2.5rem;
|
|
1377
|
+
}
|
|
1378
|
+
.wysdym-widget-container .text-base {
|
|
1379
|
+
font-size: 1rem;
|
|
1380
|
+
line-height: 1.5rem;
|
|
1381
|
+
}
|
|
1382
|
+
.wysdym-widget-container .text-lg {
|
|
1383
|
+
font-size: 1.125rem;
|
|
1384
|
+
line-height: 1.75rem;
|
|
1385
|
+
}
|
|
1386
|
+
.wysdym-widget-container .text-sm {
|
|
1387
|
+
font-size: 0.875rem;
|
|
1388
|
+
line-height: 1.25rem;
|
|
1389
|
+
}
|
|
1390
|
+
.wysdym-widget-container .text-xl {
|
|
1391
|
+
font-size: 1.25rem;
|
|
1392
|
+
line-height: 1.75rem;
|
|
1393
|
+
}
|
|
1394
|
+
.wysdym-widget-container .text-xs {
|
|
1395
|
+
font-size: 0.75rem;
|
|
1396
|
+
line-height: 1rem;
|
|
1397
|
+
}
|
|
1398
|
+
.wysdym-widget-container .font-bold {
|
|
1399
|
+
font-weight: 700;
|
|
1400
|
+
}
|
|
1401
|
+
.wysdym-widget-container .font-medium {
|
|
1402
|
+
font-weight: 500;
|
|
1403
|
+
}
|
|
1404
|
+
.wysdym-widget-container .font-semibold {
|
|
1405
|
+
font-weight: 600;
|
|
1406
|
+
}
|
|
1407
|
+
.wysdym-widget-container .uppercase {
|
|
1408
|
+
text-transform: uppercase;
|
|
1409
|
+
}
|
|
1410
|
+
.wysdym-widget-container .italic {
|
|
1411
|
+
font-style: italic;
|
|
1412
|
+
}
|
|
1413
|
+
.wysdym-widget-container .tracking-wide {
|
|
1414
|
+
letter-spacing: 0.025em;
|
|
1415
|
+
}
|
|
1416
|
+
.wysdym-widget-container .text-blue-800 {
|
|
1417
|
+
--tw-text-opacity: 1;
|
|
1418
|
+
color: rgb(30 64 175 / var(--tw-text-opacity, 1));
|
|
1419
|
+
}
|
|
1420
|
+
.wysdym-widget-container .text-gray-400 {
|
|
1421
|
+
--tw-text-opacity: 1;
|
|
1422
|
+
color: rgb(156 163 175 / var(--tw-text-opacity, 1));
|
|
1423
|
+
}
|
|
1424
|
+
.wysdym-widget-container .text-gray-500 {
|
|
1425
|
+
--tw-text-opacity: 1;
|
|
1426
|
+
color: rgb(107 114 128 / var(--tw-text-opacity, 1));
|
|
1427
|
+
}
|
|
1428
|
+
.wysdym-widget-container .text-gray-600 {
|
|
1429
|
+
--tw-text-opacity: 1;
|
|
1430
|
+
color: rgb(75 85 99 / var(--tw-text-opacity, 1));
|
|
1431
|
+
}
|
|
1432
|
+
.wysdym-widget-container .text-gray-700 {
|
|
1433
|
+
--tw-text-opacity: 1;
|
|
1434
|
+
color: rgb(55 65 81 / var(--tw-text-opacity, 1));
|
|
1435
|
+
}
|
|
1436
|
+
.wysdym-widget-container .text-gray-800 {
|
|
1437
|
+
--tw-text-opacity: 1;
|
|
1438
|
+
color: rgb(31 41 55 / var(--tw-text-opacity, 1));
|
|
1439
|
+
}
|
|
1440
|
+
.wysdym-widget-container .text-gray-900 {
|
|
1441
|
+
--tw-text-opacity: 1;
|
|
1442
|
+
color: rgb(17 24 39 / var(--tw-text-opacity, 1));
|
|
1443
|
+
}
|
|
1444
|
+
.wysdym-widget-container .text-red-500 {
|
|
1445
|
+
--tw-text-opacity: 1;
|
|
1446
|
+
color: rgb(239 68 68 / var(--tw-text-opacity, 1));
|
|
1447
|
+
}
|
|
1448
|
+
.wysdym-widget-container .text-red-600 {
|
|
1449
|
+
--tw-text-opacity: 1;
|
|
1450
|
+
color: rgb(220 38 38 / var(--tw-text-opacity, 1));
|
|
1451
|
+
}
|
|
1452
|
+
.wysdym-widget-container .text-red-700 {
|
|
1453
|
+
--tw-text-opacity: 1;
|
|
1454
|
+
color: rgb(185 28 28 / var(--tw-text-opacity, 1));
|
|
1455
|
+
}
|
|
1456
|
+
.wysdym-widget-container .text-white {
|
|
1457
|
+
--tw-text-opacity: 1;
|
|
1458
|
+
color: rgb(255 255 255 / var(--tw-text-opacity, 1));
|
|
1459
|
+
}
|
|
1460
|
+
.wysdym-widget-container .text-yellow-500 {
|
|
1461
|
+
--tw-text-opacity: 1;
|
|
1462
|
+
color: rgb(234 179 8 / var(--tw-text-opacity, 1));
|
|
1463
|
+
}
|
|
1464
|
+
.wysdym-widget-container .no-underline {
|
|
1465
|
+
text-decoration-line: none;
|
|
1466
|
+
}
|
|
1467
|
+
.wysdym-widget-container .placeholder-gray-400::-moz-placeholder {
|
|
1468
|
+
--tw-placeholder-opacity: 1;
|
|
1469
|
+
color: rgb(156 163 175 / var(--tw-placeholder-opacity, 1));
|
|
1470
|
+
}
|
|
1471
|
+
.wysdym-widget-container .placeholder-gray-400::placeholder {
|
|
1472
|
+
--tw-placeholder-opacity: 1;
|
|
1473
|
+
color: rgb(156 163 175 / var(--tw-placeholder-opacity, 1));
|
|
1474
|
+
}
|
|
1475
|
+
.wysdym-widget-container .opacity-0 {
|
|
1476
|
+
opacity: 0;
|
|
1477
|
+
}
|
|
1478
|
+
.wysdym-widget-container .opacity-100 {
|
|
1479
|
+
opacity: 1;
|
|
1480
|
+
}
|
|
1481
|
+
.wysdym-widget-container .opacity-60 {
|
|
1482
|
+
opacity: 0.6;
|
|
1483
|
+
}
|
|
1484
|
+
.wysdym-widget-container .shadow {
|
|
1485
|
+
--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
|
|
1486
|
+
--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);
|
|
1487
|
+
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
|
|
1488
|
+
}
|
|
1489
|
+
.wysdym-widget-container .shadow-lg {
|
|
1490
|
+
--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
|
|
1491
|
+
--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
|
|
1492
|
+
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
|
|
1493
|
+
}
|
|
1494
|
+
.wysdym-widget-container .shadow-md {
|
|
1495
|
+
--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
|
|
1496
|
+
--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);
|
|
1497
|
+
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
|
|
1498
|
+
}
|
|
1499
|
+
.wysdym-widget-container .shadow-sm {
|
|
1500
|
+
--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
|
1501
|
+
--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);
|
|
1502
|
+
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
|
|
1503
|
+
}
|
|
1504
|
+
.wysdym-widget-container .shadow-xl {
|
|
1505
|
+
--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
|
|
1506
|
+
--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);
|
|
1507
|
+
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
|
|
1508
|
+
}
|
|
1509
|
+
.wysdym-widget-container .outline-none {
|
|
1510
|
+
outline: 2px solid transparent;
|
|
1511
|
+
outline-offset: 2px;
|
|
1512
|
+
}
|
|
1513
|
+
.wysdym-widget-container .ring-0 {
|
|
1514
|
+
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
|
|
1515
|
+
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);
|
|
1516
|
+
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
|
|
1517
|
+
}
|
|
1518
|
+
.wysdym-widget-container .blur {
|
|
1519
|
+
--tw-blur: blur(8px);
|
|
1520
|
+
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
|
|
1521
|
+
}
|
|
1522
|
+
.wysdym-widget-container .filter {
|
|
1523
|
+
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
|
|
1524
|
+
}
|
|
1525
|
+
.wysdym-widget-container .transition {
|
|
1526
|
+
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;
|
|
1527
|
+
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
1528
|
+
transition-duration: 150ms;
|
|
1529
|
+
}
|
|
1530
|
+
.wysdym-widget-container .transition-all {
|
|
1531
|
+
transition-property: all;
|
|
1532
|
+
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
1533
|
+
transition-duration: 150ms;
|
|
1534
|
+
}
|
|
1535
|
+
.wysdym-widget-container .transition-colors {
|
|
1536
|
+
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
|
|
1537
|
+
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
1538
|
+
transition-duration: 150ms;
|
|
1539
|
+
}
|
|
1540
|
+
.wysdym-widget-container .transition-opacity {
|
|
1541
|
+
transition-property: opacity;
|
|
1542
|
+
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
1543
|
+
transition-duration: 150ms;
|
|
1544
|
+
}
|
|
1545
|
+
.wysdym-widget-container .transition-transform {
|
|
1546
|
+
transition-property: transform;
|
|
1547
|
+
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
1548
|
+
transition-duration: 150ms;
|
|
1549
|
+
}
|
|
1550
|
+
.wysdym-widget-container .duration-200 {
|
|
1551
|
+
transition-duration: 200ms;
|
|
1552
|
+
}
|
|
1553
|
+
.wysdym-widget-container .duration-\\[3000ms\\] {
|
|
1554
|
+
transition-duration: 3000ms;
|
|
1555
|
+
}
|
|
1556
|
+
.wysdym-widget-container .ease-in {
|
|
1557
|
+
transition-timing-function: cubic-bezier(0.4, 0, 1, 1);
|
|
1558
|
+
}
|
|
1559
|
+
.wysdym-widget-container .ease-in-out {
|
|
1560
|
+
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
1561
|
+
}
|
|
1562
|
+
.wysdym-widget-container .ease-out {
|
|
1563
|
+
transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/* Targeted reset for form elements — replaces @tailwind base/Preflight.
|
|
1567
|
+
Only button and input get the aggressive reset; select and textarea
|
|
1568
|
+
retain browser defaults so Tailwind utility classes can layer on top. */
|
|
1569
|
+
.wysdym-widget-container button,
|
|
1570
|
+
.wysdym-widget-container input {
|
|
1571
|
+
border: 0;
|
|
1572
|
+
background: transparent;
|
|
1573
|
+
padding: 0;
|
|
1574
|
+
margin: 0;
|
|
1575
|
+
font: inherit;
|
|
1576
|
+
color: inherit;
|
|
1577
|
+
outline: none;
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
.wysdym-widget-container button {
|
|
1581
|
+
cursor: pointer;
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/* Widget container baseline */
|
|
1585
|
+
.wysdym-widget-container {
|
|
1586
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
|
|
1587
|
+
font-size: 14px;
|
|
1588
|
+
line-height: 1.5;
|
|
1589
|
+
color: #333;
|
|
1590
|
+
box-sizing: border-box;
|
|
1591
|
+
display: block;
|
|
1592
|
+
margin: 0;
|
|
1593
|
+
padding: 0;
|
|
1594
|
+
border: none;
|
|
1595
|
+
background: none;
|
|
1596
|
+
overflow: visible;
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/* Custom scrollbar styles — scoped to widget */
|
|
1600
|
+
.wysdym-widget-container .scrollbar-thin::-webkit-scrollbar { width: 6px; }
|
|
1601
|
+
.wysdym-widget-container .scrollbar-thin::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 3px; }
|
|
1602
|
+
.wysdym-widget-container .scrollbar-thin::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
|
|
1603
|
+
.wysdym-widget-container .scrollbar-thin::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
|
|
1604
|
+
.wysdym-widget-container .scrollbar-thin { scrollbar-width: thin; scrollbar-color: #cbd5e1 #f1f5f9; }
|
|
1605
|
+
|
|
1606
|
+
/* Widget sizing */
|
|
1607
|
+
.wysdym-widget-expanded {
|
|
1608
|
+
width: 744px !important;
|
|
1609
|
+
max-width: 744px !important;
|
|
1610
|
+
min-width: 744px !important;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
.wysdym-widget-expanded-mobile {
|
|
1614
|
+
width: calc(100vw - 1rem) !important;
|
|
1615
|
+
max-width: calc(100vw - 1rem) !important;
|
|
1616
|
+
min-width: 320px !important;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
@media (min-width: 800px) {
|
|
1620
|
+
.wysdym-widget-expanded-mobile {
|
|
1621
|
+
width: 744px !important;
|
|
1622
|
+
max-width: 744px !important;
|
|
1623
|
+
min-width: 744px !important;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
@media (max-width: 639px) {
|
|
1628
|
+
.wysdym-widget-expanded-mobile {
|
|
1629
|
+
max-height: 85vh !important;
|
|
1630
|
+
margin: 0.5rem !important;
|
|
1631
|
+
width: calc(100vw - 1rem) !important;
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
.wysdym-widget-inline {
|
|
1636
|
+
width: 100% !important;
|
|
1637
|
+
max-width: 100% !important;
|
|
1638
|
+
min-width: 320px !important;
|
|
1639
|
+
height: 500px !important;
|
|
1640
|
+
max-height: 500px !important;
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
/* Keyframe animations */
|
|
1644
|
+
@keyframes pulse {
|
|
1645
|
+
0%, 100% { opacity: 1; }
|
|
1646
|
+
50% { opacity: .5; }
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
@keyframes spin {
|
|
1650
|
+
from { transform: rotate(0deg); }
|
|
1651
|
+
to { transform: rotate(360deg); }
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
@keyframes slide-up {
|
|
1655
|
+
from { opacity: 0; transform: translateY(20px); }
|
|
1656
|
+
to { opacity: 1; transform: translateY(0); }
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
.wysdym-widget-container .hover\\:scale-\\[1\\.02\\]:hover {
|
|
1660
|
+
--tw-scale-x: 1.02;
|
|
1661
|
+
--tw-scale-y: 1.02;
|
|
1662
|
+
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
.wysdym-widget-container .hover\\:border-blue-300:hover {
|
|
1666
|
+
--tw-border-opacity: 1;
|
|
1667
|
+
border-color: rgb(147 197 253 / var(--tw-border-opacity, 1));
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
.wysdym-widget-container .hover\\:border-gray-400:hover {
|
|
1671
|
+
--tw-border-opacity: 1;
|
|
1672
|
+
border-color: rgb(156 163 175 / var(--tw-border-opacity, 1));
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
.wysdym-widget-container .hover\\:bg-blue-700:hover {
|
|
1676
|
+
--tw-bg-opacity: 1;
|
|
1677
|
+
background-color: rgb(29 78 216 / var(--tw-bg-opacity, 1));
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
.wysdym-widget-container .hover\\:bg-gray-50:hover {
|
|
1681
|
+
--tw-bg-opacity: 1;
|
|
1682
|
+
background-color: rgb(249 250 251 / var(--tw-bg-opacity, 1));
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
.wysdym-widget-container .hover\\:bg-gray-700:hover {
|
|
1686
|
+
--tw-bg-opacity: 1;
|
|
1687
|
+
background-color: rgb(55 65 81 / var(--tw-bg-opacity, 1));
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
.wysdym-widget-container .hover\\:bg-red-200:hover {
|
|
1691
|
+
--tw-bg-opacity: 1;
|
|
1692
|
+
background-color: rgb(254 202 202 / var(--tw-bg-opacity, 1));
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
.wysdym-widget-container .hover\\:bg-red-700:hover {
|
|
1696
|
+
--tw-bg-opacity: 1;
|
|
1697
|
+
background-color: rgb(185 28 28 / var(--tw-bg-opacity, 1));
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
.wysdym-widget-container .hover\\:bg-white\\/20:hover {
|
|
1701
|
+
background-color: rgb(255 255 255 / 0.2);
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
.wysdym-widget-container .hover\\:from-blue-700:hover {
|
|
1705
|
+
--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);
|
|
1706
|
+
--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);
|
|
1707
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
.wysdym-widget-container .hover\\:to-indigo-700:hover {
|
|
1711
|
+
--tw-gradient-to: #4338ca var(--tw-gradient-to-position);
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
.wysdym-widget-container .hover\\:text-gray-900:hover {
|
|
1715
|
+
--tw-text-opacity: 1;
|
|
1716
|
+
color: rgb(17 24 39 / var(--tw-text-opacity, 1));
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
.wysdym-widget-container .hover\\:opacity-90:hover {
|
|
1720
|
+
opacity: 0.9;
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
.wysdym-widget-container .hover\\:shadow-lg:hover {
|
|
1724
|
+
--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
|
|
1725
|
+
--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
|
|
1726
|
+
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
.wysdym-widget-container .hover\\:brightness-110:hover {
|
|
1730
|
+
--tw-brightness: brightness(1.1);
|
|
1731
|
+
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
.wysdym-widget-container .focus\\:border-transparent:focus {
|
|
1735
|
+
border-color: transparent;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
.wysdym-widget-container .focus\\:outline-none:focus {
|
|
1739
|
+
outline: 2px solid transparent;
|
|
1740
|
+
outline-offset: 2px;
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
.wysdym-widget-container .focus\\:ring-2:focus {
|
|
1744
|
+
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
|
|
1745
|
+
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
|
|
1746
|
+
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
.wysdym-widget-container .focus\\:ring-blue-500:focus {
|
|
1750
|
+
--tw-ring-opacity: 1;
|
|
1751
|
+
--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1));
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
.wysdym-widget-container .focus\\:ring-gray-400:focus {
|
|
1755
|
+
--tw-ring-opacity: 1;
|
|
1756
|
+
--tw-ring-color: rgb(156 163 175 / var(--tw-ring-opacity, 1));
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
.wysdym-widget-container .focus\\:ring-offset-2:focus {
|
|
1760
|
+
--tw-ring-offset-width: 2px;
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
.wysdym-widget-container .active\\:scale-\\[0\\.98\\]:active {
|
|
1764
|
+
--tw-scale-x: 0.98;
|
|
1765
|
+
--tw-scale-y: 0.98;
|
|
1766
|
+
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
.wysdym-widget-container .disabled\\:cursor-not-allowed:disabled {
|
|
1770
|
+
cursor: not-allowed;
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
.wysdym-widget-container .disabled\\:opacity-50:disabled {
|
|
1774
|
+
opacity: 0.5;
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
@media (min-width: 768px) {
|
|
1778
|
+
.wysdym-widget-container .md\\:grid-cols-2 {
|
|
1779
|
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
@media (min-width: 1024px) {
|
|
1784
|
+
.wysdym-widget-container .lg\\:grid-cols-4 {
|
|
1785
|
+
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/* Widget Isolation — all styles scoped to .wysdym-widget-container */
|
|
1790
|
+
|
|
1791
|
+
.wysdym-widget-container {
|
|
1792
|
+
isolation: isolate;
|
|
1793
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
1794
|
+
contain: layout style paint;
|
|
1795
|
+
position: relative;
|
|
1796
|
+
z-index: 1;
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
/* Scrollbar styles — scoped to widget only */
|
|
1800
|
+
.wysdym-widget-container ::-webkit-scrollbar { width: 8px; }
|
|
1801
|
+
.wysdym-widget-container ::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 4px; }
|
|
1802
|
+
.wysdym-widget-container ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
|
|
1803
|
+
.wysdym-widget-container ::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
|
|
1804
|
+
|
|
1805
|
+
/* Box-sizing reset — scoped */
|
|
1806
|
+
.wysdym-widget-container *,
|
|
1807
|
+
.wysdym-widget-container *::before,
|
|
1808
|
+
.wysdym-widget-container *::after {
|
|
1809
|
+
box-sizing: border-box;
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
/* Responsive overrides — scoped */
|
|
1813
|
+
@media (max-width: 768px) {
|
|
1814
|
+
.wysdym-widget-container .grid {
|
|
1815
|
+
grid-template-columns: 1fr;
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
`,ShadowRootContext=React.createContext(null),ShadowRootProvider=ShadowRootContext.Provider;let isInitialized=!1;function injectShadowStyles(T){const n=document.createElement("style");n.textContent=combinedCSS,T.appendChild(n)}function createShadowContainer(T){const n=T.attachShadow({mode:"open"});injectShadowStyles(n);const P=document.createElement("div");return P.className="wysdym-widget-container",P.setAttribute("data-wysdym-widget","true"),n.appendChild(P),P}function createFloatingContainer(T){const n=document.getElementById("wysdym-floating-widget");if(n)return n.shadowRoot?.querySelector(".wysdym-widget-container")??n;const P=document.createElement("div");return P.id="wysdym-floating-widget",P.style.cssText=`
|
|
1819
|
+
position: fixed !important;
|
|
1820
|
+
${T.includes("bottom")?"bottom: 20px !important;":"top: 20px !important;"}
|
|
1821
|
+
${T.includes("right")?"right: 20px !important;":"left: 20px !important;"}
|
|
1822
|
+
z-index: 2147483647 !important;
|
|
1823
|
+
pointer-events: auto !important;
|
|
1824
|
+
`,document.body.appendChild(P),createShadowContainer(P)}async function mountWidget(T){const{agentId:n,companyToken:P,mode:R="floating",position:A="bottom-right",backendUrl:L,startExpanded:O=!1}=T;L&&(window.__WYSDYM_BACKEND_URL__=L);let N=null;if(R==="inline"){const U=T.container;if(!U)return;const J=typeof U=="string"?document.querySelector(U):U;if(!J)return;J.setAttribute("data-wysdym-widget","true"),N=createShadowContainer(J)}else N=createFloatingContainer(A);if(!N)return;N.innerHTML="";const V=await fetchAgentConfig(n,L),j=V?.primary_color??"#BA6296",B=V?.secondary_color??"#A0527A",z=V?.widget_trigger_text??"Need help?",W=V?.widget_trigger_button_text??"Start a call",q=V?.widget_trigger_button_icon??"Phone",H=V?.email_collection_button_text&&V.email_collection_button_text!=="Start chat"?V.email_collection_button_text:"Submit",$=V?.email_collection_button_icon??"ArrowRight";client.createRoot(N).render(jsxRuntime.jsx(React.StrictMode,{children:jsxRuntime.jsx(ShadowRootProvider,{value:N,children:jsxRuntime.jsx(ChatWidget,{companyToken:P,agentId:n,primaryColor:j,secondaryColor:B,widgetTriggerText:z,widgetTriggerButtonText:W,widgetTriggerButtonIcon:q,emailCollectionButtonText:H,emailCollectionButtonIcon:$,isExpanded:O,onExpandChange:()=>{},backendUrl:L,mode:R,initialAgentName:V?.name,initialAgentFirstMessage:V?.agent_first_message})})}))}function cleanupWidgets(){const T=document.getElementById("wysdym-floating-widget");T&&(T.dispatchEvent(new CustomEvent("wysdym-widget-cleanup")),setTimeout(()=>T.remove(),100)),document.querySelectorAll("[data-wysdym-widget]").forEach(n=>n.dispatchEvent(new CustomEvent("wysdym-widget-cleanup"))),document.dispatchEvent(new CustomEvent("wysdym-widget-cleanup"))}const widgetApi={init:async T=>{isInitialized||(await mountWidget(T),isInitialized=!0)},mount:T=>mountWidget(T),endAllConversations:cleanupWidgets};typeof window<"u"&&(window.WysdymWidget=widgetApi,window.ChatWidget=widgetApi);const main=Object.freeze(Object.defineProperty({__proto__:null,ChatWidget,WysdymWidget,getEmbedCode},Symbol.toStringTag,{value:"Module"}));exports.ChatWidget=ChatWidget;exports.WysdymWidget=WysdymWidget;exports.getEmbedCode=getEmbedCode;
|