@creativeorange/azure-text-to-speech 1.1.2 → 1.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/co-azure-tts.es.js +1 -1
- package/dist/co-azure-tts.umd.js +1 -1
- package/package.json +1 -1
- package/src/main.ts +2 -1
package/dist/co-azure-tts.es.js
CHANGED
|
@@ -6051,7 +6051,7 @@ class TextToSpeech {
|
|
|
6051
6051
|
}
|
|
6052
6052
|
}
|
|
6053
6053
|
if (wordBoundary !== void 0) {
|
|
6054
|
-
if (~[".", ",", "!", "?", "*"].indexOf(wordBoundary.text)) {
|
|
6054
|
+
if (~[".", ",", "!", "?", "*", "(", ")", "&", "\\", "/", "^", "[", "]", "<", ">"].indexOf(wordBoundary.text)) {
|
|
6055
6055
|
wordBoundary = (_a = this.previousWordBoundary) != null ? _a : void 0;
|
|
6056
6056
|
}
|
|
6057
6057
|
if (wordBoundary === void 0) {
|
package/dist/co-azure-tts.umd.js
CHANGED
|
@@ -16,4 +16,4 @@ File System access not available, please use Push or PullAudioOutputStream`),thi
|
|
|
16
16
|
return true;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
registerProcessor('speech-processor', SP);`,c=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(c)}const a=()=>{const u=(()=>{let c=0;try{return e.createScriptProcessor(c,1,1)}catch{c=2048;let p=e.sampleRate;for(;c<16384&&p>=32e3;)c<<=1,p>>=1;return e.createScriptProcessor(c,1,1)}})();u.onaudioprocess=c=>{const h=c.inputBuffer.getChannelData(0);if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}};if(!!this.privSpeechProcessorScript&&!!e.audioWorklet)e.audioWorklet.addModule(this.privSpeechProcessorScript).then(()=>{const u=new AudioWorkletNode(e,"speech-processor");u.port.onmessage=c=>{const h=c.data;if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}}).catch(()=>{a()});else try{a()}catch(u){throw new Error(`Unable to start audio worklet node for PCMRecorder: ${u}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach(t=>t.stop()),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}var ve=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class b{constructor(e){e&&(this.privProxyInfo=e),b.privDiskCache||(b.privDiskCache=new z("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){b.privDiskCache=void 0,b.privMemCache={}}GetAgent(e){const t=new z.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const r="privProxyInfo";t[r]=this.privProxyInfo}return t}static GetProxyAgent(e){const t={host:e.HostName,port:e.Port};return e.UserName?t.headers={"Proxy-Authentication":"Basic "+new Buffer(`${e.UserName}:${e.Password===void 0?"":e.Password}`).toString("base64")}:t.headers={},t.headers.requestOCSP="true",new z(t)}static OCSPCheck(e,t){return ve(this,void 0,void 0,function*(){let r,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,c)=>{o.on("OCSPResponse",h=>{h&&(this.onEvent(new Jt),n=h)}),o.on("error",h=>{s||(s=!0,o.destroy(),c(h))}),a.on("secure",()=>ve(this,void 0,void 0,function*(){const h=a.getPeerCertificate(!0);try{const p=yield this.GetIssuer(h);r=(void 0)(h.raw,p.raw);const w=r.id.toString("hex");n||(n=yield b.GetResponseFromCache(w,r,t)),yield this.VerifyOCSPResponse(n,r,t),o.uncork(),s=!0,u(o)}catch(p){o.destroy(),s=!0,c(p)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,r)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){r(s);return}t(o)})})}static GetResponseFromCache(e,t,r){return ve(this,void 0,void 0,function*(){let n=b.privMemCache[e];if(n&&this.onEvent(new Wt(e)),!n)try{const s=yield b.privDiskCache.get(e);s.isCached&&(b.onEvent(new qt(e)),b.StoreMemoryCacheEntry(e,s.value),n=s.value)}catch{n=null}if(!n)return n;try{const a=(void 0)(n).value.tbsResponseData;if(a.responses.length<1){this.onEvent(new st(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,c=a.responses[0].nextUpdate;if(c<Date.now()+this.testTimeOffset-6e4)this.onEvent(new Qt(e,c)),n=null;else{const h=Math.min(864e5,(c-u)/2);c-(Date.now()+this.testTimeOffset)<h?(this.onEvent(new Xt(e,u,c)),this.UpdateCache(t,r).catch(p=>{this.onEvent(new ti(e,p.toString()))})):this.onEvent(new Zt(e,u,c))}}catch(s){this.onEvent(new st(e,s)),n=null}return n||this.onEvent(new Vt(e)),n})}static VerifyOCSPResponse(e,t,r){return ve(this,void 0,void 0,function*(){let n=e;return n||(n=yield b.GetOCSPResponse(t,r)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(b.onEvent(new Yt(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,r).then(()=>{s()},u=>{o(u)}):o(a)):(e||b.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return ve(this,void 0,void 0,function*(){const r=e.id.toString("hex");this.onEvent(new jt(r));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(r,n),this.onEvent(new Ft(e.id.toString("hex")))})}static StoreCacheEntry(e,t){this.StoreMemoryCacheEntry(e,t),this.StoreDiskCacheEntry(e,t)}static StoreMemoryCacheEntry(e,t){this.privMemCache[e]=t,this.onEvent(new $t(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Gt(e))})}static GetOCSPResponse(e,t){const r="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=b.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,r,(a,u)=>{if(a){o(a);return}const c=new URL(u);n=Object.assign(Object.assign({},n),{host:c.host,protocol:c.protocol,port:c.port,path:c.pathname,hostname:c.host}),(void 0)(n,e.data,(h,p)=>{if(h){o(h);return}const w=e.certID;this.onEvent(new ei(w.toString("hex"))),s(p)})})})}static onEvent(e){R.instance.onEvent(e)}CreateConnection(e,t){const r=typeof process!="undefined"&&{}.NODE_TLS_REJECT_UNAUTHORIZED!=="0"&&{}.SPEECH_CONDUCT_OCSP_CHECK!=="0"&&t.secureEndpoint;let n;if(t=Object.assign(Object.assign({},t),{requestOCSP:!b.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=b.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(c,h)=>{c?u(c):a(h)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return r?b.OCSPCheck(n,this.privProxyInfo):n}}b.testTimeOffset=0,b.forceDisableOCSPStapling=!1,b.privMemCache={};var Pt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ke{constructor(e,t,r,n,s,o){if(!e)throw new D("uri");if(!r)throw new D("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new H,this.privConnectionId=t,this.privMessageFormatter=r,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[y.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===M.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new k,this.privCertificateValidatedDeferral=new k,this.privConnectionState=M.Connecting;try{if(typeof WebSocket!="undefined"&&!ke.forceNpmWebSocket)this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);else{const e={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression};this.privCertificateValidatedDeferral.resolve();const t=new b(this.proxyInfo);e.agent=t.GetAgent();let n=new URL(this.privUri).protocol;(n==null?void 0:n.toLocaleLowerCase())==="wss:"?n="https:":(n==null?void 0:n.toLocaleLowerCase())==="ws:"&&(n="http:"),e.agent.protocol=n,this.privWebsocketClient=new z(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new he,this.privDisconnectDeferral=new k,this.privSendMessageQueue=new he,this.processSendQueue().catch(e=>{R.instance.onEvent(new ce(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new Be(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Bt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new Nt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new Be(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ot(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===M.Connecting?(this.privConnectionState=M.Disconnected,this.privConnectionEstablishDeferral.resolve(new Be(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new Lt(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{R.instance.onEvent(new ce(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const r=new k;if(this.privReceivingMessageQueue.enqueueFromPromise(r.promise),e.data instanceof ArrayBuffer){const n=new ge(g.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new ge(g.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==M.Connected)return Promise.reject(`Cannot send on connection that is in ${M[this.privConnectionState]} state`);const t=new k,r=new k;return this.privSendMessageQueue.enqueueFromPromise(r.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{r.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{r.reject(`Error formatting the message. ${n}`)}),t.promise}read(){return this.privConnectionState!==M.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==M.Disconnected&&this.privWebsocketClient.close(1e3,e||"Normal closure by client");else return Promise.resolve();return this.privDisconnectDeferral.promise}get events(){return this.privConnectionEvents}sendRawMessage(e){try{if(!e)return Promise.resolve();if(this.onEvent(new _t(this.privConnectionId,new Date().toISOString(),e.Message)),this.isWebsocketOpen)this.privWebsocketClient.send(e.RawWebsocketMessage.payload);else return Promise.reject("websocket send error: Websocket not ready "+this.privConnectionId+" "+e.Message.id+" "+new Error().stack);return Promise.resolve()}catch(t){return Promise.reject(`websocket send error: ${t}`)}}onClose(e,t){return Pt(this,void 0,void 0,function*(){const r=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},r),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(r)},r)})}processSendQueue(){return Pt(this,void 0,void 0,function*(){for(;;){const t=yield this.privSendMessageQueue.dequeue();if(!t)return;try{yield this.sendRawMessage(t),t.sendStatusDeferral.resolve()}catch(r){t.sendStatusDeferral.reject(r)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),R.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}ke.forceNpmWebSocket=!1;var Ri=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ki{constructor(e,t,r,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new D("uri");if(!n)throw new D("messageFormatter");this.privMessageFormatter=n;let u="",c=0;if(t){for(const h in t)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(t[h]);u+=`${h}=${p}`,c++}}if(r){for(const h in r)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(r[h]);u+=`${h}=${p}`,c++}}this.privUri=e+u,this.privId=a||E(),this.privConnectionMessageAdapter=new ke(this.privUri,this.id,this.privMessageFormatter,s,r,o)}dispose(){return Ri(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&(yield this.privConnectionMessageAdapter.close())})}isDisposed(){return this.privIsDisposed}get id(){return this.privId}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}class Xe{constructor(e,t,r,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=r,this.privProxyPassword=n}static fromParameters(e){return new Xe(e.getProperty(d.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(d.SpeechServiceConnection_ProxyPort),10),e.getProperty(d.SpeechServiceConnection_ProxyUserName),e.getProperty(d.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}const Di=new Set(["json","buffer","string"]);var Ii=i=>(...e)=>{const t=new Set;let r,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(r){const u=`Can't set method to ${a}, already set to ${r}.`;throw new Error(u)}else r=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Di.has(a))n=a;else throw new Error(`Unknown encoding, ${a}`);else if(typeof a=="number")t.add(a);else if(typeof a=="object")if(Array.isArray(a)||a instanceof Set)a.forEach(u=>t.add(u));else{if(s)throw new Error("Cannot set headers twice.");s=a}else throw new Error(`Unknown type: ${typeof a}`)}),r||(r="GET"),t.size===0&&t.add(200),i(t,r,n,s,o)};const zi=Ii;class Ze extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ze),this.name="StatusError",this.message=e.statusMessage,this.statusCode=e.status,this.res=e,this.json=e.json.bind(e),this.text=e.text.bind(e),this.arrayBuffer=e.arrayBuffer.bind(e);let r;Object.defineProperty(this,"responseBody",{get:()=>(r||(r=this.arrayBuffer()),r)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var xi=zi((i,e,t,r,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(r||(r={}),u.username&&(r.Authorization="Basic "+btoa(u.username+":"+u.password),u=new URL(u.protocol+"//"+u.host+u.pathname+u.search)),u.protocol!=="https:"&&u.protocol!=="http:")throw new Error(`Unknown protocol, ${u.protocol}`);if(o&&!(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="string"))if(typeof o=="object")o=JSON.stringify(o),r["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...r||{},...a});const c=await fetch(u,{method:e,headers:a,body:o});if(c.statusCode=c.status,!i.has(c.status))throw new Ze(c);return t==="json"?c.json():t==="buffer"?c.arrayBuffer():t==="string"?c.text():c}),Bi=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},$;(function(i){i.Get="GET",i.Post="POST",i.Delete="DELETE",i.File="file"})($||($={}));class Ni{constructor(e){if(!e)throw new D("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let r="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),c=a.join(": ");s[u]=c}),r=s[e.toLowerCase()]}catch{}return r}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,r={},n=null,s=null){const o=new k,a=e===$.File?"POST":e,u=(p,w={})=>{const x=p;return{data:JSON.stringify(w),headers:JSON.stringify(p.headers),json:w,ok:p.statusCode>=200&&p.statusCode<300,status:p.statusCode,statusText:w.error?w.error.message:x.statusText?x.statusText:x.statusMessage}},c=p=>{const w=new FileReader;return w.readAsArrayBuffer(p),new Promise(x=>{w.onloadend=()=>{x(w.result)}})},h=p=>{const w=xi(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),x=this.queryParams(r)===""?"":`?${this.queryParams(r)}`;w(x,p).then(G=>Bi(this,void 0,void 0,function*(){if(e===$.Delete||G.statusCode===204)o.resolve(u(G));else try{const Mt=yield G.json();o.resolve(u(G,Mt))}catch{o.resolve(u(G))}})).catch(G=>{o.reject(G)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===$.File&&s){const p="multipart/form-data";this.privHeaders["content-type"]=p,this.privHeaders["Content-Type"]=p,typeof Blob!="undefined"&&s instanceof Blob?c(s).then(w=>{h(w)}).catch(w=>{o.reject(w)}):h(s)}else e===$.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),h(n);return o.promise}withQuery(e,t={}){const r=this.queryParams(t);return r?e+(e.indexOf("?")===-1?"?":"&")+r:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Li{constructor(e,t,r){A(this,"key");A(this,"region");A(this,"voice");A(this,"textToRead","");A(this,"wordBoundryList",[]);A(this,"clickedNode");A(this,"highlightDiv");A(this,"speechConfig");A(this,"audioConfig");A(this,"player");A(this,"synthesizer");A(this,"previousWordBoundary");A(this,"interval");A(this,"wordEncounters",[]);A(this,"originalHighlightDivInnerHTML","");A(this,"currentWord","");A(this,"currentOffset",0);this.key=e,this.region=t,this.voice=r}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let r=0;r<t.length;r++){if(!t[r])continue;const n=t[r];n.attributes&&(n.attributes.getNamedItem("co-tts.id")?await this.handleIdModifier(n,n.attributes.getNamedItem("co-tts.id")):n.attributes.getNamedItem("co-tts.ajax")?await this.handleAjaxModifier(n,n.attributes.getNamedItem("co-tts.ajax")):n.attributes.getNamedItem("co-tts")?await this.handleDefault(n,n.attributes.getNamedItem("co-tts")):n.attributes.getNamedItem("co-tts.stop")?await this.handleStopModifier(n,n.attributes.getNamedItem("co-tts.stop")):n.attributes.getNamedItem("co-tts.resume")?await this.handleResumeModifier(n,n.attributes.getNamedItem("co-tts.resume")):n.attributes.getNamedItem("co-tts.pause")&&await this.handlePauseModifier(n,n.attributes.getNamedItem("co-tts.pause"))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleIdModifier(e,t){e.addEventListener("click",async r=>{var s;this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=document.getElementById(t.value);!n||(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerHTML,n.hasAttribute("co-tts.highlight")&&(this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML),this.startSynthesizer(e,t))})}async handleAjaxModifier(e,t){e.addEventListener("click",async r=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async r=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener("click",async r=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async r=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async r=>{await this.createInterval(),await this.player.resume(),document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))})}async stopPlayer(){await this.clearInterval(),this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.textToRead="",this.currentWord="",this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.wordEncounters=[],this.player!==void 0&&this.player.pause(),this.player=void 0,this.highlightDiv=void 0}async startSynthesizer(e,t){this.speechConfig=lt.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=f.Audio24Khz160KBitRateMonoMp3,this.player=new Ve,this.audioConfig=Q.fromSpeakerOutput(this.player),this.synthesizer=new Ee(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(r,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const r=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));r&&r.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(r,r.attributes.getNamedItem("co-tts.text")):r&&r.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.synthesizer.speakTextAsync(this.textToRead,()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 0})}async clearInterval(){clearInterval(this.interval)}async createInterval(){this.interval=setInterval(()=>{var e;if(this.player!==void 0&&this.highlightDiv){const t=this.player.currentTime;let r;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)r=n;else break;r!==void 0?(~[".",",","!","?","*"].indexOf(r.text)&&(r=(e=this.previousWordBoundary)!=null?e:void 0),r===void 0?this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML:(this.wordEncounters[r.text]||(this.wordEncounters[r.text]=0),this.currentWord!==r.text&&(this.wordEncounters[r.text]++,this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,r.text,this.wordEncounters[r.text]),this.currentWord=r.text),this.previousWordBoundary=r,this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset)+"<mark class='co-tts-highlight'>"+r.text+"</mark>"+this.originalHighlightDivInnerHTML.substring(this.currentOffset+r.wordLength))):this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,r){const n=new RegExp(`\\b${t}\\b`,"g");return e.split(n,r).join(t).length}}return Li});
|
|
19
|
+
registerProcessor('speech-processor', SP);`,c=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(c)}const a=()=>{const u=(()=>{let c=0;try{return e.createScriptProcessor(c,1,1)}catch{c=2048;let p=e.sampleRate;for(;c<16384&&p>=32e3;)c<<=1,p>>=1;return e.createScriptProcessor(c,1,1)}})();u.onaudioprocess=c=>{const h=c.inputBuffer.getChannelData(0);if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}};if(!!this.privSpeechProcessorScript&&!!e.audioWorklet)e.audioWorklet.addModule(this.privSpeechProcessorScript).then(()=>{const u=new AudioWorkletNode(e,"speech-processor");u.port.onmessage=c=>{const h=c.data;if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}}).catch(()=>{a()});else try{a()}catch(u){throw new Error(`Unable to start audio worklet node for PCMRecorder: ${u}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach(t=>t.stop()),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}var ve=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class b{constructor(e){e&&(this.privProxyInfo=e),b.privDiskCache||(b.privDiskCache=new z("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){b.privDiskCache=void 0,b.privMemCache={}}GetAgent(e){const t=new z.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const r="privProxyInfo";t[r]=this.privProxyInfo}return t}static GetProxyAgent(e){const t={host:e.HostName,port:e.Port};return e.UserName?t.headers={"Proxy-Authentication":"Basic "+new Buffer(`${e.UserName}:${e.Password===void 0?"":e.Password}`).toString("base64")}:t.headers={},t.headers.requestOCSP="true",new z(t)}static OCSPCheck(e,t){return ve(this,void 0,void 0,function*(){let r,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,c)=>{o.on("OCSPResponse",h=>{h&&(this.onEvent(new Jt),n=h)}),o.on("error",h=>{s||(s=!0,o.destroy(),c(h))}),a.on("secure",()=>ve(this,void 0,void 0,function*(){const h=a.getPeerCertificate(!0);try{const p=yield this.GetIssuer(h);r=(void 0)(h.raw,p.raw);const w=r.id.toString("hex");n||(n=yield b.GetResponseFromCache(w,r,t)),yield this.VerifyOCSPResponse(n,r,t),o.uncork(),s=!0,u(o)}catch(p){o.destroy(),s=!0,c(p)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,r)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){r(s);return}t(o)})})}static GetResponseFromCache(e,t,r){return ve(this,void 0,void 0,function*(){let n=b.privMemCache[e];if(n&&this.onEvent(new Wt(e)),!n)try{const s=yield b.privDiskCache.get(e);s.isCached&&(b.onEvent(new qt(e)),b.StoreMemoryCacheEntry(e,s.value),n=s.value)}catch{n=null}if(!n)return n;try{const a=(void 0)(n).value.tbsResponseData;if(a.responses.length<1){this.onEvent(new st(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,c=a.responses[0].nextUpdate;if(c<Date.now()+this.testTimeOffset-6e4)this.onEvent(new Qt(e,c)),n=null;else{const h=Math.min(864e5,(c-u)/2);c-(Date.now()+this.testTimeOffset)<h?(this.onEvent(new Xt(e,u,c)),this.UpdateCache(t,r).catch(p=>{this.onEvent(new ti(e,p.toString()))})):this.onEvent(new Zt(e,u,c))}}catch(s){this.onEvent(new st(e,s)),n=null}return n||this.onEvent(new Vt(e)),n})}static VerifyOCSPResponse(e,t,r){return ve(this,void 0,void 0,function*(){let n=e;return n||(n=yield b.GetOCSPResponse(t,r)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(b.onEvent(new Yt(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,r).then(()=>{s()},u=>{o(u)}):o(a)):(e||b.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return ve(this,void 0,void 0,function*(){const r=e.id.toString("hex");this.onEvent(new jt(r));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(r,n),this.onEvent(new Ft(e.id.toString("hex")))})}static StoreCacheEntry(e,t){this.StoreMemoryCacheEntry(e,t),this.StoreDiskCacheEntry(e,t)}static StoreMemoryCacheEntry(e,t){this.privMemCache[e]=t,this.onEvent(new $t(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Gt(e))})}static GetOCSPResponse(e,t){const r="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=b.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,r,(a,u)=>{if(a){o(a);return}const c=new URL(u);n=Object.assign(Object.assign({},n),{host:c.host,protocol:c.protocol,port:c.port,path:c.pathname,hostname:c.host}),(void 0)(n,e.data,(h,p)=>{if(h){o(h);return}const w=e.certID;this.onEvent(new ei(w.toString("hex"))),s(p)})})})}static onEvent(e){R.instance.onEvent(e)}CreateConnection(e,t){const r=typeof process!="undefined"&&{}.NODE_TLS_REJECT_UNAUTHORIZED!=="0"&&{}.SPEECH_CONDUCT_OCSP_CHECK!=="0"&&t.secureEndpoint;let n;if(t=Object.assign(Object.assign({},t),{requestOCSP:!b.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=b.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(c,h)=>{c?u(c):a(h)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return r?b.OCSPCheck(n,this.privProxyInfo):n}}b.testTimeOffset=0,b.forceDisableOCSPStapling=!1,b.privMemCache={};var Pt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ke{constructor(e,t,r,n,s,o){if(!e)throw new D("uri");if(!r)throw new D("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new H,this.privConnectionId=t,this.privMessageFormatter=r,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[y.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===M.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new k,this.privCertificateValidatedDeferral=new k,this.privConnectionState=M.Connecting;try{if(typeof WebSocket!="undefined"&&!ke.forceNpmWebSocket)this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);else{const e={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression};this.privCertificateValidatedDeferral.resolve();const t=new b(this.proxyInfo);e.agent=t.GetAgent();let n=new URL(this.privUri).protocol;(n==null?void 0:n.toLocaleLowerCase())==="wss:"?n="https:":(n==null?void 0:n.toLocaleLowerCase())==="ws:"&&(n="http:"),e.agent.protocol=n,this.privWebsocketClient=new z(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new he,this.privDisconnectDeferral=new k,this.privSendMessageQueue=new he,this.processSendQueue().catch(e=>{R.instance.onEvent(new ce(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new Be(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Bt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new Nt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new Be(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ot(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===M.Connecting?(this.privConnectionState=M.Disconnected,this.privConnectionEstablishDeferral.resolve(new Be(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new Lt(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{R.instance.onEvent(new ce(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const r=new k;if(this.privReceivingMessageQueue.enqueueFromPromise(r.promise),e.data instanceof ArrayBuffer){const n=new ge(g.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new ge(g.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==M.Connected)return Promise.reject(`Cannot send on connection that is in ${M[this.privConnectionState]} state`);const t=new k,r=new k;return this.privSendMessageQueue.enqueueFromPromise(r.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{r.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{r.reject(`Error formatting the message. ${n}`)}),t.promise}read(){return this.privConnectionState!==M.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==M.Disconnected&&this.privWebsocketClient.close(1e3,e||"Normal closure by client");else return Promise.resolve();return this.privDisconnectDeferral.promise}get events(){return this.privConnectionEvents}sendRawMessage(e){try{if(!e)return Promise.resolve();if(this.onEvent(new _t(this.privConnectionId,new Date().toISOString(),e.Message)),this.isWebsocketOpen)this.privWebsocketClient.send(e.RawWebsocketMessage.payload);else return Promise.reject("websocket send error: Websocket not ready "+this.privConnectionId+" "+e.Message.id+" "+new Error().stack);return Promise.resolve()}catch(t){return Promise.reject(`websocket send error: ${t}`)}}onClose(e,t){return Pt(this,void 0,void 0,function*(){const r=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},r),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(r)},r)})}processSendQueue(){return Pt(this,void 0,void 0,function*(){for(;;){const t=yield this.privSendMessageQueue.dequeue();if(!t)return;try{yield this.sendRawMessage(t),t.sendStatusDeferral.resolve()}catch(r){t.sendStatusDeferral.reject(r)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),R.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}ke.forceNpmWebSocket=!1;var Ri=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ki{constructor(e,t,r,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new D("uri");if(!n)throw new D("messageFormatter");this.privMessageFormatter=n;let u="",c=0;if(t){for(const h in t)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(t[h]);u+=`${h}=${p}`,c++}}if(r){for(const h in r)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(r[h]);u+=`${h}=${p}`,c++}}this.privUri=e+u,this.privId=a||E(),this.privConnectionMessageAdapter=new ke(this.privUri,this.id,this.privMessageFormatter,s,r,o)}dispose(){return Ri(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&(yield this.privConnectionMessageAdapter.close())})}isDisposed(){return this.privIsDisposed}get id(){return this.privId}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}class Xe{constructor(e,t,r,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=r,this.privProxyPassword=n}static fromParameters(e){return new Xe(e.getProperty(d.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(d.SpeechServiceConnection_ProxyPort),10),e.getProperty(d.SpeechServiceConnection_ProxyUserName),e.getProperty(d.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}const Di=new Set(["json","buffer","string"]);var Ii=i=>(...e)=>{const t=new Set;let r,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(r){const u=`Can't set method to ${a}, already set to ${r}.`;throw new Error(u)}else r=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Di.has(a))n=a;else throw new Error(`Unknown encoding, ${a}`);else if(typeof a=="number")t.add(a);else if(typeof a=="object")if(Array.isArray(a)||a instanceof Set)a.forEach(u=>t.add(u));else{if(s)throw new Error("Cannot set headers twice.");s=a}else throw new Error(`Unknown type: ${typeof a}`)}),r||(r="GET"),t.size===0&&t.add(200),i(t,r,n,s,o)};const zi=Ii;class Ze extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ze),this.name="StatusError",this.message=e.statusMessage,this.statusCode=e.status,this.res=e,this.json=e.json.bind(e),this.text=e.text.bind(e),this.arrayBuffer=e.arrayBuffer.bind(e);let r;Object.defineProperty(this,"responseBody",{get:()=>(r||(r=this.arrayBuffer()),r)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var xi=zi((i,e,t,r,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(r||(r={}),u.username&&(r.Authorization="Basic "+btoa(u.username+":"+u.password),u=new URL(u.protocol+"//"+u.host+u.pathname+u.search)),u.protocol!=="https:"&&u.protocol!=="http:")throw new Error(`Unknown protocol, ${u.protocol}`);if(o&&!(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="string"))if(typeof o=="object")o=JSON.stringify(o),r["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...r||{},...a});const c=await fetch(u,{method:e,headers:a,body:o});if(c.statusCode=c.status,!i.has(c.status))throw new Ze(c);return t==="json"?c.json():t==="buffer"?c.arrayBuffer():t==="string"?c.text():c}),Bi=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},$;(function(i){i.Get="GET",i.Post="POST",i.Delete="DELETE",i.File="file"})($||($={}));class Ni{constructor(e){if(!e)throw new D("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let r="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),c=a.join(": ");s[u]=c}),r=s[e.toLowerCase()]}catch{}return r}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,r={},n=null,s=null){const o=new k,a=e===$.File?"POST":e,u=(p,w={})=>{const x=p;return{data:JSON.stringify(w),headers:JSON.stringify(p.headers),json:w,ok:p.statusCode>=200&&p.statusCode<300,status:p.statusCode,statusText:w.error?w.error.message:x.statusText?x.statusText:x.statusMessage}},c=p=>{const w=new FileReader;return w.readAsArrayBuffer(p),new Promise(x=>{w.onloadend=()=>{x(w.result)}})},h=p=>{const w=xi(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),x=this.queryParams(r)===""?"":`?${this.queryParams(r)}`;w(x,p).then(G=>Bi(this,void 0,void 0,function*(){if(e===$.Delete||G.statusCode===204)o.resolve(u(G));else try{const Mt=yield G.json();o.resolve(u(G,Mt))}catch{o.resolve(u(G))}})).catch(G=>{o.reject(G)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===$.File&&s){const p="multipart/form-data";this.privHeaders["content-type"]=p,this.privHeaders["Content-Type"]=p,typeof Blob!="undefined"&&s instanceof Blob?c(s).then(w=>{h(w)}).catch(w=>{o.reject(w)}):h(s)}else e===$.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),h(n);return o.promise}withQuery(e,t={}){const r=this.queryParams(t);return r?e+(e.indexOf("?")===-1?"?":"&")+r:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Li{constructor(e,t,r){A(this,"key");A(this,"region");A(this,"voice");A(this,"textToRead","");A(this,"wordBoundryList",[]);A(this,"clickedNode");A(this,"highlightDiv");A(this,"speechConfig");A(this,"audioConfig");A(this,"player");A(this,"synthesizer");A(this,"previousWordBoundary");A(this,"interval");A(this,"wordEncounters",[]);A(this,"originalHighlightDivInnerHTML","");A(this,"currentWord","");A(this,"currentOffset",0);this.key=e,this.region=t,this.voice=r}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let r=0;r<t.length;r++){if(!t[r])continue;const n=t[r];n.attributes&&(n.attributes.getNamedItem("co-tts.id")?await this.handleIdModifier(n,n.attributes.getNamedItem("co-tts.id")):n.attributes.getNamedItem("co-tts.ajax")?await this.handleAjaxModifier(n,n.attributes.getNamedItem("co-tts.ajax")):n.attributes.getNamedItem("co-tts")?await this.handleDefault(n,n.attributes.getNamedItem("co-tts")):n.attributes.getNamedItem("co-tts.stop")?await this.handleStopModifier(n,n.attributes.getNamedItem("co-tts.stop")):n.attributes.getNamedItem("co-tts.resume")?await this.handleResumeModifier(n,n.attributes.getNamedItem("co-tts.resume")):n.attributes.getNamedItem("co-tts.pause")&&await this.handlePauseModifier(n,n.attributes.getNamedItem("co-tts.pause"))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleIdModifier(e,t){e.addEventListener("click",async r=>{var s;this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=document.getElementById(t.value);!n||(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerHTML,n.hasAttribute("co-tts.highlight")&&(this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML),this.startSynthesizer(e,t))})}async handleAjaxModifier(e,t){e.addEventListener("click",async r=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async r=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener("click",async r=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async r=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async r=>{await this.createInterval(),await this.player.resume(),document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))})}async stopPlayer(){await this.clearInterval(),this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.textToRead="",this.currentWord="",this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.wordEncounters=[],this.player!==void 0&&this.player.pause(),this.player=void 0,this.highlightDiv=void 0}async startSynthesizer(e,t){this.speechConfig=lt.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=f.Audio24Khz160KBitRateMonoMp3,this.player=new Ve,this.audioConfig=Q.fromSpeakerOutput(this.player),this.synthesizer=new Ee(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(r,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const r=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));r&&r.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(r,r.attributes.getNamedItem("co-tts.text")):r&&r.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.synthesizer.speakTextAsync(this.textToRead,()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 0})}async clearInterval(){clearInterval(this.interval)}async createInterval(){this.interval=setInterval(()=>{var e;if(this.player!==void 0&&this.highlightDiv){const t=this.player.currentTime;let r;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)r=n;else break;r!==void 0?(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">"].indexOf(r.text)&&(r=(e=this.previousWordBoundary)!=null?e:void 0),r===void 0?this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML:(this.wordEncounters[r.text]||(this.wordEncounters[r.text]=0),this.currentWord!==r.text&&(this.wordEncounters[r.text]++,this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,r.text,this.wordEncounters[r.text]),this.currentWord=r.text),this.previousWordBoundary=r,this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset)+"<mark class='co-tts-highlight'>"+r.text+"</mark>"+this.originalHighlightDivInnerHTML.substring(this.currentOffset+r.wordLength))):this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,r){const n=new RegExp(`\\b${t}\\b`,"g");return e.split(n,r).join(t).length}}return Li});
|
package/package.json
CHANGED
package/src/main.ts
CHANGED
|
@@ -255,7 +255,8 @@ export default class TextToSpeech {
|
|
|
255
255
|
}
|
|
256
256
|
|
|
257
257
|
if (wordBoundary !== undefined) {
|
|
258
|
-
if (~['.', ',', '!', '?', '*'
|
|
258
|
+
if (~['.', ',', '!', '?', '*', '(', ')', '&', '\\', '/', '^', '[', ']', '<', '>']
|
|
259
|
+
.indexOf(wordBoundary.text)) {
|
|
259
260
|
wordBoundary = this.previousWordBoundary ?? undefined;
|
|
260
261
|
}
|
|
261
262
|
|