@16x/webphone-sdk 3.1.8 → 3.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-39dch6xL.cjs"),t=require("../CCBarClient-BqMNSIu-.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.legacyVersion=a;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../SharedWorkerProtocol-39dch6xL.cjs"),t=require("../CCBarClient-B6WqgloY.cjs");require("../createJsSipFactory-Dr8HbLl-.cjs");var n=class extends Error{code=`LEGACY_METHOD_DEPRECATED`;constructor(e,t){super(`${e} 已废弃:${t}`),this.name=`DeprecatedError`}},r=class{client;warnedMethods=new Set;unsubscribeIncoming;currentCall;constructor(e){this.client=new t.t(e),this.unsubscribeIncoming=this.client.on(`call.incoming`,({callId:e})=>{this.currentCall=this.client.getCalls().find(t=>t.id===e)})}getToken(...e){return this.warn(`getToken`,`请改用 client.connect()`),this.client.connect()}getAccount(...e){return this.warn(`getAccount`,`请改用 client.connect()`),this.client.connect()}login(...e){return this.warn(`login`,`请改用 client.connect()`),this.client.connect()}async call(e,...t){this.warn(`call`,`请改用 client.dial({ destination })`);let n=await this.client.dial({destination:String(e)});return this.currentCall=n,n}async insideCall(e,...t){this.warn(`insideCall`,`请改用 client.dial({ destination, type: 'extension' })`);let n=await this.client.dial({destination:String(e),type:`extension`});return this.currentCall=n,n}answer(...e){this.warn(`answer`,`请改用 call.answer()`);let t=this.requireCurrentCall();return this.client.answer(t.id)}async hangup(...e){this.warn(`hangup`,`请改用 call.hangup()`);let t=this.requireCurrentCall();try{await t.hangup()}finally{this.currentCall===t&&(this.currentCall=void 0)}}holdCall(...e){return this.warn(`holdCall`,`请改用 call.hold()`),this.requireCurrentCall().hold()}unholdCall(...e){return this.warn(`unholdCall`,`请改用 call.resume()`),this.requireCurrentCall().resume()}transSo(e,...t){return this.warn(`transSo`,`请改用 call.transfer({ target, type: 'blind' })`),this.requireCurrentCall().transfer({target:String(e),type:`blind`})}async signOut(...e){this.warn(`signOut`,`请改用 client.disconnect() 和 client.dispose()`);let t;try{await this.client.disconnect()}catch(e){t=e}try{await this.client.dispose()}catch(e){t??=e}if(this.unsubscribeIncoming(),this.currentCall=void 0,t!==void 0)throw t}setId(...e){return this.warn(`setId`,`请改用 client.setAgentStatus('available')`),this.client.setAgentStatus(`available`)}setBu(...e){throw this.warn(`setBu`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`),new n(`setBu()`,`busy由通话状态或服务端状态策略控制,浏览器不得伪造`)}setRe(...e){return this.warn(`setRe`,`请改用 client.setAgentStatus('break')`),this.client.setAgentStatus(`break`)}requireCurrentCall(){let t=this.client.getActiveCall();if(t!==void 0&&(this.currentCall=t),this.currentCall===void 0)throw new e.i(`CALL_NOT_CONNECTED`,`call`,!1);return this.currentCall}warn(e,t){i()&&!this.warnedMethods.has(e)&&(this.warnedMethods.add(e),console.warn(`[CCBarSDK] ${e}() 已废弃。${t}`))}};function i(){return!1}var a=`q7X4p6MvK1z8Lb3A`,o=`W9e2T4mN0aQ7Ru6C`;async function s(t,n={}){let r=String(t??``).replace(/\s+/g,``);if(!r)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`解密的密文为空:坐席账号里没有 password/registerPassword`});let i=n.subtle??globalThis.crypto?.subtle;if(i===void 0)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行`});let s;try{let e=atob(r);s=new Uint8Array(new ArrayBuffer(e.length));for(let t=0;t<e.length;t+=1)s[t]=e.charCodeAt(t)}catch{throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义`})}let l=await i.importKey(`raw`,c(n.key??a),`AES-CBC`,!1,[`decrypt`]);try{let e=await i.decrypt({name:`AES-CBC`,iv:c(n.iv??o)},l,s);return new TextDecoder(`utf-8`).decode(e).trim()}catch(t){throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`SIP 密码解密失败(检查 key/iv 与该环境是否一致):${t instanceof Error?t.message:String(t)}`})}}function c(e){let t=new TextEncoder().encode(e),n=new Uint8Array(new ArrayBuffer(t.byteLength));return n.set(t),n}var l=`/openapi/token/v1`,u=`/seat/account/get`,d=`/seats/set-status`,f=`/api/fs/sip-ws`,p=7443,m=3478,h=600,g=600,_=180,v=60,y=5e3,b=2e4,x=[`outbound`,`inbound`,`mute`,`dtmf`,`hold`,`blind_transfer`],S={available:{status:`Available`,reason:`空闲`},break:{status:`On Break`,reason:`休息`},offline:{status:`Logged Out`,reason:``}};function C(t){let n=w(t.host),r=T(t.pathPrefix??l),i=`${n}${r}${E(t.accountPath??u)}`,a=`${n}${r}${E(t.statusPath??d)}`,o=E(t.sipWsPath??f),c={...t.aesKey?{key:t.aesKey}:{},...t.aesIv?{iv:t.aesIv}:{}},b=Math.max(0,t.refreshBufferSeconds??_),C=t.fetchImpl??globalThis.fetch,j,M,N=``;async function P(){if(t.getToken!==void 0)return t.getToken();if(t.tokenUrl!==void 0){let n=t.tokenMethod??`POST`,r={method:n,headers:{Accept:`application/json`,...t.tokenHeaders??{}},credentials:`include`};n===`POST`&&(r.headers={"Content-Type":`application/json`,...r.headers},r.body=JSON.stringify(t.tokenBody??{}));let i=await A(C,t.tokenUrl,r,`取 token`),a=await i.text();try{return JSON.parse(a)}catch{throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{status:i.status,cause:`取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0,120)}`})}}throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用`})}async function F(){if(j&&j.expiresAtMs-Date.now()>y)return j.token;let t;try{t=await P()}catch(t){throw t instanceof e.i?t:new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:t})}let n=k(t);if(!n.token)throw new e.i(`AUTH_TOKEN_UNAVAILABLE`,`auth`,!0,{cause:`取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)`});let r=O(n.expires,3600);return j={token:n.token,expiresAtMs:Date.now()+r*1e3},j.token}function I(e){if(!e)return``;try{return String(new URL(e).searchParams.get(`token`)??``).trim()}catch{return``}}async function L(e){let t=I(e?.wssUrl);return t?(N=t,t):N||F()}async function R(t){let n=t||await F(),r=await A(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 e.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)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,s===50,{status:r.status,serverCode:Number.isFinite(s)?String(s):void 0,cause:o.message||`取坐席账号失败(HTTP ${r.status})`});if(!o.data)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号接口没有返回 data`});return M=o.data,M}let z=e=>s(e,c);function B(r,i){let a=Number(r.wssPort)||p,s=String(r.domain??``).trim(),c=String(t.sipWsUrl??``).trim(),l;if(c)l=new URL(c,n),l.protocol===`http:`&&(l.protocol=`ws:`),l.protocol===`https:`&&(l.protocol=`wss:`);else{if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定`});let t=a===443?``:`:${a}`;l=new URL(`wss://${s}${t}${o}`)}return(t.attachTokenToWss??!0)&&i&&l.searchParams.set(`token`,i),l.toString()}function V(e){let t=(Array.isArray(e.iceServers)?e.iceServers:[]).map(e=>{let t=(Array.isArray(e?.urls)?e.urls:typeof e?.urls==`string`?[e.urls]:[]).map(e=>String(e??``).trim()).filter(Boolean);if(t.length!==0)return{urls:t,...e?.username?{username:String(e.username)}:{},...e?.credential?{credential:String(e.credential)}:{}}}).filter(e=>e!==void 0);if(t.length>0)return t;let n=String(e.turnIp??``).trim();return n?[{urls:[`stun:${n}:${Number(e.turnPort)||m}`]}]:[]}async function H(){let r=await F(),i=await R(),a=String(i.username??i.account??``).trim();if(!a)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let o=String(i.registerPassword??i.password??``),s=o?await z(o):``;if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 password/registerPassword,或解密后为空`});let c=O(i.expiresIn??i.expires_in,g),l=Math.max(0,Math.round((j.expiresAtMs-Date.now())/1e3)),u=Math.max(v,Math.min(l||c,c)-b),d=String(i.domain??``).trim()||D(n),f=B(i,r);return r&&(N=r),{sessionId:`legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,expiresAt:Math.floor(Date.now()/1e3)+u,agent:{id:a,externalUserId:a,displayName:a,extension:a,status:`Available`},sip:{uri:`sip:${a}@${d}`,registrar:d,registerTicket:s,registerExpires:Number(t.registerExpires)>0?Number(t.registerExpires):h,ticketExpiresIn:u},transport:{wssUrl:f,ticket:``,ticketExpiresIn:u},iceServers:V(i),policy:{maxConcurrentCalls:Number(t.maxConcurrentCalls)>0?Number(t.maxConcurrentCalls):2,incomingEnabled:t.incomingEnabled??!0,mobileIncomingEnabled:t.mobileIncomingEnabled??!0,backgroundCallingSupported:!1},capabilities:[...t.capabilities??x]}}return{createSession:H,refreshSession:H,setAgentStatus:async({status:t,reason:n},r)=>{let i=await L(r),o=M??await R(i),s=String(o.username??o.account??``).trim();if(!s)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`坐席账号里没有 username`});let c=S[t],l=await A(C,a,{method:`POST`,headers:{Authorization:i,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({extension:s,status:c.status,reason:n||c.reason})},`设置坐席状态`),u=await l.text(),d;try{d=JSON.parse(u)}catch{throw new e.i(`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{status:l.status,cause:`${a} 返回了非 JSON 响应(HTTP ${l.status})`})}let f=Number(d.code??NaN);if(!l.ok||f!==0)throw new e.i(`LEGACY_PLATFORM_REJECTED`,`auth`,f===50,{status:l.status,serverCode:Number.isFinite(f)?String(f):void 0,cause:d.message||`设置坐席状态失败(HTTP ${l.status})`})},invalidateToken:()=>{j=void 0,N=``},getSeatAccount:async()=>M??R()}}function w(t){let n=String(t??``).trim().replace(/\/+$/,``);if(!n)throw new e.i(`CONFIG_INVALID`,`configuration`,!1,{cause:`createLegacySessionProvider 需要 host`});return/^https?:\/\//i.test(n)?n:`https://${n}`}function T(e){let t=String(e??``).trim();return!t||t===`/`?``:`/${t.replace(/^\/+|\/+$/g,``)}`}function E(e){let t=String(e??``).trim();return t.startsWith(`/`)?t:`/${t}`}function D(e){try{return new URL(e).hostname}catch{return``}}function O(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:(n>86400&&(n/=1e3),Math.min(Math.max(Math.floor(n),v),86400))}function k(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 A(t,n,r,i){let a=new AbortController,o=setTimeout(()=>a.abort(),b);try{return await t(n,{...r,signal:a.signal})}catch(t){let r=a.signal.aborted;throw new e.i(r?`NETWORK_TIMEOUT`:`LEGACY_PLATFORM_UNREACHABLE`,`network`,!0,{cause:r?`${i}超时(${b/1e3} 秒):POST ${n}`:`${i}失败:无法请求 ${n}(${t instanceof Error?t.message:String(t)})`})}finally{clearTimeout(o)}}var j=`0.1.0`;typeof window<`u`&&(window.CCBarSDK=r),exports.CCBarSDK=r,exports.DeprecatedError=n,exports.createLegacySessionProvider=C,exports.decryptSipPassword=s,exports.legacyVersion=j;
@@ -1,5 +1,7 @@
1
1
  import { CCBarSDK } from './CCBarSDK.js';
2
2
  export { CCBarSDK, DeprecatedError } from './CCBarSDK.js';
3
+ export { decryptSipPassword, type DecryptSipPasswordOptions } from './legacyAes.js';
4
+ export { createLegacySessionProvider, type LegacyPlatformSessionProviderOptions, type LegacySeatAccount, type LegacyTokenResult, } from './legacySessionProvider.js';
3
5
  export declare const legacyVersion = "0.1.0";
