@16x/webphone-sdk 3.0.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +2 -0
  3. package/README.md +113 -0
  4. package/dist/CCBarClient-BdbynNBi.js +2515 -0
  5. package/dist/CCBarClient-DKWdvgf5.cjs +1 -0
  6. package/dist/CCBarError-CIqJE8zK.cjs +1 -0
  7. package/dist/CCBarError-DSbPw2dA.js +14 -0
  8. package/dist/Diagnostics-BYVvmxil.cjs +1 -0
  9. package/dist/Diagnostics-Cw2HVrCD.js +123 -0
  10. package/dist/JsSipAdapter-GHzVSCDh.js +304 -0
  11. package/dist/JsSipAdapter-jtGdoXrm.cjs +1 -0
  12. package/dist/SharedWorkerProtocol-BqUafs8d.js +73 -0
  13. package/dist/SharedWorkerProtocol-CYN0AprP.cjs +1 -0
  14. package/dist/api/WebPhoneApi.d.ts +28 -0
  15. package/dist/api/contracts.d.ts +94 -0
  16. package/dist/auth/TokenManager.d.ts +22 -0
  17. package/dist/core/CCBarCall.d.ts +94 -0
  18. package/dist/core/CCBarClient.d.ts +113 -0
  19. package/dist/core/CallManager.d.ts +93 -0
  20. package/dist/core/callId.d.ts +1 -0
  21. package/dist/core/mediaBridge.d.ts +17 -0
  22. package/dist/createJsSipFactory-2X4FBIU2.cjs +75 -0
  23. package/dist/createJsSipFactory-yttVU3d6.js +9662 -0
  24. package/dist/diagnostics/Diagnostics.d.ts +74 -0
  25. package/dist/diagnostics/RingBuffer.d.ts +7 -0
  26. package/dist/diagnostics/index.cjs +1 -0
  27. package/dist/diagnostics/index.d.ts +4 -0
  28. package/dist/diagnostics/index.js +6 -0
  29. package/dist/diagnostics/redact.d.ts +5 -0
  30. package/dist/errors/CCBarError.d.ts +15 -0
  31. package/dist/events/TypedEventBus.d.ts +9 -0
  32. package/dist/index.cjs +1 -0
  33. package/dist/index.d.ts +21 -0
  34. package/dist/index.js +152 -0
  35. package/dist/index.umd.js +75 -0
  36. package/dist/legacy/CCBarSDK.d.ts +29 -0
  37. package/dist/legacy/index.cjs +1 -0
  38. package/dist/legacy/index.d.ts +8 -0
  39. package/dist/legacy/index.js +108 -0
  40. package/dist/redact-Bq26pObO.cjs +1 -0
  41. package/dist/redact-DB3CMbsK.js +21 -0
  42. package/dist/shared/SharedCallTransport.d.ts +55 -0
  43. package/dist/shared/SharedWorkerClient.d.ts +20 -0
  44. package/dist/shared/SharedWorkerEntry.d.ts +3 -0
  45. package/dist/shared/SharedWorkerFactory.d.ts +29 -0
  46. package/dist/shared/SharedWorkerProtocol.d.ts +47 -0
  47. package/dist/shared/SharedWorkerRuntime.d.ts +35 -0
  48. package/dist/shared-worker.cjs +1 -0
  49. package/dist/shared-worker.d.ts +1 -0
  50. package/dist/shared-worker.js +185 -0
  51. package/dist/state/callStateMachine.d.ts +9 -0
  52. package/dist/styles.css +7 -0
  53. package/dist/types.d.ts +134 -0
  54. package/dist/ui/XCallCCBarElement.d.ts +23 -0
  55. package/dist/ui/controllers/mobileLifecycle.d.ts +18 -0
  56. package/dist/ui/controllers/phoneActions.d.ts +27 -0
  57. package/dist/ui/i18n/en-US.d.ts +2 -0
  58. package/dist/ui/i18n/index.d.ts +6 -0
  59. package/dist/ui/i18n/types.d.ts +53 -0
  60. package/dist/ui/i18n/zh-CN.d.ts +2 -0
  61. package/dist/ui/icons/index.d.ts +5 -0
  62. package/dist/ui/index.cjs +1 -0
  63. package/dist/ui/index.d.ts +3 -0
  64. package/dist/ui/index.js +1044 -0
  65. package/dist/ui/state/toPhoneViewModel.d.ts +54 -0
  66. package/dist/ui/views/dom.d.ts +11 -0
  67. package/dist/ui/views/messages.d.ts +5 -0
  68. package/dist/ui/views/renderActiveCall.d.ts +8 -0
  69. package/dist/ui/views/renderDesktop.d.ts +24 -0
  70. package/dist/ui/views/renderDialpad.d.ts +4 -0
  71. package/dist/ui/views/renderError.d.ts +6 -0
  72. package/dist/ui/views/renderIncoming.d.ts +8 -0
  73. package/dist/ui/views/renderMobile.d.ts +15 -0
  74. package/dist/ui/views/renderSetup.d.ts +6 -0
  75. package/package.json +107 -0
