@ahmadissa/cloudworker-proxy 1.1.130 → 1.1.131

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 Ko=Object.create;var wr=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var Ro=Object.getPrototypeOf,Uo=Object.prototype.hasOwnProperty;var _=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Io=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xo(t))!Uo.call(e,o)&&o!==r&&wr(e,o,{get:()=>t[o],enumerable:!(n=Oo(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Ko(Ro(e)):{},Io(t||!e||!e.__esModule?wr(r,"default",{value:e,enumerable:!0}):r,e));var lt=_((ad,Sr)=>{function Wo({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,(T,N,U)=>(u.push(U),"([^.]+)")),f=t.replace(/(:([^/]+))/g,(T,N,U)=>U.slice(-1)==="*"?(p.push(U.slice(0,U.length-1)),"(.*)"):(p.push(U),"([^/]*)")),l=new RegExp(`^${d}$`,"i"),m=new RegExp(`^${f}$`,"i"),w=r?new RegExp(`^${r}$`,"i"):null,y=new RegExp(`^${n.join("|")}$`,"i"),g=new RegExp(`^${a}$`,"i");return{hostVariables:u,pathVariables:p,host:l,path:m,excludePath:w,method:y,protocol:g,handler:o,handlerName:s,headers:i,data:c}}function Ar(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}async function Jo(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 ko(e){let t=new URL(e.url),r=Ar(t.searchParams),n=Ar(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 Jo(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)}}Sr.exports={parseRoute:Wo,parseRequest:ko}});var br=_((sd,Er)=>{function No(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 Do(e,t){let r=!0;return Object.keys(e.headers).forEach(n=>{t.headers[n]!==e.headers[n]&&(r=!1)}),r}function Mo(e,t){return e.protocol.test(t.protocol)}function $o(e,t){return e.method.test(t.method)&&e.host.test(t.host)&&e.path.test(t.path)&&Do(e,t)&&Mo(e,t)&&(!e.excludePath||!e.excludePath.test(t.path))}async function mt(e,t){let[r,...n]=t;if(!r)return new Response("NOT_FOUND",{status:404});if(!$o(r,e.request))return mt(e,n);e.state.handlers=e.state.handlers||[],e.state.handlers.push(r.handlerName||r.handler.name),e.params=No(e.request,r);try{return r.handler(e,async o=>mt(o,n))}catch(o){throw o.route=r.handler.name,o}}Er.exports={recurseRoutes:mt}});var _r=_((id,Cr)=>{Cr.exports={methods:{DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST"},statusMessages:{404:"Not found",429:"Rate limited"}}});var Hr=_((cd,Pr)=>{var qo=lt();Pr.exports=class vr{constructor(t){this.request=qo.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 vr(this.event);return t.cloned=!0,t}}});var Kr=_((ud,Tr)=>{var ue=lt(),Lo=br(),_e=_r(),Fo=Hr();Tr.exports=class{constructor(){this.routes=[]}get(t,r){let n=ue.parseRoute({method:[_e.methods.GET,_e.methods.HEAD],path:t,handler:r});this.routes.push(n)}post(t,r){let n=ue.parseRoute({method:[_e.methods.POST],path:t,handler:r});this.routes.push(n)}patch(t,r){let n=ue.parseRoute({method:[_e.methods.PATCH],path:t,handler:r});this.routes.push(n)}del(t,r){let n=ue.parseRoute({method:[_e.methods.DELETE],path:t,handler:r});this.routes.push(n)}use(t){let r=ue.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=ue.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 Fo(t);try{return await Lo.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 M=_((pd,qr)=>{var Go="Expected a function",Ir="__lodash_hash_undefined__",Wr=1/0,Bo="[object Function]",Vo="[object GeneratorFunction]",zo="[object Symbol]",Xo=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,jo=/^\w*$/,Yo=/^\./,Zo=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Qo=/[\\^$.*+?()[\]{}|]/g,ea=/\\(\\)?/g,ta=/^\[object .+?Constructor\]$/,ra=typeof global=="object"&&global&&global.Object===Object&&global,na=typeof self=="object"&&self&&self.Object===Object&&self,gt=ra||na||Function("return this")();function oa(e,t){return e?.[t]}function aa(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var sa=Array.prototype,ia=Function.prototype,Jr=Object.prototype,yt=gt["__core-js_shared__"],Or=function(){var e=/[^.]+$/.exec(yt&&yt.keys&&yt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),kr=ia.toString,wt=Jr.hasOwnProperty,Nr=Jr.toString,ca=RegExp("^"+kr.call(wt).replace(Qo,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xr=gt.Symbol,da=sa.splice,ua=Dr(gt,"Map"),ve=Dr(Object,"create"),Rr=xr?xr.prototype:void 0,Ur=Rr?Rr.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 pa(){this.__data__=ve?ve(null):{}}function ha(e){return this.has(e)&&delete this.__data__[e]}function fa(e){var t=this.__data__;if(ve){var r=t[e];return r===Ir?void 0:r}return wt.call(t,e)?t[e]:void 0}function la(e){var t=this.__data__;return ve?t[e]!==void 0:wt.call(t,e)}function ma(e,t){var r=this.__data__;return r[e]=ve&&t===void 0?Ir:t,this}re.prototype.clear=pa;re.prototype.delete=ha;re.prototype.get=fa;re.prototype.has=la;re.prototype.set=ma;function pe(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 ya(){this.__data__=[]}function ga(e){var t=this.__data__,r=$e(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():da.call(t,r,1),!0}function wa(e){var t=this.__data__,r=$e(t,e);return r<0?void 0:t[r][1]}function Aa(e){return $e(this.__data__,e)>-1}function Sa(e,t){var r=this.__data__,n=$e(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}pe.prototype.clear=ya;pe.prototype.delete=ga;pe.prototype.get=wa;pe.prototype.has=Aa;pe.prototype.set=Sa;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 Ea(){this.__data__={hash:new re,map:new(ua||pe),string:new re}}function ba(e){return qe(this,e).delete(e)}function Ca(e){return qe(this,e).get(e)}function _a(e){return qe(this,e).has(e)}function va(e,t){return qe(this,e).set(e,t),this}ne.prototype.clear=Ea;ne.prototype.delete=ba;ne.prototype.get=Ca;ne.prototype.has=_a;ne.prototype.set=va;function $e(e,t){for(var r=e.length;r--;)if(Ja(e[r][0],t))return r;return-1}function Pa(e,t){t=Oa(t,e)?[t]:Ka(t);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Ia(t[r++])];return r&&r==n?e:void 0}function Ha(e){if(!$r(e)||Ra(e))return!1;var t=ka(e)||aa(e)?ca:ta;return t.test(Wa(e))}function Ta(e){if(typeof e=="string")return e;if(St(e))return Ur?Ur.call(e):"";var t=e+"";return t=="0"&&1/e==-Wr?"-0":t}function Ka(e){return Mr(e)?e:Ua(e)}function qe(e,t){var r=e.__data__;return xa(t)?r[typeof t=="string"?"string":"hash"]:r.map}function Dr(e,t){var r=oa(e,t);return Ha(r)?r:void 0}function Oa(e,t){if(Mr(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||St(e)?!0:jo.test(e)||!Xo.test(e)||t!=null&&e in Object(t)}function xa(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ra(e){return!!Or&&Or in e}var Ua=At(function(e){e=Da(e);var t=[];return Yo.test(e)&&t.push(""),e.replace(Zo,function(r,n,o,a){t.push(o?a.replace(ea,"$1"):n||r)}),t});function Ia(e){if(typeof e=="string"||St(e))return e;var t=e+"";return t=="0"&&1/e==-Wr?"-0":t}function Wa(e){if(e!=null){try{return kr.call(e)}catch{}try{return e+""}catch{}}return""}function At(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(Go);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(At.Cache||ne),r}At.Cache=ne;function Ja(e,t){return e===t||e!==e&&t!==t}var Mr=Array.isArray;function ka(e){var t=$r(e)?Nr.call(e):"";return t==Bo||t==Vo}function $r(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Na(e){return!!e&&typeof e=="object"}function St(e){return typeof e=="symbol"||Na(e)&&Nr.call(e)==zo}function Da(e){return e==null?"":Ta(e)}function Ma(e,t,r){var n=e==null?void 0:Pa(e,t);return n===void 0?r:n}qr.exports=Ma});var Fe=_((Le,jr)=>{(function(e,t){typeof Le=="object"&&typeof jr<"u"?t(Le):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.aws4fetch={}))})(Le,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:f,secretAccessKey:l,sessionToken:m,service:w,region:y,cache:g,retries:T,initRetryMs:N}){if(f==null)throw new TypeError("accessKeyId is a required option");if(l==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=f,this.secretAccessKey=l,this.sessionToken=m,this.service=w,this.region=y,this.cache=g||new Map,this.retries=T??10,this.initRetryMs=N||50}async sign(f,l){if(f instanceof Request){let{method:y,url:g,headers:T,body:N}=f;l=Object.assign({method:y,url:g,headers:T},l),l.body==null&&T.has("Content-Type")&&(l.body=N!=null&&T.has("X-Amz-Content-Sha256")?N:await f.clone().arrayBuffer()),f=g}let m=new a(Object.assign({url:f},l,this,l&&l.aws)),w=Object.assign({},l,await m.sign());return delete w.aws,new Request(w.url.toString(),w)}async fetch(f,l){for(let m=0;m<=this.retries;m++){let w=fetch(await this.sign(f,l));if(m===this.retries)return w;let y=await w;if(y.status<500&&y.status!==429)return y;await new Promise(g=>setTimeout(g,Math.random()*this.initRetryMs*Math.pow(2,m)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class a{constructor({method:f,url:l,headers:m,body:w,accessKeyId:y,secretAccessKey:g,sessionToken:T,service:N,region:U,cache:ee,datetime:Se,signQuery:dt,appendSessionToken:ut,allHeaders:Ne,singleEncode:pt}){if(l==null)throw new TypeError("url is a required option");if(y==null)throw new TypeError("accessKeyId is a required option");if(g==null)throw new TypeError("secretAccessKey is a required option");this.method=f||(w?"POST":"GET"),this.url=new URL(l),this.headers=new Headers(m||{}),this.body=w,this.accessKeyId=y,this.secretAccessKey=g,this.sessionToken=T;let V,Ee;(!N||!U)&&([V,Ee]=p(this.url,this.headers)),this.service=N||V||"",this.region=U||Ee||"us-east-1",this.cache=ee||new Map,this.datetime=Se||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=dt,this.appendSessionToken=ut||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(C=>Ne||!n.includes(C)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(C=>C+":"+(C==="host"?this.url.host:(this.headers.get(C)||"").replace(/\s+/g," "))).join(`
1
+ "use strict";var Ko=Object.create;var Ar=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var Ro=Object.getPrototypeOf,Uo=Object.prototype.hasOwnProperty;var _=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Io=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xo(t))!Uo.call(e,o)&&o!==r&&Ar(e,o,{get:()=>t[o],enumerable:!(n=Oo(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Ko(Ro(e)):{},Io(t||!e||!e.__esModule?Ar(r,"default",{value:e,enumerable:!0}):r,e));var lt=_((ad,Er)=>{function Wo({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,(T,N,U)=>(u.push(U),"([^.]+)")),f=t.replace(/(:([^/]+))/g,(T,N,U)=>U.slice(-1)==="*"?(p.push(U.slice(0,U.length-1)),"(.*)"):(p.push(U),"([^/]*)")),l=new RegExp(`^${d}$`,"i"),m=new RegExp(`^${f}$`,"i"),w=r?new RegExp(`^${r}$`,"i"):null,y=new RegExp(`^${n.join("|")}$`,"i"),g=new RegExp(`^${a}$`,"i");return{hostVariables:u,pathVariables:p,host:l,path:m,excludePath:w,method:y,protocol:g,handler:o,handlerName:s,headers:i,data:c}}function Sr(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}async function Jo(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 ko(e){let t=new URL(e.url),r=Sr(t.searchParams),n=Sr(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 Jo(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)}}Er.exports={parseRoute:Wo,parseRequest:ko}});var Cr=_((sd,br)=>{function No(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 Do(e,t){let r=!0;return Object.keys(e.headers).forEach(n=>{t.headers[n]!==e.headers[n]&&(r=!1)}),r}function Mo(e,t){return e.protocol.test(t.protocol)}function $o(e,t){return e.method.test(t.method)&&e.host.test(t.host)&&e.path.test(t.path)&&Do(e,t)&&Mo(e,t)&&(!e.excludePath||!e.excludePath.test(t.path))}async function mt(e,t){let[r,...n]=t;if(!r)return new Response("NOT_FOUND",{status:404});if(!$o(r,e.request))return mt(e,n);e.state.handlers=e.state.handlers||[],e.state.handlers.push(r.handlerName||r.handler.name),e.params=No(e.request,r);try{return r.handler(e,async o=>mt(o,n))}catch(o){throw o.route=r.handler.name,o}}br.exports={recurseRoutes:mt}});var vr=_((id,_r)=>{_r.exports={methods:{DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST"},statusMessages:{404:"Not found",429:"Rate limited"}}});var Tr=_((cd,Hr)=>{var qo=lt();Hr.exports=class Pr{constructor(t){this.request=qo.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 Pr(this.event);return t.cloned=!0,t}}});var Or=_((ud,Kr)=>{var ue=lt(),Lo=Cr(),_e=vr(),Fo=Tr();Kr.exports=class{constructor(){this.routes=[]}get(t,r){let n=ue.parseRoute({method:[_e.methods.GET,_e.methods.HEAD],path:t,handler:r});this.routes.push(n)}post(t,r){let n=ue.parseRoute({method:[_e.methods.POST],path:t,handler:r});this.routes.push(n)}patch(t,r){let n=ue.parseRoute({method:[_e.methods.PATCH],path:t,handler:r});this.routes.push(n)}del(t,r){let n=ue.parseRoute({method:[_e.methods.DELETE],path:t,handler:r});this.routes.push(n)}use(t){let r=ue.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=ue.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 Fo(t);try{return await Lo.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 M=_((pd,Lr)=>{var Go="Expected a function",Wr="__lodash_hash_undefined__",Jr=1/0,Bo="[object Function]",Vo="[object GeneratorFunction]",zo="[object Symbol]",Xo=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,jo=/^\w*$/,Yo=/^\./,Zo=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Qo=/[\\^$.*+?()[\]{}|]/g,ea=/\\(\\)?/g,ta=/^\[object .+?Constructor\]$/,ra=typeof global=="object"&&global&&global.Object===Object&&global,na=typeof self=="object"&&self&&self.Object===Object&&self,gt=ra||na||Function("return this")();function oa(e,t){return e?.[t]}function aa(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var sa=Array.prototype,ia=Function.prototype,kr=Object.prototype,yt=gt["__core-js_shared__"],xr=function(){var e=/[^.]+$/.exec(yt&&yt.keys&&yt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Nr=ia.toString,wt=kr.hasOwnProperty,Dr=kr.toString,ca=RegExp("^"+Nr.call(wt).replace(Qo,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Rr=gt.Symbol,da=sa.splice,ua=Mr(gt,"Map"),ve=Mr(Object,"create"),Ur=Rr?Rr.prototype:void 0,Ir=Ur?Ur.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 pa(){this.__data__=ve?ve(null):{}}function ha(e){return this.has(e)&&delete this.__data__[e]}function fa(e){var t=this.__data__;if(ve){var r=t[e];return r===Wr?void 0:r}return wt.call(t,e)?t[e]:void 0}function la(e){var t=this.__data__;return ve?t[e]!==void 0:wt.call(t,e)}function ma(e,t){var r=this.__data__;return r[e]=ve&&t===void 0?Wr:t,this}re.prototype.clear=pa;re.prototype.delete=ha;re.prototype.get=fa;re.prototype.has=la;re.prototype.set=ma;function pe(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 ya(){this.__data__=[]}function ga(e){var t=this.__data__,r=$e(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():da.call(t,r,1),!0}function wa(e){var t=this.__data__,r=$e(t,e);return r<0?void 0:t[r][1]}function Aa(e){return $e(this.__data__,e)>-1}function Sa(e,t){var r=this.__data__,n=$e(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}pe.prototype.clear=ya;pe.prototype.delete=ga;pe.prototype.get=wa;pe.prototype.has=Aa;pe.prototype.set=Sa;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 Ea(){this.__data__={hash:new re,map:new(ua||pe),string:new re}}function ba(e){return qe(this,e).delete(e)}function Ca(e){return qe(this,e).get(e)}function _a(e){return qe(this,e).has(e)}function va(e,t){return qe(this,e).set(e,t),this}ne.prototype.clear=Ea;ne.prototype.delete=ba;ne.prototype.get=Ca;ne.prototype.has=_a;ne.prototype.set=va;function $e(e,t){for(var r=e.length;r--;)if(Ja(e[r][0],t))return r;return-1}function Pa(e,t){t=Oa(t,e)?[t]:Ka(t);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Ia(t[r++])];return r&&r==n?e:void 0}function Ha(e){if(!qr(e)||Ra(e))return!1;var t=ka(e)||aa(e)?ca:ta;return t.test(Wa(e))}function Ta(e){if(typeof e=="string")return e;if(St(e))return Ir?Ir.call(e):"";var t=e+"";return t=="0"&&1/e==-Jr?"-0":t}function Ka(e){return $r(e)?e:Ua(e)}function qe(e,t){var r=e.__data__;return xa(t)?r[typeof t=="string"?"string":"hash"]:r.map}function Mr(e,t){var r=oa(e,t);return Ha(r)?r:void 0}function Oa(e,t){if($r(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||St(e)?!0:jo.test(e)||!Xo.test(e)||t!=null&&e in Object(t)}function xa(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ra(e){return!!xr&&xr in e}var Ua=At(function(e){e=Da(e);var t=[];return Yo.test(e)&&t.push(""),e.replace(Zo,function(r,n,o,a){t.push(o?a.replace(ea,"$1"):n||r)}),t});function Ia(e){if(typeof e=="string"||St(e))return e;var t=e+"";return t=="0"&&1/e==-Jr?"-0":t}function Wa(e){if(e!=null){try{return Nr.call(e)}catch{}try{return e+""}catch{}}return""}function At(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(Go);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(At.Cache||ne),r}At.Cache=ne;function Ja(e,t){return e===t||e!==e&&t!==t}var $r=Array.isArray;function ka(e){var t=qr(e)?Dr.call(e):"";return t==Bo||t==Vo}function qr(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Na(e){return!!e&&typeof e=="object"}function St(e){return typeof e=="symbol"||Na(e)&&Dr.call(e)==zo}function Da(e){return e==null?"":Ta(e)}function Ma(e,t,r){var n=e==null?void 0:Pa(e,t);return n===void 0?r:n}Lr.exports=Ma});var Fe=_((Le,Yr)=>{(function(e,t){typeof Le=="object"&&typeof Yr<"u"?t(Le):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.aws4fetch={}))})(Le,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:f,secretAccessKey:l,sessionToken:m,service:w,region:y,cache:g,retries:T,initRetryMs:N}){if(f==null)throw new TypeError("accessKeyId is a required option");if(l==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=f,this.secretAccessKey=l,this.sessionToken=m,this.service=w,this.region=y,this.cache=g||new Map,this.retries=T??10,this.initRetryMs=N||50}async sign(f,l){if(f instanceof Request){let{method:y,url:g,headers:T,body:N}=f;l=Object.assign({method:y,url:g,headers:T},l),l.body==null&&T.has("Content-Type")&&(l.body=N!=null&&T.has("X-Amz-Content-Sha256")?N:await f.clone().arrayBuffer()),f=g}let m=new a(Object.assign({url:f},l,this,l&&l.aws)),w=Object.assign({},l,await m.sign());return delete w.aws,new Request(w.url.toString(),w)}async fetch(f,l){for(let m=0;m<=this.retries;m++){let w=fetch(await this.sign(f,l));if(m===this.retries)return w;let y=await w;if(y.status<500&&y.status!==429)return y;await new Promise(g=>setTimeout(g,Math.random()*this.initRetryMs*Math.pow(2,m)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class a{constructor({method:f,url:l,headers:m,body:w,accessKeyId:y,secretAccessKey:g,sessionToken:T,service:N,region:U,cache:ee,datetime:Se,signQuery:dt,appendSessionToken:ut,allHeaders:Ne,singleEncode:pt}){if(l==null)throw new TypeError("url is a required option");if(y==null)throw new TypeError("accessKeyId is a required option");if(g==null)throw new TypeError("secretAccessKey is a required option");this.method=f||(w?"POST":"GET"),this.url=new URL(l),this.headers=new Headers(m||{}),this.body=w,this.accessKeyId=y,this.secretAccessKey=g,this.sessionToken=T;let V,Ee;(!N||!U)&&([V,Ee]=p(this.url,this.headers)),this.service=N||V||"",this.region=U||Ee||"us-east-1",this.cache=ee||new Map,this.datetime=Se||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=dt,this.appendSessionToken=ut||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(C=>Ne||!n.includes(C)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(C=>C+":"+(C==="host"?this.url.host:(this.headers.get(C)||"").replace(/\s+/g," "))).join(`
2
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,"/");pt||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=u(this.encodedPath);let De=new Set;this.encodedSearch=[...this.url.searchParams].filter(([C])=>{if(!C)return!1;if(this.service==="s3"){if(De.has(C))return!1;De.add(C)}return!0}).map(C=>C.map(be=>u(encodeURIComponent(be)))).sort(([C,be],[Ce,Me])=>C<Ce?-1:C>Ce?1:be<Me?-1:be>Me?1:0).map(C=>C.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 f=this.datetime.slice(0,8),l=[this.secretAccessKey,f,this.region,this.service].join(),m=this.cache.get(l);if(!m){let w=await s("AWS4"+this.secretAccessKey,f),y=await s(w,this.region),g=await s(y,this.service);m=await s(g,"aws4_request"),this.cache.set(l,m)}return c(await s(m,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 f=this.headers.get("X-Amz-Content-Sha256");if(f==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");f=c(await i(this.body||""))}return f}}async function s(d,f){let l=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",l,t.encode(f))}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),f=>("0"+f.toString(16)).slice(-2)).join("")}function u(d){return d.replace(/[!'()*]/g,f=>"%"+f.charCodeAt(0).toString(16).toUpperCase())}function p(d,f){let{hostname:l,pathname:m}=d,w=l.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[y,g]=(w||["",""]).slice(1,3);if(g==="us-gov")g="us-gov-west-1";else if(g==="s3"||g==="s3-accelerate")g="us-east-1",y="s3";else if(y==="iot")l.startsWith("iot.")?y="execute-api":l.startsWith("data.jobs.iot.")?y="iot-jobs-data":y=m==="/mqtt"?"iotdevicegateway":"iotdata";else if(y==="autoscaling"){let T=(f.get("X-Amz-Target")||"").split(".")[0];T==="AnyScaleFrontendService"?y="application-autoscaling":T==="AnyScaleScalingPlannerFrontendService"&&(y="autoscaling-plans")}else g==null&&y.startsWith("s3-")?(g=y.slice(3).replace(/^fips-|^external-1/,""),y="s3"):y.endsWith("-fips")?y=y.slice(0,-5):g&&/-\d$/.test(y)&&!/-\d$/.test(g)&&([y,g]=[g,y]);return[r[y]||y,g]}e.AwsClient=o,e.AwsV4Signer=a,Object.defineProperty(e,"__esModule",{value:!0})})});var Xe=_((Id,pn)=>{var cs="Expected a function",rn="__lodash_hash_undefined__",nn=1/0,ds=9007199254740991,us="[object Function]",ps="[object GeneratorFunction]",hs="[object Symbol]",fs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ls=/^\w*$/,ms=/^\./,ys=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,gs=/[\\^$.*+?()[\]{}|]/g,ws=/\\(\\)?/g,As=/^\[object .+?Constructor\]$/,Ss=/^(?:0|[1-9]\d*)$/,Es=typeof global=="object"&&global&&global.Object===Object&&global,bs=typeof self=="object"&&self&&self.Object===Object&&self,Wt=Es||bs||Function("return this")();function Cs(e,t){return e?.[t]}function _s(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var vs=Array.prototype,Ps=Function.prototype,on=Object.prototype,It=Wt["__core-js_shared__"],Zr=function(){var e=/[^.]+$/.exec(It&&It.keys&&It.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),an=Ps.toString,Be=on.hasOwnProperty,sn=on.toString,Hs=RegExp("^"+an.call(Be).replace(gs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Qr=Wt.Symbol,Ts=vs.splice,Ks=cn(Wt,"Map"),Pe=cn(Object,"create"),en=Qr?Qr.prototype:void 0,tn=en?en.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 Os(){this.__data__=Pe?Pe(null):{}}function xs(e){return this.has(e)&&delete this.__data__[e]}function Rs(e){var t=this.__data__;if(Pe){var r=t[e];return r===rn?void 0:r}return Be.call(t,e)?t[e]:void 0}function Us(e){var t=this.__data__;return Pe?t[e]!==void 0:Be.call(t,e)}function Is(e,t){var r=this.__data__;return r[e]=Pe&&t===void 0?rn:t,this}ae.prototype.clear=Os;ae.prototype.delete=xs;ae.prototype.get=Rs;ae.prototype.has=Us;ae.prototype.set=Is;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 Ws(){this.__data__=[]}function Js(e){var t=this.__data__,r=Ve(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Ts.call(t,r,1),!0}function ks(e){var t=this.__data__,r=Ve(t,e);return r<0?void 0:t[r][1]}function Ns(e){return Ve(this.__data__,e)>-1}function Ds(e,t){var r=this.__data__,n=Ve(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}he.prototype.clear=Ws;he.prototype.delete=Js;he.prototype.get=ks;he.prototype.has=Ns;he.prototype.set=Ds;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 Ms(){this.__data__={hash:new ae,map:new(Ks||he),string:new ae}}function $s(e){return ze(this,e).delete(e)}function qs(e){return ze(this,e).get(e)}function Ls(e){return ze(this,e).has(e)}function Fs(e,t){return ze(this,e).set(e,t),this}se.prototype.clear=Ms;se.prototype.delete=$s;se.prototype.get=qs;se.prototype.has=Ls;se.prototype.set=Fs;function Gs(e,t,r){var n=e[t];(!(Be.call(e,t)&&dn(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function Ve(e,t){for(var r=e.length;r--;)if(dn(e[r][0],t))return r;return-1}function Bs(e){if(!Ge(e)||Qs(e))return!1;var t=ni(e)||_s(e)?Hs:As;return t.test(ri(e))}function Vs(e,t,r,n){if(!Ge(e))return e;t=Ys(t,e)?[t]:Xs(t);for(var o=-1,a=t.length,s=a-1,i=e;i!=null&&++o<a;){var c=ti(t[o]),u=r;if(o!=s){var p=i[c];u=n?n(p,c,i):void 0,u===void 0&&(u=Ge(p)?p:js(t[o+1])?[]:{})}Gs(i,c,u),i=i[c]}return e}function zs(e){if(typeof e=="string")return e;if(kt(e))return tn?tn.call(e):"";var t=e+"";return t=="0"&&1/e==-nn?"-0":t}function Xs(e){return un(e)?e:ei(e)}function ze(e,t){var r=e.__data__;return Zs(t)?r[typeof t=="string"?"string":"hash"]:r.map}function cn(e,t){var r=Cs(e,t);return Bs(r)?r:void 0}function js(e,t){return t=t??ds,!!t&&(typeof e=="number"||Ss.test(e))&&e>-1&&e%1==0&&e<t}function Ys(e,t){if(un(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||kt(e)?!0:ls.test(e)||!fs.test(e)||t!=null&&e in Object(t)}function Zs(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Qs(e){return!!Zr&&Zr in e}var ei=Jt(function(e){e=ai(e);var t=[];return ms.test(e)&&t.push(""),e.replace(ys,function(r,n,o,a){t.push(o?a.replace(ws,"$1"):n||r)}),t});function ti(e){if(typeof e=="string"||kt(e))return e;var t=e+"";return t=="0"&&1/e==-nn?"-0":t}function ri(e){if(e!=null){try{return an.call(e)}catch{}try{return e+""}catch{}}return""}function Jt(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(cs);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||se),r}Jt.Cache=se;function dn(e,t){return e===t||e!==e&&t!==t}var un=Array.isArray;function ni(e){var t=Ge(e)?sn.call(e):"";return t==us||t==ps}function Ge(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function oi(e){return!!e&&typeof e=="object"}function kt(e){return typeof e=="symbol"||oi(e)&&sn.call(e)==hs}function ai(e){return e==null?"":zs(e)}function si(e,t,r){return e==null?e:Vs(e,t,r)}pn.exports=si});var wn=_($t=>{"use strict";$t.parse=li;$t.serialize=mi;var pi=decodeURIComponent,hi=encodeURIComponent,fi=/; */,Ye=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function li(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");for(var r={},n=t||{},o=e.split(fi),a=n.decode||pi,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]=yi(p,a))}}return r}function mi(e,t,r){var n=r||{},o=n.encode||hi;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Ye.test(e))throw new TypeError("argument name is invalid");var a=o(t);if(a&&!Ye.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(!Ye.test(n.domain))throw new TypeError("option domain is invalid");s+="; Domain="+n.domain}if(n.path){if(!Ye.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 yi(e,t){try{return t(e)}catch{return e}}});var Sn=_((Zd,An)=>{"use strict";var Ze=1;function gi(){return Ze=(Ze*9301+49297)%233280,Ze/233280}function wi(e){Ze=e}An.exports={nextValue:gi,seed:wi}});var Oe=_((Qd,_n)=>{"use strict";var qt=Sn(),ce="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",z,En,Ke;function Lt(){Ke=!1}function bn(e){if(!e){z!==ce&&(z=ce,Lt());return}if(e!==z){if(e.length!==ce.length)throw new Error("Custom alphabet for shortid must be "+ce.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 "+ce.length+" unique characters. These characters were not unique: "+t.join(", "));z=e,Lt()}}function Ai(e){return bn(e),z}function Si(e){qt.seed(e),En!==e&&(Lt(),En=e)}function Ei(){z||bn(ce);for(var e=z.split(""),t=[],r=qt.nextValue(),n;e.length>0;)r=qt.nextValue(),n=Math.floor(r*e.length),t.push(e.splice(n,1)[0]);return t.join("")}function Cn(){return Ke||(Ke=Ei(),Ke)}function bi(e){var t=Cn();return t[e]}function Ci(){return z||ce}_n.exports={get:Ci,characters:Ai,seed:Si,lookup:bi,shuffled:Cn}});var Pn=_((eu,vn)=>{"use strict";var Ft=typeof window=="object"&&(window.crypto||window.msCrypto),Gt;!Ft||!Ft.getRandomValues?Gt=function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(Math.random()*256));return t}:Gt=function(e){return Ft.getRandomValues(new Uint8Array(e))};vn.exports=Gt});var Tn=_((tu,Hn)=>{Hn.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 On=_((ru,Kn)=>{"use strict";var _i=Oe(),vi=Pn(),Pi=Tn();function Hi(e){for(var t=0,r,n="";!r;)n=n+Pi(vi,_i.get(),1),r=e<Math.pow(16,t+1),t++;return n}Kn.exports=Hi});var Un=_((ou,Rn)=>{"use strict";var Qe=On(),nu=Oe(),Ti=1567752802062,Ki=7,et,xn;function Oi(e){var t="",r=Math.floor((Date.now()-Ti)*.001);return r===xn?et++:(et=0,xn=r),t=t+Qe(Ki),t=t+Qe(e),et>0&&(t=t+Qe(et)),t=t+Qe(r),t}Rn.exports=Oi});var Wn=_((au,In)=>{"use strict";var xi=Oe();function Ri(e){if(!e||typeof e!="string"||e.length<6)return!1;var t=new RegExp("[^"+xi.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]");return!t.test(e)}In.exports=Ri});var kn=_((su,Jn)=>{"use strict";Jn.exports=0});var Mn=_((iu,G)=>{"use strict";var Bt=Oe(),Ui=Un(),Ii=Wn(),Nn=kn()||0;function Wi(e){return Bt.seed(e),G.exports}function Ji(e){return Nn=e,G.exports}function ki(e){return e!==void 0&&Bt.characters(e),Bt.shuffled()}function Dn(){return Ui(Nn)}G.exports=Dn;G.exports.generate=Dn;G.exports.seed=Wi;G.exports.worker=Ji;G.exports.characters=ki;G.exports.isValid=Ii});var qn=_((cu,$n)=>{"use strict";$n.exports=Mn()});var Co=v(Kr());var Lr=v(M()),$a={get:Lr.default};function Et(e){e.status=401,e.body="Unauthorized",e.set("WWW-Authenticate","Basic")}function bt(e){return async(t,r)=>{if(t.request.path===e.logoutPath)return Et(t);let n=$a.get(t,"request.headers.authorization");if(!n||!n.startsWith("Basic "))return Et(t);let o=e.users.map(i=>i.authToken),a=n.substring(6),s=o.indexOf(a);return s===-1?Et(t):(t.state.user=e.users[s].username,r(t))}}var Fr=caches.default;async function qa(e){return await Fr.match(e)}async function La(e,t){return Fr.put(e.href,t)}var Ct={get:qa,set:La};async function Fa(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 Gr=Fa;function Ga(e,t={}){return Object.keys(t).reduce((r,n)=>r.replace(`{${n}}`,t[n]),e)}function _t(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}function Ba(e,t){Object.entries(e).forEach(([r,n])=>{t.header(r)||t.set(r,n)})}var vt=e=>{e.set=(t,r)=>{e.response.headers[t.toLowerCase()]=r},e.header=t=>e.request.headers[t.toLowerCase()]},A={resolveParams:Ga,instanceToJson:_t,mergeHeaders:Ba,upgradeCTX:vt};var Va=["x-ratelimit-count","x-ratelimit-limit","x-ratelimit-reset","x-cache-hit"];async function za(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}async function Xa(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 Gr(await za(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 Pt({cacheDuration:e,cacheKeyTemplate:t,headerBlacklist:r=Va}){return async(n,o)=>{let a=await Xa(n,t),s=await Ct.get(a);if(s){n.body=s.body,n.status=s.status;let i=_t(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(Ct.set(a,c))}}}function Ht({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,f=c.request.headers["access-control-request-headers"];if(ja(c,d,e),Ya(c,r),ts(c,o),!t.includes(p.toUpperCase())){c.status=405,c.body={error:`Method ${p} not allowed`};return}if(p==="OPTIONS"&&(Za(c,t),Qa(c,f,n),es(c,a),i)){c.status=s,c.set("content-length","0"),c.body="";return}await u(c)}}function ja(e,t,r){if(Array.isArray(r)){if(r[0]==="origin"){e.set("Access-Control-Allow-Origin",t),Br(e,"Origin");return}r[0]==="*"?e.set("Access-Control-Allow-Origin","*"):r.indexOf(t)!==-1&&(e.set("Access-Control-Allow-Origin",t),Br(e,"Origin"))}}function Ya(e,t){t&&e.set("Access-Control-Allow-Credentials",String(t))}function Za(e,t){e.set("Access-Control-Allow-Methods",t.join(","))}function Qa(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 es(e,t){t&&e.set("Access-Control-Max-Age",String(t))}function ts(e,t){t.length&&e.set("Access-Control-Expose-Headers",t.join(","))}function Br(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 rs={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 Tt(){return async(e,t)=>{let r=e.request.headers["cf-ipcountry"]||"XX";e.request.headers["proxy-continent"]=rs[r],await t(e)}}function Vr(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 ns(e){let t=e.split("."),r=JSON.parse(Vr(t[0])),n=JSON.parse(Vr(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 Kt({jwksUri:e,iss:t,aud:r,allowPublicAccess:n=!1}){async function o(){return(await(await fetch(e)).json()).keys}function a(c){return c.status=403,c.body="Forbidden",c}async function s(c){let p=new TextEncoder().encode([c.raw.header,c.raw.payload].join(".")),d=new Uint8Array(Array.from(c.signature).map(m=>m.charCodeAt(0))),f=await o();return(await Promise.all(f.map(async m=>{let w=await crypto.subtle.importKey("jwk",m,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",w,d,p)}))).some(m=>m)}async function i(c,u){if(c.request.method==="OPTIONS"||n)return u(c);if((c.request.headers.authorization||"").toLowerCase().startsWith("bearer")){let d=ns(c.request.headers.authorization.slice(7)),f=new Date(d.payload.exp*1e3),l=new Date(Date.now());return f<=l||!t||d.payload.iss!==t||!r||d.payload.aud!==r||!await s(d)?a(c):(c.state.user=d.payload,u(c))}return a(c)}return i}var zr=v(M()),os={get:zr.default},oe=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=os.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 O={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 as(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function Ot({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 oe({accountId:e,namespace:t,authEmail:r,authKey:n,mode:p}),f={...O.mime,...u};return async l=>{let m=A.resolveParams(a,l.params),w=m===""&&i?i:as(m,s),y=await d.get(o+w);!y&&c&&(y=await d.get(o+c)),y?(l.status=200,l.body=y,l.set("Content-Type",f[w.split(".").pop()]||"text/plain")):(l.status=404,l.body=O.http.statusMessages[404],l.set("Content-Type","text/plain"))}}var Xr=v(M());var xt={get:Xr.default};function ss(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function is(e,t){let r=xt.get(e,"headers.if-none-match"),n=xt.get(t,"metadata.headers.etag");return r?r===n:!1}function Rt({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:ss(c,n),p=await s(t+u);if(!p&&a&&(p=await s(t+a)),p)if(is(i.request,p))i.status=304;else{i.status=p.status,i.body=p.value;let d=xt.get(p,"metadata.headers",{});Object.keys(d).forEach(f=>{i.set(f,d[f])})}else i.status=404,i.body=O.http.statusMessages[404],i.set("Content-Type","text/plain")}}var Yr=v(Fe());function Ut({accessKeyId:e,secretAccessKey:t,region:r,lambdaName:n}){let o=new Yr.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 fn=v(M()),ln=v(Xe());var hn={get:fn.default,set:ln.default};function ii(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function ci(e){return e[Math.floor(Math.random()*e.length)]}function Nt({sources:e=[]}){return async t=>{let r=ci(e),n={method:t.request.method,headers:ii(t.request.headers),redirect:"manual",cf:t.request.cf};if(O.methodsMethodsWithBody.indexOf(t.request.method)!==-1&&hn.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);hn.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 gn=v(M());var Dt={name:"@ahmadissa/cloudworker-proxy",version:"1.1.130",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 ie=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 mn(e,t=".",r=""){return e instanceof Object?Object.keys(e).reduce((n,o)=>e[o]==null?n:{...n,...mn(e[o],t,r+o+t)},{}):r.endsWith(t)?{[r.slice(0,r.length-1)]:e}:{[r]:e}}var je=mn;var He=class{constructor(t){this.url=t.url,this.contentType=t.contentType,this.delimiter=t.delimiter,this.chunker=new ie({sink:this.sendMessage.bind(this),...t})}async log(t){let r=je(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 yn=v(Fe());var Te=class{constructor(t){this.delimiter=t.delimiter,this.chunker=new ie({sink:this.sendMessage.bind(this),...t}),this.awsClient=new yn.AwsClient({accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,region:t.region}),this.streamName=t.streamName,this.region=t.region}async log(t){let r=je(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:gn.default};async function ui(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}function Mt(e){let t;switch(e.type){case"http":t=new He(e);break;case"kinesis":t=new Te(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 ui(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:Dt.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:Dt.version};r.event.waitUntil(t.log(s))}}}var xe=v(wn()),Bn=v(M()),Vn=v(Xe()),zn=v(qn());async function Vt({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 Ln="PBKDF2",zt="AES-GCM",Ni="SHA-256",Di="raw";function Mi(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 Fn(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 $i(e){return new TextEncoder().encode(e).buffer}function qi(e){return new TextDecoder().decode(e)}async function Li(e){let t=new TextEncoder;return crypto.subtle.importKey(Di,t.encode(e),{name:Ln},!1,["deriveKey"])}async function Fi(e,t){let r=await Li(e),o=new TextEncoder().encode(t.replace(/_/g,"/").replace(/-/g,"+"));return crypto.subtle.deriveKey({name:Ln,salt:o,iterations:1e3,hash:{name:Ni}},r,{name:zt,length:256},!0,["encrypt","decrypt"])}async function Gi(){let e=crypto.getRandomValues(new Uint8Array(8));return Fn(e)}async function Bi(e,t){let r=Mi(t),n=r.slice(0,16),o=r.slice(16),a=await crypto.subtle.decrypt({name:zt,iv:n},e,o);return qi(a)}async function Vi(e,t){let r=crypto.getRandomValues(new Uint8Array(16)),n=await crypto.subtle.encrypt({name:zt,iv:r},e,$i(t)),o=new Uint8Array(n.byteLength+r.byteLength);return o.set(r,0),o.set(new Uint8Array(n),r.byteLength),Fn(o)}var de={decrypt:Bi,deriveAesGcmKey:Fi,encrypt:Vi,getSalt:Gi};var fe={get:Bn.default,set:Vn.default};function Gn({cookieHeader:e="",cookieName:t}){return xe.default.parse(e)[t]}function zi(e){return Object.keys(e).map(t=>`${t}=${encodeURIComponent(e[t])}`).join("&")}function Xi(e=""){return e.split(",").indexOf("text/html")!==-1}function Xt({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:f=[],oauth2CallbackPath:l="/callback",oauth2CallbackType:m="cookie",oauth2LogoutPath:w="/logout",oauth2LoginPath:y="/login",oauth2ServerTokenPath:g="/oauth/token",oauth2ServerAuthorizePath:T="",oauth2ServerLogoutPath:N}){let U=new oe({accountId:n,namespace:o,authEmail:a,authKey:s,ttl:i}),ee=c,Se=l,dt=m,ut=g,Ne=T,pt=N,V=u,Ee=p,q=d,De=w,C=y,Ce=f.join("%20");async function Me(h,H){let P=`${ee}${ut}`,K=await fetch(P,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:zi({code:h,grant_type:"authorization_code",client_id:V,client_secret:Ee,redirect_uri:H})});if(!K.ok)throw new Error("Authentication failed");let L=await K.json();return{...L,expires:Date.now()+L.expires_in*1e3}}async function _o(h){if(Gn({cookieHeader:h.request.headers.cookie,cookieName:e})){let K=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${K}`,path:"/",maxAge:0}))}let P=gr(h);if(N){let K=encodeURIComponent(`${h.request.protocol}://${h.request.host}${P}`);h.set("Location",`${ee}${pt}?client_id=${V}&returnTo=${K}`)}else h.set("Location",P);h.status=302}async function vo(h){let H=h.request.href.split("?")[0],P=await Me(h.request.query.code,H),K=zn.default.generate(),L=await de.getSalt(),F=`${K}.${L}`,ht=await de.deriveAesGcmKey(K,L),te=await de.encrypt(ht,JSON.stringify(P));await U.put(K,te);let ft=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.status=302,dt==="query"?h.set("Location",`${h.request.query.state}?auth=${F}`):(h.set("Set-Cookie",xe.default.serialize(e,F,{httpOnly:t,domain:`.${ft}`,path:"/",maxAge:60*60*24*365})),h.set("Location",h.request.query.state))}async function Po(h,H){let[P,K]=H.split("."),L=await U.get(P);if(L){let F=await de.deriveAesGcmKey(P,K),ht=await de.decrypt(F,L),te=JSON.parse(ht);if(te.expires<Date.now()){te=await Vt({refresh_token:te.refresh_token,clientId:V,authDomain:ee,clientSecret:Ee});let ft=await de.encrypt(F,JSON.stringify(te));await U.put(P,ft)}h.state.accessToken=te.access_token,h.state.accessToken&&(h.request.headers.authorization=`bearer ${h.state.accessToken}`)}else{let F=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${F}`,maxAge:0}))}}function gr(h){let H=fe.get(h,"request.query.redirect-to");if(H)return H;let P=fe.get(h,"request.headers.referer");return P||"/"}async function Ho(h){if(h.request.method==="OPTIONS")h.status=200;else{let H=gr(h),P=encodeURIComponent(H||"/"),K=encodeURIComponent(`${h.request.protocol}://${h.request.host}${Se}`);h.status=302,h.set("location",`${ee}${Ne}/authorize?state=${P}&client_id=${V}&response_type=code&scope=${Ce}&audience=${q}&redirect_uri=${K}`)}}async function To(h,H){if(h.request.method==="OPTIONS")await H(h);else if(fe.get(h,"request.headers.authorization","").toLowerCase().startsWith("bearer "))fe.set(h,"state.access_token",h.request.headers.authorization.slice(7)),await H(h);else{let P=fe.get(h,"request.query.auth")||Gn({cookieHeader:h.request.headers.cookie,cookieName:e});if(P&&await Po(h,P),fe.get(h,"state.accessToken")||r)await H(h);else if(Xi(h.request.headers.accept)){let L=encodeURIComponent(h.request.href),F=encodeURIComponent(`${h.request.protocol}://${h.request.host}${Se}`);h.status=302,h.set("location",`${ee}${Ne}/authorize?state=${L}&client_id=${V}&response_type=code&scope=${Ce}&audience=${q}&redirect_uri=${F}`)}else h.status=403,h.body="Forbidden"}}return async(h,H)=>{switch(h.request.path){case Se:await vo(h);break;case De:await _o(h);break;case C:await Ho(h);break;default:await To(h,H)}}}var Xn=v(M());var ji={get:Xn.default};function Yi(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function jt(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:Yi(n.request.headers),method:n.request.method,redirect:"manual"};if(O.methodsMethodsWithBody.indexOf(n.request.method)!==-1&&ji.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 Yt({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 jn=v(M()),Yn=v(Xe()),Zt={get:jn.default,set:Yn.default};function Qt({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=Zt.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=Zt.get(n,p,0);if(["HEAD","OPTIONS"].indexOf(s.request.method)===-1&&(d+=1),Zt.set(n,p,d),r<d){s.status=429;return}a(c),await i(s)}}var Zn=v(Fe());function Zi(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 er({accessKeyId:e,secretAccessKey:t,bucket:r,region:n,endpoint:o,forcePathStyle:a,enableBucketOperations:s=!1}){let i=new Zn.AwsClient({accessKeyId:e,region:n,secretAccessKey:t}),c=Zi(o,{region:n,bucket:r,forcePathStyle:a});return async u=>{if(u.params.file===void 0&&!s){u.status=404,u.body=O.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 f=await i.fetch(p,{method:u.method||u.request.method,headers:d});u.status=f.status,u.body=f.body;let l=A.instanceToJson(f.headers);Object.keys(l).forEach(m=>{u.set(m,l[m])})}}var tr;function Qn(e){return new Uint8Array(e.split("").map(r=>r.charCodeAt(0)))}async function Qi(e){return tr||(tr=await crypto.subtle.importKey("raw",Qn(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"])),tr}async function ec(e,t){let r=await Qi(t),n=await crypto.subtle.sign({name:"HMAC"},r,Qn(e));return btoa(String.fromCharCode.apply(null,new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rr({secret:e}){return async(t,r)=>{let n=(t.request.path+t.request.search).replace(/([?|&]sign=[\w|-]+)/,"");if(await ec(n,e)!==t.query.sign){t.status=403;return}await r(t)}}function nr({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 tc(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=eo(u,r),d=s.encode(p);await o.write(d)}await o.close()}function rc(e,t){return e.replace(/{{\$(\d)}}/g,(r,n)=>t[parseInt(n,10)])}function eo(e,t){return t.reduce((r,n)=>r.replace(n.regex,(...o)=>rc(n.replace,o)),e)}function or({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=eo(a,r);else{let{readable:s,writable:i}=new TransformStream;tc(a,i,r),n.body=s}}}async function nc({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 oc=e=>(e=e.split("?")[0],e.replace(/\W/g,"").slice(0,100));function ar({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=oc(o.request.path);if((await nc({projectID:e,API_KEY:t,token:s,siteKey:r,expectedAction:i})||0)<.5){o.status=409;return}await a(o)}}async function ac({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 sc=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)},Re=(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 sr({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=Re(i,t)||Re(i,"g-recaptcha-token")||null,p=Re(i,"x-recaptcha-action")||sc(o.request?.path||o.request?.url||s.url||"/"),d=Re(i,"cf-connecting-ip")||Re(i,"x-forwarded-for")||void 0,f=await ac({secret:e,token:c,expectedAction:p,remoteip:d});if(!(f.score>=r&&f.ok)){let m={action:f.action,expectedAction:p,score:f.score??0,errors:f.errorCodes??[]};console.warn("[reCAPTCHA] failed:"+JSON.stringify(m)),o.status=409,o.set?.("Content-Type","application/json"),o.body=JSON.stringify({error:"reCAPTCHA verification failed"});return}await a(o)}}var ic=e=>!new RegExp("(\b)(onS+)(s*)=|javascript|<(|/|[^/>][^>]+|/[^>][^>]+)>").test(e),cc=(e,t,r)=>!(!ic(t)||!r[e](t)),dc=e=>!(e===null||typeof e!="object"||Array.isArray(e)&&(!e[0]||typeof e[0]!="object")),tt=(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]=""),dc(e[n])){if(!tt(e[n],t))return console.error("error validating key+validateObject:",n),!1}else if(!cc(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1}return!0},to=e=>!(e==null||typeof e!="object"),uc=(e,t)=>{let r=e.query;return to(r)?tt(r,t):!1},ro=(e,t)=>{let r=e.params;return to(r)?tt(r,t):!1};async function pc(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return{};try{let t=await e.text();return JSON.parse(t)}catch{}return{}}function ir({allowedKeys:e}){return async(r,n)=>{if(!e)return r.status=501,!1;if(!uc(r,e))return r.status=422,!1;let o=await pc(r.request);if(!tt(o,e))return r.status=422,!1;await n(r)}}var Ao=v(M());var E=crypto,D=e=>e instanceof CryptoKey;var x=new TextEncoder,W=new TextDecoder,Iu=2**32;function X(...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 no=e=>{let t=e;typeof t=="string"&&(t=x.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(""))},J=e=>no(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var le=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 le{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var k=class extends le{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},j=class extends le{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var rt=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 nt(e,t){return e.name===t}function cr(e){return parseInt(e.name.slice(4),10)}function lc(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function mc(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 ao(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!nt(e.algorithm,"HMAC"))throw B("HMAC");let n=parseInt(t.slice(2),10);if(cr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!nt(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(cr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!nt(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");let n=parseInt(t.slice(2),10);if(cr(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(!nt(e.algorithm,"ECDSA"))throw B("ECDSA");let n=lc(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}mc(e,r)}function so(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 $=(e,...t)=>so("Key must be ",e,...t);function dr(e,t,...r){return so(`Key for the ${e} algorithm must be `,t,...r)}var ur=e=>D(e),b=["CryptoKey"];var Sc=(...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},me=Sc;function Ec(e){return typeof e=="object"&&e!==null}function R(e){if(!Ec(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 ot=(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)},co=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")}},vc=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=co(i);a=u.startsWith("P-")?{name:"ECDH",namedCurve:u}:{name:u},s=c?[]:["deriveBits"];break}case"EdDSA":a={name:co(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)},uo=(e,t,r)=>vc(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r);async function pr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return uo(e,t,r)}var Pc=(e,t)=>{if(!(t instanceof Uint8Array)){if(!ur(t))throw new TypeError(dr(e,t,...b,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${b.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Hc=(e,t,r)=>{if(!ur(t))throw new TypeError(dr(e,t,...b));if(t.type==="secret")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Tc=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Pc(e,t):Hc(e,t,r)},We=Tc;function Wc(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 ye=Wc;var Mc=Symbol();function at(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 st(e,t,r){if(D(t))return ao(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($(t,...b));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError($(t,...b,"Uint8Array"))}var Q=e=>Math.floor(e.getTime()/1e3);var qc=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,it=e=>{let t=qc.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 Bc=async(e,t,r)=>{let n=await st(e,t,"sign");ot(e,n);let o=await E.subtle.sign(at(e,n.algorithm),n,r);return new Uint8Array(o)},yo=Bc;var ge=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 k("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!me(this._protectedHeader,this._unprotectedHeader))throw new k("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ye(k,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new k('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=n;if(typeof s!="string"||!s)throw new k('JWS "alg" (Algorithm) Header Parameter missing or invalid');We(s,t,"sign");let i=this._payload;a&&(i=x.encode(J(i)));let c;this._protectedHeader?c=x.encode(J(JSON.stringify(this._protectedHeader))):c=x.encode("");let u=X(c,x.encode("."),i),p=await yo(s,t,u),d={signature:J(p),payload:""};return a&&(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 ge(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 we(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Ae=class{constructor(t={}){if(!R(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:we("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:we("setNotBefore",Q(t))}:this._payload={...this._payload,nbf:Q(new Date)+it(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:we("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:we("setExpirationTime",Q(t))}:this._payload={...this._payload,exp:Q(new Date)+it(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Q(new Date)}:t instanceof Date?this._payload={...this._payload,iat:we("setIssuedAt",Q(t))}:this._payload={...this._payload,iat:we("setIssuedAt",t)},this}};var ke=class extends Ae{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new Je(x.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 j("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var jc;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(jc="jose/v5.1.0");var go=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),f={};i=i||d.data,(d.transformRequest||[]).map(function(l){i=l(i,d.headers)||i}),d.auth&&(f.authorization=d.auth),i&&typeof i=="object"&&typeof i.append!="function"&&typeof i.text!="function"&&(i=JSON.stringify(i),f["content-type"]="application/json");try{f[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,f,!0),credentials:d.withCredentials?"include":c}).then(function(l){for(var m in l)typeof l[m]!="function"&&(p[m]=l[m]);return d.responseType=="stream"?(p.data=l.body,p):l[d.responseType||"text"]().then(function(w){p.data=w,p.data=JSON.parse(w)}).catch(Object).then(function(){return(d.validateStatus?d.validateStatus(l.status):l.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 Qc=e=>{if(!e)return!1;let t=JSON.parse(atob(e.split(".")[1])),r=Math.floor(Date.now()/1e3);return t.exp>r-600},ct=async(e,t)=>{let r=await GCP_INVOKER_TOKEN.get(t);if(Qc(r))return r;let n=await pr(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 ke(a).setProtectedHeader({alg:"RS256",typ:"JWT"}).sign(n),i=await go.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 wo={get:Ao.default};function fr({project_id:e,region:t,functionName:r,serviceAccount:n}){return async(o,a)=>{let s=wo.get(o,"request.query",{}),i=new URLSearchParams(s).toString(),c=`https://${t}-${e}.cloudfunctions.net/${r}`,u=`https://${t}-${e}.cloudfunctions.net/${r}${i?`?${i}`:""}`,p=await ct(n,c);o.request.headers["X-Serverless-Authorization"]=`Bearer ${p}`;let d={headers:o.request.headers,method:o.request.method,redirect:"manual"};if(O.methodsMethodsWithBody.indexOf(o.request.method)!==-1&&wo.get(o,"event.request.body")){let m=o.event.request.clone();d.body=m.body}let f=await fetch(u,d);o.body=f.body,o.status=f.status;let l=A.instanceToJson(f.headers);A.mergeHeaders(l,o),await a(o)}}var So=v(M());var ed={get:So.default};function lr({domain:e,serviceAccount:t,allowedKeys:r}){return async(n,o)=>{if(r&&n.params&&!ro(n,r))return n.status=422,n.body=JSON.stringify({error:"Invalid params"}),!1;let a=`${e}${n.request.path}`,s=await ct(t,e),i=new Headers(n.request.headers);i.set("X-Serverless-Authorization",`Bearer ${s}`),i.set("X-Token",i.get("authorization")||"N/A"),i.set("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[l,m]of Object.entries(u))m!==void 0&&i.set(l,m);let p={method:n.request.method,headers:i,redirect:"manual"};if(O.methodsMethodsWithBody.includes(n.request.method)&&ed.get(n,"event.request.body")){let l=n.event.request.clone();p.body=l.body}let d=await fetch(a,p),f=A.instanceToJson(d.headers);n.status=d.status,n.body=await d.text(),A.mergeHeaders(f,n),await o(n)}}function mr({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 td(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return"";try{return await e.text()}catch{return""}}function rd(e){return new TextEncoder().encode(e).length}function Eo(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 yr({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 Eo(t,e,a);let s=await td(t.request),i=typeof s=="string"?rd(s):0;if(i>e)return Eo(t,e,i);await r(t)}}var bo={basicAuth:bt,cache:Pt,cors:Ht,geoDecorator:Tt,jwt:Kt,kvStorage:Ot,kvStorageBinding:Rt,lambda:Ut,loadbalancer:Nt,logger:Mt,oauth2:Xt,origin:jt,rateLimit:Qt,response:Yt,s3:er,signature:rr,split:nr,transform:or,recaptcha:ar,recaptchaV3:sr,userInputValidation:ir,cloudfunction:fr,gcpCloudrun:lr,headers:mr,bodySizeLimit:yr};function nd(e){return t=>{let r=e(t);return async(n,o)=>(n.__upgraded||(vt(n),n.__upgraded=!0),r(n,o))}}module.exports=class{constructor(t=[],r={}){this.router=new Co.default,t.forEach(n=>{let o=r[n.handlerName]||bo[n.handlerName];if(!o)throw new Error(`Handler ${n.handlerName} is not supported`);let a=nd(o);this.router.add(n,a(n.options))})}async resolve(t){return t.cf=t?.request?.cf||{},this.router.resolve(t)}};
5
+ `)}async hexBodyHash(){let f=this.headers.get("X-Amz-Content-Sha256");if(f==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");f=c(await i(this.body||""))}return f}}async function s(d,f){let l=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",l,t.encode(f))}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),f=>("0"+f.toString(16)).slice(-2)).join("")}function u(d){return d.replace(/[!'()*]/g,f=>"%"+f.charCodeAt(0).toString(16).toUpperCase())}function p(d,f){let{hostname:l,pathname:m}=d,w=l.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[y,g]=(w||["",""]).slice(1,3);if(g==="us-gov")g="us-gov-west-1";else if(g==="s3"||g==="s3-accelerate")g="us-east-1",y="s3";else if(y==="iot")l.startsWith("iot.")?y="execute-api":l.startsWith("data.jobs.iot.")?y="iot-jobs-data":y=m==="/mqtt"?"iotdevicegateway":"iotdata";else if(y==="autoscaling"){let T=(f.get("X-Amz-Target")||"").split(".")[0];T==="AnyScaleFrontendService"?y="application-autoscaling":T==="AnyScaleScalingPlannerFrontendService"&&(y="autoscaling-plans")}else g==null&&y.startsWith("s3-")?(g=y.slice(3).replace(/^fips-|^external-1/,""),y="s3"):y.endsWith("-fips")?y=y.slice(0,-5):g&&/-\d$/.test(y)&&!/-\d$/.test(g)&&([y,g]=[g,y]);return[r[y]||y,g]}e.AwsClient=o,e.AwsV4Signer=a,Object.defineProperty(e,"__esModule",{value:!0})})});var Xe=_((Id,hn)=>{var cs="Expected a function",nn="__lodash_hash_undefined__",on=1/0,ds=9007199254740991,us="[object Function]",ps="[object GeneratorFunction]",hs="[object Symbol]",fs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ls=/^\w*$/,ms=/^\./,ys=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,gs=/[\\^$.*+?()[\]{}|]/g,ws=/\\(\\)?/g,As=/^\[object .+?Constructor\]$/,Ss=/^(?:0|[1-9]\d*)$/,Es=typeof global=="object"&&global&&global.Object===Object&&global,bs=typeof self=="object"&&self&&self.Object===Object&&self,Wt=Es||bs||Function("return this")();function Cs(e,t){return e?.[t]}function _s(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var vs=Array.prototype,Ps=Function.prototype,an=Object.prototype,It=Wt["__core-js_shared__"],Qr=function(){var e=/[^.]+$/.exec(It&&It.keys&&It.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),sn=Ps.toString,Be=an.hasOwnProperty,cn=an.toString,Hs=RegExp("^"+sn.call(Be).replace(gs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),en=Wt.Symbol,Ts=vs.splice,Ks=dn(Wt,"Map"),Pe=dn(Object,"create"),tn=en?en.prototype:void 0,rn=tn?tn.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 Os(){this.__data__=Pe?Pe(null):{}}function xs(e){return this.has(e)&&delete this.__data__[e]}function Rs(e){var t=this.__data__;if(Pe){var r=t[e];return r===nn?void 0:r}return Be.call(t,e)?t[e]:void 0}function Us(e){var t=this.__data__;return Pe?t[e]!==void 0:Be.call(t,e)}function Is(e,t){var r=this.__data__;return r[e]=Pe&&t===void 0?nn:t,this}ae.prototype.clear=Os;ae.prototype.delete=xs;ae.prototype.get=Rs;ae.prototype.has=Us;ae.prototype.set=Is;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 Ws(){this.__data__=[]}function Js(e){var t=this.__data__,r=Ve(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Ts.call(t,r,1),!0}function ks(e){var t=this.__data__,r=Ve(t,e);return r<0?void 0:t[r][1]}function Ns(e){return Ve(this.__data__,e)>-1}function Ds(e,t){var r=this.__data__,n=Ve(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}he.prototype.clear=Ws;he.prototype.delete=Js;he.prototype.get=ks;he.prototype.has=Ns;he.prototype.set=Ds;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 Ms(){this.__data__={hash:new ae,map:new(Ks||he),string:new ae}}function $s(e){return ze(this,e).delete(e)}function qs(e){return ze(this,e).get(e)}function Ls(e){return ze(this,e).has(e)}function Fs(e,t){return ze(this,e).set(e,t),this}se.prototype.clear=Ms;se.prototype.delete=$s;se.prototype.get=qs;se.prototype.has=Ls;se.prototype.set=Fs;function Gs(e,t,r){var n=e[t];(!(Be.call(e,t)&&un(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function Ve(e,t){for(var r=e.length;r--;)if(un(e[r][0],t))return r;return-1}function Bs(e){if(!Ge(e)||Qs(e))return!1;var t=ni(e)||_s(e)?Hs:As;return t.test(ri(e))}function Vs(e,t,r,n){if(!Ge(e))return e;t=Ys(t,e)?[t]:Xs(t);for(var o=-1,a=t.length,s=a-1,i=e;i!=null&&++o<a;){var c=ti(t[o]),u=r;if(o!=s){var p=i[c];u=n?n(p,c,i):void 0,u===void 0&&(u=Ge(p)?p:js(t[o+1])?[]:{})}Gs(i,c,u),i=i[c]}return e}function zs(e){if(typeof e=="string")return e;if(kt(e))return rn?rn.call(e):"";var t=e+"";return t=="0"&&1/e==-on?"-0":t}function Xs(e){return pn(e)?e:ei(e)}function ze(e,t){var r=e.__data__;return Zs(t)?r[typeof t=="string"?"string":"hash"]:r.map}function dn(e,t){var r=Cs(e,t);return Bs(r)?r:void 0}function js(e,t){return t=t??ds,!!t&&(typeof e=="number"||Ss.test(e))&&e>-1&&e%1==0&&e<t}function Ys(e,t){if(pn(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||kt(e)?!0:ls.test(e)||!fs.test(e)||t!=null&&e in Object(t)}function Zs(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Qs(e){return!!Qr&&Qr in e}var ei=Jt(function(e){e=ai(e);var t=[];return ms.test(e)&&t.push(""),e.replace(ys,function(r,n,o,a){t.push(o?a.replace(ws,"$1"):n||r)}),t});function ti(e){if(typeof e=="string"||kt(e))return e;var t=e+"";return t=="0"&&1/e==-on?"-0":t}function ri(e){if(e!=null){try{return sn.call(e)}catch{}try{return e+""}catch{}}return""}function Jt(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(cs);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||se),r}Jt.Cache=se;function un(e,t){return e===t||e!==e&&t!==t}var pn=Array.isArray;function ni(e){var t=Ge(e)?cn.call(e):"";return t==us||t==ps}function Ge(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function oi(e){return!!e&&typeof e=="object"}function kt(e){return typeof e=="symbol"||oi(e)&&cn.call(e)==hs}function ai(e){return e==null?"":zs(e)}function si(e,t,r){return e==null?e:Vs(e,t,r)}hn.exports=si});var An=_($t=>{"use strict";$t.parse=li;$t.serialize=mi;var pi=decodeURIComponent,hi=encodeURIComponent,fi=/; */,Ye=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function li(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");for(var r={},n=t||{},o=e.split(fi),a=n.decode||pi,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]=yi(p,a))}}return r}function mi(e,t,r){var n=r||{},o=n.encode||hi;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Ye.test(e))throw new TypeError("argument name is invalid");var a=o(t);if(a&&!Ye.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(!Ye.test(n.domain))throw new TypeError("option domain is invalid");s+="; Domain="+n.domain}if(n.path){if(!Ye.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 yi(e,t){try{return t(e)}catch{return e}}});var En=_((Zd,Sn)=>{"use strict";var Ze=1;function gi(){return Ze=(Ze*9301+49297)%233280,Ze/233280}function wi(e){Ze=e}Sn.exports={nextValue:gi,seed:wi}});var Oe=_((Qd,vn)=>{"use strict";var qt=En(),ce="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",z,bn,Ke;function Lt(){Ke=!1}function Cn(e){if(!e){z!==ce&&(z=ce,Lt());return}if(e!==z){if(e.length!==ce.length)throw new Error("Custom alphabet for shortid must be "+ce.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 "+ce.length+" unique characters. These characters were not unique: "+t.join(", "));z=e,Lt()}}function Ai(e){return Cn(e),z}function Si(e){qt.seed(e),bn!==e&&(Lt(),bn=e)}function Ei(){z||Cn(ce);for(var e=z.split(""),t=[],r=qt.nextValue(),n;e.length>0;)r=qt.nextValue(),n=Math.floor(r*e.length),t.push(e.splice(n,1)[0]);return t.join("")}function _n(){return Ke||(Ke=Ei(),Ke)}function bi(e){var t=_n();return t[e]}function Ci(){return z||ce}vn.exports={get:Ci,characters:Ai,seed:Si,lookup:bi,shuffled:_n}});var Hn=_((eu,Pn)=>{"use strict";var Ft=typeof window=="object"&&(window.crypto||window.msCrypto),Gt;!Ft||!Ft.getRandomValues?Gt=function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(Math.random()*256));return t}:Gt=function(e){return Ft.getRandomValues(new Uint8Array(e))};Pn.exports=Gt});var Kn=_((tu,Tn)=>{Tn.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 xn=_((ru,On)=>{"use strict";var _i=Oe(),vi=Hn(),Pi=Kn();function Hi(e){for(var t=0,r,n="";!r;)n=n+Pi(vi,_i.get(),1),r=e<Math.pow(16,t+1),t++;return n}On.exports=Hi});var In=_((ou,Un)=>{"use strict";var Qe=xn(),nu=Oe(),Ti=1567752802062,Ki=7,et,Rn;function Oi(e){var t="",r=Math.floor((Date.now()-Ti)*.001);return r===Rn?et++:(et=0,Rn=r),t=t+Qe(Ki),t=t+Qe(e),et>0&&(t=t+Qe(et)),t=t+Qe(r),t}Un.exports=Oi});var Jn=_((au,Wn)=>{"use strict";var xi=Oe();function Ri(e){if(!e||typeof e!="string"||e.length<6)return!1;var t=new RegExp("[^"+xi.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]");return!t.test(e)}Wn.exports=Ri});var Nn=_((su,kn)=>{"use strict";kn.exports=0});var $n=_((iu,G)=>{"use strict";var Bt=Oe(),Ui=In(),Ii=Jn(),Dn=Nn()||0;function Wi(e){return Bt.seed(e),G.exports}function Ji(e){return Dn=e,G.exports}function ki(e){return e!==void 0&&Bt.characters(e),Bt.shuffled()}function Mn(){return Ui(Dn)}G.exports=Mn;G.exports.generate=Mn;G.exports.seed=Wi;G.exports.worker=Ji;G.exports.characters=ki;G.exports.isValid=Ii});var Ln=_((cu,qn)=>{"use strict";qn.exports=$n()});var Co=v(Or());var Fr=v(M()),$a={get:Fr.default};function Et(e){e.status=401,e.body="Unauthorized",e.set("WWW-Authenticate","Basic")}function bt(e){return async(t,r)=>{if(t.request.path===e.logoutPath)return Et(t);let n=$a.get(t,"request.headers.authorization");if(!n||!n.startsWith("Basic "))return Et(t);let o=e.users.map(i=>i.authToken),a=n.substring(6),s=o.indexOf(a);return s===-1?Et(t):(t.state.user=e.users[s].username,r(t))}}var Gr=caches.default;async function qa(e){return await Gr.match(e)}async function La(e,t){return Gr.put(e.href,t)}var Ct={get:qa,set:La};async function Fa(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 Br=Fa;function Ga(e,t={}){return Object.keys(t).reduce((r,n)=>r.replace(`{${n}}`,t[n]),e)}function _t(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}function Ba(e,t){Object.entries(e).forEach(([r,n])=>{t.header(r)||t.set(r,n)})}var vt=e=>{e.set=(t,r)=>{e.response.headers[t.toLowerCase()]=r},e.header=t=>e.request.headers[t.toLowerCase()]},A={resolveParams:Ga,instanceToJson:_t,mergeHeaders:Ba,upgradeCTX:vt};var Va=["x-ratelimit-count","x-ratelimit-limit","x-ratelimit-reset","x-cache-hit"];async function za(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}async function Xa(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 Br(await za(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 Pt({cacheDuration:e,cacheKeyTemplate:t,headerBlacklist:r=Va}){return async(n,o)=>{let a=await Xa(n,t),s=await Ct.get(a);if(s){n.body=s.body,n.status=s.status;let i=_t(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(Ct.set(a,c))}}}function Ht({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,f=c.request.headers["access-control-request-headers"];if(ja(c,d,e),Ya(c,r),ts(c,o),!t.includes(p.toUpperCase())){c.status=405,c.body={error:`Method ${p} not allowed`};return}if(p==="OPTIONS"&&(Za(c,t),Qa(c,f,n),es(c,a),i)){c.status=s,c.set("content-length","0"),c.body="";return}await u(c)}}function ja(e,t,r){if(Array.isArray(r)){if(r[0]==="origin"){e.set("Access-Control-Allow-Origin",t),Vr(e,"Origin");return}r[0]==="*"?e.set("Access-Control-Allow-Origin","*"):r.indexOf(t)!==-1&&(e.set("Access-Control-Allow-Origin",t),Vr(e,"Origin"))}}function Ya(e,t){t&&e.set("Access-Control-Allow-Credentials",String(t))}function Za(e,t){e.set("Access-Control-Allow-Methods",t.join(","))}function Qa(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 es(e,t){t&&e.set("Access-Control-Max-Age",String(t))}function ts(e,t){t.length&&e.set("Access-Control-Expose-Headers",t.join(","))}function Vr(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 rs={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 Tt(){return async(e,t)=>{let r=e.request.headers["cf-ipcountry"]||"XX";e.request.headers["proxy-continent"]=rs[r],await t(e)}}function zr(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 ns(e){let t=e.split("."),r=JSON.parse(zr(t[0])),n=JSON.parse(zr(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 Kt({jwksUri:e,iss:t,aud:r,allowPublicAccess:n=!1}){async function o(){return(await(await fetch(e)).json()).keys}function a(c){return c.status=403,c.body="Forbidden",c}async function s(c){let p=new TextEncoder().encode([c.raw.header,c.raw.payload].join(".")),d=new Uint8Array(Array.from(c.signature).map(m=>m.charCodeAt(0))),f=await o();return(await Promise.all(f.map(async m=>{let w=await crypto.subtle.importKey("jwk",m,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",w,d,p)}))).some(m=>m)}async function i(c,u){if(c.request.method==="OPTIONS"||n)return u(c);if((c.request.headers.authorization||"").toLowerCase().startsWith("bearer")){let d=ns(c.request.headers.authorization.slice(7)),f=new Date(d.payload.exp*1e3),l=new Date(Date.now());return f<=l||!t||d.payload.iss!==t||!r||d.payload.aud!==r||!await s(d)?a(c):(c.state.user=d.payload,u(c))}return a(c)}return i}var Xr=v(M()),os={get:Xr.default},oe=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=os.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 O={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 as(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function Ot({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 oe({accountId:e,namespace:t,authEmail:r,authKey:n,mode:p}),f={...O.mime,...u};return async l=>{let m=A.resolveParams(a,l.params),w=m===""&&i?i:as(m,s),y=await d.get(o+w);!y&&c&&(y=await d.get(o+c)),y?(l.status=200,l.body=y,l.set("Content-Type",f[w.split(".").pop()]||"text/plain")):(l.status=404,l.body=O.http.statusMessages[404],l.set("Content-Type","text/plain"))}}var jr=v(M());var xt={get:jr.default};function ss(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function is(e,t){let r=xt.get(e,"headers.if-none-match"),n=xt.get(t,"metadata.headers.etag");return r?r===n:!1}function Rt({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:ss(c,n),p=await s(t+u);if(!p&&a&&(p=await s(t+a)),p)if(is(i.request,p))i.status=304;else{i.status=p.status,i.body=p.value;let d=xt.get(p,"metadata.headers",{});Object.keys(d).forEach(f=>{i.set(f,d[f])})}else i.status=404,i.body=O.http.statusMessages[404],i.set("Content-Type","text/plain")}}var Zr=v(Fe());function Ut({accessKeyId:e,secretAccessKey:t,region:r,lambdaName:n}){let o=new Zr.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 ln=v(M()),mn=v(Xe());var fn={get:ln.default,set:mn.default};function ii(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function ci(e){return e[Math.floor(Math.random()*e.length)]}function Nt({sources:e=[]}){return async t=>{let r=ci(e),n={method:t.request.method,headers:ii(t.request.headers),redirect:"manual",cf:t.request.cf};if(O.methodsMethodsWithBody.indexOf(t.request.method)!==-1&&fn.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);fn.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 wn=v(M());var Dt={name:"@ahmadissa/cloudworker-proxy",version:"1.1.131",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 ie=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 yn(e,t=".",r=""){return e instanceof Object?Object.keys(e).reduce((n,o)=>e[o]==null?n:{...n,...yn(e[o],t,r+o+t)},{}):r.endsWith(t)?{[r.slice(0,r.length-1)]:e}:{[r]:e}}var je=yn;var He=class{constructor(t){this.url=t.url,this.contentType=t.contentType,this.delimiter=t.delimiter,this.chunker=new ie({sink:this.sendMessage.bind(this),...t})}async log(t){let r=je(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 gn=v(Fe());var Te=class{constructor(t){this.delimiter=t.delimiter,this.chunker=new ie({sink:this.sendMessage.bind(this),...t}),this.awsClient=new gn.AwsClient({accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,region:t.region}),this.streamName=t.streamName,this.region=t.region}async log(t){let r=je(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:wn.default};async function ui(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}function Mt(e){let t;switch(e.type){case"http":t=new He(e);break;case"kinesis":t=new Te(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 ui(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:Dt.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:Dt.version};r.event.waitUntil(t.log(s))}}}var xe=v(An()),Vn=v(M()),zn=v(Xe()),Xn=v(Ln());async function Vt({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 Fn="PBKDF2",zt="AES-GCM",Ni="SHA-256",Di="raw";function Mi(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 Gn(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 $i(e){return new TextEncoder().encode(e).buffer}function qi(e){return new TextDecoder().decode(e)}async function Li(e){let t=new TextEncoder;return crypto.subtle.importKey(Di,t.encode(e),{name:Fn},!1,["deriveKey"])}async function Fi(e,t){let r=await Li(e),o=new TextEncoder().encode(t.replace(/_/g,"/").replace(/-/g,"+"));return crypto.subtle.deriveKey({name:Fn,salt:o,iterations:1e3,hash:{name:Ni}},r,{name:zt,length:256},!0,["encrypt","decrypt"])}async function Gi(){let e=crypto.getRandomValues(new Uint8Array(8));return Gn(e)}async function Bi(e,t){let r=Mi(t),n=r.slice(0,16),o=r.slice(16),a=await crypto.subtle.decrypt({name:zt,iv:n},e,o);return qi(a)}async function Vi(e,t){let r=crypto.getRandomValues(new Uint8Array(16)),n=await crypto.subtle.encrypt({name:zt,iv:r},e,$i(t)),o=new Uint8Array(n.byteLength+r.byteLength);return o.set(r,0),o.set(new Uint8Array(n),r.byteLength),Gn(o)}var de={decrypt:Bi,deriveAesGcmKey:Fi,encrypt:Vi,getSalt:Gi};var fe={get:Vn.default,set:zn.default};function Bn({cookieHeader:e="",cookieName:t}){return xe.default.parse(e)[t]}function zi(e){return Object.keys(e).map(t=>`${t}=${encodeURIComponent(e[t])}`).join("&")}function Xi(e=""){return e.split(",").indexOf("text/html")!==-1}function Xt({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:f=[],oauth2CallbackPath:l="/callback",oauth2CallbackType:m="cookie",oauth2LogoutPath:w="/logout",oauth2LoginPath:y="/login",oauth2ServerTokenPath:g="/oauth/token",oauth2ServerAuthorizePath:T="",oauth2ServerLogoutPath:N}){let U=new oe({accountId:n,namespace:o,authEmail:a,authKey:s,ttl:i}),ee=c,Se=l,dt=m,ut=g,Ne=T,pt=N,V=u,Ee=p,q=d,De=w,C=y,Ce=f.join("%20");async function Me(h,H){let P=`${ee}${ut}`,K=await fetch(P,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:zi({code:h,grant_type:"authorization_code",client_id:V,client_secret:Ee,redirect_uri:H})});if(!K.ok)throw new Error("Authentication failed");let L=await K.json();return{...L,expires:Date.now()+L.expires_in*1e3}}async function _o(h){if(Bn({cookieHeader:h.request.headers.cookie,cookieName:e})){let K=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${K}`,path:"/",maxAge:0}))}let P=wr(h);if(N){let K=encodeURIComponent(`${h.request.protocol}://${h.request.host}${P}`);h.set("Location",`${ee}${pt}?client_id=${V}&returnTo=${K}`)}else h.set("Location",P);h.status=302}async function vo(h){let H=h.request.href.split("?")[0],P=await Me(h.request.query.code,H),K=Xn.default.generate(),L=await de.getSalt(),F=`${K}.${L}`,ht=await de.deriveAesGcmKey(K,L),te=await de.encrypt(ht,JSON.stringify(P));await U.put(K,te);let ft=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.status=302,dt==="query"?h.set("Location",`${h.request.query.state}?auth=${F}`):(h.set("Set-Cookie",xe.default.serialize(e,F,{httpOnly:t,domain:`.${ft}`,path:"/",maxAge:60*60*24*365})),h.set("Location",h.request.query.state))}async function Po(h,H){let[P,K]=H.split("."),L=await U.get(P);if(L){let F=await de.deriveAesGcmKey(P,K),ht=await de.decrypt(F,L),te=JSON.parse(ht);if(te.expires<Date.now()){te=await Vt({refresh_token:te.refresh_token,clientId:V,authDomain:ee,clientSecret:Ee});let ft=await de.encrypt(F,JSON.stringify(te));await U.put(P,ft)}h.state.accessToken=te.access_token,h.state.accessToken&&(h.request.headers.authorization=`bearer ${h.state.accessToken}`)}else{let F=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${F}`,maxAge:0}))}}function wr(h){let H=fe.get(h,"request.query.redirect-to");if(H)return H;let P=fe.get(h,"request.headers.referer");return P||"/"}async function Ho(h){if(h.request.method==="OPTIONS")h.status=200;else{let H=wr(h),P=encodeURIComponent(H||"/"),K=encodeURIComponent(`${h.request.protocol}://${h.request.host}${Se}`);h.status=302,h.set("location",`${ee}${Ne}/authorize?state=${P}&client_id=${V}&response_type=code&scope=${Ce}&audience=${q}&redirect_uri=${K}`)}}async function To(h,H){if(h.request.method==="OPTIONS")await H(h);else if(fe.get(h,"request.headers.authorization","").toLowerCase().startsWith("bearer "))fe.set(h,"state.access_token",h.request.headers.authorization.slice(7)),await H(h);else{let P=fe.get(h,"request.query.auth")||Bn({cookieHeader:h.request.headers.cookie,cookieName:e});if(P&&await Po(h,P),fe.get(h,"state.accessToken")||r)await H(h);else if(Xi(h.request.headers.accept)){let L=encodeURIComponent(h.request.href),F=encodeURIComponent(`${h.request.protocol}://${h.request.host}${Se}`);h.status=302,h.set("location",`${ee}${Ne}/authorize?state=${L}&client_id=${V}&response_type=code&scope=${Ce}&audience=${q}&redirect_uri=${F}`)}else h.status=403,h.body="Forbidden"}}return async(h,H)=>{switch(h.request.path){case Se:await vo(h);break;case De:await _o(h);break;case C:await Ho(h);break;default:await To(h,H)}}}var jn=v(M());var ji={get:jn.default};function Yi(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function jt(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:Yi(n.request.headers),method:n.request.method,redirect:"manual"};if(O.methodsMethodsWithBody.indexOf(n.request.method)!==-1&&ji.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 Yt({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 Yn=v(M()),Zn=v(Xe()),Zt={get:Yn.default,set:Zn.default};function Qt({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=Zt.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=Zt.get(n,p,0);if(["HEAD","OPTIONS"].indexOf(s.request.method)===-1&&(d+=1),Zt.set(n,p,d),r<d){s.status=429;return}a(c),await i(s)}}var Qn=v(Fe());function Zi(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 er({accessKeyId:e,secretAccessKey:t,bucket:r,region:n,endpoint:o,forcePathStyle:a,enableBucketOperations:s=!1}){let i=new Qn.AwsClient({accessKeyId:e,region:n,secretAccessKey:t}),c=Zi(o,{region:n,bucket:r,forcePathStyle:a});return async u=>{if(u.params.file===void 0&&!s){u.status=404,u.body=O.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 f=await i.fetch(p,{method:u.method||u.request.method,headers:d});u.status=f.status,u.body=f.body;let l=A.instanceToJson(f.headers);Object.keys(l).forEach(m=>{u.set(m,l[m])})}}var tr;function eo(e){return new Uint8Array(e.split("").map(r=>r.charCodeAt(0)))}async function Qi(e){return tr||(tr=await crypto.subtle.importKey("raw",eo(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"])),tr}async function ec(e,t){let r=await Qi(t),n=await crypto.subtle.sign({name:"HMAC"},r,eo(e));return btoa(String.fromCharCode.apply(null,new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rr({secret:e}){return async(t,r)=>{let n=(t.request.path+t.request.search).replace(/([?|&]sign=[\w|-]+)/,"");if(await ec(n,e)!==t.query.sign){t.status=403;return}await r(t)}}function nr({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 tc(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=to(u,r),d=s.encode(p);await o.write(d)}await o.close()}function rc(e,t){return e.replace(/{{\$(\d)}}/g,(r,n)=>t[parseInt(n,10)])}function to(e,t){return t.reduce((r,n)=>r.replace(n.regex,(...o)=>rc(n.replace,o)),e)}function or({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=to(a,r);else{let{readable:s,writable:i}=new TransformStream;tc(a,i,r),n.body=s}}}async function nc({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 oc=e=>(e=e.split("?")[0],e.replace(/\W/g,"").slice(0,100));function ar({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=oc(o.request.path);if((await nc({projectID:e,API_KEY:t,token:s,siteKey:r,expectedAction:i})||0)<.5){o.status=409;return}await a(o)}}async function ac({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 sc=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)},Re=(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 sr({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=Re(i,t)||Re(i,"g-recaptcha-token")||null,p=Re(i,"x-recaptcha-action")||sc(o.request?.path||o.request?.url||s.url||"/"),d=Re(i,"cf-connecting-ip")||Re(i,"x-forwarded-for")||void 0,f=await ac({secret:e,token:c,expectedAction:p,remoteip:d});if(!(f.score>=r&&f.ok)){let m={action:f.action,expectedAction:p,score:f.score??0,errors:f.errorCodes??[]};console.warn("[reCAPTCHA] failed:"+JSON.stringify(m)),o.status=409,o.set?.("Content-Type","application/json"),o.body=JSON.stringify({error:"reCAPTCHA verification failed"});return}await a(o)}}var ic=e=>!new RegExp("(\b)(onS+)(s*)=|javascript|<(|/|[^/>][^>]+|/[^>][^>]+)>").test(e),cc=(e,t,r)=>!(!ic(t)||!r[e](t)),dc=e=>!(e===null||typeof e!="object"||Array.isArray(e)&&(!e[0]||typeof e[0]!="object")),tt=(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]=""),dc(e[n])){if(!tt(e[n],t))return console.error("error validating key+validateObject:",n),!1}else if(!cc(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1}return!0},ro=e=>!(e==null||typeof e!="object"),uc=(e,t)=>{let r=e.query;return ro(r)?tt(r,t):!1},ir=(e,t)=>{let r=e.params;return r?ro(r)?tt(r,t):!1:!0};async function pc(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return{};try{let t=await e.text();return JSON.parse(t)}catch{}return{}}function cr({allowedKeys:e}){return async(r,n)=>{if(!e)return r.status=501,!1;if(!ir(r,e)||!uc(r,e))return r.status=422,!1;let o=await pc(r.request);if(!tt(o,e))return r.status=422,!1;await n(r)}}var Ao=v(M());var E=crypto,D=e=>e instanceof CryptoKey;var x=new TextEncoder,W=new TextDecoder,Iu=2**32;function X(...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 no=e=>{let t=e;typeof t=="string"&&(t=x.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(""))},J=e=>no(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var le=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 le{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var k=class extends le{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},j=class extends le{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var rt=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 nt(e,t){return e.name===t}function dr(e){return parseInt(e.name.slice(4),10)}function lc(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function mc(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 ao(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!nt(e.algorithm,"HMAC"))throw B("HMAC");let n=parseInt(t.slice(2),10);if(dr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!nt(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(dr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!nt(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");let n=parseInt(t.slice(2),10);if(dr(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(!nt(e.algorithm,"ECDSA"))throw B("ECDSA");let n=lc(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}mc(e,r)}function so(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 $=(e,...t)=>so("Key must be ",e,...t);function ur(e,t,...r){return so(`Key for the ${e} algorithm must be `,t,...r)}var pr=e=>D(e),b=["CryptoKey"];var Sc=(...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},me=Sc;function Ec(e){return typeof e=="object"&&e!==null}function R(e){if(!Ec(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 ot=(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)},co=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")}},vc=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=co(i);a=u.startsWith("P-")?{name:"ECDH",namedCurve:u}:{name:u},s=c?[]:["deriveBits"];break}case"EdDSA":a={name:co(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)},uo=(e,t,r)=>vc(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r);async function hr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return uo(e,t,r)}var Pc=(e,t)=>{if(!(t instanceof Uint8Array)){if(!pr(t))throw new TypeError(ur(e,t,...b,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${b.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Hc=(e,t,r)=>{if(!pr(t))throw new TypeError(ur(e,t,...b));if(t.type==="secret")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${b.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Tc=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Pc(e,t):Hc(e,t,r)},We=Tc;function Wc(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 ye=Wc;var Mc=Symbol();function at(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 st(e,t,r){if(D(t))return ao(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($(t,...b));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError($(t,...b,"Uint8Array"))}var Q=e=>Math.floor(e.getTime()/1e3);var qc=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,it=e=>{let t=qc.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 Bc=async(e,t,r)=>{let n=await st(e,t,"sign");ot(e,n);let o=await E.subtle.sign(at(e,n.algorithm),n,r);return new Uint8Array(o)},yo=Bc;var ge=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 k("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!me(this._protectedHeader,this._unprotectedHeader))throw new k("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ye(k,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new k('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=n;if(typeof s!="string"||!s)throw new k('JWS "alg" (Algorithm) Header Parameter missing or invalid');We(s,t,"sign");let i=this._payload;a&&(i=x.encode(J(i)));let c;this._protectedHeader?c=x.encode(J(JSON.stringify(this._protectedHeader))):c=x.encode("");let u=X(c,x.encode("."),i),p=await yo(s,t,u),d={signature:J(p),payload:""};return a&&(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 ge(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 we(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Ae=class{constructor(t={}){if(!R(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:we("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:we("setNotBefore",Q(t))}:this._payload={...this._payload,nbf:Q(new Date)+it(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:we("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:we("setExpirationTime",Q(t))}:this._payload={...this._payload,exp:Q(new Date)+it(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Q(new Date)}:t instanceof Date?this._payload={...this._payload,iat:we("setIssuedAt",Q(t))}:this._payload={...this._payload,iat:we("setIssuedAt",t)},this}};var ke=class extends Ae{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new Je(x.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 j("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var jc;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(jc="jose/v5.1.0");var go=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),f={};i=i||d.data,(d.transformRequest||[]).map(function(l){i=l(i,d.headers)||i}),d.auth&&(f.authorization=d.auth),i&&typeof i=="object"&&typeof i.append!="function"&&typeof i.text!="function"&&(i=JSON.stringify(i),f["content-type"]="application/json");try{f[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,f,!0),credentials:d.withCredentials?"include":c}).then(function(l){for(var m in l)typeof l[m]!="function"&&(p[m]=l[m]);return d.responseType=="stream"?(p.data=l.body,p):l[d.responseType||"text"]().then(function(w){p.data=w,p.data=JSON.parse(w)}).catch(Object).then(function(){return(d.validateStatus?d.validateStatus(l.status):l.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 Qc=e=>{if(!e)return!1;let t=JSON.parse(atob(e.split(".")[1])),r=Math.floor(Date.now()/1e3);return t.exp>r-600},ct=async(e,t)=>{let r=await GCP_INVOKER_TOKEN.get(t);if(Qc(r))return r;let n=await hr(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 ke(a).setProtectedHeader({alg:"RS256",typ:"JWT"}).sign(n),i=await go.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 wo={get:Ao.default};function lr({project_id:e,region:t,functionName:r,serviceAccount:n}){return async(o,a)=>{let s=wo.get(o,"request.query",{}),i=new URLSearchParams(s).toString(),c=`https://${t}-${e}.cloudfunctions.net/${r}`,u=`https://${t}-${e}.cloudfunctions.net/${r}${i?`?${i}`:""}`,p=await ct(n,c);o.request.headers["X-Serverless-Authorization"]=`Bearer ${p}`;let d={headers:o.request.headers,method:o.request.method,redirect:"manual"};if(O.methodsMethodsWithBody.indexOf(o.request.method)!==-1&&wo.get(o,"event.request.body")){let m=o.event.request.clone();d.body=m.body}let f=await fetch(u,d);o.body=f.body,o.status=f.status;let l=A.instanceToJson(f.headers);A.mergeHeaders(l,o),await a(o)}}var So=v(M());var ed={get:So.default};function mr({domain:e,serviceAccount:t,allowedKeys:r}){return async(n,o)=>{if(r&&n.params&&!ir(n,r))return n.status=422,n.body=JSON.stringify({error:"Invalid params"}),!1;let a=`${e}${n.request.path}`,s=await ct(t,e),i=new Headers(n.request.headers);i.set("X-Serverless-Authorization",`Bearer ${s}`),i.set("X-Token",i.get("authorization")||"N/A"),i.set("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[l,m]of Object.entries(u))m!==void 0&&i.set(l,m);let p={method:n.request.method,headers:i,redirect:"manual"};if(O.methodsMethodsWithBody.includes(n.request.method)&&ed.get(n,"event.request.body")){let l=n.event.request.clone();p.body=l.body}let d=await fetch(a,p),f=A.instanceToJson(d.headers);n.status=d.status,n.body=await d.text(),A.mergeHeaders(f,n),await o(n)}}function yr({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 td(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return"";try{return await e.text()}catch{return""}}function rd(e){return new TextEncoder().encode(e).length}function Eo(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 gr({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 Eo(t,e,a);let s=await td(t.request),i=typeof s=="string"?rd(s):0;if(i>e)return Eo(t,e,i);await r(t)}}var bo={basicAuth:bt,cache:Pt,cors:Ht,geoDecorator:Tt,jwt:Kt,kvStorage:Ot,kvStorageBinding:Rt,lambda:Ut,loadbalancer:Nt,logger:Mt,oauth2:Xt,origin:jt,rateLimit:Qt,response:Yt,s3:er,signature:rr,split:nr,transform:or,recaptcha:ar,recaptchaV3:sr,userInputValidation:cr,cloudfunction:lr,gcpCloudrun:mr,headers:yr,bodySizeLimit:gr};function nd(e){return t=>{let r=e(t);return async(n,o)=>(n.__upgraded||(vt(n),n.__upgraded=!0),r(n,o))}}module.exports=class{constructor(t=[],r={}){this.router=new Co.default,t.forEach(n=>{let o=r[n.handlerName]||bo[n.handlerName];if(!o)throw new Error(`Handler ${n.handlerName} is not supported`);let a=nd(o);this.router.add(n,a(n.options))})}async resolve(t){return t.cf=t?.request?.cf||{},this.router.resolve(t)}};
8
8
  /*! Bundled license information:
9
9
 
10
10
  aws4fetch/dist/aws4fetch.umd.js: