@16x/webphone-sdk 3.1.12 → 3.1.15

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.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-C-4KpECM.cjs"),t=require("../CCBarClient-DdOn4U0l.cjs");require("../createJsSipFactory-B1ORbJiP.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`/openapi/token/v1`,o=`/seat/account/get`,s=`/seats/set-status`,c=`/api/fs/sip-ws`,l=7443,u=3478,d=600,f=600,p=180,m=60,h=5e3,g=2e4,_=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],v={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function y(n){let r=b(n.host),i=x(n.pathPrefix??a),g=`${r}${i}${S(n.accountPath??o)}`,y=`${r}${i}${S(n.statusPath??s)}`,D=S(n.sipWsPath??c),O={...n.aesKey?{key:n.aesKey}:{},...n.aesIv?{iv:n.aesIv}:{}},k=Math.max(0,n.refreshBufferSeconds??p),A=n.fetchImpl??globalThis.fetch,j,M,N=``;async function P(){if(n.getToken!==void 0)return n.getToken();if(n.tokenUrl!==void 0){let t=n.tokenMethod??`POST`,r={method:t,headers:{Accept:`application/json`,...n.tokenHeaders??{}},credentials:`include`};t===`POST`&&(r.headers={"Content-Type":`application/json`,...r.headers},r.body=JSON.stringify(n.tokenBody??{}));let i=await E(A,n.tokenUrl,r,`取 token`),a=await i.text();try{return JSON.parse(a)}catch{throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{status:i.status,cause:`取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0,120)}`})}}throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用`})}async function F(){if(j&&j.expiresAtMs-Date.now()>h)return j.token;let t;try{t=await P()}catch(t){throw t instanceof e.i?t:new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:t})}let n=T(t);if(!n.token)throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=w(n.expires,3600);return j={token:n.token,expiresAtMs:Date.now()+r*1e3},j.token}function I(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function L(e){let t=I(e?.wssUrl);return t?(N=t,t):N||F()}async function R(t){let n=t||await F(),r=await E(A,g,{method:`POST`,headers:{Authorization:n,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`},`取坐席账号`),i=await r.text(),a;try{a=JSON.parse(i)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:r.status,cause:`${g} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`})}let o=Number(a.code??NaN);if(!r.ok||o!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,o===50,{status:r.status,serverCode:Number.isFinite(o)?String(o):void 0,cause:a.message||`取坐席账号失败(HTTP ${r.status})`});if(!a.data)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号接口没有返回 data`});return M=a.data,M}let z=e=>t.i(e,O);function B(t,i){let a=Number(t.wssPort)||l,o=String(t.domain??``).trim(),s=String(n.sipWsUrl??``).trim(),c;if(s)c=new URL(s,r),c.protocol===`http:`&&(c.protocol=`ws:`),c.protocol===`https:`&&(c.protocol=`wss:`);else{if(!o)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定`});let t=a===443?``:`:${a}`;c=new URL(`wss://${o}${t}${D}`)}return(n.attachTokenToWss??!0)&&i&&c.searchParams.set(`token`,i),c.toString()}function V(e){let t=(Array.isArray(e.iceServers)?e.iceServers:[]).map(e=>{let t=(Array.isArray(e?.urls)?e.urls:typeof e?.urls==`string`?[e.urls]:[]).map(e=>String(e??``).trim()).filter(Boolean);if(t.length!==0)return{urls:t,...e?.username?{username:String(e.username)}:{},...e?.credential?{credential:String(e.credential)}:{}}}).filter(e=>e!==void 0);if(t.length>0)return t;let n=String(e.turnIp??``).trim();return n?[{urls:[`stun:${n}:${Number(e.turnPort)||u}`]}]:[]}async function H(){let t=await F(),i=await R(),a=String(i.username??i.account??``).trim();if(!a)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let o=String(i.registerPassword??i.password??``),s=o?await z(o):``;if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let c=w(i.expiresIn??i.expires_in,f),l=Math.max(0,Math.round((j.expiresAtMs-Date.now())/1e3)),u=Math.max(m,Math.min(l||c,c)-k),p=String(i.domain??``).trim()||C(r),h=B(i,t);return t&&(N=t),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+u,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${p}`,registrar:p,registerTicket:s,registerExpires:Number(n.registerExpires)>0?Number(n.registerExpires):d,ticketExpiresIn:u},transport:{wssUrl:h,ticket:``,ticketExpiresIn:u},iceServers:V(i),policy:{maxConcurrentCalls:Number(n.maxConcurrentCalls)>0?Number(n.maxConcurrentCalls):2,incomingEnabled:n.incomingEnabled??!0,mobileIncomingEnabled:n.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...n.capabilities??_]}}return{createSession:H,refreshSession:H,setAgentStatus:async({status:t,reason:n},r)=>{let i=await L(r),a=M??await R(i),o=String(a.username??a.account??``).trim();if(!o)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let s=v[t],c=await E(A,y,{method:`POST`,headers:{Authorization:i,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({extension:o,status:s.status,reason:n||s.reason})},`设置坐席状态`),l=await c.text(),u;try{u=JSON.parse(l)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:c.status,cause:`${y} 返回了非 JSON 响应(HTTP ${c.status})`})}let d=Number(u.code??NaN);if(!c.ok||d!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,d===50,{status:c.status,serverCode:Number.isFinite(d)?String(d):void 0,cause:u.message||`设置坐席状态失败(HTTP ${c.status})`})},invalidateToken:()=>{j=void 0,N=``},getSeatAccount:async()=>M??R()}}function b(t){let n=String(t??``).trim().replace(/\/+$/,``);if(!n)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 host`});return/^https?:\/\//i.test(n)?n:`https://${n}`}function x(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function S(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function C(e){try{return new URL(e).hostname}catch{return``}}function w(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),m),86400))}function T(e){if(typeof e==`string`)return{token:e.trim()};let t=e??{},n=typeof t.data==`object`&&t.data!==null?t.data:void 0;for(let e of[t,n]){if(e===void 0)continue;let t=e.token??e.accessToken;if(typeof t==`string`&&t.trim()){let n=Number(e.expires??e.expiresIn??e.expires_at);return{token:t.trim(),...Number.isFinite(n)&&n>0?{expires:n}:{}}}}return{token:``}}async function E(t,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),g);try{return await t(n,{...r,signal:a.signal})}catch(t){let r=a.signal.aborted;throw new e.i(r?`NETWORK_TIMEOUT`:`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{cause:r?`${i}超时(${g/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${t instanceof Error?t.message:String(t)})`})}finally{clearTimeout(o)}}var D=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=y,exports.decryptSipPassword=t.i,exports.legacyVersion=D;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-C-4KpECM.cjs"),t=require("../CCBarClient-DBQefPRJ.cjs");require("../createJsSipFactory-B1ORbJiP.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`/openapi/token/v1`,o=`/seat/account/get`,s=`/seats/set-status`,c=`/api/fs/sip-ws`,l=7443,u=3478,d=600,f=600,p=180,m=60,h=5e3,g=2e4,_=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],v={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function y(n){let r=b(n.host),i=x(n.pathPrefix??a),g=`${r}${i}${S(n.accountPath??o)}`,y=`${r}${i}${S(n.statusPath??s)}`,D=S(n.sipWsPath??c),O={...n.aesKey?{key:n.aesKey}:{},...n.aesIv?{iv:n.aesIv}:{}},k=Math.max(0,n.refreshBufferSeconds??p),A=n.fetchImpl??globalThis.fetch,j,M,N=``;async function P(){if(n.getToken!==void 0)return n.getToken();if(n.tokenUrl!==void 0){let t=n.tokenMethod??`POST`,r={method:t,headers:{Accept:`application/json`,...n.tokenHeaders??{}},credentials:`include`};t===`POST`&&(r.headers={"Content-Type":`application/json`,...r.headers},r.body=JSON.stringify(n.tokenBody??{}));let i=await E(A,n.tokenUrl,r,`取 token`),a=await i.text();try{return JSON.parse(a)}catch{throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{status:i.status,cause:`取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0,120)}`})}}throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用`})}async function F(){if(j&&j.expiresAtMs-Date.now()>h)return j.token;let t;try{t=await P()}catch(t){throw t instanceof e.i?t:new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:t})}let n=T(t);if(!n.token)throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=w(n.expires,3600);return j={token:n.token,expiresAtMs:Date.now()+r*1e3},j.token}function I(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function L(e){let t=I(e?.wssUrl);return t?(N=t,t):N||F()}async function R(t){let n=t||await F(),r=await E(A,g,{method:`POST`,headers:{Authorization:n,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`},`取坐席账号`),i=await r.text(),a;try{a=JSON.parse(i)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:r.status,cause:`${g} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`})}let o=Number(a.code??NaN);if(!r.ok||o!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,o===50,{status:r.status,serverCode:Number.isFinite(o)?String(o):void 0,cause:a.message||`取坐席账号失败(HTTP ${r.status})`});if(!a.data)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号接口没有返回 data`});return M=a.data,M}let z=e=>t.i(e,O);function B(t,i){let a=Number(t.wssPort)||l,o=String(t.domain??``).trim(),s=String(n.sipWsUrl??``).trim(),c;if(s)c=new URL(s,r),c.protocol===`http:`&&(c.protocol=`ws:`),c.protocol===`https:`&&(c.protocol=`wss:`);else{if(!o)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定`});let t=a===443?``:`:${a}`;c=new URL(`wss://${o}${t}${D}`)}return(n.attachTokenToWss??!0)&&i&&c.searchParams.set(`token`,i),c.toString()}function V(e){let t=(Array.isArray(e.iceServers)?e.iceServers:[]).map(e=>{let t=(Array.isArray(e?.urls)?e.urls:typeof e?.urls==`string`?[e.urls]:[]).map(e=>String(e??``).trim()).filter(Boolean);if(t.length!==0)return{urls:t,...e?.username?{username:String(e.username)}:{},...e?.credential?{credential:String(e.credential)}:{}}}).filter(e=>e!==void 0);if(t.length>0)return t;let n=String(e.turnIp??``).trim();return n?[{urls:[`stun:${n}:${Number(e.turnPort)||u}`]}]:[]}async function H(){let t=await F(),i=await R(),a=String(i.username??i.account??``).trim();if(!a)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let o=String(i.registerPassword??i.password??``),s=o?await z(o):``;if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let c=w(i.expiresIn??i.expires_in,f),l=Math.max(0,Math.round((j.expiresAtMs-Date.now())/1e3)),u=Math.max(m,Math.min(l||c,c)-k),p=String(i.domain??``).trim()||C(r),h=B(i,t);return t&&(N=t),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+u,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${p}`,registrar:p,registerTicket:s,registerExpires:Number(n.registerExpires)>0?Number(n.registerExpires):d,ticketExpiresIn:u},transport:{wssUrl:h,ticket:``,ticketExpiresIn:u},iceServers:V(i),policy:{maxConcurrentCalls:Number(n.maxConcurrentCalls)>0?Number(n.maxConcurrentCalls):2,incomingEnabled:n.incomingEnabled??!0,mobileIncomingEnabled:n.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...n.capabilities??_]}}return{createSession:H,refreshSession:H,setAgentStatus:async({status:t,reason:n},r)=>{let i=await L(r),a=M??await R(i),o=String(a.username??a.account??``).trim();if(!o)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let s=v[t],c=await E(A,y,{method:`POST`,headers:{Authorization:i,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({extension:o,status:s.status,reason:n||s.reason})},`设置坐席状态`),l=await c.text(),u;try{u=JSON.parse(l)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:c.status,cause:`${y} 返回了非 JSON 响应(HTTP ${c.status})`})}let d=Number(u.code??NaN);if(!c.ok||d!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,d===50,{status:c.status,serverCode:Number.isFinite(d)?String(d):void 0,cause:u.message||`设置坐席状态失败(HTTP ${c.status})`})},invalidateToken:()=>{j=void 0,N=``},getSeatAccount:async()=>M??R()}}function b(t){let n=String(t??``).trim().replace(/\/+$/,``);if(!n)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 host`});return/^https?:\/\//i.test(n)?n:`https://${n}`}function x(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function S(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function C(e){try{return new URL(e).hostname}catch{return``}}function w(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),m),86400))}function T(e){if(typeof e==`string`)return{token:e.trim()};let t=e??{},n=typeof t.data==`object`&&t.data!==null?t.data:void 0;for(let e of[t,n]){if(e===void 0)continue;let t=e.token??e.accessToken;if(typeof t==`string`&&t.trim()){let n=Number(e.expires??e.expiresIn??e.expires_at);return{token:t.trim(),...Number.isFinite(n)&&n>0?{expires:n}:{}}}}return{token:``}}async function E(t,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),g);try{return await t(n,{...r,signal:a.signal})}catch(t){let r=a.signal.aborted;throw new e.i(r?`NETWORK_TIMEOUT`:`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{cause:r?`${i}超时(${g/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${t instanceof Error?t.message:String(t)})`})}finally{clearTimeout(o)}}var D=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=y,exports.decryptSipPassword=t.i,exports.legacyVersion=D;
@@ -1,5 +1,5 @@
1
1
  import { i as e } from "../SharedWorkerProtocol-CffZrUXg.js";
