@16x/webphone-sdk 3.1.9 → 3.8.1

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/CHANGELOG.md CHANGED
@@ -1,9 +1,6 @@
1
1
  # Changelog
2
2
 
3
- ## 3.1.9 - 2026-09-24
4
-
5
- > 同日先发过 `3.8.1`(内容与本文完全相同),按项目版本线改成 3.1.9(3.1.8 的补丁位)重新发布;3.8.1 不再维护。
6
-
3
+ ## 3.8.1 - 2026-09-24
7
4
 
8
5
  - **坐席状态接口直接用会话里的那张票**:老平台把 fs token 拼在软电话地址上(`wss://…/api/fs/sip-ws?token=…`),
9
6
  同一个 token 也用于 HTTP 接口的 `Authorization`。`client.setAgentStatus()` 现在把这个地址带给会话来源
@@ -1 +1 @@
1
- const e=require("./SharedWorkerProtocol-39dch6xL.cjs"),t=require("./Diagnostics-DkKlZQnY.cjs");var n=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},r={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},i=(e,t)=>r[e].has(t);function a(e,t){if(!i(e,t))throw new o(e,t);return t}var o=class extends e.i{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},s=a,c=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],l=3e4,u=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(t){this.options=t,this.id=t.id,this.destination=t.destination,this.platform=t.platform,this.capabilities=t.capabilities??new Set;try{c.forEach(e=>{this.sessionUnsubscribers.push(t.session.on(e,t=>this.handleSessionEvent(e,t)))})}catch(n){this.cleanupSessionListeners();try{t.session.terminate()}catch{}throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:n})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,`held`,()=>this.options.session.hold())}async resume(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),await this.startPendingOperation(`resume`,`active`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!f(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),d(this.currentState))throw this.operationError();try{this.options.session.terminate(),d(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!d(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||d(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.transitionIfAllowed(`held`,t,e);break;case`unhold`:this.transitionIfAllowed(`active`,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(i(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!i(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,d(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{d(e)&&this.dispose()}}startPendingOperation(e,t,n){if(this.pendingOperation!==void 0)throw this.operationError();return new Promise((r,i)=>{let a={kind:e,nextState:t,resolve:r,reject:i};this.pendingOperation=a,a.timer=setTimeout(()=>this.timeoutPendingOperation(a),l);let o;try{o=n()}catch(e){this.rejectPendingOperation(e);return}o.then(()=>this.resolvePendingOperation(a),e=>this.rejectPendingOperation(e,a))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||d(this.currentState)){e.reject(this.operationError());return}try{this.transitionTo(e.nextState),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(t){let n=t instanceof e.i&&t.callId===this.id?t:this.operationError(t);try{this.options.onError?.(n)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(t){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}};function d(e){return e===`ended`||e===`failed`}function f(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var p=0;function m(){return p+=1,`call_${Date.now().toString(36)}_${p.toString(36)}`}var h=`X-User-Data`,g=/[^\x20-\x7E]/,ee=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function te(t){if(typeof t!=`string`)return[];let n=t.trim();if(n===``)return[];if(g.test(n))throw new e.i(`CALL_INVALID_USERDATA`,`call`,!1,{cause:ee});return[`${h}: ${n}`]}var _=class{events=new v;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(t){this.options=t,this.incomingSessionSnapshot=t.session;try{this.incomingUnsubscribe=t.sip.onIncoming(e=>this.handleIncoming(e))}catch(t){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(t,n){this.assertNotDisposed();let r=this.operationGeneration,i=t.destination.trim();if(i===``)throw new e.i(`CALL_INVALID_DESTINATION`,`call`,!1);let a=te(t.userdata);this.requireCapability(n,`outbound`);let o=this.callLimit(n);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=o)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=o||this.pendingDestinations.has(i)||[...this.calls.values()].some(e=>e.destination===i))throw new e.i(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(i);let s=m(),c;try{c=await this.holdActiveCallForNewCall(),this.assertGeneration(r,s);let e;try{e=this.options.sip.dial(i,this.dialOptions(s,n,t.type,a))}catch(e){throw this.dialError(e,s)}this.assertGeneration(r,s);let o;try{o=new u({id:s,destination:i,platform:this.options.platform,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(o,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(o)})}catch(e){throw this.dialError(e,s)}if(!this.isCurrentGeneration(r))throw o.dispose(),this.callOperationError(o.id);this.calls.set(o.id,o),this.callSessions.set(o.id,e),this.options.onCallCreated?.(o.id,e);try{o.beginOutbound()}catch(e){throw o.dispose(),this.calls.delete(o.id),this.callSessions.delete(o.id),this.dialError(e,o.id)}if(!this.isCurrentGeneration(r))throw o.dispose(),this.calls.delete(o.id),this.callSessions.delete(o.id),this.callOperationError(o.id);return this.events.emit(`call.created`,{callId:o.id,state:o.state}),o}catch(e){if(this.isCurrentGeneration(r)&&c!==void 0&&this.isManagedCall(c)&&c.state===`held`)try{await c.resume()}catch(t){throw this.compensationError(c.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(i)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:y(n)}):this.events.emit(`call.failed`,{callId:e.id,error:b(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(t){if(this.disposed)return;let n=m(),r=this.incomingSessionSnapshot;if(r===void 0||!r.policy.incomingEnabled||!this.effectiveCapabilities(r).has(`inbound`)){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:this.capabilityError(n)});return}let i=t.from??t.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(r)){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:new e.i(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:n})});return}let a;try{a=new u({id:n,destination:i,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(r),session:t,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(n,e)});return}this.calls.set(a.id,a),this.callSessions.set(a.id,t),this.options.onCallCreated?.(a.id,t);try{a.beginIncoming(),this.events.emit(`call.incoming`,{callId:a.id,from:i})}catch(e){a.dispose(),this.events.emit(`error`,{error:this.callOperationError(a.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(t,n){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}capabilityError(t){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(t,n){return t instanceof e.i?new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t}):new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}},v=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function y(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function b(t,n){if(t instanceof e.i)return new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t});if(typeof t==`object`&&t&&`error`in t){let r=t.error;if(r instanceof e.i)return new e.i(r.code,r.category,r.retryable,{requestId:r.requestId,callId:n,cause:r.cause??r});if(r instanceof Error)return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:r})}return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}var x=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(t){return this.closed?Promise.reject(new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(t.requestId)?Promise.reject(new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:t.requestId})):this.lifecycleState===`reconnecting`&&t.type===`command`&&(t.command===`dial`||t.command===`answer`)?Promise.reject(new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:t.payload?.callId})):new Promise((n,r)=>{let i=setTimeout(()=>{this.pending.delete(t.requestId),r(new e.i(`NETWORK_TIMEOUT`,`network`,!0,{requestId:t.requestId}))},this.timeoutMs);this.pending.set(t.requestId,{resolve:e=>n(e),reject:r,timer:i}),this.port.postMessage(t)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(t){try{let n=e.t(t);if(n.type===`event`){n.event===`connection.stateChanged`&&S(n.payload)&&(this.lifecycleState=n.payload.state),this.eventHandlers.forEach(e=>e(n));return}if(n.type!==`response`)return;let r=this.pending.get(n.requestId);if(r===void 0)return;this.pending.delete(n.requestId),clearTimeout(r.timer),n.ok?r.resolve(n.result):r.reject(ne(n))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function S(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function ne(t){let n=t.error;return new e.i(n?.code??`SDK_INTERNAL_ERROR`,n?.category??`internal`,n?.retryable??!1,{requestId:t.requestId,...n?.message===void 0?{}:{cause:n.message},...n?.serverCode===void 0?{}:{serverCode:n.serverCode},...n?.status===void 0?{}:{status:n.status}})}function C(t={}){if((t.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let n=t.locationHref??T(),r=w(t.url,n),i=n=>{if(t.fallback===`error`)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:n});return{mode:`single-tab`,reason:n}};if(r===void 0)return i(`SharedWorker URL is unavailable`);if(!ie(r,n))return i(`SharedWorker URL must be same-origin`);let a=t.workerCtor??re();if(a===void 0)return i(`SharedWorker is not supported`);let o;try{o=new a(r,t.name===void 0?void 0:{name:t.name})}catch(e){return i(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let s=t.tabId??ae(),c=new x(o.port),l={version:1,type:`attach`,requestId:oe(),tabId:s},u=c.request(l).then(()=>void 0).catch(e=>{throw c.close(),e});return{mode:`shared`,worker:o,client:c,tabId:s,workerUrl:r,ready:u}}function w(e,t=T()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function T(){return typeof location>`u`?void 0:location.href}function re(){if(typeof SharedWorker==`function`)return SharedWorker}function ie(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function ae(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function oe(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}var E=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??D(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw A(e)}O(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw j(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(t,n){if(!this.supportsOutputSelection())throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=t;let r=++this.outputGeneration;n!==void 0&&await this.enqueueOutput(async()=>{r===this.outputGeneration&&await this.applyOutputDevice(t,n)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(t,n){let r=n;if(typeof r.setSinkId!=`function`)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await r.setSinkId(t)}catch(e){throw M(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw k(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function D(){return globalThis.navigator?.mediaDevices}function O(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function k(t){let n=N(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function A(t){let n=N(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function j(t){let n=N(t);return n===`NotFoundError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function M(t){let n=N(t);return n===`NotFoundError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function N(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}var P=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=F){this.createAudioElement=e}async bind(t,n){let r=this.bindings.get(t);if(r?.stream===n)return;let i=I(t,n),a;try{a=this.createAudioElement()}catch(n){throw L(i,this.trackOwners),new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t,cause:n})}let o=this.audioOwners.get(a);if(o!==void 0&&o!==t)throw L(i,this.trackOwners),new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});try{a.autoplay=!0,a.playsInline=!0}catch(n){throw L(i,this.trackOwners),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}try{a.srcObject=n}catch(n){throw L(i,this.trackOwners),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}this.acquireTracks(i),r!==void 0&&this.releaseBinding(r,r.audio!==a);let s=this.nextGeneration(t);this.audioOwners.set(a,t);let c={callId:t,audio:a,stream:n,tracks:i,generation:s};this.bindings.set(t,c),this.beginPlay(t);try{await a.play()}catch(n){if(!this.isCurrent(t,s))return;throw new e.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,s)}async play(t){let n=this.bindings.get(t);if(n===void 0)throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});let r=n.generation;this.beginPlay(t);try{await n.audio.play()}catch(n){if(!this.isCurrent(t,r))return;throw new e.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,r)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),z(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function F(){if(typeof document>`u`)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function I(t,n){try{return[...new Set(n.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(r){try{return[...new Set(n.getTracks())].filter(e=>e.kind===`audio`)}catch(i){throw R(n),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:r??i})}}}function L(e,t){e.forEach(e=>{(t.get(e)??0)===0&&z(e)})}function R(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(z)}catch{}}function z(e){try{e.stop()}catch{}}var B=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new E(t),this.remoteAudio=new P(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??se}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=V(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(t){let n=this.releaseOperations.get(t);if(n!==void 0)return n;if(!this.resources.has(t))return Promise.resolve();let r=t.callId;this.remoteAudio.release(r),this.releaseErrors.delete(t),this.calls.get(r)===t&&this.calls.delete(r),t.generation+=1,t.released=!0,this.unsubscribeTrackSource(t);let i=new Set([...t.localTracks,...t.pendingTracks]),a=[...t.senders.values()].filter(e=>e.audio).map(e=>({senderResource:e,promise:this.enqueueSender(t,e,()=>W(e.sender),!0)})),o=Promise.all(a.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async n=>{let a=new Set,o=[];if(n.forEach(e=>{if(e.cause!==void 0){o.push(e.cause);let t=H(e.senderResource.sender);t?.kind===`audio`&&a.add(t);return}let t=H(e.senderResource.sender);t?.kind===`audio`&&i.add(t)}),i.forEach(e=>{a.has(e)||q(e)}),o.length>0)throw t.localTracks.clear(),t.pendingTracks.clear(),a.forEach(e=>t.localTracks.add(e)),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:o[0]});if(!t.peerClosed&&t.peerConnection.close!==void 0)try{await t.peerConnection.close(),t.peerClosed=!0}catch(n){let i=[...t.senders.values()].map(e=>H(e.sender)).find(e=>e?.kind===`audio`);throw t.localTracks.clear(),t.pendingTracks.clear(),i!=null&&t.localTracks.add(i),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:n})}t.localTracks.clear(),t.pendingTracks.clear(),t.senders.clear(),this.resources.delete(t),this.releaseUnusedSenderQueues()}).catch(e=>{throw this.releaseErrors.set(t,e),this.calls.get(r)===void 0&&this.calls.set(r,t),e}).finally(()=>{this.releaseOperations.get(t)===o&&this.releaseOperations.delete(t)});return this.releaseOperations.set(t,o),o}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(t,n,r){if(this.assertActiveCall(n),this.assertDeviceSelectionCapability(n),!this.isCurrentResource(r)||n.peerConnection!==r.peerConnection)throw this.callOperationError(n.callId);let i=this.findAudioSender(r),a=H(i.sender),o=r.generation,s=await this.deviceManager.openInputStream(t),c;try{c=s.getTracks()}catch(t){throw G(s),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let l;try{l=s.getAudioTracks()}catch(t){throw K(c),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let u=l[0];if(u===void 0)throw K(c),new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:n.callId});if(!this.canCommitInputSwitch(n,r,i,a,o))throw K(c),this.callOperationError(n.callId);c.forEach(e=>r.pendingTracks.add(e)),r.pendingTracks.add(u);try{await this.enqueueSender(r,i,()=>i.sender.replaceTrack(u))}catch(t){throw r.released?this.callOperationError(n.callId):(r.released||(c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),await this.rollbackSender(r,i,a,u),K(c)),new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:n.callId,cause:t}))}if(!this.canCommitInputSwitch(n,r,i,u,o)){if(!r.released)try{await this.enqueueSender(r,i,()=>H(i.sender)===u?W(i.sender):Promise.resolve()),c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),K(c)}catch(t){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n.callId,cause:t})}throw this.callOperationError(n.callId)}c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),r.localTracks.add(u),a!==null&&a!==u&&(r.localTracks.delete(a),q(a)),c.forEach(e=>{e!==u&&q(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(t,n){let r;try{r=t.peerConnection.getSenders()}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}r.forEach(r=>{let i=H(r),a;try{a=n?.(r)??r.senderKind??r.kind}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}t.senders.set(r,{sender:r,audio:a===`audio`||a===void 0&&i?.kind===`audio`,queue:this.senderQueues.get(r)??this.createSenderQueue(r)}),i?.kind===`audio`&&t.localTracks.add(i)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(H(e.sender)?.kind===`audio`||H(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return H(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||H(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(t){if(t===void 0||t.state!==`active`)throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(t){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}callOperationError(t){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t})}assertNotDisposed(){if(this.disposed||this.disposing)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function V(e){return`peerConnection`in e}function H(e){try{return e.track}catch{return null}}function U(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function W(e){try{return e.replaceTrack(null).catch(e=>{if(!U(e))throw e})}catch(e){return U(e)?Promise.resolve():Promise.reject(e)}}function G(e){try{K(e.getTracks())}catch{}}function K(e){e.forEach(q)}function q(e){try{e.stop()}catch{}}function se(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}function ce(t,n={}){let r=new Map,i=new Map,a=new Set,o=n.ownershipRequired===!0,s=!1,c=!1,l,u=()=>t(),d=new B({getActiveCall:u});return{publicMedia:{requestPermission:()=>(f(),d.requestPermission()),getDevices:()=>(f(),d.getDevices()),getCapabilities:()=>(f(),d.getCapabilities()),supportsOutputSelection:()=>(f(),d.supportsOutputSelection()),setInputDevice:e=>(f(),d.setInputDevice(e,u())),setOutputDevice:e=>(f(),d.setOutputDevice(e)),playRemoteAudio:e=>(f(),d.playRemoteAudio(e)),releaseAll:()=>(f(),d.releaseAll())},registerCall(e,t){s||c||!J(t)||(i.set(e,t),(!o||a.has(e))&&p(e,t))},async setCallOwnership(e,t){if(s)return;if(t!==`owned`){a.delete(e),await d.releaseCall(e),r.delete(e);return}a.add(e);let n=i.get(e);n!==void 0&&p(e,n)},contextFor(e,t,n){let i=r.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:n,peerConnection:i.peerConnection}},async releaseCall(e){s||(await d.releaseCall(e),r.delete(e),i.delete(e),a.delete(e))},releaseAll:async()=>{await d.releaseAll(),r.clear(),i.clear(),a.clear()},getResourceCounts:()=>d.getResourceCounts(),dispose:()=>{if(l!==void 0)return l;c=!0;let e=d.dispose().then(()=>{s=!0,c=!1,r.clear(),i.clear(),a.clear()}).finally(()=>{l===e&&!s&&(l=void 0,c=!1)});return l=e,e}};function f(){if(s)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function p(e,t){if(!J(t)||typeof t.getMediaRegistration!=`function`)return;let n=t.getMediaRegistration();if(le(n)&&r.get(e)?.peerConnection!==n.peerConnection){r.set(e,n);try{d.registerCallMedia(e,n)}catch{r.delete(e)}}}}function J(e){return typeof e==`object`&&!!e}function le(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var ue=1e3,de=3e4;function fe(e,t=Math.random){let n=Math.min(de,ue*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var pe=class{recover;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=fe(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},me=class r{media;options;api;suppliedSip;sip;events=new n;mediaBridge;reconnect;diagnostics;callManager;session;state=`idle`;initialized=!1;disposed=!1;intentionalDisconnect=!1;deferredRebuild=!1;sessionRecoveryPending=!1;detectedPlatform;support;acceptingEvents=!0;connectOperation;disconnectOperation;refreshOperation;disposeOperation;refreshTimer;lifecycleGeneration=0;managerUnsubscribers=[];sipUnsubscribe;networkUnsubscribers=[];sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;sharedWorkerSelection;constructor(n){if(this.options=n,n.api===void 0&&n.sessionProvider===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`CCBarClient 需要 sessionProvider`});this.api=n.api===void 0?Y(X(n.sessionProvider)):Y(n.api),this.suppliedSip=n.sip===void 0?void 0:_e(n.sip),this.mediaBridge=ce(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new pe({recover:()=>this.recoverConnection(),onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new t.t({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)}),this.sharedWorkerSelection=n.sharedWorker===void 0?{mode:`single-tab`,reason:`disabled`}:C({...n.sharedWorker,...n.sharedWorkerHost??{}})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=ge(typeof navigator<`u`?navigator.userAgent:``);return{supported:e&&t,platform:n,hasMediaDevices:e,hasWebSocket:t,...e&&t?{}:{reason:`当前运行环境缺少 WebPhone 所需的浏览器能力`}}}async initialize(){if(this.assertNotDisposed(),this.initialized)return;let e=await r.checkSupport();this.support=e,this.options.platform===void 0&&(e.platform===`web`||e.platform===`mobile-web`)&&(this.detectedPlatform=e.platform),await this.awaitSharedWorkerReady(),this.assertNotDisposed(),this.initialized=!0}connect(){if(this.assertNotDisposed(),this.api.invalidateToken?.(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();let e=this.lifecycleGeneration,t=this.performConnect(e).finally(()=>{this.connectOperation===t&&(this.connectOperation=void 0)});return this.connectOperation=t,t}disconnect(){if(this.assertNotDisposed(),this.disconnectOperation!==void 0)return this.disconnectOperation;if(this.state===`idle`&&this.connectOperation===void 0||this.state===`disconnected`&&this.connectOperation===void 0)return Promise.resolve();this.lifecycleGeneration+=1,this.acceptingEvents=!1;let e=this.performDisconnect().finally(()=>{this.disconnectOperation===e&&(this.disconnectOperation=void 0)});return this.disconnectOperation=e,e}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.lifecycleGeneration+=1,this.intentionalDisconnect=!0,this.acceptingEvents=!1,this.reconnect.dispose(),this.clearRefreshTimer(),this.detachNetworkListeners(),this.releaseSharedWorker(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(t){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.dial(t,r)}answer(t,n){this.assertConnected();let r=this.callManager,i=this.session;if(r===void 0||i===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return r.answer(t,i,n)}setActiveCall(t){this.assertConnected();let n=this.callManager;if(n===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.setActiveCall(t)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getSharedWorkerState(){let e=this.sharedWorkerSelection;return e.mode===`shared`?{mode:`shared`,tabId:e.tabId}:{mode:`single-tab`,reason:e.reason}}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){this.assertNotDisposed();let t=this.session?.transport.wssUrl;await this.api.setAgentStatus({status:e,reason:``},t===void 0?void 0:{wssUrl:t}),this.disposed||this.events.emit(`agent.statusChanged`,{status:e})}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}off(e,t){this.events.off(e,t)}async performConnect(e){let n,r,i;try{await this.initialize(),this.assertGeneration(e);let a=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),n=await this.api.createSession({sdkVersion:t.r,platform:a===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??xe(a)]}),this.ownedSessionIds.add(n.sessionId),this.assertGeneration(e),r=await this.getSip(),this.assertGeneration(e),this.session=n;let o=this.callManager??this.createCallManager(r,n,a);this.callManager===void 0&&(i=o),o.updateSession(n),this.callManager=o,this.attachSipListener(r),this.attachNetworkListeners(),await r.connect(n),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(n)}catch(t){if(await this.rollbackConnect(n,r,i),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw t;let a=Z(t,`REGISTRATION_FAILED`,`registration`,!0);throw this.setConnectionState(`failed`),this.events.emit(`connection.failed`,{error:a}),a}}async performDisconnect(){let e,t=this.connectOperation;if(t!==void 0)try{await t}catch(t){$(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){$(t)||(e??=t)}this.reconnect.cancel(),this.clearRefreshTimer(),this.intentionalDisconnect=!0,this.detachNetworkListeners(),this.detachSipListener(),this.detachManagerListeners();let r=this.callManager,i=this.sip;this.callManager=void 0;try{await r?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{i!==void 0&&await i.disconnect()}catch(t){e??=t}this.session=void 0;try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new _({sip:e,platform:n,session:t,maxConcurrentCalls:this.options.maxConcurrentCalls,autoHoldPreviousCall:this.options.autoHoldPreviousCall,onCallCreated:(e,t)=>this.handleCallCreated(e,t),onCallStateChanged:(e,t)=>this.handleCallStateChanged(e,t),onCallTerminal:e=>this.handleCallTerminal(e)});return this.bindManagerEvents(r),r}async rollbackConnect(e,t,n){if(n!==void 0){this.detachManagerListeners(),this.callManager===n&&(this.callManager=void 0);try{await n.dispose({terminateCalls:!0})}catch{}}if(t!==void 0){this.detachSipListener();try{await t.disconnect()}catch{}}if(this.session===e&&(this.session=void 0),e!==void 0)try{await this.deleteSession(e.sessionId)}catch{}}async performDispose(){let e,t=[this.connectOperation,this.disconnectOperation,this.refreshOperation].filter(e=>e!==void 0);for(let n of t)try{await n}catch(t){$(t)||(e??=t)}let n=this.callManager;this.callManager=void 0;try{await n?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{await this.media.releaseAll()}catch(t){ve(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await n,this.terminalReleaseOperations.delete(t)}catch(n){try{await this.mediaBridge.releaseCall(t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}detachSipListener(){let e=this.sipUnsubscribe;this.sipUnsubscribe=void 0;try{e?.()}catch{}}detachManagerListeners(){this.managerUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}bindManagerEvents(e){[`call.created`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`error`].forEach(t=>{let n=e.on(t,e=>{this.acceptingEvents&&!this.disposed&&(this.diagnostics.log(t===`error`||t===`call.failed`?`error`:`info`,String(t),e),this.events.emit(t,e))});this.managerUnsubscribers.push(n)})}handleCallCreated(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallStateChanged(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallTerminal(e){let t=this.startTerminalRelease(e);return this.deferredRebuild&&!this.hasNonTerminalCalls()&&this.startDeferredRecovery(),t}startTerminalRelease(e){let t=this.terminalReleaseOperations.get(e);if(t!==void 0)return t;let n=this.mediaBridge.releaseCall(e).then(()=>{this.terminalReleaseOperations.get(e)===n&&this.terminalReleaseOperations.delete(e)}).catch(t=>{throw this.acceptingEvents&&!this.disposed&&this.events.emit(`error`,{error:Z(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{if(await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed){if(this.sessionRecoveryPending){this.recoverInvalidSession();return}this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start()}}catch{!this.disposed&&!this.sessionRecoveryPending&&this.reconnect.start()}}async refreshAndRebuild(){if(this.refreshOperation!==void 0)return this.refreshOperation;let e=this.performRefreshAndRebuild().finally(()=>{this.refreshOperation===e&&(this.refreshOperation=void 0),this.sessionRecoveryPending&&!this.hasNonTerminalCalls()&&!this.disposed&&this.recoverInvalidSession()});return this.refreshOperation=e,e}async performRefreshAndRebuild(){if(this.disposed||this.session===void 0)return;let e=this.lifecycleGeneration,t=this.session;try{let n=await this.api.refreshSession(t.sessionId);if(!this.isCurrentGeneration(e)||this.session!==t)return;if(this.session=n,this.callManager?.updateSession(n),this.events.emit(`token.refreshed`,{expiresAt:n.expiresAt}),this.hasNonTerminalCalls()){this.deferredRebuild=!0,this.scheduleRefresh(n);return}let r=await this.getSip();if(!this.isCurrentGeneration(e))return;await r.connect(n),this.isCurrentGeneration(e)&&(this.deferredRebuild=!1,this.setConnectionState(`connected`),this.scheduleRefresh(n))}catch(n){if(!this.isCurrentGeneration(e))return;throw this.handleRefreshFailure(t,n),n}}handleRefreshFailure(e,t){if(this.disposed)return;let n=Z(t,`NETWORK_OFFLINE`,`network`,!0);if(this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),Q(t)){this.clearRefreshTimer(),this.reconnect.cancel(),this.deletedSessions.add(e.sessionId),this.sessionRecoveryPending=!0,this.deferredRebuild=!0,(n.code===`AUTH_TOKEN_UNAVAILABLE`||n.code===`AUTH_TOKEN_EXPIRED`)&&this.api.invalidateToken?.();return}this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}async recoverInvalidSession(){if(!(!this.sessionRecoveryPending||this.disposed||this.hasNonTerminalCalls())){this.sessionRecoveryPending=!1,this.deferredRebuild=!1;try{await this.performDisconnect()}catch(e){this.disposed||this.events.emit(`error`,{error:Z(e,`SDK_INTERNAL_ERROR`,`internal`,!0)});return}if(!this.disposed)try{await this.performConnect(this.lifecycleGeneration)}catch{this.reconnect.cancel()}}}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){this.disposed||this.intentionalDisconnect||this.hasNonTerminalCalls()||(await this.awaitMediaReleaseBarriers(),await this.refreshAndRebuild())}async getSip(){if(this.sip!==void 0)return this.sip;if(this.suppliedSip!==void 0)return this.sip=this.suppliedSip,this.sip;let[e,t]=await Promise.all([Promise.resolve().then(()=>require("./createJsSipFactory-Dr8HbLl-.cjs")),Promise.resolve().then(()=>require("./JsSipAdapter-BN9BAFHr.cjs"))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl,this.options.sipKeepaliveSeconds,this.options.agentTerminal,this.options.sipSessionTimers??!1),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:Z(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>this.reconnect.notifyOnline(),n=()=>this.reconnect.notifyOffline();e.addEventListener(`online`,t),e.addEventListener(`offline`,n),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n)]}detachNetworkListeners(){this.networkUnsubscribers.splice(0).forEach(e=>e())}getActiveMediaContext(){let e=this.callManager?.getActiveCall();return e===void 0?void 0:this.mediaBridge.contextFor(e.id,e.state,new Set(this.session?.capabilities??[]))}hasNonTerminalCalls(){return this.callManager?.hasNonTerminalCalls()??!1}clearRefreshTimer(){this.refreshTimer!==void 0&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}createDiagnosticsSnapshot(){let e=this.session;return{connectionState:this.state,calls:this.getCalls().map(e=>({callId:e.id,state:e.state,destination:e.destination})),permission:this.support?.hasMediaDevices===!1?`unsupported`:`unknown`,ice:he(e),wss:{configured:e!==void 0,secure:e?.transport.wssUrl.toLowerCase().startsWith(`wss://`)??!1,state:this.state},resources:this.getDiagnosticsResourceCounts()}}getDiagnosticsResourceCounts(){let e=this.mediaBridge.getResourceCounts(),t=this.callManager?.getResourceCounts()??{timers:0,listeners:0},n=this.sip?.getResourceCounts?.(),r=(this.callManager===void 0?0:1)+(this.sipUnsubscribe===void 0?0:1),i=this.session!==void 0&&this.state!==`idle`&&this.state!==`disconnected`;return{timers:(this.refreshTimer===void 0?0:1)+this.reconnect.getTimerCount()+t.timers,listeners:this.events.listenerCount()+t.listeners+e.listeners+this.networkUnsubscribers.length+(n?.listeners??r),tracks:e.tracks,peerConnections:e.peerConnections,audioElements:e.audioElements,webSockets:n?.webSockets??+!!i,deletedSessions:this.deletedSessions.size}}async readMicrophonePermission(){if(typeof navigator>`u`||navigator.mediaDevices===void 0)return`unsupported`;if(navigator.permissions===void 0)return`unknown`;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}deleteSession(e){if(this.deletedSessions.has(e))return Promise.resolve();let t=this.sessionDeleteOperations.get(e);if(t!==void 0)return t;let n=this.api.deleteSession(e).then(()=>{this.deletedSessions.add(e)}).catch(t=>{if(Q(t)){this.deletedSessions.add(e);return}throw t}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}pruneDeletedSessionTombstones(){for(let e of[...this.deletedSessions])!this.ownedSessionIds.has(e)&&!this.sessionDeleteOperations.has(e)&&this.deletedSessions.delete(e)}async deleteOwnedSessions(){let e;for(let t of[...this.ownedSessionIds])try{await this.deleteSession(t),this.ownedSessionIds.delete(t)}catch(t){e??=t}if(e!==void 0)throw e}resolvePlatform(){let t=this.options.platform??this.detectedPlatform;if(t===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return t}setConnectionState(e){this.state===e||this.disposed||(this.state=e,this.diagnostics.log(`info`,`connection.stateChanged`,{state:e}),this.events.emit(`connection.stateChanged`,{state:e===`disconnected`||e===`idle`?`offline`:e}))}assertConnected(){if(this.assertNotDisposed(),this.state!==`connected`||this.callManager===void 0||this.session===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(t){if(this.disposed)throw this.disposedError();if(t!==this.lifecycleGeneration)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}async awaitSharedWorkerReady(){let e=this.sharedWorkerSelection;if(e.mode===`shared`)try{await e.ready}catch(e){if(this.disposed)return;if(this.options.sharedWorker?.fallback===`error`)throw e;this.sharedWorkerSelection={mode:`single-tab`,reason:e instanceof Error?e.message:`SharedWorker attach failed`}}}releaseSharedWorker(){let e=this.sharedWorkerSelection;if(this.sharedWorkerSelection={mode:`single-tab`,reason:`disposed`},e.mode===`shared`){try{e.client.request({version:1,type:`detach`,requestId:`detach-${e.tabId}`,tabId:e.tabId}).catch(()=>void 0)}catch{}e.client.close()}}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function he(e){if(e===void 0)return{configured:!1,serverCount:0,stunServerCount:0,turnServerCount:0};let t=0,n=0;return e.iceServers.forEach(e=>{let r=e.urls.map(e=>e.toLowerCase());r.some(e=>e.startsWith(`stun:`))&&(t+=1),r.some(e=>e.startsWith(`turn:`)||e.startsWith(`turns:`))&&(n+=1)}),{configured:e.iceServers.length>0,serverCount:e.iceServers.length,stunServerCount:t,turnServerCount:n}}function ge(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function Y(t){if(typeof t!=`object`||!t)throw new e.i(`CONFIG_INVALID`,`configuration`,!1);return t}function X(n){let r={createSession:e=>n.createSession(e),refreshSession:e=>n.refreshSession===void 0?n.createSession({sdkVersion:t.r,platform:`web`}):n.refreshSession(e),deleteSession:async e=>{n.deleteSession!==void 0&&await n.deleteSession(e)},setAgentStatus:(t,r)=>n.setAgentStatus===void 0?Promise.reject(new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{cause:`当前会话来源不支持坐席状态设置(sessionProvider.setAgentStatus 未提供)`})):n.setAgentStatus(t,r)},i=n.invalidateToken;return i!==void 0&&(r.invalidateToken=()=>i()),r}function _e(t){if(typeof t!=`object`||!t)throw new e.i(`CONFIG_INVALID`,`configuration`,!1);return t}function Z(t,n,r,i,a){return t instanceof e.i?new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:a??t.callId,cause:t.cause??t,serverCode:t.serverCode,status:t.status}):new e.i(n,r,i,{callId:a,cause:t})}function Q(t){return t instanceof e.i?t.status!==void 0&&t.status>=400&&t.status<500||t.serverCode===`SESSION_NOT_FOUND`||t.serverCode===`SESSION_EXPIRED`||t.serverCode===`TOKEN_INVALID`||t.serverCode===`TOKEN_EXPIRED`||t.code===`AUTH_TOKEN_UNAVAILABLE`||t.code===`AUTH_TOKEN_EXPIRED`:!1}function ve(t){return t instanceof e.i&&t.code===`SDK_ALREADY_DISPOSED`}function $(t){return t instanceof e.i&&(t.code===`SDK_ALREADY_DISPOSED`||t.code===`CALL_NOT_CONNECTED`)}var ye=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],be=[`outbound`,`mute`,`dtmf`];function xe(e){return e===`mobile-web`?be:ye}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return r}});
1
+ const e=require("./SharedWorkerProtocol-39dch6xL.cjs"),t=require("./Diagnostics--D2xwro7.cjs");var n=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},r={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},i=(e,t)=>r[e].has(t);function a(e,t){if(!i(e,t))throw new o(e,t);return t}var o=class extends e.i{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},s=a,c=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],l=3e4,u=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(t){this.options=t,this.id=t.id,this.destination=t.destination,this.platform=t.platform,this.capabilities=t.capabilities??new Set;try{c.forEach(e=>{this.sessionUnsubscribers.push(t.session.on(e,t=>this.handleSessionEvent(e,t)))})}catch(n){this.cleanupSessionListeners();try{t.session.terminate()}catch{}throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:n})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,`held`,()=>this.options.session.hold())}async resume(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),await this.startPendingOperation(`resume`,`active`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!f(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),d(this.currentState))throw this.operationError();try{this.options.session.terminate(),d(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!d(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||d(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.transitionIfAllowed(`held`,t,e);break;case`unhold`:this.transitionIfAllowed(`active`,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(i(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!i(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,d(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{d(e)&&this.dispose()}}startPendingOperation(e,t,n){if(this.pendingOperation!==void 0)throw this.operationError();return new Promise((r,i)=>{let a={kind:e,nextState:t,resolve:r,reject:i};this.pendingOperation=a,a.timer=setTimeout(()=>this.timeoutPendingOperation(a),l);let o;try{o=n()}catch(e){this.rejectPendingOperation(e);return}o.then(()=>this.resolvePendingOperation(a),e=>this.rejectPendingOperation(e,a))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||d(this.currentState)){e.reject(this.operationError());return}try{this.transitionTo(e.nextState),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(t){let n=t instanceof e.i&&t.callId===this.id?t:this.operationError(t);try{this.options.onError?.(n)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(t){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}};function d(e){return e===`ended`||e===`failed`}function f(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var p=0;function m(){return p+=1,`call_${Date.now().toString(36)}_${p.toString(36)}`}var h=`X-User-Data`,g=/[^\x20-\x7E]/,ee=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function te(t){if(typeof t!=`string`)return[];let n=t.trim();if(n===``)return[];if(g.test(n))throw new e.i(`CALL_INVALID_USERDATA`,`call`,!1,{cause:ee});return[`${h}: ${n}`]}var _=class{events=new v;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(t){this.options=t,this.incomingSessionSnapshot=t.session;try{this.incomingUnsubscribe=t.sip.onIncoming(e=>this.handleIncoming(e))}catch(t){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(t,n){this.assertNotDisposed();let r=this.operationGeneration,i=t.destination.trim();if(i===``)throw new e.i(`CALL_INVALID_DESTINATION`,`call`,!1);let a=te(t.userdata);this.requireCapability(n,`outbound`);let o=this.callLimit(n);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=o)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=o||this.pendingDestinations.has(i)||[...this.calls.values()].some(e=>e.destination===i))throw new e.i(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(i);let s=m(),c;try{c=await this.holdActiveCallForNewCall(),this.assertGeneration(r,s);let e;try{e=this.options.sip.dial(i,this.dialOptions(s,n,t.type,a))}catch(e){throw this.dialError(e,s)}this.assertGeneration(r,s);let o;try{o=new u({id:s,destination:i,platform:this.options.platform,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(o,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(o)})}catch(e){throw this.dialError(e,s)}if(!this.isCurrentGeneration(r))throw o.dispose(),this.callOperationError(o.id);this.calls.set(o.id,o),this.callSessions.set(o.id,e),this.options.onCallCreated?.(o.id,e);try{o.beginOutbound()}catch(e){throw o.dispose(),this.calls.delete(o.id),this.callSessions.delete(o.id),this.dialError(e,o.id)}if(!this.isCurrentGeneration(r))throw o.dispose(),this.calls.delete(o.id),this.callSessions.delete(o.id),this.callOperationError(o.id);return this.events.emit(`call.created`,{callId:o.id,state:o.state}),o}catch(e){if(this.isCurrentGeneration(r)&&c!==void 0&&this.isManagedCall(c)&&c.state===`held`)try{await c.resume()}catch(t){throw this.compensationError(c.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(i)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:y(n)}):this.events.emit(`call.failed`,{callId:e.id,error:b(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(t){if(this.disposed)return;let n=m(),r=this.incomingSessionSnapshot;if(r===void 0||!r.policy.incomingEnabled||!this.effectiveCapabilities(r).has(`inbound`)){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:this.capabilityError(n)});return}let i=t.from??t.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(r)){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:new e.i(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:n})});return}let a;try{a=new u({id:n,destination:i,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(r),session:t,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(n,e)});return}this.calls.set(a.id,a),this.callSessions.set(a.id,t),this.options.onCallCreated?.(a.id,t);try{a.beginIncoming(),this.events.emit(`call.incoming`,{callId:a.id,from:i})}catch(e){a.dispose(),this.events.emit(`error`,{error:this.callOperationError(a.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(t,n){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}capabilityError(t){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(t,n){return t instanceof e.i?new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t}):new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}},v=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function y(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function b(t,n){if(t instanceof e.i)return new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t});if(typeof t==`object`&&t&&`error`in t){let r=t.error;if(r instanceof e.i)return new e.i(r.code,r.category,r.retryable,{requestId:r.requestId,callId:n,cause:r.cause??r});if(r instanceof Error)return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:r})}return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}var x=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(t){return this.closed?Promise.reject(new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(t.requestId)?Promise.reject(new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:t.requestId})):this.lifecycleState===`reconnecting`&&t.type===`command`&&(t.command===`dial`||t.command===`answer`)?Promise.reject(new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:t.payload?.callId})):new Promise((n,r)=>{let i=setTimeout(()=>{this.pending.delete(t.requestId),r(new e.i(`NETWORK_TIMEOUT`,`network`,!0,{requestId:t.requestId}))},this.timeoutMs);this.pending.set(t.requestId,{resolve:e=>n(e),reject:r,timer:i}),this.port.postMessage(t)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(t){try{let n=e.t(t);if(n.type===`event`){n.event===`connection.stateChanged`&&S(n.payload)&&(this.lifecycleState=n.payload.state),this.eventHandlers.forEach(e=>e(n));return}if(n.type!==`response`)return;let r=this.pending.get(n.requestId);if(r===void 0)return;this.pending.delete(n.requestId),clearTimeout(r.timer),n.ok?r.resolve(n.result):r.reject(ne(n))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function S(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function ne(t){let n=t.error;return new e.i(n?.code??`SDK_INTERNAL_ERROR`,n?.category??`internal`,n?.retryable??!1,{requestId:t.requestId,...n?.message===void 0?{}:{cause:n.message},...n?.serverCode===void 0?{}:{serverCode:n.serverCode},...n?.status===void 0?{}:{status:n.status}})}function C(t={}){if((t.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let n=t.locationHref??T(),r=w(t.url,n),i=n=>{if(t.fallback===`error`)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:n});return{mode:`single-tab`,reason:n}};if(r===void 0)return i(`SharedWorker URL is unavailable`);if(!ie(r,n))return i(`SharedWorker URL must be same-origin`);let a=t.workerCtor??re();if(a===void 0)return i(`SharedWorker is not supported`);let o;try{o=new a(r,t.name===void 0?void 0:{name:t.name})}catch(e){return i(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let s=t.tabId??ae(),c=new x(o.port),l={version:1,type:`attach`,requestId:oe(),tabId:s},u=c.request(l).then(()=>void 0).catch(e=>{throw c.close(),e});return{mode:`shared`,worker:o,client:c,tabId:s,workerUrl:r,ready:u}}function w(e,t=T()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function T(){return typeof location>`u`?void 0:location.href}function re(){if(typeof SharedWorker==`function`)return SharedWorker}function ie(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function ae(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function oe(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}var E=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??D(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw A(e)}O(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw j(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(t,n){if(!this.supportsOutputSelection())throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=t;let r=++this.outputGeneration;n!==void 0&&await this.enqueueOutput(async()=>{r===this.outputGeneration&&await this.applyOutputDevice(t,n)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(t,n){let r=n;if(typeof r.setSinkId!=`function`)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await r.setSinkId(t)}catch(e){throw M(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw k(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function D(){return globalThis.navigator?.mediaDevices}function O(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function k(t){let n=N(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function A(t){let n=N(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function j(t){let n=N(t);return n===`NotFoundError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function M(t){let n=N(t);return n===`NotFoundError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function N(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}var P=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=F){this.createAudioElement=e}async bind(t,n){let r=this.bindings.get(t);if(r?.stream===n)return;let i=I(t,n),a;try{a=this.createAudioElement()}catch(n){throw L(i,this.trackOwners),new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t,cause:n})}let o=this.audioOwners.get(a);if(o!==void 0&&o!==t)throw L(i,this.trackOwners),new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});try{a.autoplay=!0,a.playsInline=!0}catch(n){throw L(i,this.trackOwners),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}try{a.srcObject=n}catch(n){throw L(i,this.trackOwners),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}this.acquireTracks(i),r!==void 0&&this.releaseBinding(r,r.audio!==a);let s=this.nextGeneration(t);this.audioOwners.set(a,t);let c={callId:t,audio:a,stream:n,tracks:i,generation:s};this.bindings.set(t,c),this.beginPlay(t);try{await a.play()}catch(n){if(!this.isCurrent(t,s))return;throw new e.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,s)}async play(t){let n=this.bindings.get(t);if(n===void 0)throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});let r=n.generation;this.beginPlay(t);try{await n.audio.play()}catch(n){if(!this.isCurrent(t,r))return;throw new e.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,r)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),z(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function F(){if(typeof document>`u`)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function I(t,n){try{return[...new Set(n.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(r){try{return[...new Set(n.getTracks())].filter(e=>e.kind===`audio`)}catch(i){throw R(n),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:r??i})}}}function L(e,t){e.forEach(e=>{(t.get(e)??0)===0&&z(e)})}function R(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(z)}catch{}}function z(e){try{e.stop()}catch{}}var B=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new E(t),this.remoteAudio=new P(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??se}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=V(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(t){let n=this.releaseOperations.get(t);if(n!==void 0)return n;if(!this.resources.has(t))return Promise.resolve();let r=t.callId;this.remoteAudio.release(r),this.releaseErrors.delete(t),this.calls.get(r)===t&&this.calls.delete(r),t.generation+=1,t.released=!0,this.unsubscribeTrackSource(t);let i=new Set([...t.localTracks,...t.pendingTracks]),a=[...t.senders.values()].filter(e=>e.audio).map(e=>({senderResource:e,promise:this.enqueueSender(t,e,()=>W(e.sender),!0)})),o=Promise.all(a.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async n=>{let a=new Set,o=[];if(n.forEach(e=>{if(e.cause!==void 0){o.push(e.cause);let t=H(e.senderResource.sender);t?.kind===`audio`&&a.add(t);return}let t=H(e.senderResource.sender);t?.kind===`audio`&&i.add(t)}),i.forEach(e=>{a.has(e)||q(e)}),o.length>0)throw t.localTracks.clear(),t.pendingTracks.clear(),a.forEach(e=>t.localTracks.add(e)),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:o[0]});if(!t.peerClosed&&t.peerConnection.close!==void 0)try{await t.peerConnection.close(),t.peerClosed=!0}catch(n){let i=[...t.senders.values()].map(e=>H(e.sender)).find(e=>e?.kind===`audio`);throw t.localTracks.clear(),t.pendingTracks.clear(),i!=null&&t.localTracks.add(i),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:n})}t.localTracks.clear(),t.pendingTracks.clear(),t.senders.clear(),this.resources.delete(t),this.releaseUnusedSenderQueues()}).catch(e=>{throw this.releaseErrors.set(t,e),this.calls.get(r)===void 0&&this.calls.set(r,t),e}).finally(()=>{this.releaseOperations.get(t)===o&&this.releaseOperations.delete(t)});return this.releaseOperations.set(t,o),o}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(t,n,r){if(this.assertActiveCall(n),this.assertDeviceSelectionCapability(n),!this.isCurrentResource(r)||n.peerConnection!==r.peerConnection)throw this.callOperationError(n.callId);let i=this.findAudioSender(r),a=H(i.sender),o=r.generation,s=await this.deviceManager.openInputStream(t),c;try{c=s.getTracks()}catch(t){throw G(s),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let l;try{l=s.getAudioTracks()}catch(t){throw K(c),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let u=l[0];if(u===void 0)throw K(c),new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:n.callId});if(!this.canCommitInputSwitch(n,r,i,a,o))throw K(c),this.callOperationError(n.callId);c.forEach(e=>r.pendingTracks.add(e)),r.pendingTracks.add(u);try{await this.enqueueSender(r,i,()=>i.sender.replaceTrack(u))}catch(t){throw r.released?this.callOperationError(n.callId):(r.released||(c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),await this.rollbackSender(r,i,a,u),K(c)),new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:n.callId,cause:t}))}if(!this.canCommitInputSwitch(n,r,i,u,o)){if(!r.released)try{await this.enqueueSender(r,i,()=>H(i.sender)===u?W(i.sender):Promise.resolve()),c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),K(c)}catch(t){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n.callId,cause:t})}throw this.callOperationError(n.callId)}c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),r.localTracks.add(u),a!==null&&a!==u&&(r.localTracks.delete(a),q(a)),c.forEach(e=>{e!==u&&q(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(t,n){let r;try{r=t.peerConnection.getSenders()}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}r.forEach(r=>{let i=H(r),a;try{a=n?.(r)??r.senderKind??r.kind}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}t.senders.set(r,{sender:r,audio:a===`audio`||a===void 0&&i?.kind===`audio`,queue:this.senderQueues.get(r)??this.createSenderQueue(r)}),i?.kind===`audio`&&t.localTracks.add(i)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(H(e.sender)?.kind===`audio`||H(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return H(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||H(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(t){if(t===void 0||t.state!==`active`)throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(t){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}callOperationError(t){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t})}assertNotDisposed(){if(this.disposed||this.disposing)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function V(e){return`peerConnection`in e}function H(e){try{return e.track}catch{return null}}function U(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function W(e){try{return e.replaceTrack(null).catch(e=>{if(!U(e))throw e})}catch(e){return U(e)?Promise.resolve():Promise.reject(e)}}function G(e){try{K(e.getTracks())}catch{}}function K(e){e.forEach(q)}function q(e){try{e.stop()}catch{}}function se(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}function ce(t,n={}){let r=new Map,i=new Map,a=new Set,o=n.ownershipRequired===!0,s=!1,c=!1,l,u=()=>t(),d=new B({getActiveCall:u});return{publicMedia:{requestPermission:()=>(f(),d.requestPermission()),getDevices:()=>(f(),d.getDevices()),getCapabilities:()=>(f(),d.getCapabilities()),supportsOutputSelection:()=>(f(),d.supportsOutputSelection()),setInputDevice:e=>(f(),d.setInputDevice(e,u())),setOutputDevice:e=>(f(),d.setOutputDevice(e)),playRemoteAudio:e=>(f(),d.playRemoteAudio(e)),releaseAll:()=>(f(),d.releaseAll())},registerCall(e,t){s||c||!J(t)||(i.set(e,t),(!o||a.has(e))&&p(e,t))},async setCallOwnership(e,t){if(s)return;if(t!==`owned`){a.delete(e),await d.releaseCall(e),r.delete(e);return}a.add(e);let n=i.get(e);n!==void 0&&p(e,n)},contextFor(e,t,n){let i=r.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:n,peerConnection:i.peerConnection}},async releaseCall(e){s||(await d.releaseCall(e),r.delete(e),i.delete(e),a.delete(e))},releaseAll:async()=>{await d.releaseAll(),r.clear(),i.clear(),a.clear()},getResourceCounts:()=>d.getResourceCounts(),dispose:()=>{if(l!==void 0)return l;c=!0;let e=d.dispose().then(()=>{s=!0,c=!1,r.clear(),i.clear(),a.clear()}).finally(()=>{l===e&&!s&&(l=void 0,c=!1)});return l=e,e}};function f(){if(s)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function p(e,t){if(!J(t)||typeof t.getMediaRegistration!=`function`)return;let n=t.getMediaRegistration();if(le(n)&&r.get(e)?.peerConnection!==n.peerConnection){r.set(e,n);try{d.registerCallMedia(e,n)}catch{r.delete(e)}}}}function J(e){return typeof e==`object`&&!!e}function le(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var ue=1e3,de=3e4;function fe(e,t=Math.random){let n=Math.min(de,ue*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var pe=class{recover;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=fe(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},me=class r{media;options;api;suppliedSip;sip;events=new n;mediaBridge;reconnect;diagnostics;callManager;session;state=`idle`;initialized=!1;disposed=!1;intentionalDisconnect=!1;deferredRebuild=!1;sessionRecoveryPending=!1;detectedPlatform;support;acceptingEvents=!0;connectOperation;disconnectOperation;refreshOperation;disposeOperation;refreshTimer;lifecycleGeneration=0;managerUnsubscribers=[];sipUnsubscribe;networkUnsubscribers=[];sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;sharedWorkerSelection;constructor(n){if(this.options=n,n.api===void 0&&n.sessionProvider===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`CCBarClient 需要 sessionProvider`});this.api=n.api===void 0?Y(X(n.sessionProvider)):Y(n.api),this.suppliedSip=n.sip===void 0?void 0:_e(n.sip),this.mediaBridge=ce(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new pe({recover:()=>this.recoverConnection(),onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new t.t({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)}),this.sharedWorkerSelection=n.sharedWorker===void 0?{mode:`single-tab`,reason:`disabled`}:C({...n.sharedWorker,...n.sharedWorkerHost??{}})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=ge(typeof navigator<`u`?navigator.userAgent:``);return{supported:e&&t,platform:n,hasMediaDevices:e,hasWebSocket:t,...e&&t?{}:{reason:`当前运行环境缺少 WebPhone 所需的浏览器能力`}}}async initialize(){if(this.assertNotDisposed(),this.initialized)return;let e=await r.checkSupport();this.support=e,this.options.platform===void 0&&(e.platform===`web`||e.platform===`mobile-web`)&&(this.detectedPlatform=e.platform),await this.awaitSharedWorkerReady(),this.assertNotDisposed(),this.initialized=!0}connect(){if(this.assertNotDisposed(),this.api.invalidateToken?.(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();let e=this.lifecycleGeneration,t=this.performConnect(e).finally(()=>{this.connectOperation===t&&(this.connectOperation=void 0)});return this.connectOperation=t,t}disconnect(){if(this.assertNotDisposed(),this.disconnectOperation!==void 0)return this.disconnectOperation;if(this.state===`idle`&&this.connectOperation===void 0||this.state===`disconnected`&&this.connectOperation===void 0)return Promise.resolve();this.lifecycleGeneration+=1,this.acceptingEvents=!1;let e=this.performDisconnect().finally(()=>{this.disconnectOperation===e&&(this.disconnectOperation=void 0)});return this.disconnectOperation=e,e}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.lifecycleGeneration+=1,this.intentionalDisconnect=!0,this.acceptingEvents=!1,this.reconnect.dispose(),this.clearRefreshTimer(),this.detachNetworkListeners(),this.releaseSharedWorker(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(t){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.dial(t,r)}answer(t,n){this.assertConnected();let r=this.callManager,i=this.session;if(r===void 0||i===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return r.answer(t,i,n)}setActiveCall(t){this.assertConnected();let n=this.callManager;if(n===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.setActiveCall(t)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getSharedWorkerState(){let e=this.sharedWorkerSelection;return e.mode===`shared`?{mode:`shared`,tabId:e.tabId}:{mode:`single-tab`,reason:e.reason}}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){this.assertNotDisposed();let t=this.session?.transport.wssUrl;await this.api.setAgentStatus({status:e,reason:``},t===void 0?void 0:{wssUrl:t}),this.disposed||this.events.emit(`agent.statusChanged`,{status:e})}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}off(e,t){this.events.off(e,t)}async performConnect(e){let n,r,i;try{await this.initialize(),this.assertGeneration(e);let a=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),n=await this.api.createSession({sdkVersion:t.r,platform:a===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??xe(a)]}),this.ownedSessionIds.add(n.sessionId),this.assertGeneration(e),r=await this.getSip(),this.assertGeneration(e),this.session=n;let o=this.callManager??this.createCallManager(r,n,a);this.callManager===void 0&&(i=o),o.updateSession(n),this.callManager=o,this.attachSipListener(r),this.attachNetworkListeners(),await r.connect(n),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(n)}catch(t){if(await this.rollbackConnect(n,r,i),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw t;let a=Z(t,`REGISTRATION_FAILED`,`registration`,!0);throw this.setConnectionState(`failed`),this.events.emit(`connection.failed`,{error:a}),a}}async performDisconnect(){let e,t=this.connectOperation;if(t!==void 0)try{await t}catch(t){$(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){$(t)||(e??=t)}this.reconnect.cancel(),this.clearRefreshTimer(),this.intentionalDisconnect=!0,this.detachNetworkListeners(),this.detachSipListener(),this.detachManagerListeners();let r=this.callManager,i=this.sip;this.callManager=void 0;try{await r?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{i!==void 0&&await i.disconnect()}catch(t){e??=t}this.session=void 0;try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new _({sip:e,platform:n,session:t,maxConcurrentCalls:this.options.maxConcurrentCalls,autoHoldPreviousCall:this.options.autoHoldPreviousCall,onCallCreated:(e,t)=>this.handleCallCreated(e,t),onCallStateChanged:(e,t)=>this.handleCallStateChanged(e,t),onCallTerminal:e=>this.handleCallTerminal(e)});return this.bindManagerEvents(r),r}async rollbackConnect(e,t,n){if(n!==void 0){this.detachManagerListeners(),this.callManager===n&&(this.callManager=void 0);try{await n.dispose({terminateCalls:!0})}catch{}}if(t!==void 0){this.detachSipListener();try{await t.disconnect()}catch{}}if(this.session===e&&(this.session=void 0),e!==void 0)try{await this.deleteSession(e.sessionId)}catch{}}async performDispose(){let e,t=[this.connectOperation,this.disconnectOperation,this.refreshOperation].filter(e=>e!==void 0);for(let n of t)try{await n}catch(t){$(t)||(e??=t)}let n=this.callManager;this.callManager=void 0;try{await n?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{await this.media.releaseAll()}catch(t){ve(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await n,this.terminalReleaseOperations.delete(t)}catch(n){try{await this.mediaBridge.releaseCall(t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}detachSipListener(){let e=this.sipUnsubscribe;this.sipUnsubscribe=void 0;try{e?.()}catch{}}detachManagerListeners(){this.managerUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}bindManagerEvents(e){[`call.created`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`error`].forEach(t=>{let n=e.on(t,e=>{this.acceptingEvents&&!this.disposed&&(this.diagnostics.log(t===`error`||t===`call.failed`?`error`:`info`,String(t),e),this.events.emit(t,e))});this.managerUnsubscribers.push(n)})}handleCallCreated(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallStateChanged(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallTerminal(e){let t=this.startTerminalRelease(e);return this.deferredRebuild&&!this.hasNonTerminalCalls()&&this.startDeferredRecovery(),t}startTerminalRelease(e){let t=this.terminalReleaseOperations.get(e);if(t!==void 0)return t;let n=this.mediaBridge.releaseCall(e).then(()=>{this.terminalReleaseOperations.get(e)===n&&this.terminalReleaseOperations.delete(e)}).catch(t=>{throw this.acceptingEvents&&!this.disposed&&this.events.emit(`error`,{error:Z(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{if(await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed){if(this.sessionRecoveryPending){this.recoverInvalidSession();return}this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start()}}catch{!this.disposed&&!this.sessionRecoveryPending&&this.reconnect.start()}}async refreshAndRebuild(){if(this.refreshOperation!==void 0)return this.refreshOperation;let e=this.performRefreshAndRebuild().finally(()=>{this.refreshOperation===e&&(this.refreshOperation=void 0),this.sessionRecoveryPending&&!this.hasNonTerminalCalls()&&!this.disposed&&this.recoverInvalidSession()});return this.refreshOperation=e,e}async performRefreshAndRebuild(){if(this.disposed||this.session===void 0)return;let e=this.lifecycleGeneration,t=this.session;try{let n=await this.api.refreshSession(t.sessionId);if(!this.isCurrentGeneration(e)||this.session!==t)return;if(this.session=n,this.callManager?.updateSession(n),this.events.emit(`token.refreshed`,{expiresAt:n.expiresAt}),this.hasNonTerminalCalls()){this.deferredRebuild=!0,this.scheduleRefresh(n);return}let r=await this.getSip();if(!this.isCurrentGeneration(e))return;await r.connect(n),this.isCurrentGeneration(e)&&(this.deferredRebuild=!1,this.setConnectionState(`connected`),this.scheduleRefresh(n))}catch(n){if(!this.isCurrentGeneration(e))return;throw this.handleRefreshFailure(t,n),n}}handleRefreshFailure(e,t){if(this.disposed)return;let n=Z(t,`NETWORK_OFFLINE`,`network`,!0);if(this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),Q(t)){this.clearRefreshTimer(),this.reconnect.cancel(),this.deletedSessions.add(e.sessionId),this.sessionRecoveryPending=!0,this.deferredRebuild=!0,(n.code===`AUTH_TOKEN_UNAVAILABLE`||n.code===`AUTH_TOKEN_EXPIRED`)&&this.api.invalidateToken?.();return}this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}async recoverInvalidSession(){if(!(!this.sessionRecoveryPending||this.disposed||this.hasNonTerminalCalls())){this.sessionRecoveryPending=!1,this.deferredRebuild=!1;try{await this.performDisconnect()}catch(e){this.disposed||this.events.emit(`error`,{error:Z(e,`SDK_INTERNAL_ERROR`,`internal`,!0)});return}if(!this.disposed)try{await this.performConnect(this.lifecycleGeneration)}catch{this.reconnect.cancel()}}}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){this.disposed||this.intentionalDisconnect||this.hasNonTerminalCalls()||(await this.awaitMediaReleaseBarriers(),await this.refreshAndRebuild())}async getSip(){if(this.sip!==void 0)return this.sip;if(this.suppliedSip!==void 0)return this.sip=this.suppliedSip,this.sip;let[e,t]=await Promise.all([Promise.resolve().then(()=>require("./createJsSipFactory-Dr8HbLl-.cjs")),Promise.resolve().then(()=>require("./JsSipAdapter-BN9BAFHr.cjs"))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl,this.options.sipKeepaliveSeconds,this.options.agentTerminal,this.options.sipSessionTimers??!1),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:Z(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>this.reconnect.notifyOnline(),n=()=>this.reconnect.notifyOffline();e.addEventListener(`online`,t),e.addEventListener(`offline`,n),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n)]}detachNetworkListeners(){this.networkUnsubscribers.splice(0).forEach(e=>e())}getActiveMediaContext(){let e=this.callManager?.getActiveCall();return e===void 0?void 0:this.mediaBridge.contextFor(e.id,e.state,new Set(this.session?.capabilities??[]))}hasNonTerminalCalls(){return this.callManager?.hasNonTerminalCalls()??!1}clearRefreshTimer(){this.refreshTimer!==void 0&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}createDiagnosticsSnapshot(){let e=this.session;return{connectionState:this.state,calls:this.getCalls().map(e=>({callId:e.id,state:e.state,destination:e.destination})),permission:this.support?.hasMediaDevices===!1?`unsupported`:`unknown`,ice:he(e),wss:{configured:e!==void 0,secure:e?.transport.wssUrl.toLowerCase().startsWith(`wss://`)??!1,state:this.state},resources:this.getDiagnosticsResourceCounts()}}getDiagnosticsResourceCounts(){let e=this.mediaBridge.getResourceCounts(),t=this.callManager?.getResourceCounts()??{timers:0,listeners:0},n=this.sip?.getResourceCounts?.(),r=(this.callManager===void 0?0:1)+(this.sipUnsubscribe===void 0?0:1),i=this.session!==void 0&&this.state!==`idle`&&this.state!==`disconnected`;return{timers:(this.refreshTimer===void 0?0:1)+this.reconnect.getTimerCount()+t.timers,listeners:this.events.listenerCount()+t.listeners+e.listeners+this.networkUnsubscribers.length+(n?.listeners??r),tracks:e.tracks,peerConnections:e.peerConnections,audioElements:e.audioElements,webSockets:n?.webSockets??+!!i,deletedSessions:this.deletedSessions.size}}async readMicrophonePermission(){if(typeof navigator>`u`||navigator.mediaDevices===void 0)return`unsupported`;if(navigator.permissions===void 0)return`unknown`;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}deleteSession(e){if(this.deletedSessions.has(e))return Promise.resolve();let t=this.sessionDeleteOperations.get(e);if(t!==void 0)return t;let n=this.api.deleteSession(e).then(()=>{this.deletedSessions.add(e)}).catch(t=>{if(Q(t)){this.deletedSessions.add(e);return}throw t}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}pruneDeletedSessionTombstones(){for(let e of[...this.deletedSessions])!this.ownedSessionIds.has(e)&&!this.sessionDeleteOperations.has(e)&&this.deletedSessions.delete(e)}async deleteOwnedSessions(){let e;for(let t of[...this.ownedSessionIds])try{await this.deleteSession(t),this.ownedSessionIds.delete(t)}catch(t){e??=t}if(e!==void 0)throw e}resolvePlatform(){let t=this.options.platform??this.detectedPlatform;if(t===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return t}setConnectionState(e){this.state===e||this.disposed||(this.state=e,this.diagnostics.log(`info`,`connection.stateChanged`,{state:e}),this.events.emit(`connection.stateChanged`,{state:e===`disconnected`||e===`idle`?`offline`:e}))}assertConnected(){if(this.assertNotDisposed(),this.state!==`connected`||this.callManager===void 0||this.session===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(t){if(this.disposed)throw this.disposedError();if(t!==this.lifecycleGeneration)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}async awaitSharedWorkerReady(){let e=this.sharedWorkerSelection;if(e.mode===`shared`)try{await e.ready}catch(e){if(this.disposed)return;if(this.options.sharedWorker?.fallback===`error`)throw e;this.sharedWorkerSelection={mode:`single-tab`,reason:e instanceof Error?e.message:`SharedWorker attach failed`}}}releaseSharedWorker(){let e=this.sharedWorkerSelection;if(this.sharedWorkerSelection={mode:`single-tab`,reason:`disposed`},e.mode===`shared`){try{e.client.request({version:1,type:`detach`,requestId:`detach-${e.tabId}`,tabId:e.tabId}).catch(()=>void 0)}catch{}e.client.close()}}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function he(e){if(e===void 0)return{configured:!1,serverCount:0,stunServerCount:0,turnServerCount:0};let t=0,n=0;return e.iceServers.forEach(e=>{let r=e.urls.map(e=>e.toLowerCase());r.some(e=>e.startsWith(`stun:`))&&(t+=1),r.some(e=>e.startsWith(`turn:`)||e.startsWith(`turns:`))&&(n+=1)}),{configured:e.iceServers.length>0,serverCount:e.iceServers.length,stunServerCount:t,turnServerCount:n}}function ge(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function Y(t){if(typeof t!=`object`||!t)throw new e.i(`CONFIG_INVALID`,`configuration`,!1);return t}function X(n){let r={createSession:e=>n.createSession(e),refreshSession:e=>n.refreshSession===void 0?n.createSession({sdkVersion:t.r,platform:`web`}):n.refreshSession(e),deleteSession:async e=>{n.deleteSession!==void 0&&await n.deleteSession(e)},setAgentStatus:(t,r)=>n.setAgentStatus===void 0?Promise.reject(new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{cause:`当前会话来源不支持坐席状态设置(sessionProvider.setAgentStatus 未提供)`})):n.setAgentStatus(t,r)},i=n.invalidateToken;return i!==void 0&&(r.invalidateToken=()=>i()),r}function _e(t){if(typeof t!=`object`||!t)throw new e.i(`CONFIG_INVALID`,`configuration`,!1);return t}function Z(t,n,r,i,a){return t instanceof e.i?new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:a??t.callId,cause:t.cause??t,serverCode:t.serverCode,status:t.status}):new e.i(n,r,i,{callId:a,cause:t})}function Q(t){return t instanceof e.i?t.status!==void 0&&t.status>=400&&t.status<500||t.serverCode===`SESSION_NOT_FOUND`||t.serverCode===`SESSION_EXPIRED`||t.serverCode===`TOKEN_INVALID`||t.serverCode===`TOKEN_EXPIRED`||t.code===`AUTH_TOKEN_UNAVAILABLE`||t.code===`AUTH_TOKEN_EXPIRED`:!1}function ve(t){return t instanceof e.i&&t.code===`SDK_ALREADY_DISPOSED`}function $(t){return t instanceof e.i&&(t.code===`SDK_ALREADY_DISPOSED`||t.code===`CALL_NOT_CONNECTED`)}var ye=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],be=[`outbound`,`mute`,`dtmf`];function xe(e){return e===`mobile-web`?be:ye}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return r}});
@@ -1,5 +1,5 @@
1
1
  import { i as e, t } from "./SharedWorkerProtocol-DKVQ5-po.js";
2
- import { r as n, t as r } from "./Diagnostics-CfbmMp-b.js";
2
+ import { r as n, t as r } from "./Diagnostics-Cmo6qDKu.js";
3
3
  //#region src/events/TypedEventBus.ts
4
4
  var i = class {
5
5
  handlers = /* @__PURE__ */ new Map();
@@ -1 +1 @@
1
- const e=require("./redact-Bq26pObO.cjs");var t=`3.1.9`,n=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},r=`@16x/webphone-sdk`,i=200,a=class{dependencies;logs=new n(i);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(t,n,r){this.logs.push({timestamp:this.now().toISOString(),level:t,message:e.t(n),...r===void 0?{}:{context:e.n(r)}})}async getReport(n={}){let i=n.includeRecentLogs!==!1,a=n.includeDeviceNames===!0,u=n.maskPhoneNumbers!==!1,d=this.dependencies.getSnapshot(),f=this.dependencies.getPermission===void 0?d.permission:await o(this.dependencies.getPermission,d.permission),p=a?await s(this.dependencies.getDeviceNames):void 0,m=l(c(this.dependencies.getUserAgent)),h={generatedAt:this.now().toISOString(),sdk:{name:r,version:t},browser:m.browser,os:m.os,...d,permission:f,recentLogs:i?this.logs.toArray():[],...p===void 0?{}:{deviceNames:p}};return e.n(h,{maskPhoneNumbers:u})}};async function o(e,t){try{return await e()}catch{return t}}async function s(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function c(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function l(e){return{browser:u(e),os:d(e)}}function u(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function d(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
1
+ const e=require("./redact-Bq26pObO.cjs");var t=`3.8.1`,n=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},r=`@16x/webphone-sdk`,i=200,a=class{dependencies;logs=new n(i);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(t,n,r){this.logs.push({timestamp:this.now().toISOString(),level:t,message:e.t(n),...r===void 0?{}:{context:e.n(r)}})}async getReport(n={}){let i=n.includeRecentLogs!==!1,a=n.includeDeviceNames===!0,u=n.maskPhoneNumbers!==!1,d=this.dependencies.getSnapshot(),f=this.dependencies.getPermission===void 0?d.permission:await o(this.dependencies.getPermission,d.permission),p=a?await s(this.dependencies.getDeviceNames):void 0,m=l(c(this.dependencies.getUserAgent)),h={generatedAt:this.now().toISOString(),sdk:{name:r,version:t},browser:m.browser,os:m.os,...d,permission:f,recentLogs:i?this.logs.toArray():[],...p===void 0?{}:{deviceNames:p}};return e.n(h,{maskPhoneNumbers:u})}};async function o(e,t){try{return await e()}catch{return t}}async function s(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function c(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function l(e){return{browser:u(e),os:d(e)}}function u(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function d(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
@@ -1,6 +1,6 @@
1
1
  import { n as e, t } from "./redact-DB3CMbsK.js";
2
2
  //#region src/version.ts
3
- var n = "3.1.9", r = class {
3
+ var n = "3.8.1", r = class {
4
4
  capacity;
5
5
  entries = [];
6
6
  constructor(e) {
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../Diagnostics-DkKlZQnY.cjs"),t=require("../redact-Bq26pObO.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs"),exports.Diagnostics=e.t,exports.RingBuffer=e.n,exports.diagnosticsVersion=e.r,exports.redactText=t.t,exports.redactValue=t.n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../Diagnostics--D2xwro7.cjs"),t=require("../redact-Bq26pObO.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs"),exports.Diagnostics=e.t,exports.RingBuffer=e.n,exports.diagnosticsVersion=e.r,exports.redactText=t.t,exports.redactValue=t.n;
@@ -1,3 +1,3 @@
1
- import { n as e, r as t, t as n } from "../Diagnostics-CfbmMp-b.js";
1
+ import { n as e, r as t, t as n } from "../Diagnostics-Cmo6qDKu.js";
2
2
  import { n as r, t as i } from "../redact-DB3CMbsK.js";
3
3
  export { n as Diagnostics, e as RingBuffer, t as diagnosticsVersion, i as redactText, r as redactValue };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./SharedWorkerProtocol-39dch6xL.cjs"),t=require("./CCBarClient-B6WqgloY.cjs"),n=require("./Diagnostics-DkKlZQnY.cjs"),r=require("./redact-Bq26pObO.cjs");require("./diagnostics/index.cjs"),require("./createJsSipFactory-Dr8HbLl-.cjs");function i(e){if(e.code!==`OK`)throw TypeError(`Unexpected session response code: ${e.code}`);if(e.data===void 0||e.data===null)throw TypeError(`Unexpected session response: missing data`);return e.data}function a(e={}){return{version:`0.1.0`,options:e}}var o=`0.1.0`;exports.CCBarCall=t.a,exports.CCBarClient=t.t,exports.CCBarError=e.i,exports.CallManager=t.i,exports.CallStateError=t.o,exports.Diagnostics=n.t,exports.RingBuffer=n.n,exports.TypedEventBus=t.d,exports.assertCallTransition=t.s,exports.canTransition=t.c,exports.createSdk=a,exports.createSharedWorkerSelection=t.n,exports.diagnosticsVersion=n.r,exports.parseSessionResponse=i,exports.redactText=r.t,exports.redactValue=r.n,exports.resolveWorkerUrl=t.r,exports.transition=t.l,exports.transitions=t.u,exports.version=o;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./SharedWorkerProtocol-39dch6xL.cjs"),t=require("./CCBarClient-BJryiSYT.cjs"),n=require("./Diagnostics--D2xwro7.cjs"),r=require("./redact-Bq26pObO.cjs");require("./diagnostics/index.cjs"),require("./createJsSipFactory-Dr8HbLl-.cjs");function i(e){if(e.code!==`OK`)throw TypeError(`Unexpected session response code: ${e.code}`);if(e.data===void 0||e.data===null)throw TypeError(`Unexpected session response: missing data`);return e.data}function a(e={}){return{version:`0.1.0`,options:e}}var o=`0.1.0`;exports.CCBarCall=t.a,exports.CCBarClient=t.t,exports.CCBarError=e.i,exports.CallManager=t.i,exports.CallStateError=t.o,exports.Diagnostics=n.t,exports.RingBuffer=n.n,exports.TypedEventBus=t.d,exports.assertCallTransition=t.s,exports.canTransition=t.c,exports.createSdk=a,exports.createSharedWorkerSelection=t.n,exports.diagnosticsVersion=n.r,exports.parseSessionResponse=i,exports.redactText=r.t,exports.redactValue=r.n,exports.resolveWorkerUrl=t.r,exports.transition=t.l,exports.transitions=t.u,exports.version=o;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as e } from "./SharedWorkerProtocol-DKVQ5-po.js";
2
- import { a as t, c as n, d as r, i, l as a, n as o, o as s, r as c, s as l, t as u, u as d } from "./CCBarClient-CfHT0tl2.js";
3
- import { n as f, r as p, t as m } from "./Diagnostics-CfbmMp-b.js";
2
+ import { a as t, c as n, d as r, i, l as a, n as o, o as s, r as c, s as l, t as u, u as d } from "./CCBarClient-CbkMKzEw.js";
3
+ import { n as f, r as p, t as m } from "./Diagnostics-Cmo6qDKu.js";
4
4
  import { n as h, t as g } from "./redact-DB3CMbsK.js";
5
5
  import "./diagnostics/index.js";
6
6
  //#region src/api/contracts.ts
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CCBarSDK={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>o.call(e,`module.exports`)?e[`module.exports`]:u(n({},`__esModule`,{value:!0}),e),p,m=s((()=>{p=class extends Error{code;category;retryable;requestId;callId;cause;serverCode;status;constructor(e,t,n,r={}){super(e),this.name=`CCBarError`,this.code=e,this.category=t,this.retryable=n,this.requestId=r.requestId,this.callId=r.callId,this.cause=r.cause,this.serverCode=r.serverCode,this.status=r.status}}}));m();var h=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},g={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},_=(e,t)=>g[e].has(t);function v(e,t){if(!_(e,t))throw new y(e,t);return t}var y=class extends p{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},b=v;function x(e){if(e.code!==`OK`)throw TypeError(`Unexpected session response code: ${e.code}`);if(e.data===void 0||e.data===null)throw TypeError(`Unexpected session response: missing data`);return e.data}m();var S=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],C=3e4,w=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(e){this.options=e,this.id=e.id,this.destination=e.destination,this.platform=e.platform,this.capabilities=e.capabilities??new Set;try{S.forEach(t=>{this.sessionUnsubscribers.push(e.session.on(t,e=>this.handleSessionEvent(t,e)))})}catch(t){this.cleanupSessionListeners();try{e.session.terminate()}catch{}throw new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,`held`,()=>this.options.session.hold())}async resume(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),await this.startPendingOperation(`resume`,`active`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!E(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),T(this.currentState))throw this.operationError();try{this.options.session.terminate(),T(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!T(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||T(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.transitionIfAllowed(`held`,t,e);break;case`unhold`:this.transitionIfAllowed(`active`,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(_(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!_(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,T(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{T(e)&&this.dispose()}}startPendingOperation(e,t,n){if(this.pendingOperation!==void 0)throw this.operationError();return new Promise((r,i)=>{let a={kind:e,nextState:t,resolve:r,reject:i};this.pendingOperation=a,a.timer=setTimeout(()=>this.timeoutPendingOperation(a),C);let o;try{o=n()}catch(e){this.rejectPendingOperation(e);return}o.then(()=>this.resolvePendingOperation(a),e=>this.rejectPendingOperation(e,a))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||T(this.currentState)){e.reject(this.operationError());return}try{this.transitionTo(e.nextState),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(e){let t=e instanceof p&&e.callId===this.id?e:this.operationError(e);try{this.options.onError?.(t)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(e){return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:e})}};function T(e){return e===`ended`||e===`failed`}function E(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var D=0;function O(){return D+=1,`call_${Date.now().toString(36)}_${D.toString(36)}`}m();var k=`X-User-Data`,A=/[^\x20-\x7E]/,j=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function M(e){if(typeof e!=`string`)return[];let t=e.trim();if(t===``)return[];if(A.test(t))throw new p(`CALL_INVALID_USERDATA`,`call`,!1,{cause:j});return[`${k}: ${t}`]}m();var N=class{events=new P;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(e){this.options=e,this.incomingSessionSnapshot=e.session;try{this.incomingUnsubscribe=e.sip.onIncoming(e=>this.handleIncoming(e))}catch(e){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(e,t){this.assertNotDisposed();let n=this.operationGeneration,r=e.destination.trim();if(r===``)throw new p(`CALL_INVALID_DESTINATION`,`call`,!1);let i=M(e.userdata);this.requireCapability(t,`outbound`);let a=this.callLimit(t);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=a)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=a||this.pendingDestinations.has(r)||[...this.calls.values()].some(e=>e.destination===r))throw new p(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(r);let o=O(),s;try{s=await this.holdActiveCallForNewCall(),this.assertGeneration(n,o);let a;try{a=this.options.sip.dial(r,this.dialOptions(o,t,e.type,i))}catch(e){throw this.dialError(e,o)}this.assertGeneration(n,o);let c;try{c=new w({id:o,destination:r,platform:this.options.platform,capabilities:this.effectiveCapabilities(t),session:a,onStateChanged:(e,t)=>this.handleStateChanged(c,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(c)})}catch(e){throw this.dialError(e,o)}if(!this.isCurrentGeneration(n))throw c.dispose(),this.callOperationError(c.id);this.calls.set(c.id,c),this.callSessions.set(c.id,a),this.options.onCallCreated?.(c.id,a);try{c.beginOutbound()}catch(e){throw c.dispose(),this.calls.delete(c.id),this.callSessions.delete(c.id),this.dialError(e,c.id)}if(!this.isCurrentGeneration(n))throw c.dispose(),this.calls.delete(c.id),this.callSessions.delete(c.id),this.callOperationError(c.id);return this.events.emit(`call.created`,{callId:c.id,state:c.state}),c}catch(e){if(this.isCurrentGeneration(n)&&s!==void 0&&this.isManagedCall(s)&&s.state===`held`)try{await s.resume()}catch(t){throw this.compensationError(s.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(r)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:ee(n)}):this.events.emit(`call.failed`,{callId:e.id,error:te(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(e){if(this.disposed)return;let t=O(),n=this.incomingSessionSnapshot;if(n===void 0||!n.policy.incomingEnabled||!this.effectiveCapabilities(n).has(`inbound`)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:this.capabilityError(t)});return}let r=e.from??e.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(n)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:new p(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:t})});return}let i;try{i=new w({id:t,destination:r,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(i,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(i)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(t,e)});return}this.calls.set(i.id,i),this.callSessions.set(i.id,e),this.options.onCallCreated?.(i.id,e);try{i.beginIncoming(),this.events.emit(`call.incoming`,{callId:i.id,from:r})}catch(e){i.dispose(),this.events.emit(`error`,{error:this.callOperationError(i.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(e,t){return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e,cause:t})}capabilityError(e){return new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(e,t){return e instanceof p?new p(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e}):new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}},P=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function ee(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function te(e,t){if(e instanceof p)return new p(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e});if(typeof e==`object`&&e&&`error`in e){let n=e.error;if(n instanceof p)return new p(n.code,n.category,n.retryable,{requestId:n.requestId,callId:t,cause:n.cause??n});if(n instanceof Error)return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}var F=`3.1.9`,I=`[REDACTED]`,ne=/\bBearer\s+[^\s,;"'}]+/gi,re=/(\bAuthorization\s*[:=]\s*)Digest\s+[^\r\n]*/gi,ie=/(\bAuthorization\s*[:=]\s*)(?:(Bearer|Basic|Digest|Token)\s+)?[^\s,;"'}]+/gi,L=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,R=/\b((?:sip|sips|turn|turns|ws|wss):(?:\/\/)?)[^/?#@\s:]+:[^/?#@\s]+@/gi,ae=/(\b(?:sip(?:Register)?Ticket|registerTicket|wssTicket|turnCredential|credential|accessToken|refreshToken|appSecret|password|jwt|ticket)\b\s*[:=]\s*)(["']?)([^\s,;&}"']+)(["']?)/gi,oe=/(?<!\d)(1[3-9]\d)\d{4}(\d{4})(?!\d)/g,se=/(?:authorization|token|ticket|credential|password|secret)$/i;function ce(e,t={}){let n=e.replace(ne,`Bearer ${I}`).replace(re,(e,t)=>`${t}Digest ${I}`).replace(ie,(e,t,n)=>`${t}${n===void 0?``:`${n} `}${I}`).replace(L,I).replace(R,(e,t)=>`${t}${I}@`).replace(ae,(e,t)=>`${t}${I}`);return t.maskPhoneNumbers!==!1&&(n=n.replace(oe,`$1****$2`)),n}function le(e,t={}){return ue(e,t,new WeakSet)}function ue(e,t,n){if(typeof e==`string`)return ce(e,t);if(typeof e!=`object`||!e)return e;if(n.has(e))return`[Circular]`;if(n.add(e),Array.isArray(e))return e.map(e=>ue(e,t,n));let r={};return Object.entries(e).forEach(([e,i])=>{r[e]=se.test(e)?I:ue(i,t,n)}),r}m();function de(e){if(!z(e))throw B(`Invalid worker message`);if(e.version!==1)throw B(`Unsupported worker protocol version`);if(e.type===`attach`||e.type===`detach`)return fe(e),e;if(e.type===`command`){if(fe(e),typeof e.command!=`string`||e.payload!==void 0&&!z(e.payload))throw B(`Invalid worker command`);return e}if(e.type===`response`){if(typeof e.requestId!=`string`||typeof e.ok!=`boolean`)throw B(`Invalid worker response`);return e}if(e.type===`event`){if(typeof e.event!=`string`||!(`payload`in e))throw B(`Invalid worker event`);return e}throw B(`Unknown worker message type`)}function fe(e){if(typeof e.requestId!=`string`||typeof e.tabId!=`string`)throw B(`Worker request requires requestId and tabId`)}function z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function B(e){return new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}m();var pe=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(e){return this.closed?Promise.reject(new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(e.requestId)?Promise.reject(new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:e.requestId})):this.lifecycleState===`reconnecting`&&e.type===`command`&&(e.command===`dial`||e.command===`answer`)?Promise.reject(new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:e.payload?.callId})):new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(e.requestId),n(new p(`NETWORK_TIMEOUT`,`network`,!0,{requestId:e.requestId}))},this.timeoutMs);this.pending.set(e.requestId,{resolve:e=>t(e),reject:n,timer:r}),this.port.postMessage(e)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(e=>{clearTimeout(e.timer),e.reject(new p(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(e){try{let t=de(e);if(t.type===`event`){t.event===`connection.stateChanged`&&me(t.payload)&&(this.lifecycleState=t.payload.state),this.eventHandlers.forEach(e=>e(t));return}if(t.type!==`response`)return;let n=this.pending.get(t.requestId);if(n===void 0)return;this.pending.delete(t.requestId),clearTimeout(n.timer),t.ok?n.resolve(t.result):n.reject(he(t))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function me(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function he(e){let t=e.error;return new p(t?.code??`SDK_INTERNAL_ERROR`,t?.category??`internal`,t?.retryable??!1,{requestId:e.requestId,...t?.message===void 0?{}:{cause:t.message},...t?.serverCode===void 0?{}:{serverCode:t.serverCode},...t?.status===void 0?{}:{status:t.status}})}m();function ge(e={}){if((e.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let t=e.locationHref??ve(),n=_e(e.url,t),r=t=>{if(e.fallback===`error`)throw new p(`CONFIG_INVALID`,`configuration`,!1,{cause:t});return{mode:`single-tab`,reason:t}};if(n===void 0)return r(`SharedWorker URL is unavailable`);if(!be(n,t))return r(`SharedWorker URL must be same-origin`);let i=e.workerCtor??ye();if(i===void 0)return r(`SharedWorker is not supported`);let a;try{a=new i(n,e.name===void 0?void 0:{name:e.name})}catch(e){return r(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let o=e.tabId??xe(),s=new pe(a.port),c={version:1,type:`attach`,requestId:Se(),tabId:o},l=s.request(c).then(()=>void 0).catch(e=>{throw s.close(),e});return{mode:`shared`,worker:a,client:s,tabId:o,workerUrl:n,ready:l}}function _e(e,t=ve()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function ve(){return typeof location>`u`?void 0:location.href}function ye(){if(typeof SharedWorker==`function`)return SharedWorker}function be(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function xe(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function Se(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}m();var Ce=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??we(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw De(e)}Te(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw V(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(e,t){if(!this.supportsOutputSelection())throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=e;let n=++this.outputGeneration;t!==void 0&&await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(e,t)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(e,t){let n=t;if(typeof n.setSinkId!=`function`)throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await n.setSinkId(e)}catch(e){throw H(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw Ee(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function we(){return globalThis.navigator?.mediaDevices}function Te(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function Ee(e){let t=Oe(e);return t===`NotFoundError`||t===`OverconstrainedError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function De(e){let t=Oe(e);return t===`NotFoundError`||t===`OverconstrainedError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function V(e){let t=Oe(e);return t===`NotFoundError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function H(e){let t=Oe(e);return t===`NotFoundError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function Oe(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}m();var ke=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=Ae){this.createAudioElement=e}async bind(e,t){let n=this.bindings.get(e);if(n?.stream===t)return;let r=je(e,t),i;try{i=this.createAudioElement()}catch(t){throw Me(r,this.trackOwners),new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e,cause:t})}let a=this.audioOwners.get(i);if(a!==void 0&&a!==e)throw Me(r,this.trackOwners),new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});try{i.autoplay=!0,i.playsInline=!0}catch(t){throw Me(r,this.trackOwners),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}try{i.srcObject=t}catch(t){throw Me(r,this.trackOwners),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}this.acquireTracks(r),n!==void 0&&this.releaseBinding(n,n.audio!==i);let o=this.nextGeneration(e);this.audioOwners.set(i,e);let s={callId:e,audio:i,stream:t,tracks:r,generation:o};this.bindings.set(e,s),this.beginPlay(e);try{await i.play()}catch(t){if(!this.isCurrent(e,o))return;throw new p(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,o)}async play(e){let t=this.bindings.get(e);if(t===void 0)throw new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});let n=t.generation;this.beginPlay(e);try{await t.audio.play()}catch(t){if(!this.isCurrent(e,n))return;throw new p(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,n)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),Pe(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function Ae(){if(typeof document>`u`)throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function je(e,t){try{return[...new Set(t.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(n){try{return[...new Set(t.getTracks())].filter(e=>e.kind===`audio`)}catch(r){throw Ne(t),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:n??r})}}}function Me(e,t){e.forEach(e=>{(t.get(e)??0)===0&&Pe(e)})}function Ne(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(Pe)}catch{}}function Pe(e){try{e.stop()}catch{}}m();var Fe=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new Ce(t),this.remoteAudio=new ke(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??He}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=Ie(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(e){let t=this.releaseOperations.get(e);if(t!==void 0)return t;if(!this.resources.has(e))return Promise.resolve();let n=e.callId;this.remoteAudio.release(n),this.releaseErrors.delete(e),this.calls.get(n)===e&&this.calls.delete(n),e.generation+=1,e.released=!0,this.unsubscribeTrackSource(e);let r=new Set([...e.localTracks,...e.pendingTracks]),i=[...e.senders.values()].filter(e=>e.audio).map(t=>({senderResource:t,promise:this.enqueueSender(e,t,()=>Re(t.sender),!0)})),a=Promise.all(i.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async t=>{let i=new Set,a=[];if(t.forEach(e=>{if(e.cause!==void 0){a.push(e.cause);let t=U(e.senderResource.sender);t?.kind===`audio`&&i.add(t);return}let t=U(e.senderResource.sender);t?.kind===`audio`&&r.add(t)}),r.forEach(e=>{i.has(e)||Ve(e)}),a.length>0)throw e.localTracks.clear(),e.pendingTracks.clear(),i.forEach(t=>e.localTracks.add(t)),new p(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:a[0]});if(!e.peerClosed&&e.peerConnection.close!==void 0)try{await e.peerConnection.close(),e.peerClosed=!0}catch(t){let r=[...e.senders.values()].map(e=>U(e.sender)).find(e=>e?.kind===`audio`);throw e.localTracks.clear(),e.pendingTracks.clear(),r!=null&&e.localTracks.add(r),new p(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:t})}e.localTracks.clear(),e.pendingTracks.clear(),e.senders.clear(),this.resources.delete(e),this.releaseUnusedSenderQueues()}).catch(t=>{throw this.releaseErrors.set(e,t),this.calls.get(n)===void 0&&this.calls.set(n,e),t}).finally(()=>{this.releaseOperations.get(e)===a&&this.releaseOperations.delete(e)});return this.releaseOperations.set(e,a),a}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(e,t,n){if(this.assertActiveCall(t),this.assertDeviceSelectionCapability(t),!this.isCurrentResource(n)||t.peerConnection!==n.peerConnection)throw this.callOperationError(t.callId);let r=this.findAudioSender(n),i=U(r.sender),a=n.generation,o=await this.deviceManager.openInputStream(e),s;try{s=o.getTracks()}catch(e){throw ze(o),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let c;try{c=o.getAudioTracks()}catch(e){throw Be(s),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let l=c[0];if(l===void 0)throw Be(s),new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:t.callId});if(!this.canCommitInputSwitch(t,n,r,i,a))throw Be(s),this.callOperationError(t.callId);s.forEach(e=>n.pendingTracks.add(e)),n.pendingTracks.add(l);try{await this.enqueueSender(n,r,()=>r.sender.replaceTrack(l))}catch(e){throw n.released?this.callOperationError(t.callId):(n.released||(s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),await this.rollbackSender(n,r,i,l),Be(s)),new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:t.callId,cause:e}))}if(!this.canCommitInputSwitch(t,n,r,l,a)){if(!n.released)try{await this.enqueueSender(n,r,()=>U(r.sender)===l?Re(r.sender):Promise.resolve()),s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),Be(s)}catch(e){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:t.callId,cause:e})}throw this.callOperationError(t.callId)}s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),n.localTracks.add(l),i!==null&&i!==l&&(n.localTracks.delete(i),Ve(i)),s.forEach(e=>{e!==l&&Ve(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(e,t){let n;try{n=e.peerConnection.getSenders()}catch(t){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}n.forEach(n=>{let r=U(n),i;try{i=t?.(n)??n.senderKind??n.kind}catch(t){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}e.senders.set(n,{sender:n,audio:i===`audio`||i===void 0&&r?.kind===`audio`,queue:this.senderQueues.get(n)??this.createSenderQueue(n)}),r?.kind===`audio`&&e.localTracks.add(r)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(U(e.sender)?.kind===`audio`||U(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return U(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||U(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(e){if(e===void 0||e.state!==`active`)throw new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(e){return new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}callOperationError(e){return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e})}assertNotDisposed(){if(this.disposed||this.disposing)throw new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function Ie(e){return`peerConnection`in e}function U(e){try{return e.track}catch{return null}}function Le(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function Re(e){try{return e.replaceTrack(null).catch(e=>{if(!Le(e))throw e})}catch(e){return Le(e)?Promise.resolve():Promise.reject(e)}}function ze(e){try{Be(e.getTracks())}catch{}}function Be(e){e.forEach(Ve)}function Ve(e){try{e.stop()}catch{}}function He(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}m();function Ue(e,t={}){let n=new Map,r=new Map,i=new Set,a=t.ownershipRequired===!0,o=!1,s=!1,c,l=()=>e(),u=new Fe({getActiveCall:l});return{publicMedia:{requestPermission:()=>(d(),u.requestPermission()),getDevices:()=>(d(),u.getDevices()),getCapabilities:()=>(d(),u.getCapabilities()),supportsOutputSelection:()=>(d(),u.supportsOutputSelection()),setInputDevice:e=>(d(),u.setInputDevice(e,l())),setOutputDevice:e=>(d(),u.setOutputDevice(e)),playRemoteAudio:e=>(d(),u.playRemoteAudio(e)),releaseAll:()=>(d(),u.releaseAll())},registerCall(e,t){o||s||!We(t)||(r.set(e,t),(!a||i.has(e))&&f(e,t))},async setCallOwnership(e,t){if(o)return;if(t!==`owned`){i.delete(e),await u.releaseCall(e),n.delete(e);return}i.add(e);let a=r.get(e);a!==void 0&&f(e,a)},contextFor(e,t,r){let i=n.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:r,peerConnection:i.peerConnection}},async releaseCall(e){o||(await u.releaseCall(e),n.delete(e),r.delete(e),i.delete(e))},releaseAll:async()=>{await u.releaseAll(),n.clear(),r.clear(),i.clear()},getResourceCounts:()=>u.getResourceCounts(),dispose:()=>{if(c!==void 0)return c;s=!0;let e=u.dispose().then(()=>{o=!0,s=!1,n.clear(),r.clear(),i.clear()}).finally(()=>{c===e&&!o&&(c=void 0,s=!1)});return c=e,e}};function d(){if(o)throw new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function f(e,t){if(!We(t)||typeof t.getMediaRegistration!=`function`)return;let r=t.getMediaRegistration();if(Ge(r)&&n.get(e)?.peerConnection!==r.peerConnection){n.set(e,r);try{u.registerCallMedia(e,r)}catch{n.delete(e)}}}}function We(e){return typeof e==`object`&&!!e}function Ge(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var Ke=1e3,qe=3e4;function Je(e,t=Math.random){let n=Math.min(qe,Ke*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var Ye=class{recover;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=Je(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},Xe=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},Ze=`@16x/webphone-sdk`,Qe=200,$e=class{dependencies;logs=new Xe(Qe);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(e,t,n){this.logs.push({timestamp:this.now().toISOString(),level:e,message:ce(t),...n===void 0?{}:{context:le(n)}})}async getReport(e={}){let t=e.includeRecentLogs!==!1,n=e.includeDeviceNames===!0,r=e.maskPhoneNumbers!==!1,i=this.dependencies.getSnapshot(),a=this.dependencies.getPermission===void 0?i.permission:await et(this.dependencies.getPermission,i.permission),o=n?await tt(this.dependencies.getDeviceNames):void 0,s=rt(nt(this.dependencies.getUserAgent));return le({generatedAt:this.now().toISOString(),sdk:{name:Ze,version:F},browser:s.browser,os:s.os,...i,permission:a,recentLogs:t?this.logs.toArray():[],...o===void 0?{}:{deviceNames:o}},{maskPhoneNumbers:r})}};async function et(e,t){try{return await e()}catch{return t}}async function tt(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function nt(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function rt(e){return{browser:it(e),os:at(e)}}function it(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function at(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}var ot=l({bugs:()=>_t,contributors:()=>ft,default:()=>xt,dependencies:()=>vt,description:()=>lt,devDependencies:()=>yt,homepage:()=>dt,keywords:()=>ht,license:()=>`MIT`,main:()=>mt,name:()=>st,repository:()=>gt,scripts:()=>bt,title:()=>ct,types:()=>pt,version:()=>ut}),st,ct,lt,ut,dt,ft,pt,mt,ht,gt,_t,vt,yt,bt,xt,St=s((()=>{st=`jssip`,ct=`JsSIP`,lt=`the Javascript SIP library`,ut=`3.10.1`,dt=`https://jssip.net`,ft=[`José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)`,`Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)`],pt=`lib/JsSIP.d.ts`,mt=`lib-es5/JsSIP.js`,ht=[`sip`,`websocket`,`webrtc`,`node`,`browser`,`library`],gt={type:`git`,url:`https://github.com/versatica/JsSIP.git`},_t={url:`https://github.com/versatica/JsSIP/issues`},vt={"@types/events":`^3.0.0`,"@types/debug":`^4.1.7`,debug:`^4.3.1`,events:`^3.3.0`,"sdp-transform":`^2.14.1`},yt={"@babel/core":`^7.19.6`,"@babel/preset-env":`^7.19.4`,"ansi-colors":`^3.2.4`,browserify:`^16.5.1`,eslint:`^5.16.0`,"fancy-log":`^1.3.3`,gulp:`^4.0.2`,"gulp-babel":`^8.0.0`,"gulp-eslint":`^5.0.0`,"gulp-expect-file":`^1.0.2`,"gulp-header":`^2.0.9`,"gulp-nodeunit-runner":`^0.2.2`,"gulp-plumber":`^1.2.1`,"gulp-rename":`^1.4.0`,"gulp-uglify-es":`^1.0.4`,pegjs:`^0.7.0`,"vinyl-buffer":`^1.0.1`,"vinyl-source-stream":`^2.0.0`},bt={lint:`node npm-scripts.js lint`,test:`node npm-scripts.js test`,prepublish:`node npm-scripts.js prepublish`,release:`node npm-scripts.js release`},xt={name:st,title:ct,description:lt,version:ut,homepage:dt,contributors:ft,types:pt,main:mt,keywords:ht,license:`MIT`,repository:gt,bugs:_t,dependencies:vt,devDependencies:yt,scripts:bt}})),W=c(((e,t)=>{var n=(St(),f(ot).default);t.exports={USER_AGENT:`${n.title} ${n.version}`,SIP:`sip`,SIPS:`sips`,causes:{CONNECTION_ERROR:`Connection Error`,REQUEST_TIMEOUT:`Request Timeout`,SIP_FAILURE_CODE:`SIP Failure Code`,INTERNAL_ERROR:`Internal Error`,BUSY:`Busy`,REJECTED:`Rejected`,REDIRECTED:`Redirected`,UNAVAILABLE:`Unavailable`,NOT_FOUND:`Not Found`,ADDRESS_INCOMPLETE:`Address Incomplete`,INCOMPATIBLE_SDP:`Incompatible SDP`,MISSING_SDP:`Missing SDP`,AUTHENTICATION_ERROR:`Authentication Error`,BYE:`Terminated`,WEBRTC_ERROR:`WebRTC Error`,CANCELED:`Canceled`,NO_ANSWER:`No Answer`,EXPIRES:`Expires`,NO_ACK:`No ACK`,DIALOG_ERROR:`Dialog Error`,USER_DENIED_MEDIA_ACCESS:`User Denied Media Access`,BAD_MEDIA_DESCRIPTION:`Bad Media Description`,RTP_TIMEOUT:`RTP Timeout`},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:`ACK`,BYE:`BYE`,CANCEL:`CANCEL`,INFO:`INFO`,INVITE:`INVITE`,MESSAGE:`MESSAGE`,NOTIFY:`NOTIFY`,OPTIONS:`OPTIONS`,REGISTER:`REGISTER`,REFER:`REFER`,UPDATE:`UPDATE`,SUBSCRIBE:`SUBSCRIBE`,DTMF_TRANSPORT:{INFO:`INFO`,RFC2833:`RFC2833`},REASON_PHRASE:{100:`Trying`,180:`Ringing`,181:`Call Is Being Forwarded`,182:`Queued`,183:`Session Progress`,199:`Early Dialog Terminated`,200:`OK`,202:`Accepted`,204:`No Notification`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Moved Temporarily`,305:`Use Proxy`,380:`Alternative Service`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,410:`Gone`,412:`Conditional Request Failed`,413:`Request Entity Too Large`,414:`Request-URI Too Long`,415:`Unsupported Media Type`,416:`Unsupported URI Scheme`,417:`Unknown Resource-Priority`,420:`Bad Extension`,421:`Extension Required`,422:`Session Interval Too Small`,423:`Interval Too Brief`,424:`Bad Location Information`,428:`Use Identity Header`,429:`Provide Referrer Identity`,430:`Flow Failed`,433:`Anonymity Disallowed`,436:`Bad Identity-Info`,437:`Unsupported Certificate`,438:`Invalid Identity Header`,439:`First Hop Lacks Outbound Support`,440:`Max-Breadth Exceeded`,469:`Bad Info Package`,470:`Consent Needed`,478:`Unresolvable Destination`,480:`Temporarily Unavailable`,481:`Call/Transaction Does Not Exist`,482:`Loop Detected`,483:`Too Many Hops`,484:`Address Incomplete`,485:`Ambiguous`,486:`Busy Here`,487:`Request Terminated`,488:`Not Acceptable Here`,489:`Bad Event`,491:`Request Pending`,493:`Undecipherable`,494:`Security Agreement Required`,500:`JsSIP Internal Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Server Time-out`,505:`Version Not Supported`,513:`Message Too Large`,580:`Precondition Failure`,600:`Busy Everywhere`,603:`Decline`,604:`Does Not Exist Anywhere`,606:`Not Acceptable`},ALLOWED_METHODS:`INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY`,ACCEPTED_BODY_TYPES:`application/sdp, application/dtmf-relay`,MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2}})),G=c(((e,t)=>{function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function i(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}function a(e){var t=u();return function(){var n=p(e),r;if(t){var i=p(this).constructor;r=Reflect.construct(n,arguments,i)}else r=n.apply(this,arguments);return o(this,r)}}function o(e,t){return t&&(n(t)===`object`||typeof t==`function`)?t:s(e)}function s(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function c(e){var t=typeof Map==`function`?new Map:void 0;return c=function(e){if(e===null||!d(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return l(e,arguments,p(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),f(n,e)},c(e)}function l(e,t,n){return l=u()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&f(i,n.prototype),i},l.apply(null,arguments)}function u(){if(typeof Reflect>`u`||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy==`function`)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function d(e){return Function.toString.call(e).indexOf(`[native code]`)!==-1}function f(e,t){return f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},f(e,t)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}t.exports={ConfigurationError:function(e){i(n,e);var t=a(n);function n(e,i){var a;return r(this,n),a=t.call(this),a.code=1,a.name=`CONFIGURATION_ERROR`,a.parameter=e,a.value=i,a.message=a.value?`Invalid value ${JSON.stringify(a.value)} for parameter "${a.parameter}"`:`Missing parameter: ${a.parameter}`,a}return n}(c(Error)),InvalidStateError:function(e){i(n,e);var t=a(n);function n(e){var i;return r(this,n),i=t.call(this),i.code=2,i.name=`INVALID_STATE_ERROR`,i.status=e,i.message=`Invalid status: ${e}`,i}return n}(c(Error)),NotSupportedError:function(e){i(n,e);var t=a(n);function n(e){var i;return r(this,n),i=t.call(this),i.code=3,i.name=`NOT_SUPPORTED_ERROR`,i.message=e,i}return n}(c(Error)),NotReadyError:function(e){i(n,e);var t=a(n);function n(e){var i;return r(this,n),i=t.call(this),i.code=4,i.name=`NOT_READY_ERROR`,i.message=e,i}return n}(c(Error))}})),Ct=c(((e,t)=>{function n(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}var a=wt(),o=K();t.exports=function(){i(e,null,[{key:`parse`,value:function(e){if(e=o.parse(e,`Name_Addr_Header`),e!==-1)return e}}]);function e(t,r,i){if(n(this,e),!t||!(t instanceof a))throw TypeError(`missing or invalid "uri" parameter`);for(var o in this._uri=t,this._parameters={},this.display_name=r,i)Object.prototype.hasOwnProperty.call(i,o)&&this.setParam(o,i[o])}return i(e,[{key:`setParam`,value:function(e,t){e&&(this._parameters[e.toLowerCase()]=t==null?null:t.toString())}},{key:`getParam`,value:function(e){if(e)return this._parameters[e.toLowerCase()]}},{key:`hasParam`,value:function(e){if(e)return this._parameters.hasOwnProperty(e.toLowerCase())&&!0||!1}},{key:`deleteParam`,value:function(e){if(e=e.toLowerCase(),this._parameters.hasOwnProperty(e)){var t=this._parameters[e];return delete this._parameters[e],t}}},{key:`clearParams`,value:function(){this._parameters={}}},{key:`clone`,value:function(){return new e(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:`_quote`,value:function(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}},{key:`toString`,value:function(){var e=this._display_name?`"${this._quote(this._display_name)}" `:``;for(var t in e+=`<${this._uri.toString()}>`,this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,t)&&(e+=`;${t}`,this._parameters[t]!==null&&(e+=`=${this._parameters[t]}`));return e}},{key:`uri`,get:function(){return this._uri}},{key:`display_name`,get:function(){return this._display_name},set:function(e){this._display_name=e===0?`0`:e}}]),e}()})),K=c(((e,t)=>{t.exports=function(){function e(e){return`"`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\x08/g,`\\b`).replace(/\t/g,`\\t`).replace(/\n/g,`\\n`).replace(/\f/g,`\\f`).replace(/\r/g,`\\r`).replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+`"`}var t={parse:function(t,n){var r={CRLF:l,DIGIT:u,ALPHA:d,HEXDIG:f,WSP:p,OCTET:m,DQUOTE:h,SP:g,HTAB:_,alphanum:v,reserved:y,unreserved:b,mark:x,escaped:S,LWS:C,SWS:w,HCOLON:T,TEXT_UTF8_TRIM:E,TEXT_UTF8char:D,UTF8_NONASCII:O,UTF8_CONT:k,LHEX:A,token:j,token_nodot:M,separators:N,word:P,STAR:ee,SLASH:te,EQUAL:F,LPAREN:I,RPAREN:ne,RAQUOT:re,LAQUOT:ie,COMMA:L,SEMI:R,COLON:ae,LDQUOT:oe,RDQUOT:se,comment:ce,ctext:le,quoted_string:ue,quoted_string_clean:de,qdtext:fe,quoted_pair:z,SIP_URI_noparams:B,SIP_URI:pe,uri_scheme:me,uri_scheme_sips:he,uri_scheme_sip:ge,userinfo:_e,user:ve,user_unreserved:ye,password:be,hostport:xe,host:Se,hostname:Ce,domainlabel:we,toplabel:Te,IPv6reference:Ee,IPv6address:De,h16:V,ls32:H,IPv4address:Oe,dec_octet:ke,port:Ae,uri_parameters:je,uri_parameter:Me,transport_param:Ne,user_param:Pe,method_param:Fe,ttl_param:Ie,maddr_param:U,lr_param:Le,other_param:Re,pname:ze,pvalue:Be,paramchar:Ve,param_unreserved:He,headers:Ue,header:We,hname:Ge,hvalue:Ke,hnv_unreserved:qe,Request_Response:Je,Request_Line:Ye,Request_URI:Xe,absoluteURI:Ze,hier_part:Qe,net_path:$e,abs_path:et,opaque_part:tt,uric:nt,uric_no_slash:rt,path_segments:it,segment:at,param:ot,pchar:st,scheme:ct,authority:lt,srvr:ut,reg_name:dt,query:ft,SIP_Version:pt,INVITEm:mt,ACKm:ht,OPTIONSm:gt,BYEm:_t,CANCELm:vt,REGISTERm:yt,SUBSCRIBEm:bt,NOTIFYm:xt,REFERm:St,Method:W,Status_Line:G,Status_Code:K,extension_code:q,Reason_Phrase:J,Allow_Events:Tt,Call_ID:Et,Contact:Dt,contact_param:Y,name_addr:X,display_name:Ot,contact_params:kt,c_p_q:At,c_p_expires:Z,delta_seconds:jt,qvalue:Mt,generic_param:Q,gen_value:Nt,Content_Disposition:Pt,disp_type:Ft,disp_param:It,handling_param:Lt,Content_Encoding:Rt,Content_Length:zt,Content_Type:Bt,media_type:Vt,m_type:Ht,discrete_type:Ut,composite_type:Wt,extension_token:Gt,x_token:Kt,m_subtype:qt,m_parameter:Jt,m_value:Yt,CSeq:Xt,CSeq_value:Zt,Expires:Qt,Event:$t,event_type:en,From:tn,from_param:nn,tag_param:rn,Max_Forwards:an,Min_Expires:on,Name_Addr_Header:sn,Proxy_Authenticate:cn,challenge:ln,other_challenge:un,auth_param:dn,digest_cln:fn,realm:pn,realm_value:mn,domain:hn,URI:gn,nonce:_n,nonce_value:vn,opaque:yn,stale:bn,algorithm:xn,qop_options:Sn,qop_value:Cn,Proxy_Require:wn,Record_Route:Tn,rec_route:En,Reason:Dn,reason_param:On,reason_cause:kn,Require:An,Route:jn,route_param:Mn,Subscription_State:Nn,substate_value:Pn,subexp_params:Fn,event_reason_value:In,Subject:Ln,Supported:Rn,To:zn,to_param:Bn,Via:Vn,via_param:Hn,via_params:Un,via_ttl:Wn,via_maddr:Gn,via_received:Kn,via_branch:qn,response_port:Jn,rport:Yn,sent_protocol:Xn,protocol_name:Zn,transport:Qn,sent_by:$n,via_host:er,via_port:tr,ttl:nr,WWW_Authenticate:rr,Session_Expires:ir,s_e_expires:ar,s_e_params:or,s_e_refresher:sr,extension_header:cr,header_value:lr,message_body:ur,uuid_URI:dr,uuid:fr,hex4:pr,hex8:mr,hex12:hr,Refer_To:gr,Replaces:_r,call_id:vr,replaces_param:yr,to_tag:br,from_tag:xr,early_flag:Sr};if(n!==void 0){if(r[n]===void 0)throw Error(`Invalid rule name: `+e(n)+`.`)}else n=`CRLF`;var i=0,a=0,o=0,s=[];function c(e){i<o||(i>o&&(o=i,s=[]),s.push(e))}function l(){var e;return t.substr(i,2)===`\r
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CCBarSDK={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>o.call(e,`module.exports`)?e[`module.exports`]:u(n({},`__esModule`,{value:!0}),e),p,m=s((()=>{p=class extends Error{code;category;retryable;requestId;callId;cause;serverCode;status;constructor(e,t,n,r={}){super(e),this.name=`CCBarError`,this.code=e,this.category=t,this.retryable=n,this.requestId=r.requestId,this.callId=r.callId,this.cause=r.cause,this.serverCode=r.serverCode,this.status=r.status}}}));m();var h=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},g={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},_=(e,t)=>g[e].has(t);function v(e,t){if(!_(e,t))throw new y(e,t);return t}var y=class extends p{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},b=v;function x(e){if(e.code!==`OK`)throw TypeError(`Unexpected session response code: ${e.code}`);if(e.data===void 0||e.data===null)throw TypeError(`Unexpected session response: missing data`);return e.data}m();var S=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],C=3e4,w=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(e){this.options=e,this.id=e.id,this.destination=e.destination,this.platform=e.platform,this.capabilities=e.capabilities??new Set;try{S.forEach(t=>{this.sessionUnsubscribers.push(e.session.on(t,e=>this.handleSessionEvent(t,e)))})}catch(t){this.cleanupSessionListeners();try{e.session.terminate()}catch{}throw new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,`held`,()=>this.options.session.hold())}async resume(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),await this.startPendingOperation(`resume`,`active`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!E(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),T(this.currentState))throw this.operationError();try{this.options.session.terminate(),T(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!T(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||T(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.transitionIfAllowed(`held`,t,e);break;case`unhold`:this.transitionIfAllowed(`active`,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(_(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!_(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,T(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{T(e)&&this.dispose()}}startPendingOperation(e,t,n){if(this.pendingOperation!==void 0)throw this.operationError();return new Promise((r,i)=>{let a={kind:e,nextState:t,resolve:r,reject:i};this.pendingOperation=a,a.timer=setTimeout(()=>this.timeoutPendingOperation(a),C);let o;try{o=n()}catch(e){this.rejectPendingOperation(e);return}o.then(()=>this.resolvePendingOperation(a),e=>this.rejectPendingOperation(e,a))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||T(this.currentState)){e.reject(this.operationError());return}try{this.transitionTo(e.nextState),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(e){let t=e instanceof p&&e.callId===this.id?e:this.operationError(e);try{this.options.onError?.(t)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(e){return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:e})}};function T(e){return e===`ended`||e===`failed`}function E(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var D=0;function O(){return D+=1,`call_${Date.now().toString(36)}_${D.toString(36)}`}m();var k=`X-User-Data`,A=/[^\x20-\x7E]/,j=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function M(e){if(typeof e!=`string`)return[];let t=e.trim();if(t===``)return[];if(A.test(t))throw new p(`CALL_INVALID_USERDATA`,`call`,!1,{cause:j});return[`${k}: ${t}`]}m();var N=class{events=new P;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(e){this.options=e,this.incomingSessionSnapshot=e.session;try{this.incomingUnsubscribe=e.sip.onIncoming(e=>this.handleIncoming(e))}catch(e){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(e,t){this.assertNotDisposed();let n=this.operationGeneration,r=e.destination.trim();if(r===``)throw new p(`CALL_INVALID_DESTINATION`,`call`,!1);let i=M(e.userdata);this.requireCapability(t,`outbound`);let a=this.callLimit(t);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=a)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=a||this.pendingDestinations.has(r)||[...this.calls.values()].some(e=>e.destination===r))throw new p(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(r);let o=O(),s;try{s=await this.holdActiveCallForNewCall(),this.assertGeneration(n,o);let a;try{a=this.options.sip.dial(r,this.dialOptions(o,t,e.type,i))}catch(e){throw this.dialError(e,o)}this.assertGeneration(n,o);let c;try{c=new w({id:o,destination:r,platform:this.options.platform,capabilities:this.effectiveCapabilities(t),session:a,onStateChanged:(e,t)=>this.handleStateChanged(c,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(c)})}catch(e){throw this.dialError(e,o)}if(!this.isCurrentGeneration(n))throw c.dispose(),this.callOperationError(c.id);this.calls.set(c.id,c),this.callSessions.set(c.id,a),this.options.onCallCreated?.(c.id,a);try{c.beginOutbound()}catch(e){throw c.dispose(),this.calls.delete(c.id),this.callSessions.delete(c.id),this.dialError(e,c.id)}if(!this.isCurrentGeneration(n))throw c.dispose(),this.calls.delete(c.id),this.callSessions.delete(c.id),this.callOperationError(c.id);return this.events.emit(`call.created`,{callId:c.id,state:c.state}),c}catch(e){if(this.isCurrentGeneration(n)&&s!==void 0&&this.isManagedCall(s)&&s.state===`held`)try{await s.resume()}catch(t){throw this.compensationError(s.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(r)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:ee(n)}):this.events.emit(`call.failed`,{callId:e.id,error:te(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(e){if(this.disposed)return;let t=O(),n=this.incomingSessionSnapshot;if(n===void 0||!n.policy.incomingEnabled||!this.effectiveCapabilities(n).has(`inbound`)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:this.capabilityError(t)});return}let r=e.from??e.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(n)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:new p(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:t})});return}let i;try{i=new w({id:t,destination:r,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(i,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(i)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(t,e)});return}this.calls.set(i.id,i),this.callSessions.set(i.id,e),this.options.onCallCreated?.(i.id,e);try{i.beginIncoming(),this.events.emit(`call.incoming`,{callId:i.id,from:r})}catch(e){i.dispose(),this.events.emit(`error`,{error:this.callOperationError(i.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(e,t){return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e,cause:t})}capabilityError(e){return new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(e,t){return e instanceof p?new p(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e}):new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}},P=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function ee(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function te(e,t){if(e instanceof p)return new p(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e});if(typeof e==`object`&&e&&`error`in e){let n=e.error;if(n instanceof p)return new p(n.code,n.category,n.retryable,{requestId:n.requestId,callId:t,cause:n.cause??n});if(n instanceof Error)return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}var F=`3.8.1`,I=`[REDACTED]`,ne=/\bBearer\s+[^\s,;"'}]+/gi,re=/(\bAuthorization\s*[:=]\s*)Digest\s+[^\r\n]*/gi,ie=/(\bAuthorization\s*[:=]\s*)(?:(Bearer|Basic|Digest|Token)\s+)?[^\s,;"'}]+/gi,L=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,R=/\b((?:sip|sips|turn|turns|ws|wss):(?:\/\/)?)[^/?#@\s:]+:[^/?#@\s]+@/gi,ae=/(\b(?:sip(?:Register)?Ticket|registerTicket|wssTicket|turnCredential|credential|accessToken|refreshToken|appSecret|password|jwt|ticket)\b\s*[:=]\s*)(["']?)([^\s,;&}"']+)(["']?)/gi,oe=/(?<!\d)(1[3-9]\d)\d{4}(\d{4})(?!\d)/g,se=/(?:authorization|token|ticket|credential|password|secret)$/i;function ce(e,t={}){let n=e.replace(ne,`Bearer ${I}`).replace(re,(e,t)=>`${t}Digest ${I}`).replace(ie,(e,t,n)=>`${t}${n===void 0?``:`${n} `}${I}`).replace(L,I).replace(R,(e,t)=>`${t}${I}@`).replace(ae,(e,t)=>`${t}${I}`);return t.maskPhoneNumbers!==!1&&(n=n.replace(oe,`$1****$2`)),n}function le(e,t={}){return ue(e,t,new WeakSet)}function ue(e,t,n){if(typeof e==`string`)return ce(e,t);if(typeof e!=`object`||!e)return e;if(n.has(e))return`[Circular]`;if(n.add(e),Array.isArray(e))return e.map(e=>ue(e,t,n));let r={};return Object.entries(e).forEach(([e,i])=>{r[e]=se.test(e)?I:ue(i,t,n)}),r}m();function de(e){if(!z(e))throw B(`Invalid worker message`);if(e.version!==1)throw B(`Unsupported worker protocol version`);if(e.type===`attach`||e.type===`detach`)return fe(e),e;if(e.type===`command`){if(fe(e),typeof e.command!=`string`||e.payload!==void 0&&!z(e.payload))throw B(`Invalid worker command`);return e}if(e.type===`response`){if(typeof e.requestId!=`string`||typeof e.ok!=`boolean`)throw B(`Invalid worker response`);return e}if(e.type===`event`){if(typeof e.event!=`string`||!(`payload`in e))throw B(`Invalid worker event`);return e}throw B(`Unknown worker message type`)}function fe(e){if(typeof e.requestId!=`string`||typeof e.tabId!=`string`)throw B(`Worker request requires requestId and tabId`)}function z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function B(e){return new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}m();var pe=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(e){return this.closed?Promise.reject(new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(e.requestId)?Promise.reject(new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:e.requestId})):this.lifecycleState===`reconnecting`&&e.type===`command`&&(e.command===`dial`||e.command===`answer`)?Promise.reject(new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:e.payload?.callId})):new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(e.requestId),n(new p(`NETWORK_TIMEOUT`,`network`,!0,{requestId:e.requestId}))},this.timeoutMs);this.pending.set(e.requestId,{resolve:e=>t(e),reject:n,timer:r}),this.port.postMessage(e)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(e=>{clearTimeout(e.timer),e.reject(new p(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(e){try{let t=de(e);if(t.type===`event`){t.event===`connection.stateChanged`&&me(t.payload)&&(this.lifecycleState=t.payload.state),this.eventHandlers.forEach(e=>e(t));return}if(t.type!==`response`)return;let n=this.pending.get(t.requestId);if(n===void 0)return;this.pending.delete(t.requestId),clearTimeout(n.timer),t.ok?n.resolve(t.result):n.reject(he(t))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function me(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function he(e){let t=e.error;return new p(t?.code??`SDK_INTERNAL_ERROR`,t?.category??`internal`,t?.retryable??!1,{requestId:e.requestId,...t?.message===void 0?{}:{cause:t.message},...t?.serverCode===void 0?{}:{serverCode:t.serverCode},...t?.status===void 0?{}:{status:t.status}})}m();function ge(e={}){if((e.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let t=e.locationHref??ve(),n=_e(e.url,t),r=t=>{if(e.fallback===`error`)throw new p(`CONFIG_INVALID`,`configuration`,!1,{cause:t});return{mode:`single-tab`,reason:t}};if(n===void 0)return r(`SharedWorker URL is unavailable`);if(!be(n,t))return r(`SharedWorker URL must be same-origin`);let i=e.workerCtor??ye();if(i===void 0)return r(`SharedWorker is not supported`);let a;try{a=new i(n,e.name===void 0?void 0:{name:e.name})}catch(e){return r(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let o=e.tabId??xe(),s=new pe(a.port),c={version:1,type:`attach`,requestId:Se(),tabId:o},l=s.request(c).then(()=>void 0).catch(e=>{throw s.close(),e});return{mode:`shared`,worker:a,client:s,tabId:o,workerUrl:n,ready:l}}function _e(e,t=ve()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function ve(){return typeof location>`u`?void 0:location.href}function ye(){if(typeof SharedWorker==`function`)return SharedWorker}function be(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function xe(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function Se(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}m();var Ce=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??we(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw De(e)}Te(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw V(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(e,t){if(!this.supportsOutputSelection())throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=e;let n=++this.outputGeneration;t!==void 0&&await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(e,t)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(e,t){let n=t;if(typeof n.setSinkId!=`function`)throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await n.setSinkId(e)}catch(e){throw H(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw Ee(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function we(){return globalThis.navigator?.mediaDevices}function Te(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function Ee(e){let t=Oe(e);return t===`NotFoundError`||t===`OverconstrainedError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function De(e){let t=Oe(e);return t===`NotFoundError`||t===`OverconstrainedError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function V(e){let t=Oe(e);return t===`NotFoundError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function H(e){let t=Oe(e);return t===`NotFoundError`?new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new p(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function Oe(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}m();var ke=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=Ae){this.createAudioElement=e}async bind(e,t){let n=this.bindings.get(e);if(n?.stream===t)return;let r=je(e,t),i;try{i=this.createAudioElement()}catch(t){throw Me(r,this.trackOwners),new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e,cause:t})}let a=this.audioOwners.get(i);if(a!==void 0&&a!==e)throw Me(r,this.trackOwners),new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});try{i.autoplay=!0,i.playsInline=!0}catch(t){throw Me(r,this.trackOwners),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}try{i.srcObject=t}catch(t){throw Me(r,this.trackOwners),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}this.acquireTracks(r),n!==void 0&&this.releaseBinding(n,n.audio!==i);let o=this.nextGeneration(e);this.audioOwners.set(i,e);let s={callId:e,audio:i,stream:t,tracks:r,generation:o};this.bindings.set(e,s),this.beginPlay(e);try{await i.play()}catch(t){if(!this.isCurrent(e,o))return;throw new p(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,o)}async play(e){let t=this.bindings.get(e);if(t===void 0)throw new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});let n=t.generation;this.beginPlay(e);try{await t.audio.play()}catch(t){if(!this.isCurrent(e,n))return;throw new p(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,n)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),Pe(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function Ae(){if(typeof document>`u`)throw new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function je(e,t){try{return[...new Set(t.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(n){try{return[...new Set(t.getTracks())].filter(e=>e.kind===`audio`)}catch(r){throw Ne(t),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:n??r})}}}function Me(e,t){e.forEach(e=>{(t.get(e)??0)===0&&Pe(e)})}function Ne(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(Pe)}catch{}}function Pe(e){try{e.stop()}catch{}}m();var Fe=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new Ce(t),this.remoteAudio=new ke(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??He}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=Ie(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(e){let t=this.releaseOperations.get(e);if(t!==void 0)return t;if(!this.resources.has(e))return Promise.resolve();let n=e.callId;this.remoteAudio.release(n),this.releaseErrors.delete(e),this.calls.get(n)===e&&this.calls.delete(n),e.generation+=1,e.released=!0,this.unsubscribeTrackSource(e);let r=new Set([...e.localTracks,...e.pendingTracks]),i=[...e.senders.values()].filter(e=>e.audio).map(t=>({senderResource:t,promise:this.enqueueSender(e,t,()=>Re(t.sender),!0)})),a=Promise.all(i.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async t=>{let i=new Set,a=[];if(t.forEach(e=>{if(e.cause!==void 0){a.push(e.cause);let t=U(e.senderResource.sender);t?.kind===`audio`&&i.add(t);return}let t=U(e.senderResource.sender);t?.kind===`audio`&&r.add(t)}),r.forEach(e=>{i.has(e)||Ve(e)}),a.length>0)throw e.localTracks.clear(),e.pendingTracks.clear(),i.forEach(t=>e.localTracks.add(t)),new p(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:a[0]});if(!e.peerClosed&&e.peerConnection.close!==void 0)try{await e.peerConnection.close(),e.peerClosed=!0}catch(t){let r=[...e.senders.values()].map(e=>U(e.sender)).find(e=>e?.kind===`audio`);throw e.localTracks.clear(),e.pendingTracks.clear(),r!=null&&e.localTracks.add(r),new p(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:t})}e.localTracks.clear(),e.pendingTracks.clear(),e.senders.clear(),this.resources.delete(e),this.releaseUnusedSenderQueues()}).catch(t=>{throw this.releaseErrors.set(e,t),this.calls.get(n)===void 0&&this.calls.set(n,e),t}).finally(()=>{this.releaseOperations.get(e)===a&&this.releaseOperations.delete(e)});return this.releaseOperations.set(e,a),a}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(e,t,n){if(this.assertActiveCall(t),this.assertDeviceSelectionCapability(t),!this.isCurrentResource(n)||t.peerConnection!==n.peerConnection)throw this.callOperationError(t.callId);let r=this.findAudioSender(n),i=U(r.sender),a=n.generation,o=await this.deviceManager.openInputStream(e),s;try{s=o.getTracks()}catch(e){throw ze(o),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let c;try{c=o.getAudioTracks()}catch(e){throw Be(s),new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let l=c[0];if(l===void 0)throw Be(s),new p(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:t.callId});if(!this.canCommitInputSwitch(t,n,r,i,a))throw Be(s),this.callOperationError(t.callId);s.forEach(e=>n.pendingTracks.add(e)),n.pendingTracks.add(l);try{await this.enqueueSender(n,r,()=>r.sender.replaceTrack(l))}catch(e){throw n.released?this.callOperationError(t.callId):(n.released||(s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),await this.rollbackSender(n,r,i,l),Be(s)),new p(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:t.callId,cause:e}))}if(!this.canCommitInputSwitch(t,n,r,l,a)){if(!n.released)try{await this.enqueueSender(n,r,()=>U(r.sender)===l?Re(r.sender):Promise.resolve()),s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),Be(s)}catch(e){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:t.callId,cause:e})}throw this.callOperationError(t.callId)}s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),n.localTracks.add(l),i!==null&&i!==l&&(n.localTracks.delete(i),Ve(i)),s.forEach(e=>{e!==l&&Ve(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(e,t){let n;try{n=e.peerConnection.getSenders()}catch(t){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}n.forEach(n=>{let r=U(n),i;try{i=t?.(n)??n.senderKind??n.kind}catch(t){throw new p(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}e.senders.set(n,{sender:n,audio:i===`audio`||i===void 0&&r?.kind===`audio`,queue:this.senderQueues.get(n)??this.createSenderQueue(n)}),r?.kind===`audio`&&e.localTracks.add(r)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(U(e.sender)?.kind===`audio`||U(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return U(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||U(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(e){if(e===void 0||e.state!==`active`)throw new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(e){return new p(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}callOperationError(e){return new p(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e})}assertNotDisposed(){if(this.disposed||this.disposing)throw new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function Ie(e){return`peerConnection`in e}function U(e){try{return e.track}catch{return null}}function Le(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function Re(e){try{return e.replaceTrack(null).catch(e=>{if(!Le(e))throw e})}catch(e){return Le(e)?Promise.resolve():Promise.reject(e)}}function ze(e){try{Be(e.getTracks())}catch{}}function Be(e){e.forEach(Ve)}function Ve(e){try{e.stop()}catch{}}function He(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}m();function Ue(e,t={}){let n=new Map,r=new Map,i=new Set,a=t.ownershipRequired===!0,o=!1,s=!1,c,l=()=>e(),u=new Fe({getActiveCall:l});return{publicMedia:{requestPermission:()=>(d(),u.requestPermission()),getDevices:()=>(d(),u.getDevices()),getCapabilities:()=>(d(),u.getCapabilities()),supportsOutputSelection:()=>(d(),u.supportsOutputSelection()),setInputDevice:e=>(d(),u.setInputDevice(e,l())),setOutputDevice:e=>(d(),u.setOutputDevice(e)),playRemoteAudio:e=>(d(),u.playRemoteAudio(e)),releaseAll:()=>(d(),u.releaseAll())},registerCall(e,t){o||s||!We(t)||(r.set(e,t),(!a||i.has(e))&&f(e,t))},async setCallOwnership(e,t){if(o)return;if(t!==`owned`){i.delete(e),await u.releaseCall(e),n.delete(e);return}i.add(e);let a=r.get(e);a!==void 0&&f(e,a)},contextFor(e,t,r){let i=n.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:r,peerConnection:i.peerConnection}},async releaseCall(e){o||(await u.releaseCall(e),n.delete(e),r.delete(e),i.delete(e))},releaseAll:async()=>{await u.releaseAll(),n.clear(),r.clear(),i.clear()},getResourceCounts:()=>u.getResourceCounts(),dispose:()=>{if(c!==void 0)return c;s=!0;let e=u.dispose().then(()=>{o=!0,s=!1,n.clear(),r.clear(),i.clear()}).finally(()=>{c===e&&!o&&(c=void 0,s=!1)});return c=e,e}};function d(){if(o)throw new p(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function f(e,t){if(!We(t)||typeof t.getMediaRegistration!=`function`)return;let r=t.getMediaRegistration();if(Ge(r)&&n.get(e)?.peerConnection!==r.peerConnection){n.set(e,r);try{u.registerCallMedia(e,r)}catch{n.delete(e)}}}}function We(e){return typeof e==`object`&&!!e}function Ge(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var Ke=1e3,qe=3e4;function Je(e,t=Math.random){let n=Math.min(qe,Ke*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var Ye=class{recover;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=Je(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},Xe=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},Ze=`@16x/webphone-sdk`,Qe=200,$e=class{dependencies;logs=new Xe(Qe);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(e,t,n){this.logs.push({timestamp:this.now().toISOString(),level:e,message:ce(t),...n===void 0?{}:{context:le(n)}})}async getReport(e={}){let t=e.includeRecentLogs!==!1,n=e.includeDeviceNames===!0,r=e.maskPhoneNumbers!==!1,i=this.dependencies.getSnapshot(),a=this.dependencies.getPermission===void 0?i.permission:await et(this.dependencies.getPermission,i.permission),o=n?await tt(this.dependencies.getDeviceNames):void 0,s=rt(nt(this.dependencies.getUserAgent));return le({generatedAt:this.now().toISOString(),sdk:{name:Ze,version:F},browser:s.browser,os:s.os,...i,permission:a,recentLogs:t?this.logs.toArray():[],...o===void 0?{}:{deviceNames:o}},{maskPhoneNumbers:r})}};async function et(e,t){try{return await e()}catch{return t}}async function tt(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function nt(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function rt(e){return{browser:it(e),os:at(e)}}function it(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function at(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}var ot=l({bugs:()=>_t,contributors:()=>ft,default:()=>xt,dependencies:()=>vt,description:()=>lt,devDependencies:()=>yt,homepage:()=>dt,keywords:()=>ht,license:()=>`MIT`,main:()=>mt,name:()=>st,repository:()=>gt,scripts:()=>bt,title:()=>ct,types:()=>pt,version:()=>ut}),st,ct,lt,ut,dt,ft,pt,mt,ht,gt,_t,vt,yt,bt,xt,St=s((()=>{st=`jssip`,ct=`JsSIP`,lt=`the Javascript SIP library`,ut=`3.10.1`,dt=`https://jssip.net`,ft=[`José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)`,`Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)`],pt=`lib/JsSIP.d.ts`,mt=`lib-es5/JsSIP.js`,ht=[`sip`,`websocket`,`webrtc`,`node`,`browser`,`library`],gt={type:`git`,url:`https://github.com/versatica/JsSIP.git`},_t={url:`https://github.com/versatica/JsSIP/issues`},vt={"@types/events":`^3.0.0`,"@types/debug":`^4.1.7`,debug:`^4.3.1`,events:`^3.3.0`,"sdp-transform":`^2.14.1`},yt={"@babel/core":`^7.19.6`,"@babel/preset-env":`^7.19.4`,"ansi-colors":`^3.2.4`,browserify:`^16.5.1`,eslint:`^5.16.0`,"fancy-log":`^1.3.3`,gulp:`^4.0.2`,"gulp-babel":`^8.0.0`,"gulp-eslint":`^5.0.0`,"gulp-expect-file":`^1.0.2`,"gulp-header":`^2.0.9`,"gulp-nodeunit-runner":`^0.2.2`,"gulp-plumber":`^1.2.1`,"gulp-rename":`^1.4.0`,"gulp-uglify-es":`^1.0.4`,pegjs:`^0.7.0`,"vinyl-buffer":`^1.0.1`,"vinyl-source-stream":`^2.0.0`},bt={lint:`node npm-scripts.js lint`,test:`node npm-scripts.js test`,prepublish:`node npm-scripts.js prepublish`,release:`node npm-scripts.js release`},xt={name:st,title:ct,description:lt,version:ut,homepage:dt,contributors:ft,types:pt,main:mt,keywords:ht,license:`MIT`,repository:gt,bugs:_t,dependencies:vt,devDependencies:yt,scripts:bt}})),W=c(((e,t)=>{var n=(St(),f(ot).default);t.exports={USER_AGENT:`${n.title} ${n.version}`,SIP:`sip`,SIPS:`sips`,causes:{CONNECTION_ERROR:`Connection Error`,REQUEST_TIMEOUT:`Request Timeout`,SIP_FAILURE_CODE:`SIP Failure Code`,INTERNAL_ERROR:`Internal Error`,BUSY:`Busy`,REJECTED:`Rejected`,REDIRECTED:`Redirected`,UNAVAILABLE:`Unavailable`,NOT_FOUND:`Not Found`,ADDRESS_INCOMPLETE:`Address Incomplete`,INCOMPATIBLE_SDP:`Incompatible SDP`,MISSING_SDP:`Missing SDP`,AUTHENTICATION_ERROR:`Authentication Error`,BYE:`Terminated`,WEBRTC_ERROR:`WebRTC Error`,CANCELED:`Canceled`,NO_ANSWER:`No Answer`,EXPIRES:`Expires`,NO_ACK:`No ACK`,DIALOG_ERROR:`Dialog Error`,USER_DENIED_MEDIA_ACCESS:`User Denied Media Access`,BAD_MEDIA_DESCRIPTION:`Bad Media Description`,RTP_TIMEOUT:`RTP Timeout`},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:`ACK`,BYE:`BYE`,CANCEL:`CANCEL`,INFO:`INFO`,INVITE:`INVITE`,MESSAGE:`MESSAGE`,NOTIFY:`NOTIFY`,OPTIONS:`OPTIONS`,REGISTER:`REGISTER`,REFER:`REFER`,UPDATE:`UPDATE`,SUBSCRIBE:`SUBSCRIBE`,DTMF_TRANSPORT:{INFO:`INFO`,RFC2833:`RFC2833`},REASON_PHRASE:{100:`Trying`,180:`Ringing`,181:`Call Is Being Forwarded`,182:`Queued`,183:`Session Progress`,199:`Early Dialog Terminated`,200:`OK`,202:`Accepted`,204:`No Notification`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Moved Temporarily`,305:`Use Proxy`,380:`Alternative Service`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,410:`Gone`,412:`Conditional Request Failed`,413:`Request Entity Too Large`,414:`Request-URI Too Long`,415:`Unsupported Media Type`,416:`Unsupported URI Scheme`,417:`Unknown Resource-Priority`,420:`Bad Extension`,421:`Extension Required`,422:`Session Interval Too Small`,423:`Interval Too Brief`,424:`Bad Location Information`,428:`Use Identity Header`,429:`Provide Referrer Identity`,430:`Flow Failed`,433:`Anonymity Disallowed`,436:`Bad Identity-Info`,437:`Unsupported Certificate`,438:`Invalid Identity Header`,439:`First Hop Lacks Outbound Support`,440:`Max-Breadth Exceeded`,469:`Bad Info Package`,470:`Consent Needed`,478:`Unresolvable Destination`,480:`Temporarily Unavailable`,481:`Call/Transaction Does Not Exist`,482:`Loop Detected`,483:`Too Many Hops`,484:`Address Incomplete`,485:`Ambiguous`,486:`Busy Here`,487:`Request Terminated`,488:`Not Acceptable Here`,489:`Bad Event`,491:`Request Pending`,493:`Undecipherable`,494:`Security Agreement Required`,500:`JsSIP Internal Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Server Time-out`,505:`Version Not Supported`,513:`Message Too Large`,580:`Precondition Failure`,600:`Busy Everywhere`,603:`Decline`,604:`Does Not Exist Anywhere`,606:`Not Acceptable`},ALLOWED_METHODS:`INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY`,ACCEPTED_BODY_TYPES:`application/sdp, application/dtmf-relay`,MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2}})),G=c(((e,t)=>{function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function i(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}function a(e){var t=u();return function(){var n=p(e),r;if(t){var i=p(this).constructor;r=Reflect.construct(n,arguments,i)}else r=n.apply(this,arguments);return o(this,r)}}function o(e,t){return t&&(n(t)===`object`||typeof t==`function`)?t:s(e)}function s(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function c(e){var t=typeof Map==`function`?new Map:void 0;return c=function(e){if(e===null||!d(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return l(e,arguments,p(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),f(n,e)},c(e)}function l(e,t,n){return l=u()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&f(i,n.prototype),i},l.apply(null,arguments)}function u(){if(typeof Reflect>`u`||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy==`function`)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function d(e){return Function.toString.call(e).indexOf(`[native code]`)!==-1}function f(e,t){return f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},f(e,t)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}t.exports={ConfigurationError:function(e){i(n,e);var t=a(n);function n(e,i){var a;return r(this,n),a=t.call(this),a.code=1,a.name=`CONFIGURATION_ERROR`,a.parameter=e,a.value=i,a.message=a.value?`Invalid value ${JSON.stringify(a.value)} for parameter "${a.parameter}"`:`Missing parameter: ${a.parameter}`,a}return n}(c(Error)),InvalidStateError:function(e){i(n,e);var t=a(n);function n(e){var i;return r(this,n),i=t.call(this),i.code=2,i.name=`INVALID_STATE_ERROR`,i.status=e,i.message=`Invalid status: ${e}`,i}return n}(c(Error)),NotSupportedError:function(e){i(n,e);var t=a(n);function n(e){var i;return r(this,n),i=t.call(this),i.code=3,i.name=`NOT_SUPPORTED_ERROR`,i.message=e,i}return n}(c(Error)),NotReadyError:function(e){i(n,e);var t=a(n);function n(e){var i;return r(this,n),i=t.call(this),i.code=4,i.name=`NOT_READY_ERROR`,i.message=e,i}return n}(c(Error))}})),Ct=c(((e,t)=>{function n(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}var a=wt(),o=K();t.exports=function(){i(e,null,[{key:`parse`,value:function(e){if(e=o.parse(e,`Name_Addr_Header`),e!==-1)return e}}]);function e(t,r,i){if(n(this,e),!t||!(t instanceof a))throw TypeError(`missing or invalid "uri" parameter`);for(var o in this._uri=t,this._parameters={},this.display_name=r,i)Object.prototype.hasOwnProperty.call(i,o)&&this.setParam(o,i[o])}return i(e,[{key:`setParam`,value:function(e,t){e&&(this._parameters[e.toLowerCase()]=t==null?null:t.toString())}},{key:`getParam`,value:function(e){if(e)return this._parameters[e.toLowerCase()]}},{key:`hasParam`,value:function(e){if(e)return this._parameters.hasOwnProperty(e.toLowerCase())&&!0||!1}},{key:`deleteParam`,value:function(e){if(e=e.toLowerCase(),this._parameters.hasOwnProperty(e)){var t=this._parameters[e];return delete this._parameters[e],t}}},{key:`clearParams`,value:function(){this._parameters={}}},{key:`clone`,value:function(){return new e(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:`_quote`,value:function(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}},{key:`toString`,value:function(){var e=this._display_name?`"${this._quote(this._display_name)}" `:``;for(var t in e+=`<${this._uri.toString()}>`,this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,t)&&(e+=`;${t}`,this._parameters[t]!==null&&(e+=`=${this._parameters[t]}`));return e}},{key:`uri`,get:function(){return this._uri}},{key:`display_name`,get:function(){return this._display_name},set:function(e){this._display_name=e===0?`0`:e}}]),e}()})),K=c(((e,t)=>{t.exports=function(){function e(e){return`"`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\x08/g,`\\b`).replace(/\t/g,`\\t`).replace(/\n/g,`\\n`).replace(/\f/g,`\\f`).replace(/\r/g,`\\r`).replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+`"`}var t={parse:function(t,n){var r={CRLF:l,DIGIT:u,ALPHA:d,HEXDIG:f,WSP:p,OCTET:m,DQUOTE:h,SP:g,HTAB:_,alphanum:v,reserved:y,unreserved:b,mark:x,escaped:S,LWS:C,SWS:w,HCOLON:T,TEXT_UTF8_TRIM:E,TEXT_UTF8char:D,UTF8_NONASCII:O,UTF8_CONT:k,LHEX:A,token:j,token_nodot:M,separators:N,word:P,STAR:ee,SLASH:te,EQUAL:F,LPAREN:I,RPAREN:ne,RAQUOT:re,LAQUOT:ie,COMMA:L,SEMI:R,COLON:ae,LDQUOT:oe,RDQUOT:se,comment:ce,ctext:le,quoted_string:ue,quoted_string_clean:de,qdtext:fe,quoted_pair:z,SIP_URI_noparams:B,SIP_URI:pe,uri_scheme:me,uri_scheme_sips:he,uri_scheme_sip:ge,userinfo:_e,user:ve,user_unreserved:ye,password:be,hostport:xe,host:Se,hostname:Ce,domainlabel:we,toplabel:Te,IPv6reference:Ee,IPv6address:De,h16:V,ls32:H,IPv4address:Oe,dec_octet:ke,port:Ae,uri_parameters:je,uri_parameter:Me,transport_param:Ne,user_param:Pe,method_param:Fe,ttl_param:Ie,maddr_param:U,lr_param:Le,other_param:Re,pname:ze,pvalue:Be,paramchar:Ve,param_unreserved:He,headers:Ue,header:We,hname:Ge,hvalue:Ke,hnv_unreserved:qe,Request_Response:Je,Request_Line:Ye,Request_URI:Xe,absoluteURI:Ze,hier_part:Qe,net_path:$e,abs_path:et,opaque_part:tt,uric:nt,uric_no_slash:rt,path_segments:it,segment:at,param:ot,pchar:st,scheme:ct,authority:lt,srvr:ut,reg_name:dt,query:ft,SIP_Version:pt,INVITEm:mt,ACKm:ht,OPTIONSm:gt,BYEm:_t,CANCELm:vt,REGISTERm:yt,SUBSCRIBEm:bt,NOTIFYm:xt,REFERm:St,Method:W,Status_Line:G,Status_Code:K,extension_code:q,Reason_Phrase:J,Allow_Events:Tt,Call_ID:Et,Contact:Dt,contact_param:Y,name_addr:X,display_name:Ot,contact_params:kt,c_p_q:At,c_p_expires:Z,delta_seconds:jt,qvalue:Mt,generic_param:Q,gen_value:Nt,Content_Disposition:Pt,disp_type:Ft,disp_param:It,handling_param:Lt,Content_Encoding:Rt,Content_Length:zt,Content_Type:Bt,media_type:Vt,m_type:Ht,discrete_type:Ut,composite_type:Wt,extension_token:Gt,x_token:Kt,m_subtype:qt,m_parameter:Jt,m_value:Yt,CSeq:Xt,CSeq_value:Zt,Expires:Qt,Event:$t,event_type:en,From:tn,from_param:nn,tag_param:rn,Max_Forwards:an,Min_Expires:on,Name_Addr_Header:sn,Proxy_Authenticate:cn,challenge:ln,other_challenge:un,auth_param:dn,digest_cln:fn,realm:pn,realm_value:mn,domain:hn,URI:gn,nonce:_n,nonce_value:vn,opaque:yn,stale:bn,algorithm:xn,qop_options:Sn,qop_value:Cn,Proxy_Require:wn,Record_Route:Tn,rec_route:En,Reason:Dn,reason_param:On,reason_cause:kn,Require:An,Route:jn,route_param:Mn,Subscription_State:Nn,substate_value:Pn,subexp_params:Fn,event_reason_value:In,Subject:Ln,Supported:Rn,To:zn,to_param:Bn,Via:Vn,via_param:Hn,via_params:Un,via_ttl:Wn,via_maddr:Gn,via_received:Kn,via_branch:qn,response_port:Jn,rport:Yn,sent_protocol:Xn,protocol_name:Zn,transport:Qn,sent_by:$n,via_host:er,via_port:tr,ttl:nr,WWW_Authenticate:rr,Session_Expires:ir,s_e_expires:ar,s_e_params:or,s_e_refresher:sr,extension_header:cr,header_value:lr,message_body:ur,uuid_URI:dr,uuid:fr,hex4:pr,hex8:mr,hex12:hr,Refer_To:gr,Replaces:_r,call_id:vr,replaces_param:yr,to_tag:br,from_tag:xr,early_flag:Sr};if(n!==void 0){if(r[n]===void 0)throw Error(`Invalid rule name: `+e(n)+`.`)}else n=`CRLF`;var i=0,a=0,o=0,s=[];function c(e){i<o||(i>o&&(o=i,s=[]),s.push(e))}function l(){var e;return t.substr(i,2)===`\r
2
2
  `?(e=`\r
3
3
  `,i+=2):(e=null,a===0&&c(`"\\r\\n"`)),e}function u(){var e;return/^[0-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[0-9]`)),e}function d(){var e;return/^[a-zA-Z]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-zA-Z]`)),e}function f(){var e;return/^[0-9a-fA-F]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[0-9a-fA-F]`)),e}function p(){var e=g();return e===null&&(e=_()),e}function m(){var e;return/^[\0-\xFF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\0-\\xFF]`)),e}function h(){var e;return/^["]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`["]`)),e}function g(){var e;return t.charCodeAt(i)===32?(e=` `,i++):(e=null,a===0&&c(`" "`)),e}function _(){var e;return t.charCodeAt(i)===9?(e=` `,i++):(e=null,a===0&&c(`"\\t"`)),e}function v(){var e;return/^[a-zA-Z0-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-zA-Z0-9]`)),e}function y(){var e;return t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`))))))))))),e}function b(){var e=v();return e===null&&(e=x()),e}function x(){var e;return t.charCodeAt(i)===45?(e=`-`,i++):(e=null,a===0&&c(`"-"`)),e===null&&(t.charCodeAt(i)===95?(e=`_`,i++):(e=null,a===0&&c(`"_"`)),e===null&&(t.charCodeAt(i)===46?(e=`.`,i++):(e=null,a===0&&c(`"."`)),e===null&&(t.charCodeAt(i)===33?(e=`!`,i++):(e=null,a===0&&c(`"!"`)),e===null&&(t.charCodeAt(i)===126?(e=`~`,i++):(e=null,a===0&&c(`"~"`)),e===null&&(t.charCodeAt(i)===42?(e=`*`,i++):(e=null,a===0&&c(`"*"`)),e===null&&(t.charCodeAt(i)===39?(e=`'`,i++):(e=null,a===0&&c(`"'"`)),e===null&&(t.charCodeAt(i)===40?(e=`(`,i++):(e=null,a===0&&c(`"("`)),e===null&&(t.charCodeAt(i)===41?(e=`)`,i++):(e=null,a===0&&c(`")"`)))))))))),e}function S(){var e,n,r,o=i,s=i;return t.charCodeAt(i)===37?(e=`%`,i++):(e=null,a===0&&c(`"%"`)),e===null?(e=null,i=s):(n=f(),n===null?(e=null,i=s):(r=f(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){return t.join(``)}(o,e)),e===null&&(i=o),e}function C(){var e,t,n,r=i,a=i,o=i;for(e=[],t=p();t!==null;)e.push(t),t=p();if(e===null?(e=null,i=o):(t=l(),t===null?(e=null,i=o):e=[e,t]),e=e===null?``:e,e!==null){if(n=p(),n!==null)for(t=[];n!==null;)t.push(n),n=p();else t=null;t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e!==null&&(e=function(e){return` `}(r)),e===null&&(i=r),e}function w(){var e=C();return e=e===null?``:e,e}function T(){var e,n,r,o=i,s=i;for(e=[],n=g(),n===null&&(n=_());n!==null;)e.push(n),n=g(),n===null&&(n=_());return e===null?(e=null,i=s):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`:`}(o)),e===null&&(i=o),e}function E(){var e,n,r,a,o=i,s=i,c;if(n=D(),n!==null)for(e=[];n!==null;)e.push(n),n=D();else e=null;if(e!==null){for(n=[],c=i,r=[],a=C();a!==null;)r.push(a),a=C();for(r===null?(r=null,i=c):(a=D(),a===null?(r=null,i=c):r=[r,a]);r!==null;){for(n.push(r),c=i,r=[],a=C();a!==null;)r.push(a),a=C();r===null?(r=null,i=c):(a=D(),a===null?(r=null,i=c):r=[r,a])}n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e!==null&&(e=function(e){return t.substring(i,e)}(o)),e===null&&(i=o),e}function D(){var e;return/^[!-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[!-~]`)),e===null&&(e=O()),e}function O(){var e;return/^[\x80-\uFFFF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\x80-\\uFFFF]`)),e}function k(){var e;return/^[\x80-\xBF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\x80-\\xBF]`)),e}function A(){var e=u();return e===null&&(/^[a-f]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-f]`))),e}function j(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`))))))))))));else e=null;return e!==null&&(e=function(e){return t.substring(i,e)}(r)),e===null&&(i=r),e}function M(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)))))))))));else e=null;return e!==null&&(e=function(e){return t.substring(i,e)}(r)),e===null&&(i=r),e}function N(){var e;return t.charCodeAt(i)===40?(e=`(`,i++):(e=null,a===0&&c(`"("`)),e===null&&(t.charCodeAt(i)===41?(e=`)`,i++):(e=null,a===0&&c(`")"`)),e===null&&(t.charCodeAt(i)===60?(e=`<`,i++):(e=null,a===0&&c(`"<"`)),e===null&&(t.charCodeAt(i)===62?(e=`>`,i++):(e=null,a===0&&c(`">"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===92?(e=`\\`,i++):(e=null,a===0&&c(`"\\\\"`)),e===null&&(e=h(),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===123?(e=`{`,i++):(e=null,a===0&&c(`"{"`)),e===null&&(t.charCodeAt(i)===125?(e=`}`,i++):(e=null,a===0&&c(`"}"`)),e===null&&(e=g(),e===null&&(e=_())))))))))))))))))),e}function P(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)),n===null&&(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null&&(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null&&(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null&&(t.charCodeAt(i)===62?(n=`>`,i++):(n=null,a===0&&c(`">"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===92?(n=`\\`,i++):(n=null,a===0&&c(`"\\\\"`)),n===null&&(n=h(),n===null&&(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null&&(t.charCodeAt(i)===91?(n=`[`,i++):(n=null,a===0&&c(`"["`)),n===null&&(t.charCodeAt(i)===93?(n=`]`,i++):(n=null,a===0&&c(`"]"`)),n===null&&(t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null&&(t.charCodeAt(i)===123?(n=`{`,i++):(n=null,a===0&&c(`"{"`)),n===null&&(t.charCodeAt(i)===125?(n=`}`,i++):(n=null,a===0&&c(`"}"`))))))))))))))))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)),n===null&&(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null&&(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null&&(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null&&(t.charCodeAt(i)===62?(n=`>`,i++):(n=null,a===0&&c(`">"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===92?(n=`\\`,i++):(n=null,a===0&&c(`"\\\\"`)),n===null&&(n=h(),n===null&&(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null&&(t.charCodeAt(i)===91?(n=`[`,i++):(n=null,a===0&&c(`"["`)),n===null&&(t.charCodeAt(i)===93?(n=`]`,i++):(n=null,a===0&&c(`"]"`)),n===null&&(t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null&&(t.charCodeAt(i)===123?(n=`{`,i++):(n=null,a===0&&c(`"{"`)),n===null&&(t.charCodeAt(i)===125?(n=`}`,i++):(n=null,a===0&&c(`"}"`)))))))))))))))))))))))));else e=null;return e!==null&&(e=function(e){return t.substring(i,e)}(r)),e===null&&(i=r),e}function ee(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`*`}(o)),e===null&&(i=o),e}function te(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`/`}(o)),e===null&&(i=o),e}function F(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`=`}(o)),e===null&&(i=o),e}function I(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`(`}(o)),e===null&&(i=o),e}function ne(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`)`}(o)),e===null&&(i=o),e}function re(){var e,n,r=i,o=i;return t.charCodeAt(i)===62?(e=`>`,i++):(e=null,a===0&&c(`">"`)),e===null?(e=null,i=o):(n=w(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e){return`>`}(r)),e===null&&(i=r),e}function ie(){var e,n,r=i,o=i;return e=w(),e===null?(e=null,i=o):(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e){return`<`}(r)),e===null&&(i=r),e}function L(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`,`}(o)),e===null&&(i=o),e}function R(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`;`}(o)),e===null&&(i=o),e}function ae(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return`:`}(o)),e===null&&(i=o),e}function oe(){var e,t,n=i,r=i;return e=w(),e===null?(e=null,i=r):(t=h(),t===null?(e=null,i=r):e=[e,t]),e!==null&&(e=function(e){return`"`}(n)),e===null&&(i=n),e}function se(){var e,t,n=i,r=i;return e=h(),e===null?(e=null,i=r):(t=w(),t===null?(e=null,i=r):e=[e,t]),e!==null&&(e=function(e){return`"`}(n)),e===null&&(i=n),e}function ce(){var e,t,n,r=i;if(e=I(),e!==null){for(t=[],n=le(),n===null&&(n=z(),n===null&&(n=ce()));n!==null;)t.push(n),n=le(),n===null&&(n=z(),n===null&&(n=ce()));t===null?(e=null,i=r):(n=ne(),n===null?(e=null,i=r):e=[e,t,n])}else e=null,i=r;return e}function le(){var e;return/^[!-']/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[!-']`)),e===null&&(/^[*-[]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[*-[]`)),e===null&&(/^[\]-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\]-~]`)),e===null&&(e=O(),e===null&&(e=C())))),e}function ue(){var e,n,r,a,o=i,s=i;if(e=w(),e!==null){if(n=h(),n!==null){for(r=[],a=fe(),a===null&&(a=z());a!==null;)r.push(a),a=fe(),a===null&&(a=z());r===null?(e=null,i=s):(a=h(),a===null?(e=null,i=s):e=[e,n,r,a])}else e=null,i=s}else e=null,i=s;return e!==null&&(e=function(e){return t.substring(i,e)}(o)),e===null&&(i=o),e}function de(){var e,n,r,a,o=i,s=i;if(e=w(),e!==null){if(n=h(),n!==null){for(r=[],a=fe(),a===null&&(a=z());a!==null;)r.push(a),a=fe(),a===null&&(a=z());r===null?(e=null,i=s):(a=h(),a===null?(e=null,i=s):e=[e,n,r,a])}else e=null,i=s}else e=null,i=s;return e!==null&&(e=function(e){var n=t.substring(i,e).trim();return n.substring(1,n.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,`$1`)}(o)),e===null&&(i=o),e}function fe(){var e=C();return e===null&&(t.charCodeAt(i)===33?(e=`!`,i++):(e=null,a===0&&c(`"!"`)),e===null&&(/^[#-[]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[#-[]`)),e===null&&(/^[\]-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\]-~]`)),e===null&&(e=O())))),e}function z(){var e,n,r=i;return t.charCodeAt(i)===92?(e=`\\`,i++):(e=null,a===0&&c(`"\\\\"`)),e===null?(e=null,i=r):(/^[\0-\t]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\0-\\t]`)),n===null&&(/^[\x0B-\f]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\x0B-\\f]`)),n===null&&(/^[\x0E-]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\x0E-]`)))),n===null?(e=null,i=r):e=[e,n]),e}function B(){var e,n,r,o,s=i,l=i;return e=me(),e===null?(e=null,i=l):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=l):(r=_e(),r=r===null?``:r,r===null?(e=null,i=l):(o=xe(),o===null?(e=null,i=l):e=[e,n,r,o]))),e!==null&&(e=function(e){try{$.uri=new Tr($.scheme,$.user,$.host,$.port),delete $.scheme,delete $.user,delete $.host,delete $.host_type,delete $.port}catch{$=-1}}(s)),e===null&&(i=s),e}function pe(){var e,r,o,s,l,u,d=i,f=i;return e=me(),e===null?(e=null,i=f):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=f):(o=_e(),o=o===null?``:o,o===null?(e=null,i=f):(s=xe(),s===null?(e=null,i=f):(l=je(),l===null?(e=null,i=f):(u=Ue(),u=u===null?``:u,u===null?(e=null,i=f):e=[e,r,o,s,l,u]))))),e!==null&&(e=function(e){try{$.uri=new Tr($.scheme,$.user,$.host,$.port,$.uri_params,$.uri_headers),delete $.scheme,delete $.user,delete $.host,delete $.host_type,delete $.port,delete $.uri_params,n===`SIP_URI`&&($=$.uri)}catch{$=-1}}(d)),e===null&&(i=d),e}function me(){var e=he();return e===null&&(e=ge()),e}function he(){var e,n=i;return t.substr(i,4).toLowerCase()===`sips`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"sips"`)),e!==null&&(e=function(e,t){$.scheme=t.toLowerCase()}(n,e)),e===null&&(i=n),e}function ge(){var e,n=i;return t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"sip"`)),e!==null&&(e=function(e,t){$.scheme=t.toLowerCase()}(n,e)),e===null&&(i=n),e}function _e(){var e,n,r,o=i,s=i,l;return e=ve(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=l):(r=be(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):(t.charCodeAt(i)===64?(r=`@`,i++):(r=null,a===0&&c(`"@"`)),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){$.user=decodeURIComponent(t.substring(i-1,e))}(o)),e===null&&(i=o),e}function ve(){var e,t=b();if(t===null&&(t=S(),t===null&&(t=ye())),t!==null)for(e=[];t!==null;)e.push(t),t=b(),t===null&&(t=S(),t===null&&(t=ye()));else e=null;return e}function ye(){var e;return t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`))))))))),e}function be(){var e,n,r=i;for(e=[],n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`))))))));n!==null;)e.push(n),n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`))))))));return e!==null&&(e=function(e){$.password=t.substring(i,e)}(r)),e===null&&(i=r),e}function xe(){var e,n,r,o=i,s;return e=Se(),e===null?(e=null,i=o):(s=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=s):(r=Ae(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function Se(){var e,n=i;return e=Ce(),e===null&&(e=Oe(),e===null&&(e=Ee())),e!==null&&(e=function(e){return $.host=t.substring(i,e).toLowerCase(),$.host}(n)),e===null&&(i=n),e}function Ce(){var e,n,r,o=i,s=i,l;for(e=[],l=i,n=we(),n===null?(n=null,i=l):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(n=null,i=l):n=[n,r]);n!==null;)e.push(n),l=i,n=we(),n===null?(n=null,i=l):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(n=null,i=l):n=[n,r]);return e===null?(e=null,i=s):(n=Te(),n===null?(e=null,i=s):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r=r===null?``:r,r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return $.host_type=`domain`,t.substring(i,e)}(o)),e===null&&(i=o),e}function we(){var e,n,r,o=i;if(e=v(),e!==null){for(n=[],r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));r!==null;)n.push(r),r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));n===null?(e=null,i=o):e=[e,n]}else e=null,i=o;return e}function Te(){var e,n,r,o=i;if(e=d(),e!==null){for(n=[],r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));r!==null;)n.push(r),r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));n===null?(e=null,i=o):e=[e,n]}else e=null,i=o;return e}function Ee(){var e,n,r,o=i,s=i;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null?(e=null,i=s):(n=De(),n===null?(e=null,i=s):(t.charCodeAt(i)===93?(r=`]`,i++):(r=null,a===0&&c(`"]"`)),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e){return $.host_type=`IPv6`,t.substring(i,e)}(o)),e===null&&(i=o),e}function De(){var e,n,r,o,s,l,u,d,f,p,m,h,g,_=i,v=i,y;return e=V(),e===null?(e=null,i=v):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=v):(r=V(),r===null?(e=null,i=v):(t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(e=null,i=v):(s=V(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=V(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=V(),f===null?(e=null,i=v):(t.charCodeAt(i)===58?(p=`:`,i++):(p=null,a===0&&c(`":"`)),p===null?(e=null,i=v):(m=V(),m===null?(e=null,i=v):(t.charCodeAt(i)===58?(h=`:`,i++):(h=null,a===0&&c(`":"`)),h===null?(e=null,i=v):(g=H(),g===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m,h,g])))))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=V(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=V(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=V(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=V(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=V(),p===null?(e=null,i=v):(t.charCodeAt(i)===58?(m=`:`,i++):(m=null,a===0&&c(`":"`)),m===null?(e=null,i=v):(h=H(),h===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m,h]))))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=V(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=V(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=V(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=V(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=H(),p===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p]))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=V(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=V(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=V(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=H(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=V(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=V(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=H(),l===null?(e=null,i=v):e=[e,n,r,o,s,l]))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=V(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=H(),o===null?(e=null,i=v):e=[e,n,r,o]))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=H(),n===null?(e=null,i=v):e=[e,n]),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=V(),n===null?(e=null,i=v):e=[e,n]),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(t.substr(i,2)===`::`?(n=`::`,i+=2):(n=null,a===0&&c(`"::"`)),n===null?(e=null,i=v):(r=V(),r===null?(e=null,i=v):(t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(e=null,i=v):(s=V(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=V(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=V(),f===null?(e=null,i=v):(t.charCodeAt(i)===58?(p=`:`,i++):(p=null,a===0&&c(`":"`)),p===null?(e=null,i=v):(m=H(),m===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m])))))))))),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=V(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(t.substr(i,2)===`::`?(r=`::`,i+=2):(r=null,a===0&&c(`"::"`)),r===null?(e=null,i=v):(o=V(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=V(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=V(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=H(),p===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p]))))))))),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=V(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=V(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(t.substr(i,2)===`::`?(o=`::`,i+=2):(o=null,a===0&&c(`"::"`)),o===null?(e=null,i=v):(s=V(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=V(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=H(),f===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f])))))))),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=V(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=V(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=V(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(t.substr(i,2)===`::`?(s=`::`,i+=2):(s=null,a===0&&c(`"::"`)),s===null?(e=null,i=v):(l=V(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=H(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=V(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=V(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=V(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=V(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(t.substr(i,2)===`::`?(l=`::`,i+=2):(l=null,a===0&&c(`"::"`)),l===null?(e=null,i=v):(u=H(),u===null?(e=null,i=v):e=[e,n,r,o,s,l,u])))))),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=V(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=V(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=V(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=V(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(l=null,i=y):(u=V(),u===null?(l=null,i=y):l=[l,u]),l=l===null?``:l,l===null?(e=null,i=v):(t.substr(i,2)===`::`?(u=`::`,i+=2):(u=null,a===0&&c(`"::"`)),u===null?(e=null,i=v):(d=V(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,e=V(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=V(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=V(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=V(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=V(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(l=null,i=y):(u=V(),u===null?(l=null,i=y):l=[l,u]),l=l===null?``:l,l===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(u=null,i=y):(d=V(),d===null?(u=null,i=y):u=[u,d]),u=u===null?``:u,u===null?(e=null,i=v):(t.substr(i,2)===`::`?(d=`::`,i+=2):(d=null,a===0&&c(`"::"`)),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))))))))))))))))),e!==null&&(e=function(e){return $.host_type=`IPv6`,t.substring(i,e)}(_)),e===null&&(i=_),e}function V(){var e,t,n,r,a=i;return e=f(),e===null?(e=null,i=a):(t=f(),t=t===null?``:t,t===null?(e=null,i=a):(n=f(),n=n===null?``:n,n===null?(e=null,i=a):(r=f(),r=r===null?``:r,r===null?(e=null,i=a):e=[e,t,n,r]))),e}function H(){var e,n,r,o=i;return e=V(),e===null?(e=null,i=o):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=o):(r=V(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(e=Oe()),e}function Oe(){var e,n,r,o,s,l,u,d=i,f=i;return e=ke(),e===null?(e=null,i=f):(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null?(e=null,i=f):(r=ke(),r===null?(e=null,i=f):(t.charCodeAt(i)===46?(o=`.`,i++):(o=null,a===0&&c(`"."`)),o===null?(e=null,i=f):(s=ke(),s===null?(e=null,i=f):(t.charCodeAt(i)===46?(l=`.`,i++):(l=null,a===0&&c(`"."`)),l===null?(e=null,i=f):(u=ke(),u===null?(e=null,i=f):e=[e,n,r,o,s,l,u])))))),e!==null&&(e=function(e){return $.host_type=`IPv4`,t.substring(i,e)}(d)),e===null&&(i=d),e}function ke(){var e,n,r,o=i;return t.substr(i,2)===`25`?(e=`25`,i+=2):(e=null,a===0&&c(`"25"`)),e===null?(e=null,i=o):(/^[0-5]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[0-5]`)),n===null?(e=null,i=o):e=[e,n]),e===null&&(o=i,t.charCodeAt(i)===50?(e=`2`,i++):(e=null,a===0&&c(`"2"`)),e===null?(e=null,i=o):(/^[0-4]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[0-4]`)),n===null?(e=null,i=o):(r=u(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(o=i,t.charCodeAt(i)===49?(e=`1`,i++):(e=null,a===0&&c(`"1"`)),e===null?(e=null,i=o):(n=u(),n===null?(e=null,i=o):(r=u(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(o=i,/^[1-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[1-9]`)),e===null?(e=null,i=o):(n=u(),n===null?(e=null,i=o):e=[e,n]),e===null&&(e=u())))),e}function Ae(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=function(e,t){return t=parseInt(t.join(``)),$.port=t,t}(o,e)),e===null&&(i=o),e}function je(){var e=[],n,r,o=i;for(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(n=null,i=o):(r=Me(),r===null?(n=null,i=o):n=[n,r]);n!==null;)e.push(n),o=i,t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(n=null,i=o):(r=Me(),r===null?(n=null,i=o):n=[n,r]);return e}function Me(){var e=Ne();return e===null&&(e=Pe(),e===null&&(e=Fe(),e===null&&(e=Ie(),e===null&&(e=U(),e===null&&(e=Le(),e===null&&(e=Re())))))),e}function Ne(){var e,n,r=i,o=i;return t.substr(i,10).toLowerCase()===`transport=`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"transport="`)),e===null?(e=null,i=o):(t.substr(i,3).toLowerCase()===`udp`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"udp"`)),n===null&&(t.substr(i,3).toLowerCase()===`tcp`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"tcp"`)),n===null&&(t.substr(i,4).toLowerCase()===`sctp`?(n=t.substr(i,4),i+=4):(n=null,a===0&&c(`"sctp"`)),n===null&&(t.substr(i,3).toLowerCase()===`tls`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"tls"`)),n===null&&(n=j())))),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e,t){$.uri_params||($.uri_params={}),$.uri_params.transport=t.toLowerCase()}(r,e[1])),e===null&&(i=r),e}function Pe(){var e,n,r=i,o=i;return t.substr(i,5).toLowerCase()===`user=`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"user="`)),e===null?(e=null,i=o):(t.substr(i,5).toLowerCase()===`phone`?(n=t.substr(i,5),i+=5):(n=null,a===0&&c(`"phone"`)),n===null&&(t.substr(i,2).toLowerCase()===`ip`?(n=t.substr(i,2),i+=2):(n=null,a===0&&c(`"ip"`)),n===null&&(n=j())),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e,t){$.uri_params||($.uri_params={}),$.uri_params.user=t.toLowerCase()}(r,e[1])),e===null&&(i=r),e}function Fe(){var e,n,r=i,o=i;return t.substr(i,7).toLowerCase()===`method=`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"method="`)),e===null?(e=null,i=o):(n=W(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e,t){$.uri_params||($.uri_params={}),$.uri_params.method=t}(r,e[1])),e===null&&(i=r),e}function Ie(){var e,n,r=i,o=i;return t.substr(i,4).toLowerCase()===`ttl=`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"ttl="`)),e===null?(e=null,i=o):(n=nr(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e,t){$.params||($.params={}),$.params.ttl=t}(r,e[1])),e===null&&(i=r),e}function U(){var e,n,r=i,o=i;return t.substr(i,6).toLowerCase()===`maddr=`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"maddr="`)),e===null?(e=null,i=o):(n=Se(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=function(e,t){$.uri_params||($.uri_params={}),$.uri_params.maddr=t}(r,e[1])),e===null&&(i=r),e}function Le(){var e,n,r,o=i,s=i,l;return t.substr(i,2).toLowerCase()===`lr`?(e=t.substr(i,2),i+=2):(e=null,a===0&&c(`"lr"`)),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(n=null,i=l):(r=j(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=function(e){$.uri_params||($.uri_params={}),$.uri_params.lr=void 0}(o)),e===null&&(i=o),e}function Re(){var e,n,r,o=i,s=i,l;return e=ze(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(n=null,i=l):(r=Be(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=function(e,t,n){$.uri_params||($.uri_params={}),n=n===void 0?void 0:n[1],$.uri_params[t.toLowerCase()]=n}(o,e[0],e[1])),e===null&&(i=o),e}function ze(){var e,t,n=i;if(t=Ve(),t!==null)for(e=[];t!==null;)e.push(t),t=Ve();else e=null;return e!==null&&(e=function(e,t){return t.join(``)}(n,e)),e===null&&(i=n),e}function Be(){var e,t,n=i;if(t=Ve(),t!==null)for(e=[];t!==null;)e.push(t),t=Ve();else e=null;return e!==null&&(e=function(e,t){return t.join(``)}(n,e)),e===null&&(i=n),e}function Ve(){var e=He();return e===null&&(e=b(),e===null&&(e=S())),e}function He(){var e;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)))))))),e}function Ue(){var e,n,r,o,s,l=i,u;if(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e!==null){if(n=We(),n!==null){for(r=[],u=i,t.charCodeAt(i)===38?(o=`&`,i++):(o=null,a===0&&c(`"&"`)),o===null?(o=null,i=u):(s=We(),s===null?(o=null,i=u):o=[o,s]);o!==null;)r.push(o),u=i,t.charCodeAt(i)===38?(o=`&`,i++):(o=null,a===0&&c(`"&"`)),o===null?(o=null,i=u):(s=We(),s===null?(o=null,i=u):o=[o,s]);r===null?(e=null,i=l):e=[e,n,r]}else e=null,i=l}else e=null,i=l;return e}function We(){var e,n,r,o=i,s=i;return e=Ge(),e===null?(e=null,i=s):(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(e=null,i=s):(r=Ke(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t,n){t=t.join(``).toLowerCase(),n=n.join(``),$.uri_headers||($.uri_headers={}),$.uri_headers[t]?$.uri_headers[t].push(n):$.uri_headers[t]=[n]}(o,e[0],e[2])),e===null&&(i=o),e}function Ge(){var e,t=qe();if(t===null&&(t=b(),t===null&&(t=S())),t!==null)for(e=[];t!==null;)e.push(t),t=qe(),t===null&&(t=b(),t===null&&(t=S()));else e=null;return e}function Ke(){var e=[],t=qe();for(t===null&&(t=b(),t===null&&(t=S()));t!==null;)e.push(t),t=qe(),t===null&&(t=b(),t===null&&(t=S()));return e}function qe(){var e;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)))))))),e}function Je(){var e=G();return e===null&&(e=Ye()),e}function Ye(){var e,t,n,r,a,o=i;return e=W(),e===null?(e=null,i=o):(t=g(),t===null?(e=null,i=o):(n=Xe(),n===null?(e=null,i=o):(r=g(),r===null?(e=null,i=o):(a=pt(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function Xe(){var e=pe();return e===null&&(e=Ze()),e}function Ze(){var e,n,r,o=i;return e=ct(),e===null?(e=null,i=o):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=o):(r=Qe(),r===null&&(r=tt()),r===null?(e=null,i=o):e=[e,n,r])),e}function Qe(){var e,n,r,o=i,s;return e=$e(),e===null&&(e=et()),e===null?(e=null,i=o):(s=i,t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null?(n=null,i=s):(r=ft(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function $e(){var e,n,r,o=i;return t.substr(i,2)===`//`?(e=`//`,i+=2):(e=null,a===0&&c(`"//"`)),e===null?(e=null,i=o):(n=lt(),n===null?(e=null,i=o):(r=et(),r=r===null?``:r,r===null?(e=null,i=o):e=[e,n,r])),e}function et(){var e,n,r=i;return t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null?(e=null,i=r):(n=it(),n===null?(e=null,i=r):e=[e,n]),e}function tt(){var e,t,n,r=i;if(e=rt(),e!==null){for(t=[],n=nt();n!==null;)t.push(n),n=nt();t===null?(e=null,i=r):e=[e,t]}else e=null,i=r;return e}function nt(){var e=y();return e===null&&(e=b(),e===null&&(e=S())),e}function rt(){var e=b();return e===null&&(e=S(),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)))))))))))),e}function it(){var e,n,r,o,s=i,l;if(e=at(),e!==null){for(n=[],l=i,t.charCodeAt(i)===47?(r=`/`,i++):(r=null,a===0&&c(`"/"`)),r===null?(r=null,i=l):(o=at(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===47?(r=`/`,i++):(r=null,a===0&&c(`"/"`)),r===null?(r=null,i=l):(o=at(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function at(){var e,n,r,o,s=i,l;for(e=[],n=st();n!==null;)e.push(n),n=st();if(e!==null){for(n=[],l=i,t.charCodeAt(i)===59?(r=`;`,i++):(r=null,a===0&&c(`";"`)),r===null?(r=null,i=l):(o=ot(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===59?(r=`;`,i++):(r=null,a===0&&c(`";"`)),r===null?(r=null,i=l):(o=ot(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function ot(){for(var e=[],t=st();t!==null;)e.push(t),t=st();return e}function st(){var e=b();return e===null&&(e=S(),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)))))))))),e}function ct(){var e,n,r,o=i,s=i;if(e=d(),e!==null){for(n=[],r=d(),r===null&&(r=u(),r===null&&(t.charCodeAt(i)===43?(r=`+`,i++):(r=null,a===0&&c(`"+"`)),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`))))));r!==null;)n.push(r),r=d(),r===null&&(r=u(),r===null&&(t.charCodeAt(i)===43?(r=`+`,i++):(r=null,a===0&&c(`"+"`)),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`))))));n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e!==null&&(e=function(e){$.scheme=t.substring(i,e)}(o)),e===null&&(i=o),e}function lt(){var e=ut();return e===null&&(e=dt()),e}function ut(){var e,n,r=i,o=i;return e=_e(),e===null?(e=null,i=o):(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(e=null,i=o):e=[e,n]),e=e===null?``:e,e===null?(e=null,i=r):(n=xe(),n===null?(e=null,i=r):e=[e,n]),e=e===null?``:e,e}function dt(){var e,n=b();if(n===null&&(n=S(),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null&&(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null&&(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)))))))))));else e=null;return e}function ft(){for(var e=[],t=nt();t!==null;)e.push(t),t=nt();return e}function pt(){var e,n,r,o,s,l,d=i,f=i;if(t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e!==null){if(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n!==null){if(o=u(),o!==null)for(r=[];o!==null;)r.push(o),o=u();else r=null;if(r!==null){if(t.charCodeAt(i)===46?(o=`.`,i++):(o=null,a===0&&c(`"."`)),o!==null){if(l=u(),l!==null)for(s=[];l!==null;)s.push(l),l=u();else s=null;s===null?(e=null,i=f):e=[e,n,r,o,s]}else e=null,i=f}else e=null,i=f}else e=null,i=f}else e=null,i=f;return e!==null&&(e=function(e){$.sip_version=t.substring(i,e)}(d)),e===null&&(i=d),e}function mt(){var e;return t.substr(i,6)===`INVITE`?(e=`INVITE`,i+=6):(e=null,a===0&&c(`"INVITE"`)),e}function ht(){var e;return t.substr(i,3)===`ACK`?(e=`ACK`,i+=3):(e=null,a===0&&c(`"ACK"`)),e}function gt(){var e;return t.substr(i,7)===`OPTIONS`?(e=`OPTIONS`,i+=7):(e=null,a===0&&c(`"OPTIONS"`)),e}function _t(){var e;return t.substr(i,3)===`BYE`?(e=`BYE`,i+=3):(e=null,a===0&&c(`"BYE"`)),e}function vt(){var e;return t.substr(i,6)===`CANCEL`?(e=`CANCEL`,i+=6):(e=null,a===0&&c(`"CANCEL"`)),e}function yt(){var e;return t.substr(i,8)===`REGISTER`?(e=`REGISTER`,i+=8):(e=null,a===0&&c(`"REGISTER"`)),e}function bt(){var e;return t.substr(i,9)===`SUBSCRIBE`?(e=`SUBSCRIBE`,i+=9):(e=null,a===0&&c(`"SUBSCRIBE"`)),e}function xt(){var e;return t.substr(i,6)===`NOTIFY`?(e=`NOTIFY`,i+=6):(e=null,a===0&&c(`"NOTIFY"`)),e}function St(){var e;return t.substr(i,5)===`REFER`?(e=`REFER`,i+=5):(e=null,a===0&&c(`"REFER"`)),e}function W(){var e,n=i;return e=mt(),e===null&&(e=ht(),e===null&&(e=gt(),e===null&&(e=_t(),e===null&&(e=vt(),e===null&&(e=yt(),e===null&&(e=bt(),e===null&&(e=xt(),e===null&&(e=St(),e===null&&(e=j()))))))))),e!==null&&(e=function(e){return $.method=t.substring(i,e),$.method}(n)),e===null&&(i=n),e}function G(){var e,t,n,r,a,o=i;return e=pt(),e===null?(e=null,i=o):(t=g(),t===null?(e=null,i=o):(n=K(),n===null?(e=null,i=o):(r=g(),r===null?(e=null,i=o):(a=J(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function K(){var e,t=i;return e=q(),e!==null&&(e=function(e,t){$.status_code=parseInt(t.join(``))}(t,e)),e===null&&(i=t),e}function q(){var e,t,n,r=i;return e=u(),e===null?(e=null,i=r):(t=u(),t===null?(e=null,i=r):(n=u(),n===null?(e=null,i=r):e=[e,t,n])),e}function J(){var e,n,r=i;for(e=[],n=y(),n===null&&(n=b(),n===null&&(n=S(),n===null&&(n=O(),n===null&&(n=k(),n===null&&(n=g(),n===null&&(n=_()))))));n!==null;)e.push(n),n=y(),n===null&&(n=b(),n===null&&(n=S(),n===null&&(n=O(),n===null&&(n=k(),n===null&&(n=g(),n===null&&(n=_()))))));return e!==null&&(e=function(e){$.reason_phrase=t.substring(i,e)}(r)),e===null&&(i=r),e}function Tt(){var e,t,n,r,a=i,o;if(e=en(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=en(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=en(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Et(){var e,n,r,o=i,s=i,l;return e=P(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(n=null,i=l):(r=P(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=function(e){$=t.substring(i,e)}(o)),e===null&&(i=o),e}function Dt(){var e,t,n,r,a=i,o,s;if(e=ee(),e===null){if(o=i,e=Y(),e!==null){for(t=[],s=i,n=L(),n===null?(n=null,i=s):(r=Y(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=L(),n===null?(n=null,i=s):(r=Y(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o}return e!==null&&(e=function(e){var t,n=$.multi_header.length;for(t=0;t<n;t++)if($.multi_header[t].parsed===null){$=null;break}$=$===null?-1:$.multi_header}(a)),e===null&&(i=a),e}function Y(){var e,t,n,r,a=i,o=i,s;if(e=B(),e===null&&(e=X()),e!==null){for(t=[],s=i,n=R(),n===null?(n=null,i=s):(r=kt(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=R(),n===null?(n=null,i=s):(r=kt(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e){var t;$.multi_header||($.multi_header=[]);try{t=new Er($.uri,$.display_name,$.params),delete $.uri,delete $.display_name,delete $.params}catch{t=null}$.multi_header.push({possition:i,offset:e,parsed:t})}(a)),e===null&&(i=a),e}function X(){var e,t,n,r,a=i;return e=Ot(),e=e===null?``:e,e===null?(e=null,i=a):(t=ie(),t===null?(e=null,i=a):(n=pe(),n===null?(e=null,i=a):(r=re(),r===null?(e=null,i=a):e=[e,t,n,r]))),e}function Ot(){var e,t,n,r,a=i,o=i,s;if(e=j(),e!==null){for(t=[],s=i,n=C(),n===null?(n=null,i=s):(r=j(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=C(),n===null?(n=null,i=s):(r=j(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e===null&&(e=de()),e!==null&&(e=function(e,t){typeof t==`string`?$.display_name=t:$.display_name=t[1].reduce(function(e,t){return e+t[0]+t[1]},t[0])}(a,e)),e===null&&(i=a),e}function kt(){var e=At();return e===null&&(e=Z(),e===null&&(e=Q())),e}function At(){var e,n,r,o=i,s=i;return t.substr(i,1).toLowerCase()===`q`?(e=t.substr(i,1),i++):(e=null,a===0&&c(`"q"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=Mt(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.params||($.params={}),$.params.q=t}(o,e[2])),e===null&&(i=o),e}function Z(){var e,n,r,o=i,s=i;return t.substr(i,7).toLowerCase()===`expires`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"expires"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=jt(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.params||($.params={}),$.params.expires=t}(o,e[2])),e===null&&(i=o),e}function jt(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=function(e,t){return parseInt(t.join(``))}(n,e)),e===null&&(i=n),e}function Mt(){var e,n,r,o,s,l=i,d=i,f;return t.charCodeAt(i)===48?(e=`0`,i++):(e=null,a===0&&c(`"0"`)),e===null?(e=null,i=d):(f=i,t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null?(n=null,i=f):(r=u(),r=r===null?``:r,r===null?(n=null,i=f):(o=u(),o=o===null?``:o,o===null?(n=null,i=f):(s=u(),s=s===null?``:s,s===null?(n=null,i=f):n=[n,r,o,s]))),n=n===null?``:n,n===null?(e=null,i=d):e=[e,n]),e!==null&&(e=function(e){return parseFloat(t.substring(i,e))}(l)),e===null&&(i=l),e}function Q(){var e,t,n,r=i,a=i,o;return e=j(),e===null?(e=null,i=a):(o=i,t=F(),t===null?(t=null,i=o):(n=Nt(),n===null?(t=null,i=o):t=[t,n]),t=t===null?``:t,t===null?(e=null,i=a):e=[e,t]),e!==null&&(e=function(e,t,n){$.params||($.params={}),n=n===void 0?void 0:n[1],$.params[t.toLowerCase()]=n}(r,e[0],e[1])),e===null&&(i=r),e}function Nt(){var e=j();return e===null&&(e=Se(),e===null&&(e=ue())),e}function Pt(){var e,t,n,r,a=i,o;if(e=Ft(),e!==null){for(t=[],o=i,n=R(),n===null?(n=null,i=o):(r=It(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=R(),n===null?(n=null,i=o):(r=It(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Ft(){var e;return t.substr(i,6).toLowerCase()===`render`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"render"`)),e===null&&(t.substr(i,7).toLowerCase()===`session`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"session"`)),e===null&&(t.substr(i,4).toLowerCase()===`icon`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"icon"`)),e===null&&(t.substr(i,5).toLowerCase()===`alert`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"alert"`)),e===null&&(e=j())))),e}function It(){var e=Lt();return e===null&&(e=Q()),e}function Lt(){var e,n,r,o=i;return t.substr(i,8).toLowerCase()===`handling`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"handling"`)),e===null?(e=null,i=o):(n=F(),n===null?(e=null,i=o):(t.substr(i,8).toLowerCase()===`optional`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"optional"`)),r===null&&(t.substr(i,8).toLowerCase()===`required`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"required"`)),r===null&&(r=j())),r===null?(e=null,i=o):e=[e,n,r])),e}function Rt(){var e,t,n,r,a=i,o;if(e=j(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function zt(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=function(e,t){$=parseInt(t.join(``))}(n,e)),e===null&&(i=n),e}function Bt(){var e,n=i;return e=Vt(),e!==null&&(e=function(e){$=t.substring(i,e)}(n)),e===null&&(i=n),e}function Vt(){var e,t,n,r,a,o,s=i,c;if(e=Ht(),e!==null){if(t=te(),t!==null){if(n=qt(),n!==null){for(r=[],c=i,a=R(),a===null?(a=null,i=c):(o=Jt(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=R(),a===null?(a=null,i=c):(o=Jt(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function Ht(){var e=Ut();return e===null&&(e=Wt()),e}function Ut(){var e;return t.substr(i,4).toLowerCase()===`text`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"text"`)),e===null&&(t.substr(i,5).toLowerCase()===`image`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"image"`)),e===null&&(t.substr(i,5).toLowerCase()===`audio`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"audio"`)),e===null&&(t.substr(i,5).toLowerCase()===`video`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"video"`)),e===null&&(t.substr(i,11).toLowerCase()===`application`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"application"`)),e===null&&(e=Gt()))))),e}function Wt(){var e;return t.substr(i,7).toLowerCase()===`message`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"message"`)),e===null&&(t.substr(i,9).toLowerCase()===`multipart`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"multipart"`)),e===null&&(e=Gt())),e}function Gt(){var e=j();return e===null&&(e=Kt()),e}function Kt(){var e,n,r=i;return t.substr(i,2).toLowerCase()===`x-`?(e=t.substr(i,2),i+=2):(e=null,a===0&&c(`"x-"`)),e===null?(e=null,i=r):(n=j(),n===null?(e=null,i=r):e=[e,n]),e}function qt(){var e=Gt();return e===null&&(e=j()),e}function Jt(){var e,t,n,r=i;return e=j(),e===null?(e=null,i=r):(t=F(),t===null?(e=null,i=r):(n=Yt(),n===null?(e=null,i=r):e=[e,t,n])),e}function Yt(){var e=j();return e===null&&(e=ue()),e}function Xt(){var e,t,n,r=i;return e=Zt(),e===null?(e=null,i=r):(t=C(),t===null?(e=null,i=r):(n=W(),n===null?(e=null,i=r):e=[e,t,n])),e}function Zt(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=function(e,t){$.value=parseInt(t.join(``))}(n,e)),e===null&&(i=n),e}function Qt(){var e,t=i;return e=jt(),e!==null&&(e=function(e,t){$=t}(t,e)),e===null&&(i=t),e}function $t(){var e,t,n,r,a=i,o=i,s;if(e=en(),e!==null){for(t=[],s=i,n=R(),n===null?(n=null,i=s):(r=Q(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=R(),n===null?(n=null,i=s):(r=Q(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e,t){$.event=t.join(``).toLowerCase()}(a,e[0])),e===null&&(i=a),e}function en(){var e,n,r,o,s=i,l;if(e=M(),e!==null){for(n=[],l=i,t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(r=null,i=l):(o=M(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(r=null,i=l):(o=M(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function tn(){var e,t,n,r,a=i,o=i,s;if(e=B(),e===null&&(e=X()),e!==null){for(t=[],s=i,n=R(),n===null?(n=null,i=s):(r=nn(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=R(),n===null?(n=null,i=s):(r=nn(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e){var t=$.tag;try{$=new Er($.uri,$.display_name,$.params),t&&$.setParam(`tag`,t)}catch{$=-1}}(a)),e===null&&(i=a),e}function nn(){var e=rn();return e===null&&(e=Q()),e}function rn(){var e,n,r,o=i,s=i;return t.substr(i,3).toLowerCase()===`tag`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"tag"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=j(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.tag=t}(o,e[2])),e===null&&(i=o),e}function an(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=function(e,t){$=parseInt(t.join(``))}(n,e)),e===null&&(i=n),e}function on(){var e,t=i;return e=jt(),e!==null&&(e=function(e,t){$=t}(t,e)),e===null&&(i=t),e}function sn(){var e,t,n,r,a,o,s,c=i,l=i,u;for(e=[],t=Ot();t!==null;)e.push(t),t=Ot();if(e!==null){if(t=ie(),t!==null){if(n=pe(),n!==null){if(r=re(),r!==null){for(a=[],u=i,o=R(),o===null?(o=null,i=u):(s=Q(),s===null?(o=null,i=u):o=[o,s]);o!==null;)a.push(o),u=i,o=R(),o===null?(o=null,i=u):(s=Q(),s===null?(o=null,i=u):o=[o,s]);a===null?(e=null,i=l):e=[e,t,n,r,a]}else e=null,i=l}else e=null,i=l}else e=null,i=l}else e=null,i=l;return e!==null&&(e=function(e){try{$=new Er($.uri,$.display_name,$.params)}catch{$=-1}}(c)),e===null&&(i=c),e}function cn(){return ln()}function ln(){var e,n,r,o,s,l,u=i,d;if(t.substr(i,6).toLowerCase()===`digest`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"Digest"`)),e!==null){if(n=C(),n!==null){if(r=fn(),r!==null){for(o=[],d=i,s=L(),s===null?(s=null,i=d):(l=fn(),l===null?(s=null,i=d):s=[s,l]);s!==null;)o.push(s),d=i,s=L(),s===null?(s=null,i=d):(l=fn(),l===null?(s=null,i=d):s=[s,l]);o===null?(e=null,i=u):e=[e,n,r,o]}else e=null,i=u}else e=null,i=u}else e=null,i=u;return e===null&&(e=un()),e}function un(){var e,t,n,r,a,o,s=i,c;if(e=j(),e!==null){if(t=C(),t!==null){if(n=dn(),n!==null){for(r=[],c=i,a=L(),a===null?(a=null,i=c):(o=dn(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=L(),a===null?(a=null,i=c):(o=dn(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function dn(){var e,t,n,r=i;return e=j(),e===null?(e=null,i=r):(t=F(),t===null?(e=null,i=r):(n=j(),n===null&&(n=ue()),n===null?(e=null,i=r):e=[e,t,n])),e}function fn(){var e=pn();return e===null&&(e=hn(),e===null&&(e=_n(),e===null&&(e=yn(),e===null&&(e=bn(),e===null&&(e=xn(),e===null&&(e=Sn(),e===null&&(e=dn()))))))),e}function pn(){var e,n,r,o=i;return t.substr(i,5).toLowerCase()===`realm`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"realm"`)),e===null?(e=null,i=o):(n=F(),n===null?(e=null,i=o):(r=mn(),r===null?(e=null,i=o):e=[e,n,r])),e}function mn(){var e,t=i;return e=de(),e!==null&&(e=function(e,t){$.realm=t}(t,e)),e===null&&(i=t),e}function hn(){var e,n,r,o,s,l,u,d=i,f;if(t.substr(i,6).toLowerCase()===`domain`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"domain"`)),e!==null){if(n=F(),n!==null){if(r=oe(),r!==null){if(o=gn(),o!==null){if(s=[],f=i,u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;for(l===null?(l=null,i=f):(u=gn(),u===null?(l=null,i=f):l=[l,u]);l!==null;){if(s.push(l),f=i,u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;l===null?(l=null,i=f):(u=gn(),u===null?(l=null,i=f):l=[l,u])}s===null?(e=null,i=d):(l=se(),l===null?(e=null,i=d):e=[e,n,r,o,s,l])}else e=null,i=d}else e=null,i=d}else e=null,i=d}else e=null,i=d;return e}function gn(){var e=Ze();return e===null&&(e=et()),e}function _n(){var e,n,r,o=i;return t.substr(i,5).toLowerCase()===`nonce`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"nonce"`)),e===null?(e=null,i=o):(n=F(),n===null?(e=null,i=o):(r=vn(),r===null?(e=null,i=o):e=[e,n,r])),e}function vn(){var e,t=i;return e=de(),e!==null&&(e=function(e,t){$.nonce=t}(t,e)),e===null&&(i=t),e}function yn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`opaque`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"opaque"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=de(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.opaque=t}(o,e[2])),e===null&&(i=o),e}function bn(){var e,n,r,o=i,s;return t.substr(i,5).toLowerCase()===`stale`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"stale"`)),e===null?(e=null,i=o):(n=F(),n===null?(e=null,i=o):(s=i,t.substr(i,4).toLowerCase()===`true`?(r=t.substr(i,4),i+=4):(r=null,a===0&&c(`"true"`)),r!==null&&(r=function(e){$.stale=!0}(s)),r===null&&(i=s),r===null&&(s=i,t.substr(i,5).toLowerCase()===`false`?(r=t.substr(i,5),i+=5):(r=null,a===0&&c(`"false"`)),r!==null&&(r=function(e){$.stale=!1}(s)),r===null&&(i=s)),r===null?(e=null,i=o):e=[e,n,r])),e}function xn(){var e,n,r,o=i,s=i;return t.substr(i,9).toLowerCase()===`algorithm`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"algorithm"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(t.substr(i,3).toLowerCase()===`md5`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"MD5"`)),r===null&&(t.substr(i,8).toLowerCase()===`md5-sess`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"MD5-sess"`)),r===null&&(r=j())),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.algorithm=t.toUpperCase()}(o,e[2])),e===null&&(i=o),e}function Sn(){var e,n,r,o,s,l,u,d=i,f,p;if(t.substr(i,3).toLowerCase()===`qop`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"qop"`)),e!==null){if(n=F(),n!==null){if(r=oe(),r!==null){if(f=i,o=Cn(),o!==null){for(s=[],p=i,t.charCodeAt(i)===44?(l=`,`,i++):(l=null,a===0&&c(`","`)),l===null?(l=null,i=p):(u=Cn(),u===null?(l=null,i=p):l=[l,u]);l!==null;)s.push(l),p=i,t.charCodeAt(i)===44?(l=`,`,i++):(l=null,a===0&&c(`","`)),l===null?(l=null,i=p):(u=Cn(),u===null?(l=null,i=p):l=[l,u]);s===null?(o=null,i=f):o=[o,s]}else o=null,i=f;o===null?(e=null,i=d):(s=se(),s===null?(e=null,i=d):e=[e,n,r,o,s])}else e=null,i=d}else e=null,i=d}else e=null,i=d;return e}function Cn(){var e,n=i;return t.substr(i,8).toLowerCase()===`auth-int`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"auth-int"`)),e===null&&(t.substr(i,4).toLowerCase()===`auth`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"auth"`)),e===null&&(e=j())),e!==null&&(e=function(e,t){$.qop||($.qop=[]),$.qop.push(t.toLowerCase())}(n,e)),e===null&&(i=n),e}function wn(){var e,t,n,r,a=i,o;if(e=j(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Tn(){var e,t,n,r,a=i,o=i,s;if(e=En(),e!==null){for(t=[],s=i,n=L(),n===null?(n=null,i=s):(r=En(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=L(),n===null?(n=null,i=s):(r=En(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e){var t,n=$.multi_header.length;for(t=0;t<n;t++)if($.multi_header[t].parsed===null){$=null;break}$=$===null?-1:$.multi_header}(a)),e===null&&(i=a),e}function En(){var e,t,n,r,a=i,o=i,s;if(e=X(),e!==null){for(t=[],s=i,n=R(),n===null?(n=null,i=s):(r=Q(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=R(),n===null?(n=null,i=s):(r=Q(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e){var t;$.multi_header||($.multi_header=[]);try{t=new Er($.uri,$.display_name,$.params),delete $.uri,delete $.display_name,delete $.params}catch{t=null}$.multi_header.push({possition:i,offset:e,parsed:t})}(a)),e===null&&(i=a),e}function Dn(){var e,n,r,o,s=i,l=i,u;if(t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e===null&&(e=j()),e!==null){for(n=[],u=i,r=R(),r===null?(r=null,i=u):(o=On(),o===null?(r=null,i=u):r=[r,o]);r!==null;)n.push(r),u=i,r=R(),r===null?(r=null,i=u):(o=On(),o===null?(r=null,i=u):r=[r,o]);n===null?(e=null,i=l):e=[e,n]}else e=null,i=l;return e!==null&&(e=function(e,t){if($.protocol=t.toLowerCase(),$.params||($.params={}),$.params.text&&$.params.text[0]===`"`){var n=$.params.text;$.text=n.substring(1,n.length-1),delete $.params.text}}(s,e[0])),e===null&&(i=s),e}function On(){var e=kn();return e===null&&(e=Q()),e}function kn(){var e,n,r,o,s=i,l=i;if(t.substr(i,5).toLowerCase()===`cause`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"cause"`)),e!==null){if(n=F(),n!==null){if(o=u(),o!==null)for(r=[];o!==null;)r.push(o),o=u();else r=null;r===null?(e=null,i=l):e=[e,n,r]}else e=null,i=l}else e=null,i=l;return e!==null&&(e=function(e,t){$.cause=parseInt(t.join(``))}(s,e[2])),e===null&&(i=s),e}function An(){var e,t,n,r,a=i,o;if(e=j(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function jn(){var e,t,n,r,a=i,o;if(e=Mn(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=Mn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=Mn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Mn(){var e,t,n,r,a=i,o;if(e=X(),e!==null){for(t=[],o=i,n=R(),n===null?(n=null,i=o):(r=Q(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=R(),n===null?(n=null,i=o):(r=Q(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Nn(){var e,t,n,r,a=i,o;if(e=Pn(),e!==null){for(t=[],o=i,n=R(),n===null?(n=null,i=o):(r=Fn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=R(),n===null?(n=null,i=o):(r=Fn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Pn(){var e,n=i;return t.substr(i,6).toLowerCase()===`active`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"active"`)),e===null&&(t.substr(i,7).toLowerCase()===`pending`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"pending"`)),e===null&&(t.substr(i,10).toLowerCase()===`terminated`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"terminated"`)),e===null&&(e=j()))),e!==null&&(e=function(e){$.state=t.substring(i,e)}(n)),e===null&&(i=n),e}function Fn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`reason`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"reason"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=In(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){t!==void 0&&($.reason=t)}(o,e[2])),e===null&&(i=o),e===null&&(o=i,s=i,t.substr(i,7).toLowerCase()===`expires`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"expires"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=jt(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){t!==void 0&&($.expires=t)}(o,e[2])),e===null&&(i=o),e===null&&(o=i,s=i,t.substr(i,11).toLowerCase()===`retry_after`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"retry_after"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=jt(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){t!==void 0&&($.retry_after=t)}(o,e[2])),e===null&&(i=o),e===null&&(e=Q()))),e}function In(){var e;return t.substr(i,11).toLowerCase()===`deactivated`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"deactivated"`)),e===null&&(t.substr(i,9).toLowerCase()===`probation`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"probation"`)),e===null&&(t.substr(i,8).toLowerCase()===`rejected`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"rejected"`)),e===null&&(t.substr(i,7).toLowerCase()===`timeout`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"timeout"`)),e===null&&(t.substr(i,6).toLowerCase()===`giveup`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"giveup"`)),e===null&&(t.substr(i,10).toLowerCase()===`noresource`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"noresource"`)),e===null&&(t.substr(i,9).toLowerCase()===`invariant`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"invariant"`)),e===null&&(e=j()))))))),e}function Ln(){var e=E();return e=e===null?``:e,e}function Rn(){var e,t,n,r,a=i,o;if(e=j(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=j(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e=e===null?``:e,e}function zn(){var e,t,n,r,a=i,o=i,s;if(e=B(),e===null&&(e=X()),e!==null){for(t=[],s=i,n=R(),n===null?(n=null,i=s):(r=Bn(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=R(),n===null?(n=null,i=s):(r=Bn(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e){var t=$.tag;try{$=new Er($.uri,$.display_name,$.params),t&&$.setParam(`tag`,t)}catch{$=-1}}(a)),e===null&&(i=a),e}function Bn(){var e=rn();return e===null&&(e=Q()),e}function Vn(){var e,t,n,r,a=i,o;if(e=Hn(),e!==null){for(t=[],o=i,n=L(),n===null?(n=null,i=o):(r=Hn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=L(),n===null?(n=null,i=o):(r=Hn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Hn(){var e,t,n,r,a,o,s=i,c;if(e=Xn(),e!==null){if(t=C(),t!==null){if(n=$n(),n!==null){for(r=[],c=i,a=R(),a===null?(a=null,i=c):(o=Un(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=R(),a===null?(a=null,i=c):(o=Un(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function Un(){var e=Wn();return e===null&&(e=Gn(),e===null&&(e=Kn(),e===null&&(e=qn(),e===null&&(e=Jn(),e===null&&(e=Q()))))),e}function Wn(){var e,n,r,o=i,s=i;return t.substr(i,3).toLowerCase()===`ttl`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"ttl"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=nr(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.ttl=t}(o,e[2])),e===null&&(i=o),e}function Gn(){var e,n,r,o=i,s=i;return t.substr(i,5).toLowerCase()===`maddr`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"maddr"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=Se(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.maddr=t}(o,e[2])),e===null&&(i=o),e}function Kn(){var e,n,r,o=i,s=i;return t.substr(i,8).toLowerCase()===`received`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"received"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=Oe(),r===null&&(r=De()),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.received=t}(o,e[2])),e===null&&(i=o),e}function qn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`branch`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"branch"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=j(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.branch=t}(o,e[2])),e===null&&(i=o),e}function Jn(){var e,n,r,o=i,s;return t.substr(i,5).toLowerCase()===`rport`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"rport"`)),e===null?(e=null,i=o):(s=i,n=F(),n===null?(n=null,i=s):(r=Yn(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function Yn(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=function(e,t){$.rport=parseInt(t.join(``))}(o,e)),e===null&&(i=o),e}function Xn(){var e,t,n,r,a,o=i;return e=Zn(),e===null?(e=null,i=o):(t=te(),t===null?(e=null,i=o):(n=j(),n===null?(e=null,i=o):(r=te(),r===null?(e=null,i=o):(a=Qn(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function Zn(){var e,n=i;return t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e===null&&(e=j()),e!==null&&(e=function(e,t){$.protocol=t}(n,e)),e===null&&(i=n),e}function Qn(){var e,n=i;return t.substr(i,3).toLowerCase()===`udp`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"UDP"`)),e===null&&(t.substr(i,3).toLowerCase()===`tcp`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"TCP"`)),e===null&&(t.substr(i,3).toLowerCase()===`tls`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"TLS"`)),e===null&&(t.substr(i,4).toLowerCase()===`sctp`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"SCTP"`)),e===null&&(e=j())))),e!==null&&(e=function(e,t){$.transport=t}(n,e)),e===null&&(i=n),e}function $n(){var e,t,n,r=i,a;return e=er(),e===null?(e=null,i=r):(a=i,t=ae(),t===null?(t=null,i=a):(n=tr(),n===null?(t=null,i=a):t=[t,n]),t=t===null?``:t,t===null?(e=null,i=r):e=[e,t]),e}function er(){var e,n=i;return e=Oe(),e===null&&(e=Ee(),e===null&&(e=Ce())),e!==null&&(e=function(e){$.host=t.substring(i,e)}(n)),e===null&&(i=n),e}function tr(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=function(e,t){$.port=parseInt(t.join(``))}(o,e)),e===null&&(i=o),e}function nr(){var e,t,n,r=i,a=i;return e=u(),e===null?(e=null,i=a):(t=u(),t=t===null?``:t,t===null?(e=null,i=a):(n=u(),n=n===null?``:n,n===null?(e=null,i=a):e=[e,t,n])),e!==null&&(e=function(e,t){return parseInt(t.join(``))}(r,e)),e===null&&(i=r),e}function rr(){return ln()}function ir(){var e,t,n,r,a=i,o;if(e=ar(),e!==null){for(t=[],o=i,n=R(),n===null?(n=null,i=o):(r=or(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=R(),n===null?(n=null,i=o):(r=or(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function ar(){var e,t=i;return e=jt(),e!==null&&(e=function(e,t){$.expires=t}(t,e)),e===null&&(i=t),e}function or(){var e=sr();return e===null&&(e=Q()),e}function sr(){var e,n,r,o=i,s=i;return t.substr(i,9).toLowerCase()===`refresher`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"refresher"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(t.substr(i,3).toLowerCase()===`uac`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"uac"`)),r===null&&(t.substr(i,3).toLowerCase()===`uas`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"uas"`))),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.refresher=t.toLowerCase()}(o,e[2])),e===null&&(i=o),e}function cr(){var e,t,n,r=i;return e=j(),e===null?(e=null,i=r):(t=T(),t===null?(e=null,i=r):(n=lr(),n===null?(e=null,i=r):e=[e,t,n])),e}function lr(){var e=[],t=D();for(t===null&&(t=k(),t===null&&(t=C()));t!==null;)e.push(t),t=D(),t===null&&(t=k(),t===null&&(t=C()));return e}function ur(){for(var e=[],t=m();t!==null;)e.push(t),t=m();return e}function dr(){var e,n,r=i;return t.substr(i,5)===`uuid:`?(e=`uuid:`,i+=5):(e=null,a===0&&c(`"uuid:"`)),e===null?(e=null,i=r):(n=fr(),n===null?(e=null,i=r):e=[e,n]),e}function fr(){var e,n,r,o,s,l,u,d,f,p=i,m=i;return e=mr(),e===null?(e=null,i=m):(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null?(e=null,i=m):(r=pr(),r===null?(e=null,i=m):(t.charCodeAt(i)===45?(o=`-`,i++):(o=null,a===0&&c(`"-"`)),o===null?(e=null,i=m):(s=pr(),s===null?(e=null,i=m):(t.charCodeAt(i)===45?(l=`-`,i++):(l=null,a===0&&c(`"-"`)),l===null?(e=null,i=m):(u=pr(),u===null?(e=null,i=m):(t.charCodeAt(i)===45?(d=`-`,i++):(d=null,a===0&&c(`"-"`)),d===null?(e=null,i=m):(f=hr(),f===null?(e=null,i=m):e=[e,n,r,o,s,l,u,d,f])))))))),e!==null&&(e=function(e,n){$=t.substring(i+5,e)}(p,e[0])),e===null&&(i=p),e}function pr(){var e,t,n,r,a=i;return e=f(),e===null?(e=null,i=a):(t=f(),t===null?(e=null,i=a):(n=f(),n===null?(e=null,i=a):(r=f(),r===null?(e=null,i=a):e=[e,t,n,r]))),e}function mr(){var e,t,n=i;return e=pr(),e===null?(e=null,i=n):(t=pr(),t===null?(e=null,i=n):e=[e,t]),e}function hr(){var e,t,n,r=i;return e=pr(),e===null?(e=null,i=r):(t=pr(),t===null?(e=null,i=r):(n=pr(),n===null?(e=null,i=r):e=[e,t,n])),e}function gr(){var e,t,n,r,a=i,o=i,s;if(e=B(),e===null&&(e=X()),e!==null){for(t=[],s=i,n=R(),n===null?(n=null,i=s):(r=Q(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=R(),n===null?(n=null,i=s):(r=Q(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=function(e){try{$=new Er($.uri,$.display_name,$.params)}catch{$=-1}}(a)),e===null&&(i=a),e}function _r(){var e,t,n,r,a=i,o;if(e=vr(),e!==null){for(t=[],o=i,n=R(),n===null?(n=null,i=o):(r=yr(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=R(),n===null?(n=null,i=o):(r=yr(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function vr(){var e,n,r,o=i,s=i,l;return e=P(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(n=null,i=l):(r=P(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=function(e){$.call_id=t.substring(i,e)}(o)),e===null&&(i=o),e}function yr(){var e=br();return e===null&&(e=xr(),e===null&&(e=Sr(),e===null&&(e=Q()))),e}function br(){var e,n,r,o=i,s=i;return t.substr(i,6)===`to-tag`?(e=`to-tag`,i+=6):(e=null,a===0&&c(`"to-tag"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=j(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.to_tag=t}(o,e[2])),e===null&&(i=o),e}function xr(){var e,n,r,o=i,s=i;return t.substr(i,8)===`from-tag`?(e=`from-tag`,i+=8):(e=null,a===0&&c(`"from-tag"`)),e===null?(e=null,i=s):(n=F(),n===null?(e=null,i=s):(r=j(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=function(e,t){$.from_tag=t}(o,e[2])),e===null&&(i=o),e}function Sr(){var e,n=i;return t.substr(i,10)===`early-only`?(e=`early-only`,i+=10):(e=null,a===0&&c(`"early-only"`)),e!==null&&(e=function(e){$.early_only=!0}(n)),e===null&&(i=n),e}function Cr(e){e.sort();for(var t=null,n=[],r=0;r<e.length;r++)e[r]!==t&&(n.push(e[r]),t=e[r]);return n}function wr(){for(var e=1,n=1,r=!1,a=0;a<Math.max(i,o);a++){var s=t.charAt(a);s===`
4
4
  `?(r||e++,n=1,r=!1):s===`\r`||s===`\u2028`||s===`\u2029`?(e++,n=1,r=!0):(n++,r=!1)}return{line:e,column:n}}var Tr=wt(),Er=Ct(),$={};if(r[n]()===null||i!==t.length){var Dr=Math.max(i,o),Or=Dr<t.length?t.charAt(Dr):null,kr=wr();return new this.SyntaxError(Cr(s),Or,Dr,kr.line,kr.column),-1}return $},toSource:function(){return this._source}};return t.SyntaxError=function(t,n,r,i,a){function o(t,n){var r,i;switch(t.length){case 0:r=`end of input`;break;case 1:r=t[0];break;default:r=t.slice(0,t.length-1).join(`, `)+` or `+t[t.length-1]}return i=n?e(n):`end of input`,`Expected `+r+` but `+i+` found.`}this.name=`SyntaxError`,this.expected=t,this.found=n,this.message=o(t,n),this.offset=r,this.line=i,this.column=a},t.SyntaxError.prototype=Error.prototype,t}()})),wt=c(((e,t)=>{function n(e,t){var n;if(typeof Symbol>`u`||e[Symbol.iterator]==null){if(Array.isArray(e)||(n=r(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var i=0,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-39dch6xL.cjs"),t=require("../CCBarClient-B6WqgloY.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`q7X4p6MvK1z8Lb3A`,o=`W9e2T4mN0aQ7Ru6C`;async function s(t,n={}){let r=String(t??``).replace(/\s+/g,``);if(!r)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`解密的密文为空:坐席账号里没有 password/registerPassword`});let i=n.subtle??globalThis.crypto?.subtle;if(i===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行`});let s;try{let e=atob(r);s=new Uint8Array(new ArrayBuffer(e.length));for(let t=0;t<e.length;t+=1)s[t]=e.charCodeAt(t)}catch{throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义`})}let l=await i.importKey(`raw`,c(n.key??a),`AES-CBC`,!1,[`decrypt`]);try{let e=await i.decrypt({name:`AES-CBC`,iv:c(n.iv??o)},l,s);return new TextDecoder(`utf-8`).decode(e).trim()}catch(t){throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`SIP 密码解密失败(检查 key/iv 与该环境是否一致):${t instanceof Error?t.message:String(t)}`})}}function c(e){let t=new TextEncoder().encode(e),n=new Uint8Array(new ArrayBuffer(t.byteLength));return n.set(t),n}var l=`/openapi/token/v1`,u=`/seat/account/get`,d=`/seats/set-status`,f=`/api/fs/sip-ws`,p=7443,m=3478,h=600,g=600,_=180,v=60,y=5e3,b=2e4,x=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],S={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function C(t){let n=w(t.host),r=T(t.pathPrefix??l),i=`${n}${r}${E(t.accountPath??u)}`,a=`${n}${r}${E(t.statusPath??d)}`,o=E(t.sipWsPath??f),c={...t.aesKey?{key:t.aesKey}:{},...t.aesIv?{iv:t.aesIv}:{}},b=Math.max(0,t.refreshBufferSeconds??_),C=t.fetchImpl??globalThis.fetch,j,M,N=``;async function P(){if(t.getToken!==void 0)return t.getToken();if(t.tokenUrl!==void 0){let n=t.tokenMethod??`POST`,r={method:n,headers:{Accept:`application/json`,...t.tokenHeaders??{}},credentials:`include`};n===`POST`&&(r.headers={"Content-Type":`application/json`,...r.headers},r.body=JSON.stringify(t.tokenBody??{}));let i=await A(C,t.tokenUrl,r,`取 token`),a=await i.text();try{return JSON.parse(a)}catch{throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{status:i.status,cause:`取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0,120)}`})}}throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用`})}async function F(){if(j&&j.expiresAtMs-Date.now()>y)return j.token;let t;try{t=await P()}catch(t){throw t instanceof e.i?t:new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:t})}let n=k(t);if(!n.token)throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=O(n.expires,3600);return j={token:n.token,expiresAtMs:Date.now()+r*1e3},j.token}function I(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function L(e){let t=I(e?.wssUrl);return t?(N=t,t):N||F()}async function R(t){let n=t||await F(),r=await A(C,i,{method:`POST`,headers:{Authorization:n,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`},`取坐席账号`),a=await r.text(),o;try{o=JSON.parse(a)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:r.status,cause:`${i} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`})}let s=Number(o.code??NaN);if(!r.ok||s!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,s===50,{status:r.status,serverCode:Number.isFinite(s)?String(s):void 0,cause:o.message||`取坐席账号失败(HTTP ${r.status})`});if(!o.data)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号接口没有返回 data`});return M=o.data,M}let z=e=>s(e,c);function B(r,i){let a=Number(r.wssPort)||p,s=String(r.domain??``).trim(),c=String(t.sipWsUrl??``).trim(),l;if(c)l=new URL(c,n),l.protocol===`http:`&&(l.protocol=`ws:`),l.protocol===`https:`&&(l.protocol=`wss:`);else{if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定`});let t=a===443?``:`:${a}`;l=new URL(`wss://${s}${t}${o}`)}return(t.attachTokenToWss??!0)&&i&&l.searchParams.set(`token`,i),l.toString()}function V(e){let t=(Array.isArray(e.iceServers)?e.iceServers:[]).map(e=>{let t=(Array.isArray(e?.urls)?e.urls:typeof e?.urls==`string`?[e.urls]:[]).map(e=>String(e??``).trim()).filter(Boolean);if(t.length!==0)return{urls:t,...e?.username?{username:String(e.username)}:{},...e?.credential?{credential:String(e.credential)}:{}}}).filter(e=>e!==void 0);if(t.length>0)return t;let n=String(e.turnIp??``).trim();return n?[{urls:[`stun:${n}:${Number(e.turnPort)||m}`]}]:[]}async function H(){let r=await F(),i=await R(),a=String(i.username??i.account??``).trim();if(!a)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let o=String(i.registerPassword??i.password??``),s=o?await z(o):``;if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let c=O(i.expiresIn??i.expires_in,g),l=Math.max(0,Math.round((j.expiresAtMs-Date.now())/1e3)),u=Math.max(v,Math.min(l||c,c)-b),d=String(i.domain??``).trim()||D(n),f=B(i,r);return r&&(N=r),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+u,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${d}`,registrar:d,registerTicket:s,registerExpires:Number(t.registerExpires)>0?Number(t.registerExpires):h,ticketExpiresIn:u},transport:{wssUrl:f,ticket:``,ticketExpiresIn:u},iceServers:V(i),policy:{maxConcurrentCalls:Number(t.maxConcurrentCalls)>0?Number(t.maxConcurrentCalls):2,incomingEnabled:t.incomingEnabled??!0,mobileIncomingEnabled:t.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...t.capabilities??x]}}return{createSession:H,refreshSession:H,setAgentStatus:async({status:t,reason:n},r)=>{let i=await L(r),o=M??await R(i),s=String(o.username??o.account??``).trim();if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let c=S[t],l=await A(C,a,{method:`POST`,headers:{Authorization:i,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({extension:s,status:c.status,reason:n||c.reason})},`设置坐席状态`),u=await l.text(),d;try{d=JSON.parse(u)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:l.status,cause:`${a} 返回了非 JSON 响应(HTTP ${l.status})`})}let f=Number(d.code??NaN);if(!l.ok||f!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,f===50,{status:l.status,serverCode:Number.isFinite(f)?String(f):void 0,cause:d.message||`设置坐席状态失败(HTTP ${l.status})`})},invalidateToken:()=>{j=void 0,N=``},getSeatAccount:async()=>M??R()}}function w(t){let n=String(t??``).trim().replace(/\/+$/,``);if(!n)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 host`});return/^https?:\/\//i.test(n)?n:`https://${n}`}function T(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function E(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function D(e){try{return new URL(e).hostname}catch{return``}}function O(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),v),86400))}function k(e){if(typeof e==`string`)return{token:e.trim()};let t=e??{},n=typeof t.data==`object`&&t.data!==null?t.data:void 0;for(let e of[t,n]){if(e===void 0)continue;let t=e.token??e.accessToken;if(typeof t==`string`&&t.trim()){let n=Number(e.expires??e.expiresIn??e.expires_at);return{token:t.trim(),...Number.isFinite(n)&&n>0?{expires:n}:{}}}}return{token:``}}async function A(t,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),b);try{return await t(n,{...r,signal:a.signal})}catch(t){let r=a.signal.aborted;throw new e.i(r?`NETWORK_TIMEOUT`:`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{cause:r?`${i}超时(${b/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${t instanceof Error?t.message:String(t)})`})}finally{clearTimeout(o)}}var j=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=C,exports.decryptSipPassword=s,exports.legacyVersion=j;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-39dch6xL.cjs"),t=require("../CCBarClient-BJryiSYT.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`q7X4p6MvK1z8Lb3A`,o=`W9e2T4mN0aQ7Ru6C`;async function s(t,n={}){let r=String(t??``).replace(/\s+/g,``);if(!r)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`解密的密文为空:坐席账号里没有 password/registerPassword`});let i=n.subtle??globalThis.crypto?.subtle;if(i===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行`});let s;try{let e=atob(r);s=new Uint8Array(new ArrayBuffer(e.length));for(let t=0;t<e.length;t+=1)s[t]=e.charCodeAt(t)}catch{throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义`})}let l=await i.importKey(`raw`,c(n.key??a),`AES-CBC`,!1,[`decrypt`]);try{let e=await i.decrypt({name:`AES-CBC`,iv:c(n.iv??o)},l,s);return new TextDecoder(`utf-8`).decode(e).trim()}catch(t){throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`SIP 密码解密失败(检查 key/iv 与该环境是否一致):${t instanceof Error?t.message:String(t)}`})}}function c(e){let t=new TextEncoder().encode(e),n=new Uint8Array(new ArrayBuffer(t.byteLength));return n.set(t),n}var l=`/openapi/token/v1`,u=`/seat/account/get`,d=`/seats/set-status`,f=`/api/fs/sip-ws`,p=7443,m=3478,h=600,g=600,_=180,v=60,y=5e3,b=2e4,x=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],S={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function C(t){let n=w(t.host),r=T(t.pathPrefix??l),i=`${n}${r}${E(t.accountPath??u)}`,a=`${n}${r}${E(t.statusPath??d)}`,o=E(t.sipWsPath??f),c={...t.aesKey?{key:t.aesKey}:{},...t.aesIv?{iv:t.aesIv}:{}},b=Math.max(0,t.refreshBufferSeconds??_),C=t.fetchImpl??globalThis.fetch,j,M,N=``;async function P(){if(t.getToken!==void 0)return t.getToken();if(t.tokenUrl!==void 0){let n=t.tokenMethod??`POST`,r={method:n,headers:{Accept:`application/json`,...t.tokenHeaders??{}},credentials:`include`};n===`POST`&&(r.headers={"Content-Type":`application/json`,...r.headers},r.body=JSON.stringify(t.tokenBody??{}));let i=await A(C,t.tokenUrl,r,`取 token`),a=await i.text();try{return JSON.parse(a)}catch{throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{status:i.status,cause:`取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0,120)}`})}}throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用`})}async function F(){if(j&&j.expiresAtMs-Date.now()>y)return j.token;let t;try{t=await P()}catch(t){throw t instanceof e.i?t:new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:t})}let n=k(t);if(!n.token)throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=O(n.expires,3600);return j={token:n.token,expiresAtMs:Date.now()+r*1e3},j.token}function I(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function L(e){let t=I(e?.wssUrl);return t?(N=t,t):N||F()}async function R(t){let n=t||await F(),r=await A(C,i,{method:`POST`,headers:{Authorization:n,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`},`取坐席账号`),a=await r.text(),o;try{o=JSON.parse(a)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:r.status,cause:`${i} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`})}let s=Number(o.code??NaN);if(!r.ok||s!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,s===50,{status:r.status,serverCode:Number.isFinite(s)?String(s):void 0,cause:o.message||`取坐席账号失败(HTTP ${r.status})`});if(!o.data)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号接口没有返回 data`});return M=o.data,M}let z=e=>s(e,c);function B(r,i){let a=Number(r.wssPort)||p,s=String(r.domain??``).trim(),c=String(t.sipWsUrl??``).trim(),l;if(c)l=new URL(c,n),l.protocol===`http:`&&(l.protocol=`ws:`),l.protocol===`https:`&&(l.protocol=`wss:`);else{if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定`});let t=a===443?``:`:${a}`;l=new URL(`wss://${s}${t}${o}`)}return(t.attachTokenToWss??!0)&&i&&l.searchParams.set(`token`,i),l.toString()}function V(e){let t=(Array.isArray(e.iceServers)?e.iceServers:[]).map(e=>{let t=(Array.isArray(e?.urls)?e.urls:typeof e?.urls==`string`?[e.urls]:[]).map(e=>String(e??``).trim()).filter(Boolean);if(t.length!==0)return{urls:t,...e?.username?{username:String(e.username)}:{},...e?.credential?{credential:String(e.credential)}:{}}}).filter(e=>e!==void 0);if(t.length>0)return t;let n=String(e.turnIp??``).trim();return n?[{urls:[`stun:${n}:${Number(e.turnPort)||m}`]}]:[]}async function H(){let r=await F(),i=await R(),a=String(i.username??i.account??``).trim();if(!a)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let o=String(i.registerPassword??i.password??``),s=o?await z(o):``;if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let c=O(i.expiresIn??i.expires_in,g),l=Math.max(0,Math.round((j.expiresAtMs-Date.now())/1e3)),u=Math.max(v,Math.min(l||c,c)-b),d=String(i.domain??``).trim()||D(n),f=B(i,r);return r&&(N=r),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+u,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${d}`,registrar:d,registerTicket:s,registerExpires:Number(t.registerExpires)>0?Number(t.registerExpires):h,ticketExpiresIn:u},transport:{wssUrl:f,ticket:``,ticketExpiresIn:u},iceServers:V(i),policy:{maxConcurrentCalls:Number(t.maxConcurrentCalls)>0?Number(t.maxConcurrentCalls):2,incomingEnabled:t.incomingEnabled??!0,mobileIncomingEnabled:t.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...t.capabilities??x]}}return{createSession:H,refreshSession:H,setAgentStatus:async({status:t,reason:n},r)=>{let i=await L(r),o=M??await R(i),s=String(o.username??o.account??``).trim();if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let c=S[t],l=await A(C,a,{method:`POST`,headers:{Authorization:i,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({extension:s,status:c.status,reason:n||c.reason})},`设置坐席状态`),u=await l.text(),d;try{d=JSON.parse(u)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:l.status,cause:`${a} 返回了非 JSON 响应(HTTP ${l.status})`})}let f=Number(d.code??NaN);if(!l.ok||f!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,f===50,{status:l.status,serverCode:Number.isFinite(f)?String(f):void 0,cause:d.message||`设置坐席状态失败(HTTP ${l.status})`})},invalidateToken:()=>{j=void 0,N=``},getSeatAccount:async()=>M??R()}}function w(t){let n=String(t??``).trim().replace(/\/+$/,``);if(!n)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 host`});return/^https?:\/\//i.test(n)?n:`https://${n}`}function T(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function E(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function D(e){try{return new URL(e).hostname}catch{return``}}function O(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),v),86400))}function k(e){if(typeof e==`string`)return{token:e.trim()};let t=e??{},n=typeof t.data==`object`&&t.data!==null?t.data:void 0;for(let e of[t,n]){if(e===void 0)continue;let t=e.token??e.accessToken;if(typeof t==`string`&&t.trim()){let n=Number(e.expires??e.expiresIn??e.expires_at);return{token:t.trim(),...Number.isFinite(n)&&n>0?{expires:n}:{}}}}return{token:``}}async function A(t,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),b);try{return await t(n,{...r,signal:a.signal})}catch(t){let r=a.signal.aborted;throw new e.i(r?`NETWORK_TIMEOUT`:`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{cause:r?`${i}超时(${b/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${t instanceof Error?t.message:String(t)})`})}finally{clearTimeout(o)}}var j=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=C,exports.decryptSipPassword=s,exports.legacyVersion=j;
@@ -1,5 +1,5 @@
1
1
  import { i as e } from "../SharedWorkerProtocol-DKVQ5-po.js";
2
- import { t } from "../CCBarClient-CfHT0tl2.js";
2
+ import { t } from "../CCBarClient-CbkMKzEw.js";
3
3
  //#region src/legacy/CCBarSDK.ts
4
4
  var n = class extends Error {
5
5
  code = "LEGACY_METHOD_DEPRECATED";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "3.1.9";
1
+ export declare const SDK_VERSION = "3.8.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@16x/webphone-sdk",
3
- "version": "3.1.9",
3
+ "version": "3.8.1",
4
4
  "homepage": "https://www.npmjs.com/package/@16x/webphone-sdk",
5
5
  "private": false,
6
6
  "license": "UNLICENSED",