@adonix.org/cloud-spark 0.0.158 → 0.0.160

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
@@ -29,8 +29,8 @@ npm install @adonix.org/cloud-spark
29
29
  import { BasicWorker, TextResponse } from "@adonix.org/cloud-spark";
30
30
 
31
31
  export class HelloWorld extends BasicWorker {
32
- protected override async get(): Promise<Response> {
33
- return this.getResponse(TextResponse, "Hi from Cloud Spark!");
32
+ async get(): Promise<Response> {
33
+ return this.response(TextResponse, "Hi from Cloud Spark!");
34
34
  }
35
35
  }
36
36
  ```
@@ -61,6 +61,10 @@ And it's ready on http://localhost:8787
61
61
 
62
62
  <br>
63
63
 
64
+ ## :left_right_arrow: Web Sockets
65
+
66
+ <br>
67
+
64
68
  ## :gear: Middleware
65
69
 
66
70
  <br>
package/dist/index.d.ts CHANGED
@@ -47,6 +47,9 @@ declare namespace HttpHeader {
47
47
  const ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
48
48
  const ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
49
49
  const ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
50
+ const SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version";
51
+ const CONNECTION = "Connection";
52
+ const UPGRADE = "Upgrade";
50
53
  }
51
54
  /**
52
55
  * Standard HTTP request methods.
@@ -136,6 +139,34 @@ declare const Time: {
136
139
  readonly Year: 31536000;
137
140
  };
138
141
 
142
+ /** WebSocket upgrade header value */
143
+ declare const WS_UPGRADE = "upgrade";
144
+ /** WebSocket protocol header value */
145
+ declare const WS_WEBSOCKET = "websocket";
146
+ /** WebSocket protocol version */
147
+ declare const WS_VERSION = "13";
148
+ /** Max close code a user can send */
149
+ declare const WS_MAX_CLOSE_CODE = 4999;
150
+ /** Max number of reason chars a user can send */
151
+ declare const WS_MAX_REASON_CHARS = 123;
152
+ /** WebSocket close codes */
153
+ declare const CloseCode: {
154
+ readonly NORMAL: 1000;
155
+ readonly GOING_AWAY: 1001;
156
+ readonly PROTOCOL_ERROR: 1002;
157
+ readonly UNSUPPORTED_DATA: 1003;
158
+ readonly NO_STATUS: 1005;
159
+ readonly ABNORMAL: 1006;
160
+ readonly INVALID_PAYLOAD: 1007;
161
+ readonly POLICY_VIOLATION: 1008;
162
+ readonly MESSAGE_TOO_BIG: 1009;
163
+ readonly MISSING_EXTENSION: 1010;
164
+ readonly INTERNAL_ERROR: 1011;
165
+ readonly TLS_HANDSHAKE: 1015;
166
+ };
167
+ /** WebSocket RESERVED close codes */
168
+ declare const WS_RESERVED_CODES: Set<number>;
169
+
139
170
  /**
140
171
  * Type guard that checks if a string is a valid HTTP method.
141
172
  *
@@ -469,6 +500,8 @@ declare function cache(cacheName?: string, getKey?: (request: Request) => URL):
469
500
  */
470
501
  declare function cors(init?: CorsInit): Middleware;
471
502
 
503
+ declare function websocket(path?: string): Middleware;
504
+
472
505
  /**
473
506
  * Lexicographically compares two strings.
474
507
  *
@@ -564,6 +597,48 @@ declare function stripSearchParams(request: Request): URL;
564
597
  */
565
598
  declare function getContentType(type: MediaType): string;
566
599
 
600
+ type WarnEvent = {
601
+ type: "warn";
602
+ message: string;
603
+ };
604
+ type CustomEventMap = {
605
+ warn: WarnEvent;
606
+ open: Event;
607
+ };
608
+ type EventOptions = {
609
+ once?: boolean;
610
+ };
611
+ type ExtendedEventMap = WebSocketEventMap & CustomEventMap;
612
+ type ExtendedEventType = keyof ExtendedEventMap;
613
+ type ExtendedEventListener<K extends ExtendedEventType> = (ev: ExtendedEventMap[K]) => void;
614
+ type WSAttachment = object;
615
+ interface WebSocketConnection<A extends WSAttachment> {
616
+ get readyState(): number;
617
+ isState(...states: number[]): boolean;
618
+ accept(): WebSocket;
619
+ acceptWebSocket(ctx: DurableObjectState, tags?: string[]): WebSocket;
620
+ get attachment(): A;
621
+ attach(attachment: A): void;
622
+ send(message: string | ArrayBuffer): void;
623
+ close(code?: number, reason?: string): void;
624
+ addEventListener<K extends ExtendedEventType>(type: K, listener: ExtendedEventListener<K>, options?: EventOptions): void;
625
+ removeEventListener<K extends ExtendedEventType>(type: K, listener: ExtendedEventListener<K>): void;
626
+ }
627
+
628
+ declare class WebSocketSessions<A extends WSAttachment = WSAttachment> {
629
+ private readonly map;
630
+ create(attachment?: A): WebSocketConnection<A>;
631
+ restore(ws: WebSocket): WebSocketConnection<A>;
632
+ restoreAll(all: WebSocket[]): ReadonlyArray<WebSocketConnection<A>>;
633
+ get(ws: WebSocket): WebSocketConnection<A> | undefined;
634
+ values(): IterableIterator<WebSocketConnection<A>>;
635
+ keys(): IterableIterator<WebSocket>;
636
+ close(ws: WebSocket, code?: number, reason?: string): boolean;
637
+ [Symbol.iterator](): IterableIterator<WebSocketConnection<A>>;
638
+ private register;
639
+ private unregister;
640
+ }
641
+
567
642
  /**
568
643
  * A type-safe Cloudflare Worker handler with a guaranteed `fetch` method.
569
644
  *
@@ -616,6 +691,12 @@ declare abstract class BaseWorker implements Worker {
616
691
  * @returns A Promise that resolves to the `Response` for the request.
617
692
  */
618
693
  protected abstract dispatch(): Promise<Response>;
694
+ /**
695
+ * Checks if the given HTTP method is allowed for this worker.
696
+ * @param method HTTP method string
697
+ * @returns true if the method is allowed
698
+ */
699
+ isAllowed(method: string): boolean;
619
700
  abstract getAllowedMethods(): Method[];
620
701
  /**
621
702
  * Creates a new instance of the current Worker subclass.
@@ -630,6 +711,23 @@ declare abstract class BaseWorker implements Worker {
630
711
  * @returns A {@link Response} promise for the {@link Request}.
631
712
  */
632
713
  abstract fetch(): Promise<Response>;
714
+ /**
715
+ * Simplify and standardize {@link Response} creation by extending {@link WorkerResponse}
716
+ * or any of its subclasses and passing to this method.
717
+ *
718
+ * Or directly use any of the built-in classes.
719
+ *
720
+ * ```ts
721
+ * this.response(TextResponse, "Hello World!")
722
+ * ```
723
+ *
724
+ * @param ResponseClass The response class to instantiate
725
+ * @param args Additional constructor arguments
726
+ * @returns A Promise resolving to the {@link Response} object
727
+ */
728
+ protected response<Ctor extends new (...args: any[]) => {
729
+ response(): Promise<Response>;
730
+ }>(ResponseClass: Ctor, ...args: ConstructorParameters<Ctor>): Promise<Response>;
633
731
  /**
634
732
  * **Ignite** your `Worker` implementation into a Cloudflare handler.
635
733
  *
@@ -646,6 +744,10 @@ declare abstract class BaseWorker implements Worker {
646
744
  declare abstract class MiddlewareWorker extends BaseWorker {
647
745
  /** Middleware handlers registered for this worker. */
648
746
  protected readonly middlewares: Middleware[];
747
+ /**
748
+ * Hook for subclasses to perform any initialization.
749
+ */
750
+ protected init(): void | Promise<void>;
649
751
  /**
650
752
  * Add a middleware instance to this worker.
651
753
  *
@@ -676,16 +778,6 @@ declare abstract class BasicWorker extends MiddlewareWorker {
676
778
  * Dispatches the request to the method-specific handler.
677
779
  */
678
780
  protected dispatch(): Promise<Response>;
679
- /**
680
- * Hook for subclasses to perform any initialization.
681
- */
682
- protected init(): void | Promise<void>;
683
- /**
684
- * Checks if the given HTTP method is allowed for this worker.
685
- * @param method HTTP method string
686
- * @returns true if the method is allowed
687
- */
688
- isAllowed(method: string): boolean;
689
781
  /** Override and implement this method for GET requests. */
690
782
  protected get(): Promise<Response>;
691
783
  /** Override and implement this method for PUT requests. */
@@ -713,23 +805,6 @@ declare abstract class BasicWorker extends MiddlewareWorker {
713
805
  * overridden for each specific worker.
714
806
  */
715
807
  getAllowedMethods(): Method[];
716
- /**
717
- * Simplify and standardize {@link Response} creation by extending {@link WorkerResponse}
718
- * or any of its subclasses and passing to this method.
719
- *
720
- * Or directly use any of the built-in classes.
721
- *
722
- * ```ts
723
- * this.getResponse(TextResponse, "Hello World!")
724
- * ```
725
- *
726
- * @param ResponseClass The response class to instantiate
727
- * @param args Additional constructor arguments
728
- * @returns A Promise resolving to the {@link Response} object
729
- */
730
- protected getResponse<Ctor extends new (...args: any[]) => {
731
- getResponse(): Promise<Response>;
732
- }>(ResponseClass: Ctor, ...args: ConstructorParameters<Ctor>): Promise<Response>;
733
808
  }
734
809
 
735
810
  /**
@@ -808,6 +883,8 @@ declare abstract class BaseResponse {
808
883
  status: StatusCodes;
809
884
  /** Optional status text. Defaults to standard reason phrase. */
810
885
  statusText?: string;
886
+ /** Enable websocket responses. */
887
+ webSocket: WebSocket | null;
811
888
  /** Default media type of the response body. */
812
889
  mediaType: MediaType;
813
890
  /** Converts current state to ResponseInit for constructing a Response. */
@@ -834,8 +911,8 @@ declare abstract class CacheResponse extends BaseResponse {
834
911
  declare abstract class WorkerResponse extends CacheResponse {
835
912
  private readonly body;
836
913
  constructor(body?: BodyInit | null, cache?: CacheControl);
837
- /** Builds the Response object with body, headers, and status. */
838
- getResponse(): Promise<Response>;
914
+ /** Builds the Response with body, headers, and status. */
915
+ response(): Promise<Response>;
839
916
  }
840
917
  /**
841
918
  * Wraps an existing Response and clones its body, headers, and status.
@@ -867,6 +944,13 @@ declare class HtmlResponse extends SuccessResponse {
867
944
  declare class TextResponse extends SuccessResponse {
868
945
  constructor(content: string, cache?: CacheControl, status?: StatusCodes);
869
946
  }
947
+ /**
948
+ * Response for WebSocket upgrade requests.
949
+ * Automatically sets status to 101 and attaches the client socket.
950
+ */
951
+ declare class WebSocketUpgrade extends WorkerResponse {
952
+ constructor(client: WebSocket);
953
+ }
870
954
  /**
871
955
  * Response for HEAD requests. Copy headers and status from a GET response
872
956
  * without the body.
@@ -914,6 +998,10 @@ declare class NotFound extends HttpError {
914
998
  declare class MethodNotAllowed extends HttpError {
915
999
  constructor(worker: Worker);
916
1000
  }
1001
+ /** 426 Upgrade Required error response. */
1002
+ declare class UpgradeRequired extends HttpError {
1003
+ constructor();
1004
+ }
917
1005
  /** 500 Internal Server Error response. */
918
1006
  declare class InternalServerError extends HttpError {
919
1007
  constructor(details?: string);
@@ -931,4 +1019,4 @@ declare class ServiceUnavailable extends HttpError {
931
1019
  constructor(details?: string);
932
1020
  }
933
1021
 
934
- export { BadRequest, BasicWorker, CacheControl, ClonedResponse, type CorsConfig, type CorsInit, DELETE, type ErrorJson, Forbidden, GET, HEAD, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, Middleware, NotFound, NotImplemented, OPTIONS, Options, PATCH, POST, PUT, type PathParams, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, type Worker, type WorkerClass, WorkerResponse, assertMethods, cache, cors, getContentType, getHeaderValues, getOrigin, isMethod, isMethodArray, lexCompare, mergeHeader, setHeader, sortSearchParams, stripSearchParams };
1022
+ export { BadRequest, BasicWorker, CacheControl, ClonedResponse, CloseCode, type CorsConfig, type CorsInit, DELETE, type ErrorJson, Forbidden, GET, HEAD, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, NotFound, NotImplemented, OPTIONS, Options, PATCH, POST, PUT, type PathParams, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, UpgradeRequired, WS_MAX_CLOSE_CODE, WS_MAX_REASON_CHARS, WS_RESERVED_CODES, WS_UPGRADE, WS_VERSION, WS_WEBSOCKET, WebSocketSessions, WebSocketUpgrade, type Worker, type WorkerClass, WorkerResponse, assertMethods, cache, cors, getContentType, getHeaderValues, getOrigin, isMethod, isMethodArray, lexCompare, mergeHeader, setHeader, sortSearchParams, stripSearchParams, websocket };