@pyai/sdk 0.17.0 → 0.18.0

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,3 +1,4 @@
1
+ import { IncomingReceiver } from '/incoming.js';
1
2
  import { ManagedDialer, dialerCallHandedOff } from '/modules/managedDialer.js';
2
3
  import { IndexedDbDialerJournal, IndexedDbDialingQueueJournal } from '/modules/indexedDbJournal.js';
3
4
  import { VoiceSdkAudio } from '/modules/voiceSdkAudio.js';
@@ -10,15 +11,68 @@ import '/modules/meetingIntelligenceElement.js';
10
11
 
11
12
  const $=selector=>document.querySelector(selector),error=$('#error');
12
13
  const showError=value=>{error.textContent=value instanceof Error?value.message:String(value);};
13
- let config,dialer,queue,audio,closed=false,poll,audioGeneration=0;
14
+ let incoming,config,dialer,queue,audio,meetingRecorder,closed=false,poll,audioGeneration=0;
15
+ let presentation,appearanceInfo,appearanceLogo=null,appearanceSequence=0,lastAppearanceBinding,manifestUrl;
14
16
  let localSession=null,preparingClose=false;const meetingOperations=new Set();
15
17
  async function request(path,options={}){
16
18
  if(preparingClose&&options.method==='POST'&&(path==='/api/sessions'||path.startsWith('/api/meetings/')))throw Error('The app is preparing to close. Reopen the workspace to continue.');
17
19
  const operation=(async()=>{const response=await fetch(path,{...options,headers:{...(options.body?{'content-type':options.body instanceof Blob?options.body.type:'application/json'}:{}),...(localSession?{authorization:`Bearer ${localSession}`} :{}),...(config?{'x-pyai-local-session':config.nonce}:{}),...options.headers},cache:'no-store',signal:AbortSignal.timeout(20000)});
18
- const body=await response.json();if(!response.ok)throw Error(body?.error?.message??'This operation could not be confirmed.');return body;})();
20
+ const body=await response.json();if(!response.ok){const error=Error(body?.error?.message??'This operation could not be confirmed.');error.status=response.status;throw error;}return body;})();
19
21
  const tracked=path.startsWith('/api/meetings/')&&options.method==='POST';if(tracked)meetingOperations.add(operation);
20
22
  try{return await operation;}finally{if(tracked)meetingOperations.delete(operation);}
21
23
  }
