@microsoft/agents-copilotstudio-client 1.1.4-g8d884129e7 → 1.1.4-geb1c05c291

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/agents-copilotstudio-client",
3
- "version": "1.1.4-g8d884129e7",
3
+ "version": "1.1.4-geb1c05c291",
4
4
  "homepage": "https://github.com/microsoft/Agents-for-js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  "build:browser": "esbuild --platform=browser --target=es2019 --format=esm --bundle --sourcemap --minify --outfile=dist/src/browser.mjs src/index.ts"
28
28
  },
29
29
  "dependencies": {
30
- "@microsoft/agents-activity": "1.1.4-g8d884129e7",
30
+ "@microsoft/agents-activity": "1.1.4-geb1c05c291",
31
31
  "eventsource-client": "^1.2.0",
32
32
  "rxjs": "7.8.2",
33
33
  "uuid": "^11.1.0"
@@ -2,7 +2,7 @@ var Ss=Object.create;var co=Object.defineProperty;var As=Object.getOwnPropertyDe
2
2
  `;break;case"id":a=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?n(parseInt(S,10)):r(new rr(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:A}));break;default:r(new rr(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:S,line:A}));break}}function T(){d.length>0&&e({id:a,event:l||void 0,data:d.endsWith(`
3
3
  `)?d.slice(0,-1):d}),a=void 0,d="",l=""}function O(v={}){i&&v.consume&&m(i),s=!0,a=void 0,d="",l="",i=""}return{feed:f,reset:O}}function ks(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),i=t.indexOf(`
4
4
  `,n),s=-1;if(o!==-1&&i!==-1?s=Math.min(o,i):o!==-1?o===t.length-1?s=-1:s=o:i!==-1&&(s=i),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
5
- `&&n++}}return[e,r]}var lo="connecting",Es="open",Br="closed",nr=()=>{};function Us(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=nr,onConnect:i=nr,onDisconnect:s=nr,onScheduleReconnect:a=nr}=r,{fetch:d,url:l,initialLastEventId:f}=Rs(r),m={...r.headers},g=[],T=n?[n]:[],O=U=>T.forEach(se=>se(U)),v=uo({onEvent:Cs,onRetry:Is,onComment:o}),S,A=l.toString(),P=new AbortController,R=f,V=2e3,ie,$=Br;return Y(),{close:Se,connect:Y,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Vr,get lastEventId(){return R},get url(){return A},get readyState(){return $}};function Y(){S||($=lo,P=new AbortController,S=d(l,Ts()).then(ws).catch(U=>{S=null,!(U.name==="AbortError"||U.type==="aborted"||P.signal.aborted)&&io()}))}function Se(){$=Br,P.abort(),v.reset(),clearTimeout(ie),g.forEach(U=>U())}function Vr(){let U=[],se=[];function Et(){return new Promise(W=>{let ae=se.shift();ae?W({value:ae,done:!1}):U.push(W)})}let Xe=function(W){let ae=U.shift();ae?ae({value:W,done:!1}):se.push(W)};function Ae(){for(T.splice(T.indexOf(Xe),1);U.shift(););for(;se.shift(););}function Ut(){let W=U.shift();W&&(W({done:!0,value:void 0}),Ae())}return g.push(Ut),T.push(Xe),{next(){return $===Br?this.return():Et()},return(){return Ae(),Promise.resolve({done:!0,value:void 0})},throw(W){return Ae(),Promise.reject(W)},[Symbol.asyncIterator](){return this}}}function io(){a({delay:V}),!P.signal.aborted&&($=lo,ie=setTimeout(Y,V))}async function ws(U){i(),v.reset();let{body:se,redirected:Et,status:Xe}=U;if(Xe===204){s(),Se();return}if(!se)throw new Error("Missing response body");Et&&(A=U.url);let Ae=e(se),Ut=new TextDecoder,W=Ae.getReader(),ae=!0;$=Es;do{let{done:so,value:ao}=await W.read();ao&&v.feed(Ut.decode(ao,{stream:!so})),so&&(ae=!1,S=null,v.reset(),io(),s())}while(ae)}function Cs(U){typeof U.id=="string"&&(R=U.id),O(U)}function Is(U){V=U}function Ts(){let{mode:U,credentials:se,body:Et,method:Xe,redirect:Ae,referrer:Ut,referrerPolicy:W}=r,ae={Accept:"text/event-stream",...m,...R?{"Last-Event-ID":R}:void 0};return{mode:U,credentials:se,body:Et,method:Xe,redirect:Ae,referrer:Ut,referrerPolicy:W,headers:ae,cache:"no-store",signal:P.signal}}}function Rs(t){let e=t.fetch||globalThis.fetch;if(!Ms(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:r,initialLastEventId:n}=t;if(typeof r!="string"&&!(r instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:r,initialLastEventId:n}}function Ms(t){return typeof t=="function"}var Ns={getStream:Ds};function fo(t){return Us(t,Ns)}function Ds(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var _o=Rt(Dt());var ar=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{identifier:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var cr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var rt=(0,_o.debug)("copilot-studio:power-platform");function dr(t,e){var a,d,l,f,m,g;if((a=t.directConnectUrl)!=null&&a.trim()){if(rt.debug(`Using direct connection: ${t.directConnectUrl}`),!zt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return t.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(rt.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${t.directConnectUrl}`),dr({...t,directConnectUrl:""},e)):ta(t.directConnectUrl,e).href}let r=(d=t.cloud)!=null?d:"Prod",n=(l=t.copilotAgentType)!=null?l:"Published";if(rt.debug(`Using cloud setting: ${r}`),rt.debug(`Using agent type: ${n}`),!((f=t.environmentId)!=null&&f.trim()))throw new Error("EnvironmentId must be provided");if(!((m=t.agentIdentifier)!=null&&m.trim()))throw new Error("AgentIdentifier must be provided");if(r==="Other")if((g=t.customPowerPlatformCloud)!=null&&g.trim())if(zt(t.customPowerPlatformCloud))rt.debug(`Using custom Power Platform cloud: ${t.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let o=ra(r,t.environmentId,t.customPowerPlatformCloud),s={Published:()=>new cr({host:o,schema:t.agentIdentifier}),Prebuilt:()=>new ar({host:o,identifier:t.agentIdentifier})}[n]().getConversationUrl(e);return rt.debug(`Generated Copilot Studio connection URL: ${s}`),s}function bo(t,e="Unknown",r="",n=""){var o,i;if(!n&&!(t!=null&&t.directConnectUrl)){if(e==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!t&&e==="Unknown")throw new Error("Either settings or cloud must be provided");if(t&&t.cloud&&t.cloud!=="Unknown"&&(e=t.cloud),e==="Other")if(r&&zt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&zt(t.customPowerPlatformCloud))e="Other",r=t.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return r!=null||(r="api.unknown.powerplatform.com"),`https://${ur(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&zt(n)){if(go(new URL(n))==="Unknown"){let s=(i=t==null?void 0:t.cloud)!=null?i:e;if(s==="Other"||s==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(s!=="Unknown")return`https://${ur(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${ur(go(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function zt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function ta(t,e){let r=new URL(t);return r.searchParams.has("api-version")||r.searchParams.append("api-version","2022-03-01-preview"),r.pathname.endsWith("/")&&(r.pathname=r.pathname.slice(0,-1)),r.pathname.includes("/conversations")&&(r.pathname=r.pathname.substring(0,r.pathname.indexOf("/conversations"))),r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r}function ra(t,e,r){if(t==="Other"&&(!r||!r.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");r=r!=null?r:"api.unknown.powerplatform.com";let n=e.toLowerCase().replaceAll("-",""),o=na(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${ur(t,r)}`)}function ur(t,e){switch(t){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return e;default:throw new Error(`Invalid cluster category value: ${t}`)}}function na(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function go(t){switch(t.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var St=Rt(Wn());var Mr=class{constructor(e){this.activity=e}};var os=Rt(Dt());var rs="1.1.4-g8d884129e7";var Nr={};var G=(0,os.debug)("copilot-studio:client"),ve=class ve{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}async*postRequestAsync(e,r,n="POST"){var s,a,d,l,f,m,g,T,O,v;G.debug(`>>> SEND TO ${e}`);let o=new Map,i=fo({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":ve.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(S,A)=>{let P=await fetch(S,A);return this.processResponseHeaders(P.headers),P}});try{for await(let{data:S,event:A}of i){if(S&&A==="activity")try{let P=St.Activity.fromJson(S),R=(s=P.entities)==null?void 0:s.find(V=>V.type==="streaminfo"&&V.streamType==="streaming");switch(P.type){case St.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(d=(a=P.conversation)==null?void 0:a.id)!=null?d:"",G.debug(`Conversation ID: ${this.conversationId}`)),yield P;break;case St.ActivityTypes.Typing:if(G.debug(`Activity type: ${P.type}`),R||((l=P.channelData)==null?void 0:l.streamType)==="streaming"){let V=(f=P.text)!=null?f:"",ie=(g=R==null?void 0:R.streamId)!=null?g:(m=P.channelData)==null?void 0:m.streamId,$=(O=R==null?void 0:R.streamSequence)!=null?O:(T=P.channelData)==null?void 0:T.streamSequence;if(ie&&$){if(o.has(ie)){let Y=o.get(ie);Y.push({text:V,sequence:$}),o.set(ie,Y)}else o.set(ie,[{text:V,sequence:$}]);P.text=((v=o.get(ie))==null?void 0:v.sort((Y,Se)=>Y.sequence-Se.sequence).map(Y=>Y.text).join(""))||""}}yield P;break;default:G.debug(`Activity type: ${P.type}`),yield P;break}}catch(P){G.error("Failed to parse activity:",P)}else if(A==="end"){G.debug("Stream complete");break}if(i.readyState==="closed"){G.debug("Connection closed");break}}}finally{i.close()}}static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${rs}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Nr.platform()}-${Nr.arch()}/${Nr.release()}`,G.debug(`User-Agent: ${r}`),r}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(ve.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,G.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(ve.conversationIdHeaderKey))!=null?o:"",this.conversationId&&G.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==ve.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),G.debug("Headers received:",r)}async*startConversationStreaming(e=!0){let r=dr(this.settings),n={emitStartConversationEvent:e};G.info("Starting conversation ..."),yield*this.postRequestAsync(r,n,"POST")}async*sendActivityStreaming(e,r=this.conversationId){var s,a;let n=(a=(s=e.conversation)==null?void 0:s.id)!=null?a:r,o=dr(this.settings,n),i=new Mr(e);G.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}async startConversationAsync(e=!0){let r=[];for await(let n of this.startConversationStreaming(e))r.push(n);return r}async askQuestionAsync(e,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:e,conversation:o},s=St.Activity.fromObject(i),a=[];for await(let d of this.sendActivityStreaming(s,r))a.push(d);return a}async sendActivity(e,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(e,r))n.push(o);return n}};ve.conversationIdHeaderKey="x-ms-conversationid",ve.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",ve.scopeFromSettings=bo;var ns=ve;var N=[];for(let t=0;t<256;++t)N.push((t+256).toString(16).slice(1));function is(t,e=0){return(N[t[e+0]]+N[t[e+1]]+N[t[e+2]]+N[t[e+3]]+"-"+N[t[e+4]]+N[t[e+5]]+"-"+N[t[e+6]]+N[t[e+7]]+"-"+N[t[e+8]]+N[t[e+9]]+"-"+N[t[e+10]]+N[t[e+11]]+N[t[e+12]]+N[t[e+13]]+N[t[e+14]]+N[t[e+15]]).toLowerCase()}var Hn,Zd=new Uint8Array(16);function Bn(){if(!Hn){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Hn=crypto.getRandomValues.bind(crypto)}return Hn(Zd)}var jd=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Kn={randomUUID:jd};function kd(t,e,r){var o,i,s;if(Kn.randomUUID&&!e&&!t)return Kn.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:Bn();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[r+a]=n[a];return e}return is(n)}var Jn=kd;var bs=Rt(Wn());var Gn=function(t,e){return Gn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Gn(t,e)};function Te(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Gn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function er(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function At(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function Ot(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function te(t){return typeof t=="function"}function Dr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var zr=Dr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
5
+ `&&n++}}return[e,r]}var lo="connecting",Es="open",Br="closed",nr=()=>{};function Us(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=nr,onConnect:i=nr,onDisconnect:s=nr,onScheduleReconnect:a=nr}=r,{fetch:d,url:l,initialLastEventId:f}=Rs(r),m={...r.headers},g=[],T=n?[n]:[],O=U=>T.forEach(se=>se(U)),v=uo({onEvent:Cs,onRetry:Is,onComment:o}),S,A=l.toString(),P=new AbortController,R=f,V=2e3,ie,$=Br;return Y(),{close:Se,connect:Y,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Vr,get lastEventId(){return R},get url(){return A},get readyState(){return $}};function Y(){S||($=lo,P=new AbortController,S=d(l,Ts()).then(ws).catch(U=>{S=null,!(U.name==="AbortError"||U.type==="aborted"||P.signal.aborted)&&io()}))}function Se(){$=Br,P.abort(),v.reset(),clearTimeout(ie),g.forEach(U=>U())}function Vr(){let U=[],se=[];function Et(){return new Promise(W=>{let ae=se.shift();ae?W({value:ae,done:!1}):U.push(W)})}let Xe=function(W){let ae=U.shift();ae?ae({value:W,done:!1}):se.push(W)};function Ae(){for(T.splice(T.indexOf(Xe),1);U.shift(););for(;se.shift(););}function Ut(){let W=U.shift();W&&(W({done:!0,value:void 0}),Ae())}return g.push(Ut),T.push(Xe),{next(){return $===Br?this.return():Et()},return(){return Ae(),Promise.resolve({done:!0,value:void 0})},throw(W){return Ae(),Promise.reject(W)},[Symbol.asyncIterator](){return this}}}function io(){a({delay:V}),!P.signal.aborted&&($=lo,ie=setTimeout(Y,V))}async function ws(U){i(),v.reset();let{body:se,redirected:Et,status:Xe}=U;if(Xe===204){s(),Se();return}if(!se)throw new Error("Missing response body");Et&&(A=U.url);let Ae=e(se),Ut=new TextDecoder,W=Ae.getReader(),ae=!0;$=Es;do{let{done:so,value:ao}=await W.read();ao&&v.feed(Ut.decode(ao,{stream:!so})),so&&(ae=!1,S=null,v.reset(),io(),s())}while(ae)}function Cs(U){typeof U.id=="string"&&(R=U.id),O(U)}function Is(U){V=U}function Ts(){let{mode:U,credentials:se,body:Et,method:Xe,redirect:Ae,referrer:Ut,referrerPolicy:W}=r,ae={Accept:"text/event-stream",...m,...R?{"Last-Event-ID":R}:void 0};return{mode:U,credentials:se,body:Et,method:Xe,redirect:Ae,referrer:Ut,referrerPolicy:W,headers:ae,cache:"no-store",signal:P.signal}}}function Rs(t){let e=t.fetch||globalThis.fetch;if(!Ms(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:r,initialLastEventId:n}=t;if(typeof r!="string"&&!(r instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:r,initialLastEventId:n}}function Ms(t){return typeof t=="function"}var Ns={getStream:Ds};function fo(t){return Us(t,Ns)}function Ds(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var _o=Rt(Dt());var ar=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{identifier:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var cr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var rt=(0,_o.debug)("copilot-studio:power-platform");function dr(t,e){var a,d,l,f,m,g;if((a=t.directConnectUrl)!=null&&a.trim()){if(rt.debug(`Using direct connection: ${t.directConnectUrl}`),!zt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return t.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(rt.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${t.directConnectUrl}`),dr({...t,directConnectUrl:""},e)):ta(t.directConnectUrl,e).href}let r=(d=t.cloud)!=null?d:"Prod",n=(l=t.copilotAgentType)!=null?l:"Published";if(rt.debug(`Using cloud setting: ${r}`),rt.debug(`Using agent type: ${n}`),!((f=t.environmentId)!=null&&f.trim()))throw new Error("EnvironmentId must be provided");if(!((m=t.agentIdentifier)!=null&&m.trim()))throw new Error("AgentIdentifier must be provided");if(r==="Other")if((g=t.customPowerPlatformCloud)!=null&&g.trim())if(zt(t.customPowerPlatformCloud))rt.debug(`Using custom Power Platform cloud: ${t.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let o=ra(r,t.environmentId,t.customPowerPlatformCloud),s={Published:()=>new cr({host:o,schema:t.agentIdentifier}),Prebuilt:()=>new ar({host:o,identifier:t.agentIdentifier})}[n]().getConversationUrl(e);return rt.debug(`Generated Copilot Studio connection URL: ${s}`),s}function bo(t,e="Unknown",r="",n=""){var o,i;if(!n&&!(t!=null&&t.directConnectUrl)){if(e==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!t&&e==="Unknown")throw new Error("Either settings or cloud must be provided");if(t&&t.cloud&&t.cloud!=="Unknown"&&(e=t.cloud),e==="Other")if(r&&zt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&zt(t.customPowerPlatformCloud))e="Other",r=t.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return r!=null||(r="api.unknown.powerplatform.com"),`https://${ur(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&zt(n)){if(go(new URL(n))==="Unknown"){let s=(i=t==null?void 0:t.cloud)!=null?i:e;if(s==="Other"||s==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(s!=="Unknown")return`https://${ur(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${ur(go(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function zt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function ta(t,e){let r=new URL(t);return r.searchParams.has("api-version")||r.searchParams.append("api-version","2022-03-01-preview"),r.pathname.endsWith("/")&&(r.pathname=r.pathname.slice(0,-1)),r.pathname.includes("/conversations")&&(r.pathname=r.pathname.substring(0,r.pathname.indexOf("/conversations"))),r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r}function ra(t,e,r){if(t==="Other"&&(!r||!r.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");r=r!=null?r:"api.unknown.powerplatform.com";let n=e.toLowerCase().replaceAll("-",""),o=na(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${ur(t,r)}`)}function ur(t,e){switch(t){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return e;default:throw new Error(`Invalid cluster category value: ${t}`)}}function na(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function go(t){switch(t.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var St=Rt(Wn());var Mr=class{constructor(e){this.activity=e}};var os=Rt(Dt());var rs="1.1.4-geb1c05c291";var Nr={};var G=(0,os.debug)("copilot-studio:client"),ve=class ve{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}async*postRequestAsync(e,r,n="POST"){var s,a,d,l,f,m,g,T,O,v;G.debug(`>>> SEND TO ${e}`);let o=new Map,i=fo({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":ve.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(S,A)=>{let P=await fetch(S,A);return this.processResponseHeaders(P.headers),P}});try{for await(let{data:S,event:A}of i){if(S&&A==="activity")try{let P=St.Activity.fromJson(S),R=(s=P.entities)==null?void 0:s.find(V=>V.type==="streaminfo"&&V.streamType==="streaming");switch(P.type){case St.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(d=(a=P.conversation)==null?void 0:a.id)!=null?d:"",G.debug(`Conversation ID: ${this.conversationId}`)),yield P;break;case St.ActivityTypes.Typing:if(G.debug(`Activity type: ${P.type}`),R||((l=P.channelData)==null?void 0:l.streamType)==="streaming"){let V=(f=P.text)!=null?f:"",ie=(g=R==null?void 0:R.streamId)!=null?g:(m=P.channelData)==null?void 0:m.streamId,$=(O=R==null?void 0:R.streamSequence)!=null?O:(T=P.channelData)==null?void 0:T.streamSequence;if(ie&&$){if(o.has(ie)){let Y=o.get(ie);Y.push({text:V,sequence:$}),o.set(ie,Y)}else o.set(ie,[{text:V,sequence:$}]);P.text=((v=o.get(ie))==null?void 0:v.sort((Y,Se)=>Y.sequence-Se.sequence).map(Y=>Y.text).join(""))||""}}yield P;break;default:G.debug(`Activity type: ${P.type}`),yield P;break}}catch(P){G.error("Failed to parse activity:",P)}else if(A==="end"){G.debug("Stream complete");break}if(i.readyState==="closed"){G.debug("Connection closed");break}}}finally{i.close()}}static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${rs}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Nr.platform()}-${Nr.arch()}/${Nr.release()}`,G.debug(`User-Agent: ${r}`),r}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(ve.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,G.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(ve.conversationIdHeaderKey))!=null?o:"",this.conversationId&&G.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==ve.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),G.debug("Headers received:",r)}async*startConversationStreaming(e=!0){let r=dr(this.settings),n={emitStartConversationEvent:e};G.info("Starting conversation ..."),yield*this.postRequestAsync(r,n,"POST")}async*sendActivityStreaming(e,r=this.conversationId){var s,a;let n=(a=(s=e.conversation)==null?void 0:s.id)!=null?a:r,o=dr(this.settings,n),i=new Mr(e);G.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}async startConversationAsync(e=!0){let r=[];for await(let n of this.startConversationStreaming(e))r.push(n);return r}async askQuestionAsync(e,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:e,conversation:o},s=St.Activity.fromObject(i),a=[];for await(let d of this.sendActivityStreaming(s,r))a.push(d);return a}async sendActivity(e,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(e,r))n.push(o);return n}};ve.conversationIdHeaderKey="x-ms-conversationid",ve.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",ve.scopeFromSettings=bo;var ns=ve;var N=[];for(let t=0;t<256;++t)N.push((t+256).toString(16).slice(1));function is(t,e=0){return(N[t[e+0]]+N[t[e+1]]+N[t[e+2]]+N[t[e+3]]+"-"+N[t[e+4]]+N[t[e+5]]+"-"+N[t[e+6]]+N[t[e+7]]+"-"+N[t[e+8]]+N[t[e+9]]+"-"+N[t[e+10]]+N[t[e+11]]+N[t[e+12]]+N[t[e+13]]+N[t[e+14]]+N[t[e+15]]).toLowerCase()}var Hn,Zd=new Uint8Array(16);function Bn(){if(!Hn){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Hn=crypto.getRandomValues.bind(crypto)}return Hn(Zd)}var jd=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Kn={randomUUID:jd};function kd(t,e,r){var o,i,s;if(Kn.randomUUID&&!e&&!t)return Kn.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:Bn();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[r+a]=n[a];return e}return is(n)}var Jn=kd;var bs=Rt(Wn());var Gn=function(t,e){return Gn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Gn(t,e)};function Te(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Gn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function er(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function At(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function Ot(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function te(t){return typeof t=="function"}function Dr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var zr=Dr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
6
6
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
7
7
  `):"",this.name="UnsubscriptionError",this.errors=r}});function tr(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Pt=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=er(s),d=a.next();!d.done;d=a.next()){var l=d.value;l.remove(this)}}catch(v){e={error:v}}finally{try{d&&!d.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}else s.remove(this);var f=this.initialTeardown;if(te(f))try{f()}catch(v){i=v instanceof zr?v.errors:[v]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var g=er(m),T=g.next();!T.done;T=g.next()){var O=T.value;try{ss(O)}catch(v){i=i!=null?i:[],v instanceof zr?i=Ot(Ot([],At(i)),At(v.errors)):i.push(v)}}}catch(v){n={error:v}}finally{try{T&&!T.done&&(o=g.return)&&o.call(g)}finally{if(n)throw n.error}}}if(i)throw new zr(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)ss(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&tr(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&tr(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Yn=Pt.EMPTY;function Lr(t){return t instanceof Pt||t&&"closed"in t&&te(t.remove)&&te(t.add)&&te(t.unsubscribe)}function ss(t){te(t)?t():t.unsubscribe()}var oe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Zt={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=Zt.delegate;return o!=null&&o.setTimeout?o.setTimeout.apply(o,Ot([t,e],At(r))):setTimeout.apply(void 0,Ot([t,e],At(r)))},clearTimeout:function(t){var e=Zt.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function as(t){Zt.setTimeout(function(){var e=oe.onUnhandledError;if(e)e(t);else throw t})}function Xn(){}var cs=(function(){return Qn("C",void 0,void 0)})();function us(t){return Qn("E",void 0,t)}function ds(t){return Qn("N",t,void 0)}function Qn(t,e,r){return{kind:t,value:e,error:r}}var Ye=null;function jt(t){if(oe.useDeprecatedSynchronousErrorHandling){var e=!Ye;if(e&&(Ye={errorThrown:!1,error:null}),t(),e){var r=Ye,n=r.errorThrown,o=r.error;if(Ye=null,n)throw o}}else t()}function ls(t){oe.useDeprecatedSynchronousErrorHandling&&Ye&&(Ye.errorThrown=!0,Ye.error=t)}var ro=(function(t){Te(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Lr(r)&&r.add(n)):n.destination=Md,n}return e.create=function(r,n,o){return new Fr(r,n,o)},e.prototype.next=function(r){this.isStopped?to(ds(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?to(us(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?to(cs,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Pt);var Ed=Function.prototype.bind;function eo(t,e){return Ed.call(t,e)}var Ud=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){qr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){qr(n)}else qr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){qr(r)}},t})(),Fr=(function(t){Te(e,t);function e(r,n,o){var i=t.call(this)||this,s;if(te(r)||!r)s={next:r!=null?r:void 0,error:n!=null?n:void 0,complete:o!=null?o:void 0};else{var a;i&&oe.useDeprecatedNextContext?(a=Object.create(r),a.unsubscribe=function(){return i.unsubscribe()},s={next:r.next&&eo(r.next,a),error:r.error&&eo(r.error,a),complete:r.complete&&eo(r.complete,a)}):s=r}return i.destination=new Ud(s),i}return e})(ro);function qr(t){oe.useDeprecatedSynchronousErrorHandling?ls(t):as(t)}function Rd(t){throw t}function to(t,e){var r=oe.onStoppedNotification;r&&Zt.setTimeout(function(){return r(t,e)})}var Md={closed:!0,next:Xn,error:Rd,complete:Xn};var fs=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function ps(t){return t}function hs(t){return t.length===0?ps:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var kt=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,i=Dd(e)?e:new Fr(e,r,n);return jt(function(){var s=o,a=s.operator,d=s.source;i.add(a?a.call(i,d):d?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=ms(r),new r(function(o,i){var s=new Fr({next:function(a){try{e(a)}catch(d){i(d),s.unsubscribe()}},error:i,complete:o});n.subscribe(s)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[fs]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hs(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=ms(e),new e(function(n,o){var i;r.subscribe(function(s){return i=s},function(s){return o(s)},function(){return n(i)})})},t.create=function(e){return new t(e)},t})();function ms(t){var e;return(e=t!=null?t:oe.Promise)!==null&&e!==void 0?e:Promise}function Nd(t){return t&&te(t.next)&&te(t.error)&&te(t.complete)}function Dd(t){return t&&t instanceof ro||Nd(t)&&Lr(t)}var ys=Dr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var no=(function(t){Te(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new vs(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ys},e.prototype.next=function(r){var n=this;jt(function(){var o,i;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var s=er(n.currentObservers),a=s.next();!a.done;a=s.next()){var d=a.value;d.next(r)}}catch(l){o={error:l}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;jt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;jt(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?Yn:(this.currentObservers=null,a.push(r),new Pt(function(){n.currentObservers=null,tr(a,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,s=n.isStopped;o?r.error(i):s&&r.complete()},e.prototype.asObservable=function(){var r=new kt;return r.source=this,r},e.create=function(r,n){return new vs(r,n)},e})(kt);var vs=(function(t){Te(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Yn},e})(no);var oo=(function(t){Te(e,t);function e(r){var n=t.call(this)||this;return n._value=r,n}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(r){var n=t.prototype._subscribe.call(this,r);return!n.closed&&r.next(this._value),n},e.prototype.getValue=function(){var r=this,n=r.hasError,o=r.thrownError,i=r._value;if(n)throw o;return this._throwIfClosed(),i},e.prototype.next=function(r){t.prototype.next.call(this,this._value=r)},e})(no);var xs=Rt(Dt()),ge=(0,xs.debug)("copilot-studio:webchat"),gs=class{static createConnection(e,r){ge.info("--> Creating connection between Copilot Studio and WebChat ...");let n=0,o,i,s=new oo(0),a=_s(async f=>{o=f;let m=async()=>{s.next(2),await 0};if(ge.debug("--> Connection established."),l(),s.value<2)for await(let g of e.startConversationStreaming())delete g.replyToId,!i&&g.conversation&&(i=g.conversation,await m()),d(g)}),d=f=>{let m={...f,timestamp:new Date().toISOString(),channelData:{...f.channelData,"webchat:sequence-id":n}};n++,ge.debug(`Notify '${m.type}' activity to WebChat:`,m),o==null||o.next(m)},l=()=>{if(!(r!=null&&r.showTyping))return;let f=i?{id:i.id,name:i.name}:{id:"agent",name:"Agent"};d({type:"typing",from:f})};return{connectionStatus$:s,activity$:a,postActivity(f){if(ge.info("--> Preparing to send activity to Copilot Studio ..."),!f)throw new Error("Activity cannot be null.");if(!o)throw new Error("Activity subscriber is not initialized.");return _s(async m=>{try{ge.info("--> Sending activity to Copilot Studio ...");let g=bs.Activity.fromObject({...f,id:Jn(),attachments:await zd(f)});d(g),l(),m.next(g.id);for await(let T of e.sendActivityStreaming(g))d(T),ge.info("<-- Activity received correctly from Copilot Studio.");m.complete()}catch(g){ge.error("Error sending Activity to Copilot Studio:",g),m.error(g)}})},end(){ge.info("--> Ending connection between Copilot Studio and WebChat ..."),s.complete(),o&&(o.complete(),o=void 0)}}}};async function zd(t){var r;if(t.type!=="message"||!((r=t.attachments)!=null&&r.length))return t.attachments||[];let e=[];for(let n of t.attachments){let o=await Ld(n);e.push(o)}return e}async function Ld(t){let e=t.contentUrl;if(!(e!=null&&e.startsWith("blob:")))return t;try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch blob URL: ${r.status} ${r.statusText}`);let n=await r.blob(),o=await n.arrayBuffer(),i=qd(o);e=`data:${n.type};base64,${i}`}catch(r){e=t.contentUrl,ge.error("Error processing blob attachment:",e,r)}return{...t,contentUrl:e}}function qd(t){let e=typeof globalThis.Buffer=="function"?globalThis.Buffer:void 0;if(e&&typeof e.from=="function")return e.from(t).toString("base64");let r="";for(let n of new Uint8Array(t))r+=String.fromCharCode(n);return btoa(r)}function _s(t){return new kt(e=>{Promise.resolve(t(e)).catch(r=>e.error(r))})}export{Mt as AgentType,Wr as ConnectionSettings,ns as CopilotStudioClient,gs as CopilotStudioWebChat,Mr as ExecuteTurnRequest,Nt as PowerPlatformCloud,dr as getCopilotStudioConnectionUrl,bo as getTokenAudience,Bd as loadCopilotStudioConnectionSettingsFromEnv};
8
8
  //# sourceMappingURL=browser.mjs.map