@16x/webphone-sdk 3.1.11 → 3.2.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.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-39dch6xL.cjs"),t=require("../CCBarClient-B7SRICz8.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`/openapi/token/v1`,o=`/seat/account/get`,s=`/seats/set-status`,c=3478,l=600,u=600,d=180,f=60,p=5e3,m=2e4,h=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],g={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function _(n){let r=v(n.host),i=y(n.pathPrefix??a),m=`${r}${i}${b(n.accountPath??o)}`,_=`${r}${i}${b(n.statusPath??s)}`,T={...n.aesKey?{key:n.aesKey}:{},...n.aesIv?{iv:n.aesIv}:{}},E=Math.max(0,n.refreshBufferSeconds??d),D=n.fetchImpl??globalThis.fetch,O,k,A=``;async function j(){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 w(D,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 M(){if(O&&O.expiresAtMs-Date.now()>p)return O.token;let t;try{t=await j()}catch(t){throw t instanceof e.i?t:new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:t})}let n=C(t);if(!n.token)throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=S(n.expires,3600);return O={token:n.token,expiresAtMs:Date.now()+r*1e3},O.token}function N(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function P(e){let t=N(e?.wssUrl);return t?(A=t,t):A||M()}async function F(t){let n=t||await M(),r=await w(D,m,{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:`${m} 返回了非 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 k=a.data,k}let I=e=>t.i(e,T);function L(t){let r=String(n.sipWsUrl??``).trim();if(!r)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 sipWsUrl:软电话 WSS 地址由接入方提供(wss:// 或 ws:// 开头的完整地址)`});let i;try{i=new URL(r)}catch{throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`sipWsUrl 不是完整地址(需要 wss:// 或 ws:// 开头):${r}`})}if(i.protocol!==`wss:`&&i.protocol!==`ws:`)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`sipWsUrl 需要 wss:// 或 ws:// 开头:${r}`});return(n.attachTokenToWss??!0)&&t&&i.searchParams.set(`token`,t),i.toString()}function R(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)||c}`]}]:[]}async function z(){let t=await M(),i=await F(),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 I(o):``;if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let c=S(i.expiresIn??i.expires_in,u),d=Math.max(0,Math.round((O.expiresAtMs-Date.now())/1e3)),p=Math.max(f,Math.min(d||c,c)-E),m=String(i.domain??``).trim()||x(r),g=L(t);return t&&(A=t),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+p,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${m}`,registrar:m,registerTicket:s,registerExpires:Number(n.registerExpires)>0?Number(n.registerExpires):l,ticketExpiresIn:p},transport:{wssUrl:g,ticket:``,ticketExpiresIn:p},iceServers:R(i),policy:{maxConcurrentCalls:Number(n.maxConcurrentCalls)>0?Number(n.maxConcurrentCalls):2,incomingEnabled:n.incomingEnabled??!0,mobileIncomingEnabled:n.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...n.capabilities??h]}}return{createSession:z,refreshSession:z,setAgentStatus:async({status:t,reason:n},r)=>{let i=await P(r),a=k??await F(i),o=String(a.username??a.account??``).trim();if(!o)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let s=g[t],c=await w(D,_,{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:`${_} 返回了非 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:()=>{O=void 0,A=``},getSeatAccount:async()=>k??F()}}function v(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 y(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function b(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function x(e){try{return new URL(e).hostname}catch{return``}}function S(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),f),86400))}function C(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 w(t,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),m);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}超时(${m/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${t instanceof Error?t.message:String(t)})`})}finally{clearTimeout(o)}}var T=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=_,exports.decryptSipPassword=t.i,exports.legacyVersion=T;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-39dch6xL.cjs"),t=require("../legacySessionProvider-DTVNPQRk.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.r(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=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=t.t,exports.decryptSipPassword=t.o,exports.legacyVersion=a;
@@ -1,12 +1,12 @@
1
1
  import { i as e } from "../SharedWorkerProtocol-DKVQ5-po.js";
2
- import { i as t, t as n } from "../CCBarClient-Dmw3T0lF.js";
2
+ import { o as t, r as n, t as r } from "../legacySessionProvider-BFVae8mj.js";
3
3
  //#region src/legacy/CCBarSDK.ts
4
- var r = class extends Error {
4
+ var i = class extends Error {
5
5
  code = "LEGACY_METHOD_DEPRECATED";
6
6
  constructor(e, t) {
7
7
  super(`${e} 已废弃:${t}`), this.name = "DeprecatedError";
8
8
  }
9
- }, i = class {
9
+ }, a = class {
10
10
  client;
11
11
  warnedMethods = /* @__PURE__ */ new Set();
12
12
  unsubscribeIncoming;
@@ -83,7 +83,7 @@ var r = class extends Error {
83
83
  return this.warn("setId", "请改用 client.setAgentStatus('available')"), this.client.setAgentStatus("available");
84
84
  }
85
85
  setBu(...e) {
86
- throw this.warn("setBu", "busy由通话状态或服务端状态策略控制,浏览器不得伪造"), new r("setBu()", "busy由通话状态或服务端状态策略控制,浏览器不得伪造");
86
+ throw this.warn("setBu", "busy由通话状态或服务端状态策略控制,浏览器不得伪造"), new i("setBu()", "busy由通话状态或服务端状态策略控制,浏览器不得伪造");
87
87
  }
88
88
  setRe(...e) {
89
89
  return this.warn("setRe", "请改用 client.setAgentStatus('break')"), this.client.setAgentStatus("break");
@@ -94,283 +94,15 @@ var r = class extends Error {
94
94
  return this.currentCall;
95
95
  }
96
96
  warn(e, t) {
97
- a() && !this.warnedMethods.has(e) && (this.warnedMethods.add(e), console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`));
97
+ o() && !this.warnedMethods.has(e) && (this.warnedMethods.add(e), console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`));
98
98
  }
99
99
  };
100
- function a() {
100
+ function o() {
101
101
  return !1;
102
102
  }
103
103
  //#endregion
104
- //#region src/legacy/legacySessionProvider.ts
105
- var o = "/openapi/token/v1", s = "/seat/account/get", c = "/seats/set-status", l = 3478, u = 600, d = 600, f = 180, p = 60, m = 5e3, h = 2e4, g = [
106
- "outbound",
107
- "inbound",
108
- "mute",
109
- "dtmf",
110
- "hold",
111
- "blind_transfer"
112
- ], _ = {
113
- available: {
114
- status: "Available",
115
- reason: "空闲"
116
- },
117
- break: {
118
- status: "On Break",
119
- reason: "休息"
120
- },
121
- offline: {
122
- status: "Logged Out",
123
- reason: ""
124
- }
125
- };
126
- function v(n) {
127
- let r = y(n.host), i = b(n.pathPrefix ?? o), a = `${r}${i}${x(n.accountPath ?? s)}`, h = `${r}${i}${x(n.statusPath ?? c)}`, v = {
128
- ...n.aesKey ? { key: n.aesKey } : {},
129
- ...n.aesIv ? { iv: n.aesIv } : {}
130
- }, E = Math.max(0, n.refreshBufferSeconds ?? f), D = n.fetchImpl ?? globalThis.fetch, O, k, A = "";
131
- async function j() {
132
- if (n.getToken !== void 0) return n.getToken();
133
- if (n.tokenUrl !== void 0) {
134
- let t = n.tokenMethod ?? "POST", r = {
135
- method: t,
136
- headers: {
137
- Accept: "application/json",
138
- ...n.tokenHeaders ?? {}
139
- },
140
- credentials: "include"
141
- };
142
- t === "POST" && (r.headers = {
143
- "Content-Type": "application/json",
144
- ...r.headers
145
- }, r.body = JSON.stringify(n.tokenBody ?? {}));
146
- let i = await T(D, n.tokenUrl, r, "取 token"), a = await i.text();
147
- try {
148
- return JSON.parse(a);
149
- } catch {
150
- throw new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, {
151
- status: i.status,
152
- cause: `取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0, 120)}`
153
- });
154
- }
155
- }
156
- throw new e("CONFIG_INVALID", "configuration", !1, { cause: "createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用" });
157
- }
158
- async function M() {
159
- if (O && O.expiresAtMs - Date.now() > m) return O.token;
160
- let t;
161
- try {
162
- t = await j();
163
- } catch (t) {
164
- throw t instanceof e ? t : new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, { cause: t });
165
- }
166
- let n = w(t);
167
- if (!n.token) throw new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, { cause: "取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)" });
168
- let r = C(n.expires, 3600);
169
- return O = {
170
- token: n.token,
171
- expiresAtMs: Date.now() + r * 1e3
172
- }, O.token;
173
- }
174
- function N(e) {
175
- if (!e) return "";
176
- try {
177
- return String(new URL(e).searchParams.get("token") ?? "").trim();
178
- } catch {
179
- return "";
180
- }
181
- }
182
- async function P(e) {
183
- let t = N(e?.wssUrl);
184
- return t ? (A = t, t) : A || M();
185
- }
186
- async function F(t) {
187
- let n = t || await M(), r = await T(D, a, {
188
- method: "POST",
189
- headers: {
190
- Authorization: n,
191
- "Content-Type": "application/json",
192
- Accept: "application/json"
193
- },
194
- body: "{}"
195
- }, "取坐席账号"), i = await r.text(), o;
196
- try {
197
- o = JSON.parse(i);
198
- } catch {
199
- throw new e("LEGACY_PLATFORM_UNREACHABLE", "network", !0, {
200
- status: r.status,
201
- cause: `${a} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`
202
- });
203
- }
204
- let s = Number(o.code ?? NaN);
205
- if (!r.ok || s !== 0) throw new e("LEGACY_PLATFORM_REJECTED", "auth", s === 50, {
206
- status: r.status,
207
- serverCode: Number.isFinite(s) ? String(s) : void 0,
208
- cause: o.message || `取坐席账号失败(HTTP ${r.status})`
209
- });
210
- if (!o.data) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号接口没有返回 data" });
211
- return k = o.data, k;
212
- }
213
- let I = (e) => t(e, v);
214
- function L(t) {
215
- let r = String(n.sipWsUrl ?? "").trim();
216
- if (!r) throw new e("CONFIG_INVALID", "configuration", !1, { cause: "需要 sipWsUrl:软电话 WSS 地址由接入方提供(wss:// 或 ws:// 开头的完整地址)" });
217
- let i;
218
- try {
219
- i = new URL(r);
220
- } catch {
221
- throw new e("CONFIG_INVALID", "configuration", !1, { cause: `sipWsUrl 不是完整地址(需要 wss:// 或 ws:// 开头):${r}` });
222
- }
223
- if (i.protocol !== "wss:" && i.protocol !== "ws:") throw new e("CONFIG_INVALID", "configuration", !1, { cause: `sipWsUrl 需要 wss:// 或 ws:// 开头:${r}` });
224
- return (n.attachTokenToWss ?? !0) && t && i.searchParams.set("token", t), i.toString();
225
- }
226
- function R(e) {
227
- let t = (Array.isArray(e.iceServers) ? e.iceServers : []).map((e) => {
228
- let t = (Array.isArray(e?.urls) ? e.urls : typeof e?.urls == "string" ? [e.urls] : []).map((e) => String(e ?? "").trim()).filter(Boolean);
229
- if (t.length !== 0) return {
230
- urls: t,
231
- ...e?.username ? { username: String(e.username) } : {},
232
- ...e?.credential ? { credential: String(e.credential) } : {}
233
- };
234
- }).filter((e) => e !== void 0);
235
- if (t.length > 0) return t;
236
- let n = String(e.turnIp ?? "").trim();
237
- return n ? [{ urls: [`stun:${n}:${Number(e.turnPort) || l}`] }] : [];
238
- }
239
- async function z() {
240
- let t = await M(), i = await F(), a = String(i.username ?? i.account ?? "").trim();
241
- if (!a) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 username" });
242
- let o = String(i.registerPassword ?? i.password ?? ""), s = o ? await I(o) : "";
243
- if (!s) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 password/registerPassword,或解密后为空" });
244
- let c = C(i.expiresIn ?? i.expires_in, d), l = Math.max(0, Math.round((O.expiresAtMs - Date.now()) / 1e3)), f = Math.max(p, Math.min(l || c, c) - E), m = String(i.domain ?? "").trim() || S(r), h = L(t);
245
- return t && (A = t), {
246
- sessionId: `legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
247
- expiresAt: Math.floor(Date.now() / 1e3) + f,
248
- agent: {
249
- id: a,
250
- externalUserId: a,
251
- displayName: a,
252
- extension: a,
253
- status: "Available"
254
- },
255
- sip: {
256
- uri: `sip:${a}@${m}`,
257
- registrar: m,
258
- registerTicket: s,
259
- registerExpires: Number(n.registerExpires) > 0 ? Number(n.registerExpires) : u,
260
- ticketExpiresIn: f
261
- },
262
- transport: {
263
- wssUrl: h,
264
- ticket: "",
265
- ticketExpiresIn: f
266
- },
267
- iceServers: R(i),
268
- policy: {
269
- maxConcurrentCalls: Number(n.maxConcurrentCalls) > 0 ? Number(n.maxConcurrentCalls) : 2,
270
- incomingEnabled: n.incomingEnabled ?? !0,
271
- mobileIncomingEnabled: n.mobileIncomingEnabled ?? !0,
272
- backgroundCallingSupported: !1
273
- },
274
- capabilities: [...n.capabilities ?? g]
275
- };
276
- }
277
- return {
278
- createSession: z,
279
- refreshSession: z,
280
- setAgentStatus: async ({ status: t, reason: n }, r) => {
281
- let i = await P(r), a = k ?? await F(i), o = String(a.username ?? a.account ?? "").trim();
282
- if (!o) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 username" });
283
- let s = _[t], c = await T(D, h, {
284
- method: "POST",
285
- headers: {
286
- Authorization: i,
287
- "Content-Type": "application/json",
288
- Accept: "application/json"
289
- },
290
- body: JSON.stringify({
291
- extension: o,
292
- status: s.status,
293
- reason: n || s.reason
294
- })
295
- }, "设置坐席状态"), l = await c.text(), u;
296
- try {
297
- u = JSON.parse(l);
298
- } catch {
299
- throw new e("LEGACY_PLATFORM_UNREACHABLE", "network", !0, {
300
- status: c.status,
301
- cause: `${h} 返回了非 JSON 响应(HTTP ${c.status})`
302
- });
303
- }
304
- let d = Number(u.code ?? NaN);
305
- if (!c.ok || d !== 0) throw new e("LEGACY_PLATFORM_REJECTED", "auth", d === 50, {
306
- status: c.status,
307
- serverCode: Number.isFinite(d) ? String(d) : void 0,
308
- cause: u.message || `设置坐席状态失败(HTTP ${c.status})`
309
- });
310
- },
311
- invalidateToken: () => {
312
- O = void 0, A = "";
313
- },
314
- getSeatAccount: async () => k ?? F()
315
- };
316
- }
317
- function y(t) {
318
- let n = String(t ?? "").trim().replace(/\/+$/, "");
319
- if (!n) throw new e("CONFIG_INVALID", "configuration", !1, { cause: "createLegacySessionProvider 需要 host" });
320
- return /^https?:\/\//i.test(n) ? n : `https://${n}`;
321
- }
322
- function b(e) {
323
- let t = String(e ?? "").trim();
324
- return !t || t === "/" ? "" : `/${t.replace(/^\/+|\/+$/g, "")}`;
325
- }
326
- function x(e) {
327
- let t = String(e ?? "").trim();
328
- return t.startsWith("/") ? t : `/${t}`;
329
- }
330
- function S(e) {
331
- try {
332
- return new URL(e).hostname;
333
- } catch {
334
- return "";
335
- }
336
- }
337
- function C(e, t) {
338
- let n = Number(e);
339
- return !Number.isFinite(n) || n <= 0 ? t : (n > 86400 && (n /= 1e3), Math.min(Math.max(Math.floor(n), p), 86400));
340
- }
341
- function w(e) {
342
- if (typeof e == "string") return { token: e.trim() };
343
- let t = e ?? {}, n = typeof t.data == "object" && t.data !== null ? t.data : void 0;
344
- for (let e of [t, n]) {
345
- if (e === void 0) continue;
346
- let t = e.token ?? e.accessToken;
347
- if (typeof t == "string" && t.trim()) {
348
- let n = Number(e.expires ?? e.expiresIn ?? e.expires_at);
349
- return {
350
- token: t.trim(),
351
- ...Number.isFinite(n) && n > 0 ? { expires: n } : {}
352
- };
353
- }
354
- }
355
- return { token: "" };
356
- }
357
- async function T(t, n, r, i) {
358
- let a = new AbortController(), o = setTimeout(() => a.abort(), h);
359
- try {
360
- return await t(n, {
361
- ...r,
362
- signal: a.signal
363
- });
364
- } catch (t) {
365
- let r = a.signal.aborted;
366
- throw new e(r ? "NETWORK_TIMEOUT" : "LEGACY_PLATFORM_UNREACHABLE", "network", !0, { cause: r ? `${i}超时(${h / 1e3} 秒):POST ${n}` : `${i}失败:无法请求 ${n}(${t instanceof Error ? t.message : String(t)})` });
367
- } finally {
368
- clearTimeout(o);
369
- }
370
- }
371
- //#endregion
372
104
  //#region src/legacy/index.ts
373
- var E = "0.1.0";
374
- typeof window < "u" && (window.CCBarSDK = i);
105
+ var s = "0.1.0";
106
+ typeof window < "u" && (window.CCBarSDK = a);
375
107
  //#endregion
376
- export { i as CCBarSDK, r as DeprecatedError, v as createLegacySessionProvider, t as decryptSipPassword, E as legacyVersion };
108
+ export { a as CCBarSDK, i as DeprecatedError, r as createLegacySessionProvider, t as decryptSipPassword, s as legacyVersion };
@@ -29,7 +29,8 @@ export interface LegacySeatAccount {
29
29
  }>;
30
30
  [key: string]: unknown;
31
31
  }
32
- export interface LegacyPlatformSessionProviderOptions {
32
+ export type TokenSessionSeatAccount = LegacySeatAccount;
33
+ export interface TokenSessionProviderOptions {
33
34
  /** 平台网关地址,例如 `https://vxapi.yundianlab.com`(不含路径前缀);必填 */
34
35
  host: string;
35
36
  /** 取 token 的两种写法二选一:函数(接入方自己调) */
@@ -74,10 +75,16 @@ export interface LegacyPlatformSessionProviderOptions {
74
75
  /** 请求实现(测试/代理场景可替换),默认全局 fetch */
75
76
  fetchImpl?: typeof fetch;
76
77
  }
78
+ /** @deprecated Use TokenSessionProviderOptions. */
79
+ export type LegacyPlatformSessionProviderOptions = TokenSessionProviderOptions;
80
+ export type TokenSessionProvider = SessionProvider & {
81
+ getSeatAccount(): Promise<TokenSessionSeatAccount>;
82
+ };
83
+ export type TokenSessionTokenResult = LegacyTokenResult;
77
84
  /**
78
- * 造一个会话来源:`new CCBarClient({ sessionProvider: createLegacySessionProvider({...}) })`。
85
+ * Create a token-backed session provider for the package's root npm API.
79
86
  * `refreshSession` 与 `createSession` 等价——整条链路重跑一遍,等价于换一次 SIP 密码。
80
87
  */
81
- export declare function createLegacySessionProvider(options: LegacyPlatformSessionProviderOptions): SessionProvider & {
82
- getSeatAccount(): Promise<LegacySeatAccount>;
83
- };
88
+ export declare function createTokenSessionProvider(options: TokenSessionProviderOptions): TokenSessionProvider;
89
+ /** @deprecated Use createTokenSessionProvider. Kept for existing /legacy consumers. */
90
+ export declare function createLegacySessionProvider(options: LegacyPlatformSessionProviderOptions): TokenSessionProvider;