2
- import { i as t, t as n } from "../CCBarClient-DBNOXOlX.js";
2
+ import { i as t, t as n } from "../CCBarClient-AX6m4-Vg.js";
3
3
  //#region src/legacy/CCBarSDK.ts
4
4
  var r = class extends Error {
5
5
  code = "LEGACY_METHOD_DEPRECATED";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "3.1.12";
1
+ export declare const SDK_VERSION = "3.1.15";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@16x/webphone-sdk",
3
- "version": "3.1.12",
3
+ "version": "3.1.15",
4
4
  "homepage": "https://www.npmjs.com/package/@16x/webphone-sdk",
5
5
  "private": false,
6
6
  "license": "UNLICENSED",
@@ -1,405 +0,0 @@
1
- import { i as e } from "./SharedWorkerProtocol-CffZrUXg.js";
2
- //#region src/sip/nativeMediaAdapter.ts
3
- function t(e) {
4
- let t = /* @__PURE__ */ new Map();
5
- return {
6
- peerConnection: {
7
- getSenders: () => e.getSenders().map((n) => {
8
- let r = t.get(n);
9
- if (r !== void 0) return r;
10
- let i = {
11
- get track() {
12
- return n.track;
13
- },
14
- get senderKind() {
15
- let t = n.track;
16
- if (t !== null) return t.kind === "audio" || t.kind === "video" ? t.kind : void 0;
17
- let r = e.getTransceivers().find((e) => e.sender === n)?.receiver.track;
18
- if (r?.kind === "audio" || r?.kind === "video") return r.kind;
19
- let i = n.getParameters().codecs?.find((e) => typeof e.mimeType == "string");
20
- if (i?.mimeType?.toLowerCase().startsWith("video/")) return "video";
21
- if (i?.mimeType?.toLowerCase().startsWith("audio/")) return "audio";
22
- },
23
- replaceTrack: (e) => n.replaceTrack(e)
24
- };
25
- return t.set(n, i), i;
26
- }),
27
- close: () => {
28
- e.connectionState !== "closed" && e.close();
29
- }
30
- },
31
- trackSource: { onTrack(t) {
32
- let n = (e) => {
33
- let n = e.track;
34
- t({
35
- streams: [...e.streams],
36
- track: n
37
- });
38
- };
39
- return e.addEventListener("track", n), () => e.removeEventListener("track", n);
40
- } }
41
- };
42
- }
43
- //#endregion
44
- //#region src/sip/JsSipAdapter.ts
45
- var n = 300, r = 25, i = 2, a = "", o = 120;
46
- function s(e) {
47
- let t = Math.floor(Number(e.sip.registerExpires));
48
- return Number.isFinite(t) && t > 0 ? t : n;
49
- }
50
- var c = class {
51
- factory;
52
- transportBaseUrl;
53
- keepaliveSeconds;
54
- agentTerminal;
55
- sessionTimers;
56
- ua;
57
- uaListeners;
58
- incomingHandlers;
59
- iceServers;
60
- pendingConnection;
61
- disposed = !1;
62
- warmPc;
63
- keepaliveTimer;
64
- keepaliveBusy = !1;
65
- registerExpiresSeconds = 0;
66
- connectionHandlers = /* @__PURE__ */ new Set();
67
- constructor(e, t, n = r, i = a, o = !1) {
68
- this.factory = e, this.transportBaseUrl = t, this.keepaliveSeconds = n, this.agentTerminal = i, this.sessionTimers = o;
69
- }
70
- terminalHeaders() {
71
- return this.agentTerminal === "" ? [] : [`X-Agent-Terminal: ${this.agentTerminal}`];
72
- }
73
- warmIceCandidatePool() {
74
- if (this.closeWarmPc(), typeof RTCPeerConnection < "u" && this.iceServers !== void 0) try {
75
- this.warmPc = new RTCPeerConnection({
76
- iceServers: [...this.iceServers],
77
- iceCandidatePoolSize: i
78
- });
79
- } catch {
80
- this.warmPc = void 0;
81
- }
82
- }
83
- closeWarmPc() {
84
- try {
85
- this.warmPc?.close();
86
- } catch {}
87
- this.warmPc = void 0;
88
- }
89
- keepaliveTick(e) {
90
- if (this.isCurrentUa(e) && !this.keepaliveBusy) try {
91
- if (typeof e.isConnected == "function" && e.isConnected() === !1 || typeof e.register != "function") return;
92
- this.keepaliveBusy = !0, e.register({ extraHeaders: this.terminalHeaders() });
93
- } catch {} finally {
94
- this.keepaliveBusy = !1;
95
- }
96
- }
97
- startKeepalive(e, t) {
98
- if (this.stopKeepalive(), !Number.isFinite(this.keepaliveSeconds) || this.keepaliveSeconds <= 0 || t > 0 && t <= this.keepaliveSeconds) return;
99
- let n = Math.max(10, Math.floor(this.keepaliveSeconds)) * 1e3;
100
- this.keepaliveTimer = setInterval(() => this.keepaliveTick(e), n);
101
- }
102
- stopKeepalive() {
103
- this.keepaliveTimer !== void 0 && clearInterval(this.keepaliveTimer), this.keepaliveTimer = void 0;
104
- }
105
- connect(t) {
106
- this.assertNotDisposed(), this.disconnect(this.registrationError("SIP connection replaced"));
107
- try {
108
- let e = this.factory.createUa({
109
- sockets: f(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(t.transport.wssUrl)), t.transport.ticket)),
110
- uri: t.sip.uri,
111
- password: t.sip.registerTicket,
112
- registrar_server: t.sip.registrar,
113
- register: !0,
114
- register_expires: s(t),
115
- session_timers: this.sessionTimers,
116
- ...this.agentTerminal === "" ? {} : { user_agent: this.agentTerminal }
117
- });
118
- return this.ua = e, this.registerExpiresSeconds = s(t), this.iceServers = t.iceServers, this.uaListeners = [], this.startRegistration(e);
119
- } catch (t) {
120
- let n = t instanceof e && t.code === "CONFIG_INVALID" ? t : this.transportError(t);
121
- return this.disconnect(n), Promise.reject(n);
122
- }
123
- }
124
- disconnect(e = this.registrationError("SIP connection disconnected")) {
125
- this.stopKeepalive(), this.closeWarmPc();
126
- let t = this.pendingConnection;
127
- 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);
128
- }
129
- dial(t, n) {
130
- let r = this.requireUa();
131
- if (t.trim() === "") throw new e("CALL_INVALID_DESTINATION", "call", !1);
132
- try {
133
- let e = n === void 0 ? {
134
- mediaConstraints: {
135
- audio: !0,
136
- video: !1
137
- },
138
- sessionTimersExpires: o,
139
- pcConfig: {
140
- iceServers: this.iceServers,
141
- iceCandidatePoolSize: i
142
- }
143
- } : {
144
- mediaConstraints: {
145
- audio: !0,
146
- video: !1
147
- },
148
- sessionTimersExpires: o,
149
- pcConfig: {
150
- iceServers: [...n.iceServers],
151
- iceCandidatePoolSize: i
152
- },
153
- extraHeaders: [
154
- ...this.terminalHeaders(),
155
- ...n.extraHeaders,
156
- ...n.type === "extension" ? ["X-XCall-Destination-Type: extension"] : []
157
- ]
158
- };
159
- return new l(r.call(t, e));
160
- } catch (t) {
161
- throw new e("CALL_OPERATION_NOT_ALLOWED", "call", !1, { cause: t });
162
- }
163
- }
164
- onIncoming(e) {
165
- this.assertNotDisposed();
166
- let t = this.incomingHandlers ?? /* @__PURE__ */ new Set();
167
- return this.incomingHandlers = t, t.add(e), () => t.delete(e);
168
- }
169
- onConnectionStateChanged(e) {
170
- return this.disposed ? () => void 0 : (this.connectionHandlers.add(e), () => this.connectionHandlers.delete(e));
171
- }
172
- dispose() {
173
- this.disposed || (this.disposed = !0, this.disconnect(), this.incomingHandlers = void 0, this.connectionHandlers.clear());
174
- }
175
- getResourceCounts() {
176
- return {
177
- listeners: (this.uaListeners?.length ?? 0) + (this.incomingHandlers?.size ?? 0) + this.connectionHandlers.size,
178
- webSockets: this.ua === void 0 ? 0 : 1
179
- };
180
- }
181
- handleIncoming(e) {
182
- if (!u(e)) return;
183
- let t = e.session;
184
- if (t === void 0) return;
185
- let n = new l(t);
186
- this.incomingHandlers?.forEach((e) => e(n));
187
- }
188
- startRegistration(e) {
189
- let t = !0, n = !1, r = new Promise((t, n) => {
190
- this.pendingConnection = {
191
- ua: e,
192
- resolve: t,
193
- reject: n
194
- };
195
- });
196
- this.listen(e, "registered", () => {
197
- if (this.isCurrentUa(e)) {
198
- if (t) {
199
- n = !0;
200
- return;
201
- }
202
- this.resolveConnection(e);
203
- }
204
- }), this.listen(e, "registrationFailed", (t) => {
205
- if (!this.isCurrentUa(e)) return;
206
- let n = this.registrationError(this.registrationFailureCause(t));
207
- this.connectionHandlers.forEach((e) => e("failed", n)), this.disconnect(n);
208
- }), this.listen(e, "disconnected", (t) => {
209
- if (!this.isCurrentUa(e)) return;
210
- let n = this.transportError(t);
211
- this.connectionHandlers.forEach((e) => e("disconnected", n)), this.disconnect(n);
212
- }), this.listen(e, "newRTCSession", (t) => {
213
- this.isCurrentUa(e) && this.handleIncoming(t);
214
- });
215
- try {
216
- e.start();
217
- } catch (e) {
218
- let t = this.transportError(e);
219
- this.connectionHandlers.forEach((e) => e("failed", t)), this.disconnect(t);
220
- } finally {
221
- t = !1;
222
- }
223
- return n && this.resolveConnection(e), r;
224
- }
225
- listen(e, t, n) {
226
- e.on(t, n), this.uaListeners?.push({
227
- event: t,
228
- handler: n
229
- });
230
- }
231
- removeUaListeners(e) {
232
- this.uaListeners?.forEach(({ event: t, handler: n }) => e.off(t, n));
233
- }
234
- isCurrentUa(e) {
235
- return this.ua === e;
236
- }
237
- resolveConnection(e) {
238
- let t = this.pendingConnection;
239
- t?.ua === e && (this.pendingConnection = void 0, t.resolve(), this.warmIceCandidatePool(), this.startKeepalive(e, this.registerExpiresSeconds), this.connectionHandlers.forEach((e) => e("registered")));
240
- }
241
- resolveWssUrl(e) {
242
- 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);
243
- return n.protocol === "http:" && (n.protocol = "ws:"), n.protocol === "https:" && (n.protocol = "wss:"), this.assertAllowedWssUrl(n), n.toString();
244
- }
245
- assertAllowedWssUrl(t) {
246
- if (t.protocol !== "wss:" && !(t.protocol === "ws:" && p(t.hostname))) throw new e("CONFIG_INVALID", "configuration", !1, { cause: t.origin });
247
- }
248
- withoutTicket(e) {
249
- let t = new URL(e);
250
- return t.searchParams.delete("ticket"), t.toString();
251
- }
252
- requireUa() {
253
- if (this.assertNotDisposed(), this.ua === void 0) throw new e("CALL_NOT_CONNECTED", "call", !1);
254
- return this.ua;
255
- }
256
- assertNotDisposed() {
257
- if (this.disposed) throw new e("SDK_ALREADY_DISPOSED", "internal", !1);
258
- }
259
- registrationError(t) {
260
- return new e("REGISTRATION_FAILED", "registration", !0, { cause: t });
261
- }
262
- transportError(t) {
263
- return new e("SIP_WS_UNAVAILABLE", "registration", !0, { cause: t });
264
- }
265
- registrationFailureCause(e) {
266
- return typeof e == "object" && e && "cause" in e ? e.cause : e;
267
- }
268
- }, l = class {
269
- session;
270
- pendingHoldReject;
271
- mediaRegistration;
272
- mediaConnection;
273
- mediaHandlers = /* @__PURE__ */ new Set();
274
- mediaWatchStarted = !1;
275
- sessionUnsubscribeFromPeerConnection;
276
- constructor(e) {
277
- this.session = e;
278
- }
279
- get id() {
280
- return this.session.id;
281
- }
282
- get from() {
283
- return this.session.from ?? m(this.session.remote_identity);
284
- }
285
- getMediaRegistration() {
286
- let e = this.session.connection;
287
- if (e != null) return this.mediaRegistration !== void 0 && this.mediaConnection === e ? this.mediaRegistration : (this.mediaConnection = e, this.mediaRegistration = t(e), this.mediaRegistration);
288
- }
289
- answer(e) {
290
- this.session.answer({
291
- mediaConstraints: e.mediaConstraints,
292
- pcConfig: { iceServers: [...e.pcConfig.iceServers] }
293
- });
294
- }
295
- terminate() {
296
- this.pendingHoldReject?.(/* @__PURE__ */ Error("SIP session terminated")), this.session.terminate();
297
- }
298
- hold() {
299
- return this.changeHoldState("hold");
300
- }
301
- unhold() {
302
- return this.changeHoldState("unhold");
303
- }
304
- mute() {
305
- this.session.mute();
306
- }
307
- unmute() {
308
- this.session.unmute();
309
- }
310
- sendDtmf(e) {
311
- this.session.sendDTMF(e);
312
- }
313
- refer(e) {
314
- this.session.refer(e);
315
- }
316
- on(e, t) {
317
- return e === "mediaConnected" ? (this.mediaHandlers.add(t), this.watchMediaConnection(), () => {
318
- this.mediaHandlers.delete(t), this.mediaHandlers.size === 0 && (this.sessionUnsubscribeFromPeerConnection?.(), this.sessionUnsubscribeFromPeerConnection = void 0);
319
- }) : (this.session.on(e, t), () => this.session.off(e, t));
320
- }
321
- watchMediaConnection() {
322
- if (this.mediaWatchStarted) return;
323
- this.mediaWatchStarted = !0;
324
- let e = !1, t = (t) => {
325
- if (t == null) return;
326
- let n = () => {
327
- if (e) return;
328
- let n = t.connectionState || t.iceConnectionState;
329
- if (n === "connected") {
330
- e = !0;
331
- for (let e of this.mediaHandlers) try {
332
- e({ state: n });
333
- } catch {}
334
- }
335
- };
336
- t.addEventListener("connectionstatechange", n), n();
337
- }, n = this.session.connection;
338
- if (n != null) {
339
- t(n);
340
- return;
341
- }
342
- let r = (e) => {
343
- t(e?.peerconnection ?? void 0);
344
- };
345
- this.session.on("peerconnection", r), this.sessionUnsubscribeFromPeerConnection = () => this.session.off("peerconnection", r);
346
- }
347
- changeHoldState(t) {
348
- return new Promise((n, r) => {
349
- let i = !1, a = (e) => {
350
- c(e);
351
- }, o = () => {
352
- try {
353
- this.session.off("ended", a);
354
- } catch {}
355
- try {
356
- this.session.off("failed", a);
357
- } catch {}
358
- this.pendingHoldReject === c && (this.pendingHoldReject = void 0);
359
- }, s = () => {
360
- i || (i = !0, o(), n());
361
- }, c = (t) => {
362
- i || (i = !0, o(), r(new e("CALL_OPERATION_NOT_ALLOWED", "call", !1, { cause: t })));
363
- };
364
- try {
365
- this.session.on("ended", a), this.session.on("failed", a);
366
- } catch (e) {
367
- c(e);
368
- return;
369
- }
370
- this.pendingHoldReject = c;
371
- try {
372
- this.session[t](void 0, s) || c({
373
- reason: "jssip_operation_rejected",
374
- operation: t
375
- });
376
- } catch (e) {
377
- c(e);
378
- }
379
- });
380
- }
381
- };
382
- function u(e) {
383
- if (typeof e != "object" || !e) return !1;
384
- let t = e;
385
- return t.originator === "remote" && d(t.session);
386
- }
387
- function d(e) {
388
- return typeof e == "object" && !!e && "id" in e;
389
- }
390
- function f(e) {
391
- return typeof e == "object" && e && (e.via_transport = "WSS"), e;
392
- }
393
- function p(e) {
394
- let t = e.replace(/^\[|\]$/g, "").toLowerCase();
395
- return t === "localhost" || t === "127.0.0.1" || t === "::1" || t === "0:0:0:0:0:0:0:1";
396
- }
397
- function m(e) {
398
- let t = e?.uri;
399
- if (t == null) return;
400
- if (typeof t.user == "string" && t.user !== "") return t.user;
401
- let n = t.toString();
402
- return n.match(/^sips?:([^@;>]+)/i)?.[1] ?? (n === "" ? void 0 : n);
403
- }
404
- //#endregion
405
- export { c as JsSipAdapter };
@@ -1 +0,0 @@
1
- const e=require("./SharedWorkerProtocol-C-4KpECM.cjs");require("./createJsSipFactory-B1ORbJiP.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,i=2,a=``,o=120;function s(e){let t=Math.floor(Number(e.sip.registerExpires));return Number.isFinite(t)&&t>0?t:n}var c=class{factory;transportBaseUrl;keepaliveSeconds;agentTerminal;sessionTimers;ua;uaListeners;incomingHandlers;iceServers;pendingConnection;disposed=!1;warmPc;keepaliveTimer;keepaliveBusy=!1;registerExpiresSeconds=0;connectionHandlers=new Set;constructor(e,t,n=r,i=a,o=!1){this.factory=e,this.transportBaseUrl=t,this.keepaliveSeconds=n,this.agentTerminal=i,this.sessionTimers=o}terminalHeaders(){return this.agentTerminal===``?[]:[`X-Agent-Terminal: ${this.agentTerminal}`]}warmIceCandidatePool(){if(this.closeWarmPc(),typeof RTCPeerConnection<`u`&&this.iceServers!==void 0)try{this.warmPc=new RTCPeerConnection({iceServers:[...this.iceServers],iceCandidatePoolSize:i})}catch{this.warmPc=void 0}}closeWarmPc(){try{this.warmPc?.close()}catch{}this.warmPc=void 0}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({extraHeaders:this.terminalHeaders()})}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:f(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:s(t),session_timers:this.sessionTimers,...this.agentTerminal===``?{}:{user_agent:this.agentTerminal}});return this.ua=e,this.registerExpiresSeconds=s(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(),this.closeWarmPc();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:o,pcConfig:{iceServers:this.iceServers,iceCandidatePoolSize:i}}:{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:o,pcConfig:{iceServers:[...n.iceServers],iceCandidatePoolSize:i},extraHeaders:[...this.terminalHeaders(),...n.extraHeaders,...n.type===`extension`?[`X-XCall-Destination-Type: extension`]:[]]};return new l(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(!u(e))return;let t=e.session;if(t===void 0)return;let n=new l(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.warmIceCandidatePool(),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:`&&p(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}},l=class{session;pendingHoldReject;mediaRegistration;mediaConnection;mediaHandlers=new Set;mediaWatchStarted=!1;sessionUnsubscribeFromPeerConnection;constructor(e){this.session=e}get id(){return this.session.id}get from(){return this.session.from??m(this.session.remote_identity)}getMediaRegistration(){let e=this.session.connection;if(e!=null)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 e===`mediaConnected`?(this.mediaHandlers.add(t),this.watchMediaConnection(),()=>{this.mediaHandlers.delete(t),this.mediaHandlers.size===0&&(this.sessionUnsubscribeFromPeerConnection?.(),this.sessionUnsubscribeFromPeerConnection=void 0)}):(this.session.on(e,t),()=>this.session.off(e,t))}watchMediaConnection(){if(this.mediaWatchStarted)return;this.mediaWatchStarted=!0;let e=!1,t=t=>{if(t==null)return;let n=()=>{if(e)return;let n=t.connectionState||t.iceConnectionState;if(n===`connected`){e=!0;for(let e of this.mediaHandlers)try{e({state:n})}catch{}}};t.addEventListener(`connectionstatechange`,n),n()},n=this.session.connection;if(n!=null){t(n);return}let r=e=>{t(e?.peerconnection??void 0)};this.session.on(`peerconnection`,r),this.sessionUnsubscribeFromPeerConnection=()=>this.session.off(`peerconnection`,r)}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({reason:`jssip_operation_rejected`,operation:t})}catch(e){c(e)}})}};function u(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.originator===`remote`&&d(t.session)}function d(e){return typeof e==`object`&&!!e&&`id`in e}function f(e){return typeof e==`object`&&e&&(e.via_transport=`WSS`),e}function p(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 m(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=c;