@adonix.org/cloud-spark 0.0.163 → 0.0.165

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import CacheLib from 'cache-control-parser';
2
- import { MatchFunction } from 'path-to-regexp';
3
1
  import { StatusCodes } from 'http-status-codes';
4
2
  export { StatusCodes } from 'http-status-codes';
3
+ import CacheLib from 'cache-control-parser';
4
+ import { MatchFunction } from 'path-to-regexp';
5
5
 
6
6
  /**
7
7
  * @see {@link https://github.com/etienne-martin/cache-control-parser | cache-control-parser}
@@ -19,41 +19,6 @@ declare const CacheControl: {
19
19
  }>;
20
20
  };
21
21
 
22
- /**
23
- * https://github.com/prettymuchbryce/http-status-codes
24
- */
25
-
26
- /**
27
- * Standard HTTP header names and common values.
28
- */
29
- declare namespace HttpHeader {
30
- const ACCEPT_ENCODING = "Accept-Encoding";
31
- const ACCEPT_RANGES = "Accept-Ranges";
32
- const ALLOW = "Allow";
33
- const CONTENT_LENGTH = "Content-Length";
34
- const CONTENT_RANGE = "Content-Range";
35
- const CONTENT_TYPE = "Content-Type";
36
- const CACHE_CONTROL = "Cache-Control";
37
- const ORIGIN = "Origin";
38
- const USER_AGENT = "User-Agent";
39
- const VARY = "Vary";
40
- const CONTENT_SECURITY_POLICY = "Content-Security-Policy";
41
- const PERMISSIONS_POLICY = "Permissions-Policy";
42
- const STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security";
43
- const REFERRER_POLICY = "Referrer-Policy";
44
- const X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options";
45
- const X_FRAME_OPTIONS = "X-Frame-Options";
46
- const ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
47
- const ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
48
- const ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
49
- const ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
50
- const ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
51
- const ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
52
- const ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
53
- const SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version";
54
- const CONNECTION = "Connection";
55
- const UPGRADE = "Upgrade";
56
- }
57
22
  /**
58
23
  * Standard HTTP request methods.
59
24
  */
@@ -80,55 +45,6 @@ declare const PATCH: Method;
80
45
  declare const DELETE: Method;
81
46
  declare const OPTIONS: Method;
82
47
 
83
- /**
84
- * Common media types used for HTTP headers.
85
- */
86
- declare enum MediaType {
87
- PLAIN_TEXT = "text/plain",
88
- HTML = "text/html",
89
- CSS = "text/css",
90
- CSV = "text/csv",
91
- XML = "text/xml",
92
- MARKDOWN = "text/markdown",
93
- RICH_TEXT = "text/richtext",
94
- JSON = "application/json",
95
- XML_APP = "application/xml",
96
- YAML = "application/x-yaml",
97
- FORM_URLENCODED = "application/x-www-form-urlencoded",
98
- NDJSON = "application/x-ndjson",
99
- MSGPACK = "application/x-msgpack",
100
- PROTOBUF = "application/x-protobuf",
101
- MULTIPART_FORM_DATA = "multipart/form-data",
102
- MULTIPART_MIXED = "multipart/mixed",
103
- MULTIPART_ALTERNATIVE = "multipart/alternative",
104
- MULTIPART_DIGEST = "multipart/digest",
105
- MULTIPART_RELATED = "multipart/related",
106
- MULTIPART_SIGNED = "multipart/signed",
107
- MULTIPART_ENCRYPTED = "multipart/encrypted",
108
- OCTET_STREAM = "application/octet-stream",
109
- PDF = "application/pdf",
110
- ZIP = "application/zip",
111
- GZIP = "application/gzip",
112
- MSWORD = "application/msword",
113
- DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
114
- EXCEL = "application/vnd.ms-excel",
115
- XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
116
- POWERPOINT = "application/vnd.ms-powerpoint",
117
- PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
118
- ICO = "image/x-icon",
119
- ICO_MS = "image/vnd.microsoft.icon",
120
- GIF = "image/gif",
121
- PNG = "image/png",
122
- JPEG = "image/jpeg",
123
- WEBP = "image/webp",
124
- SVG = "image/svg+xml",
125
- HEIF = "image/heif",
126
- AVIF = "image/avif",
127
- EVENT_STREAM = "text/event-stream",
128
- TAR = "application/x-tar",
129
- BZIP2 = "application/x-bzip2"
130
- }
131
-
132
48
  /**
133
49
  * Time constants in seconds. Month is approximated as 30 days.
134
50
  */
@@ -142,63 +58,6 @@ declare const Time: {
142
58
  readonly Year: 31536000;
143
59
  };
144
60
 
145
- /** WebSocket upgrade header value */
146
- declare const WS_UPGRADE = "upgrade";
147
- /** WebSocket protocol header value */
148
- declare const WS_WEBSOCKET = "websocket";
149
- /** WebSocket protocol version */
150
- declare const WS_VERSION = "13";
151
- /** Max close code a user can send */
152
- declare const WS_MAX_CLOSE_CODE = 4999;
153
- /** Max number of reason chars a user can send */
154
- declare const WS_MAX_REASON_CHARS = 123;
155
- /** WebSocket close codes */
156
- declare const CloseCode: {
157
- readonly NORMAL: 1000;
158
- readonly GOING_AWAY: 1001;
159
- readonly PROTOCOL_ERROR: 1002;
160
- readonly UNSUPPORTED_DATA: 1003;
161
- readonly NO_STATUS: 1005;
162
- readonly ABNORMAL: 1006;
163
- readonly INVALID_PAYLOAD: 1007;
164
- readonly POLICY_VIOLATION: 1008;
165
- readonly MESSAGE_TOO_BIG: 1009;
166
- readonly MISSING_EXTENSION: 1010;
167
- readonly INTERNAL_ERROR: 1011;
168
- readonly TLS_HANDSHAKE: 1015;
169
- };
170
- /** WebSocket RESERVED close codes */
171
- declare const WS_RESERVED_CODES: Set<number>;
172
-
173
- /**
174
- * Type guard that checks if a string is a valid HTTP method.
175
- *
176
- * @param value - The string to test.
177
- * @returns True if `value` is a recognized HTTP method.
178
- */
179
- declare function isMethod(value: unknown): value is Method;
180
- /**
181
- * Checks if a value is an array of valid HTTP methods.
182
- *
183
- * Each element is verified using the `isMethod` type guard.
184
- *
185
- * @param value - The value to check.
186
- * @returns `true` if `value` is an array and every element is a valid `Method`, otherwise `false`.
187
- */
188
- declare function isMethodArray(value: unknown): value is Method[];
189
- /**
190
- * Asserts that a value is an array of valid HTTP methods.
191
- *
192
- * This function uses {@link isMethodArray} to validate the input. If the
193
- * value is not an array of `Method` elements, it throws a `TypeError`.
194
- * Otherwise, TypeScript will narrow the type of `value` to `Method[]`
195
- * within the calling scope.
196
- *
197
- * @param value - The value to check.
198
- * @throws TypeError If `value` is not a valid method array.
199
- */
200
- declare function assertMethods(value: unknown): asserts value is Method[];
201
-
202
61
  /**
203
62
  * User-supplied options for configuring`CORS`behavior.
204
63
  *
@@ -503,90 +362,10 @@ declare abstract class Middleware {
503
362
  * @returns A `Middleware` instance that can be used in a Worker pipeline.
504
363
  */