24
+ function inkFor(color){const c=[1,3,5].map(i=>parseInt(color.slice(i,i+2),16)/255).map(v=>v<=.04045?v/12.92:((v+.055)/1.055)**2.4);return .2126*c[0]+.7152*c[1]+.0722*c[2]>.179?'#111827':'#FFFFFF';}
25
+ function applyFeatureVisibility(){
26
+ if(!config||!presentation)return;
27
+ const supported=appearanceInfo?.features_supported??{calls:!config.receive_only,incoming:true,meetings:!config.receive_only,power_queue:!config.receive_only};
28
+ const pending=Boolean(queue&&(queue.current.remaining||queue.current.activeIds.length)),callActive=Boolean(dialer&&dialer.current.state!=='idle');
29
+ const captureActive=Boolean(meetingRecorder&&['starting','recording','paused','stopping'].includes(meetingRecorder.current.state))||meetingOperations.size>0;
30
+ const visible={calls:supported.calls&&(presentation.features.calls||callActive||pending),incoming:supported.incoming&&(presentation.features.incoming||!!incoming?.credential),meetings:supported.meetings&&(presentation.features.meetings||captureActive)};
31
+ for(const [key,value] of Object.entries(visible))document.querySelector(`[data-tab="${key}"]`).hidden=!value;
32
+ $('nav').dataset.single=String(Object.values(visible).filter(Boolean).length<=1);
33
+ $('details.power-queue').hidden=!(supported.power_queue&&(presentation.features.power_queue||pending));
34
+ const selected=document.querySelector('nav button.selected');if(selected?.hidden){const next=[...document.querySelectorAll('nav [data-tab]')].find(x=>!x.hidden);if(next)next.click();}
35
+ const activeTab=document.querySelector('nav button.selected:not([hidden])')?.dataset.tab;for(const panel of document.querySelectorAll('[data-panel]'))panel.hidden=!visible[panel.dataset.panel]||panel.dataset.panel!==activeTab;
36
+ $('#sections-hidden').hidden=Object.values(visible).some(Boolean);
37
+ }
38
+ function applyAppearance(){
39
+ if(!presentation)return;const p=presentation,ink=inkFor(p.primary_color);
40
+ document.title=p.name;document.body.dataset.layout=p.layout;document.body.dataset.receiveOnly=String(config?.receive_only===true);
41
+ document.documentElement.style.setProperty('--accent',p.primary_color);document.documentElement.style.setProperty('--accent-ink',ink);
42
+ $('[data-brand]').textContent=p.name;$('.brand').setAttribute('aria-label',p.name);
43
+ const logo=$('.logo');logo.replaceChildren();if(p.logo_png){const image=document.createElement('img');image.src=p.logo_png;image.alt='';logo.append(image);}else logo.textContent=[...p.name][0]?.toUpperCase()??'P';
44
+ $('.aside-foot small').hidden=p.white_label;
45
+ $('footer').textContent=p.white_label?'Call history and recordings stay in your workspace. Meeting audio stays on this device until you save or send it.':'Call history and call recordings are stored in your PyAI workspace. Meeting audio stays on this device until you save or send it.';
46
+ $('pyai-dialer').setAppearance?.({name:p.name,accent:p.primary_color,showBranding:!p.white_label});
47
+ let icon=p.logo_png;
48
+ try{if(!icon){const canvas=document.createElement('canvas');canvas.width=canvas.height=512;const paint=canvas.getContext('2d');if(paint){paint.fillStyle=p.primary_color;paint.fillRect(0,0,512,512);paint.fillStyle=ink;paint.font='600 336px system-ui';paint.textAlign='center';paint.textBaseline='middle';paint.fillText([...p.name][0]?.toUpperCase()??'P',256,272);icon=canvas.toDataURL('image/png');}}}catch{/* Optional icon rendering never blocks calling. */}
49
+ icon??=new URL('/icon.svg',location.origin).href;document.querySelector('link[rel="icon"]').href=icon;document.querySelector('meta[name="theme-color"]').content=p.primary_color;
50
+ try{if(manifestUrl)URL.revokeObjectURL(manifestUrl);manifestUrl=URL.createObjectURL(new Blob([JSON.stringify({id:location.origin+'/',name:p.name,short_name:p.name.slice(0,24),start_url:location.origin+'/',scope:location.origin+'/',display:'standalone',theme_color:p.primary_color,background_color:'#FFFFFF',icons:[{src:icon,sizes:'any',type:icon.startsWith('data:image/png')?'image/png':'image/svg+xml'}]})],{type:'application/manifest+json'}));document.querySelector('link[rel="manifest"]').href=manifestUrl;}catch{/* Keep the ordinary app usable if this browser cannot install it. */}
51
+ $('#connection-help').textContent=`Open ${p.name} from the installed app or your terminal, then use its private launch link in this browser. A workspace connection cannot unlock another browser profile.`;
52
+ applyFeatureVisibility();
53
+ }
54
+ function fillAppearance(){
55
+ if(!presentation)return;$('#appearance-name').value=presentation.name;$('#appearance-color').value=presentation.primary_color;$('#appearance-layout').value=presentation.layout;$('#appearance-white-label').checked=presentation.white_label;appearanceLogo=presentation.logo_png;
56
+ for(const field of document.querySelectorAll('[data-appearance-feature]')){field.disabled=appearanceInfo?.features_supported?.[field.dataset.appearanceFeature]===false;field.checked=!field.disabled&&presentation.features[field.dataset.appearanceFeature];}
57
+ $('#appearance-context').textContent=appearanceInfo?.save_enabled?'Connected to your calling workspace. Appearance saves for this workspace only.':'Preview on this device. Connect a workspace to save its appearance.';
58
+ $('#appearance-save').textContent=appearanceInfo?.save_enabled?'Save for workspace':'Apply preview';
59
+ }
60
+ async function refreshAppearance(){
61
+ const sequence=++appearanceSequence;
62
+ try{const result=await request('/api/presentation');if(sequence!==appearanceSequence||closed)return;appearanceInfo=result;presentation=result.presentation;applyAppearance();fillAppearance();}catch{if(!presentation&&config?.presentation){presentation=config.presentation;applyAppearance();fillAppearance();}}
63
+ }
64
+ $('#appearance-toggle').addEventListener('click',()=>{$('#appearance-settings').hidden=!$('#appearance-settings').hidden;$('#appearance-toggle').setAttribute('aria-expanded',String(!$('#appearance-settings').hidden));if(!$('#appearance-settings').hidden){fillAppearance();$('#appearance-name').focus();}});
65
+ $('#appearance-close').addEventListener('click',()=>{$('#appearance-settings').hidden=true;$('#appearance-toggle').setAttribute('aria-expanded','false');$('#appearance-toggle').focus();});
66
+ $('#appearance-logo').addEventListener('change',()=>void act(async()=>{const file=$('#appearance-logo').files?.[0];if(!file)return;if(file.size>8192||file.type!=='image/png')throw Error('Choose a PNG logo up to 8 KB.');appearanceLogo=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=()=>reject(Error('The logo could not be read.'));reader.readAsDataURL(file);});$('#appearance-logo').value='';}));
67
+ $('#appearance-clear-logo').addEventListener('click',()=>{appearanceLogo=null;$('#appearance-logo').value='';$('#appearance-result').textContent='Initials will be used when you apply these changes.';});
68
+ $('#appearance-form').addEventListener('submit',event=>{event.preventDefault();void act(async()=>{
69
+ const features={};for(const field of document.querySelectorAll('[data-appearance-feature]'))features[field.dataset.appearanceFeature]=field.checked;
70
+ const draft={name:$('#appearance-name').value,primary_color:$('#appearance-color').value,layout:$('#appearance-layout').value,white_label:$('#appearance-white-label').checked,logo_png:appearanceLogo,features};
71
+ const save=appearanceInfo?.save_enabled===true;const result=await request(save?'/api/presentation':'/api/presentation/preview',{method:save?'PUT':'POST',body:JSON.stringify(save?{workspace_scope:appearanceInfo.workspace_scope,presentation:draft}:draft)});
72
+ appearanceInfo=result;presentation=result.presentation;applyAppearance();fillAppearance();$('#appearance-result').textContent=save?'Saved for this workspace.':'Preview applied. It will reset when the app closes or you connect a workspace.';
73
+ });});
74
+ window.addEventListener('pagehide',()=>{if(manifestUrl)URL.revokeObjectURL(manifestUrl);});
75
+
22
76
  let media;