4
6
  declare global {
5
7
  interface Window {
@@ -1,5 +1,5 @@
1
1
  import { i as e } from "../SharedWorkerProtocol-DKVQ5-po.js";
2
- import { t } from "../CCBarClient-DdxjJrdT.js";
2
+ import { t } from "../CCBarClient-CfHT0tl2.js";
3
3
  //#region src/legacy/CCBarSDK.ts
4
4
  var n = class extends Error {
5
5
  code = "LEGACY_METHOD_DEPRECATED";
@@ -101,8 +101,305 @@ function i() {
101
101
  return !1;
102
102
  }
103
103
  //#endregion
104
+ //#region src/legacy/legacyAes.ts
105
+ var a = "q7X4p6MvK1z8Lb3A", o = "W9e2T4mN0aQ7Ru6C";
106
+ async function s(t, n = {}) {
107
+ let r = String(t ?? "").replace(/\s+/g, "");
108
+ if (!r) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "解密的密文为空:坐席账号里没有 password/registerPassword" });
109
+ let i = n.subtle ?? globalThis.crypto?.subtle;
110
+ if (i === void 0) throw new e("CONFIG_INVALID", "configuration", !1, { cause: "需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行" });
111
+ let s;
112
+ try {
113
+ let e = atob(r);
114
+ s = new Uint8Array(new ArrayBuffer(e.length));
115
+ for (let t = 0; t < e.length; t += 1) s[t] = e.charCodeAt(t);
116
+ } catch {
117
+ throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义" });
118
+ }
119
+ let l = await i.importKey("raw", c(n.key ?? a), "AES-CBC", !1, ["decrypt"]);
120
+ try {
121
+ let e = await i.decrypt({
122
+ name: "AES-CBC",
123
+ iv: c(n.iv ?? o)
124
+ }, l, s);
125
+ return new TextDecoder("utf-8").decode(e).trim();
126
+ } catch (t) {
127
+ throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: `SIP 密码解密失败(检查 key/iv 与该环境是否一致):${t instanceof Error ? t.message : String(t)}` });
128
+ }
129
+ }
130
+ function c(e) {
131
+ let t = new TextEncoder().encode(e), n = new Uint8Array(new ArrayBuffer(t.byteLength));
132
+ return n.set(t), n;
133
+ }
134
+ //#endregion
135
+ //#region src/legacy/legacySessionProvider.ts
136
+ var l = "/openapi/token/v1", u = "/seat/account/get", d = "/seats/set-status", f = "/api/fs/sip-ws", p = 7443, m = 3478, h = 600, g = 600, _ = 180, v = 60, y = 5e3, b = 2e4, x = [
137
+ "outbound",
138
+ "inbound",
139
+ "mute",
140
+ "dtmf",
141
+ "hold",
142
+ "blind_transfer"
143
+ ], S = {
144
+ available: {
145
+ status: "Available",
146
+ reason: "空闲"
147
+ },
148
+ break: {
149
+ status: "On Break",
150
+ reason: "休息"
151
+ },
152
+ offline: {
153
+ status: "Logged Out",
154
+ reason: ""
155
+ }
156
+ };
157
+ function C(t) {
158
+ let n = w(t.host), r = T(t.pathPrefix ?? l), i = `${n}${r}${E(t.accountPath ?? u)}`, a = `${n}${r}${E(t.statusPath ?? d)}`, o = E(t.sipWsPath ?? f), c = {
159
+ ...t.aesKey ? { key: t.aesKey } : {},
160
+ ...t.aesIv ? { iv: t.aesIv } : {}
161
+ }, b = Math.max(0, t.refreshBufferSeconds ?? _), C = t.fetchImpl ?? globalThis.fetch, j, M, N = "";
162
+ async function P() {
163
+ if (t.getToken !== void 0) return t.getToken();
164
+ if (t.tokenUrl !== void 0) {
165
+ let n = t.tokenMethod ?? "POST", r = {
166
+ method: n,
167
+ headers: {
168
+ Accept: "application/json",
169
+ ...t.tokenHeaders ?? {}
170
+ },
171
+ credentials: "include"
172
+ };
173
+ n === "POST" && (r.headers = {
174
+ "Content-Type": "application/json",
175
+ ...r.headers
176
+ }, r.body = JSON.stringify(t.tokenBody ?? {}));
177
+ let i = await A(C, t.tokenUrl, r, "取 token"), a = await i.text();
178
+ try {
179
+ return JSON.parse(a);
180
+ } catch {
181
+ throw new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, {
182
+ status: i.status,
183
+ cause: `取 token 的接口返回了非 JSON 响应(HTTP ${i.status}):${a.trim().slice(0, 120)}`
184
+ });
185
+ }
186
+ }
187
+ throw new e("CONFIG_INVALID", "configuration", !1, { cause: "createLegacySessionProvider 需要 getToken 或 tokenUrl;坐席状态也可以直接用会话软电话地址里的 token(setAgentStatus 的 context.wssUrl),但这次调用没有会话可用" });
188
+ }
189
+ async function F() {
190
+ if (j && j.expiresAtMs - Date.now() > y) return j.token;
191
+ let t;
192
+ try {
193
+ t = await P();
194
+ } catch (t) {
195
+ throw t instanceof e ? t : new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, { cause: t });
196
+ }
197
+ let n = k(t);
198
+ if (!n.token) throw new e("AUTH_TOKEN_UNAVAILABLE", "auth", !0, { cause: "取 token 的返回里没有 token(支持 {token}、{accessToken}、{data:{token}} 或裸字符串)" });
199
+ let r = O(n.expires, 3600);
200
+ return j = {
201
+ token: n.token,
202
+ expiresAtMs: Date.now() + r * 1e3
203
+ }, j.token;
204
+ }
205
+ function I(e) {
206
+ if (!e) return "";
207
+ try {
208
+ return String(new URL(e).searchParams.get("token") ?? "").trim();
209
+ } catch {
210
+ return "";
211
+ }
212
+ }
213
+ async function L(e) {
214
+ let t = I(e?.wssUrl);
215
+ return t ? (N = t, t) : N || F();
216
+ }
217
+ async function R(t) {
218
+ let n = t || await F(), r = await A(C, i, {
219
+ method: "POST",
220
+ headers: {
221
+ Authorization: n,
222
+ "Content-Type": "application/json",
223
+ Accept: "application/json"
224
+ },
225
+ body: "{}"
226
+ }, "取坐席账号"), a = await r.text(), o;
227
+ try {
228
+ o = JSON.parse(a);
229
+ } catch {
230
+ throw new e("LEGACY_PLATFORM_UNREACHABLE", "network", !0, {
231
+ status: r.status,
232
+ cause: `${i} 返回了非 JSON 响应(HTTP ${r.status});请确认 host 填的是接口网关(不是文档站)`
233
+ });
234
+ }
235
+ let s = Number(o.code ?? NaN);
236
+ if (!r.ok || s !== 0) throw new e("LEGACY_PLATFORM_REJECTED", "auth", s === 50, {
237
+ status: r.status,
238
+ serverCode: Number.isFinite(s) ? String(s) : void 0,
239
+ cause: o.message || `取坐席账号失败(HTTP ${r.status})`
240
+ });
241
+ if (!o.data) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号接口没有返回 data" });
242
+ return M = o.data, M;
243
+ }
244
+ let z = (e) => s(e, c);
245
+ function B(r, i) {
246
+ let a = Number(r.wssPort) || p, s = String(r.domain ?? "").trim(), c = String(t.sipWsUrl ?? "").trim(), l;
247
+ if (c) l = new URL(c, n), l.protocol === "http:" && (l.protocol = "ws:"), l.protocol === "https:" && (l.protocol = "wss:");
248
+ else {
249
+ if (!s) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 domain,无法拼软电话地址;可用 sipWsUrl 显式指定" });
250
+ let t = a === 443 ? "" : `:${a}`;
251
+ l = new URL(`wss://${s}${t}${o}`);
252
+ }
253
+ return (t.attachTokenToWss ?? !0) && i && l.searchParams.set("token", i), l.toString();
254
+ }
255
+ function V(e) {
256
+ let t = (Array.isArray(e.iceServers) ? e.iceServers : []).map((e) => {
257
+ let t = (Array.isArray(e?.urls) ? e.urls : typeof e?.urls == "string" ? [e.urls] : []).map((e) => String(e ?? "").trim()).filter(Boolean);
258
+ if (t.length !== 0) return {
259
+ urls: t,
260
+ ...e?.username ? { username: String(e.username) } : {},
261
+ ...e?.credential ? { credential: String(e.credential) } : {}
262
+ };
263
+ }).filter((e) => e !== void 0);
264
+ if (t.length > 0) return t;
265
+ let n = String(e.turnIp ?? "").trim();
266
+ return n ? [{ urls: [`stun:${n}:${Number(e.turnPort) || m}`] }] : [];
267
+ }
268
+ async function H() {
269
+ let r = await F(), i = await R(), a = String(i.username ?? i.account ?? "").trim();
270
+ if (!a) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 username" });
271
+ let o = String(i.registerPassword ?? i.password ?? ""), s = o ? await z(o) : "";
272
+ if (!s) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 password/registerPassword,或解密后为空" });
273
+ let c = O(i.expiresIn ?? i.expires_in, g), l = Math.max(0, Math.round((j.expiresAtMs - Date.now()) / 1e3)), u = Math.max(v, Math.min(l || c, c) - b), d = String(i.domain ?? "").trim() || D(n), f = B(i, r);
274
+ return r && (N = r), {
275
+ sessionId: `legacy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
276
+ expiresAt: Math.floor(Date.now() / 1e3) + u,
277
+ agent: {
278
+ id: a,
279
+ externalUserId: a,
280
+ displayName: a,
281
+ extension: a,
282
+ status: "Available"
283
+ },
284
+ sip: {
285
+ uri: `sip:${a}@${d}`,
286
+ registrar: d,
287
+ registerTicket: s,
288
+ registerExpires: Number(t.registerExpires) > 0 ? Number(t.registerExpires) : h,
289
+ ticketExpiresIn: u
290
+ },
291
+ transport: {
292
+ wssUrl: f,
293
+ ticket: "",
294
+ ticketExpiresIn: u
295
+ },
296
+ iceServers: V(i),
297
+ policy: {
298
+ maxConcurrentCalls: Number(t.maxConcurrentCalls) > 0 ? Number(t.maxConcurrentCalls) : 2,
299
+ incomingEnabled: t.incomingEnabled ?? !0,
300
+ mobileIncomingEnabled: t.mobileIncomingEnabled ?? !0,
301
+ backgroundCallingSupported: !1
302
+ },
303
+ capabilities: [...t.capabilities ?? x]
304
+ };
305
+ }
306
+ return {
307
+ createSession: H,
308
+ refreshSession: H,
309
+ setAgentStatus: async ({ status: t, reason: n }, r) => {
310
+ let i = await L(r), o = M ?? await R(i), s = String(o.username ?? o.account ?? "").trim();
311
+ if (!s) throw new e("LEGACY_PLATFORM_REJECTED", "auth", !1, { cause: "坐席账号里没有 username" });
312
+ let c = S[t], l = await A(C, a, {
313
+ method: "POST",
314
+ headers: {
315
+ Authorization: i,
316
+ "Content-Type": "application/json",
317
+ Accept: "application/json"
318
+ },
319
+ body: JSON.stringify({
320
+ extension: s,
321
+ status: c.status,
322
+ reason: n || c.reason
323
+ })
324
+ }, "设置坐席状态"), u = await l.text(), d;
325
+ try {
326
+ d = JSON.parse(u);
327
+ } catch {
328
+ throw new e("LEGACY_PLATFORM_UNREACHABLE", "network", !0, {
329
+ status: l.status,
330
+ cause: `${a} 返回了非 JSON 响应(HTTP ${l.status})`
331
+ });
332
+ }
333
+ let f = Number(d.code ?? NaN);
334
+ if (!l.ok || f !== 0) throw new e("LEGACY_PLATFORM_REJECTED", "auth", f === 50, {
335
+ status: l.status,
336
+ serverCode: Number.isFinite(f) ? String(f) : void 0,
337
+ cause: d.message || `设置坐席状态失败(HTTP ${l.status})`
338
+ });
339
+ },
340
+ invalidateToken: () => {
341
+ j = void 0, N = "";
342
+ },
343
+ getSeatAccount: async () => M ?? R()
344
+ };
345
+ }
346
+ function w(t) {
347
+ let n = String(t ?? "").trim().replace(/\/+$/, "");
348
+ if (!n) throw new e("CONFIG_INVALID", "configuration", !1, { cause: "createLegacySessionProvider 需要 host" });
349
+ return /^https?:\/\//i.test(n) ? n : `https://${n}`;
350
+ }
351
+ function T(e) {
352
+ let t = String(e ?? "").trim();
353
+ return !t || t === "/" ? "" : `/${t.replace(/^\/+|\/+$/g, "")}`;
354
+ }
355
+ function E(e) {
356
+ let t = String(e ?? "").trim();
357
+ return t.startsWith("/") ? t : `/${t}`;
358
+ }
359
+ function D(e) {
360
+ try {
361
+ return new URL(e).hostname;
362
+ } catch {
363
+ return "";
364
+ }
365
+ }
366
+ function O(e, t) {
367
+ let n = Number(e);
368
+ return !Number.isFinite(n) || n <= 0 ? t : (n > 86400 && (n /= 1e3), Math.min(Math.max(Math.floor(n), v), 86400));
369
+ }
370
+ function k(e) {
371
+ if (typeof e == "string") return { token: e.trim() };
372
+ let t = e ?? {}, n = typeof t.data == "object" && t.data !== null ? t.data : void 0;
373
+ for (let e of [t, n]) {
374
+ if (e === void 0) continue;
375
+ let t = e.token ?? e.accessToken;
376
+ if (typeof t == "string" && t.trim()) {
377
+ let n = Number(e.expires ?? e.expiresIn ?? e.expires_at);
378
+ return {
379
+ token: t.trim(),
380
+ ...Number.isFinite(n) && n > 0 ? { expires: n } : {}
381
+ };
382
+ }
383
+ }
384
+ return { token: "" };
385
+ }
386
+ async function A(t, n, r, i) {
387
+ let a = new AbortController(), o = setTimeout(() => a.abort(), b);
388
+ try {
389
+ return await t(n, {
390
+ ...r,
391
+ signal: a.signal
392
+ });
393
+ } catch (t) {
394
+ let r = a.signal.aborted;
395
+ throw new e(r ? "NETWORK_TIMEOUT" : "LEGACY_PLATFORM_UNREACHABLE", "network", !0, { cause: r ? `${i}超时(${b / 1e3} 秒):POST ${n}` : `${i}失败:无法请求 ${n}(${t instanceof Error ? t.message : String(t)})` });
396
+ } finally {
397
+ clearTimeout(o);
398
+ }
399
+ }
400
+ //#endregion
104
401
  //#region src/legacy/index.ts
105
- var a = "0.1.0";
402
+ var j = "0.1.0";
106
403
  typeof window < "u" && (window.CCBarSDK = r);
107
404
  //#endregion
108
- export { r as CCBarSDK, n as DeprecatedError, a as legacyVersion };
405
+ export { r as CCBarSDK, n as DeprecatedError, C as createLegacySessionProvider, s as decryptSipPassword, j as legacyVersion };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 老平台坐席密码的解密:`seat/account/get` 返回的 `password`(或 `registerPassword`)
3
+ * 是 **AES-128-CBC / Pkcs7 的密文,Base64 编码**,需要解密才有明文 SIP 密码。
4
+ *
5
+ * key/iv 各 16 字节,老平台是固定值(旧版 `ccbar.js` 里同样是硬编码),可用 options 覆盖。
6
+ * 在浏览器与 Node 里都能用(走 WebCrypto,无需额外依赖;需要安全上下文或 Node 18+)。
7
+ */
8
+ export interface DecryptSipPasswordOptions {
9
+ /** AES key(16 字节,UTF-8),默认用老平台内置值 */
10
+ key?: string;
11
+ /** AES iv(16 字节,UTF-8),默认用老平台内置值 */
12
+ iv?: string;
13
+ /** 解密实现所用的 WebCrypto(测试可注入),默认全局 crypto.subtle */
14
+ subtle?: SubtleCrypto;
15
+ }
16
+ /**
17
+ * 解出 SIP 密码明文。
18
+ *
19
+ * ```ts
20
+ * import { decryptSipPassword } from '@16x/webphone-sdk/legacy';
21
+ *
22
+ * const res = await fetch(`${host}/openapi/token/v1/seat/account/get`, { method: 'POST', headers: { Authorization: token }, body: '{}' });
23
+ * const { data } = await res.json();
24
+ * const password = await decryptSipPassword(data.password); // 明文 SIP 密码
25
+ * ```
26
+ *
27
+ * 失败时抛 `CCBarError`:可读原因在 `error.cause` 上(密文为空 / 不是合法 Base64 / 解密失败)。
28
+ */
29
+ export declare function decryptSipPassword(cipherText: string, options?: DecryptSipPasswordOptions): Promise<string>;
@@ -0,0 +1,79 @@
1
+ import { SessionProvider } from '../core/CCBarClient.js';
2
+ /** 换票结果:`{ token, expires }`、`{ accessToken, expires }`、`{ data: {...} }` 或裸字符串都能接 */
3
+ export type LegacyTokenResult = string | {
4
+ token?: string;
5
+ accessToken?: string;
6
+ expires?: number;
7
+ data?: unknown;
8
+ };
9
+ export interface LegacySeatAccount {
10
+ username?: string;
11
+ account?: string;
12
+ customerPrefix?: string;
13
+ extension?: string;
14
+ password?: string;
15
+ registerPassword?: string;
16
+ expiresIn?: number;
17
+ expires_in?: number;
18
+ domain?: string;
19
+ wsPort?: number;
20
+ wssPort?: number;
21
+ turnIp?: string;
22
+ turnPort?: number;
23
+ iceServers?: Array<{
24
+ urls?: string[] | string;
25
+ username?: string;
26
+ credential?: string;
27
+ }>;
28
+ [key: string]: unknown;
29
+ }
30
+ export interface LegacyPlatformSessionProviderOptions {
31
+ /** 平台网关地址,例如 `https://vxapi.yundianlab.com`(不含路径前缀);必填 */
32
+ host: string;
33
+ /** 取 token 的两种写法二选一:函数(接入方自己调) */
34
+ getToken?: () => LegacyTokenResult | Promise<LegacyTokenResult>;
35
+ /** 取 token 的两种写法二选一:地址(SDK 去 POST 这个地址,通常是接入方自己的接口) */
36
+ tokenUrl?: string;
37
+ /** tokenUrl 的请求方法,默认 POST */
38
+ tokenMethod?: 'GET' | 'POST';
39
+ /** tokenUrl 的请求体(POST 时 JSON 发送),默认 {} */
40
+ tokenBody?: Record<string, unknown>;
41
+ /** tokenUrl 的额外请求头 */
42
+ tokenHeaders?: Record<string, string>;
43
+ /** 路径前缀,默认 `/openapi/token/v1` */
44
+ pathPrefix?: string;
45
+ /** 坐席账号路径(相对 pathPrefix),默认 `/seat/account/get` */
46
+ accountPath?: string;
47
+ /** 坐席状态路径(相对 pathPrefix),默认 `/seats/set-status` */
48
+ statusPath?: string;
49
+ /** 软电话路径,默认 `/api/fs/sip-ws` */
50
+ sipWsPath?: string;
51
+ /** 显式指定 WSS 地址(覆盖按 domain/wssPort 拼装),可以是相对路径 */
52
+ sipWsUrl?: string;
53
+ /** 是否把 token 挂到 WSS 的 `?token=`,默认 true(旧页面那套不挂时可设 false) */
54
+ attachTokenToWss?: boolean;
55
+ /** AES key / iv(16 字节,UTF-8);默认用平台内置值 */
56
+ aesKey?: string;
57
+ aesIv?: string;
58
+ /** REGISTER 有效期(秒),默认 600 */
59
+ registerExpires?: number;
60
+ /** 会话 TTL 的提前换票缓冲(秒),默认 180 */
61
+ refreshBufferSeconds?: number;
62
+ /** 并发上限,默认 2(移动端形态下 SDK 也会压到 1) */
63
+ maxConcurrentCalls?: number;
64
+ /** 是否允许接来电(总闸),默认 true */
65
+ incomingEnabled?: boolean;
66
+ /** 移动端是否允许接来电,默认 true(桌面形态不看这一项) */
67
+ mobileIncomingEnabled?: boolean;
68
+ /** 能力白名单,默认老平台六项 */
69
+ capabilities?: string[];
70
+ /** 请求实现(测试/代理场景可替换),默认全局 fetch */
71
+ fetchImpl?: typeof fetch;
72
+ }
73
+ /**
74
+ * 造一个会话来源:`new CCBarClient({ sessionProvider: createLegacySessionProvider({...}) })`。
75
+ * `refreshSession` 与 `createSession` 等价——整条链路重跑一遍,等价于换一次 SIP 密码。
76
+ */
77
+ export declare function createLegacySessionProvider(options: LegacyPlatformSessionProviderOptions): SessionProvider & {
78
+ getSeatAccount(): Promise<LegacySeatAccount>;
79
+ };
package/dist/types.d.ts CHANGED
@@ -58,7 +58,11 @@ export interface MediaManager {
58
58
  releaseAll(): Promise<void>;
59
59
  }
60
60
  export type CCBarErrorCategory = 'auth' | 'configuration' | 'network' | 'registration' | 'media' | 'call' | 'capability' | 'internal';
61
- export type CCBarErrorCode = 'AUTH_TOKEN_UNAVAILABLE' | 'AUTH_TOKEN_EXPIRED' | 'AUTH_PERMISSION_DENIED' | 'CONFIG_INVALID' | 'CONFIG_ORIGIN_NOT_ALLOWED' | 'NETWORK_OFFLINE' | 'NETWORK_TIMEOUT' | 'SIP_WS_UNAVAILABLE' | 'REGISTRATION_FAILED' | 'REGISTRATION_REJECTED' | 'MEDIA_PERMISSION_DENIED' | 'MEDIA_DEVICE_NOT_FOUND' | 'MEDIA_DEVICE_IN_USE' | 'MEDIA_PLAYBACK_BLOCKED' | 'CALL_INVALID_DESTINATION' | 'CALL_INVALID_USERDATA' | 'CALL_ALREADY_EXISTS' | 'CALL_REJECTED' | 'CALL_BUSY' | 'CALL_NOT_CONNECTED' | 'CALL_OPERATION_NOT_ALLOWED' | 'CAPABILITY_NOT_SUPPORTED' | 'H5_BACKGROUND_NOT_SUPPORTED' | 'SDK_ALREADY_DISPOSED' | 'SDK_INTERNAL_ERROR';
61
+ export type CCBarErrorCode = 'AUTH_TOKEN_UNAVAILABLE' | 'AUTH_TOKEN_EXPIRED' | 'AUTH_PERMISSION_DENIED' | 'CONFIG_INVALID' | 'CONFIG_ORIGIN_NOT_ALLOWED' | 'NETWORK_OFFLINE' | 'NETWORK_TIMEOUT' | 'SIP_WS_UNAVAILABLE' | 'REGISTRATION_FAILED' | 'REGISTRATION_REJECTED' | 'MEDIA_PERMISSION_DENIED' | 'MEDIA_DEVICE_NOT_FOUND' | 'MEDIA_DEVICE_IN_USE' | 'MEDIA_PLAYBACK_BLOCKED' | 'CALL_INVALID_DESTINATION' | 'CALL_INVALID_USERDATA' | 'CALL_ALREADY_EXISTS' | 'CALL_REJECTED' | 'CALL_BUSY' | 'CALL_NOT_CONNECTED' | 'CALL_OPERATION_NOT_ALLOWED' | 'CAPABILITY_NOT_SUPPORTED' | 'H5_BACKGROUND_NOT_SUPPORTED' | 'SDK_ALREADY_DISPOSED' | 'SDK_INTERNAL_ERROR'
62
+ /** 老平台接口(seat/account/get、seats/set-status)不可达:网络失败、超时或返回非 JSON */
63
+ | 'LEGACY_PLATFORM_UNREACHABLE'
64
+ /** 老平台接口返回了业务错误(code != 0)或缺少必需字段;平台的 code 在 error.serverCode 上 */
65
+ | 'LEGACY_PLATFORM_REJECTED';
62
66
  export interface ConnectionStateEvent {
63
67
  state: 'offline' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
64
68
  }
package/dist/ui/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require("../createJsSipFactory-Dr8HbLl-.cjs");var e={call:`Call`,numberLabel:`Number`,statusReady:`Ready`,statusSetup:`Not initialized`,statusConnecting:`Connecting`,statusIncoming:`Incoming call`,statusActive:`On a call`,statusHeld:`On hold`,statusDialing:`Dialing`,statusEnded:`Call ended`,statusFailed:`Call failed`,statusUnsupported:`Unsupported browser`,statusPermission:`Microphone unavailable`,statusError:`Unable to continue`,incoming:`Incoming call`,answer:`Answer`,reject:`Decline`,hangup:`Hang up`,mute:`Mute`,unmute:`Unmute`,hold:`Hold`,resume:`Resume`,transfer:`Transfer`,blindTransfer:`Blind transfer`,more:`More`,devices:`Devices`,enablePhone:`Enable phone`,retryPermission:`Check again`,permissionTitle:`Microphone unavailable`,permissionBody:`Allow microphone access in the browser settings, then check again.`,errorTitle:`Unable to continue`,errorBody:`Check the network, origin allowlist, or agent permission, then retry.`,currentCall:`Current call`,inbound:`Inbound`,outbound:`Outbound`,foregroundChecking:`Back in foreground, checking the connection`,foregroundFailed:`Foreground recovery failed. Retry.`,signIn:`Sign in`,signOut:`Sign out`,outboundCall:`Outbound`,internalCall:`Internal`,agentIdle:`Available`,agentBusy:`Busy`,agentBreak:`Break`,agentBusyHint:`Busy is controlled by the call or server`,rowSignIn:`Presence`,rowCall:`Call`,rowAgent:`Agent`,extensionLabel:`Extension`,extensionPlaceholder:`Optional, assigned by the server`},t={call:`呼叫`,numberLabel:`号码`,statusReady:`可拨号`,statusSetup:`未初始化`,statusConnecting:`正在连接`,statusIncoming:`来电`,statusActive:`通话中`,statusHeld:`保持中`,statusDialing:`正在拨号`,statusEnded:`通话结束`,statusFailed:`呼叫失败`,statusUnsupported:`不支持的浏览器`,statusPermission:`无法使用麦克风`,statusError:`无法继续通话`,incoming:`来电`,answer:`接听`,reject:`拒绝`,hangup:`挂断`,mute:`静音`,unmute:`取消静音`,hold:`保持`,resume:`恢复`,transfer:`转接`,blindTransfer:`盲转`,more:`更多`,devices:`设备`,enablePhone:`启用电话`,retryPermission:`重新检测`,permissionTitle:`无法使用麦克风`,permissionBody:`请在浏览器设置中允许本网站访问麦克风,然后重新检测。`,errorTitle:`无法继续通话`,errorBody:`请检查网络、域名授权或坐席权限后重试。`,currentCall:`当前通话`,inbound:`呼入`,outbound:`呼出`,foregroundChecking:`已返回前台,正在检查连接`,foregroundFailed:`前台恢复失败,请重试`,signIn:`签入`,signOut:`退签`,outboundCall:`外呼`,internalCall:`内呼`,agentIdle:`空闲`,agentBusy:`置忙`,agentBreak:`休息`,agentBusyHint:`置忙由通话或服务端状态控制`,rowSignIn:`签入`,rowCall:`通话`,rowAgent:`坐席`,extensionLabel:`分机`,extensionPlaceholder:`可空,由服务端分配`};function n(n){return n.toLowerCase().startsWith(`en`)?e:t}function r(e,t,r){return{...n(e),...r===void 0?{}:r(e),...t??{}}}async function i(e){await e.media.requestPermission(),await e.initialize(),await e.connect()}function a(e,t={}){let n=t.document??(typeof document>`u`?void 0:document);if(n===void 0)return()=>void 0;let r=()=>{if(n.visibilityState===`hidden`){t.onHidden?.();return}t.onChecking?.(),e.recover().then(()=>t.onRecovered?.()).catch(e=>t.onFailed?.(e))};return n.addEventListener(`visibilitychange`,r),()=>n.removeEventListener(`visibilitychange`,r)}function o(e){return e.replace(/\s+/g,``)}function s(e,t,n){return o(e).length>0&&n===`connected`&&t!==`denied`}async function c(e,t,n){let r=o(t);r!==``&&await e.dial({destination:r,...n===void 0?{}:{type:n}})}async function l(e,t){return t?await e.unmute():await e.mute(),!t}async function u(e){e.state===`held`?await e.resume():await e.hold()}async function d(e,t){await e.sendDtmf(t)}async function f(e,t){let n=o(t);n!==``&&await e.transfer({target:n,type:`blind`})}function p(e,t={}){let n=document.createElement(e);return t.className!==void 0&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),Object.entries(t.attrs??{}).forEach(([e,t])=>n.setAttribute(e,t)),t.children?.forEach(e=>n.append(e)),n}function m(e){return p(`div`,{attrs:{part:`status-rail`,role:`status`,"aria-live":`polite`},text:e})}function h(e,t,n=`destination`){let r=p(`input`,{attrs:{id:e,type:`tel`,inputmode:`tel`,name:n,autocomplete:`tel`}});return{field:p(`div`,{children:[p(`label`,{attrs:{for:e},text:t}),r]}),input:r}}var g=[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`*`,`0`,`#`];function _(e){return e.mode===`compact`?v(e):y(e)}function v(e){let{field:t,input:n}=h(`ccbar-destination`,e.messages.numberLabel??`号码`);n.value=e.destination;let r=e.view.kind===`ready`||e.view.kind===`setup`||e.view.kind===`ended`?p(`button`,{attrs:{type:`button`,"data-action":`dial`,part:`call-button`,...e.canDial?{}:{disabled:``}},text:e.messages.call??`呼叫`}):p(`button`,{attrs:{type:`button`,"data-action":`hangup`,part:`hangup-button`},text:e.messages.hangup??`挂断`}),i=[S(e.messages.status??``,e.floating),p(`div`,{className:`ccbar-toolbar`,children:[t,e.view.kind===`active`||e.view.kind===`held`?E(e):p(`span`),r,p(`button`,{attrs:{type:`button`,"data-action":`more`},text:e.messages.more??`更多`})]})];return e.moreOpen&&i.push(p(`div`,{className:`ccbar-more`,children:[D(e.view,e.messages),p(`button`,{attrs:{type:`button`,"data-action":`devices`},text:e.messages.devices??`设备`})]})),p(`div`,{attrs:{part:`panel`,"data-layout":`compact`},children:i})}function y(e){let{input:t}=h(`ccbar-destination`,e.messages.numberLabel??`号码`),{field:n}=h(`ccbar-transfer-target`,e.messages.transfer??`转接号码`,`transfer-target`);t.value=e.destination,t.placeholder=e.messages.numberLabel??`号码`,t.setAttribute(`aria-label`,e.messages.numberLabel??`号码`);let r=e.view.kind===`active`||e.view.kind===`held`||e.view.kind===`dialing`,i=e.view.kind===`held`,a=e.view.kind===`connecting`,o=[S(e.messages.status??``,e.floating,e.extension,e.messages.extensionLabel??`分机`),b(e.messages.rowSignIn??`签入`,[C(e),x(`signin`,e.messages.signIn??`签入`,{variant:`primary`,disabled:e.connected||a}),x(`signout`,e.messages.signOut??`退签`,{disabled:!e.connected})]),b(e.messages.numberLabel??`号码`,[t],{labelFor:t.id}),b(e.messages.rowCall??`通话`,[x(`dial`,e.messages.outboundCall??`外呼`,{variant:`primary`,disabled:!e.canDial}),x(`dial-internal`,e.messages.internalCall??`内呼`,{disabled:!e.canDial}),x(`hangup`,e.messages.hangup??`挂断`,{variant:`danger`,disabled:!r}),x(`transfer`,e.messages.transfer??`转接`,{disabled:!r}),x(`hold`,e.messages.hold??`保持`,{pressed:i,disabled:!r||i}),x(`resume`,e.messages.resume??`恢复`,{disabled:!i}),E(e)]),...r?[b(e.messages.transfer??`转接号码`,[n],{labelFor:`ccbar-transfer-target`})]:[],b(e.messages.rowAgent??`坐席`,[x(`agent-available`,e.messages.agentIdle??`空闲`,{pressed:e.agentStatus===`available`,disabled:!e.connected}),x(`agent-busy`,e.messages.agentBusy??`置忙`,{disabled:!0,title:e.messages.agentBusyHint??`置忙由通话或服务端状态控制`}),x(`agent-break`,e.messages.agentBreak??`休息`,{pressed:e.agentStatus===`break`,disabled:!e.connected})]),T()];return e.calls.length>1&&o.push(O(e.calls,e.messages)),p(`div`,{attrs:{part:`panel`,"data-layout":`panel`},children:o})}function b(e,t,n={}){return p(`div`,{className:`ccbar-bar-row`,children:[p(n.labelFor===void 0?`div`:`label`,{className:`ccbar-bar-label`,attrs:n.labelFor===void 0?{}:{for:n.labelFor},text:e}),p(`div`,{className:`ccbar-bar-keys`,children:t})]})}function x(e,t,n={}){let r=e===`dial`?`call-button`:e===`hangup`?`hangup-button`:void 0;return p(`button`,{attrs:{type:`button`,"data-action":e,...r===void 0?{}:{part:r},...n.variant===void 0?{}:{"data-variant":n.variant},...n.disabled===!0?{disabled:``}:{},...n.pressed===void 0?{}:{"aria-pressed":n.pressed?`true`:`false`},...n.title===void 0?{}:{title:n.title}},text:t})}function S(e,t,n=``,r=`分机`){let i=w(e);return t&&i.setAttribute(`data-drag-handle`,``),n!==``&&i.append(p(`span`,{className:`ccbar-ext-chip`,text:`${r} ${n}`})),i}function C(e){let t=p(`input`,{attrs:{id:`ccbar-extension`,type:`tel`,inputmode:`numeric`,name:`extension`,autocomplete:`off`,placeholder:e.messages.extensionPlaceholder??`可空,由服务端分配`,"aria-label":e.messages.extensionLabel??`分机`}});return t.value=e.extension,e.connected&&(t.readOnly=!0),t}function w(e){return m(e)}function T(){return p(`div`,{className:`ccbar-dialpad`,children:g.map(e=>p(`button`,{attrs:{type:`button`,"data-digit":e},text:e}))})}function E(e){return p(`button`,{attrs:{type:`button`,"data-action":`mute`,"aria-pressed":e.muted?`true`:`false`},text:e.muted?e.messages.unmute??`取消静音`:e.messages.mute??`静音`})}function D(e,t){let n=e.kind===`held`;return p(`button`,{attrs:{type:`button`,"data-action":`hold`,"aria-pressed":n?`true`:`false`},text:n?t.resume??`恢复`:t.hold??`保持`})}function O(e,t){return p(`ul`,{className:`ccbar-call-list`,children:e.map(e=>p(`li`,{children:[p(`button`,{attrs:{type:`button`,"data-call-id":e.id},children:[p(`span`,{text:`${e.destination} ${e.direction===`inbound`?t.inbound??`呼入`:t.outbound??`呼出`} ${k(e.state,t)}`}),...e.current?[p(`span`,{className:`ccbar-call-current`,text:t.currentCall??`当前通话`})]:[]]})]}))})}function k(e,t){return e===`held`?t.statusHeld??`保持中`:e===`active`?t.statusActive??`通话中`:e===`dialing`||e===`ringing`||e===`connecting`?t.statusDialing??`拨号中`:e}function A(e){switch(e.view.kind){case`permission-error`:return p(`div`,{attrs:{part:`panel`},children:[m(e.messages.permissionTitle??`无法使用麦克风`),p(`h2`,{text:e.messages.permissionTitle??`无法使用麦克风`}),p(`p`,{text:e.messages.permissionBody??`请在浏览器设置中允许本网站访问麦克风,然后重新检测。`}),p(`button`,{attrs:{type:`button`,"data-action":`retry-permission`},text:e.messages.retryPermission??`重新检测`})]});case`unrecoverable-error`:case`unsupported`:return p(`div`,{attrs:{part:`panel`},children:[p(`div`,{attrs:{role:`alert`,part:`status-rail`},text:e.messages.errorTitle??`无法继续通话`}),p(`p`,{text:e.messages.errorBody??`请检查网络、域名授权或坐席权限后重试。`})]});case`setup`:case`connecting`:case`incoming`:case`active`:case`held`:case`dialing`:case`ended`:case`ready`:return p(`div`,{attrs:{part:`panel`},children:[m(e.messages.status??``)]});default:return e.view}}function j(e){return p(`div`,{attrs:{part:`panel`},children:[m(e.messages.status??`来电`),p(`p`,{text:e.view.from}),p(`button`,{attrs:{type:`button`,"data-action":`answer`},text:e.messages.answer??`接听`}),p(`button`,{attrs:{type:`button`,"data-action":`reject`},text:e.messages.reject??`拒绝`})]})}var M=[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`*`,`0`,`#`];function N(e){return F(p(`div`,{attrs:{part:`panel`,"data-layout":`mobile`},children:[m(e.status),p(`button`,{attrs:{type:`button`,"data-action":`enable-phone`,...e.enabling?{disabled:``}:{}},text:e.enablePhone??`启用电话`})]}))}function P(e){let t=e.view.kind===`active`||e.view.kind===`dialing`,n=[m(e.messages.status??``)];if(t){let t=e.view.kind===`active`||e.view.kind===`dialing`?e.view.destination??``:``;n.push(p(`p`,{text:t}),I(p(`button`,{attrs:{type:`button`,"data-action":`mute`,"aria-pressed":e.muted?`true`:`false`},text:e.muted?e.messages.unmute??`取消静音`:e.messages.mute??`静音`}),44),L(),I(p(`button`,{attrs:{type:`button`,"data-action":`hangup`,part:`hangup-button`},text:e.messages.hangup??`挂断`}),52))}else{let{field:t,input:r}=h(`ccbar-destination`,e.messages.numberLabel??`号码`);r.value=e.destination,n.push(t,L(),p(`button`,{attrs:{type:`button`,"data-action":`dial`,part:`call-button`,...e.canDial?{}:{disabled:``}},text:e.messages.call??`呼叫`}))}return e.showOutputDevice&&n.push(p(`button`,{attrs:{type:`button`,"data-action":`devices`},text:e.messages.devices??`设备`})),F(p(`div`,{attrs:{part:`panel`,"data-layout":`mobile`},children:n}))}function F(e){return e.style.minHeight=`100dvh`,e.style.paddingBottom=`max(16px, env(safe-area-inset-bottom))`,e}function I(e,t){return e.style.minHeight=`${t}px`,e}function L(){return p(`div`,{className:`ccbar-dialpad`,children:M.map(e=>p(`button`,{attrs:{type:`button`,"data-digit":e},text:e}))})}var R={kind:`permission-error`,code:`MEDIA_PERMISSION_DENIED`,action:`retry-permission`};function z(e){if(e.supported===!1)return{kind:`unsupported`};if(e.permission===`denied`||e.error?.code===`MEDIA_PERMISSION_DENIED`)return R;if(e.error!==void 0&&e.error.code!==`MEDIA_PLAYBACK_BLOCKED`)return{kind:`unrecoverable-error`,code:e.error.code};let t=e.calls.find(e=>e.direction===`inbound`&&(e.state===`ringing`||e.state===`new`));if(t!==void 0)return{kind:`incoming`,callId:t.id,from:t.destination??``};let n=e.calls.find(e=>e.state===`active`);if(n!==void 0)return{kind:`active`,callId:n.id,destination:n.destination};let r=e.calls.find(e=>e.state===`held`);if(r!==void 0)return{kind:`held`,callId:r.id,destination:r.destination};let i=e.calls.find(e=>e.state===`dialing`||e.state===`ringing`||e.state===`connecting`);if(i!==void 0)return{kind:`dialing`,callId:i.id,destination:i.destination};let a=e.calls.find(e=>e.state===`ended`||e.state===`failed`);return a===void 0?e.connectionState===`connecting`||e.connectionState===`reconnecting`?{kind:`connecting`}:e.connectionState===`connected`?{kind:`ready`}:{kind:`setup`}:{kind:`ended`,callId:a.id}}var B=`:root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f5f9;--ccbar-color-border:#d8e0ea;--ccbar-color-title:#0f172a;--ccbar-color-text:#334155;--ccbar-color-muted:#475569;--ccbar-color-primary:#2563eb;--ccbar-color-primary-hover:#1d4ed8;--ccbar-color-success:#15803d;--ccbar-color-warning:#a15c00;--ccbar-color-danger:#b91c1c;--ccbar-radius-sm:6px;--ccbar-radius:8px;--ccbar-radius-lg:12px;--ccbar-control-height:40px;--ccbar-control-height-touch:44px;--ccbar-space-1:4px;--ccbar-space-2:8px;--ccbar-space-3:12px;--ccbar-space-4:16px;--ccbar-space-6:24px;--ccbar-font-family:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--ccbar-panel-width:560px}:host{color:var(--ccbar-color-text);font-family:var(--ccbar-font-family);display:block}:host([floating]){z-index:2147483646;right:var(--ccbar-space-6);bottom:var(--ccbar-space-6);position:fixed}[part=panel]{background:var(--ccbar-color-surface);border:1px solid var(--ccbar-color-border);border-radius:var(--ccbar-radius-lg)}[part=status-rail]{align-items:center;gap:var(--ccbar-space-2);min-height:var(--ccbar-control-height);padding:var(--ccbar-space-2) var(--ccbar-space-3);border-bottom:1px solid var(--ccbar-color-border);color:var(--ccbar-color-muted);font-variant-numeric:tabular-nums;display:flex}[part=status-rail]:before{content:"";background:var(--ccbar-color-muted);border-radius:50%;flex:none;width:8px;height:8px}button{min-height:var(--ccbar-control-height);border:1px solid var(--ccbar-color-border);border-radius:var(--ccbar-radius-sm);background:var(--ccbar-color-surface);color:var(--ccbar-color-title);font:inherit}button[data-action=dial],button[data-action=signin],button[data-action=answer],button[data-variant=primary]{background:var(--ccbar-color-primary);border-color:var(--ccbar-color-primary);color:#fff}button[aria-pressed=true]{border-color:var(--ccbar-color-primary);color:var(--ccbar-color-primary);background:var(--ccbar-color-surface-muted)}button[data-action=hangup],button[data-action=reject]{background:var(--ccbar-color-danger);border-color:var(--ccbar-color-danger);color:#fff;margin-top:var(--ccbar-space-4)}button:disabled{opacity:.5}button:focus-visible,input:focus-visible{outline:2px solid var(--ccbar-color-primary);outline-offset:2px}input[type=tel]{width:100%;min-height:var(--ccbar-control-height);border:1px solid var(--ccbar-color-border);border-radius:var(--ccbar-radius-sm);font-variant-numeric:tabular-nums}.ccbar-call-list{gap:var(--ccbar-space-2);margin:var(--ccbar-space-3) 0 0;padding:0;list-style:none;display:grid}.ccbar-call-list button{text-align:left;width:100%}.ccbar-call-current{color:var(--ccbar-color-title);display:block}[data-layout=compact]{min-height:80px;max-height:96px}[data-layout=compact] .ccbar-toolbar{gap:var(--ccbar-space-2);padding:var(--ccbar-space-2) var(--ccbar-space-3);grid-template-columns:minmax(0,1fr) auto auto auto;align-items:center;display:grid}[data-layout=compact] .ccbar-more{right:var(--ccbar-space-3);gap:var(--ccbar-space-2);display:grid;position:absolute}[data-layout=panel]{width:min(var(--ccbar-panel-width), 100%);min-width:420px;max-width:560px;padding:var(--ccbar-space-3)}[data-layout=panel] .ccbar-bar-row{gap:var(--ccbar-space-2) var(--ccbar-space-3);grid-template-columns:48px minmax(0,1fr);align-items:center;min-height:36px;display:grid}[data-layout=panel] .ccbar-bar-row+.ccbar-bar-row{margin-top:var(--ccbar-space-2)}[data-layout=panel] .ccbar-bar-label{color:var(--ccbar-color-muted);font-size:12px}[data-layout=panel] .ccbar-bar-keys{align-items:center;gap:var(--ccbar-space-2);flex-wrap:wrap;display:flex}[data-layout=panel] .ccbar-bar-keys button{min-width:48px;min-height:32px;padding:0 10px;font-size:13px}[data-layout=panel] .ccbar-bar-keys input[type=tel]{max-width:320px}[data-layout=panel] .ccbar-bar-keys input[name=extension]{width:148px;max-width:148px}[data-layout=panel] .ccbar-ext-chip{background:var(--ccbar-color-surface-muted);height:28px;color:var(--ccbar-color-title);font-variant-numeric:tabular-nums;border-radius:999px;align-items:center;margin-left:auto;padding:0 10px;font-size:12px;display:inline-flex}[data-layout=panel] [data-action=hangup]{margin-top:0}[data-layout=panel] .ccbar-dialpad{gap:var(--ccbar-space-2);margin:var(--ccbar-space-3) 0 0;grid-template-columns:repeat(3,1fr);display:grid}[data-layout=panel] .ccbar-safe-actions{gap:var(--ccbar-space-2);flex-wrap:wrap;display:flex}[data-layout=mobile]{min-height:100vh;padding:var(--ccbar-space-4);padding-bottom:max(16px, env(safe-area-inset-bottom))}[data-layout=mobile] button{min-width:44px;min-height:44px}[data-layout=mobile] [data-action=enable-phone],[data-layout=mobile] [data-action=dial],[data-layout=mobile] [data-action=hangup]{min-height:52px}[data-layout=mobile] .ccbar-dialpad{gap:var(--ccbar-space-2);margin:var(--ccbar-space-3) 0;grid-template-columns:repeat(3,1fr);display:grid}:host([data-theme=dark]){--ccbar-color-surface:#0f172a;--ccbar-color-surface-muted:#1e293b;--ccbar-color-border:#334155;--ccbar-color-title:#f8fafc;--ccbar-color-text:#e2e8f0;--ccbar-color-muted:#94a3b8;--ccbar-color-primary:#3b82f6;--ccbar-color-primary-hover:#2563eb;--ccbar-color-success:#22c55e;--ccbar-color-warning:#f59e0b;--ccbar-color-danger:#ef4444}@media (prefers-reduced-motion:reduce){:host *,:host :before,:host :after{transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}`,V=typeof HTMLElement==`function`?HTMLElement:class{},H=new WeakSet,U=[`connection.stateChanged`,`connection.reconnecting`,`connection.failed`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`media.permissionChanged`,`agent.statusChanged`,`error`],W=class extends V{static get observedAttributes(){return[`mode`,`floating`,`draggable`,`locale`,`theme`]}#e;#t=!1;#n=[];#r=`idle`;#i=`unknown`;#a;#o=new Set;#s=``;#c=``;#l=`offline`;#u=!1;#d=!1;#f=Promise.resolve();#p;#m=!1;#h=!1;#g;#_;#v;#y;#b;get messageResolver(){return this.#y}set messageResolver(e){this.#y=e,this.shadowRoot!==null&&this.render()}get client(){return this.#e}set client(e){this.#O(),this.#e=e,this.#D(),this.render()}get ownsClient(){return this.#t}set ownsClient(e){this.#t=e===!0}connectedCallback(){this.#V(),this.#B(),this.render()}disconnectedCallback(){let e=this.#e,t=this.#t;this.#O(),this.#G(),this.#b?.(),this.#b=void 0,t&&(this.#e=void 0,e?.dispose())}attributeChangedCallback(e){this.#V(),e===`theme`&&this.#B(),this.shadowRoot!==null&&this.render()}render(){let e=this.#k();e!==void 0&&(e.innerHTML=`<style>${B}</style>`,e.append(this.#S(this.#x())))}#x(){let e=this.#e?.getCalls?.().map(e=>({id:e.id,state:e.state,destination:e.destination,direction:this.#o.has(e.id)?`inbound`:`outbound`}))??[];return z({connectionState:this.#r,permission:this.#i,calls:e,error:this.#a})}#S(e){let t=this.#z(),n=this.#_??this.#g??K(e,t),r={...t,status:n},i=this.#C(e,r,n);return i.setAttribute(`data-view`,this.#E()&&!this.#m?`setup`:e.kind),i.hasAttribute(`data-layout`)||i.setAttribute(`data-layout`,this.#E()?`mobile`:`panel`),i}#C(e,t,n){if(this.#E()&&!this.#m)return N({enabling:this.#h,status:n,enablePhone:t.enablePhone});switch(e.kind){case`permission-error`:case`unrecoverable-error`:case`unsupported`:return A({view:e,messages:t});case`incoming`:return this.#E()?P({view:{kind:`ready`},messages:t,destination:this.#s,muted:this.#u,canDial:s(this.#s,this.#i,this.#r),showOutputDevice:this.#e?.media.supportsOutputSelection()===!0}):j({view:e,messages:t});case`setup`:case`connecting`:case`ended`:case`ready`:case`active`:case`held`:case`dialing`:return this.#E()?P({view:e.kind===`held`?{kind:`ready`}:e,messages:t,destination:this.#s,muted:this.#u,canDial:s(this.#s,this.#i,this.#r),showOutputDevice:this.#e?.media.supportsOutputSelection()===!0}):_({mode:this.#T()===`compact`?`compact`:`panel`,view:e,messages:t,destination:this.#s,muted:this.#u,canDial:s(this.#s,this.#i,this.#r),moreOpen:this.#d,floating:this.hasAttribute(`floating`),connected:this.#r===`connected`,agentStatus:this.#l,extension:this.#c,calls:this.#w()});default:return e}}#w(){let e=this.#e?.getActiveCall?.()?.id;return this.#e?.getCalls?.().map(t=>({id:t.id,destination:t.destination,state:t.state,direction:this.#o.has(t.id)?`inbound`:`outbound`,current:t.id===e}))??[]}#T(){let e=this.getAttribute(`mode`);return e===`compact`||e===`mobile`?e:`panel`}#E(){return this.#T()===`mobile`}#D(){let e=this.#e;e!==void 0&&(this.#n.push(e.on(`connection.stateChanged`,t=>{if(this.#r=t.state,t.state!==`connected`&&(this.#l=`offline`),t.state===`connected`){let t=e.getAgent?.()?.extension?.trim();t!==void 0&&t!==``&&(this.#c=t)}})),this.#n.push(e.on(`agent.statusChanged`,e=>{(e.status===`available`||e.status===`offline`||e.status===`break`)&&(this.#l=e.status)})),this.#n.push(e.on(`connection.failed`,e=>{this.#r=`failed`,this.#a={code:e.error.code}})),this.#n.push(e.on(`media.permissionChanged`,e=>{this.#i=e.permission})),this.#n.push(e.on(`error`,e=>{this.#a={code:e.error.code}})),this.#n.push(e.on(`call.incoming`,e=>{this.#o.add(e.callId)})),this.#n.push(e.on(`call.ended`,e=>{this.#o.delete(e.callId),this.#u=!1})),this.#n.push(e.on(`call.failed`,()=>{this.#_=this.#z().statusFailed})),U.forEach(t=>{this.#n.push(e.on(t,()=>this.render()))}),this.#E()&&typeof e.recover==`function`&&(this.#v=a(e,{onChecking:()=>{this.#g=this.#z().foregroundChecking,this.render()},onRecovered:()=>{this.#g=void 0,this.render()},onFailed:()=>{this.#g=this.#z().foregroundFailed,this.render()}})))}#O(){let e=this.#n;this.#n=[],e.forEach(e=>e()),this.#r=`idle`,this.#i=`unknown`,this.#l=`offline`,this.#a=void 0,this.#o.clear(),this.#u=!1,this.#d=!1,this.#m=!1,this.#h=!1,this.#g=void 0,this.#v?.(),this.#v=void 0}#k(){if(typeof this.attachShadow!=`function`)return;let e=this.shadowRoot??this.attachShadow({mode:`open`});return H.has(e)||(H.add(e),e.addEventListener(`click`,e=>this.#A(e)),e.addEventListener(`input`,e=>this.#P(e)),e.addEventListener(`pointerdown`,e=>this.#H(e))),e}#A(e){let t=J(e,this),n=t?.closest(`[data-action="enable-phone"]`);n instanceof HTMLButtonElement&&(n.disabled=!0),this.#f=this.#f.then(()=>this.#F(t)).catch(e=>{this.#_=Y(e),this.render()})}#j(){let e=this.shadowRoot?.querySelector(`input[name="destination"]`);return e instanceof HTMLInputElement?e.value:this.#s}#M(){let e=this.shadowRoot?.querySelector(`input[name="extension"]`);return e instanceof HTMLInputElement?e.value.trim():this.#c}#N(){let e=this.shadowRoot?.querySelector(`input[name="transfer-target"]`);return e instanceof HTMLInputElement?e.value:``}#P(e){let t=J(e,this);if(t instanceof HTMLInputElement&&t.name!==`transfer-target`){if(t.name===`extension`){this.#c=t.value.trim();return}this.#s=t.value,this.#L()}}async#F(e){if(this.#_=void 0,e===void 0)return;let t=e.closest(`[data-call-id]`);if(t instanceof HTMLElement&&t.dataset.callId!==void 0){await this.#e?.setActiveCall(t.dataset.callId);return}let n=e.closest(`[data-digit]`);if(n instanceof HTMLElement&&n.dataset.digit!==void 0){await this.#I(n.dataset.digit);return}let r=e.closest(`[data-action]`);if(!(r instanceof HTMLElement)||r instanceof HTMLButtonElement&&r.disabled&&r.getAttribute(`data-action`)!==`enable-phone`)return;let a=this.#e?.getActiveCall?.();switch(r.getAttribute(`data-action`)){case`signin`:if(this.#e===void 0)return;this.#c=this.#M(),await this.#e.media?.requestPermission?.(),await this.#e.initialize(),await this.#e.connect(this.#c===``?void 0:{extension:this.#c});return;case`signout`:if(this.#e===void 0)return;this.#l=`offline`,await this.#e.disconnect();return;case`dial`:case`dial-internal`:if(this.#s=this.#j(),this.#e===void 0)return;this.#i!==`granted`&&await this.#e.media?.requestPermission?.(),await c(this.#e,this.#s,r.getAttribute(`data-action`)===`dial-internal`?`extension`:void 0);return;case`mute`:if(a===void 0)return;this.#u=await l(a,this.#u),this.#R();return;case`hold`:a!==void 0&&await u(a);return;case`resume`:a!==void 0&&await a.resume();return;case`transfer`:a!==void 0&&await f(a,this.#N());return;case`hangup`:await a?.hangup();return;case`answer`:a!==void 0&&await this.#e?.answer(a.id);return;case`reject`:await a?.reject();return;case`enable-phone`:if(this.#e===void 0||this.#m)return;this.#h=!0;try{await i(this.#e),this.#m=!0}finally{this.#h=!1,this.render()}return;case`more`:this.#d=!this.#d,this.render();return;case`retry-permission`:await this.#e?.media.requestPermission();return;case`devices`:return;case`agent-available`:await this.#e?.setAgentStatus(`available`);return;case`agent-break`:await this.#e?.setAgentStatus(`break`);return;case`agent-busy`:return;default:return}}async#I(e){let t=this.#e?.getActiveCall?.();if(t!==void 0&&(t.state===`active`||t.state===`held`)){await d(t,e);return}this.#s+=e;let n=this.shadowRoot?.querySelector(`input[name="destination"]`);n instanceof HTMLInputElement&&(n.value=this.#s),this.#L()}#L(){let e=!s(this.#s,this.#i,this.#r);for(let t of[`dial`,`dial-internal`]){let n=this.shadowRoot?.querySelector(`[data-action="${t}"]`);n instanceof HTMLButtonElement&&(n.disabled=e)}}#R(){let e=this.shadowRoot?.querySelector(`[data-action="mute"]`);e instanceof HTMLButtonElement&&(e.setAttribute(`aria-pressed`,this.#u?`true`:`false`),e.textContent=this.#u?this.#z().unmute:this.#z().mute)}#z(){return r(this.getAttribute(`locale`)??`zh-CN`,void 0,this.#y)}#B(){this.#b?.(),this.#b=void 0;let e=this.getAttribute(`theme`)??`light`;if(e===`dark`||e===`light`){this.setAttribute(`data-theme`,e);return}if(typeof window>`u`||typeof window.matchMedia!=`function`){this.setAttribute(`data-theme`,`light`);return}let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>{this.setAttribute(`data-theme`,t.matches?`dark`:`light`)};n(),t.addEventListener(`change`,n),this.#b=()=>t.removeEventListener(`change`,n)}#V(){this.style.position=this.hasAttribute(`floating`)?`fixed`:``}#H(e){if(!(e instanceof PointerEvent)||!this.hasAttribute(`floating`)||!this.hasAttribute(`draggable`)||(e.target instanceof Element?e.target.closest(`[data-drag-handle]`):null)===null)return;e.preventDefault();let t=this.getBoundingClientRect();this.#p={pointerId:e.pointerId,offsetX:e.clientX-t.left,offsetY:e.clientY-t.top},window.addEventListener(`pointermove`,this.#U),window.addEventListener(`pointerup`,this.#W)}#U=e=>{if(this.#p===void 0||e.pointerId!==this.#p.pointerId)return;let t=window.visualViewport,n=t?.width??window.innerWidth,r=t?.height??window.innerHeight,i=q(e.clientX-this.#p.offsetX,0,Math.max(0,n-this.offsetWidth)),a=q(e.clientY-this.#p.offsetY,0,Math.max(0,r-this.offsetHeight));this.style.left=`${i}px`,this.style.top=`${a}px`,this.style.right=`auto`,this.style.bottom=`auto`};#W=e=>{this.#p!==void 0&&e.pointerId===this.#p.pointerId&&this.#G()};#G(){this.#p=void 0,window.removeEventListener(`pointermove`,this.#U),window.removeEventListener(`pointerup`,this.#W)}};function G(e={}){if(typeof customElements>`u`)return;let t=e.tagName??`xcall-ccbar`;if(customElements.get(t)!==void 0)return;let n=t===`xcall-ccbar`?W:class extends W{};customElements.define(t,n)}function K(e,t){switch(e.kind){case`unsupported`:return t.statusUnsupported;case`permission-error`:return t.statusPermission;case`unrecoverable-error`:return t.statusError;case`setup`:return t.statusSetup;case`connecting`:return t.statusConnecting;case`incoming`:return t.statusIncoming;case`active`:return t.statusActive;case`held`:return t.statusHeld;case`dialing`:return t.statusDialing;case`ended`:return t.statusEnded;case`ready`:return t.statusReady;default:return e}}function q(e,t,n){return Math.min(n,Math.max(t,e))}function J(e,t){for(let n of e.composedPath())if(n instanceof Element&&n!==t)return n;return e.target instanceof Element&&e.target!==t?e.target:void 0}function Y(e){return typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:`SDK_INTERNAL_ERROR`}var X=`0.1.0`;exports.XCallCCBarElement=W,exports.defineCCBarElement=G,exports.enUS=e,exports.resolveMessages=r,exports.uiVersion=X,exports.zhCN=t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require("../createJsSipFactory-Dr8HbLl-.cjs");var e={call:`Call`,numberLabel:`Number`,statusReady:`Ready`,statusSetup:`Not initialized`,statusConnecting:`Connecting`,statusIncoming:`Incoming call`,statusActive:`On a call`,statusHeld:`On hold`,statusDialing:`Dialing`,statusEnded:`Call ended`,statusFailed:`Call failed`,statusUnsupported:`Unsupported browser`,statusPermission:`Microphone unavailable`,statusError:`Unable to continue`,incoming:`Incoming call`,answer:`Answer`,reject:`Decline`,hangup:`Hang up`,mute:`Mute`,unmute:`Unmute`,hold:`Hold`,resume:`Resume`,transfer:`Transfer`,blindTransfer:`Blind transfer`,more:`More`,devices:`Devices`,enablePhone:`Enable phone`,retryPermission:`Check again`,permissionTitle:`Microphone unavailable`,permissionBody:`Allow microphone access in the browser settings, then check again.`,errorTitle:`Unable to continue`,errorBody:`Check the network, origin allowlist, or agent permission, then retry.`,currentCall:`Current call`,inbound:`Inbound`,outbound:`Outbound`,foregroundChecking:`Back in foreground, checking the connection`,foregroundFailed:`Foreground recovery failed. Retry.`,signIn:`Sign in`,signOut:`Sign out`,outboundCall:`Outbound`,internalCall:`Internal`,agentIdle:`Available`,agentBusy:`Busy`,agentBreak:`Break`,agentBusyHint:`Busy is controlled by the call or server`,rowSignIn:`Presence`,rowCall:`Call`,rowAgent:`Agent`,extensionLabel:`Extension`,extensionPlaceholder:`Optional, assigned by the server`},t={call:`呼叫`,numberLabel:`号码`,statusReady:`可拨号`,statusSetup:`未初始化`,statusConnecting:`正在连接`,statusIncoming:`来电`,statusActive:`通话中`,statusHeld:`保持中`,statusDialing:`正在拨号`,statusEnded:`通话结束`,statusFailed:`呼叫失败`,statusUnsupported:`不支持的浏览器`,statusPermission:`无法使用麦克风`,statusError:`无法继续通话`,incoming:`来电`,answer:`接听`,reject:`拒绝`,hangup:`挂断`,mute:`静音`,unmute:`取消静音`,hold:`保持`,resume:`恢复`,transfer:`转接`,blindTransfer:`盲转`,more:`更多`,devices:`设备`,enablePhone:`启用电话`,retryPermission:`重新检测`,permissionTitle:`无法使用麦克风`,permissionBody:`请在浏览器设置中允许本网站访问麦克风,然后重新检测。`,errorTitle:`无法继续通话`,errorBody:`请检查网络、域名授权或坐席权限后重试。`,currentCall:`当前通话`,inbound:`呼入`,outbound:`呼出`,foregroundChecking:`已返回前台,正在检查连接`,foregroundFailed:`前台恢复失败,请重试`,signIn:`签入`,signOut:`退签`,outboundCall:`外呼`,internalCall:`内呼`,agentIdle:`空闲`,agentBusy:`置忙`,agentBreak:`休息`,agentBusyHint:`置忙由通话或服务端状态控制`,rowSignIn:`签入`,rowCall:`通话`,rowAgent:`坐席`,extensionLabel:`分机`,extensionPlaceholder:`可空,由服务端分配`};function n(n){return n.toLowerCase().startsWith(`en`)?e:t}function r(e,t,r){return{...n(e),...r===void 0?{}:r(e),...t??{}}}async function i(e){await e.media.requestPermission(),await e.initialize(),await e.connect()}function a(e,t={}){let n=t.document??(typeof document>`u`?void 0:document);if(n===void 0)return()=>void 0;let r=()=>{if(n.visibilityState===`hidden`){t.onHidden?.();return}t.onChecking?.(),e.recover().then(()=>t.onRecovered?.()).catch(e=>t.onFailed?.(e))};return n.addEventListener(`visibilitychange`,r),()=>n.removeEventListener(`visibilitychange`,r)}function o(e){return e.replace(/\s+/g,``)}function s(e,t,n){return o(e).length>0&&n===`connected`&&t!==`denied`}async function c(e,t,n){let r=o(t);r!==``&&await e.dial({destination:r,...n===void 0?{}:{type:n}})}async function l(e,t){return t?await e.unmute():await e.mute(),!t}async function u(e){e.state===`held`?await e.resume():await e.hold()}async function d(e,t){await e.sendDtmf(t)}async function f(e,t){let n=o(t);n!==``&&await e.transfer({target:n,type:`blind`})}function p(e,t={}){let n=document.createElement(e);return t.className!==void 0&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),Object.entries(t.attrs??{}).forEach(([e,t])=>n.setAttribute(e,t)),t.children?.forEach(e=>n.append(e)),n}function m(e){return p(`div`,{attrs:{part:`status-rail`,role:`status`,"aria-live":`polite`},text:e})}function h(e,t,n=`destination`){let r=p(`input`,{attrs:{id:e,type:`tel`,inputmode:`tel`,name:n,autocomplete:`tel`}});return{field:p(`div`,{children:[p(`label`,{attrs:{for:e},text:t}),r]}),input:r}}var g=[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`*`,`0`,`#`];function _(e){return e.mode===`compact`?v(e):y(e)}function v(e){let{field:t,input:n}=h(`ccbar-destination`,e.messages.numberLabel??`号码`);n.value=e.destination;let r=e.view.kind===`ready`||e.view.kind===`setup`||e.view.kind===`ended`?p(`button`,{attrs:{type:`button`,"data-action":`dial`,part:`call-button`,...e.canDial?{}:{disabled:``}},text:e.messages.call??`呼叫`}):p(`button`,{attrs:{type:`button`,"data-action":`hangup`,part:`hangup-button`},text:e.messages.hangup??`挂断`}),i=[S(e.messages.status??``,e.floating),p(`div`,{className:`ccbar-toolbar`,children:[t,e.view.kind===`active`||e.view.kind===`held`?E(e):p(`span`),r,p(`button`,{attrs:{type:`button`,"data-action":`more`},text:e.messages.more??`更多`})]})];return e.moreOpen&&i.push(p(`div`,{className:`ccbar-more`,children:[D(e.view,e.messages),p(`button`,{attrs:{type:`button`,"data-action":`devices`},text:e.messages.devices??`设备`})]})),p(`div`,{attrs:{part:`panel`,"data-layout":`compact`},children:i})}function y(e){let{input:t}=h(`ccbar-destination`,e.messages.numberLabel??`号码`),{field:n}=h(`ccbar-transfer-target`,e.messages.transfer??`转接号码`,`transfer-target`);t.value=e.destination,t.placeholder=e.messages.numberLabel??`号码`,t.setAttribute(`aria-label`,e.messages.numberLabel??`号码`);let r=e.view.kind===`active`||e.view.kind===`held`||e.view.kind===`dialing`,i=e.view.kind===`held`,a=e.view.kind===`connecting`,o=[S(e.messages.status??``,e.floating,e.extension,e.messages.extensionLabel??`分机`),b(e.messages.rowSignIn??`签入`,[C(e),x(`signin`,e.messages.signIn??`签入`,{variant:`primary`,disabled:e.connected||a}),x(`signout`,e.messages.signOut??`退签`,{disabled:!e.connected})]),b(e.messages.numberLabel??`号码`,[t],{labelFor:t.id}),b(e.messages.rowCall??`通话`,[x(`dial`,e.messages.outboundCall??`外呼`,{variant:`primary`,disabled:!e.canDial}),x(`dial-internal`,e.messages.internalCall??`内呼`,{disabled:!e.canDial}),x(`hangup`,e.messages.hangup??`挂断`,{variant:`danger`,disabled:!r}),x(`transfer`,e.messages.transfer??`转接`,{disabled:!r}),x(`hold`,e.messages.hold??`保持`,{pressed:i,disabled:!r||i}),x(`resume`,e.messages.resume??`恢复`,{disabled:!i}),E(e)]),...r?[b(e.messages.transfer??`转接号码`,[n],{labelFor:`ccbar-transfer-target`})]:[],b(e.messages.rowAgent??`坐席`,[x(`agent-available`,e.messages.agentIdle??`空闲`,{pressed:e.agentStatus===`available`,disabled:!e.connected}),x(`agent-busy`,e.messages.agentBusy??`置忙`,{disabled:!0,title:e.messages.agentBusyHint??`置忙由通话或服务端状态控制`}),x(`agent-break`,e.messages.agentBreak??`休息`,{pressed:e.agentStatus===`break`,disabled:!e.connected})]),T()];return e.calls.length>1&&o.push(O(e.calls,e.messages)),p(`div`,{attrs:{part:`panel`,"data-layout":`panel`},children:o})}function b(e,t,n={}){return p(`div`,{className:`ccbar-bar-row`,children:[p(n.labelFor===void 0?`div`:`label`,{className:`ccbar-bar-label`,attrs:n.labelFor===void 0?{}:{for:n.labelFor},text:e}),p(`div`,{className:`ccbar-bar-keys`,children:t})]})}function x(e,t,n={}){let r=e===`dial`?`call-button`:e===`hangup`?`hangup-button`:void 0;return p(`button`,{attrs:{type:`button`,"data-action":e,...r===void 0?{}:{part:r},...n.variant===void 0?{}:{"data-variant":n.variant},...n.disabled===!0?{disabled:``}:{},...n.pressed===void 0?{}:{"aria-pressed":n.pressed?`true`:`false`},...n.title===void 0?{}:{title:n.title}},text:t})}function S(e,t,n=``,r=`分机`){let i=w(e);return t&&i.setAttribute(`data-drag-handle`,``),n!==``&&i.append(p(`span`,{className:`ccbar-ext-chip`,text:`${r} ${n}`})),i}function C(e){let t=p(`input`,{attrs:{id:`ccbar-extension`,type:`tel`,inputmode:`numeric`,name:`extension`,autocomplete:`off`,placeholder:e.messages.extensionPlaceholder??`可空,由服务端分配`,"aria-label":e.messages.extensionLabel??`分机`}});return t.value=e.extension,e.connected&&(t.readOnly=!0),t}function w(e){return m(e)}function T(){return p(`div`,{className:`ccbar-dialpad`,children:g.map(e=>p(`button`,{attrs:{type:`button`,"data-digit":e},text:e}))})}function E(e){return p(`button`,{attrs:{type:`button`,"data-action":`mute`,"aria-pressed":e.muted?`true`:`false`},text:e.muted?e.messages.unmute??`取消静音`:e.messages.mute??`静音`})}function D(e,t){let n=e.kind===`held`;return p(`button`,{attrs:{type:`button`,"data-action":`hold`,"aria-pressed":n?`true`:`false`},text:n?t.resume??`恢复`:t.hold??`保持`})}function O(e,t){return p(`ul`,{className:`ccbar-call-list`,children:e.map(e=>p(`li`,{children:[p(`button`,{attrs:{type:`button`,"data-call-id":e.id},children:[p(`span`,{text:`${e.destination} ${e.direction===`inbound`?t.inbound??`呼入`:t.outbound??`呼出`} ${k(e.state,t)}`}),...e.current?[p(`span`,{className:`ccbar-call-current`,text:t.currentCall??`当前通话`})]:[]]})]}))})}function k(e,t){return e===`held`?t.statusHeld??`保持中`:e===`active`?t.statusActive??`通话中`:e===`dialing`||e===`ringing`||e===`connecting`?t.statusDialing??`拨号中`:e}function A(e){switch(e.view.kind){case`permission-error`:return p(`div`,{attrs:{part:`panel`},children:[m(e.messages.permissionTitle??`无法使用麦克风`),p(`h2`,{text:e.messages.permissionTitle??`无法使用麦克风`}),p(`p`,{text:e.messages.permissionBody??`请在浏览器设置中允许本网站访问麦克风,然后重新检测。`}),p(`button`,{attrs:{type:`button`,"data-action":`retry-permission`},text:e.messages.retryPermission??`重新检测`})]});case`unrecoverable-error`:case`unsupported`:return p(`div`,{attrs:{part:`panel`},children:[p(`div`,{attrs:{role:`alert`,part:`status-rail`},text:e.messages.errorTitle??`无法继续通话`}),p(`p`,{text:e.messages.errorBody??`请检查网络、域名授权或坐席权限后重试。`})]});case`setup`:case`connecting`:case`incoming`:case`active`:case`held`:case`dialing`:case`ended`:case`ready`:return p(`div`,{attrs:{part:`panel`},children:[m(e.messages.status??``)]});default:return e.view}}function j(e){return p(`div`,{attrs:{part:`panel`},children:[m(e.messages.status??`来电`),p(`p`,{text:e.view.from}),p(`button`,{attrs:{type:`button`,"data-action":`answer`},text:e.messages.answer??`接听`}),p(`button`,{attrs:{type:`button`,"data-action":`reject`},text:e.messages.reject??`拒绝`})]})}var M=[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`*`,`0`,`#`];function N(e){return F(p(`div`,{attrs:{part:`panel`,"data-layout":`mobile`},children:[m(e.status),p(`button`,{attrs:{type:`button`,"data-action":`enable-phone`,...e.enabling?{disabled:``}:{}},text:e.enablePhone??`启用电话`})]}))}function P(e){let t=e.view.kind===`active`||e.view.kind===`dialing`,n=[m(e.messages.status??``)];if(t){let t=e.view.kind===`active`||e.view.kind===`dialing`?e.view.destination??``:``;n.push(p(`p`,{text:t}),I(p(`button`,{attrs:{type:`button`,"data-action":`mute`,"aria-pressed":e.muted?`true`:`false`},text:e.muted?e.messages.unmute??`取消静音`:e.messages.mute??`静音`}),44),L(),I(p(`button`,{attrs:{type:`button`,"data-action":`hangup`,part:`hangup-button`},text:e.messages.hangup??`挂断`}),52))}else{let{field:t,input:r}=h(`ccbar-destination`,e.messages.numberLabel??`号码`);r.value=e.destination,n.push(t,L(),p(`button`,{attrs:{type:`button`,"data-action":`dial`,part:`call-button`,...e.canDial?{}:{disabled:``}},text:e.messages.call??`呼叫`}))}return e.showOutputDevice&&n.push(p(`button`,{attrs:{type:`button`,"data-action":`devices`},text:e.messages.devices??`设备`})),F(p(`div`,{attrs:{part:`panel`,"data-layout":`mobile`},children:n}))}function F(e){return e.style.minHeight=`100dvh`,e.style.paddingBottom=`max(16px, env(safe-area-inset-bottom))`,e}function I(e,t){return e.style.minHeight=`${t}px`,e}function L(){return p(`div`,{className:`ccbar-dialpad`,children:M.map(e=>p(`button`,{attrs:{type:`button`,"data-digit":e},text:e}))})}var R={kind:`permission-error`,code:`MEDIA_PERMISSION_DENIED`,action:`retry-permission`};function z(e){if(e.supported===!1)return{kind:`unsupported`};if(e.permission===`denied`||e.error?.code===`MEDIA_PERMISSION_DENIED`)return R;if(e.error!==void 0&&e.error.code!==`MEDIA_PLAYBACK_BLOCKED`)return{kind:`unrecoverable-error`,code:e.error.code};let t=e.calls.find(e=>e.direction===`inbound`&&(e.state===`ringing`||e.state===`new`));if(t!==void 0)return{kind:`incoming`,callId:t.id,from:t.destination??``};let n=e.calls.find(e=>e.state===`active`);if(n!==void 0)return{kind:`active`,callId:n.id,destination:n.destination};let r=e.calls.find(e=>e.state===`held`);if(r!==void 0)return{kind:`held`,callId:r.id,destination:r.destination};let i=e.calls.find(e=>e.state===`dialing`||e.state===`ringing`||e.state===`connecting`);if(i!==void 0)return{kind:`dialing`,callId:i.id,destination:i.destination};let a=e.calls.find(e=>e.state===`ended`||e.state===`failed`);return a===void 0?e.connectionState===`connecting`||e.connectionState===`reconnecting`?{kind:`connecting`}:e.connectionState===`connected`?{kind:`ready`}:{kind:`setup`}:{kind:`ended`,callId:a.id}}var B=`:root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f5f9;--ccbar-color-border:#d8e0ea;--ccbar-color-title:#0f172a;--ccbar-color-text:#334155;--ccbar-color-muted:#475569;--ccbar-color-primary:#2563eb;--ccbar-color-primary-hover:#1d4ed8;--ccbar-color-success:#15803d;--ccbar-color-warning:#a15c00;--ccbar-color-danger:#b91c1c;--ccbar-radius-sm:6px;--ccbar-radius:8px;--ccbar-radius-lg:12px;--ccbar-control-height:40px;--ccbar-control-height-touch:44px;--ccbar-space-1:4px;--ccbar-space-2:8px;--ccbar-space-3:12px;--ccbar-space-4:16px;--ccbar-space-6:24px;--ccbar-font-family:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--ccbar-panel-width:560px}:host{color:var(--ccbar-color-text);font-family:var(--ccbar-font-family);display:block}:host([floating]){z-index:2147483646;right:var(--ccbar-space-6);bottom:var(--ccbar-space-6);position:fixed}[part=panel]{background:var(--ccbar-color-surface);border:1px solid var(--ccbar-color-border);border-radius:var(--ccbar-radius-lg)}[part=status-rail]{align-items:center;gap:var(--ccbar-space-2);min-height:var(--ccbar-control-height);padding:var(--ccbar-space-2) var(--ccbar-space-3);border-bottom:1px solid var(--ccbar-color-border);color:var(--ccbar-color-muted);font-variant-numeric:tabular-nums;display:flex}[part=status-rail]:before{content:"";background:var(--ccbar-color-muted);border-radius:50%;flex:none;width:8px;height:8px}button{min-height:var(--ccbar-control-height);border:1px solid var(--ccbar-color-border);border-radius:var(--ccbar-radius-sm);background:var(--ccbar-color-surface);color:var(--ccbar-color-title);font:inherit}button[data-action=dial],button[data-action=signin],button[data-action=answer],button[data-variant=primary]{background:var(--ccbar-color-primary);border-color:var(--ccbar-color-primary);color:#fff}button[aria-pressed=true]{border-color:var(--ccbar-color-primary);color:var(--ccbar-color-primary);background:var(--ccbar-color-surface-muted)}button[data-action=hangup],button[data-action=reject]{background:var(--ccbar-color-danger);border-color:var(--ccbar-color-danger);color:#fff;margin-top:var(--ccbar-space-4)}button:disabled{opacity:.5}button:focus-visible,input:focus-visible{outline:2px solid var(--ccbar-color-primary);outline-offset:2px}input[type=tel]{width:100%;min-height:var(--ccbar-control-height);border:1px solid var(--ccbar-color-border);border-radius:var(--ccbar-radius-sm);font-variant-numeric:tabular-nums}.ccbar-call-list{gap:var(--ccbar-space-2);margin:var(--ccbar-space-3) 0 0;padding:0;list-style:none;display:grid}.ccbar-call-list button{text-align:left;width:100%}.ccbar-call-current{color:var(--ccbar-color-title);display:block}[data-layout=compact]{min-height:80px;max-height:96px}[data-layout=compact] .ccbar-toolbar{gap:var(--ccbar-space-2);padding:var(--ccbar-space-2) var(--ccbar-space-3);grid-template-columns:minmax(0,1fr) auto auto auto;align-items:center;display:grid}[data-layout=compact] .ccbar-more{right:var(--ccbar-space-3);gap:var(--ccbar-space-2);display:grid;position:absolute}[data-layout=panel]{width:min(var(--ccbar-panel-width), 100%);min-width:420px;max-width:560px;padding:var(--ccbar-space-3)}[data-layout=panel] .ccbar-bar-row{gap:var(--ccbar-space-2) var(--ccbar-space-3);grid-template-columns:48px minmax(0,1fr);align-items:center;min-height:36px;display:grid}[data-layout=panel] .ccbar-bar-row+.ccbar-bar-row{margin-top:var(--ccbar-space-2)}[data-layout=panel] .ccbar-bar-label{color:var(--ccbar-color-muted);font-size:12px}[data-layout=panel] .ccbar-bar-keys{align-items:center;gap:var(--ccbar-space-2);flex-wrap:wrap;display:flex}[data-layout=panel] .ccbar-bar-keys button{min-width:48px;min-height:32px;padding:0 10px;font-size:13px}[data-layout=panel] .ccbar-bar-keys input[type=tel]{max-width:320px}[data-layout=panel] .ccbar-bar-keys input[name=extension]{width:148px;max-width:148px}[data-layout=panel] .ccbar-ext-chip{background:var(--ccbar-color-surface-muted);height:28px;color:var(--ccbar-color-title);font-variant-numeric:tabular-nums;border-radius:999px;align-items:center;margin-left:auto;padding:0 10px;font-size:12px;display:inline-flex}[data-layout=panel] [data-action=hangup]{margin-top:0}[data-layout=panel] .ccbar-dialpad{gap:var(--ccbar-space-2);margin:var(--ccbar-space-3) 0 0;grid-template-columns:repeat(3,1fr);display:grid}[data-layout=panel] .ccbar-safe-actions{gap:var(--ccbar-space-2);flex-wrap:wrap;display:flex}[data-layout=mobile]{min-height:100vh;padding:var(--ccbar-space-4);padding-bottom:max(16px, env(safe-area-inset-bottom))}[data-layout=mobile] button{min-width:44px;min-height:44px}[data-layout=mobile] [data-action=enable-phone],[data-layout=mobile] [data-action=dial],[data-layout=mobile] [data-action=hangup]{min-height:52px}[data-layout=mobile] .ccbar-dialpad{gap:var(--ccbar-space-2);margin:var(--ccbar-space-3) 0;grid-template-columns:repeat(3,1fr);display:grid}:host([data-theme=dark]){--ccbar-color-surface:#0f172a;--ccbar-color-surface-muted:#1e293b;--ccbar-color-border:#334155;--ccbar-color-title:#f8fafc;--ccbar-color-text:#e2e8f0;--ccbar-color-muted:#94a3b8;--ccbar-color-primary:#3b82f6;--ccbar-color-primary-hover:#2563eb;--ccbar-color-success:#22c55e;--ccbar-color-warning:#f59e0b;--ccbar-color-danger:#ef4444}@media (prefers-reduced-motion:reduce){:host *,:host :before,:host :after{transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}`,V=typeof HTMLElement==`function`?HTMLElement:class{},H=new WeakSet,U=[`connection.stateChanged`,`connection.reconnecting`,`connection.failed`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`media.permissionChanged`,`agent.statusChanged`,`error`],W=class extends V{static get observedAttributes(){return[`mode`,`floating`,`draggable`,`locale`,`theme`]}#e;#t=!1;#n=[];#r=`idle`;#i=`unknown`;#a;#o=new Set;#s=``;#c=``;#l=`offline`;#u=!1;#d=!1;#f=Promise.resolve();#p;#m=!1;#h=!1;#g;#_;#v;#y;#b;get messageResolver(){return this.#y}set messageResolver(e){this.#y=e,this.shadowRoot!==null&&this.render()}get client(){return this.#e}set client(e){this.#O(),this.#e=e,this.#D(),this.render()}get ownsClient(){return this.#t}set ownsClient(e){this.#t=e===!0}connectedCallback(){this.#V(),this.#B(),this.render()}disconnectedCallback(){let e=this.#e,t=this.#t;this.#O(),this.#G(),this.#b?.(),this.#b=void 0,t&&(this.#e=void 0,e?.dispose())}attributeChangedCallback(e){this.#V(),e===`theme`&&this.#B(),this.shadowRoot!==null&&this.render()}render(){let e=this.#k();e!==void 0&&(e.innerHTML=`<style>${B}</style>`,e.append(this.#S(this.#x())))}#x(){let e=this.#e?.getCalls?.().map(e=>({id:e.id,state:e.state,destination:e.destination,direction:this.#o.has(e.id)?`inbound`:`outbound`}))??[];return z({connectionState:this.#r,permission:this.#i,calls:e,error:this.#a})}#S(e){let t=this.#z(),n=this.#_??this.#g??K(e,t),r={...t,status:n},i=this.#C(e,r,n);return i.setAttribute(`data-view`,this.#E()&&!this.#m?`setup`:e.kind),i.hasAttribute(`data-layout`)||i.setAttribute(`data-layout`,this.#E()?`mobile`:`panel`),i}#C(e,t,n){if(this.#E()&&!this.#m)return N({enabling:this.#h,status:n,enablePhone:t.enablePhone});switch(e.kind){case`permission-error`:case`unrecoverable-error`:case`unsupported`:return A({view:e,messages:t});case`incoming`:return this.#E()?P({view:{kind:`ready`},messages:t,destination:this.#s,muted:this.#u,canDial:s(this.#s,this.#i,this.#r),showOutputDevice:this.#e?.media.supportsOutputSelection()===!0}):j({view:e,messages:t});case`setup`:case`connecting`:case`ended`:case`ready`:case`active`:case`held`:case`dialing`:return this.#E()?P({view:e.kind===`held`?{kind:`ready`}:e,messages:t,destination:this.#s,muted:this.#u,canDial:s(this.#s,this.#i,this.#r),showOutputDevice:this.#e?.media.supportsOutputSelection()===!0}):_({mode:this.#T()===`compact`?`compact`:`panel`,view:e,messages:t,destination:this.#s,muted:this.#u,canDial:s(this.#s,this.#i,this.#r),moreOpen:this.#d,floating:this.hasAttribute(`floating`),connected:this.#r===`connected`,agentStatus:this.#l,extension:this.#c,calls:this.#w()});default:return e}}#w(){let e=this.#e?.getActiveCall?.()?.id;return this.#e?.getCalls?.().map(t=>({id:t.id,destination:t.destination,state:t.state,direction:this.#o.has(t.id)?`inbound`:`outbound`,current:t.id===e}))??[]}#T(){let e=this.getAttribute(`mode`);return e===`compact`||e===`mobile`?e:`panel`}#E(){return this.#T()===`mobile`}#D(){let e=this.#e;e!==void 0&&(this.#n.push(e.on(`connection.stateChanged`,t=>{if(this.#r=t.state,t.state!==`connected`&&(this.#l=`offline`),t.state===`connected`){let t=e.getAgent?.()?.extension?.trim();t!==void 0&&t!==``&&(this.#c=t)}})),this.#n.push(e.on(`agent.statusChanged`,e=>{(e.status===`available`||e.status===`offline`||e.status===`break`)&&(this.#l=e.status)})),this.#n.push(e.on(`connection.failed`,e=>{this.#r=`failed`,this.#a={code:e.error.code}})),this.#n.push(e.on(`media.permissionChanged`,e=>{this.#i=e.permission})),this.#n.push(e.on(`error`,e=>{this.#a={code:e.error.code}})),this.#n.push(e.on(`call.incoming`,e=>{this.#o.add(e.callId)})),this.#n.push(e.on(`call.ended`,e=>{this.#o.delete(e.callId),this.#u=!1})),this.#n.push(e.on(`call.failed`,()=>{this.#_=this.#z().statusFailed})),U.forEach(t=>{this.#n.push(e.on(t,()=>this.render()))}),this.#E()&&typeof e.recover==`function`&&(this.#v=a(e,{onChecking:()=>{this.#g=this.#z().foregroundChecking,this.render()},onRecovered:()=>{this.#g=void 0,this.render()},onFailed:()=>{this.#g=this.#z().foregroundFailed,this.render()}})))}#O(){let e=this.#n;this.#n=[],e.forEach(e=>e()),this.#r=`idle`,this.#i=`unknown`,this.#l=`offline`,this.#a=void 0,this.#o.clear(),this.#u=!1,this.#d=!1,this.#m=!1,this.#h=!1,this.#g=void 0,this.#v?.(),this.#v=void 0}#k(){if(typeof this.attachShadow!=`function`)return;let e=this.shadowRoot??this.attachShadow({mode:`open`});return H.has(e)||(H.add(e),e.addEventListener(`click`,e=>this.#A(e)),e.addEventListener(`input`,e=>this.#P(e)),e.addEventListener(`pointerdown`,e=>this.#H(e))),e}#A(e){let t=J(e,this),n=t?.closest(`[data-action="enable-phone"]`);n instanceof HTMLButtonElement&&(n.disabled=!0),this.#f=this.#f.then(()=>this.#F(t)).catch(e=>{this.#_=Y(e),this.render()})}#j(){let e=this.shadowRoot?.querySelector(`input[name="destination"]`);return e instanceof HTMLInputElement?e.value:this.#s}#M(){let e=this.shadowRoot?.querySelector(`input[name="extension"]`);return e instanceof HTMLInputElement?e.value.trim():this.#c}#N(){let e=this.shadowRoot?.querySelector(`input[name="transfer-target"]`);return e instanceof HTMLInputElement?e.value:``}#P(e){let t=J(e,this);if(t instanceof HTMLInputElement&&t.name!==`transfer-target`){if(t.name===`extension`){this.#c=t.value.trim();return}this.#s=t.value,this.#L()}}async#F(e){if(this.#_=void 0,e===void 0)return;let t=e.closest(`[data-call-id]`);if(t instanceof HTMLElement&&t.dataset.callId!==void 0){await this.#e?.setActiveCall(t.dataset.callId);return}let n=e.closest(`[data-digit]`);if(n instanceof HTMLElement&&n.dataset.digit!==void 0){await this.#I(n.dataset.digit);return}let r=e.closest(`[data-action]`);if(!(r instanceof HTMLElement)||r instanceof HTMLButtonElement&&r.disabled&&r.getAttribute(`data-action`)!==`enable-phone`)return;let a=this.#e?.getActiveCall?.();switch(r.getAttribute(`data-action`)){case`signin`:if(this.#e===void 0)return;this.#c=this.#M(),await this.#e.media?.requestPermission?.(),await this.#e.initialize(),await this.#e.connect();return;case`signout`:if(this.#e===void 0)return;this.#l=`offline`,await this.#e.disconnect();return;case`dial`:case`dial-internal`:if(this.#s=this.#j(),this.#e===void 0)return;this.#i!==`granted`&&await this.#e.media?.requestPermission?.(),await c(this.#e,this.#s,r.getAttribute(`data-action`)===`dial-internal`?`extension`:void 0);return;case`mute`:if(a===void 0)return;this.#u=await l(a,this.#u),this.#R();return;case`hold`:a!==void 0&&await u(a);return;case`resume`:a!==void 0&&await a.resume();return;case`transfer`:a!==void 0&&await f(a,this.#N());return;case`hangup`:await a?.hangup();return;case`answer`:a!==void 0&&await this.#e?.answer(a.id);return;case`reject`:await a?.reject();return;case`enable-phone`:if(this.#e===void 0||this.#m)return;this.#h=!0;try{await i(this.#e),this.#m=!0}finally{this.#h=!1,this.render()}return;case`more`:this.#d=!this.#d,this.render();return;case`retry-permission`:await this.#e?.media.requestPermission();return;case`devices`:return;case`agent-available`:await this.#e?.setAgentStatus(`available`);return;case`agent-break`:await this.#e?.setAgentStatus(`break`);return;case`agent-busy`:return;default:return}}async#I(e){let t=this.#e?.getActiveCall?.();if(t!==void 0&&(t.state===`active`||t.state===`held`)){await d(t,e);return}this.#s+=e;let n=this.shadowRoot?.querySelector(`input[name="destination"]`);n instanceof HTMLInputElement&&(n.value=this.#s),this.#L()}#L(){let e=!s(this.#s,this.#i,this.#r);for(let t of[`dial`,`dial-internal`]){let n=this.shadowRoot?.querySelector(`[data-action="${t}"]`);n instanceof HTMLButtonElement&&(n.disabled=e)}}#R(){let e=this.shadowRoot?.querySelector(`[data-action="mute"]`);e instanceof HTMLButtonElement&&(e.setAttribute(`aria-pressed`,this.#u?`true`:`false`),e.textContent=this.#u?this.#z().unmute:this.#z().mute)}#z(){return r(this.getAttribute(`locale`)??`zh-CN`,void 0,this.#y)}#B(){this.#b?.(),this.#b=void 0;let e=this.getAttribute(`theme`)??`light`;if(e===`dark`||e===`light`){this.setAttribute(`data-theme`,e);return}if(typeof window>`u`||typeof window.matchMedia!=`function`){this.setAttribute(`data-theme`,`light`);return}let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>{this.setAttribute(`data-theme`,t.matches?`dark`:`light`)};n(),t.addEventListener(`change`,n),this.#b=()=>t.removeEventListener(`change`,n)}#V(){this.style.position=this.hasAttribute(`floating`)?`fixed`:``}#H(e){if(!(e instanceof PointerEvent)||!this.hasAttribute(`floating`)||!this.hasAttribute(`draggable`)||(e.target instanceof Element?e.target.closest(`[data-drag-handle]`):null)===null)return;e.preventDefault();let t=this.getBoundingClientRect();this.#p={pointerId:e.pointerId,offsetX:e.clientX-t.left,offsetY:e.clientY-t.top},window.addEventListener(`pointermove`,this.#U),window.addEventListener(`pointerup`,this.#W)}#U=e=>{if(this.#p===void 0||e.pointerId!==this.#p.pointerId)return;let t=window.visualViewport,n=t?.width??window.innerWidth,r=t?.height??window.innerHeight,i=q(e.clientX-this.#p.offsetX,0,Math.max(0,n-this.offsetWidth)),a=q(e.clientY-this.#p.offsetY,0,Math.max(0,r-this.offsetHeight));this.style.left=`${i}px`,this.style.top=`${a}px`,this.style.right=`auto`,this.style.bottom=`auto`};#W=e=>{this.#p!==void 0&&e.pointerId===this.#p.pointerId&&this.#G()};#G(){this.#p=void 0,window.removeEventListener(`pointermove`,this.#U),window.removeEventListener(`pointerup`,this.#W)}};function G(e={}){if(typeof customElements>`u`)return;let t=e.tagName??`xcall-ccbar`;if(customElements.get(t)!==void 0)return;let n=t===`xcall-ccbar`?W:class extends W{};customElements.define(t,n)}function K(e,t){switch(e.kind){case`unsupported`:return t.statusUnsupported;case`permission-error`:return t.statusPermission;case`unrecoverable-error`:return t.statusError;case`setup`:return t.statusSetup;case`connecting`:return t.statusConnecting;case`incoming`:return t.statusIncoming;case`active`:return t.statusActive;case`held`:return t.statusHeld;case`dialing`:return t.statusDialing;case`ended`:return t.statusEnded;case`ready`:return t.statusReady;default:return e}}function q(e,t,n){return Math.min(n,Math.max(t,e))}function J(e,t){for(let n of e.composedPath())if(n instanceof Element&&n!==t)return n;return e.target instanceof Element&&e.target!==t?e.target:void 0}function Y(e){return typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:`SDK_INTERNAL_ERROR`}var X=`0.1.0`;exports.XCallCCBarElement=W,exports.defineCCBarElement=G,exports.enUS=e,exports.resolveMessages=r,exports.uiVersion=X,exports.zhCN=t;
package/dist/ui/index.js CHANGED
@@ -888,7 +888,7 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
888
888
  switch (r.getAttribute("data-action")) {
889
889
  case "signin":
890
890
  if (this.#e === void 0) return;
891
- this.#c = this.#M(), await this.#e.media?.requestPermission?.(), await this.#e.initialize(), await this.#e.connect(this.#c === "" ? void 0 : { extension: this.#c });
891
+ this.#c = this.#M(), await this.#e.media?.requestPermission?.(), await this.#e.initialize(), await this.#e.connect();
892
892
  return;
893
893
  case "signout":
894
894
  if (this.#e === void 0) return;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "3.1.8";
1
+ export declare const SDK_VERSION = "3.1.9";