@adonix.org/cloud-spark 0.0.181 → 0.0.183
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 +201 -11
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/dist/index.d.ts
CHANGED
|
@@ -368,7 +368,7 @@ type RouteTable = Iterable<RouteTuple>;
|
|
|
368
368
|
* This middleware:
|
|
369
369
|
* - Caches `GET` requests **only**.
|
|
370
370
|
* - Respects the `Vary` header of responses, ensuring that requests
|
|
371
|
-
* with different headers (e.g., `
|
|
371
|
+
* with different headers (e.g., `Accept-Language`) receive the correct cached response.
|
|
372
372
|
* - Skips caching for non-cacheable responses (e.g., error responses or
|
|
373
373
|
* responses with `Vary: *`).
|
|
374
374
|
*
|
|
@@ -376,7 +376,7 @@ type RouteTable = Iterable<RouteTuple>;
|
|
|
376
376
|
* @param init.name Optional name of the cache to use. If omitted, the default cache is used.
|
|
377
377
|
* @param init.getKey Optional function to compute a custom cache key from a request.
|
|
378
378
|
*
|
|
379
|
-
* @returns A
|
|
379
|
+
* @returns A {@link Middleware} instance that can be used in your middleware chain.
|
|
380
380
|
*/
|
|
381
381
|
declare function cache(init?: Partial<CacheInit>): Middleware;
|
|
382
382
|
|
|
@@ -402,7 +402,7 @@ declare function sortSearchParams(request: Request): URL;
|
|
|
402
402
|
declare function stripSearchParams(request: Request): URL;
|
|
403
403
|
|
|
404
404
|
/**
|
|
405
|
-
*
|
|
405
|
+
* Returns a `CORS` middleware instance.
|
|
406
406
|
*
|
|
407
407
|
* This middleware automatically handles Cross-Origin Resource Sharing (CORS)
|
|
408
408
|
* for incoming requests, including preflight `OPTIONS` requests, and adds
|
|
@@ -413,47 +413,230 @@ declare function stripSearchParams(request: Request): URL;
|
|
|
413
413
|
*/
|
|
414
414
|
declare function cors(init?: CorsInit): Middleware;
|
|
415
415
|
|
|
416
|
+
/**
|
|
417
|
+
* Returns a middleware that validates incoming WebSocket upgrade requests.
|
|
418
|
+
*
|
|
419
|
+
* - Only validates the upgrade request; it does **not** perform the actual WebSocket upgrade.
|
|
420
|
+
* - Ensures the request:
|
|
421
|
+
* - Uses the `GET` method.
|
|
422
|
+
* - Matches the specified path, supporting `path-to-regex` style patterns
|
|
423
|
+
* (e.g., `/chat/:name`).
|
|
424
|
+
* - Contains required WebSocket headers:
|
|
425
|
+
* - `Connection: Upgrade`
|
|
426
|
+
* - `Upgrade: websocket`
|
|
427
|
+
* - `Sec-WebSocket-Version` matches the expected version
|
|
428
|
+
* - Returns an error response if validation fails, otherwise passes control to
|
|
429
|
+
* the next middleware or origin handler.
|
|
430
|
+
*
|
|
431
|
+
* @param path - The URL path to intercept for WebSocket upgrades. Defaults to `/`.
|
|
432
|
+
* Supports dynamic segments using `path-to-regex` syntax.
|
|
433
|
+
* @returns A {@link Middleware} instance that can be used in your middleware chain.
|
|
434
|
+
*
|
|
435
|
+
* @example
|
|
436
|
+
* ```ts
|
|
437
|
+
* app.use(websocket("/chat/:name"));
|
|
438
|
+
* ```
|
|
439
|
+
*/
|
|
416
440
|
declare function websocket(path?: string): Middleware;
|
|
417
441
|
|
|
442
|
+
/**
|
|
443
|
+
* Represents a warning event emitted by a WebSocket.
|
|
444
|
+
*/
|
|
418
445
|
type WarnEvent = {
|
|
419
446
|
type: "warn";
|
|
420
447
|
message: string;
|
|
421
448
|
};
|
|
449
|
+
/**
|
|
450
|
+
* Map of custom WebSocket events.
|
|
451
|
+
* - `warn`: internal warning notifications
|
|
452
|
+
* - `open`: triggered when the WebSocket is accepted
|
|
453
|
+
*/
|
|
422
454
|
type CustomEventMap = {
|
|
423
455
|
warn: WarnEvent;
|
|
424
456
|
open: Event;
|
|
425
457
|
};
|
|
458
|
+
/** Options for registering WebSocket event listeners. */
|
|
426
459
|
type EventOptions = {
|
|
427
460
|
once?: boolean;
|
|
428
461
|
};
|
|
462
|
+
/** Map of all events, combining native WebSocket events and custom events. */
|
|
429
463
|
type ExtendedEventMap = WebSocketEventMap & CustomEventMap;
|
|
464
|
+
/** Names of all events, including standard and custom WebSocket events. */
|
|
430
465
|
type ExtendedEventType = keyof ExtendedEventMap;
|
|
466
|
+
/** Event listener type for an extended WebSocket event. */
|
|
431
467
|
type ExtendedEventListener<K extends ExtendedEventType> = (ev: ExtendedEventMap[K]) => void;
|
|
468
|
+
/**
|
|
469
|
+
* Represents a user-defined attachment object that can be associated with a WebSocket connection.
|
|
470
|
+
*/
|
|
432
471
|
type WSAttachment = object;
|
|
472
|
+
/**
|
|
473
|
+
* Represents a managed WebSocket connection with typed attachment and extended event support.
|
|
474
|
+
*
|
|
475
|
+
* @template A - Type of the attachment object associated with this connection.
|
|
476
|
+
*/
|
|
433
477
|
interface WebSocketConnection<A extends WSAttachment> {
|
|
478
|
+
/**
|
|
479
|
+
* Current readyState of the WebSocket (0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED).
|
|
480
|
+
*/
|
|
434
481
|
get readyState(): number;
|
|
482
|
+
/**
|
|
483
|
+
* Checks whether the WebSocket is currently in one of the provided states.
|
|
484
|
+
*
|
|
485
|
+
* @param states - List of WebSocket readyState values to check against.
|
|
486
|
+
* @returns `true` if the WebSocket's readyState matches any of the provided states.
|
|
487
|
+
*/
|
|
435
488
|
isState(...states: number[]): boolean;
|
|
489
|
+
/**
|
|
490
|
+
* Accepts the WebSocket connection if not already accepted.
|
|
491
|
+
*
|
|
492
|
+
* @returns The readonly native WebSocket instance.
|
|
493
|
+
*/
|
|
436
494
|
accept(): Readonly<WebSocket>;
|
|
495
|
+
/**
|
|
496
|
+
* Accepts the WebSocket connection in the context of a Durable Object.
|
|
497
|
+
* Optionally associates tags for filtering.
|
|
498
|
+
*
|
|
499
|
+
* @param ctx - DurableObjectState for the WebSocket.
|
|
500
|
+
* @param tags - Optional list of string tags.
|
|
501
|
+
* @returns The readonly native WebSocket instance.
|
|
502
|
+
*/
|
|
437
503
|
acceptWebSocket(ctx: DurableObjectState, tags?: string[]): Readonly<WebSocket>;
|
|
504
|
+
/**
|
|
505
|
+
* Retrieves the user-defined attachment object associated with this connection.
|
|
506
|
+
*
|
|
507
|
+
* The returned object is a read-only view of the attachment to prevent
|
|
508
|
+
* accidental mutation. To modify the attachment, call {@link attach}.
|
|
509
|
+
*
|
|
510
|
+
* @returns A read-only view of the current attachment.
|
|
511
|
+
*/
|
|
438
512
|
get attachment(): Readonly<A>;
|
|
513
|
+
/**
|
|
514
|
+
* Attaches a user-defined object to this WebSocket connection.
|
|
515
|
+
*
|
|
516
|
+
* @param attachment - Object containing the metadata to attach.
|
|
517
|
+
*/
|
|
439
518
|
attach(attachment: A): void;
|
|
519
|
+
/**
|
|
520
|
+
* Sends a message to the connected WebSocket client.
|
|
521
|
+
*
|
|
522
|
+
* @param message - Message to send, either string or binary data.
|
|
523
|
+
*/
|
|
440
524
|
send(message: string | ArrayBuffer): void;
|
|
525
|
+
/**
|
|
526
|
+
* Closes the WebSocket connection with an optional code and reason.
|
|
527
|
+
*
|
|
528
|
+
* @param code - Close code (default is `1000` NORMAL).
|
|
529
|
+
* @param reason - Optional reason string (sanitized to valid characters).
|
|
530
|
+
*/
|
|
441
531
|
close(code?: number, reason?: string): void;
|
|
532
|
+
/**
|
|
533
|
+
* Registers an event listener for a WebSocket event.
|
|
534
|
+
*
|
|
535
|
+
* Supports both standard WebSocket events (`message`, `close`, etc.)
|
|
536
|
+
* and custom events (`open`, `warn`).
|
|
537
|
+
*
|
|
538
|
+
* @param type - Event type to listen for.
|
|
539
|
+
* @param listener - Callback invoked when the event occurs.
|
|
540
|
+
* @param options - Optional event listener options (`once`).
|
|
541
|
+
*/
|
|
442
542
|
addEventListener<K extends ExtendedEventType>(type: K, listener: ExtendedEventListener<K>, options?: EventOptions): void;
|
|
543
|
+
/**
|
|
544
|
+
* Removes a previously registered WebSocket event listener.
|
|
545
|
+
*
|
|
546
|
+
* Works for both standard and custom events.
|
|
547
|
+
*
|
|
548
|
+
* @param type - Event type to remove.
|
|
549
|
+
* @param listener - Listener function to remove.
|
|
550
|
+
*/
|
|
443
551
|
removeEventListener<K extends ExtendedEventType>(type: K, listener: ExtendedEventListener<K>): void;
|
|
444
552
|
}
|
|
445
553
|
|
|
554
|
+
/**
|
|
555
|
+
* Manages active WebSocket connections in a Cloudflare Workers environment.
|
|
556
|
+
*
|
|
557
|
+
* Provides a simple interface for creating, restoring, and managing
|
|
558
|
+
* WebSocket connections with optional attachments. Users can:
|
|
559
|
+
*
|
|
560
|
+
* - Create new WebSocket connections (`create`) and attach arbitrary data.
|
|
561
|
+
* - Accept connections using the standard WebSocket API (`accept`).
|
|
562
|
+
* - Accept connections using the hibernatable WebSocket API (`acceptWebSocket`),
|
|
563
|
+
* which allows the connection to be put to sleep when inactive.
|
|
564
|
+
* - Restore existing WebSockets into a managed session (`restore`, `restoreAll`),
|
|
565
|
+
* maintaining their hibernation state.
|
|
566
|
+
* - Iterate over active connections or retrieve a connection by its WebSocket instance.
|
|
567
|
+
* - Close a connection cleanly with optional code and reason (`close`).
|
|
568
|
+
*
|
|
569
|
+
* @template A - Type of attachment data stored on each WebSocket connection.
|
|
570
|
+
*/
|
|
446
571
|
declare class WebSocketSessions<A extends WSAttachment = WSAttachment> {
|
|
572
|
+
/** @internal Map of active WebSocket to their connection wrapper. */
|
|
447
573
|
private readonly map;
|
|
574
|
+
/**
|
|
575
|
+
* Create a new WebSocket connection and optionally attach user data.
|
|
576
|
+
*
|
|
577
|
+
* @param attachment - Partial attachment object to initialize the connection with.
|
|
578
|
+
* @returns A `WebSocketConnection` instance ready for accepting and sending messages.
|
|
579
|
+
*/
|
|
448
580
|
create(attachment?: Partial<A>): WebSocketConnection<A>;
|
|
581
|
+
/**
|
|
582
|
+
* Wraps an existing WebSocket in a managed connection session.
|
|
583
|
+
*
|
|
584
|
+
* @param ws - An existing WebSocket to restore.
|
|
585
|
+
* @returns A `WebSocketConnection` representing the restored session.
|
|
586
|
+
*/
|
|
449
587
|
restore(ws: WebSocket): WebSocketConnection<A>;
|
|
588
|
+
/**
|
|
589
|
+
* Restores multiple WebSockets into managed sessions at once.
|
|
590
|
+
*
|
|
591
|
+
* @param all - Array of WebSocket instances to restore.
|
|
592
|
+
* @returns Array of `WebSocketConnections` restored.
|
|
593
|
+
*/
|
|
450
594
|
restoreAll(all: WebSocket[]): ReadonlyArray<WebSocketConnection<A>>;
|
|
595
|
+
/**
|
|
596
|
+
* Retrieves the managed connection for a specific WebSocket, if any.
|
|
597
|
+
*
|
|
598
|
+
* @param ws - WebSocket instance.
|
|
599
|
+
* @returns Corresponding `WebSocketConnection` or `undefined` if not managed.
|
|
600
|
+
*/
|
|
451
601
|
get(ws: WebSocket): WebSocketConnection<A> | undefined;
|
|
602
|
+
/**
|
|
603
|
+
* Selects the managed `WebSocketConnection` objects corresponding to the given WebSockets.
|
|
604
|
+
*
|
|
605
|
+
* @param sockets - Array of WebSocket instances to resolve.
|
|
606
|
+
* @returns Array of corresponding `WebSocketConnection` objects.
|
|
607
|
+
*/
|
|
608
|
+
select(sockets: WebSocket[]): WebSocketConnection<A>[];
|
|
609
|
+
/**
|
|
610
|
+
* Returns an iterator over all active `WebSocketConnection` objects
|
|
611
|
+
* managed by this session.
|
|
612
|
+
*
|
|
613
|
+
* Useful for iterating over all connections to perform actions such as
|
|
614
|
+
* broadcasting messages.
|
|
615
|
+
*
|
|
616
|
+
* @returns Iterable iterator of all active `WebSocketConnection` objects.
|
|
617
|
+
*/
|
|
452
618
|
values(): IterableIterator<WebSocketConnection<A>>;
|
|
619
|
+
/**
|
|
620
|
+
* Returns an iterator over all active raw `WebSocket` instances
|
|
621
|
+
* currently tracked by this session.
|
|
622
|
+
*
|
|
623
|
+
* @returns Iterable iterator of all active `WebSocket` instances.
|
|
624
|
+
*/
|
|
453
625
|
keys(): IterableIterator<WebSocket>;
|
|
626
|
+
/**
|
|
627
|
+
* Closes a managed WebSocket connection with optional code and reason.
|
|
628
|
+
*
|
|
629
|
+
* @param ws - WebSocket to close.
|
|
630
|
+
* @param code - Optional WebSocket close code.
|
|
631
|
+
* @param reason - Optional reason string.
|
|
632
|
+
* @returns `true` if the connection was managed and removed, `false` otherwise.
|
|
633
|
+
*/
|
|
454
634
|
close(ws: WebSocket, code?: number, reason?: string): boolean;
|
|
635
|
+
/** Iterates over all active WebSocket connections. */
|
|
455
636
|
[Symbol.iterator](): IterableIterator<WebSocketConnection<A>>;
|
|
637
|
+
/** Registers a connection internally. */
|
|
456
638
|
private register;
|
|
639
|
+
/** Un-registers a connection internally. */
|
|
457
640
|
private unregister;
|
|
458
641
|
}
|
|
459
642
|
|
|
@@ -503,9 +686,15 @@ declare abstract class BaseWorker implements Worker {
|
|
|
503
686
|
*/
|
|
504
687
|
protected abstract dispatch(): Promise<Response>;
|
|
505
688
|
/**
|
|
506
|
-
*
|
|
507
|
-
*
|
|
508
|
-
*
|
|
689
|
+
* Determines whether a given HTTP method is allowed for this worker.
|
|
690
|
+
*
|
|
691
|
+
* - GET and HEAD are **always allowed**, in compliance with RFC 7231,
|
|
692
|
+
* even if they are not explicitly listed in `getAllowedMethods()`.
|
|
693
|
+
* - Other methods are allowed only if included in the array returned by
|
|
694
|
+
* `getAllowedMethods()` and are valid HTTP methods.
|
|
695
|
+
*
|
|
696
|
+
* @param method - The HTTP method to check (e.g., "GET", "POST").
|
|
697
|
+
* @returns `true` if the method is allowed, `false` otherwise.
|
|
509
698
|
*/
|
|
510
699
|
isAllowed(method: string): boolean;
|
|
511
700
|
abstract getAllowedMethods(): Method[];
|
|
@@ -611,10 +800,11 @@ declare abstract class BasicWorker extends MiddlewareWorker {
|
|
|
611
800
|
*/
|
|
612
801
|
protected head(): Promise<Response>;
|
|
613
802
|
/**
|
|
614
|
-
*
|
|
803
|
+
* Returns the HTTP methods allowed by this worker.
|
|
615
804
|
*
|
|
616
|
-
*
|
|
617
|
-
*
|
|
805
|
+
* - GET and HEAD are always allowed per RFC 7231, even if subclasses do not include them here.
|
|
806
|
+
* - OPTIONS is included by default since a default handler is implemented.
|
|
807
|
+
* - Subclasses can override this method to allow additional methods or change the defaults.
|
|
618
808
|
*/
|
|
619
809
|
getAllowedMethods(): Method[];
|
|
620
810
|
}
|
|
@@ -663,7 +853,8 @@ declare abstract class RouteWorker extends BasicWorker {
|
|
|
663
853
|
* - If the handler is a Worker class, a new instance is created and its `fetch()` is called.
|
|
664
854
|
* - If the handler is a callback function, it is invoked with the extracted path parameters.
|
|
665
855
|
*
|
|
666
|
-
* If no route matches, the request is passed to the
|
|
856
|
+
* If no route matches, the request is passed to the superclass ({@link BasicWorker})
|
|
857
|
+
* `dispatch()` handler.
|
|
667
858
|
*
|
|
668
859
|
* @returns A `Promise<Response>` from the matched handler or parent dispatch.
|
|
669
860
|
*/
|
|
@@ -677,7 +868,6 @@ declare abstract class RouteWorker extends BasicWorker {
|
|
|
677
868
|
* @returns `true` if `handler` is a subclass of `BaseWorker` at runtime, `false` otherwise.
|
|
678
869
|
*/
|
|
679
870
|
private static isWorkerClass;
|
|
680
|
-
protected get(): Promise<Response>;
|
|
681
871
|
protected put(): Promise<Response>;
|
|
682
872
|
protected post(): Promise<Response>;
|
|
683
873
|
protected patch(): Promise<Response>;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{StatusCodes as m}from"http-status-codes";import Ie from"cache-control-parser";var g={parse:Ie.parse,stringify:Ie.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var q=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(q||{}),{GET:R,PUT:tr,HEAD:B,POST:rr,PATCH:sr,DELETE:or,OPTIONS:F}=q;var Le={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 S(t){return typeof t=="string"}function h(t){return typeof t=="number"&&!Number.isNaN(t)}function He(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),wt(r)}function yt(t){if(t!==void 0&&!S(t))throw new TypeError("Cache name must be a string.")}function wt(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 N(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])=>N(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}async execute(e,r){return this.rules.reduceRight((o,i)=>()=>i.apply(e,o),()=>r())()}};import{StatusCodes as _t}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"},Me=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],ke=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function l(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(N);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()));l(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(N)}function Oe(t,e){for(let r of e)t.delete(r)}var It="https://vary",Lt="*";function De(t,e){if(e.status!==_t.OK||t.method!==R||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)||Ae(e).includes(Lt))return!1;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 g.parse(t.get(n.CACHE_CONTROL)??"")}function Ae(t){return w(d(t.headers,n.VARY))}function w(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(N);return Array.from(new Set(e))}function _(t,e,r){let s=[],o=w(e);for(let a of o){let c=t.headers.get(a);c!==null&&s.push([a,Ht(a,c)])}let i=vt(JSON.stringify([r.toString(),s]));return new URL(i,It).toString()}function Ht(t,e){switch(t.toLowerCase()){case n.ACCEPT:case n.ACCEPT_LANGUAGE:case n.ORIGIN:return e.toLowerCase();default:return e}}function vt(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 Wt=/^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=Wt.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&&!Be(t,e,Ve)}function qe(t,e){return Be(t,Fe(e),Ve)}function Be(t,...e){return t.some(r=>e.includes(r))}function Y(t){if(!S(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Fe(t){return t.startsWith(Ge)?t.slice(2):t}function Te(t){return{ifMatch:d(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:d(t,n.IF_NONE_MATCH).map(Fe),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}=Te(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(h(r))return r}var X=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 Dt,StatusCodes as C}from"http-status-codes";var $e="upgrade",Ye="websocket";var x={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},Xe=new Set([x.NO_STATUS,x.ABNORMAL,x.TLS_HANDSHAKE]);var Pt=new Set(Object.values(q));function be(t){return S(t)&&Pt.has(t)}function Mt(t){return Array.isArray(t)&&t.every(be)}function A(t){if(!Mt(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}import{getReasonPhrase as kt,StatusCodes as p}from"http-status-codes";var k="utf-8";function Je(t){if(typeof t!="object"||t===null)throw new TypeError("OctetStreamInit must be an object.");let e=t,r=e.size;if(!h(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(!h(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(!h(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 D(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var Ne=class{headers=new Headers;status=p.OK;statusText;webSocket;mediaType=D("text/plain",k);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??kt(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){l(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===p.NO_CONTENT?Oe(this.headers,ke):this.status===p.NOT_MODIFIED&&Oe(this.headers,Me)}},xe=class extends Ne{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,g.stringify(this.cache))}},f=class extends xe{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)}},G=class extends f{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},I=class extends f{constructor(e){super(),this.status=p.NOT_MODIFIED,this.headers=new Headers(e.headers)}},V=class extends f{constructor(e=null,r,s=p.OK){super(e,r),this.status=s}},J=class extends V{constructor(e={},r,s=p.OK){super(JSON.stringify(e),r,s),this.mediaType=D("application/json",k)}},Ze=class extends V{constructor(e,r,s=p.OK,o=k){super(e,r,s),this.mediaType=D("text/html",o)}},Qe=class extends V{constructor(e,r,s=p.OK,o=k){super(e,r,s),this.mediaType=D("text/plain",o)}},ye=class t extends f{constructor(e,r,s){Je(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=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===0&&e.length===e.size)}},et=class t extends ye{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=g.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}}},tt=class extends f{constructor(e){super(),this.status=p.SWITCHING_PROTOCOLS,this.webSocket=e}},L=class extends f{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},Z=class extends f{constructor(e){let r=e.getAllowedMethods();A(r),super(),this.status=p.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var u=class extends J{constructor(r,s){let o={status:r,error:Dt(r),details:s??""};super(o,g.DISABLE,r);this.details=s}},U=class extends u{constructor(e){super(C.BAD_REQUEST,e)}},rt=class extends u{constructor(e){super(C.UNAUTHORIZED,e)}},st=class extends u{constructor(e){super(C.FORBIDDEN,e)}},T=class extends u{constructor(e){super(C.NOT_FOUND,e)}},H=class extends u{constructor(e){let r=e.getAllowedMethods();A(r),super(C.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},v=class extends u{constructor(e){super(C.PRECONDITION_FAILED,e)}},Q=class extends u{constructor(){super(C.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13")}},ee=class extends u{constructor(e){super(C.INTERNAL_SERVER_ERROR,e)}},we=class extends u{constructor(e){super(C.NOT_IMPLEMENTED,e)}},b=class extends we{constructor(e){super(`${e.request.method} method not implemented.`)}},ot=class extends u{constructor(e){super(C.SERVICE_UNAVAILABLE,e)}};import{StatusCodes as Gt}from"http-status-codes";var W=class{async apply(e,r){let s=await r();if(!s||s.status!==Gt.OK)return s;let o=this.getHeader(s);if(o===void 0)return s;let i=Te(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===R)return r();if(e.request.method===B){let s=await r();return s?new L(s).response():void 0}}};var ne=class extends W{getHeader(e){return Y(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=Y(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=Y(s.ifUnmodifiedSince);return o===void 0?e:r>o?new v(`Last-Modified: ${new Date(r).toUTCString()}`).response():e}};import{StatusCodes as Vt}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!==Vt.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 de=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var O=class t extends f{_isModified=!1;constructor(e){let r=w(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(w(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=g.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,w(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 ue=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 X).use(new oe).use(new de).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(!O.isVariantResponse(o))return o;let i=O.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=Ae(i),c=await e.match(o),xt=c&&O.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let E=O.new(a);E.expireAfter(i),await e.put(o,await E.response()),await e.put(_(r,E.vary,o),i);return}if(xt){let E=O.restore(c);E.expireAfter(i),a.length>0&&(E.append(a),E.isModified&&await e.put(o,await E.response())),await e.put(_(r,E.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let K=O.new(a);K.expireAfter(c),K.expireAfter(i),await e.put(o,await K.response()),await e.put(_(r,K.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 ue(t)}function it(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&&!He(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!h(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var le="*",at=[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],ct={allowedOrigins:[le],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*Le.Minute};async function pt(t,e,r){let s=new G(t),o=ht(e.request);return ut(s.headers,r),o&&(lt(s.headers,r,o),ft(s.headers,r,o),Ut(s.headers,e),qt(s.headers,r),Kt(s.headers,r)),s.response()}async function dt(t,e,r){let s=new G(t),o=ht(e.request);return Ft(s.headers),ut(s.headers,r),o&&(lt(s.headers,r,o),ft(s.headers,r,o),Bt(s.headers,r)),s.response()}function ut(t,e){_e(e)||$(t,n.VARY,n.ORIGIN)}function lt(t,e,r){if(_e(e)){l(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,le);return}e.allowedOrigins.includes(r)&&l(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r)}function ft(t,e,r){e.allowCredentials&&(_e(e)||e.allowedOrigins.includes(r)&&l(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function Ut(t,e){let r=e.getAllowedMethods();A(r),r.length>0&&l(t,n.ACCESS_CONTROL_ALLOW_METHODS,r)}function Kt(t,e){let r=Math.max(0,Math.floor(e.maxAge));l(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function qt(t,e){e.allowedHeaders.length>0&&l(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function Bt(t,e){l(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!!(at.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={...ct,...e}}async handle(e,r){let s=await r();return e.request.method===F?pt(s,e,this.config):mt(s)?s:dt(s,e,this.config)}};function Ro(t){return it(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()===Ye)}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!==R||!this.isMatch(e.request))return r();let s=e.request.headers;return Ct(s)?Et(s)?gt(s)?r():new Q().response():new U("Missing or invalid 'Upgrade' header").response():new U("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 Yt(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function Rt(t){return S(t)?t.length>0:Yt(t)?t.byteLength>0:!1}function St(t){return h(t)?Xt(t)&&!Jt(t)?t:x.NORMAL:x.NORMAL}function Xt(t){return t>=x.NORMAL&&t<=4999}function Jt(t){return Xe.has(t)}function Ot(t){if(S(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}function At(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;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 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(!Rt(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};At(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(St(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 Tt=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)}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 bt(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 A(r),be(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()}}};var ge=class extends M{middlewares=[];init(){}use(...e){for(let r of e)bt(r);return this.middlewares.push(...e),this}async fetch(){return this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(H,this))()}};var Re=class extends ge{async fetch(){try{return await this.init(),await super.fetch()}catch(e){return console.error(e),this.response(ee)}}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(H,this)))()}async get(){return this.response(b,this)}async put(){return this.response(b,this)}async post(){return this.response(b,this)}async patch(){return this.response(b,this)}async delete(){return this.response(b,this)}async options(){return this.response(Z,this)}async head(){let e=this.create(new Request(this.request.url,{method:R,headers:this.request.headers}));return this.response(L,await e.fetch())}getAllowedMethods(){return[R,B,F]}};import{match as Zt}from"path-to-regexp";var Se=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 Re{_routes=new Se;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)}async get(){return this.response(T)}async put(){return this.response(T)}async post(){return this.response(T)}async patch(){return this.response(T)}async delete(){return this.response(T)}};export{U as BadRequest,Re as BasicWorker,g as CacheControl,G as CopyResponse,or as DELETE,st as Forbidden,R as GET,B as HEAD,L as Head,Ze as HtmlResponse,u as HttpError,ee as InternalServerError,J as JsonResponse,q as Method,H as MethodNotAllowed,b as MethodNotImplemented,T as NotFound,we as NotImplemented,I as NotModified,F as OPTIONS,ye as OctetStream,Z as Options,sr as PATCH,rr as POST,tr as PUT,v as PreconditionFailed,et as R2ObjectStream,Nt as RouteWorker,ot as ServiceUnavailable,m as StatusCodes,V as SuccessResponse,Qe as TextResponse,Le as Time,rt as Unauthorized,Q as UpgradeRequired,Tt as WebSocketSessions,tt as WebSocketUpgrade,f as WorkerResponse,Zs 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 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}async 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};async 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()}async 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};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|