@orpc/standard-server-node 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 oRPC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.js ADDED
@@ -0,0 +1,253 @@
1
+ // src/body.ts
2
+ import { Readable as Readable2 } from "node:stream";
3
+ import { contentDisposition, isAsyncIteratorObject, parseContentDisposition, parseEmptyableJSON as parseEmptyableJSON2 } from "@orpc/standard-server";
4
+
5
+ // src/event-source.ts
6
+ import { Readable } from "node:stream";
7
+ import {
8
+ encodeEventMessage,
9
+ ErrorEvent,
10
+ EventDecoderStream,
11
+ getEventMeta,
12
+ isEventMetaContainer,
13
+ parseEmptyableJSON,
14
+ UnknownEvent,
15
+ withEventMeta
16
+ } from "@orpc/standard-server";
17
+ function toEventIterator(stream) {
18
+ const eventStream = Readable.toWeb(stream).pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
19
+ const reader = eventStream.getReader();
20
+ async function* gen() {
21
+ try {
22
+ while (true) {
23
+ const { done, value } = await reader.read();
24
+ if (done) {
25
+ return;
26
+ }
27
+ switch (value.event) {
28
+ case "message": {
29
+ let message = parseEmptyableJSON(value.data);
30
+ if (isEventMetaContainer(message)) {
31
+ message = withEventMeta(message, value);
32
+ }
33
+ yield message;
34
+ break;
35
+ }
36
+ case "error": {
37
+ let error = new ErrorEvent({
38
+ data: parseEmptyableJSON(value.data)
39
+ });
40
+ error = withEventMeta(error, value);
41
+ throw error;
42
+ }
43
+ case "done": {
44
+ let done2 = parseEmptyableJSON(value.data);
45
+ if (isEventMetaContainer(done2)) {
46
+ done2 = withEventMeta(done2, value);
47
+ }
48
+ return done2;
49
+ }
50
+ default: {
51
+ let error = new UnknownEvent({
52
+ message: `Unknown event: ${value.event}`,
53
+ data: parseEmptyableJSON(value.data)
54
+ });
55
+ error = withEventMeta(error, value);
56
+ throw error;
57
+ }
58
+ }
59
+ }
60
+ } finally {
61
+ await reader.cancel();
62
+ }
63
+ }
64
+ return gen();
65
+ }
66
+ function toEventStream(iterator) {
67
+ const stream = new ReadableStream({
68
+ async pull(controller) {
69
+ try {
70
+ const value = await iterator.next();
71
+ controller.enqueue(encodeEventMessage({
72
+ ...getEventMeta(value.value),
73
+ event: value.done ? "done" : "message",
74
+ data: JSON.stringify(value.value)
75
+ }));
76
+ if (value.done) {
77
+ controller.close();
78
+ }
79
+ } catch (err) {
80
+ controller.enqueue(encodeEventMessage({
81
+ ...getEventMeta(err),
82
+ event: "error",
83
+ data: err instanceof ErrorEvent ? JSON.stringify(err.data) : void 0
84
+ }));
85
+ controller.close();
86
+ }
87
+ },
88
+ async cancel(reason) {
89
+ if (reason) {
90
+ await iterator.throw?.(reason);
91
+ } else {
92
+ await iterator.return?.();
93
+ }
94
+ }
95
+ });
96
+ return Readable.fromWeb(stream);
97
+ }
98
+
99
+ // src/body.ts
100
+ async function toStandardBody(req) {
101
+ const method = req.method ?? "GET";
102
+ if (method === "GET" || method === "HEAD") {
103
+ return void 0;
104
+ }
105
+ const contentDisposition2 = req.headers["content-disposition"];
106
+ const contentType = req.headers["content-type"];
107
+ if (contentDisposition2) {
108
+ const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
109
+ if (typeof fileName === "string") {
110
+ return _streamToFile(req, fileName, contentType ?? "");
111
+ }
112
+ }
113
+ if (!contentType || contentType.startsWith("application/json")) {
114
+ const text = await _streamToString(req);
115
+ return parseEmptyableJSON2(text);
116
+ }
117
+ if (contentType.startsWith("multipart/form-data")) {
118
+ return _streamToFormData(req, contentType);
119
+ }
120
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
121
+ const text = await _streamToString(req);
122
+ return new URLSearchParams(text);
123
+ }
124
+ if (contentType.startsWith("text/event-stream")) {
125
+ return toEventIterator(req);
126
+ }
127
+ if (contentType.startsWith("text/")) {
128
+ return _streamToString(req);
129
+ }
130
+ return _streamToFile(req, "blob", contentType);
131
+ }
132
+ function toNodeHttpBody(body, headers) {
133
+ delete headers["content-type"];
134
+ delete headers["content-disposition"];
135
+ if (body === void 0) {
136
+ return;
137
+ }
138
+ if (body instanceof Blob) {
139
+ headers["content-type"] = body.type;
140
+ headers["content-length"] = body.size.toString();
141
+ headers["content-disposition"] = contentDisposition(
142
+ body instanceof File ? body.name : "blob",
143
+ { type: "inline" }
144
+ );
145
+ return Readable2.fromWeb(body.stream());
146
+ }
147
+ if (body instanceof FormData) {
148
+ const response = new Response(body);
149
+ headers["content-type"] = response.headers.get("content-type");
150
+ return Readable2.fromWeb(response.body);
151
+ }
152
+ if (body instanceof URLSearchParams) {
153
+ headers["content-type"] = "application/x-www-form-urlencoded";
154
+ return body.toString();
155
+ }
156
+ if (isAsyncIteratorObject(body)) {
157
+ headers["content-type"] = "text/event-stream";
158
+ headers["cache-control"] = "no-cache";
159
+ headers.connection = "keep-alive";
160
+ return toEventStream(body);
161
+ }
162
+ headers["content-type"] = "application/json";
163
+ return JSON.stringify(body);
164
+ }
165
+ function _streamToFormData(stream, contentType) {
166
+ const response = new Response(stream, {
167
+ headers: {
168
+ "content-type": contentType
169
+ }
170
+ });
171
+ return response.formData();
172
+ }
173
+ async function _streamToString(stream) {
174
+ let string = "";
175
+ for await (const chunk of stream) {
176
+ string += chunk.toString();
177
+ }
178
+ return string;
179
+ }
180
+ async function _streamToFile(stream, fileName, contentType) {
181
+ const chunks = [];
182
+ for await (const chunk of stream) {
183
+ chunks.push(chunk);
184
+ }
185
+ return new File(chunks, fileName, { type: contentType });
186
+ }
187
+
188
+ // src/request.ts
189
+ import { once } from "@orpc/standard-server";
190
+
191
+ // src/signal.ts
192
+ function toAbortSignal(res) {
193
+ const controller = new AbortController();
194
+ res.on("close", () => {
195
+ if (res.errored) {
196
+ controller.abort(res.errored.toString());
197
+ } else if (!res.writableFinished) {
198
+ controller.abort("Client connection prematurely closed.");
199
+ } else {
200
+ controller.abort("Server closed the connection.");
201
+ }
202
+ });
203
+ return controller.signal;
204
+ }
205
+
206
+ // src/request.ts
207
+ function toStandardRequest(req, res) {
208
+ const method = req.method ?? "GET";
209
+ const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
210
+ const host = req.headers.host ?? "localhost";
211
+ const url = new URL(req.originalUrl ?? req.url ?? "/", `${protocol}//${host}`);
212
+ return {
213
+ raw: { request: req, response: res },
214
+ method,
215
+ url,
216
+ headers: req.headers,
217
+ body: once(() => toStandardBody(req)),
218
+ signal: toAbortSignal(res)
219
+ };
220
+ }
221
+
222
+ // src/response.ts
223
+ function sendStandardResponse(res, standardResponse) {
224
+ return new Promise((resolve, reject) => {
225
+ res.on("error", reject);
226
+ res.on("finish", resolve);
227
+ const resHeaders = standardResponse.headers;
228
+ const resBody = toNodeHttpBody(standardResponse.body, resHeaders);
229
+ res.writeHead(standardResponse.status, resHeaders);
230
+ if (resBody === void 0) {
231
+ res.end(resBody);
232
+ } else if (typeof resBody === "string") {
233
+ res.end(resBody);
234
+ } else {
235
+ res.on("close", () => {
236
+ if (!resBody.closed) {
237
+ resBody.destroy(res.errored ?? void 0);
238
+ }
239
+ });
240
+ resBody.pipe(res);
241
+ }
242
+ });
243
+ }
244
+ export {
245
+ sendStandardResponse,
246
+ toAbortSignal,
247
+ toEventIterator,
248
+ toEventStream,
249
+ toNodeHttpBody,
250
+ toStandardBody,
251
+ toStandardRequest
252
+ };
253
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ import type { StandardBody, StandardHeaders } from '@orpc/standard-server';
2
+ import type { NodeHttpRequest } from './types';
3
+ import { Readable } from 'node:stream';
4
+ export declare function toStandardBody(req: NodeHttpRequest): Promise<StandardBody>;
5
+ /**
6
+ * @param body
7
+ * @param headers - The headers can be changed by the function and effects on the original headers.
8
+ */
9
+ export declare function toNodeHttpBody(body: StandardBody, headers: StandardHeaders): Readable | undefined | string;
10
+ //# sourceMappingURL=body.d.ts.map
@@ -0,0 +1,5 @@
1
+ import type { JsonValue } from '@orpc/standard-server';
2
+ import { Readable } from 'node:stream';
3
+ export declare function toEventIterator(stream: Readable): AsyncGenerator<JsonValue | void, JsonValue | void, void>;
4
+ export declare function toEventStream(iterator: AsyncIterator<JsonValue | void, JsonValue | void, void>): Readable;
5
+ //# sourceMappingURL=event-source.d.ts.map
@@ -0,0 +1,7 @@
1
+ export * from './body';
2
+ export * from './event-source';
3
+ export * from './request';
4
+ export * from './response';
5
+ export * from './signal';
6
+ export * from './types';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ import type { StandardRequest } from '@orpc/standard-server';
2
+ import type { NodeHttpRequest, NodeHttpResponse } from './types';
3
+ export declare function toStandardRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardRequest;
4
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1,4 @@
1
+ import type { StandardResponse } from '@orpc/standard-server';
2
+ import type { NodeHttpResponse } from './types';
3
+ export declare function sendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse): Promise<void>;
4
+ //# sourceMappingURL=response.d.ts.map
@@ -0,0 +1,3 @@
1
+ import type { NodeHttpResponse } from './types';
2
+ export declare function toAbortSignal(res: NodeHttpResponse): AbortSignal;
3
+ //# sourceMappingURL=signal.d.ts.map
@@ -0,0 +1,11 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
3
+ export type NodeHttpRequest = (IncomingMessage | Http2ServerRequest) & {
4
+ /**
5
+ * Replace `req.url` with `req.originalUrl` when `req.originalUrl` is available.
6
+ * This is useful for `express.js` middleware.
7
+ */
8
+ originalUrl?: string;
9
+ };
10
+ export type NodeHttpResponse = ServerResponse | Http2ServerResponse;
11
+ //# sourceMappingURL=types.d.ts.map
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@orpc/standard-server-node",
3
+ "type": "module",
4
+ "version": "0.0.0",
5
+ "license": "MIT",
6
+ "homepage": "https://orpc.unnoq.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/unnoq/orpc.git",
10
+ "directory": "packages/standard-server-node"
11
+ },
12
+ "keywords": [
13
+ "orpc"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/src/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./🔒/*": {
22
+ "types": "./dist/src/*.d.ts"
23
+ }
24
+ },
25
+ "files": [
26
+ "!**/*.map",
27
+ "!**/*.tsbuildinfo",
28
+ "dist"
29
+ ],
30
+ "dependencies": {
31
+ "@orpc/standard-server": "0.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^22.13.1",
35
+ "@types/supertest": "^6.0.2",
36
+ "supertest": "^7.0.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
40
+ "build:watch": "pnpm run build --watch",
41
+ "type:check": "tsc -b"
42
+ }
43
+ }