@nmtjs/http-transport 0.1.7 → 0.15.0-beta.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/LICENSE.md CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2024 Denis Ilchyshyn
1
+ Copyright (c) 2025 Denys Ilchyshyn
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
 
package/README.md CHANGED
@@ -1 +1,9 @@
1
- ## HTTP transport for [Neemata](https://github.com/neematajs/neemata)
1
+ # NeemataJS - RPC application server for real-time applications (proof of concept)
2
+
3
+ ### Built with following in mind:
4
+ - transport-agnostic (like WebSockets, WebTransport, .etc)
5
+ - format-agnostic (like JSON, MessagePack, BSON, .etc)
6
+ - binary data streaming and event subscriptions
7
+ - contract-based API
8
+ - end-to-end type safety
9
+ - CPU-intensive task execution on separate workers
package/package.json CHANGED
@@ -2,37 +2,57 @@
2
2
  "name": "@nmtjs/http-transport",
3
3
  "type": "module",
4
4
  "exports": {
5
- ".": {
6
- "default": "./dist/index.js",
7
- "types": "./index.ts"
8
- }
5
+ ".": "./dist/index.js",
6
+ "./bun": "./dist/runtimes/bun.js",
7
+ "./deno": "./dist/runtimes/deno.js",
8
+ "./node": "./dist/runtimes/node.js"
9
9
  },