23
77
  async function loadMedia(){
24
78
  if(window.Twilio?.Device)return;
@@ -26,8 +80,27 @@ async function loadMedia(){
26
80
  try{await media;}catch(e){media=null;throw e;}
27
81
  if(!window.Twilio?.Device)throw Error('Calling audio is unavailable.');
28
82
  }
83
+ function setupIncoming(){
84
+ const status=$('#incoming-status'),labels={offline:'Incoming calls are off.',enrolled:'Workspace connected. Enable incoming calls to register this device.',registering:'Registering incoming audio…',registered:'Registered. Confirming availability…',ringing:'Incoming call',answering:'Answering…',on_call:'On a call'};
85
+ incoming=new IncomingReceiver({request,createDevice:token=>new window.Twilio.Device(token,{logLevel:'silent'}),isBusy:()=>Boolean(dialer&&!['idle','wrapup','transferred','handing_off'].includes(dialer.current.state)),onChange:state=>{
86
+ status.dataset.phase=state.phase==='registered'&&state.available?'ready':state.phase;
87
+ status.textContent=state.error??(state.phase==='registered'&&state.available?'Ready for incoming calls.':labels[state.phase]);
88
+ $('#incoming-binding').textContent=state.binding?state.binding.label:'';
89
+ $('#incoming-enable').disabled=state.phase!=='enrolled'||!window.Twilio?.Device;$('#incoming-logout').disabled=state.phase==='offline';
90
+ const active=['ringing','answering','on_call'].includes(state.phase);$('#incoming-call').hidden=!active;$('#incoming-caller').textContent=state.caller??'';
91
+ $('#incoming-answer').disabled=state.phase!=='ringing';$('#incoming-reject').disabled=state.phase!=='ringing';$('#incoming-end').disabled=!['answering','on_call'].includes(state.phase);$('#incoming-mute').disabled=state.phase!=='on_call';$('#incoming-send').disabled=state.phase!=='on_call';renderQueue();
92
+ const binding=state.binding?`${state.binding.org_id}:${state.binding.project_id}`:null;if(config&&binding!==lastAppearanceBinding){lastAppearanceBinding=binding;void refreshAppearance();}
93
+ }});
94
+ $('#incoming-file').addEventListener('change',()=>void act(async()=>{const file=$('#incoming-file').files?.[0];if(file){if(file.size>16384)throw Error('Choose a desktop enrollment JSON file.');$('#incoming-handoff').value=await file.text();}$('#incoming-file').value='';}));
95
+ $('#incoming-enroll').addEventListener('click',()=>void act(async()=>{const raw=$('#incoming-handoff').value;$('#incoming-handoff').value='';let handoff;try{handoff=JSON.parse(raw);}catch{throw Error('Paste the desktop enrollment JSON from your workspace.');}await loadMedia();await incoming.enroll(handoff);}));
96
+ $('#incoming-enable').addEventListener('click',()=>void act(()=>incoming.register()));
97
+ $('#incoming-logout').addEventListener('click',()=>void act(()=>incoming.stop()));
98
+ $('#incoming-answer').addEventListener('click',()=>void act(()=>incoming.answer()));$('#incoming-reject').addEventListener('click',()=>void act(()=>incoming.reject()));$('#incoming-end').addEventListener('click',()=>void act(()=>incoming.hangup()));
99
+ let muted=false;$('#incoming-mute').addEventListener('click',()=>void act(()=>{muted=!muted;incoming.mute(muted);$('#incoming-mute').textContent=muted?'Unmute':'Mute';}));$('#incoming-send').addEventListener('click',()=>void act(()=>incoming.digits($('#incoming-digits').value)));
100
+ window.addEventListener('pagehide',()=>{void incoming.stop(false);void fetch('/api/incoming/presence',{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:JSON.stringify({ready:false}),keepalive:true}).catch(()=>{});});
101
+ }
29
102
  function renderQueue(){
30
- if(!queue)return;const state=queue.current,active=dialer.current.state!=='idle',saved=Boolean(state.remaining);
103
+ applyFeatureVisibility();if(!queue)return;const state=queue.current;if(state.remaining||state.activeIds.length)document.querySelector('details.power-queue').open=true;const active=dialer.current.state!=='idle'||Boolean(incoming?.call),saved=Boolean(state.remaining);
31
104
  $('#queue-start').disabled=active||state.running||Boolean(state.remaining)||!config.numbers.length;
32
105
  $('#queue-clear').disabled=active||state.running||!state.remaining;
33
106
  $('#parallel-choice').hidden=$('#mode').value!=='parallel';$('#parallel-lines').disabled=active||state.running||Boolean(state.remaining);
@@ -45,8 +118,13 @@ async function init(){
45
118
  try{localSession=localStorage.getItem('pyai-local-app-session');}catch{throw Error('Private app storage is unavailable. Enable storage for this local app before calling.');}
46
119
  const code=location.hash.slice(1);history.replaceState(null,'',location.pathname);
47
120
  if(code){const unlocked=await request('/api/unlock',{method:'POST',body:JSON.stringify({code})});localSession=unlocked.session_token;localStorage.setItem('pyai-local-app-session',localSession);}
48
- config=await request('/api/config');$('#transfer-choice').hidden=!config.transfers_enabled;document.title=config.name;$('[data-brand]').textContent=config.name;
49
- if(config.white_label){$('.logo').textContent=(config.name.match(/[A-Za-z]/)?.[0]??'P').toUpperCase();$('.aside-foot small').hidden=true;$('footer').textContent='Calls and call recordings stay in your workspace. Meeting audio stays in this browser until you save or submit it.';}
121
+ config=await request('/api/config');$('#connection-help').hidden=true;presentation=config.presentation;setupIncoming();await incoming.restore();if(incoming.credential){await loadMedia();incoming.publish({});}$('#transfer-choice').hidden=!config.transfers_enabled;await refreshAppearance();
122
+ if(config.receive_only){
123
+ for(const tab of document.querySelectorAll('[data-tab="calls"],[data-tab="meetings"]'))tab.hidden=true;
124
+ document.querySelector('[data-tab="incoming"]').click();
125
+ window.addEventListener('pyai-desktop-prepare-close',event=>{const requestId=event.detail?.requestId;if(typeof requestId==='string')void incoming.stop().then(()=>window.dispatchEvent(new CustomEvent('pyai-desktop-close-result',{detail:{requestId,ready:true,reason:'Incoming receiver disconnected.'}})));});
126
+ return;
127
+ }
50
128
  const source=$('#source');source.replaceChildren();
51
129
  for(const number of config.numbers){const option=document.createElement('option');option.value=number.id;option.textContent=number.phone_number;source.append(option);}
52
130
  if(!config.numbers.length){const option=document.createElement('option');option.textContent='No active voice numbers in this workspace';source.append(option);}
@@ -61,12 +139,13 @@ async function init(){
61
139
  await queue.restore();
62
140
  if(queue.current.remaining||queue.current.activeIds.length){$('#mode').value=queue.current.mode;$('#parallel-lines').value=String(queue.current.parallelLines);}
63
141
  $('pyai-dialer').bind(dialer,to=>{
142
+ if(incoming?.call)throw Error('Finish the incoming call before dialing.');
64
143
  if(!config.numbers.length)throw Error('Add a voice number in your PyAI workspace before calling.');
65
144
  const sourceNumber=config.numbers.find(n=>n.id===source.value);if(sourceNumber?.phone_number===to)throw Error('Choose a destination different from your calling number.');
66
145
  return inputFor(to);
67
146
  },{name:config.name,showBranding:!config.white_label},async()=>{await queue.finishWrapup();renderQueue();});
68
- dialer.subscribe(()=>renderQueue());renderQueue();
69
- const store=new IndexedDbMeetingRecordingStore(),recorder=new MeetingRecorder(config.scope,store);$('pyai-meeting-recorder').bind(recorder,store);
147
+ dialer.subscribe(()=>{incoming?.busyChanged();renderQueue();});renderQueue();
148
+ const store=new IndexedDbMeetingRecordingStore(),recorder=new MeetingRecorder(config.scope,store);meetingRecorder=recorder;recorder.subscribe(()=>applyFeatureVisibility());$('pyai-meeting-recorder').bind(recorder,store);
70
149
  $('pyai-meeting-intelligence').bind(config.scope,store,{availability:()=>request('/api/meetings/availability'),submit:(id,audio,notice)=>request(`/api/meetings/${encodeURIComponent(id)}`,{method:'POST',headers:{'x-pyai-meeting-notice':notice?'accepted':''},body:audio}),get:id=>request(`/api/meetings/${encodeURIComponent(id)}`),remove:id=>request(`/api/meetings/${encodeURIComponent(id)}/remove`,{method:'POST',body:'{}'})});
71
150
  $('#queue-start').addEventListener('click',()=>void act(async()=>{
72
151
  const contacts=$('#contacts').value.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map((line,index)=>{
@@ -82,7 +161,7 @@ async function init(){
82
161
  window.addEventListener('pyai-desktop-prepare-close',event=>{
83
162
  const requestId=event.detail?.requestId;if(typeof requestId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(requestId))return;
84
163
  closePreparation??=(async()=>{
85
- preparingClose=true;queue.pause();audio.disconnect();clearTimeout(poll);
164
+ preparingClose=true;await incoming?.stop();queue.pause();audio.disconnect();clearTimeout(poll);
86
165
  await recorder.stop();await Promise.allSettled([...meetingOperations]);
87
166
  // Never replay admission during close. An intent without a known call ID
88
167
  // remains recoverable under the same credential after the app reopens.
@@ -99,19 +178,20 @@ async function init(){
99
178
  closed=true;clearTimeout(poll);queue.pause();audio.disconnect();void recorder.stop();
100
179
  const id=dialer.current.callId;if(id&&!['idle','wrapup','transferred','handing_off'].includes(dialer.current.state)&&!dialerCallHandedOff(dialer.current.call??{}))void fetch(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:'{}',keepalive:true}).catch(()=>{});
101
180
  });
102
- void refresh();
181
+ applyAppearance();void refresh();
103
182
  }
104
183
  async function act(action){error.textContent='';try{await action();}catch(e){showError(e);renderQueue();}}
105
184
  for(const tab of document.querySelectorAll('[data-tab]'))tab.addEventListener('click',()=>{
106
185
  for(const button of document.querySelectorAll('[data-tab]'))button.classList.toggle('selected',button===tab);
107
186
  for(const panel of document.querySelectorAll('[data-panel]'))panel.hidden=panel.dataset.panel!==tab.dataset.tab;
108
- $('[data-heading]').textContent=tab.dataset.tab==='calls'?'Make the next connection.':'Be present. Keep the conversation.';
109
- $('[data-subtitle]').textContent=tab.dataset.tab==='calls'?'A clear line. A little less busywork.':'A private recording, on your terms.';
187
+ $('[data-heading]').textContent=tab.dataset.tab==='calls'?'Phone':tab.dataset.tab==='incoming'?'Incoming calls':'Meetings';
188
+ $('[data-subtitle]').textContent=tab.dataset.tab==='calls'?'A clear line. A little less busywork.':tab.dataset.tab==='incoming'?'Connect from your workspace. Answer when ready.':'A private recording, on your terms.';
110
189
  });
111
190
  async function connectWorkspace(){
112
191
  $('#retry').disabled=true;error.textContent='';
113
192
  try{await init();$('#retry').hidden=true;}
114
- catch(e){showError(e);$('#retry').hidden=false;$('#retry').disabled=false;}
193
+ catch(e){showError(e);if(e?.status===401&&!config){$('#connection-help').hidden=false;$('#connection-help').textContent=`Open ${presentation?.name??'PyAI Phone'} from the installed app or your terminal, then use its private launch link in this browser. A workspace connection cannot unlock another browser profile.`;}$('#retry').hidden=false;$('#retry').disabled=false;}
115
194
  }
116
195
  $('#retry').addEventListener('click',()=>void connectWorkspace());
196
+ try{presentation=JSON.parse(document.body.dataset.presentationDefaults);applyAppearance();fillAppearance();}catch{/* A private app launch still confirms actual backend configuration. */}
117
197
  void connectWorkspace();
@@ -0,0 +1,107 @@
1
+ /** Incoming-only SDK lifecycle. No project key, enrollment, presence or refresh
2
+ * capability is retained in this renderer. Registration is a user action. */
3
+ export class IncomingReceiver {
4
+ constructor({request,createDevice,onChange=()=>{},isBusy=()=>false,clock=()=>Date.now(),later=(fn,ms)=>globalThis.setTimeout(fn,ms),cancel=handle=>globalThis.clearTimeout(handle)}){
5
+ Object.assign(this,{request,createDevice,onChange,isBusy,clock,later,cancel});this.generation=0;this.state={phase:'offline',available:false};
6
+ }
7
+ publish(fields){this.state={...this.state,...fields};this.onChange({...this.state});}
8
+ async restore(){
9
+ const generation=this.generation;try{const credential=await this.request('/api/incoming/status',{method:'POST',body:'{}'});if(generation===this.generation){this.credential=credential;this.publish({phase:'enrolled',binding:credential.binding,available:false,error:null});if(credential.expires_at<=this.clock())await this.renew();}}catch(error){if(![401,403,410].includes(error.status))throw error;await this.stop();}
10
+ }
11
+ async enroll(handoff){
12
+ if(this.call)throw Error('Finish the incoming call before changing workspace.');
13
+ await this.stop();const generation=++this.generation;
14
+ const credential=await this.request('/api/incoming/enroll',{method:'POST',body:JSON.stringify(handoff)});
15
+ if(generation!==this.generation)return;
16
+ this.credential=credential;this.publish({phase:'enrolled',binding:credential.binding,available:false,error:null});
17
+ }
18
+ // Called directly from the Enable button: no network await before register().
19
+ async register(){
20
+ if(!this.credential)throw Error('Reconnect your workspace before enabling incoming calls.');
21
+ if(this.credential.session_expires_at<=this.clock()){await this.stop();throw Error('Reconnect your workspace before enabling incoming calls.');}
22
+ this.deviceFault=false;
23
+ if(this.credential.expires_at<=this.clock()){try{await this.renew();}catch(error){if([401,403,410].includes(error.status))await this.stop();throw Error('Incoming renewal could not be confirmed.');}return;}
24
+ if(this.device){if(this.device.state==='registered'){this.registered=true;this.publish({phase:'registered',error:null,error_code:null,error_phase:null});await this.beat();return;}this.publish({phase:'registering',available:false,error:null});if(this.device.state!=='registering')await this.device.register();return;}
25
+ const generation=this.generation,device=this.device=this.createDevice(this.credential.access_token),current=()=>generation===this.generation&&this.device===device;
26
+ device.on('registered',()=>{if(current()){this.registered=true;this.publish({phase:this.call?'on_call':this.deviceFault?'enrolled':'registered',...(!this.deviceFault?{error:null,error_code:null,error_phase:null}:{})});void this.beat();}});
27
+ device.on('unregistered',()=>{if(current()){this.registered=false;this.publish({phase:this.call?'on_call':'enrolled',available:false});void this.beat();}});
28
+ device.on('tokenWillExpire',()=>{if(current()&&!this.deviceFault)void this.renew().catch(error=>{if(!current())return;if([401,403,410].includes(error.status))void this.stop();else this.publish({error:'Incoming renewal could not be confirmed.',available:false});});});
29
+ device.on('incoming',call=>{if(current())this.incoming(call);else call.reject();});
30
+ device.on('error',error=>{if(current())this.deviceError(error);});
31
+ this.publish({phase:'registering',available:false});
32
+ try{await device.register();}catch(error){if(current())this.deviceError(error);throw Error(this.state.error??'Incoming registration could not be confirmed.');}
33
+ if(current())this.armExpiry();
34
+ }
35
+ deviceError(error){
36
+ // Retain only the SDK's numeric classification, never its message/URL/token.
37
+ const code=Number.isSafeInteger(error?.code)&&error.code>0&&error.code<=99999?error.code:null;
38
+ const generation=this.generation,expired=code===31205||code===20104; // SDK maps signaling 31205 to AccessTokenExpired (20104).
39
+ this.registered=false;this.deviceFault=!expired;
40
+ this.publish({phase:this.call?this.state.phase:'enrolled',available:false,error_code:code,error_phase:this.state.phase,
41
+ error:expired?'Incoming token expired; confirming renewal.':`Incoming calling is unavailable${code===null?'':` (code ${code})`}. Check the connection or reconnect your workspace.`});
42
+ if(!this.credential)return;
43
+ if(this.credential.session_expires_at<=this.clock()){void this.stop();return;}
44
+ if(expired){void this.renew().catch(error=>{if(generation!==this.generation)return;if([401,403,410].includes(error.status))void this.stop();else{this.publish({available:false,error:'Incoming renewal could not be confirmed.'});void this.beat();}});}
45
+ else{this.armExpiry();void this.beat();}
46
+ }
47
+ armExpiry(){
48
+ this.cancel(this.expiry);const generation=this.generation;
49
+ const until=this.deviceFault?this.credential.session_expires_at:Math.min(this.credential.expires_at,this.credential.session_expires_at);
50
+ this.expiry=this.later(()=>{if(generation!==this.generation)return;
51
+ if(this.credential.session_expires_at<=this.clock()){void this.stop();return;}
52
+ this.publish({available:false});
53
+ if(this.call){this.renewPending=true;void this.beat();this.expiry=this.later(()=>{if(generation===this.generation)void this.stop();},Math.max(0,this.credential.session_expires_at-this.clock()));}else void this.beat();
54
+ },Math.max(0,until-this.clock()));
55
+ }
56
+ async beat(){
57
+ if(this.beating)return;this.cancel(this.heartbeat);if(!this.credential)return;
58
+ // The existing call is owned by the SDK; an expired incoming grant cannot
59
+ // be refreshed mid-call or used as authority to tear that call down.
60
+ if(this.credential.session_expires_at<=this.clock()){await this.stop();return;}
61
+ if(this.deviceFault&&this.credential.expires_at<=this.clock()){this.publish({available:false});return;}
62
+ if(this.credential.expires_at<=this.clock()){
63
+ this.publish({available:false});if(this.call){this.renewPending=true;return;}
64
+ try{await this.renew();}catch(error){if([401,403,410].includes(error.status))await this.stop();else{this.publish({error:'Incoming renewal could not be confirmed.',available:false});const generation=this.generation;this.heartbeat=this.later(()=>{if(generation===this.generation)void this.beat();},15000);}}return;
65
+ }
66
+ this.beating=true;const generation=this.generation;
67
+ try{const ready=Boolean(this.registered&&!this.deviceFault&&!this.call&&!this.isBusy()&&this.credential.expires_at>this.clock()&&this.credential.session_expires_at>this.clock());const result=await this.request('/api/incoming/presence',{method:'POST',body:JSON.stringify({ready})});
68
+ if(generation===this.generation)this.publish({available:ready&&result.available===true});
69
+ }catch(error){if(generation===this.generation){this.publish({available:false,error:'Incoming availability could not be confirmed.'});if([401,403,410].includes(error.status)&&!(this.call&&this.credential?.expires_at<=this.clock()))void this.stop();}}
70
+ finally{this.beating=false;if(generation===this.generation&&this.credential)this.heartbeat=this.later(()=>void this.beat(),15000);}
71
+ }
72
+ async renew(){
73
+ if(this.deviceFault)return;
74
+ if(this.call){this.renewPending=true;return;}// Do not disrupt an active SDK call to update a token.
75
+ if(this.renewing)return this.renewing;
76
+ const generation=this.generation;
77
+ this.renewing=(async()=>{const credential=await this.request('/api/incoming/renew',{method:'POST',body:'{}'});
78
+ if(generation!==this.generation)return;
79
+ this.credential=credential;
80
+ if(this.deviceFault){this.armExpiry();return;}
81
+ if(this.device){this.device.updateToken(credential.access_token);if(this.device.state==='registered'){this.registered=true;this.publish({phase:'registered',error:null,error_code:null,error_phase:null});}else if(!this.registered&&this.device.state!=='registering')await this.device.register();}else this.publish({phase:'enrolled',available:false,error:null});
82
+ this.armExpiry();await this.beat();
83
+ })();try{await this.renewing;}finally{this.renewing=null;}
84
+ }
85
+ incoming(call){
86
+ if(this.call||this.isBusy()||this.deviceFault||!this.registered||this.credential?.expires_at<=this.clock()||this.credential?.session_expires_at<=this.clock()){call.reject();return;}
87
+ const generation=this.generation;this.call=call;this.publish({phase:'ringing',caller:String(call.parameters?.From??'Incoming call'),available:false});void this.beat();
88
+ const done=()=>{if(generation!==this.generation||this.call!==call)return;this.call=null;call.removeAllListeners?.();this.publish({phase:this.registered?'registered':'enrolled',caller:null});
89
+ if(this.renewPending||this.credential?.expires_at<=this.clock()){this.renewPending=false;void this.renew().catch(error=>{if([401,403,410].includes(error.status))void this.stop();else{this.publish({available:false,error:'Incoming renewal could not be confirmed.'});void this.beat();}});}else void this.beat();};
90
+ call.on('accept',()=>{if(generation===this.generation&&this.call===call)this.publish({phase:'on_call'});});
91
+ for(const event of ['cancel','reject','disconnect','error'])call.on(event,done);
92
+ }
93
+ answer(){if(!this.call||this.state.phase!=='ringing')throw Error('No incoming call is waiting.');this.publish({phase:'answering'});this.call.accept();}
94
+ reject(){if(this.call&&['ringing','answering'].includes(this.state.phase))this.call.reject();}
95
+ hangup(){if(this.call)this.call.disconnect();}
96
+ mute(value){if(this.call&&this.state.phase==='on_call')this.call.mute(value);}
97
+ digits(value){if(!/^[0-9*#]{1,32}$/.test(value))throw Error('Use keypad digits only.');if(this.call&&this.state.phase==='on_call')this.call.sendDigits(value);}
98
+ busyChanged(){void this.beat();}
99
+ async stop(server=true){
100
+ ++this.generation;this.cancel(this.heartbeat);this.cancel(this.expiry);
101
+ const device=this.device,call=this.call;this.device=null;this.call=null;this.credential=null;this.registered=false;this.renewPending=false;this.deviceFault=false;
102
+ call?.removeAllListeners?.();try{call?.disconnect();}catch{}
103
+ let unregister;try{unregister=device?.unregister();}catch{}finally{try{device?.destroy();}catch{}device?.removeAllListeners?.();}
104
+ this.publish({phase:'offline',available:false,caller:null,binding:null});
105
+ await Promise.allSettled([unregister,...(server?[this.request('/api/incoming/logout',{method:'POST',body:'{}'})]:[])]);
106
+ }
107
+ }