@miqro/core 5.0.16 → 5.0.18

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/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ParserInterface, Schema } from "@miqro/parser";
1
+ import { ParserInterface, Schema, InferSchema } from "@miqro/parser";
2
2
  import { SerializeOptions as CookieSerializeOptions, parse, serialize } from "cookie";
3
3
  import { randomUUID } from "crypto";
4
4
  import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
@@ -257,21 +257,25 @@ export const RouteOptionsSchema: Schema<RouteOptions> = {
257
257
  }
258
258
  };
259
259
 
260
- export interface RouteOptions {
260
+ export interface RouteOptions<
261
+ TBody extends SchemaProperties | string | boolean | undefined = undefined,
262
+ TParams extends SchemaProperties | string | boolean | undefined = undefined,
263
+ TQuery extends SchemaProperties | string | boolean | undefined = undefined
264
+ > {
261
265
  name?: string;
262
266
  identifier?: string;
263
267
  apiName?: string;
264
268
  description?: string;
265
269
  policy?: GroupPolicy;
266
270
  request?: {
267
- headers?: string | SchemaProperties[] | SchemaProperties;
268
- headersMode?: ParserMode;
269
- query?: boolean | string | SchemaProperties[] | SchemaProperties;
271
+ body?: TBody;
272
+ params?: TParams;
273
+ query?: TQuery;
274
+ bodyMode?: ParserMode;
270
275
  queryMode?: ParserMode;
271
- params?: string | SchemaProperties | boolean | SchemaProperties[];
272
276
  paramsMode?: ParserMode;
273
- body?: string | SchemaProperties | boolean | SchemaProperties[];
274
- bodyMode?: ParserMode;
277
+ headers?: string | SchemaProperties[] | SchemaProperties;
278
+ headersMode?: ParserMode;
275
279
  };
276
280
  response?: {
277
281
  status?: number | number[];
@@ -312,12 +316,43 @@ export const RouterHandlerOptionsSchema: Schema<RouterHandlerOptions> = {
312
316
  }
313
317
  };
314
318
 
315
- export interface RouterHandlerOptions extends RouteOptions {
319
+ export interface RouterHandlerOptions<
320
+ TBody extends SchemaProperties | string | boolean | undefined = undefined,
321
+ TParams extends SchemaProperties | string | boolean | undefined = undefined,
322
+ TQuery extends SchemaProperties | string | boolean | undefined = undefined
323
+ > extends RouteOptions<TBody, TParams, TQuery> {
316
324
  parser?: ParserInterface;
317
325
  middleware?: Handler | Handler[];
318
326
  session?: SessionHandlerOptions | Handler;
319
327
  }
320
328
 
329
+ /**
330
+ * Infer the TypeScript type produced by a request-part schema (body / params / query).
331
+ * - string shorthand → `InferSchema<T>`
332
+ * - plain properties object `{ name: "string", age: "integer" }` → object with inferred fields
333
+ * - `boolean | undefined` → `any` (pass-through, no type enforcement)
334
+ */
335
+ export type InferRequestPart<T> =
336
+ [T] extends [boolean | undefined | null] ? any :
337
+ [T] extends [string] ? InferSchema<T & string> :
338
+ T extends SchemaProperties ? InferSchema<{ type: "object"; properties: T }> :
339
+ any;
340
+
341
+ /**
342
+ * A `Request` narrowed to the typed `body`, `params`, and `query` shapes inferred
343
+ * from the schemas declared on a route's `request` option.
344
+ */
345
+ export type TypedRequest<
346
+ TBody = any,
347
+ TParams = any,
348
+ TQuery = any,
349
+ BaseRequest extends Request = Request
350
+ > = Omit<BaseRequest, "body" | "params" | "query"> & {
351
+ body?: TBody; // optional to stay compatible with Request — ParseRequest validates it at runtime
352
+ params: TParams;
353
+ query: TQuery;
354
+ };
355
+
321
356
  export const HandlerWithOptionsSchema: Schema<HandlerWithOptions> = {
322
357
  type: "object",
323
358
  properties: {
@@ -326,8 +361,16 @@ export const HandlerWithOptionsSchema: Schema<HandlerWithOptions> = {
326
361
  }
327
362
  };
328
363
 
329
- export interface HandlerWithOptions extends RouterHandlerOptions {
330
- handler: Handler | Array<Handler>;
364
+ export interface HandlerWithOptions<
365
+ TBody extends SchemaProperties | string | boolean | undefined = undefined,
366
+ TParams extends SchemaProperties | string | boolean | undefined = undefined,
367
+ TQuery extends SchemaProperties | string | boolean | undefined = undefined,
368
+ BaseRequest extends Request = Request
369
+ > extends RouterHandlerOptions<TBody, TParams, TQuery> {
370
+ handler:
371
+ | ((req: TypedRequest<InferRequestPart<TBody>, InferRequestPart<TParams>, InferRequestPart<TQuery>, BaseRequest>, res: Response) => Promise<boolean | void | HandlerResponse>)
372
+ | ((req: TypedRequest<InferRequestPart<TBody>, InferRequestPart<TParams>, InferRequestPart<TQuery>, BaseRequest>, res: Response) => boolean | void | HandlerResponse)
373
+ | Array<Handler>;
331
374
  }
332
375
 
333
376
  export interface RouterOptions {
@@ -363,17 +406,63 @@ export function isMinimalRouter(obj: any) {
363
406
  *};
364
407
  *export default route;
365
408
  * ```
409
+ *
410
+ * Use the type parameters to get typed `req.body`, `req.params`, and `req.query`
411
+ * in the handler. Use `defineRoute()` for automatic schema inference.
366
412
  */
367
- export interface APIRoute extends RouterHandlerOptions {
413
+ export interface APIRoute<
414
+ BaseRequest extends Request = Request,
415
+ TBody extends SchemaProperties | string | boolean | undefined = undefined,
416
+ TParams extends SchemaProperties | string | boolean | undefined = undefined,
417
+ TQuery extends SchemaProperties | string | boolean | undefined = undefined,
418
+ > extends Omit<RouterHandlerOptions, "request"> {
368
419
  postFolder?: boolean;
369
420
  basePath?: string;
370
421
  method?: Method[] | Method | "use" | "USE";
371
422
  path?: string[] | string | null;
372
423
  ignore?: boolean;
373
- handler: Handler | Array<Handler> | MinimalRouter;
424
+ request?: {
425
+ body?: TBody;
426
+ params?: TParams;
427
+ query?: TQuery;
428
+ bodyMode?: ParserMode;
429
+ queryMode?: ParserMode;
430
+ paramsMode?: ParserMode;
431
+ headers?: string | SchemaProperties[] | SchemaProperties;
432
+ headersMode?: ParserMode;
433
+ };
434
+ handler:
435
+ | ((req: TypedRequest<InferRequestPart<TBody>, InferRequestPart<TParams>, InferRequestPart<TQuery>, BaseRequest>, res: Response) => Promise<boolean | void | HandlerResponse>)
436
+ | ((req: TypedRequest<InferRequestPart<TBody>, InferRequestPart<TParams>, InferRequestPart<TQuery>, BaseRequest>, res: Response) => boolean | void | HandlerResponse)
437
+ | Array<Handler>
438
+ | MinimalRouter;
374
439
  init?: (route: APIRoute) => Promise<void>;
375
440
  }
376
441
 
442
+ /**
443
+ * Type-safe factory for file-based API routes (`export default`).
444
+ *
445
+ * Wrap your route object so TypeScript automatically infers `req.body`,
446
+ * `req.params`, and `req.query` from the schemas in `request`.
447
+ *
448
+ * @example
449
+ * export default defineRoute({
450
+ * request: { body: { name: "string", age: "integer" } },
451
+ * handler: async (req) => {
452
+ * req.body.name; // string
453
+ * req.body.age; // number
454
+ * }
455
+ * });
456
+ */
457
+ export function defineRoute<
458
+ BaseRequest extends Request = Request,
459
+ const TBody extends SchemaProperties | string | boolean | undefined = undefined,
460
+ const TParams extends SchemaProperties | string | boolean | undefined = undefined,
461
+ const TQuery extends SchemaProperties | string | boolean | undefined = undefined,
462
+ >(route: APIRoute<BaseRequest, TBody, TParams, TQuery>): APIRoute<BaseRequest, TBody, TParams, TQuery> {
463
+ return route as unknown as APIRoute<BaseRequest, TBody, TParams, TQuery>;
464
+ }
465
+
377
466
  export interface APIRouterOptions {
378
467
  dirname: string;
379
468
  apiName?: string;
@@ -574,7 +663,7 @@ export class Response<Request extends IncomingMessage = IncomingMessage> extends
574
663
  return this.asyncEnd({
575
664
  status: status !== undefined ? status : 200,
576
665
  headers: {
577
- ['Content-Type']: 'plain/text; charset=utf-8',
666
+ ['Content-Type']: 'text/plain; charset=utf-8',
578
667
  ...headers
579
668
  },
580
669
  body: text
@@ -590,9 +679,9 @@ export class Response<Request extends IncomingMessage = IncomingMessage> extends
590
679
  const newValue = current ? `${current}, ${nV}` : nV;
591
680
  return this.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
592
681
  }
593
- async asyncClose(): Promise<void> {
682
+ async asyncClose(status: number = 400): Promise<void> {
594
683
  return this.asyncEnd({
595
- status: 400,
684
+ status,
596
685
  headers: {
597
686
  connection: "close"
598
687
  }
package/src/websocket.ts CHANGED
@@ -26,14 +26,7 @@ export class WebSocketServer implements ConnectionUpgrader {
26
26
  const clients = this.clients.values();
27
27
  for (const client of clients) {
28
28
  if (fromUUID === undefined || client.uuid !== fromUUID) {
29
- tR.push(new Promise<void>(async (resolve, reject) => {
30
- try {
31
- await this.writeTo(client.uuid, data);
32
- resolve();
33
- } catch (e) {
34
- reject(e);
35
- }
36
- }));
29
+ tR.push(this.writeTo(client.uuid, data));
37
30
  }
38
31
  }
39
32
  await Promise.allSettled(tR);
@@ -46,7 +39,7 @@ export class WebSocketServer implements ConnectionUpgrader {
46
39
  }
47
40
  return new Promise<void>((resolve, reject) => {
48
41
  try {
49
- client.req.socket.write(createFrame(data), (err?: Error) => {
42
+ client.req.socket.write(createFrame(data), (err?: Error | null) => {
50
43
  if (err) {
51
44
  try {
52
45
  client.req.socket.destroy(err);
@@ -123,7 +116,13 @@ export class WebSocketServer implements ConnectionUpgrader {
123
116
 
124
117
  socket.on("data", (data: Buffer) => {
125
118
  const frame = parseFrame(data);
126
- if (frame !== null) {
119
+ if (frame === PING) {
120
+ try {
121
+ socket.write(Buffer.from([0x8A, 0x00])); // pong frame
122
+ } catch (e) {
123
+ req.logger.error(e);
124
+ }
125
+ } else if (frame !== null) {
127
126
  if (!this.options.onMessage) {
128
127
  socket.end();
129
128
  socket.destroy();
@@ -134,6 +133,15 @@ export class WebSocketServer implements ConnectionUpgrader {
134
133
  req.logger.error(e);
135
134
  }
136
135
  }
136
+ } else {
137
+ // send close frame back and clean up
138
+ try {
139
+ socket.write(Buffer.from([0x88, 0x00]));
140
+ } catch (e) {
141
+ req.logger.error(e);
142
+ }
143
+ socket.end();
144
+ socket.destroy();
137
145
  }
138
146
  });
139
147
 
@@ -332,8 +340,8 @@ export class ClusterWebSocketServer extends WebSocketServer {
332
340
  * Private
333
341
  */
334
342
 
335
-
336
- const OPCODES = { text: 0x01, close: 0x08 };
343
+ const PING = Symbol()
344
+ const OPCODES = { text: 0x01, close: 0x08, ping: 0x09, pong: 0x0A };
337
345
  const GUID: string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
338
346
  //Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
339
347
  function createUpgradeHeaders(acceptKey: string, extraHeaders?: {
@@ -354,8 +362,10 @@ function parseFrame(buffer: Buffer) {
354
362
  if (opCode === OPCODES.close) {
355
363
  //this.emit('close');
356
364
  return null;
365
+ } else if (opCode === OPCODES.ping) {
366
+ return PING;
357
367
  } else if (opCode !== OPCODES.text) {
358
- return;
368
+ return null;
359
369
  }
360
370
 
361
371
  const secondByte = buffer.readUInt8(1); // start with a payload length
@@ -364,8 +374,10 @@ function parseFrame(buffer: Buffer) {
364
374
  let payloadLength = secondByte & 0b01111111; // get last 7 bits of a second byte
365
375
 
366
376
  if (payloadLength === 126) {
377
+ payloadLength = buffer.readUInt16BE(offset); // read real 16-bit length
367
378
  offset += 2;
368
379
  } else if (payloadLength === 127) {
380
+ payloadLength = Number(buffer.readBigUInt64BE(offset)); // read real 64-bit length
369
381
  offset += 8;
370
382
  }
371
383
 
@@ -374,12 +386,12 @@ function parseFrame(buffer: Buffer) {
374
386
  if (isMasked) {
375
387
  const maskingKey = buffer.readUInt32BE(offset); // read 4-byte mask
376
388
  offset += 4;
377
- const payload = buffer.subarray(offset);
389
+ const payload = buffer.subarray(offset, offset + payloadLength);
378
390
  const result = unmask(payload, maskingKey);
379
391
  return result.toString('utf-8');
380
392
  }
381
393
 
382
- return buffer.subarray(offset).toString('utf-8');
394
+ return buffer.subarray(offset, offset + payloadLength).toString('utf-8');
383
395
  }
384
396
 
385
397
  function unmask(payload: Buffer, maskingKey: number) {
@@ -419,7 +431,7 @@ function createFrame(payload: string) {
419
431
 
420
432
  if (payloadLength === 126) { // write actual payload length as a 16-bit unsigned integer
421
433
  buffer.writeUInt16BE(payloadByteLength, 2);
422
- } else if (payloadByteLength === 127) { // write actual payload length as a 64-bit unsigned integer
434
+ } else if (payloadLength === 127) { // write actual payload length as a 64-bit unsigned integer
423
435
  buffer.writeBigUInt64BE(BigInt(payloadByteLength), 2);
424
436
  }
425
437