505
364
  declare function cache(cacheName?: string, getKey?: (request: Request) => URL): Middleware;
506
-
507
- /**
508
- * Creates a`CORS`middleware instance.
509
- *
510
- * This middleware automatically handles Cross-Origin Resource Sharing (CORS)
511
- * for incoming requests, including preflight `OPTIONS` requests, and adds
512
- * appropriate headers to responses.
513
- *
514
- * @param init - Optional configuration for `CORS` behavior. See {@link CorsConfig}.
515
- * @returns A {@link Middleware} instance that can be used in your middleware chain.
516
- */
517
- declare function cors(init?: CorsInit): Middleware;
518
-
519
- declare function websocket(path?: string): Middleware;
520
-
521
- /**
522
- * Lexicographically compares two strings.
523
- *
524
- * This comparator can be used in `Array.prototype.sort()` to produce a
525
- * consistent, stable ordering of string arrays.
526
- *
527
- * @param a - The first string to compare.
528
- * @param b - The second string to compare.
529
- * @returns A number indicating the relative order of `a` and `b`.
530
- */
531
- declare function lexCompare(a: string, b: string): number;
532
-
533
- /**
534
- * Sets a header on the given Headers object.
535
- *
536
- * - If `value` is an array, any duplicates and empty strings are removed.
537
- * - If the resulting value is empty, the header is deleted.
538
- * - Otherwise, values are joined with `", "` and set as the header value.
539
- *
540
- * @param headers - The Headers object to modify.
541
- * @param key - The header name to set.
542
- * @param value - The header value(s) to set. Can be a string or array of strings.
543
- */
544
- declare function setHeader(headers: Headers, key: string, value: string | string[]): void;
545
- /**
546
- * Merges new value(s) into an existing header on the given Headers object.
547
- *
548
- * - Preserves any existing values and adds new ones.
549
- * - Removes duplicates and trims all values.
550
- * - If the header does not exist, it is created.
551
- * - If the resulting value array is empty, the header is deleted.
552
- *
553
- * @param headers - The Headers object to modify.
554
- * @param key - The header name to merge into.
555
- * @param value - The new header value(s) to add. Can be a string or array of strings.
556
- */
557
- declare function mergeHeader(headers: Headers, key: string, value: string | string[]): void;
558
- /**
559
- * Returns the values of an HTTP header as an array of strings.
560
- *
561
- * This helper:
562
- * - Retrieves the header value by `key`.
563
- * - Splits the value on commas.
564
- * - Trims surrounding whitespace from each entry.
565
- * - Filters out any empty tokens.
566
- * - Removes duplicate values (case-sensitive)
567
- *
568
- * If the header is not present, an empty array is returned.
569
- *
570
- */
571
- declare function getHeaderValues(headers: Headers, key: string): string[];
572
-
573
- /**
574
- * Extracts and normalizes the `Origin` header from a request.
575
- *
576
- * Returns the origin (scheme + host + port) as a string if present and valid.
577
- * Returns `null` if:
578
- * - The `Origin` header is missing
579
- * - The `Origin` header is `"null"` (opaque origin)
580
- * - The `Origin` header is malformed
581
- *
582
- * @param request - The incoming {@link Request} object.
583
- * @returns The normalized origin string, or `null` if not present or invalid.
584
- */
585
- declare function getOrigin(request: Request): string | null;
586
365
  /**
587
366
  * Returns a new URL with its query parameters sorted into a stable order.
588
367
  *
589
- * This is useful for cache key generation: URLs that differ only in the
368
+ * This is used for cache key generation: URLs that differ only in the
590
369
  * order of their query parameters will normalize to the same key.
591
370
  *
592
371
  * @param request - The incoming Request whose URL will be normalized.
@@ -596,7 +375,7 @@ declare function sortSearchParams(request: Request): URL;
596
375
  /**
597
376
  * Returns a new URL with all query parameters removed.
598
377
  *
599
- * This is useful when query parameters are not relevant to cache lookups,
378
+ * This is used when query parameters are not relevant to cache lookups,
600
379
  * ensuring that variants of the same resource share a single cache entry.
601
380
  *
602
381
  * @param request - The incoming Request whose URL will be normalized.
@@ -605,13 +384,18 @@ declare function sortSearchParams(request: Request): URL;
605
384
  declare function stripSearchParams(request: Request): URL;
606
385
 
607
386
  /**
608
- * Returns the proper Content-Type string for a given media type.
609
- * Appends `charset=utf-8` for text-based types that require it.
387
+ * Creates a`CORS`middleware instance.
610
388
  *
611
- * @param type - The media type.
612
- * @returns A string suitable for the `Content-Type` header.
389
+ * This middleware automatically handles Cross-Origin Resource Sharing (CORS)
390
+ * for incoming requests, including preflight `OPTIONS` requests, and adds
391
+ * appropriate headers to responses.
392
+ *
393
+ * @param init - Optional configuration for `CORS` behavior. See {@link CorsConfig}.
394
+ * @returns A {@link Middleware} instance that can be used in your middleware chain.
613
395
  */
614
- declare function getContentType(type: MediaType | string): string;
396
+ declare function cors(init?: CorsInit): Middleware;
397
+
398
+ declare function websocket(path?: string): Middleware;
615
399
 
