@bereasoftware/nexa 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/nexa.iife.js CHANGED
@@ -1,2 +1,462 @@
1
- var Nexa=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,t)=>()=>(e&&(t=e(e=0)),t),r=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},i=e=>({ok:!0,value:e}),a=e=>({ok:!1,error:e});function o(e){return{validate(t){let n=t;for(let[t,r]of Object.entries(e))if(!r(n[t]))return a({message:`Validation failed: field "${t}" is invalid`,code:`VALIDATION_ERROR`});return i(t)}}}function s(e){return{validate(t){let n=t,r=e.filter(e=>!(e in n));return r.length>0?a({message:`Validation failed: missing fields: ${r.join(`, `)}`,code:`VALIDATION_ERROR`}):i(t)}}}var c={validate(e){return Array.isArray(e)?i(e):a({message:`Expected array response`,code:`VALIDATION_ERROR`})}},l={validate(e){return e&&typeof e==`object`&&!Array.isArray(e)?i(e):a({message:`Expected object response`,code:`VALIDATION_ERROR`})}},u={transform(e){return v(e,ee)}},d={transform(e){return v(e,te)}},f={transform(e){return y(e)}};function p(e){return{transform(t){return Array.isArray(t)?t.map(t=>b(t,e)):b(t,e)}}}function m(e){return{transform(t){return{[e]:t}}}}var h=class{maxAttempts;constructor(e=5){this.maxAttempts=e}shouldRetry(e){return e<this.maxAttempts}delayMs(e){return e*50}},g=class{retryableStatuses=[408,429,500,502,503,504];maxAttempts;constructor(e=3){this.maxAttempts=e}shouldRetry(e,t){return e>=this.maxAttempts?!1:this.retryableStatuses.includes(t.status??0)||t.code===`TIMEOUT`}delayMs(e){return Math.min(1e3*2**(e-1),1e4)}},_=class{failureCount=0;lastFailureTime=0;maxAttempts;failureThreshold;resetTimeMs;constructor(e=3,t=5,n=6e4){this.maxAttempts=e,this.failureThreshold=t,this.resetTimeMs=n}shouldRetry(e){return e>=this.maxAttempts||(Date.now()-this.lastFailureTime>this.resetTimeMs&&(this.failureCount=0),this.failureCount>=this.failureThreshold)?!1:(this.failureCount++,this.lastFailureTime=Date.now(),!0)}delayMs(e){return 100*2**(e-1)}reset(){this.failureCount=0,this.lastFailureTime=0}};function ee(e){return e.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function te(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function v(e,t){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>v(e,t));let n={};for(let[r,i]of Object.entries(e))n[t(r)]=v(i,t);return n}function y(e,t=``){let n={};if(Array.isArray(e))e.forEach((e,r)=>{let i=t?`${t}[${r}]`:`[${r}]`;Object.assign(n,y(e,i))});else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e)){let e=t?`${t}.${r}`:r;i&&typeof i==`object`&&!Array.isArray(i)?Object.assign(n,y(i,e)):n[e]=i}return n}function b(e,t){if(!e||typeof e!=`object`)return{};let n=e,r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function ne(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return t.signal.addEventListener(`abort`,()=>clearTimeout(n),{once:!0}),t}async function re(e,t=3){try{return await e()}catch(n){if(t<=0)throw n;return re(e,t-1)}}var x=class{cache=new Map;get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),null):t.data:null}set(e,t,n=6e4){this.cache.set(e,{data:t,timestamp:Date.now(),ttlMs:n})}clear(){this.cache.clear()}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),!1):!0:!1}delete(e){this.cache.delete(e)}};function S(e={}){let t=e.cache||new x,n=e.ttlMs||6e4,r=e.cacheableStatuses||[200,304];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase(),o=a===`GET`,s=`${a}:${e.request.url}`;if(o&&t.has(s)){let n=t.get(s);if(n){e.response=n,e.state.cacheHit=!0;return}}await i(),o&&e.response&&r.includes(e.response.status)&&(t.set(s,e.response,n),e.state.cacheMiss=!0)}}var ie=S(),C=class{pending=new Map;async execute(e,t){if(this.pending.has(e))return this.pending.get(e);let n=t().finally(()=>{this.pending.delete(e)});return this.pending.set(e,n),n}clear(){this.pending.clear()}};function w(e={}){let t=e.deduplicator||new C,n=e.includeBody??!1,r=e.methods||[`GET`];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase();if(!r.includes(a)){await i();return}let o=`${a}:${e.request.url}`;n&&e.request.body&&(o+=`:${JSON.stringify(e.request.body)}`);try{e.response=await t.execute(o,async()=>(await i(),e.response)),e.state.deduped=!0}catch(t){throw e.error=t,t}}}var ae=w();function T(e={maxRequests:100,windowMs:6e4}){let t=e.windowMs??6e4,n=e.maxRequests,r=e.keyGenerator??(e=>`${e.request.method}:${e.request.url}`),i=new Map;return async(a,o)=>{let s=r(a),c=Date.now();if(i.size>1e3)for(let[e,t]of i.entries())c>t.resetTime&&i.delete(e);let l=i.get(s);if((!l||c>l.resetTime)&&(l={count:0,resetTime:c+t},i.set(s,l)),l.count>=n){a.response={status:e.errorResponse?.status??429,headers:{"Content-Type":`application/json`},body:e.errorResponse?.body??{error:`Too Many Requests`,message:`Rate limit exceeded`}},a.state.rateLimited=!0;return}l.count++,a.state.rateLimit={limit:n,remaining:n-l.count,reset:l.resetTime},await o()}}var oe=T();function E(e={}){let t=e.failureThreshold??5,n=e.resetTimeout??3e4,r=e.isFailure??(e=>e.response.status>=500),i=e.keyGenerator??(e=>`${e.request.method}:${e.request.url}`),a=new Map;return async(e,o)=>{let s=i(e),c=a.get(s);if(c||(c={state:`closed`,failures:0,lastFailure:0,successCount:0},a.set(s,c)),c.state===`open`)if(Date.now()-c.lastFailure>n)c.state=`half-open`,c.successCount=0;else{e.response={status:503,headers:{"Content-Type":`application/json`},body:{error:`Service Unavailable`,message:`Circuit breaker is open`}},e.state.circuitOpen=!0;return}try{await o(),r(e)?(c.failures++,c.lastFailure=Date.now(),(c.failures>=t||c.state===`half-open`)&&(c.state=`open`)):(c.failures=0,c.state===`half-open`&&(c.successCount++,c.successCount>=3&&(c.state=`closed`,c.successCount=0)))}catch(e){throw c.failures++,c.lastFailure=Date.now(),(c.failures>=t||c.state===`half-open`)&&(c.state=`open`),e}}}var se=E();function D(e){return async t=>{let n=-1;async function r(i){if(i<=n)throw Error(`next() called multiple times`);n=i;let a=e[i];a&&await a(t,()=>r(i+1))}await r(0)}}var ce=class{middlewares=[];use(e){return this.middlewares.push(e),this}async execute(e){if(e&&typeof e==`object`&&`request`in e&&`response`in e){let t=e;return await D(this.middlewares.map(e=>typeof e==`function`&&e.length===2?e:async(t,n)=>{let r=e;t.response.body=await r(t.response.body),await n()}))(t),t.response.body}let t=e;for(let e of this.middlewares)t=await e(t);return t}clear(){this.middlewares=[]}};function le(e,t,n,r={}){return{ok:e>=200&&e<300,data:t,error:n,status:e,headers:r}}function O(e){return async(t,n)=>{let r=e.path,i;switch(e.method){case`GET`:i=await t.get(r);break;case`POST`:i=await t.post(r,n);break;case`PUT`:i=await t.put(r,n);break;case`PATCH`:i=await t.patch(r,n);break;case`DELETE`:i=await t.delete(r);break;default:throw Error(`Unsupported method: ${e.method}`)}return i}}function ue(e){return{request:async(t,n,r)=>{let i=e[n];return await O(i)(t,r)}}}var de=class e{subscribers=[];errorSubscribers=[];completeSubscribers=[];subscribe(e,t,n){return e&&this.subscribers.push(e),t&&this.errorSubscribers.push(t),n&&this.completeSubscribers.push(n),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e),this.errorSubscribers=this.errorSubscribers.filter(e=>e!==t),this.completeSubscribers=this.completeSubscribers.filter(e=>e!==n)}}}next(e){this.subscribers.forEach(t=>t(e))}error(e){this.errorSubscribers.forEach(t=>t(e))}complete(){this.completeSubscribers.forEach(e=>e())}map(t){let n=new e;return this.subscribe(e=>n.next(t(e)),e=>n.error(e),()=>n.complete()),n}filter(t){let n=new e;return this.subscribe(e=>{t(e)&&n.next(e)},e=>n.error(e),()=>n.complete()),n}};function fe(e){return t=>{if(!e(t))throw TypeError(`Value does not match expected type`);return t}}function k(e){return e}function pe(e){return k(e)}var me=class{_promise;resolveFunc;rejectFunc;constructor(){this._promise=new Promise((e,t)=>{this.resolveFunc=e,this.rejectFunc=t})}resolve(e){this.resolveFunc(e)}reject(e){this.rejectFunc(e)}get promise(){return this._promise}promise_(){return this._promise}};async function A(e,t={}){let n=e.body?.getReader();if(!n)throw Error(`Response body is not readable`);let r=[],i=0,a=parseInt(e.headers.get(`content-length`)||`0`,10);for(;;){let{done:e,value:o}=await n.read();if(e)break;r.push(o),i+=o.length,t.onChunk&&await t.onChunk(o),t.onProgress&&a>0&&t.onProgress(i,a)}return j(r,i)}function j(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}async function he(e,t){let n=await A(e);if(typeof window>`u`)await(await import(`fs`).then(e=>e.promises)).writeFile(t,n);else{let e=new Blob([n.buffer],{type:`application/octet-stream`}),r=URL.createObjectURL(e),i=document.createElement(`a`);i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}}function M(e={}){return async(t,n)=>{if(await n(),t.response&&t.response.body&&typeof t.response.body==`object`&&`getReader`in t.response.body){let n=t.response.body.getReader(),r=[],i=0,a=parseInt(t.response.headers?.[`content-length`]||`0`,10);try{for(;;){let{done:o,value:s}=await n.read();if(o)break;r.push(s),i+=s.length,e.onChunk&&await e.onChunk(s),e.onProgress&&a>0&&e.onProgress(i,a),t.state.streamedChunks=t.state.streamedChunks||[],t.state.streamedChunks.push(s)}let o=j(r,i);t.response.body=o,t.state.streaming=!0,t.state.streamedBytes=i}finally{n.releaseLock()}}}}var ge=M({onProgress:(e,t)=>{if(t>0){let n=Math.round(e/t*100);console.log(`⬇️ Streaming: ${n}% (${e}/${t} bytes)`)}}}),N=class{plugins=[];cache=new x;deduplicator=new C;middlewares=[];listeners=new Map;register(e){return this.plugins.push(e),e.setup(this),this.emit(`plugin:registered`,e.name),this}addMiddleware(e){return this.middlewares.push(e),this}getCache(){return this.cache}getDeduplicator(){return this.deduplicator}getPipeline(){return D(this.middlewares)}async executePipeline(e){await this.getPipeline()(e)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t),this}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}off(e,t){return this.listeners.get(e)?.delete(t),this}getPlugins(){return[...this.plugins]}clear(){this.plugins=[],this.middlewares=[],this.listeners.clear(),this.cache.clear(),this.deduplicator.clear()}},_e={name:`logger`,setup(e){e.on(`request:start`,(...e)=>{let t=e[0];console.log(`📤 Request started: ${t}`)}),e.on(`request:success`,(...e)=>{let t=e[0],n=e[1];console.log(`✅ Request succeeded: ${t} (${n})`)}),e.on(`request:error`,(...e)=>{let t=e[0],n=e[1];console.error(`❌ Request failed: ${t}`,n)})}},ve=class{name=`metrics`;metrics={requests:0,errors:0,totalTime:0,avgTime:0};setup(e){e.on(`request:complete`,(...e)=>{let t=e[0],n=e[1];this.metrics.requests++,this.metrics.totalTime+=t,this.metrics.avgTime=this.metrics.totalTime/this.metrics.requests,n||this.metrics.errors++})}getMetrics(){return{...this.metrics}}},ye=class{name=`cache`;ttlMs;constructor(e=6e4){this.ttlMs=e}setup(e){e.addMiddleware(S({ttlMs:this.ttlMs}))}},be=class{name=`dedupe`;setup(e){e.addMiddleware(w())}},xe=class{name=`rate-limit`;options;constructor(e={}){this.options=e}setup(e){e.addMiddleware(T({maxRequests:this.options.maxRequests??100,windowMs:this.options.windowMs??6e4,keyGenerator:this.options.keyGenerator,errorResponse:this.options.errorResponse}))}},Se=class{name=`circuit-breaker`;options;constructor(e={}){this.options=e}setup(e){e.addMiddleware(E({failureThreshold:this.options.failureThreshold??5,resetTimeout:this.options.resetTimeout??3e4,isFailure:this.options.isFailure,keyGenerator:this.options.keyGenerator}))}},P=r({Http2SessionPool:()=>z,closeHttp2SessionPool:()=>ke,getHttp2SessionPoolStats:()=>Ae,nodeHttp2Adapter:()=>Oe,nodeHttpAdapter:()=>De});async function Ce(){return I||(I=await import(`http`),L=await import(`https`)),{http:I,https:L}}async function we(){return R||=await import(`http2`),R}function F(e,t){let n,r,i,a,o;if(typeof e==`string`)n=e,r=t?.method||`GET`,i=t?.headers||{},a=t?.body,o=t?.signal===null?void 0:t?.signal;else{n=e.url,r=t?.method||e.method||`GET`;let s=new Headers(e.headers),c=new Headers(t?.headers),l=new Headers(s);c.forEach((e,t)=>l.set(t,e)),i=Object.fromEntries(l.entries()),a=t?.body??e.body??void 0,o=t?.signal===null?e.signal:t?.signal}return{url:n,method:r,headers:i,body:a,signal:o}}function Te(e,t,n,r,i=!1){if(i)return null;let a=e.startsWith(`https:`)?n.Agent:t.Agent,o={keepAlive:r?.keepAlive??!0,maxSockets:r?.maxSockets??50,maxFreeSockets:r?.maxFreeSockets??10,timeout:r?.timeout??6e4};return r?.maxRequestsPerSocket!==void 0&&(o.maxRequestsPerSocket=r.maxRequestsPerSocket),new a(o)}async function Ee(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers))Array.isArray(r)?r.forEach(e=>t.append(n,e)):r!==void 0&&t.set(n,String(r));let n=[];return e.on(`data`,e=>n.push(e)),new Promise(r=>{e.on(`end`,()=>{let i=Buffer.concat(n);r(new Response(i,{status:e.statusCode||200,statusText:e.statusMessage||`OK`,headers:t}))})})}async function De(e,t,n){let{http:r,https:i}=await Ce(),{url:a,method:o,headers:s,body:c,signal:l}=F(e,t),u=new URL(a),d=u.protocol===`https:`,f=d?i:r,p=Te(a,r,i,n,!1);return new Promise((e,t)=>{let r=f.request({hostname:u.hostname,port:u.port||(d?443:80),path:u.pathname+u.search,method:o,headers:s,agent:p});if(l){if(l.aborted){r.destroy(),t(Error(`Request aborted`));return}let e=()=>{r.destroy(),t(Error(`Request aborted`))};l.addEventListener(`abort`,e);let n=()=>l.removeEventListener(`abort`,e);r.on(`close`,n),r.on(`error`,n)}r.setTimeout(n?.timeout??6e4,()=>{r.destroy(),t(Error(`Request timed out`))}),r.on(`response`,async n=>{try{e(await Ee(n))}catch(e){t(e)}}),r.on(`error`,t),c&&(typeof c==`string`?r.write(c):c instanceof Uint8Array?r.write(Buffer.from(c)):Buffer.isBuffer(c)?r.write(c):typeof c==`object`&&r.write(JSON.stringify(c))),r.end()})}async function Oe(e,t,n){let{url:r,method:i,headers:a,body:o,signal:s}=F(e,t),c=new URL(r),l=c.origin;return new Promise(async(e,t)=>{let r,u,d=!1,f=()=>{d||(d=!0,B.releaseSession(l))},p=e=>{f(),t(e)},m=t=>{f(),e(t)};try{if(r=await B.getSession(l,n),s?.aborted){p(Error(`Request aborted`));return}if(u=r.request({":path":c.pathname+c.search,":method":i,...a}),n?.timeout&&u.setTimeout(n.timeout,()=>{u.close(),p(Error(`Request timed out`))}),s){let e=()=>{u.close(),p(Error(`Request aborted`))};s.addEventListener(`abort`,e);let t=()=>s.removeEventListener(`abort`,e);u.on(`close`,t),u.on(`error`,t)}let e=[];u.on(`data`,t=>e.push(Buffer.isBuffer(t)?t:Buffer.from(t))),u.on(`response`,t=>{let n=Number(t[`:status`])||200,r=new Headers;for(let[e,n]of Object.entries(t))e.startsWith(`:`)||(Array.isArray(n)?n.forEach(t=>r.append(e,t)):n!==void 0&&r.set(e,String(n)));u.on(`end`,()=>{let t=Buffer.concat(e);m(new Response(t,{status:n,statusText:`OK`,headers:r}))})}),u.on(`error`,e=>{p(e)}),o&&(typeof o==`string`||o instanceof Uint8Array||Buffer.isBuffer(o)?u.write(o):typeof o==`object`&&u.write(JSON.stringify(o))),u.end()}catch(e){p(e instanceof Error?e:Error(String(e)))}})}function ke(){B.closeAll()}function Ae(){let e=B.getStats();return{sessionCount:e.sessionCount,origins:e.origins}}var I,L,R,z,B,V=n((()=>{z=class{sessions=new Map;cleanupInterval=null;maxIdleTime=3e4;maxRequestsPerSession=1e3;constructor(){this.startCleanup()}startCleanup(){this.cleanupInterval||=setInterval(()=>this.cleanup(),1e4)}cleanup(){let e=Date.now();for(let t of this.sessions.values())!t.closing&&e-t.lastUsed>this.maxIdleTime&&this.closeSession(t,`idle timeout`),!t.closing&&t.requestCount>=this.maxRequestsPerSession&&this.closeSession(t,`max requests exceeded`)}closeSession(e,t){e.closing=!0,e.session.close(),this.sessions.delete(e.origin)}async getSession(e,t){let n=this.sessions.get(e);if(n&&!n.session.closed&&!n.session.destroyed)return n.lastUsed=Date.now(),n.requestCount++,n.session;let r=(await we()).connect(e,{settings:t?.http2Settings});return r.on(`error`,t=>{this.sessions.delete(e)}),r.on(`close`,()=>{this.sessions.delete(e)}),n={session:r,lastUsed:Date.now(),requestCount:1,origin:e,closing:!1},this.sessions.set(e,n),r}releaseSession(e){let t=this.sessions.get(e);t&&(t.lastUsed=Date.now())}getStats(){return{sessionCount:this.sessions.size,origins:Array.from(this.sessions.keys()),sessions:Array.from(this.sessions.values()).map(e=>({origin:e.origin,requestCount:e.requestCount,lastUsed:e.lastUsed,closing:e.closing,sessionAlive:!e.session.closed&&!e.session.destroyed}))}}closeAll(){for(let e of this.sessions.values())e.closing||e.session.close();this.sessions.clear(),this.cleanupInterval&&=(clearInterval(this.cleanupInterval),null)}},B=new z}));function je(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}function Me(){let e=globalThis;return typeof window>`u`&&e.Deno!==void 0&&e.Deno.version?.deno!==void 0}function Ne(){let e=globalThis;return e.Bun!==void 0&&e.Bun.version!==void 0}function Pe(){let e=globalThis;return e.caches!==void 0&&e.WebSocketPair!==void 0}function Fe(e,t){if(!e||e===`fetch`)return fetch;if(e===`node`||e===`http2`){if(!je())throw Error(`Transport '${e}' is only available in Node.js environment`);return(n,r)=>e===`http2`?Promise.resolve().then(()=>(V(),P)).then(e=>e.nodeHttp2Adapter(n,r,t)):Promise.resolve().then(()=>(V(),P)).then(e=>e.nodeHttpAdapter(n,r,t))}switch(e){case`deno`:if(!Me())throw Error(`Transport 'deno' is only available in Deno environment`);return fetch;case`bun`:if(!Ne())throw Error(`Transport 'bun' is only available in Bun environment`);return fetch;case`cloudflare`:if(!Pe())throw Error(`Transport 'cloudflare' is only available in Cloudflare Workers environment`);return fetch;default:return fetch}}var Ie=class{store=new x;get(e){return this.store.get(e)}set(e,t,n=6e4){this.store.set(e,t,n)}has(e){return this.store.has(e)}clear(){this.store.clear()}},Le=class{maxAttempts;baseDelayMs;constructor(e=3,t=100){this.maxAttempts=e,this.baseDelayMs=t}shouldRetry(e,t){let n=t.status!==void 0&&t.status>=500,r=t.code===`NETWORK_ERROR`;return e<this.maxAttempts&&(n||r||t.code===`TIMEOUT`)}delayMs(e){let t=this.baseDelayMs*2**(e-1),n=Math.random()*t*.1;return Math.min(t+n,3e4)}},Re=class{maxAttempts;baseDelayMs;condition;constructor(e=3,t=100,n){this.maxAttempts=e,this.baseDelayMs=t,this.condition=n}shouldRetry(e,t){if(e>=this.maxAttempts)return!1;if(this.condition)return this.condition(t,e);let n=t.status!==void 0&&t.status>=500,r=t.code===`NETWORK_ERROR`;return n||r||t.code===`TIMEOUT`}delayMs(e){let t=this.baseDelayMs*2**(e-1),n=Math.random()*t*.1;return Math.min(t+n,3e4)}},ze=class{running=0;queue=[];maxConcurrent;constructor(e){this.maxConcurrent=e}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}get pending(){return this.queue.length}get active(){return this.running}};function H(e){return e==null?!1:typeof Blob<`u`&&e instanceof Blob||typeof File<`u`&&e instanceof File?!0:Array.isArray(e)?e.some(e=>H(e)):typeof e==`object`?Object.values(e).some(e=>H(e)):!1}function U(e,t,n){let r=t||new FormData;for(let[t,i]of Object.entries(e)){let e=n?`${n}[${t}]`:t;i!=null&&(typeof Blob<`u`&&i instanceof Blob?r.append(e,i):Array.isArray(i)?i.some(e=>H(e))?i.forEach(t=>{H(t)?r.append(e,t):r.append(e,JSON.stringify(t))}):r.append(e,JSON.stringify(i)):typeof i==`object`&&!(i instanceof Blob)?U(i,r,e):r.append(e,String(i)))}return r}function Be(e,t){return!t||e==null||typeof FormData<`u`&&e instanceof FormData||typeof Blob<`u`&&e instanceof Blob||typeof URLSearchParams<`u`&&e instanceof URLSearchParams||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof ReadableStream<`u`&&e instanceof ReadableStream||typeof e==`string`?e:typeof e==`object`&&H(e)?U(e):e}function Ve(e,t=!0){let n=Be(e,t);return n==null?{serialized:void 0,contentType:null}:typeof FormData<`u`&&n instanceof FormData?{serialized:n,contentType:null}:typeof URLSearchParams<`u`&&n instanceof URLSearchParams?{serialized:n,contentType:`application/x-www-form-urlencoded`}:typeof Blob<`u`&&n instanceof Blob?{serialized:n,contentType:n.type||`application/octet-stream`}:n instanceof ArrayBuffer||ArrayBuffer.isView(n)||typeof ReadableStream<`u`&&n instanceof ReadableStream?{serialized:n,contentType:`application/octet-stream`}:typeof n==`string`?{serialized:n,contentType:`text/plain`}:{serialized:JSON.stringify(n),contentType:`application/json`}}function W(e,t){return t?e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing path parameter: :${n}`);return encodeURIComponent(String(r))}):e}function G(e,t){if(e!==void 0)return e;if(t!==void 0)return t?`include`:`same-origin`}function He(e){return typeof e==`number`?{total:e}:typeof e==`object`&&e?{connection:e.connection,response:e.response,total:e.total}:{}}var K=class e{requestInterceptors=[];responseInterceptors=[];cache;config;requestQueue;pendingRequests=new Map;constructor(e={}){this.config={baseURL:e.baseURL??``,defaultHeaders:e.defaultHeaders??{"Content-Type":`application/json`},defaultTimeout:e.defaultTimeout??3e4,validateStatus:e.validateStatus??(e=>e>=200&&e<300),cacheStrategy:e.cacheStrategy??new Ie,maxConcurrent:e.maxConcurrent??0,defaultResponseType:e.defaultResponseType??`auto`,defaultHooks:e.defaultHooks??{},transformRequest:e.transformRequest,credentials:G(e.credentials,e.withCredentials),adapter:e.adapter,autoFormData:e.autoFormData??!0,debug:e.debug,logger:e.logger,transport:e.transport,nodeOptions:e.nodeOptions},this.cache=this.config.cacheStrategy,this.requestQueue=this.config.maxConcurrent>0?new ze(this.config.maxConcurrent):null}logDebug(e,t,n,r,i){let a=e??this.config.debug;if(!a||a===!0&&t===`verbose`)return;let o=`[Nexa HTTP] `+n,s=i??this.config.logger??console.log;r===void 0?s(o):s(o,r)}async request(e){let t={...this.config.defaultHooks,...e.hooks},n=e.debug??this.config.debug,r=e.logger??this.config.logger,o=this.getMaxAttempts(e.retry),s=this.getRetryStrategy(e.retry),c=Symbol(`request`);t.onStart?.(this.buildRequest(e)),this.requestQueue&&await this.requestQueue.acquire();try{for(let l=1;l<=o;l++){let u;try{if((e.method===`GET`||!e.method)&&e.cache?.enabled){let a=this.getCacheKey(e),o=this.cache.get(a);if(o){let a=o;return this.logDebug(n,`info`,`Cache hit for ${e.url}`,a,r),t.onSuccess?.(a),t.onFinally?.(),i(a)}}u=this.buildRequest(e),this.logDebug(n,`info`,`${u.method||`GET`} ${u.url}`,u,r);for(let e of this.requestInterceptors)u=await e.onRequest(u);this.logDebug(n,`verbose`,`Request after interceptors`,u,r),u=this.applyTransformRequestToRequest(u,e),this.logDebug(n,`verbose`,`Request after transformRequest`,u,r);let a=He(e.timeout??this.config.defaultTimeout),s=new AbortController;this.pendingRequests.set(c,s),e.signal&&e.signal.addEventListener(`abort`,()=>s.abort(),{once:!0}),this.logDebug(n,`info`,`Fetching (attempt ${l}/${o})`,{url:u.url,method:u.method},r);let d=performance.now(),f=await this.fetchWithTimeout(u,a,s),p=performance.now()-d;this.logDebug(n,`info`,`Response ${f.status} ${f.statusText}`,{duration:p,status:f.status,attempt:l},r);let m=f;e.onDownloadProgress&&f.body&&(m=this.trackDownloadProgress(f,e.onDownloadProgress));let h=e.responseType??this.config.defaultResponseType,g=await this.parseResponse(m,u,p,h,a.response);if(!this.config.validateStatus(g.status))throw{message:`Request failed with status ${g.status}`,status:g.status,statusText:g.statusText,code:`HTTP_ERROR`,request:u,response:g,config:e};if(e.validate){let t=e.validate.validate(g.data);if(!t.ok)return t}e.transform&&(g.data=e.transform.transform(g.data));let _=g;for(let e of this.responseInterceptors)_=await e.onResponse(_);if((e.method===`GET`||!e.method)&&e.cache?.enabled){let t=this.getCacheKey(e);this.cache.set(t,_,e.cache.ttlMs)}return t.onSuccess?.(_),this.logDebug(n,`verbose`,`Response data`,_.data,r),this.pendingRequests.delete(c),i(_)}catch(i){let d=this.normalizeError(i,u,e);if(this.logDebug(n,`info`,`Error: ${d.message}`,{error:d,attempt:l},r),l<o&&s.shouldRetry(l,d)){t.onRetry?.(l,d);let e=s.delayMs(l);this.logDebug(n,`info`,`Retrying after ${e}ms (attempt ${l+1}/${o})`,{error:d},r),await this.delay(e);continue}let f=d;for(let e of this.responseInterceptors)e.onError&&(f=await e.onError(f));return t.onError?.(f),this.pendingRequests.delete(c),a(f)}}let l={message:`Max retries exceeded`,code:`MAX_RETRIES`};return this.logDebug(n,`info`,`Max retries exceeded`,l,r),t.onError?.(l),a(l)}finally{t.onFinally?.(),this.requestQueue&&this.requestQueue.release()}}get(e,t){return this.request({...t,url:e,method:`GET`})}post(e,t,n){return this.request({...n,url:e,method:`POST`,body:t})}put(e,t,n){return this.request({...n,url:e,method:`PUT`,body:t})}patch(e,t,n){return this.request({...n,url:e,method:`PATCH`,body:t})}delete(e,t){return this.request({...t,url:e,method:`DELETE`})}head(e,t){return this.request({...t,url:e,method:`HEAD`})}options(e,t){return this.request({...t,url:e,method:`OPTIONS`})}addRequestInterceptor(e){return this.requestInterceptors.push(e),()=>{let t=this.requestInterceptors.indexOf(e);t!==-1&&this.requestInterceptors.splice(t,1)}}addResponseInterceptor(e){return this.responseInterceptors.push(e),()=>{let t=this.responseInterceptors.indexOf(e);t!==-1&&this.responseInterceptors.splice(t,1)}}clearInterceptors(){this.requestInterceptors=[],this.responseInterceptors=[]}clearCache(){this.cache.clear()}cancelAll(){for(let e of this.pendingRequests.values())e.abort();this.pendingRequests.clear()}get activeRequests(){return this.pendingRequests.size}get queueStats(){return{active:this.requestQueue?.active??this.pendingRequests.size,pending:this.requestQueue?.pending??0}}extend(t={}){let n=new e({baseURL:t.baseURL??this.config.baseURL,defaultHeaders:{...this.config.defaultHeaders,...t.defaultHeaders},credentials:G(t.credentials,t.withCredentials)??this.config.credentials,defaultTimeout:t.defaultTimeout??this.config.defaultTimeout,validateStatus:t.validateStatus??this.config.validateStatus,cacheStrategy:t.cacheStrategy??this.cache,maxConcurrent:t.maxConcurrent??this.config.maxConcurrent,defaultResponseType:t.defaultResponseType??this.config.defaultResponseType,defaultHooks:{...this.config.defaultHooks,...t.defaultHooks},transformRequest:t.transformRequest??this.config.transformRequest,adapter:t.adapter??this.config.adapter,autoFormData:t.autoFormData??this.config.autoFormData});for(let e of this.requestInterceptors)n.addRequestInterceptor(e);for(let e of this.responseInterceptors)n.addResponseInterceptor(e);return n}async*paginate(e,t,n={}){let r={...n};for(;;){let n=await this.get(e,r);if(!n.ok)break;yield t.getItems(n.value.data);let i=t.getNextPage(n.value.data,r);if(!i)break;r=i}}async poll(e,t,n={}){let r=t.maxAttempts??0;for(let i=1;r===0||i<=r;i++){let a=await this.get(e,n);if(!a.ok||(t.onPoll?.(a.value.data,i),t.until(a.value.data)))return a;if(r>0&&i>=r)break;await this.delay(t.intervalMs)}return a({message:`Polling exhausted after ${r} attempts`,code:`POLL_EXHAUSTED`})}buildRequest(e){let t=W(e.url,e.params),n=this.buildUrl(t,e.query),r=G(e.credentials,e.withCredentials)??this.config.credentials,i=e.transport??this.config.transport,a=e.nodeOptions??this.config.nodeOptions;return{url:n,method:e.method??`GET`,headers:{...this.config.defaultHeaders,...e.headers},body:e.body,query:e.query,params:e.params,timeout:e.timeout,signal:e.signal,credentials:r,adapter:e.adapter,autoFormData:e.autoFormData??this.config.autoFormData,transport:i,nodeOptions:a}}buildUrl(e,t){let n=this.config.baseURL+e;if(t&&Object.keys(t).length>0){let e=new URLSearchParams;Object.entries(t).forEach(([t,n])=>{e.append(t,String(n))}),n+=`?${e.toString()}`}return n}applyTransformRequestToRequest(e,t){let n=this.config.transformRequest,r=t.transformRequest,i=[];if(n&&(Array.isArray(n)?i.push(...n):i.push(n)),r&&(Array.isArray(r)?i.push(...r):i.push(r)),i.length===0)return e;let a=e.body,o=e.headers??{};for(let e of i)a=e(a,o);return{...e,body:a,headers:o}}getCacheKey(e){let t=W(e.url,e.params),n=e.query?JSON.stringify(e.query):``;return`${e.method??`GET`}:${t}${n?`:`+n:``}`}fetchWithTimeout(e,t,n){let{serialized:r,contentType:i}=Ve(e.body,e.autoFormData),a={...e.headers};i?a[`Content-Type`]=i:i===null&&r instanceof FormData&&delete a[`Content-Type`];let o=t.total??t.connection;return new Promise((t,i)=>{let s=null;o!==void 0&&(s=setTimeout(()=>{n.abort();let e=Error(`Request timed out`);e.name=`TimeoutError`,i(e)},o));let c={method:e.method,headers:a,body:r,signal:n.signal};e.credentials!==void 0&&(c.credentials=e.credentials);let l=e.transport??this.config.transport??`fetch`,u=e.nodeOptions??this.config.nodeOptions,d=e.adapter??this.config.adapter;d||=Fe(l,u),d(e.url,c).then(e=>{s&&clearTimeout(s),t(e)},e=>{s&&clearTimeout(s),i(e)})})}trackDownloadProgress(e,t){let n=parseInt(e.headers.get(`content-length`)||`0`,10),r=e.body?.getReader();if(!r)return e;let i=0,a=new ReadableStream({async pull(e){let{done:a,value:o}=await r.read();if(a){e.close();return}i+=o.byteLength,t({loaded:i,total:n,percent:n>0?Math.round(i/n*100):0}),e.enqueue(o)}});return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})}withTimeout(e,t,n=`Operation timed out`){return t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>{let e=Error(n);e.name=`TimeoutError`,i(e)},t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}async parseResponse(e,t,n,r,i){let a=await this.parseBody(e,r,i);return{status:e.status,statusText:e.statusText,headers:e.headers,data:a,request:t,duration:n}}async parseBody(e,t,n){let r=async e=>n!==void 0&&n>0?this.withTimeout(e,n,`Response timeout`):e;switch(t){case`json`:return await r(e.json());case`text`:return await r(e.text());case`blob`:return await r(e.blob());case`arrayBuffer`:return await r(e.arrayBuffer());case`formData`:return await r(e.formData());case`stream`:return e.body;default:{let t=e.headers.get(`content-type`)??``;if(t.includes(`application/json`))return await r(e.json());if(t.includes(`text/`))return await r(e.text());if(t.includes(`multipart/form-data`))return await r(e.formData());if(t.includes(`application/octet-stream`)||t.includes(`image/`)||t.includes(`audio/`)||t.includes(`video/`))return await r(e.blob());try{return await r(e.json())}catch{return await r(e.text())}}}}normalizeError(e,t,n){let r=(r,i)=>({message:i,code:r,originalError:e,request:t,config:n});return e instanceof Error&&e.name===`TimeoutError`?e.message.includes(`Response timeout`)?r(`RESPONSE_TIMEOUT`,e.message):r(`TIMEOUT`,`Request timed out`):e instanceof DOMException&&e.name===`AbortError`?r(`ABORTED`,`Request aborted`):e instanceof Error?e.name===`AbortError`||e.message.includes(`abort`)?r(`ABORTED`,`Request aborted`):{message:e.message,code:e.name===`TypeError`?`NETWORK_ERROR`:`UNKNOWN_ERROR`,originalError:e,request:t,config:n}:this.isHttpErrorDetails(e)?{...e,request:e.request??t,config:e.config??n}:{message:String(e),code:`UNKNOWN_ERROR`,originalError:e,request:t,config:n}}isHttpErrorDetails(e){return typeof e==`object`&&!!e&&`message`in e&&`code`in e}getMaxAttempts(e){return e?`shouldRetry`in e?100:e.maxAttempts??3:1}getRetryStrategy(e){if(!e)return{shouldRetry:()=>!1,delayMs:()=>0};if(`shouldRetry`in e)return e;let t=e;return t.on?new Re(t.maxAttempts??3,t.backoffMs??100,t.on):new Le(t.maxAttempts??3,t.backoffMs??100)}delay(e){return new Promise(t=>setTimeout(t,e))}},q=class extends Error{status;code;response;constructor(e,t,n,r){super(e),this.name=`HttpError`,this.status=t,this.code=n,this.response=r}};function Ue(e){return e instanceof q}function We(e){return new K(e)}function J(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var Ge=class{url;options;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;heartbeatTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set};constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new N}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}emitOpen(e){this.pluginManager.emit(`websocket:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(e){this.pluginManager.emit(`websocket:close`,this.url,e);for(let t of this.listeners.close)t(e)}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`websocket:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`websocket:message`,this.url,e);for(let t of this.listeners.message)t(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`websocket:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`websocket:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}startHeartbeat(){if(!this.options.heartbeat)return;let e=this.options.heartbeat.interval??3e4,t=this.options.heartbeat.pingMessage??`ping`,n=this.options.heartbeat.pongMessage??`pong`,r=!0,i=()=>{if(!r){this.pluginManager.emit(`websocket:heartbeat:timeout`,this.url),this.disconnect();return}r=!1,this.send(t),this.heartbeatTimer=setTimeout(i,e)};this.onMessage(e=>{let t=e.raw;typeof t==`string`&&t===n&&(r=!0)}),this.heartbeatTimer=setTimeout(i,e)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.stopHeartbeat()}},Y=class extends Ge{socket=null;messageTypeListeners=new Map;constructor(e,t={}){super(e,t)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`websocket:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this.socket?.close(),this.socket=null;let e=Error(`WebSocket connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this.socket=new WebSocket(this.url,this.options.protocols),this.socket.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.startHeartbeat(),this.pluginManager.emit(`websocket:connect:success`,this.url),e()},this.socket.onclose=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitClose(e),this.options.onClose?.(e),this.stopHeartbeat(),this.pluginManager.emit(`websocket:disconnected`,this.url,e.code,e.reason),e.code!==1e3&&!e.wasClean&&this.scheduleReconnect()},this.socket.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)},this.socket.onmessage=e=>{this.stats.messagesReceived++;let t={data:this.tryParseData(e.data),raw:e.data,type:`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`websocket:message:received`,this.url,t)}}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this.socket&&(this.updateStatus(`closing`),this.socket.close(1e3,`Client disconnected`),this.socket=null,this.updateStatus(`closed`))}send(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.socket.send(e),this.stats.messagesSent++,this.pluginManager.emit(`websocket:message:sent`,this.url,e)}sendJson(e){this.send(JSON.stringify(e))}onMessageType(e,t){return this.messageTypeListeners.has(e)||this.messageTypeListeners.set(e,new Set),this.messageTypeListeners.get(e).add(t),()=>{let n=this.messageTypeListeners.get(e);n&&(n.delete(t),n.size===0&&this.messageTypeListeners.delete(e))}}tryParseData(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}},Ke=class extends Y{async connect(){if(J())try{let{default:e}=await import(`ws`);return super.connect()}catch{throw Error(`WebSocket client for Node.js requires the "ws" package. Please install it: npm install ws`)}return super.connect()}};function qe(e,t={}){return J()?new Ke(e,t):new Y(e,t)}function X(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var Z=class{url;options;_source=null;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set,event:new Map};_lastEventId=null;constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new N}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`sse:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this._source?.close(),this._source=null;let e=Error(`SSE connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this._source=new EventSource(this.url),this._source.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.pluginManager.emit(`sse:connect:success`,this.url),e()},this._source.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`sse:connect:error`,this.url,e),this._source?.readyState===EventSource.CLOSED&&(this.emitClose(),this.options.onClose?.(),this.scheduleReconnect()),t(e)},this._source.onmessage=e=>{this.stats.messagesReceived++,this._lastEventId=e.lastEventId||this._lastEventId;let t={data:this.tryParseData(e.data),raw:e.data,type:e.type||`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`sse:message:received`,this.url,t);let n=e.type||`message`,r=this.listeners.event.get(n);if(r)for(let e of r)e(t.data)},this._source.addEventListener=this._source.addEventListener.bind(this._source)}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`sse:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this._source&&(this.updateStatus(`closing`),this._source.close(),this._source=null,this.updateStatus(`closed`),this.emitClose(),this.options.onClose?.())}send(e){throw Error(`SSE is a receive-only protocol. Use HTTP requests to send data to server.`)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onEvent(e,t){return this.listeners.event.has(e)||this.listeners.event.set(e,new Set),this.listeners.event.get(e).add(t),this._source&&!this._source[`on${e}`]&&this._source.addEventListener(e,n=>{t({data:this.tryParseData(n.data),raw:n.data,type:e,timestamp:Date.now()}.data)}),()=>{let n=this.listeners.event.get(e);n&&(n.delete(t),n.size===0&&this.listeners.event.delete(e))}}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}get lastEventId(){return this._lastEventId}get source(){return this._source}emitOpen(e){this.pluginManager.emit(`sse:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(){this.pluginManager.emit(`sse:close`,this.url);for(let e of this.listeners.close)e()}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`sse:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`sse:message`,this.url,e);for(let t of this.listeners.message)t(e)}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`sse:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`sse:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null)}tryParseData(e){try{return JSON.parse(e)}catch{return e}}},Je=class extends Z{async connect(){if(X())throw Error(`SSE client for Node.js requires a polyfill or custom implementation. Consider using a library like "eventsource" or implement using fetch with streaming.`);return super.connect()}};function Ye(e,t={}){return X()?new Je(e,t):new Z(e,t)}var Xe=class{name=`realtime`;setup(e){e.on(`websocket:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`websocket`,n)}),e.on(`websocket:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`websocket`,n)}),e.on(`websocket:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`websocket`,n,r)}),e.on(`sse:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`sse`,n)}),e.on(`sse:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`sse`,n)}),e.on(`sse:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`sse`,n,r)})}};function Ze(){return new Xe}var Q=class{adapter;method;urlPattern;constructor(e,t,n){this.adapter=e,this.method=t,this.urlPattern=n}reply(e,t,n){let r;return r=typeof e==`number`?{status:e,data:t,headers:n}:e,this.adapter.addRoute(this.method,this.urlPattern,r),this.adapter}replyOnce(e,t,n){let r;return r=typeof e==`number`?{status:e,data:t,headers:n}:e,this.adapter.addRoute(this.method,this.urlPattern,r,{times:1}),this.adapter}networkError(e=`Network Error`){return this.adapter.addRoute(this.method,this.urlPattern,{networkError:!0,errorMessage:e}),this.adapter}timeout(){return this.adapter.addRoute(this.method,this.urlPattern,{status:408,statusText:`Request Timeout`}),this.adapter}},$=class{routes=[];originalAdapter;mockClient;options;defaultResponse={status:200,statusText:`OK`,headers:{"content-type":`application/json`}};constructor(e,t={}){this.options=t;let n=this.createAdapter();if(typeof e.extend==`function`)this.mockClient=e.extend({adapter:n});else throw Error(`MockAdapter requires an HttpClient instance with extend() method`)}get client(){return this.mockClient}createAdapter(){return async(e,t)=>{let n=typeof e==`string`?e:e.url,r=t?.method||`GET`,i={url:n,method:r,headers:t?.headers,body:t?.body,signal:t?.signal??void 0},a=this.findMatchingRoute(r,n);if(!a)return this.options.passthrough?(this.originalAdapter||fetch)(e,t):new Response(JSON.stringify({error:`No mock route matched`}),{status:404,statusText:`Not Found`,headers:{"content-type":`application/json`}});a.timesCalled++;let o;if(o=typeof a.response==`function`?await a.response(i):a.response,o.networkError)throw TypeError(o.errorMessage||`Network Error`);let s=Object.fromEntries(Object.entries(o).filter(([e,t])=>t!==void 0)),c={...this.defaultResponse,...s};if(o.headers&&`content-type`in o.headers||(c.data instanceof Uint8Array||ArrayBuffer.isView(c.data)?c.headers={...c.headers,"content-type":`application/octet-stream`}:c.data&&typeof c.data==`object`&&(c.headers={...c.headers,"content-type":`application/json`})),c.delay||this.options.delay){let e=c.delay??this.options.delay;if(e&&e>0){let n=t?.signal;n?(n.throwIfAborted(),await new Promise((t,r)=>{let i=setTimeout(t,e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};n.addEventListener(`abort`,a,{once:!0}),setTimeout(()=>{n.removeEventListener(`abort`,a)},e)})):await new Promise(t=>setTimeout(t,e))}}let l=new Headers(c.headers),u=c.data;(c.status===204||c.status===205)&&l.delete(`content-type`);let d;if(u==null)d=``;else if(typeof u==`string`)d=u;else if(u instanceof Uint8Array||ArrayBuffer.isView(u)){let e;if(u.buffer instanceof ArrayBuffer)e=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);else{let t=new Uint8Array(u.byteLength);t.set(new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),e=t.buffer}return new Response(e,{status:c.status,statusText:c.statusText,headers:l})}else d=JSON.stringify(u);let f=d;return(c.status===204||c.status===205||f===``)&&(f=null),f===null&&l.delete(`content-type`),new Response(f,{status:c.status,statusText:c.statusText,headers:l})}}onGet(e){return new Q(this,`GET`,e)}onPost(e){return new Q(this,`POST`,e)}onPut(e){return new Q(this,`PUT`,e)}onPatch(e){return new Q(this,`PATCH`,e)}onDelete(e){return new Q(this,`DELETE`,e)}onAny(e){return new Q(this,`ANY`,e)}addRoute(e,t,n,r){return this.routes.push({method:e.toUpperCase(),urlPattern:t,response:n,timesCalled:0,times:r?.times}),this}reset(){this.routes=[]}restore(){}static reply(e,t,n){return{status:e,data:t,headers:n}}static networkError(e=`Network Error`){return{networkError:!0,errorMessage:e}}findMatchingRoute(e,t){let n=t;if(this.options.baseURL&&t.startsWith(this.options.baseURL))n=t.slice(this.options.baseURL.length);else try{if(n.includes(`://`)){let e=new URL(n);n=e.pathname+e.search}}catch{}for(let t of this.routes){if(t.times&&t.timesCalled>=t.times||t.method!==`ANY`&&t.method!==e.toUpperCase())continue;let r=!1;if(typeof t.urlPattern==`string`?r=n===t.urlPattern||n.startsWith(t.urlPattern):t.urlPattern instanceof RegExp&&(r=t.urlPattern.test(n)),r)return t}return null}};function Qe(e,t={}){return new $(e,t)}return e.AggressiveRetry=h,e.CachePlugin=ye,e.CacheStore=x,e.CircuitBreakerPlugin=Se,e.CircuitBreakerRetry=_,e.ConservativeRetry=g,e.DedupePlugin=be,e.Defer=me,e.Err=a,e.HttpClient=K,e.HttpError=q,e.LoggerPlugin=_e,e.MetricsPlugin=ve,e.MiddlewarePipeline=ce,e.MockAdapter=$,e.Ok=i,e.PluginManager=N,e.RateLimitPlugin=xe,e.RequestDeduplicator=C,e.TypedObservable=de,e.cacheMiddleware=ie,e.circuitBreakerMiddleware=se,e.createApiUrl=pe,e.createCacheMiddleware=S,e.createCircuitBreakerMiddleware=E,e.createDedupeMiddleware=w,e.createHttpClient=We,e.createMockClient=Qe,e.createPipeline=D,e.createProjectionTransformer=p,e.createRateLimitMiddleware=T,e.createRealtimePlugin=Ze,e.createRequiredFieldsValidator=s,e.createSSEClient=Ye,e.createSchemaValidator=o,e.createStreamingMiddleware=M,e.createTypeGuard=fe,e.createTypedApiClient=ue,e.createTypedRequest=O,e.createTypedResponse=le,e.createUrl=k,e.createWebSocketClient=qe,e.createWrapperTransformer=m,e.dedupeMiddleware=ae,e.handleStream=A,e.isHttpError=Ue,e.rateLimitMiddleware=oe,e.retry=re,e.streamToFile=he,e.streamingMiddleware=ge,e.transformCamelToSnake=d,e.transformFlatten=f,e.transformSnakeToCamel=u,e.validatorIsArray=c,e.validatorIsObject=l,e.withTimeout=ne,e})({});
1
+ var Nexa=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=e=>({ok:!0,value:e}),n=e=>({ok:!1,error:e});function r(e){return{validate(r){let i=r;for(let[t,r]of Object.entries(e))if(!r(i[t]))return n({message:`Validation failed: field "${t}" is invalid`,code:`VALIDATION_ERROR`});return t(r)}}}function i(e){return{validate(r){let i=r,a=e.filter(e=>!(e in i));return a.length>0?n({message:`Validation failed: missing fields: ${a.join(`, `)}`,code:`VALIDATION_ERROR`}):t(r)}}}var a={validate(e){return Array.isArray(e)?t(e):n({message:`Expected array response`,code:`VALIDATION_ERROR`})}},o={validate(e){return e&&typeof e==`object`&&!Array.isArray(e)?t(e):n({message:`Expected object response`,code:`VALIDATION_ERROR`})}},s={transform(e){return h(e,te)}},c={transform(e){return h(e,m)}},l={transform(e){return g(e)}};function u(e){return{transform(t){return Array.isArray(t)?t.map(t=>_(t,e)):_(t,e)}}}function d(e){return{transform(t){return{[e]:t}}}}var f=class{maxAttempts;constructor(e=5){this.maxAttempts=e}shouldRetry(e){return e<this.maxAttempts}delayMs(e){return e*50}},p=class{retryableStatuses=[408,429,500,502,503,504];maxAttempts;constructor(e=3){this.maxAttempts=e}shouldRetry(e,t){return e>=this.maxAttempts?!1:this.retryableStatuses.includes(t.status??0)||t.code===`TIMEOUT`}delayMs(e){return Math.min(1e3*2**(e-1),1e4)}},ee=class{failureCount=0;lastFailureTime=0;maxAttempts;failureThreshold;resetTimeMs;constructor(e=3,t=5,n=6e4){this.maxAttempts=e,this.failureThreshold=t,this.resetTimeMs=n}shouldRetry(e){return e>=this.maxAttempts||(Date.now()-this.lastFailureTime>this.resetTimeMs&&(this.failureCount=0),this.failureCount>=this.failureThreshold)?!1:(this.failureCount++,this.lastFailureTime=Date.now(),!0)}delayMs(e){return 100*2**(e-1)}reset(){this.failureCount=0,this.lastFailureTime=0}};function te(e){return e.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function m(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function h(e,t){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>h(e,t));let n={};for(let[r,i]of Object.entries(e))n[t(r)]=h(i,t);return n}function g(e,t=``){let n={};if(Array.isArray(e))e.forEach((e,r)=>{let i=t?`${t}[${r}]`:`[${r}]`;Object.assign(n,g(e,i))});else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e)){let e=t?`${t}.${r}`:r;i&&typeof i==`object`&&!Array.isArray(i)?Object.assign(n,g(i,e)):n[e]=i}return n}function _(e,t){if(!e||typeof e!=`object`)return{};let n=e,r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function ne(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return t.signal.addEventListener(`abort`,()=>clearTimeout(n),{once:!0}),t}async function v(e,t=3){try{return await e()}catch(n){if(t<=0)throw n;return v(e,t-1)}}var y=class{cache=new Map;get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),null):t.data:null}set(e,t,n=6e4){this.cache.set(e,{data:t,timestamp:Date.now(),ttlMs:n})}clear(){this.cache.clear()}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),!1):!0:!1}delete(e){this.cache.delete(e)}};function b(e={}){let t=e.cache||new y,n=e.ttlMs||6e4,r=e.cacheableStatuses||[200,304];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase(),o=a===`GET`,s=`${a}:${e.request.url}`;if(o&&t.has(s)){let n=t.get(s);if(n){e.response=n,e.state.cacheHit=!0;return}}await i(),o&&e.response&&r.includes(e.response.status)&&(t.set(s,e.response,n),e.state.cacheMiss=!0)}}var re=b(),x=class{pending=new Map;async execute(e,t){if(this.pending.has(e))return this.pending.get(e);let n=t().finally(()=>{this.pending.delete(e)});return this.pending.set(e,n),n}clear(){this.pending.clear()}};function S(e={}){let t=e.deduplicator||new x,n=e.includeBody??!1,r=e.methods||[`GET`];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase();if(!r.includes(a)){await i();return}let o=`${a}:${e.request.url}`;n&&e.request.body&&(o+=`:${JSON.stringify(e.request.body)}`);try{e.response=await t.execute(o,async()=>(await i(),e.response)),e.state.deduped=!0}catch(t){throw e.error=t,t}}}var ie=S();function C(e){return async t=>{let n=-1;async function r(i){if(i<=n)throw Error(`next() called multiple times`);n=i;let a=e[i];a&&await a(t,()=>r(i+1))}await r(0)}}var ae=class{middlewares=[];use(e){return this.middlewares.push(e),this}async execute(e){if(e&&typeof e==`object`&&`request`in e&&`response`in e){let t=e;return await C(this.middlewares.map(e=>typeof e==`function`&&e.length===2?e:async(t,n)=>{let r=e;t.response.body=await r(t.response.body),await n()}))(t),t.response.body}let t=e;for(let e of this.middlewares)t=await e(t);return t}clear(){this.middlewares=[]}};function w(e,t,n,r={}){return{ok:e>=200&&e<300,data:t,error:n,status:e,headers:r}}function T(e){return async(t,n)=>{let r=e.path,i;switch(e.method){case`GET`:i=await t.get(r);break;case`POST`:i=await t.post(r,n);break;case`PUT`:i=await t.put(r,n);break;case`PATCH`:i=await t.patch(r,n);break;case`DELETE`:i=await t.delete(r);break;default:throw Error(`Unsupported method: ${e.method}`)}return i}}function oe(e){return{request:async(t,n,r)=>{let i=e[n];return await T(i)(t,r)}}}var se=class e{subscribers=[];errorSubscribers=[];completeSubscribers=[];subscribe(e,t,n){return e&&this.subscribers.push(e),t&&this.errorSubscribers.push(t),n&&this.completeSubscribers.push(n),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e),this.errorSubscribers=this.errorSubscribers.filter(e=>e!==t),this.completeSubscribers=this.completeSubscribers.filter(e=>e!==n)}}}next(e){this.subscribers.forEach(t=>t(e))}error(e){this.errorSubscribers.forEach(t=>t(e))}complete(){this.completeSubscribers.forEach(e=>e())}map(t){let n=new e;return this.subscribe(e=>n.next(t(e)),e=>n.error(e),()=>n.complete()),n}filter(t){let n=new e;return this.subscribe(e=>{t(e)&&n.next(e)},e=>n.error(e),()=>n.complete()),n}};function E(e){return t=>{if(!e(t))throw TypeError(`Value does not match expected type`);return t}}function D(e){return e}function O(e){return D(e)}var k=class{_promise;resolveFunc;rejectFunc;constructor(){this._promise=new Promise((e,t)=>{this.resolveFunc=e,this.rejectFunc=t})}resolve(e){this.resolveFunc(e)}reject(e){this.rejectFunc(e)}get promise(){return this._promise}promise_(){return this._promise}};async function A(e,t={}){let n=e.body?.getReader();if(!n)throw Error(`Response body is not readable`);let r=[],i=0,a=parseInt(e.headers.get(`content-length`)||`0`,10);for(;;){let{done:e,value:o}=await n.read();if(e)break;r.push(o),i+=o.length,t.onChunk&&await t.onChunk(o),t.onProgress&&a>0&&t.onProgress(i,a)}return j(r,i)}function j(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}async function ce(e,t){let n=await A(e);if(typeof window>`u`)await(await import(`fs`).then(e=>e.promises)).writeFile(t,n);else{let e=new Blob([n.buffer],{type:`application/octet-stream`}),r=URL.createObjectURL(e),i=document.createElement(`a`);i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}}function M(e={}){return async(t,n)=>{if(await n(),t.response&&t.response.body&&typeof t.response.body==`object`&&`getReader`in t.response.body){let n=t.response.body.getReader(),r=[],i=0,a=parseInt(t.response.headers?.[`content-length`]||`0`,10);try{for(;;){let{done:o,value:s}=await n.read();if(o)break;r.push(s),i+=s.length,e.onChunk&&await e.onChunk(s),e.onProgress&&a>0&&e.onProgress(i,a),t.state.streamedChunks=t.state.streamedChunks||[],t.state.streamedChunks.push(s)}let o=j(r,i);t.response.body=o,t.state.streaming=!0,t.state.streamedBytes=i}finally{n.releaseLock()}}}}var le=M({onProgress:(e,t)=>{if(t>0){let n=Math.round(e/t*100);console.warn(`Streaming: ${n}% (${e}/${t} bytes)`)}}}),N=class{plugins=[];cache=new y;deduplicator=new x;middlewares=[];listeners=new Map;register(e){return this.plugins.push(e),e.setup(this),this.emit(`plugin:registered`,e.name),this}addMiddleware(e){return this.middlewares.push(e),this}getCache(){return this.cache}getDeduplicator(){return this.deduplicator}getPipeline(){return C(this.middlewares)}async executePipeline(e){await this.getPipeline()(e)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e),r=t;return n&&n.add(r),this}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}off(e,t){return this.listeners.get(e)?.delete(t),this}getPlugins(){return[...this.plugins]}clear(){this.plugins=[],this.middlewares=[],this.listeners.clear(),this.cache.clear(),this.deduplicator.clear()}},P={name:`logger`,setup(e){e.on(`request:start`,(...e)=>{let t=e[0];console.warn(`Request started: ${t}`)}),e.on(`request:success`,(...e)=>{let t=e[0],n=e[1];console.warn(`Request succeeded: ${t} (${n})`)}),e.on(`request:error`,(...e)=>{let t=e[0],n=e[1];console.error(`❌ Request failed: ${t}`,n)})}},F=class{name=`metrics`;metrics={requests:0,errors:0,totalTime:0,avgTime:0};setup(e){e.on(`request:complete`,(...e)=>{let t=e[0],n=e[1];this.metrics.requests++,this.metrics.totalTime+=t,this.metrics.avgTime=this.metrics.totalTime/this.metrics.requests,n||this.metrics.errors++})}getMetrics(){return{...this.metrics}}},I=class{name=`cache`;ttlMs;constructor(e=6e4){this.ttlMs=e}setup(e){e.addMiddleware(b({ttlMs:this.ttlMs}))}},L=class{name=`dedupe`;setup(e){e.addMiddleware(S())}},R=class{store=new y;get(e){return this.store.get(e)}set(e,t,n=6e4){this.store.set(e,t,n)}has(e){return this.store.has(e)}clear(){this.store.clear()}},z=class{maxAttempts;baseDelayMs;constructor(e=3,t=100){this.maxAttempts=e,this.baseDelayMs=t}shouldRetry(e,t){let n=t.status!==void 0&&t.status>=500,r=t.code===`NETWORK_ERROR`;return e<this.maxAttempts&&(n||r||t.code===`TIMEOUT`)}delayMs(e){let t=this.baseDelayMs*2**(e-1),n=Math.random()*t*.1;return Math.min(t+n,3e4)}},B=class{running=0;queue=[];maxConcurrent;constructor(e){this.maxConcurrent=e}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}get pending(){return this.queue.length}get active(){return this.running}};function V(e){return e==null?{serialized:void 0,contentType:null}:typeof e==`string`?{serialized:e,contentType:`text/plain`}:typeof FormData<`u`&&e instanceof FormData?{serialized:e,contentType:null}:typeof URLSearchParams<`u`&&e instanceof URLSearchParams?{serialized:e,contentType:`application/x-www-form-urlencoded`}:typeof Blob<`u`&&e instanceof Blob?{serialized:e,contentType:e.type||`application/octet-stream`}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof ReadableStream<`u`&&e instanceof ReadableStream?{serialized:e,contentType:`application/octet-stream`}:{serialized:JSON.stringify(e),contentType:`application/json`}}function H(e,t){return t?e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing path parameter: :${n}`);return encodeURIComponent(String(r))}):e}var U=class e{requestInterceptors=[];responseInterceptors=[];cache;devTracker;config;requestQueue;pendingRequests=new Set;constructor(e={}){this.config={baseURL:e.baseURL??``,defaultHeaders:e.defaultHeaders??{"Content-Type":`application/json`},defaultTimeout:e.defaultTimeout??3e4,validateStatus:e.validateStatus??(e=>e>=200&&e<300),cacheStrategy:e.cacheStrategy??new R,maxConcurrent:e.maxConcurrent??0,defaultResponseType:e.defaultResponseType??`auto`,defaultHooks:e.defaultHooks??{},adapter:e.adapter},this.cache=this.config.cacheStrategy,this.requestQueue=this.config.maxConcurrent>0?new B(this.config.maxConcurrent):null,this.devTracker=e.devTracker??null}async request(e){if(!this.requestInterceptors.length&&!this.responseInterceptors.length&&!e.cache?.enabled&&!e.hooks&&!Object.keys(this.config.defaultHooks).length&&!e.retry&&!e.validate&&!e.transform&&!this.requestQueue&&!e.onDownloadProgress&&!e.signal)return this.fastPath(e);let r=e.hooks?{...this.config.defaultHooks,...e.hooks}:this.config.defaultHooks,i=this.getMaxAttempts(e.retry),a=this.getRetryStrategy(e.retry),o=this.buildRequest(e);r.onStart?.(o),this.requestQueue&&await this.requestQueue.acquire();try{for(let s=1;s<=i;s++){let c;try{if((e.method===`GET`||!e.method)&&e.cache?.enabled){let n=this.getCacheKey(e),i=this.cache.get(n);if(i){let n=i;return this.trackDev({method:e.method??`GET`,url:o.url,status:n.status,duration:n.duration,cached:!0,ok:!0,headers:{...o.headers},body:e.body,retryCount:0}),r.onSuccess?.(n),r.onFinally?.(),t(n)}}let n=o;for(let e of this.requestInterceptors)n=await e.onRequest(n);c=new AbortController,this.pendingRequests.add(c),e.signal&&e.signal.addEventListener(`abort`,()=>c.abort(),{once:!0});let i=performance.now(),a=await this.fetchWithTimeout(n,this.resolveTimeoutMs(e.timeout??this.config.defaultTimeout),c),l=performance.now()-i,u=a;e.onDownloadProgress&&a.body&&(u=this.trackDownloadProgress(a,e.onDownloadProgress));let d=e.responseType??this.config.defaultResponseType,f=await this.parseResponse(u,n,l,d);if(!this.config.validateStatus(f.status))throw{message:`Request failed with status ${f.status}`,status:f.status,statusText:f.statusText,code:`HTTP_ERROR`};if(e.validate){let t=e.validate.validate(f.data);if(!t.ok)return t}e.transform&&(f.data=e.transform.transform(f.data));let p=f;for(let e of this.responseInterceptors)p=await e.onResponse(p);if((e.method===`GET`||!e.method)&&e.cache?.enabled){let t=this.getCacheKey(e);this.cache.set(t,p,e.cache.ttlMs)}return r.onSuccess?.(p),this.pendingRequests.delete(c),this.trackDev({method:e.method??`GET`,url:o.url,status:p.status,duration:p.duration,cached:!1,ok:!0,headers:{...o.headers},body:e.body,retryCount:s-1}),t(p)}catch(t){let l;if(l=t instanceof DOMException?t.name===`TimeoutError`?{message:`Request timed out`,code:`TIMEOUT`}:t.name===`AbortError`?{message:`Request aborted`,code:`ABORTED`}:{message:t.message,code:`UNKNOWN_ERROR`,originalError:t}:this.isHttpErrorDetails(t)?t:this.normalizeError(t),s<i&&a.shouldRetry(s,l)){r.onRetry?.(s,l);let e=a.delayMs(s);await this.delay(e);continue}let u=l;for(let e of this.responseInterceptors)e.onError&&(u=await e.onError(u));return r.onError?.(u),c&&this.pendingRequests.delete(c),this.trackDev({method:e.method??`GET`,url:o.url,status:u.status,duration:0,cached:!1,ok:!1,code:u.code,headers:{...o.headers},body:e.body,retryCount:s-1}),n(u)}}let s={message:`Max retries exceeded`,code:`MAX_RETRIES`};return r.onError?.(s),this.trackDev({method:e.method??`GET`,url:o.url,duration:0,cached:!1,ok:!1,code:`MAX_RETRIES`,headers:{...o.headers},body:e.body,retryCount:i}),n(s)}finally{r.onFinally?.(),this.requestQueue&&this.requestQueue.release()}}async fastPath(e){let r=H(e.url,e.params),i=this.buildUrl(r,e.query),{serialized:a,contentType:o}=V(e.body),s={...this.config.defaultHeaders,...e.headers};o?s[`Content-Type`]=o:a instanceof FormData&&delete s[`Content-Type`];let c=new AbortController,l=this.resolveTimeoutMs(e.timeout??this.config.defaultTimeout);this.pendingRequests.add(c);try{let r=performance.now(),a=await this.fetchWithTimeout({url:i,method:e.method??`GET`,headers:s,body:e.body,params:e.params},l,c),o=performance.now()-r,u=await this.parseBody(a,e.responseType??this.config.defaultResponseType);if(!this.config.validateStatus(a.status)){let t=n({message:`Request failed with status ${a.status}`,status:a.status,statusText:a.statusText,code:`HTTP_ERROR`});return this.trackDev({method:e.method??`GET`,url:i,status:a.status,duration:o,cached:!1,ok:!1,code:`HTTP_ERROR`,headers:s,body:e.body,retryCount:0}),this.pendingRequests.delete(c),t}return this.pendingRequests.delete(c),this.trackDev({method:e.method??`GET`,url:i,status:a.status,duration:o,cached:!1,ok:!0,headers:s,body:e.body,retryCount:0}),t({status:a.status,statusText:a.statusText,headers:a.headers,data:u,request:{url:i,method:e.method??`GET`,headers:s,body:e.body,params:e.params},duration:o})}catch(t){this.pendingRequests.delete(c);let r=`UNKNOWN_ERROR`;if(t instanceof DOMException?t.name===`TimeoutError`?r=`TIMEOUT`:t.name===`AbortError`&&(r=`ABORTED`):t instanceof Error&&(t.name===`TimeoutError`?r=`TIMEOUT`:t.name===`AbortError`||t.message.includes(`abort`)?r=`ABORTED`:t.name===`TypeError`&&(r=`NETWORK_ERROR`)),this.trackDev({method:e.method??`GET`,url:i,duration:performance.now()-(performance.now()-0),cached:!1,ok:!1,code:r,headers:s,body:e.body,retryCount:0}),t instanceof DOMException){if(t.name===`TimeoutError`)return n({message:`Request timed out`,code:`TIMEOUT`});if(t.name===`AbortError`)return n({message:`Request aborted`,code:`ABORTED`})}return t instanceof Error?t.name===`TimeoutError`?n({message:`Request timed out`,code:`TIMEOUT`}):t.name===`AbortError`||t.message.includes(`abort`)?n({message:`Request aborted`,code:`ABORTED`}):n({message:t.message,code:t.name===`TypeError`?`NETWORK_ERROR`:`UNKNOWN_ERROR`}):n({message:String(t),code:`UNKNOWN_ERROR`})}}get(e,t){return this.request({...t,url:e,method:`GET`})}post(e,t,n){return this.request({...n,url:e,method:`POST`,body:t})}put(e,t,n){return this.request({...n,url:e,method:`PUT`,body:t})}patch(e,t,n){return this.request({...n,url:e,method:`PATCH`,body:t})}delete(e,t){return this.request({...t,url:e,method:`DELETE`})}head(e,t){return this.request({...t,url:e,method:`HEAD`})}options(e,t){return this.request({...t,url:e,method:`OPTIONS`})}addRequestInterceptor(e){return this.requestInterceptors.push(e),()=>{let t=this.requestInterceptors.indexOf(e);t!==-1&&this.requestInterceptors.splice(t,1)}}addResponseInterceptor(e){return this.responseInterceptors.push(e),()=>{let t=this.responseInterceptors.indexOf(e);t!==-1&&this.responseInterceptors.splice(t,1)}}clearInterceptors(){this.requestInterceptors=[],this.responseInterceptors=[]}clearCache(){this.cache.clear()}cancelAll(){for(let e of this.pendingRequests)e.abort();this.pendingRequests.clear()}get activeRequests(){return this.pendingRequests.size}get queueStats(){return{active:this.requestQueue?.active??this.pendingRequests.size,pending:this.requestQueue?.pending??0}}extend(t={}){let n=new e({baseURL:t.baseURL??this.config.baseURL,defaultHeaders:{...this.config.defaultHeaders,...t.defaultHeaders},defaultTimeout:t.defaultTimeout??this.config.defaultTimeout,validateStatus:t.validateStatus??this.config.validateStatus,cacheStrategy:t.cacheStrategy??this.cache,maxConcurrent:t.maxConcurrent??this.config.maxConcurrent,defaultResponseType:t.defaultResponseType??this.config.defaultResponseType,defaultHooks:{...this.config.defaultHooks,...t.defaultHooks},adapter:t.adapter});for(let e of this.requestInterceptors)n.addRequestInterceptor(e);for(let e of this.responseInterceptors)n.addResponseInterceptor(e);return n}async*paginate(e,t,n={}){let r={...n};for(;;){let n=await this.get(e,r);if(!n.ok)break;yield t.getItems(n.value.data);let i=t.getNextPage(n.value.data,r);if(!i)break;r=i}}async poll(e,t,r={}){let i=t.maxAttempts??0;for(let n=1;i===0||n<=i;n++){let a=await this.get(e,r);if(!a.ok||(t.onPoll?.(a.value.data,n),t.until(a.value.data)))return a;if(i>0&&n>=i)break;await this.delay(t.intervalMs)}return n({message:`Polling exhausted after ${i} attempts`,code:`POLL_EXHAUSTED`})}buildRequest(e){let t=H(e.url,e.params);return{url:this.buildUrl(t,e.query),method:e.method??`GET`,headers:{...this.config.defaultHeaders,...e.headers},body:e.body,params:e.params}}buildUrl(e,t){let n=this.config.baseURL+e;if(t){let e=Object.keys(t);if(e.length>0){let r=new URLSearchParams;for(let n=0;n<e.length;n++)r.append(e[n],String(t[e[n]]));n+=`?${r.toString()}`}}return n}getCacheKey(e){let t=H(e.url,e.params),n=e.query?JSON.stringify(e.query):``;return`${e.method??`GET`}:${t}${n?`:`+n:``}`}fetchWithTimeout(e,t,n){let{serialized:r,contentType:i}=V(e.body),a={...e.headers};return i?a[`Content-Type`]=i:r instanceof FormData&&delete a[`Content-Type`],new Promise((i,o)=>{let s=setTimeout(()=>{n.abort(),o(new DOMException(`Request timed out`,`TimeoutError`))},t);(this.config.adapter??fetch)(e.url,{method:e.method,headers:a,body:r,signal:n.signal}).then(e=>{clearTimeout(s),i(e)},e=>{clearTimeout(s),o(e)})})}trackDownloadProgress(e,t){let n=parseInt(e.headers.get(`content-length`)||`0`,10),r=e.body?.getReader();if(!r)return e;let i=0,a=new ReadableStream({async pull(e){let{done:a,value:o}=await r.read();if(a){e.close();return}i+=o.byteLength,t({loaded:i,total:n,percent:n>0?Math.round(i/n*100):0}),e.enqueue(o)}});return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})}async parseResponse(e,t,n,r){let i=await this.parseBody(e,r);return{status:e.status,statusText:e.statusText,headers:e.headers,data:i,request:t,duration:n}}async parseBody(e,t){switch(t){case`json`:return await e.json();case`text`:return await e.text();case`blob`:return await e.blob();case`arrayBuffer`:return await e.arrayBuffer();case`formData`:return await e.formData();case`stream`:return e.body;default:{let t=e.headers.get(`content-type`)??``;if(t.includes(`application/json`))return await e.json();if(t.includes(`text/`))return await e.text();if(t.includes(`multipart/form-data`))return await e.formData();if(t.includes(`application/octet-stream`)||t.includes(`image/`)||t.includes(`audio/`)||t.includes(`video/`))return await e.blob();try{return await e.json()}catch{return await e.text()}}}}normalizeError(e){if(e instanceof DOMException){if(e.name===`TimeoutError`)return{message:`Request timed out`,code:`TIMEOUT`};if(e.name===`AbortError`)return{message:`Request aborted`,code:`ABORTED`}}return e instanceof Error?e.name===`TimeoutError`?{message:`Request timed out`,code:`TIMEOUT`}:e.name===`AbortError`||e.message.includes(`abort`)?{message:`Request aborted`,code:`ABORTED`}:{message:e.message,code:e.name===`TypeError`?`NETWORK_ERROR`:`UNKNOWN_ERROR`,originalError:e}:{message:String(e),code:`UNKNOWN_ERROR`,originalError:e}}isHttpErrorDetails(e){return typeof e==`object`&&!!e&&`message`in e&&`code`in e}getMaxAttempts(e){return e?`maxAttempts`in e?e.maxAttempts??1:100:1}getRetryStrategy(e){return e?`shouldRetry`in e?e:new z(e.maxAttempts,e.backoffMs):{shouldRetry:()=>!1,delayMs:()=>0}}resolveTimeoutMs(e){return typeof e==`number`?e:e.total??e.response??e.connection??3e4}delay(e){return new Promise(t=>setTimeout(t,e))}trackDev(e){this.devTracker&&this.devTracker.track(e)}},W=class extends Error{status;code;response;constructor(e,t,n,r){super(e),this.name=`HttpError`,this.status=t,this.code=n,this.response=r}};function ue(e){return e instanceof W}function de(e){return new U(e)}function G(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var fe=class{url;options;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;heartbeatTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set};constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new N}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}emitOpen(e){this.pluginManager.emit(`websocket:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(e){this.pluginManager.emit(`websocket:close`,this.url,e);for(let t of this.listeners.close)t(e)}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`websocket:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`websocket:message`,this.url,e);for(let t of this.listeners.message)t(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`websocket:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`websocket:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}startHeartbeat(){if(!this.options.heartbeat)return;let e=this.options.heartbeat.interval??3e4,t=this.options.heartbeat.pingMessage??`ping`,n=this.options.heartbeat.pongMessage??`pong`,r=!0,i=()=>{if(!r){this.pluginManager.emit(`websocket:heartbeat:timeout`,this.url),this.disconnect();return}r=!1,this.send(t),this.heartbeatTimer=setTimeout(i,e)};this.onMessage(e=>{let t=e.raw;typeof t==`string`&&t===n&&(r=!0)}),this.heartbeatTimer=setTimeout(i,e)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.stopHeartbeat()}},K=class extends fe{socket=null;messageTypeListeners=new Map;constructor(e,t={}){super(e,t)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`websocket:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this.socket?.close(),this.socket=null;let e=Error(`WebSocket connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this.socket=new WebSocket(this.url,this.options.protocols),this.socket.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.startHeartbeat(),this.pluginManager.emit(`websocket:connect:success`,this.url),e()},this.socket.onclose=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitClose(e),this.options.onClose?.(e),this.stopHeartbeat(),this.pluginManager.emit(`websocket:disconnected`,this.url,e.code,e.reason),e.code!==1e3&&!e.wasClean&&this.scheduleReconnect()},this.socket.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)},this.socket.onmessage=e=>{this.stats.messagesReceived++;let t={data:this.tryParseData(e.data),raw:e.data,type:`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`websocket:message:received`,this.url,t)}}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this.socket&&(this.updateStatus(`closing`),this.socket.close(1e3,`Client disconnected`),this.socket=null,this.updateStatus(`closed`))}send(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.socket.send(e),this.stats.messagesSent++,this.pluginManager.emit(`websocket:message:sent`,this.url,e)}sendJson(e){this.send(JSON.stringify(e))}onMessageType(e,t){return this.messageTypeListeners.has(e)||this.messageTypeListeners.set(e,new Set),this.messageTypeListeners.get(e).add(t),()=>{let n=this.messageTypeListeners.get(e);n&&(n.delete(t),n.size===0&&this.messageTypeListeners.delete(e))}}tryParseData(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}},pe=class extends K{async connect(){if(G())try{let{default:e}=await import(`ws`);return super.connect()}catch{throw Error(`WebSocket client for Node.js requires the "ws" package. Please install it: npm install ws`)}return super.connect()}};function me(e,t={}){return G()?new pe(e,t):new K(e,t)}function q(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var J=class{url;options;_source=null;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set,event:new Map};_lastEventId=null;constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new N}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`sse:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this._source?.close(),this._source=null;let e=Error(`SSE connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this._source=new EventSource(this.url),this._source.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.pluginManager.emit(`sse:connect:success`,this.url),e()},this._source.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`sse:connect:error`,this.url,e),this._source?.readyState===EventSource.CLOSED&&(this.emitClose(),this.options.onClose?.(),this.scheduleReconnect()),t(e)},this._source.onmessage=e=>{this.stats.messagesReceived++,this._lastEventId=e.lastEventId||this._lastEventId;let t={data:this.tryParseData(e.data),raw:e.data,type:e.type||`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`sse:message:received`,this.url,t);let n=e.type||`message`,r=this.listeners.event.get(n);if(r)for(let e of r)e(t.data)},this._source.addEventListener=this._source.addEventListener.bind(this._source)}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`sse:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this._source&&(this.updateStatus(`closing`),this._source.close(),this._source=null,this.updateStatus(`closed`),this.emitClose(),this.options.onClose?.())}send(e){throw Error(`SSE is a receive-only protocol. Use HTTP requests to send data to server.`)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onEvent(e,t){return this.listeners.event.has(e)||this.listeners.event.set(e,new Set),this.listeners.event.get(e).add(t),this._source&&!this._source[`on${e}`]&&this._source.addEventListener(e,n=>{t({data:this.tryParseData(n.data),raw:n.data,type:e,timestamp:Date.now()}.data)}),()=>{let n=this.listeners.event.get(e);n&&(n.delete(t),n.size===0&&this.listeners.event.delete(e))}}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}get lastEventId(){return this._lastEventId}get source(){return this._source}emitOpen(e){this.pluginManager.emit(`sse:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(){this.pluginManager.emit(`sse:close`,this.url);for(let e of this.listeners.close)e()}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`sse:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`sse:message`,this.url,e);for(let t of this.listeners.message)t(e)}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`sse:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`sse:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null)}tryParseData(e){try{return JSON.parse(e)}catch{return e}}},he=class extends J{async connect(){if(q())throw Error(`SSE client for Node.js requires a polyfill or custom implementation. Consider using a library like "eventsource" or implement using fetch with streaming.`);return super.connect()}};function ge(e,t={}){return q()?new he(e,t):new J(e,t)}var _e=class{name=`realtime`;setup(e){e.on(`websocket:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`websocket`,n)}),e.on(`websocket:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`websocket`,n)}),e.on(`websocket:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`websocket`,n,r)}),e.on(`sse:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`sse`,n)}),e.on(`sse:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`sse`,n)}),e.on(`sse:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`sse`,n,r)})}};function ve(){return new _e}var Y=class{history=[];maxHistory;listeners=new Set;startTime=Date.now();config;constructor(e={}){this.maxHistory=e.maxHistory??500,this.config={enabled:e.enabled??!0,maxHistory:this.maxHistory,keyboardShortcut:e.keyboardShortcut??`ctrl+shift+n`,position:e.position??`bottom-right`,theme:e.theme??`dark`}}track(e){let t={...e,id:this.generateId(),timestamp:Date.now()};this.history.unshift(t),this.history.length>this.maxHistory&&this.history.pop();for(let e of this.listeners)e(t);return t}getHistory(){return this.history}getMetrics(){let e=this.history.map(e=>e.duration),t=(Date.now()-this.startTime)/1e3;return{totalRequests:this.history.length,successfulRequests:this.history.filter(e=>e.ok).length,failedRequests:this.history.filter(e=>!e.ok).length,cachedRequests:this.history.filter(e=>e.cached).length,avgDuration:e.length?e.reduce((e,t)=>e+t,0)/e.length:0,maxDuration:e.length?Math.max(...e):0,minDuration:e.length?Math.min(...e):0,requestsPerSecond:t>0?this.history.length/t:0,slowestRequests:[...this.history].sort((e,t)=>t.duration-e.duration).slice(0,5)}}clear(){this.history=[],this.startTime=Date.now()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getConfig(){return this.config}generateId(){return`${Date.now()}-${Math.random().toString(36).slice(2,8)}`}},X={close:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>`,chevron:`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>`,back:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>`,retry:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 4v6h6M23 20v-6h-6"/><path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/></svg>`,clear:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>`,search:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>`,clock:`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>`,zap:`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`},Z={bg:`#09090b`,bgElevated:`#18181b`,border:`#27272a`,borderFocus:`#3f3f46`,text:`#fafafa`,textMuted:`#a1a1aa`,textDim:`#71717a`,accent:`#3b82f6`,accentHover:`#2563eb`,success:`#22c55e`,successBg:`rgba(34, 197, 94, 0.1)`,error:`#ef4444`,errorBg:`rgba(239, 68, 68, 0.1)`,warning:`#f59e0b`,get:`#22c55e`,post:`#3b82f6`,put:`#f59e0b`,patch:`#a855f7`,delete:`#ef4444`},ye=`
2
+ #nexa-dev-overlay * { margin: 0; padding: 0; box-sizing: border-box; }
3
+ #nexa-dev-overlay {
4
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
5
+ background: ${Z.bg};
6
+ color: ${Z.text};
7
+ border: 1px solid ${Z.border};
8
+ border-radius: 16px;
9
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255,255,255,0.03);
10
+ overflow: hidden;
11
+ }
12
+ #nexa-dev-overlay .nexa-header {
13
+ display: flex;
14
+ align-items: center;
15
+ justify-content: space-between;
16
+ padding: 16px 20px;
17
+ border-bottom: 1px solid ${Z.border};
18
+ background: ${Z.bgElevated};
19
+ }
20
+ #nexa-dev-overlay .nexa-header-left {
21
+ display: flex;
22
+ align-items: center;
23
+ gap: 12px;
24
+ }
25
+ #nexa-dev-overlay .nexa-logo {
26
+ width: 32px;
27
+ height: 32px;
28
+ display: flex;
29
+ align-items: center;
30
+ justify-content: center;
31
+ background: ${Z.bgElevated};
32
+ border-radius: 8px;
33
+ overflow: hidden;
34
+ }
35
+ #nexa-dev-overlay .nexa-title {
36
+ font-size: 15px;
37
+ font-weight: 600;
38
+ letter-spacing: -0.02em;
39
+ }
40
+ #nexa-dev-overlay .nexa-header-actions {
41
+ display: flex;
42
+ gap: 4px;
43
+ }
44
+ #nexa-dev-overlay .nexa-icon-btn {
45
+ width: 32px;
46
+ height: 32px;
47
+ display: flex;
48
+ align-items: center;
49
+ justify-content: center;
50
+ background: transparent;
51
+ border: none;
52
+ border-radius: 8px;
53
+ color: ${Z.textMuted};
54
+ cursor: pointer;
55
+ transition: all 0.15s;
56
+ }
57
+ #nexa-dev-overlay .nexa-icon-btn:hover {
58
+ background: ${Z.border};
59
+ color: ${Z.text};
60
+ }
61
+ #nexa-dev-overlay .nexa-metrics-bar {
62
+ display: flex;
63
+ gap: 4px;
64
+ padding: 12px 16px;
65
+ background: ${Z.bg};
66
+ border-bottom: 1px solid ${Z.border};
67
+ }
68
+ #nexa-dev-overlay .nexa-metric {
69
+ flex: 1;
70
+ display: flex;
71
+ flex-direction: column;
72
+ align-items: center;
73
+ gap: 2px;
74
+ padding: 8px 12px;
75
+ background: ${Z.bgElevated};
76
+ border-radius: 10px;
77
+ transition: all 0.2s;
78
+ }
79
+ #nexa-dev-overlay .nexa-metric:hover {
80
+ background: ${Z.border};
81
+ }
82
+ #nexa-dev-overlay .nexa-metric-value {
83
+ font-size: 18px;
84
+ font-weight: 700;
85
+ letter-spacing: -0.03em;
86
+ color: ${Z.text};
87
+ }
88
+ #nexa-dev-overlay .nexa-metric-ok .nexa-metric-value { color: ${Z.success}; }
89
+ #nexa-dev-overlay .nexa-metric-err .nexa-metric-value { color: ${Z.error}; }
90
+ #nexa-dev-overlay .nexa-metric-label {
91
+ font-size: 11px;
92
+ color: ${Z.textDim};
93
+ text-transform: uppercase;
94
+ letter-spacing: 0.05em;
95
+ }
96
+ #nexa-dev-overlay .nexa-search {
97
+ padding: 12px 16px;
98
+ border-bottom: 1px solid ${Z.border};
99
+ position: relative;
100
+ }
101
+ #nexa-dev-overlay .nexa-search-icon {
102
+ position: absolute;
103
+ left: 28px;
104
+ top: 50%;
105
+ transform: translateY(-50%);
106
+ color: ${Z.textDim};
107
+ }
108
+ #nexa-dev-overlay .nexa-search-input {
109
+ width: 100%;
110
+ padding: 10px 12px 10px 38px;
111
+ background: ${Z.bg};
112
+ border: 1px solid ${Z.border};
113
+ border-radius: 10px;
114
+ color: ${Z.text};
115
+ font-size: 13px;
116
+ outline: none;
117
+ transition: all 0.15s;
118
+ }
119
+ #nexa-dev-overlay .nexa-search-input:focus {
120
+ border-color: ${Z.accent};
121
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
122
+ }
123
+ #nexa-dev-overlay .nexa-search-input::placeholder { color: ${Z.textDim}; }
124
+ #nexa-dev-overlay .nexa-tabs {
125
+ display: flex;
126
+ gap: 4px;
127
+ padding: 8px 16px;
128
+ border-bottom: 1px solid ${Z.border};
129
+ }
130
+ #nexa-dev-overlay .nexa-tab {
131
+ display: flex;
132
+ align-items: center;
133
+ gap: 8px;
134
+ padding: 8px 14px;
135
+ background: transparent;
136
+ border: none;
137
+ border-radius: 8px;
138
+ color: ${Z.textMuted};
139
+ font-size: 13px;
140
+ font-weight: 500;
141
+ cursor: pointer;
142
+ transition: all 0.15s;
143
+ }
144
+ #nexa-dev-overlay .nexa-tab:hover { color: ${Z.text}; background: ${Z.bgElevated}; }
145
+ #nexa-dev-overlay .nexa-tab-active { color: ${Z.text}; background: ${Z.accent} !important; }
146
+ #nexa-dev-overlay .nexa-tab-count {
147
+ font-size: 11px;
148
+ padding: 2px 6px;
149
+ background: rgba(255,255,255,0.1);
150
+ border-radius: 10px;
151
+ }
152
+ #nexa-dev-overlay .nexa-body { flex: 1; overflow: hidden; display: flex; }
153
+ #nexa-dev-overlay .nexa-panel { display: none; width: 100%; overflow-y: auto; }
154
+ #nexa-dev-overlay .nexa-panel-active { display: block; }
155
+ #nexa-dev-overlay .nexa-request-list {
156
+ padding: 8px;
157
+ display: flex;
158
+ flex-direction: column;
159
+ gap: 4px;
160
+ }
161
+ #nexa-dev-overlay .nexa-request-item {
162
+ display: flex;
163
+ align-items: center;
164
+ justify-content: space-between;
165
+ padding: 12px 14px;
166
+ background: ${Z.bgElevated};
167
+ border: 1px solid transparent;
168
+ border-radius: 12px;
169
+ cursor: pointer;
170
+ transition: all 0.15s;
171
+ animation: nexaFadeIn 0.2s ease forwards;
172
+ opacity: 0;
173
+ }
174
+ @keyframes nexaFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
175
+ #nexa-dev-overlay .nexa-request-item:hover {
176
+ background: ${Z.border};
177
+ border-color: ${Z.borderFocus};
178
+ transform: translateX(2px);
179
+ }
180
+ #nexa-dev-overlay .nexa-req-left {
181
+ display: flex;
182
+ align-items: center;
183
+ gap: 10px;
184
+ }
185
+ #nexa-dev-overlay .nexa-method {
186
+ font-size: 11px;
187
+ font-weight: 700;
188
+ padding: 4px 8px;
189
+ border-radius: 6px;
190
+ text-transform: uppercase;
191
+ letter-spacing: 0.03em;
192
+ }
193
+ #nexa-dev-overlay .nexa-method-get { background: ${Z.successBg}; color: ${Z.get}; }
194
+ #nexa-dev-overlay .nexa-method-post { background: rgba(59, 130, 246, 0.15); color: ${Z.post}; }
195
+ #nexa-dev-overlay .nexa-method-put { background: rgba(245, 158, 11, 0.15); color: ${Z.put}; }
196
+ #nexa-dev-overlay .nexa-method-patch { background: rgba(168, 85, 247, 0.15); color: ${Z.patch}; }
197
+ #nexa-dev-overlay .nexa-method-delete { background: ${Z.errorBg}; color: ${Z.delete}; }
198
+ #nexa-dev-overlay .nexa-status {
199
+ font-size: 12px;
200
+ font-weight: 600;
201
+ padding: 4px 8px;
202
+ border-radius: 6px;
203
+ min-width: 36px;
204
+ text-align: center;
205
+ }
206
+ #nexa-dev-overlay .nexa-ok { background: ${Z.successBg}; color: ${Z.success}; }
207
+ #nexa-dev-overlay .nexa-err { background: ${Z.errorBg}; color: ${Z.error}; }
208
+ #nexa-dev-overlay .nexa-url {
209
+ font-size: 13px;
210
+ color: ${Z.textMuted};
211
+ max-width: 180px;
212
+ overflow: hidden;
213
+ text-overflow: ellipsis;
214
+ white-space: nowrap;
215
+ }
216
+ #nexa-dev-overlay .nexa-req-right {
217
+ display: flex;
218
+ align-items: center;
219
+ gap: 8px;
220
+ }
221
+ #nexa-dev-overlay .nexa-badge {
222
+ font-size: 10px;
223
+ font-weight: 600;
224
+ padding: 3px 6px;
225
+ border-radius: 6px;
226
+ text-transform: uppercase;
227
+ letter-spacing: 0.03em;
228
+ }
229
+ #nexa-dev-overlay .nexa-badge-cache { background: rgba(168, 85, 247, 0.15); color: #a855f7; }
230
+ #nexa-dev-overlay .nexa-badge-retry { background: rgba(245, 158, 11, 0.15); color: ${Z.warning}; }
231
+ #nexa-dev-overlay .nexa-duration {
232
+ font-size: 12px;
233
+ font-weight: 600;
234
+ color: ${Z.textDim};
235
+ font-variant-numeric: tabular-nums;
236
+ }
237
+ #nexa-dev-overlay .nexa-slow { color: ${Z.warning}; }
238
+ #nexa-dev-overlay .nexa-empty {
239
+ display: flex;
240
+ flex-direction: column;
241
+ align-items: center;
242
+ justify-content: center;
243
+ padding: 48px 24px;
244
+ text-align: center;
245
+ color: ${Z.textDim};
246
+ }
247
+ #nexa-dev-overlay .nexa-empty svg { margin-bottom: 16px; opacity: 0.4; }
248
+ #nexa-dev-overlay .nexa-empty p { font-size: 14px; color: ${Z.textMuted}; margin-bottom: 4px; }
249
+ #nexa-dev-overlay .nexa-empty span { font-size: 12px; color: ${Z.textDim}; }
250
+ #nexa-dev-overlay .nexa-detail {
251
+ flex-direction: column;
252
+ padding: 16px;
253
+ display: none;
254
+ overflow-y: auto;
255
+ max-height: 100%;
256
+ }
257
+ #nexa-dev-overlay .nexa-detail-active { display: flex; }
258
+ #nexa-dev-overlay .nexa-detail-header {
259
+ display: flex;
260
+ align-items: center;
261
+ justify-content: space-between;
262
+ margin-bottom: 16px;
263
+ }
264
+ #nexa-dev-overlay .nexa-btn {
265
+ display: flex;
266
+ align-items: center;
267
+ gap: 6px;
268
+ padding: 8px 14px;
269
+ background: ${Z.bgElevated};
270
+ border: 1px solid ${Z.border};
271
+ border-radius: 8px;
272
+ color: ${Z.textMuted};
273
+ font-size: 13px;
274
+ font-weight: 500;
275
+ cursor: pointer;
276
+ transition: all 0.15s;
277
+ }
278
+ #nexa-dev-overlay .nexa-btn:hover { background: ${Z.border}; color: ${Z.text}; }
279
+ #nexa-dev-overlay .nexa-btn-retry { background: ${Z.successBg}; border-color: transparent; color: ${Z.success}; }
280
+ #nexa-dev-overlay .nexa-btn-retry:hover { background: ${Z.success}; color: white; }
281
+ #nexa-dev-overlay .nexa-card {
282
+ background: ${Z.bgElevated};
283
+ border: 1px solid ${Z.border};
284
+ border-radius: 12px;
285
+ padding: 16px;
286
+ margin-bottom: 12px;
287
+ }
288
+ #nexa-dev-overlay .nexa-card h3 {
289
+ font-size: 12px;
290
+ font-weight: 600;
291
+ color: ${Z.textDim};
292
+ text-transform: uppercase;
293
+ letter-spacing: 0.05em;
294
+ margin-bottom: 12px;
295
+ }
296
+ #nexa-dev-overlay .nexa-row {
297
+ display: flex;
298
+ justify-content: space-between;
299
+ align-items: center;
300
+ padding: 6px 0;
301
+ font-size: 13px;
302
+ border-bottom: 1px solid ${Z.border};
303
+ }
304
+ #nexa-dev-overlay .nexa-row:last-child { border-bottom: none; }
305
+ #nexa-dev-overlay .nexa-row span { color: ${Z.textMuted}; }
306
+ #nexa-dev-overlay .nexa-row strong { color: ${Z.text}; font-weight: 500; font-variant-numeric: tabular-nums; }
307
+ #nexa-dev-overlay .nexa-row .nexa-ok { color: ${Z.success}; }
308
+ #nexa-dev-overlay .nexa-row .nexa-err { color: ${Z.error}; }
309
+ #nexa-dev-overlay .nexa-code {
310
+ background: ${Z.bg};
311
+ border-radius: 8px;
312
+ padding: 12px;
313
+ font-size: 11px;
314
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
315
+ color: ${Z.textMuted};
316
+ overflow-x: auto;
317
+ white-space: pre;
318
+ max-height: 200px;
319
+ line-height: 1.6;
320
+ }
321
+ #nexa-dev-overlay .nexa-url-full {
322
+ font-size: 12px;
323
+ word-break: break-all;
324
+ color: ${Z.accent};
325
+ }
326
+ #nexa-dev-overlay .nexa-metrics-content {
327
+ padding: 16px;
328
+ display: flex;
329
+ flex-direction: column;
330
+ gap: 12px;
331
+ }
332
+ #nexa-dev-overlay .nexa-slow-req {
333
+ display: flex;
334
+ align-items: center;
335
+ gap: 8px;
336
+ }
337
+ `,be=class{panel=null;tracker;visible=!1;selectedRequest=null;config;searchQuery=``;removeTrackerListener=null;keyboardShortcutHandler=null;globalKeyboardHandler=null;constructor(e){this.tracker=e,this.config=e.getConfig(),this.canUseDOM()&&(this.setupKeyboardShortcut(),this.createPanel())}show(){this.panel&&(this.panel.style.display=`flex`,this.panel.style.opacity=`0`,this.panel.style.transform=`scale(0.96) translateY(8px)`,(typeof requestAnimationFrame==`function`?requestAnimationFrame:e=>setTimeout(e,0))(()=>{this.panel.style.transition=`all 0.25s cubic-bezier(0.16, 1, 0.3, 1)`,this.panel.style.opacity=`1`,this.panel.style.transform=`scale(1) translateY(0)`}),this.visible=!0)}hide(){this.panel&&(this.panel.style.transition=`all 0.15s ease-out`,this.panel.style.opacity=`0`,this.panel.style.transform=`scale(0.96) translateY(8px)`,setTimeout(()=>{this.panel&&(this.panel.style.display=`none`)},150),this.visible=!1)}toggle(){this.visible?this.hide():this.show()}destroy(){this.keyboardShortcutHandler&&=(document.removeEventListener(`keydown`,this.keyboardShortcutHandler),null),this.globalKeyboardHandler&&=(document.removeEventListener(`keydown`,this.globalKeyboardHandler),null),this.removeTrackerListener?.(),this.removeTrackerListener=null,this.panel?.remove(),this.panel=null,this.visible=!1,this.selectedRequest=null}setupKeyboardShortcut(){let e=this.config.keyboardShortcut.split(`+`),t=new Set(e.map(e=>e.toLowerCase()));this.keyboardShortcutHandler=e=>{let n=new Set;e.ctrlKey&&n.add(`ctrl`),e.metaKey&&(n.add(`meta`),n.add(`cmd`),n.add(`ctrl`)),e.shiftKey&&n.add(`shift`),e.altKey&&n.add(`alt`),(e.key&&e.key.length===1||e.key.length>1)&&n.add(e.key.toLowerCase());let r=!0;for(let e of t)if(!n.has(e)){r=!1;break}r&&n.size===t.size&&(e.preventDefault(),this.toggle())},document.addEventListener(`keydown`,this.keyboardShortcutHandler)}createPanel(){if(!this.canUseDOM())return;this.panel=document.createElement(`div`),this.panel.id=`nexa-dev-overlay`;let e=this.config.position,t=e.includes(`bottom`),n=e.includes(`right`);this.panel.style.cssText=`
338
+ position: fixed;
339
+ ${t?`bottom: 24px;`:`top: 24px;`}
340
+ ${n?`right: 24px;`:`left: 24px;`}
341
+ width: 420px;
342
+ max-height: 70vh;
343
+ z-index: 2147483647;
344
+ display: flex;
345
+ flex-direction: column;
346
+ overflow: hidden;
347
+ `,this.panel.innerHTML=`<style>${ye}</style>
348
+
349
+ <div class="nexa-header">
350
+ <div class="nexa-header-left">
351
+ <div class="nexa-logo">
352
+ <span style="display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;color:#fff;background:linear-gradient(135deg,#3b82f6,#238636);width:18px;height:18px;border-radius:4px;">N</span>
353
+ </div>
354
+ <span class="nexa-title">Nexa DevTools</span>
355
+ </div>
356
+ <div class="nexa-header-actions">
357
+ <button class="nexa-icon-btn nexa-btn-clear" title="Clear history">${X.clear}</button>
358
+ <button class="nexa-icon-btn nexa-btn-close" title="Close (Esc)">${X.close}</button>
359
+ </div>
360
+ </div>
361
+
362
+ <div class="nexa-metrics-bar">
363
+ <div class="nexa-metric"><span class="nexa-metric-value" data-metric="total">0</span><span class="nexa-metric-label">Requests</span></div>
364
+ <div class="nexa-metric"><span class="nexa-metric-value" data-metric="avg">0ms</span><span class="nexa-metric-label">Avg</span></div>
365
+ <div class="nexa-metric"><span class="nexa-metric-value" data-metric="rate">0/s</span><span class="nexa-metric-label">Throughput</span></div>
366
+ <div class="nexa-metric nexa-metric-ok"><span class="nexa-metric-value" data-metric="success">0</span><span class="nexa-metric-label">Success</span></div>
367
+ <div class="nexa-metric nexa-metric-err"><span class="nexa-metric-value" data-metric="fail">0</span><span class="nexa-metric-label">Failed</span></div>
368
+ </div>
369
+
370
+ <div class="nexa-search">
371
+ <span class="nexa-search-icon">${X.search}</span>
372
+ <input type="text" class="nexa-search-input" placeholder="Filter by URL, method, or status..." />
373
+ </div>
374
+
375
+ <div class="nexa-tabs">
376
+ <button class="nexa-tab nexa-tab-active" data-tab="requests"><span>Requests</span><span class="nexa-tab-count" data-count="requests">0</span></button>
377
+ <button class="nexa-tab" data-tab="metrics"><span>Metrics</span></button>
378
+ </div>
379
+
380
+ <div class="nexa-body">
381
+ <div class="nexa-panel nexa-panel-active" data-panel="requests"><div class="nexa-request-list"></div></div>
382
+ <div class="nexa-panel" data-panel="metrics"><div class="nexa-metrics-content"></div></div>
383
+ </div>
384
+
385
+ <div class="nexa-detail" style="display:none">
386
+ <div class="nexa-detail-header">
387
+ <button class="nexa-btn nexa-btn-back">${X.back} Back</button>
388
+ <button class="nexa-btn nexa-btn-retry">${X.retry} Retry</button>
389
+ </div>
390
+ <div class="nexa-detail-body"></div>
391
+ </div>
392
+ `,document.body.appendChild(this.panel),this.bindEvents(),this.removeTrackerListener=this.tracker.onChange(()=>this.render()),this.hide(),this.globalKeyboardHandler=e=>{if(e.key===`Escape`&&this.visible){this.hide();return}if(this.visible&&(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`f`){e.preventDefault();let t=this.panel?.querySelector(`.nexa-search-input`);t?.focus(),t?.select()}},document.addEventListener(`keydown`,this.globalKeyboardHandler)}bindEvents(){this.panel&&(this.panel.querySelector(`.nexa-btn-close`)?.addEventListener(`click`,()=>this.hide()),this.panel.querySelector(`.nexa-btn-clear`)?.addEventListener(`click`,()=>{this.tracker.clear(),this.render()}),this.panel.querySelector(`.nexa-btn-back`)?.addEventListener(`click`,()=>this.showMainView()),this.panel.querySelector(`.nexa-btn-retry`)?.addEventListener(`click`,()=>this.retrySelected()),this.panel.querySelector(`.nexa-search-input`)?.addEventListener(`input`,e=>{this.searchQuery=e.target.value.toLowerCase(),this.renderRequestList()}),this.panel.querySelectorAll(`.nexa-tab`).forEach(e=>{e.addEventListener(`click`,()=>{this.panel.querySelectorAll(`.nexa-tab`).forEach(e=>e.classList.remove(`nexa-tab-active`)),this.panel.querySelectorAll(`.nexa-panel`).forEach(e=>e.classList.remove(`nexa-panel-active`)),e.classList.add(`nexa-tab-active`),this.panel.querySelector(`[data-panel="${e.dataset.tab}"]`)?.classList.add(`nexa-panel-active`),e.dataset.tab===`metrics`&&this.renderMetrics()})}))}render(){!this.panel||!this.visible||(this.renderMetricsBar(),this.renderRequestList())}renderMetricsBar(){let e=this.tracker.getMetrics(),t=this.panel;t&&(t.querySelector(`[data-metric="total"]`).textContent=String(e.totalRequests),t.querySelector(`[data-metric="avg"]`).textContent=`${e.avgDuration.toFixed(0)}ms`,t.querySelector(`[data-metric="rate"]`).textContent=`${e.requestsPerSecond.toFixed(1)}`,t.querySelector(`[data-metric="success"]`).textContent=String(e.successfulRequests),t.querySelector(`[data-metric="fail"]`).textContent=String(e.failedRequests),t.querySelector(`[data-count="requests"]`).textContent=String(e.totalRequests))}renderRequestList(){let e=this.panel?.querySelector(`.nexa-request-list`);if(!e)return;let t=this.tracker.getHistory();if(this.searchQuery&&(t=t.filter(e=>e.url.toLowerCase().includes(this.searchQuery)||e.method.toLowerCase().includes(this.searchQuery)||String(e.status).includes(this.searchQuery))),t.length===0){e.innerHTML=`
393
+ <div class="nexa-empty">
394
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
395
+ <circle cx="12" cy="12" r="10"/><path d="M8 12h8M12 8v8"/>
396
+ </svg>
397
+ <p>${this.searchQuery?`No matching requests`:`No requests yet`}</p>
398
+ <span>${this.searchQuery?`Try a different search term`:`Make a request to see it here`}</span>
399
+ </div>`;return}e.innerHTML=t.map((e,t)=>`
400
+ <div class="nexa-request-item" data-id="${e.id}" style="animation-delay: ${Math.min(t*20,300)}ms">
401
+ <div class="nexa-req-left">
402
+ <span class="nexa-method nexa-method-${e.method.toLowerCase()}">${e.method}</span>
403
+ <span class="nexa-status ${e.ok?`nexa-ok`:`nexa-err`}">${e.status||`ERR`}</span>
404
+ <span class="nexa-url" title="${e.url}">${this.truncateUrl(e.url)}</span>
405
+ </div>
406
+ <div class="nexa-req-right">
407
+ ${e.cached?`<span class="nexa-badge nexa-badge-cache">Cache</span>`:``}
408
+ ${e.retryCount>0?`<span class="nexa-badge nexa-badge-retry">${e.retryCount}R</span>`:``}
409
+ <span class="nexa-duration ${e.duration>500?`nexa-slow`:``}">${e.duration.toFixed(0)}ms</span>
410
+ ${X.chevron}
411
+ </div>
412
+ </div>
413
+ `).join(``),e.querySelectorAll(`.nexa-request-item`).forEach(e=>{e.addEventListener(`click`,()=>{let n=e.dataset.id,r=t.find(e=>e.id===n);r&&this.showDetail(r)})})}renderMetrics(){let e=this.tracker.getMetrics(),t=this.panel?.querySelector(`.nexa-metrics-content`);if(!t)return;let n=e.totalRequests>0?(e.successfulRequests/e.totalRequests*100).toFixed(1):`0`;t.innerHTML=`
414
+ <div class="nexa-card">
415
+ <h3>Overview</h3>
416
+ <div class="nexa-row"><span>Total Requests</span><strong>${e.totalRequests}</strong></div>
417
+ <div class="nexa-row"><span>Successful</span><strong class="nexa-ok">${e.successfulRequests}</strong></div>
418
+ <div class="nexa-row"><span>Failed</span><strong class="nexa-err">${e.failedRequests}</strong></div>
419
+ <div class="nexa-row"><span>Cached</span><strong>${e.cachedRequests}</strong></div>
420
+ <div class="nexa-row"><span>Success Rate</span><strong>${n}%</strong></div>
421
+ </div>
422
+ <div class="nexa-card">
423
+ <h3>Performance</h3>
424
+ <div class="nexa-row"><span>Average</span><strong>${e.avgDuration.toFixed(1)}ms</strong></div>
425
+ <div class="nexa-row"><span>Fastest</span><strong class="nexa-ok">${e.minDuration.toFixed(1)}ms</strong></div>
426
+ <div class="nexa-row"><span>Slowest</span><strong class="nexa-err">${e.maxDuration.toFixed(1)}ms</strong></div>
427
+ <div class="nexa-row"><span>Throughput</span><strong>${e.requestsPerSecond.toFixed(2)} req/s</strong></div>
428
+ </div>
429
+ ${e.slowestRequests.length>0?`
430
+ <div class="nexa-card">
431
+ <h3>Slowest Requests</h3>
432
+ ${e.slowestRequests.map(e=>`
433
+ <div class="nexa-row nexa-slow-req">
434
+ <span><span class="nexa-method nexa-method-${e.method.toLowerCase()}" style="font-size:10px;padding:2px 5px;">${e.method}</span> ${this.truncateUrl(e.url,25)}</span>
435
+ <strong class="nexa-err">${e.duration.toFixed(0)}ms</strong>
436
+ </div>
437
+ `).join(``)}
438
+ </div>
439
+ `:``}`}showDetail(e){this.selectedRequest=e;let t=this.panel?.querySelector(`.nexa-body`),n=this.panel?.querySelector(`.nexa-detail`),r=this.panel?.querySelector(`.nexa-detail-body`);!t||!n||!r||(t.style.display=`none`,n.style.display=`flex`,r.innerHTML=`
440
+ <div class="nexa-card">
441
+ <h3>Request</h3>
442
+ <div class="nexa-row"><span>Method</span><strong style="color:${e.method===`GET`?Z.get:e.method===`POST`?Z.post:e.method===`DELETE`?Z.delete:Z.warning}">${e.method}</strong></div>
443
+ <div class="nexa-row"><span>URL</span><span class="nexa-url-full">${e.url}</span></div>
444
+ <div class="nexa-row"><span>Status</span><strong class="${e.ok?`nexa-ok`:`nexa-err`}">${e.status||`N/A`}</strong></div>
445
+ <div class="nexa-row"><span>Duration</span><strong>${e.duration.toFixed(1)}ms</strong></div>
446
+ <div class="nexa-row"><span>Cached</span><strong>${e.cached?`Yes`:`No`}</strong></div>
447
+ <div class="nexa-row"><span>Retries</span><strong>${e.retryCount}</strong></div>
448
+ <div class="nexa-row"><span>Timestamp</span><strong>${new Date(e.timestamp).toLocaleTimeString()}</strong></div>
449
+ </div>
450
+ ${e.body===void 0?``:`
451
+ <div class="nexa-card">
452
+ <h3>Request Body</h3>
453
+ <pre class="nexa-code">${this.formatJson(e.body)}</pre>
454
+ </div>
455
+ `}
456
+ ${Object.keys(e.headers).length>0?`
457
+ <div class="nexa-card">
458
+ <h3>Headers</h3>
459
+ <pre class="nexa-code">${this.formatJson(e.headers)}</pre>
460
+ </div>
461
+ `:``}`)}showMainView(){let e=this.panel?.querySelector(`.nexa-body`),t=this.panel?.querySelector(`.nexa-detail`);e&&(e.style.display=`flex`),t&&(t.style.display=`none`),this.selectedRequest=null}retrySelected(){if(!this.selectedRequest)return;let{method:e,url:t,body:n,headers:r}=this.selectedRequest;fetch(t,{method:e,headers:r,body:n?JSON.stringify(n):void 0}).then(async e=>{this.selectedRequest&&(this.selectedRequest={...this.selectedRequest,status:e.status,ok:e.ok,duration:this.selectedRequest.duration,timestamp:Date.now()},this.showDetail(this.selectedRequest))}).catch(()=>{})}truncateUrl(e,t=35){try{let t=new URL(e);return t.pathname+(t.search||``)}catch{return e.length>t?e.slice(0,t)+`...`:e}}formatJson(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}canUseDOM(){return typeof document<`u`&&typeof document.createElement==`function`&&!!document.body}},Q=null,$=null;function xe(e={}){return Q?{tracker:$,ui:Q}:($=new Y(e),Q=new be($),Q.show(),{tracker:$,ui:Q})}function Se(){return{tracker:$,ui:Q}}function Ce(){Q?.destroy(),Q=null,$=null}return e.AggressiveRetry=f,e.CachePlugin=I,e.CacheStore=y,e.CircuitBreakerRetry=ee,e.ConservativeRetry=p,e.DedupePlugin=L,e.Defer=k,e.Err=n,e.HttpClient=U,e.HttpError=W,e.LoggerPlugin=P,e.MetricsPlugin=F,e.MiddlewarePipeline=ae,e.Ok=t,e.PluginManager=N,e.RequestDeduplicator=x,e.RequestTracker=Y,e.TypedObservable=se,e.cacheMiddleware=re,e.createApiUrl=O,e.createCacheMiddleware=b,e.createDedupeMiddleware=S,e.createDevOverlay=xe,e.createHttpClient=de,e.createPipeline=C,e.createProjectionTransformer=u,e.createRealtimePlugin=ve,e.createRequiredFieldsValidator=i,e.createSSEClient=ge,e.createSchemaValidator=r,e.createStreamingMiddleware=M,e.createTypeGuard=E,e.createTypedApiClient=oe,e.createTypedRequest=T,e.createTypedResponse=w,e.createUrl=D,e.createWebSocketClient=me,e.createWrapperTransformer=d,e.dedupeMiddleware=ie,e.destroyDevOverlay=Ce,e.getDevOverlay=Se,e.handleStream=A,e.isHttpError=ue,e.retry=v,e.streamToFile=ce,e.streamingMiddleware=le,e.transformCamelToSnake=c,e.transformFlatten=l,e.transformSnakeToCamel=s,e.validatorIsArray=a,e.validatorIsObject=o,e.withTimeout=ne,e})({});
2
462
  //# sourceMappingURL=nexa.iife.js.map