@ahmadissa/cloudworker-proxy 1.1.142 → 1.1.143

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,10 +1,10 @@
1
- "use strict";var Lo=Object.create;var xr=Object.defineProperty;var Go=Object.getOwnPropertyDescriptor;var Bo=Object.getOwnPropertyNames;var Vo=Object.getPrototypeOf,jo=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var zo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Bo(t))!jo.call(e,o)&&o!==r&&xr(e,o,{get:()=>t[o],enumerable:!(n=Go(t,o))||n.enumerable});return e};var P=(e,t,r)=>(r=e!=null?Lo(Vo(e)):{},zo(t||!e||!e.__esModule?xr(r,"default",{value:e,enumerable:!0}):r,e));var At=v(($u,kr)=>{function Xo({host:e=".*",path:t=".*",excludePath:r=null,method:n=[".*"],handler:o,protocol:s=".*",handlerName:a,headers:i={},data:c}){let u=[],p=[],d=e.replace(/(:([^.]+))/g,(b,K,O)=>(u.push(O),"([^.]+)")),h=t.replace(/(:([^/]+))/g,(b,K,O)=>O.slice(-1)==="*"?(p.push(O.slice(0,O.length-1)),"(.*)"):(p.push(O),"([^/]*)")),f=new RegExp(`^${d}$`,"i"),l=new RegExp(`^${h}$`,"i"),g=r?new RegExp(`^${r}$`,"i"):null,y=new RegExp(`^${n.join("|")}$`,"i"),w=new RegExp(`^${s}$`,"i");return{hostVariables:u,pathVariables:p,host:f,path:l,excludePath:g,method:y,protocol:w,handler:o,handlerName:a,headers:i,data:c}}function Ur(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}async function Yo(e,t=1024*1024){let r=[],n=e.getReader(),o=new TextDecoder,s=0;for(;t&&s<t;){let{done:i,value:c}=await n.read();if(i)break;s+=c.byteLength,r.push(o.decode(c))}let a=r.join("");return t?a.substring(0,t):a}function Zo(e){let t=new URL(e.url),r=Ur(t.searchParams),n=Ur(e.headers);n.host&&(t.hostname=n.host);let o,s;async function a(i){if(s>=i)return o.substring(0,i);let c=e.clone();return o=await Yo(c.body,i),o}return{body:e.body,headers:n,host:t.host,hostname:t.hostname,href:t.href,json:async i=>JSON.parse(a(i)),method:e.method,origin:`${t.protocol}//${t.host}`,path:t.pathname,protocol:t.protocol.slice(0,-1),query:r,querystring:t.search.slice(1),search:t.search,text:async i=>e.headers.get("content-type")==="application/x-www-form-urlencoded"?decodeURIComponent(await a(i)):a(i)}}kr.exports={parseRoute:Xo,parseRequest:Zo}});var Wr=v((Mu,Ir)=>{function Qo(e,t){let r={},n=t.host.exec(e.host);t.hostVariables.forEach((s,a)=>{r[s]=n[a+1]});let o=t.path.exec(e.path);return t.pathVariables.forEach((s,a)=>{r[s]=o[a+1]}),r}function es(e,t){let r=!0;return Object.keys(e.headers).forEach(n=>{t.headers[n]!==e.headers[n]&&(r=!1)}),r}function ts(e,t){return e.protocol.test(t.protocol)}function rs(e,t){return e.method.test(t.method)&&e.host.test(t.host)&&e.path.test(t.path)&&es(e,t)&&ts(e,t)&&(!e.excludePath||!e.excludePath.test(t.path))}async function St(e,t){let[r,...n]=t;if(!r)return new Response("NOT_FOUND",{status:404});if(!rs(r,e.request))return St(e,n);e.state.handlers=e.state.handlers||[],e.state.handlers.push(r.handlerName||r.handler.name),e.params=Qo(e.request,r);try{return r.handler(e,async o=>St(o,n))}catch(o){throw o.route=r.handler.name,o}}Ir.exports={recurseRoutes:St}});var Jr=v((qu,Nr)=>{Nr.exports={methods:{DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST"},statusMessages:{404:"Not found",429:"Rate limited"}}});var Mr=v((Fu,$r)=>{var ns=At();$r.exports=class Dr{constructor(t){this.request=ns.parseRequest(t.request),this.event=t,this.state={},this.cloned=!1,this.response={headers:{}},this.body="",this.status=404,this.query=this.request.query}header(t){return this.request.headers[t]}set(t,r){this.response.headers[t]=r}clone(){let t=new Dr(this.event);return t.cloned=!0,t}}});var Fr=v((Gu,qr)=>{var pe=At(),os=Wr(),ve=Jr(),ss=Mr();qr.exports=class{constructor(){this.routes=[]}get(t,r){let n=pe.parseRoute({method:[ve.methods.GET,ve.methods.HEAD],path:t,handler:r});this.routes.push(n)}post(t,r){let n=pe.parseRoute({method:[ve.methods.POST],path:t,handler:r});this.routes.push(n)}patch(t,r){let n=pe.parseRoute({method:[ve.methods.PATCH],path:t,handler:r});this.routes.push(n)}del(t,r){let n=pe.parseRoute({method:[ve.methods.DELETE],path:t,handler:r});this.routes.push(n)}use(t){let r=pe.parseRoute({handler:t,middleware:!0});this.routes.push(r)}add({host:t,path:r,excludePath:n,method:o,handlerName:s,headers:a,protocol:i},c){let u=pe.parseRoute({method:o,host:t,path:r,excludePath:n,handler:c,headers:a,handlerName:s,protocol:i});this.routes.push(u)}async resolve(t){let r=new ss(t);try{return await os.recurseRoutes(r,this.routes),new Response(r.body,{status:r.status,headers:r.response.headers})}catch(n){return new Response(n.message,{status:500})}}}});var $=v((Bu,rn)=>{var as="Expected a function",jr="__lodash_hash_undefined__",zr=1/0,is="[object Function]",cs="[object GeneratorFunction]",us="[object Symbol]",ds=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ps=/^\w*$/,hs=/^\./,ls=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fs=/[\\^$.*+?()[\]{}|]/g,ms=/\\(\\)?/g,ys=/^\[object .+?Constructor\]$/,gs=typeof global=="object"&&global&&global.Object===Object&&global,ws=typeof self=="object"&&self&&self.Object===Object&&self,Et=gs||ws||Function("return this")();function As(e,t){return e?.[t]}function Ss(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var bs=Array.prototype,Es=Function.prototype,Xr=Object.prototype,bt=Et["__core-js_shared__"],Lr=function(){var e=/[^.]+$/.exec(bt&&bt.keys&&bt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Yr=Es.toString,Ct=Xr.hasOwnProperty,Zr=Xr.toString,Cs=RegExp("^"+Yr.call(Ct).replace(fs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Gr=Et.Symbol,_s=bs.splice,vs=Qr(Et,"Map"),Pe=Qr(Object,"create"),Br=Gr?Gr.prototype:void 0,Vr=Br?Br.toString:void 0;function re(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ps(){this.__data__=Pe?Pe(null):{}}function Ts(e){return this.has(e)&&delete this.__data__[e]}function Hs(e){var t=this.__data__;if(Pe){var r=t[e];return r===jr?void 0:r}return Ct.call(t,e)?t[e]:void 0}function Ks(e){var t=this.__data__;return Pe?t[e]!==void 0:Ct.call(t,e)}function Os(e,t){var r=this.__data__;return r[e]=Pe&&t===void 0?jr:t,this}re.prototype.clear=Ps;re.prototype.delete=Ts;re.prototype.get=Hs;re.prototype.has=Ks;re.prototype.set=Os;function he(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Rs(){this.__data__=[]}function xs(e){var t=this.__data__,r=Le(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():_s.call(t,r,1),!0}function Us(e){var t=this.__data__,r=Le(t,e);return r<0?void 0:t[r][1]}function ks(e){return Le(this.__data__,e)>-1}function Is(e,t){var r=this.__data__,n=Le(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}he.prototype.clear=Rs;he.prototype.delete=xs;he.prototype.get=Us;he.prototype.has=ks;he.prototype.set=Is;function ne(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ws(){this.__data__={hash:new re,map:new(vs||he),string:new re}}function Ns(e){return Ge(this,e).delete(e)}function Js(e){return Ge(this,e).get(e)}function Ds(e){return Ge(this,e).has(e)}function $s(e,t){return Ge(this,e).set(e,t),this}ne.prototype.clear=Ws;ne.prototype.delete=Ns;ne.prototype.get=Js;ne.prototype.has=Ds;ne.prototype.set=$s;function Le(e,t){for(var r=e.length;r--;)if(Ys(e[r][0],t))return r;return-1}function Ms(e,t){t=Gs(t,e)?[t]:Ls(t);for(var r=0,n=t.length;e!=null&&r<n;)e=e[zs(t[r++])];return r&&r==n?e:void 0}function qs(e){if(!tn(e)||Vs(e))return!1;var t=Zs(e)||Ss(e)?Cs:ys;return t.test(Xs(e))}function Fs(e){if(typeof e=="string")return e;if(vt(e))return Vr?Vr.call(e):"";var t=e+"";return t=="0"&&1/e==-zr?"-0":t}function Ls(e){return en(e)?e:js(e)}function Ge(e,t){var r=e.__data__;return Bs(t)?r[typeof t=="string"?"string":"hash"]:r.map}function Qr(e,t){var r=As(e,t);return qs(r)?r:void 0}function Gs(e,t){if(en(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||vt(e)?!0:ps.test(e)||!ds.test(e)||t!=null&&e in Object(t)}function Bs(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Vs(e){return!!Lr&&Lr in e}var js=_t(function(e){e=ea(e);var t=[];return hs.test(e)&&t.push(""),e.replace(ls,function(r,n,o,s){t.push(o?s.replace(ms,"$1"):n||r)}),t});function zs(e){if(typeof e=="string"||vt(e))return e;var t=e+"";return t=="0"&&1/e==-zr?"-0":t}function Xs(e){if(e!=null){try{return Yr.call(e)}catch{}try{return e+""}catch{}}return""}function _t(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(as);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],s=r.cache;if(s.has(o))return s.get(o);var a=e.apply(this,n);return r.cache=s.set(o,a),a};return r.cache=new(_t.Cache||ne),r}_t.Cache=ne;function Ys(e,t){return e===t||e!==e&&t!==t}var en=Array.isArray;function Zs(e){var t=tn(e)?Zr.call(e):"";return t==is||t==cs}function tn(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Qs(e){return!!e&&typeof e=="object"}function vt(e){return typeof e=="symbol"||Qs(e)&&Zr.call(e)==us}function ea(e){return e==null?"":Fs(e)}function ta(e,t,r){var n=e==null?void 0:Ms(e,t);return n===void 0?r:n}rn.exports=ta});var je=v((Ve,fn)=>{(function(e,t){typeof Ve=="object"&&typeof fn<"u"?t(Ve):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.aws4fetch={}))})(Ve,function(e){"use strict";let t=new TextEncoder,r={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},n=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class o{constructor({accessKeyId:h,secretAccessKey:f,sessionToken:l,service:g,region:y,cache:w,retries:b,initRetryMs:K}){if(h==null)throw new TypeError("accessKeyId is a required option");if(f==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=h,this.secretAccessKey=f,this.sessionToken=l,this.service=g,this.region=y,this.cache=w||new Map,this.retries=b??10,this.initRetryMs=K||50}async sign(h,f){if(h instanceof Request){let{method:y,url:w,headers:b,body:K}=h;f=Object.assign({method:y,url:w,headers:b},f),f.body==null&&b.has("Content-Type")&&(f.body=K!=null&&b.has("X-Amz-Content-Sha256")?K:await h.clone().arrayBuffer()),h=w}let l=new s(Object.assign({url:h},f,this,f&&f.aws)),g=Object.assign({},f,await l.sign());return delete g.aws,new Request(g.url.toString(),g)}async fetch(h,f){for(let l=0;l<=this.retries;l++){let g=fetch(await this.sign(h,f));if(l===this.retries)return g;let y=await g;if(y.status<500&&y.status!==429)return y;await new Promise(w=>setTimeout(w,Math.random()*this.initRetryMs*Math.pow(2,l)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class s{constructor({method:h,url:f,headers:l,body:g,accessKeyId:y,secretAccessKey:w,sessionToken:b,service:K,region:O,cache:ee,datetime:be,signQuery:ft,appendSessionToken:mt,allHeaders:Me,singleEncode:yt}){if(f==null)throw new TypeError("url is a required option");if(y==null)throw new TypeError("accessKeyId is a required option");if(w==null)throw new TypeError("secretAccessKey is a required option");this.method=h||(g?"POST":"GET"),this.url=new URL(f),this.headers=new Headers(l||{}),this.body=g,this.accessKeyId=y,this.secretAccessKey=w,this.sessionToken=b;let V,Ee;(!K||!O)&&([V,Ee]=p(this.url,this.headers)),this.service=K||V||"",this.region=O||Ee||"us-east-1",this.cache=ee||new Map,this.datetime=be||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=ft,this.appendSessionToken=mt||this.service==="iotdevicegateway",this.headers.delete("Host");let q=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),q.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&q.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>Me||!n.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
2
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!q.has("X-Amz-Expires")&&q.set("X-Amz-Expires","86400"),q.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),q.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),q.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");yt||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=u(this.encodedPath);let qe=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if(qe.has(_))return!1;qe.add(_)}return!0}).map(_=>_.map(Ce=>u(encodeURIComponent(Ce)))).sort(([_,Ce],[_e,Fe])=>_<_e?-1:_>_e?1:Ce<Fe?-1:Ce>Fe?1:0).map(_=>_.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let h=this.datetime.slice(0,8),f=[this.secretAccessKey,h,this.region,this.service].join(),l=this.cache.get(f);if(!l){let g=await a("AWS4"+this.secretAccessKey,h),y=await a(g,this.region),w=await a(y,this.service);l=await a(w,"aws4_request"),this.cache.set(f,l)}return c(await a(l,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,c(await i(await this.canonicalString()))].join(`
1
+ "use strict";var Go=Object.create;var xr=Object.defineProperty;var Bo=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,zo=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Xo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vo(t))!zo.call(e,o)&&o!==r&&xr(e,o,{get:()=>t[o],enumerable:!(n=Bo(t,o))||n.enumerable});return e};var P=(e,t,r)=>(r=e!=null?Go(jo(e)):{},Xo(t||!e||!e.__esModule?xr(r,"default",{value:e,enumerable:!0}):r,e));var At=v(($u,kr)=>{function Yo({host:e=".*",path:t=".*",excludePath:r=null,method:n=[".*"],handler:o,protocol:a=".*",handlerName:s,headers:i={},data:c}){let u=[],p=[],d=e.replace(/(:([^.]+))/g,(b,K,O)=>(u.push(O),"([^.]+)")),h=t.replace(/(:([^/]+))/g,(b,K,O)=>O.slice(-1)==="*"?(p.push(O.slice(0,O.length-1)),"(.*)"):(p.push(O),"([^/]*)")),f=new RegExp(`^${d}$`,"i"),l=new RegExp(`^${h}$`,"i"),g=r?new RegExp(`^${r}$`,"i"):null,y=new RegExp(`^${n.join("|")}$`,"i"),w=new RegExp(`^${a}$`,"i");return{hostVariables:u,pathVariables:p,host:f,path:l,excludePath:g,method:y,protocol:w,handler:o,handlerName:s,headers:i,data:c}}function Ur(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}async function Zo(e,t=1024*1024){let r=[],n=e.getReader(),o=new TextDecoder,a=0;for(;t&&a<t;){let{done:i,value:c}=await n.read();if(i)break;a+=c.byteLength,r.push(o.decode(c))}let s=r.join("");return t?s.substring(0,t):s}function Qo(e){let t=new URL(e.url),r=Ur(t.searchParams),n=Ur(e.headers);n.host&&(t.hostname=n.host);let o,a;async function s(i){if(a>=i)return o.substring(0,i);let c=e.clone();return o=await Zo(c.body,i),o}return{body:e.body,headers:n,host:t.host,hostname:t.hostname,href:t.href,json:async i=>JSON.parse(s(i)),method:e.method,origin:`${t.protocol}//${t.host}`,path:t.pathname,protocol:t.protocol.slice(0,-1),query:r,querystring:t.search.slice(1),search:t.search,text:async i=>e.headers.get("content-type")==="application/x-www-form-urlencoded"?decodeURIComponent(await s(i)):s(i)}}kr.exports={parseRoute:Yo,parseRequest:Qo}});var Wr=v((Mu,Ir)=>{function ea(e,t){let r={},n=t.host.exec(e.host);t.hostVariables.forEach((a,s)=>{r[a]=n[s+1]});let o=t.path.exec(e.path);return t.pathVariables.forEach((a,s)=>{r[a]=o[s+1]}),r}function ta(e,t){let r=!0;return Object.keys(e.headers).forEach(n=>{t.headers[n]!==e.headers[n]&&(r=!1)}),r}function ra(e,t){return e.protocol.test(t.protocol)}function na(e,t){return e.method.test(t.method)&&e.host.test(t.host)&&e.path.test(t.path)&&ta(e,t)&&ra(e,t)&&(!e.excludePath||!e.excludePath.test(t.path))}async function St(e,t){let[r,...n]=t;if(!r)return new Response("NOT_FOUND",{status:404});if(!na(r,e.request))return St(e,n);e.state.handlers=e.state.handlers||[],e.state.handlers.push(r.handlerName||r.handler.name),e.params=ea(e.request,r);try{return r.handler(e,async o=>St(o,n))}catch(o){throw o.route=r.handler.name,o}}Ir.exports={recurseRoutes:St}});var Jr=v((qu,Nr)=>{Nr.exports={methods:{DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST"},statusMessages:{404:"Not found",429:"Rate limited"}}});var Mr=v((Fu,$r)=>{var oa=At();$r.exports=class Dr{constructor(t){this.request=oa.parseRequest(t.request),this.event=t,this.state={},this.cloned=!1,this.response={headers:{}},this.body="",this.status=404,this.query=this.request.query}header(t){return this.request.headers[t]}set(t,r){this.response.headers[t]=r}clone(){let t=new Dr(this.event);return t.cloned=!0,t}}});var Fr=v((Gu,qr)=>{var pe=At(),aa=Wr(),ve=Jr(),sa=Mr();qr.exports=class{constructor(){this.routes=[]}get(t,r){let n=pe.parseRoute({method:[ve.methods.GET,ve.methods.HEAD],path:t,handler:r});this.routes.push(n)}post(t,r){let n=pe.parseRoute({method:[ve.methods.POST],path:t,handler:r});this.routes.push(n)}patch(t,r){let n=pe.parseRoute({method:[ve.methods.PATCH],path:t,handler:r});this.routes.push(n)}del(t,r){let n=pe.parseRoute({method:[ve.methods.DELETE],path:t,handler:r});this.routes.push(n)}use(t){let r=pe.parseRoute({handler:t,middleware:!0});this.routes.push(r)}add({host:t,path:r,excludePath:n,method:o,handlerName:a,headers:s,protocol:i},c){let u=pe.parseRoute({method:o,host:t,path:r,excludePath:n,handler:c,headers:s,handlerName:a,protocol:i});this.routes.push(u)}async resolve(t){let r=new sa(t);try{return await aa.recurseRoutes(r,this.routes),new Response(r.body,{status:r.status,headers:r.response.headers})}catch(n){return new Response(n.message,{status:500})}}}});var $=v((Bu,rn)=>{var ia="Expected a function",jr="__lodash_hash_undefined__",zr=1/0,ca="[object Function]",ua="[object GeneratorFunction]",da="[object Symbol]",pa=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ha=/^\w*$/,la=/^\./,fa=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ma=/[\\^$.*+?()[\]{}|]/g,ya=/\\(\\)?/g,ga=/^\[object .+?Constructor\]$/,wa=typeof global=="object"&&global&&global.Object===Object&&global,Aa=typeof self=="object"&&self&&self.Object===Object&&self,Et=wa||Aa||Function("return this")();function Sa(e,t){return e?.[t]}function ba(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var Ea=Array.prototype,Ca=Function.prototype,Xr=Object.prototype,bt=Et["__core-js_shared__"],Lr=function(){var e=/[^.]+$/.exec(bt&&bt.keys&&bt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Yr=Ca.toString,Ct=Xr.hasOwnProperty,Zr=Xr.toString,_a=RegExp("^"+Yr.call(Ct).replace(ma,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Gr=Et.Symbol,va=Ea.splice,Pa=Qr(Et,"Map"),Pe=Qr(Object,"create"),Br=Gr?Gr.prototype:void 0,Vr=Br?Br.toString:void 0;function re(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ta(){this.__data__=Pe?Pe(null):{}}function Ha(e){return this.has(e)&&delete this.__data__[e]}function Ka(e){var t=this.__data__;if(Pe){var r=t[e];return r===jr?void 0:r}return Ct.call(t,e)?t[e]:void 0}function Oa(e){var t=this.__data__;return Pe?t[e]!==void 0:Ct.call(t,e)}function Ra(e,t){var r=this.__data__;return r[e]=Pe&&t===void 0?jr:t,this}re.prototype.clear=Ta;re.prototype.delete=Ha;re.prototype.get=Ka;re.prototype.has=Oa;re.prototype.set=Ra;function he(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function xa(){this.__data__=[]}function Ua(e){var t=this.__data__,r=Ge(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():va.call(t,r,1),!0}function ka(e){var t=this.__data__,r=Ge(t,e);return r<0?void 0:t[r][1]}function Ia(e){return Ge(this.__data__,e)>-1}function Wa(e,t){var r=this.__data__,n=Ge(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}he.prototype.clear=xa;he.prototype.delete=Ua;he.prototype.get=ka;he.prototype.has=Ia;he.prototype.set=Wa;function ne(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Na(){this.__data__={hash:new re,map:new(Pa||he),string:new re}}function Ja(e){return Be(this,e).delete(e)}function Da(e){return Be(this,e).get(e)}function $a(e){return Be(this,e).has(e)}function Ma(e,t){return Be(this,e).set(e,t),this}ne.prototype.clear=Na;ne.prototype.delete=Ja;ne.prototype.get=Da;ne.prototype.has=$a;ne.prototype.set=Ma;function Ge(e,t){for(var r=e.length;r--;)if(Za(e[r][0],t))return r;return-1}function qa(e,t){t=Ba(t,e)?[t]:Ga(t);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Xa(t[r++])];return r&&r==n?e:void 0}function Fa(e){if(!tn(e)||ja(e))return!1;var t=Qa(e)||ba(e)?_a:ga;return t.test(Ya(e))}function La(e){if(typeof e=="string")return e;if(vt(e))return Vr?Vr.call(e):"";var t=e+"";return t=="0"&&1/e==-zr?"-0":t}function Ga(e){return en(e)?e:za(e)}function Be(e,t){var r=e.__data__;return Va(t)?r[typeof t=="string"?"string":"hash"]:r.map}function Qr(e,t){var r=Sa(e,t);return Fa(r)?r:void 0}function Ba(e,t){if(en(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||vt(e)?!0:ha.test(e)||!pa.test(e)||t!=null&&e in Object(t)}function Va(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function ja(e){return!!Lr&&Lr in e}var za=_t(function(e){e=ts(e);var t=[];return la.test(e)&&t.push(""),e.replace(fa,function(r,n,o,a){t.push(o?a.replace(ya,"$1"):n||r)}),t});function Xa(e){if(typeof e=="string"||vt(e))return e;var t=e+"";return t=="0"&&1/e==-zr?"-0":t}function Ya(e){if(e!=null){try{return Yr.call(e)}catch{}try{return e+""}catch{}}return""}function _t(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(ia);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var s=e.apply(this,n);return r.cache=a.set(o,s),s};return r.cache=new(_t.Cache||ne),r}_t.Cache=ne;function Za(e,t){return e===t||e!==e&&t!==t}var en=Array.isArray;function Qa(e){var t=tn(e)?Zr.call(e):"";return t==ca||t==ua}function tn(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function es(e){return!!e&&typeof e=="object"}function vt(e){return typeof e=="symbol"||es(e)&&Zr.call(e)==da}function ts(e){return e==null?"":La(e)}function rs(e,t,r){var n=e==null?void 0:qa(e,t);return n===void 0?r:n}rn.exports=rs});var ze=v((je,fn)=>{(function(e,t){typeof je=="object"&&typeof fn<"u"?t(je):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.aws4fetch={}))})(je,function(e){"use strict";let t=new TextEncoder,r={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},n=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class o{constructor({accessKeyId:h,secretAccessKey:f,sessionToken:l,service:g,region:y,cache:w,retries:b,initRetryMs:K}){if(h==null)throw new TypeError("accessKeyId is a required option");if(f==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=h,this.secretAccessKey=f,this.sessionToken=l,this.service=g,this.region=y,this.cache=w||new Map,this.retries=b??10,this.initRetryMs=K||50}async sign(h,f){if(h instanceof Request){let{method:y,url:w,headers:b,body:K}=h;f=Object.assign({method:y,url:w,headers:b},f),f.body==null&&b.has("Content-Type")&&(f.body=K!=null&&b.has("X-Amz-Content-Sha256")?K:await h.clone().arrayBuffer()),h=w}let l=new a(Object.assign({url:h},f,this,f&&f.aws)),g=Object.assign({},f,await l.sign());return delete g.aws,new Request(g.url.toString(),g)}async fetch(h,f){for(let l=0;l<=this.retries;l++){let g=fetch(await this.sign(h,f));if(l===this.retries)return g;let y=await g;if(y.status<500&&y.status!==429)return y;await new Promise(w=>setTimeout(w,Math.random()*this.initRetryMs*Math.pow(2,l)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class a{constructor({method:h,url:f,headers:l,body:g,accessKeyId:y,secretAccessKey:w,sessionToken:b,service:K,region:O,cache:ee,datetime:be,signQuery:ft,appendSessionToken:mt,allHeaders:qe,singleEncode:yt}){if(f==null)throw new TypeError("url is a required option");if(y==null)throw new TypeError("accessKeyId is a required option");if(w==null)throw new TypeError("secretAccessKey is a required option");this.method=h||(g?"POST":"GET"),this.url=new URL(f),this.headers=new Headers(l||{}),this.body=g,this.accessKeyId=y,this.secretAccessKey=w,this.sessionToken=b;let V,Ee;(!K||!O)&&([V,Ee]=p(this.url,this.headers)),this.service=K||V||"",this.region=O||Ee||"us-east-1",this.cache=ee||new Map,this.datetime=be||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=ft,this.appendSessionToken=mt||this.service==="iotdevicegateway",this.headers.delete("Host");let q=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),q.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&q.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>qe||!n.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
2
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!q.has("X-Amz-Expires")&&q.set("X-Amz-Expires","86400"),q.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),q.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),q.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");yt||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=u(this.encodedPath);let Fe=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if(Fe.has(_))return!1;Fe.add(_)}return!0}).map(_=>_.map(Ce=>u(encodeURIComponent(Ce)))).sort(([_,Ce],[_e,Le])=>_<_e?-1:_>_e?1:Ce<Le?-1:Ce>Le?1:0).map(_=>_.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let h=this.datetime.slice(0,8),f=[this.secretAccessKey,h,this.region,this.service].join(),l=this.cache.get(f);if(!l){let g=await s("AWS4"+this.secretAccessKey,h),y=await s(g,this.region),w=await s(y,this.service);l=await s(w,"aws4_request"),this.cache.set(f,l)}return c(await s(l,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,c(await i(await this.canonicalString()))].join(`
3
3
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
4
4
  `,this.signedHeaders,await this.hexBodyHash()].join(`
5
- `)}async hexBodyHash(){let h=this.headers.get("X-Amz-Content-Sha256");if(h==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");h=c(await i(this.body||""))}return h}}async function a(d,h){let f=await crypto.subtle.importKey("raw",typeof d=="string"?t.encode(d):d,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",f,t.encode(h))}async function i(d){return crypto.subtle.digest("SHA-256",typeof d=="string"?t.encode(d):d)}function c(d){return Array.prototype.map.call(new Uint8Array(d),h=>("0"+h.toString(16)).slice(-2)).join("")}function u(d){return d.replace(/[!'()*]/g,h=>"%"+h.charCodeAt(0).toString(16).toUpperCase())}function p(d,h){let{hostname:f,pathname:l}=d,g=f.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[y,w]=(g||["",""]).slice(1,3);if(w==="us-gov")w="us-gov-west-1";else if(w==="s3"||w==="s3-accelerate")w="us-east-1",y="s3";else if(y==="iot")f.startsWith("iot.")?y="execute-api":f.startsWith("data.jobs.iot.")?y="iot-jobs-data":y=l==="/mqtt"?"iotdevicegateway":"iotdata";else if(y==="autoscaling"){let b=(h.get("X-Amz-Target")||"").split(".")[0];b==="AnyScaleFrontendService"?y="application-autoscaling":b==="AnyScaleScalingPlannerFrontendService"&&(y="autoscaling-plans")}else w==null&&y.startsWith("s3-")?(w=y.slice(3).replace(/^fips-|^external-1/,""),y="s3"):y.endsWith("-fips")?y=y.slice(0,-5):w&&/-\d$/.test(y)&&!/-\d$/.test(w)&&([y,w]=[w,y]);return[r[y]||y,w]}e.AwsClient=o,e.AwsV4Signer=s,Object.defineProperty(e,"__esModule",{value:!0})})});var Qe=v((bd,Hn)=>{var Da="Expected a function",Sn="__lodash_hash_undefined__",bn=1/0,$a=9007199254740991,Ma="[object Function]",qa="[object GeneratorFunction]",Fa="[object Symbol]",La=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ga=/^\w*$/,Ba=/^\./,Va=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ja=/[\\^$.*+?()[\]{}|]/g,za=/\\(\\)?/g,Xa=/^\[object .+?Constructor\]$/,Ya=/^(?:0|[1-9]\d*)$/,Za=typeof global=="object"&&global&&global.Object===Object&&global,Qa=typeof self=="object"&&self&&self.Object===Object&&self,Vt=Za||Qa||Function("return this")();function ei(e,t){return e?.[t]}function ti(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var ri=Array.prototype,ni=Function.prototype,En=Object.prototype,Bt=Vt["__core-js_shared__"],yn=function(){var e=/[^.]+$/.exec(Bt&&Bt.keys&&Bt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Cn=ni.toString,Xe=En.hasOwnProperty,_n=En.toString,oi=RegExp("^"+Cn.call(Xe).replace(ja,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),gn=Vt.Symbol,si=ri.splice,ai=vn(Vt,"Map"),Te=vn(Object,"create"),wn=gn?gn.prototype:void 0,An=wn?wn.toString:void 0;function ae(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function ii(){this.__data__=Te?Te(null):{}}function ci(e){return this.has(e)&&delete this.__data__[e]}function ui(e){var t=this.__data__;if(Te){var r=t[e];return r===Sn?void 0:r}return Xe.call(t,e)?t[e]:void 0}function di(e){var t=this.__data__;return Te?t[e]!==void 0:Xe.call(t,e)}function pi(e,t){var r=this.__data__;return r[e]=Te&&t===void 0?Sn:t,this}ae.prototype.clear=ii;ae.prototype.delete=ci;ae.prototype.get=ui;ae.prototype.has=di;ae.prototype.set=pi;function le(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function hi(){this.__data__=[]}function li(e){var t=this.__data__,r=Ye(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():si.call(t,r,1),!0}function fi(e){var t=this.__data__,r=Ye(t,e);return r<0?void 0:t[r][1]}function mi(e){return Ye(this.__data__,e)>-1}function yi(e,t){var r=this.__data__,n=Ye(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}le.prototype.clear=hi;le.prototype.delete=li;le.prototype.get=fi;le.prototype.has=mi;le.prototype.set=yi;function ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function gi(){this.__data__={hash:new ae,map:new(ai||le),string:new ae}}function wi(e){return Ze(this,e).delete(e)}function Ai(e){return Ze(this,e).get(e)}function Si(e){return Ze(this,e).has(e)}function bi(e,t){return Ze(this,e).set(e,t),this}ie.prototype.clear=gi;ie.prototype.delete=wi;ie.prototype.get=Ai;ie.prototype.has=Si;ie.prototype.set=bi;function Ei(e,t,r){var n=e[t];(!(Xe.call(e,t)&&Pn(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function Ye(e,t){for(var r=e.length;r--;)if(Pn(e[r][0],t))return r;return-1}function Ci(e){if(!ze(e)||Oi(e))return!1;var t=ki(e)||ti(e)?oi:Xa;return t.test(Ui(e))}function _i(e,t,r,n){if(!ze(e))return e;t=Hi(t,e)?[t]:Pi(t);for(var o=-1,s=t.length,a=s-1,i=e;i!=null&&++o<s;){var c=xi(t[o]),u=r;if(o!=a){var p=i[c];u=n?n(p,c,i):void 0,u===void 0&&(u=ze(p)?p:Ti(t[o+1])?[]:{})}Ei(i,c,u),i=i[c]}return e}function vi(e){if(typeof e=="string")return e;if(zt(e))return An?An.call(e):"";var t=e+"";return t=="0"&&1/e==-bn?"-0":t}function Pi(e){return Tn(e)?e:Ri(e)}function Ze(e,t){var r=e.__data__;return Ki(t)?r[typeof t=="string"?"string":"hash"]:r.map}function vn(e,t){var r=ei(e,t);return Ci(r)?r:void 0}function Ti(e,t){return t=t??$a,!!t&&(typeof e=="number"||Ya.test(e))&&e>-1&&e%1==0&&e<t}function Hi(e,t){if(Tn(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||zt(e)?!0:Ga.test(e)||!La.test(e)||t!=null&&e in Object(t)}function Ki(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Oi(e){return!!yn&&yn in e}var Ri=jt(function(e){e=Wi(e);var t=[];return Ba.test(e)&&t.push(""),e.replace(Va,function(r,n,o,s){t.push(o?s.replace(za,"$1"):n||r)}),t});function xi(e){if(typeof e=="string"||zt(e))return e;var t=e+"";return t=="0"&&1/e==-bn?"-0":t}function Ui(e){if(e!=null){try{return Cn.call(e)}catch{}try{return e+""}catch{}}return""}function jt(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(Da);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],s=r.cache;if(s.has(o))return s.get(o);var a=e.apply(this,n);return r.cache=s.set(o,a),a};return r.cache=new(jt.Cache||ie),r}jt.Cache=ie;function Pn(e,t){return e===t||e!==e&&t!==t}var Tn=Array.isArray;function ki(e){var t=ze(e)?_n.call(e):"";return t==Ma||t==qa}function ze(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Ii(e){return!!e&&typeof e=="object"}function zt(e){return typeof e=="symbol"||Ii(e)&&_n.call(e)==Fa}function Wi(e){return e==null?"":vi(e)}function Ni(e,t,r){return e==null?e:_i(e,t,r)}Hn.exports=Ni});var In=v(Qt=>{"use strict";Qt.parse=Gi;Qt.serialize=Bi;var qi=decodeURIComponent,Fi=encodeURIComponent,Li=/; */,tt=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function Gi(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");for(var r={},n=t||{},o=e.split(Li),s=n.decode||qi,a=0;a<o.length;a++){var i=o[a],c=i.indexOf("=");if(!(c<0)){var u=i.substr(0,c).trim(),p=i.substr(++c,i.length).trim();p[0]=='"'&&(p=p.slice(1,-1)),r[u]==null&&(r[u]=Vi(p,s))}}return r}function Bi(e,t,r){var n=r||{},o=n.encode||Fi;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!tt.test(e))throw new TypeError("argument name is invalid");var s=o(t);if(s&&!tt.test(s))throw new TypeError("argument val is invalid");var a=e+"="+s;if(n.maxAge!=null){var i=n.maxAge-0;if(isNaN(i)||!isFinite(i))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(i)}if(n.domain){if(!tt.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!tt.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.sameSite){var c=typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite;switch(c){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function Vi(e,t){try{return t(e)}catch{return e}}});var Nn=v((Dd,Wn)=>{"use strict";var rt=1;function ji(){return rt=(rt*9301+49297)%233280,rt/233280}function zi(e){rt=e}Wn.exports={nextValue:ji,seed:zi}});var Re=v(($d,Mn)=>{"use strict";var er=Nn(),ue="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",j,Jn,Oe;function tr(){Oe=!1}function Dn(e){if(!e){j!==ue&&(j=ue,tr());return}if(e!==j){if(e.length!==ue.length)throw new Error("Custom alphabet for shortid must be "+ue.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter(function(r,n,o){return n!==o.lastIndexOf(r)});if(t.length)throw new Error("Custom alphabet for shortid must be "+ue.length+" unique characters. These characters were not unique: "+t.join(", "));j=e,tr()}}function Xi(e){return Dn(e),j}function Yi(e){er.seed(e),Jn!==e&&(tr(),Jn=e)}function Zi(){j||Dn(ue);for(var e=j.split(""),t=[],r=er.nextValue(),n;e.length>0;)r=er.nextValue(),n=Math.floor(r*e.length),t.push(e.splice(n,1)[0]);return t.join("")}function $n(){return Oe||(Oe=Zi(),Oe)}function Qi(e){var t=$n();return t[e]}function ec(){return j||ue}Mn.exports={get:ec,characters:Xi,seed:Yi,lookup:Qi,shuffled:$n}});var Fn=v((Md,qn)=>{"use strict";var rr=typeof window=="object"&&(window.crypto||window.msCrypto),nr;!rr||!rr.getRandomValues?nr=function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(Math.random()*256));return t}:nr=function(e){return rr.getRandomValues(new Uint8Array(e))};qn.exports=nr});var Gn=v((qd,Ln)=>{Ln.exports=function(e,t,r){for(var n=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*n*r/t.length),s="";;)for(var a=e(o),i=o;i--;)if(s+=t[a[i]&n]||"",s.length===+r)return s}});var Vn=v((Fd,Bn)=>{"use strict";var tc=Re(),rc=Fn(),nc=Gn();function oc(e){for(var t=0,r,n="";!r;)n=n+nc(rc,tc.get(),1),r=e<Math.pow(16,t+1),t++;return n}Bn.exports=oc});var Xn=v((Gd,zn)=>{"use strict";var nt=Vn(),Ld=Re(),sc=1567752802062,ac=7,ot,jn;function ic(e){var t="",r=Math.floor((Date.now()-sc)*.001);return r===jn?ot++:(ot=0,jn=r),t=t+nt(ac),t=t+nt(e),ot>0&&(t=t+nt(ot)),t=t+nt(r),t}zn.exports=ic});var Zn=v((Bd,Yn)=>{"use strict";var cc=Re();function uc(e){if(!e||typeof e!="string"||e.length<6)return!1;var t=new RegExp("[^"+cc.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]");return!t.test(e)}Yn.exports=uc});var eo=v((Vd,Qn)=>{"use strict";Qn.exports=0});var no=v((jd,G)=>{"use strict";var or=Re(),dc=Xn(),pc=Zn(),to=eo()||0;function hc(e){return or.seed(e),G.exports}function lc(e){return to=e,G.exports}function fc(e){return e!==void 0&&or.characters(e),or.shuffled()}function ro(){return dc(to)}G.exports=ro;G.exports.generate=ro;G.exports.seed=hc;G.exports.worker=lc;G.exports.characters=fc;G.exports.isValid=pc});var so=v((zd,oo)=>{"use strict";oo.exports=no()});var Jo=P(Fr());var nn=P($()),ra={get:nn.default};function Pt(e){e.status=401,e.body="Unauthorized",e.set("WWW-Authenticate","Basic")}function Tt(e){return async(t,r)=>{if(t.request.path===e.logoutPath)return Pt(t);let n=ra.get(t,"request.headers.authorization");if(!n||!n.startsWith("Basic "))return Pt(t);let o=e.users.map(i=>i.authToken),s=n.substring(6),a=o.indexOf(s);return a===-1?Pt(t):(t.state.user=e.users[a].username,r(t))}}var on=caches.default;async function na(e){return await on.match(e)}async function oa(e,t){return on.put(e.href,t)}var Ht={get:na,set:oa};async function sa(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}var sn=sa;function aa(e,t={}){return Object.keys(t).reduce((r,n)=>r.replace(`{${n}}`,t[n]),e)}function Kt(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}function ia(e,t){Object.entries(e).forEach(([r,n])=>{t.header(r)||t.set(r,n)})}var Ot=e=>{e.set=(t,r)=>{e.response.headers[t.toLowerCase()]=r},e.header=t=>e.request.headers[t.toLowerCase()]},A={resolveParams:aa,instanceToJson:Kt,mergeHeaders:ia,upgradeCTX:Ot};var ca=["x-ratelimit-count","x-ratelimit-limit","x-ratelimit-reset","x-cache-hit"];async function ua(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}async function da(e,t){if(!t)return e.event.request;let r=t.match(/{.*?}/gi).map(s=>s.slice(1,-1)),n={};for(let s=0;s<r.length;s+=1){let a=r[s],i=a.split(":");switch(i[0]){case"method":n[a]=e.request.method;break;case"path":n[a]=e.request.path;break;case"bodyHash":n[a]=await sn(await ua(e.request));break;case"header":n[a]=e.request.headers[i[1]]||"";break;default:n[a]=a}}let o=encodeURIComponent(t.replace(/({(.*?)})/gi,(s,a,i)=>n[i]));return new Request(`http://${e.request.hostname}/${o}`)}function Rt({cacheDuration:e,cacheKeyTemplate:t,headerBlacklist:r=ca}){return async(n,o)=>{let s=await da(n,t),a=await Ht.get(s);if(a){n.body=a.body,n.status=a.status;let i=Kt(a.headers);Object.keys(i).forEach(c=>{n.set(c,i[c])}),n.set("X-Cache-Hit",!0)}else{await o(n);let i;n.body.tee?[n.body,i]=n.body.tee():i=n.body;let c=new Response(i,{status:n.status});Object.keys(n.response.headers).forEach(u=>{r.indexOf(u.toLowerCase())===-1&&c.headers.set(u,n.response.headers[u])}),e&&(c.headers.delete("Cache-Control"),c.headers.set("Cache-Control",`max-age=${e}`)),n.event.waitUntil(Ht.set(s,c))}}}function xt({allowedOrigins:e=["*"],allowedMethods:t=["GET","PUT","POST","PATCH","DELETE","HEAD","OPTIONS"],allowCredentials:r=!0,allowedHeaders:n=["Content-Type"],allowedExposeHeaders:o=[],maxAge:s=600,optionsSuccessStatus:a=204,terminatePreflight:i=!1}){return async(c,u)=>{let{method:p}=c.request,{origin:d}=c.request.headers,h=c.request.headers["access-control-request-headers"];if(pa(c,d,e),ha(c,r),ya(c,o),!t.includes(p.toUpperCase())){c.status=405,c.body={error:`Method ${p} not allowed`};return}if(p==="OPTIONS"&&(la(c,t),fa(c,h,n),ma(c,s),i)){c.status=a,c.body=null,c.set("content-length","0");return}await u(c)}}function pa(e,t,r){if(Array.isArray(r)){if(r[0]==="origin"){e.set("Access-Control-Allow-Origin",t),an(e,"Origin");return}r[0]==="*"?e.set("Access-Control-Allow-Origin","*"):r.indexOf(t)!==-1&&(e.set("Access-Control-Allow-Origin",t),an(e,"Origin"))}}function ha(e,t){t&&e.set("Access-Control-Allow-Credentials",String(t))}function la(e,t){e.set("Access-Control-Allow-Methods",t.join(","))}function fa(e,t,r){r.length===0&&t?e.set("Access-Control-Allow-Headers",t):r.length&&e.set("Access-Control-Allow-Headers",r.join(","))}function ma(e,t){t&&e.set("Access-Control-Max-Age",String(t))}function ya(e,t){t.length&&e.set("Access-Control-Expose-Headers",t.join(","))}function an(e,t){let r=e.header("vary")||e.header("Vary");(r?.split(",").map(o=>o.trim().toLowerCase())||[]).includes(t.toLowerCase())||e.set("Vary",r?`${r}, ${t}`:t)}var ga={AF:"AS",AL:"EU",AQ:"AN",DZ:"AF",AS:"OC",AD:"EU",AO:"AF",AG:"NA",AZ:"EU",AR:"SA",AU:"OC",AT:"EU",BS:"NA",BH:"AS",BD:"AS",AM:"EU",BB:"NA",BE:"EU",BM:"NA",BT:"AS",BO:"SA",BA:"EU",BW:"AF",BV:"AN",BR:"SA",BZ:"NA",IO:"AS",SB:"OC",VG:"NA",BN:"AS",BG:"EU",MM:"AS",BI:"AF",BY:"EU",KH:"AS",CM:"AF",CA:"NA",CV:"AF",KY:"NA",CF:"AF",LK:"AS",TD:"AF",CL:"SA",CN:"AS",TW:"AS",CX:"AS",CC:"AS",CO:"SA",KM:"AF",YT:"AF",CG:"AF",CD:"AF",CK:"OC",CR:"NA",HR:"EU",CU:"NA",CY:"EU",CZ:"EU",BJ:"AF",DK:"EU",DM:"NA",DO:"NA",EC:"SA",SV:"NA",GQ:"AF",ET:"AF",ER:"AF",EE:"EU",FO:"EU",FK:"SA",GS:"AN",FJ:"OC",FI:"EU",AX:"EU",FR:"EU",GF:"SA",PF:"OC",TF:"AN",DJ:"AF",GA:"AF",GE:"EU",GM:"AF",PS:"AS",DE:"EU",GH:"AF",GI:"EU",KI:"OC",GR:"EU",GL:"NA",GD:"NA",GP:"NA",GU:"OC",GT:"NA",GN:"AF",GY:"SA",HT:"NA",HM:"AN",VA:"EU",HN:"NA",HK:"AS",HU:"EU",IS:"EU",IN:"AS",ID:"AS",IR:"AS",IQ:"AS",IE:"EU",IL:"AS",IT:"EU",CI:"AF",JM:"NA",JP:"AS",KZ:"EU",JO:"AS",KE:"AF",KP:"AS",KR:"AS",KW:"AS",KG:"AS",LA:"AS",LB:"AS",LS:"AF",LV:"EU",LR:"AF",LY:"AF",LI:"EU",LT:"EU",LU:"EU",MO:"AS",MG:"AF",MW:"AF",MY:"AS",MV:"AS",ML:"AF",MT:"EU",MQ:"NA",MR:"AF",MU:"AF",MX:"NA",MC:"EU",MN:"AS",MD:"EU",ME:"EU",MS:"NA",MA:"AF",MZ:"AF",OM:"AS",NA:"AF",NR:"OC",NP:"AS",NL:"EU",AN:"NA",CW:"NA",AW:"NA",SX:"NA",BQ:"NA",NC:"OC",VU:"OC",NZ:"OC",NI:"NA",NE:"AF",NG:"AF",NU:"OC",NF:"OC",NO:"EU",MP:"OC",UM:"OC",FM:"OC",MH:"OC",PW:"OC",PK:"AS",PA:"NA",PG:"OC",PY:"SA",PE:"SA",PH:"AS",PN:"OC",PL:"EU",PT:"EU",GW:"AF",TL:"AS",PR:"NA",QA:"AS",RE:"AF",RO:"EU",RU:"EU",RW:"AF",BL:"NA",SH:"AF",KN:"NA",AI:"NA",LC:"NA",MF:"NA",PM:"NA",VC:"NA",SM:"EU",ST:"AF",SA:"AS",SN:"AF",RS:"EU",SC:"AF",SL:"AF",SG:"AS",SK:"EU",VN:"AS",SI:"EU",SO:"AF",ZA:"AF",ZW:"AF",ES:"EU",SS:"AF",EH:"AF",SD:"AF",SR:"SA",SJ:"EU",SZ:"AF",SE:"EU",CH:"EU",SY:"AS",TJ:"AS",TH:"AS",TG:"AF",TK:"OC",TO:"OC",TT:"NA",AE:"AS",TN:"AF",TR:"EU",TM:"AS",TC:"NA",TV:"OC",UG:"AF",UA:"EU",MK:"EU",EG:"AF",GB:"EU",GG:"EU",JE:"EU",IM:"EU",TZ:"AF",US:"NA",VI:"NA",BF:"AF",UY:"SA",UZ:"AS",VE:"SA",WF:"OC",WS:"OC",YE:"AS",ZM:"AF",XX:"XX"};function Ut(){return async(e,t)=>{let r=e.request.headers["cf-ipcountry"]||"XX";e.request.headers["proxy-continent"]=ga[r],await t(e)}}function wa(e){let t=0;for(let r=0;r<e.length;r+=1)t=(t*31+e.charCodeAt(r))%2147483647;return t}function Aa(e){let t=globalThis[e];if(!t)throw new Error(`Durable Object binding ${e} was not found on global scope`);return t}function kt({bindingName:e,cacheKey:t,shardCount:r}){let n=Aa(e),o=wa(t)%r,s=n.idFromName(`ttl-cache:${o}`);return n.get(s)}async function Sa(e){return e.json()}var oe=class{constructor({bindingName:t,shardCount:r=64}){this.bindingName=t,this.shardCount=r}async get(t){let n=await kt({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`);if(n.status===404)return null;if(!n.ok)throw new Error("Failed to read cache record from Durable Object");return Sa(n)}async put({cacheKey:t,value:r,ttlSeconds:n}){if(!(await kt({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({value:r,ttlSeconds:n})})).ok)throw new Error("Failed to write cache record to Durable Object")}async delete(t){if(!(await kt({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`,{method:"DELETE"})).ok)throw new Error("Failed to delete cache record from Durable Object")}};var cn="https://oauth2.googleapis.com/token",ba="https://www.googleapis.com/auth/datastore";function Wt(e){let t=e.client_email;return e.clientEmail||t||""}function Ea(e){let t=e.private_key;return e.privateKey||t||""}function Ca(e,t){return`google-access-token:${Wt(e)}:${t}`}function _a(e){let t=e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\s+/g,""),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.charCodeAt(o);return n.buffer}function It(e){let t=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e),r="";return t.forEach(n=>{r+=String.fromCharCode(n)}),btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function va({serviceAccount:e,scope:t}){let r=Math.floor(Date.now()/1e3),n={alg:"RS256",typ:"JWT"},o={iss:Wt(e),sub:Wt(e),scope:t,aud:cn,iat:r,exp:r+3600},s=It(JSON.stringify(n)),a=It(JSON.stringify(o)),i=`${s}.${a}`,c=await crypto.subtle.importKey("pkcs8",_a(Ea(e)),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]),u=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",c,new TextEncoder().encode(i));return`${i}.${It(new Uint8Array(u))}`}async function un({serviceAccount:e,scope:t=ba,durableObjectNamespaceBinding:r,durableObjectShardCount:n}){let o=r?new oe({bindingName:r,shardCount:n}):null,s=Ca(e,t);if(o){let u=await o.get(s);if(u?.value)return u.value}let a=await va({serviceAccount:e,scope:t}),i=await fetch(cn,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:a}).toString()});if(!i.ok)throw new Error("Failed to fetch Google access token");let c=await i.json();if(o){let u=Math.max(Number(c.expires_in||3600)-60,1);await o.put({cacheKey:s,value:c.access_token,ttlSeconds:u})}return c.access_token}function Nt(e){return`api-key:${e}`}function Jt(e){e.status=401,e.body="Unauthorized"}function Pa(e){e.status=503,e.body="Unable to validate api key"}function Ta(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").toLowerCase()}function Ha({headers:e={},apiKeyHeader:t,apiKeyPrefix:r}){let n=e[t.toLowerCase()]||e[t]||"";return n?r?n.toLowerCase().startsWith(r.toLowerCase())?n.slice(r.length).trim():"":n.trim():""}function Ka(e,t){let r=encodeURIComponent(t),n=e.includes("{apiKey}")?e.replace(/{apiKey}/g,r):`${e.replace(/\/$/,"")}/${r}`;return n.startsWith("https://")||n.startsWith("http://")?n:`https://firestore.googleapis.com/v1/${n.replace(/^\/?v1\//,"").replace(/^\//,"")}`}function Dt(e){if(!(!e||typeof e!="object")){if("stringValue"in e)return e.stringValue;if("booleanValue"in e)return e.booleanValue;if("integerValue"in e)return e.integerValue;if("doubleValue"in e)return e.doubleValue;if("timestampValue"in e)return e.timestampValue;if("nullValue"in e)return null;if("bytesValue"in e)return e.bytesValue;if("referenceValue"in e)return e.referenceValue;if("geoPointValue"in e)return e.geoPointValue;if("arrayValue"in e)return(e.arrayValue?.values||[]).map(Dt);if("mapValue"in e){let t=e.mapValue?.fields||{};return Object.entries(t).reduce((r,[n,o])=>(r[n]=Dt(o),r),{})}}}function Oa(e){let t=e?.fields||{};return Object.entries(t).reduce((r,[n,o])=>(r[n]=Dt(o),r),{})}function Ra(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||e===null||typeof e=="bigint"?String(e):JSON.stringify(e)}function dn(e,t,r){Object.entries(t).forEach(([n,o])=>{typeof o>"u"||(e.request.headers[`${r}${Ta(n)}`]=Ra(o))})}async function xa({firestoreToken:e,serviceAccount:t,durableObjectNamespaceBinding:r,durableObjectShardCount:n}){if(e)return e;if(!t)throw new Error("Either firestoreToken or serviceAccount must be provided");return un({serviceAccount:t,durableObjectNamespaceBinding:r,durableObjectShardCount:n})}async function Ua({firestorePath:e,apiKey:t,firestoreToken:r,serviceAccount:n,durableObjectNamespaceBinding:o,durableObjectShardCount:s}){let a=await xa({firestoreToken:r,serviceAccount:n,durableObjectNamespaceBinding:o,durableObjectShardCount:s}),i=await fetch(Ka(e,t),{headers:{authorization:`Bearer ${a}`}});if(i.status===404)return null;if(!i.ok)throw new Error("Failed to fetch api key from Firestore");let c=await i.json();return Oa(c)}function $t({firestorePath:e,firestoreToken:t,serviceAccount:r,durableObjectNamespaceBinding:n,durableObjectShardCount:o=64,apiKeyHeader:s="x-api-key",apiKeyPrefix:a="",claimsHeaderPrefix:i="x-api-key-claim-",cacheTtl:c=60*60,blockedCacheTtl:u=60*60}){if(!e)throw new Error("firestorePath is required");if(!t&&!r)throw new Error("Either firestoreToken or serviceAccount must be provided");if(!n)throw new Error("durableObjectNamespaceBinding is required");let p=new oe({bindingName:n,shardCount:o});async function d(l){let g=await p.get(Nt(l));return g?g.value:null}async function h(l,g){await p.put({cacheKey:Nt(l),value:{status:"allowed",claims:g},ttlSeconds:c})}async function f(l){await p.put({cacheKey:Nt(l),value:{status:"blocked"},ttlSeconds:u})}return async(l,g)=>{let y=Ha({headers:l.request.headers,apiKeyHeader:s,apiKeyPrefix:a});if(!y)return Jt(l);let w=await d(y);if(w?.status==="allowed"&&w.claims)return l.state.apiKey=y,l.state.apiKeyClaims=w.claims,dn(l,w.claims,i),g(l);if(w?.status==="blocked")return Jt(l);try{let b=await Ua({firestorePath:e,apiKey:y,firestoreToken:t,serviceAccount:r,durableObjectNamespaceBinding:n,durableObjectShardCount:o});return b?(await h(y,b),l.state.apiKey=y,l.state.apiKeyClaims=b,dn(l,b,i),g(l)):(await f(y),Jt(l))}catch{return Pa(l)}}}function pn(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),n=Uint8Array.from(r,o=>o.charCodeAt(0));return new TextDecoder().decode(n)}function ka(e){let t=e.split("."),r=JSON.parse(pn(t[0])),n=JSON.parse(pn(t[1])),o=atob(t[2].replace(/-/g,"+").replace(/_/g,"/"));return{header:r,payload:n,signature:o,raw:{header:t[0],payload:t[1],signature:t[2]}}}function Be(e,t,r){typeof r>"u"||(e[t]=typeof r=="string"?r:JSON.stringify(r))}function Mt({jwksUri:e,iss:t,aud:r,allowPublicAccess:n=!1,headerKey:o="authorization"}){async function s(){return(await(await fetch(e)).json()).keys}function a(u){return u.status=403,u.body="Forbidden",u}async function i(u){let d=new TextEncoder().encode([u.raw.header,u.raw.payload].join(".")),h=new Uint8Array(Array.from(u.signature).map(g=>g.charCodeAt(0))),f=await s();return(await Promise.all(f.map(async g=>{let y=await crypto.subtle.importKey("jwk",g,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",y,h,d)}))).some(g=>g)}async function c(u,p){if(u.request.method==="OPTIONS"||n)return p(u);let d=u.request.headers[o.toLowerCase()]||"";if(d.toLowerCase().startsWith("bearer")){let h=ka(d.slice(7)),f=new Date(h.payload.exp*1e3),l=new Date(Date.now());return f<=l||!t||h.payload.iss!==t||!r||h.payload.aud!==r||!await i(h)?a(u):(Be(u.request.headers,"x-jwt-sub",h.payload.sub),Be(u.request.headers,"x-jwt-iss",h.payload.iss),Be(u.request.headers,"x-jwt-aud",h.payload.aud),Be(u.request.headers,"x-jwt-user-id",h.payload.user_id),u.state.user=h.payload,p(u))}return a(u)}return c}var hn=P($()),Ia={get:hn.default},se=class{constructor({accountId:t,namespace:r,authEmail:n,authKey:o,ttl:s}){this.accountId=t,this.namespace=r,this.authEmail=n,this.authKey=o,this.ttl=s}getNamespaceUrl(){return new URL(`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/storage/kv/namespaces/${this.namespace}`)}getUrlForKey(t){return new URL(`${this.getNamespaceUrl()}/values/${t}`)}async list(t,r=10){let n=`${this.getNamespaceUrl()}/keys?prefix=${t}&limit=${r}`,o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});return o.ok?o.json():null}async get(t,r){let n=this.getUrlForKey(t),o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});if(o.ok)switch(r){case"json":return o.json();case"stream":return o;case"arrayBuffer":return o.arrayBuffer();default:return o.text()}return null}async getWithMetadata(t,r){let[n,o]=await Promise.all([this.get(t,r),this.list(t)]),s=Ia.get(o,"result.0.metadata",{});return{value:n,metadata:s}}async put(t,r,n={}){let o=this.getUrlForKey(t),s=new URLSearchParams;this.ttl&&s.append("expiration_ttl",this.ttl.toString());let a={"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey};o.search=s.toString();let i=new FormData;return i.append("value",r),i.append("metadata",JSON.stringify(n)),(await fetch(o.toString(),{method:"PUT",headers:a,body:r})).ok}async delete(t){let r=this.getUrlForKey(t);return fetch(r,{method:"DELETE",headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}})}};var x={methodsMethodsWithBody:["POST","PUT","PATCH"],http:{statusMessages:{404:"Not Found"}},mime:{css:"text/css",csv:"text/csv",html:"text/html",ico:"image/microsoft.vnd.icon",jpeg:"image/jpeg",js:"application/javascript",json:"application/json",png:"image/png",svg:"image/svg+xml",xml:"application/xml"}};function Wa(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function qt({kvAccountId:e,kvNamespace:t,kvAuthEmail:r,kvAuthKey:n,kvBasePath:o="",kvKey:s="{file}",defaultExtension:a="html",defaultIndexDocument:i,defaultErrorDocument:c,mime:u={},mode:p="rest"}){let d=new se({accountId:e,namespace:t,authEmail:r,authKey:n,mode:p}),h={...x.mime,...u};return async f=>{let l=A.resolveParams(s,f.params),g=l===""&&i?i:Wa(l,a),y=await d.get(o+g);!y&&c&&(y=await d.get(o+c)),y?(f.status=200,f.body=y,f.set("Content-Type",h[g.split(".").pop()]||"text/plain")):(f.status=404,f.body=x.http.statusMessages[404],f.set("Content-Type","text/plain"))}}var ln=P($());var Ft={get:ln.default};function Na(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function Ja(e,t){let r=Ft.get(e,"headers.if-none-match"),n=Ft.get(t,"metadata.headers.etag");return r?r===n:!1}function Lt({kvNamespaceBinding:e,kvBasePath:t="",kvKey:r="{file}",defaultExtension:n="html",defaultIndexDocument:o,defaultErrorDocument:s}){async function a(i){return await global[e].getWithMetadata(i)}return async i=>{let c=A.resolveParams(r,i.params),u=c===""&&o?o:Na(c,n),p=await a(t+u);if(!p&&s&&(p=await a(t+s)),p)if(Ja(i.request,p))i.status=304;else{i.status=p.status,i.body=p.value;let d=Ft.get(p,"metadata.headers",{});Object.keys(d).forEach(h=>{i.set(h,d[h])})}else i.status=404,i.body=x.http.statusMessages[404],i.set("Content-Type","text/plain")}}var mn=P(je());function Gt({accessKeyId:e,secretAccessKey:t,region:r,lambdaName:n}){let o=new mn.AwsClient({accessKeyId:e,secretAccessKey:t});return async s=>{let a=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${n}/invocations`,i={},c=await o.fetch(a,{body:JSON.stringify(i)});s.status=c.status,s.body=c.body;let u=A.instanceToJson(c.headers);Object.keys(u).forEach(p=>{s.set(p,u[p])})}}var On=P($()),Rn=P(Qe());var Kn={get:On.default,set:Rn.default};function Ji(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function Di(e){return e[Math.floor(Math.random()*e.length)]}function Xt({sources:e=[]}){return async t=>{let r=Di(e),n={method:t.request.method,headers:Ji(t.request.headers),redirect:"manual",cf:t.request.cf};if(x.methodsMethodsWithBody.indexOf(t.request.method)!==-1&&Kn.get(t,"event.request.body")){let i=t.event.request.clone();n.body=i.body}let o=A.resolveParams(r.url,t.params);if(r.resolveOverride){let i=A.resolveParams(r.resolveOverride,t.request.params);Kn.set(n,"cf.resolveOverride",i)}let s=await fetch(o+t.request.search,n);t.body=s.body,t.status=s.status;let a=A.instanceToJson(s.headers);Object.keys(a).forEach(i=>{t.set(i,a[i])})}}var kn=P($());var Yt={name:"@ahmadissa/cloudworker-proxy",version:"1.1.142",description:"An api gateway for cloudflare workers",license:"MIT",repository:{type:"git",url:"git+https://github.com/ahmadissa/cloudworker-proxy.git"},bugs:{url:"https://github.com/ahmadissa/cloudworker-proxy/issues"},homepage:"https://github.com/ahmadissa/cloudworker-proxy#readme",author:"Ahmad Issa",keywords:["cloudflare","workers","api","gateway","proxy"],main:"dist/index.js",files:["dist/**"],scripts:{build:"esbuild --bundle src/index.ts --format=cjs --outdir=dist --sourcemap --minify",lint:"eslint src",package:"bun install; npm run build",test:"npm run unit && npm run lint",public:"npm run package && npm publish","test:integration":"node integration/run.js",unit:"bun test","semantic-release":"semantic-release",prepare:"husky install"},release:{branches:["master"],plugins:["@semantic-release/commit-analyzer","@semantic-release/release-notes-generator",["@semantic-release/npm",{npmPublish:!1}],["@semantic-release/git",{assets:["docs","package.json"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}]]},dependencies:{aws4fetch:"1.0.13",build:"^0.1.4","cloudworker-router":"1.11.2",cookie:"0.4.1",jose:"^5.1.0","lodash.get":"4.4.2","lodash.set":"4.3.2",package:"^1.0.1",redaxios:"^0.5.1",shortid:"2.2.16"},devDependencies:{"@semantic-release/git":"^10.0.1","@types/jest":"^29.5.5","@types/mocha":"^10.0.1","@types/node":"^20.5.9","@typescript-eslint/eslint-plugin":"^6.6.0","@typescript-eslint/parser":"^6.6.0",bun:"1.0.3",dotenv:"8.2.0",esbuild:"^0.19.2",eslint:"7.13.0","eslint-config-airbnb-base":"14.2.1","eslint-config-prettier":"6.15.0","eslint-plugin-import":"2.22.1","eslint-plugin-prettier":"3.1.4","fetch-mock":"9.11.0",husky:"^8.0.3","node-fetch":"2.6.1",prettier:"2.1.2","semantic-release":"^22.0.4",typescript:"^5.2.2",wrangler:"^3.7.0"},directories:{example:"examples",test:"test"}};var ce=class{constructor({maxSize:t=10,maxSeconds:r=10,sink:n}){this.maxSize=t,this.maxSeconds=r,this.queue=[],this.sink=n,this.flushing=!1,this.timer=null}async push(t){return this.queue.push(t),this.queue.length>this.maxSize?this.flush():(this.timer||(this.timer=new Promise((r,n)=>{this.resolveTimer=r,this.rejectTimer=n,this.cancelationToken=setTimeout(async()=>{try{r(await this.flush())}catch(o){n(o)}},this.maxSeconds*1e3)})),this.timer)}async flush(){if(!this.flushing){this.flushing=!0;try{let t=this.queue.join(`
6
- `);this.queue=[];let r=await this.sink(t);this.timer&&(clearTimeout(this.cancelationToken),this.resolveTimer(r))}catch(t){this.timer&&this.rejectTimer(t)}finally{this.timer=null,this.flushing=!1}}}};function xn(e,t=".",r=""){return e instanceof Object?Object.keys(e).reduce((n,o)=>e[o]==null?n:{...n,...xn(e[o],t,r+o+t)},{}):r.endsWith(t)?{[r.slice(0,r.length-1)]:e}:{[r]:e}}var et=xn;var He=class{constructor(t){this.url=t.url,this.contentType=t.contentType,this.delimiter=t.delimiter,this.chunker=new ce({sink:this.sendMessage.bind(this),...t})}async log(t){let r=et(t,this.delimiter);await this.chunker.push(JSON.stringify(r))}async sendMessage(t){return fetch(this.url,{body:t,method:"POST",headers:{"Content-Type":this.contentType}})}};var Un=P(je());var Ke=class{constructor(t){this.delimiter=t.delimiter,this.chunker=new ce({sink:this.sendMessage.bind(this),...t}),this.awsClient=new Un.AwsClient({accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,region:t.region}),this.streamName=t.streamName,this.region=t.region}async log(t){let r=et(t,this.delimiter);await this.chunker.push(JSON.stringify(r))}async sendMessage(t){let r=btoa(`${JSON.stringify(t)}
7
- `),n=JSON.stringify({DeliveryStreamName:this.streamName,Record:{Data:r}}),o=`https://firehose.${this.region}.amazonaws.com`,s=new Request(o,{method:"POST",body:n,headers:{"X-Amz-Target":"Firehose_20150804.PutRecord","Content-Type":" application/x-amz-json-1.1"}});return this.awsClient.fetch(s)}};var I={get:kn.default};async function Mi(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}function Zt(e){let t;switch(e.type){case"http":t=new He(e);break;case"kinesis":t=new Ke(e);break;default:throw new Error(`Log service type not supported: ${e.type}`)}return async(r,n)=>{r.state["logger-startDate"]=new Date;let o=await Mi(r.request);try{await n(r);let s={message:"START",requestIp:I.get(r,"request.headers.x-real-ip"),requestId:I.get(r,"request.requestId"),request:{headers:I.get(r,"request.headers"),method:I.get(r,"request.method"),url:I.get(r,"request.href"),protocol:I.get(r,"request.protocol"),body:o},response:{status:r.status,headers:I.get(r,"response.headers")},handlers:I.get(r,"state.handlers",[]).join(","),route:I.get(r,"route.name"),timestamp:new Date().toISOString(),ttfb:new Date-r.state["logger-startDate"],redirectUrl:r.userRedirect,severity:30,proxyVersion:Yt.version};r.event.waitUntil(t.log(s))}catch(s){let a={request:{headers:I.get(r,"request.headers"),method:I.get(r,"request.method"),handlers:I.get(r,"state.handlers",[]).join(","),url:I.get(r,"request.href"),body:o},message:"ERROR",stack:s.stack,error:s.message,severity:50,proxyVersion:Yt.version};r.event.waitUntil(t.log(a))}}}var xe=P(In()),uo=P($()),po=P(Qe()),ho=P(so());async function sr({refresh_token:e,authDomain:t,clientId:r,clientSecret:n}){let o=`${t}/oauth/token`,s=await fetch(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:r,client_secret:n,refresh_token:e})});if(!s.ok)throw new Error("Authentication failed");let a=await s.json();return{...a,expires:Date.now()+a.expires_in*1e3,refresh_token:e}}var ao="PBKDF2",ar="AES-GCM",mc="SHA-256",yc="raw";function gc(e){let t=atob(e.replace(/_/g,"/").replace(/-/g,"+")),r=t.length,n=new Uint8Array(r);for(let o=0;o<r;o+=1)n[o]=t.charCodeAt(o);return n.buffer}function io(e){let t="",r=new Uint8Array(e),n=r.byteLength;for(let o=0;o<n;o+=1)t+=String.fromCharCode(r[o]);return btoa(t).replace(/\//g,"_").replace(/\+/g,"-")}function wc(e){return new TextEncoder().encode(e).buffer}function Ac(e){return new TextDecoder().decode(e)}async function Sc(e){let t=new TextEncoder;return crypto.subtle.importKey(yc,t.encode(e),{name:ao},!1,["deriveKey"])}async function bc(e,t){let r=await Sc(e),o=new TextEncoder().encode(t.replace(/_/g,"/").replace(/-/g,"+"));return crypto.subtle.deriveKey({name:ao,salt:o,iterations:1e3,hash:{name:mc}},r,{name:ar,length:256},!0,["encrypt","decrypt"])}async function Ec(){let e=crypto.getRandomValues(new Uint8Array(8));return io(e)}async function Cc(e,t){let r=gc(t),n=r.slice(0,16),o=r.slice(16),s=await crypto.subtle.decrypt({name:ar,iv:n},e,o);return Ac(s)}async function _c(e,t){let r=crypto.getRandomValues(new Uint8Array(16)),n=await crypto.subtle.encrypt({name:ar,iv:r},e,wc(t)),o=new Uint8Array(n.byteLength+r.byteLength);return o.set(r,0),o.set(new Uint8Array(n),r.byteLength),io(o)}var de={decrypt:Cc,deriveAesGcmKey:bc,encrypt:_c,getSalt:Ec};var fe={get:uo.default,set:po.default};function co({cookieHeader:e="",cookieName:t}){return xe.default.parse(e)[t]}function vc(e){return Object.keys(e).map(t=>`${t}=${encodeURIComponent(e[t])}`).join("&")}function Pc(e=""){return e.split(",").indexOf("text/html")!==-1}function ir({cookieName:e="proxy",cookieHttpOnly:t=!0,allowPublicAccess:r=!1,kvAccountId:n,kvNamespace:o,kvAuthEmail:s,kvAuthKey:a,kvTtl:i=2592e3,oauth2AuthDomain:c,oauth2ClientId:u,oauth2ClientSecret:p,oauth2Audience:d,oauth2Scopes:h=[],oauth2CallbackPath:f="/callback",oauth2CallbackType:l="cookie",oauth2LogoutPath:g="/logout",oauth2LoginPath:y="/login",oauth2ServerTokenPath:w="/oauth/token",oauth2ServerAuthorizePath:b="",oauth2ServerLogoutPath:K}){let O=new se({accountId:n,namespace:o,authEmail:s,authKey:a,ttl:i}),ee=c,be=f,ft=l,mt=w,Me=b,yt=K,V=u,Ee=p,q=d,qe=g,_=y,_e=h.join("%20");async function Fe(m,H){let T=`${ee}${mt}`,R=await fetch(T,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:vc({code:m,grant_type:"authorization_code",client_id:V,client_secret:Ee,redirect_uri:H})});if(!R.ok)throw new Error("Authentication failed");let F=await R.json();return{...F,expires:Date.now()+F.expires_in*1e3}}async function Do(m){if(co({cookieHeader:m.request.headers.cookie,cookieName:e})){let R=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${R}`,path:"/",maxAge:0}))}let T=Rr(m);if(K){let R=encodeURIComponent(`${m.request.protocol}://${m.request.host}${T}`);m.set("Location",`${ee}${yt}?client_id=${V}&returnTo=${R}`)}else m.set("Location",T);m.status=302}async function $o(m){let H=m.request.href.split("?")[0],T=await Fe(m.request.query.code,H),R=ho.default.generate(),F=await de.getSalt(),L=`${R}.${F}`,gt=await de.deriveAesGcmKey(R,F),te=await de.encrypt(gt,JSON.stringify(T));await O.put(R,te);let wt=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.status=302,ft==="query"?m.set("Location",`${m.request.query.state}?auth=${L}`):(m.set("Set-Cookie",xe.default.serialize(e,L,{httpOnly:t,domain:`.${wt}`,path:"/",maxAge:60*60*24*365})),m.set("Location",m.request.query.state))}async function Mo(m,H){let[T,R]=H.split("."),F=await O.get(T);if(F){let L=await de.deriveAesGcmKey(T,R),gt=await de.decrypt(L,F),te=JSON.parse(gt);if(te.expires<Date.now()){te=await sr({refresh_token:te.refresh_token,clientId:V,authDomain:ee,clientSecret:Ee});let wt=await de.encrypt(L,JSON.stringify(te));await O.put(T,wt)}m.state.accessToken=te.access_token,m.state.accessToken&&(m.request.headers.authorization=`bearer ${m.state.accessToken}`)}else{let L=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${L}`,maxAge:0}))}}function Rr(m){let H=fe.get(m,"request.query.redirect-to");if(H)return H;let T=fe.get(m,"request.headers.referer");return T||"/"}async function qo(m){if(m.request.method==="OPTIONS")m.status=200;else{let H=Rr(m),T=encodeURIComponent(H||"/"),R=encodeURIComponent(`${m.request.protocol}://${m.request.host}${be}`);m.status=302,m.set("location",`${ee}${Me}/authorize?state=${T}&client_id=${V}&response_type=code&scope=${_e}&audience=${q}&redirect_uri=${R}`)}}async function Fo(m,H){if(m.request.method==="OPTIONS")await H(m);else if(fe.get(m,"request.headers.authorization","").toLowerCase().startsWith("bearer "))fe.set(m,"state.access_token",m.request.headers.authorization.slice(7)),await H(m);else{let T=fe.get(m,"request.query.auth")||co({cookieHeader:m.request.headers.cookie,cookieName:e});if(T&&await Mo(m,T),fe.get(m,"state.accessToken")||r)await H(m);else if(Pc(m.request.headers.accept)){let F=encodeURIComponent(m.request.href),L=encodeURIComponent(`${m.request.protocol}://${m.request.host}${be}`);m.status=302,m.set("location",`${ee}${Me}/authorize?state=${F}&client_id=${V}&response_type=code&scope=${_e}&audience=${q}&redirect_uri=${L}`)}else m.status=403,m.body="Forbidden"}}return async(m,H)=>{switch(m.request.path){case be:await $o(m);break;case qe:await Do(m);break;case _:await qo(m);break;default:await Fo(m,H)}}}var lo=P($());var Tc={get:lo.default};function Hc(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function cr(e){let{localOriginOverride:t,backend:r}=e;return async n=>{let o=process.env.LOCAL?`${t||n.request.origin}${n.request.path}`:`${r}${n.request.path}`,s={headers:Hc(n.request.headers),method:n.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(n.request.method)!==-1&&Tc.get(n,"event.request.body")){let c=n.event.request.clone();s.body=c.body}let a=await fetch(o,s);n.body=a.body,n.status=a.status;let i=A.instanceToJson(a.headers);Object.keys(i).forEach(c=>{n.set(c,i[c])})}}function ur({body:e="",headers:t={},status:r=200}){return async n=>{e instanceof Object?(n.body=JSON.stringify(e),n.set("Content-Type","application/json")):n.body=A.resolveParams(e,n.params),n.status=r,Object.keys(t).forEach(o=>{n.set(o,A.resolveParams(t[o],n.params))})}}var fo=P($()),mo=P(Qe()),dr={get:fo.default,set:mo.default};function pr({type:e="IP",scope:t="default",limit:r=1e3}){let n={};function o(a,i){let c=i["x-real-ip"];return e==="IP"?`minute.${a}.${t}.${c}`:`minute.${a}.${t}.account`}function s(a){let i=dr.get(n,"minutes",{});Object.keys(i).forEach(c=>{c!==a&&delete n.minutes.minute})}return async(a,i)=>{let c=Math.trunc(Date.now()/6e4),u=Math.trunc(c*60+60-Date.now()/1e3),p=o(c,a.request.headers),d=dr.get(n,p,0);if(["HEAD","OPTIONS"].indexOf(a.request.method)===-1&&(d+=1),dr.set(n,p,d),r<d){a.status=429;return}s(c),await i(a)}}var yo=P(je());function Kc(e,t={}){if(e&&t.forcePathStyle){let r=new URL(e);return`${r.protocol}//${r.host}/${t.bucket}`}if(e){let r=new URL(e);return`${r.protocol}//${t.bucket}.${r.host}`}return t.forcePathStyle&&t.region?`https://s3.${t.region}.amazonaws.com/${t.bucket}`:t.forcePathStyle?`https://s3.amazonaws.com/${t.bucket}`:t.region?`https://${t.bucket}.s3.${t.region}.amazonaws.com`:`https://${t.bucket}.s3.amazonaws.com`}function hr({accessKeyId:e,secretAccessKey:t,bucket:r,region:n,endpoint:o,forcePathStyle:s,enableBucketOperations:a=!1}){let i=new yo.AwsClient({accessKeyId:e,region:n,secretAccessKey:t}),c=Kc(o,{region:n,bucket:r,forcePathStyle:s});return async u=>{if(u.params.file===void 0&&!a){u.status=404,u.body=x.http.statusMessages[404],u.set("Content-Type","text/plain");return}let p=u.params.file?A.resolveParams(`${c}/{file}`,u.params):c,d={};u.request.headers.range&&(d.range=u.request.headers.range);let h=await i.fetch(p,{method:u.method||u.request.method,headers:d});u.status=h.status,u.body=h.body;let f=A.instanceToJson(h.headers);Object.keys(f).forEach(l=>{u.set(l,f[l])})}}var lr;function go(e){return new Uint8Array(e.split("").map(r=>r.charCodeAt(0)))}async function Oc(e){return lr||(lr=await crypto.subtle.importKey("raw",go(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"])),lr}async function Rc(e,t){let r=await Oc(t),n=await crypto.subtle.sign({name:"HMAC"},r,go(e));return btoa(String.fromCharCode.apply(null,new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fr({secret:e}){return async(t,r)=>{let n=(t.request.path+t.request.search).replace(/([?|&]sign=[\w|-]+)/,"");if(await Rc(n,e)!==t.query.sign){t.status=403;return}await r(t)}}function mr({host:e}){if(!e)throw new Error("Need to specify a host for the split middleware.");return async(t,r)=>{let n=t.clone();n.cloned=!0,n.request={...n.request,href:n.request.href.replace(n.request.href,e),host:e},t.event.waitUntil(r(n)),await r(t)}}async function xc(e,t,r){let n=e.getReader(),o=t.getWriter(),s=new TextDecoder,a=new TextEncoder;for(;;){let{done:i,value:c}=await n.read();if(i)break;let u=s.decode(c),p=wo(u,r),d=a.encode(p);await o.write(d)}await o.close()}function Uc(e,t){return e.replace(/{{\$(\d)}}/g,(r,n)=>t[parseInt(n,10)])}function wo(e,t){return t.reduce((r,n)=>r.replace(n.regex,(...o)=>Uc(n.replace,o)),e)}function yr({transforms:e=[],statusCodes:t=[200]}){let r=e.map(n=>({regex:new RegExp(n.regex,"g"),replace:n.replace}));return async(n,o)=>{await o(n);let{body:s}=n;if(t.indexOf(n.status)!==-1)if(typeof s=="string")n.body=wo(s,r);else{let{readable:a,writable:i}=new TransformStream;xc(s,i,r),n.body=a}}}async function kc({projectID:e="your-project-id",API_KEY:t="GCP_API_KEY",token:r="action-token",siteKey:n="siteKey",expectedAction:o="action-name"}){let a=await(await fetch(`https://recaptchaenterprise.googleapis.com/v1/projects/${e}/assessments?key=${t}`,{body:JSON.stringify({event:{token:r,siteKey:n,expectedAction:o}}),headers:{"Content-Type":"application/json"},method:"POST"})).json();return a.tokenProperties.valid?a.tokenProperties.action===o?(a.riskAnalysis.reasons.forEach(i=>{console.log(i)}),a.riskAnalysis.score):(console.error("reCAPTCHA action error:"+o+":action:"+a.tokenProperties.action),null):(console.error("The CreateAssessment call failed because the token was: "+a.tokenProperties.invalidReason),0)}var Ic=e=>(e=e.split("?")[0],e.replace(/\W/g,"").slice(0,100));function gr({projectID:e,API_KEY:t,siteKey:r}){function n(o){return{token:o["g-recaptcha-token"]}}return async(o,s)=>{let{token:a}=n(o.request.headers),i=Ic(o.request.path);if((await kc({projectID:e,API_KEY:t,token:a,siteKey:r,expectedAction:i})||0)<.5){o.status=409;return}await s(o)}}async function Wc({secret:e,token:t,expectedAction:r,remoteip:n}){if(!t)return{ok:!1,score:0,errorCodes:["missing-input-response"]};let o=new URLSearchParams({secret:e,response:t,...n?{remoteip:n}:{}}),a=await(await fetch("https://www.google.com/recaptcha/api/siteverify",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})).json(),i=!!a.success,c=a.action===r,u=typeof a.score=="number"?a.score:0;return{ok:i&&c,score:u,action:a.action,errorCodes:a["error-codes"]}}var Nc=e=>{let t=e;try{t=new URL(e,"http://dummy").pathname}catch{}return t=t.split("?")[0]||"/",t.replace(/\W/g,"").slice(0,100)},Ue=(e,t)=>{if(e instanceof Headers)return e.get(t);let r=e[t]??e[t.toLowerCase()];return Array.isArray(r)?r[0]??null:r??null};function wr({secret:e,headerName:t="x-recaptcha-token",minScore:r=.5,requireActionMatch:n=!0}){return async(o,s)=>{let a=o.request?.req||o.request||o,i=a.headers??o.request?.headers??{},c=Ue(i,t)||Ue(i,"g-recaptcha-token")||null,p=Ue(i,"x-recaptcha-action")||Nc(o.request?.path||o.request?.url||a.url||"/"),d=Ue(i,"cf-connecting-ip")||Ue(i,"x-forwarded-for")||void 0,h=await Wc({secret:e,token:c,expectedAction:p,remoteip:d});if(!(h.score>=r&&h.ok)){let l={action:h.action,expectedAction:p,score:h.score??0,errors:h.errorCodes??[]};console.warn("[reCAPTCHA] failed:"+JSON.stringify(l)),o.status=409,o.set?.("Content-Type","application/json"),o.body=JSON.stringify({error:"reCAPTCHA verification failed"});return}await s(o)}}async function Jc({secret:e,token:t,remoteip:r}){if(!t)return{ok:!1,errorCodes:["missing-input-response"]};let n=new URLSearchParams({secret:e,response:t,...r?{remoteip:r}:{}}),s=await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:n})).json();return{ok:!!s.success,errorCodes:s["error-codes"]}}var st=(e,t)=>{if(e instanceof Headers)return e.get(t);let r=e[t]??e[t.toLowerCase()];return Array.isArray(r)?r[0]??null:r??null};function Ar({secret:e,headerName:t="x-recaptcha-token"}){return async(r,n)=>{let s=(r.request||r).headers||{},a=st(s,t)||st(s,"cf-turnstile-token")||null,i=st(s,"cf-connecting-ip")||st(s,"x-forwarded-for")||void 0,c=await Jc({secret:e,token:a,remoteip:i});if(!c.ok){let p={errors:c.errorCodes??[]};console.warn("[Turnstile] verification failed: "+JSON.stringify(p)),r.status=409,r.headers||=new Headers,r.headers.set("Content-Type","application/json"),r.body=JSON.stringify({error:"Turnstile verification failed"});return}await n(r)}}var Dc=e=>!new RegExp("(\b)(onS+)(s*)=|javascript|<(|/|[^/>][^>]+|/[^>][^>]+)>").test(e),$c=(e,t,r)=>!(!Dc(t)||!r[e](t)),Mc=e=>!(e===null||typeof e!="object"||Array.isArray(e)&&(!e[0]||typeof e[0]!="object")),at=(e,t)=>{let r=Object.keys(e);for(let n of r){if(!t[n])return console.error("key not allowed",n),!1;if(e[n]===null&&(e[n]=""),Mc(e[n])){if(!at(e[n],t))return console.error("error validating key+validateObject:",n),!1}else if(!$c(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1}return!0},Ao=e=>!(e==null||typeof e!="object"),qc=(e,t)=>{let r=e.query;return Ao(r)?at(r,t):!1},ke=(e,t)=>{let r=e.params;return r?Ao(r)?at(r,t):!1:!0};async function Fc(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return{};try{let t=await e.text();return JSON.parse(t)}catch{}return{}}function Sr({allowedKeys:e}){return async(r,n)=>{if(!e)return r.status=501,!1;if(!ke(r,e)||!qc(r,e))return r.status=422,!1;let o=await Fc(r.request);if(!at(o,e))return r.status=422,!1;await n(r)}}var Io=P($());var E=crypto,D=e=>e instanceof CryptoKey;var U=new TextEncoder,W=new TextDecoder,Ep=2**32;function z(...e){let t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}var So=e=>{let t=e;typeof t=="string"&&(t=U.encode(t));let r=32768,n=[];for(let o=0;o<t.length;o+=r)n.push(String.fromCharCode.apply(null,t.subarray(o,o+r)));return btoa(n.join(""))},N=e=>So(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var me=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var S=class extends me{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var J=class extends me{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},X=class extends me{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var it=E.getRandomValues.bind(E);function B(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ct(e,t){return e.name===t}function br(e){return parseInt(e.name.slice(4),10)}function Bc(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vc(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Eo(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ct(e.algorithm,"HMAC"))throw B("HMAC");let n=parseInt(t.slice(2),10);if(br(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ct(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(br(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ct(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");let n=parseInt(t.slice(2),10);if(br(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw B("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ct(e.algorithm,"ECDSA"))throw B("ECDSA");let n=Bc(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vc(e,r)}function Co(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var M=(e,...t)=>Co("Key must be ",e,...t);function Er(e,t,...r){return Co(`Key for the ${e} algorithm must be `,t,...r)}var Cr=e=>D(e),C=["CryptoKey"];var Zc=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let s of o){if(r.has(s))return!1;r.add(s)}}return!0},ye=Zc;function Qc(e){return typeof e=="object"&&e!==null}function k(e){if(!Qc(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var ut=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var Z=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((s,a)=>s===t[a])||Z(e,t,n+1)},vo=e=>{switch(!0){case Z(e,[42,134,72,206,61,3,1,7]):return"P-256";case Z(e,[43,129,4,0,34]):return"P-384";case Z(e,[43,129,4,0,35]):return"P-521";case Z(e,[43,101,110]):return"X25519";case Z(e,[43,101,111]):return"X448";case Z(e,[43,101,112]):return"Ed25519";case Z(e,[43,101,113]):return"Ed448";default:throw new S("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},nu=async(e,t,r,n,o)=>{let s,a,i=new Uint8Array(atob(r.replace(e,"")).split("").map(u=>u.charCodeAt(0))),c=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let u=vo(i);s=u.startsWith("P-")?{name:"ECDH",namedCurve:u}:{name:u},a=c?[]:["deriveBits"];break}case"EdDSA":s={name:vo(i)},a=c?["verify"]:["sign"];break;default:throw new S('Invalid or unsupported "alg" (Algorithm) value')}return E.subtle.importKey(t,i,s,o?.extractable??!1,a)},Po=(e,t,r)=>nu(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r);async function _r(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Po(e,t,r)}var ou=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Cr(t))throw new TypeError(Er(e,t,...C,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${C.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},su=(e,t,r)=>{if(!Cr(t))throw new TypeError(Er(e,t,...C));if(t.type==="secret")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},au=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ou(e,t):su(e,t,r)},Ne=au;function lu(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let a of n.crit){if(!s.has(a))throw new S(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var ge=lu;var wu=Symbol();function dt(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new S(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function pt(e,t,r){if(D(t))return Eo(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(M(t,...C));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(M(t,...C,"Uint8Array"))}var Q=e=>Math.floor(e.getTime()/1e3);var Su=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ht=e=>{let t=Su.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var _u=async(e,t,r)=>{let n=await pt(e,t,"sign");ut(e,n);let o=await E.subtle.sign(dt(e,n.algorithm),n,r);return new Uint8Array(o)},xo=_u;var we=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ye(this._protectedHeader,this._unprotectedHeader))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ge(J,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(o.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ne(a,t,"sign");let i=this._payload;s&&(i=U.encode(N(i)));let c;this._protectedHeader?c=U.encode(N(JSON.stringify(this._protectedHeader))):c=U.encode("");let u=z(c,U.encode("."),i),p=await xo(a,t,u),d={signature:N(p),payload:""};return s&&(d.payload=W.decode(i)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=W.decode(c)),d}};var Je=class{constructor(t){this._flattened=new we(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function Ae(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Se=class{constructor(t={}){if(!k(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:Ae("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Ae("setNotBefore",Q(t))}:this._payload={...this._payload,nbf:Q(new Date)+ht(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Ae("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Ae("setExpirationTime",Q(t))}:this._payload={...this._payload,exp:Q(new Date)+ht(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Q(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Ae("setIssuedAt",Q(t))}:this._payload={...this._payload,iat:Ae("setIssuedAt",t)},this}};var De=class extends Se{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new Je(U.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new X("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var Hu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Hu="jose/v5.1.0");var Uo=function e(t){function r(o,s,a){var i,c={};if(Array.isArray(o))return o.concat(s);for(i in o)c[a?i.toLowerCase():i]=o[i];for(i in s){var u=a?i.toLowerCase():i,p=s[i];c[u]=u in c&&typeof p=="object"?r(c[u],p,u=="headers"):p}return c}function n(o,s,a,i,c){var u=typeof o!="string"?(s=o).url:o,p={config:s},d=r(t,s),h={};i=i||d.data,(d.transformRequest||[]).map(function(f){i=f(i,d.headers)||i}),d.auth&&(h.authorization=d.auth),i&&typeof i=="object"&&typeof i.append!="function"&&typeof i.text!="function"&&(i=JSON.stringify(i),h["content-type"]="application/json");try{h[d.xsrfHeaderName]=decodeURIComponent(document.cookie.match(RegExp("(^|; )"+d.xsrfCookieName+"=([^;]*)"))[2])}catch{}return d.baseURL&&(u=u.replace(/^(?!.*\/\/)\/?/,d.baseURL+"/")),d.params&&(u+=(~u.indexOf("?")?"&":"?")+(d.paramsSerializer?d.paramsSerializer(d.params):new URLSearchParams(d.params))),(d.fetch||fetch)(u,{method:(a||d.method||"get").toUpperCase(),body:i,headers:r(d.headers,h,!0),credentials:d.withCredentials?"include":c}).then(function(f){for(var l in f)typeof f[l]!="function"&&(p[l]=f[l]);return d.responseType=="stream"?(p.data=f.body,p):f[d.responseType||"text"]().then(function(g){p.data=g,p.data=JSON.parse(g)}).catch(Object).then(function(){return(d.validateStatus?d.validateStatus(f.status):f.ok)?p:Promise.reject(p)})})}return t=t||{},n.request=n,n.get=function(o,s){return n(o,s,"get")},n.delete=function(o,s){return n(o,s,"delete")},n.head=function(o,s){return n(o,s,"head")},n.options=function(o,s){return n(o,s,"options")},n.post=function(o,s,a){return n(o,a,"post",s)},n.put=function(o,s,a){return n(o,a,"put",s)},n.patch=function(o,s,a){return n(o,a,"patch",s)},n.all=Promise.all.bind(Promise),n.spread=function(o){return o.apply.bind(o,o)},n.CancelToken=typeof AbortController=="function"?AbortController:Object,n.defaults=t,n.create=e,n}();var Ru=e=>{if(!e)return!1;let t=JSON.parse(atob(e.split(".")[1])),r=Math.floor(Date.now()/1e3);return t.exp>r-600},lt=async(e,t)=>{let r=await GCP_INVOKER_TOKEN.get(t);if(Ru(r))return r;let n=await _r(e.private_key,"RS256"),o=e.client_email,s={iss:o,sub:o,aud:"https://www.googleapis.com/oauth2/v4/token",target_audience:t,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+3600},a=await new De(s).setProtectedHeader({alg:"RS256",typ:"JWT"}).sign(n),i=await Uo.post("https://www.googleapis.com/oauth2/v4/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:a});return await GCP_INVOKER_TOKEN.delete(t),await GCP_INVOKER_TOKEN.put(t,i.data.id_token),i.data.id_token};var ko={get:Io.default};function Pr({project_id:e,region:t,functionName:r,serviceAccount:n,allowedKeys:o}){return async(s,a)=>{if(o&&s.params&&!ke(s,o))return s.status=422,s.body=JSON.stringify({error:"Invalid params"}),!1;let i=ko.get(s,"request.query",{}),c=new URLSearchParams(i).toString(),u=`https://${t}-${e}.cloudfunctions.net/${r}`,p=s.request.path,d=`https://${t}-${e}.cloudfunctions.net/${r}${p||""}${c?`?${c}`:""}`,h=await lt(n,u),f=new Headers(s.request.headers);f.set("X-Serverless-Authorization",`Bearer ${h}`);let l=s.event.cf||{},g={"X-Geo-Country":l.country,"X-Geo-City":l.city,"X-Geo-Latitude":l.latitude,"X-Geo-Longitude":l.longitude,"X-Geo-Timezone":l.timezone,"X-Geo-Region":l.region,"X-Geo-PostalCode":l.postalCode,"X-Geo-RegionCode":l.regionCode,"X-Geo-EU-Country":l.isEUCountry?"1":"0"};for(let[K,O]of Object.entries(g))O!==void 0&&f.set(K,O);let y={headers:f,method:s.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(s.request.method)!==-1&&ko.get(s,"event.request.body")){let K=s.event.request.clone();y.body=K.body}let w=await fetch(d,y);s.body=w.body,s.status=w.status;let b=A.instanceToJson(w.headers);A.mergeHeaders(b,s),await a(s)}}var xu=P($());function Tr({domain:e,serviceAccount:t,allowedKeys:r}){return async(n,o)=>{if(r&&n.params&&!ke(n,r))return n.status=422,n.body=JSON.stringify({error:"Invalid params"}),!1;let s=new URL(n.event.request.url),a=`${e}${s.pathname}${s.search}`,i=new Headers(n.request.headers);if(t){let f=await lt(t,e);i.set("X-Serverless-Authorization",`Bearer ${f}`)}i.set("X-Token",i.get("authorization")||i.get("x-token")||"N/A"),i.delete("authorization");let c=n.event.cf||{},u={"X-Geo-Country":c.country,"X-Geo-City":c.city,"X-Geo-Latitude":c.latitude,"X-Geo-Longitude":c.longitude,"X-Geo-Timezone":c.timezone,"X-Geo-Region":c.region,"X-Geo-PostalCode":c.postalCode,"X-Geo-RegionCode":c.regionCode,"X-Geo-EU-Country":c.isEUCountry?"1":"0"};for(let[f,l]of Object.entries(u))l!==void 0&&i.set(f,l);let p={method:n.request.method,headers:i,redirect:"manual"};if(x.methodsMethodsWithBody.includes(n.request.method)){let f=n.event.request.clone();p.body=f.body}let d=await fetch(a,p),h=new Headers(d.headers);h.delete("content-length"),h.delete("transfer-encoding"),n.status=d.status,A.mergeHeaders(A.instanceToJson(h),n),n.body=d.body,await o(n)}}function Hr({headers:e={},headersFN:t}){return async(r,n)=>{if(e)for(let o of Object.keys(e))r.set(o.toLowerCase(),e[o]);if(t){let o=await t();for(let s of Object.keys(o))r.set(s,o[s])}await n(r)}}async function Uu(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return"";try{return await e.text()}catch{return""}}function ku(e){return new TextEncoder().encode(e).length}function Wo(e,t,r){e.status=413;let n=JSON.stringify({error:"Payload too large",limit:t,...r!=null?{received:r}:{}});e.set("content-type","application/json"),e.set("content-length",String(n.length)),e.body=n}function Kr({bodySizeLimit:e=512}={}){return async(t,r)=>{let n=t.request?.method||"GET";if(["POST","PATCH","PUT","DELETE"].indexOf(n)===-1)return r(t);let o=t.request?.headers?.["content-length"],s=o?Number(o):NaN;if(Number.isFinite(s)&&s>e)return Wo(t,e,s);let a=await Uu(t.request),i=typeof a=="string"?ku(a):0;if(i>e)return Wo(t,e,i);await r(t)}}var No={basicAuth:Tt,cache:Rt,cors:xt,geoDecorator:Ut,firestoreApiKey:$t,jwt:Mt,kvStorage:qt,kvStorageBinding:Lt,lambda:Gt,loadbalancer:Xt,logger:Zt,oauth2:ir,origin:cr,rateLimit:pr,response:ur,s3:hr,signature:fr,split:mr,transform:yr,recaptcha:gr,recaptchaV3:wr,turnstileVerify:Ar,userInputValidation:Sr,cloudfunction:Pr,gcpCloudrun:Tr,headers:Hr,bodySizeLimit:Kr};function Iu(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}function Wu(e){return e.storage}function Nu(e){let t=e.match(/^\/cache\/(.+)$/);return t?decodeURIComponent(t[1]):null}var $e=class{constructor(t,r){this.state=t,this.env=r}async fetch(t){let r=new URL(t.url),n=Nu(r.pathname);if(!n)return new Response("Not Found",{status:404});let o=Wu(this.state);if(t.method==="GET"){let s=await o.get(n);return s?s.expiresAt<=Date.now()?(await o.delete(n),new Response(null,{status:404})):Iu(s):new Response(null,{status:404})}if(t.method==="PUT"){let s=await t.json(),a=Number(s.ttlSeconds||0);return await o.put(n,{value:s.value,expiresAt:Date.now()+a*1e3}),new Response(null,{status:204})}return t.method==="DELETE"?(await o.delete(n),new Response(null,{status:204})):new Response("Method Not Allowed",{status:405})}};function Ju(e){return t=>{let r=e(t);return async(n,o)=>(n.upgradedByProxy||(Ot(n),n.upgradedByProxy=!0),r(n,o))}}var Or=class{constructor(t=[],r={}){this.router=new Jo.default,t.forEach(n=>{let o=r[n.handlerName]||No[n.handlerName];if(!o)throw new Error(`Handler ${n.handlerName} is not supported`);let s=Ju(o);this.router.add(n,s(n.options||{}))})}async resolve(t){let r=t;return r.cf=r.request?.cf||{},this.router.resolve(r)}};module.exports=Or;module.exports.ApiKeyCacheDurableObject=$e;
5
+ `)}async hexBodyHash(){let h=this.headers.get("X-Amz-Content-Sha256");if(h==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");h=c(await i(this.body||""))}return h}}async function s(d,h){let f=await crypto.subtle.importKey("raw",typeof d=="string"?t.encode(d):d,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",f,t.encode(h))}async function i(d){return crypto.subtle.digest("SHA-256",typeof d=="string"?t.encode(d):d)}function c(d){return Array.prototype.map.call(new Uint8Array(d),h=>("0"+h.toString(16)).slice(-2)).join("")}function u(d){return d.replace(/[!'()*]/g,h=>"%"+h.charCodeAt(0).toString(16).toUpperCase())}function p(d,h){let{hostname:f,pathname:l}=d,g=f.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[y,w]=(g||["",""]).slice(1,3);if(w==="us-gov")w="us-gov-west-1";else if(w==="s3"||w==="s3-accelerate")w="us-east-1",y="s3";else if(y==="iot")f.startsWith("iot.")?y="execute-api":f.startsWith("data.jobs.iot.")?y="iot-jobs-data":y=l==="/mqtt"?"iotdevicegateway":"iotdata";else if(y==="autoscaling"){let b=(h.get("X-Amz-Target")||"").split(".")[0];b==="AnyScaleFrontendService"?y="application-autoscaling":b==="AnyScaleScalingPlannerFrontendService"&&(y="autoscaling-plans")}else w==null&&y.startsWith("s3-")?(w=y.slice(3).replace(/^fips-|^external-1/,""),y="s3"):y.endsWith("-fips")?y=y.slice(0,-5):w&&/-\d$/.test(y)&&!/-\d$/.test(w)&&([y,w]=[w,y]);return[r[y]||y,w]}e.AwsClient=o,e.AwsV4Signer=a,Object.defineProperty(e,"__esModule",{value:!0})})});var et=v((bd,Hn)=>{var $s="Expected a function",Sn="__lodash_hash_undefined__",bn=1/0,Ms=9007199254740991,qs="[object Function]",Fs="[object GeneratorFunction]",Ls="[object Symbol]",Gs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Bs=/^\w*$/,Vs=/^\./,js=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,zs=/[\\^$.*+?()[\]{}|]/g,Xs=/\\(\\)?/g,Ys=/^\[object .+?Constructor\]$/,Zs=/^(?:0|[1-9]\d*)$/,Qs=typeof global=="object"&&global&&global.Object===Object&&global,ei=typeof self=="object"&&self&&self.Object===Object&&self,Vt=Qs||ei||Function("return this")();function ti(e,t){return e?.[t]}function ri(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var ni=Array.prototype,oi=Function.prototype,En=Object.prototype,Bt=Vt["__core-js_shared__"],yn=function(){var e=/[^.]+$/.exec(Bt&&Bt.keys&&Bt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Cn=oi.toString,Ye=En.hasOwnProperty,_n=En.toString,ai=RegExp("^"+Cn.call(Ye).replace(zs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),gn=Vt.Symbol,si=ni.splice,ii=vn(Vt,"Map"),Te=vn(Object,"create"),wn=gn?gn.prototype:void 0,An=wn?wn.toString:void 0;function se(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function ci(){this.__data__=Te?Te(null):{}}function ui(e){return this.has(e)&&delete this.__data__[e]}function di(e){var t=this.__data__;if(Te){var r=t[e];return r===Sn?void 0:r}return Ye.call(t,e)?t[e]:void 0}function pi(e){var t=this.__data__;return Te?t[e]!==void 0:Ye.call(t,e)}function hi(e,t){var r=this.__data__;return r[e]=Te&&t===void 0?Sn:t,this}se.prototype.clear=ci;se.prototype.delete=ui;se.prototype.get=di;se.prototype.has=pi;se.prototype.set=hi;function le(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function li(){this.__data__=[]}function fi(e){var t=this.__data__,r=Ze(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():si.call(t,r,1),!0}function mi(e){var t=this.__data__,r=Ze(t,e);return r<0?void 0:t[r][1]}function yi(e){return Ze(this.__data__,e)>-1}function gi(e,t){var r=this.__data__,n=Ze(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}le.prototype.clear=li;le.prototype.delete=fi;le.prototype.get=mi;le.prototype.has=yi;le.prototype.set=gi;function ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function wi(){this.__data__={hash:new se,map:new(ii||le),string:new se}}function Ai(e){return Qe(this,e).delete(e)}function Si(e){return Qe(this,e).get(e)}function bi(e){return Qe(this,e).has(e)}function Ei(e,t){return Qe(this,e).set(e,t),this}ie.prototype.clear=wi;ie.prototype.delete=Ai;ie.prototype.get=Si;ie.prototype.has=bi;ie.prototype.set=Ei;function Ci(e,t,r){var n=e[t];(!(Ye.call(e,t)&&Pn(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function Ze(e,t){for(var r=e.length;r--;)if(Pn(e[r][0],t))return r;return-1}function _i(e){if(!Xe(e)||Ri(e))return!1;var t=Ii(e)||ri(e)?ai:Ys;return t.test(ki(e))}function vi(e,t,r,n){if(!Xe(e))return e;t=Ki(t,e)?[t]:Ti(t);for(var o=-1,a=t.length,s=a-1,i=e;i!=null&&++o<a;){var c=Ui(t[o]),u=r;if(o!=s){var p=i[c];u=n?n(p,c,i):void 0,u===void 0&&(u=Xe(p)?p:Hi(t[o+1])?[]:{})}Ci(i,c,u),i=i[c]}return e}function Pi(e){if(typeof e=="string")return e;if(zt(e))return An?An.call(e):"";var t=e+"";return t=="0"&&1/e==-bn?"-0":t}function Ti(e){return Tn(e)?e:xi(e)}function Qe(e,t){var r=e.__data__;return Oi(t)?r[typeof t=="string"?"string":"hash"]:r.map}function vn(e,t){var r=ti(e,t);return _i(r)?r:void 0}function Hi(e,t){return t=t??Ms,!!t&&(typeof e=="number"||Zs.test(e))&&e>-1&&e%1==0&&e<t}function Ki(e,t){if(Tn(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||zt(e)?!0:Bs.test(e)||!Gs.test(e)||t!=null&&e in Object(t)}function Oi(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ri(e){return!!yn&&yn in e}var xi=jt(function(e){e=Ni(e);var t=[];return Vs.test(e)&&t.push(""),e.replace(js,function(r,n,o,a){t.push(o?a.replace(Xs,"$1"):n||r)}),t});function Ui(e){if(typeof e=="string"||zt(e))return e;var t=e+"";return t=="0"&&1/e==-bn?"-0":t}function ki(e){if(e!=null){try{return Cn.call(e)}catch{}try{return e+""}catch{}}return""}function jt(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError($s);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var s=e.apply(this,n);return r.cache=a.set(o,s),s};return r.cache=new(jt.Cache||ie),r}jt.Cache=ie;function Pn(e,t){return e===t||e!==e&&t!==t}var Tn=Array.isArray;function Ii(e){var t=Xe(e)?_n.call(e):"";return t==qs||t==Fs}function Xe(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Wi(e){return!!e&&typeof e=="object"}function zt(e){return typeof e=="symbol"||Wi(e)&&_n.call(e)==Ls}function Ni(e){return e==null?"":Pi(e)}function Ji(e,t,r){return e==null?e:vi(e,t,r)}Hn.exports=Ji});var In=v(Qt=>{"use strict";Qt.parse=Bi;Qt.serialize=Vi;var Fi=decodeURIComponent,Li=encodeURIComponent,Gi=/; */,rt=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function Bi(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");for(var r={},n=t||{},o=e.split(Gi),a=n.decode||Fi,s=0;s<o.length;s++){var i=o[s],c=i.indexOf("=");if(!(c<0)){var u=i.substr(0,c).trim(),p=i.substr(++c,i.length).trim();p[0]=='"'&&(p=p.slice(1,-1)),r[u]==null&&(r[u]=ji(p,a))}}return r}function Vi(e,t,r){var n=r||{},o=n.encode||Li;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!rt.test(e))throw new TypeError("argument name is invalid");var a=o(t);if(a&&!rt.test(a))throw new TypeError("argument val is invalid");var s=e+"="+a;if(n.maxAge!=null){var i=n.maxAge-0;if(isNaN(i)||!isFinite(i))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+Math.floor(i)}if(n.domain){if(!rt.test(n.domain))throw new TypeError("option domain is invalid");s+="; Domain="+n.domain}if(n.path){if(!rt.test(n.path))throw new TypeError("option path is invalid");s+="; Path="+n.path}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(s+="; HttpOnly"),n.secure&&(s+="; Secure"),n.sameSite){var c=typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite;switch(c){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return s}function ji(e,t){try{return t(e)}catch{return e}}});var Nn=v((Dd,Wn)=>{"use strict";var nt=1;function zi(){return nt=(nt*9301+49297)%233280,nt/233280}function Xi(e){nt=e}Wn.exports={nextValue:zi,seed:Xi}});var Re=v(($d,Mn)=>{"use strict";var er=Nn(),ue="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",j,Jn,Oe;function tr(){Oe=!1}function Dn(e){if(!e){j!==ue&&(j=ue,tr());return}if(e!==j){if(e.length!==ue.length)throw new Error("Custom alphabet for shortid must be "+ue.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter(function(r,n,o){return n!==o.lastIndexOf(r)});if(t.length)throw new Error("Custom alphabet for shortid must be "+ue.length+" unique characters. These characters were not unique: "+t.join(", "));j=e,tr()}}function Yi(e){return Dn(e),j}function Zi(e){er.seed(e),Jn!==e&&(tr(),Jn=e)}function Qi(){j||Dn(ue);for(var e=j.split(""),t=[],r=er.nextValue(),n;e.length>0;)r=er.nextValue(),n=Math.floor(r*e.length),t.push(e.splice(n,1)[0]);return t.join("")}function $n(){return Oe||(Oe=Qi(),Oe)}function ec(e){var t=$n();return t[e]}function tc(){return j||ue}Mn.exports={get:tc,characters:Yi,seed:Zi,lookup:ec,shuffled:$n}});var Fn=v((Md,qn)=>{"use strict";var rr=typeof window=="object"&&(window.crypto||window.msCrypto),nr;!rr||!rr.getRandomValues?nr=function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(Math.random()*256));return t}:nr=function(e){return rr.getRandomValues(new Uint8Array(e))};qn.exports=nr});var Gn=v((qd,Ln)=>{Ln.exports=function(e,t,r){for(var n=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*n*r/t.length),a="";;)for(var s=e(o),i=o;i--;)if(a+=t[s[i]&n]||"",a.length===+r)return a}});var Vn=v((Fd,Bn)=>{"use strict";var rc=Re(),nc=Fn(),oc=Gn();function ac(e){for(var t=0,r,n="";!r;)n=n+oc(nc,rc.get(),1),r=e<Math.pow(16,t+1),t++;return n}Bn.exports=ac});var Xn=v((Gd,zn)=>{"use strict";var ot=Vn(),Ld=Re(),sc=1567752802062,ic=7,at,jn;function cc(e){var t="",r=Math.floor((Date.now()-sc)*.001);return r===jn?at++:(at=0,jn=r),t=t+ot(ic),t=t+ot(e),at>0&&(t=t+ot(at)),t=t+ot(r),t}zn.exports=cc});var Zn=v((Bd,Yn)=>{"use strict";var uc=Re();function dc(e){if(!e||typeof e!="string"||e.length<6)return!1;var t=new RegExp("[^"+uc.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]");return!t.test(e)}Yn.exports=dc});var eo=v((Vd,Qn)=>{"use strict";Qn.exports=0});var no=v((jd,G)=>{"use strict";var or=Re(),pc=Xn(),hc=Zn(),to=eo()||0;function lc(e){return or.seed(e),G.exports}function fc(e){return to=e,G.exports}function mc(e){return e!==void 0&&or.characters(e),or.shuffled()}function ro(){return pc(to)}G.exports=ro;G.exports.generate=ro;G.exports.seed=lc;G.exports.worker=fc;G.exports.characters=mc;G.exports.isValid=hc});var ao=v((zd,oo)=>{"use strict";oo.exports=no()});var Do=P(Fr());var nn=P($()),ns={get:nn.default};function Pt(e){e.status=401,e.body="Unauthorized",e.set("WWW-Authenticate","Basic")}function Tt(e){return async(t,r)=>{if(t.request.path===e.logoutPath)return Pt(t);let n=ns.get(t,"request.headers.authorization");if(!n||!n.startsWith("Basic "))return Pt(t);let o=e.users.map(i=>i.authToken),a=n.substring(6),s=o.indexOf(a);return s===-1?Pt(t):(t.state.user=e.users[s].username,r(t))}}var on=caches.default;async function os(e){return await on.match(e)}async function as(e,t){return on.put(e.href,t)}var Ht={get:os,set:as};async function ss(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}var an=ss;function is(e,t={}){return Object.keys(t).reduce((r,n)=>r.replace(`{${n}}`,t[n]),e)}function Kt(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}function cs(e,t){Object.entries(e).forEach(([r,n])=>{t.header(r)||t.set(r,n)})}var Ot=e=>{e.set=(t,r)=>{e.response.headers[t.toLowerCase()]=r},e.header=t=>e.request.headers[t.toLowerCase()]},A={resolveParams:is,instanceToJson:Kt,mergeHeaders:cs,upgradeCTX:Ot};var us=["x-ratelimit-count","x-ratelimit-limit","x-ratelimit-reset","x-cache-hit"];async function ds(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}async function ps(e,t){if(!t)return e.event.request;let r=t.match(/{.*?}/gi).map(a=>a.slice(1,-1)),n={};for(let a=0;a<r.length;a+=1){let s=r[a],i=s.split(":");switch(i[0]){case"method":n[s]=e.request.method;break;case"path":n[s]=e.request.path;break;case"bodyHash":n[s]=await an(await ds(e.request));break;case"header":n[s]=e.request.headers[i[1]]||"";break;default:n[s]=s}}let o=encodeURIComponent(t.replace(/({(.*?)})/gi,(a,s,i)=>n[i]));return new Request(`http://${e.request.hostname}/${o}`)}function Rt({cacheDuration:e,cacheKeyTemplate:t,headerBlacklist:r=us}){return async(n,o)=>{let a=await ps(n,t),s=await Ht.get(a);if(s){n.body=s.body,n.status=s.status;let i=Kt(s.headers);Object.keys(i).forEach(c=>{n.set(c,i[c])}),n.set("X-Cache-Hit",!0)}else{await o(n);let i;n.body.tee?[n.body,i]=n.body.tee():i=n.body;let c=new Response(i,{status:n.status});Object.keys(n.response.headers).forEach(u=>{r.indexOf(u.toLowerCase())===-1&&c.headers.set(u,n.response.headers[u])}),e&&(c.headers.delete("Cache-Control"),c.headers.set("Cache-Control",`max-age=${e}`)),n.event.waitUntil(Ht.set(a,c))}}}function xt({allowedOrigins:e=["*"],allowedMethods:t=["GET","PUT","POST","PATCH","DELETE","HEAD","OPTIONS"],allowCredentials:r=!0,allowedHeaders:n=["Content-Type"],allowedExposeHeaders:o=[],maxAge:a=600,optionsSuccessStatus:s=204,terminatePreflight:i=!1}){return async(c,u)=>{let{method:p}=c.request,{origin:d}=c.request.headers,h=c.request.headers["access-control-request-headers"];if(hs(c,d,e),ls(c,r),gs(c,o),!t.includes(p.toUpperCase())){c.status=405,c.body={error:`Method ${p} not allowed`};return}if(p==="OPTIONS"&&(fs(c,t),ms(c,h,n),ys(c,a),i)){c.status=s,c.body=null,c.set("content-length","0");return}await u(c)}}function hs(e,t,r){if(Array.isArray(r)){if(r[0]==="origin"){e.set("Access-Control-Allow-Origin",t),sn(e,"Origin");return}r[0]==="*"?e.set("Access-Control-Allow-Origin","*"):r.indexOf(t)!==-1&&(e.set("Access-Control-Allow-Origin",t),sn(e,"Origin"))}}function ls(e,t){t&&e.set("Access-Control-Allow-Credentials",String(t))}function fs(e,t){e.set("Access-Control-Allow-Methods",t.join(","))}function ms(e,t,r){r.length===0&&t?e.set("Access-Control-Allow-Headers",t):r.length&&e.set("Access-Control-Allow-Headers",r.join(","))}function ys(e,t){t&&e.set("Access-Control-Max-Age",String(t))}function gs(e,t){t.length&&e.set("Access-Control-Expose-Headers",t.join(","))}function sn(e,t){let r=e.header("vary")||e.header("Vary");(r?.split(",").map(o=>o.trim().toLowerCase())||[]).includes(t.toLowerCase())||e.set("Vary",r?`${r}, ${t}`:t)}var ws={AF:"AS",AL:"EU",AQ:"AN",DZ:"AF",AS:"OC",AD:"EU",AO:"AF",AG:"NA",AZ:"EU",AR:"SA",AU:"OC",AT:"EU",BS:"NA",BH:"AS",BD:"AS",AM:"EU",BB:"NA",BE:"EU",BM:"NA",BT:"AS",BO:"SA",BA:"EU",BW:"AF",BV:"AN",BR:"SA",BZ:"NA",IO:"AS",SB:"OC",VG:"NA",BN:"AS",BG:"EU",MM:"AS",BI:"AF",BY:"EU",KH:"AS",CM:"AF",CA:"NA",CV:"AF",KY:"NA",CF:"AF",LK:"AS",TD:"AF",CL:"SA",CN:"AS",TW:"AS",CX:"AS",CC:"AS",CO:"SA",KM:"AF",YT:"AF",CG:"AF",CD:"AF",CK:"OC",CR:"NA",HR:"EU",CU:"NA",CY:"EU",CZ:"EU",BJ:"AF",DK:"EU",DM:"NA",DO:"NA",EC:"SA",SV:"NA",GQ:"AF",ET:"AF",ER:"AF",EE:"EU",FO:"EU",FK:"SA",GS:"AN",FJ:"OC",FI:"EU",AX:"EU",FR:"EU",GF:"SA",PF:"OC",TF:"AN",DJ:"AF",GA:"AF",GE:"EU",GM:"AF",PS:"AS",DE:"EU",GH:"AF",GI:"EU",KI:"OC",GR:"EU",GL:"NA",GD:"NA",GP:"NA",GU:"OC",GT:"NA",GN:"AF",GY:"SA",HT:"NA",HM:"AN",VA:"EU",HN:"NA",HK:"AS",HU:"EU",IS:"EU",IN:"AS",ID:"AS",IR:"AS",IQ:"AS",IE:"EU",IL:"AS",IT:"EU",CI:"AF",JM:"NA",JP:"AS",KZ:"EU",JO:"AS",KE:"AF",KP:"AS",KR:"AS",KW:"AS",KG:"AS",LA:"AS",LB:"AS",LS:"AF",LV:"EU",LR:"AF",LY:"AF",LI:"EU",LT:"EU",LU:"EU",MO:"AS",MG:"AF",MW:"AF",MY:"AS",MV:"AS",ML:"AF",MT:"EU",MQ:"NA",MR:"AF",MU:"AF",MX:"NA",MC:"EU",MN:"AS",MD:"EU",ME:"EU",MS:"NA",MA:"AF",MZ:"AF",OM:"AS",NA:"AF",NR:"OC",NP:"AS",NL:"EU",AN:"NA",CW:"NA",AW:"NA",SX:"NA",BQ:"NA",NC:"OC",VU:"OC",NZ:"OC",NI:"NA",NE:"AF",NG:"AF",NU:"OC",NF:"OC",NO:"EU",MP:"OC",UM:"OC",FM:"OC",MH:"OC",PW:"OC",PK:"AS",PA:"NA",PG:"OC",PY:"SA",PE:"SA",PH:"AS",PN:"OC",PL:"EU",PT:"EU",GW:"AF",TL:"AS",PR:"NA",QA:"AS",RE:"AF",RO:"EU",RU:"EU",RW:"AF",BL:"NA",SH:"AF",KN:"NA",AI:"NA",LC:"NA",MF:"NA",PM:"NA",VC:"NA",SM:"EU",ST:"AF",SA:"AS",SN:"AF",RS:"EU",SC:"AF",SL:"AF",SG:"AS",SK:"EU",VN:"AS",SI:"EU",SO:"AF",ZA:"AF",ZW:"AF",ES:"EU",SS:"AF",EH:"AF",SD:"AF",SR:"SA",SJ:"EU",SZ:"AF",SE:"EU",CH:"EU",SY:"AS",TJ:"AS",TH:"AS",TG:"AF",TK:"OC",TO:"OC",TT:"NA",AE:"AS",TN:"AF",TR:"EU",TM:"AS",TC:"NA",TV:"OC",UG:"AF",UA:"EU",MK:"EU",EG:"AF",GB:"EU",GG:"EU",JE:"EU",IM:"EU",TZ:"AF",US:"NA",VI:"NA",BF:"AF",UY:"SA",UZ:"AS",VE:"SA",WF:"OC",WS:"OC",YE:"AS",ZM:"AF",XX:"XX"};function Ut(){return async(e,t)=>{let r=e.request.headers["cf-ipcountry"]||"XX";e.request.headers["proxy-continent"]=ws[r],await t(e)}}function As(e){let t=0;for(let r=0;r<e.length;r+=1)t=(t*31+e.charCodeAt(r))%2147483647;return t}function Ss(e){let t=globalThis[e];if(!t)throw new Error(`Durable Object binding ${e} was not found on global scope`);return t}function kt({bindingName:e,cacheKey:t,shardCount:r}){let n=Ss(e),o=As(t)%r,a=n.idFromName(`ttl-cache:${o}`);return n.get(a)}async function bs(e){return e.json()}var oe=class{constructor({bindingName:t,shardCount:r=64}){this.bindingName=t,this.shardCount=r}async get(t){let n=await kt({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`);if(n.status===404)return null;if(!n.ok)throw new Error("Failed to read cache record from Durable Object");return bs(n)}async put({cacheKey:t,value:r,ttlSeconds:n}){if(!(await kt({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({value:r,ttlSeconds:n})})).ok)throw new Error("Failed to write cache record to Durable Object")}async delete(t){if(!(await kt({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`,{method:"DELETE"})).ok)throw new Error("Failed to delete cache record from Durable Object")}};var cn="https://oauth2.googleapis.com/token",Es="https://www.googleapis.com/auth/datastore";function Wt(e){let t=e.client_email;return e.clientEmail||t||""}function Cs(e){let t=e.private_key;return e.privateKey||t||""}function _s(e,t){return`google-access-token:${Wt(e)}:${t}`}function vs(e){let t=e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\s+/g,""),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.charCodeAt(o);return n.buffer}function It(e){let t=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e),r="";return t.forEach(n=>{r+=String.fromCharCode(n)}),btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Ps({serviceAccount:e,scope:t}){let r=Math.floor(Date.now()/1e3),n={alg:"RS256",typ:"JWT"},o={iss:Wt(e),sub:Wt(e),scope:t,aud:cn,iat:r,exp:r+3600},a=It(JSON.stringify(n)),s=It(JSON.stringify(o)),i=`${a}.${s}`,c=await crypto.subtle.importKey("pkcs8",vs(Cs(e)),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]),u=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",c,new TextEncoder().encode(i));return`${i}.${It(new Uint8Array(u))}`}async function un({serviceAccount:e,scope:t=Es,durableObjectNamespaceBinding:r,durableObjectShardCount:n}){let o=r?new oe({bindingName:r,shardCount:n}):null,a=_s(e,t);if(o){let u=await o.get(a);if(u?.value)return u.value}let s=await Ps({serviceAccount:e,scope:t}),i=await fetch(cn,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s}).toString()});if(!i.ok)throw new Error("Failed to fetch Google access token");let c=await i.json();if(o){let u=Math.max(Number(c.expires_in||3600)-60,1);await o.put({cacheKey:a,value:c.access_token,ttlSeconds:u})}return c.access_token}function Nt(e){return`api-key:${e}`}function Jt(e){e.status=401,e.body="Unauthorized"}function Ts(e){e.status=503,e.body="Unable to validate api key"}function Hs(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").toLowerCase()}function Ks({headers:e={},apiKeyHeader:t,apiKeyPrefix:r}){let n=e[t.toLowerCase()]||e[t]||"";return n?r?n.toLowerCase().startsWith(r.toLowerCase())?n.slice(r.length).trim():"":n.trim():""}function Os(e,t){let r=encodeURIComponent(t),n=e.includes("{apiKey}")?e.replace(/{apiKey}/g,r):`${e.replace(/\/$/,"")}/${r}`;return n.startsWith("https://")||n.startsWith("http://")?n:`https://firestore.googleapis.com/v1/${n.replace(/^\/?v1\//,"").replace(/^\//,"")}`}function Dt(e){if(!(!e||typeof e!="object")){if("stringValue"in e)return e.stringValue;if("booleanValue"in e)return e.booleanValue;if("integerValue"in e)return e.integerValue;if("doubleValue"in e)return e.doubleValue;if("timestampValue"in e)return e.timestampValue;if("nullValue"in e)return null;if("bytesValue"in e)return e.bytesValue;if("referenceValue"in e)return e.referenceValue;if("geoPointValue"in e)return e.geoPointValue;if("arrayValue"in e)return(e.arrayValue?.values||[]).map(Dt);if("mapValue"in e){let t=e.mapValue?.fields||{};return Object.entries(t).reduce((r,[n,o])=>(r[n]=Dt(o),r),{})}}}function Rs(e){let t=e?.fields||{};return Object.entries(t).reduce((r,[n,o])=>(r[n]=Dt(o),r),{})}function xs(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||e===null||typeof e=="bigint"?String(e):JSON.stringify(e)}function dn(e,t,r){Object.entries(t).forEach(([n,o])=>{typeof o>"u"||(e.request.headers[`${r}${Hs(n)}`]=xs(o))})}async function Us({firestoreToken:e,serviceAccount:t,durableObjectNamespaceBinding:r,durableObjectShardCount:n}){if(e)return e;if(!t)throw new Error("Either firestoreToken or serviceAccount must be provided");return un({serviceAccount:t,durableObjectNamespaceBinding:r,durableObjectShardCount:n})}async function ks({firestorePath:e,apiKey:t,firestoreToken:r,serviceAccount:n,durableObjectNamespaceBinding:o,durableObjectShardCount:a}){let s=await Us({firestoreToken:r,serviceAccount:n,durableObjectNamespaceBinding:o,durableObjectShardCount:a}),i=await fetch(Os(e,t),{headers:{authorization:`Bearer ${s}`}});if(i.status===404)return null;if(!i.ok)throw new Error("Failed to fetch api key from Firestore");let c=await i.json();return Rs(c)}function $t({firestorePath:e,firestoreToken:t,serviceAccount:r,durableObjectNamespaceBinding:n,durableObjectShardCount:o=64,apiKeyHeader:a="x-api-key",apiKeyPrefix:s="",claimsHeaderPrefix:i="x-api-key-claim-",cacheTtl:c=60*60,blockedCacheTtl:u=60*60}){if(!e)throw new Error("firestorePath is required");if(!t&&!r)throw new Error("Either firestoreToken or serviceAccount must be provided");if(!n)throw new Error("durableObjectNamespaceBinding is required");let p=new oe({bindingName:n,shardCount:o});async function d(l){let g=await p.get(Nt(l));return g?g.value:null}async function h(l,g){await p.put({cacheKey:Nt(l),value:{status:"allowed",claims:g},ttlSeconds:c})}async function f(l){await p.put({cacheKey:Nt(l),value:{status:"blocked"},ttlSeconds:u})}return async(l,g)=>{let y=Ks({headers:l.request.headers,apiKeyHeader:a,apiKeyPrefix:s});if(!y)return Jt(l);let w=await d(y);if(w?.status==="allowed"&&w.claims)return l.state.apiKey=y,l.state.apiKeyClaims=w.claims,dn(l,w.claims,i),g(l);if(w?.status==="blocked")return Jt(l);try{let b=await ks({firestorePath:e,apiKey:y,firestoreToken:t,serviceAccount:r,durableObjectNamespaceBinding:n,durableObjectShardCount:o});return b?(await h(y,b),l.state.apiKey=y,l.state.apiKeyClaims=b,dn(l,b,i),g(l)):(await f(y),Jt(l))}catch{return Ts(l)}}}function pn(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),n=Uint8Array.from(r,o=>o.charCodeAt(0));return new TextDecoder().decode(n)}function Is(e){let t=e.split("."),r=JSON.parse(pn(t[0])),n=JSON.parse(pn(t[1])),o=atob(t[2].replace(/-/g,"+").replace(/_/g,"/"));return{header:r,payload:n,signature:o,raw:{header:t[0],payload:t[1],signature:t[2]}}}function Ve(e,t,r){typeof r>"u"||(e[t]=typeof r=="string"?r:JSON.stringify(r))}function Mt({jwksUri:e,iss:t,aud:r,allowPublicAccess:n=!1,headerKey:o="authorization"}){async function a(){return(await(await fetch(e)).json()).keys}function s(u){return u.status=403,u.body="Forbidden",u}async function i(u){let d=new TextEncoder().encode([u.raw.header,u.raw.payload].join(".")),h=new Uint8Array(Array.from(u.signature).map(g=>g.charCodeAt(0))),f=await a();return(await Promise.all(f.map(async g=>{let y=await crypto.subtle.importKey("jwk",g,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",y,h,d)}))).some(g=>g)}async function c(u,p){if(u.request.method==="OPTIONS"||n)return p(u);let d=u.request.headers[o.toLowerCase()]||"";if(d.toLowerCase().startsWith("bearer")){let h=Is(d.slice(7)),f=new Date(h.payload.exp*1e3),l=new Date(Date.now());return f<=l||!t||h.payload.iss!==t||!r||h.payload.aud!==r||!await i(h)?s(u):(Ve(u.request.headers,"x-jwt-sub",h.payload.sub),Ve(u.request.headers,"x-jwt-iss",h.payload.iss),Ve(u.request.headers,"x-jwt-aud",h.payload.aud),Ve(u.request.headers,"x-jwt-user-id",h.payload.user_id),u.state.user=h.payload,p(u))}return s(u)}return c}var hn=P($()),Ws={get:hn.default},ae=class{constructor({accountId:t,namespace:r,authEmail:n,authKey:o,ttl:a}){this.accountId=t,this.namespace=r,this.authEmail=n,this.authKey=o,this.ttl=a}getNamespaceUrl(){return new URL(`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/storage/kv/namespaces/${this.namespace}`)}getUrlForKey(t){return new URL(`${this.getNamespaceUrl()}/values/${t}`)}async list(t,r=10){let n=`${this.getNamespaceUrl()}/keys?prefix=${t}&limit=${r}`,o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});return o.ok?o.json():null}async get(t,r){let n=this.getUrlForKey(t),o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});if(o.ok)switch(r){case"json":return o.json();case"stream":return o;case"arrayBuffer":return o.arrayBuffer();default:return o.text()}return null}async getWithMetadata(t,r){let[n,o]=await Promise.all([this.get(t,r),this.list(t)]),a=Ws.get(o,"result.0.metadata",{});return{value:n,metadata:a}}async put(t,r,n={}){let o=this.getUrlForKey(t),a=new URLSearchParams;this.ttl&&a.append("expiration_ttl",this.ttl.toString());let s={"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey};o.search=a.toString();let i=new FormData;return i.append("value",r),i.append("metadata",JSON.stringify(n)),(await fetch(o.toString(),{method:"PUT",headers:s,body:r})).ok}async delete(t){let r=this.getUrlForKey(t);return fetch(r,{method:"DELETE",headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}})}};var x={methodsMethodsWithBody:["POST","PUT","PATCH"],http:{statusMessages:{404:"Not Found"}},mime:{css:"text/css",csv:"text/csv",html:"text/html",ico:"image/microsoft.vnd.icon",jpeg:"image/jpeg",js:"application/javascript",json:"application/json",png:"image/png",svg:"image/svg+xml",xml:"application/xml"}};function Ns(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function qt({kvAccountId:e,kvNamespace:t,kvAuthEmail:r,kvAuthKey:n,kvBasePath:o="",kvKey:a="{file}",defaultExtension:s="html",defaultIndexDocument:i,defaultErrorDocument:c,mime:u={},mode:p="rest"}){let d=new ae({accountId:e,namespace:t,authEmail:r,authKey:n,mode:p}),h={...x.mime,...u};return async f=>{let l=A.resolveParams(a,f.params),g=l===""&&i?i:Ns(l,s),y=await d.get(o+g);!y&&c&&(y=await d.get(o+c)),y?(f.status=200,f.body=y,f.set("Content-Type",h[g.split(".").pop()]||"text/plain")):(f.status=404,f.body=x.http.statusMessages[404],f.set("Content-Type","text/plain"))}}var ln=P($());var Ft={get:ln.default};function Js(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function Ds(e,t){let r=Ft.get(e,"headers.if-none-match"),n=Ft.get(t,"metadata.headers.etag");return r?r===n:!1}function Lt({kvNamespaceBinding:e,kvBasePath:t="",kvKey:r="{file}",defaultExtension:n="html",defaultIndexDocument:o,defaultErrorDocument:a}){async function s(i){return await global[e].getWithMetadata(i)}return async i=>{let c=A.resolveParams(r,i.params),u=c===""&&o?o:Js(c,n),p=await s(t+u);if(!p&&a&&(p=await s(t+a)),p)if(Ds(i.request,p))i.status=304;else{i.status=p.status,i.body=p.value;let d=Ft.get(p,"metadata.headers",{});Object.keys(d).forEach(h=>{i.set(h,d[h])})}else i.status=404,i.body=x.http.statusMessages[404],i.set("Content-Type","text/plain")}}var mn=P(ze());function Gt({accessKeyId:e,secretAccessKey:t,region:r,lambdaName:n}){let o=new mn.AwsClient({accessKeyId:e,secretAccessKey:t});return async a=>{let s=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${n}/invocations`,i={},c=await o.fetch(s,{body:JSON.stringify(i)});a.status=c.status,a.body=c.body;let u=A.instanceToJson(c.headers);Object.keys(u).forEach(p=>{a.set(p,u[p])})}}var On=P($()),Rn=P(et());var Kn={get:On.default,set:Rn.default};function Di(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function $i(e){return e[Math.floor(Math.random()*e.length)]}function Xt({sources:e=[]}){return async t=>{let r=$i(e),n={method:t.request.method,headers:Di(t.request.headers),redirect:"manual",cf:t.request.cf};if(x.methodsMethodsWithBody.indexOf(t.request.method)!==-1&&Kn.get(t,"event.request.body")){let i=t.event.request.clone();n.body=i.body}let o=A.resolveParams(r.url,t.params);if(r.resolveOverride){let i=A.resolveParams(r.resolveOverride,t.request.params);Kn.set(n,"cf.resolveOverride",i)}let a=await fetch(o+t.request.search,n);t.body=a.body,t.status=a.status;let s=A.instanceToJson(a.headers);Object.keys(s).forEach(i=>{t.set(i,s[i])})}}var kn=P($());var Yt={name:"@ahmadissa/cloudworker-proxy",version:"1.1.143",description:"An api gateway for cloudflare workers",license:"MIT",repository:{type:"git",url:"git+https://github.com/ahmadissa/cloudworker-proxy.git"},bugs:{url:"https://github.com/ahmadissa/cloudworker-proxy/issues"},homepage:"https://github.com/ahmadissa/cloudworker-proxy#readme",author:"Ahmad Issa",keywords:["cloudflare","workers","api","gateway","proxy"],main:"dist/index.js",files:["dist/**"],scripts:{build:"esbuild --bundle src/index.ts --format=cjs --outdir=dist --sourcemap --minify",lint:"eslint src",package:"bun install; npm run build",test:"npm run unit && npm run lint",public:"npm run package && npm publish","test:integration":"node integration/run.js",unit:"bun test","semantic-release":"semantic-release",prepare:"husky install"},release:{branches:["master"],plugins:["@semantic-release/commit-analyzer","@semantic-release/release-notes-generator",["@semantic-release/npm",{npmPublish:!1}],["@semantic-release/git",{assets:["docs","package.json"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}]]},dependencies:{aws4fetch:"1.0.13",build:"^0.1.4","cloudworker-router":"1.11.2",cookie:"0.4.1",jose:"^5.1.0","lodash.get":"4.4.2","lodash.set":"4.3.2",package:"^1.0.1",redaxios:"^0.5.1",shortid:"2.2.16"},devDependencies:{"@semantic-release/git":"^10.0.1","@types/jest":"^29.5.5","@types/mocha":"^10.0.1","@types/node":"^20.5.9","@typescript-eslint/eslint-plugin":"^6.6.0","@typescript-eslint/parser":"^6.6.0",bun:"1.0.3",dotenv:"8.2.0",esbuild:"^0.19.2",eslint:"7.13.0","eslint-config-airbnb-base":"14.2.1","eslint-config-prettier":"6.15.0","eslint-plugin-import":"2.22.1","eslint-plugin-prettier":"3.1.4","fetch-mock":"9.11.0",husky:"^8.0.3","node-fetch":"2.6.1",prettier:"2.1.2","semantic-release":"^22.0.4",typescript:"^5.2.2",wrangler:"^3.7.0"},directories:{example:"examples",test:"test"}};var ce=class{constructor({maxSize:t=10,maxSeconds:r=10,sink:n}){this.maxSize=t,this.maxSeconds=r,this.queue=[],this.sink=n,this.flushing=!1,this.timer=null}async push(t){return this.queue.push(t),this.queue.length>this.maxSize?this.flush():(this.timer||(this.timer=new Promise((r,n)=>{this.resolveTimer=r,this.rejectTimer=n,this.cancelationToken=setTimeout(async()=>{try{r(await this.flush())}catch(o){n(o)}},this.maxSeconds*1e3)})),this.timer)}async flush(){if(!this.flushing){this.flushing=!0;try{let t=this.queue.join(`
6
+ `);this.queue=[];let r=await this.sink(t);this.timer&&(clearTimeout(this.cancelationToken),this.resolveTimer(r))}catch(t){this.timer&&this.rejectTimer(t)}finally{this.timer=null,this.flushing=!1}}}};function xn(e,t=".",r=""){return e instanceof Object?Object.keys(e).reduce((n,o)=>e[o]==null?n:{...n,...xn(e[o],t,r+o+t)},{}):r.endsWith(t)?{[r.slice(0,r.length-1)]:e}:{[r]:e}}var tt=xn;var He=class{constructor(t){this.url=t.url,this.contentType=t.contentType,this.delimiter=t.delimiter,this.chunker=new ce({sink:this.sendMessage.bind(this),...t})}async log(t){let r=tt(t,this.delimiter);await this.chunker.push(JSON.stringify(r))}async sendMessage(t){return fetch(this.url,{body:t,method:"POST",headers:{"Content-Type":this.contentType}})}};var Un=P(ze());var Ke=class{constructor(t){this.delimiter=t.delimiter,this.chunker=new ce({sink:this.sendMessage.bind(this),...t}),this.awsClient=new Un.AwsClient({accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,region:t.region}),this.streamName=t.streamName,this.region=t.region}async log(t){let r=tt(t,this.delimiter);await this.chunker.push(JSON.stringify(r))}async sendMessage(t){let r=btoa(`${JSON.stringify(t)}
7
+ `),n=JSON.stringify({DeliveryStreamName:this.streamName,Record:{Data:r}}),o=`https://firehose.${this.region}.amazonaws.com`,a=new Request(o,{method:"POST",body:n,headers:{"X-Amz-Target":"Firehose_20150804.PutRecord","Content-Type":" application/x-amz-json-1.1"}});return this.awsClient.fetch(a)}};var I={get:kn.default};async function qi(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}function Zt(e){let t;switch(e.type){case"http":t=new He(e);break;case"kinesis":t=new Ke(e);break;default:throw new Error(`Log service type not supported: ${e.type}`)}return async(r,n)=>{r.state["logger-startDate"]=new Date;let o=await qi(r.request);try{await n(r);let a={message:"START",requestIp:I.get(r,"request.headers.x-real-ip"),requestId:I.get(r,"request.requestId"),request:{headers:I.get(r,"request.headers"),method:I.get(r,"request.method"),url:I.get(r,"request.href"),protocol:I.get(r,"request.protocol"),body:o},response:{status:r.status,headers:I.get(r,"response.headers")},handlers:I.get(r,"state.handlers",[]).join(","),route:I.get(r,"route.name"),timestamp:new Date().toISOString(),ttfb:new Date-r.state["logger-startDate"],redirectUrl:r.userRedirect,severity:30,proxyVersion:Yt.version};r.event.waitUntil(t.log(a))}catch(a){let s={request:{headers:I.get(r,"request.headers"),method:I.get(r,"request.method"),handlers:I.get(r,"state.handlers",[]).join(","),url:I.get(r,"request.href"),body:o},message:"ERROR",stack:a.stack,error:a.message,severity:50,proxyVersion:Yt.version};r.event.waitUntil(t.log(s))}}}var xe=P(In()),uo=P($()),po=P(et()),ho=P(ao());async function ar({refresh_token:e,authDomain:t,clientId:r,clientSecret:n}){let o=`${t}/oauth/token`,a=await fetch(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:r,client_secret:n,refresh_token:e})});if(!a.ok)throw new Error("Authentication failed");let s=await a.json();return{...s,expires:Date.now()+s.expires_in*1e3,refresh_token:e}}var so="PBKDF2",sr="AES-GCM",yc="SHA-256",gc="raw";function wc(e){let t=atob(e.replace(/_/g,"/").replace(/-/g,"+")),r=t.length,n=new Uint8Array(r);for(let o=0;o<r;o+=1)n[o]=t.charCodeAt(o);return n.buffer}function io(e){let t="",r=new Uint8Array(e),n=r.byteLength;for(let o=0;o<n;o+=1)t+=String.fromCharCode(r[o]);return btoa(t).replace(/\//g,"_").replace(/\+/g,"-")}function Ac(e){return new TextEncoder().encode(e).buffer}function Sc(e){return new TextDecoder().decode(e)}async function bc(e){let t=new TextEncoder;return crypto.subtle.importKey(gc,t.encode(e),{name:so},!1,["deriveKey"])}async function Ec(e,t){let r=await bc(e),o=new TextEncoder().encode(t.replace(/_/g,"/").replace(/-/g,"+"));return crypto.subtle.deriveKey({name:so,salt:o,iterations:1e3,hash:{name:yc}},r,{name:sr,length:256},!0,["encrypt","decrypt"])}async function Cc(){let e=crypto.getRandomValues(new Uint8Array(8));return io(e)}async function _c(e,t){let r=wc(t),n=r.slice(0,16),o=r.slice(16),a=await crypto.subtle.decrypt({name:sr,iv:n},e,o);return Sc(a)}async function vc(e,t){let r=crypto.getRandomValues(new Uint8Array(16)),n=await crypto.subtle.encrypt({name:sr,iv:r},e,Ac(t)),o=new Uint8Array(n.byteLength+r.byteLength);return o.set(r,0),o.set(new Uint8Array(n),r.byteLength),io(o)}var de={decrypt:_c,deriveAesGcmKey:Ec,encrypt:vc,getSalt:Cc};var fe={get:uo.default,set:po.default};function co({cookieHeader:e="",cookieName:t}){return xe.default.parse(e)[t]}function Pc(e){return Object.keys(e).map(t=>`${t}=${encodeURIComponent(e[t])}`).join("&")}function Tc(e=""){return e.split(",").indexOf("text/html")!==-1}function ir({cookieName:e="proxy",cookieHttpOnly:t=!0,allowPublicAccess:r=!1,kvAccountId:n,kvNamespace:o,kvAuthEmail:a,kvAuthKey:s,kvTtl:i=2592e3,oauth2AuthDomain:c,oauth2ClientId:u,oauth2ClientSecret:p,oauth2Audience:d,oauth2Scopes:h=[],oauth2CallbackPath:f="/callback",oauth2CallbackType:l="cookie",oauth2LogoutPath:g="/logout",oauth2LoginPath:y="/login",oauth2ServerTokenPath:w="/oauth/token",oauth2ServerAuthorizePath:b="",oauth2ServerLogoutPath:K}){let O=new ae({accountId:n,namespace:o,authEmail:a,authKey:s,ttl:i}),ee=c,be=f,ft=l,mt=w,qe=b,yt=K,V=u,Ee=p,q=d,Fe=g,_=y,_e=h.join("%20");async function Le(m,H){let T=`${ee}${mt}`,R=await fetch(T,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:Pc({code:m,grant_type:"authorization_code",client_id:V,client_secret:Ee,redirect_uri:H})});if(!R.ok)throw new Error("Authentication failed");let F=await R.json();return{...F,expires:Date.now()+F.expires_in*1e3}}async function $o(m){if(co({cookieHeader:m.request.headers.cookie,cookieName:e})){let R=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${R}`,path:"/",maxAge:0}))}let T=Rr(m);if(K){let R=encodeURIComponent(`${m.request.protocol}://${m.request.host}${T}`);m.set("Location",`${ee}${yt}?client_id=${V}&returnTo=${R}`)}else m.set("Location",T);m.status=302}async function Mo(m){let H=m.request.href.split("?")[0],T=await Le(m.request.query.code,H),R=ho.default.generate(),F=await de.getSalt(),L=`${R}.${F}`,gt=await de.deriveAesGcmKey(R,F),te=await de.encrypt(gt,JSON.stringify(T));await O.put(R,te);let wt=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.status=302,ft==="query"?m.set("Location",`${m.request.query.state}?auth=${L}`):(m.set("Set-Cookie",xe.default.serialize(e,L,{httpOnly:t,domain:`.${wt}`,path:"/",maxAge:60*60*24*365})),m.set("Location",m.request.query.state))}async function qo(m,H){let[T,R]=H.split("."),F=await O.get(T);if(F){let L=await de.deriveAesGcmKey(T,R),gt=await de.decrypt(L,F),te=JSON.parse(gt);if(te.expires<Date.now()){te=await ar({refresh_token:te.refresh_token,clientId:V,authDomain:ee,clientSecret:Ee});let wt=await de.encrypt(L,JSON.stringify(te));await O.put(T,wt)}m.state.accessToken=te.access_token,m.state.accessToken&&(m.request.headers.authorization=`bearer ${m.state.accessToken}`)}else{let L=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${L}`,maxAge:0}))}}function Rr(m){let H=fe.get(m,"request.query.redirect-to");if(H)return H;let T=fe.get(m,"request.headers.referer");return T||"/"}async function Fo(m){if(m.request.method==="OPTIONS")m.status=200;else{let H=Rr(m),T=encodeURIComponent(H||"/"),R=encodeURIComponent(`${m.request.protocol}://${m.request.host}${be}`);m.status=302,m.set("location",`${ee}${qe}/authorize?state=${T}&client_id=${V}&response_type=code&scope=${_e}&audience=${q}&redirect_uri=${R}`)}}async function Lo(m,H){if(m.request.method==="OPTIONS")await H(m);else if(fe.get(m,"request.headers.authorization","").toLowerCase().startsWith("bearer "))fe.set(m,"state.access_token",m.request.headers.authorization.slice(7)),await H(m);else{let T=fe.get(m,"request.query.auth")||co({cookieHeader:m.request.headers.cookie,cookieName:e});if(T&&await qo(m,T),fe.get(m,"state.accessToken")||r)await H(m);else if(Tc(m.request.headers.accept)){let F=encodeURIComponent(m.request.href),L=encodeURIComponent(`${m.request.protocol}://${m.request.host}${be}`);m.status=302,m.set("location",`${ee}${qe}/authorize?state=${F}&client_id=${V}&response_type=code&scope=${_e}&audience=${q}&redirect_uri=${L}`)}else m.status=403,m.body="Forbidden"}}return async(m,H)=>{switch(m.request.path){case be:await Mo(m);break;case Fe:await $o(m);break;case _:await Fo(m);break;default:await Lo(m,H)}}}var lo=P($());var Hc={get:lo.default};function Kc(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function cr(e){let{localOriginOverride:t,backend:r}=e;return async n=>{let o=process.env.LOCAL?`${t||n.request.origin}${n.request.path}`:`${r}${n.request.path}`,a={headers:Kc(n.request.headers),method:n.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(n.request.method)!==-1&&Hc.get(n,"event.request.body")){let c=n.event.request.clone();a.body=c.body}let s=await fetch(o,a);n.body=s.body,n.status=s.status;let i=A.instanceToJson(s.headers);Object.keys(i).forEach(c=>{n.set(c,i[c])})}}function ur({body:e="",headers:t={},status:r=200}){return async n=>{e instanceof Object?(n.body=JSON.stringify(e),n.set("Content-Type","application/json")):n.body=A.resolveParams(e,n.params),n.status=r,Object.keys(t).forEach(o=>{n.set(o,A.resolveParams(t[o],n.params))})}}var fo=P($()),mo=P(et()),dr={get:fo.default,set:mo.default};function pr({type:e="IP",scope:t="default",limit:r=1e3}){let n={};function o(s,i){let c=i["x-real-ip"];return e==="IP"?`minute.${s}.${t}.${c}`:`minute.${s}.${t}.account`}function a(s){let i=dr.get(n,"minutes",{});Object.keys(i).forEach(c=>{c!==s&&delete n.minutes.minute})}return async(s,i)=>{let c=Math.trunc(Date.now()/6e4),u=Math.trunc(c*60+60-Date.now()/1e3),p=o(c,s.request.headers),d=dr.get(n,p,0);if(["HEAD","OPTIONS"].indexOf(s.request.method)===-1&&(d+=1),dr.set(n,p,d),r<d){s.status=429;return}a(c),await i(s)}}var yo=P(ze());function Oc(e,t={}){if(e&&t.forcePathStyle){let r=new URL(e);return`${r.protocol}//${r.host}/${t.bucket}`}if(e){let r=new URL(e);return`${r.protocol}//${t.bucket}.${r.host}`}return t.forcePathStyle&&t.region?`https://s3.${t.region}.amazonaws.com/${t.bucket}`:t.forcePathStyle?`https://s3.amazonaws.com/${t.bucket}`:t.region?`https://${t.bucket}.s3.${t.region}.amazonaws.com`:`https://${t.bucket}.s3.amazonaws.com`}function hr({accessKeyId:e,secretAccessKey:t,bucket:r,region:n,endpoint:o,forcePathStyle:a,enableBucketOperations:s=!1}){let i=new yo.AwsClient({accessKeyId:e,region:n,secretAccessKey:t}),c=Oc(o,{region:n,bucket:r,forcePathStyle:a});return async u=>{if(u.params.file===void 0&&!s){u.status=404,u.body=x.http.statusMessages[404],u.set("Content-Type","text/plain");return}let p=u.params.file?A.resolveParams(`${c}/{file}`,u.params):c,d={};u.request.headers.range&&(d.range=u.request.headers.range);let h=await i.fetch(p,{method:u.method||u.request.method,headers:d});u.status=h.status,u.body=h.body;let f=A.instanceToJson(h.headers);Object.keys(f).forEach(l=>{u.set(l,f[l])})}}var lr;function go(e){return new Uint8Array(e.split("").map(r=>r.charCodeAt(0)))}async function Rc(e){return lr||(lr=await crypto.subtle.importKey("raw",go(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"])),lr}async function xc(e,t){let r=await Rc(t),n=await crypto.subtle.sign({name:"HMAC"},r,go(e));return btoa(String.fromCharCode.apply(null,new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fr({secret:e}){return async(t,r)=>{let n=(t.request.path+t.request.search).replace(/([?|&]sign=[\w|-]+)/,"");if(await xc(n,e)!==t.query.sign){t.status=403;return}await r(t)}}function mr({host:e}){if(!e)throw new Error("Need to specify a host for the split middleware.");return async(t,r)=>{let n=t.clone();n.cloned=!0,n.request={...n.request,href:n.request.href.replace(n.request.href,e),host:e},t.event.waitUntil(r(n)),await r(t)}}async function Uc(e,t,r){let n=e.getReader(),o=t.getWriter(),a=new TextDecoder,s=new TextEncoder;for(;;){let{done:i,value:c}=await n.read();if(i)break;let u=a.decode(c),p=wo(u,r),d=s.encode(p);await o.write(d)}await o.close()}function kc(e,t){return e.replace(/{{\$(\d)}}/g,(r,n)=>t[parseInt(n,10)])}function wo(e,t){return t.reduce((r,n)=>r.replace(n.regex,(...o)=>kc(n.replace,o)),e)}function yr({transforms:e=[],statusCodes:t=[200]}){let r=e.map(n=>({regex:new RegExp(n.regex,"g"),replace:n.replace}));return async(n,o)=>{await o(n);let{body:a}=n;if(t.indexOf(n.status)!==-1)if(typeof a=="string")n.body=wo(a,r);else{let{readable:s,writable:i}=new TransformStream;Uc(a,i,r),n.body=s}}}async function Ic({projectID:e="your-project-id",API_KEY:t="GCP_API_KEY",token:r="action-token",siteKey:n="siteKey",expectedAction:o="action-name"}){let s=await(await fetch(`https://recaptchaenterprise.googleapis.com/v1/projects/${e}/assessments?key=${t}`,{body:JSON.stringify({event:{token:r,siteKey:n,expectedAction:o}}),headers:{"Content-Type":"application/json"},method:"POST"})).json();return s.tokenProperties.valid?s.tokenProperties.action===o?(s.riskAnalysis.reasons.forEach(i=>{console.log(i)}),s.riskAnalysis.score):(console.error("reCAPTCHA action error:"+o+":action:"+s.tokenProperties.action),null):(console.error("The CreateAssessment call failed because the token was: "+s.tokenProperties.invalidReason),0)}var Wc=e=>(e=e.split("?")[0],e.replace(/\W/g,"").slice(0,100));function gr({projectID:e,API_KEY:t,siteKey:r}){function n(o){return{token:o["g-recaptcha-token"]}}return async(o,a)=>{let{token:s}=n(o.request.headers),i=Wc(o.request.path);if((await Ic({projectID:e,API_KEY:t,token:s,siteKey:r,expectedAction:i})||0)<.5){o.status=409;return}await a(o)}}async function Nc({secret:e,token:t,expectedAction:r,remoteip:n}){if(!t)return{ok:!1,score:0,errorCodes:["missing-input-response"]};let o=new URLSearchParams({secret:e,response:t,...n?{remoteip:n}:{}}),s=await(await fetch("https://www.google.com/recaptcha/api/siteverify",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})).json(),i=!!s.success,c=s.action===r,u=typeof s.score=="number"?s.score:0;return{ok:i&&c,score:u,action:s.action,errorCodes:s["error-codes"]}}var Jc=e=>{let t=e;try{t=new URL(e,"http://dummy").pathname}catch{}return t=t.split("?")[0]||"/",t.replace(/\W/g,"").slice(0,100)},Ue=(e,t)=>{if(e instanceof Headers)return e.get(t);let r=e[t]??e[t.toLowerCase()];return Array.isArray(r)?r[0]??null:r??null};function wr({secret:e,headerName:t="x-recaptcha-token",minScore:r=.5,requireActionMatch:n=!0}){return async(o,a)=>{let s=o.request?.req||o.request||o,i=s.headers??o.request?.headers??{},c=Ue(i,t)||Ue(i,"g-recaptcha-token")||null,p=Ue(i,"x-recaptcha-action")||Jc(o.request?.path||o.request?.url||s.url||"/"),d=Ue(i,"cf-connecting-ip")||Ue(i,"x-forwarded-for")||void 0,h=await Nc({secret:e,token:c,expectedAction:p,remoteip:d});if(!(h.score>=r&&h.ok)){let l={action:h.action,expectedAction:p,score:h.score??0,errors:h.errorCodes??[]};console.warn("[reCAPTCHA] failed:"+JSON.stringify(l)),o.status=409,o.set?.("Content-Type","application/json"),o.body=JSON.stringify({error:"reCAPTCHA verification failed"});return}await a(o)}}async function Dc({secret:e,token:t,remoteip:r}){if(!t)return{ok:!1,errorCodes:["missing-input-response"]};let n=new URLSearchParams({secret:e,response:t,...r?{remoteip:r}:{}}),a=await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:n})).json();return{ok:!!a.success,errorCodes:a["error-codes"]}}var st=(e,t)=>{if(e instanceof Headers)return e.get(t);let r=e[t]??e[t.toLowerCase()];return Array.isArray(r)?r[0]??null:r??null};function Ar({secret:e,headerName:t="x-recaptcha-token"}){return async(r,n)=>{let a=(r.request||r).headers||{},s=st(a,t)||st(a,"cf-turnstile-token")||null,i=st(a,"cf-connecting-ip")||st(a,"x-forwarded-for")||void 0,c=await Dc({secret:e,token:s,remoteip:i});if(!c.ok){let p={errors:c.errorCodes??[]};console.warn("[Turnstile] verification failed: "+JSON.stringify(p)),r.status=409,r.headers||=new Headers,r.headers.set("Content-Type","application/json"),r.body=JSON.stringify({error:"Turnstile verification failed"});return}await n(r)}}var $c=e=>!new RegExp("(\b)(onS+)(s*)=|javascript|<(|/|[^/>][^>]+|/[^>][^>]+)>").test(e),Ao=(e,t,r)=>!(!$c(t)||!r[e](t));var Mc=e=>e!=null&&typeof e=="object"&&!Array.isArray(e),ke=(e,t)=>{let r=Object.keys(e);for(let n of r){let o=t[n];if(!o)return console.error("key not allowed",n),!1;if(e[n]===null&&(e[n]=""),Array.isArray(e[n])){if(typeof o=="function"){if(!Ao(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1;continue}for(let a of e[n])if(!ke(a,o))return console.error("error validating key+validateObject:",n),!1;continue}if(Mc(e[n])){if(!ke(e[n],o))return console.error("error validating key+validateObject:",n),!1;continue}if(!Ao(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1}return!0},So=e=>!(e==null||typeof e!="object"),qc=(e,t)=>{let r=e.query;return So(r)?ke(r,t):!1},Ie=(e,t)=>{let r=e.params;return r?So(r)?ke(r,t):!1:!0};async function Fc(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return{};try{let t=await e.text();return JSON.parse(t)}catch{}return{}}function Sr({allowedKeys:e}){return async(r,n)=>{if(!e)return r.status=501,!1;if(!Ie(r,e)||!qc(r,e))return r.status=422,!1;let o=await Fc(r.request);if(!ke(o,e))return r.status=422,!1;await n(r)}}var Wo=P($());var E=crypto,D=e=>e instanceof CryptoKey;var U=new TextEncoder,W=new TextDecoder,Ep=2**32;function z(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}var bo=e=>{let t=e;typeof t=="string"&&(t=U.encode(t));let r=32768,n=[];for(let o=0;o<t.length;o+=r)n.push(String.fromCharCode.apply(null,t.subarray(o,o+r)));return btoa(n.join(""))},N=e=>bo(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var me=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var S=class extends me{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var J=class extends me{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},X=class extends me{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var it=E.getRandomValues.bind(E);function B(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ct(e,t){return e.name===t}function br(e){return parseInt(e.name.slice(4),10)}function Bc(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vc(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Co(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ct(e.algorithm,"HMAC"))throw B("HMAC");let n=parseInt(t.slice(2),10);if(br(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ct(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(br(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ct(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");let n=parseInt(t.slice(2),10);if(br(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw B("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ct(e.algorithm,"ECDSA"))throw B("ECDSA");let n=Bc(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vc(e,r)}function _o(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var M=(e,...t)=>_o("Key must be ",e,...t);function Er(e,t,...r){return _o(`Key for the ${e} algorithm must be `,t,...r)}var Cr=e=>D(e),C=["CryptoKey"];var Zc=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},ye=Zc;function Qc(e){return typeof e=="object"&&e!==null}function k(e){if(!Qc(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var ut=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var Z=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,s)=>a===t[s])||Z(e,t,n+1)},Po=e=>{switch(!0){case Z(e,[42,134,72,206,61,3,1,7]):return"P-256";case Z(e,[43,129,4,0,34]):return"P-384";case Z(e,[43,129,4,0,35]):return"P-521";case Z(e,[43,101,110]):return"X25519";case Z(e,[43,101,111]):return"X448";case Z(e,[43,101,112]):return"Ed25519";case Z(e,[43,101,113]):return"Ed448";default:throw new S("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},nu=async(e,t,r,n,o)=>{let a,s,i=new Uint8Array(atob(r.replace(e,"")).split("").map(u=>u.charCodeAt(0))),c=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},s=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},s=c?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},s=c?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},s=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let u=Po(i);a=u.startsWith("P-")?{name:"ECDH",namedCurve:u}:{name:u},s=c?[]:["deriveBits"];break}case"EdDSA":a={name:Po(i)},s=c?["verify"]:["sign"];break;default:throw new S('Invalid or unsupported "alg" (Algorithm) value')}return E.subtle.importKey(t,i,a,o?.extractable??!1,s)},To=(e,t,r)=>nu(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r);async function _r(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return To(e,t,r)}var ou=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Cr(t))throw new TypeError(Er(e,t,...C,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${C.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},au=(e,t,r)=>{if(!Cr(t))throw new TypeError(Er(e,t,...C));if(t.type==="secret")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},su=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ou(e,t):au(e,t,r)},Je=su;function lu(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of n.crit){if(!a.has(s))throw new S(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}var ge=lu;var wu=Symbol();function dt(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new S(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function pt(e,t,r){if(D(t))return Co(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(M(t,...C));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(M(t,...C,"Uint8Array"))}var Q=e=>Math.floor(e.getTime()/1e3);var Su=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ht=e=>{let t=Su.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var _u=async(e,t,r)=>{let n=await pt(e,t,"sign");ut(e,n);let o=await E.subtle.sign(dt(e,n.algorithm),n,r);return new Uint8Array(o)},Uo=_u;var we=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ye(this._protectedHeader,this._unprotectedHeader))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ge(J,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=n;if(typeof s!="string"||!s)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');Je(s,t,"sign");let i=this._payload;a&&(i=U.encode(N(i)));let c;this._protectedHeader?c=U.encode(N(JSON.stringify(this._protectedHeader))):c=U.encode("");let u=z(c,U.encode("."),i),p=await Uo(s,t,u),d={signature:N(p),payload:""};return a&&(d.payload=W.decode(i)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=W.decode(c)),d}};var De=class{constructor(t){this._flattened=new we(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function Ae(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Se=class{constructor(t={}){if(!k(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:Ae("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Ae("setNotBefore",Q(t))}:this._payload={...this._payload,nbf:Q(new Date)+ht(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Ae("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Ae("setExpirationTime",Q(t))}:this._payload={...this._payload,exp:Q(new Date)+ht(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Q(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Ae("setIssuedAt",Q(t))}:this._payload={...this._payload,iat:Ae("setIssuedAt",t)},this}};var $e=class extends Se{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new De(U.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new X("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var Hu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Hu="jose/v5.1.0");var ko=function e(t){function r(o,a,s){var i,c={};if(Array.isArray(o))return o.concat(a);for(i in o)c[s?i.toLowerCase():i]=o[i];for(i in a){var u=s?i.toLowerCase():i,p=a[i];c[u]=u in c&&typeof p=="object"?r(c[u],p,u=="headers"):p}return c}function n(o,a,s,i,c){var u=typeof o!="string"?(a=o).url:o,p={config:a},d=r(t,a),h={};i=i||d.data,(d.transformRequest||[]).map(function(f){i=f(i,d.headers)||i}),d.auth&&(h.authorization=d.auth),i&&typeof i=="object"&&typeof i.append!="function"&&typeof i.text!="function"&&(i=JSON.stringify(i),h["content-type"]="application/json");try{h[d.xsrfHeaderName]=decodeURIComponent(document.cookie.match(RegExp("(^|; )"+d.xsrfCookieName+"=([^;]*)"))[2])}catch{}return d.baseURL&&(u=u.replace(/^(?!.*\/\/)\/?/,d.baseURL+"/")),d.params&&(u+=(~u.indexOf("?")?"&":"?")+(d.paramsSerializer?d.paramsSerializer(d.params):new URLSearchParams(d.params))),(d.fetch||fetch)(u,{method:(s||d.method||"get").toUpperCase(),body:i,headers:r(d.headers,h,!0),credentials:d.withCredentials?"include":c}).then(function(f){for(var l in f)typeof f[l]!="function"&&(p[l]=f[l]);return d.responseType=="stream"?(p.data=f.body,p):f[d.responseType||"text"]().then(function(g){p.data=g,p.data=JSON.parse(g)}).catch(Object).then(function(){return(d.validateStatus?d.validateStatus(f.status):f.ok)?p:Promise.reject(p)})})}return t=t||{},n.request=n,n.get=function(o,a){return n(o,a,"get")},n.delete=function(o,a){return n(o,a,"delete")},n.head=function(o,a){return n(o,a,"head")},n.options=function(o,a){return n(o,a,"options")},n.post=function(o,a,s){return n(o,s,"post",a)},n.put=function(o,a,s){return n(o,s,"put",a)},n.patch=function(o,a,s){return n(o,s,"patch",a)},n.all=Promise.all.bind(Promise),n.spread=function(o){return o.apply.bind(o,o)},n.CancelToken=typeof AbortController=="function"?AbortController:Object,n.defaults=t,n.create=e,n}();var Ru=e=>{if(!e)return!1;let t=JSON.parse(atob(e.split(".")[1])),r=Math.floor(Date.now()/1e3);return t.exp>r-600},lt=async(e,t)=>{let r=await GCP_INVOKER_TOKEN.get(t);if(Ru(r))return r;let n=await _r(e.private_key,"RS256"),o=e.client_email,a={iss:o,sub:o,aud:"https://www.googleapis.com/oauth2/v4/token",target_audience:t,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+3600},s=await new $e(a).setProtectedHeader({alg:"RS256",typ:"JWT"}).sign(n),i=await ko.post("https://www.googleapis.com/oauth2/v4/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s});return await GCP_INVOKER_TOKEN.delete(t),await GCP_INVOKER_TOKEN.put(t,i.data.id_token),i.data.id_token};var Io={get:Wo.default};function Pr({project_id:e,region:t,functionName:r,serviceAccount:n,allowedKeys:o}){return async(a,s)=>{if(o&&a.params&&!Ie(a,o))return a.status=422,a.body=JSON.stringify({error:"Invalid params"}),!1;let i=Io.get(a,"request.query",{}),c=new URLSearchParams(i).toString(),u=`https://${t}-${e}.cloudfunctions.net/${r}`,p=a.request.path,d=`https://${t}-${e}.cloudfunctions.net/${r}${p||""}${c?`?${c}`:""}`,h=await lt(n,u),f=new Headers(a.request.headers);f.set("X-Serverless-Authorization",`Bearer ${h}`);let l=a.event.cf||{},g={"X-Geo-Country":l.country,"X-Geo-City":l.city,"X-Geo-Latitude":l.latitude,"X-Geo-Longitude":l.longitude,"X-Geo-Timezone":l.timezone,"X-Geo-Region":l.region,"X-Geo-PostalCode":l.postalCode,"X-Geo-RegionCode":l.regionCode,"X-Geo-EU-Country":l.isEUCountry?"1":"0"};for(let[K,O]of Object.entries(g))O!==void 0&&f.set(K,O);let y={headers:f,method:a.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(a.request.method)!==-1&&Io.get(a,"event.request.body")){let K=a.event.request.clone();y.body=K.body}let w=await fetch(d,y);a.body=w.body,a.status=w.status;let b=A.instanceToJson(w.headers);A.mergeHeaders(b,a),await s(a)}}var xu=P($());function Tr({domain:e,serviceAccount:t,allowedKeys:r}){return async(n,o)=>{if(r&&n.params&&!Ie(n,r))return n.status=422,n.body=JSON.stringify({error:"Invalid params"}),!1;let a=new URL(n.event.request.url),s=`${e}${a.pathname}${a.search}`,i=new Headers(n.request.headers);if(t){let f=await lt(t,e);i.set("X-Serverless-Authorization",`Bearer ${f}`)}i.set("X-Token",i.get("authorization")||i.get("x-token")||"N/A"),i.delete("authorization");let c=n.event.cf||{},u={"X-Geo-Country":c.country,"X-Geo-City":c.city,"X-Geo-Latitude":c.latitude,"X-Geo-Longitude":c.longitude,"X-Geo-Timezone":c.timezone,"X-Geo-Region":c.region,"X-Geo-PostalCode":c.postalCode,"X-Geo-RegionCode":c.regionCode,"X-Geo-EU-Country":c.isEUCountry?"1":"0"};for(let[f,l]of Object.entries(u))l!==void 0&&i.set(f,l);let p={method:n.request.method,headers:i,redirect:"manual"};if(x.methodsMethodsWithBody.includes(n.request.method)){let f=n.event.request.clone();p.body=f.body}let d=await fetch(s,p),h=new Headers(d.headers);h.delete("content-length"),h.delete("transfer-encoding"),n.status=d.status,A.mergeHeaders(A.instanceToJson(h),n),n.body=d.body,await o(n)}}function Hr({headers:e={},headersFN:t}){return async(r,n)=>{if(e)for(let o of Object.keys(e))r.set(o.toLowerCase(),e[o]);if(t){let o=await t();for(let a of Object.keys(o))r.set(a,o[a])}await n(r)}}async function Uu(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return"";try{return await e.text()}catch{return""}}function ku(e){return new TextEncoder().encode(e).length}function No(e,t,r){e.status=413;let n=JSON.stringify({error:"Payload too large",limit:t,...r!=null?{received:r}:{}});e.set("content-type","application/json"),e.set("content-length",String(n.length)),e.body=n}function Kr({bodySizeLimit:e=512}={}){return async(t,r)=>{let n=t.request?.method||"GET";if(["POST","PATCH","PUT","DELETE"].indexOf(n)===-1)return r(t);let o=t.request?.headers?.["content-length"],a=o?Number(o):NaN;if(Number.isFinite(a)&&a>e)return No(t,e,a);let s=await Uu(t.request),i=typeof s=="string"?ku(s):0;if(i>e)return No(t,e,i);await r(t)}}var Jo={basicAuth:Tt,cache:Rt,cors:xt,geoDecorator:Ut,firestoreApiKey:$t,jwt:Mt,kvStorage:qt,kvStorageBinding:Lt,lambda:Gt,loadbalancer:Xt,logger:Zt,oauth2:ir,origin:cr,rateLimit:pr,response:ur,s3:hr,signature:fr,split:mr,transform:yr,recaptcha:gr,recaptchaV3:wr,turnstileVerify:Ar,userInputValidation:Sr,cloudfunction:Pr,gcpCloudrun:Tr,headers:Hr,bodySizeLimit:Kr};function Iu(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}function Wu(e){return e.storage}function Nu(e){let t=e.match(/^\/cache\/(.+)$/);return t?decodeURIComponent(t[1]):null}var Me=class{constructor(t,r){this.state=t,this.env=r}async fetch(t){let r=new URL(t.url),n=Nu(r.pathname);if(!n)return new Response("Not Found",{status:404});let o=Wu(this.state);if(t.method==="GET"){let a=await o.get(n);return a?a.expiresAt<=Date.now()?(await o.delete(n),new Response(null,{status:404})):Iu(a):new Response(null,{status:404})}if(t.method==="PUT"){let a=await t.json(),s=Number(a.ttlSeconds||0);return await o.put(n,{value:a.value,expiresAt:Date.now()+s*1e3}),new Response(null,{status:204})}return t.method==="DELETE"?(await o.delete(n),new Response(null,{status:204})):new Response("Method Not Allowed",{status:405})}};function Ju(e){return t=>{let r=e(t);return async(n,o)=>(n.upgradedByProxy||(Ot(n),n.upgradedByProxy=!0),r(n,o))}}var Or=class{constructor(t=[],r={}){this.router=new Do.default,t.forEach(n=>{let o=r[n.handlerName]||Jo[n.handlerName];if(!o)throw new Error(`Handler ${n.handlerName} is not supported`);let a=Ju(o);this.router.add(n,a(n.options||{}))})}async resolve(t){let r=t;return r.cf=r.request?.cf||{},this.router.resolve(r)}};module.exports=Or;module.exports.ApiKeyCacheDurableObject=Me;
8
8
  /*! Bundled license information:
9
9
 
10
10
  aws4fetch/dist/aws4fetch.umd.js: