@adonix.org/cloud-spark 0.0.108 → 0.0.109

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@adonix.org/cloud-spark.svg?color=blue)](https://www.npmjs.com/package/@adonix.org/cloud-spark)
4
4
  [![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/adonix-org/cloud-spark/blob/main/LICENSE)
5
5
  [![Build](https://github.com/adonix-org/cloud-spark/actions/workflows/build.yml/badge.svg)](https://github.com/adonix-org/postrise/actions/workflows/build.yml)
6
- [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=adonix-org_cloud-spark)
7
- [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=adonix-org_cloud-spark)
8
- [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=coverage)](https://sonarcloud.io/summary/new_code?id=adonix-org_cloud-spark)
6
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=alert_status)](https://sonarcloud.io/summary/overall?id=adonix-org_cloud-spark&branch=main)
7
+ [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=security_rating)](https://sonarcloud.io/summary/overall?id=adonix-org_cloud-spark&branch=main)
8
+ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=adonix-org_cloud-spark&metric=coverage)](https://sonarcloud.io/summary/overall?id=adonix-org_cloud-spark&branch=main)
9
9
 
10
10
  Ignite your Cloudflare Workers with a type-safe library for rapid development.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
+ import CacheLib from 'cache-control-parser';
1
2
  import { StatusCodes } from 'http-status-codes';
2
3
  export { StatusCodes } from 'http-status-codes';
3
- import CacheLib from 'cache-control-parser';
4
4
  import { MatchFunction } from 'path-to-regexp';
5
5
 
6
6
  /**
@@ -223,136 +223,231 @@ interface Worker {
223
223
  getAllowedMethods(): Method[];
224
224
  }
225
225
 
226
- type CorsWorker = Worker & CorsProvider;
226
+ /**
227
+ * Default CORS configuration used by `CorsProvider`.
228
+ *
229
+ * By default, all origins are allowed, only `Content-Type` is allowed as a header,
230
+ * no headers are exposed, and preflight caching is 1 week.
231
+ *
232
+ * @see {@link CorsConfig}
233
+ */
234
+ declare const DEFAULT_CORS_CONFIG: Required<CorsConfig>;
235
+ /**
236
+ * Configuration options for `CorsProvider`.
237
+ *
238
+ * @see {@link DEFAULT_CORS_CONFIG}
239
+ */
240
+ interface CorsConfig {
241
+ /** Origins allowed for CORS requests. */
242
+ allowedOrigins?: string[];
243
+ /** Allowed HTTP headers for CORS requests. */
244
+ allowedHeaders?: string[];
245
+ /** HTTP headers exposed to the client. */
246
+ exposedHeaders?: string[];
247
+ /** Max age in seconds for CORS preflight caching. */
248
+ maxAge?: number;
249
+ }
250
+ /**
251
+ * Provides CORS settings for a worker.
252
+ *
253
+ * Combines a user-supplied `CorsConfig` with defaults. Used by
254
+ * `CorsHandler` to automatically set the appropriate headers.
255
+ */
256
+ declare class CorsProvider {
257
+ private readonly config;
258
+ /**
259
+ * Create a new `CorsProvider`.
260
+ *
261
+ * @param config - Optional configuration to override defaults.
262
+ */
263
+ constructor(config?: CorsConfig);
264
+ /** Returns the allowed origins. Default: all (`*`). */
265
+ getAllowedOrigins(): string[];
266
+ /** Returns the allowed HTTP headers. Default: `["Content-Type"]`. */
267
+ getAllowedHeaders(): string[];
268
+ /** Returns headers exposed to the client. Default: `[]`. */
269
+ getExposedHeaders(): string[];
270
+ /** Returns the max age in seconds for preflight requests. Default: 1 week. */
271
+ getMaxAge(): number;
272
+ }
273
+ /**
274
+ * Constants for common CORS headers.
275
+ */
276
+ declare namespace Cors {
277
+ const MAX_AGE = "Access-Control-Max-Age";
278
+ const ALLOW_ORIGIN = "Access-Control-Allow-Origin";
279
+ const ALLOW_HEADERS = "Access-Control-Allow-Headers";
280
+ const ALLOW_METHODS = "Access-Control-Allow-Methods";
281
+ const EXPOSE_HEADERS = "Access-Control-Expose-Headers";
282
+ const ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
283
+ const ALLOW_ALL_ORIGINS = "*";
284
+ }
285
+ /**
286
+ * Adds or updates CORS headers on a Headers object according to the provided policy.
287
+ *
288
+ * Behavior:
289
+ * - Removes any existing CORS headers to avoid stale values.
290
+ * - If the request has no origin, the function exits early.
291
+ * - If wildcard `*` is allowed, sets Access-Control-Allow-Origin to `*`.
292
+ * - If the origin is explicitly allowed, sets the correct headers including credentials.
293
+ * - Optional headers (Expose-Headers, Allow-Headers, Allow-Methods, Max-Age) are always applied.
294
+ *
295
+ * @param cors The CorsProvider instance that determines allowed origins and headers
296
+ * @param headers The Headers object to update
297
+ */
298
+ declare function addCorsHeaders(worker: Worker, cors: CorsProvider, headers: Headers): void;
299
+ /**
300
+ * Determines if a CORS policy allows any origin (`*`).
301
+ *
302
+ * @param cors - The `CorsProvider` instance to check.
303
+ * @returns `true` if the allowed origins include `"*"`, otherwise `false`.
304
+ */
305
+ declare function allowAnyOrigin(cors: CorsProvider): boolean;
306
+
307
+ /**
308
+ * Base class for building HTTP responses.
309
+ * Manages headers, status, and media type.
310
+ */
227
311
  declare abstract class BaseResponse {
312
+ readonly worker: Worker;
313
+ constructor(worker: Worker);
314
+ /** HTTP headers for the response. */
228
315
  headers: Headers;
316
+ /** HTTP status code (default 200 OK). */
229
317
  status: StatusCodes;
318
+ /** Optional status text. Defaults to standard reason phrase. */
230
319
  statusText?: string;
320
+ /** Optional media type of the response body. */
231
321
  mediaType?: MediaType;
322
+ /** Converts current state to ResponseInit for constructing a Response. */
232
323
  protected get responseInit(): ResponseInit;
324
+ /** Sets a header, overwriting any existing value. */
233
325
  setHeader(key: string, value: string | string[]): void;
326
+ /** Merges a header with existing values (does not overwrite). */
234
327
  mergeHeader(key: string, value: string | string[]): void;
328
+ /** Adds a Content-Type header based on the media type if set. */
235
329
  addContentType(): void;
236
330
  }
237
- declare abstract class CorsResponse extends BaseResponse {
238
- readonly worker: CorsWorker;
239
- constructor(worker: CorsWorker);
240
- protected addCorsHeaders(): void;
241
- protected getOrigin(): string | null;
242
- }
243
- declare abstract class CacheResponse extends CorsResponse {
331
+ /**
332
+ * Base response class that adds caching headers.
333
+ */
334
+ declare abstract class CacheResponse extends BaseResponse {
244
335
  cache?: CacheControl | undefined;
245
- constructor(worker: CorsWorker, cache?: CacheControl | undefined);
336
+ constructor(worker: Worker, cache?: CacheControl | undefined);
337
+ /** Adds Cache-Control header if caching is configured. */
246
338
  protected addCacheHeader(): void;
247
339
  }
340
+ /**
341
+ * Core worker response. Combines caching, and security headers.
342
+ */
248
343
  declare abstract class WorkerResponse extends CacheResponse {
249
344
  private readonly body;
250
- constructor(worker: CorsWorker, body?: BodyInit | null, cache?: CacheControl);
345
+ constructor(worker: Worker, body?: BodyInit | null, cache?: CacheControl);
346
+ /** Builds the Response object with body, headers, and status. */
251
347
  getResponse(): Promise<Response>;
348
+ /** Adds default security headers. */
252
349
  protected addSecurityHeaders(): void;
253
350
  }
351
+ /**
352
+ * Wraps an existing Response and clones its body, headers, and status.
353
+ */
254
354
  declare class ClonedResponse extends WorkerResponse {
255
- constructor(worker: CorsWorker, response: Response, cache?: CacheControl);
355
+ constructor(worker: Worker, response: Response, cache?: CacheControl);
256
356
  }
357
+ /**
358
+ * Represents a successful response with customizable body and status.
359
+ */
257
360
  declare class SuccessResponse extends WorkerResponse {
258
- constructor(worker: CorsWorker, body?: BodyInit | null, cache?: CacheControl, status?: StatusCodes);
361
+ constructor(worker: Worker, body?: BodyInit | null, cache?: CacheControl, status?: StatusCodes);
259
362
  }
363
+ /**
364
+ * JSON response. Automatically sets Content-Type to application/json.
365
+ */
260
366
  declare class JsonResponse extends SuccessResponse {
261
- constructor(worker: CorsWorker, json?: unknown, cache?: CacheControl, status?: StatusCodes);
262
- }
263
- declare class HtmlResponse extends SuccessResponse {
264
- constructor(worker: CorsWorker, body: string, cache?: CacheControl, status?: StatusCodes);
265
- }
266
- declare class TextResponse extends SuccessResponse {
267
- constructor(worker: CorsWorker, content: string, cache?: CacheControl, status?: StatusCodes);
367
+ constructor(worker: Worker, json?: unknown, cache?: CacheControl, status?: StatusCodes);
268
368
  }
269
369
  /**
270
- * Removes the body from a GET response.
370
+ * HTML response. Automatically sets Content-Type to text/html.
271
371
  */
272
- declare class Head extends WorkerResponse {
273
- constructor(worker: CorsWorker, get: Response);
274
- }
275
- declare class Options extends SuccessResponse {
276
- constructor(worker: CorsWorker);
372
+ declare class HtmlResponse extends SuccessResponse {
373
+ constructor(worker: Worker, body: string, cache?: CacheControl, status?: StatusCodes);
277
374
  }
278
-
279
375
  /**
280
- * Implementations will provide a specific CORS policy.
376
+ * Plain text response. Automatically sets Content-Type to text/plain.
281
377
  */
282
- interface CorsProvider {
283
- /** Returns a list of allowed origins. */
284
- getAllowedOrigins(): string[];
285
- /** Returns true if any origin is allowed (`*`). */
286
- allowAnyOrigin(): boolean;
287
- /** Returns the HTTP headers allowed by CORS. */
288
- getAllowedHeaders(): string[];
289
- /** Returns the HTTP headers that should be exposed to the browser. */
290
- getExposedHeaders(): string[];
291
- /** Returns the max age (in seconds) for CORS preflight caching. */
292
- getMaxAge(): number;
378
+ declare class TextResponse extends SuccessResponse {
379
+ constructor(worker: Worker, content: string, cache?: CacheControl, status?: StatusCodes);
293
380
  }
294
381
  /**
295
- * Constants for common CORS headers.
382
+ * Response for HEAD requests. Clones headers but has no body.
296
383
  */
297
- declare namespace Cors {
298
- const MAX_AGE = "Access-Control-Max-Age";
299
- const ALLOW_ORIGIN = "Access-Control-Allow-Origin";
300
- const ALLOW_HEADERS = "Access-Control-Allow-Headers";
301
- const ALLOW_METHODS = "Access-Control-Allow-Methods";
302
- const EXPOSE_HEADERS = "Access-Control-Expose-Headers";
303
- const ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
304
- const ALLOW_ALL_ORIGINS = "*";
384
+ declare class Head extends WorkerResponse {
385
+ constructor(worker: Worker, get: Response);
305
386
  }
306
387
  /**
307
- * Adds or updates CORS headers on a Headers object according to the provided policy.
308
- *
309
- * Behavior:
310
- * - Removes any existing CORS headers to avoid stale values.
311
- * - If the request has no origin, the function exits early.
312
- * - If wildcard `*` is allowed, sets Access-Control-Allow-Origin to `*`.
313
- * - If the origin is explicitly allowed, sets the correct headers including credentials and Vary: Origin.
314
- * - Optional headers (Expose-Headers, Allow-Headers, Allow-Methods, Max-Age) are always applied.
315
- *
316
- * @param cors The CorsProvider instance that determines allowed origins and headers
317
- * @param headers The Headers object to update
388
+ * Response for OPTIONS requests. Sets allowed methods and returns 204 No Content.
318
389
  */
319
- declare function addCorsHeaders(origin: string | null, cors: CorsWorker, headers: Headers): void;
390
+ declare class Options extends SuccessResponse {
391
+ constructor(worker: Worker);
392
+ }
320
393
 
394
+ /** Structure for JSON error responses. */
321
395
  interface ErrorJson {
396
+ /** HTTP status code. */
322
397
  status: number;
398
+ /** Standard HTTP reason phrase. */
323
399
  error: string;
400
+ /** Optional detailed message about the error. */
324
401
  details: string;
325
402
  }
403
+ /**
404
+ * Generic HTTP error response.
405
+ * Sends a JSON body with status, error message, and details.
406
+ */
326
407
  declare class HttpError extends JsonResponse {
327
408
  protected readonly details?: string | undefined;
328
- constructor(worker: CorsWorker, status: StatusCodes, details?: string | undefined);
409
+ /**
410
+ * @param worker The worker handling the request.
411
+ * @param status HTTP status code.
412
+ * @param details Optional detailed error message.
413
+ */
414
+ constructor(worker: Worker, status: StatusCodes, details?: string | undefined);
329
415
  }
416
+ /** 400 Bad Request error response. */
330
417
  declare class BadRequest extends HttpError {
331
- constructor(worker: CorsWorker, details?: string);
418
+ constructor(worker: Worker, details?: string);
332
419
  }
420
+ /** 401 Unauthorized error response. */
333
421
  declare class Unauthorized extends HttpError {
334
- constructor(worker: CorsWorker, details?: string);
422
+ constructor(worker: Worker, details?: string);
335
423
  }
424
+ /** 403 Forbidden error response. */
336
425
  declare class Forbidden extends HttpError {
337
- constructor(worker: CorsWorker, details?: string);
426
+ constructor(worker: Worker, details?: string);
338
427
  }
428
+ /** 404 Not Found error response. */
339
429
  declare class NotFound extends HttpError {
340
- constructor(worker: CorsWorker, details?: string);
430
+ constructor(worker: Worker, details?: string);
341
431
  }
432
+ /** 405 Method Not Allowed error response. */
342
433
  declare class MethodNotAllowed extends HttpError {
343
- constructor(worker: CorsWorker);
434
+ constructor(worker: Worker);
344
435
  }
436
+ /** 500 Internal Server Error response. */
345
437
  declare class InternalServerError extends HttpError {
346
- constructor(worker: CorsWorker, details?: string);
438
+ constructor(worker: Worker, details?: string);
347
439
  }
440
+ /** 501 Not Implemented error response. */
348
441
  declare class NotImplemented extends HttpError {
349
- constructor(worker: CorsWorker, details?: string);
442
+ constructor(worker: Worker, details?: string);
350
443
  }
444
+ /** 501 Method Not Implemented error response for unsupported HTTP methods. */
351
445
  declare class MethodNotImplemented extends NotImplemented {
352
- constructor(worker: CorsWorker);
446
+ constructor(worker: Worker);
353
447
  }
448
+ /** 503 Service Unavailable error response. */
354
449
  declare class ServiceUnavailable extends HttpError {
355
- constructor(worker: CorsWorker, details?: string);
450
+ constructor(worker: Worker, details?: string);
356
451
  }
357
452
 
358
453
  /** Parameters extracted from a matched route */
@@ -420,6 +515,33 @@ declare class Routes implements Iterable<Route> {
420
515
  [Symbol.iterator](): Iterator<Route>;
421
516
  }
422
517
 
518
+ /**
519
+ * Abstract base class for Worker middleware.
520
+ * Provides a structured pre/post pattern around the next middleware or final handler,
521
+ * with optional short-circuit support.
522
+ */
523
+ declare abstract class Middleware {
524
+ /**
525
+ * Implement this method to perform logic **before** the next middleware.
526
+ * Can inspect or modify the request via the worker instance.
527
+ * Return a Response to short-circuit the chain, or `undefined` to continue.
528
+ * @param worker The worker handling the request
529
+ */
530
+ protected pre(_worker: Worker): void | Response | Promise<void | Response>;
531
+ /**
532
+ * Implement this method to perform logic **after** the next middleware.
533
+ * Can inspect or modify the response before it is returned.
534
+ * @param worker The worker handling the request
535
+ * @param response The Response returned from the next middleware or final handler
536
+ */
537
+ protected post(_worker: Worker, _response: Response): void | Promise<void>;
538
+ /**
539
+ * Executes this middleware around the next middleware or final handler.
540
+ * Calls `pre`, then `next()` if not short-circuited, then `post`.
541
+ */
542
+ handle(worker: Worker, next: () => Promise<Response>): Promise<Response>;
543
+ }
544
+
423
545
  /**
424
546
  * A type-safe Cloudflare Worker handler.
425
547
  *
@@ -460,6 +582,16 @@ declare abstract class BaseWorker implements Worker {
460
582
  get env(): Env;
461
583
  /** Execution context for background tasks or `waitUntil` */
462
584
  get ctx(): ExecutionContext;
585
+ /**
586
+ * Dispatches the incoming request to the appropriate handler and produces a response.
587
+ *
588
+ * Subclasses must implement this method to define how the worker generates a `Response`
589
+ * for the current request. This is the central point where request processing occurs,
590
+ * and where middleware chains, routing, or other custom behavior can be applied.
591
+ *
592
+ * @returns A Promise that resolves to the `Response` for the request.
593
+ */
594
+ protected abstract dispatch(): Promise<Response>;
463
595
  /**
464
596
  * The DEFAULT allowed HTTP methods for subclasses.
465
597
  */
@@ -491,141 +623,115 @@ declare abstract class BaseWorker implements Worker {
491
623
  }
492
624
 
493
625
  /**
494
- * Abstract base class for Workers to provide a default CORS policy.
495
- *
496
- * Implements the `CorsProvider` interface and provides a standard policy:
497
- * - Allows all origins (`*`) by default.
498
- * - Allows the `Content-Type` header.
499
- * - Exposes no additional headers.
500
- * - Sets CORS preflight max-age to one week.
501
- *
502
- * Subclasses can override any of the methods to customize the CORS behavior.
503
- */
504
- declare abstract class CorsDefaults extends BaseWorker implements CorsProvider {
505
- getAllowedOrigins(): string[];
506
- allowAnyOrigin(): boolean;
507
- getAllowedHeaders(): string[];
508
- getExposedHeaders(): string[];
509
- getMaxAge(): number;
510
- }
511
-
512
- /**
513
- * Abstract worker class that adds caching support for GET requests.
514
- *
515
- * Behavior:
516
- * - Caches successful GET responses (`response.ok === true`) in the selected cache.
517
- * - Strips CORS headers from cached responses; all other origin headers are preserved.
518
- * - Dynamically adds CORS headers to cached responses when returned to the client.
519
- *
520
- * Subclasses should override `getCacheKey()` to customize cache key generation if needed.
626
+ * Worker that supports class-based middleware with optional always-run middleware.
627
+ * Extends CacheWorker to include caching logic automatically.
521
628
  */
522
- declare abstract class CacheWorker extends CorsDefaults {
629
+ declare abstract class MiddlewareWorker extends BaseWorker {
630
+ private readonly middlewares;
523
631
  /**
524
- * Returns the cache key for the current request.
525
- *
526
- * Behavior:
527
- * - By default, returns the normalized request URL.
528
- * - Query parameters are normalized so that the order does not affect the cache key.
529
- * For example, `?a=1&b=2` and `?b=2&a=1` produce the same cache key.
530
- *
531
- * Subclasses may override this method to implement custom cache key strategies.
532
- *
533
- * @returns {URL | RequestInfo} The URL or RequestInfo used as the cache key.
632
+ * Register a middleware instance.
633
+ * @param mw Middleware to register
534
634
  */
535
- protected getCacheKey(): URL | RequestInfo;
635
+ use(mw: Middleware): this;
536
636
  /**
537
- * Retrieves a cached Response for the current request, if one exists.
637
+ * Fetch the current request through the registered middleware chain
638
+ * and ultimately to the final worker handler.
538
639
  *
539
- * Behavior:
540
- * - Only GET requests are considered.
541
- * - Returns a new Response with dynamic CORS headers applied via `addCacheHeaders`.
542
- * - Returns `undefined` if no cached response is found.
543
- * - Cloudflare dynamic headers (`CF-Cache-Status`, `Age`, `Connection`, etc.) will
544
- * always be present on the returned response, even though they are not stored in the cache.
640
+ * Middleware are executed in **last-registered-first-called** order (via reduceRight).
641
+ * Each middleware receives the worker instance and a `next` function to call the
642
+ * next middleware or final handler.
545
643
  *
546
- * @param {string} [cacheName] Optional named cache; defaults to `caches.default`.
547
- * @returns {Promise<Response | undefined>} A Response with CORS headers, or undefined.
548
- * @see {@link setCachedResponse}
549
- * @see {@link getCacheKey}
644
+ * @returns A Promise resolving to the Response returned by the middleware chain
645
+ * or the final handler.
550
646
  */
551
- protected getCachedResponse(cacheName?: string): Promise<Response | undefined>;
552
- /**
553
- * Stores a Response in the cache for the current request.
554
- *
555
- * Behavior:
556
- * - Only caches successful GET responses (`response.ok === true`).
557
- * - Strips headers via `removeCacheHeaders` before storing.
558
- * - Uses `ctx.waitUntil` to perform caching asynchronously without blocking the response.
559
- * - All other origin headers (e.g., Cache-Control, Expires) are preserved.
560
- *
561
- * @param {Response} response The Response to cache.
562
- * @param {string} [cacheName] Optional named cache; defaults to `caches.default`.
563
- * @see {@link getCachedResponse}
564
- * @see {@link getCacheKey}
565
- */
566
- protected setCachedResponse(response: Response, cacheName?: string): Promise<void>;
647
+ fetch(): Promise<Response>;
648
+ }
649
+
650
+ /**
651
+ * Base worker class providing HTTP method dispatching, caching, and error handling.
652
+ * Extends `CacheWorker` and defines default implementations for HTTP methods.
653
+ */
654
+ declare abstract class BasicWorker extends MiddlewareWorker {
567
655
  /**
568
- * Controls whether the library's automatic caching is enabled.
569
- *
570
- * This method only affects the caching behavior provided by the library’s
571
- * `getCachedResponse()` and `setCachedResponse()` methods. It does **not**
572
- * prevent users from manually reading from or writing to `caches.default`
573
- * or any other Cache API. By default, this returns `true`, enabling the
574
- * library’s default caching behavior.
575
- *
576
- * Subclasses can override this method to disable automatic caching in
577
- * development environments, for certain pathnames, or based on
578
- * environment variables.
579
- *
580
- * @returns {boolean} `true` if the library should use its default caching,
581
- * `false` to disable the library cache.
656
+ * Entry point to handle a fetch request.
657
+ * Checks allowed methods, serves cached responses, or dispatches to the appropriate handler.
582
658
  */
583
- protected isCacheEnabled(): boolean | Promise<boolean>;
659
+ fetch(): Promise<Response>;
584
660
  /**
585
- * Adds headers to a cached response.
586
- *
587
- * @param {Response} cached The cached Response.
588
- * @returns {Response} A new Response with dynamic CORS headers applied.
589
- * @see {@link removeCacheHeaders}
661
+ * Dispatches the request to the method-specific handler.
662
+ * Defaults to MethodNotAllowed if the HTTP method is not recognized.
590
663
  */
591
- protected addCacheHeaders(cached: Response): Response;
664
+ protected dispatch(): Promise<Response>;
592
665
  /**
593
- * Removes headers that should not be stored in the cache (currently only CORS headers).
594
- *
595
- * @param {Response} response The Response to clean before caching.
596
- * @returns {Response} A new Response with excluded headers removed.
597
- * @see {@link addCacheHeaders}
666
+ * Hook for subclasses to perform any setup, e.g., registering middleware,
667
+ * overriding defaults, or configuring state.
598
668
  */
599
- protected removeCacheHeaders(response: Response): Response;
669
+ protected setup(): void;
600
670
  /**
601
- * Returns the list of headers to exclude from the cached response.
602
- * By default, excludes only dynamic CORS headers.
603
- *
604
- * @returns {string[]} Array of header names to exclude.
605
- * @see {@link removeCacheHeaders}
671
+ * Checks if the given HTTP method is allowed for this worker.
672
+ * @param method HTTP method string
673
+ * @returns true if the method is allowed
606
674
  */
607
- protected excludeCacheHeaders(): string[];
608
- }
609
-
610
- declare abstract class BasicWorker extends CacheWorker {
611
- fetch(): Promise<Response>;
612
- protected dispatch(): Promise<Response>;
613
675
  isAllowed(method: string): boolean;
676
+ /** Default handler for GET requests. Returns MethodNotImplemented unless overridden. */
614
677
  protected get(): Promise<Response>;
678
+ /** Default handler for PUT requests. Returns MethodNotImplemented unless overridden. */
615
679
  protected put(): Promise<Response>;
680
+ /** Default handler for POST requests. Returns MethodNotImplemented unless overridden. */
616
681
  protected post(): Promise<Response>;
682
+ /** Default handler for PATCH requests. Returns MethodNotImplemented unless overridden. */
617
683
  protected patch(): Promise<Response>;
684
+ /** Default handler for DELETE requests. Returns MethodNotImplemented unless overridden. */
618
685
  protected delete(): Promise<Response>;
686
+ /**
687
+ * Default handler for OPTIONS requests.
688
+ * Returns an Options response.
689
+ *
690
+ * Typically does not need to be overridden.
691
+ */
619
692
  protected options(): Promise<Response>;
693
+ /**
694
+ * Default handler for HEAD requests.
695
+ * Performs a GET request internally and removes the body for HEAD semantics.
696
+ *
697
+ * Usually does not need to be overridden, as this behavior covers standard HEAD requirements.
698
+ */
620
699
  protected head(): Promise<Response>;
621
- protected getResponse<T extends WorkerResponse, Ctor extends new (worker: CorsWorker, ...args: any[]) => T>(ResponseClass: Ctor, ...args: ConstructorParameters<Ctor> extends [CorsWorker, ...infer R] ? R : never): Promise<Response>;
700
+ /**
701
+ * Helper to construct a WorkerResponse of the given class with arguments.
702
+ * @param ResponseClass The response class to instantiate
703
+ * @param args Additional constructor arguments
704
+ * @returns The final Response object
705
+ */
706
+ protected getResponse<T extends WorkerResponse, Ctor extends new (worker: Worker, ...args: any[]) => T>(ResponseClass: Ctor, ...args: ConstructorParameters<Ctor> extends [Worker, ...infer R] ? R : never): Promise<Response>;
622
707
  }
623
708
 
709
+ /**
710
+ * Abstract worker that provides routing capabilities.
711
+ * Extends `BasicWorker` and uses a `Routes` table to map HTTP methods and paths
712
+ * to handler callbacks.
713
+ */
624
714
  declare abstract class RouteWorker extends BasicWorker {
715
+ /** Routing table used for registering and matching routes. */
625
716
  protected readonly routes: Routes;
626
- protected abstract registerRoutes(): void;
717
+ /**
718
+ * Loads routes from a `RouteTable` into this worker's route table.
719
+ * @param table The table of routes to load.
720
+ */
627
721
  protected load(table: RouteTable): void;
722
+ /**
723
+ * Adds a single route to this worker.
724
+ * @param method HTTP method (GET, POST, etc.)
725
+ * @param path Route path
726
+ * @param callback Function to handle requests matching this route
727
+ * @returns The worker instance (for chaining)
728
+ */
628
729
  protected add(method: Method, path: string, callback: RouteCallback): this;
730
+ /**
731
+ * Matches the incoming request against registered routes and executes
732
+ * the corresponding callback. Falls back to `BasicWorker.dispatch()` if no match.
733
+ * @returns The response from the matched route or the default handler.
734
+ */
629
735
  protected dispatch(): Promise<Response>;
630
736
  protected get(): Promise<Response>;
631
737
  protected put(): Promise<Response>;
@@ -634,4 +740,4 @@ declare abstract class RouteWorker extends BasicWorker {
634
740
  protected delete(): Promise<Response>;
635
741
  }
636
742
 
637
- export { BadRequest, BasicWorker, CacheControl, ClonedResponse, Cors, type CorsProvider, type CorsWorker, type ErrorJson, Forbidden, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, NotFound, NotImplemented, Options, type Route, type RouteCallback, type RouteParams, type RouteTable, type RouteTuple, RouteWorker, Routes, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, type Worker, type WorkerConstructor, WorkerResponse, addCorsHeaders, getContentType, getOrigin, isMethod, lexCompare, mergeHeader, normalizeUrl, setHeader };
743
+ export { BadRequest, BasicWorker, CacheControl, ClonedResponse, Cors, type CorsConfig, CorsProvider, DEFAULT_CORS_CONFIG, type ErrorJson, Forbidden, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, Middleware, NotFound, NotImplemented, Options, type Route, type RouteCallback, type RouteParams, type RouteTable, type RouteTuple, RouteWorker, Routes, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, type Worker, type WorkerConstructor, WorkerResponse, addCorsHeaders, allowAnyOrigin, getContentType, getOrigin, isMethod, lexCompare, mergeHeader, normalizeUrl, setHeader };