@@ -0,0 +1 @@
1
+ const e=require("./CCBarError-CIqJE8zK.cjs"),t=require("./Diagnostics-BYVvmxil.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.t{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},s=a,c=60,l=class{tokenProvider;cachedToken;cachedRequestKey=``;refreshing;generation=0;constructor(e){this.tokenProvider=e}getValidToken(e){let t=e?.extension?.trim()??``;if(this.cachedToken&&this.cachedRequestKey===t&&!this.needsRefresh(this.cachedToken))return Promise.resolve(this.cachedToken.accessToken);if(!this.refreshing){let n=this.generation,r=this.refresh(e,t,n);this.refreshing=r,r.then(()=>this.clearRefresh(r),()=>this.clearRefresh(r))}return this.refreshing}invalidate(){this.generation+=1,this.cachedToken=void 0,this.cachedRequestKey=``,this.refreshing=void 0}needsRefresh(e){return e.expiresAt!==void 0&&e.expiresAt<=Math.floor(Date.now()/1e3)+c}async refresh(e,t,n){let r=await this.tokenProvider(e),i=typeof r==`string`?{accessToken:r}:r;return n===this.generation&&(this.cachedToken=i,this.cachedRequestKey=t),i.accessToken}clearRefresh(e){this.refreshing===e&&(this.refreshing=void 0)}},u={ORIGIN_NOT_ALLOWED:{code:`CONFIG_ORIGIN_NOT_ALLOWED`,category:`configuration`,retryable:!1},CAPABILITY_DENIED:{code:`CAPABILITY_NOT_SUPPORTED`,category:`capability`,retryable:!1},TOKEN_INVALID:{code:`AUTH_TOKEN_UNAVAILABLE`,category:`auth`,retryable:!1},TOKEN_EXPIRED:{code:`AUTH_TOKEN_EXPIRED`,category:`auth`,retryable:!1},INVALID_ARGUMENT:{code:`CONFIG_INVALID`,category:`configuration`,retryable:!1},INVALID_EXTENSION:{code:`CONFIG_INVALID`,category:`configuration`,retryable:!1},SEAT_NOT_FOUND:{code:`AUTH_PERMISSION_DENIED`,category:`auth`,retryable:!1},SESSION_NOT_FOUND:{code:`CALL_NOT_CONNECTED`,category:`call`,retryable:!1},SEAT_IN_USE:{code:`CALL_ALREADY_EXISTS`,category:`call`,retryable:!1},SESSION_CONFLICT:{code:`CALL_ALREADY_EXISTS`,category:`call`,retryable:!1},SEAT_NOT_ASSIGNED:{code:`AUTH_PERMISSION_DENIED`,category:`auth`,retryable:!1},QUEUE_NOT_ASSIGNED:{code:`CAPABILITY_NOT_SUPPORTED`,category:`capability`,retryable:!1},RATE_LIMITED:{code:`NETWORK_OFFLINE`,category:`network`,retryable:!0},SIP_GATEWAY_UNAVAILABLE:{code:`SIP_WS_UNAVAILABLE`,category:`registration`,retryable:!0},SERVICE_UNAVAILABLE:{code:`NETWORK_OFFLINE`,category:`network`,retryable:!0},INTERNAL_ERROR:{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!0}},d=class{tokenManager;fetcher;baseUrl;timeoutMs;constructor(e){this.tokenManager=new l(e.tokenProvider),this.fetcher=e.fetcher??fetch.bind(globalThis),this.baseUrl=e.baseUrl.replace(/\/$/,``),this.timeoutMs=e.timeoutMs??1e4}invalidateToken(){this.tokenManager.invalidate()}createSession(e){return this.request(`POST`,`/webphone/v1/sessions`,e).then(e=>this.requireData(e))}refreshSession(e,t={refresh:[`sip_register_ticket`,`wss_ticket`,`turn_credentials`]}){return this.request(`POST`,`/webphone/v1/sessions/${encodeURIComponent(e)}/refresh`,t).then(e=>this.requireData(e))}deleteSession(e){return this.request(`DELETE`,`/webphone/v1/sessions/${encodeURIComponent(e)}`).then(()=>void 0)}setAgentStatus(e){return this.request(`PUT`,`/webphone/v1/agents/me/status`,e).then(()=>void 0)}getCapabilities(){return this.request(`GET`,`/webphone/v1/capabilities`).then(e=>this.requireData(e))}async request(t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs);try{let e=await this.tokenManager.getValidToken(),a=await this.fetcher(`${this.baseUrl}${n}`,{method:t,headers:{Authorization:`Bearer ${e}`,...r===void 0?{}:{"Content-Type":`application/json`}},...r===void 0?{}:{body:JSON.stringify(r)},signal:i.signal}),o=await this.parseResponse(a);if(!a.ok||o.code!==`OK`)throw this.toCCBarError(a.status,o);return{data:o.data,requestId:o.requestId}}catch(t){throw t instanceof e.t?t:t instanceof DOMException&&t.name===`AbortError`?new e.t(`NETWORK_TIMEOUT`,`network`,!0,{cause:t}):new e.t(`NETWORK_OFFLINE`,`network`,!0,{cause:t})}finally{clearTimeout(a)}}requireData(t){if(t.data===void 0||t.data===null)throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:t.requestId});return t.data}async parseResponse(t){try{return await t.json()}catch(n){throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,t.status>=500,{cause:n})}}toCCBarError(t,n){let r=u[n.code??``]??this.mapStatus(t);return new e.t(r.code,r.category,r.retryable,{requestId:n.requestId})}mapStatus(e){return e===401?{code:`AUTH_TOKEN_EXPIRED`,category:`auth`,retryable:!1}:e===403?{code:`AUTH_PERMISSION_DENIED`,category:`auth`,retryable:!1}:e>=500?{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!0}:{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!1}}},f=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`],p=3e4,m=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{f.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.t(`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){if(this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.platform===`mobile-web`)throw this.capabilityError();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)}}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`),!g(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),h(this.currentState))throw this.operationError();try{this.options.session.terminate(),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,!h(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||h(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`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,h(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{h(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),p);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||h(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.t&&t.callId===this.id?t:this.operationError(t);try{this.options.onError?.(n)}catch{}}finishFailedIncomingOperation(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.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(t){return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}};function h(e){return e===`ended`||e===`failed`}function g(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var _=0;function v(){return _+=1,`call_${Date.now().toString(36)}_${_.toString(36)}`}var y=class{events=new b;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.t(`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.t(`CALL_INVALID_DESTINATION`,`call`,!1);this.requireCapability(n,`outbound`);let a=this.callLimit(n);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(i)||[...this.calls.values()].some(e=>e.destination===i))throw new e.t(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(i);let o=v(),s;try{s=await this.holdActiveCallForNewCall(),this.assertGeneration(r,o);let e;try{e=this.options.sip.dial(i,this.dialOptions(o,n,t.type))}catch(e){throw this.dialError(e,o)}this.assertGeneration(r,o);let a;try{a=new m({id:o,destination:i,platform:this.options.platform,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){throw this.dialError(e,o)}if(!this.isCurrentGeneration(r))throw a.dispose(),this.callOperationError(a.id);this.calls.set(a.id,a),this.callSessions.set(a.id,e),this.options.onCallCreated?.(a.id,e);try{a.beginOutbound()}catch(e){throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.dialError(e,a.id)}if(!this.isCurrentGeneration(r))throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.callOperationError(a.id);return this.events.emit(`call.created`,{callId:a.id,state:a.state}),a}catch(e){if(this.isCurrentGeneration(r)&&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(i)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`)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)}}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})).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:x(n)}):this.events.emit(`call.failed`,{callId:e.id,error:S(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=v();if(this.options.platform===`mobile-web`){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:this.capabilityError(n)});return}let 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.t(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:n})});return}let a;try{a=new m({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(`inbound`),t.delete(`hold`),t.delete(`blind_transfer`)),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),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),r}assertNotDisposed(){if(this.disposed)throw new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(t,n){return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}capabilityError(t){return new e.t(`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){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`],...n===void 0?{}:{type:n}}}dialError(t,n){return t instanceof e.t?new e.t(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t}):new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}},b=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 x(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function S(t,n){if(t instanceof e.t)return new e.t(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.t)return new e.t(r.code,r.category,r.retryable,{requestId:r.requestId,callId:n,cause:r.cause??r});if(r instanceof Error)return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:r})}return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}var C=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??w(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw E(e)}T(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 te(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.t(`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.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await r.setSinkId(t)}catch(e){throw ne(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 e.t(`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 w(){return globalThis.navigator?.mediaDevices}function T(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function ee(t){let n=D(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function E(t){let n=D(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function te(t){let n=D(t);return n===`NotFoundError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function ne(t){let n=D(t);return n===`NotFoundError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function D(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}var O=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=k){this.createAudioElement=e}async bind(t,n){let r=this.bindings.get(t);if(r?.stream===n)return;let i=A(t,n),a;try{a=this.createAudioElement()}catch(n){throw j(i,this.trackOwners),new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t,cause:n})}let o=this.audioOwners.get(a);if(o!==void 0&&o!==t)throw j(i,this.trackOwners),new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});try{a.autoplay=!0,a.playsInline=!0}catch(n){throw j(i,this.trackOwners),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}try{a.srcObject=n}catch(n){throw j(i,this.trackOwners),new e.t(`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.t(`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.t(`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.t(`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),N(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 k(){if(typeof document>`u`)throw new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function A(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 M(n),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:r??i})}}}function j(e,t){e.forEach(e=>{(t.get(e)??0)===0&&N(e)})}function M(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(N)}catch{}}function N(e){try{e.stop()}catch{}}var P=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 C(t),this.remoteAudio=new O(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??V}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=F(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,()=>L(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=I(e.senderResource.sender);t?.kind===`audio`&&a.add(t);return}let t=I(e.senderResource.sender);t?.kind===`audio`&&i.add(t)}),i.forEach(e=>{a.has(e)||B(e)}),o.length>0)throw t.localTracks.clear(),t.pendingTracks.clear(),a.forEach(e=>t.localTracks.add(e)),new e.t(`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=>I(e.sender)).find(e=>e?.kind===`audio`);throw t.localTracks.clear(),t.pendingTracks.clear(),i!=null&&t.localTracks.add(i),new e.t(`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=I(i.sender),o=r.generation,s=await this.deviceManager.openInputStream(t),c;try{c=s.getTracks()}catch(t){throw R(s),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let l;try{l=s.getAudioTracks()}catch(t){throw z(c),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let u=l[0];if(u===void 0)throw z(c),new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:n.callId});if(!this.canCommitInputSwitch(n,r,i,a,o))throw z(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),z(c)),new e.t(`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,()=>I(i.sender)===u?L(i.sender):Promise.resolve()),c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),z(c)}catch(t){throw new e.t(`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),B(a)),c.forEach(e=>{e!==u&&B(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.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}r.forEach(r=>{let i=I(r),a;try{a=n?.(r)??r.senderKind??r.kind}catch(n){throw new e.t(`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&&(I(e.sender)?.kind===`audio`||I(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 I(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||I(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.t(`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.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}callOperationError(t){return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t})}assertNotDisposed(){if(this.disposed||this.disposing)throw new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function F(e){return`peerConnection`in e}function I(e){try{return e.track}catch{return null}}function L(e){try{return e.replaceTrack(null)}catch(e){return Promise.reject(e)}}function R(e){try{z(e.getTracks())}catch{}}function z(e){e.forEach(B)}function B(e){try{e.stop()}catch{}}function V(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}function H(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 P({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||!U(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.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function p(e,t){if(!U(t)||typeof t.getMediaRegistration!=`function`)return;let n=t.getMediaRegistration();if(W(n)&&r.get(e)?.peerConnection!==n.peerConnection){r.set(e,n);try{d.registerCallMedia(e,n)}catch{r.delete(e)}}}}function U(e){return typeof e==`object`&&!!e}function W(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var G=1e3,K=3e4;function q(e,t=Math.random){let n=Math.min(K,G*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var J=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=q(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)}},Y=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;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;tokenRequest={};constructor(e){this.options=e;let n=e=>this.options.tokenProvider({...e,...this.tokenRequest});this.api=e.api===void 0?new d({baseUrl:e.baseUrl??``,tokenProvider:n}):re(e.api),this.suppliedSip=e.sip===void 0?void 0:ie(e.sip),this.mediaBridge=H(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new J({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!==``)})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=Z(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),this.assertNotDisposed(),this.initialized=!0}connect(e){this.assertNotDisposed();let t=e?.extension?.trim();if(this.tokenRequest=t===void 0||t===``?{}:{extension:t},this.api.invalidateToken?.(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();let n=this.lifecycleGeneration,r=this.performConnect(n).finally(()=>{this.connectOperation===r&&(this.connectOperation=void 0)});return this.connectOperation=r,r}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.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.t(`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.t(`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.t(`CALL_NOT_CONNECTED`,`call`,!1);return n.setActiveCall(t)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){this.assertNotDisposed(),await this.api.setAgentStatus({status:e,reason:``}),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 t,n,r;try{await this.initialize(),this.assertGeneration(e);let i=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),t=await this.api.createSession({sdkVersion:`0.1.0`,platform:i===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??ce(i)]}),this.ownedSessionIds.add(t.sessionId),this.assertGeneration(e),n=await this.getSip(),this.assertGeneration(e),this.session=t;let a=this.callManager??this.createCallManager(n,t,i);this.callManager===void 0&&(r=a),a.updateSession(t),this.callManager=a,this.attachSipListener(n),this.attachNetworkListeners(),await n.connect(t),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(t)}catch(i){if(await this.rollbackConnect(t,n,r),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw i;let a=Q(i,`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.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.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new y({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){ae(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.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:Q(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed&&(this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start())}catch{this.disposed||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)});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=Q(t,`NETWORK_OFFLINE`,`network`,!0);this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}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.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-2X4FBIU2.cjs")),Promise.resolve().then(()=>require("./JsSipAdapter-jtGdoXrm.cjs"))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl),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:Q(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:X(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}}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)}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}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.t(`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.t(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(t){if(this.disposed)throw this.disposedError();if(t!==this.lifecycleGeneration)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function X(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 Z(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function re(t){if(typeof t!=`object`||!t)throw new e.t(`CONFIG_INVALID`,`configuration`,!1);return t}function ie(t){if(typeof t!=`object`||!t)throw new e.t(`CONFIG_INVALID`,`configuration`,!1);return t}function Q(t,n,r,i,a){return t instanceof e.t?new e.t(t.code,t.category,t.retryable,{requestId:t.requestId,callId:a??t.callId,cause:t.cause??t}):new e.t(n,r,i,{callId:a,cause:t})}function ae(t){return t instanceof e.t&&t.code===`SDK_ALREADY_DISPOSED`}function $(t){return t instanceof e.t&&(t.code===`SDK_ALREADY_DISPOSED`||t.code===`CALL_NOT_CONNECTED`)}var oe=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],se=[`outbound`,`mute`,`dtmf`];function ce(e){return e===`mobile-web`?se:oe}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),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 d}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return r}});
@@ -0,0 +1 @@
1
+ var e=class extends Error{code;category;retryable;requestId;callId;cause;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}};Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
@@ -0,0 +1,14 @@
1
+ //#region src/errors/CCBarError.ts
2
+ var e = class extends Error {
3
+ code;
4
+ category;
5
+ retryable;
6
+ requestId;
7
+ callId;
8
+ cause;
9
+ constructor(e, t, n, r = {}) {
10
+ 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;
11
+ }
12
+ };
13
+ //#endregion
14
+ export { e as t };
@@ -0,0 +1 @@
1
+ const e=require("./redact-Bq26pObO.cjs");var t=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]}},n=`@16x/webphone-sdk`,r=`0.1.0`,i=200,a=class{dependencies;logs=new t(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(t={}){let i=t.includeRecentLogs!==!1,a=t.includeDeviceNames===!0,u=t.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:n,version:r},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 t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
@@ -0,0 +1,123 @@
1
+ import { n as e, t } from "./redact-DB3CMbsK.js";
2
+ //#region src/diagnostics/RingBuffer.ts
3
+ var n = class {
4
+ capacity;
5
+ entries = [];
6
+ constructor(e) {
7
+ if (this.capacity = e, !Number.isInteger(e) || e <= 0) throw RangeError("RingBuffer capacity must be a positive integer");
8
+ }
9
+ push(e) {
10
+ this.entries.length === this.capacity && this.entries.shift(), this.entries.push(e);
11
+ }
12
+ toArray() {
13
+ return [...this.entries];
14
+ }
15
+ }, r = "@16x/webphone-sdk", i = "0.1.0", a = 200, o = class {
16
+ dependencies;
17
+ logs = new n(a);
18
+ now;
19
+ constructor(e) {
20
+ this.dependencies = e, this.now = e.now ?? (() => /* @__PURE__ */ new Date());
21
+ }
22
+ log(n, r, i) {
23
+ this.logs.push({
24
+ timestamp: this.now().toISOString(),
25
+ level: n,
26
+ message: t(r),
27
+ ...i === void 0 ? {} : { context: e(i) }
28
+ });
29
+ }
30
+ async getReport(t = {}) {
31
+ let n = t.includeRecentLogs !== !1, a = t.includeDeviceNames === !0, o = t.maskPhoneNumbers !== !1, d = this.dependencies.getSnapshot(), f = this.dependencies.getPermission === void 0 ? d.permission : await s(this.dependencies.getPermission, d.permission), p = a ? await c(this.dependencies.getDeviceNames) : void 0, m = u(l(this.dependencies.getUserAgent)), h = {
32
+ generatedAt: this.now().toISOString(),
33
+ sdk: {
34
+ name: r,
35
+ version: i
36
+ },
37
+ browser: m.browser,
38
+ os: m.os,
39
+ ...d,
40
+ permission: f,
41
+ recentLogs: n ? this.logs.toArray() : [],
42
+ ...p === void 0 ? {} : { deviceNames: p }
43
+ };
44
+ return e(h, { maskPhoneNumbers: o });
45
+ }
46
+ };
47
+ async function s(e, t) {
48
+ try {
49
+ return await e();
50
+ } catch {
51
+ return t;
52
+ }
53
+ }
54
+ async function c(e) {
55
+ if (e === void 0) return [];
56
+ try {
57
+ return [...await e()];
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+ function l(e) {
63
+ if (e !== void 0) try {
64
+ return e();
65
+ } catch {
66
+ return "";
67
+ }
68
+ return typeof navigator > "u" ? "" : navigator.userAgent;
69
+ }
70
+ function u(e) {
71
+ return {
72
+ browser: d(e),
73
+ os: f(e)
74
+ };
75
+ }
76
+ function d(e) {
77
+ for (let [t, n] of [
78
+ ["Edge", /Edg\/([\d.]+)/],
79
+ ["Chrome", /(?:Chrome|CriOS)\/([\d.]+)/],
80
+ ["Firefox", /(?:Firefox|FxiOS)\/([\d.]+)/],
81
+ ["Safari", /Version\/([\d.]+).*Safari/]
82
+ ]) {
83
+ let r = e.match(n);
84
+ if (r?.[1] !== void 0) return {
85
+ name: t,
86
+ version: r[1]
87
+ };
88
+ }
89
+ return {
90
+ name: "unknown",
91
+ version: ""
92
+ };
93
+ }
94
+ function f(e) {
95
+ let t = e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);
96
+ if (t?.[1] !== void 0) return {
97
+ name: "iOS",
98
+ version: t[1].replaceAll("_", ".")
99
+ };
100
+ let n = e.match(/Android ([\d.]+)/);
101
+ if (n?.[1] !== void 0) return {
102
+ name: "Android",
103
+ version: n[1]
104
+ };
105
+ let r = e.match(/Windows NT ([\d.]+)/);
106
+ if (r?.[1] !== void 0) return {
107
+ name: "Windows",
108
+ version: r[1]
109
+ };
110
+ let i = e.match(/Mac OS X ([\d_]+)/);
111
+ return i?.[1] === void 0 ? /Linux/.test(e) ? {
112
+ name: "Linux",
113
+ version: ""
114
+ } : {
115
+ name: "unknown",
116
+ version: ""
117
+ } : {
118
+ name: "macOS",
119
+ version: i[1].replaceAll("_", ".")
120
+ };
121
+ }
122
+ //#endregion
123
+ export { n, o as t };
@@ -0,0 +1,304 @@
1
+ import { t as e } from "./CCBarError-DSbPw2dA.js";
2
+ //#region src/sip/nativeMediaAdapter.ts
3
+ function t(e) {
4
+ let t = /* @__PURE__ */ new Map();
5
+ return {
6
+ peerConnection: {
7
+ getSenders: () => e.getSenders().map((n) => {
8
+ let r = t.get(n);
9
+ if (r !== void 0) return r;
10
+ let i = {
11
+ get track() {
12
+ return n.track;
13
+ },
14
+ get senderKind() {
15
+ let t = n.track;
16
+ if (t !== null) return t.kind === "audio" || t.kind === "video" ? t.kind : void 0;
17
+ let r = e.getTransceivers().find((e) => e.sender === n)?.receiver.track;
18
+ if (r?.kind === "audio" || r?.kind === "video") return r.kind;
19
+ let i = n.getParameters().codecs?.find((e) => typeof e.mimeType == "string");
20
+ if (i?.mimeType?.toLowerCase().startsWith("video/")) return "video";
21
+ if (i?.mimeType?.toLowerCase().startsWith("audio/")) return "audio";
22
+ },
23
+ replaceTrack: (e) => n.replaceTrack(e)
24
+ };
25
+ return t.set(n, i), i;
26
+ }),
27
+ close: () => {
28
+ e.connectionState !== "closed" && e.close();
29
+ }
30
+ },
31
+ trackSource: { onTrack(t) {
32
+ let n = (e) => {
33
+ let n = e.track;
34
+ t({
35
+ streams: [...e.streams],
36
+ track: n
37
+ });
38
+ };
39
+ return e.addEventListener("track", n), () => e.removeEventListener("track", n);
40
+ } }
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region src/sip/JsSipAdapter.ts
45
+ var n = 300, r = class {
46
+ factory;
47
+ transportBaseUrl;
48
+ ua;
49
+ uaListeners;
50
+ incomingHandlers;
51
+ iceServers;
52
+ pendingConnection;
53
+ disposed = !1;
54
+ connectionHandlers = /* @__PURE__ */ new Set();
55
+ constructor(e, t) {
56
+ this.factory = e, this.transportBaseUrl = t;
57
+ }
58
+ connect(e) {
59
+ this.assertNotDisposed(), this.disconnect(this.registrationError("SIP connection replaced"));
60
+ try {
61
+ let t = this.factory.createUa({
62
+ sockets: s(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(e.transport.wssUrl)), e.transport.ticket)),
63
+ uri: e.sip.uri,
64
+ password: e.sip.registerTicket,
65
+ registrar_server: e.sip.registrar,
66
+ register: !0,
67
+ register_expires: n
68
+ });
69
+ return this.ua = t, this.iceServers = e.iceServers, this.uaListeners = [], this.startRegistration(t);
70
+ } catch (e) {
71
+ let t = this.transportError(e);
72
+ return this.disconnect(t), Promise.reject(t);
73
+ }
74
+ }
75
+ disconnect(e = this.registrationError("SIP connection disconnected")) {
76
+ let t = this.pendingConnection;
77
+ this.pendingConnection = void 0, this.ua !== void 0 && (this.removeUaListeners(this.ua), this.ua.stop()), this.ua = void 0, this.uaListeners = void 0, this.iceServers = void 0, t?.reject(e);
78
+ }
79
+ dial(t, n) {
80
+ let r = this.requireUa();
81
+ if (t.trim() === "") throw new e("CALL_INVALID_DESTINATION", "call", !1);
82
+ try {
83
+ let e = n === void 0 ? {
84
+ mediaConstraints: {
85
+ audio: !0,
86
+ video: !1
87
+ },
88
+ sessionTimersExpires: 1800,
89
+ pcConfig: { iceServers: this.iceServers }
90
+ } : {
91
+ mediaConstraints: {
92
+ audio: !0,
93
+ video: !1
94
+ },
95
+ sessionTimersExpires: 1800,
96
+ pcConfig: { iceServers: [...n.iceServers] },
97
+ extraHeaders: [...n.extraHeaders, ...n.type === "extension" ? ["X-XCall-Destination-Type: extension"] : []]
98
+ };
99
+ return new i(r.call(t, e));
100
+ } catch (t) {
101
+ throw new e("CALL_OPERATION_NOT_ALLOWED", "call", !1, { cause: t });
102
+ }
103
+ }
104
+ onIncoming(e) {
105
+ this.assertNotDisposed();
106
+ let t = this.incomingHandlers ?? /* @__PURE__ */ new Set();
107
+ return this.incomingHandlers = t, t.add(e), () => t.delete(e);
108
+ }
109
+ onConnectionStateChanged(e) {
110
+ return this.disposed ? () => void 0 : (this.connectionHandlers.add(e), () => this.connectionHandlers.delete(e));
111
+ }
112
+ dispose() {
113
+ this.disposed || (this.disposed = !0, this.disconnect(), this.incomingHandlers = void 0, this.connectionHandlers.clear());
114
+ }
115
+ getResourceCounts() {
116
+ return {
117
+ listeners: (this.uaListeners?.length ?? 0) + (this.incomingHandlers?.size ?? 0) + this.connectionHandlers.size,
118
+ webSockets: this.ua === void 0 ? 0 : 1
119
+ };
120
+ }
121
+ handleIncoming(e) {
122
+ if (!a(e)) return;
123
+ let t = e.session;
124
+ if (t === void 0) return;
125
+ let n = new i(t);
126
+ this.incomingHandlers?.forEach((e) => e(n));
127
+ }
128
+ startRegistration(e) {
129
+ let t = !0, n = !1, r = new Promise((t, n) => {
130
+ this.pendingConnection = {
131
+ ua: e,
132
+ resolve: t,
133
+ reject: n
134
+ };
135
+ });
136
+ this.listen(e, "registered", () => {
137
+ if (this.isCurrentUa(e)) {
138
+ if (t) {
139
+ n = !0;
140
+ return;
141
+ }
142
+ this.resolveConnection(e);
143
+ }
144
+ }), this.listen(e, "registrationFailed", (t) => {
145
+ if (!this.isCurrentUa(e)) return;
146
+ let n = this.registrationError(this.registrationFailureCause(t));
147
+ this.connectionHandlers.forEach((e) => e("failed", n)), this.disconnect(n);
148
+ }), this.listen(e, "disconnected", (t) => {
149
+ if (!this.isCurrentUa(e)) return;
150
+ let n = this.transportError(t);
151
+ this.connectionHandlers.forEach((e) => e("disconnected", n)), this.disconnect(n);
152
+ }), this.listen(e, "newRTCSession", (t) => {
153
+ this.isCurrentUa(e) && this.handleIncoming(t);
154
+ });
155
+ try {
156
+ e.start();
157
+ } catch (e) {
158
+ let t = this.transportError(e);
159
+ this.connectionHandlers.forEach((e) => e("failed", t)), this.disconnect(t);
160
+ } finally {
161
+ t = !1;
162
+ }
163
+ return n && this.resolveConnection(e), r;
164
+ }
165
+ listen(e, t, n) {
166
+ e.on(t, n), this.uaListeners?.push({
167
+ event: t,
168
+ handler: n
169
+ });
170
+ }
171
+ removeUaListeners(e) {
172
+ this.uaListeners?.forEach(({ event: t, handler: n }) => e.off(t, n));
173
+ }
174
+ isCurrentUa(e) {
175
+ return this.ua === e;
176
+ }
177
+ resolveConnection(e) {
178
+ let t = this.pendingConnection;
179
+ t?.ua === e && (this.pendingConnection = void 0, t.resolve(), this.connectionHandlers.forEach((e) => e("registered")));
180
+ }
181
+ resolveWssUrl(e) {
182
+ let t = this.transportBaseUrl?.trim() === "" || this.transportBaseUrl === void 0 ? typeof location > "u" ? "http://localhost" : location.origin : this.transportBaseUrl, n = e.startsWith("/") ? new URL(e, t) : new URL(e);
183
+ return n.protocol === "http:" && (n.protocol = "ws:"), n.protocol === "https:" && (n.protocol = "wss:"), n.toString();
184
+ }
185
+ withoutTicket(e) {
186
+ let t = new URL(e);
187
+ return t.searchParams.delete("ticket"), t.toString();
188
+ }
189
+ requireUa() {
190
+ if (this.assertNotDisposed(), this.ua === void 0) throw new e("CALL_NOT_CONNECTED", "call", !1);
191
+ return this.ua;
192
+ }
193
+ assertNotDisposed() {
194
+ if (this.disposed) throw new e("SDK_ALREADY_DISPOSED", "internal", !1);
195
+ }
196
+ registrationError(t) {
197
+ return new e("REGISTRATION_FAILED", "registration", !0, { cause: t });
198
+ }
199
+ transportError(t) {
200
+ return new e("SIP_WS_UNAVAILABLE", "registration", !0, { cause: t });
201
+ }
202
+ registrationFailureCause(e) {
203
+ return typeof e == "object" && e && "cause" in e ? e.cause : e;
204
+ }
205
+ }, i = class {
206
+ session;
207
+ pendingHoldReject;
208
+ mediaRegistration;
209
+ mediaConnection;
210
+ constructor(e) {
211
+ this.session = e;
212
+ }
213
+ get id() {
214
+ return this.session.id;
215
+ }
216
+ get from() {
217
+ return this.session.from ?? c(this.session.remote_identity);
218
+ }
219
+ getMediaRegistration() {
220
+ let e = this.session.connection;
221
+ if (e !== void 0) return this.mediaRegistration !== void 0 && this.mediaConnection === e ? this.mediaRegistration : (this.mediaConnection = e, this.mediaRegistration = t(e), this.mediaRegistration);
222
+ }
223
+ answer(e) {
224
+ this.session.answer({
225
+ mediaConstraints: e.mediaConstraints,
226
+ pcConfig: { iceServers: [...e.pcConfig.iceServers] }
227
+ });
228
+ }
229
+ terminate() {
230
+ this.pendingHoldReject?.(/* @__PURE__ */ Error("SIP session terminated")), this.session.terminate();
231
+ }
232
+ hold() {
233
+ return this.changeHoldState("hold");
234
+ }
235
+ unhold() {
236
+ return this.changeHoldState("unhold");
237
+ }
238
+ mute() {
239
+ this.session.mute();
240
+ }
241
+ unmute() {
242
+ this.session.unmute();
243
+ }
244
+ sendDtmf(e) {
245
+ this.session.sendDTMF(e);
246
+ }
247
+ refer(e) {
248
+ this.session.refer(e);
249
+ }
250
+ on(e, t) {
251
+ return this.session.on(e, t), () => this.session.off(e, t);
252
+ }
253
+ changeHoldState(t) {
254
+ return new Promise((n, r) => {
255
+ let i = !1, a = (e) => {
256
+ c(e);
257
+ }, o = () => {
258
+ try {
259
+ this.session.off("ended", a);
260
+ } catch {}
261
+ try {
262
+ this.session.off("failed", a);
263
+ } catch {}
264
+ this.pendingHoldReject === c && (this.pendingHoldReject = void 0);
265
+ }, s = () => {
266
+ i || (i = !0, o(), n());
267
+ }, c = (t) => {
268
+ i || (i = !0, o(), r(new e("CALL_OPERATION_NOT_ALLOWED", "call", !1, { cause: t })));
269
+ };
270
+ try {
271
+ this.session.on("ended", a), this.session.on("failed", a);
272
+ } catch (e) {
273
+ c(e);
274
+ return;
275
+ }
276
+ this.pendingHoldReject = c;
277
+ try {
278
+ this.session[t](void 0, s) || c();
279
+ } catch (e) {
280
+ c(e);
281
+ }
282
+ });
283
+ }
284
+ };
285
+ function a(e) {
286
+ if (typeof e != "object" || !e) return !1;
287
+ let t = e;
288
+ return t.originator === "remote" && o(t.session);
289
+ }
290
+ function o(e) {
291
+ return typeof e == "object" && !!e && "id" in e;
292
+ }
293
+ function s(e) {
294
+ return typeof e == "object" && e && (e.via_transport = "WSS"), e;
295
+ }
296
+ function c(e) {
297
+ let t = e?.uri;
298
+ if (t == null) return;
299
+ if (typeof t.user == "string" && t.user !== "") return t.user;
300
+ let n = t.toString();
301
+ return n.match(/^sips?:([^@;>]+)/i)?.[1] ?? (n === "" ? void 0 : n);
302
+ }
303
+ //#endregion
304
+ export { r as JsSipAdapter };
@@ -0,0 +1 @@
1
+ const e=require("./CCBarError-CIqJE8zK.cjs");require("./createJsSipFactory-2X4FBIU2.cjs");function t(e){let t=new Map;return{peerConnection:{getSenders:()=>e.getSenders().map(n=>{let r=t.get(n);if(r!==void 0)return r;let i={get track(){return n.track},get senderKind(){let t=n.track;if(t!==null)return t.kind===`audio`||t.kind===`video`?t.kind:void 0;let r=e.getTransceivers().find(e=>e.sender===n)?.receiver.track;if(r?.kind===`audio`||r?.kind===`video`)return r.kind;let i=n.getParameters().codecs?.find(e=>typeof e.mimeType==`string`);if(i?.mimeType?.toLowerCase().startsWith(`video/`))return`video`;if(i?.mimeType?.toLowerCase().startsWith(`audio/`))return`audio`},replaceTrack:e=>n.replaceTrack(e)};return t.set(n,i),i}),close:()=>{e.connectionState!==`closed`&&e.close()}},trackSource:{onTrack(t){let n=e=>{let n=e.track;t({streams:[...e.streams],track:n})};return e.addEventListener(`track`,n),()=>e.removeEventListener(`track`,n)}}}}var n=300,r=class{factory;transportBaseUrl;ua;uaListeners;incomingHandlers;iceServers;pendingConnection;disposed=!1;connectionHandlers=new Set;constructor(e,t){this.factory=e,this.transportBaseUrl=t}connect(e){this.assertNotDisposed(),this.disconnect(this.registrationError(`SIP connection replaced`));try{let t=this.factory.createUa({sockets:s(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(e.transport.wssUrl)),e.transport.ticket)),uri:e.sip.uri,password:e.sip.registerTicket,registrar_server:e.sip.registrar,register:!0,register_expires:n});return this.ua=t,this.iceServers=e.iceServers,this.uaListeners=[],this.startRegistration(t)}catch(e){let t=this.transportError(e);return this.disconnect(t),Promise.reject(t)}}disconnect(e=this.registrationError(`SIP connection disconnected`)){let t=this.pendingConnection;this.pendingConnection=void 0,this.ua!==void 0&&(this.removeUaListeners(this.ua),this.ua.stop()),this.ua=void 0,this.uaListeners=void 0,this.iceServers=void 0,t?.reject(e)}dial(t,n){let r=this.requireUa();if(t.trim()===``)throw new e.t(`CALL_INVALID_DESTINATION`,`call`,!1);try{let e=n===void 0?{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:1800,pcConfig:{iceServers:this.iceServers}}:{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:1800,pcConfig:{iceServers:[...n.iceServers]},extraHeaders:[...n.extraHeaders,...n.type===`extension`?[`X-XCall-Destination-Type: extension`]:[]]};return new i(r.call(t,e))}catch(t){throw new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:t})}}onIncoming(e){this.assertNotDisposed();let t=this.incomingHandlers??new Set;return this.incomingHandlers=t,t.add(e),()=>t.delete(e)}onConnectionStateChanged(e){return this.disposed?()=>void 0:(this.connectionHandlers.add(e),()=>this.connectionHandlers.delete(e))}dispose(){this.disposed||(this.disposed=!0,this.disconnect(),this.incomingHandlers=void 0,this.connectionHandlers.clear())}getResourceCounts(){return{listeners:(this.uaListeners?.length??0)+(this.incomingHandlers?.size??0)+this.connectionHandlers.size,webSockets:this.ua===void 0?0:1}}handleIncoming(e){if(!a(e))return;let t=e.session;if(t===void 0)return;let n=new i(t);this.incomingHandlers?.forEach(e=>e(n))}startRegistration(e){let t=!0,n=!1,r=new Promise((t,n)=>{this.pendingConnection={ua:e,resolve:t,reject:n}});this.listen(e,`registered`,()=>{if(this.isCurrentUa(e)){if(t){n=!0;return}this.resolveConnection(e)}}),this.listen(e,`registrationFailed`,t=>{if(!this.isCurrentUa(e))return;let n=this.registrationError(this.registrationFailureCause(t));this.connectionHandlers.forEach(e=>e(`failed`,n)),this.disconnect(n)}),this.listen(e,`disconnected`,t=>{if(!this.isCurrentUa(e))return;let n=this.transportError(t);this.connectionHandlers.forEach(e=>e(`disconnected`,n)),this.disconnect(n)}),this.listen(e,`newRTCSession`,t=>{this.isCurrentUa(e)&&this.handleIncoming(t)});try{e.start()}catch(e){let t=this.transportError(e);this.connectionHandlers.forEach(e=>e(`failed`,t)),this.disconnect(t)}finally{t=!1}return n&&this.resolveConnection(e),r}listen(e,t,n){e.on(t,n),this.uaListeners?.push({event:t,handler:n})}removeUaListeners(e){this.uaListeners?.forEach(({event:t,handler:n})=>e.off(t,n))}isCurrentUa(e){return this.ua===e}resolveConnection(e){let t=this.pendingConnection;t?.ua===e&&(this.pendingConnection=void 0,t.resolve(),this.connectionHandlers.forEach(e=>e(`registered`)))}resolveWssUrl(e){let t=this.transportBaseUrl?.trim()===``||this.transportBaseUrl===void 0?typeof location>`u`?`http://localhost`:location.origin:this.transportBaseUrl,n=e.startsWith(`/`)?new URL(e,t):new URL(e);return n.protocol===`http:`&&(n.protocol=`ws:`),n.protocol===`https:`&&(n.protocol=`wss:`),n.toString()}withoutTicket(e){let t=new URL(e);return t.searchParams.delete(`ticket`),t.toString()}requireUa(){if(this.assertNotDisposed(),this.ua===void 0)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1);return this.ua}assertNotDisposed(){if(this.disposed)throw new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}registrationError(t){return new e.t(`REGISTRATION_FAILED`,`registration`,!0,{cause:t})}transportError(t){return new e.t(`SIP_WS_UNAVAILABLE`,`registration`,!0,{cause:t})}registrationFailureCause(e){return typeof e==`object`&&e&&`cause`in e?e.cause:e}},i=class{session;pendingHoldReject;mediaRegistration;mediaConnection;constructor(e){this.session=e}get id(){return this.session.id}get from(){return this.session.from??c(this.session.remote_identity)}getMediaRegistration(){let e=this.session.connection;if(e!==void 0)return this.mediaRegistration!==void 0&&this.mediaConnection===e?this.mediaRegistration:(this.mediaConnection=e,this.mediaRegistration=t(e),this.mediaRegistration)}answer(e){this.session.answer({mediaConstraints:e.mediaConstraints,pcConfig:{iceServers:[...e.pcConfig.iceServers]}})}terminate(){this.pendingHoldReject?.(Error(`SIP session terminated`)),this.session.terminate()}hold(){return this.changeHoldState(`hold`)}unhold(){return this.changeHoldState(`unhold`)}mute(){this.session.mute()}unmute(){this.session.unmute()}sendDtmf(e){this.session.sendDTMF(e)}refer(e){this.session.refer(e)}on(e,t){return this.session.on(e,t),()=>this.session.off(e,t)}changeHoldState(t){return new Promise((n,r)=>{let i=!1,a=e=>{c(e)},o=()=>{try{this.session.off(`ended`,a)}catch{}try{this.session.off(`failed`,a)}catch{}this.pendingHoldReject===c&&(this.pendingHoldReject=void 0)},s=()=>{i||(i=!0,o(),n())},c=t=>{i||(i=!0,o(),r(new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:t})))};try{this.session.on(`ended`,a),this.session.on(`failed`,a)}catch(e){c(e);return}this.pendingHoldReject=c;try{this.session[t](void 0,s)||c()}catch(e){c(e)}})}};function a(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.originator===`remote`&&o(t.session)}function o(e){return typeof e==`object`&&!!e&&`id`in e}function s(e){return typeof e==`object`&&e&&(e.via_transport=`WSS`),e}function c(e){let t=e?.uri;if(t==null)return;if(typeof t.user==`string`&&t.user!==``)return t.user;let n=t.toString();return n.match(/^sips?:([^@;>]+)/i)?.[1]??(n===``?void 0:n)}exports.JsSipAdapter=r;