@16x/webphone-sdk 3.1.17 → 3.1.19
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 +267 -31
- package/LICENSE +1 -1
- package/README.md +214 -161
- package/dist/{Diagnostics-CK0ai_sy.cjs → Diagnostics-CgDSPlQx.cjs} +1 -1
- package/dist/{Diagnostics-B6xGNl8M.js → Diagnostics-DJdBDGad.js} +1 -1
- package/dist/{JsSipAdapter-l97xq1ao.cjs → JsSipAdapter-CgBtmR16.cjs} +1 -1
- package/dist/{JsSipAdapter-B8ueIoBA.js → JsSipAdapter-CiqM4KOq.js} +1 -1
- package/dist/SharedWorkerProtocol-4VARy5ma.cjs +1 -0
- package/dist/SharedWorkerProtocol-DvLUl0JZ.js +93 -0
- package/dist/core/CCBarCall.d.ts +1 -1
- package/dist/createJsSipFactory-9CPsweDR.js +9665 -0
- package/dist/createJsSipFactory-Dr8HbLl-.cjs +75 -0
- package/dist/crypto/legacySipTicket.d.ts +40 -0
- package/dist/diagnostics/index.cjs +1 -1
- package/dist/diagnostics/index.js +1 -1
- package/dist/errors/CCBarError.d.ts +2 -0
- package/dist/i18n/index.d.ts +22 -0
- package/dist/i18n/messages/en-US.d.ts +2 -0
- package/dist/i18n/messages/es-ES.d.ts +2 -0
- package/dist/i18n/messages/id-ID.d.ts +2 -0
- package/dist/i18n/messages/index.d.ts +7 -0
- package/dist/i18n/messages/zh-CN.d.ts +2 -0
- package/dist/i18n/types.d.ts +5 -0
- package/dist/i18n-BbEy6K9z.cjs +1 -0
- package/dist/i18n-D-DdHtGz.js +150 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +9 -8
- package/dist/index.umd.js +69 -16
- package/dist/legacy/index.cjs +1 -1
- package/dist/legacy/index.js +10 -276
- package/dist/legacy/legacySessionProvider.d.ts +20 -9
- package/dist/legacySessionProvider-CKJyrade.cjs +1 -0
- package/dist/{CCBarClient-C2sC86Xi.js → legacySessionProvider-DBrRBB3S.js} +795 -493
- package/dist/shared/SharedWorkerFactory.d.ts +2 -0
- package/dist/shared/SharedWorkerProtocol.d.ts +2 -0
- package/dist/shared-worker.cjs +1 -1
- package/dist/shared-worker.js +65 -64
- package/dist/styles.css +7 -7
- package/dist/ui/i18n/es-ES.d.ts +2 -0
- package/dist/ui/i18n/id-ID.d.ts +2 -0
- package/dist/ui/i18n/index.d.ts +2 -0
- package/dist/ui/index.cjs +1 -1
- package/dist/ui/index.js +278 -170
- package/dist/version.d.ts +1 -1
- package/package.json +114 -109
- package/dist/CCBarClient-GQ3yxDur.cjs +0 -1
- package/dist/SharedWorkerProtocol-C-4KpECM.cjs +0 -1
- package/dist/SharedWorkerProtocol-CffZrUXg.js +0 -119
- package/dist/createJsSipFactory-B1ORbJiP.cjs +0 -22
- package/dist/createJsSipFactory-CoWZN-BC.js +0 -7410
package/dist/legacy/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-4VARy5ma.cjs"),t=require("../legacySessionProvider-CKJyrade.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.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;
|
package/dist/legacy/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { i as e } from "../SharedWorkerProtocol-
|
|
2
|
-
import {
|
|
1
|
+
import { i as e } from "../SharedWorkerProtocol-DvLUl0JZ.js";
|
|
2
|
+
import { o as t, r as n, t as r } from "../legacySessionProvider-DBrRBB3S.js";
|
|
3
3
|
//#region src/legacy/CCBarSDK.ts
|
|
4
|
-
var
|
|
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
|
-
},
|
|
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
|
|
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,281 +94,15 @@ var r = class extends Error {
|
|
|
94
94
|
return this.currentCall;
|
|
95
95
|
}
|
|
96
96
|
warn(e, t) {
|
|
97
|
-
|
|
97
|
+
o() && !this.warnedMethods.has(e) && (this.warnedMethods.add(e), console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`));
|
|
98
98
|
}
|
|
99
99
|
};
|
|
100
|
-
function
|
|
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 = "/api/fs/sip-ws", u = 7443, d = 3478, f = 600, p = 600, m = 180, h = 60, g = 5e3, _ = 2e4, v = [
|
|
106
|
-
"outbound",
|
|
107
|
-
"inbound",
|
|
108
|
-
"mute",
|
|
109
|
-
"dtmf",
|
|
110
|
-
"hold",
|
|
111
|
-
"blind_transfer"
|
|
112
|
-
], y = {
|
|
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 b(n) {
|
|
127
|
-
let r = x(n.host), i = S(n.pathPrefix ?? o), a = `${r}${i}${C(n.accountPath ?? s)}`, _ = `${r}${i}${C(n.statusPath ?? c)}`, b = C(n.sipWsPath ?? l), O = {
|
|
128
|
-
...n.aesKey ? { key: n.aesKey } : {},
|
|
129
|
-
...n.aesIv ? { iv: n.aesIv } : {}
|
|
130
|
-
}, k = Math.max(0, n.refreshBufferSeconds ?? m), A = n.fetchImpl ?? globalThis.fetch, j, M, N = "";
|
|
131
|
-
async function P() {
|
|
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 D(A, 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 F() {
|
|
159
|
-
if (j && j.expiresAtMs - Date.now() > g) return j.token;
|
|
160
|
-
let t;
|
|
161
|
-
try {
|
|
162
|
-
t = await P();
|
|
163
|
-
} catch (t) {
|
|
164
|
-
throw t instanceof e ? t : new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, { cause: t });
|
|
165
|
-
}
|
|
166
|
-
let n = E(t);
|
|
167
|
-
if (!n.token) throw new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, { cause: "取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)" });
|
|
168
|
-
let r = T(n.expires, 3600);
|
|
169
|
-
return j = {
|
|
170
|
-
token: n.token,
|
|
171
|
-
expiresAtMs: Date.now() + r * 1e3
|
|
172
|
-
}, j.token;
|
|
173
|
-
}
|
|
174
|
-
function I(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 L(e) {
|
|
183
|
-
let t = I(e?.wssUrl);
|
|
184
|
-
return t ? (N = t, t) : N || F();
|
|
185
|
-
}
|
|
186
|
-
async function R(t) {
|
|
187
|
-
let n = t || await F(), r = await D(A, 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 M = o.data, M;
|
|
212
|
-
}
|
|
213
|
-
let z = (e) => t(e, O);
|
|
214
|
-
function B(t, i) {
|
|
215
|
-
let a = Number(t.wssPort) || u, o = String(t.domain ?? "").trim(), s = String(n.sipWsUrl ?? "").trim(), c;
|
|
216
|
-
if (s) c = new URL(s, r), c.protocol === "http:" && (c.protocol = "ws:"), c.protocol === "https:" && (c.protocol = "wss:");
|
|
217
|
-
else {
|
|
218
|
-
if (!o) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定" });
|
|
219
|
-
let t = a === 443 ? "" : `:${a}`;
|
|
220
|
-
c = new URL(`wss://${o}${t}${b}`);
|
|
221
|
-
}
|
|
222
|
-
return (n.attachTokenToWss ?? !0) && i && c.searchParams.set("token", i), c.toString();
|
|
223
|
-
}
|
|
224
|
-
function V(e) {
|
|
225
|
-
let t = (Array.isArray(e.iceServers) ? e.iceServers : []).map((e) => {
|
|
226
|
-
let t = (Array.isArray(e?.urls) ? e.urls : typeof e?.urls == "string" ? [e.urls] : []).map((e) => String(e ?? "").trim()).filter(Boolean);
|
|
227
|
-
if (t.length !== 0) return {
|
|
228
|
-
urls: t,
|
|
229
|
-
...e?.username ? { username: String(e.username) } : {},
|
|
230
|
-
...e?.credential ? { credential: String(e.credential) } : {}
|
|
231
|
-
};
|
|
232
|
-
}).filter((e) => e !== void 0);
|
|
233
|
-
if (t.length > 0) return t;
|
|
234
|
-
let n = String(e.turnIp ?? "").trim();
|
|
235
|
-
return n ? [{ urls: [`stun:${n}:${Number(e.turnPort) || d}`] }] : [];
|
|
236
|
-
}
|
|
237
|
-
async function H() {
|
|
238
|
-
let t = await F(), i = await R(), a = String(i.username ?? i.account ?? "").trim();
|
|
239
|
-
if (!a) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 username" });
|
|
240
|
-
let o = String(i.registerPassword ?? i.password ?? ""), s = o ? await z(o) : "";
|
|
241
|
-
if (!s) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 password/registerPassword,或解密后为空" });
|
|
242
|
-
let c = T(i.expiresIn ?? i.expires_in, p), l = Math.max(0, Math.round((j.expiresAtMs - Date.now()) / 1e3)), u = Math.max(h, Math.min(l || c, c) - k), d = String(i.domain ?? "").trim() || w(r), m = B(i, t);
|
|
243
|
-
return t && (N = t), {
|
|
244
|
-
sessionId: `legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
245
|
-
expiresAt: Math.floor(Date.now() / 1e3) + u,
|
|
246
|
-
agent: {
|
|
247
|
-
id: a,
|
|
248
|
-
externalUserId: a,
|
|
249
|
-
displayName: a,
|
|
250
|
-
extension: a,
|
|
251
|
-
status: "Available"
|
|
252
|
-
},
|
|
253
|
-
sip: {
|
|
254
|
-
uri: `sip:${a}@${d}`,
|
|
255
|
-
registrar: d,
|
|
256
|
-
registerTicket: s,
|
|
257
|
-
registerExpires: Number(n.registerExpires) > 0 ? Number(n.registerExpires) : f,
|
|
258
|
-
ticketExpiresIn: u
|
|
259
|
-
},
|
|
260
|
-
transport: {
|
|
261
|
-
wssUrl: m,
|
|
262
|
-
ticket: "",
|
|
263
|
-
ticketExpiresIn: u
|
|
264
|
-
},
|
|
265
|
-
iceServers: V(i),
|
|
266
|
-
policy: {
|
|
267
|
-
maxConcurrentCalls: Number(n.maxConcurrentCalls) > 0 ? Number(n.maxConcurrentCalls) : 2,
|
|
268
|
-
incomingEnabled: n.incomingEnabled ?? !0,
|
|
269
|
-
mobileIncomingEnabled: n.mobileIncomingEnabled ?? !0,
|
|
270
|
-
backgroundCallingSupported: !1
|
|
271
|
-
},
|
|
272
|
-
capabilities: [...n.capabilities ?? v]
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
return {
|
|
276
|
-
createSession: H,
|
|
277
|
-
refreshSession: H,
|
|
278
|
-
setAgentStatus: async ({ status: t, reason: n }, r) => {
|
|
279
|
-
let i = await L(r), a = M ?? await R(i), o = String(a.username ?? a.account ?? "").trim();
|
|
280
|
-
if (!o) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 username" });
|
|
281
|
-
let s = y[t], c = await D(A, _, {
|
|
282
|
-
method: "POST",
|
|
283
|
-
headers: {
|
|
284
|
-
Authorization: i,
|
|
285
|
-
"Content-Type": "application/json",
|
|
286
|
-
Accept: "application/json"
|
|
287
|
-
},
|
|
288
|
-
body: JSON.stringify({
|
|
289
|
-
extension: o,
|
|
290
|
-
status: s.status,
|
|
291
|
-
reason: n || s.reason
|
|
292
|
-
})
|
|
293
|
-
}, "设置坐席状态"), l = await c.text(), u;
|
|
294
|
-
try {
|
|
295
|
-
u = JSON.parse(l);
|
|
296
|
-
} catch {
|
|
297
|
-
throw new e("LEGACY_PLATFORM_UNREACHABLE", "network", !0, {
|
|
298
|
-
status: c.status,
|
|
299
|
-
cause: `${_} 返回了非 JSON 响应(HTTP ${c.status})`
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
let d = Number(u.code ?? NaN);
|
|
303
|
-
if (!c.ok || d !== 0) throw new e("LEGACY_PLATFORM_REJECTED", "auth", d === 50, {
|
|
304
|
-
status: c.status,
|
|
305
|
-
serverCode: Number.isFinite(d) ? String(d) : void 0,
|
|
306
|
-
cause: u.message || `设置坐席状态失败(HTTP ${c.status})`
|
|
307
|
-
});
|
|
308
|
-
},
|
|
309
|
-
invalidateToken: () => {
|
|
310
|
-
j = void 0, N = "";
|
|
311
|
-
},
|
|
312
|
-
getSeatAccount: async () => M ?? R()
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
function x(t) {
|
|
316
|
-
let n = String(t ?? "").trim().replace(/\/+$/, "");
|
|
317
|
-
if (!n) throw new e("CONFIG_INVALID", "configuration", !1, { cause: "createLegacySessionProvider 需要 host" });
|
|
318
|
-
return /^https?:\/\//i.test(n) ? n : `https://${n}`;
|
|
319
|
-
}
|
|
320
|
-
function S(e) {
|
|
321
|
-
let t = String(e ?? "").trim();
|
|
322
|
-
return !t || t === "/" ? "" : `/${t.replace(/^\/+|\/+$/g, "")}`;
|
|
323
|
-
}
|
|
324
|
-
function C(e) {
|
|
325
|
-
let t = String(e ?? "").trim();
|
|
326
|
-
return t.startsWith("/") ? t : `/${t}`;
|
|
327
|
-
}
|
|
328
|
-
function w(e) {
|
|
329
|
-
try {
|
|
330
|
-
return new URL(e).hostname;
|
|
331
|
-
} catch {
|
|
332
|
-
return "";
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
function T(e, t) {
|
|
336
|
-
let n = Number(e);
|
|
337
|
-
return !Number.isFinite(n) || n <= 0 ? t : (n > 86400 && (n /= 1e3), Math.min(Math.max(Math.floor(n), h), 86400));
|
|
338
|
-
}
|
|
339
|
-
function E(e) {
|
|
340
|
-
if (typeof e == "string") return { token: e.trim() };
|
|
341
|
-
let t = e ?? {}, n = typeof t.data == "object" && t.data !== null ? t.data : void 0;
|
|
342
|
-
for (let e of [t, n]) {
|
|
343
|
-
if (e === void 0) continue;
|
|
344
|
-
let t = e.token ?? e.accessToken;
|
|
345
|
-
if (typeof t == "string" && t.trim()) {
|
|
346
|
-
let n = Number(e.expires ?? e.expiresIn ?? e.expires_at);
|
|
347
|
-
return {
|
|
348
|
-
token: t.trim(),
|
|
349
|
-
...Number.isFinite(n) && n > 0 ? { expires: n } : {}
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
return { token: "" };
|
|
354
|
-
}
|
|
355
|
-
async function D(t, n, r, i) {
|
|
356
|
-
let a = new AbortController(), o = setTimeout(() => a.abort(), _);
|
|
357
|
-
try {
|
|
358
|
-
return await t(n, {
|
|
359
|
-
...r,
|
|
360
|
-
signal: a.signal
|
|
361
|
-
});
|
|
362
|
-
} catch (t) {
|
|
363
|
-
let r = a.signal.aborted;
|
|
364
|
-
throw new e(r ? "NETWORK_TIMEOUT" : "LEGACY_PLATFORM_UNREACHABLE", "network", !0, { cause: r ? `${i}超时(${_ / 1e3} 秒):POST ${n}` : `${i}失败:无法请求 ${n}(${t instanceof Error ? t.message : String(t)})` });
|
|
365
|
-
} finally {
|
|
366
|
-
clearTimeout(o);
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
//#endregion
|
|
370
104
|
//#region src/legacy/index.ts
|
|
371
|
-
var
|
|
372
|
-
typeof window < "u" && (window.CCBarSDK =
|
|
105
|
+
var s = "0.1.0";
|
|
106
|
+
typeof window < "u" && (window.CCBarSDK = a);
|
|
373
107
|
//#endregion
|
|
374
|
-
export {
|
|
108
|
+
export { a as CCBarSDK, i as DeprecatedError, r as createLegacySessionProvider, t as decryptSipPassword, s as legacyVersion };
|
|
@@ -15,7 +15,9 @@ export interface LegacySeatAccount {
|
|
|
15
15
|
registerPassword?: string;
|
|
16
16
|
expiresIn?: number;
|
|
17
17
|
expires_in?: number;
|
|
18
|
+
/** SIP 域名:拼 `sip.uri` / `sip.registrar` 用(软电话地址不再从这里拼,见 `sipWsUrl`) */
|
|
18
19
|
domain?: string;
|
|
20
|
+
/** 平台返回的端口字段:SDK 不再读它们(软电话地址由接入方传 `sipWsUrl`) */
|
|
19
21
|
wsPort?: number;
|
|
20
22
|
wssPort?: number;
|
|
21
23
|
turnIp?: string;
|
|
@@ -27,7 +29,8 @@ export interface LegacySeatAccount {
|
|
|
27
29
|
}>;
|
|
28
30
|
[key: string]: unknown;
|
|
29
31
|
}
|
|
30
|
-
export
|
|
32
|
+
export type TokenSessionSeatAccount = LegacySeatAccount;
|
|
33
|
+
export interface TokenSessionProviderOptions {
|
|
31
34
|
/** 平台网关地址,例如 `https://vxapi.yundianlab.com`(不含路径前缀);必填 */
|
|
32
35
|
host: string;
|
|
33
36
|
/** 取 token 的两种写法二选一:函数(接入方自己调) */
|
|
@@ -46,10 +49,12 @@ export interface LegacyPlatformSessionProviderOptions {
|
|
|
46
49
|
accountPath?: string;
|
|
47
50
|
/** 坐席状态路径(相对 pathPrefix),默认 `/seats/set-status` */
|
|
48
51
|
statusPath?: string;
|
|
49
|
-
/**
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
/**
|
|
53
|
+
* 软电话 WSS 地址(必填):`wss://` 或 `ws://` 开头的**完整地址**。
|
|
54
|
+
* SDK 只在这个地址上挂 `?token=<fs token>`(见 `attachTokenToWss`),
|
|
55
|
+
* 不再按坐席账号的 domain / wssPort 拼装,也不接受相对路径。
|
|
56
|
+
*/
|
|
57
|
+
sipWsUrl: string;
|
|
53
58
|
/** 是否把 token 挂到 WSS 的 `?token=`,默认 true(旧页面那套不挂时可设 false) */
|
|
54
59
|
attachTokenToWss?: boolean;
|
|
55
60
|
/** AES key / iv(16 字节,UTF-8);默认用平台内置值 */
|
|
@@ -70,10 +75,16 @@ export interface LegacyPlatformSessionProviderOptions {
|
|
|
70
75
|
/** 请求实现(测试/代理场景可替换),默认全局 fetch */
|
|
71
76
|
fetchImpl?: typeof fetch;
|
|
72
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;
|
|
73
84
|
/**
|
|
74
|
-
*
|
|
85
|
+
* Create a token-backed session provider for the package's root npm API.
|
|
75
86
|
* `refreshSession` 与 `createSession` 等价——整条链路重跑一遍,等价于换一次 SIP 密码。
|
|
76
87
|
*/
|
|
77
|
-
export declare function
|
|
78
|
-
|
|
79
|
-
|
|
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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./i18n-BbEy6K9z.cjs"),t=require("./SharedWorkerProtocol-4VARy5ma.cjs"),n=require("./Diagnostics-CgDSPlQx.cjs");var r=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()}},i={new:new Set([`dialing`,`ringing`,`ended`,`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},a=(e,t)=>i[e].has(t);function o(e,t){if(!a(e,t))throw new s(e,t);return t}var s=class extends t.i{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},c=o,l=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],u=3e4,d=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;localHeld=!1;remoteHeld=!1;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(e){this.options=e,this.id=e.id,this.destination=e.destination,this.platform=e.platform,this.capabilities=e.capabilities??new Set;try{l.forEach(t=>{this.sessionUnsubscribers.push(e.session.on(t,e=>this.handleSessionEvent(t,e)))})}catch(n){this.cleanupSessionListeners();try{e.session.terminate()}catch{}throw new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:n})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,()=>this.options.session.hold())}async resume(e){if(this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),this.remoteHeld&&!this.localHeld)throw this.operationError({reason:`remote_hold_active`});await this.startPendingOperation(`resume`,()=>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`),!p(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(!(this.disposed||f(this.currentState))){this.assertOwner(e);try{this.options.session.terminate(),f(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!f(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||f(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.updateHoldState(!0,t,e);break;case`unhold`:this.updateHoldState(!1,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`))}updateHoldState(e,t,n){let r=typeof t==`object`&&t?t.originator:void 0;r===`remote`?this.remoteHeld=e:r===`both`?(this.localHeld=e,this.remoteHeld=e):this.localHeld=e;let i=this.localHeld||this.remoteHeld?`held`:`active`;this.transitionIfAllowed(i,t,n)}transitionIfAllowed(e,t,n){this.currentState!==e&&(a(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(!a(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,f(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{f(e)&&this.dispose()}}startPendingOperation(e,t){if(this.pendingOperation!==void 0)throw this.operationError({reason:`pending_operation_in_progress`,operation:this.pendingOperation.kind});return new Promise((n,r)=>{let i={kind:e,resolve:n,reject:r};this.pendingOperation=i,i.timer=setTimeout(()=>this.timeoutPendingOperation(i),u);let a;try{a=t()}catch(e){this.rejectPendingOperation(e);return}a.then(()=>this.resolvePendingOperation(i),e=>this.rejectPendingOperation(e,i))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||f(this.currentState)){e.reject(this.operationError());return}try{this.localHeld=e.kind===`hold`;let t=this.localHeld||this.remoteHeld?`held`:`active`;this.transitionTo(t),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(e){let n=e instanceof t.i&&e.callId===this.id?e:this.operationError(e);try{this.options.onError?.(n)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(e){return new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:e})}};function f(e){return e===`ended`||e===`failed`}function p(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var m=0;function h(){return m+=1,`call_${Date.now().toString(36)}_${m.toString(36)}`}var g=`X-User-Data`,_=/[^\x20-\x7E]/,v=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function y(e){if(typeof e!=`string`)return[];let n=e.trim();if(n===``)return[];if(_.test(n))throw new t.i(`CALL_INVALID_USERDATA`,`call`,!1,{cause:v});return[`${g}: ${n}`]}var b=class{events=new ee;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(e){this.options=e,this.incomingSessionSnapshot=e.session;try{this.incomingUnsubscribe=e.sip.onIncoming(e=>this.handleIncoming(e))}catch(e){throw new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(e,n){this.assertNotDisposed();let r=this.operationGeneration,i=e.destination.trim();if(i===``)throw new t.i(`CALL_INVALID_DESTINATION`,`call`,!1);let a=/^\+?\d{3,20}$/.test(i),o=/^sips?:[^\s<>@]+(?:@[^\s<>@]+)?$/i.test(i);if(!a&&!o)throw new t.i(`CALL_INVALID_DESTINATION`,`call`,!1);let s=y(e.userdata);this.requireCapability(n,`outbound`);let c=this.callLimit(n);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=c)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=c||this.pendingDestinations.has(i)||[...this.calls.values()].some(e=>e.destination===i))throw new t.i(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(i);let l=h(),u;try{u=await this.holdActiveCallForNewCall(),this.assertGeneration(r,l);let t;try{t=this.options.sip.dial(i,this.dialOptions(l,n,e.type,s))}catch(e){throw this.dialError(e,l)}this.assertGeneration(r,l);let a;try{a=new d({id:l,destination:i,platform:this.options.platform,capabilities:this.effectiveCapabilities(n),session:t,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,l)}if(!this.isCurrentGeneration(r))throw a.dispose(),this.callOperationError(a.id);this.calls.set(a.id,a),this.callSessions.set(a.id,t),this.options.onCallCreated?.(a.id,t);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)&&u!==void 0&&this.isManagedCall(u)&&u.state===`held`)try{await u.resume()}catch(t){throw this.compensationError(u.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(i)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}async forceTerminateCalls(e=5e3){if(this.disposed)return;let t=[...this.calls.values()];for(let n of t){if(this.disposed)return;if(this.calls.get(n.id)===n){try{await Promise.race([n.hangup().catch(()=>void 0),new Promise(t=>setTimeout(t,Math.max(0,e)))])}catch{}try{n.dispose()}catch{}if(this.calls.get(n.id)===n){this.calls.delete(n.id),this.callSessions.delete(n.id),this.callOwners.delete(n.id),this.ownerLostCalls.delete(n.id),this.activeCallId===n.id&&(this.activeCallId=null);try{await this.notifyCallTerminal(n.id)}catch{}}}}}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:te(n)}):this.events.emit(`call.failed`,{callId:e.id,error:re(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(e){if(this.disposed)return;let n=h(),r=this.incomingSessionSnapshot;if(r===void 0||!r.policy.incomingEnabled||!this.effectiveCapabilities(r).has(`inbound`)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:this.capabilityError(n)});return}let i=e.from??e.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(r)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:new t.i(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:n})});return}let a;try{a=new d({id:n,destination:i,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(r),session:e,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,e),this.options.onCallCreated?.(a.id,e);try{a.beginIncoming(),this.events.emit(`call.incoming`,{callId:a.id,from:i})}catch(e){a.dispose(),this.events.emit(`error`,{error:this.callOperationError(a.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new t.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(e,n){return new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e,cause:n})}capabilityError(e){return new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(e,n){return e instanceof t.i?new t.i(e.code,e.category,e.retryable,{requestId:e.requestId,callId:n,cause:e.cause??e}):new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:e})}},ee=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 te(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function ne(e){if(typeof e!=`object`||!e)return;let{cause:t,cause_code:n,message:r}=e,i=typeof n==`number`?n:void 0,a=typeof t==`string`?t:void 0;if(i===void 0&&typeof r==`object`&&r){let e=r.data;if(typeof e==`string`){let t=/^SIP\/2\.0\s+(\d{3})/m.exec(e);if(t)return{code:Number(t[1])}}}return i===void 0&&a===void 0?void 0:{code:i,cause:a}}function re(e,n){if(e instanceof t.i)return new t.i(e.code,e.category,e.retryable,{requestId:e.requestId,callId:n,cause:e.cause??e});if(typeof e==`object`&&e&&`error`in e){let r=e.error;if(r instanceof t.i)return new t.i(r.code,r.category,r.retryable,{requestId:r.requestId,callId:n,cause:r.cause??r});if(r instanceof Error)return new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:r})}let r=ne(e);return r===void 0?new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:e}):r.code===486||r.cause===`Busy`?new t.i(`CALL_BUSY`,`call`,!1,{callId:n,cause:e}):r.code===408||r.cause===`Request Timeout`?new t.i(`NETWORK_TIMEOUT`,`call`,!0,{callId:n,cause:e}):new t.i(`CALL_REJECTED`,`call`,!1,{callId:n,cause:e})}var ie=`q7X4p6MvK1z8Lb3A`,ae=`W9e2T4mN0aQ7Ru6C`,x=16,oe=`�`;function se(e){for(let t of e){let e=t.codePointAt(0)??0;if(e===127||e<32&&e!==9)return!0}return!1}async function S(e,n={}){let r=String(e??``).replace(/\s+/g,``);if(!r)throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`解密的密文为空:坐席账号里没有 password/registerPassword`});let i=n.subtle??globalThis.crypto?.subtle;if(i===void 0)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行`});let a=C(r);if(a===void 0)throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义`});let o=await i.importKey(`raw`,w(n.key??ie),`AES-CBC`,!1,[`decrypt`]);try{let e=await i.decrypt({name:`AES-CBC`,iv:w(n.iv??ae)},o,a);return new TextDecoder(`utf-8`).decode(e).trim()}catch(e){throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`SIP 密码解密失败(检查 key/iv 与该环境是否一致):${e instanceof Error?e.message:String(e)}`})}}async function ce(e,t={}){let n=String(e??``).replace(/\s+/g,``);if(le(n))try{let e=await S(n,t);return ue(e)?e:void 0}catch{return}}function le(e){let t=C(e);return t!==void 0&&t.byteLength>0&&t.byteLength%x===0}function ue(e){return e.length===0||e.includes(oe)?!1:!se(e)}function C(e){if(e.length!==0&&e.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(e))try{let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}catch{return}}function w(e){let t=new TextEncoder().encode(e),n=new Uint8Array(new ArrayBuffer(t.byteLength));return n.set(t),n}var de=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(e){return this.closed?Promise.reject(new t.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(e.requestId)?Promise.reject(new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:e.requestId})):this.lifecycleState===`reconnecting`&&e.type===`command`&&(e.command===`dial`||e.command===`answer`)?Promise.reject(new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:e.payload?.callId})):new Promise((n,r)=>{let i=setTimeout(()=>{this.pending.delete(e.requestId),r(new t.i(`NETWORK_TIMEOUT`,`network`,!0,{requestId:e.requestId}))},this.timeoutMs);this.pending.set(e.requestId,{resolve:e=>n(e),reject:r,timer:i}),this.port.postMessage(e)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(e=>{clearTimeout(e.timer),e.reject(new t.i(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(e){try{let n=t.t(e);if(n.type===`event`){n.event===`connection.stateChanged`&&fe(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(pe(n))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function fe(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function pe(e){let n=e.error;return new t.i(n?.code??`SDK_INTERNAL_ERROR`,n?.category??`internal`,n?.retryable??!1,{requestId:e.requestId,...n?.message===void 0?{}:{cause:n.message},...n?.serverCode===void 0?{}:{serverCode:n.serverCode},...n?.platformCode===void 0?{}:{platformCode:n.platformCode},...n?.status===void 0?{}:{status:n.status}})}function T(e={}){if((e.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let n=e.locationHref??D(),r=E(e.url,n),i=n=>{if(e.fallback===`error`)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:n});return{mode:`single-tab`,reason:n}};if(r===void 0)return i(`SharedWorker URL is unavailable`);if(!he(r,n))return i(`SharedWorker URL must be same-origin`);let a=e.workerCtor??me();if(a===void 0)return i(`SharedWorker is not supported`);let o;try{o=new a(r,e.name===void 0?void 0:{name:e.name})}catch(e){return i(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let s=e.tabId??ge(),c=new de(o.port),l={version:1,type:`attach`,requestId:_e(),tabId:s,...e.locale===void 0?{}:{locale:e.locale}},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 E(e,t=D()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function D(){return typeof location>`u`?void 0:location.href}function me(){if(typeof SharedWorker==`function`)return SharedWorker}function he(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function ge(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function _e(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}var ve=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??ye(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw k(e)}be(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 A(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(e,n){if(!this.supportsOutputSelection())throw new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=e;let r=++this.outputGeneration;n!==void 0&&await this.enqueueOutput(async()=>{r===this.outputGeneration&&await this.applyOutputDevice(e,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(e,n){let r=n;if(typeof r.setSinkId!=`function`)throw new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await r.setSinkId(e)}catch(e){throw j(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 O(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new t.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 ye(){return globalThis.navigator?.mediaDevices}function be(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function O(e){let n=M(e);return n===`NotFoundError`||n===`OverconstrainedError`?new t.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):n===`NotReadableError`||n===`AbortError`?new t.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):n===`NotAllowedError`||n===`SecurityError`?new t.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function k(e){let n=M(e);return n===`NotFoundError`||n===`OverconstrainedError`?new t.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):n===`NotReadableError`||n===`AbortError`?new t.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):n===`NotAllowedError`||n===`SecurityError`?new t.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function A(e){let n=M(e);return n===`NotFoundError`?new t.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):n===`NotAllowedError`||n===`SecurityError`?new t.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):n===`AbortError`||n===`NotReadableError`?new t.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function j(e){let n=M(e);return n===`NotFoundError`?new t.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):n===`NotAllowedError`||n===`SecurityError`?new t.i(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):n===`AbortError`||n===`NotReadableError`?new t.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function M(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}var N=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=xe){this.createAudioElement=e}async bind(e,n){let r=this.bindings.get(e);if(r?.stream===n)return;let i=Se(e,n),a;try{a=this.createAudioElement()}catch(n){throw P(i,this.trackOwners),new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e,cause:n})}let o=this.audioOwners.get(a);if(o!==void 0&&o!==e)throw P(i,this.trackOwners),new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});try{a.autoplay=!0,a.playsInline=!0}catch(n){throw P(i,this.trackOwners),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:n})}try{a.srcObject=n}catch(n){throw P(i,this.trackOwners),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:n})}this.acquireTracks(i),r!==void 0&&this.releaseBinding(r,r.audio!==a);let s=this.nextGeneration(e);this.audioOwners.set(a,e);let c={callId:e,audio:a,stream:n,tracks:i,generation:s};this.bindings.set(e,c),this.beginPlay(e);try{await a.play()}catch(n){if(!this.isCurrent(e,s))return;throw new t.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:n})}finally{this.finishPlay(e)}this.isCurrent(e,s)}async play(e){let n=this.bindings.get(e);if(n===void 0)throw new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});let r=n.generation;this.beginPlay(e);try{await n.audio.play()}catch(n){if(!this.isCurrent(e,r))return;throw new t.i(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:n})}finally{this.finishPlay(e)}this.isCurrent(e,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),F(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 xe(){if(typeof document>`u`)throw new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function Se(e,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 Ce(n),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:r??i})}}}function P(e,t){e.forEach(e=>{(t.get(e)??0)===0&&F(e)})}function Ce(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(F)}catch{}}function F(e){try{e.stop()}catch{}}var we=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 ve(t),this.remoteAudio=new N(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??De}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=Te(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(e){let n=this.releaseOperations.get(e);if(n!==void 0)return n;if(!this.resources.has(e))return Promise.resolve();let r=e.callId;this.remoteAudio.release(r),this.releaseErrors.delete(e),this.calls.get(r)===e&&this.calls.delete(r),e.generation+=1,e.released=!0,this.unsubscribeTrackSource(e);let i=new Set([...e.localTracks,...e.pendingTracks]),a=[...e.senders.values()].filter(e=>e.audio).map(t=>({senderResource:t,promise:this.enqueueSender(e,t,()=>R(t.sender),!0)})),o=Promise.all(a.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async n=>{let a=new Set,o=[];if(n.forEach(e=>{if(e.cause!==void 0){o.push(e.cause);let t=I(e.senderResource.sender);t?.kind===`audio`&&a.add(t);return}let t=I(e.senderResource.sender);t?.kind===`audio`&&i.add(t)}),i.forEach(e=>{a.has(e)||B(e)}),o.length>0)throw e.localTracks.clear(),e.pendingTracks.clear(),a.forEach(t=>e.localTracks.add(t)),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:o[0]});if(!e.peerClosed&&e.peerConnection.close!==void 0)try{await e.peerConnection.close(),e.peerClosed=!0}catch(n){let i=[...e.senders.values()].map(e=>I(e.sender)).find(e=>e?.kind===`audio`);throw e.localTracks.clear(),e.pendingTracks.clear(),i!=null&&e.localTracks.add(i),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:n})}e.localTracks.clear(),e.pendingTracks.clear(),e.senders.clear(),this.resources.delete(e),this.releaseUnusedSenderQueues()}).catch(t=>{throw this.releaseErrors.set(e,t),this.calls.get(r)===void 0&&this.calls.set(r,e),t}).finally(()=>{this.releaseOperations.get(e)===o&&this.releaseOperations.delete(e)});return this.releaseOperations.set(e,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(e,n,r){if(this.assertActiveCall(n),this.assertDeviceSelectionCapability(n),!this.isCurrentResource(r)||n.peerConnection!==r.peerConnection)throw this.callOperationError(n.callId);let i=this.findAudioSender(r),a=I(i.sender),o=r.generation,s=await this.deviceManager.openInputStream(e),c;try{c=s.getTracks()}catch(e){throw Ee(s),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:e})}let l;try{l=s.getAudioTracks()}catch(e){throw z(c),new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:e})}let u=l[0];if(u===void 0)throw z(c),new t.i(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:n.callId});if(!this.canCommitInputSwitch(n,r,i,a,o))throw z(c),this.callOperationError(n.callId);c.forEach(e=>r.pendingTracks.add(e)),r.pendingTracks.add(u);try{await this.enqueueSender(r,i,()=>i.sender.replaceTrack(u))}catch(e){throw r.released?this.callOperationError(n.callId):(r.released||(c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),await this.rollbackSender(r,i,a,u),z(c)),new t.i(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:n.callId,cause:e}))}if(!this.canCommitInputSwitch(n,r,i,u,o)){if(!r.released)try{await this.enqueueSender(r,i,()=>I(i.sender)===u?R(i.sender):Promise.resolve()),c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),z(c)}catch(e){throw new t.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n.callId,cause:e})}throw this.callOperationError(n.callId)}c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),r.localTracks.add(u),a!==null&&a!==u&&(r.localTracks.delete(a),B(a)),c.forEach(e=>{e!==u&&B(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(e,n){let r;try{r=e.peerConnection.getSenders()}catch(n){throw new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:n})}r.forEach(r=>{let i=I(r),a;try{a=n?.(r)??r.senderKind??r.kind}catch(n){throw new t.i(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:n})}e.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`&&e.localTracks.add(i)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(I(e.sender)?.kind===`audio`||I(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return I(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||I(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(e){if(e===void 0||e.state!==`active`)throw new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(e){return new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}callOperationError(e){return new t.i(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e})}assertNotDisposed(){if(this.disposed||this.disposing)throw new t.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function Te(e){return`peerConnection`in e}function I(e){try{return e.track}catch{return null}}function L(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function R(e){try{return e.replaceTrack(null).catch(e=>{if(!L(e))throw e})}catch(e){return L(e)?Promise.resolve():Promise.reject(e)}}function Ee(e){try{z(e.getTracks())}catch{}}function z(e){e.forEach(B)}function B(e){try{e.stop()}catch{}}function De(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}function Oe(e,n={}){let r=new Map,i=new Map,a=new Set,o=n.ownershipRequired===!0,s=!1,c=!1,l,u=()=>e(),d=new we({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||!V(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 t.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function p(e,t){if(!V(t)||typeof t.getMediaRegistration!=`function`)return;let n=t.getMediaRegistration();if(ke(n)&&r.get(e)?.peerConnection!==n.peerConnection){r.set(e,n);try{d.registerCallMedia(e,n)}catch{r.delete(e)}}}}function V(e){return typeof e==`object`&&!!e}function ke(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var Ae=1e3,je=3e4;function Me(e,t=Math.random){let n=Math.min(je,Ae*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var Ne=class{recover;isRecovered;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.isRecovered=e.isRecovered,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=Me(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}!t&&this.isCurrent(e)&&this.isRecovered!==void 0&&!this.isRecovered()&&(this.attempt+=1,t=!0),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=12e4,Fe=5e3,Ie=class i{media;options;api;suppliedSip;sip;events=new r;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=[];networkProbeTimer;stuckCallsSince;sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;sharedWorkerSelection;constructor(r){if(this.options=r,e.s(e.o(r.locale)),r.api===void 0&&r.sessionProvider===void 0)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`CCBarClient 需要 sessionProvider`});this.api=r.api===void 0?H(ze(r.sessionProvider)):H(r.api),this.suppliedSip=r.sip===void 0?void 0:Be(r.sip),this.mediaBridge=Oe(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new Ne({recover:()=>this.recoverConnection(),isRecovered:()=>this.state===`connected`,onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new n.t({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)}),this.sharedWorkerSelection=r.sharedWorker===void 0?{mode:`single-tab`,reason:`disabled`}:T({...r.sharedWorker,...r.sharedWorkerHost??{},locale:e.o(r.locale)})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=Re(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 i.checkSupport();this.support=e,this.options.platform===void 0&&(e.platform===`web`||e.platform===`mobile-web`)&&(this.detectedPlatform=e.platform),await this.awaitSharedWorkerReady(),this.assertNotDisposed(),this.initialized=!0}connect(){if(this.assertNotDisposed(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();this.api.invalidateToken?.();let e=this.lifecycleGeneration,t=this.performConnect(e).finally(()=>{this.connectOperation===t&&(this.connectOperation=void 0)});return this.connectOperation=t,t}disconnect(){if(this.assertNotDisposed(),this.disconnectOperation!==void 0)return this.disconnectOperation;if(this.state===`idle`&&this.connectOperation===void 0||this.state===`disconnected`&&this.connectOperation===void 0)return Promise.resolve();this.lifecycleGeneration+=1,this.acceptingEvents=!1;let e=this.performDisconnect().finally(()=>{this.disconnectOperation===e&&(this.disconnectOperation=void 0)});return this.disconnectOperation=e,e}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.lifecycleGeneration+=1,this.intentionalDisconnect=!0,this.acceptingEvents=!1,this.reconnect.dispose(),this.clearRefreshTimer(),this.detachNetworkListeners(),this.releaseSharedWorker(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(e){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new t.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.dial(e,r)}answer(e,n){this.assertConnected();let r=this.callManager,i=this.session;if(r===void 0||i===void 0)throw new t.i(`CALL_NOT_CONNECTED`,`call`,!1);return r.answer(e,i,n)}setActiveCall(e){this.assertConnected();let n=this.callManager;if(n===void 0)throw new t.i(`CALL_NOT_CONNECTED`,`call`,!1);return n.setActiveCall(e)}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){if(this.assertNotDisposed(),e!==`available`&&e!==`offline`&&e!==`break`)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`Unsupported agent status: ${String(e)}`});let n=this.session?.transport.wssUrl;await this.api.setAgentStatus({status:e,reason:``},n===void 0?void 0:{wssUrl:n}),this.disposed||this.events.emit(`agent.statusChanged`,{status:e})}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}off(e,t){this.events.off(e,t)}async performConnect(e){let t,r,i;try{await this.initialize(),this.assertGeneration(e);let a=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),t=await this.api.createSession({sdkVersion:n.r,platform:a===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??We(a)]}),this.ownedSessionIds.add(t.sessionId),this.assertGeneration(e),r=await this.getSip(),this.assertGeneration(e),this.session=t;let o=this.callManager??this.createCallManager(r,t,a);this.callManager===void 0&&(i=o),o.updateSession(t),this.callManager=o,this.attachSipListener(r),this.attachNetworkListeners(),await r.connect(t),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(t)}catch(n){if(await this.rollbackConnect(t,r,i),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw n;let a=W(n,`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){K(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){K(t)||(e??=t)}this.reconnect.cancel(),this.stuckCallsSince=void 0,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 b({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){K(t)||(e??=t)}let n=this.callManager;this.callManager=void 0;try{await n?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{await this.media.releaseAll()}catch(t){Ve(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await this.withBarrierTimeout(n,t),this.terminalReleaseOperations.delete(t)}catch(n){try{await this.withBarrierTimeout(this.mediaBridge.releaseCall(t),t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}withBarrierTimeout(e,n,r=Fe){return new Promise((i,a)=>{let o=setTimeout(()=>{a(new t.i(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:`media release barrier timeout`}))},Math.max(0,r));e.then(e=>{clearTimeout(o),i(e)},e=>{clearTimeout(o),a(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:W(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=W(t,`NETWORK_OFFLINE`,`network`,!0);if(this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),G(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`||n.code===`AUTH_TOKEN_REJECTED`)&&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:W(e,`SDK_INTERNAL_ERROR`,`internal`,!0)});return}if(!this.disposed)try{await this.performConnect(this.lifecycleGeneration)}catch{this.disposed||this.reconnect.start()}}}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){if(!(this.disposed||this.intentionalDisconnect)){if(this.hasNonTerminalCalls()){let e=Date.now();if(this.stuckCallsSince===void 0&&(this.stuckCallsSince=e),e-this.stuckCallsSince<Pe)return;this.stuckCallsSince=void 0,await this.callManager?.forceTerminateCalls()}else this.stuckCallsSince=void 0;if(await this.awaitMediaReleaseBarriers(),this.session===void 0){await this.performConnect(this.lifecycleGeneration);return}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-CgBtmR16.cjs"))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl,this.options.sipKeepaliveSeconds,this.options.agentTerminal,this.options.sipSessionTimers??!1),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:W(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>{this.reconnect.notifyOnline(),this.scheduleIceReassessment()},n=()=>this.reconnect.notifyOffline(),r=()=>this.scheduleIceReassessment();e.addEventListener(`online`,t),e.addEventListener(`offline`,n);let i=(typeof navigator>`u`?void 0:navigator)?.connection;i?.addEventListener(`change`,r),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n),...i===void 0?[]:[()=>i.removeEventListener(`change`,r)]]}scheduleIceReassessment(){this.networkProbeTimer!==void 0&&clearTimeout(this.networkProbeTimer),this.networkProbeTimer=setTimeout(()=>{this.networkProbeTimer=void 0,!this.disposed&&this.state===`connected`&&this.sip?.reassessIceServers?.(`network-online`)},2e3)}detachNetworkListeners(){this.networkProbeTimer!==void 0&&clearTimeout(this.networkProbeTimer),this.networkProbeTimer=void 0,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:Le(e,this.sip?.iceQualitySnapshot?.()),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(G(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 e=this.options.platform??this.detectedPlatform;if(e===void 0)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return e}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 t.i(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(e){if(this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw new t.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 t.i(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function Le(e,t){if(e===void 0)return{configured:!1,serverCount:0,stunServerCount:0,turnServerCount:0,...t?{probe:t}:{}};let n=0,r=0;return e.iceServers.forEach(e=>{let t=e.urls.map(e=>e.toLowerCase());t.some(e=>e.startsWith(`stun:`))&&(n+=1),t.some(e=>e.startsWith(`turn:`)||e.startsWith(`turns:`))&&(r+=1)}),{...t?{probe:t}:{},configured:e.iceServers.length>0,serverCount:e.iceServers.length,stunServerCount:n,turnServerCount:r}}function Re(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function H(e){if(typeof e!=`object`||!e)throw new t.i(`CONFIG_INVALID`,`configuration`,!1);return e}async function U(e){let t=e.sip?.registerTicket;if(typeof t!=`string`||t===``)return e;let n=await ce(t);return n===void 0||n===t?e:{...e,sip:{...e.sip,registerTicket:n}}}function ze(e){let r={createSession:async t=>U(await e.createSession(t)),refreshSession:async t=>U(e.refreshSession===void 0?await e.createSession({sdkVersion:n.r,platform:`web`}):await e.refreshSession(t)),deleteSession:async t=>{e.deleteSession!==void 0&&await e.deleteSession(t)},setAgentStatus:(n,r)=>e.setAgentStatus===void 0?Promise.reject(new t.i(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{cause:`当前会话来源不支持坐席状态设置(sessionProvider.setAgentStatus 未提供)`})):e.setAgentStatus(n,r)},i=e.invalidateToken;return i!==void 0&&(r.invalidateToken=()=>i()),r}function Be(e){if(typeof e!=`object`||!e)throw new t.i(`CONFIG_INVALID`,`configuration`,!1);return e}function W(e,n,r,i,a){return e instanceof t.i?new t.i(e.code,e.category,e.retryable,{requestId:e.requestId,callId:a??e.callId,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status}):new t.i(n,r,i,{callId:a,cause:e})}function G(e){return e instanceof t.i?e.status!==void 0&&e.status>=400&&e.status<500||e.serverCode===`SESSION_NOT_FOUND`||e.serverCode===`SESSION_EXPIRED`||e.serverCode===`TOKEN_INVALID`||e.serverCode===`TOKEN_EXPIRED`||e.code===`AUTH_TOKEN_UNAVAILABLE`||e.code===`AUTH_TOKEN_EXPIRED`||e.code===`AUTH_TOKEN_REJECTED`:!1}function Ve(e){return e instanceof t.i&&e.code===`SDK_ALREADY_DISPOSED`}function K(e){return e instanceof t.i&&(e.code===`SDK_ALREADY_DISPOSED`||e.code===`CALL_NOT_CONNECTED`)}var He=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],Ue=[`outbound`,`mute`,`dtmf`];function We(e){return e===`mobile-web`?Ue:He}var Ge=`/openapi/token/v1`,Ke=`/seat/account/get`,qe=`/seats/set-status`,Je=3478,Ye=600,Xe=600,Ze=180,q=60,Qe=5e3,J=2e4,Y=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],$e={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function X(e){let n=tt(e.host),r=nt(e.pathPrefix??Ge),i=`${n}${r}${Z(e.accountPath??Ke)}`,a=`${n}${r}${Z(e.statusPath??qe)}`,o={...e.aesKey?{key:e.aesKey}:{},...e.aesIv?{iv:e.aesIv}:{}},s=Math.max(0,e.refreshBufferSeconds??Ze),c=e.fetchImpl??globalThis.fetch,l,u,d=``;async function f(){if(e.getToken!==void 0)return e.getToken();if(e.tokenUrl!==void 0){let n=e.tokenMethod??`POST`,r={method:n,headers:{Accept:`application/json`,...e.tokenHeaders??{}},credentials:`include`};n===`POST`&&(r.headers={"Content-Type":`application/json`,...r.headers},r.body=JSON.stringify(e.tokenBody??{}));let i=await $(c,e.tokenUrl,r,`取 token`),a=await i.text();try{return JSON.parse(a)}catch{throw new t.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{status:i.status,cause:`取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0,120)}`})}}throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用`})}async function p(){if(l&&l.expiresAtMs-Date.now()>Qe)return l.token;let e;try{e=await f()}catch(e){throw e instanceof t.i?e:new t.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:e})}let n=it(e);if(!n.token)throw new t.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=Q(n.expires,3600);return l={token:n.token,expiresAtMs:Date.now()+r*1e3},l.token}function m(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function h(e){let t=m(e?.wssUrl);return t?(d=t,t):d||p()}async function g(e){let n=e||await p(),r=await $(c,i,{method:`POST`,headers:{Authorization:n,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`},`取坐席账号`),a=await r.text(),o;try{o=JSON.parse(a)}catch{throw new t.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:r.status,cause:`${i} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`})}let s=Number(o.code??NaN);if(!r.ok||s!==0){let e=r.status===401||s===401?`AUTH_TOKEN_REJECTED`:`LEGACY_PLATFORM_REJECTED`;throw new t.i(e,`auth`,s===50,{status:r.status,serverCode:Number.isFinite(s)?String(s):void 0,platformCode:Number.isFinite(s)?s:void 0,cause:o.message||`取坐席账号失败(HTTP ${r.status})`})}if(!o.data)throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号接口没有返回 data`});return u=o.data,u}let _=e=>S(e,o);function v(n){let r=String(e.sipWsUrl??``).trim();if(!r)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 sipWsUrl:软电话 WSS 地址由接入方提供(wss:// 或 ws:// 开头的完整地址)`});let i;try{i=new URL(r)}catch{throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`sipWsUrl 不是完整地址(需要 wss:// 或 ws:// 开头):${r}`})}if(i.protocol!==`wss:`&&i.protocol!==`ws:`)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`sipWsUrl 需要 wss:// 或 ws:// 开头:${r}`});return(e.attachTokenToWss??!0)&&n&&i.searchParams.set(`token`,n),i.toString()}function y(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)||Je}`]}]:[]}async function b(){let r=await p(),i=await g(),a=String(i.username??i.account??``).trim();if(!a)throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let o=String(i.registerPassword??i.password??``),c=o?await _(o):``;if(!c)throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let u=Q(i.expiresIn??i.expires_in,Xe),f=Math.max(0,Math.round((l.expiresAtMs-Date.now())/1e3)),m=Math.max(q,Math.min(f||u,u)-s),h=String(i.domain??``).trim()||rt(n),b=v(r);return r&&(d=r),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+m,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${h}`,registrar:h,registerTicket:c,registerExpires:Number(e.registerExpires)>0?Number(e.registerExpires):Ye,ticketExpiresIn:m},transport:{wssUrl:b,ticket:``,ticketExpiresIn:m},iceServers:y(i),policy:{maxConcurrentCalls:Number(e.maxConcurrentCalls)>0?Number(e.maxConcurrentCalls):2,incomingEnabled:e.incomingEnabled??!0,mobileIncomingEnabled:e.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...e.capabilities??Y]}}return{createSession:b,refreshSession:b,setAgentStatus:async({status:e,reason:n},r)=>{if(e!==`available`&&e!==`offline`&&e!==`break`)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`Unsupported agent status: ${String(e)}`});let i=await h(r),o=u??await g(i),s=String(o.username??o.account??``).trim();if(!s)throw new t.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let l=$e[e],d=await $(c,a,{method:`POST`,headers:{Authorization:i,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({extension:s,status:l.status,reason:n||l.reason})},`设置坐席状态`),f=await d.text(),p;try{p=JSON.parse(f)}catch{throw new t.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:d.status,cause:`${a} 返回了非 JSON 响应(HTTP ${d.status})`})}let m=Number(p.code??NaN);if(!d.ok||m!==0){let e=d.status===401||m===401?`AUTH_TOKEN_REJECTED`:`LEGACY_PLATFORM_REJECTED`;throw new t.i(e,`auth`,m===50,{status:d.status,serverCode:Number.isFinite(m)?String(m):void 0,platformCode:Number.isFinite(m)?m:void 0,cause:p.message||`设置坐席状态失败(HTTP ${d.status})`})}},invalidateToken:()=>{l=void 0,d=``},getSeatAccount:async()=>u??g()}}function et(e){return X(e)}function tt(e){let n=String(e??``).trim().replace(/\/+$/,``);if(!n)throw new t.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 host`});return/^https?:\/\//i.test(n)?n:`https://${n}`}function nt(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function Z(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function rt(e){try{return new URL(e).hostname}catch{return``}}function Q(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),q),86400))}function it(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,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),J);try{return await e(n,{...r,signal:a.signal})}catch(e){let r=a.signal.aborted;throw new t.i(r?`NETWORK_TIMEOUT`:`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{cause:r?`${i}超时(${J/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${e instanceof Error?e.message:String(e)})`})}finally{clearTimeout(o)}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return o}});
|