@adonix.org/cloud-spark 1.0.2 → 2.0.0
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/cache.js +3 -0
- package/dist/cache.js.map +1 -0
- package/dist/cors.js +2 -0
- package/dist/cors.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/sessions.js +2 -0
- package/dist/sessions.js.map +1 -0
- package/dist/websocket.js +2 -0
- package/dist/websocket.js.map +1 -0
- package/package.json +19 -3
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function a(t){return typeof t=="string"}function d(t){return typeof t=="number"&&!Number.isNaN(t)}function k(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function S(t){return a(t)?t.length>0:k(t)?t.byteLength>0:false}function h(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 u=class t{server;customListeners={};constructor(e){this.server=e;}addEventListener(e,r,n){if(t.isCustomEvent(e)){let o=this.customListeners[e];o||(o=[],this.customListeners[e]=o),o.push(r);}else {let o=e==="close"?{...n,once:true}:n;this.server.addEventListener(e,r,o);}}removeEventListener(e,r){if(t.isCustomEvent(e)){let n=this.customListeners[e];if(n){let o=n.indexOf(r);o!==-1&&n.splice(o,1);}}else this.server.removeEventListener(e,r);}dispatch(e,r,n=false){let o=this.customListeners[e]?.slice()??[];n&&(this.customListeners[e]=[]);for(let c of o)c(r);}warn(e){this.dispatch("warn",{type:"warn",message:e});}open(){this.dispatch("open",new Event("open"),true);}static isCustomEvent(e){return ["open","warn"].includes(e)}};var s={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},f=new Set([s.NO_STATUS,s.ABNORMAL,s.TLS_HANDSHAKE]);function m(t){return d(t)?C(t)&&!x(t)?t:s.NORMAL:s.NORMAL}function C(t){return t>=s.NORMAL&&t<=4999}function x(t){return f.has(t)}function v(t){if(a(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var i=class extends u{accepted=false;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(!S(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 n={...this.attachment,...e};h(n),this.server.serializeAttachment(n);}}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(m(e),v(r));}onclose=e=>{this.close(e.code,e.reason);}};var p=class extends i{client;constructor(){let e=new WebSocketPair,[r,n]=[e[0],e[1]];super(n),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=true,this.open(),this.client}};var l=class extends i{constructor(e){super(e),this.accepted=true;}accept(){throw new Error("Do not call accept() on restore")}acceptWebSocket(){throw new Error("Do not call acceptWebSocket() on restore")}};var A=class{map=new Map;create(e){class r extends p{constructor(b){super();this.sessions=b;}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(b,W){return this.sessions.register(this.server,this),super.acceptWebSocket(b,W)}}let n=new r(this);return n.attach(e),n}restore(e){class r extends l{constructor(o,c){super(c),o.register(this.server,this);}}return new r(this,e)}restoreAll(e){let r=[];for(let n of e)r.push(this.restore(n));return r}get(e){return this.map.get(e)}select(e){let r=[];for(let n of e){let o=this.map.get(n);o&&r.push(o);}return r}values(){return this.map.values()}keys(){return this.map.keys()}close(e,r,n){let o=this.get(e);return o&&o.close(r,n),this.unregister(e)}*[Symbol.iterator](){yield*this.values();}register(e,r){this.map.set(e,r);}unregister(e){return this.map.delete(e)}};export{A as WebSocketSessions};//# sourceMappingURL=sessions.js.map
|
|
2
|
+
//# sourceMappingURL=sessions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/guards/basic.ts","../src/guards/websocket.ts","../src/websocket/events.ts","../src/websocket/constants.ts","../src/websocket/utils.ts","../src/websocket/base.ts","../src/websocket/new.ts","../src/websocket/restore.ts","../src/websocket/sessions.ts"],"names":["isString","value","isNumber","isBinary","isSendable","assertSerializable","WebSocketEvents","_WebSocketEvents","server","type","listener","options","arr","finalOptions","index","ev","once","listeners","msg","CloseCode","WS_RESERVED_CODES","safeCloseCode","code","isCodeInRange","isReservedCode","safeReason","reason","BaseWebSocket","data","attachment","merged","states","event","NewConnectionBase","pair","client","ctx","tags","RestoredConnectionBase","ws","WebSocketSessions","NewConnection","sessions","connection","RestoredConnection","restore","all","restored","sockets","result","con"],"mappings":"AAgCO,SAASA,CAAAA,CAASC,EAAiC,CACtD,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAYO,SAASC,CAAAA,CAASD,CAAAA,CAAiC,CACtD,OAAO,OAAOA,GAAU,QAAA,EAAY,CAAC,OAAO,KAAA,CAAMA,CAAK,CAC3D,CCrBO,SAASE,CAAAA,CAASF,EAAwD,CAC7E,OAAOA,aAAiB,WAAA,EAAe,WAAA,CAAY,OAAOA,CAAK,CACnE,CAcO,SAASG,CAAAA,CAAWH,CAAAA,CAAiE,CACxF,OAAID,CAAAA,CAASC,CAAK,CAAA,CAAUA,CAAAA,CAAM,MAAA,CAAS,EACvCE,CAAAA,CAASF,CAAK,CAAA,CAAUA,CAAAA,CAAM,UAAA,CAAa,CAAA,CACxC,KACX,CAWO,SAASI,EAAmBJ,CAAAA,CAAyC,CACxE,GAAIA,CAAAA,GAAU,IAAA,EAAQ,OAAOA,CAAAA,EAAU,QAAA,CACnC,MAAM,IAAI,SAAA,CAAU,wCAAwC,EAEhE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AA,CAAOA,CAAE,CAC7B,CACJ","file":"sessions.js","sourcesContent":["/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks if the provided value is an array of strings.\n *\n * @param value - The value to check.\n * @returns True if `array` is an array where every item is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a string, otherwise `false`.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n\n/**\n * Checks if a value is a valid number (not NaN).\n *\n * This function returns `true` if the value is of type `number`\n * and is not `NaN`. It works as a type guard for TypeScript.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a number and not `NaN`, otherwise `false`.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a boolean (`true` or `false`), otherwise `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isString } from \"./basic\";\n\n/**\n * Checks whether a value is binary data suitable for WebSocket transmission.\n *\n * A value is considered binary if it is an {@link ArrayBuffer} or any\n * {@link ArrayBufferView} (such as a `Uint8Array`, `DataView`, etc.).\n *\n * @param value - The value to check.\n * @returns `true` if `value` is an {@link ArrayBuffer} or {@link ArrayBufferView}, otherwise `false`.\n */\nexport function isBinary(value: unknown): value is ArrayBuffer | ArrayBufferView {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n}\n\n/**\n * Checks whether a value can be sent over a WebSocket connection.\n *\n * A sendable value is either:\n * - a non-empty string, or\n * - a non-empty {@link ArrayBuffer} / {@link ArrayBufferView}.\n *\n * Empty strings and zero-length binary data are considered non-sendable.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is a non-empty string or binary buffer, otherwise `false`.\n */\nexport function isSendable(value: unknown): value is string | ArrayBuffer | ArrayBufferView {\n if (isString(value)) return value.length > 0;\n if (isBinary(value)) return value.byteLength > 0;\n return false;\n}\n\n/**\n * Asserts that a value is a serializable object suitable for JSON encoding.\n *\n * This function ensures the value is a non-null object and that\n * `JSON.stringify()` succeeds without throwing an error.\n *\n * @param value - The value to validate.\n * @throws {TypeError} If `value` is not an object or cannot be serialized to JSON.\n */\nexport function assertSerializable(value: unknown): asserts value is object {\n if (value === null || typeof value !== \"object\") {\n throw new TypeError(\"WebSocket attachment must be an object\");\n }\n try {\n JSON.stringify(value);\n } catch {\n throw new TypeError(\"WebSocket attachment is not serializable\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CustomEventType,\n EventOptions,\n ExtendedEventListener,\n ExtendedEventMap,\n ExtendedEventType,\n} from \"../interfaces/websocket\";\n\n/**\n * Base class for managing WebSocket events, including both standard WebSocket events\n * and internal custom events (`open` and `warn`).\n *\n * This class wraps a native WebSocket instance (`server`) and provides:\n * - Delegation of standard events (`message`, `close`, etc.)\n * - Support for custom events used internally by the library:\n * - `open`: dispatched once when the connection is accepted\n * - `warn`: dispatched whenever a warning occurs\n *\n * Subclasses can call `warn()` or `open()` to trigger custom events.\n */\nexport abstract class WebSocketEvents {\n /** The underlying WebSocket server instance being wrapped. */\n protected readonly server: WebSocket;\n\n /** Internal map of custom event listeners. */\n private customListeners: {\n [K in ExtendedEventType]?: ((ev: ExtendedEventMap[K]) => void)[];\n } = {};\n\n /**\n * @param server - The native WebSocket instance to wrap.\n */\n constructor(server: WebSocket) {\n this.server = server;\n }\n\n /**\n * Adds an event listener for either a standard WebSocket event or a custom event.\n *\n * - Custom events: `open`, `warn`\n * - Standard events: `message`, `close`, `error`, etc.\n *\n * The `close` event is automatically set to `{ once: true }` if no options are provided.\n *\n * @param type - Event type to listen for.\n * @param listener - Callback invoked when the event occurs.\n * @param options - Optional event options (`once`).\n */\n public addEventListener<K extends ExtendedEventType>(\n type: K,\n listener: ExtendedEventListener<K>,\n options?: EventOptions,\n ): void {\n if (WebSocketEvents.isCustomEvent(type)) {\n let arr = this.customListeners[type];\n if (!arr) {\n arr = [];\n this.customListeners[type] = arr;\n }\n arr.push(listener);\n } else {\n const finalOptions = type === \"close\" ? { ...options, once: true } : options;\n this.server.addEventListener(\n type as keyof WebSocketEventMap,\n listener as EventListener,\n finalOptions,\n );\n }\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * Works for both standard WebSocket events and custom events.\n *\n * @param type - Event type to remove.\n * @param listener - Listener function to remove.\n */\n public removeEventListener<K extends ExtendedEventType>(\n type: K,\n listener: ExtendedEventListener<K>,\n ): void {\n if (WebSocketEvents.isCustomEvent(type)) {\n const arr = this.customListeners[type];\n if (arr) {\n const index = arr.indexOf(listener);\n if (index !== -1) arr.splice(index, 1);\n }\n } else {\n this.server.removeEventListener(\n type as keyof WebSocketEventMap,\n listener as EventListener,\n );\n }\n }\n\n /**\n * Dispatches a custom event to all registered listeners.\n *\n * @param type - The custom event type (`open` or `warn`).\n * @param ev - Event object to pass to listeners.\n * @param once - If `true`, all listeners for this event are removed after dispatch.\n */\n private dispatch<K extends CustomEventType>(\n type: K,\n ev: ExtendedEventMap[K],\n once: boolean = false,\n ): void {\n const listeners = this.customListeners[type]?.slice() ?? [];\n if (once) {\n this.customListeners[type] = [];\n }\n for (const listener of listeners) {\n listener(ev);\n }\n }\n\n /**\n * Dispatches a `warn` event with a given message.\n *\n * Intended for internal use to notify listeners of warnings.\n *\n * @param msg - Warning message to emit.\n */\n protected warn(msg: string) {\n this.dispatch(\"warn\", { type: \"warn\", message: msg });\n }\n\n /**\n * Dispatches an `open` event.\n *\n * Intended to signal that the WebSocket has been accepted and is ready.\n * This event is dispatched only once.\n */\n protected open() {\n this.dispatch(\"open\", new Event(\"open\"), true);\n }\n\n /** Internal helper to determine if an event is a custom event. */\n private static isCustomEvent(type: ExtendedEventType): boolean {\n return [\"open\", \"warn\"].includes(type);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Max close code a user can send */\nexport const WS_MAX_CLOSE_CODE = 4999;\n/** Max number of reason chars a user can send */\nexport const WS_MAX_REASON_CHARS = 123;\n\n/** WebSocket close codes */\nexport const CloseCode = {\n NORMAL: 1000,\n NO_STATUS: 1005,\n ABNORMAL: 1006,\n TLS_HANDSHAKE: 1015,\n} as const;\n\n/** WebSocket RESERVED close codes */\nexport const WS_RESERVED_CODES = new Set<number>([\n CloseCode.NO_STATUS,\n CloseCode.ABNORMAL,\n CloseCode.TLS_HANDSHAKE,\n]);\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isNumber, isString } from \"../guards/basic\";\n\nimport { CloseCode, WS_MAX_CLOSE_CODE, WS_MAX_REASON_CHARS, WS_RESERVED_CODES } from \"./constants\";\n\n/**\n * Normalizes a WebSocket close code to ensure it is safe to send.\n *\n * - Returns `CloseCode.NORMAL` if the code is undefined, out of range, or reserved.\n *\n * @param code - The optional close code to validate.\n * @returns A valid close code to use for WebSocket closure.\n */\nexport function safeCloseCode(code?: number): number {\n if (!isNumber(code)) return CloseCode.NORMAL;\n if (isCodeInRange(code) && !isReservedCode(code)) return code;\n return CloseCode.NORMAL;\n}\n\n/**\n * Determines whether a close code is within the valid WebSocket range.\n *\n * @param code - The code to validate.\n * @returns `true` if the code is within 1000–4999, `false` otherwise.\n */\nexport function isCodeInRange(code: number): boolean {\n return code >= CloseCode.NORMAL && code <= WS_MAX_CLOSE_CODE;\n}\n\n/**\n * Determines whether a close code is reserved by the WebSocket specification.\n *\n * @param code - The code to check.\n * @returns `true` if the code is reserved, `false` otherwise.\n */\nexport function isReservedCode(code: number): boolean {\n return WS_RESERVED_CODES.has(code);\n}\n\n/**\n * Sanitizes a close reason string to comply with WebSocket limits.\n *\n * - Removes non-printable ASCII characters.\n * - Truncates to the maximum allowed length (`WS_MAX_REASON_CHARS`).\n *\n * @param reason - The optional reason string to sanitize.\n * @returns A cleaned reason string or `undefined` if input is invalid.\n */\nexport function safeReason(reason?: string): string | undefined {\n if (!isString(reason)) return;\n return reason.replaceAll(/[^\\x20-\\x7E]/g, \"\").slice(0, WS_MAX_REASON_CHARS);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertSerializable, isSendable } from \"../guards/websocket\";\nimport { WSAttachment } from \"../interfaces/websocket\";\n\nimport { WebSocketEvents } from \"./events\";\nimport { safeCloseCode, safeReason } from \"./utils\";\n\n/**\n * Base class providing core WebSocket functionality and attachment management.\n *\n * Extends `WebSocketEvents` to inherit custom event handling.\n *\n * @template A - Type of the attachment object associated with this WebSocket.\n */\nexport abstract class BaseWebSocket<A extends WSAttachment> extends WebSocketEvents {\n /** Tracks whether the WebSocket has been accepted. */\n protected accepted = false;\n\n /** The underlying WebSocket server instance. */\n protected readonly server: WebSocket;\n\n /**\n * Initializes the base WebSocket wrapper.\n *\n * Registers a listener to handle the underlying WebSocket `close` event.\n *\n * @param server - The underlying WebSocket instance.\n */\n constructor(server: WebSocket) {\n super(server);\n this.server = server;\n this.server.addEventListener(\"close\", this.onclose);\n }\n\n /**\n * Sends a message over the WebSocket if it is open.\n *\n * Performs validation to ensure the WebSocket is in an open state\n * and the data is non-empty and sendable. Emits a warning if not.\n *\n * @param data - The message to send, as a string or binary data.\n */\n public send(data: string | ArrayBuffer | ArrayBufferView): void {\n if (this.isState(WebSocket.CONNECTING, WebSocket.CLOSED)) {\n this.warn(\"Cannot send: WebSocket not open\");\n return;\n }\n if (!isSendable(data)) {\n this.warn(\"Cannot send: empty or invalid data\");\n return;\n }\n\n this.server.send(data);\n }\n\n /**\n * Returns the current attachment associated with this WebSocket.\n *\n * Attachments are stored as serialized objects on the underlying WebSocket.\n *\n * @returns Readonly attachment object of type `A`.\n */\n public get attachment(): Readonly<A> {\n return (this.server.deserializeAttachment() ?? {}) as A;\n }\n\n /**\n * Updates the attachment object for this WebSocket.\n *\n * Merges the provided partial attachment with the current attachment,\n * ensures it is serializable, and stores it on the underlying WebSocket.\n *\n * @param attachment - Partial or full attachment object to store,\n * or `null` to clear the attachment.\n */\n public attach(attachment?: Partial<A> | null): void {\n if (attachment === undefined) return;\n if (attachment === null) {\n this.server.serializeAttachment({});\n } else {\n const current = this.attachment;\n const merged = { ...current, ...attachment };\n assertSerializable(merged);\n this.server.serializeAttachment(merged);\n }\n }\n\n /**\n * Returns the current WebSocket ready state.\n *\n * If the WebSocket has not been accepted, returns `WebSocket.CONNECTING`.\n *\n * @returns The ready state of the WebSocket.\n */\n public get readyState(): number {\n if (!this.accepted) return WebSocket.CONNECTING;\n return this.server.readyState;\n }\n\n /**\n * Checks if the current ready state matches any of the provided states.\n *\n * @param states - One or more WebSocket state constants to check.\n * @returns `true` if the current state matches any provided, `false` otherwise.\n */\n public isState(...states: number[]): boolean {\n return states.includes(this.readyState);\n }\n\n /**\n * Closes the WebSocket safely.\n *\n * Removes the internal `close` listener and closes the underlying WebSocket\n * using validated close code and sanitized reason.\n *\n * @param code - Optional WebSocket close code.\n * @param reason - Optional reason for closing the WebSocket.\n */\n public close(code?: number, reason?: string): void {\n this.server.removeEventListener(\"close\", this.onclose);\n this.server.close(safeCloseCode(code), safeReason(reason));\n }\n\n /** Internal handler for the underlying WebSocket `close` event. */\n private readonly onclose = (event: CloseEvent): void => {\n this.close(event.code, event.reason);\n };\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WebSocketConnection, WSAttachment } from \"../interfaces/websocket\";\n\nimport { BaseWebSocket } from \"./base\";\n\n/**\n * Internal base for managing a new WebSocket connection.\n *\n * - Creates a WebSocket pair and stores the client side internally.\n * - Provides methods to accept the server WebSocket and retrieve the client.\n * - Ensures the `open` event is dispatched when the connection is accepted.\n * - Tracks whether the connection has already been accepted to prevent multiple acceptances.\n *\n * @template A - Type of the attachment object for this connection.\n */\nexport abstract class NewConnectionBase<A extends WSAttachment>\n extends BaseWebSocket<A>\n implements WebSocketConnection<A>\n{\n /** The client-facing end of the WebSocket pair. */\n private readonly client: WebSocket;\n\n /**\n * Creates a new WebSocket pair and initializes the server side.\n *\n * The client side is stored internally and returned upon acceptance.\n */\n public constructor() {\n const pair = new WebSocketPair();\n const [client, server] = [pair[0], pair[1]];\n super(server);\n this.client = client;\n }\n\n /**\n * Accepts the server WebSocket and returns the client WebSocket.\n *\n * If already accepted, returns the existing client WebSocket.\n * Otherwise, uses a Durable Object state to accept the connection\n * and marks it as ready.\n *\n * @param ctx - DurableObjectState used to accept the WebSocket.\n * @param tags - Optional array of tags to attach to the WebSocket.\n * @returns Readonly client WebSocket ready for use.\n */\n public acceptWebSocket(ctx: DurableObjectState, tags?: string[]): Readonly<WebSocket> {\n if (this.accepted) return this.client;\n ctx.acceptWebSocket(this.server, tags);\n return this.ready();\n }\n\n /**\n * Accepts the server WebSocket and returns the client WebSocket.\n *\n * If already accepted, returns the existing client WebSocket.\n * Otherwise, calls the internal server accept method and marks\n * the connection as ready.\n *\n * @returns Readonly client WebSocket ready for use.\n */\n public accept(): Readonly<WebSocket> {\n if (this.accepted) return this.client;\n this.server.accept();\n return this.ready();\n }\n\n /**\n * Marks the WebSocket connection as ready.\n *\n * Sets the accepted flag, dispatches the `open` event,\n * and returns the client WebSocket.\n *\n * @returns Client WebSocket ready for use.\n */\n private ready(): WebSocket {\n this.accepted = true;\n this.open();\n\n return this.client;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WebSocketConnection, WSAttachment } from \"../interfaces/websocket\";\n\nimport { BaseWebSocket } from \"./base\";\n\n/**\n * Internal base for a WebSocket connection that has already been restored.\n *\n * - Marks the connection as accepted immediately upon construction.\n * - Overrides acceptance methods to prevent re-accepting an already-active WebSocket.\n * - Throws an error if `accept()` or `acceptWebSocket()` is called.\n *\n * @template A - Type of the attachment object for this connection.\n */\nexport abstract class RestoredConnectionBase<A extends WSAttachment>\n extends BaseWebSocket<A>\n implements WebSocketConnection<A>\n{\n constructor(ws: WebSocket) {\n super(ws);\n this.accepted = true;\n }\n\n /** Not supported for restored connections; throws an error. */\n public accept(): Readonly<WebSocket> {\n throw new Error(\"Do not call accept() on restore\");\n }\n\n /** Not supported for restored connections; throws an error. */\n public acceptWebSocket(): Readonly<WebSocket> {\n throw new Error(\"Do not call acceptWebSocket() on restore\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WebSocketConnection, WSAttachment } from \"../interfaces/websocket\";\n\nimport { NewConnectionBase } from \"./new\";\nimport { RestoredConnectionBase } from \"./restore\";\n\n/**\n * Manages active WebSocket connections in a Cloudflare Workers environment.\n *\n * Provides a simple interface for creating, restoring, and managing\n * WebSocket connections with optional attachments. Users can:\n *\n * - Create new WebSocket connections (`create`) and attach arbitrary data.\n * - Accept connections using the standard WebSocket API (`accept`).\n * - Accept connections using the hibernatable WebSocket API (`acceptWebSocket`),\n * which allows the connection to be put to sleep when inactive.\n * - Restore existing WebSockets into a managed session (`restore`, `restoreAll`),\n * maintaining their hibernation state.\n * - Iterate over active connections or retrieve a connection by its WebSocket instance.\n * - Close a connection cleanly with optional code and reason (`close`).\n *\n * @template A - Type of attachment data stored on each WebSocket connection.\n */\nexport class WebSocketSessions<A extends WSAttachment = WSAttachment> {\n /** @internal Map of active WebSocket to their connection wrapper. */\n private readonly map = new Map<WebSocket, WebSocketConnection<A>>();\n\n /**\n * Create a new WebSocket connection and optionally attach user data.\n *\n * @param attachment - Partial attachment object to initialize the connection with.\n * @returns A `WebSocketConnection` instance ready for accepting and sending messages.\n */\n public create(attachment?: Partial<A>): WebSocketConnection<A> {\n class NewConnection extends NewConnectionBase<A> {\n constructor(private readonly sessions: WebSocketSessions<A>) {\n super();\n }\n\n public override accept(): WebSocket {\n this.addEventListener(\"close\", () => this.sessions.unregister(this.server));\n this.sessions.register(this.server, this);\n return super.accept();\n }\n\n public override acceptWebSocket(ctx: DurableObjectState, tags?: string[]): WebSocket {\n this.sessions.register(this.server, this);\n return super.acceptWebSocket(ctx, tags);\n }\n }\n\n const connection = new NewConnection(this);\n connection.attach(attachment);\n return connection;\n }\n\n /**\n * Wraps an existing WebSocket in a managed connection session.\n *\n * @param ws - An existing WebSocket to restore.\n * @returns A `WebSocketConnection` representing the restored session.\n */\n public restore(ws: WebSocket): WebSocketConnection<A> {\n class RestoredConnection extends RestoredConnectionBase<A> {\n constructor(sessions: WebSocketSessions<A>, restore: WebSocket) {\n super(restore);\n sessions.register(this.server, this);\n }\n }\n return new RestoredConnection(this, ws);\n }\n\n /**\n * Restores multiple WebSockets into managed sessions at once.\n *\n * @param all - Array of WebSocket instances to restore.\n * @returns Array of `WebSocketConnections` restored.\n */\n public restoreAll(all: WebSocket[]): ReadonlyArray<WebSocketConnection<A>> {\n const restored: WebSocketConnection<A>[] = [];\n for (const ws of all) {\n restored.push(this.restore(ws));\n }\n return restored;\n }\n\n /**\n * Retrieves the managed connection for a specific WebSocket, if any.\n *\n * @param ws - WebSocket instance.\n * @returns Corresponding `WebSocketConnection` or `undefined` if not managed.\n */\n public get(ws: WebSocket): WebSocketConnection<A> | undefined {\n return this.map.get(ws);\n }\n\n /**\n * Selects the managed `WebSocketConnection` objects corresponding to the given WebSockets.\n *\n * @param sockets - Array of WebSocket instances to resolve.\n * @returns Array of corresponding `WebSocketConnection` objects.\n */\n public select(sockets: WebSocket[]): WebSocketConnection<A>[] {\n const result: WebSocketConnection<A>[] = [];\n for (const ws of sockets) {\n const con = this.map.get(ws);\n if (con) result.push(con);\n }\n return result;\n }\n\n /**\n * Returns an iterator over all active `WebSocketConnection` objects\n * managed by this session.\n *\n * Useful for iterating over all connections to perform actions such as\n * broadcasting messages.\n *\n * @returns Iterable iterator of all active `WebSocketConnection` objects.\n */\n public values(): IterableIterator<WebSocketConnection<A>> {\n return this.map.values();\n }\n\n /**\n * Returns an iterator over all active raw `WebSocket` instances\n * currently tracked by this session.\n *\n * @returns Iterable iterator of all active `WebSocket` instances.\n */\n public keys(): IterableIterator<WebSocket> {\n return this.map.keys();\n }\n\n /**\n * Closes a managed WebSocket connection with optional code and reason.\n *\n * @param ws - WebSocket to close.\n * @param code - Optional WebSocket close code.\n * @param reason - Optional reason string.\n * @returns `true` if the connection was managed and removed, `false` otherwise.\n */\n public close(ws: WebSocket, code?: number, reason?: string): boolean {\n const con = this.get(ws);\n if (con) con.close(code, reason);\n\n return this.unregister(ws);\n }\n\n /** Iterates over all active WebSocket connections. */\n public *[Symbol.iterator](): IterableIterator<WebSocketConnection<A>> {\n yield* this.values();\n }\n\n /** Registers a connection internally. */\n private register(ws: WebSocket, con: WebSocketConnection<A>): void {\n this.map.set(ws, con);\n }\n\n /** Un-registers a connection internally. */\n private unregister(ws: WebSocket): boolean {\n return this.map.delete(ws);\n }\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {match}from'path-to-regexp';import {StatusCodes}from'http-status-codes/build/es/status-codes';import {getReasonPhrase}from'http-status-codes/build/es/utils-functions';import R from'cache-control-parser';var g=(n=>(n.GET="GET",n.PUT="PUT",n.HEAD="HEAD",n.POST="POST",n.PATCH="PATCH",n.DELETE="DELETE",n.OPTIONS="OPTIONS",n))(g||{}),{GET:I,PUT:V,HEAD:v,POST:K,PATCH:q,DELETE:$,OPTIONS:z}=g;var E={parse:R.parse,stringify:R.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var o={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",SEC_WEBSOCKET_VERSION:"sec-websocket-version",UPGRADE:"upgrade"},H=[o.CONTENT_TYPE,o.CONTENT_LENGTH,o.CONTENT_RANGE,o.CONTENT_ENCODING,o.CONTENT_LANGUAGE,o.CONTENT_DISPOSITION,o.CONTENT_MD5],D=[o.CONTENT_LENGTH,o.CONTENT_RANGE];var L="upgrade",P="websocket";var O="utf-8";function h(e,t){return e<t?-1:e>t?1:0}function m(e,t,r){let s=Array.isArray(r)?r:[r],i=Array.from(new Set(s.map(c=>c.trim()))).filter(c=>c.length).sort(h);if(!i.length){e.delete(t);return}e.set(t,i.join(", "));}function b(e,t,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let c=d(e,t).concat(s.map(M=>M.trim()));m(e,t,c);}function d(e,t){let r=e.get(t)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(h)}function N(e,t){for(let r of t)e.delete(r);}function f(e,t){return !t||e.toLowerCase().includes("charset=")?e:`${e}; charset=${t.toLowerCase()}`}var _=class{headers=new Headers;status=StatusCodes.OK;statusText;webSocket;mediaType=f("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,r){m(this.headers,t,r);}mergeHeader(t,r){b(this.headers,t,r);}addContentType(){this.headers.get(o.CONTENT_TYPE)||this.setHeader(o.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===StatusCodes.NO_CONTENT?N(this.headers,D):this.status===StatusCodes.NOT_MODIFIED&&N(this.headers,H);}},S=class extends _{constructor(r){super();this.cache=r;}addCacheHeader(){this.cache&&this.setHeader(o.CACHE_CONTROL,E.stringify(this.cache));}},A=class extends S{constructor(r=null,s){super(s);this.body=r;}async response(){this.addCacheHeader();let r=[StatusCodes.NO_CONTENT,StatusCodes.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}};var x=class extends A{constructor(t=null,r,s=StatusCodes.OK){super(t,r),this.status=s;}},u=class extends x{constructor(t={},r,s=StatusCodes.OK){super(JSON.stringify(t),r,s),this.mediaType=f("application/json",O);}};var T=class extends u{constructor(r,s){let i={status:r,error:getReasonPhrase(r),details:s??""};super(i,E.DISABLE,r);this.details=s;}};var p=class extends T{constructor(t){super(StatusCodes.BAD_REQUEST,t);}};var l=class extends T{constructor(){super(StatusCodes.UPGRADE_REQUIRED),this.setHeader(o.SEC_WEBSOCKET_VERSION,"13");}};function G(e){return d(e,o.CONNECTION).some(t=>t.toLowerCase()===L)}function W(e){return d(e,o.UPGRADE).some(t=>t.toLowerCase()===P)}function U(e){return e.get(o.SEC_WEBSOCKET_VERSION)?.trim()==="13"}var C=class{constructor(t){this.path=t;}handle(t,r){if(t.request.method!==I||!this.isMatch(t.request))return r();let s=t.request.headers;return G(s)?W(s)?U(s)?r():new l().response():new p("Missing or invalid 'Upgrade' header").response():new p("Missing or invalid 'Connection' header").response()}isMatch(t){return match(this.path)(new URL(t.url).pathname)!==false}};function Dt(e="/"){return new C(e)}export{Dt as websocket};//# sourceMappingURL=websocket.js.map
|
|
2
|
+
//# sourceMappingURL=websocket.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/constants/methods.ts","../src/constants/cache.ts","../src/constants/headers.ts","../src/middleware/websocket/constants.ts","../src/constants/media.ts","../src/utils/compare.ts","../src/utils/headers.ts","../src/utils/media.ts","../src/responses.ts","../src/errors.ts","../src/middleware/websocket/utils.ts","../src/middleware/websocket/handler.ts","../src/middleware/websocket/websocket.ts"],"names":["Method","GET","PUT","HEAD","POST","PATCH","DELETE","OPTIONS","CacheControl","CacheLib","HttpHeader","FORBIDDEN_304_HEADERS","FORBIDDEN_204_HEADERS","WS_UPGRADE","WS_WEBSOCKET","UTF8_CHARSET","lexCompare","a","b","setHeader","headers","key","value","raw","values","v","mergeHeader","merged","getHeaderValues","filterHeaders","keys","withCharset","mediaType","charset","BaseResponse","StatusCodes","getReasonPhrase","CacheResponse","cache","WorkerResponse","body","SuccessResponse","status","JsonResponse","json","HttpError","details","BadRequest","UpgradeRequired","hasConnectionHeader","hasUpgradeHeader","hasWebSocketVersion","WebSocketHandler","path","worker","next","request","match","websocket"],"mappings":"kNAmBO,IAAKA,OACRA,CAAAA,CAAA,GAAA,CAAM,MACNA,CAAAA,CAAA,GAAA,CAAM,MACNA,CAAAA,CAAA,IAAA,CAAO,OACPA,CAAAA,CAAA,IAAA,CAAO,OACPA,CAAAA,CAAA,KAAA,CAAQ,OAAA,CACRA,CAAAA,CAAA,MAAA,CAAS,QAAA,CACTA,EAAA,OAAA,CAAU,S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C,CACJ,CAQO,SAASqC,CAAAA,CAAoB/B,EAA2B,CAC3D,OAAOA,EAAQ,GAAA,CAAIV,CAAAA,CAAW,qBAAqB,CAAA,EAAG,IAAA,EAAK,GAAM,IACrE,CChBO,IAAM0C,EAAN,KAA6C,CAOhD,YAA6BC,CAAAA,CAAc,CAAd,UAAAA,EAAe,CAUrC,MAAA,CAAOC,CAAAA,CAAgBC,CAAAA,CAAkD,CAK5E,GAJID,CAAAA,CAAO,OAAA,CAAQ,SAAWrD,CAAAA,EAI1B,CAAC,KAAK,OAAA,CAAQqD,CAAAA,CAAO,OAAO,CAAA,CAC5B,OAAOC,CAAAA,GAGX,IAAMnC,CAAAA,CAAUkC,EAAO,OAAA,CAAQ,OAAA,CAC/B,OAAKL,CAAAA,CAAoB7B,CAAO,CAAA,CAG3B8B,CAAAA,CAAiB9B,CAAO,CAAA,CAGxB+B,EAAoB/B,CAAO,CAAA,CAIzBmC,GAAK,CAHD,IAAIP,GAAgB,CAAE,QAAA,EAAS,CAH/B,IAAID,CAAAA,CAAW,qCAAqC,EAAE,QAAA,EAAS,CAH/D,IAAIA,CAAAA,CAAW,wCAAwC,EAAE,QAAA,EAUxE,CAQQ,OAAA,CAAQS,CAAAA,CAA2B,CACvC,OAAOC,KAAAA,CAAM,IAAA,CAAK,IAAI,CAAA,CAAE,IAAI,IAAID,CAAAA,CAAQ,GAAG,CAAA,CAAE,QAAQ,CAAA,GAAM,KAC/D,CACJ,CAAA,CC1CO,SAASE,GAAUL,CAAAA,CAAe,GAAA,CAAiB,CACtD,OAAO,IAAID,CAAAA,CAAiBC,CAAI,CACpC","file":"websocket.js","sourcesContent":["/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Standard HTTP request methods.\n */\nexport enum Method {\n GET = \"GET\",\n PUT = \"PUT\",\n HEAD = \"HEAD\",\n POST = \"POST\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n OPTIONS = \"OPTIONS\",\n}\n\n/**\n * Shorthand constants for each HTTP method.\n *\n * These are equivalent to the corresponding enum members in `Method`.\n * For example, `GET === Method.GET`.\n */\nexport const { GET, PUT, HEAD, POST, PATCH, DELETE, OPTIONS } = Method;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport CacheLib from \"cache-control-parser\";\n\n/**\n * @see {@link https://github.com/etienne-martin/cache-control-parser | cache-control-parser}\n */\nexport type CacheControl = CacheLib.CacheControl;\nexport const CacheControl = {\n parse: CacheLib.parse,\n stringify: CacheLib.stringify,\n\n /** A CacheControl directive that disables all caching. */\n DISABLE: Object.freeze({\n \"no-cache\": true,\n \"no-store\": true,\n \"must-revalidate\": true,\n \"max-age\": 0,\n }) satisfies CacheControl,\n};\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Internally used headers.\n */\nexport const HttpHeader = {\n ACCEPT: \"accept\",\n ACCEPT_ENCODING: \"accept-encoding\",\n ACCEPT_LANGUAGE: \"accept-language\",\n ACCEPT_RANGES: \"accept-ranges\",\n ALLOW: \"allow\",\n AUTHORIZATION: \"authorization\",\n CACHE_CONTROL: \"cache-control\",\n CONNECTION: \"connection\",\n CONTENT_DISPOSITION: \"content-disposition\",\n CONTENT_ENCODING: \"content-encoding\",\n CONTENT_LANGUAGE: \"content-language\",\n CONTENT_LENGTH: \"content-length\",\n CONTENT_RANGE: \"content-range\",\n CONTENT_TYPE: \"content-type\",\n CONTENT_MD5: \"content-md5\",\n COOKIE: \"cookie\",\n ETAG: \"etag\",\n IF_MATCH: \"if-match\",\n IF_MODIFIED_SINCE: \"if-modified-since\",\n IF_NONE_MATCH: \"if-none-match\",\n IF_UNMODIFIED_SINCE: \"if-unmodified-since\",\n LAST_MODIFIED: \"last-modified\",\n ORIGIN: \"origin\",\n RANGE: \"range\",\n SET_COOKIE: \"set-cookie\",\n VARY: \"vary\",\n\n // Cors Headers\n ACCESS_CONTROL_ALLOW_CREDENTIALS: \"access-control-allow-credentials\",\n ACCESS_CONTROL_ALLOW_HEADERS: \"access-control-allow-headers\",\n ACCESS_CONTROL_ALLOW_METHODS: \"access-control-allow-methods\",\n ACCESS_CONTROL_ALLOW_ORIGIN: \"access-control-allow-origin\",\n ACCESS_CONTROL_EXPOSE_HEADERS: \"access-control-expose-headers\",\n ACCESS_CONTROL_MAX_AGE: \"access-control-max-age\",\n\n // Websocket Headers\n SEC_WEBSOCKET_VERSION: \"sec-websocket-version\",\n UPGRADE: \"upgrade\",\n\n // Internal Headers\n INTERNAL_VARIANT_SET: \"internal-variant-set\",\n} as const;\n\n/**\n * Headers that must not be sent in 304 Not Modified responses.\n * These are stripped to comply with the HTTP spec.\n */\nexport const FORBIDDEN_304_HEADERS = [\n HttpHeader.CONTENT_TYPE,\n HttpHeader.CONTENT_LENGTH,\n HttpHeader.CONTENT_RANGE,\n HttpHeader.CONTENT_ENCODING,\n HttpHeader.CONTENT_LANGUAGE,\n HttpHeader.CONTENT_DISPOSITION,\n HttpHeader.CONTENT_MD5,\n];\n\n/**\n * Headers that should not be sent in 204 No Content responses.\n * Stripping them is recommended but optional per spec.\n */\nexport const FORBIDDEN_204_HEADERS = [HttpHeader.CONTENT_LENGTH, HttpHeader.CONTENT_RANGE];\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** WebSocket upgrade header value */\nexport const WS_UPGRADE = \"upgrade\";\n\n/** WebSocket protocol header value */\nexport const WS_WEBSOCKET = \"websocket\";\n\n/** WebSocket protocol version */\nexport const WS_VERSION = \"13\";\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const UTF8_CHARSET = \"utf-8\";\n\n/**\n * Internal media types.\n */\nexport enum MediaType {\n PLAIN_TEXT = \"text/plain\",\n HTML = \"text/html\",\n JSON = \"application/json\",\n OCTET_STREAM = \"application/octet-stream\",\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Lexicographically compares two strings.\n *\n * This comparator can be used in `Array.prototype.sort()` to produce a\n * consistent, stable ordering of string arrays.\n *\n * @param a - The first string to compare.\n * @param b - The second string to compare.\n * @returns A number indicating the relative order of `a` and `b`.\n */\nexport function lexCompare(a: string, b: string): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { lexCompare } from \"./compare\";\n\n/**\n * Sets a header on the given Headers object.\n *\n * - If `value` is an array, any duplicates and empty strings are removed.\n * - If the resulting value is empty, the header is deleted.\n * - Otherwise, values are joined with `\", \"` and set as the header value.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to set.\n * @param value - The header value(s) to set. Can be a string or array of strings.\n */\nexport function setHeader(headers: Headers, key: string, value: string | string[]): void {\n const raw = Array.isArray(value) ? value : [value];\n const values = Array.from(new Set(raw.map((v) => v.trim())))\n .filter((v) => v.length)\n .sort(lexCompare);\n\n if (!values.length) {\n headers.delete(key);\n return;\n }\n\n headers.set(key, values.join(\", \"));\n}\n\n/**\n * Merges new value(s) into an existing header on the given Headers object.\n *\n * - Preserves any existing values and adds new ones.\n * - Removes duplicates and trims all values.\n * - If the header does not exist, it is created.\n * - If the resulting value array is empty, the header is deleted.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to merge into.\n * @param value - The new header value(s) to add. Can be a string or array of strings.\n */\nexport function mergeHeader(headers: Headers, key: string, value: string | string[]): void {\n const values = Array.isArray(value) ? value : [value];\n if (values.length === 0) return;\n\n const existing = getHeaderValues(headers, key);\n const merged = existing.concat(values.map((v) => v.trim()));\n\n setHeader(headers, key, merged);\n}\n\n/**\n * Returns the values of an HTTP header as an array of strings.\n *\n * This helper:\n * - Retrieves the header value by `key`.\n * - Splits the value on commas.\n * - Trims surrounding whitespace from each entry.\n * - Filters out any empty tokens.\n * - Removes duplicate values (case-sensitive)\n *\n * If the header is not present, an empty array is returned.\n *\n */\nexport function getHeaderValues(headers: Headers, key: string): string[] {\n const values =\n headers\n .get(key)\n ?.split(\",\")\n .map((v) => v.trim())\n .filter((v) => v.length > 0) ?? [];\n return Array.from(new Set(values)).sort(lexCompare);\n}\n\n/**\n * Removes a list of header fields from a {@link Headers} object.\n *\n * @param headers - The {@link Headers} object to modify in place.\n * @param keys - An array of header field names to remove. Header names are\n * matched case-insensitively per the Fetch spec.\n */\nexport function filterHeaders(headers: Headers, keys: string[]): void {\n for (const key of keys) {\n headers.delete(key);\n }\n}\n\n/**\n * Extracts all header names from a `Headers` object, normalizes them,\n * and returns them in a stable, lexicographically sorted array.\n *\n * @param headers - The `Headers` object to extract keys from.\n * @returns A sorted array of lowercase header names.\n */\nexport function getHeaderKeys(headers: Headers): string[] {\n return [...headers.keys()].sort(lexCompare);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Appends a charset parameter to a given media type string,\n * avoiding duplicates and ignoring empty charsets.\n *\n * @param {string} mediaType - The MIME type (e.g., \"text/html\").\n * @param {string} charset - The character set to append (e.g., \"utf-8\").\n * @returns {string} The media type with charset appended if provided.\n */\nexport function withCharset(mediaType: string, charset: string): string {\n if (!charset || mediaType.toLowerCase().includes(\"charset=\")) {\n return mediaType;\n }\n return `${mediaType}; charset=${charset.toLowerCase()}`;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"http-status-codes/build/es/status-codes\";\nimport { getReasonPhrase } from \"http-status-codes/build/es/utils-functions\";\n\nimport { CacheControl } from \"./constants/cache\";\nimport { FORBIDDEN_204_HEADERS, FORBIDDEN_304_HEADERS, HttpHeader } from \"./constants/headers\";\nimport { MediaType, UTF8_CHARSET } from \"./constants/media\";\nimport { GET, HEAD } from \"./constants/methods\";\nimport { assertMethods } from \"./guards/methods\";\nimport { assertOctetStreamInit } from \"./guards/responses\";\nimport { Worker } from \"./interfaces\";\nimport { OctetStreamInit } from \"./interfaces/response\";\nimport { filterHeaders, mergeHeader, setHeader } from \"./utils/headers\";\nimport { withCharset } from \"./utils/media\";\n\n/**\n * Base class for building HTTP responses.\n * Manages headers, status, and media type.\n */\nabstract class BaseResponse {\n /** HTTP headers for the response. */\n public headers: Headers = new Headers();\n\n /** HTTP status code (default 200 OK). */\n public status: StatusCodes = StatusCodes.OK;\n\n /** Optional status text. Defaults to standard reason phrase. */\n public statusText?: string;\n\n /** Optional websocket property. */\n public webSocket?: WebSocket | null;\n\n /** Default media type of the response body. */\n public mediaType: string = withCharset(MediaType.PLAIN_TEXT, UTF8_CHARSET);\n\n /** Converts current state to ResponseInit for constructing a Response. */\n protected get responseInit(): ResponseInit {\n return {\n headers: this.headers,\n status: this.status,\n statusText: this.statusText ?? getReasonPhrase(this.status),\n webSocket: this.webSocket,\n encodeBody: \"automatic\",\n };\n }\n\n /** Sets a header, overwriting any existing value. */\n public setHeader(key: string, value: string | string[]): void {\n setHeader(this.headers, key, value);\n }\n\n /** Merges a header with existing values (does not overwrite). */\n public mergeHeader(key: string, value: string | string[]): void {\n mergeHeader(this.headers, key, value);\n }\n\n /** Adds a Content-Type header if not already existing (does not overwrite). */\n public addContentType() {\n if (!this.headers.get(HttpHeader.CONTENT_TYPE)) {\n this.setHeader(HttpHeader.CONTENT_TYPE, this.mediaType);\n }\n }\n\n /**\n * Removes headers that are disallowed or discouraged based on the current\n * status code.\n *\n * - **204 No Content:** strips headers that \"should not\" be sent\n * (`Content-Length`, `Content-Range`), per the HTTP spec.\n * - **304 Not Modified:** strips headers that \"must not\" be sent\n * (`Content-Type`, `Content-Length`, `Content-Range`, etc.), per the HTTP spec.\n *\n * This ensures that responses remain compliant with HTTP/1.1 standards while preserving\n * custom headers that are allowed.\n */\n public filterHeaders(): void {\n if (this.status === StatusCodes.NO_CONTENT) {\n filterHeaders(this.headers, FORBIDDEN_204_HEADERS);\n } else if (this.status === StatusCodes.NOT_MODIFIED) {\n filterHeaders(this.headers, FORBIDDEN_304_HEADERS);\n }\n }\n}\n\n/**\n * Base response class that adds caching headers.\n */\nabstract class CacheResponse extends BaseResponse {\n constructor(public cache?: CacheControl) {\n super();\n }\n\n /** Adds Cache-Control header if caching is configured. */\n protected addCacheHeader(): void {\n if (this.cache) {\n this.setHeader(HttpHeader.CACHE_CONTROL, CacheControl.stringify(this.cache));\n }\n }\n}\n\n/**\n * Core response. Combines caching, and content type headers.\n */\nexport abstract class WorkerResponse extends CacheResponse {\n constructor(\n private readonly body: BodyInit | null = null,\n cache?: CacheControl,\n ) {\n super(cache);\n }\n\n /** Builds the Response with body, headers, and status. */\n public async response(): Promise<Response> {\n this.addCacheHeader();\n\n const body = [StatusCodes.NO_CONTENT, StatusCodes.NOT_MODIFIED].includes(this.status)\n ? null\n : this.body;\n\n if (body) this.addContentType();\n\n this.filterHeaders();\n\n return new Response(body, this.responseInit);\n }\n}\n\n/**\n * Copies an existing response for mutation. Pass in a CacheControl\n * to be used for the response, overriding any existing `cache-control`\n * on the source response.\n */\nexport class CopyResponse extends WorkerResponse {\n constructor(response: Response, cache?: CacheControl) {\n super(response.body, cache);\n this.status = response.status;\n this.statusText = response.statusText;\n this.headers = new Headers(response.headers);\n }\n}\n\n/**\n * Copies the response, but with null body and status 304 Not Modified.\n */\nexport class NotModified extends WorkerResponse {\n constructor(response: Response) {\n super();\n this.status = StatusCodes.NOT_MODIFIED;\n this.headers = new Headers(response.headers);\n }\n}\n\n/**\n * Represents a successful response with customizable body, cache and status.\n */\nexport class SuccessResponse extends WorkerResponse {\n constructor(\n body: BodyInit | null = null,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n ) {\n super(body, cache);\n this.status = status;\n }\n}\n\n/**\n * JSON response. Automatically sets Content-Type to application/json.\n */\nexport class JsonResponse extends SuccessResponse {\n constructor(json: unknown = {}, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(JSON.stringify(json), cache, status);\n this.mediaType = withCharset(MediaType.JSON, UTF8_CHARSET);\n }\n}\n\n/**\n * HTML response. Automatically sets Content-Type to text/html.\n */\nexport class HtmlResponse extends SuccessResponse {\n constructor(\n body: string,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n charset: string = UTF8_CHARSET,\n ) {\n super(body, cache, status);\n this.mediaType = withCharset(MediaType.HTML, charset);\n }\n}\n\n/**\n * Plain text response. Automatically sets Content-Type to text/plain.\n */\nexport class TextResponse extends SuccessResponse {\n constructor(\n body: string,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n charset: string = UTF8_CHARSET,\n ) {\n super(body, cache, status);\n this.mediaType = withCharset(MediaType.PLAIN_TEXT, charset);\n }\n}\n\n/**\n * Represents an HTTP response for serving binary data as `application/octet-stream`.\n *\n * This class wraps a `ReadableStream` and sets all necessary headers for both\n * full and partial content responses, handling range requests in a hybrid way\n * to maximize browser and CDN caching.\n *\n * Key behaviors:\n * - `Content-Type` is set to `application/octet-stream`.\n * - `Accept-Ranges: bytes` is always included.\n * - `Content-Length` is always set to the validated length of the response body.\n * - If the request is a true partial range (offset > 0 or length < size), the response\n * will be `206 Partial Content` with the appropriate `Content-Range` header.\n * - If the requested range covers the entire file (even if a Range header is present),\n * the response will return `200 OK` to enable browser and edge caching.\n * - Zero-length streams (`size = 0`) are never treated as partial.\n * - Special case: a requested range of `0-0` on a non-empty file is normalized to 1 byte.\n */\nexport class OctetStream extends WorkerResponse {\n constructor(stream: ReadableStream, init: OctetStreamInit, cache?: CacheControl) {\n assertOctetStreamInit(init);\n\n super(stream, cache);\n this.mediaType = MediaType.OCTET_STREAM;\n\n const normalized = OctetStream.normalizeInit(init);\n const { size, offset, length } = normalized;\n\n if (OctetStream.isPartial(normalized)) {\n this.setHeader(\n HttpHeader.CONTENT_RANGE,\n `bytes ${offset}-${offset + length - 1}/${size}`,\n );\n this.status = StatusCodes.PARTIAL_CONTENT;\n }\n\n this.setHeader(HttpHeader.ACCEPT_RANGES, \"bytes\");\n this.setHeader(HttpHeader.CONTENT_LENGTH, `${length}`);\n }\n\n /**\n * Normalizes a partially-specified `OctetStreamInit` into a fully-specified object.\n *\n * Ensures that all required fields (`size`, `offset`, `length`) are defined:\n * - `offset` defaults to 0 if not provided.\n * - `length` defaults to `size - offset` if not provided.\n * - Special case: if `offset` and `length` are both 0 but `size > 0`, `length` is set to 1\n * to avoid zero-length partial streams.\n *\n * @param init - The initial `OctetStreamInit` object, possibly with missing `offset` or `length`.\n * @returns A fully-specified `OctetStreamInit` object with `size`, `offset`, and `length` guaranteed.\n */\n private static normalizeInit(init: OctetStreamInit): Required<OctetStreamInit> {\n const { size } = init;\n const offset = init.offset ?? 0;\n let length = init.length ?? size - offset;\n\n if (offset === 0 && length === 0 && size > 0) {\n length = 1;\n }\n\n return { size, offset, length };\n }\n\n /**\n * Determines whether the given `OctetStreamInit` represents a partial range.\n *\n * Partial ranges are defined as any range that does **not** cover the entire file:\n * - If `size === 0`, the stream is never partial.\n * - If `offset === 0` and `length === size`, the stream is treated as a full file (not partial),\n * even if a Range header is present. This enables browser and CDN caching.\n * - All other cases are considered partial, and will result in a `206 Partial Content` response.\n *\n * @param init - A fully-normalized `OctetStreamInit` object.\n * @returns `true` if the stream represents a partial range; `false` if it represents the full file.\n */\n private static isPartial(init: Required<OctetStreamInit>): boolean {\n if (init.size === 0) return false;\n return !(init.offset === 0 && init.length === init.size);\n }\n}\n\n/**\n * A streaming response for Cloudflare R2 objects.\n *\n * **Partial content support:** To enable HTTP 206 streaming, you must provide\n * request headers containing the `Range` header when calling the R2 bucket's `get()` method.\n *\n * Example:\n * ```ts\n * const stream = await this.env.R2_BUCKET.get(\"key\", { range: this.request.headers });\n * ```\n *\n * @param source - The R2 object to stream.\n * @param cache - Optional caching override.\n */\nexport class R2ObjectStream extends OctetStream {\n constructor(source: R2ObjectBody, cache?: CacheControl) {\n let useCache = cache;\n if (!useCache && source.httpMetadata?.cacheControl) {\n useCache = CacheControl.parse(source.httpMetadata.cacheControl);\n }\n\n super(source.body, R2ObjectStream.computeRange(source.size, source.range), useCache);\n\n this.setHeader(HttpHeader.ETAG, source.httpEtag);\n\n if (source.httpMetadata?.contentType) {\n this.mediaType = source.httpMetadata.contentType;\n }\n }\n\n /**\n * Computes an `OctetStreamInit` object from a given R2 range.\n *\n * This function normalizes a Cloudflare R2 `R2Range` into the shape expected\n * by `OctetStream`. It handles the following cases:\n *\n * - No range provided: returns `{ size }` (full content).\n * - `suffix` range: calculates the offset and length from the end of the file.\n * - Explicit `offset` and/or `length`: passed through as-is.\n *\n * @param size - The total size of the file/object.\n * @param range - Optional range to extract (from R2). Can be:\n * - `{ offset: number; length?: number }`\n * - `{ offset?: number; length: number }`\n * - `{ suffix: number }`\n * @returns An `OctetStreamInit` object suitable for `OctetStream`.\n */\n private static computeRange(size: number, range?: R2Range): OctetStreamInit {\n if (!range) return { size };\n\n if (\"suffix\" in range) {\n const offset = Math.max(0, size - range.suffix);\n const length = size - offset;\n return { size, offset, length };\n }\n\n return { size, ...range };\n }\n}\n\n/**\n * Response for WebSocket upgrade requests.\n * Automatically sets status to 101 and attaches the client socket.\n */\nexport class WebSocketUpgrade extends WorkerResponse {\n constructor(client: WebSocket) {\n super();\n this.status = StatusCodes.SWITCHING_PROTOCOLS;\n this.webSocket = client;\n }\n}\n\n/**\n * Response for `HEAD` requests. Copy headers and status from a `GET` response\n * without the body.\n */\nexport class Head extends WorkerResponse {\n constructor(get: Response) {\n super();\n this.status = get.status;\n this.statusText = get.statusText;\n this.headers = new Headers(get.headers);\n }\n}\n\n/**\n * Response for `OPTIONS` requests.\n */\nexport class Options extends WorkerResponse {\n constructor(worker: Worker) {\n const allowed = Array.from(new Set([GET, HEAD, ...worker.getAllowedMethods()]));\n assertMethods(allowed);\n\n super();\n this.status = StatusCodes.NO_CONTENT;\n this.setHeader(HttpHeader.ALLOW, allowed);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"http-status-codes/build/es/status-codes\";\nimport { getReasonPhrase } from \"http-status-codes/build/es/utils-functions\";\n\nimport { CacheControl } from \"./constants/cache\";\nimport { HttpHeader } from \"./constants/headers\";\nimport { assertMethods } from \"./guards/methods\";\nimport { ErrorJson } from \"./interfaces/error\";\nimport { Worker } from \"./interfaces/worker\";\nimport { WS_VERSION } from \"./middleware/websocket/constants\";\nimport { JsonResponse } from \"./responses\";\n\n/**\n * Generic HTTP error response.\n * Sends a JSON body with status, error message, and details.\n */\nexport class HttpError extends JsonResponse {\n /**\n * @param worker The worker handling the request.\n * @param status HTTP status code.\n * @param details Optional detailed error message.\n */\n constructor(\n status: StatusCodes,\n protected readonly details?: string,\n ) {\n const json: ErrorJson = {\n status,\n error: getReasonPhrase(status),\n details: details ?? \"\",\n };\n super(json, CacheControl.DISABLE, status);\n }\n}\n\n/**\n * Creates a structured error response without exposing the error\n * details to the client. Links the sent response to the logged\n * error via a generated correlation ID.\n *\n * Status defaults to 500 Internal Server Error.\n */\nexport class LoggedHttpError extends HttpError {\n constructor(error: unknown, status: StatusCodes = StatusCodes.INTERNAL_SERVER_ERROR) {\n const uuid = crypto.randomUUID();\n console.error(uuid, error);\n super(status, uuid);\n }\n}\n\n/** 400 Bad Request error response. */\nexport class BadRequest extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.BAD_REQUEST, details);\n }\n}\n\n/** 401 Unauthorized error response. */\nexport class Unauthorized extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.UNAUTHORIZED, details);\n }\n}\n\n/** 403 Forbidden error response. */\nexport class Forbidden extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.FORBIDDEN, details);\n }\n}\n\n/** 404 Not Found error response. */\nexport class NotFound extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.NOT_FOUND, details);\n }\n}\n\n/** 405 Method Not Allowed error response. */\nexport class MethodNotAllowed extends HttpError {\n constructor(worker: Worker) {\n const methods = worker.getAllowedMethods();\n assertMethods(methods);\n\n super(StatusCodes.METHOD_NOT_ALLOWED, `${worker.request.method} method not allowed.`);\n this.setHeader(HttpHeader.ALLOW, methods);\n }\n}\n\n/** 412 Precondition Failed error response */\nexport class PreconditionFailed extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.PRECONDITION_FAILED, details);\n }\n}\n\n/** 426 Upgrade Required error response. */\nexport class UpgradeRequired extends HttpError {\n constructor() {\n super(StatusCodes.UPGRADE_REQUIRED);\n this.setHeader(HttpHeader.SEC_WEBSOCKET_VERSION, WS_VERSION);\n }\n}\n\n/** 500 Internal Server Error response. */\nexport class InternalServerError extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.INTERNAL_SERVER_ERROR, details);\n }\n}\n\n/** 501 Not Implemented error response. */\nexport class NotImplemented extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.NOT_IMPLEMENTED, details);\n }\n}\n\n/** 501 Method Not Implemented error response for unsupported HTTP methods. */\nexport class MethodNotImplemented extends NotImplemented {\n constructor(worker: Worker) {\n super(`${worker.request.method} method not implemented.`);\n }\n}\n\n/** 503 Service Unavailable error response. */\nexport class ServiceUnavailable extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.SERVICE_UNAVAILABLE, details);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/headers\";\nimport { getHeaderValues } from \"../../utils/headers\";\n\nimport { WS_UPGRADE, WS_VERSION, WS_WEBSOCKET } from \"./constants\";\n\n/**\n * Checks if the `Connection` header includes the WebSocket upgrade token.\n *\n * @param headers - The Headers object to inspect.\n * @returns `true` if a WebSocket upgrade is requested via `Connection` header, `false` otherwise.\n */\nexport function hasConnectionHeader(headers: Headers): boolean {\n return getHeaderValues(headers, HttpHeader.CONNECTION).some(\n (value) => value.toLowerCase() === WS_UPGRADE,\n );\n}\n\n/**\n * Checks if the `Upgrade` header requests a WebSocket upgrade.\n *\n * @param headers - The Headers object to inspect.\n * @returns `true` if the `Upgrade` header is set to `websocket`, `false` otherwise.\n */\nexport function hasUpgradeHeader(headers: Headers): boolean {\n return getHeaderValues(headers, HttpHeader.UPGRADE).some(\n (value) => value.toLowerCase() === WS_WEBSOCKET,\n );\n}\n\n/**\n * Determines whether the request includes the correct WebSocket version.\n *\n * @param headers - The Headers object to inspect.\n * @returns `true` if `Sec-WebSocket-Version` matches the expected version, `false` otherwise.\n */\nexport function hasWebSocketVersion(headers: Headers): boolean {\n return headers.get(HttpHeader.SEC_WEBSOCKET_VERSION)?.trim() === WS_VERSION;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { match } from \"path-to-regexp\";\n\nimport { GET } from \"../../constants/methods\";\nimport { BadRequest, UpgradeRequired } from \"../../errors\";\nimport { Middleware } from \"../../interfaces/middleware\";\nimport { Worker } from \"../../interfaces/worker\";\n\nimport { hasConnectionHeader, hasUpgradeHeader, hasWebSocketVersion } from \"./utils\";\n\n/**\n * Middleware for validating WebSocket upgrade requests.\n *\n * - Only applies to `GET` requests.\n * - Matches requests against a specific path using `path-to-regexp` patterns.\n * - Validates that the request contains required WebSocket headers:\n * - `Connection: Upgrade`\n * - `Upgrade: websocket`\n * - `Sec-WebSocket-Version` matches the expected version\n * - Returns an error response if any validation fails.\n * - Otherwise, passes control to the next middleware or origin handler.\n */\nexport class WebSocketHandler implements Middleware {\n /**\n * Creates a new WebSocketHandler for a specific path.\n *\n * @param path - The request path this handler should intercept for WebSocket upgrades.\n * Supports dynamic segments using `path-to-regexp` syntax.\n */\n constructor(private readonly path: string) {}\n\n /**\n * Handles an incoming request, validating WebSocket upgrade headers.\n *\n * @param worker - The Worker instance containing the request.\n * @param next - Function to invoke the next middleware.\n * @returns A Response object if the request fails WebSocket validation,\n * or the result of `next()` if the request is valid or does not match.\n */\n public handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n if (worker.request.method !== GET) {\n return next();\n }\n\n if (!this.isMatch(worker.request)) {\n return next();\n }\n\n const headers = worker.request.headers;\n if (!hasConnectionHeader(headers)) {\n return new BadRequest(\"Missing or invalid 'Connection' header\").response();\n }\n if (!hasUpgradeHeader(headers)) {\n return new BadRequest(\"Missing or invalid 'Upgrade' header\").response();\n }\n if (!hasWebSocketVersion(headers)) {\n return new UpgradeRequired().response();\n }\n\n return next();\n }\n\n /**\n * Checks if the request path matches the configured path for this handler.\n *\n * @param request - The incoming Request object.\n * @returns `true` if the request path matches, `false` otherwise.\n */\n private isMatch(request: Request): boolean {\n return match(this.path)(new URL(request.url).pathname) !== false;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Middleware } from \"../../interfaces/middleware\";\n\nimport { WebSocketHandler } from \"./handler\";\n\n/**\n * Returns a middleware that validates incoming WebSocket upgrade requests.\n *\n * - Only validates the upgrade request; it does **not** perform the actual WebSocket upgrade.\n * - Ensures the request:\n * - Uses the `GET` method.\n * - Matches the specified path, supporting `path-to-regexp` style patterns\n * (e.g., `/chat/:name`).\n * - Contains required WebSocket headers:\n * - `Connection: Upgrade`\n * - `Upgrade: websocket`\n * - `Sec-WebSocket-Version: 13`\n * - Returns an error response if validation fails, otherwise passes control to\n * the next middleware or origin handler.\n *\n * @param path - The URL path to intercept for WebSocket upgrades. Defaults to `/`.\n * Supports dynamic segments using `path-to-regexp` syntax.\n * @returns A {@link Middleware} instance that can be used in your middleware chain.\n *\n * @example\n * ```ts\n * app.use(websocket(\"/chat/:name\"));\n * ```\n */\nexport function websocket(path: string = \"/\"): Middleware {\n return new WebSocketHandler(path);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adonix.org/cloud-spark",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Ignite your Cloudflare Workers with a type-safe library for rapid development.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -10,6 +10,22 @@
|
|
|
10
10
|
".": {
|
|
11
11
|
"import": "./dist/index.js",
|
|
12
12
|
"types": "./dist/index.d.ts"
|
|
13
|
+
},
|
|
14
|
+
"./cache": {
|
|
15
|
+
"import": "./dist/cache.js",
|
|
16
|
+
"types": "./dist/cache.d.ts"
|
|
17
|
+
},
|
|
18
|
+
"./cors": {
|
|
19
|
+
"import": "./dist/cors.js",
|
|
20
|
+
"types": "./dist/cors.d.ts"
|
|
21
|
+
},
|
|
22
|
+
"./websocket": {
|
|
23
|
+
"import": "./dist/websocket.js",
|
|
24
|
+
"types": "./dist/websocket.d.ts"
|
|
25
|
+
},
|
|
26
|
+
"./sessions": {
|
|
27
|
+
"import": "./dist/sessions.js",
|
|
28
|
+
"types": "./dist/sessions.d.ts"
|
|
13
29
|
}
|
|
14
30
|
},
|
|
15
31
|
"files": [
|
|
@@ -41,8 +57,8 @@
|
|
|
41
57
|
},
|
|
42
58
|
"scripts": {
|
|
43
59
|
"types": "wrangler types --config wrangler.jsonc ./types/cloudflare.d.ts",
|
|
44
|
-
"prebuild": "npm run lint && mkdir -p ./types",
|
|
45
|
-
"build": "
|
|
60
|
+
"prebuild": "npm run lint && mkdir -p ./types && npm run types",
|
|
61
|
+
"build": "tsup",
|
|
46
62
|
"dev-types": "wrangler types --config wrangler.local.jsonc ./types/cloudflare.d.ts",
|
|
47
63
|
"dev": "npm run dev-types && wrangler dev --config wrangler.local.jsonc",
|
|
48
64
|
"dev-debug": "npm run dev-types && wrangler dev --config wrangler.local.jsonc --log-level debug",
|