@16x/webphone-sdk 3.0.2 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -26
- package/LICENSE +1 -1
- package/README.md +113 -113
- package/dist/{CCBarClient-xC63i3Qd.js → CCBarClient-BCWPbFNX.js} +226 -163
- package/dist/CCBarClient-BaO_GM1u.cjs +1 -0
- package/dist/{Diagnostics-CvH6cjih.cjs → Diagnostics-BXKjfW9h.cjs} +1 -1
- package/dist/{Diagnostics-BhsVHELt.js → Diagnostics-Hb2Y9WsN.js} +1 -1
- package/dist/JsSipAdapter-915kI1VH.cjs +1 -0
- package/dist/{JsSipAdapter-CV6q6UUY.js → JsSipAdapter-BoxqJZsR.js} +47 -21
- package/dist/SharedWorkerProtocol-39dch6xL.cjs +1 -0
- package/dist/{SharedWorkerProtocol-jfo9N5wa.js → SharedWorkerProtocol-DKVQ5-po.js} +5 -1
- package/dist/core/CCBarClient.d.ts +28 -2
- package/dist/{createJsSipFactory-yttVU3d6.js → createJsSipFactory-9CPsweDR.js} +4 -1
- package/dist/{createJsSipFactory-2X4FBIU2.cjs → createJsSipFactory-Dr8HbLl-.cjs} +1 -1
- package/dist/diagnostics/index.cjs +1 -1
- package/dist/diagnostics/index.js +1 -1
- package/dist/errors/CCBarError.d.ts +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/index.umd.js +2 -2
- package/dist/legacy/index.cjs +1 -1
- package/dist/legacy/index.js +2 -2
- package/dist/shared/SharedWorkerProtocol.d.ts +2 -0
- package/dist/shared-worker.cjs +1 -1
- package/dist/shared-worker.js +1 -1
- package/dist/styles.css +7 -7
- package/dist/ui/index.cjs +1 -1
- package/dist/version.d.ts +1 -0
- package/package.json +111 -109
- package/dist/CCBarClient-DdLM2NKm.cjs +0 -1
- package/dist/JsSipAdapter-BM7I95Xb.cjs +0 -1
- package/dist/SharedWorkerProtocol-V_x8Erjv.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./SharedWorkerProtocol-39dch6xL.cjs"),t=require("./Diagnostics-BXKjfW9h.cjs");var n=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},r={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},i=(e,t)=>r[e].has(t);function a(e,t){if(!i(e,t))throw new o(e,t);return t}var o=class extends e.i{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},s=a,c=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},SESSION_EXPIRED:{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,credentials:`omit`,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.i?t:t instanceof DOMException&&t.name===`AbortError`?new e.i(`NETWORK_TIMEOUT`,`network`,!0,{cause:t}):new e.i(`NETWORK_OFFLINE`,`network`,!0,{cause:t})}finally{clearTimeout(a)}}requireData(t){if(t.data===void 0||t.data===null)throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:t.requestId});return t.data}async parseResponse(t){try{return await t.json()}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,t.status>=500,{cause:n})}}toCCBarError(t,n){let r=u[n.code??``]??this.mapStatus(t);return new e.i(r.code,r.category,r.retryable,{requestId:n.requestId,serverCode:n.code,status:t})}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.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:n})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){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.i&&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.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(t){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}};function 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.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(t,n){this.assertNotDisposed();let r=this.operationGeneration,i=t.destination.trim();if(i===``)throw new e.i(`CALL_INVALID_DESTINATION`,`call`,!1);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.i(`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),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason: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.i(`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).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(t,n){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}capabilityError(t){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n){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.i?new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t}):new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}},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.i)return new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t});if(typeof t==`object`&&t&&`error`in t){let r=t.error;if(r instanceof e.i)return new e.i(r.code,r.category,r.retryable,{requestId:r.requestId,callId:n,cause:r.cause??r});if(r instanceof Error)return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:r})}return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}var C=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(t){return this.closed?Promise.reject(new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(t.requestId)?Promise.reject(new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:t.requestId})):this.lifecycleState===`reconnecting`&&t.type===`command`&&(t.command===`dial`||t.command===`answer`)?Promise.reject(new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:t.payload?.callId})):new Promise((n,r)=>{let i=setTimeout(()=>{this.pending.delete(t.requestId),r(new e.i(`NETWORK_TIMEOUT`,`network`,!0,{requestId:t.requestId}))},this.timeoutMs);this.pending.set(t.requestId,{resolve:e=>n(e),reject:r,timer:i}),this.port.postMessage(t)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(t){try{let n=e.t(t);if(n.type===`event`){n.event===`connection.stateChanged`&&w(n.payload)&&(this.lifecycleState=n.payload.state),this.eventHandlers.forEach(e=>e(n));return}if(n.type!==`response`)return;let r=this.pending.get(n.requestId);if(r===void 0)return;this.pending.delete(n.requestId),clearTimeout(r.timer),n.ok?r.resolve(n.result):r.reject(T(n))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function w(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function T(t){let n=t.error;return new e.i(n?.code??`SDK_INTERNAL_ERROR`,n?.category??`internal`,n?.retryable??!1,{requestId:t.requestId,...n?.message===void 0?{}:{cause:n.message},...n?.serverCode===void 0?{}:{serverCode:n.serverCode},...n?.status===void 0?{}:{status:n.status}})}function E(t={}){if((t.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let n=t.locationHref??O(),r=D(t.url,n),i=n=>{if(t.fallback===`error`)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:n});return{mode:`single-tab`,reason:n}};if(r===void 0)return i(`SharedWorker URL is unavailable`);if(!te(r,n))return i(`SharedWorker URL must be same-origin`);let a=t.workerCtor??ee();if(a===void 0)return i(`SharedWorker is not supported`);let o;try{o=new a(r,t.name===void 0?void 0:{name:t.name})}catch(e){return i(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let s=t.tabId??ne(),c=new C(o.port),l={version:1,type:`attach`,requestId:re(),tabId:s},u=c.request(l).then(()=>void 0).catch(e=>{throw c.close(),e});return{mode:`shared`,worker:o,client:c,tabId:s,workerUrl:r,ready:u}}function D(e,t=O()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function O(){return typeof location>`u`?void 0:location.href}function ee(){if(typeof SharedWorker==`function`)return SharedWorker}function te(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function ne(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function re(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}var ie=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??ae(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw A(e)}oe(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw j(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(t,n){if(!this.supportsOutputSelection())throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=t;let r=++this.outputGeneration;n!==void 0&&await this.enqueueOutput(async()=>{r===this.outputGeneration&&await this.applyOutputDevice(t,n)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(t,n){let r=n;if(typeof r.setSinkId!=`function`)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await r.setSinkId(t)}catch(e){throw M(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw k(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function ae(){return globalThis.navigator?.mediaDevices}function oe(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function k(t){let n=N(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function A(t){let n=N(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function j(t){let n=N(t);return n===`NotFoundError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function M(t){let n=N(t);return n===`NotFoundError`?new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function N(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}var P=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=F){this.createAudioElement=e}async bind(t,n){let r=this.bindings.get(t);if(r?.stream===n)return;let i=I(t,n),a;try{a=this.createAudioElement()}catch(n){throw L(i,this.trackOwners),new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t,cause:n})}let o=this.audioOwners.get(a);if(o!==void 0&&o!==t)throw L(i,this.trackOwners),new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});try{a.autoplay=!0,a.playsInline=!0}catch(n){throw L(i,this.trackOwners),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}try{a.srcObject=n}catch(n){throw L(i,this.trackOwners),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}this.acquireTracks(i),r!==void 0&&this.releaseBinding(r,r.audio!==a);let s=this.nextGeneration(t);this.audioOwners.set(a,t);let c={callId:t,audio:a,stream:n,tracks:i,generation:s};this.bindings.set(t,c),this.beginPlay(t);try{await a.play()}catch(n){if(!this.isCurrent(t,s))return;throw new e.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,s)}async play(t){let n=this.bindings.get(t);if(n===void 0)throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});let r=n.generation;this.beginPlay(t);try{await n.audio.play()}catch(n){if(!this.isCurrent(t,r))return;throw new e.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,r)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),z(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function F(){if(typeof document>`u`)throw new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function I(t,n){try{return[...new Set(n.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(r){try{return[...new Set(n.getTracks())].filter(e=>e.kind===`audio`)}catch(i){throw R(n),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:r??i})}}}function L(e,t){e.forEach(e=>{(t.get(e)??0)===0&&z(e)})}function R(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(z)}catch{}}function z(e){try{e.stop()}catch{}}var B=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new ie(t),this.remoteAudio=new P(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??q}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=V(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(t){let n=this.releaseOperations.get(t);if(n!==void 0)return n;if(!this.resources.has(t))return Promise.resolve();let r=t.callId;this.remoteAudio.release(r),this.releaseErrors.delete(t),this.calls.get(r)===t&&this.calls.delete(r),t.generation+=1,t.released=!0,this.unsubscribeTrackSource(t);let i=new Set([...t.localTracks,...t.pendingTracks]),a=[...t.senders.values()].filter(e=>e.audio).map(e=>({senderResource:e,promise:this.enqueueSender(t,e,()=>U(e.sender),!0)})),o=Promise.all(a.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async n=>{let a=new Set,o=[];if(n.forEach(e=>{if(e.cause!==void 0){o.push(e.cause);let t=H(e.senderResource.sender);t?.kind===`audio`&&a.add(t);return}let t=H(e.senderResource.sender);t?.kind===`audio`&&i.add(t)}),i.forEach(e=>{a.has(e)||K(e)}),o.length>0)throw t.localTracks.clear(),t.pendingTracks.clear(),a.forEach(e=>t.localTracks.add(e)),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:o[0]});if(!t.peerClosed&&t.peerConnection.close!==void 0)try{await t.peerConnection.close(),t.peerClosed=!0}catch(n){let i=[...t.senders.values()].map(e=>H(e.sender)).find(e=>e?.kind===`audio`);throw t.localTracks.clear(),t.pendingTracks.clear(),i!=null&&t.localTracks.add(i),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:n})}t.localTracks.clear(),t.pendingTracks.clear(),t.senders.clear(),this.resources.delete(t),this.releaseUnusedSenderQueues()}).catch(e=>{throw this.releaseErrors.set(t,e),this.calls.get(r)===void 0&&this.calls.set(r,t),e}).finally(()=>{this.releaseOperations.get(t)===o&&this.releaseOperations.delete(t)});return this.releaseOperations.set(t,o),o}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(t,n,r){if(this.assertActiveCall(n),this.assertDeviceSelectionCapability(n),!this.isCurrentResource(r)||n.peerConnection!==r.peerConnection)throw this.callOperationError(n.callId);let i=this.findAudioSender(r),a=H(i.sender),o=r.generation,s=await this.deviceManager.openInputStream(t),c;try{c=s.getTracks()}catch(t){throw W(s),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let l;try{l=s.getAudioTracks()}catch(t){throw G(c),new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let u=l[0];if(u===void 0)throw G(c),new e.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:n.callId});if(!this.canCommitInputSwitch(n,r,i,a,o))throw G(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),G(c)),new e.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:n.callId,cause:t}))}if(!this.canCommitInputSwitch(n,r,i,u,o)){if(!r.released)try{await this.enqueueSender(r,i,()=>H(i.sender)===u?U(i.sender):Promise.resolve()),c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),G(c)}catch(t){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n.callId,cause:t})}throw this.callOperationError(n.callId)}c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),r.localTracks.add(u),a!==null&&a!==u&&(r.localTracks.delete(a),K(a)),c.forEach(e=>{e!==u&&K(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(t,n){let r;try{r=t.peerConnection.getSenders()}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}r.forEach(r=>{let i=H(r),a;try{a=n?.(r)??r.senderKind??r.kind}catch(n){throw new e.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}t.senders.set(r,{sender:r,audio:a===`audio`||a===void 0&&i?.kind===`audio`,queue:this.senderQueues.get(r)??this.createSenderQueue(r)}),i?.kind===`audio`&&t.localTracks.add(i)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(H(e.sender)?.kind===`audio`||H(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return H(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||H(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(t){if(t===void 0||t.state!==`active`)throw new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(t){return new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}callOperationError(t){return new e.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t})}assertNotDisposed(){if(this.disposed||this.disposing)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function V(e){return`peerConnection`in e}function H(e){try{return e.track}catch{return null}}function U(e){try{return e.replaceTrack(null)}catch(e){return Promise.reject(e)}}function W(e){try{G(e.getTracks())}catch{}}function G(e){e.forEach(K)}function K(e){try{e.stop()}catch{}}function q(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}function se(t,n={}){let r=new Map,i=new Map,a=new Set,o=n.ownershipRequired===!0,s=!1,c=!1,l,u=()=>t(),d=new B({getActiveCall:u});return{publicMedia:{requestPermission:()=>(f(),d.requestPermission()),getDevices:()=>(f(),d.getDevices()),getCapabilities:()=>(f(),d.getCapabilities()),supportsOutputSelection:()=>(f(),d.supportsOutputSelection()),setInputDevice:e=>(f(),d.setInputDevice(e,u())),setOutputDevice:e=>(f(),d.setOutputDevice(e)),playRemoteAudio:e=>(f(),d.playRemoteAudio(e)),releaseAll:()=>(f(),d.releaseAll())},registerCall(e,t){s||c||!J(t)||(i.set(e,t),(!o||a.has(e))&&p(e,t))},async setCallOwnership(e,t){if(s)return;if(t!==`owned`){a.delete(e),await d.releaseCall(e),r.delete(e);return}a.add(e);let n=i.get(e);n!==void 0&&p(e,n)},contextFor(e,t,n){let i=r.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:n,peerConnection:i.peerConnection}},async releaseCall(e){s||(await d.releaseCall(e),r.delete(e),i.delete(e),a.delete(e))},releaseAll:async()=>{await d.releaseAll(),r.clear(),i.clear(),a.clear()},getResourceCounts:()=>d.getResourceCounts(),dispose:()=>{if(l!==void 0)return l;c=!0;let e=d.dispose().then(()=>{s=!0,c=!1,r.clear(),i.clear(),a.clear()}).finally(()=>{l===e&&!s&&(l=void 0,c=!1)});return l=e,e}};function f(){if(s)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function p(e,t){if(!J(t)||typeof t.getMediaRegistration!=`function`)return;let n=t.getMediaRegistration();if(ce(n)&&r.get(e)?.peerConnection!==n.peerConnection){r.set(e,n);try{d.registerCallMedia(e,n)}catch{r.delete(e)}}}}function J(e){return typeof e==`object`&&!!e}function ce(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var le=1e3,ue=3e4;function de(e,t=Math.random){let n=Math.min(ue,le*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var fe=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=de(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)}},pe=class r{media;options;api;suppliedSip;sip;events=new n;mediaBridge;reconnect;diagnostics;callManager;session;state=`idle`;initialized=!1;disposed=!1;intentionalDisconnect=!1;deferredRebuild=!1;sessionRecoveryPending=!1;detectedPlatform;support;acceptingEvents=!0;connectOperation;disconnectOperation;refreshOperation;disposeOperation;refreshTimer;lifecycleGeneration=0;managerUnsubscribers=[];sipUnsubscribe;networkUnsubscribers=[];sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;tokenRequest={};sharedWorkerSelection;constructor(n){if(this.options=n,n.api===void 0&&n.sessionProvider===void 0&&n.tokenProvider===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`CCBarClient 需要 tokenProvider 或 sessionProvider`});let r=n.tokenProvider,i=t=>r===void 0?Promise.reject(new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`未提供 tokenProvider`})):r({...t,...this.tokenRequest});this.api=n.api===void 0?n.sessionProvider===void 0?new d({baseUrl:n.baseUrl??``,tokenProvider:i}):Y(ge(n.sessionProvider)):Y(n.api),this.suppliedSip=n.sip===void 0?void 0:X(n.sip),this.mediaBridge=se(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new fe({recover:()=>this.recoverConnection(),onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new t.t({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)}),this.sharedWorkerSelection=n.sharedWorker===void 0?{mode:`single-tab`,reason:`disabled`}:E({...n.sharedWorker,...n.sharedWorkerHost??{}})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=he(typeof navigator<`u`?navigator.userAgent:``);return{supported:e&&t,platform:n,hasMediaDevices:e,hasWebSocket:t,...e&&t?{}:{reason:`当前运行环境缺少 WebPhone 所需的浏览器能力`}}}async initialize(){if(this.assertNotDisposed(),this.initialized)return;let e=await r.checkSupport();this.support=e,this.options.platform===void 0&&(e.platform===`web`||e.platform===`mobile-web`)&&(this.detectedPlatform=e.platform),await this.awaitSharedWorkerReady(),this.assertNotDisposed(),this.initialized=!0}connect(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.releaseSharedWorker(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(t){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.dial(t,r)}answer(t,n){this.assertConnected();let r=this.callManager,i=this.session;if(r===void 0||i===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return r.answer(t,i,n)}setActiveCall(t){this.assertConnected();let n=this.callManager;if(n===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.setActiveCall(t)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getSharedWorkerState(){let e=this.sharedWorkerSelection;return e.mode===`shared`?{mode:`shared`,tabId:e.tabId}:{mode:`single-tab`,reason:e.reason}}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){this.assertNotDisposed(),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 n,r,i;try{await this.initialize(),this.assertGeneration(e);let a=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),n=await this.api.createSession({sdkVersion:t.r,platform:a===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??be(a)]}),this.ownedSessionIds.add(n.sessionId),this.assertGeneration(e),r=await this.getSip(),this.assertGeneration(e),this.session=n;let o=this.callManager??this.createCallManager(r,n,a);this.callManager===void 0&&(i=o),o.updateSession(n),this.callManager=o,this.attachSipListener(r),this.attachNetworkListeners(),await r.connect(n),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(n)}catch(t){if(await this.rollbackConnect(n,r,i),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw t;let a=Z(t,`REGISTRATION_FAILED`,`registration`,!0);throw this.setConnectionState(`failed`),this.events.emit(`connection.failed`,{error:a}),a}}async performDisconnect(){let e,t=this.connectOperation;if(t!==void 0)try{await t}catch(t){$(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){$(t)||(e??=t)}this.reconnect.cancel(),this.clearRefreshTimer(),this.intentionalDisconnect=!0,this.detachNetworkListeners(),this.detachSipListener(),this.detachManagerListeners();let r=this.callManager,i=this.sip;this.callManager=void 0;try{await r?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{i!==void 0&&await i.disconnect()}catch(t){e??=t}this.session=void 0;try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new 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){_e(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await n,this.terminalReleaseOperations.delete(t)}catch(n){try{await this.mediaBridge.releaseCall(t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}detachSipListener(){let e=this.sipUnsubscribe;this.sipUnsubscribe=void 0;try{e?.()}catch{}}detachManagerListeners(){this.managerUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}bindManagerEvents(e){[`call.created`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`error`].forEach(t=>{let n=e.on(t,e=>{this.acceptingEvents&&!this.disposed&&(this.diagnostics.log(t===`error`||t===`call.failed`?`error`:`info`,String(t),e),this.events.emit(t,e))});this.managerUnsubscribers.push(n)})}handleCallCreated(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallStateChanged(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallTerminal(e){let t=this.startTerminalRelease(e);return this.deferredRebuild&&!this.hasNonTerminalCalls()&&this.startDeferredRecovery(),t}startTerminalRelease(e){let t=this.terminalReleaseOperations.get(e);if(t!==void 0)return t;let n=this.mediaBridge.releaseCall(e).then(()=>{this.terminalReleaseOperations.get(e)===n&&this.terminalReleaseOperations.delete(e)}).catch(t=>{throw this.acceptingEvents&&!this.disposed&&this.events.emit(`error`,{error:Z(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{if(await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed){if(this.sessionRecoveryPending){this.recoverInvalidSession();return}this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start()}}catch{!this.disposed&&!this.sessionRecoveryPending&&this.reconnect.start()}}async refreshAndRebuild(){if(this.refreshOperation!==void 0)return this.refreshOperation;let e=this.performRefreshAndRebuild().finally(()=>{this.refreshOperation===e&&(this.refreshOperation=void 0),this.sessionRecoveryPending&&!this.hasNonTerminalCalls()&&!this.disposed&&this.recoverInvalidSession()});return this.refreshOperation=e,e}async performRefreshAndRebuild(){if(this.disposed||this.session===void 0)return;let e=this.lifecycleGeneration,t=this.session;try{let n=await this.api.refreshSession(t.sessionId);if(!this.isCurrentGeneration(e)||this.session!==t)return;if(this.session=n,this.callManager?.updateSession(n),this.events.emit(`token.refreshed`,{expiresAt:n.expiresAt}),this.hasNonTerminalCalls()){this.deferredRebuild=!0,this.scheduleRefresh(n);return}let r=await this.getSip();if(!this.isCurrentGeneration(e))return;await r.connect(n),this.isCurrentGeneration(e)&&(this.deferredRebuild=!1,this.setConnectionState(`connected`),this.scheduleRefresh(n))}catch(n){if(!this.isCurrentGeneration(e))return;throw this.handleRefreshFailure(t,n),n}}handleRefreshFailure(e,t){if(this.disposed)return;let n=Z(t,`NETWORK_OFFLINE`,`network`,!0);if(this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),Q(t)){this.clearRefreshTimer(),this.reconnect.cancel(),this.deletedSessions.add(e.sessionId),this.sessionRecoveryPending=!0,this.deferredRebuild=!0,(n.code===`AUTH_TOKEN_UNAVAILABLE`||n.code===`AUTH_TOKEN_EXPIRED`)&&this.api.invalidateToken?.();return}this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}async recoverInvalidSession(){if(!(!this.sessionRecoveryPending||this.disposed||this.hasNonTerminalCalls())){this.sessionRecoveryPending=!1,this.deferredRebuild=!1;try{await this.performDisconnect()}catch(e){this.disposed||this.events.emit(`error`,{error:Z(e,`SDK_INTERNAL_ERROR`,`internal`,!0)});return}if(!this.disposed)try{await this.performConnect(this.lifecycleGeneration)}catch{this.reconnect.cancel()}}}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){this.disposed||this.intentionalDisconnect||this.hasNonTerminalCalls()||(await this.awaitMediaReleaseBarriers(),await this.refreshAndRebuild())}async getSip(){if(this.sip!==void 0)return this.sip;if(this.suppliedSip!==void 0)return this.sip=this.suppliedSip,this.sip;let[e,t]=await Promise.all([Promise.resolve().then(()=>require("./createJsSipFactory-Dr8HbLl-.cjs")),Promise.resolve().then(()=>require("./JsSipAdapter-915kI1VH.cjs"))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl,this.options.sipKeepaliveSeconds),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:Z(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>this.reconnect.notifyOnline(),n=()=>this.reconnect.notifyOffline();e.addEventListener(`online`,t),e.addEventListener(`offline`,n),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n)]}detachNetworkListeners(){this.networkUnsubscribers.splice(0).forEach(e=>e())}getActiveMediaContext(){let e=this.callManager?.getActiveCall();return e===void 0?void 0:this.mediaBridge.contextFor(e.id,e.state,new Set(this.session?.capabilities??[]))}hasNonTerminalCalls(){return this.callManager?.hasNonTerminalCalls()??!1}clearRefreshTimer(){this.refreshTimer!==void 0&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}createDiagnosticsSnapshot(){let e=this.session;return{connectionState:this.state,calls:this.getCalls().map(e=>({callId:e.id,state:e.state,destination:e.destination})),permission:this.support?.hasMediaDevices===!1?`unsupported`:`unknown`,ice:me(e),wss:{configured:e!==void 0,secure:e?.transport.wssUrl.toLowerCase().startsWith(`wss://`)??!1,state:this.state},resources:this.getDiagnosticsResourceCounts()}}getDiagnosticsResourceCounts(){let e=this.mediaBridge.getResourceCounts(),t=this.callManager?.getResourceCounts()??{timers:0,listeners:0},n=this.sip?.getResourceCounts?.(),r=(this.callManager===void 0?0:1)+(this.sipUnsubscribe===void 0?0:1),i=this.session!==void 0&&this.state!==`idle`&&this.state!==`disconnected`;return{timers:(this.refreshTimer===void 0?0:1)+this.reconnect.getTimerCount()+t.timers,listeners:this.events.listenerCount()+t.listeners+e.listeners+this.networkUnsubscribers.length+(n?.listeners??r),tracks:e.tracks,peerConnections:e.peerConnections,audioElements:e.audioElements,webSockets:n?.webSockets??+!!i,deletedSessions:this.deletedSessions.size}}async readMicrophonePermission(){if(typeof navigator>`u`||navigator.mediaDevices===void 0)return`unsupported`;if(navigator.permissions===void 0)return`unknown`;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}deleteSession(e){if(this.deletedSessions.has(e))return Promise.resolve();let t=this.sessionDeleteOperations.get(e);if(t!==void 0)return t;let n=this.api.deleteSession(e).then(()=>{this.deletedSessions.add(e)}).catch(t=>{if(Q(t)){this.deletedSessions.add(e);return}throw t}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}pruneDeletedSessionTombstones(){for(let e of[...this.deletedSessions])!this.ownedSessionIds.has(e)&&!this.sessionDeleteOperations.has(e)&&this.deletedSessions.delete(e)}async deleteOwnedSessions(){let e;for(let t of[...this.ownedSessionIds])try{await this.deleteSession(t),this.ownedSessionIds.delete(t)}catch(t){e??=t}if(e!==void 0)throw e}resolvePlatform(){let t=this.options.platform??this.detectedPlatform;if(t===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return t}setConnectionState(e){this.state===e||this.disposed||(this.state=e,this.diagnostics.log(`info`,`connection.stateChanged`,{state:e}),this.events.emit(`connection.stateChanged`,{state:e===`disconnected`||e===`idle`?`offline`:e}))}assertConnected(){if(this.assertNotDisposed(),this.state!==`connected`||this.callManager===void 0||this.session===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(t){if(this.disposed)throw this.disposedError();if(t!==this.lifecycleGeneration)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}async awaitSharedWorkerReady(){let e=this.sharedWorkerSelection;if(e.mode===`shared`)try{await e.ready}catch(e){if(this.disposed)return;if(this.options.sharedWorker?.fallback===`error`)throw e;this.sharedWorkerSelection={mode:`single-tab`,reason:e instanceof Error?e.message:`SharedWorker attach failed`}}}releaseSharedWorker(){let e=this.sharedWorkerSelection;if(this.sharedWorkerSelection={mode:`single-tab`,reason:`disposed`},e.mode===`shared`){try{e.client.request({version:1,type:`detach`,requestId:`detach-${e.tabId}`,tabId:e.tabId}).catch(()=>void 0)}catch{}e.client.close()}}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function me(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 he(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function Y(t){if(typeof t!=`object`||!t)throw new e.i(`CONFIG_INVALID`,`configuration`,!1);return t}function ge(n){let r={createSession:e=>n.createSession(e),refreshSession:e=>n.refreshSession===void 0?n.createSession({sdkVersion:t.r,platform:`web`}):n.refreshSession(e),deleteSession:async e=>{n.deleteSession!==void 0&&await n.deleteSession(e)},setAgentStatus:t=>n.setAgentStatus===void 0?Promise.reject(new e.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{cause:`当前会话来源不支持坐席状态设置(sessionProvider.setAgentStatus 未提供)`})):n.setAgentStatus(t)},i=n.invalidateToken;return i!==void 0&&(r.invalidateToken=()=>i()),r}function X(t){if(typeof t!=`object`||!t)throw new e.i(`CONFIG_INVALID`,`configuration`,!1);return t}function Z(t,n,r,i,a){return t instanceof e.i?new e.i(t.code,t.category,t.retryable,{requestId:t.requestId,callId:a??t.callId,cause:t.cause??t,serverCode:t.serverCode,status:t.status}):new e.i(n,r,i,{callId:a,cause:t})}function Q(t){return t instanceof e.i?t.status!==void 0&&t.status>=400&&t.status<500||t.serverCode===`SESSION_NOT_FOUND`||t.serverCode===`SESSION_EXPIRED`||t.serverCode===`TOKEN_INVALID`||t.serverCode===`TOKEN_EXPIRED`||t.code===`AUTH_TOKEN_UNAVAILABLE`||t.code===`AUTH_TOKEN_EXPIRED`:!1}function _e(t){return t instanceof e.i&&t.code===`SDK_ALREADY_DISPOSED`}function $(t){return t instanceof e.i&&(t.code===`SDK_ALREADY_DISPOSED`||t.code===`CALL_NOT_CONNECTED`)}var ve=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],ye=[`outbound`,`mute`,`dtmf`];function be(e){return e===`mobile-web`?ye:ve}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return i}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require("./redact-Bq26pObO.cjs");var t=`3.
|
|
1
|
+
const e=require("./redact-Bq26pObO.cjs");var t=`3.1.1`,n=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},r=`@16x/webphone-sdk`,i=200,a=class{dependencies;logs=new n(i);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(t,n,r){this.logs.push({timestamp:this.now().toISOString(),level:t,message:e.t(n),...r===void 0?{}:{context:e.n(r)}})}async getReport(n={}){let i=n.includeRecentLogs!==!1,a=n.includeDeviceNames===!0,u=n.maskPhoneNumbers!==!1,d=this.dependencies.getSnapshot(),f=this.dependencies.getPermission===void 0?d.permission:await o(this.dependencies.getPermission,d.permission),p=a?await s(this.dependencies.getDeviceNames):void 0,m=l(c(this.dependencies.getUserAgent)),h={generatedAt:this.now().toISOString(),sdk:{name:r,version:t},browser:m.browser,os:m.os,...d,permission:f,recentLogs:i?this.logs.toArray():[],...p===void 0?{}:{deviceNames:p}};return e.n(h,{maskPhoneNumbers:u})}};async function o(e,t){try{return await e()}catch{return t}}async function s(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function c(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function l(e){return{browser:u(e),os:d(e)}}function u(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function d(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./SharedWorkerProtocol-39dch6xL.cjs");require("./createJsSipFactory-Dr8HbLl-.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=25;function i(e){let t=Math.floor(Number(e.sip.registerExpires));return Number.isFinite(t)&&t>0?t:n}var a=class{factory;transportBaseUrl;keepaliveSeconds;ua;uaListeners;incomingHandlers;iceServers;pendingConnection;disposed=!1;keepaliveTimer;keepaliveBusy=!1;registerExpiresSeconds=0;connectionHandlers=new Set;constructor(e,t,n=r){this.factory=e,this.transportBaseUrl=t,this.keepaliveSeconds=n}keepaliveTick(e){if(this.isCurrentUa(e)&&!this.keepaliveBusy)try{if(typeof e.isConnected==`function`&&e.isConnected()===!1||typeof e.register!=`function`)return;this.keepaliveBusy=!0,e.register()}catch{}finally{this.keepaliveBusy=!1}}startKeepalive(e,t){if(this.stopKeepalive(),!Number.isFinite(this.keepaliveSeconds)||this.keepaliveSeconds<=0||t>0&&t<=this.keepaliveSeconds)return;let n=Math.max(10,Math.floor(this.keepaliveSeconds))*1e3;this.keepaliveTimer=setInterval(()=>this.keepaliveTick(e),n)}stopKeepalive(){this.keepaliveTimer!==void 0&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=void 0}connect(t){this.assertNotDisposed(),this.disconnect(this.registrationError(`SIP connection replaced`));try{let e=this.factory.createUa({sockets:l(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(t.transport.wssUrl)),t.transport.ticket)),uri:t.sip.uri,password:t.sip.registerTicket,registrar_server:t.sip.registrar,register:!0,register_expires:i(t)});return this.ua=e,this.registerExpiresSeconds=i(t),this.iceServers=t.iceServers,this.uaListeners=[],this.startRegistration(e)}catch(t){let n=t instanceof e.i&&t.code===`CONFIG_INVALID`?t:this.transportError(t);return this.disconnect(n),Promise.reject(n)}}disconnect(e=this.registrationError(`SIP connection disconnected`)){this.stopKeepalive();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.i(`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 o(r.call(t,e))}catch(t){throw new e.i(`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(!s(e))return;let t=e.session;if(t===void 0)return;let n=new o(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.startKeepalive(e,this.registerExpiresSeconds),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:`),this.assertAllowedWssUrl(n),n.toString()}assertAllowedWssUrl(t){if(t.protocol!==`wss:`&&!(t.protocol===`ws:`&&u(t.hostname)))throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:t.origin})}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.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.ua}assertNotDisposed(){if(this.disposed)throw new e.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}registrationError(t){return new e.i(`REGISTRATION_FAILED`,`registration`,!0,{cause:t})}transportError(t){return new e.i(`SIP_WS_UNAVAILABLE`,`registration`,!0,{cause:t})}registrationFailureCause(e){return typeof e==`object`&&e&&`cause`in e?e.cause:e}},o=class{session;pendingHoldReject;mediaRegistration;mediaConnection;constructor(e){this.session=e}get id(){return this.session.id}get from(){return this.session.from??d(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.i(`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 s(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.originator===`remote`&&c(t.session)}function c(e){return typeof e==`object`&&!!e&&`id`in e}function l(e){return typeof e==`object`&&e&&(e.via_transport=`WSS`),e}function u(e){let t=e.replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`0:0:0:0:0:0:0:1`}function d(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=a;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as e } from "./SharedWorkerProtocol-
|
|
1
|
+
import { i as e } from "./SharedWorkerProtocol-DKVQ5-po.js";
|
|
2
2
|
//#region src/sip/nativeMediaAdapter.ts
|
|
3
3
|
function t(e) {
|
|
4
4
|
let t = /* @__PURE__ */ new Map();
|
|
@@ -42,37 +42,63 @@ function t(e) {
|
|
|
42
42
|
}
|
|
43
43
|
//#endregion
|
|
44
44
|
//#region src/sip/JsSipAdapter.ts
|
|
45
|
-
var n = 300, r =
|
|
45
|
+
var n = 300, r = 25;
|
|
46
|
+
function i(e) {
|
|
47
|
+
let t = Math.floor(Number(e.sip.registerExpires));
|
|
48
|
+
return Number.isFinite(t) && t > 0 ? t : n;
|
|
49
|
+
}
|
|
50
|
+
var a = class {
|
|
46
51
|
factory;
|
|
47
52
|
transportBaseUrl;
|
|
53
|
+
keepaliveSeconds;
|
|
48
54
|
ua;
|
|
49
55
|
uaListeners;
|
|
50
56
|
incomingHandlers;
|
|
51
57
|
iceServers;
|
|
52
58
|
pendingConnection;
|
|
53
59
|
disposed = !1;
|
|
60
|
+
keepaliveTimer;
|
|
61
|
+
keepaliveBusy = !1;
|
|
62
|
+
registerExpiresSeconds = 0;
|
|
54
63
|
connectionHandlers = /* @__PURE__ */ new Set();
|
|
55
|
-
constructor(e, t) {
|
|
56
|
-
this.factory = e, this.transportBaseUrl = t;
|
|
64
|
+
constructor(e, t, n = r) {
|
|
65
|
+
this.factory = e, this.transportBaseUrl = t, this.keepaliveSeconds = n;
|
|
66
|
+
}
|
|
67
|
+
keepaliveTick(e) {
|
|
68
|
+
if (this.isCurrentUa(e) && !this.keepaliveBusy) try {
|
|
69
|
+
if (typeof e.isConnected == "function" && e.isConnected() === !1 || typeof e.register != "function") return;
|
|
70
|
+
this.keepaliveBusy = !0, e.register();
|
|
71
|
+
} catch {} finally {
|
|
72
|
+
this.keepaliveBusy = !1;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
startKeepalive(e, t) {
|
|
76
|
+
if (this.stopKeepalive(), !Number.isFinite(this.keepaliveSeconds) || this.keepaliveSeconds <= 0 || t > 0 && t <= this.keepaliveSeconds) return;
|
|
77
|
+
let n = Math.max(10, Math.floor(this.keepaliveSeconds)) * 1e3;
|
|
78
|
+
this.keepaliveTimer = setInterval(() => this.keepaliveTick(e), n);
|
|
79
|
+
}
|
|
80
|
+
stopKeepalive() {
|
|
81
|
+
this.keepaliveTimer !== void 0 && clearInterval(this.keepaliveTimer), this.keepaliveTimer = void 0;
|
|
57
82
|
}
|
|
58
83
|
connect(t) {
|
|
59
84
|
this.assertNotDisposed(), this.disconnect(this.registrationError("SIP connection replaced"));
|
|
60
85
|
try {
|
|
61
86
|
let e = this.factory.createUa({
|
|
62
|
-
sockets:
|
|
87
|
+
sockets: l(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(t.transport.wssUrl)), t.transport.ticket)),
|
|
63
88
|
uri: t.sip.uri,
|
|
64
89
|
password: t.sip.registerTicket,
|
|
65
90
|
registrar_server: t.sip.registrar,
|
|
66
91
|
register: !0,
|
|
67
|
-
register_expires:
|
|
92
|
+
register_expires: i(t)
|
|
68
93
|
});
|
|
69
|
-
return this.ua = e, this.iceServers = t.iceServers, this.uaListeners = [], this.startRegistration(e);
|
|
94
|
+
return this.ua = e, this.registerExpiresSeconds = i(t), this.iceServers = t.iceServers, this.uaListeners = [], this.startRegistration(e);
|
|
70
95
|
} catch (t) {
|
|
71
96
|
let n = t instanceof e && t.code === "CONFIG_INVALID" ? t : this.transportError(t);
|
|
72
97
|
return this.disconnect(n), Promise.reject(n);
|
|
73
98
|
}
|
|
74
99
|
}
|
|
75
100
|
disconnect(e = this.registrationError("SIP connection disconnected")) {
|
|
101
|
+
this.stopKeepalive();
|
|
76
102
|
let t = this.pendingConnection;
|
|
77
103
|
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
104
|
}
|
|
@@ -96,7 +122,7 @@ var n = 300, r = class {
|
|
|
96
122
|
pcConfig: { iceServers: [...n.iceServers] },
|
|
97
123
|
extraHeaders: [...n.extraHeaders, ...n.type === "extension" ? ["X-XCall-Destination-Type: extension"] : []]
|
|
98
124
|
};
|
|
99
|
-
return new
|
|
125
|
+
return new o(r.call(t, e));
|
|
100
126
|
} catch (t) {
|
|
101
127
|
throw new e("CALL_OPERATION_NOT_ALLOWED", "call", !1, { cause: t });
|
|
102
128
|
}
|
|
@@ -119,10 +145,10 @@ var n = 300, r = class {
|
|
|
119
145
|
};
|
|
120
146
|
}
|
|
121
147
|
handleIncoming(e) {
|
|
122
|
-
if (!
|
|
148
|
+
if (!s(e)) return;
|
|
123
149
|
let t = e.session;
|
|
124
150
|
if (t === void 0) return;
|
|
125
|
-
let n = new
|
|
151
|
+
let n = new o(t);
|
|
126
152
|
this.incomingHandlers?.forEach((e) => e(n));
|
|
127
153
|
}
|
|
128
154
|
startRegistration(e) {
|
|
@@ -176,14 +202,14 @@ var n = 300, r = class {
|
|
|
176
202
|
}
|
|
177
203
|
resolveConnection(e) {
|
|
178
204
|
let t = this.pendingConnection;
|
|
179
|
-
t?.ua === e && (this.pendingConnection = void 0, t.resolve(), this.connectionHandlers.forEach((e) => e("registered")));
|
|
205
|
+
t?.ua === e && (this.pendingConnection = void 0, t.resolve(), this.startKeepalive(e, this.registerExpiresSeconds), this.connectionHandlers.forEach((e) => e("registered")));
|
|
180
206
|
}
|
|
181
207
|
resolveWssUrl(e) {
|
|
182
208
|
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
209
|
return n.protocol === "http:" && (n.protocol = "ws:"), n.protocol === "https:" && (n.protocol = "wss:"), this.assertAllowedWssUrl(n), n.toString();
|
|
184
210
|
}
|
|
185
211
|
assertAllowedWssUrl(t) {
|
|
186
|
-
if (t.protocol !== "wss:" && !(t.protocol === "ws:" &&
|
|
212
|
+
if (t.protocol !== "wss:" && !(t.protocol === "ws:" && u(t.hostname))) throw new e("CONFIG_INVALID", "configuration", !1, { cause: t.origin });
|
|
187
213
|
}
|
|
188
214
|
withoutTicket(e) {
|
|
189
215
|
let t = new URL(e);
|
|
@@ -205,7 +231,7 @@ var n = 300, r = class {
|
|
|
205
231
|
registrationFailureCause(e) {
|
|
206
232
|
return typeof e == "object" && e && "cause" in e ? e.cause : e;
|
|
207
233
|
}
|
|
208
|
-
},
|
|
234
|
+
}, o = class {
|
|
209
235
|
session;
|
|
210
236
|
pendingHoldReject;
|
|
211
237
|
mediaRegistration;
|
|
@@ -217,7 +243,7 @@ var n = 300, r = class {
|
|
|
217
243
|
return this.session.id;
|
|
218
244
|
}
|
|
219
245
|
get from() {
|
|
220
|
-
return this.session.from ??
|
|
246
|
+
return this.session.from ?? d(this.session.remote_identity);
|
|
221
247
|
}
|
|
222
248
|
getMediaRegistration() {
|
|
223
249
|
let e = this.session.connection;
|
|
@@ -285,22 +311,22 @@ var n = 300, r = class {
|
|
|
285
311
|
});
|
|
286
312
|
}
|
|
287
313
|
};
|
|
288
|
-
function
|
|
314
|
+
function s(e) {
|
|
289
315
|
if (typeof e != "object" || !e) return !1;
|
|
290
316
|
let t = e;
|
|
291
|
-
return t.originator === "remote" &&
|
|
317
|
+
return t.originator === "remote" && c(t.session);
|
|
292
318
|
}
|
|
293
|
-
function
|
|
319
|
+
function c(e) {
|
|
294
320
|
return typeof e == "object" && !!e && "id" in e;
|
|
295
321
|
}
|
|
296
|
-
function
|
|
322
|
+
function l(e) {
|
|
297
323
|
return typeof e == "object" && e && (e.via_transport = "WSS"), e;
|
|
298
324
|
}
|
|
299
|
-
function
|
|
325
|
+
function u(e) {
|
|
300
326
|
let t = e.replace(/^\[|\]$/g, "").toLowerCase();
|
|
301
327
|
return t === "localhost" || t === "127.0.0.1" || t === "::1" || t === "0:0:0:0:0:0:0:1";
|
|
302
328
|
}
|
|
303
|
-
function
|
|
329
|
+
function d(e) {
|
|
304
330
|
let t = e?.uri;
|
|
305
331
|
if (t == null) return;
|
|
306
332
|
if (typeof t.user == "string" && t.user !== "") return t.user;
|
|
@@ -308,4 +334,4 @@ function l(e) {
|
|
|
308
334
|
return n.match(/^sips?:([^@;>]+)/i)?.[1] ?? (n === "" ? void 0 : n);
|
|
309
335
|
}
|
|
310
336
|
//#endregion
|
|
311
|
-
export {
|
|
337
|
+
export { a as JsSipAdapter };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./redact-Bq26pObO.cjs");var t=class extends Error{code;category;retryable;requestId;callId;cause;serverCode;status;constructor(e,t,n,r={}){super(e),this.name=`CCBarError`,this.code=e,this.category=t,this.retryable=n,this.requestId=r.requestId,this.callId=r.callId,this.cause=r.cause,this.serverCode=r.serverCode,this.status=r.status}},n=[`new`,`dialing`,`ringing`,`connecting`,`active`,`held`,`ended`,`failed`];function r(e){if(!c(e)||typeof e.id!=`string`||typeof e.destination!=`string`||typeof e.incoming!=`boolean`||!s(e.state))throw u(`Invalid call snapshot`);return{id:e.id,...typeof e.from==`string`?{from:e.from}:{},destination:e.destination,state:e.state,incoming:e.incoming,...typeof e.ownerTabId==`string`?{ownerTabId:e.ownerTabId}:{}}}function i(e){return e instanceof t?{code:e.code,category:e.category,retryable:e.retryable,...e.requestId===void 0?{}:{requestId:e.requestId},...e.callId===void 0?{}:{callId:e.callId},...e.serverCode===void 0?{}:{serverCode:e.serverCode},...e.status===void 0?{}:{status:e.status},message:l(e.message)}:{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!1,message:l(e instanceof Error?e.message:String(e))}}function a(e){if(!c(e))throw u(`Invalid worker message`);if(e.version!==1)throw u(`Unsupported worker protocol version`);if(e.type===`attach`||e.type===`detach`)return o(e),e;if(e.type===`command`){if(o(e),typeof e.command!=`string`||e.payload!==void 0&&!c(e.payload))throw u(`Invalid worker command`);return e}if(e.type===`response`){if(typeof e.requestId!=`string`||typeof e.ok!=`boolean`)throw u(`Invalid worker response`);return e}if(e.type===`event`){if(typeof e.event!=`string`||!(`payload`in e))throw u(`Invalid worker event`);return e}throw u(`Unknown worker message type`)}function o(e){if(typeof e.requestId!=`string`||typeof e.tabId!=`string`)throw u(`Worker request requires requestId and tabId`)}function s(e){return typeof e==`string`&&n.includes(e)}function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(t){return e.t(t).replace(/(?:authorization|token|ticket|credential|password|secret)/gi,`[REDACTED]`)}function u(e){return new t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
|
|
@@ -7,8 +7,10 @@ var t = class extends Error {
|
|
|
7
7
|
requestId;
|
|
8
8
|
callId;
|
|
9
9
|
cause;
|
|
10
|
+
serverCode;
|
|
11
|
+
status;
|
|
10
12
|
constructor(e, t, n, r = {}) {
|
|
11
|
-
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;
|
|
13
|
+
super(e), this.name = "CCBarError", this.code = e, this.category = t, this.retryable = n, this.requestId = r.requestId, this.callId = r.callId, this.cause = r.cause, this.serverCode = r.serverCode, this.status = r.status;
|
|
12
14
|
}
|
|
13
15
|
}, n = [
|
|
14
16
|
"new",
|
|
@@ -38,6 +40,8 @@ function i(e) {
|
|
|
38
40
|
retryable: e.retryable,
|
|
39
41
|
...e.requestId === void 0 ? {} : { requestId: e.requestId },
|
|
40
42
|
...e.callId === void 0 ? {} : { callId: e.callId },
|
|
43
|
+
...e.serverCode === void 0 ? {} : { serverCode: e.serverCode },
|
|
44
|
+
...e.status === void 0 ? {} : { status: e.status },
|
|
41
45
|
message: l(e.message)
|
|
42
46
|
} : {
|
|
43
47
|
code: "SDK_INTERNAL_ERROR",
|
|
@@ -1,18 +1,42 @@
|
|
|
1
|
-
import { MediaConstraints, WebPhoneSession } from '../api/contracts.js';
|
|
1
|
+
import { AgentStatusRequest, CreateSessionRequest, MediaConstraints, WebPhoneSession } from '../api/contracts.js';
|
|
2
2
|
import { TokenProvider } from '../auth/TokenManager.js';
|
|
3
3
|
import { CCBarEvents, MediaManager as PublicMedia, SharedWorkerOptions, SharedWorkerState } from '../types.js';
|
|
4
4
|
import { SharedWorkerConstructor } from '../shared/SharedWorkerFactory.js';
|
|
5
5
|
import { DialOptions } from './CallManager.js';
|
|
6
6
|
import { CCBarCall, CallPlatform } from './CCBarCall.js';
|
|
7
7
|
import { DiagnosticsOptions, DiagnosticsReport } from '../diagnostics/Diagnostics.js';
|
|
8
|
+
/**
|
|
9
|
+
* 自定义会话来源:给「没有新版 WebPhone API」的旧平台/自建网关用。
|
|
10
|
+
* 提供后 SDK 不再请求 `POST {baseUrl}/webphone/v1/sessions`,完全由这里给会话;
|
|
11
|
+
* 签名、解密等必须在服务端做的事,由接入方自己的接口完成。
|
|
12
|
+
*/
|
|
13
|
+
export interface SessionProvider {
|
|
14
|
+
createSession(request: CreateSessionRequest): Promise<WebPhoneSession>;
|
|
15
|
+
/** 缺省时用 createSession 重建 */
|
|
16
|
+
refreshSession?(sessionId: string): Promise<WebPhoneSession>;
|
|
17
|
+
/** 缺省时不做清理 */
|
|
18
|
+
deleteSession?(sessionId: string): Promise<void>;
|
|
19
|
+
/** 缺省时调用 setAgentStatus 会抛 CAPABILITY_NOT_SUPPORTED */
|
|
20
|
+
setAgentStatus?(request: AgentStatusRequest): Promise<void>;
|
|
21
|
+
invalidateToken?(): void;
|
|
22
|
+
}
|
|
8
23
|
export interface CCBarClientOptions {
|
|
9
24
|
readonly baseUrl?: string;
|
|
10
|
-
|
|
25
|
+
/** 用 sessionProvider 时可以省略(那条路不发 token 请求) */
|
|
26
|
+
readonly tokenProvider?: TokenProvider;
|
|
27
|
+
/** 自己提供会话(旧平台兼容模式);与 tokenProvider + 新版 API 二选一 */
|
|
28
|
+
readonly sessionProvider?: SessionProvider;
|
|
11
29
|
readonly locale?: string;
|
|
12
30
|
readonly platform?: CallPlatform;
|
|
13
31
|
readonly requestedCapabilities?: readonly string[];
|
|
14
32
|
readonly maxConcurrentCalls?: number;
|
|
15
33
|
readonly autoHoldPreviousCall?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* 已注册时主动重发 REGISTER 的间隔(秒),用来撑住 NAT/代理上的长连接,默认 25;0 = 关闭。
|
|
36
|
+
* 浏览器发不了 WebSocket ping,中间设备(nginx/NAT)会静默掐掉空闲的 WSS:
|
|
37
|
+
* 页面还显示已注册,下一次 INVITE 却直接失败。
|
|
38
|
+
*/
|
|
39
|
+
readonly sipKeepaliveSeconds?: number;
|
|
16
40
|
/** SharedWorker attach/close is attempted when this option is provided. SIP remains tab-local until the next-minor adapter. */
|
|
17
41
|
readonly sharedWorker?: SharedWorkerOptions;
|
|
18
42
|
/** @internal Test/integration dependency injection; not required by consumers. */
|
|
@@ -43,6 +67,7 @@ export declare class CCBarClient {
|
|
|
43
67
|
private disposed;
|
|
44
68
|
private intentionalDisconnect;
|
|
45
69
|
private deferredRebuild;
|
|
70
|
+
private sessionRecoveryPending;
|
|
46
71
|
private detectedPlatform?;
|
|
47
72
|
private support?;
|
|
48
73
|
private acceptingEvents;
|
|
@@ -98,6 +123,7 @@ export declare class CCBarClient {
|
|
|
98
123
|
private refreshAndRebuild;
|
|
99
124
|
private performRefreshAndRebuild;
|
|
100
125
|
private handleRefreshFailure;
|
|
126
|
+
private recoverInvalidSession;
|
|
101
127
|
private scheduleRefresh;
|
|
102
128
|
private recoverConnection;
|
|
103
129
|
private getSip;
|
|
@@ -9647,12 +9647,15 @@ var xe = class extends ye.WebSocketInterface {
|
|
|
9647
9647
|
constructor(e, t) {
|
|
9648
9648
|
super(e), this.ticket = t;
|
|
9649
9649
|
}
|
|
9650
|
+
protocols() {
|
|
9651
|
+
return this.ticket === "" ? ["sip"] : [`xcall-ticket.${this.ticket}`, "sip"];
|
|
9652
|
+
}
|
|
9650
9653
|
connect() {
|
|
9651
9654
|
if (this.isConnected() || this.isConnecting()) return;
|
|
9652
9655
|
let e = this;
|
|
9653
9656
|
e._ws && this.disconnect();
|
|
9654
9657
|
try {
|
|
9655
|
-
e._ws = new WebSocket(this.url,
|
|
9658
|
+
e._ws = new WebSocket(this.url, this.protocols()), e._ws.binaryType = "arraybuffer", e._ws.onopen = e._onOpen.bind(this), e._ws.onclose = e._onClose.bind(this), e._ws.onmessage = e._onMessage.bind(this), e._ws.onerror = e._onError.bind(this);
|
|
9656
9659
|
} catch (t) {
|
|
9657
9660
|
e._onError.call(this, t);
|
|
9658
9661
|
}
|
|
@@ -72,4 +72,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
72
72
|
`,i+=`CSeq: ${p.cseq} ${p.method}\r
|
|
73
73
|
`,i+=`\r
|
|
74
74
|
`,h.send(i)}})),ge=s((e=>{function t(e,t){var r;if(typeof Symbol>`u`||e[Symbol.iterator]==null){if(Array.isArray(e)||(r=n(e))||t&&e&&typeof e.length==`number`){r&&(e=r);var i=0,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
75
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,c;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return o=e.done,e},e:function(e){s=!0,c=e},f:function(){try{!o&&r.return!=null&&r.return()}finally{if(s)throw c}}}}function n(e,t){if(e){if(typeof e==`string`)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(e,t)}}function r(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var i=P(),a=k(),o=M(),s=N(),c=fe(),l=A();e.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:a.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:a.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:a.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${i.createRandomToken(12)}.invalid`};var u={mandatory:{sockets:function(e){var n=[];if(c.isSocket(e))n.push({socket:e});else if(Array.isArray(e)&&e.length){var r=t(e),i;try{for(r.s();!(i=r.n()).done;){var a=i.value;Object.prototype.hasOwnProperty.call(a,`socket`)&&c.isSocket(a.socket)?n.push(a):c.isSocket(a)&&n.push({socket:a})}}catch(e){r.e(e)}finally{r.f()}}else return;return n},uri:function(e){/^sip:/i.test(e)||(e=`${a.SIP}:${e}`);var t=s.parse(e);if(t&&t.user)return t}},optional:{authorization_user:function(e){if(o.parse(`"${e}"`,`quoted_string`)!==-1)return e},authorization_jwt:function(e){if(typeof e==`string`)return e},user_agent:function(e){if(typeof e==`string`)return e},connection_recovery_max_interval:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},connection_recovery_min_interval:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},contact_uri:function(e){if(typeof e==`string`){var t=o.parse(e,`SIP_URI`);if(t!==-1)return t}},display_name:function(e){return e},instance_id:function(e){if(/^uuid:/i.test(e)&&(e=e.substr(5)),o.parse(e,`uuid`)!==-1)return e},no_answer_timeout:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},session_timers:function(e){if(typeof e==`boolean`)return e},session_timers_refresh_method:function(e){if(typeof e==`string`&&(e=e.toUpperCase(),e===a.INVITE||e===a.UPDATE))return e},session_timers_force_refresher:function(e){if(typeof e==`boolean`)return e},password:function(e){return String(e)},realm:function(e){return String(e)},ha1:function(e){return String(e)},register:function(e){if(typeof e==`boolean`)return e},register_expires:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},registrar_server:function(e){/^sip:/i.test(e)||(e=`${a.SIP}:${e}`);var t=s.parse(e);if(t&&!t.user)return t},use_preloaded_route:function(e){if(typeof e==`boolean`)return e},extra_headers:function(e){var n=[];if(Array.isArray(e)&&e.length){var r=t(e),i;try{for(r.s();!(i=r.n()).done;){var a=i.value;typeof a==`string`&&n.push(a)}}catch(e){r.e(e)}finally{r.f()}}else return;return n}}};e.load=function(e,t){for(var n in u.mandatory)if(t.hasOwnProperty(n)){var r=t[n],a=u.mandatory[n](r);if(a!==void 0)e[n]=a;else throw new l.ConfigurationError(n,r)}else throw new l.ConfigurationError(n);for(var o in u.optional)if(t.hasOwnProperty(o)){var s=t[o];if(i.isEmpty(s))continue;var c=u.optional[o](s);if(c!==void 0)e[o]=c;else throw new l.ConfigurationError(o,s)}}})),_e=s(((e,t)=>{function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function a(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}function o(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}function s(e,t){return s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},s(e,t)}function c(e){var t=d();return function(){var n=f(e),r;if(t){var i=f(this).constructor;r=Reflect.construct(n,arguments,i)}else r=n.apply(this,arguments);return l(this,r)}}function l(e,t){return t&&(n(t)===`object`||typeof t==`function`)?t:u(e)}function u(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function d(){if(typeof Reflect>`u`||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy==`function`)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function f(e){return f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},f(e)}var p=F().EventEmitter,m=z(),h=k(),g=ie(),_=le(),v=ue(),y=de(),b=U(),x=pe(),S=P(),C=A(),w=N(),T=me(),E=V(),D=he(),O=ge(),j=new m(`UA`),M={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};t.exports=function(e){o(n,e);var t=c(n);a(n,null,[{key:`C`,get:function(){return M}}]);function n(e){var i;if(r(this,n),j.debug(`new() [configuration:%o]`,e),i=t.call(this),i._cache={credentials:{}},i._configuration=Object.assign({},O.settings),i._dynConfiguration={},i._dialogs={},i._applicants={},i._sessions={},i._transport=null,i._contact=null,i._status=M.STATUS_INIT,i._error=null,i._transactions={nist:{},nict:{},ist:{},ict:{}},i._data={},i._closeTimer=null,e===void 0)throw TypeError(`Not enough arguments`);try{i._loadConfig(e)}catch(e){throw i._status=M.STATUS_NOT_READY,i._error=M.CONFIGURATION_ERROR,e}return i._registrator=new g(u(i)),i}return a(n,[{key:`start`,value:function(){j.debug(`start()`),this._status===M.STATUS_INIT?this._transport.connect():this._status===M.STATUS_USER_CLOSED?(j.debug(`restarting UA`),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=M.STATUS_INIT,this._transport.connect()):this._status===M.STATUS_READY?j.debug(`UA is in READY status, not restarted`):j.debug(`ERROR: connection is down, Auto-Recovery system is trying to reconnect`),this._dynConfiguration.register=this._configuration.register}},{key:`register`,value:function(){j.debug(`register()`),this._dynConfiguration.register=!0,this._registrator.register()}},{key:`unregister`,value:function(e){j.debug(`unregister()`),this._dynConfiguration.register=!1,this._registrator.unregister(e)}},{key:`registrator`,value:function(){return this._registrator}},{key:`isRegistered`,value:function(){return this._registrator.registered}},{key:`isConnected`,value:function(){return this._transport.isConnected()}},{key:`call`,value:function(e,t){j.debug(`call()`);var n=new _(this);return n.connect(e,t),n}},{key:`sendMessage`,value:function(e,t,n){j.debug(`sendMessage()`);var r=new v(this);return r.send(e,t,n),r}},{key:`sendOptions`,value:function(e,t,n){j.debug(`sendOptions()`);var r=new y(this);return r.send(e,t,n),r}},{key:`terminateSessions`,value:function(e){for(var t in j.debug(`terminateSessions()`),this._sessions)this._sessions[t].isEnded()||this._sessions[t].terminate(e)}},{key:`stop`,value:function(){var e=this;if(j.debug(`stop()`),this._dynConfiguration={},this._status===M.STATUS_USER_CLOSED){j.debug(`UA already closed`);return}this._registrator.close();var t=Object.keys(this._sessions).length;for(var n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){j.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch{}}for(var r in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,r))try{this._applicants[r].close()}catch{}this._status=M.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){e._closeTimer=null,e._transport.disconnect()},2e3)}},{key:`normalizeTarget`,value:function(e){return S.normalizeTarget(e,this._configuration.hostport_params)}},{key:`get`,value:function(e){switch(e){case`authorization_user`:return this._configuration.authorization_user;case`realm`:return this._configuration.realm;case`ha1`:return this._configuration.ha1;case`authorization_jwt`:return this._configuration.authorization_jwt;default:j.warn(`get() | cannot get "%s" parameter in runtime`,e);return}}},{key:`set`,value:function(e,t){switch(e){case`authorization_user`:this._configuration.authorization_user=String(t);break;case`password`:this._configuration.password=String(t);break;case`realm`:this._configuration.realm=String(t);break;case`ha1`:this._configuration.ha1=String(t),this._configuration.password=null;break;case`authorization_jwt`:this._configuration.authorization_jwt=String(t);break;case`display_name`:this._configuration.display_name=t;break;case`extra_headers`:this._configuration.extra_headers=t;break;default:return j.warn(`set() | cannot set "%s" parameter in runtime`,e),!1}return!0}},{key:`newTransaction`,value:function(e){this._transactions[e.type][e.id]=e,this.emit(`newTransaction`,{transaction:e})}},{key:`destroyTransaction`,value:function(e){delete this._transactions[e.type][e.id],this.emit(`transactionDestroyed`,{transaction:e})}},{key:`newDialog`,value:function(e){this._dialogs[e.id]=e}},{key:`destroyDialog`,value:function(e){delete this._dialogs[e.id]}},{key:`newMessage`,value:function(e,t){this._applicants[e]=e,this.emit(`newMessage`,t)}},{key:`newOptions`,value:function(e,t){this._applicants[e]=e,this.emit(`newOptions`,t)}},{key:`destroyMessage`,value:function(e){delete this._applicants[e]}},{key:`newRTCSession`,value:function(e,t){this._sessions[e.id]=e,this.emit(`newRTCSession`,t)}},{key:`destroyRTCSession`,value:function(e){delete this._sessions[e.id]}},{key:`registered`,value:function(e){this.emit(`registered`,e)}},{key:`unregistered`,value:function(e){this.emit(`unregistered`,e)}},{key:`registrationFailed`,value:function(e){this.emit(`registrationFailed`,e)}},{key:`receiveRequest`,value:function(e){var t=e.method;if(e.ruri.user!==this._configuration.uri.user&&e.ruri.user!==this._contact.uri.user){j.debug(`Request-URI does not point to us`),e.method!==h.ACK&&e.reply_sl(404);return}if(e.ruri.scheme===h.SIPS){e.reply_sl(416);return}if(!b.checkTransaction(this,e)){if(t===h.INVITE?new b.InviteServerTransaction(this,this._transport,e):t!==h.ACK&&t!==h.CANCEL&&new b.NonInviteServerTransaction(this,this._transport,e),t===h.OPTIONS){if(this.listeners(`newOptions`).length===0){e.reply(200);return}new y(this).init_incoming(e)}else if(t===h.MESSAGE){if(this.listeners(`newMessage`).length===0){e.reply(405);return}new v(this).init_incoming(e)}else if(t===h.INVITE&&!e.to_tag&&this.listeners(`newRTCSession`).length===0){e.reply(405);return}var n,r;if(e.to_tag)n=this._findDialog(e.call_id,e.from_tag,e.to_tag),n?n.receiveRequest(e):t===h.NOTIFY?(r=this._findSession(e),r?r.receiveRequest(e):(j.debug(`received NOTIFY request for a non existent subscription`),e.reply(481,`Subscription does not exist`))):t!==h.ACK&&e.reply(481);else switch(t){case h.INVITE:if(window.RTCPeerConnection){if(e.hasHeader(`replaces`)){var i=e.replaces;n=this._findDialog(i.call_id,i.from_tag,i.to_tag),n?(r=n.owner,r.isEnded()?e.reply(603):r.receiveRequest(e)):e.reply(481)}else r=new _(this),r.init_incoming(e)}else j.warn(`INVITE received but WebRTC is not supported`),e.reply(488);break;case h.BYE:e.reply(481);break;case h.CANCEL:r=this._findSession(e),r?r.receiveRequest(e):j.debug(`received CANCEL request for a non existent session`);break;case h.ACK:break;case h.NOTIFY:this.emit(`sipEvent`,{event:e.event,request:e}),e.reply(200);break;default:e.reply(405)}}}},{key:`_findSession`,value:function(e){var t=e.call_id,n=e.from_tag,r=e.to_tag,i=t+n,a=this._sessions[i],o=t+r,s=this._sessions[o];return a||s||null}},{key:`_findDialog`,value:function(e,t,n){var r=e+t+n,i=this._dialogs[r];return i||(r=e+n+t,i=this._dialogs[r],i||null)}},{key:`_loadConfig`,value:function(e){try{O.load(this._configuration,e)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name=`0`),this._configuration.instance_id||(this._configuration.instance_id=S.newUUID()),this._configuration.jssip_id=S.createRandomToken(5);var t=this._configuration.uri.clone();t.user=null,this._configuration.hostport_params=t.toString().replace(/^sip:/i,``);try{this._transport=new x(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=I.bind(this),this._transport.onconnect=L.bind(this),this._transport.ondisconnect=R.bind(this),this._transport.ondata=B.bind(this)}catch(e){throw j.warn(e),new C.ConfigurationError(`sockets`,this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){var n=this._configuration.uri.clone();n.user=null,n.clearParams(),n.clearHeaders(),this._configuration.registrar_server=n}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new w(`sip`,S.createRandomToken(8),this._configuration.via_host,null,{transport:`ws`}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.anonymous||null,n=e.outbound||null,r=`<`;return r+=t?this.temp_gruu||`sip:anonymous@anonymous.invalid;transport=ws`:this.pub_gruu||this.uri.toString(),n&&(t?!this.temp_gruu:!this.pub_gruu)&&(r+=`;ob`),r+=`>`,r}};var r=[`authorization_user`,`password`,`realm`,`ha1`,`authorization_jwt`,`display_name`,`register`,`extra_headers`];for(var i in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,i)&&(r.indexOf(i)===-1?Object.defineProperty(this._configuration,i,{writable:!1,configurable:!1}):Object.defineProperty(this._configuration,i,{writable:!0,configurable:!1}));for(var a in j.debug(`configuration parameters after validation:`),this._configuration)if(Object.prototype.hasOwnProperty.call(O.settings,a))switch(a){case`uri`:case`registrar_server`:j.debug(`- ${a}: ${this._configuration[a]}`);break;case`password`:case`ha1`:case`authorization_jwt`:j.debug(`- ${a}: NOT SHOWN`);break;default:j.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}},{key:`C`,get:function(){return M}},{key:`status`,get:function(){return this._status}},{key:`contact`,get:function(){return this._contact}},{key:`configuration`,get:function(){return this._configuration}},{key:`transport`,get:function(){return this._transport}}]),n}(p);function I(e){this.emit(`connecting`,e)}function L(e){this._status!==M.STATUS_USER_CLOSED&&(this._status=M.STATUS_READY,this._error=null,this.emit(`connected`,e),this._dynConfiguration.register&&this._registrator.register())}function R(e){for(var t=[`nict`,`ict`,`nist`,`ist`],n=0,r=t;n<r.length;n++){var i=r[n];for(var a in this._transactions[i])Object.prototype.hasOwnProperty.call(this._transactions[i],a)&&this._transactions[i][a].onTransportError()}this.emit(`disconnected`,e),this._registrator.onTransportClosed(),this._status!==M.STATUS_USER_CLOSED&&(this._status=M.STATUS_NOT_READY,this._error=M.NETWORK_ERROR)}function B(e){var t=e.transport,n=e.message;if(n=T.parseMessage(n,this),n&&!(this._status===M.STATUS_USER_CLOSED&&n instanceof E.IncomingRequest)&&D(n,this,t)){if(n instanceof E.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof E.IncomingResponse){var r;switch(n.method){case h.INVITE:r=this._transactions.ict[n.via_branch],r&&r.receiveResponse(n);break;case h.ACK:break;default:r=this._transactions.nict[n.via_branch],r&&r.receiveResponse(n)}}}}})),ve=s(((e,t)=>{function n(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}var a=z(),o=M(),s=new a(`WebSocketInterface`);t.exports=function(){function e(t){n(this,e),s.debug(`new() [url:"%s"]`,t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var r=o.parse(t,`absoluteURI`);if(r===-1)throw s.warn(`invalid WebSocket URI: ${t}`),TypeError(`Invalid argument: ${t}`);if(r.scheme!==`wss`&&r.scheme!==`ws`)throw s.warn(`invalid WebSocket URI scheme: ${r.scheme}`),TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:``};transport=ws`,this._via_transport=r.scheme.toUpperCase()}return i(e,[{key:`connect`,value:function(){if(s.debug(`connect()`),this.isConnected()){s.debug(`WebSocket ${this._url} is already connected`);return}if(this.isConnecting()){s.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),s.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,`sip`),this._ws.binaryType=`arraybuffer`,this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(e){this._onError(e)}}},{key:`disconnect`,value:function(){s.debug(`disconnect()`),this._ws&&=(this._ws.onopen=function(){},this._ws.onclose=function(){},this._ws.onmessage=function(){},this._ws.onerror=function(){},this._ws.close(),null)}},{key:`send`,value:function(e){return s.debug(`send()`),this.isConnected()?(this._ws.send(e),!0):(s.warn(`unable to send message, WebSocket is not open`),!1)}},{key:`isConnected`,value:function(){return this._ws&&this._ws.readyState===this._ws.OPEN}},{key:`isConnecting`,value:function(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}},{key:`_onOpen`,value:function(){s.debug(`WebSocket ${this._url} connected`),this.onconnect()}},{key:`_onClose`,value:function(e){var t=e.wasClean,n=e.code,r=e.reason;s.debug(`WebSocket ${this._url} closed`),t===!1&&s.debug(`WebSocket abrupt disconnection`),this.ondisconnect(!t,n,r)}},{key:`_onMessage`,value:function(e){var t=e.data;s.debug(`received WebSocket message`),this.ondata(t)}},{key:`_onError`,value:function(e){s.warn(`WebSocket ${this._url} error: `,e)}},{key:`via_transport`,get:function(){return this._via_transport},set:function(e){this._via_transport=e.toUpperCase()}},{key:`sip_uri`,get:function(){return this._sip_uri}},{key:`url`,get:function(){return this._url}}]),e}()})),ye=u(s(((e,t)=>{var n=(O(),d(f).default),r=k(),i=A(),a=P(),o=_e(),s=N(),c=j(),l=M(),u=ve();R()(`JsSIP`)(`version %s`,n.version),t.exports={C:r,Exceptions:i,Utils:a,UA:o,URI:s,NameAddrHeader:c,WebSocketInterface:u,Grammar:l,debug:R(),get name(){return n.title},get version(){return n.version}}}))(),1);function be(){return{createSocket:(e,t)=>new xe(e,t),createUa:e=>new ye.UA(e)}}var xe=class extends ye.WebSocketInterface{ticket;constructor(e,t){super(e),this.ticket=t}connect(){if(this.isConnected()||this.isConnecting())return;let e=this;e._ws&&this.disconnect();try{e._ws=new WebSocket(this.url,[`xcall-ticket.${this.ticket}`,`sip`]),e._ws.binaryType=`arraybuffer`,e._ws.onopen=e._onOpen.bind(this),e._ws.onclose=e._onClose.bind(this),e._ws.onmessage=e._onMessage.bind(this),e._ws.onerror=e._onError.bind(this)}catch(t){e._onError.call(this,t)}}};exports.createJsSipFactory=be,exports.t=d;
|
|
75
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,c;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return o=e.done,e},e:function(e){s=!0,c=e},f:function(){try{!o&&r.return!=null&&r.return()}finally{if(s)throw c}}}}function n(e,t){if(e){if(typeof e==`string`)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(e,t)}}function r(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var i=P(),a=k(),o=M(),s=N(),c=fe(),l=A();e.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:a.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:a.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:a.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${i.createRandomToken(12)}.invalid`};var u={mandatory:{sockets:function(e){var n=[];if(c.isSocket(e))n.push({socket:e});else if(Array.isArray(e)&&e.length){var r=t(e),i;try{for(r.s();!(i=r.n()).done;){var a=i.value;Object.prototype.hasOwnProperty.call(a,`socket`)&&c.isSocket(a.socket)?n.push(a):c.isSocket(a)&&n.push({socket:a})}}catch(e){r.e(e)}finally{r.f()}}else return;return n},uri:function(e){/^sip:/i.test(e)||(e=`${a.SIP}:${e}`);var t=s.parse(e);if(t&&t.user)return t}},optional:{authorization_user:function(e){if(o.parse(`"${e}"`,`quoted_string`)!==-1)return e},authorization_jwt:function(e){if(typeof e==`string`)return e},user_agent:function(e){if(typeof e==`string`)return e},connection_recovery_max_interval:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},connection_recovery_min_interval:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},contact_uri:function(e){if(typeof e==`string`){var t=o.parse(e,`SIP_URI`);if(t!==-1)return t}},display_name:function(e){return e},instance_id:function(e){if(/^uuid:/i.test(e)&&(e=e.substr(5)),o.parse(e,`uuid`)!==-1)return e},no_answer_timeout:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},session_timers:function(e){if(typeof e==`boolean`)return e},session_timers_refresh_method:function(e){if(typeof e==`string`&&(e=e.toUpperCase(),e===a.INVITE||e===a.UPDATE))return e},session_timers_force_refresher:function(e){if(typeof e==`boolean`)return e},password:function(e){return String(e)},realm:function(e){return String(e)},ha1:function(e){return String(e)},register:function(e){if(typeof e==`boolean`)return e},register_expires:function(e){if(i.isDecimal(e)){var t=Number(e);if(t>0)return t}},registrar_server:function(e){/^sip:/i.test(e)||(e=`${a.SIP}:${e}`);var t=s.parse(e);if(t&&!t.user)return t},use_preloaded_route:function(e){if(typeof e==`boolean`)return e},extra_headers:function(e){var n=[];if(Array.isArray(e)&&e.length){var r=t(e),i;try{for(r.s();!(i=r.n()).done;){var a=i.value;typeof a==`string`&&n.push(a)}}catch(e){r.e(e)}finally{r.f()}}else return;return n}}};e.load=function(e,t){for(var n in u.mandatory)if(t.hasOwnProperty(n)){var r=t[n],a=u.mandatory[n](r);if(a!==void 0)e[n]=a;else throw new l.ConfigurationError(n,r)}else throw new l.ConfigurationError(n);for(var o in u.optional)if(t.hasOwnProperty(o)){var s=t[o];if(i.isEmpty(s))continue;var c=u.optional[o](s);if(c!==void 0)e[o]=c;else throw new l.ConfigurationError(o,s)}}})),_e=s(((e,t)=>{function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function a(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}function o(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}function s(e,t){return s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},s(e,t)}function c(e){var t=d();return function(){var n=f(e),r;if(t){var i=f(this).constructor;r=Reflect.construct(n,arguments,i)}else r=n.apply(this,arguments);return l(this,r)}}function l(e,t){return t&&(n(t)===`object`||typeof t==`function`)?t:u(e)}function u(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function d(){if(typeof Reflect>`u`||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy==`function`)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function f(e){return f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},f(e)}var p=F().EventEmitter,m=z(),h=k(),g=ie(),_=le(),v=ue(),y=de(),b=U(),x=pe(),S=P(),C=A(),w=N(),T=me(),E=V(),D=he(),O=ge(),j=new m(`UA`),M={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};t.exports=function(e){o(n,e);var t=c(n);a(n,null,[{key:`C`,get:function(){return M}}]);function n(e){var i;if(r(this,n),j.debug(`new() [configuration:%o]`,e),i=t.call(this),i._cache={credentials:{}},i._configuration=Object.assign({},O.settings),i._dynConfiguration={},i._dialogs={},i._applicants={},i._sessions={},i._transport=null,i._contact=null,i._status=M.STATUS_INIT,i._error=null,i._transactions={nist:{},nict:{},ist:{},ict:{}},i._data={},i._closeTimer=null,e===void 0)throw TypeError(`Not enough arguments`);try{i._loadConfig(e)}catch(e){throw i._status=M.STATUS_NOT_READY,i._error=M.CONFIGURATION_ERROR,e}return i._registrator=new g(u(i)),i}return a(n,[{key:`start`,value:function(){j.debug(`start()`),this._status===M.STATUS_INIT?this._transport.connect():this._status===M.STATUS_USER_CLOSED?(j.debug(`restarting UA`),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=M.STATUS_INIT,this._transport.connect()):this._status===M.STATUS_READY?j.debug(`UA is in READY status, not restarted`):j.debug(`ERROR: connection is down, Auto-Recovery system is trying to reconnect`),this._dynConfiguration.register=this._configuration.register}},{key:`register`,value:function(){j.debug(`register()`),this._dynConfiguration.register=!0,this._registrator.register()}},{key:`unregister`,value:function(e){j.debug(`unregister()`),this._dynConfiguration.register=!1,this._registrator.unregister(e)}},{key:`registrator`,value:function(){return this._registrator}},{key:`isRegistered`,value:function(){return this._registrator.registered}},{key:`isConnected`,value:function(){return this._transport.isConnected()}},{key:`call`,value:function(e,t){j.debug(`call()`);var n=new _(this);return n.connect(e,t),n}},{key:`sendMessage`,value:function(e,t,n){j.debug(`sendMessage()`);var r=new v(this);return r.send(e,t,n),r}},{key:`sendOptions`,value:function(e,t,n){j.debug(`sendOptions()`);var r=new y(this);return r.send(e,t,n),r}},{key:`terminateSessions`,value:function(e){for(var t in j.debug(`terminateSessions()`),this._sessions)this._sessions[t].isEnded()||this._sessions[t].terminate(e)}},{key:`stop`,value:function(){var e=this;if(j.debug(`stop()`),this._dynConfiguration={},this._status===M.STATUS_USER_CLOSED){j.debug(`UA already closed`);return}this._registrator.close();var t=Object.keys(this._sessions).length;for(var n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){j.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch{}}for(var r in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,r))try{this._applicants[r].close()}catch{}this._status=M.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){e._closeTimer=null,e._transport.disconnect()},2e3)}},{key:`normalizeTarget`,value:function(e){return S.normalizeTarget(e,this._configuration.hostport_params)}},{key:`get`,value:function(e){switch(e){case`authorization_user`:return this._configuration.authorization_user;case`realm`:return this._configuration.realm;case`ha1`:return this._configuration.ha1;case`authorization_jwt`:return this._configuration.authorization_jwt;default:j.warn(`get() | cannot get "%s" parameter in runtime`,e);return}}},{key:`set`,value:function(e,t){switch(e){case`authorization_user`:this._configuration.authorization_user=String(t);break;case`password`:this._configuration.password=String(t);break;case`realm`:this._configuration.realm=String(t);break;case`ha1`:this._configuration.ha1=String(t),this._configuration.password=null;break;case`authorization_jwt`:this._configuration.authorization_jwt=String(t);break;case`display_name`:this._configuration.display_name=t;break;case`extra_headers`:this._configuration.extra_headers=t;break;default:return j.warn(`set() | cannot set "%s" parameter in runtime`,e),!1}return!0}},{key:`newTransaction`,value:function(e){this._transactions[e.type][e.id]=e,this.emit(`newTransaction`,{transaction:e})}},{key:`destroyTransaction`,value:function(e){delete this._transactions[e.type][e.id],this.emit(`transactionDestroyed`,{transaction:e})}},{key:`newDialog`,value:function(e){this._dialogs[e.id]=e}},{key:`destroyDialog`,value:function(e){delete this._dialogs[e.id]}},{key:`newMessage`,value:function(e,t){this._applicants[e]=e,this.emit(`newMessage`,t)}},{key:`newOptions`,value:function(e,t){this._applicants[e]=e,this.emit(`newOptions`,t)}},{key:`destroyMessage`,value:function(e){delete this._applicants[e]}},{key:`newRTCSession`,value:function(e,t){this._sessions[e.id]=e,this.emit(`newRTCSession`,t)}},{key:`destroyRTCSession`,value:function(e){delete this._sessions[e.id]}},{key:`registered`,value:function(e){this.emit(`registered`,e)}},{key:`unregistered`,value:function(e){this.emit(`unregistered`,e)}},{key:`registrationFailed`,value:function(e){this.emit(`registrationFailed`,e)}},{key:`receiveRequest`,value:function(e){var t=e.method;if(e.ruri.user!==this._configuration.uri.user&&e.ruri.user!==this._contact.uri.user){j.debug(`Request-URI does not point to us`),e.method!==h.ACK&&e.reply_sl(404);return}if(e.ruri.scheme===h.SIPS){e.reply_sl(416);return}if(!b.checkTransaction(this,e)){if(t===h.INVITE?new b.InviteServerTransaction(this,this._transport,e):t!==h.ACK&&t!==h.CANCEL&&new b.NonInviteServerTransaction(this,this._transport,e),t===h.OPTIONS){if(this.listeners(`newOptions`).length===0){e.reply(200);return}new y(this).init_incoming(e)}else if(t===h.MESSAGE){if(this.listeners(`newMessage`).length===0){e.reply(405);return}new v(this).init_incoming(e)}else if(t===h.INVITE&&!e.to_tag&&this.listeners(`newRTCSession`).length===0){e.reply(405);return}var n,r;if(e.to_tag)n=this._findDialog(e.call_id,e.from_tag,e.to_tag),n?n.receiveRequest(e):t===h.NOTIFY?(r=this._findSession(e),r?r.receiveRequest(e):(j.debug(`received NOTIFY request for a non existent subscription`),e.reply(481,`Subscription does not exist`))):t!==h.ACK&&e.reply(481);else switch(t){case h.INVITE:if(window.RTCPeerConnection){if(e.hasHeader(`replaces`)){var i=e.replaces;n=this._findDialog(i.call_id,i.from_tag,i.to_tag),n?(r=n.owner,r.isEnded()?e.reply(603):r.receiveRequest(e)):e.reply(481)}else r=new _(this),r.init_incoming(e)}else j.warn(`INVITE received but WebRTC is not supported`),e.reply(488);break;case h.BYE:e.reply(481);break;case h.CANCEL:r=this._findSession(e),r?r.receiveRequest(e):j.debug(`received CANCEL request for a non existent session`);break;case h.ACK:break;case h.NOTIFY:this.emit(`sipEvent`,{event:e.event,request:e}),e.reply(200);break;default:e.reply(405)}}}},{key:`_findSession`,value:function(e){var t=e.call_id,n=e.from_tag,r=e.to_tag,i=t+n,a=this._sessions[i],o=t+r,s=this._sessions[o];return a||s||null}},{key:`_findDialog`,value:function(e,t,n){var r=e+t+n,i=this._dialogs[r];return i||(r=e+n+t,i=this._dialogs[r],i||null)}},{key:`_loadConfig`,value:function(e){try{O.load(this._configuration,e)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name=`0`),this._configuration.instance_id||(this._configuration.instance_id=S.newUUID()),this._configuration.jssip_id=S.createRandomToken(5);var t=this._configuration.uri.clone();t.user=null,this._configuration.hostport_params=t.toString().replace(/^sip:/i,``);try{this._transport=new x(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=I.bind(this),this._transport.onconnect=L.bind(this),this._transport.ondisconnect=R.bind(this),this._transport.ondata=B.bind(this)}catch(e){throw j.warn(e),new C.ConfigurationError(`sockets`,this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){var n=this._configuration.uri.clone();n.user=null,n.clearParams(),n.clearHeaders(),this._configuration.registrar_server=n}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new w(`sip`,S.createRandomToken(8),this._configuration.via_host,null,{transport:`ws`}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.anonymous||null,n=e.outbound||null,r=`<`;return r+=t?this.temp_gruu||`sip:anonymous@anonymous.invalid;transport=ws`:this.pub_gruu||this.uri.toString(),n&&(t?!this.temp_gruu:!this.pub_gruu)&&(r+=`;ob`),r+=`>`,r}};var r=[`authorization_user`,`password`,`realm`,`ha1`,`authorization_jwt`,`display_name`,`register`,`extra_headers`];for(var i in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,i)&&(r.indexOf(i)===-1?Object.defineProperty(this._configuration,i,{writable:!1,configurable:!1}):Object.defineProperty(this._configuration,i,{writable:!0,configurable:!1}));for(var a in j.debug(`configuration parameters after validation:`),this._configuration)if(Object.prototype.hasOwnProperty.call(O.settings,a))switch(a){case`uri`:case`registrar_server`:j.debug(`- ${a}: ${this._configuration[a]}`);break;case`password`:case`ha1`:case`authorization_jwt`:j.debug(`- ${a}: NOT SHOWN`);break;default:j.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}},{key:`C`,get:function(){return M}},{key:`status`,get:function(){return this._status}},{key:`contact`,get:function(){return this._contact}},{key:`configuration`,get:function(){return this._configuration}},{key:`transport`,get:function(){return this._transport}}]),n}(p);function I(e){this.emit(`connecting`,e)}function L(e){this._status!==M.STATUS_USER_CLOSED&&(this._status=M.STATUS_READY,this._error=null,this.emit(`connected`,e),this._dynConfiguration.register&&this._registrator.register())}function R(e){for(var t=[`nict`,`ict`,`nist`,`ist`],n=0,r=t;n<r.length;n++){var i=r[n];for(var a in this._transactions[i])Object.prototype.hasOwnProperty.call(this._transactions[i],a)&&this._transactions[i][a].onTransportError()}this.emit(`disconnected`,e),this._registrator.onTransportClosed(),this._status!==M.STATUS_USER_CLOSED&&(this._status=M.STATUS_NOT_READY,this._error=M.NETWORK_ERROR)}function B(e){var t=e.transport,n=e.message;if(n=T.parseMessage(n,this),n&&!(this._status===M.STATUS_USER_CLOSED&&n instanceof E.IncomingRequest)&&D(n,this,t)){if(n instanceof E.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof E.IncomingResponse){var r;switch(n.method){case h.INVITE:r=this._transactions.ict[n.via_branch],r&&r.receiveResponse(n);break;case h.ACK:break;default:r=this._transactions.nict[n.via_branch],r&&r.receiveResponse(n)}}}}})),ve=s(((e,t)=>{function n(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}var a=z(),o=M(),s=new a(`WebSocketInterface`);t.exports=function(){function e(t){n(this,e),s.debug(`new() [url:"%s"]`,t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var r=o.parse(t,`absoluteURI`);if(r===-1)throw s.warn(`invalid WebSocket URI: ${t}`),TypeError(`Invalid argument: ${t}`);if(r.scheme!==`wss`&&r.scheme!==`ws`)throw s.warn(`invalid WebSocket URI scheme: ${r.scheme}`),TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:``};transport=ws`,this._via_transport=r.scheme.toUpperCase()}return i(e,[{key:`connect`,value:function(){if(s.debug(`connect()`),this.isConnected()){s.debug(`WebSocket ${this._url} is already connected`);return}if(this.isConnecting()){s.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),s.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,`sip`),this._ws.binaryType=`arraybuffer`,this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(e){this._onError(e)}}},{key:`disconnect`,value:function(){s.debug(`disconnect()`),this._ws&&=(this._ws.onopen=function(){},this._ws.onclose=function(){},this._ws.onmessage=function(){},this._ws.onerror=function(){},this._ws.close(),null)}},{key:`send`,value:function(e){return s.debug(`send()`),this.isConnected()?(this._ws.send(e),!0):(s.warn(`unable to send message, WebSocket is not open`),!1)}},{key:`isConnected`,value:function(){return this._ws&&this._ws.readyState===this._ws.OPEN}},{key:`isConnecting`,value:function(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}},{key:`_onOpen`,value:function(){s.debug(`WebSocket ${this._url} connected`),this.onconnect()}},{key:`_onClose`,value:function(e){var t=e.wasClean,n=e.code,r=e.reason;s.debug(`WebSocket ${this._url} closed`),t===!1&&s.debug(`WebSocket abrupt disconnection`),this.ondisconnect(!t,n,r)}},{key:`_onMessage`,value:function(e){var t=e.data;s.debug(`received WebSocket message`),this.ondata(t)}},{key:`_onError`,value:function(e){s.warn(`WebSocket ${this._url} error: `,e)}},{key:`via_transport`,get:function(){return this._via_transport},set:function(e){this._via_transport=e.toUpperCase()}},{key:`sip_uri`,get:function(){return this._sip_uri}},{key:`url`,get:function(){return this._url}}]),e}()})),ye=u(s(((e,t)=>{var n=(O(),d(f).default),r=k(),i=A(),a=P(),o=_e(),s=N(),c=j(),l=M(),u=ve();R()(`JsSIP`)(`version %s`,n.version),t.exports={C:r,Exceptions:i,Utils:a,UA:o,URI:s,NameAddrHeader:c,WebSocketInterface:u,Grammar:l,debug:R(),get name(){return n.title},get version(){return n.version}}}))(),1);function be(){return{createSocket:(e,t)=>new xe(e,t),createUa:e=>new ye.UA(e)}}var xe=class extends ye.WebSocketInterface{ticket;constructor(e,t){super(e),this.ticket=t}protocols(){return this.ticket===``?[`sip`]:[`xcall-ticket.${this.ticket}`,`sip`]}connect(){if(this.isConnected()||this.isConnecting())return;let e=this;e._ws&&this.disconnect();try{e._ws=new WebSocket(this.url,this.protocols()),e._ws.binaryType=`arraybuffer`,e._ws.onopen=e._onOpen.bind(this),e._ws.onclose=e._onClose.bind(this),e._ws.onmessage=e._onMessage.bind(this),e._ws.onerror=e._onError.bind(this)}catch(t){e._onError.call(this,t)}}};exports.createJsSipFactory=be,exports.t=d;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../Diagnostics-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../Diagnostics-BXKjfW9h.cjs"),t=require("../redact-Bq26pObO.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs"),exports.Diagnostics=e.t,exports.RingBuffer=e.n,exports.diagnosticsVersion=e.r,exports.redactText=t.t,exports.redactValue=t.n;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as e, r as t, t as n } from "../Diagnostics-
|
|
1
|
+
import { n as e, r as t, t as n } from "../Diagnostics-Hb2Y9WsN.js";
|
|
2
2
|
import { n as r, t as i } from "../redact-DB3CMbsK.js";
|
|
3
3
|
export { n as Diagnostics, e as RingBuffer, t as diagnosticsVersion, i as redactText, r as redactValue };
|