@adonix.org/cloud-spark 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -13
- package/dist/cache.d.ts +58 -0
- package/dist/cache.js +2 -2
- package/dist/cache.js.map +1 -1
- package/dist/cors.d.ts +106 -0
- package/dist/cors.js +1 -1
- package/dist/cors.js.map +1 -1
- package/dist/index.d.ts +11 -504
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware-CfKw8AlN.d.ts +106 -0
- package/dist/sessions.d.ts +207 -0
- package/dist/websocket.d.ts +29 -0
- package/dist/websocket.js +1 -1
- package/dist/websocket.js.map +1 -1
- package/package.json +10 -10
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { StatusCodes } from 'http-status-codes/build/es/status-codes';
|
|
2
2
|
export { StatusCodes } from 'http-status-codes/build/es/status-codes';
|
|
3
3
|
import CacheLib from 'cache-control-parser';
|
|
4
|
+
import { W as WorkerClass, M as Method, a as Worker, b as Middleware } from './middleware-CfKw8AlN.js';
|
|
5
|
+
export { D as DELETE, G as GET, H as HEAD, O as OPTIONS, d as PATCH, c as POST, P as PUT } from './middleware-CfKw8AlN.js';
|
|
4
6
|
import { MatchFunction } from 'path-to-regexp';
|
|
5
7
|
|
|
6
8
|
/**
|
|
@@ -19,32 +21,6 @@ declare const CacheControl: {
|
|
|
19
21
|
}>;
|
|
20
22
|
};
|
|
21
23
|
|
|
22
|
-
/**
|
|
23
|
-
* Standard HTTP request methods.
|
|
24
|
-
*/
|
|
25
|
-
declare enum Method {
|
|
26
|
-
GET = "GET",
|
|
27
|
-
PUT = "PUT",
|
|
28
|
-
HEAD = "HEAD",
|
|
29
|
-
POST = "POST",
|
|
30
|
-
PATCH = "PATCH",
|
|
31
|
-
DELETE = "DELETE",
|
|
32
|
-
OPTIONS = "OPTIONS"
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Shorthand constants for each HTTP method.
|
|
36
|
-
*
|
|
37
|
-
* These are equivalent to the corresponding enum members in `Method`.
|
|
38
|
-
* For example, `GET === Method.GET`.
|
|
39
|
-
*/
|
|
40
|
-
declare const GET: Method;
|
|
41
|
-
declare const PUT: Method;
|
|
42
|
-
declare const HEAD: Method;
|
|
43
|
-
declare const POST: Method;
|
|
44
|
-
declare const PATCH: Method;
|
|
45
|
-
declare const DELETE: Method;
|
|
46
|
-
declare const OPTIONS: Method;
|
|
47
|
-
|
|
48
24
|
/**
|
|
49
25
|
* Time constants in seconds. Month is approximated as 30 days.
|
|
50
26
|
*/
|
|
@@ -58,113 +34,6 @@ declare const Time: {
|
|
|
58
34
|
readonly Year: 31536000;
|
|
59
35
|
};
|
|
60
36
|
|
|
61
|
-
/**
|
|
62
|
-
* Configuration options for the cache middleware.
|
|
63
|
-
*/
|
|
64
|
-
interface CacheInit {
|
|
65
|
-
/**
|
|
66
|
-
* Name of the cache storage to use.
|
|
67
|
-
* If omitted, the default cache is used.
|
|
68
|
-
*/
|
|
69
|
-
name?: string;
|
|
70
|
-
/**
|
|
71
|
-
* Function that maps the incoming request
|
|
72
|
-
* to a cache key.
|
|
73
|
-
*/
|
|
74
|
-
getKey: (request: Request) => URL;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* User-supplied options for configuring `CORS` behavior.
|
|
79
|
-
*
|
|
80
|
-
* This is a partial form of {@link CorsConfig}, meaning you only need
|
|
81
|
-
* to provide the options you want to override. Any missing values will
|
|
82
|
-
* fall back to the {@link defaultCorsConfig}.
|
|
83
|
-
*
|
|
84
|
-
* Example:
|
|
85
|
-
* ```ts
|
|
86
|
-
* const cors: CorsInit = {
|
|
87
|
-
* allowedOrigins: ["https://example.com"],
|
|
88
|
-
* allowCredentials: true,
|
|
89
|
-
* };
|
|
90
|
-
* ```
|
|
91
|
-
*/
|
|
92
|
-
type CorsInit = Partial<CorsConfig>;
|
|
93
|
-
/**
|
|
94
|
-
* Configuration options for Cross-Origin Resource Sharing `CORS`.
|
|
95
|
-
*
|
|
96
|
-
* Implementations of `CORS` middleware use this interface to determine
|
|
97
|
-
* how cross-origin requests are validated and which headers are sent
|
|
98
|
-
* in the response.
|
|
99
|
-
*
|
|
100
|
-
* @default
|
|
101
|
-
* ```ts
|
|
102
|
-
* {
|
|
103
|
-
* allowedOrigins: ["*"],
|
|
104
|
-
* allowedHeaders: ["Content-Type"],
|
|
105
|
-
* exposedHeaders: [],
|
|
106
|
-
* allowCredentials: false,
|
|
107
|
-
* maxAge: 300, // 5 minutes
|
|
108
|
-
* }
|
|
109
|
-
* ```
|
|
110
|
-
*/
|
|
111
|
-
interface CorsConfig {
|
|
112
|
-
/**
|
|
113
|
-
* Origins allowed for `CORS` requests.
|
|
114
|
-
*
|
|
115
|
-
* Use `["*"]` to allow all origins, or provide a list of specific origins.
|
|
116
|
-
* Example: `["https://example.com", "https://api.example.com"]`
|
|
117
|
-
*
|
|
118
|
-
* @default ["*"]
|
|
119
|
-
*/
|
|
120
|
-
allowedOrigins: string[];
|
|
121
|
-
/**
|
|
122
|
-
* HTTP headers allowed in `CORS` requests.
|
|
123
|
-
*
|
|
124
|
-
* Browsers always allow `CORS`-safelisted request headers* without preflight:
|
|
125
|
-
* - `Accept`
|
|
126
|
-
* - `Accept-Language`
|
|
127
|
-
* - `Content-Language`
|
|
128
|
-
* - `Content-Type` (but only if its value is `application/x-www-form-urlencoded`,
|
|
129
|
-
* `multipart/form-data`, or `text/plain`)
|
|
130
|
-
*
|
|
131
|
-
* Because `Content-Type` is only partially safelisted, it is included in the
|
|
132
|
-
* default allowed headers.
|
|
133
|
-
*
|
|
134
|
-
* Add custom headers here (e.g., `Authorization`) if your clients send them.
|
|
135
|
-
*
|
|
136
|
-
* @default ["Content-Type"]
|
|
137
|
-
*/
|
|
138
|
-
allowedHeaders: string[];
|
|
139
|
-
/**
|
|
140
|
-
* HTTP headers exposed to the client.
|
|
141
|
-
*
|
|
142
|
-
* By default, most headers are not accessible from client-side JavaScript.
|
|
143
|
-
* Use this option to explicitly allow certain response headers to be read.
|
|
144
|
-
*
|
|
145
|
-
* @default []
|
|
146
|
-
*/
|
|
147
|
-
exposedHeaders: string[];
|
|
148
|
-
/**
|
|
149
|
-
* Whether the resource supports user credentials (cookies, HTTP authentication).
|
|
150
|
-
*
|
|
151
|
-
* If true, the Access-Control-Allow-Origin response header must not be "*".
|
|
152
|
-
*
|
|
153
|
-
* @default false
|
|
154
|
-
*/
|
|
155
|
-
allowCredentials: boolean;
|
|
156
|
-
/**
|
|
157
|
-
* Maximum age (in seconds) that the results of a preflight request
|
|
158
|
-
* can be cached by the client.
|
|
159
|
-
*
|
|
160
|
-
* Increase for production use to reduce preflights, or lower for development
|
|
161
|
-
* if you frequently adjust `CORS` rules.
|
|
162
|
-
*
|
|
163
|
-
* @default 300 (5 minutes)
|
|
164
|
-
*/
|
|
165
|
-
maxAge: number;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
37
|
/**
|
|
169
38
|
* Structure for JSON-formatted error responses.
|
|
170
39
|
*
|
|
@@ -196,82 +65,18 @@ interface ErrorJson {
|
|
|
196
65
|
}
|
|
197
66
|
|
|
198
67
|
/**
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
* @template T - The specific type of Worker being constructed. Defaults to `Worker`.
|
|
202
|
-
* @param req - The `Request` object to be handled by the worker instance.
|
|
203
|
-
* @param env - The environment bindings available to the worker.
|
|
204
|
-
* @param ctx - The `ExecutionContext` for the worker invocation.
|
|
205
|
-
* @returns An instance of the worker type `T`.
|
|
206
|
-
*/
|
|
207
|
-
type WorkerClass<T extends Worker = Worker> = new (request: Request, env: Env, ctx: ExecutionContext) => T;
|
|
208
|
-
/**
|
|
209
|
-
* Defines the contract for a Cloudflare-compatible Worker.
|
|
210
|
-
*
|
|
211
|
-
* Implementations are responsible for handling incoming requests,
|
|
212
|
-
* providing access to the request, environment bindings, and
|
|
213
|
-
* execution context.
|
|
214
|
-
*/
|
|
215
|
-
interface Worker {
|
|
216
|
-
/**
|
|
217
|
-
* Processes the incoming {@link Request} and produces a {@link Response}.
|
|
218
|
-
*
|
|
219
|
-
* @returns A Promise that resolves to the HTTP {@link Response}.
|
|
220
|
-
*/
|
|
221
|
-
fetch(): Promise<Response>;
|
|
222
|
-
/**
|
|
223
|
-
* The original {@link Request} being processed by this worker instance.
|
|
224
|
-
*/
|
|
225
|
-
get request(): Request;
|
|
226
|
-
/**
|
|
227
|
-
* The environment bindings provided at runtime (e.g., KV, R2, secrets).
|
|
228
|
-
*/
|
|
229
|
-
get env(): Env;
|
|
230
|
-
/**
|
|
231
|
-
* The {@link ExecutionContext} associated with the current request,
|
|
232
|
-
* used to manage background tasks and request lifecycle.
|
|
233
|
-
*/
|
|
234
|
-
get ctx(): ExecutionContext;
|
|
235
|
-
/**
|
|
236
|
-
* Returns the list of HTTP methods that are allowed for this worker.
|
|
237
|
-
*
|
|
238
|
-
* @returns An array of allowed HTTP methods.
|
|
239
|
-
*/
|
|
240
|
-
getAllowedMethods(): Method[];
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Middleware interface for request/response processing.
|
|
245
|
-
*
|
|
246
|
-
* Middleware objects implement logic that can process requests and responses
|
|
247
|
-
* in a chainable manner. Each middleware receives a `Worker` object and a
|
|
248
|
-
* `next` function that invokes the next middleware in the chain.
|
|
249
|
-
*
|
|
250
|
-
* Implementers **must provide** the `handle` method.
|
|
251
|
-
*
|
|
252
|
-
* Example implementation:
|
|
253
|
-
* ```ts
|
|
254
|
-
* class LoggingMiddleware implements Middleware {
|
|
255
|
-
* public async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {
|
|
256
|
-
* console.log(`Processing request: ${worker.request.url}`);
|
|
257
|
-
* const response = await next();
|
|
258
|
-
* console.log(`Response status: ${response.status}`);
|
|
259
|
-
* return response;
|
|
260
|
-
* }
|
|
261
|
-
* }
|
|
262
|
-
* ```
|
|
68
|
+
* A type-safe Cloudflare Worker handler with a guaranteed `fetch` method.
|
|
263
69
|
*/
|
|
264
|
-
interface
|
|
70
|
+
interface FetchHandler {
|
|
265
71
|
/**
|
|
266
|
-
*
|
|
72
|
+
* Handles an incoming request and produces a response.
|
|
267
73
|
*
|
|
268
|
-
* @param
|
|
269
|
-
* @param
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
* @returns A `Response` object, either returned directly or from `next()`.
|
|
74
|
+
* @param request - The incoming `Request` object.
|
|
75
|
+
* @param env - User-provided environment bindings.
|
|
76
|
+
* @param ctx - Execution context for background tasks (`waitUntil`).
|
|
77
|
+
* @returns A `Promise` that resolves to a `Response`.
|
|
273
78
|
*/
|
|
274
|
-
|
|
79
|
+
fetch: (request: Request, env: Env, ctx: ExecutionContext) => Promise<Response>;
|
|
275
80
|
}
|
|
276
81
|
|
|
277
82
|
/**
|
|
@@ -362,304 +167,6 @@ type RouteTuple = [Method, string, RouteHandler];
|
|
|
362
167
|
*/
|
|
363
168
|
type RouteTable = Iterable<RouteTuple>;
|
|
364
169
|
|
|
365
|
-
/**
|
|
366
|
-
* Creates a Vary-aware caching middleware for Workers.
|
|
367
|
-
*
|
|
368
|
-
* This middleware:
|
|
369
|
-
* - Caches `GET` requests **only**.
|
|
370
|
-
* - Respects the `Vary` header of responses, ensuring that requests
|
|
371
|
-
* with different headers (e.g., `Accept-Language`) receive the correct cached response.
|
|
372
|
-
* - Skips caching for non-cacheable responses (e.g., error responses or
|
|
373
|
-
* responses with `Vary: *`).
|
|
374
|
-
*
|
|
375
|
-
* @param init Optional cache configuration object.
|
|
376
|
-
* @param init.name Optional name of the cache to use. If omitted, the default cache is used.
|
|
377
|
-
* @param init.getKey Optional function to compute a custom cache key from a request.
|
|
378
|
-
*
|
|
379
|
-
* @returns A {@link Middleware} instance that can be used in your middleware chain.
|
|
380
|
-
*/
|
|
381
|
-
declare function cache(init?: Partial<CacheInit>): Middleware;
|
|
382
|
-
|
|
383
|
-
/**
|
|
384
|
-
* Returns a new URL with its query parameters sorted into a stable order.
|
|
385
|
-
*
|
|
386
|
-
* This is used for cache key generation: URLs that differ only in the
|
|
387
|
-
* order of their query parameters will normalize to the same key.
|
|
388
|
-
*
|
|
389
|
-
* @param request - The incoming Request whose URL will be normalized.
|
|
390
|
-
* @returns A new URL with query parameters sorted by name.
|
|
391
|
-
*/
|
|
392
|
-
declare function sortSearchParams(request: Request): URL;
|
|
393
|
-
/**
|
|
394
|
-
* Returns a new URL with all query parameters removed.
|
|
395
|
-
*
|
|
396
|
-
* This is used when query parameters are not relevant to cache lookups,
|
|
397
|
-
* ensuring that variants of the same resource share a single cache entry.
|
|
398
|
-
*
|
|
399
|
-
* @param request - The incoming Request whose URL will be normalized.
|
|
400
|
-
* @returns A new URL with no query parameters.
|
|
401
|
-
*/
|
|
402
|
-
declare function stripSearchParams(request: Request): URL;
|
|
403
|
-
|
|
404
|
-
/**
|
|
405
|
-
* Returns a `CORS` middleware instance.
|
|
406
|
-
*
|
|
407
|
-
* This middleware automatically handles Cross-Origin Resource Sharing (CORS)
|
|
408
|
-
* for incoming requests, including preflight `OPTIONS` requests, and adds
|
|
409
|
-
* appropriate headers to responses.
|
|
410
|
-
*
|
|
411
|
-
* @param init - Optional configuration for `CORS` behavior. See {@link CorsConfig}.
|
|
412
|
-
* @returns A {@link Middleware} instance that can be used in your middleware chain.
|
|
413
|
-
*/
|
|
414
|
-
declare function cors(init?: CorsInit): Middleware;
|
|
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-regexp` style patterns
|
|
423
|
-
* (e.g., `/chat/:name`).
|
|
424
|
-
* - Contains required WebSocket headers:
|
|
425
|
-
* - `Connection: Upgrade`
|
|
426
|
-
* - `Upgrade: websocket`
|
|
427
|
-
* - `Sec-WebSocket-Version: 13`
|
|
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-regexp` 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
|
-
*/
|
|
440
|
-
declare function websocket(path?: string): Middleware;
|
|
441
|
-
|
|
442
|
-
/**
|
|
443
|
-
* Represents a warning event emitted by a WebSocket.
|
|
444
|
-
*/
|
|
445
|
-
type WarnEvent = {
|
|
446
|
-
type: "warn";
|
|
447
|
-
message: string;
|
|
448
|
-
};
|
|
449
|
-
/**
|
|
450
|
-
* Map of custom WebSocket events.
|
|
451
|
-
* - `warn`: internal warning notifications
|
|
452
|
-
* - `open`: triggered when the WebSocket is accepted
|
|
453
|
-
*/
|
|
454
|
-
type CustomEventMap = {
|
|
455
|
-
warn: WarnEvent;
|
|
456
|
-
open: Event;
|
|
457
|
-
};
|
|
458
|
-
/** Options for registering WebSocket event listeners. */
|
|
459
|
-
type EventOptions = {
|
|
460
|
-
once?: boolean;
|
|
461
|
-
};
|
|
462
|
-
/** Map of all events, combining native WebSocket events and custom events. */
|
|
463
|
-
type ExtendedEventMap = WebSocketEventMap & CustomEventMap;
|
|
464
|
-
/** Names of all events, including standard and custom WebSocket events. */
|
|
465
|
-
type ExtendedEventType = keyof ExtendedEventMap;
|
|
466
|
-
/** Event listener type for an extended WebSocket event. */
|
|
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
|
-
*/
|
|
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
|
-
*/
|
|
477
|
-
interface WebSocketConnection<A extends WSAttachment> {
|
|
478
|
-
/**
|
|
479
|
-
* Current readyState of the WebSocket (0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED).
|
|
480
|
-
*/
|
|
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
|
-
*/
|
|
488
|
-
isState(...states: number[]): boolean;
|
|
489
|
-
/**
|
|
490
|
-
* Accepts the WebSocket connection if not already accepted.
|
|
491
|
-
*
|
|
492
|
-
* @returns The readonly native WebSocket instance.
|
|
493
|
-
*/
|
|
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
|
-
*/
|
|
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
|
-
*/
|
|
512
|
-
get attachment(): Readonly<A>;
|
|
513
|
-
/**
|
|
514
|
-
* Attaches or updates a user-defined object on this connection.
|
|
515
|
-
*
|
|
516
|
-
* Passing a partial object merges the new properties into the existing
|
|
517
|
-
* attachment, leaving other fields unchanged. Pass `null` to clear
|
|
518
|
-
* the attachment entirely.
|
|
519
|
-
*
|
|
520
|
-
* @param attachment - Partial object containing metadata to attach or update,
|
|
521
|
-
* or `null` to clear the attachment.
|
|
522
|
-
*/
|
|
523
|
-
attach(attachment?: Partial<A> | null): void;
|
|
524
|
-
/**
|
|
525
|
-
* Sends a message to the connected WebSocket client.
|
|
526
|
-
*
|
|
527
|
-
* @param message - Message to send, either string or binary data.
|
|
528
|
-
*/
|
|
529
|
-
send(message: string | ArrayBuffer): void;
|
|
530
|
-
/**
|
|
531
|
-
* Closes the WebSocket connection with an optional code and reason.
|
|
532
|
-
*
|
|
533
|
-
* @param code - Close code (default is `1000` NORMAL).
|
|
534
|
-
* @param reason - Optional reason string (sanitized to valid characters).
|
|
535
|
-
*/
|
|
536
|
-
close(code?: number, reason?: string): void;
|
|
537
|
-
/**
|
|
538
|
-
* Registers an event listener for a WebSocket event.
|
|
539
|
-
*
|
|
540
|
-
* Supports both standard WebSocket events (`message`, `close`, etc.)
|
|
541
|
-
* and custom events (`open`, `warn`).
|
|
542
|
-
*
|
|
543
|
-
* @param type - Event type to listen for.
|
|
544
|
-
* @param listener - Callback invoked when the event occurs.
|
|
545
|
-
* @param options - Optional event listener options (`once`).
|
|
546
|
-
*/
|
|
547
|
-
addEventListener<K extends ExtendedEventType>(type: K, listener: ExtendedEventListener<K>, options?: EventOptions): void;
|
|
548
|
-
/**
|
|
549
|
-
* Removes a previously registered WebSocket event listener.
|
|
550
|
-
*
|
|
551
|
-
* Works for both standard and custom events.
|
|
552
|
-
*
|
|
553
|
-
* @param type - Event type to remove.
|
|
554
|
-
* @param listener - Listener function to remove.
|
|
555
|
-
*/
|
|
556
|
-
removeEventListener<K extends ExtendedEventType>(type: K, listener: ExtendedEventListener<K>): void;
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
/**
|
|
560
|
-
* Manages active WebSocket connections in a Cloudflare Workers environment.
|
|
561
|
-
*
|
|
562
|
-
* Provides a simple interface for creating, restoring, and managing
|
|
563
|
-
* WebSocket connections with optional attachments. Users can:
|
|
564
|
-
*
|
|
565
|
-
* - Create new WebSocket connections (`create`) and attach arbitrary data.
|
|
566
|
-
* - Accept connections using the standard WebSocket API (`accept`).
|
|
567
|
-
* - Accept connections using the hibernatable WebSocket API (`acceptWebSocket`),
|
|
568
|
-
* which allows the connection to be put to sleep when inactive.
|
|
569
|
-
* - Restore existing WebSockets into a managed session (`restore`, `restoreAll`),
|
|
570
|
-
* maintaining their hibernation state.
|
|
571
|
-
* - Iterate over active connections or retrieve a connection by its WebSocket instance.
|
|
572
|
-
* - Close a connection cleanly with optional code and reason (`close`).
|
|
573
|
-
*
|
|
574
|
-
* @template A - Type of attachment data stored on each WebSocket connection.
|
|
575
|
-
*/
|
|
576
|
-
declare class WebSocketSessions<A extends WSAttachment = WSAttachment> {
|
|
577
|
-
/** @internal Map of active WebSocket to their connection wrapper. */
|
|
578
|
-
private readonly map;
|
|
579
|
-
/**
|
|
580
|
-
* Create a new WebSocket connection and optionally attach user data.
|
|
581
|
-
*
|
|
582
|
-
* @param attachment - Partial attachment object to initialize the connection with.
|
|
583
|
-
* @returns A `WebSocketConnection` instance ready for accepting and sending messages.
|
|
584
|
-
*/
|
|
585
|
-
create(attachment?: Partial<A>): WebSocketConnection<A>;
|
|
586
|
-
/**
|
|
587
|
-
* Wraps an existing WebSocket in a managed connection session.
|
|
588
|
-
*
|
|
589
|
-
* @param ws - An existing WebSocket to restore.
|
|
590
|
-
* @returns A `WebSocketConnection` representing the restored session.
|
|
591
|
-
*/
|
|
592
|
-
restore(ws: WebSocket): WebSocketConnection<A>;
|
|
593
|
-
/**
|
|
594
|
-
* Restores multiple WebSockets into managed sessions at once.
|
|
595
|
-
*
|
|
596
|
-
* @param all - Array of WebSocket instances to restore.
|
|
597
|
-
* @returns Array of `WebSocketConnections` restored.
|
|
598
|
-
*/
|
|
599
|
-
restoreAll(all: WebSocket[]): ReadonlyArray<WebSocketConnection<A>>;
|
|
600
|
-
/**
|
|
601
|
-
* Retrieves the managed connection for a specific WebSocket, if any.
|
|
602
|
-
*
|
|
603
|
-
* @param ws - WebSocket instance.
|
|
604
|
-
* @returns Corresponding `WebSocketConnection` or `undefined` if not managed.
|
|
605
|
-
*/
|
|
606
|
-
get(ws: WebSocket): WebSocketConnection<A> | undefined;
|
|
607
|
-
/**
|
|
608
|
-
* Selects the managed `WebSocketConnection` objects corresponding to the given WebSockets.
|
|
609
|
-
*
|
|
610
|
-
* @param sockets - Array of WebSocket instances to resolve.
|
|
611
|
-
* @returns Array of corresponding `WebSocketConnection` objects.
|
|
612
|
-
*/
|
|
613
|
-
select(sockets: WebSocket[]): WebSocketConnection<A>[];
|
|
614
|
-
/**
|
|
615
|
-
* Returns an iterator over all active `WebSocketConnection` objects
|
|
616
|
-
* managed by this session.
|
|
617
|
-
*
|
|
618
|
-
* Useful for iterating over all connections to perform actions such as
|
|
619
|
-
* broadcasting messages.
|
|
620
|
-
*
|
|
621
|
-
* @returns Iterable iterator of all active `WebSocketConnection` objects.
|
|
622
|
-
*/
|
|
623
|
-
values(): IterableIterator<WebSocketConnection<A>>;
|
|
624
|
-
/**
|
|
625
|
-
* Returns an iterator over all active raw `WebSocket` instances
|
|
626
|
-
* currently tracked by this session.
|
|
627
|
-
*
|
|
628
|
-
* @returns Iterable iterator of all active `WebSocket` instances.
|
|
629
|
-
*/
|
|
630
|
-
keys(): IterableIterator<WebSocket>;
|
|
631
|
-
/**
|
|
632
|
-
* Closes a managed WebSocket connection with optional code and reason.
|
|
633
|
-
*
|
|
634
|
-
* @param ws - WebSocket to close.
|
|
635
|
-
* @param code - Optional WebSocket close code.
|
|
636
|
-
* @param reason - Optional reason string.
|
|
637
|
-
* @returns `true` if the connection was managed and removed, `false` otherwise.
|
|
638
|
-
*/
|
|
639
|
-
close(ws: WebSocket, code?: number, reason?: string): boolean;
|
|
640
|
-
/** Iterates over all active WebSocket connections. */
|
|
641
|
-
[Symbol.iterator](): IterableIterator<WebSocketConnection<A>>;
|
|
642
|
-
/** Registers a connection internally. */
|
|
643
|
-
private register;
|
|
644
|
-
/** Un-registers a connection internally. */
|
|
645
|
-
private unregister;
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
/**
|
|
649
|
-
* A type-safe Cloudflare Worker handler with a guaranteed `fetch` method.
|
|
650
|
-
*/
|
|
651
|
-
interface FetchHandler {
|
|
652
|
-
/**
|
|
653
|
-
* Handles an incoming request and produces a response.
|
|
654
|
-
*
|
|
655
|
-
* @param request - The incoming `Request` object.
|
|
656
|
-
* @param env - User-provided environment bindings.
|
|
657
|
-
* @param ctx - Execution context for background tasks (`waitUntil`).
|
|
658
|
-
* @returns A `Promise` that resolves to a `Response`.
|
|
659
|
-
*/
|
|
660
|
-
fetch: (request: Request, env: Env, ctx: ExecutionContext) => Promise<Response>;
|
|
661
|
-
}
|
|
662
|
-
|
|
663
170
|
/**
|
|
664
171
|
* Provides the foundational structure for handling requests,
|
|
665
172
|
* environment bindings, and the worker execution context.
|
|
@@ -1143,4 +650,4 @@ declare class ServiceUnavailable extends HttpError {
|
|
|
1143
650
|
constructor(details?: string);
|
|
1144
651
|
}
|
|
1145
652
|
|
|
1146
|
-
export { BadRequest, BasicWorker, CacheControl,
|
|
653
|
+
export { BadRequest, BasicWorker, CacheControl, CopyResponse, type ErrorJson, type FetchHandler, Forbidden, Head, HtmlResponse, HttpError, InternalServerError, JsonResponse, LoggedHttpError, type MatchedRoute, Method, MethodNotAllowed, MethodNotImplemented, Middleware, NotFound, NotImplemented, NotModified, OctetStream, type OctetStreamInit, Options, type PathParams, PreconditionFailed, R2ObjectStream, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, UpgradeRequired, WebSocketUpgrade, Worker, WorkerClass, WorkerResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {StatusCodes}from'http-status-codes/build/es/status-codes';export{StatusCodes}from'http-status-codes/build/es/status-codes';import q from'cache-control-parser';import {getReasonPhrase}from'http-status-codes/build/es/utils-functions';import {match}from'path-to-regexp';var O={parse:q.parse,stringify:q.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var A=(u=>(u.GET="GET",u.PUT="PUT",u.HEAD="HEAD",u.POST="POST",u.PATCH="PATCH",u.DELETE="DELETE",u.OPTIONS="OPTIONS",u))(A||{}),{GET:l,PUT:Tt,HEAD:f,POST:Ct,PATCH:Ot,DELETE:Nt,OPTIONS:U}=A;var xt={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var n={ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",CACHE_CONTROL:"cache-control",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",ETAG:"etag",SEC_WEBSOCKET_VERSION:"sec-websocket-version"},B=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],$=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function z(r){return typeof r=="string"}function S(r){return typeof r=="number"&&!Number.isNaN(r)}var pt=new Set(Object.values(A));function D(r){return z(r)&&pt.has(r)}function ut(r){return Array.isArray(r)&&r.every(D)}function E(r){if(!ut(r)){let t=Array.isArray(r)?JSON.stringify(r):String(r);throw new TypeError(`Invalid method array: ${t}`)}}var N="utf-8";function J(r){if(typeof r!="object"||r===null)throw new TypeError("OctetStreamInit must be an object.");let t=r,e=t.size;if(!S(e)||e<0||!Number.isInteger(e))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(e)}).`);let s=t.offset??0;if(!S(s)||s<0||s>e||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(e)}, offset=${JSON.stringify(s)}).`);let o=t.length??e-s;if(!S(o)||o<0||s+o>e||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(e)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function L(r,t){return r<t?-1:r>t?1:0}function M(r,t,e){let s=Array.isArray(e)?e:[e],o=Array.from(new Set(s.map(c=>c.trim()))).filter(c=>c.length).sort(L);if(!o.length){r.delete(t);return}r.set(t,o.join(", "));}function j(r,t,e){let s=Array.isArray(e)?e:[e];if(s.length===0)return;let c=dt(r,t).concat(s.map(R=>R.trim()));M(r,t,c);}function dt(r,t){let e=r.get(t)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(e)).sort(L)}function v(r,t){for(let e of t)r.delete(e);}function g(r,t){return !t||r.toLowerCase().includes("charset=")?r:`${r}; charset=${t.toLowerCase()}`}var k=class{headers=new Headers;status=StatusCodes.OK;statusText;webSocket;mediaType=g("text/plain",N);get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??getReasonPhrase(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(t,e){M(this.headers,t,e);}mergeHeader(t,e){j(this.headers,t,e);}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===StatusCodes.NO_CONTENT?v(this.headers,$):this.status===StatusCodes.NOT_MODIFIED&&v(this.headers,B);}},G=class extends k{constructor(e){super();this.cache=e;}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,O.stringify(this.cache));}},d=class extends G{constructor(e=null,s){super(s);this.body=e;}async response(){this.addCacheHeader();let e=[StatusCodes.NO_CONTENT,StatusCodes.NOT_MODIFIED].includes(this.status)?null:this.body;return e&&this.addContentType(),this.filterHeaders(),new Response(e,this.responseInit)}},K=class extends d{constructor(t,e){super(t.body,e),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}},V=class extends d{constructor(t){super(),this.status=StatusCodes.NOT_MODIFIED,this.headers=new Headers(t.headers);}},x=class extends d{constructor(t=null,e,s=StatusCodes.OK){super(t,e),this.status=s;}},_=class extends x{constructor(t={},e,s=StatusCodes.OK){super(JSON.stringify(t),e,s),this.mediaType=g("application/json",N);}},Y=class extends x{constructor(t,e,s=StatusCodes.OK,o=N){super(t,e,s),this.mediaType=g("text/html",o);}},X=class extends x{constructor(t,e,s=StatusCodes.OK,o=N){super(t,e,s),this.mediaType=g("text/plain",o);}},W=class r extends d{constructor(t,e,s){J(e),super(t,s),this.mediaType="application/octet-stream";let o=r.normalizeInit(e),{size:c,offset:R,length:u}=o;r.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${R}-${R+u-1}/${c}`),this.status=StatusCodes.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${u}`);}static normalizeInit(t){let{size:e}=t,s=t.offset??0,o=t.length??e-s;return s===0&&o===0&&e>0&&(o=1),{size:e,offset:s,length:o}}static isPartial(t){return t.size===0?false:!(t.offset===0&&t.length===t.size)}},Q=class r extends W{constructor(t,e){let s=e;!s&&t.httpMetadata?.cacheControl&&(s=O.parse(t.httpMetadata.cacheControl)),super(t.body,r.computeRange(t.size,t.range),s),this.setHeader(n.ETAG,t.httpEtag),t.httpMetadata?.contentType&&(this.mediaType=t.httpMetadata.contentType);}static computeRange(t,e){if(!e)return {size:t};if("suffix"in e){let s=Math.max(0,t-e.suffix),o=t-s;return {size:t,offset:s,length:o}}return {size:t,...e}}},Z=class extends d{constructor(t){super(),this.status=StatusCodes.SWITCHING_PROTOCOLS,this.webSocket=t;}},I=class extends d{constructor(t){super(),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}},y=class extends d{constructor(t){let e=Array.from(new Set([l,f,...t.getAllowedMethods()]));E(e),super(),this.status=StatusCodes.NO_CONTENT,this.setHeader(n.ALLOW,e);}};var a=class extends _{constructor(e,s){let o={status:e,error:getReasonPhrase(e),details:s??""};super(o,O.DISABLE,e);this.details=s;}},w=class extends a{constructor(t,e=StatusCodes.INTERNAL_SERVER_ERROR){let s=crypto.randomUUID();console.error(s,t),super(e,s);}},tt=class extends a{constructor(t){super(StatusCodes.BAD_REQUEST,t);}},et=class extends a{constructor(t){super(StatusCodes.UNAUTHORIZED,t);}},rt=class extends a{constructor(t){super(StatusCodes.FORBIDDEN,t);}},h=class extends a{constructor(t){super(StatusCodes.NOT_FOUND,t);}},T=class extends a{constructor(t){let e=t.getAllowedMethods();E(e),super(StatusCodes.METHOD_NOT_ALLOWED,`${t.request.method} method not allowed.`),this.setHeader(n.ALLOW,e);}},st=class extends a{constructor(t){super(StatusCodes.PRECONDITION_FAILED,t);}},ot=class extends a{constructor(){super(StatusCodes.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13");}},nt=class extends a{constructor(t){super(StatusCodes.INTERNAL_SERVER_ERROR,t);}},F=class extends a{constructor(t){super(StatusCodes.NOT_IMPLEMENTED,t);}},m=class extends F{constructor(t){super(`${t.request.method} method not implemented.`);}},it=class extends a{constructor(t){super(StatusCodes.SERVICE_UNAVAILABLE,t);}};function at(r){if(r===null||typeof r!="object"||typeof r.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var C=class{constructor(t,e,s){this._request=t;this._env=e;this._ctx=s;}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(t){let e=this.getAllowedMethods();return E(e),t===l||t===f?true:D(t)&&e.includes(t)}create(t){let e=this.constructor;return new e(t,this.env,this.ctx)}response(t,...e){return new t(...e).response()}static ignite(){return {fetch:(t,e,s)=>new this(t,e,s).fetch()}}};var b=class extends C{middlewares=[];init(){}use(...t){for(let e of t)at(e);return this.middlewares.push(...t),this}async fetch(){return await this.init(),this.middlewares.reduceRight((e,s)=>()=>s.handle(this,e),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(T,this))()}};var H=class extends b{async fetch(){try{return await super.fetch()}catch(t){return this.response(w,t)}}dispatch(){let t=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()}[t]??(()=>this.response(T,this)))()}get(){return this.response(h)}put(){return this.response(m,this)}post(){return this.response(m,this)}patch(){return this.response(m,this)}delete(){return this.response(m,this)}options(){return this.response(y,this)}async head(){let t=this.create(new Request(this.request.url,{method:l,headers:this.request.headers}));return this.response(I,await t.fetch())}getAllowedMethods(){return [l,f,U]}};var P=class{routes=[];add(t){for(let[e,s,o]of t){let c=match(s);this.routes.push({method:e,matcher:c,handler:o});}}match(t,e){let s=new URL(e).pathname;for(let o of this){if(o.method!==t)continue;let c=o.matcher(s);if(c)return {route:o,params:c.params}}return null}*[Symbol.iterator](){yield*this.routes;}};var ct=class r extends H{_routes=new P;route(t,e,s){return this.routes([[t,e,s]]),this}routes(t){return this._routes.add(t),this}async dispatch(){let t=this._routes.match(this.request.method,this.request.url);if(!t)return super.dispatch();let{handler:e}=t.route;return r.isWorkerClass(e)?new e(this.request,this.env,this.ctx).fetch():e.call(this,t.params)}static isWorkerClass(t){return Object.prototype.isPrototypeOf.call(C.prototype,t.prototype)}put(){return this.response(h)}post(){return this.response(h)}patch(){return this.response(h)}delete(){return this.response(h)}};export{tt as BadRequest,H as BasicWorker,O as CacheControl,K as CopyResponse,Nt as DELETE,rt as Forbidden,l as GET,f as HEAD,I as Head,Y as HtmlResponse,a as HttpError,nt as InternalServerError,_ as JsonResponse,w as LoggedHttpError,A as Method,T as MethodNotAllowed,m as MethodNotImplemented,h as NotFound,F as NotImplemented,V as NotModified,U as OPTIONS,W as OctetStream,y as Options,Ot as PATCH,Ct as POST,Tt as PUT,st as PreconditionFailed,Q as R2ObjectStream,ct as RouteWorker,it as ServiceUnavailable,x as SuccessResponse,X as TextResponse,xt as Time,et as Unauthorized,ot as UpgradeRequired,Z as WebSocketUpgrade,d as WorkerResponse};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {StatusCodes}from'http-status-codes/build/es/status-codes';export{StatusCodes}from'http-status-codes/build/es/status-codes';import F from'cache-control-parser';import {getReasonPhrase}from'http-status-codes/build/es/utils-functions';import {match}from'path-to-regexp';var C={parse:F.parse,stringify:F.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var R=(p=>(p.GET="GET",p.PUT="PUT",p.HEAD="HEAD",p.POST="POST",p.PATCH="PATCH",p.DELETE="DELETE",p.OPTIONS="OPTIONS",p))(R||{}),{GET:h,PUT:Et,HEAD:m,POST:Tt,PATCH:Ct,DELETE:Ot,OPTIONS:q}=R;var gt={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var i={ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",CACHE_CONTROL:"cache-control",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",ETAG:"etag",SEC_WEBSOCKET_VERSION:"sec-websocket-version"},U=[i.CONTENT_TYPE,i.CONTENT_LENGTH,i.CONTENT_RANGE,i.CONTENT_ENCODING,i.CONTENT_LANGUAGE,i.CONTENT_DISPOSITION,i.CONTENT_MD5],B=[i.CONTENT_LENGTH,i.CONTENT_RANGE];function $(r){return typeof r=="string"}function A(r){return typeof r=="number"&&!Number.isNaN(r)}var ct=new Set(Object.values(R));function P(r){return $(r)&&ct.has(r)}function pt(r){return Array.isArray(r)&&r.every(P)}function f(r){if(!pt(r)){let t=Array.isArray(r)?JSON.stringify(r):String(r);throw new TypeError(`Invalid method array: ${t}`)}}var O="utf-8";function z(r){if(typeof r!="object"||r===null)throw new TypeError("OctetStreamInit must be an object.");let t=r,e=t.size;if(!A(e)||e<0||!Number.isInteger(e))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(e)}).`);let s=t.offset??0;if(!A(s)||s<0||s>e||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(e)}, offset=${JSON.stringify(s)}).`);let o=t.length??e-s;if(!A(o)||o<0||s+o>e||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(e)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function D(r,t){return r<t?-1:r>t?1:0}function L(r,t,e){let s=Array.isArray(e)?e:[e],o=Array.from(new Set(s.map(c=>c.trim()))).filter(c=>c.length).sort(D);if(!o.length){r.delete(t);return}r.set(t,o.join(", "));}function J(r,t,e){let s=Array.isArray(e)?e:[e];if(s.length===0)return;let c=ut(r,t).concat(s.map(x=>x.trim()));L(r,t,c);}function ut(r,t){let e=r.get(t)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(e)).sort(D)}function M(r,t){for(let e of t)r.delete(e);}function N(r,t){return !t||r.toLowerCase().includes("charset=")?r:`${r}; charset=${t.toLowerCase()}`}var v=class{headers=new Headers;status=StatusCodes.OK;statusText;webSocket;mediaType=N("text/plain",O);get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??getReasonPhrase(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(t,e){L(this.headers,t,e);}mergeHeader(t,e){J(this.headers,t,e);}addContentType(){this.headers.get(i.CONTENT_TYPE)||this.setHeader(i.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===StatusCodes.NO_CONTENT?M(this.headers,B):this.status===StatusCodes.NOT_MODIFIED&&M(this.headers,U);}},k=class extends v{constructor(e){super();this.cache=e;}addCacheHeader(){this.cache&&this.setHeader(i.CACHE_CONTROL,C.stringify(this.cache));}},u=class extends k{constructor(e=null,s){super(s);this.body=e;}async response(){this.addCacheHeader();let e=[StatusCodes.NO_CONTENT,StatusCodes.NOT_MODIFIED].includes(this.status)?null:this.body;return e&&this.addContentType(),this.filterHeaders(),new Response(e,this.responseInit)}},j=class extends u{constructor(t,e){super(t.body,e),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}},K=class extends u{constructor(t){super(),this.status=StatusCodes.NOT_MODIFIED,this.headers=new Headers(t.headers);}},g=class extends u{constructor(t=null,e,s=StatusCodes.OK){super(t,e),this.status=s;}},S=class extends g{constructor(t={},e,s=StatusCodes.OK){super(JSON.stringify(t),e,s),this.mediaType=N("application/json",O);}},V=class extends g{constructor(t,e,s=StatusCodes.OK,o=O){super(t,e,s),this.mediaType=N("text/html",o);}},Y=class extends g{constructor(t,e,s=StatusCodes.OK,o=O){super(t,e,s),this.mediaType=N("text/plain",o);}},G=class r extends u{constructor(t,e,s){z(e),super(t,s),this.mediaType="application/octet-stream";let o=r.normalizeInit(e),{size:c,offset:x,length:p}=o;r.isPartial(o)&&(this.setHeader(i.CONTENT_RANGE,`bytes ${x}-${x+p-1}/${c}`),this.status=StatusCodes.PARTIAL_CONTENT),this.setHeader(i.ACCEPT_RANGES,"bytes"),this.setHeader(i.CONTENT_LENGTH,`${p}`);}static normalizeInit(t){let{size:e}=t,s=t.offset??0,o=t.length??e-s;return s===0&&o===0&&e>0&&(o=1),{size:e,offset:s,length:o}}static isPartial(t){return t.size===0?false:!(t.offset===0&&t.length===t.size)}},X=class r extends G{constructor(t,e){let s=e;!s&&t.httpMetadata?.cacheControl&&(s=C.parse(t.httpMetadata.cacheControl)),super(t.body,r.computeRange(t.size,t.range),s),this.setHeader(i.ETAG,t.httpEtag),t.httpMetadata?.contentType&&(this.mediaType=t.httpMetadata.contentType);}static computeRange(t,e){if(!e)return {size:t};if("suffix"in e){let s=Math.max(0,t-e.suffix),o=t-s;return {size:t,offset:s,length:o}}return {size:t,...e}}},Q=class extends u{constructor(t){super(),this.status=StatusCodes.SWITCHING_PROTOCOLS,this.webSocket=t;}},_=class extends u{constructor(t){super(),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}},I=class extends u{constructor(t){let e=Array.from(new Set([h,m,...t.getAllowedMethods()]));f(e),super(),this.status=StatusCodes.NO_CONTENT,this.setHeader(i.ALLOW,e);}};var a=class extends S{constructor(e,s){let o={status:e,error:getReasonPhrase(e),details:s??""};super(o,C.DISABLE,e);this.details=s;}},y=class extends a{constructor(t,e=StatusCodes.INTERNAL_SERVER_ERROR){let s=crypto.randomUUID();console.error(s,t),super(e,s);}},Z=class extends a{constructor(t){super(StatusCodes.BAD_REQUEST,t);}},tt=class extends a{constructor(t){super(StatusCodes.UNAUTHORIZED,t);}},et=class extends a{constructor(t){super(StatusCodes.FORBIDDEN,t);}},d=class extends a{constructor(t){super(StatusCodes.NOT_FOUND,t);}},E=class extends a{constructor(t){let e=t.getAllowedMethods();f(e),super(StatusCodes.METHOD_NOT_ALLOWED,`${t.request.method} method not allowed.`),this.setHeader(i.ALLOW,e);}},rt=class extends a{constructor(t){super(StatusCodes.PRECONDITION_FAILED,t);}},st=class extends a{constructor(){super(StatusCodes.UPGRADE_REQUIRED),this.setHeader(i.SEC_WEBSOCKET_VERSION,"13");}},ot=class extends a{constructor(t){super(StatusCodes.INTERNAL_SERVER_ERROR,t);}},W=class extends a{constructor(t){super(StatusCodes.NOT_IMPLEMENTED,t);}},l=class extends W{constructor(t){super(`${t.request.method} method not implemented.`);}},nt=class extends a{constructor(t){super(StatusCodes.SERVICE_UNAVAILABLE,t);}};function it(r){if(r===null||typeof r!="object"||typeof r.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var T=class{constructor(t,e,s){this._request=t;this._env=e;this._ctx=s;}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(t){let e=this.getAllowedMethods();return f(e),t===h||t===m?true:P(t)&&e.includes(t)}create(t){let e=this.constructor;return new e(t,this.env,this.ctx)}response(t,...e){return new t(...e).response()}static ignite(){return {fetch:(t,e,s)=>new this(t,e,s).fetch()}}};var w=class extends T{middlewares=[];init(){}use(...t){for(let e of t)it(e);return this.middlewares.push(...t),this}async fetch(){return await this.init(),this.middlewares.reduceRight((e,s)=>()=>s.handle(this,e),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(E,this))()}};var b=class extends w{async fetch(){try{return await super.fetch()}catch(t){return this.response(y,t)}}dispatch(){let t=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()}[t]??(()=>this.response(E,this)))()}get(){return this.response(d)}put(){return this.response(l,this)}post(){return this.response(l,this)}patch(){return this.response(l,this)}delete(){return this.response(l,this)}options(){return this.response(I,this)}async head(){let t=this.create(new Request(this.request.url,{method:h,headers:this.request.headers}));return this.response(_,await t.fetch())}getAllowedMethods(){return [h,m,q]}};var H=class{routes=[];add(t){for(let[e,s,o]of t){let c=match(s);this.routes.push({method:e,matcher:c,handler:o});}}match(t,e){let s=new URL(e).pathname;for(let o of this){if(o.method!==t)continue;let c=o.matcher(s);if(c)return {route:o,params:c.params}}return null}*[Symbol.iterator](){yield*this.routes;}};var at=class r extends b{_routes=new H;route(t,e,s){return this.routes([[t,e,s]]),this}routes(t){return this._routes.add(t),this}async dispatch(){let t=this._routes.match(this.request.method,this.request.url);if(!t)return super.dispatch();let{handler:e}=t.route;return r.isWorkerClass(e)?new e(this.request,this.env,this.ctx).fetch():e.call(this,t.params)}static isWorkerClass(t){return Object.prototype.isPrototypeOf.call(T.prototype,t.prototype)}put(){return this.response(d)}post(){return this.response(d)}patch(){return this.response(d)}delete(){return this.response(d)}};export{Z as BadRequest,b as BasicWorker,C as CacheControl,j as CopyResponse,Ot as DELETE,et as Forbidden,h as GET,m as HEAD,_ as Head,V as HtmlResponse,a as HttpError,ot as InternalServerError,S as JsonResponse,y as LoggedHttpError,R as Method,E as MethodNotAllowed,l as MethodNotImplemented,d as NotFound,W as NotImplemented,K as NotModified,q as OPTIONS,G as OctetStream,I as Options,Ct as PATCH,Tt as POST,Et as PUT,rt as PreconditionFailed,X as R2ObjectStream,at as RouteWorker,nt as ServiceUnavailable,g as SuccessResponse,Y as TextResponse,gt as Time,tt as Unauthorized,st as UpgradeRequired,Q as WebSocketUpgrade,u as WorkerResponse};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|