barejs 0.1.62 → 0.2.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.
@@ -0,0 +1,554 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+ import type { ServeOptions, ServerHandle } from './types';
4
+
5
+ export interface UwsRouteEntry {
6
+ method: string;
7
+ path: string;
8
+ paramNames: string[];
9
+ rawHandler: Function;
10
+ isPureStaticString: boolean;
11
+ isTrulyZeroArg: boolean;
12
+ }
13
+
14
+ const HTTP_STATUS_TEXT: Record<number, string> = {
15
+ 200: '200 OK',
16
+ 201: '201 Created',
17
+ 202: '202 Accepted',
18
+ 204: '204 No Content',
19
+ 206: '206 Partial Content',
20
+ 301: '301 Moved Permanently',
21
+ 302: '302 Found',
22
+ 304: '304 Not Modified',
23
+ 400: '400 Bad Request',
24
+ 401: '401 Unauthorized',
25
+ 403: '403 Forbidden',
26
+ 404: '404 Not Found',
27
+ 405: '405 Method Not Allowed',
28
+ 409: '409 Conflict',
29
+ 413: '413 Payload Too Large',
30
+ 415: '415 Unsupported Media Type',
31
+ 422: '422 Unprocessable Entity',
32
+ 429: '429 Too Many Requests',
33
+ 500: '500 Internal Server Error',
34
+ 502: '502 Bad Gateway',
35
+ 503: '503 Service Unavailable'
36
+ };
37
+
38
+ function statusLine(code: number): string {
39
+ return HTTP_STATUS_TEXT[code] || `${code}`;
40
+ }
41
+
42
+ export function tryLoadUws(): any | null {
43
+ if (typeof (globalThis as any).Bun !== 'undefined' || typeof (globalThis as any).Deno !== 'undefined') {
44
+ return null;
45
+ }
46
+ try {
47
+ return createRequire(join(process.cwd(), 'package.json'))('uWebSockets.js');
48
+ } catch {
49
+ try {
50
+ return createRequire(import.meta.url)('uWebSockets.js');
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ }
56
+
57
+ class UwsContext {
58
+ public res: any = null;
59
+ public params: Record<string, string> = {};
60
+ public store: Map<string, any> = new Map();
61
+ public _status: number = 200;
62
+ public _headers: Record<string, string> | undefined = undefined;
63
+ public _setCookies: string[] | undefined = undefined;
64
+ public _queryStr: string = '';
65
+ public _query: Record<string, any> | undefined = undefined;
66
+ public _url: string = '/';
67
+ public _method: string = 'GET';
68
+ public _reqHeaders: Record<string, string> | undefined = undefined;
69
+ public _req: Request | undefined = undefined;
70
+ public _peerIp: string | undefined = undefined;
71
+ public _responded: boolean = false;
72
+ public _inSync: boolean = false;
73
+ public _aborted: boolean = false;
74
+
75
+ public reset(): void {
76
+ this.res = null;
77
+ this.params = {};
78
+ if (this.store.size > 0) this.store.clear();
79
+ this._status = 200;
80
+ this._headers = undefined;
81
+ this._setCookies = undefined;
82
+ this._queryStr = '';
83
+ this._query = undefined;
84
+ this._url = '/';
85
+ this._method = 'GET';
86
+ this._reqHeaders = undefined;
87
+ this._req = undefined;
88
+ this._peerIp = undefined;
89
+ this._responded = false;
90
+ this._inSync = false;
91
+ this._aborted = false;
92
+ }
93
+
94
+ get req(): Request {
95
+ if (!this._req) {
96
+ const qs = this._queryStr ? `?${this._queryStr}` : '';
97
+ const host = this._reqHeaders?.host || 'localhost';
98
+ this._req = new Request(`http://${host}${this._url}${qs}`, {
99
+ method: this._method,
100
+ headers: this._reqHeaders
101
+ });
102
+ }
103
+ return this._req;
104
+ }
105
+
106
+ get query(): Record<string, any> {
107
+ if (!this._query) {
108
+ const q: Record<string, any> = {};
109
+ if (this._queryStr) {
110
+ const sp = new URLSearchParams(this._queryStr);
111
+ for (const [k, v] of sp) {
112
+ if (k in q) {
113
+ if (Array.isArray(q[k])) q[k].push(v);
114
+ else q[k] = [q[k], v];
115
+ } else {
116
+ q[k] = v;
117
+ }
118
+ }
119
+ }
120
+ this._query = q;
121
+ }
122
+ return this._query;
123
+ }
124
+
125
+ get ip(): string {
126
+ const xff = this._reqHeaders?.['x-forwarded-for'];
127
+ if (xff) {
128
+ const comma = xff.indexOf(',');
129
+ return (comma === -1 ? xff : xff.slice(0, comma)).trim();
130
+ }
131
+ return this._reqHeaders?.['x-real-ip'] || this._reqHeaders?.['cf-connecting-ip'] || this._peerIp || '127.0.0.1';
132
+ }
133
+
134
+ public status(code: number): this {
135
+ this._status = code;
136
+ return this;
137
+ }
138
+
139
+ public setHeader(key: string, val: string): this {
140
+ if (!this._headers) this._headers = {};
141
+ this._headers[key.toLowerCase()] = val;
142
+ return this;
143
+ }
144
+
145
+ public getHeader(key: string): string | undefined {
146
+ return this._reqHeaders?.[key.toLowerCase()];
147
+ }
148
+
149
+ public header(key: string): string | undefined {
150
+ return this.getHeader(key);
151
+ }
152
+
153
+ public set(key: string, val: any): this {
154
+ this.store.set(key, val);
155
+ return this;
156
+ }
157
+
158
+ public get<T = any>(key: string): T | undefined {
159
+ return this.store.get(key);
160
+ }
161
+
162
+ private _flushJson(res: any, payload: string): void {
163
+ if (this._status !== 200) res.writeStatus(statusLine(this._status));
164
+ res.writeHeader('content-type', 'application/json');
165
+ if (this._headers) {
166
+ for (const k in this._headers) {
167
+ if (k !== 'content-type') res.writeHeader(k, this._headers[k]);
168
+ }
169
+ }
170
+ if (this._setCookies) {
171
+ for (let i = 0; i < this._setCookies.length; i++) {
172
+ res.writeHeader('set-cookie', this._setCookies[i]);
173
+ }
174
+ }
175
+ res.end(payload);
176
+ }
177
+
178
+ public json(data: any): undefined {
179
+ const res = this.res;
180
+ if (!res || this._responded || this._aborted) return undefined;
181
+ this._responded = true;
182
+ const payload = JSON.stringify(data);
183
+ if (this._inSync) {
184
+ this._flushJson(res, payload);
185
+ } else {
186
+ res.cork(() => this._flushJson(res, payload));
187
+ }
188
+ return undefined;
189
+ }
190
+
191
+ private _flushText(res: any, data: string, code: number): void {
192
+ if (code !== 200) res.writeStatus(statusLine(code));
193
+ if (this._headers) {
194
+ for (const k in this._headers) res.writeHeader(k, this._headers[k]);
195
+ }
196
+ if (this._setCookies) {
197
+ for (let i = 0; i < this._setCookies.length; i++) {
198
+ res.writeHeader('set-cookie', this._setCookies[i]);
199
+ }
200
+ }
201
+ res.end(data);
202
+ }
203
+
204
+ public text(data: string, status?: number): undefined {
205
+ const res = this.res;
206
+ if (!res || this._responded || this._aborted) return undefined;
207
+ this._responded = true;
208
+ const code = status ?? this._status;
209
+ if (this._inSync) {
210
+ this._flushText(res, data, code);
211
+ } else {
212
+ res.cork(() => this._flushText(res, data, code));
213
+ }
214
+ return undefined;
215
+ }
216
+
217
+ public html(data: string, status?: number): undefined {
218
+ this.setHeader('content-type', 'text/html; charset=utf-8');
219
+ return this.text(data, status);
220
+ }
221
+
222
+ public redirect(url: string, status: number = 302): undefined {
223
+ this.setHeader('location', url);
224
+ return this.text('', status);
225
+ }
226
+ }
227
+
228
+ function writeWebResponseToUws(res: any, webRes: Response): void {
229
+ const status = webRes.status;
230
+ if (status !== 200) res.writeStatus(statusLine(status));
231
+ webRes.headers.forEach((value, key) => {
232
+ res.writeHeader(key, value);
233
+ });
234
+ const anyHeaders = webRes.headers as any;
235
+ if (typeof anyHeaders.getSetCookie === 'function') {
236
+ const cookies: string[] = anyHeaders.getSetCookie();
237
+ for (let i = 0; i < cookies.length; i++) {
238
+ res.writeHeader('set-cookie', cookies[i]);
239
+ }
240
+ }
241
+ if (!webRes.body) {
242
+ res.end();
243
+ return;
244
+ }
245
+ webRes.arrayBuffer().then(
246
+ (buf) => {
247
+ res.cork(() => {
248
+ res.end(Buffer.from(buf));
249
+ });
250
+ },
251
+ () => {
252
+ try { res.close(); } catch {}
253
+ }
254
+ );
255
+ }
256
+
257
+ function writeOutToUws(res: any, ctx: UwsContext | null, out: any): void {
258
+ if (ctx?._responded) return;
259
+ if (out instanceof Response) {
260
+ writeWebResponseToUws(res, out);
261
+ return;
262
+ }
263
+ if (typeof out === 'string') {
264
+ if (ctx) {
265
+ ctx.text(out);
266
+ } else {
267
+ res.end(out);
268
+ }
269
+ return;
270
+ }
271
+ if (ctx) {
272
+ ctx.json(out ?? null);
273
+ } else {
274
+ res.writeHeader('content-type', 'application/json');
275
+ res.end(JSON.stringify(out ?? null));
276
+ }
277
+ }
278
+
279
+ function writeUwsError(res: any, err: any): void {
280
+ const code = err?.status >= 400 && err?.status < 500 ? err.status : 500;
281
+ res.writeStatus(statusLine(code));
282
+ res.writeHeader('content-type', 'application/json');
283
+ const msg =
284
+ code === 500
285
+ ? (process.env.NODE_ENV === 'development' ? (err?.message || 'Internal Server Error') : 'Internal Server Error')
286
+ : (err?.message || 'Bad Request');
287
+ res.end(JSON.stringify({ status: code, message: msg }));
288
+ }
289
+
290
+ const UWS_METHOD_MAP: Record<string, string> = {
291
+ GET: 'get',
292
+ HEAD: 'head',
293
+ DELETE: 'del',
294
+ OPTIONS: 'options'
295
+ };
296
+
297
+ export function serveUws(
298
+ opts: ServeOptions & { uwsRoutes?: UwsRouteEntry[] },
299
+ uwsMod: any
300
+ ): ServerHandle {
301
+ const app = uwsMod.App();
302
+ const isProd = process.env.NODE_ENV === 'production';
303
+ const pool: UwsContext[] = [];
304
+ const maxPool = 4096;
305
+
306
+ // Tier 1: Direct uWS fast-path for bodyless methods (GET, HEAD, DELETE, OPTIONS)
307
+ if (opts.uwsRoutes) {
308
+ for (const r of opts.uwsRoutes) {
309
+ const uwsMethod = UWS_METHOD_MAP[r.method];
310
+ if (!uwsMethod) continue;
311
+
312
+ if (isProd && r.isPureStaticString) {
313
+ const buf = Buffer.from(r.rawHandler());
314
+ app[uwsMethod](r.path, (res: any) => {
315
+ res.end(buf);
316
+ });
317
+ continue;
318
+ }
319
+
320
+ if (isProd && r.isTrulyZeroArg) {
321
+ const fn = r.rawHandler;
322
+ app[uwsMethod](r.path, (res: any) => {
323
+ try {
324
+ const out = fn();
325
+ if (out && typeof out.then === 'function') {
326
+ let aborted = false;
327
+ res.onAborted(() => { aborted = true; });
328
+ out.then(
329
+ (v: any) => {
330
+ if (!aborted) res.cork(() => writeOutToUws(res, null, v));
331
+ },
332
+ (e: any) => {
333
+ if (!aborted) res.cork(() => writeUwsError(res, e));
334
+ }
335
+ );
336
+ return;
337
+ }
338
+ writeOutToUws(res, null, out);
339
+ } catch (e) {
340
+ writeUwsError(res, e);
341
+ }
342
+ });
343
+ continue;
344
+ }
345
+
346
+ const fn = r.rawHandler;
347
+ const paramNames = r.paramNames;
348
+ const pLen = paramNames.length;
349
+ const fnSrc = fn.toString();
350
+ const needsHeaders = /\b(?:getHeader|header|ip|req)\b/.test(fnSrc);
351
+ const needsQuery = /\b(?:query|req)\b/.test(fnSrc);
352
+
353
+ app[uwsMethod](r.path, (res: any, req: any) => {
354
+ const ctx = pool.length > 0 ? pool.pop()! : new UwsContext();
355
+ ctx.res = res;
356
+ if (pLen > 0) {
357
+ const p: Record<string, string> = {};
358
+ for (let i = 0; i < pLen; i++) {
359
+ p[paramNames[i]] = req.getParameter(i);
360
+ }
361
+ ctx.params = p;
362
+ }
363
+ if (needsQuery) {
364
+ ctx._queryStr = req.getQuery();
365
+ ctx._url = req.getUrl();
366
+ ctx._method = r.method;
367
+ }
368
+ if (needsHeaders) {
369
+ const h: Record<string, string> = {};
370
+ req.forEach((k: string, v: string) => {
371
+ h[k] = v;
372
+ });
373
+ ctx._reqHeaders = h;
374
+ ctx._url = req.getUrl();
375
+ ctx._method = r.method;
376
+ }
377
+
378
+ ctx._inSync = true;
379
+ try {
380
+ const out = fn(ctx);
381
+ ctx._inSync = false;
382
+ if (out && typeof out.then === 'function') {
383
+ res.onAborted(() => { ctx._aborted = true; });
384
+ out.then(
385
+ (v: any) => {
386
+ if (!ctx._aborted && !ctx._responded) {
387
+ res.cork(() => writeOutToUws(res, ctx, v));
388
+ }
389
+ ctx.reset();
390
+ if (pool.length < maxPool) pool.push(ctx);
391
+ },
392
+ (e: any) => {
393
+ if (!ctx._aborted && !ctx._responded) {
394
+ res.cork(() => writeUwsError(res, e));
395
+ }
396
+ ctx.reset();
397
+ if (pool.length < maxPool) pool.push(ctx);
398
+ }
399
+ );
400
+ return;
401
+ }
402
+ if (!ctx._responded) writeOutToUws(res, ctx, out);
403
+ ctx.reset();
404
+ if (pool.length < maxPool) pool.push(ctx);
405
+ } catch (e) {
406
+ ctx._inSync = false;
407
+ if (!ctx._responded) writeUwsError(res, e);
408
+ ctx.reset();
409
+ if (pool.length < maxPool) pool.push(ctx);
410
+ }
411
+ });
412
+ }
413
+ }
414
+
415
+ // Tier 2: Full Web-Standard Request/Response fallback for POST/PUT/PATCH, middlewares, 404, etc.
416
+ app.any('/*', (res: any, req: any) => {
417
+ let aborted = false;
418
+ res.onAborted(() => { aborted = true; });
419
+
420
+ const method = req.getMethod().toUpperCase();
421
+ const urlPath = req.getUrl();
422
+ const queryStr = req.getQuery();
423
+ const headers = new Headers();
424
+ let host = 'localhost';
425
+ req.forEach((k: string, v: string) => {
426
+ if (k === 'host') host = v;
427
+ headers.append(k, v);
428
+ });
429
+ const fullUrl = `http://${host}${urlPath}${queryStr ? `?${queryStr}` : ''}`;
430
+ let peerIp = '127.0.0.1';
431
+ try {
432
+ peerIp = Buffer.from(res.getRemoteAddressAsText()).toString() || '127.0.0.1';
433
+ } catch {}
434
+
435
+ const dispatchFetch = (bodyBuf?: Buffer) => {
436
+ if (aborted) return;
437
+ const webReq = new Request(fullUrl, {
438
+ method,
439
+ headers,
440
+ body: bodyBuf && bodyBuf.length > 0 ? (bodyBuf as any) : undefined
441
+ });
442
+ Promise.resolve(opts.fetch(webReq, peerIp)).then(
443
+ (webRes) => {
444
+ if (aborted) return;
445
+ if (!webRes.body) {
446
+ res.cork(() => {
447
+ writeWebResponseToUws(res, webRes);
448
+ });
449
+ return;
450
+ }
451
+ webRes.arrayBuffer().then(
452
+ (buf) => {
453
+ if (aborted) return;
454
+ res.cork(() => {
455
+ const status = webRes.status;
456
+ if (status !== 200) res.writeStatus(statusLine(status));
457
+ webRes.headers.forEach((value, key) => {
458
+ res.writeHeader(key, value);
459
+ });
460
+ const anyHeaders = webRes.headers as any;
461
+ if (typeof anyHeaders.getSetCookie === 'function') {
462
+ const cookies: string[] = anyHeaders.getSetCookie();
463
+ for (let i = 0; i < cookies.length; i++) {
464
+ res.writeHeader('set-cookie', cookies[i]);
465
+ }
466
+ }
467
+ res.end(Buffer.from(buf));
468
+ });
469
+ },
470
+ () => {
471
+ if (!aborted) try { res.close(); } catch {}
472
+ }
473
+ );
474
+ },
475
+ (e) => {
476
+ if (!aborted) res.cork(() => writeUwsError(res, e));
477
+ }
478
+ );
479
+ };
480
+
481
+ if (method === 'GET' || method === 'HEAD') {
482
+ dispatchFetch();
483
+ return;
484
+ }
485
+
486
+ const chunks: Buffer[] = [];
487
+ let totalLen = 0;
488
+ const maxBody = opts.maxRequestBodySize || 10 * 1024 * 1024;
489
+ let rejected = false;
490
+
491
+ res.onData((ab: ArrayBuffer, isLast: boolean) => {
492
+ if (aborted || rejected) return;
493
+ const chunk = Buffer.from(ab);
494
+ totalLen += chunk.length;
495
+ if (totalLen > maxBody) {
496
+ rejected = true;
497
+ res.cork(() => {
498
+ res.writeStatus('413 Payload Too Large');
499
+ res.writeHeader('content-type', 'application/json');
500
+ res.end(JSON.stringify({ status: 413, message: 'Payload Too Large' }));
501
+ });
502
+ return;
503
+ }
504
+ if (chunk.length > 0) chunks.push(chunk);
505
+ if (isLast) {
506
+ dispatchFetch(chunks.length === 0 ? undefined : chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
507
+ }
508
+ });
509
+ });
510
+
511
+ let listenSocket: any = null;
512
+ let boundPort = opts.port;
513
+
514
+ const ready = new Promise<void>((resolve, reject) => {
515
+ app.listen(opts.hostname, opts.port, (token: any) => {
516
+ if (!token) {
517
+ reject(new Error(`[BareJS] uWebSockets.js failed to listen on ${opts.hostname}:${opts.port}`));
518
+ return;
519
+ }
520
+ listenSocket = token;
521
+ try {
522
+ boundPort = uwsMod.us_socket_local_port(token) || opts.port;
523
+ } catch {
524
+ boundPort = opts.port;
525
+ }
526
+ resolve();
527
+ });
528
+ });
529
+
530
+ const stopFn = () => {
531
+ if (listenSocket) {
532
+ try {
533
+ uwsMod.us_listen_socket_close(listenSocket);
534
+ } catch {}
535
+ listenSocket = null;
536
+ }
537
+ };
538
+
539
+ Object.defineProperty(app, 'port', {
540
+ get: () => boundPort,
541
+ configurable: true
542
+ });
543
+ app.stop = stopFn;
544
+ app.ready = ready;
545
+
546
+ return {
547
+ get port() {
548
+ return boundPort;
549
+ },
550
+ stop: stopFn,
551
+ raw: app,
552
+ ready
553
+ } as ServerHandle & { ready: Promise<void> };
554
+ }