@universal-middleware/express 0.4.29 → 0.4.31
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/dist/index.d.ts +35 -33
- package/dist/index.js +360 -411
- package/dist/request.d.ts +2 -1
- package/dist/request.js +2 -10
- package/package.json +12 -11
- package/dist/chunk-N42HUXDK.js +0 -8
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { DecoratedRequest, NodeRequestAdapterOptions } from
|
|
4
|
-
|
|
5
|
-
import { Readable } from
|
|
6
|
-
import { Express
|
|
7
|
-
import { Express as Express$1 } from
|
|
8
|
-
|
|
1
|
+
import { createRequestAdapter } from "./request.js";
|
|
2
|
+
import { Awaitable, EnhancedMiddleware, Get, RuntimeAdapterTarget, UniversalFn, UniversalHandler, UniversalMiddleware, UniversalRouter, UniversalRouterInterface } from "@universal-middleware/core";
|
|
3
|
+
import { DecoratedRequest, NodeRequestAdapterOptions, sendResponse } from "@universal-middleware/node";
|
|
4
|
+
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
5
|
+
import { Readable } from "node:stream";
|
|
6
|
+
import { Express } from "express";
|
|
7
|
+
import { Express as Express$1 } from "express4";
|
|
8
|
+
//#region src/const.d.ts
|
|
9
9
|
declare const pendingMiddlewaresSymbol: unique symbol;
|
|
10
10
|
declare const wrappedResponseSymbol: unique symbol;
|
|
11
|
-
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/types.d.ts
|
|
12
13
|
interface DecoratedServerResponse extends ServerResponse {
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
[pendingMiddlewaresSymbol]?: ((response: Response) => Awaitable<Response | undefined>)[];
|
|
15
|
+
[wrappedResponseSymbol]?: boolean;
|
|
15
16
|
}
|
|
16
17
|
/** Connect/Express style request listener/middleware */
|
|
17
18
|
type NodeMiddleware<In extends Universal.Context, Out extends Universal.Context> = UniversalFn<UniversalMiddleware<In, Out>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
|
|
18
19
|
type NodeHandler<In extends Universal.Context> = UniversalFn<UniversalHandler<In>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
|
|
19
20
|
/** Adapter options */
|
|
20
|
-
interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {}
|
|
22
|
+
interface NodeAdapterMiddlewareOptions extends NodeRequestAdapterOptions {}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/common.d.ts
|
|
25
25
|
/**
|
|
26
26
|
* Creates a request handler to be passed to http.createServer() or used as a
|
|
27
27
|
* middleware in Connect-style frameworks like Express.
|
|
@@ -32,8 +32,9 @@ declare function createHandler<T extends unknown[], InContext extends Universal.
|
|
|
32
32
|
*/
|
|
33
33
|
declare function createMiddleware<T extends unknown[], InContext extends Universal.Context, OutContext extends Universal.Context>(middlewareFactory: Get<T, UniversalMiddleware<InContext, OutContext>>, options?: NodeAdapterMiddlewareOptions): Get<T, NodeMiddleware<InContext, OutContext>>;
|
|
34
34
|
declare function getContext<InContext extends Universal.Context = Universal.Context>(req: DecoratedRequest): InContext;
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/utils.d.ts
|
|
37
|
+
type Express$2 = Express$1 | Express;
|
|
37
38
|
type ConnectMiddleware = (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void | Promise<void>;
|
|
38
39
|
type ConnectMiddlewareBoolean = (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => boolean | Promise<boolean>;
|
|
39
40
|
type WebHandler<InContext extends Universal.Context = Universal.Context, Target = unknown> = (request: Request, context?: InContext, runtime?: RuntimeAdapterTarget<Target>) => Response | undefined | Promise<Response | undefined>;
|
|
@@ -58,22 +59,23 @@ declare function createIncomingMessage(request: Request): IncomingMessage;
|
|
|
58
59
|
* providing an object with the readable stream, headers, and status code.
|
|
59
60
|
*/
|
|
60
61
|
declare function createServerResponse(incomingMessage: IncomingMessage): {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
res: ServerResponse<IncomingMessage>;
|
|
63
|
+
onReadable: (cb: (result: {
|
|
64
|
+
readable: Readable;
|
|
65
|
+
headers: OutgoingHttpHeaders;
|
|
66
|
+
statusCode: number;
|
|
67
|
+
}) => void) => void;
|
|
67
68
|
};
|
|
68
|
-
|
|
69
|
-
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/router.d.ts
|
|
71
|
+
type App = Express$2;
|
|
70
72
|
type EnhancedMiddlewareExpress = EnhancedMiddleware | EnhancedMiddleware<Universal.Context, Universal.Context, "express">;
|
|
71
73
|
declare class UniversalExpressRouter<T extends App> extends UniversalRouter implements UniversalRouterInterface {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
74
|
+
#private;
|
|
75
|
+
constructor(app: T);
|
|
76
|
+
use(middleware: EnhancedMiddlewareExpress): this;
|
|
77
|
+
applyCatchAll(): this;
|
|
76
78
|
}
|
|
77
|
-
declare function apply(app: Express, middlewares: EnhancedMiddlewareExpress[]): void;
|
|
78
|
-
|
|
79
|
-
export { type App, type ConnectMiddleware, type ConnectMiddlewareBoolean, type DecoratedServerResponse, type NodeHandler, type NodeMiddleware, UniversalExpressRouter, type WebHandler, apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createServerResponse, getContext };
|
|
79
|
+
declare function apply(app: Express$2, middlewares: EnhancedMiddlewareExpress[]): void;
|
|
80
|
+
//#endregion
|
|
81
|
+
export { type App, type ConnectMiddleware, type ConnectMiddlewareBoolean, type DecoratedRequest, type DecoratedServerResponse, type NodeHandler, type NodeMiddleware, type UniversalExpressRouter, type WebHandler, apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createRequestAdapter, createServerResponse, getContext, sendResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,451 +1,400 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
} from "./chunk-N42HUXDK.js";
|
|
4
|
-
|
|
5
|
-
// src/common.ts
|
|
6
|
-
import { bindUniversal, contextSymbol, getAdapterRuntime, universalSymbol } from "@universal-middleware/core";
|
|
7
|
-
|
|
8
|
-
// src/const.ts
|
|
9
|
-
import { env, requestSymbol } from "@universal-middleware/node";
|
|
10
|
-
var pendingMiddlewaresSymbol = /* @__PURE__ */ Symbol.for("unPendingMiddlewares");
|
|
11
|
-
var wrappedResponseSymbol = /* @__PURE__ */ Symbol.for("unWrappedResponse");
|
|
12
|
-
|
|
13
|
-
// src/response.ts
|
|
1
|
+
import { createRequestAdapter } from "./request.js";
|
|
2
|
+
import { UniversalRouter, apply as apply$1, bindUniversal, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol } from "@universal-middleware/core";
|
|
14
3
|
import { responseAdapter, sendResponse, setResponseHeaders } from "@universal-middleware/node";
|
|
4
|
+
import { EventEmitter } from "node:events";
|
|
5
|
+
import { ServerResponse } from "node:http";
|
|
6
|
+
import { PassThrough, Readable } from "node:stream";
|
|
7
|
+
//#region src/const.ts
|
|
8
|
+
const pendingMiddlewaresSymbol = Symbol.for("unPendingMiddlewares");
|
|
9
|
+
const wrappedResponseSymbol = Symbol.for("unWrappedResponse");
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/response.ts
|
|
15
12
|
function createTransformStream() {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
ctrl.enqueue(chunk);
|
|
23
|
-
} else {
|
|
24
|
-
ctrl.enqueue(new Uint8Array(chunk));
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
});
|
|
13
|
+
const textEncoder = new TextEncoder();
|
|
14
|
+
return new TransformStream({ transform(chunk, ctrl) {
|
|
15
|
+
if (typeof chunk === "string") ctrl.enqueue(textEncoder.encode(chunk));
|
|
16
|
+
else if (chunk instanceof Uint8Array) ctrl.enqueue(chunk);
|
|
17
|
+
else ctrl.enqueue(new Uint8Array(chunk));
|
|
18
|
+
} });
|
|
28
19
|
}
|
|
29
20
|
function override(nodeResponse, key, forwardTo) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
original(...args) {
|
|
46
|
-
original.apply(nodeResponse, args);
|
|
47
|
-
},
|
|
48
|
-
restore() {
|
|
49
|
-
nodeResponse[key] = original;
|
|
50
|
-
}
|
|
51
|
-
};
|
|
21
|
+
const original = nodeResponse[key];
|
|
22
|
+
nodeResponse[key] = (...args) => {
|
|
23
|
+
if (!nodeResponse.headersSent) nodeResponse.writeHead(nodeResponse.statusCode);
|
|
24
|
+
if (args[0] && args[0].length > 0) forwardTo.write(args[0]).catch(console.error);
|
|
25
|
+
if (key === "end") forwardTo.close().catch(() => {});
|
|
26
|
+
return true;
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
original(...args) {
|
|
30
|
+
original.apply(nodeResponse, args);
|
|
31
|
+
},
|
|
32
|
+
restore() {
|
|
33
|
+
nodeResponse[key] = original;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
52
36
|
}
|
|
53
37
|
function overrideWriteHead(nodeResponse, callback) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
38
|
+
const original = nodeResponse.writeHead;
|
|
39
|
+
let alreadyCalled = false;
|
|
40
|
+
nodeResponse.writeHead = () => {
|
|
41
|
+
if (!alreadyCalled) {
|
|
42
|
+
callback().catch(console.error);
|
|
43
|
+
alreadyCalled = true;
|
|
44
|
+
}
|
|
45
|
+
return nodeResponse;
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
original(...args) {
|
|
49
|
+
original.apply(nodeResponse, args);
|
|
50
|
+
},
|
|
51
|
+
restore() {
|
|
52
|
+
nodeResponse.writeHead = original;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
71
55
|
}
|
|
72
56
|
function wrapResponse(nodeResponse, next) {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
original.end.original();
|
|
123
|
-
}
|
|
124
|
-
})
|
|
125
|
-
);
|
|
126
|
-
await wait;
|
|
127
|
-
original.write.restore();
|
|
128
|
-
original.end.restore();
|
|
129
|
-
}
|
|
57
|
+
if (nodeResponse[wrappedResponseSymbol]) return;
|
|
58
|
+
nodeResponse[wrappedResponseSymbol] = true;
|
|
59
|
+
const body = createTransformStream();
|
|
60
|
+
const writer = body.writable.getWriter();
|
|
61
|
+
const [reader1, reader2] = body.readable.tee();
|
|
62
|
+
const original = {
|
|
63
|
+
write: override(nodeResponse, "write", writer),
|
|
64
|
+
end: override(nodeResponse, "end", writer),
|
|
65
|
+
writeHead: overrideWriteHead(nodeResponse, triggerPendingMiddlewares)
|
|
66
|
+
};
|
|
67
|
+
async function triggerPendingMiddlewares() {
|
|
68
|
+
if (!nodeResponse[pendingMiddlewaresSymbol]) return;
|
|
69
|
+
const middlewares = nodeResponse[pendingMiddlewaresSymbol];
|
|
70
|
+
delete nodeResponse[pendingMiddlewaresSymbol];
|
|
71
|
+
let response;
|
|
72
|
+
try {
|
|
73
|
+
response = responseAdapter(nodeResponse, reader1);
|
|
74
|
+
for (const middleware of middlewares) {
|
|
75
|
+
const tmp = await middleware(response);
|
|
76
|
+
if (tmp) response = tmp;
|
|
77
|
+
}
|
|
78
|
+
} catch (e) {
|
|
79
|
+
response = void 0;
|
|
80
|
+
await writer.abort();
|
|
81
|
+
original.writeHead.restore();
|
|
82
|
+
original.write.restore();
|
|
83
|
+
original.end.restore();
|
|
84
|
+
if (next) next(e);
|
|
85
|
+
else throw e;
|
|
86
|
+
}
|
|
87
|
+
if (!response) return;
|
|
88
|
+
const readableToOriginal = response.body ?? reader2;
|
|
89
|
+
setResponseHeaders(response, nodeResponse, true);
|
|
90
|
+
original.writeHead.restore();
|
|
91
|
+
nodeResponse.flushHeaders();
|
|
92
|
+
await readableToOriginal.pipeTo(new WritableStream({
|
|
93
|
+
write(chunk) {
|
|
94
|
+
original.write.original(chunk);
|
|
95
|
+
},
|
|
96
|
+
close() {
|
|
97
|
+
original.end.original();
|
|
98
|
+
},
|
|
99
|
+
abort() {
|
|
100
|
+
original.end.original();
|
|
101
|
+
}
|
|
102
|
+
}));
|
|
103
|
+
original.write.restore();
|
|
104
|
+
original.end.restore();
|
|
105
|
+
}
|
|
130
106
|
}
|
|
131
|
-
|
|
132
|
-
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/common.ts
|
|
133
109
|
function nextOr404(res, next) {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
110
|
+
if (next) next();
|
|
111
|
+
else {
|
|
112
|
+
res.statusCode = 404;
|
|
113
|
+
res.end();
|
|
114
|
+
}
|
|
140
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Creates a request handler to be passed to http.createServer() or used as a
|
|
118
|
+
* middleware in Connect-style frameworks like Express.
|
|
119
|
+
*/
|
|
141
120
|
function createHandler(handlerFactory, options = {}) {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
next(error);
|
|
162
|
-
} else {
|
|
163
|
-
console.error(error);
|
|
164
|
-
if (!res.headersSent) {
|
|
165
|
-
res.statusCode = 500;
|
|
166
|
-
}
|
|
167
|
-
if (!res.writableEnded) {
|
|
168
|
-
res.end();
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
});
|
|
173
|
-
};
|
|
121
|
+
const requestAdapter = createRequestAdapter(options);
|
|
122
|
+
return (...args) => {
|
|
123
|
+
return bindUniversal(handlerFactory(...args), async function universalHandlerExpress(req, res, next) {
|
|
124
|
+
try {
|
|
125
|
+
req[contextSymbol] ??= {};
|
|
126
|
+
const request = requestAdapter(req, res);
|
|
127
|
+
const response = await this[universalSymbol](request, req[contextSymbol], getRuntime(req, res));
|
|
128
|
+
if (!response) nextOr404(res, next);
|
|
129
|
+
else await sendResponse(response, res);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (next) next(error);
|
|
132
|
+
else {
|
|
133
|
+
console.error(error);
|
|
134
|
+
if (!res.headersSent) res.statusCode = 500;
|
|
135
|
+
if (!res.writableEnded) res.end();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
};
|
|
174
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* Creates a middleware to be passed to Connect-style frameworks like Express
|
|
143
|
+
*/
|
|
175
144
|
function createMiddleware(middlewareFactory, options = {}) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
next(error);
|
|
208
|
-
} else {
|
|
209
|
-
console.error(error);
|
|
210
|
-
if (!res.headersSent) {
|
|
211
|
-
res.statusCode = 500;
|
|
212
|
-
}
|
|
213
|
-
if (!res.writableEnded) {
|
|
214
|
-
res.end();
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
});
|
|
219
|
-
};
|
|
145
|
+
const requestAdapter = createRequestAdapter(options);
|
|
146
|
+
return (...args) => {
|
|
147
|
+
return bindUniversal(middlewareFactory(...args), async function universalMiddlewareExpress(req, res, next) {
|
|
148
|
+
try {
|
|
149
|
+
req[contextSymbol] ??= {};
|
|
150
|
+
const request = requestAdapter(req, res);
|
|
151
|
+
const response = await this[universalSymbol](request, getContext(req), getRuntime(req, res));
|
|
152
|
+
if (!response) return nextOr404(res, next);
|
|
153
|
+
if (typeof response === "function") {
|
|
154
|
+
if (res.headersSent) throw new Error("Universal Middleware called after headers have been sent. Please open an issue at https://github.com/magne4000/universal-middleware");
|
|
155
|
+
if (req.complete === void 0) req.complete = req._readableState?.ended ?? true;
|
|
156
|
+
wrapResponse(res, next);
|
|
157
|
+
res[pendingMiddlewaresSymbol] ??= [];
|
|
158
|
+
res[pendingMiddlewaresSymbol].push(response);
|
|
159
|
+
return nextOr404(res, next);
|
|
160
|
+
}
|
|
161
|
+
if (response instanceof Response) await sendResponse(response, res);
|
|
162
|
+
else {
|
|
163
|
+
req[contextSymbol] = response;
|
|
164
|
+
return nextOr404(res, next);
|
|
165
|
+
}
|
|
166
|
+
} catch (error) {
|
|
167
|
+
if (next) next(error);
|
|
168
|
+
else {
|
|
169
|
+
console.error(error);
|
|
170
|
+
if (!res.headersSent) res.statusCode = 500;
|
|
171
|
+
if (!res.writableEnded) res.end();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
};
|
|
220
176
|
}
|
|
221
177
|
function getContext(req) {
|
|
222
|
-
|
|
178
|
+
return req[contextSymbol];
|
|
223
179
|
}
|
|
224
180
|
function getRuntime(request, response) {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
// biome-ignore lint/suspicious/noExplicitAny: cast
|
|
235
|
-
res: response
|
|
236
|
-
})
|
|
237
|
-
});
|
|
181
|
+
return getAdapterRuntime("express", {
|
|
182
|
+
params: request.params,
|
|
183
|
+
req: request,
|
|
184
|
+
res: response,
|
|
185
|
+
express: Object.freeze({
|
|
186
|
+
req: request,
|
|
187
|
+
res: response
|
|
188
|
+
})
|
|
189
|
+
});
|
|
238
190
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
import { ServerResponse } from "node:http";
|
|
250
|
-
import { PassThrough, Readable } from "node:stream";
|
|
251
|
-
var statusCodesWithoutBody = [
|
|
252
|
-
100,
|
|
253
|
-
// Continue
|
|
254
|
-
101,
|
|
255
|
-
// Switching Protocols
|
|
256
|
-
102,
|
|
257
|
-
// Processing (WebDAV)
|
|
258
|
-
103,
|
|
259
|
-
// Early Hints
|
|
260
|
-
204,
|
|
261
|
-
// No Content
|
|
262
|
-
205,
|
|
263
|
-
// Reset Content
|
|
264
|
-
304
|
|
265
|
-
// Not Modified
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/utils.ts
|
|
193
|
+
const statusCodesWithoutBody = [
|
|
194
|
+
100,
|
|
195
|
+
101,
|
|
196
|
+
102,
|
|
197
|
+
103,
|
|
198
|
+
204,
|
|
199
|
+
205,
|
|
200
|
+
304
|
|
266
201
|
];
|
|
202
|
+
/**
|
|
203
|
+
* Converts a Connect-style middleware to a web-compatible request handler.
|
|
204
|
+
* @beta
|
|
205
|
+
*/
|
|
267
206
|
function connectToWeb(handler) {
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
const handled = await handler(req, res, next);
|
|
300
|
-
if (handled === false) {
|
|
301
|
-
res.destroy();
|
|
302
|
-
stopForwardingAbort?.();
|
|
303
|
-
resolve(void 0);
|
|
304
|
-
}
|
|
305
|
-
} catch (e) {
|
|
306
|
-
next(e);
|
|
307
|
-
}
|
|
308
|
-
});
|
|
309
|
-
};
|
|
207
|
+
return async (request, _context, runtime) => {
|
|
208
|
+
const realReq = runtime && "req" in runtime && runtime.req || request.runtime?.node?.req;
|
|
209
|
+
const req = realReq ?? createIncomingMessage(request);
|
|
210
|
+
const { res, onReadable } = createServerResponse(req);
|
|
211
|
+
const stopForwardingAbort = realReq ? void 0 : forwardAbort(request.signal, req, res);
|
|
212
|
+
return new Promise(async (resolve, reject) => {
|
|
213
|
+
onReadable(({ readable, headers, statusCode }) => {
|
|
214
|
+
const hasBody = !statusCodesWithoutBody.includes(statusCode);
|
|
215
|
+
if (stopForwardingAbort) if (hasBody) readable.once("close", stopForwardingAbort);
|
|
216
|
+
else stopForwardingAbort();
|
|
217
|
+
resolve(new Response(hasBody ? toWebStream(readable) : null, {
|
|
218
|
+
status: statusCode,
|
|
219
|
+
headers: flattenHeaders(headers)
|
|
220
|
+
}));
|
|
221
|
+
});
|
|
222
|
+
const next = (error) => {
|
|
223
|
+
stopForwardingAbort?.();
|
|
224
|
+
if (error) reject(error instanceof Error ? error : new Error(String(error)));
|
|
225
|
+
else resolve(void 0);
|
|
226
|
+
};
|
|
227
|
+
try {
|
|
228
|
+
if (await handler(req, res, next) === false) {
|
|
229
|
+
res.destroy();
|
|
230
|
+
stopForwardingAbort?.();
|
|
231
|
+
resolve(void 0);
|
|
232
|
+
}
|
|
233
|
+
} catch (e) {
|
|
234
|
+
next(e);
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
};
|
|
310
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* Creates an IncomingMessage object from a web Request.
|
|
241
|
+
* @beta
|
|
242
|
+
*/
|
|
311
243
|
function createIncomingMessage(request) {
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
244
|
+
const url = new URL(request.url, "http://localhost");
|
|
245
|
+
const body = request.body ? Readable.fromWeb(request.body) : Readable.from([]);
|
|
246
|
+
const headers = Object.fromEntries(request.headers);
|
|
247
|
+
if (request.body && headers["content-length"] === void 0) headers["transfer-encoding"] = "chunked";
|
|
248
|
+
const message = Object.assign(body, {
|
|
249
|
+
url: url.pathname + url.search,
|
|
250
|
+
method: request.method,
|
|
251
|
+
headers,
|
|
252
|
+
rawHeaders: Object.entries(headers).flat(),
|
|
253
|
+
httpVersion: "1.1",
|
|
254
|
+
httpVersionMajor: 1,
|
|
255
|
+
httpVersionMinor: 1,
|
|
256
|
+
complete: !request.body,
|
|
257
|
+
socket: Object.assign(new EventEmitter(), {
|
|
258
|
+
encrypted: url.protocol === "https:",
|
|
259
|
+
readable: true
|
|
260
|
+
})
|
|
261
|
+
});
|
|
262
|
+
message.once("end", () => {
|
|
263
|
+
message.complete = true;
|
|
264
|
+
});
|
|
265
|
+
return message;
|
|
320
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* Creates a custom ServerResponse object that allows for intercepting and streaming the response.
|
|
269
|
+
*
|
|
270
|
+
* @beta
|
|
271
|
+
* @returns
|
|
272
|
+
* An object containing:
|
|
273
|
+
* - res: The custom ServerResponse object.
|
|
274
|
+
* - onReadable: A function that takes a callback. The callback is invoked when the response is readable,
|
|
275
|
+
* providing an object with the readable stream, headers, and status code.
|
|
276
|
+
*/
|
|
321
277
|
function createServerResponse(incomingMessage) {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
278
|
+
const res = new ServerResponse(incomingMessage);
|
|
279
|
+
const passThrough = new PassThrough();
|
|
280
|
+
let handled = false;
|
|
281
|
+
const onReadable = (cb) => {
|
|
282
|
+
const handleReadable = () => {
|
|
283
|
+
if (handled) return;
|
|
284
|
+
handled = true;
|
|
285
|
+
cb({
|
|
286
|
+
readable: Readable.from(passThrough),
|
|
287
|
+
headers: res.getHeaders(),
|
|
288
|
+
statusCode: res.statusCode
|
|
289
|
+
});
|
|
290
|
+
};
|
|
291
|
+
passThrough.once("readable", handleReadable);
|
|
292
|
+
passThrough.once("end", handleReadable);
|
|
293
|
+
};
|
|
294
|
+
passThrough.once("finish", () => {
|
|
295
|
+
res.emit("finish");
|
|
296
|
+
});
|
|
297
|
+
passThrough.once("close", () => {
|
|
298
|
+
res.destroy();
|
|
299
|
+
res.emit("close");
|
|
300
|
+
});
|
|
301
|
+
passThrough.on("drain", () => {
|
|
302
|
+
res.emit("drain");
|
|
303
|
+
});
|
|
304
|
+
res.write = passThrough.write.bind(passThrough);
|
|
305
|
+
res.end = passThrough.end.bind(passThrough);
|
|
306
|
+
res.writeHead = function writeHead(statusCode, statusMessage, headers) {
|
|
307
|
+
res.statusCode = statusCode;
|
|
308
|
+
if (typeof statusMessage === "object") {
|
|
309
|
+
headers = statusMessage;
|
|
310
|
+
statusMessage = void 0;
|
|
311
|
+
}
|
|
312
|
+
if (headers) {
|
|
313
|
+
for (const [key, value] of Object.entries(headers)) if (value !== void 0) res.setHeader(key, value);
|
|
314
|
+
}
|
|
315
|
+
return res;
|
|
316
|
+
};
|
|
317
|
+
return {
|
|
318
|
+
res,
|
|
319
|
+
onReadable
|
|
320
|
+
};
|
|
365
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* Bridges a web `AbortSignal` to a synthetic Node `req`/`res` and returns a stop function.
|
|
324
|
+
*
|
|
325
|
+
* `createRequestAdapter` derives the handler's `request.signal` from `res`'s "close" event,
|
|
326
|
+
* which a socketless `ServerResponse` never emits on its own — so emit it explicitly.
|
|
327
|
+
*/
|
|
366
328
|
function forwardAbort(signal, req, res) {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
329
|
+
let active = true;
|
|
330
|
+
const abort = () => {
|
|
331
|
+
if (!active) return;
|
|
332
|
+
active = false;
|
|
333
|
+
res.emit("close");
|
|
334
|
+
req.destroy();
|
|
335
|
+
};
|
|
336
|
+
if (signal.aborted) queueMicrotask(abort);
|
|
337
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
338
|
+
return () => {
|
|
339
|
+
active = false;
|
|
340
|
+
signal.removeEventListener("abort", abort);
|
|
341
|
+
};
|
|
380
342
|
}
|
|
381
343
|
function toWebStream(readable) {
|
|
382
|
-
|
|
383
|
-
// biome-ignore lint/suspicious/noExplicitAny: Web/Node stream type clash
|
|
384
|
-
ReadableStream.from(readable)
|
|
385
|
-
) : (
|
|
386
|
-
// biome-ignore lint/suspicious/noExplicitAny: Web/Node stream type clash
|
|
387
|
-
Readable.toWeb(readable)
|
|
388
|
-
);
|
|
344
|
+
return "from" in ReadableStream ? ReadableStream.from(readable) : Readable.toWeb(readable);
|
|
389
345
|
}
|
|
346
|
+
/** Connection-specific headers: they describe one transport hop, not the message (RFC 9110 §7.6.1). */
|
|
347
|
+
const HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
|
|
348
|
+
"connection",
|
|
349
|
+
"keep-alive",
|
|
350
|
+
"proxy-authenticate",
|
|
351
|
+
"proxy-authorization",
|
|
352
|
+
"te",
|
|
353
|
+
"trailer",
|
|
354
|
+
"transfer-encoding",
|
|
355
|
+
"upgrade"
|
|
356
|
+
]);
|
|
390
357
|
function flattenHeaders(headers) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
} else {
|
|
403
|
-
flatHeaders.push([key, String(value)]);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
return flatHeaders;
|
|
358
|
+
const flatHeaders = [];
|
|
359
|
+
const connectionTokens = String(headers.connection ?? "").split(",");
|
|
360
|
+
const dropped = /* @__PURE__ */ new Set([...HOP_BY_HOP_HEADERS, ...connectionTokens.map((name) => name.trim().toLowerCase())]);
|
|
361
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
362
|
+
if (value === void 0 || value === null) continue;
|
|
363
|
+
if (dropped.has(key.toLowerCase())) continue;
|
|
364
|
+
if (Array.isArray(value)) {
|
|
365
|
+
for (const v of value) if (v != null) flatHeaders.push([key, String(v)]);
|
|
366
|
+
} else flatHeaders.push([key, String(value)]);
|
|
367
|
+
}
|
|
368
|
+
return flatHeaders;
|
|
407
369
|
}
|
|
408
370
|
function isExpressV4(app) {
|
|
409
|
-
|
|
371
|
+
return "del" in app;
|
|
410
372
|
}
|
|
411
373
|
function isExpressV5(app) {
|
|
412
|
-
|
|
374
|
+
return !isExpressV4(app);
|
|
413
375
|
}
|
|
414
|
-
|
|
415
|
-
|
|
376
|
+
//#endregion
|
|
377
|
+
//#region src/router.ts
|
|
416
378
|
var UniversalExpressRouter = class extends UniversalRouter {
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
this.#app.all("/**", createHandler(() => this[universalSymbol2])());
|
|
432
|
-
}
|
|
433
|
-
return this;
|
|
434
|
-
}
|
|
379
|
+
#app;
|
|
380
|
+
constructor(app) {
|
|
381
|
+
super(false);
|
|
382
|
+
this.#app = app;
|
|
383
|
+
}
|
|
384
|
+
use(middleware) {
|
|
385
|
+
this.#app.use(createMiddleware(() => getUniversal(middleware))());
|
|
386
|
+
return this;
|
|
387
|
+
}
|
|
388
|
+
applyCatchAll() {
|
|
389
|
+
if (isExpressV5(this.#app)) this.#app.all("/{*catchAll}", createHandler(() => this[universalSymbol])());
|
|
390
|
+
if (isExpressV4(this.#app)) this.#app.all("/**", createHandler(() => this[universalSymbol])());
|
|
391
|
+
return this;
|
|
392
|
+
}
|
|
435
393
|
};
|
|
436
394
|
function apply(app, middlewares) {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
395
|
+
const router = new UniversalExpressRouter(app);
|
|
396
|
+
apply$1(router, middlewares, true);
|
|
397
|
+
Promise.resolve().then(() => router.applyCatchAll());
|
|
440
398
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
connectToWeb,
|
|
444
|
-
createHandler,
|
|
445
|
-
createIncomingMessage,
|
|
446
|
-
createMiddleware,
|
|
447
|
-
createRequestAdapter,
|
|
448
|
-
createServerResponse,
|
|
449
|
-
getContext,
|
|
450
|
-
sendResponse
|
|
451
|
-
};
|
|
399
|
+
//#endregion
|
|
400
|
+
export { apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createRequestAdapter, createServerResponse, getContext, sendResponse };
|
package/dist/request.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import { DecoratedRequest, NodeRequestAdapterOptions, PossiblyEncryptedSocket, createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
2
|
+
export { type DecoratedRequest, type NodeRequestAdapterOptions, type PossiblyEncryptedSocket, createRequestAdapter, env, requestSymbol };
|
package/dist/request.js
CHANGED
|
@@ -1,10 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
env,
|
|
4
|
-
requestSymbol
|
|
5
|
-
} from "./chunk-N42HUXDK.js";
|
|
6
|
-
export {
|
|
7
|
-
createRequestAdapter,
|
|
8
|
-
env,
|
|
9
|
-
requestSymbol
|
|
10
|
-
};
|
|
1
|
+
import { createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
2
|
+
export { createRequestAdapter, env, requestSymbol };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@universal-middleware/express",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.31",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Express adapter for universal middlewares",
|
|
6
6
|
"files": [
|
|
@@ -18,22 +18,23 @@
|
|
|
18
18
|
"license": "MIT",
|
|
19
19
|
"dependencies": {
|
|
20
20
|
"@universal-middleware/core": "^0.4.18",
|
|
21
|
-
"@universal-middleware/node": "^0.2.
|
|
21
|
+
"@universal-middleware/node": "^0.2.2"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@swc/core": "^1.15.
|
|
24
|
+
"@swc/core": "^1.15.43",
|
|
25
25
|
"@types/express": "^5.0.6",
|
|
26
26
|
"@types/express4": "npm:@types/express@^4.17.25",
|
|
27
27
|
"@types/node": "^20.19.35",
|
|
28
28
|
"express": "^5.2.1",
|
|
29
29
|
"express4": "npm:express@^4.22.2",
|
|
30
|
-
"helmet": "^8.
|
|
30
|
+
"helmet": "^8.3.0",
|
|
31
31
|
"rimraf": "^6.1.3",
|
|
32
|
-
"
|
|
33
|
-
"tsx": "^4.
|
|
34
|
-
"typescript": "^
|
|
35
|
-
"vite": "^8.
|
|
36
|
-
"vitest": "^4.1.
|
|
32
|
+
"tsdown": "^0.22.13",
|
|
33
|
+
"tsx": "^4.23.1",
|
|
34
|
+
"typescript": "^7.0.2",
|
|
35
|
+
"vite": "^8.1.5",
|
|
36
|
+
"vitest": "^4.1.10",
|
|
37
|
+
"@universal-middleware/tsdown-config": "0.0.0",
|
|
37
38
|
"@universal-middleware/tests": "0.0.2"
|
|
38
39
|
},
|
|
39
40
|
"sideEffects": false,
|
|
@@ -49,8 +50,8 @@
|
|
|
49
50
|
"request-handling"
|
|
50
51
|
],
|
|
51
52
|
"scripts": {
|
|
52
|
-
"build": "
|
|
53
|
-
"dev": "
|
|
53
|
+
"build": "tsdown",
|
|
54
|
+
"dev": "tsdown --watch",
|
|
54
55
|
"test": "vitest run",
|
|
55
56
|
"test:run-express:node": "tsx tests/entry-express.ts",
|
|
56
57
|
"test:run-express:bun": "bun tests/entry-express.ts",
|