@easbot/gateway-sdk 0.3.29 → 0.3.32
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/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +275 -205
- package/dist/index.d.ts +275 -205
- package/dist/index.mjs +6 -6
- package/package.json +2 -2
package/README.en.md
CHANGED
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var child_process=require('child_process');var
|
|
2
|
-
`);let
|
|
1
|
+
'use strict';var child_process=require('child_process');var me=Object.defineProperty;var be=(r,t,e)=>t in r?me(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e;var R=(r,t,e)=>be(r,typeof t!="symbol"?t+"":t,e);function ne({onRequest:r,onSseError:t,onSseEvent:e,responseTransformer:n,responseValidator:i,sseDefaultRetryDelay:l,sseMaxRetryAttempts:o,sseMaxRetryDelay:a,sseSleepFn:s,url:c,...p}){let u,g=s??(d=>new Promise(y=>setTimeout(y,d)));return {stream:async function*(){let d=l??3e3,y=0,w=p.signal??new AbortController().signal;for(;!w.aborted;){y++;let C=p.headers instanceof Headers?p.headers:new Headers(p.headers);u!==void 0&&C.set("Last-Event-ID",u);try{let x={redirect:"follow",...p,body:p.serializedBody,headers:C,signal:w},G=new Request(c,x);r&&(G=await r(c,x));let m=await(p.fetch??globalThis.fetch)(G);if(!m.ok)throw new Error(`SSE failed: ${m.status} ${m.statusText}`);if(!m.body)throw new Error("No body in SSE response");let O=m.body.pipeThrough(new TextDecoderStream).getReader(),S="",Y=()=>{try{O.cancel();}catch{}};w.addEventListener("abort",Y);try{for(;;){let{done:fe,value:he}=await O.read();if(fe)break;S+=he,S=S.replace(/\r\n?/g,`
|
|
2
|
+
`);let Z=S.split(`
|
|
3
3
|
|
|
4
|
-
`);S=
|
|
5
|
-
`),
|
|
6
|
-
`);try{E=JSON.parse(x),K=!0;}catch{E=x;}}K&&(a&&await a(E),n&&(E=await n(E))),t?.({data:E,event:W,id:u,retry:y}),z.length&&(yield E);}}}finally{m.removeEventListener("abort",J),O.releaseLock();}break}catch(w){if(e?.(w),o!==void 0&&d>=o)break;let k=Math.min(y*2**(d-1),i??3e4);await g(k);}}}()}}var fe=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},he=r=>{switch(r){case "form":return ",";case "pipeDelimited":return "|";case "spaceDelimited":return "%20";default:return ","}},ge=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},P=({allowReserved:r,explode:e,name:t,style:n,value:a})=>{if(!e){let i=(r?a:a.map(s=>encodeURIComponent(s))).join(he(n));switch(n){case "label":return `.${i}`;case "matrix":return `;${t}=${i}`;case "simple":return i;default:return `${t}=${i}`}}let l=fe(n),o=a.map(i=>n==="label"||n==="simple"?r?i:encodeURIComponent(i):I({allowReserved:r,name:t,value:i})).join(l);return n==="label"||n==="matrix"?l+o:o},I=({allowReserved:r,name:e,value:t})=>{if(t==null)return "";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return `${e}=${r?t:encodeURIComponent(t)}`},j=({allowReserved:r,explode:e,name:t,style:n,value:a,valueOnly:l})=>{if(a instanceof Date)return l?a.toISOString():`${t}=${a.toISOString()}`;if(n!=="deepObject"&&!e){let s=[];Object.entries(a).forEach(([p,u])=>{s=[...s,p,r?u:encodeURIComponent(u)];});let c=s.join(",");switch(n){case "form":return `${t}=${c}`;case "label":return `.${c}`;case "matrix":return `;${t}=${c}`;default:return c}}let o=ge(n),i=Object.entries(a).map(([s,c])=>I({allowReserved:r,name:n==="deepObject"?`${t}[${s}]`:s,value:c})).join(o);return n==="label"||n==="matrix"?o+i:i};var me=/\{[^{}]+\}/g,Re=({path:r,url:e})=>{let t=e,n=e.match(me);if(n)for(let a of n){let l=false,o=a.substring(1,a.length-1),i="simple";o.endsWith("*")&&(l=true,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),i="label"):o.startsWith(";")&&(o=o.substring(1),i="matrix");let s=r[o];if(s==null)continue;if(Array.isArray(s)){t=t.replace(a,P({explode:l,name:o,style:i,value:s}));continue}if(typeof s=="object"){t=t.replace(a,j({explode:l,name:o,style:i,value:s,valueOnly:true}));continue}if(i==="matrix"){t=t.replace(a,`;${I({name:o,value:s})}`);continue}let c=encodeURIComponent(i==="label"?`.${s}`:s);t=t.replace(a,c);}return t},Y=({baseUrl:r,path:e,query:t,querySerializer:n,url:a})=>{let l=a.startsWith("/")?a:`/${a}`,o=(r??"")+l;e&&(o=Re({path:e,url:o}));let i=t?n(t):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o};function B(r){let e=r.body!==void 0;if(e&&r.bodySerializer)return "serializedBody"in r?r.serializedBody!==void 0&&r.serializedBody!==""?r.serializedBody:null:r.body!==""?r.body:null;if(e)return r.body}var Z=async(r,e)=>{let t=typeof e=="function"?await e(r):e;if(t)return r.scheme==="bearer"?`Bearer ${t}`:r.scheme==="basic"?`Basic ${btoa(t)}`:t};var $={bodySerializer:r=>JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString():t)};var ee=({parameters:r={},...e}={})=>n=>{let a=[];if(n&&typeof n=="object")for(let l in n){let o=n[l];if(o==null)continue;let i=r[l]||e;if(Array.isArray(o)){let s=P({allowReserved:i.allowReserved,explode:true,name:l,style:"form",value:o,...i.array});s&&a.push(s);}else if(typeof o=="object"){let s=j({allowReserved:i.allowReserved,explode:true,name:l,style:"deepObject",value:o,...i.object});s&&a.push(s);}else {let s=I({allowReserved:i.allowReserved,name:l,value:o});s&&a.push(s);}}return a.join("&")},te=r=>{if(!r)return "stream";let e=r.split(";")[0]?.trim();if(e){if(e.startsWith("application/json")||e.endsWith("+json"))return "json";if(e==="multipart/form-data")return "formData";if(["application/","audio/","image/","video/"].some(t=>e.startsWith(t)))return "blob";if(e.startsWith("text/"))return "text"}},be=(r,e)=>e?!!(r.headers.has(e)||r.query?.[e]||r.headers.get("Cookie")?.includes(`${e}=`)):false;async function re(r){for(let e of r.security??[]){if(be(r,e.name))continue;let t=await Z(e,r.auth);if(!t)continue;let n=e.name??"Authorization";switch(e.in){case "query":r.query||(r.query={}),r.query[n]=t;break;case "cookie":r.headers.append("Cookie",`${n}=${t}`);break;default:r.headers.set(n,t);break}}}var H=r=>Y({baseUrl:r.baseUrl,path:r.path,query:r.query,querySerializer:typeof r.querySerializer=="function"?r.querySerializer:ee(r.querySerializer),url:r.url}),F=(r,e)=>{let t={...r,...e};return t.baseUrl?.endsWith("/")&&(t.baseUrl=t.baseUrl.substring(0,t.baseUrl.length-1)),t.headers=M(r.headers,e.headers),t},Se=r=>{let e=[];return r.forEach((t,n)=>{e.push([n,t]);}),e},M=(...r)=>{let e=new Headers;for(let t of r){if(!t)continue;let n=t instanceof Headers?Se(t):Object.entries(t);for(let[a,l]of n)if(l===null)e.delete(a);else if(Array.isArray(l))for(let o of l)e.append(a,o);else l!==void 0&&e.set(a,typeof l=="object"?JSON.stringify(l):l);}return e},D=class{constructor(){q(this,"fns",[]);}clear(){this.fns=[];}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null);}exists(e){let t=this.getInterceptorIndex(e);return !!this.fns[t]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):false}use(e){return this.fns.push(e),this.fns.length-1}},ne=()=>({error:new D,request:new D,response:new D}),we=ee({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}}),Oe={"Content-Type":"application/json"},v=(r={})=>({...$,headers:Oe,parseAs:"auto",querySerializer:we,...r});var A=(r={})=>{let e=F(v(),r),t=()=>({...e}),n=p=>(e=F(e,p),t()),a=ne(),l=async p=>{let u={...e,...p,fetch:p.fetch??e.fetch??globalThis.fetch,headers:M(e.headers,p.headers),serializedBody:void 0};u.security&&await re(u),u.requestValidator&&await u.requestValidator(u),u.body!==void 0&&u.bodySerializer&&(u.serializedBody=u.bodySerializer(u.body)),(u.body===void 0||u.serializedBody==="")&&u.headers.delete("Content-Type");let g=u,f=H(g);return {opts:g,url:f}},o=async p=>{let u=p.throwOnError??e.throwOnError,g=p.responseStyle??e.responseStyle,f,h;try{let{opts:y,url:d}=await l(p),m={redirect:"follow",...y,body:B(y)};f=new Request(d,m);for(let R of a.request.fns)R&&(f=await R(f,y));let T=y.fetch;h=await T(f);for(let R of a.response.fns)R&&(h=await R(h,f,y));let w={request:f,response:h};if(h.ok){let R=(y.parseAs==="auto"?te(h.headers.get("Content-Type")):y.parseAs)??"json";if(h.status===204||h.headers.get("Content-Length")==="0"){let S;switch(R){case "arrayBuffer":case "blob":case "text":S=await h[R]();break;case "formData":S=new FormData;break;case "stream":S=h.body;break;default:S={};break}return y.responseStyle==="data"?S:{data:S,...w}}let O;switch(R){case "arrayBuffer":case "blob":case "formData":case "text":O=await h[R]();break;case "json":{let S=await h.text();O=S?JSON.parse(S):{};break}case "stream":return y.responseStyle==="data"?h.body:{data:h.body,...w}}return R==="json"&&(y.responseValidator&&await y.responseValidator(O),y.responseTransformer&&(O=await y.responseTransformer(O))),y.responseStyle==="data"?O:{data:O,...w}}let k=await h.text(),G;try{G=JSON.parse(k);}catch{}throw G??k}catch(y){let d=y;for(let m of a.error.fns)m&&(d=await m(d,h,f,p));if(d=d||{},u)throw d;return g==="data"?void 0:{error:d,request:f,response:h}}},i=p=>u=>o({...u,method:p}),s=p=>async u=>{let{opts:g,url:f}=await l(u);return X({...g,body:g.body,method:p,onRequest:async(h,y)=>{let d=new Request(h,y);for(let m of a.request.fns)m&&(d=await m(d,g));return d},serializedBody:B(g),url:f})};return {buildUrl:p=>H({...e,...p}),connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:t,head:i("HEAD"),interceptors:a,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:o,setConfig:n,sse:{connect:s("CONNECT"),delete:s("DELETE"),get:s("GET"),head:s("HEAD"),options:s("OPTIONS"),patch:s("PATCH"),post:s("POST"),put:s("PUT"),trace:s("TRACE")},trace:i("TRACE")}};var xe={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},Te=Object.entries(xe);function se(r,e){e||(e=new Map);for(let t of r)"in"in t?t.key&&e.set(t.key,{in:t.in,map:t.map}):"key"in t?e.set(t.key,{map:t.map}):t.args&&se(t.args,e);return e}function Ce(r){for(let[e,t]of Object.entries(r))e!=="body"&&t&&typeof t=="object"&&!Array.isArray(t)&&!Object.keys(t).length&&delete r[e];}function C(r,e){let t={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},n=se(e);function a(o,i,s){let c=t[o];c===void 0&&(c=Object.create(null),t[o]=c),c[i]=s;}let l;for(let[o,i]of r.entries())if(e[o]&&(l=e[o]),!!l)if("in"in l)if(l.key){let s=n.get(l.key),c=s.map||l.key;s.in&&a(s.in,c,i);}else t.body=i;else for(let[s,c]of Object.entries(i??{})){let p=n.get(s);if(p)if(p.in){let u=p.map||s;a(p.in,u,c);}else t[p.map]=c;else {let u=Te.find(([g])=>s.startsWith(g));if(u){let[g,f]=u;a(f,s.slice(g.length),c);}else if("allowExtra"in l&&l.allowExtra){for(let[g,f]of Object.entries(l.allowExtra))if(f){a(g,s,c);break}}}}return Ce(t),t}var oe=A(v({baseUrl:"http://localhost:8080"}));var N=class{constructor(e){q(this,"client");this.client=e?.client??oe;}},V=class{constructor(){q(this,"defaultKey","default");q(this,"instances",new Map);}get(e){let t=this.instances.get(e??this.defaultKey);if(!t)throw new Error('No SDK client found. Create one with "new EasbotGatewayClient()" to fix this error.');return t}set(e,t){this.instances.set(t??this.defaultKey,e);}},L=class L extends N{constructor(e){super(e),L.__registry.set(this,e?.key);}healthCheck(e){return (e?.client??this.client).get({url:"/health",...e})}getStatus(e){return (e?.client??this.client).get({url:"/status",...e})}listChannels(e){return (e?.client??this.client).get({url:"/channels",...e})}listContacts(e,t){let n=C([e],[{args:[{in:"query",key:"platform"},{in:"query",key:"limit"},{in:"query",key:"offset"}]}]);return (t?.client??this.client).get({url:"/contacts",...t,...n})}getContact(e,t){let n=C([e],[{args:[{in:"path",key:"uid"}]}]);return (t?.client??this.client).get({url:"/contacts/{uid}",...t,...n})}listSessions(e,t){let n=C([e],[{args:[{in:"query",key:"limit"},{in:"query",key:"offset"},{in:"query",key:"platform"},{in:"query",key:"channelId"},{in:"query",key:"userId"},{in:"query",key:"chatId"}]}]);return (t?.client??this.client).get({url:"/sessions",...t,...n})}getSession(e,t){let n=C([e],[{args:[{in:"path",key:"id"}]}]);return (t?.client??this.client).get({url:"/sessions/{id}",...t,...n})}createSession(e,t){let n=C([e],[{args:[{in:"body",key:"title"},{in:"body",key:"channel"}]}]);return (t?.client??this.client).post({url:"/session",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}sendMessage(e,t){let n=C([e],[{args:[{in:"path",key:"id"},{in:"body",key:"content"},{in:"body",key:"channel"},{in:"body",key:"userId"},{in:"body",key:"chatId"},{in:"body",key:"messageType"},{in:"body",key:"processorId"},{in:"body",key:"agent"},{in:"body",key:"replyToMessageId"}]}]);return (t?.client??this.client).post({url:"/session/{id}/prompt",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}};q(L,"__registry",new V);var U=L;function ie(r){if(r?.fetch||(r={...r,fetch:n=>(n.timeout=false,fetch(n))}),r?.directory){let n=/[^\x00-\x7F]/.test(r.directory)?encodeURIComponent(r.directory):r.directory;r.headers={...r.headers,"x-easbot-directory|":n};}let e=A(r);return new U({client:e})}function Ee(r){if(r.includes("/")||r.includes("\\"))return r;if(process.platform==="win32"){let e=r.toLowerCase();if(!e.endsWith(".cmd")&&!e.endsWith(".exe")&&!e.endsWith(".bat"))return `${r}.cmd`}return r}function qe(r,e,t){let n=r.config??{};return {...n,server:{...n.server??{},...e!==void 0?{port:e}:{},...t?{hostname:t}:{}}}}var Ie=8080,De="127.0.0.1",ve=3e5;async function ae(r){let t=Object.assign({hostname:De,port:Ie,timeout:ve},r??{}),n=r&&"port"in r?r.port:void 0,a=r&&"hostname"in r?r.hostname:void 0,l=["gateway","start"],o=child_process.spawn(Ee("easbot"),l,{signal:t.signal,shell:process.platform==="win32",env:{...process.env,EASBOT_CONFIG_CONTENT:JSON.stringify(qe(t,n,a))}});return {url:await new Promise((s,c)=>{let p=false,u=null,g=null,f=()=>{u&&clearTimeout(u),g&&clearInterval(g);},h=`${t.port===443?"https":"http"}://${t.hostname}:${t.port}/health`,y=()=>{g=setInterval(async()=>{try{let d=new AbortController,m=setTimeout(()=>d.abort(),2e3),T=await fetch(h,{signal:d.signal});clearTimeout(m),T.ok&&(p||(p=!0,f(),s(h)));}catch{}},500);};o.stdout?.on("data",d=>{let m=d.toString();for(let T of m.split(`
|
|
7
|
-
`))if(
|
|
4
|
+
`);S=Z.pop()??"";for(let ge of Z){let we=ge.split(`
|
|
5
|
+
`),P=[],ee;for(let T of we)if(T.startsWith("data:"))P.push(T.replace(/^data:\s*/,""));else if(T.startsWith("event:"))ee=T.replace(/^event:\s*/,"");else if(T.startsWith("id:"))u=T.replace(/^id:\s*/,"");else if(T.startsWith("retry:")){let re=Number.parseInt(T.replace(/^retry:\s*/,""),10);Number.isNaN(re)||(d=re);}let q,te=!1;if(P.length){let T=P.join(`
|
|
6
|
+
`);try{q=JSON.parse(T),te=!0;}catch{q=T;}}te&&(i&&await i(q),n&&(q=await n(q))),e?.({data:q,event:ee,id:u,retry:d}),P.length&&(yield q);}}}finally{w.removeEventListener("abort",Y),O.releaseLock();}break}catch(x){if(t?.(x),o!==void 0&&y>=o)break;let G=Math.min(d*2**(y-1),a??3e4);await g(G);}}}()}}var Se=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},Re=r=>{switch(r){case "form":return ",";case "pipeDelimited":return "|";case "spaceDelimited":return "%20";default:return ","}},xe=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},z=({allowReserved:r,explode:t,name:e,style:n,value:i})=>{if(!t){let a=(r?i:i.map(s=>encodeURIComponent(s))).join(Re(n));switch(n){case "label":return `.${a}`;case "matrix":return `;${e}=${a}`;case "simple":return a;default:return `${e}=${a}`}}let l=Se(n),o=i.map(a=>n==="label"||n==="simple"?r?a:encodeURIComponent(a):v({allowReserved:r,name:e,value:a})).join(l);return n==="label"||n==="matrix"?l+o:o},v=({allowReserved:r,name:t,value:e})=>{if(e==null)return "";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return `${t}=${r?e:encodeURIComponent(e)}`},j=({allowReserved:r,explode:t,name:e,style:n,value:i,valueOnly:l})=>{if(i instanceof Date)return l?i.toISOString():`${e}=${i.toISOString()}`;if(n!=="deepObject"&&!t){let s=[];Object.entries(i).forEach(([p,u])=>{s=[...s,p,r?u:encodeURIComponent(u)];});let c=s.join(",");switch(n){case "form":return `${e}=${c}`;case "label":return `.${c}`;case "matrix":return `;${e}=${c}`;default:return c}}let o=xe(n),a=Object.entries(i).map(([s,c])=>v({allowReserved:r,name:n==="deepObject"?`${e}[${s}]`:s,value:c})).join(o);return n==="label"||n==="matrix"?o+a:a};var Oe=/\{[^{}]+\}/g,Te=({path:r,url:t})=>{let e=t,n=t.match(Oe);if(n)for(let i of n){let l=false,o=i.substring(1,i.length-1),a="simple";o.endsWith("*")&&(l=true,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),a="label"):o.startsWith(";")&&(o=o.substring(1),a="matrix");let s=r[o];if(s==null)continue;if(Array.isArray(s)){e=e.replace(i,z({explode:l,name:o,style:a,value:s}));continue}if(typeof s=="object"){e=e.replace(i,j({explode:l,name:o,style:a,value:s,valueOnly:true}));continue}if(a==="matrix"){e=e.replace(i,`;${v({name:o,value:s})}`);continue}let c=encodeURIComponent(a==="label"?`.${s}`:s);e=e.replace(i,c);}return e},se=({baseUrl:r,path:t,query:e,querySerializer:n,url:i})=>{let l=i.startsWith("/")?i:`/${i}`,o=(r??"")+l;t&&(o=Te({path:t,url:o}));let a=e?n(e):"";return a.startsWith("?")&&(a=a.substring(1)),a&&(o+=`?${a}`),o};function M(r){let t=r.body!==void 0;if(t&&r.bodySerializer)return "serializedBody"in r?r.serializedBody!==void 0&&r.serializedBody!==""?r.serializedBody:null:r.body!==""?r.body:null;if(t)return r.body}var oe=async(r,t)=>{let e=typeof t=="function"?await t(r):t;if(e)return r.scheme==="bearer"?`Bearer ${e}`:r.scheme==="basic"?`Basic ${btoa(e)}`:e};var H={bodySerializer:r=>JSON.stringify(r,(t,e)=>typeof e=="bigint"?e.toString():e)};var ae=({parameters:r={},...t}={})=>n=>{let i=[];if(n&&typeof n=="object")for(let l in n){let o=n[l];if(o==null)continue;let a=r[l]||t;if(Array.isArray(o)){let s=z({allowReserved:a.allowReserved,explode:true,name:l,style:"form",value:o,...a.array});s&&i.push(s);}else if(typeof o=="object"){let s=j({allowReserved:a.allowReserved,explode:true,name:l,style:"deepObject",value:o,...a.object});s&&i.push(s);}else {let s=v({allowReserved:a.allowReserved,name:l,value:o});s&&i.push(s);}}return i.join("&")},ie=r=>{if(!r)return "stream";let t=r.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return "json";if(t==="multipart/form-data")return "formData";if(["application/","audio/","image/","video/"].some(e=>t.startsWith(e)))return "blob";if(t.startsWith("text/"))return "text"}},Ce=(r,t)=>t?!!(r.headers.has(t)||r.query?.[t]||r.headers.get("Cookie")?.includes(`${t}=`)):false;async function le(r){for(let t of r.security??[]){if(Ce(r,t.name))continue;let e=await oe(t,r.auth);if(!e)continue;let n=t.name??"Authorization";switch(t.in){case "query":r.query||(r.query={}),r.query[n]=e;break;case "cookie":r.headers.append("Cookie",`${n}=${e}`);break;default:r.headers.set(n,e);break}}}var F=r=>se({baseUrl:r.baseUrl,path:r.path,query:r.query,querySerializer:typeof r.querySerializer=="function"?r.querySerializer:ae(r.querySerializer),url:r.url}),N=(r,t)=>{let e={...r,...t};return e.baseUrl?.endsWith("/")&&(e.baseUrl=e.baseUrl.substring(0,e.baseUrl.length-1)),e.headers=L(r.headers,t.headers),e},Ee=r=>{let t=[];return r.forEach((e,n)=>{t.push([n,e]);}),t},L=(...r)=>{let t=new Headers;for(let e of r){if(!e)continue;let n=e instanceof Headers?Ee(e):Object.entries(e);for(let[i,l]of n)if(l===null)t.delete(i);else if(Array.isArray(l))for(let o of l)t.append(i,o);else l!==void 0&&t.set(i,typeof l=="object"?JSON.stringify(l):l);}return t},I=class{constructor(){R(this,"fns",[]);}clear(){this.fns=[];}eject(t){let e=this.getInterceptorIndex(t);this.fns[e]&&(this.fns[e]=null);}exists(t){let e=this.getInterceptorIndex(t);return !!this.fns[e]}getInterceptorIndex(t){return typeof t=="number"?this.fns[t]?t:-1:this.fns.indexOf(t)}update(t,e){let n=this.getInterceptorIndex(t);return this.fns[n]?(this.fns[n]=e,t):false}use(t){return this.fns.push(t),this.fns.length-1}},pe=()=>({error:new I,request:new I,response:new I}),ke=ae({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}}),Ge={"Content-Type":"application/json"},A=(r={})=>({...H,headers:Ge,parseAs:"auto",querySerializer:ke,...r});var D=(r={})=>{let t=N(A(),r),e=()=>({...t}),n=p=>(t=N(t,p),e()),i=pe(),l=async p=>{let u={...t,...p,fetch:p.fetch??t.fetch??globalThis.fetch,headers:L(t.headers,p.headers),serializedBody:void 0};u.security&&await le(u),u.requestValidator&&await u.requestValidator(u),u.body!==void 0&&u.bodySerializer&&(u.serializedBody=u.bodySerializer(u.body)),(u.body===void 0||u.serializedBody==="")&&u.headers.delete("Content-Type");let g=u,f=F(g);return {opts:g,url:f}},o=async p=>{let u=p.throwOnError??t.throwOnError,g=p.responseStyle??t.responseStyle,f,h;try{let{opts:d,url:y}=await l(p),w={redirect:"follow",...d,body:M(d)};f=new Request(y,w);for(let m of i.request.fns)m&&(f=await m(f,d));let C=d.fetch;h=await C(f);for(let m of i.response.fns)m&&(h=await m(h,f,d));let x={request:f,response:h};if(h.ok){let m=(d.parseAs==="auto"?ie(h.headers.get("Content-Type")):d.parseAs)??"json";if(h.status===204||h.headers.get("Content-Length")==="0"){let S;switch(m){case "arrayBuffer":case "blob":case "text":S=await h[m]();break;case "formData":S=new FormData;break;case "stream":S=h.body;break;default:S={};break}return d.responseStyle==="data"?S:{data:S,...x}}let O;switch(m){case "arrayBuffer":case "blob":case "formData":case "text":O=await h[m]();break;case "json":{let S=await h.text();O=S?JSON.parse(S):{};break}case "stream":return d.responseStyle==="data"?h.body:{data:h.body,...x}}return m==="json"&&(d.responseValidator&&await d.responseValidator(O),d.responseTransformer&&(O=await d.responseTransformer(O))),d.responseStyle==="data"?O:{data:O,...x}}let G=await h.text(),$;try{$=JSON.parse(G);}catch{}throw $??G}catch(d){let y=d;for(let w of i.error.fns)w&&(y=await w(y,h,f,p));if(y=y||{},u)throw y;return g==="data"?void 0:{error:y,request:f,response:h}}},a=p=>u=>o({...u,method:p}),s=p=>async u=>{let{opts:g,url:f}=await l(u);return ne({...g,body:g.body,method:p,onRequest:async(h,d)=>{let y=new Request(h,d);for(let w of i.request.fns)w&&(y=await w(y,g));return y},serializedBody:M(g),url:f})};return {buildUrl:p=>F({...t,...p}),connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),getConfig:e,head:a("HEAD"),interceptors:i,options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),request:o,setConfig:n,sse:{connect:s("CONNECT"),delete:s("DELETE"),get:s("GET"),head:s("HEAD"),options:s("OPTIONS"),patch:s("PATCH"),post:s("POST"),put:s("PUT"),trace:s("TRACE")},trace:a("TRACE")}};var qe={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},ve=Object.entries(qe);function ue(r,t){t||(t=new Map);for(let e of r)"in"in e?e.key&&t.set(e.key,{in:e.in,map:e.map}):"key"in e?t.set(e.key,{map:e.map}):e.args&&ue(e.args,t);return t}function Ie(r){for(let[t,e]of Object.entries(r))t!=="body"&&e&&typeof e=="object"&&!Array.isArray(e)&&!Object.keys(e).length&&delete r[t];}function E(r,t){let e={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},n=ue(t);function i(o,a,s){let c=e[o];c===void 0&&(c=Object.create(null),e[o]=c),c[a]=s;}let l;for(let[o,a]of r.entries())if(t[o]&&(l=t[o]),!!l)if("in"in l)if(l.key){let s=n.get(l.key),c=s.map||l.key;s.in&&i(s.in,c,a);}else e.body=a;else for(let[s,c]of Object.entries(a??{})){let p=n.get(s);if(p)if(p.in){let u=p.map||s;i(p.in,u,c);}else e[p.map]=c;else {let u=ve.find(([g])=>s.startsWith(g));if(u){let[g,f]=u;i(f,s.slice(g.length),c);}else if("allowExtra"in l&&l.allowExtra){for(let[g,f]of Object.entries(l.allowExtra))if(f){i(g,s,c);break}}}}return Ie(e),e}var ce=D(A({baseUrl:"http://localhost:8080"}));var k=class{constructor(t){R(this,"client");this.client=t?.client??ce;}},_=class{constructor(){R(this,"defaultKey","default");R(this,"instances",new Map);}get(t){let e=this.instances.get(t??this.defaultKey);if(!e)throw new Error('No SDK client found. Create one with "new EasbotGatewayClient()" to fix this error.');return e}set(t,e){this.instances.set(e??this.defaultKey,t);}},V=class extends k{list(t){return (t?.client??this.client).get({url:"/channels",...t})}},J=class extends k{list(t,e){let n=E([t],[{args:[{in:"query",key:"platform"},{in:"query",key:"limit"},{in:"query",key:"offset"}]}]);return (e?.client??this.client).get({url:"/contacts",...e,...n})}get(t,e){let n=E([t],[{args:[{in:"path",key:"uid"}]}]);return (e?.client??this.client).get({url:"/contacts/{uid}",...e,...n})}},W=class extends k{list(t,e){let n=E([t],[{args:[{in:"query",key:"platform"},{in:"query",key:"channelId"},{in:"query",key:"userId"},{in:"query",key:"chatId"},{in:"query",key:"limit"},{in:"query",key:"offset"}]}]);return (e?.client??this.client).get({url:"/sessions",...e,...n})}get(t,e){let n=E([t],[{args:[{in:"path",key:"sessionId"}]}]);return (e?.client??this.client).get({url:"/sessions/{sessionId}",...e,...n})}},K=class extends k{create(t,e){let n=E([t],[{args:[{key:"body",map:"body"}]}]);return (e?.client??this.client).post({url:"/session",...e,...n,headers:{"Content-Type":"application/json",...e?.headers,...n.headers}})}prompt(t,e){let n=E([t],[{args:[{in:"path",key:"sessionId"},{key:"body",map:"body"}]}]);return (e?.client??this.client).post({url:"/session/{sessionId}/prompt",...e,...n,headers:{"Content-Type":"application/json",...e?.headers,...n.headers}})}},Q=class extends k{list(t,e){let n=E([t],[{args:[{in:"query",key:"sessionId"},{in:"query",key:"subscriberId"}]}]);return (e?.client??this.client).get({url:"/subscriptions",...e,...n})}},X=class extends k{constructor(){super(...arguments);R(this,"_channels");R(this,"_contacts");R(this,"_sessions");R(this,"_session");R(this,"_subscriptions");}health(e){return (e?.client??this.client).get({url:"/health",...e})}status(e){return (e?.client??this.client).get({url:"/status",...e})}get channels(){return this._channels??(this._channels=new V({client:this.client}))}get contacts(){return this._contacts??(this._contacts=new J({client:this.client}))}get sessions(){return this._sessions??(this._sessions=new W({client:this.client}))}get session(){return this._session??(this._session=new K({client:this.client}))}get subscriptions(){return this._subscriptions??(this._subscriptions=new Q({client:this.client}))}},B=class B extends k{constructor(e){super(e);R(this,"_gateway");B.__registry.set(this,e?.key);}get gateway(){return this._gateway??(this._gateway=new X({client:this.client}))}};R(B,"__registry",new _);var U=B;function ye(r){if(r?.fetch||(r={...r,fetch:n=>(n.timeout=false,fetch(n))}),r?.directory){let n=/[^\p{ASCII}]/u.test(r.directory)?encodeURIComponent(r.directory):r.directory;r.headers={...r.headers,"x-easbot-directory":n};}let t=D(r);return new U({client:t})}function De(r){if(r.includes("/")||r.includes("\\"))return r;if(process.platform==="win32"){let t=r.toLowerCase();if(!t.endsWith(".cmd")&&!t.endsWith(".exe")&&!t.endsWith(".bat"))return `${r}.cmd`}return r}function Pe(r,t,e){let n=r.config??{};return {...n,server:{...n.server??{},...t!==void 0?{port:t}:{},...e?{hostname:e}:{}}}}var ze=8080,je="127.0.0.1",Le=3e5;async function de(r){let e=Object.assign({hostname:je,port:ze,timeout:Le},r??{}),n=r&&"port"in r?r.port:void 0,i=r&&"hostname"in r?r.hostname:void 0,l=["gateway","start"],o=child_process.spawn(De("easbot"),l,{signal:e.signal,shell:process.platform==="win32",env:{...process.env,EASBOT_CONFIG_CONTENT:JSON.stringify(Pe(e,n,i))}});return {url:await new Promise((s,c)=>{let p=false,u=null,g=null,f=()=>{u&&clearTimeout(u),g&&clearInterval(g);},h=`${e.port===443?"https":"http"}://${e.hostname}:${e.port}/health`,d=()=>{g=setInterval(async()=>{try{let y=new AbortController,w=setTimeout(()=>y.abort(),2e3),C=await fetch(h,{signal:y.signal});clearTimeout(w),C.ok&&(p||(p=!0,f(),s(h)));}catch{}},500);};o.stdout?.on("data",y=>{let w=y.toString();for(let C of w.split(`
|
|
7
|
+
`))if(C.startsWith("easbot gateway listening")){let x=C.match(/on\s+(https?:\/\/[^\s]+)/);if(x&&!p){p=true,f(),s(x[1]);return}}}),o.stderr?.on("data",()=>{}),o.on("exit",y=>{if(p)return;f();let w=`Gateway server exited with code ${y}`;c(new Error(w));}),o.on("error",y=>{p||(f(),c(y));}),u=setTimeout(()=>{p||(f(),c(new Error(`Timeout waiting for gateway server to start after ${e.timeout}ms`)));},e.timeout),e.signal&&e.signal.addEventListener("abort",()=>{p||(f(),c(new Error("Aborted")));}),d();}),close(){o.kill();}}}async function Nt(r){let t=await de({...r});return {client:ye({baseUrl:t.url}),server:t}}exports.EasbotGatewayClient=U;exports.createEasbotGateway=Nt;exports.createEasbotGatewayClient=ye;exports.createEasbotGatewayServer=de;
|