@ahmadissa/cloudworker-proxy 1.1.136 → 1.1.137
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ An api gateway for cloudflare workers with configurable handlers for:
|
|
|
10
10
|
- Static responses from config or Cloudflare KV-Storage
|
|
11
11
|
- Splitting requests to multiple endpoints
|
|
12
12
|
- Logging (http, kinesis)
|
|
13
|
-
- Authentication (basic, oauth2, signature)
|
|
13
|
+
- Authentication (basic, firestore api key, oauth2, signature)
|
|
14
14
|
- Rate limiting
|
|
15
15
|
- Caching
|
|
16
16
|
- Rewrite
|
|
@@ -174,6 +174,105 @@ config = [{
|
|
|
174
174
|
}];
|
|
175
175
|
```
|
|
176
176
|
|
|
177
|
+
### Firestore API Key
|
|
178
|
+
|
|
179
|
+
Authenticates requests using an API key stored in Firestore.
|
|
180
|
+
|
|
181
|
+
The handler requires a Durable Object binding and uses it for:
|
|
182
|
+
|
|
183
|
+
- caching allowed API keys for `cacheTtl` seconds. Defaults to 3600 seconds
|
|
184
|
+
- caching blocked or missing API keys for `blockedCacheTtl` seconds. Defaults to 3600 seconds
|
|
185
|
+
- caching the Google access token used to read Firestore when `serviceAccount` is used
|
|
186
|
+
|
|
187
|
+
If the API key exists in Firestore, the Firestore document fields are added to the request headers before the request is sent to the backend. Header names are created using the configured `claimsHeaderPrefix`, which defaults to `x-api-key-claim-`.
|
|
188
|
+
|
|
189
|
+
The handler supports the following options:
|
|
190
|
+
|
|
191
|
+
- firestorePath, the Firestore document path prefix or full document template. If the path contains `{apiKey}` it will be replaced, otherwise the encoded API key is appended to the path
|
|
192
|
+
- durableObjectNamespaceBinding, the Durable Object binding name. This is required
|
|
193
|
+
- durableObjectShardCount, optional number of shards used when storing cache records in the Durable Object. Defaults to 64
|
|
194
|
+
- firestoreToken, optional bearer token used to read Firestore directly
|
|
195
|
+
- serviceAccount, optional Google service account object with `client_email` and `private_key`. Use this when `firestoreToken` is not provided
|
|
196
|
+
- apiKeyHeader, the header used to read the API key from the request. Defaults to `x-api-key`
|
|
197
|
+
- apiKeyPrefix, optional prefix for the API key header value. For example `Bearer `
|
|
198
|
+
- claimsHeaderPrefix, prefix for injected backend request headers. Defaults to `x-api-key-claim-`
|
|
199
|
+
- cacheTtl, cache duration in seconds for valid API keys. Defaults to 3600
|
|
200
|
+
- blockedCacheTtl, cache duration in seconds for missing or blocked API keys. Defaults to 3600
|
|
201
|
+
|
|
202
|
+
An example of the configuration for the Firestore API key handler:
|
|
203
|
+
|
|
204
|
+
```js
|
|
205
|
+
const Proxy = require('cloudworker-proxy');
|
|
206
|
+
|
|
207
|
+
const config = [{
|
|
208
|
+
handlerName: 'firestoreApiKey',
|
|
209
|
+
path: '/api/.*',
|
|
210
|
+
options: {
|
|
211
|
+
firestorePath: 'projects/my-project/databases/(default)/documents/apiKeys',
|
|
212
|
+
durableObjectNamespaceBinding: 'API_KEY_CACHE',
|
|
213
|
+
serviceAccount: {
|
|
214
|
+
client_email: process.env.GCP_CLIENT_EMAIL,
|
|
215
|
+
private_key: process.env.GCP_PRIVATE_KEY,
|
|
216
|
+
},
|
|
217
|
+
apiKeyHeader: 'x-api-key',
|
|
218
|
+
claimsHeaderPrefix: 'x-api-key-claim-',
|
|
219
|
+
cacheTtl: 3600,
|
|
220
|
+
blockedCacheTtl: 3600,
|
|
221
|
+
},
|
|
222
|
+
}];
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
If the Firestore document for the API key contains fields like:
|
|
226
|
+
|
|
227
|
+
```json
|
|
228
|
+
{
|
|
229
|
+
"tenantId": "tenant-1",
|
|
230
|
+
"role": "admin",
|
|
231
|
+
"active": true
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
the backend request will receive headers like:
|
|
236
|
+
|
|
237
|
+
```text
|
|
238
|
+
x-api-key-claim-tenant-id: tenant-1
|
|
239
|
+
x-api-key-claim-role: admin
|
|
240
|
+
x-api-key-claim-active: true
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
The worker must also expose the Durable Object class exported by the package:
|
|
244
|
+
|
|
245
|
+
```js
|
|
246
|
+
const Proxy = require('cloudworker-proxy');
|
|
247
|
+
|
|
248
|
+
const proxy = new Proxy(config);
|
|
249
|
+
|
|
250
|
+
export const ApiKeyCacheDurableObject = Proxy.ApiKeyCacheDurableObject;
|
|
251
|
+
|
|
252
|
+
export default {
|
|
253
|
+
async fetch(request, env, ctx) {
|
|
254
|
+
return proxy.resolve({
|
|
255
|
+
request,
|
|
256
|
+
waitUntil: ctx.waitUntil.bind(ctx),
|
|
257
|
+
cf: request.cf,
|
|
258
|
+
env,
|
|
259
|
+
});
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
The Wrangler configuration needs a Durable Object binding and a migration for the `ApiKeyCacheDurableObject` class:
|
|
265
|
+
|
|
266
|
+
```toml
|
|
267
|
+
[[durable_objects.bindings]]
|
|
268
|
+
name = "API_KEY_CACHE"
|
|
269
|
+
class_name = "ApiKeyCacheDurableObject"
|
|
270
|
+
|
|
271
|
+
[[migrations]]
|
|
272
|
+
tag = "v1"
|
|
273
|
+
new_sqlite_classes = [ "ApiKeyCacheDurableObject" ]
|
|
274
|
+
```
|
|
275
|
+
|
|
177
276
|
### Oauth2
|
|
178
277
|
|
|
179
278
|
Logs in using standard oauth2 providers. So far tested with Auth0, AWS Cognito and Patreon but should work with any.
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var Oo=Object.create;var Er=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var Uo=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var _=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Wo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xo(t))!Io.call(e,o)&&o!==r&&Er(e,o,{get:()=>t[o],enumerable:!(n=Ro(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Oo(Uo(e)):{},Wo(t||!e||!e.__esModule?Er(r,"default",{value:e,enumerable:!0}):r,e));var yt=_((id,Cr)=>{function Jo({host:e=".*",path:t=".*",excludePath:r=null,method:n=[".*"],handler:o,protocol:s=".*",handlerName:a,headers:i={},data:c}){let d=[],p=[],u=e.replace(/(:([^.]+))/g,(H,K,O)=>(d.push(O),"([^.]+)")),f=t.replace(/(:([^/]+))/g,(H,K,O)=>O.slice(-1)==="*"?(p.push(O.slice(0,O.length-1)),"(.*)"):(p.push(O),"([^/]*)")),l=new RegExp(`^${u}$`,"i"),m=new RegExp(`^${f}$`,"i"),g=r?new RegExp(`^${r}$`,"i"):null,y=new RegExp(`^${n.join("|")}$`,"i"),w=new RegExp(`^${s}$`,"i");return{hostVariables:d,pathVariables:p,host:l,path:m,excludePath:g,method:y,protocol:w,handler:o,handlerName:a,headers:i,data:c}}function br(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}async function ko(e,t=1024*1024){let r=[],n=e.getReader(),o=new TextDecoder,s=0;for(;t&&s<t;){let{done:i,value:c}=await n.read();if(i)break;s+=c.byteLength,r.push(o.decode(c))}let a=r.join("");return t?a.substring(0,t):a}function No(e){let t=new URL(e.url),r=br(t.searchParams),n=br(e.headers);n.host&&(t.hostname=n.host);let o,s;async function a(i){if(s>=i)return o.substring(0,i);let c=e.clone();return o=await ko(c.body,i),o}return{body:e.body,headers:n,host:t.host,hostname:t.hostname,href:t.href,json:async i=>JSON.parse(a(i)),method:e.method,origin:`${t.protocol}//${t.host}`,path:t.pathname,protocol:t.protocol.slice(0,-1),query:r,querystring:t.search.slice(1),search:t.search,text:async i=>e.headers.get("content-type")==="application/x-www-form-urlencoded"?decodeURIComponent(await a(i)):a(i)}}Cr.exports={parseRoute:Jo,parseRequest:No}});var vr=_((cd,_r)=>{function Do(e,t){let r={},n=t.host.exec(e.host);t.hostVariables.forEach((s,a)=>{r[s]=n[a+1]});let o=t.path.exec(e.path);return t.pathVariables.forEach((s,a)=>{r[s]=o[a+1]}),r}function Mo(e,t){let r=!0;return Object.keys(e.headers).forEach(n=>{t.headers[n]!==e.headers[n]&&(r=!1)}),r}function $o(e,t){return e.protocol.test(t.protocol)}function qo(e,t){return e.method.test(t.method)&&e.host.test(t.host)&&e.path.test(t.path)&&Mo(e,t)&&$o(e,t)&&(!e.excludePath||!e.excludePath.test(t.path))}async function gt(e,t){let[r,...n]=t;if(!r)return new Response("NOT_FOUND",{status:404});if(!qo(r,e.request))return gt(e,n);e.state.handlers=e.state.handlers||[],e.state.handlers.push(r.handlerName||r.handler.name),e.params=Do(e.request,r);try{return r.handler(e,async o=>gt(o,n))}catch(o){throw o.route=r.handler.name,o}}_r.exports={recurseRoutes:gt}});var Hr=_((dd,Pr)=>{Pr.exports={methods:{DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST"},statusMessages:{404:"Not found",429:"Rate limited"}}});var Or=_((ud,Kr)=>{var Lo=yt();Kr.exports=class Tr{constructor(t){this.request=Lo.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 Tr(this.event);return t.cloned=!0,t}}});var xr=_((hd,Rr)=>{var ue=yt(),Fo=vr(),_e=Hr(),Go=Or();Rr.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:s,headers:a,protocol:i},c){let d=ue.parseRoute({method:o,host:t,path:r,excludePath:n,handler:c,headers:a,handlerName:s,protocol:i});this.routes.push(d)}async resolve(t){let r=new Go(t);try{return await Fo.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=_((fd,Gr)=>{var Bo="Expected a function",kr="__lodash_hash_undefined__",Nr=1/0,Vo="[object Function]",Xo="[object GeneratorFunction]",zo="[object Symbol]",jo=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yo=/^\w*$/,Zo=/^\./,Qo=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,es=/[\\^$.*+?()[\]{}|]/g,ts=/\\(\\)?/g,rs=/^\[object .+?Constructor\]$/,ns=typeof global=="object"&&global&&global.Object===Object&&global,os=typeof self=="object"&&self&&self.Object===Object&&self,At=ns||os||Function("return this")();function ss(e,t){return e?.[t]}function as(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var is=Array.prototype,cs=Function.prototype,Dr=Object.prototype,wt=At["__core-js_shared__"],Ur=function(){var e=/[^.]+$/.exec(wt&&wt.keys&&wt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Mr=cs.toString,St=Dr.hasOwnProperty,$r=Dr.toString,ds=RegExp("^"+Mr.call(St).replace(es,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ir=At.Symbol,us=is.splice,ps=qr(At,"Map"),ve=qr(Object,"create"),Wr=Ir?Ir.prototype:void 0,Jr=Wr?Wr.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 hs(){this.__data__=ve?ve(null):{}}function fs(e){return this.has(e)&&delete this.__data__[e]}function ls(e){var t=this.__data__;if(ve){var r=t[e];return r===kr?void 0:r}return St.call(t,e)?t[e]:void 0}function ms(e){var t=this.__data__;return ve?t[e]!==void 0:St.call(t,e)}function ys(e,t){var r=this.__data__;return r[e]=ve&&t===void 0?kr:t,this}re.prototype.clear=hs;re.prototype.delete=fs;re.prototype.get=ls;re.prototype.has=ms;re.prototype.set=ys;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 gs(){this.__data__=[]}function ws(e){var t=this.__data__,r=qe(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():us.call(t,r,1),!0}function As(e){var t=this.__data__,r=qe(t,e);return r<0?void 0:t[r][1]}function Ss(e){return qe(this.__data__,e)>-1}function Es(e,t){var r=this.__data__,n=qe(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}pe.prototype.clear=gs;pe.prototype.delete=ws;pe.prototype.get=As;pe.prototype.has=Ss;pe.prototype.set=Es;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 bs(){this.__data__={hash:new re,map:new(ps||pe),string:new re}}function Cs(e){return Le(this,e).delete(e)}function _s(e){return Le(this,e).get(e)}function vs(e){return Le(this,e).has(e)}function Ps(e,t){return Le(this,e).set(e,t),this}ne.prototype.clear=bs;ne.prototype.delete=Cs;ne.prototype.get=_s;ne.prototype.has=vs;ne.prototype.set=Ps;function qe(e,t){for(var r=e.length;r--;)if(ks(e[r][0],t))return r;return-1}function Hs(e,t){t=Rs(t,e)?[t]:Os(t);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Ws(t[r++])];return r&&r==n?e:void 0}function Ts(e){if(!Fr(e)||Us(e))return!1;var t=Ns(e)||as(e)?ds:rs;return t.test(Js(e))}function Ks(e){if(typeof e=="string")return e;if(bt(e))return Jr?Jr.call(e):"";var t=e+"";return t=="0"&&1/e==-Nr?"-0":t}function Os(e){return Lr(e)?e:Is(e)}function Le(e,t){var r=e.__data__;return xs(t)?r[typeof t=="string"?"string":"hash"]:r.map}function qr(e,t){var r=ss(e,t);return Ts(r)?r:void 0}function Rs(e,t){if(Lr(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||bt(e)?!0:Yo.test(e)||!jo.test(e)||t!=null&&e in Object(t)}function xs(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Us(e){return!!Ur&&Ur in e}var Is=Et(function(e){e=Ms(e);var t=[];return Zo.test(e)&&t.push(""),e.replace(Qo,function(r,n,o,s){t.push(o?s.replace(ts,"$1"):n||r)}),t});function Ws(e){if(typeof e=="string"||bt(e))return e;var t=e+"";return t=="0"&&1/e==-Nr?"-0":t}function Js(e){if(e!=null){try{return Mr.call(e)}catch{}try{return e+""}catch{}}return""}function Et(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(Bo);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],s=r.cache;if(s.has(o))return s.get(o);var a=e.apply(this,n);return r.cache=s.set(o,a),a};return r.cache=new(Et.Cache||ne),r}Et.Cache=ne;function ks(e,t){return e===t||e!==e&&t!==t}var Lr=Array.isArray;function Ns(e){var t=Fr(e)?$r.call(e):"";return t==Vo||t==Xo}function Fr(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Ds(e){return!!e&&typeof e=="object"}function bt(e){return typeof e=="symbol"||Ds(e)&&$r.call(e)==zo}function Ms(e){return e==null?"":Ks(e)}function $s(e,t,r){var n=e==null?void 0:Hs(e,t);return n===void 0?r:n}Gr.exports=$s});var Ge=_((Fe,Qr)=>{(function(e,t){typeof Fe=="object"&&typeof Qr<"u"?t(Fe):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.aws4fetch={}))})(Fe,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:g,region:y,cache:w,retries:H,initRetryMs:K}){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=g,this.region=y,this.cache=w||new Map,this.retries=H??10,this.initRetryMs=K||50}async sign(f,l){if(f instanceof Request){let{method:y,url:w,headers:H,body:K}=f;l=Object.assign({method:y,url:w,headers:H},l),l.body==null&&H.has("Content-Type")&&(l.body=K!=null&&H.has("X-Amz-Content-Sha256")?K:await f.clone().arrayBuffer()),f=w}let m=new s(Object.assign({url:f},l,this,l&&l.aws)),g=Object.assign({},l,await m.sign());return delete g.aws,new Request(g.url.toString(),g)}async fetch(f,l){for(let m=0;m<=this.retries;m++){let g=fetch(await this.sign(f,l));if(m===this.retries)return g;let y=await g;if(y.status<500&&y.status!==429)return y;await new Promise(w=>setTimeout(w,Math.random()*this.initRetryMs*Math.pow(2,m)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class s{constructor({method:f,url:l,headers:m,body:g,accessKeyId:y,secretAccessKey:w,sessionToken:H,service:K,region:O,cache:ee,datetime:Se,signQuery:pt,appendSessionToken:ht,allHeaders:De,singleEncode:ft}){if(l==null)throw new TypeError("url is a required option");if(y==null)throw new TypeError("accessKeyId is a required option");if(w==null)throw new TypeError("secretAccessKey is a required option");this.method=f||(g?"POST":"GET"),this.url=new URL(l),this.headers=new Headers(m||{}),this.body=g,this.accessKeyId=y,this.secretAccessKey=w,this.sessionToken=H;let V,Ee;(!K||!O)&&([V,Ee]=p(this.url,this.headers)),this.service=K||V||"",this.region=O||Ee||"us-east-1",this.cache=ee||new Map,this.datetime=Se||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=pt,this.appendSessionToken=ht||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=>De||!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
|
-
`),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,"/");
|
|
1
|
+
"use strict";var Fo=Object.create;var Rr=Object.defineProperty;var Lo=Object.getOwnPropertyDescriptor;var Go=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var jo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Go(t))!Vo.call(e,o)&&o!==r&&Rr(e,o,{get:()=>t[o],enumerable:!(n=Lo(t,o))||n.enumerable});return e};var P=(e,t,r)=>(r=e!=null?Fo(Bo(e)):{},jo(t||!e||!e.__esModule?Rr(r,"default",{value:e,enumerable:!0}):r,e));var wt=v((Du,Ur)=>{function zo({host:e=".*",path:t=".*",excludePath:r=null,method:n=[".*"],handler:o,protocol:a=".*",handlerName:s,headers:i={},data:c}){let u=[],h=[],d=e.replace(/(:([^.]+))/g,(b,K,O)=>(u.push(O),"([^.]+)")),l=t.replace(/(:([^/]+))/g,(b,K,O)=>O.slice(-1)==="*"?(h.push(O.slice(0,O.length-1)),"(.*)"):(h.push(O),"([^/]*)")),f=new RegExp(`^${d}$`,"i"),p=new RegExp(`^${l}$`,"i"),g=r?new RegExp(`^${r}$`,"i"):null,y=new RegExp(`^${n.join("|")}$`,"i"),w=new RegExp(`^${a}$`,"i");return{hostVariables:u,pathVariables:h,host:f,path:p,excludePath:g,method:y,protocol:w,handler:o,handlerName:s,headers:i,data:c}}function xr(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}async function Xo(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 Yo(e){let t=new URL(e.url),r=xr(t.searchParams),n=xr(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 Xo(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)}}Ur.exports={parseRoute:zo,parseRequest:Yo}});var Ir=v(($u,kr)=>{function Zo(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 Qo(e,t){let r=!0;return Object.keys(e.headers).forEach(n=>{t.headers[n]!==e.headers[n]&&(r=!1)}),r}function ea(e,t){return e.protocol.test(t.protocol)}function ta(e,t){return e.method.test(t.method)&&e.host.test(t.host)&&e.path.test(t.path)&&Qo(e,t)&&ea(e,t)&&(!e.excludePath||!e.excludePath.test(t.path))}async function At(e,t){let[r,...n]=t;if(!r)return new Response("NOT_FOUND",{status:404});if(!ta(r,e.request))return At(e,n);e.state.handlers=e.state.handlers||[],e.state.handlers.push(r.handlerName||r.handler.name),e.params=Zo(e.request,r);try{return r.handler(e,async o=>At(o,n))}catch(o){throw o.route=r.handler.name,o}}kr.exports={recurseRoutes:At}});var Nr=v((Mu,Wr)=>{Wr.exports={methods:{DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST"},statusMessages:{404:"Not found",429:"Rate limited"}}});var $r=v((qu,Dr)=>{var ra=wt();Dr.exports=class Jr{constructor(t){this.request=ra.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 Jr(this.event);return t.cloned=!0,t}}});var qr=v((Lu,Mr)=>{var pe=wt(),na=Ir(),ve=Nr(),oa=$r();Mr.exports=class{constructor(){this.routes=[]}get(t,r){let n=pe.parseRoute({method:[ve.methods.GET,ve.methods.HEAD],path:t,handler:r});this.routes.push(n)}post(t,r){let n=pe.parseRoute({method:[ve.methods.POST],path:t,handler:r});this.routes.push(n)}patch(t,r){let n=pe.parseRoute({method:[ve.methods.PATCH],path:t,handler:r});this.routes.push(n)}del(t,r){let n=pe.parseRoute({method:[ve.methods.DELETE],path:t,handler:r});this.routes.push(n)}use(t){let r=pe.parseRoute({handler:t,middleware:!0});this.routes.push(r)}add({host:t,path:r,excludePath:n,method:o,handlerName:a,headers:s,protocol:i},c){let u=pe.parseRoute({method:o,host:t,path:r,excludePath:n,handler:c,headers:s,handlerName:a,protocol:i});this.routes.push(u)}async resolve(t){let r=new oa(t);try{return await na.recurseRoutes(r,this.routes),new Response(r.body,{status:r.status,headers:r.response.headers})}catch(n){return new Response(n.message,{status:500})}}}});var $=v((Gu,tn)=>{var aa="Expected a function",Vr="__lodash_hash_undefined__",jr=1/0,sa="[object Function]",ia="[object GeneratorFunction]",ca="[object Symbol]",ua=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,da=/^\w*$/,pa=/^\./,ha=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,la=/[\\^$.*+?()[\]{}|]/g,fa=/\\(\\)?/g,ma=/^\[object .+?Constructor\]$/,ya=typeof global=="object"&&global&&global.Object===Object&&global,ga=typeof self=="object"&&self&&self.Object===Object&&self,bt=ya||ga||Function("return this")();function wa(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,ba=Function.prototype,zr=Object.prototype,St=bt["__core-js_shared__"],Fr=function(){var e=/[^.]+$/.exec(St&&St.keys&&St.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Xr=ba.toString,Et=zr.hasOwnProperty,Yr=zr.toString,Ea=RegExp("^"+Xr.call(Et).replace(la,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Lr=bt.Symbol,Ca=Sa.splice,_a=Zr(bt,"Map"),Pe=Zr(Object,"create"),Gr=Lr?Lr.prototype:void 0,Br=Gr?Gr.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 va(){this.__data__=Pe?Pe(null):{}}function Pa(e){return this.has(e)&&delete this.__data__[e]}function Ta(e){var t=this.__data__;if(Pe){var r=t[e];return r===Vr?void 0:r}return Et.call(t,e)?t[e]:void 0}function Ha(e){var t=this.__data__;return Pe?t[e]!==void 0:Et.call(t,e)}function Ka(e,t){var r=this.__data__;return r[e]=Pe&&t===void 0?Vr:t,this}re.prototype.clear=va;re.prototype.delete=Pa;re.prototype.get=Ta;re.prototype.has=Ha;re.prototype.set=Ka;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 Oa(){this.__data__=[]}function Ra(e){var t=this.__data__,r=Le(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Ca.call(t,r,1),!0}function xa(e){var t=this.__data__,r=Le(t,e);return r<0?void 0:t[r][1]}function Ua(e){return Le(this.__data__,e)>-1}function ka(e,t){var r=this.__data__,n=Le(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}he.prototype.clear=Oa;he.prototype.delete=Ra;he.prototype.get=xa;he.prototype.has=Ua;he.prototype.set=ka;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 Ia(){this.__data__={hash:new re,map:new(_a||he),string:new re}}function Wa(e){return Ge(this,e).delete(e)}function Na(e){return Ge(this,e).get(e)}function Ja(e){return Ge(this,e).has(e)}function Da(e,t){return Ge(this,e).set(e,t),this}ne.prototype.clear=Ia;ne.prototype.delete=Wa;ne.prototype.get=Na;ne.prototype.has=Ja;ne.prototype.set=Da;function Le(e,t){for(var r=e.length;r--;)if(Xa(e[r][0],t))return r;return-1}function $a(e,t){t=La(t,e)?[t]:Fa(t);for(var r=0,n=t.length;e!=null&&r<n;)e=e[ja(t[r++])];return r&&r==n?e:void 0}function Ma(e){if(!en(e)||Ba(e))return!1;var t=Ya(e)||Aa(e)?Ea:ma;return t.test(za(e))}function qa(e){if(typeof e=="string")return e;if(_t(e))return Br?Br.call(e):"";var t=e+"";return t=="0"&&1/e==-jr?"-0":t}function Fa(e){return Qr(e)?e:Va(e)}function Ge(e,t){var r=e.__data__;return Ga(t)?r[typeof t=="string"?"string":"hash"]:r.map}function Zr(e,t){var r=wa(e,t);return Ma(r)?r:void 0}function La(e,t){if(Qr(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||_t(e)?!0:da.test(e)||!ua.test(e)||t!=null&&e in Object(t)}function Ga(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ba(e){return!!Fr&&Fr in e}var Va=Ct(function(e){e=Qa(e);var t=[];return pa.test(e)&&t.push(""),e.replace(ha,function(r,n,o,a){t.push(o?a.replace(fa,"$1"):n||r)}),t});function ja(e){if(typeof e=="string"||_t(e))return e;var t=e+"";return t=="0"&&1/e==-jr?"-0":t}function za(e){if(e!=null){try{return Xr.call(e)}catch{}try{return e+""}catch{}}return""}function Ct(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(aa);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(Ct.Cache||ne),r}Ct.Cache=ne;function Xa(e,t){return e===t||e!==e&&t!==t}var Qr=Array.isArray;function Ya(e){var t=en(e)?Yr.call(e):"";return t==sa||t==ia}function en(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Za(e){return!!e&&typeof e=="object"}function _t(e){return typeof e=="symbol"||Za(e)&&Yr.call(e)==ca}function Qa(e){return e==null?"":qa(e)}function es(e,t,r){var n=e==null?void 0:$a(e,t);return n===void 0?r:n}tn.exports=es});var Ve=v((Be,ln)=>{(function(e,t){typeof Be=="object"&&typeof ln<"u"?t(Be):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.aws4fetch={}))})(Be,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:l,secretAccessKey:f,sessionToken:p,service:g,region:y,cache:w,retries:b,initRetryMs:K}){if(l==null)throw new TypeError("accessKeyId is a required option");if(f==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=l,this.secretAccessKey=f,this.sessionToken=p,this.service=g,this.region=y,this.cache=w||new Map,this.retries=b??10,this.initRetryMs=K||50}async sign(l,f){if(l instanceof Request){let{method:y,url:w,headers:b,body:K}=l;f=Object.assign({method:y,url:w,headers:b},f),f.body==null&&b.has("Content-Type")&&(f.body=K!=null&&b.has("X-Amz-Content-Sha256")?K:await l.clone().arrayBuffer()),l=w}let p=new a(Object.assign({url:l},f,this,f&&f.aws)),g=Object.assign({},f,await p.sign());return delete g.aws,new Request(g.url.toString(),g)}async fetch(l,f){for(let p=0;p<=this.retries;p++){let g=fetch(await this.sign(l,f));if(p===this.retries)return g;let y=await g;if(y.status<500&&y.status!==429)return y;await new Promise(w=>setTimeout(w,Math.random()*this.initRetryMs*Math.pow(2,p)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class a{constructor({method:l,url:f,headers:p,body:g,accessKeyId:y,secretAccessKey:w,sessionToken:b,service:K,region:O,cache:ee,datetime:be,signQuery:lt,appendSessionToken:ft,allHeaders:Me,singleEncode:mt}){if(f==null)throw new TypeError("url is a required option");if(y==null)throw new TypeError("accessKeyId is a required option");if(w==null)throw new TypeError("secretAccessKey is a required option");this.method=l||(g?"POST":"GET"),this.url=new URL(f),this.headers=new Headers(p||{}),this.body=g,this.accessKeyId=y,this.secretAccessKey=w,this.sessionToken=b;let V,Ee;(!K||!O)&&([V,Ee]=h(this.url,this.headers)),this.service=K||V||"",this.region=O||Ee||"us-east-1",this.cache=ee||new Map,this.datetime=be||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=lt,this.appendSessionToken=ft||this.service==="iotdevicegateway",this.headers.delete("Host");let q=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),q.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&q.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>Me||!n.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
|
|
2
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!q.has("X-Amz-Expires")&&q.set("X-Amz-Expires","86400"),q.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),q.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),q.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");mt||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=u(this.encodedPath);let qe=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if(qe.has(_))return!1;qe.add(_)}return!0}).map(_=>_.map(Ce=>u(encodeURIComponent(Ce)))).sort(([_,Ce],[_e,Fe])=>_<_e?-1:_>_e?1:Ce<Fe?-1:Ce>Fe?1:0).map(_=>_.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let l=this.datetime.slice(0,8),f=[this.secretAccessKey,l,this.region,this.service].join(),p=this.cache.get(f);if(!p){let g=await s("AWS4"+this.secretAccessKey,l),y=await s(g,this.region),w=await s(y,this.service);p=await s(w,"aws4_request"),this.cache.set(f,p)}return c(await s(p,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 a(u,f){let l=await crypto.subtle.importKey("raw",typeof u=="string"?t.encode(u):u,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",l,t.encode(f))}async function i(u){return crypto.subtle.digest("SHA-256",typeof u=="string"?t.encode(u):u)}function c(u){return Array.prototype.map.call(new Uint8Array(u),f=>("0"+f.toString(16)).slice(-2)).join("")}function d(u){return u.replace(/[!'()*]/g,f=>"%"+f.charCodeAt(0).toString(16).toUpperCase())}function p(u,f){let{hostname:l,pathname:m}=u,g=l.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[y,w]=(g||["",""]).slice(1,3);if(w==="us-gov")w="us-gov-west-1";else if(w==="s3"||w==="s3-accelerate")w="us-east-1",y="s3";else if(y==="iot")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 H=(f.get("X-Amz-Target")||"").split(".")[0];H==="AnyScaleFrontendService"?y="application-autoscaling":H==="AnyScaleScalingPlannerFrontendService"&&(y="autoscaling-plans")}else w==null&&y.startsWith("s3-")?(w=y.slice(3).replace(/^fips-|^external-1/,""),y="s3"):y.endsWith("-fips")?y=y.slice(0,-5):w&&/-\d$/.test(y)&&!/-\d$/.test(w)&&([y,w]=[w,y]);return[r[y]||y,w]}e.AwsClient=o,e.AwsV4Signer=s,Object.defineProperty(e,"__esModule",{value:!0})})});var je=_((Jd,ln)=>{var da="Expected a function",sn="__lodash_hash_undefined__",an=1/0,ua=9007199254740991,pa="[object Function]",ha="[object GeneratorFunction]",fa="[object Symbol]",la=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ma=/^\w*$/,ya=/^\./,ga=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,wa=/[\\^$.*+?()[\]{}|]/g,Aa=/\\(\\)?/g,Sa=/^\[object .+?Constructor\]$/,Ea=/^(?:0|[1-9]\d*)$/,ba=typeof global=="object"&&global&&global.Object===Object&&global,Ca=typeof self=="object"&&self&&self.Object===Object&&self,kt=ba||Ca||Function("return this")();function _a(e,t){return e?.[t]}function va(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var Pa=Array.prototype,Ha=Function.prototype,cn=Object.prototype,Jt=kt["__core-js_shared__"],tn=function(){var e=/[^.]+$/.exec(Jt&&Jt.keys&&Jt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),dn=Ha.toString,Ve=cn.hasOwnProperty,un=cn.toString,Ta=RegExp("^"+dn.call(Ve).replace(wa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),rn=kt.Symbol,Ka=Pa.splice,Oa=pn(kt,"Map"),Pe=pn(Object,"create"),nn=rn?rn.prototype:void 0,on=nn?nn.toString:void 0;function se(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ra(){this.__data__=Pe?Pe(null):{}}function xa(e){return this.has(e)&&delete this.__data__[e]}function Ua(e){var t=this.__data__;if(Pe){var r=t[e];return r===sn?void 0:r}return Ve.call(t,e)?t[e]:void 0}function Ia(e){var t=this.__data__;return Pe?t[e]!==void 0:Ve.call(t,e)}function Wa(e,t){var r=this.__data__;return r[e]=Pe&&t===void 0?sn:t,this}se.prototype.clear=Ra;se.prototype.delete=xa;se.prototype.get=Ua;se.prototype.has=Ia;se.prototype.set=Wa;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 Ja(){this.__data__=[]}function ka(e){var t=this.__data__,r=Xe(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Ka.call(t,r,1),!0}function Na(e){var t=this.__data__,r=Xe(t,e);return r<0?void 0:t[r][1]}function Da(e){return Xe(this.__data__,e)>-1}function Ma(e,t){var r=this.__data__,n=Xe(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}he.prototype.clear=Ja;he.prototype.delete=ka;he.prototype.get=Na;he.prototype.has=Da;he.prototype.set=Ma;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 $a(){this.__data__={hash:new se,map:new(Oa||he),string:new se}}function qa(e){return ze(this,e).delete(e)}function La(e){return ze(this,e).get(e)}function Fa(e){return ze(this,e).has(e)}function Ga(e,t){return ze(this,e).set(e,t),this}ae.prototype.clear=$a;ae.prototype.delete=qa;ae.prototype.get=La;ae.prototype.has=Fa;ae.prototype.set=Ga;function Ba(e,t,r){var n=e[t];(!(Ve.call(e,t)&&hn(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function Xe(e,t){for(var r=e.length;r--;)if(hn(e[r][0],t))return r;return-1}function Va(e){if(!Be(e)||ei(e))return!1;var t=oi(e)||va(e)?Ta:Sa;return t.test(ni(e))}function Xa(e,t,r,n){if(!Be(e))return e;t=Za(t,e)?[t]:ja(t);for(var o=-1,s=t.length,a=s-1,i=e;i!=null&&++o<s;){var c=ri(t[o]),d=r;if(o!=a){var p=i[c];d=n?n(p,c,i):void 0,d===void 0&&(d=Be(p)?p:Ya(t[o+1])?[]:{})}Ba(i,c,d),i=i[c]}return e}function za(e){if(typeof e=="string")return e;if(Dt(e))return on?on.call(e):"";var t=e+"";return t=="0"&&1/e==-an?"-0":t}function ja(e){return fn(e)?e:ti(e)}function ze(e,t){var r=e.__data__;return Qa(t)?r[typeof t=="string"?"string":"hash"]:r.map}function pn(e,t){var r=_a(e,t);return Va(r)?r:void 0}function Ya(e,t){return t=t??ua,!!t&&(typeof e=="number"||Ea.test(e))&&e>-1&&e%1==0&&e<t}function Za(e,t){if(fn(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||Dt(e)?!0:ma.test(e)||!la.test(e)||t!=null&&e in Object(t)}function Qa(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function ei(e){return!!tn&&tn in e}var ti=Nt(function(e){e=ai(e);var t=[];return ya.test(e)&&t.push(""),e.replace(ga,function(r,n,o,s){t.push(o?s.replace(Aa,"$1"):n||r)}),t});function ri(e){if(typeof e=="string"||Dt(e))return e;var t=e+"";return t=="0"&&1/e==-an?"-0":t}function ni(e){if(e!=null){try{return dn.call(e)}catch{}try{return e+""}catch{}}return""}function Nt(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(da);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],s=r.cache;if(s.has(o))return s.get(o);var a=e.apply(this,n);return r.cache=s.set(o,a),a};return r.cache=new(Nt.Cache||ae),r}Nt.Cache=ae;function hn(e,t){return e===t||e!==e&&t!==t}var fn=Array.isArray;function oi(e){var t=Be(e)?un.call(e):"";return t==pa||t==ha}function Be(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function si(e){return!!e&&typeof e=="object"}function Dt(e){return typeof e=="symbol"||si(e)&&un.call(e)==fa}function ai(e){return e==null?"":za(e)}function ii(e,t,r){return e==null?e:Xa(e,t,r)}ln.exports=ii});var En=_(Lt=>{"use strict";Lt.parse=mi;Lt.serialize=yi;var hi=decodeURIComponent,fi=encodeURIComponent,li=/; */,Ze=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function mi(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");for(var r={},n=t||{},o=e.split(li),s=n.decode||hi,a=0;a<o.length;a++){var i=o[a],c=i.indexOf("=");if(!(c<0)){var d=i.substr(0,c).trim(),p=i.substr(++c,i.length).trim();p[0]=='"'&&(p=p.slice(1,-1)),r[d]==null&&(r[d]=gi(p,s))}}return r}function yi(e,t,r){var n=r||{},o=n.encode||fi;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Ze.test(e))throw new TypeError("argument name is invalid");var s=o(t);if(s&&!Ze.test(s))throw new TypeError("argument val is invalid");var a=e+"="+s;if(n.maxAge!=null){var i=n.maxAge-0;if(isNaN(i)||!isFinite(i))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(i)}if(n.domain){if(!Ze.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!Ze.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.sameSite){var c=typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite;switch(c){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function gi(e,t){try{return t(e)}catch{return e}}});var Cn=_((eu,bn)=>{"use strict";var Qe=1;function wi(){return Qe=(Qe*9301+49297)%233280,Qe/233280}function Ai(e){Qe=e}bn.exports={nextValue:wi,seed:Ai}});var Oe=_((tu,Hn)=>{"use strict";var Ft=Cn(),ce="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",X,_n,Ke;function Gt(){Ke=!1}function vn(e){if(!e){X!==ce&&(X=ce,Gt());return}if(e!==X){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(", "));X=e,Gt()}}function Si(e){return vn(e),X}function Ei(e){Ft.seed(e),_n!==e&&(Gt(),_n=e)}function bi(){X||vn(ce);for(var e=X.split(""),t=[],r=Ft.nextValue(),n;e.length>0;)r=Ft.nextValue(),n=Math.floor(r*e.length),t.push(e.splice(n,1)[0]);return t.join("")}function Pn(){return Ke||(Ke=bi(),Ke)}function Ci(e){var t=Pn();return t[e]}function _i(){return X||ce}Hn.exports={get:_i,characters:Si,seed:Ei,lookup:Ci,shuffled:Pn}});var Kn=_((ru,Tn)=>{"use strict";var Bt=typeof window=="object"&&(window.crypto||window.msCrypto),Vt;!Bt||!Bt.getRandomValues?Vt=function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(Math.random()*256));return t}:Vt=function(e){return Bt.getRandomValues(new Uint8Array(e))};Tn.exports=Vt});var Rn=_((nu,On)=>{On.exports=function(e,t,r){for(var n=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*n*r/t.length),s="";;)for(var a=e(o),i=o;i--;)if(s+=t[a[i]&n]||"",s.length===+r)return s}});var Un=_((ou,xn)=>{"use strict";var vi=Oe(),Pi=Kn(),Hi=Rn();function Ti(e){for(var t=0,r,n="";!r;)n=n+Hi(Pi,vi.get(),1),r=e<Math.pow(16,t+1),t++;return n}xn.exports=Ti});var Jn=_((au,Wn)=>{"use strict";var et=Un(),su=Oe(),Ki=1567752802062,Oi=7,tt,In;function Ri(e){var t="",r=Math.floor((Date.now()-Ki)*.001);return r===In?tt++:(tt=0,In=r),t=t+et(Oi),t=t+et(e),tt>0&&(t=t+et(tt)),t=t+et(r),t}Wn.exports=Ri});var Nn=_((iu,kn)=>{"use strict";var xi=Oe();function Ui(e){if(!e||typeof e!="string"||e.length<6)return!1;var t=new RegExp("[^"+xi.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]");return!t.test(e)}kn.exports=Ui});var Mn=_((cu,Dn)=>{"use strict";Dn.exports=0});var Ln=_((du,G)=>{"use strict";var Xt=Oe(),Ii=Jn(),Wi=Nn(),$n=Mn()||0;function Ji(e){return Xt.seed(e),G.exports}function ki(e){return $n=e,G.exports}function Ni(e){return e!==void 0&&Xt.characters(e),Xt.shuffled()}function qn(){return Ii($n)}G.exports=qn;G.exports.generate=qn;G.exports.seed=Ji;G.exports.worker=ki;G.exports.characters=Ni;G.exports.isValid=Wi});var Gn=_((uu,Fn)=>{"use strict";Fn.exports=Ln()});var _o=v(xr());var Br=v(M()),qs={get:Br.default};function Ct(e){e.status=401,e.body="Unauthorized",e.set("WWW-Authenticate","Basic")}function _t(e){return async(t,r)=>{if(t.request.path===e.logoutPath)return Ct(t);let n=qs.get(t,"request.headers.authorization");if(!n||!n.startsWith("Basic "))return Ct(t);let o=e.users.map(i=>i.authToken),s=n.substring(6),a=o.indexOf(s);return a===-1?Ct(t):(t.state.user=e.users[a].username,r(t))}}var Vr=caches.default;async function Ls(e){return await Vr.match(e)}async function Fs(e,t){return Vr.put(e.href,t)}var vt={get:Ls,set:Fs};async function Gs(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}var Xr=Gs;function Bs(e,t={}){return Object.keys(t).reduce((r,n)=>r.replace(`{${n}}`,t[n]),e)}function Pt(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}function Vs(e,t){Object.entries(e).forEach(([r,n])=>{t.header(r)||t.set(r,n)})}var Ht=e=>{e.set=(t,r)=>{e.response.headers[t.toLowerCase()]=r},e.header=t=>e.request.headers[t.toLowerCase()]},A={resolveParams:Bs,instanceToJson:Pt,mergeHeaders:Vs,upgradeCTX:Ht};var Xs=["x-ratelimit-count","x-ratelimit-limit","x-ratelimit-reset","x-cache-hit"];async function zs(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}async function js(e,t){if(!t)return e.event.request;let r=t.match(/{.*?}/gi).map(s=>s.slice(1,-1)),n={};for(let s=0;s<r.length;s+=1){let a=r[s],i=a.split(":");switch(i[0]){case"method":n[a]=e.request.method;break;case"path":n[a]=e.request.path;break;case"bodyHash":n[a]=await Xr(await zs(e.request));break;case"header":n[a]=e.request.headers[i[1]]||"";break;default:n[a]=a}}let o=encodeURIComponent(t.replace(/({(.*?)})/gi,(s,a,i)=>n[i]));return new Request(`http://${e.request.hostname}/${o}`)}function Tt({cacheDuration:e,cacheKeyTemplate:t,headerBlacklist:r=Xs}){return async(n,o)=>{let s=await js(n,t),a=await vt.get(s);if(a){n.body=a.body,n.status=a.status;let i=Pt(a.headers);Object.keys(i).forEach(c=>{n.set(c,i[c])}),n.set("X-Cache-Hit",!0)}else{await o(n);let i;n.body.tee?[n.body,i]=n.body.tee():i=n.body;let c=new Response(i,{status:n.status});Object.keys(n.response.headers).forEach(d=>{r.indexOf(d.toLowerCase())===-1&&c.headers.set(d,n.response.headers[d])}),e&&(c.headers.delete("Cache-Control"),c.headers.set("Cache-Control",`max-age=${e}`)),n.event.waitUntil(vt.set(s,c))}}}function Kt({allowedOrigins:e=["*"],allowedMethods:t=["GET","PUT","POST","PATCH","DELETE","HEAD","OPTIONS"],allowCredentials:r=!0,allowedHeaders:n=["Content-Type"],allowedExposeHeaders:o=[],maxAge:s=600,optionsSuccessStatus:a=204,terminatePreflight:i=!1}){return async(c,d)=>{let{method:p}=c.request,{origin:u}=c.request.headers,f=c.request.headers["access-control-request-headers"];if(Ys(c,u,e),Zs(c,r),ra(c,o),!t.includes(p.toUpperCase())){c.status=405,c.body={error:`Method ${p} not allowed`};return}if(p==="OPTIONS"&&(Qs(c,t),ea(c,f,n),ta(c,s),i)){c.status=a,c.set("content-length","0"),c.body="";return}await d(c)}}function Ys(e,t,r){if(Array.isArray(r)){if(r[0]==="origin"){e.set("Access-Control-Allow-Origin",t),zr(e,"Origin");return}r[0]==="*"?e.set("Access-Control-Allow-Origin","*"):r.indexOf(t)!==-1&&(e.set("Access-Control-Allow-Origin",t),zr(e,"Origin"))}}function Zs(e,t){t&&e.set("Access-Control-Allow-Credentials",String(t))}function Qs(e,t){e.set("Access-Control-Allow-Methods",t.join(","))}function ea(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 ta(e,t){t&&e.set("Access-Control-Max-Age",String(t))}function ra(e,t){t.length&&e.set("Access-Control-Expose-Headers",t.join(","))}function zr(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 na={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 Ot(){return async(e,t)=>{let r=e.request.headers["cf-ipcountry"]||"XX";e.request.headers["proxy-continent"]=na[r],await t(e)}}function jr(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 oa(e){let t=e.split("."),r=JSON.parse(jr(t[0])),n=JSON.parse(jr(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 Rt({jwksUri:e,iss:t,aud:r,allowPublicAccess:n=!1}){async function o(){return(await(await fetch(e)).json()).keys}function s(c){return c.status=403,c.body="Forbidden",c}async function a(c){let p=new TextEncoder().encode([c.raw.header,c.raw.payload].join(".")),u=new Uint8Array(Array.from(c.signature).map(m=>m.charCodeAt(0))),f=await o();return(await Promise.all(f.map(async m=>{let g=await crypto.subtle.importKey("jwk",m,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",g,u,p)}))).some(m=>m)}async function i(c,d){if(c.request.method==="OPTIONS"||n)return d(c);if((c.request.headers.authorization||"").toLowerCase().startsWith("bearer")){let u=oa(c.request.headers.authorization.slice(7)),f=new Date(u.payload.exp*1e3),l=new Date(Date.now());return f<=l||!t||u.payload.iss!==t||!r||u.payload.aud!==r||!await a(u)?s(c):(c.state.user=u.payload,d(c))}return s(c)}return i}var Yr=v(M()),sa={get:Yr.default},oe=class{constructor({accountId:t,namespace:r,authEmail:n,authKey:o,ttl:s}){this.accountId=t,this.namespace=r,this.authEmail=n,this.authKey=o,this.ttl=s}getNamespaceUrl(){return new URL(`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/storage/kv/namespaces/${this.namespace}`)}getUrlForKey(t){return new URL(`${this.getNamespaceUrl()}/values/${t}`)}async list(t,r=10){let n=`${this.getNamespaceUrl()}/keys?prefix=${t}&limit=${r}`,o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});return o.ok?o.json():null}async get(t,r){let n=this.getUrlForKey(t),o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});if(o.ok)switch(r){case"json":return o.json();case"stream":return o;case"arrayBuffer":return o.arrayBuffer();default:return o.text()}return null}async getWithMetadata(t,r){let[n,o]=await Promise.all([this.get(t,r),this.list(t)]),s=sa.get(o,"result.0.metadata",{});return{value:n,metadata:s}}async put(t,r,n={}){let o=this.getUrlForKey(t),s=new URLSearchParams;this.ttl&&s.append("expiration_ttl",this.ttl.toString());let a={"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey};o.search=s.toString();let i=new FormData;return i.append("value",r),i.append("metadata",JSON.stringify(n)),(await fetch(o.toString(),{method:"PUT",headers:a,body:r})).ok}async delete(t){let r=this.getUrlForKey(t);return fetch(r,{method:"DELETE",headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}})}};var x={methodsMethodsWithBody:["POST","PUT","PATCH"],http:{statusMessages:{404:"Not Found"}},mime:{css:"text/css",csv:"text/csv",html:"text/html",ico:"image/microsoft.vnd.icon",jpeg:"image/jpeg",js:"application/javascript",json:"application/json",png:"image/png",svg:"image/svg+xml",xml:"application/xml"}};function aa(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function xt({kvAccountId:e,kvNamespace:t,kvAuthEmail:r,kvAuthKey:n,kvBasePath:o="",kvKey:s="{file}",defaultExtension:a="html",defaultIndexDocument:i,defaultErrorDocument:c,mime:d={},mode:p="rest"}){let u=new oe({accountId:e,namespace:t,authEmail:r,authKey:n,mode:p}),f={...x.mime,...d};return async l=>{let m=A.resolveParams(s,l.params),g=m===""&&i?i:aa(m,a),y=await u.get(o+g);!y&&c&&(y=await u.get(o+c)),y?(l.status=200,l.body=y,l.set("Content-Type",f[g.split(".").pop()]||"text/plain")):(l.status=404,l.body=x.http.statusMessages[404],l.set("Content-Type","text/plain"))}}var Zr=v(M());var Ut={get:Zr.default};function ia(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function ca(e,t){let r=Ut.get(e,"headers.if-none-match"),n=Ut.get(t,"metadata.headers.etag");return r?r===n:!1}function It({kvNamespaceBinding:e,kvBasePath:t="",kvKey:r="{file}",defaultExtension:n="html",defaultIndexDocument:o,defaultErrorDocument:s}){async function a(i){return await global[e].getWithMetadata(i)}return async i=>{let c=A.resolveParams(r,i.params),d=c===""&&o?o:ia(c,n),p=await a(t+d);if(!p&&s&&(p=await a(t+s)),p)if(ca(i.request,p))i.status=304;else{i.status=p.status,i.body=p.value;let u=Ut.get(p,"metadata.headers",{});Object.keys(u).forEach(f=>{i.set(f,u[f])})}else i.status=404,i.body=x.http.statusMessages[404],i.set("Content-Type","text/plain")}}var en=v(Ge());function Wt({accessKeyId:e,secretAccessKey:t,region:r,lambdaName:n}){let o=new en.AwsClient({accessKeyId:e,secretAccessKey:t});return async s=>{let a=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${n}/invocations`,i={},c=await o.fetch(a,{body:JSON.stringify(i)});s.status=c.status,s.body=c.body;let d=A.instanceToJson(c.headers);Object.keys(d).forEach(p=>{s.set(p,d[p])})}}var yn=v(M()),gn=v(je());var mn={get:yn.default,set:gn.default};function ci(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function di(e){return e[Math.floor(Math.random()*e.length)]}function Mt({sources:e=[]}){return async t=>{let r=di(e),n={method:t.request.method,headers:ci(t.request.headers),redirect:"manual",cf:t.request.cf};if(x.methodsMethodsWithBody.indexOf(t.request.method)!==-1&&mn.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);mn.set(n,"cf.resolveOverride",i)}let s=await fetch(o+t.request.search,n);t.body=s.body,t.status=s.status;let a=A.instanceToJson(s.headers);Object.keys(a).forEach(i=>{t.set(i,a[i])})}}var Sn=v(M());var $t={name:"@ahmadissa/cloudworker-proxy",version:"1.1.136",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
|
|
7
|
-
`),n=JSON.stringify({DeliveryStreamName:this.streamName,Record:{Data:r}}),o=`https://firehose.${this.region}.amazonaws.com`,s=new Request(o,{method:"POST",body:n,headers:{"X-Amz-Target":"Firehose_20150804.PutRecord","Content-Type":" application/x-amz-json-1.1"}});return this.awsClient.fetch(s)}};var W={get:Sn.default};async function pi(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}function qt(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 pi(r.request);try{await n(r);let s={message:"START",requestIp:W.get(r,"request.headers.x-real-ip"),requestId:W.get(r,"request.requestId"),request:{headers:W.get(r,"request.headers"),method:W.get(r,"request.method"),url:W.get(r,"request.href"),protocol:W.get(r,"request.protocol"),body:o},response:{status:r.status,headers:W.get(r,"response.headers")},handlers:W.get(r,"state.handlers",[]).join(","),route:W.get(r,"route.name"),timestamp:new Date().toISOString(),ttfb:new Date-r.state["logger-startDate"],redirectUrl:r.userRedirect,severity:30,proxyVersion:$t.version};r.event.waitUntil(t.log(s))}catch(s){let a={request:{headers:W.get(r,"request.headers"),method:W.get(r,"request.method"),handlers:W.get(r,"state.handlers",[]).join(","),url:W.get(r,"request.href"),body:o},message:"ERROR",stack:s.stack,error:s.message,severity:50,proxyVersion:$t.version};r.event.waitUntil(t.log(a))}}}var Re=v(En()),zn=v(M()),jn=v(je()),Yn=v(Gn());async function zt({refresh_token:e,authDomain:t,clientId:r,clientSecret:n}){let o=`${t}/oauth/token`,s=await fetch(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:r,client_secret:n,refresh_token:e})});if(!s.ok)throw new Error("Authentication failed");let a=await s.json();return{...a,expires:Date.now()+a.expires_in*1e3,refresh_token:e}}var Bn="PBKDF2",jt="AES-GCM",Di="SHA-256",Mi="raw";function $i(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 Vn(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 qi(e){return new TextEncoder().encode(e).buffer}function Li(e){return new TextDecoder().decode(e)}async function Fi(e){let t=new TextEncoder;return crypto.subtle.importKey(Mi,t.encode(e),{name:Bn},!1,["deriveKey"])}async function Gi(e,t){let r=await Fi(e),o=new TextEncoder().encode(t.replace(/_/g,"/").replace(/-/g,"+"));return crypto.subtle.deriveKey({name:Bn,salt:o,iterations:1e3,hash:{name:Di}},r,{name:jt,length:256},!0,["encrypt","decrypt"])}async function Bi(){let e=crypto.getRandomValues(new Uint8Array(8));return Vn(e)}async function Vi(e,t){let r=$i(t),n=r.slice(0,16),o=r.slice(16),s=await crypto.subtle.decrypt({name:jt,iv:n},e,o);return Li(s)}async function Xi(e,t){let r=crypto.getRandomValues(new Uint8Array(16)),n=await crypto.subtle.encrypt({name:jt,iv:r},e,qi(t)),o=new Uint8Array(n.byteLength+r.byteLength);return o.set(r,0),o.set(new Uint8Array(n),r.byteLength),Vn(o)}var de={decrypt:Vi,deriveAesGcmKey:Gi,encrypt:Xi,getSalt:Bi};var fe={get:zn.default,set:jn.default};function Xn({cookieHeader:e="",cookieName:t}){return Re.default.parse(e)[t]}function zi(e){return Object.keys(e).map(t=>`${t}=${encodeURIComponent(e[t])}`).join("&")}function ji(e=""){return e.split(",").indexOf("text/html")!==-1}function Yt({cookieName:e="proxy",cookieHttpOnly:t=!0,allowPublicAccess:r=!1,kvAccountId:n,kvNamespace:o,kvAuthEmail:s,kvAuthKey:a,kvTtl:i=2592e3,oauth2AuthDomain:c,oauth2ClientId:d,oauth2ClientSecret:p,oauth2Audience:u,oauth2Scopes:f=[],oauth2CallbackPath:l="/callback",oauth2CallbackType:m="cookie",oauth2LogoutPath:g="/logout",oauth2LoginPath:y="/login",oauth2ServerTokenPath:w="/oauth/token",oauth2ServerAuthorizePath:H="",oauth2ServerLogoutPath:K}){let O=new oe({accountId:n,namespace:o,authEmail:s,authKey:a,ttl:i}),ee=c,Se=l,pt=m,ht=w,De=H,ft=K,V=d,Ee=p,q=u,Me=g,C=y,Ce=f.join("%20");async function $e(h,T){let P=`${ee}${ht}`,R=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:T})});if(!R.ok)throw new Error("Authentication failed");let L=await R.json();return{...L,expires:Date.now()+L.expires_in*1e3}}async function vo(h){if(Xn({cookieHeader:h.request.headers.cookie,cookieName:e})){let R=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.set("Set-Cookie",Re.default.serialize(e,"",{domain:`.${R}`,path:"/",maxAge:0}))}let P=Sr(h);if(K){let R=encodeURIComponent(`${h.request.protocol}://${h.request.host}${P}`);h.set("Location",`${ee}${ft}?client_id=${V}&returnTo=${R}`)}else h.set("Location",P);h.status=302}async function Po(h){let T=h.request.href.split("?")[0],P=await $e(h.request.query.code,T),R=Yn.default.generate(),L=await de.getSalt(),F=`${R}.${L}`,lt=await de.deriveAesGcmKey(R,L),te=await de.encrypt(lt,JSON.stringify(P));await O.put(R,te);let mt=h.request.hostname.match(/[^.]+\.[^.]+$/i)[0];h.status=302,pt==="query"?h.set("Location",`${h.request.query.state}?auth=${F}`):(h.set("Set-Cookie",Re.default.serialize(e,F,{httpOnly:t,domain:`.${mt}`,path:"/",maxAge:60*60*24*365})),h.set("Location",h.request.query.state))}async function Ho(h,T){let[P,R]=T.split("."),L=await O.get(P);if(L){let F=await de.deriveAesGcmKey(P,R),lt=await de.decrypt(F,L),te=JSON.parse(lt);if(te.expires<Date.now()){te=await zt({refresh_token:te.refresh_token,clientId:V,authDomain:ee,clientSecret:Ee});let mt=await de.encrypt(F,JSON.stringify(te));await O.put(P,mt)}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",Re.default.serialize(e,"",{domain:`.${F}`,maxAge:0}))}}function Sr(h){let T=fe.get(h,"request.query.redirect-to");if(T)return T;let P=fe.get(h,"request.headers.referer");return P||"/"}async function To(h){if(h.request.method==="OPTIONS")h.status=200;else{let T=Sr(h),P=encodeURIComponent(T||"/"),R=encodeURIComponent(`${h.request.protocol}://${h.request.host}${Se}`);h.status=302,h.set("location",`${ee}${De}/authorize?state=${P}&client_id=${V}&response_type=code&scope=${Ce}&audience=${q}&redirect_uri=${R}`)}}async function Ko(h,T){if(h.request.method==="OPTIONS")await T(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 T(h);else{let P=fe.get(h,"request.query.auth")||Xn({cookieHeader:h.request.headers.cookie,cookieName:e});if(P&&await Ho(h,P),fe.get(h,"state.accessToken")||r)await T(h);else if(ji(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}${De}/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,T)=>{switch(h.request.path){case Se:await Po(h);break;case Me:await vo(h);break;case C:await To(h);break;default:await Ko(h,T)}}}var Zn=v(M());var Yi={get:Zn.default};function Zi(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function Zt(e){let{localOriginOverride:t,backend:r}=e;return async n=>{let o=process.env.LOCAL?`${t||n.request.origin}${n.request.path}`:`${r}${n.request.path}`,s={headers:Zi(n.request.headers),method:n.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(n.request.method)!==-1&&Yi.get(n,"event.request.body")){let c=n.event.request.clone();s.body=c.body}let a=await fetch(o,s);n.body=a.body,n.status=a.status;let i=A.instanceToJson(a.headers);Object.keys(i).forEach(c=>{n.set(c,i[c])})}}function Qt({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 Qn=v(M()),eo=v(je()),er={get:Qn.default,set:eo.default};function tr({type:e="IP",scope:t="default",limit:r=1e3}){let n={};function o(a,i){let c=i["x-real-ip"];return e==="IP"?`minute.${a}.${t}.${c}`:`minute.${a}.${t}.account`}function s(a){let i=er.get(n,"minutes",{});Object.keys(i).forEach(c=>{c!==a&&delete n.minutes.minute})}return async(a,i)=>{let c=Math.trunc(Date.now()/6e4),d=Math.trunc(c*60+60-Date.now()/1e3),p=o(c,a.request.headers),u=er.get(n,p,0);if(["HEAD","OPTIONS"].indexOf(a.request.method)===-1&&(u+=1),er.set(n,p,u),r<u){a.status=429;return}s(c),await i(a)}}var to=v(Ge());function Qi(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 rr({accessKeyId:e,secretAccessKey:t,bucket:r,region:n,endpoint:o,forcePathStyle:s,enableBucketOperations:a=!1}){let i=new to.AwsClient({accessKeyId:e,region:n,secretAccessKey:t}),c=Qi(o,{region:n,bucket:r,forcePathStyle:s});return async d=>{if(d.params.file===void 0&&!a){d.status=404,d.body=x.http.statusMessages[404],d.set("Content-Type","text/plain");return}let p=d.params.file?A.resolveParams(`${c}/{file}`,d.params):c,u={};d.request.headers.range&&(u.range=d.request.headers.range);let f=await i.fetch(p,{method:d.method||d.request.method,headers:u});d.status=f.status,d.body=f.body;let l=A.instanceToJson(f.headers);Object.keys(l).forEach(m=>{d.set(m,l[m])})}}var nr;function ro(e){return new Uint8Array(e.split("").map(r=>r.charCodeAt(0)))}async function ec(e){return nr||(nr=await crypto.subtle.importKey("raw",ro(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"])),nr}async function tc(e,t){let r=await ec(t),n=await crypto.subtle.sign({name:"HMAC"},r,ro(e));return btoa(String.fromCharCode.apply(null,new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function or({secret:e}){return async(t,r)=>{let n=(t.request.path+t.request.search).replace(/([?|&]sign=[\w|-]+)/,"");if(await tc(n,e)!==t.query.sign){t.status=403;return}await r(t)}}function sr({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 rc(e,t,r){let n=e.getReader(),o=t.getWriter(),s=new TextDecoder,a=new TextEncoder;for(;;){let{done:i,value:c}=await n.read();if(i)break;let d=s.decode(c),p=no(d,r),u=a.encode(p);await o.write(u)}await o.close()}function nc(e,t){return e.replace(/{{\$(\d)}}/g,(r,n)=>t[parseInt(n,10)])}function no(e,t){return t.reduce((r,n)=>r.replace(n.regex,(...o)=>nc(n.replace,o)),e)}function ar({transforms:e=[],statusCodes:t=[200]}){let r=e.map(n=>({regex:new RegExp(n.regex,"g"),replace:n.replace}));return async(n,o)=>{await o(n);let{body:s}=n;if(t.indexOf(n.status)!==-1)if(typeof s=="string")n.body=no(s,r);else{let{readable:a,writable:i}=new TransformStream;rc(s,i,r),n.body=a}}}async function oc({projectID:e="your-project-id",API_KEY:t="GCP_API_KEY",token:r="action-token",siteKey:n="siteKey",expectedAction:o="action-name"}){let a=await(await fetch(`https://recaptchaenterprise.googleapis.com/v1/projects/${e}/assessments?key=${t}`,{body:JSON.stringify({event:{token:r,siteKey:n,expectedAction:o}}),headers:{"Content-Type":"application/json"},method:"POST"})).json();return a.tokenProperties.valid?a.tokenProperties.action===o?(a.riskAnalysis.reasons.forEach(i=>{console.log(i)}),a.riskAnalysis.score):(console.error("reCAPTCHA action error:"+o+":action:"+a.tokenProperties.action),null):(console.error("The CreateAssessment call failed because the token was: "+a.tokenProperties.invalidReason),0)}var sc=e=>(e=e.split("?")[0],e.replace(/\W/g,"").slice(0,100));function ir({projectID:e,API_KEY:t,siteKey:r}){function n(o){return{token:o["g-recaptcha-token"]}}return async(o,s)=>{let{token:a}=n(o.request.headers),i=sc(o.request.path);if((await oc({projectID:e,API_KEY:t,token:a,siteKey:r,expectedAction:i})||0)<.5){o.status=409;return}await s(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}:{}}),a=await(await fetch("https://www.google.com/recaptcha/api/siteverify",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})).json(),i=!!a.success,c=a.action===r,d=typeof a.score=="number"?a.score:0;return{ok:i&&c,score:d,action:a.action,errorCodes:a["error-codes"]}}var ic=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)},xe=(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 cr({secret:e,headerName:t="x-recaptcha-token",minScore:r=.5,requireActionMatch:n=!0}){return async(o,s)=>{let a=o.request?.req||o.request||o,i=a.headers??o.request?.headers??{},c=xe(i,t)||xe(i,"g-recaptcha-token")||null,p=xe(i,"x-recaptcha-action")||ic(o.request?.path||o.request?.url||a.url||"/"),u=xe(i,"cf-connecting-ip")||xe(i,"x-forwarded-for")||void 0,f=await ac({secret:e,token:c,expectedAction:p,remoteip:u});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 s(o)}}async function cc({secret:e,token:t,remoteip:r}){if(!t)return{ok:!1,errorCodes:["missing-input-response"]};let n=new URLSearchParams({secret:e,response:t,...r?{remoteip:r}:{}}),s=await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:n})).json();return{ok:!!s.success,errorCodes:s["error-codes"]}}var rt=(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 dr({secret:e,headerName:t="x-recaptcha-token"}){return async(r,n)=>{let s=(r.request||r).headers||{},a=rt(s,t)||rt(s,"cf-turnstile-token")||null,i=rt(s,"cf-connecting-ip")||rt(s,"x-forwarded-for")||void 0,c=await cc({secret:e,token:a,remoteip:i});if(!c.ok){let p={errors:c.errorCodes??[]};console.warn("[Turnstile] verification failed: "+JSON.stringify(p)),r.status=409,r.headers||=new Headers,r.headers.set("Content-Type","application/json"),r.body=JSON.stringify({error:"Turnstile verification failed"});return}await n(r)}}var dc=e=>!new RegExp("(\b)(onS+)(s*)=|javascript|<(|/|[^/>][^>]+|/[^>][^>]+)>").test(e),uc=(e,t,r)=>!(!dc(t)||!r[e](t)),pc=e=>!(e===null||typeof e!="object"||Array.isArray(e)&&(!e[0]||typeof e[0]!="object")),nt=(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]=""),pc(e[n])){if(!nt(e[n],t))return console.error("error validating key+validateObject:",n),!1}else if(!uc(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1}return!0},oo=e=>!(e==null||typeof e!="object"),hc=(e,t)=>{let r=e.query;return oo(r)?nt(r,t):!1},Ue=(e,t)=>{let r=e.params;return r?oo(r)?nt(r,t):!1:!0};async function fc(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return{};try{let t=await e.text();return JSON.parse(t)}catch{}return{}}function ur({allowedKeys:e}){return async(r,n)=>{if(!e)return r.status=501,!1;if(!Ue(r,e)||!hc(r,e))return r.status=422,!1;let o=await fc(r.request);if(!nt(o,e))return r.status=422,!1;await n(r)}}var Eo=v(M());var E=crypto,D=e=>e instanceof CryptoKey;var U=new TextEncoder,J=new TextDecoder,ku=2**32;function z(...e){let t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}var so=e=>{let t=e;typeof t=="string"&&(t=U.encode(t));let r=32768,n=[];for(let o=0;o<t.length;o+=r)n.push(String.fromCharCode.apply(null,t.subarray(o,o+r)));return btoa(n.join(""))},k=e=>so(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 N=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 ot=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 st(e,t){return e.name===t}function pr(e){return parseInt(e.name.slice(4),10)}function yc(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function gc(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 io(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!st(e.algorithm,"HMAC"))throw B("HMAC");let n=parseInt(t.slice(2),10);if(pr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!st(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(pr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!st(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");let n=parseInt(t.slice(2),10);if(pr(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(!st(e.algorithm,"ECDSA"))throw B("ECDSA");let n=yc(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}gc(e,r)}function co(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var $=(e,...t)=>co("Key must be ",e,...t);function hr(e,t,...r){return co(`Key for the ${e} algorithm must be `,t,...r)}var fr=e=>D(e),b=["CryptoKey"];var bc=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let s of o){if(r.has(s))return!1;r.add(s)}}return!0},me=bc;function Cc(e){return typeof e=="object"&&e!==null}function I(e){if(!Cc(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 at=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var Z=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((s,a)=>s===t[a])||Z(e,t,n+1)},po=e=>{switch(!0){case Z(e,[42,134,72,206,61,3,1,7]):return"P-256";case Z(e,[43,129,4,0,34]):return"P-384";case Z(e,[43,129,4,0,35]):return"P-521";case Z(e,[43,101,110]):return"X25519";case Z(e,[43,101,111]):return"X448";case Z(e,[43,101,112]):return"Ed25519";case Z(e,[43,101,113]):return"Ed448";default:throw new S("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Hc=async(e,t,r,n,o)=>{let s,a,i=new Uint8Array(atob(r.replace(e,"")).split("").map(d=>d.charCodeAt(0))),c=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=po(i);s=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},a=c?[]:["deriveBits"];break}case"EdDSA":s={name:po(i)},a=c?["verify"]:["sign"];break;default:throw new S('Invalid or unsupported "alg" (Algorithm) value')}return E.subtle.importKey(t,i,s,o?.extractable??!1,a)},ho=(e,t,r)=>Hc(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r);async function lr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ho(e,t,r)}var Tc=(e,t)=>{if(!(t instanceof Uint8Array)){if(!fr(t))throw new TypeError(hr(e,t,...b,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${b.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Kc=(e,t,r)=>{if(!fr(t))throw new TypeError(hr(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"`)},Oc=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Tc(e,t):Kc(e,t,r)},Je=Oc;function kc(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let a of n.crit){if(!s.has(a))throw new S(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var ye=kc;var qc=Symbol();function it(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 ct(e,t,r){if(D(t))return io(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 Fc=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,dt=e=>{let t=Fc.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 Xc=async(e,t,r)=>{let n=await ct(e,t,"sign");at(e,n);let o=await E.subtle.sign(it(e,n.algorithm),n,r);return new Uint8Array(o)},wo=Xc;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 N("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!me(this._protectedHeader,this._unprotectedHeader))throw new N("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ye(N,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(o.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new N('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new N('JWS "alg" (Algorithm) Header Parameter missing or invalid');Je(a,t,"sign");let i=this._payload;s&&(i=U.encode(k(i)));let c;this._protectedHeader?c=U.encode(k(JSON.stringify(this._protectedHeader))):c=U.encode("");let d=z(c,U.encode("."),i),p=await wo(a,t,d),u={signature:k(p),payload:""};return s&&(u.payload=J.decode(i)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=J.decode(c)),u}};var ke=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(!I(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)+dt(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)+dt(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 Ne=class extends Ae{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new ke(U.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new j("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var Zc;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Zc="jose/v5.1.0");var Ao=function e(t){function r(o,s,a){var i,c={};if(Array.isArray(o))return o.concat(s);for(i in o)c[a?i.toLowerCase():i]=o[i];for(i in s){var d=a?i.toLowerCase():i,p=s[i];c[d]=d in c&&typeof p=="object"?r(c[d],p,d=="headers"):p}return c}function n(o,s,a,i,c){var d=typeof o!="string"?(s=o).url:o,p={config:s},u=r(t,s),f={};i=i||u.data,(u.transformRequest||[]).map(function(l){i=l(i,u.headers)||i}),u.auth&&(f.authorization=u.auth),i&&typeof i=="object"&&typeof i.append!="function"&&typeof i.text!="function"&&(i=JSON.stringify(i),f["content-type"]="application/json");try{f[u.xsrfHeaderName]=decodeURIComponent(document.cookie.match(RegExp("(^|; )"+u.xsrfCookieName+"=([^;]*)"))[2])}catch{}return u.baseURL&&(d=d.replace(/^(?!.*\/\/)\/?/,u.baseURL+"/")),u.params&&(d+=(~d.indexOf("?")?"&":"?")+(u.paramsSerializer?u.paramsSerializer(u.params):new URLSearchParams(u.params))),(u.fetch||fetch)(d,{method:(a||u.method||"get").toUpperCase(),body:i,headers:r(u.headers,f,!0),credentials:u.withCredentials?"include":c}).then(function(l){for(var m in l)typeof l[m]!="function"&&(p[m]=l[m]);return u.responseType=="stream"?(p.data=l.body,p):l[u.responseType||"text"]().then(function(g){p.data=g,p.data=JSON.parse(g)}).catch(Object).then(function(){return(u.validateStatus?u.validateStatus(l.status):l.ok)?p:Promise.reject(p)})})}return t=t||{},n.request=n,n.get=function(o,s){return n(o,s,"get")},n.delete=function(o,s){return n(o,s,"delete")},n.head=function(o,s){return n(o,s,"head")},n.options=function(o,s){return n(o,s,"options")},n.post=function(o,s,a){return n(o,a,"post",s)},n.put=function(o,s,a){return n(o,a,"put",s)},n.patch=function(o,s,a){return n(o,a,"patch",s)},n.all=Promise.all.bind(Promise),n.spread=function(o){return o.apply.bind(o,o)},n.CancelToken=typeof AbortController=="function"?AbortController:Object,n.defaults=t,n.create=e,n}();var td=e=>{if(!e)return!1;let t=JSON.parse(atob(e.split(".")[1])),r=Math.floor(Date.now()/1e3);return t.exp>r-600},ut=async(e,t)=>{let r=await GCP_INVOKER_TOKEN.get(t);if(td(r))return r;let n=await lr(e.private_key,"RS256"),o=e.client_email,s={iss:o,sub:o,aud:"https://www.googleapis.com/oauth2/v4/token",target_audience:t,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+3600},a=await new Ne(s).setProtectedHeader({alg:"RS256",typ:"JWT"}).sign(n),i=await Ao.post("https://www.googleapis.com/oauth2/v4/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:a});return await GCP_INVOKER_TOKEN.delete(t),await GCP_INVOKER_TOKEN.put(t,i.data.id_token),i.data.id_token};var So={get:Eo.default};function yr({project_id:e,region:t,functionName:r,serviceAccount:n,allowedKeys:o}){return async(s,a)=>{if(o&&s.params&&!Ue(s,o))return s.status=422,s.body=JSON.stringify({error:"Invalid params"}),!1;let i=So.get(s,"request.query",{}),c=new URLSearchParams(i).toString(),d=`https://${t}-${e}.cloudfunctions.net/${r}`,p=s.request.path,u=`https://${t}-${e}.cloudfunctions.net/${r}${p||""}${c?`?${c}`:""}`,f=await ut(n,d),l=new Headers(s.request.headers);l.set("X-Serverless-Authorization",`Bearer ${f}`);let m=s.event.cf||{},g={"X-Geo-Country":m.country,"X-Geo-City":m.city,"X-Geo-Latitude":m.latitude,"X-Geo-Longitude":m.longitude,"X-Geo-Timezone":m.timezone,"X-Geo-Region":m.region,"X-Geo-PostalCode":m.postalCode,"X-Geo-RegionCode":m.regionCode,"X-Geo-EU-Country":m.isEUCountry?"1":"0"};for(let[K,O]of Object.entries(g))O!==void 0&&l.set(K,O);let y={headers:l,method:s.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(s.request.method)!==-1&&So.get(s,"event.request.body")){let K=s.event.request.clone();y.body=K.body}let w=await fetch(u,y);s.body=w.body,s.status=w.status;let H=A.instanceToJson(w.headers);A.mergeHeaders(H,s),await a(s)}}var rd=v(M());function gr({domain:e,serviceAccount:t,allowedKeys:r}){return async(n,o)=>{if(r&&n.params&&!Ue(n,r))return n.status=422,n.body=JSON.stringify({error:"Invalid params"}),!1;let s=new URL(n.event.request.url),a=`${e}${s.pathname}${s.search}`,i=await ut(t,e),c=new Headers(n.request.headers);c.set("X-Serverless-Authorization",`Bearer ${i}`),c.set("X-Token",c.get("authorization")||"N/A"),c.delete("authorization");let d=n.event.cf||{},p={"X-Geo-Country":d.country,"X-Geo-City":d.city,"X-Geo-Latitude":d.latitude,"X-Geo-Longitude":d.longitude,"X-Geo-Timezone":d.timezone,"X-Geo-Region":d.region,"X-Geo-PostalCode":d.postalCode,"X-Geo-RegionCode":d.regionCode,"X-Geo-EU-Country":d.isEUCountry?"1":"0"};for(let[m,g]of Object.entries(p))g!==void 0&&c.set(m,g);let u={method:n.request.method,headers:c,redirect:"manual"};if(x.methodsMethodsWithBody.includes(n.request.method)){let m=n.event.request.clone();u.body=m.body}let f=await fetch(a,u),l=new Headers(f.headers);l.delete("content-length"),l.delete("transfer-encoding"),n.status=f.status,A.mergeHeaders(A.instanceToJson(l),n),n.body=f.body,await o(n)}}function wr({headers:e={},headersFN:t}){return async(r,n)=>{if(e)for(let o of Object.keys(e))r.set(o.toLowerCase(),e[o]);if(t){let o=await t();for(let s of Object.keys(o))r.set(s,o[s])}await n(r)}}async function nd(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return"";try{return await e.text()}catch{return""}}function od(e){return new TextEncoder().encode(e).length}function bo(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 Ar({bodySizeLimit:e=512}={}){return async(t,r)=>{let n=t.request?.method||"GET";if(["POST","PATCH","PUT","DELETE"].indexOf(n)===-1)return r(t);let o=t.request?.headers?.["content-length"],s=o?Number(o):NaN;if(Number.isFinite(s)&&s>e)return bo(t,e,s);let a=await nd(t.request),i=typeof a=="string"?od(a):0;if(i>e)return bo(t,e,i);await r(t)}}var Co={basicAuth:_t,cache:Tt,cors:Kt,geoDecorator:Ot,jwt:Rt,kvStorage:xt,kvStorageBinding:It,lambda:Wt,loadbalancer:Mt,logger:qt,oauth2:Yt,origin:Zt,rateLimit:tr,response:Qt,s3:rr,signature:or,split:sr,transform:ar,recaptcha:ir,recaptchaV3:cr,turnstileVerify:dr,userInputValidation:ur,cloudfunction:yr,gcpCloudrun:gr,headers:wr,bodySizeLimit:Ar};function sd(e){return t=>{let r=e(t);return async(n,o)=>(n.__upgraded||(Ht(n),n.__upgraded=!0),r(n,o))}}module.exports=class{constructor(t=[],r={}){this.router=new _o.default,t.forEach(n=>{let o=r[n.handlerName]||Co[n.handlerName];if(!o)throw new Error(`Handler ${n.handlerName} is not supported`);let s=sd(o);this.router.add(n,s(n.options))})}async resolve(t){return t.cf=t?.request?.cf||{},this.router.resolve(t)}};
|
|
5
|
+
`)}async hexBodyHash(){let l=this.headers.get("X-Amz-Content-Sha256");if(l==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");l=c(await i(this.body||""))}return l}}async function s(d,l){let f=await crypto.subtle.importKey("raw",typeof d=="string"?t.encode(d):d,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",f,t.encode(l))}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),l=>("0"+l.toString(16)).slice(-2)).join("")}function u(d){return d.replace(/[!'()*]/g,l=>"%"+l.charCodeAt(0).toString(16).toUpperCase())}function h(d,l){let{hostname:f,pathname:p}=d,g=f.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[y,w]=(g||["",""]).slice(1,3);if(w==="us-gov")w="us-gov-west-1";else if(w==="s3"||w==="s3-accelerate")w="us-east-1",y="s3";else if(y==="iot")f.startsWith("iot.")?y="execute-api":f.startsWith("data.jobs.iot.")?y="iot-jobs-data":y=p==="/mqtt"?"iotdevicegateway":"iotdata";else if(y==="autoscaling"){let b=(l.get("X-Amz-Target")||"").split(".")[0];b==="AnyScaleFrontendService"?y="application-autoscaling":b==="AnyScaleScalingPlannerFrontendService"&&(y="autoscaling-plans")}else w==null&&y.startsWith("s3-")?(w=y.slice(3).replace(/^fips-|^external-1/,""),y="s3"):y.endsWith("-fips")?y=y.slice(0,-5):w&&/-\d$/.test(y)&&!/-\d$/.test(w)&&([y,w]=[w,y]);return[r[y]||y,w]}e.AwsClient=o,e.AwsV4Signer=a,Object.defineProperty(e,"__esModule",{value:!0})})});var Ze=v((Sd,Tn)=>{var Js="Expected a function",An="__lodash_hash_undefined__",Sn=1/0,Ds=9007199254740991,$s="[object Function]",Ms="[object GeneratorFunction]",qs="[object Symbol]",Fs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ls=/^\w*$/,Gs=/^\./,Bs=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Vs=/[\\^$.*+?()[\]{}|]/g,js=/\\(\\)?/g,zs=/^\[object .+?Constructor\]$/,Xs=/^(?:0|[1-9]\d*)$/,Ys=typeof global=="object"&&global&&global.Object===Object&&global,Zs=typeof self=="object"&&self&&self.Object===Object&&self,Bt=Ys||Zs||Function("return this")();function Qs(e,t){return e?.[t]}function ei(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var ti=Array.prototype,ri=Function.prototype,bn=Object.prototype,Gt=Bt["__core-js_shared__"],mn=function(){var e=/[^.]+$/.exec(Gt&&Gt.keys&&Gt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),En=ri.toString,ze=bn.hasOwnProperty,Cn=bn.toString,ni=RegExp("^"+En.call(ze).replace(Vs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),yn=Bt.Symbol,oi=ti.splice,ai=_n(Bt,"Map"),Te=_n(Object,"create"),gn=yn?yn.prototype:void 0,wn=gn?gn.toString:void 0;function se(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function si(){this.__data__=Te?Te(null):{}}function ii(e){return this.has(e)&&delete this.__data__[e]}function ci(e){var t=this.__data__;if(Te){var r=t[e];return r===An?void 0:r}return ze.call(t,e)?t[e]:void 0}function ui(e){var t=this.__data__;return Te?t[e]!==void 0:ze.call(t,e)}function di(e,t){var r=this.__data__;return r[e]=Te&&t===void 0?An:t,this}se.prototype.clear=si;se.prototype.delete=ii;se.prototype.get=ci;se.prototype.has=ui;se.prototype.set=di;function le(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function pi(){this.__data__=[]}function hi(e){var t=this.__data__,r=Xe(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():oi.call(t,r,1),!0}function li(e){var t=this.__data__,r=Xe(t,e);return r<0?void 0:t[r][1]}function fi(e){return Xe(this.__data__,e)>-1}function mi(e,t){var r=this.__data__,n=Xe(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}le.prototype.clear=pi;le.prototype.delete=hi;le.prototype.get=li;le.prototype.has=fi;le.prototype.set=mi;function ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function yi(){this.__data__={hash:new se,map:new(ai||le),string:new se}}function gi(e){return Ye(this,e).delete(e)}function wi(e){return Ye(this,e).get(e)}function Ai(e){return Ye(this,e).has(e)}function Si(e,t){return Ye(this,e).set(e,t),this}ie.prototype.clear=yi;ie.prototype.delete=gi;ie.prototype.get=wi;ie.prototype.has=Ai;ie.prototype.set=Si;function bi(e,t,r){var n=e[t];(!(ze.call(e,t)&&vn(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function Xe(e,t){for(var r=e.length;r--;)if(vn(e[r][0],t))return r;return-1}function Ei(e){if(!je(e)||Ki(e))return!1;var t=Ui(e)||ei(e)?ni:zs;return t.test(xi(e))}function Ci(e,t,r,n){if(!je(e))return e;t=Ti(t,e)?[t]:vi(t);for(var o=-1,a=t.length,s=a-1,i=e;i!=null&&++o<a;){var c=Ri(t[o]),u=r;if(o!=s){var h=i[c];u=n?n(h,c,i):void 0,u===void 0&&(u=je(h)?h:Pi(t[o+1])?[]:{})}bi(i,c,u),i=i[c]}return e}function _i(e){if(typeof e=="string")return e;if(jt(e))return wn?wn.call(e):"";var t=e+"";return t=="0"&&1/e==-Sn?"-0":t}function vi(e){return Pn(e)?e:Oi(e)}function Ye(e,t){var r=e.__data__;return Hi(t)?r[typeof t=="string"?"string":"hash"]:r.map}function _n(e,t){var r=Qs(e,t);return Ei(r)?r:void 0}function Pi(e,t){return t=t??Ds,!!t&&(typeof e=="number"||Xs.test(e))&&e>-1&&e%1==0&&e<t}function Ti(e,t){if(Pn(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||jt(e)?!0:Ls.test(e)||!Fs.test(e)||t!=null&&e in Object(t)}function Hi(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ki(e){return!!mn&&mn in e}var Oi=Vt(function(e){e=Ii(e);var t=[];return Gs.test(e)&&t.push(""),e.replace(Bs,function(r,n,o,a){t.push(o?a.replace(js,"$1"):n||r)}),t});function Ri(e){if(typeof e=="string"||jt(e))return e;var t=e+"";return t=="0"&&1/e==-Sn?"-0":t}function xi(e){if(e!=null){try{return En.call(e)}catch{}try{return e+""}catch{}}return""}function Vt(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(Js);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(Vt.Cache||ie),r}Vt.Cache=ie;function vn(e,t){return e===t||e!==e&&t!==t}var Pn=Array.isArray;function Ui(e){var t=je(e)?Cn.call(e):"";return t==$s||t==Ms}function je(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function ki(e){return!!e&&typeof e=="object"}function jt(e){return typeof e=="symbol"||ki(e)&&Cn.call(e)==qs}function Ii(e){return e==null?"":_i(e)}function Wi(e,t,r){return e==null?e:Ci(e,t,r)}Tn.exports=Wi});var kn=v(Zt=>{"use strict";Zt.parse=Li;Zt.serialize=Gi;var Mi=decodeURIComponent,qi=encodeURIComponent,Fi=/; */,et=/^[\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||Mi,s=0;s<o.length;s++){var i=o[s],c=i.indexOf("=");if(!(c<0)){var u=i.substr(0,c).trim(),h=i.substr(++c,i.length).trim();h[0]=='"'&&(h=h.slice(1,-1)),r[u]==null&&(r[u]=Bi(h,a))}}return r}function Gi(e,t,r){var n=r||{},o=n.encode||qi;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!et.test(e))throw new TypeError("argument name is invalid");var a=o(t);if(a&&!et.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(!et.test(n.domain))throw new TypeError("option domain is invalid");s+="; Domain="+n.domain}if(n.path){if(!et.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 Bi(e,t){try{return t(e)}catch{return e}}});var Wn=v((Jd,In)=>{"use strict";var tt=1;function Vi(){return tt=(tt*9301+49297)%233280,tt/233280}function ji(e){tt=e}In.exports={nextValue:Vi,seed:ji}});var Re=v((Dd,$n)=>{"use strict";var Qt=Wn(),ue="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",j,Nn,Oe;function er(){Oe=!1}function Jn(e){if(!e){j!==ue&&(j=ue,er());return}if(e!==j){if(e.length!==ue.length)throw new Error("Custom alphabet for shortid must be "+ue.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter(function(r,n,o){return n!==o.lastIndexOf(r)});if(t.length)throw new Error("Custom alphabet for shortid must be "+ue.length+" unique characters. These characters were not unique: "+t.join(", "));j=e,er()}}function zi(e){return Jn(e),j}function Xi(e){Qt.seed(e),Nn!==e&&(er(),Nn=e)}function Yi(){j||Jn(ue);for(var e=j.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 Dn(){return Oe||(Oe=Yi(),Oe)}function Zi(e){var t=Dn();return t[e]}function Qi(){return j||ue}$n.exports={get:Qi,characters:zi,seed:Xi,lookup:Zi,shuffled:Dn}});var qn=v(($d,Mn)=>{"use strict";var tr=typeof window=="object"&&(window.crypto||window.msCrypto),rr;!tr||!tr.getRandomValues?rr=function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(Math.random()*256));return t}:rr=function(e){return tr.getRandomValues(new Uint8Array(e))};Mn.exports=rr});var Ln=v((Md,Fn)=>{Fn.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 Bn=v((qd,Gn)=>{"use strict";var ec=Re(),tc=qn(),rc=Ln();function nc(e){for(var t=0,r,n="";!r;)n=n+rc(tc,ec.get(),1),r=e<Math.pow(16,t+1),t++;return n}Gn.exports=nc});var zn=v((Ld,jn)=>{"use strict";var rt=Bn(),Fd=Re(),oc=1567752802062,ac=7,nt,Vn;function sc(e){var t="",r=Math.floor((Date.now()-oc)*.001);return r===Vn?nt++:(nt=0,Vn=r),t=t+rt(ac),t=t+rt(e),nt>0&&(t=t+rt(nt)),t=t+rt(r),t}jn.exports=sc});var Yn=v((Gd,Xn)=>{"use strict";var ic=Re();function cc(e){if(!e||typeof e!="string"||e.length<6)return!1;var t=new RegExp("[^"+ic.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]");return!t.test(e)}Xn.exports=cc});var Qn=v((Bd,Zn)=>{"use strict";Zn.exports=0});var ro=v((Vd,G)=>{"use strict";var nr=Re(),uc=zn(),dc=Yn(),eo=Qn()||0;function pc(e){return nr.seed(e),G.exports}function hc(e){return eo=e,G.exports}function lc(e){return e!==void 0&&nr.characters(e),nr.shuffled()}function to(){return uc(eo)}G.exports=to;G.exports.generate=to;G.exports.seed=pc;G.exports.worker=hc;G.exports.characters=lc;G.exports.isValid=dc});var oo=v((jd,no)=>{"use strict";no.exports=ro()});var No=P(qr());var rn=P($()),ts={get:rn.default};function vt(e){e.status=401,e.body="Unauthorized",e.set("WWW-Authenticate","Basic")}function Pt(e){return async(t,r)=>{if(t.request.path===e.logoutPath)return vt(t);let n=ts.get(t,"request.headers.authorization");if(!n||!n.startsWith("Basic "))return vt(t);let o=e.users.map(i=>i.authToken),a=n.substring(6),s=o.indexOf(a);return s===-1?vt(t):(t.state.user=e.users[s].username,r(t))}}var nn=caches.default;async function rs(e){return await nn.match(e)}async function ns(e,t){return nn.put(e.href,t)}var Tt={get:rs,set:ns};async function os(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 on=os;function as(e,t={}){return Object.keys(t).reduce((r,n)=>r.replace(`{${n}}`,t[n]),e)}function Ht(e){return[...e].reduce((t,r)=>{let n={};return n[r[0]]=r[1],{...t,...n}},{})}function ss(e,t){Object.entries(e).forEach(([r,n])=>{t.header(r)||t.set(r,n)})}var Kt=e=>{e.set=(t,r)=>{e.response.headers[t.toLowerCase()]=r},e.header=t=>e.request.headers[t.toLowerCase()]},A={resolveParams:as,instanceToJson:Ht,mergeHeaders:ss,upgradeCTX:Kt};var is=["x-ratelimit-count","x-ratelimit-limit","x-ratelimit-reset","x-cache-hit"];async function cs(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}async function us(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 on(await cs(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 Ot({cacheDuration:e,cacheKeyTemplate:t,headerBlacklist:r=is}){return async(n,o)=>{let a=await us(n,t),s=await Tt.get(a);if(s){n.body=s.body,n.status=s.status;let i=Ht(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(Tt.set(a,c))}}}function Rt({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:h}=c.request,{origin:d}=c.request.headers,l=c.request.headers["access-control-request-headers"];if(ds(c,d,e),ps(c,r),ms(c,o),!t.includes(h.toUpperCase())){c.status=405,c.body={error:`Method ${h} not allowed`};return}if(h==="OPTIONS"&&(hs(c,t),ls(c,l,n),fs(c,a),i)){c.status=s,c.set("content-length","0");return}await u(c)}}function ds(e,t,r){if(Array.isArray(r)){if(r[0]==="origin"){e.set("Access-Control-Allow-Origin",t),an(e,"Origin");return}r[0]==="*"?e.set("Access-Control-Allow-Origin","*"):r.indexOf(t)!==-1&&(e.set("Access-Control-Allow-Origin",t),an(e,"Origin"))}}function ps(e,t){t&&e.set("Access-Control-Allow-Credentials",String(t))}function hs(e,t){e.set("Access-Control-Allow-Methods",t.join(","))}function ls(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 fs(e,t){t&&e.set("Access-Control-Max-Age",String(t))}function ms(e,t){t.length&&e.set("Access-Control-Expose-Headers",t.join(","))}function an(e,t){let r=e.header("vary")||e.header("Vary");(r?.split(",").map(o=>o.trim().toLowerCase())||[]).includes(t.toLowerCase())||e.set("Vary",r?`${r}, ${t}`:t)}var ys={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 xt(){return async(e,t)=>{let r=e.request.headers["cf-ipcountry"]||"XX";e.request.headers["proxy-continent"]=ys[r],await t(e)}}function gs(e){let t=0;for(let r=0;r<e.length;r+=1)t=(t*31+e.charCodeAt(r))%2147483647;return t}function ws(e){let t=globalThis[e];if(!t)throw new Error(`Durable Object binding ${e} was not found on global scope`);return t}function Ut({bindingName:e,cacheKey:t,shardCount:r}){let n=ws(e),o=gs(t)%r,a=n.idFromName(`ttl-cache:${o}`);return n.get(a)}async function As(e){return e.json()}var oe=class{constructor({bindingName:t,shardCount:r=64}){this.bindingName=t,this.shardCount=r}async get(t){let n=await Ut({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`);if(n.status===404)return null;if(!n.ok)throw new Error("Failed to read cache record from Durable Object");return As(n)}async put({cacheKey:t,value:r,ttlSeconds:n}){if(!(await Ut({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({value:r,ttlSeconds:n})})).ok)throw new Error("Failed to write cache record to Durable Object")}async delete(t){if(!(await Ut({bindingName:this.bindingName,cacheKey:t,shardCount:this.shardCount}).fetch(`https://internal/cache/${encodeURIComponent(t)}`,{method:"DELETE"})).ok)throw new Error("Failed to delete cache record from Durable Object")}};var sn="https://oauth2.googleapis.com/token",Ss="https://www.googleapis.com/auth/datastore";function It(e){let t=e.client_email;return e.clientEmail||t||""}function bs(e){let t=e.private_key;return e.privateKey||t||""}function Es(e,t){return`google-access-token:${It(e)}:${t}`}function Cs(e){let t=e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\s+/g,""),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.charCodeAt(o);return n.buffer}function kt(e){let t=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e),r="";return t.forEach(n=>{r+=String.fromCharCode(n)}),btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function _s({serviceAccount:e,scope:t}){let r=Math.floor(Date.now()/1e3),n={alg:"RS256",typ:"JWT"},o={iss:It(e),sub:It(e),scope:t,aud:sn,iat:r,exp:r+3600},a=kt(JSON.stringify(n)),s=kt(JSON.stringify(o)),i=`${a}.${s}`,c=await crypto.subtle.importKey("pkcs8",Cs(bs(e)),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]),u=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",c,new TextEncoder().encode(i));return`${i}.${kt(new Uint8Array(u))}`}async function cn({serviceAccount:e,scope:t=Ss,durableObjectNamespaceBinding:r,durableObjectShardCount:n}){let o=r?new oe({bindingName:r,shardCount:n}):null,a=Es(e,t);if(o){let u=await o.get(a);if(u?.value)return u.value}let s=await _s({serviceAccount:e,scope:t}),i=await fetch(sn,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s}).toString()});if(!i.ok)throw new Error("Failed to fetch Google access token");let c=await i.json();if(o){let u=Math.max(Number(c.expires_in||3600)-60,1);await o.put({cacheKey:a,value:c.access_token,ttlSeconds:u})}return c.access_token}function Wt(e){return`api-key:${e}`}function Nt(e){e.status=401,e.body="Unauthorized"}function vs(e){e.status=503,e.body="Unable to validate api key"}function Ps(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").toLowerCase()}function Ts({headers:e={},apiKeyHeader:t,apiKeyPrefix:r}){let n=e[t.toLowerCase()]||e[t]||"";return n?r?n.toLowerCase().startsWith(r.toLowerCase())?n.slice(r.length).trim():"":n.trim():""}function Hs(e,t){let r=encodeURIComponent(t),n=e.includes("{apiKey}")?e.replace(/{apiKey}/g,r):`${e.replace(/\/$/,"")}/${r}`;return n.startsWith("https://")||n.startsWith("http://")?n:`https://firestore.googleapis.com/v1/${n.replace(/^\/?v1\//,"").replace(/^\//,"")}`}function Jt(e){if(!(!e||typeof e!="object")){if("stringValue"in e)return e.stringValue;if("booleanValue"in e)return e.booleanValue;if("integerValue"in e)return e.integerValue;if("doubleValue"in e)return e.doubleValue;if("timestampValue"in e)return e.timestampValue;if("nullValue"in e)return null;if("bytesValue"in e)return e.bytesValue;if("referenceValue"in e)return e.referenceValue;if("geoPointValue"in e)return e.geoPointValue;if("arrayValue"in e)return(e.arrayValue?.values||[]).map(Jt);if("mapValue"in e){let t=e.mapValue?.fields||{};return Object.entries(t).reduce((r,[n,o])=>(r[n]=Jt(o),r),{})}}}function Ks(e){let t=e?.fields||{};return Object.entries(t).reduce((r,[n,o])=>(r[n]=Jt(o),r),{})}function Os(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||e===null||typeof e=="bigint"?String(e):JSON.stringify(e)}function un(e,t,r){Object.entries(t).forEach(([n,o])=>{typeof o>"u"||(e.request.headers[`${r}${Ps(n)}`]=Os(o))})}async function Rs({firestoreToken:e,serviceAccount:t,durableObjectNamespaceBinding:r,durableObjectShardCount:n}){if(e)return e;if(!t)throw new Error("Either firestoreToken or serviceAccount must be provided");return cn({serviceAccount:t,durableObjectNamespaceBinding:r,durableObjectShardCount:n})}async function xs({firestorePath:e,apiKey:t,firestoreToken:r,serviceAccount:n,durableObjectNamespaceBinding:o,durableObjectShardCount:a}){let s=await Rs({firestoreToken:r,serviceAccount:n,durableObjectNamespaceBinding:o,durableObjectShardCount:a}),i=await fetch(Hs(e,t),{headers:{authorization:`Bearer ${s}`}});if(i.status===404)return null;if(!i.ok)throw new Error("Failed to fetch api key from Firestore");let c=await i.json();return Ks(c)}function Dt({firestorePath:e,firestoreToken:t,serviceAccount:r,durableObjectNamespaceBinding:n,durableObjectShardCount:o=64,apiKeyHeader:a="x-api-key",apiKeyPrefix:s="",claimsHeaderPrefix:i="x-api-key-claim-",cacheTtl:c=60*60,blockedCacheTtl:u=60*60}){if(!e)throw new Error("firestorePath is required");if(!t&&!r)throw new Error("Either firestoreToken or serviceAccount must be provided");if(!n)throw new Error("durableObjectNamespaceBinding is required");let h=new oe({bindingName:n,shardCount:o});async function d(p){let g=await h.get(Wt(p));return g?g.value:null}async function l(p,g){await h.put({cacheKey:Wt(p),value:{status:"allowed",claims:g},ttlSeconds:c})}async function f(p){await h.put({cacheKey:Wt(p),value:{status:"blocked"},ttlSeconds:u})}return async(p,g)=>{let y=Ts({headers:p.request.headers,apiKeyHeader:a,apiKeyPrefix:s});if(!y)return Nt(p);let w=await d(y);if(w?.status==="allowed"&&w.claims)return p.state.apiKey=y,p.state.apiKeyClaims=w.claims,un(p,w.claims,i),g(p);if(w?.status==="blocked")return Nt(p);try{let b=await xs({firestorePath:e,apiKey:y,firestoreToken:t,serviceAccount:r,durableObjectNamespaceBinding:n,durableObjectShardCount:o});return b?(await l(y,b),p.state.apiKey=y,p.state.apiKeyClaims=b,un(p,b,i),g(p)):(await f(y),Nt(p))}catch{return vs(p)}}}function dn(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 Us(e){let t=e.split("."),r=JSON.parse(dn(t[0])),n=JSON.parse(dn(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 $t({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 h=new TextEncoder().encode([c.raw.header,c.raw.payload].join(".")),d=new Uint8Array(Array.from(c.signature).map(p=>p.charCodeAt(0))),l=await o();return(await Promise.all(l.map(async p=>{let g=await crypto.subtle.importKey("jwk",p,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",g,d,h)}))).some(p=>p)}async function i(c,u){if(c.request.method==="OPTIONS"||n)return u(c);if((c.request.headers.authorization||"").toLowerCase().startsWith("bearer")){let d=Us(c.request.headers.authorization.slice(7)),l=new Date(d.payload.exp*1e3),f=new Date(Date.now());return l<=f||!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 pn=P($()),ks={get:pn.default},ae=class{constructor({accountId:t,namespace:r,authEmail:n,authKey:o,ttl:a}){this.accountId=t,this.namespace=r,this.authEmail=n,this.authKey=o,this.ttl=a}getNamespaceUrl(){return new URL(`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/storage/kv/namespaces/${this.namespace}`)}getUrlForKey(t){return new URL(`${this.getNamespaceUrl()}/values/${t}`)}async list(t,r=10){let n=`${this.getNamespaceUrl()}/keys?prefix=${t}&limit=${r}`,o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});return o.ok?o.json():null}async get(t,r){let n=this.getUrlForKey(t),o=await fetch(n,{headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}});if(o.ok)switch(r){case"json":return o.json();case"stream":return o;case"arrayBuffer":return o.arrayBuffer();default:return o.text()}return null}async getWithMetadata(t,r){let[n,o]=await Promise.all([this.get(t,r),this.list(t)]),a=ks.get(o,"result.0.metadata",{});return{value:n,metadata:a}}async put(t,r,n={}){let o=this.getUrlForKey(t),a=new URLSearchParams;this.ttl&&a.append("expiration_ttl",this.ttl.toString());let s={"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey};o.search=a.toString();let i=new FormData;return i.append("value",r),i.append("metadata",JSON.stringify(n)),(await fetch(o.toString(),{method:"PUT",headers:s,body:r})).ok}async delete(t){let r=this.getUrlForKey(t);return fetch(r,{method:"DELETE",headers:{"X-Auth-Email":this.authEmail,"X-Auth-Key":this.authKey}})}};var x={methodsMethodsWithBody:["POST","PUT","PATCH"],http:{statusMessages:{404:"Not Found"}},mime:{css:"text/css",csv:"text/csv",html:"text/html",ico:"image/microsoft.vnd.icon",jpeg:"image/jpeg",js:"application/javascript",json:"application/json",png:"image/png",svg:"image/svg+xml",xml:"application/xml"}};function Is(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function Mt({kvAccountId:e,kvNamespace:t,kvAuthEmail:r,kvAuthKey:n,kvBasePath:o="",kvKey:a="{file}",defaultExtension:s="html",defaultIndexDocument:i,defaultErrorDocument:c,mime:u={},mode:h="rest"}){let d=new ae({accountId:e,namespace:t,authEmail:r,authKey:n,mode:h}),l={...x.mime,...u};return async f=>{let p=A.resolveParams(a,f.params),g=p===""&&i?i:Is(p,s),y=await d.get(o+g);!y&&c&&(y=await d.get(o+c)),y?(f.status=200,f.body=y,f.set("Content-Type",l[g.split(".").pop()]||"text/plain")):(f.status=404,f.body=x.http.statusMessages[404],f.set("Content-Type","text/plain"))}}var hn=P($());var qt={get:hn.default};function Ws(e,t,r){if(e==="/"&&r)return r;let n=e.split("/").pop();return n.split(".").pop()!==n?e:`${e}.${t}`}function Ns(e,t){let r=qt.get(e,"headers.if-none-match"),n=qt.get(t,"metadata.headers.etag");return r?r===n:!1}function Ft({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:Ws(c,n),h=await s(t+u);if(!h&&a&&(h=await s(t+a)),h)if(Ns(i.request,h))i.status=304;else{i.status=h.status,i.body=h.value;let d=qt.get(h,"metadata.headers",{});Object.keys(d).forEach(l=>{i.set(l,d[l])})}else i.status=404,i.body=x.http.statusMessages[404],i.set("Content-Type","text/plain")}}var fn=P(Ve());function Lt({accessKeyId:e,secretAccessKey:t,region:r,lambdaName:n}){let o=new fn.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(h=>{a.set(h,u[h])})}}var Kn=P($()),On=P(Ze());var Hn={get:Kn.default,set:On.default};function Ni(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function Ji(e){return e[Math.floor(Math.random()*e.length)]}function zt({sources:e=[]}){return async t=>{let r=Ji(e),n={method:t.request.method,headers:Ni(t.request.headers),redirect:"manual",cf:t.request.cf};if(x.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 Un=P($());var Xt={name:"@ahmadissa/cloudworker-proxy",version:"1.1.137",description:"An api gateway for cloudflare workers",license:"MIT",repository:{type:"git",url:"git+https://github.com/ahmadissa/cloudworker-proxy.git"},bugs:{url:"https://github.com/ahmadissa/cloudworker-proxy/issues"},homepage:"https://github.com/ahmadissa/cloudworker-proxy#readme",author:"Ahmad Issa",keywords:["cloudflare","workers","api","gateway","proxy"],main:"dist/index.js",files:["dist/**"],scripts:{build:"esbuild --bundle src/index.ts --format=cjs --outdir=dist --sourcemap --minify",lint:"eslint src",package:"bun install; npm run build",test:"npm run unit && npm run lint",public:"npm run package && npm publish","test:integration":"node integration/run.js",unit:"bun test","semantic-release":"semantic-release",prepare:"husky install"},release:{branches:["master"],plugins:["@semantic-release/commit-analyzer","@semantic-release/release-notes-generator",["@semantic-release/npm",{npmPublish:!1}],["@semantic-release/git",{assets:["docs","package.json"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}]]},dependencies:{aws4fetch:"1.0.13",build:"^0.1.4","cloudworker-router":"1.11.2",cookie:"0.4.1",jose:"^5.1.0","lodash.get":"4.4.2","lodash.set":"4.3.2",package:"^1.0.1",redaxios:"^0.5.1",shortid:"2.2.16"},devDependencies:{"@semantic-release/git":"^10.0.1","@types/jest":"^29.5.5","@types/mocha":"^10.0.1","@types/node":"^20.5.9","@typescript-eslint/eslint-plugin":"^6.6.0","@typescript-eslint/parser":"^6.6.0",bun:"1.0.3",dotenv:"8.2.0",esbuild:"^0.19.2",eslint:"7.13.0","eslint-config-airbnb-base":"14.2.1","eslint-config-prettier":"6.15.0","eslint-plugin-import":"2.22.1","eslint-plugin-prettier":"3.1.4","fetch-mock":"9.11.0",husky:"^8.0.3","node-fetch":"2.6.1",prettier:"2.1.2","semantic-release":"^22.0.4",typescript:"^5.2.2",wrangler:"^3.7.0"},directories:{example:"examples",test:"test"}};var ce=class{constructor({maxSize:t=10,maxSeconds:r=10,sink:n}){this.maxSize=t,this.maxSeconds=r,this.queue=[],this.sink=n,this.flushing=!1,this.timer=null}async push(t){return this.queue.push(t),this.queue.length>this.maxSize?this.flush():(this.timer||(this.timer=new Promise((r,n)=>{this.resolveTimer=r,this.rejectTimer=n,this.cancelationToken=setTimeout(async()=>{try{r(await this.flush())}catch(o){n(o)}},this.maxSeconds*1e3)})),this.timer)}async flush(){if(!this.flushing){this.flushing=!0;try{let t=this.queue.join(`
|
|
6
|
+
`);this.queue=[];let r=await this.sink(t);this.timer&&(clearTimeout(this.cancelationToken),this.resolveTimer(r))}catch(t){this.timer&&this.rejectTimer(t)}finally{this.timer=null,this.flushing=!1}}}};function Rn(e,t=".",r=""){return e instanceof Object?Object.keys(e).reduce((n,o)=>e[o]==null?n:{...n,...Rn(e[o],t,r+o+t)},{}):r.endsWith(t)?{[r.slice(0,r.length-1)]:e}:{[r]:e}}var Qe=Rn;var He=class{constructor(t){this.url=t.url,this.contentType=t.contentType,this.delimiter=t.delimiter,this.chunker=new ce({sink:this.sendMessage.bind(this),...t})}async log(t){let r=Qe(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 xn=P(Ve());var Ke=class{constructor(t){this.delimiter=t.delimiter,this.chunker=new ce({sink:this.sendMessage.bind(this),...t}),this.awsClient=new xn.AwsClient({accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,region:t.region}),this.streamName=t.streamName,this.region=t.region}async log(t){let r=Qe(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:Un.default};async function $i(e){return["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1?null:e.text()}function Yt(e){let t;switch(e.type){case"http":t=new He(e);break;case"kinesis":t=new Ke(e);break;default:throw new Error(`Log service type not supported: ${e.type}`)}return async(r,n)=>{r.state["logger-startDate"]=new Date;let o=await $i(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:Xt.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:Xt.version};r.event.waitUntil(t.log(s))}}}var xe=P(kn()),co=P($()),uo=P(Ze()),po=P(oo());async function or({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 ao="PBKDF2",ar="AES-GCM",fc="SHA-256",mc="raw";function yc(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 so(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 gc(e){return new TextEncoder().encode(e).buffer}function wc(e){return new TextDecoder().decode(e)}async function Ac(e){let t=new TextEncoder;return crypto.subtle.importKey(mc,t.encode(e),{name:ao},!1,["deriveKey"])}async function Sc(e,t){let r=await Ac(e),o=new TextEncoder().encode(t.replace(/_/g,"/").replace(/-/g,"+"));return crypto.subtle.deriveKey({name:ao,salt:o,iterations:1e3,hash:{name:fc}},r,{name:ar,length:256},!0,["encrypt","decrypt"])}async function bc(){let e=crypto.getRandomValues(new Uint8Array(8));return so(e)}async function Ec(e,t){let r=yc(t),n=r.slice(0,16),o=r.slice(16),a=await crypto.subtle.decrypt({name:ar,iv:n},e,o);return wc(a)}async function Cc(e,t){let r=crypto.getRandomValues(new Uint8Array(16)),n=await crypto.subtle.encrypt({name:ar,iv:r},e,gc(t)),o=new Uint8Array(n.byteLength+r.byteLength);return o.set(r,0),o.set(new Uint8Array(n),r.byteLength),so(o)}var de={decrypt:Ec,deriveAesGcmKey:Sc,encrypt:Cc,getSalt:bc};var fe={get:co.default,set:uo.default};function io({cookieHeader:e="",cookieName:t}){return xe.default.parse(e)[t]}function _c(e){return Object.keys(e).map(t=>`${t}=${encodeURIComponent(e[t])}`).join("&")}function vc(e=""){return e.split(",").indexOf("text/html")!==-1}function sr({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:h,oauth2Audience:d,oauth2Scopes:l=[],oauth2CallbackPath:f="/callback",oauth2CallbackType:p="cookie",oauth2LogoutPath:g="/logout",oauth2LoginPath:y="/login",oauth2ServerTokenPath:w="/oauth/token",oauth2ServerAuthorizePath:b="",oauth2ServerLogoutPath:K}){let O=new ae({accountId:n,namespace:o,authEmail:a,authKey:s,ttl:i}),ee=c,be=f,lt=p,ft=w,Me=b,mt=K,V=u,Ee=h,q=d,qe=g,_=y,_e=l.join("%20");async function Fe(m,H){let T=`${ee}${ft}`,R=await fetch(T,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:_c({code:m,grant_type:"authorization_code",client_id:V,client_secret:Ee,redirect_uri:H})});if(!R.ok)throw new Error("Authentication failed");let F=await R.json();return{...F,expires:Date.now()+F.expires_in*1e3}}async function Jo(m){if(io({cookieHeader:m.request.headers.cookie,cookieName:e})){let R=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${R}`,path:"/",maxAge:0}))}let T=Or(m);if(K){let R=encodeURIComponent(`${m.request.protocol}://${m.request.host}${T}`);m.set("Location",`${ee}${mt}?client_id=${V}&returnTo=${R}`)}else m.set("Location",T);m.status=302}async function Do(m){let H=m.request.href.split("?")[0],T=await Fe(m.request.query.code,H),R=po.default.generate(),F=await de.getSalt(),L=`${R}.${F}`,yt=await de.deriveAesGcmKey(R,F),te=await de.encrypt(yt,JSON.stringify(T));await O.put(R,te);let gt=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.status=302,lt==="query"?m.set("Location",`${m.request.query.state}?auth=${L}`):(m.set("Set-Cookie",xe.default.serialize(e,L,{httpOnly:t,domain:`.${gt}`,path:"/",maxAge:60*60*24*365})),m.set("Location",m.request.query.state))}async function $o(m,H){let[T,R]=H.split("."),F=await O.get(T);if(F){let L=await de.deriveAesGcmKey(T,R),yt=await de.decrypt(L,F),te=JSON.parse(yt);if(te.expires<Date.now()){te=await or({refresh_token:te.refresh_token,clientId:V,authDomain:ee,clientSecret:Ee});let gt=await de.encrypt(L,JSON.stringify(te));await O.put(T,gt)}m.state.accessToken=te.access_token,m.state.accessToken&&(m.request.headers.authorization=`bearer ${m.state.accessToken}`)}else{let L=m.request.hostname.match(/[^.]+\.[^.]+$/i)[0];m.set("Set-Cookie",xe.default.serialize(e,"",{domain:`.${L}`,maxAge:0}))}}function Or(m){let H=fe.get(m,"request.query.redirect-to");if(H)return H;let T=fe.get(m,"request.headers.referer");return T||"/"}async function Mo(m){if(m.request.method==="OPTIONS")m.status=200;else{let H=Or(m),T=encodeURIComponent(H||"/"),R=encodeURIComponent(`${m.request.protocol}://${m.request.host}${be}`);m.status=302,m.set("location",`${ee}${Me}/authorize?state=${T}&client_id=${V}&response_type=code&scope=${_e}&audience=${q}&redirect_uri=${R}`)}}async function qo(m,H){if(m.request.method==="OPTIONS")await H(m);else if(fe.get(m,"request.headers.authorization","").toLowerCase().startsWith("bearer "))fe.set(m,"state.access_token",m.request.headers.authorization.slice(7)),await H(m);else{let T=fe.get(m,"request.query.auth")||io({cookieHeader:m.request.headers.cookie,cookieName:e});if(T&&await $o(m,T),fe.get(m,"state.accessToken")||r)await H(m);else if(vc(m.request.headers.accept)){let F=encodeURIComponent(m.request.href),L=encodeURIComponent(`${m.request.protocol}://${m.request.host}${be}`);m.status=302,m.set("location",`${ee}${Me}/authorize?state=${F}&client_id=${V}&response_type=code&scope=${_e}&audience=${q}&redirect_uri=${L}`)}else m.status=403,m.body="Forbidden"}}return async(m,H)=>{switch(m.request.path){case be:await Do(m);break;case qe:await Jo(m);break;case _:await Mo(m);break;default:await qo(m,H)}}}var ho=P($());var Pc={get:ho.default};function Tc(e){let t={};return Object.keys(e).forEach(r=>{r.startsWith("cf")||(t[r]=e[r])}),t}function ir(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:Tc(n.request.headers),method:n.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(n.request.method)!==-1&&Pc.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 cr({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 lo=P($()),fo=P(Ze()),ur={get:lo.default,set:fo.default};function dr({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=ur.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),h=o(c,s.request.headers),d=ur.get(n,h,0);if(["HEAD","OPTIONS"].indexOf(s.request.method)===-1&&(d+=1),ur.set(n,h,d),r<d){s.status=429;return}a(c),await i(s)}}var mo=P(Ve());function Hc(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 pr({accessKeyId:e,secretAccessKey:t,bucket:r,region:n,endpoint:o,forcePathStyle:a,enableBucketOperations:s=!1}){let i=new mo.AwsClient({accessKeyId:e,region:n,secretAccessKey:t}),c=Hc(o,{region:n,bucket:r,forcePathStyle:a});return async u=>{if(u.params.file===void 0&&!s){u.status=404,u.body=x.http.statusMessages[404],u.set("Content-Type","text/plain");return}let h=u.params.file?A.resolveParams(`${c}/{file}`,u.params):c,d={};u.request.headers.range&&(d.range=u.request.headers.range);let l=await i.fetch(h,{method:u.method||u.request.method,headers:d});u.status=l.status,u.body=l.body;let f=A.instanceToJson(l.headers);Object.keys(f).forEach(p=>{u.set(p,f[p])})}}var hr;function yo(e){return new Uint8Array(e.split("").map(r=>r.charCodeAt(0)))}async function Kc(e){return hr||(hr=await crypto.subtle.importKey("raw",yo(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"])),hr}async function Oc(e,t){let r=await Kc(t),n=await crypto.subtle.sign({name:"HMAC"},r,yo(e));return btoa(String.fromCharCode.apply(null,new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function lr({secret:e}){return async(t,r)=>{let n=(t.request.path+t.request.search).replace(/([?|&]sign=[\w|-]+)/,"");if(await Oc(n,e)!==t.query.sign){t.status=403;return}await r(t)}}function fr({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 Rc(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),h=go(u,r),d=s.encode(h);await o.write(d)}await o.close()}function xc(e,t){return e.replace(/{{\$(\d)}}/g,(r,n)=>t[parseInt(n,10)])}function go(e,t){return t.reduce((r,n)=>r.replace(n.regex,(...o)=>xc(n.replace,o)),e)}function mr({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=go(a,r);else{let{readable:s,writable:i}=new TransformStream;Rc(a,i,r),n.body=s}}}async function Uc({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 kc=e=>(e=e.split("?")[0],e.replace(/\W/g,"").slice(0,100));function yr({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=kc(o.request.path);if((await Uc({projectID:e,API_KEY:t,token:s,siteKey:r,expectedAction:i})||0)<.5){o.status=409;return}await a(o)}}async function Ic({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 Wc=e=>{let t=e;try{t=new URL(e,"http://dummy").pathname}catch{}return t=t.split("?")[0]||"/",t.replace(/\W/g,"").slice(0,100)},Ue=(e,t)=>{if(e instanceof Headers)return e.get(t);let r=e[t]??e[t.toLowerCase()];return Array.isArray(r)?r[0]??null:r??null};function gr({secret:e,headerName:t="x-recaptcha-token",minScore:r=.5,requireActionMatch:n=!0}){return async(o,a)=>{let s=o.request?.req||o.request||o,i=s.headers??o.request?.headers??{},c=Ue(i,t)||Ue(i,"g-recaptcha-token")||null,h=Ue(i,"x-recaptcha-action")||Wc(o.request?.path||o.request?.url||s.url||"/"),d=Ue(i,"cf-connecting-ip")||Ue(i,"x-forwarded-for")||void 0,l=await Ic({secret:e,token:c,expectedAction:h,remoteip:d});if(!(l.score>=r&&l.ok)){let p={action:l.action,expectedAction:h,score:l.score??0,errors:l.errorCodes??[]};console.warn("[reCAPTCHA] failed:"+JSON.stringify(p)),o.status=409,o.set?.("Content-Type","application/json"),o.body=JSON.stringify({error:"reCAPTCHA verification failed"});return}await a(o)}}async function Nc({secret:e,token:t,remoteip:r}){if(!t)return{ok:!1,errorCodes:["missing-input-response"]};let n=new URLSearchParams({secret:e,response:t,...r?{remoteip:r}:{}}),a=await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:n})).json();return{ok:!!a.success,errorCodes:a["error-codes"]}}var ot=(e,t)=>{if(e instanceof Headers)return e.get(t);let r=e[t]??e[t.toLowerCase()];return Array.isArray(r)?r[0]??null:r??null};function wr({secret:e,headerName:t="x-recaptcha-token"}){return async(r,n)=>{let a=(r.request||r).headers||{},s=ot(a,t)||ot(a,"cf-turnstile-token")||null,i=ot(a,"cf-connecting-ip")||ot(a,"x-forwarded-for")||void 0,c=await Nc({secret:e,token:s,remoteip:i});if(!c.ok){let h={errors:c.errorCodes??[]};console.warn("[Turnstile] verification failed: "+JSON.stringify(h)),r.status=409,r.headers||=new Headers,r.headers.set("Content-Type","application/json"),r.body=JSON.stringify({error:"Turnstile verification failed"});return}await n(r)}}var Jc=e=>!new RegExp("(\b)(onS+)(s*)=|javascript|<(|/|[^/>][^>]+|/[^>][^>]+)>").test(e),Dc=(e,t,r)=>!(!Jc(t)||!r[e](t)),$c=e=>!(e===null||typeof e!="object"||Array.isArray(e)&&(!e[0]||typeof e[0]!="object")),at=(e,t)=>{let r=Object.keys(e);for(let n of r){if(!t[n])return console.error("key not allowed",n),!1;if(e[n]===null&&(e[n]=""),$c(e[n])){if(!at(e[n],t))return console.error("error validating key+validateObject:",n),!1}else if(!Dc(n,e[n],t))return console.error("error validating key+validateKeyValue:",n),!1}return!0},wo=e=>!(e==null||typeof e!="object"),Mc=(e,t)=>{let r=e.query;return wo(r)?at(r,t):!1},ke=(e,t)=>{let r=e.params;return r?wo(r)?at(r,t):!1:!0};async function qc(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return{};try{let t=await e.text();return JSON.parse(t)}catch{}return{}}function Ar({allowedKeys:e}){return async(r,n)=>{if(!e)return r.status=501,!1;if(!ke(r,e)||!Mc(r,e))return r.status=422,!1;let o=await qc(r.request);if(!at(o,e))return r.status=422,!1;await n(r)}}var ko=P($());var E=crypto,D=e=>e instanceof CryptoKey;var U=new TextEncoder,W=new TextDecoder,bp=2**32;function z(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}var Ao=e=>{let t=e;typeof t=="string"&&(t=U.encode(t));let r=32768,n=[];for(let o=0;o<t.length;o+=r)n.push(String.fromCharCode.apply(null,t.subarray(o,o+r)));return btoa(n.join(""))},N=e=>Ao(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var me=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var S=class extends me{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var J=class extends me{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},X=class extends me{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var st=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 it(e,t){return e.name===t}function Sr(e){return parseInt(e.name.slice(4),10)}function Gc(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Bc(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 bo(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!it(e.algorithm,"HMAC"))throw B("HMAC");let n=parseInt(t.slice(2),10);if(Sr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!it(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Sr(e.algorithm.hash)!==n)throw B(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!it(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");let n=parseInt(t.slice(2),10);if(Sr(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(!it(e.algorithm,"ECDSA"))throw B("ECDSA");let n=Gc(t);if(e.algorithm.namedCurve!==n)throw B(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Bc(e,r)}function Eo(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var M=(e,...t)=>Eo("Key must be ",e,...t);function br(e,t,...r){return Eo(`Key for the ${e} algorithm must be `,t,...r)}var Er=e=>D(e),C=["CryptoKey"];var Yc=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},ye=Yc;function Zc(e){return typeof e=="object"&&e!==null}function k(e){if(!Zc(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 ct=(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)},_o=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")}},ru=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=_o(i);a=u.startsWith("P-")?{name:"ECDH",namedCurve:u}:{name:u},s=c?[]:["deriveBits"];break}case"EdDSA":a={name:_o(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)},vo=(e,t,r)=>ru(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r);async function Cr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return vo(e,t,r)}var nu=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Er(t))throw new TypeError(br(e,t,...C,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${C.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},ou=(e,t,r)=>{if(!Er(t))throw new TypeError(br(e,t,...C));if(t.type==="secret")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},au=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?nu(e,t):ou(e,t,r)},Ne=au;function hu(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of n.crit){if(!a.has(s))throw new S(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}var ge=hu;var gu=Symbol();function ut(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 dt(e,t,r){if(D(t))return bo(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(M(t,...C));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(M(t,...C,"Uint8Array"))}var Q=e=>Math.floor(e.getTime()/1e3);var Au=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,pt=e=>{let t=Au.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 Cu=async(e,t,r)=>{let n=await dt(e,t,"sign");ct(e,n);let o=await E.subtle.sign(ut(e,n.algorithm),n,r);return new Uint8Array(o)},Ro=Cu;var we=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ye(this._protectedHeader,this._unprotectedHeader))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ge(J,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=n;if(typeof s!="string"||!s)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ne(s,t,"sign");let i=this._payload;a&&(i=U.encode(N(i)));let c;this._protectedHeader?c=U.encode(N(JSON.stringify(this._protectedHeader))):c=U.encode("");let u=z(c,U.encode("."),i),h=await Ro(s,t,u),d={signature:N(h),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 we(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function Ae(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Se=class{constructor(t={}){if(!k(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:Ae("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Ae("setNotBefore",Q(t))}:this._payload={...this._payload,nbf:Q(new Date)+pt(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Ae("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Ae("setExpirationTime",Q(t))}:this._payload={...this._payload,exp:Q(new Date)+pt(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Q(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Ae("setIssuedAt",Q(t))}:this._payload={...this._payload,iat:Ae("setIssuedAt",t)},this}};var De=class extends Se{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new Je(U.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new X("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var Tu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Tu="jose/v5.1.0");var xo=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,h=a[i];c[u]=u in c&&typeof h=="object"?r(c[u],h,u=="headers"):h}return c}function n(o,a,s,i,c){var u=typeof o!="string"?(a=o).url:o,h={config:a},d=r(t,a),l={};i=i||d.data,(d.transformRequest||[]).map(function(f){i=f(i,d.headers)||i}),d.auth&&(l.authorization=d.auth),i&&typeof i=="object"&&typeof i.append!="function"&&typeof i.text!="function"&&(i=JSON.stringify(i),l["content-type"]="application/json");try{l[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,l,!0),credentials:d.withCredentials?"include":c}).then(function(f){for(var p in f)typeof f[p]!="function"&&(h[p]=f[p]);return d.responseType=="stream"?(h.data=f.body,h):f[d.responseType||"text"]().then(function(g){h.data=g,h.data=JSON.parse(g)}).catch(Object).then(function(){return(d.validateStatus?d.validateStatus(f.status):f.ok)?h:Promise.reject(h)})})}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 Ou=e=>{if(!e)return!1;let t=JSON.parse(atob(e.split(".")[1])),r=Math.floor(Date.now()/1e3);return t.exp>r-600},ht=async(e,t)=>{let r=await GCP_INVOKER_TOKEN.get(t);if(Ou(r))return r;let n=await Cr(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 De(a).setProtectedHeader({alg:"RS256",typ:"JWT"}).sign(n),i=await xo.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 Uo={get:ko.default};function vr({project_id:e,region:t,functionName:r,serviceAccount:n,allowedKeys:o}){return async(a,s)=>{if(o&&a.params&&!ke(a,o))return a.status=422,a.body=JSON.stringify({error:"Invalid params"}),!1;let i=Uo.get(a,"request.query",{}),c=new URLSearchParams(i).toString(),u=`https://${t}-${e}.cloudfunctions.net/${r}`,h=a.request.path,d=`https://${t}-${e}.cloudfunctions.net/${r}${h||""}${c?`?${c}`:""}`,l=await ht(n,u),f=new Headers(a.request.headers);f.set("X-Serverless-Authorization",`Bearer ${l}`);let p=a.event.cf||{},g={"X-Geo-Country":p.country,"X-Geo-City":p.city,"X-Geo-Latitude":p.latitude,"X-Geo-Longitude":p.longitude,"X-Geo-Timezone":p.timezone,"X-Geo-Region":p.region,"X-Geo-PostalCode":p.postalCode,"X-Geo-RegionCode":p.regionCode,"X-Geo-EU-Country":p.isEUCountry?"1":"0"};for(let[K,O]of Object.entries(g))O!==void 0&&f.set(K,O);let y={headers:f,method:a.request.method,redirect:"manual"};if(x.methodsMethodsWithBody.indexOf(a.request.method)!==-1&&Uo.get(a,"event.request.body")){let K=a.event.request.clone();y.body=K.body}let w=await fetch(d,y);a.body=w.body,a.status=w.status;let b=A.instanceToJson(w.headers);A.mergeHeaders(b,a),await s(a)}}var Ru=P($());function Pr({domain:e,serviceAccount:t,allowedKeys:r}){return async(n,o)=>{if(r&&n.params&&!ke(n,r))return n.status=422,n.body=JSON.stringify({error:"Invalid params"}),!1;let a=new URL(n.event.request.url),s=`${e}${a.pathname}${a.search}`,i=await ht(t,e),c=new Headers(n.request.headers);c.set("X-Serverless-Authorization",`Bearer ${i}`),c.set("X-Token",c.get("authorization")||"N/A"),c.delete("authorization");let u=n.event.cf||{},h={"X-Geo-Country":u.country,"X-Geo-City":u.city,"X-Geo-Latitude":u.latitude,"X-Geo-Longitude":u.longitude,"X-Geo-Timezone":u.timezone,"X-Geo-Region":u.region,"X-Geo-PostalCode":u.postalCode,"X-Geo-RegionCode":u.regionCode,"X-Geo-EU-Country":u.isEUCountry?"1":"0"};for(let[p,g]of Object.entries(h))g!==void 0&&c.set(p,g);let d={method:n.request.method,headers:c,redirect:"manual"};if(x.methodsMethodsWithBody.includes(n.request.method)){let p=n.event.request.clone();d.body=p.body}let l=await fetch(s,d),f=new Headers(l.headers);f.delete("content-length"),f.delete("transfer-encoding"),n.status=l.status,A.mergeHeaders(A.instanceToJson(f),n),n.body=l.body,await o(n)}}function Tr({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 xu(e){if(["POST","PATCH","PUT","DELETE"].indexOf(e.method)===-1)return"";try{return await e.text()}catch{return""}}function Uu(e){return new TextEncoder().encode(e).length}function Io(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 Hr({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 Io(t,e,a);let s=await xu(t.request),i=typeof s=="string"?Uu(s):0;if(i>e)return Io(t,e,i);await r(t)}}var Wo={basicAuth:Pt,cache:Ot,cors:Rt,geoDecorator:xt,firestoreApiKey:Dt,jwt:$t,kvStorage:Mt,kvStorageBinding:Ft,lambda:Lt,loadbalancer:zt,logger:Yt,oauth2:sr,origin:ir,rateLimit:dr,response:cr,s3:pr,signature:lr,split:fr,transform:mr,recaptcha:yr,recaptchaV3:gr,turnstileVerify:wr,userInputValidation:Ar,cloudfunction:vr,gcpCloudrun:Pr,headers:Tr,bodySizeLimit:Hr};function ku(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}function Iu(e){return e.storage}function Wu(e){let t=e.match(/^\/cache\/(.+)$/);return t?decodeURIComponent(t[1]):null}var $e=class{constructor(t,r){this.state=t,this.env=r}async fetch(t){let r=new URL(t.url),n=Wu(r.pathname);if(!n)return new Response("Not Found",{status:404});let o=Iu(this.state);if(t.method==="GET"){let a=await o.get(n);return a?a.expiresAt<=Date.now()?(await o.delete(n),new Response(null,{status:404})):ku(a):new Response(null,{status:404})}if(t.method==="PUT"){let a=await t.json(),s=Number(a.ttlSeconds||0);return await o.put(n,{value:a.value,expiresAt:Date.now()+s*1e3}),new Response(null,{status:204})}return t.method==="DELETE"?(await o.delete(n),new Response(null,{status:204})):new Response("Method Not Allowed",{status:405})}};function Nu(e){return t=>{let r=e(t);return async(n,o)=>(n.upgradedByProxy||(Kt(n),n.upgradedByProxy=!0),r(n,o))}}var Kr=class{constructor(t=[],r={}){this.router=new No.default,t.forEach(n=>{let o=r[n.handlerName]||Wo[n.handlerName];if(!o)throw new Error(`Handler ${n.handlerName} is not supported`);let a=Nu(o);this.router.add(n,a(n.options||{}))})}async resolve(t){let r=t;return r.cf=r.request?.cf||{},this.router.resolve(r)}};module.exports=Kr;module.exports.ApiKeyCacheDurableObject=$e;
|
|
8
8
|
/*! Bundled license information:
|
|
9
9
|
|
|
10
10
|
aws4fetch/dist/aws4fetch.umd.js:
|