@ublitzjs/core 0.1.1 → 1.0.1

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/types/index.d.ts DELETED
@@ -1,170 +0,0 @@
1
- import type {
2
- HttpRequest as uwsHttpRequest,
3
- TemplatedApp,
4
- HttpResponse as uwsHttpResponse,
5
- RecognizedString,
6
- us_socket_context_t,
7
- } from "uWebSockets.js";
8
- import { Buffer } from "node:buffer";
9
-
10
- import { EventEmitter } from "tseep";
11
- import type { DocumentedWSBehavior } from "./uws-types";
12
- /**
13
- * function to effortlessly mark response as aborted AND to attach an event emitter, so that you can easily scale the handler. If you don't need event emitter and only some res.aborted - set it by yourself (no overkill for the handler)
14
- * @param res
15
- */
16
- export function registerAbort(res: uwsHttpResponse): HttpResponse;
17
- /**
18
- * An extended version of uWS.App . It provides you with several features:
19
- * 1) plugin registration (just like in Fastify);
20
- * 2) "ready" function and _startPromises array (use it to make your code more asynchronous and safe)
21
- * 3) "route" function for more descriptive adn extensible way of registering handlers
22
- * 4) "onError" function (mainly used by @ublitzjs/router)
23
- */
24
- export interface Server extends TemplatedApp {
25
- /**
26
- * It is same as plugins in Fastify -> you register some routes in remove file
27
- * @param plugin
28
- * @returns itself for chaining methods
29
- */
30
- register(plugin: (server: this) => void): this;
31
- /** set global _errHandler (in fact it is used only by @ublitzjs/router) */
32
- onError(fn: (error: Error, res: HttpResponse, data: any) => any): this;
33
- _errHandler?(error: Error, res: HttpResponse, data: any): any;
34
- /**some undocumented property in uWS - get it here */
35
- addChildAppDescriptor(...any: any[]): this;
36
- /**a function, which awaits all promises inside _startPromises array and then clears it*/
37
- ready: () => Promise<any[]>;
38
- /**
39
- * simple array of promises. You can push several inside and await all of them using server.ready() method
40
- */
41
- _startPromises: Promise<any>[];
42
- /**
43
- * this function allows you to create new handlers but more dynamically than uWS. Best use case - development. By default, the first param you pass includes a method, path, and a controller. However you can configure it for additional properties, which can be consumed on startup by second param - plugins
44
- * @example
45
- * server.route<onlyHttpMethods, {deprecated:boolean}>({
46
- * method:"any",
47
- * path: "/",
48
- * controller(res){ res.end("hello") },
49
- * deprecated:true
50
- * },
51
- * [
52
- * (opts)=>{
53
- * if(opts.deprecated) console.error("DEPRECATION FOUND", opts.path)
54
- * }
55
- * ])
56
- */
57
- route<T extends HttpMethods, obj extends object = {}>(
58
- opts: routeFNOpts<T> & obj,
59
- plugins?: ((param: typeof opts, server: this) => void)[]
60
- ): this;
61
- get(pattern: RecognizedString, handler: HttpControllerFn): this;
62
- post(pattern: RecognizedString, handler: HttpControllerFn): this;
63
- options(pattern: RecognizedString, handler: HttpControllerFn): this;
64
- del(pattern: RecognizedString, handler: HttpControllerFn): this;
65
- patch(pattern: RecognizedString, handler: HttpControllerFn): this;
66
- put(pattern: RecognizedString, handler: HttpControllerFn): this;
67
- head(pattern: RecognizedString, handler: HttpControllerFn): this;
68
- connect(pattern: RecognizedString, handler: HttpControllerFn): this;
69
- trace(pattern: RecognizedString, handler: HttpControllerFn): this;
70
- any(pattern: RecognizedString, handler: HttpControllerFn): this;
71
- }
72
- export type routeFNOpts<T extends HttpMethods> = {
73
- method: T;
74
- path: RecognizedString;
75
- controller: T extends "ws" ? DocumentedWSBehavior<any> : HttpControllerFn;
76
- };
77
-
78
- /**
79
- * Utility for making closures. Exists for organizing code and caching values in non-global scope.
80
- * @param param
81
- * @returns what you passed
82
- */
83
- export var closure: <T>(param: () => T) => T;
84
- /**
85
- * little more typed response which has:
86
- * 1) "emitter", that comes from "tseep" package
87
- * 2) "aborted" flag
88
- * 3) "finished" flag
89
- * 4) "collect" function, which comes from original uWS (and isn't documented), but the purpose remains unknown
90
- */
91
- export interface HttpResponse<UserDataForWS extends object = {}>
92
- extends uwsHttpResponse {
93
- upgrade<UserData = UserDataForWS>(
94
- userData: UserData,
95
- secWebSocketKey: RecognizedString,
96
- secWebSocketProtocol: RecognizedString,
97
- secWebSocketExtensions: RecognizedString,
98
- context: us_socket_context_t
99
- ): void;
100
- /**
101
- * This method actually exists in original uWebSockets.js, but is undocumented. I'll put it here for your IDE to be happy
102
- */
103
- collect: (...any: any[]) => any;
104
- /**
105
- * An event emitter, which lets you subscribe several listeners to "abort" event OR your own events, defined with Symbol().
106
- */
107
- emitter: EventEmitter<{
108
- abort: () => void;
109
- [k: symbol]: (...any: any[]) => void;
110
- }>;
111
- /**
112
- * changes when res.onAborted fires.
113
- */
114
- aborted?: boolean;
115
- /**
116
- * You should set it manually when ending the response. Particularly useful if some error has fired and you are doubting whether res.aborted is a sufficient flag.
117
- */
118
- finished: boolean;
119
- }
120
- /**This HttpRequest is same as original uWS.HttpRequest, but getHeader method is typed for additional tips
121
- * @example
122
- * import {lowHeaders} from "ublitzjs"
123
- * // some handler later
124
- * req.getHeader<lowHeaders>("content-type")
125
- */
126
- export interface HttpRequest extends uwsHttpRequest {
127
- getHeader<T extends RecognizedString = RecognizedString>(a: T): string;
128
- }
129
-
130
- export type HttpControllerFn = (
131
- res: HttpResponse,
132
- req: HttpRequest
133
- ) => any | Promise<any>;
134
- /**
135
- * only http methods without "ws"
136
- */
137
- export type onlyHttpMethods =
138
- | "get"
139
- | "post"
140
- | "del"
141
- | "patch"
142
- | "put"
143
- | "head"
144
- | "trace"
145
- | "options"
146
- | "connect"
147
- | "any";
148
- /**
149
- * all httpMethods with "ws" method
150
- */
151
- export type HttpMethods = onlyHttpMethods | "ws"; //NOT A HTTP METHOD, but had to put it here
152
- type MergeObjects<T extends any[]> = T extends [infer First, ...infer Rest]
153
- ? First & MergeObjects<Rest extends any[] ? Rest : []>
154
- : {};
155
- /**
156
- * extends uWS.App() or uWS.SSLApp. See interface Server
157
- * @param app uWS.App()
158
- */
159
- export function extendApp<T extends object[]>(
160
- app: TemplatedApp,
161
- ...rest: T
162
- ): Server & MergeObjects<T>;
163
- /**
164
- * conversion to ArrayBuffer ('cause transferring strings to uWS is really slow)
165
- */
166
- export function toAB(data: Buffer | string): ArrayBuffer;
167
-
168
- export * from "./http-headers";
169
- export * from "./http-codes";
170
- export * from "./uws-types";
@@ -1,123 +0,0 @@
1
- import type {
2
- CompressOptions,
3
- RecognizedString,
4
- us_socket_context_t,
5
- WebSocket,
6
- } from "uWebSockets.js";
7
- import type { BaseHeaders, HttpRequest, HttpResponse } from "./index";
8
- /**
9
- * Thanks to "acarstoiu" github user for listing such methods here: "https://github.com/uNetworking/uWebSockets.js/issues/1165".
10
- */
11
- type WebSocketFragmentation = {
12
- /** Sends the first frame of a multi-frame message. More fragments are expected (possibly none), followed by a last fragment. Care must be taken so as not to interleave these fragments with whole messages (sent with WebSocket.send) or with other messages' fragments.
13
- *
14
- * Returns 1 for success, 2 for dropped due to backpressure limit, and 0 for built up backpressure that will drain over time. You can check backpressure before or after sending by calling getBufferedAmount().
15
- *
16
- * Make sure you properly understand the concept of backpressure. Check the backpressure example file.
17
- */
18
- sendFirstFragment(
19
- message: RecognizedString,
20
- isBinary?: boolean,
21
- compress?: boolean
22
- ): number;
23
- /** Sends a continuation frame of a multi-frame message. More fragments are expected (possibly none), followed by a last fragment. In terms of sending data, a call to this method must follow a call to WebSocket.sendFirstFragment.
24
- *
25
- * Returns 1 for success, 2 for dropped due to backpressure limit, and 0 for built up backpressure that will drain over time. You can check backpressure before or after sending by calling getBufferedAmount().
26
- *
27
- * Make sure you properly understand the concept of backpressure. Check the backpressure example file.
28
- */
29
- sendFragment(message: RecognizedString, compress?: boolean): number;
30
- /** Sends the last continuation frame of a multi-frame message. In terms of sending data, a call to this method must follow a call to WebSocket.sendFirstFragment or WebSocket.sendFragment.
31
- *
32
- * Returns 1 for success, 2 for dropped due to backpressure limit, and 0 for built up backpressure that will drain over time. You can check backpressure before or after sending by calling getBufferedAmount().
33
- *
34
- * Make sure you properly understand the concept of backpressure. Check the backpressure example file.
35
- */
36
- sendLastFragment(message: RecognizedString, compress?: boolean): number;
37
- };
38
- export type DocumentedWS<UserData> = WebSocket<UserData> &
39
- WebSocketFragmentation;
40
- export interface DocumentedWSBehavior<UserData extends object> {
41
- /** Maximum length of received message. If a client tries to send you a message larger than this, the connection is immediately closed. Defaults to 16 * 1024. */
42
- maxPayloadLength?: number;
43
- /** Whether or not we should automatically close the socket when a message is dropped due to backpressure. Defaults to false. */
44
- closeOnBackpressureLimit?: boolean;
45
- /** Maximum number of minutes a WebSocket may be connected before being closed by the server. 0 disables the feature. */
46
- maxLifetime?: number;
47
- /** Maximum amount of seconds that may pass without sending or getting a message. Connection is closed if this timeout passes. Resolution (granularity) for timeouts are typically 4 seconds, rounded to closest.
48
- * Disable by using 0. Defaults to 120.
49
- */
50
- idleTimeout?: number;
51
- /** What permessage-deflate compression to use. uWS.DISABLED, uWS.SHARED_COMPRESSOR or any of the uWS.DEDICATED_COMPRESSOR_xxxKB. Defaults to uWS.DISABLED. */
52
- compression?: CompressOptions;
53
- /** Maximum length of allowed backpressure per socket when publishing or sending messages. Slow receivers with too high backpressure will be skipped until they catch up or timeout. Defaults to 64 * 1024. */
54
- maxBackpressure?: number;
55
- /** Whether or not we should automatically send pings to uphold a stable connection given whatever idleTimeout. */
56
- sendPingsAutomatically?: boolean;
57
- /** Handler for new WebSocket connection. WebSocket is valid from open to close, no errors. */
58
- open?: (ws: DocumentedWS<UserData>) => void | Promise<void>;
59
- /** Handler for a WebSocket message. Messages are given as ArrayBuffer no matter if they are binary or not. Given ArrayBuffer is valid during the lifetime of this callback (until first await or return) and will be neutered. */
60
- message?: (
61
- ws: DocumentedWS<UserData>,
62
- message: ArrayBuffer,
63
- isBinary: boolean
64
- ) => void | Promise<void>;
65
- /** Handler for a dropped WebSocket message. Messages can be dropped due to specified backpressure settings. Messages are given as ArrayBuffer no matter if they are binary or not. Given ArrayBuffer is valid during the lifetime of this callback (until first await or return) and will be neutered. */
66
- dropped?: (
67
- ws: DocumentedWS<UserData>,
68
- message: ArrayBuffer,
69
- isBinary: boolean
70
- ) => void | Promise<void>;
71
- /** Handler for when WebSocket backpressure drains. Check ws.getBufferedAmount(). Use this to guide / drive your backpressure throttling. */
72
- drain?: (ws: DocumentedWS<UserData>) => void;
73
- /** Handler for close event, no matter if error, timeout or graceful close. You may not use WebSocket after this event. Do not send on this WebSocket from within here, it is closed. */
74
- close?: (
75
- ws: DocumentedWS<UserData>,
76
- code: number,
77
- message: ArrayBuffer
78
- ) => void;
79
- /** Handler for received ping control message. You do not need to handle this, pong messages are automatically sent as per the standard. */
80
- ping?: (ws: DocumentedWS<UserData>, message: ArrayBuffer) => void;
81
- /** Handler for received pong control message. */
82
- pong?: (ws: DocumentedWS<UserData>, message: ArrayBuffer) => void;
83
- /** Handler for subscription changes. */
84
- subscription?: (
85
- ws: DocumentedWS<UserData>,
86
- topic: ArrayBuffer,
87
- newCount: number,
88
- oldCount: number
89
- ) => void;
90
- /** Upgrade handler used to intercept HTTP upgrade requests and potentially upgrade to WebSocket.
91
- * See UpgradeAsync and UpgradeSync example files.
92
- */
93
- upgrade?: (
94
- res: HttpResponse<UserData>,
95
- req: HttpRequest,
96
- context: us_socket_context_t
97
- ) => void | Promise<void>;
98
- }
99
- export type DeclarativeResType = {
100
- writeHeader(key: string, value: string): DeclarativeResType;
101
- writeQueryValue(key: string): DeclarativeResType;
102
- writeHeaderValue(key: string): DeclarativeResType;
103
- /**
104
- * Write a chunk to the precompiled response
105
- */
106
- write(value: string): DeclarativeResType;
107
- writeParameterValue(key: string): DeclarativeResType;
108
- /**
109
- * Method to finalize forming a response.
110
- */
111
- end(value: string): any;
112
- writeBody(): DeclarativeResType;
113
- /**
114
- * additional method from ublitzjs
115
- */
116
- writeHeaders<Opts extends BaseHeaders>(headers: Opts): DeclarativeResType;
117
- };
118
- /**
119
- * Almost nothing different from uWS.DeclarativeResponse. The only modification - writeHeaders method (several methods, typescript intellisense)
120
- */
121
- export var DeclarativeResponse: {
122
- new (): DeclarativeResType;
123
- };