@adonix.org/cloud-spark 0.0.187 → 0.0.189

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  # Cloud⚡️Spark
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@adonix.org/cloud-spark.svg?color=blue)](https://www.npmjs.com/package/@adonix.org/cloud-spark)
4
- [![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/adonix-org/cloud-spark/blob/main/LICENSE)
4
+ [![Apache 2.0 License](https://badges.adonix.org/License/Apache%202.0?color=blue)](https://github.com/adonix-org/cloud-spark/blob/main/LICENSE)
5
5
  [![Build](https://github.com/adonix-org/cloud-spark/actions/workflows/build.yml/badge.svg)](https://github.com/adonix-org/postrise/actions/workflows/build.yml)
6
6
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=alert_status)](https://sonarcloud.io/summary/overall?id=adonix-org_cloud-spark&branch=main)
7
7
  [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=security_rating)](https://sonarcloud.io/summary/overall?id=adonix-org_cloud-spark&branch=main)
@@ -41,7 +41,7 @@ class HelloWorld extends BasicWorker {
41
41
  export default HelloWorld.ignite();
42
42
  ```
43
43
 
44
- :computer: Now run your worker locally
44
+ :computer: Now to run the worker locally:
45
45
 
46
46
  ```bash
47
47
  wrangler dev
@@ -56,7 +56,7 @@ And it's ready on http://localhost:8787
56
56
  As shown in the [Quickstart](#rocket-quickstart), BasicWorker is the base class for building Cloudflare Workers with CloudSpark. It handles common tasks, including:
57
57
 
58
58
  - Dispatching incoming HTTP requests to the corresponding handler (GET, POST, PUT, etc.).
59
- - Providing defaults for standard HTTP behavior, such as HEAD requests and OPTIONS responses.
59
+ - Providing defaults for standard HTTP behavior, such as HEAD and OPTIONS requests.
60
60
  - Ensuring type safety and consistent response formatting.
61
61
  - Support for built-in and custom middleware.
62
62
  - Catching unhandled errors.
@@ -90,7 +90,7 @@ export class MyWorker extends BasicWorker {
90
90
  * If a requested method is not listed, the response is:
91
91
  * 405 Method Not Allowed
92
92
  *
93
- * If an allowed method isn’t implemented, the response is:
93
+ * If an allowed method is not implemented, the response is:
94
94
  * GET or HEAD: 404 Not Found
95
95
  * All other methods: 501 Not Implemented
96
96
  *
@@ -380,7 +380,7 @@ class ChatWorker extends RouteWorker {
380
380
  /**
381
381
  * Handles WebSocket upgrade requests.
382
382
  *
383
- * Expects a DurableObject binding named CHAT
383
+ * Expects a DurableObject binding named CHAT
384
384
  * in wrangler.jsonc
385
385
  */
386
386
  protected upgrade(params: PathParams): Promise<Response> {
@@ -388,7 +388,7 @@ class ChatWorker extends RouteWorker {
388
388
  const chat = this.env.CHAT;
389
389
 
390
390
  /**
391
- * Request has already been validated by the
391
+ * Request has already been validated by the
392
392
  * WebSocket middleware.
393
393
  */
394
394
  return chat.get(chat.idFromName(room)).fetch(this.request);
@@ -403,6 +403,80 @@ export default ChatWorker.ignite();
403
403
 
404
404
  ### Custom
405
405
 
406
+ Create custom middleware by implementing the [Middleware](https://github.com/adonix-org/cloud-spark/blob/main/src/interfaces/middleware.ts) interface and its single _handle_ method, then register it with your worker. Within your middleware, you can inspect requests and modify responses or short-circuit processing entirely.
407
+
408
+ Here is a simple example:
409
+
410
+ ```ts
411
+ import { BadRequest, CopyResponse, Middleware, Worker } from "@adonix.org/cloud-spark";
412
+
413
+ /**
414
+ * Custom middleware example.
415
+ *
416
+ * Demonstrates several key middleware capabilities:
417
+ * • Options via constructor parameters.
418
+ * • Inspection of the incoming request.
419
+ * • Short-circuiting by returning a response directly.
420
+ * • Modifying outgoing responses dispatched by the worker.
421
+ */
422
+ class PoweredBy implements Middleware {
423
+ /**
424
+ * Optional constructor parameter to customize the "X-Powered-By" header.
425
+ */
426
+ constructor(private readonly name = "CloudSpark") {}
427
+
428
+ public async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {
429
+ /**
430
+ * Extract the User-Agent header from the request.
431
+ */
432
+ const userAgent = worker.request.headers.get("User-Agent")?.trim();
433
+
434
+ /**
435
+ * If the User-Agent is missing, short-circuit by directly
436
+ * returning 400 Bad Request.
437
+ */
438
+ if (!userAgent) {
439
+ return new BadRequest(`Missing User-Agent`).response();
440
+ }
441
+
442
+ /**
443
+ * Calls the next middleware or worker dispatch method.
444
+ */
445
+ const response = await next();
446
+
447
+ /**
448
+ * Wrap the response in a mutable copy.
449
+ */
450
+ const copy = new CopyResponse(response);
451
+
452
+ /**
453
+ * Append custom headers to the response.
454
+ */
455
+ copy.setHeader("X-User-Agent", userAgent);
456
+ copy.setHeader("X-Powered-By", this.name);
457
+ copy.setHeader("X-Processed-At", new Date().toUTCString());
458
+
459
+ /**
460
+ * Return the modified response.
461
+ */
462
+ return copy.response();
463
+ }
464
+ }
465
+
466
+ /**
467
+ * Factory function for registering the middleware, with an optional
468
+ * name parameter. Workers interact with the `Middleware` interface,
469
+ * and not the concrete implementation.
470
+ *
471
+ * Example:
472
+ * this.use(poweredby());
473
+ * this.use(poweredby("My Project Name"));
474
+ */
475
+ export function poweredby(name?: string): Middleware {
476
+ return new PoweredBy(name);
477
+ }
478
+ ```
479
+
406
480
  <br>
407
481
 
408
482
  ## :left_right_arrow: Web Sockets
package/dist/index.d.ts CHANGED
@@ -1036,9 +1036,9 @@ declare class R2ObjectStream extends OctetStream {
1036
1036
  * This function normalizes a Cloudflare R2 `R2Range` into the shape expected
1037
1037
  * by `OctetStream`. It handles the following cases:
1038
1038
  *
1039
- * - No range provided returns `{ size }` (full content).
1040
- * - `suffix` range calculates the offset and length from the end of the file.
1041
- * - Explicit `offset` and/or `length` passed through as-is.
1039
+ * - No range provided: returns `{ size }` (full content).
1040
+ * - `suffix` range: calculates the offset and length from the end of the file.
1041
+ * - Explicit `offset` and/or `length`: passed through as-is.
1042
1042
  *
1043
1043
  * @param size - The total size of the file/object.
1044
1044
  * @param range - Optional range to extract (from R2). Can be:
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{StatusCodes as h}from"http-status-codes";import Ie from"cache-control-parser";var R={parse:Ie.parse,stringify:Ie.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var F=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(F||{}),{GET:p,PUT:tr,HEAD:O,POST:rr,PATCH:sr,DELETE:or,OPTIONS:B}=F;var He={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};function z(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function C(t){return typeof t=="string"}function E(t){return typeof t=="number"&&!Number.isNaN(t)}function Le(t){return typeof t=="boolean"}function ve(t){if(typeof t!="object"||t===null)throw new TypeError("CacheInit must be an object.");let{name:e,getKey:r}=t;yt(e),_t(r)}function yt(t){if(t!==void 0&&!C(t))throw new TypeError("Cache name must be a string.")}function _t(t){if(t!==void 0&&typeof t!="function")throw new TypeError("getKey must be a function.")}function We(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}function x(t,e){return t<e?-1:t>e?1:0}function Pe(t){let e=new URL(t.url),r=new URLSearchParams([...e.searchParams.entries()].sort(([s],[o])=>x(s,o)));return e.search=r.toString(),e.hash="",e}function Er(t){let e=new URL(t.url);return e.search="",e.hash="",e}var j=class{rules=[];use(...e){return this.rules.push(...e),this}execute(e,r){return this.rules.reduceRight((o,i)=>()=>i.apply(e,o),()=>r())()}};import{StatusCodes as It}from"http-status-codes";var n={ACCEPT:"accept",ACCEPT_ENCODING:"accept-encoding",ACCEPT_LANGUAGE:"accept-language",ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",AUTHORIZATION:"authorization",CACHE_CONTROL:"cache-control",CONNECTION:"connection",CONTENT_DISPOSITION:"content-disposition",CONTENT_ENCODING:"content-encoding",CONTENT_LANGUAGE:"content-language",CONTENT_LENGTH:"content-length",CONTENT_RANGE:"content-range",CONTENT_TYPE:"content-type",CONTENT_MD5:"content-md5",COOKIE:"cookie",ETAG:"etag",IF_MATCH:"if-match",IF_MODIFIED_SINCE:"if-modified-since",IF_NONE_MATCH:"if-none-match",IF_UNMODIFIED_SINCE:"if-unmodified-since",LAST_MODIFIED:"last-modified",ORIGIN:"origin",RANGE:"range",SET_COOKIE:"set-cookie",VARY:"vary",ACCESS_CONTROL_ALLOW_CREDENTIALS:"access-control-allow-credentials",ACCESS_CONTROL_ALLOW_HEADERS:"access-control-allow-headers",ACCESS_CONTROL_ALLOW_METHODS:"access-control-allow-methods",ACCESS_CONTROL_ALLOW_ORIGIN:"access-control-allow-origin",ACCESS_CONTROL_EXPOSE_HEADERS:"access-control-expose-headers",ACCESS_CONTROL_MAX_AGE:"access-control-max-age",SEC_WEBSOCKET_VERSION:"sec-websocket-version",UPGRADE:"upgrade",INTERNAL_VARIANT_SET:"internal-variant-set"},ke=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],Me=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function f(t,e,r){let s=Array.isArray(r)?r:[r],o=Array.from(new Set(s.map(i=>i.trim()))).filter(i=>i.length).sort(x);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function $(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let i=d(t,e).concat(s.map(a=>a.trim()));f(t,e,i)}function d(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(x)}function Ae(t,e){for(let r of e)t.delete(r)}var Ht="https://vary",Lt="*";function De(t,e){if(e.status!==It.OK||t.method!==p||t.headers.has(n.AUTHORIZATION)||t.headers.has(n.COOKIE)||y(t.headers)["no-store"]||!e.headers.has(n.CACHE_CONTROL))return!1;let s=y(e.headers),o=s["s-maxage"]??s["max-age"];if(o===void 0||o===0||s["no-store"]||s["no-cache"]||s.private||e.headers.has(n.SET_COOKIE)||Te(e).includes(Lt))return!1;if(e.headers.has(n.INTERNAL_VARIANT_SET))throw new Error("Found conflicting vary header.");if(e.headers.has(n.CONTENT_RANGE))throw new Error("Found content-range header on 200 OK. Must use 206 Partial Content");return!0}function y(t){return R.parse(t.get(n.CACHE_CONTROL)??"")}function Te(t){return _(d(t.headers,n.VARY))}function _(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(x);return Array.from(new Set(e))}function I(t,e,r){let s=[],o=_(e);for(let a of o){let c=t.headers.get(a);c!==null&&s.push([a,vt(a,c)])}let i=Wt(JSON.stringify([r.toString(),s]));return new URL(i,Ht).toString()}function vt(t,e){switch(t.toLowerCase()){case n.ACCEPT:case n.ACCEPT_LANGUAGE:case n.ORIGIN:return e.toLowerCase();default:return e}}function Wt(t){let e=new TextEncoder().encode(t),r="";for(let s of e)r+=String.fromCodePoint(s);return btoa(r).replaceAll("+","-").replaceAll("/","_").replace(/={1,2}$/,"")}var Pt=/^bytes=(\d{1,12})-(\d{0,12})$/,Ge="W/",Ve="*";function Ue(t){let e=t.headers.get(n.RANGE);if(!e)return;let r=Pt.exec(e);if(!r)return;let s=Number(r[1]),o=r[2]===""?void 0:Number(r[2]);return o===void 0?{start:s}:{start:s,end:o}}function Ke(t,e){return t.length>0&&!Fe(t,e,Ve)}function qe(t,e){return Fe(t,Be(e),Ve)}function Fe(t,...e){return t.some(r=>e.includes(r))}function X(t){if(!C(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Be(t){return t.startsWith(Ge)?t.slice(2):t}function Oe(t){return{ifMatch:d(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:d(t,n.IF_NONE_MATCH).map(Be),ifModifiedSince:t.get(n.IF_MODIFIED_SINCE),ifUnmodifiedSince:t.get(n.IF_UNMODIFIED_SINCE)}}function ze(t){let{ifNoneMatch:e,ifMatch:r,ifModifiedSince:s,ifUnmodifiedSince:o}=Oe(t);return e.length>0||r.length>0||s!==null||o!==null}function je(t){let e=t.get(n.CONTENT_LENGTH);if(e===null||e.trim()==="")return;let r=Number(e);if(E(r))return r}var Y=class{async apply(e,r){let s=y(e.request.headers);if(!s["no-store"]&&!((s["no-cache"]||s["max-age"]===0)&&!ze(e.request.headers)))return r()}};import{getReasonPhrase as Gt,StatusCodes as g}from"http-status-codes";var kt=new Set(Object.values(F));function be(t){return C(t)&&kt.has(t)}function Mt(t){return Array.isArray(t)&&t.every(be)}function b(t){if(!Mt(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}var $e="upgrade",Xe="websocket";import{getReasonPhrase as Dt,StatusCodes as u}from"http-status-codes";var D="utf-8";function Ye(t){if(typeof t!="object"||t===null)throw new TypeError("OctetStreamInit must be an object.");let e=t,r=e.size;if(!E(r)||r<0||!Number.isInteger(r))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(r)}).`);let s=e.offset??0;if(!E(s)||s<0||s>r||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}).`);let o=e.length??r-s;if(!E(o)||o<0||s+o>r||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function G(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var xe=class{headers=new Headers;status=u.OK;statusText;webSocket;mediaType=G("text/plain",D);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??Dt(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){f(this.headers,e,r)}mergeHeader(e,r){$(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===u.NO_CONTENT?Ae(this.headers,Me):this.status===u.NOT_MODIFIED&&Ae(this.headers,ke)}},Ne=class extends xe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,R.stringify(this.cache))}},m=class extends Ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=[u.NO_CONTENT,u.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},V=class extends m{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},H=class extends m{constructor(e){super(),this.status=u.NOT_MODIFIED,this.headers=new Headers(e.headers)}},U=class extends m{constructor(e=null,r,s=u.OK){super(e,r),this.status=s}},J=class extends U{constructor(e={},r,s=u.OK){super(JSON.stringify(e),r,s),this.mediaType=G("application/json",D)}},Je=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/html",o)}},Ze=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/plain",o)}},we=class t extends m{constructor(e,r,s){Ye(r),super(e,s),this.mediaType="application/octet-stream";let o=t.normalizeInit(r),{size:i,offset:a,length:c}=o;t.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${a}-${a+c-1}/${i}`),this.status=u.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${c}`)}static normalizeInit(e){let{size:r}=e,s=e.offset??0,o=e.length??r-s;return s===0&&o===0&&r>0&&(o=1),{size:r,offset:s,length:o}}static isPartial(e){return e.size===0?!1:!(e.offset===0&&e.length===e.size)}},Qe=class t extends we{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=R.parse(e.httpMetadata.cacheControl)),super(e.body,t.computeRange(e.size,e.range),s),this.setHeader(n.ETAG,e.httpEtag),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType)}static computeRange(e,r){if(!r)return{size:e};if("suffix"in r){let s=Math.max(0,e-r.suffix),o=e-s;return{size:e,offset:s,length:o}}return{size:e,...r}}},et=class extends m{constructor(e){super(),this.status=u.SWITCHING_PROTOCOLS,this.webSocket=e}},L=class extends m{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},Z=class extends m{constructor(e){let r=Array.from(new Set([p,O,...e.getAllowedMethods()]));b(r),super(),this.status=u.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var l=class extends J{constructor(r,s){let o={status:r,error:Gt(r),details:s??""};super(o,R.DISABLE,r);this.details=s}},K=class extends l{constructor(e){super(g.BAD_REQUEST,e)}},tt=class extends l{constructor(e){super(g.UNAUTHORIZED,e)}},rt=class extends l{constructor(e){super(g.FORBIDDEN,e)}},A=class extends l{constructor(e){super(g.NOT_FOUND,e)}},v=class extends l{constructor(e){let r=e.getAllowedMethods();b(r),super(g.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},W=class extends l{constructor(e){super(g.PRECONDITION_FAILED,e)}},Q=class extends l{constructor(){super(g.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13")}},ee=class extends l{constructor(e){super(g.INTERNAL_SERVER_ERROR,e)}},ye=class extends l{constructor(e){super(g.NOT_IMPLEMENTED,e)}},N=class extends ye{constructor(e){super(`${e.request.method} method not implemented.`)}},st=class extends l{constructor(e){super(g.SERVICE_UNAVAILABLE,e)}};import{StatusCodes as Vt}from"http-status-codes";var P=class{async apply(e,r){let s=await r();if(!s||s.status!==Vt.OK)return s;let o=this.getHeader(s);if(o===void 0)return s;let i=Oe(e.request.headers);return this.response(s,o,i)}};var te=class extends P{getHeader(e){return e.headers.get(n.ETAG)??void 0}},re=class extends te{async response(e,r,s){return Ke(s.ifMatch,r)?new W(`ETag: ${r}`).response():e}},se=class extends te{async response(e,r,s){if(s.ifNoneMatch.length===0)return e;if(qe(s.ifNoneMatch,r))return new H(e).response()}};var oe=class{async apply(e,r){if(e.request.method===p)return r();if(e.request.method===O){let s=await r();return s?new L(s).response():void 0}}};var ne=class extends P{getHeader(e){return X(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=X(s.ifModifiedSince);if(o===void 0)return e;if(r<=o)return new H(e).response()}},ae=class extends ne{async response(e,r,s){let o=X(s.ifUnmodifiedSince);return o===void 0?e:r>o?new W(`Last-Modified: ${new Date(r).toUTCString()}`).response():e}};import{StatusCodes as Ut}from"http-status-codes";var ce=class{async apply(e,r){let s=Ue(e.request);if(s&&(s.start!==0||s.end===0))return;let o=await r();if(!o||o.status!==Ut.OK||!s||s.end===void 0)return o;let i=je(o.headers);if(i&&s.end===i-1)return o}};var pe=class{async apply(e,r){let s=e.request.headers;if(!s.has(n.AUTHORIZATION)&&!s.has(n.COOKIE))return r()}};var ue=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var T=class t extends m{_isModified=!1;constructor(e){let r=_(e);if(r.length===0)throw new Error("The filtered vary array is empty.");super(),this.setHeader(n.INTERNAL_VARIANT_SET,r)}static new(e){return new t(_(e))}static restore(e){if(!t.isVariantResponse(e))throw new Error("The source response is not a variant response");let r=t.new(d(e.headers,n.INTERNAL_VARIANT_SET)),s=e.headers.get(n.CACHE_CONTROL);return s&&(r.cache=R.parse(s)),r}get vary(){return d(this.headers,n.INTERNAL_VARIANT_SET)}get isModified(){return this._isModified}append(e){let r=this.vary.length;this.mergeHeader(n.INTERNAL_VARIANT_SET,_(e)),this._isModified=this.vary.length!==r}static isVariantResponse(e){return e.headers.has(n.INTERNAL_VARIANT_SET)}expireAfter(e){let r=y(e.headers),s=r["s-maxage"]??r["max-age"];if(s===void 0)return;let o=this.cache?.["s-maxage"];(o===void 0||s>o)&&(this.cache={"s-maxage":s},this._isModified=!0)}};var de=class{init;constructor(e){let{name:r,getKey:s=Pe}=e;this.init={name:r?.trim()||void 0,getKey:s}}async handle(e,r){let s=this.init.name?await caches.open(this.init.name):caches.default,i=await new j().use(new Y).use(new oe).use(new ue).use(new pe).use(new ce).use(new ie).use(new se).use(new ae).use(new re).execute(e,()=>this.getCached(s,e.request));if(i)return i;let a=await r();return e.ctx.waitUntil(this.setCached(s,e.request,a)),a}async getCached(e,r){let s=this.getCacheKey(r),o=await e.match(s.toString());if(!o)return;if(!T.isVariantResponse(o))return o;let i=T.restore(o).vary,a=I(r,i,s);return e.match(a)}async setCached(e,r,s){if(!De(r,s))return;let o=this.getCacheKey(r),i=s.clone(),a=Te(i),c=await e.match(o),wt=c&&T.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let S=T.new(a);S.expireAfter(i),await e.put(o,await S.response()),await e.put(I(r,S.vary,o),i);return}if(wt){let S=T.restore(c);S.expireAfter(i),a.length>0&&(S.append(a),S.isModified&&await e.put(o,await S.response())),await e.put(I(r,S.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let q=T.new(a);q.expireAfter(c),q.expireAfter(i),await e.put(o,await q.response()),await e.put(I(r,q.vary,o),i),await e.put(I(r,[],o),c)}getCacheKey(e){let r=this.init.getKey(e);return We(r),r.hash="",r}};function Qs(t={}){return ve(t),new de(t)}function nt(t){if(t===void 0)return;if(typeof t!="object"||t===null)throw new TypeError("CorsInit must be an object.");let e=t;if(e.allowedOrigins!==void 0&&!z(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!z(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!z(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!Le(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!E(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var le="*",it=[h.SWITCHING_PROTOCOLS,h.CONTINUE,h.PROCESSING,h.EARLY_HINTS,h.MOVED_PERMANENTLY,h.MOVED_TEMPORARILY,h.SEE_OTHER,h.TEMPORARY_REDIRECT,h.PERMANENT_REDIRECT],at={allowedOrigins:[le],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*He.Minute};function ct(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Kt(s.headers,e),Ft(s.headers,r),qt(s.headers,r)),s.response()}function pt(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Bt(s.headers,r)),s.response()}function ut(t,e){_e(e)||$(t,n.VARY,n.ORIGIN)}function dt(t,e,r){if(_e(e)){f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,le);return}e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r)}function lt(t,e,r){e.allowCredentials&&(_e(e)||e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function Kt(t,e){let r=e.getAllowedMethods();b(r),f(t,n.ACCESS_CONTROL_ALLOW_METHODS,r)}function qt(t,e){let r=Math.max(0,Math.floor(e.maxAge));f(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function Ft(t,e){f(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function Bt(t,e){f(t,n.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function _e(t){return t.allowedOrigins.includes(le)}function ft(t){t.delete(n.ACCESS_CONTROL_MAX_AGE),t.delete(n.ACCESS_CONTROL_ALLOW_ORIGIN),t.delete(n.ACCESS_CONTROL_ALLOW_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_METHODS),t.delete(n.ACCESS_CONTROL_EXPOSE_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_CREDENTIALS)}function mt(t){let{status:e,headers:r}=t;return!!(it.includes(e)||r.has(n.UPGRADE))}function ht(t){let e=t.headers.get(n.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}var fe=class{config;constructor(e){this.config={...at,...e}}async handle(e,r){let s=await r();return e.request.method===B?ct(s,e,this.config):mt(s)?s:pt(s,e,this.config)}};function Ro(t){return nt(t),new fe(t)}import{match as zt}from"path-to-regexp";function Ct(t){return d(t,n.CONNECTION).some(e=>e.toLowerCase()===$e)}function Et(t){return d(t,n.UPGRADE).some(e=>e.toLowerCase()===Xe)}function gt(t){return t.get(n.SEC_WEBSOCKET_VERSION)?.trim()==="13"}var me=class{constructor(e){this.path=e}handle(e,r){if(e.request.method!==p||!this.isMatch(e.request))return r();let s=e.request.headers;return Ct(s)?Et(s)?gt(s)?r():new Q().response():new K("Missing or invalid 'Upgrade' header").response():new K("Missing or invalid 'Connection' header").response()}isMatch(e){return zt(this.path)(new URL(e.url).pathname)!==!1}};function Lo(t="/"){return new me(t)}function jt(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function St(t){return C(t)?t.length>0:jt(t)?t.byteLength>0:!1}function Rt(t){if(t===null||typeof t!="object")throw new TypeError("WebSocket attachment must be an object");try{JSON.stringify(t)}catch{throw new TypeError("WebSocket attachment is not serializable")}}var he=class t{server;customListeners={};constructor(e){this.server=e}addEventListener(e,r,s){if(t.isCustomEvent(e)){let o=this.customListeners[e];o||(o=[],this.customListeners[e]=o),o.push(r)}else{let o=e==="close"?{...s,once:!0}:s;this.server.addEventListener(e,r,o)}}removeEventListener(e,r){if(t.isCustomEvent(e)){let s=this.customListeners[e];if(s){let o=s.indexOf(r);o!==-1&&s.splice(o,1)}}else this.server.removeEventListener(e,r)}dispatch(e,r,s=!1){let o=this.customListeners[e]?.slice()??[];s&&(this.customListeners[e]=[]);for(let i of o)i(r)}warn(e){this.dispatch("warn",{type:"warn",message:e})}open(){this.dispatch("open",new Event("open"),!0)}static isCustomEvent(e){return["open","warn"].includes(e)}};var w={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},At=new Set([w.NO_STATUS,w.ABNORMAL,w.TLS_HANDSHAKE]);function Tt(t){return E(t)?Yt(t)&&!Jt(t)?t:w.NORMAL:w.NORMAL}function Yt(t){return t>=w.NORMAL&&t<=4999}function Jt(t){return At.has(t)}function Ot(t){if(C(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var k=class extends he{accepted=!1;server;constructor(e){super(e),this.server=e,this.server.addEventListener("close",this.onclose)}send(e){if(this.isState(WebSocket.CONNECTING,WebSocket.CLOSED)){this.warn("Cannot send: WebSocket not open");return}if(!St(e)){this.warn("Cannot send: empty or invalid data");return}this.server.send(e)}get attachment(){return this.server.deserializeAttachment()??{}}attach(e){if(e!==void 0)if(e===null)this.server.serializeAttachment({});else{let s={...this.attachment,...e};Rt(s),this.server.serializeAttachment(s)}}get readyState(){return this.accepted?this.server.readyState:WebSocket.CONNECTING}isState(...e){return e.includes(this.readyState)}close(e,r){this.server.removeEventListener("close",this.onclose),this.server.close(Tt(e),Ot(r))}onclose=e=>{this.close(e.code,e.reason)}};var Ce=class extends k{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return this.accepted?this.client:(e.acceptWebSocket(this.server,r),this.ready())}accept(){return this.accepted?this.client:(this.server.accept(),this.ready())}ready(){return this.accepted=!0,this.open(),this.client}};var Ee=class extends k{constructor(e){super(e),this.accepted=!0}accept(){throw new Error("Do not call accept() on restore")}acceptWebSocket(){throw new Error("Do not call acceptWebSocket() on restore")}};var bt=class{map=new Map;create(e){class r extends Ce{constructor(a){super();this.sessions=a}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(a,c){return this.sessions.register(this.server,this),super.acceptWebSocket(a,c)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends Ee{constructor(o,i){super(i),o.register(this.server,this)}}return new r(this,e)}restoreAll(e){let r=[];for(let s of e)r.push(this.restore(s));return r}get(e){return this.map.get(e)}select(e){let r=[];for(let s of e){let o=this.map.get(s);o&&r.push(o)}return r}values(){return this.map.values()}keys(){return this.map.keys()}close(e,r,s){let o=this.get(e);return o&&o.close(r,s),this.unregister(e)}*[Symbol.iterator](){yield*this.values()}register(e,r){this.map.set(e,r)}unregister(e){return this.map.delete(e)}};function xt(t){if(t===null||typeof t!="object"||typeof t.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var M=class{constructor(e,r,s){this._request=e;this._env=r;this._ctx=s}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(e){let r=this.getAllowedMethods();return b(r),e===p||e===O?!0:be(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};var ge=class extends M{middlewares=[];init(){}use(...e){for(let r of e)xt(r);return this.middlewares.push(...e),this}async fetch(){return await this.init(),this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(v,this))()}};var Se=class extends ge{async fetch(){try{return await super.fetch()}catch(e){return console.error(e),this.response(ee)}}dispatch(){let e=this.request.method;return({GET:()=>this.get(),PUT:()=>this.put(),HEAD:()=>this.head(),POST:()=>this.post(),PATCH:()=>this.patch(),DELETE:()=>this.delete(),OPTIONS:()=>this.options()}[e]??(()=>this.response(v,this)))()}get(){return this.response(A)}put(){return this.response(N,this)}post(){return this.response(N,this)}patch(){return this.response(N,this)}delete(){return this.response(N,this)}options(){return this.response(Z,this)}async head(){let e=this.create(new Request(this.request.url,{method:p,headers:this.request.headers}));return this.response(L,await e.fetch())}getAllowedMethods(){return[p,O,B]}};import{match as Zt}from"path-to-regexp";var Re=class{routes=[];add(e){for(let[r,s,o]of e){let i=Zt(s);this.routes.push({method:r,matcher:i,handler:o})}}match(e,r){let s=new URL(r).pathname;for(let o of this){if(o.method!==e)continue;let i=o.matcher(s);if(i)return{route:o,params:i.params}}return null}*[Symbol.iterator](){yield*this.routes}};var Nt=class t extends Se{_routes=new Re;route(e,r,s){return this.routes([[e,r,s]]),this}routes(e){return this._routes.add(e),this}async dispatch(){let e=this._routes.match(this.request.method,this.request.url);if(!e)return super.dispatch();let{handler:r}=e.route;return t.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(M.prototype,e.prototype)}put(){return this.response(A)}post(){return this.response(A)}patch(){return this.response(A)}delete(){return this.response(A)}};export{K as BadRequest,Se as BasicWorker,R as CacheControl,V as CopyResponse,or as DELETE,rt as Forbidden,p as GET,O as HEAD,L as Head,Je as HtmlResponse,l as HttpError,ee as InternalServerError,J as JsonResponse,F as Method,v as MethodNotAllowed,N as MethodNotImplemented,A as NotFound,ye as NotImplemented,H as NotModified,B as OPTIONS,we as OctetStream,Z as Options,sr as PATCH,rr as POST,tr as PUT,W as PreconditionFailed,Qe as R2ObjectStream,Nt as RouteWorker,st as ServiceUnavailable,h as StatusCodes,U as SuccessResponse,Ze as TextResponse,He as Time,tt as Unauthorized,Q as UpgradeRequired,bt as WebSocketSessions,et as WebSocketUpgrade,m as WorkerResponse,Qs as cache,Ro as cors,Pe as sortSearchParams,Er as stripSearchParams,Lo as websocket};
1
+ import{StatusCodes as h}from"http-status-codes";import Ie from"cache-control-parser";var R={parse:Ie.parse,stringify:Ie.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var F=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(F||{}),{GET:p,PUT:tr,HEAD:O,POST:rr,PATCH:sr,DELETE:or,OPTIONS:B}=F;var He={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};function z(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function C(t){return typeof t=="string"}function E(t){return typeof t=="number"&&!Number.isNaN(t)}function Le(t){return typeof t=="boolean"}function ve(t){if(typeof t!="object"||t===null)throw new TypeError("CacheInit must be an object.");let{name:e,getKey:r}=t;yt(e),_t(r)}function yt(t){if(t!==void 0&&!C(t))throw new TypeError("Cache name must be a string.")}function _t(t){if(t!==void 0&&typeof t!="function")throw new TypeError("getKey must be a function.")}function We(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}function Pe(t){let e=new URL(t.url);return e.searchParams.sort(),e.hash="",e}function hr(t){let e=new URL(t.url);return e.search="",e.hash="",e}var j=class{rules=[];use(...e){return this.rules.push(...e),this}execute(e,r){return this.rules.reduceRight((o,i)=>()=>i.apply(e,o),()=>r())()}};import{StatusCodes as It}from"http-status-codes";var n={ACCEPT:"accept",ACCEPT_ENCODING:"accept-encoding",ACCEPT_LANGUAGE:"accept-language",ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",AUTHORIZATION:"authorization",CACHE_CONTROL:"cache-control",CONNECTION:"connection",CONTENT_DISPOSITION:"content-disposition",CONTENT_ENCODING:"content-encoding",CONTENT_LANGUAGE:"content-language",CONTENT_LENGTH:"content-length",CONTENT_RANGE:"content-range",CONTENT_TYPE:"content-type",CONTENT_MD5:"content-md5",COOKIE:"cookie",ETAG:"etag",IF_MATCH:"if-match",IF_MODIFIED_SINCE:"if-modified-since",IF_NONE_MATCH:"if-none-match",IF_UNMODIFIED_SINCE:"if-unmodified-since",LAST_MODIFIED:"last-modified",ORIGIN:"origin",RANGE:"range",SET_COOKIE:"set-cookie",VARY:"vary",ACCESS_CONTROL_ALLOW_CREDENTIALS:"access-control-allow-credentials",ACCESS_CONTROL_ALLOW_HEADERS:"access-control-allow-headers",ACCESS_CONTROL_ALLOW_METHODS:"access-control-allow-methods",ACCESS_CONTROL_ALLOW_ORIGIN:"access-control-allow-origin",ACCESS_CONTROL_EXPOSE_HEADERS:"access-control-expose-headers",ACCESS_CONTROL_MAX_AGE:"access-control-max-age",SEC_WEBSOCKET_VERSION:"sec-websocket-version",UPGRADE:"upgrade",INTERNAL_VARIANT_SET:"internal-variant-set"},ke=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],Me=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function M(t,e){return t<e?-1:t>e?1:0}function f(t,e,r){let s=Array.isArray(r)?r:[r],o=Array.from(new Set(s.map(i=>i.trim()))).filter(i=>i.length).sort(M);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function $(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let i=d(t,e).concat(s.map(a=>a.trim()));f(t,e,i)}function d(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(M)}function Ae(t,e){for(let r of e)t.delete(r)}var Ht="https://vary",Lt="*";function De(t,e){if(e.status!==It.OK||t.method!==p||t.headers.has(n.AUTHORIZATION)||t.headers.has(n.COOKIE)||w(t.headers)["no-store"]||!e.headers.has(n.CACHE_CONTROL))return!1;let s=w(e.headers),o=s["s-maxage"]??s["max-age"];if(o===void 0||o===0||s["no-store"]||s["no-cache"]||s.private||e.headers.has(n.SET_COOKIE)||Te(e).includes(Lt))return!1;if(e.headers.has(n.INTERNAL_VARIANT_SET))throw new Error("Found conflicting vary header.");if(e.headers.has(n.CONTENT_RANGE))throw new Error("Found content-range header on 200 OK. Must use 206 Partial Content");return!0}function w(t){return R.parse(t.get(n.CACHE_CONTROL)??"")}function Te(t){return y(d(t.headers,n.VARY))}function y(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(M);return Array.from(new Set(e))}function _(t,e,r){let s=[],o=y(e);for(let a of o){let c=t.headers.get(a);c!==null&&s.push([a,vt(a,c)])}let i=Wt(JSON.stringify([r.toString(),s]));return new URL(i,Ht).toString()}function vt(t,e){switch(t.toLowerCase()){case n.ACCEPT:case n.ACCEPT_LANGUAGE:case n.ORIGIN:return e.toLowerCase();default:return e}}function Wt(t){let e=new TextEncoder().encode(t),r="";for(let s of e)r+=String.fromCodePoint(s);return btoa(r).replaceAll("+","-").replaceAll("/","_").replace(/={1,2}$/,"")}var Pt=/^bytes=(\d{1,12})-(\d{0,12})$/,Ge="W/",Ve="*";function Ue(t){let e=t.headers.get(n.RANGE);if(!e)return;let r=Pt.exec(e);if(!r)return;let s=Number(r[1]),o=r[2]===""?void 0:Number(r[2]);return o===void 0?{start:s}:{start:s,end:o}}function Ke(t,e){return t.length>0&&!Fe(t,e,Ve)}function qe(t,e){return Fe(t,Be(e),Ve)}function Fe(t,...e){return t.some(r=>e.includes(r))}function X(t){if(!C(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Be(t){return t.startsWith(Ge)?t.slice(2):t}function Oe(t){return{ifMatch:d(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:d(t,n.IF_NONE_MATCH).map(Be),ifModifiedSince:t.get(n.IF_MODIFIED_SINCE),ifUnmodifiedSince:t.get(n.IF_UNMODIFIED_SINCE)}}function ze(t){let{ifNoneMatch:e,ifMatch:r,ifModifiedSince:s,ifUnmodifiedSince:o}=Oe(t);return e.length>0||r.length>0||s!==null||o!==null}function je(t){let e=t.get(n.CONTENT_LENGTH);if(e===null||e.trim()==="")return;let r=Number(e);if(E(r))return r}var Y=class{async apply(e,r){let s=w(e.request.headers);if(!s["no-store"]&&!((s["no-cache"]||s["max-age"]===0)&&!ze(e.request.headers)))return r()}};import{getReasonPhrase as Gt,StatusCodes as g}from"http-status-codes";var kt=new Set(Object.values(F));function be(t){return C(t)&&kt.has(t)}function Mt(t){return Array.isArray(t)&&t.every(be)}function b(t){if(!Mt(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}var $e="upgrade",Xe="websocket";import{getReasonPhrase as Dt,StatusCodes as u}from"http-status-codes";var D="utf-8";function Ye(t){if(typeof t!="object"||t===null)throw new TypeError("OctetStreamInit must be an object.");let e=t,r=e.size;if(!E(r)||r<0||!Number.isInteger(r))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(r)}).`);let s=e.offset??0;if(!E(s)||s<0||s>r||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}).`);let o=e.length??r-s;if(!E(o)||o<0||s+o>r||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function G(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var xe=class{headers=new Headers;status=u.OK;statusText;webSocket;mediaType=G("text/plain",D);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??Dt(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){f(this.headers,e,r)}mergeHeader(e,r){$(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===u.NO_CONTENT?Ae(this.headers,Me):this.status===u.NOT_MODIFIED&&Ae(this.headers,ke)}},Ne=class extends xe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,R.stringify(this.cache))}},m=class extends Ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=[u.NO_CONTENT,u.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},V=class extends m{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},I=class extends m{constructor(e){super(),this.status=u.NOT_MODIFIED,this.headers=new Headers(e.headers)}},U=class extends m{constructor(e=null,r,s=u.OK){super(e,r),this.status=s}},J=class extends U{constructor(e={},r,s=u.OK){super(JSON.stringify(e),r,s),this.mediaType=G("application/json",D)}},Je=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/html",o)}},Ze=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/plain",o)}},we=class t extends m{constructor(e,r,s){Ye(r),super(e,s),this.mediaType="application/octet-stream";let o=t.normalizeInit(r),{size:i,offset:a,length:c}=o;t.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${a}-${a+c-1}/${i}`),this.status=u.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${c}`)}static normalizeInit(e){let{size:r}=e,s=e.offset??0,o=e.length??r-s;return s===0&&o===0&&r>0&&(o=1),{size:r,offset:s,length:o}}static isPartial(e){return e.size===0?!1:!(e.offset===0&&e.length===e.size)}},Qe=class t extends we{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=R.parse(e.httpMetadata.cacheControl)),super(e.body,t.computeRange(e.size,e.range),s),this.setHeader(n.ETAG,e.httpEtag),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType)}static computeRange(e,r){if(!r)return{size:e};if("suffix"in r){let s=Math.max(0,e-r.suffix),o=e-s;return{size:e,offset:s,length:o}}return{size:e,...r}}},et=class extends m{constructor(e){super(),this.status=u.SWITCHING_PROTOCOLS,this.webSocket=e}},H=class extends m{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},Z=class extends m{constructor(e){let r=Array.from(new Set([p,O,...e.getAllowedMethods()]));b(r),super(),this.status=u.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var l=class extends J{constructor(r,s){let o={status:r,error:Gt(r),details:s??""};super(o,R.DISABLE,r);this.details=s}},K=class extends l{constructor(e){super(g.BAD_REQUEST,e)}},tt=class extends l{constructor(e){super(g.UNAUTHORIZED,e)}},rt=class extends l{constructor(e){super(g.FORBIDDEN,e)}},A=class extends l{constructor(e){super(g.NOT_FOUND,e)}},L=class extends l{constructor(e){let r=e.getAllowedMethods();b(r),super(g.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},v=class extends l{constructor(e){super(g.PRECONDITION_FAILED,e)}},Q=class extends l{constructor(){super(g.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13")}},ee=class extends l{constructor(e){super(g.INTERNAL_SERVER_ERROR,e)}},ye=class extends l{constructor(e){super(g.NOT_IMPLEMENTED,e)}},x=class extends ye{constructor(e){super(`${e.request.method} method not implemented.`)}},st=class extends l{constructor(e){super(g.SERVICE_UNAVAILABLE,e)}};import{StatusCodes as Vt}from"http-status-codes";var W=class{async apply(e,r){let s=await r();if(!s||s.status!==Vt.OK)return s;let o=this.getHeader(s);if(o===void 0)return s;let i=Oe(e.request.headers);return this.response(s,o,i)}};var te=class extends W{getHeader(e){return e.headers.get(n.ETAG)??void 0}},re=class extends te{async response(e,r,s){return Ke(s.ifMatch,r)?new v(`ETag: ${r}`).response():e}},se=class extends te{async response(e,r,s){if(s.ifNoneMatch.length===0)return e;if(qe(s.ifNoneMatch,r))return new I(e).response()}};var oe=class{async apply(e,r){if(e.request.method===p)return r();if(e.request.method===O){let s=await r();return s?new H(s).response():void 0}}};var ne=class extends W{getHeader(e){return X(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=X(s.ifModifiedSince);if(o===void 0)return e;if(r<=o)return new I(e).response()}},ae=class extends ne{async response(e,r,s){let o=X(s.ifUnmodifiedSince);return o===void 0?e:r>o?new v(`Last-Modified: ${new Date(r).toUTCString()}`).response():e}};import{StatusCodes as Ut}from"http-status-codes";var ce=class{async apply(e,r){let s=Ue(e.request);if(s&&(s.start!==0||s.end===0))return;let o=await r();if(!o||o.status!==Ut.OK||!s||s.end===void 0)return o;let i=je(o.headers);if(i&&s.end===i-1)return o}};var pe=class{async apply(e,r){let s=e.request.headers;if(!s.has(n.AUTHORIZATION)&&!s.has(n.COOKIE))return r()}};var ue=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var T=class t extends m{_isModified=!1;constructor(e){let r=y(e);if(r.length===0)throw new Error("The filtered vary array is empty.");super(),this.setHeader(n.INTERNAL_VARIANT_SET,r)}static new(e){return new t(y(e))}static restore(e){if(!t.isVariantResponse(e))throw new Error("The source response is not a variant response");let r=t.new(d(e.headers,n.INTERNAL_VARIANT_SET)),s=e.headers.get(n.CACHE_CONTROL);return s&&(r.cache=R.parse(s)),r}get vary(){return d(this.headers,n.INTERNAL_VARIANT_SET)}get isModified(){return this._isModified}append(e){let r=this.vary.length;this.mergeHeader(n.INTERNAL_VARIANT_SET,y(e)),this._isModified=this.vary.length!==r}static isVariantResponse(e){return e.headers.has(n.INTERNAL_VARIANT_SET)}expireAfter(e){let r=w(e.headers),s=r["s-maxage"]??r["max-age"];if(s===void 0)return;let o=this.cache?.["s-maxage"];(o===void 0||s>o)&&(this.cache={"s-maxage":s},this._isModified=!0)}};var de=class{init;constructor(e){let{name:r,getKey:s=Pe}=e;this.init={name:r?.trim()||void 0,getKey:s}}async handle(e,r){let s=this.init.name?await caches.open(this.init.name):caches.default,i=await new j().use(new Y).use(new oe).use(new ue).use(new pe).use(new ce).use(new ie).use(new se).use(new ae).use(new re).execute(e,()=>this.getCached(s,e.request));if(i)return i;let a=await r();return e.ctx.waitUntil(this.setCached(s,e.request,a)),a}async getCached(e,r){let s=this.getCacheKey(r),o=await e.match(s.toString());if(!o)return;if(!T.isVariantResponse(o))return o;let i=T.restore(o).vary,a=_(r,i,s);return e.match(a)}async setCached(e,r,s){if(!De(r,s))return;let o=this.getCacheKey(r),i=s.clone(),a=Te(i),c=await e.match(o),wt=c&&T.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let S=T.new(a);S.expireAfter(i),await e.put(o,await S.response()),await e.put(_(r,S.vary,o),i);return}if(wt){let S=T.restore(c);S.expireAfter(i),a.length>0&&(S.append(a),S.isModified&&await e.put(o,await S.response())),await e.put(_(r,S.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let q=T.new(a);q.expireAfter(c),q.expireAfter(i),await e.put(o,await q.response()),await e.put(_(r,q.vary,o),i),await e.put(_(r,[],o),c)}getCacheKey(e){let r=this.init.getKey(e);return We(r),r.hash="",r}};function Zs(t={}){return ve(t),new de(t)}function nt(t){if(t===void 0)return;if(typeof t!="object"||t===null)throw new TypeError("CorsInit must be an object.");let e=t;if(e.allowedOrigins!==void 0&&!z(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!z(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!z(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!Le(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!E(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var le="*",it=[h.SWITCHING_PROTOCOLS,h.CONTINUE,h.PROCESSING,h.EARLY_HINTS,h.MOVED_PERMANENTLY,h.MOVED_TEMPORARILY,h.SEE_OTHER,h.TEMPORARY_REDIRECT,h.PERMANENT_REDIRECT],at={allowedOrigins:[le],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*He.Minute};function ct(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Kt(s.headers,e),Ft(s.headers,r),qt(s.headers,r)),s.response()}function pt(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Bt(s.headers,r)),s.response()}function ut(t,e){_e(e)||$(t,n.VARY,n.ORIGIN)}function dt(t,e,r){if(_e(e)){f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,le);return}e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r)}function lt(t,e,r){e.allowCredentials&&(_e(e)||e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function Kt(t,e){let r=e.getAllowedMethods();b(r),f(t,n.ACCESS_CONTROL_ALLOW_METHODS,r)}function qt(t,e){let r=Math.max(0,Math.floor(e.maxAge));f(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function Ft(t,e){f(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function Bt(t,e){f(t,n.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function _e(t){return t.allowedOrigins.includes(le)}function ft(t){t.delete(n.ACCESS_CONTROL_MAX_AGE),t.delete(n.ACCESS_CONTROL_ALLOW_ORIGIN),t.delete(n.ACCESS_CONTROL_ALLOW_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_METHODS),t.delete(n.ACCESS_CONTROL_EXPOSE_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_CREDENTIALS)}function mt(t){let{status:e,headers:r}=t;return!!(it.includes(e)||r.has(n.UPGRADE))}function ht(t){let e=t.headers.get(n.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}var fe=class{config;constructor(e){this.config={...at,...e}}async handle(e,r){let s=await r();return e.request.method===B?ct(s,e,this.config):mt(s)?s:pt(s,e,this.config)}};function So(t){return nt(t),new fe(t)}import{match as zt}from"path-to-regexp";function Ct(t){return d(t,n.CONNECTION).some(e=>e.toLowerCase()===$e)}function Et(t){return d(t,n.UPGRADE).some(e=>e.toLowerCase()===Xe)}function gt(t){return t.get(n.SEC_WEBSOCKET_VERSION)?.trim()==="13"}var me=class{constructor(e){this.path=e}handle(e,r){if(e.request.method!==p||!this.isMatch(e.request))return r();let s=e.request.headers;return Ct(s)?Et(s)?gt(s)?r():new Q().response():new K("Missing or invalid 'Upgrade' header").response():new K("Missing or invalid 'Connection' header").response()}isMatch(e){return zt(this.path)(new URL(e.url).pathname)!==!1}};function Ho(t="/"){return new me(t)}function jt(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function St(t){return C(t)?t.length>0:jt(t)?t.byteLength>0:!1}function Rt(t){if(t===null||typeof t!="object")throw new TypeError("WebSocket attachment must be an object");try{JSON.stringify(t)}catch{throw new TypeError("WebSocket attachment is not serializable")}}var he=class t{server;customListeners={};constructor(e){this.server=e}addEventListener(e,r,s){if(t.isCustomEvent(e)){let o=this.customListeners[e];o||(o=[],this.customListeners[e]=o),o.push(r)}else{let o=e==="close"?{...s,once:!0}:s;this.server.addEventListener(e,r,o)}}removeEventListener(e,r){if(t.isCustomEvent(e)){let s=this.customListeners[e];if(s){let o=s.indexOf(r);o!==-1&&s.splice(o,1)}}else this.server.removeEventListener(e,r)}dispatch(e,r,s=!1){let o=this.customListeners[e]?.slice()??[];s&&(this.customListeners[e]=[]);for(let i of o)i(r)}warn(e){this.dispatch("warn",{type:"warn",message:e})}open(){this.dispatch("open",new Event("open"),!0)}static isCustomEvent(e){return["open","warn"].includes(e)}};var N={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},At=new Set([N.NO_STATUS,N.ABNORMAL,N.TLS_HANDSHAKE]);function Tt(t){return E(t)?Yt(t)&&!Jt(t)?t:N.NORMAL:N.NORMAL}function Yt(t){return t>=N.NORMAL&&t<=4999}function Jt(t){return At.has(t)}function Ot(t){if(C(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var P=class extends he{accepted=!1;server;constructor(e){super(e),this.server=e,this.server.addEventListener("close",this.onclose)}send(e){if(this.isState(WebSocket.CONNECTING,WebSocket.CLOSED)){this.warn("Cannot send: WebSocket not open");return}if(!St(e)){this.warn("Cannot send: empty or invalid data");return}this.server.send(e)}get attachment(){return this.server.deserializeAttachment()??{}}attach(e){if(e!==void 0)if(e===null)this.server.serializeAttachment({});else{let s={...this.attachment,...e};Rt(s),this.server.serializeAttachment(s)}}get readyState(){return this.accepted?this.server.readyState:WebSocket.CONNECTING}isState(...e){return e.includes(this.readyState)}close(e,r){this.server.removeEventListener("close",this.onclose),this.server.close(Tt(e),Ot(r))}onclose=e=>{this.close(e.code,e.reason)}};var Ce=class extends P{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return this.accepted?this.client:(e.acceptWebSocket(this.server,r),this.ready())}accept(){return this.accepted?this.client:(this.server.accept(),this.ready())}ready(){return this.accepted=!0,this.open(),this.client}};var Ee=class extends P{constructor(e){super(e),this.accepted=!0}accept(){throw new Error("Do not call accept() on restore")}acceptWebSocket(){throw new Error("Do not call acceptWebSocket() on restore")}};var bt=class{map=new Map;create(e){class r extends Ce{constructor(a){super();this.sessions=a}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(a,c){return this.sessions.register(this.server,this),super.acceptWebSocket(a,c)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends Ee{constructor(o,i){super(i),o.register(this.server,this)}}return new r(this,e)}restoreAll(e){let r=[];for(let s of e)r.push(this.restore(s));return r}get(e){return this.map.get(e)}select(e){let r=[];for(let s of e){let o=this.map.get(s);o&&r.push(o)}return r}values(){return this.map.values()}keys(){return this.map.keys()}close(e,r,s){let o=this.get(e);return o&&o.close(r,s),this.unregister(e)}*[Symbol.iterator](){yield*this.values()}register(e,r){this.map.set(e,r)}unregister(e){return this.map.delete(e)}};function xt(t){if(t===null||typeof t!="object"||typeof t.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var k=class{constructor(e,r,s){this._request=e;this._env=r;this._ctx=s}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(e){let r=this.getAllowedMethods();return b(r),e===p||e===O?!0:be(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};var ge=class extends k{middlewares=[];init(){}use(...e){for(let r of e)xt(r);return this.middlewares.push(...e),this}async fetch(){return await this.init(),this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(L,this))()}};var Se=class extends ge{async fetch(){try{return await super.fetch()}catch(e){return console.error(e),this.response(ee)}}dispatch(){let e=this.request.method;return({GET:()=>this.get(),PUT:()=>this.put(),HEAD:()=>this.head(),POST:()=>this.post(),PATCH:()=>this.patch(),DELETE:()=>this.delete(),OPTIONS:()=>this.options()}[e]??(()=>this.response(L,this)))()}get(){return this.response(A)}put(){return this.response(x,this)}post(){return this.response(x,this)}patch(){return this.response(x,this)}delete(){return this.response(x,this)}options(){return this.response(Z,this)}async head(){let e=this.create(new Request(this.request.url,{method:p,headers:this.request.headers}));return this.response(H,await e.fetch())}getAllowedMethods(){return[p,O,B]}};import{match as Zt}from"path-to-regexp";var Re=class{routes=[];add(e){for(let[r,s,o]of e){let i=Zt(s);this.routes.push({method:r,matcher:i,handler:o})}}match(e,r){let s=new URL(r).pathname;for(let o of this){if(o.method!==e)continue;let i=o.matcher(s);if(i)return{route:o,params:i.params}}return null}*[Symbol.iterator](){yield*this.routes}};var Nt=class t extends Se{_routes=new Re;route(e,r,s){return this.routes([[e,r,s]]),this}routes(e){return this._routes.add(e),this}async dispatch(){let e=this._routes.match(this.request.method,this.request.url);if(!e)return super.dispatch();let{handler:r}=e.route;return t.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(k.prototype,e.prototype)}put(){return this.response(A)}post(){return this.response(A)}patch(){return this.response(A)}delete(){return this.response(A)}};export{K as BadRequest,Se as BasicWorker,R as CacheControl,V as CopyResponse,or as DELETE,rt as Forbidden,p as GET,O as HEAD,H as Head,Je as HtmlResponse,l as HttpError,ee as InternalServerError,J as JsonResponse,F as Method,L as MethodNotAllowed,x as MethodNotImplemented,A as NotFound,ye as NotImplemented,I as NotModified,B as OPTIONS,we as OctetStream,Z as Options,sr as PATCH,rr as POST,tr as PUT,v as PreconditionFailed,Qe as R2ObjectStream,Nt as RouteWorker,st as ServiceUnavailable,h as StatusCodes,U as SuccessResponse,Ze as TextResponse,He as Time,tt as Unauthorized,Q as UpgradeRequired,bt as WebSocketSessions,et as WebSocketUpgrade,m as WorkerResponse,Zs as cache,So as cors,Pe as sortSearchParams,hr as stripSearchParams,Ho as websocket};
2
2
  //# sourceMappingURL=index.js.map