10
- "dependencies": {
11
- "uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.49.0"
10
+ "devDependencies": {
11
+ "uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.56.0",
12
+ "@nmtjs/common": "0.15.0-beta.1",
13
+ "@nmtjs/gateway": "0.15.0-beta.1",
14
+ "@nmtjs/protocol": "0.15.0-beta.1",
15
+ "@nmtjs/client": "0.15.0-beta.1"
12
16
  },
13
17
  "peerDependencies": {
14
- "@nmtjs/application": "^0.4.2s",
15
- "@nmtjs/common": "^0.4.2s"
18
+ "@types/bun": "^1.3.0",
19
+ "@types/deno": "^2.3.0",
20
+ "@types/node": "^24",
21
+ "uWebSockets.js": "^20.56.0",
22
+ "@nmtjs/common": "0.15.0-beta.1",
23
+ "@nmtjs/core": "0.15.0-beta.1",
24
+ "@nmtjs/gateway": "0.15.0-beta.1",
25
+ "@nmtjs/protocol": "0.15.0-beta.1"
16
26
  },
17
- "devDependencies": {
18
- "@nmtjs/application": "^0.4.2s",
19
- "@nmtjs/common": "^0.4.2s",
20
- "@types/node": "^18.0.0"
27
+ "peerDependenciesMeta": {
28
+ "@types/bun": {
29
+ "optional": true
30
+ },
31
+ "@types/deno": {
32
+ "optional": true
33
+ },
34
+ "@types/node": {
35
+ "optional": true
36
+ },
37
+ "uWebSockets.js": {
38
+ "optional": true
39
+ }
21
40
  },
22
41
  "engines": {
23
- "node": ">=18.9.0"
42
+ "node": ">=20",
43
+ "bun": ">=1.2.19",
44
+ "deno": ">=2.3.0"
24
45
  },
25
46
  "files": [
26
- "index.ts",
27
- "lib",
28
47
  "dist",
29
- "tsconfig.json",
30
48
  "LICENSE.md",
31
49
  "README.md"
32
50
  ],
33
- "version": "0.1.7",
51
+ "version": "0.15.0-beta.1",
34
52
  "scripts": {
35
- "build": "neemata-build ./index.ts './lib/**/*.ts'",
53
+ "clean-build": "rm -rf ./dist",
54
+ "build": "tsc",
55
+ "dev": "tsc --watch",
36
56
  "type-check": "tsc --noEmit"
37
57
  }
38
58
  }
package/dist/index.js DELETED
@@ -1,5 +0,0 @@
1
- export * from "./lib/server.js";
2
- export * from "./lib/transport.js";
3
- export * from "./lib/types.js";
4
- export * from "./lib/utils.js";
5
- export * from "./lib/injectables.js";
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../index.ts"],"sourcesContent":["export * from './lib/server.ts'\nexport * from './lib/transport.ts'\nexport * from './lib/types.ts'\nexport * from './lib/utils.ts'\nexport * from './lib/injectables.ts'\n"],"names":[],"mappings":"AAAA,cAAc,kBAAiB;AAC/B,cAAc,qBAAoB;AAClC,cAAc,iBAAgB;AAC9B,cAAc,iBAAgB;AAC9B,cAAc,uBAAsB"}
@@ -1,2 +0,0 @@
1
- import { injectables } from '@nmtjs/application';
2
- export const connectionData = injectables.connectionData;
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/injectables.ts"],"sourcesContent":["import {\n type LazyInjectable,\n type Scope,\n injectables,\n} from '@nmtjs/application'\nimport type { HttpConnectionData } from './types.ts'\n\nexport const connectionData = injectables.connectionData as LazyInjectable<\n HttpConnectionData,\n Scope.Connection\n>\n"],"names":["injectables","connectionData"],"mappings":"AAAA,SAGEA,WAAW,QACN,qBAAoB;AAG3B,OAAO,MAAMC,iBAAiBD,YAAYC,cAAc,CAGvD"}
@@ -1,154 +0,0 @@
1
- import { ApiError, Scope, injectables } from '@nmtjs/application';
2
- import { TransportType } from '@nmtjs/common';
3
- import { App, SSLApp } from 'uWebSockets.js';
4
- import { connectionData } from "./injectables.js";
5
- import { InternalError, getFormat, getRequestData } from "./utils.js";
6
- export class HttpTransportServer {
7
- application;
8
- options;
9
- server;
10
- transportType;
11
- constructor(application, options){
12
- this.application = application;
13
- this.options = options;
14
- this.transportType = TransportType.HTTP;
15
- this.server = this.options.tls ? SSLApp(options.tls) : App();
16
- this.server.options('/*', (res, req)=>{
17
- this.applyCors(res, req);
18
- res.writeStatus('200 OK');
19
- res.endWithoutBody();
20
- }).get('/healthy', (res, req)=>{
21
- this.applyCors(res, req);
22
- res.writeHeader('Content-Type', 'text/plain');
23
- res.end('OK');
24
- }).post('/api/:service/:procudure', async (res, req)=>{
25
- const ac = new AbortController();
26
- res.onAborted(()=>ac.abort());
27
- const tryEnd = (cb)=>{
28
- if (!ac.signal.aborted) res.cork(cb);
29
- };
30
- try {
31
- this.applyCors(res, req);
32
- const requestData = getRequestData(req);
33
- const serviceName = req.getParameter(0);
34
- const procedureName = req.getParameter(1);
35
- const service = this.application.registry.services.get(serviceName);
36
- if (!service) throw new Error(`Service ${serviceName} not found`);
37
- if (this.transportType in service.contract.transports === false) throw new Error(`Service ${serviceName} not supported`);
38
- const format = getFormat(requestData, this.application.format);
39
- const body = await this.getBody(res);
40
- const container = this.application.container.createScope(Scope.Call);
41
- const payload = body.byteLength ? format.decoder.decode(body) : null;
42
- const connection = this.application.connections.add({
43
- services: [
44
- serviceName
45
- ],
46
- type: this.transportType,
47
- subscriptions: new Map()
48
- });
49
- const responseHeaders = new Headers();
50
- container.provide(connectionData, {
51
- query: requestData.query,
52
- headers: requestData.headers,
53
- proxiedRemoteAddress: Buffer.from(res.getProxiedRemoteAddressAsText()).toString(),
54
- remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),
55
- responseHeaders
56
- });
57
- container.provide(injectables.connection, connection);
58
- const { procedure } = this.api.find(serviceName, procedureName, this.transportType);
59
- try {
60
- const response = await this.handleRPC({
61
- connection,
62
- service,
63
- procedure,
64
- container,
65
- signal: ac.signal,
66
- payload
67
- });
68
- tryEnd(()=>{
69
- res.writeStatus('200 OK').writeHeader('Content-Type', format.encoder.contentType);
70
- responseHeaders.forEach((v, k)=>res.writeHeader(k, v));
71
- res.end(format.encoder.encode({
72
- error: null,
73
- result: response
74
- }));
75
- });
76
- } catch (error) {
77
- if (error instanceof ApiError) {
78
- tryEnd(()=>res.writeStatus('200 OK').end(format.encoder.encode({
79
- error,
80
- result: null
81
- })));
82
- } else {
83
- tryEnd(()=>res.writeStatus('200 OK').end(format.encoder.encode({
84
- error: InternalError(),
85
- result: null
86
- })));
87
- }
88
- this.logError(error);
89
- } finally{
90
- this.application.connections.remove(connection);
91
- this.handleContainerDisposal(container);
92
- }
93
- } catch (error) {
94
- this.logError(error);
95
- tryEnd(()=>res.writeStatus('500 Internal Server Error').endWithoutBody());
96
- }
97
- });
98
- }
99
- async start() {
100
- return new Promise((resolve, reject)=>{
101
- const hostname = this.options.hostname ?? '127.0.0.1';
102
- this.server.listen(hostname, this.options.port, (socket)=>{
103
- if (socket) {
104
- this.logger.info('Server started on %s:%s', hostname, this.options.port);
105
- resolve();
106
- } else {
107
- reject(new Error('Failed to start server'));
108
- }
109
- });
110
- });
111
- }
112
- async stop() {
113
- this.server.close();
114
- }
115
- get api() {
116
- return this.application.api;
117
- }
118
- get logger() {
119
- return this.application.logger;
120
- }
121
- async logError(cause, message = 'Unknown error while processing request') {
122
- this.logger.error(new Error(message, {
123
- cause
124
- }));
125
- }
126
- applyCors(res, req) {
127
- const origin = req.getHeader('origin');
128
- if (!origin) return;
129
- res.writeHeader('Access-Control-Allow-Origin', origin);
130
- res.writeHeader('Access-Control-Allow-Headers', 'Content-Type');
131
- res.writeHeader('Access-Control-Allow-Methods', 'GET, POST');
132
- res.writeHeader('Access-Control-Allow-Credentials', 'true');
133
- }
134
- handleContainerDisposal(container) {
135
- container.dispose();
136
- }
137
- async handleRPC(options) {
138
- return await this.api.call({
139
- ...options,
140
- transport: this.transportType
141
- });
142
- }
143
- async getBody(res) {
144
- return new Promise((resolve)=>{
145
- const chunks = [];
146
- res.onData((chunk, isLast)=>{
147
- chunks.push(Buffer.from(chunk));
148
- if (isLast) {
149
- resolve(Buffer.concat(chunks));
150
- }
151
- });
152
- });
153
- }
154
- }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import {\n type AnyBaseProcedure,\n ApiError,\n type ApplicationContext,\n type Connection,\n type Container,\n Scope,\n type Service,\n injectables,\n} from '@nmtjs/application'\nimport { TransportType } from '@nmtjs/common'\nimport {\n App,\n type HttpRequest,\n type HttpResponse,\n SSLApp,\n type TemplatedApp,\n} from 'uWebSockets.js'\nimport { connectionData } from './injectables.ts'\nimport type { HttpTransportOptions } from './types.ts'\nimport { InternalError, getFormat, getRequestData } from './utils.ts'\n\nexport class HttpTransportServer {\n protected server!: TemplatedApp\n protected readonly transportType = TransportType.HTTP\n\n constructor(\n protected readonly application: ApplicationContext,\n protected readonly options: HttpTransportOptions,\n ) {\n this.server = this.options.tls ? SSLApp(options.tls!) : App()\n\n this.server\n .options('/*', (res, req) => {\n this.applyCors(res, req)\n res.writeStatus('200 OK')\n res.endWithoutBody()\n })\n .get('/healthy', (res, req) => {\n this.applyCors(res, req)\n res.writeHeader('Content-Type', 'text/plain')\n res.end('OK')\n })\n .post('/api/:service/:procudure', async (res, req) => {\n const ac = new AbortController()\n res.onAborted(() => ac.abort())\n const tryEnd = (cb) => {\n if (!ac.signal.aborted) res.cork(cb)\n }\n\n try {\n this.applyCors(res, req)\n const requestData = getRequestData(req)\n\n const serviceName = req.getParameter(0)!\n const procedureName = req.getParameter(1)!\n\n const service = this.application.registry.services.get(serviceName)\n\n if (!service) throw new Error(`Service ${serviceName} not found`)\n if (this.transportType in service.contract.transports === false)\n throw new Error(`Service ${serviceName} not supported`)\n\n const format = getFormat(requestData, this.application.format)\n const body = await this.getBody(res)\n const container = this.application.container.createScope(Scope.Call)\n const payload = body.byteLength ? format.decoder.decode(body) : null\n const connection = this.application.connections.add({\n services: [serviceName],\n type: this.transportType,\n subscriptions: new Map(),\n })\n\n const responseHeaders = new Headers()\n\n container.provide(connectionData, {\n query: requestData.query,\n headers: requestData.headers,\n proxiedRemoteAddress: Buffer.from(\n res.getProxiedRemoteAddressAsText(),\n ).toString(),\n remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),\n responseHeaders,\n })\n container.provide(injectables.connection, connection)\n\n const { procedure } = this.api.find(\n serviceName,\n procedureName,\n this.transportType,\n )\n\n try {\n const response = await this.handleRPC({\n connection,\n service,\n procedure,\n container,\n signal: ac.signal,\n payload,\n })\n\n tryEnd(() => {\n res\n .writeStatus('200 OK')\n .writeHeader('Content-Type', format.encoder.contentType)\n responseHeaders.forEach((v, k) => res.writeHeader(k, v))\n res.end(format.encoder.encode({ error: null, result: response }))\n })\n } catch (error: any) {\n if (error instanceof ApiError) {\n tryEnd(() =>\n res\n .writeStatus('200 OK')\n .end(format.encoder.encode({ error, result: null })),\n )\n } else {\n tryEnd(() =>\n res.writeStatus('200 OK').end(\n format.encoder.encode({\n error: InternalError(),\n result: null,\n }),\n ),\n )\n }\n this.logError(error)\n } finally {\n this.application.connections.remove(connection)\n this.handleContainerDisposal(container)\n }\n } catch (error: any) {\n this.logError(error)\n tryEnd(() =>\n res.writeStatus('500 Internal Server Error').endWithoutBody(),\n )\n }\n })\n }\n\n async start() {\n return new Promise<void>((resolve, reject) => {\n const hostname = this.options.hostname ?? '127.0.0.1'\n this.server.listen(hostname, this.options.port!, (socket) => {\n if (socket) {\n this.logger.info(\n 'Server started on %s:%s',\n hostname,\n this.options.port!,\n )\n resolve()\n } else {\n reject(new Error('Failed to start server'))\n }\n })\n })\n }\n\n async stop() {\n this.server.close()\n }\n\n protected get api() {\n return this.application.api\n }\n\n protected get logger() {\n return this.application.logger\n }\n\n protected async logError(\n cause: Error,\n message = 'Unknown error while processing request',\n ) {\n this.logger.error(new Error(message, { cause }))\n }\n\n protected applyCors(res: HttpResponse, req: HttpRequest) {\n // TODO: this should be configurable\n const origin = req.getHeader('origin')\n if (!origin) return\n res.writeHeader('Access-Control-Allow-Origin', origin)\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET, POST')\n res.writeHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n protected handleContainerDisposal(container: Container) {\n container.dispose()\n }\n\n protected async handleRPC(options: {\n connection: Connection\n service: Service\n procedure: AnyBaseProcedure\n container: Container\n signal: AbortSignal\n payload: any\n }) {\n return await this.api.call({\n ...options,\n transport: this.transportType,\n })\n }\n\n protected async getBody(res: HttpResponse) {\n return new Promise<Buffer>((resolve) => {\n const chunks: Buffer[] = []\n res.onData((chunk, isLast) => {\n chunks.push(Buffer.from(chunk))\n if (isLast) {\n resolve(Buffer.concat(chunks))\n }\n })\n })\n }\n}\n"],"names":["ApiError","Scope","injectables","TransportType","App","SSLApp","connectionData","InternalError","getFormat","getRequestData","HttpTransportServer","server","transportType","constructor","application","options","HTTP","tls","res","req","applyCors","writeStatus","endWithoutBody","get","writeHeader","end","post","ac","AbortController","onAborted","abort","tryEnd","cb","signal","aborted","cork","requestData","serviceName","getParameter","procedureName","service","registry","services","Error","contract","transports","format","body","getBody","container","createScope","Call","payload","byteLength","decoder","decode","connection","connections","add","type","subscriptions","Map","responseHeaders","Headers","provide","query","headers","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","procedure","api","find","response","handleRPC","encoder","contentType","forEach","v","k","encode","error","result","logError","remove","handleContainerDisposal","start","Promise","resolve","reject","hostname","listen","port","socket","logger","info","stop","close","cause","message","origin","getHeader","dispose","call","transport","chunks","onData","chunk","isLast","push","concat"],"mappings":"AAAA,SAEEA,QAAQ,EAIRC,KAAK,EAELC,WAAW,QACN,qBAAoB;AAC3B,SAASC,aAAa,QAAQ,gBAAe;AAC7C,SACEC,GAAG,EAGHC,MAAM,QAED,iBAAgB;AACvB,SAASC,cAAc,QAAQ,mBAAkB;AAEjD,SAASC,aAAa,EAAEC,SAAS,EAAEC,cAAc,QAAQ,aAAY;AAErE,OAAO,MAAMC;;;IACDC,OAAqB;IACZC,cAAkC;IAErDC,YACE,AAAmBC,WAA+B,EAClD,AAAmBC,OAA6B,CAChD;aAFmBD,cAAAA;aACAC,UAAAA;aAJFH,gBAAgBT,cAAca,IAAI;QAMnD,IAAI,CAACL,MAAM,GAAG,IAAI,CAACI,OAAO,CAACE,GAAG,GAAGZ,OAAOU,QAAQE,GAAG,IAAKb;QAExD,IAAI,CAACO,MAAM,CACRI,OAAO,CAAC,MAAM,CAACG,KAAKC;YACnB,IAAI,CAACC,SAAS,CAACF,KAAKC;YACpBD,IAAIG,WAAW,CAAC;YAChBH,IAAII,cAAc;QACpB,GACCC,GAAG,CAAC,YAAY,CAACL,KAAKC;YACrB,IAAI,CAACC,SAAS,CAACF,KAAKC;YACpBD,IAAIM,WAAW,CAAC,gBAAgB;YAChCN,IAAIO,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AwBxC,SAAoB,EAAE;QACtDA,UAAUyD,OAAO;IACnB;IAEA,MAAgB5B,UAAU/D,OAOzB,EAAE;QACD,OAAO,MAAM,IAAI,CAAC4D,GAAG,CAACgC,IAAI,CAAC;YACzB,GAAG5F,OAAO;YACV6F,WAAW,IAAI,CAAChG,aAAa;QAC/B;IACF;IAEA,MAAgBoC,QAAQ9B,GAAiB,EAAE;QACzC,OAAO,IAAIyE,QAAgB,CAACC;YAC1B,MAAMiB,SAAmB,EAAE;YAC3B3F,IAAI4F,MAAM,CAAC,CAACC,OAAOC;gBACjBH,OAAOI,IAAI,CAAC7C,OAAOC,IAAI,CAAC0C;gBACxB,IAAIC,QAAQ;oBACVpB,QAAQxB,OAAO8C,MAAM,CAACL;gBACxB;YACF;QACF;IACF;AACF"}
@@ -1,5 +0,0 @@
1
- import { createTransport } from '@nmtjs/application';
2
- import { HttpTransportServer } from "./server.js";
3
- export const HttpTransport = createTransport('HttpTransport', (app, options)=>{
4
- return new HttpTransportServer(app, options);
5
- });
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import { createTransport } from '@nmtjs/application'\nimport { HttpTransportServer } from './server.ts'\nimport type { HttpTransportOptions } from './types.ts'\n\nexport const HttpTransport = createTransport<HttpTransportOptions>(\n 'HttpTransport',\n (app, options) => {\n return new HttpTransportServer(app, options)\n },\n)\n"],"names":["createTransport","HttpTransportServer","HttpTransport","app","options"],"mappings":"AAAA,SAASA,eAAe,QAAQ,qBAAoB;AACpD,SAASC,mBAAmB,QAAQ,cAAa;AAGjD,OAAO,MAAMC,gBAAgBF,gBAC3B,iBACA,CAACG,KAAKC;IACJ,OAAO,IAAIH,oBAAoBE,KAAKC;AACtC,GACD"}
package/dist/lib/types.js DELETED
@@ -1 +0,0 @@
1
- export { };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type { AppOptions } from 'uWebSockets.js'\n\nexport type HttpTransportOptions = {\n port?: number\n hostname?: string\n unix?: string\n tls?: AppOptions\n maxPayloadLength?: number\n maxStreamChunkLength?: number\n}\n\nexport type HttpConnectionData = {\n headers: Map<string, string>\n query: URLSearchParams\n remoteAddress: string\n proxiedRemoteAddress: string\n responseHeaders: Headers\n}\n"],"names":[],"mappings":"AAWA,WAMC"}
package/dist/lib/utils.js DELETED
@@ -1,33 +0,0 @@
1
- import { ApiError } from '@nmtjs/application';
2
- import { ErrorCode } from '@nmtjs/common';
3
- export const getFormat = ({ headers, query }, format)=>{
4
- const contentType = headers.get('content-type') || query.get('content-type');
5
- const acceptType = headers.get('accept') || query.get('accept');
6
- const encoder = contentType ? format.supportsEncoder(contentType) : undefined;
7
- if (!encoder) throw new Error('Unsupported content-type');
8
- const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined;
9
- if (!decoder) throw new Error('Unsupported accept');
10
- return {
11
- encoder,
12
- decoder
13
- };
14
- };
15
- export const getRequestData = (req)=>{
16
- const url = req.getUrl();
17
- const method = req.getMethod();
18
- const headers = new Map();
19
- req.forEach((key, value)=>headers.set(key, value));
20
- const query = new URLSearchParams(req.getQuery());
21
- const origin = headers.has('origin') ? new URL(url, headers.get('origin')) : null;
22
- return {
23
- url,
24
- origin,
25
- method,
26
- headers,
27
- query
28
- };
29
- };
30
- export const InternalError = (message = 'Internal Server Error')=>new ApiError(ErrorCode.InternalServerError, message);
31
- export const NotFoundError = (message = 'Not Found')=>new ApiError(ErrorCode.NotFound, message);
32
- export const ForbiddenError = (message = 'Forbidden')=>new ApiError(ErrorCode.Forbidden, message);
33
- export const RequestTimeoutError = (message = 'Request Timeout')=>new ApiError(ErrorCode.RequestTimeout, message);
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/utils.ts"],"sourcesContent":["import { ApiError, type Format } from '@nmtjs/application'\nimport { ErrorCode } from '@nmtjs/common'\nimport type { HttpRequest } from 'uWebSockets.js'\n\nexport const getFormat = ({ headers, query }: RequestData, format: Format) => {\n const contentType = headers.get('content-type') || query.get('content-type')\n const acceptType = headers.get('accept') || query.get('accept')\n\n const encoder = contentType ? format.supportsEncoder(contentType) : undefined\n if (!encoder) throw new Error('Unsupported content-type')\n\n const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined\n if (!decoder) throw new Error('Unsupported accept')\n\n return {\n encoder,\n decoder,\n }\n}\n\nexport type RequestData = {\n url: string\n origin: URL | null\n method: string\n headers: Map<string, string>\n query: URLSearchParams\n}\n\nexport const getRequestData = (req: HttpRequest): RequestData => {\n const url = req.getUrl()\n const method = req.getMethod()\n const headers = new Map()\n req.forEach((key, value) => headers.set(key, value))\n const query = new URLSearchParams(req.getQuery())\n const origin = headers.has('origin')\n ? new URL(url, headers.get('origin'))\n : null\n\n return {\n url,\n origin,\n method,\n headers,\n query,\n }\n}\n\nexport const InternalError = (message = 'Internal Server Error') =>\n new ApiError(ErrorCode.InternalServerError, message)\n\nexport const NotFoundError = (message = 'Not Found') =>\n new ApiError(ErrorCode.NotFound, message)\n\nexport const ForbiddenError = (message = 'Forbidden') =>\n new ApiError(ErrorCode.Forbidden, message)\n\nexport const RequestTimeoutError = (message = 'Request Timeout') =>\n new ApiError(ErrorCode.RequestTimeout, message)\n"],"names":["ApiError","ErrorCode","getFormat","headers","query","format","contentType","get","acceptType","encoder","supportsEncoder","undefined","Error","decoder","supportsDecoder","getRequestData","req","url","getUrl","method","getMethod","Map","forEach","key","value","set","URLSearchParams","getQuery","origin","has","URL","InternalError","message","InternalServerError","NotFoundError","NotFound","ForbiddenError","Forbidden","RequestTimeoutError","RequestTimeout"],"mappings":"AAAA,SAASA,QAAQ,QAAqB,qBAAoB;AAC1D,SAASC,SAAS,QAAQ,gBAAe;AAGzC,OAAO,MAAMC,YAAY,CAAC,EAAEC,OAAO,EAAEC,KAAK,EAAe,EAAEC;IACzD,MAAMC,cAAcH,QAAQI,GAAG,CAAC,mBAAmBH,MAAMG,GAAG,CAAC;IAC7D,MAAMC,aAAaL,QAAQI,GAAG,CAAC,aAAaH,MAAMG,GAAG,CAAC;IAEtD,MAAME,UAAUH,cAAcD,OAAOK,eAAe,CAACJ,eAAeK;IACpE,IAAI,CAACF,SAAS,MAAM,IAAIG,MAAM;IAE9B,MAAMC,UAAUL,aAAaH,OAAOS,eAAe,CAACN,cAAcG;IAClE,IAAI,CAACE,SAAS,MAAM,IAAID,MAAM;IAE9B,OAAO;QACLH;QACAI;IACF;AACF,EAAC;AAUD,OAAO,MAAME,iBAAiB,CAACC;IAC7B,MAAMC,MAAMD,IAAIE,MAAM;IACtB,MAAMC,SAASH,IAAII,SAAS;IAC5B,MAAMjB,UAAU,IAAIkB;IACpBL,IAAIM,OAAO,CAAC,CAACC,KAAKC,QAAUrB,QAAQsB,GAAG,CAACF,KAAKC;IAC7C,MAAMpB,QAAQ,IAAIsB,gBAAgBV,IAAIW,QAAQ;IAC9C,MAAMC,SAASzB,QAAQ0B,GAAG,CAAC,YACvB,IAAIC,IAAIb,KAAKd,QAAQI,GAAG,CAAC,aACzB;IAEJ,OAAO;QACLU;QACAW;QACAT;QACAhB;QACAC;IACF;AACF,EAAC;AAED,OAAO,MAAM2B,gBAAgB,CAACC,UAAU,uBAAuB,GAC7D,IAAIhC,SAASC,UAAUgC,mBAAmB,EAAED,SAAQ;AAEtD,OAAO,MAAME,gBAAgB,CAACF,UAAU,WAAW,GACjD,IAAIhC,SAASC,UAAUkC,QAAQ,EAAEH,SAAQ;AAE3C,OAAO,MAAMI,iBAAiB,CAACJ,UAAU,WAAW,GAClD,IAAIhC,SAASC,UAAUoC,SAAS,EAAEL,SAAQ;AAE5C,OAAO,MAAMM,sBAAsB,CAACN,UAAU,iBAAiB,GAC7D,IAAIhC,SAASC,UAAUsC,cAAc,EAAEP,SAAQ"}
package/index.ts DELETED
@@ -1,5 +0,0 @@
1
- export * from './lib/server.ts'
2
- export * from './lib/transport.ts'
3
- export * from './lib/types.ts'
4
- export * from './lib/utils.ts'
5
- export * from './lib/injectables.ts'
@@ -1,11 +0,0 @@
1
- import {
2
- type LazyInjectable,
3
- type Scope,
4
- injectables,
5
- } from '@nmtjs/application'
6
- import type { HttpConnectionData } from './types.ts'
7
-
8
- export const connectionData = injectables.connectionData as LazyInjectable<
9
- HttpConnectionData,
10
- Scope.Connection
11
- >
package/lib/server.ts DELETED
@@ -1,217 +0,0 @@
1
- import {
2
- type AnyBaseProcedure,
3
- ApiError,
4
- type ApplicationContext,
5
- type Connection,
6
- type Container,
7
- Scope,
8
- type Service,
9
- injectables,
10
- } from '@nmtjs/application'
11
- import { TransportType } from '@nmtjs/common'
12
- import {
13
- App,
14
- type HttpRequest,
15
- type HttpResponse,
16
- SSLApp,
17
- type TemplatedApp,
18
- } from 'uWebSockets.js'
19
- import { connectionData } from './injectables.ts'
20
- import type { HttpTransportOptions } from './types.ts'
21
- import { InternalError, getFormat, getRequestData } from './utils.ts'
22
-
23
- export class HttpTransportServer {
24
- protected server!: TemplatedApp
25
- protected readonly transportType = TransportType.HTTP
26
-
27
- constructor(
28
- protected readonly application: ApplicationContext,
29
- protected readonly options: HttpTransportOptions,
30
- ) {
31
- this.server = this.options.tls ? SSLApp(options.tls!) : App()
32
-
33
- this.server
34
- .options('/*', (res, req) => {
35
- this.applyCors(res, req)
36
- res.writeStatus('200 OK')
37
- res.endWithoutBody()
38
- })
39
- .get('/healthy', (res, req) => {
40
- this.applyCors(res, req)
41
- res.writeHeader('Content-Type', 'text/plain')
42
- res.end('OK')
43
- })
44
- .post('/api/:service/:procudure', async (res, req) => {
45
- const ac = new AbortController()
46
- res.onAborted(() => ac.abort())
47
- const tryEnd = (cb) => {
48
- if (!ac.signal.aborted) res.cork(cb)
49
- }
50
-
51
- try {
52
- this.applyCors(res, req)
53
- const requestData = getRequestData(req)
54
-
55
- const serviceName = req.getParameter(0)!
56
- const procedureName = req.getParameter(1)!
57
-
58
- const service = this.application.registry.services.get(serviceName)
59
-
60
- if (!service) throw new Error(`Service ${serviceName} not found`)
61
- if (this.transportType in service.contract.transports === false)
62
- throw new Error(`Service ${serviceName} not supported`)
63
-
64
- const format = getFormat(requestData, this.application.format)
65
- const body = await this.getBody(res)
66
- const container = this.application.container.createScope(Scope.Call)
67
- const payload = body.byteLength ? format.decoder.decode(body) : null
68
- const connection = this.application.connections.add({
69
- services: [serviceName],
70
- type: this.transportType,
71
- subscriptions: new Map(),
72
- })
73
-
74
- const responseHeaders = new Headers()
75
-
76
- container.provide(connectionData, {
77
- query: requestData.query,
78
- headers: requestData.headers,
79
- proxiedRemoteAddress: Buffer.from(
80
- res.getProxiedRemoteAddressAsText(),
81
- ).toString(),
82
- remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),
83
- responseHeaders,
84
- })
85
- container.provide(injectables.connection, connection)
86
-
87
- const { procedure } = this.api.find(
88
- serviceName,
89
- procedureName,
90
- this.transportType,
91
- )
92
-
93
- try {
94
- const response = await this.handleRPC({
95
- connection,
96
- service,
97
- procedure,
98
- container,
99
- signal: ac.signal,
100
- payload,
101
- })
102
-
103
- tryEnd(() => {
104
- res
105
- .writeStatus('200 OK')
106
- .writeHeader('Content-Type', format.encoder.contentType)
107
- responseHeaders.forEach((v, k) => res.writeHeader(k, v))
108
- res.end(format.encoder.encode({ error: null, result: response }))
109
- })
110
- } catch (error: any) {
111
- if (error instanceof ApiError) {
112
- tryEnd(() =>
113
- res
114
- .writeStatus('200 OK')
115
- .end(format.encoder.encode({ error, result: null })),
116
- )
117
- } else {
118
- tryEnd(() =>
119
- res.writeStatus('200 OK').end(
120
- format.encoder.encode({
121
- error: InternalError(),
122
- result: null,
123
- }),
124
- ),
125
- )
126
- }
127
- this.logError(error)
128
- } finally {
129
- this.application.connections.remove(connection)
130
- this.handleContainerDisposal(container)
131
- }
132
- } catch (error: any) {
133
- this.logError(error)
134
- tryEnd(() =>
135
- res.writeStatus('500 Internal Server Error').endWithoutBody(),
136
- )
137
- }
138
- })
139
- }
140
-
141
- async start() {
142
- return new Promise<void>((resolve, reject) => {
143
- const hostname = this.options.hostname ?? '127.0.0.1'
144
- this.server.listen(hostname, this.options.port!, (socket) => {
145
- if (socket) {
146
- this.logger.info(
147
- 'Server started on %s:%s',
148
- hostname,
149
- this.options.port!,
150
- )
151
- resolve()
152
- } else {
153
- reject(new Error('Failed to start server'))
154
- }
155
- })
156
- })
157
- }
158
-
159
- async stop() {
160
- this.server.close()
161
- }
162
-
163
- protected get api() {
164
- return this.application.api
165
- }
166
-
167
- protected get logger() {
168
- return this.application.logger
169
- }
170
-
171
- protected async logError(
172
- cause: Error,
173
- message = 'Unknown error while processing request',
174
- ) {
175
- this.logger.error(new Error(message, { cause }))
176
- }
177
-
178
- protected applyCors(res: HttpResponse, req: HttpRequest) {
179
- // TODO: this should be configurable
180
- const origin = req.getHeader('origin')
181
- if (!origin) return
182
- res.writeHeader('Access-Control-Allow-Origin', origin)
183
- res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')
184
- res.writeHeader('Access-Control-Allow-Methods', 'GET, POST')
185
- res.writeHeader('Access-Control-Allow-Credentials', 'true')
186
- }
187
-
188
- protected handleContainerDisposal(container: Container) {
189
- container.dispose()
190
- }
191
-
192
- protected async handleRPC(options: {
193
- connection: Connection
194
- service: Service
195
- procedure: AnyBaseProcedure
196
- container: Container
197
- signal: AbortSignal
198
- payload: any
199
- }) {
200
- return await this.api.call({
201
- ...options,
202
- transport: this.transportType,
203
- })
204
- }
205
-
206
- protected async getBody(res: HttpResponse) {
207
- return new Promise<Buffer>((resolve) => {
208
- const chunks: Buffer[] = []
209
- res.onData((chunk, isLast) => {
210
- chunks.push(Buffer.from(chunk))
211
- if (isLast) {
212
- resolve(Buffer.concat(chunks))
213
- }
214
- })
215
- })
216
- }
217
- }
package/lib/transport.ts DELETED
@@ -1,10 +0,0 @@
1
- import { createTransport } from '@nmtjs/application'
2
- import { HttpTransportServer } from './server.ts'
3
- import type { HttpTransportOptions } from './types.ts'
4
-
5
- export const HttpTransport = createTransport<HttpTransportOptions>(
6
- 'HttpTransport',
7
- (app, options) => {
8
- return new HttpTransportServer(app, options)
9
- },
10
- )
package/lib/types.ts DELETED
@@ -1,18 +0,0 @@
1
- import type { AppOptions } from 'uWebSockets.js'
2
-
3
- export type HttpTransportOptions = {
4
- port?: number
5
- hostname?: string
6
- unix?: string
7
- tls?: AppOptions
8
- maxPayloadLength?: number
9
- maxStreamChunkLength?: number
10
- }
11
-
12
- export type HttpConnectionData = {
13
- headers: Map<string, string>
14
- query: URLSearchParams
15
- remoteAddress: string
16
- proxiedRemoteAddress: string
17
- responseHeaders: Headers
18
- }
package/lib/utils.ts DELETED
@@ -1,58 +0,0 @@
1
- import { ApiError, type Format } from '@nmtjs/application'
2
- import { ErrorCode } from '@nmtjs/common'
3
- import type { HttpRequest } from 'uWebSockets.js'
4
-
5
- export const getFormat = ({ headers, query }: RequestData, format: Format) => {
6
- const contentType = headers.get('content-type') || query.get('content-type')
7
- const acceptType = headers.get('accept') || query.get('accept')
8
-
9
- const encoder = contentType ? format.supportsEncoder(contentType) : undefined
10
- if (!encoder) throw new Error('Unsupported content-type')
11
-
12
- const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined
13
- if (!decoder) throw new Error('Unsupported accept')
14
-
15
- return {
16
- encoder,
17
- decoder,
18
- }
19
- }
20
-
21
- export type RequestData = {
22
- url: string
23
- origin: URL | null
24
- method: string
25
- headers: Map<string, string>
26
- query: URLSearchParams
27
- }
28
-
29
- export const getRequestData = (req: HttpRequest): RequestData => {
30
- const url = req.getUrl()
31
- const method = req.getMethod()
32
- const headers = new Map()
33
- req.forEach((key, value) => headers.set(key, value))
34
- const query = new URLSearchParams(req.getQuery())
35
- const origin = headers.has('origin')
36
- ? new URL(url, headers.get('origin'))
37
- : null
38
-
39
- return {
40
- url,
41
- origin,
42
- method,
43
- headers,
44
- query,
45
- }
46
- }
47
-
48
- export const InternalError = (message = 'Internal Server Error') =>
49
- new ApiError(ErrorCode.InternalServerError, message)
50
-
51
- export const NotFoundError = (message = 'Not Found') =>
52
- new ApiError(ErrorCode.NotFound, message)
53
-
54
- export const ForbiddenError = (message = 'Forbidden') =>
55
- new ApiError(ErrorCode.Forbidden, message)
56
-
57
- export const RequestTimeoutError = (message = 'Request Timeout') =>
58
- new ApiError(ErrorCode.RequestTimeout, message)
package/tsconfig.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json"
3
- }