616
400
  type WarnEvent = {
617
401
  type: "warn";
@@ -895,7 +679,7 @@ declare abstract class BaseResponse {
895
679
  /** Enable websocket responses. */
896
680
  webSocket: WebSocket | null;
897
681
  /** Default media type of the response body. */
898
- mediaType: MediaType | string;
682
+ mediaType: string;
899
683
  /** Converts current state to ResponseInit for constructing a Response. */
900
684
  protected get responseInit(): ResponseInit;
901
685
  /** Sets a header, overwriting any existing value. */
@@ -904,6 +688,19 @@ declare abstract class BaseResponse {
904
688
  mergeHeader(key: string, value: string | string[]): void;
905
689
  /** Adds a Content-Type header if not already existing (does not overwrite). */
906
690
  addContentType(): void;
691
+ /**
692
+ * Removes headers that are disallowed or discouraged based on the current
693
+ * status code.
694
+ *
695
+ * - **204 No Content:** strips headers that "should not" be sent
696
+ * (`Content-Length`, `Content-Range`), per the HTTP spec.
697
+ * - **304 Not Modified:** strips headers that "must not" be sent
698
+ * (`Content-Type`, `Content-Length`, `Content-Range`, etc.), per the HTTP spec.
699
+ *
700
+ * This ensures that responses remain compliant with HTTP/1.1 standards while preserving
701
+ * custom headers that are allowed.
702
+ */
703
+ filterHeaders(): void;
907
704
  }
908
705
  /**
909
706
  * Base response class that adds caching headers.
@@ -915,7 +712,7 @@ declare abstract class CacheResponse extends BaseResponse {
915
712
  protected addCacheHeader(): void;
916
713
  }
917
714
  /**
918
- * Core worker response. Combines caching, and security headers.
715
+ * Core response. Combines caching, and content type headers.
919
716
  */
920
717
  declare abstract class WorkerResponse extends CacheResponse {
921
718
  private readonly body;
@@ -945,60 +742,80 @@ declare class JsonResponse extends SuccessResponse {
945
742
  * HTML response. Automatically sets Content-Type to text/html.
946
743
  */
947
744
  declare class HtmlResponse extends SuccessResponse {
948
- constructor(body: string, cache?: CacheControl, status?: StatusCodes);
745
+ constructor(body: string, cache?: CacheControl, status?: StatusCodes, charset?: string);
949
746
  }
950
747
  /**
951
748
  * Plain text response. Automatically sets Content-Type to text/plain.
952
749
  */
953
750
  declare class TextResponse extends SuccessResponse {
954
- constructor(content: string, cache?: CacheControl, status?: StatusCodes);
751
+ constructor(body: string, cache?: CacheControl, status?: StatusCodes, charset?: string);
955
752
  }
956
753
  /**
957
- * A response class for streaming binary data.
958
- *
959
- * Automatically sets headers for:
960
- * - Accept-Ranges: bytes
961
- * - Content-Length
962
- * - Content-Range (for partial content)
754
+ * Represents an HTTP response for serving binary data as `application/octet-stream`.
963
755
  *
964
- * The status code is handled internally:
965
- * - 200 OK for full content
966
- * - 206 Partial Content for range responses
756
+ * This class validates the provided `OctetStreamInit` configuration and
757
+ * automatically sets the correct HTTP headers for either a full or partial
758
+ * content response.
967
759
  *
968
- * @param stream - The ReadableStream containing the data to send.
969
- * @param init - Options for the response:
970
- * - size: Total size of the data (required)
971
- * - offset: Start of the byte range (defaults to 0)
972
- * - length: Length of the byte range (defaults to size)
973
- * @param cache: Optional caching information
760
+ * Behavior:
761
+ * - Always sets `Content-Type` to `application/octet-stream`.
762
+ * - Always sets `Accept-Ranges: bytes`.
763
+ * - Always sets `Content-Length` to the validated length of the response body.
764
+ * - If either `offset` or `length` is provided and the size is non-zero, the response
765
+ * is treated as partial content (`206 Partial Content`) and a `Content-Range` header
766
+ * is added, even if the specified range spans the entire file.
767
+ * - Special case: a requested range of `0-0` on a non-empty file returns 1 byte.
768
+ * - Zero-length streams (`size = 0`) are never treated as partial content.
974
769
  */
975
770
  declare class OctetStream extends WorkerResponse {
976
771
  constructor(stream: ReadableStream, init: OctetStreamInit, cache?: CacheControl);
772
+ /**
773
+ * Returns a fully specified `OctetStreamInit` with all fields set.
774
+ *
775
+ * Fills in defaults for any missing values:
776
+ * - `offset` defaults to 0
777
+ * - `length` defaults to `size - offset`
778
+ * - If `offset` and `length` are both 0 but `size > 0`, `length` is set to 1
779
+ *
780
+ * @param init - Partial or complete OctetStreamInit
781
+ * @returns An object with `size`, `offset`, and `length` guaranteed
782
+ */
783
+ private static normalizeInit;
784
+ /**
785
+ * Returns true if the given `OctetStreamInit` represents a partial range.
786
+ *
787
+ * A partial range is any init with an explicit `offset` or `length`, provided
788
+ * the stream size is greater than zero.
789
+ *
790
+ * @param init - The OctetStreamInit to check.
791
+ * @returns `true` if partial, `false` otherwise.
792
+ */
793
+ private static isPartial;
977
794
  }
978
795
  /**
979
796
  * A streaming response for Cloudflare R2 objects.
980
797
  *
981
- * @param object - The R2 object to stream.
798
+ * @param source - The R2 object to stream.
982
799
  * @param cache - Optional caching information.
983
800
  */
984
801
  declare class R2ObjectStream extends OctetStream {
985
- constructor(object: R2ObjectBody, cache?: CacheControl);
802
+ constructor(source: R2ObjectBody, cache?: CacheControl);
986
803
  /**
987
- * Computes the byte range for an R2 object, returning all values needed
988
- * to construct a proper streaming response.
804
+ * Computes an `OctetStreamInit` object from a given R2 range.
805
+ *
806
+ * This function normalizes a Cloudflare R2 `R2Range` into the shape expected
807
+ * by `OctetStream`. It handles the following cases:
989
808
  *
990
- * Handles three cases:
991
- * 1. **No range specified** returns the full object.
992
- * 2. **Suffix range** (e.g., last N bytes) calculates offset and length
993
- * so that only the requested suffix is returned.
994
- * 3. **Standard offset/length range** — returns the requested range,
995
- * applying defaults if offset or length are missing.
809
+ * - No range provided → returns `{ size }` (full content).
810
+ * - `suffix` range calculates the offset and length from the end of the file.
811
+ * - Explicit `offset` and/or `length` passed through as-is.
996
812
  *
997
- * @param object - The R2 object containing optional range information.
998
- * @returns An object containing:
999
- * - `size` total size of the object in bytes
1000
- * - `offset` starting byte of the range
1001
- * - `length` number of bytes in the range
813
+ * @param size - The total size of the file/object.
814
+ * @param range - Optional range to extract (from R2). Can be:
815
+ * - `{ offset: number; length?: number }`
816
+ * - `{ offset?: number; length: number }`
817
+ * - `{ suffix: number }`
818
+ * @returns An `OctetStreamInit` object suitable for `OctetStream`.
1002
819
  */
1003
820
  private static computeRange;
1004
821
  }
@@ -1077,4 +894,4 @@ declare class ServiceUnavailable extends HttpError {
1077
894
  constructor(details?: string);
1078
895
  }
1079
896
 
1080
- export { BadRequest, BasicWorker, CacheControl, ClonedResponse, CloseCode, type CorsConfig, type CorsInit, DELETE, type ErrorJson, Forbidden, GET, HEAD, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, NotFound, NotImplemented, OPTIONS, OctetStream, type OctetStreamInit, Options, PATCH, POST, PUT, type PathParams, R2ObjectStream, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, UpgradeRequired, WS_MAX_CLOSE_CODE, WS_MAX_REASON_CHARS, WS_RESERVED_CODES, WS_UPGRADE, WS_VERSION, WS_WEBSOCKET, WebSocketSessions, WebSocketUpgrade, type Worker, type WorkerClass, WorkerResponse, assertMethods, cache, cors, getContentType, getHeaderValues, getOrigin, isMethod, isMethodArray, lexCompare, mergeHeader, setHeader, sortSearchParams, stripSearchParams, websocket };
897
+ export { BadRequest, BasicWorker, CacheControl, ClonedResponse, type CorsConfig, type CorsInit, DELETE, type ErrorJson, Forbidden, GET, HEAD, Head, HtmlResponse, HttpError, InternalServerError, JsonResponse, type MatchedRoute, Method, MethodNotAllowed, MethodNotImplemented, NotFound, NotImplemented, OPTIONS, OctetStream, type OctetStreamInit, Options, PATCH, POST, PUT, type PathParams, R2ObjectStream, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, UpgradeRequired, WebSocketSessions, WebSocketUpgrade, type Worker, type WorkerClass, WorkerResponse, cache, cors, sortSearchParams, stripSearchParams, websocket };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import ue from"cache-control-parser";var I={parse:ue.parse,stringify:ue.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};import{StatusCodes as m}from"http-status-codes";var i;(c=>(c.ACCEPT_ENCODING="Accept-Encoding",c.ACCEPT_RANGES="Accept-Ranges",c.ALLOW="Allow",c.CONTENT_LENGTH="Content-Length",c.CONTENT_RANGE="Content-Range",c.CONTENT_TYPE="Content-Type",c.CACHE_CONTROL="Cache-Control",c.ORIGIN="Origin",c.USER_AGENT="User-Agent",c.VARY="Vary",c.CONTENT_SECURITY_POLICY="Content-Security-Policy",c.PERMISSIONS_POLICY="Permissions-Policy",c.STRICT_TRANSPORT_SECURITY="Strict-Transport-Security",c.REFERRER_POLICY="Referrer-Policy",c.X_CONTENT_TYPE_OPTIONS="X-Content-Type-Options",c.X_FRAME_OPTIONS="X-Frame-Options",c.ACCESS_CONTROL_ALLOW_CREDENTIALS="Access-Control-Allow-Credentials",c.ACCESS_CONTROL_ALLOW_HEADERS="Access-Control-Allow-Headers",c.ACCESS_CONTROL_ALLOW_METHODS="Access-Control-Allow-Methods",c.ACCESS_CONTROL_ALLOW_ORIGIN="Access-Control-Allow-Origin",c.ACCESS_CONTROL_EXPOSE_HEADERS="Access-Control-Expose-Headers",c.ACCESS_CONTROL_MAX_AGE="Access-Control-Max-Age",c.ACCESS_CONTROL_REQUEST_HEADERS="Access-Control-Request-Headers",c.SEC_WEBSOCKET_VERSION="Sec-WebSocket-Version",c.CONNECTION="Connection",c.UPGRADE="Upgrade"))(i||={});var W=(u=>(u.GET="GET",u.PUT="PUT",u.HEAD="HEAD",u.POST="POST",u.PATCH="PATCH",u.DELETE="DELETE",u.OPTIONS="OPTIONS",u))(W||{}),{GET:f,PUT:kt,HEAD:k,POST:Dt,PATCH:Mt,DELETE:Ht,OPTIONS:b}=W;var Ze=(n=>(n.PLAIN_TEXT="text/plain",n.HTML="text/html",n.CSS="text/css",n.CSV="text/csv",n.XML="text/xml",n.MARKDOWN="text/markdown",n.RICH_TEXT="text/richtext",n.JSON="application/json",n.XML_APP="application/xml",n.YAML="application/x-yaml",n.FORM_URLENCODED="application/x-www-form-urlencoded",n.NDJSON="application/x-ndjson",n.MSGPACK="application/x-msgpack",n.PROTOBUF="application/x-protobuf",n.MULTIPART_FORM_DATA="multipart/form-data",n.MULTIPART_MIXED="multipart/mixed",n.MULTIPART_ALTERNATIVE="multipart/alternative",n.MULTIPART_DIGEST="multipart/digest",n.MULTIPART_RELATED="multipart/related",n.MULTIPART_SIGNED="multipart/signed",n.MULTIPART_ENCRYPTED="multipart/encrypted",n.OCTET_STREAM="application/octet-stream",n.PDF="application/pdf",n.ZIP="application/zip",n.GZIP="application/gzip",n.MSWORD="application/msword",n.DOCX="application/vnd.openxmlformats-officedocument.wordprocessingml.document",n.EXCEL="application/vnd.ms-excel",n.XLSX="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",n.POWERPOINT="application/vnd.ms-powerpoint",n.PPTX="application/vnd.openxmlformats-officedocument.presentationml.presentation",n.ICO="image/x-icon",n.ICO_MS="image/vnd.microsoft.icon",n.GIF="image/gif",n.PNG="image/png",n.JPEG="image/jpeg",n.WEBP="image/webp",n.SVG="image/svg+xml",n.HEIF="image/heif",n.AVIF="image/avif",n.EVENT_STREAM="text/event-stream",n.TAR="application/x-tar",n.BZIP2="application/x-bzip2",n))(Ze||{});var le={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var de="upgrade",me="websocket",$="13",he=4999,fe=123,O={NORMAL:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS:1005,ABNORMAL:1006,INVALID_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,MISSING_EXTENSION:1010,INTERNAL_ERROR:1011,TLS_HANDSHAKE:1015},Ce=new Set([O.NO_STATUS,O.ABNORMAL,O.TLS_HANDSHAKE]);function D(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function g(t){return typeof t=="string"}function Ee(t){return typeof t=="function"}function M(t){return typeof t=="number"&&!Number.isNaN(t)}function Se(t){return typeof t=="boolean"}var Qe=new Set(Object.values(W));function Z(t){return g(t)&&Qe.has(t)}function et(t){return Array.isArray(t)&&t.every(Z)}function T(t){if(!et(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}var h=class{};function Ae(t){if(t!==void 0&&!g(t))throw new TypeError("Cache name must be a string.")}function xe(t){if(t!==void 0&&!Ee(t))throw new TypeError("getKey must be a function.")}function Re(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}function S(t,e){return t<e?-1:t>e?1:0}function l(t,e,r){let s=Array.isArray(r)?r:[r],o=Array.from(new Set(s.map(a=>a.trim()))).filter(a=>a.length).sort(S);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function H(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let a=_(t,e).concat(s.map(p=>p.trim()));l(t,e,a)}function _(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(S)}function Q(t){let e=t.headers.get(i.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}function Oe(t){let e=new URL(t.url),r=new URLSearchParams([...e.searchParams.entries()].sort(([s],[o])=>S(s,o)));return e.search=r.toString(),e.hash="",e}function rr(t){let e=new URL(t.url);return e.search="",e.hash="",e}var tt=new Set(["text/css","text/csv","text/xml","image/svg+xml","text/html","application/json","application/x-ndjson","application/xml","text/markdown","text/richtext","text/plain","application/x-www-form-urlencoded"]);function ge(t){return tt.has(t)?`${t}; charset=utf-8`:t}var rt="https://vary";function be(t){return!(!t.ok||ee(t).includes("*"))}function ee(t){let e=_(t.headers,i.VARY);return Array.from(new Set(e.map(r=>r.toLowerCase()))).sort(S)}function te(t){return t.map(e=>e.toLowerCase()).filter(e=>e!==i.ACCEPT_ENCODING.toLowerCase())}function re(t,e,r){let s=[],o=te(e);o.sort(S);for(let p of o){let u=t.headers.get(p);u!==null&&s.push([p,u])}let a=st(JSON.stringify([r.toString(),s]));return new URL(a,rt).href}function st(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}$/,"")}function hr(t,e){return Ae(t),xe(e),new se(t,e)}var se=class extends h{constructor(r,s){super();this.cacheName=r;this.getKey=s;this.cacheName=r?.trim()||void 0}async handle(r,s){if(r.request.method!==f)return s();let o=this.cacheName?await caches.open(this.cacheName):caches.default,a=await this.getCached(o,r.request);if(a)return a;let p=await s();return this.setCached(o,r,p),p}async getCached(r,s){let o=this.getCacheKey(s),a=await r.match(o);if(!a)return;let p=this.getFilteredVary(a);if(p.length===0)return a;let u=re(s,p,o);return r.match(u)}async setCached(r,s,o){if(!be(o))return;let a=this.getCacheKey(s.request);s.ctx.waitUntil(r.put(a,o.clone()));let p=this.getFilteredVary(o);p.length>0&&s.ctx.waitUntil(r.put(re(s.request,p,a),o.clone()))}getFilteredVary(r){return te(ee(r))}getCacheKey(r){let s=this.getKey?this.getKey(r):Oe(r);return Re(s),s.hash="",s}};import{getReasonPhrase as ot,StatusCodes as C}from"http-status-codes";var oe=class{headers=new Headers;status=C.OK;statusText;webSocket=null;mediaType="text/plain";get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??ot(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){l(this.headers,e,r)}mergeHeader(e,r){H(this.headers,e,r)}addContentType(){this.headers.get(i.CONTENT_TYPE)||this.headers.set(i.CONTENT_TYPE,ge(this.mediaType))}},ne=class extends oe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.headers.set(i.CACHE_CONTROL,I.stringify(this.cache))}},A=class extends ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=this.status===C.NO_CONTENT?null:this.body;return r&&this.addContentType(),new Response(r,this.responseInit)}},U=class extends A{constructor(e,r){let s=e.clone();super(s.body,r),this.headers=new Headers(s.headers),this.status=s.status,this.statusText=s.statusText}},y=class extends A{constructor(e=null,r,s=C.OK){super(e,r),this.status=s}},G=class extends y{constructor(e={},r,s=C.OK){super(JSON.stringify(e),r,s),this.mediaType="application/json"}},Te=class extends y{constructor(e,r,s=C.OK){super(e,r,s),this.mediaType="text/html"}},_e=class extends y{constructor(e,r,s=C.OK){super(e,r,s),this.mediaType="text/plain"}},ie=class extends A{constructor(e,r,s){let{size:o,offset:a=0,length:p=o}=r;super(e,s),this.mediaType="application/octet-stream",this.setHeader(i.ACCEPT_RANGES,"bytes"),this.setHeader(i.CONTENT_LENGTH,`${p}`),(a>0||p<o)&&(this.setHeader(i.CONTENT_RANGE,`bytes ${a}-${a+p-1}/${o}`),this.status=C.PARTIAL_CONTENT)}},Ne=class t extends ie{constructor(e,r){super(e.body,t.computeRange(e),r),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType)}static computeRange(e){let r=e.size;if(!e.range)return{size:r,offset:0,length:r};if("suffix"in e.range){let a=Math.max(0,r-e.range.suffix),p=r-a;return{size:r,offset:a,length:p}}let{offset:s=0,length:o=r}=e.range;return{size:r,offset:s,length:o}}},Le=class extends A{constructor(e){super(null),this.status=C.SWITCHING_PROTOCOLS,this.webSocket=e}},V=class extends A{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},N=class extends A{constructor(){super(),this.status=C.NO_CONTENT}};var K="*",we=new Set([f,k,b]),ye=[m.SWITCHING_PROTOCOLS,m.CONTINUE,m.PROCESSING,m.EARLY_HINTS,m.MOVED_PERMANENTLY,m.MOVED_TEMPORARILY,m.SEE_OTHER,m.TEMPORARY_REDIRECT,m.PERMANENT_REDIRECT],Pe={allowedOrigins:[K],allowedHeaders:[i.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*le.Minute};async function ve(t,e){let r=new N,s=Q(t.request);return s&&(We(r.headers,e,s),ke(r.headers,e,s)),nt(r.headers,t),at(r.headers,e),it(r.headers,e),r.response()}async function Ie(t,e,r){let s=new U(t),o=Q(e.request);return pt(s.headers),o&&(We(s.headers,r,o),ke(s.headers,r,o),ct(s.headers,r)),s.response()}function We(t,e,r){De(e)?l(t,i.ACCESS_CONTROL_ALLOW_ORIGIN,K):(e.allowedOrigins.includes(r)&&l(t,i.ACCESS_CONTROL_ALLOW_ORIGIN,r),H(t,i.VARY,i.ORIGIN))}function ke(t,e,r){e.allowCredentials&&(De(e)||e.allowedOrigins.includes(r)&&l(t,i.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function nt(t,e){let r=e.getAllowedMethods();T(r);let s=r.filter(o=>!we.has(o));s.length>0&&l(t,i.ACCESS_CONTROL_ALLOW_METHODS,s)}function it(t,e){let r=Math.max(0,Math.floor(e.maxAge));l(t,i.ACCESS_CONTROL_MAX_AGE,String(r))}function at(t,e){e.allowedHeaders.length>0&&l(t,i.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function ct(t,e){l(t,i.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function De(t){return t.allowedOrigins.includes(K)}function pt(t){t.delete(i.ACCESS_CONTROL_MAX_AGE),t.delete(i.ACCESS_CONTROL_ALLOW_ORIGIN),t.delete(i.ACCESS_CONTROL_ALLOW_HEADERS),t.delete(i.ACCESS_CONTROL_ALLOW_METHODS),t.delete(i.ACCESS_CONTROL_EXPOSE_HEADERS),t.delete(i.ACCESS_CONTROL_ALLOW_CREDENTIALS)}function Me(t){let{status:e,headers:r}=t;return!!(ye.includes(e)||r.has(i.UPGRADE))}function He(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&&!D(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!D(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!D(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!Se(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!M(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}function Gr(t){return He(t),new ae(t)}var ae=class extends h{config;constructor(e){super(),this.config={...Pe,...e}}async handle(e,r){if(e.request.method===b)return ve(e,this.config);let s=await r();return Me(s)?s:Ie(s,e,this.config)}};import{getReasonPhrase as ut,StatusCodes as E}from"http-status-codes";var d=class extends G{constructor(r,s){let o={status:r,error:ut(r),details:s??""};super(o,I.DISABLE,r);this.details=s}},P=class extends d{constructor(e){super(E.BAD_REQUEST,e)}},Ue=class extends d{constructor(e){super(E.UNAUTHORIZED,e)}},Ge=class extends d{constructor(e){super(E.FORBIDDEN,e)}},x=class extends d{constructor(e){super(E.NOT_FOUND,e)}},v=class extends d{constructor(e){let r=e.getAllowedMethods();T(r),super(E.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(i.ALLOW,r)}},q=class extends d{constructor(){super(E.UPGRADE_REQUIRED),this.headers.set(i.SEC_WEBSOCKET_VERSION,"13")}},B=class extends d{constructor(e){super(E.INTERNAL_SERVER_ERROR,e)}},ce=class extends d{constructor(e){super(E.NOT_IMPLEMENTED,e)}},R=class extends ce{constructor(e){super(`${e.request.method} method not implemented.`)}},Ve=class extends d{constructor(e){super(E.SERVICE_UNAVAILABLE,e)}};function Ke(t){return _(t,i.CONNECTION).some(e=>e.toLowerCase()===de)}function qe(t){return _(t,i.UPGRADE).some(e=>e.toLowerCase()===me)}function Be(t){return t.get(i.SEC_WEBSOCKET_VERSION)?.trim()==="13"}function rs(t="/"){return new pe(t)}var pe=class extends h{constructor(r){super();this.path=r}handle(r,s){if(r.request.method!==f||this.getPath(r.request)!==this.path)return s();let o=r.request.headers;return Ke(o)?qe(o)?Be(o)?s():new q().response():new P("Missing or invalid Upgrade header").response():new P("Missing or invalid Connection header").response()}getPath(r){return new URL(r.url).pathname}};function lt(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function Xe(t){return g(t)?t.length>0:lt(t)?t.byteLength>0:!1}function Ye(t){return M(t)?dt(t)&&!mt(t)?t:O.NORMAL:O.NORMAL}function dt(t){return t>=O.NORMAL&&t<=4999}function mt(t){return Ce.has(t)}function Fe(t){if(g(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}function ze(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 X=class t{server;static isCustomEvent(e){return["open","warn"].includes(e)}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 a of o)a(r)}warn(e){this.dispatch("warn",{type:"warn",message:e})}open(){this.dispatch("open",new Event("open"),!0)}};var L=class extends X{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(!Xe(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};ze(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(Ye(e),Fe(r))}onclose=e=>{this.close(e.code,e.reason)}};var Y=class extends L{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return e.acceptWebSocket(this.server,r),this.ready()}accept(){return this.server.accept(),this.ready()}ready(){return this.accepted=!0,this.open(),this.client}};var F=class extends L{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 Je=class{map=new Map;create(e){class r extends Y{constructor(p){super();this.sessions=p}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(p,u){return this.sessions.register(this.server,this),super.acceptWebSocket(p,u)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends F{constructor(o,a){super(a),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)}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)}};var w=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 T(r),Z(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}async response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};function je(t){if(!(t instanceof h))throw new TypeError("Handler must be a subclass of Middleware.")}var z=class extends w{middlewares=[];init(){}use(e){return je(e),this.middlewares.push(e),this}async fetch(){return await this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.dispatch())()}};var J=class extends z{async fetch(){if(!this.isAllowed(this.request.method))return this.response(v,this);try{return await this.init(),await super.fetch()}catch(e){return console.error(e),this.response(B)}}async 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)))()}async get(){return this.response(R,this)}async put(){return this.response(R,this)}async post(){return this.response(R,this)}async patch(){return this.response(R,this)}async delete(){return this.response(R,this)}async options(){return this.response(N)}async head(){let e=this.create(new Request(this.request.url,{method:f,headers:this.request.headers}));return this.response(V,await e.fetch())}getAllowedMethods(){return[f,k,b]}};import{match as ht}from"path-to-regexp";var j=class{routes=[];add(e){for(let[r,s,o]of e){let a=ht(s);this.routes.push({method:r,matcher:a,handler:o})}}match(e,r){let s=new URL(r).pathname;for(let o of this){if(o.method!==e)continue;let a=o.matcher(s);if(a)return{route:o,params:a.params}}return null}*[Symbol.iterator](){yield*this.routes}};var $e=class t extends J{_routes=new j;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 w.prototype.isPrototypeOf(e.prototype)}async get(){return this.response(x)}async put(){return this.response(x)}async post(){return this.response(x)}async patch(){return this.response(x)}async delete(){return this.response(x)}};export{P as BadRequest,J as BasicWorker,I as CacheControl,U as ClonedResponse,O as CloseCode,Ht as DELETE,Ge as Forbidden,f as GET,k as HEAD,V as Head,Te as HtmlResponse,d as HttpError,i as HttpHeader,B as InternalServerError,G as JsonResponse,Ze as MediaType,W as Method,v as MethodNotAllowed,R as MethodNotImplemented,x as NotFound,ce as NotImplemented,b as OPTIONS,ie as OctetStream,N as Options,Mt as PATCH,Dt as POST,kt as PUT,Ne as R2ObjectStream,$e as RouteWorker,Ve as ServiceUnavailable,m as StatusCodes,y as SuccessResponse,_e as TextResponse,le as Time,Ue as Unauthorized,q as UpgradeRequired,he as WS_MAX_CLOSE_CODE,fe as WS_MAX_REASON_CHARS,Ce as WS_RESERVED_CODES,de as WS_UPGRADE,$ as WS_VERSION,me as WS_WEBSOCKET,Je as WebSocketSessions,Le as WebSocketUpgrade,A as WorkerResponse,T as assertMethods,hr as cache,Gr as cors,ge as getContentType,_ as getHeaderValues,Q as getOrigin,Z as isMethod,et as isMethodArray,S as lexCompare,H as mergeHeader,l as setHeader,Oe as sortSearchParams,rr as stripSearchParams,rs as websocket};
1
+ import{StatusCodes as h}from"http-status-codes";import pe from"cache-control-parser";var L={parse:pe.parse,stringify:pe.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var M=(u=>(u.GET="GET",u.PUT="PUT",u.HEAD="HEAD",u.POST="POST",u.PATCH="PATCH",u.DELETE="DELETE",u.OPTIONS="OPTIONS",u))(M||{}),{GET:f,PUT:Pt,HEAD:D,POST:kt,PATCH:Mt,DELETE:Dt,OPTIONS:b}=M;var de={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var m=class{};function H(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function x(t){return typeof t=="string"}function le(t){return typeof t=="function"}function E(t){return typeof t=="number"&&!Number.isNaN(t)}function he(t){return typeof t=="boolean"}function me(t){if(t!==void 0&&!x(t))throw new TypeError("Cache name must be a string.")}function fe(t){if(t!==void 0&&!le(t))throw new TypeError("getKey must be a function.")}function Ce(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}var n;(a=>(a.ACCEPT_ENCODING="Accept-Encoding",a.ACCEPT_RANGES="Accept-Ranges",a.ALLOW="Allow",a.CACHE_CONTROL="Cache-Control",a.CONNECTION="Connection",a.CONTENT_DISPOSITION="Content-Disposition",a.CONTENT_ENCODING="Content-Encoding",a.CONTENT_LANGUAGE="Content-Language",a.CONTENT_LENGTH="Content-Length",a.CONTENT_RANGE="Content-Range",a.CONTENT_TYPE="Content-Type",a.CONTENT_MD5="Content-MD5",a.ETAG="ETag",a.ORIGIN="Origin",a.VARY="Vary",a.ACCESS_CONTROL_ALLOW_CREDENTIALS="Access-Control-Allow-Credentials",a.ACCESS_CONTROL_ALLOW_HEADERS="Access-Control-Allow-Headers",a.ACCESS_CONTROL_ALLOW_METHODS="Access-Control-Allow-Methods",a.ACCESS_CONTROL_ALLOW_ORIGIN="Access-Control-Allow-Origin",a.ACCESS_CONTROL_EXPOSE_HEADERS="Access-Control-Expose-Headers",a.ACCESS_CONTROL_MAX_AGE="Access-Control-Max-Age",a.SEC_WEBSOCKET_VERSION="Sec-WebSocket-Version",a.UPGRADE="Upgrade"))(n||={});var Ee=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],Se=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function S(t,e){return t<e?-1:t>e?1:0}function d(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(S);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function G(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let i=R(t,e).concat(s.map(c=>c.trim()));d(t,e,i)}function R(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(S)}function Q(t,e){for(let r of e)t.delete(r)}var Ze="https://vary";function Oe(t){return!(!t.ok||Z(t).includes("*"))}function Z(t){let e=R(t.headers,n.VARY);return Array.from(new Set(e.map(r=>r.toLowerCase()))).sort(S)}function ee(t){return t.map(e=>e.toLowerCase()).filter(e=>e!==n.ACCEPT_ENCODING.toLowerCase())}function te(t,e,r){let s=[],o=ee(e);o.sort(S);for(let c of o){let u=t.headers.get(c);u!==null&&s.push([c,u])}let i=et(JSON.stringify([r.toString(),s]));return new URL(i,Ze).href}function et(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}$/,"")}function ur(t,e){return me(t),fe(e),new re(t,e)}function tt(t){let e=new URL(t.url),r=new URLSearchParams([...e.searchParams.entries()].sort(([s],[o])=>S(s,o)));return e.search=r.toString(),e.hash="",e}function pr(t){let e=new URL(t.url);return e.search="",e.hash="",e}var re=class extends m{constructor(r,s){super();this.cacheName=r;this.getKey=s;this.cacheName=r?.trim()||void 0}async handle(r,s){if(r.request.method!==f)return s();let o=this.cacheName?await caches.open(this.cacheName):caches.default,i=await this.getCached(o,r.request);if(i)return i;let c=await s();return this.setCached(o,r,c),c}async getCached(r,s){let o=this.getCacheKey(s),i=await r.match(o);if(!i)return;let c=this.getFilteredVary(i);if(c.length===0)return i;let u=te(s,c,o);return r.match(u)}async setCached(r,s,o){if(!Oe(o))return;let i=this.getCacheKey(s.request);s.ctx.waitUntil(r.put(i,o.clone()));let c=this.getFilteredVary(o);c.length>0&&s.ctx.waitUntil(r.put(te(s.request,c,i),o.clone()))}getFilteredVary(r){return ee(Z(r))}getCacheKey(r){let s=this.getKey?this.getKey(r):tt(r);return Ce(s),s.hash="",s}};var rt=new Set(Object.values(M));function se(t){return x(t)&&rt.has(t)}function st(t){return Array.isArray(t)&&t.every(se)}function N(t){if(!st(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}import{getReasonPhrase as ot,StatusCodes as p}from"http-status-codes";var v="utf-8";function I(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}function ge(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)}).`)}var oe=class{headers=new Headers;status=p.OK;statusText;webSocket=null;mediaType=I("text/plain",v);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??ot(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){d(this.headers,e,r)}mergeHeader(e,r){G(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===p.NO_CONTENT?Q(this.headers,Se):this.status===p.NOT_MODIFIED&&Q(this.headers,Ee)}},ne=class extends oe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,L.stringify(this.cache))}},O=class extends ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=[p.NO_CONTENT,p.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},U=class extends O{constructor(e,r){let s=e.clone();super(s.body,r),this.headers=new Headers(s.headers),this.status=s.status,this.statusText=s.statusText}},W=class extends O{constructor(e=null,r,s=p.OK){super(e,r),this.status=s}},V=class extends W{constructor(e={},r,s=p.OK){super(JSON.stringify(e),r,s),this.mediaType=I("application/json",v)}},Ae=class extends W{constructor(e,r,s=p.OK,o=v){super(e,r,s),this.mediaType=I("text/html",o)}},xe=class extends W{constructor(e,r,s=p.OK,o=v){super(e,r,s),this.mediaType=I("text/plain",o)}},ie=class t extends O{constructor(e,r,s){ge(r),super(e,s),this.mediaType="application/octet-stream";let{size:o,offset:i,length:c}=t.normalizeInit(r);t.isPartial(r)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${i}-${i+c-1}/${o}`),this.status=p.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!==void 0||e.length!==void 0}},Te=class t extends ie{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=L.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}}},be=class extends O{constructor(e){super(null),this.status=p.SWITCHING_PROTOCOLS,this.webSocket=e}},q=class extends O{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},y=class extends O{constructor(){super(),this.status=p.NO_CONTENT}};var K="*",Re=new Set([f,D,b]),Ne=[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],ye={allowedOrigins:[K],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*de.Minute};async function _e(t,e){let r=new y,s=Pe(t.request);return s&&(Le(r.headers,e,s),ve(r.headers,e,s)),nt(r.headers,t),at(r.headers,e),it(r.headers,e),r.response()}async function we(t,e,r){let s=new U(t),o=Pe(e.request);return ut(s.headers),o&&(Le(s.headers,r,o),ve(s.headers,r,o),ct(s.headers,r)),s.response()}function Le(t,e,r){Ie(e)?d(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,K):(e.allowedOrigins.includes(r)&&d(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r),G(t,n.VARY,n.ORIGIN))}function ve(t,e,r){e.allowCredentials&&(Ie(e)||e.allowedOrigins.includes(r)&&d(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function nt(t,e){let r=e.getAllowedMethods();N(r);let s=r.filter(o=>!Re.has(o));s.length>0&&d(t,n.ACCESS_CONTROL_ALLOW_METHODS,s)}function it(t,e){let r=Math.max(0,Math.floor(e.maxAge));d(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function at(t,e){e.allowedHeaders.length>0&&d(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function ct(t,e){d(t,n.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function Ie(t){return t.allowedOrigins.includes(K)}function ut(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 We(t){let{status:e,headers:r}=t;return!!(Ne.includes(e)||r.has(n.UPGRADE))}function Pe(t){let e=t.headers.get(n.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}function ke(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&&!H(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!H(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!H(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!he(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.")}function jr(t){return ke(t),new ae(t)}var ae=class extends m{config;constructor(e){super(),this.config={...ye,...e}}async handle(e,r){if(e.request.method===b)return _e(e,this.config);let s=await r();return We(s)?s:we(s,e,this.config)}};import{getReasonPhrase as pt,StatusCodes as C}from"http-status-codes";var Me="upgrade",De="websocket";var T={NORMAL:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS:1005,ABNORMAL:1006,INVALID_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,MISSING_EXTENSION:1010,INTERNAL_ERROR:1011,TLS_HANDSHAKE:1015},He=new Set([T.NO_STATUS,T.ABNORMAL,T.TLS_HANDSHAKE]);var l=class extends V{constructor(r,s){let o={status:r,error:pt(r),details:s??""};super(o,L.DISABLE,r);this.details=s}},P=class extends l{constructor(e){super(C.BAD_REQUEST,e)}},Ge=class extends l{constructor(e){super(C.UNAUTHORIZED,e)}},Ue=class extends l{constructor(e){super(C.FORBIDDEN,e)}},g=class extends l{constructor(e){super(C.NOT_FOUND,e)}},k=class extends l{constructor(e){let r=e.getAllowedMethods();N(r),super(C.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},B=class extends l{constructor(){super(C.UPGRADE_REQUIRED),this.headers.set(n.SEC_WEBSOCKET_VERSION,"13")}},F=class extends l{constructor(e){super(C.INTERNAL_SERVER_ERROR,e)}},ce=class extends l{constructor(e){super(C.NOT_IMPLEMENTED,e)}},A=class extends ce{constructor(e){super(`${e.request.method} method not implemented.`)}},Ve=class extends l{constructor(e){super(C.SERVICE_UNAVAILABLE,e)}};function Ke(t){return R(t,n.CONNECTION).some(e=>e.toLowerCase()===Me)}function Be(t){return R(t,n.UPGRADE).some(e=>e.toLowerCase()===De)}function Fe(t){return t.get(n.SEC_WEBSOCKET_VERSION)?.trim()==="13"}function ps(t="/"){return new ue(t)}var ue=class extends m{constructor(r){super();this.path=r}handle(r,s){if(r.request.method!==f||this.getPath(r.request)!==this.path)return s();let o=r.request.headers;return Ke(o)?Be(o)?Fe(o)?s():new B().response():new P("Missing or invalid Upgrade header").response():new P("Missing or invalid Connection header").response()}getPath(r){return new URL(r.url).pathname}};function ht(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function Ye(t){return x(t)?t.length>0:ht(t)?t.byteLength>0:!1}function je(t){return E(t)?mt(t)&&!ft(t)?t:T.NORMAL:T.NORMAL}function mt(t){return t>=T.NORMAL&&t<=4999}function ft(t){return He.has(t)}function ze(t){if(x(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}function $e(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 Y=class t{server;static isCustomEvent(e){return["open","warn"].includes(e)}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)}};var _=class extends Y{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(!Ye(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};$e(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(je(e),ze(r))}onclose=e=>{this.close(e.code,e.reason)}};var j=class extends _{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return e.acceptWebSocket(this.server,r),this.ready()}accept(){return this.server.accept(),this.ready()}ready(){return this.accepted=!0,this.open(),this.client}};var z=class extends _{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 Je=class{map=new Map;create(e){class r extends j{constructor(c){super();this.sessions=c}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(c,u){return this.sessions.register(this.server,this),super.acceptWebSocket(c,u)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends z{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)}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)}};var w=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 N(r),se(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}async response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};function Xe(t){if(!(t instanceof m))throw new TypeError("Handler must be a subclass of Middleware.")}var $=class extends w{middlewares=[];init(){}use(e){return Xe(e),this.middlewares.push(e),this}async fetch(){return await this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.dispatch())()}};var J=class extends ${async fetch(){if(!this.isAllowed(this.request.method))return this.response(k,this);try{return await this.init(),await super.fetch()}catch(e){return console.error(e),this.response(F)}}async 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(k,this)))()}async get(){return this.response(A,this)}async put(){return this.response(A,this)}async post(){return this.response(A,this)}async patch(){return this.response(A,this)}async delete(){return this.response(A,this)}async options(){return this.response(y)}async head(){let e=this.create(new Request(this.request.url,{method:f,headers:this.request.headers}));return this.response(q,await e.fetch())}getAllowedMethods(){return[f,D,b]}};import{match as Ct}from"path-to-regexp";var X=class{routes=[];add(e){for(let[r,s,o]of e){let i=Ct(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 Qe=class t extends J{_routes=new X;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 w.prototype.isPrototypeOf(e.prototype)}async get(){return this.response(g)}async put(){return this.response(g)}async post(){return this.response(g)}async patch(){return this.response(g)}async delete(){return this.response(g)}};export{P as BadRequest,J as BasicWorker,L as CacheControl,U as ClonedResponse,Dt as DELETE,Ue as Forbidden,f as GET,D as HEAD,q as Head,Ae as HtmlResponse,l as HttpError,F as InternalServerError,V as JsonResponse,M as Method,k as MethodNotAllowed,A as MethodNotImplemented,g as NotFound,ce as NotImplemented,b as OPTIONS,ie as OctetStream,y as Options,Mt as PATCH,kt as POST,Pt as PUT,Te as R2ObjectStream,Qe as RouteWorker,Ve as ServiceUnavailable,h as StatusCodes,W as SuccessResponse,xe as TextResponse,de as Time,Ge as Unauthorized,B as UpgradeRequired,Je as WebSocketSessions,be as WebSocketUpgrade,O as WorkerResponse,ur as cache,jr as cors,tt as sortSearchParams,pr as stripSearchParams,ps as websocket};
2
2
  //# sourceMappingURL=index.js.map