express-file-cluster 0.10.0 → 0.11.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/dist/auth/index.cjs +7 -6
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +3 -1
- package/dist/auth/index.d.ts +3 -1
- package/dist/auth/index.js +5 -5
- package/dist/{chunk-73XJUT2S.js → chunk-2IDRC7RK.js} +163 -5
- package/dist/chunk-2IDRC7RK.js.map +1 -0
- package/dist/{chunk-QDEDOHP7.js → chunk-336IU55W.js} +9 -42
- package/dist/chunk-336IU55W.js.map +1 -0
- package/dist/{chunk-R52CUEGT.js → chunk-3SWI46YK.js} +2 -2
- package/dist/{chunk-7KO4DJRJ.cjs → chunk-6WTMRZS7.cjs} +14 -14
- package/dist/{chunk-7KO4DJRJ.cjs.map → chunk-6WTMRZS7.cjs.map} +1 -1
- package/dist/chunk-AGOYTFRO.cjs +42 -0
- package/dist/chunk-AGOYTFRO.cjs.map +1 -0
- package/dist/{chunk-RAB44UGX.js → chunk-B6MB6HEG.js} +1 -1
- package/dist/chunk-CGY7JU4Y.cjs +8 -0
- package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
- package/dist/chunk-DGYPIIJE.cjs +845 -0
- package/dist/chunk-DGYPIIJE.cjs.map +1 -0
- package/dist/{chunk-EGSSZUVO.js → chunk-DN4TCGYB.js} +38 -11
- package/dist/chunk-DN4TCGYB.js.map +1 -0
- package/dist/{chunk-YK4ZM3CA.cjs → chunk-DTMDJGRW.cjs} +15 -15
- package/dist/{chunk-YK4ZM3CA.cjs.map → chunk-DTMDJGRW.cjs.map} +1 -1
- package/dist/{chunk-R4XO4SVM.js → chunk-EJDZZ4KX.js} +4 -4
- package/dist/{chunk-NKLOE4AK.cjs → chunk-GWMW6XY7.cjs} +20 -53
- package/dist/chunk-GWMW6XY7.cjs.map +1 -0
- package/dist/{chunk-GBI77W5T.cjs → chunk-H2PVWCWC.cjs} +1 -1
- package/dist/{chunk-GBI77W5T.cjs.map → chunk-H2PVWCWC.cjs.map} +1 -1
- package/dist/{chunk-KFVFP2Q7.cjs → chunk-IEF6AEK3.cjs} +70 -55
- package/dist/chunk-IEF6AEK3.cjs.map +1 -0
- package/dist/{chunk-PGJQK36V.js → chunk-JBOMTZT5.js} +7 -5
- package/dist/{chunk-PGJQK36V.js.map → chunk-JBOMTZT5.js.map} +1 -1
- package/dist/chunk-LECHRAU3.js +845 -0
- package/dist/chunk-LECHRAU3.js.map +1 -0
- package/dist/{chunk-4DOHQU6I.cjs → chunk-M53GODCX.cjs} +39 -12
- package/dist/chunk-M53GODCX.cjs.map +1 -0
- package/dist/{chunk-NI2BNGGV.js → chunk-O2E7H2XA.js} +2 -2
- package/dist/{chunk-ATVD2HGC.js → chunk-OM2XJJWX.js} +4 -4
- package/dist/{chunk-DUADUR6R.cjs → chunk-QSIP7YLW.cjs} +172 -14
- package/dist/chunk-QSIP7YLW.cjs.map +1 -0
- package/dist/{chunk-7KC2H76D.js → chunk-R6GPQZLI.js} +62 -47
- package/dist/chunk-R6GPQZLI.js.map +1 -0
- package/dist/{chunk-WBLUGOAG.cjs → chunk-RPL2IFWK.cjs} +8 -5
- package/dist/chunk-RPL2IFWK.cjs.map +1 -0
- package/dist/{chunk-HBCY7ILD.cjs → chunk-SOU3PBJC.cjs} +97 -95
- package/dist/chunk-SOU3PBJC.cjs.map +1 -0
- package/dist/{chunk-DCJOWFVD.cjs → chunk-WHBSVYUY.cjs} +3 -3
- package/dist/{chunk-DCJOWFVD.cjs.map → chunk-WHBSVYUY.cjs.map} +1 -1
- package/dist/chunk-XPY5TQDK.js +42 -0
- package/dist/chunk-XPY5TQDK.js.map +1 -0
- package/dist/cli/db-runner.cjs +81 -42
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +54 -16
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +23 -25
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +12 -17
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +23 -0
- package/dist/docs/api-reference/compose.md +1 -1
- package/dist/docs/api-reference/db.md +8 -0
- package/dist/docs/api-reference/ignite.md +8 -1
- package/dist/docs/api-reference/openapi.md +36 -0
- package/dist/docs/api-reference/testing.md +28 -0
- package/dist/docs/api-reference/websockets.md +23 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/core-concepts/clustering.md +2 -0
- package/dist/docs/core-concepts/file-based-routing.md +4 -0
- package/dist/docs/core-concepts/middleware.md +2 -2
- package/dist/docs/getting-started/index.md +4 -0
- package/dist/docs/guides/authentication.md +33 -0
- package/dist/docs/guides/caching.md +2 -0
- package/dist/docs/guides/database.md +15 -0
- package/dist/docs/guides/environment-variables.md +6 -0
- package/dist/docs/guides/feature-matrix.md +9 -0
- package/dist/docs/guides/generated-portals.md +3 -1
- package/dist/docs/guides/logging.md +17 -0
- package/dist/docs/guides/migrations.md +4 -2
- package/dist/docs/guides/openapi.md +57 -0
- package/dist/docs/guides/testing.md +31 -0
- package/dist/docs/guides/validation.md +2 -0
- package/dist/docs/guides/websockets.md +60 -0
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +8 -2
- package/dist/docs/skills/api-surface.md +30 -4
- package/dist/docs/skills/auth-internals.md +14 -1
- package/dist/docs/skills/pre-flight.md +8 -0
- package/dist/docs/skills/routing-rules.md +5 -1
- package/dist/docs/skills/what-not-to-invent.md +11 -1
- package/dist/docs/versioning.md +1 -1
- package/dist/index.cjs +100 -267
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -3
- package/dist/index.d.ts +28 -3
- package/dist/index.js +52 -221
- package/dist/index.js.map +1 -1
- package/dist/openapi-cjs.cjs +5 -0
- package/dist/pgboss-backend-PQW6I3VF.js +14 -0
- package/dist/pgboss-backend-QVXISTLP.cjs +15 -0
- package/dist/pgboss-backend-QVXISTLP.cjs.map +1 -0
- package/dist/registry/index.json +27 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/account-security.json +1 -1
- package/dist/registry/js-mongo-collection/admin-users.json +1 -1
- package/dist/registry/js-mongo-collection/auth.json +1 -1
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -1
- package/dist/registry/js-mongo-collection/auth@google.json +1 -1
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -1
- package/dist/registry/js-mongo-collection/user-profile.json +1 -1
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/account-security.json +1 -1
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -1
- package/dist/registry/ts-mongo-collection/auth.json +1 -1
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -1
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -1
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -1
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -1
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +3 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +3 -1
- package/dist/tasks/index.d.ts +3 -1
- package/dist/tasks/index.js +1 -1
- package/dist/testing-cjs.cjs +5 -0
- package/dist/testing.cjs +65 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +30 -0
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +64 -0
- package/dist/testing.js.map +1 -0
- package/dist/thread-runner.cjs +4 -3
- package/dist/thread-runner.cjs.map +1 -1
- package/dist/thread-runner.js +2 -2
- package/dist/{types-Bnxvj3l0.d.ts → types-D3QmZgeX.d.cts} +88 -2
- package/dist/{types-Bnxvj3l0.d.cts → types-D3QmZgeX.d.ts} +88 -2
- package/package.json +11 -4
- package/dist/chunk-4DOHQU6I.cjs.map +0 -1
- package/dist/chunk-73XJUT2S.js.map +0 -1
- package/dist/chunk-7KC2H76D.js.map +0 -1
- package/dist/chunk-DUADUR6R.cjs.map +0 -1
- package/dist/chunk-EGSSZUVO.js.map +0 -1
- package/dist/chunk-HBCY7ILD.cjs.map +0 -1
- package/dist/chunk-KFVFP2Q7.cjs.map +0 -1
- package/dist/chunk-NKLOE4AK.cjs.map +0 -1
- package/dist/chunk-QDEDOHP7.js.map +0 -1
- package/dist/chunk-WBLUGOAG.cjs.map +0 -1
- package/dist/pgboss-backend-FW42SBSM.js +0 -14
- package/dist/pgboss-backend-RVHUBJTU.cjs +0 -14
- package/dist/pgboss-backend-RVHUBJTU.cjs.map +0 -1
- /package/dist/{chunk-R52CUEGT.js.map → chunk-3SWI46YK.js.map} +0 -0
- /package/dist/{chunk-RAB44UGX.js.map → chunk-B6MB6HEG.js.map} +0 -0
- /package/dist/{chunk-R4XO4SVM.js.map → chunk-EJDZZ4KX.js.map} +0 -0
- /package/dist/{chunk-NI2BNGGV.js.map → chunk-O2E7H2XA.js.map} +0 -0
- /package/dist/{chunk-ATVD2HGC.js.map → chunk-OM2XJJWX.js.map} +0 -0
- /package/dist/{pgboss-backend-FW42SBSM.js.map → pgboss-backend-PQW6I3VF.js.map} +0 -0
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
import {
|
|
2
|
+
scanDir
|
|
3
|
+
} from "./chunk-O2E7H2XA.js";
|
|
4
|
+
import {
|
|
5
|
+
isHttpError
|
|
6
|
+
} from "./chunk-XPY5TQDK.js";
|
|
7
|
+
import {
|
|
8
|
+
getLogger,
|
|
9
|
+
getRequestContext,
|
|
10
|
+
processState,
|
|
11
|
+
requestLogger,
|
|
12
|
+
runWithContext
|
|
13
|
+
} from "./chunk-2IDRC7RK.js";
|
|
14
|
+
|
|
15
|
+
// src/websocket.ts
|
|
16
|
+
import http from "http";
|
|
17
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
18
|
+
var UPGRADE = /* @__PURE__ */ Symbol.for("express-file-cluster.websocket-upgrade.v1");
|
|
19
|
+
var servers = processState("websocket-servers", () => /* @__PURE__ */ new WeakMap());
|
|
20
|
+
var isUpgrade = (req) => !!req[UPGRADE];
|
|
21
|
+
var websocketOnly = (req, res, next) => {
|
|
22
|
+
const upgrade = req[UPGRADE];
|
|
23
|
+
if (!upgrade) return next("route");
|
|
24
|
+
const origin = req.headers.origin;
|
|
25
|
+
if (origin !== void 0) {
|
|
26
|
+
let valid = false;
|
|
27
|
+
try {
|
|
28
|
+
const parsed = new URL(origin);
|
|
29
|
+
valid = parsed.origin === origin && ["http:", "https:"].includes(parsed.protocol) && (upgrade.options.origins ? upgrade.options.origins.includes(origin) : origin === `${req.protocol}://${req.get("host")}`);
|
|
30
|
+
} catch {
|
|
31
|
+
}
|
|
32
|
+
if (!valid) {
|
|
33
|
+
res.status(403).json({ error: "WebSocket origin rejected" });
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
next();
|
|
38
|
+
};
|
|
39
|
+
function websocketHandler(handler) {
|
|
40
|
+
return (req, res) => {
|
|
41
|
+
req[UPGRADE].accept(handler, req, res);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function attachWebSockets(server, app, options = {}) {
|
|
45
|
+
if (servers.has(server)) throw new Error("[EFC] WebSockets already attached to this server");
|
|
46
|
+
const maxPayload = options.maxPayload ?? 1024 * 1024;
|
|
47
|
+
const heartbeat = options.heartbeatIntervalMs ?? 3e4;
|
|
48
|
+
const timeout = options.handshakeTimeoutMs ?? 1e4;
|
|
49
|
+
for (const [name, value, minimum] of [
|
|
50
|
+
["maxPayload", maxPayload, 1],
|
|
51
|
+
["heartbeatIntervalMs", heartbeat, 0],
|
|
52
|
+
["handshakeTimeoutMs", timeout, 1]
|
|
53
|
+
]) {
|
|
54
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > 2147483647)
|
|
55
|
+
throw new Error(`[EFC] websocket.${name} must be an integer from ${minimum} to 2147483647`);
|
|
56
|
+
}
|
|
57
|
+
for (const origin of options.origins ?? []) {
|
|
58
|
+
const parsed = new URL(origin);
|
|
59
|
+
if (parsed.origin !== origin || !["http:", "https:"].includes(parsed.protocol))
|
|
60
|
+
throw new Error("[EFC] websocket.origins must contain HTTP(S) origins");
|
|
61
|
+
}
|
|
62
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload, perMessageDeflate: false });
|
|
63
|
+
const reserved = /* @__PURE__ */ new Set([
|
|
64
|
+
"upgrade",
|
|
65
|
+
"connection",
|
|
66
|
+
"sec-websocket-accept",
|
|
67
|
+
"sec-websocket-protocol",
|
|
68
|
+
"sec-websocket-extensions",
|
|
69
|
+
"content-length",
|
|
70
|
+
"transfer-encoding",
|
|
71
|
+
"content-type"
|
|
72
|
+
]);
|
|
73
|
+
wss.on("headers", (headers, incoming) => {
|
|
74
|
+
const response = incoming.res;
|
|
75
|
+
for (const [name, value] of Object.entries(response?.getHeaders() ?? {})) {
|
|
76
|
+
if (reserved.has(name.toLowerCase()) || value === void 0) continue;
|
|
77
|
+
for (const entry of Array.isArray(value) ? value : [value])
|
|
78
|
+
headers.push(name + ": " + String(entry));
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
const alive = /* @__PURE__ */ new WeakSet();
|
|
82
|
+
const interval = heartbeat ? setInterval(() => {
|
|
83
|
+
for (const client of wss.clients) {
|
|
84
|
+
if (!alive.has(client)) {
|
|
85
|
+
client.terminate();
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
alive.delete(client);
|
|
89
|
+
if (client.readyState === WebSocket.OPEN) client.ping();
|
|
90
|
+
}
|
|
91
|
+
}, heartbeat) : void 0;
|
|
92
|
+
interval?.unref();
|
|
93
|
+
const state = {
|
|
94
|
+
wss,
|
|
95
|
+
pending: /* @__PURE__ */ new Set(),
|
|
96
|
+
stopHeartbeat: () => {
|
|
97
|
+
if (interval) clearInterval(interval);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
servers.set(server, state);
|
|
101
|
+
server.on("upgrade", (incoming, socket, head) => {
|
|
102
|
+
if (state.closing) {
|
|
103
|
+
socket.destroy();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const req = incoming;
|
|
107
|
+
const response = new http.ServerResponse(incoming);
|
|
108
|
+
try {
|
|
109
|
+
response.assignSocket(socket);
|
|
110
|
+
} catch {
|
|
111
|
+
socket.destroy();
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
state.pending.add(socket);
|
|
115
|
+
const onError = () => socket.destroy();
|
|
116
|
+
socket.on("error", onError);
|
|
117
|
+
const timer = setTimeout(() => {
|
|
118
|
+
if (!response.headersSent)
|
|
119
|
+
response.status(408).json({ error: "WebSocket upgrade timed out" });
|
|
120
|
+
socket.end();
|
|
121
|
+
}, timeout);
|
|
122
|
+
timer.unref();
|
|
123
|
+
socket.once("close", () => {
|
|
124
|
+
state.pending.delete(socket);
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
socket.removeListener("error", onError);
|
|
127
|
+
});
|
|
128
|
+
const upgrade = {
|
|
129
|
+
options,
|
|
130
|
+
accepted: false,
|
|
131
|
+
accept(handler, request, res) {
|
|
132
|
+
if (upgrade.accepted || res.headersSent || socket.destroyed || state.closing) return;
|
|
133
|
+
upgrade.accepted = true;
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
wss.handleUpgrade(incoming, socket, head, (ws) => {
|
|
136
|
+
state.pending.delete(socket);
|
|
137
|
+
res.detachSocket(socket);
|
|
138
|
+
res.statusCode = 101;
|
|
139
|
+
res.emit("finish");
|
|
140
|
+
socket.removeListener("error", onError);
|
|
141
|
+
alive.add(ws);
|
|
142
|
+
ws.on("pong", () => alive.add(ws));
|
|
143
|
+
const context = {
|
|
144
|
+
...getRequestContext(),
|
|
145
|
+
user: request.user
|
|
146
|
+
};
|
|
147
|
+
const emit = ws.emit;
|
|
148
|
+
ws.emit = ((event, ...args) => runWithContext(
|
|
149
|
+
{ ...context, queryCounts: /* @__PURE__ */ new Map() },
|
|
150
|
+
() => Reflect.apply(emit, ws, [event, ...args])
|
|
151
|
+
));
|
|
152
|
+
ws.on("error", (error) => getLogger().warn({ err: error }, "WebSocket error"));
|
|
153
|
+
const failed = (error) => {
|
|
154
|
+
getLogger().error({ err: error }, "WebSocket handler failed");
|
|
155
|
+
ws.close(1011, "Internal Server Error");
|
|
156
|
+
};
|
|
157
|
+
try {
|
|
158
|
+
void Promise.resolve(
|
|
159
|
+
runWithContext(context, () => {
|
|
160
|
+
wss.emit("connection", ws, incoming);
|
|
161
|
+
return handler(ws, request);
|
|
162
|
+
})
|
|
163
|
+
).catch(failed);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
failed(error);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
req[UPGRADE] = upgrade;
|
|
171
|
+
response.once("finish", () => {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
if (!upgrade.accepted) socket.end();
|
|
174
|
+
});
|
|
175
|
+
app(req, response);
|
|
176
|
+
});
|
|
177
|
+
const close = server.close;
|
|
178
|
+
server.close = function(callback) {
|
|
179
|
+
void closeWebSockets(server);
|
|
180
|
+
return close.call(this, callback);
|
|
181
|
+
};
|
|
182
|
+
server.once("close", () => {
|
|
183
|
+
state.stopHeartbeat();
|
|
184
|
+
});
|
|
185
|
+
return wss;
|
|
186
|
+
}
|
|
187
|
+
function closeWebSockets(server, timeoutMs = 1e3) {
|
|
188
|
+
const state = servers.get(server);
|
|
189
|
+
if (!state) return Promise.resolve();
|
|
190
|
+
if (state.closing) return state.closing;
|
|
191
|
+
state.stopHeartbeat();
|
|
192
|
+
state.closing = new Promise((resolve) => {
|
|
193
|
+
for (const socket of state.pending) socket.destroy();
|
|
194
|
+
state.pending.clear();
|
|
195
|
+
const timer = setTimeout(() => {
|
|
196
|
+
for (const client of state.wss.clients) client.terminate();
|
|
197
|
+
}, timeoutMs);
|
|
198
|
+
timer.unref();
|
|
199
|
+
state.wss.close(() => {
|
|
200
|
+
clearTimeout(timer);
|
|
201
|
+
resolve();
|
|
202
|
+
});
|
|
203
|
+
for (const client of state.wss.clients) client.close(1001, "Server shutting down");
|
|
204
|
+
});
|
|
205
|
+
return state.closing;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/router/validate.ts
|
|
209
|
+
var LOCATIONS = ["params", "query", "body"];
|
|
210
|
+
function isRequestSchema(value) {
|
|
211
|
+
return value != null && typeof value === "object" && LOCATIONS.some((loc) => loc in value);
|
|
212
|
+
}
|
|
213
|
+
function schemaFor(schema, method) {
|
|
214
|
+
if (!schema) return void 0;
|
|
215
|
+
const byMethod = schema[method];
|
|
216
|
+
if (isRequestSchema(byMethod)) return byMethod;
|
|
217
|
+
return isRequestSchema(schema) ? schema : void 0;
|
|
218
|
+
}
|
|
219
|
+
function pathToString(path2) {
|
|
220
|
+
if (!path2) return "";
|
|
221
|
+
return path2.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).map(String).join(".");
|
|
222
|
+
}
|
|
223
|
+
async function run(validator, input) {
|
|
224
|
+
const std = validator["~standard"];
|
|
225
|
+
if (std && typeof std.validate === "function") {
|
|
226
|
+
return await std.validate(input);
|
|
227
|
+
}
|
|
228
|
+
const v = validator;
|
|
229
|
+
const parse = v.safeParseAsync ?? v.safeParse;
|
|
230
|
+
if (typeof parse !== "function") {
|
|
231
|
+
throw new Error("[EFC] Route schema entries must be Standard Schema validators (e.g. zod)");
|
|
232
|
+
}
|
|
233
|
+
const r = await parse.call(validator, input);
|
|
234
|
+
return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: "Invalid" }] };
|
|
235
|
+
}
|
|
236
|
+
function validateRequest(schema) {
|
|
237
|
+
return (req, res, next) => {
|
|
238
|
+
void (async () => {
|
|
239
|
+
const issues = [];
|
|
240
|
+
const parsed = {};
|
|
241
|
+
for (const location of LOCATIONS) {
|
|
242
|
+
const validator = schema[location];
|
|
243
|
+
if (!validator) continue;
|
|
244
|
+
const result = await run(validator, req[location]);
|
|
245
|
+
if (result.issues) {
|
|
246
|
+
for (const issue of result.issues) {
|
|
247
|
+
issues.push({ location, path: pathToString(issue.path), message: issue.message });
|
|
248
|
+
}
|
|
249
|
+
} else {
|
|
250
|
+
parsed[location] = result.value;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (issues.length > 0) {
|
|
254
|
+
res.status(400).json({ error: "Validation failed", statusCode: 400, issues });
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
for (const location of LOCATIONS) {
|
|
258
|
+
if (location in parsed) {
|
|
259
|
+
Object.defineProperty(req, location, {
|
|
260
|
+
value: parsed[location],
|
|
261
|
+
writable: true,
|
|
262
|
+
configurable: true,
|
|
263
|
+
enumerable: true
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
next();
|
|
268
|
+
})().catch(next);
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// src/router/mount.ts
|
|
273
|
+
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
274
|
+
function asyncWrap(handler) {
|
|
275
|
+
return (req, res, next) => {
|
|
276
|
+
Promise.resolve(handler(req, res, next)).catch(next);
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
function namedParams(route) {
|
|
280
|
+
const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
|
|
281
|
+
return (req, _res, next) => {
|
|
282
|
+
const captures = route.pattern.exec(req.path);
|
|
283
|
+
const named = {};
|
|
284
|
+
route.params.forEach((name, i) => {
|
|
285
|
+
const value = captures?.[i + 1];
|
|
286
|
+
if (value === void 0 || value === "") {
|
|
287
|
+
named[name] = catchAlls.has(name) ? [] : void 0;
|
|
288
|
+
} else if (catchAlls.has(name)) {
|
|
289
|
+
named[name] = value.split("/").filter(Boolean).map(decodeURIComponent);
|
|
290
|
+
} else {
|
|
291
|
+
named[name] = decodeURIComponent(value);
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
req.params = named;
|
|
295
|
+
next();
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
async function mountRoutes(app, routes) {
|
|
299
|
+
const mounted = [];
|
|
300
|
+
for (const route of routes) {
|
|
301
|
+
const mod = await import(route.filePath);
|
|
302
|
+
const routeMiddlewares = Array.isArray(mod["middlewares"]) ? mod["middlewares"] : [];
|
|
303
|
+
const raw = mod["meta"];
|
|
304
|
+
const meta = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
|
|
305
|
+
const schema = mod["schema"] != null && typeof mod["schema"] === "object" ? mod["schema"] : void 0;
|
|
306
|
+
const routePath = route.pattern ?? route.urlPath;
|
|
307
|
+
const paramMapper = route.pattern ? [namedParams(route)] : [];
|
|
308
|
+
const websocket = typeof mod["WS"] === "function";
|
|
309
|
+
if (mod["WS"] !== void 0 && !websocket)
|
|
310
|
+
throw new Error(`[EFC] WS must be a function: ${route.filePath}`);
|
|
311
|
+
if (websocket) {
|
|
312
|
+
const validation = schemaFor(schema, "WS");
|
|
313
|
+
app.all(
|
|
314
|
+
routePath,
|
|
315
|
+
websocketOnly,
|
|
316
|
+
...paramMapper,
|
|
317
|
+
...routeMiddlewares,
|
|
318
|
+
...validation ? [validateRequest(validation)] : [],
|
|
319
|
+
websocketHandler(mod["WS"])
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
const httpOnly = (req, _res, next) => isUpgrade(req) ? next("route") : next();
|
|
323
|
+
const implemented = [];
|
|
324
|
+
const unimplemented = [];
|
|
325
|
+
for (const method of HTTP_METHODS) {
|
|
326
|
+
if (typeof mod[method] === "function") {
|
|
327
|
+
implemented.push(method);
|
|
328
|
+
const methodSchema = schemaFor(schema, method);
|
|
329
|
+
const validation = methodSchema ? [validateRequest(methodSchema)] : [];
|
|
330
|
+
app[method.toLowerCase()](
|
|
331
|
+
routePath,
|
|
332
|
+
httpOnly,
|
|
333
|
+
...paramMapper,
|
|
334
|
+
...routeMiddlewares,
|
|
335
|
+
...validation,
|
|
336
|
+
asyncWrap(mod[method])
|
|
337
|
+
);
|
|
338
|
+
} else {
|
|
339
|
+
unimplemented.push(method);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (implemented.length > 0 && unimplemented.length > 0) {
|
|
343
|
+
const allowHeader = implemented.join(", ");
|
|
344
|
+
app.all(routePath, (req, res, next) => {
|
|
345
|
+
if (isUpgrade(req)) return next();
|
|
346
|
+
if (unimplemented.includes(req.method)) {
|
|
347
|
+
res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
|
|
348
|
+
} else {
|
|
349
|
+
next();
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
mounted.push({
|
|
354
|
+
...route,
|
|
355
|
+
methods: implemented,
|
|
356
|
+
...meta !== void 0 && { meta },
|
|
357
|
+
...schema && { schema },
|
|
358
|
+
...websocket && { websocket }
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
return mounted;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/openapi.ts
|
|
365
|
+
import { Router } from "express";
|
|
366
|
+
import fs from "fs";
|
|
367
|
+
import path from "path";
|
|
368
|
+
var pointer = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
369
|
+
var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
370
|
+
function variants(url) {
|
|
371
|
+
let paths = [""];
|
|
372
|
+
for (const segment of url.split("/").filter(Boolean)) {
|
|
373
|
+
const optional = /^:([\w$]+)(\*)?\?$/.test(segment);
|
|
374
|
+
const formatted = segment.replace(/:([\w$]+)\*?\??/g, "{$1}");
|
|
375
|
+
paths = paths.flatMap(
|
|
376
|
+
(path2) => optional ? [path2 + "/" + formatted, path2] : [path2 + "/" + formatted]
|
|
377
|
+
);
|
|
378
|
+
if (paths.length > 256) throw new Error("[EFC] OpenAPI: too many optional path variants");
|
|
379
|
+
}
|
|
380
|
+
const shapes = /* @__PURE__ */ new Set();
|
|
381
|
+
return paths.map((path2) => path2 || "/").filter((path2) => {
|
|
382
|
+
const shape = path2.replace(/\{[^}]+\}/g, "{}");
|
|
383
|
+
if (shapes.has(shape)) return false;
|
|
384
|
+
shapes.add(shape);
|
|
385
|
+
return true;
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
function rebase(value, root, resource = false) {
|
|
389
|
+
if (Array.isArray(value)) return value.map((child) => rebase(child, root, resource));
|
|
390
|
+
const object = record(value);
|
|
391
|
+
if (!object) return value;
|
|
392
|
+
resource = resource || typeof object.$id === "string";
|
|
393
|
+
const maps = /* @__PURE__ */ new Set([
|
|
394
|
+
"properties",
|
|
395
|
+
"patternProperties",
|
|
396
|
+
"$defs",
|
|
397
|
+
"definitions",
|
|
398
|
+
"dependentSchemas"
|
|
399
|
+
]);
|
|
400
|
+
const children = /* @__PURE__ */ new Set([
|
|
401
|
+
"items",
|
|
402
|
+
"additionalProperties",
|
|
403
|
+
"contains",
|
|
404
|
+
"propertyNames",
|
|
405
|
+
"not",
|
|
406
|
+
"if",
|
|
407
|
+
"then",
|
|
408
|
+
"else",
|
|
409
|
+
"unevaluatedProperties",
|
|
410
|
+
"unevaluatedItems",
|
|
411
|
+
"contentSchema",
|
|
412
|
+
"allOf",
|
|
413
|
+
"anyOf",
|
|
414
|
+
"oneOf",
|
|
415
|
+
"prefixItems"
|
|
416
|
+
]);
|
|
417
|
+
return Object.fromEntries(
|
|
418
|
+
Object.entries(object).map(([key, child]) => {
|
|
419
|
+
if (!resource && (key === "$ref" || key === "$dynamicRef") && typeof child === "string" && (child === "#" || child.startsWith("#/")))
|
|
420
|
+
return [key, root + child.slice(1)];
|
|
421
|
+
if (maps.has(key) && record(child))
|
|
422
|
+
return [
|
|
423
|
+
key,
|
|
424
|
+
Object.fromEntries(
|
|
425
|
+
Object.entries(child).map(([name, schema]) => [
|
|
426
|
+
name,
|
|
427
|
+
rebase(schema, root, resource)
|
|
428
|
+
])
|
|
429
|
+
)
|
|
430
|
+
];
|
|
431
|
+
return [key, children.has(key) ? rebase(child, root, resource) : child];
|
|
432
|
+
})
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
function parameterObject(schema, rootRef) {
|
|
436
|
+
const empty = () => ({ properties: /* @__PURE__ */ new Map(), required: /* @__PURE__ */ new Set() });
|
|
437
|
+
if (schema === void 0) return empty();
|
|
438
|
+
const target = (ref) => {
|
|
439
|
+
if (!ref.startsWith("#/")) throw new Error("parameter schemas need local JSON pointers");
|
|
440
|
+
let value = schema;
|
|
441
|
+
for (const part of ref.slice(2).split("/")) {
|
|
442
|
+
const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
443
|
+
const object = record(value);
|
|
444
|
+
value = Array.isArray(value) ? value[Number(key)] : object && Object.hasOwn(object, key) ? object[key] : void 0;
|
|
445
|
+
}
|
|
446
|
+
return value;
|
|
447
|
+
};
|
|
448
|
+
const hasType = (value, type, seen = /* @__PURE__ */ new Set()) => {
|
|
449
|
+
const object = record(value);
|
|
450
|
+
if (!object) return false;
|
|
451
|
+
if (object.type === type || type === "object" && object.properties) return true;
|
|
452
|
+
if (typeof object.$ref === "string" && object.$ref.startsWith("#/") && !seen.has(object.$ref)) {
|
|
453
|
+
return hasType(target(object.$ref), type, /* @__PURE__ */ new Set([...seen, object.$ref]));
|
|
454
|
+
}
|
|
455
|
+
return ["allOf", "anyOf", "oneOf"].some(
|
|
456
|
+
(key) => Array.isArray(object[key]) && object[key].some((child) => hasType(child, type, seen))
|
|
457
|
+
);
|
|
458
|
+
};
|
|
459
|
+
const merge = (shapes, mode) => {
|
|
460
|
+
const result = empty();
|
|
461
|
+
const names = new Set(shapes.flatMap((shape) => [...shape.properties.keys()]));
|
|
462
|
+
for (const name of names) {
|
|
463
|
+
const fields = shapes.flatMap((shape) => {
|
|
464
|
+
const field = shape.properties.get(name);
|
|
465
|
+
return field ? [field] : [];
|
|
466
|
+
});
|
|
467
|
+
result.properties.set(name, {
|
|
468
|
+
schema: fields.length === 1 ? fields[0].schema : { [mode]: fields.map((field) => field.schema) },
|
|
469
|
+
object: fields.some((field) => field.object),
|
|
470
|
+
array: fields.some((field) => field.array)
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
const required = new Set(shapes.flatMap((shape) => [...shape.required]));
|
|
474
|
+
for (const name of required) {
|
|
475
|
+
if (mode === "allOf" || shapes.every((shape) => shape.required.has(name)))
|
|
476
|
+
result.required.add(name);
|
|
477
|
+
}
|
|
478
|
+
return result;
|
|
479
|
+
};
|
|
480
|
+
const visit = (value, fragment, seen) => {
|
|
481
|
+
const object = record(value);
|
|
482
|
+
if (!object) throw new Error("query/params schemas must describe objects");
|
|
483
|
+
const shapes = [];
|
|
484
|
+
const properties = record(object.properties);
|
|
485
|
+
if (properties || object.type === "object" || Array.isArray(object.required)) {
|
|
486
|
+
const direct = empty();
|
|
487
|
+
for (const [name, child] of Object.entries(properties ?? {})) {
|
|
488
|
+
direct.properties.set(name, {
|
|
489
|
+
schema: { $ref: rootRef + fragment + "/properties/" + pointer(name) },
|
|
490
|
+
object: hasType(child, "object"),
|
|
491
|
+
array: hasType(child, "array")
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
if (Array.isArray(object.required)) {
|
|
495
|
+
for (const name of object.required) if (typeof name === "string") direct.required.add(name);
|
|
496
|
+
}
|
|
497
|
+
shapes.push(direct);
|
|
498
|
+
}
|
|
499
|
+
if (typeof object.$ref === "string") {
|
|
500
|
+
if (seen.has(object.$ref)) throw new Error("cyclic parameter object reference");
|
|
501
|
+
shapes.push(
|
|
502
|
+
visit(target(object.$ref), object.$ref.slice(1), /* @__PURE__ */ new Set([...seen, object.$ref]))
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
for (const key of ["allOf", "anyOf", "oneOf"]) {
|
|
506
|
+
const branches = object[key];
|
|
507
|
+
if (!Array.isArray(branches) || !branches.length) continue;
|
|
508
|
+
shapes.push(
|
|
509
|
+
merge(
|
|
510
|
+
branches.map((branch, index) => visit(branch, fragment + "/" + key + "/" + index, seen)),
|
|
511
|
+
key === "allOf" ? "allOf" : "anyOf"
|
|
512
|
+
)
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
if (!shapes.length)
|
|
516
|
+
throw new Error(
|
|
517
|
+
"query/params schemas must describe objects; use explicit openapi.parameters for other shapes"
|
|
518
|
+
);
|
|
519
|
+
return merge(shapes, "allOf");
|
|
520
|
+
};
|
|
521
|
+
return visit(schema, "", /* @__PURE__ */ new Set());
|
|
522
|
+
}
|
|
523
|
+
function acceptsEmptyObject(schema, root = schema, seen = /* @__PURE__ */ new Set()) {
|
|
524
|
+
if (typeof schema === "boolean") return schema;
|
|
525
|
+
if (schema !== root && typeof schema.$id === "string") {
|
|
526
|
+
root = schema;
|
|
527
|
+
seen = /* @__PURE__ */ new Set();
|
|
528
|
+
}
|
|
529
|
+
const results = [];
|
|
530
|
+
if (typeof schema.$dynamicRef === "string") results.push(void 0);
|
|
531
|
+
if (schema.type !== void 0) {
|
|
532
|
+
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
533
|
+
results.push(types.includes("object"));
|
|
534
|
+
}
|
|
535
|
+
const isEmpty = (value) => !!record(value) && Object.keys(value).length === 0;
|
|
536
|
+
if ("const" in schema) results.push(isEmpty(schema.const));
|
|
537
|
+
if (Array.isArray(schema.enum)) results.push(schema.enum.some(isEmpty));
|
|
538
|
+
if (Array.isArray(schema.required)) results.push(schema.required.length === 0);
|
|
539
|
+
if (typeof schema.minProperties === "number") results.push(schema.minProperties <= 0);
|
|
540
|
+
if (typeof schema.$ref === "string") {
|
|
541
|
+
const ref = schema.$ref;
|
|
542
|
+
if (!ref.startsWith("#/") && ref !== "#" || seen.has(ref)) results.push(void 0);
|
|
543
|
+
else {
|
|
544
|
+
let target = root;
|
|
545
|
+
for (const part of ref === "#" ? [] : ref.slice(2).split("/")) {
|
|
546
|
+
const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
547
|
+
target = Array.isArray(target) ? target[Number(key)] : record(target)?.[key];
|
|
548
|
+
}
|
|
549
|
+
results.push(
|
|
550
|
+
typeof target === "boolean" || record(target) ? acceptsEmptyObject(target, root, /* @__PURE__ */ new Set([...seen, ref])) : void 0
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
for (const key of ["allOf", "anyOf", "oneOf"]) {
|
|
555
|
+
if (!Array.isArray(schema[key])) continue;
|
|
556
|
+
const values = schema[key].map((child) => acceptsEmptyObject(child, root, seen));
|
|
557
|
+
if (key === "allOf")
|
|
558
|
+
results.push(values.includes(false) ? false : values.includes(void 0) ? void 0 : true);
|
|
559
|
+
if (key === "anyOf")
|
|
560
|
+
results.push(values.includes(true) ? true : values.includes(void 0) ? void 0 : false);
|
|
561
|
+
if (key === "oneOf")
|
|
562
|
+
results.push(
|
|
563
|
+
values.filter((value) => value === true).length > 1 ? false : values.includes(void 0) ? void 0 : values.filter((value) => value === true).length === 1
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
if (typeof schema.not === "boolean" || record(schema.not)) {
|
|
567
|
+
const value = acceptsEmptyObject(schema.not, root, seen);
|
|
568
|
+
results.push(value === void 0 ? void 0 : !value);
|
|
569
|
+
}
|
|
570
|
+
if (typeof schema.if === "boolean" || record(schema.if)) {
|
|
571
|
+
const condition = acceptsEmptyObject(schema.if, root, seen);
|
|
572
|
+
const branch = (key) => typeof schema[key] === "boolean" || record(schema[key]) ? acceptsEmptyObject(schema[key], root, seen) : true;
|
|
573
|
+
results.push(
|
|
574
|
+
condition === void 0 ? branch("then") === branch("else") ? branch("then") : void 0 : branch(condition ? "then" : "else")
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
return results.includes(false) ? false : results.includes(void 0) ? void 0 : true;
|
|
578
|
+
}
|
|
579
|
+
async function generateOpenAPI(input, options = {}) {
|
|
580
|
+
let routes;
|
|
581
|
+
if (typeof input === "string") {
|
|
582
|
+
if (!input.trim() || !fs.existsSync(input) || !fs.statSync(input).isDirectory())
|
|
583
|
+
throw new Error("[EFC] OpenAPI apiDir must be an existing directory");
|
|
584
|
+
routes = [];
|
|
585
|
+
for (const route of scanDir(path.resolve(input))) {
|
|
586
|
+
const mod = await import(route.filePath);
|
|
587
|
+
routes.push({
|
|
588
|
+
...route,
|
|
589
|
+
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].filter(
|
|
590
|
+
(method) => typeof mod[method] === "function"
|
|
591
|
+
),
|
|
592
|
+
...record(mod.meta) && { meta: mod.meta },
|
|
593
|
+
...record(mod.schema) && { schema: mod.schema }
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
} else routes = input;
|
|
597
|
+
const schemas = {
|
|
598
|
+
...record(options.components?.schemas)
|
|
599
|
+
};
|
|
600
|
+
const doc = {
|
|
601
|
+
openapi: "3.1.0",
|
|
602
|
+
info: options.info ?? { title: "EFC API", version: "1.0.0" },
|
|
603
|
+
paths: {},
|
|
604
|
+
components: { ...options.components, schemas },
|
|
605
|
+
...options.servers && { servers: options.servers }
|
|
606
|
+
};
|
|
607
|
+
const prefix = (options.basePath ?? "/v1/api").replace(/\/+$/, "");
|
|
608
|
+
const ids = /* @__PURE__ */ new Set();
|
|
609
|
+
const pathShapes = /* @__PURE__ */ new Map();
|
|
610
|
+
let sequence = 0;
|
|
611
|
+
const convert = async (validator, label) => {
|
|
612
|
+
const standard = validator["~standard"];
|
|
613
|
+
let converted;
|
|
614
|
+
try {
|
|
615
|
+
if (standard?.jsonSchema?.input)
|
|
616
|
+
converted = await standard.jsonSchema.input({ target: "draft-2020-12" });
|
|
617
|
+
else if (options.schemaToJSONSchema) converted = await options.schemaToJSONSchema(validator);
|
|
618
|
+
else throw new Error("validator needs Standard JSON Schema support or schemaToJSONSchema");
|
|
619
|
+
} catch (error) {
|
|
620
|
+
throw new Error(`[EFC] OpenAPI ${label}: ${error.message}`, { cause: error });
|
|
621
|
+
}
|
|
622
|
+
if (typeof converted !== "boolean" && !record(converted))
|
|
623
|
+
throw new Error(`[EFC] OpenAPI ${label}: invalid JSON Schema`);
|
|
624
|
+
let name;
|
|
625
|
+
do {
|
|
626
|
+
name = "EfcRequest" + ++sequence;
|
|
627
|
+
} while (Object.hasOwn(schemas, name));
|
|
628
|
+
const ref = "#/components/schemas/" + pointer(name);
|
|
629
|
+
schemas[name] = rebase(converted, ref);
|
|
630
|
+
return { ref, schema: converted };
|
|
631
|
+
};
|
|
632
|
+
for (const route of routes) {
|
|
633
|
+
const paths = variants(prefix + (route.urlPath === "/" ? "" : route.urlPath));
|
|
634
|
+
for (const method of route.methods) {
|
|
635
|
+
const meta = route.meta?.[method];
|
|
636
|
+
const explicit = meta?.openapi ?? {};
|
|
637
|
+
if (explicit.hidden) continue;
|
|
638
|
+
const request = schemaFor(route.schema, method);
|
|
639
|
+
const roots = {};
|
|
640
|
+
for (const location of ["params", "query", "body"]) {
|
|
641
|
+
if (request?.[location])
|
|
642
|
+
roots[location] = await convert(
|
|
643
|
+
request[location],
|
|
644
|
+
`${method} ${route.urlPath} ${location}`
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
for (const [index, path2] of paths.entries()) {
|
|
648
|
+
const shape = path2.replace(/\{[^}]+\}/g, "{}");
|
|
649
|
+
const previous = pathShapes.get(shape);
|
|
650
|
+
if (previous && previous !== path2)
|
|
651
|
+
throw new Error(`[EFC] OpenAPI: ambiguous paths ${previous} and ${path2}`);
|
|
652
|
+
pathShapes.set(shape, path2);
|
|
653
|
+
const item = doc.paths[path2] ??= {};
|
|
654
|
+
if (Object.hasOwn(item, method.toLowerCase())) continue;
|
|
655
|
+
const pathNames = [...path2.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
656
|
+
const parameters = [];
|
|
657
|
+
for (const location of ["params", "query"]) {
|
|
658
|
+
if (explicit.parameters !== void 0) break;
|
|
659
|
+
const root = roots[location];
|
|
660
|
+
let fields;
|
|
661
|
+
try {
|
|
662
|
+
fields = parameterObject(root?.schema, root?.ref ?? "");
|
|
663
|
+
} catch (error) {
|
|
664
|
+
throw new Error(
|
|
665
|
+
`[EFC] OpenAPI ${method} ${route.urlPath} ${location}: ${error.message}`,
|
|
666
|
+
{ cause: error }
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
const { properties, required } = fields;
|
|
670
|
+
const names = location === "params" ? pathNames : [.../* @__PURE__ */ new Set([...properties.keys(), ...Object.keys(meta?.request?.query ?? {})])];
|
|
671
|
+
for (const name of names) {
|
|
672
|
+
const field = properties.get(name);
|
|
673
|
+
parameters.push({
|
|
674
|
+
// Brackets keep one-element arrays as arrays in Express's query parser.
|
|
675
|
+
name: location === "query" && field?.array ? name + "[]" : name,
|
|
676
|
+
in: location === "params" ? "path" : "query",
|
|
677
|
+
required: location === "params" || required.has(name),
|
|
678
|
+
schema: field?.schema ?? { type: "string" },
|
|
679
|
+
...location === "query" && field?.object && { style: "deepObject", explode: true },
|
|
680
|
+
...location === "query" && field?.array && { style: "form", explode: true },
|
|
681
|
+
...meta?.request?.[location]?.[name] !== void 0 && {
|
|
682
|
+
example: meta.request[location][name]
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
for (const [name, example] of Object.entries(meta?.request?.headers ?? {})) {
|
|
688
|
+
parameters.push({ name, in: "header", schema: { type: "string" }, example });
|
|
689
|
+
}
|
|
690
|
+
const requestedId = typeof explicit.operationId === "string" ? explicit.operationId : meta?.operationId;
|
|
691
|
+
const baseId = (requestedId ?? `${method.toLowerCase()}_${path2.replace(/[^a-zA-Z0-9_]/g, "_")}`) + (requestedId && paths.length > 1 ? "_" + index : "");
|
|
692
|
+
let id = baseId;
|
|
693
|
+
if (requestedId && ids.has(id))
|
|
694
|
+
throw new Error(`[EFC] OpenAPI: duplicate operationId ${id}`);
|
|
695
|
+
let suffix = 2;
|
|
696
|
+
while (ids.has(id)) id = baseId + "_" + suffix++;
|
|
697
|
+
ids.add(id);
|
|
698
|
+
const status = String(meta?.response?.status ?? 200);
|
|
699
|
+
const response = {
|
|
700
|
+
description: "Response",
|
|
701
|
+
...meta?.response?.body !== void 0 && {
|
|
702
|
+
content: { "application/json": { example: meta.response.body } }
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
const overrides = { ...explicit };
|
|
706
|
+
delete overrides.hidden;
|
|
707
|
+
delete overrides.operationId;
|
|
708
|
+
item[method.toLowerCase()] = {
|
|
709
|
+
operationId: id,
|
|
710
|
+
...meta?.description && { description: meta.description },
|
|
711
|
+
...meta?.summary && { summary: meta.summary },
|
|
712
|
+
...meta?.tags && { tags: meta.tags },
|
|
713
|
+
...parameters.length && { parameters },
|
|
714
|
+
...roots.query && { "x-efc-query-schema": { $ref: roots.query.ref } },
|
|
715
|
+
...(roots.body || meta?.request?.body !== void 0) && {
|
|
716
|
+
requestBody: {
|
|
717
|
+
required: roots.body ? acceptsEmptyObject(roots.body.schema) !== true : false,
|
|
718
|
+
content: {
|
|
719
|
+
"application/json": {
|
|
720
|
+
...roots.body && { schema: { $ref: roots.body.ref } },
|
|
721
|
+
...meta?.request?.body !== void 0 && { example: meta.request.body }
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
},
|
|
726
|
+
responses: {
|
|
727
|
+
[status]: response,
|
|
728
|
+
...request && status !== "400" && { "400": { description: "Request validation failed" } }
|
|
729
|
+
},
|
|
730
|
+
...route.urlPath.includes("*") && { "x-efc-catch-all": true },
|
|
731
|
+
...overrides
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
return doc;
|
|
737
|
+
}
|
|
738
|
+
async function mountOpenAPI(app, routes, options) {
|
|
739
|
+
const path2 = options.path ?? "/openapi.json";
|
|
740
|
+
if (!path2.startsWith("/") || /[?*:[\](){}#]/.test(path2))
|
|
741
|
+
throw new Error("[EFC] openapi.path must be an absolute static URL path");
|
|
742
|
+
const conflict = await new Promise((resolve, reject) => {
|
|
743
|
+
const probe = Router();
|
|
744
|
+
const api = Router();
|
|
745
|
+
for (const route of routes) {
|
|
746
|
+
if (route.methods.some((method) => method === "GET" || method === "HEAD"))
|
|
747
|
+
api.get(route.pattern ?? route.urlPath, (_req, _res) => resolve(true));
|
|
748
|
+
}
|
|
749
|
+
probe.use(options.basePath ?? "/v1/api", api);
|
|
750
|
+
probe({ method: "GET", url: path2 }, {}, (error) => {
|
|
751
|
+
if (error) reject(error);
|
|
752
|
+
else resolve(false);
|
|
753
|
+
});
|
|
754
|
+
});
|
|
755
|
+
if (conflict) throw new Error(`[EFC] OpenAPI URL conflicts with a GET/HEAD route: ${path2}`);
|
|
756
|
+
const document = await generateOpenAPI(routes, options);
|
|
757
|
+
app.get(path2, (req, res, next) => {
|
|
758
|
+
if (req.headers.upgrade) return next();
|
|
759
|
+
res.json(document);
|
|
760
|
+
});
|
|
761
|
+
return document;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/http-app.ts
|
|
765
|
+
import express from "express";
|
|
766
|
+
import cors from "cors";
|
|
767
|
+
import cookieParser from "cookie-parser";
|
|
768
|
+
function createHttpApp(config) {
|
|
769
|
+
const globalMiddlewares = config.globalMiddlewares ?? [];
|
|
770
|
+
const app = express();
|
|
771
|
+
if (config.trustProxy !== void 0) app.set("trust proxy", config.trustProxy);
|
|
772
|
+
app.set(
|
|
773
|
+
"json replacer",
|
|
774
|
+
(_key, value) => typeof value === "bigint" ? value.toString() : value
|
|
775
|
+
);
|
|
776
|
+
app.use((_req, _res, next) => {
|
|
777
|
+
runWithContext({}, next);
|
|
778
|
+
});
|
|
779
|
+
app.use(requestLogger());
|
|
780
|
+
if (config.requestTimeout) {
|
|
781
|
+
const ms = config.requestTimeout;
|
|
782
|
+
app.use((_req, res, next) => {
|
|
783
|
+
const timer = setTimeout(() => {
|
|
784
|
+
if (!res.headersSent) res.status(408).json({ error: "Request Timeout", statusCode: 408 });
|
|
785
|
+
}, ms);
|
|
786
|
+
const clear = () => clearTimeout(timer);
|
|
787
|
+
res.once("finish", clear);
|
|
788
|
+
res.once("close", clear);
|
|
789
|
+
next();
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
const corsOption = config.cors ?? true;
|
|
793
|
+
if (corsOption !== false) {
|
|
794
|
+
const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
|
|
795
|
+
const corsOpts = typeof corsOption === "object" ? { ...corsOption, origin } : { origin };
|
|
796
|
+
app.use(cors(corsOpts));
|
|
797
|
+
}
|
|
798
|
+
app.use(express.json());
|
|
799
|
+
app.use(express.urlencoded({ extended: true }));
|
|
800
|
+
app.use(cookieParser());
|
|
801
|
+
for (const mw of globalMiddlewares) {
|
|
802
|
+
app.use(mw);
|
|
803
|
+
}
|
|
804
|
+
return app;
|
|
805
|
+
}
|
|
806
|
+
function mountErrorHandler(app, onError) {
|
|
807
|
+
if (onError) {
|
|
808
|
+
app.use(onError);
|
|
809
|
+
} else {
|
|
810
|
+
app.use(
|
|
811
|
+
(err, _req, res, _next) => {
|
|
812
|
+
if (res.headersSent) {
|
|
813
|
+
getLogger().warn({ err }, "Error after the response was sent");
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const status = err?.statusCode;
|
|
817
|
+
const duckTyped = err instanceof Error && typeof status === "number" && status >= 400 && status < 500 ? err : null;
|
|
818
|
+
if (isHttpError(err)) {
|
|
819
|
+
const issues = err.issues;
|
|
820
|
+
res.status(err.statusCode).json({
|
|
821
|
+
error: err.message,
|
|
822
|
+
statusCode: err.statusCode,
|
|
823
|
+
...issues !== void 0 && { issues }
|
|
824
|
+
});
|
|
825
|
+
} else if (duckTyped) {
|
|
826
|
+
res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
|
|
827
|
+
} else {
|
|
828
|
+
getLogger().error({ err }, "Unhandled error");
|
|
829
|
+
res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
export {
|
|
837
|
+
attachWebSockets,
|
|
838
|
+
closeWebSockets,
|
|
839
|
+
mountRoutes,
|
|
840
|
+
generateOpenAPI,
|
|
841
|
+
mountOpenAPI,
|
|
842
|
+
createHttpApp,
|
|
843
|
+
mountErrorHandler
|
|
844
|
+
};
|
|
845
|
+
//# sourceMappingURL=chunk-LECHRAU3.js.map
|