@adonix.org/cloud-spark 1.0.1 → 2.0.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/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{StatusCodes as C}from"http-status-codes";import Ie from"cache-control-parser";var S={parse:Ie.parse,stringify:Ie.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var F=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(F||{}),{GET:p,PUT:rr,HEAD:O,POST:sr,PATCH:or,DELETE:nr,OPTIONS:B}=F;var He={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};function z(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function E(t){return typeof t=="string"}function g(t){return typeof t=="number"&&!Number.isNaN(t)}function Le(t){return typeof t=="boolean"}function ve(t){if(typeof t!="object"||t===null)throw new TypeError("CacheInit must be an object.");let{name:e,getKey:r}=t;_t(e),It(r)}function _t(t){if(t!==void 0&&!E(t))throw new TypeError("Cache name must be a string.")}function It(t){if(t!==void 0&&typeof t!="function")throw new TypeError("getKey must be a function.")}function We(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}function Pe(t){let e=new URL(t.url);return e.searchParams.sort(),e.hash="",e}function Cr(t){let e=new URL(t.url);return e.search="",e.hash="",e}var j=class{rules=[];use(...e){return this.rules.push(...e),this}execute(e,r){return this.rules.reduceRight((o,i)=>()=>i.apply(e,o),()=>r())()}};import{StatusCodes as Ht}from"http-status-codes";var n={ACCEPT:"accept",ACCEPT_ENCODING:"accept-encoding",ACCEPT_LANGUAGE:"accept-language",ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",AUTHORIZATION:"authorization",CACHE_CONTROL:"cache-control",CONNECTION:"connection",CONTENT_DISPOSITION:"content-disposition",CONTENT_ENCODING:"content-encoding",CONTENT_LANGUAGE:"content-language",CONTENT_LENGTH:"content-length",CONTENT_RANGE:"content-range",CONTENT_TYPE:"content-type",CONTENT_MD5:"content-md5",COOKIE:"cookie",ETAG:"etag",IF_MATCH:"if-match",IF_MODIFIED_SINCE:"if-modified-since",IF_NONE_MATCH:"if-none-match",IF_UNMODIFIED_SINCE:"if-unmodified-since",LAST_MODIFIED:"last-modified",ORIGIN:"origin",RANGE:"range",SET_COOKIE:"set-cookie",VARY:"vary",ACCESS_CONTROL_ALLOW_CREDENTIALS:"access-control-allow-credentials",ACCESS_CONTROL_ALLOW_HEADERS:"access-control-allow-headers",ACCESS_CONTROL_ALLOW_METHODS:"access-control-allow-methods",ACCESS_CONTROL_ALLOW_ORIGIN:"access-control-allow-origin",ACCESS_CONTROL_EXPOSE_HEADERS:"access-control-expose-headers",ACCESS_CONTROL_MAX_AGE:"access-control-max-age",SEC_WEBSOCKET_VERSION:"sec-websocket-version",UPGRADE:"upgrade",INTERNAL_VARIANT_SET:"internal-variant-set"},ke=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],Me=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function M(t,e){return t<e?-1:t>e?1:0}function f(t,e,r){let s=Array.isArray(r)?r:[r],o=Array.from(new Set(s.map(i=>i.trim()))).filter(i=>i.length).sort(M);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function $(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let i=l(t,e).concat(s.map(a=>a.trim()));f(t,e,i)}function l(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(M)}function Ae(t,e){for(let r of e)t.delete(r)}var Lt="https://vary",vt="*";function De(t,e){if(e.status!==Ht.OK||t.method!==p||t.headers.has(n.AUTHORIZATION)||t.headers.has(n.COOKIE)||w(t.headers)["no-store"]||!e.headers.has(n.CACHE_CONTROL))return!1;let s=w(e.headers),o=s["s-maxage"]??s["max-age"];if(o===void 0||o===0||s["no-store"]||s["no-cache"]||s.private||e.headers.has(n.SET_COOKIE)||Te(e).includes(vt))return!1;if(e.headers.has(n.INTERNAL_VARIANT_SET))throw new Error("Found conflicting vary header.");if(e.headers.has(n.CONTENT_RANGE))throw new Error("Found content-range header on 200 OK. Must use 206 Partial Content");return!0}function w(t){return S.parse(t.get(n.CACHE_CONTROL)??"")}function Te(t){return y(l(t.headers,n.VARY))}function y(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(M);return Array.from(new Set(e))}function _(t,e,r){let s=[],o=y(e);for(let a of o){let c=t.headers.get(a);c!==null&&s.push([a,Wt(a,c)])}let i=Pt(JSON.stringify([r.toString(),s]));return new URL(i,Lt).toString()}function Wt(t,e){switch(t.toLowerCase()){case n.ACCEPT:case n.ACCEPT_LANGUAGE:case n.ORIGIN:return e.toLowerCase();default:return e}}function Pt(t){let e=new TextEncoder().encode(t),r="";for(let s of e)r+=String.fromCodePoint(s);return btoa(r).replaceAll("+","-").replaceAll("/","_").replace(/={1,2}$/,"")}var kt=/^bytes=(\d{1,12})-(\d{0,12})$/,Ge="W/",Ve="*";function Ue(t){let e=t.headers.get(n.RANGE);if(!e)return;let r=kt.exec(e);if(!r)return;let s=Number(r[1]),o=r[2]===""?void 0:Number(r[2]);return o===void 0?{start:s}:{start:s,end:o}}function Ke(t,e){return t.length>0&&!Fe(t,e,Ve)}function qe(t,e){return Fe(t,Be(e),Ve)}function Fe(t,...e){return t.some(r=>e.includes(r))}function X(t){if(!E(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Be(t){return t.startsWith(Ge)?t.slice(2):t}function Oe(t){return{ifMatch:l(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:l(t,n.IF_NONE_MATCH).map(Be),ifModifiedSince:t.get(n.IF_MODIFIED_SINCE),ifUnmodifiedSince:t.get(n.IF_UNMODIFIED_SINCE)}}function ze(t){let{ifNoneMatch:e,ifMatch:r,ifModifiedSince:s,ifUnmodifiedSince:o}=Oe(t);return e.length>0||r.length>0||s!==null||o!==null}function je(t){let e=t.get(n.CONTENT_LENGTH);if(e===null||e.trim()==="")return;let r=Number(e);if(g(r))return r}var Y=class{async apply(e,r){let s=w(e.request.headers);if(!s["no-store"]&&!((s["no-cache"]||s["max-age"]===0)&&!ze(e.request.headers)))return r()}};import{getReasonPhrase as Vt,StatusCodes as h}from"http-status-codes";var Mt=new Set(Object.values(F));function be(t){return E(t)&&Mt.has(t)}function Dt(t){return Array.isArray(t)&&t.every(be)}function b(t){if(!Dt(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}var $e="upgrade",Xe="websocket";import{getReasonPhrase as Gt,StatusCodes as u}from"http-status-codes";var D="utf-8";function Ye(t){if(typeof t!="object"||t===null)throw new TypeError("OctetStreamInit must be an object.");let e=t,r=e.size;if(!g(r)||r<0||!Number.isInteger(r))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(r)}).`);let s=e.offset??0;if(!g(s)||s<0||s>r||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}).`);let o=e.length??r-s;if(!g(o)||o<0||s+o>r||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function G(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var xe=class{headers=new Headers;status=u.OK;statusText;webSocket;mediaType=G("text/plain",D);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??Gt(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){f(this.headers,e,r)}mergeHeader(e,r){$(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===u.NO_CONTENT?Ae(this.headers,Me):this.status===u.NOT_MODIFIED&&Ae(this.headers,ke)}},Ne=class extends xe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,S.stringify(this.cache))}},m=class extends Ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=[u.NO_CONTENT,u.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},V=class extends m{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},I=class extends m{constructor(e){super(),this.status=u.NOT_MODIFIED,this.headers=new Headers(e.headers)}},U=class extends m{constructor(e=null,r,s=u.OK){super(e,r),this.status=s}},J=class extends U{constructor(e={},r,s=u.OK){super(JSON.stringify(e),r,s),this.mediaType=G("application/json",D)}},Je=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/html",o)}},Ze=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/plain",o)}},we=class t extends m{constructor(e,r,s){Ye(r),super(e,s),this.mediaType="application/octet-stream";let o=t.normalizeInit(r),{size:i,offset:a,length:c}=o;t.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${a}-${a+c-1}/${i}`),this.status=u.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${c}`)}static normalizeInit(e){let{size:r}=e,s=e.offset??0,o=e.length??r-s;return s===0&&o===0&&r>0&&(o=1),{size:r,offset:s,length:o}}static isPartial(e){return e.size===0?!1:!(e.offset===0&&e.length===e.size)}},Qe=class t extends we{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=S.parse(e.httpMetadata.cacheControl)),super(e.body,t.computeRange(e.size,e.range),s),this.setHeader(n.ETAG,e.httpEtag),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType)}static computeRange(e,r){if(!r)return{size:e};if("suffix"in r){let s=Math.max(0,e-r.suffix),o=e-s;return{size:e,offset:s,length:o}}return{size:e,...r}}},et=class extends m{constructor(e){super(),this.status=u.SWITCHING_PROTOCOLS,this.webSocket=e}},H=class extends m{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},Z=class extends m{constructor(e){let r=Array.from(new Set([p,O,...e.getAllowedMethods()]));b(r),super(),this.status=u.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var d=class extends J{constructor(r,s){let o={status:r,error:Vt(r),details:s??""};super(o,S.DISABLE,r);this.details=s}},Q=class extends d{constructor(e,r=h.INTERNAL_SERVER_ERROR){let s=crypto.randomUUID();console.error(s,e),super(r,s)}},K=class extends d{constructor(e){super(h.BAD_REQUEST,e)}},tt=class extends d{constructor(e){super(h.UNAUTHORIZED,e)}},rt=class extends d{constructor(e){super(h.FORBIDDEN,e)}},A=class extends d{constructor(e){super(h.NOT_FOUND,e)}},L=class extends d{constructor(e){let r=e.getAllowedMethods();b(r),super(h.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},v=class extends d{constructor(e){super(h.PRECONDITION_FAILED,e)}},ee=class extends d{constructor(){super(h.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13")}},st=class extends d{constructor(e){super(h.INTERNAL_SERVER_ERROR,e)}},ye=class extends d{constructor(e){super(h.NOT_IMPLEMENTED,e)}},x=class extends ye{constructor(e){super(`${e.request.method} method not implemented.`)}},ot=class extends d{constructor(e){super(h.SERVICE_UNAVAILABLE,e)}};import{StatusCodes as Ut}from"http-status-codes";var W=class{async apply(e,r){let s=await r();if(!s||s.status!==Ut.OK)return s;let o=this.getHeader(s);if(o===void 0)return s;let i=Oe(e.request.headers);return this.response(s,o,i)}};var te=class extends W{getHeader(e){return e.headers.get(n.ETAG)??void 0}},re=class extends te{async response(e,r,s){return Ke(s.ifMatch,r)?new v(`ETag: ${r}`).response():e}},se=class extends te{async response(e,r,s){if(s.ifNoneMatch.length===0)return e;if(qe(s.ifNoneMatch,r))return new I(e).response()}};var oe=class{async apply(e,r){if(e.request.method===p)return r();if(e.request.method===O){let s=await r();return s?new H(s).response():void 0}}};var ne=class extends W{getHeader(e){return X(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=X(s.ifModifiedSince);if(o===void 0)return e;if(r<=o)return new I(e).response()}},ae=class extends ne{async response(e,r,s){let o=X(s.ifUnmodifiedSince);return o===void 0?e:r>o?new v(`Last-Modified: ${new Date(r).toUTCString()}`).response():e}};import{StatusCodes as Kt}from"http-status-codes";var ce=class{async apply(e,r){let s=Ue(e.request);if(s&&(s.start!==0||s.end===0))return;let o=await r();if(!o||o.status!==Kt.OK||!s||s.end===void 0)return o;let i=je(o.headers);if(i&&s.end===i-1)return o}};var pe=class{async apply(e,r){let s=e.request.headers;if(!s.has(n.AUTHORIZATION)&&!s.has(n.COOKIE))return r()}};var ue=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var T=class t extends m{_isModified=!1;constructor(e){let r=y(e);if(r.length===0)throw new Error("The filtered vary array is empty.");super(),this.setHeader(n.INTERNAL_VARIANT_SET,r)}static new(e){return new t(y(e))}static restore(e){if(!t.isVariantResponse(e))throw new Error("The source response is not a variant response");let r=t.new(l(e.headers,n.INTERNAL_VARIANT_SET)),s=e.headers.get(n.CACHE_CONTROL);return s&&(r.cache=S.parse(s)),r}get vary(){return l(this.headers,n.INTERNAL_VARIANT_SET)}get isModified(){return this._isModified}append(e){let r=this.vary.length;this.mergeHeader(n.INTERNAL_VARIANT_SET,y(e)),this._isModified=this.vary.length!==r}static isVariantResponse(e){return e.headers.has(n.INTERNAL_VARIANT_SET)}expireAfter(e){let r=w(e.headers),s=r["s-maxage"]??r["max-age"];if(s===void 0)return;let o=this.cache?.["s-maxage"];(o===void 0||s>o)&&(this.cache={"s-maxage":s},this._isModified=!0)}};var de=class{init;constructor(e){let{name:r,getKey:s=Pe}=e;this.init={name:r?.trim()||void 0,getKey:s}}async handle(e,r){let s=this.init.name?await caches.open(this.init.name):caches.default,i=await new j().use(new Y).use(new oe).use(new ue).use(new pe).use(new ce).use(new ie).use(new se).use(new ae).use(new re).execute(e,()=>this.getCached(s,e.request));if(i)return i;let a=await r();return e.ctx.waitUntil(this.setCached(s,e.request,a)),a}async getCached(e,r){let s=this.getCacheKey(r),o=await e.match(s.toString());if(!o)return;if(!T.isVariantResponse(o))return o;let i=T.restore(o).vary,a=_(r,i,s);return e.match(a)}async setCached(e,r,s){if(!De(r,s))return;let o=this.getCacheKey(r),i=s.clone(),a=Te(i),c=await e.match(o),yt=c&&T.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let R=T.new(a);R.expireAfter(i),await e.put(o,await R.response()),await e.put(_(r,R.vary,o),i);return}if(yt){let R=T.restore(c);R.expireAfter(i),a.length>0&&(R.append(a),R.isModified&&await e.put(o,await R.response())),await e.put(_(r,R.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let q=T.new(a);q.expireAfter(c),q.expireAfter(i),await e.put(o,await q.response()),await e.put(_(r,q.vary,o),i),await e.put(_(r,[],o),c)}getCacheKey(e){let r=this.init.getKey(e);return We(r),r.hash="",r}};function Qs(t={}){return ve(t),new de(t)}function it(t){if(t===void 0)return;if(typeof t!="object"||t===null)throw new TypeError("CorsInit must be an object.");let e=t;if(e.allowedOrigins!==void 0&&!z(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!z(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!z(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!Le(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!g(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var le="*",at=[C.SWITCHING_PROTOCOLS,C.CONTINUE,C.PROCESSING,C.EARLY_HINTS,C.MOVED_PERMANENTLY,C.MOVED_TEMPORARILY,C.SEE_OTHER,C.TEMPORARY_REDIRECT,C.PERMANENT_REDIRECT],ct={allowedOrigins:[le],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*He.Minute};function pt(t,e,r){let s=new V(t),o=Ct(e.request);return mt(s.headers),dt(s.headers,r),o&&(lt(s.headers,r,o),ft(s.headers,r,o),qt(s.headers,e),Bt(s.headers,r),Ft(s.headers,r)),s.response()}function ut(t,e,r){let s=new V(t),o=Ct(e.request);return mt(s.headers),dt(s.headers,r),o&&(lt(s.headers,r,o),ft(s.headers,r,o),zt(s.headers,r)),s.response()}function dt(t,e){_e(e)||$(t,n.VARY,n.ORIGIN)}function lt(t,e,r){if(_e(e)){f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,le);return}e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r)}function ft(t,e,r){e.allowCredentials&&(_e(e)||e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function qt(t,e){let r=e.getAllowedMethods();b(r),f(t,n.ACCESS_CONTROL_ALLOW_METHODS,r)}function Ft(t,e){let r=Math.max(0,Math.floor(e.maxAge));f(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function Bt(t,e){f(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function zt(t,e){f(t,n.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function _e(t){return t.allowedOrigins.includes(le)}function mt(t){t.delete(n.ACCESS_CONTROL_MAX_AGE),t.delete(n.ACCESS_CONTROL_ALLOW_ORIGIN),t.delete(n.ACCESS_CONTROL_ALLOW_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_METHODS),t.delete(n.ACCESS_CONTROL_EXPOSE_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_CREDENTIALS)}function ht(t){let{status:e,headers:r}=t;return!!(at.includes(e)||r.has(n.UPGRADE))}function Ct(t){let e=t.headers.get(n.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}var fe=class{config;constructor(e){this.config={...ct,...e}}async handle(e,r){let s=await r();return e.request.method===B?pt(s,e,this.config):ht(s)?s:ut(s,e,this.config)}};function So(t){return it(t),new fe(t)}import{match as jt}from"path-to-regexp";function Et(t){return l(t,n.CONNECTION).some(e=>e.toLowerCase()===$e)}function gt(t){return l(t,n.UPGRADE).some(e=>e.toLowerCase()===Xe)}function Rt(t){return t.get(n.SEC_WEBSOCKET_VERSION)?.trim()==="13"}var me=class{constructor(e){this.path=e}handle(e,r){if(e.request.method!==p||!this.isMatch(e.request))return r();let s=e.request.headers;return Et(s)?gt(s)?Rt(s)?r():new ee().response():new K("Missing or invalid 'Upgrade' header").response():new K("Missing or invalid 'Connection' header").response()}isMatch(e){return jt(this.path)(new URL(e.url).pathname)!==!1}};function Lo(t="/"){return new me(t)}function $t(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function St(t){return E(t)?t.length>0:$t(t)?t.byteLength>0:!1}function At(t){if(t===null||typeof t!="object")throw new TypeError("WebSocket attachment must be an object");try{JSON.stringify(t)}catch{throw new TypeError("WebSocket attachment is not serializable")}}var he=class t{server;customListeners={};constructor(e){this.server=e}addEventListener(e,r,s){if(t.isCustomEvent(e)){let o=this.customListeners[e];o||(o=[],this.customListeners[e]=o),o.push(r)}else{let o=e==="close"?{...s,once:!0}:s;this.server.addEventListener(e,r,o)}}removeEventListener(e,r){if(t.isCustomEvent(e)){let s=this.customListeners[e];if(s){let o=s.indexOf(r);o!==-1&&s.splice(o,1)}}else this.server.removeEventListener(e,r)}dispatch(e,r,s=!1){let o=this.customListeners[e]?.slice()??[];s&&(this.customListeners[e]=[]);for(let i of o)i(r)}warn(e){this.dispatch("warn",{type:"warn",message:e})}open(){this.dispatch("open",new Event("open"),!0)}static isCustomEvent(e){return["open","warn"].includes(e)}};var N={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},Tt=new Set([N.NO_STATUS,N.ABNORMAL,N.TLS_HANDSHAKE]);function Ot(t){return g(t)?Jt(t)&&!Zt(t)?t:N.NORMAL:N.NORMAL}function Jt(t){return t>=N.NORMAL&&t<=4999}function Zt(t){return Tt.has(t)}function bt(t){if(E(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var P=class extends he{accepted=!1;server;constructor(e){super(e),this.server=e,this.server.addEventListener("close",this.onclose)}send(e){if(this.isState(WebSocket.CONNECTING,WebSocket.CLOSED)){this.warn("Cannot send: WebSocket not open");return}if(!St(e)){this.warn("Cannot send: empty or invalid data");return}this.server.send(e)}get attachment(){return this.server.deserializeAttachment()??{}}attach(e){if(e!==void 0)if(e===null)this.server.serializeAttachment({});else{let s={...this.attachment,...e};At(s),this.server.serializeAttachment(s)}}get readyState(){return this.accepted?this.server.readyState:WebSocket.CONNECTING}isState(...e){return e.includes(this.readyState)}close(e,r){this.server.removeEventListener("close",this.onclose),this.server.close(Ot(e),bt(r))}onclose=e=>{this.close(e.code,e.reason)}};var Ce=class extends P{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return this.accepted?this.client:(e.acceptWebSocket(this.server,r),this.ready())}accept(){return this.accepted?this.client:(this.server.accept(),this.ready())}ready(){return this.accepted=!0,this.open(),this.client}};var Ee=class extends P{constructor(e){super(e),this.accepted=!0}accept(){throw new Error("Do not call accept() on restore")}acceptWebSocket(){throw new Error("Do not call acceptWebSocket() on restore")}};var xt=class{map=new Map;create(e){class r extends Ce{constructor(a){super();this.sessions=a}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(a,c){return this.sessions.register(this.server,this),super.acceptWebSocket(a,c)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends Ee{constructor(o,i){super(i),o.register(this.server,this)}}return new r(this,e)}restoreAll(e){let r=[];for(let s of e)r.push(this.restore(s));return r}get(e){return this.map.get(e)}select(e){let r=[];for(let s of e){let o=this.map.get(s);o&&r.push(o)}return r}values(){return this.map.values()}keys(){return this.map.keys()}close(e,r,s){let o=this.get(e);return o&&o.close(r,s),this.unregister(e)}*[Symbol.iterator](){yield*this.values()}register(e,r){this.map.set(e,r)}unregister(e){return this.map.delete(e)}};function Nt(t){if(t===null||typeof t!="object"||typeof t.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var k=class{constructor(e,r,s){this._request=e;this._env=r;this._ctx=s}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(e){let r=this.getAllowedMethods();return b(r),e===p||e===O?!0:be(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};var ge=class extends k{middlewares=[];init(){}use(...e){for(let r of e)Nt(r);return this.middlewares.push(...e),this}async fetch(){return await this.init(),this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(L,this))()}};var Re=class extends ge{async fetch(){try{return await super.fetch()}catch(e){return this.response(Q,e)}}dispatch(){let e=this.request.method;return({GET:()=>this.get(),PUT:()=>this.put(),HEAD:()=>this.head(),POST:()=>this.post(),PATCH:()=>this.patch(),DELETE:()=>this.delete(),OPTIONS:()=>this.options()}[e]??(()=>this.response(L,this)))()}get(){return this.response(A)}put(){return this.response(x,this)}post(){return this.response(x,this)}patch(){return this.response(x,this)}delete(){return this.response(x,this)}options(){return this.response(Z,this)}async head(){let e=this.create(new Request(this.request.url,{method:p,headers:this.request.headers}));return this.response(H,await e.fetch())}getAllowedMethods(){return[p,O,B]}};import{match as Qt}from"path-to-regexp";var Se=class{routes=[];add(e){for(let[r,s,o]of e){let i=Qt(s);this.routes.push({method:r,matcher:i,handler:o})}}match(e,r){let s=new URL(r).pathname;for(let o of this){if(o.method!==e)continue;let i=o.matcher(s);if(i)return{route:o,params:i.params}}return null}*[Symbol.iterator](){yield*this.routes}};var wt=class t extends Re{_routes=new Se;route(e,r,s){return this.routes([[e,r,s]]),this}routes(e){return this._routes.add(e),this}async dispatch(){let e=this._routes.match(this.request.method,this.request.url);if(!e)return super.dispatch();let{handler:r}=e.route;return t.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(k.prototype,e.prototype)}put(){return this.response(A)}post(){return this.response(A)}patch(){return this.response(A)}delete(){return this.response(A)}};export{K as BadRequest,Re as BasicWorker,S as CacheControl,V as CopyResponse,nr as DELETE,rt as Forbidden,p as GET,O as HEAD,H as Head,Je as HtmlResponse,d as HttpError,st as InternalServerError,J as JsonResponse,Q as LoggedHttpError,F as Method,L as MethodNotAllowed,x as MethodNotImplemented,A as NotFound,ye as NotImplemented,I as NotModified,B as OPTIONS,we as OctetStream,Z as Options,or as PATCH,sr as POST,rr as PUT,v as PreconditionFailed,Qe as R2ObjectStream,wt as RouteWorker,ot as ServiceUnavailable,C as StatusCodes,U as SuccessResponse,Ze as TextResponse,He as Time,tt as Unauthorized,ee as UpgradeRequired,xt as WebSocketSessions,et as WebSocketUpgrade,m as WorkerResponse,Qs as cache,So as cors,Pe as sortSearchParams,Cr as stripSearchParams,Lo as websocket};
1
+ import {StatusCodes}from'http-status-codes/build/es/status-codes';export{StatusCodes}from'http-status-codes/build/es/status-codes';import q from'cache-control-parser';import {getReasonPhrase}from'http-status-codes/build/es/utils-functions';import {match}from'path-to-regexp';var O={parse:q.parse,stringify:q.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var A=(u=>(u.GET="GET",u.PUT="PUT",u.HEAD="HEAD",u.POST="POST",u.PATCH="PATCH",u.DELETE="DELETE",u.OPTIONS="OPTIONS",u))(A||{}),{GET:l,PUT:Tt,HEAD:f,POST:Ct,PATCH:Ot,DELETE:Nt,OPTIONS:U}=A;var xt={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var n={ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",CACHE_CONTROL:"cache-control",CONTENT_DISPOSITION:"content-disposition",CONTENT_ENCODING:"content-encoding",CONTENT_LANGUAGE:"content-language",CONTENT_LENGTH:"content-length",CONTENT_RANGE:"content-range",CONTENT_TYPE:"content-type",CONTENT_MD5:"content-md5",ETAG:"etag",SEC_WEBSOCKET_VERSION:"sec-websocket-version"},B=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],$=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function z(r){return typeof r=="string"}function S(r){return typeof r=="number"&&!Number.isNaN(r)}var pt=new Set(Object.values(A));function D(r){return z(r)&&pt.has(r)}function ut(r){return Array.isArray(r)&&r.every(D)}function E(r){if(!ut(r)){let t=Array.isArray(r)?JSON.stringify(r):String(r);throw new TypeError(`Invalid method array: ${t}`)}}var N="utf-8";function J(r){if(typeof r!="object"||r===null)throw new TypeError("OctetStreamInit must be an object.");let t=r,e=t.size;if(!S(e)||e<0||!Number.isInteger(e))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(e)}).`);let s=t.offset??0;if(!S(s)||s<0||s>e||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(e)}, offset=${JSON.stringify(s)}).`);let o=t.length??e-s;if(!S(o)||o<0||s+o>e||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(e)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function L(r,t){return r<t?-1:r>t?1:0}function M(r,t,e){let s=Array.isArray(e)?e:[e],o=Array.from(new Set(s.map(c=>c.trim()))).filter(c=>c.length).sort(L);if(!o.length){r.delete(t);return}r.set(t,o.join(", "));}function j(r,t,e){let s=Array.isArray(e)?e:[e];if(s.length===0)return;let c=dt(r,t).concat(s.map(R=>R.trim()));M(r,t,c);}function dt(r,t){let e=r.get(t)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(e)).sort(L)}function v(r,t){for(let e of t)r.delete(e);}function g(r,t){return !t||r.toLowerCase().includes("charset=")?r:`${r}; charset=${t.toLowerCase()}`}var k=class{headers=new Headers;status=StatusCodes.OK;statusText;webSocket;mediaType=g("text/plain",N);get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??getReasonPhrase(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(t,e){M(this.headers,t,e);}mergeHeader(t,e){j(this.headers,t,e);}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===StatusCodes.NO_CONTENT?v(this.headers,$):this.status===StatusCodes.NOT_MODIFIED&&v(this.headers,B);}},G=class extends k{constructor(e){super();this.cache=e;}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,O.stringify(this.cache));}},d=class extends G{constructor(e=null,s){super(s);this.body=e;}async response(){this.addCacheHeader();let e=[StatusCodes.NO_CONTENT,StatusCodes.NOT_MODIFIED].includes(this.status)?null:this.body;return e&&this.addContentType(),this.filterHeaders(),new Response(e,this.responseInit)}},K=class extends d{constructor(t,e){super(t.body,e),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}},V=class extends d{constructor(t){super(),this.status=StatusCodes.NOT_MODIFIED,this.headers=new Headers(t.headers);}},x=class extends d{constructor(t=null,e,s=StatusCodes.OK){super(t,e),this.status=s;}},_=class extends x{constructor(t={},e,s=StatusCodes.OK){super(JSON.stringify(t),e,s),this.mediaType=g("application/json",N);}},Y=class extends x{constructor(t,e,s=StatusCodes.OK,o=N){super(t,e,s),this.mediaType=g("text/html",o);}},X=class extends x{constructor(t,e,s=StatusCodes.OK,o=N){super(t,e,s),this.mediaType=g("text/plain",o);}},W=class r extends d{constructor(t,e,s){J(e),super(t,s),this.mediaType="application/octet-stream";let o=r.normalizeInit(e),{size:c,offset:R,length:u}=o;r.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${R}-${R+u-1}/${c}`),this.status=StatusCodes.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${u}`);}static normalizeInit(t){let{size:e}=t,s=t.offset??0,o=t.length??e-s;return s===0&&o===0&&e>0&&(o=1),{size:e,offset:s,length:o}}static isPartial(t){return t.size===0?false:!(t.offset===0&&t.length===t.size)}},Q=class r extends W{constructor(t,e){let s=e;!s&&t.httpMetadata?.cacheControl&&(s=O.parse(t.httpMetadata.cacheControl)),super(t.body,r.computeRange(t.size,t.range),s),this.setHeader(n.ETAG,t.httpEtag),t.httpMetadata?.contentType&&(this.mediaType=t.httpMetadata.contentType);}static computeRange(t,e){if(!e)return {size:t};if("suffix"in e){let s=Math.max(0,t-e.suffix),o=t-s;return {size:t,offset:s,length:o}}return {size:t,...e}}},Z=class extends d{constructor(t){super(),this.status=StatusCodes.SWITCHING_PROTOCOLS,this.webSocket=t;}},I=class extends d{constructor(t){super(),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}},y=class extends d{constructor(t){let e=Array.from(new Set([l,f,...t.getAllowedMethods()]));E(e),super(),this.status=StatusCodes.NO_CONTENT,this.setHeader(n.ALLOW,e);}};var a=class extends _{constructor(e,s){let o={status:e,error:getReasonPhrase(e),details:s??""};super(o,O.DISABLE,e);this.details=s;}},w=class extends a{constructor(t,e=StatusCodes.INTERNAL_SERVER_ERROR){let s=crypto.randomUUID();console.error(s,t),super(e,s);}},tt=class extends a{constructor(t){super(StatusCodes.BAD_REQUEST,t);}},et=class extends a{constructor(t){super(StatusCodes.UNAUTHORIZED,t);}},rt=class extends a{constructor(t){super(StatusCodes.FORBIDDEN,t);}},h=class extends a{constructor(t){super(StatusCodes.NOT_FOUND,t);}},T=class extends a{constructor(t){let e=t.getAllowedMethods();E(e),super(StatusCodes.METHOD_NOT_ALLOWED,`${t.request.method} method not allowed.`),this.setHeader(n.ALLOW,e);}},st=class extends a{constructor(t){super(StatusCodes.PRECONDITION_FAILED,t);}},ot=class extends a{constructor(){super(StatusCodes.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13");}},nt=class extends a{constructor(t){super(StatusCodes.INTERNAL_SERVER_ERROR,t);}},F=class extends a{constructor(t){super(StatusCodes.NOT_IMPLEMENTED,t);}},m=class extends F{constructor(t){super(`${t.request.method} method not implemented.`);}},it=class extends a{constructor(t){super(StatusCodes.SERVICE_UNAVAILABLE,t);}};function at(r){if(r===null||typeof r!="object"||typeof r.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var C=class{constructor(t,e,s){this._request=t;this._env=e;this._ctx=s;}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(t){let e=this.getAllowedMethods();return E(e),t===l||t===f?true:D(t)&&e.includes(t)}create(t){let e=this.constructor;return new e(t,this.env,this.ctx)}response(t,...e){return new t(...e).response()}static ignite(){return {fetch:(t,e,s)=>new this(t,e,s).fetch()}}};var b=class extends C{middlewares=[];init(){}use(...t){for(let e of t)at(e);return this.middlewares.push(...t),this}async fetch(){return await this.init(),this.middlewares.reduceRight((e,s)=>()=>s.handle(this,e),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(T,this))()}};var H=class extends b{async fetch(){try{return await super.fetch()}catch(t){return this.response(w,t)}}dispatch(){let t=this.request.method;return ({GET:()=>this.get(),PUT:()=>this.put(),HEAD:()=>this.head(),POST:()=>this.post(),PATCH:()=>this.patch(),DELETE:()=>this.delete(),OPTIONS:()=>this.options()}[t]??(()=>this.response(T,this)))()}get(){return this.response(h)}put(){return this.response(m,this)}post(){return this.response(m,this)}patch(){return this.response(m,this)}delete(){return this.response(m,this)}options(){return this.response(y,this)}async head(){let t=this.create(new Request(this.request.url,{method:l,headers:this.request.headers}));return this.response(I,await t.fetch())}getAllowedMethods(){return [l,f,U]}};var P=class{routes=[];add(t){for(let[e,s,o]of t){let c=match(s);this.routes.push({method:e,matcher:c,handler:o});}}match(t,e){let s=new URL(e).pathname;for(let o of this){if(o.method!==t)continue;let c=o.matcher(s);if(c)return {route:o,params:c.params}}return null}*[Symbol.iterator](){yield*this.routes;}};var ct=class r extends H{_routes=new P;route(t,e,s){return this.routes([[t,e,s]]),this}routes(t){return this._routes.add(t),this}async dispatch(){let t=this._routes.match(this.request.method,this.request.url);if(!t)return super.dispatch();let{handler:e}=t.route;return r.isWorkerClass(e)?new e(this.request,this.env,this.ctx).fetch():e.call(this,t.params)}static isWorkerClass(t){return Object.prototype.isPrototypeOf.call(C.prototype,t.prototype)}put(){return this.response(h)}post(){return this.response(h)}patch(){return this.response(h)}delete(){return this.response(h)}};export{tt as BadRequest,H as BasicWorker,O as CacheControl,K as CopyResponse,Nt as DELETE,rt as Forbidden,l as GET,f as HEAD,I as Head,Y as HtmlResponse,a as HttpError,nt as InternalServerError,_ as JsonResponse,w as LoggedHttpError,A as Method,T as MethodNotAllowed,m as MethodNotImplemented,h as NotFound,F as NotImplemented,V as NotModified,U as OPTIONS,W as OctetStream,y as Options,Ot as PATCH,Ct as POST,Tt as PUT,st as PreconditionFailed,Q as R2ObjectStream,ct as RouteWorker,it as ServiceUnavailable,x as SuccessResponse,X as TextResponse,xt as Time,et as Unauthorized,ot as UpgradeRequired,Z as WebSocketUpgrade,d as WorkerResponse};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map